/
pilot.ts
190 lines (163 loc) Β· 6.04 KB
/
pilot.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env node
/* eslint-disable require-jsdoc */
/*
* Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
* http://github.com/fonoster/rox
*
* This file is part of Rox AI
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { CLIENT_EVENTS } from "./events/types";
import { VoiceRequest, VoiceResponse, VoiceServer } from "@fonoster/voice";
import { Cerebro } from "./cerebro";
import { eventsServer } from "./events/server";
import { nanoid } from "nanoid";
import { getIntentsEngine } from "./intents/engines";
import { ServerConfig } from "./types";
import { sendClientEvent } from "./util";
import GoogleASR, { GoogleSpeechConfig } from "@fonoster/googleasr";
import { getLogger, ulogger, ULogType } from "@fonoster/logger";
import GoogleTTS, { GoogleTTSConfig } from "@fonoster/googletts";
import Apps from "@fonoster/apps";
import Secrets from "@fonoster/secrets";
import {
APISERVER_AUTOPILOT_MEDIA_BUSY_MESSAGE,
APISERVER_AUTOPILOT_MEDIA_NOANSWER_MESSAGE
} from "./envs";
const logger = getLogger({ service: "autopilot", filePath: __filename });
export default function pilot(config: ServerConfig) {
logger.info("starting autopilot");
const voiceServer = new VoiceServer({
port: config.port
});
if (config.eventsServerEnabled) eventsServer.start();
logger.verbose("events server enabled = " + config.eventsServerEnabled);
voiceServer.listen(
async (voiceRequest: VoiceRequest, voiceResponse: VoiceResponse) => {
logger.verbose(`new request [sessionId: ${voiceRequest.sessionId}]`, {
voiceRequest
});
try {
if (!voiceRequest.appRef)
throw new Error("invalid voice request: missing appRef");
// If set, we overwrite the configuration with the values obtain from the webhook
const serviceCredentials = {
accessKeyId: voiceRequest.accessKeyId,
accessKeySecret: voiceRequest.sessionToken
};
const apps = new Apps(serviceCredentials);
const secrets = new Secrets(serviceCredentials);
const app = await apps.getApp(voiceRequest.appRef);
logger.verbose("requested app", { app, ref: app.ref });
const ieSecret = await secrets.getSecret(
app.intentsEngineConfig.secretName
);
const intentsEngine = getIntentsEngine(app)(
JSON.parse(ieSecret.secret)
);
intentsEngine?.setProjectId(app.intentsEngineConfig.projectId);
const voiceConfig = {
name: app.speechConfig.voice,
playbackId: nanoid()
};
const speechSecret = await secrets.getSecret(
app.speechConfig.secretName
);
const speechCredentials = {
private_key: JSON.parse(speechSecret.secret).private_key,
client_email: JSON.parse(speechSecret.secret).client_email
};
voiceResponse.use(
new GoogleTTS({
credentials: speechCredentials,
languageCode: config.defaultLanguageCode,
path: config.fileRetentionPolicyDirectory
} as GoogleTTSConfig)
);
voiceResponse.use(
new GoogleASR({
credentials: speechCredentials,
languageCode: config.defaultLanguageCode
} as GoogleSpeechConfig)
);
await voiceResponse.answer();
const eventsClient =
app.enableEvents && config.eventsServerEnabled
? eventsServer.getConnection(voiceRequest.callerNumber)
: null;
sendClientEvent(eventsClient, {
eventName: CLIENT_EVENTS.ANSWERED
});
if (app.initialDtmf) {
await voiceResponse.dtmf({ dtmf: app.initialDtmf });
}
if (
app.intentsEngineConfig.welcomeIntentId &&
intentsEngine.findIntentWithEvent
) {
const response = await intentsEngine.findIntentWithEvent(
// TODO: This should be renamed to welcomeEventId
app.intentsEngineConfig.welcomeIntentId,
{
telephony: {
caller_id: voiceRequest.callerNumber
}
}
);
if (response.effects.length > 0) {
// eslint-disable-next-line no-loops/no-loops
for await (const effect of response.effects) {
if (effect.type === "say") {
await voiceResponse.say(
effect.parameters["response"] as string,
voiceConfig
);
}
}
} else {
logger.warn("no effects found for welcome event", {
eventId: app.intentsEngineConfig.welcomeIntentId
});
}
}
const transfer = app.transferConfig;
transfer.messageNoAnswer = transfer.messageBusy =
transfer.messageBusy || APISERVER_AUTOPILOT_MEDIA_BUSY_MESSAGE;
transfer.messageNoAnswer =
transfer.messageNoAnswer ||
APISERVER_AUTOPILOT_MEDIA_NOANSWER_MESSAGE;
const cerebro = new Cerebro({
voiceRequest,
voiceResponse,
eventsClient,
voiceConfig,
intentsEngine,
activationIntentId: app.activationIntentId,
activationTimeout: app.activationTimeout,
transfer: app.transferConfig,
alternativeLanguageCode: app.speechConfig.languageCode
});
// Open for bussiness
await cerebro.wake();
} catch (e) {
ulogger({
accessKeyId: voiceRequest.accessKeyId,
eventType: ULogType.APP,
level: "error",
message: (e as Error).message
});
}
}
);
}