twilio-agent-connect 2.4.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 +14 -12
- package/dist/index.d.ts +991 -200
- package/dist/index.js +2227 -1023
- package/dist/index.js.map +1 -1
- package/package.json +9 -5
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,19 +37,73 @@ 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;
|
|
55
|
+
var RCS_SENDER_ID_REGEX = /^rcs:.+$/;
|
|
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)";
|
|
57
|
+
var WHATSAPP_NUMBER_REGEX = /^whatsapp:\+\d+$/;
|
|
58
|
+
var WHATSAPP_NUMBER_MESSAGE = "WhatsApp number must be in format: whatsapp:+1234567890";
|
|
59
|
+
function normalizeSenderPair(defaultValue, plural) {
|
|
60
|
+
const trimmedDefault = typeof defaultValue === "string" && defaultValue.trim().length > 0 ? defaultValue.trim() : void 0;
|
|
61
|
+
const cleaned = [];
|
|
62
|
+
for (const entry of plural) {
|
|
63
|
+
const trimmed = entry.trim();
|
|
64
|
+
if (trimmed && !cleaned.includes(trimmed)) {
|
|
65
|
+
cleaned.push(trimmed);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (trimmedDefault === void 0 && cleaned.length === 0) {
|
|
69
|
+
return { default: void 0, plural: [] };
|
|
70
|
+
}
|
|
71
|
+
const resolvedDefault = trimmedDefault ?? cleaned[0];
|
|
72
|
+
const withoutDefault = cleaned.filter((a) => a !== resolvedDefault);
|
|
73
|
+
return { default: resolvedDefault, plural: [resolvedDefault, ...withoutDefault] };
|
|
74
|
+
}
|
|
41
75
|
var TACConfigSchema = z.object({
|
|
42
76
|
accountSid: z.string().min(1, "Twilio Account SID is required"),
|
|
43
77
|
authToken: z.string().min(1, "Twilio Auth Token is required"),
|
|
44
78
|
apiKey: z.string().min(1, "Twilio API Key is required"),
|
|
45
79
|
apiSecret: z.string().min(1, "Twilio API Secret is required"),
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
80
|
+
/**
|
|
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.
|
|
85
|
+
*/
|
|
86
|
+
phoneNumber: z.string().min(1, "Twilio Phone Number is required").optional(),
|
|
87
|
+
/**
|
|
88
|
+
* Full set of Twilio phone numbers this instance serves for Voice and SMS
|
|
89
|
+
* (the inbound allowlist). Defaults to `[phoneNumber]` when omitted;
|
|
90
|
+
* `phoneNumber` is always included as the default sender.
|
|
91
|
+
*/
|
|
92
|
+
phoneNumbers: z.array(z.string().min(1, "Twilio Phone Number is required")).optional(),
|
|
93
|
+
/** Default Twilio RCS Sender ID. Optional; symmetric with `rcsSenderIds`. */
|
|
94
|
+
rcsSenderId: z.string().trim().regex(RCS_SENDER_ID_REGEX, RCS_SENDER_ID_MESSAGE).optional(),
|
|
95
|
+
/**
|
|
96
|
+
* Full set of Twilio RCS Sender IDs this instance serves. Defaults to
|
|
97
|
+
* `[rcsSenderId]` when a default is set.
|
|
98
|
+
*/
|
|
99
|
+
rcsSenderIds: z.array(z.string().trim().regex(RCS_SENDER_ID_REGEX, RCS_SENDER_ID_MESSAGE)).optional(),
|
|
100
|
+
/** Default Twilio WhatsApp number. Optional; symmetric with `whatsappNumbers`. */
|
|
101
|
+
whatsappNumber: z.string().trim().regex(WHATSAPP_NUMBER_REGEX, WHATSAPP_NUMBER_MESSAGE).optional(),
|
|
102
|
+
/**
|
|
103
|
+
* Full set of Twilio WhatsApp numbers this instance serves. Defaults to
|
|
104
|
+
* `[whatsappNumber]` when a default is set.
|
|
105
|
+
*/
|
|
106
|
+
whatsappNumbers: z.array(z.string().trim().regex(WHATSAPP_NUMBER_REGEX, WHATSAPP_NUMBER_MESSAGE)).optional(),
|
|
52
107
|
memoryConfig: TwilioMemoryConfigSchema.prefault({}),
|
|
53
108
|
conversationConfigurationId: z.string().regex(/^conv_configuration_[0-9a-z]{26}$/, "Invalid Conversation Configuration ID format").optional(),
|
|
54
109
|
/**
|
|
@@ -61,19 +116,21 @@ var TACConfigSchema = z.object({
|
|
|
61
116
|
* automatically; anything else is passed through as given. Mirrors the Python
|
|
62
117
|
* SDK's `_normalize_voice_public_domain` — keep the two in step.
|
|
63
118
|
*/
|
|
64
|
-
voicePublicDomain:
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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(),
|
|
77
134
|
/**
|
|
78
135
|
* Path the voice WebSocket is served at. Combined with voicePublicDomain to
|
|
79
136
|
* build the public WebSocket URL the voice channel hands to Twilio in TwiML;
|
|
@@ -109,6 +166,19 @@ var TACConfigSchema = z.object({
|
|
|
109
166
|
/^FW[0-9a-f]{32}$/,
|
|
110
167
|
"Invalid Studio Flow SID format (expected FW followed by 32 hex chars)"
|
|
111
168
|
).optional()
|
|
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 ?? []);
|
|
173
|
+
return {
|
|
174
|
+
...data,
|
|
175
|
+
phoneNumber: phone.default,
|
|
176
|
+
phoneNumbers: phone.plural,
|
|
177
|
+
rcsSenderId: rcs.default,
|
|
178
|
+
rcsSenderIds: rcs.plural,
|
|
179
|
+
whatsappNumber: whatsapp.default,
|
|
180
|
+
whatsappNumbers: whatsapp.plural
|
|
181
|
+
};
|
|
112
182
|
});
|
|
113
183
|
var EnvironmentVariables = {
|
|
114
184
|
TWILIO_ACCOUNT_SID: "TWILIO_ACCOUNT_SID",
|
|
@@ -116,8 +186,11 @@ var EnvironmentVariables = {
|
|
|
116
186
|
TWILIO_API_KEY: "TWILIO_API_KEY",
|
|
117
187
|
TWILIO_API_SECRET: "TWILIO_API_SECRET",
|
|
118
188
|
TWILIO_PHONE_NUMBER: "TWILIO_PHONE_NUMBER",
|
|
189
|
+
TWILIO_PHONE_NUMBERS: "TWILIO_PHONE_NUMBERS",
|
|
119
190
|
TWILIO_RCS_SENDER_ID: "TWILIO_RCS_SENDER_ID",
|
|
191
|
+
TWILIO_RCS_SENDER_IDS: "TWILIO_RCS_SENDER_IDS",
|
|
120
192
|
TWILIO_WHATSAPP_NUMBER: "TWILIO_WHATSAPP_NUMBER",
|
|
193
|
+
TWILIO_WHATSAPP_NUMBERS: "TWILIO_WHATSAPP_NUMBERS",
|
|
121
194
|
TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: "TWILIO_MEMORY_PROFILE_TRAIT_GROUPS",
|
|
122
195
|
TWILIO_MEMORY_OBSERVATIONS_LIMIT: "TWILIO_MEMORY_OBSERVATIONS_LIMIT",
|
|
123
196
|
TWILIO_MEMORY_SUMMARIES_LIMIT: "TWILIO_MEMORY_SUMMARIES_LIMIT",
|
|
@@ -127,6 +200,7 @@ var EnvironmentVariables = {
|
|
|
127
200
|
TWILIO_MEMORY_PHONE_TRAIT_FIELD: "TWILIO_MEMORY_PHONE_TRAIT_FIELD",
|
|
128
201
|
TWILIO_CONVERSATION_CONFIGURATION_ID: "TWILIO_CONVERSATION_CONFIGURATION_ID",
|
|
129
202
|
TWILIO_VOICE_PUBLIC_DOMAIN: "TWILIO_VOICE_PUBLIC_DOMAIN",
|
|
203
|
+
TWILIO_INSTANCE_PUBLIC_DOMAIN: "TWILIO_INSTANCE_PUBLIC_DOMAIN",
|
|
130
204
|
TWILIO_VOICE_WEBSOCKET_PATH: "TWILIO_VOICE_WEBSOCKET_PATH",
|
|
131
205
|
TWILIO_VOICE_ACTION_PATH: "TWILIO_VOICE_ACTION_PATH",
|
|
132
206
|
TWILIO_VOICE_CALL_EVENT_PATH: "TWILIO_VOICE_CALL_EVENT_PATH",
|
|
@@ -241,7 +315,8 @@ var ConversationSessionSchema = z.object({
|
|
|
241
315
|
* Twilio Call SID on the Voice channel, unset on messaging. The correlation
|
|
242
316
|
* key for call events (`VoiceChannel.onCallStatus` / `onAmd` / `onRecording`)
|
|
243
317
|
* and `endCall`. Equals `conversationId` in relay-only mode; look the session
|
|
244
|
-
* up the other way with `VoiceChannel.getConversationSessionByCallSid
|
|
318
|
+
* up the other way with `VoiceChannel.getConversationSessionByCallSid`, or,
|
|
319
|
+
* from another instance, `VoiceChannel.resolveConversationSessionByCallSid`.
|
|
245
320
|
*/
|
|
246
321
|
callSid: z.string().optional(),
|
|
247
322
|
profileId: z.string().optional(),
|
|
@@ -256,6 +331,13 @@ var ConversationSessionSchema = z.object({
|
|
|
256
331
|
*/
|
|
257
332
|
aiAgentInfo: AuthorInfoSchema.optional(),
|
|
258
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
|
+
*/
|
|
259
341
|
metadata: z.record(z.string(), z.unknown()).optional().default({}),
|
|
260
342
|
/**
|
|
261
343
|
* Pending handoff payload set by the handoff tool. Voice channel sends
|
|
@@ -277,6 +359,11 @@ function isProfileId(value) {
|
|
|
277
359
|
function isParticipantId(value) {
|
|
278
360
|
return value.length > 0;
|
|
279
361
|
}
|
|
362
|
+
function stringEntries(value) {
|
|
363
|
+
return Object.fromEntries(
|
|
364
|
+
Object.entries(value).filter((entry) => typeof entry[1] === "string")
|
|
365
|
+
);
|
|
366
|
+
}
|
|
280
367
|
var ConversationResponseSchema = z.object({
|
|
281
368
|
id: z.string(),
|
|
282
369
|
accountId: z.string(),
|
|
@@ -285,7 +372,17 @@ var ConversationResponseSchema = z.object({
|
|
|
285
372
|
// API returns null when not set
|
|
286
373
|
configurationId: z.string().optional(),
|
|
287
374
|
createdAt: z.string().optional(),
|
|
288
|
-
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
|
+
)
|
|
289
386
|
});
|
|
290
387
|
var ListConversationsResponseSchema = z.object({
|
|
291
388
|
conversations: z.array(ConversationResponseSchema)
|
|
@@ -348,7 +445,20 @@ var ConversationConfigurationSchema = z.object({
|
|
|
348
445
|
var InitiateMessagingConversationOptionsSchema = z.object({
|
|
349
446
|
to: z.string().min(1, "Recipient address is required"),
|
|
350
447
|
message: z.string().min(1, "Initial message is required"),
|
|
351
|
-
|
|
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
|
+
*/
|
|
454
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
455
|
+
/**
|
|
456
|
+
* Sender address to send from. Must be one of the channel's configured
|
|
457
|
+
* senders (`config.phoneNumbers` / `rcsSenderIds` / `whatsappNumbers`). When
|
|
458
|
+
* omitted, the channel default is used (`config.phoneNumber` / `rcsSenderId` /
|
|
459
|
+
* `whatsappNumber`).
|
|
460
|
+
*/
|
|
461
|
+
from: z.string().min(1).optional()
|
|
352
462
|
});
|
|
353
463
|
|
|
354
464
|
// packages/core/src/types/tac.ts
|
|
@@ -1270,6 +1380,7 @@ function callOptionsToCreateParams(options) {
|
|
|
1270
1380
|
}
|
|
1271
1381
|
var InitiateVoiceConversationOptionsBase = z.object({
|
|
1272
1382
|
to: z.string().min(1, "Recipient phone number is required"),
|
|
1383
|
+
from: z.string().min(1).optional(),
|
|
1273
1384
|
websocketUrl: z.url().optional(),
|
|
1274
1385
|
twimlOptions: VoiceTwiMLOptionsConversationRelaySchema.optional(),
|
|
1275
1386
|
callOptions: CallOptionsSchema.optional()
|
|
@@ -1435,12 +1546,35 @@ var TACConfig = class _TACConfig {
|
|
|
1435
1546
|
authToken;
|
|
1436
1547
|
apiKey;
|
|
1437
1548
|
apiSecret;
|
|
1549
|
+
/**
|
|
1550
|
+
* Default Twilio phone number for Voice and SMS — the sender used for
|
|
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}.
|
|
1555
|
+
*/
|
|
1438
1556
|
phoneNumber;
|
|
1557
|
+
/**
|
|
1558
|
+
* Full set of Twilio phone numbers this instance serves for Voice and SMS
|
|
1559
|
+
* (the inbound allowlist). Empty when none is configured; otherwise includes
|
|
1560
|
+
* {@link phoneNumber} as the first, default sender.
|
|
1561
|
+
*/
|
|
1562
|
+
phoneNumbers;
|
|
1439
1563
|
rcsSenderId;
|
|
1564
|
+
/** Full set of RCS Sender IDs this instance serves; the default is first. */
|
|
1565
|
+
rcsSenderIds;
|
|
1440
1566
|
whatsappNumber;
|
|
1567
|
+
/** Full set of WhatsApp numbers this instance serves; the default is first. */
|
|
1568
|
+
whatsappNumbers;
|
|
1441
1569
|
memoryConfig;
|
|
1442
1570
|
conversationConfigurationId;
|
|
1443
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;
|
|
1444
1578
|
/** Path the voice WebSocket is served at (default '/ws'). */
|
|
1445
1579
|
voiceWebsocketPath;
|
|
1446
1580
|
/** Path the ConversationRelay action callback is served at (default '/conversation-relay-callback'). */
|
|
@@ -1465,13 +1599,18 @@ var TACConfig = class _TACConfig {
|
|
|
1465
1599
|
this.authToken = validatedConfig.authToken;
|
|
1466
1600
|
this.apiKey = validatedConfig.apiKey;
|
|
1467
1601
|
this.apiSecret = validatedConfig.apiSecret;
|
|
1468
|
-
|
|
1602
|
+
if (validatedConfig.phoneNumber) {
|
|
1603
|
+
this.phoneNumber = validatedConfig.phoneNumber;
|
|
1604
|
+
}
|
|
1605
|
+
this.phoneNumbers = validatedConfig.phoneNumbers;
|
|
1469
1606
|
if (validatedConfig.rcsSenderId) {
|
|
1470
1607
|
this.rcsSenderId = validatedConfig.rcsSenderId;
|
|
1471
1608
|
}
|
|
1609
|
+
this.rcsSenderIds = validatedConfig.rcsSenderIds;
|
|
1472
1610
|
if (validatedConfig.whatsappNumber) {
|
|
1473
1611
|
this.whatsappNumber = validatedConfig.whatsappNumber;
|
|
1474
1612
|
}
|
|
1613
|
+
this.whatsappNumbers = validatedConfig.whatsappNumbers;
|
|
1475
1614
|
this.memoryConfig = validatedConfig.memoryConfig;
|
|
1476
1615
|
if (validatedConfig.conversationConfigurationId) {
|
|
1477
1616
|
this.conversationConfigurationId = validatedConfig.conversationConfigurationId;
|
|
@@ -1479,6 +1618,9 @@ var TACConfig = class _TACConfig {
|
|
|
1479
1618
|
if (validatedConfig.voicePublicDomain) {
|
|
1480
1619
|
this.voicePublicDomain = validatedConfig.voicePublicDomain;
|
|
1481
1620
|
}
|
|
1621
|
+
if (validatedConfig.instancePublicDomain) {
|
|
1622
|
+
this.instancePublicDomain = validatedConfig.instancePublicDomain;
|
|
1623
|
+
}
|
|
1482
1624
|
this.voiceWebsocketPath = validatedConfig.voiceWebsocketPath;
|
|
1483
1625
|
this.voiceActionPath = validatedConfig.voiceActionPath;
|
|
1484
1626
|
this.voiceCallEventPath = validatedConfig.voiceCallEventPath;
|
|
@@ -1503,18 +1645,33 @@ var TACConfig = class _TACConfig {
|
|
|
1503
1645
|
* - TWILIO_AUTH_TOKEN: Twilio Auth Token for API authentication
|
|
1504
1646
|
* - TWILIO_API_KEY: Twilio API Key SID (starts with SK)
|
|
1505
1647
|
* - TWILIO_API_SECRET: Twilio API Secret for API Key authentication
|
|
1506
|
-
* - TWILIO_PHONE_NUMBER: Phone number for voice and SMS channels
|
|
1507
1648
|
*
|
|
1508
1649
|
* Optional environment variables:
|
|
1509
|
-
* -
|
|
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.
|
|
1652
|
+
* - TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS: WhatsApp number(s) for the
|
|
1653
|
+
* WhatsApp channel (e.g., 'whatsapp:+1234567890')
|
|
1654
|
+
* - TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS: RCS Sender ID(s) for the RCS channel
|
|
1510
1655
|
* - TWILIO_CONVERSATION_CONFIGURATION_ID: Conversation Orchestrator configuration ID (enables orchestrated mode)
|
|
1511
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)
|
|
1512
1659
|
* - TWILIO_VOICE_WEBSOCKET_PATH: Path for the voice WebSocket (default: /ws)
|
|
1513
1660
|
* - TWILIO_VOICE_ACTION_PATH: Path for the ConversationRelay action callback (default: /conversation-relay-callback)
|
|
1514
1661
|
* - TWILIO_VOICE_CALL_EVENT_PATH: Base path for the call-event callbacks — status, async AMD, recording (default: /twilio/call-events)
|
|
1515
1662
|
* - TWILIO_REGION: Twilio region subdomain for API routing (e.g. transforms base URLs to `https://{product}.{region}.twilio.com`)
|
|
1516
1663
|
* - TWILIO_STUDIO_HANDOFF_FLOW_SID: Studio Flow SID used by createStudioHandoffTool for human handoff
|
|
1517
|
-
*
|
|
1664
|
+
*
|
|
1665
|
+
* Multi-Value Senders:
|
|
1666
|
+
* - Each singular env var (TWILIO_PHONE_NUMBER, TWILIO_RCS_SENDER_ID,
|
|
1667
|
+
* TWILIO_WHATSAPP_NUMBER) pairs with a plural, comma-separated one
|
|
1668
|
+
* (TWILIO_PHONE_NUMBERS, TWILIO_RCS_SENDER_IDS, TWILIO_WHATSAPP_NUMBERS),
|
|
1669
|
+
* e.g. `TWILIO_PHONE_NUMBERS=+1555,+1444`. Whichever side is set back-fills
|
|
1670
|
+
* the other: the singular becomes the default sender and the plural the full
|
|
1671
|
+
* allowlist. Entries are whitespace-trimmed and de-duplicated, with the
|
|
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`).
|
|
1518
1675
|
*
|
|
1519
1676
|
* Memory Configuration (defaults defined in TwilioMemoryConfigSchema):
|
|
1520
1677
|
* - TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: Trait groups to include (comma-separated, e.g., "Contact,Preferences")
|
|
@@ -1541,8 +1698,7 @@ var TACConfig = class _TACConfig {
|
|
|
1541
1698
|
{ key: EnvironmentVariables.TWILIO_ACCOUNT_SID, name: "TWILIO_ACCOUNT_SID" },
|
|
1542
1699
|
{ key: EnvironmentVariables.TWILIO_AUTH_TOKEN, name: "TWILIO_AUTH_TOKEN" },
|
|
1543
1700
|
{ key: EnvironmentVariables.TWILIO_API_KEY, name: "TWILIO_API_KEY" },
|
|
1544
|
-
{ key: EnvironmentVariables.TWILIO_API_SECRET, name: "TWILIO_API_SECRET" }
|
|
1545
|
-
{ key: EnvironmentVariables.TWILIO_PHONE_NUMBER, name: "TWILIO_PHONE_NUMBER" }
|
|
1701
|
+
{ key: EnvironmentVariables.TWILIO_API_SECRET, name: "TWILIO_API_SECRET" }
|
|
1546
1702
|
];
|
|
1547
1703
|
for (const { key, name } of requiredVars) {
|
|
1548
1704
|
if (!process.env[key]) {
|
|
@@ -1582,14 +1738,18 @@ var TACConfig = class _TACConfig {
|
|
|
1582
1738
|
}
|
|
1583
1739
|
return parsed;
|
|
1584
1740
|
};
|
|
1741
|
+
const splitCsvEnv = (value) => (value ?? "").split(",").map((part) => part.trim()).filter((part) => part.length > 0);
|
|
1585
1742
|
const rawConfig = {
|
|
1586
1743
|
accountSid: process.env[EnvironmentVariables.TWILIO_ACCOUNT_SID],
|
|
1587
1744
|
authToken: process.env[EnvironmentVariables.TWILIO_AUTH_TOKEN],
|
|
1588
1745
|
apiKey: process.env[EnvironmentVariables.TWILIO_API_KEY],
|
|
1589
1746
|
apiSecret: process.env[EnvironmentVariables.TWILIO_API_SECRET],
|
|
1590
|
-
phoneNumber: process.env[EnvironmentVariables.TWILIO_PHONE_NUMBER],
|
|
1747
|
+
phoneNumber: process.env[EnvironmentVariables.TWILIO_PHONE_NUMBER] || void 0,
|
|
1748
|
+
phoneNumbers: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_PHONE_NUMBERS]),
|
|
1591
1749
|
rcsSenderId: process.env[EnvironmentVariables.TWILIO_RCS_SENDER_ID],
|
|
1750
|
+
rcsSenderIds: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_RCS_SENDER_IDS]),
|
|
1592
1751
|
whatsappNumber: process.env[EnvironmentVariables.TWILIO_WHATSAPP_NUMBER] || void 0,
|
|
1752
|
+
whatsappNumbers: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_WHATSAPP_NUMBERS]),
|
|
1593
1753
|
memoryConfig: {
|
|
1594
1754
|
traitGroups,
|
|
1595
1755
|
observationsLimit: parseIntEnv(
|
|
@@ -1621,6 +1781,7 @@ var TACConfig = class _TACConfig {
|
|
|
1621
1781
|
},
|
|
1622
1782
|
conversationConfigurationId: process.env[EnvironmentVariables.TWILIO_CONVERSATION_CONFIGURATION_ID] || void 0,
|
|
1623
1783
|
voicePublicDomain: process.env[EnvironmentVariables.TWILIO_VOICE_PUBLIC_DOMAIN],
|
|
1784
|
+
instancePublicDomain: process.env[EnvironmentVariables.TWILIO_INSTANCE_PUBLIC_DOMAIN],
|
|
1624
1785
|
voiceWebsocketPath: process.env[EnvironmentVariables.TWILIO_VOICE_WEBSOCKET_PATH] || void 0,
|
|
1625
1786
|
voiceActionPath: process.env[EnvironmentVariables.TWILIO_VOICE_ACTION_PATH] || void 0,
|
|
1626
1787
|
voiceCallEventPath: process.env[EnvironmentVariables.TWILIO_VOICE_CALL_EVENT_PATH] || void 0,
|
|
@@ -1640,14 +1801,22 @@ var TACConfig = class _TACConfig {
|
|
|
1640
1801
|
callEventPath(kind) {
|
|
1641
1802
|
return `${this.voiceCallEventPath.replace(/\/+$/, "")}/${kind}`;
|
|
1642
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
|
+
}
|
|
1643
1811
|
/**
|
|
1644
1812
|
* Public URL for a call-event callback, or `undefined` without a public domain.
|
|
1645
1813
|
*/
|
|
1646
1814
|
callEventUrl(kind) {
|
|
1647
|
-
|
|
1815
|
+
const domain = this.voiceCallbackDomain;
|
|
1816
|
+
if (!domain) {
|
|
1648
1817
|
return void 0;
|
|
1649
1818
|
}
|
|
1650
|
-
return `https://${
|
|
1819
|
+
return `https://${domain}${this.callEventPath(kind)}`;
|
|
1651
1820
|
}
|
|
1652
1821
|
/**
|
|
1653
1822
|
* Whether Conversation Orchestrator is configured.
|
|
@@ -1765,7 +1934,7 @@ function createLogger(options) {
|
|
|
1765
1934
|
// package.json
|
|
1766
1935
|
var package_default = {
|
|
1767
1936
|
name: "twilio-agent-connect",
|
|
1768
|
-
version: "2.
|
|
1937
|
+
version: "2.6.0",
|
|
1769
1938
|
description: "Twilio Agent Connect - A TypeScript framework for building intelligent agents",
|
|
1770
1939
|
type: "module",
|
|
1771
1940
|
main: "./dist/index.js",
|
|
@@ -1787,15 +1956,17 @@ var package_default = {
|
|
|
1787
1956
|
test: "vitest --run",
|
|
1788
1957
|
"test:watch": "vitest",
|
|
1789
1958
|
"test:coverage": "vitest --coverage",
|
|
1790
|
-
lint: "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts'",
|
|
1791
|
-
"lint:fix": "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' --fix",
|
|
1959
|
+
lint: "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/twilio-setup/src/**/*.ts'",
|
|
1960
|
+
"lint:fix": "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/twilio-setup/src/**/*.ts' --fix",
|
|
1792
1961
|
format: "prettier --write 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/**/*.ts'",
|
|
1793
1962
|
"format:check": "prettier --check 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/**/*.ts'",
|
|
1794
|
-
typecheck: "tsc --noEmit",
|
|
1963
|
+
typecheck: "tsc --noEmit && tsc --noEmit -p getting_started/twilio-setup",
|
|
1795
1964
|
docs: "typedoc",
|
|
1796
1965
|
"docs:watch": "typedoc --watch",
|
|
1966
|
+
setup: "tsx getting_started/twilio-setup/src/index.ts | pino-pretty",
|
|
1797
1967
|
"example:getting-started": "cd getting_started/examples/openai && npm install && npm run dev",
|
|
1798
|
-
"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"
|
|
1799
1970
|
},
|
|
1800
1971
|
keywords: [
|
|
1801
1972
|
"twilio",
|
|
@@ -1819,9 +1990,11 @@ var package_default = {
|
|
|
1819
1990
|
"axios-mock-adapter": "^2.1.0",
|
|
1820
1991
|
eslint: "^9.0.0",
|
|
1821
1992
|
globals: "^15.0.0",
|
|
1993
|
+
"pino-pretty": "^13.0.0",
|
|
1822
1994
|
prettier: "^3.0.0",
|
|
1823
1995
|
rimraf: "^5.0.0",
|
|
1824
1996
|
tsup: "^8.5.1",
|
|
1997
|
+
tsx: "^4.19.2",
|
|
1825
1998
|
typedoc: "^0.28.20",
|
|
1826
1999
|
"typedoc-material-theme": "^1.4.1",
|
|
1827
2000
|
typescript: "^5.0.0",
|
|
@@ -1867,7 +2040,7 @@ var BaseClient = class {
|
|
|
1867
2040
|
this.logger = logger || createLogger({ name: this.constructor.name });
|
|
1868
2041
|
const authHeader = "Basic " + Buffer.from(`${config.apiKey}:${config.apiSecret}`).toString("base64");
|
|
1869
2042
|
const baseOrigin = new URL(baseUrl).origin;
|
|
1870
|
-
this.axiosInstance =
|
|
2043
|
+
this.axiosInstance = axios3.create({
|
|
1871
2044
|
baseURL: baseUrl,
|
|
1872
2045
|
timeout: 3e4,
|
|
1873
2046
|
maxRedirects: 5,
|
|
@@ -1895,7 +2068,7 @@ var BaseClient = class {
|
|
|
1895
2068
|
this.axiosInstance.interceptors.response.use(
|
|
1896
2069
|
(response) => response,
|
|
1897
2070
|
(error) => {
|
|
1898
|
-
if (
|
|
2071
|
+
if (axios3.isAxiosError(error)) {
|
|
1899
2072
|
const status = error.response?.status;
|
|
1900
2073
|
const logContext = {
|
|
1901
2074
|
error: error.message,
|
|
@@ -2326,6 +2499,9 @@ var ConversationClient = class extends BaseClient {
|
|
|
2326
2499
|
if (options?.participants) {
|
|
2327
2500
|
requestBody.participants = options.participants;
|
|
2328
2501
|
}
|
|
2502
|
+
if (options?.metadata) {
|
|
2503
|
+
requestBody.metadata = options.metadata;
|
|
2504
|
+
}
|
|
2329
2505
|
try {
|
|
2330
2506
|
const data = await this.makeRequest(url, "POST", requestBody);
|
|
2331
2507
|
return ConversationResponseSchema.parse(data);
|
|
@@ -2342,10 +2518,17 @@ var ConversationClient = class extends BaseClient {
|
|
|
2342
2518
|
*
|
|
2343
2519
|
* On 409 CO returns the existing conversation ID in the
|
|
2344
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
|
|
2345
2525
|
*/
|
|
2346
|
-
async createOrReuseConversation(participants) {
|
|
2526
|
+
async createOrReuseConversation(participants, metadata) {
|
|
2347
2527
|
try {
|
|
2348
|
-
const conversation = await this.createConversation({
|
|
2528
|
+
const conversation = await this.createConversation({
|
|
2529
|
+
participants,
|
|
2530
|
+
...metadata !== void 0 && { metadata }
|
|
2531
|
+
});
|
|
2349
2532
|
return { conversation, reused: false };
|
|
2350
2533
|
} catch (error) {
|
|
2351
2534
|
const existingId = this.extractConversationIdFrom409(error);
|
|
@@ -2364,7 +2547,7 @@ var ConversationClient = class extends BaseClient {
|
|
|
2364
2547
|
*/
|
|
2365
2548
|
extractConversationIdFrom409(error) {
|
|
2366
2549
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
2367
|
-
if (!
|
|
2550
|
+
if (!axios3.isAxiosError(cause) || cause.response?.status !== 409) {
|
|
2368
2551
|
return null;
|
|
2369
2552
|
}
|
|
2370
2553
|
const headers = cause.response.headers;
|
|
@@ -2523,6 +2706,46 @@ var ConversationClient = class extends BaseClient {
|
|
|
2523
2706
|
);
|
|
2524
2707
|
}
|
|
2525
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
|
+
}
|
|
2526
2749
|
/**
|
|
2527
2750
|
* Retrieve the details for a single configuration
|
|
2528
2751
|
*
|
|
@@ -2918,7 +3141,86 @@ var OperatorResultProcessor = class {
|
|
|
2918
3141
|
}
|
|
2919
3142
|
};
|
|
2920
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
|
+
|
|
2921
3221
|
// packages/core/src/lib/tac.ts
|
|
3222
|
+
var SHARED_PARTICIPANTS_TTL_MS = 6e4;
|
|
3223
|
+
var ENDED_REPORT_TTL_MS = 6e4;
|
|
2922
3224
|
var TAC = class _TAC {
|
|
2923
3225
|
static FACTORY_TOKEN = /* @__PURE__ */ Symbol("TAC.create");
|
|
2924
3226
|
config;
|
|
@@ -2933,6 +3235,13 @@ var TAC = class _TAC {
|
|
|
2933
3235
|
messageReadyCallback;
|
|
2934
3236
|
interruptCallback;
|
|
2935
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 });
|
|
2936
3245
|
constructor(token, options = {}) {
|
|
2937
3246
|
if (token !== _TAC.FACTORY_TOKEN) {
|
|
2938
3247
|
throw new Error("TAC constructor is private. Use TAC.create() instead of new TAC().");
|
|
@@ -2986,11 +3295,24 @@ var TAC = class _TAC {
|
|
|
2986
3295
|
}
|
|
2987
3296
|
}
|
|
2988
3297
|
/**
|
|
2989
|
-
* Register a channel with the framework
|
|
3298
|
+
* Register a channel with the framework, routing its inbound messages to the
|
|
3299
|
+
* {@link TAC.onMessageReady} callback and shutting it down with {@link TAC.shutdown}.
|
|
3300
|
+
*
|
|
3301
|
+
* `TACServer` registers the channels passed to it (`voiceChannel` /
|
|
3302
|
+
* `messagingChannels`), so you only need this when wiring channels into your
|
|
3303
|
+
* own web framework instead of `TACServer`.
|
|
3304
|
+
*
|
|
3305
|
+
* Only one channel per type is registered: registering a different instance
|
|
3306
|
+
* of the same type shuts down and replaces the existing one. Registering the
|
|
3307
|
+
* same instance again is a no-op.
|
|
2990
3308
|
*/
|
|
2991
3309
|
registerChannel(channel) {
|
|
2992
|
-
this.logger.info({ channel: channel.channelType }, "Registering channel");
|
|
2993
3310
|
const existingChannel = this.channels.get(channel.channelType);
|
|
3311
|
+
if (existingChannel === channel) {
|
|
3312
|
+
this.logger.debug({ channel: channel.channelType }, "Channel already registered");
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
this.logger.info({ channel: channel.channelType }, "Registering channel");
|
|
2994
3316
|
if (existingChannel) {
|
|
2995
3317
|
this.logger.info({ channel: channel.channelType }, "Replacing existing channel registration");
|
|
2996
3318
|
existingChannel.shutdown();
|
|
@@ -3035,6 +3357,7 @@ var TAC = class _TAC {
|
|
|
3035
3357
|
author: "user",
|
|
3036
3358
|
userMemory,
|
|
3037
3359
|
channelType: channel.channelType,
|
|
3360
|
+
session: eventSession,
|
|
3038
3361
|
abortSignal
|
|
3039
3362
|
});
|
|
3040
3363
|
}
|
|
@@ -3066,9 +3389,7 @@ var TAC = class _TAC {
|
|
|
3066
3389
|
}
|
|
3067
3390
|
}
|
|
3068
3391
|
);
|
|
3069
|
-
channel.
|
|
3070
|
-
"conversationEnded",
|
|
3071
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- Intentionally async event handler
|
|
3392
|
+
channel.setConversationEndedForwarderInternal(
|
|
3072
3393
|
async ({ session }) => {
|
|
3073
3394
|
if (this.conversationEndedCallback) {
|
|
3074
3395
|
try {
|
|
@@ -3111,7 +3432,7 @@ var TAC = class _TAC {
|
|
|
3111
3432
|
{ conversation_id: data.conversationId, channel: channel.channelType },
|
|
3112
3433
|
"Using channel for message"
|
|
3113
3434
|
);
|
|
3114
|
-
const session = channel.getConversationSession(data.conversationId);
|
|
3435
|
+
const session = data.session ?? channel.getConversationSession(data.conversationId);
|
|
3115
3436
|
if (!session) {
|
|
3116
3437
|
throw new Error(`No session found for conversation ${data.conversationId}`);
|
|
3117
3438
|
}
|
|
@@ -3143,7 +3464,7 @@ var TAC = class _TAC {
|
|
|
3143
3464
|
);
|
|
3144
3465
|
} else {
|
|
3145
3466
|
try {
|
|
3146
|
-
await channel.sendResponse(
|
|
3467
|
+
await channel.sendResponse(session, response);
|
|
3147
3468
|
} catch (sendError) {
|
|
3148
3469
|
this.logger.error(
|
|
3149
3470
|
{ err: sendError, conversation_id: data.conversationId },
|
|
@@ -3174,7 +3495,24 @@ var TAC = class _TAC {
|
|
|
3174
3495
|
this.messageReadyCallback = callback;
|
|
3175
3496
|
}
|
|
3176
3497
|
/**
|
|
3177
|
-
* Register callback
|
|
3498
|
+
* Register callback invoked when the caller interrupts the agent on a voice call.
|
|
3499
|
+
*
|
|
3500
|
+
* Currently fired by the ConversationRelay voice provider. The callback receives
|
|
3501
|
+
* `conversationId`, the call's `session`, `utteranceUntilInterrupt` (the text the
|
|
3502
|
+
* agent had spoken when interrupted) and `durationUntilInterruptMs` (how long it
|
|
3503
|
+
* had been speaking); either of the last two may be `undefined` if
|
|
3504
|
+
* ConversationRelay doesn't report it. Errors thrown by the callback are logged,
|
|
3505
|
+
* not rethrown.
|
|
3506
|
+
*
|
|
3507
|
+
* @example
|
|
3508
|
+
* ```typescript
|
|
3509
|
+
* tac.onInterrupt(({ conversationId, utteranceUntilInterrupt, durationUntilInterruptMs }) => {
|
|
3510
|
+
* console.log(
|
|
3511
|
+
* `${conversationId} interrupted after ${durationUntilInterruptMs} ms: ` +
|
|
3512
|
+
* JSON.stringify(utteranceUntilInterrupt)
|
|
3513
|
+
* );
|
|
3514
|
+
* });
|
|
3515
|
+
* ```
|
|
3178
3516
|
*/
|
|
3179
3517
|
onInterrupt(callback) {
|
|
3180
3518
|
this.interruptCallback = callback;
|
|
@@ -3182,14 +3520,88 @@ var TAC = class _TAC {
|
|
|
3182
3520
|
/**
|
|
3183
3521
|
* Register callback for when a conversation ends.
|
|
3184
3522
|
*
|
|
3185
|
-
*
|
|
3186
|
-
*
|
|
3187
|
-
*
|
|
3188
|
-
*
|
|
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`.
|
|
3189
3534
|
*/
|
|
3190
3535
|
onConversationEnded(callback) {
|
|
3191
3536
|
this.conversationEndedCallback = callback;
|
|
3192
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
|
+
}
|
|
3193
3605
|
/**
|
|
3194
3606
|
* Whether Conversation Orchestrator is configured.
|
|
3195
3607
|
* Returns false in voice-only mode.
|
|
@@ -3394,14 +3806,31 @@ var TAC = class _TAC {
|
|
|
3394
3806
|
}
|
|
3395
3807
|
};
|
|
3396
3808
|
|
|
3809
|
+
// packages/core/src/util/outbound-sender.ts
|
|
3810
|
+
function resolveOutboundSender(requested, options) {
|
|
3811
|
+
if (requested !== void 0) {
|
|
3812
|
+
if (!options.allowlist.includes(requested)) {
|
|
3813
|
+
throw new Error(
|
|
3814
|
+
`from '${requested}' is not a configured ${options.channel} sender; configured senders: ${JSON.stringify(options.allowlist)}`
|
|
3815
|
+
);
|
|
3816
|
+
}
|
|
3817
|
+
return requested;
|
|
3818
|
+
}
|
|
3819
|
+
if (options.default === void 0) {
|
|
3820
|
+
throw new Error(`No default sender configured for ${options.channel}.`);
|
|
3821
|
+
}
|
|
3822
|
+
return options.default;
|
|
3823
|
+
}
|
|
3824
|
+
|
|
3397
3825
|
// packages/core/src/channels/base.ts
|
|
3398
3826
|
var BaseChannel = class {
|
|
3399
3827
|
tac;
|
|
3400
3828
|
config;
|
|
3401
3829
|
logger;
|
|
3402
3830
|
conversationClient;
|
|
3403
|
-
activeConversations;
|
|
3404
3831
|
callbacks;
|
|
3832
|
+
/** TAC's forwarder to `tac.onConversationEnded`, while it fills the slot. */
|
|
3833
|
+
tacConversationEndedForwarder;
|
|
3405
3834
|
memoryMode;
|
|
3406
3835
|
processedWebhookTokens;
|
|
3407
3836
|
maxTrackedTokens;
|
|
@@ -3410,7 +3839,6 @@ var BaseChannel = class {
|
|
|
3410
3839
|
this.config = tac.getConfig();
|
|
3411
3840
|
this.logger = tac.logger.child({ component: "channel" });
|
|
3412
3841
|
this.conversationClient = tac.getConversationClient();
|
|
3413
|
-
this.activeConversations = /* @__PURE__ */ new Map();
|
|
3414
3842
|
this.callbacks = {};
|
|
3415
3843
|
const providedMode = options?.memoryMode;
|
|
3416
3844
|
const modeToValidate = providedMode === void 0 ? "never" : providedMode;
|
|
@@ -3428,6 +3856,16 @@ var BaseChannel = class {
|
|
|
3428
3856
|
this.maxTrackedTokens = capacity;
|
|
3429
3857
|
this.processedWebhookTokens = /* @__PURE__ */ new Set();
|
|
3430
3858
|
}
|
|
3859
|
+
/**
|
|
3860
|
+
* Resolve the outbound sender address for this channel.
|
|
3861
|
+
*
|
|
3862
|
+
* `requested` (the caller's `options.from`) wins when it is one of the
|
|
3863
|
+
* channel's configured senders; otherwise throws. When omitted, the channel
|
|
3864
|
+
* default is used.
|
|
3865
|
+
*/
|
|
3866
|
+
resolveOutboundFrom(requested, options) {
|
|
3867
|
+
return resolveOutboundSender(requested, { ...options, channel: this.channelType });
|
|
3868
|
+
}
|
|
3431
3869
|
/**
|
|
3432
3870
|
* Register event callbacks
|
|
3433
3871
|
*/
|
|
@@ -3446,102 +3884,141 @@ var BaseChannel = class {
|
|
|
3446
3884
|
}
|
|
3447
3885
|
}
|
|
3448
3886
|
/**
|
|
3449
|
-
*
|
|
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`.
|
|
3450
3891
|
*/
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
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"
|
|
3460
3936
|
);
|
|
3461
|
-
return
|
|
3937
|
+
return;
|
|
3462
3938
|
}
|
|
3463
|
-
const
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
}
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
{
|
|
3474
|
-
conversation_id: conversationId,
|
|
3475
|
-
profile_id: profileId,
|
|
3476
|
-
service_id: serviceId,
|
|
3477
|
-
channel: this.channelType
|
|
3478
|
-
},
|
|
3479
|
-
"Conversation started"
|
|
3480
|
-
);
|
|
3481
|
-
if (this.callbacks.onConversationStarted) {
|
|
3482
|
-
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;
|
|
3483
3949
|
}
|
|
3484
3950
|
trackEvent("Conversation Started", {
|
|
3485
3951
|
account_sid: this.config.accountSid,
|
|
3486
3952
|
channel: this.channelType,
|
|
3487
|
-
conversation_id: conversationId,
|
|
3488
|
-
has_profile_id: !!profileId
|
|
3953
|
+
conversation_id: participant.conversationId,
|
|
3954
|
+
has_profile_id: !!participant.profileId
|
|
3489
3955
|
});
|
|
3490
|
-
return session;
|
|
3491
3956
|
}
|
|
3492
3957
|
/**
|
|
3493
|
-
*
|
|
3958
|
+
* Report "Conversation Ended" for a conversation CO closed.
|
|
3959
|
+
*
|
|
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.
|
|
3494
3963
|
*
|
|
3495
|
-
*
|
|
3496
|
-
* so the callback receives the full ConversationSession data.
|
|
3497
|
-
* Errors in the callback do not prevent session cleanup.
|
|
3964
|
+
* @internal
|
|
3498
3965
|
*/
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
conversation_id: conversationId,
|
|
3522
|
-
channel: this.channelType,
|
|
3523
|
-
service_id: session.serviceId
|
|
3524
|
-
},
|
|
3525
|
-
"Conversation ended"
|
|
3526
|
-
);
|
|
3527
|
-
} else {
|
|
3528
|
-
this.logger.debug(
|
|
3529
|
-
{ conversation_id: conversationId, channel: this.channelType },
|
|
3530
|
-
"Conversation end requested but no active session found"
|
|
3531
|
-
);
|
|
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;
|
|
3532
3988
|
}
|
|
3989
|
+
return this.tac.hasConversationEndedCallback();
|
|
3533
3990
|
}
|
|
3534
3991
|
/**
|
|
3535
|
-
*
|
|
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
|
|
3536
3997
|
*/
|
|
3537
|
-
|
|
3538
|
-
|
|
3998
|
+
setConversationEndedForwarderInternal(forwarder) {
|
|
3999
|
+
this.callbacks.onConversationEnded = forwarder;
|
|
4000
|
+
this.tacConversationEndedForwarder = forwarder;
|
|
3539
4001
|
}
|
|
3540
4002
|
/**
|
|
3541
|
-
*
|
|
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
|
|
3542
4009
|
*/
|
|
3543
|
-
|
|
3544
|
-
|
|
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
|
+
}
|
|
3545
4022
|
}
|
|
3546
4023
|
/**
|
|
3547
4024
|
* Handle errors with proper context
|
|
@@ -3585,8 +4062,10 @@ var BaseChannel = class {
|
|
|
3585
4062
|
* Self-filtering: check if webhook event belongs to this channel.
|
|
3586
4063
|
*
|
|
3587
4064
|
* - COMMUNICATION_CREATED: require author.channel matches this channel type
|
|
3588
|
-
* -
|
|
3589
|
-
*
|
|
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.
|
|
3590
4069
|
*/
|
|
3591
4070
|
isEventForThisChannel(webhookData) {
|
|
3592
4071
|
const eventType = webhookData.eventType;
|
|
@@ -3597,12 +4076,6 @@ var BaseChannel = class {
|
|
|
3597
4076
|
}
|
|
3598
4077
|
return authorChannel === this.channelType.toUpperCase();
|
|
3599
4078
|
}
|
|
3600
|
-
if (eventType === "CONVERSATION_UPDATED") {
|
|
3601
|
-
const conversationId = this.extractConversationId(webhookData);
|
|
3602
|
-
if (conversationId && !this.activeConversations.has(conversationId)) {
|
|
3603
|
-
return false;
|
|
3604
|
-
}
|
|
3605
|
-
}
|
|
3606
4079
|
return true;
|
|
3607
4080
|
}
|
|
3608
4081
|
/**
|
|
@@ -3728,34 +4201,128 @@ var BaseChannel = class {
|
|
|
3728
4201
|
}
|
|
3729
4202
|
}
|
|
3730
4203
|
/**
|
|
3731
|
-
*
|
|
3732
|
-
* INACTIVE. Conversation Orchestrator updates memory on the INACTIVE
|
|
3733
|
-
* transition, so the next message re-fetches fresh memory. No-op for other
|
|
3734
|
-
* memory modes.
|
|
3735
|
-
*/
|
|
3736
|
-
invalidateCachedMemory(conversationId) {
|
|
3737
|
-
if (this.memoryMode !== "once") {
|
|
3738
|
-
return;
|
|
3739
|
-
}
|
|
3740
|
-
const session = this.activeConversations.get(conversationId);
|
|
3741
|
-
if (session?.cachedMemory !== void 0) {
|
|
3742
|
-
session.cachedMemory = void 0;
|
|
3743
|
-
this.logger.debug(
|
|
3744
|
-
{ conversation_id: conversationId },
|
|
3745
|
-
"Invalidated cached memory on INACTIVE status"
|
|
3746
|
-
);
|
|
3747
|
-
}
|
|
3748
|
-
}
|
|
3749
|
-
/**
|
|
3750
|
-
* Cleanup resources when shutting down
|
|
4204
|
+
* Cleanup resources when shutting down
|
|
3751
4205
|
*/
|
|
3752
4206
|
shutdown() {
|
|
3753
|
-
this.activeConversations.clear();
|
|
3754
4207
|
delete this.callbacks.onConversationStarted;
|
|
3755
4208
|
delete this.callbacks.onConversationEnded;
|
|
3756
4209
|
delete this.callbacks.onError;
|
|
4210
|
+
this.tacConversationEndedForwarder = void 0;
|
|
3757
4211
|
}
|
|
3758
4212
|
};
|
|
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
|
|
3759
4326
|
var AGENT_TYPES = /* @__PURE__ */ new Set(["AGENT", "AI_AGENT"]);
|
|
3760
4327
|
var CHANNEL_IDENTITY_TYPES = {
|
|
3761
4328
|
SMS: "phone",
|
|
@@ -3771,16 +4338,83 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3771
4338
|
* participant to CUSTOMER. Subclasses override to opt out (e.g. chat).
|
|
3772
4339
|
*/
|
|
3773
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();
|
|
4354
|
+
}
|
|
3774
4355
|
constructor(tac, config) {
|
|
3775
|
-
|
|
4356
|
+
const onceDeprecated = config?.memoryMode === "once";
|
|
4357
|
+
super(tac, onceDeprecated ? { ...config, memoryMode: "always" } : config);
|
|
3776
4358
|
if (!tac.isOrchestratorEnabled()) {
|
|
3777
4359
|
throw new Error(
|
|
3778
4360
|
"Messaging channels require conversationConfigurationId to be configured. Voice-only mode does not support SMS or Chat channels."
|
|
3779
4361
|
);
|
|
3780
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
|
+
}
|
|
3781
4374
|
this.conversationClient = tac.getConversationClient();
|
|
3782
4375
|
this.messagingCallbacks = {};
|
|
3783
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
|
+
}
|
|
3784
4418
|
/**
|
|
3785
4419
|
* Report a delivered response.
|
|
3786
4420
|
*
|
|
@@ -3797,36 +4431,215 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3797
4431
|
});
|
|
3798
4432
|
}
|
|
3799
4433
|
/**
|
|
3800
|
-
*
|
|
4434
|
+
* Whether the author is TAC, judged from an already-fetched participant list.
|
|
3801
4435
|
*
|
|
3802
|
-
*
|
|
3803
|
-
*
|
|
4436
|
+
* The caller does the free check (author address is a configured agent
|
|
4437
|
+
* address) first; this catches TAC speaking from some other address.
|
|
3804
4438
|
*/
|
|
3805
|
-
|
|
3806
|
-
if (
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
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.`
|
|
3826
4550
|
);
|
|
3827
4551
|
}
|
|
4552
|
+
session = this.sessionFromParticipants(target, participants);
|
|
4553
|
+
} else {
|
|
4554
|
+
session = target;
|
|
3828
4555
|
}
|
|
3829
|
-
|
|
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);
|
|
3830
4643
|
}
|
|
3831
4644
|
/**
|
|
3832
4645
|
* Register event callbacks (override for messaging-specific events)
|
|
@@ -3835,12 +4648,31 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3835
4648
|
on(event, callback) {
|
|
3836
4649
|
if (event === "messageReceived") {
|
|
3837
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
|
+
);
|
|
3838
4656
|
} else {
|
|
3839
4657
|
super.on(event, callback);
|
|
3840
4658
|
}
|
|
3841
4659
|
}
|
|
3842
4660
|
/**
|
|
3843
|
-
* 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.
|
|
3844
4676
|
*/
|
|
3845
4677
|
async processWebhook(payload, idempotencyToken) {
|
|
3846
4678
|
try {
|
|
@@ -3851,11 +4683,10 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3851
4683
|
const { webhookData, eventType, conversationId } = result;
|
|
3852
4684
|
switch (eventType) {
|
|
3853
4685
|
case "CONVERSATION_CREATED":
|
|
3854
|
-
this.logger.debug(
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
);
|
|
3858
|
-
this.handleConversationCreated(webhookData);
|
|
4686
|
+
this.logger.debug({ conversation_id: conversationId }, "Ignoring CONVERSATION_CREATED");
|
|
4687
|
+
break;
|
|
4688
|
+
case "PARTICIPANT_ADDED":
|
|
4689
|
+
this.trackConversationStarted(webhookData.data);
|
|
3859
4690
|
break;
|
|
3860
4691
|
case "COMMUNICATION_CREATED":
|
|
3861
4692
|
this.logger.debug({ conversation_id: conversationId }, "Handling COMMUNICATION_CREATED");
|
|
@@ -3887,19 +4718,54 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3887
4718
|
}
|
|
3888
4719
|
}
|
|
3889
4720
|
/**
|
|
3890
|
-
*
|
|
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.
|
|
3891
4724
|
*/
|
|
3892
|
-
|
|
3893
|
-
|
|
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);
|
|
3894
4750
|
const profileId = this.extractProfileId(payload);
|
|
3895
|
-
if (
|
|
3896
|
-
|
|
3897
|
-
{ operation: "handle_conversation_created" },
|
|
3898
|
-
"Missing conversation ID in conversation.created event"
|
|
3899
|
-
);
|
|
3900
|
-
throw new Error("Missing conversation ID in conversation.created event");
|
|
4751
|
+
if (profileId) {
|
|
4752
|
+
session.profileId = profileId;
|
|
3901
4753
|
}
|
|
3902
|
-
|
|
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;
|
|
3903
4769
|
}
|
|
3904
4770
|
/**
|
|
3905
4771
|
* Handle new communication event (incoming message)
|
|
@@ -3930,104 +4796,74 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3930
4796
|
this.logger.info({ conversation_id: conversationId }, "Ignoring empty message");
|
|
3931
4797
|
return;
|
|
3932
4798
|
}
|
|
3933
|
-
|
|
3934
|
-
if (communicationId) {
|
|
3935
|
-
const session2 = this.getConversationSession(conversationId);
|
|
3936
|
-
if (session2?.metadata?.lastCommunicationId === communicationId) {
|
|
3937
|
-
this.logger.debug(
|
|
3938
|
-
{ conversation_id: conversationId, communication_id: communicationId },
|
|
3939
|
-
"Skipping already-processed communication"
|
|
3940
|
-
);
|
|
3941
|
-
return;
|
|
3942
|
-
}
|
|
3943
|
-
}
|
|
3944
|
-
if (await this.isOwnMessage(author, conversationId, payload.data?.author?.participantId)) {
|
|
4799
|
+
if (this.isDefaultAgentAddress(author)) {
|
|
3945
4800
|
this.logger.info(
|
|
3946
|
-
{
|
|
3947
|
-
conversation_id: conversationId,
|
|
3948
|
-
author_address: maskAddress(author)
|
|
3949
|
-
},
|
|
4801
|
+
{ conversation_id: conversationId, author_address: maskAddress(author) },
|
|
3950
4802
|
"Ignoring message from AI agent"
|
|
3951
4803
|
);
|
|
3952
4804
|
return;
|
|
3953
4805
|
}
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
3966
|
-
"
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
3974
|
-
|
|
3975
|
-
participantId: payload.data?.author?.participantId
|
|
3976
|
-
};
|
|
3977
|
-
if (payload.data?.channelId) {
|
|
3978
|
-
if (!session.metadata) {
|
|
3979
|
-
session.metadata = {};
|
|
3980
|
-
}
|
|
3981
|
-
session.metadata.channelId = payload.data.channelId;
|
|
3982
|
-
this.logger.debug(
|
|
3983
|
-
{ conversation_id: conversationId, channel_id: payload.data.channelId },
|
|
3984
|
-
"Stored channelId in session metadata"
|
|
3985
|
-
);
|
|
3986
|
-
}
|
|
3987
|
-
if (communicationId) {
|
|
3988
|
-
if (!session.metadata) {
|
|
3989
|
-
session.metadata = {};
|
|
3990
|
-
}
|
|
3991
|
-
session.metadata.lastCommunicationId = communicationId;
|
|
3992
|
-
}
|
|
3993
|
-
if (!session.aiAgentInfo) {
|
|
3994
|
-
const resolved = await this.reconcileParticipants(conversationId);
|
|
3995
|
-
if (!resolved) {
|
|
3996
|
-
const error = new Error(
|
|
3997
|
-
`Participant reconciliation failed for conversation ${conversationId}; inbound message dropped because no sendable participants could be resolved.`
|
|
4806
|
+
const channelName = this.getChannelName();
|
|
4807
|
+
let inboundAgentAddress;
|
|
4808
|
+
if (this.deriveInboundAgentFromRecipients) {
|
|
4809
|
+
const channelRecipients = (payload.data?.recipients ?? []).filter(
|
|
4810
|
+
(r) => r.channel === channelName
|
|
4811
|
+
);
|
|
4812
|
+
if (channelRecipients.length > 0) {
|
|
4813
|
+
const matched = channelRecipients.find(
|
|
4814
|
+
(r) => r.address !== void 0 && this.isDefaultAgentAddress(r.address)
|
|
4815
|
+
)?.address;
|
|
4816
|
+
if (matched === void 0) {
|
|
4817
|
+
const maskedRecipients = channelRecipients.map((r) => maskAddress(r.address ?? ""));
|
|
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"
|
|
3998
4827
|
);
|
|
3999
|
-
error.name = "ParticipantReconciliationError";
|
|
4000
4828
|
this.handleError(error, {
|
|
4001
4829
|
conversation_id: conversationId,
|
|
4002
|
-
channel:
|
|
4830
|
+
channel: channelName,
|
|
4003
4831
|
dropped_inbound: true,
|
|
4004
|
-
|
|
4832
|
+
recipients: maskedRecipients
|
|
4005
4833
|
});
|
|
4006
4834
|
return;
|
|
4007
4835
|
}
|
|
4008
|
-
|
|
4009
|
-
const agentAddress = this.getAgentAddress(conversationId);
|
|
4010
|
-
session.aiAgentInfo = {
|
|
4011
|
-
address: agentAddress.address,
|
|
4012
|
-
participantId: agentParticipant.id
|
|
4013
|
-
};
|
|
4014
|
-
if (customerParticipant && session.authorInfo) {
|
|
4015
|
-
session.authorInfo.participantId = customerParticipant.id;
|
|
4016
|
-
if (customerParticipant.profileId && !session.profileId) {
|
|
4017
|
-
session.profileId = customerParticipant.profileId;
|
|
4018
|
-
}
|
|
4019
|
-
}
|
|
4836
|
+
inboundAgentAddress = matched;
|
|
4020
4837
|
}
|
|
4021
4838
|
}
|
|
4022
|
-
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);
|
|
4023
4858
|
if (this.messagingCallbacks.onMessageReceived) {
|
|
4024
4859
|
this.logger.debug({ conversation_id: conversationId }, "Invoking message received callback");
|
|
4025
4860
|
this.messagingCallbacks.onMessageReceived({
|
|
4026
4861
|
conversationId,
|
|
4027
|
-
profileId: session
|
|
4862
|
+
profileId: session.profileId,
|
|
4028
4863
|
message,
|
|
4029
4864
|
author,
|
|
4030
|
-
userMemory
|
|
4865
|
+
userMemory,
|
|
4866
|
+
session
|
|
4031
4867
|
});
|
|
4032
4868
|
}
|
|
4033
4869
|
trackEvent("Message Received", {
|
|
@@ -4037,22 +4873,121 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4037
4873
|
});
|
|
4038
4874
|
}
|
|
4039
4875
|
/**
|
|
4040
|
-
*
|
|
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.
|
|
4041
4946
|
*/
|
|
4042
4947
|
async handleConversationUpdated(payload) {
|
|
4043
4948
|
const conversationId = this.extractConversationId(payload);
|
|
4044
4949
|
if (!conversationId) {
|
|
4045
4950
|
throw new Error("Missing conversation ID in conversation.updated event");
|
|
4046
4951
|
}
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
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"
|
|
4051
4976
|
);
|
|
4052
|
-
|
|
4053
|
-
}
|
|
4054
|
-
|
|
4977
|
+
return;
|
|
4978
|
+
}
|
|
4979
|
+
const session = this.sessionFromParticipants(conversationId, participants);
|
|
4980
|
+
if (session === null) {
|
|
4981
|
+
return;
|
|
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) });
|
|
4055
4988
|
}
|
|
4989
|
+
this.logger.debug({ conversation_id: conversationId }, "Conversation closed");
|
|
4990
|
+
await this.triggerConversationEnded(session);
|
|
4056
4991
|
}
|
|
4057
4992
|
/**
|
|
4058
4993
|
* Validate messaging channel webhook payload structure
|
|
@@ -4093,24 +5028,21 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4093
5028
|
* (via `session.authorInfo.participantId`), so promoting some other
|
|
4094
5029
|
* `UNKNOWN` CHAT participant could pick the wrong recipient.
|
|
4095
5030
|
*
|
|
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.
|
|
4096
5036
|
* @returns `[agent, customerOrNull]` on success. `customer` is `null` when
|
|
4097
5037
|
* `reconcileCustomerType` is `false`. `null` overall when either the agent
|
|
4098
5038
|
* or the customer cannot be resolved — the caller treats `null` as a hard
|
|
4099
5039
|
* stop and skips the message-ready callback.
|
|
4100
5040
|
*/
|
|
4101
|
-
async reconcileParticipants(
|
|
4102
|
-
const
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
} catch (error) {
|
|
4107
|
-
this.logger.error(
|
|
4108
|
-
{ err: error, conversation_id: conversationId },
|
|
4109
|
-
"Failed to list participants for reconciliation"
|
|
4110
|
-
);
|
|
4111
|
-
return null;
|
|
4112
|
-
}
|
|
4113
|
-
const channel = agentAddress.channel;
|
|
5041
|
+
async reconcileParticipants(session, participants) {
|
|
5042
|
+
const conversationId = session.conversationId;
|
|
5043
|
+
const channel = this.getChannelName();
|
|
5044
|
+
const baseAgentAddress = this.agentAddressFor(session);
|
|
5045
|
+
const agentAddress = session.aiAgentInfo ? { ...baseAgentAddress, address: session.aiAgentInfo.address } : baseAgentAddress;
|
|
4114
5046
|
const ownsAgentAddress = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel && a.address === agentAddress.address);
|
|
4115
5047
|
const matchesChannel = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel);
|
|
4116
5048
|
let agentCandidate = participants.find(ownsAgentAddress);
|
|
@@ -4153,15 +5085,45 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4153
5085
|
"CUSTOMER",
|
|
4154
5086
|
profileId
|
|
4155
5087
|
);
|
|
4156
|
-
if (promotedCustomer) {
|
|
4157
|
-
return [agentCandidate, promotedCustomer];
|
|
4158
|
-
}
|
|
5088
|
+
if (promotedCustomer) {
|
|
5089
|
+
return [agentCandidate, promotedCustomer];
|
|
5090
|
+
}
|
|
5091
|
+
}
|
|
5092
|
+
this.logger.warn(
|
|
5093
|
+
{ conversation_id: conversationId, channel },
|
|
5094
|
+
"No customer participant resolvable; skipping webhook"
|
|
5095
|
+
);
|
|
5096
|
+
return null;
|
|
5097
|
+
}
|
|
5098
|
+
/**
|
|
5099
|
+
* Resolve the agent address when the inbound webhook carried no recipient.
|
|
5100
|
+
*
|
|
5101
|
+
* Scans the conversation's participants for any of TAC's configured addresses
|
|
5102
|
+
* on this channel; falls back to the channel default when none is present.
|
|
5103
|
+
* Defensive path — the primary source is the webhook.
|
|
5104
|
+
*/
|
|
5105
|
+
fallbackAgentAddress(session, participants, channel) {
|
|
5106
|
+
const conversationId = session.conversationId;
|
|
5107
|
+
const owned = this.ownedAgentAddress(participants, channel);
|
|
5108
|
+
if (owned !== void 0) {
|
|
5109
|
+
this.logger.warn(
|
|
5110
|
+
{ conversation_id: conversationId, channel },
|
|
5111
|
+
"Inbound webhook had no channel recipient; using owned participant address from participant scan"
|
|
5112
|
+
);
|
|
5113
|
+
return { channel, address: owned };
|
|
4159
5114
|
}
|
|
4160
5115
|
this.logger.warn(
|
|
4161
5116
|
{ conversation_id: conversationId, channel },
|
|
4162
|
-
"
|
|
5117
|
+
"Inbound webhook had no channel recipient and no owned participant; using default agent address"
|
|
4163
5118
|
);
|
|
4164
|
-
return
|
|
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;
|
|
4165
5127
|
}
|
|
4166
5128
|
/**
|
|
4167
5129
|
* Find or mint a Conversation Memory profile for a customer being promoted from UNKNOWN.
|
|
@@ -4308,11 +5270,11 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4308
5270
|
}
|
|
4309
5271
|
isConflictError(error) {
|
|
4310
5272
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
4311
|
-
return
|
|
5273
|
+
return axios3.isAxiosError(cause) && cause.response?.status === 409;
|
|
4312
5274
|
}
|
|
4313
5275
|
extractConflictingResourceId(error) {
|
|
4314
5276
|
const cause = error instanceof Error ? error.cause ?? error : error;
|
|
4315
|
-
if (!
|
|
5277
|
+
if (!axios3.isAxiosError(cause)) return void 0;
|
|
4316
5278
|
const headers = cause.response?.headers;
|
|
4317
5279
|
const id = headers?.["x-conflicting-resource-id"];
|
|
4318
5280
|
return typeof id === "string" && id.length > 0 ? id : void 0;
|
|
@@ -4320,8 +5282,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4320
5282
|
/**
|
|
4321
5283
|
* Shared outbound conversation initiation for messaging channels (SMS/RCS/Chat/WhatsApp).
|
|
4322
5284
|
*
|
|
4323
|
-
* Handles the full flow: create conversation → find participants →
|
|
4324
|
-
* 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.
|
|
4325
5293
|
*/
|
|
4326
5294
|
async initiateOutboundMessagingConversation(params) {
|
|
4327
5295
|
const {
|
|
@@ -4335,6 +5303,14 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4335
5303
|
} = params;
|
|
4336
5304
|
let conversationId;
|
|
4337
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
|
+
}
|
|
4338
5314
|
try {
|
|
4339
5315
|
const customerAddress = {
|
|
4340
5316
|
channel,
|
|
@@ -4346,15 +5322,38 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4346
5322
|
address: fromAddress,
|
|
4347
5323
|
...channelId ? { channelId } : {}
|
|
4348
5324
|
};
|
|
4349
|
-
const result = await this.conversationClient.createOrReuseConversation(
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
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
|
+
);
|
|
4353
5334
|
conversationId = result.conversation.id;
|
|
4354
5335
|
conversationReused = result.reused;
|
|
4355
5336
|
if (!isConversationId(conversationId)) {
|
|
4356
5337
|
throw new Error(`Invalid conversation ID returned: ${conversationId}`);
|
|
4357
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
|
+
}
|
|
4358
5357
|
const participants = await this.conversationClient.listParticipants(conversationId);
|
|
4359
5358
|
const customerParticipant = participants.find(
|
|
4360
5359
|
(p) => p.type === "CUSTOMER" && Array.isArray(p.addresses) && p.addresses.some(
|
|
@@ -4372,7 +5371,7 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4372
5371
|
if (!agentParticipant) {
|
|
4373
5372
|
throw new Error("Agent participant not found after conversation creation");
|
|
4374
5373
|
}
|
|
4375
|
-
const session = this.
|
|
5374
|
+
const session = this.newSession(conversationId);
|
|
4376
5375
|
session.authorInfo = {
|
|
4377
5376
|
address: to,
|
|
4378
5377
|
participantId: customerParticipant.id
|
|
@@ -4387,6 +5386,10 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4387
5386
|
direction: "outbound",
|
|
4388
5387
|
...channelId ? { channelId } : {}
|
|
4389
5388
|
};
|
|
5389
|
+
attachConversationMetadata(session, {
|
|
5390
|
+
...knownCoMetadata !== void 0 && { known: knownCoMetadata },
|
|
5391
|
+
loader: this.coMetadataLoader(conversationId)
|
|
5392
|
+
});
|
|
4390
5393
|
const actionRequest = {
|
|
4391
5394
|
type: "SEND_MESSAGE",
|
|
4392
5395
|
payload: {
|
|
@@ -4403,8 +5406,13 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4403
5406
|
);
|
|
4404
5407
|
return { conversationId, session };
|
|
4405
5408
|
} catch (error) {
|
|
4406
|
-
|
|
4407
|
-
|
|
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
|
+
);
|
|
4408
5416
|
}
|
|
4409
5417
|
if (conversationId && !conversationReused) {
|
|
4410
5418
|
await this.conversationClient.updateConversation(conversationId, "CLOSED").catch((closeErr) => {
|
|
@@ -4426,99 +5434,35 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4426
5434
|
|
|
4427
5435
|
// packages/core/src/channels/sms.ts
|
|
4428
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
|
+
}
|
|
4429
5445
|
get channelType() {
|
|
4430
5446
|
return "sms";
|
|
4431
5447
|
}
|
|
4432
5448
|
isDefaultAgentAddress(authorAddress) {
|
|
4433
|
-
return
|
|
5449
|
+
return this.config.phoneNumbers.includes(authorAddress);
|
|
4434
5450
|
}
|
|
4435
5451
|
getAgentAddress(_conversationId) {
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
* Send SMS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4440
|
-
*
|
|
4441
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4442
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4443
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4444
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4445
|
-
* both of which populate the session.
|
|
4446
|
-
*/
|
|
4447
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4448
|
-
this.logger.debug(
|
|
4449
|
-
{
|
|
4450
|
-
conversation_id: conversationId,
|
|
4451
|
-
message_length: message.length,
|
|
4452
|
-
operation: "send_response"
|
|
4453
|
-
},
|
|
4454
|
-
"Sending SMS response"
|
|
4455
|
-
);
|
|
4456
|
-
try {
|
|
4457
|
-
const session = this.getConversationSession(conversationId);
|
|
4458
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4459
|
-
throw new Error(
|
|
4460
|
-
`Unable to send SMS: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4461
|
-
);
|
|
4462
|
-
}
|
|
4463
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4464
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4465
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4466
|
-
throw new Error(
|
|
4467
|
-
`Unable to send SMS: session for conversation ${conversationId} is missing participant ids.`
|
|
4468
|
-
);
|
|
4469
|
-
}
|
|
4470
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4471
|
-
this.logger.debug(
|
|
4472
|
-
{
|
|
4473
|
-
conversation_id: conversationId,
|
|
4474
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4475
|
-
recipient_participant_id: customerParticipantId,
|
|
4476
|
-
agent_participant_id: agentParticipantId
|
|
4477
|
-
},
|
|
4478
|
-
"Sending SMS via Actions API"
|
|
4479
|
-
);
|
|
4480
|
-
const actionRequest = {
|
|
4481
|
-
type: "SEND_MESSAGE",
|
|
4482
|
-
payload: {
|
|
4483
|
-
from: {
|
|
4484
|
-
channel: "SMS",
|
|
4485
|
-
participantId: agentParticipantId
|
|
4486
|
-
},
|
|
4487
|
-
to: [
|
|
4488
|
-
{
|
|
4489
|
-
channel: "SMS",
|
|
4490
|
-
participantId: customerParticipantId
|
|
4491
|
-
}
|
|
4492
|
-
],
|
|
4493
|
-
content: { text: message },
|
|
4494
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
4495
|
-
}
|
|
4496
|
-
};
|
|
4497
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4498
|
-
this.logger.info(
|
|
4499
|
-
{
|
|
4500
|
-
conversation_id: conversationId,
|
|
4501
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
4502
|
-
},
|
|
4503
|
-
"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."
|
|
4504
5455
|
);
|
|
4505
|
-
} catch (error) {
|
|
4506
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4507
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4508
|
-
conversationId,
|
|
4509
|
-
message,
|
|
4510
|
-
metadata
|
|
4511
|
-
});
|
|
4512
|
-
throw error;
|
|
4513
5456
|
}
|
|
4514
|
-
this.
|
|
5457
|
+
return { channel: "SMS", address: this.config.phoneNumber };
|
|
4515
5458
|
}
|
|
4516
5459
|
/**
|
|
4517
5460
|
* Initiate an outbound SMS conversation
|
|
4518
5461
|
*
|
|
4519
5462
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4520
5463
|
* agent participants, then sends the initial message via the Actions API.
|
|
4521
|
-
*
|
|
5464
|
+
* Uses `options.from` when provided (must be one of the configured phone
|
|
5465
|
+
* numbers), otherwise falls back to the default `config.phoneNumber`.
|
|
4522
5466
|
*/
|
|
4523
5467
|
async initiateOutboundConversation(options) {
|
|
4524
5468
|
const validated = InitiateMessagingConversationOptionsSchema.parse(options);
|
|
@@ -4529,7 +5473,10 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4529
5473
|
return this.initiateOutboundMessagingConversation({
|
|
4530
5474
|
channel: "SMS",
|
|
4531
5475
|
to: validated.to,
|
|
4532
|
-
from: this.
|
|
5476
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
5477
|
+
allowlist: this.config.phoneNumbers,
|
|
5478
|
+
default: this.config.phoneNumber
|
|
5479
|
+
}),
|
|
4533
5480
|
message: validated.message,
|
|
4534
5481
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4535
5482
|
});
|
|
@@ -4540,9 +5487,9 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4540
5487
|
var RCSChannel = class extends MessagingChannel {
|
|
4541
5488
|
constructor(tac, config) {
|
|
4542
5489
|
super(tac, config);
|
|
4543
|
-
if (
|
|
5490
|
+
if (this.config.rcsSenderIds.length === 0) {
|
|
4544
5491
|
throw new Error(
|
|
4545
|
-
"rcsSenderId is required for RCS channel.
|
|
5492
|
+
"rcsSenderId(s) is required for RCS channel. Set TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS or provide rcsSenderId / rcsSenderIds in TACConfig."
|
|
4546
5493
|
);
|
|
4547
5494
|
}
|
|
4548
5495
|
}
|
|
@@ -4550,7 +5497,7 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4550
5497
|
return "rcs";
|
|
4551
5498
|
}
|
|
4552
5499
|
isDefaultAgentAddress(authorAddress) {
|
|
4553
|
-
return
|
|
5500
|
+
return this.config.rcsSenderIds.includes(authorAddress);
|
|
4554
5501
|
}
|
|
4555
5502
|
getAgentAddress(_conversationId) {
|
|
4556
5503
|
if (!this.config.rcsSenderId) {
|
|
@@ -4558,96 +5505,16 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4558
5505
|
}
|
|
4559
5506
|
return { channel: "RCS", address: this.config.rcsSenderId };
|
|
4560
5507
|
}
|
|
4561
|
-
/**
|
|
4562
|
-
* Send RCS response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4563
|
-
*
|
|
4564
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4565
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4566
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4567
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4568
|
-
* both of which populate the session.
|
|
4569
|
-
*/
|
|
4570
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4571
|
-
this.logger.debug(
|
|
4572
|
-
{
|
|
4573
|
-
conversation_id: conversationId,
|
|
4574
|
-
message_length: message.length,
|
|
4575
|
-
operation: "send_response"
|
|
4576
|
-
},
|
|
4577
|
-
"Sending RCS response"
|
|
4578
|
-
);
|
|
4579
|
-
try {
|
|
4580
|
-
const session = this.getConversationSession(conversationId);
|
|
4581
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4582
|
-
throw new Error(
|
|
4583
|
-
`Unable to send RCS: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4584
|
-
);
|
|
4585
|
-
}
|
|
4586
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4587
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4588
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4589
|
-
throw new Error(
|
|
4590
|
-
`Unable to send RCS: session for conversation ${conversationId} is missing participant ids.`
|
|
4591
|
-
);
|
|
4592
|
-
}
|
|
4593
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4594
|
-
this.logger.debug(
|
|
4595
|
-
{
|
|
4596
|
-
conversation_id: conversationId,
|
|
4597
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4598
|
-
recipient_participant_id: customerParticipantId,
|
|
4599
|
-
agent_participant_id: agentParticipantId
|
|
4600
|
-
},
|
|
4601
|
-
"Sending RCS via Actions API"
|
|
4602
|
-
);
|
|
4603
|
-
const actionRequest = {
|
|
4604
|
-
type: "SEND_MESSAGE",
|
|
4605
|
-
payload: {
|
|
4606
|
-
from: {
|
|
4607
|
-
channel: "RCS",
|
|
4608
|
-
participantId: agentParticipantId
|
|
4609
|
-
},
|
|
4610
|
-
to: [
|
|
4611
|
-
{
|
|
4612
|
-
channel: "RCS",
|
|
4613
|
-
participantId: customerParticipantId
|
|
4614
|
-
}
|
|
4615
|
-
],
|
|
4616
|
-
content: { text: message },
|
|
4617
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
4618
|
-
}
|
|
4619
|
-
};
|
|
4620
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4621
|
-
this.logger.info(
|
|
4622
|
-
{
|
|
4623
|
-
conversation_id: conversationId,
|
|
4624
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
4625
|
-
},
|
|
4626
|
-
"RCS sent successfully via Actions API"
|
|
4627
|
-
);
|
|
4628
|
-
} catch (error) {
|
|
4629
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4630
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4631
|
-
conversationId,
|
|
4632
|
-
message,
|
|
4633
|
-
metadata
|
|
4634
|
-
});
|
|
4635
|
-
throw error;
|
|
4636
|
-
}
|
|
4637
|
-
this.trackResponseSent(conversationId);
|
|
4638
|
-
}
|
|
4639
5508
|
/**
|
|
4640
5509
|
* Initiate an outbound RCS conversation
|
|
4641
5510
|
*
|
|
4642
5511
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4643
5512
|
* agent participants, then sends the initial message via the Actions API.
|
|
4644
|
-
*
|
|
5513
|
+
* Uses `options.from` when provided (must be one of the configured RCS
|
|
5514
|
+
* senders), otherwise falls back to the default `config.rcsSenderId`.
|
|
4645
5515
|
*/
|
|
4646
5516
|
async initiateOutboundConversation(options) {
|
|
4647
5517
|
const validated = InitiateMessagingConversationOptionsSchema.parse(options);
|
|
4648
|
-
if (!this.config.rcsSenderId) {
|
|
4649
|
-
throw new Error("rcsSenderId is required for RCS channel.");
|
|
4650
|
-
}
|
|
4651
5518
|
this.logger.info(
|
|
4652
5519
|
{ to: maskAddress(validated.to), message_length: validated.message.length },
|
|
4653
5520
|
"Initiating outbound RCS conversation"
|
|
@@ -4655,7 +5522,10 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4655
5522
|
return this.initiateOutboundMessagingConversation({
|
|
4656
5523
|
channel: "RCS",
|
|
4657
5524
|
to: validated.to,
|
|
4658
|
-
from: this.
|
|
5525
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
5526
|
+
allowlist: this.config.rcsSenderIds,
|
|
5527
|
+
default: this.config.rcsSenderId
|
|
5528
|
+
}),
|
|
4659
5529
|
message: validated.message,
|
|
4660
5530
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4661
5531
|
});
|
|
@@ -4664,16 +5534,19 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4664
5534
|
|
|
4665
5535
|
// packages/core/src/channels/whatsapp.ts
|
|
4666
5536
|
var WhatsAppChannel = class extends MessagingChannel {
|
|
5537
|
+
constructor(tac, config) {
|
|
5538
|
+
super(tac, config);
|
|
5539
|
+
if (this.config.whatsappNumbers.length === 0) {
|
|
5540
|
+
throw new Error(
|
|
5541
|
+
"whatsappNumber(s) is required for WhatsApp channel. Set TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS or provide whatsappNumber / whatsappNumbers in TACConfig."
|
|
5542
|
+
);
|
|
5543
|
+
}
|
|
5544
|
+
}
|
|
4667
5545
|
get channelType() {
|
|
4668
5546
|
return "whatsapp";
|
|
4669
5547
|
}
|
|
4670
5548
|
isDefaultAgentAddress(authorAddress) {
|
|
4671
|
-
|
|
4672
|
-
throw new Error(
|
|
4673
|
-
"whatsappNumber is required for WhatsApp channel. Please set TWILIO_WHATSAPP_NUMBER environment variable or provide whatsappNumber in TACConfig."
|
|
4674
|
-
);
|
|
4675
|
-
}
|
|
4676
|
-
return authorAddress === this.config.whatsappNumber;
|
|
5549
|
+
return this.config.whatsappNumbers.includes(authorAddress);
|
|
4677
5550
|
}
|
|
4678
5551
|
getAgentAddress(_conversationId) {
|
|
4679
5552
|
if (!this.config.whatsappNumber) {
|
|
@@ -4683,98 +5556,16 @@ var WhatsAppChannel = class extends MessagingChannel {
|
|
|
4683
5556
|
}
|
|
4684
5557
|
return { channel: "WHATSAPP", address: this.config.whatsappNumber };
|
|
4685
5558
|
}
|
|
4686
|
-
/**
|
|
4687
|
-
* Send WhatsApp response using the Conversation Orchestrator Actions API (SEND_MESSAGE).
|
|
4688
|
-
*
|
|
4689
|
-
* Reads the agent and customer participant ids stashed on the session by
|
|
4690
|
-
* inbound reconciliation or outbound initiation. Missing ids are a misuse —
|
|
4691
|
-
* `sendResponse` is only expected to be called after an inbound webhook
|
|
4692
|
-
* (COMMUNICATION_CREATED → reconcile) or after `initiateOutboundConversation`,
|
|
4693
|
-
* both of which populate the session.
|
|
4694
|
-
*/
|
|
4695
|
-
async sendResponse(conversationId, message, metadata) {
|
|
4696
|
-
this.logger.debug(
|
|
4697
|
-
{
|
|
4698
|
-
conversation_id: conversationId,
|
|
4699
|
-
message_length: message.length,
|
|
4700
|
-
operation: "send_response"
|
|
4701
|
-
},
|
|
4702
|
-
"Sending WhatsApp response"
|
|
4703
|
-
);
|
|
4704
|
-
try {
|
|
4705
|
-
const session = this.getConversationSession(conversationId);
|
|
4706
|
-
if (!session || !session.authorInfo || !session.aiAgentInfo) {
|
|
4707
|
-
throw new Error(
|
|
4708
|
-
`Unable to send WhatsApp: sendResponse called without a reconciled session for conversation ${conversationId}. Wait for an inbound webhook or call initiateOutboundConversation first.`
|
|
4709
|
-
);
|
|
4710
|
-
}
|
|
4711
|
-
const customerParticipantId = session.authorInfo.participantId;
|
|
4712
|
-
const agentParticipantId = session.aiAgentInfo.participantId;
|
|
4713
|
-
if (!customerParticipantId || !agentParticipantId) {
|
|
4714
|
-
throw new Error(
|
|
4715
|
-
`Unable to send WhatsApp: session for conversation ${conversationId} is missing participant ids.`
|
|
4716
|
-
);
|
|
4717
|
-
}
|
|
4718
|
-
const channelId = typeof session.metadata?.channelId === "string" ? session.metadata.channelId : void 0;
|
|
4719
|
-
this.logger.debug(
|
|
4720
|
-
{
|
|
4721
|
-
conversation_id: conversationId,
|
|
4722
|
-
recipient_address: maskAddress(session.authorInfo.address),
|
|
4723
|
-
recipient_participant_id: customerParticipantId,
|
|
4724
|
-
agent_participant_id: agentParticipantId
|
|
4725
|
-
},
|
|
4726
|
-
"Sending WhatsApp via Actions API"
|
|
4727
|
-
);
|
|
4728
|
-
const actionRequest = {
|
|
4729
|
-
type: "SEND_MESSAGE",
|
|
4730
|
-
payload: {
|
|
4731
|
-
from: {
|
|
4732
|
-
channel: "WHATSAPP",
|
|
4733
|
-
participantId: agentParticipantId
|
|
4734
|
-
},
|
|
4735
|
-
to: [
|
|
4736
|
-
{
|
|
4737
|
-
channel: "WHATSAPP",
|
|
4738
|
-
participantId: customerParticipantId
|
|
4739
|
-
}
|
|
4740
|
-
],
|
|
4741
|
-
content: { text: message },
|
|
4742
|
-
...channelId ? { channelSettings: { channelId } } : {}
|
|
4743
|
-
}
|
|
4744
|
-
};
|
|
4745
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4746
|
-
this.logger.info(
|
|
4747
|
-
{
|
|
4748
|
-
conversation_id: conversationId,
|
|
4749
|
-
recipient_address: maskAddress(session.authorInfo.address)
|
|
4750
|
-
},
|
|
4751
|
-
"WhatsApp sent successfully via Actions API"
|
|
4752
|
-
);
|
|
4753
|
-
} catch (error) {
|
|
4754
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4755
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4756
|
-
conversationId,
|
|
4757
|
-
message,
|
|
4758
|
-
metadata
|
|
4759
|
-
});
|
|
4760
|
-
throw error;
|
|
4761
|
-
}
|
|
4762
|
-
this.trackResponseSent(conversationId);
|
|
4763
|
-
}
|
|
4764
5559
|
/**
|
|
4765
5560
|
* Initiate an outbound WhatsApp conversation
|
|
4766
5561
|
*
|
|
4767
5562
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4768
5563
|
* agent participants, then sends the initial message via the Actions API.
|
|
4769
|
-
*
|
|
5564
|
+
* Uses `options.from` when provided (must be one of the configured WhatsApp
|
|
5565
|
+
* numbers), otherwise falls back to the default `config.whatsappNumber`.
|
|
4770
5566
|
*/
|
|
4771
5567
|
async initiateOutboundConversation(options) {
|
|
4772
5568
|
const validated = InitiateMessagingConversationOptionsSchema.parse(options);
|
|
4773
|
-
if (!this.config.whatsappNumber) {
|
|
4774
|
-
throw new Error(
|
|
4775
|
-
"whatsappNumber is required for WhatsApp channel. Please set TWILIO_WHATSAPP_NUMBER environment variable or provide whatsappNumber in TACConfig."
|
|
4776
|
-
);
|
|
4777
|
-
}
|
|
4778
5569
|
this.logger.info(
|
|
4779
5570
|
{ to: maskAddress(validated.to), message_length: validated.message.length },
|
|
4780
5571
|
"Initiating outbound WhatsApp conversation"
|
|
@@ -4782,7 +5573,10 @@ var WhatsAppChannel = class extends MessagingChannel {
|
|
|
4782
5573
|
return this.initiateOutboundMessagingConversation({
|
|
4783
5574
|
channel: "WHATSAPP",
|
|
4784
5575
|
to: validated.to,
|
|
4785
|
-
from: this.
|
|
5576
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
5577
|
+
allowlist: this.config.whatsappNumbers,
|
|
5578
|
+
default: this.config.whatsappNumber
|
|
5579
|
+
}),
|
|
4786
5580
|
message: validated.message,
|
|
4787
5581
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4788
5582
|
});
|
|
@@ -4799,108 +5593,64 @@ var ChatChannel = class extends MessagingChannel {
|
|
|
4799
5593
|
// Chat identifies the customer author-driven from the webhook's
|
|
4800
5594
|
// `author.participantId`; promoting some other channel-matching UNKNOWN
|
|
4801
5595
|
// CHAT participant could pick the wrong recipient.
|
|
4802
|
-
reconcileCustomerType = false;
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
}
|
|
4810
|
-
|
|
4811
|
-
return
|
|
4812
|
-
}
|
|
4813
|
-
|
|
4814
|
-
|
|
4815
|
-
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
}
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
|
|
4848
|
-
|
|
4849
|
-
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
|
|
4853
|
-
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
"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."
|
|
4858
|
-
);
|
|
4859
|
-
}
|
|
4860
|
-
const channelSettings = {
|
|
4861
|
-
channelId: chatChannelSid
|
|
4862
|
-
};
|
|
4863
|
-
this.logger.debug(
|
|
4864
|
-
{
|
|
4865
|
-
conversation_id: conversationId,
|
|
4866
|
-
recipient_participant_id: customerParticipantId,
|
|
4867
|
-
agent_participant_id: agentParticipantId,
|
|
4868
|
-
channel_id: chatChannelSid
|
|
4869
|
-
},
|
|
4870
|
-
"Sending chat message via Actions API"
|
|
4871
|
-
);
|
|
4872
|
-
const actionRequest = {
|
|
4873
|
-
type: "SEND_MESSAGE",
|
|
4874
|
-
payload: {
|
|
4875
|
-
from: {
|
|
4876
|
-
channel: "CHAT",
|
|
4877
|
-
participantId: agentParticipantId
|
|
4878
|
-
},
|
|
4879
|
-
to: [
|
|
4880
|
-
{
|
|
4881
|
-
channel: "CHAT",
|
|
4882
|
-
participantId: customerParticipantId
|
|
4883
|
-
}
|
|
4884
|
-
],
|
|
4885
|
-
content: { text: message },
|
|
4886
|
-
channelSettings
|
|
4887
|
-
}
|
|
4888
|
-
};
|
|
4889
|
-
await this.conversationClient.createAction(conversationId, actionRequest);
|
|
4890
|
-
this.logger.info(
|
|
4891
|
-
{ conversation_id: conversationId, channel_id: chatChannelSid },
|
|
4892
|
-
"Chat message sent successfully via Actions API"
|
|
5596
|
+
reconcileCustomerType = false;
|
|
5597
|
+
// Chat's agent is a single identity, not a set of numbers, so it keeps the
|
|
5598
|
+
// default-address path rather than deriving the agent from webhook recipients.
|
|
5599
|
+
deriveInboundAgentFromRecipients = false;
|
|
5600
|
+
constructor(tac, config) {
|
|
5601
|
+
super(tac, config);
|
|
5602
|
+
this.agentAddress = config?.agentAddress ?? "ai-assistant";
|
|
5603
|
+
}
|
|
5604
|
+
get channelType() {
|
|
5605
|
+
return "chat";
|
|
5606
|
+
}
|
|
5607
|
+
isDefaultAgentAddress(authorAddress) {
|
|
5608
|
+
return authorAddress === this.agentAddress;
|
|
5609
|
+
}
|
|
5610
|
+
getAgentAddress(_conversationId) {
|
|
5611
|
+
return this.chatAddress(void 0);
|
|
5612
|
+
}
|
|
5613
|
+
agentAddressFor(session) {
|
|
5614
|
+
return this.chatAddress(session.metadata?.channelId);
|
|
5615
|
+
}
|
|
5616
|
+
chatAddress(channelId) {
|
|
5617
|
+
return {
|
|
5618
|
+
channel: "CHAT",
|
|
5619
|
+
address: this.agentAddress,
|
|
5620
|
+
...typeof channelId === "string" && channelId ? { channelId } : {}
|
|
5621
|
+
};
|
|
5622
|
+
}
|
|
5623
|
+
/**
|
|
5624
|
+
* Rebuild the session, recovering `channelId` from the participants.
|
|
5625
|
+
*
|
|
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.
|
|
5629
|
+
*/
|
|
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
|
+
)
|
|
5639
|
+
);
|
|
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."
|
|
4893
5651
|
);
|
|
4894
|
-
} catch (error) {
|
|
4895
|
-
this.logger.error({ err: error, conversation_id: conversationId }, "Send response error");
|
|
4896
|
-
this.handleError(error instanceof Error ? error : new Error(String(error)), {
|
|
4897
|
-
conversationId,
|
|
4898
|
-
message,
|
|
4899
|
-
metadata
|
|
4900
|
-
});
|
|
4901
|
-
throw error;
|
|
4902
5652
|
}
|
|
4903
|
-
|
|
5653
|
+
return { channelId };
|
|
4904
5654
|
}
|
|
4905
5655
|
/**
|
|
4906
5656
|
* Initiate an outbound chat conversation
|
|
@@ -4929,14 +5679,6 @@ var ChatChannel = class extends MessagingChannel {
|
|
|
4929
5679
|
}
|
|
4930
5680
|
};
|
|
4931
5681
|
|
|
4932
|
-
// packages/core/src/lib/deprecation.ts
|
|
4933
|
-
var warned = /* @__PURE__ */ new Set();
|
|
4934
|
-
function warnDeprecated(oldName, replacement) {
|
|
4935
|
-
if (warned.has(oldName)) return;
|
|
4936
|
-
warned.add(oldName);
|
|
4937
|
-
console.warn(`${oldName} is deprecated and will be removed in 3.0 \u2014 use ${replacement} instead.`);
|
|
4938
|
-
}
|
|
4939
|
-
|
|
4940
5682
|
// packages/core/src/channels/voice/provider.ts
|
|
4941
5683
|
var VoiceProvider = class {
|
|
4942
5684
|
/** The `VoiceChannel` that owns this provider. */
|
|
@@ -4967,6 +5709,20 @@ var VoiceProvider = class {
|
|
|
4967
5709
|
get channelName() {
|
|
4968
5710
|
return "VOICE";
|
|
4969
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
|
+
}
|
|
4970
5726
|
/**
|
|
4971
5727
|
* Build the response for an inbound call. Default: not supported.
|
|
4972
5728
|
*
|
|
@@ -5072,6 +5828,21 @@ var VoiceProvider = class {
|
|
|
5072
5828
|
}
|
|
5073
5829
|
return callParams;
|
|
5074
5830
|
}
|
|
5831
|
+
/**
|
|
5832
|
+
* Resolve the outbound caller ID for a voice call.
|
|
5833
|
+
*
|
|
5834
|
+
* Validates `requested` against `config.phoneNumbers`, defaulting to
|
|
5835
|
+
* `config.phoneNumber` — the same rule messaging channels apply via
|
|
5836
|
+
* `resolveOutboundSender`.
|
|
5837
|
+
*/
|
|
5838
|
+
resolveFromNumber(requested) {
|
|
5839
|
+
const cfg = this.channel.getTacConfig();
|
|
5840
|
+
return resolveOutboundSender(requested, {
|
|
5841
|
+
allowlist: cfg.phoneNumbers,
|
|
5842
|
+
default: cfg.phoneNumber,
|
|
5843
|
+
channel: "voice"
|
|
5844
|
+
});
|
|
5845
|
+
}
|
|
5075
5846
|
};
|
|
5076
5847
|
var VoiceProviderConfig = class {
|
|
5077
5848
|
/** Memory retrieval mode for this channel. Defaults to `'never'`. */
|
|
@@ -5160,27 +5931,32 @@ var TwiMLBuilderBase = class {
|
|
|
5160
5931
|
);
|
|
5161
5932
|
}
|
|
5162
5933
|
/**
|
|
5163
|
-
* The WebSocket URL derived from `TACConfig.
|
|
5164
|
-
* `TACConfig.voiceWebsocketPath`, or undefined when
|
|
5165
|
-
*
|
|
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.
|
|
5166
5940
|
*/
|
|
5167
5941
|
defaultWebsocketUrl() {
|
|
5168
|
-
|
|
5942
|
+
const domain = this.tacConfig.voiceCallbackDomain;
|
|
5943
|
+
if (!domain) {
|
|
5169
5944
|
return void 0;
|
|
5170
5945
|
}
|
|
5171
|
-
return `wss://${
|
|
5946
|
+
return `wss://${domain}${this.tacConfig.voiceWebsocketPath}`;
|
|
5172
5947
|
}
|
|
5173
5948
|
/**
|
|
5174
5949
|
* Resolve the default `<Connect action=...>` cleanup URL from
|
|
5175
|
-
* `TACConfig.
|
|
5950
|
+
* `TACConfig.voiceCallbackDomain` + `TACConfig.voiceActionPath`.
|
|
5176
5951
|
*
|
|
5177
|
-
* Returns undefined if
|
|
5952
|
+
* Returns undefined if no public domain is set; that's fine because
|
|
5178
5953
|
* actionUrl has higher-priority layers (customizer, twimlOptions, Studio
|
|
5179
5954
|
* handoff) above this fallback.
|
|
5180
5955
|
*/
|
|
5181
5956
|
defaultActionUrl() {
|
|
5182
|
-
|
|
5183
|
-
|
|
5957
|
+
const domain = this.tacConfig.voiceCallbackDomain;
|
|
5958
|
+
if (domain) {
|
|
5959
|
+
return `https://${domain}${this.tacConfig.voiceActionPath}`;
|
|
5184
5960
|
}
|
|
5185
5961
|
return void 0;
|
|
5186
5962
|
}
|
|
@@ -5408,6 +6184,16 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5408
6184
|
get channelName() {
|
|
5409
6185
|
return "VOICE";
|
|
5410
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
|
+
}
|
|
5411
6197
|
/**
|
|
5412
6198
|
* Get active WebSocket connection for a conversation
|
|
5413
6199
|
*/
|
|
@@ -5449,7 +6235,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5449
6235
|
const conversation = conversations[0];
|
|
5450
6236
|
const conversationId = conversation.id;
|
|
5451
6237
|
const participants = await conversationClient.listParticipants(conversationId);
|
|
5452
|
-
const customerParticipant = participants.find(
|
|
6238
|
+
const customerParticipant = participants.find(
|
|
6239
|
+
(p) => p.type === "CUSTOMER" && p.addresses?.some((a) => a.channel === "VOICE")
|
|
6240
|
+
);
|
|
5453
6241
|
const customerAddress = customerParticipant?.addresses?.find((a) => a.channel === "VOICE")?.address ?? fromNumber ?? void 0;
|
|
5454
6242
|
const profileId = customerParticipant?.profileId ? customerParticipant.profileId : void 0;
|
|
5455
6243
|
this.webSocketConnections.set(conversationId, ws);
|
|
@@ -5757,27 +6545,44 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5757
6545
|
});
|
|
5758
6546
|
}
|
|
5759
6547
|
/**
|
|
5760
|
-
*
|
|
5761
|
-
*
|
|
5762
|
-
*
|
|
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.
|
|
5763
6557
|
*/
|
|
5764
6558
|
async handleWebSocketDisconnect(conversationId) {
|
|
6559
|
+
if (!this.webSocketConnections.has(conversationId) && !this.promptQueues.has(conversationId) && !this.channel.isConversationActive(conversationId)) {
|
|
6560
|
+
return;
|
|
6561
|
+
}
|
|
5765
6562
|
this.cancelStreamTask(conversationId);
|
|
5766
6563
|
this.webSocketConnections.delete(conversationId);
|
|
5767
6564
|
this.promptQueues.delete(conversationId);
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
voiceCallbacks.onWebSocketDisconnected
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
|
|
5778
|
-
|
|
5779
|
-
|
|
5780
|
-
|
|
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);
|
|
5781
6586
|
}
|
|
5782
6587
|
}
|
|
5783
6588
|
/**
|
|
@@ -5795,18 +6600,7 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5795
6600
|
last: true
|
|
5796
6601
|
};
|
|
5797
6602
|
ws.send(JSON.stringify(response));
|
|
5798
|
-
|
|
5799
|
-
if (session?.pendingHandoffData) {
|
|
5800
|
-
try {
|
|
5801
|
-
ws.send(JSON.stringify(session.pendingHandoffData));
|
|
5802
|
-
delete session.pendingHandoffData;
|
|
5803
|
-
} catch (err) {
|
|
5804
|
-
this.logger.warn(
|
|
5805
|
-
{ err, conversation_id: conversationId },
|
|
5806
|
-
"WebSocket closed before sending handoff end message; caller will not be transferred"
|
|
5807
|
-
);
|
|
5808
|
-
}
|
|
5809
|
-
}
|
|
6603
|
+
this.flushPendingHandoff(conversationId, ws);
|
|
5810
6604
|
return Promise.resolve();
|
|
5811
6605
|
} catch (error) {
|
|
5812
6606
|
this.channel.handleErrorInternal(error instanceof Error ? error : new Error(String(error)), {
|
|
@@ -5817,6 +6611,29 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5817
6611
|
throw error;
|
|
5818
6612
|
}
|
|
5819
6613
|
}
|
|
6614
|
+
/**
|
|
6615
|
+
* Send the ConversationRelay `end` message if the session has a handoff
|
|
6616
|
+
* pending, so the caller is transferred once the response has been delivered.
|
|
6617
|
+
* No-op when nothing is pending.
|
|
6618
|
+
*/
|
|
6619
|
+
flushPendingHandoff(conversationId, ws) {
|
|
6620
|
+
const session = this.channel.getConversationSession(conversationId);
|
|
6621
|
+
if (!session?.pendingHandoffData) {
|
|
6622
|
+
return;
|
|
6623
|
+
}
|
|
6624
|
+
try {
|
|
6625
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
6626
|
+
throw new Error(`WebSocket is not open (readyState: ${ws.readyState})`);
|
|
6627
|
+
}
|
|
6628
|
+
ws.send(JSON.stringify(session.pendingHandoffData));
|
|
6629
|
+
delete session.pendingHandoffData;
|
|
6630
|
+
} catch (err) {
|
|
6631
|
+
this.logger.warn(
|
|
6632
|
+
{ err, conversation_id: conversationId },
|
|
6633
|
+
"WebSocket closed before sending handoff end message; caller will not be transferred"
|
|
6634
|
+
);
|
|
6635
|
+
}
|
|
6636
|
+
}
|
|
5820
6637
|
/**
|
|
5821
6638
|
* Send a streaming voice response via WebSocket, token by token.
|
|
5822
6639
|
*
|
|
@@ -5826,6 +6643,10 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5826
6643
|
* interrupted), iteration stops and no final marker is sent (the interrupt
|
|
5827
6644
|
* handler sends the finalization instead).
|
|
5828
6645
|
*
|
|
6646
|
+
* Once the stream completes, a handoff pending on the session is delivered as
|
|
6647
|
+
* the WS `end` message, matching {@link sendResponse}. An aborted stream
|
|
6648
|
+
* leaves it pending for the next response.
|
|
6649
|
+
*
|
|
5829
6650
|
* @returns The accumulated full response text.
|
|
5830
6651
|
*/
|
|
5831
6652
|
async sendStreamingResponse(conversationId, stream, options) {
|
|
@@ -5867,6 +6688,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5867
6688
|
if (!signal?.aborted && hasSentTokens && ws.readyState === WebSocket.OPEN) {
|
|
5868
6689
|
ws.send(JSON.stringify({ type: "text", token: "", last: true }));
|
|
5869
6690
|
}
|
|
6691
|
+
if (!signal?.aborted) {
|
|
6692
|
+
this.flushPendingHandoff(conversationId, ws);
|
|
6693
|
+
}
|
|
5870
6694
|
} catch (error) {
|
|
5871
6695
|
this.channel.handleErrorInternal(error instanceof Error ? error : new Error(String(error)), {
|
|
5872
6696
|
conversationId
|
|
@@ -6095,7 +6919,7 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
6095
6919
|
*/
|
|
6096
6920
|
async initiateOutboundConversation(options) {
|
|
6097
6921
|
const validated = InitiateVoiceConversationOptionsSchema.parse(options);
|
|
6098
|
-
const fromNumber = this.
|
|
6922
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
6099
6923
|
this.logger.info(
|
|
6100
6924
|
{ to: validated.to, from: fromNumber },
|
|
6101
6925
|
"Initiating outbound voice conversation"
|
|
@@ -6165,11 +6989,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
6165
6989
|
return { status: 403, content: "Forbidden", contentType: "text/plain" };
|
|
6166
6990
|
}
|
|
6167
6991
|
if (payload.CallStatus === "completed" && !this.channel.isOrchestratorEnabledInternal()) {
|
|
6168
|
-
const conversationId = this.callSidToConversationId.get(payload.CallSid);
|
|
6169
|
-
|
|
6170
|
-
|
|
6171
|
-
await this.channel.endConversationInternal(conversationId);
|
|
6172
|
-
}
|
|
6992
|
+
const conversationId = this.callSidToConversationId.get(payload.CallSid) ?? payload.CallSid;
|
|
6993
|
+
this.callSidToConversationId.delete(payload.CallSid);
|
|
6994
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
6173
6995
|
}
|
|
6174
6996
|
return { status: 200, content: "OK", contentType: "text/plain" };
|
|
6175
6997
|
}
|
|
@@ -6250,6 +7072,8 @@ var ConversationRelayProviderConfig = class extends VoiceProviderConfig {
|
|
|
6250
7072
|
};
|
|
6251
7073
|
|
|
6252
7074
|
// packages/core/src/channels/voice/channel.ts
|
|
7075
|
+
var CO_VOICE_CHANNEL = "VOICE";
|
|
7076
|
+
var AGENT_TYPES2 = /* @__PURE__ */ new Set(["AGENT", "AI_AGENT"]);
|
|
6253
7077
|
var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
6254
7078
|
provider;
|
|
6255
7079
|
voiceCallbacks;
|
|
@@ -6258,6 +7082,17 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6258
7082
|
onCallStatusHandler;
|
|
6259
7083
|
onAmdHandler;
|
|
6260
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;
|
|
6261
7096
|
/**
|
|
6262
7097
|
* @param tac - The owning {@link TAC} instance.
|
|
6263
7098
|
* @param options - Either a {@link VoiceProviderConfig} selecting the media
|
|
@@ -6267,7 +7102,14 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6267
7102
|
*/
|
|
6268
7103
|
constructor(tac, options) {
|
|
6269
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
|
+
}
|
|
6270
7110
|
this.voiceCallbacks = {};
|
|
7111
|
+
this.activeConversations = /* @__PURE__ */ new Map();
|
|
7112
|
+
this.closedWhileLive = /* @__PURE__ */ new Set();
|
|
6271
7113
|
this.provider = _VoiceChannel.toProviderConfig(options).createProvider(this, this.config);
|
|
6272
7114
|
}
|
|
6273
7115
|
/**
|
|
@@ -6412,6 +7254,30 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6412
7254
|
onDtmf(callback) {
|
|
6413
7255
|
this.voiceCallbacks.onDtmf = callback;
|
|
6414
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
|
+
}
|
|
6415
7281
|
// =========================================================================
|
|
6416
7282
|
// Provider-facing surface
|
|
6417
7283
|
//
|
|
@@ -6496,8 +7362,7 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6496
7362
|
return this.onInboundCallTwimlHandler;
|
|
6497
7363
|
}
|
|
6498
7364
|
/**
|
|
6499
|
-
* Start tracking a
|
|
6500
|
-
* `BaseChannel.startConversation`.
|
|
7365
|
+
* Start tracking a call's session. Forwards to {@link startConversation}.
|
|
6501
7366
|
*
|
|
6502
7367
|
* @internal
|
|
6503
7368
|
*/
|
|
@@ -6505,13 +7370,13 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6505
7370
|
return this.startConversation(conversationId, profileId);
|
|
6506
7371
|
}
|
|
6507
7372
|
/**
|
|
6508
|
-
*
|
|
6509
|
-
*
|
|
7373
|
+
* Release a finished call's session and fire the end-of-call hooks.
|
|
7374
|
+
* Forwards to {@link releaseSession}.
|
|
6510
7375
|
*
|
|
6511
7376
|
* @internal
|
|
6512
7377
|
*/
|
|
6513
|
-
|
|
6514
|
-
return this.
|
|
7378
|
+
releaseSessionInternal(conversationId) {
|
|
7379
|
+
return this.releaseSession(conversationId);
|
|
6515
7380
|
}
|
|
6516
7381
|
/**
|
|
6517
7382
|
* Retrieve memory when `memoryMode` calls for it. Forwards to
|
|
@@ -6572,67 +7437,389 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6572
7437
|
}
|
|
6573
7438
|
}
|
|
6574
7439
|
/**
|
|
6575
|
-
* 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.
|
|
6576
7639
|
*
|
|
6577
|
-
*
|
|
6578
|
-
*
|
|
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.
|
|
6579
7646
|
*
|
|
6580
|
-
*
|
|
6581
|
-
*
|
|
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.
|
|
6582
7654
|
*
|
|
6583
|
-
*
|
|
6584
|
-
*
|
|
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`.
|
|
6585
7657
|
*/
|
|
6586
|
-
async
|
|
6587
|
-
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
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;
|
|
6591
7694
|
}
|
|
6592
|
-
const
|
|
6593
|
-
|
|
6594
|
-
|
|
6595
|
-
this.logger.debug(
|
|
6596
|
-
{ conversation_id: conversationId, status: webhookData.data?.status },
|
|
6597
|
-
"Handling CONVERSATION_UPDATED"
|
|
6598
|
-
);
|
|
6599
|
-
await this.handleConversationUpdated(webhookData);
|
|
6600
|
-
break;
|
|
6601
|
-
default:
|
|
6602
|
-
this.logger.debug(
|
|
6603
|
-
{
|
|
6604
|
-
event_type: eventType,
|
|
6605
|
-
raw_event_type: webhookData.eventType,
|
|
6606
|
-
conversation_id: conversationId
|
|
6607
|
-
},
|
|
6608
|
-
"Unhandled event type - this event will be ignored"
|
|
6609
|
-
);
|
|
7695
|
+
const proto = Object.getPrototypeOf(value);
|
|
7696
|
+
if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
|
|
7697
|
+
return value;
|
|
6610
7698
|
}
|
|
6611
|
-
|
|
6612
|
-
|
|
6613
|
-
|
|
6614
|
-
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;
|
|
6615
7707
|
}
|
|
6616
|
-
|
|
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");
|
|
7721
|
+
}
|
|
7722
|
+
if (live.aiAgentInfo !== void 0) {
|
|
7723
|
+
snapshot.aiAgentInfo = detached(live.aiAgentInfo, "aiAgentInfo");
|
|
6617
7724
|
}
|
|
7725
|
+
if (live.pendingHandoffData !== void 0) {
|
|
7726
|
+
snapshot.pendingHandoffData = detached(live.pendingHandoffData, "pendingHandoffData");
|
|
7727
|
+
}
|
|
7728
|
+
return snapshot;
|
|
6618
7729
|
}
|
|
6619
7730
|
/**
|
|
6620
|
-
*
|
|
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.
|
|
6621
7734
|
*/
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
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;
|
|
6626
7758
|
}
|
|
6627
|
-
|
|
6628
|
-
|
|
6629
|
-
|
|
6630
|
-
|
|
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"
|
|
6631
7766
|
);
|
|
6632
|
-
|
|
6633
|
-
}
|
|
6634
|
-
|
|
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 };
|
|
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 };
|
|
6635
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);
|
|
6636
7823
|
}
|
|
6637
7824
|
/**
|
|
6638
7825
|
* Get active WebSocket connection for a conversation
|
|
@@ -6664,7 +7851,8 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6664
7851
|
/**
|
|
6665
7852
|
* Send voice response via WebSocket
|
|
6666
7853
|
*/
|
|
6667
|
-
async sendResponse(
|
|
7854
|
+
async sendResponse(conversationIdOrSession, message, metadata) {
|
|
7855
|
+
const conversationId = typeof conversationIdOrSession === "string" ? conversationIdOrSession : conversationIdOrSession.conversationId;
|
|
6668
7856
|
await this.provider.sendResponse(conversationId, message, metadata);
|
|
6669
7857
|
trackEvent("Response Sent", {
|
|
6670
7858
|
account_sid: this.config.accountSid,
|
|
@@ -6875,6 +8063,11 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6875
8063
|
* hangs up while AMD is still resolving), and handlers shouldn't have to
|
|
6876
8064
|
* guard against it.
|
|
6877
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
|
+
*
|
|
6878
8071
|
* @param callSid - Twilio Call SID (from a call event, the outbound result, or
|
|
6879
8072
|
* `ConversationSession.callSid`).
|
|
6880
8073
|
* @returns True if Twilio accepted the hangup, false if it failed (logged).
|
|
@@ -6891,7 +8084,7 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6891
8084
|
}
|
|
6892
8085
|
const session = this.getConversationSessionByCallSid(callSid);
|
|
6893
8086
|
if (session) {
|
|
6894
|
-
await this.
|
|
8087
|
+
await this.releaseSession(session.conversationId);
|
|
6895
8088
|
}
|
|
6896
8089
|
return hungUp;
|
|
6897
8090
|
}
|
|
@@ -6908,10 +8101,10 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6908
8101
|
* exist before the caller speaks — including before `onAmd` fires. Treat it
|
|
6909
8102
|
* as racy and hang up with {@link endCall}, which needs no session.
|
|
6910
8103
|
*
|
|
6911
|
-
* At the other end
|
|
6912
|
-
*
|
|
6913
|
-
* `onRecording`
|
|
6914
|
-
*
|
|
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.
|
|
6915
8108
|
*
|
|
6916
8109
|
* @example
|
|
6917
8110
|
* ```typescript
|
|
@@ -6926,8 +8119,9 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6926
8119
|
* @param callSid - Twilio Call SID, e.g. from
|
|
6927
8120
|
* `InitiateVoiceConversationResult.callSid` or a call event.
|
|
6928
8121
|
* @returns The session, or `undefined` — not created yet, the call ended, or
|
|
6929
|
-
* it landed on another instance
|
|
6930
|
-
*
|
|
8122
|
+
* it landed on another instance. For the last case,
|
|
8123
|
+
* {@link resolveConversationSessionByCallSid} falls back to Conversation
|
|
8124
|
+
* Orchestrator.
|
|
6931
8125
|
*/
|
|
6932
8126
|
getConversationSessionByCallSid(callSid) {
|
|
6933
8127
|
for (const session of this.activeConversations.values()) {
|
|
@@ -6937,6 +8131,81 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
6937
8131
|
}
|
|
6938
8132
|
return void 0;
|
|
6939
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
|
+
}
|
|
6940
8209
|
// =========================================================================
|
|
6941
8210
|
// Stream Task Management
|
|
6942
8211
|
//
|
|
@@ -7026,6 +8295,8 @@ var VoiceChannel = class _VoiceChannel extends BaseChannel {
|
|
|
7026
8295
|
*/
|
|
7027
8296
|
shutdown() {
|
|
7028
8297
|
this.provider.shutdown();
|
|
8298
|
+
this.activeConversations.clear();
|
|
8299
|
+
this.closedWhileLive.clear();
|
|
7029
8300
|
super.shutdown();
|
|
7030
8301
|
}
|
|
7031
8302
|
};
|
|
@@ -7075,7 +8346,7 @@ var TwiMLBuilderMediaStreams = class extends TwiMLBuilderBase {
|
|
|
7075
8346
|
* 2. the provider config's `defaultTwimlOptions` — channel-wide defaults
|
|
7076
8347
|
* 3. `host` — per-call transport facts supplied by the host
|
|
7077
8348
|
* 4. TAC defaults: the WebSocket URL derived from
|
|
7078
|
-
* `TACConfig.
|
|
8349
|
+
* `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
|
|
7079
8350
|
*
|
|
7080
8351
|
* @param caller - Name of the calling method, used in the "no WebSocket URL"
|
|
7081
8352
|
* error so it points at the API the developer actually called.
|
|
@@ -7097,6 +8368,8 @@ var TwiMLBuilderMediaStreams = class extends TwiMLBuilderBase {
|
|
|
7097
8368
|
*
|
|
7098
8369
|
* `customParameters` replaces wholesale when set at a higher-priority layer —
|
|
7099
8370
|
* there's no per-key merging.
|
|
8371
|
+
*
|
|
8372
|
+
* @internal
|
|
7100
8373
|
*/
|
|
7101
8374
|
buildTwimlOptions(host, perCall) {
|
|
7102
8375
|
const merged = {};
|
|
@@ -7199,11 +8472,11 @@ var MediaStreamsOpenAICallState = class {
|
|
|
7199
8472
|
modelReady = null;
|
|
7200
8473
|
};
|
|
7201
8474
|
var OPENAI_USER_AGENT = `twilio-agent-connect/TypeScript ${package_default.version}`;
|
|
7202
|
-
var
|
|
8475
|
+
var SESSION_CONFIG_TOKEN_PARAM = "_tac_session_config_token";
|
|
7203
8476
|
function describeIssues(issues) {
|
|
7204
8477
|
return issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join(", ");
|
|
7205
8478
|
}
|
|
7206
|
-
var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
8479
|
+
var MediaStreamsOpenAIProvider = class _MediaStreamsOpenAIProvider extends VoiceProvider {
|
|
7207
8480
|
/**
|
|
7208
8481
|
* The owning channel's logger, so this provider logs under the same name the
|
|
7209
8482
|
* rest of the voice channel does.
|
|
@@ -7217,21 +8490,16 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7217
8490
|
tacConfig;
|
|
7218
8491
|
twimlBuilder;
|
|
7219
8492
|
/**
|
|
7220
|
-
*
|
|
8493
|
+
* Per-call session config overrides, minted by one Twilio request and
|
|
8494
|
+
* consumed when the call's WebSocket connects.
|
|
7221
8495
|
*
|
|
7222
|
-
*
|
|
7223
|
-
*
|
|
7224
|
-
*
|
|
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.
|
|
7225
8501
|
*/
|
|
7226
8502
|
pendingSessionConfigs;
|
|
7227
|
-
/**
|
|
7228
|
-
* Expiry timers for the inbound {@link pendingSessionConfigs} entries, keyed
|
|
7229
|
-
* by the same call SID. Each fires once to purge a stash whose Media Stream
|
|
7230
|
-
* never connected; a normal connect cancels it in the subclass's
|
|
7231
|
-
* `registerCall`. Outbound entries are keyed by token instead and are not
|
|
7232
|
-
* tracked here.
|
|
7233
|
-
*/
|
|
7234
|
-
pendingInboundExpiries;
|
|
7235
8503
|
constructor(channel, tacConfig, config) {
|
|
7236
8504
|
super(channel);
|
|
7237
8505
|
this.logger = channel.getLoggerInternal();
|
|
@@ -7240,8 +8508,7 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7240
8508
|
this.toolsByName = new Map(config.tools.map((tool) => [tool.name, tool]));
|
|
7241
8509
|
this.calls = /* @__PURE__ */ new Map();
|
|
7242
8510
|
this.twimlBuilder = new TwiMLBuilderMediaStreams(tacConfig, config, this.logger);
|
|
7243
|
-
this.pendingSessionConfigs =
|
|
7244
|
-
this.pendingInboundExpiries = /* @__PURE__ */ new Map();
|
|
8511
|
+
this.pendingSessionConfigs = new ExpiringMap();
|
|
7245
8512
|
}
|
|
7246
8513
|
/** The Twilio-facing WebSocket for a conversation, if one is tracked. */
|
|
7247
8514
|
getWebSocket(conversationId) {
|
|
@@ -7279,16 +8546,17 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7279
8546
|
* The transcript captured so far for an in-progress call.
|
|
7280
8547
|
*
|
|
7281
8548
|
* It lives on `ConversationSession.metadata.transcript`, so once the call
|
|
7282
|
-
* ends and the session is
|
|
7283
|
-
* 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.
|
|
7284
8552
|
*/
|
|
7285
8553
|
getTranscript(conversationId) {
|
|
7286
8554
|
const transcript = this.channel.getConversationSession(conversationId)?.metadata.transcript;
|
|
7287
8555
|
return Array.isArray(transcript) ? [...transcript] : [];
|
|
7288
8556
|
}
|
|
7289
8557
|
/**
|
|
7290
|
-
* The session config stashed for `key` — a
|
|
7291
|
-
*
|
|
8558
|
+
* The session config stashed for `key` — a session-config token before the
|
|
8559
|
+
* call connects, its conversation id after.
|
|
7292
8560
|
*
|
|
7293
8561
|
* @internal
|
|
7294
8562
|
*/
|
|
@@ -7304,37 +8572,55 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7304
8572
|
return this.pendingSessionConfigs.size;
|
|
7305
8573
|
}
|
|
7306
8574
|
/**
|
|
7307
|
-
*
|
|
7308
|
-
*
|
|
7309
|
-
*
|
|
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.
|
|
8585
|
+
*
|
|
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.
|
|
7310
8590
|
*
|
|
7311
|
-
*
|
|
7312
|
-
* the call it belongs to is long over. Re-arming replaces any prior timer for
|
|
7313
|
-
* the same call SID, so a duplicate inbound webhook can't orphan one.
|
|
8591
|
+
* @internal
|
|
7314
8592
|
*/
|
|
7315
|
-
|
|
7316
|
-
this.
|
|
7317
|
-
|
|
7318
|
-
|
|
7319
|
-
|
|
7320
|
-
}
|
|
7321
|
-
timer.unref();
|
|
7322
|
-
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
|
+
};
|
|
7323
8599
|
}
|
|
7324
8600
|
/**
|
|
7325
|
-
*
|
|
7326
|
-
*
|
|
7327
|
-
*
|
|
7328
|
-
*
|
|
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`.
|
|
7329
8608
|
*
|
|
7330
8609
|
* @internal
|
|
7331
8610
|
*/
|
|
7332
|
-
|
|
7333
|
-
|
|
7334
|
-
|
|
7335
|
-
|
|
7336
|
-
|
|
8611
|
+
claimSessionConfig(token, conversationId) {
|
|
8612
|
+
if (token === void 0) {
|
|
8613
|
+
return;
|
|
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;
|
|
7337
8622
|
}
|
|
8623
|
+
this.pendingSessionConfigs.set(conversationId, sessionConfig);
|
|
7338
8624
|
}
|
|
7339
8625
|
/**
|
|
7340
8626
|
* The executable tool the model would run for `name`, if the config supplied
|
|
@@ -7360,12 +8646,14 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7360
8646
|
* 3. `options.hostTwimlOptions` — per-call transport facts supplied by the
|
|
7361
8647
|
* host
|
|
7362
8648
|
* 4. TAC defaults: the WebSocket URL derived from
|
|
7363
|
-
* `TACConfig.
|
|
8649
|
+
* `TACConfig.voiceCallbackDomain` + `voiceWebsocketPath`
|
|
7364
8650
|
*
|
|
7365
8651
|
* Also runs `MediaStreamsOpenAIProviderConfig.onInboundCallSessionConfig`, if
|
|
7366
|
-
* set, and stashes its result for the call to pick up once it connects
|
|
7367
|
-
*
|
|
7368
|
-
*
|
|
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.
|
|
7369
8657
|
*
|
|
7370
8658
|
* @param twimlRequest - Parsed Twilio webhook fields for the inbound call.
|
|
7371
8659
|
* @param options - Additional per-call inputs.
|
|
@@ -7391,13 +8679,18 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7391
8679
|
"the onInboundCallTwiml customizer output"
|
|
7392
8680
|
);
|
|
7393
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
|
+
}
|
|
7394
8691
|
const twiml = this.twimlBuilder.build("handleIncomingCall", { host, perCall: customized });
|
|
7395
|
-
if (
|
|
7396
|
-
|
|
7397
|
-
if (sessionConfig !== null) {
|
|
7398
|
-
this.pendingSessionConfigs.set(twimlRequest.callSid, sessionConfig);
|
|
7399
|
-
this.armInboundConfigExpiry(twimlRequest.callSid);
|
|
7400
|
-
}
|
|
8692
|
+
if (token !== void 0 && sessionConfig !== null) {
|
|
8693
|
+
this.pendingSessionConfigs.set(token, sessionConfig);
|
|
7401
8694
|
}
|
|
7402
8695
|
return twiml;
|
|
7403
8696
|
}
|
|
@@ -7516,10 +8809,6 @@ var MediaStreamsOpenAIProvider = class extends VoiceProvider {
|
|
|
7516
8809
|
*/
|
|
7517
8810
|
shutdown() {
|
|
7518
8811
|
super.shutdown();
|
|
7519
|
-
for (const timer of this.pendingInboundExpiries.values()) {
|
|
7520
|
-
clearTimeout(timer);
|
|
7521
|
-
}
|
|
7522
|
-
this.pendingInboundExpiries.clear();
|
|
7523
8812
|
this.calls.clear();
|
|
7524
8813
|
this.pendingSessionConfigs.clear();
|
|
7525
8814
|
}
|
|
@@ -7549,7 +8838,6 @@ var CallState = class extends MediaStreamsOpenAICallState {
|
|
|
7549
8838
|
};
|
|
7550
8839
|
|
|
7551
8840
|
// packages/core/src/channels/voice/media-streams/openai-realtime/provider.ts
|
|
7552
|
-
var SESSION_CONFIG_TOKEN_PARAM = "_tac_session_config_token";
|
|
7553
8841
|
var TWILIO_AUDIO_FORMAT_FOR_REALTIME = { type: "audio/pcmu" };
|
|
7554
8842
|
var PCMU_BYTES_PER_MS = 8;
|
|
7555
8843
|
function isTwilioMediaStreamAudioFormat(value) {
|
|
@@ -7561,7 +8849,7 @@ function isTwilioMediaStreamAudioFormat(value) {
|
|
|
7561
8849
|
const keys = Object.keys(actual);
|
|
7562
8850
|
return keys.length === Object.keys(expected).length && keys.every((key) => actual[key] === expected[key]);
|
|
7563
8851
|
}
|
|
7564
|
-
var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
8852
|
+
var OpenAIRealtimeProvider = class _OpenAIRealtimeProvider extends MediaStreamsOpenAIProvider {
|
|
7565
8853
|
/** @internal */
|
|
7566
8854
|
get providerId() {
|
|
7567
8855
|
return "openai_realtime";
|
|
@@ -7615,16 +8903,10 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
7615
8903
|
const sessionConfig = validated.sessionConfig ?? null;
|
|
7616
8904
|
let sessionConfigToken = null;
|
|
7617
8905
|
if (sessionConfig !== null) {
|
|
7618
|
-
sessionConfigToken =
|
|
7619
|
-
twimlOptions =
|
|
7620
|
-
...twimlOptions,
|
|
7621
|
-
customParameters: {
|
|
7622
|
-
...twimlOptions?.customParameters,
|
|
7623
|
-
[SESSION_CONFIG_TOKEN_PARAM]: sessionConfigToken
|
|
7624
|
-
}
|
|
7625
|
-
};
|
|
8906
|
+
sessionConfigToken = _OpenAIRealtimeProvider.newSessionConfigToken();
|
|
8907
|
+
twimlOptions = this.withSessionConfigToken(void 0, twimlOptions, sessionConfigToken);
|
|
7626
8908
|
}
|
|
7627
|
-
const fromNumber = this.
|
|
8909
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
7628
8910
|
this.logger.info(
|
|
7629
8911
|
{ to: maskPhone(validated.to), from: maskPhone(fromNumber) },
|
|
7630
8912
|
"Initiating outbound voice conversation"
|
|
@@ -7773,15 +9055,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
7773
9055
|
registerCall(start, ws) {
|
|
7774
9056
|
const message = StreamStartMessageSchema.parse(start ?? {});
|
|
7775
9057
|
const conversationId = message.callSid;
|
|
7776
|
-
this.
|
|
7777
|
-
const token = message.customParameters[SESSION_CONFIG_TOKEN_PARAM];
|
|
7778
|
-
if (token !== void 0) {
|
|
7779
|
-
const pending = this.pendingSessionConfigs.get(token);
|
|
7780
|
-
if (pending !== void 0) {
|
|
7781
|
-
this.pendingSessionConfigs.delete(token);
|
|
7782
|
-
this.pendingSessionConfigs.set(conversationId, pending);
|
|
7783
|
-
}
|
|
7784
|
-
}
|
|
9058
|
+
this.claimSessionConfig(message.customParameters[SESSION_CONFIG_TOKEN_PARAM], conversationId);
|
|
7785
9059
|
try {
|
|
7786
9060
|
const session = this.channel.startConversationInternal(conversationId);
|
|
7787
9061
|
session.callSid = message.callSid;
|
|
@@ -7796,7 +9070,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
7796
9070
|
});
|
|
7797
9071
|
} catch (err) {
|
|
7798
9072
|
this.pendingSessionConfigs.delete(conversationId);
|
|
7799
|
-
void this.channel.
|
|
9073
|
+
void this.channel.releaseSessionInternal(conversationId).catch(() => void 0);
|
|
7800
9074
|
throw err;
|
|
7801
9075
|
}
|
|
7802
9076
|
const call = new CallState();
|
|
@@ -8106,14 +9380,15 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8106
9380
|
this.modelSend(conversationId, { type: "response.create" });
|
|
8107
9381
|
}
|
|
8108
9382
|
/**
|
|
8109
|
-
* Drop this call's transport state
|
|
8110
|
-
* session.
|
|
9383
|
+
* Drop this call's transport state and any stashed session config, close
|
|
9384
|
+
* the model socket, and release the session.
|
|
8111
9385
|
*
|
|
8112
9386
|
* Both legs can report the call ending, and the first one to arrive tears
|
|
8113
9387
|
* down the other, so this runs at most once per call: a second invocation
|
|
8114
9388
|
* finds nothing tracked and returns.
|
|
8115
9389
|
*/
|
|
8116
9390
|
async cleanupCall(conversationId) {
|
|
9391
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
8117
9392
|
const call = this.calls.get(conversationId);
|
|
8118
9393
|
if (call === void 0) {
|
|
8119
9394
|
return;
|
|
@@ -8126,7 +9401,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
8126
9401
|
this.logger.debug({ err, conversation_id: conversationId }, "Error closing model socket");
|
|
8127
9402
|
}
|
|
8128
9403
|
}
|
|
8129
|
-
await this.channel.
|
|
9404
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
8130
9405
|
}
|
|
8131
9406
|
};
|
|
8132
9407
|
|
|
@@ -8173,8 +9448,6 @@ var CallState2 = class extends MediaStreamsOpenAICallState {
|
|
|
8173
9448
|
// packages/core/src/channels/voice/media-streams/gpt-live/provider.ts
|
|
8174
9449
|
var TWILIO_AUDIO_FORMAT_FOR_GPT_LIVE = { type: "audio/pcmu", rate: 8e3 };
|
|
8175
9450
|
var GPT_LIVE_SESSION_ID_METADATA_KEY = "gpt_live_session_id";
|
|
8176
|
-
var SESSION_CONFIG_TOKEN_PARAM2 = "_tac_session_config_token";
|
|
8177
|
-
var SESSION_CONFIG_TOKEN_TTL_MS = 12e4;
|
|
8178
9451
|
var GPT_LIVE_URL = "wss://api.openai.com/v1/live/sessions";
|
|
8179
9452
|
var CLOSE_TIMEOUT_MS = 5e3;
|
|
8180
9453
|
function isTwilioMediaStreamAudioFormat2(value) {
|
|
@@ -8202,7 +9475,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8202
9475
|
get providerId() {
|
|
8203
9476
|
return "gpt_live";
|
|
8204
9477
|
}
|
|
8205
|
-
pendingTokenExpiries = /* @__PURE__ */ new Map();
|
|
8206
9478
|
/** Calls whose teardown has begun but is still awaiting `session.closed`. */
|
|
8207
9479
|
closingCalls = /* @__PURE__ */ new Set();
|
|
8208
9480
|
get channelName() {
|
|
@@ -8245,16 +9517,10 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8245
9517
|
const sessionConfig = validated.sessionConfig ?? null;
|
|
8246
9518
|
let sessionConfigToken = null;
|
|
8247
9519
|
if (sessionConfig !== null) {
|
|
8248
|
-
sessionConfigToken =
|
|
8249
|
-
twimlOptions =
|
|
8250
|
-
...twimlOptions,
|
|
8251
|
-
customParameters: {
|
|
8252
|
-
...twimlOptions?.customParameters,
|
|
8253
|
-
[SESSION_CONFIG_TOKEN_PARAM2]: sessionConfigToken
|
|
8254
|
-
}
|
|
8255
|
-
};
|
|
9520
|
+
sessionConfigToken = _GPTLiveProvider.newSessionConfigToken();
|
|
9521
|
+
twimlOptions = this.withSessionConfigToken(void 0, twimlOptions, sessionConfigToken);
|
|
8256
9522
|
}
|
|
8257
|
-
const fromNumber = this.
|
|
9523
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
8258
9524
|
this.logger.info(
|
|
8259
9525
|
{ to: maskPhone(validated.to), from: maskPhone(fromNumber) },
|
|
8260
9526
|
"Initiating outbound voice conversation"
|
|
@@ -8285,9 +9551,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8285
9551
|
{ call_sid: call.sid, to: maskPhone(validated.to) },
|
|
8286
9552
|
"Outbound voice call placed"
|
|
8287
9553
|
);
|
|
8288
|
-
if (sessionConfigToken !== null) {
|
|
8289
|
-
this.armTokenExpiry(sessionConfigToken);
|
|
8290
|
-
}
|
|
8291
9554
|
return { callSid: call.sid };
|
|
8292
9555
|
} catch (error) {
|
|
8293
9556
|
if (sessionConfigToken !== null) {
|
|
@@ -8300,34 +9563,6 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8300
9563
|
throw error;
|
|
8301
9564
|
}
|
|
8302
9565
|
}
|
|
8303
|
-
/**
|
|
8304
|
-
* Start the clock on a stashed token, so a call that never connects cannot
|
|
8305
|
-
* strand its override in {@link pendingSessionConfigs} forever.
|
|
8306
|
-
*
|
|
8307
|
-
* Unref'd: a two-minute timer must not be what keeps the process alive after
|
|
8308
|
-
* the call it belongs to is long over.
|
|
8309
|
-
*/
|
|
8310
|
-
armTokenExpiry(token) {
|
|
8311
|
-
const timer = setTimeout(() => {
|
|
8312
|
-
this.pendingTokenExpiries.delete(token);
|
|
8313
|
-
this.pendingSessionConfigs.delete(token);
|
|
8314
|
-
}, SESSION_CONFIG_TOKEN_TTL_MS);
|
|
8315
|
-
timer.unref();
|
|
8316
|
-
this.pendingTokenExpiries.set(token, timer);
|
|
8317
|
-
}
|
|
8318
|
-
/**
|
|
8319
|
-
* Stop the clock on a token, once the call it belongs to has claimed it.
|
|
8320
|
-
*
|
|
8321
|
-
* Without this a two-minute timer outlives every call that connected
|
|
8322
|
-
* normally, waiting to purge an entry that is already gone.
|
|
8323
|
-
*/
|
|
8324
|
-
cancelTokenExpiry(token) {
|
|
8325
|
-
const timer = this.pendingTokenExpiries.get(token);
|
|
8326
|
-
if (timer !== void 0) {
|
|
8327
|
-
clearTimeout(timer);
|
|
8328
|
-
this.pendingTokenExpiries.delete(token);
|
|
8329
|
-
}
|
|
8330
|
-
}
|
|
8331
9566
|
// =========================================================================
|
|
8332
9567
|
// Audio Bridge
|
|
8333
9568
|
// =========================================================================
|
|
@@ -8424,16 +9659,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8424
9659
|
registerCall(start, ws) {
|
|
8425
9660
|
const message = StreamStartMessageSchema.parse(start ?? {});
|
|
8426
9661
|
const conversationId = message.callSid;
|
|
8427
|
-
this.
|
|
8428
|
-
const token = message.customParameters[SESSION_CONFIG_TOKEN_PARAM2];
|
|
8429
|
-
if (token !== void 0) {
|
|
8430
|
-
const pending = this.pendingSessionConfigs.get(token);
|
|
8431
|
-
if (pending !== void 0) {
|
|
8432
|
-
this.pendingSessionConfigs.delete(token);
|
|
8433
|
-
this.pendingSessionConfigs.set(conversationId, pending);
|
|
8434
|
-
}
|
|
8435
|
-
this.cancelTokenExpiry(token);
|
|
8436
|
-
}
|
|
9662
|
+
this.claimSessionConfig(message.customParameters[SESSION_CONFIG_TOKEN_PARAM], conversationId);
|
|
8437
9663
|
const call = new CallState2();
|
|
8438
9664
|
call.twilioWs = ws;
|
|
8439
9665
|
this.calls.set(conversationId, call);
|
|
@@ -8452,7 +9678,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8452
9678
|
} catch (err) {
|
|
8453
9679
|
this.calls.delete(conversationId);
|
|
8454
9680
|
this.pendingSessionConfigs.delete(conversationId);
|
|
8455
|
-
void this.channel.
|
|
9681
|
+
void this.channel.releaseSessionInternal(conversationId).catch(() => void 0);
|
|
8456
9682
|
throw err;
|
|
8457
9683
|
}
|
|
8458
9684
|
this.logger.debug(
|
|
@@ -8558,6 +9784,9 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8558
9784
|
async cleanupCall(conversationId) {
|
|
8559
9785
|
const call = this.calls.get(conversationId);
|
|
8560
9786
|
if (call === void 0 || this.closingCalls.has(conversationId)) {
|
|
9787
|
+
if (call === void 0) {
|
|
9788
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
9789
|
+
}
|
|
8561
9790
|
return;
|
|
8562
9791
|
}
|
|
8563
9792
|
this.closingCalls.add(conversationId);
|
|
@@ -8592,6 +9821,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8592
9821
|
}
|
|
8593
9822
|
this.calls.delete(conversationId);
|
|
8594
9823
|
this.closingCalls.delete(conversationId);
|
|
9824
|
+
this.pendingSessionConfigs.delete(conversationId);
|
|
8595
9825
|
if (modelWs !== null) {
|
|
8596
9826
|
try {
|
|
8597
9827
|
modelWs.close();
|
|
@@ -8599,21 +9829,13 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8599
9829
|
this.logger.debug({ err, conversation_id: conversationId }, "Error closing model socket");
|
|
8600
9830
|
}
|
|
8601
9831
|
}
|
|
8602
|
-
await this.channel.
|
|
9832
|
+
await this.channel.releaseSessionInternal(conversationId);
|
|
8603
9833
|
}
|
|
8604
9834
|
/**
|
|
8605
9835
|
* Drop this provider's transport state on channel shutdown, including the
|
|
8606
9836
|
* bookkeeping it keeps beyond the base class's.
|
|
8607
|
-
*
|
|
8608
|
-
* The token expiry timers are unref'd and delete themselves, so nothing hangs
|
|
8609
|
-
* without this — but a shut-down provider must not still be holding entries
|
|
8610
|
-
* for calls that can no longer arrive.
|
|
8611
9837
|
*/
|
|
8612
9838
|
shutdown() {
|
|
8613
|
-
for (const timer of this.pendingTokenExpiries.values()) {
|
|
8614
|
-
clearTimeout(timer);
|
|
8615
|
-
}
|
|
8616
|
-
this.pendingTokenExpiries.clear();
|
|
8617
9839
|
this.closingCalls.clear();
|
|
8618
9840
|
super.shutdown();
|
|
8619
9841
|
}
|
|
@@ -8779,51 +10001,6 @@ var GPTLiveProviderConfig = class extends MediaStreamsOpenAIProviderConfig {
|
|
|
8779
10001
|
}
|
|
8780
10002
|
};
|
|
8781
10003
|
|
|
8782
|
-
// packages/core/src/lib/conversation-session-helpers.ts
|
|
8783
|
-
function formatTraitValue(value) {
|
|
8784
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
8785
|
-
return String(value);
|
|
8786
|
-
}
|
|
8787
|
-
try {
|
|
8788
|
-
return JSON.stringify(value, (_key, replacerValue) => {
|
|
8789
|
-
if (typeof replacerValue === "bigint") {
|
|
8790
|
-
return String(replacerValue);
|
|
8791
|
-
}
|
|
8792
|
-
return replacerValue;
|
|
8793
|
-
}) ?? String(value);
|
|
8794
|
-
} catch {
|
|
8795
|
-
return String(value);
|
|
8796
|
-
}
|
|
8797
|
-
}
|
|
8798
|
-
function buildProfilePrompt(context, traitGroups) {
|
|
8799
|
-
if (!context.profile || !context.profile.traits) {
|
|
8800
|
-
return null;
|
|
8801
|
-
}
|
|
8802
|
-
let filteredTraits;
|
|
8803
|
-
if (traitGroups !== void 0) {
|
|
8804
|
-
if (traitGroups.length === 0) {
|
|
8805
|
-
return null;
|
|
8806
|
-
}
|
|
8807
|
-
filteredTraits = Object.fromEntries(
|
|
8808
|
-
Object.entries(context.profile.traits).filter(
|
|
8809
|
-
([key, value]) => traitGroups.includes(key) && value != null
|
|
8810
|
-
)
|
|
8811
|
-
);
|
|
8812
|
-
} else {
|
|
8813
|
-
filteredTraits = Object.fromEntries(
|
|
8814
|
-
Object.entries(context.profile.traits).filter(([, value]) => value != null)
|
|
8815
|
-
);
|
|
8816
|
-
}
|
|
8817
|
-
if (Object.keys(filteredTraits).length === 0) {
|
|
8818
|
-
return null;
|
|
8819
|
-
}
|
|
8820
|
-
const lines = ["## Customer Profile", "Information about this customer:"];
|
|
8821
|
-
for (const [key, value] of Object.entries(filteredTraits)) {
|
|
8822
|
-
lines.push(`- ${key}: ${formatTraitValue(value)}`);
|
|
8823
|
-
}
|
|
8824
|
-
return lines.join("\n");
|
|
8825
|
-
}
|
|
8826
|
-
|
|
8827
10004
|
// packages/core/src/adapters/options.ts
|
|
8828
10005
|
function getProfileTraits(options) {
|
|
8829
10006
|
if (!options || options.profileTraits === void 0) {
|
|
@@ -9151,7 +10328,7 @@ function createMemoryTools(memoryClient) {
|
|
|
9151
10328
|
}
|
|
9152
10329
|
|
|
9153
10330
|
// packages/tools/src/built-in/messaging.ts
|
|
9154
|
-
function createSendMessageTool(channel,
|
|
10331
|
+
function createSendMessageTool(channel, conversationIdOrSession) {
|
|
9155
10332
|
return defineTool(
|
|
9156
10333
|
BuiltInTools.SEND_MESSAGE,
|
|
9157
10334
|
"Send a message to the user in the current conversation",
|
|
@@ -9172,7 +10349,7 @@ function createSendMessageTool(channel, conversationId) {
|
|
|
9172
10349
|
},
|
|
9173
10350
|
async (params) => {
|
|
9174
10351
|
try {
|
|
9175
|
-
await channel.sendResponse(
|
|
10352
|
+
await channel.sendResponse(conversationIdOrSession, params.message, params.metadata);
|
|
9176
10353
|
return {
|
|
9177
10354
|
success: true,
|
|
9178
10355
|
message_id: `msg_${Date.now()}`
|
|
@@ -9190,11 +10367,30 @@ function createSendMessageTool(channel, conversationId) {
|
|
|
9190
10367
|
function createMessagingTools() {
|
|
9191
10368
|
return {
|
|
9192
10369
|
/**
|
|
9193
|
-
* 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}).
|
|
9194
10372
|
*/
|
|
9195
|
-
forConversation: (channel,
|
|
10373
|
+
forConversation: (channel, conversationIdOrSession) => createSendMessageTool(channel, conversationIdOrSession)
|
|
9196
10374
|
};
|
|
9197
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
|
+
}
|
|
9198
10394
|
function buildHandoffPayload(session, memoryStoreId, attributes) {
|
|
9199
10395
|
return {
|
|
9200
10396
|
conversationId: session.conversationId,
|
|
@@ -9210,7 +10406,7 @@ async function postStudioHandoff(payload, session, options) {
|
|
|
9210
10406
|
form.append("To", toAddress);
|
|
9211
10407
|
form.append("From", fromAddress);
|
|
9212
10408
|
form.append("Parameters", JSON.stringify({ HandoffData: payload }));
|
|
9213
|
-
await
|
|
10409
|
+
await axios3.post(handoffUrl, form.toString(), {
|
|
9214
10410
|
timeout: 1e4,
|
|
9215
10411
|
auth: { username: apiKey, password: apiSecret },
|
|
9216
10412
|
headers: { "Content-Type": "application/x-www-form-urlencoded" }
|
|
@@ -9258,48 +10454,53 @@ function createStudioHandoffTool(tac, session, options = {}) {
|
|
|
9258
10454
|
async (params) => {
|
|
9259
10455
|
const attributes = { ...staticAttributes, reason: params.reason };
|
|
9260
10456
|
const payload = buildHandoffPayload(session, memoryStoreId, attributes);
|
|
9261
|
-
|
|
9262
|
-
await coClient
|
|
9263
|
-
|
|
9264
|
-
|
|
9265
|
-
|
|
9266
|
-
|
|
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.`
|
|
9267
10483
|
);
|
|
9268
10484
|
}
|
|
10485
|
+
await stopTacRouting(tac, coClient, session.conversationId);
|
|
9269
10486
|
try {
|
|
9270
|
-
await
|
|
10487
|
+
await postStudioHandoff(payload, session, {
|
|
10488
|
+
handoffUrl: studioExecutionsUrl(flowSid),
|
|
10489
|
+
fromAddress,
|
|
10490
|
+
apiKey: config.apiKey,
|
|
10491
|
+
apiSecret: config.apiSecret
|
|
10492
|
+
});
|
|
9271
10493
|
} catch (err) {
|
|
9272
|
-
|
|
10494
|
+
const message = err instanceof AxiosError ? err.message : err instanceof Error ? err.message : String(err);
|
|
10495
|
+
tac.logger.error(
|
|
9273
10496
|
{ err, conversation_id: session.conversationId },
|
|
9274
|
-
"Failed to
|
|
10497
|
+
"Failed to deliver handoff payload"
|
|
9275
10498
|
);
|
|
9276
|
-
|
|
9277
|
-
|
|
9278
|
-
|
|
9279
|
-
|
|
9280
|
-
handoffData: JSON.stringify(payload)
|
|
10499
|
+
return {
|
|
10500
|
+
status: "handoff_failed",
|
|
10501
|
+
channel: session.channel,
|
|
10502
|
+
error: message
|
|
9281
10503
|
};
|
|
9282
|
-
session.pendingHandoffData = pending;
|
|
9283
|
-
} else {
|
|
9284
|
-
try {
|
|
9285
|
-
await postStudioHandoff(payload, session, {
|
|
9286
|
-
handoffUrl: studioExecutionsUrl(flowSid),
|
|
9287
|
-
fromAddress: config.phoneNumber,
|
|
9288
|
-
apiKey: config.apiKey,
|
|
9289
|
-
apiSecret: config.apiSecret
|
|
9290
|
-
});
|
|
9291
|
-
} catch (err) {
|
|
9292
|
-
const message = err instanceof AxiosError ? err.message : err instanceof Error ? err.message : String(err);
|
|
9293
|
-
tac.logger.error(
|
|
9294
|
-
{ err, conversation_id: session.conversationId },
|
|
9295
|
-
"Failed to deliver handoff payload"
|
|
9296
|
-
);
|
|
9297
|
-
return {
|
|
9298
|
-
status: "handoff_failed",
|
|
9299
|
-
channel: session.channel,
|
|
9300
|
-
error: message
|
|
9301
|
-
};
|
|
9302
|
-
}
|
|
9303
10504
|
}
|
|
9304
10505
|
return { status: "handoff_initiated", channel: session.channel };
|
|
9305
10506
|
}
|
|
@@ -9400,9 +10601,9 @@ var TACServer = class {
|
|
|
9400
10601
|
webhookPaths
|
|
9401
10602
|
};
|
|
9402
10603
|
this.voiceChannel = config.voiceChannel ?? tac.getChannel("voice");
|
|
9403
|
-
if (this.voiceChannel && !tac.getConfig().
|
|
10604
|
+
if (this.voiceChannel && !tac.getConfig().voiceCallbackDomain) {
|
|
9404
10605
|
throw new Error(
|
|
9405
|
-
"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.)"
|
|
9406
10607
|
);
|
|
9407
10608
|
}
|
|
9408
10609
|
this.validateCallEventPaths();
|
|
@@ -9417,9 +10618,12 @@ var TACServer = class {
|
|
|
9417
10618
|
this.webhookChannels.push(this.voiceChannel);
|
|
9418
10619
|
}
|
|
9419
10620
|
this.webhookChannels.push(...this.messagingChannels);
|
|
10621
|
+
for (const channel of this.webhookChannels) {
|
|
10622
|
+
tac.registerChannel(channel);
|
|
10623
|
+
}
|
|
9420
10624
|
if (this.webhookChannels.length === 0) {
|
|
9421
10625
|
console.warn(
|
|
9422
|
-
"TACServer: No channels configured for webhook processing.
|
|
10626
|
+
"TACServer: No channels configured for webhook processing. Pass `voiceChannel` / `messagingChannels` to enable webhooks."
|
|
9423
10627
|
);
|
|
9424
10628
|
}
|
|
9425
10629
|
if (config.fastifyInstance) {
|
|
@@ -9799,6 +11003,6 @@ var TACServer = class {
|
|
|
9799
11003
|
}
|
|
9800
11004
|
};
|
|
9801
11005
|
|
|
9802
|
-
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 };
|
|
9803
11007
|
//# sourceMappingURL=index.js.map
|
|
9804
11008
|
//# sourceMappingURL=index.js.map
|