@agenticmail/core 0.9.13 → 0.9.15

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.js CHANGED
@@ -1401,6 +1401,10 @@ var AccountManager = class {
1401
1401
  }
1402
1402
  const stmt = this.db.prepare("DELETE FROM agents WHERE id = ?");
1403
1403
  const result = stmt.run(id);
1404
+ try {
1405
+ this.db.prepare("DELETE FROM agent_memory WHERE agent_id = ?").run(id);
1406
+ } catch {
1407
+ }
1404
1408
  return result.changes > 0;
1405
1409
  }
1406
1410
  /**
@@ -6225,8 +6229,969 @@ var RELAY_PRESETS = {
6225
6229
  }
6226
6230
  };
6227
6231
 
6232
+ // src/phone/realtime.ts
6233
+ var ELKS_REALTIME_AUDIO_FORMATS = ["ulaw", "pcm_16000", "pcm_24000", "wav"];
6234
+ function asRecord(value) {
6235
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) ? value : {};
6236
+ }
6237
+ function asString2(value) {
6238
+ return typeof value === "string" ? value.trim() : "";
6239
+ }
6240
+ function isAudioFormat(value) {
6241
+ return typeof value === "string" && ELKS_REALTIME_AUDIO_FORMATS.includes(value);
6242
+ }
6243
+ function assertAudioFormat(format) {
6244
+ if (!isAudioFormat(format)) {
6245
+ throw new Error(`Unsupported 46elks realtime audio format: ${String(format)}`);
6246
+ }
6247
+ return format;
6248
+ }
6249
+ function looksLikeBase64(value) {
6250
+ return value.length > 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value) && value.length % 4 === 0;
6251
+ }
6252
+ function decodeJsonMessage(input) {
6253
+ if (typeof input === "string") {
6254
+ try {
6255
+ return asRecord(JSON.parse(input));
6256
+ } catch {
6257
+ throw new Error("Invalid 46elks realtime message: expected JSON object string");
6258
+ }
6259
+ }
6260
+ return asRecord(input);
6261
+ }
6262
+ function parseElksRealtimeMessage(input) {
6263
+ const msg = decodeJsonMessage(input);
6264
+ const type = asString2(msg.t);
6265
+ if (type === "hello") {
6266
+ const callid = asString2(msg.callid);
6267
+ const from = asString2(msg.from);
6268
+ const to = asString2(msg.to);
6269
+ if (!callid || !from || !to) {
6270
+ throw new Error("Invalid 46elks realtime hello: callid, from, and to are required");
6271
+ }
6272
+ return { ...msg, t: "hello", callid, from, to };
6273
+ }
6274
+ if (type === "audio") {
6275
+ const data = asString2(msg.data);
6276
+ if (!looksLikeBase64(data)) {
6277
+ throw new Error("Invalid 46elks realtime audio: data must be non-empty base64");
6278
+ }
6279
+ return { t: "audio", data };
6280
+ }
6281
+ if (type === "bye") {
6282
+ const reason = asString2(msg.reason) || void 0;
6283
+ const message = asString2(msg.message) || void 0;
6284
+ return { ...msg, t: "bye", reason, message };
6285
+ }
6286
+ throw new Error(`Unsupported 46elks realtime message type: ${type || "(missing)"}`);
6287
+ }
6288
+ function buildElksListeningMessage(format = "pcm_24000") {
6289
+ return { t: "listening", format: assertAudioFormat(format) };
6290
+ }
6291
+ function buildElksSendingMessage(format = "pcm_24000") {
6292
+ return { t: "sending", format: assertAudioFormat(format) };
6293
+ }
6294
+ function buildElksAudioMessage(data) {
6295
+ const encoded = typeof data === "string" ? data : Buffer.from(data).toString("base64");
6296
+ if (!looksLikeBase64(encoded)) {
6297
+ throw new Error("46elks realtime audio data must be base64 or bytes");
6298
+ }
6299
+ return { t: "audio", data: encoded };
6300
+ }
6301
+ function buildElksInterruptMessage() {
6302
+ return { t: "interrupt" };
6303
+ }
6304
+ function buildElksByeMessage() {
6305
+ return { t: "bye" };
6306
+ }
6307
+ function buildElksHandshakeMessages(options = {}) {
6308
+ return [
6309
+ buildElksListeningMessage(options.listenFormat ?? "pcm_24000"),
6310
+ buildElksSendingMessage(options.sendFormat ?? "pcm_24000")
6311
+ ];
6312
+ }
6313
+
6314
+ // src/phone/manager.ts
6315
+ import { createHash as createHash2, createHmac, randomUUID, timingSafeEqual } from "crypto";
6316
+
6317
+ // src/phone/mission.ts
6318
+ var PHONE_REGION_SCOPES = ["AT", "DE", "EU", "WORLD"];
6319
+ var TELEPHONY_TRANSPORT_CAPABILITIES = [
6320
+ "sms",
6321
+ "call_control",
6322
+ "realtime_media",
6323
+ "recording_supported"
6324
+ ];
6325
+ var PHONE_MISSION_STATES = [
6326
+ "draft",
6327
+ "approved",
6328
+ "dialing",
6329
+ "connected",
6330
+ "conversing",
6331
+ "needs_operator",
6332
+ "completed",
6333
+ "failed",
6334
+ "cancelled"
6335
+ ];
6336
+ var PHONE_SERVER_MAX_CALL_DURATION_SECONDS = 3600;
6337
+ var PHONE_SERVER_MAX_COST_PER_MISSION = 5;
6338
+ var PHONE_SERVER_MAX_ATTEMPTS = 3;
6339
+ var PHONE_TASK_MAX_LENGTH = 2e3;
6340
+ var EU_DIAL_PREFIXES = [
6341
+ "+30",
6342
+ "+31",
6343
+ "+32",
6344
+ "+33",
6345
+ "+34",
6346
+ "+351",
6347
+ "+352",
6348
+ "+353",
6349
+ "+354",
6350
+ "+356",
6351
+ "+357",
6352
+ "+358",
6353
+ "+359",
6354
+ "+36",
6355
+ "+370",
6356
+ "+371",
6357
+ "+372",
6358
+ "+385",
6359
+ "+386",
6360
+ "+39",
6361
+ "+40",
6362
+ "+420",
6363
+ "+421",
6364
+ "+43",
6365
+ "+45",
6366
+ "+46",
6367
+ "+48",
6368
+ "+49"
6369
+ ];
6370
+ var PREMIUM_OR_SPECIAL_PREFIXES = [
6371
+ "+1900",
6372
+ "+1976",
6373
+ "+43810",
6374
+ "+43820",
6375
+ "+43821",
6376
+ "+43828",
6377
+ "+43900",
6378
+ "+43901",
6379
+ "+43930",
6380
+ "+43931",
6381
+ "+49190",
6382
+ "+49900"
6383
+ ];
6384
+ function issue(code, field, message) {
6385
+ return { code, field, message };
6386
+ }
6387
+ function isRecord(value) {
6388
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6389
+ }
6390
+ function isPhoneRegionScope(value) {
6391
+ return typeof value === "string" && PHONE_REGION_SCOPES.includes(value);
6392
+ }
6393
+ function isTelephonyTransportCapability(value) {
6394
+ return typeof value === "string" && TELEPHONY_TRANSPORT_CAPABILITIES.includes(value);
6395
+ }
6396
+ function readPositiveInteger(value) {
6397
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
6398
+ }
6399
+ function readNonNegativeNumber(value) {
6400
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
6401
+ }
6402
+ function readBoolean(value) {
6403
+ return typeof value === "boolean" ? value : null;
6404
+ }
6405
+ function readRegionList(value) {
6406
+ if (!Array.isArray(value) || value.length === 0) return null;
6407
+ const regions = value.filter(isPhoneRegionScope);
6408
+ if (regions.length !== value.length) return null;
6409
+ return Array.from(new Set(regions));
6410
+ }
6411
+ function readCapabilityList(value) {
6412
+ if (!Array.isArray(value) || value.length === 0) return null;
6413
+ const capabilities = value.filter(isTelephonyTransportCapability);
6414
+ if (capabilities.length !== value.length) return null;
6415
+ return Array.from(new Set(capabilities));
6416
+ }
6417
+ function validateConfirmPolicy(value) {
6418
+ const issues = [];
6419
+ if (!isRecord(value)) {
6420
+ return [issue("confirm-policy-required", "policy.confirmPolicy", "confirmPolicy is required")];
6421
+ }
6422
+ const required = {
6423
+ paymentDetails: "never",
6424
+ contractCommitment: "never",
6425
+ costOverLimit: "needs_operator",
6426
+ sensitivePersonalData: "needs_operator",
6427
+ unclearAlternative: "needs_operator"
6428
+ };
6429
+ for (const [field, expected] of Object.entries(required)) {
6430
+ if (value[field] !== expected) {
6431
+ issues.push(issue(
6432
+ "unsafe-confirm-policy",
6433
+ `policy.confirmPolicy.${field}`,
6434
+ `${field} must be ${expected}`
6435
+ ));
6436
+ }
6437
+ }
6438
+ return issues;
6439
+ }
6440
+ function validateAlternativePolicy(value) {
6441
+ if (!isRecord(value)) {
6442
+ return [issue("alternative-policy-required", "policy.alternativePolicy", "alternativePolicy is required")];
6443
+ }
6444
+ const maxTimeShiftMinutes = readNonNegativeNumber(value.maxTimeShiftMinutes);
6445
+ if (maxTimeShiftMinutes === null || !Number.isInteger(maxTimeShiftMinutes)) {
6446
+ return [issue(
6447
+ "invalid-alternative-policy",
6448
+ "policy.alternativePolicy.maxTimeShiftMinutes",
6449
+ "maxTimeShiftMinutes must be a non-negative integer"
6450
+ )];
6451
+ }
6452
+ return [];
6453
+ }
6454
+ function validatePhoneMissionPolicy(policy) {
6455
+ const issues = [];
6456
+ if (!isRecord(policy)) {
6457
+ return { ok: false, issues: [issue("policy-required", "policy", "policy is required")] };
6458
+ }
6459
+ if (policy.policyVersion !== 1) {
6460
+ issues.push(issue("unsupported-policy-version", "policy.policyVersion", "policyVersion must be 1"));
6461
+ }
6462
+ const regionAllowlist = readRegionList(policy.regionAllowlist);
6463
+ if (!regionAllowlist) {
6464
+ issues.push(issue("invalid-region-allowlist", "policy.regionAllowlist", "regionAllowlist must contain at least one supported region"));
6465
+ }
6466
+ const maxCallDurationSeconds = readPositiveInteger(policy.maxCallDurationSeconds);
6467
+ if (maxCallDurationSeconds === null) {
6468
+ issues.push(issue("invalid-max-duration", "policy.maxCallDurationSeconds", "maxCallDurationSeconds must be a positive integer"));
6469
+ }
6470
+ const maxCostPerMission = readNonNegativeNumber(policy.maxCostPerMission);
6471
+ if (maxCostPerMission === null) {
6472
+ issues.push(issue("invalid-max-cost", "policy.maxCostPerMission", "maxCostPerMission must be a non-negative number"));
6473
+ }
6474
+ const maxAttempts = readPositiveInteger(policy.maxAttempts);
6475
+ if (maxAttempts === null) {
6476
+ issues.push(issue("invalid-max-attempts", "policy.maxAttempts", "maxAttempts must be a positive integer"));
6477
+ }
6478
+ const transcriptEnabled = readBoolean(policy.transcriptEnabled);
6479
+ if (transcriptEnabled === null) {
6480
+ issues.push(issue("invalid-transcript-enabled", "policy.transcriptEnabled", "transcriptEnabled must be boolean"));
6481
+ }
6482
+ const recordingEnabled = readBoolean(policy.recordingEnabled);
6483
+ if (recordingEnabled === null) {
6484
+ issues.push(issue("invalid-recording-enabled", "policy.recordingEnabled", "recordingEnabled must be boolean"));
6485
+ }
6486
+ issues.push(...validateConfirmPolicy(policy.confirmPolicy));
6487
+ issues.push(...validateAlternativePolicy(policy.alternativePolicy));
6488
+ if (issues.length > 0) return { ok: false, issues };
6489
+ return {
6490
+ ok: true,
6491
+ policy: {
6492
+ policyVersion: 1,
6493
+ regionAllowlist,
6494
+ maxCallDurationSeconds: Math.min(maxCallDurationSeconds, PHONE_SERVER_MAX_CALL_DURATION_SECONDS),
6495
+ maxCostPerMission: Math.min(maxCostPerMission, PHONE_SERVER_MAX_COST_PER_MISSION),
6496
+ maxAttempts: Math.min(maxAttempts, PHONE_SERVER_MAX_ATTEMPTS),
6497
+ transcriptEnabled,
6498
+ recordingEnabled,
6499
+ confirmPolicy: policy.confirmPolicy,
6500
+ alternativePolicy: {
6501
+ maxTimeShiftMinutes: policy.alternativePolicy.maxTimeShiftMinutes
6502
+ }
6503
+ },
6504
+ issues: []
6505
+ };
6506
+ }
6507
+ function validatePhoneTransportProfile(transport) {
6508
+ const issues = [];
6509
+ if (!isRecord(transport)) {
6510
+ return { ok: false, issues: [issue("transport-required", "transport", "transport profile is required")] };
6511
+ }
6512
+ const provider = typeof transport.provider === "string" ? transport.provider.trim() : "";
6513
+ if (!provider) {
6514
+ issues.push(issue("invalid-provider", "transport.provider", "provider is required"));
6515
+ }
6516
+ const phoneNumber = typeof transport.phoneNumber === "string" ? normalizePhoneNumber(transport.phoneNumber) : null;
6517
+ if (!phoneNumber) {
6518
+ issues.push(issue("invalid-transport-number", "transport.phoneNumber", "transport phoneNumber must be valid E.164"));
6519
+ }
6520
+ const capabilities = readCapabilityList(transport.capabilities);
6521
+ if (!capabilities) {
6522
+ issues.push(issue("invalid-capabilities", "transport.capabilities", "capabilities must contain supported transport capabilities"));
6523
+ } else if (!capabilities.includes("call_control")) {
6524
+ issues.push(issue("missing-call-control", "transport.capabilities", "transport must support call_control to start phone missions"));
6525
+ }
6526
+ const supportedRegions = readRegionList(transport.supportedRegions);
6527
+ if (!supportedRegions) {
6528
+ issues.push(issue("invalid-supported-regions", "transport.supportedRegions", "supportedRegions must contain at least one supported region"));
6529
+ }
6530
+ if (issues.length > 0) return { ok: false, issues };
6531
+ return {
6532
+ ok: true,
6533
+ transport: {
6534
+ provider,
6535
+ phoneNumber,
6536
+ capabilities,
6537
+ supportedRegions
6538
+ },
6539
+ issues: []
6540
+ };
6541
+ }
6542
+ function inferPhoneRegion(phoneNumber) {
6543
+ const normalized = normalizePhoneNumber(phoneNumber);
6544
+ if (!normalized) return null;
6545
+ if (normalized.startsWith("+43")) return "AT";
6546
+ if (normalized.startsWith("+49")) return "DE";
6547
+ if (EU_DIAL_PREFIXES.some((prefix) => normalized.startsWith(prefix))) return "EU";
6548
+ return "WORLD";
6549
+ }
6550
+ function isPhoneRegionAllowed(region, allowlist) {
6551
+ if (allowlist.includes("WORLD")) return true;
6552
+ if (allowlist.includes(region)) return true;
6553
+ if ((region === "AT" || region === "DE" || region === "EU") && allowlist.includes("EU")) return true;
6554
+ return false;
6555
+ }
6556
+ function classifyPhoneNumberRisk(phoneNumber) {
6557
+ const normalized = normalizePhoneNumber(phoneNumber);
6558
+ if (!normalized) return "invalid";
6559
+ if (PREMIUM_OR_SPECIAL_PREFIXES.some((prefix) => normalized.startsWith(prefix))) {
6560
+ return "premium_or_special";
6561
+ }
6562
+ return "standard";
6563
+ }
6564
+ function validatePhoneMissionStart(input, transport, options = {}) {
6565
+ const issues = [];
6566
+ if (!isRecord(input)) {
6567
+ return { ok: false, issues: [issue("start-input-required", "input", "start input is required")] };
6568
+ }
6569
+ const to = typeof input.to === "string" ? normalizePhoneNumber(input.to) : null;
6570
+ if (!to) {
6571
+ issues.push(issue("invalid-target-number", "input.to", "target number must be valid E.164"));
6572
+ }
6573
+ const rawTask = typeof input.task === "string" ? input.task : "";
6574
+ const task = rawTask.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
6575
+ if (!task) {
6576
+ issues.push(issue("task-required", "input.task", "task is required"));
6577
+ } else if (task.length > PHONE_TASK_MAX_LENGTH) {
6578
+ issues.push(issue("task-too-long", "input.task", `task must be ${PHONE_TASK_MAX_LENGTH} characters or fewer`));
6579
+ }
6580
+ const policyResult = validatePhoneMissionPolicy(input.policy);
6581
+ if (!policyResult.ok) issues.push(...policyResult.issues);
6582
+ const transportResult = validatePhoneTransportProfile(transport);
6583
+ if (!transportResult.ok) issues.push(...transportResult.issues);
6584
+ const risk = typeof input.to === "string" ? classifyPhoneNumberRisk(input.to) : "invalid";
6585
+ if (risk === "premium_or_special" && !options.allowPremiumOrSpecialNumbers) {
6586
+ issues.push(issue("premium-number-blocked", "input.to", "premium or special-rate numbers require an explicit allowlist"));
6587
+ }
6588
+ const targetRegion = to ? inferPhoneRegion(to) : null;
6589
+ if (!targetRegion) {
6590
+ issues.push(issue("unknown-target-region", "input.to", "target region could not be inferred"));
6591
+ }
6592
+ if (policyResult.ok && targetRegion && !isPhoneRegionAllowed(targetRegion, policyResult.policy.regionAllowlist)) {
6593
+ issues.push(issue("region-not-allowed", "input.to", "target number is outside the mission policy regionAllowlist"));
6594
+ }
6595
+ if (transportResult.ok && targetRegion && !isPhoneRegionAllowed(targetRegion, transportResult.transport.supportedRegions)) {
6596
+ issues.push(issue("transport-region-unsupported", "transport.supportedRegions", "target number is outside the transport supportedRegions"));
6597
+ }
6598
+ const capabilities = transportResult.ok ? transportResult.transport.capabilities : [];
6599
+ if (policyResult.ok && policyResult.policy.recordingEnabled && !capabilities.includes("recording_supported")) {
6600
+ issues.push(issue("recording-unsupported", "policy.recordingEnabled", "recordingEnabled requires transport recording_supported capability"));
6601
+ }
6602
+ if (issues.length > 0 || !policyResult.ok || !transportResult.ok || !to || !targetRegion) {
6603
+ return { ok: false, issues };
6604
+ }
6605
+ return {
6606
+ ok: true,
6607
+ mission: {
6608
+ to,
6609
+ task,
6610
+ policy: policyResult.policy,
6611
+ targetRegion,
6612
+ transport: transportResult.transport,
6613
+ voiceRuntimeRef: typeof input.voiceRuntimeRef === "string" && input.voiceRuntimeRef.trim() ? input.voiceRuntimeRef.trim() : void 0
6614
+ },
6615
+ issues: []
6616
+ };
6617
+ }
6618
+
6619
+ // src/phone/manager.ts
6620
+ var PHONE_RATE_LIMIT_PER_MINUTE = 5;
6621
+ var PHONE_RATE_LIMIT_PER_HOUR = 30;
6622
+ var PHONE_MAX_CONCURRENT_MISSIONS = 3;
6623
+ var PHONE_MIN_WEBHOOK_SECRET_LENGTH = 24;
6624
+ var TERMINAL_MISSION_STATES = ["completed", "failed", "cancelled"];
6625
+ var PhoneWebhookAuthError = class extends Error {
6626
+ isPhoneWebhookAuthError = true;
6627
+ constructor() {
6628
+ super("Invalid phone webhook request");
6629
+ this.name = "PhoneWebhookAuthError";
6630
+ }
6631
+ };
6632
+ var PhoneRateLimitError = class extends Error {
6633
+ isPhoneRateLimitError = true;
6634
+ constructor(message) {
6635
+ super(message);
6636
+ this.name = "PhoneRateLimitError";
6637
+ }
6638
+ };
6639
+ var PHONE_SECRET_FIELDS = ["password", "webhookSecret"];
6640
+ var MAX_PHONE_WEBHOOK_EVENT_KEYS = 50;
6641
+ function asString3(value) {
6642
+ return typeof value === "string" ? value.trim() : "";
6643
+ }
6644
+ function asRecord2(value) {
6645
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
6646
+ }
6647
+ function defaultApiUrl2(config) {
6648
+ const url = (config.apiUrl || "https://api.46elks.com/a1").replace(/\/+$/, "");
6649
+ if (!/^https:\/\//i.test(url)) {
6650
+ throw new Error("46elks apiUrl must use https:// \u2014 refusing to send credentials over a non-TLS connection");
6651
+ }
6652
+ return url;
6653
+ }
6654
+ function basicAuth2(username, password) {
6655
+ return Buffer.from(`${username}:${password}`, "utf8").toString("base64");
6656
+ }
6657
+ function secretMatches(provided, expected) {
6658
+ const a = Buffer.from(provided);
6659
+ const b = Buffer.from(expected);
6660
+ return a.length === b.length && timingSafeEqual(a, b);
6661
+ }
6662
+ function apiBaseUrl(webhookBaseUrl) {
6663
+ const root = webhookBaseUrl.replace(/\/+$/, "");
6664
+ return root.endsWith("/api/agenticmail") ? root : `${root}/api/agenticmail`;
6665
+ }
6666
+ function webhookToken(webhookSecret, missionId) {
6667
+ return createHmac("sha256", webhookSecret).update(missionId).digest("hex");
6668
+ }
6669
+ function buildWebhookUrl(config, path2, missionId) {
6670
+ const url = new URL(`${apiBaseUrl(config.webhookBaseUrl)}${path2}`);
6671
+ url.searchParams.set("missionId", missionId);
6672
+ url.searchParams.set("token", webhookToken(config.webhookSecret, missionId));
6673
+ return url.toString();
6674
+ }
6675
+ function redactWebhookUrl(value) {
6676
+ try {
6677
+ const url = new URL(value);
6678
+ if (url.searchParams.has("token")) url.searchParams.set("token", "***");
6679
+ if (url.searchParams.has("secret")) url.searchParams.set("secret", "***");
6680
+ return url.toString();
6681
+ } catch {
6682
+ return "[redacted-url]";
6683
+ }
6684
+ }
6685
+ function redactProviderRequest(request) {
6686
+ return {
6687
+ url: request.url,
6688
+ body: {
6689
+ ...request.body,
6690
+ voice_start: redactWebhookUrl(request.body.voice_start),
6691
+ whenhangup: redactWebhookUrl(request.body.whenhangup)
6692
+ }
6693
+ };
6694
+ }
6695
+ function stableFlatJson(value) {
6696
+ return JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))));
6697
+ }
6698
+ function phoneWebhookEventKey(kind, payload) {
6699
+ const callId = asString3(payload.callid) || asString3(payload.id) || asString3(payload.call_id);
6700
+ const result = asString3(payload.result) || asString3(payload.status) || asString3(payload.why);
6701
+ const fingerprint = createHash2("sha256").update(stableFlatJson(payload)).digest("hex").slice(0, 16);
6702
+ return [kind, callId || fingerprint, result].filter(Boolean).join(":");
6703
+ }
6704
+ function processedWebhookEventKeys(mission) {
6705
+ const value = mission.metadata.phoneWebhookEvents;
6706
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
6707
+ }
6708
+ function hasProcessedWebhookEvent(mission, eventKey) {
6709
+ return processedWebhookEventKeys(mission).includes(eventKey);
6710
+ }
6711
+ function appendProcessedWebhookEvent(mission, eventKey) {
6712
+ return [...processedWebhookEventKeys(mission), eventKey].slice(-MAX_PHONE_WEBHOOK_EVENT_KEYS);
6713
+ }
6714
+ function parseJson(value, fallback) {
6715
+ if (!value) return fallback;
6716
+ try {
6717
+ return JSON.parse(value);
6718
+ } catch {
6719
+ return fallback;
6720
+ }
6721
+ }
6722
+ function rowToMission(row) {
6723
+ return {
6724
+ id: row.id,
6725
+ agentId: row.agent_id,
6726
+ status: row.status,
6727
+ from: row.from_phone,
6728
+ to: row.to_phone,
6729
+ task: row.task,
6730
+ policy: parseJson(row.policy_json, {}),
6731
+ transport: parseJson(row.transport_json, {}),
6732
+ provider: row.provider,
6733
+ providerCallId: row.provider_call_id ?? void 0,
6734
+ transcript: parseJson(row.transcript_json, []),
6735
+ metadata: parseJson(row.metadata_json, {}),
6736
+ createdAt: row.created_at,
6737
+ updatedAt: row.updated_at
6738
+ };
6739
+ }
6740
+ function redactPhoneTransportConfig(config) {
6741
+ return {
6742
+ ...config,
6743
+ password: config.password ? "***" : "",
6744
+ webhookSecret: config.webhookSecret ? "***" : ""
6745
+ };
6746
+ }
6747
+ var PhoneManager = class {
6748
+ constructor(db2, encryptionKey) {
6749
+ this.db = db2;
6750
+ this.encryptionKey = encryptionKey;
6751
+ this.ensureTables();
6752
+ }
6753
+ initialized = false;
6754
+ /** Per-agent outbound-call timestamps (ms) for the in-memory rate limiter. */
6755
+ callTimestamps = /* @__PURE__ */ new Map();
6756
+ /**
6757
+ * Abuse / cost gate for /calls/start (#43-H1). Each non-dry-run call is
6758
+ * a real billed outbound call, so before dialing we enforce:
6759
+ * - a hard cap on concurrently-active (non-terminal) missions, and
6760
+ * - a per-agent token-bucket rate limit (per-minute + per-hour).
6761
+ * Throws {@link PhoneRateLimitError} (-> HTTP 429) when a limit is hit.
6762
+ * Call only on the real path — dry runs place no call and are exempt.
6763
+ */
6764
+ enforceCallLimits(agentId, nowMs) {
6765
+ const activeRow = this.db.prepare(
6766
+ `SELECT COUNT(*) AS cnt FROM phone_missions
6767
+ WHERE agent_id = ? AND status NOT IN ('completed', 'failed', 'cancelled')`
6768
+ ).get(agentId);
6769
+ if ((activeRow?.cnt ?? 0) >= PHONE_MAX_CONCURRENT_MISSIONS) {
6770
+ throw new PhoneRateLimitError(
6771
+ `Too many active phone missions (max ${PHONE_MAX_CONCURRENT_MISSIONS}). Wait for an active call to end before starting another.`
6772
+ );
6773
+ }
6774
+ const recent = (this.callTimestamps.get(agentId) ?? []).filter((ts) => nowMs - ts < 36e5);
6775
+ const lastMinute = recent.filter((ts) => nowMs - ts < 6e4).length;
6776
+ if (lastMinute >= PHONE_RATE_LIMIT_PER_MINUTE) {
6777
+ throw new PhoneRateLimitError(
6778
+ `Phone call rate limit reached (max ${PHONE_RATE_LIMIT_PER_MINUTE}/minute). Try again shortly.`
6779
+ );
6780
+ }
6781
+ if (recent.length >= PHONE_RATE_LIMIT_PER_HOUR) {
6782
+ throw new PhoneRateLimitError(
6783
+ `Phone call rate limit reached (max ${PHONE_RATE_LIMIT_PER_HOUR}/hour). Try again later.`
6784
+ );
6785
+ }
6786
+ recent.push(nowMs);
6787
+ this.callTimestamps.set(agentId, recent);
6788
+ }
6789
+ encryptConfig(config) {
6790
+ if (!this.encryptionKey) return config;
6791
+ const out = { ...config };
6792
+ for (const field of PHONE_SECRET_FIELDS) {
6793
+ const value = out[field];
6794
+ if (typeof value === "string" && value && !isEncryptedSecret(value)) {
6795
+ out[field] = encryptSecret(value, this.encryptionKey);
6796
+ }
6797
+ }
6798
+ return out;
6799
+ }
6800
+ decryptConfig(config) {
6801
+ if (!this.encryptionKey) return config;
6802
+ const out = { ...config };
6803
+ for (const field of PHONE_SECRET_FIELDS) {
6804
+ const value = out[field];
6805
+ if (typeof value === "string" && isEncryptedSecret(value)) {
6806
+ try {
6807
+ out[field] = decryptSecret(value, this.encryptionKey);
6808
+ } catch {
6809
+ }
6810
+ }
6811
+ }
6812
+ return out;
6813
+ }
6814
+ ensureTables() {
6815
+ if (this.initialized) return;
6816
+ this.db.exec(`
6817
+ CREATE TABLE IF NOT EXISTS phone_missions (
6818
+ id TEXT PRIMARY KEY,
6819
+ agent_id TEXT NOT NULL,
6820
+ status TEXT NOT NULL,
6821
+ from_phone TEXT NOT NULL,
6822
+ to_phone TEXT NOT NULL,
6823
+ task TEXT NOT NULL,
6824
+ policy_json TEXT NOT NULL,
6825
+ transport_json TEXT NOT NULL,
6826
+ provider TEXT NOT NULL,
6827
+ provider_call_id TEXT,
6828
+ transcript_json TEXT NOT NULL DEFAULT '[]',
6829
+ metadata_json TEXT NOT NULL DEFAULT '{}',
6830
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
6831
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
6832
+ )
6833
+ `);
6834
+ try {
6835
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_phone_missions_agent ON phone_missions(agent_id)");
6836
+ } catch {
6837
+ }
6838
+ try {
6839
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_phone_missions_status ON phone_missions(status)");
6840
+ } catch {
6841
+ }
6842
+ this.initialized = true;
6843
+ }
6844
+ getPhoneTransportConfig(agentId) {
6845
+ const row = this.db.prepare("SELECT metadata FROM agents WHERE id = ?").get(agentId);
6846
+ if (!row) return null;
6847
+ const meta = parseJson(row.metadata, {});
6848
+ const config = meta.phoneTransport;
6849
+ if (!config || typeof config !== "object") return null;
6850
+ return this.decryptConfig(config);
6851
+ }
6852
+ savePhoneTransportConfig(agentId, config) {
6853
+ const row = this.db.prepare("SELECT metadata FROM agents WHERE id = ?").get(agentId);
6854
+ if (!row) throw new Error(`Agent ${agentId} not found`);
6855
+ const transportCheck = validatePhoneTransportProfile(config);
6856
+ if (!transportCheck.ok) {
6857
+ throw new Error(`Invalid phone transport config: ${transportCheck.issues.map((item) => `${item.field}: ${item.message}`).join("; ")}`);
6858
+ }
6859
+ const meta = parseJson(row.metadata, {});
6860
+ meta.phoneTransport = this.encryptConfig({
6861
+ ...config,
6862
+ phoneNumber: transportCheck.transport.phoneNumber,
6863
+ capabilities: transportCheck.transport.capabilities,
6864
+ supportedRegions: transportCheck.transport.supportedRegions
6865
+ });
6866
+ this.db.prepare("UPDATE agents SET metadata = ?, updated_at = datetime('now') WHERE id = ?").run(JSON.stringify(meta), agentId);
6867
+ return config;
6868
+ }
6869
+ getMission(missionId, agentId) {
6870
+ 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);
6871
+ return row ? rowToMission(row) : null;
6872
+ }
6873
+ listMissions(agentId, opts = {}) {
6874
+ const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
6875
+ const offset = Math.max(opts.offset ?? 0, 0);
6876
+ const params = [agentId];
6877
+ let sql = "SELECT * FROM phone_missions WHERE agent_id = ?";
6878
+ if (opts.status && PHONE_MISSION_STATES.includes(opts.status)) {
6879
+ sql += " AND status = ?";
6880
+ params.push(opts.status);
6881
+ }
6882
+ sql += " ORDER BY created_at DESC LIMIT ? OFFSET ?";
6883
+ params.push(limit, offset);
6884
+ return this.db.prepare(sql).all(...params).map(rowToMission);
6885
+ }
6886
+ async startMission(agentId, input, options = {}) {
6887
+ const config = this.getPhoneTransportConfig(agentId);
6888
+ if (!config) {
6889
+ throw new Error("Phone transport is not configured. Use phone_transport_setup first.");
6890
+ }
6891
+ if (config.provider !== "46elks") {
6892
+ throw new Error(`Phone provider ${config.provider} does not support call_control yet`);
6893
+ }
6894
+ const validation = validatePhoneMissionStart(input, config);
6895
+ if (!validation.ok) {
6896
+ throw new Error(`Invalid phone mission: ${validation.issues.map((item) => `${item.code} (${item.field})`).join(", ")}`);
6897
+ }
6898
+ const now = options.now ?? /* @__PURE__ */ new Date();
6899
+ if (!options.dryRun) {
6900
+ this.enforceCallLimits(agentId, now.getTime());
6901
+ }
6902
+ const missionId = `call_${randomUUID()}`;
6903
+ const transcript = [{
6904
+ at: now.toISOString(),
6905
+ source: "system",
6906
+ text: "Phone mission created; outbound carrier call requested."
6907
+ }];
6908
+ const metadata = {
6909
+ voiceRuntimeRef: validation.mission.voiceRuntimeRef,
6910
+ targetRegion: validation.mission.targetRegion,
6911
+ dryRun: !!options.dryRun,
6912
+ // Attempt counter (#43-H2) — wired for breach detection; there is
6913
+ // no automatic retry loop today, so a fresh mission is attempt 1.
6914
+ attempts: 1
6915
+ };
6916
+ const mission = {
6917
+ id: missionId,
6918
+ agentId,
6919
+ status: "dialing",
6920
+ from: config.phoneNumber,
6921
+ to: validation.mission.to,
6922
+ task: validation.mission.task,
6923
+ policy: validation.mission.policy,
6924
+ transport: validation.mission.transport,
6925
+ provider: config.provider,
6926
+ transcript,
6927
+ metadata,
6928
+ createdAt: now.toISOString(),
6929
+ updatedAt: now.toISOString()
6930
+ };
6931
+ this.insertMission(mission);
6932
+ const providerRequest = this.build46ElksCallRequest(config, mission);
6933
+ if (options.dryRun) {
6934
+ const updated2 = this.updateProviderCall(missionId, "dryrun-call", {
6935
+ dryRun: true,
6936
+ providerRequest: redactProviderRequest(providerRequest)
6937
+ });
6938
+ return { mission: updated2, providerRequest };
6939
+ }
6940
+ const fetchFn = options.fetchFn ?? fetch;
6941
+ let response;
6942
+ try {
6943
+ response = await fetchFn(providerRequest.url, {
6944
+ method: "POST",
6945
+ headers: {
6946
+ "Authorization": `Basic ${basicAuth2(config.username, config.password)}`,
6947
+ "Content-Type": "application/x-www-form-urlencoded"
6948
+ },
6949
+ body: new URLSearchParams(providerRequest.body),
6950
+ signal: AbortSignal.timeout(15e3)
6951
+ });
6952
+ } catch (err) {
6953
+ const message = err?.message ?? String(err);
6954
+ this.updateMissionStatus(missionId, "failed", {
6955
+ providerError: message
6956
+ }, [{
6957
+ at: (/* @__PURE__ */ new Date()).toISOString(),
6958
+ source: "provider",
6959
+ text: "46elks call start failed \u2014 the provider request threw before any response.",
6960
+ metadata: { error: message }
6961
+ }]);
6962
+ throw err;
6963
+ }
6964
+ const text = await response.text();
6965
+ let raw = text;
6966
+ try {
6967
+ raw = JSON.parse(text);
6968
+ } catch {
6969
+ }
6970
+ if (!response.ok) {
6971
+ const failed = this.updateMissionStatus(missionId, "failed", {
6972
+ providerStatus: response.status,
6973
+ providerResponse: raw
6974
+ }, [{
6975
+ at: (/* @__PURE__ */ new Date()).toISOString(),
6976
+ source: "provider",
6977
+ text: `46elks call start failed with HTTP ${response.status}.`,
6978
+ metadata: { providerResponse: raw }
6979
+ }]);
6980
+ throw new Error(`46elks call start failed (${response.status}) for mission ${failed.id}`);
6981
+ }
6982
+ const providerCallId = asRecord2(raw).id ? String(asRecord2(raw).id) : void 0;
6983
+ const updated = this.updateProviderCall(missionId, providerCallId, { providerResponse: raw });
6984
+ return { mission: updated, providerRequest, providerResponse: raw };
6985
+ }
6986
+ /**
6987
+ * Verify a webhook request and return the mission, or throw a uniform
6988
+ * {@link PhoneWebhookAuthError} for ANY failure (unknown mission, no
6989
+ * token, wrong token). Uniform on purpose — no 404-vs-403 oracle.
6990
+ */
6991
+ authenticateWebhook(missionId, providedToken) {
6992
+ const mission = missionId ? this.getMission(missionId) : null;
6993
+ const config = mission ? this.getPhoneTransportConfig(mission.agentId) : null;
6994
+ if (!mission || !config || !providedToken || !secretMatches(providedToken, webhookToken(config.webhookSecret, mission.id))) {
6995
+ throw new PhoneWebhookAuthError();
6996
+ }
6997
+ return mission;
6998
+ }
6999
+ handleVoiceStartWebhook(missionId, providedToken, payload = {}) {
7000
+ const mission = this.authenticateWebhook(missionId, providedToken);
7001
+ if (TERMINAL_MISSION_STATES.includes(mission.status)) {
7002
+ return { mission, action: this.buildVoiceStartAction() };
7003
+ }
7004
+ const eventKey = phoneWebhookEventKey("voice_start", payload);
7005
+ if (hasProcessedWebhookEvent(mission, eventKey)) {
7006
+ return {
7007
+ mission,
7008
+ action: this.buildVoiceStartAction()
7009
+ };
7010
+ }
7011
+ const updated = this.updateMissionStatus(mission.id, "connected", {
7012
+ lastVoiceStartPayload: payload,
7013
+ phoneWebhookEvents: appendProcessedWebhookEvent(mission, eventKey)
7014
+ }, [{
7015
+ at: (/* @__PURE__ */ new Date()).toISOString(),
7016
+ source: "provider",
7017
+ text: "46elks voice_start webhook received. Realtime voice runtime is not connected in this slice.",
7018
+ metadata: { payload }
7019
+ }]);
7020
+ return {
7021
+ mission: updated,
7022
+ action: this.buildVoiceStartAction()
7023
+ };
7024
+ }
7025
+ handleHangupWebhook(missionId, providedToken, payload = {}) {
7026
+ const mission = this.authenticateWebhook(missionId, providedToken);
7027
+ const eventKey = phoneWebhookEventKey("hangup", payload);
7028
+ if (hasProcessedWebhookEvent(mission, eventKey)) {
7029
+ return mission;
7030
+ }
7031
+ const costPatch = this.buildCostMetadataPatch(mission, payload);
7032
+ const nextStatus = TERMINAL_MISSION_STATES.includes(mission.status) ? mission.status : "failed";
7033
+ const transcript = [{
7034
+ at: (/* @__PURE__ */ new Date()).toISOString(),
7035
+ source: "provider",
7036
+ text: nextStatus === "failed" ? "46elks hangup webhook received before a conversation runtime completed the mission." : "46elks hangup webhook received.",
7037
+ metadata: { payload }
7038
+ }];
7039
+ if (costPatch.costExceeded) {
7040
+ transcript.push({
7041
+ at: (/* @__PURE__ */ new Date()).toISOString(),
7042
+ source: "system",
7043
+ text: `Mission cost ${costPatch.totalCost} exceeded the policy cap of ${mission.policy.maxCostPerMission}.`
7044
+ });
7045
+ }
7046
+ return this.updateMissionStatus(mission.id, nextStatus, {
7047
+ lastHangupPayload: payload,
7048
+ hangupReason: nextStatus === "failed" ? "call-ended-before-conversation-runtime" : void 0,
7049
+ phoneWebhookEvents: appendProcessedWebhookEvent(mission, eventKey),
7050
+ ...costPatch
7051
+ }, transcript);
7052
+ }
7053
+ /**
7054
+ * Read the call cost off a 46elks hangup payload, add it to the
7055
+ * mission's running total, and flag a policy-cap breach (#43-H2).
7056
+ * Cost is only knowable post-call from the provider — the preventive
7057
+ * cost controls are the duration ceiling, rate limit, and concurrency
7058
+ * cap; this is the after-the-fact accounting + alerting.
7059
+ */
7060
+ buildCostMetadataPatch(mission, payload) {
7061
+ const rawCost = payload.cost;
7062
+ const callCost = typeof rawCost === "number" && Number.isFinite(rawCost) && rawCost >= 0 ? rawCost : Number.parseFloat(asString3(rawCost)) || 0;
7063
+ const priorCost = typeof mission.metadata.totalCost === "number" ? mission.metadata.totalCost : 0;
7064
+ const totalCost = Math.round((priorCost + callCost) * 1e6) / 1e6;
7065
+ const cap = mission.policy?.maxCostPerMission;
7066
+ const costExceeded = typeof cap === "number" && totalCost > cap;
7067
+ return { totalCost, costExceeded };
7068
+ }
7069
+ buildVoiceStartAction() {
7070
+ return {
7071
+ play: "AgenticMail has received this call mission. The live voice runtime is not connected yet; the operator will follow up."
7072
+ };
7073
+ }
7074
+ cancelMission(agentId, missionId) {
7075
+ const mission = this.getMission(missionId, agentId);
7076
+ if (!mission) throw new Error("Phone mission not found");
7077
+ return this.updateMissionStatus(mission.id, "cancelled", {}, [{
7078
+ at: (/* @__PURE__ */ new Date()).toISOString(),
7079
+ source: "operator",
7080
+ text: "Phone mission cancelled."
7081
+ }]);
7082
+ }
7083
+ build46ElksCallRequest(config, mission) {
7084
+ const timeout = Math.min(Math.max(mission.policy.maxCallDurationSeconds, 1), PHONE_SERVER_MAX_CALL_DURATION_SECONDS);
7085
+ return {
7086
+ url: `${defaultApiUrl2(config)}/calls`,
7087
+ body: {
7088
+ from: config.phoneNumber,
7089
+ to: mission.to,
7090
+ voice_start: buildWebhookUrl(config, "/calls/webhook/46elks/voice-start", mission.id),
7091
+ whenhangup: buildWebhookUrl(config, "/calls/webhook/46elks/hangup", mission.id),
7092
+ timeout: String(timeout)
7093
+ }
7094
+ };
7095
+ }
7096
+ insertMission(mission) {
7097
+ this.db.prepare(`
7098
+ INSERT INTO phone_missions (
7099
+ id, agent_id, status, from_phone, to_phone, task,
7100
+ policy_json, transport_json, provider, provider_call_id,
7101
+ transcript_json, metadata_json, created_at, updated_at
7102
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7103
+ `).run(
7104
+ mission.id,
7105
+ mission.agentId,
7106
+ mission.status,
7107
+ mission.from,
7108
+ mission.to,
7109
+ mission.task,
7110
+ JSON.stringify(mission.policy),
7111
+ JSON.stringify(mission.transport),
7112
+ mission.provider,
7113
+ mission.providerCallId ?? null,
7114
+ JSON.stringify(mission.transcript),
7115
+ JSON.stringify(mission.metadata),
7116
+ mission.createdAt,
7117
+ mission.updatedAt
7118
+ );
7119
+ }
7120
+ updateProviderCall(missionId, providerCallId, metadata) {
7121
+ const mission = this.getMission(missionId);
7122
+ if (!mission) throw new Error("Phone mission not found");
7123
+ const nextMetadata = { ...mission.metadata, ...metadata };
7124
+ this.db.prepare(`
7125
+ UPDATE phone_missions
7126
+ SET provider_call_id = ?, metadata_json = ?, updated_at = ?
7127
+ WHERE id = ?
7128
+ `).run(providerCallId ?? null, JSON.stringify(nextMetadata), (/* @__PURE__ */ new Date()).toISOString(), missionId);
7129
+ return this.getMission(missionId);
7130
+ }
7131
+ updateMissionStatus(missionId, status, metadata, transcriptEntries = []) {
7132
+ const mission = this.getMission(missionId);
7133
+ if (!mission) throw new Error("Phone mission not found");
7134
+ const nextTranscript = [...mission.transcript, ...transcriptEntries];
7135
+ const nextMetadata = Object.fromEntries(
7136
+ Object.entries({ ...mission.metadata, ...metadata }).filter(([, value]) => value !== void 0)
7137
+ );
7138
+ this.db.prepare(`
7139
+ UPDATE phone_missions
7140
+ SET status = ?, transcript_json = ?, metadata_json = ?, updated_at = ?
7141
+ WHERE id = ?
7142
+ `).run(status, JSON.stringify(nextTranscript), JSON.stringify(nextMetadata), (/* @__PURE__ */ new Date()).toISOString(), missionId);
7143
+ return this.getMission(missionId);
7144
+ }
7145
+ };
7146
+ function buildPhoneTransportConfig(input) {
7147
+ const provider = asString3(input.provider) || "46elks";
7148
+ if (provider !== "46elks") throw new Error('provider must be "46elks"');
7149
+ const phoneNumber = normalizePhoneNumber(asString3(input.phoneNumber));
7150
+ if (!phoneNumber) throw new Error("phoneNumber must be a valid E.164 phone number");
7151
+ const username = asString3(input.username);
7152
+ const password = asString3(input.password);
7153
+ const webhookBaseUrl = asString3(input.webhookBaseUrl);
7154
+ const webhookSecret = asString3(input.webhookSecret);
7155
+ if (!username || !password) throw new Error('username and password are required for provider "46elks"');
7156
+ if (!webhookBaseUrl) throw new Error("webhookBaseUrl is required");
7157
+ if (!webhookSecret) throw new Error("webhookSecret is required");
7158
+ if (webhookSecret.length < PHONE_MIN_WEBHOOK_SECRET_LENGTH) {
7159
+ throw new Error(`webhookSecret must be at least ${PHONE_MIN_WEBHOOK_SECRET_LENGTH} characters`);
7160
+ }
7161
+ const parsedWebhookBaseUrl = new URL(webhookBaseUrl);
7162
+ if (parsedWebhookBaseUrl.protocol !== "https:" && parsedWebhookBaseUrl.hostname !== "127.0.0.1" && parsedWebhookBaseUrl.hostname !== "localhost") {
7163
+ throw new Error("webhookBaseUrl must use https:// unless it points at localhost");
7164
+ }
7165
+ const apiUrl = asString3(input.apiUrl);
7166
+ if (apiUrl) {
7167
+ const parsedApiUrl = new URL(apiUrl);
7168
+ if (parsedApiUrl.protocol !== "https:") {
7169
+ throw new Error("apiUrl must use https:// \u2014 credentials are sent on every request");
7170
+ }
7171
+ }
7172
+ const capabilities = Array.isArray(input.capabilities) ? input.capabilities.filter((item) => typeof item === "string" && ["sms", "call_control", "realtime_media", "recording_supported"].includes(item)) : ["call_control"];
7173
+ const supportedRegions = Array.isArray(input.supportedRegions) ? input.supportedRegions.filter((item) => typeof item === "string" && ["AT", "DE", "EU", "WORLD"].includes(item)) : ["EU"];
7174
+ const config = {
7175
+ provider,
7176
+ phoneNumber,
7177
+ username,
7178
+ password,
7179
+ webhookBaseUrl,
7180
+ webhookSecret,
7181
+ apiUrl: apiUrl || void 0,
7182
+ capabilities: Array.from(/* @__PURE__ */ new Set(["call_control", ...capabilities])),
7183
+ supportedRegions: supportedRegions.length ? Array.from(new Set(supportedRegions)) : ["EU"],
7184
+ configuredAt: input.configuredAt ?? (/* @__PURE__ */ new Date()).toISOString()
7185
+ };
7186
+ const validation = validatePhoneTransportProfile(config);
7187
+ if (!validation.ok) {
7188
+ throw new Error(`Invalid phone transport config: ${validation.issues.map((item) => `${item.field}: ${item.message}`).join("; ")}`);
7189
+ }
7190
+ return config;
7191
+ }
7192
+
6228
7193
  // src/telemetry.ts
