@miguelmorales13/nestkit 0.31.4 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +234 -0
- package/dist/chunk-2RQINZCR.cjs +17 -0
- package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
- package/dist/chunk-HMHUOXGB.cjs +63 -0
- package/dist/chunk-L2QK2HN5.js +17 -0
- package/dist/chunk-PBAPT3L5.js +63 -0
- package/dist/chunk-QVLTEABJ.cjs +248 -0
- package/dist/chunk-XKI3DJVA.js +248 -0
- package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
- package/dist/payments/index.cjs +6 -5
- package/dist/payments/index.js +2 -1
- package/dist/resilience/index.cjs +48 -262
- package/dist/resilience/index.js +19 -233
- package/dist/security/index.cjs +4 -2
- package/dist/security/index.js +5 -3
- package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
- package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
- package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
- package/dist/telephony/index.cjs +2269 -0
- package/dist/telephony/index.d.ts +20 -0
- package/dist/telephony/index.js +2269 -0
- package/dist/telephony/provider-http.d.ts +35 -0
- package/dist/telephony/relay/access.d.ts +72 -0
- package/dist/telephony/relay/backend.d.ts +81 -0
- package/dist/telephony/relay/index.cjs +483 -0
- package/dist/telephony/relay/index.d.ts +9 -0
- package/dist/telephony/relay/index.js +483 -0
- package/dist/telephony/relay/server.d.ts +89 -0
- package/dist/telephony/relay/session.d.ts +100 -0
- package/dist/telephony/rules/call-limits.d.ts +48 -0
- package/dist/telephony/rules/call-token.d.ts +30 -0
- package/dist/telephony/rules/destination-policy.d.ts +21 -0
- package/dist/telephony/rules/dial-destination.d.ts +21 -0
- package/dist/telephony/rules/event-deduper.d.ts +15 -0
- package/dist/telephony/rules/handoff.d.ts +7 -0
- package/dist/telephony/rules/index.d.ts +20 -0
- package/dist/telephony/rules/opt-out.d.ts +32 -0
- package/dist/telephony/rules/phone.d.ts +9 -0
- package/dist/telephony/rules/provider-gate.d.ts +31 -0
- package/dist/telephony/rules/redact.d.ts +11 -0
- package/dist/telephony/rules/sanitize.d.ts +10 -0
- package/dist/telephony/rules/sliding-window.d.ts +10 -0
- package/dist/telephony/rules/ttl-cache.d.ts +14 -0
- package/dist/telephony/rules/usage-counter.d.ts +16 -0
- package/dist/telephony/telephony.errors.d.ts +46 -0
- package/dist/telephony/telephony.facade.d.ts +71 -0
- package/dist/telephony/telephony.module.d.ts +38 -0
- package/dist/telephony/telephony.options.d.ts +187 -0
- package/dist/telephony/telephony.port.d.ts +421 -0
- package/dist/telephony/telephony.registry.d.ts +24 -0
- package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
- package/dist/telephony/telephony.webhooks.d.ts +53 -0
- package/dist/whatsapp/index.cjs +28 -0
- package/dist/whatsapp/index.js +28 -0
- package/dist/whatsapp/whatsapp-client.d.ts +5 -0
- package/package.json +12 -2
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { decideRelayAccess, relayAccessConfigFromEnv, relayLimitsFromEnv, DEFAULT_RELAY_LIMITS, } from './access.js';
|
|
2
|
+
export type { RelayAccessInput, RelayAccessDecision, RelayAccessConfig, RelayLimits } from './access.js';
|
|
3
|
+
export { httpRelayBackend, parseTurnReply } from './backend.js';
|
|
4
|
+
export type { RelayBackend, RelayTurn, RelayWho, RelayAction, RelayTurnReply, RelayTurnMeta, RelayCallContext, RelayCallRecord, HttpRelayBackendOptions, } from './backend.js';
|
|
5
|
+
export { RelaySession, waitBeforeHangup, DEFAULT_LIMIT_PHRASE, DEFAULT_FALLBACK_PHRASE, DEFAULT_SAVE_PAUSES_MS, } from './session.js';
|
|
6
|
+
export type { RelaySessionOptions } from './session.js';
|
|
7
|
+
export { startRelayServer } from './server.js';
|
|
8
|
+
export type { RelayServer, RelayServerOptions } from './server.js';
|
|
9
|
+
export { HANDOFF_DATA, isHandoffRequested } from '../rules/handoff.js';
|
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HANDOFF_DATA,
|
|
3
|
+
SlidingWindowLimiter,
|
|
4
|
+
isHandoffRequested,
|
|
5
|
+
redactText
|
|
6
|
+
} from "../../chunk-PBAPT3L5.js";
|
|
7
|
+
import {
|
|
8
|
+
constantTimeEqual
|
|
9
|
+
} from "../../chunk-L2QK2HN5.js";
|
|
10
|
+
import "../../chunk-D3DDJWUD.js";
|
|
11
|
+
|
|
12
|
+
// src/telephony/relay/access.ts
|
|
13
|
+
function decideRelayAccess(input) {
|
|
14
|
+
if (input.origin) return { ok: false, status: 403, message: "Origen no permitido." };
|
|
15
|
+
if (input.requireSecureTransport && input.forwardedProto && input.forwardedProto.split(",")[0].trim().toLowerCase() !== "https") {
|
|
16
|
+
return { ok: false, status: 426, message: "Se requiere conexi\xF3n cifrada (wss)." };
|
|
17
|
+
}
|
|
18
|
+
if (input.ipAttemptsAllowed === false) return { ok: false, status: 429, message: "Demasiados intentos." };
|
|
19
|
+
if (input.requireSecret && !input.expectedSecret) {
|
|
20
|
+
return { ok: false, status: 503, message: "Servidor de voz sin configurar." };
|
|
21
|
+
}
|
|
22
|
+
if (input.expectedSecret) {
|
|
23
|
+
if (!input.receivedKey || !constantTimeEqual(input.receivedKey, input.expectedSecret)) {
|
|
24
|
+
return { ok: false, status: 401, message: "No autorizado." };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (input.connections >= input.maxConnections) {
|
|
28
|
+
return { ok: false, status: 503, message: "Servidor de voz ocupado." };
|
|
29
|
+
}
|
|
30
|
+
return { ok: true };
|
|
31
|
+
}
|
|
32
|
+
function relayAccessConfigFromEnv(env = process.env) {
|
|
33
|
+
const secret = env.RELAY_SECRET?.trim() || void 0;
|
|
34
|
+
const requireSecret = env.NODE_ENV === "production";
|
|
35
|
+
if (requireSecret && !secret) {
|
|
36
|
+
throw new Error("Falta RELAY_SECRET: en producci\xF3n el servidor de voz no arranca sin \xE9l.");
|
|
37
|
+
}
|
|
38
|
+
return { secret, requireSecret };
|
|
39
|
+
}
|
|
40
|
+
var DEFAULT_RELAY_LIMITS = {
|
|
41
|
+
maxConnections: 100,
|
|
42
|
+
maxBytesPerMessage: 64 * 1024,
|
|
43
|
+
setupWaitMs: 1e4,
|
|
44
|
+
maxDurationMs: 8 * 6e4 + 3e4,
|
|
45
|
+
shutdownGraceMs: 55e3,
|
|
46
|
+
maxConnectsPerIpPerMinute: 30,
|
|
47
|
+
maxMessagesPerWindow: 200,
|
|
48
|
+
messageWindowMs: 1e4,
|
|
49
|
+
maxBufferedBytes: 1024 * 1024,
|
|
50
|
+
idleTimeoutSeconds: 120
|
|
51
|
+
};
|
|
52
|
+
function relayLimitsFromEnv(env = process.env, defaults = DEFAULT_RELAY_LIMITS) {
|
|
53
|
+
const n = (v, fallback) => {
|
|
54
|
+
const x = Number(v);
|
|
55
|
+
return Number.isFinite(x) && x > 0 ? x : fallback;
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
maxConnections: n(env.RELAY_MAX_CONNECTIONS, defaults.maxConnections),
|
|
59
|
+
maxBytesPerMessage: n(env.RELAY_MAX_BYTES_PER_MESSAGE, defaults.maxBytesPerMessage),
|
|
60
|
+
setupWaitMs: n(env.RELAY_SETUP_WAIT_MS, defaults.setupWaitMs),
|
|
61
|
+
// Se puede bajar, no ampliar: el tope duro de duración es del servidor.
|
|
62
|
+
maxDurationMs: Math.min(defaults.maxDurationMs, n(env.RELAY_MAX_DURATION_MS, defaults.maxDurationMs)),
|
|
63
|
+
shutdownGraceMs: n(env.RELAY_SHUTDOWN_GRACE_MS, defaults.shutdownGraceMs),
|
|
64
|
+
maxConnectsPerIpPerMinute: n(env.RELAY_MAX_CONNECTS_PER_IP_PER_MINUTE, defaults.maxConnectsPerIpPerMinute),
|
|
65
|
+
maxMessagesPerWindow: n(env.RELAY_MAX_MESSAGES_PER_WINDOW, defaults.maxMessagesPerWindow),
|
|
66
|
+
messageWindowMs: n(env.RELAY_MESSAGE_WINDOW_MS, defaults.messageWindowMs),
|
|
67
|
+
maxBufferedBytes: n(env.RELAY_MAX_BUFFERED_BYTES, defaults.maxBufferedBytes),
|
|
68
|
+
idleTimeoutSeconds: n(env.RELAY_IDLE_TIMEOUT_SECONDS, defaults.idleTimeoutSeconds)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/telephony/relay/backend.ts
|
|
73
|
+
var ACTIONS = ["continue", "end", "handoff"];
|
|
74
|
+
function parseTurnReply(body) {
|
|
75
|
+
const envelope = body;
|
|
76
|
+
const value = typeof envelope?.success === "boolean" ? envelope.success ? envelope.data : null : body;
|
|
77
|
+
if (typeof value?.reply !== "string" || !value.reply.trim() || !ACTIONS.includes(value.action)) {
|
|
78
|
+
throw new Error("El API respondi\xF3 un turno ilegible.");
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
reply: value.reply,
|
|
82
|
+
action: value.action,
|
|
83
|
+
outcome: typeof value.outcome === "string" ? value.outcome : "",
|
|
84
|
+
summary: typeof value.summary === "string" ? value.summary : "",
|
|
85
|
+
...value.data && typeof value.data === "object" ? { data: value.data } : {}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function httpRelayBackend(options) {
|
|
89
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
90
|
+
if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(base) && !options.allowInsecure) {
|
|
91
|
+
throw new Error("httpRelayBackend: `baseUrl` debe ser https:// (usa `allowInsecure` solo en una red privada).");
|
|
92
|
+
}
|
|
93
|
+
const paths = { turn: "turn", progress: "progress", finish: "finish", session: "session", ...options.paths };
|
|
94
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
95
|
+
const post = async (path, body, timeoutMs, ignoreMissing = false) => {
|
|
96
|
+
const r = await doFetch(`${base}/${path}`, {
|
|
97
|
+
method: "POST",
|
|
98
|
+
headers: { "Content-Type": "application/json" },
|
|
99
|
+
body: JSON.stringify(body),
|
|
100
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
101
|
+
});
|
|
102
|
+
if (ignoreMissing && r.status === 404) return void 0;
|
|
103
|
+
if (!r.ok) throw new Error(`El API respondi\xF3 ${r.status} en ${path}.`);
|
|
104
|
+
return r.json().catch(() => void 0);
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
async turn(token, said, history, meta) {
|
|
108
|
+
return parseTurnReply(await post(paths.turn, { t: token, said, history, ...meta }, options.turnTimeoutMs ?? 9e3));
|
|
109
|
+
},
|
|
110
|
+
async progress(token, record) {
|
|
111
|
+
await post(paths.progress, { t: token, ...record }, 1e3, true);
|
|
112
|
+
},
|
|
113
|
+
async finish(token, record) {
|
|
114
|
+
await post(paths.finish, { t: token, ...record }, options.finishTimeoutMs ?? 15e3);
|
|
115
|
+
},
|
|
116
|
+
async validate(token, call) {
|
|
117
|
+
const r = await doFetch(`${base}/${paths.session}`, {
|
|
118
|
+
method: "POST",
|
|
119
|
+
headers: { "Content-Type": "application/json" },
|
|
120
|
+
body: JSON.stringify({ t: token, ...call ? { callId: call.callId, from: call.from } : {} }),
|
|
121
|
+
signal: AbortSignal.timeout(3e3)
|
|
122
|
+
});
|
|
123
|
+
if (r.status === 401) return false;
|
|
124
|
+
if (!r.ok) throw new Error(`El API respondi\xF3 ${r.status} en ${paths.session}.`);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/telephony/relay/session.ts
|
|
131
|
+
var DEFAULT_LIMIT_PHRASE = "Gracias por tu llamada. Para atenderte mejor, te paso con una persona.";
|
|
132
|
+
var DEFAULT_FALLBACK_PHRASE = "Disculpa, tuve un problema. Te paso con una persona.";
|
|
133
|
+
var DEFAULT_SAVE_PAUSES_MS = [500, 1e3, 5e3, 15e3, 3e4];
|
|
134
|
+
var waitBeforeHangup = (text) => Math.min(12e3, 600 + text.length * 70);
|
|
135
|
+
var RelaySession = class {
|
|
136
|
+
constructor(backend, send, options = {}) {
|
|
137
|
+
this.backend = backend;
|
|
138
|
+
this.send = send;
|
|
139
|
+
this.token = null;
|
|
140
|
+
this.callId = "unknown-call";
|
|
141
|
+
this.from = null;
|
|
142
|
+
this.transcript = [];
|
|
143
|
+
this.summary = "";
|
|
144
|
+
this.data = {};
|
|
145
|
+
this.failed = false;
|
|
146
|
+
this.finished = false;
|
|
147
|
+
this.timedOut = false;
|
|
148
|
+
this.queue = Promise.resolve();
|
|
149
|
+
this.callerTurns = 0;
|
|
150
|
+
this.saved = null;
|
|
151
|
+
/** La llamada ya armada que aún no se guarda ni se ha dado por perdida. */
|
|
152
|
+
this.pending = null;
|
|
153
|
+
this.maxTurns = options.maxTurns ?? 40;
|
|
154
|
+
this.limitPhrase = options.limitPhrase ?? DEFAULT_LIMIT_PHRASE;
|
|
155
|
+
this.fallbackPhrase = options.fallbackPhrase ?? DEFAULT_FALLBACK_PHRASE;
|
|
156
|
+
this.outcomes = { empty: "no_message", handoff: "handoff", failure: "failure", ...options.outcomes };
|
|
157
|
+
this.pauses = options.savePausesMs ?? DEFAULT_SAVE_PAUSES_MS;
|
|
158
|
+
this.wait = options.wait ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
159
|
+
this.now = options.now ?? Date.now;
|
|
160
|
+
this.closeSocket = options.close ?? (() => {
|
|
161
|
+
});
|
|
162
|
+
this.log = options.log ?? ((line) => console.error(line));
|
|
163
|
+
this.outcome = this.outcomes.empty;
|
|
164
|
+
this.startedAt = new Date(this.now());
|
|
165
|
+
}
|
|
166
|
+
/** ¿Ya presentó un token que el API aceptó? El servidor cierra el socket que no lo logra a tiempo. */
|
|
167
|
+
get hasToken() {
|
|
168
|
+
return this.token !== null;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Se agotó el tiempo de la llamada (el servidor lo mide con un temporizador real): se despide y pasa a la persona.
|
|
172
|
+
* Entra por la misma cola que los mensajes del proveedor, así no se pisa con una respuesta a medias.
|
|
173
|
+
*/
|
|
174
|
+
forceEndByTimeout() {
|
|
175
|
+
this.timedOut = true;
|
|
176
|
+
this.queue = this.queue.then(() => this.endByLimit()).catch(() => void 0);
|
|
177
|
+
return this.queue;
|
|
178
|
+
}
|
|
179
|
+
async endByLimit() {
|
|
180
|
+
if (this.finished || !this.token) return;
|
|
181
|
+
this.finished = true;
|
|
182
|
+
this.transcript.push({ who: "agent", text: this.limitPhrase });
|
|
183
|
+
this.outcome = this.outcomes.handoff;
|
|
184
|
+
this.technicalCause = "limit";
|
|
185
|
+
this.sendProgress();
|
|
186
|
+
this.send({ type: "text", token: this.limitPhrase, last: true });
|
|
187
|
+
await this.wait(waitBeforeHangup(this.limitPhrase));
|
|
188
|
+
this.send({ type: "end", handoffData: HANDOFF_DATA });
|
|
189
|
+
}
|
|
190
|
+
/** Un mensaje del proveedor. Se atienden de uno en uno: no se contesta una frase antes de la anterior. */
|
|
191
|
+
onMessage(raw) {
|
|
192
|
+
let message;
|
|
193
|
+
try {
|
|
194
|
+
message = JSON.parse(raw);
|
|
195
|
+
} catch {
|
|
196
|
+
return Promise.resolve();
|
|
197
|
+
}
|
|
198
|
+
this.queue = this.queue.then(() => this.handle(message)).catch(() => void 0);
|
|
199
|
+
return this.queue;
|
|
200
|
+
}
|
|
201
|
+
async handle(m) {
|
|
202
|
+
switch (m.type) {
|
|
203
|
+
case "setup":
|
|
204
|
+
this.token = typeof m.customParameters?.t === "string" ? m.customParameters.t : null;
|
|
205
|
+
this.greeting = typeof m.customParameters?.greeting === "string" ? m.customParameters.greeting : void 0;
|
|
206
|
+
this.from = typeof m.from === "string" ? m.from : null;
|
|
207
|
+
if (typeof m.callSid === "string" && m.callSid) this.callId = m.callSid.slice(0, 64);
|
|
208
|
+
this.startedAt = new Date(this.now());
|
|
209
|
+
if (this.token && this.backend.validate) {
|
|
210
|
+
try {
|
|
211
|
+
if (!await this.backend.validate(this.token, { callId: this.callId, from: this.from })) {
|
|
212
|
+
this.token = null;
|
|
213
|
+
this.closeSocket();
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return;
|
|
219
|
+
case "prompt":
|
|
220
|
+
if (m.last === false) return;
|
|
221
|
+
return this.respond(String(m.voicePrompt ?? "").trim());
|
|
222
|
+
default:
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async respond(said) {
|
|
227
|
+
if (!said || this.finished || this.timedOut || !this.token) return;
|
|
228
|
+
const history = [...this.transcript];
|
|
229
|
+
this.transcript.push({ who: "caller", text: said });
|
|
230
|
+
if (++this.callerTurns > this.maxTurns) return this.endByLimit();
|
|
231
|
+
let reply;
|
|
232
|
+
try {
|
|
233
|
+
reply = await this.backend.turn(this.token, said, history, {
|
|
234
|
+
from: this.from,
|
|
235
|
+
...this.greeting ? { greeting: this.greeting } : {}
|
|
236
|
+
});
|
|
237
|
+
} catch {
|
|
238
|
+
this.failed = true;
|
|
239
|
+
this.technicalCause = "service_failure";
|
|
240
|
+
reply = {
|
|
241
|
+
reply: this.fallbackPhrase,
|
|
242
|
+
action: "handoff",
|
|
243
|
+
outcome: this.outcomes.handoff,
|
|
244
|
+
summary: this.summary
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
this.transcript.push({ who: "agent", text: reply.reply });
|
|
248
|
+
this.outcome = reply.outcome;
|
|
249
|
+
this.summary = reply.summary;
|
|
250
|
+
for (const [key, value] of Object.entries(reply.data ?? {})) if (value != null) this.data[key] = value;
|
|
251
|
+
if (this.failed) this.sendProgress();
|
|
252
|
+
this.send({ type: "text", token: reply.reply, last: true });
|
|
253
|
+
if (reply.action === "continue") return;
|
|
254
|
+
this.finished = true;
|
|
255
|
+
await this.wait(waitBeforeHangup(reply.reply));
|
|
256
|
+
this.send(
|
|
257
|
+
reply.action === "handoff" ? { type: "end", handoffData: HANDOFF_DATA } : { type: "end" }
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Se cerró el WebSocket (colgó el llamante o terminó la sesión): se guarda la llamada. Es idempotente: quien la
|
|
262
|
+
* llame de nuevo espera el mismo guardado.
|
|
263
|
+
*/
|
|
264
|
+
onClose() {
|
|
265
|
+
return this.saved ??= this.save();
|
|
266
|
+
}
|
|
267
|
+
/** El proceso se apaga y la llamada sigue sin guardarse: queda dicho cuál, una vez y sin datos del llamante. */
|
|
268
|
+
giveUp(reason) {
|
|
269
|
+
if (!this.pending && !this.token) return;
|
|
270
|
+
this.logLost(reason, this.pending);
|
|
271
|
+
this.pending = null;
|
|
272
|
+
this.token = null;
|
|
273
|
+
}
|
|
274
|
+
logLost(reason, record, attempts) {
|
|
275
|
+
this.log(
|
|
276
|
+
`[voz] LLAMADA SIN GUARDAR callId=${this.callId} startedAt=${this.startedAt.toISOString()} ` + (record ? `outcome=${record.outcome} durationSeconds=${record.durationSeconds} turns=${record.transcript.length} ` : "") + (attempts ? `attempts=${attempts} ` : "") + `reason=${reason}`
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
record() {
|
|
280
|
+
return {
|
|
281
|
+
startedAt: this.startedAt.toISOString(),
|
|
282
|
+
durationSeconds: Math.max(0, Math.round((this.now() - this.startedAt.getTime()) / 1e3)),
|
|
283
|
+
from: this.from,
|
|
284
|
+
outcome: this.failed ? this.outcomes.failure : this.outcome,
|
|
285
|
+
summary: this.summary,
|
|
286
|
+
data: { ...this.data },
|
|
287
|
+
transcript: [...this.transcript],
|
|
288
|
+
...this.greeting ? { greeting: this.greeting } : {},
|
|
289
|
+
...this.technicalCause ? { technicalCause: this.technicalCause } : {}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
sendProgress() {
|
|
293
|
+
if (!this.token || !this.backend.progress) return;
|
|
294
|
+
void this.backend.progress(this.token, this.record()).catch(() => {
|
|
295
|
+
this.log(`[voz] No se confirm\xF3 el avance callId=${this.callId}`);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
async save() {
|
|
299
|
+
await this.queue;
|
|
300
|
+
if (!this.token) return;
|
|
301
|
+
const token = this.token;
|
|
302
|
+
this.token = null;
|
|
303
|
+
const record = this.record();
|
|
304
|
+
if (!record.transcript.some((t) => t.who === "caller")) record.outcome = this.outcomes.empty;
|
|
305
|
+
this.pending = record;
|
|
306
|
+
for (let attempt = 0; ; attempt++) {
|
|
307
|
+
try {
|
|
308
|
+
await this.backend.finish(token, record);
|
|
309
|
+
this.pending = null;
|
|
310
|
+
return;
|
|
311
|
+
} catch {
|
|
312
|
+
const pause = this.pauses[attempt];
|
|
313
|
+
if (pause === void 0) {
|
|
314
|
+
if (this.pending) this.logLost("finish sin confirmaci\xF3n del API", record, attempt + 1);
|
|
315
|
+
this.pending = null;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
await this.wait(pause);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// src/telephony/relay/server.ts
|
|
325
|
+
function startRelayServer(options) {
|
|
326
|
+
const bun = globalThis.Bun;
|
|
327
|
+
const serve = options.serve ?? (bun ? (o) => bun.serve(o) : void 0);
|
|
328
|
+
if (!serve) {
|
|
329
|
+
throw new Error("startRelayServer requiere Bun (usa RelaySession con tu propio servidor de sockets en otro runtime).");
|
|
330
|
+
}
|
|
331
|
+
const access = options.secret !== void 0 || options.requireSecret !== void 0 ? { secret: options.secret, requireSecret: options.requireSecret ?? false } : relayAccessConfigFromEnv();
|
|
332
|
+
const limits = { ...relayLimitsFromEnv(), ...options.limits };
|
|
333
|
+
const write = options.log ?? ((line) => console.error(line));
|
|
334
|
+
const log = (line) => write(redactText(line, [access.secret]));
|
|
335
|
+
const secureOnly = options.requireSecureTransport ?? access.requireSecret;
|
|
336
|
+
const connects = new SlidingWindowLimiter(limits.maxConnectsPerIpPerMinute, 6e4);
|
|
337
|
+
const sourceIp = (req, srv) => {
|
|
338
|
+
if (options.trustProxy) {
|
|
339
|
+
const hop = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
|
|
340
|
+
if (hop) return hop;
|
|
341
|
+
}
|
|
342
|
+
return srv.requestIP?.(req)?.address ?? "unknown";
|
|
343
|
+
};
|
|
344
|
+
const path = options.path ?? "/relay";
|
|
345
|
+
const healthPath = options.healthPath ?? "/health";
|
|
346
|
+
let connections = 0;
|
|
347
|
+
let shuttingDown = false;
|
|
348
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
349
|
+
const server = serve({
|
|
350
|
+
port: options.port ?? Number(process.env.PORT ?? 4105),
|
|
351
|
+
...options.hostname ? { hostname: options.hostname } : {},
|
|
352
|
+
fetch(req, srv) {
|
|
353
|
+
const url = new URL(req.url);
|
|
354
|
+
if (url.pathname === healthPath) {
|
|
355
|
+
return shuttingDown ? new Response("apagando", { status: 503 }) : new Response("ok");
|
|
356
|
+
}
|
|
357
|
+
if (url.pathname === path) {
|
|
358
|
+
if (shuttingDown) return new Response("Servidor de voz reiniciando.", { status: 503 });
|
|
359
|
+
const decision = decideRelayAccess({
|
|
360
|
+
origin: req.headers.get("origin"),
|
|
361
|
+
receivedKey: url.searchParams.get("k"),
|
|
362
|
+
expectedSecret: access.secret,
|
|
363
|
+
requireSecret: access.requireSecret,
|
|
364
|
+
connections,
|
|
365
|
+
maxConnections: limits.maxConnections,
|
|
366
|
+
forwardedProto: req.headers.get("x-forwarded-proto"),
|
|
367
|
+
requireSecureTransport: secureOnly,
|
|
368
|
+
ipAttemptsAllowed: connects.allow(sourceIp(req, srv))
|
|
369
|
+
});
|
|
370
|
+
if (!decision.ok) return new Response(decision.message, { status: decision.status });
|
|
371
|
+
const ok = srv.upgrade(req, {
|
|
372
|
+
data: {
|
|
373
|
+
session: void 0,
|
|
374
|
+
timers: [],
|
|
375
|
+
messages: new SlidingWindowLimiter(limits.maxMessagesPerWindow, limits.messageWindowMs, 1)
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
return ok ? void 0 : new Response("Se esperaba un WebSocket.", { status: 426 });
|
|
379
|
+
}
|
|
380
|
+
return new Response("No encontrado.", { status: 404 });
|
|
381
|
+
},
|
|
382
|
+
websocket: {
|
|
383
|
+
maxPayloadLength: limits.maxBytesPerMessage,
|
|
384
|
+
idleTimeout: limits.idleTimeoutSeconds,
|
|
385
|
+
open(ws) {
|
|
386
|
+
connections++;
|
|
387
|
+
const session = new RelaySession(options.backend, (m) => {
|
|
388
|
+
if ((ws.getBufferedAmount?.() ?? 0) > limits.maxBufferedBytes) {
|
|
389
|
+
ws.close(1013, "Cliente lento");
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
ws.send(JSON.stringify(m));
|
|
393
|
+
}, {
|
|
394
|
+
...options.session,
|
|
395
|
+
// Siempre el log con redacción: una sesión no puede saltársela con su propio `log`.
|
|
396
|
+
log,
|
|
397
|
+
close: () => ws.close(1008, "Sesi\xF3n inv\xE1lida")
|
|
398
|
+
});
|
|
399
|
+
ws.data.session = session;
|
|
400
|
+
sessions.set(session, () => ws.close(1012, "Reinicio"));
|
|
401
|
+
ws.data.timers = [
|
|
402
|
+
// Sin un `setup` con token válido a tiempo, no hay llamada: se libera el socket.
|
|
403
|
+
setTimeout(() => {
|
|
404
|
+
if (!session.hasToken) ws.close(1008, "Sin sesi\xF3n");
|
|
405
|
+
}, limits.setupWaitMs),
|
|
406
|
+
// Tope de duración: se despide y pasa a la persona; si el socket sigue abierto, se cierra.
|
|
407
|
+
setTimeout(() => {
|
|
408
|
+
void session.forceEndByTimeout().then(() => setTimeout(() => ws.close(1e3, "Tiempo"), 5e3));
|
|
409
|
+
}, limits.maxDurationMs)
|
|
410
|
+
];
|
|
411
|
+
},
|
|
412
|
+
message(ws, message) {
|
|
413
|
+
if (!ws.data.messages.allow("m")) {
|
|
414
|
+
ws.close(1008, "Demasiados mensajes");
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
void ws.data.session.onMessage(typeof message === "string" ? message : Buffer.from(message).toString());
|
|
418
|
+
},
|
|
419
|
+
close(ws) {
|
|
420
|
+
connections = Math.max(0, connections - 1);
|
|
421
|
+
for (const t of ws.data.timers) clearTimeout(t);
|
|
422
|
+
const { session } = ws.data;
|
|
423
|
+
void session.onClose().finally(() => sessions.delete(session));
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
let shutdownPromise = null;
|
|
428
|
+
const shutdown = () => shutdownPromise ??= (async () => {
|
|
429
|
+
shuttingDown = true;
|
|
430
|
+
const saved = [...sessions].map(([session, cut]) => {
|
|
431
|
+
cut();
|
|
432
|
+
return session.onClose();
|
|
433
|
+
});
|
|
434
|
+
let timer;
|
|
435
|
+
await Promise.race([
|
|
436
|
+
Promise.allSettled(saved),
|
|
437
|
+
new Promise((resolve) => timer = setTimeout(resolve, limits.shutdownGraceMs))
|
|
438
|
+
]);
|
|
439
|
+
if (timer) clearTimeout(timer);
|
|
440
|
+
for (const session of sessions.keys()) session.giveUp("apagado del servidor");
|
|
441
|
+
await server.stop(true);
|
|
442
|
+
})();
|
|
443
|
+
if (options.handleSignals ?? true) {
|
|
444
|
+
let signals = 0;
|
|
445
|
+
const onSignal = () => {
|
|
446
|
+
if (++signals > 1) {
|
|
447
|
+
for (const session of sessions.keys()) session.giveUp("apagado del servidor");
|
|
448
|
+
if (options.exitOnSignal ?? true) process.exit(0);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
void shutdown().then(() => {
|
|
452
|
+
if (options.exitOnSignal ?? true) process.exit(0);
|
|
453
|
+
});
|
|
454
|
+
};
|
|
455
|
+
process.on("SIGINT", onSignal);
|
|
456
|
+
process.on("SIGTERM", onSignal);
|
|
457
|
+
}
|
|
458
|
+
return {
|
|
459
|
+
get port() {
|
|
460
|
+
return server.port;
|
|
461
|
+
},
|
|
462
|
+
get connections() {
|
|
463
|
+
return connections;
|
|
464
|
+
},
|
|
465
|
+
shutdown
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
export {
|
|
469
|
+
DEFAULT_FALLBACK_PHRASE,
|
|
470
|
+
DEFAULT_LIMIT_PHRASE,
|
|
471
|
+
DEFAULT_RELAY_LIMITS,
|
|
472
|
+
DEFAULT_SAVE_PAUSES_MS,
|
|
473
|
+
HANDOFF_DATA,
|
|
474
|
+
RelaySession,
|
|
475
|
+
decideRelayAccess,
|
|
476
|
+
httpRelayBackend,
|
|
477
|
+
isHandoffRequested,
|
|
478
|
+
parseTurnReply,
|
|
479
|
+
relayAccessConfigFromEnv,
|
|
480
|
+
relayLimitsFromEnv,
|
|
481
|
+
startRelayServer,
|
|
482
|
+
waitBeforeHangup
|
|
483
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { RelayBackend } from './backend.js';
|
|
2
|
+
import { type RelayLimits } from './access.js';
|
|
3
|
+
import { RelaySession, type RelaySessionOptions } from './session.js';
|
|
4
|
+
import { SlidingWindowLimiter } from '../rules/sliding-window.js';
|
|
5
|
+
/** Lo mínimo de `Bun.serve` que usa el relay (así los tipos públicos no arrastran los de Bun). */
|
|
6
|
+
interface BunSocket {
|
|
7
|
+
data: {
|
|
8
|
+
session: RelaySession;
|
|
9
|
+
timers: ReturnType<typeof setTimeout>[];
|
|
10
|
+
messages: SlidingWindowLimiter;
|
|
11
|
+
};
|
|
12
|
+
send(data: string): void;
|
|
13
|
+
close(code?: number, reason?: string): void;
|
|
14
|
+
/** Bytes encolados sin enviar (cliente lento). */
|
|
15
|
+
getBufferedAmount?(): number;
|
|
16
|
+
}
|
|
17
|
+
interface BunServerLike {
|
|
18
|
+
port: number;
|
|
19
|
+
requestIP?(req: Request): {
|
|
20
|
+
address: string;
|
|
21
|
+
} | null;
|
|
22
|
+
upgrade(req: Request, options: {
|
|
23
|
+
data: BunSocket['data'];
|
|
24
|
+
}): boolean;
|
|
25
|
+
stop(closeActiveConnections?: boolean): void | Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
type BunServe = (options: {
|
|
28
|
+
port: number;
|
|
29
|
+
hostname?: string;
|
|
30
|
+
fetch(req: Request, server: BunServerLike): Response | undefined | Promise<Response | undefined>;
|
|
31
|
+
websocket: {
|
|
32
|
+
maxPayloadLength: number;
|
|
33
|
+
idleTimeout: number;
|
|
34
|
+
open(ws: BunSocket): void;
|
|
35
|
+
message(ws: BunSocket, message: string | Uint8Array): void;
|
|
36
|
+
close(ws: BunSocket): void;
|
|
37
|
+
};
|
|
38
|
+
}) => BunServerLike;
|
|
39
|
+
export interface RelayServerOptions {
|
|
40
|
+
backend: RelayBackend;
|
|
41
|
+
/** Por omisión `PORT` o 4105. Con `0` el sistema elige uno libre (`server.port`). */
|
|
42
|
+
port?: number;
|
|
43
|
+
hostname?: string;
|
|
44
|
+
/** Ruta del WebSocket. Por omisión `/relay`. */
|
|
45
|
+
path?: string;
|
|
46
|
+
/** Ruta del chequeo de salud. Por omisión `/health`. */
|
|
47
|
+
healthPath?: string;
|
|
48
|
+
/** Secreto del `?k=`. Por omisión `RELAY_SECRET`; en producción es obligatorio. */
|
|
49
|
+
secret?: string;
|
|
50
|
+
/** Exigir secreto aunque no sea producción. */
|
|
51
|
+
requireSecret?: boolean;
|
|
52
|
+
/** Rechazar lo que el proxy marque como `http` (`X-Forwarded-Proto`). Por omisión, solo en producción. */
|
|
53
|
+
requireSecureTransport?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Confiar en `X-Forwarded-For` para la IP de origen (solo detrás de un proxy propio). Por omisión `false`: la IP es la
|
|
56
|
+
* del socket, porque la cabecera la puede escribir cualquiera.
|
|
57
|
+
*/
|
|
58
|
+
trustProxy?: boolean;
|
|
59
|
+
limits?: Partial<RelayLimits>;
|
|
60
|
+
session?: RelaySessionOptions;
|
|
61
|
+
/** Registrar `SIGINT`/`SIGTERM` para cerrar ordenadamente y salir del proceso. Por omisión `true`. */
|
|
62
|
+
handleSignals?: boolean;
|
|
63
|
+
/** Llamar a `process.exit(0)` al terminar el cierre por señal. Por omisión `true`. */
|
|
64
|
+
exitOnSignal?: boolean;
|
|
65
|
+
log?: (line: string) => void;
|
|
66
|
+
/** Para pruebas: otra implementación de `Bun.serve`. */
|
|
67
|
+
serve?: BunServe;
|
|
68
|
+
}
|
|
69
|
+
export interface RelayServer {
|
|
70
|
+
readonly port: number;
|
|
71
|
+
/** Conexiones abiertas. */
|
|
72
|
+
readonly connections: number;
|
|
73
|
+
/**
|
|
74
|
+
* Cierre ordenado: deja de recibir llamadas (503 también en la salud), cierra los sockets y espera a que se guarden
|
|
75
|
+
* las llamadas pendientes hasta `shutdownGraceMs`. Lo que no se logre queda en el registro como `LLAMADA SIN GUARDAR`.
|
|
76
|
+
*/
|
|
77
|
+
shutdown(): Promise<void>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Levanta el servidor de voz: el WebSocket al que se conecta Twilio ConversationRelay. Va en su propio proceso para que
|
|
81
|
+
* una llamada larga no le quite recursos al API. **Solo Bun**: usa `Bun.serve` (un WebSocket sin dependencias).
|
|
82
|
+
* Para otro runtime, usa {@link RelaySession} y {@link decideRelayAccess} con tu propio servidor de sockets.
|
|
83
|
+
*
|
|
84
|
+
* Es público, así que se protege solo: rechaza orígenes de navegador, exige el secreto, topa conexiones y tamaño de
|
|
85
|
+
* mensaje, cierra el socket que no presenta en `setupWaitMs` un `setup` con token que el API acepte y corta la llamada
|
|
86
|
+
* que pasa de su duración máxima. Nada se escribe en disco.
|
|
87
|
+
*/
|
|
88
|
+
export declare function startRelayServer(options: RelayServerOptions): RelayServer;
|
|
89
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { RelayBackend } from './backend.js';
|
|
2
|
+
/**
|
|
3
|
+
* Una llamada vista desde el servidor de voz. Twilio ConversationRelay transcribe lo que dice el llamante y lo manda
|
|
4
|
+
* por WebSocket; aquí se lo pasamos al API (que tiene la IA, los datos y los permisos) y devolvemos lo que responde
|
|
5
|
+
* para que el proveedor lo lea en voz alta. La sesión **no sabe de clientes ni guarda llaves**: solo lleva el token de
|
|
6
|
+
* llamada que el API puso en la conexión y lo devuelve en cada aviso.
|
|
7
|
+
*
|
|
8
|
+
* Es una clase sin sockets (recibe `send` y el backend) para probarla sin red. Habla el protocolo de mensajes de
|
|
9
|
+
* ConversationRelay (`setup`, `prompt`, `text`, `end`); otro proveedor necesitaría su propio traductor de mensajes.
|
|
10
|
+
*/
|
|
11
|
+
/** Lo que se dice al llegar al tope de turnos o de duración. */
|
|
12
|
+
export declare const DEFAULT_LIMIT_PHRASE = "Gracias por tu llamada. Para atenderte mejor, te paso con una persona.";
|
|
13
|
+
/** Lo que se dice si el API no contesta a tiempo: se disculpa y la llamada pasa a una persona (nunca se pierde). */
|
|
14
|
+
export declare const DEFAULT_FALLBACK_PHRASE = "Disculpa, tuve un problema. Te paso con una persona.";
|
|
15
|
+
/**
|
|
16
|
+
* Pausas entre los intentos de guardar la llamada al colgar (6 intentos, unos 50 s): un API caído por un despliegue o
|
|
17
|
+
* un corte corto no impide completar el registro.
|
|
18
|
+
*/
|
|
19
|
+
export declare const DEFAULT_SAVE_PAUSES_MS: readonly number[];
|
|
20
|
+
/**
|
|
21
|
+
* Cuánto esperar antes de colgar tras la última frase para no cortarla: lo que tarda en decirse (~70 ms por carácter)
|
|
22
|
+
* más un margen, con tope. El proveedor reproduce el texto a su ritmo y `end` corta la sesión; a verificar con una
|
|
23
|
+
* llamada real.
|
|
24
|
+
*/
|
|
25
|
+
export declare const waitBeforeHangup: (text: string) => number;
|
|
26
|
+
export interface RelaySessionOptions {
|
|
27
|
+
/** Frases del llamante que atiende la IA. Por omisión 40. */
|
|
28
|
+
maxTurns?: number;
|
|
29
|
+
limitPhrase?: string;
|
|
30
|
+
fallbackPhrase?: string;
|
|
31
|
+
/** Resultados que la sesión fija por sí sola. */
|
|
32
|
+
outcomes?: {
|
|
33
|
+
empty?: string;
|
|
34
|
+
handoff?: string;
|
|
35
|
+
failure?: string;
|
|
36
|
+
};
|
|
37
|
+
savePausesMs?: readonly number[];
|
|
38
|
+
/** Pausa (inyectable en pruebas). */
|
|
39
|
+
wait?: (ms: number) => Promise<void>;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
/** Cierra el socket cuando el API rechaza el token del `setup`. */
|
|
42
|
+
close?: () => void;
|
|
43
|
+
/** El registro del servidor: solo recibe fallos, sin datos del llamante. */
|
|
44
|
+
log?: (line: string) => void;
|
|
45
|
+
}
|
|
46
|
+
export declare class RelaySession {
|
|
47
|
+
private readonly backend;
|
|
48
|
+
private readonly send;
|
|
49
|
+
private token;
|
|
50
|
+
private callId;
|
|
51
|
+
private from;
|
|
52
|
+
private greeting;
|
|
53
|
+
private startedAt;
|
|
54
|
+
private readonly transcript;
|
|
55
|
+
private outcome;
|
|
56
|
+
private summary;
|
|
57
|
+
private data;
|
|
58
|
+
private failed;
|
|
59
|
+
private technicalCause;
|
|
60
|
+
private finished;
|
|
61
|
+
private timedOut;
|
|
62
|
+
private queue;
|
|
63
|
+
private callerTurns;
|
|
64
|
+
private saved;
|
|
65
|
+
/** La llamada ya armada que aún no se guarda ni se ha dado por perdida. */
|
|
66
|
+
private pending;
|
|
67
|
+
private readonly maxTurns;
|
|
68
|
+
private readonly limitPhrase;
|
|
69
|
+
private readonly fallbackPhrase;
|
|
70
|
+
private readonly outcomes;
|
|
71
|
+
private readonly pauses;
|
|
72
|
+
private readonly wait;
|
|
73
|
+
private readonly now;
|
|
74
|
+
private readonly closeSocket;
|
|
75
|
+
private readonly log;
|
|
76
|
+
constructor(backend: RelayBackend, send: (message: Record<string, unknown>) => void, options?: RelaySessionOptions);
|
|
77
|
+
/** ¿Ya presentó un token que el API aceptó? El servidor cierra el socket que no lo logra a tiempo. */
|
|
78
|
+
get hasToken(): boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Se agotó el tiempo de la llamada (el servidor lo mide con un temporizador real): se despide y pasa a la persona.
|
|
81
|
+
* Entra por la misma cola que los mensajes del proveedor, así no se pisa con una respuesta a medias.
|
|
82
|
+
*/
|
|
83
|
+
forceEndByTimeout(): Promise<void>;
|
|
84
|
+
private endByLimit;
|
|
85
|
+
/** Un mensaje del proveedor. Se atienden de uno en uno: no se contesta una frase antes de la anterior. */
|
|
86
|
+
onMessage(raw: string): Promise<void>;
|
|
87
|
+
private handle;
|
|
88
|
+
private respond;
|
|
89
|
+
/**
|
|
90
|
+
* Se cerró el WebSocket (colgó el llamante o terminó la sesión): se guarda la llamada. Es idempotente: quien la
|
|
91
|
+
* llame de nuevo espera el mismo guardado.
|
|
92
|
+
*/
|
|
93
|
+
onClose(): Promise<void>;
|
|
94
|
+
/** El proceso se apaga y la llamada sigue sin guardarse: queda dicho cuál, una vez y sin datos del llamante. */
|
|
95
|
+
giveUp(reason: string): void;
|
|
96
|
+
private logLost;
|
|
97
|
+
private record;
|
|
98
|
+
private sendProgress;
|
|
99
|
+
private save;
|
|
100
|
+
}
|