@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.
Files changed (56) hide show
  1. package/README.md +234 -0
  2. package/dist/chunk-2RQINZCR.cjs +17 -0
  3. package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
  4. package/dist/chunk-HMHUOXGB.cjs +63 -0
  5. package/dist/chunk-L2QK2HN5.js +17 -0
  6. package/dist/chunk-PBAPT3L5.js +63 -0
  7. package/dist/chunk-QVLTEABJ.cjs +248 -0
  8. package/dist/chunk-XKI3DJVA.js +248 -0
  9. package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
  10. package/dist/payments/index.cjs +6 -5
  11. package/dist/payments/index.js +2 -1
  12. package/dist/resilience/index.cjs +48 -262
  13. package/dist/resilience/index.js +19 -233
  14. package/dist/security/index.cjs +4 -2
  15. package/dist/security/index.js +5 -3
  16. package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
  17. package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
  18. package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
  19. package/dist/telephony/index.cjs +2269 -0
  20. package/dist/telephony/index.d.ts +20 -0
  21. package/dist/telephony/index.js +2269 -0
  22. package/dist/telephony/provider-http.d.ts +35 -0
  23. package/dist/telephony/relay/access.d.ts +72 -0
  24. package/dist/telephony/relay/backend.d.ts +81 -0
  25. package/dist/telephony/relay/index.cjs +483 -0
  26. package/dist/telephony/relay/index.d.ts +9 -0
  27. package/dist/telephony/relay/index.js +483 -0
  28. package/dist/telephony/relay/server.d.ts +89 -0
  29. package/dist/telephony/relay/session.d.ts +100 -0
  30. package/dist/telephony/rules/call-limits.d.ts +48 -0
  31. package/dist/telephony/rules/call-token.d.ts +30 -0
  32. package/dist/telephony/rules/destination-policy.d.ts +21 -0
  33. package/dist/telephony/rules/dial-destination.d.ts +21 -0
  34. package/dist/telephony/rules/event-deduper.d.ts +15 -0
  35. package/dist/telephony/rules/handoff.d.ts +7 -0
  36. package/dist/telephony/rules/index.d.ts +20 -0
  37. package/dist/telephony/rules/opt-out.d.ts +32 -0
  38. package/dist/telephony/rules/phone.d.ts +9 -0
  39. package/dist/telephony/rules/provider-gate.d.ts +31 -0
  40. package/dist/telephony/rules/redact.d.ts +11 -0
  41. package/dist/telephony/rules/sanitize.d.ts +10 -0
  42. package/dist/telephony/rules/sliding-window.d.ts +10 -0
  43. package/dist/telephony/rules/ttl-cache.d.ts +14 -0
  44. package/dist/telephony/rules/usage-counter.d.ts +16 -0
  45. package/dist/telephony/telephony.errors.d.ts +46 -0
  46. package/dist/telephony/telephony.facade.d.ts +71 -0
  47. package/dist/telephony/telephony.module.d.ts +38 -0
  48. package/dist/telephony/telephony.options.d.ts +187 -0
  49. package/dist/telephony/telephony.port.d.ts +421 -0
  50. package/dist/telephony/telephony.registry.d.ts +24 -0
  51. package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
  52. package/dist/telephony/telephony.webhooks.d.ts +53 -0
  53. package/dist/whatsapp/index.cjs +28 -0
  54. package/dist/whatsapp/index.js +28 -0
  55. package/dist/whatsapp/whatsapp-client.d.ts +5 -0
  56. package/package.json +12 -2