6229
- import { randomUUID } from "crypto";
7194
+ import { randomUUID as randomUUID2 } from "crypto";
6230
7195
  import { readFileSync as readFileSync2, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, existsSync as existsSync3 } from "fs";
6231
7196
  import { join as join5 } from "path";
6232
7197
  import { homedir as homedir4 } from "os";
@@ -6257,12 +7222,12 @@ function getInstallId() {
6257
7222
  return installId;
6258
7223
  }
6259
7224
  }
6260
- installId = randomUUID();
7225
+ installId = randomUUID2();
6261
7226
  if (!existsSync3(dir2)) mkdirSync3(dir2, { recursive: true });
6262
7227
  writeFileSync3(idFile, installId, "utf8");
6263
7228
  return installId;
6264
7229
  } catch {
6265
- installId = randomUUID();
7230
+ installId = randomUUID2();
6266
7231
  return installId;
6267
7232
  }
6268
7233
  }
@@ -8039,7 +9004,7 @@ secret = "${password}"
8039
9004
  };
8040
9005
 
8041
9006
  // src/threading/thread-id.ts
8042
- import { createHash as createHash2 } from "crypto";
9007
+ import { createHash as createHash3 } from "crypto";
8043
9008
  function stripReplyPrefixes(subject) {
8044
9009
  let s = subject.length > 1e3 ? subject.slice(0, 1e3) : subject;
8045
9010
  for (; ; ) {
@@ -8068,7 +9033,7 @@ function normalizeAddress(addr) {
8068
9033
  }
8069
9034
  function threadIdFor(input) {
8070
9035
  const subject = normalizeSubject(input.subject);
8071
- return createHash2("sha256").update(subject).digest("base64url").slice(0, 16);
9036
+ return createHash3("sha256").update(subject).digest("base64url").slice(0, 16);
8072
9037
  }
8073
9038
 
8074
9039
  // src/threading/thread-cache.ts
@@ -8328,10 +9293,890 @@ function parse(raw) {
8328
9293
  }
8329
9294
  return out;
8330
9295
  }
9296
+
9297
+ // src/memory/manager.ts
9298
+ import { randomUUID as randomUUID3 } from "crypto";
9299
+
9300
+ // src/memory/text-search.ts
9301
+ var BM25_K1 = 1.2;
9302
+ var BM25_B = 0.75;
9303
+ var FIELD_WEIGHT_TITLE = 3;
9304
+ var FIELD_WEIGHT_TAGS = 2;
9305
+ var FIELD_WEIGHT_CONTENT = 1;
9306
+ var PREFIX_MATCH_PENALTY = 0.7;
9307
+ var STOP_WORDS = /* @__PURE__ */ new Set([
9308
+ "a",
9309
+ "about",
9310
+ "above",
9311
+ "after",
9312
+ "again",
9313
+ "against",
9314
+ "all",
9315
+ "am",
9316
+ "an",
9317
+ "and",
9318
+ "any",
9319
+ "are",
9320
+ "as",
9321
+ "at",
9322
+ "be",
9323
+ "because",
9324
+ "been",
9325
+ "before",
9326
+ "being",
9327
+ "below",
9328
+ "between",
9329
+ "both",
9330
+ "but",
9331
+ "by",
9332
+ "can",
9333
+ "could",
9334
+ "did",
9335
+ "do",
9336
+ "does",
9337
+ "doing",
9338
+ "down",
9339
+ "during",
9340
+ "each",
9341
+ "either",
9342
+ "every",
9343
+ "few",
9344
+ "for",
9345
+ "from",
9346
+ "further",
9347
+ "get",
9348
+ "got",
9349
+ "had",
9350
+ "has",
9351
+ "have",
9352
+ "having",
9353
+ "he",
9354
+ "her",
9355
+ "here",
9356
+ "hers",
9357
+ "herself",
9358
+ "him",
9359
+ "himself",
9360
+ "his",
9361
+ "how",
9362
+ "i",
9363
+ "if",
9364
+ "in",
9365
+ "into",
9366
+ "is",
9367
+ "it",
9368
+ "its",
9369
+ "itself",
9370
+ "just",
9371
+ "may",
9372
+ "me",
9373
+ "might",
9374
+ "more",
9375
+ "most",
9376
+ "must",
9377
+ "my",
9378
+ "myself",
9379
+ "neither",
9380
+ "no",
9381
+ "nor",
9382
+ "not",
9383
+ "now",
9384
+ "of",
9385
+ "off",
9386
+ "on",
9387
+ "once",
9388
+ "only",
9389
+ "or",
9390
+ "other",
9391
+ "ought",
9392
+ "our",
9393
+ "ours",
9394
+ "ourselves",
9395
+ "out",
9396
+ "over",
9397
+ "own",
9398
+ "same",
9399
+ "shall",
9400
+ "she",
9401
+ "should",
9402
+ "so",
9403
+ "some",
9404
+ "such",
9405
+ "than",
9406
+ "that",
9407
+ "the",
9408
+ "their",
9409
+ "theirs",
9410
+ "them",
9411
+ "themselves",
9412
+ "then",
9413
+ "there",
9414
+ "these",
9415
+ "they",
9416
+ "this",
9417
+ "those",
9418
+ "through",
9419
+ "to",
9420
+ "too",
9421
+ "under",
9422
+ "until",
9423
+ "up",
9424
+ "us",
9425
+ "very",
9426
+ "was",
9427
+ "we",
9428
+ "were",
9429
+ "what",
9430
+ "when",
9431
+ "where",
9432
+ "which",
9433
+ "while",
9434
+ "who",
9435
+ "whom",
9436
+ "why",
9437
+ "will",
9438
+ "with",
9439
+ "would",
9440
+ "yet",
9441
+ "you",
9442
+ "your",
9443
+ "yours",
9444
+ "yourself",
9445
+ "yourselves"
9446
+ ]);
9447
+ var STEM_RULES = [
9448
+ // Step 1: plurals and past participles
9449
+ [/ies$/, "i", 3],
9450
+ // policies → polici,eries → eri
9451
+ [/sses$/, "ss", 4],
9452
+ // addresses → address
9453
+ [/([^s])s$/, "$1", 3],
9454
+ // items → item, but not "ss"
9455
+ [/eed$/, "ee", 4],
9456
+ // agreed → agree
9457
+ [/ed$/, "", 3],
9458
+ // configured → configur, but min length 3
9459
+ [/ing$/, "", 4],
9460
+ // running → runn → run (handled below)
9461
+ // Step 2: derivational suffixes
9462
+ [/ational$/, "ate", 6],
9463
+ // relational → relate
9464
+ [/tion$/, "t", 5],
9465
+ // adoption → adopt
9466
+ [/ness$/, "", 5],
9467
+ // awareness → aware
9468
+ [/ment$/, "", 5],
9469
+ // deployment → deploy
9470
+ [/able$/, "", 5],
9471
+ // configurable → configur
9472
+ [/ible$/, "", 5],
9473
+ // accessible → access
9474
+ [/ful$/, "", 5],
9475
+ // powerful → power
9476
+ [/ous$/, "", 5],
9477
+ // dangerous → danger
9478
+ [/ive$/, "", 5],
9479
+ // interactive → interact
9480
+ [/ize$/, "", 4],
9481
+ // normalize → normal
9482
+ [/ise$/, "", 4],
9483
+ // organise → organ
9484
+ [/ally$/, "", 5],
9485
+ // automatically → automat
9486
+ [/ly$/, "", 4],
9487
+ // quickly → quick
9488
+ [/er$/, "", 4]
9489
+ // handler → handl
9490
+ ];
9491
+ var DOUBLE_CONSONANT = /([^aeiou])\1$/;
9492
+ function stem(word) {
9493
+ if (word.length < 3) return word;
9494
+ let stemmed = word;
9495
+ for (const [pattern, replacement, minLen] of STEM_RULES) {
9496
+ if (stemmed.length >= minLen && pattern.test(stemmed)) {
9497
+ stemmed = stemmed.replace(pattern, replacement);
9498
+ break;
9499
+ }
9500
+ }
9501
+ if (stemmed.length > 2 && DOUBLE_CONSONANT.test(stemmed)) {
9502
+ stemmed = stemmed.slice(0, -1);
9503
+ }
9504
+ return stemmed;
9505
+ }
9506
+ function tokenize(text) {
9507
+ return text.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1 && !STOP_WORDS.has(t)).map(stem);
9508
+ }
9509
+ var MemorySearchIndex = class {
9510
+ /** Posting lists: stemmed term → Set of memory IDs containing it */
9511
+ postings = /* @__PURE__ */ new Map();
9512
+ /** Per-document metadata for BM25 scoring */
9513
+ docs = /* @__PURE__ */ new Map();
9514
+ /** Pre-computed IDF values. Stale flag triggers lazy recomputation. */
9515
+ idf = /* @__PURE__ */ new Map();
9516
+ idfStale = true;
9517
+ /** 3-character prefix map for prefix matching: prefix → Set of full stems */
9518
+ prefixMap = /* @__PURE__ */ new Map();
9519
+ /** Total weighted document length (for computing average) */
9520
+ totalWeightedLen = 0;
9521
+ get docCount() {
9522
+ return this.docs.size;
9523
+ }
9524
+ get avgDocLen() {
9525
+ return this.docs.size > 0 ? this.totalWeightedLen / this.docs.size : 1;
9526
+ }
9527
+ /**
9528
+ * Index a memory entry. Extracts stems from title, content, and tags
9529
+ * with field-specific weighting and builds posting lists.
9530
+ */
9531
+ addDocument(id, entry) {
9532
+ if (this.docs.has(id)) this.removeDocument(id);
9533
+ const titleTokens = tokenize(entry.title);
9534
+ const contentTokens = tokenize(entry.content);
9535
+ const tagTokens = entry.tags.flatMap((t) => tokenize(t));
9536
+ const weightedTf = /* @__PURE__ */ new Map();
9537
+ for (const t of titleTokens) weightedTf.set(t, (weightedTf.get(t) || 0) + FIELD_WEIGHT_TITLE);
9538
+ for (const t of tagTokens) weightedTf.set(t, (weightedTf.get(t) || 0) + FIELD_WEIGHT_TAGS);
9539
+ for (const t of contentTokens) weightedTf.set(t, (weightedTf.get(t) || 0) + FIELD_WEIGHT_CONTENT);
9540
+ const weightedLen = titleTokens.length * FIELD_WEIGHT_TITLE + tagTokens.length * FIELD_WEIGHT_TAGS + contentTokens.length * FIELD_WEIGHT_CONTENT;
9541
+ const allStems = /* @__PURE__ */ new Set();
9542
+ for (const t of weightedTf.keys()) allStems.add(t);
9543
+ const stemSequence = [...titleTokens, ...contentTokens];
9544
+ const docRecord = { weightedTf, weightedLen, allStems, stemSequence };
9545
+ this.docs.set(id, docRecord);
9546
+ this.totalWeightedLen += weightedLen;
9547
+ for (const term of allStems) {
9548
+ let posting = this.postings.get(term);
9549
+ if (!posting) {
9550
+ posting = /* @__PURE__ */ new Set();
9551
+ this.postings.set(term, posting);
9552
+ }
9553
+ posting.add(id);
9554
+ if (term.length >= 3) {
9555
+ const prefix = term.slice(0, 3);
9556
+ let prefixSet = this.prefixMap.get(prefix);
9557
+ if (!prefixSet) {
9558
+ prefixSet = /* @__PURE__ */ new Set();
9559
+ this.prefixMap.set(prefix, prefixSet);
9560
+ }
9561
+ prefixSet.add(term);
9562
+ }
9563
+ }
9564
+ this.idfStale = true;
9565
+ }
9566
+ /** Remove a document from the index. */
9567
+ removeDocument(id) {
9568
+ const doc = this.docs.get(id);
9569
+ if (!doc) return;
9570
+ this.totalWeightedLen -= doc.weightedLen;
9571
+ this.docs.delete(id);
9572
+ for (const term of doc.allStems) {
9573
+ const posting = this.postings.get(term);
9574
+ if (posting) {
9575
+ posting.delete(id);
9576
+ if (posting.size === 0) {
9577
+ this.postings.delete(term);
9578
+ if (term.length >= 3) {
9579
+ const prefixSet = this.prefixMap.get(term.slice(0, 3));
9580
+ if (prefixSet) {
9581
+ prefixSet.delete(term);
9582
+ if (prefixSet.size === 0) this.prefixMap.delete(term.slice(0, 3));
9583
+ }
9584
+ }
9585
+ }
9586
+ }
9587
+ }
9588
+ this.idfStale = true;
9589
+ }
9590
+ /** Recompute IDF values for all terms. Called lazily before search. */
9591
+ refreshIdf() {
9592
+ if (!this.idfStale) return;
9593
+ const N = this.docs.size;
9594
+ this.idf.clear();
9595
+ for (const [term, posting] of this.postings) {
9596
+ const df = posting.size;
9597
+ this.idf.set(term, Math.log((N - df + 0.5) / (df + 0.5) + 1));
9598
+ }
9599
+ this.idfStale = false;
9600
+ }
9601
+ /**
9602
+ * Expand query terms with prefix matches.
9603
+ * "deploy" → ["deploy", "deployment", "deploying", ...] (if they exist in the index)
9604
+ */
9605
+ expandQueryTerms(queryStems) {
9606
+ const expanded = /* @__PURE__ */ new Map();
9607
+ for (const qs of queryStems) {
9608
+ if (this.postings.has(qs)) {
9609
+ expanded.set(qs, Math.max(expanded.get(qs) || 0, 1));
9610
+ }
9611
+ if (qs.length >= 3) {
9612
+ const prefix = qs.slice(0, 3);
9613
+ const candidates = this.prefixMap.get(prefix);
9614
+ if (candidates) {
9615
+ for (const candidate of candidates) {
9616
+ if (candidate !== qs && candidate.startsWith(qs)) {
9617
+ expanded.set(candidate, Math.max(expanded.get(candidate) || 0, PREFIX_MATCH_PENALTY));
9618
+ }
9619
+ }
9620
+ }
9621
+ }
9622
+ }
9623
+ return expanded;
9624
+ }
9625
+ /**
9626
+ * Compute bigram proximity boost: if two query terms appear adjacent
9627
+ * in the document's stem sequence, boost the score.
9628
+ */
9629
+ bigramProximityBoost(docId, queryStems) {
9630
+ if (queryStems.length < 2) return 0;
9631
+ const doc = this.docs.get(docId);
9632
+ if (!doc || doc.stemSequence.length < 2) return 0;
9633
+ let boost = 0;
9634
+ const seq = doc.stemSequence;
9635
+ const querySet = new Set(queryStems);
9636
+ for (let i = 0; i < seq.length - 1; i++) {
9637
+ if (querySet.has(seq[i]) && querySet.has(seq[i + 1]) && seq[i] !== seq[i + 1]) {
9638
+ boost += 0.5;
9639
+ }
9640
+ }
9641
+ return Math.min(boost, 2);
9642
+ }
9643
+ /**
9644
+ * Search the index for documents matching a query.
9645
+ * Returns scored results sorted by BM25F relevance.
9646
+ *
9647
+ * @param query - Raw query string
9648
+ * @param candidateIds - Optional: only score these document IDs (for agent-scoped search)
9649
+ * @returns Array of { id, score } sorted by descending score
9650
+ */
9651
+ search(query, candidateIds) {
9652
+ const queryStems = tokenize(query);
9653
+ if (queryStems.length === 0) return [];
9654
+ this.refreshIdf();
9655
+ const expandedTerms = this.expandQueryTerms(queryStems);
9656
+ if (expandedTerms.size === 0) return [];
9657
+ const avgDl = this.avgDocLen;
9658
+ const candidates = /* @__PURE__ */ new Set();
9659
+ for (const term of expandedTerms.keys()) {
9660
+ const posting = this.postings.get(term);
9661
+ if (posting) {
9662
+ for (const docId of posting) {
9663
+ if (!candidateIds || candidateIds.has(docId)) candidates.add(docId);
9664
+ }
9665
+ }
9666
+ }
9667
+ const results = [];
9668
+ for (const docId of candidates) {
9669
+ const doc = this.docs.get(docId);
9670
+ if (!doc) continue;
9671
+ let score = 0;
9672
+ for (const [term, weight] of expandedTerms) {
9673
+ const tf = doc.weightedTf.get(term) || 0;
9674
+ if (tf === 0) continue;
9675
+ const termIdf = this.idf.get(term) || 0;
9676
+ const numerator = tf * (BM25_K1 + 1);
9677
+ const denominator = tf + BM25_K1 * (1 - BM25_B + BM25_B * (doc.weightedLen / avgDl));
9678
+ score += termIdf * (numerator / denominator) * weight;
9679
+ }
9680
+ score += this.bigramProximityBoost(docId, queryStems);
9681
+ if (score > 0) results.push({ id: docId, score });
9682
+ }
9683
+ results.sort((a, b) => b.score - a.score);
9684
+ return results;
9685
+ }
9686
+ /** Check if a document exists in the index. */
9687
+ has(id) {
9688
+ return this.docs.has(id);
9689
+ }
9690
+ };
9691
+
9692
+ // src/memory/manager.ts
9693
+ function sj(v, fb = {}) {
9694
+ if (!v) return fb;
9695
+ try {
9696
+ return JSON.parse(v);
9697
+ } catch {
9698
+ return fb;
9699
+ }
9700
+ }
9701
+ var MEMORY_CATEGORIES = {
9702
+ knowledge: {
9703
+ label: "Knowledge",
9704
+ description: "Facts, procedures, and reference information the agent has learned"
9705
+ },
9706
+ interaction_pattern: {
9707
+ label: "Interaction Patterns",
9708
+ description: "Learned patterns from past interactions"
9709
+ },
9710
+ preference: {
9711
+ label: "Preferences",
9712
+ description: "User and counterparty preferences"
9713
+ },
9714
+ correction: {
9715
+ label: "Corrections",
9716
+ description: "Corrections and feedback received"
9717
+ },
9718
+ skill: {
9719
+ label: "Skills",
9720
+ description: "Learned abilities and competencies"
9721
+ },
9722
+ context: {
9723
+ label: "Context",
9724
+ description: "Contextual information and background knowledge"
9725
+ },
9726
+ reflection: {
9727
+ label: "Reflections",
9728
+ description: "Self-reflective insights and learnings"
9729
+ },
9730
+ session_learning: {
9731
+ label: "Session Learnings",
9732
+ description: "Insights captured during conversation sessions"
9733
+ },
9734
+ system_notice: {
9735
+ label: "System Notices",
9736
+ description: "System-generated notifications about configuration changes"
9737
+ }
9738
+ };
9739
+ var VALID_CATEGORIES = new Set(Object.keys(MEMORY_CATEGORIES));
9740
+ var VALID_IMPORTANCE = /* @__PURE__ */ new Set(["critical", "high", "normal", "low"]);
9741
+ var IMPORTANCE_WEIGHT = {
9742
+ critical: 4,
9743
+ high: 3,
9744
+ normal: 2,
9745
+ low: 1
9746
+ };
9747
+ var AgentMemoryManager = class {
9748
+ constructor(db2) {
9749
+ this.db = db2;
9750
+ this.ensureTable();
9751
+ this.loadFromDb();
9752
+ }
9753
+ memories = /* @__PURE__ */ new Map();
9754
+ /** Per-agent index: agentId → Set of memory IDs for O(1) agent lookups */
9755
+ agentIndex = /* @__PURE__ */ new Map();
9756
+ /** Full-text search index (BM25F + stemming + inverted index) */
9757
+ searchIndex = new MemorySearchIndex();
9758
+ initialized = false;
9759
+ // ─── Database layer ─────────────────────────────────
9760
+ ensureTable() {
9761
+ if (this.initialized) return;
9762
+ this.db.exec(`
9763
+ CREATE TABLE IF NOT EXISTS agent_memory (
9764
+ id TEXT PRIMARY KEY,
9765
+ agent_id TEXT NOT NULL,
9766
+ category TEXT NOT NULL,
9767
+ title TEXT NOT NULL,
9768
+ content TEXT NOT NULL,
9769
+ source TEXT NOT NULL DEFAULT 'interaction',
9770
+ importance TEXT NOT NULL DEFAULT 'normal',
9771
+ confidence REAL NOT NULL DEFAULT 1.0,
9772
+ access_count INTEGER NOT NULL DEFAULT 0,
9773
+ last_accessed_at TEXT,
9774
+ expires_at TEXT,
9775
+ tags TEXT NOT NULL DEFAULT '[]',
9776
+ metadata TEXT NOT NULL DEFAULT '{}',
9777
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
9778
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
9779
+ )
9780
+ `);
9781
+ try {
9782
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_agent_memory_agent ON agent_memory(agent_id)");
9783
+ } catch {
9784
+ }
9785
+ try {
9786
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_agent_memory_category ON agent_memory(category)");
9787
+ } catch {
9788
+ }
9789
+ this.initialized = true;
9790
+ }
9791
+ /** Run a write statement, swallowing errors with a log (memory must never crash a caller). */
9792
+ dbRun(sql, params) {
9793
+ try {
9794
+ this.db.prepare(sql).run(...params);
9795
+ } catch (err) {
9796
+ console.error("[agent-memory] DB write failed:", err.message);
9797
+ }
9798
+ }
9799
+ dbAll(sql, params = []) {
9800
+ try {
9801
+ return this.db.prepare(sql).all(...params);
9802
+ } catch (err) {
9803
+ console.error("[agent-memory] DB read failed:", err.message);
9804
+ return [];
9805
+ }
9806
+ }
9807
+ loadFromDb() {
9808
+ const rows = this.dbAll("SELECT * FROM agent_memory");
9809
+ for (const r of rows) {
9810
+ try {
9811
+ const entry = this.rowToEntry(r);
9812
+ this.memories.set(entry.id, entry);
9813
+ this.indexAdd(entry.agentId, entry.id);
9814
+ this.searchIndex.addDocument(entry.id, entry);
9815
+ } catch {
9816
+ }
9817
+ }
9818
+ }
9819
+ /** Add a memory ID to the per-agent index. */
9820
+ indexAdd(agentId, memoryId) {
9821
+ let set = this.agentIndex.get(agentId);
9822
+ if (!set) {
9823
+ set = /* @__PURE__ */ new Set();
9824
+ this.agentIndex.set(agentId, set);
9825
+ }
9826
+ set.add(memoryId);
9827
+ }
9828
+ /** Remove a memory ID from the per-agent index. */
9829
+ indexRemove(agentId, memoryId) {
9830
+ const set = this.agentIndex.get(agentId);
9831
+ if (set) {
9832
+ set.delete(memoryId);
9833
+ if (set.size === 0) this.agentIndex.delete(agentId);
9834
+ }
9835
+ }
9836
+ /** Get all memory entries for an agent via the index. */
9837
+ getAgentMemories(agentId) {
9838
+ const ids = this.agentIndex.get(agentId);
9839
+ if (!ids || ids.size === 0) return [];
9840
+ const result = [];
9841
+ for (const id of ids) {
9842
+ const entry = this.memories.get(id);
9843
+ if (entry) result.push(entry);
9844
+ }
9845
+ return result;
9846
+ }
9847
+ // ─── Convenience Methods ─────────────────────────────
9848
+ /** Store a memory with minimal input — the common "just remember this" case. */
9849
+ async storeMemory(agentId, opts) {
9850
+ const category = opts.category && VALID_CATEGORIES.has(opts.category) ? opts.category : "context";
9851
+ const importance = opts.importance && VALID_IMPORTANCE.has(opts.importance) ? opts.importance : "normal";
9852
+ return this.createMemory({
9853
+ agentId,
9854
+ content: opts.content,
9855
+ category,
9856
+ importance,
9857
+ confidence: opts.confidence ?? 1,
9858
+ title: opts.title || opts.content.slice(0, 80),
9859
+ source: "system",
9860
+ tags: opts.tags ?? [],
9861
+ metadata: {}
9862
+ });
9863
+ }
9864
+ /** Search memories by text query, sorted by relevance. */
9865
+ async recall(agentId, query, limit = 5) {
9866
+ return this.queryMemories({ agentId, query, limit });
9867
+ }
9868
+ // ─── CRUD Operations ────────────────────────────────
9869
+ /** Create a new memory entry with auto-generated id + timestamps. */
9870
+ async createMemory(input) {
9871
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9872
+ const entry = {
9873
+ ...input,
9874
+ confidence: input.confidence ?? 0.8,
9875
+ tags: input.tags ?? [],
9876
+ metadata: input.metadata ?? {},
9877
+ id: randomUUID3(),
9878
+ accessCount: 0,
9879
+ createdAt: now,
9880
+ updatedAt: now
9881
+ };
9882
+ this.memories.set(entry.id, entry);
9883
+ this.indexAdd(entry.agentId, entry.id);
9884
+ this.searchIndex.addDocument(entry.id, entry);
9885
+ this.dbRun(
9886
+ `INSERT INTO agent_memory (id, agent_id, category, title, content, source, importance, confidence, access_count, last_accessed_at, expires_at, tags, metadata, created_at, updated_at)
9887
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
9888
+ [
9889
+ entry.id,
9890
+ entry.agentId,
9891
+ entry.category,
9892
+ entry.title,
9893
+ entry.content,
9894
+ entry.source,
9895
+ entry.importance,
9896
+ entry.confidence,
9897
+ entry.accessCount,
9898
+ entry.lastAccessedAt || null,
9899
+ entry.expiresAt || null,
9900
+ JSON.stringify(entry.tags),
9901
+ JSON.stringify(entry.metadata),
9902
+ entry.createdAt,
9903
+ entry.updatedAt
9904
+ ]
9905
+ );
9906
+ return entry;
9907
+ }
9908
+ /** Update an existing memory entry by merging provided fields. */
9909
+ async updateMemory(id, updates) {
9910
+ const existing = this.memories.get(id);
9911
+ if (!existing) return null;
9912
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9913
+ const updated = {
9914
+ ...existing,
9915
+ ...updates,
9916
+ id: existing.id,
9917
+ agentId: existing.agentId,
9918
+ createdAt: existing.createdAt,
9919
+ updatedAt: now
9920
+ };
9921
+ this.memories.set(id, updated);
9922
+ if (updates.title !== void 0 || updates.content !== void 0 || updates.tags !== void 0) {
9923
+ this.searchIndex.addDocument(id, updated);
9924
+ }
9925
+ this.dbRun(
9926
+ `UPDATE agent_memory SET
9927
+ category = ?, title = ?, content = ?, source = ?,
9928
+ importance = ?, confidence = ?, access_count = ?,
9929
+ last_accessed_at = ?, expires_at = ?, tags = ?,
9930
+ metadata = ?, updated_at = ?
9931
+ WHERE id = ?`,
9932
+ [
9933
+ updated.category,
9934
+ updated.title,
9935
+ updated.content,
9936
+ updated.source,
9937
+ updated.importance,
9938
+ updated.confidence,
9939
+ updated.accessCount,
9940
+ updated.lastAccessedAt || null,
9941
+ updated.expiresAt || null,
9942
+ JSON.stringify(updated.tags),
9943
+ JSON.stringify(updated.metadata),
9944
+ updated.updatedAt,
9945
+ id
9946
+ ]
9947
+ );
9948
+ return updated;
9949
+ }
9950
+ /** Delete a single memory entry. Returns true if it existed. */
9951
+ async deleteMemory(id) {
9952
+ const entry = this.memories.get(id);
9953
+ const existed = this.memories.delete(id);
9954
+ if (entry) this.indexRemove(entry.agentId, id);
9955
+ this.searchIndex.removeDocument(id);
9956
+ this.dbRun("DELETE FROM agent_memory WHERE id = ?", [id]);
9957
+ return existed;
9958
+ }
9959
+ /**
9960
+ * Purge every memory entry belonging to an agent — Map, per-agent
9961
+ * index, search index, and the database row. Called when an agent is
9962
+ * deleted so no orphaned memory is left behind.
9963
+ * Returns the number of entries removed.
9964
+ */
9965
+ async deleteAgentMemories(agentId) {
9966
+ const ids = Array.from(this.agentIndex.get(agentId) ?? []);
9967
+ for (const id of ids) {
9968
+ this.memories.delete(id);
9969
+ this.searchIndex.removeDocument(id);
9970
+ }
9971
+ this.agentIndex.delete(agentId);
9972
+ this.dbRun("DELETE FROM agent_memory WHERE agent_id = ?", [agentId]);
9973
+ return ids.length;
9974
+ }
9975
+ /** Retrieve a single memory entry by id. */
9976
+ async getMemory(id) {
9977
+ return this.memories.get(id);
9978
+ }
9979
+ // ─── Query Operations ───────────────────────────────
9980
+ /** Query an agent's memory with optional category/importance/source filters + text search. */
9981
+ async queryMemories(opts) {
9982
+ let results = this.getAgentMemories(opts.agentId);
9983
+ if (opts.category) results = results.filter((m) => m.category === opts.category);
9984
+ if (opts.importance) results = results.filter((m) => m.importance === opts.importance);
9985
+ if (opts.source) results = results.filter((m) => m.source === opts.source);
9986
+ if (opts.query) {
9987
+ const candidateIds = new Set(results.map((m) => m.id));
9988
+ const searchResults = this.searchIndex.search(opts.query, candidateIds);
9989
+ if (searchResults.length > 0) {
9990
+ const scored = searchResults.map((r) => {
9991
+ const entry = this.memories.get(r.id);
9992
+ return entry ? { entry, score: r.score * IMPORTANCE_WEIGHT[entry.importance] } : null;
9993
+ }).filter((r) => r !== null);
9994
+ scored.sort((a, b) => b.score - a.score);
9995
+ return scored.slice(0, opts.limit || 100).map((d) => d.entry);
9996
+ }
9997
+ return [];
9998
+ }
9999
+ results.sort((a, b) => {
10000
+ const weightDiff = IMPORTANCE_WEIGHT[b.importance] - IMPORTANCE_WEIGHT[a.importance];
10001
+ if (weightDiff !== 0) return weightDiff;
10002
+ return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
10003
+ });
10004
+ return results.slice(0, opts.limit || 100);
10005
+ }
10006
+ /** Memories created within the last N hours for an agent. */
10007
+ async getRecentMemories(agentId, hours = 24) {
10008
+ const cutoff = new Date(Date.now() - hours * 36e5).toISOString();
10009
+ return this.getAgentMemories(agentId).filter((m) => m.createdAt >= cutoff).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
10010
+ }
10011
+ // ─── Access Tracking ────────────────────────────────
10012
+ /** Bump access count + lastAccessedAt for a memory entry. */
10013
+ async recordAccess(memoryId) {
10014
+ const entry = this.memories.get(memoryId);
10015
+ if (!entry) return;
10016
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10017
+ entry.accessCount += 1;
10018
+ entry.lastAccessedAt = now;
10019
+ entry.updatedAt = now;
10020
+ this.dbRun(
10021
+ "UPDATE agent_memory SET access_count = ?, last_accessed_at = ?, updated_at = ? WHERE id = ?",
10022
+ [entry.accessCount, entry.lastAccessedAt, entry.updatedAt, memoryId]
10023
+ );
10024
+ }
10025
+ // ─── Context Generation ─────────────────────────────
10026
+ /**
10027
+ * Render an agent's memory as a markdown block for prompt injection.
10028
+ * Ranks entries by confidence × access × recency × importance, with a
10029
+ * BM25F relevance boost when a query is supplied, groups by category,
10030
+ * and truncates to ~maxTokens (estimated at 4 chars/token).
10031
+ */
10032
+ async generateMemoryContext(agentId, query, maxTokens = 1500) {
10033
+ const entries = this.getAgentMemories(agentId).filter((m) => m.confidence >= 0.1);
10034
+ if (entries.length === 0) return "";
10035
+ const now = Date.now();
10036
+ let relevanceMap;
10037
+ if (query) {
10038
+ const candidateIds = new Set(entries.map((e) => e.id));
10039
+ const searchResults = this.searchIndex.search(query, candidateIds);
10040
+ if (searchResults.length > 0) {
10041
+ relevanceMap = /* @__PURE__ */ new Map();
10042
+ const maxScore = searchResults[0].score;
10043
+ for (const r of searchResults) {
10044
+ relevanceMap.set(r.id, maxScore > 0 ? r.score / maxScore : 0);
10045
+ }
10046
+ }
10047
+ }
10048
+ const scored = entries.map((entry) => {
10049
+ const accessWeight = 1 + Math.log1p(entry.accessCount) * 0.3;
10050
+ const lastTouch = entry.lastAccessedAt || entry.createdAt;
10051
+ const ageHours = Math.max(1, (now - new Date(lastTouch).getTime()) / 36e5);
10052
+ const recencyWeight = 1 / (1 + Math.log1p(ageHours / 24) * 0.2);
10053
+ let score = entry.confidence * accessWeight * recencyWeight;
10054
+ score *= IMPORTANCE_WEIGHT[entry.importance];
10055
+ if (relevanceMap) {
10056
+ const relevance = relevanceMap.get(entry.id) || 0;
10057
+ if (relevance > 0) score *= 1 + relevance * 3;
10058
+ }
10059
+ return { entry, score };
10060
+ });
10061
+ scored.sort((a, b) => b.score - a.score);
10062
+ const grouped = /* @__PURE__ */ new Map();
10063
+ for (const { entry } of scored) {
10064
+ const group = grouped.get(entry.category) || [];
10065
+ group.push(entry);
10066
+ grouped.set(entry.category, group);
10067
+ }
10068
+ const maxChars = maxTokens * 4;
10069
+ const lines = ["## Agent Memory", ""];
10070
+ let charCount = lines.join("\n").length;
10071
+ for (const [category, categoryEntries] of Array.from(grouped.entries())) {
10072
+ const meta = MEMORY_CATEGORIES[category];
10073
+ if (!meta) continue;
10074
+ const header2 = `### ${meta.label}`;
10075
+ if (charCount + header2.length + 2 > maxChars) break;
10076
+ lines.push(header2, "");
10077
+ charCount += header2.length + 2;
10078
+ for (const entry of categoryEntries) {
10079
+ const badge = entry.importance === "critical" ? "[CRITICAL] " : entry.importance === "high" ? "[HIGH] " : "";
10080
+ const entryLine = `- **${badge}${entry.title}**: ${entry.content}`;
10081
+ if (charCount + entryLine.length + 1 > maxChars) break;
10082
+ lines.push(entryLine);
10083
+ charCount += entryLine.length + 1;
10084
+ }
10085
+ lines.push("");
10086
+ charCount += 1;
10087
+ }
10088
+ return lines.join("\n").trim();
10089
+ }
10090
+ // ─── Memory Lifecycle ───────────────────────────────
10091
+ /** Decay confidence for entries unaccessed for 7+ days. Critical entries are exempt. */
10092
+ async decayConfidence(agentId, decayRate = 0.05) {
10093
+ const cutoff = new Date(Date.now() - 7 * 864e5).toISOString();
10094
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10095
+ let decayed = 0;
10096
+ for (const entry of this.getAgentMemories(agentId)) {
10097
+ if (entry.importance === "critical") continue;
10098
+ const lastTouch = entry.lastAccessedAt || entry.createdAt;
10099
+ if (lastTouch >= cutoff) continue;
10100
+ const newConfidence = Math.max(0, entry.confidence - decayRate);
10101
+ if (newConfidence === entry.confidence) continue;
10102
+ entry.confidence = parseFloat(newConfidence.toFixed(4));
10103
+ entry.updatedAt = now;
10104
+ this.dbRun(
10105
+ "UPDATE agent_memory SET confidence = ?, updated_at = ? WHERE id = ?",
10106
+ [entry.confidence, now, entry.id]
10107
+ );
10108
+ decayed += 1;
10109
+ }
10110
+ return decayed;
10111
+ }
10112
+ /** Prune entries with confidence < 0.1 or past their expiresAt. */
10113
+ async pruneExpired(agentId) {
10114
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10115
+ const toDelete = [];
10116
+ const entries = agentId ? this.getAgentMemories(agentId) : Array.from(this.memories.values());
10117
+ for (const entry of entries) {
10118
+ const isLowConfidence = entry.confidence < 0.1;
10119
+ const isExpired = !!entry.expiresAt && entry.expiresAt <= now;
10120
+ if (isLowConfidence || isExpired) toDelete.push({ id: entry.id, agentId: entry.agentId });
10121
+ }
10122
+ for (const item of toDelete) {
10123
+ this.memories.delete(item.id);
10124
+ this.indexRemove(item.agentId, item.id);
10125
+ this.searchIndex.removeDocument(item.id);
10126
+ this.dbRun("DELETE FROM agent_memory WHERE id = ?", [item.id]);
10127
+ }
10128
+ return toDelete.length;
10129
+ }
10130
+ // ─── Statistics ─────────────────────────────────────
10131
+ /** Aggregate statistics for a specific agent's memory. */
10132
+ async getStats(agentId) {
10133
+ return this.computeStats(this.getAgentMemories(agentId));
10134
+ }
10135
+ computeStats(entries) {
10136
+ const byCategory = {};
10137
+ const byImportance = {};
10138
+ const bySource = {};
10139
+ let totalConfidence = 0;
10140
+ for (const entry of entries) {
10141
+ byCategory[entry.category] = (byCategory[entry.category] || 0) + 1;
10142
+ byImportance[entry.importance] = (byImportance[entry.importance] || 0) + 1;
10143
+ bySource[entry.source] = (bySource[entry.source] || 0) + 1;
10144
+ totalConfidence += entry.confidence;
10145
+ }
10146
+ return {
10147
+ totalEntries: entries.length,
10148
+ byCategory,
10149
+ byImportance,
10150
+ bySource,
10151
+ avgConfidence: entries.length > 0 ? parseFloat((totalConfidence / entries.length).toFixed(4)) : 0
10152
+ };
10153
+ }
10154
+ // ─── Row Mapper ─────────────────────────────────────
10155
+ rowToEntry(row) {
10156
+ return {
10157
+ id: row.id,
10158
+ agentId: row.agent_id,
10159
+ category: row.category,
10160
+ title: row.title,
10161
+ content: row.content,
10162
+ source: row.source,
10163
+ importance: row.importance,
10164
+ confidence: row.confidence,
10165
+ accessCount: row.access_count || 0,
10166
+ lastAccessedAt: row.last_accessed_at || void 0,
10167
+ expiresAt: row.expires_at || void 0,
10168
+ tags: Array.isArray(sj(row.tags)) ? sj(row.tags) : [],
10169
+ metadata: sj(row.metadata || "{}"),
10170
+ createdAt: row.created_at,
10171
+ updatedAt: row.updated_at
10172
+ };
10173
+ }
10174
+ };
8331
10175
  export {
8332
10176
  AGENT_ROLES,
8333
10177
  AccountManager,
8334
10178
  AgentDeletionService,
10179
+ AgentMemoryManager,
8335
10180
  AgentMemoryStore,
8336
10181
  AgenticMailClient,
8337
10182
  BRIDGE_OPERATOR_LIVE_WINDOW_MS,
@@ -8344,12 +10189,28 @@ export {
8344
10189
  DependencyInstaller,
8345
10190
  DomainManager,
8346
10191
  DomainPurchaser,
10192
+ ELKS_REALTIME_AUDIO_FORMATS,
8347
10193
  EmailSearchIndex,
8348
10194
  GatewayManager,
8349
10195
  InboxWatcher,
10196
+ MEMORY_CATEGORIES,
8350
10197
  MailReceiver,
8351
10198
  MailSender,
10199
+ MemorySearchIndex,
10200
+ PHONE_MAX_CONCURRENT_MISSIONS,
10201
+ PHONE_MIN_WEBHOOK_SECRET_LENGTH,
10202
+ PHONE_MISSION_STATES,
10203
+ PHONE_RATE_LIMIT_PER_HOUR,
10204
+ PHONE_RATE_LIMIT_PER_MINUTE,
10205
+ PHONE_REGION_SCOPES,
10206
+ PHONE_SERVER_MAX_ATTEMPTS,
10207
+ PHONE_SERVER_MAX_CALL_DURATION_SECONDS,
10208
+ PHONE_SERVER_MAX_COST_PER_MISSION,
10209
+ PHONE_TASK_MAX_LENGTH,
8352
10210
  PathTraversalError,
10211
+ PhoneManager,
10212
+ PhoneRateLimitError,
10213
+ PhoneWebhookAuthError,
8353
10214
  REDACTED,
8354
10215
  RELAY_PRESETS,
8355
10216
  RelayBridge,
@@ -8360,6 +10221,7 @@ export {
8360
10221
  SmsManager,
8361
10222
  SmsPoller,
8362
10223
  StalwartAdmin,
10224
+ TELEPHONY_TRANSPORT_CAPABILITIES,
8363
10225
  ThreadCache,
8364
10226
  TunnelManager,
8365
10227
  UnsafeApiUrlError,
@@ -8368,8 +10230,16 @@ export {
8368
10230
  bridgeWakeErrorMessage,
8369
10231
  bridgeWakeLastSeenAgeMs,
8370
10232
  buildApiUrl,
10233
+ buildElksAudioMessage,
10234
+ buildElksByeMessage,
10235
+ buildElksHandshakeMessages,
10236
+ buildElksInterruptMessage,
10237
+ buildElksListeningMessage,
10238
+ buildElksSendingMessage,
8371
10239
  buildInboundSecurityAdvisory,
10240
+ buildPhoneTransportConfig,
8372
10241
  classifyEmailRoute,
10242
+ classifyPhoneNumberRisk,
8373
10243
  classifyResumeError,
8374
10244
  closeDatabase,
8375
10245
  composeBridgeWakePrompt,
@@ -8384,8 +10254,10 @@ export {
8384
10254
  getOperatorEmail,
8385
10255
  getSmsProvider,
8386
10256
  hostSessionStoragePath,
10257
+ inferPhoneRegion,
8387
10258
  isInternalEmail,
8388
10259
  isLoopbackMailHost,
10260
+ isPhoneRegionAllowed,
8389
10261
  isSessionFresh,
8390
10262
  isValidPhoneNumber,
8391
10263
  loadHostSession,
@@ -8394,11 +10266,13 @@ export {
8394
10266
  normalizePhoneNumber,
8395
10267
  normalizeSubject,
8396
10268
  operatorPrefsStoragePath,
10269
+ parseElksRealtimeMessage,
8397
10270
  parseEmail,
8398
10271
  parseGoogleVoiceSms,
8399
10272
  planBridgeWake,
8400
10273
  recordToolCall,
8401
10274
  redactObject,
10275
+ redactPhoneTransportConfig,
8402
10276
  redactSecret,
8403
10277
  redactSmsConfig,
8404
10278
  resolveConfig,
@@ -8413,7 +10287,12 @@ export {
8413
10287
  setTelemetryVersion,
8414
10288
  shouldSkipBridgeWakeForLiveOperator,
8415
10289
  startRelayBridge,
10290
+ stem,
8416
10291
  threadIdFor,
10292
+ tokenize,
8417
10293
  tryJoin,
8418
- validateApiUrl
10294
+ validateApiUrl,
10295
+ validatePhoneMissionPolicy,
10296
+ validatePhoneMissionStart,
10297
+ validatePhoneTransportProfile
8419
10298
  };