realtime-voice-agents 2.4.0 → 2.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 (46) hide show
  1. package/README.md +30 -11
  2. package/dist/{BaseRealtimeProvider-CWJ81HIt.d.mts → BaseRealtimeProvider-BJQO-hpu.d.mts} +44 -1
  3. package/dist/{BaseRealtimeProvider-BL75_HHh.d.cts → BaseRealtimeProvider-CO9N8jt-.d.cts} +44 -1
  4. package/dist/{BaseRealtimeProvider-C9C3s8jx.mjs → BaseRealtimeProvider-Cj6JWR2k.mjs} +1 -1
  5. package/dist/{BaseRealtimeProvider-C2mRn1V_.cjs → BaseRealtimeProvider-ZfFzijdr.cjs} +1 -1
  6. package/dist/{GeminiLiveProvider-Cc1dkxW6.d.cts → GeminiLiveProvider-C_LQCTX5.d.mts} +1 -1
  7. package/dist/{GeminiLiveProvider-TvY_cQQZ.d.mts → GeminiLiveProvider-DM-GwD0w.d.cts} +1 -1
  8. package/dist/{InMemorySessionStore-CRBmmCA6.d.cts → InMemorySessionStore-BlsyPnIp.d.cts} +2 -0
  9. package/dist/{InMemorySessionStore-CRBmmCA6.d.mts → InMemorySessionStore-BlsyPnIp.d.mts} +2 -0
  10. package/dist/{OpenAICompatibleProvider-D-2OOVBU.mjs → OpenAICompatibleProvider-Dqje-boq.mjs} +3 -3
  11. package/dist/{OpenAICompatibleProvider-Mp0Mefbh.cjs → OpenAICompatibleProvider-j2Nza2q2.cjs} +8 -2
  12. package/dist/{events-BylBSBW-.mjs → events-D-pvCH_F.mjs} +2 -1
  13. package/dist/{events-BxDTIKKq.cjs → events-DWX9535M.cjs} +2 -1
  14. package/dist/gemini.cjs +1 -1
  15. package/dist/gemini.d.cts +2 -2
  16. package/dist/gemini.d.mts +2 -2
  17. package/dist/gemini.mjs +1 -1
  18. package/dist/gpt-live.cjs +954 -0
  19. package/dist/gpt-live.d.cts +261 -0
  20. package/dist/gpt-live.d.mts +261 -0
  21. package/dist/gpt-live.mjs +936 -0
  22. package/dist/index.cjs +116 -19
  23. package/dist/index.d.cts +7 -3
  24. package/dist/index.d.mts +7 -3
  25. package/dist/index.mjs +116 -19
  26. package/dist/openai.cjs +2 -2
  27. package/dist/openai.d.cts +1 -1
  28. package/dist/openai.d.mts +1 -1
  29. package/dist/openai.mjs +2 -2
  30. package/dist/{rest-BYqiVOhe.mjs → rest-D-DWWVIj.mjs} +1 -1
  31. package/dist/{rest-BvUKut_k.cjs → rest-OR4VhEif.cjs} +1 -1
  32. package/dist/{session-config-CbifLlkV.mjs → session-config-C31WZESg.mjs} +1 -1
  33. package/dist/{session-config-CqJm2Kxz.cjs → session-config-CYjxBqpF.cjs} +1 -1
  34. package/dist/store.d.cts +1 -1
  35. package/dist/store.d.mts +1 -1
  36. package/dist/testing.cjs +376 -0
  37. package/dist/testing.d.cts +119 -2
  38. package/dist/testing.d.mts +119 -2
  39. package/dist/testing.mjs +374 -2
  40. package/dist/twilio.cjs +1 -1
  41. package/dist/twilio.mjs +1 -1
  42. package/dist/xai.cjs +3 -3
  43. package/dist/xai.d.cts +1 -1
  44. package/dist/xai.d.mts +1 -1
  45. package/dist/xai.mjs +3 -3
  46. package/package.json +14 -2
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
3
- const require_events = require("./events-BxDTIKKq.cjs");
4
- const require_BaseRealtimeProvider = require("./BaseRealtimeProvider-C2mRn1V_.cjs");
3
+ const require_events = require("./events-DWX9535M.cjs");
4
+ const require_BaseRealtimeProvider = require("./BaseRealtimeProvider-ZfFzijdr.cjs");
5
5
  const require_InMemorySessionStore = require("./InMemorySessionStore-B0_i-DOU.cjs");
6
- const require_rest = require("./rest-BvUKut_k.cjs");
6
+ const require_rest = require("./rest-OR4VhEif.cjs");
7
7
  const require_mulaw = require("./mulaw-DLUObjdP.cjs");
8
8
  const require_noise = require("./noise-D9jKottW.cjs");
9
- const require_session_config = require("./session-config-CqJm2Kxz.cjs");
9
+ const require_session_config = require("./session-config-CYjxBqpF.cjs");
10
10
  let node_fs = require("node:fs");
11
11
  let zod = require("zod");
12
12
  zod = require_rolldown_runtime.__toESM(zod, 1);
@@ -829,6 +829,43 @@ function formatTranscriptForInjection(entries, options = {}) {
829
829
  }
830
830
  return lines.sort((a, b) => a.atMs - b.atMs).map((line) => line.text).join("\n");
831
831
  }
832
+ /**
833
+ * The same replay as `formatTranscriptForInjection`, as structured turns for
834
+ * providers that seed history at session start (`ProviderSessionInit.history`).
835
+ * Agent lines keep their attribution (`Name: text`) whenever more than one
836
+ * agent exists on the call, and completed transfers become `developer` notes
837
+ * in timeline order — the anti-loop guarantees are identical to the text
838
+ * replay (see the field bug notes there).
839
+ */
840
+ function buildHistoryForSeeding(entries, options = {}) {
841
+ const { maxTurns = 30, agentNames, handoffs = [] } = options;
842
+ const recent = entries.slice(-maxTurns);
843
+ if (recent.length === 0) return [];
844
+ const multiAgent = (agentNames?.size ?? 0) > 1 || handoffs.length > 0;
845
+ const nameOf = (agentId) => (agentId ? agentNames?.get(agentId) : void 0) ?? agentId ?? "Agent";
846
+ const windowStartMs = recent[0].timestampMs;
847
+ const items = recent.map((entry) => ({
848
+ atMs: entry.timestampMs,
849
+ entry: entry.role === "user" ? {
850
+ role: "user",
851
+ text: entry.text
852
+ } : {
853
+ role: "assistant",
854
+ text: multiAgent ? `${nameOf(entry.agentId)}: ${entry.text}` : entry.text
855
+ }
856
+ }));
857
+ for (const handoff of handoffs) {
858
+ if (handoff.atMs < windowStartMs) continue;
859
+ items.push({
860
+ atMs: handoff.atMs,
861
+ entry: {
862
+ role: "developer",
863
+ text: `[transfer] ${nameOf(handoff.from)} -> ${nameOf(handoff.to)}` + (handoff.reason ? ` (reason: ${handoff.reason})` : "")
864
+ }
865
+ });
866
+ }
867
+ return items.sort((a, b) => a.atMs - b.atMs).map((item) => item.entry);
868
+ }
832
869
  //#endregion
833
870
  //#region src/session/usage.ts
