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/README.md +6 -3
- package/dist/index.d.ts +753 -187
- package/dist/index.js +1943 -1038
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export { z } from 'zod';
|
|
3
3
|
import pino from 'pino';
|
|
4
|
-
import
|
|
4
|
+
import axios3, { AxiosError } from 'axios';
|
|
5
5
|
import axiosRetry from 'axios-retry';
|
|
6
6
|
import { Analytics } from '@segment/analytics-node';
|
|
7
7
|
import twilio from 'twilio';
|
|
8
8
|
import { WebSocket } from 'ws';
|
|
9
9
|
import VoiceResponse from 'twilio/lib/twiml/VoiceResponse.js';
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
10
11
|
import Fastify from 'fastify';
|
|
11
12
|
import formbody from '@fastify/formbody';
|
|
12
13
|
import websocket from '@fastify/websocket';
|
|
@@ -36,13 +37,26 @@ var voicePathSchema = (defaultPath) => z.preprocess((v) => {
|
|
|
36
37
|
const trimmed = v.trim();
|
|
37
38
|
return trimmed.length === 0 ? void 0 : trimmed;
|
|
38
39
|
}, z.string().startsWith("/", 'Path must start with "/"').default(defaultPath));
|
|
40
|
+
var publicDomainSchema = () => z.preprocess((v) => {
|
|
41
|
+
if (typeof v !== "string") return v;
|
|
42
|
+
let s = v.trim();
|
|
43
|
+
if (s.length === 0) return void 0;
|
|
44
|
+
for (const scheme of ["https://", "http://", "wss://", "ws://"]) {
|
|
45
|
+
if (s.toLowerCase().startsWith(scheme)) {
|
|
46
|
+
s = s.slice(scheme.length);
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
s = s.replace(/\/+$/, "");
|
|
51
|
+
return s.length === 0 ? void 0 : s;
|
|
52
|
+
}, z.string().optional()).optional();
|
|
39
53
|
var CallEventKindSchema = z.enum(["status", "amd", "recording"]);
|
|
40
54
|
var CALL_EVENT_KINDS = CallEventKindSchema.options;
|
|
41
55
|
var RCS_SENDER_ID_REGEX = /^rcs:.+$/;
|
|
42
56
|
var RCS_SENDER_ID_MESSAGE = "RCS sender ID must be in format: rcs:<sender-id-or-phone> (e.g., rcs:brand_acme_agent or rcs:+1234567890)";
|
|
43
57
|
var WHATSAPP_NUMBER_REGEX = /^whatsapp:\+\d+$/;
|
|
44
58
|
var WHATSAPP_NUMBER_MESSAGE = "WhatsApp number must be in format: whatsapp:+1234567890";
|
|
45
|
-
function normalizeSenderPair(defaultValue, plural
|
|
59
|
+
function normalizeSenderPair(defaultValue, plural) {
|
|
46
60
|
const trimmedDefault = typeof defaultValue === "string" && defaultValue.trim().length > 0 ? defaultValue.trim() : void 0;
|
|
47
61
|
const cleaned = [];
|
|
48
62
|
for (const entry of plural) {
|
|
@@ -52,13 +66,6 @@ function normalizeSenderPair(defaultValue, plural, options) {
|
|
|
52
66
|
}
|
|
53
67
|
}
|
|
54
68
|
if (trimmedDefault === void 0 && cleaned.length === 0) {
|
|
55
|
-
if (options.required) {
|
|
56
|
-
return {
|
|
57
|
-
default: void 0,
|
|
58
|
-
plural: [],
|
|
59
|
-
error: `At least one of \`${options.field}\` / \`${options.field}s\` must be set.`
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
69
|
return { default: void 0, plural: [] };
|
|
63
70
|
}
|
|
64
71
|
const resolvedDefault = trimmedDefault ?? cleaned[0];
|
|
@@ -71,9 +78,10 @@ var TACConfigSchema = z.object({
|
|
|
71
78
|
apiKey: z.string().min(1, "Twilio API Key is required"),
|
|
72
79
|
apiSecret: z.string().min(1, "Twilio API Secret is required"),
|
|
73
80
|
/**
|
|
74
|
-
* Default Twilio phone number for Voice (inbound) and SMS. Optional
|
|
75
|
-
* `phoneNumbers`
|
|
76
|
-
*
|
|
81
|
+
* Default Twilio phone number for Voice (inbound) and SMS. Optional;
|
|
82
|
+
* back-filled from `phoneNumbers` when omitted, and always a member of
|
|
83
|
+
* `phoneNumbers` when set. Required (this or `phoneNumbers`) by the Voice
|
|
84
|
+
* and SMS channels.
|
|
77
85
|
*/
|
|
78
86
|
phoneNumber: z.string().min(1, "Twilio Phone Number is required").optional(),
|
|
79
87
|
/**
|
|
@@ -108,19 +116,21 @@ var TACConfigSchema = z.object({
|
|
|
108
116
|
* automatically; anything else is passed through as given. Mirrors the Python
|
|
109
117
|
* SDK's `_normalize_voice_public_domain` — keep the two in step.
|
|
110
118
|
*/
|
|
111
|
-
voicePublicDomain:
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
119
|
+
voicePublicDomain: publicDomainSchema(),
|
|
120
|
+
/**
|
|
121
|
+
* Directly-routable host for *this process* (e.g. a Kubernetes pod's own
|
|
122
|
+
* address). When set, the URLs TAC hands Twilio for a call point here
|
|
123
|
+
* instead of at `voicePublicDomain`: the WebSocket and action callback
|
|
124
|
+
* always, and the status/AMD/recording callbacks on calls TAC places. So
|
|
125
|
+
* those webhooks return to the process holding the call's socket. An
|
|
126
|
+
* inbound call's status/AMD/recording webhooks come from the phone
|
|
127
|
+
* number's own configuration and still reach `voicePublicDomain`.
|
|
128
|
+
*
|
|
129
|
+
* Requires per-pod addressability; without it, leave this unset and route
|
|
130
|
+
* by `CallSid` at the load balancer. Normalized the same way as
|
|
131
|
+
* `voicePublicDomain`.
|
|
132
|
+
*/
|
|
133
|
+
instancePublicDomain: publicDomainSchema(),
|
|
124
134
|
/**
|
|
125
135
|
* Path the voice WebSocket is served at. Combined with voicePublicDomain to
|
|
126
136
|
* build the public WebSocket URL the voice channel hands to Twilio in TwiML;
|
|
@@ -156,26 +166,12 @@ var TACConfigSchema = z.object({
|
|
|
156
166
|
/^FW[0-9a-f]{32}$/,
|
|
157
167
|
"Invalid Studio Flow SID format (expected FW followed by 32 hex chars)"
|
|
158
168
|
).optional()
|
|
159
|
-
}).transform((data
|
|
160
|
-
const phone = normalizeSenderPair(data.phoneNumber, data.phoneNumbers ?? []
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
});
|
|
164
|
-
if (phone.error) {
|
|
165
|
-
ctx.addIssue({ code: "custom", message: phone.error, path: ["phoneNumber"] });
|
|
166
|
-
return z.NEVER;
|
|
167
|
-
}
|
|
168
|
-
const rcs = normalizeSenderPair(data.rcsSenderId, data.rcsSenderIds ?? [], {
|
|
169
|
-
required: false,
|
|
170
|
-
field: "rcsSenderId"
|
|
171
|
-
});
|
|
172
|
-
const whatsapp = normalizeSenderPair(data.whatsappNumber, data.whatsappNumbers ?? [], {
|
|
173
|
-
required: false,
|
|
174
|
-
field: "whatsappNumber"
|
|
175
|
-
});
|
|
169
|
+
}).transform((data) => {
|
|
170
|
+
const phone = normalizeSenderPair(data.phoneNumber, data.phoneNumbers ?? []);
|
|
171
|
+
const rcs = normalizeSenderPair(data.rcsSenderId, data.rcsSenderIds ?? []);
|
|
172
|
+
const whatsapp = normalizeSenderPair(data.whatsappNumber, data.whatsappNumbers ?? []);
|
|
176
173
|
return {
|
|
177
174
|
...data,
|
|
178
|
-
// Guaranteed populated: the required check above returned early otherwise.
|
|
179
175
|
phoneNumber: phone.default,
|
|
180
176
|
phoneNumbers: phone.plural,
|
|
181
177
|
rcsSenderId: rcs.default,
|
|
@@ -204,6 +200,7 @@ var EnvironmentVariables = {
|
|
|
204
200
|
TWILIO_MEMORY_PHONE_TRAIT_FIELD: "TWILIO_MEMORY_PHONE_TRAIT_FIELD",
|
|
205
201
|
TWILIO_CONVERSATION_CONFIGURATION_ID: "TWILIO_CONVERSATION_CONFIGURATION_ID",
|
|
206
202
|
TWILIO_VOICE_PUBLIC_DOMAIN: "TWILIO_VOICE_PUBLIC_DOMAIN",
|
|
203
|
+
TWILIO_INSTANCE_PUBLIC_DOMAIN: "TWILIO_INSTANCE_PUBLIC_DOMAIN",
|
|
207
204
|
TWILIO_VOICE_WEBSOCKET_PATH: "TWILIO_VOICE_WEBSOCKET_PATH",
|
|
208
205
|
TWILIO_VOICE_ACTION_PATH: "TWILIO_VOICE_ACTION_PATH",
|
|
209
206
|
TWILIO_VOICE_CALL_EVENT_PATH: "TWILIO_VOICE_CALL_EVENT_PATH",
|
|
@@ -318,7 +315,8 @@ var ConversationSessionSchema = z.object({
|
|
|
318
315
|
* Twilio Call SID on the Voice channel, unset on messaging. The correlation
|
|
319
316
|
* key for call events (`VoiceChannel.onCallStatus` / `onAmd` / `onRecording`)
|
|
320
317
|
* and `endCall`. Equals `conversationId` in relay-only mode; look the session
|
|
321
|
-
* up the other way with `VoiceChannel.getConversationSessionByCallSid
|
|
318
|
+
* up the other way with `VoiceChannel.getConversationSessionByCallSid`, or,
|
|
319
|
+
* from another instance, `VoiceChannel.resolveConversationSessionByCallSid`.
|
|
322
320
|
*/
|
|
323
321
|
callSid: z.string().optional(),
|
|
324
322
|
profileId: z.string().optional(),
|
|
@@ -333,6 +331,13 @@ var ConversationSessionSchema = z.object({
|
|
|
333
331
|
*/
|
|
334
332
|
aiAgentInfo: AuthorInfoSchema.optional(),
|
|
335
333
|
profile: z.custom().optional(),
|
|
334
|
+
/**
|
|
335
|
+
* Generic metadata storage for session-specific data. On messaging channels
|
|
336
|
+
* a session lasts one turn, so nothing here carries over to the next
|
|
337
|
+
* message; keep cross-turn state in your own store, keyed by
|
|
338
|
+
* `conversationId`. To read metadata stored on the conversation itself (from
|
|
339
|
+
* any instance), use `conversationMetadata(session)`.
|
|
340
|
+
*/
|
|
336
341
|
metadata: z.record(z.string(), z.unknown()).optional().default({}),
|
|
337
342
|
/**
|
|
338
343
|
* Pending handoff payload set by the handoff tool. Voice channel sends
|
|
@@ -354,6 +359,11 @@ function isProfileId(value) {
|
|
|
354
359
|
function isParticipantId(value) {
|
|
355
360
|
return value.length > 0;
|
|
356
361
|
}
|
|
362
|
+
function stringEntries(value) {
|
|
363
|
+
return Object.fromEntries(
|
|
364
|
+
Object.entries(value).filter((entry) => typeof entry[1] === "string")
|
|
365
|
+
);
|
|
366
|
+
}
|
|
357
367
|
var ConversationResponseSchema = z.object({
|
|
358
368
|
id: z.string(),
|
|
359
369
|
accountId: z.string(),
|
|
@@ -362,7 +372,17 @@ var ConversationResponseSchema = z.object({
|
|
|
362
372
|
// API returns null when not set
|
|
363
373
|
configurationId: z.string().optional(),
|
|
364
374
|
createdAt: z.string().optional(),
|
|
365
|
-
updatedAt: z.string().optional()
|
|
375
|
+
updatedAt: z.string().optional(),
|
|
376
|
+
/**
|
|
377
|
+
* Customer-managed key-value data stored on the conversation. Only string
|
|
378
|
+
* entries are kept: a conversation can carry metadata written by other tools,
|
|
379
|
+
* and a non-string entry is dropped rather than failing the whole parse.
|
|
380
|
+
* Metadata that isn't an object becomes `undefined`.
|
|
381
|
+
*/
|
|
382
|
+
metadata: z.preprocess(
|
|
383
|
+
(v) => v !== null && typeof v === "object" && !Array.isArray(v) ? stringEntries(v) : void 0,
|
|
384
|
+
z.record(z.string(), z.string()).optional()
|
|
385
|
+
)
|
|
366
386
|
});
|
|
367
387
|
var ListConversationsResponseSchema = z.object({
|
|
368
388
|
conversations: z.array(ConversationResponseSchema)
|
|
@@ -425,6 +445,12 @@ var ConversationConfigurationSchema = z.object({
|
|
|
425
445
|
var InitiateMessagingConversationOptionsSchema = z.object({
|
|
426
446
|
to: z.string().min(1, "Recipient address is required"),
|
|
427
447
|
message: z.string().min(1, "Initial message is required"),
|
|
448
|
+
/**
|
|
449
|
+
* Attached to the returned session. Entries with string values that fit
|
|
450
|
+
* Conversation Orchestrator's limits (8 keys of letters, digits, `.`, `_` or
|
|
451
|
+
* `-` up to 128 characters; values up to 512 characters) are also stored on
|
|
452
|
+
* the conversation, for `conversationMetadata(session)` on any replica.
|
|
453
|
+
*/
|
|
428
454
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
429
455
|
/**
|
|
430
456
|
* Sender address to send from. Must be one of the channel's configured
|
|
@@ -1522,14 +1548,16 @@ var TACConfig = class _TACConfig {
|
|
|
1522
1548
|
apiSecret;
|
|
1523
1549
|
/**
|
|
1524
1550
|
* Default Twilio phone number for Voice and SMS — the sender used for
|
|
1525
|
-
* outbound when a call does not specify `from`.
|
|
1526
|
-
*
|
|
1551
|
+
* outbound when a call does not specify `from`. Undefined when no phone
|
|
1552
|
+
* number is configured (the Voice and SMS channels then refuse to
|
|
1553
|
+
* construct, and Studio handoff from Chat returns `handoff_failed`);
|
|
1554
|
+
* otherwise a member of {@link phoneNumbers}.
|
|
1527
1555
|
*/
|
|
1528
1556
|
phoneNumber;
|
|
1529
1557
|
/**
|
|
1530
1558
|
* Full set of Twilio phone numbers this instance serves for Voice and SMS
|
|
1531
|
-
* (the inbound allowlist).
|
|
1532
|
-
* default sender.
|
|
1559
|
+
* (the inbound allowlist). Empty when none is configured; otherwise includes
|
|
1560
|
+
* {@link phoneNumber} as the first, default sender.
|
|
1533
1561
|
*/
|
|
1534
1562
|
phoneNumbers;
|
|
1535
1563
|
rcsSenderId;
|
|
@@ -1541,6 +1569,12 @@ var TACConfig = class _TACConfig {
|
|
|
1541
1569
|
memoryConfig;
|
|
1542
1570
|
conversationConfigurationId;
|
|
1543
1571
|
voicePublicDomain;
|
|
1572
|
+
/**
|
|
1573
|
+
* This process's own directly-routable host. When set, the WebSocket and
|
|
1574
|
+
* action URLs (and call-event callbacks on calls TAC places) point here
|
|
1575
|
+
* instead of at {@link voicePublicDomain}. See {@link voiceCallbackDomain}.
|
|
1576
|
+
*/
|
|
1577
|
+
instancePublicDomain;
|
|
1544
1578
|
/** Path the voice WebSocket is served at (default '/ws'). */
|
|
1545
1579
|
voiceWebsocketPath;
|
|
1546
1580
|
/** Path the ConversationRelay action callback is served at (default '/conversation-relay-callback'). */
|
|
@@ -1565,7 +1599,9 @@ var TACConfig = class _TACConfig {
|
|
|
1565
1599
|
this.authToken = validatedConfig.authToken;
|
|
1566
1600
|
this.apiKey = validatedConfig.apiKey;
|
|
1567
1601
|
this.apiSecret = validatedConfig.apiSecret;
|
|
1568
|
-
|
|
1602
|
+
if (validatedConfig.phoneNumber) {
|
|
1603
|
+
this.phoneNumber = validatedConfig.phoneNumber;
|
|
1604
|
+
}
|
|
1569
1605
|
this.phoneNumbers = validatedConfig.phoneNumbers;
|
|
1570
1606
|
if (validatedConfig.rcsSenderId) {
|
|
1571
1607
|
this.rcsSenderId = validatedConfig.rcsSenderId;
|
|
@@ -1582,6 +1618,9 @@ var TACConfig = class _TACConfig {
|
|
|
1582
1618
|
if (validatedConfig.voicePublicDomain) {
|
|
1583
1619
|
this.voicePublicDomain = validatedConfig.voicePublicDomain;
|
|
1584
1620
|
}
|
|
1621
|
+
if (validatedConfig.instancePublicDomain) {
|
|
1622
|
+
this.instancePublicDomain = validatedConfig.instancePublicDomain;
|
|
1623
|
+
}
|
|
1585
1624
|
this.voiceWebsocketPath = validatedConfig.voiceWebsocketPath;
|
|
1586
1625
|
this.voiceActionPath = validatedConfig.voiceActionPath;
|
|
1587
1626
|
this.voiceCallEventPath = validatedConfig.voiceCallEventPath;
|
|
@@ -1606,15 +1645,17 @@ var TACConfig = class _TACConfig {
|
|
|
1606
1645
|
* - TWILIO_AUTH_TOKEN: Twilio Auth Token for API authentication
|
|
1607
1646
|
* - TWILIO_API_KEY: Twilio API Key SID (starts with SK)
|
|
1608
1647
|
* - TWILIO_API_SECRET: Twilio API Secret for API Key authentication
|
|
1609
|
-
* - TWILIO_PHONE_NUMBER and/or TWILIO_PHONE_NUMBERS: at least one is required.
|
|
1610
|
-
* Phone number(s) for voice and SMS channels — see **Multi-Value Senders** below.
|
|
1611
1648
|
*
|
|
1612
1649
|
* Optional environment variables:
|
|
1650
|
+
* - TWILIO_PHONE_NUMBER / TWILIO_PHONE_NUMBERS: phone number(s) for the voice and SMS
|
|
1651
|
+
* channels, which require at least one — see **Multi-Value Senders** below.
|
|
1613
1652
|
* - TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS: WhatsApp number(s) for the
|
|
1614
1653
|
* WhatsApp channel (e.g., 'whatsapp:+1234567890')
|
|
1615
1654
|
* - TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS: RCS Sender ID(s) for the RCS channel
|
|
1616
1655
|
* - TWILIO_CONVERSATION_CONFIGURATION_ID: Conversation Orchestrator configuration ID (enables orchestrated mode)
|
|
1617
1656
|
* - 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')
|
|
1657
|
+
* - TWILIO_INSTANCE_PUBLIC_DOMAIN: This process's own directly-routable host, for pinning a
|
|
1658
|
+
* call's out-of-band webhooks to the instance holding its WebSocket (multi-replica voice only)
|
|
1618
1659
|
* - TWILIO_VOICE_WEBSOCKET_PATH: Path for the voice WebSocket (default: /ws)
|
|
1619
1660
|
* - TWILIO_VOICE_ACTION_PATH: Path for the ConversationRelay action callback (default: /conversation-relay-callback)
|
|
1620
1661
|
* - TWILIO_VOICE_CALL_EVENT_PATH: Base path for the call-event callbacks — status, async AMD, recording (default: /twilio/call-events)
|
|
@@ -1628,8 +1669,9 @@ var TACConfig = class _TACConfig {
|
|
|
1628
1669
|
* e.g. `TWILIO_PHONE_NUMBERS=+1555,+1444`. Whichever side is set back-fills
|
|
1629
1670
|
* the other: the singular becomes the default sender and the plural the full
|
|
1630
1671
|
* allowlist. Entries are whitespace-trimmed and de-duplicated, with the
|
|
1631
|
-
* default kept first.
|
|
1632
|
-
*
|
|
1672
|
+
* default kept first. All three pairs are optional at the config level; each
|
|
1673
|
+
* channel requires its own pair at construction (Voice and SMS need
|
|
1674
|
+
* `phoneNumber`/`phoneNumbers`).
|
|
1633
1675
|
*
|
|
1634
1676
|
* Memory Configuration (defaults defined in TwilioMemoryConfigSchema):
|
|
1635
1677
|
* - TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: Trait groups to include (comma-separated, e.g., "Contact,Preferences")
|
|
@@ -1739,6 +1781,7 @@ var TACConfig = class _TACConfig {
|
|
|
1739
1781
|
},
|
|
1740
1782
|
conversationConfigurationId: process.env[EnvironmentVariables.TWILIO_CONVERSATION_CONFIGURATION_ID] || void 0,
|
|
1741
1783
|
voicePublicDomain: process.env[EnvironmentVariables.TWILIO_VOICE_PUBLIC_DOMAIN],
|
|
1784
|
+
instancePublicDomain: process.env[EnvironmentVariables.TWILIO_INSTANCE_PUBLIC_DOMAIN],
|
|
1742
1785
|
voiceWebsocketPath: process.env[EnvironmentVariables.TWILIO_VOICE_WEBSOCKET_PATH] || void 0,
|
|
1743
1786
|
voiceActionPath: process.env[EnvironmentVariables.TWILIO_VOICE_ACTION_PATH] || void 0,
|
|
1744
1787
|
voiceCallEventPath: process.env[EnvironmentVariables.TWILIO_VOICE_CALL_EVENT_PATH] || void 0,
|
|
@@ -1758,14 +1801,22 @@ var TACConfig = class _TACConfig {
|
|
|
1758
1801
|
callEventPath(kind) {
|
|
1759
1802
|
return `${this.voiceCallEventPath.replace(/\/+$/, "")}/${kind}`;
|
|
1760
1803
|
}
|
|
1804
|
+
/**
|
|
1805
|
+
* Host Twilio should reach for a call in progress: {@link instancePublicDomain}
|
|
1806
|
+
* if set, else the shared {@link voicePublicDomain}.
|
|
1807
|
+
*/
|
|
1808
|
+
get voiceCallbackDomain() {
|
|
1809
|
+
return this.instancePublicDomain ?? this.voicePublicDomain;
|
|
1810
|
+
}
|
|
1761
1811
|
/**
|
|
1762
1812
|
* Public URL for a call-event callback, or `undefined` without a public domain.
|
|
1763
1813
|
*/
|
|
1764
1814
|
callEventUrl(kind) {
|
|
1765
|
-
|
|
1815
|
+
const domain = this.voiceCallbackDomain;
|
|
1816
|
+
if (!domain) {
|
|
1766
1817
|
return void 0;
|
|
1767
1818
|
}
|
|
1768
|
-
return `https://${
|
|
1819
|
+
return `https://${domain}${this.callEventPath(kind)}`;
|
|
1769
1820
|
}
|
|
1770
1821
|
/**
|
|
1771
1822
|
* Whether Conversation Orchestrator is configured.
|
|
@@ -1883,7 +1934,7 @@ function createLogger(options) {
|
|
|
1883
1934
|
// package.json
|
|
1884
1935
|
var package_default = {
|
|
1885
1936
|
name: "twilio-agent-connect",
|
|
1886
|
-
version: "2.
|
|
1937
|
+
version: "2.6.0",
|
|
1887
1938
|
description: "Twilio Agent Connect - A TypeScript framework for building intelligent agents",
|
|
1888
1939
|
type: "module",
|
|
1889
1940
|
main: "./dist/index.js",
|
|
@@ -1914,7 +1965,8 @@ var package_default = {
|
|
|
1914
1965
|
"docs:watch": "typedoc --watch",
|
|
1915
1966
|
setup: "tsx getting_started/twilio-setup/src/index.ts | pino-pretty",
|
|
1916
1967
|
"example:getting-started": "cd getting_started/examples/openai && npm install && npm run dev",
|
|
1917
|
-
"example:chat": "cd getting_started/examples/chat && npm install && npm run dev"
|
|
1968
|
+
"example:chat": "cd getting_started/examples/chat && npm install && npm run dev",
|
|
1969
|
+
"example:overview": "cd getting_started/examples/overview && npm install && npm run dev"
|
|
1918
1970
|
},
|
|
1919
1971
|
keywords: [
|
|
1920
1972
|
"twilio",
|
|
@@ -1988,7 +2040,7 @@ var BaseClient = class {
|
|
|
1988
2040
|
this.logger = logger || createLogger({ name: this.constructor.name });
|
|
1989
2041
|
const authHeader = "Basic " + Buffer.from(`${config.apiKey}:${config.apiSecret}`).toString("base64");
|
|
1990
2042
|
const baseOrigin = new URL(baseUrl).origin;
|
|
1991
|
-
this.axiosInstance =
|
|
2043
|
+
this.axiosInstance = axios3.create({
|
|
1992
2044
|
baseURL: baseUrl,
|
|
1993
2045
|
timeout: 3e4,
|
|
1994
2046
|
maxRedirects: 5,
|
|
@@ -2016,7 +2068,7 @@ var BaseClient = class {
|
|
|
2016
2068
|
this.axiosInstance.interceptors.response.use(
|
|
2017
2069
|
(response) => response,
|
|
2018
2070
|
(error) => {
|
|
2019
|
-
if (
|
|
2071
|
+
if (axios3.isAxiosError(error)) {
|
|
2020
2072
|
const status = error.response?.status;
|
|
2021
2073
|
const logContext = {
|
|
2022
2074
|
error: error.message,
|
|
@@ -2447,6 +2499,9 @@ var ConversationClient = class extends BaseClient {
|
|
|
2447
2499
|
if (options?.participants) {
|
|
2448
2500
|
requestBody.participants = options.participants;
|
|
2449
2501
|
}
|
|
2502
|
+
if (options?.metadata) {
|
|
2503
|
+
requestBody.metadata = options.metadata;
|
|
2504
|
+
}
|
|
2450
2505
|
try {
|
|
2451
2506
|
const data = await this.makeRequest(url, "POST", requestBody);
|
|
2452
2507
|
return ConversationResponseSchema.parse(data);
|
|
@@ -2463,10 +2518,17 @@ var ConversationClient = class extends BaseClient {
|
|
|
2463
2518
|
*
|
|
2464
2519
|
* On 409 CO returns the existing conversation ID in the
|
|
2465
2520
|
* X-Conflicting-Resource-Id response header.
|
|
2521
|
+
*
|
|
2522
|
+
* @param participants - Participants to create with the conversation
|
|
2523
|
+
* @param metadata - Set at creation; not applied when an existing
|
|
2524
|
+
* conversation is reused — the caller patches it
|
|
2466
2525
|
*/
|
|
2467
|
-
async createOrReuseConversation(participants) {
|
|
2526
|
+
async createOrReuseConversation(participants, metadata) {
|
|
2468
2527
|
try {
|
|
2469
|
-
const conversation = await this.createConversation({
|
|
2528
|
+
const conversation = await this.createConversation({
|
|
2529
|
+
participants,
|
|
2530
|
+
...metadata !== void 0 && { metadata }
|
|
2531
|
+
});
|
|
2470
2532
|
return { conversation, reused: false };
|
|
2471
2533
|
} catch (error) {
|
|
2472
2534
|
const existingId = this.extractConversationIdFrom409(error);
|
|
@@ -2485,7 +2547,7 @@ var ConversationClient = class extends BaseClient {
|
|
|
2485
2547
|
*/
|
|
2486
2548
|
extractConversationIdFrom409(error) {
|
|
2487
2549
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
2488
|
-
if (!
|
|
2550
|
+
if (!axios3.isAxiosError(cause) || cause.response?.status !== 409) {
|
|
2489
2551
|
return null;
|
|
2490
2552
|
}
|
|
2491
2553
|
const headers = cause.response.headers;
|
|
@@ -2644,6 +2706,46 @@ var ConversationClient = class extends BaseClient {
|
|
|
2644
2706
|
);
|
|
2645
2707
|
}
|
|
2646
2708
|
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Fetch a conversation, including its metadata.
|
|
2711
|
+
*
|
|
2712
|
+
* @param conversationId - The conversation ID to fetch
|
|
2713
|
+
*/
|
|
2714
|
+
async getConversation(conversationId) {
|
|
2715
|
+
const url = `/v2/Conversations/${conversationId}`;
|
|
2716
|
+
try {
|
|
2717
|
+
const data = await this.makeRequest(url, "GET");
|
|
2718
|
+
return ConversationResponseSchema.parse(data);
|
|
2719
|
+
} catch (error) {
|
|
2720
|
+
throw new Error(
|
|
2721
|
+
`Failed to fetch conversation: ${error instanceof Error ? error.message : String(error)}`,
|
|
2722
|
+
{ cause: error }
|
|
2723
|
+
);
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* Merge `metadata` into a conversation's metadata.
|
|
2728
|
+
*
|
|
2729
|
+
* A `PATCH` with only the given keys: other keys already on the conversation
|
|
2730
|
+
* are kept. Conversation Orchestrator rejects metadata changes once the
|
|
2731
|
+
* conversation is CLOSED.
|
|
2732
|
+
*
|
|
2733
|
+
* @param conversationId - The conversation ID to update
|
|
2734
|
+
* @param metadata - Keys to set (string values)
|
|
2735
|
+
* @returns The conversation, with its merged metadata
|
|
2736
|
+
*/
|
|
2737
|
+
async patchConversationMetadata(conversationId, metadata) {
|
|
2738
|
+
const url = `/v2/Conversations/${conversationId}`;
|
|
2739
|
+
try {
|
|
2740
|
+
const data = await this.makeRequest(url, "PATCH", { metadata });
|
|
2741
|
+
return ConversationResponseSchema.parse(data);
|
|
2742
|
+
} catch (error) {
|
|
2743
|
+
throw new Error(
|
|
2744
|
+
`Failed to update conversation metadata: ${error instanceof Error ? error.message : String(error)}`,
|
|
2745
|
+
{ cause: error }
|
|
2746
|
+
);
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2647
2749
|
/**
|
|
2648
2750
|
* Retrieve the details for a single configuration
|
|
2649
2751
|
*
|
|
@@ -3039,7 +3141,86 @@ var OperatorResultProcessor = class {
|
|
|
3039
3141
|
}
|
|
3040
3142
|
};
|
|
3041
3143
|
|
|
3144
|
+
// packages/core/src/util/expiring-map.ts
|
|
3145
|
+
var DEFAULT_EXPIRING_MAP_TTL_MS = 15 * 60 * 1e3;
|
|
3146
|
+
var DEFAULT_EXPIRING_MAP_MAX_ENTRIES = 1e3;
|
|
3147
|
+
var ExpiringMap = class {
|
|
3148
|
+
ttlMs;
|
|
3149
|
+
maxEntries;
|
|
3150
|
+
// Insertion-ordered, so the oldest entries are also the first to expire.
|
|
3151
|
+
entries = /* @__PURE__ */ new Map();
|
|
3152
|
+
constructor(options) {
|
|
3153
|
+
const ttlMs = options?.ttlMs ?? DEFAULT_EXPIRING_MAP_TTL_MS;
|
|
3154
|
+
const maxEntries = options?.maxEntries ?? DEFAULT_EXPIRING_MAP_MAX_ENTRIES;
|
|
3155
|
+
if (!(ttlMs > 0)) {
|
|
3156
|
+
throw new Error(`ttlMs must be positive, got ${ttlMs}`);
|
|
3157
|
+
}
|
|
3158
|
+
if (!(maxEntries > 0)) {
|
|
3159
|
+
throw new Error(`maxEntries must be positive, got ${maxEntries}`);
|
|
3160
|
+
}
|
|
3161
|
+
this.ttlMs = ttlMs;
|
|
3162
|
+
this.maxEntries = maxEntries;
|
|
3163
|
+
}
|
|
3164
|
+
/** Current time in ms; overridable in tests. */
|
|
3165
|
+
now() {
|
|
3166
|
+
return Date.now();
|
|
3167
|
+
}
|
|
3168
|
+
/** Drop expired entries, then the oldest survivors if still over capacity. */
|
|
3169
|
+
purge() {
|
|
3170
|
+
const now = this.now();
|
|
3171
|
+
for (const [key, entry] of this.entries) {
|
|
3172
|
+
if (entry.expiresAt > now) break;
|
|
3173
|
+
this.entries.delete(key);
|
|
3174
|
+
}
|
|
3175
|
+
while (this.entries.size > this.maxEntries) {
|
|
3176
|
+
const oldest = this.entries.keys().next().value;
|
|
3177
|
+
this.entries.delete(oldest);
|
|
3178
|
+
}
|
|
3179
|
+
}
|
|
3180
|
+
set(key, value) {
|
|
3181
|
+
this.entries.delete(key);
|
|
3182
|
+
this.entries.set(key, { expiresAt: this.now() + this.ttlMs, value });
|
|
3183
|
+
this.purge();
|
|
3184
|
+
return this;
|
|
3185
|
+
}
|
|
3186
|
+
get(key) {
|
|
3187
|
+
const entry = this.entries.get(key);
|
|
3188
|
+
if (entry === void 0 || entry.expiresAt <= this.now()) {
|
|
3189
|
+
return void 0;
|
|
3190
|
+
}
|
|
3191
|
+
return entry.value;
|
|
3192
|
+
}
|
|
3193
|
+
has(key) {
|
|
3194
|
+
const entry = this.entries.get(key);
|
|
3195
|
+
return entry !== void 0 && entry.expiresAt > this.now();
|
|
3196
|
+
}
|
|
3197
|
+
/** Remove `key` and return its live value, if any. */
|
|
3198
|
+
take(key) {
|
|
3199
|
+
const entry = this.entries.get(key);
|
|
3200
|
+
if (entry === void 0) {
|
|
3201
|
+
return void 0;
|
|
3202
|
+
}
|
|
3203
|
+
this.entries.delete(key);
|
|
3204
|
+
return entry.expiresAt <= this.now() ? void 0 : entry.value;
|
|
3205
|
+
}
|
|
3206
|
+
delete(key) {
|
|
3207
|
+
const live = this.has(key);
|
|
3208
|
+
this.entries.delete(key);
|
|
3209
|
+
return live;
|
|
3210
|
+
}
|
|
3211
|
+
clear() {
|
|
3212
|
+
this.entries.clear();
|
|
3213
|
+
}
|
|
3214
|
+
/** Number of live entries. */
|
|
3215
|
+
get size() {
|
|
3216
|
+
this.purge();
|
|
3217
|
+
return this.entries.size;
|
|
3218
|
+
}
|
|
3219
|
+
};
|
|
3220
|
+
|
|
3042
3221
|
// packages/core/src/lib/tac.ts
|
|
3222
|
+
var SHARED_PARTICIPANTS_TTL_MS = 6e4;
|
|
3223
|
+
var ENDED_REPORT_TTL_MS = 6e4;
|
|
3043
3224
|
var TAC = class _TAC {
|
|
3044
3225
|
static FACTORY_TOKEN = /* @__PURE__ */ Symbol("TAC.create");
|
|
3045
3226
|
config;
|
|
@@ -3054,6 +3235,13 @@ var TAC = class _TAC {
|
|
|
3054
3235
|
messageReadyCallback;
|
|
3055
3236
|
interruptCallback;
|
|
3056
3237
|
conversationEndedCallback;
|
|
3238
|
+
// In-flight or recent participant lookups, keyed by conversation id — see
|
|
3239
|
+
// listParticipantsShared.
|
|
3240
|
+
participantLookups = new ExpiringMap({
|
|
3241
|
+
ttlMs: SHARED_PARTICIPANTS_TTL_MS
|
|
3242
|
+
});
|
|
3243
|
+
// Conversations recently reported ended — see reportConversationEnded.
|
|
3244
|
+
reportedEnded = new ExpiringMap({ ttlMs: ENDED_REPORT_TTL_MS });
|
|
3057
3245
|
constructor(token, options = {}) {
|
|
3058
3246
|
if (token !== _TAC.FACTORY_TOKEN) {
|
|
3059
3247
|
throw new Error("TAC constructor is private. Use TAC.create() instead of new TAC().");
|
|
@@ -3169,6 +3357,7 @@ var TAC = class _TAC {
|
|
|
3169
3357
|
author: "user",
|
|
3170
3358
|
userMemory,
|
|
3171
3359
|
channelType: channel.channelType,
|
|
3360
|
+
session: eventSession,
|
|
3172
3361
|
abortSignal
|
|
3173
3362
|
});
|
|
3174
3363
|
}
|
|
@@ -3200,9 +3389,7 @@ var TAC = class _TAC {
|
|
|
3200
3389
|
}
|
|
3201
3390
|
}
|
|
3202
3391
|
);
|
|
3203
|
-
channel.
|
|
3204
|
-
"conversationEnded",
|
|
3205
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- Intentionally async event handler
|
|
3392
|
+
channel.setConversationEndedForwarderInternal(
|
|
3206
3393
|
async ({ session }) => {
|
|
3207
3394
|
if (this.conversationEndedCallback) {
|
|
3208
3395
|
try {
|
|
@@ -3245,7 +3432,7 @@ var TAC = class _TAC {
|
|
|
3245
3432
|
{ conversation_id: data.conversationId, channel: channel.channelType },
|
|
3246
3433
|
"Using channel for message"
|
|
3247
3434
|
);
|
|
3248
|
-
const session = channel.getConversationSession(data.conversationId);
|
|
3435
|
+
const session = data.session ?? channel.getConversationSession(data.conversationId);
|
|
3249
3436
|
if (!session) {
|
|
3250
3437
|
throw new Error(`No session found for conversation ${data.conversationId}`);
|
|
3251
3438
|
}
|
|
@@ -3277,7 +3464,7 @@ var TAC = class _TAC {
|
|
|
3277
3464
|
);
|
|
3278
3465
|
} else {
|
|
3279
3466
|
try {
|
|
3280
|
-
await channel.sendResponse(
|
|
3467
|
+
await channel.sendResponse(session, response);
|
|
3281
3468
|
} catch (sendError) {
|
|
3282
3469
|
this.logger.error(
|
|
3283
3470
|
{ err: sendError, conversation_id: data.conversationId },
|
|
@@ -3333,14 +3520,88 @@ var TAC = class _TAC {
|
|
|
3333
3520
|
/**
|
|
3334
3521
|
* Register callback for when a conversation ends.
|
|
3335
3522
|
*
|
|
3336
|
-
*
|
|
3337
|
-
*
|
|
3338
|
-
*
|
|
3339
|
-
*
|
|
3523
|
+
* Fires when Conversation Orchestrator closes a conversation, on whichever
|
|
3524
|
+
* replica receives the CLOSED webhook — so the session it receives is
|
|
3525
|
+
* rebuilt from Conversation Orchestrator's participant list (identity only:
|
|
3526
|
+
* `conversationId`, `profileId`, participants). On messaging, read the
|
|
3527
|
+
* conversation's stored metadata with `conversationMetadata(session)`.
|
|
3528
|
+
* Relay-only and Media
|
|
3529
|
+
* Streams voice calls have no CO conversation, so they fire it at WebSocket
|
|
3530
|
+
* teardown with the live session instead. For an orchestrated call's live
|
|
3531
|
+
* state (transcript, `metadata`), use `VoiceChannel.onCallEnded`.
|
|
3532
|
+
*
|
|
3533
|
+
* At-least-once across webhook retries and replicas, like `onMessageReady`.
|
|
3340
3534
|
*/
|
|
3341
3535
|
onConversationEnded(callback) {
|
|
3342
3536
|
this.conversationEndedCallback = callback;
|
|
3343
3537
|
}
|
|
3538
|
+
/**
|
|
3539
|
+
* Whether an `onConversationEnded` handler is registered. Channels check this
|
|
3540
|
+
* before rebuilding a session from Conversation Orchestrator: with no
|
|
3541
|
+
* handler, there is nothing to hand it to.
|
|
3542
|
+
*
|
|
3543
|
+
* @internal
|
|
3544
|
+
*/
|
|
3545
|
+
hasConversationEndedCallback() {
|
|
3546
|
+
return this.conversationEndedCallback !== void 0;
|
|
3547
|
+
}
|
|
3548
|
+
/**
|
|
3549
|
+
* List a conversation's participants, shared across channels briefly.
|
|
3550
|
+
*
|
|
3551
|
+
* A CO webhook is handed to every channel, and several may need the same
|
|
3552
|
+
* conversation's participants — to rebuild a closed conversation's session
|
|
3553
|
+
* for `onConversationEnded`. Concurrent callers share one in-flight request, and
|
|
3554
|
+
* later callers reuse its result until a minute after the request started. A
|
|
3555
|
+
* failure isn't cached. Not for paths that need fresh participants, like
|
|
3556
|
+
* reconciliation or resolving a session by CallSid.
|
|
3557
|
+
*
|
|
3558
|
+
* @throws If Conversation Orchestrator isn't configured, or whatever
|
|
3559
|
+
* `listParticipants` throws.
|
|
3560
|
+
* @internal
|
|
3561
|
+
*/
|
|
3562
|
+
listParticipantsShared(conversationId) {
|
|
3563
|
+
const client2 = this.conversationClient;
|
|
3564
|
+
if (client2 === null) {
|
|
3565
|
+
return Promise.reject(new Error("Conversation Orchestrator is not configured"));
|
|
3566
|
+
}
|
|
3567
|
+
const existing = this.participantLookups.get(conversationId);
|
|
3568
|
+
if (existing !== void 0) {
|
|
3569
|
+
return existing;
|
|
3570
|
+
}
|
|
3571
|
+
const lookup = client2.listParticipants(conversationId);
|
|
3572
|
+
this.participantLookups.set(conversationId, lookup);
|
|
3573
|
+
lookup.catch(() => {
|
|
3574
|
+
if (this.participantLookups.get(conversationId) === lookup) {
|
|
3575
|
+
this.participantLookups.delete(conversationId);
|
|
3576
|
+
}
|
|
3577
|
+
});
|
|
3578
|
+
return lookup;
|
|
3579
|
+
}
|
|
3580
|
+
/**
|
|
3581
|
+
* Report "Conversation Ended" for a conversation Conversation Orchestrator
|
|
3582
|
+
* closed, once per process.
|
|
3583
|
+
*
|
|
3584
|
+
* Every channel is handed the CLOSED webhook, and its payload doesn't say
|
|
3585
|
+
* which channel the conversation was on. Finding out would take a
|
|
3586
|
+
* participant lookup made only for telemetry, so the event carries no
|
|
3587
|
+
* `channel`: join it to "Conversation Started" on `conversation_id`. The
|
|
3588
|
+
* first channel to report a conversation wins; the rest are dropped.
|
|
3589
|
+
*
|
|
3590
|
+
* @param durationMs - CO's `updatedAt − createdAt`; `undefined` leaves it
|
|
3591
|
+
* out rather than guessing.
|
|
3592
|
+
* @internal
|
|
3593
|
+
*/
|
|
3594
|
+
reportConversationEnded(conversationId, durationMs) {
|
|
3595
|
+
if (this.reportedEnded.has(conversationId)) {
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
this.reportedEnded.set(conversationId, true);
|
|
3599
|
+
trackEvent("Conversation Ended", {
|
|
3600
|
+
account_sid: this.config.accountSid,
|
|
3601
|
+
conversation_id: conversationId,
|
|
3602
|
+
...durationMs !== void 0 && { duration_ms: durationMs }
|
|
3603
|
+
});
|
|
3604
|
+
}
|
|
3344
3605
|
/**
|
|
3345
3606
|
* Whether Conversation Orchestrator is configured.
|
|
3346
3607
|
* Returns false in voice-only mode.
|
|
@@ -3567,8 +3828,9 @@ var BaseChannel = class {
|
|
|
3567
3828
|
config;
|
|
3568
3829
|
logger;
|
|
3569
3830
|
conversationClient;
|
|
3570
|
-
activeConversations;
|
|
3571
3831
|
callbacks;
|
|
3832
|
+
/** TAC's forwarder to `tac.onConversationEnded`, while it fills the slot. */
|
|
3833
|
+
tacConversationEndedForwarder;
|
|
3572
3834
|
memoryMode;
|
|
3573
3835
|
processedWebhookTokens;
|
|
3574
3836
|
maxTrackedTokens;
|
|
@@ -3577,7 +3839,6 @@ var BaseChannel = class {
|
|
|
3577
3839
|
this.config = tac.getConfig();
|
|
3578
3840
|
this.logger = tac.logger.child({ component: "channel" });
|
|
3579
3841
|
this.conversationClient = tac.getConversationClient();
|
|
3580
|
-
this.activeConversations = /* @__PURE__ */ new Map();
|
|
3581
3842
|
this.callbacks = {};
|
|
3582
3843
|
const providedMode = options?.memoryMode;
|
|
3583
3844
|
const modeToValidate = providedMode === void 0 ? "never" : providedMode;
|
|
@@ -3623,102 +3884,141 @@ var BaseChannel = class {
|
|
|
3623
3884
|
}
|
|
3624
3885
|
}
|
|
3625
3886
|
/**
|
|
3626
|
-
*
|
|
3887
|
+
* Get a live conversation session held by this channel.
|
|
3888
|
+
*
|
|
3889
|
+
* Only `VoiceChannel` holds sessions (a call is pinned to one process); the
|
|
3890
|
+
* default returns `undefined`.
|
|
3627
3891
|
*/
|
|
3628
|
-
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
3892
|
+
getConversationSession(_conversationId) {
|
|
3893
|
+
return void 0;
|
|
3894
|
+
}
|
|
3895
|
+
/**
|
|
3896
|
+
* Check if this channel holds a live session for a conversation. Only
|
|
3897
|
+
* `VoiceChannel` holds sessions; the default returns `false`.
|
|
3898
|
+
*/
|
|
3899
|
+
isConversationActive(_conversationId) {
|
|
3900
|
+
return false;
|
|
3901
|
+
}
|
|
3902
|
+
/**
|
|
3903
|
+
* This channel's type as Conversation Orchestrator writes it on participant
|
|
3904
|
+
* addresses (`SMS`, `WHATSAPP`, `VOICE`, …).
|
|
3905
|
+
*
|
|
3906
|
+
* @internal
|
|
3907
|
+
*/
|
|
3908
|
+
get coChannel() {
|
|
3909
|
+
return this.channelType.toUpperCase();
|
|
3910
|
+
}
|
|
3911
|
+
/**
|
|
3912
|
+
* Whether `address` is TAC's own address on this channel. Channels override
|
|
3913
|
+
* this; the default claims no address.
|
|
3914
|
+
*
|
|
3915
|
+
* @internal
|
|
3916
|
+
*/
|
|
3917
|
+
isOwnCoAddress(_address) {
|
|
3918
|
+
return false;
|
|
3919
|
+
}
|
|
3920
|
+
/**
|
|
3921
|
+
* Report "Conversation Started" from a CO `PARTICIPANT_ADDED` event.
|
|
3922
|
+
*
|
|
3923
|
+
* Counts the customer joining on this channel: a `CUSTOMER`, or an `UNKNOWN`
|
|
3924
|
+
* participant that isn't TAC's own address (capture can add the customer
|
|
3925
|
+
* untyped). Each channel reports only its own channel type, so a webhook
|
|
3926
|
+
* handed to every channel counts once per channel.
|
|
3927
|
+
*
|
|
3928
|
+
* @internal
|
|
3929
|
+
*/
|
|
3930
|
+
trackConversationStarted(eventData) {
|
|
3931
|
+
const parsed = ConversationParticipantSchema.safeParse(eventData);
|
|
3932
|
+
if (!parsed.success) {
|
|
3933
|
+
this.logger.warn(
|
|
3934
|
+
{ validation_errors: parsed.error.issues },
|
|
3935
|
+
"Skipping unparseable PARTICIPANT_ADDED payload"
|
|
3637
3936
|
);
|
|
3638
|
-
return
|
|
3937
|
+
return;
|
|
3639
3938
|
}
|
|
3640
|
-
const
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
}
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
{
|
|
3651
|
-
conversation_id: conversationId,
|
|
3652
|
-
profile_id: profileId,
|
|
3653
|
-
service_id: serviceId,
|
|
3654
|
-
channel: this.channelType
|
|
3655
|
-
},
|
|
3656
|
-
"Conversation started"
|
|
3657
|
-
);
|
|
3658
|
-
if (this.callbacks.onConversationStarted) {
|
|
3659
|
-
this.callbacks.onConversationStarted({ session });
|
|
3939
|
+
const participant = parsed.data;
|
|
3940
|
+
if (participant.type !== "CUSTOMER" && participant.type !== "UNKNOWN") {
|
|
3941
|
+
return;
|
|
3942
|
+
}
|
|
3943
|
+
const addresses = participant.addresses.filter((a) => a.channel === this.coChannel).map((a) => a.address);
|
|
3944
|
+
if (addresses.length === 0) {
|
|
3945
|
+
return;
|
|
3946
|
+
}
|
|
3947
|
+
if (participant.type === "UNKNOWN" && addresses.some((a) => this.isOwnCoAddress(a))) {
|
|
3948
|
+
return;
|
|
3660
3949
|
}
|
|
3661
3950
|
trackEvent("Conversation Started", {
|
|
3662
3951
|
account_sid: this.config.accountSid,
|
|
3663
3952
|
channel: this.channelType,
|
|
3664
|
-
conversation_id: conversationId,
|
|
3665
|
-
has_profile_id: !!profileId
|
|
3953
|
+
conversation_id: participant.conversationId,
|
|
3954
|
+
has_profile_id: !!participant.profileId
|
|
3666
3955
|
});
|
|
3667
|
-
return session;
|
|
3668
3956
|
}
|
|
3669
3957
|
/**
|
|
3670
|
-
*
|
|
3958
|
+
* Report "Conversation Ended" for a conversation CO closed.
|
|
3671
3959
|
*
|
|
3672
|
-
*
|
|
3673
|
-
*
|
|
3674
|
-
*
|
|
3960
|
+
* Reported once per process across channels, without a `channel` — see
|
|
3961
|
+
* `TAC.reportConversationEnded`. `durationMs` is CO's `updatedAt −
|
|
3962
|
+
* createdAt`; `undefined` leaves it out rather than guessing.
|
|
3963
|
+
*
|
|
3964
|
+
* @internal
|
|
3675
3965
|
*/
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
conversation_id: conversationId,
|
|
3699
|
-
channel: this.channelType,
|
|
3700
|
-
service_id: session.serviceId
|
|
3701
|
-
},
|
|
3702
|
-
"Conversation ended"
|
|
3703
|
-
);
|
|
3704
|
-
} else {
|
|
3705
|
-
this.logger.debug(
|
|
3706
|
-
{ conversation_id: conversationId, channel: this.channelType },
|
|
3707
|
-
"Conversation end requested but no active session found"
|
|
3708
|
-
);
|
|
3966
|
+
trackConversationEnded(conversationId, durationMs) {
|
|
3967
|
+
this.tac.reportConversationEnded(conversationId, durationMs);
|
|
3968
|
+
}
|
|
3969
|
+
/**
|
|
3970
|
+
* Whether anything would receive `onConversationEnded`. Channels check this
|
|
3971
|
+
* before rebuilding a closed conversation's session from Conversation
|
|
3972
|
+
* Orchestrator: with no handler, there is nothing to hand it to.
|
|
3973
|
+
*
|
|
3974
|
+
* Registering with TAC fills the slot with a forwarder to
|
|
3975
|
+
* `tac.onConversationEnded`; while that forwarder is installed, ask TAC. A
|
|
3976
|
+
* handler set with `channel.on('conversationEnded', ...)` — before or after
|
|
3977
|
+
* registration — replaces it and counts on its own.
|
|
3978
|
+
*
|
|
3979
|
+
* @internal
|
|
3980
|
+
*/
|
|
3981
|
+
hasConversationEndedHandler() {
|
|
3982
|
+
const handler = this.callbacks.onConversationEnded;
|
|
3983
|
+
if (!handler) {
|
|
3984
|
+
return false;
|
|
3985
|
+
}
|
|
3986
|
+
if (handler !== this.tacConversationEndedForwarder) {
|
|
3987
|
+
return true;
|
|
3709
3988
|
}
|
|
3989
|
+
return this.tac.hasConversationEndedCallback();
|
|
3710
3990
|
}
|
|
3711
3991
|
/**
|
|
3712
|
-
*
|
|
3992
|
+
* Install TAC's forwarder to `tac.onConversationEnded` in this channel's
|
|
3993
|
+
* slot, remembering it so {@link hasConversationEndedHandler} can tell it
|
|
3994
|
+
* apart from a handler registered directly on the channel.
|
|
3995
|
+
*
|
|
3996
|
+
* @internal
|
|
3713
3997
|
*/
|
|
3714
|
-
|
|
3715
|
-
|
|
3998
|
+
setConversationEndedForwarderInternal(forwarder) {
|
|
3999
|
+
this.callbacks.onConversationEnded = forwarder;
|
|
4000
|
+
this.tacConversationEndedForwarder = forwarder;
|
|
3716
4001
|
}
|
|
3717
4002
|
/**
|
|
3718
|
-
*
|
|
4003
|
+
* Fire `onConversationEnded` for a session, swallowing handler errors.
|
|
4004
|
+
*
|
|
4005
|
+
* A developer callback throwing must not abort the channel's own cleanup or
|
|
4006
|
+
* fail the webhook, so the error is logged and dropped here.
|
|
4007
|
+
*
|
|
4008
|
+
* @internal
|
|
3719
4009
|
*/
|
|
3720
|
-
|
|
3721
|
-
|
|
4010
|
+
async triggerConversationEnded(session) {
|
|
4011
|
+
if (!this.callbacks.onConversationEnded) {
|
|
4012
|
+
return;
|
|
4013
|
+
}
|
|
4014
|
+
try {
|
|
4015
|
+
await this.callbacks.onConversationEnded({ session });
|
|
4016
|
+
} catch (error) {
|
|
4017
|
+
this.logger.error(
|
|
4018
|
+
{ err: error, conversation_id: session.conversationId },
|
|
4019
|
+
"Error in conversation ended callback"
|
|
4020
|
+
);
|
|
4021
|
+
}
|
|
3722
4022
|
}
|
|
3723
4023
|
/**
|
|
3724
4024
|
* Handle errors with proper context
|
|
@@ -3762,8 +4062,10 @@ var BaseChannel = class {
|
|
|
3762
4062
|
* Self-filtering: check if webhook event belongs to this channel.
|
|
3763
4063
|
*
|
|
3764
4064
|
* - COMMUNICATION_CREATED: require author.channel matches this channel type
|
|
3765
|
-
* -
|
|
3766
|
-
*
|
|
4065
|
+
* - Other events pass through, including CONVERSATION_UPDATED — the
|
|
4066
|
+
* per-channel handler filters that one. Filtering it here on locally
|
|
4067
|
+
* tracked state would drop it on any instance that didn't serve the
|
|
4068
|
+
* conversation's messages.
|
|
3767
4069
|
*/
|
|
3768
4070
|
isEventForThisChannel(webhookData) {
|
|
3769
4071
|
const eventType = webhookData.eventType;
|
|
@@ -3774,12 +4076,6 @@ var BaseChannel = class {
|
|
|
3774
4076
|
}
|
|
3775
4077
|
return authorChannel === this.channelType.toUpperCase();
|
|
3776
4078
|
}
|
|
3777
|
-
if (eventType === "CONVERSATION_UPDATED") {
|
|
3778
|
-
const conversationId = this.extractConversationId(webhookData);
|
|
3779
|
-
if (conversationId && !this.activeConversations.has(conversationId)) {
|
|
3780
|
-
return false;
|
|
3781
|
-
}
|
|
3782
|
-
}
|
|
3783
4079
|
return true;
|
|
3784
4080
|
}
|
|
3785
4081
|
/**
|
|
@@ -3904,74 +4200,221 @@ var BaseChannel = class {
|
|
|
3904
4200
|
return void 0;
|
|
3905
4201
|
}
|
|
3906
4202
|
}
|
|
3907
|
-
/**
|
|
3908
|
-
* Invalidate cached memory for "once" mode when a conversation becomes
|
|
3909
|
-
* INACTIVE. Conversation Orchestrator updates memory on the INACTIVE
|
|
3910
|
-
* transition, so the next message re-fetches fresh memory. No-op for other
|
|
3911
|
-
* memory modes.
|
|
3912
|
-
*/
|
|
3913
|
-
invalidateCachedMemory(conversationId) {
|
|
3914
|
-
if (this.memoryMode !== "once") {
|
|
3915
|
-
return;
|
|
3916
|
-
}
|
|
3917
|
-
const session = this.activeConversations.get(conversationId);
|
|
3918
|
-
if (session?.cachedMemory !== void 0) {
|
|
3919
|
-
session.cachedMemory = void 0;
|
|
3920
|
-
this.logger.debug(
|
|
3921
|
-
{ conversation_id: conversationId },
|
|
3922
|
-
"Invalidated cached memory on INACTIVE status"
|
|
3923
|
-
);
|
|
3924
|
-
}
|
|
3925
|
-
}
|
|
3926
4203
|
/**
|
|
3927
4204
|
* Cleanup resources when shutting down
|
|
3928
4205
|
*/
|
|
3929
4206
|
shutdown() {
|
|
3930
|
-
this.activeConversations.clear();
|
|
3931
4207
|
delete this.callbacks.onConversationStarted;
|
|
3932
4208
|
delete this.callbacks.onConversationEnded;
|
|
3933
4209
|
delete this.callbacks.onError;
|
|
4210
|
+
this.tacConversationEndedForwarder = void 0;
|
|
3934
4211
|
}
|
|
3935
4212
|
};
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
4213
|
+
|
|
4214
|
+
// packages/core/src/lib/conversation-session-helpers.ts
|
|
4215
|
+
function formatTraitValue(value) {
|
|
4216
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
4217
|
+
return String(value);
|
|
4218
|
+
}
|
|
4219
|
+
try {
|
|
4220
|
+
return JSON.stringify(value, (_key, replacerValue) => {
|
|
4221
|
+
if (typeof replacerValue === "bigint") {
|
|
4222
|
+
return String(replacerValue);
|
|
4223
|
+
}
|
|
4224
|
+
return replacerValue;
|
|
4225
|
+
}) ?? String(value);
|
|
4226
|
+
} catch {
|
|
4227
|
+
return String(value);
|
|
4228
|
+
}
|
|
4229
|
+
}
|
|
4230
|
+
function buildProfilePrompt(context, traitGroups) {
|
|
4231
|
+
if (!context.profile || !context.profile.traits) {
|
|
4232
|
+
return null;
|
|
4233
|
+
}
|
|
4234
|
+
let filteredTraits;
|
|
4235
|
+
if (traitGroups !== void 0) {
|
|
4236
|
+
if (traitGroups.length === 0) {
|
|
4237
|
+
return null;
|
|
4238
|
+
}
|
|
4239
|
+
filteredTraits = Object.fromEntries(
|
|
4240
|
+
Object.entries(context.profile.traits).filter(
|
|
4241
|
+
([key, value]) => traitGroups.includes(key) && value != null
|
|
4242
|
+
)
|
|
4243
|
+
);
|
|
4244
|
+
} else {
|
|
4245
|
+
filteredTraits = Object.fromEntries(
|
|
4246
|
+
Object.entries(context.profile.traits).filter(([, value]) => value != null)
|
|
4247
|
+
);
|
|
4248
|
+
}
|
|
4249
|
+
if (Object.keys(filteredTraits).length === 0) {
|
|
4250
|
+
return null;
|
|
4251
|
+
}
|
|
4252
|
+
const lines = ["## Customer Profile", "Information about this customer:"];
|
|
4253
|
+
for (const [key, value] of Object.entries(filteredTraits)) {
|
|
4254
|
+
lines.push(`- ${key}: ${formatTraitValue(value)}`);
|
|
4255
|
+
}
|
|
4256
|
+
return lines.join("\n");
|
|
4257
|
+
}
|
|
4258
|
+
var conversationMetadataStates = /* @__PURE__ */ new WeakMap();
|
|
4259
|
+
function attachConversationMetadata(session, state) {
|
|
4260
|
+
const existing = conversationMetadataStates.get(session) ?? {};
|
|
4261
|
+
conversationMetadataStates.set(session, { ...existing, ...state });
|
|
4262
|
+
}
|
|
4263
|
+
async function conversationMetadata(session) {
|
|
4264
|
+
const state = conversationMetadataStates.get(session);
|
|
4265
|
+
if (state === void 0) {
|
|
4266
|
+
return {};
|
|
4267
|
+
}
|
|
4268
|
+
if (state.known === void 0 && state.loader !== void 0) {
|
|
4269
|
+
const loaded = await state.loader();
|
|
4270
|
+
if (loaded !== void 0) {
|
|
4271
|
+
state.known = loaded;
|
|
4272
|
+
}
|
|
4273
|
+
}
|
|
4274
|
+
return { ...state.known ?? {} };
|
|
4275
|
+
}
|
|
4276
|
+
|
|
4277
|
+
// packages/core/src/lib/deprecation.ts
|
|
4278
|
+
var warned = /* @__PURE__ */ new Set();
|
|
4279
|
+
function warnDeprecated(oldName, replacement) {
|
|
4280
|
+
if (warned.has(oldName)) return;
|
|
4281
|
+
warned.add(oldName);
|
|
4282
|
+
console.warn(`${oldName} is deprecated and will be removed in 3.0 \u2014 use ${replacement} instead.`);
|
|
4283
|
+
}
|
|
4284
|
+
|
|
4285
|
+
// packages/core/src/util/conversation-metadata.ts
|
|
4286
|
+
var CONVERSATION_METADATA_MAX_KEYS = 8;
|
|
4287
|
+
var CONVERSATION_METADATA_MAX_KEY_LENGTH = 128;
|
|
4288
|
+
var CONVERSATION_METADATA_MAX_VALUE_LENGTH = 512;
|
|
4289
|
+
var KEY_PATTERN = /^[a-zA-Z0-9._-]+$/;
|
|
4290
|
+
function fitConversationMetadata(metadata) {
|
|
4291
|
+
const persisted = {};
|
|
4292
|
+
const skippedKeys = [];
|
|
4293
|
+
let count = 0;
|
|
4294
|
+
for (const [key, value] of Object.entries(metadata ?? {})) {
|
|
4295
|
+
const fits = key.length <= CONVERSATION_METADATA_MAX_KEY_LENGTH && KEY_PATTERN.test(key) && typeof value === "string" && value.length <= CONVERSATION_METADATA_MAX_VALUE_LENGTH && count < CONVERSATION_METADATA_MAX_KEYS;
|
|
4296
|
+
if (fits) {
|
|
4297
|
+
persisted[key] = value;
|
|
4298
|
+
count += 1;
|
|
4299
|
+
} else {
|
|
4300
|
+
skippedKeys.push(key);
|
|
4301
|
+
}
|
|
4302
|
+
}
|
|
4303
|
+
return { persisted, skippedKeys };
|
|
4304
|
+
}
|
|
4305
|
+
|
|
4306
|
+
// packages/core/src/util/timestamps.ts
|
|
4307
|
+
function parseIso8601(value) {
|
|
4308
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
4309
|
+
return void 0;
|
|
4310
|
+
}
|
|
4311
|
+
const hasZone = /(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(value);
|
|
4312
|
+
const isDateTime = value.includes("T");
|
|
4313
|
+
const parsed = Date.parse(isDateTime && !hasZone ? `${value}Z` : value);
|
|
4314
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
4315
|
+
}
|
|
4316
|
+
function elapsedMs(start, end) {
|
|
4317
|
+
const startAt = parseIso8601(start);
|
|
4318
|
+
const endAt = parseIso8601(end);
|
|
4319
|
+
if (startAt === void 0 || endAt === void 0 || endAt < startAt) {
|
|
4320
|
+
return void 0;
|
|
4321
|
+
}
|
|
4322
|
+
return Math.trunc(endAt - startAt);
|
|
4323
|
+
}
|
|
4324
|
+
|
|
4325
|
+
// packages/core/src/channels/messaging.ts
|
|
4326
|
+
var AGENT_TYPES = /* @__PURE__ */ new Set(["AGENT", "AI_AGENT"]);
|
|
4327
|
+
var CHANNEL_IDENTITY_TYPES = {
|
|
4328
|
+
SMS: "phone",
|
|
4329
|
+
VOICE: "phone",
|
|
4330
|
+
RCS: "rcs",
|
|
4331
|
+
WHATSAPP: "whatsapp"
|
|
4332
|
+
};
|
|
4333
|
+
var MessagingChannel = class extends BaseChannel {
|
|
4334
|
+
conversationClient;
|
|
4335
|
+
messagingCallbacks;
|
|
4336
|
+
/**
|
|
4337
|
+
* Controls whether reconciliation promotes an UNKNOWN customer-side
|
|
4338
|
+
* participant to CUSTOMER. Subclasses override to opt out (e.g. chat).
|
|
4339
|
+
*/
|
|
4340
|
+
reconcileCustomerType = true;
|
|
4341
|
+
/**
|
|
4342
|
+
* Phone-like channels derive the agent address from the inbound webhook's
|
|
4343
|
+
* recipient (which of TAC's numbers was messaged). Chat uses a single identity
|
|
4344
|
+
* and opts out, keeping the default-address path.
|
|
4345
|
+
*/
|
|
4346
|
+
deriveInboundAgentFromRecipients = true;
|
|
4347
|
+
/**
|
|
4348
|
+
* The uppercase Conversation Orchestrator channel name for this channel (e.g.
|
|
4349
|
+
* `"SMS"`, `"RCS"`), used to filter webhook recipients and participant
|
|
4350
|
+
* addresses. Derived from {@link channelType}.
|
|
4351
|
+
*/
|
|
4352
|
+
getChannelName() {
|
|
4353
|
+
return this.channelType.toUpperCase();
|
|
3964
4354
|
}
|
|
3965
4355
|
constructor(tac, config) {
|
|
3966
|
-
|
|
4356
|
+
const onceDeprecated = config?.memoryMode === "once";
|
|
4357
|
+
super(tac, onceDeprecated ? { ...config, memoryMode: "always" } : config);
|
|
3967
4358
|
if (!tac.isOrchestratorEnabled()) {
|
|
3968
4359
|
throw new Error(
|
|
3969
4360
|
"Messaging channels require conversationConfigurationId to be configured. Voice-only mode does not support SMS or Chat channels."
|
|
3970
4361
|
);
|
|
3971
4362
|
}
|
|
4363
|
+
if (onceDeprecated) {
|
|
4364
|
+
const name = new.target.name;
|
|
4365
|
+
warnDeprecated(
|
|
4366
|
+
`memoryMode "once" on ${name}`,
|
|
4367
|
+
'memoryMode "always" (it runs as "always" until then; "once" is still supported on VoiceChannel)'
|
|
4368
|
+
);
|
|
4369
|
+
this.logger.warn(
|
|
4370
|
+
{ channel: name },
|
|
4371
|
+
`memoryMode "once" is deprecated on ${name} and will be removed in 3.0; running as "always". It caches a recall on a session that outlives one request, which messaging channels don't keep. ("once" is still supported on VoiceChannel.)`
|
|
4372
|
+
);
|
|
4373
|
+
}
|
|
3972
4374
|
this.conversationClient = tac.getConversationClient();
|
|
3973
4375
|
this.messagingCallbacks = {};
|
|
3974
4376
|
}
|
|
4377
|
+
/**
|
|
4378
|
+
* The agent-side address for `session`; what TAC's own paths call.
|
|
4379
|
+
*
|
|
4380
|
+
* Defaults to `getAgentAddress(session.conversationId)`, so a subclass
|
|
4381
|
+
* overriding only that keeps working. Channels whose address depends on
|
|
4382
|
+
* per-conversation data (chat's `channelId`) override this to read the
|
|
4383
|
+
* session directly.
|
|
4384
|
+
*/
|
|
4385
|
+
agentAddressFor(session) {
|
|
4386
|
+
return this.getAgentAddress(session.conversationId);
|
|
4387
|
+
}
|
|
4388
|
+
isOwnCoAddress(address) {
|
|
4389
|
+
return this.isDefaultAgentAddress(address);
|
|
4390
|
+
}
|
|
4391
|
+
/**
|
|
4392
|
+
* Messaging channels keep no sessions between webhooks, so there is nothing
|
|
4393
|
+
* to look up: always `undefined`.
|
|
4394
|
+
*
|
|
4395
|
+
* @deprecated Use the session `onMessageReady` (or
|
|
4396
|
+
* `initiateOutboundConversation`) hands you. Removed in 3.0.
|
|
4397
|
+
*/
|
|
4398
|
+
getConversationSession(_conversationId) {
|
|
4399
|
+
warnDeprecated(
|
|
4400
|
+
`${this.constructor.name}.getConversationSession()`,
|
|
4401
|
+
"the session passed to onMessageReady (messaging channels keep no sessions)"
|
|
4402
|
+
);
|
|
4403
|
+
return void 0;
|
|
4404
|
+
}
|
|
4405
|
+
/**
|
|
4406
|
+
* Messaging channels keep no sessions between webhooks: always `false`.
|
|
4407
|
+
*
|
|
4408
|
+
* @deprecated Messaging channels are stateless; track conversations in your
|
|
4409
|
+
* own store, keyed by `conversationId`. Removed in 3.0.
|
|
4410
|
+
*/
|
|
4411
|
+
isConversationActive(_conversationId) {
|
|
4412
|
+
warnDeprecated(
|
|
4413
|
+
`${this.constructor.name}.isConversationActive()`,
|
|
4414
|
+
"your own store keyed by conversationId (messaging channels keep no sessions)"
|
|
4415
|
+
);
|
|
4416
|
+
return false;
|
|
4417
|
+
}
|
|
3975
4418
|
/**
|
|
3976
4419
|
* Report a delivered response.
|
|
3977
4420
|
*
|
|
@@ -3988,36 +4431,215 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3988
4431
|
});
|
|
3989
4432
|
}
|
|
3990
4433
|
/**
|
|
3991
|
-
*
|
|
4434
|
+
* Whether the author is TAC, judged from an already-fetched participant list.
|
|
3992
4435
|
*
|
|
3993
|
-
*
|
|
3994
|
-
*
|
|
4436
|
+
* The caller does the free check (author address is a configured agent
|
|
4437
|
+
* address) first; this catches TAC speaking from some other address.
|
|
3995
4438
|
*/
|
|
3996
|
-
|
|
3997
|
-
if (
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4439
|
+
isOwnMessage(authorParticipantId, participants, conversationId) {
|
|
4440
|
+
if (!authorParticipantId) return false;
|
|
4441
|
+
const author = participants.find((p) => p.id === authorParticipantId);
|
|
4442
|
+
if (!author) return false;
|
|
4443
|
+
if (author.type === void 0) {
|
|
4444
|
+
this.logger.warn(
|
|
4445
|
+
{ conversation_id: conversationId, participant_id: authorParticipantId },
|
|
4446
|
+
"Participant type is undefined \u2014 cannot determine if this is an agent message"
|
|
4447
|
+
);
|
|
4448
|
+
}
|
|
4449
|
+
return author.type !== void 0 && AGENT_TYPES.has(author.type);
|
|
4450
|
+
}
|
|
4451
|
+
/**
|
|
4452
|
+
* Fetch a conversation's participants, returning `null` on failure.
|
|
4453
|
+
*
|
|
4454
|
+
* One call per inbound message, shared by the self-message check,
|
|
4455
|
+
* reconciliation, and profile resolution. None of them can proceed without
|
|
4456
|
+
* it, so a failure is a hard stop for the caller.
|
|
4457
|
+
*/
|
|
4458
|
+
async listParticipantsOrNull(conversationId) {
|
|
4459
|
+
try {
|
|
4460
|
+
return await this.conversationClient.listParticipants(conversationId);
|
|
4461
|
+
} catch (error) {
|
|
4462
|
+
this.logger.error(
|
|
4463
|
+
{ err: error, conversation_id: conversationId },
|
|
4464
|
+
"Failed to list participants"
|
|
4465
|
+
);
|
|
4466
|
+
return null;
|
|
4467
|
+
}
|
|
4468
|
+
}
|
|
4469
|
+
/**
|
|
4470
|
+
* Build an Actions API participant reference.
|
|
4471
|
+
*
|
|
4472
|
+
* Conversation Orchestrator resolves by participant id or by explicit
|
|
4473
|
+
* `(channel, address)`. Prefer the id — reconciliation has already
|
|
4474
|
+
* established it — and fall back to the address when there isn't one.
|
|
4475
|
+
*/
|
|
4476
|
+
participantRef(address, participantId) {
|
|
4477
|
+
const channel = this.getChannelName();
|
|
4478
|
+
if (participantId) {
|
|
4479
|
+
return { channel, participantId };
|
|
4480
|
+
}
|
|
4481
|
+
return { channel, ...address ? { address } : {} };
|
|
4482
|
+
}
|
|
4483
|
+
/** A fresh, empty session for one turn of `conversationId` on this channel. */
|
|
4484
|
+
newSession(conversationId) {
|
|
4485
|
+
return {
|
|
4486
|
+
conversationId,
|
|
4487
|
+
channel: this.channelType,
|
|
4488
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
4489
|
+
metadata: {}
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
4492
|
+
/** Whether `p` holds `address` on `channel`. */
|
|
4493
|
+
ownsAddress(p, channel, address) {
|
|
4494
|
+
return Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel && a.address === address);
|
|
4495
|
+
}
|
|
4496
|
+
/**
|
|
4497
|
+
* Build a session for a conversation from its participants.
|
|
4498
|
+
*
|
|
4499
|
+
* Used where no inbound webhook is in hand: a CLOSED webhook, or
|
|
4500
|
+
* `sendResponse` given a bare id. Returns `null` when no participant is on
|
|
4501
|
+
* this channel, which is how another channel's conversation is filtered out.
|
|
4502
|
+
*/
|
|
4503
|
+
sessionFromParticipants(conversationId, participants) {
|
|
4504
|
+
const channel = this.getChannelName();
|
|
4505
|
+
const matchesChannel = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel);
|
|
4506
|
+
if (!participants.some(matchesChannel)) {
|
|
4507
|
+
return null;
|
|
4508
|
+
}
|
|
4509
|
+
const session = this.newSession(conversationId);
|
|
4510
|
+
const owned = this.deriveInboundAgentFromRecipients ? this.ownedAgentAddress(participants, channel) : void 0;
|
|
4511
|
+
const agentAddress = owned ?? this.agentAddressFor(session).address;
|
|
4512
|
+
const agent = participants.find(
|
|
4513
|
+
(p) => p.type !== void 0 && AGENT_TYPES.has(p.type) && this.ownsAddress(p, channel, agentAddress)
|
|
4514
|
+
);
|
|
4515
|
+
session.aiAgentInfo = {
|
|
4516
|
+
address: agentAddress,
|
|
4517
|
+
...agent ? { participantId: agent.id } : {}
|
|
4518
|
+
};
|
|
4519
|
+
const customer = participants.find(
|
|
4520
|
+
(p) => p.type === "CUSTOMER" && matchesChannel(p) && !this.ownsAddress(p, channel, agentAddress)
|
|
4521
|
+
);
|
|
4522
|
+
if (customer) {
|
|
4523
|
+
if (customer.profileId) {
|
|
4524
|
+
session.profileId = customer.profileId;
|
|
4525
|
+
}
|
|
4526
|
+
const customerAddress = customer.addresses.find((a) => a.channel === channel)?.address;
|
|
4527
|
+
if (customerAddress) {
|
|
4528
|
+
session.authorInfo = { address: customerAddress, participantId: customer.id };
|
|
4529
|
+
}
|
|
4530
|
+
}
|
|
4531
|
+
return session;
|
|
4532
|
+
}
|
|
4533
|
+
/**
|
|
4534
|
+
* Resolve the session a `sendResponse` call replies within.
|
|
4535
|
+
*
|
|
4536
|
+
* A session is used as-is — it already carries both participants. A bare id
|
|
4537
|
+
* costs a `listParticipants` call to rebuild one, since the channel keeps no
|
|
4538
|
+
* session to look up.
|
|
4539
|
+
*
|
|
4540
|
+
* @throws If the participants can't be read, or no recipient resolves.
|
|
4541
|
+
*/
|
|
4542
|
+
async resolveSendSession(target) {
|
|
4543
|
+
const label = this.getChannelName();
|
|
4544
|
+
let session;
|
|
4545
|
+
if (typeof target === "string") {
|
|
4546
|
+
const participants = await this.listParticipantsOrNull(target);
|
|
4547
|
+
if (participants === null) {
|
|
4548
|
+
throw new Error(
|
|
4549
|
+
`Unable to send ${label} message: could not read participants for conversation ${target}. Pass the ConversationSession from onMessageReady or initiateOutboundConversation to avoid this lookup.`
|
|
4017
4550
|
);
|
|
4018
4551
|
}
|
|
4552
|
+
session = this.sessionFromParticipants(target, participants);
|
|
4553
|
+
} else {
|
|
4554
|
+
session = target;
|
|
4019
4555
|
}
|
|
4020
|
-
|
|
4556
|
+
if (!session?.authorInfo) {
|
|
4557
|
+
const conversationId = typeof target === "string" ? target : target.conversationId;
|
|
4558
|
+
throw new Error(
|
|
4559
|
+
`Unable to send ${label} message: no recipient resolved for conversation ${conversationId}. Pass the ConversationSession you were handed by onMessageReady or initiateOutboundConversation.`
|
|
4560
|
+
);
|
|
4561
|
+
}
|
|
4562
|
+
return session;
|
|
4563
|
+
}
|
|
4564
|
+
/**
|
|
4565
|
+
* The `channelSettings` for a reply within `session`, if any.
|
|
4566
|
+
*
|
|
4567
|
+
* Default (SMS, RCS, WhatsApp): `channelId` is optional and passed through
|
|
4568
|
+
* when the session carries one. Chat overrides this, since `channelId` is
|
|
4569
|
+
* required for delivery there.
|
|
4570
|
+
*/
|
|
4571
|
+
buildChannelSettings(session) {
|
|
4572
|
+
const channelId = session.metadata?.channelId;
|
|
4573
|
+
return typeof channelId === "string" && channelId ? { channelId } : void 0;
|
|
4574
|
+
}
|
|
4575
|
+
/**
|
|
4576
|
+
* Send a text response using the Conversation Orchestrator Actions API
|
|
4577
|
+
* (SEND_MESSAGE).
|
|
4578
|
+
*
|
|
4579
|
+
* **Pass the session, not the id.** Hand back the one `onMessageReady` gave
|
|
4580
|
+
* you (or that `initiateOutboundConversation` returned) and the send costs no
|
|
4581
|
+
* extra API call — it already carries both participants. A bare id still
|
|
4582
|
+
* works, but the channel keeps no session to look up, so it spends a
|
|
4583
|
+
* `listParticipants` call rebuilding one.
|
|
4584
|
+
*
|
|
4585
|
+
* @param conversationIdOrSession - The `ConversationSession` to reply within
|
|
4586
|
+
* (preferred), or the conversation id.
|
|
4587
|
+
* @param message - Message content.
|
|
4588
|
+
* @param metadata - Optional metadata, passed to `onError` on failure.
|
|
4589
|
+
* @throws If no recipient can be resolved for the conversation, or the send
|
|
4590
|
+
* fails.
|
|
4591
|
+
*/
|
|
4592
|
+
async sendResponse(conversationIdOrSession, message, metadata) {
|
|
4593
|
+
const conversationId = typeof conversationIdOrSession === "string" ? conversationIdOrSession : conversationIdOrSession.conversationId;
|
|
4594
|
+
const label = this.getChannelName();
|
|
4595
|
+
this.logger.debug(
|
|
4596
|
+
{
|
|
4597
|
+
conversation_id: conversationId,
|
|
4598
|
+
message_length: message.length,
|
|
4599
|
+
operation: "send_response"
|
|
4600
|
+
},
|
|
4601
|
+
`Sending ${label} response`
|
|
4602
|
+
);
|
|
4603
|
+
try {
|
|
4604
|
+
const session = await this.resolveSendSession(conversationIdOrSession);
|
|
4605
|
+
const channelSettings = this.buildChannelSettings(session);
|
|
4606
|
+
const agentAddress = session.aiAgentInfo?.address ?? this.agentAddressFor(session).address;
|
|
4607
|
+
this.logger.debug(
|
|
4608
|
+
{
|
|
4609
|
+
conversation_id: conversationId,
|
|
4610
|
+
recipient_address: maskAddress(session.authorInfo.address),
|
|
4611
|
+
recipient_participant_id: session.authorInfo.participantId,
|
|
4612
|
+
agent_participant_id: session.aiAgentInfo?.participantId
|
|
4613
|
+
},
|
|
4614
|
+
`Sending ${label} via Actions API`
|
|
4615
|
+
);
|
|
4616
|
+
const actionRequest = {
|
|
4617
|
+
type: "SEND_MESSAGE",
|
|
4618
|
+
payload: {
|
|
4619
|
+
from: this.participantRef(agentAddress, session.aiAgentInfo?.participantId),
|
|
4620
|
+
to: [this.participantRef(session.authorInfo.address, session.authorInfo.participantId)],
|
|
4621
|
+
content: { text: message },
|
|
4622
|
+
...channelSettings ? { channelSettings } : {}
|
|
4623
|
+
}
|
|
4624
|
+
};
|
|
4625
|
+
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4626
|
+
this.logger.info(
|
|
4627
|
+
{
|
|
4628
|
+
conversation_id: conversationId,
|
|
4629
|
+
recipient_address: maskAddress(session.authorInfo.address)
|
|
4630
|
+
},
|
|
4631
|
+
`${label} message sent successfully via Actions API`
|
|
4632
|
+
);
|
|
4633
|
+
} catch (error) {
|
|
4634
|
+
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4635
|
+
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4636
|
+
conversationId,
|
|
4637
|
+
message,
|
|
4638
|
+
metadata
|
|
4639
|
+
});
|
|
4640
|
+
throw error;
|
|
4641
|
+
}
|
|
4642
|
+
this.trackResponseSent(conversationId);
|
|
4021
4643
|
}
|
|
4022
4644
|
/**
|
|
4023
4645
|
* Register event callbacks (override for messaging-specific events)
|
|
@@ -4026,12 +4648,31 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4026
4648
|
on(event, callback) {
|
|
4027
4649
|
if (event === "messageReceived") {
|
|
4028
4650
|
this.messagingCallbacks.onMessageReceived = callback;
|
|
4651
|
+
} else if (event === "conversationStarted") {
|
|
4652
|
+
warnDeprecated(
|
|
4653
|
+
`${this.constructor.name}.on('conversationStarted')`,
|
|
4654
|
+
"tac.onMessageReady (messaging channels keep no sessions, so 'conversationStarted' never fires)"
|
|
4655
|
+
);
|
|
4029
4656
|
} else {
|
|
4030
4657
|
super.on(event, callback);
|
|
4031
4658
|
}
|
|
4032
4659
|
}
|
|
4033
4660
|
/**
|
|
4034
|
-
* Process messaging channel webhook from Conversation Orchestrator
|
|
4661
|
+
* Process messaging channel webhook from Conversation Orchestrator.
|
|
4662
|
+
*
|
|
4663
|
+
* Handles:
|
|
4664
|
+
*
|
|
4665
|
+
* - `COMMUNICATION_CREATED`: process an incoming message from the customer
|
|
4666
|
+
* - `CONVERSATION_UPDATED`: fire `onConversationEnded` and report
|
|
4667
|
+
* "Conversation Ended" when the conversation closes
|
|
4668
|
+
* - `PARTICIPANT_ADDED`: report "Conversation Started" when the customer
|
|
4669
|
+
* joins on this channel
|
|
4670
|
+
*
|
|
4671
|
+
* Any replica can handle any webhook. The idempotency cache is per-process,
|
|
4672
|
+
* though, so a Twilio retry landing on a different replica is processed
|
|
4673
|
+
* again, and `onMessageReady` can run twice for the same message. Retries
|
|
4674
|
+
* are rare when the webhook is acknowledged before processing, as
|
|
4675
|
+
* `TACServer` does.
|
|
4035
4676
|
*/
|
|
4036
4677
|
async processWebhook(payload, idempotencyToken) {
|
|
4037
4678
|
try {
|
|
@@ -4042,11 +4683,10 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4042
4683
|
const { webhookData, eventType, conversationId } = result;
|
|
4043
4684
|
switch (eventType) {
|
|
4044
4685
|
case "CONVERSATION_CREATED":
|
|
4045
|
-
this.logger.debug(
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
);
|
|
4049
|
-
this.handleConversationCreated(webhookData);
|
|
4686
|
+
this.logger.debug({ conversation_id: conversationId }, "Ignoring CONVERSATION_CREATED");
|
|
4687
|
+
break;
|
|
4688
|
+
case "PARTICIPANT_ADDED":
|
|
4689
|
+
this.trackConversationStarted(webhookData.data);
|
|
4050
4690
|
break;
|
|
4051
4691
|
case "COMMUNICATION_CREATED":
|
|
4052
4692
|
this.logger.debug({ conversation_id: conversationId }, "Handling COMMUNICATION_CREATED");
|
|
@@ -4078,19 +4718,54 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4078
4718
|
}
|
|
4079
4719
|
}
|
|
4080
4720
|
/**
|
|
4081
|
-
*
|
|
4721
|
+
* A loader that fetches a conversation's CO metadata, for
|
|
4722
|
+
* `conversationMetadata(session)`. The session keeps the result, so for its
|
|
4723
|
+
* turn only.
|
|
4082
4724
|
*/
|
|
4083
|
-
|
|
4084
|
-
|
|
4725
|
+
coMetadataLoader(conversationId) {
|
|
4726
|
+
return async () => {
|
|
4727
|
+
try {
|
|
4728
|
+
const conversation = await this.conversationClient.getConversation(conversationId);
|
|
4729
|
+
return { ...conversation.metadata ?? {} };
|
|
4730
|
+
} catch (error) {
|
|
4731
|
+
this.logger.warn(
|
|
4732
|
+
{ err: error, conversation_id: conversationId },
|
|
4733
|
+
"Failed to fetch conversation metadata"
|
|
4734
|
+
);
|
|
4735
|
+
return void 0;
|
|
4736
|
+
}
|
|
4737
|
+
};
|
|
4738
|
+
}
|
|
4739
|
+
/**
|
|
4740
|
+
* Build this request's session from the webhook payload and config.
|
|
4741
|
+
*
|
|
4742
|
+
* Network-free — the author, the agent address and `channelId` are all in
|
|
4743
|
+
* hand already. Reconciliation layers the participant ids on after.
|
|
4744
|
+
* `inboundAgentAddress` is the sender the customer messaged, when the webhook
|
|
4745
|
+
* names it; otherwise the channel default stands in until the caller
|
|
4746
|
+
* resolves it.
|
|
4747
|
+
*/
|
|
4748
|
+
resolveSession(conversationId, payload, inboundAgentAddress) {
|
|
4749
|
+
const session = this.newSession(conversationId);
|
|
4085
4750
|
const profileId = this.extractProfileId(payload);
|
|
4086
|
-
if (
|
|
4087
|
-
|
|
4088
|
-
{ operation: "handle_conversation_created" },
|
|
4089
|
-
"Missing conversation ID in conversation.created event"
|
|
4090
|
-
);
|
|
4091
|
-
throw new Error("Missing conversation ID in conversation.created event");
|
|
4751
|
+
if (profileId) {
|
|
4752
|
+
session.profileId = profileId;
|
|
4092
4753
|
}
|
|
4093
|
-
|
|
4754
|
+
if (payload.data?.serviceId) {
|
|
4755
|
+
session.serviceId = payload.data.serviceId;
|
|
4756
|
+
}
|
|
4757
|
+
session.authorInfo = {
|
|
4758
|
+
address: payload.data?.author?.address || "unknown",
|
|
4759
|
+
...payload.data?.author?.participantId ? { participantId: payload.data.author.participantId } : {}
|
|
4760
|
+
};
|
|
4761
|
+
if (payload.data?.channelId) {
|
|
4762
|
+
session.metadata.channelId = payload.data.channelId;
|
|
4763
|
+
}
|
|
4764
|
+
session.aiAgentInfo = {
|
|
4765
|
+
address: inboundAgentAddress ?? this.agentAddressFor(session).address
|
|
4766
|
+
};
|
|
4767
|
+
attachConversationMetadata(session, { loader: this.coMetadataLoader(conversationId) });
|
|
4768
|
+
return session;
|
|
4094
4769
|
}
|
|
4095
4770
|
/**
|
|
4096
4771
|
* Handle new communication event (incoming message)
|
|
@@ -4121,23 +4796,9 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4121
4796
|
this.logger.info({ conversation_id: conversationId }, "Ignoring empty message");
|
|
4122
4797
|
return;
|
|
4123
4798
|
}
|
|
4124
|
-
|
|
4125
|
-
if (communicationId) {
|
|
4126
|
-
const session2 = this.getConversationSession(conversationId);
|
|
4127
|
-
if (session2?.metadata?.lastCommunicationId === communicationId) {
|
|
4128
|
-
this.logger.debug(
|
|
4129
|
-
{ conversation_id: conversationId, communication_id: communicationId },
|
|
4130
|
-
"Skipping already-processed communication"
|
|
4131
|
-
);
|
|
4132
|
-
return;
|
|
4133
|
-
}
|
|
4134
|
-
}
|
|
4135
|
-
if (await this.isOwnMessage(author, conversationId, payload.data?.author?.participantId)) {
|
|
4799
|
+
if (this.isDefaultAgentAddress(author)) {
|
|
4136
4800
|
this.logger.info(
|
|
4137
|
-
{
|
|
4138
|
-
conversation_id: conversationId,
|
|
4139
|
-
author_address: maskAddress(author)
|
|
4140
|
-
},
|
|
4801
|
+
{ conversation_id: conversationId, author_address: maskAddress(author) },
|
|
4141
4802
|
"Ignoring message from AI agent"
|
|
4142
4803
|
);
|
|
4143
4804
|
return;
|
|
@@ -4154,104 +4815,55 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4154
4815
|
)?.address;
|
|
4155
4816
|
if (matched === void 0) {
|
|
4156
4817
|
const maskedRecipients = channelRecipients.map((r) => maskAddress(r.address ?? ""));
|
|
4157
|
-
const error = new Error("Inbound message to an unconfigured agent address; dropped");
|
|
4158
|
-
error.name = "UnconfiguredAgentAddressError";
|
|
4159
|
-
this.logger.error(
|
|
4160
|
-
{
|
|
4161
|
-
conversation_id: conversationId,
|
|
4162
|
-
channel: channelName,
|
|
4163
|
-
recipients: maskedRecipients
|
|
4164
|
-
},
|
|
4165
|
-
"Inbound message addressed to a number not in this channel's configured set; dropping"
|
|
4166
|
-
);
|
|
4167
|
-
this.handleError(error, {
|
|
4168
|
-
conversation_id: conversationId,
|
|
4169
|
-
channel: channelName,
|
|
4170
|
-
dropped_inbound: true,
|
|
4171
|
-
recipients: maskedRecipients
|
|
4172
|
-
});
|
|
4173
|
-
return;
|
|
4174
|
-
}
|
|
4175
|
-
inboundAgentAddress = { channel: channelName, address: matched };
|
|
4176
|
-
}
|
|
4177
|
-
}
|
|
4178
|
-
if (!this.isConversationActive(conversationId)) {
|
|
4179
|
-
this.logger.debug({ conversation_id: conversationId }, "Starting new conversation");
|
|
4180
|
-
this.startConversation(conversationId, profileId ?? void 0, payload.data?.serviceId);
|
|
4181
|
-
} else if (payload.data?.serviceId) {
|
|
4182
|
-
const session2 = this.getConversationSession(conversationId);
|
|
4183
|
-
if (session2 && session2.serviceId !== payload.data.serviceId) {
|
|
4184
|
-
this.logger.debug(
|
|
4185
|
-
{
|
|
4186
|
-
conversation_id: conversationId,
|
|
4187
|
-
old_service_id: session2.serviceId,
|
|
4188
|
-
new_service_id: payload.data.serviceId
|
|
4189
|
-
},
|
|
4190
|
-
"Updating conversation configuration ID from communication.created"
|
|
4191
|
-
);
|
|
4192
|
-
session2.serviceId = payload.data.serviceId;
|
|
4193
|
-
}
|
|
4194
|
-
}
|
|
4195
|
-
const session = this.getConversationSession(conversationId);
|
|
4196
|
-
if (session) {
|
|
4197
|
-
session.authorInfo = {
|
|
4198
|
-
address: author,
|
|
4199
|
-
participantId: payload.data?.author?.participantId
|
|
4200
|
-
};
|
|
4201
|
-
if (payload.data?.channelId) {
|
|
4202
|
-
if (!session.metadata) {
|
|
4203
|
-
session.metadata = {};
|
|
4204
|
-
}
|
|
4205
|
-
session.metadata.channelId = payload.data.channelId;
|
|
4206
|
-
this.logger.debug(
|
|
4207
|
-
{ conversation_id: conversationId, channel_id: payload.data.channelId },
|
|
4208
|
-
"Stored channelId in session metadata"
|
|
4209
|
-
);
|
|
4210
|
-
}
|
|
4211
|
-
if (communicationId) {
|
|
4212
|
-
if (!session.metadata) {
|
|
4213
|
-
session.metadata = {};
|
|
4214
|
-
}
|
|
4215
|
-
session.metadata.lastCommunicationId = communicationId;
|
|
4216
|
-
}
|
|
4217
|
-
if (!session.aiAgentInfo) {
|
|
4218
|
-
const resolved = await this.reconcileParticipants(conversationId, inboundAgentAddress);
|
|
4219
|
-
if (!resolved) {
|
|
4220
|
-
const error = new Error(
|
|
4221
|
-
`Participant reconciliation failed for conversation ${conversationId}; inbound message dropped because no sendable participants could be resolved.`
|
|
4818
|
+
const error = new Error("Inbound message to an unconfigured agent address; dropped");
|
|
4819
|
+
error.name = "UnconfiguredAgentAddressError";
|
|
4820
|
+
this.logger.error(
|
|
4821
|
+
{
|
|
4822
|
+
conversation_id: conversationId,
|
|
4823
|
+
channel: channelName,
|
|
4824
|
+
recipients: maskedRecipients
|
|
4825
|
+
},
|
|
4826
|
+
"Inbound message addressed to a number not in this channel's configured set; dropping"
|
|
4222
4827
|
);
|
|
4223
|
-
error.name = "ParticipantReconciliationError";
|
|
4224
4828
|
this.handleError(error, {
|
|
4225
4829
|
conversation_id: conversationId,
|
|
4226
|
-
channel:
|
|
4830
|
+
channel: channelName,
|
|
4227
4831
|
dropped_inbound: true,
|
|
4228
|
-
|
|
4832
|
+
recipients: maskedRecipients
|
|
4229
4833
|
});
|
|
4230
4834
|
return;
|
|
4231
4835
|
}
|
|
4232
|
-
|
|
4233
|
-
const agentAddrValue = inboundAgentAddress !== void 0 ? inboundAgentAddress.address : agentParticipant.addresses.find((a) => a.channel === channelName)?.address;
|
|
4234
|
-
session.aiAgentInfo = {
|
|
4235
|
-
address: agentAddrValue ?? this.getAgentAddress(conversationId).address,
|
|
4236
|
-
participantId: agentParticipant.id
|
|
4237
|
-
};
|
|
4238
|
-
if (customerParticipant && session.authorInfo) {
|
|
4239
|
-
session.authorInfo.participantId = customerParticipant.id;
|
|
4240
|
-
if (customerParticipant.profileId && !session.profileId) {
|
|
4241
|
-
session.profileId = customerParticipant.profileId;
|
|
4242
|
-
}
|
|
4243
|
-
}
|
|
4836
|
+
inboundAgentAddress = matched;
|
|
4244
4837
|
}
|
|
4245
4838
|
}
|
|
4246
|
-
const
|
|
4839
|
+
const session = this.resolveSession(conversationId, payload, inboundAgentAddress);
|
|
4840
|
+
const participants = await this.listParticipantsOrNull(conversationId);
|
|
4841
|
+
if (participants === null) {
|
|
4842
|
+
const error = new Error(
|
|
4843
|
+
`Could not read participants for conversation ${conversationId}; inbound message dropped.`
|
|
4844
|
+
);
|
|
4845
|
+
error.name = "ParticipantLookupError";
|
|
4846
|
+
this.handleError(error, {
|
|
4847
|
+
conversation_id: conversationId,
|
|
4848
|
+
channel: this.channelType,
|
|
4849
|
+
dropped_inbound: true,
|
|
4850
|
+
error_code: "participant_lookup_failed"
|
|
4851
|
+
});
|
|
4852
|
+
return;
|
|
4853
|
+
}
|
|
4854
|
+
if (!await this.resolveParticipants(session, payload, participants, inboundAgentAddress)) {
|
|
4855
|
+
return;
|
|
4856
|
+
}
|
|
4857
|
+
const userMemory = await this.retrieveMemoryIfEnabled(session, message);
|
|
4247
4858
|
if (this.messagingCallbacks.onMessageReceived) {
|
|
4248
4859
|
this.logger.debug({ conversation_id: conversationId }, "Invoking message received callback");
|
|
4249
4860
|
this.messagingCallbacks.onMessageReceived({
|
|
4250
4861
|
conversationId,
|
|
4251
|
-
profileId: session
|
|
4862
|
+
profileId: session.profileId,
|
|
4252
4863
|
message,
|
|
4253
4864
|
author,
|
|
4254
|
-
userMemory
|
|
4865
|
+
userMemory,
|
|
4866
|
+
session
|
|
4255
4867
|
});
|
|
4256
4868
|
}
|
|
4257
4869
|
trackEvent("Message Received", {
|
|
@@ -4261,22 +4873,121 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4261
4873
|
});
|
|
4262
4874
|
}
|
|
4263
4875
|
/**
|
|
4264
|
-
*
|
|
4876
|
+
* Resolve both sides of this turn from the participant list.
|
|
4877
|
+
*
|
|
4878
|
+
* Returns `false` when the message must not be answered: it's TAC's own, or
|
|
4879
|
+
* reconciliation failed (dropped, surfaced through `onError`).
|
|
4880
|
+
*/
|
|
4881
|
+
async resolveParticipants(session, payload, participants, inboundAgentAddress) {
|
|
4882
|
+
const conversationId = session.conversationId;
|
|
4883
|
+
const channel = this.getChannelName();
|
|
4884
|
+
if (this.isOwnMessage(payload.data?.author?.participantId, participants, conversationId)) {
|
|
4885
|
+
this.logger.info(
|
|
4886
|
+
{
|
|
4887
|
+
conversation_id: conversationId,
|
|
4888
|
+
author_address: maskAddress(session.authorInfo?.address ?? "")
|
|
4889
|
+
},
|
|
4890
|
+
"Ignoring message from AI agent"
|
|
4891
|
+
);
|
|
4892
|
+
return false;
|
|
4893
|
+
}
|
|
4894
|
+
if (inboundAgentAddress === void 0 && this.deriveInboundAgentFromRecipients) {
|
|
4895
|
+
session.aiAgentInfo = {
|
|
4896
|
+
address: this.fallbackAgentAddress(session, participants, channel).address
|
|
4897
|
+
};
|
|
4898
|
+
}
|
|
4899
|
+
const resolved = await this.reconcileParticipants(session, participants);
|
|
4900
|
+
if (!resolved) {
|
|
4901
|
+
const error = new Error(
|
|
4902
|
+
`Participant reconciliation failed for conversation ${conversationId}; inbound message dropped because no sendable participants could be resolved.`
|
|
4903
|
+
);
|
|
4904
|
+
error.name = "ParticipantReconciliationError";
|
|
4905
|
+
this.handleError(error, {
|
|
4906
|
+
conversation_id: conversationId,
|
|
4907
|
+
channel: this.channelType,
|
|
4908
|
+
dropped_inbound: true,
|
|
4909
|
+
error_code: "participant_reconciliation_failed"
|
|
4910
|
+
});
|
|
4911
|
+
return false;
|
|
4912
|
+
}
|
|
4913
|
+
const [agentParticipant, customerParticipant] = resolved;
|
|
4914
|
+
session.aiAgentInfo = {
|
|
4915
|
+
address: session.aiAgentInfo?.address ?? this.agentAddressFor(session).address,
|
|
4916
|
+
participantId: agentParticipant.id
|
|
4917
|
+
};
|
|
4918
|
+
if (customerParticipant && session.authorInfo) {
|
|
4919
|
+
session.authorInfo.participantId = customerParticipant.id;
|
|
4920
|
+
if (customerParticipant.profileId) {
|
|
4921
|
+
session.profileId = customerParticipant.profileId;
|
|
4922
|
+
}
|
|
4923
|
+
}
|
|
4924
|
+
if (session.profileId === void 0 && this.memoryMode !== "never") {
|
|
4925
|
+
const authorParticipantId = session.authorInfo?.participantId;
|
|
4926
|
+
const authorProfileId = authorParticipantId ? participants.find((p) => p.id === authorParticipantId)?.profileId : void 0;
|
|
4927
|
+
if (authorProfileId) {
|
|
4928
|
+
session.profileId = authorProfileId;
|
|
4929
|
+
}
|
|
4930
|
+
}
|
|
4931
|
+
return true;
|
|
4932
|
+
}
|
|
4933
|
+
/**
|
|
4934
|
+
* Handle conversation updated event.
|
|
4935
|
+
*
|
|
4936
|
+
* Only CLOSED is acted on: it reports "Conversation Ended", from the payload
|
|
4937
|
+
* alone and once across channels, and fires `onConversationEnded`. Only a
|
|
4938
|
+
* registered handler costs a participant lookup — shared with the other
|
|
4939
|
+
* channels handling the same webhook — which confirms the conversation is on
|
|
4940
|
+
* this channel (a CHAT close must not fire on SMS) and lets this work on
|
|
4941
|
+
* whichever replica Twilio picked.
|
|
4942
|
+
*
|
|
4943
|
+
* The session is rebuilt the same way on every replica. The conversation's
|
|
4944
|
+
* CO metadata is read through `conversationMetadata(session)`: answered from
|
|
4945
|
+
* the payload when it carries metadata, otherwise fetched on demand.
|
|
4265
4946
|
*/
|
|
4266
4947
|
async handleConversationUpdated(payload) {
|
|
4267
4948
|
const conversationId = this.extractConversationId(payload);
|
|
4268
4949
|
if (!conversationId) {
|
|
4269
4950
|
throw new Error("Missing conversation ID in conversation.updated event");
|
|
4270
4951
|
}
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
|
|
4274
|
-
|
|
4952
|
+
const data = payload.data ?? {};
|
|
4953
|
+
if (data.configurationId !== this.config.conversationConfigurationId) {
|
|
4954
|
+
return;
|
|
4955
|
+
}
|
|
4956
|
+
if (data.status !== "CLOSED") {
|
|
4957
|
+
return;
|
|
4958
|
+
}
|
|
4959
|
+
this.trackConversationEnded(
|
|
4960
|
+
conversationId,
|
|
4961
|
+
elapsedMs(
|
|
4962
|
+
typeof data.createdAt === "string" ? data.createdAt : void 0,
|
|
4963
|
+
typeof data.updatedAt === "string" ? data.updatedAt : void 0
|
|
4964
|
+
)
|
|
4965
|
+
);
|
|
4966
|
+
if (!this.hasConversationEndedHandler()) {
|
|
4967
|
+
return;
|
|
4968
|
+
}
|
|
4969
|
+
let participants;
|
|
4970
|
+
try {
|
|
4971
|
+
participants = await this.tac.listParticipantsShared(conversationId);
|
|
4972
|
+
} catch (error) {
|
|
4973
|
+
this.logger.error(
|
|
4974
|
+
{ err: error, conversation_id: conversationId },
|
|
4975
|
+
"Failed to list participants for a closed conversation"
|
|
4275
4976
|
);
|
|
4276
|
-
|
|
4277
|
-
}
|
|
4278
|
-
|
|
4977
|
+
return;
|
|
4978
|
+
}
|
|
4979
|
+
const session = this.sessionFromParticipants(conversationId, participants);
|
|
4980
|
+
if (session === null) {
|
|
4981
|
+
return;
|
|
4279
4982
|
}
|
|
4983
|
+
const parsed = ConversationResponseSchema.shape.metadata.safeParse(data.metadata);
|
|
4984
|
+
if (parsed.success && parsed.data !== void 0) {
|
|
4985
|
+
attachConversationMetadata(session, { known: parsed.data });
|
|
4986
|
+
} else {
|
|
4987
|
+
attachConversationMetadata(session, { loader: this.coMetadataLoader(conversationId) });
|
|
4988
|
+
}
|
|
4989
|
+
this.logger.debug({ conversation_id: conversationId }, "Conversation closed");
|
|
4990
|
+
await this.triggerConversationEnded(session);
|
|
4280
4991
|
}
|
|
4281
4992
|
/**
|
|
4282
4993
|
* Validate messaging channel webhook payload structure
|
|
@@ -4317,29 +5028,21 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4317
5028
|
* (via `session.authorInfo.participantId`), so promoting some other
|
|
4318
5029
|
* `UNKNOWN` CHAT participant could pick the wrong recipient.
|
|
4319
5030
|
*
|
|
4320
|
-
* @param
|
|
4321
|
-
*
|
|
4322
|
-
*
|
|
5031
|
+
* @param session - Supplies the conversation id and the agent address to
|
|
5032
|
+
* match on — the sender the customer messaged, already resolved on
|
|
5033
|
+
* `session.aiAgentInfo`.
|
|
5034
|
+
* @param participants - Already fetched by the caller; reusing that response
|
|
5035
|
+
* is what makes running this on every message free.
|
|
4323
5036
|
* @returns `[agent, customerOrNull]` on success. `customer` is `null` when
|
|
4324
5037
|
* `reconcileCustomerType` is `false`. `null` overall when either the agent
|
|
4325
5038
|
* or the customer cannot be resolved — the caller treats `null` as a hard
|
|
4326
5039
|
* stop and skips the message-ready callback.
|
|
4327
5040
|
*/
|
|
4328
|
-
async reconcileParticipants(
|
|
4329
|
-
|
|
4330
|
-
try {
|
|
4331
|
-
participants = await this.conversationClient.listParticipants(conversationId);
|
|
4332
|
-
} catch (error) {
|
|
4333
|
-
this.logger.error(
|
|
4334
|
-
{ err: error, conversation_id: conversationId },
|
|
4335
|
-
"Failed to list participants for reconciliation"
|
|
4336
|
-
);
|
|
4337
|
-
return null;
|
|
4338
|
-
}
|
|
5041
|
+
async reconcileParticipants(session, participants) {
|
|
5042
|
+
const conversationId = session.conversationId;
|
|
4339
5043
|
const channel = this.getChannelName();
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
}
|
|
5044
|
+
const baseAgentAddress = this.agentAddressFor(session);
|
|
5045
|
+
const agentAddress = session.aiAgentInfo ? { ...baseAgentAddress, address: session.aiAgentInfo.address } : baseAgentAddress;
|
|
4343
5046
|
const ownsAgentAddress = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel && a.address === agentAddress.address);
|
|
4344
5047
|
const matchesChannel = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel);
|
|
4345
5048
|
let agentCandidate = participants.find(ownsAgentAddress);
|
|
@@ -4399,8 +5102,9 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4399
5102
|
* on this channel; falls back to the channel default when none is present.
|
|
4400
5103
|
* Defensive path — the primary source is the webhook.
|
|
4401
5104
|
*/
|
|
4402
|
-
fallbackAgentAddress(
|
|
4403
|
-
const
|
|
5105
|
+
fallbackAgentAddress(session, participants, channel) {
|
|
5106
|
+
const conversationId = session.conversationId;
|
|
5107
|
+
const owned = this.ownedAgentAddress(participants, channel);
|
|
4404
5108
|
if (owned !== void 0) {
|
|
4405
5109
|
this.logger.warn(
|
|
4406
5110
|
{ conversation_id: conversationId, channel },
|
|
@@ -4412,7 +5116,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4412
5116
|
{ conversation_id: conversationId, channel },
|
|
4413
5117
|
"Inbound webhook had no channel recipient and no owned participant; using default agent address"
|
|
4414
5118
|
);
|
|
4415
|
-
return this.
|
|
5119
|
+
return this.agentAddressFor(session);
|
|
5120
|
+
}
|
|
5121
|
+
/**
|
|
5122
|
+
* The first of TAC's configured addresses on this channel that a participant
|
|
5123
|
+
* holds, if any.
|
|
5124
|
+
*/
|
|
5125
|
+
ownedAgentAddress(participants, channel) {
|
|
5126
|
+
return participants.flatMap((p) => Array.isArray(p.addresses) ? p.addresses : []).find((a) => a.channel === channel && this.isDefaultAgentAddress(a.address))?.address;
|
|
4416
5127
|
}
|
|
4417
5128
|
/**
|
|
4418
5129
|
* Find or mint a Conversation Memory profile for a customer being promoted from UNKNOWN.
|
|
@@ -4559,11 +5270,11 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4559
5270
|
}
|
|
4560
5271
|
isConflictError(error) {
|
|
4561
5272
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
4562
|
-
return
|
|
5273
|
+
return axios3.isAxiosError(cause) && cause.response?.status === 409;
|
|
4563
5274
|
}
|
|
4564
5275
|
extractConflictingResourceId(error) {
|
|
4565
5276
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
4566
|
-
if (!
|
|
5277
|
+
if (!axios3.isAxiosError(cause)) return void 0;
|
|
4567
5278
|
const headers = cause.response?.headers;
|
|
4568
5279
|
const id = headers?.["x-conflicting-resource-id"];
|
|
4569
5280
|
return typeof id === "string" && id.length > 0 ? id : void 0;
|
|
@@ -4571,8 +5282,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4571
5282
|
/**
|
|
4572
5283
|
* Shared outbound conversation initiation for messaging channels (SMS/RCS/Chat/WhatsApp).
|
|
4573
5284
|
*
|
|
4574
|
-
* Handles the full flow: create conversation → find participants →
|
|
4575
|
-
* session → send initial message → error cleanup.
|
|
5285
|
+
* Handles the full flow: create conversation → find participants → build
|
|
5286
|
+
* session → send initial message → error cleanup. The session isn't kept by
|
|
5287
|
+
* the channel; it is returned to the caller.
|
|
5288
|
+
*
|
|
5289
|
+
* `metadata` entries with string values that fit Conversation Orchestrator's
|
|
5290
|
+
* limits are stored on the conversation (at creation; merged with a `PATCH`
|
|
5291
|
+
* when an existing conversation is reused), so `conversationMetadata()` can
|
|
5292
|
+
* read them on any replica. The rest stay on the returned session only.
|
|
4576
5293
|
*/
|
|
4577
5294
|
async initiateOutboundMessagingConversation(params) {
|
|
4578
5295
|
const {
|
|
@@ -4586,6 +5303,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4586
5303
|
} = params;
|
|
4587
5304
|
let conversationId;
|
|
4588
5305
|
let conversationReused = false;
|
|
5306
|
+
const { persisted: coMetadata, skippedKeys } = fitConversationMetadata(metadata);
|
|
5307
|
+
const hasCoMetadata = Object.keys(coMetadata).length > 0;
|
|
5308
|
+
if (skippedKeys.length > 0) {
|
|
5309
|
+
this.logger.warn(
|
|
5310
|
+
{ skipped_keys: skippedKeys },
|
|
5311
|
+
"Outbound metadata not stored on the conversation: Conversation Orchestrator allows at most 8 keys of letters, digits, '.', '_' or '-', with string values up to 512 characters"
|
|
5312
|
+
);
|
|
5313
|
+
}
|
|
4589
5314
|
try {
|
|
4590
5315
|
const customerAddress = {
|
|
4591
5316
|
channel,
|
|
@@ -4597,15 +5322,38 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4597
5322
|
address: fromAddress,
|
|
4598
5323
|
...channelId ? { channelId } : {}
|
|
4599
5324
|
};
|
|
4600
|
-
const result = await this.conversationClient.createOrReuseConversation(
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
5325
|
+
const result = await this.conversationClient.createOrReuseConversation(
|
|
5326
|
+
[
|
|
5327
|
+
{ type: "CUSTOMER", addresses: [customerAddress] },
|
|
5328
|
+
{ type: "AI_AGENT", addresses: [agentAddress] }
|
|
5329
|
+
],
|
|
5330
|
+
// Omitted, not {}, so a send without metadata creates the conversation
|
|
5331
|
+
// exactly as before.
|
|
5332
|
+
hasCoMetadata ? coMetadata : void 0
|
|
5333
|
+
);
|
|
4604
5334
|
conversationId = result.conversation.id;
|
|
4605
5335
|
conversationReused = result.reused;
|
|
4606
5336
|
if (!isConversationId(conversationId)) {
|
|
4607
5337
|
throw new Error(`Invalid conversation ID returned: ${conversationId}`);
|
|
4608
5338
|
}
|
|
5339
|
+
let knownCoMetadata = coMetadata;
|
|
5340
|
+
if (conversationReused && !hasCoMetadata) {
|
|
5341
|
+
knownCoMetadata = void 0;
|
|
5342
|
+
} else if (conversationReused) {
|
|
5343
|
+
try {
|
|
5344
|
+
const patched = await this.conversationClient.patchConversationMetadata(
|
|
5345
|
+
conversationId,
|
|
5346
|
+
coMetadata
|
|
5347
|
+
);
|
|
5348
|
+
knownCoMetadata = { ...patched.metadata ?? {} };
|
|
5349
|
+
} catch (patchError) {
|
|
5350
|
+
this.logger.warn(
|
|
5351
|
+
{ err: patchError, conversation_id: conversationId },
|
|
5352
|
+
"Failed to store outbound metadata on the reused conversation"
|
|
5353
|
+
);
|
|
5354
|
+
knownCoMetadata = void 0;
|
|
5355
|
+
}
|
|
5356
|
+
}
|
|
4609
5357
|
const participants = await this.conversationClient.listParticipants(conversationId);
|
|
4610
5358
|
const customerParticipant = participants.find(
|
|
4611
5359
|
(p) => p.type === "CUSTOMER" && Array.isArray(p.addresses) && p.addresses.some(
|
|
@@ -4623,7 +5371,7 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4623
5371
|
if (!agentParticipant) {
|
|
4624
5372
|
throw new Error("Agent participant not found after conversation creation");
|
|
4625
5373
|
}
|
|
4626
|
-
const session = this.
|
|
5374
|
+
const session = this.newSession(conversationId);
|
|
4627
5375
|
session.authorInfo = {
|
|
4628
5376
|
address: to,
|
|
4629
5377
|
participantId: customerParticipant.id
|
|
@@ -4638,6 +5386,10 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4638
5386
|
direction: "outbound",
|
|
4639
5387
|
...channelId ? { channelId } : {}
|
|
4640
5388
|
};
|
|
5389
|
+
attachConversationMetadata(session, {
|
|
5390
|
+
...knownCoMetadata !== void 0 && { known: knownCoMetadata },
|
|
5391
|
+
loader: this.coMetadataLoader(conversationId)
|
|
5392
|
+
});
|
|
4641
5393
|
const actionRequest = {
|
|
4642
5394
|
type: "SEND_MESSAGE",
|
|
4643
5395
|
payload: {
|
|
@@ -4654,8 +5406,13 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4654
5406
|
);
|
|
4655
5407
|
return { conversationId, session };
|
|
4656
5408
|
} catch (error) {
|
|
4657
|
-
|
|
4658
|
-
|
|
5409
|
+
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
5410
|
+
const status = axios3.isAxiosError(cause) ? cause.response?.status : void 0;
|
|
5411
|
+
if (conversationId === void 0 && hasCoMetadata && status !== void 0 && status >= 400 && status < 500) {
|
|
5412
|
+
this.logger.warn(
|
|
5413
|
+
{ status, metadata_keys: Object.keys(coMetadata).sort() },
|
|
5414
|
+
"Conversation Orchestrator rejected creating the conversation; the request included conversation metadata, which may be the cause"
|
|
5415
|
+
);
|
|
4659
5416
|
}
|
|
4660
5417
|
if (conversationId && !conversationReused) {
|
|
4661
5418
|
await this.conversationClient.updateConversation(conversationId, "CLOSED").catch((closeErr) => {
|
|
@@ -4677,6 +5434,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4677
5434
|
|
|
4678
5435
|
// packages/core/src/channels/sms.ts
|
|
4679
5436
|
var SMSChannel = class extends MessagingChannel {
|
|
5437
|
+
constructor(tac, config) {
|
|
5438
|
+
super(tac, config);
|
|
5439
|
+
if (this.config.phoneNumbers.length === 0) {
|
|
5440
|
+
throw new Error(
|
|
5441
|
+
"phoneNumber(s) is required for SMS channel. Set TWILIO_PHONE_NUMBER / TWILIO_PHONE_NUMBERS or provide phoneNumber / phoneNumbers in TACConfig."
|
|
5442
|
+
);
|
|
5443
|
+
}
|
|
5444
|
+
}
|
|
4680
5445
|
get channelType() {
|
|
4681
5446
|
return "sms";
|
|
4682
5447
|
}
|
|
@@ -4684,85 +5449,12 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4684
5449
|
return this.config.phoneNumbers.includes(authorAddress);
|
|
4685
5450
|
}
|
|
4686
5451
|
getAgentAddress(_conversationId) {
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
* Send SMS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4691
|
-
*
|
|
4692
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4693
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4694
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4695
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4696
|
-
* both of which populate the session.
|
|
4697
|
-
*/
|
|
4698
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4699
|
-
this.logger.debug(
|
|
4700
|
-
{
|
|
4701
|
-
conversation_id: conversationId,
|
|
4702
|
-
message_length: message.length,
|
|
4703
|
-
operation: "send_response"
|
|
4704
|
-
},
|
|
4705
|
-
"Sending SMS response"
|
|
4706
|
-
);
|
|
4707
|
-
try {
|
|
4708
|
-
const session = this.getConversationSession(conversationId);
|
|
4709
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4710
|
-
throw new Error(
|
|
4711
|
-
`Unable to send SMS: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4712
|
-
);
|
|
4713
|
-
}
|
|
4714
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4715
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4716
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4717
|
-
throw new Error(
|
|
4718
|
-
`Unable to send SMS: session for conversation ${conversationId} is missing participant ids.`
|
|
4719
|
-
);
|
|
4720
|
-
}
|
|
4721
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4722
|
-
this.logger.debug(
|
|
4723
|
-
{
|
|
4724
|
-
conversation_id: conversationId,
|
|
4725
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4726
|
-
recipient_participant_id: customerParticipantId,
|
|
4727
|
-
agent_participant_id: agentParticipantId
|
|
4728
|
-
},
|
|
4729
|
-
"Sending SMS via Actions API"
|
|
4730
|
-
);
|
|
4731
|
-
const actionRequest = {
|
|
4732
|
-
type: "SEND_MESSAGE",
|
|
4733
|
-
payload: {
|
|
4734
|
-
from: {
|
|
4735
|
-
channel: "SMS",
|
|
4736
|
-
participantId: agentParticipantId
|
|
4737
|
-
},
|
|
4738
|
-
to: [
|
|
4739
|
-
{
|
|
4740
|
-
channel: "SMS",
|
|
4741
|
-
participantId: customerParticipantId
|
|
4742
|
-
}
|
|
4743
|
-
],
|
|
4744
|
-
content: { text: message },
|
|
4745
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
4746
|
-
}
|
|
4747
|
-
};
|
|
4748
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4749
|
-
this.logger.info(
|
|
4750
|
-
{
|
|
4751
|
-
conversation_id: conversationId,
|
|
4752
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
4753
|
-
},
|
|
4754
|
-
"SMS sent successfully via Actions API"
|
|
5452
|
+
if (!this.config.phoneNumber) {
|
|
5453
|
+
throw new Error(
|
|
5454
|
+
"phoneNumber is required for SMS channel. Set TWILIO_PHONE_NUMBER / TWILIO_PHONE_NUMBERS or provide phoneNumber / phoneNumbers in TACConfig."
|
|
4755
5455
|
);
|
|
4756
|
-
} catch (error) {
|
|
4757
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4758
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4759
|
-
conversationId,
|
|
4760
|
-
message,
|
|
4761
|
-
metadata
|
|
4762
|
-
});
|
|
4763
|
-
throw error;
|
|
4764
5456
|
}
|
|
4765
|
-
this.
|
|
5457
|
+
return { channel: "SMS", address: this.config.phoneNumber };
|
|
4766
5458
|
}
|
|
4767
5459
|
/**
|
|
4768
5460
|
* Initiate an outbound SMS conversation
|
|
@@ -4813,84 +5505,6 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4813
5505
|
}
|
|
4814
5506
|
return { channel: "RCS", address: this.config.rcsSenderId };
|
|
4815
5507
|
}
|
|
4816
|
-
/**
|
|
4817
|
-
* Send RCS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4818
|
-
*
|
|
4819
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4820
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4821
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4822
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4823
|
-
* both of which populate the session.
|
|
4824
|
-
*/
|
|
4825
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4826
|
-
this.logger.debug(
|
|
4827
|
-
{
|
|
4828
|
-
conversation_id: conversationId,
|
|
4829
|
-
message_length: message.length,
|
|
4830
|
-
operation: "send_response"
|
|
4831
|
-
},
|
|
4832
|
-
"Sending RCS response"
|
|
4833
|
-
);
|
|
4834
|
-
try {
|
|
4835
|
-
const session = this.getConversationSession(conversationId);
|
|
4836
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4837
|
-
throw new Error(
|
|
4838
|
-
`Unable to send RCS: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4839
|
-
);
|
|
4840
|
-
}
|
|
4841
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4842
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4843
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4844
|
-
throw new Error(
|
|
4845
|
-
`Unable to send RCS: session for conversation ${conversationId} is missing participant ids.`
|
|
4846
|
-
);
|
|
4847
|
-
}
|
|
4848
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4849
|
-
this.logger.debug(
|
|
4850
|
-
{
|
|
4851
|
-
conversation_id: conversationId,
|
|
4852
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4853
|
-
recipient_participant_id: customerParticipantId,
|
|
4854
|
-
agent_participant_id: agentParticipantId
|
|
4855
|
-
},
|
|
4856
|
-
"Sending RCS via Actions API"
|
|
4857
|
-
);
|
|
4858
|
-
const actionRequest = {
|
|
4859
|
-
type: "SEND_MESSAGE",
|
|
4860
|
-
payload: {
|
|
4861
|
-
from: {
|
|
4862
|
-
channel: "RCS",
|
|
4863
|
-
participantId: agentParticipantId
|
|
4864
|
-
},
|
|
4865
|
-
to: [
|
|
4866
|
-
{
|
|
4867
|
-
channel: "RCS",
|
|
4868
|
-
participantId: customerParticipantId
|
|
4869
|
-
}
|
|
4870
|
-
],
|
|
4871
|
-
content: { text: message },
|
|
4872
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
4873
|
-
}
|
|
4874
|
-
};
|
|
4875
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4876
|
-
this.logger.info(
|
|
4877
|
-
{
|
|
4878
|
-
conversation_id: conversationId,
|
|
4879
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
4880
|
-
},
|
|
4881
|
-
"RCS sent successfully via Actions API"
|
|
4882
|
-
);
|
|
4883
|
-
} catch (error) {
|
|
4884
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4885
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4886
|
-
conversationId,
|
|
4887
|
-
message,
|
|
4888
|
-
metadata
|
|
4889
|
-
});
|
|
4890
|
-
throw error;
|
|
4891
|
-
}
|
|
4892
|
-
this.trackResponseSent(conversationId);
|
|
4893
|
-
}
|
|
4894
5508
|
/**
|
|
4895
5509
|
* Initiate an outbound RCS conversation
|
|
4896
5510
|
*
|
|
@@ -4933,92 +5547,14 @@ var WhatsAppChannel = class extends MessagingChannel {
|
|
|
4933
5547
|
}
|
|
4934
5548
|
isDefaultAgentAddress(authorAddress) {
|
|
4935
5549
|
return this.config.whatsappNumbers.includes(authorAddress);
|
|
4936
|
-
}
|
|
4937
|
-
getAgentAddress(_conversationId) {
|
|
4938
|
-
if (!this.config.whatsappNumber) {
|
|
4939
|
-
throw new Error(
|
|
4940
|
-
"whatsappNumber is required for WhatsApp channel. Please set TWILIO_WHATSAPP_NUMBER environment variable or provide whatsappNumber in TACConfig."
|
|
4941
|
-
);
|
|
4942
|
-
}
|
|
4943
|
-
return { channel: "WHATSAPP", address: this.config.whatsappNumber };
|
|
4944
|
-
}
|
|
4945
|
-
/**
|
|
4946
|
-
* Send WhatsApp response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4947
|
-
*
|
|
4948
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4949
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4950
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4951
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4952
|
-
* both of which populate the session.
|
|
4953
|
-
*/
|
|
4954
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4955
|
-
this.logger.debug(
|
|
4956
|
-
{
|
|
4957
|
-
conversation_id: conversationId,
|
|
4958
|
-
message_length: message.length,
|
|
4959
|
-
operation: "send_response"
|
|
4960
|
-
},
|
|
4961
|
-
"Sending WhatsApp response"
|
|
4962
|
-
);
|
|
4963
|
-
try {
|
|
4964
|
-
const session = this.getConversationSession(conversationId);
|
|
4965
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4966
|
-
throw new Error(
|
|
4967
|
-
`Unable to send WhatsApp: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4968
|
-
);
|
|
4969
|
-
}
|
|
4970
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4971
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4972
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4973
|
-
throw new Error(
|
|
4974
|
-
`Unable to send WhatsApp: session for conversation ${conversationId} is missing participant ids.`
|
|
4975
|
-
);
|
|
4976
|
-
}
|
|
4977
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4978
|
-
this.logger.debug(
|
|
4979
|
-
{
|
|
4980
|
-
conversation_id: conversationId,
|
|
4981
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4982
|
-
recipient_participant_id: customerParticipantId,
|
|
4983
|
-
agent_participant_id: agentParticipantId
|
|
4984
|
-
},
|
|
4985
|
-
"Sending WhatsApp via Actions API"
|
|
4986
|
-
);
|
|
4987
|
-
const actionRequest = {
|
|
4988
|
-
type: "SEND_MESSAGE",
|
|
4989
|
-
payload: {
|
|
4990
|
-
from: {
|
|
4991
|
-
channel: "WHATSAPP",
|
|
4992
|
-
participantId: agentParticipantId
|
|
4993
|
-
},
|
|
4994
|
-
to: [
|
|
4995
|
-
{
|
|
4996
|
-
channel: "WHATSAPP",
|
|
4997
|
-
participantId: customerParticipantId
|
|
4998
|
-
}
|
|
4999
|
-
],
|
|
5000
|
-
content: { text: message },
|
|
5001
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
5002
|
-
}
|
|
5003
|
-
};
|
|
5004
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
5005
|
-
this.logger.info(
|
|
5006
|
-
{
|
|
5007
|
-
conversation_id: conversationId,
|
|
5008
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
5009
|
-
},
|
|
5010
|
-
"WhatsApp sent successfully via Actions API"
|
|
5550
|
+
}
|
|
5551
|
+
getAgentAddress(_conversationId) {
|
|
5552
|
+
if (!this.config.whatsappNumber) {
|
|
5553
|
+
throw new Error(
|
|
5554
|
+
"whatsappNumber is required for WhatsApp channel. Please set TWILIO_WHATSAPP_NUMBER environment variable or provide whatsappNumber in TACConfig."
|
|
5011
5555
|
);
|
|
5012
|
-
} catch (error) {
|
|
5013
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
5014
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
5015
|
-
conversationId,
|
|
5016
|
-
message,
|
|
5017
|
-
metadata
|
|
5018
|
-
});
|
|
5019
|
-
throw error;
|
|
5020
5556
|
}
|
|
5021
|
-
this.
|
|
5557
|
+
return { channel: "WHATSAPP", address: this.config.whatsappNumber };
|
|
5022
5558
|
}
|
|
5023
5559
|
/**
|
|
5024
5560
|
* Initiate an outbound WhatsApp conversation
|
|
@@ -5071,97 +5607,50 @@ var ChatChannel = class extends MessagingChannel {
|
|
|
5071
5607
|
isDefaultAgentAddress(authorAddress) {
|
|
5072
5608
|
return authorAddress === this.agentAddress;
|
|
5073
5609
|
}
|
|
5074
|
-
getAgentAddress(
|
|
5075
|
-
|
|
5076
|
-
|
|
5610
|
+
getAgentAddress(_conversationId) {
|
|
5611
|
+
return this.chatAddress(void 0);
|
|
5612
|
+
}
|
|
5613
|
+
agentAddressFor(session) {
|
|
5614
|
+
return this.chatAddress(session.metadata?.channelId);
|
|
5615
|
+
}
|
|
5616
|
+
chatAddress(channelId) {
|
|
5077
5617
|
return {
|
|
5078
5618
|
channel: "CHAT",
|
|
5079
5619
|
address: this.agentAddress,
|
|
5080
|
-
...channelId ? { channelId } : {}
|
|
5620
|
+
...typeof channelId === "string" && channelId ? { channelId } : {}
|
|
5081
5621
|
};
|
|
5082
5622
|
}
|
|
5083
5623
|
/**
|
|
5084
|
-
*
|
|
5624
|
+
* Rebuild the session, recovering `channelId` from the participants.
|
|
5085
5625
|
*
|
|
5086
|
-
*
|
|
5087
|
-
*
|
|
5088
|
-
*
|
|
5089
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
5090
|
-
* both of which populate the session.
|
|
5626
|
+
* A session rebuilt from a bare conversation id has no webhook to take
|
|
5627
|
+
* `channelId` from, so it's read off the customer's or agent's CHAT address
|
|
5628
|
+
* instead, where Conversation Orchestrator records it.
|
|
5091
5629
|
*/
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5630
|
+
sessionFromParticipants(conversationId, participants) {
|
|
5631
|
+
const session = super.sessionFromParticipants(conversationId, participants);
|
|
5632
|
+
if (session === null || session.metadata.channelId) {
|
|
5633
|
+
return session;
|
|
5634
|
+
}
|
|
5635
|
+
const ownIds = new Set(
|
|
5636
|
+
[session.authorInfo?.participantId, session.aiAgentInfo?.participantId].filter(
|
|
5637
|
+
(id) => Boolean(id)
|
|
5638
|
+
)
|
|
5100
5639
|
);
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
|
|
5108
|
-
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
`Unable to send chat message: session for conversation ${conversationId} is missing participant ids.`
|
|
5113
|
-
);
|
|
5114
|
-
}
|
|
5115
|
-
const chatChannelSid = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
5116
|
-
if (!chatChannelSid) {
|
|
5117
|
-
throw new Error(
|
|
5118
|
-
"Missing required session.metadata['channelId'] for chat sendResponse; this is normally populated by an inbound webhook. Ensure an inbound message has been processed before calling sendResponse, or set session.metadata['channelId'] explicitly in advanced usage."
|
|
5119
|
-
);
|
|
5120
|
-
}
|
|
5121
|
-
const channelSettings = {
|
|
5122
|
-
channelId: chatChannelSid
|
|
5123
|
-
};
|
|
5124
|
-
this.logger.debug(
|
|
5125
|
-
{
|
|
5126
|
-
conversation_id: conversationId,
|
|
5127
|
-
recipient_participant_id: customerParticipantId,
|
|
5128
|
-
agent_participant_id: agentParticipantId,
|
|
5129
|
-
channel_id: chatChannelSid
|
|
5130
|
-
},
|
|
5131
|
-
"Sending chat message via Actions API"
|
|
5132
|
-
);
|
|
5133
|
-
const actionRequest = {
|
|
5134
|
-
type: "SEND_MESSAGE",
|
|
5135
|
-
payload: {
|
|
5136
|
-
from: {
|
|
5137
|
-
channel: "CHAT",
|
|
5138
|
-
participantId: agentParticipantId
|
|
5139
|
-
},
|
|
5140
|
-
to: [
|
|
5141
|
-
{
|
|
5142
|
-
channel: "CHAT",
|
|
5143
|
-
participantId: customerParticipantId
|
|
5144
|
-
}
|
|
5145
|
-
],
|
|
5146
|
-
content: { text: message },
|
|
5147
|
-
channelSettings
|
|
5148
|
-
}
|
|
5149
|
-
};
|
|
5150
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
5151
|
-
this.logger.info(
|
|
5152
|
-
{ conversation_id: conversationId, channel_id: chatChannelSid },
|
|
5153
|
-
"Chat message sent successfully via Actions API"
|
|
5640
|
+
const channelId = participants.filter((p) => ownIds.has(p.id)).flatMap((p) => p.addresses).find((a) => a.channel === "CHAT" && a.channelId)?.channelId;
|
|
5641
|
+
if (channelId) {
|
|
5642
|
+
session.metadata.channelId = channelId;
|
|
5643
|
+
}
|
|
5644
|
+
return session;
|
|
5645
|
+
}
|
|
5646
|
+
buildChannelSettings(session) {
|
|
5647
|
+
const channelId = session.metadata?.channelId;
|
|
5648
|
+
if (typeof channelId !== "string" || !channelId) {
|
|
5649
|
+
throw new Error(
|
|
5650
|
+
"Missing required session.metadata['channelId'] for chat sendResponse. Pass the ConversationSession from onMessageReady or initiateOutboundConversation: a bare conversation id works only when the conversation's CHAT participants carry a channelId."
|
|
5154
5651
|
);
|
|
5155
|
-
} catch (error) {
|
|
5156
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
5157
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
5158
|
-
conversationId,
|
|
5159
|
-
message,
|
|
5160
|
-
metadata
|
|
5161
|
-
});
|
|
5162
|
-
throw error;
|
|
5163
5652
|
}
|
|
5164
|
-
|
|
5653
|
+
return { channelId };
|
|
5165
5654
|
}
|
|
5166
5655
|
/**
|
|
5167
5656
|
* Initiate an outbound chat conversation
|
|
@@ -5190,14 +5679,6 @@ var ChatChannel = class extends MessagingChannel {
|
|
|
5190
5679
|
}
|
|
5191
5680
|
};
|
|
5192
5681
|
|
|
5193
|
-
// packages/core/src/lib/deprecation.ts
|
|
5194
|
-
var warned = /* @__PURE__ */ new Set();
|
|
5195
|
-
function warnDeprecated(oldName, replacement) {
|
|
5196
|
-
if (warned.has(oldName)) return;
|
|
5197
|
-
warned.add(oldName);
|
|
5198
|
-
console.warn(`${oldName} is deprecated and will be removed in 3.0 \u2014 use ${replacement} instead.`);
|
|
5199
|
-
}
|
|
5200
|
-
|
|
5201
5682
|
// packages/core/src/channels/voice/provider.ts
|
|
5202
5683
|
var VoiceProvider = class {
|
|
5203
5684
|
/** The `VoiceChannel` that owns this provider. */
|
|
@@ -5228,6 +5709,20 @@ var VoiceProvider = class {
|
|
|
5228
5709
|
get channelName() {
|
|
5229
5710
|
return "VOICE";
|
|
5230
5711
|
}
|
|
5712
|
+
/**
|
|
5713
|
+
* Whether a Conversation Orchestrator `CLOSED` webhook will end this
|
|
5714
|
+
* provider's conversations.
|
|
5715
|
+
*
|
|
5716
|
+
* Decides who owns `onConversationEnded`. `false` (the default): no CO
|
|
5717
|
+
* conversation exists, so `VoiceChannel` fires it itself at teardown.
|
|
5718
|
+
* `true`: only `onCallEnded` fires at teardown and the CLOSED webhook — which
|
|
5719
|
+
* may reach another instance — does the rest.
|
|
5720
|
+
*
|
|
5721
|
+
* @internal
|
|
5722
|
+
*/
|
|
5723
|
+
get conversationClosedByOrchestrator() {
|
|
5724
|
+
return false;
|
|
5725
|
+
}
|
|
5231
5726
|
/**
|
|
5232
5727
|
* Build the response for an inbound call. Default: not supported.
|
|
5233
5728
|
*
|
|
@@ -5436,27 +5931,32 @@ var TwiMLBuilderBase = class {
|
|
|
5436
5931
|
);
|
|
5437
5932
|
}
|
|
5438
5933
|
/**
|
|
5439
|
-
* The WebSocket URL derived from `TACConfig.
|
|
5440
|
-
* `TACConfig.voiceWebsocketPath`, or undefined when
|
|
5441
|
-
*
|
|
5934
|
+
* The WebSocket URL derived from `TACConfig.voiceCallbackDomain` +
|
|
5935
|
+
* `TACConfig.voiceWebsocketPath`, or undefined when no public domain is set.
|
|
5936
|
+
*
|
|
5937
|
+
* Uses `voiceCallbackDomain`, so a deployment that sets
|
|
5938
|
+
* `instancePublicDomain` pins the call to this process from its very first
|
|
5939
|
+
* connection.
|
|
5442
5940
|
*/
|
|
5443
5941
|
defaultWebsocketUrl() {
|
|
5444
|
-
|
|
5942
|
+
const domain = this.tacConfig.voiceCallbackDomain;
|
|
5943
|
+
if (!domain) {
|
|
5445
5944
|
return void 0;
|
|
5446
5945
|
}
|
|
5447
|
-
return `wss://${
|
|
5946
|
+
return `wss://${domain}${this.tacConfig.voiceWebsocketPath}`;
|
|
5448
5947
|
}
|
|
5449
5948
|
/**
|
|
5450
5949
|
* Resolve the default `<Connect action=...>` cleanup URL from
|
|
5451
|
-
* `TACConfig.
|
|
5950
|
+
* `TACConfig.voiceCallbackDomain` + `TACConfig.voiceActionPath`.
|
|
5452
5951
|
*
|
|
5453
|
-
* Returns undefined if
|
|
5952
|
+
* Returns undefined if no public domain is set; that's fine because
|
|
5454
5953
|
* actionUrl has higher-priority layers (customizer, twimlOptions, Studio
|
|
5455
5954
|
* handoff) above this fallback.
|
|
5456
5955
|
*/
|
|
5457
5956
|
defaultActionUrl() {
|
|
5458
|
-
|
|
5459
|
-
|
|
5957
|
+
const domain = this.tacConfig.voiceCallbackDomain;
|
|
5958
|
+
if (domain) {
|
|
5959
|
+
return `https://${domain}${this.tacConfig.voiceActionPath}`;
|
|
5460
5960
|
}
|
|
5461
5961
|
return void 0;
|
|
5462
5962
|
}
|
|
@@ -5684,6 +6184,16 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5684
6184
|
get channelName() {
|
|
5685
6185
|
return "VOICE";
|
|
5686
6186
|
}
|
|
6187
|
+
/**
|
|
6188
|
+
* ConversationRelay asks Conversation Orchestrator to create the
|
|
6189
|
+
* conversation whenever TAC is orchestrated; in relay-only mode there is no
|
|
6190
|
+
* CO conversation and nothing will ever close it for us.
|
|
6191
|
+
*
|
|
6192
|
+
* @internal
|
|
6193
|
+
*/
|
|
6194
|
+
get conversationClosedByOrchestrator() {
|
|
6195
|
+
return this.channel.isOrchestratorEnabledInternal();
|
|
6196
|
+
}
|
|
5687
6197
|
/**
|
|
5688
6198
|
* Get active WebSocket connection for a conversation
|
|
5689
6199
|
*/
|
|
@@ -5725,7 +6235,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5725
6235
|
const conversation = conversations[0];
|
|
5726
6236
|
const conversationId = conversation.id;
|
|
5727
6237
|
const participants = await conversationClient.listParticipants(conversationId);
|
|
5728
|
-
const customerParticipant = participants.find(
|
|
6238
|
+
const customerParticipant = participants.find(
|
|
6239
|
+
(p) => p.type === "CUSTOMER" && p.addresses?.some((a) => a.channel === "VOICE")
|
|
6240
|
+
);
|
|
5729
6241
|
const customerAddress = customerParticipant?.addresses?.find((a) => a.channel === "VOICE")?.address ?? fromNumber ?? void 0;
|
|
5730
6242
|
const profileId = customerParticipant?.profileId ? customerParticipant.profileId : void 0;
|
|
5731
6243
|
this.webSocketConnections.set(conversationId, ws);
|
|
@@ -6033,27 +6545,44 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
6033
6545
|
});
|
|
6034
6546
|
}
|
|
6035
6547
|
/**
|
|
6036
|
-
*
|
|
6037
|
-
*
|
|
6038
|
-
*
|
|
6548
|
+
* Clean up WebSocket and session resources when the connection closes.
|
|
6549
|
+
*
|
|
6550
|
+
* Runs unconditionally — the call is over in every mode once its socket is
|
|
6551
|
+
* gone, so nothing local is kept waiting for a Conversation Orchestrator
|
|
6552
|
+
* webhook that may land on a different instance. Releasing the session fires
|
|
6553
|
+
* `onCallEnded` here and defers `onConversationEnded` to CO's CLOSED webhook
|
|
6554
|
+
* when orchestrated.
|
|
6555
|
+
*
|
|
6556
|
+
* Idempotent: a second run for a call already torn down does nothing.
|
|
6039
6557
|
*/
|
|
6040
6558
|
async handleWebSocketDisconnect(conversationId) {
|
|
6559
|
+
if (!this.webSocketConnections.has(conversationId) && !this.promptQueues.has(conversationId) && !this.channel.isConversationActive(conversationId)) {
|
|
6560
|
+
return;
|
|
6561
|
+
}
|
|
6041
6562
|
this.cancelStreamTask(conversationId);
|
|
6042
6563
|
this.webSocketConnections.delete(conversationId);
|
|
6043
6564
|
this.promptQueues.delete(conversationId);
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
voiceCallbacks.onWebSocketDisconnected
|
|
6047
|
-
|
|
6048
|
-
|
|
6049
|
-
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
|
|
6056
|
-
|
|
6565
|
+
try {
|
|
6566
|
+
const voiceCallbacks = this.channel.getVoiceCallbacks();
|
|
6567
|
+
if (voiceCallbacks.onWebSocketDisconnected) {
|
|
6568
|
+
try {
|
|
6569
|
+
voiceCallbacks.onWebSocketDisconnected({ conversationId });
|
|
6570
|
+
} catch (error) {
|
|
6571
|
+
this.logger.error(
|
|
6572
|
+
{ err: error, conversation_id: conversationId },
|
|
6573
|
+
"Error in WebSocket disconnected callback"
|
|
6574
|
+
);
|
|
6575
|
+
}
|
|
6576
|
+
}
|
|
6577
|
+
trackEvent("Websocket Disconnected", {
|
|
6578
|
+
account_sid: this.tacConfig.accountSid,
|
|
6579
|
+
channel: "voice",
|
|
6580
|
+
conversation_id: conversationId,
|
|
6581
|
+
provider: this.providerId,
|
|
6582
|
+
orchestrator_enabled: this.tacConfig.isOrchestratorEnabled()
|
|
6583
|
+
});
|
|
6584
|
+
} finally {
|
|
6585
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
6057
6586
|
}
|
|
6058
6587
|
}
|
|
6059
6588
|
/**
|
|
@@ -6460,11 +6989,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
6460
6989
|
return { status: 403, content: "Forbidden", contentType: "text/plain" };
|
|
6461
6990
|
}
|
|
6462
6991
|
if (payload.CallStatus === "completed" && !this.channel.isOrchestratorEnabledInternal()) {
|
|
6463
|
-
const conversationId = this.callSidToConversationId.get(payload.CallSid);
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
await this.channel.endConversationInternal(conversationId);
|
|
6467
|
-
}
|
|
6992
|
+
const conversationId = this.callSidToConversationId.get(payload.CallSid) ?? payload.CallSid;
|
|
6993
|
+
this.callSidToConversationId.delete(payload.CallSid);
|
|
6994
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
6468
6995
|
}
|
|
6469
6996
|
return { status: 200, content: "OK", contentType: "text/plain" };
|
|
6470
6997
|
}
|
|
@@ -6545,6 +7072,8 @@ var ConversationRelayProviderConfig = class extends VoiceProviderConfig {
|
|
|
6545
7072
|
};
|
|
6546
7073
|
|
|
6547
7074
|
// packages/core/src/channels/voice/channel.ts
|
|
7075
|
+
var CO_VOICE_CHANNEL = "VOICE";
|
|
7076
|
+
var AGENT_TYPES2 = /* @__PURE__ */ new Set(["AGENT", "AI_AGENT"]);
|
|
6548
7077
|
var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
6549
7078
|
provider;
|
|
6550
7079
|
voiceCallbacks;
|
|
@@ -6553,6 +7082,17 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6553
7082
|
onCallStatusHandler;
|
|
6554
7083
|
onAmdHandler;
|
|
6555
7084
|
onRecordingHandler;
|
|
7085
|
+
onCallEndedHandler;
|
|
7086
|
+
/**
|
|
7087
|
+
* Live sessions by conversation id. Instance-local by design: a call is
|
|
7088
|
+
* pinned to the process holding its WebSocket.
|
|
7089
|
+
*/
|
|
7090
|
+
activeConversations;
|
|
7091
|
+
/**
|
|
7092
|
+
* Live calls whose conversation CO already closed mid-call: their
|
|
7093
|
+
* `onConversationEnded` has fired, so teardown doesn't fire it again.
|
|
7094
|
+
*/
|
|
7095
|
+
closedWhileLive;
|
|
6556
7096
|
/**
|
|
6557
7097
|
* @param tac - The owning {@link TAC} instance.
|
|
6558
7098
|
* @param options - Either a {@link VoiceProviderConfig} selecting the media
|
|
@@ -6562,7 +7102,14 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6562
7102
|
*/
|
|
6563
7103
|
constructor(tac, options) {
|
|
6564
7104
|
super(tac, _VoiceChannel.toBaseOptions(options));
|
|
7105
|
+
if (this.config.phoneNumbers.length === 0) {
|
|
7106
|
+
throw new Error(
|
|
7107
|
+
"phoneNumber(s) is required for Voice channel. Set TWILIO_PHONE_NUMBER / TWILIO_PHONE_NUMBERS or provide phoneNumber / phoneNumbers in TACConfig."
|
|
7108
|
+
);
|
|
7109
|
+
}
|
|
6565
7110
|
this.voiceCallbacks = {};
|
|
7111
|
+
this.activeConversations = /* @__PURE__ */ new Map();
|
|
7112
|
+
this.closedWhileLive = /* @__PURE__ */ new Set();
|
|
6566
7113
|
this.provider = _VoiceChannel.toProviderConfig(options).createProvider(this, this.config);
|
|
6567
7114
|
}
|
|
6568
7115
|
/**
|
|
@@ -6707,6 +7254,30 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6707
7254
|
onDtmf(callback) {
|
|
6708
7255
|
this.voiceCallbacks.onDtmf = callback;
|
|
6709
7256
|
}
|
|
7257
|
+
/**
|
|
7258
|
+
* Register a handler for a call's WebSocket teardown.
|
|
7259
|
+
*
|
|
7260
|
+
* Fires once per call, always, on the instance that held the call. It
|
|
7261
|
+
* receives the live session just before it is discarded, so it is the only
|
|
7262
|
+
* place late-call in-memory state — the transcript, `callSid`, anything you
|
|
7263
|
+
* put on `metadata` — is still reachable.
|
|
7264
|
+
*
|
|
7265
|
+
* Not the same as `onConversationEnded` (fires when the *conversation*
|
|
7266
|
+
* closes, on any instance; on an orchestrated call, from a session rebuilt
|
|
7267
|
+
* from Conversation Orchestrator, identity only) or {@link onCallStatus} (a
|
|
7268
|
+
* Twilio Calls-API webhook, no session). Handler errors are logged and
|
|
7269
|
+
* swallowed.
|
|
7270
|
+
*
|
|
7271
|
+
* @example
|
|
7272
|
+
* ```typescript
|
|
7273
|
+
* voiceChannel.onCallEnded(async session => {
|
|
7274
|
+
* await archive(session.callSid, session.metadata.transcript ?? []);
|
|
7275
|
+
* });
|
|
7276
|
+
* ```
|
|
7277
|
+
*/
|
|
7278
|
+
onCallEnded(callback) {
|
|
7279
|
+
this.onCallEndedHandler = callback;
|
|
7280
|
+
}
|
|
6710
7281
|
// =========================================================================
|
|
6711
7282
|
// Provider-facing surface
|
|
6712
7283
|
//
|
|
@@ -6791,8 +7362,7 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6791
7362
|
return this.onInboundCallTwimlHandler;
|
|
6792
7363
|
}
|
|
6793
7364
|
/**
|
|
6794
|
-
* Start tracking a
|
|
6795
|
-
* `BaseChannel.startConversation`.
|
|
7365
|
+
* Start tracking a call's session. Forwards to {@link startConversation}.
|
|
6796
7366
|
*
|
|
6797
7367
|
* @internal
|
|
6798
7368
|
*/
|
|
@@ -6800,13 +7370,13 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6800
7370
|
return this.startConversation(conversationId, profileId);
|
|
6801
7371
|
}
|
|
6802
7372
|
/**
|
|
6803
|
-
*
|
|
6804
|
-
*
|
|
7373
|
+
* Release a finished call's session and fire the end-of-call hooks.
|
|
7374
|
+
* Forwards to {@link releaseSession}.
|
|
6805
7375
|
*
|
|
6806
7376
|
* @internal
|
|
6807
7377
|
*/
|
|
6808
|
-
|
|
6809
|
-
return this.
|
|
7378
|
+
releaseSessionInternal(conversationId) {
|
|
7379
|
+
return this.releaseSession(conversationId);
|
|
6810
7380
|
}
|
|
6811
7381
|
/**
|
|
6812
7382
|
* Retrieve memory when `memoryMode` calls for it. Forwards to
|
|
@@ -6867,67 +7437,389 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6867
7437
|
}
|
|
6868
7438
|
}
|
|
6869
7439
|
/**
|
|
6870
|
-
* Process
|
|
7440
|
+
* Process Conversation Orchestrator webhooks.
|
|
7441
|
+
*
|
|
7442
|
+
* Voice channel processes these events:
|
|
7443
|
+
*
|
|
7444
|
+
* - **PARTICIPANT_ADDED**: report "Conversation Started" when the customer
|
|
7445
|
+
* joins on voice (orchestrated ConversationRelay only).
|
|
7446
|
+
* - **CLOSED** (CONVERSATION_UPDATED): fire `onConversationEnded`. The call's
|
|
7447
|
+
* session is normally already released (the WebSocket closed when the
|
|
7448
|
+
* caller hung up), so this rebuilds it from Conversation Orchestrator —
|
|
7449
|
+
* which is also what makes the hook fire on whichever instance received the
|
|
7450
|
+
* webhook rather than only on the one that held the call. If this instance
|
|
7451
|
+
* still holds the call's session (the call is live), the hook fires now
|
|
7452
|
+
* instead, with a snapshot of that live session, and the session stays
|
|
7453
|
+
* until the call's own teardown — which still fires {@link onCallEnded}. A
|
|
7454
|
+
* single call can then produce a second `onConversationEnded`, under a
|
|
7455
|
+
* different conversation id, when Conversation Orchestrator later closes
|
|
7456
|
+
* the conversation it started for the call's remaining traffic. It also
|
|
7457
|
+
* reports "Conversation Ended", with CO's duration, from the payload alone
|
|
7458
|
+
* and once across channels; only a registered handler costs the lookup.
|
|
7459
|
+
* - **INACTIVE**: invalidate cached memory, if this instance holds the
|
|
7460
|
+
* session. A call is pinned to one instance for its lifetime, so an
|
|
7461
|
+
* INACTIVE landing elsewhere has no cache to clear and is ignored.
|
|
7462
|
+
*
|
|
7463
|
+
* @param payload - Raw webhook event data from Twilio
|
|
7464
|
+
* @param idempotencyToken - Optional Twilio idempotency token from request headers
|
|
7465
|
+
*/
|
|
7466
|
+
async processWebhook(payload, idempotencyToken) {
|
|
7467
|
+
try {
|
|
7468
|
+
const result = this.preprocessWebhook(payload, idempotencyToken);
|
|
7469
|
+
if (!result) {
|
|
7470
|
+
return;
|
|
7471
|
+
}
|
|
7472
|
+
const { webhookData, eventType, conversationId } = result;
|
|
7473
|
+
switch (eventType) {
|
|
7474
|
+
case "PARTICIPANT_ADDED":
|
|
7475
|
+
if (this.provider.conversationClosedByOrchestrator) {
|
|
7476
|
+
this.trackConversationStarted(webhookData.data);
|
|
7477
|
+
}
|
|
7478
|
+
break;
|
|
7479
|
+
case "CONVERSATION_UPDATED":
|
|
7480
|
+
this.logger.debug(
|
|
7481
|
+
{ conversation_id: conversationId, status: webhookData.data?.status },
|
|
7482
|
+
"Handling CONVERSATION_UPDATED"
|
|
7483
|
+
);
|
|
7484
|
+
await this.handleConversationUpdated(webhookData);
|
|
7485
|
+
break;
|
|
7486
|
+
default:
|
|
7487
|
+
this.logger.debug(
|
|
7488
|
+
{
|
|
7489
|
+
event_type: eventType,
|
|
7490
|
+
raw_event_type: webhookData.eventType,
|
|
7491
|
+
conversation_id: conversationId
|
|
7492
|
+
},
|
|
7493
|
+
"Unhandled event type - this event will be ignored"
|
|
7494
|
+
);
|
|
7495
|
+
}
|
|
7496
|
+
this.logger.debug({ event_type: eventType }, "Webhook processing completed");
|
|
7497
|
+
} catch (error) {
|
|
7498
|
+
if (idempotencyToken) {
|
|
7499
|
+
this.removeWebhookToken(idempotencyToken);
|
|
7500
|
+
}
|
|
7501
|
+
this.handleError(error instanceof Error ? error : new Error(String(error)), { payload });
|
|
7502
|
+
}
|
|
7503
|
+
}
|
|
7504
|
+
/**
|
|
7505
|
+
* Handle conversation updated event
|
|
7506
|
+
*/
|
|
7507
|
+
async handleConversationUpdated(payload) {
|
|
7508
|
+
const conversationId = this.extractConversationId(payload);
|
|
7509
|
+
if (!conversationId) {
|
|
7510
|
+
throw new Error("Missing conversation ID in conversation.updated event");
|
|
7511
|
+
}
|
|
7512
|
+
if (payload.data?.configurationId !== this.config.conversationConfigurationId) {
|
|
7513
|
+
return;
|
|
7514
|
+
}
|
|
7515
|
+
const status = payload.data?.status;
|
|
7516
|
+
if (status === "CLOSED") {
|
|
7517
|
+
if (!this.provider.conversationClosedByOrchestrator) {
|
|
7518
|
+
return;
|
|
7519
|
+
}
|
|
7520
|
+
const createdAt = payload.data?.createdAt;
|
|
7521
|
+
const updatedAt = payload.data?.updatedAt;
|
|
7522
|
+
await this.handleConversationClosed(
|
|
7523
|
+
conversationId,
|
|
7524
|
+
elapsedMs(
|
|
7525
|
+
typeof createdAt === "string" ? createdAt : void 0,
|
|
7526
|
+
typeof updatedAt === "string" ? updatedAt : void 0
|
|
7527
|
+
)
|
|
7528
|
+
);
|
|
7529
|
+
} else if (status === "INACTIVE" && this.memoryMode === "once") {
|
|
7530
|
+
const session = this.activeConversations.get(conversationId);
|
|
7531
|
+
if (session?.cachedMemory !== void 0) {
|
|
7532
|
+
session.cachedMemory = void 0;
|
|
7533
|
+
this.logger.debug(
|
|
7534
|
+
{ conversation_id: conversationId },
|
|
7535
|
+
"Invalidated cached memory on INACTIVE status"
|
|
7536
|
+
);
|
|
7537
|
+
}
|
|
7538
|
+
}
|
|
7539
|
+
}
|
|
7540
|
+
// =========================================================================
|
|
7541
|
+
// Session lifecycle
|
|
7542
|
+
// =========================================================================
|
|
7543
|
+
/**
|
|
7544
|
+
* Get the live session this instance holds for a conversation.
|
|
7545
|
+
*/
|
|
7546
|
+
getConversationSession(conversationId) {
|
|
7547
|
+
return this.activeConversations.get(conversationId);
|
|
7548
|
+
}
|
|
7549
|
+
/**
|
|
7550
|
+
* Whether this instance holds a live session for a conversation.
|
|
7551
|
+
*/
|
|
7552
|
+
isConversationActive(conversationId) {
|
|
7553
|
+
return this.activeConversations.has(conversationId);
|
|
7554
|
+
}
|
|
7555
|
+
/**
|
|
7556
|
+
* Track a new session for a call, or return the existing one.
|
|
7557
|
+
*/
|
|
7558
|
+
startConversation(conversationId, profileId) {
|
|
7559
|
+
const existing = this.activeConversations.get(conversationId);
|
|
7560
|
+
if (existing) {
|
|
7561
|
+
this.logger.debug(
|
|
7562
|
+
{ conversation_id: conversationId, profile_id: existing.profileId },
|
|
7563
|
+
"Conversation already active"
|
|
7564
|
+
);
|
|
7565
|
+
return existing;
|
|
7566
|
+
}
|
|
7567
|
+
const session = {
|
|
7568
|
+
conversationId,
|
|
7569
|
+
profileId,
|
|
7570
|
+
channel: this.channelType,
|
|
7571
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
7572
|
+
metadata: {}
|
|
7573
|
+
};
|
|
7574
|
+
this.activeConversations.set(conversationId, session);
|
|
7575
|
+
this.logger.debug(
|
|
7576
|
+
{ conversation_id: conversationId, profile_id: profileId, channel: this.channelType },
|
|
7577
|
+
"Conversation started"
|
|
7578
|
+
);
|
|
7579
|
+
if (this.callbacks.onConversationStarted) {
|
|
7580
|
+
this.callbacks.onConversationStarted({ session });
|
|
7581
|
+
}
|
|
7582
|
+
if (!this.provider.conversationClosedByOrchestrator) {
|
|
7583
|
+
trackEvent("Conversation Started", {
|
|
7584
|
+
account_sid: this.config.accountSid,
|
|
7585
|
+
channel: this.channelType,
|
|
7586
|
+
conversation_id: conversationId,
|
|
7587
|
+
has_profile_id: !!profileId
|
|
7588
|
+
});
|
|
7589
|
+
}
|
|
7590
|
+
return session;
|
|
7591
|
+
}
|
|
7592
|
+
/**
|
|
7593
|
+
* Free a finished call's session and fire the end-of-call hooks.
|
|
7594
|
+
*
|
|
7595
|
+
* Called from every teardown path and idempotent, so a second call is a
|
|
7596
|
+
* no-op returning `undefined`. Always fires {@link onCallEnded}. Also fires
|
|
7597
|
+
* `onConversationEnded` unless a Conversation Orchestrator CLOSED webhook will
|
|
7598
|
+
* do that later (see `VoiceProvider.conversationClosedByOrchestrator`).
|
|
7599
|
+
* Nothing is kept for that CLOSED: it gets a session rebuilt from
|
|
7600
|
+
* Conversation Orchestrator.
|
|
7601
|
+
*/
|
|
7602
|
+
async releaseSession(conversationId) {
|
|
7603
|
+
const session = this.activeConversations.get(conversationId);
|
|
7604
|
+
if (!session) {
|
|
7605
|
+
return void 0;
|
|
7606
|
+
}
|
|
7607
|
+
this.activeConversations.delete(conversationId);
|
|
7608
|
+
const durationMs = Date.now() - session.startedAt.getTime();
|
|
7609
|
+
const orchestrated = this.provider.conversationClosedByOrchestrator;
|
|
7610
|
+
if (this.onCallEndedHandler) {
|
|
7611
|
+
try {
|
|
7612
|
+
await this.onCallEndedHandler(session);
|
|
7613
|
+
} catch (error) {
|
|
7614
|
+
this.logger.error(
|
|
7615
|
+
{ err: error, conversation_id: conversationId },
|
|
7616
|
+
"Error in call ended callback"
|
|
7617
|
+
);
|
|
7618
|
+
}
|
|
7619
|
+
}
|
|
7620
|
+
if (orchestrated) {
|
|
7621
|
+
this.closedWhileLive.delete(conversationId);
|
|
7622
|
+
} else {
|
|
7623
|
+
await this.triggerConversationEnded(session);
|
|
7624
|
+
trackEvent("Conversation Ended", {
|
|
7625
|
+
account_sid: this.config.accountSid,
|
|
7626
|
+
channel: this.channelType,
|
|
7627
|
+
conversation_id: conversationId,
|
|
7628
|
+
duration_ms: durationMs
|
|
7629
|
+
});
|
|
7630
|
+
}
|
|
7631
|
+
this.logger.debug(
|
|
7632
|
+
{ conversation_id: conversationId, channel: this.channelType },
|
|
7633
|
+
"Released voice session"
|
|
7634
|
+
);
|
|
7635
|
+
return session;
|
|
7636
|
+
}
|
|
7637
|
+
/**
|
|
7638
|
+
* Fire `onConversationEnded` for a CLOSED webhook.
|
|
6871
7639
|
*
|
|
6872
|
-
*
|
|
6873
|
-
*
|
|
7640
|
+
* The call has normally ended by now (the socket closed when the caller hung
|
|
7641
|
+
* up, or {@link endCall} hung it up), and its session went with it. The hook
|
|
7642
|
+
* gets a session rebuilt from Conversation Orchestrator, identity only,
|
|
7643
|
+
* which is what lets it fire on whichever instance received the webhook. The
|
|
7644
|
+
* call's live state (transcript, `metadata`) reached {@link onCallEnded} at
|
|
7645
|
+
* teardown.
|
|
6874
7646
|
*
|
|
6875
|
-
*
|
|
6876
|
-
*
|
|
7647
|
+
* If this instance still holds the session, the call is live: CO closed the
|
|
7648
|
+
* conversation mid-call (a closed timeout during a long hold, or the app
|
|
7649
|
+
* closing it). The hook fires now, from a snapshot, and the session stays for
|
|
7650
|
+
* the call's own teardown to release — which is what keeps `onCallEnded`
|
|
7651
|
+
* firing and the rest of the call working. The call then carries on under
|
|
7652
|
+
* the closed conversation's id; CO starts a new conversation for its later
|
|
7653
|
+
* traffic, whose own CLOSED arrives here later and takes the rebuild path.
|
|
6877
7654
|
*
|
|
6878
|
-
*
|
|
6879
|
-
*
|
|
7655
|
+
* The hook is at-least-once: a duplicate CLOSED delivery that isn't deduped
|
|
7656
|
+
* by its idempotency token fires it again, same as `onMessageReady`.
|
|
6880
7657
|
*/
|
|
6881
|
-
async
|
|
6882
|
-
|
|
6883
|
-
|
|
6884
|
-
|
|
6885
|
-
|
|
7658
|
+
async handleConversationClosed(conversationId, durationMs) {
|
|
7659
|
+
const live = this.activeConversations.get(conversationId);
|
|
7660
|
+
if (live) {
|
|
7661
|
+
this.logger.warn(
|
|
7662
|
+
{ conversation_id: conversationId, call_sid: live.callSid },
|
|
7663
|
+
"Conversation closed while its call is still live; the call continues under the closed conversation's id"
|
|
7664
|
+
);
|
|
7665
|
+
this.closedWhileLive.add(conversationId);
|
|
7666
|
+
this.trackConversationEnded(conversationId, durationMs);
|
|
7667
|
+
await this.triggerConversationEnded(this.detachedSnapshot(live));
|
|
7668
|
+
return;
|
|
7669
|
+
}
|
|
7670
|
+
this.trackConversationEnded(conversationId, durationMs);
|
|
7671
|
+
if (!this.hasConversationEndedHandler()) {
|
|
7672
|
+
return;
|
|
7673
|
+
}
|
|
7674
|
+
const session = await this.rebuildSession(conversationId, void 0, { shared: true });
|
|
7675
|
+
if (!session) {
|
|
7676
|
+
return;
|
|
7677
|
+
}
|
|
7678
|
+
await this.triggerConversationEnded(session);
|
|
7679
|
+
}
|
|
7680
|
+
/**
|
|
7681
|
+
* A copy of a live call's session that shares no mutable state with it.
|
|
7682
|
+
*
|
|
7683
|
+
* `onConversationEnded` may keep or edit what it's given while the call
|
|
7684
|
+
* carries on, so the callback-visible data — `metadata` and the nested
|
|
7685
|
+
* objects — is cloned. A value that can't be cloned (an app-owned handle, a
|
|
7686
|
+
* class instance whose methods a clone would lose) is shared rather than
|
|
7687
|
+
* failing the hook.
|
|
7688
|
+
*/
|
|
7689
|
+
detachedSnapshot(live) {
|
|
7690
|
+
const conversationId = live.conversationId;
|
|
7691
|
+
const detached = (value, what) => {
|
|
7692
|
+
if (value === null || typeof value !== "object") {
|
|
7693
|
+
return value;
|
|
6886
7694
|
}
|
|
6887
|
-
const
|
|
6888
|
-
|
|
6889
|
-
|
|
6890
|
-
this.logger.debug(
|
|
6891
|
-
{ conversation_id: conversationId, status: webhookData.data?.status },
|
|
6892
|
-
"Handling CONVERSATION_UPDATED"
|
|
6893
|
-
);
|
|
6894
|
-
await this.handleConversationUpdated(webhookData);
|
|
6895
|
-
break;
|
|
6896
|
-
default:
|
|
6897
|
-
this.logger.debug(
|
|
6898
|
-
{
|
|
6899
|
-
event_type: eventType,
|
|
6900
|
-
raw_event_type: webhookData.eventType,
|
|
6901
|
-
conversation_id: conversationId
|
|
6902
|
-
},
|
|
6903
|
-
"Unhandled event type - this event will be ignored"
|
|
6904
|
-
);
|
|
7695
|
+
const proto = Object.getPrototypeOf(value);
|
|
7696
|
+
if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
|
|
7697
|
+
return value;
|
|
6905
7698
|
}
|
|
6906
|
-
|
|
6907
|
-
|
|
6908
|
-
|
|
6909
|
-
this.
|
|
7699
|
+
try {
|
|
7700
|
+
return structuredClone(value);
|
|
7701
|
+
} catch (error) {
|
|
7702
|
+
this.logger.debug(
|
|
7703
|
+
{ conversation_id: conversationId, value: what, err: error },
|
|
7704
|
+
"Sharing a value that can't be copied into the CLOSED snapshot"
|
|
7705
|
+
);
|
|
7706
|
+
return value;
|
|
6910
7707
|
}
|
|
6911
|
-
|
|
7708
|
+
};
|
|
7709
|
+
const metadata = {};
|
|
7710
|
+
for (const [key, value] of Object.entries(live.metadata)) {
|
|
7711
|
+
metadata[key] = detached(value, `metadata[${JSON.stringify(key)}]`);
|
|
7712
|
+
}
|
|
7713
|
+
const snapshot = {
|
|
7714
|
+
...live,
|
|
7715
|
+
startedAt: new Date(live.startedAt.getTime()),
|
|
7716
|
+
metadata
|
|
7717
|
+
};
|
|
7718
|
+
if (live.profile !== void 0) snapshot.profile = detached(live.profile, "profile");
|
|
7719
|
+
if (live.authorInfo !== void 0) {
|
|
7720
|
+
snapshot.authorInfo = detached(live.authorInfo, "authorInfo");
|
|
6912
7721
|
}
|
|
7722
|
+
if (live.aiAgentInfo !== void 0) {
|
|
7723
|
+
snapshot.aiAgentInfo = detached(live.aiAgentInfo, "aiAgentInfo");
|
|
7724
|
+
}
|
|
7725
|
+
if (live.pendingHandoffData !== void 0) {
|
|
7726
|
+
snapshot.pendingHandoffData = detached(live.pendingHandoffData, "pendingHandoffData");
|
|
7727
|
+
}
|
|
7728
|
+
return snapshot;
|
|
6913
7729
|
}
|
|
6914
7730
|
/**
|
|
6915
|
-
*
|
|
7731
|
+
* The participant representing TAC's agent at `address` on voice: one that
|
|
7732
|
+
* owns the address AND has an agent type. A HUMAN_AGENT at that address is
|
|
7733
|
+
* someone else.
|
|
6916
7734
|
*/
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
|
|
6920
|
-
|
|
7735
|
+
static findVoiceAgent(participants, address) {
|
|
7736
|
+
return participants.find(
|
|
7737
|
+
(p) => p.type !== void 0 && AGENT_TYPES2.has(p.type) && p.addresses.some((a) => a.channel === CO_VOICE_CHANNEL && a.address === address)
|
|
7738
|
+
);
|
|
7739
|
+
}
|
|
7740
|
+
/**
|
|
7741
|
+
* Reconstruct a session from Conversation Orchestrator.
|
|
7742
|
+
*
|
|
7743
|
+
* Carries identity only — conversation id, `callSid`, profile, both
|
|
7744
|
+
* participants. Live in-memory state (transcript, metadata) isn't available
|
|
7745
|
+
* here; it reaches {@link onCallEnded}. `callSid` defaults to a VOICE
|
|
7746
|
+
* participant address's `channelId` — the customer's if present, else the
|
|
7747
|
+
* agent's, else any other participant's. Returns `undefined` if no
|
|
7748
|
+
* participant is on the voice channel, which is how another channel's CLOSED
|
|
7749
|
+
* is filtered out.
|
|
7750
|
+
*
|
|
7751
|
+
* `shared` (the CLOSED path) shares the participant lookup with the other
|
|
7752
|
+
* channels handling the same webhook; other callers need fresh participants.
|
|
7753
|
+
*/
|
|
7754
|
+
async rebuildSession(conversationId, callSid, options) {
|
|
7755
|
+
const client2 = this.conversationClient;
|
|
7756
|
+
if (!client2) {
|
|
7757
|
+
return void 0;
|
|
6921
7758
|
}
|
|
6922
|
-
|
|
6923
|
-
|
|
6924
|
-
|
|
6925
|
-
|
|
7759
|
+
let participants;
|
|
7760
|
+
try {
|
|
7761
|
+
participants = options?.shared ? await this.tac.listParticipantsShared(conversationId) : await client2.listParticipants(conversationId);
|
|
7762
|
+
} catch (error) {
|
|
7763
|
+
this.logger.error(
|
|
7764
|
+
{ err: error, conversation_id: conversationId },
|
|
7765
|
+
"Failed to list participants while rebuilding a voice session"
|
|
6926
7766
|
);
|
|
6927
|
-
|
|
6928
|
-
}
|
|
6929
|
-
|
|
7767
|
+
return void 0;
|
|
7768
|
+
}
|
|
7769
|
+
const onVoice = (p) => p.addresses.some((a) => a.channel === CO_VOICE_CHANNEL);
|
|
7770
|
+
if (!participants.some(onVoice)) {
|
|
7771
|
+
return void 0;
|
|
7772
|
+
}
|
|
7773
|
+
const customer = participants.find((p) => p.type === "CUSTOMER" && onVoice(p));
|
|
7774
|
+
let agent;
|
|
7775
|
+
for (const number of this.config.phoneNumbers) {
|
|
7776
|
+
agent = _VoiceChannel.findVoiceAgent(participants, number);
|
|
7777
|
+
if (agent) break;
|
|
7778
|
+
}
|
|
7779
|
+
let resolvedCallSid = callSid;
|
|
7780
|
+
if (resolvedCallSid === void 0) {
|
|
7781
|
+
const ordered = [
|
|
7782
|
+
...[customer, agent].filter((p) => p !== void 0),
|
|
7783
|
+
...participants.filter((p) => p !== customer && p !== agent)
|
|
7784
|
+
];
|
|
7785
|
+
resolvedCallSid = ordered.flatMap((p) => p.addresses).find((a) => a.channel === CO_VOICE_CHANNEL && a.channelId)?.channelId ?? void 0;
|
|
7786
|
+
if (resolvedCallSid === void 0) {
|
|
7787
|
+
this.logger.debug(
|
|
7788
|
+
{ conversation_id: conversationId },
|
|
7789
|
+
"Rebuilt voice session has no callSid"
|
|
7790
|
+
);
|
|
7791
|
+
}
|
|
7792
|
+
}
|
|
7793
|
+
const session = {
|
|
7794
|
+
conversationId,
|
|
7795
|
+
channel: this.channelType,
|
|
7796
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
7797
|
+
metadata: {}
|
|
7798
|
+
};
|
|
7799
|
+
if (resolvedCallSid !== void 0) session.callSid = resolvedCallSid;
|
|
7800
|
+
if (customer?.profileId) session.profileId = customer.profileId;
|
|
7801
|
+
const customerAddress = customer?.addresses.find((a) => a.channel === CO_VOICE_CHANNEL)?.address;
|
|
7802
|
+
if (customer && customerAddress) {
|
|
7803
|
+
session.authorInfo = { address: customerAddress, participantId: customer.id };
|
|
6930
7804
|
}
|
|
7805
|
+
const agentAddress = agent?.addresses.find((a) => a.channel === CO_VOICE_CHANNEL)?.address ?? this.config.phoneNumber;
|
|
7806
|
+
if (agent && agentAddress) {
|
|
7807
|
+
session.aiAgentInfo = { address: agentAddress, participantId: agent.id };
|
|
7808
|
+
}
|
|
7809
|
+
return session;
|
|
7810
|
+
}
|
|
7811
|
+
/**
|
|
7812
|
+
* This channel's participants are recorded by Conversation Orchestrator as
|
|
7813
|
+
* VOICE, whatever the provider's transport label.
|
|
7814
|
+
*
|
|
7815
|
+
* @internal
|
|
7816
|
+
*/
|
|
7817
|
+
get coChannel() {
|
|
7818
|
+
return CO_VOICE_CHANNEL;
|
|
7819
|
+
}
|
|
7820
|
+
/** @internal */
|
|
7821
|
+
isOwnCoAddress(address) {
|
|
7822
|
+
return this.config.phoneNumbers.includes(address);
|
|
6931
7823
|
}
|
|
6932
7824
|
/**
|
|
6933
7825
|
* Get active WebSocket connection for a conversation
|
|
@@ -6959,7 +7851,8 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6959
7851
|
/**
|
|
6960
7852
|
* Send voice response via WebSocket
|
|
6961
7853
|
*/
|
|
6962
|
-
async sendResponse(
|
|
7854
|
+
async sendResponse(conversationIdOrSession, message, metadata) {
|
|
7855
|
+
const conversationId = typeof conversationIdOrSession === "string" ? conversationIdOrSession : conversationIdOrSession.conversationId;
|
|
6963
7856
|
await this.provider.sendResponse(conversationId, message, metadata);
|
|
6964
7857
|
trackEvent("Response Sent", {
|
|
6965
7858
|
account_sid: this.config.accountSid,
|
|
@@ -7170,6 +8063,11 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7170
8063
|
* hangs up while AMD is still resolving), and handlers shouldn't have to
|
|
7171
8064
|
* guard against it.
|
|
7172
8065
|
*
|
|
8066
|
+
* The session is released as on any hangup: {@link onCallEnded} fires now.
|
|
8067
|
+
* On an orchestrated call `onConversationEnded` fires later, when
|
|
8068
|
+
* Conversation Orchestrator's CLOSED webhook arrives; otherwise it fires now
|
|
8069
|
+
* too.
|
|
8070
|
+
*
|
|
7173
8071
|
* @param callSid - Twilio Call SID (from a call event, the outbound result, or
|
|
7174
8072
|
* `ConversationSession.callSid`).
|
|
7175
8073
|
* @returns True if Twilio accepted the hangup, false if it failed (logged).
|
|
@@ -7186,7 +8084,7 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7186
8084
|
}
|
|
7187
8085
|
const session = this.getConversationSessionByCallSid(callSid);
|
|
7188
8086
|
if (session) {
|
|
7189
|
-
await this.
|
|
8087
|
+
await this.releaseSession(session.conversationId);
|
|
7190
8088
|
}
|
|
7191
8089
|
return hungUp;
|
|
7192
8090
|
}
|
|
@@ -7203,10 +8101,10 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7203
8101
|
* exist before the caller speaks — including before `onAmd` fires. Treat it
|
|
7204
8102
|
* as racy and hang up with {@link endCall}, which needs no session.
|
|
7205
8103
|
*
|
|
7206
|
-
* At the other end
|
|
7207
|
-
*
|
|
7208
|
-
* `onRecording`
|
|
7209
|
-
*
|
|
8104
|
+
* At the other end the session is released as soon as the call's WebSocket
|
|
8105
|
+
* closes, in every mode — so out-of-band events that arrive after the hangup
|
|
8106
|
+
* (`onCallStatus`, `onRecording`) generally find nothing here. Read
|
|
8107
|
+
* late-call state from the session {@link onCallEnded} hands you instead.
|
|
7210
8108
|
*
|
|
7211
8109
|
* @example
|
|
7212
8110
|
* ```typescript
|
|
@@ -7221,8 +8119,9 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7221
8119
|
* @param callSid - Twilio Call SID, e.g. from
|
|
7222
8120
|
* `InitiateVoiceConversationResult.callSid` or a call event.
|
|
7223
8121
|
* @returns The session, or `undefined` — not created yet, the call ended, or
|
|
7224
|
-
* it landed on another instance
|
|
7225
|
-
*
|
|
8122
|
+
* it landed on another instance. For the last case,
|
|
8123
|
+
* {@link resolveConversationSessionByCallSid} falls back to Conversation
|
|
8124
|
+
* Orchestrator.
|
|
7226
8125
|
*/
|
|
7227
8126
|
getConversationSessionByCallSid(callSid) {
|
|
7228
8127
|
for (const session of this.activeConversations.values()) {
|
|
@@ -7232,6 +8131,81 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7232
8131
|
}
|
|
7233
8132
|
return void 0;
|
|
7234
8133
|
}
|
|
8134
|
+
/**
|
|
8135
|
+
* Look up a call's session on any instance, falling back to Conversation
|
|
8136
|
+
* Orchestrator when this instance doesn't hold the call.
|
|
8137
|
+
*
|
|
8138
|
+
* Out-of-band call events (`onCallStatus`, `onAmd`, `onRecording`) carry
|
|
8139
|
+
* only a CallSid and, without `TACConfig.instancePublicDomain`, can reach any
|
|
8140
|
+
* replica. This returns the live session when the call is held here — same
|
|
8141
|
+
* as {@link getConversationSessionByCallSid} — and otherwise, for a
|
|
8142
|
+
* ConversationRelay call in orchestrator mode, a session rebuilt from
|
|
8143
|
+
* Conversation Orchestrator.
|
|
8144
|
+
*
|
|
8145
|
+
* A rebuilt session carries identity only (conversation id, `callSid`,
|
|
8146
|
+
* profile, both participants), is not tracked, and can't be used with
|
|
8147
|
+
* {@link sendResponse}: the call's WebSocket is on another instance. If CO
|
|
8148
|
+
* holds several conversations for the call (it starts a new one when a
|
|
8149
|
+
* conversation closes mid-call), the active one wins, else the newest — this
|
|
8150
|
+
* rule applies only to the rebuild path. On the instance holding the call,
|
|
8151
|
+
* the live session is returned as-is, so after a mid-call close it still
|
|
8152
|
+
* carries the closed conversation's id while other instances return the new
|
|
8153
|
+
* one; correlate by `callSid` if you need a stable key.
|
|
8154
|
+
*
|
|
8155
|
+
* To tell live from rebuilt, check
|
|
8156
|
+
* `voiceChannel.getWebsocket(session.conversationId) !== null` — true only
|
|
8157
|
+
* for a session live on this instance. A rebuilt session's `startedAt` is
|
|
8158
|
+
* the rebuild time, not the call's, and its `metadata` is always empty.
|
|
8159
|
+
*
|
|
8160
|
+
* Cost: on a local miss this makes up to two Conversation Orchestrator
|
|
8161
|
+
* requests (list conversations, then participants). Prefer
|
|
8162
|
+
* {@link getConversationSessionByCallSid} on hot paths, or when
|
|
8163
|
+
* `TACConfig.instancePublicDomain` already routes call events to the
|
|
8164
|
+
* instance holding the call.
|
|
8165
|
+
*
|
|
8166
|
+
* @example
|
|
8167
|
+
* ```typescript
|
|
8168
|
+
* voiceChannel.onCallStatus(async event => {
|
|
8169
|
+
* const session = await voiceChannel.resolveConversationSessionByCallSid(event.callSid);
|
|
8170
|
+
* if (session) {
|
|
8171
|
+
* auditLog(session.conversationId, session.profileId, event.callStatus);
|
|
8172
|
+
* }
|
|
8173
|
+
* });
|
|
8174
|
+
* ```
|
|
8175
|
+
*
|
|
8176
|
+
* @param callSid - Twilio Call SID, e.g. from a call event.
|
|
8177
|
+
* @returns The live or rebuilt session, or `undefined` — relay-only or Media
|
|
8178
|
+
* Streams mode (no CO conversation behind the call), CO knows no
|
|
8179
|
+
* conversation for it, or the lookup failed (logged).
|
|
8180
|
+
*/
|
|
8181
|
+
async resolveConversationSessionByCallSid(callSid) {
|
|
8182
|
+
const local = this.getConversationSessionByCallSid(callSid);
|
|
8183
|
+
if (local) {
|
|
8184
|
+
return local;
|
|
8185
|
+
}
|
|
8186
|
+
const client2 = this.conversationClient;
|
|
8187
|
+
if (!client2 || !this.provider.conversationClosedByOrchestrator) {
|
|
8188
|
+
return void 0;
|
|
8189
|
+
}
|
|
8190
|
+
let conversations;
|
|
8191
|
+
try {
|
|
8192
|
+
conversations = await client2.listConversations({ channelId: callSid });
|
|
8193
|
+
} catch (error) {
|
|
8194
|
+
this.logger.error(
|
|
8195
|
+
{ err: error, call_sid: callSid },
|
|
8196
|
+
"Failed to look up the conversation for a call"
|
|
8197
|
+
);
|
|
8198
|
+
return void 0;
|
|
8199
|
+
}
|
|
8200
|
+
if (conversations.length === 0) {
|
|
8201
|
+
return void 0;
|
|
8202
|
+
}
|
|
8203
|
+
const active = conversations.filter((c) => c.status === "ACTIVE");
|
|
8204
|
+
const candidates = active.length > 0 ? active : conversations;
|
|
8205
|
+
const createdAt = (c) => parseIso8601(c.createdAt) ?? Number.NEGATIVE_INFINITY;
|
|
8206
|
+
const chosen = candidates.reduce((best, c) => createdAt(c) > createdAt(best) ? c : best);
|
|
8207
|
+
return this.rebuildSession(chosen.id, callSid);
|
|
8208
|
+
}
|
|
7235
8209
|
// =========================================================================
|
|
7236
8210
|
// Stream Task Management
|
|
7237
8211
|
//
|
|
@@ -7321,6 +8295,8 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7321
8295
|
*/
|
|
7322
8296
|
shutdown() {
|
|
7323
8297
|
this.provider.shutdown();
|
|
8298
|
+
this.activeConversations.clear();
|
|
8299
|
+
this.closedWhileLive.clear();
|
|
7324
8300
|
super.shutdown();
|
|
7325
8301
|
}
|
|
7326
8302
|
};
|
|
@@ -7370,7 +8346,7 @@ var TwiMLBuilderMediaStreams = class extends TwiMLBuilderBase {
|
|
|
7370
8346
|
* 2. the provider config's `defaultTwimlOptions` — channel-wide defaults
|
|
7371
8347
|
* 3. `host` — per-call transport facts supplied by the host
|
|
7372
8348
|
* 4. TAC defaults: the WebSocket URL derived from
|
|
7373
|
-
* `TACConfig.
|
|
8349
|
+
* `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
|
|
7374
8350
|
*
|
|
7375
8351
|
* @param caller - Name of the calling method, used in the "no WebSocket URL"
|
|
7376
8352
|
* error so it points at the API the developer actually called.
|
|
@@ -7392,6 +8368,8 @@ var TwiMLBuilderMediaStreams = class extends TwiMLBuilderBase {
|
|
|
7392
8368
|
*
|
|
7393
8369
|
* `customParameters` replaces wholesale when set at a higher-priority layer —
|
|
7394
8370
|
* there's no per-key merging.
|
|
8371
|
+
*
|
|
8372
|
+
* @internal
|
|
7395
8373
|
*/
|
|
7396
8374
|
buildTwimlOptions(host, perCall) {
|
|
7397
8375
|
const merged = {};
|
|
@@ -7494,11 +8472,11 @@ var MediaStreamsOpenAICallState = class {
|
|
|
7494
8472
|
modelReady = null;
|
|
7495
8473
|
};
|
|
7496
8474
|
var OPENAI_USER_AGENT = `twilio-agent-connect/TypeScript ${package_default.version}`;
|
|
7497
|
-
var
|
|
8475
|
+
var SESSION_CONFIG_TOKEN_PARAM = "_tac_session_config_token";
|
|
7498
8476
|
function describeIssues(issues) {
|
|
7499
8477
|
return issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join(", ");
|
|
7500
8478
|
}
|
|
7501
|
-
var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
8479
|
+
var MediaStreamsOpenAIProvider = class _MediaStreamsOpenAIProvider extends VoiceProvider {
|
|
7502
8480
|
/**
|
|
7503
8481
|
* The owning channel's logger, so this provider logs under the same name the
|
|
7504
8482
|
* rest of the voice channel does.
|
|
@@ -7512,21 +8490,16 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7512
8490
|
tacConfig;
|
|
7513
8491
|
twimlBuilder;
|
|
7514
8492
|
/**
|
|
7515
|
-
*
|
|
8493
|
+
* Per-call session config overrides, minted by one Twilio request and
|
|
8494
|
+
* consumed when the call's WebSocket connects.
|
|
7516
8495
|
*
|
|
7517
|
-
*
|
|
7518
|
-
*
|
|
7519
|
-
*
|
|
8496
|
+
* Keyed by a token that rides the TwiML's custom parameters, rekeyed to the
|
|
8497
|
+
* call's conversation id on connect ({@link claimSessionConfig}). Set in
|
|
8498
|
+
* `handleIncomingCall` or `initiateOutboundConversation`, consumed when the
|
|
8499
|
+
* model connects. Bounded and expiring, so a call that never connects
|
|
8500
|
+
* doesn't leave its entry here forever.
|
|
7520
8501
|
*/
|
|
7521
8502
|
pendingSessionConfigs;
|
|
7522
|
-
/**
|
|
7523
|
-
* Expiry timers for the inbound {@link pendingSessionConfigs} entries, keyed
|
|
7524
|
-
* by the same call SID. Each fires once to purge a stash whose Media Stream
|
|
7525
|
-
* never connected; a normal connect cancels it in the subclass's
|
|
7526
|
-
* `registerCall`. Outbound entries are keyed by token instead and are not
|
|
7527
|
-
* tracked here.
|
|
7528
|
-
*/
|
|
7529
|
-
pendingInboundExpiries;
|
|
7530
8503
|
constructor(channel, tacConfig, config) {
|
|
7531
8504
|
super(channel);
|
|
7532
8505
|
this.logger = channel.getLoggerInternal();
|
|
@@ -7535,8 +8508,7 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7535
8508
|
this.toolsByName = new Map(config.tools.map((tool) => [tool.name, tool]));
|
|
7536
8509
|
this.calls = /* @__PURE__ */ new Map();
|
|
7537
8510
|
this.twimlBuilder = new TwiMLBuilderMediaStreams(tacConfig, config, this.logger);
|
|
7538
|
-
this.pendingSessionConfigs =
|
|
7539
|
-
this.pendingInboundExpiries = /* @__PURE__ */ new Map();
|
|
8511
|
+
this.pendingSessionConfigs = new ExpiringMap();
|
|
7540
8512
|
}
|
|
7541
8513
|
/** The Twilio-facing WebSocket for a conversation, if one is tracked. */
|
|
7542
8514
|
getWebSocket(conversationId) {
|
|
@@ -7574,16 +8546,17 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7574
8546
|
* The transcript captured so far for an in-progress call.
|
|
7575
8547
|
*
|
|
7576
8548
|
* It lives on `ConversationSession.metadata.transcript`, so once the call
|
|
7577
|
-
* ends and the session is
|
|
7578
|
-
* from the session
|
|
8549
|
+
* ends (and the session is released at WebSocket teardown) it is no longer
|
|
8550
|
+
* reachable here — read it from the session a `VoiceChannel.onCallEnded`
|
|
8551
|
+
* handler receives instead.
|
|
7579
8552
|
*/
|
|
7580
8553
|
getTranscript(conversationId) {
|
|
7581
8554
|
const transcript = this.channel.getConversationSession(conversationId)?.metadata.transcript;
|
|
7582
8555
|
return Array.isArray(transcript) ? [...transcript] : [];
|
|
7583
8556
|
}
|
|
7584
8557
|
/**
|
|
7585
|
-
* The session config stashed for `key` — a
|
|
7586
|
-
*
|
|
8558
|
+
* The session config stashed for `key` — a session-config token before the
|
|
8559
|
+
* call connects, its conversation id after.
|
|
7587
8560
|
*
|
|
7588
8561
|
* @internal
|
|
7589
8562
|
*/
|
|
@@ -7599,37 +8572,55 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7599
8572
|
return this.pendingSessionConfigs.size;
|
|
7600
8573
|
}
|
|
7601
8574
|
/**
|
|
7602
|
-
*
|
|
7603
|
-
*
|
|
7604
|
-
*
|
|
8575
|
+
* Mint a fresh session-config token.
|
|
8576
|
+
*
|
|
8577
|
+
* @internal
|
|
8578
|
+
*/
|
|
8579
|
+
static newSessionConfigToken() {
|
|
8580
|
+
return randomUUID().replace(/-/g, "");
|
|
8581
|
+
}
|
|
8582
|
+
/**
|
|
8583
|
+
* `perCall` with the session-config token added to the stream's custom
|
|
8584
|
+
* parameters.
|
|
7605
8585
|
*
|
|
7606
|
-
*
|
|
7607
|
-
* the call
|
|
7608
|
-
*
|
|
8586
|
+
* The builder replaces whole fields, so the token is added to the parameters
|
|
8587
|
+
* the call would otherwise get — from `perCall`, `defaultTwimlOptions` or
|
|
8588
|
+
* `host`, by the builder's precedence — rather than to `perCall`'s alone,
|
|
8589
|
+
* which would drop inherited ones.
|
|
8590
|
+
*
|
|
8591
|
+
* @internal
|
|
7609
8592
|
*/
|
|
7610
|
-
|
|
7611
|
-
this.
|
|
7612
|
-
|
|
7613
|
-
|
|
7614
|
-
|
|
7615
|
-
}
|
|
7616
|
-
timer.unref();
|
|
7617
|
-
this.pendingInboundExpiries.set(callSid, timer);
|
|
8593
|
+
withSessionConfigToken(host, perCall, token) {
|
|
8594
|
+
const effective = this.twimlBuilder.buildTwimlOptions(host, perCall).customParameters ?? {};
|
|
8595
|
+
return {
|
|
8596
|
+
...perCall,
|
|
8597
|
+
customParameters: { ...effective, [SESSION_CONFIG_TOKEN_PARAM]: token }
|
|
8598
|
+
};
|
|
7618
8599
|
}
|
|
7619
8600
|
/**
|
|
7620
|
-
*
|
|
7621
|
-
*
|
|
7622
|
-
*
|
|
7623
|
-
*
|
|
8601
|
+
* Move the session config stashed under `token` to this call's id.
|
|
8602
|
+
*
|
|
8603
|
+
* A token this instance doesn't hold means the config was stashed on another
|
|
8604
|
+
* instance — the TwiML webhook or `initiateOutboundConversation` ran
|
|
8605
|
+
* somewhere other than where the stream connected — or it expired. The call
|
|
8606
|
+
* then falls back to `defaultSessionConfig`, so this warns: with multiple
|
|
8607
|
+
* instances, per-call session configs need `TACConfig.instancePublicDomain`.
|
|
7624
8608
|
*
|
|
7625
8609
|
* @internal
|
|
7626
8610
|
*/
|
|
7627
|
-
|
|
7628
|
-
|
|
7629
|
-
|
|
7630
|
-
clearTimeout(timer);
|
|
7631
|
-
this.pendingInboundExpiries.delete(callSid);
|
|
8611
|
+
claimSessionConfig(token, conversationId) {
|
|
8612
|
+
if (token === void 0) {
|
|
8613
|
+
return;
|
|
7632
8614
|
}
|
|
8615
|
+
const sessionConfig = this.pendingSessionConfigs.take(token);
|
|
8616
|
+
if (sessionConfig === void 0) {
|
|
8617
|
+
this.logger.warn(
|
|
8618
|
+
{ conversation_id: conversationId },
|
|
8619
|
+
"Per-call sessionConfig not found on this instance; using defaultSessionConfig. With multiple instances, set TACConfig.instancePublicDomain so the stream connects to the instance that stashed it."
|
|
8620
|
+
);
|
|
8621
|
+
return;
|
|
8622
|
+
}
|
|
8623
|
+
this.pendingSessionConfigs.set(conversationId, sessionConfig);
|
|
7633
8624
|
}
|
|
7634
8625
|
/**
|
|
7635
8626
|
* The executable tool the model would run for `name`, if the config supplied
|
|
@@ -7655,12 +8646,14 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7655
8646
|
* 3. `options.hostTwimlOptions` — per-call transport facts supplied by the
|
|
7656
8647
|
* host
|
|
7657
8648
|
* 4. TAC defaults: the WebSocket URL derived from
|
|
7658
|
-
* `TACConfig.
|
|
8649
|
+
* `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
|
|
7659
8650
|
*
|
|
7660
8651
|
* Also runs `MediaStreamsOpenAIProviderConfig.onInboundCallSessionConfig`, if
|
|
7661
|
-
* set, and stashes its result for the call to pick up once it connects
|
|
7662
|
-
*
|
|
7663
|
-
*
|
|
8652
|
+
* set, and stashes its result for the call to pick up once it connects,
|
|
8653
|
+
* under a token carried on the stream's custom parameters — so the config is
|
|
8654
|
+
* found by the stream it belongs to rather than keyed to a call SID. The
|
|
8655
|
+
* stash is written only after the TwiML builds, so a webhook that fails
|
|
8656
|
+
* leaves nothing behind it.
|
|
7664
8657
|
*
|
|
7665
8658
|
* @param twimlRequest - Parsed Twilio webhook fields for the inbound call.
|
|
7666
8659
|
* @param options - Additional per-call inputs.
|
|
@@ -7686,13 +8679,18 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7686
8679
|
"the onInboundCallTwiml customizer output"
|
|
7687
8680
|
);
|
|
7688
8681
|
}
|
|
8682
|
+
let sessionConfig = null;
|
|
8683
|
+
if (this.config.onInboundCallSessionConfig && twimlRequest) {
|
|
8684
|
+
sessionConfig = await this.config.onInboundCallSessionConfig(twimlRequest);
|
|
8685
|
+
}
|
|
8686
|
+
let token;
|
|
8687
|
+
if (sessionConfig !== null) {
|
|
8688
|
+
token = _MediaStreamsOpenAIProvider.newSessionConfigToken();
|
|
8689
|
+
customized = this.withSessionConfigToken(host, customized, token);
|
|
8690
|
+
}
|
|
7689
8691
|
const twiml = this.twimlBuilder.build("handleIncomingCall", { host, perCall: customized });
|
|
7690
|
-
if (
|
|
7691
|
-
|
|
7692
|
-
if (sessionConfig !== null) {
|
|
7693
|
-
this.pendingSessionConfigs.set(twimlRequest.callSid, sessionConfig);
|
|
7694
|
-
this.armInboundConfigExpiry(twimlRequest.callSid);
|
|
7695
|
-
}
|
|
8692
|
+
if (token !== void 0 && sessionConfig !== null) {
|
|
8693
|
+
this.pendingSessionConfigs.set(token, sessionConfig);
|
|
7696
8694
|
}
|
|
7697
8695
|
return twiml;
|
|
7698
8696
|
}
|
|
@@ -7811,10 +8809,6 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7811
8809
|
*/
|
|
7812
8810
|
shutdown() {
|
|
7813
8811
|
super.shutdown();
|
|
7814
|
-
for (const timer of this.pendingInboundExpiries.values()) {
|
|
7815
|
-
clearTimeout(timer);
|
|
7816
|
-
}
|
|
7817
|
-
this.pendingInboundExpiries.clear();
|
|
7818
8812
|
this.calls.clear();
|
|
7819
8813
|
this.pendingSessionConfigs.clear();
|
|
7820
8814
|
}
|
|
@@ -7844,7 +8838,6 @@ var CallState = class extends MediaStreamsOpenAICallState {
|
|
|
7844
8838
|
};
|
|
7845
8839
|
|
|
7846
8840
|
// packages/core/src/channels/voice/media-streams/openai-realtime/provider.ts
|
|
7847
|
-
var SESSION_CONFIG_TOKEN_PARAM = "_tac_session_config_token";
|
|
7848
8841
|
var TWILIO_AUDIO_FORMAT_FOR_REALTIME = { type: "audio/pcmu" };
|
|
7849
8842
|
var PCMU_BYTES_PER_MS = 8;
|
|
7850
8843
|
function isTwilioMediaStreamAudioFormat(value) {
|
|
@@ -7856,7 +8849,7 @@ function isTwilioMediaStreamAudioFormat(value) {
|
|
|
7856
8849
|
const keys = Object.keys(actual);
|
|
7857
8850
|
return keys.length === Object.keys(expected).length && keys.every((key) => actual[key] === expected[key]);
|
|
7858
8851
|
}
|
|
7859
|
-
var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
8852
|
+
var OpenAIRealtimeProvider = class _OpenAIRealtimeProvider extends MediaStreamsOpenAIProvider {
|
|
7860
8853
|
/** @internal */
|
|
7861
8854
|
get providerId() {
|
|
7862
8855
|
return "openai_realtime";
|
|
@@ -7910,14 +8903,8 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
7910
8903
|
const sessionConfig = validated.sessionConfig ?? null;
|
|
7911
8904
|
let sessionConfigToken = null;
|
|
7912
8905
|
if (sessionConfig !== null) {
|
|
7913
|
-
sessionConfigToken =
|
|
7914
|
-
twimlOptions =
|
|
7915
|
-
...twimlOptions,
|
|
7916
|
-
customParameters: {
|
|
7917
|
-
...twimlOptions?.customParameters,
|
|
7918
|
-
[SESSION_CONFIG_TOKEN_PARAM]: sessionConfigToken
|
|
7919
|
-
}
|
|
7920
|
-
};
|
|
8906
|
+
sessionConfigToken = _OpenAIRealtimeProvider.newSessionConfigToken();
|
|
8907
|
+
twimlOptions = this.withSessionConfigToken(void 0, twimlOptions, sessionConfigToken);
|
|
7921
8908
|
}
|
|
7922
8909
|
const fromNumber = this.resolveFromNumber(validated.from);
|
|
7923
8910
|
this.logger.info(
|
|
@@ -8068,15 +9055,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8068
9055
|
registerCall(start, ws) {
|
|
8069
9056
|
const message = StreamStartMessageSchema.parse(start ?? {});
|
|
8070
9057
|
const conversationId = message.callSid;
|
|
8071
|
-
this.
|
|
8072
|
-
const token = message.customParameters[SESSION_CONFIG_TOKEN_PARAM];
|
|
8073
|
-
if (token !== void 0) {
|
|
8074
|
-
const pending = this.pendingSessionConfigs.get(token);
|
|
8075
|
-
if (pending !== void 0) {
|
|
8076
|
-
this.pendingSessionConfigs.delete(token);
|
|
8077
|
-
this.pendingSessionConfigs.set(conversationId, pending);
|
|
8078
|
-
}
|
|
8079
|
-
}
|
|
9058
|
+
this.claimSessionConfig(message.customParameters[SESSION_CONFIG_TOKEN_PARAM], conversationId);
|
|
8080
9059
|
try {
|
|
8081
9060
|
const session = this.channel.startConversationInternal(conversationId);
|
|
8082
9061
|
session.callSid = message.callSid;
|
|
@@ -8091,7 +9070,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8091
9070
|
});
|
|
8092
9071
|
} catch (err) {
|
|
8093
9072
|
this.pendingSessionConfigs.delete(conversationId);
|
|
8094
|
-
void this.channel.
|
|
9073
|
+
void this.channel.releaseSessionInternal(conversationId).catch(() => void 0);
|
|
8095
9074
|
throw err;
|
|
8096
9075
|
}
|
|
8097
9076
|
const call = new CallState();
|
|
@@ -8401,14 +9380,15 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8401
9380
|
this.modelSend(conversationId, { type: "response.create" });
|
|
8402
9381
|
}
|
|
8403
9382
|
/**
|
|
8404
|
-
* Drop this call's transport state
|
|
8405
|
-
* session.
|
|
9383
|
+
* Drop this call's transport state and any stashed session config, close
|
|
9384
|
+
* the model socket, and release the session.
|
|
8406
9385
|
*
|
|
8407
9386
|
* Both legs can report the call ending, and the first one to arrive tears
|
|
8408
9387
|
* down the other, so this runs at most once per call: a second invocation
|
|
8409
9388
|
* finds nothing tracked and returns.
|
|
8410
9389
|
*/
|
|
8411
9390
|
async cleanupCall(conversationId) {
|
|
9391
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
8412
9392
|
const call = this.calls.get(conversationId);
|
|
8413
9393
|
if (call === void 0) {
|
|
8414
9394
|
return;
|
|
@@ -8421,7 +9401,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8421
9401
|
this.logger.debug({ err, conversation_id: conversationId }, "Error closing model socket");
|
|
8422
9402
|
}
|
|
8423
9403
|
}
|
|
8424
|
-
await this.channel.
|
|
9404
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
8425
9405
|
}
|
|
8426
9406
|
};
|
|
8427
9407
|
|
|
@@ -8468,8 +9448,6 @@ var CallState2 = class extends MediaStreamsOpenAICallState {
|
|
|
8468
9448
|
// packages/core/src/channels/voice/media-streams/gpt-live/provider.ts
|
|
8469
9449
|
var TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE = { type: "audio/pcmu", rate: 8e3 };
|
|
8470
9450
|
var GPT_LIVE_SESSION_ID_METADATA_KEY = "gpt_live_session_id";
|
|
8471
|
-
var SESSION_CONFIG_TOKEN_PARAM2 = "_tac_session_config_token";
|
|
8472
|
-
var SESSION_CONFIG_TOKEN_TTL_MS = 12e4;
|
|
8473
9451
|
var GPT_LIVE_URL = "wss://api.openai.com/v1/live/sessions";
|
|
8474
9452
|
var CLOSE_TIMEOUT_MS = 5e3;
|
|
8475
9453
|
function isTwilioMediaStreamAudioFormat2(value) {
|
|
@@ -8497,7 +9475,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8497
9475
|
get providerId() {
|
|
8498
9476
|
return "gpt_live";
|
|
8499
9477
|
}
|
|
8500
|
-
pendingTokenExpiries = /* @__PURE__ */ new Map();
|
|
8501
9478
|
/** Calls whose teardown has begun but is still awaiting `session.closed`. */
|
|
8502
9479
|
closingCalls = /* @__PURE__ */ new Set();
|
|
8503
9480
|
get channelName() {
|
|
@@ -8540,14 +9517,8 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8540
9517
|
const sessionConfig = validated.sessionConfig ?? null;
|
|
8541
9518
|
let sessionConfigToken = null;
|
|
8542
9519
|
if (sessionConfig !== null) {
|
|
8543
|
-
sessionConfigToken =
|
|
8544
|
-
twimlOptions =
|
|
8545
|
-
...twimlOptions,
|
|
8546
|
-
customParameters: {
|
|
8547
|
-
...twimlOptions?.customParameters,
|
|
8548
|
-
[SESSION_CONFIG_TOKEN_PARAM2]: sessionConfigToken
|
|
8549
|
-
}
|
|
8550
|
-
};
|
|
9520
|
+
sessionConfigToken = _GPTLiveProvider.newSessionConfigToken();
|
|
9521
|
+
twimlOptions = this.withSessionConfigToken(void 0, twimlOptions, sessionConfigToken);
|
|
8551
9522
|
}
|
|
8552
9523
|
const fromNumber = this.resolveFromNumber(validated.from);
|
|
8553
9524
|
this.logger.info(
|
|
@@ -8580,9 +9551,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8580
9551
|
{ call_sid: call.sid, to: maskPhone(validated.to) },
|
|
8581
9552
|
"Outbound voice call placed"
|
|
8582
9553
|
);
|
|
8583
|
-
if (sessionConfigToken !== null) {
|
|
8584
|
-
this.armTokenExpiry(sessionConfigToken);
|
|
8585
|
-
}
|
|
8586
9554
|
return { callSid: call.sid };
|
|
8587
9555
|
} catch (error) {
|
|
8588
9556
|
if (sessionConfigToken !== null) {
|
|
@@ -8595,34 +9563,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8595
9563
|
throw error;
|
|
8596
9564
|
}
|
|
8597
9565
|
}
|
|
8598
|
-
/**
|
|
8599
|
-
* Start the clock on a stashed token, so a call that never connects cannot
|
|
8600
|
-
* strand its override in {@link pendingSessionConfigs} forever.
|
|
8601
|
-
*
|
|
8602
|
-
* Unref'd: a two-minute timer must not be what keeps the process alive after
|
|
8603
|
-
* the call it belongs to is long over.
|
|
8604
|
-
*/
|
|
8605
|
-
armTokenExpiry(token) {
|
|
8606
|
-
const timer = setTimeout(() => {
|
|
8607
|
-
this.pendingTokenExpiries.delete(token);
|
|
8608
|
-
this.pendingSessionConfigs.delete(token);
|
|
8609
|
-
}, SESSION_CONFIG_TOKEN_TTL_MS);
|
|
8610
|
-
timer.unref();
|
|
8611
|
-
this.pendingTokenExpiries.set(token, timer);
|
|
8612
|
-
}
|
|
8613
|
-
/**
|
|
8614
|
-
* Stop the clock on a token, once the call it belongs to has claimed it.
|
|
8615
|
-
*
|
|
8616
|
-
* Without this a two-minute timer outlives every call that connected
|
|
8617
|
-
* normally, waiting to purge an entry that is already gone.
|
|
8618
|
-
*/
|
|
8619
|
-
cancelTokenExpiry(token) {
|
|
8620
|
-
const timer = this.pendingTokenExpiries.get(token);
|
|
8621
|
-
if (timer !== void 0) {
|
|
8622
|
-
clearTimeout(timer);
|
|
8623
|
-
this.pendingTokenExpiries.delete(token);
|
|
8624
|
-
}
|
|
8625
|
-
}
|
|
8626
9566
|
// =========================================================================
|
|
8627
9567
|
// Audio Bridge
|
|
8628
9568
|
// =========================================================================
|
|
@@ -8719,16 +9659,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8719
9659
|
registerCall(start, ws) {
|
|
8720
9660
|
const message = StreamStartMessageSchema.parse(start ?? {});
|
|
8721
9661
|
const conversationId = message.callSid;
|
|
8722
|
-
this.
|
|
8723
|
-
const token = message.customParameters[SESSION_CONFIG_TOKEN_PARAM2];
|
|
8724
|
-
if (token !== void 0) {
|
|
8725
|
-
const pending = this.pendingSessionConfigs.get(token);
|
|
8726
|
-
if (pending !== void 0) {
|
|
8727
|
-
this.pendingSessionConfigs.delete(token);
|
|
8728
|
-
this.pendingSessionConfigs.set(conversationId, pending);
|
|
8729
|
-
}
|
|
8730
|
-
this.cancelTokenExpiry(token);
|
|
8731
|
-
}
|
|
9662
|
+
this.claimSessionConfig(message.customParameters[SESSION_CONFIG_TOKEN_PARAM], conversationId);
|
|
8732
9663
|
const call = new CallState2();
|
|
8733
9664
|
call.twilioWs = ws;
|
|
8734
9665
|
this.calls.set(conversationId, call);
|
|
@@ -8747,7 +9678,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8747
9678
|
} catch (err) {
|
|
8748
9679
|
this.calls.delete(conversationId);
|
|
8749
9680
|
this.pendingSessionConfigs.delete(conversationId);
|
|
8750
|
-
void this.channel.
|
|
9681
|
+
void this.channel.releaseSessionInternal(conversationId).catch(() => void 0);
|
|
8751
9682
|
throw err;
|
|
8752
9683
|
}
|
|
8753
9684
|
this.logger.debug(
|
|
@@ -8853,6 +9784,9 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8853
9784
|
async cleanupCall(conversationId) {
|
|
8854
9785
|
const call = this.calls.get(conversationId);
|
|
8855
9786
|
if (call === void 0 || this.closingCalls.has(conversationId)) {
|
|
9787
|
+
if (call === void 0) {
|
|
9788
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
9789
|
+
}
|
|
8856
9790
|
return;
|
|
8857
9791
|
}
|
|
8858
9792
|
this.closingCalls.add(conversationId);
|
|
@@ -8887,6 +9821,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8887
9821
|
}
|
|
8888
9822
|
this.calls.delete(conversationId);
|
|
8889
9823
|
this.closingCalls.delete(conversationId);
|
|
9824
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
8890
9825
|
if (modelWs !== null) {
|
|
8891
9826
|
try {
|
|
8892
9827
|
modelWs.close();
|
|
@@ -8894,21 +9829,13 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8894
9829
|
this.logger.debug({ err, conversation_id: conversationId }, "Error closing model socket");
|
|
8895
9830
|
}
|
|
8896
9831
|
}
|
|
8897
|
-
await this.channel.
|
|
9832
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
8898
9833
|
}
|
|
8899
9834
|
/**
|
|
8900
9835
|
* Drop this provider's transport state on channel shutdown, including the
|
|
8901
9836
|
* bookkeeping it keeps beyond the base class's.
|
|
8902
|
-
*
|
|
8903
|
-
* The token expiry timers are unref'd and delete themselves, so nothing hangs
|
|
8904
|
-
* without this — but a shut-down provider must not still be holding entries
|
|
8905
|
-
* for calls that can no longer arrive.
|
|
8906
9837
|
*/
|
|
8907
9838
|
shutdown() {
|
|
8908
|
-
for (const timer of this.pendingTokenExpiries.values()) {
|
|
8909
|
-
clearTimeout(timer);
|
|
8910
|
-
}
|
|
8911
|
-
this.pendingTokenExpiries.clear();
|
|
8912
9839
|
this.closingCalls.clear();
|
|
8913
9840
|
super.shutdown();
|
|
8914
9841
|
}
|
|
@@ -9074,51 +10001,6 @@ var GPTLiveProviderConfig = class extends MediaStreamsOpenAIProviderConfig {
|
|
|
9074
10001
|
}
|
|
9075
10002
|
};
|
|
9076
10003
|
|
|
9077
|
-
// packages/core/src/lib/conversation-session-helpers.ts
|
|
9078
|
-
function formatTraitValue(value) {
|
|
9079
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
9080
|
-
return String(value);
|
|
9081
|
-
}
|
|
9082
|
-
try {
|
|
9083
|
-
return JSON.stringify(value, (_key, replacerValue) => {
|
|
9084
|
-
if (typeof replacerValue === "bigint") {
|
|
9085
|
-
return String(replacerValue);
|
|
9086
|
-
}
|
|
9087
|
-
return replacerValue;
|
|
9088
|
-
}) ?? String(value);
|
|
9089
|
-
} catch {
|
|
9090
|
-
return String(value);
|
|
9091
|
-
}
|
|
9092
|
-
}
|
|
9093
|
-
function buildProfilePrompt(context, traitGroups) {
|
|
9094
|
-
if (!context.profile || !context.profile.traits) {
|
|
9095
|
-
return null;
|
|
9096
|
-
}
|
|
9097
|
-
let filteredTraits;
|
|
9098
|
-
if (traitGroups !== void 0) {
|
|
9099
|
-
if (traitGroups.length === 0) {
|
|
9100
|
-
return null;
|
|
9101
|
-
}
|
|
9102
|
-
filteredTraits = Object.fromEntries(
|
|
9103
|
-
Object.entries(context.profile.traits).filter(
|
|
9104
|
-
([key, value]) => traitGroups.includes(key) && value != null
|
|
9105
|
-
)
|
|
9106
|
-
);
|
|
9107
|
-
} else {
|
|
9108
|
-
filteredTraits = Object.fromEntries(
|
|
9109
|
-
Object.entries(context.profile.traits).filter(([, value]) => value != null)
|
|
9110
|
-
);
|
|
9111
|
-
}
|
|
9112
|
-
if (Object.keys(filteredTraits).length === 0) {
|
|
9113
|
-
return null;
|
|
9114
|
-
}
|
|
9115
|
-
const lines = ["## Customer Profile", "Information about this customer:"];
|
|
9116
|
-
for (const [key, value] of Object.entries(filteredTraits)) {
|
|
9117
|
-
lines.push(`- ${key}: ${formatTraitValue(value)}`);
|
|
9118
|
-
}
|
|
9119
|
-
return lines.join("\n");
|
|
9120
|
-
}
|
|
9121
|
-
|
|
9122
10004
|
// packages/core/src/adapters/options.ts
|
|
9123
10005
|
function getProfileTraits(options) {
|
|
9124
10006
|
if (!options || options.profileTraits === void 0) {
|
|
@@ -9446,7 +10328,7 @@ function createMemoryTools(memoryClient) {
|
|
|
9446
10328
|
}
|
|
9447
10329
|
|
|
9448
10330
|
// packages/tools/src/built-in/messaging.ts
|
|
9449
|
-
function createSendMessageTool(channel,
|
|
10331
|
+
function createSendMessageTool(channel, conversationIdOrSession) {
|
|
9450
10332
|
return defineTool(
|
|
9451
10333
|
BuiltInTools.SEND_MESSAGE,
|
|
9452
10334
|
"Send a message to the user in the current conversation",
|
|
@@ -9467,7 +10349,7 @@ function createSendMessageTool(channel, conversationId) {
|
|
|
9467
10349
|
},
|
|
9468
10350
|
async (params) => {
|
|
9469
10351
|
try {
|
|
9470
|
-
await channel.sendResponse(
|
|
10352
|
+
await channel.sendResponse(conversationIdOrSession, params.message, params.metadata);
|
|
9471
10353
|
return {
|
|
9472
10354
|
success: true,
|
|
9473
10355
|
message_id: `msg_${Date.now()}`
|
|
@@ -9485,11 +10367,30 @@ function createSendMessageTool(channel, conversationId) {
|
|
|
9485
10367
|
function createMessagingTools() {
|
|
9486
10368
|
return {
|
|
9487
10369
|
/**
|
|
9488
|
-
* Create send message tool for specific channel and conversation
|
|
10370
|
+
* Create send message tool for specific channel and conversation. Prefer
|
|
10371
|
+
* passing the turn's `ConversationSession` (see {@link createSendMessageTool}).
|
|
9489
10372
|
*/
|
|
9490
|
-
forConversation: (channel,
|
|
10373
|
+
forConversation: (channel, conversationIdOrSession) => createSendMessageTool(channel, conversationIdOrSession)
|
|
9491
10374
|
};
|
|
9492
10375
|
}
|
|
10376
|
+
async function stopTacRouting(tac, coClient, conversationId) {
|
|
10377
|
+
try {
|
|
10378
|
+
await coClient.updateConversation(conversationId, "INACTIVE");
|
|
10379
|
+
} catch (err) {
|
|
10380
|
+
tac.logger.warn(
|
|
10381
|
+
{ err, conversation_id: conversationId },
|
|
10382
|
+
"Failed to set conversation INACTIVE during handoff"
|
|
10383
|
+
);
|
|
10384
|
+
}
|
|
10385
|
+
try {
|
|
10386
|
+
await coClient.clearStatusCallbacks(conversationId);
|
|
10387
|
+
} catch (err) {
|
|
10388
|
+
tac.logger.warn(
|
|
10389
|
+
{ err, conversation_id: conversationId },
|
|
10390
|
+
"Failed to clear status callbacks during handoff"
|
|
10391
|
+
);
|
|
10392
|
+
}
|
|
10393
|
+
}
|
|
9493
10394
|
function buildHandoffPayload(session, memoryStoreId, attributes) {
|
|
9494
10395
|
return {
|
|
9495
10396
|
conversationId: session.conversationId,
|
|
@@ -9505,7 +10406,7 @@ async function postStudioHandoff(payload, session, options) {
|
|
|
9505
10406
|
form.append("To", toAddress);
|
|
9506
10407
|
form.append("From", fromAddress);
|
|
9507
10408
|
form.append("Parameters", JSON.stringify({ HandoffData: payload }));
|
|
9508
|
-
await
|
|
10409
|
+
await axios3.post(handoffUrl, form.toString(), {
|
|
9509
10410
|
timeout: 1e4,
|
|
9510
10411
|
auth: { username: apiKey, password: apiSecret },
|
|
9511
10412
|
headers: { "Content-Type": "application/x-www-form-urlencoded" }
|
|
@@ -9553,49 +10454,53 @@ function createStudioHandoffTool(tac, session, options = {}) {
|
|
|
9553
10454
|
async (params) => {
|
|
9554
10455
|
const attributes = { ...staticAttributes, reason: params.reason };
|
|
9555
10456
|
const payload = buildHandoffPayload(session, memoryStoreId, attributes);
|
|
9556
|
-
|
|
9557
|
-
await coClient
|
|
9558
|
-
|
|
9559
|
-
|
|
9560
|
-
|
|
9561
|
-
|
|
10457
|
+
if (session.channel === "voice") {
|
|
10458
|
+
await stopTacRouting(tac, coClient, session.conversationId);
|
|
10459
|
+
const pending = {
|
|
10460
|
+
type: "end",
|
|
10461
|
+
handoffData: JSON.stringify(payload)
|
|
10462
|
+
};
|
|
10463
|
+
session.pendingHandoffData = pending;
|
|
10464
|
+
return { status: "handoff_initiated", channel: session.channel };
|
|
10465
|
+
}
|
|
10466
|
+
const failUndeliverable = (error) => {
|
|
10467
|
+
tac.logger.error(
|
|
10468
|
+
{ conversation_id: session.conversationId },
|
|
10469
|
+
`Failed to deliver handoff payload: ${error}`
|
|
10470
|
+
);
|
|
10471
|
+
return { status: "handoff_failed", channel: session.channel, error };
|
|
10472
|
+
};
|
|
10473
|
+
const toAddress = session.authorInfo?.address;
|
|
10474
|
+
if (!toAddress) {
|
|
10475
|
+
return failUndeliverable(
|
|
10476
|
+
`No Studio \`To\` address for ${session.channel} handoff: the session has no customer address.`
|
|
10477
|
+
);
|
|
10478
|
+
}
|
|
10479
|
+
const fromAddress = session.channel !== "chat" && session.aiAgentInfo?.address ? session.aiAgentInfo.address : config.phoneNumber;
|
|
10480
|
+
if (!fromAddress) {
|
|
10481
|
+
return failUndeliverable(
|
|
10482
|
+
`No Studio \`From\` sender for ${session.channel} handoff: set phoneNumber in TACConfig.`
|
|
9562
10483
|
);
|
|
9563
10484
|
}
|
|
10485
|
+
await stopTacRouting(tac, coClient, session.conversationId);
|
|
9564
10486
|
try {
|
|
9565
|
-
await
|
|
10487
|
+
await postStudioHandoff(payload, session, {
|
|
10488
|
+
handoffUrl: studioExecutionsUrl(flowSid),
|
|
10489
|
+
fromAddress,
|
|
10490
|
+
apiKey: config.apiKey,
|
|
10491
|
+
apiSecret: config.apiSecret
|
|
10492
|
+
});
|
|
9566
10493
|
} catch (err) {
|
|
9567
|
-
|
|
10494
|
+
const message = err instanceof AxiosError ? err.message : err instanceof Error ? err.message : String(err);
|
|
10495
|
+
tac.logger.error(
|
|
9568
10496
|
{ err, conversation_id: session.conversationId },
|
|
9569
|
-
"Failed to
|
|
10497
|
+
"Failed to deliver handoff payload"
|
|
9570
10498
|
);
|
|
9571
|
-
|
|
9572
|
-
|
|
9573
|
-
|
|
9574
|
-
|
|
9575
|
-
handoffData: JSON.stringify(payload)
|
|
10499
|
+
return {
|
|
10500
|
+
status: "handoff_failed",
|
|
10501
|
+
channel: session.channel,
|
|
10502
|
+
error: message
|
|
9576
10503
|
};
|
|
9577
|
-
session.pendingHandoffData = pending;
|
|
9578
|
-
} else {
|
|
9579
|
-
try {
|
|
9580
|
-
const fromAddress = session.channel !== "chat" && session.aiAgentInfo?.address ? session.aiAgentInfo.address : config.phoneNumber;
|
|
9581
|
-
await postStudioHandoff(payload, session, {
|
|
9582
|
-
handoffUrl: studioExecutionsUrl(flowSid),
|
|
9583
|
-
fromAddress,
|
|
9584
|
-
apiKey: config.apiKey,
|
|
9585
|
-
apiSecret: config.apiSecret
|
|
9586
|
-
});
|
|
9587
|
-
} catch (err) {
|
|
9588
|
-
const message = err instanceof AxiosError ? err.message : err instanceof Error ? err.message : String(err);
|
|
9589
|
-
tac.logger.error(
|
|
9590
|
-
{ err, conversation_id: session.conversationId },
|
|
9591
|
-
"Failed to deliver handoff payload"
|
|
9592
|
-
);
|
|
9593
|
-
return {
|
|
9594
|
-
status: "handoff_failed",
|
|
9595
|
-
channel: session.channel,
|
|
9596
|
-
error: message
|
|
9597
|
-
};
|
|
9598
|
-
}
|
|
9599
10504
|
}
|
|
9600
10505
|
return { status: "handoff_initiated", channel: session.channel };
|
|
9601
10506
|
}
|
|
@@ -9696,9 +10601,9 @@ var TACServer = class {
|
|
|
9696
10601
|
webhookPaths
|
|
9697
10602
|
};
|
|
9698
10603
|
this.voiceChannel = config.voiceChannel ?? tac.getChannel("voice");
|
|
9699
|
-
if (this.voiceChannel && !tac.getConfig().
|
|
10604
|
+
if (this.voiceChannel && !tac.getConfig().voiceCallbackDomain) {
|
|
9700
10605
|
throw new Error(
|
|
9701
|
-
"Voice channel is configured but TACConfig.voicePublicDomain is not set. Set it directly or via the TWILIO_VOICE_PUBLIC_DOMAIN env var."
|
|
10606
|
+
"Voice channel is configured but TACConfig.voicePublicDomain is not set. Set it directly or via the TWILIO_VOICE_PUBLIC_DOMAIN env var. (TACConfig.instancePublicDomain also satisfies this, if each replica is directly addressable.)"
|
|
9702
10607
|
);
|
|
9703
10608
|
}
|
|
9704
10609
|
this.validateCallEventPaths();
|
|
@@ -10098,6 +11003,6 @@ var TACServer = class {
|
|
|
10098
11003
|
}
|
|
10099
11004
|
};
|
|
10100
11005
|
|
|
10101
|
-
export { ActionChannelSettingsSchema, ActionParticipantRefSchema, ActionResponseSchema, ActionTextContentSchema, AmdEventSchema, AnthropicToolSchema, AuthorInfoSchema, BaseChannel, BaseClient, BuiltInTools, CALL_EVENT_KINDS, CallEventKindSchema, CallOptionsSchema, CallStatusEventSchema, CaptureRuleSchema, ChannelSettingsSchema, ChannelTypeSchema, ChatChannel, CintelParticipantSchema, CommunicationContentSchema, CommunicationParticipantSchema, CommunicationSchema, ConversationAddressSchema, ConversationClient, ConversationConfigurationSchema, ConversationGroupingTypeSchema, ConversationIntelligenceConfigSchema, ConversationParticipantSchema, ConversationRelayAttributesSchema, ConversationRelayCallbackPayloadSchema, ConversationRelayConfigSchema, ConversationRelayProvider, ConversationRelayProviderConfig, ConversationResponseSchema, ConversationSessionSchema, ConversationSummaryItemSchema, CreateConversationSummariesResponseSchema, CreateObservationResponseSchema, CreateObservationsRequestSchema, CustomParametersSchema, DtmfMessageSchema, EMPTY_MEMORY_RESPONSE, EnvironmentVariables, ExecutionDetailsSchema, GPTLiveProvider, GPTLiveProviderConfig, GPT_LIVE_SESSION_ID_METADATA_KEY, HandoffPayloadSchema, InitiateMessagingConversationOptionsSchema, InitiateVoiceConversationOptionsGPTLiveSchema, InitiateVoiceConversationOptionsOpenAIRealtimeSchema, InitiateVoiceConversationOptionsSchema, IntelligenceConfigurationSchema, InterruptMessageSchema, InterruptModeSchema, JSONSchemaSchema, KnowledgeBaseSchema, KnowledgeBaseStatusSchema, KnowledgeChunkResultSchema, KnowledgeClient, KnowledgeSearchResponseSchema, LanguageAttributesSchema, LanguageConfigSchema, ListCommunicationsResponseSchema, ListConversationsResponseSchema, ListParticipantsResponseSchema, MediaStreamsOpenAICallState, MediaStreamsOpenAIProvider, MediaStreamsOpenAIProviderConfig, MediaStreamsProviderConfig, MemoryChannelTypeSchema, MemoryClient, MemoryCommunicationContentSchema, MemoryCommunicationSchema, MemoryDeliveryStatusSchema, MemoryModeSchema, MemoryParticipantSchema, MemoryParticipantTypeSchema, MemoryPromptBuilder, MemoryRetrievalRequestSchema, MemoryRetrievalResponseSchema, MessageDirectionSchema, MessagingChannel, OPENAI_USER_AGENT, ObservationCreateRequestSchema, ObservationInfoSchema, OpenAIRealtimeProvider, OpenAIRealtimeProviderConfig, OpenAIRealtimeToolSchema, OpenAIToolSchema, OperatorProcessingResultSchema, OperatorResultEventSchema, OperatorResultProcessor, OperatorResultSchema, OperatorSchema, ParticipantAddressSchema, ParticipantAddressTypeSchema, PendingHandoffDataSchema, ProfileLookupResponseSchema, ProfileResponseSchema, PromptMessageSchema, RCSChannel, RecordingEventSchema, SMSChannel, SendMessageActionPayloadSchema, SendMessageActionRequestSchema, SessionInfoSchema, SessionMessageSchema, SetupMessageSchema, StatusCallbackSchema, StatusTimeoutsSchema, StreamStartMessageSchema, SummaryInfoSchema, TAC, TACChannelTypeSchema, TACCommunicationAuthorSchema, TACCommunicationContentSchema, TACCommunicationSchema, TACConfig, TACConfigSchema, TACDeliveryStatusSchema, TACMemoryResponse, TACParticipantTypeSchema, TACServer, TACTool, TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE, TWILIO_AUDIO_FORMAT_FOR_REALTIME, TextTokenMessageSchema, ToolExecutionResultSchema, TranscriptionSchema, TranscriptionWordSchema, TwiMLBuilderMediaStreams, TwiMLOptionsSchema, TwiMLRequestSchema, TwilioMemoryConfigSchema, VoiceChannel, VoiceProvider, VoiceProviderConfig, VoiceTwiMLOptionsConversationRelaySchema, VoiceTwiMLOptionsMediaStreamsSchema, VoiceTwiMLOptionsSchema, WebSocketMessageSchema, WhatsAppChannel, 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 };
|
|
11006
|
+
export { ActionChannelSettingsSchema, ActionParticipantRefSchema, ActionResponseSchema, ActionTextContentSchema, AmdEventSchema, AnthropicToolSchema, AuthorInfoSchema, BaseChannel, BaseClient, BuiltInTools, CALL_EVENT_KINDS, CallEventKindSchema, CallOptionsSchema, CallStatusEventSchema, CaptureRuleSchema, ChannelSettingsSchema, ChannelTypeSchema, ChatChannel, CintelParticipantSchema, CommunicationContentSchema, CommunicationParticipantSchema, CommunicationSchema, ConversationAddressSchema, ConversationClient, ConversationConfigurationSchema, ConversationGroupingTypeSchema, ConversationIntelligenceConfigSchema, ConversationParticipantSchema, ConversationRelayAttributesSchema, ConversationRelayCallbackPayloadSchema, ConversationRelayConfigSchema, ConversationRelayProvider, ConversationRelayProviderConfig, ConversationResponseSchema, ConversationSessionSchema, ConversationSummaryItemSchema, CreateConversationSummariesResponseSchema, CreateObservationResponseSchema, CreateObservationsRequestSchema, CustomParametersSchema, DtmfMessageSchema, EMPTY_MEMORY_RESPONSE, EnvironmentVariables, ExecutionDetailsSchema, GPTLiveProvider, GPTLiveProviderConfig, GPT_LIVE_SESSION_ID_METADATA_KEY, HandoffPayloadSchema, InitiateMessagingConversationOptionsSchema, InitiateVoiceConversationOptionsGPTLiveSchema, InitiateVoiceConversationOptionsOpenAIRealtimeSchema, InitiateVoiceConversationOptionsSchema, IntelligenceConfigurationSchema, InterruptMessageSchema, InterruptModeSchema, JSONSchemaSchema, KnowledgeBaseSchema, KnowledgeBaseStatusSchema, KnowledgeChunkResultSchema, KnowledgeClient, KnowledgeSearchResponseSchema, LanguageAttributesSchema, LanguageConfigSchema, ListCommunicationsResponseSchema, ListConversationsResponseSchema, ListParticipantsResponseSchema, MediaStreamsOpenAICallState, MediaStreamsOpenAIProvider, MediaStreamsOpenAIProviderConfig, MediaStreamsProviderConfig, MemoryChannelTypeSchema, MemoryClient, MemoryCommunicationContentSchema, MemoryCommunicationSchema, MemoryDeliveryStatusSchema, MemoryModeSchema, MemoryParticipantSchema, MemoryParticipantTypeSchema, MemoryPromptBuilder, MemoryRetrievalRequestSchema, MemoryRetrievalResponseSchema, MessageDirectionSchema, MessagingChannel, OPENAI_USER_AGENT, ObservationCreateRequestSchema, ObservationInfoSchema, OpenAIRealtimeProvider, OpenAIRealtimeProviderConfig, OpenAIRealtimeToolSchema, OpenAIToolSchema, OperatorProcessingResultSchema, OperatorResultEventSchema, OperatorResultProcessor, OperatorResultSchema, OperatorSchema, ParticipantAddressSchema, ParticipantAddressTypeSchema, PendingHandoffDataSchema, ProfileLookupResponseSchema, ProfileResponseSchema, PromptMessageSchema, RCSChannel, RecordingEventSchema, SMSChannel, SendMessageActionPayloadSchema, SendMessageActionRequestSchema, SessionInfoSchema, SessionMessageSchema, SetupMessageSchema, StatusCallbackSchema, StatusTimeoutsSchema, StreamStartMessageSchema, SummaryInfoSchema, TAC, TACChannelTypeSchema, TACCommunicationAuthorSchema, TACCommunicationContentSchema, TACCommunicationSchema, TACConfig, TACConfigSchema, TACDeliveryStatusSchema, TACMemoryResponse, TACParticipantTypeSchema, TACServer, TACTool, TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE, TWILIO_AUDIO_FORMAT_FOR_REALTIME, TextTokenMessageSchema, ToolExecutionResultSchema, TranscriptionSchema, TranscriptionWordSchema, TwiMLBuilderMediaStreams, TwiMLOptionsSchema, TwiMLRequestSchema, TwilioMemoryConfigSchema, VoiceChannel, VoiceProvider, VoiceProviderConfig, VoiceTwiMLOptionsConversationRelaySchema, VoiceTwiMLOptionsMediaStreamsSchema, VoiceTwiMLOptionsSchema, WebSocketMessageSchema, WhatsAppChannel, 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 };
|
|
10102
11007
|
//# sourceMappingURL=index.js.map
|
|
10103
11008
|
//# sourceMappingURL=index.js.map
|