@absolutejs/voice 0.0.22-beta.13 → 0.0.22-beta.131
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 +781 -5
- package/dist/agent.d.ts +24 -0
- package/dist/agentSquadContract.d.ts +64 -0
- package/dist/angular/index.d.ts +9 -0
- package/dist/angular/index.js +1394 -46
- package/dist/angular/voice-campaign-dialer-proof.service.d.ts +14 -0
- package/dist/angular/voice-controller.service.d.ts +1 -0
- package/dist/angular/voice-ops-status.component.d.ts +15 -0
- package/dist/angular/voice-ops-status.service.d.ts +12 -0
- package/dist/angular/voice-provider-capabilities.service.d.ts +12 -0
- package/dist/angular/voice-provider-status.service.d.ts +12 -0
- package/dist/angular/voice-routing-status.service.d.ts +11 -0
- package/dist/angular/voice-stream.service.d.ts +3 -0
- package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
- package/dist/angular/voice-turn-latency.service.d.ts +13 -0
- package/dist/angular/voice-turn-quality.service.d.ts +12 -0
- package/dist/angular/voice-workflow-status.service.d.ts +12 -0
- package/dist/assistantHealth.d.ts +81 -0
- package/dist/audit.d.ts +128 -0
- package/dist/auditDeliveryRoutes.d.ts +85 -0
- package/dist/auditExport.d.ts +34 -0
- package/dist/auditRoutes.d.ts +66 -0
- package/dist/auditSinks.d.ts +133 -0
- package/dist/bargeInRoutes.d.ts +56 -0
- package/dist/campaign.d.ts +610 -0
- package/dist/campaignDialers.d.ts +90 -0
- package/dist/client/actions.d.ts +105 -0
- package/dist/client/bargeInMonitor.d.ts +7 -0
- package/dist/client/campaignDialerProof.d.ts +23 -0
- package/dist/client/connection.d.ts +3 -0
- package/dist/client/duplex.d.ts +1 -1
- package/dist/client/htmxBootstrap.js +697 -15
- package/dist/client/index.d.ts +40 -0
- package/dist/client/index.js +2138 -10
- package/dist/client/liveTurnLatency.d.ts +41 -0
- package/dist/client/opsStatus.d.ts +19 -0
- package/dist/client/opsStatusWidget.d.ts +40 -0
- package/dist/client/providerCapabilities.d.ts +19 -0
- package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
- package/dist/client/providerSimulationControls.d.ts +33 -0
- package/dist/client/providerSimulationControlsWidget.d.ts +20 -0
- package/dist/client/providerStatus.d.ts +19 -0
- package/dist/client/providerStatusWidget.d.ts +32 -0
- package/dist/client/routingStatus.d.ts +19 -0
- package/dist/client/routingStatusWidget.d.ts +28 -0
- package/dist/client/traceTimeline.d.ts +19 -0
- package/dist/client/traceTimelineWidget.d.ts +32 -0
- package/dist/client/turnLatency.d.ts +22 -0
- package/dist/client/turnLatencyWidget.d.ts +33 -0
- package/dist/client/turnQuality.d.ts +19 -0
- package/dist/client/turnQualityWidget.d.ts +32 -0
- package/dist/client/workflowStatus.d.ts +19 -0
- package/dist/dataControl.d.ts +47 -0
- package/dist/demoReadyRoutes.d.ts +98 -0
- package/dist/diagnosticsRoutes.d.ts +44 -0
- package/dist/evalRoutes.d.ts +213 -0
- package/dist/fileStore.d.ts +11 -2
- package/dist/handoff.d.ts +54 -0
- package/dist/handoffHealth.d.ts +94 -0
- package/dist/index.d.ts +104 -9
- package/dist/index.js +17310 -4708
- package/dist/liveLatency.d.ts +78 -0
- package/dist/modelAdapters.d.ts +26 -2
- package/dist/openaiRealtime.d.ts +27 -0
- package/dist/openaiTTS.d.ts +18 -0
- package/dist/opsConsoleRoutes.d.ts +77 -0
- package/dist/opsStatus.d.ts +65 -0
- package/dist/opsStatusRoutes.d.ts +33 -0
- package/dist/opsWebhook.d.ts +126 -0
- package/dist/outcomeContract.d.ts +112 -0
- package/dist/phoneAgent.d.ts +62 -0
- package/dist/phoneAgentProductionSmoke.d.ts +115 -0
- package/dist/postgresStore.d.ts +13 -2
- package/dist/productionReadiness.d.ts +227 -0
- package/dist/providerAdapters.d.ts +48 -0
- package/dist/providerCapabilities.d.ts +92 -0
- package/dist/providerHealth.d.ts +79 -0
- package/dist/providerRoutingContract.d.ts +38 -0
- package/dist/qualityRoutes.d.ts +76 -0
- package/dist/queue.d.ts +61 -0
- package/dist/react/VoiceOpsStatus.d.ts +6 -0
- package/dist/react/VoiceProviderCapabilities.d.ts +6 -0
- package/dist/react/VoiceProviderSimulationControls.d.ts +5 -0
- package/dist/react/VoiceProviderStatus.d.ts +6 -0
- package/dist/react/VoiceRoutingStatus.d.ts +6 -0
- package/dist/react/VoiceTraceTimeline.d.ts +6 -0
- package/dist/react/VoiceTurnLatency.d.ts +6 -0
- package/dist/react/VoiceTurnQuality.d.ts +6 -0
- package/dist/react/index.d.ts +18 -0
- package/dist/react/index.js +2726 -14
- package/dist/react/useVoiceCampaignDialerProof.d.ts +10 -0
- package/dist/react/useVoiceController.d.ts +3 -0
- package/dist/react/useVoiceOpsStatus.d.ts +8 -0
- package/dist/react/useVoiceProviderCapabilities.d.ts +8 -0
- package/dist/react/useVoiceProviderSimulationControls.d.ts +10 -0
- package/dist/react/useVoiceProviderStatus.d.ts +8 -0
- package/dist/react/useVoiceRoutingStatus.d.ts +8 -0
- package/dist/react/useVoiceStream.d.ts +3 -0
- package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
- package/dist/react/useVoiceTurnLatency.d.ts +9 -0
- package/dist/react/useVoiceTurnQuality.d.ts +8 -0
- package/dist/react/useVoiceWorkflowStatus.d.ts +8 -0
- package/dist/reconnectContract.d.ts +83 -0
- package/dist/resilienceRoutes.d.ts +142 -0
- package/dist/sessionReplay.d.ts +175 -0
- package/dist/simulationSuite.d.ts +120 -0
- package/dist/sqliteStore.d.ts +13 -2
- package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
- package/dist/svelte/createVoiceOpsStatus.d.ts +9 -0
- package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
- package/dist/svelte/createVoiceProviderSimulationControls.d.ts +11 -0
- package/dist/svelte/createVoiceProviderStatus.d.ts +10 -0
- package/dist/svelte/createVoiceRoutingStatus.d.ts +10 -0
- package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
- package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
- package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
- package/dist/svelte/createVoiceWorkflowStatus.d.ts +8 -0
- package/dist/svelte/index.d.ts +10 -0
- package/dist/svelte/index.js +2152 -202
- package/dist/telephony/contract.d.ts +61 -0
- package/dist/telephony/matrix.d.ts +97 -0
- package/dist/telephony/plivo.d.ts +254 -0
- package/dist/telephony/telnyx.d.ts +247 -0
- package/dist/telephony/twilio.d.ts +135 -2
- package/dist/telephonyOutcome.d.ts +201 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.js +2830 -37
- package/dist/testing/ioProviderSimulator.d.ts +41 -0
- package/dist/testing/providerSimulator.d.ts +44 -0
- package/dist/toolContract.d.ts +130 -0
- package/dist/toolRuntime.d.ts +50 -0
- package/dist/trace.d.ts +1 -1
- package/dist/traceDeliveryRoutes.d.ts +86 -0
- package/dist/traceTimeline.d.ts +93 -0
- package/dist/turnLatency.d.ts +95 -0
- package/dist/turnQuality.d.ts +94 -0
- package/dist/types.d.ts +169 -4
- package/dist/vue/VoiceOpsStatus.d.ts +30 -0
- package/dist/vue/VoiceProviderCapabilities.d.ts +51 -0
- package/dist/vue/VoiceProviderSimulationControls.d.ts +88 -0
- package/dist/vue/VoiceProviderStatus.d.ts +51 -0
- package/dist/vue/VoiceRoutingStatus.d.ts +51 -0
- package/dist/vue/VoiceTurnLatency.d.ts +69 -0
- package/dist/vue/VoiceTurnQuality.d.ts +51 -0
- package/dist/vue/index.d.ts +17 -0
- package/dist/vue/index.js +2636 -31
- package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
- package/dist/vue/useVoiceController.d.ts +2 -1
- package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
- package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
- package/dist/vue/useVoiceProviderSimulationControls.d.ts +24 -0
- package/dist/vue/useVoiceProviderStatus.d.ts +9 -0
- package/dist/vue/useVoiceRoutingStatus.d.ts +8 -0
- package/dist/vue/useVoiceStream.d.ts +4 -1
- package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
- package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
- package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
- package/dist/vue/useVoiceWorkflowStatus.d.ts +9 -0
- package/dist/workflowContract.d.ts +91 -0
- package/package.json +1 -1
package/dist/testing/index.js
CHANGED
|
@@ -2105,6 +2105,17 @@ var serverMessageToAction = (message) => {
|
|
|
2105
2105
|
sessionId: message.sessionId,
|
|
2106
2106
|
type: "complete"
|
|
2107
2107
|
};
|
|
2108
|
+
case "connection":
|
|
2109
|
+
return {
|
|
2110
|
+
reconnect: message.reconnect,
|
|
2111
|
+
type: "connection"
|
|
2112
|
+
};
|
|
2113
|
+
case "call_lifecycle":
|
|
2114
|
+
return {
|
|
2115
|
+
event: message.event,
|
|
2116
|
+
sessionId: message.sessionId,
|
|
2117
|
+
type: "call_lifecycle"
|
|
2118
|
+
};
|
|
2108
2119
|
case "error":
|
|
2109
2120
|
return {
|
|
2110
2121
|
message: normalizeErrorMessage(message.message),
|
|
@@ -2120,6 +2131,17 @@ var serverMessageToAction = (message) => {
|
|
|
2120
2131
|
transcript: message.transcript,
|
|
2121
2132
|
type: "partial"
|
|
2122
2133
|
};
|
|
2134
|
+
case "replay":
|
|
2135
|
+
return {
|
|
2136
|
+
assistantTexts: message.assistantTexts,
|
|
2137
|
+
call: message.call,
|
|
2138
|
+
partial: message.partial,
|
|
2139
|
+
scenarioId: message.scenarioId,
|
|
2140
|
+
sessionId: message.sessionId,
|
|
2141
|
+
status: message.status,
|
|
2142
|
+
turns: message.turns,
|
|
2143
|
+
type: "replay"
|
|
2144
|
+
};
|
|
2123
2145
|
case "session":
|
|
2124
2146
|
return {
|
|
2125
2147
|
sessionId: message.sessionId,
|
|
@@ -2148,7 +2170,7 @@ var DEFAULT_SCENARIO_QUERY_PARAM = "scenarioId";
|
|
|
2148
2170
|
var noop = () => {};
|
|
2149
2171
|
var noopUnsubscribe = () => noop;
|
|
2150
2172
|
var NOOP_CONNECTION = {
|
|
2151
|
-
|
|
2173
|
+
callControl: noop,
|
|
2152
2174
|
close: noop,
|
|
2153
2175
|
endTurn: noop,
|
|
2154
2176
|
getReadyState: () => WS_CLOSED,
|
|
@@ -2156,6 +2178,7 @@ var NOOP_CONNECTION = {
|
|
|
2156
2178
|
getSessionId: () => "",
|
|
2157
2179
|
send: noop,
|
|
2158
2180
|
sendAudio: noop,
|
|
2181
|
+
start: () => {},
|
|
2159
2182
|
subscribe: noopUnsubscribe
|
|
2160
2183
|
};
|
|
2161
2184
|
var createSessionId = () => crypto.randomUUID();
|
|
@@ -2177,11 +2200,14 @@ var isVoiceServerMessage = (value) => {
|
|
|
2177
2200
|
switch (value.type) {
|
|
2178
2201
|
case "audio":
|
|
2179
2202
|
case "assistant":
|
|
2203
|
+
case "call_lifecycle":
|
|
2180
2204
|
case "complete":
|
|
2205
|
+
case "connection":
|
|
2181
2206
|
case "error":
|
|
2182
2207
|
case "final":
|
|
2183
2208
|
case "partial":
|
|
2184
2209
|
case "pong":
|
|
2210
|
+
case "replay":
|
|
2185
2211
|
case "session":
|
|
2186
2212
|
case "turn":
|
|
2187
2213
|
return true;
|
|
@@ -2218,6 +2244,9 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2218
2244
|
sessionId: options.sessionId ?? createSessionId(),
|
|
2219
2245
|
ws: null
|
|
2220
2246
|
};
|
|
2247
|
+
const emitConnection = (reconnect) => {
|
|
2248
|
+
listeners.forEach((listener) => listener(reconnect));
|
|
2249
|
+
};
|
|
2221
2250
|
const clearTimers = () => {
|
|
2222
2251
|
if (state.pingInterval) {
|
|
2223
2252
|
clearInterval(state.pingInterval);
|
|
@@ -2240,9 +2269,28 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2240
2269
|
}
|
|
2241
2270
|
};
|
|
2242
2271
|
const scheduleReconnect = () => {
|
|
2272
|
+
const nextAttemptAt = Date.now() + RECONNECT_DELAY_MS;
|
|
2243
2273
|
state.reconnectAttempts += 1;
|
|
2274
|
+
emitConnection({
|
|
2275
|
+
reconnect: {
|
|
2276
|
+
attempts: state.reconnectAttempts,
|
|
2277
|
+
lastDisconnectAt: Date.now(),
|
|
2278
|
+
maxAttempts: maxReconnectAttempts,
|
|
2279
|
+
nextAttemptAt,
|
|
2280
|
+
status: "reconnecting"
|
|
2281
|
+
},
|
|
2282
|
+
type: "connection"
|
|
2283
|
+
});
|
|
2244
2284
|
state.reconnectTimeout = setTimeout(() => {
|
|
2245
2285
|
if (state.reconnectAttempts > maxReconnectAttempts) {
|
|
2286
|
+
emitConnection({
|
|
2287
|
+
reconnect: {
|
|
2288
|
+
attempts: state.reconnectAttempts,
|
|
2289
|
+
maxAttempts: maxReconnectAttempts,
|
|
2290
|
+
status: "exhausted"
|
|
2291
|
+
},
|
|
2292
|
+
type: "connection"
|
|
2293
|
+
});
|
|
2246
2294
|
return;
|
|
2247
2295
|
}
|
|
2248
2296
|
connect();
|
|
@@ -2252,9 +2300,21 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2252
2300
|
const ws = new WebSocket(buildWsUrl(path, state.sessionId, state.scenarioId));
|
|
2253
2301
|
ws.binaryType = "arraybuffer";
|
|
2254
2302
|
ws.onopen = () => {
|
|
2303
|
+
const wasReconnecting = state.reconnectAttempts > 0;
|
|
2255
2304
|
state.isConnected = true;
|
|
2256
|
-
state.reconnectAttempts = 0;
|
|
2257
2305
|
flushPendingMessages();
|
|
2306
|
+
if (wasReconnecting) {
|
|
2307
|
+
emitConnection({
|
|
2308
|
+
reconnect: {
|
|
2309
|
+
attempts: state.reconnectAttempts,
|
|
2310
|
+
lastResumedAt: Date.now(),
|
|
2311
|
+
maxAttempts: maxReconnectAttempts,
|
|
2312
|
+
status: "resumed"
|
|
2313
|
+
},
|
|
2314
|
+
type: "connection"
|
|
2315
|
+
});
|
|
2316
|
+
state.reconnectAttempts = 0;
|
|
2317
|
+
}
|
|
2258
2318
|
listeners.forEach((listener) => listener({
|
|
2259
2319
|
scenarioId: state.scenarioId ?? undefined,
|
|
2260
2320
|
sessionId: state.sessionId,
|
|
@@ -2284,6 +2344,16 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2284
2344
|
const reconnectable = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && state.reconnectAttempts < maxReconnectAttempts;
|
|
2285
2345
|
if (reconnectable) {
|
|
2286
2346
|
scheduleReconnect();
|
|
2347
|
+
} else if (shouldReconnect && event.code !== WS_NORMAL_CLOSURE) {
|
|
2348
|
+
emitConnection({
|
|
2349
|
+
reconnect: {
|
|
2350
|
+
attempts: state.reconnectAttempts,
|
|
2351
|
+
lastDisconnectAt: Date.now(),
|
|
2352
|
+
maxAttempts: maxReconnectAttempts,
|
|
2353
|
+
status: "exhausted"
|
|
2354
|
+
},
|
|
2355
|
+
type: "connection"
|
|
2356
|
+
});
|
|
2287
2357
|
}
|
|
2288
2358
|
};
|
|
2289
2359
|
state.ws = ws;
|
|
@@ -2317,6 +2387,12 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2317
2387
|
const endTurn = () => {
|
|
2318
2388
|
send({ type: "end_turn" });
|
|
2319
2389
|
};
|
|
2390
|
+
const callControl = (message) => {
|
|
2391
|
+
send({
|
|
2392
|
+
...message,
|
|
2393
|
+
type: "call_control"
|
|
2394
|
+
});
|
|
2395
|
+
};
|
|
2320
2396
|
const close = () => {
|
|
2321
2397
|
clearTimers();
|
|
2322
2398
|
if (state.ws) {
|
|
@@ -2334,7 +2410,7 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2334
2410
|
};
|
|
2335
2411
|
connect();
|
|
2336
2412
|
return {
|
|
2337
|
-
|
|
2413
|
+
callControl,
|
|
2338
2414
|
close,
|
|
2339
2415
|
endTurn,
|
|
2340
2416
|
getReadyState: () => state.ws?.readyState ?? WS_CLOSED,
|
|
@@ -2342,18 +2418,26 @@ var createVoiceConnection = (path, options = {}) => {
|
|
|
2342
2418
|
getSessionId: () => state.sessionId,
|
|
2343
2419
|
send,
|
|
2344
2420
|
sendAudio,
|
|
2421
|
+
start,
|
|
2345
2422
|
subscribe
|
|
2346
2423
|
};
|
|
2347
2424
|
};
|
|
2348
2425
|
|
|
2349
2426
|
// src/client/store.ts
|
|
2427
|
+
var createInitialReconnectState = () => ({
|
|
2428
|
+
attempts: 0,
|
|
2429
|
+
maxAttempts: 0,
|
|
2430
|
+
status: "idle"
|
|
2431
|
+
});
|
|
2350
2432
|
var createInitialState2 = () => ({
|
|
2351
2433
|
assistantAudio: [],
|
|
2352
2434
|
assistantTexts: [],
|
|
2435
|
+
call: null,
|
|
2353
2436
|
error: null,
|
|
2354
2437
|
isConnected: false,
|
|
2355
2438
|
scenarioId: null,
|
|
2356
2439
|
partial: "",
|
|
2440
|
+
reconnect: createInitialReconnectState(),
|
|
2357
2441
|
sessionId: null,
|
|
2358
2442
|
status: "idle",
|
|
2359
2443
|
turns: []
|
|
@@ -2393,10 +2477,36 @@ var createVoiceStreamStore = () => {
|
|
|
2393
2477
|
status: "completed"
|
|
2394
2478
|
};
|
|
2395
2479
|
break;
|
|
2480
|
+
case "call_lifecycle":
|
|
2481
|
+
state = {
|
|
2482
|
+
...state,
|
|
2483
|
+
call: {
|
|
2484
|
+
...state.call,
|
|
2485
|
+
disposition: action.event.type === "end" ? action.event.disposition : state.call?.disposition,
|
|
2486
|
+
endedAt: action.event.type === "end" ? action.event.at : state.call?.endedAt,
|
|
2487
|
+
events: [...state.call?.events ?? [], action.event],
|
|
2488
|
+
lastEventAt: action.event.at,
|
|
2489
|
+
startedAt: state.call?.startedAt ?? action.event.at
|
|
2490
|
+
},
|
|
2491
|
+
sessionId: action.sessionId
|
|
2492
|
+
};
|
|
2493
|
+
break;
|
|
2396
2494
|
case "connected":
|
|
2397
2495
|
state = {
|
|
2398
2496
|
...state,
|
|
2399
|
-
isConnected: true
|
|
2497
|
+
isConnected: true,
|
|
2498
|
+
reconnect: state.reconnect.status === "reconnecting" ? {
|
|
2499
|
+
...state.reconnect,
|
|
2500
|
+
lastResumedAt: Date.now(),
|
|
2501
|
+
nextAttemptAt: undefined,
|
|
2502
|
+
status: "resumed"
|
|
2503
|
+
} : state.reconnect
|
|
2504
|
+
};
|
|
2505
|
+
break;
|
|
2506
|
+
case "connection":
|
|
2507
|
+
state = {
|
|
2508
|
+
...state,
|
|
2509
|
+
reconnect: action.reconnect
|
|
2400
2510
|
};
|
|
2401
2511
|
break;
|
|
2402
2512
|
case "disconnected":
|
|
@@ -2424,6 +2534,26 @@ var createVoiceStreamStore = () => {
|
|
|
2424
2534
|
partial: action.transcript.text
|
|
2425
2535
|
};
|
|
2426
2536
|
break;
|
|
2537
|
+
case "replay":
|
|
2538
|
+
state = {
|
|
2539
|
+
...state,
|
|
2540
|
+
assistantTexts: [...action.assistantTexts],
|
|
2541
|
+
call: action.call ?? null,
|
|
2542
|
+
error: null,
|
|
2543
|
+
isConnected: action.status === "active",
|
|
2544
|
+
partial: action.partial,
|
|
2545
|
+
reconnect: state.reconnect.status === "reconnecting" ? {
|
|
2546
|
+
...state.reconnect,
|
|
2547
|
+
lastResumedAt: Date.now(),
|
|
2548
|
+
nextAttemptAt: undefined,
|
|
2549
|
+
status: "resumed"
|
|
2550
|
+
} : state.reconnect,
|
|
2551
|
+
scenarioId: action.scenarioId ?? state.scenarioId,
|
|
2552
|
+
sessionId: action.sessionId,
|
|
2553
|
+
status: action.status,
|
|
2554
|
+
turns: [...action.turns]
|
|
2555
|
+
};
|
|
2556
|
+
break;
|
|
2427
2557
|
case "session":
|
|
2428
2558
|
state = {
|
|
2429
2559
|
...state,
|
|
@@ -2479,6 +2609,9 @@ var createVoiceStream = (path, options = {}) => {
|
|
|
2479
2609
|
}
|
|
2480
2610
|
});
|
|
2481
2611
|
return {
|
|
2612
|
+
callControl(message) {
|
|
2613
|
+
connection.callControl(message);
|
|
2614
|
+
},
|
|
2482
2615
|
close() {
|
|
2483
2616
|
unsubscribeConnection();
|
|
2484
2617
|
connection.close();
|
|
@@ -2507,6 +2640,9 @@ var createVoiceStream = (path, options = {}) => {
|
|
|
2507
2640
|
get partial() {
|
|
2508
2641
|
return store.getSnapshot().partial;
|
|
2509
2642
|
},
|
|
2643
|
+
get reconnect() {
|
|
2644
|
+
return store.getSnapshot().reconnect;
|
|
2645
|
+
},
|
|
2510
2646
|
get sessionId() {
|
|
2511
2647
|
return connection.getSessionId();
|
|
2512
2648
|
},
|
|
@@ -2522,6 +2658,9 @@ var createVoiceStream = (path, options = {}) => {
|
|
|
2522
2658
|
get assistantAudio() {
|
|
2523
2659
|
return store.getSnapshot().assistantAudio;
|
|
2524
2660
|
},
|
|
2661
|
+
get call() {
|
|
2662
|
+
return store.getSnapshot().call;
|
|
2663
|
+
},
|
|
2525
2664
|
sendAudio(audio) {
|
|
2526
2665
|
connection.sendAudio(audio);
|
|
2527
2666
|
},
|
|
@@ -2854,10 +2993,12 @@ var resolveVoiceRuntimePreset = (name = "default") => {
|
|
|
2854
2993
|
var createInitialState3 = (stream) => ({
|
|
2855
2994
|
assistantAudio: [...stream.assistantAudio],
|
|
2856
2995
|
assistantTexts: [...stream.assistantTexts],
|
|
2996
|
+
call: stream.call,
|
|
2857
2997
|
error: stream.error,
|
|
2858
2998
|
isConnected: stream.isConnected,
|
|
2859
2999
|
isRecording: false,
|
|
2860
3000
|
partial: stream.partial,
|
|
3001
|
+
reconnect: stream.reconnect,
|
|
2861
3002
|
recordingError: null,
|
|
2862
3003
|
sessionId: stream.sessionId,
|
|
2863
3004
|
scenarioId: stream.scenarioId,
|
|
@@ -2883,9 +3024,11 @@ var createVoiceController = (path, options = {}) => {
|
|
|
2883
3024
|
...state,
|
|
2884
3025
|
assistantAudio: [...stream.assistantAudio],
|
|
2885
3026
|
assistantTexts: [...stream.assistantTexts],
|
|
3027
|
+
call: stream.call,
|
|
2886
3028
|
error: stream.error,
|
|
2887
3029
|
isConnected: stream.isConnected,
|
|
2888
3030
|
partial: stream.partial,
|
|
3031
|
+
reconnect: stream.reconnect,
|
|
2889
3032
|
sessionId: stream.sessionId,
|
|
2890
3033
|
scenarioId: stream.scenarioId,
|
|
2891
3034
|
status: stream.status,
|
|
@@ -2910,7 +3053,13 @@ var createVoiceController = (path, options = {}) => {
|
|
|
2910
3053
|
capture = createMicrophoneCapture({
|
|
2911
3054
|
channelCount: options.capture?.channelCount ?? preset.capture.channelCount,
|
|
2912
3055
|
onLevel: options.capture?.onLevel,
|
|
2913
|
-
onAudio: (audio) =>
|
|
3056
|
+
onAudio: (audio) => {
|
|
3057
|
+
if (options.capture?.onAudio) {
|
|
3058
|
+
options.capture.onAudio(audio, stream.sendAudio);
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
stream.sendAudio(audio);
|
|
3062
|
+
},
|
|
2914
3063
|
sampleRateHz: options.capture?.sampleRateHz ?? preset.capture.sampleRateHz
|
|
2915
3064
|
});
|
|
2916
3065
|
return capture;
|
|
@@ -2960,6 +3109,7 @@ var createVoiceController = (path, options = {}) => {
|
|
|
2960
3109
|
bindHTMX(bindingOptions) {
|
|
2961
3110
|
return bindVoiceHTMX(stream, bindingOptions);
|
|
2962
3111
|
},
|
|
3112
|
+
callControl: (message) => stream.callControl(message),
|
|
2963
3113
|
close,
|
|
2964
3114
|
endTurn: () => stream.endTurn(),
|
|
2965
3115
|
get error() {
|
|
@@ -2979,6 +3129,9 @@ var createVoiceController = (path, options = {}) => {
|
|
|
2979
3129
|
get recordingError() {
|
|
2980
3130
|
return state.recordingError;
|
|
2981
3131
|
},
|
|
3132
|
+
get reconnect() {
|
|
3133
|
+
return state.reconnect;
|
|
3134
|
+
},
|
|
2982
3135
|
sendAudio: (audio) => stream.sendAudio(audio),
|
|
2983
3136
|
get sessionId() {
|
|
2984
3137
|
return state.sessionId;
|
|
@@ -3012,6 +3165,9 @@ var createVoiceController = (path, options = {}) => {
|
|
|
3012
3165
|
},
|
|
3013
3166
|
get assistantAudio() {
|
|
3014
3167
|
return state.assistantAudio;
|
|
3168
|
+
},
|
|
3169
|
+
get call() {
|
|
3170
|
+
return state.call;
|
|
3015
3171
|
}
|
|
3016
3172
|
};
|
|
3017
3173
|
};
|
|
@@ -3021,11 +3177,26 @@ var DEFAULT_INTERRUPT_THRESHOLD = 0.08;
|
|
|
3021
3177
|
var shouldInterruptForLevel = (level, options = {}) => (options.enabled ?? true) && level >= (options.interruptThreshold ?? DEFAULT_INTERRUPT_THRESHOLD);
|
|
3022
3178
|
var bindVoiceBargeIn = (controller, player, options = {}) => {
|
|
3023
3179
|
let lastPartial = controller.partial;
|
|
3024
|
-
const interruptIfPlaying = () => {
|
|
3180
|
+
const interruptIfPlaying = (reason) => {
|
|
3025
3181
|
if (!player.isPlaying || options.enabled === false) {
|
|
3182
|
+
options.monitor?.recordSkipped({
|
|
3183
|
+
reason,
|
|
3184
|
+
sessionId: controller.sessionId
|
|
3185
|
+
});
|
|
3026
3186
|
return;
|
|
3027
3187
|
}
|
|
3028
|
-
|
|
3188
|
+
options.monitor?.recordRequested({
|
|
3189
|
+
reason,
|
|
3190
|
+
sessionId: controller.sessionId
|
|
3191
|
+
});
|
|
3192
|
+
player.interrupt().then(() => {
|
|
3193
|
+
options.monitor?.recordStopped({
|
|
3194
|
+
latencyMs: player.lastInterruptLatencyMs,
|
|
3195
|
+
playbackStopLatencyMs: player.lastPlaybackStopLatencyMs,
|
|
3196
|
+
reason,
|
|
3197
|
+
sessionId: controller.sessionId
|
|
3198
|
+
});
|
|
3199
|
+
});
|
|
3029
3200
|
};
|
|
3030
3201
|
const unsubscribe = controller.subscribe(() => {
|
|
3031
3202
|
if (options.interruptOnPartial === false) {
|
|
@@ -3033,7 +3204,7 @@ var bindVoiceBargeIn = (controller, player, options = {}) => {
|
|
|
3033
3204
|
return;
|
|
3034
3205
|
}
|
|
3035
3206
|
if (!lastPartial && controller.partial) {
|
|
3036
|
-
interruptIfPlaying();
|
|
3207
|
+
interruptIfPlaying("partial-transcript");
|
|
3037
3208
|
}
|
|
3038
3209
|
lastPartial = controller.partial;
|
|
3039
3210
|
});
|
|
@@ -3043,11 +3214,11 @@ var bindVoiceBargeIn = (controller, player, options = {}) => {
|
|
|
3043
3214
|
},
|
|
3044
3215
|
handleLevel: (level) => {
|
|
3045
3216
|
if (shouldInterruptForLevel(level, options)) {
|
|
3046
|
-
interruptIfPlaying();
|
|
3217
|
+
interruptIfPlaying("input-level");
|
|
3047
3218
|
}
|
|
3048
3219
|
},
|
|
3049
3220
|
sendAudio: (audio) => {
|
|
3050
|
-
interruptIfPlaying();
|
|
3221
|
+
interruptIfPlaying("manual-audio");
|
|
3051
3222
|
controller.sendAudio(audio);
|
|
3052
3223
|
}
|
|
3053
3224
|
};
|
|
@@ -3077,7 +3248,17 @@ var createVoiceDuplexController = (path, options = {}) => {
|
|
|
3077
3248
|
audioPlayer,
|
|
3078
3249
|
close,
|
|
3079
3250
|
interruptAssistant: async () => {
|
|
3251
|
+
options.bargeIn?.monitor?.recordRequested({
|
|
3252
|
+
reason: "manual-interrupt",
|
|
3253
|
+
sessionId: controller.sessionId
|
|
3254
|
+
});
|
|
3080
3255
|
await audioPlayer.interrupt();
|
|
3256
|
+
options.bargeIn?.monitor?.recordStopped({
|
|
3257
|
+
latencyMs: audioPlayer.lastInterruptLatencyMs,
|
|
3258
|
+
playbackStopLatencyMs: audioPlayer.lastPlaybackStopLatencyMs,
|
|
3259
|
+
reason: "manual-interrupt",
|
|
3260
|
+
sessionId: controller.sessionId
|
|
3261
|
+
});
|
|
3081
3262
|
},
|
|
3082
3263
|
sendAudio: (audio) => {
|
|
3083
3264
|
bargeInBinding?.sendAudio(audio);
|
|
@@ -3468,6 +3649,1004 @@ var loadVoiceTestFixtures = async (fixtureDirectory) => {
|
|
|
3468
3649
|
}
|
|
3469
3650
|
return fixtures;
|
|
3470
3651
|
};
|
|
3652
|
+
// src/testing/ioProviderSimulator.ts
|
|
3653
|
+
var defaultFailureMessage = (input) => `Simulated ${input.provider} ${input.kind.toUpperCase()} ${input.operation} failure.`;
|
|
3654
|
+
var resolveRecoveryElapsedMs = (value, provider) => {
|
|
3655
|
+
if (typeof value === "number") {
|
|
3656
|
+
return value;
|
|
3657
|
+
}
|
|
3658
|
+
return value?.[provider] ?? 25;
|
|
3659
|
+
};
|
|
3660
|
+
var createHealth = (input) => ({
|
|
3661
|
+
consecutiveFailures: input.status === "healthy" ? 0 : 1,
|
|
3662
|
+
lastFailureAt: input.status === "healthy" ? undefined : input.now,
|
|
3663
|
+
provider: input.provider,
|
|
3664
|
+
status: input.status,
|
|
3665
|
+
suppressedUntil: input.suppressedUntil
|
|
3666
|
+
});
|
|
3667
|
+
var resolveFallback = async (options, provider) => {
|
|
3668
|
+
const configured = typeof options.fallback === "function" ? await options.fallback(provider) : options.fallback;
|
|
3669
|
+
return (configured ?? options.providers).find((candidate) => candidate !== provider);
|
|
3670
|
+
};
|
|
3671
|
+
var createVoiceIOProviderFailureSimulator = (options) => {
|
|
3672
|
+
if (options.providers.length === 0) {
|
|
3673
|
+
throw new Error("At least one provider is required.");
|
|
3674
|
+
}
|
|
3675
|
+
const now = options.now ?? Date.now;
|
|
3676
|
+
const operation = options.operation ?? "open";
|
|
3677
|
+
const cooldownMs = Math.max(0, options.cooldownMs ?? 30000);
|
|
3678
|
+
const emit = async (event, input) => {
|
|
3679
|
+
await options.onProviderEvent?.(event, input);
|
|
3680
|
+
};
|
|
3681
|
+
const run = async (provider, mode) => {
|
|
3682
|
+
if (!options.providers.includes(provider)) {
|
|
3683
|
+
throw new Error(`${provider} is not configured for simulation.`);
|
|
3684
|
+
}
|
|
3685
|
+
const startedAt = now();
|
|
3686
|
+
const sessionId = options.sessionId?.({ mode, now: startedAt, provider }) ?? `${options.kind}-provider-sim-${startedAt}`;
|
|
3687
|
+
if (mode === "recovery") {
|
|
3688
|
+
await emit({
|
|
3689
|
+
at: startedAt,
|
|
3690
|
+
attempt: 0,
|
|
3691
|
+
elapsedMs: resolveRecoveryElapsedMs(options.recoveryElapsedMs, provider),
|
|
3692
|
+
kind: options.kind,
|
|
3693
|
+
latencyBudgetMs: options.latencyBudgets?.[provider],
|
|
3694
|
+
operation,
|
|
3695
|
+
provider,
|
|
3696
|
+
providerHealth: createHealth({
|
|
3697
|
+
now: startedAt,
|
|
3698
|
+
provider,
|
|
3699
|
+
status: "healthy"
|
|
3700
|
+
}),
|
|
3701
|
+
selectedProvider: provider,
|
|
3702
|
+
status: "success"
|
|
3703
|
+
}, { mode, provider, sessionId });
|
|
3704
|
+
return {
|
|
3705
|
+
mode,
|
|
3706
|
+
provider,
|
|
3707
|
+
sessionId,
|
|
3708
|
+
status: "simulated"
|
|
3709
|
+
};
|
|
3710
|
+
}
|
|
3711
|
+
const fallbackProvider = await resolveFallback(options, provider);
|
|
3712
|
+
const suppressedUntil = startedAt + cooldownMs;
|
|
3713
|
+
await emit({
|
|
3714
|
+
at: startedAt,
|
|
3715
|
+
attempt: 0,
|
|
3716
|
+
elapsedMs: options.failureElapsedMs ?? 10,
|
|
3717
|
+
error: (options.failureMessage ?? defaultFailureMessage)({
|
|
3718
|
+
kind: options.kind,
|
|
3719
|
+
operation,
|
|
3720
|
+
provider
|
|
3721
|
+
}),
|
|
3722
|
+
fallbackProvider,
|
|
3723
|
+
kind: options.kind,
|
|
3724
|
+
latencyBudgetMs: options.latencyBudgets?.[provider],
|
|
3725
|
+
operation,
|
|
3726
|
+
provider,
|
|
3727
|
+
providerHealth: createHealth({
|
|
3728
|
+
now: startedAt,
|
|
3729
|
+
provider,
|
|
3730
|
+
status: "suppressed",
|
|
3731
|
+
suppressedUntil
|
|
3732
|
+
}),
|
|
3733
|
+
selectedProvider: provider,
|
|
3734
|
+
status: "error",
|
|
3735
|
+
suppressedUntil
|
|
3736
|
+
}, { mode, provider, sessionId });
|
|
3737
|
+
if (fallbackProvider) {
|
|
3738
|
+
await emit({
|
|
3739
|
+
at: startedAt + 1,
|
|
3740
|
+
attempt: 1,
|
|
3741
|
+
elapsedMs: resolveRecoveryElapsedMs(options.recoveryElapsedMs, fallbackProvider),
|
|
3742
|
+
fallbackProvider,
|
|
3743
|
+
kind: options.kind,
|
|
3744
|
+
latencyBudgetMs: options.latencyBudgets?.[fallbackProvider],
|
|
3745
|
+
operation,
|
|
3746
|
+
provider: fallbackProvider,
|
|
3747
|
+
providerHealth: createHealth({
|
|
3748
|
+
now: startedAt + 1,
|
|
3749
|
+
provider: fallbackProvider,
|
|
3750
|
+
status: "healthy"
|
|
3751
|
+
}),
|
|
3752
|
+
selectedProvider: provider,
|
|
3753
|
+
status: "fallback"
|
|
3754
|
+
}, { mode, provider, sessionId });
|
|
3755
|
+
}
|
|
3756
|
+
return {
|
|
3757
|
+
fallbackProvider,
|
|
3758
|
+
mode,
|
|
3759
|
+
provider,
|
|
3760
|
+
sessionId,
|
|
3761
|
+
status: "simulated",
|
|
3762
|
+
suppressedUntil
|
|
3763
|
+
};
|
|
3764
|
+
};
|
|
3765
|
+
return {
|
|
3766
|
+
run
|
|
3767
|
+
};
|
|
3768
|
+
};
|
|
3769
|
+
// src/modelAdapters.ts
|
|
3770
|
+
var resolveVoiceProviderRoutingPolicyPreset = (preset, options = {}) => {
|
|
3771
|
+
switch (preset) {
|
|
3772
|
+
case "balanced":
|
|
3773
|
+
return {
|
|
3774
|
+
fallbackMode: "provider-error",
|
|
3775
|
+
strategy: "balanced",
|
|
3776
|
+
weights: {
|
|
3777
|
+
cost: 1,
|
|
3778
|
+
latencyMs: 0.005,
|
|
3779
|
+
priority: 1,
|
|
3780
|
+
quality: 10,
|
|
3781
|
+
...options.weights
|
|
3782
|
+
},
|
|
3783
|
+
...options
|
|
3784
|
+
};
|
|
3785
|
+
case "cost-cap":
|
|
3786
|
+
return {
|
|
3787
|
+
fallbackMode: "provider-error",
|
|
3788
|
+
strategy: "prefer-cheapest",
|
|
3789
|
+
...options
|
|
3790
|
+
};
|
|
3791
|
+
case "cost-first":
|
|
3792
|
+
return {
|
|
3793
|
+
fallbackMode: "provider-error",
|
|
3794
|
+
strategy: "prefer-cheapest",
|
|
3795
|
+
...options
|
|
3796
|
+
};
|
|
3797
|
+
case "latency-first":
|
|
3798
|
+
return {
|
|
3799
|
+
fallbackMode: "provider-error",
|
|
3800
|
+
strategy: "prefer-fastest",
|
|
3801
|
+
...options
|
|
3802
|
+
};
|
|
3803
|
+
case "quality-first":
|
|
3804
|
+
return {
|
|
3805
|
+
fallbackMode: "provider-error",
|
|
3806
|
+
strategy: "quality-first",
|
|
3807
|
+
...options
|
|
3808
|
+
};
|
|
3809
|
+
}
|
|
3810
|
+
};
|
|
3811
|
+
var OUTPUT_SCHEMA = {
|
|
3812
|
+
additionalProperties: false,
|
|
3813
|
+
properties: {
|
|
3814
|
+
assistantText: {
|
|
3815
|
+
type: "string"
|
|
3816
|
+
},
|
|
3817
|
+
complete: {
|
|
3818
|
+
type: "boolean"
|
|
3819
|
+
},
|
|
3820
|
+
escalate: {
|
|
3821
|
+
additionalProperties: false,
|
|
3822
|
+
properties: {
|
|
3823
|
+
metadata: {
|
|
3824
|
+
additionalProperties: true,
|
|
3825
|
+
type: "object"
|
|
3826
|
+
},
|
|
3827
|
+
reason: {
|
|
3828
|
+
type: "string"
|
|
3829
|
+
}
|
|
3830
|
+
},
|
|
3831
|
+
required: ["reason"],
|
|
3832
|
+
type: "object"
|
|
3833
|
+
},
|
|
3834
|
+
noAnswer: {
|
|
3835
|
+
additionalProperties: false,
|
|
3836
|
+
properties: {
|
|
3837
|
+
metadata: {
|
|
3838
|
+
additionalProperties: true,
|
|
3839
|
+
type: "object"
|
|
3840
|
+
}
|
|
3841
|
+
},
|
|
3842
|
+
type: "object"
|
|
3843
|
+
},
|
|
3844
|
+
result: {
|
|
3845
|
+
additionalProperties: true,
|
|
3846
|
+
type: "object"
|
|
3847
|
+
},
|
|
3848
|
+
transfer: {
|
|
3849
|
+
additionalProperties: false,
|
|
3850
|
+
properties: {
|
|
3851
|
+
metadata: {
|
|
3852
|
+
additionalProperties: true,
|
|
3853
|
+
type: "object"
|
|
3854
|
+
},
|
|
3855
|
+
reason: {
|
|
3856
|
+
type: "string"
|
|
3857
|
+
},
|
|
3858
|
+
target: {
|
|
3859
|
+
type: "string"
|
|
3860
|
+
}
|
|
3861
|
+
},
|
|
3862
|
+
required: ["target"],
|
|
3863
|
+
type: "object"
|
|
3864
|
+
},
|
|
3865
|
+
voicemail: {
|
|
3866
|
+
additionalProperties: false,
|
|
3867
|
+
properties: {
|
|
3868
|
+
metadata: {
|
|
3869
|
+
additionalProperties: true,
|
|
3870
|
+
type: "object"
|
|
3871
|
+
}
|
|
3872
|
+
},
|
|
3873
|
+
type: "object"
|
|
3874
|
+
}
|
|
3875
|
+
},
|
|
3876
|
+
type: "object"
|
|
3877
|
+
};
|
|
3878
|
+
var ROUTE_RESULT_INSTRUCTION = "Return only a JSON object with assistantText, complete, transfer, escalate, voicemail, noAnswer, and result when you are not calling tools. Only set transfer, escalate, voicemail, or noAnswer when the user explicitly asks for that lifecycle outcome or a tool result says that exact outcome. Do not infer voicemail from generic words like voice, voice app, or voice integration.";
|
|
3879
|
+
var stripJSONCodeFence = (value) => {
|
|
3880
|
+
const trimmed = value.trim();
|
|
3881
|
+
const match = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
|
|
3882
|
+
return match?.[1]?.trim() ?? value;
|
|
3883
|
+
};
|
|
3884
|
+
var parseJSON = (value) => {
|
|
3885
|
+
try {
|
|
3886
|
+
const parsed = JSON.parse(stripJSONCodeFence(value));
|
|
3887
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
3888
|
+
} catch {
|
|
3889
|
+
return {
|
|
3890
|
+
assistantText: value
|
|
3891
|
+
};
|
|
3892
|
+
}
|
|
3893
|
+
};
|
|
3894
|
+
var parseJSONValue = (value) => {
|
|
3895
|
+
try {
|
|
3896
|
+
return JSON.parse(value);
|
|
3897
|
+
} catch {
|
|
3898
|
+
return value;
|
|
3899
|
+
}
|
|
3900
|
+
};
|
|
3901
|
+
|
|
3902
|
+
class VoiceProviderTimeoutError extends Error {
|
|
3903
|
+
provider;
|
|
3904
|
+
timeoutMs;
|
|
3905
|
+
constructor(provider, timeoutMs) {
|
|
3906
|
+
super(`Voice provider ${provider} exceeded ${timeoutMs}ms latency budget.`);
|
|
3907
|
+
this.name = "VoiceProviderTimeoutError";
|
|
3908
|
+
this.provider = provider;
|
|
3909
|
+
this.timeoutMs = timeoutMs;
|
|
3910
|
+
}
|
|
3911
|
+
}
|
|
3912
|
+
var getMessageToolCalls = (message) => {
|
|
3913
|
+
const toolCalls = message.metadata?.toolCalls;
|
|
3914
|
+
return Array.isArray(toolCalls) ? toolCalls.filter((toolCall) => toolCall && typeof toolCall === "object" && typeof toolCall.name === "string") : [];
|
|
3915
|
+
};
|
|
3916
|
+
var createHTTPError = (provider, response) => new Error(`${provider} voice assistant model failed: HTTP ${response.status}`);
|
|
3917
|
+
var sleep = (ms) => new Promise((resolve2) => {
|
|
3918
|
+
setTimeout(resolve2, ms);
|
|
3919
|
+
});
|
|
3920
|
+
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
3921
|
+
var defaultIsRateLimitError = (error) => /(\b429\b|rate limit|quota|too many requests)/i.test(errorMessage(error));
|
|
3922
|
+
var normalizeRouteOutput = (output) => {
|
|
3923
|
+
const result = {};
|
|
3924
|
+
if (typeof output.assistantText === "string") {
|
|
3925
|
+
result.assistantText = output.assistantText;
|
|
3926
|
+
}
|
|
3927
|
+
if (typeof output.complete === "boolean") {
|
|
3928
|
+
result.complete = output.complete;
|
|
3929
|
+
}
|
|
3930
|
+
if (output.result !== undefined) {
|
|
3931
|
+
result.result = output.result;
|
|
3932
|
+
}
|
|
3933
|
+
if (output.transfer && typeof output.transfer === "object") {
|
|
3934
|
+
const transfer = output.transfer;
|
|
3935
|
+
if (typeof transfer.target === "string") {
|
|
3936
|
+
result.transfer = {
|
|
3937
|
+
metadata: transfer.metadata && typeof transfer.metadata === "object" ? transfer.metadata : undefined,
|
|
3938
|
+
reason: typeof transfer.reason === "string" ? transfer.reason : undefined,
|
|
3939
|
+
target: transfer.target
|
|
3940
|
+
};
|
|
3941
|
+
}
|
|
3942
|
+
}
|
|
3943
|
+
if (output.escalate && typeof output.escalate === "object") {
|
|
3944
|
+
const escalate = output.escalate;
|
|
3945
|
+
if (typeof escalate.reason === "string") {
|
|
3946
|
+
result.escalate = {
|
|
3947
|
+
metadata: escalate.metadata && typeof escalate.metadata === "object" ? escalate.metadata : undefined,
|
|
3948
|
+
reason: escalate.reason
|
|
3949
|
+
};
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
if (output.voicemail && typeof output.voicemail === "object") {
|
|
3953
|
+
const voicemail = output.voicemail;
|
|
3954
|
+
result.voicemail = {
|
|
3955
|
+
metadata: voicemail.metadata && typeof voicemail.metadata === "object" ? voicemail.metadata : undefined
|
|
3956
|
+
};
|
|
3957
|
+
}
|
|
3958
|
+
if (output.noAnswer && typeof output.noAnswer === "object") {
|
|
3959
|
+
const noAnswer = output.noAnswer;
|
|
3960
|
+
result.noAnswer = {
|
|
3961
|
+
metadata: noAnswer.metadata && typeof noAnswer.metadata === "object" ? noAnswer.metadata : undefined
|
|
3962
|
+
};
|
|
3963
|
+
}
|
|
3964
|
+
return result;
|
|
3965
|
+
};
|
|
3966
|
+
var createJSONVoiceAssistantModel = (options) => ({
|
|
3967
|
+
generate: async (input) => {
|
|
3968
|
+
const output = await options.generate(input);
|
|
3969
|
+
if ("assistantText" in output || "toolCalls" in output || "complete" in output || "transfer" in output || "escalate" in output) {
|
|
3970
|
+
return output;
|
|
3971
|
+
}
|
|
3972
|
+
return options.mapOutput?.(output) ?? normalizeRouteOutput(output);
|
|
3973
|
+
}
|
|
3974
|
+
});
|
|
3975
|
+
var createVoiceProviderRouter = (options) => {
|
|
3976
|
+
const providerIds = Object.keys(options.providers);
|
|
3977
|
+
const firstProvider = providerIds[0];
|
|
3978
|
+
const policy = typeof options.policy === "string" ? options.policy === "balanced" || options.policy === "cost-cap" || options.policy === "cost-first" || options.policy === "latency-first" || options.policy === "quality-first" ? resolveVoiceProviderRoutingPolicyPreset(options.policy) : {
|
|
3979
|
+
strategy: options.policy
|
|
3980
|
+
} : options.policy;
|
|
3981
|
+
const strategy = policy?.strategy ?? "prefer-selected";
|
|
3982
|
+
const fallbackMode = policy?.fallbackMode ?? options.fallbackMode ?? "provider-error";
|
|
3983
|
+
const healthOptions = typeof options.providerHealth === "object" ? options.providerHealth : options.providerHealth ? {} : undefined;
|
|
3984
|
+
const healthState = new Map;
|
|
3985
|
+
const now = () => healthOptions?.now?.() ?? Date.now();
|
|
3986
|
+
const failureThreshold = Math.max(1, healthOptions?.failureThreshold ?? 1);
|
|
3987
|
+
const cooldownMs = Math.max(0, healthOptions?.cooldownMs ?? 30000);
|
|
3988
|
+
const rateLimitCooldownMs = Math.max(0, healthOptions?.rateLimitCooldownMs ?? 60000);
|
|
3989
|
+
const getProviderTimeoutMs = (provider) => {
|
|
3990
|
+
const timeoutMs = options.providerProfiles?.[provider]?.timeoutMs ?? options.timeoutMs;
|
|
3991
|
+
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : undefined;
|
|
3992
|
+
};
|
|
3993
|
+
const getHealth = (provider) => {
|
|
3994
|
+
const existing = healthState.get(provider);
|
|
3995
|
+
if (existing) {
|
|
3996
|
+
return existing;
|
|
3997
|
+
}
|
|
3998
|
+
const next = {
|
|
3999
|
+
consecutiveFailures: 0,
|
|
4000
|
+
provider,
|
|
4001
|
+
status: "healthy"
|
|
4002
|
+
};
|
|
4003
|
+
healthState.set(provider, next);
|
|
4004
|
+
return next;
|
|
4005
|
+
};
|
|
4006
|
+
const cloneHealth = (provider) => {
|
|
4007
|
+
if (!healthOptions) {
|
|
4008
|
+
return;
|
|
4009
|
+
}
|
|
4010
|
+
return {
|
|
4011
|
+
...getHealth(provider)
|
|
4012
|
+
};
|
|
4013
|
+
};
|
|
4014
|
+
const getSuppressionRemainingMs = (provider) => {
|
|
4015
|
+
if (!healthOptions) {
|
|
4016
|
+
return;
|
|
4017
|
+
}
|
|
4018
|
+
const suppressedUntil = getHealth(provider).suppressedUntil;
|
|
4019
|
+
return typeof suppressedUntil === "number" ? Math.max(0, suppressedUntil - now()) : undefined;
|
|
4020
|
+
};
|
|
4021
|
+
const isSuppressed = (provider) => {
|
|
4022
|
+
if (!healthOptions) {
|
|
4023
|
+
return false;
|
|
4024
|
+
}
|
|
4025
|
+
const health = getHealth(provider);
|
|
4026
|
+
return typeof health.suppressedUntil === "number" && health.suppressedUntil > now();
|
|
4027
|
+
};
|
|
4028
|
+
const recordProviderSuccess = (provider) => {
|
|
4029
|
+
if (!healthOptions) {
|
|
4030
|
+
return;
|
|
4031
|
+
}
|
|
4032
|
+
const health = getHealth(provider);
|
|
4033
|
+
health.consecutiveFailures = 0;
|
|
4034
|
+
health.status = "healthy";
|
|
4035
|
+
health.suppressedUntil = undefined;
|
|
4036
|
+
return cloneHealth(provider);
|
|
4037
|
+
};
|
|
4038
|
+
const recordProviderError = (provider, isProviderError, rateLimited) => {
|
|
4039
|
+
if (!healthOptions || !isProviderError) {
|
|
4040
|
+
return cloneHealth(provider);
|
|
4041
|
+
}
|
|
4042
|
+
const currentTime = now();
|
|
4043
|
+
const health = getHealth(provider);
|
|
4044
|
+
health.consecutiveFailures += 1;
|
|
4045
|
+
health.lastFailureAt = currentTime;
|
|
4046
|
+
if (rateLimited) {
|
|
4047
|
+
health.lastRateLimitedAt = currentTime;
|
|
4048
|
+
}
|
|
4049
|
+
if (rateLimited || health.consecutiveFailures >= failureThreshold) {
|
|
4050
|
+
health.status = "suppressed";
|
|
4051
|
+
health.suppressedUntil = currentTime + (rateLimited ? rateLimitCooldownMs : cooldownMs);
|
|
4052
|
+
}
|
|
4053
|
+
return cloneHealth(provider);
|
|
4054
|
+
};
|
|
4055
|
+
const resolveAllowedProviders = async (input) => {
|
|
4056
|
+
const allowProviders = policy?.allowProviders ?? options.allowProviders;
|
|
4057
|
+
const allowed = typeof allowProviders === "function" ? await allowProviders(input) : allowProviders;
|
|
4058
|
+
return new Set(allowed ?? providerIds);
|
|
4059
|
+
};
|
|
4060
|
+
const passesBudgetFilters = (provider) => {
|
|
4061
|
+
const profile = options.providerProfiles?.[provider];
|
|
4062
|
+
if (typeof policy?.maxCost === "number" && typeof profile?.cost === "number" && profile.cost > policy.maxCost) {
|
|
4063
|
+
return false;
|
|
4064
|
+
}
|
|
4065
|
+
if (typeof policy?.maxLatencyMs === "number" && typeof profile?.latencyMs === "number" && profile.latencyMs > policy.maxLatencyMs) {
|
|
4066
|
+
return false;
|
|
4067
|
+
}
|
|
4068
|
+
if (typeof policy?.minQuality === "number" && typeof profile?.quality === "number" && profile.quality < policy.minQuality) {
|
|
4069
|
+
return false;
|
|
4070
|
+
}
|
|
4071
|
+
return true;
|
|
4072
|
+
};
|
|
4073
|
+
const getBalancedScore = (provider) => {
|
|
4074
|
+
const profile = options.providerProfiles?.[provider];
|
|
4075
|
+
if (policy?.scoreProvider) {
|
|
4076
|
+
return policy.scoreProvider(provider, profile);
|
|
4077
|
+
}
|
|
4078
|
+
const weights = policy?.weights ?? {};
|
|
4079
|
+
return (profile?.cost ?? Number.MAX_SAFE_INTEGER) * (weights.cost ?? 1) + (profile?.latencyMs ?? Number.MAX_SAFE_INTEGER) * (weights.latencyMs ?? 0.005) + (profile?.priority ?? 0) * (weights.priority ?? 1) - (profile?.quality ?? 0) * (weights.quality ?? 10);
|
|
4080
|
+
};
|
|
4081
|
+
const sortProviders = (providers) => {
|
|
4082
|
+
if (strategy !== "prefer-cheapest" && strategy !== "prefer-fastest" && strategy !== "quality-first" && strategy !== "balanced") {
|
|
4083
|
+
return providers;
|
|
4084
|
+
}
|
|
4085
|
+
return [...providers].sort((left, right) => {
|
|
4086
|
+
const leftProfile = options.providerProfiles?.[left];
|
|
4087
|
+
const rightProfile = options.providerProfiles?.[right];
|
|
4088
|
+
if (strategy === "quality-first") {
|
|
4089
|
+
return (rightProfile?.quality ?? Number.MIN_SAFE_INTEGER) - (leftProfile?.quality ?? Number.MIN_SAFE_INTEGER) || (leftProfile?.priority ?? Number.MAX_SAFE_INTEGER) - (rightProfile?.priority ?? Number.MAX_SAFE_INTEGER) || (leftProfile?.latencyMs ?? Number.MAX_SAFE_INTEGER) - (rightProfile?.latencyMs ?? Number.MAX_SAFE_INTEGER) || (leftProfile?.cost ?? Number.MAX_SAFE_INTEGER) - (rightProfile?.cost ?? Number.MAX_SAFE_INTEGER);
|
|
4090
|
+
}
|
|
4091
|
+
if (strategy === "balanced") {
|
|
4092
|
+
return getBalancedScore(left) - getBalancedScore(right);
|
|
4093
|
+
}
|
|
4094
|
+
const leftValue = strategy === "prefer-cheapest" ? leftProfile?.cost ?? Number.MAX_SAFE_INTEGER : leftProfile?.latencyMs ?? Number.MAX_SAFE_INTEGER;
|
|
4095
|
+
const rightValue = strategy === "prefer-cheapest" ? rightProfile?.cost ?? Number.MAX_SAFE_INTEGER : rightProfile?.latencyMs ?? Number.MAX_SAFE_INTEGER;
|
|
4096
|
+
return leftValue - rightValue || (leftProfile?.priority ?? Number.MAX_SAFE_INTEGER) - (rightProfile?.priority ?? Number.MAX_SAFE_INTEGER);
|
|
4097
|
+
});
|
|
4098
|
+
};
|
|
4099
|
+
const resolveOrder = async (input) => {
|
|
4100
|
+
const selectedProvider = await options.selectProvider?.(input);
|
|
4101
|
+
const allowedProviders = await resolveAllowedProviders(input);
|
|
4102
|
+
const fallbackOrder = typeof options.fallback === "function" ? await options.fallback(input) : options.fallback;
|
|
4103
|
+
const allowedRankedProviders = sortProviders([
|
|
4104
|
+
...fallbackOrder ?? providerIds
|
|
4105
|
+
]).filter((provider) => allowedProviders.has(provider));
|
|
4106
|
+
const rankedProviders = allowedRankedProviders.filter(passesBudgetFilters);
|
|
4107
|
+
const healthyRankedProviders = healthOptions ? rankedProviders.filter((provider) => !isSuppressed(provider)) : rankedProviders;
|
|
4108
|
+
const candidateRankedProviders = healthyRankedProviders.length ? healthyRankedProviders : rankedProviders;
|
|
4109
|
+
const preferred = selectedProvider && allowedProviders.has(selectedProvider) && passesBudgetFilters(selectedProvider) && (!healthOptions || !isSuppressed(selectedProvider)) ? selectedProvider : candidateRankedProviders[0] ?? firstProvider;
|
|
4110
|
+
const seen = new Set;
|
|
4111
|
+
const order = [];
|
|
4112
|
+
const candidates = strategy === "ordered" ? candidateRankedProviders : [
|
|
4113
|
+
preferred,
|
|
4114
|
+
...candidateRankedProviders,
|
|
4115
|
+
...providerIds.filter((provider) => !healthOptions || !isSuppressed(provider))
|
|
4116
|
+
];
|
|
4117
|
+
for (const provider of candidates) {
|
|
4118
|
+
if (!provider || seen.has(provider) || !allowedProviders.has(provider) || !options.providers[provider]) {
|
|
4119
|
+
continue;
|
|
4120
|
+
}
|
|
4121
|
+
seen.add(provider);
|
|
4122
|
+
order.push(provider);
|
|
4123
|
+
}
|
|
4124
|
+
return {
|
|
4125
|
+
order,
|
|
4126
|
+
selectedProvider: preferred
|
|
4127
|
+
};
|
|
4128
|
+
};
|
|
4129
|
+
const emit = async (event, input) => {
|
|
4130
|
+
await options.onProviderEvent?.(event, input);
|
|
4131
|
+
};
|
|
4132
|
+
const runProvider = async (provider, model, input) => {
|
|
4133
|
+
const timeoutMs = getProviderTimeoutMs(provider);
|
|
4134
|
+
if (!timeoutMs) {
|
|
4135
|
+
return model.generate(input);
|
|
4136
|
+
}
|
|
4137
|
+
let timeout;
|
|
4138
|
+
try {
|
|
4139
|
+
return await Promise.race([
|
|
4140
|
+
model.generate(input),
|
|
4141
|
+
new Promise((_, reject) => {
|
|
4142
|
+
timeout = setTimeout(() => reject(new VoiceProviderTimeoutError(provider, timeoutMs)), timeoutMs);
|
|
4143
|
+
})
|
|
4144
|
+
]);
|
|
4145
|
+
} finally {
|
|
4146
|
+
if (timeout) {
|
|
4147
|
+
clearTimeout(timeout);
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
};
|
|
4151
|
+
return {
|
|
4152
|
+
generate: async (input) => {
|
|
4153
|
+
const { order, selectedProvider } = await resolveOrder(input);
|
|
4154
|
+
if (!selectedProvider || order.length === 0) {
|
|
4155
|
+
throw new Error("Voice provider router has no available providers.");
|
|
4156
|
+
}
|
|
4157
|
+
let lastError;
|
|
4158
|
+
for (const [index, provider] of order.entries()) {
|
|
4159
|
+
const model = options.providers[provider];
|
|
4160
|
+
if (!model) {
|
|
4161
|
+
continue;
|
|
4162
|
+
}
|
|
4163
|
+
const startedAt = Date.now();
|
|
4164
|
+
try {
|
|
4165
|
+
const output = await runProvider(provider, model, input);
|
|
4166
|
+
const providerHealth = recordProviderSuccess(provider);
|
|
4167
|
+
await emit({
|
|
4168
|
+
at: Date.now(),
|
|
4169
|
+
attempt: index + 1,
|
|
4170
|
+
elapsedMs: Date.now() - startedAt,
|
|
4171
|
+
fallbackProvider: provider === selectedProvider ? undefined : provider,
|
|
4172
|
+
latencyBudgetMs: getProviderTimeoutMs(provider),
|
|
4173
|
+
provider,
|
|
4174
|
+
providerHealth,
|
|
4175
|
+
recovered: provider !== selectedProvider,
|
|
4176
|
+
selectedProvider,
|
|
4177
|
+
status: provider === selectedProvider ? "success" : "fallback"
|
|
4178
|
+
}, input);
|
|
4179
|
+
return output;
|
|
4180
|
+
} catch (error) {
|
|
4181
|
+
lastError = error;
|
|
4182
|
+
const hasNextProvider = index < order.length - 1;
|
|
4183
|
+
const isProviderError = options.isProviderError?.(error, provider) ?? true;
|
|
4184
|
+
const timedOut = options.isTimeoutError?.(error, provider) ?? error instanceof VoiceProviderTimeoutError;
|
|
4185
|
+
const rateLimited = options.isRateLimitError?.(error, provider) ?? defaultIsRateLimitError(error);
|
|
4186
|
+
const shouldFallback = fallbackMode === "provider-error" ? isProviderError : fallbackMode === "rate-limit" ? isProviderError && rateLimited : false;
|
|
4187
|
+
const providerHealth = recordProviderError(provider, isProviderError, rateLimited);
|
|
4188
|
+
const nextProvider = hasNextProvider ? order[index + 1] : undefined;
|
|
4189
|
+
await emit({
|
|
4190
|
+
at: Date.now(),
|
|
4191
|
+
attempt: index + 1,
|
|
4192
|
+
elapsedMs: Date.now() - startedAt,
|
|
4193
|
+
error: errorMessage(error),
|
|
4194
|
+
fallbackProvider: shouldFallback ? nextProvider : undefined,
|
|
4195
|
+
latencyBudgetMs: getProviderTimeoutMs(provider),
|
|
4196
|
+
provider,
|
|
4197
|
+
providerHealth,
|
|
4198
|
+
rateLimited,
|
|
4199
|
+
selectedProvider,
|
|
4200
|
+
suppressionRemainingMs: getSuppressionRemainingMs(provider),
|
|
4201
|
+
suppressedUntil: providerHealth?.suppressedUntil,
|
|
4202
|
+
status: "error",
|
|
4203
|
+
timedOut
|
|
4204
|
+
}, input);
|
|
4205
|
+
if (!hasNextProvider || !shouldFallback) {
|
|
4206
|
+
throw error;
|
|
4207
|
+
}
|
|
4208
|
+
}
|
|
4209
|
+
}
|
|
4210
|
+
throw lastError ?? new Error("Voice provider router did not run a provider.");
|
|
4211
|
+
}
|
|
4212
|
+
};
|
|
4213
|
+
};
|
|
4214
|
+
var messageToOpenAIInput = (message) => {
|
|
4215
|
+
if (message.role === "tool") {
|
|
4216
|
+
return [
|
|
4217
|
+
{
|
|
4218
|
+
call_id: message.toolCallId ?? message.name ?? crypto.randomUUID(),
|
|
4219
|
+
output: message.content,
|
|
4220
|
+
type: "function_call_output"
|
|
4221
|
+
}
|
|
4222
|
+
];
|
|
4223
|
+
}
|
|
4224
|
+
const toolCalls = getMessageToolCalls(message);
|
|
4225
|
+
if (message.role === "assistant" && toolCalls.length) {
|
|
4226
|
+
return toolCalls.map((toolCall) => ({
|
|
4227
|
+
arguments: JSON.stringify(toolCall.args),
|
|
4228
|
+
call_id: toolCall.id ?? crypto.randomUUID(),
|
|
4229
|
+
name: toolCall.name,
|
|
4230
|
+
type: "function_call"
|
|
4231
|
+
}));
|
|
4232
|
+
}
|
|
4233
|
+
return [
|
|
4234
|
+
{
|
|
4235
|
+
content: message.content,
|
|
4236
|
+
role: message.role === "system" ? "developer" : message.role
|
|
4237
|
+
}
|
|
4238
|
+
];
|
|
4239
|
+
};
|
|
4240
|
+
var messagesToOpenAIInput = (messages) => messages.flatMap(messageToOpenAIInput);
|
|
4241
|
+
var messageToAnthropicMessage = (message) => {
|
|
4242
|
+
if (message.role === "system") {
|
|
4243
|
+
return;
|
|
4244
|
+
}
|
|
4245
|
+
if (message.role === "tool") {
|
|
4246
|
+
if (!message.toolCallId) {
|
|
4247
|
+
return {
|
|
4248
|
+
content: `Tool result from ${message.name ?? "tool"}: ${message.content}`,
|
|
4249
|
+
role: "user"
|
|
4250
|
+
};
|
|
4251
|
+
}
|
|
4252
|
+
return {
|
|
4253
|
+
content: [
|
|
4254
|
+
{
|
|
4255
|
+
content: message.content,
|
|
4256
|
+
tool_use_id: message.toolCallId,
|
|
4257
|
+
type: "tool_result"
|
|
4258
|
+
}
|
|
4259
|
+
],
|
|
4260
|
+
role: "user"
|
|
4261
|
+
};
|
|
4262
|
+
}
|
|
4263
|
+
const toolCalls = getMessageToolCalls(message);
|
|
4264
|
+
if (message.role === "assistant" && toolCalls.length) {
|
|
4265
|
+
return {
|
|
4266
|
+
content: [
|
|
4267
|
+
...message.content ? [
|
|
4268
|
+
{
|
|
4269
|
+
text: message.content,
|
|
4270
|
+
type: "text"
|
|
4271
|
+
}
|
|
4272
|
+
] : [],
|
|
4273
|
+
...toolCalls.map((toolCall) => ({
|
|
4274
|
+
id: toolCall.id ?? crypto.randomUUID(),
|
|
4275
|
+
input: toolCall.args,
|
|
4276
|
+
name: toolCall.name,
|
|
4277
|
+
type: "tool_use"
|
|
4278
|
+
}))
|
|
4279
|
+
],
|
|
4280
|
+
role: "assistant"
|
|
4281
|
+
};
|
|
4282
|
+
}
|
|
4283
|
+
return {
|
|
4284
|
+
content: message.content,
|
|
4285
|
+
role: message.role
|
|
4286
|
+
};
|
|
4287
|
+
};
|
|
4288
|
+
var toGeminiSchema = (schema) => {
|
|
4289
|
+
const next = {};
|
|
4290
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
4291
|
+
if (key === "additionalProperties") {
|
|
4292
|
+
continue;
|
|
4293
|
+
}
|
|
4294
|
+
if (key === "type" && typeof value === "string") {
|
|
4295
|
+
next[key] = value.toUpperCase();
|
|
4296
|
+
continue;
|
|
4297
|
+
}
|
|
4298
|
+
if (Array.isArray(value)) {
|
|
4299
|
+
next[key] = value.map((item) => item && typeof item === "object" ? toGeminiSchema(item) : item);
|
|
4300
|
+
continue;
|
|
4301
|
+
}
|
|
4302
|
+
if (value && typeof value === "object") {
|
|
4303
|
+
next[key] = toGeminiSchema(value);
|
|
4304
|
+
continue;
|
|
4305
|
+
}
|
|
4306
|
+
next[key] = value;
|
|
4307
|
+
}
|
|
4308
|
+
return next;
|
|
4309
|
+
};
|
|
4310
|
+
var messageToGeminiContent = (message) => {
|
|
4311
|
+
if (message.role === "system") {
|
|
4312
|
+
return;
|
|
4313
|
+
}
|
|
4314
|
+
if (message.role === "tool") {
|
|
4315
|
+
return {
|
|
4316
|
+
parts: [
|
|
4317
|
+
{
|
|
4318
|
+
functionResponse: {
|
|
4319
|
+
id: message.toolCallId,
|
|
4320
|
+
name: message.name ?? "tool",
|
|
4321
|
+
response: {
|
|
4322
|
+
result: parseJSONValue(message.content)
|
|
4323
|
+
}
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
],
|
|
4327
|
+
role: "user"
|
|
4328
|
+
};
|
|
4329
|
+
}
|
|
4330
|
+
const toolCalls = getMessageToolCalls(message);
|
|
4331
|
+
if (message.role === "assistant" && toolCalls.length) {
|
|
4332
|
+
return {
|
|
4333
|
+
parts: [
|
|
4334
|
+
...message.content ? [
|
|
4335
|
+
{
|
|
4336
|
+
text: message.content
|
|
4337
|
+
}
|
|
4338
|
+
] : [],
|
|
4339
|
+
...toolCalls.map((toolCall) => ({
|
|
4340
|
+
functionCall: {
|
|
4341
|
+
args: toolCall.args,
|
|
4342
|
+
id: toolCall.id,
|
|
4343
|
+
name: toolCall.name
|
|
4344
|
+
}
|
|
4345
|
+
}))
|
|
4346
|
+
],
|
|
4347
|
+
role: "model"
|
|
4348
|
+
};
|
|
4349
|
+
}
|
|
4350
|
+
return {
|
|
4351
|
+
parts: [
|
|
4352
|
+
{
|
|
4353
|
+
text: message.content
|
|
4354
|
+
}
|
|
4355
|
+
],
|
|
4356
|
+
role: message.role === "assistant" ? "model" : "user"
|
|
4357
|
+
};
|
|
4358
|
+
};
|
|
4359
|
+
var extractText = (response) => {
|
|
4360
|
+
if (typeof response.output_text === "string") {
|
|
4361
|
+
return response.output_text;
|
|
4362
|
+
}
|
|
4363
|
+
const output = Array.isArray(response.output) ? response.output : [];
|
|
4364
|
+
for (const item of output) {
|
|
4365
|
+
if (!item || typeof item !== "object") {
|
|
4366
|
+
continue;
|
|
4367
|
+
}
|
|
4368
|
+
const record = item;
|
|
4369
|
+
const content = Array.isArray(record.content) ? record.content : [];
|
|
4370
|
+
for (const contentItem of content) {
|
|
4371
|
+
if (!contentItem || typeof contentItem !== "object") {
|
|
4372
|
+
continue;
|
|
4373
|
+
}
|
|
4374
|
+
const contentRecord = contentItem;
|
|
4375
|
+
if (typeof contentRecord.text === "string") {
|
|
4376
|
+
return contentRecord.text;
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
}
|
|
4380
|
+
return "";
|
|
4381
|
+
};
|
|
4382
|
+
var extractToolCalls = (response) => {
|
|
4383
|
+
const output = Array.isArray(response.output) ? response.output : [];
|
|
4384
|
+
const toolCalls = [];
|
|
4385
|
+
for (const item of output) {
|
|
4386
|
+
if (!item || typeof item !== "object") {
|
|
4387
|
+
continue;
|
|
4388
|
+
}
|
|
4389
|
+
const record = item;
|
|
4390
|
+
if (record.type !== "function_call" || typeof record.name !== "string") {
|
|
4391
|
+
continue;
|
|
4392
|
+
}
|
|
4393
|
+
const args = typeof record.arguments === "string" ? parseJSON(record.arguments) : {};
|
|
4394
|
+
toolCalls.push({
|
|
4395
|
+
args,
|
|
4396
|
+
id: typeof record.call_id === "string" ? record.call_id : typeof record.id === "string" ? record.id : undefined,
|
|
4397
|
+
name: record.name
|
|
4398
|
+
});
|
|
4399
|
+
}
|
|
4400
|
+
return toolCalls;
|
|
4401
|
+
};
|
|
4402
|
+
var createOpenAIVoiceAssistantModel = (options) => {
|
|
4403
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
4404
|
+
const baseUrl = options.baseUrl ?? "https://api.openai.com/v1";
|
|
4405
|
+
const model = options.model ?? "gpt-4.1-mini";
|
|
4406
|
+
return {
|
|
4407
|
+
generate: async (input) => {
|
|
4408
|
+
const response = await fetchImpl(`${baseUrl.replace(/\/$/, "")}/responses`, {
|
|
4409
|
+
body: JSON.stringify({
|
|
4410
|
+
input: messagesToOpenAIInput(input.messages),
|
|
4411
|
+
instructions: [
|
|
4412
|
+
input.system,
|
|
4413
|
+
"Return a JSON object with assistantText, complete, transfer, escalate, voicemail, noAnswer, and result when you are not calling tools."
|
|
4414
|
+
].filter(Boolean).join(`
|
|
4415
|
+
|
|
4416
|
+
`),
|
|
4417
|
+
max_output_tokens: options.maxOutputTokens,
|
|
4418
|
+
model,
|
|
4419
|
+
temperature: options.temperature,
|
|
4420
|
+
text: {
|
|
4421
|
+
format: {
|
|
4422
|
+
name: "voice_route_result",
|
|
4423
|
+
schema: OUTPUT_SCHEMA,
|
|
4424
|
+
strict: false,
|
|
4425
|
+
type: "json_schema"
|
|
4426
|
+
}
|
|
4427
|
+
},
|
|
4428
|
+
tool_choice: input.tools.length ? "auto" : "none",
|
|
4429
|
+
tools: input.tools.map((tool) => ({
|
|
4430
|
+
description: tool.description,
|
|
4431
|
+
name: tool.name,
|
|
4432
|
+
parameters: tool.parameters ?? {
|
|
4433
|
+
additionalProperties: true,
|
|
4434
|
+
type: "object"
|
|
4435
|
+
},
|
|
4436
|
+
strict: false,
|
|
4437
|
+
type: "function"
|
|
4438
|
+
}))
|
|
4439
|
+
}),
|
|
4440
|
+
headers: {
|
|
4441
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
4442
|
+
"content-type": "application/json"
|
|
4443
|
+
},
|
|
4444
|
+
method: "POST"
|
|
4445
|
+
});
|
|
4446
|
+
if (!response.ok) {
|
|
4447
|
+
throw createHTTPError("OpenAI", response);
|
|
4448
|
+
}
|
|
4449
|
+
const body = await response.json();
|
|
4450
|
+
if (body.usage && typeof body.usage === "object") {
|
|
4451
|
+
await options.onUsage?.(body.usage);
|
|
4452
|
+
}
|
|
4453
|
+
const toolCalls = extractToolCalls(body);
|
|
4454
|
+
if (toolCalls.length) {
|
|
4455
|
+
return {
|
|
4456
|
+
toolCalls
|
|
4457
|
+
};
|
|
4458
|
+
}
|
|
4459
|
+
return normalizeRouteOutput(parseJSON(extractText(body)));
|
|
4460
|
+
}
|
|
4461
|
+
};
|
|
4462
|
+
};
|
|
4463
|
+
var extractAnthropicText = (response) => {
|
|
4464
|
+
const content = Array.isArray(response.content) ? response.content : [];
|
|
4465
|
+
return content.map((item) => item && typeof item === "object" && item.type === "text" && typeof item.text === "string" ? item.text : "").filter(Boolean).join(`
|
|
4466
|
+
`);
|
|
4467
|
+
};
|
|
4468
|
+
var extractAnthropicToolCalls = (response) => {
|
|
4469
|
+
const content = Array.isArray(response.content) ? response.content : [];
|
|
4470
|
+
const toolCalls = [];
|
|
4471
|
+
for (const item of content) {
|
|
4472
|
+
if (!item || typeof item !== "object") {
|
|
4473
|
+
continue;
|
|
4474
|
+
}
|
|
4475
|
+
const record = item;
|
|
4476
|
+
if (record.type !== "tool_use" || typeof record.name !== "string") {
|
|
4477
|
+
continue;
|
|
4478
|
+
}
|
|
4479
|
+
toolCalls.push({
|
|
4480
|
+
args: record.input && typeof record.input === "object" ? record.input : {},
|
|
4481
|
+
id: typeof record.id === "string" ? record.id : undefined,
|
|
4482
|
+
name: record.name
|
|
4483
|
+
});
|
|
4484
|
+
}
|
|
4485
|
+
return toolCalls;
|
|
4486
|
+
};
|
|
4487
|
+
var createAnthropicVoiceAssistantModel = (options) => {
|
|
4488
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
4489
|
+
const baseUrl = options.baseUrl ?? "https://api.anthropic.com/v1";
|
|
4490
|
+
const model = options.model ?? "claude-sonnet-4-5";
|
|
4491
|
+
return {
|
|
4492
|
+
generate: async (input) => {
|
|
4493
|
+
const response = await fetchImpl(`${baseUrl.replace(/\/$/, "")}/messages`, {
|
|
4494
|
+
body: JSON.stringify({
|
|
4495
|
+
max_tokens: options.maxOutputTokens ?? 1024,
|
|
4496
|
+
messages: input.messages.map(messageToAnthropicMessage).filter(Boolean),
|
|
4497
|
+
model,
|
|
4498
|
+
system: [input.system, ROUTE_RESULT_INSTRUCTION].filter(Boolean).join(`
|
|
4499
|
+
|
|
4500
|
+
`),
|
|
4501
|
+
temperature: options.temperature,
|
|
4502
|
+
tool_choice: input.tools.length ? { type: "auto" } : { type: "none" },
|
|
4503
|
+
tools: input.tools.map((tool) => ({
|
|
4504
|
+
description: tool.description,
|
|
4505
|
+
input_schema: tool.parameters ?? {
|
|
4506
|
+
additionalProperties: true,
|
|
4507
|
+
type: "object"
|
|
4508
|
+
},
|
|
4509
|
+
name: tool.name
|
|
4510
|
+
}))
|
|
4511
|
+
}),
|
|
4512
|
+
headers: {
|
|
4513
|
+
"anthropic-version": options.version ?? "2023-06-01",
|
|
4514
|
+
"content-type": "application/json",
|
|
4515
|
+
"x-api-key": options.apiKey
|
|
4516
|
+
},
|
|
4517
|
+
method: "POST"
|
|
4518
|
+
});
|
|
4519
|
+
if (!response.ok) {
|
|
4520
|
+
throw createHTTPError("Anthropic", response);
|
|
4521
|
+
}
|
|
4522
|
+
const body = await response.json();
|
|
4523
|
+
if (body.usage && typeof body.usage === "object") {
|
|
4524
|
+
await options.onUsage?.(body.usage);
|
|
4525
|
+
}
|
|
4526
|
+
const toolCalls = extractAnthropicToolCalls(body);
|
|
4527
|
+
if (toolCalls.length) {
|
|
4528
|
+
return {
|
|
4529
|
+
assistantText: extractAnthropicText(body) || undefined,
|
|
4530
|
+
toolCalls
|
|
4531
|
+
};
|
|
4532
|
+
}
|
|
4533
|
+
return normalizeRouteOutput(parseJSON(extractAnthropicText(body)));
|
|
4534
|
+
}
|
|
4535
|
+
};
|
|
4536
|
+
};
|
|
4537
|
+
var extractGeminiCandidateParts = (response) => {
|
|
4538
|
+
const candidates = Array.isArray(response.candidates) ? response.candidates : [];
|
|
4539
|
+
const first = candidates[0];
|
|
4540
|
+
if (!first || typeof first !== "object") {
|
|
4541
|
+
return [];
|
|
4542
|
+
}
|
|
4543
|
+
const content = first.content;
|
|
4544
|
+
if (!content || typeof content !== "object") {
|
|
4545
|
+
return [];
|
|
4546
|
+
}
|
|
4547
|
+
const parts = content.parts;
|
|
4548
|
+
return Array.isArray(parts) ? parts : [];
|
|
4549
|
+
};
|
|
4550
|
+
var extractGeminiText = (response) => extractGeminiCandidateParts(response).map((part) => part && typeof part === "object" && typeof part.text === "string" ? part.text : "").filter(Boolean).join(`
|
|
4551
|
+
`);
|
|
4552
|
+
var extractGeminiToolCalls = (response) => {
|
|
4553
|
+
const toolCalls = [];
|
|
4554
|
+
for (const part of extractGeminiCandidateParts(response)) {
|
|
4555
|
+
if (!part || typeof part !== "object") {
|
|
4556
|
+
continue;
|
|
4557
|
+
}
|
|
4558
|
+
const functionCall = part.functionCall;
|
|
4559
|
+
if (!functionCall || typeof functionCall !== "object") {
|
|
4560
|
+
continue;
|
|
4561
|
+
}
|
|
4562
|
+
const record = functionCall;
|
|
4563
|
+
if (typeof record.name !== "string") {
|
|
4564
|
+
continue;
|
|
4565
|
+
}
|
|
4566
|
+
toolCalls.push({
|
|
4567
|
+
args: record.args && typeof record.args === "object" ? record.args : {},
|
|
4568
|
+
id: typeof record.id === "string" ? record.id : undefined,
|
|
4569
|
+
name: record.name
|
|
4570
|
+
});
|
|
4571
|
+
}
|
|
4572
|
+
return toolCalls;
|
|
4573
|
+
};
|
|
4574
|
+
var createGeminiVoiceAssistantModel = (options) => {
|
|
4575
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
4576
|
+
const baseUrl = options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta";
|
|
4577
|
+
const model = options.model ?? "gemini-2.5-flash";
|
|
4578
|
+
const maxRetries = Math.max(0, options.maxRetries ?? 2);
|
|
4579
|
+
return {
|
|
4580
|
+
generate: async (input) => {
|
|
4581
|
+
const endpoint = `${baseUrl.replace(/\/$/, "")}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(options.apiKey)}`;
|
|
4582
|
+
let response;
|
|
4583
|
+
for (let attempt = 0;attempt <= maxRetries; attempt += 1) {
|
|
4584
|
+
response = await fetchImpl(endpoint, {
|
|
4585
|
+
body: JSON.stringify({
|
|
4586
|
+
contents: input.messages.map(messageToGeminiContent).filter(Boolean),
|
|
4587
|
+
generationConfig: {
|
|
4588
|
+
maxOutputTokens: options.maxOutputTokens,
|
|
4589
|
+
...input.tools.length ? {} : {
|
|
4590
|
+
responseMimeType: "application/json",
|
|
4591
|
+
responseSchema: toGeminiSchema(OUTPUT_SCHEMA)
|
|
4592
|
+
},
|
|
4593
|
+
temperature: options.temperature
|
|
4594
|
+
},
|
|
4595
|
+
systemInstruction: {
|
|
4596
|
+
parts: [
|
|
4597
|
+
{
|
|
4598
|
+
text: [input.system, ROUTE_RESULT_INSTRUCTION].filter(Boolean).join(`
|
|
4599
|
+
|
|
4600
|
+
`)
|
|
4601
|
+
}
|
|
4602
|
+
]
|
|
4603
|
+
},
|
|
4604
|
+
tools: input.tools.length ? [
|
|
4605
|
+
{
|
|
4606
|
+
functionDeclarations: input.tools.map((tool) => ({
|
|
4607
|
+
description: tool.description,
|
|
4608
|
+
name: tool.name,
|
|
4609
|
+
parameters: toGeminiSchema(tool.parameters ?? {
|
|
4610
|
+
additionalProperties: true,
|
|
4611
|
+
type: "object"
|
|
4612
|
+
})
|
|
4613
|
+
}))
|
|
4614
|
+
}
|
|
4615
|
+
] : undefined
|
|
4616
|
+
}),
|
|
4617
|
+
headers: {
|
|
4618
|
+
"content-type": "application/json"
|
|
4619
|
+
},
|
|
4620
|
+
method: "POST"
|
|
4621
|
+
});
|
|
4622
|
+
if (response.ok || response.status !== 429 && response.status < 500 || attempt === maxRetries) {
|
|
4623
|
+
break;
|
|
4624
|
+
}
|
|
4625
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
4626
|
+
await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 500 * 2 ** attempt);
|
|
4627
|
+
}
|
|
4628
|
+
if (!response) {
|
|
4629
|
+
throw new Error("Gemini voice assistant model failed: no response");
|
|
4630
|
+
}
|
|
4631
|
+
if (!response.ok) {
|
|
4632
|
+
throw createHTTPError("Gemini", response);
|
|
4633
|
+
}
|
|
4634
|
+
const body = await response.json();
|
|
4635
|
+
if (body.usageMetadata && typeof body.usageMetadata === "object") {
|
|
4636
|
+
await options.onUsage?.(body.usageMetadata);
|
|
4637
|
+
}
|
|
4638
|
+
const toolCalls = extractGeminiToolCalls(body);
|
|
4639
|
+
if (toolCalls.length) {
|
|
4640
|
+
return {
|
|
4641
|
+
assistantText: extractGeminiText(body) || undefined,
|
|
4642
|
+
toolCalls
|
|
4643
|
+
};
|
|
4644
|
+
}
|
|
4645
|
+
return normalizeRouteOutput(parseJSON(extractGeminiText(body)));
|
|
4646
|
+
}
|
|
4647
|
+
};
|
|
4648
|
+
};
|
|
4649
|
+
|
|
3471
4650
|
// src/store.ts
|
|
3472
4651
|
var createId = () => crypto.randomUUID();
|
|
3473
4652
|
var createVoiceSessionRecord = (id, scenarioId) => ({
|
|
@@ -3508,6 +4687,118 @@ var toVoiceSessionSummary = (session) => ({
|
|
|
3508
4687
|
turnCount: session.turns.length
|
|
3509
4688
|
});
|
|
3510
4689
|
|
|
4690
|
+
// src/testing/providerSimulator.ts
|
|
4691
|
+
var getContextQuery = (context) => context.query;
|
|
4692
|
+
var titleCaseProvider = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => part[0]?.toUpperCase() + part.slice(1)).join(" ");
|
|
4693
|
+
var resolveRequestedProvider = (context, providers) => {
|
|
4694
|
+
const provider = getContextQuery(context).provider;
|
|
4695
|
+
return providers.includes(provider) ? provider : providers[0];
|
|
4696
|
+
};
|
|
4697
|
+
var createVoiceProviderFailureSimulator = (options) => {
|
|
4698
|
+
if (options.providers.length === 0) {
|
|
4699
|
+
throw new Error("At least one provider is required.");
|
|
4700
|
+
}
|
|
4701
|
+
const providerModels = Object.fromEntries(options.providers.map((provider) => [
|
|
4702
|
+
provider,
|
|
4703
|
+
{
|
|
4704
|
+
generate: async (input) => {
|
|
4705
|
+
const query = getContextQuery(input.context);
|
|
4706
|
+
if (provider === query.simulateFailureProvider) {
|
|
4707
|
+
const label = options.providerLabel?.(provider) ?? titleCaseProvider(provider);
|
|
4708
|
+
throw new Error(`${label} voice assistant model failed: HTTP 429`);
|
|
4709
|
+
}
|
|
4710
|
+
if (options.response) {
|
|
4711
|
+
return options.response({
|
|
4712
|
+
...input,
|
|
4713
|
+
mode: query.recoverProvider === provider ? "recovery" : "failure",
|
|
4714
|
+
provider
|
|
4715
|
+
});
|
|
4716
|
+
}
|
|
4717
|
+
return {
|
|
4718
|
+
assistantText: `Simulated ${provider} provider recovered.`
|
|
4719
|
+
};
|
|
4720
|
+
}
|
|
4721
|
+
}
|
|
4722
|
+
]));
|
|
4723
|
+
const router = createVoiceProviderRouter({
|
|
4724
|
+
allowProviders: async (input) => {
|
|
4725
|
+
const recoverProvider = getContextQuery(input.context).recoverProvider;
|
|
4726
|
+
if (recoverProvider) {
|
|
4727
|
+
return [recoverProvider];
|
|
4728
|
+
}
|
|
4729
|
+
if (typeof options.allowProviders === "function") {
|
|
4730
|
+
return options.allowProviders(input);
|
|
4731
|
+
}
|
|
4732
|
+
return options.allowProviders ?? options.providers;
|
|
4733
|
+
},
|
|
4734
|
+
fallback: async (input) => {
|
|
4735
|
+
const selectedProvider = resolveRequestedProvider(input.context, options.providers);
|
|
4736
|
+
if (typeof options.fallback === "function") {
|
|
4737
|
+
return options.fallback(selectedProvider, input);
|
|
4738
|
+
}
|
|
4739
|
+
return options.fallback ?? options.providers.filter((provider) => provider !== selectedProvider);
|
|
4740
|
+
},
|
|
4741
|
+
fallbackMode: "provider-error",
|
|
4742
|
+
isProviderError: options.isProviderError,
|
|
4743
|
+
isRateLimitError: options.isRateLimitError,
|
|
4744
|
+
onProviderEvent: options.onProviderEvent,
|
|
4745
|
+
policy: "prefer-selected",
|
|
4746
|
+
providerHealth: options.providerHealth ?? {
|
|
4747
|
+
cooldownMs: 30000,
|
|
4748
|
+
failureThreshold: 1,
|
|
4749
|
+
rateLimitCooldownMs: 120000
|
|
4750
|
+
},
|
|
4751
|
+
providers: providerModels,
|
|
4752
|
+
selectProvider: ({ context }) => resolveRequestedProvider(context, options.providers)
|
|
4753
|
+
});
|
|
4754
|
+
const run = async (provider, mode) => {
|
|
4755
|
+
const now = Date.now();
|
|
4756
|
+
const session = createVoiceSessionRecord(`provider-sim-${now}`, "provider-simulation");
|
|
4757
|
+
const turn = {
|
|
4758
|
+
committedAt: now,
|
|
4759
|
+
id: `provider-sim-turn-${now}`,
|
|
4760
|
+
text: mode === "failure" ? `Simulate ${provider} provider failure.` : `Simulate ${provider} provider recovery.`,
|
|
4761
|
+
transcripts: []
|
|
4762
|
+
};
|
|
4763
|
+
const context = {
|
|
4764
|
+
query: {
|
|
4765
|
+
provider,
|
|
4766
|
+
...mode === "recovery" ? { recoverProvider: provider } : {},
|
|
4767
|
+
...mode === "failure" ? { simulateFailureProvider: provider } : {}
|
|
4768
|
+
}
|
|
4769
|
+
};
|
|
4770
|
+
const result = await router.generate({
|
|
4771
|
+
agentId: "provider-simulator",
|
|
4772
|
+
context,
|
|
4773
|
+
messages: [
|
|
4774
|
+
{
|
|
4775
|
+
content: turn.text,
|
|
4776
|
+
role: "user"
|
|
4777
|
+
}
|
|
4778
|
+
],
|
|
4779
|
+
session,
|
|
4780
|
+
system: "Simulate provider routing without calling external APIs.",
|
|
4781
|
+
tools: [],
|
|
4782
|
+
turn
|
|
4783
|
+
});
|
|
4784
|
+
return {
|
|
4785
|
+
mode,
|
|
4786
|
+
provider,
|
|
4787
|
+
replayHref: options.replayHref === false ? undefined : typeof options.replayHref === "function" ? options.replayHref({
|
|
4788
|
+
provider,
|
|
4789
|
+
sessionId: session.id,
|
|
4790
|
+
turnId: turn.id
|
|
4791
|
+
}) : `${options.replayHref ?? "/api/voice-sessions"}/${encodeURIComponent(session.id)}/replay/htmx`,
|
|
4792
|
+
result,
|
|
4793
|
+
sessionId: session.id,
|
|
4794
|
+
status: "simulated",
|
|
4795
|
+
turnId: turn.id
|
|
4796
|
+
};
|
|
4797
|
+
};
|
|
4798
|
+
return {
|
|
4799
|
+
run
|
|
4800
|
+
};
|
|
4801
|
+
};
|
|
3511
4802
|
// src/memoryStore.ts
|
|
3512
4803
|
var createVoiceMemoryStore = () => {
|
|
3513
4804
|
const sessions = new Map;
|
|
@@ -3531,7 +4822,290 @@ var createVoiceMemoryStore = () => {
|
|
|
3531
4822
|
};
|
|
3532
4823
|
|
|
3533
4824
|
// src/session.ts
|
|
3534
|
-
import { Buffer } from "buffer";
|
|
4825
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
4826
|
+
|
|
4827
|
+
// src/handoff.ts
|
|
4828
|
+
var toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
4829
|
+
var signHandoffBody = async (input) => {
|
|
4830
|
+
const encoder = new TextEncoder;
|
|
4831
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(input.secret), {
|
|
4832
|
+
hash: "SHA-256",
|
|
4833
|
+
name: "HMAC"
|
|
4834
|
+
}, false, ["sign"]);
|
|
4835
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(`${input.timestamp}.${input.body}`));
|
|
4836
|
+
return `sha256=${toHex(new Uint8Array(signature))}`;
|
|
4837
|
+
};
|
|
4838
|
+
var toErrorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
4839
|
+
var createSkippedDelivery = (adapter) => ({
|
|
4840
|
+
adapterId: adapter.id,
|
|
4841
|
+
adapterKind: adapter.kind,
|
|
4842
|
+
status: "skipped"
|
|
4843
|
+
});
|
|
4844
|
+
var aggregateHandoffStatus = (deliveries) => {
|
|
4845
|
+
const statuses = Object.values(deliveries).map((delivery) => delivery.status);
|
|
4846
|
+
if (statuses.some((status) => status === "failed")) {
|
|
4847
|
+
return "failed";
|
|
4848
|
+
}
|
|
4849
|
+
if (statuses.some((status) => status === "delivered")) {
|
|
4850
|
+
return "delivered";
|
|
4851
|
+
}
|
|
4852
|
+
return "skipped";
|
|
4853
|
+
};
|
|
4854
|
+
var createHandoffDeliveryId = (input) => [
|
|
4855
|
+
"voice-handoff",
|
|
4856
|
+
input.sessionId,
|
|
4857
|
+
input.action,
|
|
4858
|
+
Date.now(),
|
|
4859
|
+
crypto.randomUUID()
|
|
4860
|
+
].join(":");
|
|
4861
|
+
var resolveHandoffDeliveryError = (deliveries) => Object.values(deliveries).map((delivery) => delivery.error).find(Boolean);
|
|
4862
|
+
var defaultWebhookBody = (input) => ({
|
|
4863
|
+
action: input.action,
|
|
4864
|
+
metadata: input.metadata,
|
|
4865
|
+
reason: input.reason,
|
|
4866
|
+
result: input.result,
|
|
4867
|
+
session: {
|
|
4868
|
+
id: input.session.id,
|
|
4869
|
+
scenarioId: input.session.scenarioId,
|
|
4870
|
+
status: input.session.status
|
|
4871
|
+
},
|
|
4872
|
+
source: "absolutejs-voice",
|
|
4873
|
+
target: input.target
|
|
4874
|
+
});
|
|
4875
|
+
var deliverVoiceHandoff = async (input) => {
|
|
4876
|
+
if (!input.config || input.config.adapters.length === 0) {
|
|
4877
|
+
return;
|
|
4878
|
+
}
|
|
4879
|
+
const deliveries = {};
|
|
4880
|
+
for (const adapter of input.config.adapters) {
|
|
4881
|
+
if (adapter.actions && !adapter.actions.includes(input.handoff.action)) {
|
|
4882
|
+
deliveries[adapter.id] = createSkippedDelivery(adapter);
|
|
4883
|
+
continue;
|
|
4884
|
+
}
|
|
4885
|
+
try {
|
|
4886
|
+
const result = await adapter.handoff(input.handoff);
|
|
4887
|
+
deliveries[adapter.id] = {
|
|
4888
|
+
...result,
|
|
4889
|
+
adapterId: adapter.id,
|
|
4890
|
+
adapterKind: adapter.kind
|
|
4891
|
+
};
|
|
4892
|
+
} catch (error) {
|
|
4893
|
+
deliveries[adapter.id] = {
|
|
4894
|
+
adapterId: adapter.id,
|
|
4895
|
+
adapterKind: adapter.kind,
|
|
4896
|
+
error: toErrorMessage(error),
|
|
4897
|
+
status: "failed"
|
|
4898
|
+
};
|
|
4899
|
+
if (input.config.failMode === "throw") {
|
|
4900
|
+
throw error;
|
|
4901
|
+
}
|
|
4902
|
+
}
|
|
4903
|
+
}
|
|
4904
|
+
return {
|
|
4905
|
+
action: input.handoff.action,
|
|
4906
|
+
deliveries,
|
|
4907
|
+
status: aggregateHandoffStatus(deliveries)
|
|
4908
|
+
};
|
|
4909
|
+
};
|
|
4910
|
+
var createVoiceHandoffDeliveryRecord = (input) => {
|
|
4911
|
+
const now = Date.now();
|
|
4912
|
+
return {
|
|
4913
|
+
action: input.action,
|
|
4914
|
+
context: input.context,
|
|
4915
|
+
createdAt: now,
|
|
4916
|
+
deliveryAttempts: 0,
|
|
4917
|
+
deliveryStatus: "pending",
|
|
4918
|
+
id: input.id ?? createHandoffDeliveryId({
|
|
4919
|
+
action: input.action,
|
|
4920
|
+
sessionId: input.session.id
|
|
4921
|
+
}),
|
|
4922
|
+
metadata: input.metadata,
|
|
4923
|
+
reason: input.reason,
|
|
4924
|
+
result: input.result,
|
|
4925
|
+
session: input.session,
|
|
4926
|
+
sessionId: input.session.id,
|
|
4927
|
+
target: input.target,
|
|
4928
|
+
updatedAt: now
|
|
4929
|
+
};
|
|
4930
|
+
};
|
|
4931
|
+
var applyVoiceHandoffDeliveryResult = (delivery, result) => ({
|
|
4932
|
+
...delivery,
|
|
4933
|
+
deliveredAt: result.status === "delivered" || result.status === "skipped" ? Date.now() : delivery.deliveredAt,
|
|
4934
|
+
deliveries: result.deliveries,
|
|
4935
|
+
deliveryAttempts: (delivery.deliveryAttempts ?? 0) + 1,
|
|
4936
|
+
deliveryError: result.status === "failed" ? resolveHandoffDeliveryError(result.deliveries) : undefined,
|
|
4937
|
+
deliveryStatus: result.status,
|
|
4938
|
+
updatedAt: Date.now()
|
|
4939
|
+
});
|
|
4940
|
+
var deliverVoiceHandoffDelivery = async (options) => {
|
|
4941
|
+
const result = await deliverVoiceHandoff({
|
|
4942
|
+
config: {
|
|
4943
|
+
adapters: options.adapters,
|
|
4944
|
+
failMode: options.failMode
|
|
4945
|
+
},
|
|
4946
|
+
handoff: {
|
|
4947
|
+
action: options.delivery.action,
|
|
4948
|
+
api: options.api,
|
|
4949
|
+
context: options.delivery.context,
|
|
4950
|
+
metadata: options.delivery.metadata,
|
|
4951
|
+
reason: options.delivery.reason,
|
|
4952
|
+
result: options.delivery.result,
|
|
4953
|
+
session: options.delivery.session,
|
|
4954
|
+
target: options.delivery.target
|
|
4955
|
+
}
|
|
4956
|
+
});
|
|
4957
|
+
return result ? applyVoiceHandoffDeliveryResult(options.delivery, result) : {
|
|
4958
|
+
...options.delivery,
|
|
4959
|
+
deliveryAttempts: (options.delivery.deliveryAttempts ?? 0) + 1,
|
|
4960
|
+
deliveryStatus: "skipped",
|
|
4961
|
+
updatedAt: Date.now()
|
|
4962
|
+
};
|
|
4963
|
+
};
|
|
4964
|
+
var createVoiceMemoryHandoffDeliveryStore = () => {
|
|
4965
|
+
const deliveries = new Map;
|
|
4966
|
+
return {
|
|
4967
|
+
get: async (id) => deliveries.get(id),
|
|
4968
|
+
list: async () => [...deliveries.values()].sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id)),
|
|
4969
|
+
remove: async (id) => {
|
|
4970
|
+
deliveries.delete(id);
|
|
4971
|
+
},
|
|
4972
|
+
set: async (id, delivery) => {
|
|
4973
|
+
deliveries.set(id, delivery);
|
|
4974
|
+
}
|
|
4975
|
+
};
|
|
4976
|
+
};
|
|
4977
|
+
var createVoiceWebhookHandoffAdapter = (options) => ({
|
|
4978
|
+
actions: options.actions,
|
|
4979
|
+
handoff: async (input) => {
|
|
4980
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
4981
|
+
if (typeof fetchImpl !== "function") {
|
|
4982
|
+
return {
|
|
4983
|
+
deliveredTo: options.url,
|
|
4984
|
+
error: "Handoff delivery failed: fetch is not available in this runtime.",
|
|
4985
|
+
status: "failed"
|
|
4986
|
+
};
|
|
4987
|
+
}
|
|
4988
|
+
const body = JSON.stringify(await options.body?.(input) ?? defaultWebhookBody(input));
|
|
4989
|
+
const headers = {
|
|
4990
|
+
"content-type": "application/json",
|
|
4991
|
+
...options.headers
|
|
4992
|
+
};
|
|
4993
|
+
if (options.signingSecret) {
|
|
4994
|
+
const timestamp = String(Date.now());
|
|
4995
|
+
headers["x-absolutejs-timestamp"] = timestamp;
|
|
4996
|
+
headers["x-absolutejs-signature"] = await signHandoffBody({
|
|
4997
|
+
body,
|
|
4998
|
+
secret: options.signingSecret,
|
|
4999
|
+
timestamp
|
|
5000
|
+
});
|
|
5001
|
+
}
|
|
5002
|
+
const controller = options.timeoutMs && options.timeoutMs > 0 ? new AbortController : undefined;
|
|
5003
|
+
const timeout = controller && options.timeoutMs ? setTimeout(() => controller.abort(), options.timeoutMs) : undefined;
|
|
5004
|
+
try {
|
|
5005
|
+
const response = await fetchImpl(options.url, {
|
|
5006
|
+
body,
|
|
5007
|
+
headers,
|
|
5008
|
+
method: options.method ?? "POST",
|
|
5009
|
+
signal: controller?.signal
|
|
5010
|
+
});
|
|
5011
|
+
if (!response.ok) {
|
|
5012
|
+
return {
|
|
5013
|
+
deliveredTo: options.url,
|
|
5014
|
+
error: `Handoff delivery failed with response ${response.status}.`,
|
|
5015
|
+
status: "failed"
|
|
5016
|
+
};
|
|
5017
|
+
}
|
|
5018
|
+
return {
|
|
5019
|
+
deliveredAt: Date.now(),
|
|
5020
|
+
deliveredTo: options.url,
|
|
5021
|
+
status: "delivered"
|
|
5022
|
+
};
|
|
5023
|
+
} finally {
|
|
5024
|
+
if (timeout) {
|
|
5025
|
+
clearTimeout(timeout);
|
|
5026
|
+
}
|
|
5027
|
+
}
|
|
5028
|
+
},
|
|
5029
|
+
id: options.id,
|
|
5030
|
+
kind: options.kind ?? "webhook"
|
|
5031
|
+
});
|
|
5032
|
+
var escapeXml = (value) => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">");
|
|
5033
|
+
var defaultTwilioTransferTwiML = (input) => {
|
|
5034
|
+
if (!input.target) {
|
|
5035
|
+
return "<Response><Hangup /></Response>";
|
|
5036
|
+
}
|
|
5037
|
+
return `<Response><Dial>${escapeXml(input.target)}</Dial></Response>`;
|
|
5038
|
+
};
|
|
5039
|
+
var resolveTwilioCallSid = async (resolver, input) => {
|
|
5040
|
+
if (typeof resolver === "function") {
|
|
5041
|
+
return resolver(input);
|
|
5042
|
+
}
|
|
5043
|
+
if (typeof resolver === "string" && resolver.length > 0) {
|
|
5044
|
+
return resolver;
|
|
5045
|
+
}
|
|
5046
|
+
const metadataSid = typeof input.metadata?.callSid === "string" ? input.metadata.callSid : undefined;
|
|
5047
|
+
const sessionMetadata = input.session.metadata && typeof input.session.metadata === "object" ? input.session.metadata : undefined;
|
|
5048
|
+
const sessionSid = typeof sessionMetadata?.callSid === "string" ? sessionMetadata.callSid : undefined;
|
|
5049
|
+
return metadataSid ?? sessionSid;
|
|
5050
|
+
};
|
|
5051
|
+
var createVoiceTwilioRedirectHandoffAdapter = (options) => ({
|
|
5052
|
+
actions: options.actions ?? ["transfer"],
|
|
5053
|
+
handoff: async (input) => {
|
|
5054
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
5055
|
+
const callSid = await resolveTwilioCallSid(options.callSid, input);
|
|
5056
|
+
if (!callSid) {
|
|
5057
|
+
return {
|
|
5058
|
+
error: "Twilio handoff requires a callSid.",
|
|
5059
|
+
status: "failed"
|
|
5060
|
+
};
|
|
5061
|
+
}
|
|
5062
|
+
if (typeof fetchImpl !== "function") {
|
|
5063
|
+
return {
|
|
5064
|
+
error: "Twilio handoff failed: fetch is not available in this runtime.",
|
|
5065
|
+
status: "failed"
|
|
5066
|
+
};
|
|
5067
|
+
}
|
|
5068
|
+
const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(options.accountSid)}/Calls/${encodeURIComponent(callSid)}.json`;
|
|
5069
|
+
const body = new URLSearchParams({
|
|
5070
|
+
Twiml: await (options.buildTwiML?.(input) ?? defaultTwilioTransferTwiML(input))
|
|
5071
|
+
});
|
|
5072
|
+
const auth = btoa(`${options.accountSid}:${options.authToken}`);
|
|
5073
|
+
const controller = options.timeoutMs && options.timeoutMs > 0 ? new AbortController : undefined;
|
|
5074
|
+
const timeout = controller && options.timeoutMs ? setTimeout(() => controller.abort(), options.timeoutMs) : undefined;
|
|
5075
|
+
try {
|
|
5076
|
+
const response = await fetchImpl(url, {
|
|
5077
|
+
body,
|
|
5078
|
+
headers: {
|
|
5079
|
+
authorization: `Basic ${auth}`,
|
|
5080
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
5081
|
+
},
|
|
5082
|
+
method: "POST",
|
|
5083
|
+
signal: controller?.signal
|
|
5084
|
+
});
|
|
5085
|
+
if (!response.ok) {
|
|
5086
|
+
return {
|
|
5087
|
+
deliveredTo: url,
|
|
5088
|
+
error: `Twilio handoff failed with response ${response.status}.`,
|
|
5089
|
+
status: "failed"
|
|
5090
|
+
};
|
|
5091
|
+
}
|
|
5092
|
+
return {
|
|
5093
|
+
deliveredAt: Date.now(),
|
|
5094
|
+
deliveredTo: url,
|
|
5095
|
+
metadata: {
|
|
5096
|
+
callSid
|
|
5097
|
+
},
|
|
5098
|
+
status: "delivered"
|
|
5099
|
+
};
|
|
5100
|
+
} finally {
|
|
5101
|
+
if (timeout) {
|
|
5102
|
+
clearTimeout(timeout);
|
|
5103
|
+
}
|
|
5104
|
+
}
|
|
5105
|
+
},
|
|
5106
|
+
id: options.id ?? "twilio-redirect",
|
|
5107
|
+
kind: "twilio-redirect"
|
|
5108
|
+
});
|
|
3535
5109
|
|
|
3536
5110
|
// src/logger.ts
|
|
3537
5111
|
var noop2 = () => {};
|
|
@@ -3567,6 +5141,12 @@ var DEFAULT_FORMAT = {
|
|
|
3567
5141
|
encoding: "pcm_s16le",
|
|
3568
5142
|
sampleRateHz: 16000
|
|
3569
5143
|
};
|
|
5144
|
+
var DEFAULT_REALTIME_FORMAT = {
|
|
5145
|
+
channels: 1,
|
|
5146
|
+
container: "raw",
|
|
5147
|
+
encoding: "pcm_s16le",
|
|
5148
|
+
sampleRateHz: 24000
|
|
5149
|
+
};
|
|
3570
5150
|
var toError = (value) => value instanceof Error ? value : new Error(String(value));
|
|
3571
5151
|
var createEmptyCurrentTurn = () => ({
|
|
3572
5152
|
finalText: "",
|
|
@@ -3579,7 +5159,7 @@ var createEmptyCurrentTurn = () => ({
|
|
|
3579
5159
|
transcripts: []
|
|
3580
5160
|
});
|
|
3581
5161
|
var cloneTranscript = (transcript) => ({ ...transcript });
|
|
3582
|
-
var encodeBase64 = (chunk) =>
|
|
5162
|
+
var encodeBase64 = (chunk) => Buffer2.from(chunk).toString("base64");
|
|
3583
5163
|
var countWords2 = (text) => text.trim().split(/\s+/).filter(Boolean).length;
|
|
3584
5164
|
var normalizeText2 = (text) => text.trim().replace(/\s+/g, " ");
|
|
3585
5165
|
var getAudioChunkDurationMs = (chunk) => chunk.byteLength / (DEFAULT_FORMAT.sampleRateHz * DEFAULT_FORMAT.channels * 2) * 1000;
|
|
@@ -3725,6 +5305,7 @@ var pushCallLifecycleEvent = (session, input) => {
|
|
|
3725
5305
|
}
|
|
3726
5306
|
return lifecycle;
|
|
3727
5307
|
};
|
|
5308
|
+
var getLatestCallLifecycleEvent = (session) => session.call?.events.at(-1);
|
|
3728
5309
|
var createVoiceSession = (options) => {
|
|
3729
5310
|
const logger = resolveLogger(options.logger);
|
|
3730
5311
|
const reconnect = {
|
|
@@ -3749,7 +5330,7 @@ var createVoiceSession = (options) => {
|
|
|
3749
5330
|
} : undefined;
|
|
3750
5331
|
const appendTrace = async (input) => {
|
|
3751
5332
|
await options.trace?.append({
|
|
3752
|
-
at: Date.now(),
|
|
5333
|
+
at: input.at ?? Date.now(),
|
|
3753
5334
|
metadata: input.metadata,
|
|
3754
5335
|
payload: input.payload,
|
|
3755
5336
|
scenarioId: input.session?.scenarioId ?? options.scenarioId,
|
|
@@ -3758,6 +5339,13 @@ var createVoiceSession = (options) => {
|
|
|
3758
5339
|
type: input.type
|
|
3759
5340
|
});
|
|
3760
5341
|
};
|
|
5342
|
+
const appendTurnLatencyStage = async (input) => appendTrace({
|
|
5343
|
+
at: input.at,
|
|
5344
|
+
payload: { stage: input.stage },
|
|
5345
|
+
session: input.session,
|
|
5346
|
+
turnId: input.turnId,
|
|
5347
|
+
type: "turn_latency.stage"
|
|
5348
|
+
});
|
|
3761
5349
|
const phraseHints = options.phraseHints ?? [];
|
|
3762
5350
|
const lexicon = options.lexicon ?? [];
|
|
3763
5351
|
let socket = options.socket;
|
|
@@ -3825,6 +5413,76 @@ var createVoiceSession = (options) => {
|
|
|
3825
5413
|
});
|
|
3826
5414
|
}
|
|
3827
5415
|
};
|
|
5416
|
+
const sendCallLifecycle = async (session) => {
|
|
5417
|
+
const event = getLatestCallLifecycleEvent(session);
|
|
5418
|
+
if (!event) {
|
|
5419
|
+
return;
|
|
5420
|
+
}
|
|
5421
|
+
await send({
|
|
5422
|
+
event,
|
|
5423
|
+
sessionId: options.id,
|
|
5424
|
+
type: "call_lifecycle"
|
|
5425
|
+
});
|
|
5426
|
+
};
|
|
5427
|
+
const sendReplay = async (session) => {
|
|
5428
|
+
await send({
|
|
5429
|
+
assistantTexts: session.turns.flatMap((turn) => turn.assistantText ? [turn.assistantText] : []),
|
|
5430
|
+
call: session.call,
|
|
5431
|
+
partial: session.currentTurn.partialText,
|
|
5432
|
+
scenarioId: session.scenarioId,
|
|
5433
|
+
sessionId: options.id,
|
|
5434
|
+
status: session.status,
|
|
5435
|
+
turns: session.turns,
|
|
5436
|
+
type: "replay"
|
|
5437
|
+
});
|
|
5438
|
+
};
|
|
5439
|
+
const runHandoff = async (input) => {
|
|
5440
|
+
const queuedDelivery = options.handoff?.deliveryQueue ? createVoiceHandoffDeliveryRecord({
|
|
5441
|
+
action: input.action,
|
|
5442
|
+
context: options.context,
|
|
5443
|
+
metadata: input.metadata,
|
|
5444
|
+
reason: input.reason,
|
|
5445
|
+
result: input.result,
|
|
5446
|
+
session: input.session,
|
|
5447
|
+
target: input.target
|
|
5448
|
+
}) : undefined;
|
|
5449
|
+
if (queuedDelivery) {
|
|
5450
|
+
await options.handoff?.deliveryQueue?.set(queuedDelivery.id, queuedDelivery);
|
|
5451
|
+
}
|
|
5452
|
+
if (options.handoff?.enqueueOnly) {
|
|
5453
|
+
return;
|
|
5454
|
+
}
|
|
5455
|
+
const result = await deliverVoiceHandoff({
|
|
5456
|
+
config: options.handoff,
|
|
5457
|
+
handoff: {
|
|
5458
|
+
action: input.action,
|
|
5459
|
+
api,
|
|
5460
|
+
context: options.context,
|
|
5461
|
+
metadata: input.metadata,
|
|
5462
|
+
reason: input.reason,
|
|
5463
|
+
result: input.result,
|
|
5464
|
+
session: input.session,
|
|
5465
|
+
target: input.target
|
|
5466
|
+
}
|
|
5467
|
+
});
|
|
5468
|
+
if (!result) {
|
|
5469
|
+
return;
|
|
5470
|
+
}
|
|
5471
|
+
if (queuedDelivery) {
|
|
5472
|
+
const updatedDelivery = applyVoiceHandoffDeliveryResult(queuedDelivery, result);
|
|
5473
|
+
await options.handoff?.deliveryQueue?.set(updatedDelivery.id, updatedDelivery);
|
|
5474
|
+
}
|
|
5475
|
+
await appendTrace({
|
|
5476
|
+
metadata: input.metadata,
|
|
5477
|
+
payload: {
|
|
5478
|
+
...result,
|
|
5479
|
+
reason: input.reason,
|
|
5480
|
+
target: input.target
|
|
5481
|
+
},
|
|
5482
|
+
session: input.session,
|
|
5483
|
+
type: "call.handoff"
|
|
5484
|
+
});
|
|
5485
|
+
};
|
|
3828
5486
|
const readSession = async () => options.store.getOrCreate(options.id);
|
|
3829
5487
|
const writeSession = async (mutate) => {
|
|
3830
5488
|
const session = await options.store.getOrCreate(options.id);
|
|
@@ -3881,6 +5539,23 @@ var createVoiceSession = (options) => {
|
|
|
3881
5539
|
});
|
|
3882
5540
|
}
|
|
3883
5541
|
};
|
|
5542
|
+
const sendAssistantAudio = async (chunk, input) => {
|
|
5543
|
+
const normalizedChunk = chunk instanceof Uint8Array ? new Uint8Array(chunk) : chunk instanceof ArrayBuffer ? new Uint8Array(chunk.slice(0)) : new Uint8Array(chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength));
|
|
5544
|
+
await send({
|
|
5545
|
+
chunkBase64: encodeBase64(normalizedChunk),
|
|
5546
|
+
format: input.format,
|
|
5547
|
+
receivedAt: input.receivedAt,
|
|
5548
|
+
turnId: activeTTSTurnId,
|
|
5549
|
+
type: "audio"
|
|
5550
|
+
});
|
|
5551
|
+
if (activeTTSTurnId) {
|
|
5552
|
+
await appendTurnLatencyStage({
|
|
5553
|
+
at: input.receivedAt,
|
|
5554
|
+
stage: "assistant_audio_received",
|
|
5555
|
+
turnId: activeTTSTurnId
|
|
5556
|
+
});
|
|
5557
|
+
}
|
|
5558
|
+
};
|
|
3884
5559
|
const scheduleTurnCommit = (delayMs, reason, reset = true) => {
|
|
3885
5560
|
if (!reset && silenceTimer) {
|
|
3886
5561
|
return;
|
|
@@ -4015,6 +5690,7 @@ var createVoiceSession = (options) => {
|
|
|
4015
5690
|
await appendTrace({
|
|
4016
5691
|
payload: {
|
|
4017
5692
|
disposition,
|
|
5693
|
+
metadata: input.metadata,
|
|
4018
5694
|
reason: input.reason,
|
|
4019
5695
|
target: input.target,
|
|
4020
5696
|
type: "end"
|
|
@@ -4022,6 +5698,7 @@ var createVoiceSession = (options) => {
|
|
|
4022
5698
|
session,
|
|
4023
5699
|
type: "call.lifecycle"
|
|
4024
5700
|
});
|
|
5701
|
+
await sendCallLifecycle(session);
|
|
4025
5702
|
await send({
|
|
4026
5703
|
sessionId: options.id,
|
|
4027
5704
|
type: "complete"
|
|
@@ -4101,6 +5778,15 @@ var createVoiceSession = (options) => {
|
|
|
4101
5778
|
session,
|
|
4102
5779
|
type: "call.lifecycle"
|
|
4103
5780
|
});
|
|
5781
|
+
await sendCallLifecycle(session);
|
|
5782
|
+
await runHandoff({
|
|
5783
|
+
action: "transfer",
|
|
5784
|
+
metadata: input.metadata,
|
|
5785
|
+
reason: input.reason,
|
|
5786
|
+
result: input.result,
|
|
5787
|
+
session,
|
|
5788
|
+
target: input.target
|
|
5789
|
+
});
|
|
4104
5790
|
await completeInternal(input.result, {
|
|
4105
5791
|
disposition: "transferred",
|
|
4106
5792
|
invokeOnComplete: false,
|
|
@@ -4126,6 +5812,14 @@ var createVoiceSession = (options) => {
|
|
|
4126
5812
|
session,
|
|
4127
5813
|
type: "call.lifecycle"
|
|
4128
5814
|
});
|
|
5815
|
+
await sendCallLifecycle(session);
|
|
5816
|
+
await runHandoff({
|
|
5817
|
+
action: "escalate",
|
|
5818
|
+
metadata: input.metadata,
|
|
5819
|
+
reason: input.reason,
|
|
5820
|
+
result: input.result,
|
|
5821
|
+
session
|
|
5822
|
+
});
|
|
4129
5823
|
await completeInternal(input.result, {
|
|
4130
5824
|
disposition: "escalated",
|
|
4131
5825
|
invokeOnComplete: false,
|
|
@@ -4148,6 +5842,13 @@ var createVoiceSession = (options) => {
|
|
|
4148
5842
|
session,
|
|
4149
5843
|
type: "call.lifecycle"
|
|
4150
5844
|
});
|
|
5845
|
+
await sendCallLifecycle(session);
|
|
5846
|
+
await runHandoff({
|
|
5847
|
+
action: "no-answer",
|
|
5848
|
+
metadata: input?.metadata,
|
|
5849
|
+
result: input?.result,
|
|
5850
|
+
session
|
|
5851
|
+
});
|
|
4151
5852
|
await completeInternal(input?.result, {
|
|
4152
5853
|
disposition: "no-answer",
|
|
4153
5854
|
invokeOnComplete: false,
|
|
@@ -4169,6 +5870,13 @@ var createVoiceSession = (options) => {
|
|
|
4169
5870
|
session,
|
|
4170
5871
|
type: "call.lifecycle"
|
|
4171
5872
|
});
|
|
5873
|
+
await sendCallLifecycle(session);
|
|
5874
|
+
await runHandoff({
|
|
5875
|
+
action: "voicemail",
|
|
5876
|
+
metadata: input?.metadata,
|
|
5877
|
+
result: input?.result,
|
|
5878
|
+
session
|
|
5879
|
+
});
|
|
4172
5880
|
await completeInternal(input?.result, {
|
|
4173
5881
|
disposition: "voicemail",
|
|
4174
5882
|
invokeOnComplete: false,
|
|
@@ -4549,8 +6257,12 @@ var createVoiceSession = (options) => {
|
|
|
4549
6257
|
if (sttSession) {
|
|
4550
6258
|
return sttSession;
|
|
4551
6259
|
}
|
|
4552
|
-
const
|
|
4553
|
-
|
|
6260
|
+
const inputAdapter = options.realtime ?? options.stt;
|
|
6261
|
+
if (!inputAdapter) {
|
|
6262
|
+
throw new Error("Voice session requires either an stt or realtime adapter.");
|
|
6263
|
+
}
|
|
6264
|
+
const openedSession = await inputAdapter.open({
|
|
6265
|
+
format: options.realtime ? options.realtimeInputFormat ?? DEFAULT_REALTIME_FORMAT : DEFAULT_FORMAT,
|
|
4554
6266
|
languageStrategy: options.languageStrategy,
|
|
4555
6267
|
lexicon,
|
|
4556
6268
|
phraseHints,
|
|
@@ -4585,6 +6297,16 @@ var createVoiceSession = (options) => {
|
|
|
4585
6297
|
openedSession.on("close", (event) => {
|
|
4586
6298
|
runAdapterEvent("adapter.close", () => handleClose(event));
|
|
4587
6299
|
});
|
|
6300
|
+
if (options.realtime) {
|
|
6301
|
+
openedSession.on("audio", ({ chunk, format, receivedAt }) => {
|
|
6302
|
+
runAdapterEvent("adapter.audio", async () => {
|
|
6303
|
+
await sendAssistantAudio(chunk, {
|
|
6304
|
+
format,
|
|
6305
|
+
receivedAt
|
|
6306
|
+
});
|
|
6307
|
+
});
|
|
6308
|
+
});
|
|
6309
|
+
}
|
|
4588
6310
|
return openedSession;
|
|
4589
6311
|
};
|
|
4590
6312
|
const ensureTTSSession = async () => {
|
|
@@ -4609,13 +6331,9 @@ var createVoiceSession = (options) => {
|
|
|
4609
6331
|
if (ttsSession !== openedSession) {
|
|
4610
6332
|
return;
|
|
4611
6333
|
}
|
|
4612
|
-
|
|
4613
|
-
await send({
|
|
4614
|
-
chunkBase64: encodeBase64(normalizedChunk),
|
|
6334
|
+
await sendAssistantAudio(chunk, {
|
|
4615
6335
|
format,
|
|
4616
|
-
receivedAt
|
|
4617
|
-
turnId: activeTTSTurnId,
|
|
4618
|
-
type: "audio"
|
|
6336
|
+
receivedAt
|
|
4619
6337
|
});
|
|
4620
6338
|
});
|
|
4621
6339
|
});
|
|
@@ -4675,6 +6393,7 @@ var createVoiceSession = (options) => {
|
|
|
4675
6393
|
voicemail: committedOutput?.voicemail
|
|
4676
6394
|
};
|
|
4677
6395
|
if (output?.assistantText) {
|
|
6396
|
+
const assistantTextStartedAt = Date.now();
|
|
4678
6397
|
await writeSession((currentSession) => {
|
|
4679
6398
|
setTurnResult(currentSession, turn.id, {
|
|
4680
6399
|
assistantText: output.assistantText
|
|
@@ -4685,10 +6404,17 @@ var createVoiceSession = (options) => {
|
|
|
4685
6404
|
turnId: turn.id,
|
|
4686
6405
|
type: "assistant"
|
|
4687
6406
|
});
|
|
6407
|
+
await appendTurnLatencyStage({
|
|
6408
|
+
at: assistantTextStartedAt,
|
|
6409
|
+
session,
|
|
6410
|
+
stage: "assistant_text_started",
|
|
6411
|
+
turnId: turn.id
|
|
6412
|
+
});
|
|
4688
6413
|
await appendTrace({
|
|
4689
6414
|
payload: {
|
|
4690
6415
|
text: output.assistantText,
|
|
4691
|
-
ttsConfigured: Boolean(options.tts)
|
|
6416
|
+
ttsConfigured: Boolean(options.tts),
|
|
6417
|
+
realtimeConfigured: Boolean(options.realtime)
|
|
4692
6418
|
},
|
|
4693
6419
|
session,
|
|
4694
6420
|
turnId: turn.id,
|
|
@@ -4699,7 +6425,18 @@ var createVoiceSession = (options) => {
|
|
|
4699
6425
|
if (activeTTSSession) {
|
|
4700
6426
|
const ttsStartedAt = Date.now();
|
|
4701
6427
|
activeTTSTurnId = turn.id;
|
|
6428
|
+
await appendTurnLatencyStage({
|
|
6429
|
+
at: ttsStartedAt,
|
|
6430
|
+
session,
|
|
6431
|
+
stage: "tts_send_started",
|
|
6432
|
+
turnId: turn.id
|
|
6433
|
+
});
|
|
4702
6434
|
await activeTTSSession.send(output.assistantText);
|
|
6435
|
+
await appendTurnLatencyStage({
|
|
6436
|
+
session,
|
|
6437
|
+
stage: "tts_send_completed",
|
|
6438
|
+
turnId: turn.id
|
|
6439
|
+
});
|
|
4703
6440
|
await appendTrace({
|
|
4704
6441
|
payload: {
|
|
4705
6442
|
elapsedMs: Date.now() - ttsStartedAt,
|
|
@@ -4709,9 +6446,35 @@ var createVoiceSession = (options) => {
|
|
|
4709
6446
|
turnId: turn.id,
|
|
4710
6447
|
type: "turn.assistant"
|
|
4711
6448
|
});
|
|
6449
|
+
} else if (options.realtime) {
|
|
6450
|
+
const activeRealtimeSession = await ensureAdapter();
|
|
6451
|
+
const realtimeStartedAt = Date.now();
|
|
6452
|
+
activeTTSTurnId = turn.id;
|
|
6453
|
+
await appendTurnLatencyStage({
|
|
6454
|
+
at: realtimeStartedAt,
|
|
6455
|
+
session,
|
|
6456
|
+
stage: "tts_send_started",
|
|
6457
|
+
turnId: turn.id
|
|
6458
|
+
});
|
|
6459
|
+
await activeRealtimeSession.send(output.assistantText);
|
|
6460
|
+
await appendTurnLatencyStage({
|
|
6461
|
+
session,
|
|
6462
|
+
stage: "tts_send_completed",
|
|
6463
|
+
turnId: turn.id
|
|
6464
|
+
});
|
|
6465
|
+
await appendTrace({
|
|
6466
|
+
payload: {
|
|
6467
|
+
elapsedMs: Date.now() - realtimeStartedAt,
|
|
6468
|
+
mode: "realtime",
|
|
6469
|
+
status: "sent"
|
|
6470
|
+
},
|
|
6471
|
+
session,
|
|
6472
|
+
turnId: turn.id,
|
|
6473
|
+
type: "turn.assistant"
|
|
6474
|
+
});
|
|
4712
6475
|
}
|
|
4713
6476
|
} catch (error) {
|
|
4714
|
-
logger.warn("voice
|
|
6477
|
+
logger.warn("voice assistant audio send failed", {
|
|
4715
6478
|
error: toError(error).message,
|
|
4716
6479
|
sessionId: options.id,
|
|
4717
6480
|
turnId: turn.id
|
|
@@ -4719,7 +6482,7 @@ var createVoiceSession = (options) => {
|
|
|
4719
6482
|
await appendTrace({
|
|
4720
6483
|
payload: {
|
|
4721
6484
|
error: toError(error).message,
|
|
4722
|
-
status: "tts-send-failed"
|
|
6485
|
+
status: options.realtime ? "realtime-send-failed" : "tts-send-failed"
|
|
4723
6486
|
},
|
|
4724
6487
|
session,
|
|
4725
6488
|
turnId: turn.id,
|
|
@@ -4896,11 +6659,35 @@ var createVoiceSession = (options) => {
|
|
|
4896
6659
|
turnId: turn.id,
|
|
4897
6660
|
type: "turn.cost"
|
|
4898
6661
|
});
|
|
6662
|
+
const firstTranscriptAt = turn.transcripts.map((transcript) => transcript.endedAtMs ?? transcript.startedAtMs).filter((value) => typeof value === "number").sort((left, right) => left - right)[0];
|
|
6663
|
+
const finalTranscriptAt = turn.transcripts.filter((transcript) => transcript.isFinal).map((transcript) => transcript.endedAtMs ?? transcript.startedAtMs).filter((value) => typeof value === "number").sort((left, right) => left - right)[0];
|
|
6664
|
+
if (firstTranscriptAt !== undefined) {
|
|
6665
|
+
await appendTurnLatencyStage({
|
|
6666
|
+
at: firstTranscriptAt,
|
|
6667
|
+
session: updatedSession,
|
|
6668
|
+
stage: "speech_detected",
|
|
6669
|
+
turnId: turn.id
|
|
6670
|
+
});
|
|
6671
|
+
}
|
|
6672
|
+
if (finalTranscriptAt !== undefined) {
|
|
6673
|
+
await appendTurnLatencyStage({
|
|
6674
|
+
at: finalTranscriptAt,
|
|
6675
|
+
session: updatedSession,
|
|
6676
|
+
stage: "final_transcript",
|
|
6677
|
+
turnId: turn.id
|
|
6678
|
+
});
|
|
6679
|
+
}
|
|
6680
|
+
await appendTurnLatencyStage({
|
|
6681
|
+
at: turn.committedAt,
|
|
6682
|
+
session: updatedSession,
|
|
6683
|
+
stage: "turn_committed",
|
|
6684
|
+
turnId: turn.id
|
|
6685
|
+
});
|
|
4899
6686
|
await send({
|
|
4900
6687
|
turn,
|
|
4901
6688
|
type: "turn"
|
|
4902
6689
|
});
|
|
4903
|
-
if (options.sttLifecycle === "turn-scoped") {
|
|
6690
|
+
if (options.stt && options.sttLifecycle === "turn-scoped") {
|
|
4904
6691
|
await closeAdapter("turn-commit");
|
|
4905
6692
|
}
|
|
4906
6693
|
await completeTurn(updatedSession, turn);
|
|
@@ -4955,6 +6742,7 @@ var createVoiceSession = (options) => {
|
|
|
4955
6742
|
session,
|
|
4956
6743
|
type: "call.lifecycle"
|
|
4957
6744
|
});
|
|
6745
|
+
await sendCallLifecycle(session);
|
|
4958
6746
|
}
|
|
4959
6747
|
await send({
|
|
4960
6748
|
sessionId: options.id,
|
|
@@ -4962,6 +6750,7 @@ var createVoiceSession = (options) => {
|
|
|
4962
6750
|
scenarioId: session.scenarioId,
|
|
4963
6751
|
type: "session"
|
|
4964
6752
|
});
|
|
6753
|
+
await sendReplay(session);
|
|
4965
6754
|
if (shouldFireOnSession) {
|
|
4966
6755
|
await options.route.onCallStart?.({
|
|
4967
6756
|
api,
|
|
@@ -5545,7 +7334,7 @@ var createVoiceCallReviewFromLiveTelephonyReport = (report, options = {}) => {
|
|
|
5545
7334
|
}
|
|
5546
7335
|
};
|
|
5547
7336
|
};
|
|
5548
|
-
var
|
|
7337
|
+
var toErrorMessage2 = (error) => {
|
|
5549
7338
|
if (typeof error === "string" && error.trim().length > 0) {
|
|
5550
7339
|
return error;
|
|
5551
7340
|
}
|
|
@@ -5632,7 +7421,7 @@ var createVoiceCallReviewRecorder = (options = {}) => {
|
|
|
5632
7421
|
};
|
|
5633
7422
|
},
|
|
5634
7423
|
recordError: (error) => {
|
|
5635
|
-
const message =
|
|
7424
|
+
const message = toErrorMessage2(error);
|
|
5636
7425
|
errors.push(message);
|
|
5637
7426
|
push("turn", "error", {
|
|
5638
7427
|
reason: message
|
|
@@ -6338,10 +8127,870 @@ var runVoiceSessionBenchmarkSeries = async (input) => {
|
|
|
6338
8127
|
});
|
|
6339
8128
|
};
|
|
6340
8129
|
// src/telephony/twilio.ts
|
|
6341
|
-
import { Buffer as
|
|
8130
|
+
import { Buffer as Buffer3 } from "buffer";
|
|
8131
|
+
import { Elysia as Elysia2 } from "elysia";
|
|
8132
|
+
|
|
8133
|
+
// src/telephonyOutcome.ts
|
|
8134
|
+
import { Elysia } from "elysia";
|
|
8135
|
+
var DEFAULT_COMPLETED_STATUSES = [
|
|
8136
|
+
"answered",
|
|
8137
|
+
"completed",
|
|
8138
|
+
"complete",
|
|
8139
|
+
"connected",
|
|
8140
|
+
"in-progress",
|
|
8141
|
+
"live"
|
|
8142
|
+
];
|
|
8143
|
+
var DEFAULT_NO_ANSWER_STATUSES = [
|
|
8144
|
+
"busy",
|
|
8145
|
+
"canceled",
|
|
8146
|
+
"cancelled",
|
|
8147
|
+
"failed",
|
|
8148
|
+
"no-answer",
|
|
8149
|
+
"no_answer",
|
|
8150
|
+
"not-answered",
|
|
8151
|
+
"ring-no-answer",
|
|
8152
|
+
"timeout",
|
|
8153
|
+
"unanswered"
|
|
8154
|
+
];
|
|
8155
|
+
var DEFAULT_VOICEMAIL_STATUSES = [
|
|
8156
|
+
"answering-machine",
|
|
8157
|
+
"machine",
|
|
8158
|
+
"voicemail",
|
|
8159
|
+
"voice-mail"
|
|
8160
|
+
];
|
|
8161
|
+
var DEFAULT_TRANSFER_STATUSES = ["bridged", "forwarded", "transferred"];
|
|
8162
|
+
var DEFAULT_ESCALATION_STATUSES = ["escalated", "human-required", "operator"];
|
|
8163
|
+
var DEFAULT_FAILED_STATUSES = ["busy", "failed", "no-answer"];
|
|
8164
|
+
var DEFAULT_MACHINE_VOICEMAIL_VALUES = [
|
|
8165
|
+
"answering-machine",
|
|
8166
|
+
"fax",
|
|
8167
|
+
"machine",
|
|
8168
|
+
"machine-end-beep",
|
|
8169
|
+
"machine-end-other",
|
|
8170
|
+
"machine-start",
|
|
8171
|
+
"voicemail"
|
|
8172
|
+
];
|
|
8173
|
+
var DEFAULT_NO_ANSWER_SIP_CODES = [408, 480, 486, 487, 603];
|
|
8174
|
+
var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
8175
|
+
|
|
8176
|
+
class VoiceTelephonyWebhookVerificationError extends Error {
|
|
8177
|
+
result;
|
|
8178
|
+
constructor(result) {
|
|
8179
|
+
super(result.ok ? "telephony webhook verified" : result.reason);
|
|
8180
|
+
this.name = "VoiceTelephonyWebhookVerificationError";
|
|
8181
|
+
this.result = result;
|
|
8182
|
+
}
|
|
8183
|
+
}
|
|
8184
|
+
var createMemoryVoiceTelephonyWebhookIdempotencyStore = () => {
|
|
8185
|
+
const decisions = new Map;
|
|
8186
|
+
return {
|
|
8187
|
+
get: (key) => decisions.get(key),
|
|
8188
|
+
set: (key, decision) => {
|
|
8189
|
+
decisions.set(key, decision);
|
|
8190
|
+
}
|
|
8191
|
+
};
|
|
8192
|
+
};
|
|
8193
|
+
var normalizeToken = (value) => typeof value === "string" ? value.trim().toLowerCase().replace(/\s+/g, "-").replace(/_+/g, "-") : undefined;
|
|
8194
|
+
var firstString = (source, keys) => {
|
|
8195
|
+
for (const key of keys) {
|
|
8196
|
+
const value = source[key];
|
|
8197
|
+
if (typeof value === "string" && value.trim()) {
|
|
8198
|
+
return value.trim();
|
|
8199
|
+
}
|
|
8200
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
8201
|
+
return String(value);
|
|
8202
|
+
}
|
|
8203
|
+
}
|
|
8204
|
+
};
|
|
8205
|
+
var firstNumber = (source, keys) => {
|
|
8206
|
+
for (const key of keys) {
|
|
8207
|
+
const value = source[key];
|
|
8208
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
8209
|
+
return value;
|
|
8210
|
+
}
|
|
8211
|
+
if (typeof value === "string" && value.trim()) {
|
|
8212
|
+
const parsed = Number(value);
|
|
8213
|
+
if (Number.isFinite(parsed)) {
|
|
8214
|
+
return parsed;
|
|
8215
|
+
}
|
|
8216
|
+
}
|
|
8217
|
+
}
|
|
8218
|
+
};
|
|
8219
|
+
var parseMaybeJSON = (value) => {
|
|
8220
|
+
try {
|
|
8221
|
+
return JSON.parse(value);
|
|
8222
|
+
} catch {
|
|
8223
|
+
return;
|
|
8224
|
+
}
|
|
8225
|
+
};
|
|
8226
|
+
var flattenPayload = (value) => {
|
|
8227
|
+
if (!isRecord(value)) {
|
|
8228
|
+
return {};
|
|
8229
|
+
}
|
|
8230
|
+
const data = isRecord(value.data) ? value.data : undefined;
|
|
8231
|
+
const payload = isRecord(value.payload) ? value.payload : undefined;
|
|
8232
|
+
const event = isRecord(value.event) ? value.event : undefined;
|
|
8233
|
+
return {
|
|
8234
|
+
...value,
|
|
8235
|
+
...payload,
|
|
8236
|
+
...event,
|
|
8237
|
+
...data,
|
|
8238
|
+
...isRecord(data?.payload) ? data.payload : undefined
|
|
8239
|
+
};
|
|
8240
|
+
};
|
|
8241
|
+
var toBase64 = (bytes) => Buffer.from(new Uint8Array(bytes)).toString("base64");
|
|
8242
|
+
var timingSafeEqual = (left, right) => {
|
|
8243
|
+
const encoder = new TextEncoder;
|
|
8244
|
+
const leftBytes = encoder.encode(left);
|
|
8245
|
+
const rightBytes = encoder.encode(right);
|
|
8246
|
+
if (leftBytes.length !== rightBytes.length) {
|
|
8247
|
+
return false;
|
|
8248
|
+
}
|
|
8249
|
+
let diff = 0;
|
|
8250
|
+
for (let index = 0;index < leftBytes.length; index += 1) {
|
|
8251
|
+
diff |= leftBytes[index] ^ rightBytes[index];
|
|
8252
|
+
}
|
|
8253
|
+
return diff === 0;
|
|
8254
|
+
};
|
|
8255
|
+
var signHmacSHA1Base64 = async (secret, payload) => {
|
|
8256
|
+
const encoder = new TextEncoder;
|
|
8257
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
8258
|
+
hash: "SHA-1",
|
|
8259
|
+
name: "HMAC"
|
|
8260
|
+
}, false, ["sign"]);
|
|
8261
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
|
|
8262
|
+
return toBase64(signature);
|
|
8263
|
+
};
|
|
8264
|
+
var sortedParamsForSignature = (body) => Object.entries(flattenPayload(body)).filter(([, value]) => value !== undefined && value !== null).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}${String(value)}`).join("");
|
|
8265
|
+
var normalizeList = (values, fallback) => new Set((values ?? fallback).map(normalizeToken).filter(Boolean));
|
|
8266
|
+
var metadataValue = (metadata, keys) => {
|
|
8267
|
+
for (const key of keys) {
|
|
8268
|
+
const value = metadata?.[key];
|
|
8269
|
+
if (typeof value === "string" && value.trim()) {
|
|
8270
|
+
return value.trim();
|
|
8271
|
+
}
|
|
8272
|
+
}
|
|
8273
|
+
};
|
|
8274
|
+
var resolveTransferTarget = (event, policy) => {
|
|
8275
|
+
if (typeof event.target === "string" && event.target.trim()) {
|
|
8276
|
+
return event.target.trim();
|
|
8277
|
+
}
|
|
8278
|
+
const metadataTarget = metadataValue(event.metadata, [
|
|
8279
|
+
"transferTarget",
|
|
8280
|
+
"target",
|
|
8281
|
+
"queue",
|
|
8282
|
+
"department"
|
|
8283
|
+
]);
|
|
8284
|
+
if (metadataTarget) {
|
|
8285
|
+
return metadataTarget;
|
|
8286
|
+
}
|
|
8287
|
+
if (typeof policy.transferTarget === "function") {
|
|
8288
|
+
const target = policy.transferTarget(event);
|
|
8289
|
+
return typeof target === "string" && target.trim() ? target.trim() : undefined;
|
|
8290
|
+
}
|
|
8291
|
+
return typeof policy.transferTarget === "string" && policy.transferTarget.trim() ? policy.transferTarget.trim() : undefined;
|
|
8292
|
+
};
|
|
8293
|
+
var mergeMetadata = (event, policy) => ({
|
|
8294
|
+
...policy.includeProviderPayload ? {
|
|
8295
|
+
answeredBy: event.answeredBy,
|
|
8296
|
+
durationMs: event.durationMs,
|
|
8297
|
+
provider: event.provider,
|
|
8298
|
+
reason: event.reason,
|
|
8299
|
+
sipCode: event.sipCode,
|
|
8300
|
+
status: event.status
|
|
8301
|
+
} : undefined,
|
|
8302
|
+
...policy.metadata,
|
|
8303
|
+
...event.metadata
|
|
8304
|
+
});
|
|
8305
|
+
var withDecisionDefaults = (decision, input) => {
|
|
8306
|
+
if (typeof decision === "string") {
|
|
8307
|
+
return buildDecision(decision, input);
|
|
8308
|
+
}
|
|
8309
|
+
return {
|
|
8310
|
+
...buildDecision(decision.action, input),
|
|
8311
|
+
...decision,
|
|
8312
|
+
confidence: decision.confidence ?? "high",
|
|
8313
|
+
metadata: {
|
|
8314
|
+
...mergeMetadata(input.event, input.policy),
|
|
8315
|
+
...decision.metadata
|
|
8316
|
+
},
|
|
8317
|
+
source: decision.source ?? input.source,
|
|
8318
|
+
target: decision.target ?? (decision.action === "transfer" ? resolveTransferTarget(input.event, input.policy) : undefined)
|
|
8319
|
+
};
|
|
8320
|
+
};
|
|
8321
|
+
var dispositionForAction = (action) => {
|
|
8322
|
+
switch (action) {
|
|
8323
|
+
case "complete":
|
|
8324
|
+
return "completed";
|
|
8325
|
+
case "escalate":
|
|
8326
|
+
return "escalated";
|
|
8327
|
+
case "no-answer":
|
|
8328
|
+
return "no-answer";
|
|
8329
|
+
case "transfer":
|
|
8330
|
+
return "transferred";
|
|
8331
|
+
case "voicemail":
|
|
8332
|
+
return "voicemail";
|
|
8333
|
+
default:
|
|
8334
|
+
return;
|
|
8335
|
+
}
|
|
8336
|
+
};
|
|
8337
|
+
var buildDecision = (action, input) => ({
|
|
8338
|
+
action,
|
|
8339
|
+
confidence: action === "ignore" ? "low" : "high",
|
|
8340
|
+
disposition: dispositionForAction(action),
|
|
8341
|
+
metadata: mergeMetadata(input.event, input.policy),
|
|
8342
|
+
reason: input.event.reason,
|
|
8343
|
+
source: input.source,
|
|
8344
|
+
target: action === "transfer" ? resolveTransferTarget(input.event, input.policy) : undefined
|
|
8345
|
+
});
|
|
8346
|
+
var createVoiceTelephonyOutcomePolicy = (policy = {}) => ({
|
|
8347
|
+
completedStatuses: policy.completedStatuses ?? DEFAULT_COMPLETED_STATUSES,
|
|
8348
|
+
escalationStatuses: policy.escalationStatuses ?? DEFAULT_ESCALATION_STATUSES,
|
|
8349
|
+
failedAsNoAnswer: policy.failedAsNoAnswer ?? true,
|
|
8350
|
+
failedStatuses: policy.failedStatuses ?? DEFAULT_FAILED_STATUSES,
|
|
8351
|
+
includeProviderPayload: policy.includeProviderPayload ?? true,
|
|
8352
|
+
machineDetectionVoicemailValues: policy.machineDetectionVoicemailValues ?? DEFAULT_MACHINE_VOICEMAIL_VALUES,
|
|
8353
|
+
metadata: policy.metadata,
|
|
8354
|
+
minAnsweredDurationMs: policy.minAnsweredDurationMs,
|
|
8355
|
+
noAnswerOnZeroDuration: policy.noAnswerOnZeroDuration ?? true,
|
|
8356
|
+
noAnswerSipCodes: policy.noAnswerSipCodes ?? DEFAULT_NO_ANSWER_SIP_CODES,
|
|
8357
|
+
noAnswerStatuses: policy.noAnswerStatuses ?? DEFAULT_NO_ANSWER_STATUSES,
|
|
8358
|
+
statusMap: policy.statusMap,
|
|
8359
|
+
transferStatuses: policy.transferStatuses ?? DEFAULT_TRANSFER_STATUSES,
|
|
8360
|
+
transferTarget: policy.transferTarget,
|
|
8361
|
+
voicemailStatuses: policy.voicemailStatuses ?? DEFAULT_VOICEMAIL_STATUSES
|
|
8362
|
+
});
|
|
8363
|
+
var resolveVoiceTelephonyOutcome = (event, policyInput = {}) => {
|
|
8364
|
+
const policy = createVoiceTelephonyOutcomePolicy(policyInput);
|
|
8365
|
+
const status = normalizeToken(event.status);
|
|
8366
|
+
const provider = normalizeToken(event.provider);
|
|
8367
|
+
const answeredBy = normalizeToken(event.answeredBy);
|
|
8368
|
+
const target = resolveTransferTarget(event, policy);
|
|
8369
|
+
if (status) {
|
|
8370
|
+
const mapped = policy.statusMap?.[status] ?? (provider ? policy.statusMap?.[`${provider}:${status}`] : undefined);
|
|
8371
|
+
if (mapped) {
|
|
8372
|
+
return withDecisionDefaults(mapped, {
|
|
8373
|
+
event,
|
|
8374
|
+
policy,
|
|
8375
|
+
source: "policy"
|
|
8376
|
+
});
|
|
8377
|
+
}
|
|
8378
|
+
}
|
|
8379
|
+
if (answeredBy && normalizeList(policy.machineDetectionVoicemailValues, []).has(answeredBy)) {
|
|
8380
|
+
return buildDecision("voicemail", { event, policy, source: "answered-by" });
|
|
8381
|
+
}
|
|
8382
|
+
if (typeof event.sipCode === "number" && policy.noAnswerSipCodes.includes(event.sipCode)) {
|
|
8383
|
+
return buildDecision("no-answer", { event, policy, source: "sip" });
|
|
8384
|
+
}
|
|
8385
|
+
if (target && status && normalizeList(policy.transferStatuses, []).has(status)) {
|
|
8386
|
+
return buildDecision("transfer", { event, policy, source: "status" });
|
|
8387
|
+
}
|
|
8388
|
+
if (status && normalizeList(policy.voicemailStatuses, []).has(status)) {
|
|
8389
|
+
return buildDecision("voicemail", { event, policy, source: "status" });
|
|
8390
|
+
}
|
|
8391
|
+
if (status && normalizeList(policy.escalationStatuses, []).has(status)) {
|
|
8392
|
+
return buildDecision("escalate", { event, policy, source: "status" });
|
|
8393
|
+
}
|
|
8394
|
+
if (status && (policy.failedAsNoAnswer ? normalizeList(policy.noAnswerStatuses, []).has(status) || normalizeList(policy.failedStatuses, []).has(status) : normalizeList(policy.noAnswerStatuses, []).has(status))) {
|
|
8395
|
+
return buildDecision("no-answer", { event, policy, source: "status" });
|
|
8396
|
+
}
|
|
8397
|
+
if (policy.noAnswerOnZeroDuration && typeof event.durationMs === "number" && event.durationMs <= 0) {
|
|
8398
|
+
return buildDecision("no-answer", { event, policy, source: "duration" });
|
|
8399
|
+
}
|
|
8400
|
+
if (typeof policy.minAnsweredDurationMs === "number" && typeof event.durationMs === "number" && event.durationMs < policy.minAnsweredDurationMs) {
|
|
8401
|
+
return {
|
|
8402
|
+
...buildDecision("no-answer", { event, policy, source: "duration" }),
|
|
8403
|
+
confidence: "medium"
|
|
8404
|
+
};
|
|
8405
|
+
}
|
|
8406
|
+
if (status && normalizeList(policy.completedStatuses, []).has(status)) {
|
|
8407
|
+
return buildDecision("complete", { event, policy, source: "status" });
|
|
8408
|
+
}
|
|
8409
|
+
if (target) {
|
|
8410
|
+
return {
|
|
8411
|
+
...buildDecision("transfer", { event, policy, source: "explicit-target" }),
|
|
8412
|
+
confidence: "medium"
|
|
8413
|
+
};
|
|
8414
|
+
}
|
|
8415
|
+
return buildDecision("ignore", { event, policy, source: "status" });
|
|
8416
|
+
};
|
|
8417
|
+
var voiceTelephonyOutcomeToRouteResult = (decision, result) => {
|
|
8418
|
+
switch (decision.action) {
|
|
8419
|
+
case "complete":
|
|
8420
|
+
return { complete: true, result };
|
|
8421
|
+
case "escalate":
|
|
8422
|
+
return {
|
|
8423
|
+
escalate: {
|
|
8424
|
+
metadata: decision.metadata,
|
|
8425
|
+
reason: decision.reason ?? "telephony-escalation"
|
|
8426
|
+
},
|
|
8427
|
+
result
|
|
8428
|
+
};
|
|
8429
|
+
case "no-answer":
|
|
8430
|
+
return {
|
|
8431
|
+
noAnswer: {
|
|
8432
|
+
metadata: decision.metadata
|
|
8433
|
+
},
|
|
8434
|
+
result
|
|
8435
|
+
};
|
|
8436
|
+
case "transfer":
|
|
8437
|
+
if (!decision.target) {
|
|
8438
|
+
return { result };
|
|
8439
|
+
}
|
|
8440
|
+
return {
|
|
8441
|
+
result,
|
|
8442
|
+
transfer: {
|
|
8443
|
+
metadata: decision.metadata,
|
|
8444
|
+
reason: decision.reason,
|
|
8445
|
+
target: decision.target
|
|
8446
|
+
}
|
|
8447
|
+
};
|
|
8448
|
+
case "voicemail":
|
|
8449
|
+
return {
|
|
8450
|
+
result,
|
|
8451
|
+
voicemail: {
|
|
8452
|
+
metadata: decision.metadata
|
|
8453
|
+
}
|
|
8454
|
+
};
|
|
8455
|
+
default:
|
|
8456
|
+
return { result };
|
|
8457
|
+
}
|
|
8458
|
+
};
|
|
8459
|
+
var applyVoiceTelephonyOutcome = async (api, decision, result) => {
|
|
8460
|
+
switch (decision.action) {
|
|
8461
|
+
case "complete":
|
|
8462
|
+
await api.complete(result);
|
|
8463
|
+
break;
|
|
8464
|
+
case "escalate":
|
|
8465
|
+
await api.escalate({
|
|
8466
|
+
metadata: decision.metadata,
|
|
8467
|
+
reason: decision.reason ?? "telephony-escalation",
|
|
8468
|
+
result
|
|
8469
|
+
});
|
|
8470
|
+
break;
|
|
8471
|
+
case "no-answer":
|
|
8472
|
+
await api.markNoAnswer({
|
|
8473
|
+
metadata: decision.metadata,
|
|
8474
|
+
result
|
|
8475
|
+
});
|
|
8476
|
+
break;
|
|
8477
|
+
case "transfer":
|
|
8478
|
+
if (!decision.target) {
|
|
8479
|
+
return;
|
|
8480
|
+
}
|
|
8481
|
+
await api.transfer({
|
|
8482
|
+
metadata: decision.metadata,
|
|
8483
|
+
reason: decision.reason,
|
|
8484
|
+
result,
|
|
8485
|
+
target: decision.target
|
|
8486
|
+
});
|
|
8487
|
+
break;
|
|
8488
|
+
case "voicemail":
|
|
8489
|
+
await api.markVoicemail({
|
|
8490
|
+
metadata: decision.metadata,
|
|
8491
|
+
result
|
|
8492
|
+
});
|
|
8493
|
+
break;
|
|
8494
|
+
default:
|
|
8495
|
+
break;
|
|
8496
|
+
}
|
|
8497
|
+
};
|
|
8498
|
+
var parseRequestBodyText = (input) => {
|
|
8499
|
+
const { contentType, text } = input;
|
|
8500
|
+
if (!text) {
|
|
8501
|
+
return {};
|
|
8502
|
+
}
|
|
8503
|
+
if (contentType.includes("application/json")) {
|
|
8504
|
+
return parseMaybeJSON(text) ?? {};
|
|
8505
|
+
}
|
|
8506
|
+
if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
|
|
8507
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
8508
|
+
}
|
|
8509
|
+
return parseMaybeJSON(text) ?? Object.fromEntries(new URLSearchParams(text));
|
|
8510
|
+
};
|
|
8511
|
+
var readRequestBody = async (request) => {
|
|
8512
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
8513
|
+
const text = await request.text();
|
|
8514
|
+
return {
|
|
8515
|
+
body: parseRequestBodyText({ contentType, text }),
|
|
8516
|
+
rawBody: text
|
|
8517
|
+
};
|
|
8518
|
+
};
|
|
8519
|
+
var signVoiceTwilioWebhook = async (input) => signHmacSHA1Base64(input.authToken, `${input.url}${sortedParamsForSignature(input.body ?? {})}`);
|
|
8520
|
+
var verifyVoiceTwilioWebhookSignature = async (input) => {
|
|
8521
|
+
if (!input.authToken) {
|
|
8522
|
+
return { ok: false, reason: "missing-secret" };
|
|
8523
|
+
}
|
|
8524
|
+
const signature = input.headers.get("x-twilio-signature");
|
|
8525
|
+
if (!signature) {
|
|
8526
|
+
return { ok: false, reason: "missing-signature" };
|
|
8527
|
+
}
|
|
8528
|
+
const expected = await signVoiceTwilioWebhook({
|
|
8529
|
+
authToken: input.authToken,
|
|
8530
|
+
body: input.body,
|
|
8531
|
+
url: input.url
|
|
8532
|
+
});
|
|
8533
|
+
return timingSafeEqual(signature, expected) ? { ok: true } : { ok: false, reason: "invalid-signature" };
|
|
8534
|
+
};
|
|
8535
|
+
var resolveVerificationUrl = (option, input) => typeof option === "function" ? option(input) : option ?? input.request.url;
|
|
8536
|
+
var verifyVoiceTelephonyWebhook = async (input) => {
|
|
8537
|
+
if (input.options.verify) {
|
|
8538
|
+
return input.options.verify({
|
|
8539
|
+
body: input.body,
|
|
8540
|
+
headers: input.request.headers,
|
|
8541
|
+
provider: input.provider,
|
|
8542
|
+
query: input.query,
|
|
8543
|
+
rawBody: input.rawBody,
|
|
8544
|
+
request: input.request
|
|
8545
|
+
});
|
|
8546
|
+
}
|
|
8547
|
+
if (!input.options.signingSecret) {
|
|
8548
|
+
return input.options.requireVerification ? { ok: false, reason: "missing-secret" } : { ok: true };
|
|
8549
|
+
}
|
|
8550
|
+
if (input.provider !== "twilio") {
|
|
8551
|
+
return { ok: false, reason: "unsupported-provider" };
|
|
8552
|
+
}
|
|
8553
|
+
return verifyVoiceTwilioWebhookSignature({
|
|
8554
|
+
authToken: input.options.signingSecret,
|
|
8555
|
+
body: input.body,
|
|
8556
|
+
headers: input.request.headers,
|
|
8557
|
+
url: resolveVerificationUrl(input.options.verificationUrl, {
|
|
8558
|
+
query: input.query,
|
|
8559
|
+
request: input.request
|
|
8560
|
+
})
|
|
8561
|
+
});
|
|
8562
|
+
};
|
|
8563
|
+
var durationMsFromSeconds = (value) => typeof value === "number" ? value * 1000 : undefined;
|
|
8564
|
+
var parseVoiceTelephonyWebhookEvent = (input) => {
|
|
8565
|
+
const payload = flattenPayload(input.body);
|
|
8566
|
+
const provider = firstString(payload, ["provider", "Provider"]) ?? input.provider;
|
|
8567
|
+
const status = firstString(payload, [
|
|
8568
|
+
"CallStatus",
|
|
8569
|
+
"call_status",
|
|
8570
|
+
"callStatus",
|
|
8571
|
+
"DialCallStatus",
|
|
8572
|
+
"dial_call_status",
|
|
8573
|
+
"status",
|
|
8574
|
+
"event_type",
|
|
8575
|
+
"type"
|
|
8576
|
+
]);
|
|
8577
|
+
const durationMs = firstNumber(payload, ["durationMs", "duration_ms"]) ?? durationMsFromSeconds(firstNumber(payload, [
|
|
8578
|
+
"CallDuration",
|
|
8579
|
+
"call_duration",
|
|
8580
|
+
"callDuration",
|
|
8581
|
+
"DialCallDuration",
|
|
8582
|
+
"dial_call_duration",
|
|
8583
|
+
"duration"
|
|
8584
|
+
]));
|
|
8585
|
+
const sipCode = firstNumber(payload, [
|
|
8586
|
+
"SipResponseCode",
|
|
8587
|
+
"sip_response_code",
|
|
8588
|
+
"sipCode",
|
|
8589
|
+
"sip_code",
|
|
8590
|
+
"hangupCauseCode"
|
|
8591
|
+
]);
|
|
8592
|
+
const from = firstString(payload, ["From", "from", "caller_id", "callerId"]);
|
|
8593
|
+
const to = firstString(payload, ["To", "to", "called_number", "calledNumber"]);
|
|
8594
|
+
const target = firstString(payload, [
|
|
8595
|
+
"transferTarget",
|
|
8596
|
+
"TransferTarget",
|
|
8597
|
+
"target",
|
|
8598
|
+
"queue",
|
|
8599
|
+
"department"
|
|
8600
|
+
]);
|
|
8601
|
+
return {
|
|
8602
|
+
answeredBy: firstString(payload, [
|
|
8603
|
+
"AnsweredBy",
|
|
8604
|
+
"answered_by",
|
|
8605
|
+
"answeredBy",
|
|
8606
|
+
"machineDetection",
|
|
8607
|
+
"machine_detection"
|
|
8608
|
+
]),
|
|
8609
|
+
durationMs,
|
|
8610
|
+
from,
|
|
8611
|
+
metadata: {
|
|
8612
|
+
...input.query,
|
|
8613
|
+
...payload
|
|
8614
|
+
},
|
|
8615
|
+
provider,
|
|
8616
|
+
reason: firstString(payload, [
|
|
8617
|
+
"Reason",
|
|
8618
|
+
"reason",
|
|
8619
|
+
"HangupCause",
|
|
8620
|
+
"hangup_cause",
|
|
8621
|
+
"hangupCause"
|
|
8622
|
+
]),
|
|
8623
|
+
sipCode,
|
|
8624
|
+
status,
|
|
8625
|
+
target,
|
|
8626
|
+
to
|
|
8627
|
+
};
|
|
8628
|
+
};
|
|
8629
|
+
var defaultSessionId = (input) => {
|
|
8630
|
+
const payload = flattenPayload(input.body);
|
|
8631
|
+
const metadataSessionId = input.event.metadata?.sessionId;
|
|
8632
|
+
return firstString(input.query, ["sessionId", "session_id"]) ?? firstString(payload, [
|
|
8633
|
+
"sessionId",
|
|
8634
|
+
"session_id",
|
|
8635
|
+
"SessionId",
|
|
8636
|
+
"CallSid",
|
|
8637
|
+
"call_sid",
|
|
8638
|
+
"callSid",
|
|
8639
|
+
"CallUUID",
|
|
8640
|
+
"call_uuid",
|
|
8641
|
+
"callControlId",
|
|
8642
|
+
"call_control_id"
|
|
8643
|
+
]) ?? (typeof metadataSessionId === "string" ? metadataSessionId : undefined);
|
|
8644
|
+
};
|
|
8645
|
+
var defaultIdempotencyKey = (input) => {
|
|
8646
|
+
const payload = flattenPayload(input.body);
|
|
8647
|
+
const eventId = firstString(payload, [
|
|
8648
|
+
"id",
|
|
8649
|
+
"event_id",
|
|
8650
|
+
"eventId",
|
|
8651
|
+
"EventSid",
|
|
8652
|
+
"event_sid",
|
|
8653
|
+
"MessageSid",
|
|
8654
|
+
"message_sid",
|
|
8655
|
+
"CallSid",
|
|
8656
|
+
"call_sid",
|
|
8657
|
+
"CallUUID",
|
|
8658
|
+
"call_uuid",
|
|
8659
|
+
"callControlId",
|
|
8660
|
+
"call_control_id"
|
|
8661
|
+
]);
|
|
8662
|
+
const status = normalizeToken(input.event.status) ?? "unknown";
|
|
8663
|
+
if (eventId) {
|
|
8664
|
+
return `${input.provider}:${eventId}:${status}`;
|
|
8665
|
+
}
|
|
8666
|
+
if (input.sessionId) {
|
|
8667
|
+
return `${input.provider}:${input.sessionId}:${status}`;
|
|
8668
|
+
}
|
|
8669
|
+
};
|
|
8670
|
+
var createVoiceTelephonyWebhookHandler = (options = {}) => async (input) => {
|
|
8671
|
+
const provider = options.provider ?? "generic";
|
|
8672
|
+
const query = input.query ?? {};
|
|
8673
|
+
const { body, rawBody } = await readRequestBody(input.request);
|
|
8674
|
+
const verification = await verifyVoiceTelephonyWebhook({
|
|
8675
|
+
body,
|
|
8676
|
+
options,
|
|
8677
|
+
provider,
|
|
8678
|
+
query,
|
|
8679
|
+
rawBody,
|
|
8680
|
+
request: input.request
|
|
8681
|
+
});
|
|
8682
|
+
if (!verification.ok) {
|
|
8683
|
+
throw new VoiceTelephonyWebhookVerificationError(verification);
|
|
8684
|
+
}
|
|
8685
|
+
const event = options.parse ? await options.parse({
|
|
8686
|
+
body,
|
|
8687
|
+
headers: input.request.headers,
|
|
8688
|
+
provider,
|
|
8689
|
+
query,
|
|
8690
|
+
request: input.request
|
|
8691
|
+
}) : parseVoiceTelephonyWebhookEvent({
|
|
8692
|
+
body,
|
|
8693
|
+
headers: input.request.headers,
|
|
8694
|
+
provider,
|
|
8695
|
+
query,
|
|
8696
|
+
request: input.request
|
|
8697
|
+
});
|
|
8698
|
+
const sessionId = await (options.resolveSessionId?.({
|
|
8699
|
+
body,
|
|
8700
|
+
event,
|
|
8701
|
+
query,
|
|
8702
|
+
request: input.request
|
|
8703
|
+
}) ?? defaultSessionId({ body, event, query }));
|
|
8704
|
+
const idempotencyEnabled = options.idempotency?.enabled !== false;
|
|
8705
|
+
const idempotencyKey = idempotencyEnabled ? await (options.idempotency?.key?.({
|
|
8706
|
+
body,
|
|
8707
|
+
event,
|
|
8708
|
+
provider,
|
|
8709
|
+
query,
|
|
8710
|
+
request: input.request,
|
|
8711
|
+
sessionId
|
|
8712
|
+
}) ?? defaultIdempotencyKey({ body, event, provider, sessionId })) : undefined;
|
|
8713
|
+
const idempotencyStore = options.idempotency?.store;
|
|
8714
|
+
if (idempotencyKey && idempotencyStore) {
|
|
8715
|
+
const existing = await idempotencyStore.get(idempotencyKey);
|
|
8716
|
+
if (existing) {
|
|
8717
|
+
const duplicateDecision = {
|
|
8718
|
+
...existing,
|
|
8719
|
+
duplicate: true
|
|
8720
|
+
};
|
|
8721
|
+
await options.onDecision?.({
|
|
8722
|
+
...duplicateDecision,
|
|
8723
|
+
context: options.context,
|
|
8724
|
+
request: input.request
|
|
8725
|
+
});
|
|
8726
|
+
return duplicateDecision;
|
|
8727
|
+
}
|
|
8728
|
+
}
|
|
8729
|
+
const decision = resolveVoiceTelephonyOutcome(event, options.policy);
|
|
8730
|
+
const resultResolver = options.result;
|
|
8731
|
+
const result = typeof resultResolver === "function" ? await resultResolver({
|
|
8732
|
+
decision,
|
|
8733
|
+
event,
|
|
8734
|
+
sessionId
|
|
8735
|
+
}) : resultResolver;
|
|
8736
|
+
const routeResult = voiceTelephonyOutcomeToRouteResult(decision, result);
|
|
8737
|
+
const shouldApply = typeof options.apply === "function" ? options.apply({
|
|
8738
|
+
applied: false,
|
|
8739
|
+
decision,
|
|
8740
|
+
event,
|
|
8741
|
+
routeResult,
|
|
8742
|
+
sessionId
|
|
8743
|
+
}) : options.apply === true;
|
|
8744
|
+
let applied = false;
|
|
8745
|
+
if (shouldApply && decision.action !== "ignore" && options.getSessionHandle) {
|
|
8746
|
+
const api = await options.getSessionHandle({
|
|
8747
|
+
context: options.context,
|
|
8748
|
+
decision,
|
|
8749
|
+
event,
|
|
8750
|
+
request: input.request,
|
|
8751
|
+
sessionId
|
|
8752
|
+
});
|
|
8753
|
+
if (api) {
|
|
8754
|
+
await applyVoiceTelephonyOutcome(api, decision, result);
|
|
8755
|
+
applied = true;
|
|
8756
|
+
}
|
|
8757
|
+
}
|
|
8758
|
+
const webhookDecision = {
|
|
8759
|
+
applied,
|
|
8760
|
+
decision,
|
|
8761
|
+
event,
|
|
8762
|
+
idempotencyKey,
|
|
8763
|
+
routeResult,
|
|
8764
|
+
sessionId
|
|
8765
|
+
};
|
|
8766
|
+
if (idempotencyKey && idempotencyStore) {
|
|
8767
|
+
const now = Date.now();
|
|
8768
|
+
await idempotencyStore.set(idempotencyKey, {
|
|
8769
|
+
...webhookDecision,
|
|
8770
|
+
createdAt: now,
|
|
8771
|
+
updatedAt: now
|
|
8772
|
+
});
|
|
8773
|
+
}
|
|
8774
|
+
await options.onDecision?.({
|
|
8775
|
+
...webhookDecision,
|
|
8776
|
+
context: options.context,
|
|
8777
|
+
request: input.request
|
|
8778
|
+
});
|
|
8779
|
+
return webhookDecision;
|
|
8780
|
+
};
|
|
8781
|
+
var createVoiceTelephonyWebhookRoutes = (options = {}) => {
|
|
8782
|
+
const path = options.path ?? "/api/voice/telephony/webhook";
|
|
8783
|
+
const handler = createVoiceTelephonyWebhookHandler(options);
|
|
8784
|
+
return new Elysia({
|
|
8785
|
+
name: options.name ?? "absolutejs-voice-telephony-webhooks"
|
|
8786
|
+
}).post(path, async ({ query, request }) => {
|
|
8787
|
+
try {
|
|
8788
|
+
return await handler({ query, request });
|
|
8789
|
+
} catch (error) {
|
|
8790
|
+
if (error instanceof VoiceTelephonyWebhookVerificationError) {
|
|
8791
|
+
return new Response(JSON.stringify({ verification: error.result }), {
|
|
8792
|
+
headers: {
|
|
8793
|
+
"content-type": "application/json"
|
|
8794
|
+
},
|
|
8795
|
+
status: 401
|
|
8796
|
+
});
|
|
8797
|
+
}
|
|
8798
|
+
throw error;
|
|
8799
|
+
}
|
|
8800
|
+
}, {
|
|
8801
|
+
parse: "none"
|
|
8802
|
+
});
|
|
8803
|
+
};
|
|
8804
|
+
|
|
8805
|
+
// src/telephony/twilio.ts
|
|
6342
8806
|
var TWILIO_MULAW_SAMPLE_RATE = 8000;
|
|
6343
8807
|
var VOICE_PCM_SAMPLE_RATE = 16000;
|
|
6344
|
-
var
|
|
8808
|
+
var escapeXml2 = (value) => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">");
|
|
8809
|
+
var resolveRequestOrigin = (request) => {
|
|
8810
|
+
const url = new URL(request.url);
|
|
8811
|
+
const forwardedHost = request.headers.get("x-forwarded-host");
|
|
8812
|
+
const forwardedProto = request.headers.get("x-forwarded-proto");
|
|
8813
|
+
const host = forwardedHost ?? request.headers.get("host") ?? url.host;
|
|
8814
|
+
const protocol = forwardedProto ?? url.protocol.replace(":", "");
|
|
8815
|
+
return `${protocol}://${host}`;
|
|
8816
|
+
};
|
|
8817
|
+
var resolveTwilioStreamUrl = async (options, input) => {
|
|
8818
|
+
if (typeof options.twiml?.streamUrl === "function") {
|
|
8819
|
+
return options.twiml.streamUrl(input);
|
|
8820
|
+
}
|
|
8821
|
+
if (typeof options.twiml?.streamUrl === "string") {
|
|
8822
|
+
return options.twiml.streamUrl;
|
|
8823
|
+
}
|
|
8824
|
+
const origin = resolveRequestOrigin(input.request);
|
|
8825
|
+
const wsOrigin = origin.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
|
|
8826
|
+
return `${wsOrigin}${input.streamPath}`;
|
|
8827
|
+
};
|
|
8828
|
+
var resolveTwilioStreamParameters = async (parameters, input) => {
|
|
8829
|
+
if (typeof parameters === "function") {
|
|
8830
|
+
return parameters(input);
|
|
8831
|
+
}
|
|
8832
|
+
return parameters;
|
|
8833
|
+
};
|
|
8834
|
+
var joinUrlPath = (origin, path) => `${origin.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
|
|
8835
|
+
var escapeHtml2 = (value) => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">");
|
|
8836
|
+
var getWebhookVerificationUrl = (webhook, input) => {
|
|
8837
|
+
if (!webhook?.verificationUrl) {
|
|
8838
|
+
return;
|
|
8839
|
+
}
|
|
8840
|
+
if (typeof webhook.verificationUrl === "function") {
|
|
8841
|
+
return webhook.verificationUrl(input);
|
|
8842
|
+
}
|
|
8843
|
+
return webhook.verificationUrl;
|
|
8844
|
+
};
|
|
8845
|
+
var buildTwilioVoiceSetupStatus = async (options, input) => {
|
|
8846
|
+
const origin = resolveRequestOrigin(input.request);
|
|
8847
|
+
const stream = await resolveTwilioStreamUrl(options, input);
|
|
8848
|
+
const twiml = joinUrlPath(origin, input.twimlPath);
|
|
8849
|
+
const webhook = joinUrlPath(origin, input.webhookPath);
|
|
8850
|
+
const verificationUrl = getWebhookVerificationUrl(options.webhook, input);
|
|
8851
|
+
const missing = Object.entries(options.setup?.requiredEnv ?? {}).filter((entry) => !entry[1]).map(([name]) => name);
|
|
8852
|
+
const signingConfigured = Boolean(options.webhook?.signingSecret || options.webhook?.verify);
|
|
8853
|
+
const warnings = [
|
|
8854
|
+
...stream.startsWith("wss://") ? [] : ["Twilio media streams should use wss:// in production."],
|
|
8855
|
+
...signingConfigured ? [] : ["Webhook signature verification is not configured."],
|
|
8856
|
+
...verificationUrl || !signingConfigured ? [] : ["Webhook signing is configured without an explicit verification URL."]
|
|
8857
|
+
];
|
|
8858
|
+
return {
|
|
8859
|
+
generatedAt: Date.now(),
|
|
8860
|
+
missing,
|
|
8861
|
+
provider: "twilio",
|
|
8862
|
+
ready: missing.length === 0 && signingConfigured && warnings.length === 0,
|
|
8863
|
+
signing: {
|
|
8864
|
+
configured: signingConfigured,
|
|
8865
|
+
mode: options.webhook?.verify ? "custom" : options.webhook?.signingSecret ? "twilio-signature" : "none",
|
|
8866
|
+
verificationUrl
|
|
8867
|
+
},
|
|
8868
|
+
urls: {
|
|
8869
|
+
stream,
|
|
8870
|
+
twiml,
|
|
8871
|
+
webhook
|
|
8872
|
+
},
|
|
8873
|
+
warnings
|
|
8874
|
+
};
|
|
8875
|
+
};
|
|
8876
|
+
var renderTwilioVoiceSetupHTML = (status, title) => `<main style="font-family: ui-sans-serif, system-ui; max-width: 860px; margin: 40px auto; padding: 0 20px;">
|
|
8877
|
+
<p style="letter-spacing: .12em; text-transform: uppercase; color: #52606d;">Twilio setup</p>
|
|
8878
|
+
<h1>${escapeHtml2(title)}</h1>
|
|
8879
|
+
<p><strong>Status:</strong> ${status.ready ? "Ready" : "Needs attention"}</p>
|
|
8880
|
+
<section>
|
|
8881
|
+
<h2>URLs</h2>
|
|
8882
|
+
<ul>
|
|
8883
|
+
<li><strong>TwiML:</strong> <code>${escapeHtml2(status.urls.twiml)}</code></li>
|
|
8884
|
+
<li><strong>Media stream:</strong> <code>${escapeHtml2(status.urls.stream)}</code></li>
|
|
8885
|
+
<li><strong>Status webhook:</strong> <code>${escapeHtml2(status.urls.webhook)}</code></li>
|
|
8886
|
+
</ul>
|
|
8887
|
+
</section>
|
|
8888
|
+
<section>
|
|
8889
|
+
<h2>Signing</h2>
|
|
8890
|
+
<p>Mode: <code>${status.signing.mode}</code></p>
|
|
8891
|
+
${status.signing.verificationUrl ? `<p>Verification URL: <code>${escapeHtml2(status.signing.verificationUrl)}</code></p>` : ""}
|
|
8892
|
+
</section>
|
|
8893
|
+
${status.missing.length ? `<section><h2>Missing env</h2><ul>${status.missing.map((name) => `<li><code>${escapeHtml2(name)}</code></li>`).join("")}</ul></section>` : ""}
|
|
8894
|
+
${status.warnings.length ? `<section><h2>Warnings</h2><ul>${status.warnings.map((warning) => `<li>${escapeHtml2(warning)}</li>`).join("")}</ul></section>` : ""}
|
|
8895
|
+
</main>`;
|
|
8896
|
+
var extractTwilioStreamUrl = (twiml) => twiml.match(/<Stream\b[^>]*\surl="([^"]+)"/i)?.[1]?.replaceAll("&", "&");
|
|
8897
|
+
var createSmokeCheck = (name, status, message, details) => ({
|
|
8898
|
+
details,
|
|
8899
|
+
message,
|
|
8900
|
+
name,
|
|
8901
|
+
status
|
|
8902
|
+
});
|
|
8903
|
+
var renderTwilioVoiceSmokeHTML = (report, title) => `<main style="font-family: ui-sans-serif, system-ui; max-width: 860px; margin: 40px auto; padding: 0 20px;">
|
|
8904
|
+
<p style="letter-spacing: .12em; text-transform: uppercase; color: #52606d;">Twilio smoke test</p>
|
|
8905
|
+
<h1>${escapeHtml2(title)}</h1>
|
|
8906
|
+
<p><strong>Status:</strong> ${report.pass ? "Pass" : "Fail"}</p>
|
|
8907
|
+
<section>
|
|
8908
|
+
<h2>Checks</h2>
|
|
8909
|
+
<ul>
|
|
8910
|
+
${report.checks.map((check) => `<li><strong>${escapeHtml2(check.name)}</strong>: ${escapeHtml2(check.status)}${check.message ? ` - ${escapeHtml2(check.message)}` : ""}</li>`).join("")}
|
|
8911
|
+
</ul>
|
|
8912
|
+
</section>
|
|
8913
|
+
<section>
|
|
8914
|
+
<h2>Observed URLs</h2>
|
|
8915
|
+
<ul>
|
|
8916
|
+
<li><strong>TwiML:</strong> <code>${escapeHtml2(report.setup.urls.twiml)}</code></li>
|
|
8917
|
+
<li><strong>Stream:</strong> <code>${escapeHtml2(report.twiml?.streamUrl ?? report.setup.urls.stream)}</code></li>
|
|
8918
|
+
<li><strong>Webhook:</strong> <code>${escapeHtml2(report.setup.urls.webhook)}</code></li>
|
|
8919
|
+
</ul>
|
|
8920
|
+
</section>
|
|
8921
|
+
</main>`;
|
|
8922
|
+
var runTwilioVoiceSmokeTest = async (input) => {
|
|
8923
|
+
const setup = await buildTwilioVoiceSetupStatus(input.options, input);
|
|
8924
|
+
const checks = [];
|
|
8925
|
+
const twimlUrl = new URL(setup.urls.twiml);
|
|
8926
|
+
twimlUrl.searchParams.set("scenarioId", input.options.smoke?.scenarioId ?? "smoke");
|
|
8927
|
+
twimlUrl.searchParams.set("sessionId", input.options.smoke?.sessionId ?? "smoke-session");
|
|
8928
|
+
const twimlResponse = await input.app.handle(new Request(twimlUrl, {
|
|
8929
|
+
headers: input.request.headers
|
|
8930
|
+
}));
|
|
8931
|
+
const twiml = await twimlResponse.text();
|
|
8932
|
+
const streamUrl = extractTwilioStreamUrl(twiml);
|
|
8933
|
+
checks.push(createSmokeCheck("twiml", twimlResponse.ok && Boolean(streamUrl) ? "pass" : "fail", streamUrl ? "TwiML includes a media stream URL." : 'TwiML is missing <Stream url="...">.', {
|
|
8934
|
+
status: twimlResponse.status,
|
|
8935
|
+
streamUrl
|
|
8936
|
+
}));
|
|
8937
|
+
checks.push(createSmokeCheck("stream-url", streamUrl?.startsWith("wss://") ? "pass" : "fail", streamUrl?.startsWith("wss://") ? "Media stream URL uses wss://." : "Media stream URL should use wss:// for Twilio.", {
|
|
8938
|
+
streamUrl
|
|
8939
|
+
}));
|
|
8940
|
+
const webhookBody = {
|
|
8941
|
+
CallSid: input.options.smoke?.callSid ?? "CA_SMOKE_TEST",
|
|
8942
|
+
CallStatus: input.options.smoke?.status ?? "busy",
|
|
8943
|
+
SipResponseCode: String(input.options.smoke?.sipCode ?? 486)
|
|
8944
|
+
};
|
|
8945
|
+
const webhookHeaders = new Headers({
|
|
8946
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
8947
|
+
});
|
|
8948
|
+
const verificationUrl = setup.signing.verificationUrl ?? setup.urls.webhook;
|
|
8949
|
+
if (input.options.webhook?.signingSecret) {
|
|
8950
|
+
webhookHeaders.set("x-twilio-signature", await signVoiceTwilioWebhook({
|
|
8951
|
+
authToken: input.options.webhook.signingSecret,
|
|
8952
|
+
body: webhookBody,
|
|
8953
|
+
url: verificationUrl
|
|
8954
|
+
}));
|
|
8955
|
+
}
|
|
8956
|
+
const webhookResponse = await input.app.handle(new Request(setup.urls.webhook, {
|
|
8957
|
+
body: new URLSearchParams(webhookBody),
|
|
8958
|
+
headers: webhookHeaders,
|
|
8959
|
+
method: "POST"
|
|
8960
|
+
}));
|
|
8961
|
+
const webhookText = await webhookResponse.text();
|
|
8962
|
+
const webhookPayload = (() => {
|
|
8963
|
+
try {
|
|
8964
|
+
return JSON.parse(webhookText);
|
|
8965
|
+
} catch {
|
|
8966
|
+
return webhookText;
|
|
8967
|
+
}
|
|
8968
|
+
})();
|
|
8969
|
+
checks.push(createSmokeCheck("webhook", webhookResponse.ok ? "pass" : "fail", webhookResponse.ok ? "Synthetic Twilio status callback was accepted." : "Synthetic Twilio status callback failed.", {
|
|
8970
|
+
status: webhookResponse.status
|
|
8971
|
+
}));
|
|
8972
|
+
for (const warning of setup.warnings) {
|
|
8973
|
+
checks.push(createSmokeCheck("setup-warning", "warn", warning));
|
|
8974
|
+
}
|
|
8975
|
+
for (const name of setup.missing) {
|
|
8976
|
+
checks.push(createSmokeCheck("missing-env", "fail", `${name} is missing.`));
|
|
8977
|
+
}
|
|
8978
|
+
return {
|
|
8979
|
+
checks,
|
|
8980
|
+
generatedAt: Date.now(),
|
|
8981
|
+
pass: checks.every((check) => check.status !== "fail"),
|
|
8982
|
+
provider: "twilio",
|
|
8983
|
+
setup,
|
|
8984
|
+
twiml: {
|
|
8985
|
+
status: twimlResponse.status,
|
|
8986
|
+
streamUrl
|
|
8987
|
+
},
|
|
8988
|
+
webhook: {
|
|
8989
|
+
body: webhookPayload,
|
|
8990
|
+
status: webhookResponse.status
|
|
8991
|
+
}
|
|
8992
|
+
};
|
|
8993
|
+
};
|
|
6345
8994
|
var normalizeOnTurn = (handler) => {
|
|
6346
8995
|
if (handler.length > 1) {
|
|
6347
8996
|
const directHandler = handler;
|
|
@@ -6443,7 +9092,7 @@ var bytesToInt16Array = (bytes) => {
|
|
|
6443
9092
|
return output;
|
|
6444
9093
|
};
|
|
6445
9094
|
var decodeTwilioMulawBase64 = (payload) => {
|
|
6446
|
-
const bytes = Uint8Array.from(
|
|
9095
|
+
const bytes = Uint8Array.from(Buffer3.from(payload, "base64"));
|
|
6447
9096
|
const samples = new Int16Array(bytes.length);
|
|
6448
9097
|
for (let index = 0;index < bytes.length; index += 1) {
|
|
6449
9098
|
samples[index] = decodeMulawSample(bytes[index] ?? 0);
|
|
@@ -6455,7 +9104,7 @@ var encodeTwilioMulawBase64 = (samples) => {
|
|
|
6455
9104
|
for (let index = 0;index < samples.length; index += 1) {
|
|
6456
9105
|
bytes[index] = encodeMulawSample(samples[index] ?? 0);
|
|
6457
9106
|
}
|
|
6458
|
-
return
|
|
9107
|
+
return Buffer3.from(bytes).toString("base64");
|
|
6459
9108
|
};
|
|
6460
9109
|
var transcodeTwilioInboundPayloadToPCM16 = (payload) => {
|
|
6461
9110
|
const narrowband = decodeTwilioMulawBase64(payload);
|
|
@@ -6464,7 +9113,7 @@ var transcodeTwilioInboundPayloadToPCM16 = (payload) => {
|
|
|
6464
9113
|
};
|
|
6465
9114
|
var transcodePCMToTwilioOutboundPayload = (chunk, format) => {
|
|
6466
9115
|
if (format.container === "raw" && format.encoding === "mulaw" && format.channels === 1 && format.sampleRateHz === TWILIO_MULAW_SAMPLE_RATE) {
|
|
6467
|
-
return
|
|
9116
|
+
return Buffer3.from(chunk).toString("base64");
|
|
6468
9117
|
}
|
|
6469
9118
|
if (format.encoding !== "pcm_s16le") {
|
|
6470
9119
|
throw new Error(`Unsupported outbound telephony audio format: ${format.container}/${format.encoding}`);
|
|
@@ -6505,7 +9154,7 @@ var createTwilioSocketAdapter = (socket, getState) => ({
|
|
|
6505
9154
|
return;
|
|
6506
9155
|
}
|
|
6507
9156
|
if (message.type === "audio") {
|
|
6508
|
-
const payload = transcodePCMToTwilioOutboundPayload(Uint8Array.from(
|
|
9157
|
+
const payload = transcodePCMToTwilioOutboundPayload(Uint8Array.from(Buffer3.from(message.chunkBase64, "base64")), message.format);
|
|
6509
9158
|
state.hasOutboundAudioSinceLastInbound = true;
|
|
6510
9159
|
state.reviewRecorder?.recordTwilioOutbound({
|
|
6511
9160
|
bytes: payload.length,
|
|
@@ -6537,8 +9186,8 @@ var createTwilioSocketAdapter = (socket, getState) => ({
|
|
|
6537
9186
|
}
|
|
6538
9187
|
});
|
|
6539
9188
|
var createTwilioVoiceResponse = (options) => {
|
|
6540
|
-
const parameters = Object.entries(options.parameters ?? {}).filter((entry) => entry[1] !== undefined).map(([name, value]) => `<Parameter name="${
|
|
6541
|
-
return `<?xml version="1.0" encoding="UTF-8"?><Response><Connect><Stream url="${
|
|
9189
|
+
const parameters = Object.entries(options.parameters ?? {}).filter((entry) => entry[1] !== undefined).map(([name, value]) => `<Parameter name="${escapeXml2(name)}" value="${escapeXml2(String(value))}" />`).join("");
|
|
9190
|
+
return `<?xml version="1.0" encoding="UTF-8"?><Response><Connect><Stream url="${escapeXml2(options.streamUrl)}"${options.track ? ` track="${escapeXml2(options.track)}"` : ""}${options.streamName ? ` name="${escapeXml2(options.streamName)}"` : ""}>${parameters}</Stream></Connect></Response>`;
|
|
6542
9191
|
};
|
|
6543
9192
|
var createTwilioMediaStreamBridge = (socket, options) => {
|
|
6544
9193
|
const runtimePreset = resolveVoiceRuntimePreset(options.preset);
|
|
@@ -6718,6 +9367,148 @@ var createTwilioMediaStreamBridge = (socket, options) => {
|
|
|
6718
9367
|
}
|
|
6719
9368
|
};
|
|
6720
9369
|
};
|
|
9370
|
+
var createTwilioVoiceRoutes = (options) => {
|
|
9371
|
+
const streamPath = options.streamPath ?? "/api/voice/twilio/stream";
|
|
9372
|
+
const twimlPath = options.twiml?.path ?? "/api/voice/twilio";
|
|
9373
|
+
const webhookPath = options.webhook?.path ?? "/api/voice/twilio/webhook";
|
|
9374
|
+
const setupPath = options.setup?.path === false ? false : options.setup?.path ?? "/api/voice/twilio/setup";
|
|
9375
|
+
const smokePath = options.smoke?.path === false ? false : options.smoke?.path ?? "/api/voice/twilio/smoke";
|
|
9376
|
+
const bridges = new WeakMap;
|
|
9377
|
+
const webhookPolicy = options.webhook?.policy ?? options.outcomePolicy ?? createVoiceTelephonyOutcomePolicy();
|
|
9378
|
+
const app = new Elysia2({
|
|
9379
|
+
name: options.name ?? "absolutejs-voice-twilio"
|
|
9380
|
+
}).get(twimlPath, async ({ query, request }) => {
|
|
9381
|
+
const streamUrl = await resolveTwilioStreamUrl(options, {
|
|
9382
|
+
query,
|
|
9383
|
+
request,
|
|
9384
|
+
streamPath
|
|
9385
|
+
});
|
|
9386
|
+
const parameters = await resolveTwilioStreamParameters(options.twiml?.parameters, {
|
|
9387
|
+
query,
|
|
9388
|
+
request
|
|
9389
|
+
});
|
|
9390
|
+
return new Response(createTwilioVoiceResponse({
|
|
9391
|
+
parameters,
|
|
9392
|
+
streamName: options.twiml?.streamName,
|
|
9393
|
+
streamUrl,
|
|
9394
|
+
track: options.twiml?.track
|
|
9395
|
+
}), {
|
|
9396
|
+
headers: {
|
|
9397
|
+
"content-type": "text/xml; charset=utf-8"
|
|
9398
|
+
}
|
|
9399
|
+
});
|
|
9400
|
+
}).post(twimlPath, async ({ query, request }) => {
|
|
9401
|
+
const streamUrl = await resolveTwilioStreamUrl(options, {
|
|
9402
|
+
query,
|
|
9403
|
+
request,
|
|
9404
|
+
streamPath
|
|
9405
|
+
});
|
|
9406
|
+
const parameters = await resolveTwilioStreamParameters(options.twiml?.parameters, {
|
|
9407
|
+
query,
|
|
9408
|
+
request
|
|
9409
|
+
});
|
|
9410
|
+
return new Response(createTwilioVoiceResponse({
|
|
9411
|
+
parameters,
|
|
9412
|
+
streamName: options.twiml?.streamName,
|
|
9413
|
+
streamUrl,
|
|
9414
|
+
track: options.twiml?.track
|
|
9415
|
+
}), {
|
|
9416
|
+
headers: {
|
|
9417
|
+
"content-type": "text/xml; charset=utf-8"
|
|
9418
|
+
}
|
|
9419
|
+
});
|
|
9420
|
+
}).ws(streamPath, {
|
|
9421
|
+
close: async (ws, _code, reason) => {
|
|
9422
|
+
const bridge = bridges.get(ws);
|
|
9423
|
+
bridges.delete(ws);
|
|
9424
|
+
await bridge?.close(reason);
|
|
9425
|
+
},
|
|
9426
|
+
message: async (ws, raw) => {
|
|
9427
|
+
let bridge = bridges.get(ws);
|
|
9428
|
+
if (!bridge) {
|
|
9429
|
+
bridge = createTwilioMediaStreamBridge({
|
|
9430
|
+
close: (code, reason) => {
|
|
9431
|
+
ws.close(code, reason);
|
|
9432
|
+
},
|
|
9433
|
+
send: (data) => {
|
|
9434
|
+
ws.send(data);
|
|
9435
|
+
}
|
|
9436
|
+
}, options);
|
|
9437
|
+
bridges.set(ws, bridge);
|
|
9438
|
+
}
|
|
9439
|
+
await bridge.handleMessage(raw);
|
|
9440
|
+
}
|
|
9441
|
+
}).use(createVoiceTelephonyWebhookRoutes({
|
|
9442
|
+
...options.webhook ?? {},
|
|
9443
|
+
context: options.context,
|
|
9444
|
+
path: webhookPath,
|
|
9445
|
+
policy: webhookPolicy,
|
|
9446
|
+
provider: "twilio"
|
|
9447
|
+
}));
|
|
9448
|
+
if (!setupPath) {
|
|
9449
|
+
if (!smokePath) {
|
|
9450
|
+
return app;
|
|
9451
|
+
}
|
|
9452
|
+
return app.get(smokePath, async ({ query, request }) => {
|
|
9453
|
+
const report = await runTwilioVoiceSmokeTest({
|
|
9454
|
+
app,
|
|
9455
|
+
options,
|
|
9456
|
+
query,
|
|
9457
|
+
request,
|
|
9458
|
+
streamPath,
|
|
9459
|
+
twimlPath,
|
|
9460
|
+
webhookPath
|
|
9461
|
+
});
|
|
9462
|
+
if (query.format === "html") {
|
|
9463
|
+
return new Response(renderTwilioVoiceSmokeHTML(report, options.smoke?.title ?? "AbsoluteJS Twilio Voice Smoke Test"), {
|
|
9464
|
+
headers: {
|
|
9465
|
+
"content-type": "text/html; charset=utf-8"
|
|
9466
|
+
}
|
|
9467
|
+
});
|
|
9468
|
+
}
|
|
9469
|
+
return report;
|
|
9470
|
+
});
|
|
9471
|
+
}
|
|
9472
|
+
const withSetup = app.get(setupPath, async ({ query, request }) => {
|
|
9473
|
+
const status = await buildTwilioVoiceSetupStatus(options, {
|
|
9474
|
+
query,
|
|
9475
|
+
request,
|
|
9476
|
+
streamPath,
|
|
9477
|
+
twimlPath,
|
|
9478
|
+
webhookPath
|
|
9479
|
+
});
|
|
9480
|
+
if (query.format === "html") {
|
|
9481
|
+
return new Response(renderTwilioVoiceSetupHTML(status, options.setup?.title ?? "AbsoluteJS Twilio Voice Setup"), {
|
|
9482
|
+
headers: {
|
|
9483
|
+
"content-type": "text/html; charset=utf-8"
|
|
9484
|
+
}
|
|
9485
|
+
});
|
|
9486
|
+
}
|
|
9487
|
+
return status;
|
|
9488
|
+
});
|
|
9489
|
+
if (!smokePath) {
|
|
9490
|
+
return withSetup;
|
|
9491
|
+
}
|
|
9492
|
+
return withSetup.get(smokePath, async ({ query, request }) => {
|
|
9493
|
+
const report = await runTwilioVoiceSmokeTest({
|
|
9494
|
+
app,
|
|
9495
|
+
options,
|
|
9496
|
+
query,
|
|
9497
|
+
request,
|
|
9498
|
+
streamPath,
|
|
9499
|
+
twimlPath,
|
|
9500
|
+
webhookPath
|
|
9501
|
+
});
|
|
9502
|
+
if (query.format === "html") {
|
|
9503
|
+
return new Response(renderTwilioVoiceSmokeHTML(report, options.smoke?.title ?? "AbsoluteJS Twilio Voice Smoke Test"), {
|
|
9504
|
+
headers: {
|
|
9505
|
+
"content-type": "text/html; charset=utf-8"
|
|
9506
|
+
}
|
|
9507
|
+
});
|
|
9508
|
+
}
|
|
9509
|
+
return report;
|
|
9510
|
+
});
|
|
9511
|
+
};
|
|
6721
9512
|
|
|
6722
9513
|
// src/testing/telephony.ts
|
|
6723
9514
|
var DEFAULT_PCM16_FORMAT = {
|
|
@@ -6983,7 +9774,7 @@ var runVoiceTelephonyBenchmark = async (scenarios = getDefaultVoiceTelephonyBenc
|
|
|
6983
9774
|
};
|
|
6984
9775
|
};
|
|
6985
9776
|
// src/testing/tts.ts
|
|
6986
|
-
var
|
|
9777
|
+
var DEFAULT_REALTIME_FORMAT2 = {
|
|
6987
9778
|
channels: 1,
|
|
6988
9779
|
container: "raw",
|
|
6989
9780
|
encoding: "pcm_s16le",
|
|
@@ -7042,7 +9833,7 @@ var runTTSAdapterFixture = async (adapter, fixture, options = {}) => {
|
|
|
7042
9833
|
let audioDurationMs = 0;
|
|
7043
9834
|
let audioChunkCount = 0;
|
|
7044
9835
|
const session = adapter.kind === "realtime" ? await adapter.open({
|
|
7045
|
-
format: options.realtimeFormat ??
|
|
9836
|
+
format: options.realtimeFormat ?? DEFAULT_REALTIME_FORMAT2,
|
|
7046
9837
|
sessionId: `tts-benchmark:${fixture.id}`,
|
|
7047
9838
|
...openOptions ?? {}
|
|
7048
9839
|
}) : await adapter.open({
|
|
@@ -7208,6 +9999,8 @@ export {
|
|
|
7208
9999
|
getDefaultVoiceDuplexBenchmarkScenarios,
|
|
7209
10000
|
getDefaultTTSBenchmarkFixtures,
|
|
7210
10001
|
evaluateSTTBenchmarkAcceptance,
|
|
10002
|
+
createVoiceProviderFailureSimulator,
|
|
10003
|
+
createVoiceIOProviderFailureSimulator,
|
|
7211
10004
|
createVoiceCallReviewRecorder,
|
|
7212
10005
|
createVoiceCallReviewFromLiveTelephonyReport,
|
|
7213
10006
|
createTelephonyVoiceTestFixtures,
|