@agenticmail/core 0.9.13 → 0.9.14
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/dist/index.cjs +1028 -7
- package/dist/index.d.cts +288 -1
- package/dist/index.d.ts +288 -1
- package/dist/index.js +997 -6
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6225,8 +6225,969 @@ var RELAY_PRESETS = {
|
|
|
6225
6225
|
}
|
|
6226
6226
|
};
|
|
6227
6227
|
|
|
6228
|
+
// src/phone/realtime.ts
|
|
6229
|
+
var ELKS_REALTIME_AUDIO_FORMATS = ["ulaw", "pcm_16000", "pcm_24000", "wav"];
|
|
6230
|
+
function asRecord(value) {
|
|
6231
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
6232
|
+
}
|
|
6233
|
+
function asString2(value) {
|
|
6234
|
+
return typeof value === "string" ? value.trim() : "";
|
|
6235
|
+
}
|
|
6236
|
+
function isAudioFormat(value) {
|
|
6237
|
+
return typeof value === "string" && ELKS_REALTIME_AUDIO_FORMATS.includes(value);
|
|
6238
|
+
}
|
|
6239
|
+
function assertAudioFormat(format) {
|
|
6240
|
+
if (!isAudioFormat(format)) {
|
|
6241
|
+
throw new Error(`Unsupported 46elks realtime audio format: ${String(format)}`);
|
|
6242
|
+
}
|
|
6243
|
+
return format;
|
|
6244
|
+
}
|
|
6245
|
+
function looksLikeBase64(value) {
|
|
6246
|
+
return value.length > 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value) && value.length % 4 === 0;
|
|
6247
|
+
}
|
|
6248
|
+
function decodeJsonMessage(input) {
|
|
6249
|
+
if (typeof input === "string") {
|
|
6250
|
+
try {
|
|
6251
|
+
return asRecord(JSON.parse(input));
|
|
6252
|
+
} catch {
|
|
6253
|
+
throw new Error("Invalid 46elks realtime message: expected JSON object string");
|
|
6254
|
+
}
|
|
6255
|
+
}
|
|
6256
|
+
return asRecord(input);
|
|
6257
|
+
}
|
|
6258
|
+
function parseElksRealtimeMessage(input) {
|
|
6259
|
+
const msg = decodeJsonMessage(input);
|
|
6260
|
+
const type = asString2(msg.t);
|
|
6261
|
+
if (type === "hello") {
|
|
6262
|
+
const callid = asString2(msg.callid);
|
|
6263
|
+
const from = asString2(msg.from);
|
|
6264
|
+
const to = asString2(msg.to);
|
|
6265
|
+
if (!callid || !from || !to) {
|
|
6266
|
+
throw new Error("Invalid 46elks realtime hello: callid, from, and to are required");
|
|
6267
|
+
}
|
|
6268
|
+
return { ...msg, t: "hello", callid, from, to };
|
|
6269
|
+
}
|
|
6270
|
+
if (type === "audio") {
|
|
6271
|
+
const data = asString2(msg.data);
|
|
6272
|
+
if (!looksLikeBase64(data)) {
|
|
6273
|
+
throw new Error("Invalid 46elks realtime audio: data must be non-empty base64");
|
|
6274
|
+
}
|
|
6275
|
+
return { t: "audio", data };
|
|
6276
|
+
}
|
|
6277
|
+
if (type === "bye") {
|
|
6278
|
+
const reason = asString2(msg.reason) || void 0;
|
|
6279
|
+
const message = asString2(msg.message) || void 0;
|
|
6280
|
+
return { ...msg, t: "bye", reason, message };
|
|
6281
|
+
}
|
|
6282
|
+
throw new Error(`Unsupported 46elks realtime message type: ${type || "(missing)"}`);
|
|
6283
|
+
}
|
|
6284
|
+
function buildElksListeningMessage(format = "pcm_24000") {
|
|
6285
|
+
return { t: "listening", format: assertAudioFormat(format) };
|
|
6286
|
+
}
|
|
6287
|
+
function buildElksSendingMessage(format = "pcm_24000") {
|
|
6288
|
+
return { t: "sending", format: assertAudioFormat(format) };
|
|
6289
|
+
}
|
|
6290
|
+
function buildElksAudioMessage(data) {
|
|
6291
|
+
const encoded = typeof data === "string" ? data : Buffer.from(data).toString("base64");
|
|
6292
|
+
if (!looksLikeBase64(encoded)) {
|
|
6293
|
+
throw new Error("46elks realtime audio data must be base64 or bytes");
|
|
6294
|
+
}
|
|
6295
|
+
return { t: "audio", data: encoded };
|
|
6296
|
+
}
|
|
6297
|
+
function buildElksInterruptMessage() {
|
|
6298
|
+
return { t: "interrupt" };
|
|
6299
|
+
}
|
|
6300
|
+
function buildElksByeMessage() {
|
|
6301
|
+
return { t: "bye" };
|
|
6302
|
+
}
|
|
6303
|
+
function buildElksHandshakeMessages(options = {}) {
|
|
6304
|
+
return [
|
|
6305
|
+
buildElksListeningMessage(options.listenFormat ?? "pcm_24000"),
|
|
6306
|
+
buildElksSendingMessage(options.sendFormat ?? "pcm_24000")
|
|
6307
|
+
];
|
|
6308
|
+
}
|
|
6309
|
+
|
|
6310
|
+
// src/phone/manager.ts
|
|
6311
|
+
import { createHash as createHash2, createHmac, randomUUID, timingSafeEqual } from "crypto";
|
|
6312
|
+
|
|
6313
|
+
// src/phone/mission.ts
|
|
6314
|
+
var PHONE_REGION_SCOPES = ["AT", "DE", "EU", "WORLD"];
|
|
6315
|
+
var TELEPHONY_TRANSPORT_CAPABILITIES = [
|
|
6316
|
+
"sms",
|
|
6317
|
+
"call_control",
|
|
6318
|
+
"realtime_media",
|
|
6319
|
+
"recording_supported"
|
|
6320
|
+
];
|
|
6321
|
+
var PHONE_MISSION_STATES = [
|
|
6322
|
+
"draft",
|
|
6323
|
+
"approved",
|
|
6324
|
+
"dialing",
|
|
6325
|
+
"connected",
|
|
6326
|
+
"conversing",
|
|
6327
|
+
"needs_operator",
|
|
6328
|
+
"completed",
|
|
6329
|
+
"failed",
|
|
6330
|
+
"cancelled"
|
|
6331
|
+
];
|
|
6332
|
+
var PHONE_SERVER_MAX_CALL_DURATION_SECONDS = 3600;
|
|
6333
|
+
var PHONE_SERVER_MAX_COST_PER_MISSION = 5;
|
|
6334
|
+
var PHONE_SERVER_MAX_ATTEMPTS = 3;
|
|
6335
|
+
var PHONE_TASK_MAX_LENGTH = 2e3;
|
|
6336
|
+
var EU_DIAL_PREFIXES = [
|
|
6337
|
+
"+30",
|
|
6338
|
+
"+31",
|
|
6339
|
+
"+32",
|
|
6340
|
+
"+33",
|
|
6341
|
+
"+34",
|
|
6342
|
+
"+351",
|
|
6343
|
+
"+352",
|
|
6344
|
+
"+353",
|
|
6345
|
+
"+354",
|
|
6346
|
+
"+356",
|
|
6347
|
+
"+357",
|
|
6348
|
+
"+358",
|
|
6349
|
+
"+359",
|
|
6350
|
+
"+36",
|
|
6351
|
+
"+370",
|
|
6352
|
+
"+371",
|
|
6353
|
+
"+372",
|
|
6354
|
+
"+385",
|
|
6355
|
+
"+386",
|
|
6356
|
+
"+39",
|
|
6357
|
+
"+40",
|
|
6358
|
+
"+420",
|
|
6359
|
+
"+421",
|
|
6360
|
+
"+43",
|
|
6361
|
+
"+45",
|
|
6362
|
+
"+46",
|
|
6363
|
+
"+48",
|
|
6364
|
+
"+49"
|
|
6365
|
+
];
|
|
6366
|
+
var PREMIUM_OR_SPECIAL_PREFIXES = [
|
|
6367
|
+
"+1900",
|
|
6368
|
+
"+1976",
|
|
6369
|
+
"+43810",
|
|
6370
|
+
"+43820",
|
|
6371
|
+
"+43821",
|
|
6372
|
+
"+43828",
|
|
6373
|
+
"+43900",
|
|
6374
|
+
"+43901",
|
|
6375
|
+
"+43930",
|
|
6376
|
+
"+43931",
|
|
6377
|
+
"+49190",
|
|
6378
|
+
"+49900"
|
|
6379
|
+
];
|
|
6380
|
+
function issue(code, field, message) {
|
|
6381
|
+
return { code, field, message };
|
|
6382
|
+
}
|
|
6383
|
+
function isRecord(value) {
|
|
6384
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
6385
|
+
}
|
|
6386
|
+
function isPhoneRegionScope(value) {
|
|
6387
|
+
return typeof value === "string" && PHONE_REGION_SCOPES.includes(value);
|
|
6388
|
+
}
|
|
6389
|
+
function isTelephonyTransportCapability(value) {
|
|
6390
|
+
return typeof value === "string" && TELEPHONY_TRANSPORT_CAPABILITIES.includes(value);
|
|
6391
|
+
}
|
|
6392
|
+
function readPositiveInteger(value) {
|
|
6393
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
|
|
6394
|
+
}
|
|
6395
|
+
function readNonNegativeNumber(value) {
|
|
6396
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
|
|
6397
|
+
}
|
|
6398
|
+
function readBoolean(value) {
|
|
6399
|
+
return typeof value === "boolean" ? value : null;
|
|
6400
|
+
}
|
|
6401
|
+
function readRegionList(value) {
|
|
6402
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
6403
|
+
const regions = value.filter(isPhoneRegionScope);
|
|
6404
|
+
if (regions.length !== value.length) return null;
|
|
6405
|
+
return Array.from(new Set(regions));
|
|
6406
|
+
}
|
|
6407
|
+
function readCapabilityList(value) {
|
|
6408
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
6409
|
+
const capabilities = value.filter(isTelephonyTransportCapability);
|
|
6410
|
+
if (capabilities.length !== value.length) return null;
|
|
6411
|
+
return Array.from(new Set(capabilities));
|
|
6412
|
+
}
|
|
6413
|
+
function validateConfirmPolicy(value) {
|
|
6414
|
+
const issues = [];
|
|
6415
|
+
if (!isRecord(value)) {
|
|
6416
|
+
return [issue("confirm-policy-required", "policy.confirmPolicy", "confirmPolicy is required")];
|
|
6417
|
+
}
|
|
6418
|
+
const required = {
|
|
6419
|
+
paymentDetails: "never",
|
|
6420
|
+
contractCommitment: "never",
|
|
6421
|
+
costOverLimit: "needs_operator",
|
|
6422
|
+
sensitivePersonalData: "needs_operator",
|
|
6423
|
+
unclearAlternative: "needs_operator"
|
|
6424
|
+
};
|
|
6425
|
+
for (const [field, expected] of Object.entries(required)) {
|
|
6426
|
+
if (value[field] !== expected) {
|
|
6427
|
+
issues.push(issue(
|
|
6428
|
+
"unsafe-confirm-policy",
|
|
6429
|
+
`policy.confirmPolicy.${field}`,
|
|
6430
|
+
`${field} must be ${expected}`
|
|
6431
|
+
));
|
|
6432
|
+
}
|
|
6433
|
+
}
|
|
6434
|
+
return issues;
|
|
6435
|
+
}
|
|
6436
|
+
function validateAlternativePolicy(value) {
|
|
6437
|
+
if (!isRecord(value)) {
|
|
6438
|
+
return [issue("alternative-policy-required", "policy.alternativePolicy", "alternativePolicy is required")];
|
|
6439
|
+
}
|
|
6440
|
+
const maxTimeShiftMinutes = readNonNegativeNumber(value.maxTimeShiftMinutes);
|
|
6441
|
+
if (maxTimeShiftMinutes === null || !Number.isInteger(maxTimeShiftMinutes)) {
|
|
6442
|
+
return [issue(
|
|
6443
|
+
"invalid-alternative-policy",
|
|
6444
|
+
"policy.alternativePolicy.maxTimeShiftMinutes",
|
|
6445
|
+
"maxTimeShiftMinutes must be a non-negative integer"
|
|
6446
|
+
)];
|
|
6447
|
+
}
|
|
6448
|
+
return [];
|
|
6449
|
+
}
|
|
6450
|
+
function validatePhoneMissionPolicy(policy) {
|
|
6451
|
+
const issues = [];
|
|
6452
|
+
if (!isRecord(policy)) {
|
|
6453
|
+
return { ok: false, issues: [issue("policy-required", "policy", "policy is required")] };
|
|
6454
|
+
}
|
|
6455
|
+
if (policy.policyVersion !== 1) {
|
|
6456
|
+
issues.push(issue("unsupported-policy-version", "policy.policyVersion", "policyVersion must be 1"));
|
|
6457
|
+
}
|
|
6458
|
+
const regionAllowlist = readRegionList(policy.regionAllowlist);
|
|
6459
|
+
if (!regionAllowlist) {
|
|
6460
|
+
issues.push(issue("invalid-region-allowlist", "policy.regionAllowlist", "regionAllowlist must contain at least one supported region"));
|
|
6461
|
+
}
|
|
6462
|
+
const maxCallDurationSeconds = readPositiveInteger(policy.maxCallDurationSeconds);
|
|
6463
|
+
if (maxCallDurationSeconds === null) {
|
|
6464
|
+
issues.push(issue("invalid-max-duration", "policy.maxCallDurationSeconds", "maxCallDurationSeconds must be a positive integer"));
|
|
6465
|
+
}
|
|
6466
|
+
const maxCostPerMission = readNonNegativeNumber(policy.maxCostPerMission);
|
|
6467
|
+
if (maxCostPerMission === null) {
|
|
6468
|
+
issues.push(issue("invalid-max-cost", "policy.maxCostPerMission", "maxCostPerMission must be a non-negative number"));
|
|
6469
|
+
}
|
|
6470
|
+
const maxAttempts = readPositiveInteger(policy.maxAttempts);
|
|
6471
|
+
if (maxAttempts === null) {
|
|
6472
|
+
issues.push(issue("invalid-max-attempts", "policy.maxAttempts", "maxAttempts must be a positive integer"));
|
|
6473
|
+
}
|
|
6474
|
+
const transcriptEnabled = readBoolean(policy.transcriptEnabled);
|
|
6475
|
+
if (transcriptEnabled === null) {
|
|
6476
|
+
issues.push(issue("invalid-transcript-enabled", "policy.transcriptEnabled", "transcriptEnabled must be boolean"));
|
|
6477
|
+
}
|
|
6478
|
+
const recordingEnabled = readBoolean(policy.recordingEnabled);
|
|
6479
|
+
if (recordingEnabled === null) {
|
|
6480
|
+
issues.push(issue("invalid-recording-enabled", "policy.recordingEnabled", "recordingEnabled must be boolean"));
|
|
6481
|
+
}
|
|
6482
|
+
issues.push(...validateConfirmPolicy(policy.confirmPolicy));
|
|
6483
|
+
issues.push(...validateAlternativePolicy(policy.alternativePolicy));
|
|
6484
|
+
if (issues.length > 0) return { ok: false, issues };
|
|
6485
|
+
return {
|
|
6486
|
+
ok: true,
|
|
6487
|
+
policy: {
|
|
6488
|
+
policyVersion: 1,
|
|
6489
|
+
regionAllowlist,
|
|
6490
|
+
maxCallDurationSeconds: Math.min(maxCallDurationSeconds, PHONE_SERVER_MAX_CALL_DURATION_SECONDS),
|
|
6491
|
+
maxCostPerMission: Math.min(maxCostPerMission, PHONE_SERVER_MAX_COST_PER_MISSION),
|
|
6492
|
+
maxAttempts: Math.min(maxAttempts, PHONE_SERVER_MAX_ATTEMPTS),
|
|
6493
|
+
transcriptEnabled,
|
|
6494
|
+
recordingEnabled,
|
|
6495
|
+
confirmPolicy: policy.confirmPolicy,
|
|
6496
|
+
alternativePolicy: {
|
|
6497
|
+
maxTimeShiftMinutes: policy.alternativePolicy.maxTimeShiftMinutes
|
|
6498
|
+
}
|
|
6499
|
+
},
|
|
6500
|
+
issues: []
|
|
6501
|
+
};
|
|
6502
|
+
}
|
|
6503
|
+
function validatePhoneTransportProfile(transport) {
|
|
6504
|
+
const issues = [];
|
|
6505
|
+
if (!isRecord(transport)) {
|
|
6506
|
+
return { ok: false, issues: [issue("transport-required", "transport", "transport profile is required")] };
|
|
6507
|
+
}
|
|
6508
|
+
const provider = typeof transport.provider === "string" ? transport.provider.trim() : "";
|
|
6509
|
+
if (!provider) {
|
|
6510
|
+
issues.push(issue("invalid-provider", "transport.provider", "provider is required"));
|
|
6511
|
+
}
|
|
6512
|
+
const phoneNumber = typeof transport.phoneNumber === "string" ? normalizePhoneNumber(transport.phoneNumber) : null;
|
|
6513
|
+
if (!phoneNumber) {
|
|
6514
|
+
issues.push(issue("invalid-transport-number", "transport.phoneNumber", "transport phoneNumber must be valid E.164"));
|
|
6515
|
+
}
|
|
6516
|
+
const capabilities = readCapabilityList(transport.capabilities);
|
|
6517
|
+
if (!capabilities) {
|
|
6518
|
+
issues.push(issue("invalid-capabilities", "transport.capabilities", "capabilities must contain supported transport capabilities"));
|
|
6519
|
+
} else if (!capabilities.includes("call_control")) {
|
|
6520
|
+
issues.push(issue("missing-call-control", "transport.capabilities", "transport must support call_control to start phone missions"));
|
|
6521
|
+
}
|
|
6522
|
+
const supportedRegions = readRegionList(transport.supportedRegions);
|
|
6523
|
+
if (!supportedRegions) {
|
|
6524
|
+
issues.push(issue("invalid-supported-regions", "transport.supportedRegions", "supportedRegions must contain at least one supported region"));
|
|
6525
|
+
}
|
|
6526
|
+
if (issues.length > 0) return { ok: false, issues };
|
|
6527
|
+
return {
|
|
6528
|
+
ok: true,
|
|
6529
|
+
transport: {
|
|
6530
|
+
provider,
|
|
6531
|
+
phoneNumber,
|
|
6532
|
+
capabilities,
|
|
6533
|
+
supportedRegions
|
|
6534
|
+
},
|
|
6535
|
+
issues: []
|
|
6536
|
+
};
|
|
6537
|
+
}
|
|
6538
|
+
function inferPhoneRegion(phoneNumber) {
|
|
6539
|
+
const normalized = normalizePhoneNumber(phoneNumber);
|
|
6540
|
+
if (!normalized) return null;
|
|
6541
|
+
if (normalized.startsWith("+43")) return "AT";
|
|
6542
|
+
if (normalized.startsWith("+49")) return "DE";
|
|
6543
|
+
if (EU_DIAL_PREFIXES.some((prefix) => normalized.startsWith(prefix))) return "EU";
|
|
6544
|
+
return "WORLD";
|
|
6545
|
+
}
|
|
6546
|
+
function isPhoneRegionAllowed(region, allowlist) {
|
|
6547
|
+
if (allowlist.includes("WORLD")) return true;
|
|
6548
|
+
if (allowlist.includes(region)) return true;
|
|
6549
|
+
if ((region === "AT" || region === "DE" || region === "EU") && allowlist.includes("EU")) return true;
|
|
6550
|
+
return false;
|
|
6551
|
+
}
|
|
6552
|
+
function classifyPhoneNumberRisk(phoneNumber) {
|
|
6553
|
+
const normalized = normalizePhoneNumber(phoneNumber);
|
|
6554
|
+
if (!normalized) return "invalid";
|
|
6555
|
+
if (PREMIUM_OR_SPECIAL_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {
|
|
6556
|
+
return "premium_or_special";
|
|
6557
|
+
}
|
|
6558
|
+
return "standard";
|
|
6559
|
+
}
|
|
6560
|
+
function validatePhoneMissionStart(input, transport, options = {}) {
|
|
6561
|
+
const issues = [];
|
|
6562
|
+
if (!isRecord(input)) {
|
|
6563
|
+
return { ok: false, issues: [issue("start-input-required", "input", "start input is required")] };
|
|
6564
|
+
}
|
|
6565
|
+
const to = typeof input.to === "string" ? normalizePhoneNumber(input.to) : null;
|
|
6566
|
+
if (!to) {
|
|
6567
|
+
issues.push(issue("invalid-target-number", "input.to", "target number must be valid E.164"));
|
|
6568
|
+
}
|
|
6569
|
+
const rawTask = typeof input.task === "string" ? input.task : "";
|
|
6570
|
+
const task = rawTask.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
|
|
6571
|
+
if (!task) {
|
|
6572
|
+
issues.push(issue("task-required", "input.task", "task is required"));
|
|
6573
|
+
} else if (task.length > PHONE_TASK_MAX_LENGTH) {
|
|
6574
|
+
issues.push(issue("task-too-long", "input.task", `task must be ${PHONE_TASK_MAX_LENGTH} characters or fewer`));
|
|
6575
|
+
}
|
|
6576
|
+
const policyResult = validatePhoneMissionPolicy(input.policy);
|
|
6577
|
+
if (!policyResult.ok) issues.push(...policyResult.issues);
|
|
6578
|
+
const transportResult = validatePhoneTransportProfile(transport);
|
|
6579
|
+
if (!transportResult.ok) issues.push(...transportResult.issues);
|
|
6580
|
+
const risk = typeof input.to === "string" ? classifyPhoneNumberRisk(input.to) : "invalid";
|
|
6581
|
+
if (risk === "premium_or_special" && !options.allowPremiumOrSpecialNumbers) {
|
|
6582
|
+
issues.push(issue("premium-number-blocked", "input.to", "premium or special-rate numbers require an explicit allowlist"));
|
|
6583
|
+
}
|
|
6584
|
+
const targetRegion = to ? inferPhoneRegion(to) : null;
|
|
6585
|
+
if (!targetRegion) {
|
|
6586
|
+
issues.push(issue("unknown-target-region", "input.to", "target region could not be inferred"));
|
|
6587
|
+
}
|
|
6588
|
+
if (policyResult.ok && targetRegion && !isPhoneRegionAllowed(targetRegion, policyResult.policy.regionAllowlist)) {
|
|
6589
|
+
issues.push(issue("region-not-allowed", "input.to", "target number is outside the mission policy regionAllowlist"));
|
|
6590
|
+
}
|
|
6591
|
+
if (transportResult.ok && targetRegion && !isPhoneRegionAllowed(targetRegion, transportResult.transport.supportedRegions)) {
|
|
6592
|
+
issues.push(issue("transport-region-unsupported", "transport.supportedRegions", "target number is outside the transport supportedRegions"));
|
|
6593
|
+
}
|
|
6594
|
+
const capabilities = transportResult.ok ? transportResult.transport.capabilities : [];
|
|
6595
|
+
if (policyResult.ok && policyResult.policy.recordingEnabled && !capabilities.includes("recording_supported")) {
|
|
6596
|
+
issues.push(issue("recording-unsupported", "policy.recordingEnabled", "recordingEnabled requires transport recording_supported capability"));
|
|
6597
|
+
}
|
|
6598
|
+
if (issues.length > 0 || !policyResult.ok || !transportResult.ok || !to || !targetRegion) {
|
|
6599
|
+
return { ok: false, issues };
|
|
6600
|
+
}
|
|
6601
|
+
return {
|
|
6602
|
+
ok: true,
|
|
6603
|
+
mission: {
|
|
6604
|
+
to,
|
|
6605
|
+
task,
|
|
6606
|
+
policy: policyResult.policy,
|
|
6607
|
+
targetRegion,
|
|
6608
|
+
transport: transportResult.transport,
|
|
6609
|
+
voiceRuntimeRef: typeof input.voiceRuntimeRef === "string" && input.voiceRuntimeRef.trim() ? input.voiceRuntimeRef.trim() : void 0
|
|
6610
|
+
},
|
|
6611
|
+
issues: []
|
|
6612
|
+
};
|
|
6613
|
+
}
|
|
6614
|
+
|
|
6615
|
+
// src/phone/manager.ts
|
|
6616
|
+
var PHONE_RATE_LIMIT_PER_MINUTE = 5;
|
|
6617
|
+
var PHONE_RATE_LIMIT_PER_HOUR = 30;
|
|
6618
|
+
var PHONE_MAX_CONCURRENT_MISSIONS = 3;
|
|
6619
|
+
var PHONE_MIN_WEBHOOK_SECRET_LENGTH = 24;
|
|
6620
|
+
var TERMINAL_MISSION_STATES = ["completed", "failed", "cancelled"];
|
|
6621
|
+
var PhoneWebhookAuthError = class extends Error {
|
|
6622
|
+
isPhoneWebhookAuthError = true;
|
|
6623
|
+
constructor() {
|
|
6624
|
+
super("Invalid phone webhook request");
|
|
6625
|
+
this.name = "PhoneWebhookAuthError";
|
|
6626
|
+
}
|
|
6627
|
+
};
|
|
6628
|
+
var PhoneRateLimitError = class extends Error {
|
|
6629
|
+
isPhoneRateLimitError = true;
|
|
6630
|
+
constructor(message) {
|
|
6631
|
+
super(message);
|
|
6632
|
+
this.name = "PhoneRateLimitError";
|
|
6633
|
+
}
|
|
6634
|
+
};
|
|
6635
|
+
var PHONE_SECRET_FIELDS = ["password", "webhookSecret"];
|
|
6636
|
+
var MAX_PHONE_WEBHOOK_EVENT_KEYS = 50;
|
|
6637
|
+
function asString3(value) {
|
|
6638
|
+
return typeof value === "string" ? value.trim() : "";
|
|
6639
|
+
}
|
|
6640
|
+
function asRecord2(value) {
|
|
6641
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
6642
|
+
}
|
|
6643
|
+
function defaultApiUrl2(config) {
|
|
6644
|
+
const url = (config.apiUrl || "https://api.46elks.com/a1").replace(/\/+$/, "");
|
|
6645
|
+
if (!/^https:\/\//i.test(url)) {
|
|
6646
|
+
throw new Error("46elks apiUrl must use https:// \u2014 refusing to send credentials over a non-TLS connection");
|
|
6647
|
+
}
|
|
6648
|
+
return url;
|
|
6649
|
+
}
|
|
6650
|
+
function basicAuth2(username, password) {
|
|
6651
|
+
return Buffer.from(`${username}:${password}`, "utf8").toString("base64");
|
|
6652
|
+
}
|
|
6653
|
+
function secretMatches(provided, expected) {
|
|
6654
|
+
const a = Buffer.from(provided);
|
|
6655
|
+
const b = Buffer.from(expected);
|
|
6656
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
6657
|
+
}
|
|
6658
|
+
function apiBaseUrl(webhookBaseUrl) {
|
|
6659
|
+
const root = webhookBaseUrl.replace(/\/+$/, "");
|
|
6660
|
+
return root.endsWith("/api/agenticmail") ? root : `${root}/api/agenticmail`;
|
|
6661
|
+
}
|
|
6662
|
+
function webhookToken(webhookSecret, missionId) {
|
|
6663
|
+
return createHmac("sha256", webhookSecret).update(missionId).digest("hex");
|
|
6664
|
+
}
|
|
6665
|
+
function buildWebhookUrl(config, path2, missionId) {
|
|
6666
|
+
const url = new URL(`${apiBaseUrl(config.webhookBaseUrl)}${path2}`);
|
|
6667
|
+
url.searchParams.set("missionId", missionId);
|
|
6668
|
+
url.searchParams.set("token", webhookToken(config.webhookSecret, missionId));
|
|
6669
|
+
return url.toString();
|
|
6670
|
+
}
|
|
6671
|
+
function redactWebhookUrl(value) {
|
|
6672
|
+
try {
|
|
6673
|
+
const url = new URL(value);
|
|
6674
|
+
if (url.searchParams.has("token")) url.searchParams.set("token", "***");
|
|
6675
|
+
if (url.searchParams.has("secret")) url.searchParams.set("secret", "***");
|
|
6676
|
+
return url.toString();
|
|
6677
|
+
} catch {
|
|
6678
|
+
return "[redacted-url]";
|
|
6679
|
+
}
|
|
6680
|
+
}
|
|
6681
|
+
function redactProviderRequest(request) {
|
|
6682
|
+
return {
|
|
6683
|
+
url: request.url,
|
|
6684
|
+
body: {
|
|
6685
|
+
...request.body,
|
|
6686
|
+
voice_start: redactWebhookUrl(request.body.voice_start),
|
|
6687
|
+
whenhangup: redactWebhookUrl(request.body.whenhangup)
|
|
6688
|
+
}
|
|
6689
|
+
};
|
|
6690
|
+
}
|
|
6691
|
+
function stableFlatJson(value) {
|
|
6692
|
+
return JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))));
|
|
6693
|
+
}
|
|
6694
|
+
function phoneWebhookEventKey(kind, payload) {
|
|
6695
|
+
const callId = asString3(payload.callid) || asString3(payload.id) || asString3(payload.call_id);
|
|
6696
|
+
const result = asString3(payload.result) || asString3(payload.status) || asString3(payload.why);
|
|
6697
|
+
const fingerprint = createHash2("sha256").update(stableFlatJson(payload)).digest("hex").slice(0, 16);
|
|
6698
|
+
return [kind, callId || fingerprint, result].filter(Boolean).join(":");
|
|
6699
|
+
}
|
|
6700
|
+
function processedWebhookEventKeys(mission) {
|
|
6701
|
+
const value = mission.metadata.phoneWebhookEvents;
|
|
6702
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
6703
|
+
}
|
|
6704
|
+
function hasProcessedWebhookEvent(mission, eventKey) {
|
|
6705
|
+
return processedWebhookEventKeys(mission).includes(eventKey);
|
|
6706
|
+
}
|
|
6707
|
+
function appendProcessedWebhookEvent(mission, eventKey) {
|
|
6708
|
+
return [...processedWebhookEventKeys(mission), eventKey].slice(-MAX_PHONE_WEBHOOK_EVENT_KEYS);
|
|
6709
|
+
}
|
|
6710
|
+
function parseJson(value, fallback) {
|
|
6711
|
+
if (!value) return fallback;
|
|
6712
|
+
try {
|
|
6713
|
+
return JSON.parse(value);
|
|
6714
|
+
} catch {
|
|
6715
|
+
return fallback;
|
|
6716
|
+
}
|
|
6717
|
+
}
|
|
6718
|
+
function rowToMission(row) {
|
|
6719
|
+
return {
|
|
6720
|
+
id: row.id,
|
|
6721
|
+
agentId: row.agent_id,
|
|
6722
|
+
status: row.status,
|
|
6723
|
+
from: row.from_phone,
|
|
6724
|
+
to: row.to_phone,
|
|
6725
|
+
task: row.task,
|
|
6726
|
+
policy: parseJson(row.policy_json, {}),
|
|
6727
|
+
transport: parseJson(row.transport_json, {}),
|
|
6728
|
+
provider: row.provider,
|
|
6729
|
+
providerCallId: row.provider_call_id ?? void 0,
|
|
6730
|
+
transcript: parseJson(row.transcript_json, []),
|
|
6731
|
+
metadata: parseJson(row.metadata_json, {}),
|
|
6732
|
+
createdAt: row.created_at,
|
|
6733
|
+
updatedAt: row.updated_at
|
|
6734
|
+
};
|
|
6735
|
+
}
|
|
6736
|
+
function redactPhoneTransportConfig(config) {
|
|
6737
|
+
return {
|
|
6738
|
+
...config,
|
|
6739
|
+
password: config.password ? "***" : "",
|
|
6740
|
+
webhookSecret: config.webhookSecret ? "***" : ""
|
|
6741
|
+
};
|
|
6742
|
+
}
|
|
6743
|
+
var PhoneManager = class {
|
|
6744
|
+
constructor(db2, encryptionKey) {
|
|
6745
|
+
this.db = db2;
|
|
6746
|
+
this.encryptionKey = encryptionKey;
|
|
6747
|
+
this.ensureTables();
|
|
6748
|
+
}
|
|
6749
|
+
initialized = false;
|
|
6750
|
+
/** Per-agent outbound-call timestamps (ms) for the in-memory rate limiter. */
|
|
6751
|
+
callTimestamps = /* @__PURE__ */ new Map();
|
|
6752
|
+
/**
|
|
6753
|
+
* Abuse / cost gate for /calls/start (#43-H1). Each non-dry-run call is
|
|
6754
|
+
* a real billed outbound call, so before dialing we enforce:
|
|
6755
|
+
* - a hard cap on concurrently-active (non-terminal) missions, and
|
|
6756
|
+
* - a per-agent token-bucket rate limit (per-minute + per-hour).
|
|
6757
|
+
* Throws {@link PhoneRateLimitError} (-> HTTP 429) when a limit is hit.
|
|
6758
|
+
* Call only on the real path — dry runs place no call and are exempt.
|
|
6759
|
+
*/
|
|
6760
|
+
enforceCallLimits(agentId, nowMs) {
|
|
6761
|
+
const activeRow = this.db.prepare(
|
|
6762
|
+
`SELECT COUNT(*) AS cnt FROM phone_missions
|
|
6763
|
+
WHERE agent_id = ? AND status NOT IN ('completed', 'failed', 'cancelled')`
|
|
6764
|
+
).get(agentId);
|
|
6765
|
+
if ((activeRow?.cnt ?? 0) >= PHONE_MAX_CONCURRENT_MISSIONS) {
|
|
6766
|
+
throw new PhoneRateLimitError(
|
|
6767
|
+
`Too many active phone missions (max ${PHONE_MAX_CONCURRENT_MISSIONS}). Wait for an active call to end before starting another.`
|
|
6768
|
+
);
|
|
6769
|
+
}
|
|
6770
|
+
const recent = (this.callTimestamps.get(agentId) ?? []).filter((ts) => nowMs - ts < 36e5);
|
|
6771
|
+
const lastMinute = recent.filter((ts) => nowMs - ts < 6e4).length;
|
|
6772
|
+
if (lastMinute >= PHONE_RATE_LIMIT_PER_MINUTE) {
|
|
6773
|
+
throw new PhoneRateLimitError(
|
|
6774
|
+
`Phone call rate limit reached (max ${PHONE_RATE_LIMIT_PER_MINUTE}/minute). Try again shortly.`
|
|
6775
|
+
);
|
|
6776
|
+
}
|
|
6777
|
+
if (recent.length >= PHONE_RATE_LIMIT_PER_HOUR) {
|
|
6778
|
+
throw new PhoneRateLimitError(
|
|
6779
|
+
`Phone call rate limit reached (max ${PHONE_RATE_LIMIT_PER_HOUR}/hour). Try again later.`
|
|
6780
|
+
);
|
|
6781
|
+
}
|
|
6782
|
+
recent.push(nowMs);
|
|
6783
|
+
this.callTimestamps.set(agentId, recent);
|
|
6784
|
+
}
|
|
6785
|
+
encryptConfig(config) {
|
|
6786
|
+
if (!this.encryptionKey) return config;
|
|
6787
|
+
const out = { ...config };
|
|
6788
|
+
for (const field of PHONE_SECRET_FIELDS) {
|
|
6789
|
+
const value = out[field];
|
|
6790
|
+
if (typeof value === "string" && value && !isEncryptedSecret(value)) {
|
|
6791
|
+
out[field] = encryptSecret(value, this.encryptionKey);
|
|
6792
|
+
}
|
|
6793
|
+
}
|
|
6794
|
+
return out;
|
|
6795
|
+
}
|
|
6796
|
+
decryptConfig(config) {
|
|
6797
|
+
if (!this.encryptionKey) return config;
|
|
6798
|
+
const out = { ...config };
|
|
6799
|
+
for (const field of PHONE_SECRET_FIELDS) {
|
|
6800
|
+
const value = out[field];
|
|
6801
|
+
if (typeof value === "string" && isEncryptedSecret(value)) {
|
|
6802
|
+
try {
|
|
6803
|
+
out[field] = decryptSecret(value, this.encryptionKey);
|
|
6804
|
+
} catch {
|
|
6805
|
+
}
|
|
6806
|
+
}
|
|
6807
|
+
}
|
|
6808
|
+
return out;
|
|
6809
|
+
}
|
|
6810
|
+
ensureTables() {
|
|
6811
|
+
if (this.initialized) return;
|
|
6812
|
+
this.db.exec(`
|
|
6813
|
+
CREATE TABLE IF NOT EXISTS phone_missions (
|
|
6814
|
+
id TEXT PRIMARY KEY,
|
|
6815
|
+
agent_id TEXT NOT NULL,
|
|
6816
|
+
status TEXT NOT NULL,
|
|
6817
|
+
from_phone TEXT NOT NULL,
|
|
6818
|
+
to_phone TEXT NOT NULL,
|
|
6819
|
+
task TEXT NOT NULL,
|
|
6820
|
+
policy_json TEXT NOT NULL,
|
|
6821
|
+
transport_json TEXT NOT NULL,
|
|
6822
|
+
provider TEXT NOT NULL,
|
|
6823
|
+
provider_call_id TEXT,
|
|
6824
|
+
transcript_json TEXT NOT NULL DEFAULT '[]',
|
|
6825
|
+
metadata_json TEXT NOT NULL DEFAULT '{}',
|
|
6826
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
6827
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
6828
|
+
)
|
|
6829
|
+
`);
|
|
6830
|
+
try {
|
|
6831
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS idx_phone_missions_agent ON phone_missions(agent_id)");
|
|
6832
|
+
} catch {
|
|
6833
|
+
}
|
|
6834
|
+
try {
|
|
6835
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS idx_phone_missions_status ON phone_missions(status)");
|
|
6836
|
+
} catch {
|
|
6837
|
+
}
|
|
6838
|
+
this.initialized = true;
|
|
6839
|
+
}
|
|
6840
|
+
getPhoneTransportConfig(agentId) {
|
|
6841
|
+
const row = this.db.prepare("SELECT metadata FROM agents WHERE id = ?").get(agentId);
|
|
6842
|
+
if (!row) return null;
|
|
6843
|
+
const meta = parseJson(row.metadata, {});
|
|
6844
|
+
const config = meta.phoneTransport;
|
|
6845
|
+
if (!config || typeof config !== "object") return null;
|
|
6846
|
+
return this.decryptConfig(config);
|
|
6847
|
+
}
|
|
6848
|
+
savePhoneTransportConfig(agentId, config) {
|
|
6849
|
+
const row = this.db.prepare("SELECT metadata FROM agents WHERE id = ?").get(agentId);
|
|
6850
|
+
if (!row) throw new Error(`Agent ${agentId} not found`);
|
|
6851
|
+
const transportCheck = validatePhoneTransportProfile(config);
|
|
6852
|
+
if (!transportCheck.ok) {
|
|
6853
|
+
throw new Error(`Invalid phone transport config: ${transportCheck.issues.map((item) => `${item.field}: ${item.message}`).join("; ")}`);
|
|
6854
|
+
}
|
|
6855
|
+
const meta = parseJson(row.metadata, {});
|
|
6856
|
+
meta.phoneTransport = this.encryptConfig({
|
|
6857
|
+
...config,
|
|
6858
|
+
phoneNumber: transportCheck.transport.phoneNumber,
|
|
6859
|
+
capabilities: transportCheck.transport.capabilities,
|
|
6860
|
+
supportedRegions: transportCheck.transport.supportedRegions
|
|
6861
|
+
});
|
|
6862
|
+
this.db.prepare("UPDATE agents SET metadata = ?, updated_at = datetime('now') WHERE id = ?").run(JSON.stringify(meta), agentId);
|
|
6863
|
+
return config;
|
|
6864
|
+
}
|
|
6865
|
+
getMission(missionId, agentId) {
|
|
6866
|
+
const row = agentId ? this.db.prepare("SELECT * FROM phone_missions WHERE id = ? AND agent_id = ?").get(missionId, agentId) : this.db.prepare("SELECT * FROM phone_missions WHERE id = ?").get(missionId);
|
|
6867
|
+
return row ? rowToMission(row) : null;
|
|
6868
|
+
}
|
|
6869
|
+
listMissions(agentId, opts = {}) {
|
|
6870
|
+
const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
|
|
6871
|
+
const offset = Math.max(opts.offset ?? 0, 0);
|
|
6872
|
+
const params = [agentId];
|
|
6873
|
+
let sql = "SELECT * FROM phone_missions WHERE agent_id = ?";
|
|
6874
|
+
if (opts.status && PHONE_MISSION_STATES.includes(opts.status)) {
|
|
6875
|
+
sql += " AND status = ?";
|
|
6876
|
+
params.push(opts.status);
|
|
6877
|
+
}
|
|
6878
|
+
sql += " ORDER BY created_at DESC LIMIT ? OFFSET ?";
|
|
6879
|
+
params.push(limit, offset);
|
|
6880
|
+
return this.db.prepare(sql).all(...params).map(rowToMission);
|
|
6881
|
+
}
|
|
6882
|
+
async startMission(agentId, input, options = {}) {
|
|
6883
|
+
const config = this.getPhoneTransportConfig(agentId);
|
|
6884
|
+
if (!config) {
|
|
6885
|
+
throw new Error("Phone transport is not configured. Use phone_transport_setup first.");
|
|
6886
|
+
}
|
|
6887
|
+
if (config.provider !== "46elks") {
|
|
6888
|
+
throw new Error(`Phone provider ${config.provider} does not support call_control yet`);
|
|
6889
|
+
}
|
|
6890
|
+
const validation = validatePhoneMissionStart(input, config);
|
|
6891
|
+
if (!validation.ok) {
|
|
6892
|
+
throw new Error(`Invalid phone mission: ${validation.issues.map((item) => `${item.code} (${item.field})`).join(", ")}`);
|
|
6893
|
+
}
|
|
6894
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
6895
|
+
if (!options.dryRun) {
|
|
6896
|
+
this.enforceCallLimits(agentId, now.getTime());
|
|
6897
|
+
}
|
|
6898
|
+
const missionId = `call_${randomUUID()}`;
|
|
6899
|
+
const transcript = [{
|
|
6900
|
+
at: now.toISOString(),
|
|
6901
|
+
source: "system",
|
|
6902
|
+
text: "Phone mission created; outbound carrier call requested."
|
|
6903
|
+
}];
|
|
6904
|
+
const metadata = {
|
|
6905
|
+
voiceRuntimeRef: validation.mission.voiceRuntimeRef,
|
|
6906
|
+
targetRegion: validation.mission.targetRegion,
|
|
6907
|
+
dryRun: !!options.dryRun,
|
|
6908
|
+
// Attempt counter (#43-H2) — wired for breach detection; there is
|
|
6909
|
+
// no automatic retry loop today, so a fresh mission is attempt 1.
|
|
6910
|
+
attempts: 1
|
|
6911
|
+
};
|
|
6912
|
+
const mission = {
|
|
6913
|
+
id: missionId,
|
|
6914
|
+
agentId,
|
|
6915
|
+
status: "dialing",
|
|
6916
|
+
from: config.phoneNumber,
|
|
6917
|
+
to: validation.mission.to,
|
|
6918
|
+
task: validation.mission.task,
|
|
6919
|
+
policy: validation.mission.policy,
|
|
6920
|
+
transport: validation.mission.transport,
|
|
6921
|
+
provider: config.provider,
|
|
6922
|
+
transcript,
|
|
6923
|
+
metadata,
|
|
6924
|
+
createdAt: now.toISOString(),
|
|
6925
|
+
updatedAt: now.toISOString()
|
|
6926
|
+
};
|
|
6927
|
+
this.insertMission(mission);
|
|
6928
|
+
const providerRequest = this.build46ElksCallRequest(config, mission);
|
|
6929
|
+
if (options.dryRun) {
|
|
6930
|
+
const updated2 = this.updateProviderCall(missionId, "dryrun-call", {
|
|
6931
|
+
dryRun: true,
|
|
6932
|
+
providerRequest: redactProviderRequest(providerRequest)
|
|
6933
|
+
});
|
|
6934
|
+
return { mission: updated2, providerRequest };
|
|
6935
|
+
}
|
|
6936
|
+
const fetchFn = options.fetchFn ?? fetch;
|
|
6937
|
+
let response;
|
|
6938
|
+
try {
|
|
6939
|
+
response = await fetchFn(providerRequest.url, {
|
|
6940
|
+
method: "POST",
|
|
6941
|
+
headers: {
|
|
6942
|
+
"Authorization": `Basic ${basicAuth2(config.username, config.password)}`,
|
|
6943
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
6944
|
+
},
|
|
6945
|
+
body: new URLSearchParams(providerRequest.body),
|
|
6946
|
+
signal: AbortSignal.timeout(15e3)
|
|
6947
|
+
});
|
|
6948
|
+
} catch (err) {
|
|
6949
|
+
const message = err?.message ?? String(err);
|
|
6950
|
+
this.updateMissionStatus(missionId, "failed", {
|
|
6951
|
+
providerError: message
|
|
6952
|
+
}, [{
|
|
6953
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6954
|
+
source: "provider",
|
|
6955
|
+
text: "46elks call start failed \u2014 the provider request threw before any response.",
|
|
6956
|
+
metadata: { error: message }
|
|
6957
|
+
}]);
|
|
6958
|
+
throw err;
|
|
6959
|
+
}
|
|
6960
|
+
const text = await response.text();
|
|
6961
|
+
let raw = text;
|
|
6962
|
+
try {
|
|
6963
|
+
raw = JSON.parse(text);
|
|
6964
|
+
} catch {
|
|
6965
|
+
}
|
|
6966
|
+
if (!response.ok) {
|
|
6967
|
+
const failed = this.updateMissionStatus(missionId, "failed", {
|
|
6968
|
+
providerStatus: response.status,
|
|
6969
|
+
providerResponse: raw
|
|
6970
|
+
}, [{
|
|
6971
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6972
|
+
source: "provider",
|
|
6973
|
+
text: `46elks call start failed with HTTP ${response.status}.`,
|
|
6974
|
+
metadata: { providerResponse: raw }
|
|
6975
|
+
}]);
|
|
6976
|
+
throw new Error(`46elks call start failed (${response.status}) for mission ${failed.id}`);
|
|
6977
|
+
}
|
|
6978
|
+
const providerCallId = asRecord2(raw).id ? String(asRecord2(raw).id) : void 0;
|
|
6979
|
+
const updated = this.updateProviderCall(missionId, providerCallId, { providerResponse: raw });
|
|
6980
|
+
return { mission: updated, providerRequest, providerResponse: raw };
|
|
6981
|
+
}
|
|
6982
|
+
/**
|
|
6983
|
+
* Verify a webhook request and return the mission, or throw a uniform
|
|
6984
|
+
* {@link PhoneWebhookAuthError} for ANY failure (unknown mission, no
|
|
6985
|
+
* token, wrong token). Uniform on purpose — no 404-vs-403 oracle.
|
|
6986
|
+
*/
|
|
6987
|
+
authenticateWebhook(missionId, providedToken) {
|
|
6988
|
+
const mission = missionId ? this.getMission(missionId) : null;
|
|
6989
|
+
const config = mission ? this.getPhoneTransportConfig(mission.agentId) : null;
|
|
6990
|
+
if (!mission || !config || !providedToken || !secretMatches(providedToken, webhookToken(config.webhookSecret, mission.id))) {
|
|
6991
|
+
throw new PhoneWebhookAuthError();
|
|
6992
|
+
}
|
|
6993
|
+
return mission;
|
|
6994
|
+
}
|
|
6995
|
+
handleVoiceStartWebhook(missionId, providedToken, payload = {}) {
|
|
6996
|
+
const mission = this.authenticateWebhook(missionId, providedToken);
|
|
6997
|
+
if (TERMINAL_MISSION_STATES.includes(mission.status)) {
|
|
6998
|
+
return { mission, action: this.buildVoiceStartAction() };
|
|
6999
|
+
}
|
|
7000
|
+
const eventKey = phoneWebhookEventKey("voice_start", payload);
|
|
7001
|
+
if (hasProcessedWebhookEvent(mission, eventKey)) {
|
|
7002
|
+
return {
|
|
7003
|
+
mission,
|
|
7004
|
+
action: this.buildVoiceStartAction()
|
|
7005
|
+
};
|
|
7006
|
+
}
|
|
7007
|
+
const updated = this.updateMissionStatus(mission.id, "connected", {
|
|
7008
|
+
lastVoiceStartPayload: payload,
|
|
7009
|
+
phoneWebhookEvents: appendProcessedWebhookEvent(mission, eventKey)
|
|
7010
|
+
}, [{
|
|
7011
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7012
|
+
source: "provider",
|
|
7013
|
+
text: "46elks voice_start webhook received. Realtime voice runtime is not connected in this slice.",
|
|
7014
|
+
metadata: { payload }
|
|
7015
|
+
}]);
|
|
7016
|
+
return {
|
|
7017
|
+
mission: updated,
|
|
7018
|
+
action: this.buildVoiceStartAction()
|
|
7019
|
+
};
|
|
7020
|
+
}
|
|
7021
|
+
handleHangupWebhook(missionId, providedToken, payload = {}) {
|
|
7022
|
+
const mission = this.authenticateWebhook(missionId, providedToken);
|
|
7023
|
+
const eventKey = phoneWebhookEventKey("hangup", payload);
|
|
7024
|
+
if (hasProcessedWebhookEvent(mission, eventKey)) {
|
|
7025
|
+
return mission;
|
|
7026
|
+
}
|
|
7027
|
+
const costPatch = this.buildCostMetadataPatch(mission, payload);
|
|
7028
|
+
const nextStatus = TERMINAL_MISSION_STATES.includes(mission.status) ? mission.status : "failed";
|
|
7029
|
+
const transcript = [{
|
|
7030
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7031
|
+
source: "provider",
|
|
7032
|
+
text: nextStatus === "failed" ? "46elks hangup webhook received before a conversation runtime completed the mission." : "46elks hangup webhook received.",
|
|
7033
|
+
metadata: { payload }
|
|
7034
|
+
}];
|
|
7035
|
+
if (costPatch.costExceeded) {
|
|
7036
|
+
transcript.push({
|
|
7037
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7038
|
+
source: "system",
|
|
7039
|
+
text: `Mission cost ${costPatch.totalCost} exceeded the policy cap of ${mission.policy.maxCostPerMission}.`
|
|
7040
|
+
});
|
|
7041
|
+
}
|
|
7042
|
+
return this.updateMissionStatus(mission.id, nextStatus, {
|
|
7043
|
+
lastHangupPayload: payload,
|
|
7044
|
+
hangupReason: nextStatus === "failed" ? "call-ended-before-conversation-runtime" : void 0,
|
|
7045
|
+
phoneWebhookEvents: appendProcessedWebhookEvent(mission, eventKey),
|
|
7046
|
+
...costPatch
|
|
7047
|
+
}, transcript);
|
|
7048
|
+
}
|
|
7049
|
+
/**
|
|
7050
|
+
* Read the call cost off a 46elks hangup payload, add it to the
|
|
7051
|
+
* mission's running total, and flag a policy-cap breach (#43-H2).
|
|
7052
|
+
* Cost is only knowable post-call from the provider — the preventive
|
|
7053
|
+
* cost controls are the duration ceiling, rate limit, and concurrency
|
|
7054
|
+
* cap; this is the after-the-fact accounting + alerting.
|
|
7055
|
+
*/
|
|
7056
|
+
buildCostMetadataPatch(mission, payload) {
|
|
7057
|
+
const rawCost = payload.cost;
|
|
7058
|
+
const callCost = typeof rawCost === "number" && Number.isFinite(rawCost) && rawCost >= 0 ? rawCost : Number.parseFloat(asString3(rawCost)) || 0;
|
|
7059
|
+
const priorCost = typeof mission.metadata.totalCost === "number" ? mission.metadata.totalCost : 0;
|
|
7060
|
+
const totalCost = Math.round((priorCost + callCost) * 1e6) / 1e6;
|
|
7061
|
+
const cap = mission.policy?.maxCostPerMission;
|
|
7062
|
+
const costExceeded = typeof cap === "number" && totalCost > cap;
|
|
7063
|
+
return { totalCost, costExceeded };
|
|
7064
|
+
}
|
|
7065
|
+
buildVoiceStartAction() {
|
|
7066
|
+
return {
|
|
7067
|
+
play: "AgenticMail has received this call mission. The live voice runtime is not connected yet; the operator will follow up."
|
|
7068
|
+
};
|
|
7069
|
+
}
|
|
7070
|
+
cancelMission(agentId, missionId) {
|
|
7071
|
+
const mission = this.getMission(missionId, agentId);
|
|
7072
|
+
if (!mission) throw new Error("Phone mission not found");
|
|
7073
|
+
return this.updateMissionStatus(mission.id, "cancelled", {}, [{
|
|
7074
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7075
|
+
source: "operator",
|
|
7076
|
+
text: "Phone mission cancelled."
|
|
7077
|
+
}]);
|
|
7078
|
+
}
|
|
7079
|
+
build46ElksCallRequest(config, mission) {
|
|
7080
|
+
const timeout = Math.min(Math.max(mission.policy.maxCallDurationSeconds, 1), PHONE_SERVER_MAX_CALL_DURATION_SECONDS);
|
|
7081
|
+
return {
|
|
7082
|
+
url: `${defaultApiUrl2(config)}/calls`,
|
|
7083
|
+
body: {
|
|
7084
|
+
from: config.phoneNumber,
|
|
7085
|
+
to: mission.to,
|
|
7086
|
+
voice_start: buildWebhookUrl(config, "/calls/webhook/46elks/voice-start", mission.id),
|
|
7087
|
+
whenhangup: buildWebhookUrl(config, "/calls/webhook/46elks/hangup", mission.id),
|
|
7088
|
+
timeout: String(timeout)
|
|
7089
|
+
}
|
|
7090
|
+
};
|
|
7091
|
+
}
|
|
7092
|
+
insertMission(mission) {
|
|
7093
|
+
this.db.prepare(`
|
|
7094
|
+
INSERT INTO phone_missions (
|
|
7095
|
+
id, agent_id, status, from_phone, to_phone, task,
|
|
7096
|
+
policy_json, transport_json, provider, provider_call_id,
|
|
7097
|
+
transcript_json, metadata_json, created_at, updated_at
|
|
7098
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7099
|
+
`).run(
|
|
7100
|
+
mission.id,
|
|
7101
|
+
mission.agentId,
|
|
7102
|
+
mission.status,
|
|
7103
|
+
mission.from,
|
|
7104
|
+
mission.to,
|
|
7105
|
+
mission.task,
|
|
7106
|
+
JSON.stringify(mission.policy),
|
|
7107
|
+
JSON.stringify(mission.transport),
|
|
7108
|
+
mission.provider,
|
|
7109
|
+
mission.providerCallId ?? null,
|
|
7110
|
+
JSON.stringify(mission.transcript),
|
|
7111
|
+
JSON.stringify(mission.metadata),
|
|
7112
|
+
mission.createdAt,
|
|
7113
|
+
mission.updatedAt
|
|
7114
|
+
);
|
|
7115
|
+
}
|
|
7116
|
+
updateProviderCall(missionId, providerCallId, metadata) {
|
|
7117
|
+
const mission = this.getMission(missionId);
|
|
7118
|
+
if (!mission) throw new Error("Phone mission not found");
|
|
7119
|
+
const nextMetadata = { ...mission.metadata, ...metadata };
|
|
7120
|
+
this.db.prepare(`
|
|
7121
|
+
UPDATE phone_missions
|
|
7122
|
+
SET provider_call_id = ?, metadata_json = ?, updated_at = ?
|
|
7123
|
+
WHERE id = ?
|
|
7124
|
+
`).run(providerCallId ?? null, JSON.stringify(nextMetadata), (/* @__PURE__ */ new Date()).toISOString(), missionId);
|
|
7125
|
+
return this.getMission(missionId);
|
|
7126
|
+
}
|
|
7127
|
+
updateMissionStatus(missionId, status, metadata, transcriptEntries = []) {
|
|
7128
|
+
const mission = this.getMission(missionId);
|
|
7129
|
+
if (!mission) throw new Error("Phone mission not found");
|
|
7130
|
+
const nextTranscript = [...mission.transcript, ...transcriptEntries];
|
|
7131
|
+
const nextMetadata = Object.fromEntries(
|
|
7132
|
+
Object.entries({ ...mission.metadata, ...metadata }).filter(([, value]) => value !== void 0)
|
|
7133
|
+
);
|
|
7134
|
+
this.db.prepare(`
|
|
7135
|
+
UPDATE phone_missions
|
|
7136
|
+
SET status = ?, transcript_json = ?, metadata_json = ?, updated_at = ?
|
|
7137
|
+
WHERE id = ?
|
|
7138
|
+
`).run(status, JSON.stringify(nextTranscript), JSON.stringify(nextMetadata), (/* @__PURE__ */ new Date()).toISOString(), missionId);
|
|
7139
|
+
return this.getMission(missionId);
|
|
7140
|
+
}
|
|
7141
|
+
};
|
|
7142
|
+
function buildPhoneTransportConfig(input) {
|
|
7143
|
+
const provider = asString3(input.provider) || "46elks";
|
|
7144
|
+
if (provider !== "46elks") throw new Error('provider must be "46elks"');
|
|
7145
|
+
const phoneNumber = normalizePhoneNumber(asString3(input.phoneNumber));
|
|
7146
|
+
if (!phoneNumber) throw new Error("phoneNumber must be a valid E.164 phone number");
|
|
7147
|
+
const username = asString3(input.username);
|
|
7148
|
+
const password = asString3(input.password);
|
|
7149
|
+
const webhookBaseUrl = asString3(input.webhookBaseUrl);
|
|
7150
|
+
const webhookSecret = asString3(input.webhookSecret);
|
|
7151
|
+
if (!username || !password) throw new Error('username and password are required for provider "46elks"');
|
|
7152
|
+
if (!webhookBaseUrl) throw new Error("webhookBaseUrl is required");
|
|
7153
|
+
if (!webhookSecret) throw new Error("webhookSecret is required");
|
|
7154
|
+
if (webhookSecret.length < PHONE_MIN_WEBHOOK_SECRET_LENGTH) {
|
|
7155
|
+
throw new Error(`webhookSecret must be at least ${PHONE_MIN_WEBHOOK_SECRET_LENGTH} characters`);
|
|
7156
|
+
}
|
|
7157
|
+
const parsedWebhookBaseUrl = new URL(webhookBaseUrl);
|
|
7158
|
+
if (parsedWebhookBaseUrl.protocol !== "https:" && parsedWebhookBaseUrl.hostname !== "127.0.0.1" && parsedWebhookBaseUrl.hostname !== "localhost") {
|
|
7159
|
+
throw new Error("webhookBaseUrl must use https:// unless it points at localhost");
|
|
7160
|
+
}
|
|
7161
|
+
const apiUrl = asString3(input.apiUrl);
|
|
7162
|
+
if (apiUrl) {
|
|
7163
|
+
const parsedApiUrl = new URL(apiUrl);
|
|
7164
|
+
if (parsedApiUrl.protocol !== "https:") {
|
|
7165
|
+
throw new Error("apiUrl must use https:// \u2014 credentials are sent on every request");
|
|
7166
|
+
}
|
|
7167
|
+
}
|
|
7168
|
+
const capabilities = Array.isArray(input.capabilities) ? input.capabilities.filter((item) => typeof item === "string" && ["sms", "call_control", "realtime_media", "recording_supported"].includes(item)) : ["call_control"];
|
|
7169
|
+
const supportedRegions = Array.isArray(input.supportedRegions) ? input.supportedRegions.filter((item) => typeof item === "string" && ["AT", "DE", "EU", "WORLD"].includes(item)) : ["EU"];
|
|
7170
|
+
const config = {
|
|
7171
|
+
provider,
|
|
7172
|
+
phoneNumber,
|
|
7173
|
+
username,
|
|
7174
|
+
password,
|
|
7175
|
+
webhookBaseUrl,
|
|
7176
|
+
webhookSecret,
|
|
7177
|
+
apiUrl: apiUrl || void 0,
|
|
7178
|
+
capabilities: Array.from(/* @__PURE__ */ new Set(["call_control", ...capabilities])),
|
|
7179
|
+
supportedRegions: supportedRegions.length ? Array.from(new Set(supportedRegions)) : ["EU"],
|
|
7180
|
+
configuredAt: input.configuredAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
7181
|
+
};
|
|
7182
|
+
const validation = validatePhoneTransportProfile(config);
|
|
7183
|
+
if (!validation.ok) {
|
|
7184
|
+
throw new Error(`Invalid phone transport config: ${validation.issues.map((item) => `${item.field}: ${item.message}`).join("; ")}`);
|
|
7185
|
+
}
|
|
7186
|
+
return config;
|
|
7187
|
+
}
|
|
7188
|
+
|
|
6228
7189
|
// src/telemetry.ts
|
|
6229
|
-
import { randomUUID } from "crypto";
|
|
7190
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
6230
7191
|
import { readFileSync as readFileSync2, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, existsSync as existsSync3 } from "fs";
|
|
6231
7192
|
import { join as join5 } from "path";
|
|
6232
7193
|
import { homedir as homedir4 } from "os";
|
|
@@ -6257,12 +7218,12 @@ function getInstallId() {
|
|
|
6257
7218
|
return installId;
|
|
6258
7219
|
}
|
|
6259
7220
|
}
|
|
6260
|
-
installId =
|
|
7221
|
+
installId = randomUUID2();
|
|
6261
7222
|
if (!existsSync3(dir2)) mkdirSync3(dir2, { recursive: true });
|
|
6262
7223
|
writeFileSync3(idFile, installId, "utf8");
|
|
6263
7224
|
return installId;
|
|
6264
7225
|
} catch {
|
|
6265
|
-
installId =
|
|
7226
|
+
installId = randomUUID2();
|
|
6266
7227
|
return installId;
|
|
6267
7228
|
}
|
|
6268
7229
|
}
|
|
@@ -8039,7 +9000,7 @@ secret = "${password}"
|
|
|
8039
9000
|
};
|
|
8040
9001
|
|
|
8041
9002
|
// src/threading/thread-id.ts
|
|
8042
|
-
import { createHash as
|
|
9003
|
+
import { createHash as createHash3 } from "crypto";
|
|
8043
9004
|
function stripReplyPrefixes(subject) {
|
|
8044
9005
|
let s = subject.length > 1e3 ? subject.slice(0, 1e3) : subject;
|
|
8045
9006
|
for (; ; ) {
|
|
@@ -8068,7 +9029,7 @@ function normalizeAddress(addr) {
|
|
|
8068
9029
|
}
|
|
8069
9030
|
function threadIdFor(input) {
|
|
8070
9031
|
const subject = normalizeSubject(input.subject);
|
|
8071
|
-
return
|
|
9032
|
+
return createHash3("sha256").update(subject).digest("base64url").slice(0, 16);
|
|
8072
9033
|
}
|
|
8073
9034
|
|
|
8074
9035
|
// src/threading/thread-cache.ts
|
|
@@ -8344,12 +9305,26 @@ export {
|
|
|
8344
9305
|
DependencyInstaller,
|
|
8345
9306
|
DomainManager,
|
|
8346
9307
|
DomainPurchaser,
|
|
9308
|
+
ELKS_REALTIME_AUDIO_FORMATS,
|
|
8347
9309
|
EmailSearchIndex,
|
|
8348
9310
|
GatewayManager,
|
|
8349
9311
|
InboxWatcher,
|
|
8350
9312
|
MailReceiver,
|
|
8351
9313
|
MailSender,
|
|
9314
|
+
PHONE_MAX_CONCURRENT_MISSIONS,
|
|
9315
|
+
PHONE_MIN_WEBHOOK_SECRET_LENGTH,
|
|
9316
|
+
PHONE_MISSION_STATES,
|
|
9317
|
+
PHONE_RATE_LIMIT_PER_HOUR,
|
|
9318
|
+
PHONE_RATE_LIMIT_PER_MINUTE,
|
|
9319
|
+
PHONE_REGION_SCOPES,
|
|
9320
|
+
PHONE_SERVER_MAX_ATTEMPTS,
|
|
9321
|
+
PHONE_SERVER_MAX_CALL_DURATION_SECONDS,
|
|
9322
|
+
PHONE_SERVER_MAX_COST_PER_MISSION,
|
|
9323
|
+
PHONE_TASK_MAX_LENGTH,
|
|
8352
9324
|
PathTraversalError,
|
|
9325
|
+
PhoneManager,
|
|
9326
|
+
PhoneRateLimitError,
|
|
9327
|
+
PhoneWebhookAuthError,
|
|
8353
9328
|
REDACTED,
|
|
8354
9329
|
RELAY_PRESETS,
|
|
8355
9330
|
RelayBridge,
|
|
@@ -8360,6 +9335,7 @@ export {
|
|
|
8360
9335
|
SmsManager,
|
|
8361
9336
|
SmsPoller,
|
|
8362
9337
|
StalwartAdmin,
|
|
9338
|
+
TELEPHONY_TRANSPORT_CAPABILITIES,
|
|
8363
9339
|
ThreadCache,
|
|
8364
9340
|
TunnelManager,
|
|
8365
9341
|
UnsafeApiUrlError,
|
|
@@ -8368,8 +9344,16 @@ export {
|
|
|
8368
9344
|
bridgeWakeErrorMessage,
|
|
8369
9345
|
bridgeWakeLastSeenAgeMs,
|
|
8370
9346
|
buildApiUrl,
|
|
9347
|
+
buildElksAudioMessage,
|
|
9348
|
+
buildElksByeMessage,
|
|
9349
|
+
buildElksHandshakeMessages,
|
|
9350
|
+
buildElksInterruptMessage,
|
|
9351
|
+
buildElksListeningMessage,
|
|
9352
|
+
buildElksSendingMessage,
|
|
8371
9353
|
buildInboundSecurityAdvisory,
|
|
9354
|
+
buildPhoneTransportConfig,
|
|
8372
9355
|
classifyEmailRoute,
|
|
9356
|
+
classifyPhoneNumberRisk,
|
|
8373
9357
|
classifyResumeError,
|
|
8374
9358
|
closeDatabase,
|
|
8375
9359
|
composeBridgeWakePrompt,
|
|
@@ -8384,8 +9368,10 @@ export {
|
|
|
8384
9368
|
getOperatorEmail,
|
|
8385
9369
|
getSmsProvider,
|
|
8386
9370
|
hostSessionStoragePath,
|
|
9371
|
+
inferPhoneRegion,
|
|
8387
9372
|
isInternalEmail,
|
|
8388
9373
|
isLoopbackMailHost,
|
|
9374
|
+
isPhoneRegionAllowed,
|
|
8389
9375
|
isSessionFresh,
|
|
8390
9376
|
isValidPhoneNumber,
|
|
8391
9377
|
loadHostSession,
|
|
@@ -8394,11 +9380,13 @@ export {
|
|
|
8394
9380
|
normalizePhoneNumber,
|
|
8395
9381
|
normalizeSubject,
|
|
8396
9382
|
operatorPrefsStoragePath,
|
|
9383
|
+
parseElksRealtimeMessage,
|
|
8397
9384
|
parseEmail,
|
|
8398
9385
|
parseGoogleVoiceSms,
|
|
8399
9386
|
planBridgeWake,
|
|
8400
9387
|
recordToolCall,
|
|
8401
9388
|
redactObject,
|
|
9389
|
+
redactPhoneTransportConfig,
|
|
8402
9390
|
redactSecret,
|
|
8403
9391
|
redactSmsConfig,
|
|
8404
9392
|
resolveConfig,
|
|
@@ -8415,5 +9403,8 @@ export {
|
|
|
8415
9403
|
startRelayBridge,
|
|
8416
9404
|
threadIdFor,
|
|
8417
9405
|
tryJoin,
|
|
8418
|
-
validateApiUrl
|
|
9406
|
+
validateApiUrl,
|
|
9407
|
+
validatePhoneMissionPolicy,
|
|
9408
|
+
validatePhoneMissionStart,
|
|
9409
|
+
validatePhoneTransportProfile
|
|
8419
9410
|
};
|