mirror of
https://github.com/jambonz/jambonz-feature-server.git
synced 2026-02-11 08:51:13 +00:00
Compare commits
239 Commits
v0.8.6-rc2
...
v0.9.3-12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
305facb03b | ||
|
|
d310ba0ed1 | ||
|
|
77f0fc85a3 | ||
|
|
c708b7d007 | ||
|
|
343b382373 | ||
|
|
0a541e089d | ||
|
|
d910981b1a | ||
|
|
3f2744f032 | ||
|
|
fcaf2e59e7 | ||
|
|
ee846b283d | ||
|
|
acdb8695a0 | ||
|
|
f33f197e8d | ||
|
|
9c437ab687 | ||
|
|
1873694784 | ||
|
|
d36e6b4c22 | ||
|
|
0470168757 | ||
|
|
3120dbc3e0 | ||
|
|
8b8283e603 | ||
|
|
29de4b8878 | ||
|
|
fa5fc1af9f | ||
|
|
a5e778d7f3 | ||
|
|
bf4ae5b618 | ||
|
|
ad2d99c417 | ||
|
|
af4e17f447 | ||
|
|
cd2563ce17 | ||
|
|
af475cbea4 | ||
|
|
69ba18acd1 | ||
|
|
8bed44cce3 | ||
|
|
8ede41714b | ||
|
|
ee54e4341a | ||
|
|
4bf2f42f33 | ||
|
|
e09c763d3a | ||
|
|
e8a7366526 | ||
|
|
122d267816 | ||
|
|
33bca8e67c | ||
|
|
9c05fd3deb | ||
|
|
7fa0041f6b | ||
|
|
59d9c62cbe | ||
|
|
55b408eecb | ||
|
|
f241faa871 | ||
|
|
65d35c893c | ||
|
|
dbdc1cd43d | ||
|
|
7105453d81 | ||
|
|
8487a4be68 | ||
|
|
2ddcd53d6b | ||
|
|
a4d07ddce0 | ||
|
|
16e044cabf | ||
|
|
ba282d775d | ||
|
|
a194ba833e | ||
|
|
77f3d9d7ec | ||
|
|
4dbc7df93d | ||
|
|
f71f0ac69a | ||
|
|
edb7e21ff9 | ||
|
|
cafd9530a2 | ||
|
|
ca8cace284 | ||
|
|
499c800213 | ||
|
|
97952afb1d | ||
|
|
f4e68d0ea1 | ||
|
|
6bad1a22f3 | ||
|
|
fcefa1ff31 | ||
|
|
67cd53c930 | ||
|
|
a59784b8ab | ||
|
|
a2581eaeb4 | ||
|
|
3706aa4d98 | ||
|
|
25f1e65f63 | ||
|
|
c9f0481ca6 | ||
|
|
564f6c9e55 | ||
|
|
02f25f8343 | ||
|
|
13ef89d605 | ||
|
|
d05e470867 | ||
|
|
17250f8386 | ||
|
|
ba3f46df64 | ||
|
|
f37e1540ee | ||
|
|
5e04db82bf | ||
|
|
0aa37a83ae | ||
|
|
c29ab0d858 | ||
|
|
71d4c90cbc | ||
|
|
a929a649f9 | ||
|
|
3bb4f1a29f | ||
|
|
54cc76606b | ||
|
|
0458bb7d6c | ||
|
|
dce4fe1f82 | ||
|
|
e96c35d571 | ||
|
|
070671a3fb | ||
|
|
efdb56f0a0 | ||
|
|
e2edbb4a5b | ||
|
|
3a6d63a1c6 | ||
|
|
c874ab8100 | ||
|
|
24a66fed64 | ||
|
|
c8c3738ae8 | ||
|
|
c1330d4651 | ||
|
|
27f3a4b520 | ||
|
|
594c867192 | ||
|
|
71c475e758 | ||
|
|
22ef201360 | ||
|
|
5be3a910ad | ||
|
|
7615509e0b | ||
|
|
851c071345 | ||
|
|
7911459c8c | ||
|
|
be258950b0 | ||
|
|
0520386a1e | ||
|
|
a4b1b22324 | ||
|
|
e800cca961 | ||
|
|
1efb198f72 | ||
|
|
4b5df855e1 | ||
|
|
24126ef1ec | ||
|
|
8e4995ec02 | ||
|
|
a005253a9f | ||
|
|
10efc5d608 | ||
|
|
1c48c40496 | ||
|
|
c79a6aaf8a | ||
|
|
da5f51e8e0 | ||
|
|
e7fd40e297 | ||
|
|
f541ff1a15 | ||
|
|
98b968d61f | ||
|
|
f09722a5b5 | ||
|
|
f84b3793e1 | ||
|
|
84b7456c2d | ||
|
|
c67499e38b | ||
|
|
e372a3cdfb | ||
|
|
ea303caa1c | ||
|
|
2af67d8f05 | ||
|
|
96b3b0fe07 | ||
|
|
b898b70520 | ||
|
|
b9ef00dfc7 | ||
|
|
68fa3c013d | ||
|
|
7c24208067 | ||
|
|
7f7c26e982 | ||
|
|
402adc2098 | ||
|
|
724d4fb713 | ||
|
|
673827cce3 | ||
|
|
c4c5ad33d8 | ||
|
|
7bbfc01cb0 | ||
|
|
7daf056d6b | ||
|
|
e69afc4be4 | ||
|
|
3a7cc27d0a | ||
|
|
c4a6057fc6 | ||
|
|
174438bb01 | ||
|
|
4348615b75 | ||
|
|
d365883bfe | ||
|
|
c0ab936b76 | ||
|
|
600ff763fa | ||
|
|
4d077e990f | ||
|
|
eccef54b04 | ||
|
|
2790e6d9ad | ||
|
|
f95d8639be | ||
|
|
fc838512b6 | ||
|
|
68992bccf6 | ||
|
|
c131fceea7 | ||
|
|
12174359f2 | ||
|
|
020c84d2df | ||
|
|
62d71d2504 | ||
|
|
c594797cb0 | ||
|
|
bae96a6752 | ||
|
|
ee68575ea4 | ||
|
|
6d0aeff6e2 | ||
|
|
d2a5d483d0 | ||
|
|
d3eb106d5d | ||
|
|
689e55bdf0 | ||
|
|
ed7e036890 | ||
|
|
f90fcdf57b | ||
|
|
c2a1819cbb | ||
|
|
4259a24fa0 | ||
|
|
e4e37d5697 | ||
|
|
b7a3c2970a | ||
|
|
cc33ac1d51 | ||
|
|
4b4807e4cf | ||
|
|
9a3c731389 | ||
|
|
edd8f20642 | ||
|
|
ee24041cba | ||
|
|
83f7abcd89 | ||
|
|
c9194168d2 | ||
|
|
83191487cf | ||
|
|
65ef4e6d64 | ||
|
|
ddb4719220 | ||
|
|
f514a65f63 | ||
|
|
5ccea65b7f | ||
|
|
8672152873 | ||
|
|
425b88f930 | ||
|
|
111976bea5 | ||
|
|
ec6d7b3f42 | ||
|
|
5e1b826da4 | ||
|
|
be9c3406c1 | ||
|
|
2f3ef1654a | ||
|
|
0baa080a1e | ||
|
|
f5cbd26c9f | ||
|
|
d9fd82fa60 | ||
|
|
76a3aa7f42 | ||
|
|
cafe149bdf | ||
|
|
9969e39e7e | ||
|
|
8eea212df2 | ||
|
|
e8e356ea3a | ||
|
|
c5e19bf775 | ||
|
|
498dd64025 | ||
|
|
24b6d2464b | ||
|
|
cd5421120f | ||
|
|
d7c3a4a632 | ||
|
|
c53ad89154 | ||
|
|
10b98630d3 | ||
|
|
d132bdb92b | ||
|
|
6be3fd9b64 | ||
|
|
844b0cb05d | ||
|
|
c0b56d4fc6 | ||
|
|
d27de284e7 | ||
|
|
5e97847a2f | ||
|
|
17c379df47 | ||
|
|
e7bc0b0737 | ||
|
|
dfe623e78a | ||
|
|
56b8f0623b | ||
|
|
7bcbab5b74 | ||
|
|
44e6a3513d | ||
|
|
fad16144b9 | ||
|
|
6523a861c0 | ||
|
|
cff67f5e4c | ||
|
|
c77bd84e0e | ||
|
|
3cd7a619ad | ||
|
|
59cf02bd04 | ||
|
|
a18d55e9ab | ||
|
|
d474b9d604 | ||
|
|
8d2b60c284 | ||
|
|
9cf9d4f587 | ||
|
|
bd002ede48 | ||
|
|
1a2aa91973 | ||
|
|
e322b7d8d3 | ||
|
|
7da11df88e | ||
|
|
09cf1345f6 | ||
|
|
2595f527ff | ||
|
|
1d77c0cd20 | ||
|
|
9eab81268b | ||
|
|
ecf3d140d6 | ||
|
|
4a52be9171 | ||
|
|
9b722ae36d | ||
|
|
370b046fac | ||
|
|
fca391c32e | ||
|
|
043860c4a3 | ||
|
|
a021ee3112 | ||
|
|
8999c85a71 | ||
|
|
72147a8110 | ||
|
|
93d0e41e31 |
11
.github/workflows/build.yml
vendored
11
.github/workflows/build.yml
vendored
@@ -6,12 +6,17 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 20
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run jslint
|
- run: npm run jslint
|
||||||
|
- name: Install Docker Compose
|
||||||
|
run: |
|
||||||
|
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
||||||
|
sudo chmod +x /usr/local/bin/docker-compose
|
||||||
|
docker-compose --version
|
||||||
- run: docker pull drachtio/sipp
|
- run: docker pull drachtio/sipp
|
||||||
- run: npm test
|
- run: npm test
|
||||||
env:
|
env:
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -42,4 +42,5 @@ ecosystem.config.js
|
|||||||
test/credentials/*.json
|
test/credentials/*.json
|
||||||
run-tests.sh
|
run-tests.sh
|
||||||
run-coverage.sh
|
run-coverage.sh
|
||||||
.vscode
|
.vscode
|
||||||
|
.env
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM --platform=linux/amd64 node:18.15-alpine3.16 as base
|
FROM --platform=linux/amd64 node:20-alpine as base
|
||||||
|
|
||||||
RUN apk --update --no-cache add --virtual .builds-deps build-base python3
|
RUN apk --update --no-cache add --virtual .builds-deps build-base python3
|
||||||
|
|
||||||
|
|||||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2021 Drachtio Communications Services, LLC
|
Copyright (c) 2018-2024 FirstFive8, Inc.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ Configuration is provided via environment variables:
|
|||||||
|AWS_ACCESS_KEY_ID| aws access key id, used for TTS/STT as well SNS notifications|no|
|
|AWS_ACCESS_KEY_ID| aws access key id, used for TTS/STT as well SNS notifications|no|
|
||||||
|AWS_REGION| aws region| no|
|
|AWS_REGION| aws region| no|
|
||||||
|AWS_SECRET_ACCESS_KEY| aws secret access key, used per above|no|
|
|AWS_SECRET_ACCESS_KEY| aws secret access key, used per above|no|
|
||||||
|AWS_SNS_TOPIC_ARM| aws sns topic arn that scale-in lifecycle notifications will be published to|no|
|
|AWS_SNS_TOPIC_ARN| aws sns topic arn that scale-in lifecycle notifications will be published to|no|
|
||||||
|DRACHTIO_HOST| ip address of drachtio server (typically '127.0.0.1')|yes|
|
|DRACHTIO_HOST| ip address of drachtio server (typically '127.0.0.1')|yes|
|
||||||
|DRACHTIO_PORT| listening port of drachtio server for control connections (typically 9022)|yes|
|
|DRACHTIO_PORT| listening port of drachtio server for control connections (typically 9022)|yes|
|
||||||
|DRACHTIO_SECRET| shared secret|yes|
|
|DRACHTIO_SECRET| shared secret|yes|
|
||||||
@@ -21,6 +21,7 @@ Configuration is provided via environment variables:
|
|||||||
|ENCRYPTION_SECRET| secret for credential encryption(JWT_SECRET is deprecated) |yes|
|
|ENCRYPTION_SECRET| secret for credential encryption(JWT_SECRET is deprecated) |yes|
|
||||||
|GOOGLE_APPLICATION_CREDENTIALS| path to gcp service key file|yes|
|
|GOOGLE_APPLICATION_CREDENTIALS| path to gcp service key file|yes|
|
||||||
|HTTP_PORT| tcp port to listen on for API requests from jambonz-api-server|yes|
|
|HTTP_PORT| tcp port to listen on for API requests from jambonz-api-server|yes|
|
||||||
|
|HTTP_IP| IP Address for API requests from jambonz-api-server |no|
|
||||||
|JAMBONES_GATHER_EARLY_HINTS_MATCH| if true and hints are provided, gather will opportunistically review interim transcripts if possible to reduce ASR latency |no|
|
|JAMBONES_GATHER_EARLY_HINTS_MATCH| if true and hints are provided, gather will opportunistically review interim transcripts if possible to reduce ASR latency |no|
|
||||||
|JAMBONES_FREESWITCH| IP:port:secret for Freeswitch server (e.g. '127.0.0.1:8021:JambonzR0ck$'|yes|
|
|JAMBONES_FREESWITCH| IP:port:secret for Freeswitch server (e.g. '127.0.0.1:8021:JambonzR0ck$'|yes|
|
||||||
|JAMBONES_LOGLEVEL| log level for application, 'info' or 'debug'|no|
|
|JAMBONES_LOGLEVEL| log level for application, 'info' or 'debug'|no|
|
||||||
@@ -71,7 +72,7 @@ module.exports = {
|
|||||||
STATS_PORT: 8125,
|
STATS_PORT: 8125,
|
||||||
STATS_PROTOCOL: 'tcp',
|
STATS_PROTOCOL: 'tcp',
|
||||||
STATS_TELEGRAF: 1,
|
STATS_TELEGRAF: 1,
|
||||||
AWS_SNS_TOPIC_ARM: 'arn:aws:sns:us-west-1:xxxxxxxxxxx:terraform-20201107200347128600000002',
|
AWS_SNS_TOPIC_ARN: 'arn:aws:sns:us-west-1:xxxxxxxxxxx:terraform-20201107200347128600000002',
|
||||||
JAMBONES_NETWORK_CIDR: '172.31.0.0/16',
|
JAMBONES_NETWORK_CIDR: '172.31.0.0/16',
|
||||||
JAMBONES_MYSQL_HOST: 'aurora-cluster-jambonz.cluster-yyyyyyyyyyy.us-west-1.rds.amazonaws.com',
|
JAMBONES_MYSQL_HOST: 'aurora-cluster-jambonz.cluster-yyyyyyyyyyy.us-west-1.rds.amazonaws.com',
|
||||||
JAMBONES_MYSQL_USER: 'admin',
|
JAMBONES_MYSQL_USER: 'admin',
|
||||||
|
|||||||
44
app.js
44
app.js
@@ -25,10 +25,22 @@ const opts = {
|
|||||||
};
|
};
|
||||||
const pino = require('pino');
|
const pino = require('pino');
|
||||||
const logger = pino(opts, pino.destination({sync: false}));
|
const logger = pino(opts, pino.destination({sync: false}));
|
||||||
const {LifeCycleEvents, FS_UUID_SET_NAME} = require('./lib/utils/constants');
|
const {LifeCycleEvents, FS_UUID_SET_NAME, SystemState, FEATURE_SERVER} = require('./lib/utils/constants');
|
||||||
const installSrfLocals = require('./lib/utils/install-srf-locals');
|
const installSrfLocals = require('./lib/utils/install-srf-locals');
|
||||||
installSrfLocals(srf, logger);
|
installSrfLocals(srf, logger);
|
||||||
|
|
||||||
|
const writeSystemAlerts = srf.locals?.writeSystemAlerts;
|
||||||
|
if (writeSystemAlerts) {
|
||||||
|
writeSystemAlerts({
|
||||||
|
system_component: FEATURE_SERVER,
|
||||||
|
state : SystemState.Online,
|
||||||
|
fields : {
|
||||||
|
detail: `feature-server with process_id ${process.pid} started`,
|
||||||
|
host: srf.locals?.ipv4
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
initLocals,
|
initLocals,
|
||||||
createRootSpan,
|
createRootSpan,
|
||||||
@@ -100,8 +112,20 @@ createHttpListener(logger, srf)
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
setInterval(() => {
|
const monInterval = setInterval(async() => {
|
||||||
srf.locals.stats.gauge('fs.sip.calls.count', sessionTracker.count);
|
srf.locals.stats.gauge('fs.sip.calls.count', sessionTracker.count);
|
||||||
|
try {
|
||||||
|
const systemInformation = await srf.locals.dbHelpers.lookupSystemInformation();
|
||||||
|
if (systemInformation && systemInformation.log_level) {
|
||||||
|
logger.level = systemInformation.log_level;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (process.env.NODE_ENV === 'test') {
|
||||||
|
clearInterval(monInterval);
|
||||||
|
logger.error('all tests complete');
|
||||||
|
}
|
||||||
|
else logger.error({err}, 'Error checking system log level in database');
|
||||||
|
}
|
||||||
}, 20000);
|
}, 20000);
|
||||||
|
|
||||||
const disconnect = () => {
|
const disconnect = () => {
|
||||||
@@ -112,13 +136,25 @@ const disconnect = () => {
|
|||||||
srf.locals.mediaservers?.forEach((ms) => ms.disconnect());
|
srf.locals.mediaservers?.forEach((ms) => ms.disconnect());
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
process.on('SIGTERM', handle);
|
process.on('SIGTERM', handle);
|
||||||
|
process.on('SIGINT', handle);
|
||||||
|
|
||||||
function handle(signal) {
|
async function handle(signal) {
|
||||||
const {removeFromSet} = srf.locals.dbHelpers;
|
const {removeFromSet} = srf.locals.dbHelpers;
|
||||||
srf.locals.disabled = true;
|
srf.locals.disabled = true;
|
||||||
logger.info(`got signal ${signal}`);
|
logger.info(`got signal ${signal}`);
|
||||||
|
const writeSystemAlerts = srf.locals?.writeSystemAlerts;
|
||||||
|
if (writeSystemAlerts) {
|
||||||
|
// it has to be synchronous call, or else by the time system saves the app terminates
|
||||||
|
await writeSystemAlerts({
|
||||||
|
system_component: FEATURE_SERVER,
|
||||||
|
state : SystemState.Offline,
|
||||||
|
fields : {
|
||||||
|
detail: `feature-server with process_id ${process.pid} stopped, signal ${signal}`,
|
||||||
|
host: srf.locals?.ipv4
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
const setName = `${(JAMBONES_CLUSTER_ID || 'default')}:active-fs`;
|
const setName = `${(JAMBONES_CLUSTER_ID || 'default')}:active-fs`;
|
||||||
const fsServiceUrlSetName = `${(JAMBONES_CLUSTER_ID || 'default')}:fs-service-url`;
|
const fsServiceUrlSetName = `${(JAMBONES_CLUSTER_ID || 'default')}:fs-service-url`;
|
||||||
if (setName && srf.locals.localSipAddress) {
|
if (setName && srf.locals.localSipAddress) {
|
||||||
|
|||||||
@@ -9,7 +9,112 @@
|
|||||||
"can't take your call",
|
"can't take your call",
|
||||||
"will get back to you",
|
"will get back to you",
|
||||||
"I'll get back to you",
|
"I'll get back to you",
|
||||||
"we are unable"
|
"we are unable",
|
||||||
|
"Unable to take your call now",
|
||||||
|
"I'll reply soon",
|
||||||
|
"I'll call back",
|
||||||
|
"I'll reach out to you as soon as possible",
|
||||||
|
"Leave a message",
|
||||||
|
"Away from phone",
|
||||||
|
"Not available now",
|
||||||
|
"I'll return call",
|
||||||
|
"On another call",
|
||||||
|
"Currently on another call",
|
||||||
|
"I will return call later",
|
||||||
|
"Busy please leave message",
|
||||||
|
"Message will be returned promptly",
|
||||||
|
"Currently unavailable to answer",
|
||||||
|
"Planning to return your call soon",
|
||||||
|
"Apologies for missing your call",
|
||||||
|
"Not by the phone at the moment",
|
||||||
|
"Expecting to return your call",
|
||||||
|
"Currently not accessible",
|
||||||
|
"Intend to call back",
|
||||||
|
"Appreciate your patience!",
|
||||||
|
"Engaged in another conversation",
|
||||||
|
"I Will respond promptly",
|
||||||
|
"Kindly leave a message",
|
||||||
|
"Currently occupied leave a message",
|
||||||
|
"Unfortunately unable to answer right now",
|
||||||
|
"Occupied at the moment",
|
||||||
|
"Not present leave a message",
|
||||||
|
"Regrettably unavailable kindly leave a message",
|
||||||
|
"Will ensure a prompt response to your message",
|
||||||
|
"Currently engaged",
|
||||||
|
"Will return your call at the earliest opportunity",
|
||||||
|
"Your message will receive my prompt attention",
|
||||||
|
"I'll respond as soon as I can",
|
||||||
|
"Your message is important please leave it after the beep",
|
||||||
|
"Away from the phone at the moment",
|
||||||
|
"Unable to answer right now",
|
||||||
|
"Engaged in another task",
|
||||||
|
"Not by the phone presently",
|
||||||
|
"I'll respond at my earliest convenience",
|
||||||
|
"Away from the phone momentarily",
|
||||||
|
"I'll return your call shortly",
|
||||||
|
"Currently not able to answer",
|
||||||
|
"Your message is important please leave it after the tone",
|
||||||
|
"I'm unable to take your call right now",
|
||||||
|
"Please leave your message for me",
|
||||||
|
"I'll get back to you soon",
|
||||||
|
"Your call has been missed",
|
||||||
|
"Please leave a detailed message for me to respond to",
|
||||||
|
"Leave a message I'll make sure to respond",
|
||||||
|
"Feel free to leave a message",
|
||||||
|
"Your call is important to me",
|
||||||
|
"I'll get back to you shortly",
|
||||||
|
"Your message will be attended to promptly",
|
||||||
|
"Not available at the moment",
|
||||||
|
"I'll be sure to get back to you",
|
||||||
|
"I'll call you back soon",
|
||||||
|
"I'll ensure a prompt response",
|
||||||
|
"Sorry for the inconvenience",
|
||||||
|
"I'll return your call",
|
||||||
|
"I'll make sure to get back to you",
|
||||||
|
"I'll call you back shortly",
|
||||||
|
"I'll return your call as soon as possible",
|
||||||
|
"Apologies for the inconvenience leave your message",
|
||||||
|
"Your call is appreciated",
|
||||||
|
"I'm unavailable to answer",
|
||||||
|
"I'm currently away",
|
||||||
|
"I'll return your call as soon as I can",
|
||||||
|
"I'm away from the phone",
|
||||||
|
"I'm currently unavailable to take your call",
|
||||||
|
"Sorry for missing your call",
|
||||||
|
"I'll ensure it receives my immediate attention",
|
||||||
|
"I'm away from the phone momentarily",
|
||||||
|
"I'll reach out to you shortly",
|
||||||
|
"Apologies for the inconvenience",
|
||||||
|
"Currently occupied",
|
||||||
|
"Unable to answer your call at the moment",
|
||||||
|
"I'll make sure to follow up with you",
|
||||||
|
"Sorry for not being available",
|
||||||
|
"I'll reach out to you as soon as I can",
|
||||||
|
"I'm currently engaged",
|
||||||
|
"I'm currently busy",
|
||||||
|
"I'm currently unavailable",
|
||||||
|
"I'll respond to you at my earliest convenience",
|
||||||
|
"Your message is appreciated",
|
||||||
|
"I'll get back to you promptly",
|
||||||
|
"I'll get back to you without delay",
|
||||||
|
"Currently away from the phone",
|
||||||
|
"I'll return your call at my earliest opportunity",
|
||||||
|
"Sorry for the missed call",
|
||||||
|
"I'll make sure to address your concerns",
|
||||||
|
"Please provide your details for a callback",
|
||||||
|
"I'll make every effort to respond promptly",
|
||||||
|
"I'll ensure it's attended to promptly",
|
||||||
|
"Away from the phone temporarily",
|
||||||
|
"I'll get back to you as soon as I return",
|
||||||
|
"Currently not in a position to answer your call",
|
||||||
|
"Your call cannot be answered at the moment",
|
||||||
|
"I'll ensure to respond as soon as I'm able",
|
||||||
|
"Your call is important please leave a message",
|
||||||
|
"Unable to answer right now please leave your message",
|
||||||
|
"Currently not accessible intending to return your call",
|
||||||
|
"I'll respond promptly to your message",
|
||||||
|
"leave a memo",
|
||||||
|
"please leave a memo"
|
||||||
],
|
],
|
||||||
"es-ES": [
|
"es-ES": [
|
||||||
"le pasamos la llamada",
|
"le pasamos la llamada",
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ const JAMBONES_LOGLEVEL = process.env.JAMBONES_LOGLEVEL || 'info';
|
|||||||
const JAMBONES_INJECT_CONTENT = process.env.JAMBONES_INJECT_CONTENT;
|
const JAMBONES_INJECT_CONTENT = process.env.JAMBONES_INJECT_CONTENT;
|
||||||
|
|
||||||
const PORT = parseInt(process.env.HTTP_PORT, 10) || 3000;
|
const PORT = parseInt(process.env.HTTP_PORT, 10) || 3000;
|
||||||
|
const HTTP_IP = process.env.HTTP_IP;
|
||||||
const HTTP_PORT_MAX = parseInt(process.env.HTTP_PORT_MAX, 10);
|
const HTTP_PORT_MAX = parseInt(process.env.HTTP_PORT_MAX, 10);
|
||||||
|
|
||||||
const K8S = process.env.K8S;
|
const K8S = process.env.K8S;
|
||||||
@@ -92,7 +93,7 @@ const AWS_REGION = process.env.AWS_REGION;
|
|||||||
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID;
|
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID;
|
||||||
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY;
|
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY;
|
||||||
const AWS_SNS_PORT = parseInt(process.env.AWS_SNS_PORT, 10) || 3001;
|
const AWS_SNS_PORT = parseInt(process.env.AWS_SNS_PORT, 10) || 3001;
|
||||||
const AWS_SNS_TOPIC_ARM = process.env.AWS_SNS_TOPIC_ARM;
|
const AWS_SNS_TOPIC_ARN = process.env.AWS_SNS_TOPIC_ARN;
|
||||||
const AWS_SNS_PORT_MAX = parseInt(process.env.AWS_SNS_PORT_MAX, 10) || 3005;
|
const AWS_SNS_PORT_MAX = parseInt(process.env.AWS_SNS_PORT_MAX, 10) || 3005;
|
||||||
|
|
||||||
const GCP_JSON_KEY = process.env.GCP_JSON_KEY;
|
const GCP_JSON_KEY = process.env.GCP_JSON_KEY;
|
||||||
@@ -107,6 +108,8 @@ const DEEPGRAM_API_KEY = process.env.DEEPGRAM_API_KEY;
|
|||||||
const ANCHOR_MEDIA_ALWAYS = process.env.ANCHOR_MEDIA_ALWAYS;
|
const ANCHOR_MEDIA_ALWAYS = process.env.ANCHOR_MEDIA_ALWAYS;
|
||||||
const VMD_HINTS_FILE = process.env.VMD_HINTS_FILE;
|
const VMD_HINTS_FILE = process.env.VMD_HINTS_FILE;
|
||||||
|
|
||||||
|
const JAMBONES_AWS_TRANSCRIBE_USE_GRPC = process.env.JAMBONES_AWS_TRANSCRIBE_USE_GRPC;
|
||||||
|
|
||||||
/* security, secrets */
|
/* security, secrets */
|
||||||
const LEGACY_CRYPTO = !!process.env.LEGACY_CRYPTO;
|
const LEGACY_CRYPTO = !!process.env.LEGACY_CRYPTO;
|
||||||
const JWT_SECRET = process.env.JWT_SECRET;
|
const JWT_SECRET = process.env.JWT_SECRET;
|
||||||
@@ -133,6 +136,12 @@ const JAMBONES_DISABLE_DIRECT_P2P_CALL = process.env.JAMBONES_DISABLE_DIRECT_P2P
|
|||||||
const JAMBONES_EAGERLY_PRE_CACHE_AUDIO = parseInt(process.env.JAMBONES_EAGERLY_PRE_CACHE_AUDIO, 10) || 0;
|
const JAMBONES_EAGERLY_PRE_CACHE_AUDIO = parseInt(process.env.JAMBONES_EAGERLY_PRE_CACHE_AUDIO, 10) || 0;
|
||||||
|
|
||||||
const JAMBONES_USE_FREESWITCH_TIMER_FD = process.env.JAMBONES_USE_FREESWITCH_TIMER_FD;
|
const JAMBONES_USE_FREESWITCH_TIMER_FD = process.env.JAMBONES_USE_FREESWITCH_TIMER_FD;
|
||||||
|
const JAMBONES_DIAL_SBC_FOR_REGISTERED_USER = process.env.JAMBONES_DIAL_SBC_FOR_REGISTERED_USER || false;
|
||||||
|
const JAMBONES_MEDIA_TIMEOUT_MS = process.env.JAMBONES_MEDIA_TIMEOUT_MS || 0;
|
||||||
|
const JAMBONES_MEDIA_HOLD_TIMEOUT_MS = process.env.JAMBONES_MEDIA_HOLD_TIMEOUT_MS || 0;
|
||||||
|
// jambonz
|
||||||
|
const JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS =
|
||||||
|
process.env.JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS;
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
JAMBONES_MYSQL_HOST,
|
JAMBONES_MYSQL_HOST,
|
||||||
@@ -170,6 +179,7 @@ module.exports = {
|
|||||||
JAMBONES_CLUSTER_ID,
|
JAMBONES_CLUSTER_ID,
|
||||||
PORT,
|
PORT,
|
||||||
HTTP_PORT_MAX,
|
HTTP_PORT_MAX,
|
||||||
|
HTTP_IP,
|
||||||
K8S,
|
K8S,
|
||||||
K8S_SBC_SIP_SERVICE_NAME,
|
K8S_SBC_SIP_SERVICE_NAME,
|
||||||
JAMBONES_SUBNET,
|
JAMBONES_SUBNET,
|
||||||
@@ -182,12 +192,13 @@ module.exports = {
|
|||||||
AWS_ACCESS_KEY_ID,
|
AWS_ACCESS_KEY_ID,
|
||||||
AWS_SECRET_ACCESS_KEY,
|
AWS_SECRET_ACCESS_KEY,
|
||||||
AWS_SNS_PORT,
|
AWS_SNS_PORT,
|
||||||
AWS_SNS_TOPIC_ARM,
|
AWS_SNS_TOPIC_ARN,
|
||||||
AWS_SNS_PORT_MAX,
|
AWS_SNS_PORT_MAX,
|
||||||
|
|
||||||
ANCHOR_MEDIA_ALWAYS,
|
ANCHOR_MEDIA_ALWAYS,
|
||||||
VMD_HINTS_FILE,
|
VMD_HINTS_FILE,
|
||||||
JAMBONES_FREESWITCH_MAX_CALL_DURATION_MINS,
|
JAMBONES_FREESWITCH_MAX_CALL_DURATION_MINS,
|
||||||
|
JAMBONES_AWS_TRANSCRIBE_USE_GRPC,
|
||||||
|
|
||||||
LEGACY_CRYPTO,
|
LEGACY_CRYPTO,
|
||||||
JWT_SECRET,
|
JWT_SECRET,
|
||||||
@@ -216,5 +227,9 @@ module.exports = {
|
|||||||
JAMBONZ_RECORD_WS_PASSWORD,
|
JAMBONZ_RECORD_WS_PASSWORD,
|
||||||
JAMBONZ_DISABLE_DIAL_PAI_HEADER,
|
JAMBONZ_DISABLE_DIAL_PAI_HEADER,
|
||||||
JAMBONES_DISABLE_DIRECT_P2P_CALL,
|
JAMBONES_DISABLE_DIRECT_P2P_CALL,
|
||||||
JAMBONES_USE_FREESWITCH_TIMER_FD
|
JAMBONES_USE_FREESWITCH_TIMER_FD,
|
||||||
|
JAMBONES_DIAL_SBC_FOR_REGISTERED_USER,
|
||||||
|
JAMBONES_MEDIA_TIMEOUT_MS,
|
||||||
|
JAMBONES_MEDIA_HOLD_TIMEOUT_MS,
|
||||||
|
JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -30,6 +30,20 @@ const appsMap = {
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}]
|
}]
|
||||||
|
},
|
||||||
|
conference: {
|
||||||
|
// Dummy hook to follow later feature server logic.
|
||||||
|
call_hook: {
|
||||||
|
url: 'https://jambonz.org',
|
||||||
|
method: 'GET'
|
||||||
|
},
|
||||||
|
account_sid: '',
|
||||||
|
app_json: [{
|
||||||
|
verb: 'conference',
|
||||||
|
name: '',
|
||||||
|
beep: false,
|
||||||
|
startConferenceOnEnter: true
|
||||||
|
}]
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -38,6 +52,7 @@ const createJambonzApp = (type, {account_sid, name, caller_id}) => {
|
|||||||
app.account_sid = account_sid;
|
app.account_sid = account_sid;
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'queue':
|
case 'queue':
|
||||||
|
case 'conference':
|
||||||
app.app_json[0].name = name;
|
app.app_json[0].name = name;
|
||||||
break;
|
break;
|
||||||
case 'user':
|
case 'user':
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ const RootSpan = require('../../utils/call-tracer');
|
|||||||
const dbUtils = require('../../utils/db-utils');
|
const dbUtils = require('../../utils/db-utils');
|
||||||
const { mergeSdpMedia, extractSdpMedia } = require('../../utils/sdp-utils');
|
const { mergeSdpMedia, extractSdpMedia } = require('../../utils/sdp-utils');
|
||||||
const { createCallSchema, customSanitizeFunction } = require('../schemas/create-call');
|
const { createCallSchema, customSanitizeFunction } = require('../schemas/create-call');
|
||||||
|
const { selectHostPort } = require('../../utils/network');
|
||||||
|
const { JAMBONES_DIAL_SBC_FOR_REGISTERED_USER } = require('../../config');
|
||||||
|
|
||||||
const removeNullProperties = (obj) => (Object.keys(obj).forEach((key) => obj[key] === null && delete obj[key]), obj);
|
const removeNullProperties = (obj) => (Object.keys(obj).forEach((key) => obj[key] === null && delete obj[key]), obj);
|
||||||
const removeNulls = (req, res, next) => {
|
const removeNulls = (req, res, next) => {
|
||||||
@@ -65,7 +67,7 @@ router.post('/',
|
|||||||
lookupAppBySid
|
lookupAppBySid
|
||||||
} = srf.locals.dbHelpers;
|
} = srf.locals.dbHelpers;
|
||||||
const {getSBC, getFreeswitch} = srf.locals;
|
const {getSBC, getFreeswitch} = srf.locals;
|
||||||
const sbcAddress = getSBC();
|
let sbcAddress = getSBC();
|
||||||
if (!sbcAddress) throw new Error('no available SBCs for outbound call creation');
|
if (!sbcAddress) throw new Error('no available SBCs for outbound call creation');
|
||||||
const target = restDial.to;
|
const target = restDial.to;
|
||||||
const opts = {
|
const opts = {
|
||||||
@@ -97,7 +99,9 @@ router.post('/',
|
|||||||
'X-Trace-ID': rootSpan.traceId,
|
'X-Trace-ID': rootSpan.traceId,
|
||||||
...(req.body?.application_sid && {'X-Application-Sid': req.body.application_sid}),
|
...(req.body?.application_sid && {'X-Application-Sid': req.body.application_sid}),
|
||||||
...(restDial.fromHost && {'X-Preferred-From-Host': restDial.fromHost}),
|
...(restDial.fromHost && {'X-Preferred-From-Host': restDial.fromHost}),
|
||||||
...(record_all_calls && {'X-Record-All-Calls': recordOutputFormat})
|
...(record_all_calls && {'X-Record-All-Calls': recordOutputFormat}),
|
||||||
|
...(target.proxy && {'X-SIP-Proxy': target.proxy}),
|
||||||
|
...target.headers
|
||||||
};
|
};
|
||||||
|
|
||||||
switch (target.type) {
|
switch (target.type) {
|
||||||
@@ -139,6 +143,16 @@ router.post('/',
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// find handling sbc sip for called user
|
||||||
|
if (JAMBONES_DIAL_SBC_FOR_REGISTERED_USER && target.type === 'user') {
|
||||||
|
const { registrar } = srf.locals.dbHelpers;
|
||||||
|
const reg = await registrar.query(target.name);
|
||||||
|
if (reg) {
|
||||||
|
sbcAddress = selectHostPort(logger, reg.sbcAddress, 'tcp')[1];
|
||||||
|
}
|
||||||
|
//sbc outbound return 404 Notfound to handle case called user is not reigstered.
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* trunk isn't specified,
|
* trunk isn't specified,
|
||||||
* check if from-number matches any existing numbers on Jambonz
|
* check if from-number matches any existing numbers on Jambonz
|
||||||
@@ -195,10 +209,13 @@ router.post('/',
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* create our application object -
|
* create our application object -
|
||||||
* not from the database as per an inbound call,
|
* we merge the inbound call application,
|
||||||
* but from the provided params in the request
|
* with the provided app params from the request body
|
||||||
*/
|
*/
|
||||||
const app = req.body;
|
const app = {
|
||||||
|
...application,
|
||||||
|
...req.body
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* attach our requestor and notifier objects
|
* attach our requestor and notifier objects
|
||||||
@@ -218,7 +235,7 @@ router.post('/',
|
|||||||
}
|
}
|
||||||
if (!app.notifier && app.call_status_hook) {
|
if (!app.notifier && app.call_status_hook) {
|
||||||
app.notifier = new HttpRequestor(logger, account.account_sid, app.call_status_hook, account.webhook_secret);
|
app.notifier = new HttpRequestor(logger, account.account_sid, app.call_status_hook, account.webhook_secret);
|
||||||
logger.debug({call_hook: app.call_hook}, 'creating http client for call status hook');
|
logger.debug({call_status_hook: app.call_status_hook}, 'creating http client for call status hook');
|
||||||
}
|
}
|
||||||
else if (!app.notifier) {
|
else if (!app.notifier) {
|
||||||
logger.debug('creating null call status hook');
|
logger.debug('creating null call status hook');
|
||||||
@@ -257,6 +274,8 @@ router.post('/',
|
|||||||
callId: inviteReq.get('Call-ID'),
|
callId: inviteReq.get('Call-ID'),
|
||||||
accountSid,
|
accountSid,
|
||||||
traceId: rootSpan.traceId
|
traceId: rootSpan.traceId
|
||||||
|
}, {
|
||||||
|
...(account.enable_debug_log && {level: 'debug'})
|
||||||
});
|
});
|
||||||
app.requestor.logger = app.notifier.logger = sipLogger;
|
app.requestor.logger = app.notifier.logger = sipLogger;
|
||||||
const callInfo = new CallInfo({
|
const callInfo = new CallInfo({
|
||||||
@@ -290,6 +309,8 @@ router.post('/',
|
|||||||
},
|
},
|
||||||
cbProvisional: (prov) => {
|
cbProvisional: (prov) => {
|
||||||
const callStatus = prov.body ? CallStatus.EarlyMedia : CallStatus.Ringing;
|
const callStatus = prov.body ? CallStatus.EarlyMedia : CallStatus.Ringing;
|
||||||
|
// Update call-id for sbc outbound INVITE
|
||||||
|
cs.callInfo.sbcCallid = prov.get('X-CID');
|
||||||
if ([180, 183].includes(prov.status) && prov.body) connectStream(prov.body);
|
if ([180, 183].includes(prov.status) && prov.body) connectStream(prov.body);
|
||||||
restDial.emit('callStatus', prov.status, !!prov.body);
|
restDial.emit('callStatus', prov.status, !!prov.body);
|
||||||
cs.emit('callStatusChange', {callStatus, sipStatus: prov.status});
|
cs.emit('callStatusChange', {callStatus, sipStatus: prov.status});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const uuidv4 = require('uuid-random');
|
const uuidv4 = require('uuid-random');
|
||||||
const {CallDirection, AllowedSipRecVerbs} = require('./utils/constants');
|
const {CallDirection, AllowedSipRecVerbs, WS_CLOSE_CODES} = require('./utils/constants');
|
||||||
const {parseSiprecPayload} = require('./utils/siprec-utils');
|
const {parseSiprecPayload} = require('./utils/siprec-utils');
|
||||||
const CallInfo = require('./session/call-info');
|
const CallInfo = require('./session/call-info');
|
||||||
const HttpRequestor = require('./utils/http-requestor');
|
const HttpRequestor = require('./utils/http-requestor');
|
||||||
@@ -75,13 +75,19 @@ module.exports = function(srf, logger) {
|
|||||||
req.locals.application_sid = application_sid;
|
req.locals.application_sid = application_sid;
|
||||||
}
|
}
|
||||||
// check for call to queue
|
// check for call to queue
|
||||||
if (uri.user?.startsWith('queue-') && req.locals.originatingUser && clientDb?.allow_direct_queue_calling) {
|
else if (uri.user?.startsWith('queue-') && req.locals.originatingUser && clientDb?.allow_direct_queue_calling) {
|
||||||
const queue_name = uri.user.match(/queue-(.*)/)[1];
|
const queue_name = uri.user.match(/queue-(.*)/)[1];
|
||||||
logger.debug(`got Queue from Request URI header: ${queue_name}`);
|
logger.debug(`got Queue from Request URI header: ${queue_name}`);
|
||||||
req.locals.queue_name = queue_name;
|
req.locals.queue_name = queue_name;
|
||||||
}
|
}
|
||||||
|
// check for call to conference
|
||||||
|
else if (uri.user?.startsWith('conference-') && req.locals.originatingUser && clientDb?.allow_direct_app_calling) {
|
||||||
|
const conference_id = uri.user.match(/conference-(.*)/)[1];
|
||||||
|
logger.debug(`got Conference from Request URI header: ${conference_id}`);
|
||||||
|
req.locals.conference_id = conference_id;
|
||||||
|
}
|
||||||
// check for call to registered user
|
// check for call to registered user
|
||||||
if (!JAMBONES_DISABLE_DIRECT_P2P_CALL && req.locals.originatingUser && clientDb?.allow_direct_user_calling) {
|
else if (!JAMBONES_DISABLE_DIRECT_P2P_CALL && req.locals.originatingUser && clientDb?.allow_direct_user_calling) {
|
||||||
const arr = /^(.*)@(.*)/.exec(req.locals.originatingUser);
|
const arr = /^(.*)@(.*)/.exec(req.locals.originatingUser);
|
||||||
if (arr) {
|
if (arr) {
|
||||||
const sipRealm = arr[2];
|
const sipRealm = arr[2];
|
||||||
@@ -181,14 +187,20 @@ module.exports = function(srf, logger) {
|
|||||||
|
|
||||||
const {span} = rootSpan.startChildSpan('lookupAccountDetails');
|
const {span} = rootSpan.startChildSpan('lookupAccountDetails');
|
||||||
try {
|
try {
|
||||||
req.locals.accountInfo = await lookupAccountDetails(account_sid);
|
const accountDetail = await lookupAccountDetails(account_sid);
|
||||||
req.locals.service_provider_sid = req.locals.accountInfo?.account?.service_provider_sid;
|
const account = accountDetail?.account;
|
||||||
|
req.locals.accountInfo = accountDetail;
|
||||||
|
req.locals.service_provider_sid = account?.service_provider_sid;
|
||||||
span.end();
|
span.end();
|
||||||
if (!req.locals.accountInfo.account.is_active) {
|
if (!account?.is_active) {
|
||||||
logger.info(`Account is inactive or suspended ${account_sid}`);
|
logger.info(`Account is inactive or suspended ${account_sid}`);
|
||||||
// TODO: alert
|
// TODO: alert
|
||||||
return res.send(503, {headers: {'X-Reason': 'Account exists but is inactive'}});
|
return res.send(503, {headers: {'X-Reason': 'Account exists but is inactive'}});
|
||||||
}
|
}
|
||||||
|
// Change the default log level to debug
|
||||||
|
if (account?.enable_debug_log) {
|
||||||
|
req.locals.logger.level = 'debug';
|
||||||
|
}
|
||||||
logger.debug({accountInfo: req.locals?.accountInfo?.account}, `retrieved account info for ${account_sid}`);
|
logger.debug({accountInfo: req.locals?.accountInfo?.account}, `retrieved account info for ${account_sid}`);
|
||||||
next();
|
next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -237,6 +249,9 @@ module.exports = function(srf, logger) {
|
|||||||
logger.debug(`calling to registered user ${req.locals.called_user}, generating dial app`);
|
logger.debug(`calling to registered user ${req.locals.called_user}, generating dial app`);
|
||||||
app = createJambonzApp('user',
|
app = createJambonzApp('user',
|
||||||
{account_sid, name: req.locals.called_user, caller_id: req.locals.callingNumber});
|
{account_sid, name: req.locals.called_user, caller_id: req.locals.callingNumber});
|
||||||
|
} else if (req.locals.conference_id) {
|
||||||
|
logger.debug(`calling to conference ${req.locals.conference_id}, generating conference app`);
|
||||||
|
app = createJambonzApp('conference', {account_sid, name: req.locals.conference_id});
|
||||||
} else if (req.locals.application_sid) {
|
} else if (req.locals.application_sid) {
|
||||||
app = await lookupAppBySid(req.locals.application_sid);
|
app = await lookupAppBySid(req.locals.application_sid);
|
||||||
} else if (req.locals.originatingUser) {
|
} else if (req.locals.originatingUser) {
|
||||||
@@ -321,7 +336,9 @@ module.exports = function(srf, logger) {
|
|||||||
if (arr) {
|
if (arr) {
|
||||||
const google_custom_voice_sid = arr[1];
|
const google_custom_voice_sid = arr[1];
|
||||||
const [custom_voice] = await lookupGoogleCustomVoice(google_custom_voice_sid);
|
const [custom_voice] = await lookupGoogleCustomVoice(google_custom_voice_sid);
|
||||||
if (custom_voice) {
|
//google voice cloning key has size 200kb, jambonz should not resolve the voice here that the app's calling
|
||||||
|
//webhook will receive big payload, tts-task should resolve the voice later.
|
||||||
|
if (!custom_voice.use_voice_cloning_key) {
|
||||||
app2.speech_synthesis_voice = {
|
app2.speech_synthesis_voice = {
|
||||||
reportedUsage: custom_voice.reported_usage,
|
reportedUsage: custom_voice.reported_usage,
|
||||||
model: custom_voice.model
|
model: custom_voice.model
|
||||||
@@ -343,6 +360,17 @@ module.exports = function(srf, logger) {
|
|||||||
direction: CallDirection.Inbound,
|
direction: CallDirection.Inbound,
|
||||||
traceId: rootSpan.traceId
|
traceId: rootSpan.traceId
|
||||||
});
|
});
|
||||||
|
// if transferred call contains callInfo, let update original data to newly created callInfo in this instance.
|
||||||
|
if (app.transferredCall && app.callInfo) {
|
||||||
|
const {direction, callerName, from, to, originatingSipIp, originatingSipTrunkName} = app.callInfo;
|
||||||
|
req.locals.callInfo.direction = direction;
|
||||||
|
req.locals.callInfo.callerName = callerName;
|
||||||
|
req.locals.callInfo.from = from;
|
||||||
|
req.locals.callInfo.to = to;
|
||||||
|
req.locals.callInfo.originatingSipIp = originatingSipIp;
|
||||||
|
req.locals.callInfo.originatingSipTrunkName = originatingSipTrunkName;
|
||||||
|
delete app.callInfo;
|
||||||
|
}
|
||||||
next();
|
next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
span.end();
|
span.end();
|
||||||
@@ -359,7 +387,7 @@ module.exports = function(srf, logger) {
|
|||||||
const {rootSpan, siprec, application:app} = req.locals;
|
const {rootSpan, siprec, application:app} = req.locals;
|
||||||
let span;
|
let span;
|
||||||
try {
|
try {
|
||||||
if (app.tasks && !JAMBONES_MYSQL_REFRESH_TTL) {
|
if (app.tasks && app.tasks?.length > 0 && !JAMBONES_MYSQL_REFRESH_TTL) {
|
||||||
app.tasks = normalizeJambones(logger, app.tasks).map((tdata) => makeTask(logger, tdata));
|
app.tasks = normalizeJambones(logger, app.tasks).map((tdata) => makeTask(logger, tdata));
|
||||||
if (0 === app.tasks.length) throw new Error('no application provided');
|
if (0 === app.tasks.length) throw new Error('no application provided');
|
||||||
return next();
|
return next();
|
||||||
@@ -432,7 +460,7 @@ module.exports = function(srf, logger) {
|
|||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for parsing application'));
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for parsing application'));
|
||||||
logger.info({err}, `Error retrieving or parsing application: ${err?.message}`);
|
logger.info({err}, `Error retrieving or parsing application: ${err?.message}`);
|
||||||
res.send(480, {headers: {'X-Reason': err?.message || 'unknown'}});
|
res.send(480, {headers: {'X-Reason': err?.message || 'unknown'}});
|
||||||
app.requestor.close();
|
app.requestor.close(WS_CLOSE_CODES.GoingAway);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,8 +45,10 @@ class AdultingCallSession extends CallSession {
|
|||||||
return this.sd.ep;
|
return this.sd.ep;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* see note above */
|
// When adulting session kicked from conference, replaceEndpoint is a must
|
||||||
set ep(newEp) {}
|
set ep(newEp) {
|
||||||
|
this.sd.ep = newEp;
|
||||||
|
}
|
||||||
|
|
||||||
get callSid() {
|
get callSid() {
|
||||||
return this.callInfo.callSid;
|
return this.callInfo.callSid;
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ class CallInfo {
|
|||||||
this.sipStatus = 100;
|
this.sipStatus = 100;
|
||||||
this.sipReason = 'Trying';
|
this.sipReason = 'Trying';
|
||||||
this.callStatus = CallStatus.Trying;
|
this.callStatus = CallStatus.Trying;
|
||||||
|
this.sbcCallid = req.get('X-CID');
|
||||||
this.originatingSipIp = req.get('X-Forwarded-For');
|
this.originatingSipIp = req.get('X-Forwarded-For');
|
||||||
this.originatingSipTrunkName = req.get('X-Originating-Carrier');
|
this.originatingSipTrunkName = req.get('X-Originating-Carrier');
|
||||||
const {siprec} = req.locals;
|
const {siprec} = req.locals;
|
||||||
@@ -129,6 +130,7 @@ class CallInfo {
|
|||||||
from: this.from,
|
from: this.from,
|
||||||
to: this.to,
|
to: this.to,
|
||||||
callId: this.callId,
|
callId: this.callId,
|
||||||
|
sbcCallid: this.sbcCallid,
|
||||||
sipStatus: this.sipStatus,
|
sipStatus: this.sipStatus,
|
||||||
sipReason: this.sipReason,
|
sipReason: this.sipReason,
|
||||||
callStatus: this.callStatus,
|
callStatus: this.callStatus,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ const CallSession = require('./call-session');
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
class ConfirmCallSession extends CallSession {
|
class ConfirmCallSession extends CallSession {
|
||||||
constructor({logger, application, dlg, ep, tasks, callInfo, accountInfo, memberId, confName, rootSpan}) {
|
constructor({logger, application, dlg, ep, tasks, callInfo, accountInfo, memberId, confName, rootSpan, req}) {
|
||||||
super({
|
super({
|
||||||
logger,
|
logger,
|
||||||
application,
|
application,
|
||||||
@@ -23,6 +23,7 @@ class ConfirmCallSession extends CallSession {
|
|||||||
});
|
});
|
||||||
this.dlg = dlg;
|
this.dlg = dlg;
|
||||||
this.ep = ep;
|
this.ep = ep;
|
||||||
|
this.req = req;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -70,8 +70,14 @@ class InboundCallSession extends CallSession {
|
|||||||
this._hangup('caller');
|
this._hangup('caller');
|
||||||
}
|
}
|
||||||
|
|
||||||
_jambonzHangup() {
|
_jambonzHangup(reason) {
|
||||||
this._hangup();
|
this.dlg?.destroy({
|
||||||
|
headers: {
|
||||||
|
...(reason && {'X-Reason': reason})
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// kill current task or wakeup the call session.
|
||||||
|
this._callReleased();
|
||||||
}
|
}
|
||||||
|
|
||||||
_hangup(terminatedBy = 'jambonz') {
|
_hangup(terminatedBy = 'jambonz') {
|
||||||
@@ -79,6 +85,7 @@ class InboundCallSession extends CallSession {
|
|||||||
this.logger.info('InboundCallSession:_hangup - race condition, dlg cleared by app hangup');
|
this.logger.info('InboundCallSession:_hangup - race condition, dlg cleared by app hangup');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
this.logger.info(`InboundCallSession: ${terminatedBy} hung up`);
|
||||||
assert(this.dlg.connectTime);
|
assert(this.dlg.connectTime);
|
||||||
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
||||||
this.rootSpan.setAttributes({'call.termination': `hangup by ${terminatedBy}`});
|
this.rootSpan.setAttributes({'call.termination': `hangup by ${terminatedBy}`});
|
||||||
@@ -87,7 +94,6 @@ class InboundCallSession extends CallSession {
|
|||||||
callStatus: CallStatus.Completed,
|
callStatus: CallStatus.Completed,
|
||||||
duration
|
duration
|
||||||
});
|
});
|
||||||
this.logger.info(`InboundCallSession: ${terminatedBy} hung up`);
|
|
||||||
this._callReleased();
|
this._callReleased();
|
||||||
this.req.removeAllListeners('cancel');
|
this.req.removeAllListeners('cancel');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
const CallSession = require('./call-session');
|
const CallSession = require('./call-session');
|
||||||
const {CallStatus} = require('../utils/constants');
|
const {CallStatus} = require('../utils/constants');
|
||||||
const moment = require('moment');
|
const moment = require('moment');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @classdesc Subclass of CallSession. This represents a CallSession that is
|
* @classdesc Subclass of CallSession. This represents a CallSession that is
|
||||||
* created for an outbound call that is initiated via the REST API.
|
* created for an outbound call that is initiated via the REST API.
|
||||||
@@ -42,9 +41,10 @@ class RestCallSession extends CallSession {
|
|||||||
setDialog(dlg) {
|
setDialog(dlg) {
|
||||||
this.dlg = dlg;
|
this.dlg = dlg;
|
||||||
dlg.on('destroy', this._callerHungup.bind(this));
|
dlg.on('destroy', this._callerHungup.bind(this));
|
||||||
|
dlg.on('refer', this._onRefer.bind(this));
|
||||||
|
dlg.on('modify', this._onReinvite.bind(this));
|
||||||
this.wrapDialog(dlg);
|
this.wrapDialog(dlg);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is invoked when the called party hangs up, in order to calculate the call duration.
|
* This is invoked when the called party hangs up, in order to calculate the call duration.
|
||||||
*/
|
*/
|
||||||
@@ -56,14 +56,14 @@ class RestCallSession extends CallSession {
|
|||||||
this._hangup();
|
this._hangup();
|
||||||
}
|
}
|
||||||
|
|
||||||
_hangup(terminatedBy = 'jamboz') {
|
_hangup(terminatedBy = 'jambonz') {
|
||||||
if (this.restDialTask) {
|
if (this.restDialTask) {
|
||||||
this.restDialTask.turnOffAmd();
|
this.restDialTask.turnOffAmd();
|
||||||
}
|
}
|
||||||
this.callInfo.callTerminationBy = terminatedBy;
|
this.callInfo.callTerminationBy = terminatedBy;
|
||||||
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
||||||
this.emit('callStatusChange', {callStatus: CallStatus.Completed, duration});
|
this.emit('callStatusChange', {callStatus: CallStatus.Completed, duration});
|
||||||
this.logger.debug(`RestCallSession: called party hung up by ${terminatedBy}`);
|
this.logger.info(`RestCallSession: called party hung up by ${terminatedBy}`);
|
||||||
this._callReleased();
|
this._callReleased();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { normalizeJambones } = require('@jambonz/verb-specifications');
|
|||||||
const makeTask = require('./make_task');
|
const makeTask = require('./make_task');
|
||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
|
const HttpRequestor = require('../utils/http-requestor');
|
||||||
const WAIT = 'wait';
|
const WAIT = 'wait';
|
||||||
const JOIN = 'join';
|
const JOIN = 'join';
|
||||||
const START = 'start';
|
const START = 'start';
|
||||||
@@ -60,6 +61,8 @@ class Conference extends Task {
|
|||||||
|
|
||||||
this.emitter = new Emitter();
|
this.emitter = new Emitter();
|
||||||
this.results = {};
|
this.results = {};
|
||||||
|
this.coaching = [];
|
||||||
|
this.speakOnlyTo = this.data.speakOnlyTo;
|
||||||
|
|
||||||
// transferred from another server in order to bridge to a local caller?
|
// transferred from another server in order to bridge to a local caller?
|
||||||
if (this.data._ && this.data._.connectTime) {
|
if (this.data._ && this.data._.connectTime) {
|
||||||
@@ -80,7 +83,11 @@ class Conference extends Task {
|
|||||||
// reset answer time if we were transferred from another feature server
|
// reset answer time if we were transferred from another feature server
|
||||||
if (this.connectTime) dlg.connectTime = this.connectTime;
|
if (this.connectTime) dlg.connectTime = this.connectTime;
|
||||||
|
|
||||||
|
if (cs.sipRequestWithinDialogHook) {
|
||||||
|
/* remove any existing listener to escape from duplicating events */
|
||||||
|
this._removeSipIndialogRequestListener(this.dlg);
|
||||||
|
this._initSipIndialogRequestListener(cs, dlg);
|
||||||
|
}
|
||||||
this.ep.on('destroy', this._kicked.bind(this, cs, dlg));
|
this.ep.on('destroy', this._kicked.bind(this, cs, dlg));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -100,6 +107,7 @@ class Conference extends Task {
|
|||||||
|
|
||||||
this.logger.debug(`Conference:exec - conference ${this.confName} is over`);
|
this.logger.debug(`Conference:exec - conference ${this.confName} is over`);
|
||||||
if (this.callMoved !== false) await this.performAction(this.results);
|
if (this.callMoved !== false) await this.performAction(this.results);
|
||||||
|
this._removeSipIndialogRequestListener(dlg);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info(err, `TaskConference:exec - error in conference ${this.confName}`);
|
this.logger.info(err, `TaskConference:exec - error in conference ${this.confName}`);
|
||||||
}
|
}
|
||||||
@@ -115,7 +123,9 @@ class Conference extends Task {
|
|||||||
this.emitter.emit('kill');
|
this.emitter.emit('kill');
|
||||||
await this._doFinalMemberCheck(cs);
|
await this._doFinalMemberCheck(cs);
|
||||||
if (this.ep && this.ep.connected) {
|
if (this.ep && this.ep.connected) {
|
||||||
this.ep.conn.removeAllListeners('esl::event::CUSTOM::*');
|
// drachtio-fsmrf override esl::event::CUSTOM to conference join listerner, After finish the conference
|
||||||
|
// the application need to reset the esl::event::CUSTOM for another use on the same endpoint
|
||||||
|
this.ep.resetEslCustomEvent();
|
||||||
this.ep.api(`conference ${this.confName} kick ${this.memberId}`)
|
this.ep.api(`conference ${this.confName} kick ${this.memberId}`)
|
||||||
.catch((err) => this.logger.info({err}, 'Error kicking participant'));
|
.catch((err) => this.logger.info({err}, 'Error kicking participant'));
|
||||||
}
|
}
|
||||||
@@ -132,15 +142,10 @@ class Conference extends Task {
|
|||||||
* @param {SipDialog} dlg
|
* @param {SipDialog} dlg
|
||||||
*/
|
*/
|
||||||
async _init(cs, dlg) {
|
async _init(cs, dlg) {
|
||||||
const friendlyName = this.confName;
|
|
||||||
const {createHash, retrieveHash} = cs.srf.locals.dbHelpers;
|
const {createHash, retrieveHash} = cs.srf.locals.dbHelpers;
|
||||||
|
this.friendlyName = this.confName;
|
||||||
this.confName = `conf:${cs.accountSid}:${this.confName}`;
|
this.confName = `conf:${cs.accountSid}:${this.confName}`;
|
||||||
|
|
||||||
this.statusParams = Object.assign({
|
|
||||||
conferenceSid: this.confName,
|
|
||||||
friendlyName
|
|
||||||
}, cs.callInfo);
|
|
||||||
|
|
||||||
// check if conference is in progress
|
// check if conference is in progress
|
||||||
const obj = await retrieveHash(this.confName);
|
const obj = await retrieveHash(this.confName);
|
||||||
if (obj) {
|
if (obj) {
|
||||||
@@ -348,7 +353,9 @@ class Conference extends Task {
|
|||||||
Object.assign(opts, {flags: {
|
Object.assign(opts, {flags: {
|
||||||
...(this.endConferenceOnExit && {endconf: true}),
|
...(this.endConferenceOnExit && {endconf: true}),
|
||||||
...(this.startConferenceOnEnter && {moderator: true}),
|
...(this.startConferenceOnEnter && {moderator: true}),
|
||||||
...((this.joinMuted || this.data.speakOnlyTo) && {joinMuted: true}),
|
//https://developer.signalwire.com/freeswitch/FreeSWITCH-Explained/Modules/mod_conference_3965534/
|
||||||
|
// mute | Enter conference muted
|
||||||
|
...((this.joinMuted || this.speakOnlyTo) && {mute: true}),
|
||||||
}});
|
}});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -361,7 +368,7 @@ class Conference extends Task {
|
|||||||
try {
|
try {
|
||||||
const {memberId, confUuid} = await this.ep.join(this.confName, opts);
|
const {memberId, confUuid} = await this.ep.join(this.confName, opts);
|
||||||
this.logger.debug({memberId, confUuid}, `Conference:_joinConference: successfully joined ${this.confName}`);
|
this.logger.debug({memberId, confUuid}, `Conference:_joinConference: successfully joined ${this.confName}`);
|
||||||
this.memberId = memberId;
|
this.memberId = parseInt(memberId, 10);
|
||||||
this.confUuid = confUuid;
|
this.confUuid = confUuid;
|
||||||
|
|
||||||
// set a tag for this member, if provided
|
// set a tag for this member, if provided
|
||||||
@@ -395,8 +402,8 @@ class Conference extends Task {
|
|||||||
.catch((err) => {});
|
.catch((err) => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.data.speakOnlyTo) {
|
if (this.speakOnlyTo) {
|
||||||
this.setCoachMode(this.data.speakOnlyTo);
|
this.setCoachMode(this.speakOnlyTo);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(err, `Failed to join conference ${this.confName}`);
|
this.logger.error(err, `Failed to join conference ${this.confName}`);
|
||||||
@@ -414,6 +421,20 @@ class Conference extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_initSipIndialogRequestListener(cs, dlg) {
|
||||||
|
dlg.on('info', this._onRequestWithinDialog.bind(this, cs));
|
||||||
|
dlg.on('message', this._onRequestWithinDialog.bind(this, cs));
|
||||||
|
}
|
||||||
|
|
||||||
|
_removeSipIndialogRequestListener(dlg) {
|
||||||
|
dlg && dlg.removeAllListeners('message');
|
||||||
|
dlg && dlg.removeAllListeners('info');
|
||||||
|
}
|
||||||
|
|
||||||
|
_onRequestWithinDialog(cs, req, res) {
|
||||||
|
cs._onRequestWithinDialog(req, res);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The conference we have been waiting for has started.
|
* The conference we have been waiting for has started.
|
||||||
* It may be on this server or a different one, and we are
|
* It may be on this server or a different one, and we are
|
||||||
@@ -488,7 +509,7 @@ class Conference extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async doConferenceParticipantAction(cs, opts) {
|
async doConferenceParticipantAction(cs, opts) {
|
||||||
const {action, tag} = opts;
|
const {action, tag, wait_hook } = opts;
|
||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'tag':
|
case 'tag':
|
||||||
@@ -504,7 +525,10 @@ class Conference extends Task {
|
|||||||
await this.clearCoachMode();
|
await this.clearCoachMode();
|
||||||
break;
|
break;
|
||||||
case 'hold':
|
case 'hold':
|
||||||
this.doConferenceHold(cs, {conf_hold_status: 'hold'});
|
this.doConferenceHold(cs, {
|
||||||
|
conf_hold_status: 'hold',
|
||||||
|
...(wait_hook && {wait_hook})
|
||||||
|
});
|
||||||
break;
|
break;
|
||||||
case 'unhold':
|
case 'unhold':
|
||||||
this.doConferenceHold(cs, {conf_hold_status: 'unhold'});
|
this.doConferenceHold(cs, {conf_hold_status: 'unhold'});
|
||||||
@@ -515,8 +539,11 @@ class Conference extends Task {
|
|||||||
case 'unmute':
|
case 'unmute':
|
||||||
this.doConferenceMute(cs, {conf_mute_status: 'unmute'});
|
this.doConferenceMute(cs, {conf_mute_status: 'unmute'});
|
||||||
break;
|
break;
|
||||||
|
case 'kick':
|
||||||
|
this.kickMember(cs);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
this.logger.info(`Conference:doConferenceParticipantState - unhandled action ${action}`);
|
this.logger.info(`Conference:doConferenceParticipantAction - unhandled action ${action}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -538,6 +565,13 @@ class Conference extends Task {
|
|||||||
} while (!this.killed && this.conf_hold_status === 'hold');
|
} while (!this.killed && this.conf_hold_status === 'hold');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* mute or unmute side of the call
|
||||||
|
*/
|
||||||
|
mute(callSid, doMute) {
|
||||||
|
this.doConferenceMute(this.callSession, {conf_mute_status: doMute});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add ourselves to the waitlist of sessions to be notified once
|
* Add ourselves to the waitlist of sessions to be notified once
|
||||||
* the conference starts
|
* the conference starts
|
||||||
@@ -567,7 +601,7 @@ class Conference extends Task {
|
|||||||
_normalizeHook(cs, hook) {
|
_normalizeHook(cs, hook) {
|
||||||
if (typeof hook === 'object') return hook;
|
if (typeof hook === 'object') return hook;
|
||||||
const url = hook.startsWith('/') ?
|
const url = hook.startsWith('/') ?
|
||||||
`${cs.application.requestor.baseUrl}${hook}` :
|
`${cs.application.requestor instanceof HttpRequestor ? cs.application.requestor.baseUrl : ''}${hook}` :
|
||||||
hook;
|
hook;
|
||||||
|
|
||||||
return { url } ;
|
return { url } ;
|
||||||
@@ -586,7 +620,7 @@ class Conference extends Task {
|
|||||||
const response = await this.ep.api('conference', [this.confName, 'get', 'count']);
|
const response = await this.ep.api('conference', [this.confName, 'get', 'count']);
|
||||||
if (response.body && confNoMatch(response.body)) this.participantCount = 0;
|
if (response.body && confNoMatch(response.body)) this.participantCount = 0;
|
||||||
else if (response.body && /^\d+$/.test(response.body)) this.participantCount = parseInt(response.body) - 1;
|
else if (response.body && /^\d+$/.test(response.body)) this.participantCount = parseInt(response.body) - 1;
|
||||||
this.logger.debug({response}, `Conference:_doFinalMemberCheck conference count ${this.participantCount}`);
|
this.logger.debug(`Conference:_doFinalMemberCheck conference count ${this.participantCount}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info({err}, 'Conference:_doFinalMemberCheck error retrieving count (we were probably kicked');
|
this.logger.info({err}, 'Conference:_doFinalMemberCheck error retrieving count (we were probably kicked');
|
||||||
}
|
}
|
||||||
@@ -596,7 +630,7 @@ class Conference extends Task {
|
|||||||
* when we hang up as the last member, the current member count = 1
|
* when we hang up as the last member, the current member count = 1
|
||||||
* when we are kicked out of the call when the moderator leaves, the member count = 0
|
* when we are kicked out of the call when the moderator leaves, the member count = 0
|
||||||
*/
|
*/
|
||||||
if (this.participantCount === 0) {
|
if (this.participantCount === 0 || this.endConferenceOnExit) {
|
||||||
const {deleteKey} = cs.srf.locals.dbHelpers;
|
const {deleteKey} = cs.srf.locals.dbHelpers;
|
||||||
try {
|
try {
|
||||||
this._notifyConferenceEvent(cs, 'end');
|
this._notifyConferenceEvent(cs, 'end');
|
||||||
@@ -604,7 +638,8 @@ class Conference extends Task {
|
|||||||
this.logger.info(`conf ${this.confName} deprovisioned: ${removed ? 'success' : 'failure'}`);
|
this.logger.info(`conf ${this.confName} deprovisioned: ${removed ? 'success' : 'failure'}`);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
this.logger.error(err, `Error deprovisioning conference ${this.confName}`);
|
this.logger.error(err, `Error deprovisioning conference ${this.confName},
|
||||||
|
might be the conference already cleaned by another moderator`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -637,7 +672,8 @@ class Conference extends Task {
|
|||||||
memberId: this.memberId,
|
memberId: this.memberId,
|
||||||
confName: this.confName,
|
confName: this.confName,
|
||||||
tasks,
|
tasks,
|
||||||
rootSpan: cs.rootSpan
|
rootSpan: cs.rootSpan,
|
||||||
|
req: cs.req
|
||||||
});
|
});
|
||||||
await this._playSession.exec();
|
await this._playSession.exec();
|
||||||
this._playSession = null;
|
this._playSession = null;
|
||||||
@@ -681,8 +717,24 @@ class Conference extends Task {
|
|||||||
if (!params.time) params.time = (new Date()).toISOString();
|
if (!params.time) params.time = (new Date()).toISOString();
|
||||||
if (!params.members && typeof this.participantCount === 'number') params.members = this.participantCount;
|
if (!params.members && typeof this.participantCount === 'number') params.members = this.participantCount;
|
||||||
cs.application.requestor
|
cs.application.requestor
|
||||||
.request('verb:hook', this.statusHook, Object.assign(params, this.statusParams, httpHeaders))
|
.request(
|
||||||
.catch((err) => this.logger.info(err, 'Conference:notifyConferenceEvent - error'));
|
'verb:hook',
|
||||||
|
this.statusHook,
|
||||||
|
Object.assign(
|
||||||
|
params,
|
||||||
|
Object.assign(
|
||||||
|
{
|
||||||
|
conferenceSid: this.confName,
|
||||||
|
friendlyName: this.friendlyName,
|
||||||
|
},
|
||||||
|
cs.callInfo.toJSON()
|
||||||
|
),
|
||||||
|
httpHeaders
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.catch((err) =>
|
||||||
|
this.logger.info(err, 'Conference:notifyConferenceEvent - error')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -699,7 +751,12 @@ class Conference extends Task {
|
|||||||
|
|
||||||
// conference event handlers
|
// conference event handlers
|
||||||
_onAddMember(logger, cs, evt) {
|
_onAddMember(logger, cs, evt) {
|
||||||
logger.debug({evt}, `Conference:_onAddMember - member added to conference ${this.confName}`);
|
const memberId = parseInt(evt.getHeader('Member-ID')) ;
|
||||||
|
if (this.speakOnlyTo) {
|
||||||
|
logger.debug(`Conference:_onAddMember - member ${memberId} added to ${this.confName}, updating coaching mode`);
|
||||||
|
this.setCoachMode(this.speakOnlyTo).catch(() => {});
|
||||||
|
}
|
||||||
|
else logger.debug(`Conference:_onAddMember - member ${memberId} added to conference ${this.confName}`);
|
||||||
}
|
}
|
||||||
_onDelMember(logger, cs, evt) {
|
_onDelMember(logger, cs, evt) {
|
||||||
const memberId = parseInt(evt.getHeader('Member-ID')) ;
|
const memberId = parseInt(evt.getHeader('Member-ID')) ;
|
||||||
@@ -734,28 +791,64 @@ class Conference extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_onTag(logger, cs, evt) {
|
||||||
|
const memberId = parseInt(evt.getHeader('Member-ID')) ;
|
||||||
|
const tag = evt.getHeader('Tag') || '';
|
||||||
|
if (memberId !== this.memberId && this.speakOnlyTo) {
|
||||||
|
logger.info(`Conference:_onTag - member ${memberId} set tag to '${tag }'; updating coach mode accordingly`);
|
||||||
|
this.setCoachMode(this.speakOnlyTo).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the conference to "coaching" mode, where the audio of the participant is only heard
|
||||||
|
* by a subset of the participants in the conference.
|
||||||
|
* We do this by first getting all of the members who do *not* have this tag, and then
|
||||||
|
* we configure this members audio to not be sent to them.
|
||||||
|
* @param {string} speakOnlyTo - tag of the members who should receive our audio
|
||||||
|
*
|
||||||
|
* N.B.: this feature requires jambonz patches to freeswitch mod_conference
|
||||||
|
*/
|
||||||
async setCoachMode(speakOnlyTo) {
|
async setCoachMode(speakOnlyTo) {
|
||||||
|
this.speakOnlyTo = speakOnlyTo;
|
||||||
|
if (!this.memberId) {
|
||||||
|
this.logger.info('Conference:_setCoachMode: no member id yet');
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const response = await this.ep.api('conference', [this.confName, 'gettag', speakOnlyTo, 'nomatch']);
|
const members = (await this.ep.getNonMatchingConfParticipants(this.confName, speakOnlyTo))
|
||||||
this.logger.info(`Conference:_setCoachMode: my audio will only be sent to particpants ${response}`);
|
.filter((m) => m !== this.memberId);
|
||||||
await this.ep.api('conference', [this.confName, 'relate', this.memberId, response, 'nospeak']);
|
if (members.length === 0) {
|
||||||
this.speakOnlyTo = speakOnlyTo;
|
this.logger.info({members}, 'Conference:_setCoachMode: all participants have the tag, so all will hear me');
|
||||||
this.coaching = response;
|
if (this.coaching.length) {
|
||||||
|
await this.ep.api('conference', [this.confName, 'relate', this.memberId, this.coaching.join(','), 'clear']);
|
||||||
|
this.coaching = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const memberList = members.join(',');
|
||||||
|
this.logger.info(`Conference:_setCoachMode: my audio will NOT be sent to ${memberList}`);
|
||||||
|
await this.ep.api('conference', [this.confName, 'relate', this.memberId, memberList, 'nospeak']);
|
||||||
|
this.coaching = members;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error({err, speakOnlyTo}, '_setCoachMode: Error');
|
this.logger.error({err, speakOnlyTo}, '_setCoachMode: Error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async clearCoachMode() {
|
async clearCoachMode() {
|
||||||
|
if (!this.memberId) return;
|
||||||
try {
|
try {
|
||||||
if (!this.coaching) {
|
if (this.coaching.length === 0) {
|
||||||
this.logger.info('Conference:_clearCoachMode: no coaching mode to clear');
|
this.logger.info('Conference:_clearCoachMode: no coaching mode to clear');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
this.logger.info(`Conference:_clearCoachMode: now sending my audio to all, including ${this.coaching}`);
|
else {
|
||||||
await this.ep.api('conference', [this.confName, 'relate', this.memberId, this.coaching, 'clear']);
|
const memberList = this.coaching.join(',');
|
||||||
|
this.logger.info(`Conference:_clearCoachMode: now sending my audio to all, including ${memberList}`);
|
||||||
|
await this.ep.api('conference', [this.confName, 'relate', this.memberId, memberList, 'clear']);
|
||||||
|
}
|
||||||
this.speakOnlyTo = null;
|
this.speakOnlyTo = null;
|
||||||
this.coaching = null;
|
this.coaching = [];
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error({err}, '_clearCoachMode: Error');
|
this.logger.error({err}, '_clearCoachMode: Error');
|
||||||
}
|
}
|
||||||
@@ -781,6 +874,16 @@ class Conference extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async kickMember(cs) {
|
||||||
|
assert(cs.isInConference);
|
||||||
|
try {
|
||||||
|
await this.ep.api('conference', [this.confName, 'kick', this.memberId]);
|
||||||
|
this.logger.info(`Conference:kickMember: kick ${this.memberId} out of conference ${this.confName}`);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error({err}, `Error kicking member out of conference for ${this.memberId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Conference;
|
module.exports = Conference;
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ class TaskConfig extends Task {
|
|||||||
'transcribe',
|
'transcribe',
|
||||||
'fillerNoise',
|
'fillerNoise',
|
||||||
'actionHookDelayAction',
|
'actionHookDelayAction',
|
||||||
'boostAudioSignal'
|
'boostAudioSignal',
|
||||||
|
'vad',
|
||||||
|
'ttsStream'
|
||||||
].forEach((k) => this[k] = this.data[k] || {});
|
].forEach((k) => this[k] = this.data[k] || {});
|
||||||
|
|
||||||
if ('notifyEvents' in this.data) {
|
if ('notifyEvents' in this.data) {
|
||||||
@@ -33,7 +35,8 @@ class TaskConfig extends Task {
|
|||||||
'finishOnKey', 'input', 'numDigits', 'minDigits', 'maxDigits',
|
'finishOnKey', 'input', 'numDigits', 'minDigits', 'maxDigits',
|
||||||
'interDigitTimeout', 'bargein', 'dtmfBargein', 'minBargeinWordCount', 'actionHook'
|
'interDigitTimeout', 'bargein', 'dtmfBargein', 'minBargeinWordCount', 'actionHook'
|
||||||
].forEach((k) => {
|
].forEach((k) => {
|
||||||
if (this.bargeIn[k]) this.gatherOpts[k] = this.bargeIn[k];
|
const val = this.bargeIn[k];
|
||||||
|
if (val !== undefined && val !== null) this.gatherOpts[k] = val;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (this.transcribe?.enable) {
|
if (this.transcribe?.enable) {
|
||||||
@@ -43,6 +46,12 @@ class TaskConfig extends Task {
|
|||||||
};
|
};
|
||||||
delete this.transcribeOpts.enable;
|
delete this.transcribeOpts.enable;
|
||||||
}
|
}
|
||||||
|
if (this.ttsStream.enable) {
|
||||||
|
this.sayOpts = {
|
||||||
|
verb: 'say',
|
||||||
|
stream: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (this.data.reset) {
|
if (this.data.reset) {
|
||||||
if (typeof this.data.reset === 'string') this.data.reset = [this.data.reset];
|
if (typeof this.data.reset === 'string') this.data.reset = [this.data.reset];
|
||||||
@@ -70,7 +79,10 @@ class TaskConfig extends Task {
|
|||||||
get hasListen() { return Object.keys(this.listen).length; }
|
get hasListen() { return Object.keys(this.listen).length; }
|
||||||
get hasTranscribe() { return Object.keys(this.transcribe).length; }
|
get hasTranscribe() { return Object.keys(this.transcribe).length; }
|
||||||
get hasDub() { return Object.keys(this.dub).length; }
|
get hasDub() { return Object.keys(this.dub).length; }
|
||||||
|
get hasVad() { return Object.keys(this.vad).length; }
|
||||||
get hasFillerNoise() { return Object.keys(this.fillerNoise).length; }
|
get hasFillerNoise() { return Object.keys(this.fillerNoise).length; }
|
||||||
|
get hasReferHook() { return Object.keys(this.data).includes('referHook'); }
|
||||||
|
get hasTtsStream() { return Object.keys(this.ttsStream).length; }
|
||||||
|
|
||||||
get summary() {
|
get summary() {
|
||||||
const phrase = [];
|
const phrase = [];
|
||||||
@@ -80,13 +92,13 @@ class TaskConfig extends Task {
|
|||||||
|
|
||||||
if (this.bargeIn.enable) phrase.push('enable barge-in');
|
if (this.bargeIn.enable) phrase.push('enable barge-in');
|
||||||
if (this.hasSynthesizer) {
|
if (this.hasSynthesizer) {
|
||||||
const {vendor:v, language:l, voice} = this.synthesizer;
|
const {vendor:v, language:l, voice, label} = this.synthesizer;
|
||||||
const s = `{${v},${l},${voice}}`;
|
const s = `{${v},${l},${voice},${label || 'None'}}`;
|
||||||
phrase.push(`set synthesizer${s}`);
|
phrase.push(`set synthesizer${s}`);
|
||||||
}
|
}
|
||||||
if (this.hasRecognizer) {
|
if (this.hasRecognizer) {
|
||||||
const {vendor:v, language:l} = this.recognizer;
|
const {vendor:v, language:l, label} = this.recognizer;
|
||||||
const s = `{${v},${l}}`;
|
const s = `{${v},${l},${label || 'None'}}`;
|
||||||
phrase.push(`set recognizer${s}`);
|
phrase.push(`set recognizer${s}`);
|
||||||
}
|
}
|
||||||
if (this.hasRecording) phrase.push(this.record.action);
|
if (this.hasRecording) phrase.push(this.record.action);
|
||||||
@@ -101,6 +113,10 @@ class TaskConfig extends Task {
|
|||||||
if (this.notifyEvents) phrase.push(`event notification ${this.notifyEvents ? 'on' : 'off'}`);
|
if (this.notifyEvents) phrase.push(`event notification ${this.notifyEvents ? 'on' : 'off'}`);
|
||||||
if (this.onHoldMusic) phrase.push(`onHoldMusic: ${this.onHoldMusic}`);
|
if (this.onHoldMusic) phrase.push(`onHoldMusic: ${this.onHoldMusic}`);
|
||||||
if ('boostAudioSignal' in this.data) phrase.push(`setGain ${this.data.boostAudioSignal}`);
|
if ('boostAudioSignal' in this.data) phrase.push(`setGain ${this.data.boostAudioSignal}`);
|
||||||
|
if (this.hasReferHook) phrase.push('set referHook');
|
||||||
|
if (this.hasTtsStream) {
|
||||||
|
phrase.push(`${this.ttsStream.enable ? 'enable' : 'disable'} ttsStream`);
|
||||||
|
}
|
||||||
return `${this.name}{${phrase.join(',')}}`;
|
return `${this.name}{${phrase.join(',')}}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,9 +155,8 @@ class TaskConfig extends Task {
|
|||||||
cs.speechSynthesisVendor = this.synthesizer.vendor !== 'default'
|
cs.speechSynthesisVendor = this.synthesizer.vendor !== 'default'
|
||||||
? this.synthesizer.vendor
|
? this.synthesizer.vendor
|
||||||
: cs.speechSynthesisVendor;
|
: cs.speechSynthesisVendor;
|
||||||
cs.speechSynthesisLabel = this.synthesizer.label !== 'default'
|
cs.speechSynthesisLabel = this.synthesizer.label === 'default'
|
||||||
? this.synthesizer.label
|
? cs.speechSynthesisLabel : this.synthesizer.label;
|
||||||
: cs.speechSynthesisLabel;
|
|
||||||
cs.speechSynthesisLanguage = this.synthesizer.language !== 'default'
|
cs.speechSynthesisLanguage = this.synthesizer.language !== 'default'
|
||||||
? this.synthesizer.language
|
? this.synthesizer.language
|
||||||
: cs.speechSynthesisLanguage;
|
: cs.speechSynthesisLanguage;
|
||||||
@@ -153,15 +168,16 @@ class TaskConfig extends Task {
|
|||||||
cs.fallbackSpeechSynthesisVendor = this.synthesizer.fallbackVendor !== 'default'
|
cs.fallbackSpeechSynthesisVendor = this.synthesizer.fallbackVendor !== 'default'
|
||||||
? this.synthesizer.fallbackVendor
|
? this.synthesizer.fallbackVendor
|
||||||
: cs.fallbackSpeechSynthesisVendor;
|
: cs.fallbackSpeechSynthesisVendor;
|
||||||
cs.fallbackSpeechSynthesisLabel = this.synthesizer.fallbackLabel !== 'default'
|
cs.fallbackSpeechSynthesisLabel = this.synthesizer.fallbackLabel === 'default'
|
||||||
? this.synthesizer.fallbackLabel
|
? cs.fallbackSpeechSynthesisLabel : this.synthesizer.fallbackLabel;
|
||||||
: cs.fallbackSpeechSynthesisLabel;
|
|
||||||
cs.fallbackSpeechSynthesisLanguage = this.synthesizer.fallbackLanguage !== 'default'
|
cs.fallbackSpeechSynthesisLanguage = this.synthesizer.fallbackLanguage !== 'default'
|
||||||
? this.synthesizer.fallbackLanguage
|
? this.synthesizer.fallbackLanguage
|
||||||
: cs.fallbackSpeechSynthesisLanguage;
|
: cs.fallbackSpeechSynthesisLanguage;
|
||||||
cs.fallbackSpeechSynthesisVoice = this.synthesizer.fallbackVoice !== 'default'
|
cs.fallbackSpeechSynthesisVoice = this.synthesizer.fallbackVoice !== 'default'
|
||||||
? this.synthesizer.fallbackVoice
|
? this.synthesizer.fallbackVoice
|
||||||
: cs.fallbackSpeechSynthesisVoice;
|
: cs.fallbackSpeechSynthesisVoice;
|
||||||
|
// new vendor is set, reset fallback vendor
|
||||||
|
cs.hasFallbackTts = false;
|
||||||
this.logger.info({synthesizer: this.synthesizer}, 'Config: updated synthesizer');
|
this.logger.info({synthesizer: this.synthesizer}, 'Config: updated synthesizer');
|
||||||
}
|
}
|
||||||
if (this.hasRecognizer) {
|
if (this.hasRecognizer) {
|
||||||
@@ -169,21 +185,22 @@ class TaskConfig extends Task {
|
|||||||
cs.speechRecognizerVendor = this.recognizer.vendor !== 'default'
|
cs.speechRecognizerVendor = this.recognizer.vendor !== 'default'
|
||||||
? this.recognizer.vendor
|
? this.recognizer.vendor
|
||||||
: cs.speechRecognizerVendor;
|
: cs.speechRecognizerVendor;
|
||||||
cs.speechRecognizerLabel = this.recognizer.label !== 'default'
|
cs.speechRecognizerLabel = this.recognizer.label === 'default'
|
||||||
? this.recognizer.label
|
? cs.speechRecognizerLabel : this.recognizer.label;
|
||||||
: cs.speechRecognizerLabel;
|
cs.speechRecognizerLanguage = this.recognizer.language !== undefined && this.recognizer.language !== 'default'
|
||||||
cs.speechRecognizerLanguage = this.recognizer.language !== 'default'
|
|
||||||
? this.recognizer.language
|
? this.recognizer.language
|
||||||
: cs.speechRecognizerLanguage;
|
: cs.speechRecognizerLanguage;
|
||||||
|
|
||||||
//fallback
|
//fallback
|
||||||
cs.fallbackSpeechRecognizerVendor = this.recognizer.fallbackVendor !== 'default'
|
cs.fallbackSpeechRecognizerVendor = this.recognizer.fallbackVendor !== undefined &&
|
||||||
|
this.recognizer.fallbackVendor !== 'default'
|
||||||
? this.recognizer.fallbackVendor
|
? this.recognizer.fallbackVendor
|
||||||
: cs.fallbackSpeechRecognizerVendor;
|
: cs.fallbackSpeechRecognizerVendor;
|
||||||
cs.fallbackSpeechRecognizerLabel = this.recognizer.fallbackLabel !== 'default'
|
cs.fallbackSpeechRecognizerLabel = this.recognizer.fallbackLabel === 'default' ?
|
||||||
? this.recognizer.fallbackLabel
|
cs.fallbackSpeechRecognizerLabel :
|
||||||
: cs.fallbackSpeechRecognizerLabel;
|
this.recognizer.fallbackLabel;
|
||||||
cs.fallbackSpeechRecognizerLanguage = this.recognizer.fallbackLanguage !== 'default'
|
cs.fallbackSpeechRecognizerLanguage = this.recognizer.fallbackLanguage !== undefined &&
|
||||||
|
this.recognizer.fallbackLanguage !== 'default'
|
||||||
? this.recognizer.fallbackLanguage
|
? this.recognizer.fallbackLanguage
|
||||||
: cs.fallbackSpeechRecognizerLanguage;
|
: cs.fallbackSpeechRecognizerLanguage;
|
||||||
|
|
||||||
@@ -206,6 +223,8 @@ class TaskConfig extends Task {
|
|||||||
if ('punctuation' in this.recognizer) {
|
if ('punctuation' in this.recognizer) {
|
||||||
cs.globalSttPunctuation = this.recognizer.punctuation;
|
cs.globalSttPunctuation = this.recognizer.punctuation;
|
||||||
}
|
}
|
||||||
|
// new vendor is set, reset fallback vendor
|
||||||
|
cs.hasFallbackAsr = false;
|
||||||
this.logger.info({
|
this.logger.info({
|
||||||
recognizer: this.recognizer,
|
recognizer: this.recognizer,
|
||||||
isContinuousAsr: cs.isContinuousAsr
|
isContinuousAsr: cs.isContinuousAsr
|
||||||
@@ -246,12 +265,14 @@ class TaskConfig extends Task {
|
|||||||
}
|
}
|
||||||
if (this.hasTranscribe) {
|
if (this.hasTranscribe) {
|
||||||
if (this.transcribe.enable) {
|
if (this.transcribe.enable) {
|
||||||
this.transcribeOpts.recognizer = this.hasRecognizer ?
|
if (!this.transcribeOpts.recognizer) {
|
||||||
this.recognizer :
|
this.transcribeOpts.recognizer = this.hasRecognizer ?
|
||||||
{
|
this.recognizer :
|
||||||
vendor: cs.speechRecognizerVendor,
|
{
|
||||||
language: cs.speechRecognizerLanguage
|
vendor: cs.speechRecognizerVendor,
|
||||||
};
|
language: cs.speechRecognizerLanguage
|
||||||
|
};
|
||||||
|
}
|
||||||
this.logger.debug(this.transcribeOpts, 'Config: enabling transcribe');
|
this.logger.debug(this.transcribeOpts, 'Config: enabling transcribe');
|
||||||
cs.startBackgroundTask('transcribe', this.transcribeOpts);
|
cs.startBackgroundTask('transcribe', this.transcribeOpts);
|
||||||
} else {
|
} else {
|
||||||
@@ -259,13 +280,8 @@ class TaskConfig extends Task {
|
|||||||
cs.stopBackgroundTask('transcribe');
|
cs.stopBackgroundTask('transcribe');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (Object.keys(this.actionHookDelayAction).length !== 0) {
|
||||||
if (this.actionHookDelayAction) {
|
cs.actionHookDelayProperties = this.actionHookDelayAction;
|
||||||
cs.actionHookDelayEnabled = this.actionHookDelayAction.enabled || false;
|
|
||||||
cs.actionHookNoResponseTimeout = this.actionHookDelayAction.noResponseTimeout || 0;
|
|
||||||
cs.actionHookNoResponseGiveUpTimeout = this.actionHookDelayAction.noResponseGiveUpTimeout || 0;
|
|
||||||
cs.actionHookDelayRetries = this.actionHookDelayAction.retries || 1;
|
|
||||||
cs.actionHookDelayActions = this.actionHookDelayAction.actions || [];
|
|
||||||
}
|
}
|
||||||
if (this.data.sipRequestWithinDialogHook) {
|
if (this.data.sipRequestWithinDialogHook) {
|
||||||
cs.sipRequestWithinDialogHook = this.data.sipRequestWithinDialogHook;
|
cs.sipRequestWithinDialogHook = this.data.sipRequestWithinDialogHook;
|
||||||
@@ -288,6 +304,36 @@ class TaskConfig extends Task {
|
|||||||
cs.enableFillerNoise(opts);
|
cs.enableFillerNoise(opts);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.hasVad) {
|
||||||
|
cs.vad = {
|
||||||
|
enable: this.vad.enable || false,
|
||||||
|
voiceMs: this.vad.voiceMs || 250,
|
||||||
|
silenceMs: this.vad.silenceMs || 150,
|
||||||
|
strategy: this.vad.strategy || 'one-shot',
|
||||||
|
mode: (this.vad.mode !== undefined && this.vad.mode !== null) ? this.vad.mode : 2
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.hasReferHook) {
|
||||||
|
cs.referHook = this.data.referHook;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.ttsStream.enable && this.sayOpts) {
|
||||||
|
this.sayOpts.synthesizer = this.hasSynthesizer ? this.synthesizer : {
|
||||||
|
vendor: cs.speechSynthesisVendor,
|
||||||
|
language: cs.speechSynthesisLanguage,
|
||||||
|
voice: cs.speechSynthesisVoice,
|
||||||
|
...(cs.speechSynthesisLabel && {
|
||||||
|
label: cs.speechSynthesisLabel
|
||||||
|
})
|
||||||
|
};
|
||||||
|
this.logger.info({opts: this.gatherOpts}, 'Config: enabling ttsStream');
|
||||||
|
cs.enableBackgroundTtsStream(this.sayOpts);
|
||||||
|
} else if (!this.ttsStream.enable) {
|
||||||
|
this.logger.info('Config: disabling ttsStream');
|
||||||
|
cs.disableTtsStream();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async kill(cs) {
|
async kill(cs) {
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ const {TaskName, TaskPreconditions, DequeueResults, BONG_TONE} = require('../uti
|
|||||||
const Emitter = require('events');
|
const Emitter = require('events');
|
||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
|
const { sleepFor } = require('../utils/helpers');
|
||||||
const sleepFor = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
|
|
||||||
|
|
||||||
const getUrl = (cs) => `${cs.srf.locals.serviceUrl}/v1/dequeue/${cs.callSid}`;
|
const getUrl = (cs) => `${cs.srf.locals.serviceUrl}/v1/dequeue/${cs.callSid}`;
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const {
|
|||||||
TaskName,
|
TaskName,
|
||||||
TaskPreconditions,
|
TaskPreconditions,
|
||||||
MAX_SIMRINGS,
|
MAX_SIMRINGS,
|
||||||
|
MediaPath,
|
||||||
KillReason
|
KillReason
|
||||||
} = require('../utils/constants');
|
} = require('../utils/constants');
|
||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
@@ -17,9 +18,13 @@ const dbUtils = require('../utils/db-utils');
|
|||||||
const parseDecibels = require('../utils/parse-decibels');
|
const parseDecibels = require('../utils/parse-decibels');
|
||||||
const debug = require('debug')('jambonz:feature-server');
|
const debug = require('debug')('jambonz:feature-server');
|
||||||
const {parseUri} = require('drachtio-srf');
|
const {parseUri} = require('drachtio-srf');
|
||||||
const {ANCHOR_MEDIA_ALWAYS, JAMBONZ_DISABLE_DIAL_PAI_HEADER} = require('../config');
|
const {ANCHOR_MEDIA_ALWAYS,
|
||||||
|
JAMBONZ_DISABLE_DIAL_PAI_HEADER,
|
||||||
|
JAMBONES_DIAL_SBC_FOR_REGISTERED_USER} = require('../config');
|
||||||
const { isOnhold, isOpusFirst } = require('../utils/sdp-utils');
|
const { isOnhold, isOpusFirst } = require('../utils/sdp-utils');
|
||||||
const { normalizeJambones } = require('@jambonz/verb-specifications');
|
const { normalizeJambones } = require('@jambonz/verb-specifications');
|
||||||
|
const { selectHostPort } = require('../utils/network');
|
||||||
|
const { sleepFor } = require('../utils/helpers');
|
||||||
|
|
||||||
function parseDtmfOptions(logger, dtmfCapture) {
|
function parseDtmfOptions(logger, dtmfCapture) {
|
||||||
let parentDtmfCollector, childDtmfCollector;
|
let parentDtmfCollector, childDtmfCollector;
|
||||||
@@ -103,6 +108,7 @@ class TaskDial extends Task {
|
|||||||
this.proxy = this.data.proxy;
|
this.proxy = this.data.proxy;
|
||||||
this.tag = this.data.tag;
|
this.tag = this.data.tag;
|
||||||
this.boostAudioSignal = this.data.boostAudioSignal;
|
this.boostAudioSignal = this.data.boostAudioSignal;
|
||||||
|
this._mediaPath = MediaPath.FullMedia;
|
||||||
|
|
||||||
if (this.dtmfHook) {
|
if (this.dtmfHook) {
|
||||||
const {parentDtmfCollector, childDtmfCollector} = parseDtmfOptions(logger, this.data.dtmfCapture || {});
|
const {parentDtmfCollector, childDtmfCollector} = parseDtmfOptions(logger, this.data.dtmfCapture || {});
|
||||||
@@ -114,8 +120,9 @@ class TaskDial extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.data.listen) {
|
const listenData = this.data.listen || this.data.stream;
|
||||||
this.listenTask = makeTask(logger, {'listen': this.data.listen}, this);
|
if (listenData) {
|
||||||
|
this.listenTask = makeTask(logger, {'listen': listenData }, this);
|
||||||
}
|
}
|
||||||
if (this.data.transcribe) {
|
if (this.data.transcribe) {
|
||||||
this.transcribeTask = makeTask(logger, {'transcribe' : this.data.transcribe}, this);
|
this.transcribeTask = makeTask(logger, {'transcribe' : this.data.transcribe}, this);
|
||||||
@@ -150,17 +157,21 @@ class TaskDial extends Task {
|
|||||||
|
|
||||||
get canReleaseMedia() {
|
get canReleaseMedia() {
|
||||||
const keepAnchor = this.data.anchorMedia ||
|
const keepAnchor = this.data.anchorMedia ||
|
||||||
this.cs.isBackGroundListen ||
|
this.cs.isBackGroundListen ||
|
||||||
this.cs.onHoldMusic ||
|
this.cs.onHoldMusic ||
|
||||||
ANCHOR_MEDIA_ALWAYS ||
|
ANCHOR_MEDIA_ALWAYS ||
|
||||||
this.listenTask ||
|
this.listenTask ||
|
||||||
this.dubTasks ||
|
this.dubTasks ||
|
||||||
this.transcribeTask ||
|
this.transcribeTask ||
|
||||||
this.startAmd;
|
this.startAmd;
|
||||||
|
|
||||||
return !keepAnchor;
|
return !keepAnchor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get shouldExitMediaPathEntirely() {
|
||||||
|
return this.data.exitMediaPath;
|
||||||
|
}
|
||||||
|
|
||||||
get summary() {
|
get summary() {
|
||||||
if (this.target.length === 1) {
|
if (this.target.length === 1) {
|
||||||
const target = this.target[0];
|
const target = this.target[0];
|
||||||
@@ -181,6 +192,16 @@ class TaskDial extends Task {
|
|||||||
|
|
||||||
async exec(cs) {
|
async exec(cs) {
|
||||||
await super.exec(cs);
|
await super.exec(cs);
|
||||||
|
|
||||||
|
if (this.data.anchorMedia && this.data.exitMediaPath) {
|
||||||
|
this.logger.info('Dial:exec - incompatible anchorMedia and exitMediaPath are both set, will obey anchorMedia');
|
||||||
|
delete this.data.exitMediaPath;
|
||||||
|
}
|
||||||
|
if (!this.canReleaseMedia && this.data.exitMediaPath) {
|
||||||
|
this.logger.info(
|
||||||
|
'Dial:exec - exitMediaPath is set so features such as transcribe and record will not work on this call');
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (this.listenTask) {
|
if (this.listenTask) {
|
||||||
const {span, ctx} = this.startChildSpan(`nested:${this.listenTask.summary}`);
|
const {span, ctx} = this.startChildSpan(`nested:${this.listenTask.summary}`);
|
||||||
@@ -203,7 +224,16 @@ class TaskDial extends Task {
|
|||||||
else {
|
else {
|
||||||
this.epOther = cs.ep;
|
this.epOther = cs.ep;
|
||||||
if (this.dialMusic && this.epOther && this.epOther.connected) {
|
if (this.dialMusic && this.epOther && this.epOther.connected) {
|
||||||
this.epOther.play(this.dialMusic).catch((err) => {});
|
(async() => {
|
||||||
|
do {
|
||||||
|
try {
|
||||||
|
await this.epOther.play(this.dialMusic);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(err, `TaskDial:exec error playing dialMusic ${this.dialMusic}`);
|
||||||
|
await sleepFor(1000);
|
||||||
|
}
|
||||||
|
} while (!this.killed && !this.bridged && this._mediaPath === MediaPath.FullMedia);
|
||||||
|
})();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!this.killed) await this._attemptCalls(cs);
|
if (!this.killed) await this._attemptCalls(cs);
|
||||||
@@ -243,7 +273,9 @@ class TaskDial extends Task {
|
|||||||
this._removeDtmfDetection(this.dlg);
|
this._removeDtmfDetection(this.dlg);
|
||||||
await this._killOutdials();
|
await this._killOutdials();
|
||||||
if (this.sd) {
|
if (this.sd) {
|
||||||
this.sd.kill();
|
const byeReasonHeader = this.killReason === KillReason.MediaTimeout ? 'Media Timeout' : undefined;
|
||||||
|
this.sd.kill(byeReasonHeader);
|
||||||
|
this.sd.ep?.removeListener('destroy', this._handleMediaTimeout.bind(this));
|
||||||
this.sd.removeAllListeners();
|
this.sd.removeAllListeners();
|
||||||
this.sd = null;
|
this.sd = null;
|
||||||
}
|
}
|
||||||
@@ -289,7 +321,7 @@ class TaskDial extends Task {
|
|||||||
if (!cs.callGone && this.epOther) {
|
if (!cs.callGone && this.epOther) {
|
||||||
|
|
||||||
/* if we can release the media back to the SBC, do so now */
|
/* if we can release the media back to the SBC, do so now */
|
||||||
if (this.canReleaseMedia) this._releaseMedia(cs, this.sd);
|
if (this.canReleaseMedia) this._releaseMedia(cs, this.sd, this.shouldExitMediaPathEntirely);
|
||||||
else this.epOther.bridge(this.ep);
|
else this.epOther.bridge(this.ep);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -329,17 +361,26 @@ class TaskDial extends Task {
|
|||||||
|
|
||||||
const to = parseUri(req.getParsedHeader('Refer-To').uri);
|
const to = parseUri(req.getParsedHeader('Refer-To').uri);
|
||||||
const by = parseUri(req.getParsedHeader('Referred-By').uri);
|
const by = parseUri(req.getParsedHeader('Referred-By').uri);
|
||||||
|
const referredBy = req.get('Referred-By');
|
||||||
|
const userAgent = req.get('User-Agent');
|
||||||
|
const customHeaders = Object.keys(req.headers)
|
||||||
|
.filter((h) => h.toLowerCase().startsWith('x-'))
|
||||||
|
.reduce((acc, h) => {
|
||||||
|
acc[h] = req.get(h);
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
this.logger.info({to}, 'refer to parsed');
|
this.logger.info({to}, 'refer to parsed');
|
||||||
const json = await cs.requestor.request('verb:hook', this.referHook, {
|
const json = await cs.requestor.request('verb:hook', this.referHook, {
|
||||||
...(callInfo.toJSON()),
|
...(callInfo.toJSON()),
|
||||||
refer_details: {
|
refer_details: {
|
||||||
sip_refer_to: req.get('Refer-To'),
|
sip_refer_to: req.get('Refer-To'),
|
||||||
sip_referred_by: req.get('Referred-By'),
|
|
||||||
sip_user_agent: req.get('User-Agent'),
|
|
||||||
refer_to_user: to.scheme === 'tel' ? to.number : to.user,
|
refer_to_user: to.scheme === 'tel' ? to.number : to.user,
|
||||||
referred_by_user: by.scheme === 'tel' ? by.number : by.user,
|
...(referredBy && {sip_referred_by: referredBy}),
|
||||||
|
...(userAgent && {sip_user_agent: userAgent}),
|
||||||
|
...(by && {referred_by_user: by.scheme === 'tel' ? by.number : by.user}),
|
||||||
referring_call_sid,
|
referring_call_sid,
|
||||||
referred_call_sid
|
referred_call_sid,
|
||||||
|
...customHeaders
|
||||||
}
|
}
|
||||||
}, httpHeaders);
|
}, httpHeaders);
|
||||||
if (json && Array.isArray(json)) {
|
if (json && Array.isArray(json)) {
|
||||||
@@ -365,9 +406,13 @@ class TaskDial extends Task {
|
|||||||
this.logger.info(err, 'Dial:handleRefer - error setting new application after receiving REFER');
|
this.logger.info(err, 'Dial:handleRefer - error setting new application after receiving REFER');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//caller and callee legs are briged together, accept refer with 202 will release callee leg endpoint
|
||||||
|
//that makes freeswitch release endpoint for caller leg.
|
||||||
|
if (this.ep) this.ep.unbridge();
|
||||||
res.send(202);
|
res.send(202);
|
||||||
this.logger.info('DialTask:handleRefer - sent 202 Accepted');
|
this.logger.info('DialTask:handleRefer - sent 202 Accepted');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'DialTask:handleRefer - error processing incoming REFER');
|
||||||
res.send(err.statusCode || 501);
|
res.send(err.statusCode || 501);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -453,7 +498,7 @@ class TaskDial extends Task {
|
|||||||
dlg && dlg.removeAllListeners('info');
|
dlg && dlg.removeAllListeners('info');
|
||||||
}
|
}
|
||||||
|
|
||||||
async _onRequestWithinDialog(cs, req, res) {
|
_onRequestWithinDialog(cs, req, res) {
|
||||||
cs._onRequestWithinDialog(req, res);
|
cs._onRequestWithinDialog(req, res);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,11 +518,11 @@ class TaskDial extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async _attemptCalls(cs) {
|
async _attemptCalls(cs) {
|
||||||
const {req, srf} = cs;
|
const {req, callInfo, direction, srf} = cs;
|
||||||
const {getSBC} = srf.locals;
|
const {getSBC} = srf.locals;
|
||||||
const {lookupTeamsByAccount, lookupAccountBySid} = srf.locals.dbHelpers;
|
const {lookupTeamsByAccount, lookupAccountBySid} = srf.locals.dbHelpers;
|
||||||
const {lookupCarrier, lookupCarrierByPhoneNumber} = dbUtils(this.logger, cs.srf);
|
const {lookupCarrier, lookupCarrierByPhoneNumber, lookupVoipCarrierBySid} = dbUtils(this.logger, cs.srf);
|
||||||
const sbcAddress = this.proxy || getSBC();
|
let sbcAddress = this.proxy || getSBC();
|
||||||
const teamsInfo = {};
|
const teamsInfo = {};
|
||||||
let fqdn;
|
let fqdn;
|
||||||
|
|
||||||
@@ -485,19 +530,28 @@ class TaskDial extends Task {
|
|||||||
this.headers = {
|
this.headers = {
|
||||||
'X-Account-Sid': cs.accountSid,
|
'X-Account-Sid': cs.accountSid,
|
||||||
...(req && req.has('X-CID') && {'X-CID': req.get('X-CID')}),
|
...(req && req.has('X-CID') && {'X-CID': req.get('X-CID')}),
|
||||||
...(req && req.has('P-Asserted-Identity') && !JAMBONZ_DISABLE_DIAL_PAI_HEADER &&
|
...(direction === 'outbound' && callInfo.sbcCallid && {'X-CID': callInfo.sbcCallid}),
|
||||||
{'P-Asserted-Identity': req.get('P-Asserted-Identity')}),
|
...(!JAMBONZ_DISABLE_DIAL_PAI_HEADER && req && {
|
||||||
|
...(req.has('P-Asserted-Identity') && {'P-Asserted-Identity': req.get('P-Asserted-Identity')}),
|
||||||
|
...(req.has('Privacy') && {'Privacy': req.get('Privacy')}),
|
||||||
|
}),
|
||||||
...(req && req.has('X-Voip-Carrier-Sid') && {'X-Voip-Carrier-Sid': req.get('X-Voip-Carrier-Sid')}),
|
...(req && req.has('X-Voip-Carrier-Sid') && {'X-Voip-Carrier-Sid': req.get('X-Voip-Carrier-Sid')}),
|
||||||
// Put headers at the end to make sure opt.headers override all default behavior.
|
// Put headers at the end to make sure opt.headers override all default behavior.
|
||||||
...this.headers
|
...this.headers
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// default to inband dtmf if not specified
|
||||||
|
this.inbandDtmfEnabled = cs.inbandDtmfEnabled;
|
||||||
|
// get calling user from From header
|
||||||
|
const parsedFrom = req.getParsedHeader('from');
|
||||||
|
const fromUri = parseUri(parsedFrom.uri);
|
||||||
const opts = {
|
const opts = {
|
||||||
headers: this.headers,
|
headers: this.headers,
|
||||||
proxy: `sip:${sbcAddress}`,
|
proxy: `sip:${sbcAddress}`,
|
||||||
callingNumber: this.callerId || req.callingNumber,
|
callingNumber: this.callerId || fromUri.user,
|
||||||
...(this.callerName && {callingName: this.callerName}),
|
...(this.callerName && {callingName: this.callerName}),
|
||||||
opusFirst: isOpusFirst(this.cs.ep.remote.sdp)
|
opusFirst: isOpusFirst(this.cs.ep.remote.sdp),
|
||||||
|
isVideoCall: this.cs.ep.remote.sdp.includes('m=video')
|
||||||
};
|
};
|
||||||
|
|
||||||
const t = this.target.find((t) => t.type === 'teams');
|
const t = this.target.find((t) => t.type === 'teams');
|
||||||
@@ -541,6 +595,15 @@ class TaskDial extends Task {
|
|||||||
this.logger.error({err}, 'Error looking up account by sid');
|
this.logger.error({err}, 'Error looking up account by sid');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// find handling sbc sip for called user
|
||||||
|
if (JAMBONES_DIAL_SBC_FOR_REGISTERED_USER && t.type === 'user') {
|
||||||
|
const { registrar } = srf.locals.dbHelpers;
|
||||||
|
const reg = await registrar.query(t.name);
|
||||||
|
if (reg) {
|
||||||
|
sbcAddress = selectHostPort(this.logger, reg.sbcAddress, 'tcp')[1];
|
||||||
|
}
|
||||||
|
//sbc outbound return 404 Notfound to handle case called user is not reigstered.
|
||||||
|
}
|
||||||
if (t.type === 'phone' && t.trunk) {
|
if (t.type === 'phone' && t.trunk) {
|
||||||
const voip_carrier_sid = await lookupCarrier(cs.accountSid, t.trunk);
|
const voip_carrier_sid = await lookupCarrier(cs.accountSid, t.trunk);
|
||||||
this.logger.info(`Dial:_attemptCalls: selected ${voip_carrier_sid} for requested carrier: ${t.trunk}`);
|
this.logger.info(`Dial:_attemptCalls: selected ${voip_carrier_sid} for requested carrier: ${t.trunk}`);
|
||||||
@@ -557,10 +620,17 @@ class TaskDial extends Task {
|
|||||||
const str = this.callerId || req.callingNumber || '';
|
const str = this.callerId || req.callingNumber || '';
|
||||||
const callingNumber = str.startsWith('+') ? str.substring(1) : str;
|
const callingNumber = str.startsWith('+') ? str.substring(1) : str;
|
||||||
const voip_carrier_sid = await lookupCarrierByPhoneNumber(cs.accountSid, callingNumber);
|
const voip_carrier_sid = await lookupCarrierByPhoneNumber(cs.accountSid, callingNumber);
|
||||||
|
const req_voip_carrier_sid = req.has('X-Voip-Carrier-Sid') ? req.get('X-Voip-Carrier-Sid') : null;
|
||||||
if (voip_carrier_sid) {
|
if (voip_carrier_sid) {
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`Dial:_attemptCalls: selected voip_carrier_sid ${voip_carrier_sid} for callingNumber: ${callingNumber}`);
|
`Dial:_attemptCalls: selected voip_carrier_sid ${voip_carrier_sid} for callingNumber: ${callingNumber}`);
|
||||||
opts.headers['X-Requested-Carrier-Sid'] = voip_carrier_sid;
|
opts.headers['X-Requested-Carrier-Sid'] = voip_carrier_sid;
|
||||||
|
|
||||||
|
// Checking if outbound carrier is different from inbound carrier and has dtmf type tones
|
||||||
|
if (voip_carrier_sid !== req_voip_carrier_sid) {
|
||||||
|
const [voipCarrier] = await lookupVoipCarrierBySid(voip_carrier_sid);
|
||||||
|
this.inbandDtmfEnabled = voipCarrier?.dtmf_type === 'tones';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -601,6 +671,7 @@ class TaskDial extends Task {
|
|||||||
dialCallStatus: obj.callStatus,
|
dialCallStatus: obj.callStatus,
|
||||||
dialSipStatus: obj.sipStatus,
|
dialSipStatus: obj.sipStatus,
|
||||||
dialCallSid: sd.callSid,
|
dialCallSid: sd.callSid,
|
||||||
|
dialSbcCallid: sd.callInfo.sbcCallid
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
switch (obj.callStatus) {
|
switch (obj.callStatus) {
|
||||||
@@ -636,6 +707,8 @@ class TaskDial extends Task {
|
|||||||
await this._connectSingleDial(cs, sd);
|
await this._connectSingleDial(cs, sd);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info({err}, 'Dial:_attemptCalls - Error calling _connectSingleDial ');
|
this.logger.info({err}, 'Dial:_attemptCalls - Error calling _connectSingleDial ');
|
||||||
|
sd.removeAllListeners();
|
||||||
|
this.kill(cs);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.on('decline', () => {
|
.on('decline', () => {
|
||||||
@@ -714,7 +787,7 @@ class TaskDial extends Task {
|
|||||||
// Offhold, time to release media
|
// Offhold, time to release media
|
||||||
const newSdp = await this.ep.modify(req.body);
|
const newSdp = await this.ep.modify(req.body);
|
||||||
await res.send(200, {body: newSdp});
|
await res.send(200, {body: newSdp});
|
||||||
await this._releaseMedia(this.cs, this.sd);
|
await this._releaseMedia(this.cs, this.sd, this.shouldExitMediaPathEntirely);
|
||||||
this.isOutgoingLegHold = false;
|
this.isOutgoingLegHold = false;
|
||||||
} else {
|
} else {
|
||||||
this.logger.debug('Dial: _onReinvite receive unhold Request, update media server');
|
this.logger.debug('Dial: _onReinvite receive unhold Request, update media server');
|
||||||
@@ -798,10 +871,14 @@ class TaskDial extends Task {
|
|||||||
|
|
||||||
if (this.parentDtmfCollector) this._installDtmfDetection(cs, cs.dlg);
|
if (this.parentDtmfCollector) this._installDtmfDetection(cs, cs.dlg);
|
||||||
if (this.childDtmfCollector) this._installDtmfDetection(cs, this.dlg);
|
if (this.childDtmfCollector) this._installDtmfDetection(cs, this.dlg);
|
||||||
if (cs.sipRequestWithinDialogHook) this._initSipIndialogRequestListener(cs, this.dlg);
|
if (cs.sipRequestWithinDialogHook) {
|
||||||
|
/* remove any existing listener to escape from duplicating events */
|
||||||
|
this._removeSipIndialogRequestListener(this.dlg);
|
||||||
|
this._initSipIndialogRequestListener(cs, this.dlg);
|
||||||
|
}
|
||||||
|
|
||||||
if (this.transcribeTask) this.transcribeTask.exec(cs, {ep: this.epOther, ep2:this.ep});
|
if (this.transcribeTask) this.transcribeTask.exec(cs, {ep: this.epOther, ep2:this.ep});
|
||||||
if (this.listenTask) this.listenTask.exec(cs, {ep: this.epOther});
|
if (this.listenTask) this.listenTask.exec(cs, {ep: this.listenTask.channel === 2 ? this.ep : this.epOther});
|
||||||
if (this.startAmd) {
|
if (this.startAmd) {
|
||||||
try {
|
try {
|
||||||
this.startAmd(cs, this.ep, this, this.data.amd);
|
this.startAmd(cs, this.ep, this, this.data.amd);
|
||||||
@@ -823,7 +900,17 @@ class TaskDial extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* if we can release the media back to the SBC, do so now */
|
/* if we can release the media back to the SBC, do so now */
|
||||||
if (this.canReleaseMedia) setTimeout(this._releaseMedia.bind(this, cs, sd), 200);
|
if (this.canReleaseMedia || this.shouldExitMediaPathEntirely) {
|
||||||
|
setTimeout(this._releaseMedia.bind(this, cs, sd, this.shouldExitMediaPathEntirely), 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sd.ep.once('destroy', this._handleMediaTimeout.bind(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
_handleMediaTimeout(evt) {
|
||||||
|
if (evt?.reason === 'MEDIA_TIMEOUT' && this.sd && this.bridged) {
|
||||||
|
this.kill(this.cs, KillReason.MediaTimeout);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_bridgeEarlyMedia(sd) {
|
_bridgeEarlyMedia(sd) {
|
||||||
@@ -835,22 +922,57 @@ class TaskDial extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* public api */
|
||||||
|
async updateMediaPath(desiredPath) {
|
||||||
|
this.logger.info(`Dial:updateMediaPath - ${this._mediaPath} => ${desiredPath}`);
|
||||||
|
switch (desiredPath) {
|
||||||
|
case MediaPath.NoMedia:
|
||||||
|
assert(this._mediaPath !== MediaPath.NoMedia, 'updateMediaPath: already no-media');
|
||||||
|
await this._releaseMedia(this.cs, this.sd, true);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MediaPath.PartialMedia:
|
||||||
|
assert(this._mediaPath !== MediaPath.PartialMedia, 'updateMediaPath: already partial-media');
|
||||||
|
if (this._mediaPath === MediaPath.FullMedia) {
|
||||||
|
await this._releaseMedia(this.cs, this.sd, false);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// to go from no-media to partial-media we need to go through full-media first
|
||||||
|
await this.reAnchorMedia(this.cs, this.sd);
|
||||||
|
await this._releaseMedia(this.cs, this.sd, false);
|
||||||
|
}
|
||||||
|
assert(!this.epOther, 'updateMediaPath: epOther should be null');
|
||||||
|
assert(!this.ep, 'updateMediaPath: ep should be null');
|
||||||
|
|
||||||
|
break;
|
||||||
|
case MediaPath.FullMedia:
|
||||||
|
assert(this._mediaPath !== MediaPath.FullMedia, 'updateMediaPath: already full-media');
|
||||||
|
await this.reAnchorMedia(this.cs, this.sd);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false, `updateMediaPath: invalid path request ${desiredPath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Release the media from freeswitch
|
* Release the media from freeswitch
|
||||||
* @param {*} cs
|
* @param {*} cs
|
||||||
* @param {*} sd
|
* @param {*} sd
|
||||||
*/
|
*/
|
||||||
async _releaseMedia(cs, sd) {
|
async _releaseMedia(cs, sd, releaseEntirely = false) {
|
||||||
assert(cs.ep && sd.ep);
|
assert(cs.ep && sd.ep);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Wait until we got new SDP from B leg to ofter to A Leg
|
// Wait until we got new SDP from B leg to ofter to A Leg
|
||||||
const aLegSdp = cs.ep.remote.sdp;
|
const aLegSdp = cs.ep.remote.sdp;
|
||||||
await sd.releaseMediaToSBC(aLegSdp, cs.ep.local.sdp);
|
await sd.releaseMediaToSBC(aLegSdp, cs.ep.local.sdp, releaseEntirely);
|
||||||
const bLegSdp = sd.dlg.remote.sdp;
|
const bLegSdp = sd.dlg.remote.sdp;
|
||||||
await cs.releaseMediaToSBC(bLegSdp);
|
await cs.releaseMediaToSBC(bLegSdp, releaseEntirely);
|
||||||
this.epOther = null;
|
this.epOther = null;
|
||||||
this.logger.info('Dial:_releaseMedia - successfully released media from freewitch');
|
this._mediaPath = releaseEntirely ? MediaPath.NoMedia : MediaPath.PartialMedia;
|
||||||
|
this.logger.info(
|
||||||
|
`Dial:_releaseMedia - successfully released media from freewitch, media path is now ${this._mediaPath}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info({err}, 'Dial:_releaseMedia error');
|
this.logger.info({err}, 'Dial:_releaseMedia error');
|
||||||
}
|
}
|
||||||
@@ -860,8 +982,14 @@ class TaskDial extends Task {
|
|||||||
if (cs.ep && sd.ep) return;
|
if (cs.ep && sd.ep) return;
|
||||||
|
|
||||||
this.logger.info('Dial:reAnchorMedia - re-anchoring media to freewitch');
|
this.logger.info('Dial:reAnchorMedia - re-anchoring media to freewitch');
|
||||||
await Promise.all([sd.reAnchorMedia(), cs.reAnchorMedia()]);
|
await Promise.all([sd.reAnchorMedia(this._mediaPath), cs.reAnchorMedia(this._mediaPath)]);
|
||||||
this.epOther = cs.ep;
|
this.epOther = cs.ep;
|
||||||
|
|
||||||
|
this.epOther.bridge(this.ep);
|
||||||
|
|
||||||
|
this._mediaPath = MediaPath.FullMedia;
|
||||||
|
this.logger.info(
|
||||||
|
`Dial:_releaseMedia - successfully re-anchored media to freewitch, media path is now ${this._mediaPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle RE-INVITE hold from caller leg.
|
// Handle RE-INVITE hold from caller leg.
|
||||||
@@ -880,11 +1008,12 @@ class TaskDial extends Task {
|
|||||||
}
|
}
|
||||||
this._onHoldHook(req);
|
this._onHoldHook(req);
|
||||||
} else if (!isOnhold(req.body)) {
|
} else if (!isOnhold(req.body)) {
|
||||||
if (this.epOther && this.ep && this.isIncomingLegHold && this.canReleaseMedia) {
|
if (this.epOther && this.ep && this.isIncomingLegHold &&
|
||||||
|
(this.canReleaseMedia || this.shouldExitMediaPathEntirely)) {
|
||||||
// Offhold, time to release media
|
// Offhold, time to release media
|
||||||
const newSdp = await this.epOther.modify(req.body);
|
const newSdp = await this.epOther.modify(req.body);
|
||||||
await res.send(200, {body: newSdp});
|
await res.send(200, {body: newSdp});
|
||||||
await this._releaseMedia(this.cs, this.sd);
|
await this._releaseMedia(this.cs, this.sd, this.shouldExitMediaPathEntirely);
|
||||||
isHandled = true;
|
isHandled = true;
|
||||||
}
|
}
|
||||||
this.isIncomingLegHold = false;
|
this.isIncomingLegHold = false;
|
||||||
@@ -943,7 +1072,8 @@ class TaskDial extends Task {
|
|||||||
callInfo: this.cs.callInfo,
|
callInfo: this.cs.callInfo,
|
||||||
accountInfo: this.cs.accountInfo,
|
accountInfo: this.cs.accountInfo,
|
||||||
tasks,
|
tasks,
|
||||||
rootSpan: this.cs.rootSpan
|
rootSpan: this.cs.rootSpan,
|
||||||
|
req: this.cs.req
|
||||||
});
|
});
|
||||||
await this._onHoldSession.exec();
|
await this._onHoldSession.exec();
|
||||||
this._onHoldSession = null;
|
this._onHoldSession = null;
|
||||||
|
|||||||
@@ -125,10 +125,12 @@ class TaskDub extends TtsTask {
|
|||||||
const path = filepath[0];
|
const path = filepath[0];
|
||||||
if (!path.startsWith('say:{')) {
|
if (!path.startsWith('say:{')) {
|
||||||
/* we have a local file of mp3 or r8 of synthesized speech audio to play */
|
/* we have a local file of mp3 or r8 of synthesized speech audio to play */
|
||||||
|
this.logger.info(`playing synthesized speech from file on track ${this.track}: ${path}`);
|
||||||
this.play = path;
|
this.play = path;
|
||||||
await this._playOnTrack(cs, ep);
|
await this._playOnTrack(cs, ep);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
this.logger.info(`doing actual text to speech file on track ${this.track}: ${path}`);
|
||||||
await ep.dub({
|
await ep.dub({
|
||||||
action: 'sayOnTrack',
|
action: 'sayOnTrack',
|
||||||
track: this.track,
|
track: this.track,
|
||||||
|
|||||||
@@ -338,6 +338,7 @@ class TaskEnqueue extends Task {
|
|||||||
this.logger.error({err}, `TaskEnqueue:_playHook error retrieving list info for queue ${this.queueName}`);
|
this.logger.error({err}, `TaskEnqueue:_playHook error retrieving list info for queue ${this.queueName}`);
|
||||||
}
|
}
|
||||||
const json = await cs.application.requestor.request('verb:hook', hook, params, httpHeaders);
|
const json = await cs.application.requestor.request('verb:hook', hook, params, httpHeaders);
|
||||||
|
this.logger.debug({json}, 'TaskEnqueue:_playHook: received response from waitHook');
|
||||||
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
||||||
|
|
||||||
const allowedTasks = tasks.filter((t) => allowed.includes(t.name));
|
const allowedTasks = tasks.filter((t) => allowed.includes(t.name));
|
||||||
@@ -368,7 +369,8 @@ class TaskEnqueue extends Task {
|
|||||||
callInfo: cs.callInfo,
|
callInfo: cs.callInfo,
|
||||||
accountInfo: cs.accountInfo,
|
accountInfo: cs.accountInfo,
|
||||||
tasks: tasksToRun,
|
tasks: tasksToRun,
|
||||||
rootSpan: cs.rootSpan
|
rootSpan: cs.rootSpan,
|
||||||
|
req: cs.req
|
||||||
});
|
});
|
||||||
await this._playSession.exec();
|
await this._playSession.exec();
|
||||||
this._playSession = null;
|
this._playSession = null;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -8,12 +8,16 @@ const DTMF_SPAN_NAME = 'dtmf';
|
|||||||
class TaskListen extends Task {
|
class TaskListen extends Task {
|
||||||
constructor(logger, opts, parentTask) {
|
constructor(logger, opts, parentTask) {
|
||||||
super(logger, opts);
|
super(logger, opts);
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
* use bidirectionalAudio.enabled
|
||||||
|
*/
|
||||||
this.disableBidirectionalAudio = opts.disableBidirectionalAudio;
|
this.disableBidirectionalAudio = opts.disableBidirectionalAudio;
|
||||||
this.preconditions = TaskPreconditions.Endpoint;
|
this.preconditions = TaskPreconditions.Endpoint;
|
||||||
|
|
||||||
[
|
[
|
||||||
'action', 'auth', 'method', 'url', 'finishOnKey', 'maxLength', 'metadata', 'mixType', 'passDtmf', 'playBeep',
|
'action', 'auth', 'method', 'url', 'finishOnKey', 'maxLength', 'metadata', 'mixType', 'passDtmf', 'playBeep',
|
||||||
'sampleRate', 'timeout', 'transcribe', 'wsAuth', 'disableBidirectionalAudio'
|
'sampleRate', 'timeout', 'transcribe', 'wsAuth', 'disableBidirectionalAudio', 'channel'
|
||||||
].forEach((k) => this[k] = this.data[k]);
|
].forEach((k) => this[k] = this.data[k]);
|
||||||
|
|
||||||
this.mixType = this.mixType || 'mono';
|
this.mixType = this.mixType || 'mono';
|
||||||
@@ -25,6 +29,15 @@ class TaskListen extends Task {
|
|||||||
this.results = {};
|
this.results = {};
|
||||||
this.playAudioQueue = [];
|
this.playAudioQueue = [];
|
||||||
this.isPlayingAudioFromQueue = false;
|
this.isPlayingAudioFromQueue = false;
|
||||||
|
this.bidirectionalAudio = {
|
||||||
|
enabled: this.disableBidirectionalAudio === true ? false : true,
|
||||||
|
...(this.data['bidirectionalAudio']),
|
||||||
|
};
|
||||||
|
|
||||||
|
// From drachtio-version 3.0.40, forkAudioStart will send empty bugname, metadata together with
|
||||||
|
// bidirectionalAudio params that cause old version of freeswitch missunderstand between bugname and
|
||||||
|
// bidirectionalAudio params
|
||||||
|
this._bugname = 'audio_fork';
|
||||||
|
|
||||||
if (this.transcribe) this.transcribeTask = makeTask(logger, {'transcribe': opts.transcribe}, this);
|
if (this.transcribe) this.transcribeTask = makeTask(logger, {'transcribe': opts.transcribe}, this);
|
||||||
}
|
}
|
||||||
@@ -133,7 +146,8 @@ class TaskListen extends Task {
|
|||||||
mixType: this.mixType,
|
mixType: this.mixType,
|
||||||
sampling: this.sampleRate,
|
sampling: this.sampleRate,
|
||||||
...(this._bugname && {bugname: this._bugname}),
|
...(this._bugname && {bugname: this._bugname}),
|
||||||
metadata
|
metadata,
|
||||||
|
bidirectionalAudio: this.bidirectionalAudio || {}
|
||||||
});
|
});
|
||||||
this.recordStartTime = moment();
|
this.recordStartTime = moment();
|
||||||
if (this.maxLength) {
|
if (this.maxLength) {
|
||||||
@@ -153,7 +167,7 @@ class TaskListen extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* support bi-directional audio */
|
/* support bi-directional audio */
|
||||||
if (!this.disableBidirectionalAudio) {
|
if (this.bidirectionalAudio.enabled) {
|
||||||
ep.addCustomEventListener(ListenEvents.PlayAudio, this._onPlayAudio.bind(this, ep));
|
ep.addCustomEventListener(ListenEvents.PlayAudio, this._onPlayAudio.bind(this, ep));
|
||||||
}
|
}
|
||||||
ep.addCustomEventListener(ListenEvents.KillAudio, this._onKillAudio.bind(this, ep));
|
ep.addCustomEventListener(ListenEvents.KillAudio, this._onKillAudio.bind(this, ep));
|
||||||
@@ -207,7 +221,7 @@ class TaskListen extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
_onConnect(ep) {
|
_onConnect(ep) {
|
||||||
this.logger.debug('TaskListen:_onConnect');
|
this.logger.info('TaskListen:_onConnect');
|
||||||
}
|
}
|
||||||
_onConnectFailure(ep, evt) {
|
_onConnectFailure(ep, evt) {
|
||||||
this.logger.info(evt, 'TaskListen:_onConnectFailure');
|
this.logger.info(evt, 'TaskListen:_onConnectFailure');
|
||||||
|
|||||||
111
lib/tasks/llm/index.js
Normal file
111
lib/tasks/llm/index.js
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
const Task = require('../task');
|
||||||
|
const {TaskPreconditions} = require('../../utils/constants');
|
||||||
|
const TaskLlmOpenAI_S2S = require('./llms/openai_s2s');
|
||||||
|
const TaskLlmVoiceAgent_S2S = require('./llms/voice_agent_s2s');
|
||||||
|
const TaskLlmUltravox_S2S = require('./llms/ultravox_s2s');
|
||||||
|
const TaskLlmElevenlabs_S2S = require('./llms/elevenlabs_s2s');
|
||||||
|
|
||||||
|
class TaskLlm extends Task {
|
||||||
|
constructor(logger, opts) {
|
||||||
|
super(logger, opts);
|
||||||
|
this.preconditions = TaskPreconditions.Endpoint;
|
||||||
|
|
||||||
|
['vendor', 'model', 'auth', 'connectOptions'].forEach((prop) => {
|
||||||
|
this[prop] = this.data[prop];
|
||||||
|
});
|
||||||
|
|
||||||
|
this.eventHandlers = [];
|
||||||
|
|
||||||
|
// delegate to the specific llm model
|
||||||
|
this.llm = this.createSpecificLlm();
|
||||||
|
}
|
||||||
|
|
||||||
|
get name() { return this.llm.name ; }
|
||||||
|
|
||||||
|
get toolHook() { return this.llm?.toolHook; }
|
||||||
|
|
||||||
|
get eventHook() { return this.llm?.eventHook; }
|
||||||
|
|
||||||
|
get ep() { return this.cs.ep; }
|
||||||
|
|
||||||
|
async exec(cs, {ep}) {
|
||||||
|
await super.exec(cs, {ep});
|
||||||
|
await this.llm.exec(cs, {ep});
|
||||||
|
}
|
||||||
|
|
||||||
|
async kill(cs) {
|
||||||
|
super.kill(cs);
|
||||||
|
await this.llm.kill(cs);
|
||||||
|
}
|
||||||
|
|
||||||
|
createSpecificLlm() {
|
||||||
|
let llm;
|
||||||
|
switch (this.vendor) {
|
||||||
|
case 'openai':
|
||||||
|
case 'microsoft':
|
||||||
|
llm = new TaskLlmOpenAI_S2S(this.logger, this.data, this);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'voiceagent':
|
||||||
|
case 'deepgram':
|
||||||
|
llm = new TaskLlmVoiceAgent_S2S(this.logger, this.data, this);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'ultravox':
|
||||||
|
llm = new TaskLlmUltravox_S2S(this.logger, this.data, this);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'elevenlabs':
|
||||||
|
llm = new TaskLlmElevenlabs_S2S(this.logger, this.data, this);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported vendor ${this.vendor} for LLM`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!llm) {
|
||||||
|
throw new Error(`Unsupported vendor:model ${this.vendor}:${this.model}`);
|
||||||
|
}
|
||||||
|
return llm;
|
||||||
|
}
|
||||||
|
|
||||||
|
addCustomEventListener(ep, event, handler) {
|
||||||
|
this.eventHandlers.push({ep, event, handler});
|
||||||
|
ep.addCustomEventListener(event, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeCustomEventListeners() {
|
||||||
|
this.eventHandlers.forEach((h) => h.ep.removeCustomEventListener(h.event, h.handler));
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendEventHook(data) {
|
||||||
|
await this.cs?.requestor.request('llm:event', this.eventHook, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendToolHook(tool_call_id, data) {
|
||||||
|
await this.cs?.requestor.request('llm:tool-call', this.toolHook, {tool_call_id, ...data});
|
||||||
|
}
|
||||||
|
|
||||||
|
async processToolOutput(tool_call_id, data) {
|
||||||
|
if (!this.ep.connected) {
|
||||||
|
this.logger.info('TaskLlm:processToolOutput - no connected endpoint');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.llm.processToolOutput(this.ep, tool_call_id, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async processLlmUpdate(data, callSid) {
|
||||||
|
if (this.ep.connected) {
|
||||||
|
if (typeof this.llm.processLlmUpdate === 'function') {
|
||||||
|
this.llm.processLlmUpdate(this.ep, data, callSid);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const {vendor, model} = this.llm;
|
||||||
|
this.logger.info({data, callSid},
|
||||||
|
`TaskLlm:_processLlmUpdate: LLM ${vendor}:${model} does not support llm:update`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TaskLlm;
|
||||||
304
lib/tasks/llm/llms/elevenlabs_s2s.js
Normal file
304
lib/tasks/llm/llms/elevenlabs_s2s.js
Normal file
@@ -0,0 +1,304 @@
|
|||||||
|
const Task = require('../../task');
|
||||||
|
const TaskName = 'Llm_Elevenlabs_s2s';
|
||||||
|
const {LlmEvents_Elevenlabs} = require('../../../utils/constants');
|
||||||
|
const {request} = require('undici');
|
||||||
|
const ClientEvent = 'client.event';
|
||||||
|
const SessionDelete = 'session.delete';
|
||||||
|
|
||||||
|
const elevenlabs_server_events = [
|
||||||
|
'conversation_initiation_metadata',
|
||||||
|
'user_transcript',
|
||||||
|
'agent_response',
|
||||||
|
'client_tool_call'
|
||||||
|
];
|
||||||
|
|
||||||
|
const expandWildcards = (events) => {
|
||||||
|
const expandedEvents = [];
|
||||||
|
|
||||||
|
events.forEach((evt) => {
|
||||||
|
if (evt.endsWith('.*')) {
|
||||||
|
const prefix = evt.slice(0, -2); // Remove the wildcard ".*"
|
||||||
|
const matchingEvents = elevenlabs_server_events.filter((e) => e.startsWith(prefix));
|
||||||
|
expandedEvents.push(...matchingEvents);
|
||||||
|
} else {
|
||||||
|
expandedEvents.push(evt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return expandedEvents;
|
||||||
|
};
|
||||||
|
|
||||||
|
class TaskLlmElevenlabs_S2S extends Task {
|
||||||
|
constructor(logger, opts, parentTask) {
|
||||||
|
super(logger, opts, parentTask);
|
||||||
|
this.parent = parentTask;
|
||||||
|
|
||||||
|
this.vendor = this.parent.vendor;
|
||||||
|
this.auth = this.parent.auth;
|
||||||
|
|
||||||
|
const {agent_id, api_key} = this.auth || {};
|
||||||
|
if (!agent_id) throw new Error('auth.agent_id is required for Elevenlabs S2S');
|
||||||
|
|
||||||
|
this.agent_id = agent_id;
|
||||||
|
this.api_key = api_key;
|
||||||
|
this.actionHook = this.data.actionHook;
|
||||||
|
this.eventHook = this.data.eventHook;
|
||||||
|
this.toolHook = this.data.toolHook;
|
||||||
|
const {
|
||||||
|
conversation_initiation_client_data,
|
||||||
|
input_sample_rate = 16000,
|
||||||
|
output_sample_rate = 16000
|
||||||
|
} = this.data.llmOptions;
|
||||||
|
this.conversation_initiation_client_data = conversation_initiation_client_data;
|
||||||
|
this.input_sample_rate = input_sample_rate;
|
||||||
|
this.output_sample_rate = output_sample_rate;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'normal conversation end'
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* only one of these will have items,
|
||||||
|
* if includeEvents, then these are the events to include
|
||||||
|
* if excludeEvents, then these are the events to exclude
|
||||||
|
*/
|
||||||
|
this.includeEvents = [];
|
||||||
|
this.excludeEvents = [];
|
||||||
|
|
||||||
|
/* default to all events if user did not specify */
|
||||||
|
this._populateEvents(this.data.events || elevenlabs_server_events);
|
||||||
|
|
||||||
|
this.addCustomEventListener = parentTask.addCustomEventListener.bind(parentTask);
|
||||||
|
this.removeCustomEventListeners = parentTask.removeCustomEventListeners.bind(parentTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
get name() { return TaskName; }
|
||||||
|
|
||||||
|
async getSignedUrl() {
|
||||||
|
if (!this.api_key) {
|
||||||
|
return {
|
||||||
|
host: 'api.elevenlabs.io',
|
||||||
|
path: `/v1/convai/conversation?agent_id=${this.agent_id}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const {statusCode, body} = await request(
|
||||||
|
`https://api.elevenlabs.io/v1/convai/conversation/get_signed_url?agent_id=${this.agent_id}`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'xi-api-key': this.api_key
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const data = await body.json();
|
||||||
|
if (statusCode !== 200 || !data?.signed_url) {
|
||||||
|
this.logger.error({statusCode, data}, 'Elevenlabs Error registering call');
|
||||||
|
throw new Error(`Elevenlabs Error registering call: ${data.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(data.signed_url);
|
||||||
|
return {
|
||||||
|
host: url.hostname,
|
||||||
|
path: url.pathname + url.search,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async _api(ep, args) {
|
||||||
|
const res = await ep.api('uuid_elevenlabs_s2s', `^^|${args.join('|')}`);
|
||||||
|
if (!res.body?.startsWith('+OK')) {
|
||||||
|
throw new Error({args}, `Error calling uuid_elevenlabs_s2s: ${res.body}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exec(cs, {ep}) {
|
||||||
|
await super.exec(cs);
|
||||||
|
await this._startListening(cs, ep);
|
||||||
|
|
||||||
|
await this.awaitTaskDone();
|
||||||
|
|
||||||
|
/* note: the parent llm verb started the span, which is why this is necessary */
|
||||||
|
await this.parent.performAction(this.results);
|
||||||
|
|
||||||
|
this._unregisterHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
async kill(cs) {
|
||||||
|
super.kill(cs);
|
||||||
|
|
||||||
|
this._api(cs.ep, [cs.ep.uuid, SessionDelete])
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmElevenlabs_S2S:kill - error deleting session'));
|
||||||
|
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send function call output to the Elevenlabs server in the form of conversation.item.create
|
||||||
|
* per https://elevenlabs.io/docs/conversational-ai/api-reference/conversational-ai/websocket
|
||||||
|
*/
|
||||||
|
async processToolOutput(ep, tool_call_id, rawData) {
|
||||||
|
try {
|
||||||
|
const {data} = rawData;
|
||||||
|
this.logger.debug({tool_call_id, data}, 'TaskLlmElevenlabs_S2S:processToolOutput');
|
||||||
|
|
||||||
|
if (!data.type || data.type !== 'client_tool_result') {
|
||||||
|
this.logger.info({data},
|
||||||
|
'TaskLlmElevenlabs_S2S:processToolOutput - invalid tool output, must be client_tool_result');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmElevenlabs_S2S:processToolOutput');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a session.update to the Elevenlabs server
|
||||||
|
* Note: creating and deleting conversation items also supported as well as interrupting the assistant
|
||||||
|
*/
|
||||||
|
async processLlmUpdate(ep, data, _callSid) {
|
||||||
|
this.logger.debug({data, _callSid}, 'TaskLlmElevenlabs_S2S:processLlmUpdate, ignored');
|
||||||
|
}
|
||||||
|
|
||||||
|
async _startListening(cs, ep) {
|
||||||
|
this._registerHandlers(ep);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const {host, path} = await this.getSignedUrl();
|
||||||
|
const args = this.conversation_initiation_client_data ?
|
||||||
|
[ep.uuid, 'session.create', this.input_sample_rate, this.output_sample_rate, host, path] :
|
||||||
|
[ep.uuid, 'session.create', this.input_sample_rate, this.output_sample_rate, host, path, 'no_initial_config'];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error({err}, 'TaskLlmElevenlabs_S2S:_startListening');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendClientEvent(ep, obj) {
|
||||||
|
let ok = true;
|
||||||
|
this.logger.debug({obj}, 'TaskLlmElevenlabs_S2S:_sendClientEvent');
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, ClientEvent, JSON.stringify(obj)];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
ok = false;
|
||||||
|
this.logger.error({err}, 'TaskLlmElevenlabs_S2S:_sendClientEvent - Error');
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendInitialMessage(ep) {
|
||||||
|
if (this.conversation_initiation_client_data) {
|
||||||
|
if (!await this._sendClientEvent(ep, {
|
||||||
|
type: 'conversation_initiation_client_data',
|
||||||
|
...this.conversation_initiation_client_data
|
||||||
|
})) {
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_registerHandlers(ep) {
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Elevenlabs.Connect, this._onConnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Elevenlabs.ConnectFailure, this._onConnectFailure.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Elevenlabs.Disconnect, this._onDisconnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Elevenlabs.ServerEvent, this._onServerEvent.bind(this, ep));
|
||||||
|
}
|
||||||
|
|
||||||
|
_unregisterHandlers() {
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onError(ep, evt) {
|
||||||
|
this.logger.info({evt}, 'TaskLlmElevenlabs_S2S:_onError');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onConnect(ep) {
|
||||||
|
this.logger.debug('TaskLlmElevenlabs_S2S:_onConnect');
|
||||||
|
this._sendInitialMessage(ep);
|
||||||
|
}
|
||||||
|
_onConnectFailure(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmElevenlabs_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'connection failure'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
_onDisconnect(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmElevenlabs_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'disconnect from remote end'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
async _onServerEvent(ep, evt) {
|
||||||
|
let endConversation = false;
|
||||||
|
const type = evt.type;
|
||||||
|
this.logger.info({evt}, 'TaskLlmElevenlabs_S2S:_onServerEvent');
|
||||||
|
|
||||||
|
if (type === 'error') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server error',
|
||||||
|
error: evt.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tool calls */
|
||||||
|
else if (type === 'client_tool_call') {
|
||||||
|
this.logger.debug({evt}, 'TaskLlmElevenlabs_S2S:_onServerEvent - function_call');
|
||||||
|
if (!this.toolHook) {
|
||||||
|
this.logger.warn({evt}, 'TaskLlmElevenlabs_S2S:_onServerEvent - no toolHook defined!');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const {client_tool_call} = evt;
|
||||||
|
const {tool_name: name, tool_call_id: call_id, parameters: args} = client_tool_call;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.parent.sendToolHook(call_id, {name, args});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, evt}, 'TaskLlmElevenlabs_S2S - error calling function');
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'client error calling function',
|
||||||
|
error: err
|
||||||
|
};
|
||||||
|
endConversation = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* check whether we should notify on this event */
|
||||||
|
if (this.includeEvents.length > 0 ? this.includeEvents.includes(type) : !this.excludeEvents.includes(type)) {
|
||||||
|
this.parent.sendEventHook(evt)
|
||||||
|
.catch((err) => this.logger.info({err},
|
||||||
|
'TaskLlmElevenlabs_S2S:_onServerEvent - error sending event hook'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endConversation) {
|
||||||
|
this.logger.info({results: this.results},
|
||||||
|
'TaskLlmElevenlabs_S2S:_onServerEvent - ending conversation due to error');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_populateEvents(events) {
|
||||||
|
if (events.includes('all')) {
|
||||||
|
/* work by excluding specific events */
|
||||||
|
const exclude = events
|
||||||
|
.filter((evt) => evt.startsWith('-'))
|
||||||
|
.map((evt) => evt.slice(1));
|
||||||
|
if (exclude.length === 0) this.includeEvents = elevenlabs_server_events;
|
||||||
|
else this.excludeEvents = expandWildcards(exclude);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* work by including specific events */
|
||||||
|
const include = events
|
||||||
|
.filter((evt) => !evt.startsWith('-'));
|
||||||
|
this.includeEvents = expandWildcards(include);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug({
|
||||||
|
includeEvents: this.includeEvents,
|
||||||
|
excludeEvents: this.excludeEvents
|
||||||
|
}, 'TaskLlmElevenlabs_S2S:_populateEvents');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TaskLlmElevenlabs_S2S;
|
||||||
357
lib/tasks/llm/llms/openai_s2s.js
Normal file
357
lib/tasks/llm/llms/openai_s2s.js
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
const Task = require('../../task');
|
||||||
|
const TaskName = 'Llm_OpenAI_s2s';
|
||||||
|
const {LlmEvents_OpenAI} = require('../../../utils/constants');
|
||||||
|
const ClientEvent = 'client.event';
|
||||||
|
const SessionDelete = 'session.delete';
|
||||||
|
|
||||||
|
const openai_server_events = [
|
||||||
|
'error',
|
||||||
|
'session.created',
|
||||||
|
'session.updated',
|
||||||
|
'conversation.created',
|
||||||
|
'input_audio_buffer.committed',
|
||||||
|
'input_audio_buffer.cleared',
|
||||||
|
'input_audio_buffer.speech_started',
|
||||||
|
'input_audio_buffer.speech_stopped',
|
||||||
|
'conversation.item.created',
|
||||||
|
'conversation.item.input_audio_transcription.completed',
|
||||||
|
'conversation.item.input_audio_transcription.failed',
|
||||||
|
'conversation.item.truncated',
|
||||||
|
'conversation.item.deleted',
|
||||||
|
'response.created',
|
||||||
|
'response.done',
|
||||||
|
'response.output_item.added',
|
||||||
|
'response.output_item.done',
|
||||||
|
'response.content_part.added',
|
||||||
|
'response.content_part.done',
|
||||||
|
'response.text.delta',
|
||||||
|
'response.text.done',
|
||||||
|
'response.audio_transcript.delta',
|
||||||
|
'response.audio_transcript.done',
|
||||||
|
'response.audio.delta',
|
||||||
|
'response.audio.done',
|
||||||
|
'response.function_call_arguments.delta',
|
||||||
|
'response.function_call_arguments.done',
|
||||||
|
'rate_limits.updated',
|
||||||
|
'output_audio.playback_started',
|
||||||
|
'output_audio.playback_stopped',
|
||||||
|
];
|
||||||
|
|
||||||
|
const expandWildcards = (events) => {
|
||||||
|
const expandedEvents = [];
|
||||||
|
|
||||||
|
events.forEach((evt) => {
|
||||||
|
if (evt.endsWith('.*')) {
|
||||||
|
const prefix = evt.slice(0, -2); // Remove the wildcard ".*"
|
||||||
|
const matchingEvents = openai_server_events.filter((e) => e.startsWith(prefix));
|
||||||
|
expandedEvents.push(...matchingEvents);
|
||||||
|
} else {
|
||||||
|
expandedEvents.push(evt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return expandedEvents;
|
||||||
|
};
|
||||||
|
|
||||||
|
class TaskLlmOpenAI_S2S extends Task {
|
||||||
|
constructor(logger, opts, parentTask) {
|
||||||
|
super(logger, opts, parentTask);
|
||||||
|
this.parent = parentTask;
|
||||||
|
|
||||||
|
this.vendor = this.parent.vendor;
|
||||||
|
this.model = this.parent.model || 'gpt-4o-realtime-preview-2024-12-17';
|
||||||
|
this.auth = this.parent.auth;
|
||||||
|
this.connectionOptions = this.parent.connectOptions;
|
||||||
|
|
||||||
|
const {apiKey} = this.auth || {};
|
||||||
|
if (!apiKey) throw new Error('auth.apiKey is required for OpenAI S2S');
|
||||||
|
|
||||||
|
if (['openai', 'microsoft'].indexOf(this.vendor) === -1) {
|
||||||
|
throw new Error(`Invalid vendor ${this.vendor} for OpenAI S2S`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ('microsoft' === this.vendor && !this.connectionOptions?.host) {
|
||||||
|
throw new Error('connectionOptions.host is required for Microsoft OpenAI S2S');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
this.authType = 'microsoft' === this.vendor ? 'query' : 'bearer';
|
||||||
|
this.actionHook = this.data.actionHook;
|
||||||
|
this.eventHook = this.data.eventHook;
|
||||||
|
this.toolHook = this.data.toolHook;
|
||||||
|
const {response_create, session_update} = this.data.llmOptions;
|
||||||
|
|
||||||
|
if (typeof response_create !== 'object') {
|
||||||
|
throw new Error('llmOptions with an initial response.create is required for OpenAI S2S');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.response_create = response_create;
|
||||||
|
this.session_update = session_update;
|
||||||
|
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'normal conversation end'
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* only one of these will have items,
|
||||||
|
* if includeEvents, then these are the events to include
|
||||||
|
* if excludeEvents, then these are the events to exclude
|
||||||
|
*/
|
||||||
|
this.includeEvents = [];
|
||||||
|
this.excludeEvents = [];
|
||||||
|
|
||||||
|
/* default to all events if user did not specify */
|
||||||
|
this._populateEvents(this.data.events || openai_server_events);
|
||||||
|
|
||||||
|
this.addCustomEventListener = parentTask.addCustomEventListener.bind(parentTask);
|
||||||
|
this.removeCustomEventListeners = parentTask.removeCustomEventListeners.bind(parentTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
get name() { return TaskName; }
|
||||||
|
|
||||||
|
get host() {
|
||||||
|
const {host} = this.connectionOptions || {};
|
||||||
|
return host || (this.vendor === 'openai' ? 'api.openai.com' : void 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
get path() {
|
||||||
|
const {path} = this.connectionOptions || {};
|
||||||
|
if (path) return path;
|
||||||
|
|
||||||
|
switch (this.vendor) {
|
||||||
|
case 'openai':
|
||||||
|
return `v1/realtime?model=${this.model}`;
|
||||||
|
case 'microsoft':
|
||||||
|
return `openai/realtime?api-version=2024-10-01-preview&deployment=${this.model}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _api(ep, args) {
|
||||||
|
const res = await ep.api('uuid_openai_s2s', `^^|${args.join('|')}`);
|
||||||
|
if (!res.body?.startsWith('+OK')) {
|
||||||
|
throw new Error({args}, `Error calling uuid_openai_s2s: ${res.body}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exec(cs, {ep}) {
|
||||||
|
await super.exec(cs);
|
||||||
|
|
||||||
|
await this._startListening(cs, ep);
|
||||||
|
|
||||||
|
await this.awaitTaskDone();
|
||||||
|
|
||||||
|
/* note: the parent llm verb started the span, which is why this is necessary */
|
||||||
|
await this.parent.performAction(this.results);
|
||||||
|
|
||||||
|
this._unregisterHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
async kill(cs) {
|
||||||
|
super.kill(cs);
|
||||||
|
|
||||||
|
this._api(cs.ep, [cs.ep.uuid, SessionDelete])
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmOpenAI_S2S:kill - error deleting session'));
|
||||||
|
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send function call output to the OpenAI server in the form of conversation.item.create
|
||||||
|
* per https://platform.openai.com/docs/guides/realtime/function-calls
|
||||||
|
*/
|
||||||
|
async processToolOutput(ep, tool_call_id, data) {
|
||||||
|
try {
|
||||||
|
this.logger.debug({tool_call_id, data}, 'TaskLlmOpenAI_S2S:processToolOutput');
|
||||||
|
|
||||||
|
if (!data.type || data.type !== 'conversation.item.create') {
|
||||||
|
this.logger.info({data},
|
||||||
|
'TaskLlmOpenAI_S2S:processToolOutput - invalid tool output, must be conversation.item.create');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
|
||||||
|
// spec also recommends to send immediate response.create
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify({type: 'response.create'})]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmOpenAI_S2S:processToolOutput');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a session.update to the OpenAI server
|
||||||
|
* Note: creating and deleting conversation items also supported as well as interrupting the assistant
|
||||||
|
*/
|
||||||
|
async processLlmUpdate(ep, data, _callSid) {
|
||||||
|
try {
|
||||||
|
this.logger.debug({data, _callSid}, 'TaskLlmOpenAI_S2S:processLlmUpdate');
|
||||||
|
|
||||||
|
if (!data.type || ![
|
||||||
|
'session.update',
|
||||||
|
'conversation.item.create',
|
||||||
|
'conversation.item.delete',
|
||||||
|
'response.cancel'
|
||||||
|
].includes(data.type)) {
|
||||||
|
this.logger.info({data}, 'TaskLlmOpenAI_S2S:processLlmUpdate - invalid mid-call request');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmOpenAI_S2S:processLlmUpdate');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _startListening(cs, ep) {
|
||||||
|
this._registerHandlers(ep);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, 'session.create', this.host, this.path, this.authType, this.apiKey];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error({err}, 'TaskLlmOpenAI_S2S:_startListening');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendClientEvent(ep, obj) {
|
||||||
|
let ok = true;
|
||||||
|
this.logger.debug({obj}, 'TaskLlmOpenAI_S2S:_sendClientEvent');
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, ClientEvent, JSON.stringify(obj)];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
ok = false;
|
||||||
|
this.logger.error({err}, 'TaskLlmOpenAI_S2S:_sendClientEvent - Error');
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendInitialMessage(ep) {
|
||||||
|
let obj = {type: 'response.create', response: this.response_create};
|
||||||
|
if (!await this._sendClientEvent(ep, obj)) {
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* send immediate session.update if present */
|
||||||
|
else if (this.session_update) {
|
||||||
|
obj = {type: 'session.update', session: this.session_update};
|
||||||
|
this.logger.debug({obj}, 'TaskLlmOpenAI_S2S:_sendInitialMessage - sending session.update');
|
||||||
|
if (!await this._sendClientEvent(ep, obj)) {
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_registerHandlers(ep) {
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_OpenAI.Connect, this._onConnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_OpenAI.ConnectFailure, this._onConnectFailure.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_OpenAI.Disconnect, this._onDisconnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_OpenAI.ServerEvent, this._onServerEvent.bind(this, ep));
|
||||||
|
}
|
||||||
|
|
||||||
|
_unregisterHandlers() {
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onError(ep, evt) {
|
||||||
|
this.logger.info({evt}, 'TaskLlmOpenAI_S2S:_onError');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onConnect(ep) {
|
||||||
|
this.logger.debug('TaskLlmOpenAI_S2S:_onConnect');
|
||||||
|
this._sendInitialMessage(ep);
|
||||||
|
}
|
||||||
|
_onConnectFailure(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmOpenAI_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'connection failure'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
_onDisconnect(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmOpenAI_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'disconnect from remote end'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
async _onServerEvent(ep, evt) {
|
||||||
|
let endConversation = false;
|
||||||
|
const type = evt.type;
|
||||||
|
this.logger.info({evt}, 'TaskLlmOpenAI_S2S:_onServerEvent');
|
||||||
|
|
||||||
|
/* check for failures, such as rate limit exceeded, that should terminate the conversation */
|
||||||
|
if (type === 'response.done' && evt.response.status === 'failed') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server failure',
|
||||||
|
error: evt.response.status_details?.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* server errors of some sort */
|
||||||
|
else if (type === 'error') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server error',
|
||||||
|
error: evt.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tool calls */
|
||||||
|
else if (type === 'response.output_item.done' && evt.item?.type === 'function_call') {
|
||||||
|
this.logger.debug({evt}, 'TaskLlmOpenAI_S2S:_onServerEvent - function_call');
|
||||||
|
if (!this.toolHook) {
|
||||||
|
this.logger.warn({evt}, 'TaskLlmOpenAI_S2S:_onServerEvent - no toolHook defined!');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const {name, call_id} = evt.item;
|
||||||
|
const args = JSON.parse(evt.item.arguments);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.parent.sendToolHook(call_id, {name, args});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, evt}, 'TaskLlmOpenAI - error calling function');
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'client error calling function',
|
||||||
|
error: err
|
||||||
|
};
|
||||||
|
endConversation = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* check whether we should notify on this event */
|
||||||
|
if (this.includeEvents.length > 0 ? this.includeEvents.includes(type) : !this.excludeEvents.includes(type)) {
|
||||||
|
this.parent.sendEventHook(evt)
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmOpenAI_S2S:_onServerEvent - error sending event hook'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endConversation) {
|
||||||
|
this.logger.info({results: this.results}, 'TaskLlmOpenAI_S2S:_onServerEvent - ending conversation due to error');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_populateEvents(events) {
|
||||||
|
if (events.includes('all')) {
|
||||||
|
/* work by excluding specific events */
|
||||||
|
const exclude = events
|
||||||
|
.filter((evt) => evt.startsWith('-'))
|
||||||
|
.map((evt) => evt.slice(1));
|
||||||
|
if (exclude.length === 0) this.includeEvents = openai_server_events;
|
||||||
|
else this.excludeEvents = expandWildcards(exclude);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* work by including specific events */
|
||||||
|
const include = events
|
||||||
|
.filter((evt) => !evt.startsWith('-'));
|
||||||
|
this.includeEvents = expandWildcards(include);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug({
|
||||||
|
includeEvents: this.includeEvents,
|
||||||
|
excludeEvents: this.excludeEvents
|
||||||
|
}, 'TaskLlmOpenAI_S2S:_populateEvents');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TaskLlmOpenAI_S2S;
|
||||||
274
lib/tasks/llm/llms/ultravox_s2s.js
Normal file
274
lib/tasks/llm/llms/ultravox_s2s.js
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
const Task = require('../../task');
|
||||||
|
const TaskName = 'Llm_Ultravox_s2s';
|
||||||
|
const {request} = require('undici');
|
||||||
|
const {LlmEvents_Ultravox} = require('../../../utils/constants');
|
||||||
|
|
||||||
|
const ultravox_server_events = [
|
||||||
|
'createCall',
|
||||||
|
'pong',
|
||||||
|
'state',
|
||||||
|
'transcript',
|
||||||
|
'conversationText',
|
||||||
|
'clientToolInvocation',
|
||||||
|
'playbackClearBuffer',
|
||||||
|
];
|
||||||
|
|
||||||
|
const ClientEvent = 'client.event';
|
||||||
|
|
||||||
|
const expandWildcards = (events) => {
|
||||||
|
// no-op for deepgram
|
||||||
|
return events;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SessionDelete = 'session.delete';
|
||||||
|
|
||||||
|
class TaskLlmUltravox_S2S extends Task {
|
||||||
|
constructor(logger, opts, parentTask) {
|
||||||
|
super(logger, opts, parentTask);
|
||||||
|
this.parent = parentTask;
|
||||||
|
|
||||||
|
this.vendor = this.parent.vendor;
|
||||||
|
this.model = this.parent.model || 'fixie-ai/ultravox';
|
||||||
|
this.auth = this.parent.auth;
|
||||||
|
this.connectionOptions = this.parent.connectOptions;
|
||||||
|
|
||||||
|
const {apiKey} = this.auth || {};
|
||||||
|
if (!apiKey) throw new Error('auth.apiKey is required for Vendor: Ultravox');
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
this.actionHook = this.data.actionHook;
|
||||||
|
this.eventHook = this.data.eventHook;
|
||||||
|
this.toolHook = this.data.toolHook;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* only one of these will have items,
|
||||||
|
* if includeEvents, then these are the events to include
|
||||||
|
* if excludeEvents, then these are the events to exclude
|
||||||
|
*/
|
||||||
|
this.includeEvents = [];
|
||||||
|
this.excludeEvents = [];
|
||||||
|
|
||||||
|
/* default to all events if user did not specify */
|
||||||
|
this._populateEvents(this.data.events || ultravox_server_events);
|
||||||
|
|
||||||
|
this.addCustomEventListener = parentTask.addCustomEventListener.bind(parentTask);
|
||||||
|
this.removeCustomEventListeners = parentTask.removeCustomEventListeners.bind(parentTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
get name() { return TaskName; }
|
||||||
|
|
||||||
|
async _api(ep, args) {
|
||||||
|
const res = await ep.api('uuid_ultravox_s2s', `^^|${args.join('|')}`);
|
||||||
|
if (!res.body?.startsWith('+OK')) {
|
||||||
|
throw new Error(`Error calling uuid_ultravox_s2s: ${JSON.stringify(res.body)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createCall() {
|
||||||
|
const payload = {
|
||||||
|
...this.data.llmOptions,
|
||||||
|
model: this.model,
|
||||||
|
medium: {
|
||||||
|
...(this.data.llmOptions.medium || {}),
|
||||||
|
serverWebSocket: {
|
||||||
|
inputSampleRate: 8000,
|
||||||
|
outputSampleRate: 8000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const {statusCode, body} = await request('https://api.ultravox.ai/api/calls', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-API-Key': this.apiKey
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
const data = await body.json();
|
||||||
|
if (statusCode !== 201 || !data?.joinUrl) {
|
||||||
|
this.logger.info({statusCode, data}, 'Ultravox Error registering call');
|
||||||
|
throw new Error(`Ultravox Error registering call: ${data.message}`);
|
||||||
|
}
|
||||||
|
this.logger.debug({joinUrl: data.joinUrl}, 'Ultravox Call registered');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
_unregisterHandlers() {
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
_registerHandlers(ep) {
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Ultravox.Connect, this._onConnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Ultravox.ConnectFailure, this._onConnectFailure.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Ultravox.Disconnect, this._onDisconnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_Ultravox.ServerEvent, this._onServerEvent.bind(this, ep));
|
||||||
|
}
|
||||||
|
|
||||||
|
async _startListening(cs, ep) {
|
||||||
|
this._registerHandlers(ep);
|
||||||
|
|
||||||
|
const data = await this.createCall();
|
||||||
|
const {joinUrl} = data;
|
||||||
|
// split the joinUrl into host and path
|
||||||
|
const {host, pathname, search} = new URL(joinUrl);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, 'session.create', host, pathname + search];
|
||||||
|
await this._api(ep, args);
|
||||||
|
// Notify the application that the session has been created with detail information
|
||||||
|
this._sendLlmEvent('createCall', {
|
||||||
|
type: 'createCall',
|
||||||
|
...data
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmUltraVox_S2S:_startListening - Error sending createCall');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exec(cs, {ep}) {
|
||||||
|
await super.exec(cs);
|
||||||
|
|
||||||
|
await this._startListening(cs, ep);
|
||||||
|
|
||||||
|
await this.awaitTaskDone();
|
||||||
|
|
||||||
|
/* note: the parent llm verb started the span, which is why this is necessary */
|
||||||
|
await this.parent.performAction(this.results);
|
||||||
|
|
||||||
|
this._unregisterHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
async kill(cs) {
|
||||||
|
super.kill(cs);
|
||||||
|
|
||||||
|
this._api(cs.ep, [cs.ep.uuid, SessionDelete])
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmUltravox_S2S:kill - error deleting session'));
|
||||||
|
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onConnect(ep) {
|
||||||
|
this.logger.info('TaskLlmUltravox_S2S:_onConnect');
|
||||||
|
}
|
||||||
|
_onConnectFailure(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmUltravox_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'connection failure'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
_onDisconnect(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmUltravox_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'disconnect from remote end'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onServerEvent(_ep, evt) {
|
||||||
|
let endConversation = false;
|
||||||
|
const type = evt.type;
|
||||||
|
this.logger.debug({evt}, 'TaskLlmUltravox_S2S:_onServerEvent');
|
||||||
|
|
||||||
|
/* server errors of some sort */
|
||||||
|
if (type === 'error') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server error',
|
||||||
|
error: evt.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tool calls */
|
||||||
|
else if (type === 'client_tool_invocation') {
|
||||||
|
this.logger.debug({evt}, 'TaskLlmUltravox_S2S:_onServerEvent - function_call');
|
||||||
|
if (!this.toolHook) {
|
||||||
|
this.logger.info({evt}, 'TaskLlmUltravox_S2S:_onServerEvent - no toolHook defined!');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const {toolName: name, invocationId: call_id, parameters: args} = evt;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.parent.sendToolHook(call_id, {name, args});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, evt}, 'TaskLlmUltravox_S2S - error calling function');
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'client error calling function',
|
||||||
|
error: err
|
||||||
|
};
|
||||||
|
endConversation = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this._sendLlmEvent(type, evt);
|
||||||
|
|
||||||
|
if (endConversation) {
|
||||||
|
this.logger.info({results: this.results},
|
||||||
|
'TaskLlmUltravox_S2S:_onServerEvent - ending conversation due to error');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_sendLlmEvent(type, evt) {
|
||||||
|
/* check whether we should notify on this event */
|
||||||
|
if (this.includeEvents.length > 0 ? this.includeEvents.includes(type) : !this.excludeEvents.includes(type)) {
|
||||||
|
this.parent.sendEventHook(evt)
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmUltravox_S2S:_onServerEvent - error sending event hook'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async processLlmUpdate(ep, data, _callSid) {
|
||||||
|
try {
|
||||||
|
this.logger.debug({data, _callSid}, 'TaskLlmUltravox_S2S:processLlmUpdate');
|
||||||
|
|
||||||
|
if (!data.type || ![
|
||||||
|
'input_text_message'
|
||||||
|
].includes(data.type)) {
|
||||||
|
this.logger.info({data},
|
||||||
|
'TaskLlmUltravox_S2S:processLlmUpdate - invalid mid-call request, only input_text_message supported');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, data}, 'TaskLlmUltravox_S2S:processLlmUpdate - Error processing LLM update');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async processToolOutput(ep, tool_call_id, data) {
|
||||||
|
try {
|
||||||
|
this.logger.debug({tool_call_id, data}, 'TaskLlmUltravox_S2S:processToolOutput');
|
||||||
|
|
||||||
|
if (!data.type || data.type !== 'client_tool_result') {
|
||||||
|
this.logger.info({data},
|
||||||
|
'TaskLlmUltravox_S2S:processToolOutput - invalid tool output, must be client_tool_result');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, data}, 'TaskLlmUltravox_S2S:processToolOutput - Error processing tool output');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_populateEvents(events) {
|
||||||
|
if (events.includes('all')) {
|
||||||
|
/* work by excluding specific events */
|
||||||
|
const exclude = events
|
||||||
|
.filter((evt) => evt.startsWith('-'))
|
||||||
|
.map((evt) => evt.slice(1));
|
||||||
|
if (exclude.length === 0) this.includeEvents = ultravox_server_events;
|
||||||
|
else this.excludeEvents = expandWildcards(exclude);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* work by including specific events */
|
||||||
|
const include = events
|
||||||
|
.filter((evt) => !evt.startsWith('-'));
|
||||||
|
this.includeEvents = expandWildcards(include);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug({
|
||||||
|
includeEvents: this.includeEvents,
|
||||||
|
excludeEvents: this.excludeEvents
|
||||||
|
}, 'TaskLlmUltravox_S2S:_populateEvents');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TaskLlmUltravox_S2S;
|
||||||
313
lib/tasks/llm/llms/voice_agent_s2s.js
Normal file
313
lib/tasks/llm/llms/voice_agent_s2s.js
Normal file
@@ -0,0 +1,313 @@
|
|||||||
|
const Task = require('../../task');
|
||||||
|
const TaskName = 'Llm_VoiceAgent_s2s';
|
||||||
|
const {LlmEvents_VoiceAgent} = require('../../../utils/constants');
|
||||||
|
const ClientEvent = 'client.event';
|
||||||
|
const SessionDelete = 'session.delete';
|
||||||
|
|
||||||
|
const va_server_events = [
|
||||||
|
'Error',
|
||||||
|
'Welcome',
|
||||||
|
'SettingsApplied',
|
||||||
|
'ConversationText',
|
||||||
|
'UserStartedSpeaking',
|
||||||
|
'EndOfThought',
|
||||||
|
'AgentThinking',
|
||||||
|
'FunctionCallRequest',
|
||||||
|
'FunctionCalling',
|
||||||
|
'AgentStartedSpeaking',
|
||||||
|
'AgentAudioDone',
|
||||||
|
];
|
||||||
|
|
||||||
|
const expandWildcards = (events) => {
|
||||||
|
// no-op for deepgram
|
||||||
|
return events;
|
||||||
|
};
|
||||||
|
|
||||||
|
class TaskLlmVoiceAgent_S2S extends Task {
|
||||||
|
constructor(logger, opts, parentTask) {
|
||||||
|
super(logger, opts, parentTask);
|
||||||
|
this.parent = parentTask;
|
||||||
|
|
||||||
|
this.vendor = this.parent.vendor;
|
||||||
|
this.model = this.parent.model;
|
||||||
|
this.auth = this.parent.auth;
|
||||||
|
this.connectionOptions = this.parent.connectOptions;
|
||||||
|
|
||||||
|
const {apiKey} = this.auth || {};
|
||||||
|
if (!apiKey) throw new Error('auth.apiKey is required for VoiceAgent S2S');
|
||||||
|
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
this.authType = 'bearer';
|
||||||
|
this.actionHook = this.data.actionHook;
|
||||||
|
this.eventHook = this.data.eventHook;
|
||||||
|
this.toolHook = this.data.toolHook;
|
||||||
|
const {settingsConfiguration} = this.data.llmOptions;
|
||||||
|
|
||||||
|
if (typeof settingsConfiguration !== 'object') {
|
||||||
|
throw new Error('llmOptions with an initial settingsConfiguration is required for VoiceAgent S2S');
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
const {audio, ...rest} = settingsConfiguration;
|
||||||
|
const cfg = this.settingsConfiguration = rest;
|
||||||
|
|
||||||
|
if (!cfg.agent) throw new Error('llmOptions.settingsConfiguration.agent is required for VoiceAgent S2S');
|
||||||
|
if (!cfg.agent.think) {
|
||||||
|
throw new Error('llmOptions.settingsConfiguration.agent.think is required for VoiceAgent S2S');
|
||||||
|
}
|
||||||
|
if (!cfg.agent.think.model) {
|
||||||
|
throw new Error('llmOptions.settingsConfiguration.agent.think.model is required for VoiceAgent S2S');
|
||||||
|
}
|
||||||
|
if (!cfg.agent.think.provider?.type) {
|
||||||
|
throw new Error('llmOptions.settingsConfiguration.agent.think.provider.type is required for VoiceAgent S2S');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'normal conversation end'
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* only one of these will have items,
|
||||||
|
* if includeEvents, then these are the events to include
|
||||||
|
* if excludeEvents, then these are the events to exclude
|
||||||
|
*/
|
||||||
|
this.includeEvents = [];
|
||||||
|
this.excludeEvents = [];
|
||||||
|
|
||||||
|
/* default to all events if user did not specify */
|
||||||
|
this._populateEvents(this.data.events || va_server_events);
|
||||||
|
|
||||||
|
this.addCustomEventListener = parentTask.addCustomEventListener.bind(parentTask);
|
||||||
|
this.removeCustomEventListeners = parentTask.removeCustomEventListeners.bind(parentTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
get name() { return TaskName; }
|
||||||
|
|
||||||
|
get host() {
|
||||||
|
const {host} = this.connectionOptions || {};
|
||||||
|
return host || 'agent.deepgram.com';
|
||||||
|
}
|
||||||
|
|
||||||
|
get path() {
|
||||||
|
const {path} = this.connectionOptions || {};
|
||||||
|
if (path) return path;
|
||||||
|
|
||||||
|
return '/agent';
|
||||||
|
}
|
||||||
|
|
||||||
|
async _api(ep, args) {
|
||||||
|
const res = await ep.api('uuid_voice_agent_s2s', `^^|${args.join('|')}`);
|
||||||
|
if (!res.body?.startsWith('+OK')) {
|
||||||
|
throw new Error(`Error calling uuid_voice_agent_s2s: ${JSON.stringify(res.body)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exec(cs, {ep}) {
|
||||||
|
await super.exec(cs);
|
||||||
|
|
||||||
|
await this._startListening(cs, ep);
|
||||||
|
|
||||||
|
await this.awaitTaskDone();
|
||||||
|
|
||||||
|
/* note: the parent llm verb started the span, which is why this is necessary */
|
||||||
|
await this.parent.performAction(this.results);
|
||||||
|
|
||||||
|
this._unregisterHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
async kill(cs) {
|
||||||
|
super.kill(cs);
|
||||||
|
|
||||||
|
this._api(cs.ep, [cs.ep.uuid, SessionDelete])
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmVoiceAgent_S2S:kill - error deleting session'));
|
||||||
|
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send function call response to the VoiceAgent server
|
||||||
|
*/
|
||||||
|
async processToolOutput(ep, tool_call_id, data) {
|
||||||
|
try {
|
||||||
|
const {data:response} = data;
|
||||||
|
this.logger.debug({tool_call_id, response}, 'TaskLlmVoiceAgent_S2S:processToolOutput');
|
||||||
|
|
||||||
|
if (!response.type || response.type !== 'FunctionCallResponse') {
|
||||||
|
this.logger.info({response},
|
||||||
|
'TaskLlmVoiceAgent_S2S:processToolOutput - invalid tool output, must be FunctionCallResponse');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(response)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmVoiceAgent_S2S:processToolOutput');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a session.update to the VoiceAgent server
|
||||||
|
* Note: creating and deleting conversation items also supported as well as interrupting the assistant
|
||||||
|
*/
|
||||||
|
async processLlmUpdate(ep, data, _callSid) {
|
||||||
|
try {
|
||||||
|
this.logger.debug({data, _callSid}, 'TaskLlmVoiceAgent_S2S:processLlmUpdate');
|
||||||
|
|
||||||
|
if (!data.type || ![
|
||||||
|
'UpdateInstructions',
|
||||||
|
'UpdateSpeak',
|
||||||
|
'InjectAgentMessage',
|
||||||
|
].includes(data.type)) {
|
||||||
|
this.logger.info({data}, 'TaskLlmVoiceAgent_S2S:processLlmUpdate - invalid mid-call request');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await this._api(ep, [ep.uuid, ClientEvent, JSON.stringify(data)]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskLlmVoiceAgent_S2S:processLlmUpdate');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _startListening(cs, ep) {
|
||||||
|
this._registerHandlers(ep);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, 'session.create', this.host, this.path, this.authType, this.apiKey];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error({err}, `TaskLlmVoiceAgent_S2S:_startListening: ${JSON.stringify(err)}`);
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendClientEvent(ep, obj) {
|
||||||
|
let ok = true;
|
||||||
|
this.logger.debug({obj}, 'TaskLlmVoiceAgent_S2S:_sendClientEvent');
|
||||||
|
try {
|
||||||
|
const args = [ep.uuid, ClientEvent, JSON.stringify(obj)];
|
||||||
|
await this._api(ep, args);
|
||||||
|
} catch (err) {
|
||||||
|
ok = false;
|
||||||
|
this.logger.error({err}, 'TaskLlmVoiceAgent_S2S:_sendClientEvent - Error');
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _sendInitialMessage(ep) {
|
||||||
|
if (!await this._sendClientEvent(ep, this.settingsConfiguration)) {
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_registerHandlers(ep) {
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_VoiceAgent.Connect, this._onConnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_VoiceAgent.ConnectFailure, this._onConnectFailure.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_VoiceAgent.Disconnect, this._onDisconnect.bind(this, ep));
|
||||||
|
this.addCustomEventListener(ep, LlmEvents_VoiceAgent.ServerEvent, this._onServerEvent.bind(this, ep));
|
||||||
|
}
|
||||||
|
|
||||||
|
_unregisterHandlers() {
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onError(_ep, evt) {
|
||||||
|
this.logger.info({evt}, 'TaskLlmVoiceAgent_S2S:_onError');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
_onConnect(ep) {
|
||||||
|
this.logger.debug('TaskLlmVoiceAgent_S2S:_onConnect');
|
||||||
|
this._sendInitialMessage(ep);
|
||||||
|
}
|
||||||
|
_onConnectFailure(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmVoiceAgent_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'connection failure'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
_onDisconnect(_ep, evt) {
|
||||||
|
this.logger.info(evt, 'TaskLlmVoiceAgent_S2S:_onConnectFailure');
|
||||||
|
this.results = {completionReason: 'disconnect from remote end'};
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
async _onServerEvent(_ep, evt) {
|
||||||
|
let endConversation = false;
|
||||||
|
const type = evt.type;
|
||||||
|
this.logger.info({evt}, 'TaskLlmVoiceAgent_S2S:_onServerEvent');
|
||||||
|
|
||||||
|
/* check for failures, such as rate limit exceeded, that should terminate the conversation */
|
||||||
|
if (type === 'response.done' && evt.response.status === 'failed') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server failure',
|
||||||
|
error: evt.response.status_details?.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* server errors of some sort */
|
||||||
|
else if (type === 'error') {
|
||||||
|
endConversation = true;
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'server error',
|
||||||
|
error: evt.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tool calls */
|
||||||
|
else if (type === 'FunctionCallRequest') {
|
||||||
|
this.logger.debug({evt}, 'TaskLlmVoiceAgent_S2S:_onServerEvent - function_call');
|
||||||
|
if (!this.toolHook) {
|
||||||
|
this.logger.warn({evt}, 'TaskLlmVoiceAgent_S2S:_onServerEvent - no toolHook defined!');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const {function_name:name, function_call_id:call_id} = evt;
|
||||||
|
const args = evt.input;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.parent.sendToolHook(call_id, {name, args});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err, evt}, 'TaskLlmVoiceAgent - error calling function');
|
||||||
|
this.results = {
|
||||||
|
completionReason: 'client error calling function',
|
||||||
|
error: err
|
||||||
|
};
|
||||||
|
endConversation = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* check whether we should notify on this event */
|
||||||
|
if (this.includeEvents.length > 0 ? this.includeEvents.includes(type) : !this.excludeEvents.includes(type)) {
|
||||||
|
this.parent.sendEventHook(evt)
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskLlmVoiceAgent_S2S:_onServerEvent - error sending event hook'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endConversation) {
|
||||||
|
this.logger.info({results: this.results},
|
||||||
|
'TaskLlmVoiceAgent_S2S:_onServerEvent - ending conversation due to error');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_populateEvents(events) {
|
||||||
|
if (events.includes('all')) {
|
||||||
|
/* work by excluding specific events */
|
||||||
|
const exclude = events
|
||||||
|
.filter((evt) => evt.startsWith('-'))
|
||||||
|
.map((evt) => evt.slice(1));
|
||||||
|
if (exclude.length === 0) this.includeEvents = va_server_events;
|
||||||
|
else this.excludeEvents = expandWildcards(exclude);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* work by including specific events */
|
||||||
|
const include = events
|
||||||
|
.filter((evt) => !evt.startsWith('-'));
|
||||||
|
this.includeEvents = expandWildcards(include);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug({
|
||||||
|
includeEvents: this.includeEvents,
|
||||||
|
excludeEvents: this.excludeEvents
|
||||||
|
}, 'TaskLlmVoiceAgent_S2S:_populateEvents');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TaskLlmVoiceAgent_S2S;
|
||||||
@@ -62,6 +62,9 @@ function makeTask(logger, obj, parent) {
|
|||||||
case TaskName.Message:
|
case TaskName.Message:
|
||||||
const TaskMessage = require('./message');
|
const TaskMessage = require('./message');
|
||||||
return new TaskMessage(logger, data, parent);
|
return new TaskMessage(logger, data, parent);
|
||||||
|
case TaskName.Llm:
|
||||||
|
const TaskLlm = require('./llm');
|
||||||
|
return new TaskLlm(logger, data, parent);
|
||||||
case TaskName.Rasa:
|
case TaskName.Rasa:
|
||||||
const TaskRasa = require('./rasa');
|
const TaskRasa = require('./rasa');
|
||||||
return new TaskRasa(logger, data, parent);
|
return new TaskRasa(logger, data, parent);
|
||||||
@@ -81,6 +84,7 @@ function makeTask(logger, obj, parent) {
|
|||||||
const TaskTranscribe = require('./transcribe');
|
const TaskTranscribe = require('./transcribe');
|
||||||
return new TaskTranscribe(logger, data, parent);
|
return new TaskTranscribe(logger, data, parent);
|
||||||
case TaskName.Listen:
|
case TaskName.Listen:
|
||||||
|
case TaskName.Stream:
|
||||||
const TaskListen = require('./listen');
|
const TaskListen = require('./listen');
|
||||||
return new TaskListen(logger, data, parent);
|
return new TaskListen(logger, data, parent);
|
||||||
case TaskName.Redirect:
|
case TaskName.Redirect:
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
const Task = require('./task');
|
const Task = require('./task');
|
||||||
const {TaskName, TaskPreconditions} = require('../utils/constants');
|
const {TaskName, TaskPreconditions} = require('../utils/constants');
|
||||||
|
const { PlayFileNotFoundError } = require('../utils/error');
|
||||||
|
|
||||||
class TaskPlay extends Task {
|
class TaskPlay extends Task {
|
||||||
constructor(logger, opts) {
|
constructor(logger, opts) {
|
||||||
@@ -66,8 +67,20 @@ class TaskPlay extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (timeout) clearTimeout(timeout);
|
this.logger.info(`TaskPlay:exec - error playing ${this.url}: ${err.message}`);
|
||||||
this.logger.info(err, `TaskPlay:exec - error playing ${this.url}`);
|
this.playComplete = true;
|
||||||
|
if (err.message === 'File Not Found') {
|
||||||
|
const {writeAlerts, AlertType} = cs.srf.locals;
|
||||||
|
await this.performAction({status: 'fail', reason: 'playFailed'}, !(this.parentTask || cs.isConfirmCallSession));
|
||||||
|
this.emit('playDone');
|
||||||
|
writeAlerts({
|
||||||
|
account_sid: cs.accountSid,
|
||||||
|
alert_type: AlertType.PLAY_FILENOTFOUND,
|
||||||
|
url: this.url,
|
||||||
|
target_sid: cs.callSid
|
||||||
|
});
|
||||||
|
throw new PlayFileNotFoundError(this.url);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this.emit('playDone');
|
this.emit('playDone');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
const Task = require('./task');
|
const Task = require('./task');
|
||||||
const {TaskName} = require('../utils/constants');
|
const {TaskName} = require('../utils/constants');
|
||||||
|
const WsRequestor = require('../utils/ws-requestor');
|
||||||
|
const URL = require('url');
|
||||||
|
const HttpRequestor = require('../utils/http-requestor');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Redirects to a new application
|
* Redirects to a new application
|
||||||
@@ -13,6 +16,32 @@ class TaskRedirect extends Task {
|
|||||||
|
|
||||||
async exec(cs) {
|
async exec(cs) {
|
||||||
await super.exec(cs);
|
await super.exec(cs);
|
||||||
|
|
||||||
|
if (cs.requestor instanceof WsRequestor && cs.application.requestor._isAbsoluteUrl(this.actionHook)) {
|
||||||
|
this.logger.info(`Task:performAction redirecting to ${this.actionHook}, requires new ws connection`);
|
||||||
|
try {
|
||||||
|
this.cs.requestor.close();
|
||||||
|
const requestor = new WsRequestor(this.logger, cs.accountSid, {url: this.actionHook}, this.webhook_secret) ;
|
||||||
|
this.cs.application.requestor = requestor;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, `Task:performAction error redirecting to ${this.actionHook}`);
|
||||||
|
}
|
||||||
|
} else if (cs.application.requestor._isAbsoluteUrl(this.actionHook)) {
|
||||||
|
const baseUrl = this.cs.application.requestor.baseUrl;
|
||||||
|
const newUrl = URL.parse(this.actionHook);
|
||||||
|
const newBaseUrl = newUrl.protocol + '//' + newUrl.host;
|
||||||
|
if (baseUrl != newBaseUrl) {
|
||||||
|
try {
|
||||||
|
this.logger.info(`Task:redirect updating base url to ${newBaseUrl}`);
|
||||||
|
const newRequestor = new HttpRequestor(this.logger, cs.accountSid, {url: this.actionHook},
|
||||||
|
cs.accountInfo.account.webhook_secret);
|
||||||
|
this.cs.requestor.removeAllListeners();
|
||||||
|
this.cs.application.requestor = newRequestor;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, `Task:redirect error updating base url to ${this.actionHook}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
await this.performAction();
|
await this.performAction();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,13 @@ class TaskRestDial extends Task {
|
|||||||
|
|
||||||
this.from = this.data.from;
|
this.from = this.data.from;
|
||||||
this.callerName = this.data.callerName;
|
this.callerName = this.data.callerName;
|
||||||
|
this.timeLimit = this.data.timeLimit;
|
||||||
this.fromHost = this.data.fromHost;
|
this.fromHost = this.data.fromHost;
|
||||||
this.to = this.data.to;
|
this.to = this.data.to;
|
||||||
this.call_hook = this.data.call_hook;
|
this.call_hook = this.data.call_hook;
|
||||||
this.timeout = this.data.timeout || 60;
|
this.timeout = this.data.timeout || 60;
|
||||||
this.sipRequestWithinDialogHook = this.data.sipRequestWithinDialogHook;
|
this.sipRequestWithinDialogHook = this.data.sipRequestWithinDialogHook;
|
||||||
|
this.referHook = this.data.referHook;
|
||||||
|
|
||||||
this.on('connect', this._onConnect.bind(this));
|
this.on('connect', this._onConnect.bind(this));
|
||||||
this.on('callStatus', this._onCallStatus.bind(this));
|
this.on('callStatus', this._onCallStatus.bind(this));
|
||||||
@@ -38,9 +40,9 @@ class TaskRestDial extends Task {
|
|||||||
|
|
||||||
if (this.data.amd) {
|
if (this.data.amd) {
|
||||||
this.startAmd = cs.startAmd;
|
this.startAmd = cs.startAmd;
|
||||||
this.stopAmd = cs.stopAmd;
|
|
||||||
this.on('amd', this._onAmdEvent.bind(this, cs));
|
this.on('amd', this._onAmdEvent.bind(this, cs));
|
||||||
}
|
}
|
||||||
|
this.stopAmd = cs.stopAmd;
|
||||||
|
|
||||||
this._setCallTimer();
|
this._setCallTimer();
|
||||||
await this.awaitTaskDone();
|
await this.awaitTaskDone();
|
||||||
@@ -64,6 +66,10 @@ class TaskRestDial extends Task {
|
|||||||
this.canCancel = false;
|
this.canCancel = false;
|
||||||
const cs = this.callSession;
|
const cs = this.callSession;
|
||||||
cs.setDialog(dlg);
|
cs.setDialog(dlg);
|
||||||
|
cs.referHook = this.referHook;
|
||||||
|
if (this.timeLimit) {
|
||||||
|
cs.startMaxCallDurationTimer(this.timeLimit);
|
||||||
|
}
|
||||||
this.logger.debug('TaskRestDial:_onConnect - call connected');
|
this.logger.debug('TaskRestDial:_onConnect - call connected');
|
||||||
if (this.sipRequestWithinDialogHook) this._initSipRequestWithinDialogHandler(cs, dlg);
|
if (this.sipRequestWithinDialogHook) this._initSipRequestWithinDialogHandler(cs, dlg);
|
||||||
try {
|
try {
|
||||||
@@ -75,11 +81,13 @@ class TaskRestDial extends Task {
|
|||||||
synthesizer: {
|
synthesizer: {
|
||||||
vendor: cs.speechSynthesisVendor,
|
vendor: cs.speechSynthesisVendor,
|
||||||
language: cs.speechSynthesisLanguage,
|
language: cs.speechSynthesisLanguage,
|
||||||
voice: cs.speechSynthesisVoice
|
voice: cs.speechSynthesisVoice,
|
||||||
|
label: cs.speechSynthesisLabel,
|
||||||
},
|
},
|
||||||
recognizer: {
|
recognizer: {
|
||||||
vendor: cs.speechRecognizerVendor,
|
vendor: cs.speechRecognizerVendor,
|
||||||
language: cs.speechRecognizerLanguage
|
language: cs.speechRecognizerLanguage,
|
||||||
|
label: cs.speechRecognizerLabel,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
254
lib/tasks/say.js
254
lib/tasks/say.js
@@ -1,6 +1,8 @@
|
|||||||
|
const assert = require('assert');
|
||||||
const TtsTask = require('./tts-task');
|
const TtsTask = require('./tts-task');
|
||||||
const {TaskName, TaskPreconditions} = require('../utils/constants');
|
const {TaskName, TaskPreconditions} = require('../utils/constants');
|
||||||
const pollySSMLSplit = require('polly-ssml-split');
|
const pollySSMLSplit = require('polly-ssml-split');
|
||||||
|
const { SpeechCredentialError } = require('../utils/error');
|
||||||
|
|
||||||
const breakLengthyTextIfNeeded = (logger, text) => {
|
const breakLengthyTextIfNeeded = (logger, text) => {
|
||||||
const chunkSize = 1000;
|
const chunkSize = 1000;
|
||||||
@@ -34,45 +36,118 @@ class TaskSay extends TtsTask {
|
|||||||
super(logger, opts, parentTask);
|
super(logger, opts, parentTask);
|
||||||
this.preconditions = TaskPreconditions.Endpoint;
|
this.preconditions = TaskPreconditions.Endpoint;
|
||||||
|
|
||||||
this.text = (Array.isArray(this.data.text) ? this.data.text : [this.data.text])
|
assert.ok((typeof this.data.text === 'string' || Array.isArray(this.data.text)) || this.data.stream === true,
|
||||||
.map((t) => breakLengthyTextIfNeeded(this.logger, t))
|
'Say: either text or stream:true is required');
|
||||||
.flat();
|
|
||||||
|
|
||||||
this.loop = this.data.loop || 1;
|
|
||||||
this.isHandledByPrimaryProvider = true;
|
if (this.data.stream === true) {
|
||||||
|
this._isStreamingTts = true;
|
||||||
|
this.closeOnStreamEmpty = this.data.closeOnStreamEmpty !== false;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
this._isStreamingTts = false;
|
||||||
|
this.text = (Array.isArray(this.data.text) ? this.data.text : [this.data.text])
|
||||||
|
.map((t) => breakLengthyTextIfNeeded(this.logger, t))
|
||||||
|
.flat();
|
||||||
|
|
||||||
|
this.loop = this.data.loop || 1;
|
||||||
|
this.isHandledByPrimaryProvider = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get name() { return TaskName.Say; }
|
get name() { return TaskName.Say; }
|
||||||
|
|
||||||
get summary() {
|
get summary() {
|
||||||
for (let i = 0; i < this.text.length; i++) {
|
if (this.isStreamingTts) return `${this.name} streaming`;
|
||||||
if (this.text[i].startsWith('silence_stream')) continue;
|
else {
|
||||||
return `${this.name}{text=${this.text[i].slice(0, 15)}${this.text[i].length > 15 ? '...' : ''}}`;
|
for (let i = 0; i < this.text.length; i++) {
|
||||||
|
if (this.text[i].startsWith('silence_stream')) continue;
|
||||||
|
return `${this.name}{text=${this.text[i].slice(0, 15)}${this.text[i].length > 15 ? '...' : ''}}`;
|
||||||
|
}
|
||||||
|
return `${this.name}{${this.text[0]}}`;
|
||||||
}
|
}
|
||||||
return `${this.name}{${this.text[0]}}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async exec(cs, {ep}) {
|
get isStreamingTts() { return this._isStreamingTts; }
|
||||||
const {srf, accountSid:account_sid} = cs;
|
|
||||||
|
_validateURL(urlString) {
|
||||||
|
try {
|
||||||
|
new URL(urlString);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exec(cs, obj) {
|
||||||
|
if (this.isStreamingTts && !cs.appIsUsingWebsockets) {
|
||||||
|
throw new Error('Say: streaming say verb requires applications to use the websocket API');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (this.isStreamingTts) await this.handlingStreaming(cs, obj);
|
||||||
|
else await this.handling(cs, obj);
|
||||||
|
this.emit('playDone');
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof SpeechCredentialError) {
|
||||||
|
// if say failed due to speech credentials, alarm is writtern and error notification is sent
|
||||||
|
// finished this say to move to next task.
|
||||||
|
this.logger.info({error}, 'Say failed due to SpeechCredentialError, finished!');
|
||||||
|
this.emit('playDone');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handlingStreaming(cs, {ep}) {
|
||||||
|
const {vendor, language, voice, label} = this.getTtsVendorData(cs);
|
||||||
|
const credentials = cs.getSpeechCredentials(vendor, 'tts', label);
|
||||||
|
if (!credentials) {
|
||||||
|
throw new SpeechCredentialError(
|
||||||
|
`No text-to-speech service credentials for ${vendor} with labels: ${label} have been configured`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
await this.setTtsStreamingChannelVars(vendor, language, voice, credentials, ep);
|
||||||
|
|
||||||
|
await cs.startTtsStream();
|
||||||
|
|
||||||
|
cs.requestor?.request('tts:streaming-event', '/streaming-event', {event_type: 'stream_open'})
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskSay:handlingStreaming - Error sending'));
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'TaskSay:handlingStreaming - Error setting channel vars');
|
||||||
|
cs.requestor?.request('tts:streaming-event', '/streaming-event', {event_type: 'stream_closed'})
|
||||||
|
.catch((err) => this.logger.info({err}, 'TaskSay:handlingStreaming - Error sending'));
|
||||||
|
|
||||||
|
//TODO: send tts:streaming-event with error?
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.awaitTaskDone();
|
||||||
|
this.logger.info('TaskSay:handlingStreaming - done');
|
||||||
|
}
|
||||||
|
|
||||||
|
async handling(cs, {ep}) {
|
||||||
|
const {srf, accountSid:account_sid, callSid:target_sid} = cs;
|
||||||
const {writeAlerts, AlertType} = srf.locals;
|
const {writeAlerts, AlertType} = srf.locals;
|
||||||
const {addFileToCache} = srf.locals.dbHelpers;
|
const {addFileToCache} = srf.locals.dbHelpers;
|
||||||
const engine = this.synthesizer.engine || 'standard';
|
const engine = this.synthesizer.engine || cs.synthesizer?.engine || 'neural';
|
||||||
|
|
||||||
await super.exec(cs);
|
await super.exec(cs);
|
||||||
this.ep = ep;
|
this.ep = ep;
|
||||||
|
|
||||||
const vendor = this.synthesizer.vendor && this.synthesizer.vendor !== 'default' ?
|
let vendor = this.synthesizer.vendor && this.synthesizer.vendor !== 'default' ?
|
||||||
this.synthesizer.vendor :
|
this.synthesizer.vendor :
|
||||||
cs.speechSynthesisVendor;
|
cs.speechSynthesisVendor;
|
||||||
const language = this.synthesizer.language && this.synthesizer.language !== 'default' ?
|
let language = this.synthesizer.language && this.synthesizer.language !== 'default' ?
|
||||||
this.synthesizer.language :
|
this.synthesizer.language :
|
||||||
cs.speechSynthesisLanguage ;
|
cs.speechSynthesisLanguage ;
|
||||||
const voice = this.synthesizer.voice && this.synthesizer.voice !== 'default' ?
|
let voice = this.synthesizer.voice && this.synthesizer.voice !== 'default' ?
|
||||||
this.synthesizer.voice :
|
this.synthesizer.voice :
|
||||||
cs.speechSynthesisVoice;
|
cs.speechSynthesisVoice;
|
||||||
const label = this.synthesizer.label && this.synthesizer.label !== 'default' ?
|
let label = this.taskIncludeSynthesizer ? this.synthesizer.label : cs.speechSynthesisLabel;
|
||||||
this.synthesizer.label :
|
|
||||||
cs.speechSynthesisLabel;
|
|
||||||
|
|
||||||
const fallbackVendor = this.synthesizer.fallbackVendor && this.synthesizer.fallbackVendor !== 'default' ?
|
const fallbackVendor = this.synthesizer.fallbackVendor && this.synthesizer.fallbackVendor !== 'default' ?
|
||||||
this.synthesizer.fallbackVendor :
|
this.synthesizer.fallbackVendor :
|
||||||
@@ -83,16 +158,22 @@ class TaskSay extends TtsTask {
|
|||||||
const fallbackVoice = this.synthesizer.fallbackVoice && this.synthesizer.fallbackVoice !== 'default' ?
|
const fallbackVoice = this.synthesizer.fallbackVoice && this.synthesizer.fallbackVoice !== 'default' ?
|
||||||
this.synthesizer.fallbackVoice :
|
this.synthesizer.fallbackVoice :
|
||||||
cs.fallbackSpeechSynthesisVoice;
|
cs.fallbackSpeechSynthesisVoice;
|
||||||
const fallbackLabel = this.synthesizer.fallbackLabel && this.synthesizer.fallbackLabel !== 'default' ?
|
const fallbackLabel = this.taskIncludeSynthesizer ?
|
||||||
this.synthesizer.fallbackLabel :
|
this.synthesizer.fallbackLabel : cs.fallbackSpeechSynthesisLabel;
|
||||||
cs.fallbackSpeechSynthesisLabel;
|
|
||||||
|
|
||||||
let filepath;
|
if (cs.hasFallbackTts) {
|
||||||
try {
|
vendor = fallbackVendor;
|
||||||
filepath = await this._synthesizeWithSpecificVendor(cs, ep, {vendor, language, voice, label});
|
language = fallbackLanguage;
|
||||||
} catch (error) {
|
voice = fallbackVoice;
|
||||||
if (fallbackVendor && this.isHandledByPrimaryProvider) {
|
label = fallbackLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
const startFallback = async(error) => {
|
||||||
|
if (fallbackVendor && this.isHandledByPrimaryProvider && !cs.hasFallbackTts) {
|
||||||
|
this.notifyError(
|
||||||
|
{ msg: 'TTS error', details:`TTS vendor ${vendor} error: ${error}`, failover: 'in progress'});
|
||||||
this.isHandledByPrimaryProvider = false;
|
this.isHandledByPrimaryProvider = false;
|
||||||
|
cs.hasFallbackTts = true;
|
||||||
this.logger.info(`Synthesize error, fallback to ${fallbackVendor}`);
|
this.logger.info(`Synthesize error, fallback to ${fallbackVendor}`);
|
||||||
filepath = await this._synthesizeWithSpecificVendor(cs, ep,
|
filepath = await this._synthesizeWithSpecificVendor(cs, ep,
|
||||||
{
|
{
|
||||||
@@ -102,8 +183,16 @@ class TaskSay extends TtsTask {
|
|||||||
label: fallbackLabel
|
label: fallbackLabel
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
throw error;
|
this.notifyError(
|
||||||
|
{ msg: 'TTS error', details:`TTS vendor ${vendor} error: ${error}`, failover: 'not available'});
|
||||||
|
throw new SpeechCredentialError(error.message);
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
let filepath;
|
||||||
|
try {
|
||||||
|
filepath = await this._synthesizeWithSpecificVendor(cs, ep, {vendor, language, voice, label});
|
||||||
|
} catch (error) {
|
||||||
|
await startFallback(error);
|
||||||
}
|
}
|
||||||
this.notifyStatus({event: 'start-playback'});
|
this.notifyStatus({event: 'start-playback'});
|
||||||
|
|
||||||
@@ -115,31 +204,35 @@ class TaskSay extends TtsTask {
|
|||||||
await this.playToConfMember(ep, memberId, confName, confUuid, filepath[segment]);
|
await this.playToConfMember(ep, memberId, confName, confUuid, filepath[segment]);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (filepath[segment].startsWith('say:{')) {
|
const isStreaming = filepath[segment].startsWith('say:{');
|
||||||
|
if (isStreaming) {
|
||||||
const arr = /^say:\{.*\}\s*(.*)$/.exec(filepath[segment]);
|
const arr = /^say:\{.*\}\s*(.*)$/.exec(filepath[segment]);
|
||||||
if (arr) this.logger.debug(`Say:exec sending streaming tts request: ${arr[1].substring(0, 64)}..`);
|
if (arr) this.logger.debug(`Say:exec sending streaming tts request: ${arr[1].substring(0, 64)}..`);
|
||||||
}
|
}
|
||||||
else this.logger.debug(`Say:exec sending ${filepath[segment].substring(0, 64)}`);
|
else this.logger.debug(`Say:exec sending ${filepath[segment].substring(0, 64)}`);
|
||||||
ep.once('playback-start', (evt) => {
|
ep.once('playback-start', (evt) => {
|
||||||
this.logger.debug({evt}, 'got playback-start');
|
this.logger.debug({evt}, 'Say got playback-start');
|
||||||
if (this.otelSpan) {
|
if (this.otelSpan) {
|
||||||
this._addStreamingTtsAttributes(this.otelSpan, evt);
|
this._addStreamingTtsAttributes(this.otelSpan, evt, vendor);
|
||||||
this.otelSpan.end();
|
this.otelSpan.end();
|
||||||
this.otelSpan = null;
|
this.otelSpan = null;
|
||||||
if (evt.variable_tts_cache_filename) cs.trackTmpFile(evt.variable_tts_cache_filename);
|
if (evt.variable_tts_cache_filename) {
|
||||||
|
cs.trackTmpFile(evt.variable_tts_cache_filename);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ep.once('playback-stop', (evt) => {
|
ep.once('playback-stop', (evt) => {
|
||||||
this.logger.debug({evt}, 'got playback-stop');
|
this.logger.debug({evt}, 'Say got playback-stop');
|
||||||
if (evt.variable_tts_error) {
|
if (evt.variable_tts_error) {
|
||||||
writeAlerts({
|
writeAlerts({
|
||||||
account_sid,
|
account_sid,
|
||||||
alert_type: AlertType.TTS_FAILURE,
|
alert_type: AlertType.TTS_FAILURE,
|
||||||
vendor,
|
vendor,
|
||||||
detail: evt.variable_tts_error
|
detail: evt.variable_tts_error,
|
||||||
|
target_sid
|
||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for no tts'));
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for no tts'));
|
||||||
}
|
}
|
||||||
if (evt.variable_tts_cache_filename) {
|
if (evt.variable_tts_cache_filename && !this.killed) {
|
||||||
const text = parseTextFromSayString(this.text[segment]);
|
const text = parseTextFromSayString(this.text[segment]);
|
||||||
addFileToCache(evt.variable_tts_cache_filename, {
|
addFileToCache(evt.variable_tts_cache_filename, {
|
||||||
account_sid,
|
account_sid,
|
||||||
@@ -147,21 +240,49 @@ class TaskSay extends TtsTask {
|
|||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
engine,
|
engine,
|
||||||
|
model: this.model || this.model_id,
|
||||||
text
|
text
|
||||||
}).catch((err) => this.logger.info({err}, 'Error adding file to cache'));
|
}).catch((err) => this.logger.info({err}, 'Error adding file to cache'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this._playResolve) {
|
||||||
|
evt.variable_tts_error ? this._playReject(new Error(evt.variable_tts_error)) : this._playResolve();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
await ep.play(filepath[segment]);
|
// wait for playback-stop event received to confirm if the playback is successful
|
||||||
|
this._playPromise = new Promise((resolve, reject) => {
|
||||||
|
this._playResolve = resolve;
|
||||||
|
this._playReject = reject;
|
||||||
|
});
|
||||||
|
const r = await ep.play(filepath[segment]);
|
||||||
|
this.logger.debug({r}, 'Say:exec play result');
|
||||||
|
try {
|
||||||
|
// wait for playback-stop event received to confirm if the playback is successful
|
||||||
|
await this._playPromise;
|
||||||
|
} catch (err) {
|
||||||
|
try {
|
||||||
|
await startFallback(err);
|
||||||
|
continue;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({err}, 'Error waiting for playback-stop event');
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this._playPromise = null;
|
||||||
|
this._playResolve = null;
|
||||||
|
this._playReject = null;
|
||||||
|
}
|
||||||
if (filepath[segment].startsWith('say:{')) {
|
if (filepath[segment].startsWith('say:{')) {
|
||||||
const arr = /^say:\{.*\}\s*(.*)$/.exec(filepath[segment]);
|
const arr = /^say:\{.*\}\s*(.*)$/.exec(filepath[segment]);
|
||||||
if (arr) this.logger.debug(`Say:exec complete playing streaming tts request: ${arr[1].substring(0, 64)}..`);
|
if (arr) this.logger.debug(`Say:exec complete playing streaming tts request: ${arr[1].substring(0, 64)}..`);
|
||||||
|
} else {
|
||||||
|
// This log will print spech credentials in say command for tts stream mode
|
||||||
|
this.logger.debug(`Say:exec completed play file ${filepath[segment]}`);
|
||||||
}
|
}
|
||||||
this.logger.debug(`Say:exec completed play file ${filepath[segment]}`);
|
|
||||||
}
|
}
|
||||||
segment++;
|
segment++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.emit('playDone');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async kill(cs) {
|
async kill(cs) {
|
||||||
@@ -178,26 +299,50 @@ class TaskSay extends TtsTask {
|
|||||||
}
|
}
|
||||||
this.ep.removeAllListeners('playback-start');
|
this.ep.removeAllListeners('playback-start');
|
||||||
this.ep.removeAllListeners('playback-stop');
|
this.ep.removeAllListeners('playback-stop');
|
||||||
|
// if we are waiting for playback-stop event, resolve the promise
|
||||||
|
if (this._playResolve) {
|
||||||
|
this._playResolve();
|
||||||
|
this._playResolve = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
this.notifyTaskDone();
|
||||||
}
|
}
|
||||||
|
|
||||||
_addStreamingTtsAttributes(span, evt) {
|
_addStreamingTtsAttributes(span, evt, vendor) {
|
||||||
const attrs = {'tts.cached': false};
|
const attrs = {'tts.cached': false};
|
||||||
for (const [key, value] of Object.entries(evt)) {
|
for (const [key, value] of Object.entries(evt)) {
|
||||||
if (key.startsWith('variable_tts_')) {
|
if (key.startsWith('variable_tts_')) {
|
||||||
let newKey = key.substring('variable_tts_'.length)
|
let newKey = key.substring('variable_tts_'.length)
|
||||||
.replace('whisper_', 'whisper.')
|
.replace('whisper_', 'whisper.')
|
||||||
|
.replace('deepgram_', 'deepgram.')
|
||||||
|
.replace('playht_', 'playht.')
|
||||||
|
.replace('cartesia_', 'cartesia.')
|
||||||
|
.replace('rimelabs_', 'rimelabs.')
|
||||||
|
.replace('verbio_', 'verbio.')
|
||||||
.replace('elevenlabs_', 'elevenlabs.');
|
.replace('elevenlabs_', 'elevenlabs.');
|
||||||
if (spanMapping[newKey]) newKey = spanMapping[newKey];
|
if (spanMapping[newKey]) newKey = spanMapping[newKey];
|
||||||
attrs[newKey] = value;
|
attrs[newKey] = value;
|
||||||
|
if (key === 'variable_tts_time_to_first_byte_ms' && value) {
|
||||||
|
this.cs.srf.locals.stats.histogram('tts.response_time', value, [`vendor:${vendor}`]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delete attrs['cache_filename']; //no value in adding this to the span
|
delete attrs['cache_filename']; //no value in adding this to the span
|
||||||
span.setAttributes(attrs);
|
span.setAttributes(attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
notifyTtsStreamIsEmpty() {
|
||||||
|
if (this.isStreamingTts && this.closeOnStreamEmpty) {
|
||||||
|
this.logger.info('TaskSay:notifyTtsStreamIsEmpty - stream is empty, killing task');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const spanMapping = {
|
const spanMapping = {
|
||||||
|
// IMPORTANT!!! JAMBONZ WEBAPP WILL SHOW TEXT PERFECTLY IF THE SPAN NAME IS SMALLER OR EQUAL 25 CHARACTERS.
|
||||||
|
// EX: whisper.ratelim_reqs has length 20 <= 25 which is perfect
|
||||||
|
// Elevenlabs
|
||||||
'elevenlabs.reported_latency_ms': 'elevenlabs.latency_ms',
|
'elevenlabs.reported_latency_ms': 'elevenlabs.latency_ms',
|
||||||
'elevenlabs.request_id': 'elevenlabs.req_id',
|
'elevenlabs.request_id': 'elevenlabs.req_id',
|
||||||
'elevenlabs.history_item_id': 'elevenlabs.item_id',
|
'elevenlabs.history_item_id': 'elevenlabs.item_id',
|
||||||
@@ -205,11 +350,42 @@ const spanMapping = {
|
|||||||
'elevenlabs.name_lookup_time_ms': 'name_lookup_ms',
|
'elevenlabs.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
'elevenlabs.connect_time_ms': 'connect_ms',
|
'elevenlabs.connect_time_ms': 'connect_ms',
|
||||||
'elevenlabs.final_response_time_ms': 'final_response_ms',
|
'elevenlabs.final_response_time_ms': 'final_response_ms',
|
||||||
|
// Whisper
|
||||||
'whisper.reported_latency_ms': 'whisper.latency_ms',
|
'whisper.reported_latency_ms': 'whisper.latency_ms',
|
||||||
'whisper.request_id': 'whisper.req_id',
|
'whisper.request_id': 'whisper.req_id',
|
||||||
|
'whisper.reported_organization': 'whisper.organization',
|
||||||
|
'whisper.reported_ratelimit_requests': 'whisper.ratelimit',
|
||||||
|
'whisper.reported_ratelimit_remaining_requests': 'whisper.ratelimit_remain',
|
||||||
|
'whisper.reported_ratelimit_reset_requests': 'whisper.ratelimit_reset',
|
||||||
'whisper.name_lookup_time_ms': 'name_lookup_ms',
|
'whisper.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
'whisper.connect_time_ms': 'connect_ms',
|
'whisper.connect_time_ms': 'connect_ms',
|
||||||
'whisper.final_response_time_ms': 'final_response_ms',
|
'whisper.final_response_time_ms': 'final_response_ms',
|
||||||
|
// Deepgram
|
||||||
|
'deepgram.request_id': 'deepgram.req_id',
|
||||||
|
'deepgram.reported_model_name': 'deepgram.model_name',
|
||||||
|
'deepgram.reported_model_uuid': 'deepgram.model_uuid',
|
||||||
|
'deepgram.reported_char_count': 'deepgram.char_count',
|
||||||
|
'deepgram.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
|
'deepgram.connect_time_ms': 'connect_ms',
|
||||||
|
'deepgram.final_response_time_ms': 'final_response_ms',
|
||||||
|
// Playht
|
||||||
|
'playht.request_id': 'playht.req_id',
|
||||||
|
'playht.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
|
'playht.connect_time_ms': 'connect_ms',
|
||||||
|
'playht.final_response_time_ms': 'final_response_ms',
|
||||||
|
// Cartesia
|
||||||
|
'cartesia.request_id': 'cartesia.req_id',
|
||||||
|
'cartesia.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
|
'cartesia.connect_time_ms': 'connect_ms',
|
||||||
|
'cartesia.final_response_time_ms': 'final_response_ms',
|
||||||
|
// Rimelabs
|
||||||
|
'rimelabs.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
|
'rimelabs.connect_time_ms': 'connect_ms',
|
||||||
|
'rimelabs.final_response_time_ms': 'final_response_ms',
|
||||||
|
// verbio
|
||||||
|
'verbio.name_lookup_time_ms': 'name_lookup_ms',
|
||||||
|
'verbio.connect_time_ms': 'connect_ms',
|
||||||
|
'verbio.final_response_time_ms': 'final_response_ms',
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = TaskSay;
|
module.exports = TaskSay;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ class TaskSipRefer extends Task {
|
|||||||
|
|
||||||
this.referTo = this.data.referTo;
|
this.referTo = this.data.referTo;
|
||||||
this.referredBy = this.data.referredBy;
|
this.referredBy = this.data.referredBy;
|
||||||
|
this.referredByDisplayName = this.data.referredByDisplayName;
|
||||||
this.headers = this.data.headers || {};
|
this.headers = this.data.headers || {};
|
||||||
this.eventHook = this.data.eventHook;
|
this.eventHook = this.data.eventHook;
|
||||||
}
|
}
|
||||||
@@ -94,7 +95,10 @@ class TaskSipRefer extends Task {
|
|||||||
}
|
}
|
||||||
if (status >= 200) {
|
if (status >= 200) {
|
||||||
this.referSpan.setAttributes({'refer.finalNotify': status});
|
this.referSpan.setAttributes({'refer.finalNotify': status});
|
||||||
await this.performAction({refer_status: 202, final_referred_call_status: status});
|
await this.performAction({refer_status: 202, final_referred_call_status: status})
|
||||||
|
.catch((err) => {
|
||||||
|
this.logger.error(err, 'TaskSipRefer:exec - error performing action finalNotify');
|
||||||
|
});
|
||||||
this.notifyTaskDone();
|
this.notifyTaskDone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -102,7 +106,7 @@ class TaskSipRefer extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_normalizeReferHeaders(cs, dlg) {
|
_normalizeReferHeaders(cs, dlg) {
|
||||||
let {referTo, referredBy} = this;
|
let {referTo, referredBy, referredByDisplayName} = this;
|
||||||
|
|
||||||
/* get IP address of the SBC to use as hostname if needed */
|
/* get IP address of the SBC to use as hostname if needed */
|
||||||
const {host} = parseUri(dlg.remote.uri);
|
const {host} = parseUri(dlg.remote.uri);
|
||||||
@@ -117,9 +121,12 @@ class TaskSipRefer extends Task {
|
|||||||
referredBy = cs.req?.callingNumber || dlg.local.uri;
|
referredBy = cs.req?.callingNumber || dlg.local.uri;
|
||||||
this.logger.info({referredBy}, 'setting referredby');
|
this.logger.info({referredBy}, 'setting referredby');
|
||||||
}
|
}
|
||||||
|
if (!referredByDisplayName) {
|
||||||
|
referredByDisplayName = cs.req?.callingName;
|
||||||
|
}
|
||||||
if (!referredBy.startsWith('<') && !referredBy.startsWith('sip') && !referredBy.startsWith('"')) {
|
if (!referredBy.startsWith('<') && !referredBy.startsWith('sip') && !referredBy.startsWith('"')) {
|
||||||
/* they may have only provided a phone number/user */
|
/* they may have only provided a phone number/user */
|
||||||
referredBy = `sip:${referredBy}@${host}`;
|
referredBy = `${referredByDisplayName ? `"${referredByDisplayName}"` : ''}<sip:${referredBy}@${host}>`;
|
||||||
}
|
}
|
||||||
return {referTo, referredBy};
|
return {referTo, referredBy};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,32 @@ const Task = require('./task');
|
|||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const { TaskPreconditions, CobaltTranscriptionEvents } = require('../utils/constants');
|
const { TaskPreconditions, CobaltTranscriptionEvents } = require('../utils/constants');
|
||||||
|
const { SpeechCredentialError } = require('../utils/error');
|
||||||
|
const {JAMBONES_AWS_TRANSCRIBE_USE_GRPC} = require('../config');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Please insert turns here: {{turns:4}}"
|
||||||
|
// -> { processed: 'Please insert turns here: {{turns}}', turns: 4 }
|
||||||
|
|
||||||
|
processTurnString("Please insert turns here: {{turns}}"));
|
||||||
|
// -> { processed: 'Please insert turns here: {{turns}}', turns: null }
|
||||||
|
*/
|
||||||
|
const processTurnString = (input) => {
|
||||||
|
const regex = /\{\{turns(?::(\d+))?\}\}/;
|
||||||
|
const match = input.match(regex);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
return {
|
||||||
|
processed: input,
|
||||||
|
turns: null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const turns = match[1] ? parseInt(match[1], 10) : null;
|
||||||
|
const processed = input.replace(regex, '{{turns}}');
|
||||||
|
|
||||||
|
return { processed, turns };
|
||||||
|
};
|
||||||
|
|
||||||
class SttTask extends Task {
|
class SttTask extends Task {
|
||||||
|
|
||||||
@@ -16,14 +42,22 @@ class SttTask extends Task {
|
|||||||
normalizeTranscription,
|
normalizeTranscription,
|
||||||
setSpeechCredentialsAtRuntime,
|
setSpeechCredentialsAtRuntime,
|
||||||
compileSonioxTranscripts,
|
compileSonioxTranscripts,
|
||||||
consolidateTranscripts
|
consolidateTranscripts,
|
||||||
|
updateSpeechmaticsPayload
|
||||||
} = require('../utils/transcription-utils')(logger);
|
} = require('../utils/transcription-utils')(logger);
|
||||||
this.setChannelVarsForStt = setChannelVarsForStt;
|
this.setChannelVarsForStt = setChannelVarsForStt;
|
||||||
this.normalizeTranscription = normalizeTranscription;
|
this.normalizeTranscription = normalizeTranscription;
|
||||||
this.compileSonioxTranscripts = compileSonioxTranscripts;
|
this.compileSonioxTranscripts = compileSonioxTranscripts;
|
||||||
this.consolidateTranscripts = consolidateTranscripts;
|
this.consolidateTranscripts = consolidateTranscripts;
|
||||||
|
this.updateSpeechmaticsPayload = updateSpeechmaticsPayload;
|
||||||
this.eventHandlers = [];
|
this.eventHandlers = [];
|
||||||
this.isHandledByPrimaryProvider = true;
|
this.isHandledByPrimaryProvider = true;
|
||||||
|
/**
|
||||||
|
* Task use taskIncludeRecognizer to identify
|
||||||
|
* if taskIncludeRecognizer === true, use label from verb.recognizer, even it's empty
|
||||||
|
* if taskIncludeRecognizer === false, use label from application.recognizer
|
||||||
|
*/
|
||||||
|
this.taskIncludeRecognizer = !!this.data.recognizer;
|
||||||
if (this.data.recognizer) {
|
if (this.data.recognizer) {
|
||||||
const recognizer = this.data.recognizer;
|
const recognizer = this.data.recognizer;
|
||||||
this.vendor = recognizer.vendor;
|
this.vendor = recognizer.vendor;
|
||||||
@@ -33,7 +67,7 @@ class SttTask extends Task {
|
|||||||
//fallback
|
//fallback
|
||||||
this.fallbackVendor = recognizer.fallbackVendor || 'default';
|
this.fallbackVendor = recognizer.fallbackVendor || 'default';
|
||||||
this.fallbackLanguage = recognizer.fallbackLanguage || 'default';
|
this.fallbackLanguage = recognizer.fallbackLanguage || 'default';
|
||||||
this.fallbackLabel = recognizer.fallbackLabel || 'default';
|
this.fallbackLabel = recognizer.fallbackLabel;
|
||||||
|
|
||||||
/* let credentials be supplied in the recognizer object at runtime */
|
/* let credentials be supplied in the recognizer object at runtime */
|
||||||
this.sttCredentials = setSpeechCredentialsAtRuntime(recognizer);
|
this.sttCredentials = setSpeechCredentialsAtRuntime(recognizer);
|
||||||
@@ -81,7 +115,7 @@ class SttTask extends Task {
|
|||||||
this.language = cs.speechRecognizerLanguage;
|
this.language = cs.speechRecognizerLanguage;
|
||||||
if (this.data.recognizer) this.data.recognizer.language = this.language;
|
if (this.data.recognizer) this.data.recognizer.language = this.language;
|
||||||
}
|
}
|
||||||
if ('default' === this.label || !this.label) {
|
if (!this.taskIncludeRecognizer) {
|
||||||
this.label = cs.speechRecognizerLabel;
|
this.label = cs.speechRecognizerLabel;
|
||||||
if (this.data.recognizer) this.data.recognizer.label = this.label;
|
if (this.data.recognizer) this.data.recognizer.label = this.label;
|
||||||
}
|
}
|
||||||
@@ -94,10 +128,22 @@ class SttTask extends Task {
|
|||||||
this.fallbackLanguage = cs.fallbackSpeechRecognizerLanguage;
|
this.fallbackLanguage = cs.fallbackSpeechRecognizerLanguage;
|
||||||
if (this.data.recognizer) this.data.recognizer.fallbackLanguage = this.fallbackLanguage;
|
if (this.data.recognizer) this.data.recognizer.fallbackLanguage = this.fallbackLanguage;
|
||||||
}
|
}
|
||||||
if ('default' === this.fallbackLabel || !this.fallbackLabel) {
|
if (!this.taskIncludeRecognizer) {
|
||||||
this.fallbackLabel = cs.fallbackSpeechRecognizerLabel;
|
this.fallbackLabel = cs.fallbackSpeechRecognizerLabel;
|
||||||
if (this.data.recognizer) this.data.recognizer.fallbackLabel = this.fallbackLabel;
|
if (this.data.recognizer) this.data.recognizer.fallbackLabel = this.fallbackLabel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (cs.hasFallbackAsr) {
|
||||||
|
if (this.taskIncludeRecognizer) {
|
||||||
|
// reset fallback ASR from previous run if this verb contains data.recognizer.
|
||||||
|
cs.hasFallbackAsr = false;
|
||||||
|
} else {
|
||||||
|
this.logger.debug('Call session has fallback to 2nd ASR, use 2nd recognizer configuration');
|
||||||
|
this.vendor = this.fallbackVendor;
|
||||||
|
this.language = this.fallbackLanguage;
|
||||||
|
this.label = this.fallbackLabel;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!this.data.recognizer.vendor) {
|
if (!this.data.recognizer.vendor) {
|
||||||
this.data.recognizer.vendor = this.vendor;
|
this.data.recognizer.vendor = this.vendor;
|
||||||
}
|
}
|
||||||
@@ -115,9 +161,19 @@ class SttTask extends Task {
|
|||||||
try {
|
try {
|
||||||
this.sttCredentials = await this._initSpeechCredentials(this.cs, this.vendor, this.label);
|
this.sttCredentials = await this._initSpeechCredentials(this.cs, this.vendor, this.label);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.fallbackVendor && this.isHandledByPrimaryProvider) {
|
if (this.canFallback) {
|
||||||
await this._fallback();
|
this.notifyError(
|
||||||
|
{
|
||||||
|
msg: 'ASR error', details:`Invalid vendor ${this.vendor}, Error: ${error}`,
|
||||||
|
failover: 'in progress'
|
||||||
|
});
|
||||||
|
await this._initFallback();
|
||||||
} else {
|
} else {
|
||||||
|
this.notifyError(
|
||||||
|
{
|
||||||
|
msg: 'ASR error', details:`Invalid vendor ${this.vendor}, Error: ${error}`,
|
||||||
|
failover: 'not available'
|
||||||
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +205,7 @@ class SttTask extends Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async _initSpeechCredentials(cs, vendor, label) {
|
async _initSpeechCredentials(cs, vendor, label) {
|
||||||
const {getNuanceAccessToken, getIbmAccessToken} = cs.srf.locals.dbHelpers;
|
const {getNuanceAccessToken, getIbmAccessToken, getAwsAuthToken, getVerbioAccessToken} = cs.srf.locals.dbHelpers;
|
||||||
let credentials = cs.getSpeechCredentials(vendor, 'stt', label);
|
let credentials = cs.getSpeechCredentials(vendor, 'stt', label);
|
||||||
|
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
@@ -158,15 +214,11 @@ class SttTask extends Task {
|
|||||||
writeAlerts({
|
writeAlerts({
|
||||||
account_sid: cs.accountSid,
|
account_sid: cs.accountSid,
|
||||||
alert_type: AlertType.STT_NOT_PROVISIONED,
|
alert_type: AlertType.STT_NOT_PROVISIONED,
|
||||||
vendor
|
vendor,
|
||||||
|
target_sid: cs.callSid
|
||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for no stt'));
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for no stt'));
|
||||||
// Notify application that STT vender is wrong.
|
// the ASR might have fallback configuration, should not done task here.
|
||||||
this.notifyError({
|
throw new SpeechCredentialError(`No speech-to-text service credentials for ${vendor} have been configured`);
|
||||||
msg: 'ASR error',
|
|
||||||
details: `No speech-to-text service credentials for ${vendor} have been configured`
|
|
||||||
});
|
|
||||||
this.notifyTaskDone();
|
|
||||||
throw new Error(`No speech-to-text service credentials for ${vendor} have been configured`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (vendor === 'nuance' && credentials.client_id) {
|
if (vendor === 'nuance' && credentials.client_id) {
|
||||||
@@ -182,21 +234,59 @@ class SttTask extends Task {
|
|||||||
const {access_token, servedFromCache} = await getIbmAccessToken(stt_api_key);
|
const {access_token, servedFromCache} = await getIbmAccessToken(stt_api_key);
|
||||||
this.logger.debug({stt_api_key}, `got ibm access token ${servedFromCache ? 'from cache' : ''}`);
|
this.logger.debug({stt_api_key}, `got ibm access token ${servedFromCache ? 'from cache' : ''}`);
|
||||||
credentials = {...credentials, access_token, stt_region};
|
credentials = {...credentials, access_token, stt_region};
|
||||||
|
} else if (['aws', 'polly'].includes(vendor) && credentials.roleArn) {
|
||||||
|
/* get aws access token */
|
||||||
|
const {roleArn, region} = credentials;
|
||||||
|
const {accessKeyId, secretAccessKey, sessionToken, servedFromCache} =
|
||||||
|
await getAwsAuthToken({
|
||||||
|
region,
|
||||||
|
roleArn
|
||||||
|
});
|
||||||
|
this.logger.debug({roleArn}, `(roleArn) got aws access token ${servedFromCache ? 'from cache' : ''}`);
|
||||||
|
// from role ARN, we will get SessionToken, but feature server use it as securityToken.
|
||||||
|
credentials = {...credentials, accessKeyId, secretAccessKey, securityToken: sessionToken};
|
||||||
}
|
}
|
||||||
|
else if (vendor === 'verbio' && credentials.client_id && credentials.client_secret) {
|
||||||
|
const {access_token, servedFromCache} = await getVerbioAccessToken(credentials);
|
||||||
|
this.logger.debug({client_id: credentials.client_id},
|
||||||
|
`got verbio access token ${servedFromCache ? 'from cache' : ''}`);
|
||||||
|
credentials.access_token = access_token;
|
||||||
|
}
|
||||||
|
else if (vendor == 'aws' && !JAMBONES_AWS_TRANSCRIBE_USE_GRPC) {
|
||||||
|
/* get AWS access token */
|
||||||
|
const {speech_credential_sid, accessKeyId, secretAccessKey, securityToken, region } = credentials;
|
||||||
|
if (!securityToken) {
|
||||||
|
const { servedFromCache, ...newCredentials} = await getAwsAuthToken({
|
||||||
|
speech_credential_sid,
|
||||||
|
accessKeyId,
|
||||||
|
secretAccessKey,
|
||||||
|
region});
|
||||||
|
this.logger.debug({newCredentials}, `got aws security token ${servedFromCache ? 'from cache' : ''}`);
|
||||||
|
credentials = {...newCredentials, region};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return credentials;
|
return credentials;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _fallback() {
|
get canFallback() {
|
||||||
|
return this.fallbackVendor && this.isHandledByPrimaryProvider && !this.cs.hasFallbackAsr;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _initFallback() {
|
||||||
assert(this.fallbackVendor, 'fallback failed without fallbackVendor configuration');
|
assert(this.fallbackVendor, 'fallback failed without fallbackVendor configuration');
|
||||||
this.isHandledByPrimaryProvider = false;
|
|
||||||
this.logger.info(`Failed to use primary STT provider, fallback to ${this.fallbackVendor}`);
|
this.logger.info(`Failed to use primary STT provider, fallback to ${this.fallbackVendor}`);
|
||||||
this.vendor = this.fallbackVendor;
|
this.isHandledByPrimaryProvider = false;
|
||||||
this.language = this.fallbackLanguage;
|
this.cs.hasFallbackAsr = true;
|
||||||
this.label = this.fallbackLabel;
|
this.vendor = this.cs.fallbackSpeechRecognizerVendor = this.fallbackVendor;
|
||||||
|
this.language = this.cs.fallbackSpeechRecognizerLanguage = this.fallbackLanguage;
|
||||||
|
this.label = this.cs.fallbackSpeechRecognizerLabel = this.fallbackLabel;
|
||||||
this.data.recognizer.vendor = this.vendor;
|
this.data.recognizer.vendor = this.vendor;
|
||||||
this.data.recognizer.language = this.language;
|
this.data.recognizer.language = this.language;
|
||||||
this.data.recognizer.label = this.label;
|
this.data.recognizer.label = this.label;
|
||||||
this.sttCredentials = await this._initSpeechCredentials(this.cs, this.vendor, this.label);
|
this.sttCredentials = await this._initSpeechCredentials(this.cs, this.vendor, this.label);
|
||||||
|
// cleanup previous listener from previous vendor
|
||||||
|
this.removeCustomEventListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
async compileHintsForCobalt(ep, hostport, model, token, hints) {
|
async compileHintsForCobalt(ep, hostport, model, token, hints) {
|
||||||
@@ -224,6 +314,57 @@ class SttTask extends Task {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
formatOpenAIPrompt(cs, {prompt, hintsTemplate, conversationHistoryTemplate, hints}) {
|
||||||
|
let conversationHistoryPrompt, hintsPrompt;
|
||||||
|
|
||||||
|
/* generate conversation history from template */
|
||||||
|
if (conversationHistoryTemplate) {
|
||||||
|
const {processed, turns} = processTurnString(conversationHistoryTemplate);
|
||||||
|
this.logger.debug({processed, turns}, 'SttTask: processed conversation history template');
|
||||||
|
conversationHistoryPrompt = cs.getFormattedConversation(turns || 4);
|
||||||
|
//this.logger.debug({conversationHistoryPrompt}, 'SttTask: conversation history');
|
||||||
|
if (conversationHistoryPrompt) {
|
||||||
|
conversationHistoryPrompt = processed.replace('{{turns}}', `\n${conversationHistoryPrompt}\nuser: `);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* generate hints from template */
|
||||||
|
if (hintsTemplate && Array.isArray(hints) && hints.length > 0) {
|
||||||
|
hintsPrompt = hintsTemplate.replace('{{hints}}', hints);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* combine into final prompt */
|
||||||
|
let finalPrompt = prompt || '';
|
||||||
|
if (hintsPrompt) {
|
||||||
|
finalPrompt = `${finalPrompt}\n${hintsPrompt}`;
|
||||||
|
}
|
||||||
|
if (conversationHistoryPrompt) {
|
||||||
|
finalPrompt = `${finalPrompt}\n${conversationHistoryPrompt}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug({
|
||||||
|
finalPrompt,
|
||||||
|
hints,
|
||||||
|
hintsPrompt,
|
||||||
|
conversationHistoryTemplate,
|
||||||
|
conversationHistoryPrompt
|
||||||
|
}, 'SttTask: formatted OpenAI prompt');
|
||||||
|
return finalPrompt?.trimStart();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* some STT engines will keep listening after a final response, so no need to restart */
|
||||||
|
doesVendorContinueListeningAfterFinalTranscript(vendor) {
|
||||||
|
return (vendor.startsWith('custom:') || [
|
||||||
|
'soniox',
|
||||||
|
'aws',
|
||||||
|
'microsoft',
|
||||||
|
'deepgram',
|
||||||
|
'google',
|
||||||
|
'speechmatics',
|
||||||
|
'openai',
|
||||||
|
].includes(vendor));
|
||||||
|
}
|
||||||
|
|
||||||
_onCompileContext(ep, key, evt) {
|
_onCompileContext(ep, key, evt) {
|
||||||
const {addKey} = this.cs.srf.locals.dbHelpers;
|
const {addKey} = this.cs.srf.locals.dbHelpers;
|
||||||
this.logger.debug({evt}, `received cobalt compile context event, will cache under ${key}`);
|
this.logger.debug({evt}, `received cobalt compile context event, will cache under ${key}`);
|
||||||
@@ -240,6 +381,20 @@ class SttTask extends Task {
|
|||||||
_doContinuousAsrWithDeepgram(asrTimeout) {
|
_doContinuousAsrWithDeepgram(asrTimeout) {
|
||||||
/* deepgram has an utterance_end_ms property that simplifies things */
|
/* deepgram has an utterance_end_ms property that simplifies things */
|
||||||
assert(this.vendor === 'deepgram');
|
assert(this.vendor === 'deepgram');
|
||||||
|
if (asrTimeout < 1000) {
|
||||||
|
this.notifyError({
|
||||||
|
msg: 'ASR error',
|
||||||
|
details:`asrTimeout ${asrTimeout} is too short for deepgram; setting it to 1000ms`
|
||||||
|
});
|
||||||
|
asrTimeout = 1000;
|
||||||
|
}
|
||||||
|
else if (asrTimeout > 5000) {
|
||||||
|
this.notifyError({
|
||||||
|
msg: 'ASR error',
|
||||||
|
details:`asrTimeout ${asrTimeout} is too long for deepgram; setting it to 5000ms`
|
||||||
|
});
|
||||||
|
asrTimeout = 5000;
|
||||||
|
}
|
||||||
this.logger.debug(`_doContinuousAsrWithDeepgram - setting utterance_end_ms to ${asrTimeout}`);
|
this.logger.debug(`_doContinuousAsrWithDeepgram - setting utterance_end_ms to ${asrTimeout}`);
|
||||||
const dgOptions = this.data.recognizer.deepgramOptions = this.data.recognizer.deepgramOptions || {};
|
const dgOptions = this.data.recognizer.deepgramOptions = this.data.recognizer.deepgramOptions || {};
|
||||||
dgOptions.utteranceEndMs = dgOptions.utteranceEndMs || asrTimeout;
|
dgOptions.utteranceEndMs = dgOptions.utteranceEndMs || asrTimeout;
|
||||||
@@ -258,8 +413,8 @@ class SttTask extends Task {
|
|||||||
message: 'STT failure reported by vendor',
|
message: 'STT failure reported by vendor',
|
||||||
detail: evt.error,
|
detail: evt.error,
|
||||||
vendor: this.vendor,
|
vendor: this.vendor,
|
||||||
|
target_sid: cs.callSid
|
||||||
}).catch((err) => this.logger.info({err}, `Error generating alert for ${this.vendor} connection failure`));
|
}).catch((err) => this.logger.info({err}, `Error generating alert for ${this.vendor} connection failure`));
|
||||||
this.notifyError({msg: 'ASR error', details:`Failed connecting to speech vendor ${this.vendor}: ${evt.error}`});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_onVendorConnectFailure(cs, _ep, evt) {
|
_onVendorConnectFailure(cs, _ep, evt) {
|
||||||
@@ -271,8 +426,8 @@ class SttTask extends Task {
|
|||||||
alert_type: AlertType.STT_FAILURE,
|
alert_type: AlertType.STT_FAILURE,
|
||||||
message: `Failed connecting to ${this.vendor} speech recognizer: ${reason}`,
|
message: `Failed connecting to ${this.vendor} speech recognizer: ${reason}`,
|
||||||
vendor: this.vendor,
|
vendor: this.vendor,
|
||||||
|
target_sid: cs.callSid
|
||||||
}).catch((err) => this.logger.info({err}, `Error generating alert for ${this.vendor} connection failure`));
|
}).catch((err) => this.logger.info({err}, `Error generating alert for ${this.vendor} connection failure`));
|
||||||
this.notifyError({msg: 'ASR error', details:`Failed connecting to speech vendor ${this.vendor}: ${reason}`});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,10 @@ class Task extends Emitter {
|
|||||||
return this.name;
|
return this.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
set disableTracing(val) {
|
||||||
|
this._disableTracing = val;
|
||||||
|
}
|
||||||
|
|
||||||
toJSON() {
|
toJSON() {
|
||||||
return this.data;
|
return this.data;
|
||||||
}
|
}
|
||||||
@@ -177,15 +181,16 @@ class Task extends Emitter {
|
|||||||
// If actionHook delay action is configured, and ws application have not responded yet any verb for actionHook
|
// If actionHook delay action is configured, and ws application have not responded yet any verb for actionHook
|
||||||
// We have to transfer the task to call-session to await on next ws command verbs, and also run action Hook
|
// We have to transfer the task to call-session to await on next ws command verbs, and also run action Hook
|
||||||
// delay actions
|
// delay actions
|
||||||
if (this.hookDelayActionOpts) {
|
//if (this.hookDelayActionOpts) {
|
||||||
this.emit('ActionHookDelayActionOptions', this.hookDelayActionOpts);
|
// this.emit('ActionHookDelayActionOptions', this.hookDelayActionOpts);
|
||||||
}
|
//}
|
||||||
}
|
}
|
||||||
if (expectResponse && json && Array.isArray(json)) {
|
if (expectResponse && json && Array.isArray(json)) {
|
||||||
const makeTask = require('./make_task');
|
const makeTask = require('./make_task');
|
||||||
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
||||||
if (tasks && tasks.length > 0) {
|
if (tasks && tasks.length > 0) {
|
||||||
this.callSession.replaceApplication(tasks);
|
this.callSession.replaceApplication(tasks);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -193,6 +198,7 @@ class Task extends Emitter {
|
|||||||
span.end();
|
span.end();
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,6 +278,7 @@ class Task extends Emitter {
|
|||||||
delete obj.requestor;
|
delete obj.requestor;
|
||||||
delete obj.notifier;
|
delete obj.notifier;
|
||||||
obj.tasks = cs.getRemainingTaskData();
|
obj.tasks = cs.getRemainingTaskData();
|
||||||
|
obj.callInfo = cs.callInfo.toJSON();
|
||||||
if (opts && obj.tasks.length > 0) {
|
if (opts && obj.tasks.length > 0) {
|
||||||
const key = Object.keys(obj.tasks[0])[0];
|
const key = Object.keys(obj.tasks[0])[0];
|
||||||
Object.assign(obj.tasks[0][key], {_: opts});
|
Object.assign(obj.tasks[0][key], {_: opts});
|
||||||
|
|||||||
@@ -12,10 +12,15 @@ const {
|
|||||||
NvidiaTranscriptionEvents,
|
NvidiaTranscriptionEvents,
|
||||||
JambonzTranscriptionEvents,
|
JambonzTranscriptionEvents,
|
||||||
TranscribeStatus,
|
TranscribeStatus,
|
||||||
AssemblyAiTranscriptionEvents
|
AssemblyAiTranscriptionEvents,
|
||||||
|
VoxistTranscriptionEvents,
|
||||||
|
OpenAITranscriptionEvents,
|
||||||
|
VerbioTranscriptionEvents,
|
||||||
|
SpeechmaticsTranscriptionEvents
|
||||||
} = require('../utils/constants.json');
|
} = require('../utils/constants.json');
|
||||||
const { normalizeJambones } = require('@jambonz/verb-specifications');
|
const { normalizeJambones } = require('@jambonz/verb-specifications');
|
||||||
const SttTask = require('./stt-task');
|
const SttTask = require('./stt-task');
|
||||||
|
const { SpeechCredentialError } = require('../utils/error');
|
||||||
|
|
||||||
const STT_LISTEN_SPAN_NAME = 'stt-listen';
|
const STT_LISTEN_SPAN_NAME = 'stt-listen';
|
||||||
|
|
||||||
@@ -24,8 +29,8 @@ class TaskTranscribe extends SttTask {
|
|||||||
super(logger, opts, parentTask);
|
super(logger, opts, parentTask);
|
||||||
|
|
||||||
this.transcriptionHook = this.data.transcriptionHook;
|
this.transcriptionHook = this.data.transcriptionHook;
|
||||||
|
this.translationHook = this.data.translationHook;
|
||||||
this.earlyMedia = this.data.earlyMedia === true || (parentTask && parentTask.earlyMedia);
|
this.earlyMedia = this.data.earlyMedia === true || (parentTask && parentTask.earlyMedia);
|
||||||
|
|
||||||
if (this.data.recognizer) {
|
if (this.data.recognizer) {
|
||||||
this.interim = !!this.data.recognizer.interim;
|
this.interim = !!this.data.recognizer.interim;
|
||||||
this.separateRecognitionPerChannel = this.data.recognizer.separateRecognitionPerChannel;
|
this.separateRecognitionPerChannel = this.data.recognizer.separateRecognitionPerChannel;
|
||||||
@@ -58,7 +63,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
this.isContinuousAsr = true;
|
this.isContinuousAsr = true;
|
||||||
}
|
}
|
||||||
/* buffer speech for continuous asr */
|
/* buffer speech for continuous asr */
|
||||||
this._bufferedTranscripts = [];
|
this._bufferedTranscripts = [ [], [] ]; // for channel 1 and 2
|
||||||
this.bugname_prefix = 'transcribe_';
|
this.bugname_prefix = 'transcribe_';
|
||||||
this.paused = false;
|
this.paused = false;
|
||||||
}
|
}
|
||||||
@@ -73,7 +78,20 @@ class TaskTranscribe extends SttTask {
|
|||||||
return this.channel === 2 || this.separateRecognitionPerChannel && this.ep2;
|
return this.channel === 2 || this.separateRecognitionPerChannel && this.ep2;
|
||||||
}
|
}
|
||||||
|
|
||||||
async exec(cs, {ep, ep2}) {
|
async exec(cs, obj) {
|
||||||
|
try {
|
||||||
|
await this.handling(cs, obj);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof SpeechCredentialError) {
|
||||||
|
this.logger.info('Transcribe failed due to SpeechCredentialError, finished!');
|
||||||
|
this.notifyTaskDone();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handling(cs, {ep, ep2}) {
|
||||||
await super.exec(cs, {ep, ep2});
|
await super.exec(cs, {ep, ep2});
|
||||||
|
|
||||||
if (this.data.recognizer.vendor === 'nuance') {
|
if (this.data.recognizer.vendor === 'nuance') {
|
||||||
@@ -84,11 +102,10 @@ class TaskTranscribe extends SttTask {
|
|||||||
...this.data.recognizer.nuanceOptions
|
...this.data.recognizer.nuanceOptions
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const {updateSpeechCredentialLastUsed} = require('../utils/db-utils')(this.logger, cs.srf);
|
|
||||||
|
|
||||||
if (cs.hasGlobalSttHints) {
|
if (cs.hasGlobalSttHints) {
|
||||||
const {hints, hintsBoost} = cs.globalSttHints;
|
const {hints, hintsBoost} = cs.globalSttHints;
|
||||||
this.data.recognizer.hints = this.data.recognizer.hints.concat(hints);
|
this.data.recognizer.hints = this.data.recognizer?.hints?.concat(hints);
|
||||||
if (!this.data.recognizer.hintsBoost && hintsBoost) this.data.recognizer.hintsBoost = hintsBoost;
|
if (!this.data.recognizer.hintsBoost && hintsBoost) this.data.recognizer.hintsBoost = hintsBoost;
|
||||||
this.logger.debug({hints: this.data.recognizer.hints, hintsBoost: this.data.recognizer.hintsBoost},
|
this.logger.debug({hints: this.data.recognizer.hints, hintsBoost: this.data.recognizer.hintsBoost},
|
||||||
'Transcribe:exec - applying global sttHints');
|
'Transcribe:exec - applying global sttHints');
|
||||||
@@ -101,15 +118,15 @@ class TaskTranscribe extends SttTask {
|
|||||||
if (this.transcribing2) {
|
if (this.transcribing2) {
|
||||||
await this._startTranscribing(cs, ep2, 2);
|
await this._startTranscribing(cs, ep2, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateSpeechCredentialLastUsed(this.sttCredentials.speech_credential_sid)
|
|
||||||
.catch(() => {/*already logged error */});
|
|
||||||
|
|
||||||
await this.awaitTaskDone();
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info(err, 'TaskTranscribe:exec - error');
|
if (!(await this._startFallback(cs, ep, {error: err}))) {
|
||||||
this.parentTask && this.parentTask.emit('error', err);
|
this.logger.info(err, 'TaskTranscribe:exec - error');
|
||||||
|
this.parentTask && this.parentTask.emit('error', err);
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
await this.awaitTaskDone();
|
||||||
this.removeCustomEventListeners();
|
this.removeCustomEventListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +140,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
})
|
})
|
||||||
.catch((err) => this.logger.info(err, 'Error TaskTranscribe:kill'));
|
.catch((err) => this.logger.info(err, 'Error TaskTranscribe:kill'));
|
||||||
}
|
}
|
||||||
if (this.transcribing2 && this.ep2.connected) {
|
if (this.transcribing2 && this.ep2?.connected) {
|
||||||
stopTranscription = true;
|
stopTranscription = true;
|
||||||
this.ep2.stopTranscription({vendor: this.vendor, bugname: this.bugname})
|
this.ep2.stopTranscription({vendor: this.vendor, bugname: this.bugname})
|
||||||
.catch((err) => this.logger.info(err, 'Error TaskTranscribe:kill'));
|
.catch((err) => this.logger.info(err, 'Error TaskTranscribe:kill'));
|
||||||
@@ -194,8 +211,8 @@ class TaskTranscribe extends SttTask {
|
|||||||
this.bugname = `${this.bugname_prefix}azure_transcribe`;
|
this.bugname = `${this.bugname_prefix}azure_transcribe`;
|
||||||
this.addCustomEventListener(ep, AzureTranscriptionEvents.Transcription,
|
this.addCustomEventListener(ep, AzureTranscriptionEvents.Transcription,
|
||||||
this._onTranscription.bind(this, cs, ep, channel));
|
this._onTranscription.bind(this, cs, ep, channel));
|
||||||
this.addCustomEventListener(ep, AzureTranscriptionEvents.NoSpeechDetected,
|
//this.addCustomEventListener(ep, AzureTranscriptionEvents.NoSpeechDetected,
|
||||||
this._onNoAudio.bind(this, cs, ep, channel));
|
// this._onNoAudio.bind(this, cs, ep, channel));
|
||||||
break;
|
break;
|
||||||
case 'nuance':
|
case 'nuance':
|
||||||
this.bugname = `${this.bugname_prefix}nuance_transcribe`;
|
this.bugname = `${this.bugname_prefix}nuance_transcribe`;
|
||||||
@@ -212,7 +229,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
this._onVendorConnectFailure.bind(this, cs, ep, channel));
|
this._onVendorConnectFailure.bind(this, cs, ep, channel));
|
||||||
|
|
||||||
/* if app sets deepgramOptions.utteranceEndMs they essentially want continuous asr */
|
/* if app sets deepgramOptions.utteranceEndMs they essentially want continuous asr */
|
||||||
if (opts.DEEPGRAM_SPEECH_UTTERANCE_END_MS) this.isContinuousAsr = true;
|
//if (opts.DEEPGRAM_SPEECH_UTTERANCE_END_MS) this.isContinuousAsr = true;
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case 'soniox':
|
case 'soniox':
|
||||||
@@ -220,6 +237,13 @@ class TaskTranscribe extends SttTask {
|
|||||||
this.addCustomEventListener(ep, SonioxTranscriptionEvents.Transcription,
|
this.addCustomEventListener(ep, SonioxTranscriptionEvents.Transcription,
|
||||||
this._onTranscription.bind(this, cs, ep, channel));
|
this._onTranscription.bind(this, cs, ep, channel));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case 'verbio':
|
||||||
|
this.bugname = `${this.bugname_prefix}verbio_transcribe`;
|
||||||
|
this.addCustomEventListener(
|
||||||
|
ep, VerbioTranscriptionEvents.Transcription, this._onTranscription.bind(this, cs, ep));
|
||||||
|
break;
|
||||||
|
|
||||||
case 'cobalt':
|
case 'cobalt':
|
||||||
this.bugname = `${this.bugname_prefix}cobalt_transcribe`;
|
this.bugname = `${this.bugname_prefix}cobalt_transcribe`;
|
||||||
this.addCustomEventListener(ep, CobaltTranscriptionEvents.Transcription,
|
this.addCustomEventListener(ep, CobaltTranscriptionEvents.Transcription,
|
||||||
@@ -277,6 +301,49 @@ class TaskTranscribe extends SttTask {
|
|||||||
this._onVendorConnectFailure.bind(this, cs, ep, channel));
|
this._onVendorConnectFailure.bind(this, cs, ep, channel));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case 'voxist':
|
||||||
|
this.bugname = `${this.bugname_prefix}voxist_transcribe`;
|
||||||
|
this.addCustomEventListener(ep, VoxistTranscriptionEvents.Transcription,
|
||||||
|
this._onTranscription.bind(this, cs, ep, channel));
|
||||||
|
this.addCustomEventListener(ep,
|
||||||
|
VoxistTranscriptionEvents.Connect, this._onVendorConnect.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, VoxistTranscriptionEvents.Error, this._onVendorError.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, VoxistTranscriptionEvents.ConnectFailure,
|
||||||
|
this._onVendorConnectFailure.bind(this, cs, ep, channel));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'speechmatics':
|
||||||
|
this.bugname = `${this.bugname_prefix}speechmatics_transcribe`;
|
||||||
|
this.addCustomEventListener(
|
||||||
|
ep, SpeechmaticsTranscriptionEvents.Transcription, this._onTranscription.bind(this, cs, ep, channel));
|
||||||
|
this.addCustomEventListener(
|
||||||
|
ep, SpeechmaticsTranscriptionEvents.Translation, this._onTranslation.bind(this, cs, ep, channel));
|
||||||
|
this.addCustomEventListener(ep, SpeechmaticsTranscriptionEvents.Info,
|
||||||
|
this._onSpeechmaticsInfo.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, SpeechmaticsTranscriptionEvents.RecognitionStarted,
|
||||||
|
this._onSpeechmaticsRecognitionStarted.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, SpeechmaticsTranscriptionEvents.Connect,
|
||||||
|
this._onVendorConnect.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, SpeechmaticsTranscriptionEvents.ConnectFailure,
|
||||||
|
this._onVendorConnectFailure.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, SpeechmaticsTranscriptionEvents.Error,
|
||||||
|
this._onSpeechmaticsError.bind(this, cs, ep));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'openai':
|
||||||
|
this.bugname = `${this.bugname_prefix}openai_transcribe`;
|
||||||
|
this.addCustomEventListener(
|
||||||
|
ep, OpenAITranscriptionEvents.Transcription, this._onTranscription.bind(this, cs, ep, channel));
|
||||||
|
this.addCustomEventListener(ep, OpenAITranscriptionEvents.Connect,
|
||||||
|
this._onVendorConnect.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, OpenAITranscriptionEvents.ConnectFailure,
|
||||||
|
this._onVendorConnectFailure.bind(this, cs, ep));
|
||||||
|
this.addCustomEventListener(ep, OpenAITranscriptionEvents.Error,
|
||||||
|
this._onOpenAIErrror.bind(this, cs, ep));
|
||||||
|
|
||||||
|
this.modelSupportsConversationTracking = opts.OPENAI_MODEL !== 'whisper-1';
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
if (this.vendor.startsWith('custom:')) {
|
if (this.vendor.startsWith('custom:')) {
|
||||||
this.bugname = `${this.bugname_prefix}${this.vendor}_transcribe`;
|
this.bugname = `${this.bugname_prefix}${this.vendor}_transcribe`;
|
||||||
@@ -312,6 +379,25 @@ class TaskTranscribe extends SttTask {
|
|||||||
async _transcribe(ep) {
|
async _transcribe(ep) {
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
`TaskTranscribe:_transcribe - starting transcription vendor ${this.vendor} bugname ${this.bugname}`);
|
`TaskTranscribe:_transcribe - starting transcription vendor ${this.vendor} bugname ${this.bugname}`);
|
||||||
|
|
||||||
|
/* special feature for openai: we can provide a prompt that includes recent conversation history */
|
||||||
|
let prompt;
|
||||||
|
if (this.vendor === 'openai') {
|
||||||
|
if (this.modelSupportsConversationTracking) {
|
||||||
|
prompt = this.formatOpenAIPrompt(this.cs, {
|
||||||
|
prompt: this.data.recognizer?.openaiOptions?.prompt,
|
||||||
|
hintsTemplate: this.data.recognizer?.openaiOptions?.promptTemplates?.hintsTemplate,
|
||||||
|
// eslint-disable-next-line max-len
|
||||||
|
conversationHistoryTemplate: this.data.recognizer?.openaiOptions?.promptTemplates?.conversationHistoryTemplate,
|
||||||
|
hints: this.data.recognizer?.hints,
|
||||||
|
});
|
||||||
|
this.logger.debug({prompt}, 'Gather:_startTranscribing - created an openai prompt');
|
||||||
|
}
|
||||||
|
else if (this.data.recognizer?.hints?.length > 0) {
|
||||||
|
prompt = this.data.recognizer?.hints.join(', ');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await ep.startTranscription({
|
await ep.startTranscription({
|
||||||
vendor: this.vendor,
|
vendor: this.vendor,
|
||||||
interim: this.interim ? true : false,
|
interim: this.interim ? true : false,
|
||||||
@@ -326,6 +412,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
// make sure this is not a transcript from answering machine detection
|
// make sure this is not a transcript from answering machine detection
|
||||||
const bugname = fsEvent.getHeader('media-bugname');
|
const bugname = fsEvent.getHeader('media-bugname');
|
||||||
const finished = fsEvent.getHeader('transcription-session-finished');
|
const finished = fsEvent.getHeader('transcription-session-finished');
|
||||||
|
const bufferedTranscripts = this._bufferedTranscripts[channel - 1];
|
||||||
if (bugname && this.bugname !== bugname) return;
|
if (bugname && this.bugname !== bugname) return;
|
||||||
if (this.paused) {
|
if (this.paused) {
|
||||||
this.logger.debug({evt}, 'TaskTranscribe:_onTranscription - paused, ignoring transcript');
|
this.logger.debug({evt}, 'TaskTranscribe:_onTranscription - paused, ignoring transcript');
|
||||||
@@ -335,14 +422,20 @@ class TaskTranscribe extends SttTask {
|
|||||||
|
|
||||||
if (this.vendor === 'deepgram' && evt.type === 'UtteranceEnd') {
|
if (this.vendor === 'deepgram' && evt.type === 'UtteranceEnd') {
|
||||||
/* we will only get this when we have set utterance_end_ms */
|
/* we will only get this when we have set utterance_end_ms */
|
||||||
if (this._bufferedTranscripts.length === 0) {
|
|
||||||
|
/* DH: send a speech event when we get UtteranceEnd if they want interim events */
|
||||||
|
if (this.interim) {
|
||||||
|
this.logger.debug('Gather:_onTranscription - got UtteranceEnd event from deepgram, sending speech event');
|
||||||
|
this._resolve(channel, evt);
|
||||||
|
}
|
||||||
|
if (bufferedTranscripts.length === 0) {
|
||||||
this.logger.debug('Gather:_onTranscription - got UtteranceEnd event from deepgram but no buffered transcripts');
|
this.logger.debug('Gather:_onTranscription - got UtteranceEnd event from deepgram but no buffered transcripts');
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.logger.debug('Gather:_onTranscription - got UtteranceEnd event from deepgram, return buffered transcript');
|
this.logger.debug('Gather:_onTranscription - got UtteranceEnd event from deepgram, return buffered transcript');
|
||||||
evt = this.consolidateTranscripts(this._bufferedTranscripts, 1, this.language, this.vendor);
|
evt = this.consolidateTranscripts(bufferedTranscripts, channel, this.language, this.vendor);
|
||||||
evt.is_final = true;
|
evt.is_final = true;
|
||||||
this._bufferedTranscripts = [];
|
this._bufferedTranscripts[channel - 1] = [];
|
||||||
this._resolve(channel, evt);
|
this._resolve(channel, evt);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -359,11 +452,11 @@ class TaskTranscribe extends SttTask {
|
|||||||
|
|
||||||
let emptyTranscript = false;
|
let emptyTranscript = false;
|
||||||
if (evt.is_final) {
|
if (evt.is_final) {
|
||||||
if (evt.alternatives[0].transcript === '' && !cs.callGone && !this.killed) {
|
if (evt.alternatives.length === 0 || evt.alternatives[0].transcript === '' && !cs.callGone && !this.killed) {
|
||||||
emptyTranscript = true;
|
emptyTranscript = true;
|
||||||
if (finished === 'true' &&
|
if (finished === 'true' &&
|
||||||
['microsoft', 'deepgram'].includes(this.vendor) &&
|
['microsoft', 'deepgram'].includes(this.vendor) &&
|
||||||
this._bufferedTranscripts.length === 0) {
|
bufferedTranscripts.length === 0) {
|
||||||
this.logger.debug({evt}, 'TaskGather:_onTranscription - got empty transcript from old gather, disregarding');
|
this.logger.debug({evt}, 'TaskGather:_onTranscription - got empty transcript from old gather, disregarding');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -376,7 +469,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
'TaskGather:_onTranscription - got empty deepgram transcript during continous asr, continue listening');
|
'TaskGather:_onTranscription - got empty deepgram transcript during continous asr, continue listening');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
else if (this.vendor === 'deepgram' && this._bufferedTranscripts.length > 0) {
|
else if (this.vendor === 'deepgram' && bufferedTranscripts.length > 0) {
|
||||||
this.logger.info({evt},
|
this.logger.info({evt},
|
||||||
'TaskGather:_onTranscription - got empty transcript from deepgram, return the buffered transcripts');
|
'TaskGather:_onTranscription - got empty transcript from deepgram, return the buffered transcripts');
|
||||||
}
|
}
|
||||||
@@ -392,11 +485,13 @@ class TaskTranscribe extends SttTask {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.logger.info({evt}, 'TaskGather:_onTranscription - got transcript during continous asr');
|
this.logger.info({evt}, 'TaskGather:_onTranscription - got transcript during continous asr');
|
||||||
this._bufferedTranscripts.push(evt);
|
bufferedTranscripts.push(evt);
|
||||||
this._startAsrTimer(channel);
|
this._startAsrTimer(channel);
|
||||||
|
|
||||||
/* some STT engines will keep listening after a final response, so no need to restart */
|
/* some STT engines will keep listening after a final response, so no need to restart */
|
||||||
if (!['soniox', 'aws', 'microsoft', 'deepgram'].includes(this.vendor)) this._startTranscribing(cs, ep, channel);
|
if (!this.doesVendorContinueListeningAfterFinalTranscript(this.vendor)) {
|
||||||
|
this._startTranscribing(cs, ep, channel);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (this.vendor === 'soniox') {
|
if (this.vendor === 'soniox') {
|
||||||
@@ -407,19 +502,22 @@ class TaskTranscribe extends SttTask {
|
|||||||
}
|
}
|
||||||
else if (this.vendor === 'deepgram') {
|
else if (this.vendor === 'deepgram') {
|
||||||
/* compile transcripts into one */
|
/* compile transcripts into one */
|
||||||
if (!emptyTranscript) this._bufferedTranscripts.push(evt);
|
if (!emptyTranscript) bufferedTranscripts.push(evt);
|
||||||
|
|
||||||
/* deepgram can send an empty and final transcript; only if we have any buffered should we resolve */
|
/* deepgram can send an empty and final transcript; only if we have any buffered should we resolve */
|
||||||
if (this._bufferedTranscripts.length === 0) return;
|
if (bufferedTranscripts.length === 0) return;
|
||||||
evt = this.consolidateTranscripts(this._bufferedTranscripts, channel, this.language);
|
evt = this.consolidateTranscripts(bufferedTranscripts, channel, this.language);
|
||||||
this._bufferedTranscripts = [];
|
this._bufferedTranscripts[channel - 1] = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/* here is where we return a final transcript */
|
/* here is where we return a final transcript */
|
||||||
this.logger.debug({evt}, 'TaskTranscribe:_onTranscription - sending final transcript');
|
this.logger.debug({evt}, 'TaskTranscribe:_onTranscription - sending final transcript');
|
||||||
this._resolve(channel, evt);
|
this._resolve(channel, evt);
|
||||||
/* some STT engines will keep listening after a final response, so no need to restart */
|
|
||||||
if (!['soniox', 'aws', 'microsoft', 'deepgram'].includes(this.vendor)) this._startTranscribing(cs, ep, channel);
|
if (!this.doesVendorContinueListeningAfterFinalTranscript(this.vendor)) {
|
||||||
|
this.logger.debug('TaskTranscribe:_onTranscription - restarting transcribe');
|
||||||
|
this._startTranscribing(cs, ep, channel);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -430,7 +528,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
const originalEvent = evt.vendor.evt;
|
const originalEvent = evt.vendor.evt;
|
||||||
if (originalEvent.is_final && evt.alternatives[0].transcript !== '') {
|
if (originalEvent.is_final && evt.alternatives[0].transcript !== '') {
|
||||||
this.logger.debug({evt}, 'Gather:_onTranscription - buffering a completed (partial) deepgram transcript');
|
this.logger.debug({evt}, 'Gather:_onTranscription - buffering a completed (partial) deepgram transcript');
|
||||||
this._bufferedTranscripts.push(evt);
|
bufferedTranscripts.push(evt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,27 +539,74 @@ class TaskTranscribe extends SttTask {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async _onTranslation(_cs, _ep, channel, evt, _fsEvent) {
|
||||||
|
this.logger.debug({evt}, 'TaskTranscribe:_onTranslation');
|
||||||
|
if (this.translationHook && evt.results?.length > 0) {
|
||||||
|
try {
|
||||||
|
const b3 = this.getTracingPropagation();
|
||||||
|
const httpHeaders = b3 && {b3};
|
||||||
|
const payload = {
|
||||||
|
...this.cs.callInfo,
|
||||||
|
...httpHeaders,
|
||||||
|
translation: {
|
||||||
|
channel,
|
||||||
|
language: evt.language,
|
||||||
|
translation: evt.results[0].content
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
this.logger.debug({payload}, 'sending translationHook');
|
||||||
|
const json = await this.cs.requestor.request('verb:hook', this.translationHook, payload);
|
||||||
|
this.logger.info({json}, 'completed translationHook');
|
||||||
|
if (json && Array.isArray(json) && !this.parentTask) {
|
||||||
|
const makeTask = require('./make_task');
|
||||||
|
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
||||||
|
if (tasks && tasks.length > 0) {
|
||||||
|
this.logger.info({tasks: tasks}, `${this.name} replacing application with ${tasks.length} tasks`);
|
||||||
|
this.cs.replaceApplication(tasks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, 'TranscribeTask:_onTranslation error');
|
||||||
|
}
|
||||||
|
if (this.parentTask) {
|
||||||
|
this.parentTask.emit('translation', evt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.killed) {
|
||||||
|
this.logger.debug('TaskTranscribe:_onTranslation exiting after receiving final transcription');
|
||||||
|
this._clearTimer();
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async _resolve(channel, evt) {
|
async _resolve(channel, evt) {
|
||||||
/* we've got a transcript, so end the otel child span for this channel */
|
if (evt.is_final) {
|
||||||
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
/* we've got a final transcript, so end the otel child span for this channel */
|
||||||
this.childSpan[channel - 1].span.setAttributes({
|
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
||||||
channel,
|
this.childSpan[channel - 1].span.setAttributes({
|
||||||
'stt.resolve': 'transcript',
|
channel,
|
||||||
'stt.result': JSON.stringify(evt)
|
'stt.label': this.label || 'None',
|
||||||
});
|
'stt.resolve': 'transcript',
|
||||||
this.childSpan[channel - 1].span.end();
|
'stt.result': JSON.stringify(evt)
|
||||||
|
});
|
||||||
|
this.childSpan[channel - 1].span.end();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.transcriptionHook) {
|
if (this.transcriptionHook) {
|
||||||
const b3 = this.getTracingPropagation();
|
const b3 = this.getTracingPropagation();
|
||||||
const httpHeaders = b3 && {b3};
|
const httpHeaders = b3 && {b3};
|
||||||
|
const payload = {
|
||||||
|
...this.cs.callInfo,
|
||||||
|
...httpHeaders,
|
||||||
|
...(evt.alternatives && {speech: evt}),
|
||||||
|
...(evt.type && {speechEvent: evt})
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
const json = await this.cs.requestor.request('verb:hook', this.transcriptionHook, {
|
this.logger.debug({payload}, 'sending transcriptionHook');
|
||||||
...this.cs.callInfo,
|
const json = await this.cs.requestor.request('verb:hook', this.transcriptionHook, payload);
|
||||||
...httpHeaders,
|
this.logger.info({json}, 'completed transcriptionHook');
|
||||||
speech: evt
|
|
||||||
});
|
|
||||||
this.logger.info({json}, 'sent transcriptionHook');
|
|
||||||
if (json && Array.isArray(json) && !this.parentTask) {
|
if (json && Array.isArray(json) && !this.parentTask) {
|
||||||
const makeTask = require('./make_task');
|
const makeTask = require('./make_task');
|
||||||
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
||||||
@@ -482,7 +627,7 @@ class TaskTranscribe extends SttTask {
|
|||||||
this._clearTimer();
|
this._clearTimer();
|
||||||
this.notifyTaskDone();
|
this.notifyTaskDone();
|
||||||
}
|
}
|
||||||
else {
|
else if (evt.is_final) {
|
||||||
/* start another child span for this channel */
|
/* start another child span for this channel */
|
||||||
const {span, ctx} = this.startChildSpan(`${STT_LISTEN_SPAN_NAME}:${channel}`);
|
const {span, ctx} = this.startChildSpan(`${STT_LISTEN_SPAN_NAME}:${channel}`);
|
||||||
this.childSpan[channel - 1] = {span, ctx};
|
this.childSpan[channel - 1] = {span, ctx};
|
||||||
@@ -495,7 +640,8 @@ class TaskTranscribe extends SttTask {
|
|||||||
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
||||||
this.childSpan[channel - 1].span.setAttributes({
|
this.childSpan[channel - 1].span.setAttributes({
|
||||||
channel,
|
channel,
|
||||||
'stt.resolve': 'timeout'
|
'stt.resolve': 'timeout',
|
||||||
|
'stt.label': this.label || 'None',
|
||||||
});
|
});
|
||||||
this.childSpan[channel - 1].span.end();
|
this.childSpan[channel - 1].span.end();
|
||||||
}
|
}
|
||||||
@@ -512,7 +658,8 @@ class TaskTranscribe extends SttTask {
|
|||||||
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
||||||
this.childSpan[channel - 1].span.setAttributes({
|
this.childSpan[channel - 1].span.setAttributes({
|
||||||
channel,
|
channel,
|
||||||
'stt.resolve': 'max duration exceeded'
|
'stt.resolve': 'max duration exceeded',
|
||||||
|
'stt.label': this.label || 'None',
|
||||||
});
|
});
|
||||||
this.childSpan[channel - 1].span.end();
|
this.childSpan[channel - 1].span.end();
|
||||||
}
|
}
|
||||||
@@ -531,58 +678,97 @@ class TaskTranscribe extends SttTask {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async _onJambonzError(cs, _ep, evt) {
|
async _startFallback(cs, _ep, evt) {
|
||||||
this.logger.info({evt}, 'TaskTranscribe:_onJambonzError');
|
if (this.canFallback) {
|
||||||
if (this.paused) return;
|
|
||||||
if (this.isHandledByPrimaryProvider && this.fallbackVendor) {
|
|
||||||
_ep.stopTranscription({
|
_ep.stopTranscription({
|
||||||
vendor: this.vendor,
|
vendor: this.vendor,
|
||||||
bugname: this.bugname
|
bugname: this.bugname
|
||||||
})
|
})
|
||||||
.catch((err) => this.logger.error({err}, `Error stopping transcription for primary vendor ${this.vendor}`));
|
.catch((err) => this.logger.error({err}, `Error stopping transcription for primary vendor ${this.vendor}`));
|
||||||
const {updateSpeechCredentialLastUsed} = require('../utils/db-utils')(this.logger, cs.srf);
|
|
||||||
try {
|
try {
|
||||||
await this._fallback();
|
this.notifyError({ msg: 'ASR error',
|
||||||
|
details:`STT Vendor ${this.vendor} error: ${evt.error || evt.reason}`, failover: 'in progress'});
|
||||||
|
await this._initFallback();
|
||||||
let channel = 1;
|
let channel = 1;
|
||||||
if (this.ep !== _ep) {
|
if (this.ep !== _ep) {
|
||||||
channel = 2;
|
channel = 2;
|
||||||
}
|
}
|
||||||
|
this[`_speechHandlersSet_${channel}`] = false;
|
||||||
this._startTranscribing(cs, _ep, channel);
|
this._startTranscribing(cs, _ep, channel);
|
||||||
updateSpeechCredentialLastUsed(this.sttCredentials.speech_credential_sid);
|
return true;
|
||||||
return;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
this.notifyError({ msg: 'ASR error',
|
||||||
|
details:`STT Vendor ${this.vendor} error: ${evt.error || evt.reason}`, failover: 'not available'});
|
||||||
this.logger.info({error}, `There is error while falling back to ${this.fallbackVendor}`);
|
this.logger.info({error}, `There is error while falling back to ${this.fallbackVendor}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const {writeAlerts, AlertType} = cs.srf.locals;
|
this.logger.debug('transcribe:_startFallback no condition for falling back');
|
||||||
|
this.notifyError({ msg: 'ASR error',
|
||||||
|
details:`STT Vendor ${this.vendor} error: ${evt.error || evt.reason}`, failover: 'not available'});
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.vendor === 'nuance') {
|
async _onJambonzError(cs, _ep, evt) {
|
||||||
const {code, error} = evt;
|
if (this.vendor === 'google' && evt.error_code === 0) {
|
||||||
//TODO: fix below, currently _resolve does not send timeout events
|
this.logger.info({evt}, 'TaskTranscribe:_onJambonzError - ignoring google error code 0');
|
||||||
if (code === 404 && error === 'No speech') return this._resolve('timeout');
|
return;
|
||||||
if (code === 413 && error === 'Too much speech') return this._resolve('timeout');
|
}
|
||||||
}
|
this.logger.info({evt}, 'TaskTranscribe:_onJambonzError');
|
||||||
this.logger.info({evt}, 'TaskTranscribe:_onJambonzError');
|
if (this.paused) return;
|
||||||
writeAlerts({
|
const {writeAlerts, AlertType} = cs.srf.locals;
|
||||||
account_sid: cs.accountSid,
|
|
||||||
alert_type: AlertType.STT_FAILURE,
|
if (this.vendor === 'nuance') {
|
||||||
message: `Custom speech vendor ${this.vendor} error: ${evt.error}`,
|
const {code, error} = evt;
|
||||||
vendor: this.vendor,
|
if (code === 404 && error === 'No speech') return this._resolve('timeout');
|
||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for jambonz custom connection failure'));
|
if (code === 413 && error === 'Too much speech') return this._resolve('timeout');
|
||||||
this.notifyError({msg: 'ASR error', details:`Custom speech vendor ${this.vendor} error: ${evt.error}`});
|
}
|
||||||
|
this.logger.info({evt}, 'TaskTranscribe:_onJambonzError');
|
||||||
|
writeAlerts({
|
||||||
|
account_sid: cs.accountSid,
|
||||||
|
alert_type: AlertType.STT_FAILURE,
|
||||||
|
message: `Custom speech vendor ${this.vendor} error: ${evt.error}`,
|
||||||
|
vendor: this.vendor,
|
||||||
|
target_sid: cs.callSid
|
||||||
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for jambonz custom connection failure'));
|
||||||
|
if (!(await this._startFallback(cs, _ep, evt))) {
|
||||||
|
this.notifyTaskDone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_onVendorConnectFailure(cs, _ep, channel, evt) {
|
async _onVendorConnectFailure(cs, _ep, channel, evt) {
|
||||||
super._onVendorConnectFailure(cs, _ep, evt);
|
super._onVendorConnectFailure(cs, _ep, evt);
|
||||||
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
if (this.childSpan[channel - 1] && this.childSpan[channel - 1].span) {
|
||||||
this.childSpan[channel - 1].span.setAttributes({
|
this.childSpan[channel - 1].span.setAttributes({
|
||||||
channel,
|
channel,
|
||||||
'stt.resolve': 'connection failure'
|
'stt.resolve': 'connection failure',
|
||||||
|
'stt.label': this.label || 'None',
|
||||||
});
|
});
|
||||||
this.childSpan[channel - 1].span.end();
|
this.childSpan[channel - 1].span.end();
|
||||||
}
|
}
|
||||||
this.notifyTaskDone();
|
if (!(await this._startFallback(cs, _ep, evt))) {
|
||||||
|
this.notifyTaskDone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onSpeechmaticsRecognitionStarted(_cs, _ep, evt) {
|
||||||
|
this.logger.debug({evt}, 'TaskGather:_onSpeechmaticsRecognitionStarted');
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onSpeechmaticsInfo(_cs, _ep, evt) {
|
||||||
|
this.logger.debug({evt}, 'TaskGather:_onSpeechmaticsInfo');
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onSpeechmaticsError(cs, _ep, evt) {
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
const {message, ...e} = evt;
|
||||||
|
this._onVendorError(cs, _ep, {error: JSON.stringify(e)});
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onOpenAIErrror(cs, _ep, evt) {
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
const {message, ...e} = evt;
|
||||||
|
this._onVendorError(cs, _ep, {error: JSON.stringify(e)});
|
||||||
}
|
}
|
||||||
|
|
||||||
_startAsrTimer(channel) {
|
_startAsrTimer(channel) {
|
||||||
@@ -591,8 +777,9 @@ class TaskTranscribe extends SttTask {
|
|||||||
this._clearAsrTimer(channel);
|
this._clearAsrTimer(channel);
|
||||||
this._asrTimer = setTimeout(() => {
|
this._asrTimer = setTimeout(() => {
|
||||||
this.logger.debug(`TaskTranscribe:_startAsrTimer - asr timer went off for channel: ${channel}`);
|
this.logger.debug(`TaskTranscribe:_startAsrTimer - asr timer went off for channel: ${channel}`);
|
||||||
const evt = this.consolidateTranscripts(this._bufferedTranscripts, channel, this.language, this.vendor);
|
const evt = this.consolidateTranscripts(
|
||||||
this._bufferedTranscripts = [];
|
this._bufferedTranscripts[channel - 1], channel, this.language, this.vendor);
|
||||||
|
this._bufferedTranscripts[channel - 1] = [];
|
||||||
this._resolve(channel, evt);
|
this._resolve(channel, evt);
|
||||||
}, this.asrTimeout);
|
}, this.asrTimeout);
|
||||||
this.logger.debug(`TaskTranscribe:_startAsrTimer: set for ${this.asrTimeout}ms for channel ${channel}`);
|
this.logger.debug(`TaskTranscribe:_startAsrTimer: set for ${this.asrTimeout}ms for channel ${channel}`);
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
const Task = require('./task');
|
const Task = require('./task');
|
||||||
const { TaskPreconditions } = require('../utils/constants');
|
const { TaskPreconditions } = require('../utils/constants');
|
||||||
|
const { SpeechCredentialError } = require('../utils/error');
|
||||||
|
const dbUtils = require('../utils/db-utils');
|
||||||
|
|
||||||
class TtsTask extends Task {
|
class TtsTask extends Task {
|
||||||
|
|
||||||
@@ -10,6 +12,12 @@ class TtsTask extends Task {
|
|||||||
this.preconditions = TaskPreconditions.Endpoint;
|
this.preconditions = TaskPreconditions.Endpoint;
|
||||||
|
|
||||||
this.earlyMedia = this.data.earlyMedia === true || (parentTask && parentTask.earlyMedia);
|
this.earlyMedia = this.data.earlyMedia === true || (parentTask && parentTask.earlyMedia);
|
||||||
|
/**
|
||||||
|
* Task use taskIncludeSynthesizer to identify
|
||||||
|
* if taskIncludeSynthesizer === true, use label from verb.synthesizer, even it's empty
|
||||||
|
* if taskIncludeSynthesizer === false, use label from application.synthesizer
|
||||||
|
*/
|
||||||
|
this.taskIncludeSynthesizer = !!this.data.synthesizer;
|
||||||
this.synthesizer = this.data.synthesizer || {};
|
this.synthesizer = this.data.synthesizer || {};
|
||||||
this.disableTtsCache = this.data.disableTtsCache;
|
this.disableTtsCache = this.data.disableTtsCache;
|
||||||
this.options = this.synthesizer.options || {};
|
this.options = this.synthesizer.options || {};
|
||||||
@@ -17,34 +25,144 @@ class TtsTask extends Task {
|
|||||||
|
|
||||||
async exec(cs) {
|
async exec(cs) {
|
||||||
super.exec(cs);
|
super.exec(cs);
|
||||||
|
if (cs.synthesizer) {
|
||||||
|
this.options = {...cs.synthesizer.options, ...this.options};
|
||||||
|
this.data.synthesizer = this.data.synthesizer || {};
|
||||||
|
for (const k in cs.synthesizer) {
|
||||||
|
const newValue = this.data.synthesizer && this.data.synthesizer[k] !== undefined ?
|
||||||
|
this.data.synthesizer[k] :
|
||||||
|
cs.synthesizer[k];
|
||||||
|
|
||||||
|
if (Array.isArray(newValue)) {
|
||||||
|
this.data.synthesizer[k] = [...(this.data.synthesizer[k] || []), ...cs.synthesizer[k]];
|
||||||
|
} else if (typeof newValue === 'object' && newValue !== null) {
|
||||||
|
this.data.synthesizer[k] = { ...(this.data.synthesizer[k] || {}), ...cs.synthesizer[k] };
|
||||||
|
} else {
|
||||||
|
this.data.synthesizer[k] = newValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fullText = Array.isArray(this.text) ? this.text.join(' ') : this.text;
|
||||||
|
if (fullText.length > 0) {
|
||||||
|
cs.emit('botSaid', fullText);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async _synthesizeWithSpecificVendor(cs, ep, {
|
getTtsVendorData(cs) {
|
||||||
vendor,
|
const vendor = this.synthesizer.vendor && this.synthesizer.vendor !== 'default' ?
|
||||||
language,
|
this.synthesizer.vendor :
|
||||||
voice,
|
cs.speechSynthesisVendor;
|
||||||
label,
|
const language = this.synthesizer.language && this.synthesizer.language !== 'default' ?
|
||||||
disableTtsStreaming,
|
this.synthesizer.language :
|
||||||
preCache
|
cs.speechSynthesisLanguage ;
|
||||||
}) {
|
const voice = this.synthesizer.voice && this.synthesizer.voice !== 'default' ?
|
||||||
|
this.synthesizer.voice :
|
||||||
|
cs.speechSynthesisVoice;
|
||||||
|
const label = this.taskIncludeSynthesizer ? this.synthesizer.label : cs.speechSynthesisLabel;
|
||||||
|
return {vendor, language, voice, label};
|
||||||
|
}
|
||||||
|
|
||||||
|
async setTtsStreamingChannelVars(vendor, language, voice, credentials, ep) {
|
||||||
|
const {api_key, model_id, custom_tts_streaming_url, auth_token} = credentials;
|
||||||
|
let obj;
|
||||||
|
|
||||||
|
this.logger.debug({credentials},
|
||||||
|
`setTtsStreamingChannelVars: vendor: ${vendor}, language: ${language}, voice: ${voice}`);
|
||||||
|
|
||||||
|
switch (vendor) {
|
||||||
|
case 'deepgram':
|
||||||
|
obj = {
|
||||||
|
DEEPGRAM_API_KEY: api_key,
|
||||||
|
DEEPGRAM_TTS_STREAMING_MODEL: voice
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'cartesia':
|
||||||
|
obj = {
|
||||||
|
CARTESIA_API_KEY: api_key,
|
||||||
|
CARTESIA_TTS_STREAMING_MODEL_ID: model_id,
|
||||||
|
CARTESIA_TTS_STREAMING_VOICE_ID: voice,
|
||||||
|
CARTESIA_TTS_STREAMING_LANGUAGE: language || 'en',
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'elevenlabs':
|
||||||
|
const {stability, similarity_boost, use_speaker_boost, style, speed} = this.options.voice_settings || {};
|
||||||
|
obj = {
|
||||||
|
ELEVENLABS_API_KEY: api_key,
|
||||||
|
ELEVENLABS_TTS_STREAMING_MODEL_ID: model_id,
|
||||||
|
ELEVENLABS_TTS_STREAMING_VOICE_ID: voice,
|
||||||
|
// 20/12/2024 - only eleven_turbo_v2_5 support multiple language
|
||||||
|
...(['eleven_turbo_v2_5'].includes(model_id) && {ELEVENLABS_TTS_STREAMING_LANGUAGE: language}),
|
||||||
|
...(stability && {ELEVENLABS_TTS_STREAMING_VOICE_SETTINGS_STABILITY: stability}),
|
||||||
|
...(similarity_boost && {ELEVENLABS_TTS_STREAMING_VOICE_SETTINGS_SIMILARITY_BOOST: similarity_boost}),
|
||||||
|
...(use_speaker_boost && {ELEVENLABS_TTS_STREAMING_VOICE_SETTINGS_USE_SPEAKER_BOOST: use_speaker_boost}),
|
||||||
|
...(style && {ELEVENLABS_TTS_STREAMING_VOICE_SETTINGS_STYLE: style}),
|
||||||
|
// speed has value 0.7 to 1.2, 1.0 is default, make sure we send the value event it's 0
|
||||||
|
...(speed !== null && speed !== undefined && {ELEVENLABS_TTS_STREAMING_VOICE_SETTINGS_SPEED: `${speed}`}),
|
||||||
|
...(this.options.pronunciation_dictionary_locators &&
|
||||||
|
Array.isArray(this.options.pronunciation_dictionary_locators) && {
|
||||||
|
ELEVENLABS_TTS_STREAMING_PRONUNCIATION_DICTIONARY_LOCATORS:
|
||||||
|
JSON.stringify(this.options.pronunciation_dictionary_locators)
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'rimelabs':
|
||||||
|
const {
|
||||||
|
pauseBetweenBrackets, phonemizeBetweenBrackets, inlineSpeedAlpha, speedAlpha, reduceLatency
|
||||||
|
} = this.options;
|
||||||
|
obj = {
|
||||||
|
RIMELABS_API_KEY: api_key,
|
||||||
|
RIMELABS_TTS_STREAMING_MODEL_ID: model_id,
|
||||||
|
RIMELABS_TTS_STREAMING_VOICE_ID: voice,
|
||||||
|
RIMELABS_TTS_STREAMING_LANGUAGE: language || 'en',
|
||||||
|
...(pauseBetweenBrackets && {RIMELABS_TTS_STREAMING_PAUSE_BETWEEN_BRACKETS: pauseBetweenBrackets}),
|
||||||
|
...(phonemizeBetweenBrackets &&
|
||||||
|
{RIMELABS_TTS_STREAMING_PHONEMIZE_BETWEEN_BRACKETS: phonemizeBetweenBrackets}),
|
||||||
|
...(inlineSpeedAlpha && {RIMELABS_TTS_STREAMING_INLINE_SPEED_ALPHA: inlineSpeedAlpha}),
|
||||||
|
...(speedAlpha && {RIMELABS_TTS_STREAMING_SPEED_ALPHA: speedAlpha}),
|
||||||
|
...(reduceLatency && {RIMELABS_TTS_STREAMING_REDUCE_LATENCY: reduceLatency})
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (vendor.startsWith('custom:')) {
|
||||||
|
const use_tls = custom_tts_streaming_url.startsWith('wss://');
|
||||||
|
obj = {
|
||||||
|
CUSTOM_TTS_STREAMING_HOST: custom_tts_streaming_url.replace(/^(ws|wss):\/\//, ''),
|
||||||
|
CUSTOM_TTS_STREAMING_API_KEY: auth_token,
|
||||||
|
CUSTOM_TTS_STREAMING_VOICE_ID: voice,
|
||||||
|
CUSTOM_TTS_STREAMING_LANGUAGE: language || 'en',
|
||||||
|
CUSTOM_TTS_STREAMING_USE_TLS: use_tls
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
throw new Error(`vendor ${vendor} is not supported for tts streaming yet`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.logger.debug({vendor, credentials, obj}, 'setTtsStreamingChannelVars');
|
||||||
|
|
||||||
|
await ep.set(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
async _synthesizeWithSpecificVendor(cs, ep, {vendor, language, voice, label, preCache = false}) {
|
||||||
const {srf, accountSid:account_sid} = cs;
|
const {srf, accountSid:account_sid} = cs;
|
||||||
const {updateSpeechCredentialLastUsed} = require('../utils/db-utils')(this.logger, srf);
|
|
||||||
const {writeAlerts, AlertType, stats} = srf.locals;
|
const {writeAlerts, AlertType, stats} = srf.locals;
|
||||||
const {synthAudio} = srf.locals.dbHelpers;
|
const {synthAudio} = srf.locals.dbHelpers;
|
||||||
const engine = this.synthesizer.engine || 'standard';
|
const engine = this.synthesizer.engine || cs.synthesizer?.engine || 'neural';
|
||||||
const salt = cs.callSid;
|
const salt = cs.callSid;
|
||||||
|
|
||||||
let credentials = cs.getSpeechCredentials(vendor, 'tts', label);
|
let credentials = cs.getSpeechCredentials(vendor, 'tts', label);
|
||||||
|
if (!credentials) {
|
||||||
|
throw new SpeechCredentialError(
|
||||||
|
`No text-to-speech service credentials for ${vendor} with labels: ${label} have been configured`);
|
||||||
|
}
|
||||||
/* parse Nuance voices into name and model */
|
/* parse Nuance voices into name and model */
|
||||||
let model;
|
|
||||||
if (vendor === 'nuance' && voice) {
|
if (vendor === 'nuance' && voice) {
|
||||||
const arr = /([A-Za-z-]*)\s+-\s+(enhanced|standard)/.exec(voice);
|
const arr = /([A-Za-z-]*)\s+-\s+(enhanced|standard)/.exec(voice);
|
||||||
if (arr) {
|
if (arr) {
|
||||||
voice = arr[1];
|
voice = arr[1];
|
||||||
model = arr[2];
|
this.model = arr[2];
|
||||||
}
|
}
|
||||||
} else if (vendor === 'deepgram') {
|
} else if (vendor === 'deepgram') {
|
||||||
model = voice;
|
this.model = voice;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* allow for microsoft custom region voice and api_key to be specified as an override */
|
/* allow for microsoft custom region voice and api_key to be specified as an override */
|
||||||
@@ -62,30 +180,68 @@ class TtsTask extends Task {
|
|||||||
credentials.optimize_streaming_latency = this.options.optimize_streaming_latency
|
credentials.optimize_streaming_latency = this.options.optimize_streaming_latency
|
||||||
|| credentials.optimize_streaming_latency;
|
|| credentials.optimize_streaming_latency;
|
||||||
voice = this.options.voice_id || voice;
|
voice = this.options.voice_id || voice;
|
||||||
|
} else if (vendor === 'rimelabs') {
|
||||||
|
credentials = credentials || {};
|
||||||
|
credentials.model_id = this.options.model_id || credentials.model_id;
|
||||||
|
} else if (vendor === 'whisper') {
|
||||||
|
credentials = credentials || {};
|
||||||
|
credentials.model_id = this.options.model_id || credentials.model_id;
|
||||||
|
} else if (vendor === 'verbio') {
|
||||||
|
credentials = credentials || {};
|
||||||
|
credentials.engine_version = this.options.engine_version || credentials.engine_version;
|
||||||
|
} else if (vendor === 'playht') {
|
||||||
|
credentials = credentials || {};
|
||||||
|
credentials.voice_engine = this.options.voice_engine || credentials.voice_engine;
|
||||||
|
} else if (vendor === 'google' && typeof voice === 'string' && voice.startsWith('custom_')) {
|
||||||
|
const {lookupGoogleCustomVoice} = dbUtils(this.logger, cs.srf);
|
||||||
|
const arr = /custom_(.*)/.exec(voice);
|
||||||
|
if (arr) {
|
||||||
|
const google_custom_voice_sid = arr[1];
|
||||||
|
const [custom_voice] = await lookupGoogleCustomVoice(google_custom_voice_sid);
|
||||||
|
if (custom_voice.use_voice_cloning_key) {
|
||||||
|
voice = {
|
||||||
|
voice_cloning_key: custom_voice.voice_cloning_key,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (vendor === 'cartesia') {
|
||||||
|
credentials.model_id = this.options.model_id || credentials.model_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
ep.set({
|
this.model_id = credentials.model_id;
|
||||||
tts_engine: vendor,
|
|
||||||
tts_voice: voice,
|
|
||||||
cache_speech_handles: 1,
|
|
||||||
}).catch((err) => this.logger.info({err}, `${this.name}: Error setting tts_engine on endpoint`));
|
|
||||||
|
|
||||||
if (!preCache) this.logger.info({vendor, language, voice, model}, `${this.name}:exec`);
|
/**
|
||||||
|
* note on cache_speech_handles. This was found to be risky.
|
||||||
|
* It can cause a crash in the following sequence on a single call:
|
||||||
|
* 1. Stream tts on vendor A with cache_speech_handles=1, then
|
||||||
|
* 2. Stream tts on vendor B with cache_speech_handles=1
|
||||||
|
*
|
||||||
|
* we previously tried to track when vendors were switched and manage the flag accordingly,
|
||||||
|
* but it difficult to track all the scenarios and the benefit (slightly faster start to tts playout)
|
||||||
|
* is probably minimal. DH.
|
||||||
|
*/
|
||||||
|
ep.set({
|
||||||
|
tts_engine: vendor.startsWith('custom:') ? 'custom' : vendor,
|
||||||
|
tts_voice: voice,
|
||||||
|
//cache_speech_handles: !cs.currentTtsVendor || cs.currentTtsVendor === vendor ? 1 : 0,
|
||||||
|
cache_speech_handles: 0,
|
||||||
|
}).catch((err) => this.logger.info({err}, 'Error setting tts_engine on endpoint'));
|
||||||
|
// set the current vendor on the call session
|
||||||
|
// If vendor is changed from the previous one, then reset the cache_speech_handles flag
|
||||||
|
//cs.currentTtsVendor = vendor;
|
||||||
|
|
||||||
|
if (!preCache && !this._disableTracing)
|
||||||
|
this.logger.debug({vendor, language, voice, model: this.model}, 'TaskSay:exec');
|
||||||
try {
|
try {
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
writeAlerts({
|
writeAlerts({
|
||||||
account_sid,
|
account_sid,
|
||||||
alert_type: AlertType.TTS_NOT_PROVISIONED,
|
alert_type: AlertType.TTS_NOT_PROVISIONED,
|
||||||
vendor
|
vendor,
|
||||||
|
target_sid: cs.callSid
|
||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for no tts'));
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for no tts'));
|
||||||
this.notifyError({
|
throw new SpeechCredentialError('no provisioned speech credentials for TTS');
|
||||||
msg: 'TTS error',
|
|
||||||
details:`No speech credentials provisioned for selected vendor ${vendor}`
|
|
||||||
});
|
|
||||||
throw new Error('no provisioned speech credentials for TTS');
|
|
||||||
}
|
}
|
||||||
// synthesize all of the text elements
|
|
||||||
let lastUpdated = false;
|
|
||||||
|
|
||||||
/* produce an audio segment from the provided text */
|
/* produce an audio segment from the provided text */
|
||||||
const generateAudio = async(text) => {
|
const generateAudio = async(text) => {
|
||||||
@@ -93,11 +249,12 @@ class TtsTask extends Task {
|
|||||||
if (text.startsWith('silence_stream://')) return text;
|
if (text.startsWith('silence_stream://')) return text;
|
||||||
|
|
||||||
/* otel: trace time for tts */
|
/* otel: trace time for tts */
|
||||||
if (!preCache && !this.parentTask) {
|
if (!preCache && !this._disableTracing) {
|
||||||
const {span} = this.startChildSpan('tts-generation', {
|
const {span} = this.startChildSpan('tts-generation', {
|
||||||
'tts.vendor': vendor,
|
'tts.vendor': vendor,
|
||||||
'tts.language': language,
|
'tts.language': language,
|
||||||
'tts.voice': voice
|
'tts.voice': voice,
|
||||||
|
'tts.label': label || 'None',
|
||||||
});
|
});
|
||||||
this.otelSpan = span;
|
this.otelSpan = span;
|
||||||
}
|
}
|
||||||
@@ -109,27 +266,22 @@ class TtsTask extends Task {
|
|||||||
language,
|
language,
|
||||||
voice,
|
voice,
|
||||||
engine,
|
engine,
|
||||||
model,
|
model: this.model,
|
||||||
salt,
|
salt,
|
||||||
credentials,
|
credentials,
|
||||||
options: this.options,
|
options: this.options,
|
||||||
disableTtsCache : this.disableTtsCache,
|
disableTtsCache : this.disableTtsCache,
|
||||||
disableTtsStreaming,
|
renderForCaching: preCache
|
||||||
preCache
|
|
||||||
});
|
});
|
||||||
if (!filePath.startsWith('say:')) {
|
if (!filePath.startsWith('say:')) {
|
||||||
this.logger.debug(`file ${filePath}, served from cache ${servedFromCache}`);
|
this.logger.debug(`Say: file ${filePath}, served from cache ${servedFromCache}`);
|
||||||
if (filePath) cs.trackTmpFile(filePath);
|
if (filePath) cs.trackTmpFile(filePath);
|
||||||
if (this.otelSpan) {
|
if (this.otelSpan) {
|
||||||
this.otelSpan.setAttributes({'tts.cached': servedFromCache});
|
this.otelSpan.setAttributes({'tts.cached': servedFromCache});
|
||||||
this.otelSpan.end();
|
this.otelSpan.end();
|
||||||
this.otelSpan = null;
|
this.otelSpan = null;
|
||||||
}
|
}
|
||||||
if (!servedFromCache && !lastUpdated) {
|
if (!servedFromCache && rtt && !preCache && !this._disableTracing) {
|
||||||
lastUpdated = true;
|
|
||||||
updateSpeechCredentialLastUsed(credentials.speech_credential_sid).catch(() => {/* logged error */});
|
|
||||||
}
|
|
||||||
if (!servedFromCache && rtt && !preCache) {
|
|
||||||
this.notifyStatus({
|
this.notifyStatus({
|
||||||
event: 'synthesized-audio',
|
event: 'synthesized-audio',
|
||||||
vendor,
|
vendor,
|
||||||
@@ -140,7 +292,7 @@ class TtsTask extends Task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.logger.debug('a streaming tts api will be used');
|
this.logger.debug('Say: a streaming tts api will be used');
|
||||||
const modifiedPath = filePath.replace('say:{', `say:{session-uuid=${ep.uuid},`);
|
const modifiedPath = filePath.replace('say:{', `say:{session-uuid=${ep.uuid},`);
|
||||||
return modifiedPath;
|
return modifiedPath;
|
||||||
}
|
}
|
||||||
@@ -152,9 +304,9 @@ class TtsTask extends Task {
|
|||||||
account_sid: cs.accountSid,
|
account_sid: cs.accountSid,
|
||||||
alert_type: AlertType.TTS_FAILURE,
|
alert_type: AlertType.TTS_FAILURE,
|
||||||
vendor,
|
vendor,
|
||||||
detail: err.message
|
detail: err.message,
|
||||||
|
target_sid: cs.callSid
|
||||||
}).catch((err) => this.logger.info({err}, 'Error generating alert for tts failure'));
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for tts failure'));
|
||||||
this.notifyError({msg: 'TTS error', details: err.message || err});
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -165,6 +317,7 @@ class TtsTask extends Task {
|
|||||||
this.logger.info(err, 'TaskSay:exec error');
|
this.logger.info(err, 'TaskSay:exec error');
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_validateURL(urlString) {
|
_validateURL(urlString) {
|
||||||
|
|||||||
187
lib/utils/action-hook-delay.js
Normal file
187
lib/utils/action-hook-delay.js
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
const makeTask = require('../tasks/make_task');
|
||||||
|
const Emitter = require('events');
|
||||||
|
const { normalizeJambones } = require('@jambonz/verb-specifications');
|
||||||
|
const {TaskName} = require('../utils/constants');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionHookDelayProcessor
|
||||||
|
* @extends Emitter
|
||||||
|
*
|
||||||
|
* @param {Object} logger - logger instance
|
||||||
|
* @param {Object} opts - options
|
||||||
|
* @param {Object} cs - call session
|
||||||
|
* @param {Object} ep - endpoint
|
||||||
|
*
|
||||||
|
* @emits {Event} 'giveup' - when associated giveup timer expires
|
||||||
|
*
|
||||||
|
* Ref:https://www.jambonz.org/docs/supporting-articles/handling-action-hook-delays/
|
||||||
|
*/
|
||||||
|
class ActionHookDelayProcessor extends Emitter {
|
||||||
|
constructor(logger, opts, cs) {
|
||||||
|
super();
|
||||||
|
this.logger = logger;
|
||||||
|
this.cs = cs;
|
||||||
|
this._active = false;
|
||||||
|
|
||||||
|
const enabled = this.init(opts);
|
||||||
|
if (enabled && this.noResponseTimeout &&
|
||||||
|
(!this.actions || !Array.isArray(this.actions) || this.actions.length === 0)) {
|
||||||
|
throw new Error('ActionHookDelayProcessor: no actions specified');
|
||||||
|
}
|
||||||
|
else if (enabled && this.actions &&
|
||||||
|
this.actions.some((a) => !a.verb || ![TaskName.Say, TaskName.Play].includes(a.verb))) {
|
||||||
|
throw new Error(`ActionHookDelayProcessor: invalid actions specified: ${JSON.stringify(this.actions)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get properties() {
|
||||||
|
return {
|
||||||
|
actions: this.actions,
|
||||||
|
retries: this.retries,
|
||||||
|
noResponseTimeout: this.noResponseTimeout,
|
||||||
|
noResponseGiveUpTimeout: this.noResponseGiveUpTimeout
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
get ep() {
|
||||||
|
return this.cs.ep;
|
||||||
|
}
|
||||||
|
|
||||||
|
init(opts) {
|
||||||
|
this.logger.debug({opts}, 'ActionHookDelayProcessor#init');
|
||||||
|
|
||||||
|
this.actions = opts.actions;
|
||||||
|
this.retries = opts.retries || 0;
|
||||||
|
this.noResponseTimeout = opts.noResponseTimeout;
|
||||||
|
this.noResponseGiveUpTimeout = opts.noResponseGiveUpTimeout;
|
||||||
|
this.giveUpActions = opts.giveUpActions;
|
||||||
|
|
||||||
|
// return false if these options actually disable the ahdp
|
||||||
|
return ('enable' in opts && opts.enable === true) ||
|
||||||
|
('enabled' in opts && opts.enabled === true) ||
|
||||||
|
(!('enable' in opts) && !('enabled' in opts));
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
this.logger.debug('ActionHookDelayProcessor#start');
|
||||||
|
if (this._active) {
|
||||||
|
this.logger.debug('ActionHookDelayProcessor#start: already started due to prior gather which is continuing');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._active = true;
|
||||||
|
this._retryCount = 0;
|
||||||
|
if (this.noResponseTimeout > 0) {
|
||||||
|
const timeoutMs = this.noResponseTimeout * 1000;
|
||||||
|
this._noResponseTimer = setTimeout(this._onNoResponseTimer.bind(this), timeoutMs);
|
||||||
|
} else {
|
||||||
|
this.logger.debug(
|
||||||
|
'ActionHookDelayProcessor#start: noResponseTimeout is 0 or undefined hence not calling _onNoResponseTimer'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.noResponseGiveUpTimeout > 0) {
|
||||||
|
const timeoutMs = this.noResponseGiveUpTimeout * 1000;
|
||||||
|
this._noResponseGiveUpTimer = setTimeout(this._onNoResponseGiveUpTimer.bind(this), timeoutMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async stop() {
|
||||||
|
this._active = false;
|
||||||
|
|
||||||
|
if (this._noResponseTimer) {
|
||||||
|
clearTimeout(this._noResponseTimer);
|
||||||
|
this._noResponseTimer = null;
|
||||||
|
}
|
||||||
|
if (this._noResponseGiveUpTimer) {
|
||||||
|
clearTimeout(this._noResponseGiveUpTimer);
|
||||||
|
this._noResponseGiveUpTimer = null;
|
||||||
|
}
|
||||||
|
if (this._taskInProgress) {
|
||||||
|
this.logger.debug(`ActionHookDelayProcessor#stop: stopping ${this._taskInProgress.name}`);
|
||||||
|
|
||||||
|
this._sayResolver = () => {
|
||||||
|
this.logger.debug('ActionHookDelayProcessor#stop: play/say is done, continue on..');
|
||||||
|
//this._taskInProgress.kill(this.cs);
|
||||||
|
this._taskInProgress = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* we let Say finish, but interrupt Play */
|
||||||
|
if (TaskName.Play === this._taskInProgress.name) {
|
||||||
|
await this._taskInProgress.kill(this.cs);
|
||||||
|
}
|
||||||
|
return new Promise((resolve) => this._sayResolver = resolve);
|
||||||
|
}
|
||||||
|
this.logger.debug('ActionHookDelayProcessor#stop returning');
|
||||||
|
}
|
||||||
|
|
||||||
|
_onNoResponseTimer() {
|
||||||
|
this.logger.debug('ActionHookDelayProcessor#_onNoResponseTimer');
|
||||||
|
this._noResponseTimer = null;
|
||||||
|
|
||||||
|
/* get the next play or say action */
|
||||||
|
const verb = this.actions[this._retryCount % this.actions.length];
|
||||||
|
|
||||||
|
const t = normalizeJambones(this.logger, [verb]);
|
||||||
|
this.logger.debug({verb}, 'ActionHookDelayProcessor#_onNoResponseTimer: starting action');
|
||||||
|
try {
|
||||||
|
this._taskInProgress = makeTask(this.logger, t[0]);
|
||||||
|
this._taskInProgress.disableTracing = true;
|
||||||
|
this._taskInProgress.exec(this.cs, {ep: this.ep}).catch((err) => {
|
||||||
|
this.logger.info(`ActionHookDelayProcessor#_onNoResponseTimer: error playing file: ${err.message}`);
|
||||||
|
this._taskInProgress = null;
|
||||||
|
this.ep.removeAllListeners('playback-start');
|
||||||
|
this.ep.removeAllListeners('playback-stop');
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, 'ActionHookDelayProcessor#_onNoResponseTimer: error starting action');
|
||||||
|
this._taskInProgress = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ep.once('playback-start', (evt) => {
|
||||||
|
this.logger.debug({evt}, 'got playback-start');
|
||||||
|
if (!this._active) {
|
||||||
|
this.logger.info({evt}, 'ActionHookDelayProcessor#_onNoResponseTimer: killing audio immediately');
|
||||||
|
|
||||||
|
/* note: in race condition we may have just hung up and cs.ep cleared */
|
||||||
|
this.ep?.api('uuid_break', this.ep?.uuid)
|
||||||
|
.catch((err) => this.logger.info(err,
|
||||||
|
'ActionHookDelayProcessor#_onNoResponseTimer Error killing audio'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.ep.once('playback-stop', (evt) => {
|
||||||
|
this._taskInProgress = null;
|
||||||
|
if (this._sayResolver) {
|
||||||
|
/* we were waiting for the play to finish before continuing to next task */
|
||||||
|
this.logger.debug({evt}, 'ActionHookDelayProcessor#_onNoResponseTimer got playback-stop');
|
||||||
|
this._sayResolver();
|
||||||
|
this._sayResolver = null;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* possibly start the no response timer again */
|
||||||
|
if (this._active && this.retries > 0 && this._retryCount < this.retries && this.noResponseTimeout > 0) {
|
||||||
|
this.logger.debug({evt}, 'ActionHookDelayProcessor#_onNoResponseTimer: playback-stop on play/say action');
|
||||||
|
const timeoutMs = this.noResponseTimeout * 1000;
|
||||||
|
this._noResponseTimer = setTimeout(this._onNoResponseTimer.bind(this), timeoutMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this._retryCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
_onNoResponseGiveUpTimer() {
|
||||||
|
this._active = false;
|
||||||
|
if (!this.giveUpActions) {
|
||||||
|
this.logger.info('ActionHookDelayProcessor#_onNoResponseGiveUpTimer');
|
||||||
|
this.stop().catch((err) => {});
|
||||||
|
this.emit('giveup');
|
||||||
|
} else {
|
||||||
|
this.logger.info('ActionHookDelayProcessor#_onNoResponseGiveUpTimer - giveUpActions');
|
||||||
|
this.emit('giveupWithTasks', this.giveUpActions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ActionHookDelayProcessor;
|
||||||
@@ -45,6 +45,7 @@ if (VMD_HINTS_FILE) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class Amd extends Emitter {
|
class Amd extends Emitter {
|
||||||
constructor(logger, cs, opts) {
|
constructor(logger, cs, opts) {
|
||||||
super();
|
super();
|
||||||
@@ -68,6 +69,8 @@ class Amd extends Emitter {
|
|||||||
this.getIbmAccessToken = getIbmAccessToken;
|
this.getIbmAccessToken = getIbmAccessToken;
|
||||||
const {setChannelVarsForStt} = require('./transcription-utils')(logger);
|
const {setChannelVarsForStt} = require('./transcription-utils')(logger);
|
||||||
this.setChannelVarsForStt = setChannelVarsForStt;
|
this.setChannelVarsForStt = setChannelVarsForStt;
|
||||||
|
this.digitCount = opts.digitCount || 0;
|
||||||
|
this.numberRegEx = RegExp(`[0-9]{${this.digitCount}}`);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
noSpeechTimeoutMs = 5000,
|
noSpeechTimeoutMs = 5000,
|
||||||
@@ -153,7 +156,7 @@ class Amd extends Emitter {
|
|||||||
const wordCount = t.alternatives[0].transcript.split(' ').length;
|
const wordCount = t.alternatives[0].transcript.split(' ').length;
|
||||||
const final = t.is_final;
|
const final = t.is_final;
|
||||||
|
|
||||||
const foundHint = hints.find((h) => t.alternatives[0].transcript.includes(h));
|
const foundHint = hints.find((h) => t.alternatives[0].transcript.toLowerCase().includes(h.toLowerCase()));
|
||||||
if (foundHint) {
|
if (foundHint) {
|
||||||
/* we detected a common voice mail greeting */
|
/* we detected a common voice mail greeting */
|
||||||
this.logger.debug(`Amd:evaluateTranscription: found hint ${foundHint}`);
|
this.logger.debug(`Amd:evaluateTranscription: found hint ${foundHint}`);
|
||||||
@@ -163,6 +166,14 @@ class Amd extends Emitter {
|
|||||||
language: t.language_code
|
language: t.language_code
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
else if (this.digitCount != 0 && this.numberRegEx.test(t.alternatives[0].transcript)) {
|
||||||
|
/* a string of numbers is typically a machine */
|
||||||
|
this.emit(this.decision = AmdEvents.MachineDetected, {
|
||||||
|
reason: 'digit count',
|
||||||
|
greeting: t.alternatives[0].transcript,
|
||||||
|
language: t.language_code
|
||||||
|
});
|
||||||
|
}
|
||||||
else if (final && wordCount < this.thresholdWordCount) {
|
else if (final && wordCount < this.thresholdWordCount) {
|
||||||
/* a short greeting is typically a human */
|
/* a short greeting is typically a human */
|
||||||
this.emit(this.decision = AmdEvents.HumanDetected, {
|
this.emit(this.decision = AmdEvents.HumanDetected, {
|
||||||
@@ -210,7 +221,8 @@ module.exports = (logger) => {
|
|||||||
account_sid: cs.accountSid,
|
account_sid: cs.accountSid,
|
||||||
alert_type: AlertType.STT_FAILURE,
|
alert_type: AlertType.STT_FAILURE,
|
||||||
vendor: vendor,
|
vendor: vendor,
|
||||||
detail: err.message
|
detail: err.message,
|
||||||
|
target_sid: cs.callSid
|
||||||
});
|
});
|
||||||
}).catch((err) => logger.info({err}, 'Error generating alert for tts failure'));
|
}).catch((err) => logger.info({err}, 'Error generating alert for tts failure'));
|
||||||
|
|
||||||
@@ -245,7 +257,10 @@ module.exports = (logger) => {
|
|||||||
const amd = ep.amd = new Amd(logger, cs, opts);
|
const amd = ep.amd = new Amd(logger, cs, opts);
|
||||||
const {vendor, language} = amd;
|
const {vendor, language} = amd;
|
||||||
let sttCredentials = amd.sttCredentials;
|
let sttCredentials = amd.sttCredentials;
|
||||||
const hints = voicemailHints[language] || [];
|
// hints from configuration might be too long for specific language and vendor that make transcribe freeswitch
|
||||||
|
// modules cannot connect to the vendor. hints is used in next step to validate if the transcription
|
||||||
|
// matchs voice mail hints.
|
||||||
|
const hints = [];
|
||||||
|
|
||||||
if (vendor === 'nuance' && sttCredentials.client_id) {
|
if (vendor === 'nuance' && sttCredentials.client_id) {
|
||||||
/* get nuance access token */
|
/* get nuance access token */
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const assert = require('assert');
|
|||||||
const {
|
const {
|
||||||
AWS_REGION,
|
AWS_REGION,
|
||||||
AWS_SNS_PORT: PORT,
|
AWS_SNS_PORT: PORT,
|
||||||
AWS_SNS_TOPIC_ARM,
|
AWS_SNS_TOPIC_ARN,
|
||||||
AWS_SNS_PORT_MAX,
|
AWS_SNS_PORT_MAX,
|
||||||
} = require('../config');
|
} = require('../config');
|
||||||
const {LifeCycleEvents} = require('./constants');
|
const {LifeCycleEvents} = require('./constants');
|
||||||
@@ -55,12 +55,12 @@ class SnsNotifier extends Emitter {
|
|||||||
async _handlePost(req, res) {
|
async _handlePost(req, res) {
|
||||||
try {
|
try {
|
||||||
const parsedBody = JSON.parse(req.body);
|
const parsedBody = JSON.parse(req.body);
|
||||||
this.logger.debug({headers: req.headers, body: parsedBody}, 'Received HTTP POST from AWS');
|
this.logger.info({headers: req.headers, body: parsedBody}, 'Received HTTP POST from AWS');
|
||||||
if (!validatePayload(parsedBody)) {
|
if (!validatePayload(parsedBody)) {
|
||||||
this.logger.info('incoming AWS SNS HTTP POST failed signature validation');
|
this.logger.info('incoming AWS SNS HTTP POST failed signature validation');
|
||||||
return res.sendStatus(403);
|
return res.sendStatus(403);
|
||||||
}
|
}
|
||||||
this.logger.debug('incoming HTTP POST passed validation');
|
this.logger.info('incoming HTTP POST passed validation');
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
|
|
||||||
switch (parsedBody.Type) {
|
switch (parsedBody.Type) {
|
||||||
@@ -74,7 +74,18 @@ class SnsNotifier extends Emitter {
|
|||||||
subscriptionRequestId: this.subscriptionRequestId
|
subscriptionRequestId: this.subscriptionRequestId
|
||||||
}, 'response from SNS SubscribeURL');
|
}, 'response from SNS SubscribeURL');
|
||||||
const data = await this.describeInstance();
|
const data = await this.describeInstance();
|
||||||
this.lifecycleState = data.AutoScalingGroups[0].Instances[0].LifecycleState;
|
|
||||||
|
const group = data.AutoScalingGroups.find((group) =>
|
||||||
|
group.Instances && group.Instances.some((instance) => instance.InstanceId === this.instanceId)
|
||||||
|
);
|
||||||
|
if (!group) {
|
||||||
|
this.logger.error('Current instance not found in any Auto Scaling group', data);
|
||||||
|
} else {
|
||||||
|
const instance = group.Instances.find((instance) => instance.InstanceId === this.instanceId);
|
||||||
|
this.lifecycleState = instance.LifecycleState;
|
||||||
|
}
|
||||||
|
|
||||||
|
//this.lifecycleState = data.AutoScalingGroups[0].Instances[0].LifecycleState;
|
||||||
this.emit('SubscriptionConfirmation', {publicIp: this.publicIp});
|
this.emit('SubscriptionConfirmation', {publicIp: this.publicIp});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -94,7 +105,7 @@ class SnsNotifier extends Emitter {
|
|||||||
this.unsubscribe();
|
this.unsubscribe();
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.logger.debug(`SnsNotifier - instance ${msg.EC2InstanceId} is scaling in (not us)`);
|
this.logger.info(`SnsNotifier - instance ${msg.EC2InstanceId} is scaling in (not us)`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -111,7 +122,7 @@ class SnsNotifier extends Emitter {
|
|||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
try {
|
try {
|
||||||
this.logger.debug('SnsNotifier: retrieving instance data');
|
this.logger.info('SnsNotifier: retrieving instance data');
|
||||||
this.instanceId = await getString('http://169.254.169.254/latest/meta-data/instance-id');
|
this.instanceId = await getString('http://169.254.169.254/latest/meta-data/instance-id');
|
||||||
this.publicIp = await getString('http://169.254.169.254/latest/meta-data/public-ipv4');
|
this.publicIp = await getString('http://169.254.169.254/latest/meta-data/public-ipv4');
|
||||||
this.logger.info({
|
this.logger.info({
|
||||||
@@ -142,13 +153,13 @@ class SnsNotifier extends Emitter {
|
|||||||
try {
|
try {
|
||||||
const params = {
|
const params = {
|
||||||
Protocol: 'http',
|
Protocol: 'http',
|
||||||
TopicArn: AWS_SNS_TOPIC_ARM,
|
TopicArn: AWS_SNS_TOPIC_ARN,
|
||||||
Endpoint: this.snsEndpoint
|
Endpoint: this.snsEndpoint
|
||||||
};
|
};
|
||||||
const response = await snsClient.send(new SubscribeCommand(params));
|
const response = await snsClient.send(new SubscribeCommand(params));
|
||||||
this.logger.info({response}, `response to SNS subscribe to ${AWS_SNS_TOPIC_ARM}`);
|
this.logger.info({response}, `response to SNS subscribe to ${AWS_SNS_TOPIC_ARN}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error({err}, `Error subscribing to SNS topic arn ${AWS_SNS_TOPIC_ARM}`);
|
this.logger.error({err}, `Error subscribing to SNS topic arn ${AWS_SNS_TOPIC_ARN}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,9 +170,9 @@ class SnsNotifier extends Emitter {
|
|||||||
SubscriptionArn: this.subscriptionArn
|
SubscriptionArn: this.subscriptionArn
|
||||||
};
|
};
|
||||||
const response = await snsClient.send(new UnsubscribeCommand(params));
|
const response = await snsClient.send(new UnsubscribeCommand(params));
|
||||||
this.logger.info({response}, `response to SNS unsubscribe to ${AWS_SNS_TOPIC_ARM}`);
|
this.logger.info({response}, `response to SNS unsubscribe to ${AWS_SNS_TOPIC_ARN}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error({err}, `Error unsubscribing to SNS topic arn ${AWS_SNS_TOPIC_ARM}`);
|
this.logger.error({err}, `Error unsubscribing to SNS topic arn ${AWS_SNS_TOPIC_ARN}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
return this.tasks.size;
|
return this.tasks.size;
|
||||||
}
|
}
|
||||||
|
|
||||||
async newTask(type, opts) {
|
async newTask(type, opts, sticky = false) {
|
||||||
this.logger.info({opts}, `initiating Background task ${type}`);
|
this.logger.info({opts}, `initiating Background task ${type}`);
|
||||||
if (this.tasks.has(type)) {
|
if (this.tasks.has(type)) {
|
||||||
this.logger.info(`Background task ${type} is running, skipped`);
|
this.logger.info(`Background task ${type} is running, skipped`);
|
||||||
@@ -46,12 +46,16 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
case 'transcribe':
|
case 'transcribe':
|
||||||
task = await this._initTranscribe(opts);
|
task = await this._initTranscribe(opts);
|
||||||
break;
|
break;
|
||||||
|
case 'ttsStream':
|
||||||
|
task = await this._initTtsStream(opts);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (task) {
|
if (task) {
|
||||||
this.tasks.set(type, task);
|
this.tasks.set(type, task);
|
||||||
}
|
}
|
||||||
|
if (task && sticky) task.sticky = true;
|
||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,6 +103,7 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
async _initBargeIn(opts) {
|
async _initBargeIn(opts) {
|
||||||
let task;
|
let task;
|
||||||
try {
|
try {
|
||||||
|
const copy = JSON.parse(JSON.stringify(opts));
|
||||||
const t = normalizeJambones(this.logger, [opts]);
|
const t = normalizeJambones(this.logger, [opts]);
|
||||||
task = makeTask(this.logger, t[0]);
|
task = makeTask(this.logger, t[0]);
|
||||||
task
|
task
|
||||||
@@ -116,7 +121,8 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
this._taskCompleted('bargeIn', task);
|
this._taskCompleted('bargeIn', task);
|
||||||
if (task.sticky && !this.cs.callGone && !this.cs._stopping) {
|
if (task.sticky && !this.cs.callGone && !this.cs._stopping) {
|
||||||
this.logger.info('BackgroundTaskManager:_initBargeIn: restarting background bargeIn');
|
this.logger.info('BackgroundTaskManager:_initBargeIn: restarting background bargeIn');
|
||||||
this.newTask('bargeIn', opts);
|
this._bargeInHandled = false;
|
||||||
|
this.newTask('bargeIn', copy, true);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
})
|
})
|
||||||
@@ -171,6 +177,25 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initiate Tts Stream
|
||||||
|
async _initTtsStream(opts) {
|
||||||
|
let task;
|
||||||
|
try {
|
||||||
|
const t = normalizeJambones(this.logger, [opts]);
|
||||||
|
task = makeTask(this.logger, t[0]);
|
||||||
|
const resources = await this.cs._evaluatePreconditions(task);
|
||||||
|
const {span, ctx} = this.rootSpan.startChildSpan(`background-ttsStream:${task.summary}`);
|
||||||
|
task.span = span;
|
||||||
|
task.ctx = ctx;
|
||||||
|
task.exec(this.cs, resources)
|
||||||
|
.then(this._taskCompleted.bind(this, 'ttsStream', task))
|
||||||
|
.catch(this._taskError.bind(this, 'ttsStream', task));
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, 'BackgroundTaskManager:_initTtsStream - Error creating ttsStream task');
|
||||||
|
}
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
_taskCompleted(type, task) {
|
_taskCompleted(type, task) {
|
||||||
this.logger.debug({type, task}, `BackgroundTaskManager:_taskCompleted: task completed, sticky: ${task.sticky}`);
|
this.logger.debug({type, task}, `BackgroundTaskManager:_taskCompleted: task completed, sticky: ${task.sticky}`);
|
||||||
task.removeAllListeners();
|
task.removeAllListeners();
|
||||||
@@ -185,6 +210,8 @@ class BackgroundTaskManager extends Emitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_bargeInTaskCompleted(evt) {
|
_bargeInTaskCompleted(evt) {
|
||||||
|
if (this._bargeInHandled) return;
|
||||||
|
this._bargeInHandled = true;
|
||||||
this.logger.debug({evt},
|
this.logger.debug({evt},
|
||||||
'BackgroundTaskManager:_bargeInTaskCompleted on event from background bargeIn, emitting bargein-done event');
|
'BackgroundTaskManager:_bargeInTaskCompleted on event from background bargeIn, emitting bargein-done event');
|
||||||
this.emit('bargeIn-done', evt);
|
this.emit('bargeIn-done', evt);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
const Emitter = require('events');
|
const Emitter = require('events');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
const parseUrl = require('parse-url');
|
||||||
const timeSeries = require('@jambonz/time-series');
|
const timeSeries = require('@jambonz/time-series');
|
||||||
const {NODE_ENV, JAMBONES_TIME_SERIES_HOST} = require('../config');
|
const {NODE_ENV, JAMBONES_TIME_SERIES_HOST} = require('../config');
|
||||||
let alerter ;
|
let alerter ;
|
||||||
@@ -21,6 +22,10 @@ class BaseRequestor extends Emitter {
|
|||||||
const {stats} = require('../../').srf.locals;
|
const {stats} = require('../../').srf.locals;
|
||||||
this.stats = stats;
|
this.stats = stats;
|
||||||
|
|
||||||
|
const u = this._parsedUrl = parseUrl(this.url);
|
||||||
|
if (u.port) this._baseUrl = `${u.protocol}://${u.resource}:${u.port}`;
|
||||||
|
else this._baseUrl = `${u.protocol}://${u.resource}`;
|
||||||
|
|
||||||
if (!alerter) {
|
if (!alerter) {
|
||||||
alerter = timeSeries(logger, {
|
alerter = timeSeries(logger, {
|
||||||
host: JAMBONES_TIME_SERIES_HOST,
|
host: JAMBONES_TIME_SERIES_HOST,
|
||||||
@@ -30,6 +35,10 @@ class BaseRequestor extends Emitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get baseUrl() {
|
||||||
|
return this._baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
get Alerter() {
|
get Alerter() {
|
||||||
return alerter;
|
return alerter;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"Leave": "leave",
|
"Leave": "leave",
|
||||||
"Lex": "lex",
|
"Lex": "lex",
|
||||||
"Listen": "listen",
|
"Listen": "listen",
|
||||||
|
"Llm": "llm",
|
||||||
"Message": "message",
|
"Message": "message",
|
||||||
"Pause": "pause",
|
"Pause": "pause",
|
||||||
"Play": "play",
|
"Play": "play",
|
||||||
@@ -27,10 +28,11 @@
|
|||||||
"SipRedirect": "sip:redirect",
|
"SipRedirect": "sip:redirect",
|
||||||
"Say": "say",
|
"Say": "say",
|
||||||
"SayLegacy": "say:legacy",
|
"SayLegacy": "say:legacy",
|
||||||
|
"Stream": "stream",
|
||||||
"Tag": "tag",
|
"Tag": "tag",
|
||||||
"Transcribe": "transcribe"
|
"Transcribe": "transcribe"
|
||||||
},
|
},
|
||||||
"AllowedSipRecVerbs": ["answer", "config", "gather", "transcribe", "listen", "tag"],
|
"AllowedSipRecVerbs": ["answer", "config", "gather", "transcribe", "listen", "tag", "hangup", "sip:decline"],
|
||||||
"AllowedConfirmSessionVerbs": ["config", "gather", "plays", "say", "tag"],
|
"AllowedConfirmSessionVerbs": ["config", "gather", "plays", "say", "tag"],
|
||||||
"CallStatus": {
|
"CallStatus": {
|
||||||
"Trying": "trying",
|
"Trying": "trying",
|
||||||
@@ -97,6 +99,10 @@
|
|||||||
"Transcription": "soniox_transcribe::transcription",
|
"Transcription": "soniox_transcribe::transcription",
|
||||||
"Error": "soniox_transcribe::error"
|
"Error": "soniox_transcribe::error"
|
||||||
},
|
},
|
||||||
|
"VerbioTranscriptionEvents": {
|
||||||
|
"Transcription": "verbio_transcribe::transcription",
|
||||||
|
"Error": "verbio_transcribe::error"
|
||||||
|
},
|
||||||
"CobaltTranscriptionEvents": {
|
"CobaltTranscriptionEvents": {
|
||||||
"Transcription": "cobalt_speech::transcription",
|
"Transcription": "cobalt_speech::transcription",
|
||||||
"CompileContext": "cobalt_speech::compile_context_response",
|
"CompileContext": "cobalt_speech::compile_context_response",
|
||||||
@@ -122,6 +128,27 @@
|
|||||||
"NoSpeechDetected": "azure_transcribe::no_speech_detected",
|
"NoSpeechDetected": "azure_transcribe::no_speech_detected",
|
||||||
"VadDetected": "azure_transcribe::vad_detected"
|
"VadDetected": "azure_transcribe::vad_detected"
|
||||||
},
|
},
|
||||||
|
"SpeechmaticsTranscriptionEvents": {
|
||||||
|
"Transcription": "speechmatics_transcribe::transcription",
|
||||||
|
"Translation": "speechmatics_transcribe::translation",
|
||||||
|
"Info": "speechmatics_transcribe::info",
|
||||||
|
"RecognitionStarted": "speechmatics_transcribe::recognition_started",
|
||||||
|
"ConnectFailure": "speechmatics_transcribe::connect_failed",
|
||||||
|
"Connect": "speechmatics_transcribe::connect",
|
||||||
|
"Error": "speechmatics_transcribe::error"
|
||||||
|
},
|
||||||
|
"OpenAITranscriptionEvents": {
|
||||||
|
"Transcription": "openai_transcribe::transcription",
|
||||||
|
"Translation": "openai_transcribe::translation",
|
||||||
|
"SpeechStarted": "openai_transcribe::speech_started",
|
||||||
|
"SpeechStopped": "openai_transcribe::speech_stopped",
|
||||||
|
"PartialTranscript": "openai_transcribe::partial_transcript",
|
||||||
|
"Info": "openai_transcribe::info",
|
||||||
|
"RecognitionStarted": "openai_transcribe::recognition_started",
|
||||||
|
"ConnectFailure": "openai_transcribe::connect_failed",
|
||||||
|
"Connect": "openai_transcribe::connect",
|
||||||
|
"Error": "openai_transcribe::error"
|
||||||
|
},
|
||||||
"JambonzTranscriptionEvents": {
|
"JambonzTranscriptionEvents": {
|
||||||
"Transcription": "jambonz_transcribe::transcription",
|
"Transcription": "jambonz_transcribe::transcription",
|
||||||
"ConnectFailure": "jambonz_transcribe::connect_failed",
|
"ConnectFailure": "jambonz_transcribe::connect_failed",
|
||||||
@@ -134,6 +161,15 @@
|
|||||||
"ConnectFailure": "assemblyai_transcribe::connect_failed",
|
"ConnectFailure": "assemblyai_transcribe::connect_failed",
|
||||||
"Connect": "assemblyai_transcribe::connect"
|
"Connect": "assemblyai_transcribe::connect"
|
||||||
},
|
},
|
||||||
|
"VoxistTranscriptionEvents": {
|
||||||
|
"Transcription": "voxist_transcribe::transcription",
|
||||||
|
"Error": "voxist_transcribe::error",
|
||||||
|
"ConnectFailure": "voxist_transcribe::connect_failed",
|
||||||
|
"Connect": "voxist_transcribe::connect"
|
||||||
|
},
|
||||||
|
"VadDetection": {
|
||||||
|
"Detection": "vad_detect:detection"
|
||||||
|
},
|
||||||
"ListenEvents": {
|
"ListenEvents": {
|
||||||
"Connect": "mod_audio_fork::connect",
|
"Connect": "mod_audio_fork::connect",
|
||||||
"ConnectFailure": "mod_audio_fork::connect_failed",
|
"ConnectFailure": "mod_audio_fork::connect_failed",
|
||||||
@@ -151,6 +187,34 @@
|
|||||||
"StandbyEnter": "standby-enter",
|
"StandbyEnter": "standby-enter",
|
||||||
"StandbyExit": "standby-exit"
|
"StandbyExit": "standby-exit"
|
||||||
},
|
},
|
||||||
|
"LlmEvents_OpenAI": {
|
||||||
|
"Error": "error",
|
||||||
|
"Connect": "openai_s2s::connect",
|
||||||
|
"ConnectFailure": "openai_s2s::connect_failed",
|
||||||
|
"Disconnect": "openai_s2s::disconnect",
|
||||||
|
"ServerEvent": "openai_s2s::server_event"
|
||||||
|
},
|
||||||
|
"LlmEvents_Elevenlabs": {
|
||||||
|
"Error": "error",
|
||||||
|
"Connect": "elevenlabs_s2s::connect",
|
||||||
|
"ConnectFailure": "elevenlabs_s2s::connect_failed",
|
||||||
|
"Disconnect": "elevenlabs_s2s::disconnect",
|
||||||
|
"ServerEvent": "elevenlabs_s2s::server_event"
|
||||||
|
},
|
||||||
|
"LlmEvents_VoiceAgent": {
|
||||||
|
"Error": "error",
|
||||||
|
"Connect": "voice_agent_s2s::connect",
|
||||||
|
"ConnectFailure": "voice_agent_s2s::connect_failed",
|
||||||
|
"Disconnect": "voice_agent_s2s::disconnect",
|
||||||
|
"ServerEvent": "voice_agent_s2s::server_event"
|
||||||
|
},
|
||||||
|
"LlmEvents_Ultravox": {
|
||||||
|
"Error": "error",
|
||||||
|
"Connect": "ultravox_s2s::connect",
|
||||||
|
"ConnectFailure": "ultravox_s2s::connect_failed",
|
||||||
|
"Disconnect": "ultravox_s2s::disconnect",
|
||||||
|
"ServerEvent": "ultravox_s2s::server_event"
|
||||||
|
},
|
||||||
"QueueResults": {
|
"QueueResults": {
|
||||||
"Bridged": "bridged",
|
"Bridged": "bridged",
|
||||||
"Error": "error",
|
"Error": "error",
|
||||||
@@ -165,17 +229,23 @@
|
|||||||
},
|
},
|
||||||
"KillReason": {
|
"KillReason": {
|
||||||
"Hangup": "hangup",
|
"Hangup": "hangup",
|
||||||
"Replaced": "replaced"
|
"Replaced": "replaced",
|
||||||
|
"MediaTimeout": "media_timeout"
|
||||||
},
|
},
|
||||||
"HookMsgTypes": [
|
"HookMsgTypes": [
|
||||||
"session:new",
|
"session:new",
|
||||||
"session:reconnect",
|
"session:reconnect",
|
||||||
"session:redirect",
|
"session:redirect",
|
||||||
|
"session:adulting",
|
||||||
"call:status",
|
"call:status",
|
||||||
"queue:status",
|
"queue:status",
|
||||||
"dial:confirm",
|
"dial:confirm",
|
||||||
"verb:hook",
|
"verb:hook",
|
||||||
"verb:status",
|
"verb:status",
|
||||||
|
"llm:event",
|
||||||
|
"llm:tool-call",
|
||||||
|
"tts:tokens-result",
|
||||||
|
"tts:streaming-event",
|
||||||
"jambonz:error"
|
"jambonz:error"
|
||||||
],
|
],
|
||||||
"RecordState": {
|
"RecordState": {
|
||||||
@@ -194,7 +264,59 @@
|
|||||||
"ToneTimeout": "amd_tone_timeout",
|
"ToneTimeout": "amd_tone_timeout",
|
||||||
"Stopped": "amd_stopped"
|
"Stopped": "amd_stopped"
|
||||||
},
|
},
|
||||||
|
"MediaPath": {
|
||||||
|
"NoMedia": "no-media",
|
||||||
|
"PartialMedia": "partial-media",
|
||||||
|
"FullMedia": "full-media"
|
||||||
|
},
|
||||||
|
"DeepgramTtsStreamingEvents": {
|
||||||
|
"Empty": "deepgram_tts_streaming::empty",
|
||||||
|
"ConnectFailure": "deepgram_tts_streaming::connect_failed",
|
||||||
|
"Connect": "deepgram_tts_streaming::connect"
|
||||||
|
},
|
||||||
|
"CartesiaTtsStreamingEvents": {
|
||||||
|
"Empty": "cartesia_tts_streaming::empty",
|
||||||
|
"ConnectFailure": "cartesia_tts_streaming::connect_failed",
|
||||||
|
"Connect": "cartesia_tts_streaming::connect"
|
||||||
|
},
|
||||||
|
"ElevenlabsTtsStreamingEvents": {
|
||||||
|
"Empty": "elevenlabs_tts_streaming::empty",
|
||||||
|
"ConnectFailure": "elevenlabs_tts_streaming::connect_failed",
|
||||||
|
"Connect": "elevenlabs_tts_streaming::connect"
|
||||||
|
},
|
||||||
|
"RimelabsTtsStreamingEvents": {
|
||||||
|
"Empty": "rimelabs_tts_streaming::empty",
|
||||||
|
"ConnectFailure": "rimelabs_tts_streaming::connect_failed",
|
||||||
|
"Connect": "rimelabs_tts_streaming::connect"
|
||||||
|
},
|
||||||
|
"CustomTtsStreamingEvents": {
|
||||||
|
"Empty": "custom_tts_streaming::empty",
|
||||||
|
"ConnectFailure": "custom_tts_streaming::connect_failed",
|
||||||
|
"Connect": "custom_tts_streaming::connect"
|
||||||
|
},
|
||||||
|
"TtsStreamingEvents": {
|
||||||
|
"Empty": "tts_streaming::empty",
|
||||||
|
"Pause": "tts_streaming::pause",
|
||||||
|
"Resume": "tts_streaming::resume",
|
||||||
|
"ConnectFailure": "tts_streaming::connect_failed"
|
||||||
|
},
|
||||||
|
"TtsStreamingConnectionStatus": {
|
||||||
|
"NotConnected": "not_connected",
|
||||||
|
"Connected": "connected",
|
||||||
|
"Connecting": "connecting",
|
||||||
|
"Failed": "failed"
|
||||||
|
},
|
||||||
"MAX_SIMRINGS": 10,
|
"MAX_SIMRINGS": 10,
|
||||||
"BONG_TONE": "tone_stream://v=-7;%(100,0,941.0,1477.0);v=-7;>=2;+=.1;%(1400,0,350,440)",
|
"BONG_TONE": "tone_stream://v=-7;%(100,0,941.0,1477.0);v=-7;>=2;+=.1;%(1400,0,350,440)",
|
||||||
"FS_UUID_SET_NAME": "fsUUIDs"
|
"FS_UUID_SET_NAME": "fsUUIDs",
|
||||||
|
"SystemState" : {
|
||||||
|
"Online": "ONLINE",
|
||||||
|
"Offline": "OFFLINE",
|
||||||
|
"GracefulShutdownInProgress":"SHUTDOWN_IN_PROGRESS"
|
||||||
|
},
|
||||||
|
"FEATURE_SERVER" : "feature-server",
|
||||||
|
"WS_CLOSE_CODES": {
|
||||||
|
"NormalClosure": 1000,
|
||||||
|
"GoingAway": 1001
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ const speechMapper = (cred) => {
|
|||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.access_key_id = o.access_key_id;
|
obj.access_key_id = o.access_key_id;
|
||||||
obj.secret_access_key = o.secret_access_key;
|
obj.secret_access_key = o.secret_access_key;
|
||||||
|
obj.role_arn = o.role_arn;
|
||||||
obj.aws_region = o.aws_region;
|
obj.aws_region = o.aws_region;
|
||||||
}
|
}
|
||||||
else if ('microsoft' === obj.vendor) {
|
else if ('microsoft' === obj.vendor) {
|
||||||
@@ -76,6 +77,7 @@ const speechMapper = (cred) => {
|
|||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.api_key = o.api_key;
|
obj.api_key = o.api_key;
|
||||||
obj.deepgram_stt_uri = o.deepgram_stt_uri;
|
obj.deepgram_stt_uri = o.deepgram_stt_uri;
|
||||||
|
obj.deepgram_tts_uri = o.deepgram_tts_uri;
|
||||||
obj.deepgram_stt_use_tls = o.deepgram_stt_use_tls;
|
obj.deepgram_stt_use_tls = o.deepgram_stt_use_tls;
|
||||||
}
|
}
|
||||||
else if ('soniox' === obj.vendor) {
|
else if ('soniox' === obj.vendor) {
|
||||||
@@ -89,23 +91,68 @@ const speechMapper = (cred) => {
|
|||||||
else if ('cobalt' === obj.vendor) {
|
else if ('cobalt' === obj.vendor) {
|
||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.cobalt_server_uri = o.cobalt_server_uri;
|
obj.cobalt_server_uri = o.cobalt_server_uri;
|
||||||
} else if ('elevenlabs' === obj.vendor) {
|
}
|
||||||
|
else if ('elevenlabs' === obj.vendor) {
|
||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.api_key = o.api_key;
|
obj.api_key = o.api_key;
|
||||||
obj.model_id = o.model_id;
|
obj.model_id = o.model_id;
|
||||||
obj.options = o.options;
|
obj.options = o.options;
|
||||||
} else if ('assemblyai' === obj.vendor) {
|
}
|
||||||
|
else if ('playht' === obj.vendor) {
|
||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.api_key = o.api_key;
|
obj.api_key = o.api_key;
|
||||||
} else if ('whisper' === obj.vendor) {
|
obj.user_id = o.user_id;
|
||||||
|
obj.voice_engine = o.voice_engine;
|
||||||
|
obj.options = o.options;
|
||||||
|
}
|
||||||
|
else if ('cartesia' === obj.vendor) {
|
||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.api_key = o.api_key;
|
obj.api_key = o.api_key;
|
||||||
obj.model_id = o.model_id;
|
obj.model_id = o.model_id;
|
||||||
} else if (obj.vendor.startsWith('custom:')) {
|
obj.embedding = o.embedding;
|
||||||
|
obj.options = o.options;
|
||||||
|
}
|
||||||
|
else if ('rimelabs' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
obj.model_id = o.model_id;
|
||||||
|
obj.options = o.options;
|
||||||
|
}
|
||||||
|
else if ('assemblyai' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
}
|
||||||
|
else if ('voxist' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
}
|
||||||
|
else if ('whisper' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
obj.model_id = o.model_id;
|
||||||
|
}
|
||||||
|
else if ('verbio' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.client_id = o.client_id;
|
||||||
|
obj.client_secret = o.client_secret;
|
||||||
|
obj.engine_version = o.engine_version;
|
||||||
|
}
|
||||||
|
else if ('speechmatics' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
obj.speechmatics_stt_uri = o.speechmatics_stt_uri;
|
||||||
|
}
|
||||||
|
else if ('openai' === obj.vendor) {
|
||||||
|
const o = JSON.parse(decrypt(credential));
|
||||||
|
obj.api_key = o.api_key;
|
||||||
|
obj.model_id = o.model_id;
|
||||||
|
}
|
||||||
|
else if (obj.vendor.startsWith('custom:')) {
|
||||||
const o = JSON.parse(decrypt(credential));
|
const o = JSON.parse(decrypt(credential));
|
||||||
obj.auth_token = o.auth_token;
|
obj.auth_token = o.auth_token;
|
||||||
obj.custom_stt_url = o.custom_stt_url;
|
obj.custom_stt_url = o.custom_stt_url;
|
||||||
obj.custom_tts_url = o.custom_tts_url;
|
obj.custom_tts_url = o.custom_tts_url;
|
||||||
|
obj.custom_tts_streaming_url = o.custom_tts_streaming_url;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
@@ -185,11 +232,23 @@ module.exports = (logger, srf) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const lookupVoipCarrierBySid = async(sid) => {
|
||||||
|
const pp = pool.promise();
|
||||||
|
try {
|
||||||
|
const [r] = await pp.query('SELECT * FROM voip_carriers WHERE voip_carrier_sid = ?', [sid]);
|
||||||
|
return r;
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({err}, `lookupVoipCarrierBySid: Error ${sid}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lookupAccountDetails,
|
lookupAccountDetails,
|
||||||
updateSpeechCredentialLastUsed,
|
updateSpeechCredentialLastUsed,
|
||||||
lookupCarrier,
|
lookupCarrier,
|
||||||
lookupCarrierByPhoneNumber,
|
lookupCarrierByPhoneNumber,
|
||||||
lookupGoogleCustomVoice
|
lookupGoogleCustomVoice,
|
||||||
|
lookupVoipCarrierBySid
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
33
lib/utils/error.js
Normal file
33
lib/utils/error.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
class NonFatalTaskError extends Error {
|
||||||
|
constructor(msg) {
|
||||||
|
super(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SpeechCredentialError extends NonFatalTaskError {
|
||||||
|
constructor(msg) {
|
||||||
|
super(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PlayFileNotFoundError extends NonFatalTaskError {
|
||||||
|
constructor(url) {
|
||||||
|
super('File not found');
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class HTTPResponseError extends Error {
|
||||||
|
constructor(statusCode) {
|
||||||
|
super('Unexpected HTTP Response');
|
||||||
|
delete this.stack;
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
SpeechCredentialError,
|
||||||
|
NonFatalTaskError,
|
||||||
|
PlayFileNotFoundError,
|
||||||
|
HTTPResponseError
|
||||||
|
};
|
||||||
5
lib/utils/helpers.js
Normal file
5
lib/utils/helpers.js
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
|
||||||
|
const sleepFor = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
|
||||||
|
module.exports = {
|
||||||
|
sleepFor
|
||||||
|
};
|
||||||
@@ -16,6 +16,7 @@ const {
|
|||||||
NODE_ENV,
|
NODE_ENV,
|
||||||
HTTP_USER_AGENT_HEADER,
|
HTTP_USER_AGENT_HEADER,
|
||||||
} = require('../config');
|
} = require('../config');
|
||||||
|
const {HTTPResponseError} = require('./error');
|
||||||
|
|
||||||
const toBase64 = (str) => Buffer.from(str || '', 'utf8').toString('base64');
|
const toBase64 = (str) => Buffer.from(str || '', 'utf8').toString('base64');
|
||||||
|
|
||||||
@@ -47,8 +48,6 @@ class HttpRequestor extends BaseRequestor {
|
|||||||
assert(['GET', 'POST'].includes(this.method));
|
assert(['GET', 'POST'].includes(this.method));
|
||||||
|
|
||||||
const u = this._parsedUrl = parseUrl(this.url);
|
const u = this._parsedUrl = parseUrl(this.url);
|
||||||
if (u.port) this._baseUrl = `${u.protocol}://${u.resource}:${u.port}`;
|
|
||||||
else this._baseUrl = `${u.protocol}://${u.resource}`;
|
|
||||||
this._protocol = u.protocol;
|
this._protocol = u.protocol;
|
||||||
this._resource = u.resource;
|
this._resource = u.resource;
|
||||||
this._port = u.port;
|
this._port = u.port;
|
||||||
@@ -56,18 +55,18 @@ class HttpRequestor extends BaseRequestor {
|
|||||||
this._usePools = HTTP_POOL && parseInt(HTTP_POOL);
|
this._usePools = HTTP_POOL && parseInt(HTTP_POOL);
|
||||||
|
|
||||||
if (this._usePools) {
|
if (this._usePools) {
|
||||||
if (pools.has(this._baseUrl)) {
|
if (pools.has(this.baseUrl)) {
|
||||||
this.client = pools.get(this._baseUrl);
|
this.client = pools.get(this.baseUrl);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
const connections = HTTP_POOLSIZE ? parseInt(HTTP_POOLSIZE) : 10;
|
const connections = HTTP_POOLSIZE ? parseInt(HTTP_POOLSIZE) : 10;
|
||||||
const pipelining = HTTP_PIPELINING ? parseInt(HTTP_PIPELINING) : 1;
|
const pipelining = HTTP_PIPELINING ? parseInt(HTTP_PIPELINING) : 1;
|
||||||
const pool = this.client = new Pool(this._baseUrl, {
|
const pool = this.client = new Pool(this.baseUrl, {
|
||||||
connections,
|
connections,
|
||||||
pipelining
|
pipelining
|
||||||
});
|
});
|
||||||
pools.set(this._baseUrl, pool);
|
pools.set(this.baseUrl, pool);
|
||||||
this.logger.debug(`HttpRequestor:created pool for ${this._baseUrl}`);
|
this.logger.debug(`HttpRequestor:created pool for ${this.baseUrl}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -88,10 +87,6 @@ class HttpRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get baseUrl() {
|
|
||||||
return this._baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
if (!this._usePools && !this.client?.closed) this.client.close();
|
if (!this._usePools && !this.client?.closed) this.client.close();
|
||||||
}
|
}
|
||||||
@@ -190,8 +185,7 @@ class HttpRequestor extends BaseRequestor {
|
|||||||
followRedirects: false
|
followRedirects: false
|
||||||
});
|
});
|
||||||
if (![200, 202, 204].includes(statusCode)) {
|
if (![200, 202, 204].includes(statusCode)) {
|
||||||
const err = new Error();
|
const err = new HTTPResponseError(statusCode);
|
||||||
err.statusCode = statusCode;
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
if (headers['content-type']?.includes('application/json')) {
|
if (headers['content-type']?.includes('application/json')) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const Mrf = require('drachtio-fsmrf');
|
const Mrf = require('drachtio-fsmrf');
|
||||||
const ip = require('ip');
|
const os = require('os');
|
||||||
const {
|
const {
|
||||||
JAMBONES_MYSQL_HOST,
|
JAMBONES_MYSQL_HOST,
|
||||||
JAMBONES_MYSQL_USER,
|
JAMBONES_MYSQL_USER,
|
||||||
@@ -12,11 +12,25 @@ const {
|
|||||||
JAMBONES_TIME_SERIES_HOST,
|
JAMBONES_TIME_SERIES_HOST,
|
||||||
JAMBONES_ESL_LISTEN_ADDRESS,
|
JAMBONES_ESL_LISTEN_ADDRESS,
|
||||||
PORT,
|
PORT,
|
||||||
|
HTTP_IP,
|
||||||
NODE_ENV,
|
NODE_ENV,
|
||||||
} = require('../config');
|
} = require('../config');
|
||||||
const Registrar = require('@jambonz/mw-registrar');
|
const Registrar = require('@jambonz/mw-registrar');
|
||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
|
|
||||||
|
function getLocalIp() {
|
||||||
|
const interfaces = os.networkInterfaces();
|
||||||
|
for (const interfaceName in interfaces) {
|
||||||
|
const interface = interfaces[interfaceName];
|
||||||
|
for (const iface of interface) {
|
||||||
|
if (iface.family === 'IPv4' && !iface.internal) {
|
||||||
|
return iface.address;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return '127.0.0.1'; // Fallback to localhost if no suitable interface found
|
||||||
|
}
|
||||||
|
|
||||||
function initMS(logger, wrapper, ms) {
|
function initMS(logger, wrapper, ms) {
|
||||||
Object.assign(wrapper, {ms, active: true, connects: 1});
|
Object.assign(wrapper, {ms, active: true, connects: 1});
|
||||||
logger.info(`connected to freeswitch at ${ms.address}`);
|
logger.info(`connected to freeswitch at ${ms.address}`);
|
||||||
@@ -138,7 +152,8 @@ function installSrfLocals(srf, logger) {
|
|||||||
lookupAccountBySid,
|
lookupAccountBySid,
|
||||||
lookupAccountCapacitiesBySid,
|
lookupAccountCapacitiesBySid,
|
||||||
lookupSmppGateways,
|
lookupSmppGateways,
|
||||||
lookupClientByAccountAndUsername
|
lookupClientByAccountAndUsername,
|
||||||
|
lookupSystemInformation
|
||||||
} = require('@jambonz/db-helpers')({
|
} = require('@jambonz/db-helpers')({
|
||||||
host: JAMBONES_MYSQL_HOST,
|
host: JAMBONES_MYSQL_HOST,
|
||||||
user: JAMBONES_MYSQL_USER,
|
user: JAMBONES_MYSQL_USER,
|
||||||
@@ -171,7 +186,7 @@ function installSrfLocals(srf, logger) {
|
|||||||
retrieveFromSortedSet,
|
retrieveFromSortedSet,
|
||||||
retrieveByPatternSortedSet,
|
retrieveByPatternSortedSet,
|
||||||
sortedSetLength,
|
sortedSetLength,
|
||||||
sortedSetPositionByPattern
|
sortedSetPositionByPattern,
|
||||||
} = require('@jambonz/realtimedb-helpers')({}, logger, tracer);
|
} = require('@jambonz/realtimedb-helpers')({}, logger, tracer);
|
||||||
const registrar = new Registrar(logger, client);
|
const registrar = new Registrar(logger, client);
|
||||||
const {
|
const {
|
||||||
@@ -179,10 +194,13 @@ function installSrfLocals(srf, logger) {
|
|||||||
addFileToCache,
|
addFileToCache,
|
||||||
getNuanceAccessToken,
|
getNuanceAccessToken,
|
||||||
getIbmAccessToken,
|
getIbmAccessToken,
|
||||||
|
getAwsAuthToken,
|
||||||
|
getVerbioAccessToken
|
||||||
} = require('@jambonz/speech-utils')({}, logger);
|
} = require('@jambonz/speech-utils')({}, logger);
|
||||||
const {
|
const {
|
||||||
writeAlerts,
|
writeAlerts,
|
||||||
AlertType
|
AlertType,
|
||||||
|
writeSystemAlerts
|
||||||
} = require('@jambonz/time-series')(logger, {
|
} = require('@jambonz/time-series')(logger, {
|
||||||
host: JAMBONES_TIME_SERIES_HOST,
|
host: JAMBONES_TIME_SERIES_HOST,
|
||||||
commitSize: 50,
|
commitSize: 50,
|
||||||
@@ -191,7 +209,8 @@ function installSrfLocals(srf, logger) {
|
|||||||
|
|
||||||
let localIp;
|
let localIp;
|
||||||
try {
|
try {
|
||||||
localIp = ip.address();
|
// Either use the configured IP address or discover it
|
||||||
|
localIp = HTTP_IP || getLocalIp();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error({err}, 'installSrfLocals - error detecting local ipv4 address');
|
logger.error({err}, 'installSrfLocals - error detecting local ipv4 address');
|
||||||
}
|
}
|
||||||
@@ -211,11 +230,13 @@ function installSrfLocals(srf, logger) {
|
|||||||
lookupAccountCapacitiesBySid,
|
lookupAccountCapacitiesBySid,
|
||||||
lookupSmppGateways,
|
lookupSmppGateways,
|
||||||
lookupClientByAccountAndUsername,
|
lookupClientByAccountAndUsername,
|
||||||
|
lookupSystemInformation,
|
||||||
updateCallStatus,
|
updateCallStatus,
|
||||||
retrieveCall,
|
retrieveCall,
|
||||||
listCalls,
|
listCalls,
|
||||||
deleteCall,
|
deleteCall,
|
||||||
synthAudio,
|
synthAudio,
|
||||||
|
getAwsAuthToken,
|
||||||
addFileToCache,
|
addFileToCache,
|
||||||
createHash,
|
createHash,
|
||||||
retrieveHash,
|
retrieveHash,
|
||||||
@@ -237,7 +258,8 @@ function installSrfLocals(srf, logger) {
|
|||||||
retrieveFromSortedSet,
|
retrieveFromSortedSet,
|
||||||
retrieveByPatternSortedSet,
|
retrieveByPatternSortedSet,
|
||||||
sortedSetLength,
|
sortedSetLength,
|
||||||
sortedSetPositionByPattern
|
sortedSetPositionByPattern,
|
||||||
|
getVerbioAccessToken
|
||||||
},
|
},
|
||||||
parentLogger: logger,
|
parentLogger: logger,
|
||||||
getSBC,
|
getSBC,
|
||||||
@@ -248,7 +270,8 @@ function installSrfLocals(srf, logger) {
|
|||||||
getFreeswitch,
|
getFreeswitch,
|
||||||
stats: stats,
|
stats: stats,
|
||||||
writeAlerts,
|
writeAlerts,
|
||||||
AlertType
|
AlertType,
|
||||||
|
writeSystemAlerts
|
||||||
};
|
};
|
||||||
|
|
||||||
if (localIp) {
|
if (localIp) {
|
||||||
|
|||||||
32
lib/utils/network.js
Normal file
32
lib/utils/network.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a list of hostport entries and selects the first one that matches the specified protocol,
|
||||||
|
* excluding any entries with the localhost IP address ('127.0.0.1').
|
||||||
|
*
|
||||||
|
* Each hostport entry should be in the format: 'protocol/ip:port'
|
||||||
|
*
|
||||||
|
* @param {Object} logger - A logging object with a 'debug' method for logging debug messages.
|
||||||
|
* @param {string} hostport - A comma-separated string containing hostport entries.
|
||||||
|
* @param {string} protocol - The protocol to match (e.g., 'udp', 'tcp').
|
||||||
|
* @returns {Array} An array containing:
|
||||||
|
* 0: protocol
|
||||||
|
* 1: ip address
|
||||||
|
* 2: port
|
||||||
|
*/
|
||||||
|
const selectHostPort = (logger, hostport, protocol) => {
|
||||||
|
logger.debug(`selectHostPort: ${hostport}, ${protocol}`);
|
||||||
|
const sel = hostport
|
||||||
|
.split(',')
|
||||||
|
.map((hp) => {
|
||||||
|
const arr = /(.*)\/(.*):(.*)/.exec(hp);
|
||||||
|
return [arr[1], arr[2], arr[3]];
|
||||||
|
})
|
||||||
|
.filter((hp) => {
|
||||||
|
return hp[0] === protocol && hp[1] !== '127.0.0.1';
|
||||||
|
});
|
||||||
|
return sel[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
selectHostPort
|
||||||
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
const Emitter = require('events');
|
const Emitter = require('events');
|
||||||
const {CallStatus} = require('./constants');
|
const {CallStatus, MediaPath} = require('./constants');
|
||||||
const SipError = require('drachtio-srf').SipError;
|
const SipError = require('drachtio-srf').SipError;
|
||||||
const {TaskPreconditions, CallDirection} = require('../utils/constants');
|
const {TaskPreconditions, CallDirection} = require('../utils/constants');
|
||||||
const CallInfo = require('../session/call-info');
|
const CallInfo = require('../session/call-info');
|
||||||
@@ -15,10 +15,14 @@ const RootSpan = require('./call-tracer');
|
|||||||
const uuidv4 = require('uuid-random');
|
const uuidv4 = require('uuid-random');
|
||||||
const HttpRequestor = require('./http-requestor');
|
const HttpRequestor = require('./http-requestor');
|
||||||
const WsRequestor = require('./ws-requestor');
|
const WsRequestor = require('./ws-requestor');
|
||||||
const {makeOpusFirst} = require('./sdp-utils');
|
const {makeOpusFirst, removeVideoSdp} = require('./sdp-utils');
|
||||||
const {
|
const {
|
||||||
JAMBONES_USE_FREESWITCH_TIMER_FD
|
JAMBONES_USE_FREESWITCH_TIMER_FD,
|
||||||
|
JAMBONES_MEDIA_TIMEOUT_MS,
|
||||||
|
JAMBONES_MEDIA_HOLD_TIMEOUT_MS,
|
||||||
|
JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS
|
||||||
} = require('../config');
|
} = require('../config');
|
||||||
|
const { sleepFor } = require('./helpers');
|
||||||
|
|
||||||
class SingleDialer extends Emitter {
|
class SingleDialer extends Emitter {
|
||||||
constructor({logger, sbcAddress, target, opts, application, callInfo, accountInfo, rootSpan, startSpan, dialTask,
|
constructor({logger, sbcAddress, target, opts, application, callInfo, accountInfo, rootSpan, startSpan, dialTask,
|
||||||
@@ -150,15 +154,21 @@ class SingleDialer extends Emitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let lastSdp;
|
let lastSdp;
|
||||||
const connectStream = async(remoteSdp) => {
|
const connectStream = async(remoteSdp, isVideoCall) => {
|
||||||
if (remoteSdp === lastSdp) return;
|
if (remoteSdp === lastSdp) return;
|
||||||
|
if (process.env.JAMBONES_VIDEO_CALLS_ENABLED_IN_FS && !isVideoCall) {
|
||||||
|
remoteSdp = removeVideoSdp(remoteSdp);
|
||||||
|
}
|
||||||
lastSdp = remoteSdp;
|
lastSdp = remoteSdp;
|
||||||
return this.ep.modify(remoteSdp);
|
return this.ep.modify(remoteSdp);
|
||||||
};
|
};
|
||||||
|
let localSdp = this.ep.local.sdp;
|
||||||
|
if (process.env.JAMBONES_VIDEO_CALLS_ENABLED_IN_FS && !opts.isVideoCall) {
|
||||||
|
localSdp = removeVideoSdp(localSdp);
|
||||||
|
}
|
||||||
Object.assign(opts, {
|
Object.assign(opts, {
|
||||||
proxy: `sip:${this.sbcAddress}`,
|
proxy: `sip:${this.sbcAddress}`,
|
||||||
localSdp: opts.opusFirst ? makeOpusFirst(this.ep.local.sdp) : this.ep.local.sdp
|
localSdp: opts.opusFirst ? makeOpusFirst(localSdp) : localSdp
|
||||||
});
|
});
|
||||||
if (this.target.auth) opts.auth = this.target.auth;
|
if (this.target.auth) opts.auth = this.target.auth;
|
||||||
inviteSpan = this.startSpan('invite', {
|
inviteSpan = this.startSpan('invite', {
|
||||||
@@ -213,18 +223,20 @@ class SingleDialer extends Emitter {
|
|||||||
},
|
},
|
||||||
cbProvisional: (prov) => {
|
cbProvisional: (prov) => {
|
||||||
const status = {sipStatus: prov.status, sipReason: prov.reason};
|
const status = {sipStatus: prov.status, sipReason: prov.reason};
|
||||||
|
// Update call-id for sbc outbound INVITE
|
||||||
|
this.callInfo.sbcCallid = prov.get('X-CID');
|
||||||
if ([180, 183].includes(prov.status) && prov.body) {
|
if ([180, 183].includes(prov.status) && prov.body) {
|
||||||
if (status.callStatus !== CallStatus.EarlyMedia) {
|
if (status.callStatus !== CallStatus.EarlyMedia) {
|
||||||
status.callStatus = CallStatus.EarlyMedia;
|
status.callStatus = CallStatus.EarlyMedia;
|
||||||
this.emit('earlyMedia');
|
this.emit('earlyMedia');
|
||||||
}
|
}
|
||||||
connectStream(prov.body);
|
connectStream(prov.body, opts.isVideoCall);
|
||||||
}
|
}
|
||||||
else status.callStatus = CallStatus.Ringing;
|
else status.callStatus = CallStatus.Ringing;
|
||||||
this.emit('callStatusChange', status);
|
this.emit('callStatusChange', status);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
await connectStream(this.dlg.remote.sdp);
|
await connectStream(this.dlg.remote.sdp, opts.isVideoCall);
|
||||||
this.dlg.callSid = this.callSid;
|
this.dlg.callSid = this.callSid;
|
||||||
this.inviteInProgress = null;
|
this.inviteInProgress = null;
|
||||||
this.emit('callStatusChange', {
|
this.emit('callStatusChange', {
|
||||||
@@ -315,14 +327,19 @@ class SingleDialer extends Emitter {
|
|||||||
/**
|
/**
|
||||||
* kill the call in progress or the stable dialog, whichever we have
|
* kill the call in progress or the stable dialog, whichever we have
|
||||||
*/
|
*/
|
||||||
async kill() {
|
async kill(Reason) {
|
||||||
this.killed = true;
|
this.killed = true;
|
||||||
if (this.inviteInProgress) await this.inviteInProgress.cancel();
|
if (this.inviteInProgress) await this.inviteInProgress.cancel();
|
||||||
else if (this.dlg && this.dlg.connected) {
|
else if (this.dlg && this.dlg.connected) {
|
||||||
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
const duration = moment().diff(this.dlg.connectTime, 'seconds');
|
||||||
this.logger.debug('SingleDialer:kill hanging up called party');
|
this.logger.debug('SingleDialer:kill hanging up called party');
|
||||||
this.emit('callStatusChange', {callStatus: CallStatus.Completed, duration});
|
this.emit('callStatusChange', {callStatus: CallStatus.Completed, duration});
|
||||||
this.dlg.destroy();
|
const headers = {
|
||||||
|
...(Reason && {'X-Reason': Reason})
|
||||||
|
};
|
||||||
|
this.dlg.destroy({
|
||||||
|
headers
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (this.ep) {
|
if (this.ep) {
|
||||||
this.logger.debug(`SingleDialer:kill - deleting endpoint ${this.ep.uuid}`);
|
this.logger.debug(`SingleDialer:kill - deleting endpoint ${this.ep.uuid}`);
|
||||||
@@ -333,11 +350,40 @@ class SingleDialer extends Emitter {
|
|||||||
_configMsEndpoint() {
|
_configMsEndpoint() {
|
||||||
const opts = {
|
const opts = {
|
||||||
...(this.onHoldMusic && {holdMusic: `shout://${this.onHoldMusic.replace(/^https?:\/\//, '')}`}),
|
...(this.onHoldMusic && {holdMusic: `shout://${this.onHoldMusic.replace(/^https?:\/\//, '')}`}),
|
||||||
...(JAMBONES_USE_FREESWITCH_TIMER_FD && {timer_name: 'timerfd'})
|
...(JAMBONES_USE_FREESWITCH_TIMER_FD && {timer_name: 'timerfd'}),
|
||||||
|
...(JAMBONES_MEDIA_TIMEOUT_MS && {media_timeout: JAMBONES_MEDIA_TIMEOUT_MS}),
|
||||||
|
...(JAMBONES_MEDIA_HOLD_TIMEOUT_MS && {media_hold_timeout: JAMBONES_MEDIA_HOLD_TIMEOUT_MS})
|
||||||
};
|
};
|
||||||
if (Object.keys(opts).length > 0) {
|
if (Object.keys(opts).length > 0) {
|
||||||
this.ep.set(opts);
|
this.ep.set(opts);
|
||||||
}
|
}
|
||||||
|
if (this.dialTask?.inbandDtmfEnabled && !this.ep.inbandDtmfEnabled) {
|
||||||
|
// https://developer.signalwire.com/freeswitch/FreeSWITCH-Explained/Modules/mod-dptools/6587132/#0-about
|
||||||
|
try {
|
||||||
|
this.ep.execute('start_dtmf');
|
||||||
|
this.ep.inbandDtmfEnabled = true;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info(err, 'place-outdial:_configMsEndpoint - error enable inband DTMF');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const origDestroy = this.ep.destroy.bind(this.ep);
|
||||||
|
this.ep.destroy = async() => {
|
||||||
|
try {
|
||||||
|
if (this.dialTask.transcribeTask && JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS) {
|
||||||
|
// transcribe task is being used, wait for some time before destroy
|
||||||
|
// if final transcription is received but endpoint is already closed,
|
||||||
|
// freeswitch module will not be able to send the transcription
|
||||||
|
|
||||||
|
this.logger.info('SingleDialer:_configMsEndpoint -' +
|
||||||
|
' Dial with transcribe task, wait for some time before destroy');
|
||||||
|
await sleepFor(JAMBONES_TRANSCRIBE_EP_DESTROY_DELAY_MS);
|
||||||
|
}
|
||||||
|
await origDestroy();
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(err, 'SingleDialer:_configMsEndpoint - error destroying endpoint');
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -379,7 +425,8 @@ class SingleDialer extends Emitter {
|
|||||||
callInfo: this.callInfo,
|
callInfo: this.callInfo,
|
||||||
accountInfo: this.accountInfo,
|
accountInfo: this.accountInfo,
|
||||||
tasks,
|
tasks,
|
||||||
rootSpan: this.rootSpan
|
rootSpan: this.rootSpan,
|
||||||
|
req: this.req
|
||||||
});
|
});
|
||||||
await cs.exec();
|
await cs.exec();
|
||||||
|
|
||||||
@@ -388,7 +435,10 @@ class SingleDialer extends Emitter {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.debug(err, 'SingleDialer:_executeApp: error');
|
this.logger.debug(err, 'SingleDialer:_executeApp: error');
|
||||||
this.emit('decline');
|
this.emit('decline');
|
||||||
if (this.dlg.connected) this.dlg.destroy();
|
if (this.dlg.connected) {
|
||||||
|
this.dlg.destroy();
|
||||||
|
this.ep.destroy();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,6 +463,7 @@ class SingleDialer extends Emitter {
|
|||||||
const app = {...application};
|
const app = {...application};
|
||||||
if ('WS' === app.call_hook?.method ||
|
if ('WS' === app.call_hook?.method ||
|
||||||
app.call_hook?.url.startsWith('ws://') || app.call_hook?.url.startsWith('wss://')) {
|
app.call_hook?.url.startsWith('ws://') || app.call_hook?.url.startsWith('wss://')) {
|
||||||
|
if (app.call_hook?.url) app.call_hook.url += '/adulting';
|
||||||
const requestor = new WsRequestor(logger, this.accountInfo.account.account_sid,
|
const requestor = new WsRequestor(logger, this.accountInfo.account.account_sid,
|
||||||
app.call_hook, this.accountInfo.account.webhook_secret);
|
app.call_hook, this.accountInfo.account.webhook_secret);
|
||||||
app.requestor = requestor;
|
app.requestor = requestor;
|
||||||
@@ -438,26 +489,40 @@ class SingleDialer extends Emitter {
|
|||||||
tasks,
|
tasks,
|
||||||
rootSpan
|
rootSpan
|
||||||
});
|
});
|
||||||
|
app.requestor.request('session:adulting', '/adulting', {
|
||||||
|
...cs.callInfo.toJSON(),
|
||||||
|
parentCallInfo: this.parentCallInfo.toJSON()
|
||||||
|
}).catch((err) => {
|
||||||
|
newLogger.error({err}, 'doAdulting: error sending adulting request');
|
||||||
|
});
|
||||||
|
|
||||||
cs.req = this.req;
|
cs.req = this.req;
|
||||||
|
// fixed hangup an adulting session does not send status callback Completed
|
||||||
|
cs.wrapDialog(this.dlg);
|
||||||
cs.exec().catch((err) => newLogger.error({err}, 'doAdulting: error executing session'));
|
cs.exec().catch((err) => newLogger.error({err}, 'doAdulting: error executing session'));
|
||||||
return cs;
|
return cs;
|
||||||
}
|
}
|
||||||
|
|
||||||
async releaseMediaToSBC(remoteSdp, localSdp) {
|
async releaseMediaToSBC(remoteSdp, localSdp, releaseMediaEntirely) {
|
||||||
assert(this.dlg && this.dlg.connected && this.ep && typeof remoteSdp === 'string');
|
assert(this.dlg && this.dlg.connected && this.ep && typeof remoteSdp === 'string');
|
||||||
const sdp = stripCodecs(this.logger, remoteSdp, localSdp) || remoteSdp;
|
const sdp = stripCodecs(this.logger, remoteSdp, localSdp) || remoteSdp;
|
||||||
await this.dlg.modify(sdp, {
|
await this.dlg.modify(sdp, {
|
||||||
headers: {
|
headers: {
|
||||||
'X-Reason': 'release-media'
|
'X-Reason': releaseMediaEntirely ? 'release-media-entirely' : 'release-media'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.ep.destroy()
|
try {
|
||||||
.then(() => this.ep = null)
|
await this.ep.destroy();
|
||||||
.catch((err) => this.logger.error({err}, 'SingleDialer:releaseMediaToSBC: Error destroying endpoint'));
|
} catch (err) {
|
||||||
|
this.logger.error({err}, 'SingleDialer:releaseMediaToSBC: Error destroying endpoint');
|
||||||
|
}
|
||||||
|
this.ep = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async reAnchorMedia() {
|
async reAnchorMedia(currentMediaRoute = MediaPath.PartialMedia) {
|
||||||
assert(this.dlg && this.dlg.connected && !this.ep);
|
assert(this.dlg && this.dlg.connected && !this.ep);
|
||||||
|
|
||||||
|
this.logger.debug('SingleDialer:reAnchorMedia: re-anchoring media after partial media');
|
||||||
this.ep = await this.ms.createEndpoint({remoteSdp: this.dlg.remote.sdp});
|
this.ep = await this.ms.createEndpoint({remoteSdp: this.dlg.remote.sdp});
|
||||||
this._configMsEndpoint();
|
this._configMsEndpoint();
|
||||||
await this.dlg.modify(this.ep.local.sdp, {
|
await this.dlg.modify(this.ep.local.sdp, {
|
||||||
@@ -465,6 +530,11 @@ class SingleDialer extends Emitter {
|
|||||||
'X-Reason': 'anchor-media'
|
'X-Reason': 'anchor-media'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (currentMediaRoute === MediaPath.NoMedia) {
|
||||||
|
this.logger.debug('SingleDialer:reAnchorMedia: repoint endpoint after no media');
|
||||||
|
await this.ep.modify(this.dlg.remote.sdp);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_notifyCallStatusChange({callStatus, sipStatus, sipReason, duration}) {
|
_notifyCallStatusChange({callStatus, sipStatus, sipReason, duration}) {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const {
|
|||||||
JAMBONES_SBCS,
|
JAMBONES_SBCS,
|
||||||
K8S,
|
K8S,
|
||||||
K8S_SBC_SIP_SERVICE_NAME,
|
K8S_SBC_SIP_SERVICE_NAME,
|
||||||
AWS_SNS_TOPIC_ARM,
|
AWS_SNS_TOPIC_ARN,
|
||||||
OPTIONS_PING_INTERVAL,
|
OPTIONS_PING_INTERVAL,
|
||||||
AWS_REGION,
|
AWS_REGION,
|
||||||
NODE_ENV,
|
NODE_ENV,
|
||||||
@@ -35,7 +35,7 @@ module.exports = (logger) => {
|
|||||||
// listen for SNS lifecycle changes
|
// listen for SNS lifecycle changes
|
||||||
let lifecycleEmitter = new Emitter();
|
let lifecycleEmitter = new Emitter();
|
||||||
let dryUpCalls = false;
|
let dryUpCalls = false;
|
||||||
if (AWS_SNS_TOPIC_ARM && AWS_REGION) {
|
if (AWS_SNS_TOPIC_ARN && AWS_REGION) {
|
||||||
|
|
||||||
(async function() {
|
(async function() {
|
||||||
try {
|
try {
|
||||||
@@ -46,12 +46,24 @@ module.exports = (logger) => {
|
|||||||
const {srf} = require('../..');
|
const {srf} = require('../..');
|
||||||
srf.locals.publicIp = publicIp;
|
srf.locals.publicIp = publicIp;
|
||||||
})
|
})
|
||||||
.on(LifeCycleEvents.ScaleIn, () => {
|
.on(LifeCycleEvents.ScaleIn, async() => {
|
||||||
logger.info('AWS scale-in notification: begin drying up calls');
|
logger.info('AWS scale-in notification: begin drying up calls');
|
||||||
dryUpCalls = true;
|
dryUpCalls = true;
|
||||||
lifecycleEmitter.operationalState = LifeCycleEvents.ScaleIn;
|
lifecycleEmitter.operationalState = LifeCycleEvents.ScaleIn;
|
||||||
|
|
||||||
const {srf} = require('../..');
|
const {srf} = require('../..');
|
||||||
|
const {writeSystemAlerts} = srf.locals;
|
||||||
|
if (writeSystemAlerts) {
|
||||||
|
const {SystemState, FEATURE_SERVER} = require('./constants');
|
||||||
|
await writeSystemAlerts({
|
||||||
|
system_component: FEATURE_SERVER,
|
||||||
|
state : SystemState.GracefulShutdownInProgress,
|
||||||
|
fields : {
|
||||||
|
detail: `feature-server with process_id ${process.pid} shutdown in progress`,
|
||||||
|
host: srf.locals?.ipv4
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
pingProxies(srf);
|
pingProxies(srf);
|
||||||
|
|
||||||
// if we have zero calls, we can complete the scale-in right
|
// if we have zero calls, we can complete the scale-in right
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ const makeOpusFirst = (sdp) => {
|
|||||||
}
|
}
|
||||||
return sdpTransform.write(parsedSdp);
|
return sdpTransform.write(parsedSdp);
|
||||||
};
|
};
|
||||||
|
const removeVideoSdp = (sdp) => {
|
||||||
|
const parsedSdp = sdpTransform.parse(sdp);
|
||||||
|
// Filter out video media sections, keeping only non-video media
|
||||||
|
parsedSdp.media = parsedSdp.media.filter((media) => media.type !== 'video');
|
||||||
|
return sdpTransform.write(parsedSdp);
|
||||||
|
};
|
||||||
|
|
||||||
const extractSdpMedia = (sdp) => {
|
const extractSdpMedia = (sdp) => {
|
||||||
const parsedSdp1 = sdpTransform.parse(sdp);
|
const parsedSdp1 = sdpTransform.parse(sdp);
|
||||||
@@ -54,5 +60,6 @@ module.exports = {
|
|||||||
mergeSdpMedia,
|
mergeSdpMedia,
|
||||||
extractSdpMedia,
|
extractSdpMedia,
|
||||||
isOpusFirst,
|
isOpusFirst,
|
||||||
makeOpusFirst
|
makeOpusFirst,
|
||||||
|
removeVideoSdp
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
const {
|
const {TaskName} = require('./constants.json');
|
||||||
TaskName,
|
|
||||||
} = require('./constants.json');
|
|
||||||
|
|
||||||
const stickyVars = {
|
const stickyVars = {
|
||||||
google: [
|
google: [
|
||||||
'GOOGLE_SPEECH_HINTS',
|
'GOOGLE_SPEECH_HINTS',
|
||||||
@@ -33,6 +30,7 @@ const stickyVars = {
|
|||||||
'DEEPGRAM_SPEECH_TIER',
|
'DEEPGRAM_SPEECH_TIER',
|
||||||
'DEEPGRAM_SPEECH_MODEL',
|
'DEEPGRAM_SPEECH_MODEL',
|
||||||
'DEEPGRAM_SPEECH_ENABLE_SMART_FORMAT',
|
'DEEPGRAM_SPEECH_ENABLE_SMART_FORMAT',
|
||||||
|
'DEEPGRAM_SPEECH_ENABLE_NO_DELAY',
|
||||||
'DEEPGRAM_SPEECH_ENABLE_AUTOMATIC_PUNCTUATION',
|
'DEEPGRAM_SPEECH_ENABLE_AUTOMATIC_PUNCTUATION',
|
||||||
'DEEPGRAM_SPEECH_PROFANITY_FILTER',
|
'DEEPGRAM_SPEECH_PROFANITY_FILTER',
|
||||||
'DEEPGRAM_SPEECH_REDACT',
|
'DEEPGRAM_SPEECH_REDACT',
|
||||||
@@ -45,12 +43,21 @@ const stickyVars = {
|
|||||||
'DEEPGRAM_SPEECH_ENDPOINTING',
|
'DEEPGRAM_SPEECH_ENDPOINTING',
|
||||||
'DEEPGRAM_SPEECH_UTTERANCE_END_MS',
|
'DEEPGRAM_SPEECH_UTTERANCE_END_MS',
|
||||||
'DEEPGRAM_SPEECH_VAD_TURNOFF',
|
'DEEPGRAM_SPEECH_VAD_TURNOFF',
|
||||||
'DEEPGRAM_SPEECH_TAG'
|
'DEEPGRAM_SPEECH_TAG',
|
||||||
|
'DEEPGRAM_SPEECH_MODEL_VERSION',
|
||||||
|
'DEEPGRAM_SPEECH_FILLER_WORDS',
|
||||||
|
'DEEPGRAM_SPEECH_KEYTERMS',
|
||||||
],
|
],
|
||||||
aws: [
|
aws: [
|
||||||
'AWS_VOCABULARY_NAME',
|
'AWS_VOCABULARY_NAME',
|
||||||
'AWS_VOCABULARY_FILTER_METHOD',
|
'AWS_VOCABULARY_FILTER_METHOD',
|
||||||
'AWS_VOCABULARY_FILTER_NAME'
|
'AWS_VOCABULARY_FILTER_NAME',
|
||||||
|
'AWS_LANGUAGE_MODEL_NAME',
|
||||||
|
'AWS_ACCESS_KEY_ID',
|
||||||
|
'AWS_SECRET_ACCESS_KEY',
|
||||||
|
'AWS_REGION',
|
||||||
|
'AWS_SECURITY_TOKEN',
|
||||||
|
'AWS_PII_ENTITY_TYPES',
|
||||||
],
|
],
|
||||||
nuance: [
|
nuance: [
|
||||||
'NUANCE_ACCESS_TOKEN',
|
'NUANCE_ACCESS_TOKEN',
|
||||||
@@ -99,7 +106,27 @@ const stickyVars = {
|
|||||||
assemblyai: [
|
assemblyai: [
|
||||||
'ASSEMBLYAI_API_KEY',
|
'ASSEMBLYAI_API_KEY',
|
||||||
'ASSEMBLYAI_WORD_BOOST'
|
'ASSEMBLYAI_WORD_BOOST'
|
||||||
]
|
],
|
||||||
|
voxist: [
|
||||||
|
'VOXIST_API_KEY',
|
||||||
|
],
|
||||||
|
speechmatics: [
|
||||||
|
'SPEECHMATICS_API_KEY',
|
||||||
|
'SPEECHMATICS_HOST',
|
||||||
|
'SPEECHMATICS_PATH',
|
||||||
|
'SPEECHMATICS_SPEECH_HINTS',
|
||||||
|
'SPEECHMATICS_TRANSLATION_LANGUAGES',
|
||||||
|
'SPEECHMATICS_TRANSLATION_PARTIALS'
|
||||||
|
],
|
||||||
|
openai: [
|
||||||
|
'OPENAI_API_KEY',
|
||||||
|
'OPENAI_MODEL',
|
||||||
|
'OPENAI_INPUT_AUDIO_NOISE_REDUCTION',
|
||||||
|
'OPENAI_TURN_DETECTION_TYPE',
|
||||||
|
'OPENAI_TURN_DETECTION_THRESHOLD',
|
||||||
|
'OPENAI_TURN_DETECTION_PREFIX_PADDING_MS',
|
||||||
|
'OPENAI_TURN_DETECTION_SILENCE_DURATION_MS',
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -141,7 +168,6 @@ const optimalDeepramModels = {
|
|||||||
tr: ['nova-2', 'nova-2'],
|
tr: ['nova-2', 'nova-2'],
|
||||||
uk: ['nova-2', 'nova-2']
|
uk: ['nova-2', 'nova-2']
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectDefaultDeepgramModel = (task, language) => {
|
const selectDefaultDeepgramModel = (task, language) => {
|
||||||
if (language in optimalDeepramModels) {
|
if (language in optimalDeepramModels) {
|
||||||
const [gather, transcribe] = optimalDeepramModels[language];
|
const [gather, transcribe] = optimalDeepramModels[language];
|
||||||
@@ -150,8 +176,34 @@ const selectDefaultDeepgramModel = (task, language) => {
|
|||||||
return 'base';
|
return 'base';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const optimalGoogleModels = {
|
||||||
|
'v1' : {
|
||||||
|
'en-IN':['telephony', 'telephony'],
|
||||||
|
'es-DO':['default', 'default'],
|
||||||
|
'es-MX':['default', 'default'],
|
||||||
|
'en-AU':['telephony', 'telephony'],
|
||||||
|
'en-GB':['telephony', 'telephony'],
|
||||||
|
'en-NZ':['telephony', 'telephony']
|
||||||
|
},
|
||||||
|
'v2' : {
|
||||||
|
'en-IN':['telephony', 'long']
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const selectDefaultGoogleModel = (task, language, version) => {
|
||||||
|
const useV2 = version === 'v2';
|
||||||
|
if (language in optimalGoogleModels[version]) {
|
||||||
|
const [gather, transcribe] = optimalGoogleModels[version][language];
|
||||||
|
return task.name === TaskName.Gather ? gather : transcribe;
|
||||||
|
}
|
||||||
|
return task.name === TaskName.Gather ?
|
||||||
|
(useV2 ? 'telephony_short' : 'command_and_search') :
|
||||||
|
(useV2 ? 'long' : 'latest_long');
|
||||||
|
};
|
||||||
const consolidateTranscripts = (bufferedTranscripts, channel, language, vendor) => {
|
const consolidateTranscripts = (bufferedTranscripts, channel, language, vendor) => {
|
||||||
if (bufferedTranscripts.length === 1) return bufferedTranscripts[0];
|
if (bufferedTranscripts.length === 1) {
|
||||||
|
bufferedTranscripts[0].is_final = true;
|
||||||
|
return bufferedTranscripts[0];
|
||||||
|
}
|
||||||
let totalConfidence = 0;
|
let totalConfidence = 0;
|
||||||
const finalTranscript = bufferedTranscripts.reduce((acc, evt) => {
|
const finalTranscript = bufferedTranscripts.reduce((acc, evt) => {
|
||||||
totalConfidence += evt.alternatives[0].confidence;
|
totalConfidence += evt.alternatives[0].confidence;
|
||||||
@@ -171,7 +223,7 @@ const consolidateTranscripts = (bufferedTranscripts, channel, language, vendor)
|
|||||||
const lastChar = acc.alternatives[0].transcript.slice(-1);
|
const lastChar = acc.alternatives[0].transcript.slice(-1);
|
||||||
const firstChar = newTranscript.charAt(0);
|
const firstChar = newTranscript.charAt(0);
|
||||||
|
|
||||||
if (lastChar.match(/\d/) && firstChar.match(/\d/)) {
|
if (vendor === 'speechmatics' || (lastChar.match(/\d/) && firstChar.match(/\d/))) {
|
||||||
acc.alternatives[0].transcript += newTranscript;
|
acc.alternatives[0].transcript += newTranscript;
|
||||||
} else {
|
} else {
|
||||||
acc.alternatives[0].transcript += ` ${newTranscript}`;
|
acc.alternatives[0].transcript += ` ${newTranscript}`;
|
||||||
@@ -261,16 +313,21 @@ const normalizeDeepgram = (evt, channel, language, shortUtterance) => {
|
|||||||
confidence: alt.confidence,
|
confidence: alt.confidence,
|
||||||
transcript: alt.transcript,
|
transcript: alt.transcript,
|
||||||
}));
|
}));
|
||||||
|
/**
|
||||||
|
* Some models (nova-2-general) return the detected language in the
|
||||||
|
* alternatives.languages array if the language is set as multi.
|
||||||
|
* If the language is detected, we use it as the language_code.
|
||||||
|
*/
|
||||||
|
const detectedLanguage = evt.channel?.alternatives?.[0]?.languages?.[0];
|
||||||
/**
|
/**
|
||||||
* note difference between is_final and speech_final in Deepgram:
|
* note difference between is_final and speech_final in Deepgram:
|
||||||
* https://developers.deepgram.com/docs/understand-endpointing-interim-results
|
* https://developers.deepgram.com/docs/understand-endpointing-interim-results
|
||||||
*/
|
*/
|
||||||
return {
|
return {
|
||||||
language_code: language,
|
language_code: detectedLanguage || language,
|
||||||
channel_tag: channel,
|
channel_tag: channel,
|
||||||
is_final: shortUtterance ? evt.is_final : evt.speech_final,
|
is_final: shortUtterance ? evt.is_final : evt.speech_final,
|
||||||
alternatives: [alternatives[0]],
|
alternatives: alternatives.length ? [alternatives[0]] : [],
|
||||||
vendor: {
|
vendor: {
|
||||||
name: 'deepgram',
|
name: 'deepgram',
|
||||||
evt: copy
|
evt: copy
|
||||||
@@ -316,8 +373,10 @@ const normalizeIbm = (evt, channel, language) => {
|
|||||||
|
|
||||||
const normalizeGoogle = (evt, channel, language) => {
|
const normalizeGoogle = (evt, channel, language) => {
|
||||||
const copy = JSON.parse(JSON.stringify(evt));
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
|
const language_code = evt.language_code || language;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
language_code: language,
|
language_code: language_code,
|
||||||
channel_tag: channel,
|
channel_tag: channel,
|
||||||
is_final: evt.is_final,
|
is_final: evt.is_final,
|
||||||
alternatives: [evt.alternatives[0]],
|
alternatives: [evt.alternatives[0]],
|
||||||
@@ -376,6 +435,20 @@ const normalizeNuance = (evt, channel, language) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeVerbio = (evt, channel, language) => {
|
||||||
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
|
return {
|
||||||
|
language_code: language,
|
||||||
|
channel_tag: channel,
|
||||||
|
is_final: evt.is_final,
|
||||||
|
alternatives: evt.alternatives,
|
||||||
|
vendor: {
|
||||||
|
name: 'verbio',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const normalizeMicrosoft = (evt, channel, language, punctuation = true) => {
|
const normalizeMicrosoft = (evt, channel, language, punctuation = true) => {
|
||||||
const copy = JSON.parse(JSON.stringify(evt));
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
const nbest = evt.NBest;
|
const nbest = evt.NBest;
|
||||||
@@ -407,16 +480,41 @@ const normalizeMicrosoft = (evt, channel, language, punctuation = true) => {
|
|||||||
|
|
||||||
const normalizeAws = (evt, channel, language) => {
|
const normalizeAws = (evt, channel, language) => {
|
||||||
const copy = JSON.parse(JSON.stringify(evt));
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
return {
|
const isGrpcPayload = Array.isArray(evt);
|
||||||
language_code: language,
|
if (isGrpcPayload) {
|
||||||
channel_tag: channel,
|
/* legacy grpc api */
|
||||||
is_final: evt[0].is_final,
|
return {
|
||||||
alternatives: evt[0].alternatives,
|
language_code: language,
|
||||||
vendor: {
|
channel_tag: channel,
|
||||||
name: 'aws',
|
is_final: evt[0].is_final,
|
||||||
evt: copy
|
alternatives: evt[0].alternatives,
|
||||||
}
|
vendor: {
|
||||||
};
|
name: 'aws',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* websocket api */
|
||||||
|
const alternatives = evt.Transcript?.Results[0]?.Alternatives.map((alt) => {
|
||||||
|
const items = alt.Items.filter((item) => item.Type === 'pronunciation' && 'Confidence' in item);
|
||||||
|
const confidence = items.reduce((acc, item) => acc + item.Confidence, 0) / items.length;
|
||||||
|
return {
|
||||||
|
transcript: alt.Transcript,
|
||||||
|
confidence
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
language_code: language,
|
||||||
|
channel_tag: channel,
|
||||||
|
is_final: evt.Transcript?.Results[0].IsPartial === false,
|
||||||
|
alternatives,
|
||||||
|
vendor: {
|
||||||
|
name: 'aws',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const normalizeAssemblyAi = (evt, channel, language) => {
|
const normalizeAssemblyAi = (evt, channel, language) => {
|
||||||
@@ -432,12 +530,85 @@ const normalizeAssemblyAi = (evt, channel, language) => {
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
vendor: {
|
vendor: {
|
||||||
name: 'ASSEMBLYAI',
|
name: 'assemblyai',
|
||||||
evt: copy
|
evt: copy
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeVoxist = (evt, channel, language) => {
|
||||||
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
|
return {
|
||||||
|
language_code: language,
|
||||||
|
channel_tag: channel,
|
||||||
|
is_final: evt.type === 'final',
|
||||||
|
alternatives: [
|
||||||
|
{
|
||||||
|
confidence: 1.00,
|
||||||
|
transcript: evt.text,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
vendor: {
|
||||||
|
name: 'voxist',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeSpeechmatics = (evt, channel, language) => {
|
||||||
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
|
const is_final = evt.message === 'AddTranscript';
|
||||||
|
const words = evt.results?.filter((r) => r.type === 'word') || [];
|
||||||
|
const confidence = words.length > 0 ?
|
||||||
|
words.reduce((acc, word) => acc + word.alternatives[0].confidence, 0) / words.length :
|
||||||
|
0;
|
||||||
|
|
||||||
|
const alternative = {
|
||||||
|
confidence,
|
||||||
|
transcript: evt.metadata?.transcript
|
||||||
|
};
|
||||||
|
const obj = {
|
||||||
|
language_code: language,
|
||||||
|
channel_tag: channel,
|
||||||
|
is_final,
|
||||||
|
alternatives: [alternative],
|
||||||
|
vendor: {
|
||||||
|
name: 'speechmatics',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return obj;
|
||||||
|
};
|
||||||
|
|
||||||
|
const calculateConfidence = (logprobsArray) => {
|
||||||
|
// Sum the individual log probabilities
|
||||||
|
const totalLogProb = logprobsArray.reduce((sum, tokenInfo) => sum + tokenInfo.logprob, 0);
|
||||||
|
|
||||||
|
// Convert the total log probability back to a regular probability
|
||||||
|
const confidence = Math.exp(totalLogProb);
|
||||||
|
return confidence;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeOpenAI = (evt, channel, language) => {
|
||||||
|
const copy = JSON.parse(JSON.stringify(evt));
|
||||||
|
const obj = {
|
||||||
|
language_code: language,
|
||||||
|
channel_tag: channel,
|
||||||
|
is_final: true,
|
||||||
|
alternatives: [
|
||||||
|
{
|
||||||
|
transcript: evt.transcript,
|
||||||
|
confidence: evt.logprobs ? calculateConfidence(evt.logprobs) : 1.0,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
vendor: {
|
||||||
|
name: 'openai',
|
||||||
|
evt: copy
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return obj;
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = (logger) => {
|
module.exports = (logger) => {
|
||||||
const normalizeTranscription = (evt, vendor, channel, language, shortUtterance, punctuation) => {
|
const normalizeTranscription = (evt, vendor, channel, language, shortUtterance, punctuation) => {
|
||||||
|
|
||||||
@@ -463,6 +634,14 @@ module.exports = (logger) => {
|
|||||||
return normalizeCobalt(evt, channel, language);
|
return normalizeCobalt(evt, channel, language);
|
||||||
case 'assemblyai':
|
case 'assemblyai':
|
||||||
return normalizeAssemblyAi(evt, channel, language, shortUtterance);
|
return normalizeAssemblyAi(evt, channel, language, shortUtterance);
|
||||||
|
case 'voxist':
|
||||||
|
return normalizeVoxist(evt, channel, language);
|
||||||
|
case 'verbio':
|
||||||
|
return normalizeVerbio(evt, channel, language);
|
||||||
|
case 'speechmatics':
|
||||||
|
return normalizeSpeechmatics(evt, channel, language);
|
||||||
|
case 'openai':
|
||||||
|
return normalizeOpenAI(evt, channel, language);
|
||||||
default:
|
default:
|
||||||
if (vendor.startsWith('custom:')) {
|
if (vendor.startsWith('custom:')) {
|
||||||
return normalizeCustom(evt, channel, language, vendor);
|
return normalizeCustom(evt, channel, language, vendor);
|
||||||
@@ -474,27 +653,13 @@ module.exports = (logger) => {
|
|||||||
|
|
||||||
const setChannelVarsForStt = (task, sttCredentials, language, rOpts = {}) => {
|
const setChannelVarsForStt = (task, sttCredentials, language, rOpts = {}) => {
|
||||||
let opts = {};
|
let opts = {};
|
||||||
const {enable, voiceMs = 0, mode = -1} = rOpts.vad || {};
|
|
||||||
const vad = {enable, voiceMs, mode};
|
|
||||||
const vendor = rOpts.vendor;
|
const vendor = rOpts.vendor;
|
||||||
|
|
||||||
/* voice activity detection works across vendors */
|
|
||||||
opts = {
|
|
||||||
...opts,
|
|
||||||
...(vad.enable && {START_RECOGNIZING_ON_VAD: 1}),
|
|
||||||
...(vad.enable && vad.voiceMs && {RECOGNIZER_VAD_VOICE_MS: vad.voiceMs}),
|
|
||||||
...(vad.enable && typeof vad.mode === 'number' && {RECOGNIZER_VAD_MODE: vad.mode}),
|
|
||||||
};
|
|
||||||
|
|
||||||
if ('google' === vendor) {
|
if ('google' === vendor) {
|
||||||
const model = task.name === TaskName.Gather ? 'command_and_search' : 'latest_long';
|
const useV2 = rOpts.googleOptions?.serviceVersion === 'v2';
|
||||||
/**
|
const version = useV2 ? 'v2' : 'v1';
|
||||||
* When we support google v2 the models are different and we will want something like:
|
let {model} = rOpts;
|
||||||
* const useV2 = sttCredentials?.credentials?.project_id; //TODO: v2 pref should be set in googleOptions
|
model = model || selectDefaultGoogleModel(task, language, version);
|
||||||
* const model = task.name === TaskName.Gather ?
|
|
||||||
* (useV2 ? 'telephony_short' : 'command_and_search') :
|
|
||||||
* (useV2 ? 'long' : 'latest_long');
|
|
||||||
*/
|
|
||||||
opts = {
|
opts = {
|
||||||
...opts,
|
...opts,
|
||||||
...(sttCredentials && {GOOGLE_APPLICATION_CREDENTIALS: JSON.stringify(sttCredentials.credentials)}),
|
...(sttCredentials && {GOOGLE_APPLICATION_CREDENTIALS: JSON.stringify(sttCredentials.credentials)}),
|
||||||
@@ -527,25 +692,52 @@ module.exports = (logger) => {
|
|||||||
...{GOOGLE_SPEECH_MODEL: rOpts.model || model},
|
...{GOOGLE_SPEECH_MODEL: rOpts.model || model},
|
||||||
...(rOpts.naicsCode > 0 && {GOOGLE_SPEECH_METADATA_INDUSTRY_NAICS_CODE: rOpts.naicsCode}),
|
...(rOpts.naicsCode > 0 && {GOOGLE_SPEECH_METADATA_INDUSTRY_NAICS_CODE: rOpts.naicsCode}),
|
||||||
GOOGLE_SPEECH_METADATA_RECORDING_DEVICE_TYPE: 'phone_line',
|
GOOGLE_SPEECH_METADATA_RECORDING_DEVICE_TYPE: 'phone_line',
|
||||||
/*
|
|
||||||
...(useV2 && {
|
...(useV2 && {
|
||||||
GOOGLE_SPEECH_RECOGNIZER_PARENT: `projects/${sttCredentials.credentials.project_id}/locations/global`,
|
GOOGLE_SPEECH_RECOGNIZER_PARENT: `projects/${sttCredentials.credentials.project_id}/locations/global`,
|
||||||
GOOGLE_SPEECH_CLOUD_SERVICES_VERSION: 'v2'
|
GOOGLE_SPEECH_CLOUD_SERVICES_VERSION: 'v2',
|
||||||
}),
|
...(rOpts.googleOptions?.speechStartTimeoutMs && {
|
||||||
*/
|
GOOGLE_SPEECH_START_TIMEOUT_MS: rOpts.googleOptions.speechStartTimeoutMs
|
||||||
|
}),
|
||||||
|
...(rOpts.googleOptions?.speechEndTimeoutMs && {
|
||||||
|
GOOGLE_SPEECH_END_TIMEOUT_MS: rOpts.googleOptions.speechEndTimeoutMs
|
||||||
|
}),
|
||||||
|
...(rOpts.googleOptions?.transcriptNormalization && {
|
||||||
|
GOOGLE_SPEECH_TRANSCRIPTION_NORMALIZATION: JSON.stringify(rOpts.googleOptions.transcriptNormalization)
|
||||||
|
}),
|
||||||
|
...(rOpts.googleOptions?.enableVoiceActivityEvents && {
|
||||||
|
GOOGLE_SPEECH_ENABLE_VOICE_ACTIVITY_EVENTS: rOpts.googleOptions.enableVoiceActivityEvents
|
||||||
|
}),
|
||||||
|
...(rOpts.sgoogleOptions?.recognizerId) && {GOOGLE_SPEECH_RECOGNIZER_ID: rOpts.googleOptions.recognizerId},
|
||||||
|
...(rOpts.googleOptions?.enableVoiceActivityEvents && {
|
||||||
|
GOOGLE_SPEECH_ENABLE_VOICE_ACTIVITY_EVENTS: rOpts.googleOptions.enableVoiceActivityEvents
|
||||||
|
}),
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if (['aws', 'polly'].includes(vendor)) {
|
else if (['aws', 'polly'].includes(vendor)) {
|
||||||
|
const {awsOptions = {}} = rOpts;
|
||||||
|
const vocabularyName = awsOptions.vocabularyName || rOpts.vocabularyName;
|
||||||
|
const vocabularyFilterName = awsOptions.vocabularyFilterName || rOpts.vocabularyFilterName;
|
||||||
|
const filterMethod = awsOptions.vocabularyFilterMethod || rOpts.filterMethod;
|
||||||
opts = {
|
opts = {
|
||||||
...opts,
|
...opts,
|
||||||
...(rOpts.vocabularyName && {AWS_VOCABULARY_NAME: rOpts.vocabularyName}),
|
...(vocabularyName && {AWS_VOCABULARY_NAME: vocabularyName}),
|
||||||
...(rOpts.vocabularyFilterName && {AWS_VOCABULARY_FILTER_NAME: rOpts.vocabularyFilterName}),
|
...(vocabularyFilterName && {AWS_VOCABULARY_FILTER_NAME: vocabularyFilterName}),
|
||||||
...(rOpts.filterMethod && {AWS_VOCABULARY_FILTER_METHOD: rOpts.filterMethod}),
|
...(filterMethod && {AWS_VOCABULARY_FILTER_METHOD: filterMethod}),
|
||||||
...(sttCredentials && {
|
...(sttCredentials && {
|
||||||
AWS_ACCESS_KEY_ID: sttCredentials.accessKeyId,
|
AWS_ACCESS_KEY_ID: sttCredentials.accessKeyId,
|
||||||
AWS_SECRET_ACCESS_KEY: sttCredentials.secretAccessKey,
|
AWS_SECRET_ACCESS_KEY: sttCredentials.secretAccessKey,
|
||||||
AWS_REGION: sttCredentials.region
|
AWS_REGION: sttCredentials.region,
|
||||||
|
AWS_SECURITY_TOKEN: sttCredentials.securityToken
|
||||||
}),
|
}),
|
||||||
|
...(awsOptions.accessKey && {AWS_ACCESS_KEY_ID: awsOptions.accessKey}),
|
||||||
|
...(awsOptions.secretKey && {AWS_SECRET_ACCESS_KEY: awsOptions.secretKey}),
|
||||||
|
...(awsOptions.region && {AWS_REGION: awsOptions.region}),
|
||||||
|
...(awsOptions.securityToken && {AWS_SECURITY_TOKEN: awsOptions.securityToken}),
|
||||||
|
...(awsOptions.languageModelName && {AWS_LANGUAGE_MODEL_NAME: awsOptions.languageModelName}),
|
||||||
|
...(awsOptions.piiEntityTypes?.length && {AWS_PII_ENTITY_TYPES: awsOptions.piiEntityTypes.join(',')}),
|
||||||
|
...(awsOptions.piiIdentifyEntities && {AWS_PII_IDENTIFY_ENTITIES: true}),
|
||||||
|
...(awsOptions.languageModelName && {AWS_LANGUAGE_MODEL_NAME: awsOptions.languageModelName}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if ('microsoft' === vendor) {
|
else if ('microsoft' === vendor) {
|
||||||
@@ -573,6 +765,8 @@ module.exports = (logger) => {
|
|||||||
{AZURE_SPEECH_SEGMENTATION_SILENCE_TIMEOUT_MS: azureOptions.speechSegmentationSilenceTimeoutMs}),
|
{AZURE_SPEECH_SEGMENTATION_SILENCE_TIMEOUT_MS: azureOptions.speechSegmentationSilenceTimeoutMs}),
|
||||||
...(azureOptions.languageIdMode &&
|
...(azureOptions.languageIdMode &&
|
||||||
{AZURE_LANGUAGE_ID_MODE: azureOptions.languageIdMode}),
|
{AZURE_LANGUAGE_ID_MODE: azureOptions.languageIdMode}),
|
||||||
|
...(azureOptions.postProcessing &&
|
||||||
|
{AZURE_POST_PROCESSING_OPTION: azureOptions.postProcessing}),
|
||||||
...(sttCredentials && {
|
...(sttCredentials && {
|
||||||
...(sttCredentials.api_key && {AZURE_SUBSCRIPTION_KEY: sttCredentials.api_key}),
|
...(sttCredentials.api_key && {AZURE_SUBSCRIPTION_KEY: sttCredentials.api_key}),
|
||||||
...(sttCredentials.region && {AZURE_REGION: sttCredentials.region}),
|
...(sttCredentials.region && {AZURE_REGION: sttCredentials.region}),
|
||||||
@@ -582,6 +776,8 @@ module.exports = (logger) => {
|
|||||||
//azureSttEndpointId overrides sttCredentials.custom_stt_endpoint
|
//azureSttEndpointId overrides sttCredentials.custom_stt_endpoint
|
||||||
...(rOpts.azureSttEndpointId &&
|
...(rOpts.azureSttEndpointId &&
|
||||||
{AZURE_SERVICE_ENDPOINT_ID: rOpts.azureSttEndpointId}),
|
{AZURE_SERVICE_ENDPOINT_ID: rOpts.azureSttEndpointId}),
|
||||||
|
...(azureOptions.speechRecognitionMode &&
|
||||||
|
{AZURE_RECOGNITION_MODE: azureOptions.speechRecognitionMode}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if ('nuance' === vendor) {
|
else if ('nuance' === vendor) {
|
||||||
@@ -633,7 +829,7 @@ module.exports = (logger) => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if ('deepgram' === vendor) {
|
else if ('deepgram' === vendor) {
|
||||||
let {model} = rOpts;
|
let model = rOpts.deepgramOptions?.model || rOpts.model;
|
||||||
const {deepgramOptions = {}} = rOpts;
|
const {deepgramOptions = {}} = rOpts;
|
||||||
const deepgramUri = deepgramOptions.deepgramSttUri || sttCredentials.deepgram_stt_uri;
|
const deepgramUri = deepgramOptions.deepgramSttUri || sttCredentials.deepgram_stt_uri;
|
||||||
const useTls = deepgramOptions.deepgramSttUseTls || sttCredentials.deepgram_stt_use_tls;
|
const useTls = deepgramOptions.deepgramSttUseTls || sttCredentials.deepgram_stt_use_tls;
|
||||||
@@ -655,6 +851,8 @@ module.exports = (logger) => {
|
|||||||
{DEEPGRAM_SPEECH_ENABLE_AUTOMATIC_PUNCTUATION: 1},
|
{DEEPGRAM_SPEECH_ENABLE_AUTOMATIC_PUNCTUATION: 1},
|
||||||
...(deepgramOptions.smartFormatting) &&
|
...(deepgramOptions.smartFormatting) &&
|
||||||
{DEEPGRAM_SPEECH_ENABLE_SMART_FORMAT: 1},
|
{DEEPGRAM_SPEECH_ENABLE_SMART_FORMAT: 1},
|
||||||
|
...(deepgramOptions.noDelay) &&
|
||||||
|
{DEEPGRAM_SPEECH_ENABLE_NO_DELAY: 1},
|
||||||
...(deepgramOptions.profanityFilter) &&
|
...(deepgramOptions.profanityFilter) &&
|
||||||
{DEEPGRAM_SPEECH_PROFANITY_FILTER: 1},
|
{DEEPGRAM_SPEECH_PROFANITY_FILTER: 1},
|
||||||
...(deepgramOptions.redact) &&
|
...(deepgramOptions.redact) &&
|
||||||
@@ -680,13 +878,21 @@ module.exports = (logger) => {
|
|||||||
...(deepgramOptions.keywords) &&
|
...(deepgramOptions.keywords) &&
|
||||||
{DEEPGRAM_SPEECH_KEYWORDS: deepgramOptions.keywords.join(',')},
|
{DEEPGRAM_SPEECH_KEYWORDS: deepgramOptions.keywords.join(',')},
|
||||||
...('endpointing' in deepgramOptions) &&
|
...('endpointing' in deepgramOptions) &&
|
||||||
{DEEPGRAM_SPEECH_ENDPOINTING: deepgramOptions.endpointing === false ? 'false' : deepgramOptions.endpointing},
|
{DEEPGRAM_SPEECH_ENDPOINTING: deepgramOptions.endpointing === false ? 'false' : deepgramOptions.endpointing,
|
||||||
|
// default DEEPGRAM_SPEECH_UTTERANCE_END_MS is 1000, will be override by user settings later if there is.
|
||||||
|
DEEPGRAM_SPEECH_UTTERANCE_END_MS: 1000},
|
||||||
...(deepgramOptions.utteranceEndMs) &&
|
...(deepgramOptions.utteranceEndMs) &&
|
||||||
{DEEPGRAM_SPEECH_UTTERANCE_END_MS: deepgramOptions.utteranceEndMs},
|
{DEEPGRAM_SPEECH_UTTERANCE_END_MS: deepgramOptions.utteranceEndMs},
|
||||||
...(deepgramOptions.vadTurnoff) &&
|
...(deepgramOptions.vadTurnoff) &&
|
||||||
{DEEPGRAM_SPEECH_VAD_TURNOFF: deepgramOptions.vadTurnoff},
|
{DEEPGRAM_SPEECH_VAD_TURNOFF: deepgramOptions.vadTurnoff},
|
||||||
...(deepgramOptions.tag) &&
|
...(deepgramOptions.tag) &&
|
||||||
{DEEPGRAM_SPEECH_TAG: deepgramOptions.tag}
|
{DEEPGRAM_SPEECH_TAG: deepgramOptions.tag},
|
||||||
|
...(deepgramOptions.version) &&
|
||||||
|
{DEEPGRAM_SPEECH_MODEL_VERSION: deepgramOptions.version},
|
||||||
|
...(deepgramOptions.fillerWords) &&
|
||||||
|
{DEEPGRAM_SPEECH_FILLER_WORDS: deepgramOptions.fillerWords},
|
||||||
|
...((Array.isArray(deepgramOptions.keyterms) && deepgramOptions.keyterms.length > 0) &&
|
||||||
|
{DEEPGRAM_SPEECH_KEYTERMS: deepgramOptions.keyterms.join(',')})
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if ('soniox' === vendor) {
|
else if ('soniox' === vendor) {
|
||||||
@@ -785,7 +991,8 @@ module.exports = (logger) => {
|
|||||||
...(cobaltOptions.enableConfusionNetwork && {COBALT_ENABLE_CONFUSION_NETWORK: 1}),
|
...(cobaltOptions.enableConfusionNetwork && {COBALT_ENABLE_CONFUSION_NETWORK: 1}),
|
||||||
...(cobaltOptions.compiledContextData && {COBALT_COMPILED_CONTEXT_DATA: cobaltOptions.compiledContextData}),
|
...(cobaltOptions.compiledContextData && {COBALT_COMPILED_CONTEXT_DATA: cobaltOptions.compiledContextData}),
|
||||||
};
|
};
|
||||||
} else if ('assemblyai' === vendor) {
|
}
|
||||||
|
else if ('assemblyai' === vendor) {
|
||||||
opts = {
|
opts = {
|
||||||
...opts,
|
...opts,
|
||||||
...(sttCredentials.api_key) &&
|
...(sttCredentials.api_key) &&
|
||||||
@@ -794,8 +1001,111 @@ module.exports = (logger) => {
|
|||||||
{ASSEMBLYAI_WORD_BOOST: JSON.stringify(rOpts.hints)})
|
{ASSEMBLYAI_WORD_BOOST: JSON.stringify(rOpts.hints)})
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if ('voxist' === vendor) {
|
||||||
|
opts = {
|
||||||
|
...opts,
|
||||||
|
...(sttCredentials.api_key) &&
|
||||||
|
{VOXIST_API_KEY: sttCredentials.api_key},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else if ('openai' === vendor) {
|
||||||
|
const {openaiOptions = {}} = rOpts;
|
||||||
|
const model = openaiOptions.model || rOpts.model || sttCredentials.model_id || 'whisper-1';
|
||||||
|
const apiKey = openaiOptions.apiKey || sttCredentials.api_key;
|
||||||
|
|
||||||
|
opts = {
|
||||||
|
OPENAI_MODEL: model,
|
||||||
|
OPENAI_API_KEY: apiKey,
|
||||||
|
...opts,
|
||||||
|
...(openaiOptions.prompt && {OPENAI_PROMPT: openaiOptions.prompt}),
|
||||||
|
...(openaiOptions.input_audio_noise_reduction &&
|
||||||
|
{OPENAI_INPUT_AUDIO_NOISE_REDUCTION: openaiOptions.input_audio_noise_reduction}),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (openaiOptions.turn_detection) {
|
||||||
|
opts = {
|
||||||
|
...opts,
|
||||||
|
OPENAI_TURN_DETECTION_TYPE: openaiOptions.turn_detection.type,
|
||||||
|
...(openaiOptions.turn_detection.threshold && {
|
||||||
|
OPENAI_TURN_DETECTION_THRESHOLD: openaiOptions.turn_detection.threshold
|
||||||
|
}),
|
||||||
|
...(openaiOptions.turn_detection.prefix_padding_ms && {
|
||||||
|
OPENAI_TURN_DETECTION_PREFIX_PADDING_MS: openaiOptions.turn_detection.prefix_padding_ms
|
||||||
|
}),
|
||||||
|
...(openaiOptions.turn_detection.silence_duration_ms && {
|
||||||
|
OPENAI_TURN_DETECTION_SILENCE_DURATION_MS: openaiOptions.turn_detection.silence_duration_ms
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if ('verbio' === vendor) {
|
||||||
|
const {verbioOptions = {}} = rOpts;
|
||||||
|
opts = {
|
||||||
|
...opts,
|
||||||
|
...(sttCredentials.access_token && { VERBIO_ACCESS_TOKEN: sttCredentials.access_token}),
|
||||||
|
...(sttCredentials.engine_version && {VERBIO_ENGINE_VERSION: sttCredentials.engine_version}),
|
||||||
|
...(language && {VERBIO_LANGUAGE: language}),
|
||||||
|
...(verbioOptions.enable_formatting && {VERBIO_ENABLE_FORMATTING: verbioOptions.enable_formatting}),
|
||||||
|
...(verbioOptions.enable_diarization && {VERBIO_ENABLE_DIARIZATION: verbioOptions.enable_diarization}),
|
||||||
|
...(verbioOptions.topic && {VERBIO_TOPIC: verbioOptions.topic}),
|
||||||
|
...(verbioOptions.inline_grammar && {VERBIO_INLINE_GRAMMAR: verbioOptions.inline_grammar}),
|
||||||
|
...(verbioOptions.grammar_uri && {VERBIO_GRAMMAR_URI: verbioOptions.grammar_uri}),
|
||||||
|
...(verbioOptions.label && {VERBIO_LABEL: verbioOptions.label}),
|
||||||
|
...(verbioOptions.recognition_timeout && {VERBIO_RECOGNITION_TIMEOUT: verbioOptions.recognition_timeout}),
|
||||||
|
...(verbioOptions.speech_complete_timeout &&
|
||||||
|
{VERBIO_SPEECH_COMPLETE_TIMEOUT: verbioOptions.speech_complete_timeout}),
|
||||||
|
...(verbioOptions.speech_incomplete_timeout &&
|
||||||
|
{VERBIO_SPEECH_INCOMPLETE_TIMEOUT: verbioOptions.speech_incomplete_timeout}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else if ('speechmatics' === vendor) {
|
||||||
|
const {speechmaticsOptions = {}} = rOpts;
|
||||||
|
opts = {
|
||||||
|
...opts,
|
||||||
|
...(sttCredentials.api_key) && {SPEECHMATICS_API_KEY: sttCredentials.api_key},
|
||||||
|
...(sttCredentials.speechmatics_stt_uri) && {SPEECHMATICS_HOST: sttCredentials.speechmatics_stt_uri},
|
||||||
|
...(rOpts.hints?.length > 0 && {SPEECHMATICS_SPEECH_HINTS: rOpts.hints.join(',')}),
|
||||||
|
...(speechmaticsOptions.translation_config &&
|
||||||
|
{
|
||||||
|
SPEECHMATICS_TRANSLATION_LANGUAGES: speechmaticsOptions.translation_config.target_languages.join(','),
|
||||||
|
SPEECHMATICS_TRANSLATION_PARTIALS: speechmaticsOptions.translation_config.enable_partials ? 1 : 0
|
||||||
|
}
|
||||||
|
),
|
||||||
|
...(speechmaticsOptions.transcription_config?.domain &&
|
||||||
|
{SPEECHMATICS_DOMAIN: speechmaticsOptions.transcription_config.domain}),
|
||||||
|
...{SPEECHMATICS_MAX_DELAY: speechmaticsOptions.transcription_config?.max_delay || 0.7},
|
||||||
|
...{SPEECHMATICS_MAX_DELAY_MODE: speechmaticsOptions.transcription_config?.max_delay_mode || 'flexible'},
|
||||||
|
...(speechmaticsOptions.transcription_config?.diarization &&
|
||||||
|
{SPEECHMATICS_DIARIZATION: speechmaticsOptions.transcription_config.diarization}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.speaker_diarization_config?.speaker_sensitivity &&
|
||||||
|
{SPEECHMATICS_DIARIZATION_SPEAKER_SENSITIVITY:
|
||||||
|
speechmaticsOptions.transcription_config.speaker_diarization_config.speaker_sensitivity}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.speaker_diarization_config?.max_speakers &&
|
||||||
|
{SPEECHMATICS_DIARIZATION_MAX_SPEAKERS:
|
||||||
|
speechmaticsOptions.transcription_config.speaker_diarization_config.max_speakers}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.output_locale &&
|
||||||
|
{SPEECHMATICS_OUTPUT_LOCALE: speechmaticsOptions.transcription_config.output_locale}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.punctuation_overrides?.permitted_marks &&
|
||||||
|
{SPEECHMATICS_PUNCTUATION_ALLOWED:
|
||||||
|
speechmaticsOptions.transcription_config.punctuation_overrides.permitted_marks.join(',')}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.punctuation_overrides?.sensitivity &&
|
||||||
|
{SPEECHMATICS_PUNCTUATION_SENSITIVITY:
|
||||||
|
speechmaticsOptions.transcription_config?.punctuation_overrides?.sensitivity}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.operating_point &&
|
||||||
|
{SPEECHMATICS_OPERATING_POINT: speechmaticsOptions.transcription_config.operating_point}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.enable_entities &&
|
||||||
|
{SPEECHMATICS_ENABLE_ENTTIES: speechmaticsOptions.transcription_config.enable_entities}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.audio_filtering_config?.volume_threshold &&
|
||||||
|
{SPEECHMATICS_VOLUME_THRESHOLD:
|
||||||
|
speechmaticsOptions.transcription_config.audio_filtering_config.volume_threshold}),
|
||||||
|
...(speechmaticsOptions.transcription_config?.transcript_filtering_config?.remove_disfluencies &&
|
||||||
|
{SPEECHMATICS_REMOVE_DISFLUENCIES:
|
||||||
|
speechmaticsOptions.transcription_config.transcript_filtering_config.remove_disfluencies})
|
||||||
|
};
|
||||||
|
}
|
||||||
else if (vendor.startsWith('custom:')) {
|
else if (vendor.startsWith('custom:')) {
|
||||||
let {options = {}} = rOpts;
|
let {options = {}} = rOpts.customOptions || {};
|
||||||
|
const {sampleRate} = rOpts.customOptions || {};
|
||||||
const {auth_token, custom_stt_url} = sttCredentials;
|
const {auth_token, custom_stt_url} = sttCredentials;
|
||||||
options = {
|
options = {
|
||||||
...options,
|
...options,
|
||||||
@@ -803,14 +1113,15 @@ module.exports = (logger) => {
|
|||||||
{hints: rOpts.hints}),
|
{hints: rOpts.hints}),
|
||||||
...(rOpts.hints?.length > 0 && typeof rOpts.hints[0] === 'object' &&
|
...(rOpts.hints?.length > 0 && typeof rOpts.hints[0] === 'object' &&
|
||||||
{hints: JSON.stringify(rOpts.hints)}),
|
{hints: JSON.stringify(rOpts.hints)}),
|
||||||
...(typeof rOpts.hintsBoost === 'number' && {hintsBoost: rOpts.hintsBoost})
|
...(typeof rOpts.hintsBoost === 'number' && {hintsBoost: rOpts.hintsBoost}),
|
||||||
|
...(task.cs?.callSid && {callSid: task.cs.callSid})
|
||||||
};
|
};
|
||||||
|
|
||||||
opts = {
|
opts = {
|
||||||
...opts,
|
...opts,
|
||||||
...(auth_token && {JAMBONZ_STT_API_KEY: auth_token}),
|
...(auth_token && {JAMBONZ_STT_API_KEY: auth_token}),
|
||||||
JAMBONZ_STT_URL: custom_stt_url,
|
JAMBONZ_STT_URL: custom_stt_url,
|
||||||
...(Object.keys(options).length > 0 && {JAMBONZ_STT_OPTIONS: JSON.stringify(options)}),
|
...(Object.keys(options).length > 0 && {JAMBONZ_STT_OPTIONS: JSON.stringify(options)}),
|
||||||
|
...(sampleRate && {JAMBONZ_STT_SAMPLING: sampleRate})
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -860,6 +1171,6 @@ module.exports = (logger) => {
|
|||||||
setChannelVarsForStt,
|
setChannelVarsForStt,
|
||||||
setSpeechCredentialsAtRuntime,
|
setSpeechCredentialsAtRuntime,
|
||||||
compileSonioxTranscripts,
|
compileSonioxTranscripts,
|
||||||
consolidateTranscripts
|
consolidateTranscripts,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
452
lib/utils/tts-streaming-buffer.js
Normal file
452
lib/utils/tts-streaming-buffer.js
Normal file
@@ -0,0 +1,452 @@
|
|||||||
|
const Emitter = require('events');
|
||||||
|
const assert = require('assert');
|
||||||
|
const {
|
||||||
|
TtsStreamingEvents,
|
||||||
|
TtsStreamingConnectionStatus
|
||||||
|
} = require('../utils/constants');
|
||||||
|
|
||||||
|
const MAX_CHUNK_SIZE = 1800;
|
||||||
|
const HIGH_WATER_BUFFER_SIZE = 1000;
|
||||||
|
const LOW_WATER_BUFFER_SIZE = 200;
|
||||||
|
const TIMEOUT_RETRY_MSECS = 3000;
|
||||||
|
|
||||||
|
|
||||||
|
const isWhitespace = (str) => /^\s*$/.test(str);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each queue item is an object:
|
||||||
|
* - { type: 'text', value: '…' } for text tokens.
|
||||||
|
* - { type: 'flush' } for a flush command.
|
||||||
|
*/
|
||||||
|
class TtsStreamingBuffer extends Emitter {
|
||||||
|
constructor(cs) {
|
||||||
|
super();
|
||||||
|
this.cs = cs;
|
||||||
|
this.logger = cs.logger;
|
||||||
|
|
||||||
|
// Use an array to hold our structured items.
|
||||||
|
this.queue = [];
|
||||||
|
// Track total number of characters in text items.
|
||||||
|
this.bufferedLength = 0;
|
||||||
|
this.eventHandlers = [];
|
||||||
|
this._isFull = false;
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.NotConnected;
|
||||||
|
this.timer = null;
|
||||||
|
// Record the last time the text buffer was updated.
|
||||||
|
this.lastUpdateTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isEmpty() {
|
||||||
|
return this.queue.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
get size() {
|
||||||
|
return this.bufferedLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isFull() {
|
||||||
|
return this._isFull;
|
||||||
|
}
|
||||||
|
|
||||||
|
get ep() {
|
||||||
|
return this.cs?.ep;
|
||||||
|
}
|
||||||
|
|
||||||
|
async start() {
|
||||||
|
assert.ok(
|
||||||
|
this._connectionStatus === TtsStreamingConnectionStatus.NotConnected,
|
||||||
|
'TtsStreamingBuffer:start already started, or has failed'
|
||||||
|
);
|
||||||
|
|
||||||
|
this.vendor = this.cs.getTsStreamingVendor();
|
||||||
|
if (!this.vendor) {
|
||||||
|
this.logger.info('TtsStreamingBuffer:start No TTS streaming vendor configured');
|
||||||
|
throw new Error('No TTS streaming vendor configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info(`TtsStreamingBuffer:start Connecting to TTS streaming with vendor ${this.vendor}`);
|
||||||
|
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.Connecting;
|
||||||
|
try {
|
||||||
|
if (this.eventHandlers.length === 0) this._initHandlers(this.ep);
|
||||||
|
await this._api(this.ep, [this.ep.uuid, 'connect']);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({ err }, 'TtsStreamingBuffer:start Error connecting to TTS streaming');
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.Failed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
clearTimeout(this.timer);
|
||||||
|
this.removeCustomEventListeners();
|
||||||
|
if (this.ep) {
|
||||||
|
this._api(this.ep, [this.ep.uuid, 'close'])
|
||||||
|
.catch((err) =>
|
||||||
|
this.logger.info({ err }, 'TtsStreamingBuffer:stop Error closing TTS streaming')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.timer = null;
|
||||||
|
this.queue = [];
|
||||||
|
this.bufferedLength = 0;
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.NotConnected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Buffer new text tokens.
|
||||||
|
*/
|
||||||
|
async bufferTokens(tokens) {
|
||||||
|
if (this._connectionStatus === TtsStreamingConnectionStatus.Failed) {
|
||||||
|
this.logger.info('TtsStreamingBuffer:bufferTokens TTS streaming connection failed, rejecting request');
|
||||||
|
return { status: 'failed', reason: `connection to ${this.vendor} failed` };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (0 === this.bufferedLength && isWhitespace(tokens)) {
|
||||||
|
this.logger.debug({tokens}, 'TtsStreamingBuffer:bufferTokens discarded whitespace tokens');
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayedTokens = tokens.length <= 40 ? tokens : tokens.substring(0, 40);
|
||||||
|
const totalLength = tokens.length;
|
||||||
|
|
||||||
|
if (this.bufferedLength + totalLength > HIGH_WATER_BUFFER_SIZE) {
|
||||||
|
this.logger.info(
|
||||||
|
`TtsStreamingBuffer throttling: buffer is full, rejecting request to buffer ${totalLength} tokens`
|
||||||
|
);
|
||||||
|
if (!this._isFull) {
|
||||||
|
this._isFull = true;
|
||||||
|
this.emit(TtsStreamingEvents.Pause);
|
||||||
|
}
|
||||||
|
return { status: 'failed', reason: 'full' };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`TtsStreamingBuffer:bufferTokens "${displayedTokens}" (length: ${totalLength})`
|
||||||
|
);
|
||||||
|
this.queue.push({ type: 'text', value: tokens });
|
||||||
|
this.bufferedLength += totalLength;
|
||||||
|
// Update the last update time each time new text is buffered.
|
||||||
|
this.lastUpdateTime = Date.now();
|
||||||
|
|
||||||
|
await this._feedQueue();
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a flush command. If no text is queued, flush immediately.
|
||||||
|
* Otherwise, append a flush marker so that all text preceding it will be sent
|
||||||
|
* (regardless of sentence boundaries) before the flush is issued.
|
||||||
|
*/
|
||||||
|
flush() {
|
||||||
|
if (this._connectionStatus === TtsStreamingConnectionStatus.Connecting) {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:flush TTS stream is not quite ready - wait for connect');
|
||||||
|
if (this.queue.length === 0 || this.queue[this.queue.length - 1].type !== 'flush') {
|
||||||
|
this.queue.push({ type: 'flush' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if (this._connectionStatus === TtsStreamingConnectionStatus.Connected) {
|
||||||
|
if (this.isEmpty) {
|
||||||
|
this._doFlush();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (this.queue[this.queue.length - 1].type !== 'flush') {
|
||||||
|
this.queue.push({ type: 'flush' });
|
||||||
|
this.logger.debug('TtsStreamingBuffer:flush added flush marker to queue');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
this.logger.debug(
|
||||||
|
`TtsStreamingBuffer:flush TTS stream is not connected, status: ${this._connectionStatus}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clear() {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:clear');
|
||||||
|
if (this._connectionStatus !== TtsStreamingConnectionStatus.Connected) return;
|
||||||
|
clearTimeout(this.timer);
|
||||||
|
this._api(this.ep, [this.ep.uuid, 'clear']).catch((err) =>
|
||||||
|
this.logger.info({ err }, 'TtsStreamingBuffer:clear Error clearing TTS streaming')
|
||||||
|
);
|
||||||
|
this.queue = [];
|
||||||
|
this.bufferedLength = 0;
|
||||||
|
this.timer = null;
|
||||||
|
this._isFull = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process the queue in two phases.
|
||||||
|
*
|
||||||
|
* Phase 1: Look for flush markers. When a flush marker is found (even if not at the very front),
|
||||||
|
* send all text tokens that came before it immediately (ignoring sentence boundaries)
|
||||||
|
* and then send the flush command. Repeat until there are no flush markers left.
|
||||||
|
*
|
||||||
|
* Phase 2: With the remaining queue (now containing only text items), accumulate text
|
||||||
|
* up to MAX_CHUNK_SIZE and use sentence-boundary logic to determine a chunk.
|
||||||
|
* Then, remove the exact tokens (or portions thereof) that were consumed.
|
||||||
|
*/
|
||||||
|
async _feedQueue(handlingTimeout = false) {
|
||||||
|
this.logger.debug({ queue: this.queue }, 'TtsStreamingBuffer:_feedQueue');
|
||||||
|
try {
|
||||||
|
if (!this.cs.isTtsStreamOpen || !this.ep) {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:_feedQueue TTS stream is not open or no endpoint available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
this._connectionStatus === TtsStreamingConnectionStatus.NotConnected ||
|
||||||
|
this._connectionStatus === TtsStreamingConnectionStatus.Failed
|
||||||
|
) {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:_feedQueue TTS stream is not connected');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Phase 1: Process flush markers ---
|
||||||
|
// Process any flush marker that isn’t in the very first position.
|
||||||
|
let flushIndex = this.queue.findIndex((item, idx) => item.type === 'flush' && idx > 0);
|
||||||
|
while (flushIndex !== -1) {
|
||||||
|
let flushText = '';
|
||||||
|
// Accumulate all text tokens preceding the flush marker.
|
||||||
|
for (let i = 0; i < flushIndex; i++) {
|
||||||
|
if (this.queue[i].type === 'text') {
|
||||||
|
flushText += this.queue[i].value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove those text items.
|
||||||
|
for (let i = 0; i < flushIndex; i++) {
|
||||||
|
const item = this.queue.shift();
|
||||||
|
if (item.type === 'text') {
|
||||||
|
this.bufferedLength -= item.value.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove the flush marker (now at the front).
|
||||||
|
if (this.queue.length > 0 && this.queue[0].type === 'flush') {
|
||||||
|
this.queue.shift();
|
||||||
|
}
|
||||||
|
// Immediately send all accumulated text (ignoring sentence boundaries).
|
||||||
|
if (flushText.length > 0) {
|
||||||
|
const modifiedFlushText = flushText.replace(/\n\n/g, '\n \n');
|
||||||
|
try {
|
||||||
|
await this._api(this.ep, [this.ep.uuid, 'send', modifiedFlushText]);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({ err, flushText }, 'TtsStreamingBuffer:_feedQueue Error sending TTS chunk');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Send the flush command.
|
||||||
|
await this._doFlush();
|
||||||
|
|
||||||
|
flushIndex = this.queue.findIndex((item, idx) => item.type === 'flush' && idx > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a flush marker is at the very front, process it.
|
||||||
|
while (this.queue.length > 0 && this.queue[0].type === 'flush') {
|
||||||
|
this.queue.shift();
|
||||||
|
await this._doFlush();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Phase 2: Process remaining text tokens ---
|
||||||
|
if (this.queue.length === 0) {
|
||||||
|
this._removeTimer();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accumulate contiguous text tokens (from the front) up to MAX_CHUNK_SIZE.
|
||||||
|
let combinedText = '';
|
||||||
|
for (const item of this.queue) {
|
||||||
|
if (item.type !== 'text') break;
|
||||||
|
combinedText += item.value;
|
||||||
|
if (combinedText.length >= MAX_CHUNK_SIZE) break;
|
||||||
|
}
|
||||||
|
if (combinedText.length === 0) {
|
||||||
|
this._removeTimer();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = Math.min(MAX_CHUNK_SIZE, combinedText.length);
|
||||||
|
let chunkEnd = findSentenceBoundary(combinedText, limit);
|
||||||
|
if (chunkEnd <= 0) {
|
||||||
|
if (handlingTimeout) {
|
||||||
|
chunkEnd = findWordBoundary(combinedText, limit);
|
||||||
|
if (chunkEnd <= 0) {
|
||||||
|
this._setTimerIfNeeded();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this._setTimerIfNeeded();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const chunk = combinedText.slice(0, chunkEnd);
|
||||||
|
|
||||||
|
// Now we iterate over the queue items
|
||||||
|
// and deduct their lengths until we've accounted for chunkEnd characters.
|
||||||
|
let remaining = chunkEnd;
|
||||||
|
let tokensProcessed = 0;
|
||||||
|
for (let i = 0; i < this.queue.length; i++) {
|
||||||
|
const token = this.queue[i];
|
||||||
|
if (token.type !== 'text') break;
|
||||||
|
if (remaining >= token.value.length) {
|
||||||
|
remaining -= token.value.length;
|
||||||
|
tokensProcessed = i + 1;
|
||||||
|
} else {
|
||||||
|
// Partially consumed token: update its value to remove the consumed part.
|
||||||
|
token.value = token.value.slice(remaining);
|
||||||
|
tokensProcessed = i;
|
||||||
|
remaining = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove the fully consumed tokens from the front of the queue.
|
||||||
|
this.queue.splice(0, tokensProcessed);
|
||||||
|
this.bufferedLength -= chunkEnd;
|
||||||
|
|
||||||
|
const modifiedChunk = chunk.replace(/\n\n/g, '\n \n');
|
||||||
|
this.logger.debug(`TtsStreamingBuffer:_feedQueue sending chunk to tts: ${modifiedChunk}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._api(this.ep, [this.ep.uuid, 'send', modifiedChunk]);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({ err, chunk }, 'TtsStreamingBuffer:_feedQueue Error sending TTS chunk');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._isFull && this.bufferedLength <= LOW_WATER_BUFFER_SIZE) {
|
||||||
|
this.logger.info('TtsStreamingBuffer throttling: buffer is no longer full - resuming');
|
||||||
|
this._isFull = false;
|
||||||
|
this.emit(TtsStreamingEvents.Resume);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this._feedQueue();
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.info({ err }, 'TtsStreamingBuffer:_feedQueue Error sending TTS chunk');
|
||||||
|
this.queue = [];
|
||||||
|
this.bufferedLength = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _api(ep, args) {
|
||||||
|
const apiCmd = `uuid_${this.vendor.startsWith('custom:') ? 'custom' : this.vendor}_tts_streaming`;
|
||||||
|
const res = await ep.api(apiCmd, `^^|${args.join('|')}`);
|
||||||
|
if (!res.body?.startsWith('+OK')) {
|
||||||
|
this.logger.info({ args }, `Error calling ${apiCmd}: ${res.body}`);
|
||||||
|
throw new Error(`Error calling ${apiCmd}: ${res.body}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_doFlush() {
|
||||||
|
return this._api(this.ep, [this.ep.uuid, 'flush'])
|
||||||
|
.then(() => this.logger.debug('TtsStreamingBuffer:_doFlush sent flush command'))
|
||||||
|
.catch((err) =>
|
||||||
|
this.logger.info(
|
||||||
|
{ err },
|
||||||
|
`TtsStreamingBuffer:_doFlush Error flushing TTS streaming: ${JSON.stringify(err)}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async _onConnect(vendor) {
|
||||||
|
this.logger.info(`TtsStreamingBuffer:_onConnect streaming tts connection made to ${vendor} successful`);
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.Connected;
|
||||||
|
if (this.queue.length > 0) {
|
||||||
|
await this._feedQueue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_onConnectFailure(vendor) {
|
||||||
|
this.logger.info(`TtsStreamingBuffer:_onConnectFailure streaming tts connection failed to ${vendor}`);
|
||||||
|
this._connectionStatus = TtsStreamingConnectionStatus.Failed;
|
||||||
|
this.queue = [];
|
||||||
|
this.bufferedLength = 0;
|
||||||
|
this.emit(TtsStreamingEvents.ConnectFailure, { vendor });
|
||||||
|
}
|
||||||
|
|
||||||
|
_setTimerIfNeeded() {
|
||||||
|
if (this.bufferedLength > 0 && !this.timer) {
|
||||||
|
this.logger.debug({queue: this.queue},
|
||||||
|
`TtsStreamingBuffer:_setTimerIfNeeded setting timer because ${this.bufferedLength} buffered`);
|
||||||
|
this.timer = setTimeout(this._onTimeout.bind(this), TIMEOUT_RETRY_MSECS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_removeTimer() {
|
||||||
|
if (this.timer) {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:_removeTimer clearing timer');
|
||||||
|
clearTimeout(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_onTimeout() {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:_onTimeout Timeout waiting for sentence boundary');
|
||||||
|
// Check if new text has been added since the timer was set.
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - this.lastUpdateTime < TIMEOUT_RETRY_MSECS) {
|
||||||
|
this.logger.debug('TtsStreamingBuffer:_onTimeout New text received recently; postponing flush.');
|
||||||
|
this._setTimerIfNeeded();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.timer = null;
|
||||||
|
this._feedQueue(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
_onTtsEmpty(vendor) {
|
||||||
|
this.emit(TtsStreamingEvents.Empty, { vendor });
|
||||||
|
}
|
||||||
|
|
||||||
|
addCustomEventListener(ep, event, handler) {
|
||||||
|
this.eventHandlers.push({ ep, event, handler });
|
||||||
|
ep.addCustomEventListener(event, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeCustomEventListeners() {
|
||||||
|
this.eventHandlers.forEach((h) => h.ep.removeCustomEventListener(h.event, h.handler));
|
||||||
|
}
|
||||||
|
|
||||||
|
_initHandlers(ep) {
|
||||||
|
[
|
||||||
|
'deepgram',
|
||||||
|
'cartesia',
|
||||||
|
'elevenlabs',
|
||||||
|
'rimelabs',
|
||||||
|
'custom'
|
||||||
|
].forEach((vendor) => {
|
||||||
|
const eventClassName = `${vendor.charAt(0).toUpperCase() + vendor.slice(1)}TtsStreamingEvents`;
|
||||||
|
const eventClass = require('../utils/constants')[eventClassName];
|
||||||
|
if (!eventClass) throw new Error(`Event class for vendor ${vendor} not found`);
|
||||||
|
|
||||||
|
this.addCustomEventListener(ep, eventClass.Connect, this._onConnect.bind(this, vendor));
|
||||||
|
this.addCustomEventListener(ep, eventClass.ConnectFailure, this._onConnectFailure.bind(this, vendor));
|
||||||
|
this.addCustomEventListener(ep, eventClass.Empty, this._onTtsEmpty.bind(this, vendor));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const findSentenceBoundary = (text, limit) => {
|
||||||
|
// Look for punctuation or double newline that signals sentence end.
|
||||||
|
const sentenceEndRegex = /[.!?](?=\s|$)|\n\n/g;
|
||||||
|
let lastSentenceBoundary = -1;
|
||||||
|
let match;
|
||||||
|
while ((match = sentenceEndRegex.exec(text)) && match.index < limit) {
|
||||||
|
const precedingText = text.slice(0, match.index).trim();
|
||||||
|
if (precedingText.length > 0) {
|
||||||
|
if (
|
||||||
|
match[0] === '\n\n' ||
|
||||||
|
(match.index === 0 || !/\d$/.test(text[match.index - 1]))
|
||||||
|
) {
|
||||||
|
lastSentenceBoundary = match.index + (match[0] === '\n\n' ? 2 : 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lastSentenceBoundary;
|
||||||
|
};
|
||||||
|
|
||||||
|
const findWordBoundary = (text, limit) => {
|
||||||
|
const wordBoundaryRegex = /\s+/g;
|
||||||
|
let lastWordBoundary = -1;
|
||||||
|
let match;
|
||||||
|
while ((match = wordBoundaryRegex.exec(text)) && match.index < limit) {
|
||||||
|
lastWordBoundary = match.index;
|
||||||
|
}
|
||||||
|
return lastWordBoundary;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = TtsStreamingBuffer;
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
const assert = require('assert');
|
const assert = require('assert');
|
||||||
const BaseRequestor = require('./base-requestor');
|
const BaseRequestor = require('./base-requestor');
|
||||||
const short = require('short-uuid');
|
const short = require('short-uuid');
|
||||||
const {HookMsgTypes} = require('./constants.json');
|
const {HookMsgTypes, WS_CLOSE_CODES} = require('./constants.json');
|
||||||
const Websocket = require('ws');
|
const Websocket = require('ws');
|
||||||
const snakeCaseKeys = require('./snakecase-keys');
|
const snakeCaseKeys = require('./snakecase-keys');
|
||||||
const {
|
const {
|
||||||
@@ -12,6 +12,20 @@ const {
|
|||||||
JAMBONES_WS_MAX_PAYLOAD,
|
JAMBONES_WS_MAX_PAYLOAD,
|
||||||
HTTP_USER_AGENT_HEADER
|
HTTP_USER_AGENT_HEADER
|
||||||
} = require('../config');
|
} = require('../config');
|
||||||
|
const MTYPE_WANTS_ACK = [
|
||||||
|
'call:status',
|
||||||
|
'verb:status',
|
||||||
|
'jambonz:error',
|
||||||
|
'llm:event',
|
||||||
|
'llm:tool-call',
|
||||||
|
'tts:streaming-event',
|
||||||
|
'tts:tokens-result',
|
||||||
|
];
|
||||||
|
const MTYPE_NO_DATA = [
|
||||||
|
'llm:tool-output',
|
||||||
|
'tts:flush',
|
||||||
|
'tts:clear'
|
||||||
|
];
|
||||||
|
|
||||||
class WsRequestor extends BaseRequestor {
|
class WsRequestor extends BaseRequestor {
|
||||||
constructor(logger, account_sid, hook, secret) {
|
constructor(logger, account_sid, hook, secret) {
|
||||||
@@ -44,7 +58,7 @@ class WsRequestor extends BaseRequestor {
|
|||||||
async request(type, hook, params, httpHeaders = {}) {
|
async request(type, hook, params, httpHeaders = {}) {
|
||||||
assert(HookMsgTypes.includes(type));
|
assert(HookMsgTypes.includes(type));
|
||||||
const url = hook.url || hook;
|
const url = hook.url || hook;
|
||||||
const wantsAck = !['call:status', 'verb:status', 'jambonz:error'].includes(type);
|
const wantsAck = !MTYPE_WANTS_ACK.includes(type);
|
||||||
|
|
||||||
if (this.maliciousClient) {
|
if (this.maliciousClient) {
|
||||||
this.logger.info({url: this.url}, 'WsRequestor:request - discarding msg to malicious client');
|
this.logger.info({url: this.url}, 'WsRequestor:request - discarding msg to malicious client');
|
||||||
@@ -56,6 +70,12 @@ class WsRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (type === 'session:new') this.call_sid = params.callSid;
|
if (type === 'session:new') this.call_sid = params.callSid;
|
||||||
|
if (type === 'session:reconnect') {
|
||||||
|
this._reconnectPromise = new Promise((resolve, reject) => {
|
||||||
|
this._reconnectResolve = resolve;
|
||||||
|
this._reconnectReject = reject;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/* if we have an absolute url, and it is http then do a standard webhook */
|
/* if we have an absolute url, and it is http then do a standard webhook */
|
||||||
if (this._isAbsoluteUrl(url) && url.startsWith('http')) {
|
if (this._isAbsoluteUrl(url) && url.startsWith('http')) {
|
||||||
@@ -71,20 +91,23 @@ class WsRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* connect if necessary */
|
/* connect if necessary */
|
||||||
|
const queueMsg = () => {
|
||||||
|
this.logger.debug(
|
||||||
|
`WsRequestor:request(${this.id}) - queueing ${type} message since we are connecting`);
|
||||||
|
if (wantsAck) {
|
||||||
|
const p = new Promise((resolve, reject) => {
|
||||||
|
this.queuedMsg.push({type, hook, params, httpHeaders, promise: {resolve, reject}});
|
||||||
|
});
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
this.queuedMsg.push({type, hook, params, httpHeaders});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
};
|
||||||
if (!this.ws) {
|
if (!this.ws) {
|
||||||
if (this.connectInProgress) {
|
if (this.connectInProgress) {
|
||||||
this.logger.debug(
|
return queueMsg();
|
||||||
`WsRequestor:request(${this.id}) - queueing ${type} message since we are connecting`);
|
|
||||||
if (wantsAck) {
|
|
||||||
const p = new Promise((resolve, reject) => {
|
|
||||||
this.queuedMsg.push({type, hook, params, httpHeaders, promise: {resolve, reject}});
|
|
||||||
});
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
this.queuedMsg.push({type, hook, params, httpHeaders});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
this.connectInProgress = true;
|
this.connectInProgress = true;
|
||||||
this.logger.debug(`WsRequestor:request(${this.id}) - connecting since we do not have a connection for ${type}`);
|
this.logger.debug(`WsRequestor:request(${this.id}) - connecting since we do not have a connection for ${type}`);
|
||||||
@@ -102,11 +125,15 @@ class WsRequestor extends BaseRequestor {
|
|||||||
return Promise.reject(err);
|
return Promise.reject(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// If jambonz wait for ack from reconnect, queue the msg until reconnect is acked
|
||||||
|
if (type !== 'session:reconnect' && this._reconnectPromise) {
|
||||||
|
return queueMsg();
|
||||||
|
}
|
||||||
assert(this.ws);
|
assert(this.ws);
|
||||||
|
|
||||||
/* prepare and send message */
|
/* prepare and send message */
|
||||||
let payload = params ? snakeCaseKeys(params, ['customerData', 'sip']) : null;
|
let payload = params ? snakeCaseKeys(params, ['customerData', 'sip']) : null;
|
||||||
if (type === 'session:new') this._sessionData = payload;
|
if (type === 'session:new' || type === 'session:adulting') this._sessionData = payload;
|
||||||
if (type === 'session:reconnect') payload = this._sessionData;
|
if (type === 'session:reconnect') payload = this._sessionData;
|
||||||
assert.ok(url, 'WsRequestor:request url was not provided');
|
assert.ok(url, 'WsRequestor:request url was not provided');
|
||||||
|
|
||||||
@@ -119,7 +146,9 @@ class WsRequestor extends BaseRequestor {
|
|||||||
type,
|
type,
|
||||||
msgid,
|
msgid,
|
||||||
call_sid: this.call_sid,
|
call_sid: this.call_sid,
|
||||||
hook: type === 'verb:hook' ? url : undefined,
|
hook: [
|
||||||
|
'verb:hook', 'dial:confirm', 'session:redirect', 'llm:event', 'llm:tool-call'
|
||||||
|
].includes(type) ? url : undefined,
|
||||||
data: {...payload},
|
data: {...payload},
|
||||||
...b3
|
...b3
|
||||||
};
|
};
|
||||||
@@ -139,6 +168,18 @@ class WsRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const rejectQueuedMsgs = (err) => {
|
||||||
|
if (this.queuedMsg.length > 0) {
|
||||||
|
for (const {promise} of this.queuedMsg) {
|
||||||
|
this.logger.debug(`WsRequestor:request - preparing queued ${type} for rejectQueuedMsgs`);
|
||||||
|
if (promise) {
|
||||||
|
promise.reject(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.queuedMsg.length = 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
//this.logger.debug({obj}, `websocket: sending (${url})`);
|
//this.logger.debug({obj}, `websocket: sending (${url})`);
|
||||||
|
|
||||||
/* special case: reconnecting before we received ack to session:new */
|
/* special case: reconnecting before we received ack to session:new */
|
||||||
@@ -179,16 +220,37 @@ class WsRequestor extends BaseRequestor {
|
|||||||
this.logger.debug({response}, `WsRequestor:request ${url} succeeded in ${rtt}ms`);
|
this.logger.debug({response}, `WsRequestor:request ${url} succeeded in ${rtt}ms`);
|
||||||
this.stats.histogram('app.hook.ws_response_time', rtt, ['hook_type:app']);
|
this.stats.histogram('app.hook.ws_response_time', rtt, ['hook_type:app']);
|
||||||
resolve(response);
|
resolve(response);
|
||||||
|
if (this._reconnectResolve) {
|
||||||
|
this._reconnectResolve();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
failure: (err) => {
|
failure: (err) => {
|
||||||
|
if (this._reconnectReject) {
|
||||||
|
this._reconnectReject(err);
|
||||||
|
}
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
reject(err);
|
reject(err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/* send the message */
|
/* send the message */
|
||||||
this.ws.send(JSON.stringify(obj), () => {
|
this.ws.send(JSON.stringify(obj), async() => {
|
||||||
this.logger.debug({obj}, `WsRequestor:request websocket: sent (${url})`);
|
this.logger.debug({obj}, `WsRequestor:request websocket: sent (${url})`);
|
||||||
|
// If session:reconnect is waiting for ack, hold here until ack to send queuedMsgs
|
||||||
|
if (this._reconnectPromise) {
|
||||||
|
try {
|
||||||
|
await this._reconnectPromise;
|
||||||
|
} catch (err) {
|
||||||
|
// bad thing happened to session:recconnect
|
||||||
|
rejectQueuedMsgs(err);
|
||||||
|
this.emit('reconnect-error');
|
||||||
|
return;
|
||||||
|
} finally {
|
||||||
|
this._reconnectPromise = null;
|
||||||
|
this._reconnectResolve = null;
|
||||||
|
this._reconnectReject = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
sendQueuedMsgs();
|
sendQueuedMsgs();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -201,13 +263,13 @@ class WsRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
close() {
|
close(code = WS_CLOSE_CODES.NormalClosure) {
|
||||||
this.closedGracefully = true;
|
this.closedGracefully = true;
|
||||||
this.logger.debug('WsRequestor:close closing socket');
|
this.logger.debug(`WsRequestor:close closing socket with code ${code}`);
|
||||||
this._stopPingTimer();
|
this._stopPingTimer();
|
||||||
try {
|
try {
|
||||||
if (this.ws) {
|
if (this.ws) {
|
||||||
this.ws.close(1000);
|
this.ws.close(code);
|
||||||
this.ws.removeAllListeners();
|
this.ws.removeAllListeners();
|
||||||
this.ws = null;
|
this.ws = null;
|
||||||
}
|
}
|
||||||
@@ -346,7 +408,10 @@ class WsRequestor extends BaseRequestor {
|
|||||||
/* messages must be JSON format */
|
/* messages must be JSON format */
|
||||||
try {
|
try {
|
||||||
const obj = JSON.parse(content);
|
const obj = JSON.parse(content);
|
||||||
const {type, msgid, command, call_sid = this.call_sid, queueCommand = false, data} = obj;
|
this.logger.debug({obj}, 'WsRequestor:_onMessage - received message');
|
||||||
|
//const {type, msgid, command, call_sid = this.call_sid, queueCommand = false, data} = obj;
|
||||||
|
const {type, msgid, command, queueCommand = false, tool_call_id, data} = obj;
|
||||||
|
const call_sid = obj.callSid || this.call_sid;
|
||||||
|
|
||||||
//this.logger.debug({obj}, 'WsRequestor:request websocket: received');
|
//this.logger.debug({obj}, 'WsRequestor:request websocket: received');
|
||||||
assert.ok(type, 'type property not supplied');
|
assert.ok(type, 'type property not supplied');
|
||||||
@@ -359,8 +424,8 @@ class WsRequestor extends BaseRequestor {
|
|||||||
|
|
||||||
case 'command':
|
case 'command':
|
||||||
assert.ok(command, 'command property not supplied');
|
assert.ok(command, 'command property not supplied');
|
||||||
assert.ok(data, 'data property not supplied');
|
assert.ok(data || MTYPE_NO_DATA.includes(command), 'data property not supplied');
|
||||||
this._recvCommand(msgid, command, call_sid, queueCommand, data);
|
this._recvCommand(msgid, command, call_sid, queueCommand, tool_call_id, data);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -368,6 +433,21 @@ class WsRequestor extends BaseRequestor {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.info({err, content}, 'WsRequestor:_onMessage - invalid incoming message');
|
this.logger.info({err, content}, 'WsRequestor:_onMessage - invalid incoming message');
|
||||||
|
const params = {
|
||||||
|
msg: 'InvalidMessage',
|
||||||
|
details: err.message,
|
||||||
|
content: Buffer.from(content).toString('utf-8')
|
||||||
|
};
|
||||||
|
const {writeAlerts, AlertType} = this.Alerter;
|
||||||
|
writeAlerts({
|
||||||
|
account_sid: this.account_sid,
|
||||||
|
alert_type: AlertType.INVALID_APP_PAYLOAD,
|
||||||
|
target_sid: this.call_sid,
|
||||||
|
message: err.message,
|
||||||
|
|
||||||
|
}).catch((err) => this.logger.info({err}, 'Error generating alert for invalid message'));
|
||||||
|
this.request('jambonz:error', '/error', params)
|
||||||
|
.catch((err) => this.logger.debug({err}, 'WsRequestor:_onMessage - Error sending'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,10 +464,10 @@ class WsRequestor extends BaseRequestor {
|
|||||||
success && success(data);
|
success && success(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
_recvCommand(msgid, command, call_sid, queueCommand, data) {
|
_recvCommand(msgid, command, call_sid, queueCommand, tool_call_id, data) {
|
||||||
// TODO: validate command
|
// TODO: validate command
|
||||||
this.logger.debug({msgid, command, call_sid, queueCommand, data}, 'received command');
|
this.logger.debug({msgid, command, call_sid, queueCommand, data}, 'received command');
|
||||||
this.emit('command', {msgid, command, call_sid, queueCommand, data});
|
this.emit('command', {msgid, command, call_sid, queueCommand, tool_call_id, data});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
17037
package-lock.json
generated
17037
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
71
package.json
71
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "jambonz-feature-server",
|
"name": "jambonz-feature-server",
|
||||||
"version": "0.8.6",
|
"version": "0.9.3",
|
||||||
"main": "app.js",
|
"main": "app.js",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 18.x"
|
"node": ">= 18.x"
|
||||||
@@ -25,57 +25,56 @@
|
|||||||
"jslint:fix": "eslint app.js tracer.js lib --fix"
|
"jslint:fix": "eslint app.js tracer.js lib --fix"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@aws-sdk/client-auto-scaling": "^3.360.0",
|
"@aws-sdk/client-auto-scaling": "^3.549.0",
|
||||||
"@aws-sdk/client-sns": "^3.360.0",
|
"@aws-sdk/client-sns": "^3.549.0",
|
||||||
"@jambonz/db-helpers": "^0.9.3",
|
"@jambonz/db-helpers": "^0.9.6",
|
||||||
"@jambonz/http-health-check": "^0.0.1",
|
"@jambonz/http-health-check": "^0.0.1",
|
||||||
"@jambonz/mw-registrar": "^0.2.4",
|
"@jambonz/mw-registrar": "^0.2.7",
|
||||||
"@jambonz/realtimedb-helpers": "^0.8.7",
|
"@jambonz/realtimedb-helpers": "^0.8.13",
|
||||||
"@jambonz/speech-utils": "^0.0.44",
|
"@jambonz/speech-utils": "^0.2.3",
|
||||||
"@jambonz/stats-collector": "^0.1.9",
|
"@jambonz/stats-collector": "^0.1.10",
|
||||||
"@jambonz/time-series": "^0.2.8",
|
"@jambonz/time-series": "^0.2.13",
|
||||||
"@jambonz/verb-specifications": "^0.0.64",
|
"@jambonz/verb-specifications": "^0.0.102",
|
||||||
"@opentelemetry/api": "^1.4.0",
|
"@opentelemetry/api": "^1.8.0",
|
||||||
"@opentelemetry/exporter-jaeger": "^1.9.0",
|
"@opentelemetry/exporter-jaeger": "^1.23.0",
|
||||||
"@opentelemetry/exporter-trace-otlp-http": "^0.35.0",
|
"@opentelemetry/exporter-trace-otlp-http": "^0.50.0",
|
||||||
"@opentelemetry/exporter-zipkin": "^1.9.0",
|
"@opentelemetry/exporter-zipkin": "^1.23.0",
|
||||||
"@opentelemetry/instrumentation": "^0.35.0",
|
"@opentelemetry/instrumentation": "^0.50.0",
|
||||||
"@opentelemetry/resources": "^1.9.0",
|
"@opentelemetry/resources": "^1.23.0",
|
||||||
"@opentelemetry/sdk-trace-base": "^1.9.0",
|
"@opentelemetry/sdk-trace-base": "^1.23.0",
|
||||||
"@opentelemetry/sdk-trace-node": "^1.9.0",
|
"@opentelemetry/sdk-trace-node": "^1.23.0",
|
||||||
"@opentelemetry/semantic-conventions": "^1.9.0",
|
"@opentelemetry/semantic-conventions": "^1.23.0",
|
||||||
"bent": "^7.3.12",
|
"bent": "^7.3.12",
|
||||||
"debug": "^4.3.4",
|
"debug": "^4.3.4",
|
||||||
"deepcopy": "^2.1.0",
|
"deepcopy": "^2.1.0",
|
||||||
"drachtio-fsmrf": "^3.0.39",
|
"drachtio-fsmrf": "^4.0.3",
|
||||||
"drachtio-srf": "^4.5.31",
|
"drachtio-srf": "^5.0.2",
|
||||||
"express": "^4.18.2",
|
"express": "^4.19.2",
|
||||||
"express-validator": "^7.0.1",
|
"express-validator": "^7.0.1",
|
||||||
"ip": "^1.1.9",
|
"moment": "^2.30.1",
|
||||||
"moment": "^2.29.4",
|
"parse-url": "^9.2.0",
|
||||||
"parse-url": "^8.1.0",
|
"pino": "^8.20.0",
|
||||||
"pino": "^8.8.0",
|
|
||||||
"polly-ssml-split": "^0.1.0",
|
"polly-ssml-split": "^0.1.0",
|
||||||
"proxyquire": "^2.1.3",
|
"proxyquire": "^2.1.3",
|
||||||
"sdp-transform": "^2.14.1",
|
"sdp-transform": "^2.15.0",
|
||||||
"short-uuid": "^4.2.2",
|
"short-uuid": "^5.1.0",
|
||||||
"sinon": "^15.0.1",
|
"sinon": "^17.0.1",
|
||||||
"to-snake-case": "^1.0.0",
|
"to-snake-case": "^1.0.0",
|
||||||
"undici": "^5.28.3",
|
"undici": "^7.5.0",
|
||||||
"uuid-random": "^1.3.2",
|
"uuid-random": "^1.3.2",
|
||||||
"verify-aws-sns-signature": "^0.1.0",
|
"verify-aws-sns-signature": "^0.1.0",
|
||||||
"ws": "^8.9.0",
|
"ws": "^8.18.0",
|
||||||
"xml2js": "^0.6.2"
|
"xml2js": "^0.6.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"clear-module": "^4.1.2",
|
"clear-module": "^4.1.2",
|
||||||
"eslint": "^7.32.0",
|
"eslint": "7.32.0",
|
||||||
"eslint-plugin-promise": "^4.3.1",
|
"eslint-plugin-promise": "^6.1.1",
|
||||||
"nyc": "^15.1.0",
|
"nyc": "^15.1.0",
|
||||||
"tape": "^5.6.1"
|
"tape": "^5.7.5"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"bufferutil": "^4.0.6",
|
"bufferutil": "^4.0.8",
|
||||||
"utf-8-validate": "^5.0.8"
|
"utf-8-validate": "^6.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -222,3 +222,62 @@ test('test create-call app_json', async(t) => {
|
|||||||
t.error(err);
|
t.error(err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test create-call timeLimit', async(t) => {
|
||||||
|
clearModule.all();
|
||||||
|
const {srf, disconnect} = require('../app');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await connect(srf);
|
||||||
|
|
||||||
|
|
||||||
|
// GIVEN
|
||||||
|
let from = 'create-call-app-json';
|
||||||
|
let account_sid = 'bb845d4b-83a9-4cde-a6e9-50f3743bab3f';
|
||||||
|
|
||||||
|
// Give UAS app time to come up
|
||||||
|
const p = sippUac('uas.xml', '172.38.0.10', from);
|
||||||
|
await waitFor(1000);
|
||||||
|
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
const app_json = `[
|
||||||
|
{
|
||||||
|
"verb": "pause",
|
||||||
|
"length": 7
|
||||||
|
}
|
||||||
|
]`;
|
||||||
|
|
||||||
|
const post = bent('http://127.0.0.1:3000/', 'POST', 'json', 201);
|
||||||
|
post('v1/createCall', {
|
||||||
|
'account_sid':account_sid,
|
||||||
|
"call_hook": {
|
||||||
|
"url": "http://127.0.0.1:3100/",
|
||||||
|
"method": "POST",
|
||||||
|
"username": "username",
|
||||||
|
"password": "password"
|
||||||
|
},
|
||||||
|
app_json,
|
||||||
|
"from": from,
|
||||||
|
"to": {
|
||||||
|
"type": "phone",
|
||||||
|
"number": "15583084809"
|
||||||
|
},
|
||||||
|
"timeLimit": 1,
|
||||||
|
"speech_recognizer_vendor": "google",
|
||||||
|
"speech_recognizer_language": "en"
|
||||||
|
});
|
||||||
|
|
||||||
|
//THEN
|
||||||
|
await p;
|
||||||
|
const endTime = Date.now();
|
||||||
|
|
||||||
|
t.ok(endTime - startTime < 2000, 'create-call: timeLimit is respected');
|
||||||
|
|
||||||
|
disconnect();
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`error received: ${err}`);
|
||||||
|
disconnect();
|
||||||
|
t.error(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
/* SQLEditor (MySQL (2))*/
|
/* SQLEditor (MySQL (2))*/
|
||||||
|
|
||||||
SET FOREIGN_KEY_CHECKS=0;
|
SET FOREIGN_KEY_CHECKS=0;
|
||||||
|
|
||||||
DROP TABLE IF EXISTS account_static_ips;
|
DROP TABLE IF EXISTS account_static_ips;
|
||||||
@@ -53,6 +54,8 @@ DROP TABLE IF EXISTS signup_history;
|
|||||||
|
|
||||||
DROP TABLE IF EXISTS smpp_addresses;
|
DROP TABLE IF EXISTS smpp_addresses;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS google_custom_voices;
|
||||||
|
|
||||||
DROP TABLE IF EXISTS speech_credentials;
|
DROP TABLE IF EXISTS speech_credentials;
|
||||||
|
|
||||||
DROP TABLE IF EXISTS system_information;
|
DROP TABLE IF EXISTS system_information;
|
||||||
@@ -136,6 +139,9 @@ account_sid CHAR(36) NOT NULL,
|
|||||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||||
username VARCHAR(64),
|
username VARCHAR(64),
|
||||||
password VARCHAR(1024),
|
password VARCHAR(1024),
|
||||||
|
allow_direct_app_calling BOOLEAN NOT NULL DEFAULT 1,
|
||||||
|
allow_direct_queue_calling BOOLEAN NOT NULL DEFAULT 1,
|
||||||
|
allow_direct_user_calling BOOLEAN NOT NULL DEFAULT 1,
|
||||||
PRIMARY KEY (client_sid)
|
PRIMARY KEY (client_sid)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -338,11 +344,25 @@ label VARCHAR(64),
|
|||||||
PRIMARY KEY (speech_credential_sid)
|
PRIMARY KEY (speech_credential_sid)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE google_custom_voices
|
||||||
|
(
|
||||||
|
google_custom_voice_sid CHAR(36) NOT NULL UNIQUE ,
|
||||||
|
speech_credential_sid CHAR(36) NOT NULL,
|
||||||
|
model VARCHAR(512) NOT NULL,
|
||||||
|
reported_usage ENUM('REPORTED_USAGE_UNSPECIFIED','REALTIME','OFFLINE') DEFAULT 'REALTIME',
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
voice_cloning_key MEDIUMTEXT,
|
||||||
|
use_voice_cloning_key BOOLEAN DEFAULT false,
|
||||||
|
PRIMARY KEY (google_custom_voice_sid)
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE system_information
|
CREATE TABLE system_information
|
||||||
(
|
(
|
||||||
domain_name VARCHAR(255),
|
domain_name VARCHAR(255),
|
||||||
sip_domain_name VARCHAR(255),
|
sip_domain_name VARCHAR(255),
|
||||||
monitoring_domain_name VARCHAR(255)
|
monitoring_domain_name VARCHAR(255),
|
||||||
|
private_network_cidr VARCHAR(8192),
|
||||||
|
log_level ENUM('info', 'debug') NOT NULL DEFAULT 'info'
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE users
|
CREATE TABLE users
|
||||||
@@ -437,11 +457,14 @@ CREATE TABLE sip_gateways
|
|||||||
sip_gateway_sid CHAR(36),
|
sip_gateway_sid CHAR(36),
|
||||||
ipv4 VARCHAR(128) NOT NULL COMMENT 'ip address or DNS name of the gateway. For gateways providing inbound calling service, ip address is required.',
|
ipv4 VARCHAR(128) NOT NULL COMMENT 'ip address or DNS name of the gateway. For gateways providing inbound calling service, ip address is required.',
|
||||||
netmask INTEGER NOT NULL DEFAULT 32,
|
netmask INTEGER NOT NULL DEFAULT 32,
|
||||||
port INTEGER NOT NULL DEFAULT 5060 COMMENT 'sip signaling port',
|
port INTEGER COMMENT 'sip signaling port',
|
||||||
inbound BOOLEAN NOT NULL COMMENT 'if true, whitelist this IP to allow inbound calls from the gateway',
|
inbound BOOLEAN NOT NULL COMMENT 'if true, whitelist this IP to allow inbound calls from the gateway',
|
||||||
outbound BOOLEAN NOT NULL COMMENT 'if true, include in least-cost routing when placing calls to the PSTN',
|
outbound BOOLEAN NOT NULL COMMENT 'if true, include in least-cost routing when placing calls to the PSTN',
|
||||||
voip_carrier_sid CHAR(36) NOT NULL,
|
voip_carrier_sid CHAR(36) NOT NULL,
|
||||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||||
|
send_options_ping BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
use_sips_scheme BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
pad_crypto BOOLEAN NOT NULL DEFAULT 0,
|
||||||
protocol ENUM('udp','tcp','tls', 'tls/srtp') DEFAULT 'udp' COMMENT 'Outbound call protocol',
|
protocol ENUM('udp','tcp','tls', 'tls/srtp') DEFAULT 'udp' COMMENT 'Outbound call protocol',
|
||||||
PRIMARY KEY (sip_gateway_sid)
|
PRIMARY KEY (sip_gateway_sid)
|
||||||
) COMMENT='A whitelisted sip gateway used for origination/termination';
|
) COMMENT='A whitelisted sip gateway used for origination/termination';
|
||||||
@@ -478,11 +501,19 @@ messaging_hook_sid CHAR(36) COMMENT 'webhook to call for inbound SMS/MMS ',
|
|||||||
app_json TEXT,
|
app_json TEXT,
|
||||||
speech_synthesis_vendor VARCHAR(64) NOT NULL DEFAULT 'google',
|
speech_synthesis_vendor VARCHAR(64) NOT NULL DEFAULT 'google',
|
||||||
speech_synthesis_language VARCHAR(12) NOT NULL DEFAULT 'en-US',
|
speech_synthesis_language VARCHAR(12) NOT NULL DEFAULT 'en-US',
|
||||||
speech_synthesis_voice VARCHAR(64),
|
speech_synthesis_voice VARCHAR(256),
|
||||||
speech_synthesis_label VARCHAR(64),
|
speech_synthesis_label VARCHAR(64),
|
||||||
speech_recognizer_vendor VARCHAR(64) NOT NULL DEFAULT 'google',
|
speech_recognizer_vendor VARCHAR(64) NOT NULL DEFAULT 'google',
|
||||||
speech_recognizer_language VARCHAR(64) NOT NULL DEFAULT 'en-US',
|
speech_recognizer_language VARCHAR(64) NOT NULL DEFAULT 'en-US',
|
||||||
speech_recognizer_label VARCHAR(64),
|
speech_recognizer_label VARCHAR(64),
|
||||||
|
use_for_fallback_speech BOOLEAN DEFAULT false,
|
||||||
|
fallback_speech_synthesis_vendor VARCHAR(64),
|
||||||
|
fallback_speech_synthesis_language VARCHAR(12),
|
||||||
|
fallback_speech_synthesis_voice VARCHAR(256),
|
||||||
|
fallback_speech_synthesis_label VARCHAR(64),
|
||||||
|
fallback_speech_recognizer_vendor VARCHAR(64),
|
||||||
|
fallback_speech_recognizer_language VARCHAR(64),
|
||||||
|
fallback_speech_recognizer_label VARCHAR(64),
|
||||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
record_all_calls BOOLEAN NOT NULL DEFAULT false,
|
record_all_calls BOOLEAN NOT NULL DEFAULT false,
|
||||||
PRIMARY KEY (application_sid)
|
PRIMARY KEY (application_sid)
|
||||||
@@ -525,6 +556,7 @@ siprec_hook_sid CHAR(36),
|
|||||||
record_all_calls BOOLEAN NOT NULL DEFAULT false,
|
record_all_calls BOOLEAN NOT NULL DEFAULT false,
|
||||||
record_format VARCHAR(16) NOT NULL DEFAULT 'mp3',
|
record_format VARCHAR(16) NOT NULL DEFAULT 'mp3',
|
||||||
bucket_credential VARCHAR(8192) COMMENT 'credential used to authenticate with storage service',
|
bucket_credential VARCHAR(8192) COMMENT 'credential used to authenticate with storage service',
|
||||||
|
enable_debug_log BOOLEAN NOT NULL DEFAULT false,
|
||||||
PRIMARY KEY (account_sid)
|
PRIMARY KEY (account_sid)
|
||||||
) COMMENT='An enterprise that uses the platform for comm services';
|
) COMMENT='An enterprise that uses the platform for comm services';
|
||||||
|
|
||||||
@@ -619,6 +651,10 @@ ALTER TABLE speech_credentials ADD FOREIGN KEY service_provider_sid_idxfk_5 (ser
|
|||||||
CREATE INDEX account_sid_idx ON speech_credentials (account_sid);
|
CREATE INDEX account_sid_idx ON speech_credentials (account_sid);
|
||||||
ALTER TABLE speech_credentials ADD FOREIGN KEY account_sid_idxfk_8 (account_sid) REFERENCES accounts (account_sid);
|
ALTER TABLE speech_credentials ADD FOREIGN KEY account_sid_idxfk_8 (account_sid) REFERENCES accounts (account_sid);
|
||||||
|
|
||||||
|
CREATE INDEX google_custom_voice_sid_idx ON google_custom_voices (google_custom_voice_sid);
|
||||||
|
CREATE INDEX speech_credential_sid_idx ON google_custom_voices (speech_credential_sid);
|
||||||
|
ALTER TABLE google_custom_voices ADD FOREIGN KEY speech_credential_sid_idxfk (speech_credential_sid) REFERENCES speech_credentials (speech_credential_sid) ON DELETE CASCADE;
|
||||||
|
|
||||||
CREATE INDEX user_sid_idx ON users (user_sid);
|
CREATE INDEX user_sid_idx ON users (user_sid);
|
||||||
CREATE INDEX email_idx ON users (email);
|
CREATE INDEX email_idx ON users (email);
|
||||||
CREATE INDEX phone_idx ON users (phone);
|
CREATE INDEX phone_idx ON users (phone);
|
||||||
@@ -704,4 +740,5 @@ ALTER TABLE accounts ADD FOREIGN KEY queue_event_hook_sid_idxfk (queue_event_hoo
|
|||||||
ALTER TABLE accounts ADD FOREIGN KEY device_calling_application_sid_idxfk (device_calling_application_sid) REFERENCES applications (application_sid);
|
ALTER TABLE accounts ADD FOREIGN KEY device_calling_application_sid_idxfk (device_calling_application_sid) REFERENCES applications (application_sid);
|
||||||
|
|
||||||
ALTER TABLE accounts ADD FOREIGN KEY siprec_hook_sid_idxfk (siprec_hook_sid) REFERENCES applications (application_sid);
|
ALTER TABLE accounts ADD FOREIGN KEY siprec_hook_sid_idxfk (siprec_hook_sid) REFERENCES applications (application_sid);
|
||||||
SET FOREIGN_KEY_CHECKS=1;
|
|
||||||
|
SET FOREIGN_KEY_CHECKS=1;
|
||||||
|
|||||||
@@ -3,9 +3,8 @@ const { sippUac } = require('./sipp')('test_fs');
|
|||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
const getJSON = bent('json')
|
const getJSON = bent('json')
|
||||||
const clearModule = require('clear-module');
|
const clearModule = require('clear-module');
|
||||||
const {provisionCallHook} = require('./utils')
|
const {provisionCallHook} = require('./utils');
|
||||||
|
const { sleepFor } = require('../lib/utils/helpers');
|
||||||
const sleepFor = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, p) => {
|
process.on('unhandledRejection', (reason, p) => {
|
||||||
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ services:
|
|||||||
ipv4_address: 172.38.0.7
|
ipv4_address: 172.38.0.7
|
||||||
|
|
||||||
drachtio:
|
drachtio:
|
||||||
image: drachtio/drachtio-server:0.8.25-rc8
|
image: drachtio/drachtio-server:0.8.26
|
||||||
restart: always
|
restart: always
|
||||||
command: drachtio --contact "sip:*;transport=udp" --mtu 4096 --address 0.0.0.0 --port 9022
|
command: drachtio --contact "sip:*;transport=udp" --mtu 4096 --address 0.0.0.0 --port 9022
|
||||||
ports:
|
ports:
|
||||||
@@ -57,7 +57,7 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|
||||||
freeswitch:
|
freeswitch:
|
||||||
image: drachtio/drachtio-freeswitch-mrf:0.6.2
|
image: drachtio/drachtio-freeswitch-mrf:0.9.2-4
|
||||||
restart: always
|
restart: always
|
||||||
command: freeswitch --rtp-range-start 20000 --rtp-range-end 20100
|
command: freeswitch --rtp-range-start 20000 --rtp-range-end 20100
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ const { sippUac } = require('./sipp')('test_fs');
|
|||||||
const clearModule = require('clear-module');
|
const clearModule = require('clear-module');
|
||||||
const {provisionCallHook, provisionActionHook, provisionAnyHook} = require('./utils');
|
const {provisionCallHook, provisionActionHook, provisionAnyHook} = require('./utils');
|
||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
|
const { sleepFor } = require('../lib/utils/helpers');
|
||||||
const getJSON = bent('json');
|
const getJSON = bent('json');
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, p) => {
|
process.on('unhandledRejection', (reason, p) => {
|
||||||
@@ -17,8 +18,6 @@ function connect(connectable) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const sleepFor = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
|
|
||||||
|
|
||||||
test('\'enqueue-dequeue\' tests', async(t) => {
|
test('\'enqueue-dequeue\' tests', async(t) => {
|
||||||
|
|
||||||
clearModule.all();
|
clearModule.all();
|
||||||
|
|||||||
@@ -3,10 +3,9 @@ const { sippUac } = require('./sipp')('test_fs');
|
|||||||
const clearModule = require('clear-module');
|
const clearModule = require('clear-module');
|
||||||
const {provisionCallHook, provisionCustomHook, provisionActionHook} = require('./utils')
|
const {provisionCallHook, provisionCustomHook, provisionActionHook} = require('./utils')
|
||||||
const bent = require('bent');
|
const bent = require('bent');
|
||||||
|
const { sleepFor } = require('../lib/utils/helpers');
|
||||||
const getJSON = bent('json')
|
const getJSON = bent('json')
|
||||||
|
|
||||||
const sleepFor = async(ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, p) => {
|
process.on('unhandledRejection', (reason, p) => {
|
||||||
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
||||||
});
|
});
|
||||||
|
|||||||
49
tracer.js
49
tracer.js
@@ -25,29 +25,38 @@ module.exports = (serviceName) => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
let exporter;
|
const exporters = [];
|
||||||
|
|
||||||
if (OTEL_EXPORTER_JAEGER_AGENT_HOST || OTEL_EXPORTER_JAEGER_ENDPOINT) {
|
if (OTEL_EXPORTER_JAEGER_AGENT_HOST || OTEL_EXPORTER_JAEGER_ENDPOINT) {
|
||||||
exporter = new JaegerExporter();
|
exporters.push(new JaegerExporter());
|
||||||
}
|
|
||||||
else if (OTEL_EXPORTER_ZIPKIN_URL) {
|
|
||||||
exporter = new ZipkinExporter({url:OTEL_EXPORTER_ZIPKIN_URL});
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
exporter = new OTLPTraceExporter({
|
|
||||||
url: OTEL_EXPORTER_COLLECTOR_URL
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
provider.addSpanProcessor(new BatchSpanProcessor(exporter, {
|
if (OTEL_EXPORTER_ZIPKIN_URL) {
|
||||||
// The maximum queue size. After the size is reached spans are dropped.
|
exporters.push(new ZipkinExporter({url:OTEL_EXPORTER_ZIPKIN_URL}));
|
||||||
maxQueueSize: 100,
|
}
|
||||||
// The maximum batch size of every export. It must be smaller or equal to maxQueueSize.
|
|
||||||
maxExportBatchSize: 10,
|
if (OTEL_EXPORTER_ZIPKIN_URL) {
|
||||||
// The interval between two consecutive exports
|
exporters.push(new ZipkinExporter({url:OTEL_EXPORTER_ZIPKIN_URL}));
|
||||||
scheduledDelayMillis: 500,
|
}
|
||||||
// How long the export can run before it is cancelled
|
|
||||||
exportTimeoutMillis: 30000,
|
if (OTEL_EXPORTER_COLLECTOR_URL) {
|
||||||
}));
|
exporters.push(new OTLPTraceExporter({
|
||||||
|
url: OTEL_EXPORTER_COLLECTOR_URL
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
exporters.forEach((element) => {
|
||||||
|
provider.addSpanProcessor(new BatchSpanProcessor(element, {
|
||||||
|
// The maximum queue size. After the size is reached spans are dropped.
|
||||||
|
maxQueueSize: 100,
|
||||||
|
// The maximum batch size of every export. It must be smaller or equal to maxQueueSize.
|
||||||
|
maxExportBatchSize: 10,
|
||||||
|
// The interval between two consecutive exports
|
||||||
|
scheduledDelayMillis: 500,
|
||||||
|
// How long the export can run before it is cancelled
|
||||||
|
exportTimeoutMillis: 30000,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
|
// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
|
||||||
provider.register();
|
provider.register();
|
||||||
|
|||||||
Reference in New Issue
Block a user