@@ -0,0 +1,35 @@
1
+ import type { ProviderConfig } from '../resilience/resilience.types.js';
2
+ import { ProviderGate, type ProviderGateOptions } from './rules/provider-gate.js';
3
+ import { TelephonyProviderException, type TelephonyErrorReason } from './telephony.errors.js';
4
+ export { TelephonyProviderException } from './telephony.errors.js';
5
+ /** Cómo un adaptador habla HTTP con su proveedor: tiempo límite, reintentos, concurrencia y cortacircuito. */
6
+ export interface ProviderHttpOptions {
7
+ /** `fetch` a usar (pruebas). Por omisión el global. */
8
+ fetchImpl?: typeof fetch;
9
+ /** Política de `fetchResiliente`: `timeoutMs` (15 s), `reintentos` (2), `backoff`, `sleep` (pruebas). */
10
+ resilience?: ProviderConfig & {
11
+ sleep?: (ms: number) => Promise<void>;
12
+ };
13
+ /** Concurrencia máxima y cortacircuito hacia el proveedor. */
14
+ gate?: ProviderGateOptions | ProviderGate;
15
+ /** Tenant dueño de las credenciales (un 401 es alerta del tenant, no de la plataforma). */
16
+ tenantId?: string;
17
+ }
18
+ export interface ProviderResponse<T> {
19
+ ok: boolean;
20
+ status: number;
21
+ body: T | undefined;
22
+ headers: Headers;
23
+ }
24
+ /**
25
+ * El cliente HTTP de un adaptador: `fetchResiliente` (tiempo límite, backoff con jitter, `Retry-After`, alertas) dentro
26
+ * de un {@link ProviderGate}. Reutiliza `resilience` de nestkit en vez de inventar su propio reintento. Un POST **solo se
27
+ * reintenta** si trae una cabecera de idempotencia (`I-Twilio-Idempotency-Token`): repetir un envío cobraría dos veces.
28
+ */
29
+ export declare function createProviderHttp(provider: string, options?: ProviderHttpOptions): {
30
+ request: <T>(url: string, init: RequestInit) => Promise<ProviderResponse<T>>;
31
+ gate: ProviderGate;
32
+ };
33
+ export type ProviderHttp = ReturnType<typeof createProviderHttp>;
34
+ /** Traduce una respuesta no-2xx a una excepción con motivo estable; el cuerpo crudo queda solo en `raw`. */
35
+ export declare function providerError(provider: string, r: ProviderResponse<unknown>, codeMap?: Record<number, TelephonyErrorReason>): TelephonyProviderException;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Quién puede abrir el WebSocket del relay. El relay es público (Twilio ConversationRelay llega desde internet), así
3
+ * que lo primero que se decide es si esa conexión merece un socket:
4
+ *
5
+ * - **Origin**: el proveedor no manda `Origin`; un navegador siempre lo manda. Una conexión con `Origin` no es el proveedor.
6
+ * - **Secreto** (`?k=`): la URL `wss://…/relay?k=<secreto>` que el API pone en la contestación debe traerlo
7
+ * (comparación en tiempo constante). En producción es **obligatorio**: sin secreto configurado se rechaza todo.
8
+ * - **Tope de conexiones** simultáneas.
9
+ *
10
+ * Además, cada socket debe presentar un token de llamada que el API valide dentro de los primeros segundos
11
+ * (`RelaySession`): sin eso se cierra.
12
+ */
13
+ export interface RelayAccessInput {
14
+ origin: string | null;
15
+ receivedKey: string | null;
16
+ expectedSecret: string | undefined;
17
+ /** En producción: sin secreto configurado no se acepta ninguna conexión (falla cerrado). */
18
+ requireSecret?: boolean;
19
+ connections: number;
20
+ maxConnections: number;
21
+ /** `X-Forwarded-Proto` del proxy, si lo hay. */
22
+ forwardedProto?: string | null;
23
+ /** Rechazar lo que llegue por una conexión sin cifrar (el proxy dice `http`). En producción es lo esperado. */
24
+ requireSecureTransport?: boolean;
25
+ /** Conexiones nuevas de esta IP en el último minuto (la cuenta la lleva el servidor). */
26
+ ipAttemptsAllowed?: boolean;
27
+ }
28
+ export type RelayAccessDecision = {
29
+ ok: true;
30
+ } | {
31
+ ok: false;
32
+ status: number;
33
+ message: string;
34
+ };
35
+ export declare function decideRelayAccess(input: RelayAccessInput): RelayAccessDecision;
36
+ export interface RelayAccessConfig {
37
+ secret: string | undefined;
38
+ requireSecret: boolean;
39
+ }
40
+ /**
41
+ * Configuración de acceso a partir del entorno (`RELAY_SECRET`, `NODE_ENV`). Lanza un error claro si en producción
42
+ * falta el secreto: el servidor no debe arrancar a medias.
43
+ */
44
+ export declare function relayAccessConfigFromEnv(env?: Record<string, string | undefined>): RelayAccessConfig;
45
+ /** Topes del servidor de voz con su valor por omisión; todos se pueden ajustar por entorno. */
46
+ export interface RelayLimits {
47
+ maxConnections: number;
48
+ /** Los mensajes del proveedor son texto corto: 64 KB sobra y un frame mayor cierra el socket. */
49
+ maxBytesPerMessage: number;
50
+ /** Cuánto se espera el `setup` con un token válido antes de cerrar el socket. */
51
+ setupWaitMs: number;
52
+ /** Duración máxima de una llamada; se despide y se pasa a una persona. */
53
+ maxDurationMs: number;
54
+ /** Cuánto se espera, al apagarse, a que se guarden las llamadas pendientes. */
55
+ shutdownGraceMs: number;
56
+ /** Conexiones nuevas por IP por minuto: frena a quien abre sockets en ráfaga. */
57
+ maxConnectsPerIpPerMinute: number;
58
+ /** Mensajes por socket en `messageWindowMs`: más que eso cierra el socket (el proveedor manda pocos por segundo). */
59
+ maxMessagesPerWindow: number;
60
+ messageWindowMs: number;
61
+ /** Bytes pendientes de enviar a un socket lento; pasado esto se cierra (memoria acotada). */
62
+ maxBufferedBytes: number;
63
+ /** Segundos sin tráfico antes de cerrar el socket. */
64
+ idleTimeoutSeconds: number;
65
+ }
66
+ export declare const DEFAULT_RELAY_LIMITS: RelayLimits;
67
+ /**
68
+ * Variables: `RELAY_MAX_CONNECTIONS`, `RELAY_MAX_BYTES_PER_MESSAGE`, `RELAY_SETUP_WAIT_MS`, `RELAY_MAX_DURATION_MS`,
69
+ * `RELAY_SHUTDOWN_GRACE_MS`, `RELAY_MAX_CONNECTS_PER_IP_PER_MINUTE`, `RELAY_MAX_MESSAGES_PER_WINDOW`,
70
+ * `RELAY_MESSAGE_WINDOW_MS`, `RELAY_MAX_BUFFERED_BYTES`, `RELAY_IDLE_TIMEOUT_SECONDS`.
71
+ */
72
+ export declare function relayLimitsFromEnv(env?: Record<string, string | undefined>, defaults?: RelayLimits): RelayLimits;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Lo que el relay le pide al API de cada proyecto. El relay **no** sabe de clientes, menús ni IA: pasa lo que dijo el
3
+ * llamante y devuelve el texto a leer. Quien lo implementa (normalmente {@link httpRelayBackend}) pone la IA.
4
+ */
5
+ export type RelayWho = 'agent' | 'caller';
6
+ export interface RelayTurn {
7
+ who: RelayWho;
8
+ text: string;
9
+ }
10
+ /** Cómo termina un turno: sigue la conversación, se despide, o se pasa a una persona. */
11
+ export type RelayAction = 'continue' | 'end' | 'handoff';
12
+ export interface RelayTurnReply {
13
+ /** Lo que se lee en voz alta al llamante. */
14
+ reply: string;
15
+ action: RelayAction;
16
+ /** Resultado de la llamada hasta ahora (texto libre del proyecto: `message_left`, `informed`…). */
17
+ outcome: string;
18
+ summary: string;
19
+ /** Datos propios del proyecto (nombre del llamante, intención…). Se acumulan: el último valor de cada clave gana. */
20
+ data?: Record<string, unknown>;
21
+ }
22
+ /** Lo que se informa cuando termina (o avanza) la llamada. */
23
+ export interface RelayCallRecord {
24
+ startedAt: string;
25
+ durationSeconds: number;
26
+ from: string | null;
27
+ outcome: string;
28
+ summary: string;
29
+ data: Record<string, unknown>;
30
+ transcript: RelayTurn[];
31
+ greeting?: string;
32
+ /** Por qué la técnica cortó la llamada, si no fue el llamante: tope alcanzado o falla del API. */
33
+ technicalCause?: 'limit' | 'service_failure';
34
+ }
35
+ export interface RelayTurnMeta {
36
+ from: string | null;
37
+ greeting?: string;
38
+ }
39
+ export interface RelayBackend {
40
+ turn(token: string, said: string, history: RelayTurn[], meta: RelayTurnMeta): Promise<RelayTurnReply>;
41
+ /** Cierre de la llamada. Se reintenta; debe ser idempotente en el API. */
42
+ finish(token: string, record: RelayCallRecord): Promise<void>;
43
+ /** Texto que el relay tuvo que emitir sin pasar por `turn` (tope, falla), para no perderlo si el proceso cae. */
44
+ progress?(token: string, record: RelayCallRecord): Promise<void>;
45
+ /**
46
+ * Comprueba el token al conectar: `false` = el API lo rechazó (se cierra el socket). Si el API no responde, se
47
+ * lanza y la llamada sigue (nunca se pierde una llamada por una falla de red del API).
48
+ */
49
+ validate?(token: string, call?: RelayCallContext): Promise<boolean>;
50
+ }
51
+ /**
52
+ * La llamada a la que el socket dice pertenecer. El API compara `callId` con el que **firmó dentro del token**: un token
53
+ * robado de otra llamada o de otro tenant no abre esta sesión.
54
+ */
55
+ export interface RelayCallContext {
56
+ callId: string;
57
+ from: string | null;
58
+ }
59
+ /**
60
+ * Lee un turno de la respuesta del API: acepta el sobre `{ success, data }` de nestkit o el turno suelto. Una
61
+ * respuesta sin texto que decir o sin acción conocida es un fallo del turno: se lanza para que la sesión se disculpe y
62
+ * pase a una persona, en vez de mandarle al proveedor un mensaje vacío.
63
+ */
64
+ export declare function parseTurnReply(body: unknown): RelayTurnReply;
65
+ export interface HttpRelayBackendOptions {
66
+ /** Base del API del proyecto, p. ej. `https://api.example.com/api/v1/voice`. Sin barra final. */
67
+ baseUrl: string;
68
+ /** Rutas (relativas a `baseUrl`) de cada llamada. Por omisión `turn`, `progress`, `finish`, `session`. */
69
+ paths?: Partial<Record<'turn' | 'progress' | 'finish' | 'session', string>>;
70
+ /** Cuánto se espera un turno; un silencio largo ya es una llamada perdida. Por omisión 9 s. */
71
+ turnTimeoutMs?: number;
72
+ finishTimeoutMs?: number;
73
+ fetchImpl?: typeof fetch;
74
+ /** Permitir `http://` hacia una red privada (el token viaja sin cifrar). Por omisión `false`. */
75
+ allowInsecure?: boolean;
76
+ }
77
+ /**
78
+ * Backend por HTTP + JSON: cada aviso es un `POST` con `{ t: <token>, … }`. Un `404` en `progress` se ignora (un API
79
+ * viejo sin esa ruta no retrasa la voz). `validate` trata solo un `401` como rechazo del token.
80
+ */
81
+ export declare function httpRelayBackend(options: HttpRelayBackendOptions): RelayBackend;
@@ -0,0 +1,483 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+ var _chunkHMHUOXGBcjs = require('../../chunk-HMHUOXGB.cjs');
7
+
8
+
9
+ var _chunk2RQINZCRcjs = require('../../chunk-2RQINZCR.cjs');
10
+ require('../../chunk-LRX7AMSS.cjs');
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 || !_chunk2RQINZCRcjs.constantTimeEqual.call(void 0, 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 = _optionalChain([env, 'access', _ => _.RELAY_SECRET, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]) || 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 _optionalChain([envelope, 'optionalAccess', _4 => _4.success]) === "boolean" ? envelope.success ? envelope.data : null : body;
77
+ if (typeof _optionalChain([value, 'optionalAccess', _5 => _5.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 = _nullishCoalesce(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 }, _nullishCoalesce(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 }, _nullishCoalesce(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 = _nullishCoalesce(options.maxTurns, () => ( 40));
154
+ this.limitPhrase = _nullishCoalesce(options.limitPhrase, () => ( DEFAULT_LIMIT_PHRASE));
155
+ this.fallbackPhrase = _nullishCoalesce(options.fallbackPhrase, () => ( DEFAULT_FALLBACK_PHRASE));
156
+ this.outcomes = { empty: "no_message", handoff: "handoff", failure: "failure", ...options.outcomes };
157
+ this.pauses = _nullishCoalesce(options.savePausesMs, () => ( DEFAULT_SAVE_PAUSES_MS));
158
+ this.wait = _nullishCoalesce(options.wait, () => ( ((ms) => new Promise((r) => setTimeout(r, ms)))));
159
+ this.now = _nullishCoalesce(options.now, () => ( Date.now));
160
+ this.closeSocket = _nullishCoalesce(options.close, () => ( (() => {
161
+ })));
162
+ this.log = _nullishCoalesce(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: _chunkHMHUOXGBcjs.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 (e) {
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 _optionalChain([m, 'access', _6 => _6.customParameters, 'optionalAccess', _7 => _7.t]) === "string" ? m.customParameters.t : null;
205
+ this.greeting = typeof _optionalChain([m, 'access', _8 => _8.customParameters, 'optionalAccess', _9 => _9.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 (e2) {
216
+ }
217
+ }
218
+ return;
219
+ case "prompt":
220
+ if (m.last === false) return;
221
+ return this.respond(String(_nullishCoalesce(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 (e3) {
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(_nullishCoalesce(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: _chunkHMHUOXGBcjs.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 (e4) {
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 = _nullishCoalesce(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: _nullishCoalesce(options.requireSecret, () => ( false)) } : relayAccessConfigFromEnv();
332
+ const limits = { ...relayLimitsFromEnv(), ...options.limits };
333
+ const write = _nullishCoalesce(options.log, () => ( ((line) => console.error(line))));
334
+ const log = (line) => write(_chunkHMHUOXGBcjs.redactText.call(void 0, line, [access.secret]));
335
+ const secureOnly = _nullishCoalesce(options.requireSecureTransport, () => ( access.requireSecret));
336
+ const connects = new (0, _chunkHMHUOXGBcjs.SlidingWindowLimiter)(limits.maxConnectsPerIpPerMinute, 6e4);
337
+ const sourceIp = (req, srv) => {
338
+ if (options.trustProxy) {
339
+ const hop = _optionalChain([req, 'access', _10 => _10.headers, 'access', _11 => _11.get, 'call', _12 => _12("x-forwarded-for"), 'optionalAccess', _13 => _13.split, 'call', _14 => _14(","), 'access', _15 => _15[0], 'optionalAccess', _16 => _16.trim, 'call', _17 => _17()]);
340
+ if (hop) return hop;
341
+ }
342
+ return _nullishCoalesce(_optionalChain([srv, 'access', _18 => _18.requestIP, 'optionalCall', _19 => _19(req), 'optionalAccess', _20 => _20.address]), () => ( "unknown"));
343
+ };
344
+ const path = _nullishCoalesce(options.path, () => ( "/relay"));
345
+ const healthPath = _nullishCoalesce(options.healthPath, () => ( "/health"));
346
+ let connections = 0;
347
+ let shuttingDown = false;
348
+ const sessions = /* @__PURE__ */ new Map();
349
+ const server = serve({
350
+ port: _nullishCoalesce(options.port, () => ( Number(_nullishCoalesce(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 (0, _chunkHMHUOXGBcjs.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 ((_nullishCoalesce(_optionalChain([ws, 'access', _21 => _21.getBufferedAmount, 'optionalCall', _22 => _22()]), () => ( 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 (_nullishCoalesce(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 (_nullishCoalesce(options.exitOnSignal, () => ( true))) process.exit(0);
449
+ return;
450
+ }
451
+ void shutdown().then(() => {
452
+ if (_nullishCoalesce(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
+
469
+
470
+
471
+
472
+
473
+
474
+
475
+
476
+
477
+
478
+
479
+
480
+
481
+
482
+
483
+ exports.DEFAULT_FALLBACK_PHRASE = DEFAULT_FALLBACK_PHRASE; exports.DEFAULT_LIMIT_PHRASE = DEFAULT_LIMIT_PHRASE; exports.DEFAULT_RELAY_LIMITS = DEFAULT_RELAY_LIMITS; exports.DEFAULT_SAVE_PAUSES_MS = DEFAULT_SAVE_PAUSES_MS; exports.HANDOFF_DATA = _chunkHMHUOXGBcjs.HANDOFF_DATA; exports.RelaySession = RelaySession; exports.decideRelayAccess = decideRelayAccess; exports.httpRelayBackend = httpRelayBackend; exports.isHandoffRequested = _chunkHMHUOXGBcjs.isHandoffRequested; exports.parseTurnReply = parseTurnReply; exports.relayAccessConfigFromEnv = relayAccessConfigFromEnv; exports.relayLimitsFromEnv = relayLimitsFromEnv; exports.startRelayServer = startRelayServer; exports.waitBeforeHangup = waitBeforeHangup;