twilio-agent-connect 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -9
- package/dist/index.d.ts +253 -28
- package/dist/index.js +366 -67
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
package/dist/index.js
CHANGED
|
@@ -38,17 +38,64 @@ var voicePathSchema = (defaultPath) => z.preprocess((v) => {
|
|
|
38
38
|
}, z.string().startsWith("/", 'Path must start with "/"').default(defaultPath));
|
|
39
39
|
var CallEventKindSchema = z.enum(["status", "amd", "recording"]);
|
|
40
40
|
var CALL_EVENT_KINDS = CallEventKindSchema.options;
|
|
41
|
+
var RCS_SENDER_ID_REGEX = /^rcs:.+$/;
|
|
42
|
+
var RCS_SENDER_ID_MESSAGE = "RCS sender ID must be in format: rcs:<sender-id-or-phone> (e.g., rcs:brand_acme_agent or rcs:+1234567890)";
|
|
43
|
+
var WHATSAPP_NUMBER_REGEX = /^whatsapp:\+\d+$/;
|
|
44
|
+
var WHATSAPP_NUMBER_MESSAGE = "WhatsApp number must be in format: whatsapp:+1234567890";
|
|
45
|
+
function normalizeSenderPair(defaultValue, plural, options) {
|
|
46
|
+
const trimmedDefault = typeof defaultValue === "string" && defaultValue.trim().length > 0 ? defaultValue.trim() : void 0;
|
|
47
|
+
const cleaned = [];
|
|
48
|
+
for (const entry of plural) {
|
|
49
|
+
const trimmed = entry.trim();
|
|
50
|
+
if (trimmed && !cleaned.includes(trimmed)) {
|
|
51
|
+
cleaned.push(trimmed);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (trimmedDefault === void 0 && cleaned.length === 0) {
|
|
55
|
+
if (options.required) {
|
|
56
|
+
return {
|
|
57
|
+
default: void 0,
|
|
58
|
+
plural: [],
|
|
59
|
+
error: `At least one of \`${options.field}\` / \`${options.field}s\` must be set.`
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { default: void 0, plural: [] };
|
|
63
|
+
}
|
|
64
|
+
const resolvedDefault = trimmedDefault ?? cleaned[0];
|
|
65
|
+
const withoutDefault = cleaned.filter((a) => a !== resolvedDefault);
|
|
66
|
+
return { default: resolvedDefault, plural: [resolvedDefault, ...withoutDefault] };
|
|
67
|
+
}
|
|
41
68
|
var TACConfigSchema = z.object({
|
|
42
69
|
accountSid: z.string().min(1, "Twilio Account SID is required"),
|
|
43
70
|
authToken: z.string().min(1, "Twilio Auth Token is required"),
|
|
44
71
|
apiKey: z.string().min(1, "Twilio API Key is required"),
|
|
45
72
|
apiSecret: z.string().min(1, "Twilio API Secret is required"),
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Default Twilio phone number for Voice (inbound) and SMS. Optional if
|
|
75
|
+
* `phoneNumbers` is set; at least one of the two is required. After
|
|
76
|
+
* validation this is always populated and is a member of `phoneNumbers`.
|
|
77
|
+
*/
|
|
78
|
+
phoneNumber: z.string().min(1, "Twilio Phone Number is required").optional(),
|
|
79
|
+
/**
|
|
80
|
+
* Full set of Twilio phone numbers this instance serves for Voice and SMS
|
|
81
|
+
* (the inbound allowlist). Defaults to `[phoneNumber]` when omitted;
|
|
82
|
+
* `phoneNumber` is always included as the default sender.
|
|
83
|
+
*/
|
|
84
|
+
phoneNumbers: z.array(z.string().min(1, "Twilio Phone Number is required")).optional(),
|
|
85
|
+
/** Default Twilio RCS Sender ID. Optional; symmetric with `rcsSenderIds`. */
|
|
86
|
+
rcsSenderId: z.string().trim().regex(RCS_SENDER_ID_REGEX, RCS_SENDER_ID_MESSAGE).optional(),
|
|
87
|
+
/**
|
|
88
|
+
* Full set of Twilio RCS Sender IDs this instance serves. Defaults to
|
|
89
|
+
* `[rcsSenderId]` when a default is set.
|
|
90
|
+
*/
|
|
91
|
+
rcsSenderIds: z.array(z.string().trim().regex(RCS_SENDER_ID_REGEX, RCS_SENDER_ID_MESSAGE)).optional(),
|
|
92
|
+
/** Default Twilio WhatsApp number. Optional; symmetric with `whatsappNumbers`. */
|
|
93
|
+
whatsappNumber: z.string().trim().regex(WHATSAPP_NUMBER_REGEX, WHATSAPP_NUMBER_MESSAGE).optional(),
|
|
94
|
+
/**
|
|
95
|
+
* Full set of Twilio WhatsApp numbers this instance serves. Defaults to
|
|
96
|
+
* `[whatsappNumber]` when a default is set.
|
|
97
|
+
*/
|
|
98
|
+
whatsappNumbers: z.array(z.string().trim().regex(WHATSAPP_NUMBER_REGEX, WHATSAPP_NUMBER_MESSAGE)).optional(),
|
|
52
99
|
memoryConfig: TwilioMemoryConfigSchema.prefault({}),
|
|
53
100
|
conversationConfigurationId: z.string().regex(/^conv_configuration_[0-9a-z]{26}$/, "Invalid Conversation Configuration ID format").optional(),
|
|
54
101
|
/**
|
|
@@ -109,6 +156,33 @@ var TACConfigSchema = z.object({
|
|
|
109
156
|
/^FW[0-9a-f]{32}$/,
|
|
110
157
|
"Invalid Studio Flow SID format (expected FW followed by 32 hex chars)"
|
|
111
158
|
).optional()
|
|
159
|
+
}).transform((data, ctx) => {
|
|
160
|
+
const phone = normalizeSenderPair(data.phoneNumber, data.phoneNumbers ?? [], {
|
|
161
|
+
required: true,
|
|
162
|
+
field: "phoneNumber"
|
|
163
|
+
});
|
|
164
|
+
if (phone.error) {
|
|
165
|
+
ctx.addIssue({ code: "custom", message: phone.error, path: ["phoneNumber"] });
|
|
166
|
+
return z.NEVER;
|
|
167
|
+
}
|
|
168
|
+
const rcs = normalizeSenderPair(data.rcsSenderId, data.rcsSenderIds ?? [], {
|
|
169
|
+
required: false,
|
|
170
|
+
field: "rcsSenderId"
|
|
171
|
+
});
|
|
172
|
+
const whatsapp = normalizeSenderPair(data.whatsappNumber, data.whatsappNumbers ?? [], {
|
|
173
|
+
required: false,
|
|
174
|
+
field: "whatsappNumber"
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
...data,
|
|
178
|
+
// Guaranteed populated: the required check above returned early otherwise.
|
|
179
|
+
phoneNumber: phone.default,
|
|
180
|
+
phoneNumbers: phone.plural,
|
|
181
|
+
rcsSenderId: rcs.default,
|
|
182
|
+
rcsSenderIds: rcs.plural,
|
|
183
|
+
whatsappNumber: whatsapp.default,
|
|
184
|
+
whatsappNumbers: whatsapp.plural
|
|
185
|
+
};
|
|
112
186
|
});
|
|
113
187
|
var EnvironmentVariables = {
|
|
114
188
|
TWILIO_ACCOUNT_SID: "TWILIO_ACCOUNT_SID",
|
|
@@ -116,8 +190,11 @@ var EnvironmentVariables = {
|
|
|
116
190
|
TWILIO_API_KEY: "TWILIO_API_KEY",
|
|
117
191
|
TWILIO_API_SECRET: "TWILIO_API_SECRET",
|
|
118
192
|
TWILIO_PHONE_NUMBER: "TWILIO_PHONE_NUMBER",
|
|
193
|
+
TWILIO_PHONE_NUMBERS: "TWILIO_PHONE_NUMBERS",
|
|
119
194
|
TWILIO_RCS_SENDER_ID: "TWILIO_RCS_SENDER_ID",
|
|
195
|
+
TWILIO_RCS_SENDER_IDS: "TWILIO_RCS_SENDER_IDS",
|
|
120
196
|
TWILIO_WHATSAPP_NUMBER: "TWILIO_WHATSAPP_NUMBER",
|
|
197
|
+
TWILIO_WHATSAPP_NUMBERS: "TWILIO_WHATSAPP_NUMBERS",
|
|
121
198
|
TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: "TWILIO_MEMORY_PROFILE_TRAIT_GROUPS",
|
|
122
199
|
TWILIO_MEMORY_OBSERVATIONS_LIMIT: "TWILIO_MEMORY_OBSERVATIONS_LIMIT",
|
|
123
200
|
TWILIO_MEMORY_SUMMARIES_LIMIT: "TWILIO_MEMORY_SUMMARIES_LIMIT",
|
|
@@ -348,7 +425,14 @@ var ConversationConfigurationSchema = z.object({
|
|
|
348
425
|
var InitiateMessagingConversationOptionsSchema = z.object({
|
|
349
426
|
to: z.string().min(1, "Recipient address is required"),
|
|
350
427
|
message: z.string().min(1, "Initial message is required"),
|
|
351
|
-
metadata: z.record(z.string(), z.unknown()).optional()
|
|
428
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
429
|
+
/**
|
|
430
|
+
* Sender address to send from. Must be one of the channel's configured
|
|
431
|
+
* senders (`config.phoneNumbers` / `rcsSenderIds` / `whatsappNumbers`). When
|
|
432
|
+
* omitted, the channel default is used (`config.phoneNumber` / `rcsSenderId` /
|
|
433
|
+
* `whatsappNumber`).
|
|
434
|
+
*/
|
|
435
|
+
from: z.string().min(1).optional()
|
|
352
436
|
});
|
|
353
437
|
|
|
354
438
|
// packages/core/src/types/tac.ts
|
|
@@ -1270,6 +1354,7 @@ function callOptionsToCreateParams(options) {
|
|
|
1270
1354
|
}
|
|
1271
1355
|
var InitiateVoiceConversationOptionsBase = z.object({
|
|
1272
1356
|
to: z.string().min(1, "Recipient phone number is required"),
|
|
1357
|
+
from: z.string().min(1).optional(),
|
|
1273
1358
|
websocketUrl: z.url().optional(),
|
|
1274
1359
|
twimlOptions: VoiceTwiMLOptionsConversationRelaySchema.optional(),
|
|
1275
1360
|
callOptions: CallOptionsSchema.optional()
|
|
@@ -1435,9 +1520,24 @@ var TACConfig = class _TACConfig {
|
|
|
1435
1520
|
authToken;
|
|
1436
1521
|
apiKey;
|
|
1437
1522
|
apiSecret;
|
|
1523
|
+
/**
|
|
1524
|
+
* Default Twilio phone number for Voice and SMS — the sender used for
|
|
1525
|
+
* outbound when a call does not specify `from`. Always populated and always a
|
|
1526
|
+
* member of {@link phoneNumbers}.
|
|
1527
|
+
*/
|
|
1438
1528
|
phoneNumber;
|
|
1529
|
+
/**
|
|
1530
|
+
* Full set of Twilio phone numbers this instance serves for Voice and SMS
|
|
1531
|
+
* (the inbound allowlist). Always includes {@link phoneNumber} as the first,
|
|
1532
|
+
* default sender.
|
|
1533
|
+
*/
|
|
1534
|
+
phoneNumbers;
|
|
1439
1535
|
rcsSenderId;
|
|
1536
|
+
/** Full set of RCS Sender IDs this instance serves; the default is first. */
|
|
1537
|
+
rcsSenderIds;
|
|
1440
1538
|
whatsappNumber;
|
|
1539
|
+
/** Full set of WhatsApp numbers this instance serves; the default is first. */
|
|
1540
|
+
whatsappNumbers;
|
|
1441
1541
|
memoryConfig;
|
|
1442
1542
|
conversationConfigurationId;
|
|
1443
1543
|
voicePublicDomain;
|
|
@@ -1466,12 +1566,15 @@ var TACConfig = class _TACConfig {
|
|
|
1466
1566
|
this.apiKey = validatedConfig.apiKey;
|
|
1467
1567
|
this.apiSecret = validatedConfig.apiSecret;
|
|
1468
1568
|
this.phoneNumber = validatedConfig.phoneNumber;
|
|
1569
|
+
this.phoneNumbers = validatedConfig.phoneNumbers;
|
|
1469
1570
|
if (validatedConfig.rcsSenderId) {
|
|
1470
1571
|
this.rcsSenderId = validatedConfig.rcsSenderId;
|
|
1471
1572
|
}
|
|
1573
|
+
this.rcsSenderIds = validatedConfig.rcsSenderIds;
|
|
1472
1574
|
if (validatedConfig.whatsappNumber) {
|
|
1473
1575
|
this.whatsappNumber = validatedConfig.whatsappNumber;
|
|
1474
1576
|
}
|
|
1577
|
+
this.whatsappNumbers = validatedConfig.whatsappNumbers;
|
|
1475
1578
|
this.memoryConfig = validatedConfig.memoryConfig;
|
|
1476
1579
|
if (validatedConfig.conversationConfigurationId) {
|
|
1477
1580
|
this.conversationConfigurationId = validatedConfig.conversationConfigurationId;
|
|
@@ -1503,10 +1606,13 @@ var TACConfig = class _TACConfig {
|
|
|
1503
1606
|
* - TWILIO_AUTH_TOKEN: Twilio Auth Token for API authentication
|
|
1504
1607
|
* - TWILIO_API_KEY: Twilio API Key SID (starts with SK)
|
|
1505
1608
|
* - TWILIO_API_SECRET: Twilio API Secret for API Key authentication
|
|
1506
|
-
* - TWILIO_PHONE_NUMBER
|
|
1609
|
+
* - TWILIO_PHONE_NUMBER and/or TWILIO_PHONE_NUMBERS: at least one is required.
|
|
1610
|
+
* Phone number(s) for voice and SMS channels — see **Multi-Value Senders** below.
|
|
1507
1611
|
*
|
|
1508
1612
|
* Optional environment variables:
|
|
1509
|
-
* - TWILIO_WHATSAPP_NUMBER: WhatsApp number for
|
|
1613
|
+
* - TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS: WhatsApp number(s) for the
|
|
1614
|
+
* WhatsApp channel (e.g., 'whatsapp:+1234567890')
|
|
1615
|
+
* - TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS: RCS Sender ID(s) for the RCS channel
|
|
1510
1616
|
* - TWILIO_CONVERSATION_CONFIGURATION_ID: Conversation Orchestrator configuration ID (enables orchestrated mode)
|
|
1511
1617
|
* - 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')
|
|
1512
1618
|
* - TWILIO_VOICE_WEBSOCKET_PATH: Path for the voice WebSocket (default: /ws)
|
|
@@ -1514,7 +1620,16 @@ var TACConfig = class _TACConfig {
|
|
|
1514
1620
|
* - TWILIO_VOICE_CALL_EVENT_PATH: Base path for the call-event callbacks — status, async AMD, recording (default: /twilio/call-events)
|
|
1515
1621
|
* - TWILIO_REGION: Twilio region subdomain for API routing (e.g. transforms base URLs to `https://{product}.{region}.twilio.com`)
|
|
1516
1622
|
* - TWILIO_STUDIO_HANDOFF_FLOW_SID: Studio Flow SID used by createStudioHandoffTool for human handoff
|
|
1517
|
-
*
|
|
1623
|
+
*
|
|
1624
|
+
* Multi-Value Senders:
|
|
1625
|
+
* - Each singular env var (TWILIO_PHONE_NUMBER, TWILIO_RCS_SENDER_ID,
|
|
1626
|
+
* TWILIO_WHATSAPP_NUMBER) pairs with a plural, comma-separated one
|
|
1627
|
+
* (TWILIO_PHONE_NUMBERS, TWILIO_RCS_SENDER_IDS, TWILIO_WHATSAPP_NUMBERS),
|
|
1628
|
+
* e.g. `TWILIO_PHONE_NUMBERS=+1555,+1444`. Whichever side is set back-fills
|
|
1629
|
+
* the other: the singular becomes the default sender and the plural the full
|
|
1630
|
+
* allowlist. Entries are whitespace-trimmed and de-duplicated, with the
|
|
1631
|
+
* default kept first. `phoneNumber` requires at least one of the two; the RCS
|
|
1632
|
+
* and WhatsApp pairs stay optional.
|
|
1518
1633
|
*
|
|
1519
1634
|
* Memory Configuration (defaults defined in TwilioMemoryConfigSchema):
|
|
1520
1635
|
* - TWILIO_MEMORY_PROFILE_TRAIT_GROUPS: Trait groups to include (comma-separated, e.g., "Contact,Preferences")
|
|
@@ -1541,8 +1656,7 @@ var TACConfig = class _TACConfig {
|
|
|
1541
1656
|
{ key: EnvironmentVariables.TWILIO_ACCOUNT_SID, name: "TWILIO_ACCOUNT_SID" },
|
|
1542
1657
|
{ key: EnvironmentVariables.TWILIO_AUTH_TOKEN, name: "TWILIO_AUTH_TOKEN" },
|
|
1543
1658
|
{ 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" }
|
|
1659
|
+
{ key: EnvironmentVariables.TWILIO_API_SECRET, name: "TWILIO_API_SECRET" }
|
|
1546
1660
|
];
|
|
1547
1661
|
for (const { key, name } of requiredVars) {
|
|
1548
1662
|
if (!process.env[key]) {
|
|
@@ -1582,14 +1696,18 @@ var TACConfig = class _TACConfig {
|
|
|
1582
1696
|
}
|
|
1583
1697
|
return parsed;
|
|
1584
1698
|
};
|
|
1699
|
+
const splitCsvEnv = (value) => (value ?? "").split(",").map((part) => part.trim()).filter((part) => part.length > 0);
|
|
1585
1700
|
const rawConfig = {
|
|
1586
1701
|
accountSid: process.env[EnvironmentVariables.TWILIO_ACCOUNT_SID],
|
|
1587
1702
|
authToken: process.env[EnvironmentVariables.TWILIO_AUTH_TOKEN],
|
|
1588
1703
|
apiKey: process.env[EnvironmentVariables.TWILIO_API_KEY],
|
|
1589
1704
|
apiSecret: process.env[EnvironmentVariables.TWILIO_API_SECRET],
|
|
1590
|
-
phoneNumber: process.env[EnvironmentVariables.TWILIO_PHONE_NUMBER],
|
|
1705
|
+
phoneNumber: process.env[EnvironmentVariables.TWILIO_PHONE_NUMBER] || void 0,
|
|
1706
|
+
phoneNumbers: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_PHONE_NUMBERS]),
|
|
1591
1707
|
rcsSenderId: process.env[EnvironmentVariables.TWILIO_RCS_SENDER_ID],
|
|
1708
|
+
rcsSenderIds: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_RCS_SENDER_IDS]),
|
|
1592
1709
|
whatsappNumber: process.env[EnvironmentVariables.TWILIO_WHATSAPP_NUMBER] || void 0,
|
|
1710
|
+
whatsappNumbers: splitCsvEnv(process.env[EnvironmentVariables.TWILIO_WHATSAPP_NUMBERS]),
|
|
1593
1711
|
memoryConfig: {
|
|
1594
1712
|
traitGroups,
|
|
1595
1713
|
observationsLimit: parseIntEnv(
|
|
@@ -1765,7 +1883,7 @@ function createLogger(options) {
|
|
|
1765
1883
|
// package.json
|
|
1766
1884
|
var package_default = {
|
|
1767
1885
|
name: "twilio-agent-connect",
|
|
1768
|
-
version: "2.
|
|
1886
|
+
version: "2.5.0",
|
|
1769
1887
|
description: "Twilio Agent Connect - A TypeScript framework for building intelligent agents",
|
|
1770
1888
|
type: "module",
|
|
1771
1889
|
main: "./dist/index.js",
|
|
@@ -1787,13 +1905,14 @@ var package_default = {
|
|
|
1787
1905
|
test: "vitest --run",
|
|
1788
1906
|
"test:watch": "vitest",
|
|
1789
1907
|
"test:coverage": "vitest --coverage",
|
|
1790
|
-
lint: "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts'",
|
|
1791
|
-
"lint:fix": "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' --fix",
|
|
1908
|
+
lint: "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/twilio-setup/src/**/*.ts'",
|
|
1909
|
+
"lint:fix": "eslint 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/twilio-setup/src/**/*.ts' --fix",
|
|
1792
1910
|
format: "prettier --write 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/**/*.ts'",
|
|
1793
1911
|
"format:check": "prettier --check 'packages/*/src/**/*.ts' 'src/**/*.ts' 'getting_started/**/*.ts'",
|
|
1794
|
-
typecheck: "tsc --noEmit",
|
|
1912
|
+
typecheck: "tsc --noEmit && tsc --noEmit -p getting_started/twilio-setup",
|
|
1795
1913
|
docs: "typedoc",
|
|
1796
1914
|
"docs:watch": "typedoc --watch",
|
|
1915
|
+
setup: "tsx getting_started/twilio-setup/src/index.ts | pino-pretty",
|
|
1797
1916
|
"example:getting-started": "cd getting_started/examples/openai && npm install && npm run dev",
|
|
1798
1917
|
"example:chat": "cd getting_started/examples/chat && npm install && npm run dev"
|
|
1799
1918
|
},
|
|
@@ -1819,9 +1938,11 @@ var package_default = {
|
|
|
1819
1938
|
"axios-mock-adapter": "^2.1.0",
|
|
1820
1939
|
eslint: "^9.0.0",
|
|
1821
1940
|
globals: "^15.0.0",
|
|
1941
|
+
"pino-pretty": "^13.0.0",
|
|
1822
1942
|
prettier: "^3.0.0",
|
|
1823
1943
|
rimraf: "^5.0.0",
|
|
1824
1944
|
tsup: "^8.5.1",
|
|
1945
|
+
tsx: "^4.19.2",
|
|
1825
1946
|
typedoc: "^0.28.20",
|
|
1826
1947
|
"typedoc-material-theme": "^1.4.1",
|
|
1827
1948
|
typescript: "^5.0.0",
|
|
@@ -2986,11 +3107,24 @@ var TAC = class _TAC {
|
|
|
2986
3107
|
}
|
|
2987
3108
|
}
|
|
2988
3109
|
/**
|
|
2989
|
-
* Register a channel with the framework
|
|
3110
|
+
* Register a channel with the framework, routing its inbound messages to the
|
|
3111
|
+
* {@link TAC.onMessageReady} callback and shutting it down with {@link TAC.shutdown}.
|
|
3112
|
+
*
|
|
3113
|
+
* `TACServer` registers the channels passed to it (`voiceChannel` /
|
|
3114
|
+
* `messagingChannels`), so you only need this when wiring channels into your
|
|
3115
|
+
* own web framework instead of `TACServer`.
|
|
3116
|
+
*
|
|
3117
|
+
* Only one channel per type is registered: registering a different instance
|
|
3118
|
+
* of the same type shuts down and replaces the existing one. Registering the
|
|
3119
|
+
* same instance again is a no-op.
|
|
2990
3120
|
*/
|
|
2991
3121
|
registerChannel(channel) {
|
|
2992
|
-
this.logger.info({ channel: channel.channelType }, "Registering channel");
|
|
2993
3122
|
const existingChannel = this.channels.get(channel.channelType);
|
|
3123
|
+
if (existingChannel === channel) {
|
|
3124
|
+
this.logger.debug({ channel: channel.channelType }, "Channel already registered");
|
|
3125
|
+
return;
|
|
3126
|
+
}
|
|
3127
|
+
this.logger.info({ channel: channel.channelType }, "Registering channel");
|
|
2994
3128
|
if (existingChannel) {
|
|
2995
3129
|
this.logger.info({ channel: channel.channelType }, "Replacing existing channel registration");
|
|
2996
3130
|
existingChannel.shutdown();
|
|
@@ -3174,7 +3308,24 @@ var TAC = class _TAC {
|
|
|
3174
3308
|
this.messageReadyCallback = callback;
|
|
3175
3309
|
}
|
|
3176
3310
|
/**
|
|
3177
|
-
* Register callback
|
|
3311
|
+
* Register callback invoked when the caller interrupts the agent on a voice call.
|
|
3312
|
+
*
|
|
3313
|
+
* Currently fired by the ConversationRelay voice provider. The callback receives
|
|
3314
|
+
* `conversationId`, the call's `session`, `utteranceUntilInterrupt` (the text the
|
|
3315
|
+
* agent had spoken when interrupted) and `durationUntilInterruptMs` (how long it
|
|
3316
|
+
* had been speaking); either of the last two may be `undefined` if
|
|
3317
|
+
* ConversationRelay doesn't report it. Errors thrown by the callback are logged,
|
|
3318
|
+
* not rethrown.
|
|
3319
|
+
*
|
|
3320
|
+
* @example
|
|
3321
|
+
* ```typescript
|
|
3322
|
+
* tac.onInterrupt(({ conversationId, utteranceUntilInterrupt, durationUntilInterruptMs }) => {
|
|
3323
|
+
* console.log(
|
|
3324
|
+
* `${conversationId} interrupted after ${durationUntilInterruptMs} ms: ` +
|
|
3325
|
+
* JSON.stringify(utteranceUntilInterrupt)
|
|
3326
|
+
* );
|
|
3327
|
+
* });
|
|
3328
|
+
* ```
|
|
3178
3329
|
*/
|
|
3179
3330
|
onInterrupt(callback) {
|
|
3180
3331
|
this.interruptCallback = callback;
|
|
@@ -3394,6 +3545,22 @@ var TAC = class _TAC {
|
|
|
3394
3545
|
}
|
|
3395
3546
|
};
|
|
3396
3547
|
|
|
3548
|
+
// packages/core/src/util/outbound-sender.ts
|
|
3549
|
+
function resolveOutboundSender(requested, options) {
|
|
3550
|
+
if (requested !== void 0) {
|
|
3551
|
+
if (!options.allowlist.includes(requested)) {
|
|
3552
|
+
throw new Error(
|
|
3553
|
+
`from '${requested}' is not a configured ${options.channel} sender; configured senders: ${JSON.stringify(options.allowlist)}`
|
|
3554
|
+
);
|
|
3555
|
+
}
|
|
3556
|
+
return requested;
|
|
3557
|
+
}
|
|
3558
|
+
if (options.default === void 0) {
|
|
3559
|
+
throw new Error(`No default sender configured for ${options.channel}.`);
|
|
3560
|
+
}
|
|
3561
|
+
return options.default;
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3397
3564
|
// packages/core/src/channels/base.ts
|
|
3398
3565
|
var BaseChannel = class {
|
|
3399
3566
|
tac;
|
|
@@ -3428,6 +3595,16 @@ var BaseChannel = class {
|
|
|
3428
3595
|
this.maxTrackedTokens = capacity;
|
|
3429
3596
|
this.processedWebhookTokens = /* @__PURE__ */ new Set();
|
|
3430
3597
|
}
|
|
3598
|
+
/**
|
|
3599
|
+
* Resolve the outbound sender address for this channel.
|
|
3600
|
+
*
|
|
3601
|
+
* `requested` (the caller's `options.from`) wins when it is one of the
|
|
3602
|
+
* channel's configured senders; otherwise throws. When omitted, the channel
|
|
3603
|
+
* default is used.
|
|
3604
|
+
*/
|
|
3605
|
+
resolveOutboundFrom(requested, options) {
|
|
3606
|
+
return resolveOutboundSender(requested, { ...options, channel: this.channelType });
|
|
3607
|
+
}
|
|
3431
3608
|
/**
|
|
3432
3609
|
* Register event callbacks
|
|
3433
3610
|
*/
|
|
@@ -3771,6 +3948,20 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3771
3948
|
* participant to CUSTOMER. Subclasses override to opt out (e.g. chat).
|
|
3772
3949
|
*/
|
|
3773
3950
|
reconcileCustomerType = true;
|
|
3951
|
+
/**
|
|
3952
|
+
* Phone-like channels derive the agent address from the inbound webhook's
|
|
3953
|
+
* recipient (which of TAC's numbers was messaged). Chat uses a single identity
|
|
3954
|
+
* and opts out, keeping the default-address path.
|
|
3955
|
+
*/
|
|
3956
|
+
deriveInboundAgentFromRecipients = true;
|
|
3957
|
+
/**
|
|
3958
|
+
* The uppercase Conversation Orchestrator channel name for this channel (e.g.
|
|
3959
|
+
* `"SMS"`, `"RCS"`), used to filter webhook recipients and participant
|
|
3960
|
+
* addresses. Derived from {@link channelType}.
|
|
3961
|
+
*/
|
|
3962
|
+
getChannelName() {
|
|
3963
|
+
return this.channelType.toUpperCase();
|
|
3964
|
+
}
|
|
3774
3965
|
constructor(tac, config) {
|
|
3775
3966
|
super(tac, config);
|
|
3776
3967
|
if (!tac.isOrchestratorEnabled()) {
|
|
@@ -3951,6 +4142,39 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3951
4142
|
);
|
|
3952
4143
|
return;
|
|
3953
4144
|
}
|
|
4145
|
+
const channelName = this.getChannelName();
|
|
4146
|
+
let inboundAgentAddress;
|
|
4147
|
+
if (this.deriveInboundAgentFromRecipients) {
|
|
4148
|
+
const channelRecipients = (payload.data?.recipients ?? []).filter(
|
|
4149
|
+
(r) => r.channel === channelName
|
|
4150
|
+
);
|
|
4151
|
+
if (channelRecipients.length > 0) {
|
|
4152
|
+
const matched = channelRecipients.find(
|
|
4153
|
+
(r) => r.address !== void 0 && this.isDefaultAgentAddress(r.address)
|
|
4154
|
+
)?.address;
|
|
4155
|
+
if (matched === void 0) {
|
|
4156
|
+
const maskedRecipients = channelRecipients.map((r) => maskAddress(r.address ?? ""));
|
|
4157
|
+
const error = new Error("Inbound message to an unconfigured agent address; dropped");
|
|
4158
|
+
error.name = "UnconfiguredAgentAddressError";
|
|
4159
|
+
this.logger.error(
|
|
4160
|
+
{
|
|
4161
|
+
conversation_id: conversationId,
|
|
4162
|
+
channel: channelName,
|
|
4163
|
+
recipients: maskedRecipients
|
|
4164
|
+
},
|
|
4165
|
+
"Inbound message addressed to a number not in this channel's configured set; dropping"
|
|
4166
|
+
);
|
|
4167
|
+
this.handleError(error, {
|
|
4168
|
+
conversation_id: conversationId,
|
|
4169
|
+
channel: channelName,
|
|
4170
|
+
dropped_inbound: true,
|
|
4171
|
+
recipients: maskedRecipients
|
|
4172
|
+
});
|
|
4173
|
+
return;
|
|
4174
|
+
}
|
|
4175
|
+
inboundAgentAddress = { channel: channelName, address: matched };
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
3954
4178
|
if (!this.isConversationActive(conversationId)) {
|
|
3955
4179
|
this.logger.debug({ conversation_id: conversationId }, "Starting new conversation");
|
|
3956
4180
|
this.startConversation(conversationId, profileId ?? void 0, payload.data?.serviceId);
|
|
@@ -3991,7 +4215,7 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
3991
4215
|
session.metadata.lastCommunicationId = communicationId;
|
|
3992
4216
|
}
|
|
3993
4217
|
if (!session.aiAgentInfo) {
|
|
3994
|
-
const resolved = await this.reconcileParticipants(conversationId);
|
|
4218
|
+
const resolved = await this.reconcileParticipants(conversationId, inboundAgentAddress);
|
|
3995
4219
|
if (!resolved) {
|
|
3996
4220
|
const error = new Error(
|
|
3997
4221
|
`Participant reconciliation failed for conversation ${conversationId}; inbound message dropped because no sendable participants could be resolved.`
|
|
@@ -4006,9 +4230,9 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4006
4230
|
return;
|
|
4007
4231
|
}
|
|
4008
4232
|
const [agentParticipant, customerParticipant] = resolved;
|
|
4009
|
-
const
|
|
4233
|
+
const agentAddrValue = inboundAgentAddress !== void 0 ? inboundAgentAddress.address : agentParticipant.addresses.find((a) => a.channel === channelName)?.address;
|
|
4010
4234
|
session.aiAgentInfo = {
|
|
4011
|
-
address:
|
|
4235
|
+
address: agentAddrValue ?? this.getAgentAddress(conversationId).address,
|
|
4012
4236
|
participantId: agentParticipant.id
|
|
4013
4237
|
};
|
|
4014
4238
|
if (customerParticipant && session.authorInfo) {
|
|
@@ -4093,13 +4317,15 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4093
4317
|
* (via `session.authorInfo.participantId`), so promoting some other
|
|
4094
4318
|
* `UNKNOWN` CHAT participant could pick the wrong recipient.
|
|
4095
4319
|
*
|
|
4320
|
+
* @param agentAddress - The agent address for this conversation, normally
|
|
4321
|
+
* derived from the inbound webhook's recipient. When omitted, it is resolved
|
|
4322
|
+
* from a participant scan (phone-like channels) or the channel default.
|
|
4096
4323
|
* @returns `[agent, customerOrNull]` on success. `customer` is `null` when
|
|
4097
4324
|
* `reconcileCustomerType` is `false`. `null` overall when either the agent
|
|
4098
4325
|
* or the customer cannot be resolved — the caller treats `null` as a hard
|
|
4099
4326
|
* stop and skips the message-ready callback.
|
|
4100
4327
|
*/
|
|
4101
|
-
async reconcileParticipants(conversationId) {
|
|
4102
|
-
const agentAddress = this.getAgentAddress(conversationId);
|
|
4328
|
+
async reconcileParticipants(conversationId, agentAddress) {
|
|
4103
4329
|
let participants;
|
|
4104
4330
|
try {
|
|
4105
4331
|
participants = await this.conversationClient.listParticipants(conversationId);
|
|
@@ -4110,7 +4336,10 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4110
4336
|
);
|
|
4111
4337
|
return null;
|
|
4112
4338
|
}
|
|
4113
|
-
const channel =
|
|
4339
|
+
const channel = this.getChannelName();
|
|
4340
|
+
if (agentAddress === void 0) {
|
|
4341
|
+
agentAddress = this.deriveInboundAgentFromRecipients ? this.fallbackAgentAddress(conversationId, participants, channel) : this.getAgentAddress(conversationId);
|
|
4342
|
+
}
|
|
4114
4343
|
const ownsAgentAddress = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel && a.address === agentAddress.address);
|
|
4115
4344
|
const matchesChannel = (p) => Array.isArray(p.addresses) && p.addresses.some((a) => a.channel === channel);
|
|
4116
4345
|
let agentCandidate = participants.find(ownsAgentAddress);
|
|
@@ -4163,6 +4392,28 @@ var MessagingChannel = class extends BaseChannel {
|
|
|
4163
4392
|
);
|
|
4164
4393
|
return null;
|
|
4165
4394
|
}
|
|
4395
|
+
/**
|
|
4396
|
+
* Resolve the agent address when the inbound webhook carried no recipient.
|
|
4397
|
+
*
|
|
4398
|
+
* Scans the conversation's participants for any of TAC's configured addresses
|
|
4399
|
+
* on this channel; falls back to the channel default when none is present.
|
|
4400
|
+
* Defensive path — the primary source is the webhook.
|
|
4401
|
+
*/
|
|
4402
|
+
fallbackAgentAddress(conversationId, participants, channel) {
|
|
4403
|
+
const owned = participants.flatMap((p) => p.addresses).find((a) => a.channel === channel && this.isDefaultAgentAddress(a.address))?.address;
|
|
4404
|
+
if (owned !== void 0) {
|
|
4405
|
+
this.logger.warn(
|
|
4406
|
+
{ conversation_id: conversationId, channel },
|
|
4407
|
+
"Inbound webhook had no channel recipient; using owned participant address from participant scan"
|
|
4408
|
+
);
|
|
4409
|
+
return { channel, address: owned };
|
|
4410
|
+
}
|
|
4411
|
+
this.logger.warn(
|
|
4412
|
+
{ conversation_id: conversationId, channel },
|
|
4413
|
+
"Inbound webhook had no channel recipient and no owned participant; using default agent address"
|
|
4414
|
+
);
|
|
4415
|
+
return this.getAgentAddress(conversationId);
|
|
4416
|
+
}
|
|
4166
4417
|
/**
|
|
4167
4418
|
* Find or mint a Conversation Memory profile for a customer being promoted from UNKNOWN.
|
|
4168
4419
|
*
|
|
@@ -4430,7 +4681,7 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4430
4681
|
return "sms";
|
|
4431
4682
|
}
|
|
4432
4683
|
isDefaultAgentAddress(authorAddress) {
|
|
4433
|
-
return
|
|
4684
|
+
return this.config.phoneNumbers.includes(authorAddress);
|
|
4434
4685
|
}
|
|
4435
4686
|
getAgentAddress(_conversationId) {
|
|
4436
4687
|
return { channel: "SMS", address: this.config.phoneNumber };
|
|
@@ -4518,7 +4769,8 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4518
4769
|
*
|
|
4519
4770
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4520
4771
|
* agent participants, then sends the initial message via the Actions API.
|
|
4521
|
-
*
|
|
4772
|
+
* Uses `options.from` when provided (must be one of the configured phone
|
|
4773
|
+
* numbers), otherwise falls back to the default `config.phoneNumber`.
|
|
4522
4774
|
*/
|
|
4523
4775
|
async initiateOutboundConversation(options) {
|
|
4524
4776
|
const validated = InitiateMessagingConversationOptionsSchema.parse(options);
|
|
@@ -4529,7 +4781,10 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4529
4781
|
return this.initiateOutboundMessagingConversation({
|
|
4530
4782
|
channel: "SMS",
|
|
4531
4783
|
to: validated.to,
|
|
4532
|
-
from: this.
|
|
4784
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
4785
|
+
allowlist: this.config.phoneNumbers,
|
|
4786
|
+
default: this.config.phoneNumber
|
|
4787
|
+
}),
|
|
4533
4788
|
message: validated.message,
|
|
4534
4789
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4535
4790
|
});
|
|
@@ -4540,9 +4795,9 @@ var SMSChannel = class extends MessagingChannel {
|
|
|
4540
4795
|
var RCSChannel = class extends MessagingChannel {
|
|
4541
4796
|
constructor(tac, config) {
|
|
4542
4797
|
super(tac, config);
|
|
4543
|
-
if (
|
|
4798
|
+
if (this.config.rcsSenderIds.length === 0) {
|
|
4544
4799
|
throw new Error(
|
|
4545
|
-
"rcsSenderId is required for RCS channel.
|
|
4800
|
+
"rcsSenderId(s) is required for RCS channel. Set TWILIO_RCS_SENDER_ID / TWILIO_RCS_SENDER_IDS or provide rcsSenderId / rcsSenderIds in TACConfig."
|
|
4546
4801
|
);
|
|
4547
4802
|
}
|
|
4548
4803
|
}
|
|
@@ -4550,7 +4805,7 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4550
4805
|
return "rcs";
|
|
4551
4806
|
}
|
|
4552
4807
|
isDefaultAgentAddress(authorAddress) {
|
|
4553
|
-
return
|
|
4808
|
+
return this.config.rcsSenderIds.includes(authorAddress);
|
|
4554
4809
|
}
|
|
4555
4810
|
getAgentAddress(_conversationId) {
|
|
4556
4811
|
if (!this.config.rcsSenderId) {
|
|
@@ -4641,13 +4896,11 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4641
4896
|
*
|
|
4642
4897
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4643
4898
|
* agent participants, then sends the initial message via the Actions API.
|
|
4644
|
-
*
|
|
4899
|
+
* Uses `options.from` when provided (must be one of the configured RCS
|
|
4900
|
+
* senders), otherwise falls back to the default `config.rcsSenderId`.
|
|
4645
4901
|
*/
|
|
4646
4902
|
async initiateOutboundConversation(options) {
|
|
4647
4903
|
const validated = InitiateMessagingConversationOptionsSchema.parse(options);
|
|
4648
|
-
if (!this.config.rcsSenderId) {
|
|
4649
|
-
throw new Error("rcsSenderId is required for RCS channel.");
|
|
4650
|
-
}
|
|
4651
4904
|
this.logger.info(
|
|
4652
4905
|
{ to: maskAddress(validated.to), message_length: validated.message.length },
|
|
4653
4906
|
"Initiating outbound RCS conversation"
|
|
@@ -4655,7 +4908,10 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4655
4908
|
return this.initiateOutboundMessagingConversation({
|
|
4656
4909
|
channel: "RCS",
|
|
4657
4910
|
to: validated.to,
|
|
4658
|
-
from: this.
|
|
4911
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
4912
|
+
allowlist: this.config.rcsSenderIds,
|
|
4913
|
+
default: this.config.rcsSenderId
|
|
4914
|
+
}),
|
|
4659
4915
|
message: validated.message,
|
|
4660
4916
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4661
4917
|
});
|
|
@@ -4664,16 +4920,19 @@ var RCSChannel = class extends MessagingChannel {
|
|
|
4664
4920
|
|
|
4665
4921
|
// packages/core/src/channels/whatsapp.ts
|
|
4666
4922
|
var WhatsAppChannel = class extends MessagingChannel {
|
|
4923
|
+
constructor(tac, config) {
|
|
4924
|
+
super(tac, config);
|
|
4925
|
+
if (this.config.whatsappNumbers.length === 0) {
|
|
4926
|
+
throw new Error(
|
|
4927
|
+
"whatsappNumber(s) is required for WhatsApp channel. Set TWILIO_WHATSAPP_NUMBER / TWILIO_WHATSAPP_NUMBERS or provide whatsappNumber / whatsappNumbers in TACConfig."
|
|
4928
|
+
);
|
|
4929
|
+
}
|
|
4930
|
+
}
|
|
4667
4931
|
get channelType() {
|
|
4668
4932
|
return "whatsapp";
|
|
4669
4933
|
}
|
|
4670
4934
|
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;
|
|
4935
|
+
return this.config.whatsappNumbers.includes(authorAddress);
|
|
4677
4936
|
}
|
|
4678
4937
|
getAgentAddress(_conversationId) {
|
|
4679
4938
|
if (!this.config.whatsappNumber) {
|
|
@@ -4766,15 +5025,11 @@ var WhatsAppChannel = class extends MessagingChannel {
|
|
|
4766
5025
|
*
|
|
4767
5026
|
* Creates a conversation via Conversation Orchestrator, adds customer and
|
|
4768
5027
|
* agent participants, then sends the initial message via the Actions API.
|
|
4769
|
-
*
|
|
5028
|
+
* Uses `options.from` when provided (must be one of the configured WhatsApp
|
|
5029
|
+
* numbers), otherwise falls back to the default `config.whatsappNumber`.
|
|
4770
5030
|
*/
|
|
4771
5031
|
async initiateOutboundConversation(options) {
|
|
4772
5032
|
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
5033
|
this.logger.info(
|
|
4779
5034
|
{ to: maskAddress(validated.to), message_length: validated.message.length },
|
|
4780
5035
|
"Initiating outbound WhatsApp conversation"
|
|
@@ -4782,7 +5037,10 @@ var WhatsAppChannel = class extends MessagingChannel {
|
|
|
4782
5037
|
return this.initiateOutboundMessagingConversation({
|
|
4783
5038
|
channel: "WHATSAPP",
|
|
4784
5039
|
to: validated.to,
|
|
4785
|
-
from: this.
|
|
5040
|
+
from: this.resolveOutboundFrom(validated.from, {
|
|
5041
|
+
allowlist: this.config.whatsappNumbers,
|
|
5042
|
+
default: this.config.whatsappNumber
|
|
5043
|
+
}),
|
|
4786
5044
|
message: validated.message,
|
|
4787
5045
|
...validated.metadata ? { metadata: validated.metadata } : {}
|
|
4788
5046
|
});
|
|
@@ -4800,6 +5058,9 @@ var ChatChannel = class extends MessagingChannel {
|
|
|
4800
5058
|
// `author.participantId`; promoting some other channel-matching UNKNOWN
|
|
4801
5059
|
// CHAT participant could pick the wrong recipient.
|
|
4802
5060
|
reconcileCustomerType = false;
|
|
5061
|
+
// Chat's agent is a single identity, not a set of numbers, so it keeps the
|
|
5062
|
+
// default-address path rather than deriving the agent from webhook recipients.
|
|
5063
|
+
deriveInboundAgentFromRecipients = false;
|
|
4803
5064
|
constructor(tac, config) {
|
|
4804
5065
|
super(tac, config);
|
|
4805
5066
|
this.agentAddress = config?.agentAddress ?? "ai-assistant";
|
|
@@ -5072,6 +5333,21 @@ var VoiceProvider = class {
|
|
|
5072
5333
|
}
|
|
5073
5334
|
return callParams;
|
|
5074
5335
|
}
|
|
5336
|
+
/**
|
|
5337
|
+
* Resolve the outbound caller ID for a voice call.
|
|
5338
|
+
*
|
|
5339
|
+
* Validates `requested` against `config.phoneNumbers`, defaulting to
|
|
5340
|
+
* `config.phoneNumber` — the same rule messaging channels apply via
|
|
5341
|
+
* `resolveOutboundSender`.
|
|
5342
|
+
*/
|
|
5343
|
+
resolveFromNumber(requested) {
|
|
5344
|
+
const cfg = this.channel.getTacConfig();
|
|
5345
|
+
return resolveOutboundSender(requested, {
|
|
5346
|
+
allowlist: cfg.phoneNumbers,
|
|
5347
|
+
default: cfg.phoneNumber,
|
|
5348
|
+
channel: "voice"
|
|
5349
|
+
});
|
|
5350
|
+
}
|
|
5075
5351
|
};
|
|
5076
5352
|
var VoiceProviderConfig = class {
|
|
5077
5353
|
/** Memory retrieval mode for this channel. Defaults to `'never'`. */
|
|
@@ -5795,18 +6071,7 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5795
6071
|
last: true
|
|
5796
6072
|
};
|
|
5797
6073
|
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
|
-
}
|
|
6074
|
+
this.flushPendingHandoff(conversationId, ws);
|
|
5810
6075
|
return Promise.resolve();
|
|
5811
6076
|
} catch (error) {
|
|
5812
6077
|
this.channel.handleErrorInternal(error instanceof Error ? error : new Error(String(error)), {
|
|
@@ -5817,6 +6082,29 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5817
6082
|
throw error;
|
|
5818
6083
|
}
|
|
5819
6084
|
}
|
|
6085
|
+
/**
|
|
6086
|
+
* Send the ConversationRelay `end` message if the session has a handoff
|
|
6087
|
+
* pending, so the caller is transferred once the response has been delivered.
|
|
6088
|
+
* No-op when nothing is pending.
|
|
6089
|
+
*/
|
|
6090
|
+
flushPendingHandoff(conversationId, ws) {
|
|
6091
|
+
const session = this.channel.getConversationSession(conversationId);
|
|
6092
|
+
if (!session?.pendingHandoffData) {
|
|
6093
|
+
return;
|
|
6094
|
+
}
|
|
6095
|
+
try {
|
|
6096
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
6097
|
+
throw new Error(`WebSocket is not open (readyState: ${ws.readyState})`);
|
|
6098
|
+
}
|
|
6099
|
+
ws.send(JSON.stringify(session.pendingHandoffData));
|
|
6100
|
+
delete session.pendingHandoffData;
|
|
6101
|
+
} catch (err) {
|
|
6102
|
+
this.logger.warn(
|
|
6103
|
+
{ err, conversation_id: conversationId },
|
|
6104
|
+
"WebSocket closed before sending handoff end message; caller will not be transferred"
|
|
6105
|
+
);
|
|
6106
|
+
}
|
|
6107
|
+
}
|
|
5820
6108
|
/**
|
|
5821
6109
|
* Send a streaming voice response via WebSocket, token by token.
|
|
5822
6110
|
*
|
|
@@ -5826,6 +6114,10 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5826
6114
|
* interrupted), iteration stops and no final marker is sent (the interrupt
|
|
5827
6115
|
* handler sends the finalization instead).
|
|
5828
6116
|
*
|
|
6117
|
+
* Once the stream completes, a handoff pending on the session is delivered as
|
|
6118
|
+
* the WS `end` message, matching {@link sendResponse}. An aborted stream
|
|
6119
|
+
* leaves it pending for the next response.
|
|
6120
|
+
*
|
|
5829
6121
|
* @returns The accumulated full response text.
|
|
5830
6122
|
*/
|
|
5831
6123
|
async sendStreamingResponse(conversationId, stream, options) {
|
|
@@ -5867,6 +6159,9 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
5867
6159
|
if (!signal?.aborted && hasSentTokens && ws.readyState === WebSocket.OPEN) {
|
|
5868
6160
|
ws.send(JSON.stringify({ type: "text", token: "", last: true }));
|
|
5869
6161
|
}
|
|
6162
|
+
if (!signal?.aborted) {
|
|
6163
|
+
this.flushPendingHandoff(conversationId, ws);
|
|
6164
|
+
}
|
|
5870
6165
|
} catch (error) {
|
|
5871
6166
|
this.channel.handleErrorInternal(error instanceof Error ? error : new Error(String(error)), {
|
|
5872
6167
|
conversationId
|
|
@@ -6095,7 +6390,7 @@ var ConversationRelayProvider = class extends VoiceProvider {
|
|
|
6095
6390
|
*/
|
|
6096
6391
|
async initiateOutboundConversation(options) {
|
|
6097
6392
|
const validated = InitiateVoiceConversationOptionsSchema.parse(options);
|
|
6098
|
-
const fromNumber = this.
|
|
6393
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
6099
6394
|
this.logger.info(
|
|
6100
6395
|
{ to: validated.to, from: fromNumber },
|
|
6101
6396
|
"Initiating outbound voice conversation"
|
|
@@ -7624,7 +7919,7 @@ var OpenAIRealtimeProvider = class extends MediaStreamsOpenAIProvider {
|
|
|
7624
7919
|
}
|
|
7625
7920
|
};
|
|
7626
7921
|
}
|
|
7627
|
-
const fromNumber = this.
|
|
7922
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
7628
7923
|
this.logger.info(
|
|
7629
7924
|
{ to: maskPhone(validated.to), from: maskPhone(fromNumber) },
|
|
7630
7925
|
"Initiating outbound voice conversation"
|
|
@@ -8254,7 +8549,7 @@ var GPTLiveProvider = class _GPTLiveProvider extends MediaStreamsOpenAIProvider
|
|
|
8254
8549
|
}
|
|
8255
8550
|
};
|
|
8256
8551
|
}
|
|
8257
|
-
const fromNumber = this.
|
|
8552
|
+
const fromNumber = this.resolveFromNumber(validated.from);
|
|
8258
8553
|
this.logger.info(
|
|
8259
8554
|
{ to: maskPhone(validated.to), from: maskPhone(fromNumber) },
|
|
8260
8555
|
"Initiating outbound voice conversation"
|
|
@@ -9282,9 +9577,10 @@ function createStudioHandoffTool(tac, session, options = {}) {
|
|
|
9282
9577
|
session.pendingHandoffData = pending;
|
|
9283
9578
|
} else {
|
|
9284
9579
|
try {
|
|
9580
|
+
const fromAddress = session.channel !== "chat" && session.aiAgentInfo?.address ? session.aiAgentInfo.address : config.phoneNumber;
|
|
9285
9581
|
await postStudioHandoff(payload, session, {
|
|
9286
9582
|
handoffUrl: studioExecutionsUrl(flowSid),
|
|
9287
|
-
fromAddress
|
|
9583
|
+
fromAddress,
|
|
9288
9584
|
apiKey: config.apiKey,
|
|
9289
9585
|
apiSecret: config.apiSecret
|
|
9290
9586
|
});
|
|
@@ -9417,9 +9713,12 @@ var TACServer = class {
|
|
|
9417
9713
|
this.webhookChannels.push(this.voiceChannel);
|
|
9418
9714
|
}
|
|
9419
9715
|
this.webhookChannels.push(...this.messagingChannels);
|
|
9716
|
+
for (const channel of this.webhookChannels) {
|
|
9717
|
+
tac.registerChannel(channel);
|
|
9718
|
+
}
|
|
9420
9719
|
if (this.webhookChannels.length === 0) {
|
|
9421
9720
|
console.warn(
|
|
9422
|
-
"TACServer: No channels configured for webhook processing.
|
|
9721
|
+
"TACServer: No channels configured for webhook processing. Pass `voiceChannel` / `messagingChannels` to enable webhooks."
|
|
9423
9722
|
);
|
|
9424
9723
|
}
|
|
9425
9724
|
if (config.fastifyInstance) {
|