twilio-agent-connect 2.5.0 → 2.6.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.
package/dist/index.d.ts CHANGED
@@ -66,6 +66,7 @@ declare const TACConfigSchema: z.ZodPipe<z.ZodObject<{
66
66
  }, z.core.$strip>>;
67
67
  conversationConfigurationId: z.ZodOptional<z.ZodString>;
68
68
  voicePublicDomain: z.ZodOptional<z.ZodPreprocess<z.ZodOptional<z.ZodString>>>;
69
+ instancePublicDomain: z.ZodOptional<z.ZodPreprocess<z.ZodOptional<z.ZodString>>>;
69
70
  voiceWebsocketPath: z.ZodPreprocess<z.ZodDefault<z.ZodString>>;
70
71
  voiceActionPath: z.ZodPreprocess<z.ZodDefault<z.ZodString>>;
71
72
  voiceCallEventPath: z.ZodPreprocess<z.ZodDefault<z.ZodString>>;
@@ -74,7 +75,7 @@ declare const TACConfigSchema: z.ZodPipe<z.ZodObject<{
74
75
  region: z.ZodOptional<z.ZodString>;
75
76
  studioHandoffFlowSid: z.ZodOptional<z.ZodString>;
76
77
  }, z.core.$strip>, z.ZodTransform<{
77
- phoneNumber: string;
78
+ phoneNumber: string | undefined;
78
79
  phoneNumbers: string[];
79
80
  rcsSenderId: string | undefined;
80
81
  rcsSenderIds: string[];
@@ -98,6 +99,7 @@ declare const TACConfigSchema: z.ZodPipe<z.ZodObject<{
98
99
  voiceCallEventPath: string;
99
100
  conversationConfigurationId?: string | undefined;
100
101
  voicePublicDomain?: string | undefined;
102
+ instancePublicDomain?: string | undefined;
101
103
  cintelConfigurationId?: string | undefined;
102
104
  cintelSummaryOperatorSid?: string | undefined;
103
105
  region?: string | undefined;
@@ -127,6 +129,7 @@ declare const TACConfigSchema: z.ZodPipe<z.ZodObject<{
127
129
  whatsappNumbers?: string[] | undefined;
128
130
  conversationConfigurationId?: string | undefined;
129
131
  voicePublicDomain?: string | undefined;
132
+ instancePublicDomain?: string | undefined;
130
133
  cintelConfigurationId?: string | undefined;
131
134
  cintelSummaryOperatorSid?: string | undefined;
132
135
  region?: string | undefined;
@@ -166,6 +169,7 @@ declare const EnvironmentVariables: {
166
169
  readonly TWILIO_MEMORY_PHONE_TRAIT_FIELD: "TWILIO_MEMORY_PHONE_TRAIT_FIELD";
167
170
  readonly TWILIO_CONVERSATION_CONFIGURATION_ID: "TWILIO_CONVERSATION_CONFIGURATION_ID";
168
171
  readonly TWILIO_VOICE_PUBLIC_DOMAIN: "TWILIO_VOICE_PUBLIC_DOMAIN";
172
+ readonly TWILIO_INSTANCE_PUBLIC_DOMAIN: "TWILIO_INSTANCE_PUBLIC_DOMAIN";
169
173
  readonly TWILIO_VOICE_WEBSOCKET_PATH: "TWILIO_VOICE_WEBSOCKET_PATH";
170
174
  readonly TWILIO_VOICE_ACTION_PATH: "TWILIO_VOICE_ACTION_PATH";
171
175
  readonly TWILIO_VOICE_CALL_EVENT_PATH: "TWILIO_VOICE_CALL_EVENT_PATH";
@@ -1327,6 +1331,7 @@ declare const ConversationResponseSchema: z.ZodObject<{
1327
1331
  configurationId: z.ZodOptional<z.ZodString>;
1328
1332
  createdAt: z.ZodOptional<z.ZodString>;
1329
1333
  updatedAt: z.ZodOptional<z.ZodString>;
1334
+ metadata: z.ZodPreprocess<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
1330
1335
  }, z.core.$strip>;
1331
1336
  type ConversationResponse = z.infer<typeof ConversationResponseSchema>;
1332
1337
  /**
@@ -1341,6 +1346,7 @@ declare const ListConversationsResponseSchema: z.ZodObject<{
1341
1346
  configurationId: z.ZodOptional<z.ZodString>;
1342
1347
  createdAt: z.ZodOptional<z.ZodString>;
1343
1348
  updatedAt: z.ZodOptional<z.ZodString>;
1349
+ metadata: z.ZodPreprocess<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
1344
1350
  }, z.core.$strip>>;
1345
1351
  }, z.core.$strip>;
1346
1352
  type ListConversationsResponse = z.infer<typeof ListConversationsResponseSchema>;
@@ -2793,14 +2799,16 @@ declare class TACConfig {
2793
2799
  readonly apiSecret: string;
2794
2800
  /**
2795
2801
  * Default Twilio phone number for Voice and SMS — the sender used for
2796
- * outbound when a call does not specify `from`. Always populated and always a
2797
- * member of {@link phoneNumbers}.
2802
+ * outbound when a call does not specify `from`. Undefined when no phone
2803
+ * number is configured (the Voice and SMS channels then refuse to
2804
+ * construct, and Studio handoff from Chat returns `handoff_failed`);
2805
+ * otherwise a member of {@link phoneNumbers}.
2798
2806
  */
2799
- readonly phoneNumber: string;
2807
+ readonly phoneNumber?: string;
2800
2808
  /**
2801
2809
  * Full set of Twilio phone numbers this instance serves for Voice and SMS
2802
- * (the inbound allowlist). Always includes {@link phoneNumber} as the first,
2803
- * default sender.
2810
+ * (the inbound allowlist). Empty when none is configured; otherwise includes
2811
+ * {@link phoneNumber} as the first, default sender.
2804
2812
  */
2805
2813
  readonly phoneNumbers: string[];
2806
2814
  readonly rcsSenderId?: string;
@@ -2812,6 +2820,12 @@ declare class TACConfig {
2812
2820
  readonly memoryConfig: TACConfigData['memoryConfig'];
2813
2821
  readonly conversationConfigurationId?: string;
2814
2822
  readonly voicePublicDomain?: string;
2823
+ /**
2824
+ * This process's own directly-routable host. When set, the WebSocket and
2825
+ * action URLs (and call-event callbacks on calls TAC places) point here
2826
+ * instead of at {@link voicePublicDomain}. See {@link voiceCallbackDomain}.
2827
+ */
2828
+ readonly instancePublicDomain?: string;
2815
2829
  /** Path the voice WebSocket is served at (default '/ws'). */
2816
2830
  readonly voiceWebsocketPath: string;
2817
2831
  /** Path the ConversationRelay action callback is served at (default '/conversation-relay-callback'). */
@@ -2839,15 +2853,17 @@ declare class TACConfig {
2839
2853
  * - TWILIO_AUTH_TOKEN: Twilio Auth Token for API authentication
2840
2854
  * - TWILIO_API_KEY: Twilio API Key SID (starts with SK)
2841
2855
  * - TWILIO_API_SECRET: Twilio API Secret for API Key authentication
2842
- * - TWILIO_PHONE_NUMBER and/or TWILIO_PHONE_NUMBERS: at least one is required.
2843
- * Phone number(s) for voice and SMS channels — see **Multi-Value Senders** below.
2844
2856
  *
2845
2857
  * Optional environment variables:
2858
+ * - TWILIO_PHONE_NUMBER / TWILIO_PHONE_NUMBERS: phone number(s) for the voice and SMS
2859
+ * channels, which require at least one — see **Multi-Value Senders** below.
2846
2860
  * - TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS: WhatsApp number(s) for the
2847
2861
  * WhatsApp channel (e.g., 'whatsapp:+1234567890')
2848
2862
  * - TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS: RCS Sender ID(s) for the RCS channel
2849
2863
  * - TWILIO_CONVERSATION_CONFIGURATION_ID: Conversation Orchestrator configuration ID (enables orchestrated mode)
2850
2864
  * - TWILIO_VOICE_PUBLIC_DOMAIN: Public domain for voice routes (required for voice; a port and/or base path are allowed, e.g., 'abc123.ngrok.app', 'example.ngrok.app:8080', or 'example.com/server1')
2865
+ * - TWILIO_INSTANCE_PUBLIC_DOMAIN: This process's own directly-routable host, for pinning a
2866
+ * call's out-of-band webhooks to the instance holding its WebSocket (multi-replica voice only)
2851
2867
  * - TWILIO_VOICE_WEBSOCKET_PATH: Path for the voice WebSocket (default: /ws)
2852
2868
  * - TWILIO_VOICE_ACTION_PATH: Path for the ConversationRelay action callback (default: /conversation-relay-callback)
2853
2869
  * - TWILIO_VOICE_CALL_EVENT_PATH: Base path for the call-event callbacks — status, async AMD, recording (default: /twilio/call-events)
@@ -2861,8 +2877,9 @@ declare class TACConfig {
2861
2877
  * e.g. `TWILIO_PHONE_NUMBERS=+1555,+1444`. Whichever side is set back-fills
2862
2878
  * the other: the singular becomes the default sender and the plural the full
2863
2879
  * allowlist. Entries are whitespace-trimmed and de-duplicated, with the
2864
- * default kept first. `phoneNumber` requires at least one of the two; the RCS
2865
- * and WhatsApp pairs stay optional.
2880
+ * default kept first. All three pairs are optional at the config level; each
2881
+ * channel requires its own pair at construction (Voice and SMS need
2882
+ * `phoneNumber`/`phoneNumbers`).
2866
2883
  *
2867
2884
  * Memory Configuration (defaults defined in TwilioMemoryConfigSchema):
2868
2885
  * - TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: Trait groups to include (comma-separated, e.g., "Contact,Preferences")
@@ -2892,6 +2909,11 @@ declare class TACConfig {
2892
2909
  * and TACServer registers routes at it, so the two can't drift.
2893
2910
  */
2894
2911
  callEventPath(kind: CallEventKind): string;
2912
+ /**
2913
+ * Host Twilio should reach for a call in progress: {@link instancePublicDomain}
2914
+ * if set, else the shared {@link voicePublicDomain}.
2915
+ */
2916
+ get voiceCallbackDomain(): string | undefined;
2895
2917
  /**
2896
2918
  * Public URL for a call-event callback, or `undefined` without a public domain.
2897
2919
  */
@@ -3081,6 +3103,8 @@ declare class ConversationClient extends BaseClient {
3081
3103
  type: 'CUSTOMER' | 'AI_AGENT' | 'HUMAN_AGENT';
3082
3104
  addresses: ConversationAddress[];
3083
3105
  }>;
3106
+ /** Conversation metadata (string values; CO allows at most 8 keys). */
3107
+ metadata?: Record<string, string>;
3084
3108
  }): Promise<ConversationResponse>;
3085
3109
  /**
3086
3110
  * Create a conversation with inline participants, reusing an existing active
@@ -3088,11 +3112,15 @@ declare class ConversationClient extends BaseClient {
3088
3112
  *
3089
3113
  * On 409 CO returns the existing conversation ID in the
3090
3114
  * X-Conflicting-Resource-Id response header.
3115
+ *
3116
+ * @param participants - Participants to create with the conversation
3117
+ * @param metadata - Set at creation; not applied when an existing
3118
+ * conversation is reused — the caller patches it
3091
3119
  */
3092
3120
  createOrReuseConversation(participants: Array<{
3093
3121
  type: 'CUSTOMER' | 'AI_AGENT' | 'HUMAN_AGENT';
3094
3122
  addresses: ConversationAddress[];
3095
- }>): Promise<{
3123
+ }>, metadata?: Record<string, string>): Promise<{
3096
3124
  conversation: {
3097
3125
  id: string;
3098
3126
  };
@@ -3164,6 +3192,24 @@ declare class ConversationClient extends BaseClient {
3164
3192
  * @returns Promise containing updated conversation
3165
3193
  */
3166
3194
  updateConversation(conversationId: string, status: 'ACTIVE' | 'INACTIVE' | 'CLOSED'): Promise<ConversationResponse>;
3195
+ /**
3196
+ * Fetch a conversation, including its metadata.
3197
+ *
3198
+ * @param conversationId - The conversation ID to fetch
3199
+ */
3200
+ getConversation(conversationId: string): Promise<ConversationResponse>;
3201
+ /**
3202
+ * Merge `metadata` into a conversation's metadata.
3203
+ *
3204
+ * A `PATCH` with only the given keys: other keys already on the conversation
3205
+ * are kept. Conversation Orchestrator rejects metadata changes once the
3206
+ * conversation is CLOSED.
3207
+ *
3208
+ * @param conversationId - The conversation ID to update
3209
+ * @param metadata - Keys to set (string values)
3210
+ * @returns The conversation, with its merged metadata
3211
+ */
3212
+ patchConversationMetadata(conversationId: string, metadata: Record<string, string>): Promise<ConversationResponse>;
3167
3213
  /**
3168
3214
  * Retrieve the details for a single configuration
3169
3215
  *
@@ -3221,7 +3267,7 @@ interface BaseChannelOptions {
3221
3267
  *
3222
3268
  * - "never": Memory is not automatically retrieved. Use the memory TAC tool or manually call `tac.retrieveMemory()` in callbacks for conditional retrieval.
3223
3269
  * - "always": Memory is automatically retrieved (using the message as query) for every inbound message and available in `onMessageReady` callback.
3224
- * - "once": Memory is retrieved once at conversation start with no query (and no conversation id) and cached on the session. Subsequent messages reuse the cache until the conversation becomes INACTIVE.
3270
+ * - "once" (Voice only): Memory is retrieved once at conversation start with no query (and no conversation id) and cached on the session. Subsequent prompts reuse the cache until the conversation becomes INACTIVE. Deprecated on messaging channels (removed in 3.0), which run it as "always".
3225
3271
  */
3226
3272
  memoryMode?: MemoryMode;
3227
3273
  /**
@@ -3233,12 +3279,13 @@ interface BaseChannelOptions {
3233
3279
  /**
3234
3280
  * Abstract base class for all channel implementations
3235
3281
  *
3236
- * Provides common functionality for:
3237
- * - Conversation lifecycle management and session tracking
3238
- * - Webhook deduplication using Twilio idempotency tokens
3239
- * - Event filtering to prevent cross-channel fanout
3240
- * - Memory retrieval integration
3241
- * - Error handling and logging
3282
+ * Provides only what every channel family shares: webhook deduplication,
3283
+ * event filtering to prevent cross-channel fanout, lifecycle analytics from
3284
+ * Conversation Orchestrator webhooks, memory retrieval, and error handling.
3285
+ *
3286
+ * Session storage deliberately isn't here. `VoiceChannel` owns its sessions (a
3287
+ * call is pinned to the process holding its WebSocket); messaging channels
3288
+ * derive a session per webhook and hold nothing between them.
3242
3289
  *
3243
3290
  * Subclasses must implement channel-specific webhook processing and message sending.
3244
3291
  */
@@ -3247,8 +3294,9 @@ declare abstract class BaseChannel {
3247
3294
  protected readonly config: TACConfig;
3248
3295
  protected readonly logger: Logger;
3249
3296
  protected readonly conversationClient: ConversationClient | null;
3250
- protected readonly activeConversations: Map<ConversationId, ConversationSession>;
3251
3297
  protected readonly callbacks: BaseChannelEvents;
3298
+ /** TAC's forwarder to `tac.onConversationEnded`, while it fills the slot. */
3299
+ private tacConversationEndedForwarder;
3252
3300
  protected readonly memoryMode: MemoryMode;
3253
3301
  private readonly processedWebhookTokens;
3254
3302
  private readonly maxTrackedTokens;
@@ -3277,29 +3325,89 @@ declare abstract class BaseChannel {
3277
3325
  */
3278
3326
  abstract processWebhook(payload: unknown): Promise<void>;
3279
3327
  /**
3280
- * Send a response back to the user (implemented by subclasses)
3328
+ * Send a response back to the user (implemented by subclasses).
3329
+ *
3330
+ * Accepts the conversation id or the turn's `ConversationSession`; messaging
3331
+ * channels send straight from a session, and rebuild one from the id.
3332
+ */
3333
+ abstract sendResponse(conversationId: ConversationId | ConversationSession, message: string, metadata?: Record<string, unknown>): Promise<void>;
3334
+ /**
3335
+ * Get a live conversation session held by this channel.
3336
+ *
3337
+ * Only `VoiceChannel` holds sessions (a call is pinned to one process); the
3338
+ * default returns `undefined`.
3281
3339
  */
3282
- abstract sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
3340
+ getConversationSession(_conversationId: ConversationId): ConversationSession | undefined;
3283
3341
  /**
3284
- * Start a new conversation session
3342
+ * Check if this channel holds a live session for a conversation. Only
3343
+ * `VoiceChannel` holds sessions; the default returns `false`.
3285
3344
  */
3286
- protected startConversation(conversationId: ConversationId, profileId?: ProfileId, serviceId?: string): ConversationSession;
3345
+ isConversationActive(_conversationId: ConversationId): boolean;
3287
3346
  /**
3288
- * End a conversation session.
3347
+ * This channel's type as Conversation Orchestrator writes it on participant
3348
+ * addresses (`SMS`, `WHATSAPP`, `VOICE`, …).
3289
3349
  *
3290
- * Triggers the onConversationEnded callback BEFORE removing the session,
3291
- * so the callback receives the full ConversationSession data.
3292
- * Errors in the callback do not prevent session cleanup.
3350
+ * @internal
3293
3351
  */
3294
- protected endConversation(conversationId: ConversationId): Promise<void>;
3352
+ protected get coChannel(): string;
3295
3353
  /**
3296
- * Get an active conversation session
3354
+ * Whether `address` is TAC's own address on this channel. Channels override
3355
+ * this; the default claims no address.
3356
+ *
3357
+ * @internal
3297
3358
  */
3298
- getConversationSession(conversationId: ConversationId): ConversationSession | undefined;
3359
+ protected isOwnCoAddress(_address: string): boolean;
3299
3360
  /**
3300
- * Check if a conversation is active
3361
+ * Report "Conversation Started" from a CO `PARTICIPANT_ADDED` event.
3362
+ *
3363
+ * Counts the customer joining on this channel: a `CUSTOMER`, or an `UNKNOWN`
3364
+ * participant that isn't TAC's own address (capture can add the customer
3365
+ * untyped). Each channel reports only its own channel type, so a webhook
3366
+ * handed to every channel counts once per channel.
3367
+ *
3368
+ * @internal
3301
3369
  */
3302
- isConversationActive(conversationId: ConversationId): boolean;
3370
+ protected trackConversationStarted(eventData: unknown): void;
3371
+ /**
3372
+ * Report "Conversation Ended" for a conversation CO closed.
3373
+ *
3374
+ * Reported once per process across channels, without a `channel` — see
3375
+ * `TAC.reportConversationEnded`. `durationMs` is CO's `updatedAt −
3376
+ * createdAt`; `undefined` leaves it out rather than guessing.
3377
+ *
3378
+ * @internal
3379
+ */
3380
+ protected trackConversationEnded(conversationId: string, durationMs: number | undefined): void;
3381
+ /**
3382
+ * Whether anything would receive `onConversationEnded`. Channels check this
3383
+ * before rebuilding a closed conversation's session from Conversation
3384
+ * Orchestrator: with no handler, there is nothing to hand it to.
3385
+ *
3386
+ * Registering with TAC fills the slot with a forwarder to
3387
+ * `tac.onConversationEnded`; while that forwarder is installed, ask TAC. A
3388
+ * handler set with `channel.on('conversationEnded', ...)` — before or after
3389
+ * registration — replaces it and counts on its own.
3390
+ *
3391
+ * @internal
3392
+ */
3393
+ protected hasConversationEndedHandler(): boolean;
3394
+ /**
3395
+ * Install TAC's forwarder to `tac.onConversationEnded` in this channel's
3396
+ * slot, remembering it so {@link hasConversationEndedHandler} can tell it
3397
+ * apart from a handler registered directly on the channel.
3398
+ *
3399
+ * @internal
3400
+ */
3401
+ setConversationEndedForwarderInternal(forwarder: NonNullable<BaseChannelEvents['onConversationEnded']>): void;
3402
+ /**
3403
+ * Fire `onConversationEnded` for a session, swallowing handler errors.
3404
+ *
3405
+ * A developer callback throwing must not abort the channel's own cleanup or
3406
+ * fail the webhook, so the error is logged and dropped here.
3407
+ *
3408
+ * @internal
3409
+ */
3410
+ protected triggerConversationEnded(session: ConversationSession): Promise<void>;
3303
3411
  /**
3304
3412
  * Handle errors with proper context
3305
3413
  */
@@ -3321,8 +3429,10 @@ declare abstract class BaseChannel {
3321
3429
  * Self-filtering: check if webhook event belongs to this channel.
3322
3430
  *
3323
3431
  * - COMMUNICATION_CREATED: require author.channel matches this channel type
3324
- * - CONVERSATION_UPDATED: only process if conversation is tracked locally
3325
- * - Other events: pass through
3432
+ * - Other events pass through, including CONVERSATION_UPDATED — the
3433
+ * per-channel handler filters that one. Filtering it here on locally
3434
+ * tracked state would drop it on any instance that didn't serve the
3435
+ * conversation's messages.
3326
3436
  */
3327
3437
  protected isEventForThisChannel(webhookData: ConversationWebhookPayload): boolean;
3328
3438
  /**
@@ -3379,13 +3489,6 @@ declare abstract class BaseChannel {
3379
3489
  * continues without memory context.
3380
3490
  */
3381
3491
  protected retrieveMemoryIfEnabled(session: ConversationSession, query?: string): Promise<TACMemoryResponse | undefined>;
3382
- /**
3383
- * Invalidate cached memory for "once" mode when a conversation becomes
3384
- * INACTIVE. Conversation Orchestrator updates memory on the INACTIVE
3385
- * transition, so the next message re-fetches fresh memory. No-op for other
3386
- * memory modes.
3387
- */
3388
- protected invalidateCachedMemory(conversationId: ConversationId): void;
3389
3492
  /**
3390
3493
  * Cleanup resources when shutting down
3391
3494
  */
@@ -3451,6 +3554,8 @@ declare class TAC {
3451
3554
  private messageReadyCallback?;
3452
3555
  private interruptCallback?;
3453
3556
  private conversationEndedCallback?;
3557
+ private readonly participantLookups;
3558
+ private readonly reportedEnded;
3454
3559
  private constructor();
3455
3560
  static create(options?: TACOptions): Promise<TAC>;
3456
3561
  /**
@@ -3503,12 +3608,57 @@ declare class TAC {
3503
3608
  /**
3504
3609
  * Register callback for when a conversation ends.
3505
3610
  *
3506
- * The callback is triggered by channels when a conversation is closed
3507
- * (e.g., SMS conversation status changed to CLOSED, or voice WebSocket
3508
- * disconnected). The callback receives the full ConversationSession before
3509
- * it is cleaned up.
3611
+ * Fires when Conversation Orchestrator closes a conversation, on whichever
3612
+ * replica receives the CLOSED webhook — so the session it receives is
3613
+ * rebuilt from Conversation Orchestrator's participant list (identity only:
3614
+ * `conversationId`, `profileId`, participants). On messaging, read the
3615
+ * conversation's stored metadata with `conversationMetadata(session)`.
3616
+ * Relay-only and Media
3617
+ * Streams voice calls have no CO conversation, so they fire it at WebSocket
3618
+ * teardown with the live session instead. For an orchestrated call's live
3619
+ * state (transcript, `metadata`), use `VoiceChannel.onCallEnded`.
3620
+ *
3621
+ * At-least-once across webhook retries and replicas, like `onMessageReady`.
3510
3622
  */
3511
3623
  onConversationEnded(callback: ConversationEndedCallback): void;
3624
+ /**
3625
+ * Whether an `onConversationEnded` handler is registered. Channels check this
3626
+ * before rebuilding a session from Conversation Orchestrator: with no
3627
+ * handler, there is nothing to hand it to.
3628
+ *
3629
+ * @internal
3630
+ */
3631
+ hasConversationEndedCallback(): boolean;
3632
+ /**
3633
+ * List a conversation's participants, shared across channels briefly.
3634
+ *
3635
+ * A CO webhook is handed to every channel, and several may need the same
3636
+ * conversation's participants — to rebuild a closed conversation's session
3637
+ * for `onConversationEnded`. Concurrent callers share one in-flight request, and
3638
+ * later callers reuse its result until a minute after the request started. A
3639
+ * failure isn't cached. Not for paths that need fresh participants, like
3640
+ * reconciliation or resolving a session by CallSid.
3641
+ *
3642
+ * @throws If Conversation Orchestrator isn't configured, or whatever
3643
+ * `listParticipants` throws.
3644
+ * @internal
3645
+ */
3646
+ listParticipantsShared(conversationId: string): Promise<ConversationParticipant[]>;
3647
+ /**
3648
+ * Report "Conversation Ended" for a conversation Conversation Orchestrator
3649
+ * closed, once per process.
3650
+ *
3651
+ * Every channel is handed the CLOSED webhook, and its payload doesn't say
3652
+ * which channel the conversation was on. Finding out would take a
3653
+ * participant lookup made only for telemetry, so the event carries no
3654
+ * `channel`: join it to "Conversation Started" on `conversation_id`. The
3655
+ * first channel to report a conversation wins; the rest are dropped.
3656
+ *
3657
+ * @param durationMs - CO's `updatedAt − createdAt`; `undefined` leaves it
3658
+ * out rather than guessing.
3659
+ * @internal
3660
+ */
3661
+ reportConversationEnded(conversationId: string, durationMs: number | undefined): void;
3512
3662
  /**
3513
3663
  * Whether Conversation Orchestrator is configured.
3514
3664
  * Returns false in voice-only mode.
@@ -3610,6 +3760,11 @@ declare function shutdownAnalytics(): Promise<void>;
3610
3760
  /**
3611
3761
  * Messaging channel configuration options.
3612
3762
  * Alias for BaseChannelOptions that can be extended by specific channel implementations.
3763
+ *
3764
+ * `memoryMode: "once"` is **deprecated** on messaging channels and removed in
3765
+ * 3.0. It caches a recall on a session that outlives one request, which
3766
+ * messaging channels don't keep, so it logs a warning and runs as `"always"`.
3767
+ * It's still supported on the Voice channel.
3613
3768
  */
3614
3769
  type MessagingChannelConfig = BaseChannelOptions;
3615
3770
  /**
@@ -3622,6 +3777,8 @@ interface MessagingChannelEvents extends BaseChannelEvents {
3622
3777
  message: string;
3623
3778
  author: string;
3624
3779
  userMemory: any;
3780
+ /** This turn's session, derived from the webhook. */
3781
+ session: ConversationSession;
3625
3782
  }) => void;
3626
3783
  }
3627
3784
  /**
@@ -3630,6 +3787,15 @@ interface MessagingChannelEvents extends BaseChannelEvents {
3630
3787
  * Provides shared webhook processing logic for messaging channels
3631
3788
  * (SMS and Chat) that use the Conversations Service webhooks.
3632
3789
  *
3790
+ * **Stateless by construction.** No conversation session is kept between
3791
+ * webhooks: each request derives its own `ConversationSession` from the
3792
+ * payload, config, and one `listParticipants` call it needs anyway. So any
3793
+ * replica can serve any webhook — no sticky sessions, no shared datastore. A
3794
+ * session lasts one turn, so `session.metadata` doesn't carry over to the next
3795
+ * message; keep state across turns in your own store, keyed by
3796
+ * `conversationId`. `conversationMetadata(session)` reads the metadata stored
3797
+ * on Conversation Orchestrator from any instance.
3798
+ *
3633
3799
  * Subclasses must implement:
3634
3800
  * - `isDefaultAgentAddress`: fast-path check for the channel's default agent address
3635
3801
  * - `getAgentAddress`: return the agent's `ConversationAddress` for a conversation
@@ -3679,11 +3845,35 @@ declare abstract class MessagingChannel extends BaseChannel {
3679
3845
  /**
3680
3846
  * Return the agent-side ConversationAddress for this conversation.
3681
3847
  *
3682
- * Used by `reconcileParticipants` to identify which participant (by channel
3683
- * + address) represents the agent. May read from session state (e.g. chat's
3684
- * per-conversation channelId) to build the address.
3848
+ * Identifies which participant represents the agent, and supplies the
3849
+ * `from` address for outbound sends.
3685
3850
  */
3686
3851
  protected abstract getAgentAddress(conversationId: ConversationId): ConversationAddress;
3852
+ /**
3853
+ * The agent-side address for `session`; what TAC's own paths call.
3854
+ *
3855
+ * Defaults to `getAgentAddress(session.conversationId)`, so a subclass
3856
+ * overriding only that keeps working. Channels whose address depends on
3857
+ * per-conversation data (chat's `channelId`) override this to read the
3858
+ * session directly.
3859
+ */
3860
+ protected agentAddressFor(session: ConversationSession): ConversationAddress;
3861
+ protected isOwnCoAddress(address: string): boolean;
3862
+ /**
3863
+ * Messaging channels keep no sessions between webhooks, so there is nothing
3864
+ * to look up: always `undefined`.
3865
+ *
3866
+ * @deprecated Use the session `onMessageReady` (or
3867
+ * `initiateOutboundConversation`) hands you. Removed in 3.0.
3868
+ */
3869
+ getConversationSession(_conversationId: ConversationId): undefined;
3870
+ /**
3871
+ * Messaging channels keep no sessions between webhooks: always `false`.
3872
+ *
3873
+ * @deprecated Messaging channels are stateless; track conversations in your
3874
+ * own store, keyed by `conversationId`. Removed in 3.0.
3875
+ */
3876
+ isConversationActive(_conversationId: ConversationId): false;
3687
3877
  /**
3688
3878
  * Report a delivered response.
3689
3879
  *
@@ -3693,30 +3883,140 @@ declare abstract class MessagingChannel extends BaseChannel {
3693
3883
  */
3694
3884
  protected trackResponseSent(conversationId: ConversationId): void;
3695
3885
  /**
3696
- * Check if a message is from the bot itself (2-tier).
3886
+ * Whether the author is TAC, judged from an already-fetched participant list.
3697
3887
  *
3698
- * 1. Default agent address (stateless, no API call)
3699
- * 2. API fallback via listParticipants (cross-process / multi-worker)
3888
+ * The caller does the free check (author address is a configured agent
3889
+ * address) first; this catches TAC speaking from some other address.
3700
3890
  */
3701
3891
  private isOwnMessage;
3892
+ /**
3893
+ * Fetch a conversation's participants, returning `null` on failure.
3894
+ *
3895
+ * One call per inbound message, shared by the self-message check,
3896
+ * reconciliation, and profile resolution. None of them can proceed without
3897
+ * it, so a failure is a hard stop for the caller.
3898
+ */
3899
+ protected listParticipantsOrNull(conversationId: ConversationId): Promise<ConversationParticipant[] | null>;
3900
+ /**
3901
+ * Build an Actions API participant reference.
3902
+ *
3903
+ * Conversation Orchestrator resolves by participant id or by explicit
3904
+ * `(channel, address)`. Prefer the id — reconciliation has already
3905
+ * established it — and fall back to the address when there isn't one.
3906
+ */
3907
+ protected participantRef(address: string | undefined, participantId: string | undefined): ActionParticipantRef;
3908
+ /** A fresh, empty session for one turn of `conversationId` on this channel. */
3909
+ protected newSession(conversationId: string): ConversationSession;
3910
+ /** Whether `p` holds `address` on `channel`. */
3911
+ private ownsAddress;
3912
+ /**
3913
+ * Build a session for a conversation from its participants.
3914
+ *
3915
+ * Used where no inbound webhook is in hand: a CLOSED webhook, or
3916
+ * `sendResponse` given a bare id. Returns `null` when no participant is on
3917
+ * this channel, which is how another channel's conversation is filtered out.
3918
+ */
3919
+ protected sessionFromParticipants(conversationId: string, participants: ConversationParticipant[]): ConversationSession | null;
3920
+ /**
3921
+ * Resolve the session a `sendResponse` call replies within.
3922
+ *
3923
+ * A session is used as-is — it already carries both participants. A bare id
3924
+ * costs a `listParticipants` call to rebuild one, since the channel keeps no
3925
+ * session to look up.
3926
+ *
3927
+ * @throws If the participants can't be read, or no recipient resolves.
3928
+ */
3929
+ protected resolveSendSession(target: ConversationId | ConversationSession): Promise<ConversationSession & {
3930
+ authorInfo: AuthorInfo;
3931
+ }>;
3932
+ /**
3933
+ * The `channelSettings` for a reply within `session`, if any.
3934
+ *
3935
+ * Default (SMS, RCS, WhatsApp): `channelId` is optional and passed through
3936
+ * when the session carries one. Chat overrides this, since `channelId` is
3937
+ * required for delivery there.
3938
+ */
3939
+ protected buildChannelSettings(session: ConversationSession): ActionChannelSettings | undefined;
3940
+ /**
3941
+ * Send a text response using the Conversation Orchestrator Actions API
3942
+ * (SEND_MESSAGE).
3943
+ *
3944
+ * **Pass the session, not the id.** Hand back the one `onMessageReady` gave
3945
+ * you (or that `initiateOutboundConversation` returned) and the send costs no
3946
+ * extra API call — it already carries both participants. A bare id still
3947
+ * works, but the channel keeps no session to look up, so it spends a
3948
+ * `listParticipants` call rebuilding one.
3949
+ *
3950
+ * @param conversationIdOrSession - The `ConversationSession` to reply within
3951
+ * (preferred), or the conversation id.
3952
+ * @param message - Message content.
3953
+ * @param metadata - Optional metadata, passed to `onError` on failure.
3954
+ * @throws If no recipient can be resolved for the conversation, or the send
3955
+ * fails.
3956
+ */
3957
+ sendResponse(conversationIdOrSession: ConversationId | ConversationSession, message: string, metadata?: Record<string, unknown>): Promise<void>;
3702
3958
  /**
3703
3959
  * Register event callbacks (override for messaging-specific events)
3704
3960
  */
3705
3961
  on(event: string, callback: (...args: any[]) => void): void;
3706
3962
  /**
3707
- * Process messaging channel webhook from Conversation Orchestrator
3963
+ * Process messaging channel webhook from Conversation Orchestrator.
3964
+ *
3965
+ * Handles:
3966
+ *
3967
+ * - `COMMUNICATION_CREATED`: process an incoming message from the customer
3968
+ * - `CONVERSATION_UPDATED`: fire `onConversationEnded` and report
3969
+ * "Conversation Ended" when the conversation closes
3970
+ * - `PARTICIPANT_ADDED`: report "Conversation Started" when the customer
3971
+ * joins on this channel
3972
+ *
3973
+ * Any replica can handle any webhook. The idempotency cache is per-process,
3974
+ * though, so a Twilio retry landing on a different replica is processed
3975
+ * again, and `onMessageReady` can run twice for the same message. Retries
3976
+ * are rare when the webhook is acknowledged before processing, as
3977
+ * `TACServer` does.
3708
3978
  */
3709
3979
  processWebhook(payload: unknown, idempotencyToken?: string): Promise<void>;
3710
3980
  /**
3711
- * Handle conversation creation event
3981
+ * A loader that fetches a conversation's CO metadata, for
3982
+ * `conversationMetadata(session)`. The session keeps the result, so for its
3983
+ * turn only.
3712
3984
  */
3713
- private handleConversationCreated;
3985
+ private coMetadataLoader;
3986
+ /**
3987
+ * Build this request's session from the webhook payload and config.
3988
+ *
3989
+ * Network-free — the author, the agent address and `channelId` are all in
3990
+ * hand already. Reconciliation layers the participant ids on after.
3991
+ * `inboundAgentAddress` is the sender the customer messaged, when the webhook
3992
+ * names it; otherwise the channel default stands in until the caller
3993
+ * resolves it.
3994
+ */
3995
+ private resolveSession;
3714
3996
  /**
3715
3997
  * Handle new communication event (incoming message)
3716
3998
  */
3717
3999
  private handleCommunicationCreated;
3718
4000
  /**
3719
- * Handle conversation updated event
4001
+ * Resolve both sides of this turn from the participant list.
4002
+ *
4003
+ * Returns `false` when the message must not be answered: it's TAC's own, or
4004
+ * reconciliation failed (dropped, surfaced through `onError`).
4005
+ */
4006
+ private resolveParticipants;
4007
+ /**
4008
+ * Handle conversation updated event.
4009
+ *
4010
+ * Only CLOSED is acted on: it reports "Conversation Ended", from the payload
4011
+ * alone and once across channels, and fires `onConversationEnded`. Only a
4012
+ * registered handler costs a participant lookup — shared with the other
4013
+ * channels handling the same webhook — which confirms the conversation is on
4014
+ * this channel (a CHAT close must not fire on SMS) and lets this work on
4015
+ * whichever replica Twilio picked.
4016
+ *
4017
+ * The session is rebuilt the same way on every replica. The conversation's
4018
+ * CO metadata is read through `conversationMetadata(session)`: answered from
4019
+ * the payload when it carries metadata, otherwise fetched on demand.
3720
4020
  */
3721
4021
  private handleConversationUpdated;
3722
4022
  /**
@@ -3752,15 +4052,17 @@ declare abstract class MessagingChannel extends BaseChannel {
3752
4052
  * (via `session.authorInfo.participantId`), so promoting some other
3753
4053
  * `UNKNOWN` CHAT participant could pick the wrong recipient.
3754
4054
  *
3755
- * @param agentAddress - The agent address for this conversation, normally
3756
- * derived from the inbound webhook's recipient. When omitted, it is resolved
3757
- * from a participant scan (phone-like channels) or the channel default.
4055
+ * @param session - Supplies the conversation id and the agent address to
4056
+ * match on — the sender the customer messaged, already resolved on
4057
+ * `session.aiAgentInfo`.
4058
+ * @param participants - Already fetched by the caller; reusing that response
4059
+ * is what makes running this on every message free.
3758
4060
  * @returns `[agent, customerOrNull]` on success. `customer` is `null` when
3759
4061
  * `reconcileCustomerType` is `false`. `null` overall when either the agent
3760
4062
  * or the customer cannot be resolved — the caller treats `null` as a hard
3761
4063
  * stop and skips the message-ready callback.
3762
4064
  */
3763
- protected reconcileParticipants(conversationId: ConversationId, agentAddress?: ConversationAddress): Promise<[ConversationParticipant, ConversationParticipant | null] | null>;
4065
+ protected reconcileParticipants(session: ConversationSession, participants: ConversationParticipant[]): Promise<[ConversationParticipant, ConversationParticipant | null] | null>;
3764
4066
  /**
3765
4067
  * Resolve the agent address when the inbound webhook carried no recipient.
3766
4068
  *
@@ -3768,7 +4070,12 @@ declare abstract class MessagingChannel extends BaseChannel {
3768
4070
  * on this channel; falls back to the channel default when none is present.
3769
4071
  * Defensive path — the primary source is the webhook.
3770
4072
  */
3771
- protected fallbackAgentAddress(conversationId: ConversationId, participants: ConversationParticipant[], channel: ParticipantAddressType): ConversationAddress;
4073
+ protected fallbackAgentAddress(session: ConversationSession, participants: ConversationParticipant[], channel: ParticipantAddressType): ConversationAddress;
4074
+ /**
4075
+ * The first of TAC's configured addresses on this channel that a participant
4076
+ * holds, if any.
4077
+ */
4078
+ protected ownedAgentAddress(participants: ConversationParticipant[], channel: ParticipantAddressType): string | undefined;
3772
4079
  /**
3773
4080
  * Find or mint a Conversation Memory profile for a customer being promoted from UNKNOWN.
3774
4081
  *
@@ -3807,8 +4114,14 @@ declare abstract class MessagingChannel extends BaseChannel {
3807
4114
  /**
3808
4115
  * Shared outbound conversation initiation for messaging channels (SMS/RCS/Chat/WhatsApp).
3809
4116
  *
3810
- * Handles the full flow: create conversation → find participants → start
3811
- * session → send initial message → error cleanup.
4117
+ * Handles the full flow: create conversation → find participants → build
4118
+ * session → send initial message → error cleanup. The session isn't kept by
4119
+ * the channel; it is returned to the caller.
4120
+ *
4121
+ * `metadata` entries with string values that fit Conversation Orchestrator's
4122
+ * limits are stored on the conversation (at creation; merged with a `PATCH`
4123
+ * when an existing conversation is reused), so `conversationMetadata()` can
4124
+ * read them on any replica. The rest stay on the returned session only.
3812
4125
  */
3813
4126
  protected initiateOutboundMessagingConversation(params: {
3814
4127
  channel: 'SMS' | 'CHAT' | 'RCS' | 'WHATSAPP';
@@ -3828,19 +4141,10 @@ declare abstract class MessagingChannel extends BaseChannel {
3828
4141
  * Automatically retrieves user memory and manages conversation lifecycle.
3829
4142
  */
3830
4143
  declare class SMSChannel extends MessagingChannel {
4144
+ constructor(tac: TAC, config?: MessagingChannelConfig);
3831
4145
  get channelType(): ChannelType;
3832
4146
  protected isDefaultAgentAddress(authorAddress: string): boolean;
3833
4147
  protected getAgentAddress(_conversationId: ConversationId): ConversationAddress;
3834
- /**
3835
- * Send SMS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
3836
- *
3837
- * Reads the agent and customer participant ids stashed on the session by
3838
- * inbound reconciliation or outbound initiation. Missing ids are a misuse —
3839
- * `sendResponse` is only expected to be called after an inbound webhook
3840
- * (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
3841
- * both of which populate the session.
3842
- */
3843
- sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
3844
4148
  /**
3845
4149
  * Initiate an outbound SMS conversation
3846
4150
  *
@@ -3865,16 +4169,6 @@ declare class RCSChannel extends MessagingChannel {
3865
4169
  get channelType(): ChannelType;
3866
4170
  protected isDefaultAgentAddress(authorAddress: string): boolean;
3867
4171
  protected getAgentAddress(_conversationId: ConversationId): ConversationAddress;
3868
- /**
3869
- * Send RCS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
3870
- *
3871
- * Reads the agent and customer participant ids stashed on the session by
3872
- * inbound reconciliation or outbound initiation. Missing ids are a misuse —
3873
- * `sendResponse` is only expected to be called after an inbound webhook
3874
- * (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
3875
- * both of which populate the session.
3876
- */
3877
- sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
3878
4172
  /**
3879
4173
  * Initiate an outbound RCS conversation
3880
4174
  *
@@ -3900,16 +4194,6 @@ declare class WhatsAppChannel extends MessagingChannel {
3900
4194
  get channelType(): ChannelType;
3901
4195
  protected isDefaultAgentAddress(authorAddress: string): boolean;
3902
4196
  protected getAgentAddress(_conversationId: ConversationId): ConversationAddress;
3903
- /**
3904
- * Send WhatsApp response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
3905
- *
3906
- * Reads the agent and customer participant ids stashed on the session by
3907
- * inbound reconciliation or outbound initiation. Missing ids are a misuse —
3908
- * `sendResponse` is only expected to be called after an inbound webhook
3909
- * (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
3910
- * both of which populate the session.
3911
- */
3912
- sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
3913
4197
  /**
3914
4198
  * Initiate an outbound WhatsApp conversation
3915
4199
  *
@@ -3955,17 +4239,18 @@ declare class ChatChannel extends MessagingChannel {
3955
4239
  constructor(tac: TAC, config?: ChatChannelConfig);
3956
4240
  get channelType(): ChannelType;
3957
4241
  protected isDefaultAgentAddress(authorAddress: string): boolean;
3958
- protected getAgentAddress(conversationId: ConversationId): ConversationAddress;
4242
+ protected getAgentAddress(_conversationId: ConversationId): ConversationAddress;
4243
+ protected agentAddressFor(session: ConversationSession): ConversationAddress;
4244
+ private chatAddress;
3959
4245
  /**
3960
- * Send chat response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
4246
+ * Rebuild the session, recovering `channelId` from the participants.
3961
4247
  *
3962
- * Reads the agent and customer participant ids stashed on the session by
3963
- * inbound reconciliation or outbound initiation. Missing ids are a misuse —
3964
- * `sendResponse` is only expected to be called after an inbound webhook
3965
- * (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
3966
- * both of which populate the session.
4248
+ * A session rebuilt from a bare conversation id has no webhook to take
4249
+ * `channelId` from, so it's read off the customer's or agent's CHAT address
4250
+ * instead, where Conversation Orchestrator records it.
3967
4251
  */
3968
- sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
4252
+ protected sessionFromParticipants(conversationId: string, participants: ConversationParticipant[]): ConversationSession | null;
4253
+ protected buildChannelSettings(session: ConversationSession): ActionChannelSettings;
3969
4254
  /**
3970
4255
  * Initiate an outbound chat conversation
3971
4256
  *
@@ -4007,6 +4292,18 @@ declare class VoiceProvider {
4007
4292
  * `VoiceChannel` reports its `ChannelType`.
4008
4293
  */
4009
4294
  get channelName(): string;
4295
+ /**
4296
+ * Whether a Conversation Orchestrator `CLOSED` webhook will end this
4297
+ * provider's conversations.
4298
+ *
4299
+ * Decides who owns `onConversationEnded`. `false` (the default): no CO
4300
+ * conversation exists, so `VoiceChannel` fires it itself at teardown.
4301
+ * `true`: only `onCallEnded` fires at teardown and the CLOSED webhook — which
4302
+ * may reach another instance — does the rest.
4303
+ *
4304
+ * @internal
4305
+ */
4306
+ get conversationClosedByOrchestrator(): boolean;
4010
4307
  /**
4011
4308
  * Build the response for an inbound call. Default: not supported.
4012
4309
  *
@@ -4239,6 +4536,14 @@ declare class ConversationRelayProvider extends VoiceProvider {
4239
4536
  private readonly MAX_INITIALIZATION_RETRIES;
4240
4537
  constructor(channel: VoiceChannel, tacConfig: TACConfig, config: ConversationRelayProviderConfig);
4241
4538
  get channelName(): string;
4539
+ /**
4540
+ * ConversationRelay asks Conversation Orchestrator to create the
4541
+ * conversation whenever TAC is orchestrated; in relay-only mode there is no
4542
+ * CO conversation and nothing will ever close it for us.
4543
+ *
4544
+ * @internal
4545
+ */
4546
+ get conversationClosedByOrchestrator(): boolean;
4242
4547
  /**
4243
4548
  * Get active WebSocket connection for a conversation
4244
4549
  */
@@ -4267,9 +4572,15 @@ declare class ConversationRelayProvider extends VoiceProvider {
4267
4572
  */
4268
4573
  private handleDtmfMessage;
4269
4574
  /**
4270
- * Handle WebSocket disconnection. In orchestrated mode the conversation stays
4271
- * tracked until the CLOSED webhook (so a follow-up call can reuse it); in
4272
- * voice-only mode there is no such webhook, so it ends here.
4575
+ * Clean up WebSocket and session resources when the connection closes.
4576
+ *
4577
+ * Runs unconditionally — the call is over in every mode once its socket is
4578
+ * gone, so nothing local is kept waiting for a Conversation Orchestrator
4579
+ * webhook that may land on a different instance. Releasing the session fires
4580
+ * `onCallEnded` here and defers `onConversationEnded` to CO's CLOSED webhook
4581
+ * when orchestrated.
4582
+ *
4583
+ * Idempotent: a second run for a call already torn down does nothing.
4273
4584
  */
4274
4585
  private handleWebSocketDisconnect;
4275
4586
  /**
@@ -4488,6 +4799,11 @@ type CallStatusHandler = (event: CallStatusEvent) => Promise<void> | void;
4488
4799
  type AmdHandler = (event: AmdEvent) => Promise<void> | void;
4489
4800
  /** Handler for Twilio `recordingStatusCallback` webhooks. */
4490
4801
  type RecordingHandler = (event: RecordingEvent) => Promise<void> | void;
4802
+ /**
4803
+ * Handler for a call's WebSocket teardown. Receives the live session just
4804
+ * before it is discarded — see {@link VoiceChannel.onCallEnded}.
4805
+ */
4806
+ type CallEndedHandler = (session: ConversationSession) => Promise<void> | void;
4491
4807
  /** One ConversationRelay keypress, as delivered to a {@link DtmfHandler}. */
4492
4808
  interface DtmfEvent {
4493
4809
  /**
@@ -4555,6 +4871,17 @@ declare class VoiceChannel extends BaseChannel {
4555
4871
  private onCallStatusHandler;
4556
4872
  private onAmdHandler;
4557
4873
  private onRecordingHandler;
4874
+ private onCallEndedHandler;
4875
+ /**
4876
+ * Live sessions by conversation id. Instance-local by design: a call is
4877
+ * pinned to the process holding its WebSocket.
4878
+ */
4879
+ private readonly activeConversations;
4880
+ /**
4881
+ * Live calls whose conversation CO already closed mid-call: their
4882
+ * `onConversationEnded` has fired, so teardown doesn't fire it again.
4883
+ */
4884
+ private readonly closedWhileLive;
4558
4885
  /**
4559
4886
  * @param tac - The owning {@link TAC} instance.
4560
4887
  * @param options - Either a {@link VoiceProviderConfig} selecting the media
@@ -4685,6 +5012,28 @@ declare class VoiceChannel extends BaseChannel {
4685
5012
  * ```
4686
5013
  */
4687
5014
  onDtmf(callback: DtmfHandler): void;
5015
+ /**
5016
+ * Register a handler for a call's WebSocket teardown.
5017
+ *
5018
+ * Fires once per call, always, on the instance that held the call. It
5019
+ * receives the live session just before it is discarded, so it is the only
5020
+ * place late-call in-memory state — the transcript, `callSid`, anything you
5021
+ * put on `metadata` — is still reachable.
5022
+ *
5023
+ * Not the same as `onConversationEnded` (fires when the *conversation*
5024
+ * closes, on any instance; on an orchestrated call, from a session rebuilt
5025
+ * from Conversation Orchestrator, identity only) or {@link onCallStatus} (a
5026
+ * Twilio Calls-API webhook, no session). Handler errors are logged and
5027
+ * swallowed.
5028
+ *
5029
+ * @example
5030
+ * ```typescript
5031
+ * voiceChannel.onCallEnded(async session => {
5032
+ * await archive(session.callSid, session.metadata.transcript ?? []);
5033
+ * });
5034
+ * ```
5035
+ */
5036
+ onCallEnded(callback: CallEndedHandler): void;
4688
5037
  /**
4689
5038
  * The registered call-event handlers, for a `VoiceProvider` deciding which
4690
5039
  * callback URLs to derive. A provider is not a subclass of `VoiceChannel`,
@@ -4745,19 +5094,18 @@ declare class VoiceChannel extends BaseChannel {
4745
5094
  */
4746
5095
  getInboundCallTwimlHandler(): InboundCallTwimlHandler | undefined;
4747
5096
  /**
4748
- * Start tracking a conversation session. Forwards to
4749
- * `BaseChannel.startConversation`.
5097
+ * Start tracking a call's session. Forwards to {@link startConversation}.
4750
5098
  *
4751
5099
  * @internal
4752
5100
  */
4753
5101
  startConversationInternal(conversationId: ConversationId, profileId?: ProfileId): ConversationSession;
4754
5102
  /**
4755
- * End a tracked conversation session. Forwards to
4756
- * `BaseChannel.endConversation`.
5103
+ * Release a finished call's session and fire the end-of-call hooks.
5104
+ * Forwards to {@link releaseSession}.
4757
5105
  *
4758
5106
  * @internal
4759
5107
  */
4760
- endConversationInternal(conversationId: ConversationId): Promise<void>;
5108
+ releaseSessionInternal(conversationId: ConversationId): Promise<ConversationSession | undefined>;
4761
5109
  /**
4762
5110
  * Retrieve memory when `memoryMode` calls for it. Forwards to
4763
5111
  * `BaseChannel.retrieveMemoryIfEnabled`.
@@ -4779,13 +5127,28 @@ declare class VoiceChannel extends BaseChannel {
4779
5127
  */
4780
5128
  on(event: string, callback: (...args: any[]) => void): void;
4781
5129
  /**
4782
- * Process conversation webhooks for cleanup.
4783
- *
4784
- * Voice channel processes CONVERSATION_UPDATED events:
4785
- * - CLOSED status: Clean up local session state
4786
- *
4787
- * Note: Conversation tracking uses instance-local memory. In multi-instance
4788
- * deployments, webhooks may route to a different instance, preventing cleanup.
5130
+ * Process Conversation Orchestrator webhooks.
5131
+ *
5132
+ * Voice channel processes these events:
5133
+ *
5134
+ * - **PARTICIPANT_ADDED**: report "Conversation Started" when the customer
5135
+ * joins on voice (orchestrated ConversationRelay only).
5136
+ * - **CLOSED** (CONVERSATION_UPDATED): fire `onConversationEnded`. The call's
5137
+ * session is normally already released (the WebSocket closed when the
5138
+ * caller hung up), so this rebuilds it from Conversation Orchestrator —
5139
+ * which is also what makes the hook fire on whichever instance received the
5140
+ * webhook rather than only on the one that held the call. If this instance
5141
+ * still holds the call's session (the call is live), the hook fires now
5142
+ * instead, with a snapshot of that live session, and the session stays
5143
+ * until the call's own teardown — which still fires {@link onCallEnded}. A
5144
+ * single call can then produce a second `onConversationEnded`, under a
5145
+ * different conversation id, when Conversation Orchestrator later closes
5146
+ * the conversation it started for the call's remaining traffic. It also
5147
+ * reports "Conversation Ended", with CO's duration, from the payload alone
5148
+ * and once across channels; only a registered handler costs the lookup.
5149
+ * - **INACTIVE**: invalidate cached memory, if this instance holds the
5150
+ * session. A call is pinned to one instance for its lifetime, so an
5151
+ * INACTIVE landing elsewhere has no cache to clear and is ignored.
4789
5152
  *
4790
5153
  * @param payload - Raw webhook event data from Twilio
4791
5154
  * @param idempotencyToken - Optional Twilio idempotency token from request headers
@@ -4795,6 +5158,91 @@ declare class VoiceChannel extends BaseChannel {
4795
5158
  * Handle conversation updated event
4796
5159
  */
4797
5160
  private handleConversationUpdated;
5161
+ /**
5162
+ * Get the live session this instance holds for a conversation.
5163
+ */
5164
+ getConversationSession(conversationId: ConversationId): ConversationSession | undefined;
5165
+ /**
5166
+ * Whether this instance holds a live session for a conversation.
5167
+ */
5168
+ isConversationActive(conversationId: ConversationId): boolean;
5169
+ /**
5170
+ * Track a new session for a call, or return the existing one.
5171
+ */
5172
+ protected startConversation(conversationId: ConversationId, profileId?: ProfileId): ConversationSession;
5173
+ /**
5174
+ * Free a finished call's session and fire the end-of-call hooks.
5175
+ *
5176
+ * Called from every teardown path and idempotent, so a second call is a
5177
+ * no-op returning `undefined`. Always fires {@link onCallEnded}. Also fires
5178
+ * `onConversationEnded` unless a Conversation Orchestrator CLOSED webhook will
5179
+ * do that later (see `VoiceProvider.conversationClosedByOrchestrator`).
5180
+ * Nothing is kept for that CLOSED: it gets a session rebuilt from
5181
+ * Conversation Orchestrator.
5182
+ */
5183
+ protected releaseSession(conversationId: ConversationId): Promise<ConversationSession | undefined>;
5184
+ /**
5185
+ * Fire `onConversationEnded` for a CLOSED webhook.
5186
+ *
5187
+ * The call has normally ended by now (the socket closed when the caller hung
5188
+ * up, or {@link endCall} hung it up), and its session went with it. The hook
5189
+ * gets a session rebuilt from Conversation Orchestrator, identity only,
5190
+ * which is what lets it fire on whichever instance received the webhook. The
5191
+ * call's live state (transcript, `metadata`) reached {@link onCallEnded} at
5192
+ * teardown.
5193
+ *
5194
+ * If this instance still holds the session, the call is live: CO closed the
5195
+ * conversation mid-call (a closed timeout during a long hold, or the app
5196
+ * closing it). The hook fires now, from a snapshot, and the session stays for
5197
+ * the call's own teardown to release — which is what keeps `onCallEnded`
5198
+ * firing and the rest of the call working. The call then carries on under
5199
+ * the closed conversation's id; CO starts a new conversation for its later
5200
+ * traffic, whose own CLOSED arrives here later and takes the rebuild path.
5201
+ *
5202
+ * The hook is at-least-once: a duplicate CLOSED delivery that isn't deduped
5203
+ * by its idempotency token fires it again, same as `onMessageReady`.
5204
+ */
5205
+ private handleConversationClosed;
5206
+ /**
5207
+ * A copy of a live call's session that shares no mutable state with it.
5208
+ *
5209
+ * `onConversationEnded` may keep or edit what it's given while the call
5210
+ * carries on, so the callback-visible data — `metadata` and the nested
5211
+ * objects — is cloned. A value that can't be cloned (an app-owned handle, a
5212
+ * class instance whose methods a clone would lose) is shared rather than
5213
+ * failing the hook.
5214
+ */
5215
+ private detachedSnapshot;
5216
+ /**
5217
+ * The participant representing TAC's agent at `address` on voice: one that
5218
+ * owns the address AND has an agent type. A HUMAN_AGENT at that address is
5219
+ * someone else.
5220
+ */
5221
+ private static findVoiceAgent;
5222
+ /**
5223
+ * Reconstruct a session from Conversation Orchestrator.
5224
+ *
5225
+ * Carries identity only — conversation id, `callSid`, profile, both
5226
+ * participants. Live in-memory state (transcript, metadata) isn't available
5227
+ * here; it reaches {@link onCallEnded}. `callSid` defaults to a VOICE
5228
+ * participant address's `channelId` — the customer's if present, else the
5229
+ * agent's, else any other participant's. Returns `undefined` if no
5230
+ * participant is on the voice channel, which is how another channel's CLOSED
5231
+ * is filtered out.
5232
+ *
5233
+ * `shared` (the CLOSED path) shares the participant lookup with the other
5234
+ * channels handling the same webhook; other callers need fresh participants.
5235
+ */
5236
+ private rebuildSession;
5237
+ /**
5238
+ * This channel's participants are recorded by Conversation Orchestrator as
5239
+ * VOICE, whatever the provider's transport label.
5240
+ *
5241
+ * @internal
5242
+ */
5243
+ protected get coChannel(): string;
5244
+ /** @internal */
5245
+ protected isOwnCoAddress(address: string): boolean;
4798
5246
  /**
4799
5247
  * Get active WebSocket connection for a conversation
4800
5248
  */
@@ -4810,7 +5258,7 @@ declare class VoiceChannel extends BaseChannel {
4810
5258
  /**
4811
5259
  * Send voice response via WebSocket
4812
5260
  */
4813
- sendResponse(conversationId: ConversationId, message: string, metadata?: Record<string, unknown>): Promise<void>;
5261
+ sendResponse(conversationIdOrSession: ConversationId | ConversationSession, message: string, metadata?: Record<string, unknown>): Promise<void>;
4814
5262
  /**
4815
5263
  * Send a streaming voice response through the active provider's transport,
4816
5264
  * token by token. Delegates to the active provider — see
@@ -4948,6 +5396,11 @@ declare class VoiceChannel extends BaseChannel {
4948
5396
  * hangs up while AMD is still resolving), and handlers shouldn't have to
4949
5397
  * guard against it.
4950
5398
  *
5399
+ * The session is released as on any hangup: {@link onCallEnded} fires now.
5400
+ * On an orchestrated call `onConversationEnded` fires later, when
5401
+ * Conversation Orchestrator's CLOSED webhook arrives; otherwise it fires now
5402
+ * too.
5403
+ *
4951
5404
  * @param callSid - Twilio Call SID (from a call event, the outbound result, or
4952
5405
  * `ConversationSession.callSid`).
4953
5406
  * @returns True if Twilio accepted the hangup, false if it failed (logged).
@@ -4967,10 +5420,10 @@ declare class VoiceChannel extends BaseChannel {
4967
5420
  * exist before the caller speaks — including before `onAmd` fires. Treat it
4968
5421
  * as racy and hang up with {@link endCall}, which needs no session.
4969
5422
  *
4970
- * At the other end, orchestrator mode keeps the session until Conversation
4971
- * Orchestrator's CLOSED webhook, so it outlives the call and `onCallStatus` /
4972
- * `onRecording` do resolve. Relay-only mode tears down on the
4973
- * ConversationRelay callback instead, which races them.
5423
+ * At the other end the session is released as soon as the call's WebSocket
5424
+ * closes, in every mode — so out-of-band events that arrive after the hangup
5425
+ * (`onCallStatus`, `onRecording`) generally find nothing here. Read
5426
+ * late-call state from the session {@link onCallEnded} hands you instead.
4974
5427
  *
4975
5428
  * @example
4976
5429
  * ```typescript
@@ -4985,10 +5438,59 @@ declare class VoiceChannel extends BaseChannel {
4985
5438
  * @param callSid - Twilio Call SID, e.g. from
4986
5439
  * `InitiateVoiceConversationResult.callSid` or a call event.
4987
5440
  * @returns The session, or `undefined` — not created yet, the call ended, or
4988
- * it landed on another instance (see the horizontal-scaling note in
4989
- * CLAUDE.md).
5441
+ * it landed on another instance. For the last case,
5442
+ * {@link resolveConversationSessionByCallSid} falls back to Conversation
5443
+ * Orchestrator.
4990
5444
  */
4991
5445
  getConversationSessionByCallSid(callSid: string): ConversationSession | undefined;
5446
+ /**
5447
+ * Look up a call's session on any instance, falling back to Conversation
5448
+ * Orchestrator when this instance doesn't hold the call.
5449
+ *
5450
+ * Out-of-band call events (`onCallStatus`, `onAmd`, `onRecording`) carry
5451
+ * only a CallSid and, without `TACConfig.instancePublicDomain`, can reach any
5452
+ * replica. This returns the live session when the call is held here — same
5453
+ * as {@link getConversationSessionByCallSid} — and otherwise, for a
5454
+ * ConversationRelay call in orchestrator mode, a session rebuilt from
5455
+ * Conversation Orchestrator.
5456
+ *
5457
+ * A rebuilt session carries identity only (conversation id, `callSid`,
5458
+ * profile, both participants), is not tracked, and can't be used with
5459
+ * {@link sendResponse}: the call's WebSocket is on another instance. If CO
5460
+ * holds several conversations for the call (it starts a new one when a
5461
+ * conversation closes mid-call), the active one wins, else the newest — this
5462
+ * rule applies only to the rebuild path. On the instance holding the call,
5463
+ * the live session is returned as-is, so after a mid-call close it still
5464
+ * carries the closed conversation's id while other instances return the new
5465
+ * one; correlate by `callSid` if you need a stable key.
5466
+ *
5467
+ * To tell live from rebuilt, check
5468
+ * `voiceChannel.getWebsocket(session.conversationId) !== null` — true only
5469
+ * for a session live on this instance. A rebuilt session's `startedAt` is
5470
+ * the rebuild time, not the call's, and its `metadata` is always empty.
5471
+ *
5472
+ * Cost: on a local miss this makes up to two Conversation Orchestrator
5473
+ * requests (list conversations, then participants). Prefer
5474
+ * {@link getConversationSessionByCallSid} on hot paths, or when
5475
+ * `TACConfig.instancePublicDomain` already routes call events to the
5476
+ * instance holding the call.
5477
+ *
5478
+ * @example
5479
+ * ```typescript
5480
+ * voiceChannel.onCallStatus(async event => {
5481
+ * const session = await voiceChannel.resolveConversationSessionByCallSid(event.callSid);
5482
+ * if (session) {
5483
+ * auditLog(session.conversationId, session.profileId, event.callStatus);
5484
+ * }
5485
+ * });
5486
+ * ```
5487
+ *
5488
+ * @param callSid - Twilio Call SID, e.g. from a call event.
5489
+ * @returns The live or rebuilt session, or `undefined` — relay-only or Media
5490
+ * Streams mode (no CO conversation behind the call), CO knows no
5491
+ * conversation for it, or the lookup failed (logged).
5492
+ */
5493
+ resolveConversationSessionByCallSid(callSid: string): Promise<ConversationSession | undefined>;
4992
5494
  /**
4993
5495
  * Narrow `provider` to the ConversationRelay implementation for the
4994
5496
  * ConversationRelay-only forwarders on this channel.
@@ -5087,16 +5589,19 @@ declare abstract class TwiMLBuilderBase<TChannelConfig = unknown> {
5087
5589
  */
5088
5590
  protected missingWebsocketUrlError(caller: string): Error;
5089
5591
  /**
5090
- * The WebSocket URL derived from `TACConfig.voicePublicDomain` +
5091
- * `TACConfig.voiceWebsocketPath`, or undefined when `voicePublicDomain` is
5092
- * unset.
5592
+ * The WebSocket URL derived from `TACConfig.voiceCallbackDomain` +
5593
+ * `TACConfig.voiceWebsocketPath`, or undefined when no public domain is set.
5594
+ *
5595
+ * Uses `voiceCallbackDomain`, so a deployment that sets
5596
+ * `instancePublicDomain` pins the call to this process from its very first
5597
+ * connection.
5093
5598
  */
5094
5599
  protected defaultWebsocketUrl(): string | undefined;
5095
5600
  /**
5096
5601
  * Resolve the default `<Connect action=...>` cleanup URL from
5097
- * `TACConfig.voicePublicDomain` + `TACConfig.voiceActionPath`.
5602
+ * `TACConfig.voiceCallbackDomain` + `TACConfig.voiceActionPath`.
5098
5603
  *
5099
- * Returns undefined if `voicePublicDomain` isn't set; that's fine because
5604
+ * Returns undefined if no public domain is set; that's fine because
5100
5605
  * actionUrl has higher-priority layers (customizer, twimlOptions, Studio
5101
5606
  * handoff) above this fallback.
5102
5607
  */
@@ -5162,7 +5667,7 @@ declare class TwiMLBuilderMediaStreams extends TwiMLBuilderBase<MediaStreamsTwiM
5162
5667
  * 2. the provider config's `defaultTwimlOptions` — channel-wide defaults
5163
5668
  * 3. `host` — per-call transport facts supplied by the host
5164
5669
  * 4. TAC defaults: the WebSocket URL derived from
5165
- * `TACConfig.voicePublicDomain` + `voiceWebsocketPath`
5670
+ * `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
5166
5671
  *
5167
5672
  * @param caller - Name of the calling method, used in the "no WebSocket URL"
5168
5673
  * error so it points at the API the developer actually called.
@@ -5177,8 +5682,10 @@ declare class TwiMLBuilderMediaStreams extends TwiMLBuilderBase<MediaStreamsTwiM
5177
5682
  *
5178
5683
  * `customParameters` replaces wholesale when set at a higher-priority layer —
5179
5684
  * there's no per-key merging.
5685
+ *
5686
+ * @internal
5180
5687
  */
5181
- protected buildTwimlOptions(host: VoiceTwiMLOptionsMediaStreams | undefined, perCall: VoiceTwiMLOptionsMediaStreams | undefined): VoiceTwiMLOptionsMediaStreams;
5688
+ buildTwimlOptions(host: VoiceTwiMLOptionsMediaStreams | undefined, perCall: VoiceTwiMLOptionsMediaStreams | undefined): VoiceTwiMLOptionsMediaStreams;
5182
5689
  }
5183
5690
 
5184
5691
  /** Options accepted by {@link MediaStreamsProviderConfig}. */
@@ -5315,13 +5822,23 @@ interface SendMessageResult {
5315
5822
  }
5316
5823
  /**
5317
5824
  * Create send message tool
5825
+ *
5826
+ * **Pass the session, not the id.** Hand in the `ConversationSession` that
5827
+ * `onMessageReady` gave you and every send reuses it as-is. A bare id still
5828
+ * works, but messaging channels keep no sessions, so each send spends a
5829
+ * `listParticipants` call rebuilding one — and on chat, where the customer
5830
+ * stays `UNKNOWN`, that rebuild resolves no recipient and the send fails.
5831
+ *
5832
+ * @param channel - Channel to send through.
5833
+ * @param conversationIdOrSession - The `ConversationSession` to reply within
5834
+ * (preferred), or the conversation id.
5318
5835
  */
5319
- declare function createSendMessageTool(channel: BaseChannel, conversationId: ConversationId): TACTool<SendMessageParams, SendMessageResult>;
5836
+ declare function createSendMessageTool(channel: BaseChannel, conversationIdOrSession: ConversationId | ConversationSession): TACTool<SendMessageParams, SendMessageResult>;
5320
5837
  /**
5321
5838
  * Create factory function for messaging tools
5322
5839
  */
5323
5840
  declare function createMessagingTools(): {
5324
- forConversation: (channel: BaseChannel, conversationId: ConversationId) => TACTool<SendMessageParams, SendMessageResult>;
5841
+ forConversation: (channel: BaseChannel, conversationIdOrSession: ConversationId | ConversationSession) => TACTool<SendMessageParams, SendMessageResult>;
5325
5842
  };
5326
5843
 
5327
5844
  /**
@@ -5555,6 +6072,41 @@ declare class MediaStreamsOpenAICallState {
5555
6072
  modelReady: Promise<boolean> | null;
5556
6073
  }
5557
6074
 
6075
+ /**
6076
+ * A string-keyed map whose entries expire and whose size is bounded.
6077
+ *
6078
+ * For state one Twilio request creates and a later one for the same call
6079
+ * consumes. Normally deleted within seconds — but a call that is never
6080
+ * answered, or whose second request lands on another instance, leaves an entry
6081
+ * nobody will collect. The TTL and cap make that leak impossible rather than
6082
+ * unlikely. Expiry is lazy: no timers are armed, so nothing keeps the process
6083
+ * alive.
6084
+ *
6085
+ * @internal
6086
+ */
6087
+ declare class ExpiringMap<V> {
6088
+ private readonly ttlMs;
6089
+ private readonly maxEntries;
6090
+ private readonly entries;
6091
+ constructor(options?: {
6092
+ ttlMs?: number;
6093
+ maxEntries?: number;
6094
+ });
6095
+ /** Current time in ms; overridable in tests. */
6096
+ protected now(): number;
6097
+ /** Drop expired entries, then the oldest survivors if still over capacity. */
6098
+ private purge;
6099
+ set(key: string, value: V): this;
6100
+ get(key: string): V | undefined;
6101
+ has(key: string): boolean;
6102
+ /** Remove `key` and return its live value, if any. */
6103
+ take(key: string): V | undefined;
6104
+ delete(key: string): boolean;
6105
+ clear(): void;
6106
+ /** Number of live entries. */
6107
+ get size(): number;
6108
+ }
6109
+
5558
6110
  /**
5559
6111
  * Identifies this SDK to OpenAI on every WebSocket connection, per OpenAI's
5560
6112
  * requested User-Agent pattern: [Company/Library name]/[Language] [Version].
@@ -5590,21 +6142,16 @@ declare abstract class MediaStreamsOpenAIProvider<TCallState extends MediaStream
5590
6142
  protected readonly tacConfig: TACConfig;
5591
6143
  protected readonly twimlBuilder: TwiMLBuilderMediaStreams;
5592
6144
  /**
5593
- * Session config overrides awaiting the call they belong to.
6145
+ * Per-call session config overrides, minted by one Twilio request and
6146
+ * consumed when the call's WebSocket connects.
5594
6147
  *
5595
- * Inbound entries are keyed by call SID (known when the TwiML webhook is
5596
- * answered); a subclass keys its outbound entries by whatever token it round
5597
- * trips through the stream's custom parameters.
5598
- */
5599
- protected readonly pendingSessionConfigs: Map<string, Record<string, unknown>>;
5600
- /**
5601
- * Expiry timers for the inbound {@link pendingSessionConfigs} entries, keyed
5602
- * by the same call SID. Each fires once to purge a stash whose Media Stream
5603
- * never connected; a normal connect cancels it in the subclass's
5604
- * `registerCall`. Outbound entries are keyed by token instead and are not
5605
- * tracked here.
6148
+ * Keyed by a token that rides the TwiML's custom parameters, rekeyed to the
6149
+ * call's conversation id on connect ({@link claimSessionConfig}). Set in
6150
+ * `handleIncomingCall` or `initiateOutboundConversation`, consumed when the
6151
+ * model connects. Bounded and expiring, so a call that never connects
6152
+ * doesn't leave its entry here forever.
5606
6153
  */
5607
- private readonly pendingInboundExpiries;
6154
+ protected readonly pendingSessionConfigs: ExpiringMap<Record<string, unknown>>;
5608
6155
  constructor(channel: VoiceChannel, tacConfig: TACConfig, config: MediaStreamsOpenAIProviderConfig);
5609
6156
  /** The Twilio-facing WebSocket for a conversation, if one is tracked. */
5610
6157
  getWebSocket(conversationId: ConversationId): WebSocket | null;
@@ -5624,13 +6171,14 @@ declare abstract class MediaStreamsOpenAIProvider<TCallState extends MediaStream
5624
6171
  * The transcript captured so far for an in-progress call.
5625
6172
  *
5626
6173
  * It lives on `ConversationSession.metadata.transcript`, so once the call
5627
- * ends and the session is dropped it is no longer reachable here — read it
5628
- * from the session an `onConversationEnded` handler receives instead.
6174
+ * ends (and the session is released at WebSocket teardown) it is no longer
6175
+ * reachable here — read it from the session a `VoiceChannel.onCallEnded`
6176
+ * handler receives instead.
5629
6177
  */
5630
6178
  getTranscript(conversationId: ConversationId): Record<string, string>[];
5631
6179
  /**
5632
- * The session config stashed for `key` — a call SID for inbound calls, a
5633
- * token for outbound ones.
6180
+ * The session config stashed for `key` — a session-config token before the
6181
+ * call connects, its conversation id after.
5634
6182
  *
5635
6183
  * @internal
5636
6184
  */
@@ -5642,24 +6190,35 @@ declare abstract class MediaStreamsOpenAIProvider<TCallState extends MediaStream
5642
6190
  */
5643
6191
  pendingSessionConfigCount(): number;
5644
6192
  /**
5645
- * Start the clock on an inbound stash, so a call whose Media Stream never
5646
- * connects cannot strand its override in {@link pendingSessionConfigs} until
5647
- * shutdown.
6193
+ * Mint a fresh session-config token.
5648
6194
  *
5649
- * Unref'd: a two-minute timer must not be what keeps the process alive after
5650
- * the call it belongs to is long over. Re-arming replaces any prior timer for
5651
- * the same call SID, so a duplicate inbound webhook can't orphan one.
6195
+ * @internal
5652
6196
  */
5653
- private armInboundConfigExpiry;
6197
+ protected static newSessionConfigToken(): string;
5654
6198
  /**
5655
- * Stop the clock on an inbound stash, once the call it belongs to has
5656
- * connected and is about to consume the entry. A no-op for outbound calls,
5657
- * which key their stash by token and never arm one — the subclass calls this
5658
- * with the call SID for every `start`, inbound or not.
6199
+ * `perCall` with the session-config token added to the stream's custom
6200
+ * parameters.
6201
+ *
6202
+ * The builder replaces whole fields, so the token is added to the parameters
6203
+ * the call would otherwise get — from `perCall`, `defaultTwimlOptions` or
6204
+ * `host`, by the builder's precedence — rather than to `perCall`'s alone,
6205
+ * which would drop inherited ones.
5659
6206
  *
5660
6207
  * @internal
5661
6208
  */
5662
- protected cancelInboundConfigExpiry(callSid: string): void;
6209
+ protected withSessionConfigToken(host: VoiceTwiMLOptionsMediaStreams | undefined, perCall: VoiceTwiMLOptionsMediaStreams | undefined, token: string): VoiceTwiMLOptionsMediaStreams;
6210
+ /**
6211
+ * Move the session config stashed under `token` to this call's id.
6212
+ *
6213
+ * A token this instance doesn't hold means the config was stashed on another
6214
+ * instance — the TwiML webhook or `initiateOutboundConversation` ran
6215
+ * somewhere other than where the stream connected — or it expired. The call
6216
+ * then falls back to `defaultSessionConfig`, so this warns: with multiple
6217
+ * instances, per-call session configs need `TACConfig.instancePublicDomain`.
6218
+ *
6219
+ * @internal
6220
+ */
6221
+ protected claimSessionConfig(token: string | undefined, conversationId: ConversationId): void;
5663
6222
  /**
5664
6223
  * The executable tool the model would run for `name`, if the config supplied
5665
6224
  * one.
@@ -5679,12 +6238,14 @@ declare abstract class MediaStreamsOpenAIProvider<TCallState extends MediaStream
5679
6238
  * 3. `options.hostTwimlOptions` — per-call transport facts supplied by the
5680
6239
  * host
5681
6240
  * 4. TAC defaults: the WebSocket URL derived from
5682
- * `TACConfig.voicePublicDomain` + `voiceWebsocketPath`
6241
+ * `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
5683
6242
  *
5684
6243
  * Also runs `MediaStreamsOpenAIProviderConfig.onInboundCallSessionConfig`, if
5685
- * set, and stashes its result for the call to pick up once it connects. The
5686
- * hook runs only after the TwiML builds, so a call that never connects
5687
- * leaves nothing stashed behind it.
6244
+ * set, and stashes its result for the call to pick up once it connects,
6245
+ * under a token carried on the stream's custom parameters — so the config is
6246
+ * found by the stream it belongs to rather than keyed to a call SID. The
6247
+ * stash is written only after the TwiML builds, so a webhook that fails
6248
+ * leaves nothing behind it.
5688
6249
  *
5689
6250
  * @param twimlRequest - Parsed Twilio webhook fields for the inbound call.
5690
6251
  * @param options - Additional per-call inputs.
@@ -6045,8 +6606,8 @@ declare class OpenAIRealtimeProvider extends MediaStreamsOpenAIProvider<CallStat
6045
6606
  */
6046
6607
  private handleFunctionCall;
6047
6608
  /**
6048
- * Drop this call's transport state, close the model socket, and end the
6049
- * session.
6609
+ * Drop this call's transport state and any stashed session config, close
6610
+ * the model socket, and release the session.
6050
6611
  *
6051
6612
  * Both legs can report the call ending, and the first one to arrive tears
6052
6613
  * down the other, so this runs at most once per call: a second invocation
@@ -6136,7 +6697,6 @@ declare class GPTLiveProvider extends MediaStreamsOpenAIProvider<CallState> {
6136
6697
  * rather than a second field that shadows it.
6137
6698
  */
6138
6699
  protected readonly config: GPTLiveProviderConfig;
6139
- private readonly pendingTokenExpiries;
6140
6700
  /** Calls whose teardown has begun but is still awaiting `session.closed`. */
6141
6701
  private readonly closingCalls;
6142
6702
  get channelName(): string;
@@ -6163,21 +6723,6 @@ declare class GPTLiveProvider extends MediaStreamsOpenAIProvider<CallState> {
6163
6723
  * `TACConfig.voicePublicDomain` is unset.
6164
6724
  */
6165
6725
  initiateOutboundConversation(options: InitiateVoiceConversationOptions | InitiateVoiceConversationOptionsGPTLive): Promise<InitiateVoiceConversationResult>;
6166
- /**
6167
- * Start the clock on a stashed token, so a call that never connects cannot
6168
- * strand its override in {@link pendingSessionConfigs} forever.
6169
- *
6170
- * Unref'd: a two-minute timer must not be what keeps the process alive after
6171
- * the call it belongs to is long over.
6172
- */
6173
- private armTokenExpiry;
6174
- /**
6175
- * Stop the clock on a token, once the call it belongs to has claimed it.
6176
- *
6177
- * Without this a two-minute timer outlives every call that connected
6178
- * normally, waiting to purge an entry that is already gone.
6179
- */
6180
- private cancelTokenExpiry;
6181
6726
  /**
6182
6727
  * Drive one Twilio Media Stream connection from `start` to disconnect.
6183
6728
  *
@@ -6254,10 +6799,6 @@ declare class GPTLiveProvider extends MediaStreamsOpenAIProvider<CallState> {
6254
6799
  /**
6255
6800
  * Drop this provider's transport state on channel shutdown, including the
6256
6801
  * bookkeeping it keeps beyond the base class's.
6257
- *
6258
- * The token expiry timers are unref'd and delete themselves, so nothing hangs
6259
- * without this — but a shut-down provider must not still be holding entries
6260
- * for calls that can no longer arrive.
6261
6802
  */
6262
6803
  shutdown(): void;
6263
6804
  /** Apply one parsed GPT-Live event to the call. */
@@ -6355,6 +6896,31 @@ declare class OperatorResultProcessor {
6355
6896
  private processSummaryEvent;
6356
6897
  }
6357
6898
 
6899
+ /**
6900
+ * The metadata stored on a conversation in Conversation Orchestrator.
6901
+ *
6902
+ * `session.metadata` is the session's own data, which another replica doesn't
6903
+ * see. This reads what's stored on the conversation itself — for example the
6904
+ * `metadata` passed to `initiateOutboundConversation` — so it works on
6905
+ * whichever replica handles the turn. It costs one Conversation Orchestrator
6906
+ * request, kept for the rest of this turn, unless the session already knows
6907
+ * it: the session `initiateOutboundConversation` returns holds what it wrote,
6908
+ * and a CLOSED webhook's session holds the payload's copy.
6909
+ *
6910
+ * Returns a copy, so editing it changes nothing. Returns `{}` when the
6911
+ * conversation has no metadata, the session didn't come from a channel, or the
6912
+ * lookup fails; a failed lookup is retried on the next call.
6913
+ *
6914
+ * @example
6915
+ * ```typescript
6916
+ * tac.onMessageReady(async ({ session }) => {
6917
+ * const metadata = await conversationMetadata(session);
6918
+ * const appointmentId = metadata.appointment_id;
6919
+ * });
6920
+ * ```
6921
+ */
6922
+ declare function conversationMetadata(session: ConversationSession): Promise<Record<string, string>>;
6923
+
6358
6924
  /**
6359
6925
  * Configuration options for adapter utilities like MemoryPromptBuilder.
6360
6926
  */
@@ -6609,4 +7175,4 @@ declare class TACServer {
6609
7175
  stop(): Promise<void>;
6610
7176
  }
6611
7177
 
6612
- export { type ActionChannelSettings, ActionChannelSettingsSchema, type ActionParticipantRef, ActionParticipantRefSchema, type ActionResponse, ActionResponseSchema, type ActionTextContent, ActionTextContentSchema, type AdapterOptions, type AmdEvent, AmdEventSchema, type AmdHandler, type AnthropicTool, AnthropicToolSchema, type AuthorInfo, AuthorInfoSchema, BaseChannel, type BaseChannelEvents, type BaseChannelOptions, BaseClient, type BuildStreamTwiMLInputs, type BuiltInToolName, BuiltInTools, CALL_EVENT_KINDS, type CallEventKind, CallEventKindSchema, type CallOptions, CallOptionsSchema, type CallStatusEvent, CallStatusEventSchema, type CallStatusHandler, type CaptureRule, CaptureRuleSchema, type ChannelSettings, ChannelSettingsSchema, type ChannelType, ChannelTypeSchema, ChatChannel, type ChatChannelConfig, type CintelParticipant, CintelParticipantSchema, type Communication, type CommunicationContent, CommunicationContentSchema, type CommunicationParticipant, CommunicationParticipantSchema, CommunicationSchema, type ConversationAddress, ConversationAddressSchema, ConversationClient, type ConversationConfiguration, ConversationConfigurationSchema, type ConversationEndedCallback, type ConversationGroupingType, ConversationGroupingTypeSchema, type ConversationId, type ConversationIntelligenceConfig, ConversationIntelligenceConfigSchema, type ConversationParticipant, ConversationParticipantSchema, type ConversationRelayAttributes, ConversationRelayAttributesSchema, type ConversationRelayCallbackPayload, ConversationRelayCallbackPayloadSchema, type ConversationRelayConfig, ConversationRelayConfigSchema, ConversationRelayProvider, ConversationRelayProviderConfig, type ConversationRelayProviderConfigOptions, type ConversationResponse, ConversationResponseSchema, type ConversationSession, ConversationSessionSchema, type ConversationSummaryItem, ConversationSummaryItemSchema, type ConversationWebhookPayload, type CreateConversationSummariesResponse, CreateConversationSummariesResponseSchema, type CreateObservationResponse, CreateObservationResponseSchema, type CreateObservationsRequest, CreateObservationsRequestSchema, type CustomParameters, CustomParametersSchema, type DtmfEvent, type DtmfHandler, type DtmfMessage, DtmfMessageSchema, EMPTY_MEMORY_RESPONSE, EnvironmentVariables, type ExecutionDetails, ExecutionDetailsSchema, GPTLiveProvider, GPTLiveProviderConfig, type GPTLiveProviderConfigOptions, GPT_LIVE_SESSION_ID_METADATA_KEY, type HandoffPayload, HandoffPayloadSchema, type HandoffResult, type InboundCallTwimlHandler, type InitiateChatConversationOptions, type InitiateConversationResult, type InitiateMessagingConversationOptions, InitiateMessagingConversationOptionsSchema, type InitiateVoiceConversationOptions, type InitiateVoiceConversationOptionsGPTLive, InitiateVoiceConversationOptionsGPTLiveSchema, type InitiateVoiceConversationOptionsOpenAIRealtime, InitiateVoiceConversationOptionsOpenAIRealtimeSchema, InitiateVoiceConversationOptionsSchema, type InitiateVoiceConversationResult, type IntelligenceConfiguration, IntelligenceConfigurationSchema, type InterruptCallback, type InterruptMessage, InterruptMessageSchema, type InterruptMode, InterruptModeSchema, type JSONSchema, JSONSchemaSchema, type KnowledgeBase, KnowledgeBaseSchema, type KnowledgeBaseStatus, KnowledgeBaseStatusSchema, type KnowledgeChunkResult, KnowledgeChunkResultSchema, KnowledgeClient, type KnowledgeSearchResponse, KnowledgeSearchResponseSchema, type LanguageAttributes, LanguageAttributesSchema, type LanguageConfig, LanguageConfigSchema, type ListCommunicationsResponse, ListCommunicationsResponseSchema, type ListConversationsResponse, ListConversationsResponseSchema, type ListParticipantsResponse, ListParticipantsResponseSchema, type Logger, MediaStreamsOpenAICallState, MediaStreamsOpenAIProvider, MediaStreamsOpenAIProviderConfig, type MediaStreamsOpenAIProviderConfigOptions, MediaStreamsProviderConfig, type MediaStreamsProviderConfigOptions, type MediaStreamsTwiMLBuilderConfig, type MemoryChannelType, MemoryChannelTypeSchema, MemoryClient, type MemoryCommunication, type MemoryCommunicationContent, MemoryCommunicationContentSchema, MemoryCommunicationSchema, type MemoryDeliveryStatus, MemoryDeliveryStatusSchema, type MemoryMode, MemoryModeSchema, type MemoryParticipant, MemoryParticipantSchema, type MemoryParticipantType, MemoryParticipantTypeSchema, MemoryPromptBuilder, type MemoryRetrievalRequest, MemoryRetrievalRequestSchema, type MemoryRetrievalResponse, MemoryRetrievalResponseSchema, type MessageDirection, MessageDirectionSchema, type MessageReadyCallback, MessagingChannel, type MessagingChannelConfig, type MessagingChannelEvents, OPENAI_USER_AGENT, type ObservationCreateRequest, ObservationCreateRequestSchema, type ObservationInfo, ObservationInfoSchema, OpenAIRealtimeProvider, OpenAIRealtimeProviderConfig, type OpenAIRealtimeProviderConfigOptions, type OpenAIRealtimeTool, OpenAIRealtimeToolSchema, type OpenAITool, OpenAIToolSchema, type Operator, type OperatorProcessingResult, OperatorProcessingResultSchema, type OperatorResult, type OperatorResultEvent, OperatorResultEventSchema, OperatorResultProcessor, OperatorResultSchema, OperatorSchema, type ParticipantAddress, ParticipantAddressSchema, type ParticipantAddressType, ParticipantAddressTypeSchema, type ParticipantId, type PendingHandoffData, PendingHandoffDataSchema, type Profile, type ProfileId, type ProfileLookupResponse, ProfileLookupResponseSchema, type ProfileResponse, ProfileResponseSchema, type PromptMessage, PromptMessageSchema, RCSChannel, type RecordingEvent, RecordingEventSchema, type RecordingHandler, SMSChannel, type SendMessageActionPayload, SendMessageActionPayloadSchema, type SendMessageActionRequest, SendMessageActionRequestSchema, type SessionInfo, SessionInfoSchema, type SessionMessage, SessionMessageSchema, type SetupMessage, SetupMessageSchema, type StatusCallback, StatusCallbackSchema, type StatusTimeouts, StatusTimeoutsSchema, type StreamStartMessage, StreamStartMessageSchema, type StreamTask, type SummaryInfo, SummaryInfoSchema, TAC, type TACChannelType, TACChannelTypeSchema, type TACCommunication, type TACCommunicationAuthor, TACCommunicationAuthorSchema, type TACCommunicationContent, TACCommunicationContentSchema, TACCommunicationSchema, TACConfig, type TACConfigData, type TACConfigInput, TACConfigSchema, type TACDeliveryStatus, TACDeliveryStatusSchema, TACMemoryResponse, type TACOptions, type TACParticipantType, TACParticipantTypeSchema, TACServer, type TACServerConfig, TACTool, TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE, TWILIO_AUDIO_FORMAT_FOR_REALTIME, type TextTokenMessage, TextTokenMessageSchema, type ToolContext, type ToolExecutionResult, ToolExecutionResultSchema, type ToolFunction, type Transcription, TranscriptionSchema, type TranscriptionWord, TranscriptionWordSchema, TwiMLBuilderMediaStreams, type TwiMLOptions, TwiMLOptionsSchema, type TwiMLRequest, TwiMLRequestSchema, type TwilioMemoryConfig, TwilioMemoryConfigSchema, type TwilioProviderCallbackResponse, type TypedCallOptions, VoiceChannel, type VoiceChannelConfig, type VoiceChannelEvents, VoiceProvider, VoiceProviderConfig, type VoiceTwiMLOptions, type VoiceTwiMLOptionsConversationRelay, VoiceTwiMLOptionsConversationRelaySchema, type VoiceTwiMLOptionsMediaStreams, VoiceTwiMLOptionsMediaStreamsSchema, VoiceTwiMLOptionsSchema, type WebSocketMessage, WebSocketMessageSchema, WhatsAppChannel, type _CallsCreateDriftGuards, type _SDKDriftGuards, amdEventFromForm, buildHandoffPayload, callOptionsToCreateParams, callStatusEventFromForm, createKnowledgeSearchTool, createKnowledgeSearchToolAsync, createKnowledgeTools, createLogger, createMemoryRetrievalTool, createMemoryTools, createMessagingTools, createSendMessageTool, createStudioHandoffTool, defineTool, generateStreamTwiml, isConversationId, isParticipantId, isProfileId, maskAddress, maskEmail, maskPhone, postStudioHandoff, recordingEventFromForm, redactTwimlParameters, scrubObject, scrubPii, shutdownAnalytics, studioExecutionsUrl, studioVoiceHandoffUrl, trackEvent, twiMLRequestFromForm };
7178
+ export { type ActionChannelSettings, ActionChannelSettingsSchema, type ActionParticipantRef, ActionParticipantRefSchema, type ActionResponse, ActionResponseSchema, type ActionTextContent, ActionTextContentSchema, type AdapterOptions, type AmdEvent, AmdEventSchema, type AmdHandler, type AnthropicTool, AnthropicToolSchema, type AuthorInfo, AuthorInfoSchema, BaseChannel, type BaseChannelEvents, type BaseChannelOptions, BaseClient, type BuildStreamTwiMLInputs, type BuiltInToolName, BuiltInTools, CALL_EVENT_KINDS, type CallEndedHandler, type CallEventKind, CallEventKindSchema, type CallOptions, CallOptionsSchema, type CallStatusEvent, CallStatusEventSchema, type CallStatusHandler, type CaptureRule, CaptureRuleSchema, type ChannelSettings, ChannelSettingsSchema, type ChannelType, ChannelTypeSchema, ChatChannel, type ChatChannelConfig, type CintelParticipant, CintelParticipantSchema, type Communication, type CommunicationContent, CommunicationContentSchema, type CommunicationParticipant, CommunicationParticipantSchema, CommunicationSchema, type ConversationAddress, ConversationAddressSchema, ConversationClient, type ConversationConfiguration, ConversationConfigurationSchema, type ConversationEndedCallback, type ConversationGroupingType, ConversationGroupingTypeSchema, type ConversationId, type ConversationIntelligenceConfig, ConversationIntelligenceConfigSchema, type ConversationParticipant, ConversationParticipantSchema, type ConversationRelayAttributes, ConversationRelayAttributesSchema, type ConversationRelayCallbackPayload, ConversationRelayCallbackPayloadSchema, type ConversationRelayConfig, ConversationRelayConfigSchema, ConversationRelayProvider, ConversationRelayProviderConfig, type ConversationRelayProviderConfigOptions, type ConversationResponse, ConversationResponseSchema, type ConversationSession, ConversationSessionSchema, type ConversationSummaryItem, ConversationSummaryItemSchema, type ConversationWebhookPayload, type CreateConversationSummariesResponse, CreateConversationSummariesResponseSchema, type CreateObservationResponse, CreateObservationResponseSchema, type CreateObservationsRequest, CreateObservationsRequestSchema, type CustomParameters, CustomParametersSchema, type DtmfEvent, type DtmfHandler, type DtmfMessage, DtmfMessageSchema, EMPTY_MEMORY_RESPONSE, EnvironmentVariables, type ExecutionDetails, ExecutionDetailsSchema, GPTLiveProvider, GPTLiveProviderConfig, type GPTLiveProviderConfigOptions, GPT_LIVE_SESSION_ID_METADATA_KEY, type HandoffPayload, HandoffPayloadSchema, type HandoffResult, type InboundCallTwimlHandler, type InitiateChatConversationOptions, type InitiateConversationResult, type InitiateMessagingConversationOptions, InitiateMessagingConversationOptionsSchema, type InitiateVoiceConversationOptions, type InitiateVoiceConversationOptionsGPTLive, InitiateVoiceConversationOptionsGPTLiveSchema, type InitiateVoiceConversationOptionsOpenAIRealtime, InitiateVoiceConversationOptionsOpenAIRealtimeSchema, InitiateVoiceConversationOptionsSchema, type InitiateVoiceConversationResult, type IntelligenceConfiguration, IntelligenceConfigurationSchema, type InterruptCallback, type InterruptMessage, InterruptMessageSchema, type InterruptMode, InterruptModeSchema, type JSONSchema, JSONSchemaSchema, type KnowledgeBase, KnowledgeBaseSchema, type KnowledgeBaseStatus, KnowledgeBaseStatusSchema, type KnowledgeChunkResult, KnowledgeChunkResultSchema, KnowledgeClient, type KnowledgeSearchResponse, KnowledgeSearchResponseSchema, type LanguageAttributes, LanguageAttributesSchema, type LanguageConfig, LanguageConfigSchema, type ListCommunicationsResponse, ListCommunicationsResponseSchema, type ListConversationsResponse, ListConversationsResponseSchema, type ListParticipantsResponse, ListParticipantsResponseSchema, type Logger, MediaStreamsOpenAICallState, MediaStreamsOpenAIProvider, MediaStreamsOpenAIProviderConfig, type MediaStreamsOpenAIProviderConfigOptions, MediaStreamsProviderConfig, type MediaStreamsProviderConfigOptions, type MediaStreamsTwiMLBuilderConfig, type MemoryChannelType, MemoryChannelTypeSchema, MemoryClient, type MemoryCommunication, type MemoryCommunicationContent, MemoryCommunicationContentSchema, MemoryCommunicationSchema, type MemoryDeliveryStatus, MemoryDeliveryStatusSchema, type MemoryMode, MemoryModeSchema, type MemoryParticipant, MemoryParticipantSchema, type MemoryParticipantType, MemoryParticipantTypeSchema, MemoryPromptBuilder, type MemoryRetrievalRequest, MemoryRetrievalRequestSchema, type MemoryRetrievalResponse, MemoryRetrievalResponseSchema, type MessageDirection, MessageDirectionSchema, type MessageReadyCallback, MessagingChannel, type MessagingChannelConfig, type MessagingChannelEvents, OPENAI_USER_AGENT, type ObservationCreateRequest, ObservationCreateRequestSchema, type ObservationInfo, ObservationInfoSchema, OpenAIRealtimeProvider, OpenAIRealtimeProviderConfig, type OpenAIRealtimeProviderConfigOptions, type OpenAIRealtimeTool, OpenAIRealtimeToolSchema, type OpenAITool, OpenAIToolSchema, type Operator, type OperatorProcessingResult, OperatorProcessingResultSchema, type OperatorResult, type OperatorResultEvent, OperatorResultEventSchema, OperatorResultProcessor, OperatorResultSchema, OperatorSchema, type ParticipantAddress, ParticipantAddressSchema, type ParticipantAddressType, ParticipantAddressTypeSchema, type ParticipantId, type PendingHandoffData, PendingHandoffDataSchema, type Profile, type ProfileId, type ProfileLookupResponse, ProfileLookupResponseSchema, type ProfileResponse, ProfileResponseSchema, type PromptMessage, PromptMessageSchema, RCSChannel, type RecordingEvent, RecordingEventSchema, type RecordingHandler, SMSChannel, type SendMessageActionPayload, SendMessageActionPayloadSchema, type SendMessageActionRequest, SendMessageActionRequestSchema, type SessionInfo, SessionInfoSchema, type SessionMessage, SessionMessageSchema, type SetupMessage, SetupMessageSchema, type StatusCallback, StatusCallbackSchema, type StatusTimeouts, StatusTimeoutsSchema, type StreamStartMessage, StreamStartMessageSchema, type StreamTask, type SummaryInfo, SummaryInfoSchema, TAC, type TACChannelType, TACChannelTypeSchema, type TACCommunication, type TACCommunicationAuthor, TACCommunicationAuthorSchema, type TACCommunicationContent, TACCommunicationContentSchema, TACCommunicationSchema, TACConfig, type TACConfigData, type TACConfigInput, TACConfigSchema, type TACDeliveryStatus, TACDeliveryStatusSchema, TACMemoryResponse, type TACOptions, type TACParticipantType, TACParticipantTypeSchema, TACServer, type TACServerConfig, TACTool, TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE, TWILIO_AUDIO_FORMAT_FOR_REALTIME, type TextTokenMessage, TextTokenMessageSchema, type ToolContext, type ToolExecutionResult, ToolExecutionResultSchema, type ToolFunction, type Transcription, TranscriptionSchema, type TranscriptionWord, TranscriptionWordSchema, TwiMLBuilderMediaStreams, type TwiMLOptions, TwiMLOptionsSchema, type TwiMLRequest, TwiMLRequestSchema, type TwilioMemoryConfig, TwilioMemoryConfigSchema, type TwilioProviderCallbackResponse, type TypedCallOptions, VoiceChannel, type VoiceChannelConfig, type VoiceChannelEvents, VoiceProvider, VoiceProviderConfig, type VoiceTwiMLOptions, type VoiceTwiMLOptionsConversationRelay, VoiceTwiMLOptionsConversationRelaySchema, type VoiceTwiMLOptionsMediaStreams, VoiceTwiMLOptionsMediaStreamsSchema, VoiceTwiMLOptionsSchema, type WebSocketMessage, WebSocketMessageSchema, WhatsAppChannel, type _CallsCreateDriftGuards, type _SDKDriftGuards, amdEventFromForm, buildHandoffPayload, callOptionsToCreateParams, callStatusEventFromForm, conversationMetadata, createKnowledgeSearchTool, createKnowledgeSearchToolAsync, createKnowledgeTools, createLogger, createMemoryRetrievalTool, createMemoryTools, createMessagingTools, createSendMessageTool, createStudioHandoffTool, defineTool, generateStreamTwiml, isConversationId, isParticipantId, isProfileId, maskAddress, maskEmail, maskPhone, postStudioHandoff, recordingEventFromForm, redactTwimlParameters, scrubObject, scrubPii, shutdownAnalytics, studioExecutionsUrl, studioVoiceHandoffUrl, trackEvent, twiMLRequestFromForm };