834
871
  function emptyUsage() {
@@ -852,6 +889,10 @@ function emptyUsage() {
852
889
  var UsageAccumulator = class {
853
890
  usage = emptyUsage();
854
891
  add(providerUsage) {
892
+ if (providerUsage.audioSeconds !== void 0) {
893
+ this.usage.audioSeconds = Math.max(this.usage.audioSeconds ?? 0, providerUsage.audioSeconds);
894
+ if (providerUsage.totalTokens === 0 && providerUsage.inputTokens === 0 && providerUsage.outputTokens === 0) return this.snapshot();
895
+ }
855
896
  this.usage.inputTokens += providerUsage.inputTokens;
856
897
  this.usage.outputTokens += providerUsage.outputTokens;
857
898
  this.usage.totalTokens += providerUsage.totalTokens;
@@ -1277,6 +1318,7 @@ var CallSession = class extends require_events.TypedEmitter {
1277
1318
  /** Manual barge-in: stop the agent mid-sentence. */
1278
1319
  interrupt() {
1279
1320
  if (!this.generating && !this.tracker.isPlaybackActive()) return;
1321
+ if (this.modelOwnsTurnTaking()) return;
1280
1322
  this.provider?.cancelResponse();
1281
1323
  this.performInterrupt();
1282
1324
  }
@@ -1385,9 +1427,26 @@ var CallSession = class extends require_events.TypedEmitter {
1385
1427
  parameters: decorated.parameters
1386
1428
  };
1387
1429
  }),
1388
- providerOptions: this.activeAgentValue.providerOptions
1430
+ providerOptions: this.activeAgentValue.providerOptions,
1431
+ history: this.buildHistory()
1389
1432
  };
1390
1433
  }
1434
+ /** Whether the connected provider decides turn-taking itself (full-duplex). */
1435
+ modelOwnsTurnTaking() {
1436
+ return this.provider?.capabilities.turnTaking === "model";
1437
+ }
1438
+ /** Attributed replay of the call so far, as turns (see buildHistoryForSeeding). */
1439
+ buildHistory() {
1440
+ if (this.transcriptEntries.length === 0) return void 0;
1441
+ const turns = buildHistoryForSeeding(this.transcriptEntries, {
1442
+ agentNames: new Map([...this.agents].map(([id, agent]) => [id, agent.name])),
1443
+ handoffs: this.handoffHistory
1444
+ });
1445
+ return [{
1446
+ role: "developer",
1447
+ text: `Context: this phone call reconnected mid-conversation. You are ${this.activeAgentValue.name}. The conversation so far follows: assistant lines that name another agent were said by that agent, and \`[transfer]\` notes are routing that ALREADY happened. Anything already answered or already routed must not be routed again. Continue naturally from where it left off; do not greet again.`
1448
+ }, ...turns];
1449
+ }
1391
1450
  wireTransport() {
1392
1451
  const { transport } = this.deps;
1393
1452
  transport.on("media", (event) => this.handleInboundMedia(event.media.payload));
@@ -1399,8 +1458,8 @@ var CallSession = class extends require_events.TypedEmitter {
1399
1458
  this.handleKeypress(digit);
1400
1459
  this.emit("dtmf", { digit });
1401
1460
  });
1402
- transport.on("stop", () => void this.teardown("caller-hangup"));
1403
- transport.on("close", () => void this.teardown("caller-hangup"));
1461
+ transport.on("stop", () => void this.teardown(this.stateValue === "ending" ? this.hangupReason : "caller-hangup"));
1462
+ transport.on("close", () => void this.teardown(this.stateValue === "ending" ? this.hangupReason : "caller-hangup"));
1404
1463
  transport.on("error", (error) => this.emitError(error));
1405
1464
  }
1406
1465
  /** Emit 'error'; when the host attached no listener, log instead of losing it. */
@@ -1424,7 +1483,14 @@ var CallSession = class extends require_events.TypedEmitter {
1424
1483
  this.generating = true;
1425
1484
  this.currentResponseId = responseId;
1426
1485
  this.blockedUserTurn = "idle";
1427
- if (this.pendingHangup) this.pendingHangup.sawResponse = true;
1486
+ if (this.pendingHangup) {
1487
+ this.pendingHangup.sawResponse = true;
1488
+ if (this.pendingHangup.grace) {
1489
+ clearTimeout(this.pendingHangup.grace);
1490
+ this.timers.delete(this.pendingHangup.grace);
1491
+ this.pendingHangup.grace = null;
1492
+ }
1493
+ }
1428
1494
  this.noteHangupProgress();
1429
1495
  this.clearIdleTimer();
1430
1496
  this.interruptions.onResponseStarted(responseId);
@@ -1484,6 +1550,11 @@ var CallSession = class extends require_events.TypedEmitter {
1484
1550
  this.emit("user.speech.ended");
1485
1551
  });
1486
1552
  provider.on("toolCall", (call) => void this.handleToolCall(call));
1553
+ provider.on("usage", (usage) => {
1554
+ if (!provider.capabilities.decoupledBackend) return;
1555
+ const total = this.usageAccumulator.add(usage);
1556
+ this.emit("usage.updated", total, usage);
1557
+ });
1487
1558
  provider.on("error", (error) => this.emitError(error));
1488
1559
  provider.on("close", (info) => {
1489
1560
  if (this.stateValue === "ended" || this.stateValue === "ending") return;
@@ -1499,18 +1570,18 @@ var CallSession = class extends require_events.TypedEmitter {
1499
1570
  this.scheduleReconnect();
1500
1571
  });
1501
1572
  }
1502
- handleInboundMedia(payload) {
1573
+ handleInboundMedia(inbound) {
1574
+ let payload = inbound;
1503
1575
  if (this.stateValue === "ended" || this.stateValue === "ending") return;
1504
1576
  if (this.noiseVad) {
1505
1577
  const excluded = this.isUserSpeechExcluded() || this.tracker.isPlaybackActive() || this.pregreeting !== null && !this.pregreeting.played;
1506
1578
  const proposal = this.noiseVad.onInboundFrame(payload, excluded);
1507
1579
  if (proposal) this.handleVadProposal(proposal);
1508
1580
  }
1509
- if (this.pregreeting && !this.pregreeting.played) return;
1510
- if (this.deps.options.deafness.ignoreUserAudioUntilFirstTurnDone && !this.firstTurnDone) return;
1511
- if (this.deps.options.deafness.muteDuringToolExecution && this.runningTools.size > 0) return;
1512
- if (this.deps.options.deafness.muteWhileAgentSpeaking && this.tracker.isPlaybackActive()) return;
1513
- if (this.interruptions.isSuspended) return;
1581
+ if (this.pregreeting !== null && !this.pregreeting.played || this.deps.options.deafness.ignoreUserAudioUntilFirstTurnDone && !this.firstTurnDone || this.deps.options.deafness.muteDuringToolExecution && this.runningTools.size > 0 || this.deps.options.deafness.muteWhileAgentSpeaking && this.tracker.isPlaybackActive() || this.interruptions.isSuspended) {
1582
+ if (!this.modelOwnsTurnTaking()) return;
1583
+ payload = silenceLike(payload);
1584
+ }
1514
1585
  if (this.provider?.isConnected && !this.reconnecting) this.provider.sendAudio(payload);
1515
1586
  else {
1516
1587
  this.inboundBuffer.push(payload);
@@ -1519,7 +1590,7 @@ var CallSession = class extends require_events.TypedEmitter {
1519
1590
  }
1520
1591
  flushInboundBuffer() {
1521
1592
  if (!this.provider?.isConnected) return;
1522
- for (const payload of this.inboundBuffer) this.provider.sendAudio(payload);
1593
+ if (!this.modelOwnsTurnTaking()) for (const payload of this.inboundBuffer) this.provider.sendAudio(payload);
1523
1594
  this.inboundBuffer = [];
1524
1595
  }
1525
1596
  /** Caller speech is excluded from the noise floor, capped so a missing
@@ -1610,6 +1681,7 @@ var CallSession = class extends require_events.TypedEmitter {
1610
1681
  }
1611
1682
  handleBargeIn() {
1612
1683
  if (!this.generating && !this.tracker.isPlaybackActive()) return;
1684
+ if (this.modelOwnsTurnTaking()) return;
1613
1685
  const decision = this.interruptions.evaluate({ toolRunning: this.runningTools.size > 0 });
1614
1686
  if (!decision.allow) {
1615
1687
  if (decision.cause === "guard" || decision.cause === "disabled") this.blockedUserTurn = "speaking";
@@ -1953,7 +2025,7 @@ var CallSession = class extends require_events.TypedEmitter {
1953
2025
  }
1954
2026
  /** Inject a text turn now, or after the agent finishes speaking. */
1955
2027
  injectOrQueueText(text, triggerResponse) {
1956
- if (this.generating || this.tracker.isPlaybackActive()) {
2028
+ if (!this.provider?.capabilities.decoupledBackend && (this.generating || this.tracker.isPlaybackActive())) {
1957
2029
  this.pendingInjections.push({
1958
2030
  text,
1959
2031
  triggerResponse
@@ -1981,7 +2053,7 @@ var CallSession = class extends require_events.TypedEmitter {
1981
2053
  }
1982
2054
  deliverToolResult(callId, payload, triggerResponse = true) {
1983
2055
  if (this.stateValue === "ended") return;
1984
- if (this.deps.options.toolResultDelivery === "afterPlayback" && (this.generating || this.tracker.isPlaybackActive())) {
2056
+ if (this.deps.options.toolResultDelivery === "afterPlayback" && !this.provider?.capabilities.decoupledBackend && (this.generating || this.tracker.isPlaybackActive())) {
1985
2057
  this.toolQueue.enqueue({
1986
2058
  callId,
1987
2059
  toolName: "",
@@ -2081,6 +2153,21 @@ var CallSession = class extends require_events.TypedEmitter {
2081
2153
  if (!this.pendingHangup) return;
2082
2154
  if (!this.pendingHangup.sawResponse) return;
2083
2155
  if (this.generating || this.tracker.isPlaybackActive()) return;
2156
+ if (this.modelOwnsTurnTaking()) {
2157
+ if (this.pendingHangup.grace) return;
2158
+ const timer = setTimeout(() => {
2159
+ this.timers.delete(timer);
2160
+ const pending = this.pendingHangup;
2161
+ if (!pending) return;
2162
+ pending.grace = null;
2163
+ if (this.generating || this.tracker.isPlaybackActive()) return;
2164
+ this.completeHangup();
2165
+ }, HANGUP_SENTENCE_GRACE_MS);
2166
+ timer.unref?.();
2167
+ this.timers.add(timer);
2168
+ this.pendingHangup.grace = timer;
2169
+ return;
2170
+ }
2084
2171
  this.completeHangup();
2085
2172
  }
2086
2173
  completeHangup() {
@@ -2155,7 +2242,7 @@ var CallSession = class extends require_events.TypedEmitter {
2155
2242
  if (this.stateValue !== "active") return;
2156
2243
  this.reconnectAttempt = 0;
2157
2244
  this.reconnecting = false;
2158
- if (!provider.didResume) this.reinjectHistory(provider);
2245
+ if (!provider.didResume && !provider.capabilities.startupHistory) this.reinjectHistory(provider);
2159
2246
  this.flushInboundBuffer();
2160
2247
  this.emit("provider.reconnected");
2161
2248
  }
@@ -2227,7 +2314,7 @@ var CallSession = class extends require_events.TypedEmitter {
2227
2314
  ...this.buildProviderInit(),
2228
2315
  freshSession: true
2229
2316
  });
2230
- this.reinjectHistory(this.provider);
2317
+ if (!this.provider.capabilities.startupHistory) this.reinjectHistory(this.provider);
2231
2318
  this.provider.createResponse({ instructions: continueInstruction });
2232
2319
  } catch (error) {
2233
2320
  this.handoffInProgress = false;
@@ -2421,11 +2508,21 @@ var CallSession = class extends require_events.TypedEmitter {
2421
2508
  }
2422
2509
  };
2423
2510
  const PREGREETING_MARK = "pre:greeting";
2511
+ /** Longer than the speech gate's quiet window plus the mark round trip (0.8 s + ~0.3 s). */
2512
+ const HANGUP_SENTENCE_GRACE_MS = 1500;
2424
2513
  /** 400ms per frame — matches production burst-write implementations. */
2425
2514
  const PREGREETING_CHUNK_BYTES = 3200;
2426
2515
  function toError(value) {
2427
2516
  return value instanceof Error ? value : new Error(String(value));
2428
2517
  }
2518
+ /** Base64 μ-law digital silence with the same byte length as `payload`. */
2519
+ function silenceLike(payload) {
2520
+ const bytes = require_mulaw.base64ByteLength(payload);
2521
+ if (bytes === SILENCE_FRAME_BYTES) return SILENCE_FRAME_BASE64;
2522
+ return Buffer.alloc(Math.max(0, Math.round(bytes)), 255).toString("base64");
2523
+ }
2524
+ const SILENCE_FRAME_BYTES = 160;
2525
+ const SILENCE_FRAME_BASE64 = Buffer.alloc(SILENCE_FRAME_BYTES, 255).toString("base64");
2429
2526
  function safeJsonStringify(value) {
2430
2527
  try {
2431
2528
  return JSON.stringify(value) ?? "null";
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { n as BackgroundAudioPreset, r as BackgroundAudioSpec, t as BackgroundAudioOptions } from "./presets-Bf75YXs5.cjs";
2
2
  import { t as TypedEmitter } from "./events-BUMYdETO.cjs";
3
- import { _ as Logger, a as ProviderToolSchema, c as SessionUpdateOptions, d as ProviderCloseInfo, f as ProviderEvents, g as VadTuningProfile, h as ProviderCapabilities, i as ProviderSessionInit, l as VadConfig, m as ProviderUsage, n as ProviderFactory, o as SendTextOptions, p as ProviderToolCall, r as ProviderFactoryContext, s as SendToolResultOptions, t as BaseRealtimeProvider, u as ProviderAudioDelta, v as consoleLogger, y as noopLogger } from "./BaseRealtimeProvider-BL75_HHh.cjs";
3
+ import { _ as VadTuningProfile, a as ProviderSessionInit, b as noopLogger, c as SendToolResultOptions, d as ProviderAudioDelta, f as ProviderCloseInfo, g as ProviderCapabilities, h as ProviderUsage, i as ProviderHistoryEntry, l as SessionUpdateOptions, m as ProviderToolCall, n as ProviderFactory, o as ProviderToolSchema, p as ProviderEvents, r as ProviderFactoryContext, s as SendTextOptions, t as BaseRealtimeProvider, u as VadConfig, v as Logger, y as consoleLogger } from "./BaseRealtimeProvider-CO9N8jt-.cjs";
4
4
  import { i as WebSocketLike, m as TwilioStartEvent, r as TwilioMediaTransport } from "./transport-B_PJFIVd.cjs";
5
- import { a as emptyUsage, i as UsageInfo, n as SessionStore, o as HandoffRecord, r as CallSnapshot, s as TranscriptEntry, t as InMemorySessionStore } from "./InMemorySessionStore-CRBmmCA6.cjs";
5
+ import { a as emptyUsage, i as UsageInfo, n as SessionStore, o as HandoffRecord, r as CallSnapshot, s as TranscriptEntry, t as InMemorySessionStore } from "./InMemorySessionStore-BlsyPnIp.cjs";
6
6
  import { i as TwilioRestClient, n as connectStreamTwiml } from "./twiml-z9LjoF4_.cjs";
7
7
  import { IncomingMessage } from "node:http";
8
8
  //#region src/tools/tool.d.ts
@@ -1025,6 +1025,10 @@ declare class CallSession extends TypedEmitter<SessionEventMap> {
1025
1025
  /** Agent instructions plus the kit's own notes that must survive handoffs (keypad). */
1026
1026
  private composeInstructions;
1027
1027
  private buildProviderInit;
1028
+ /** Whether the connected provider decides turn-taking itself (full-duplex). */
1029
+ private modelOwnsTurnTaking;
1030
+ /** Attributed replay of the call so far, as turns (see buildHistoryForSeeding). */
1031
+ private buildHistory;
1028
1032
  private wireTransport;
1029
1033
  /** Emit 'error'; when the host attached no listener, log instead of losing it. */
1030
1034
  private emitError;
@@ -1296,4 +1300,4 @@ declare class PlaybackTracker {
1296
1300
  private maybeForget;
1297
1301
  }
1298
1302
  //#endregion
1299
- export { Agent, type AgentDefinition, type ApprovalRequestInfo, type BackgroundAudioOptions, type BackgroundAudioPreset, type BackgroundAudioSpec, BaseRealtimeProvider, type BridgeConfig, type BridgeEventMap, type BuiltinToolsConfig, type CallEndReason, CallSession, type CallSessionFacade, type CallSnapshot, type CallStartedInfo, type CallState, type CaptureGreetingOptions, type CapturedGreeting, DEFAULT_KEYPAD_CLEAR_MESSAGE, DEFAULT_KEYPAD_INSTRUCTIONS, DEFAULT_KEYPAD_OPTIONS, DEFAULT_RECONNECT_POLICY, DEFAULT_SESSION_OPTIONS, type DeafnessOptions, type FinishCallToolOptions, type GreetingOptions, type HandoffDirective, type HandoffRecord, type HangupOptions, type IdleOptions, InMemorySessionStore, type InferSchema, type InterruptionBlockCause, InterruptionController, type InterruptionDecision, type InterruptionRateLimit, type InterruptionSettings, KeypadCollector, type KeypadCollectorHooks, type KeypadEntry, type KeypadEntryReason, type KeypadHandle, type KeypadKeyKind, type KeypadOptions, type Logger, type MarkEchoResult, NoiseAdaptiveVadController, type NoiseAdaptiveVadOptions, PlaybackTracker, type ProviderAudioDelta, type ProviderCapabilities, type ProviderCloseInfo, type ProviderEvents, type ProviderFactory, type ProviderFactoryContext, type ProviderFallbackInfo, type ProviderSessionInit, type ProviderToolCall, type ProviderToolSchema, type ProviderUsage, type ReconnectPolicy, type SendTextOptions, type SendToolResultOptions, SessionContext, type SessionEventMap, type SessionOptions, type SessionStore, type SessionUpdateOptions, type Tool, type ToolCallInfo, type ToolContext, type ToolDecoration, type ToolDefinition, type ToolMiddleware, type ToolRunInfo, type ToolStrategy, type TranscriptEntry, type TransferCallToolOptions, TwilioRealtimeBridge, type TwilioRestOptions, type TwilioStartEvent, type UsageInfo, type VadAdjustment, type VadConfig, type VadNoiseMetrics, type VadSuggestionInfo, type VadTuningProfile, type WebSocketLike, type ZodSchemaLike, captureGreetingAudio, collectAgentGraph, composeExecution, connectStreamTwiml, consoleLogger, createFinishCallTool, createHandoffTool, createTransferCallTool, decorateTool, defaultKeypadMessage, emptyUsage, handoffToolName, isHandoffDirective, noopLogger, resolveSessionOptions, tool, zodToJsonSchema };
1303
+ export { Agent, type AgentDefinition, type ApprovalRequestInfo, type BackgroundAudioOptions, type BackgroundAudioPreset, type BackgroundAudioSpec, BaseRealtimeProvider, type BridgeConfig, type BridgeEventMap, type BuiltinToolsConfig, type CallEndReason, CallSession, type CallSessionFacade, type CallSnapshot, type CallStartedInfo, type CallState, type CaptureGreetingOptions, type CapturedGreeting, DEFAULT_KEYPAD_CLEAR_MESSAGE, DEFAULT_KEYPAD_INSTRUCTIONS, DEFAULT_KEYPAD_OPTIONS, DEFAULT_RECONNECT_POLICY, DEFAULT_SESSION_OPTIONS, type DeafnessOptions, type FinishCallToolOptions, type GreetingOptions, type HandoffDirective, type HandoffRecord, type HangupOptions, type IdleOptions, InMemorySessionStore, type InferSchema, type InterruptionBlockCause, InterruptionController, type InterruptionDecision, type InterruptionRateLimit, type InterruptionSettings, KeypadCollector, type KeypadCollectorHooks, type KeypadEntry, type KeypadEntryReason, type KeypadHandle, type KeypadKeyKind, type KeypadOptions, type Logger, type MarkEchoResult, NoiseAdaptiveVadController, type NoiseAdaptiveVadOptions, PlaybackTracker, type ProviderAudioDelta, type ProviderCapabilities, type ProviderCloseInfo, type ProviderEvents, type ProviderFactory, type ProviderFactoryContext, type ProviderFallbackInfo, type ProviderHistoryEntry, type ProviderSessionInit, type ProviderToolCall, type ProviderToolSchema, type ProviderUsage, type ReconnectPolicy, type SendTextOptions, type SendToolResultOptions, SessionContext, type SessionEventMap, type SessionOptions, type SessionStore, type SessionUpdateOptions, type Tool, type ToolCallInfo, type ToolContext, type ToolDecoration, type ToolDefinition, type ToolMiddleware, type ToolRunInfo, type ToolStrategy, type TranscriptEntry, type TransferCallToolOptions, TwilioRealtimeBridge, type TwilioRestOptions, type TwilioStartEvent, type UsageInfo, type VadAdjustment, type VadConfig, type VadNoiseMetrics, type VadSuggestionInfo, type VadTuningProfile, type WebSocketLike, type ZodSchemaLike, captureGreetingAudio, collectAgentGraph, composeExecution, connectStreamTwiml, consoleLogger, createFinishCallTool, createHandoffTool, createTransferCallTool, decorateTool, defaultKeypadMessage, emptyUsage, handoffToolName, isHandoffDirective, noopLogger, resolveSessionOptions, tool, zodToJsonSchema };
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { n as BackgroundAudioPreset, r as BackgroundAudioSpec, t as BackgroundAudioOptions } from "./presets-Bf75YXs5.mjs";
2
2
  import { t as TypedEmitter } from "./events-BUMYdETO.mjs";
3
- import { _ as Logger, a as ProviderToolSchema, c as SessionUpdateOptions, d as ProviderCloseInfo, f as ProviderEvents, g as VadTuningProfile, h as ProviderCapabilities, i as ProviderSessionInit, l as VadConfig, m as ProviderUsage, n as ProviderFactory, o as SendTextOptions, p as ProviderToolCall, r as ProviderFactoryContext, s as SendToolResultOptions, t as BaseRealtimeProvider, u as ProviderAudioDelta, v as consoleLogger, y as noopLogger } from "./BaseRealtimeProvider-CWJ81HIt.mjs";
3
+ import { _ as VadTuningProfile, a as ProviderSessionInit, b as noopLogger, c as SendToolResultOptions, d as ProviderAudioDelta, f as ProviderCloseInfo, g as ProviderCapabilities, h as ProviderUsage, i as ProviderHistoryEntry, l as SessionUpdateOptions, m as ProviderToolCall, n as ProviderFactory, o as ProviderToolSchema, p as ProviderEvents, r as ProviderFactoryContext, s as SendTextOptions, t as BaseRealtimeProvider, u as VadConfig, v as Logger, y as consoleLogger } from "./BaseRealtimeProvider-BJQO-hpu.mjs";
4
4
  import { i as WebSocketLike, m as TwilioStartEvent, r as TwilioMediaTransport } from "./transport-CEaLFV4E.mjs";
5
- import { a as emptyUsage, i as UsageInfo, n as SessionStore, o as HandoffRecord, r as CallSnapshot, s as TranscriptEntry, t as InMemorySessionStore } from "./InMemorySessionStore-CRBmmCA6.mjs";
5
+ import { a as emptyUsage, i as UsageInfo, n as SessionStore, o as HandoffRecord, r as CallSnapshot, s as TranscriptEntry, t as InMemorySessionStore } from "./InMemorySessionStore-BlsyPnIp.mjs";
6
6
  import { i as TwilioRestClient, n as connectStreamTwiml } from "./twiml-z9LjoF4_.mjs";
7
7
  import { IncomingMessage } from "node:http";
8
8
  //#region src/tools/tool.d.ts
@@ -1025,6 +1025,10 @@ declare class CallSession extends TypedEmitter<SessionEventMap> {
1025
1025
  /** Agent instructions plus the kit's own notes that must survive handoffs (keypad). */
1026
1026
  private composeInstructions;
1027
1027
  private buildProviderInit;
1028
+ /** Whether the connected provider decides turn-taking itself (full-duplex). */
1029
+ private modelOwnsTurnTaking;
1030
+ /** Attributed replay of the call so far, as turns (see buildHistoryForSeeding). */
1031
+ private buildHistory;
1028
1032
  private wireTransport;
1029
1033
  /** Emit 'error'; when the host attached no listener, log instead of losing it. */
1030
1034
  private emitError;
@@ -1296,4 +1300,4 @@ declare class PlaybackTracker {
1296
1300
  private maybeForget;
1297
1301
  }
1298
1302
  //#endregion
1299
- export { Agent, type AgentDefinition, type ApprovalRequestInfo, type BackgroundAudioOptions, type BackgroundAudioPreset, type BackgroundAudioSpec, BaseRealtimeProvider, type BridgeConfig, type BridgeEventMap, type BuiltinToolsConfig, type CallEndReason, CallSession, type CallSessionFacade, type CallSnapshot, type CallStartedInfo, type CallState, type CaptureGreetingOptions, type CapturedGreeting, DEFAULT_KEYPAD_CLEAR_MESSAGE, DEFAULT_KEYPAD_INSTRUCTIONS, DEFAULT_KEYPAD_OPTIONS, DEFAULT_RECONNECT_POLICY, DEFAULT_SESSION_OPTIONS, type DeafnessOptions, type FinishCallToolOptions, type GreetingOptions, type HandoffDirective, type HandoffRecord, type HangupOptions, type IdleOptions, InMemorySessionStore, type InferSchema, type InterruptionBlockCause, InterruptionController, type InterruptionDecision, type InterruptionRateLimit, type InterruptionSettings, KeypadCollector, type KeypadCollectorHooks, type KeypadEntry, type KeypadEntryReason, type KeypadHandle, type KeypadKeyKind, type KeypadOptions, type Logger, type MarkEchoResult, NoiseAdaptiveVadController, type NoiseAdaptiveVadOptions, PlaybackTracker, type ProviderAudioDelta, type ProviderCapabilities, type ProviderCloseInfo, type ProviderEvents, type ProviderFactory, type ProviderFactoryContext, type ProviderFallbackInfo, type ProviderSessionInit, type ProviderToolCall, type ProviderToolSchema, type ProviderUsage, type ReconnectPolicy, type SendTextOptions, type SendToolResultOptions, SessionContext, type SessionEventMap, type SessionOptions, type SessionStore, type SessionUpdateOptions, type Tool, type ToolCallInfo, type ToolContext, type ToolDecoration, type ToolDefinition, type ToolMiddleware, type ToolRunInfo, type ToolStrategy, type TranscriptEntry, type TransferCallToolOptions, TwilioRealtimeBridge, type TwilioRestOptions, type TwilioStartEvent, type UsageInfo, type VadAdjustment, type VadConfig, type VadNoiseMetrics, type VadSuggestionInfo, type VadTuningProfile, type WebSocketLike, type ZodSchemaLike, captureGreetingAudio, collectAgentGraph, composeExecution, connectStreamTwiml, consoleLogger, createFinishCallTool, createHandoffTool, createTransferCallTool, decorateTool, defaultKeypadMessage, emptyUsage, handoffToolName, isHandoffDirective, noopLogger, resolveSessionOptions, tool, zodToJsonSchema };
1303
+ export { Agent, type AgentDefinition, type ApprovalRequestInfo, type BackgroundAudioOptions, type BackgroundAudioPreset, type BackgroundAudioSpec, BaseRealtimeProvider, type BridgeConfig, type BridgeEventMap, type BuiltinToolsConfig, type CallEndReason, CallSession, type CallSessionFacade, type CallSnapshot, type CallStartedInfo, type CallState, type CaptureGreetingOptions, type CapturedGreeting, DEFAULT_KEYPAD_CLEAR_MESSAGE, DEFAULT_KEYPAD_INSTRUCTIONS, DEFAULT_KEYPAD_OPTIONS, DEFAULT_RECONNECT_POLICY, DEFAULT_SESSION_OPTIONS, type DeafnessOptions, type FinishCallToolOptions, type GreetingOptions, type HandoffDirective, type HandoffRecord, type HangupOptions, type IdleOptions, InMemorySessionStore, type InferSchema, type InterruptionBlockCause, InterruptionController, type InterruptionDecision, type InterruptionRateLimit, type InterruptionSettings, KeypadCollector, type KeypadCollectorHooks, type KeypadEntry, type KeypadEntryReason, type KeypadHandle, type KeypadKeyKind, type KeypadOptions, type Logger, type MarkEchoResult, NoiseAdaptiveVadController, type NoiseAdaptiveVadOptions, PlaybackTracker, type ProviderAudioDelta, type ProviderCapabilities, type ProviderCloseInfo, type ProviderEvents, type ProviderFactory, type ProviderFactoryContext, type ProviderFallbackInfo, type ProviderHistoryEntry, type ProviderSessionInit, type ProviderToolCall, type ProviderToolSchema, type ProviderUsage, type ReconnectPolicy, type SendTextOptions, type SendToolResultOptions, SessionContext, type SessionEventMap, type SessionOptions, type SessionStore, type SessionUpdateOptions, type Tool, type ToolCallInfo, type ToolContext, type ToolDecoration, type ToolDefinition, type ToolMiddleware, type ToolRunInfo, type ToolStrategy, type TranscriptEntry, type TransferCallToolOptions, TwilioRealtimeBridge, type TwilioRestOptions, type TwilioStartEvent, type UsageInfo, type VadAdjustment, type VadConfig, type VadNoiseMetrics, type VadSuggestionInfo, type VadTuningProfile, type WebSocketLike, type ZodSchemaLike, captureGreetingAudio, collectAgentGraph, composeExecution, connectStreamTwiml, consoleLogger, createFinishCallTool, createHandoffTool, createTransferCallTool, decorateTool, defaultKeypadMessage, emptyUsage, handoffToolName, isHandoffDirective, noopLogger, resolveSessionOptions, tool, zodToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { t as TypedEmitter } from "./events-BylBSBW-.mjs";
2
- import { a as noopLogger, i as consoleLogger, n as deepMerge, r as childLogger, t as BaseRealtimeProvider } from "./BaseRealtimeProvider-C9C3s8jx.mjs";
1
+ import { t as TypedEmitter } from "./events-D-pvCH_F.mjs";
2
+ import { a as noopLogger, i as consoleLogger, n as deepMerge, r as childLogger, t as BaseRealtimeProvider } from "./BaseRealtimeProvider-Cj6JWR2k.mjs";
3
3
  import { t as InMemorySessionStore } from "./InMemorySessionStore-DYParOJO.mjs";
4
- import { a as TwilioMediaTransport, r as connectStreamTwiml, t as TwilioRestClient } from "./rest-BYqiVOhe.mjs";
4
+ import { a as TwilioMediaTransport, r as connectStreamTwiml, t as TwilioRestClient } from "./rest-D-DWWVIj.mjs";
5
5
  import { a as mulawBytesToMs, i as base64ByteLength } from "./mulaw--cwU2c9L.mjs";
6
6
  import { i as BackgroundAudioPlayer, n as NoiseFloorEstimator } from "./noise-CJ789zzj.mjs";
7
- import { t as buildSessionUpdate } from "./session-config-CbifLlkV.mjs";
7
+ import { t as buildSessionUpdate } from "./session-config-C31WZESg.mjs";
8
8
  import { readFileSync } from "node:fs";
9
9
  import * as z from "zod";
10
10
  import WebSocket$1 from "ws";
@@ -825,6 +825,43 @@ function formatTranscriptForInjection(entries, options = {}) {
825
825
  }
826
826
  return lines.sort((a, b) => a.atMs - b.atMs).map((line) => line.text).join("\n");
827
827
  }
828
+ /**
829
+ * The same replay as `formatTranscriptForInjection`, as structured turns for
830
+ * providers that seed history at session start (`ProviderSessionInit.history`).
831
+ * Agent lines keep their attribution (`Name: text`) whenever more than one
832
+ * agent exists on the call, and completed transfers become `developer` notes
833
+ * in timeline order — the anti-loop guarantees are identical to the text
834
+ * replay (see the field bug notes there).
835
+ */
836
+ function buildHistoryForSeeding(entries, options = {}) {
837
+ const { maxTurns = 30, agentNames, handoffs = [] } = options;
838
+ const recent = entries.slice(-maxTurns);
839
+ if (recent.length === 0) return [];
840
+ const multiAgent = (agentNames?.size ?? 0) > 1 || handoffs.length > 0;
841
+ const nameOf = (agentId) => (agentId ? agentNames?.get(agentId) : void 0) ?? agentId ?? "Agent";
842
+ const windowStartMs = recent[0].timestampMs;
843
+ const items = recent.map((entry) => ({
844
+ atMs: entry.timestampMs,
845
+ entry: entry.role === "user" ? {
846
+ role: "user",
847
+ text: entry.text
848
+ } : {
849
+ role: "assistant",
850
+ text: multiAgent ? `${nameOf(entry.agentId)}: ${entry.text}` : entry.text
851
+ }
852
+ }));
853
+ for (const handoff of handoffs) {
854
+ if (handoff.atMs < windowStartMs) continue;
855
+ items.push({
856
+ atMs: handoff.atMs,
857
+ entry: {
858
+ role: "developer",
859
+ text: `[transfer] ${nameOf(handoff.from)} -> ${nameOf(handoff.to)}` + (handoff.reason ? ` (reason: ${handoff.reason})` : "")
860
+ }
861
+ });
862
+ }
863
+ return items.sort((a, b) => a.atMs - b.atMs).map((item) => item.entry);
864
+ }
828
865
  //#endregion
829
866
  //#region src/session/usage.ts
830
867
  function emptyUsage() {
@@ -848,6 +885,10 @@ function emptyUsage() {
848
885
  var UsageAccumulator = class {
849
886
  usage = emptyUsage();
850
887
  add(providerUsage) {
888
+ if (providerUsage.audioSeconds !== void 0) {
889
+ this.usage.audioSeconds = Math.max(this.usage.audioSeconds ?? 0, providerUsage.audioSeconds);
890
+ if (providerUsage.totalTokens === 0 && providerUsage.inputTokens === 0 && providerUsage.outputTokens === 0) return this.snapshot();
891
+ }
851
892
  this.usage.inputTokens += providerUsage.inputTokens;
852
893
  this.usage.outputTokens += providerUsage.outputTokens;
853
894
  this.usage.totalTokens += providerUsage.totalTokens;
@@ -1273,6 +1314,7 @@ var CallSession = class extends TypedEmitter {
1273
1314
  /** Manual barge-in: stop the agent mid-sentence. */
1274
1315
  interrupt() {
1275
1316
  if (!this.generating && !this.tracker.isPlaybackActive()) return;
1317
+ if (this.modelOwnsTurnTaking()) return;
1276
1318
  this.provider?.cancelResponse();
1277
1319
  this.performInterrupt();
1278
1320
  }
@@ -1381,9 +1423,26 @@ var CallSession = class extends TypedEmitter {
1381
1423
  parameters: decorated.parameters
1382
1424
  };
1383
1425
  }),
1384
- providerOptions: this.activeAgentValue.providerOptions
1426
+ providerOptions: this.activeAgentValue.providerOptions,
1427
+ history: this.buildHistory()
1385
1428
  };
1386
1429
  }
1430
+ /** Whether the connected provider decides turn-taking itself (full-duplex). */
1431
+ modelOwnsTurnTaking() {
1432
+ return this.provider?.capabilities.turnTaking === "model";
1433
+ }
1434
+ /** Attributed replay of the call so far, as turns (see buildHistoryForSeeding). */
1435
+ buildHistory() {
1436
+ if (this.transcriptEntries.length === 0) return void 0;
1437
+ const turns = buildHistoryForSeeding(this.transcriptEntries, {
1438
+ agentNames: new Map([...this.agents].map(([id, agent]) => [id, agent.name])),
1439
+ handoffs: this.handoffHistory
1440
+ });
1441
+ return [{
1442
+ role: "developer",
1443
+ text: `Context: this phone call reconnected mid-conversation. You are ${this.activeAgentValue.name}. The conversation so far follows: assistant lines that name another agent were said by that agent, and \`[transfer]\` notes are routing that ALREADY happened. Anything already answered or already routed must not be routed again. Continue naturally from where it left off; do not greet again.`
1444
+ }, ...turns];
1445
+ }
1387
1446
  wireTransport() {
1388
1447
  const { transport } = this.deps;
1389
1448
  transport.on("media", (event) => this.handleInboundMedia(event.media.payload));
@@ -1395,8 +1454,8 @@ var CallSession = class extends TypedEmitter {
1395
1454
  this.handleKeypress(digit);
1396
1455
  this.emit("dtmf", { digit });
1397
1456
  });
1398
- transport.on("stop", () => void this.teardown("caller-hangup"));
1399
- transport.on("close", () => void this.teardown("caller-hangup"));
1457
+ transport.on("stop", () => void this.teardown(this.stateValue === "ending" ? this.hangupReason : "caller-hangup"));
1458
+ transport.on("close", () => void this.teardown(this.stateValue === "ending" ? this.hangupReason : "caller-hangup"));
1400
1459
  transport.on("error", (error) => this.emitError(error));
1401
1460
  }
1402
1461
  /** Emit 'error'; when the host attached no listener, log instead of losing it. */
@@ -1420,7 +1479,14 @@ var CallSession = class extends TypedEmitter {
1420
1479
  this.generating = true;
1421
1480
  this.currentResponseId = responseId;
1422
1481
  this.blockedUserTurn = "idle";
1423
- if (this.pendingHangup) this.pendingHangup.sawResponse = true;
1482
+ if (this.pendingHangup) {
1483
+ this.pendingHangup.sawResponse = true;
1484
+ if (this.pendingHangup.grace) {
1485
+ clearTimeout(this.pendingHangup.grace);
1486
+ this.timers.delete(this.pendingHangup.grace);
1487
+ this.pendingHangup.grace = null;
1488
+ }
1489
+ }
1424
1490
  this.noteHangupProgress();
1425
1491
  this.clearIdleTimer();
1426
1492
  this.interruptions.onResponseStarted(responseId);
@@ -1480,6 +1546,11 @@ var CallSession = class extends TypedEmitter {
1480
1546
  this.emit("user.speech.ended");
1481
1547
  });
1482
1548
  provider.on("toolCall", (call) => void this.handleToolCall(call));
1549
+ provider.on("usage", (usage) => {
1550
+ if (!provider.capabilities.decoupledBackend) return;
1551
+ const total = this.usageAccumulator.add(usage);
1552
+ this.emit("usage.updated", total, usage);
1553
+ });
1483
1554
  provider.on("error", (error) => this.emitError(error));
1484
1555
  provider.on("close", (info) => {
1485
1556
  if (this.stateValue === "ended" || this.stateValue === "ending") return;
@@ -1495,18 +1566,18 @@ var CallSession = class extends TypedEmitter {
1495
1566
  this.scheduleReconnect();
1496
1567
  });
1497
1568
  }
1498
- handleInboundMedia(payload) {
1569
+ handleInboundMedia(inbound) {
1570
+ let payload = inbound;
1499
1571
  if (this.stateValue === "ended" || this.stateValue === "ending") return;
1500
1572
  if (this.noiseVad) {
1501
1573
  const excluded = this.isUserSpeechExcluded() || this.tracker.isPlaybackActive() || this.pregreeting !== null && !this.pregreeting.played;
1502
1574
  const proposal = this.noiseVad.onInboundFrame(payload, excluded);
1503
1575
  if (proposal) this.handleVadProposal(proposal);
1504
1576
  }
1505
- if (this.pregreeting && !this.pregreeting.played) return;
1506
- if (this.deps.options.deafness.ignoreUserAudioUntilFirstTurnDone && !this.firstTurnDone) return;
1507
- if (this.deps.options.deafness.muteDuringToolExecution && this.runningTools.size > 0) return;
1508
- if (this.deps.options.deafness.muteWhileAgentSpeaking && this.tracker.isPlaybackActive()) return;
1509
- if (this.interruptions.isSuspended) return;
1577
+ if (this.pregreeting !== null && !this.pregreeting.played || this.deps.options.deafness.ignoreUserAudioUntilFirstTurnDone && !this.firstTurnDone || this.deps.options.deafness.muteDuringToolExecution && this.runningTools.size > 0 || this.deps.options.deafness.muteWhileAgentSpeaking && this.tracker.isPlaybackActive() || this.interruptions.isSuspended) {
1578
+ if (!this.modelOwnsTurnTaking()) return;
1579
+ payload = silenceLike(payload);
1580
+ }
1510
1581
  if (this.provider?.isConnected && !this.reconnecting) this.provider.sendAudio(payload);
1511
1582
  else {
1512
1583
  this.inboundBuffer.push(payload);
@@ -1515,7 +1586,7 @@ var CallSession = class extends TypedEmitter {
1515
1586
  }
1516
1587
  flushInboundBuffer() {
1517
1588
  if (!this.provider?.isConnected) return;
1518
- for (const payload of this.inboundBuffer) this.provider.sendAudio(payload);
1589
+ if (!this.modelOwnsTurnTaking()) for (const payload of this.inboundBuffer) this.provider.sendAudio(payload);
1519
1590
  this.inboundBuffer = [];
1520
1591
  }
1521
1592
  /** Caller speech is excluded from the noise floor, capped so a missing
@@ -1606,6 +1677,7 @@ var CallSession = class extends TypedEmitter {
1606
1677
  }
1607
1678
  handleBargeIn() {
1608
1679
  if (!this.generating && !this.tracker.isPlaybackActive()) return;
1680
+ if (this.modelOwnsTurnTaking()) return;
1609
1681
  const decision = this.interruptions.evaluate({ toolRunning: this.runningTools.size > 0 });
1610
1682
  if (!decision.allow) {
1611
1683
  if (decision.cause === "guard" || decision.cause === "disabled") this.blockedUserTurn = "speaking";
@@ -1949,7 +2021,7 @@ var CallSession = class extends TypedEmitter {
1949
2021
  }
1950
2022
  /** Inject a text turn now, or after the agent finishes speaking. */
1951
2023
  injectOrQueueText(text, triggerResponse) {
1952
- if (this.generating || this.tracker.isPlaybackActive()) {
2024
+ if (!this.provider?.capabilities.decoupledBackend && (this.generating || this.tracker.isPlaybackActive())) {
1953
2025
  this.pendingInjections.push({
1954
2026
  text,
1955
2027
  triggerResponse
@@ -1977,7 +2049,7 @@ var CallSession = class extends TypedEmitter {
1977
2049
  }
1978
2050
  deliverToolResult(callId, payload, triggerResponse = true) {
1979
2051
  if (this.stateValue === "ended") return;
1980
- if (this.deps.options.toolResultDelivery === "afterPlayback" && (this.generating || this.tracker.isPlaybackActive())) {
2052
+ if (this.deps.options.toolResultDelivery === "afterPlayback" && !this.provider?.capabilities.decoupledBackend && (this.generating || this.tracker.isPlaybackActive())) {
1981
2053
  this.toolQueue.enqueue({
1982
2054
  callId,
1983
2055
  toolName: "",
@@ -2077,6 +2149,21 @@ var CallSession = class extends TypedEmitter {
2077
2149
  if (!this.pendingHangup) return;
2078
2150
  if (!this.pendingHangup.sawResponse) return;
2079
2151
  if (this.generating || this.tracker.isPlaybackActive()) return;
2152
+ if (this.modelOwnsTurnTaking()) {
2153
+ if (this.pendingHangup.grace) return;
2154
+ const timer = setTimeout(() => {
2155
+ this.timers.delete(timer);
2156
+ const pending = this.pendingHangup;
2157
+ if (!pending) return;
2158
+ pending.grace = null;
2159
+ if (this.generating || this.tracker.isPlaybackActive()) return;
2160
+ this.completeHangup();
2161
+ }, HANGUP_SENTENCE_GRACE_MS);
2162
+ timer.unref?.();
2163
+ this.timers.add(timer);
2164
+ this.pendingHangup.grace = timer;
2165
+ return;
2166
+ }
2080
2167
  this.completeHangup();
2081
2168
  }
2082
2169
  completeHangup() {
@@ -2151,7 +2238,7 @@ var CallSession = class extends TypedEmitter {
2151
2238
  if (this.stateValue !== "active") return;
2152
2239
  this.reconnectAttempt = 0;
2153
2240
  this.reconnecting = false;
2154
- if (!provider.didResume) this.reinjectHistory(provider);
2241
+ if (!provider.didResume && !provider.capabilities.startupHistory) this.reinjectHistory(provider);
2155
2242
  this.flushInboundBuffer();
2156
2243
  this.emit("provider.reconnected");
2157
2244
  }
@@ -2223,7 +2310,7 @@ var CallSession = class extends TypedEmitter {
2223
2310
  ...this.buildProviderInit(),
2224
2311
  freshSession: true
2225
2312
  });
2226
- this.reinjectHistory(this.provider);
2313
+ if (!this.provider.capabilities.startupHistory) this.reinjectHistory(this.provider);
2227
2314
  this.provider.createResponse({ instructions: continueInstruction });
2228
2315
  } catch (error) {
2229
2316
  this.handoffInProgress = false;
@@ -2417,11 +2504,21 @@ var CallSession = class extends TypedEmitter {
2417
2504
  }
2418
2505
  };
2419
2506
  const PREGREETING_MARK = "pre:greeting";
2507
+ /** Longer than the speech gate's quiet window plus the mark round trip (0.8 s + ~0.3 s). */
2508
+ const HANGUP_SENTENCE_GRACE_MS = 1500;
2420
2509
  /** 400ms per frame — matches production burst-write implementations. */
2421
2510
  const PREGREETING_CHUNK_BYTES = 3200;
2422
2511
  function toError(value) {
2423
2512
  return value instanceof Error ? value : new Error(String(value));
2424
2513
  }
2514
+ /** Base64 μ-law digital silence with the same byte length as `payload`. */
2515
+ function silenceLike(payload) {
2516
+ const bytes = base64ByteLength(payload);
2517
+ if (bytes === SILENCE_FRAME_BYTES) return SILENCE_FRAME_BASE64;
2518
+ return Buffer.alloc(Math.max(0, Math.round(bytes)), 255).toString("base64");
2519
+ }
2520
+ const SILENCE_FRAME_BYTES = 160;
2521
+ const SILENCE_FRAME_BASE64 = Buffer.alloc(SILENCE_FRAME_BYTES, 255).toString("base64");
2425
2522
  function safeJsonStringify(value) {
2426
2523
  try {
2427
2524
  return JSON.stringify(value) ?? "null";
package/dist/openai.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_session_config = require("./session-config-CqJm2Kxz.cjs");
2
+ const require_session_config = require("./session-config-CYjxBqpF.cjs");
3
3
  const require_env = require("./env-DSnGaERV.cjs");
4
- const require_OpenAICompatibleProvider = require("./OpenAICompatibleProvider-Mp0Mefbh.cjs");
4
+ const require_OpenAICompatibleProvider = require("./OpenAICompatibleProvider-j2Nza2q2.cjs");
5
5
  //#region src/openai.ts
6
6
  /** OpenAI Realtime provider (GA API) — `realtime-voice-agents/openai`. */
7
7
  /** Env vars checked (in order) when no explicit apiKey is passed. */
package/dist/openai.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as Logger, c as SessionUpdateOptions, h as ProviderCapabilities, i as ProviderSessionInit, l as VadConfig, n as ProviderFactory, o as SendTextOptions, s as SendToolResultOptions, t as BaseRealtimeProvider } from "./BaseRealtimeProvider-BL75_HHh.cjs";
1
+ import { a as ProviderSessionInit, c as SendToolResultOptions, g as ProviderCapabilities, l as SessionUpdateOptions, n as ProviderFactory, s as SendTextOptions, t as BaseRealtimeProvider, u as VadConfig, v as Logger } from "./BaseRealtimeProvider-CO9N8jt-.cjs";
2
2
  //#region src/providers/openai-compatible/OpenAICompatibleProvider.d.ts
3
3
  interface OpenAICompatibleProviderConfig {
4
4
  apiKey: string;
package/dist/openai.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as Logger, c as SessionUpdateOptions, h as ProviderCapabilities, i as ProviderSessionInit, l as VadConfig, n as ProviderFactory, o as SendTextOptions, s as SendToolResultOptions, t as BaseRealtimeProvider } from "./BaseRealtimeProvider-CWJ81HIt.mjs";
1
+ import { a as ProviderSessionInit, c as SendToolResultOptions, g as ProviderCapabilities, l as SessionUpdateOptions, n as ProviderFactory, s as SendTextOptions, t as BaseRealtimeProvider, u as VadConfig, v as Logger } from "./BaseRealtimeProvider-BJQO-hpu.mjs";
2
2
  //#region src/providers/openai-compatible/OpenAICompatibleProvider.d.ts
3
3
  interface OpenAICompatibleProviderConfig {
4
4
  apiKey: string;
package/dist/openai.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { n as buildTurnDetection, t as buildSessionUpdate } from "./session-config-CbifLlkV.mjs";
1
+ import { n as buildTurnDetection, t as buildSessionUpdate } from "./session-config-C31WZESg.mjs";
2
2
  import { t as resolveApiKey } from "./env-DUwUWTsg.mjs";
3
- import { t as OpenAICompatibleProvider } from "./OpenAICompatibleProvider-D-2OOVBU.mjs";
3
+ import { t as OpenAICompatibleProvider } from "./OpenAICompatibleProvider-Dqje-boq.mjs";
4
4
  //#region src/openai.ts
5
5
  /** OpenAI Realtime provider (GA API) — `realtime-voice-agents/openai`. */
6
6
  /** Env vars checked (in order) when no explicit apiKey is passed. */
@@ -1,4 +1,4 @@
1
- import { t as TypedEmitter } from "./events-BylBSBW-.mjs";
1
+ import { t as TypedEmitter } from "./events-D-pvCH_F.mjs";
2
2
  //#region src/twilio/messages.ts
3
3
  const INBOUND_EVENTS = /* @__PURE__ */ new Set([
4
4
  "connected",