@hasna/contacts 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cli/index.js +1629 -3851
  2. package/dist/db/companies.d.ts.map +1 -1
  3. package/dist/db/contacts.d.ts +0 -4
  4. package/dist/db/contacts.d.ts.map +1 -1
  5. package/dist/db/database.d.ts.map +1 -1
  6. package/dist/db/tags.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -33
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +91 -1550
  10. package/dist/mcp/index.js +81 -1938
  11. package/dist/server/index.js +12 -326
  12. package/dist/server/serve.d.ts.map +1 -1
  13. package/dist/types/index.d.ts +0 -6
  14. package/dist/types/index.d.ts.map +1 -1
  15. package/package.json +2 -1
  16. package/dist/db/coordination.d.ts +0 -30
  17. package/dist/db/coordination.d.ts.map +0 -1
  18. package/dist/db/documents.d.ts +0 -37
  19. package/dist/db/documents.d.ts.map +0 -1
  20. package/dist/db/field-history.d.ts +0 -17
  21. package/dist/db/field-history.d.ts.map +0 -1
  22. package/dist/db/freshness.d.ts +0 -24
  23. package/dist/db/freshness.d.ts.map +0 -1
  24. package/dist/db/graph.d.ts +0 -21
  25. package/dist/db/graph.d.ts.map +0 -1
  26. package/dist/db/health.d.ts +0 -40
  27. package/dist/db/health.d.ts.map +0 -1
  28. package/dist/db/identity.d.ts +0 -32
  29. package/dist/db/identity.d.ts.map +0 -1
  30. package/dist/db/job-history.d.ts +0 -29
  31. package/dist/db/job-history.d.ts.map +0 -1
  32. package/dist/db/learnings.d.ts +0 -43
  33. package/dist/db/learnings.d.ts.map +0 -1
  34. package/dist/db/org-chart.d.ts +0 -37
  35. package/dist/db/org-chart.d.ts.map +0 -1
  36. package/dist/db/signals.d.ts +0 -18
  37. package/dist/db/signals.d.ts.map +0 -1
  38. package/dist/lib/context.d.ts +0 -5
  39. package/dist/lib/context.d.ts.map +0 -1
  40. package/dist/lib/document-scanner.d.ts +0 -8
  41. package/dist/lib/document-scanner.d.ts.map +0 -1
  42. package/dist/lib/embeddings.d.ts +0 -9
  43. package/dist/lib/embeddings.d.ts.map +0 -1
  44. package/dist/lib/freshness.d.ts +0 -19
  45. package/dist/lib/freshness.d.ts.map +0 -1
  46. package/dist/lib/images.d.ts +0 -30
  47. package/dist/lib/images.d.ts.map +0 -1
  48. package/dist/lib/learning-maintenance.d.ts +0 -8
  49. package/dist/lib/learning-maintenance.d.ts.map +0 -1
  50. package/dist/lib/meeting-capture.d.ts +0 -15
  51. package/dist/lib/meeting-capture.d.ts.map +0 -1
  52. package/dist/lib/signals.d.ts +0 -9
  53. package/dist/lib/signals.d.ts.map +0 -1
  54. package/dist/lib/signature-parser.d.ts +0 -36
  55. package/dist/lib/signature-parser.d.ts.map +0 -1
  56. package/dist/lib/vault.d.ts +0 -15
  57. package/dist/lib/vault.d.ts.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,28 +1,17 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var __create = Object.create;
4
- var __getProtoOf = Object.getPrototypeOf;
5
3
  var __defProp = Object.defineProperty;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __toESM = (mod, isNodeMode, target) => {
9
- target = mod != null ? __create(__getProtoOf(mod)) : {};
10
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
- for (let key of __getOwnPropNames(mod))
12
- if (!__hasOwnProp.call(to, key))
13
- __defProp(to, key, {
14
- get: () => mod[key],
15
- enumerable: true
16
- });
17
- return to;
18
- };
4
+ var __returnValue = (v) => v;
5
+ function __exportSetter(name, newValue) {
6
+ this[name] = __returnValue.bind(null, newValue);
7
+ }
19
8
  var __export = (target, all) => {
20
9
  for (var name in all)
21
10
  __defProp(target, name, {
22
11
  get: all[name],
23
12
  enumerable: true,
24
13
  configurable: true,
25
- set: (newValue) => all[name] = () => newValue
14
+ set: __exportSetter.bind(all, name)
26
15
  });
27
16
  };
28
17
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
@@ -421,177 +410,6 @@ var init_database = __esm(() => {
421
410
  deal_id TEXT REFERENCES deals(id) ON DELETE SET NULL,
422
411
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
423
412
  );
424
- `,
425
- `
426
- -- CON-00069: temporal field history
427
- CREATE TABLE IF NOT EXISTS contact_field_history (
428
- id TEXT PRIMARY KEY,
429
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
430
- field_name TEXT NOT NULL,
431
- old_value TEXT,
432
- new_value TEXT,
433
- valid_from TEXT NOT NULL DEFAULT (datetime('now')),
434
- source TEXT,
435
- confidence TEXT NOT NULL DEFAULT 'imported' CHECK(confidence IN ('verified','inferred','imported','stale')),
436
- created_by TEXT,
437
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
438
- );
439
-
440
- -- CON-00070: job history
441
- CREATE TABLE IF NOT EXISTS job_history (
442
- id TEXT PRIMARY KEY,
443
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
444
- company_id TEXT REFERENCES companies(id) ON DELETE SET NULL,
445
- company_name TEXT NOT NULL,
446
- title TEXT,
447
- start_date TEXT,
448
- end_date TEXT,
449
- is_current INTEGER NOT NULL DEFAULT 0,
450
- inferred INTEGER NOT NULL DEFAULT 0,
451
- source TEXT,
452
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
453
- );
454
-
455
- -- CON-00071: learnings
456
- CREATE TABLE IF NOT EXISTS contact_learnings (
457
- id TEXT PRIMARY KEY,
458
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
459
- content TEXT NOT NULL,
460
- type TEXT NOT NULL DEFAULT 'fact' CHECK(type IN ('preference','fact','inference','warning','signal')),
461
- confidence INTEGER NOT NULL DEFAULT 70 CHECK(confidence BETWEEN 0 AND 100),
462
- importance INTEGER NOT NULL DEFAULT 5 CHECK(importance BETWEEN 1 AND 10),
463
- learned_by TEXT,
464
- session_id TEXT,
465
- visibility TEXT NOT NULL DEFAULT 'shared' CHECK(visibility IN ('private','shared','human')),
466
- tags TEXT NOT NULL DEFAULT '[]',
467
- confirmed_count INTEGER NOT NULL DEFAULT 0,
468
- contradicts_id TEXT REFERENCES contact_learnings(id) ON DELETE SET NULL,
469
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
470
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
471
- );
472
-
473
- -- CON-00072: coordination
474
- CREATE TABLE IF NOT EXISTS contact_locks (
475
- id TEXT PRIMARY KEY,
476
- contact_id TEXT NOT NULL UNIQUE REFERENCES contacts(id) ON DELETE CASCADE,
477
- agent_name TEXT NOT NULL,
478
- reason TEXT,
479
- acquired_at TEXT NOT NULL DEFAULT (datetime('now')),
480
- expires_at TEXT NOT NULL,
481
- session_id TEXT
482
- );
483
- CREATE TABLE IF NOT EXISTS contact_agent_activity (
484
- id TEXT PRIMARY KEY,
485
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
486
- agent_name TEXT NOT NULL,
487
- action TEXT NOT NULL,
488
- details TEXT,
489
- session_id TEXT,
490
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
491
- );
492
-
493
- -- CON-00073: relationship graph extra columns
494
- ALTER TABLE contact_relationships ADD COLUMN strength_score INTEGER NOT NULL DEFAULT 50;
495
- ALTER TABLE contact_relationships ADD COLUMN interaction_count INTEGER NOT NULL DEFAULT 0;
496
- ALTER TABLE contact_relationships ADD COLUMN last_interaction TEXT;
497
- ALTER TABLE contact_relationships ADD COLUMN relationship_status TEXT NOT NULL DEFAULT 'stable' CHECK(relationship_status IN ('warming','stable','cooling','ghost'));
498
-
499
- -- CON-00074: identity resolution
500
- CREATE TABLE IF NOT EXISTS contact_identities (
501
- id TEXT PRIMARY KEY,
502
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
503
- system TEXT NOT NULL,
504
- external_id TEXT NOT NULL,
505
- external_url TEXT,
506
- confidence TEXT NOT NULL DEFAULT 'inferred' CHECK(confidence IN ('verified','inferred')),
507
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
508
- UNIQUE(system, external_id)
509
- );
510
- ALTER TABLE contacts ADD COLUMN canonical_id TEXT;
511
-
512
- -- CON-00076: relationship signals
513
- ALTER TABLE contacts ADD COLUMN relationship_health INTEGER NOT NULL DEFAULT 50;
514
- ALTER TABLE contacts ADD COLUMN avg_response_hours REAL;
515
- ALTER TABLE contacts ADD COLUMN preferred_channel TEXT;
516
- ALTER TABLE contacts ADD COLUMN engagement_status TEXT NOT NULL DEFAULT 'new' CHECK(engagement_status IN ('warming','stable','cooling','ghost','new'));
517
- ALTER TABLE contacts ADD COLUMN interaction_count_30d INTEGER NOT NULL DEFAULT 0;
518
- ALTER TABLE contacts ADD COLUMN interaction_count_90d INTEGER NOT NULL DEFAULT 0;
519
-
520
- -- CON-00079: freshness scoring
521
- CREATE TABLE IF NOT EXISTS contact_field_confidence (
522
- id TEXT PRIMARY KEY,
523
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
524
- field_name TEXT NOT NULL,
525
- confidence TEXT NOT NULL DEFAULT 'imported' CHECK(confidence IN ('verified','inferred','imported','stale')),
526
- source TEXT,
527
- last_verified_at TEXT NOT NULL DEFAULT (datetime('now')),
528
- UNIQUE(contact_id, field_name)
529
- );
530
-
531
- -- CON-00080: org chart
532
- CREATE TABLE IF NOT EXISTS org_chart_edges (
533
- id TEXT PRIMARY KEY,
534
- company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
535
- contact_a_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
536
- contact_b_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
537
- edge_type TEXT NOT NULL CHECK(edge_type IN ('reports_to','manages','collaborates_with','peer')),
538
- inferred INTEGER NOT NULL DEFAULT 0,
539
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
540
- UNIQUE(company_id, contact_a_id, contact_b_id, edge_type)
541
- );
542
- CREATE TABLE IF NOT EXISTS deal_contact_roles (
543
- id TEXT PRIMARY KEY,
544
- deal_id TEXT NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
545
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
546
- account_role TEXT NOT NULL CHECK(account_role IN ('economic_buyer','technical_evaluator','champion','blocker','influencer','user','sponsor','other')),
547
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
548
- UNIQUE(deal_id, contact_id)
549
- );
550
-
551
- -- CON-00075: embeddings
552
- CREATE TABLE IF NOT EXISTS contact_embeddings (
553
- contact_id TEXT PRIMARY KEY REFERENCES contacts(id) ON DELETE CASCADE,
554
- embedding TEXT NOT NULL,
555
- model TEXT NOT NULL DEFAULT 'tfidf',
556
- embedded_text TEXT,
557
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
558
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
559
- );
560
- `,
561
- `
562
- ALTER TABLE contacts ADD COLUMN sensitivity TEXT NOT NULL DEFAULT 'normal' CHECK(sensitivity IN ('normal','confidential','restricted'));
563
-
564
- CREATE TABLE IF NOT EXISTS contact_documents (
565
- id TEXT PRIMARY KEY,
566
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
567
- doc_type TEXT NOT NULL,
568
- label TEXT,
569
- encrypted_value TEXT NOT NULL,
570
- iv TEXT NOT NULL,
571
- encrypted_file_path TEXT,
572
- metadata TEXT NOT NULL DEFAULT '{}',
573
- expires_at TEXT,
574
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
575
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
576
- );
577
-
578
- CREATE TABLE IF NOT EXISTS contact_health (
579
- id TEXT PRIMARY KEY,
580
- contact_id TEXT NOT NULL UNIQUE REFERENCES contacts(id) ON DELETE CASCADE,
581
- blood_type TEXT,
582
- allergies TEXT NOT NULL DEFAULT '[]',
583
- medical_conditions TEXT NOT NULL DEFAULT '[]',
584
- medications TEXT NOT NULL DEFAULT '[]',
585
- emergency_contacts TEXT NOT NULL DEFAULT '[]',
586
- health_insurance_provider TEXT,
587
- health_insurance_id TEXT,
588
- primary_physician TEXT,
589
- primary_physician_phone TEXT,
590
- organ_donor INTEGER NOT NULL DEFAULT 0,
591
- notes TEXT,
592
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
593
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
594
- );
595
413
  `
596
414
  ];
597
415
  });
@@ -673,7 +491,6 @@ __export(exports_contacts, {
673
491
  getContactProjectIds: () => getContactProjectIds,
674
492
  getContactByEmail: () => getContactByEmail,
675
493
  getContact: () => getContact,
676
- findOrCreateContact: () => findOrCreateContact,
677
494
  deleteContact: () => deleteContact,
678
495
  createContact: () => createContact,
679
496
  autoLinkContactToCompany: () => autoLinkContactToCompany,
@@ -691,7 +508,6 @@ function rowToContact(row) {
691
508
  follow_up_at: row.follow_up_at ?? null,
692
509
  archived: !!row.archived,
693
510
  project_id: row.project_id ?? null,
694
- sensitivity: row.sensitivity ?? "normal",
695
511
  do_not_contact: !!row.do_not_contact,
696
512
  priority: row.priority ?? 3,
697
513
  timezone: row.timezone ?? null
@@ -779,8 +595,8 @@ function createContact(input, db) {
779
595
  const firstName = input.first_name ?? "";
780
596
  const lastName = input.last_name ?? "";
781
597
  const displayName = input.display_name ?? (firstName || lastName ? `${firstName} ${lastName}`.trim() : "Unnamed Contact");
782
- d.run(`INSERT INTO contacts (id, first_name, last_name, display_name, nickname, avatar_url, notes, birthday, company_id, job_title, source, custom_fields, last_contacted_at, website, preferred_contact_method, status, follow_up_at, project_id, sensitivity, do_not_contact, priority, timezone, created_at, updated_at)
783
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
598
+ d.run(`INSERT INTO contacts (id, first_name, last_name, display_name, nickname, avatar_url, notes, birthday, company_id, job_title, source, custom_fields, last_contacted_at, website, preferred_contact_method, status, follow_up_at, project_id, do_not_contact, priority, timezone, created_at, updated_at)
599
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
784
600
  id,
785
601
  firstName,
786
602
  lastName,
@@ -799,7 +615,6 @@ function createContact(input, db) {
799
615
  input.status ?? "active",
800
616
  input.follow_up_at ?? null,
801
617
  input.project_id ?? null,
802
- input.sensitivity ?? "normal",
803
618
  input.do_not_contact ? 1 : 0,
804
619
  input.priority ?? 3,
805
620
  input.timezone ?? null,
@@ -848,7 +663,6 @@ function listContacts(opts = {}, db) {
848
663
  order_by = "display_name",
849
664
  order_dir = "asc",
850
665
  include_dnc = false,
851
- include_restricted = false,
852
666
  priority_min,
853
667
  updated_since
854
668
  } = opts;
@@ -859,9 +673,6 @@ function listContacts(opts = {}, db) {
859
673
  if (!include_dnc) {
860
674
  conditions.push("c.do_not_contact = 0");
861
675
  }
862
- if (!include_restricted) {
863
- conditions.push("c.sensitivity != 'restricted'");
864
- }
865
676
  if (company_id) {
866
677
  conditions.push("c.company_id = ?");
867
678
  params.push(company_id);
@@ -990,10 +801,6 @@ function updateContact(id, input, db) {
990
801
  setClauses.push("project_id = ?");
991
802
  params.push(input.project_id);
992
803
  }
993
- if (input.sensitivity !== undefined) {
994
- setClauses.push("sensitivity = ?");
995
- params.push(input.sensitivity);
996
- }
997
804
  if (input.do_not_contact !== undefined) {
998
805
  setClauses.push("do_not_contact = ?");
999
806
  params.push(input.do_not_contact ? 1 : 0);
@@ -1041,26 +848,26 @@ function searchContacts(query, db) {
1041
848
  const ftsRows = d.query(`
1042
849
  SELECT c.* FROM contacts c
1043
850
  JOIN contacts_fts fts ON fts.id = c.id
1044
- WHERE contacts_fts MATCH ? AND c.archived = 0 AND c.sensitivity != 'restricted'
851
+ WHERE contacts_fts MATCH ? AND c.archived = 0
1045
852
  ORDER BY rank
1046
853
  LIMIT 50
1047
854
  `).all(`"${query.replace(/"/g, '""')}"*`);
1048
855
  const emailRows = d.query(`
1049
856
  SELECT DISTINCT c.* FROM contacts c
1050
857
  JOIN emails e ON e.contact_id = c.id
1051
- WHERE e.address LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
858
+ WHERE e.address LIKE ? AND c.archived = 0
1052
859
  LIMIT 20
1053
860
  `).all(`%${query}%`);
1054
861
  const phoneRows = d.query(`
1055
862
  SELECT DISTINCT c.* FROM contacts c
1056
863
  JOIN phones p ON p.contact_id = c.id
1057
- WHERE p.number LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
864
+ WHERE p.number LIKE ? AND c.archived = 0
1058
865
  LIMIT 20
1059
866
  `).all(`%${query}%`);
1060
867
  const companyRows = d.query(`
1061
868
  SELECT DISTINCT c.* FROM contacts c
1062
869
  JOIN companies co ON co.id = c.company_id
1063
- WHERE co.name LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
870
+ WHERE co.name LIKE ? AND c.archived = 0
1064
871
  LIMIT 20
1065
872
  `).all(`%${query}%`);
1066
873
  const seen = new Set;
@@ -1213,25 +1020,6 @@ function listColdContacts(days, db) {
1213
1020
  LIMIT 100`).all(`-${days}`);
1214
1021
  return rows.map((row) => loadContactDetails(d, rowToContact(row)));
1215
1022
  }
1216
- async function findOrCreateContact(input, db) {
1217
- const d = db || getDatabase();
1218
- const emailAddresses = (input.emails ?? []).map((e) => e.address);
1219
- for (const addr of emailAddresses) {
1220
- const emailRow = d.query(`SELECT contact_id FROM emails WHERE LOWER(address) = LOWER(?) AND contact_id IS NOT NULL LIMIT 1`).get(addr);
1221
- if (emailRow) {
1222
- return { contact: getContact(emailRow.contact_id, d), created: false };
1223
- }
1224
- }
1225
- const nameQuery = input.display_name ?? (input.first_name || input.last_name ? `${input.first_name ?? ""} ${input.last_name ?? ""}`.trim() : null);
1226
- if (nameQuery) {
1227
- const results = searchContacts(nameQuery, d);
1228
- if (results.length > 0 && results[0]) {
1229
- return { contact: results[0], created: false };
1230
- }
1231
- }
1232
- const contact = createContact(input, d);
1233
- return { contact, created: true };
1234
- }
1235
1023
  function autoLinkContactToCompany(contactId, db) {
1236
1024
  const d = db || getDatabase();
1237
1025
  const row = d.query(`SELECT * FROM contacts WHERE id = ?`).get(contactId);
@@ -1282,96 +1070,6 @@ var init_contacts = __esm(() => {
1282
1070
  init_activity();
1283
1071
  });
1284
1072
 
1285
- // src/db/events.ts
1286
- var exports_events = {};
1287
- __export(exports_events, {
1288
- logEvent: () => logEvent,
1289
- listEvents: () => listEvents,
1290
- getEvent: () => getEvent,
1291
- deleteEvent: () => deleteEvent
1292
- });
1293
- function rowToEvent(row) {
1294
- let contact_ids = [];
1295
- try {
1296
- contact_ids = JSON.parse(row.contact_ids);
1297
- } catch {
1298
- contact_ids = [];
1299
- }
1300
- return {
1301
- id: row.id,
1302
- title: row.title,
1303
- type: row.type,
1304
- event_date: row.event_date,
1305
- duration_min: row.duration_min,
1306
- contact_ids,
1307
- company_id: row.company_id,
1308
- notes: row.notes,
1309
- outcome: row.outcome,
1310
- deal_id: row.deal_id,
1311
- created_at: row.created_at
1312
- };
1313
- }
1314
- function logEvent(input, db) {
1315
- const d = db || getDatabase();
1316
- const id = uuid();
1317
- const timestamp = now();
1318
- d.run(`INSERT INTO events (id, title, type, event_date, duration_min, contact_ids, company_id, notes, outcome, deal_id, created_at)
1319
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1320
- id,
1321
- input.title,
1322
- input.type ?? "meeting",
1323
- input.event_date,
1324
- input.duration_min ?? null,
1325
- JSON.stringify(input.contact_ids ?? []),
1326
- input.company_id ?? null,
1327
- input.notes ?? null,
1328
- input.outcome ?? null,
1329
- input.deal_id ?? null,
1330
- timestamp
1331
- ]);
1332
- return rowToEvent(d.query(`SELECT * FROM events WHERE id = ?`).get(id));
1333
- }
1334
- function getEvent(id, db) {
1335
- const d = db || getDatabase();
1336
- const row = d.query(`SELECT * FROM events WHERE id = ?`).get(id);
1337
- return row ? rowToEvent(row) : null;
1338
- }
1339
- function listEvents(opts = {}, db) {
1340
- const d = db || getDatabase();
1341
- const conditions = [];
1342
- const params = [];
1343
- if (opts.contact_id) {
1344
- conditions.push("contact_ids LIKE ?");
1345
- params.push(`%${opts.contact_id}%`);
1346
- }
1347
- if (opts.company_id) {
1348
- conditions.push("company_id = ?");
1349
- params.push(opts.company_id);
1350
- }
1351
- if (opts.type) {
1352
- conditions.push("type = ?");
1353
- params.push(opts.type);
1354
- }
1355
- if (opts.date_from) {
1356
- conditions.push("event_date >= ?");
1357
- params.push(opts.date_from);
1358
- }
1359
- if (opts.date_to) {
1360
- conditions.push("event_date <= ?");
1361
- params.push(opts.date_to);
1362
- }
1363
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1364
- const rows = d.query(`SELECT * FROM events ${where} ORDER BY event_date DESC`).all(...params);
1365
- return rows.map(rowToEvent);
1366
- }
1367
- function deleteEvent(id, db) {
1368
- const d = db || getDatabase();
1369
- d.run(`DELETE FROM events WHERE id = ?`, [id]);
1370
- }
1371
- var init_events = __esm(() => {
1372
- init_database();
1373
- });
1374
-
1375
1073
  // src/mcp/index.ts
1376
1074
  init_database();
1377
1075
  init_contacts();
@@ -3581,1140 +3279,80 @@ function deleteDeal(id, db) {
3581
3279
  d.run(`DELETE FROM deals WHERE id = ?`, [id]);
3582
3280
  }
3583
3281
 
3584
- // src/mcp/index.ts
3585
- init_events();
3586
-
3587
- // src/db/field-history.ts
3588
- init_database();
3589
- function getFieldHistory(contactId, fieldName, db) {
3590
- const _db2 = db || getDatabase();
3591
- if (fieldName) {
3592
- return _db2.query(`SELECT * FROM contact_field_history WHERE contact_id=? AND field_name=? ORDER BY valid_from DESC`).all(contactId, fieldName);
3593
- }
3594
- return _db2.query(`SELECT * FROM contact_field_history WHERE contact_id=? ORDER BY valid_from DESC`).all(contactId);
3595
- }
3596
- function getContactAt(contactId, timestamp, db) {
3597
- const _db2 = db || getDatabase();
3598
- const rows = _db2.query(`SELECT field_name, new_value FROM contact_field_history WHERE contact_id=? AND valid_from<=? ORDER BY valid_from ASC`).all(contactId, timestamp);
3599
- const result = {};
3600
- for (const r of rows) {
3601
- if (r.new_value != null)
3602
- result[r.field_name] = r.new_value;
3603
- }
3604
- return result;
3605
- }
3606
-
3607
- // src/db/job-history.ts
3282
+ // src/db/events.ts
3608
3283
  init_database();
3609
- function rowToJob(r) {
3610
- return { ...r, is_current: !!r["is_current"], inferred: !!r["inferred"] };
3611
- }
3612
- function addJobEntry(contactId, input, db) {
3613
- const _db2 = db || getDatabase();
3614
- if (input.is_current) {
3615
- _db2.query(`UPDATE job_history SET is_current=0, end_date=COALESCE(end_date,?) WHERE contact_id=? AND is_current=1`).run(new Date().toISOString().slice(0, 10), contactId);
3284
+ function rowToEvent(row) {
3285
+ let contact_ids = [];
3286
+ try {
3287
+ contact_ids = JSON.parse(row.contact_ids);
3288
+ } catch {
3289
+ contact_ids = [];
3616
3290
  }
3617
- const id = uuid();
3618
- _db2.query(`INSERT INTO job_history(id,contact_id,company_id,company_name,title,start_date,end_date,is_current,inferred,source,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.company_id || null, input.company_name, input.title || null, input.start_date || null, input.end_date || null, input.is_current ? 1 : 0, input.inferred ? 1 : 0, input.source || null, now());
3619
- return rowToJob(_db2.query(`SELECT * FROM job_history WHERE id=?`).get(id));
3620
- }
3621
- function getJobHistory(contactId, db) {
3622
- const _db2 = db || getDatabase();
3623
- return _db2.query(`SELECT * FROM job_history WHERE contact_id=? ORDER BY is_current DESC, start_date DESC`).all(contactId).map(rowToJob);
3624
- }
3625
-
3626
- // src/db/learnings.ts
3627
- init_database();
3628
- function rowToLearning(r) {
3629
- return { ...r, tags: JSON.parse(r["tags"] || "[]") };
3291
+ return {
3292
+ id: row.id,
3293
+ title: row.title,
3294
+ type: row.type,
3295
+ event_date: row.event_date,
3296
+ duration_min: row.duration_min,
3297
+ contact_ids,
3298
+ company_id: row.company_id,
3299
+ notes: row.notes,
3300
+ outcome: row.outcome,
3301
+ deal_id: row.deal_id,
3302
+ created_at: row.created_at
3303
+ };
3630
3304
  }
3631
- function saveLearning(contactId, input, db) {
3632
- const _db2 = db || getDatabase();
3305
+ function logEvent(input, db) {
3306
+ const d = db || getDatabase();
3633
3307
  const id = uuid();
3634
- _db2.query(`INSERT INTO contact_learnings(id,contact_id,content,type,confidence,importance,learned_by,session_id,visibility,tags,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.content, input.type || "fact", input.confidence ?? 70, input.importance ?? 5, input.learned_by || null, input.session_id || null, input.visibility || "shared", JSON.stringify(input.tags || []), now(), now());
3635
- return rowToLearning(_db2.query(`SELECT * FROM contact_learnings WHERE id=?`).get(id));
3308
+ const timestamp = now();
3309
+ d.run(`INSERT INTO events (id, title, type, event_date, duration_min, contact_ids, company_id, notes, outcome, deal_id, created_at)
3310
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
3311
+ id,
3312
+ input.title,
3313
+ input.type ?? "meeting",
3314
+ input.event_date,
3315
+ input.duration_min ?? null,
3316
+ JSON.stringify(input.contact_ids ?? []),
3317
+ input.company_id ?? null,
3318
+ input.notes ?? null,
3319
+ input.outcome ?? null,
3320
+ input.deal_id ?? null,
3321
+ timestamp
3322
+ ]);
3323
+ return rowToEvent(d.query(`SELECT * FROM events WHERE id = ?`).get(id));
3636
3324
  }
3637
- function getLearnings(contactId, opts = {}, db) {
3638
- const _db2 = db || getDatabase();
3639
- let sql = `SELECT * FROM contact_learnings WHERE contact_id=?`;
3640
- const params = [contactId];
3641
- if (opts.type) {
3642
- sql += ` AND type=?`;
3643
- params.push(opts.type);
3644
- }
3645
- if (opts.min_importance) {
3646
- sql += ` AND importance>=?`;
3647
- params.push(opts.min_importance);
3325
+ function listEvents(opts = {}, db) {
3326
+ const d = db || getDatabase();
3327
+ const conditions = [];
3328
+ const params = [];
3329
+ if (opts.contact_id) {
3330
+ conditions.push("contact_ids LIKE ?");
3331
+ params.push(`%${opts.contact_id}%`);
3648
3332
  }
3649
- if (opts.visibility) {
3650
- sql += ` AND visibility=?`;
3651
- params.push(opts.visibility);
3333
+ if (opts.company_id) {
3334
+ conditions.push("company_id = ?");
3335
+ params.push(opts.company_id);
3652
3336
  }
3653
- sql += ` ORDER BY importance DESC, confidence DESC`;
3654
- return _db2.query(sql).all(...params).map(rowToLearning);
3655
- }
3656
- function searchLearnings(query, opts = {}, db) {
3657
- const _db2 = db || getDatabase();
3658
- let sql = `SELECT * FROM contact_learnings WHERE content LIKE ?`;
3659
- const params = [`%${query}%`];
3660
3337
  if (opts.type) {
3661
- sql += ` AND type=?`;
3338
+ conditions.push("type = ?");
3662
3339
  params.push(opts.type);
3663
3340
  }
3664
- if (opts.contact_id) {
3665
- sql += ` AND contact_id=?`;
3666
- params.push(opts.contact_id);
3341
+ if (opts.date_from) {
3342
+ conditions.push("event_date >= ?");
3343
+ params.push(opts.date_from);
3667
3344
  }
3668
- sql += ` ORDER BY importance DESC, confidence DESC LIMIT 50`;
3669
- return _db2.query(sql).all(...params).map(rowToLearning);
3670
- }
3671
- function confirmLearning(learningId, _agentName, db) {
3672
- const _db2 = db || getDatabase();
3673
- _db2.query(`UPDATE contact_learnings SET confirmed_count=confirmed_count+1, confidence=MIN(100,confidence+10), updated_at=? WHERE id=?`).run(now(), learningId);
3345
+ if (opts.date_to) {
3346
+ conditions.push("event_date <= ?");
3347
+ params.push(opts.date_to);
3348
+ }
3349
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3350
+ const rows = d.query(`SELECT * FROM events ${where} ORDER BY event_date DESC`).all(...params);
3351
+ return rows.map(rowToEvent);
3674
3352
  }
3675
- function decayLearnings(db) {
3676
- const _db2 = db || getDatabase();
3677
- const cutoff = new Date(Date.now() - 30 * 86400000).toISOString();
3678
- const result = _db2.query(`UPDATE contact_learnings SET confidence=MAX(10,confidence-5), updated_at=? WHERE confirmed_count=0 AND created_at<? AND confidence>10`).run(now(), cutoff);
3679
- return result.changes || 0;
3680
- }
3681
-
3682
- // src/db/coordination.ts
3683
- init_database();
3684
- function acquireLock(contactId, agentName, ttlSeconds = 300, reason, sessionId, db) {
3685
- const _db2 = db || getDatabase();
3686
- cleanExpiredLocks(_db2);
3687
- const existing = _db2.query(`SELECT * FROM contact_locks WHERE contact_id=?`).get(contactId);
3688
- if (existing)
3689
- return { acquired: false, held_by: existing.agent_name, lock: existing };
3690
- const id = uuid();
3691
- const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString();
3692
- _db2.query(`INSERT INTO contact_locks(id,contact_id,agent_name,reason,acquired_at,expires_at,session_id) VALUES(?,?,?,?,?,?,?)`).run(id, contactId, agentName, reason || null, now(), expiresAt, sessionId || null);
3693
- return {
3694
- acquired: true,
3695
- lock: _db2.query(`SELECT * FROM contact_locks WHERE id=?`).get(id)
3696
- };
3697
- }
3698
- function releaseLock(contactId, agentName, db) {
3699
- const _db2 = db || getDatabase();
3700
- const result = _db2.query(`DELETE FROM contact_locks WHERE contact_id=? AND agent_name=?`).run(contactId, agentName);
3701
- return (result.changes || 0) > 0;
3702
- }
3703
- function checkLock(contactId, db) {
3704
- const _db2 = db || getDatabase();
3705
- cleanExpiredLocks(_db2);
3706
- return _db2.query(`SELECT * FROM contact_locks WHERE contact_id=?`).get(contactId);
3707
- }
3708
- function cleanExpiredLocks(db) {
3709
- const _db2 = db || getDatabase();
3710
- _db2.query(`DELETE FROM contact_locks WHERE expires_at<?`).run(now());
3711
- }
3712
- function logAgentActivity(contactId, agentName, action, details, sessionId, db) {
3713
- const _db2 = db || getDatabase();
3714
- _db2.query(`INSERT INTO contact_agent_activity(id,contact_id,agent_name,action,details,session_id,created_at) VALUES(?,?,?,?,?,?,?)`).run(uuid(), contactId, agentName, action, details || null, sessionId || null, now());
3715
- }
3716
- function getAgentActivity(contactId, limit = 20, db) {
3717
- const _db2 = db || getDatabase();
3718
- return _db2.query(`SELECT * FROM contact_agent_activity WHERE contact_id=? ORDER BY created_at DESC LIMIT ?`).all(contactId, limit);
3719
- }
3720
-
3721
- // src/db/graph.ts
3722
- init_database();
3723
- function computeRelationshipStrength(contactId, db) {
3724
- const _db2 = db || getDatabase();
3725
- const contact = _db2.query(`SELECT last_contacted_at, interaction_count_30d, interaction_count_90d FROM contacts WHERE id=?`).get(contactId);
3726
- if (!contact)
3727
- return 0;
3728
- let score = 50;
3729
- if (contact.last_contacted_at) {
3730
- const days = Math.floor((Date.now() - new Date(contact.last_contacted_at).getTime()) / 86400000);
3731
- score += days < 7 ? 30 : days < 30 ? 20 : days < 90 ? 5 : -20;
3732
- } else {
3733
- score -= 20;
3734
- }
3735
- score += Math.min(20, (contact.interaction_count_30d || 0) * 4);
3736
- return Math.max(0, Math.min(100, score));
3737
- }
3738
- function findWarmPath(fromContactId, toContactId, db) {
3739
- const _db2 = db || getDatabase();
3740
- const visited = new Set([fromContactId]);
3741
- const queue = [{ id: fromContactId, path: [] }];
3742
- while (queue.length) {
3743
- const item = queue.shift();
3744
- const { id, path } = item;
3745
- if (id === toContactId)
3746
- return path;
3747
- if (path.length >= 4)
3748
- continue;
3749
- const neighbors = _db2.query(`SELECT cr.*, c.display_name FROM contact_relationships cr JOIN contacts c ON (CASE WHEN cr.contact_a_id=? THEN cr.contact_b_id ELSE cr.contact_a_id END)=c.id WHERE (cr.contact_a_id=? OR cr.contact_b_id=?) LIMIT 20`).all(id, id, id);
3750
- for (const n of neighbors) {
3751
- const nextId = n.contact_a_id === id ? n.contact_b_id : n.contact_a_id;
3752
- if (visited.has(nextId))
3753
- continue;
3754
- visited.add(nextId);
3755
- queue.push({
3756
- id: nextId,
3757
- path: [
3758
- ...path,
3759
- { contact_id: nextId, display_name: n.display_name, strength: n.strength_score || 50 }
3760
- ]
3761
- });
3762
- }
3763
- }
3764
- return [];
3765
- }
3766
- function findConnectionsAtCompany(companyId, db) {
3767
- const _db2 = db || getDatabase();
3768
- return _db2.query(`SELECT c.id as contact_id, c.display_name, c.job_title, c.relationship_health as strength FROM contacts c WHERE c.company_id=? AND c.archived=0 ORDER BY c.relationship_health DESC`).all(companyId);
3769
- }
3770
- function detectCoolingRelationships(db) {
3771
- const _db2 = db || getDatabase();
3772
- const cutoff = new Date(Date.now() - 45 * 86400000).toISOString();
3773
- return _db2.query(`SELECT id as contact_id, display_name, CAST((julianday('now') - julianday(last_contacted_at)) AS INTEGER) as days_since FROM contacts WHERE last_contacted_at IS NOT NULL AND last_contacted_at < ? AND engagement_status != 'ghost' AND archived=0 ORDER BY last_contacted_at ASC LIMIT 50`).all(cutoff);
3774
- }
3775
-
3776
- // src/db/identity.ts
3777
- init_database();
3778
- function addIdentity(contactId, system, externalId, externalUrl, confidence = "inferred", db) {
3779
- const _db2 = db || getDatabase();
3780
- const id = uuid();
3781
- _db2.query(`INSERT OR REPLACE INTO contact_identities(id,contact_id,system,external_id,external_url,confidence,created_at) VALUES(?,?,?,?,?,?,?)`).run(id, contactId, system, externalId, externalUrl || null, confidence, now());
3782
- return _db2.query(`SELECT * FROM contact_identities WHERE id=?`).get(id);
3783
- }
3784
- function resolveByPartial(partial, db) {
3785
- const _db2 = db || getDatabase();
3786
- const matches = new Map;
3787
- const addMatch = (id, name, title, score, reason) => {
3788
- const existing = matches.get(id);
3789
- if (existing) {
3790
- existing.confidence_score = Math.min(100, existing.confidence_score + score);
3791
- existing.match_reasons.push(reason);
3792
- } else {
3793
- matches.set(id, {
3794
- contact: { id, display_name: name, job_title: title },
3795
- confidence_score: score,
3796
- match_reasons: [reason]
3797
- });
3798
- }
3799
- };
3800
- if (partial.email) {
3801
- const rows = _db2.query(`SELECT c.id, c.display_name, c.job_title FROM contacts c JOIN emails e ON c.id=e.contact_id WHERE LOWER(e.address)=LOWER(?)`).all(partial.email);
3802
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 90, `email match: ${partial.email}`));
3803
- }
3804
- if (partial.linkedin_url) {
3805
- const rows = _db2.query(`SELECT c.id, c.display_name, c.job_title FROM contacts c JOIN social_profiles sp ON c.id=sp.contact_id WHERE sp.platform='linkedin' AND sp.url LIKE ?`).all(`%${partial.linkedin_url.split("/").pop()}%`);
3806
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 85, `linkedin match`));
3807
- }
3808
- if (partial.name) {
3809
- const rows = _db2.query(`SELECT id, display_name, job_title FROM contacts WHERE display_name LIKE ? AND archived=0 LIMIT 10`).all(`%${partial.name}%`);
3810
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 40, `name match: ${partial.name}`));
3811
- }
3812
- return Array.from(matches.values()).sort((a, b) => b.confidence_score - a.confidence_score);
3813
- }
3814
- function getIdentities(contactId, db) {
3815
- const _db2 = db || getDatabase();
3816
- return _db2.query(`SELECT * FROM contact_identities WHERE contact_id=? ORDER BY created_at DESC`).all(contactId);
3817
- }
3818
-
3819
- // src/lib/embeddings.ts
3820
- init_database();
3821
- function tokenize(text) {
3822
- return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((t) => t.length > 2);
3823
- }
3824
- function buildTfIdf(tokens) {
3825
- const freq = new Map;
3826
- for (const t of tokens)
3827
- freq.set(t, (freq.get(t) || 0) + 1);
3828
- const max = Math.max(...freq.values(), 1);
3829
- const result = new Map;
3830
- freq.forEach((v, k) => result.set(k, v / max));
3831
- return result;
3832
- }
3833
- function cosineSimilarity(a, b) {
3834
- let dot = 0, normA = 0, normB = 0;
3835
- a.forEach((v, k) => {
3836
- if (b.has(k))
3837
- dot += v * b.get(k);
3838
- normA += v * v;
3839
- });
3840
- b.forEach((v) => normB += v * v);
3841
- return normA && normB ? dot / (Math.sqrt(normA) * Math.sqrt(normB)) : 0;
3842
- }
3843
- function buildContactEmbeddingText(contact) {
3844
- const tags = contact.tags ?? [];
3845
- const socialProfiles = contact.social_profiles ?? [];
3846
- const company = contact.company;
3847
- const parts = [
3848
- contact.display_name,
3849
- contact.job_title,
3850
- contact.notes,
3851
- company?.name,
3852
- company?.industry,
3853
- ...tags.map((t) => t.name),
3854
- ...socialProfiles.map((s) => s.platform)
3855
- ].filter(Boolean);
3856
- return parts.join(" ");
3857
- }
3858
- async function embedContact(contactId, db) {
3859
- const { getContact: getContact2 } = await Promise.resolve().then(() => (init_contacts(), exports_contacts));
3860
- const _db2 = db || getDatabase();
3861
- const contact = getContact2(contactId, _db2);
3862
- const text = buildContactEmbeddingText(contact);
3863
- const tokens = tokenize(text);
3864
- const tfidf = buildTfIdf(tokens);
3865
- const embedding = JSON.stringify(Array.from(tfidf.entries()).sort((a, b) => b[1] - a[1]).slice(0, 100));
3866
- _db2.query(`INSERT OR REPLACE INTO contact_embeddings(contact_id, embedding, model, embedded_text, created_at, updated_at) VALUES(?,?,'tfidf',?,?,?)`).run(contactId, embedding, text.slice(0, 500), now(), now());
3867
- }
3868
- async function embedAllContacts(db) {
3869
- const _db2 = db || getDatabase();
3870
- const contacts = _db2.query(`SELECT id FROM contacts WHERE archived=0`).all();
3871
- for (const c of contacts) {
3872
- try {
3873
- await embedContact(c.id, _db2);
3874
- } catch {}
3875
- }
3876
- return contacts.length;
3877
- }
3878
- function semanticSearch(query, limit = 10, db) {
3879
- const _db2 = db || getDatabase();
3880
- const queryTokens = buildTfIdf(tokenize(query));
3881
- let embeddings = [];
3882
- try {
3883
- embeddings = _db2.query(`SELECT contact_id, embedding FROM contact_embeddings`).all();
3884
- } catch {
3885
- return [];
3886
- }
3887
- const results = embeddings.map((e) => {
3888
- try {
3889
- const emb = new Map(JSON.parse(e.embedding));
3890
- return { contact_id: e.contact_id, score: cosineSimilarity(queryTokens, emb) };
3891
- } catch {
3892
- return { contact_id: e.contact_id, score: 0 };
3893
- }
3894
- }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score).slice(0, limit);
3895
- return results;
3896
- }
3897
-
3898
- // src/db/signals.ts
3899
- init_database();
3900
- function getRelationshipSignals(contactId, db) {
3901
- const _db2 = db || getDatabase();
3902
- const row = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE id=?`).get(contactId);
3903
- if (!row)
3904
- return [];
3905
- const daysSince = row.last_contacted_at ? Math.floor((Date.now() - new Date(row.last_contacted_at).getTime()) / 86400000) : null;
3906
- const signals = [];
3907
- const cnt = row.interaction_count_30d || 0;
3908
- const health = row.relationship_health ?? 50;
3909
- if (daysSince === null || daysSince > 180) {
3910
- signals.push({ ...row, signal_type: "ghost", days_since_contact: daysSince, reason: "No contact in 180+ days or never contacted" });
3911
- } else if (daysSince > 60 && cnt === 0) {
3912
- signals.push({ ...row, signal_type: "cooling", days_since_contact: daysSince, reason: `No contact in ${daysSince} days, no recent interactions` });
3913
- } else if (cnt > 3 && health > 70) {
3914
- signals.push({ ...row, signal_type: "warming", days_since_contact: daysSince, reason: `${cnt} interactions in last 30 days, health score ${health}` });
3915
- } else {
3916
- signals.push({ ...row, signal_type: "healthy", days_since_contact: daysSince, reason: `Last contact ${daysSince}d ago, ${cnt} interactions in 30d` });
3917
- }
3918
- return signals;
3919
- }
3920
- function getGhostContacts(db) {
3921
- const _db2 = db || getDatabase();
3922
- const rows = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE (last_contacted_at IS NULL OR julianday('now') - julianday(last_contacted_at) > 180) AND archived=0 ORDER BY last_contacted_at ASC LIMIT 50`).all();
3923
- return rows.map((r) => ({
3924
- ...r,
3925
- signal_type: "ghost",
3926
- days_since_contact: r.last_contacted_at ? Math.floor((Date.now() - new Date(r.last_contacted_at).getTime()) / 86400000) : null,
3927
- reason: "No contact in 180+ days or never contacted"
3928
- }));
3929
- }
3930
- function getWarmingContacts(db) {
3931
- const _db2 = db || getDatabase();
3932
- const rows = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE interaction_count_30d > 2 AND relationship_health > 60 AND archived=0 ORDER BY relationship_health DESC LIMIT 50`).all();
3933
- return rows.map((r) => ({
3934
- ...r,
3935
- signal_type: "warming",
3936
- days_since_contact: r.last_contacted_at ? Math.floor((Date.now() - new Date(r.last_contacted_at).getTime()) / 86400000) : null,
3937
- reason: `${r.interaction_count_30d} interactions in last 30 days`
3938
- }));
3939
- }
3940
- function recomputeAllSignals(db) {
3941
- const _db2 = db || getDatabase();
3942
- _db2.query(`
3943
- UPDATE contacts SET
3944
- engagement_status = CASE
3945
- WHEN interaction_count_30d > 3 THEN 'warm'
3946
- WHEN last_contacted_at IS NULL OR julianday('now') - julianday(last_contacted_at) > 180 THEN 'ghost'
3947
- WHEN julianday('now') - julianday(last_contacted_at) > 60 THEN 'cooling'
3948
- ELSE 'active'
3949
- END,
3950
- updated_at = datetime('now')
3951
- WHERE archived = 0
3952
- `).run();
3953
- const result = _db2.query(`SELECT changes() as n`).get();
3954
- return { updated: result?.n ?? 0 };
3955
- }
3956
-
3957
- // src/lib/context.ts
3958
- init_database();
3959
- init_contacts();
3960
- function getContactCard(contactId, db) {
3961
- const _db2 = db || getDatabase();
3962
- const c = getContact(contactId, _db2);
3963
- const emails = c.emails;
3964
- const phones = c.phones;
3965
- const company = c.company;
3966
- return {
3967
- id: c.id,
3968
- display_name: c.display_name,
3969
- job_title: c.job_title,
3970
- company: company?.name,
3971
- primary_email: emails?.find((e) => e.is_primary)?.address || emails?.[0]?.address,
3972
- primary_phone: phones?.find((p) => p.is_primary)?.number || phones?.[0]?.number
3973
- };
3974
- }
3975
- function getContactBrief(contactId, taskContext, db) {
3976
- const _db2 = db || getDatabase();
3977
- const c = getContact(contactId, _db2);
3978
- const notes = listNotes(contactId, _db2).slice(0, 3);
3979
- const learnings = getLearnings(contactId, { min_importance: 7 }, _db2).slice(0, 5);
3980
- const ctx = (taskContext ?? "").toLowerCase();
3981
- const lastContactedAt = c.last_contacted_at;
3982
- const daysSince = lastContactedAt ? Math.floor((Date.now() - new Date(lastContactedAt).getTime()) / 86400000) : null;
3983
- const company = c.company;
3984
- const brief = {
3985
- id: c.id,
3986
- display_name: c.display_name,
3987
- job_title: c.job_title,
3988
- company: company?.name,
3989
- status: c.status,
3990
- last_contacted: daysSince !== null ? `${daysSince}d ago` : "never",
3991
- relationship_health: c.relationship_health,
3992
- engagement_status: c.engagement_status,
3993
- preferred_contact: c.preferred_contact_method || c.preferred_channel
3994
- };
3995
- if (ctx.includes("meeting") || ctx.includes("call") || ctx.includes("prep")) {
3996
- brief.recent_notes = notes.map((n) => ({ date: n.created_at?.slice(0, 10), content: n.body }));
3997
- brief.key_learnings = learnings.map((l) => l.content);
3998
- }
3999
- if (ctx.includes("outreach") || ctx.includes("email")) {
4000
- brief.preferred_channel = c.preferred_channel;
4001
- brief.follow_up_at = c.follow_up_at;
4002
- }
4003
- if (ctx.includes("deal")) {
4004
- const dealCompany = c.company;
4005
- brief.company_details = dealCompany ? { name: dealCompany.name, domain: dealCompany.domain } : null;
4006
- }
4007
- if (learnings.length)
4008
- brief.top_learnings = learnings.map((l) => l.content);
4009
- return brief;
4010
- }
4011
- async function assembleContext(contactIds, format = "meeting_prep", db) {
4012
- const _db2 = db || getDatabase();
4013
- const briefs = contactIds.map((id) => {
4014
- try {
4015
- return getContactBrief(id, format, _db2);
4016
- } catch {
4017
- return { id, error: "not found" };
4018
- }
4019
- });
4020
- return { format, contact_count: contactIds.length, assembled_at: new Date().toISOString(), contacts: briefs };
4021
- }
4022
-
4023
- // src/lib/signature-parser.ts
4024
- function parseEmailSignature(text) {
4025
- const result = {};
4026
- const phoneMatch = text.match(/(\+?[\d\s\-\(\)]{7,20})/);
4027
- if (phoneMatch)
4028
- result.phone = phoneMatch[1]?.trim();
4029
- const emailMatch = text.match(/[\w.+-]+@[\w-]+\.[a-z]{2,}/i);
4030
- if (emailMatch)
4031
- result.email = emailMatch[0];
4032
- const linkedinMatch = text.match(/(?:linkedin\.com\/in\/)([\w-]+)/i);
4033
- if (linkedinMatch)
4034
- result.linkedin = `https://linkedin.com/in/${linkedinMatch[1]}`;
4035
- const websiteMatch = text.match(/https?:\/\/(?!linkedin)(?!twitter)[\w.-]+\.[a-z]{2,}/i);
4036
- if (websiteMatch)
4037
- result.website = websiteMatch[0];
4038
- const lines = text.split(`
4039
- `).map((l) => l.trim()).filter((l) => l.length > 2 && l.length < 80);
4040
- if (lines[0])
4041
- result.name = lines[0];
4042
- for (const line of lines.slice(1)) {
4043
- if (line.match(/\b(CEO|CTO|VP|Director|Manager|Engineer|Partner|Associate|Consultant|Analyst|President|Founder)\b/i)) {
4044
- result.title = line;
4045
- } else if (!result.company && line.match(/^[A-Z][A-Za-z\s,\.]+$/) && !line.includes("@")) {
4046
- result.company = line;
4047
- }
4048
- }
4049
- return result;
4050
- }
4051
- function extractContactsFromEmailThread(participants) {
4052
- return participants.map((p) => {
4053
- const sig = p.signature ? parseEmailSignature(p.signature) : {};
4054
- const name = p.name || sig.name || p.email.split("@")[0] || "Unknown";
4055
- const contact = {
4056
- display_name: name,
4057
- emails: [{ address: p.email, type: "work", is_primary: true }],
4058
- source: "import"
4059
- };
4060
- if (sig.title)
4061
- contact.job_title = sig.title;
4062
- if (sig.phone)
4063
- contact.phones = [{ number: sig.phone, type: "work", is_primary: true }];
4064
- if (sig.linkedin)
4065
- contact.social_profiles = [{ platform: "linkedin", url: sig.linkedin, is_primary: true }];
4066
- if (sig.website)
4067
- contact.website = sig.website;
4068
- return contact;
4069
- });
4070
- }
4071
-
4072
- // src/lib/meeting-capture.ts
4073
- init_database();
4074
- async function ingestMeetingParticipants(event, db) {
4075
- const { findOrCreateContact: findOrCreateContact2 } = await Promise.resolve().then(() => (init_contacts(), exports_contacts));
4076
- const { logEvent: logEvent2 } = await Promise.resolve().then(() => (init_events(), exports_events));
4077
- const _db2 = db || getDatabase();
4078
- let created = 0;
4079
- let updated = 0;
4080
- const ids = [];
4081
- for (const a of event.attendees) {
4082
- try {
4083
- const nameParts = a.name.split(" ");
4084
- const result = await findOrCreateContact2({
4085
- display_name: a.name,
4086
- first_name: nameParts[0],
4087
- last_name: nameParts.slice(1).join(" ") || undefined,
4088
- emails: [{ address: a.email, type: "work", is_primary: true }],
4089
- source: "import"
4090
- }, _db2);
4091
- ids.push(result.contact.id);
4092
- if (result.created)
4093
- created++;
4094
- else
4095
- updated++;
4096
- } catch {}
4097
- }
4098
- if (ids.length) {
4099
- try {
4100
- logEvent2({
4101
- title: event.title,
4102
- type: "meeting",
4103
- event_date: event.event_date,
4104
- contact_ids: ids,
4105
- notes: event.context
4106
- }, _db2);
4107
- } catch {}
4108
- }
4109
- return { created, updated, contact_ids: ids };
4110
- }
4111
-
4112
- // src/db/freshness.ts
4113
- init_database();
4114
- var SCORED_FIELDS = ["display_name", "job_title", "company_id", "emails", "phones", "last_contacted_at"];
4115
- function getFreshnessScore(contactId, db) {
4116
- const _db2 = db || getDatabase();
4117
- const contact = _db2.query(`SELECT * FROM contacts WHERE id=?`).get(contactId);
4118
- if (!contact)
4119
- throw new Error(`Contact not found: ${contactId}`);
4120
- let historyRows = [];
4121
- try {
4122
- historyRows = _db2.query(`SELECT field_name, new_value, source, created_at FROM contact_field_history WHERE contact_id=? ORDER BY created_at DESC`).all(contactId);
4123
- } catch {}
4124
- let verifiedRows = [];
4125
- try {
4126
- verifiedRows = _db2.query(`SELECT field_name, verified_at, source FROM field_verifications WHERE contact_id=?`).all(contactId);
4127
- } catch {}
4128
- const verifiedMap = new Map(verifiedRows.map((r) => [r.field_name, r]));
4129
- const historyMap = new Map;
4130
- for (const r of historyRows) {
4131
- if (!historyMap.has(r.field_name))
4132
- historyMap.set(r.field_name, r);
4133
- }
4134
- const fields = SCORED_FIELDS.map((field) => {
4135
- let value = null;
4136
- if (field === "emails") {
4137
- const emailRow = _db2.query(`SELECT address FROM emails WHERE contact_id=? LIMIT 1`).get(contactId);
4138
- value = emailRow?.address ?? null;
4139
- } else if (field === "phones") {
4140
- const phoneRow = _db2.query(`SELECT number FROM phones WHERE contact_id=? LIMIT 1`).get(contactId);
4141
- value = phoneRow?.number ?? null;
4142
- } else {
4143
- value = contact[field] != null ? String(contact[field]) : null;
4144
- }
4145
- const verified = verifiedMap.get(field);
4146
- const history = historyMap.get(field);
4147
- let confidence = "unknown";
4148
- let days_old = null;
4149
- let last_verified_at = null;
4150
- let source = null;
4151
- if (verified) {
4152
- confidence = "verified";
4153
- last_verified_at = verified.verified_at;
4154
- source = verified.source;
4155
- days_old = Math.floor((Date.now() - new Date(verified.verified_at).getTime()) / 86400000);
4156
- } else if (history) {
4157
- confidence = history.source === "import" ? "imported" : "inferred";
4158
- last_verified_at = history.created_at;
4159
- source = history.source;
4160
- days_old = Math.floor((Date.now() - new Date(history.created_at).getTime()) / 86400000);
4161
- if (days_old > 365)
4162
- confidence = "stale";
4163
- } else if (value) {
4164
- confidence = "inferred";
4165
- }
4166
- return { field_name: field, value, last_verified_at, source, confidence, days_old };
4167
- });
4168
- const fieldScore = fields.reduce((acc, f) => {
4169
- if (!f.value)
4170
- return acc;
4171
- if (f.confidence === "verified")
4172
- return acc + 20;
4173
- if (f.confidence === "imported" || f.confidence === "inferred")
4174
- return acc + 10;
4175
- return acc + 5;
4176
- }, 0);
4177
- const overall_score = Math.min(100, fieldScore);
4178
- return {
4179
- contact_id: contactId,
4180
- overall_score,
4181
- fields,
4182
- stale_fields: fields.filter((f) => f.confidence === "stale" || !f.value && f.field_name !== "phones").map((f) => f.field_name),
4183
- verified_fields: fields.filter((f) => f.confidence === "verified").map((f) => f.field_name)
4184
- };
4185
- }
4186
- function getStaleContacts(threshold = 40, db) {
4187
- const _db2 = db || getDatabase();
4188
- const rows = _db2.query(`SELECT * FROM (
4189
- SELECT c.id as contact_id, c.display_name,
4190
- (CASE WHEN c.job_title IS NOT NULL THEN 15 ELSE 0 END +
4191
- CASE WHEN c.company_id IS NOT NULL THEN 15 ELSE 0 END +
4192
- CASE WHEN c.last_contacted_at IS NOT NULL THEN 20 ELSE 0 END +
4193
- CASE WHEN EXISTS(SELECT 1 FROM emails WHERE contact_id=c.id) THEN 20 ELSE 0 END +
4194
- CASE WHEN EXISTS(SELECT 1 FROM phones WHERE contact_id=c.id) THEN 15 ELSE 0 END +
4195
- CASE WHEN c.notes IS NOT NULL THEN 10 ELSE 0 END +
4196
- CASE WHEN EXISTS(SELECT 1 FROM contact_tags WHERE contact_id=c.id) THEN 5 ELSE 0 END
4197
- ) as score
4198
- FROM contacts c WHERE c.archived=0
4199
- ) WHERE score < ? ORDER BY score ASC LIMIT 100`).all(threshold);
4200
- return rows;
4201
- }
4202
- function markFieldVerified(contactId, fieldName, source, db) {
4203
- const _db2 = db || getDatabase();
4204
- try {
4205
- _db2.query(`INSERT OR REPLACE INTO field_verifications(contact_id,field_name,verified_at,source) VALUES(?,?,?,?)`).run(contactId, fieldName, now(), source || null);
4206
- } catch {
4207
- _db2.query(`INSERT INTO activity_log(id,contact_id,action,details,created_at) VALUES(?,?,?,?,?)`).run(crypto.randomUUID(), contactId, "field.verified", JSON.stringify({ field_name: fieldName, source }), now());
4208
- }
4209
- }
4210
-
4211
- // src/db/org-chart.ts
4212
- init_database();
4213
- function addOrgChartEdge(companyId, contactAId, contactBId, edgeType, inferred = false, db) {
4214
- const _db2 = db || getDatabase();
4215
- const id = uuid();
4216
- _db2.query(`INSERT OR IGNORE INTO org_chart_edges(id,company_id,contact_a_id,contact_b_id,edge_type,inferred,created_at) VALUES(?,?,?,?,?,?,?)`).run(id, companyId, contactAId, contactBId, edgeType, inferred ? 1 : 0, now());
4217
- return _db2.query(`SELECT * FROM org_chart_edges WHERE company_id=? AND contact_a_id=? AND contact_b_id=? AND edge_type=?`).get(companyId, contactAId, contactBId, edgeType);
4218
- }
4219
- function listOrgChart(companyId, db) {
4220
- const _db2 = db || getDatabase();
4221
- return _db2.query(`SELECT oe.*, ca.display_name as contact_a_name, cb.display_name as contact_b_name FROM org_chart_edges oe JOIN contacts ca ON oe.contact_a_id=ca.id JOIN contacts cb ON oe.contact_b_id=cb.id WHERE oe.company_id=?`).all(companyId);
4222
- }
4223
- function setDealContactRole(dealId, contactId, accountRole, db) {
4224
- const _db2 = db || getDatabase();
4225
- const id = uuid();
4226
- _db2.query(`INSERT OR REPLACE INTO deal_contact_roles(id,deal_id,contact_id,account_role,created_at) VALUES(?,?,?,?,?)`).run(id, dealId, contactId, accountRole, now());
4227
- return _db2.query(`SELECT * FROM deal_contact_roles WHERE deal_id=? AND contact_id=?`).get(dealId, contactId);
4228
- }
4229
- function getDealTeam(dealId, db) {
4230
- const _db2 = db || getDatabase();
4231
- return _db2.query(`SELECT dr.*, c.display_name, c.job_title FROM deal_contact_roles dr JOIN contacts c ON dr.contact_id=c.id WHERE dr.deal_id=?`).all(dealId);
4232
- }
4233
- function getCoverageGaps(companyId, db) {
4234
- const _db2 = db || getDatabase();
4235
- const total = _db2.query(`SELECT COUNT(*) c FROM contacts WHERE company_id=? AND archived=0`).get(companyId).c;
4236
- const hasManager = _db2.query(`SELECT COUNT(*) c FROM org_chart_edges WHERE company_id=? AND edge_type='manages'`).get(companyId).c > 0;
4237
- const hasEco = _db2.query(`SELECT COUNT(*) c FROM deal_contact_roles dr JOIN deals d ON dr.deal_id=d.id WHERE d.company_id=? AND dr.account_role='economic_buyer'`).get(companyId).c > 0;
4238
- const hasTech = _db2.query(`SELECT COUNT(*) c FROM deal_contact_roles dr JOIN deals d ON dr.deal_id=d.id WHERE d.company_id=? AND dr.account_role='technical_evaluator'`).get(companyId).c > 0;
4239
- const missing = [
4240
- !hasManager && "org chart relationships",
4241
- !hasEco && "economic buyer",
4242
- !hasTech && "technical evaluator"
4243
- ].filter(Boolean);
4244
- return {
4245
- total_contacts: total,
4246
- has_manager: hasManager,
4247
- has_technical: hasTech,
4248
- has_economic_buyer: hasEco,
4249
- suggestion: missing.length ? `Missing: ${missing.join(", ")}` : "Good coverage"
4250
- };
4251
- }
4252
-
4253
- // src/lib/images.ts
4254
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, copyFileSync, unlinkSync, readdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
4255
- import { join as join3, extname, basename } from "path";
4256
- var IMAGES_DIR = join3(process.env["HOME"] || "~", ".contacts", "images");
4257
- function ensureImagesDir() {
4258
- if (!existsSync3(IMAGES_DIR))
4259
- mkdirSync2(IMAGES_DIR, { recursive: true });
4260
- }
4261
- function saveImage(entityId, source, options) {
4262
- ensureImagesDir();
4263
- deleteImage(entityId);
4264
- const base64Match = source.match(/^data:image\/(\w+);base64,(.+)$/s);
4265
- if (base64Match) {
4266
- const ext2 = base64Match[1] === "jpeg" ? "jpg" : base64Match[1];
4267
- const data = Buffer.from(base64Match[2], "base64");
4268
- const filename2 = `${entityId}.${ext2}`;
4269
- writeFileSync(join3(IMAGES_DIR, filename2), data);
4270
- return filename2;
4271
- }
4272
- if (!existsSync3(source) && /^[A-Za-z0-9+/=\n\r]+$/.test(source.trim()) && source.length > 100) {
4273
- const ext2 = options?.format || "jpg";
4274
- const data = Buffer.from(source.trim(), "base64");
4275
- const filename2 = `${entityId}.${ext2}`;
4276
- writeFileSync(join3(IMAGES_DIR, filename2), data);
4277
- return filename2;
4278
- }
4279
- if (!existsSync3(source)) {
4280
- throw new Error(`Image file not found: ${source}`);
4281
- }
4282
- const ext = extname(source).slice(1).toLowerCase() || "jpg";
4283
- const validExts = ["jpg", "jpeg", "png", "gif", "webp", "svg", "avif", "ico"];
4284
- if (!validExts.includes(ext)) {
4285
- throw new Error(`Unsupported image format: ${ext}. Supported: ${validExts.join(", ")}`);
4286
- }
4287
- const filename = `${entityId}.${ext === "jpeg" ? "jpg" : ext}`;
4288
- copyFileSync(source, join3(IMAGES_DIR, filename));
4289
- return filename;
4290
- }
4291
- function getImagePath(entityId) {
4292
- ensureImagesDir();
4293
- const files = readdirSync(IMAGES_DIR);
4294
- const match = files.find((f) => f.startsWith(`${entityId}.`));
4295
- return match ? join3(IMAGES_DIR, match) : null;
4296
- }
4297
- function getImageAsBase64(entityId) {
4298
- const path = getImagePath(entityId);
4299
- if (!path)
4300
- return null;
4301
- const ext = extname(path).slice(1);
4302
- const mime = ext === "jpg" ? "image/jpeg" : ext === "svg" ? "image/svg+xml" : `image/${ext}`;
4303
- const data = readFileSync2(path);
4304
- return `data:${mime};base64,${data.toString("base64")}`;
4305
- }
4306
- function deleteImage(entityId) {
4307
- ensureImagesDir();
4308
- const files = readdirSync(IMAGES_DIR);
4309
- let deleted = false;
4310
- for (const f of files) {
4311
- if (f.startsWith(`${entityId}.`)) {
4312
- unlinkSync(join3(IMAGES_DIR, f));
4313
- deleted = true;
4314
- }
4315
- }
4316
- return deleted;
4317
- }
4318
-
4319
- // src/lib/vault.ts
4320
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
4321
- import { join as join4 } from "path";
4322
- import { createCipheriv, createDecipheriv, randomBytes, pbkdf2Sync, createHash } from "crypto";
4323
- var VAULT_DIR = join4(process.env["HOME"] || "~", ".contacts");
4324
- var VAULT_CONFIG = join4(VAULT_DIR, "vault.json");
4325
- var VAULT_SESSION = join4(VAULT_DIR, ".vault-session");
4326
- var DOCUMENTS_DIR = join4(VAULT_DIR, "documents");
4327
- var SESSION_TTL_MS = 30 * 60 * 1000;
4328
- var _derivedKey = null;
4329
- function deriveKey(passphrase, salt) {
4330
- return pbkdf2Sync(passphrase, salt, 1e5, 32, "sha512");
4331
- }
4332
- function saveSession(key) {
4333
- const session = {
4334
- key: key.toString("hex"),
4335
- expires_at: new Date(Date.now() + SESSION_TTL_MS).toISOString()
4336
- };
4337
- writeFileSync2(VAULT_SESSION, JSON.stringify(session), { mode: 384 });
4338
- }
4339
- function loadSession() {
4340
- if (!existsSync4(VAULT_SESSION))
4341
- return null;
4342
- try {
4343
- const session = JSON.parse(readFileSync3(VAULT_SESSION, "utf-8"));
4344
- if (new Date(session.expires_at).getTime() < Date.now()) {
4345
- try {
4346
- unlinkSync2(VAULT_SESSION);
4347
- } catch {}
4348
- return null;
4349
- }
4350
- return Buffer.from(session.key, "hex");
4351
- } catch {
4352
- return null;
4353
- }
4354
- }
4355
- function clearSession() {
4356
- try {
4357
- if (existsSync4(VAULT_SESSION))
4358
- unlinkSync2(VAULT_SESSION);
4359
- } catch {}
4360
- }
4361
- function initVault(passphrase) {
4362
- if (!existsSync4(VAULT_DIR))
4363
- mkdirSync3(VAULT_DIR, { recursive: true });
4364
- if (!existsSync4(DOCUMENTS_DIR))
4365
- mkdirSync3(DOCUMENTS_DIR, { recursive: true });
4366
- const salt = randomBytes(32);
4367
- const key = deriveKey(passphrase, salt);
4368
- const keyHash = createHash("sha256").update(key).digest("hex");
4369
- const config = { salt: salt.toString("hex"), key_hash: keyHash, created_at: new Date().toISOString() };
4370
- writeFileSync2(VAULT_CONFIG, JSON.stringify(config, null, 2));
4371
- _derivedKey = key;
4372
- saveSession(key);
4373
- }
4374
- function isVaultInitialized() {
4375
- return existsSync4(VAULT_CONFIG);
4376
- }
4377
- function unlockVault(passphrase) {
4378
- if (!existsSync4(VAULT_CONFIG))
4379
- throw new Error("Vault not initialized. Run 'contacts vault init' first.");
4380
- const config = JSON.parse(readFileSync3(VAULT_CONFIG, "utf-8"));
4381
- const salt = Buffer.from(config.salt, "hex");
4382
- const key = deriveKey(passphrase, salt);
4383
- const keyHash = createHash("sha256").update(key).digest("hex");
4384
- if (keyHash !== config.key_hash)
4385
- return false;
4386
- _derivedKey = key;
4387
- saveSession(key);
4388
- return true;
4389
- }
4390
- function lockVault() {
4391
- _derivedKey = null;
4392
- clearSession();
4393
- }
4394
- function isVaultUnlocked() {
4395
- if (_derivedKey)
4396
- return true;
4397
- const sessionKey = loadSession();
4398
- if (sessionKey) {
4399
- _derivedKey = sessionKey;
4400
- return true;
4401
- }
4402
- return false;
4403
- }
4404
- function requireVault() {
4405
- if (_derivedKey)
4406
- return _derivedKey;
4407
- const sessionKey = loadSession();
4408
- if (sessionKey) {
4409
- _derivedKey = sessionKey;
4410
- return _derivedKey;
4411
- }
4412
- throw new Error("Vault is locked. Unlock with 'contacts vault unlock --passphrase <pass>' or vault_unlock MCP tool first.");
4413
- }
4414
- function encrypt(plaintext) {
4415
- const key = requireVault();
4416
- const iv = randomBytes(16);
4417
- const cipher = createCipheriv("aes-256-gcm", key, iv);
4418
- let encrypted = cipher.update(plaintext, "utf8", "hex");
4419
- encrypted += cipher.final("hex");
4420
- const authTag = cipher.getAuthTag().toString("hex");
4421
- return { ciphertext: encrypted + ":" + authTag, iv: iv.toString("hex") };
4422
- }
4423
- function decrypt(ciphertext, iv) {
4424
- const key = requireVault();
4425
- const [encData, authTag] = ciphertext.split(":");
4426
- if (!encData || !authTag)
4427
- throw new Error("Invalid ciphertext format");
4428
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "hex"));
4429
- decipher.setAuthTag(Buffer.from(authTag, "hex"));
4430
- let decrypted = decipher.update(encData, "hex", "utf8");
4431
- decrypted += decipher.final("utf8");
4432
- return decrypted;
4433
- }
4434
- function encryptFile(sourcePath, entityId) {
4435
- const key = requireVault();
4436
- if (!existsSync4(DOCUMENTS_DIR))
4437
- mkdirSync3(DOCUMENTS_DIR, { recursive: true });
4438
- const data = readFileSync3(sourcePath);
4439
- const iv = randomBytes(16);
4440
- const cipher = createCipheriv("aes-256-gcm", key, iv);
4441
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
4442
- const authTag = cipher.getAuthTag();
4443
- const destPath = join4(DOCUMENTS_DIR, `${entityId}.enc`);
4444
- const output = Buffer.concat([iv, authTag, encrypted]);
4445
- writeFileSync2(destPath, output);
4446
- return destPath;
4447
- }
4448
-
4449
- // src/db/documents.ts
4450
- init_database();
4451
- import { existsSync as existsSync5, unlinkSync as unlinkSync3 } from "fs";
4452
- var DOCUMENT_TYPES = [
4453
- "passport",
4454
- "national_id",
4455
- "tax_id",
4456
- "ssn",
4457
- "drivers_license",
4458
- "bank_account",
4459
- "visa",
4460
- "insurance",
4461
- "contract",
4462
- "certificate",
4463
- "medical_record",
4464
- "prescription",
4465
- "allergy_list",
4466
- "vaccination",
4467
- "blood_type",
4468
- "health_insurance",
4469
- "medical_condition",
4470
- "emergency_contact_medical",
4471
- "other"
4472
- ];
4473
- function addDocument(input, db) {
4474
- requireVault();
4475
- const _db2 = db || getDatabase();
4476
- const id = uuid();
4477
- const { ciphertext, iv } = encrypt(input.value);
4478
- let encFilePath = null;
4479
- if (input.file_path) {
4480
- encFilePath = encryptFile(input.file_path, id);
4481
- }
4482
- _db2.query(`INSERT INTO contact_documents (id, contact_id, doc_type, label, encrypted_value, iv, encrypted_file_path, metadata, expires_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(id, input.contact_id, input.doc_type, input.label ?? null, ciphertext, iv, encFilePath, JSON.stringify(input.metadata || {}), input.expires_at ?? null, now(), now());
4483
- return getDocument(id, _db2);
4484
- }
4485
- function getDocument(id, db) {
4486
- requireVault();
4487
- const _db2 = db || getDatabase();
4488
- const row = _db2.query(`SELECT * FROM contact_documents WHERE id = ?`).get(id);
4489
- if (!row)
4490
- throw new Error(`Document not found: ${id}`);
4491
- return rowToDoc(row);
4492
- }
4493
- function listDocuments(contactId, db) {
4494
- const _db2 = db || getDatabase();
4495
- const rows = _db2.query(`SELECT id, doc_type, label, encrypted_file_path, expires_at, created_at FROM contact_documents WHERE contact_id = ? ORDER BY created_at DESC`).all(contactId);
4496
- return rows.map((r) => ({
4497
- id: r.id,
4498
- doc_type: r.doc_type,
4499
- label: r.label,
4500
- has_file: !!r.encrypted_file_path,
4501
- expires_at: r.expires_at,
4502
- created_at: r.created_at
4503
- }));
4504
- }
4505
- function deleteDocument(id, db) {
4506
- const _db2 = db || getDatabase();
4507
- const row = _db2.query(`SELECT encrypted_file_path FROM contact_documents WHERE id = ?`).get(id);
4508
- if (row?.encrypted_file_path && existsSync5(row.encrypted_file_path)) {
4509
- try {
4510
- unlinkSync3(row.encrypted_file_path);
4511
- } catch {}
4512
- }
4513
- _db2.query(`DELETE FROM contact_documents WHERE id = ?`).run(id);
4514
- }
4515
- function rowToDoc(row) {
4516
- return {
4517
- id: row.id,
4518
- contact_id: row.contact_id,
4519
- doc_type: row.doc_type,
4520
- label: row.label,
4521
- value: decrypt(row.encrypted_value, row.iv),
4522
- has_file: !!row.encrypted_file_path,
4523
- metadata: JSON.parse(row.metadata || "{}"),
4524
- expires_at: row.expires_at,
4525
- created_at: row.created_at,
4526
- updated_at: row.updated_at
4527
- };
4528
- }
4529
-
4530
- // src/db/health.ts
4531
- init_database();
4532
- function setHealthData(contactId, input, db) {
4533
- requireVault();
4534
- const _db2 = db || getDatabase();
4535
- const existing = _db2.query(`SELECT id FROM contact_health WHERE contact_id = ?`).get(contactId);
4536
- if (existing) {
4537
- const sets = [];
4538
- const params = [];
4539
- if (input.blood_type !== undefined) {
4540
- sets.push("blood_type = ?");
4541
- params.push(input.blood_type);
4542
- }
4543
- if (input.allergies !== undefined) {
4544
- sets.push("allergies = ?");
4545
- params.push(JSON.stringify(input.allergies));
4546
- }
4547
- if (input.medical_conditions !== undefined) {
4548
- sets.push("medical_conditions = ?");
4549
- params.push(JSON.stringify(input.medical_conditions));
4550
- }
4551
- if (input.medications !== undefined) {
4552
- sets.push("medications = ?");
4553
- params.push(JSON.stringify(input.medications));
4554
- }
4555
- if (input.emergency_contacts !== undefined) {
4556
- sets.push("emergency_contacts = ?");
4557
- params.push(JSON.stringify(input.emergency_contacts));
4558
- }
4559
- if (input.health_insurance_provider !== undefined) {
4560
- sets.push("health_insurance_provider = ?");
4561
- params.push(input.health_insurance_provider);
4562
- }
4563
- if (input.health_insurance_id !== undefined) {
4564
- sets.push("health_insurance_id = ?");
4565
- params.push(input.health_insurance_id);
4566
- }
4567
- if (input.primary_physician !== undefined) {
4568
- sets.push("primary_physician = ?");
4569
- params.push(input.primary_physician);
4570
- }
4571
- if (input.primary_physician_phone !== undefined) {
4572
- sets.push("primary_physician_phone = ?");
4573
- params.push(input.primary_physician_phone);
4574
- }
4575
- if (input.organ_donor !== undefined) {
4576
- sets.push("organ_donor = ?");
4577
- params.push(input.organ_donor ? 1 : 0);
4578
- }
4579
- if (input.notes !== undefined) {
4580
- sets.push("notes = ?");
4581
- params.push(input.notes);
4582
- }
4583
- if (sets.length) {
4584
- sets.push("updated_at = ?");
4585
- params.push(now());
4586
- params.push(contactId);
4587
- _db2.query(`UPDATE contact_health SET ${sets.join(", ")} WHERE contact_id = ?`).run(...params);
4588
- }
4589
- } else {
4590
- const id = uuid();
4591
- _db2.query(`INSERT INTO contact_health (id, contact_id, blood_type, allergies, medical_conditions, medications, emergency_contacts, health_insurance_provider, health_insurance_id, primary_physician, primary_physician_phone, organ_donor, notes, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.blood_type ?? null, JSON.stringify(input.allergies || []), JSON.stringify(input.medical_conditions || []), JSON.stringify(input.medications || []), JSON.stringify(input.emergency_contacts || []), input.health_insurance_provider ?? null, input.health_insurance_id ?? null, input.primary_physician ?? null, input.primary_physician_phone ?? null, input.organ_donor ? 1 : 0, input.notes ?? null, now(), now());
4592
- }
4593
- return getHealthData(contactId, _db2);
4594
- }
4595
- function getHealthData(contactId, db) {
4596
- requireVault();
4597
- const _db2 = db || getDatabase();
4598
- const row = _db2.query(`SELECT * FROM contact_health WHERE contact_id = ?`).get(contactId);
4599
- if (!row)
4600
- return null;
4601
- return {
4602
- id: row.id,
4603
- contact_id: row.contact_id,
4604
- blood_type: row.blood_type,
4605
- allergies: JSON.parse(row.allergies || "[]"),
4606
- medical_conditions: JSON.parse(row.medical_conditions || "[]"),
4607
- medications: JSON.parse(row.medications || "[]"),
4608
- emergency_contacts: JSON.parse(row.emergency_contacts || "[]"),
4609
- health_insurance_provider: row.health_insurance_provider,
4610
- health_insurance_id: row.health_insurance_id,
4611
- primary_physician: row.primary_physician,
4612
- primary_physician_phone: row.primary_physician_phone,
4613
- organ_donor: !!row.organ_donor,
4614
- notes: row.notes,
4615
- created_at: row.created_at,
4616
- updated_at: row.updated_at
4617
- };
4618
- }
4619
- function deleteHealthData(contactId, db) {
4620
- const _db2 = db || getDatabase();
4621
- _db2.query(`DELETE FROM contact_health WHERE contact_id = ?`).run(contactId);
4622
- }
4623
-
4624
- // src/lib/document-scanner.ts
4625
- import { readFileSync as readFileSync4, existsSync as existsSync6 } from "fs";
4626
- import { extname as extname2 } from "path";
4627
- async function scanDocument(imageSource, docType) {
4628
- const apiKey = process.env["OPENAI_API_KEY"];
4629
- if (!apiKey) {
4630
- throw new Error("OPENAI_API_KEY not set. Set it in ~/.secrets or environment to use document scanning.");
4631
- }
4632
- let imageData;
4633
- if (imageSource.startsWith("data:image/")) {
4634
- imageData = imageSource;
4635
- } else if (existsSync6(imageSource)) {
4636
- const buffer = readFileSync4(imageSource);
4637
- const ext = extname2(imageSource).slice(1).toLowerCase();
4638
- const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "png" ? "image/png" : ext === "webp" ? "image/webp" : ext === "gif" ? "image/gif" : "image/jpeg";
4639
- imageData = `data:${mime};base64,${buffer.toString("base64")}`;
4640
- } else if (/^[A-Za-z0-9+/=\n\r]+$/.test(imageSource.trim()) && imageSource.length > 100) {
4641
- imageData = `data:image/jpeg;base64,${imageSource.trim()}`;
4642
- } else {
4643
- throw new Error(`Image source not found or invalid: ${imageSource.slice(0, 50)}...`);
4644
- }
4645
- const typeHint = docType ? ` This is a ${docType} document.` : "";
4646
- const prompt = `Extract all text and structured data from this document image.${typeHint} Return a JSON object with these fields:
4647
- - document_type: detected type (passport, national_id, drivers_license, tax_document, medical_record, prescription, insurance_card, bank_statement, visa, certificate, contract, other)
4648
- - full_name: full name as shown
4649
- - date_of_birth: in YYYY-MM-DD format if visible
4650
- - document_number: main ID/document number
4651
- - issuing_country: country code or name
4652
- - issue_date: in YYYY-MM-DD format if visible
4653
- - expiry_date: in YYYY-MM-DD format if visible
4654
- - address: full address if visible
4655
- - nationality: if visible
4656
- - gender: if visible
4657
- - mrz_code: Machine Readable Zone text if this is a passport/ID with MRZ
4658
- - phone: any phone numbers visible
4659
- - email: any email addresses visible
4660
- - additional_fields: object with any other visible structured data
4661
- - raw_text: all visible text transcribed
4662
-
4663
- Only include fields that are actually visible in the document. Return valid JSON only.`;
4664
- const response = await fetch("https://api.openai.com/v1/chat/completions", {
4665
- method: "POST",
4666
- headers: {
4667
- Authorization: `Bearer ${apiKey}`,
4668
- "Content-Type": "application/json"
4669
- },
4670
- body: JSON.stringify({
4671
- model: "gpt-4o",
4672
- messages: [
4673
- {
4674
- role: "user",
4675
- content: [
4676
- { type: "text", text: prompt },
4677
- { type: "image_url", image_url: { url: imageData, detail: "high" } }
4678
- ]
4679
- }
4680
- ],
4681
- max_tokens: 2000,
4682
- temperature: 0
4683
- })
4684
- });
4685
- if (!response.ok) {
4686
- const err = await response.text();
4687
- throw new Error(`OpenAI API error: ${response.status} \u2014 ${err}`);
4688
- }
4689
- const data = await response.json();
4690
- const content = data.choices?.[0]?.message?.content || "";
4691
- const jsonMatch = content.match(/```json\s*([\s\S]*?)```/) || content.match(/\{[\s\S]*\}/);
4692
- if (!jsonMatch) {
4693
- return { fields: {}, raw_text: content, document_type: docType || "unknown", confidence: 0.3 };
4694
- }
4695
- try {
4696
- const parsed = JSON.parse(jsonMatch[1] || jsonMatch[0]);
4697
- const { document_type, raw_text, additional_fields, ...mainFields } = parsed;
4698
- const fields = {};
4699
- for (const [k, v] of Object.entries(mainFields)) {
4700
- if (v && typeof v === "string")
4701
- fields[k] = v;
4702
- }
4703
- if (additional_fields && typeof additional_fields === "object") {
4704
- for (const [k, v] of Object.entries(additional_fields)) {
4705
- if (v && typeof v === "string")
4706
- fields[k] = v;
4707
- }
4708
- }
4709
- return {
4710
- fields,
4711
- raw_text: raw_text || content,
4712
- document_type: document_type || docType || "unknown",
4713
- confidence: Object.keys(fields).length > 3 ? 0.9 : Object.keys(fields).length > 0 ? 0.7 : 0.3
4714
- };
4715
- } catch {
4716
- return { fields: {}, raw_text: content, document_type: docType || "unknown", confidence: 0.3 };
4717
- }
3353
+ function deleteEvent(id, db) {
3354
+ const d = db || getDatabase();
3355
+ d.run(`DELETE FROM events WHERE id = ?`, [id]);
4718
3356
  }
4719
3357
 
4720
3358
  // src/mcp/index.ts
@@ -4795,8 +3433,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
4795
3433
  }
4796
3434
  },
4797
3435
  tag_ids: { type: "array", items: { type: "string" }, description: "Tag IDs to assign" },
4798
- source: { type: "string", enum: ["manual", "import", "linkedin", "github", "twitter", "email", "calendar", "crm", "other"] },
4799
- sensitivity: { type: "string", enum: ["normal", "confidential", "restricted"], description: "Contact sensitivity level (default: normal)" }
3436
+ source: { type: "string", enum: ["manual", "import", "linkedin", "github", "twitter", "email", "calendar", "crm", "other"] }
4800
3437
  }
4801
3438
  }
4802
3439
  },
@@ -4832,7 +3469,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
4832
3469
  project_id: { type: "string", description: "Primary project ID (single, null to clear)" },
4833
3470
  project_ids: { type: "array", items: { type: "string" }, description: "Replace all project links with this array of todos project IDs" },
4834
3471
  source: { type: "string", enum: ["manual", "import", "linkedin", "github", "twitter", "email", "calendar", "crm", "other"] },
4835
- sensitivity: { type: "string", enum: ["normal", "confidential", "restricted"] },
4836
3472
  emails_add: { type: "array", items: { type: "object", properties: { address: { type: "string" }, type: { type: "string" }, is_primary: { type: "boolean" } }, required: ["address"] }, description: "New email addresses to append (duplicates are skipped)" },
4837
3473
  phones_add: { type: "array", items: { type: "object", properties: { number: { type: "string" }, type: { type: "string" }, country_code: { type: "string" }, is_primary: { type: "boolean" } }, required: ["number"] }, description: "New phone numbers to append (duplicates are skipped)" }
4838
3474
  },
@@ -4861,7 +3497,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
4861
3497
  status: { type: "string", enum: ["active", "pending_reply", "converted", "closed", "other"] },
4862
3498
  project_id: { type: "string", description: "Filter by project ID" },
4863
3499
  archived: { type: "boolean", description: "Include archived contacts (default false)" },
4864
- include_restricted: { type: "boolean", description: "Include restricted-sensitivity contacts (default false)" },
4865
3500
  follow_up_due: { type: "boolean", description: "Only return contacts whose follow_up_at is in the past" },
4866
3501
  last_contacted_after: { type: "string", description: "ISO 8601 date \u2014 only contacts last contacted after this date" },
4867
3502
  last_contacted_before: { type: "string", description: "ISO 8601 date \u2014 only contacts last contacted before this date" },
@@ -6138,68 +4773,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
6138
4773
  },
6139
4774
  required: ["contact_id", "do_not_contact"]
6140
4775
  }
6141
- },
6142
- { name: "get_field_history", description: "Get the change history for one or all fields of a contact (temporal audit trail).", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, field_name: { type: "string", description: "Optional \u2014 filter to a single field" } }, required: ["contact_id"] } },
6143
- { name: "get_contact_at", description: "Reconstruct a contact's profile as it was at a specific point in time, using field history.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, timestamp: { type: "string", description: "ISO 8601 datetime \u2014 reconstruct profile at this point in time" } }, required: ["contact_id", "timestamp"] } },
6144
- { name: "get_job_history", description: "Get the employment timeline for a contact \u2014 all past and current job entries in reverse chronological order.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6145
- { name: "add_job_entry", description: "Add a job history entry to a contact's employment timeline.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, company_name: { type: "string" }, title: { type: "string" }, start_date: { type: "string" }, end_date: { type: "string" }, is_current: { type: "boolean" } }, required: ["contact_id", "company_name"] } },
6146
- { name: "save_learning", description: "Save a structured learning about a contact \u2014 preferences, facts, inferences, warnings, or signals. Include confidence (0-100) and importance (1-10).", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, content: { type: "string" }, type: { type: "string", enum: ["preference", "fact", "inference", "warning", "signal"] }, confidence: { type: "number" }, importance: { type: "number" }, learned_by: { type: "string" }, visibility: { type: "string", enum: ["private", "shared", "human"] }, tags: { type: "array", items: { type: "string" } } }, required: ["contact_id", "content"] } },
6147
- { name: "get_learnings", description: "Get all learnings for a contact, optionally filtered by type and minimum importance.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, type: { type: "string", enum: ["preference", "fact", "inference", "warning", "signal"] }, min_importance: { type: "number" } }, required: ["contact_id"] } },
6148
- { name: "search_learnings", description: "Cross-contact search across all learnings for a keyword or phrase.", inputSchema: { type: "object", properties: { query: { type: "string" }, type: { type: "string" }, contact_id: { type: "string", description: "Optional \u2014 limit to a specific contact" } }, required: ["query"] } },
6149
- { name: "confirm_learning", description: "Confirm a learning as correct, boosting its confidence score.", inputSchema: { type: "object", properties: { learning_id: { type: "string" }, agent_name: { type: "string" } }, required: ["learning_id", "agent_name"] } },
6150
- { name: "get_stale_learnings", description: "Find learnings that haven't been confirmed recently and may need review.", inputSchema: { type: "object", properties: { days_old: { type: "number" }, min_confidence: { type: "number" } } } },
6151
- { name: "run_learning_maintenance", description: "Run decay (reduce confidence on old unconfirmed learnings) and contradiction detection across all learnings.", inputSchema: { type: "object", properties: {} } },
6152
- { name: "acquire_contact_lock", description: "Acquire a write lock on a contact to prevent conflicts when multiple agents edit the same record. Returns {acquired, lock, held_by}.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, agent_name: { type: "string" }, ttl_seconds: { type: "number" }, reason: { type: "string" }, session_id: { type: "string" } }, required: ["contact_id", "agent_name"] } },
6153
- { name: "release_contact_lock", description: "Release a contact write lock previously acquired by this agent.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, agent_name: { type: "string" } }, required: ["contact_id", "agent_name"] } },
6154
- { name: "check_contact_lock", description: "Check if a contact is currently locked by any agent.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6155
- { name: "log_agent_activity", description: "Log an agent action against a contact for audit/coordination purposes.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, agent_name: { type: "string" }, action: { type: "string" }, details: { type: "string" }, session_id: { type: "string" } }, required: ["contact_id", "agent_name", "action"] } },
6156
- { name: "get_contact_agent_activity", description: "Get the recent agent activity log for a contact.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, limit: { type: "number" } }, required: ["contact_id"] } },
6157
- { name: "get_relationship_strength", description: "Compute and return the relationship strength score (0-100) for a contact based on interaction frequency and recency.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6158
- { name: "find_warm_path", description: "Find the shortest warm introduction path between two contacts through the relationship graph.", inputSchema: { type: "object", properties: { from_contact_id: { type: "string" }, to_contact_id: { type: "string" } }, required: ["from_contact_id", "to_contact_id"] } },
6159
- { name: "find_connections_at_company", description: "Find all contacts linked to a specific company, with relationship strength scores.", inputSchema: { type: "object", properties: { company_id: { type: "string" } }, required: ["company_id"] } },
6160
- { name: "get_cooling_relationships", description: "Get all relationships that are cooling (no contact in 45+ days) \u2014 use to prioritize re-engagement outreach.", inputSchema: { type: "object", properties: {} } },
6161
- { name: "resolve_contact_identity", description: "Resolve a contact's identity from partial signals (email, name, LinkedIn URL, phone, or external system ID). Returns ranked matches with confidence scores.", inputSchema: { type: "object", properties: { email: { type: "string" }, name: { type: "string" }, linkedin_url: { type: "string" }, phone: { type: "string" }, system: { type: "string" }, external_id: { type: "string" } } } },
6162
- { name: "add_contact_identity", description: "Register an external system identity (e.g. Salesforce ID, LinkedIn URL) for a contact.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, system: { type: "string" }, external_id: { type: "string" }, external_url: { type: "string" }, confidence: { type: "string", enum: ["verified", "inferred"] } }, required: ["contact_id", "system", "external_id"] } },
6163
- { name: "get_contact_identities", description: "Get all registered external system identities for a contact.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6164
- { name: "semantic_search_contacts", description: "Search contacts by capability or context using TF-IDF semantic similarity \u2014 finds contacts based on meaning, not just keyword match.", inputSchema: { type: "object", properties: { query: { type: "string" }, limit: { type: "number" } }, required: ["query"] } },
6165
- { name: "embed_all_contacts", description: "Build TF-IDF embeddings for all contacts in the database \u2014 run once to enable semantic_search_contacts.", inputSchema: { type: "object", properties: {} } },
6166
- { name: "get_relationship_signals", description: "Get relationship health signals for a contact: warming/cooling/ghost/healthy status with reasons.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6167
- { name: "get_ghost_contacts", description: "List contacts you haven't been in touch with for 180+ days \u2014 relationships at risk of becoming permanently cold.", inputSchema: { type: "object", properties: {} } },
6168
- { name: "get_warming_contacts", description: "List contacts with rising interaction frequency \u2014 relationships gaining momentum.", inputSchema: { type: "object", properties: {} } },
6169
- { name: "recompute_signals", description: "Recompute engagement_status for all contacts based on interaction counts and recency.", inputSchema: { type: "object", properties: {} } },
6170
- { name: "get_contact_card", description: "Get a minimal ~50-token contact summary: name, title, company, primary email and phone. Ideal for lists and agent context injection.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6171
- { name: "assemble_context", description: "Assemble a multi-contact context package for meetings, deals, outreach, or research. Returns task-relevant briefs for each contact.", inputSchema: { type: "object", properties: { contact_ids: { type: "array", items: { type: "string" } }, format: { type: "string", enum: ["meeting_prep", "deal_review", "outreach", "research"] } }, required: ["contact_ids"] } },
6172
- { name: "parse_email_signature", description: "Parse an email signature text to extract contact fields (name, title, company, phone, email, LinkedIn, website). Does NOT create a contact.", inputSchema: { type: "object", properties: { signature_text: { type: "string" } }, required: ["signature_text"] } },
6173
- { name: "ingest_email_participants", description: "Find or create contacts from email thread participants (with optional signatures). Returns { created, updated, contacts }.", inputSchema: { type: "object", properties: { participants: { type: "array", items: { type: "object", properties: { name: { type: "string" }, email: { type: "string" }, signature: { type: "string" } }, required: ["email"] } }, context: { type: "string" } }, required: ["participants"] } },
6174
- { name: "ingest_meeting_participants", description: "Ingest meeting attendees: find-or-create contacts and log the meeting as an event. Returns { created, updated, contact_ids }.", inputSchema: { type: "object", properties: { title: { type: "string" }, event_date: { type: "string" }, attendees: { type: "array", items: { type: "object", properties: { name: { type: "string" }, email: { type: "string" } }, required: ["name", "email"] } }, context: { type: "string" } }, required: ["title", "event_date", "attendees"] } },
6175
- { name: "get_freshness_score", description: "Get a per-field freshness and confidence breakdown for a contact \u2014 shows which fields are verified, stale, or missing.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6176
- { name: "get_stale_contacts", description: "List contacts with low data completeness scores (below threshold). Default threshold: 40.", inputSchema: { type: "object", properties: { threshold: { type: "number", description: "Score threshold 0-100 (default 40)" } } } },
6177
- { name: "mark_field_verified", description: "Mark a specific contact field as verified by a human or trusted source.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, field_name: { type: "string" }, source: { type: "string" } }, required: ["contact_id", "field_name"] } },
6178
- { name: "add_org_chart_edge", description: "Add a relationship edge to the org chart for a company (reports_to, manages, peer, collaborates_with).", inputSchema: { type: "object", properties: { company_id: { type: "string" }, contact_a_id: { type: "string" }, contact_b_id: { type: "string" }, edge_type: { type: "string", enum: ["reports_to", "manages", "collaborates_with", "peer"] } }, required: ["company_id", "contact_a_id", "contact_b_id", "edge_type"] } },
6179
- { name: "get_org_chart", description: "Get the org chart for a company as a list of directed edges with contact names.", inputSchema: { type: "object", properties: { company_id: { type: "string" } }, required: ["company_id"] } },
6180
- { name: "set_deal_contact_role", description: "Assign a contact a buying committee role in a deal (economic_buyer, technical_evaluator, champion, blocker, influencer, user, sponsor, other).", inputSchema: { type: "object", properties: { deal_id: { type: "string" }, contact_id: { type: "string" }, account_role: { type: "string", enum: ["economic_buyer", "technical_evaluator", "champion", "blocker", "influencer", "user", "sponsor", "other"] } }, required: ["deal_id", "contact_id", "account_role"] } },
6181
- { name: "get_deal_team", description: "Get the full buying committee for a deal with contact names and roles.", inputSchema: { type: "object", properties: { deal_id: { type: "string" } }, required: ["deal_id"] } },
6182
- { name: "get_coverage_gaps", description: "Identify coverage gaps in a company account \u2014 missing economic buyer, technical evaluator, or org chart relationships.", inputSchema: { type: "object", properties: { company_id: { type: "string" } }, required: ["company_id"] } },
6183
- { name: "get_recent_contact_events", description: "Polling fallback for change events \u2014 returns recent activity log entries, optionally filtered by event type or date.", inputSchema: { type: "object", properties: { since: { type: "string", description: "ISO 8601 datetime \u2014 only events after this date" }, event_types: { type: "array", items: { type: "string" } } } } },
6184
- { name: "set_contact_photo", description: "Set a contact's profile photo. Provide either a local file path or base64-encoded image data (with or without data URI prefix). Stores image in ~/.contacts/images/ and updates avatar_url. Supported formats: jpg, png, gif, webp, svg, avif.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, image: { type: "string", description: "File path (e.g. /tmp/photo.jpg) OR base64 data (e.g. data:image/png;base64,...) OR raw base64 string" }, format: { type: "string", description: "Image format hint when using raw base64 (jpg, png, webp). Not needed for file paths or data URIs." } }, required: ["contact_id", "image"] } },
6185
- { name: "get_contact_photo", description: "Get a contact's profile photo as base64 data URI. Returns null if no photo is set.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6186
- { name: "delete_contact_photo", description: "Remove a contact's profile photo.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6187
- { name: "set_company_logo", description: "Set a company's logo image. Provide either a local file path or base64-encoded image data. Stores image in ~/.contacts/images/ and updates logo_url.", inputSchema: { type: "object", properties: { company_id: { type: "string" }, image: { type: "string", description: "File path or base64 data" }, format: { type: "string", description: "Image format hint for raw base64" } }, required: ["company_id", "image"] } },
6188
- { name: "get_company_logo", description: "Get a company's logo as base64 data URI.", inputSchema: { type: "object", properties: { company_id: { type: "string" } }, required: ["company_id"] } },
6189
- { name: "delete_company_logo", description: "Remove a company's logo image.", inputSchema: { type: "object", properties: { company_id: { type: "string" } }, required: ["company_id"] } },
6190
- { name: "set_sensitivity", description: "Set a contact's sensitivity level (normal, confidential, restricted). Restricted contacts are hidden from list/search unless explicitly requested.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, sensitivity: { type: "string", enum: ["normal", "confidential", "restricted"] } }, required: ["contact_id", "sensitivity"] } },
6191
- { name: "vault_init", description: "Initialize the encrypted document vault with a passphrase. Must be called before storing documents or health data.", inputSchema: { type: "object", properties: { passphrase: { type: "string" } }, required: ["passphrase"] } },
6192
- { name: "vault_unlock", description: "Unlock the vault for this session with a passphrase.", inputSchema: { type: "object", properties: { passphrase: { type: "string" } }, required: ["passphrase"] } },
6193
- { name: "vault_lock", description: "Lock the vault, clearing the encryption key from memory.", inputSchema: { type: "object", properties: {} } },
6194
- { name: "vault_status", description: "Check vault initialization and lock status.", inputSchema: { type: "object", properties: {} } },
6195
- { name: "add_document", description: "Store an encrypted document for a contact (passport, tax_id, medical_record, etc.). Vault must be unlocked.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, doc_type: { type: "string", enum: [...DOCUMENT_TYPES] }, label: { type: "string" }, value: { type: "string", description: "Plaintext value (will be encrypted)" }, file_path: { type: "string", description: "Optional file to encrypt and attach" }, metadata: { type: "object" }, expires_at: { type: "string" } }, required: ["contact_id", "doc_type", "value"] } },
6196
- { name: "list_documents", description: "List documents for a contact (metadata only \u2014 no decryption needed).", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6197
- { name: "get_document", description: "Get a document with decrypted value. Vault must be unlocked.", inputSchema: { type: "object", properties: { document_id: { type: "string" } }, required: ["document_id"] } },
6198
- { name: "delete_document", description: "Delete a document and its encrypted file.", inputSchema: { type: "object", properties: { document_id: { type: "string" } }, required: ["document_id"] } },
6199
- { name: "scan_document", description: "Scan a document image using AI vision (OpenAI GPT-4o) to extract structured data. Optionally auto-save to vault.", inputSchema: { type: "object", properties: { image: { type: "string", description: "File path or base64 image data" }, doc_type: { type: "string", description: "Hint: passport, national_id, drivers_license, etc." }, contact_id: { type: "string", description: "Contact to associate scanned document with" }, auto_save: { type: "boolean", description: "Automatically save extracted data as a vault document" } }, required: ["image"] } },
6200
- { name: "set_health_data", description: "Set or update health data for a contact. Vault must be unlocked.", inputSchema: { type: "object", properties: { contact_id: { type: "string" }, blood_type: { type: "string" }, allergies: { type: "array", items: { type: "string" } }, medical_conditions: { type: "array", items: { type: "string" } }, medications: { type: "array", items: { type: "string" } }, emergency_contacts: { type: "array", items: { type: "object", properties: { name: { type: "string" }, phone: { type: "string" }, relationship: { type: "string" } }, required: ["name", "phone", "relationship"] } }, health_insurance_provider: { type: "string" }, health_insurance_id: { type: "string" }, primary_physician: { type: "string" }, primary_physician_phone: { type: "string" }, organ_donor: { type: "boolean" }, notes: { type: "string" } }, required: ["contact_id"] } },
6201
- { name: "get_health_data", description: "Get health data for a contact. Vault must be unlocked.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } },
6202
- { name: "delete_health_data", description: "Delete all health data for a contact.", inputSchema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"] } }
4776
+ }
6203
4777
  ]
6204
4778
  }));
6205
4779
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -6228,8 +4802,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
6228
4802
  addresses: a.addresses,
6229
4803
  social_profiles: a.social_profiles,
6230
4804
  tag_ids: a.tag_ids,
6231
- source: a.source,
6232
- sensitivity: a.sensitivity
4805
+ source: a.source
6233
4806
  };
6234
4807
  const contact = createContact(input);
6235
4808
  if (Array.isArray(a.project_ids) && a.project_ids.length > 0) {
@@ -6264,7 +4837,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
6264
4837
  follow_up_at: rest.follow_up_at,
6265
4838
  project_id: rest.project_id,
6266
4839
  source: rest.source,
6267
- sensitivity: rest.sensitivity,
6268
4840
  emails_add: rest.emails_add,
6269
4841
  phones_add: rest.phones_add
6270
4842
  };
@@ -6288,7 +4860,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
6288
4860
  status: a.status,
6289
4861
  project_id: a.project_id,
6290
4862
  archived: a.archived,
6291
- include_restricted: a.include_restricted,
6292
4863
  follow_up_due: a.follow_up_due,
6293
4864
  last_contacted_after: a.last_contacted_after,
6294
4865
  last_contacted_before: a.last_contacted_before,
@@ -7149,6 +5720,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
7149
5720
  const team = listCompanyRelationships({ company_id: a.company_id }, db);
7150
5721
  return { content: [{ type: "text", text: JSON.stringify({ company, team }, null, 2) }] };
7151
5722
  }
5723
+ case "get_contact_brief": {
5724
+ const db = getDatabase();
5725
+ const brief = generateBrief(a.contact_id, db);
5726
+ return { content: [{ type: "text", text: JSON.stringify({ brief }, null, 2) }] };
5727
+ }
7152
5728
  case "list_cold_contacts": {
7153
5729
  const db = getDatabase();
7154
5730
  const contacts = listColdContacts(a.days ?? 30, db);
@@ -7396,439 +5972,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
7396
5972
  const output = await exportContacts(format, contactList);
7397
5973
  return { content: [{ type: "text", text: output }] };
7398
5974
  }
7399
- case "get_field_history": {
7400
- const db = getDatabase();
7401
- const history = getFieldHistory(a.contact_id, a.field_name, db);
7402
- return { content: [{ type: "text", text: JSON.stringify({ history }, null, 2) }] };
7403
- }
7404
- case "get_contact_at": {
7405
- const db = getDatabase();
7406
- const snapshot = getContactAt(a.contact_id, a.timestamp, db);
7407
- return { content: [{ type: "text", text: JSON.stringify({ contact_id: a.contact_id, timestamp: a.timestamp, snapshot }, null, 2) }] };
7408
- }
7409
- case "get_job_history": {
7410
- const db = getDatabase();
7411
- const history = getJobHistory(a.contact_id, db);
7412
- return { content: [{ type: "text", text: JSON.stringify({ history }, null, 2) }] };
7413
- }
7414
- case "add_job_entry": {
7415
- const db = getDatabase();
7416
- const entry = addJobEntry(a.contact_id, {
7417
- company_name: a.company_name,
7418
- title: a.title,
7419
- start_date: a.start_date,
7420
- end_date: a.end_date,
7421
- is_current: a.is_current
7422
- }, db);
7423
- return { content: [{ type: "text", text: JSON.stringify(entry, null, 2) }] };
7424
- }
7425
- case "save_learning": {
7426
- const db = getDatabase();
7427
- const input = {
7428
- content: a.content,
7429
- type: a.type,
7430
- confidence: a.confidence,
7431
- importance: a.importance,
7432
- learned_by: a.learned_by,
7433
- visibility: a.visibility,
7434
- tags: a.tags
7435
- };
7436
- const learning = saveLearning(a.contact_id, input, db);
7437
- return { content: [{ type: "text", text: JSON.stringify(learning, null, 2) }] };
7438
- }
7439
- case "get_learnings": {
7440
- const db = getDatabase();
7441
- const learnings = getLearnings(a.contact_id, {
7442
- type: a.type,
7443
- min_importance: a.min_importance
7444
- }, db);
7445
- return { content: [{ type: "text", text: JSON.stringify({ learnings }, null, 2) }] };
7446
- }
7447
- case "search_learnings": {
7448
- const db = getDatabase();
7449
- const results = searchLearnings(a.query, {
7450
- type: a.type,
7451
- contact_id: a.contact_id
7452
- }, db);
7453
- return { content: [{ type: "text", text: JSON.stringify({ results }, null, 2) }] };
7454
- }
7455
- case "confirm_learning": {
7456
- const db = getDatabase();
7457
- confirmLearning(a.learning_id, a.agent_name, db);
7458
- return { content: [{ type: "text", text: JSON.stringify({ confirmed: true }) }] };
7459
- }
7460
- case "get_stale_learnings": {
7461
- const db = getDatabase();
7462
- const daysOld = a.days_old ?? 30;
7463
- const minConf = a.min_confidence ?? 0;
7464
- const cutoff = new Date(Date.now() - daysOld * 86400000).toISOString();
7465
- const rows = db.query(`SELECT * FROM contact_learnings WHERE confirmed_count=0 AND created_at<? AND confidence>=? ORDER BY confidence ASC LIMIT 50`).all(cutoff, minConf);
7466
- return { content: [{ type: "text", text: JSON.stringify({ stale_learnings: rows }, null, 2) }] };
7467
- }
7468
- case "run_learning_maintenance": {
7469
- const db = getDatabase();
7470
- const decayed = decayLearnings(db);
7471
- const duplicates = db.query(`SELECT contact_id, COUNT(*) as cnt FROM contact_learnings GROUP BY contact_id, LOWER(SUBSTR(content,1,30)) HAVING cnt > 1`).all();
7472
- return { content: [{ type: "text", text: JSON.stringify({ decayed_count: decayed, potential_contradictions: duplicates }, null, 2) }] };
7473
- }
7474
- case "acquire_contact_lock": {
7475
- const db = getDatabase();
7476
- const result = acquireLock(a.contact_id, a.agent_name, a.ttl_seconds, a.reason, a.session_id, db);
7477
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
7478
- }
7479
- case "release_contact_lock": {
7480
- const db = getDatabase();
7481
- const released = releaseLock(a.contact_id, a.agent_name, db);
7482
- return { content: [{ type: "text", text: JSON.stringify({ released }, null, 2) }] };
7483
- }
7484
- case "check_contact_lock": {
7485
- const db = getDatabase();
7486
- const lock = checkLock(a.contact_id, db);
7487
- return { content: [{ type: "text", text: JSON.stringify({ locked: !!lock, lock }, null, 2) }] };
7488
- }
7489
- case "log_agent_activity": {
7490
- const db = getDatabase();
7491
- logAgentActivity(a.contact_id, a.agent_name, a.action, a.details, a.session_id, db);
7492
- return { content: [{ type: "text", text: JSON.stringify({ logged: true }) }] };
7493
- }
7494
- case "get_contact_agent_activity": {
7495
- const db = getDatabase();
7496
- const activity = getAgentActivity(a.contact_id, a.limit ?? 20, db);
7497
- return { content: [{ type: "text", text: JSON.stringify({ activity }, null, 2) }] };
7498
- }
7499
- case "get_relationship_strength": {
7500
- const db = getDatabase();
7501
- const score = computeRelationshipStrength(a.contact_id, db);
7502
- return { content: [{ type: "text", text: JSON.stringify({ contact_id: a.contact_id, strength_score: score }, null, 2) }] };
7503
- }
7504
- case "find_warm_path": {
7505
- const db = getDatabase();
7506
- const path = findWarmPath(a.from_contact_id, a.to_contact_id, db);
7507
- return { content: [{ type: "text", text: JSON.stringify({ path, hops: path.length }, null, 2) }] };
7508
- }
7509
- case "find_connections_at_company": {
7510
- const db = getDatabase();
7511
- const connections = findConnectionsAtCompany(a.company_id, db);
7512
- return { content: [{ type: "text", text: JSON.stringify({ connections }, null, 2) }] };
7513
- }
7514
- case "get_cooling_relationships": {
7515
- const db = getDatabase();
7516
- const cooling = detectCoolingRelationships(db);
7517
- return { content: [{ type: "text", text: JSON.stringify({ cooling }, null, 2) }] };
7518
- }
7519
- case "resolve_contact_identity": {
7520
- const db = getDatabase();
7521
- const matches = resolveByPartial({
7522
- email: a.email,
7523
- name: a.name,
7524
- linkedin_url: a.linkedin_url,
7525
- phone: a.phone
7526
- }, db);
7527
- return { content: [{ type: "text", text: JSON.stringify({ matches }, null, 2) }] };
7528
- }
7529
- case "add_contact_identity": {
7530
- const db = getDatabase();
7531
- const identity = addIdentity(a.contact_id, a.system, a.external_id, a.external_url, a.confidence ?? "inferred", db);
7532
- return { content: [{ type: "text", text: JSON.stringify(identity, null, 2) }] };
7533
- }
7534
- case "get_contact_identities": {
7535
- const db = getDatabase();
7536
- const identities = getIdentities(a.contact_id, db);
7537
- return { content: [{ type: "text", text: JSON.stringify({ identities }, null, 2) }] };
7538
- }
7539
- case "semantic_search_contacts": {
7540
- const db = getDatabase();
7541
- const results = semanticSearch(a.query, a.limit ?? 10, db);
7542
- const enriched = results.map((r) => {
7543
- try {
7544
- return { ...r, contact: getContact(r.contact_id) };
7545
- } catch {
7546
- return r;
7547
- }
7548
- });
7549
- return { content: [{ type: "text", text: JSON.stringify({ results: enriched }, null, 2) }] };
7550
- }
7551
- case "embed_all_contacts": {
7552
- const db = getDatabase();
7553
- const count = await embedAllContacts(db);
7554
- return { content: [{ type: "text", text: JSON.stringify({ embedded: count }) }] };
7555
- }
7556
- case "get_relationship_signals": {
7557
- const db = getDatabase();
7558
- const signals = getRelationshipSignals(a.contact_id, db);
7559
- return { content: [{ type: "text", text: JSON.stringify({ signals }, null, 2) }] };
7560
- }
7561
- case "get_ghost_contacts": {
7562
- const db = getDatabase();
7563
- const ghosts = getGhostContacts(db);
7564
- return { content: [{ type: "text", text: JSON.stringify({ ghosts }, null, 2) }] };
7565
- }
7566
- case "get_warming_contacts": {
7567
- const db = getDatabase();
7568
- const warming = getWarmingContacts(db);
7569
- return { content: [{ type: "text", text: JSON.stringify({ warming }, null, 2) }] };
7570
- }
7571
- case "recompute_signals": {
7572
- const db = getDatabase();
7573
- const result = recomputeAllSignals(db);
7574
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
7575
- }
7576
- case "get_contact_card": {
7577
- const db = getDatabase();
7578
- const card = getContactCard(a.contact_id, db);
7579
- return { content: [{ type: "text", text: JSON.stringify(card, null, 2) }] };
7580
- }
7581
- case "get_contact_brief": {
7582
- const db = getDatabase();
7583
- const taskContext = a.task_context ?? a.format;
7584
- if (taskContext) {
7585
- const brief2 = getContactBrief(a.contact_id, taskContext, db);
7586
- return { content: [{ type: "text", text: JSON.stringify(brief2, null, 2) }] };
7587
- }
7588
- const brief = generateBrief(a.contact_id, db);
7589
- return { content: [{ type: "text", text: JSON.stringify({ brief }, null, 2) }] };
7590
- }
7591
- case "assemble_context": {
7592
- const db = getDatabase();
7593
- const ctx = await assembleContext(a.contact_ids, a.format ?? "meeting_prep", db);
7594
- return { content: [{ type: "text", text: JSON.stringify(ctx, null, 2) }] };
7595
- }
7596
- case "parse_email_signature": {
7597
- const parsed = parseEmailSignature(a.signature_text);
7598
- return { content: [{ type: "text", text: JSON.stringify(parsed, null, 2) }] };
7599
- }
7600
- case "ingest_email_participants": {
7601
- const db = getDatabase();
7602
- const participants = a.participants;
7603
- const extracted = extractContactsFromEmailThread(participants);
7604
- let created = 0;
7605
- let updated = 0;
7606
- const contacts = [];
7607
- const { findOrCreateContact: findOrCreate } = await Promise.resolve().then(() => (init_contacts(), exports_contacts));
7608
- for (const ci of extracted) {
7609
- try {
7610
- const result = await findOrCreate({
7611
- display_name: ci.display_name,
7612
- job_title: ci.job_title,
7613
- website: ci.website,
7614
- emails: ci.emails?.map((e) => ({ address: e.address, type: e.type, is_primary: e.is_primary })),
7615
- phones: ci.phones?.map((p) => ({ number: p.number, type: p.type, is_primary: p.is_primary })),
7616
- social_profiles: ci.social_profiles?.map((s) => ({ platform: "linkedin", url: s.url, is_primary: s.is_primary })),
7617
- source: "import"
7618
- }, db);
7619
- contacts.push(result.contact);
7620
- if (result.created)
7621
- created++;
7622
- else
7623
- updated++;
7624
- } catch {}
7625
- }
7626
- return { content: [{ type: "text", text: JSON.stringify({ created, updated, contacts }, null, 2) }] };
7627
- }
7628
- case "ingest_meeting_participants": {
7629
- const db = getDatabase();
7630
- const result = await ingestMeetingParticipants({
7631
- title: a.title,
7632
- event_date: a.event_date,
7633
- attendees: a.attendees,
7634
- context: a.context
7635
- }, db);
7636
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
7637
- }
7638
- case "get_freshness_score": {
7639
- const db = getDatabase();
7640
- const score = getFreshnessScore(a.contact_id, db);
7641
- return { content: [{ type: "text", text: JSON.stringify(score, null, 2) }] };
7642
- }
7643
- case "get_stale_contacts": {
7644
- const db = getDatabase();
7645
- const contacts = getStaleContacts(a.threshold ?? 40, db);
7646
- return { content: [{ type: "text", text: JSON.stringify({ contacts }, null, 2) }] };
7647
- }
7648
- case "mark_field_verified": {
7649
- const db = getDatabase();
7650
- markFieldVerified(a.contact_id, a.field_name, a.source, db);
7651
- return { content: [{ type: "text", text: JSON.stringify({ verified: true }) }] };
7652
- }
7653
- case "add_org_chart_edge": {
7654
- const db = getDatabase();
7655
- const edge = addOrgChartEdge(a.company_id, a.contact_a_id, a.contact_b_id, a.edge_type, false, db);
7656
- return { content: [{ type: "text", text: JSON.stringify(edge, null, 2) }] };
7657
- }
7658
- case "get_org_chart": {
7659
- const db = getDatabase();
7660
- const edges = listOrgChart(a.company_id, db);
7661
- return { content: [{ type: "text", text: JSON.stringify({ company_id: a.company_id, edges }, null, 2) }] };
7662
- }
7663
- case "set_deal_contact_role": {
7664
- const db = getDatabase();
7665
- const role = setDealContactRole(a.deal_id, a.contact_id, a.account_role, db);
7666
- return { content: [{ type: "text", text: JSON.stringify(role, null, 2) }] };
7667
- }
7668
- case "get_deal_team": {
7669
- const db = getDatabase();
7670
- const team = getDealTeam(a.deal_id, db);
7671
- return { content: [{ type: "text", text: JSON.stringify({ deal_id: a.deal_id, team }, null, 2) }] };
7672
- }
7673
- case "get_coverage_gaps": {
7674
- const db = getDatabase();
7675
- const gaps = getCoverageGaps(a.company_id, db);
7676
- return { content: [{ type: "text", text: JSON.stringify(gaps, null, 2) }] };
7677
- }
7678
- case "get_recent_contact_events": {
7679
- const db = getDatabase();
7680
- const since = a.since;
7681
- const eventTypes = a.event_types;
7682
- let sql = `SELECT * FROM activity_log WHERE 1=1`;
7683
- const params = [];
7684
- if (since) {
7685
- sql += ` AND created_at >= ?`;
7686
- params.push(since);
7687
- }
7688
- if (eventTypes?.length) {
7689
- sql += ` AND action IN (${eventTypes.map(() => "?").join(",")})`;
7690
- params.push(...eventTypes);
7691
- }
7692
- sql += ` ORDER BY created_at DESC LIMIT 100`;
7693
- const events = db.query(sql).all(...params);
7694
- return { content: [{ type: "text", text: JSON.stringify({ events }, null, 2) }] };
7695
- }
7696
- case "set_contact_photo": {
7697
- const { contact_id, image, format } = a;
7698
- const contact = getContact(contact_id);
7699
- const filename = saveImage(contact_id, image, { format });
7700
- updateContact(contact_id, { avatar_url: `~/.contacts/images/${filename}` });
7701
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, contact_id, filename, avatar_url: `~/.contacts/images/${filename}` }) }] };
7702
- }
7703
- case "get_contact_photo": {
7704
- const { contact_id } = a;
7705
- const dataUri = getImageAsBase64(contact_id);
7706
- if (!dataUri)
7707
- return { content: [{ type: "text", text: JSON.stringify({ contact_id, has_photo: false, data: null }) }] };
7708
- return { content: [{ type: "text", text: JSON.stringify({ contact_id, has_photo: true, data: dataUri }) }] };
7709
- }
7710
- case "delete_contact_photo": {
7711
- const { contact_id } = a;
7712
- const deleted = deleteImage(contact_id);
7713
- if (deleted)
7714
- updateContact(contact_id, { avatar_url: null });
7715
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, deleted }) }] };
7716
- }
7717
- case "set_company_logo": {
7718
- const { company_id, image, format } = a;
7719
- const co = getCompany(company_id);
7720
- const filename = saveImage(company_id, image, { format });
7721
- updateCompany(company_id, { logo_url: `~/.contacts/images/${filename}` });
7722
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, company_id, filename, logo_url: `~/.contacts/images/${filename}` }) }] };
7723
- }
7724
- case "get_company_logo": {
7725
- const { company_id } = a;
7726
- const dataUri = getImageAsBase64(company_id);
7727
- if (!dataUri)
7728
- return { content: [{ type: "text", text: JSON.stringify({ company_id, has_logo: false, data: null }) }] };
7729
- return { content: [{ type: "text", text: JSON.stringify({ company_id, has_logo: true, data: dataUri }) }] };
7730
- }
7731
- case "delete_company_logo": {
7732
- const { company_id } = a;
7733
- const deleted = deleteImage(company_id);
7734
- if (deleted)
7735
- updateCompany(company_id, { logo_url: null });
7736
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, deleted }) }] };
7737
- }
7738
- case "set_sensitivity": {
7739
- const contact = updateContact(a.contact_id, { sensitivity: a.sensitivity });
7740
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, contact_id: a.contact_id, sensitivity: a.sensitivity }) }] };
7741
- }
7742
- case "vault_init": {
7743
- initVault(a.passphrase);
7744
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, message: "Vault initialized and unlocked" }) }] };
7745
- }
7746
- case "vault_unlock": {
7747
- const ok = unlockVault(a.passphrase);
7748
- if (!ok)
7749
- return { content: [{ type: "text", text: "Invalid passphrase" }], isError: true };
7750
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, message: "Vault unlocked" }) }] };
7751
- }
7752
- case "vault_lock": {
7753
- lockVault();
7754
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, message: "Vault locked" }) }] };
7755
- }
7756
- case "vault_status": {
7757
- const initialized = isVaultInitialized();
7758
- const unlocked = isVaultUnlocked();
7759
- const db = getDatabase();
7760
- let docCount = 0;
7761
- try {
7762
- docCount = db.query("SELECT COUNT(*) as n FROM contact_documents").get().n;
7763
- } catch {}
7764
- return { content: [{ type: "text", text: JSON.stringify({ initialized, unlocked, document_count: docCount }) }] };
7765
- }
7766
- case "add_document": {
7767
- const doc = addDocument({
7768
- contact_id: a.contact_id,
7769
- doc_type: a.doc_type,
7770
- label: a.label,
7771
- value: a.value,
7772
- file_path: a.file_path,
7773
- metadata: a.metadata,
7774
- expires_at: a.expires_at
7775
- });
7776
- return { content: [{ type: "text", text: JSON.stringify(doc, null, 2) }] };
7777
- }
7778
- case "list_documents": {
7779
- const docs = listDocuments(a.contact_id);
7780
- return { content: [{ type: "text", text: JSON.stringify(docs, null, 2) }] };
7781
- }
7782
- case "get_document": {
7783
- const doc = getDocument(a.document_id);
7784
- return { content: [{ type: "text", text: JSON.stringify(doc, null, 2) }] };
7785
- }
7786
- case "delete_document": {
7787
- deleteDocument(a.document_id);
7788
- return { content: [{ type: "text", text: JSON.stringify({ deleted: true }) }] };
7789
- }
7790
- case "scan_document": {
7791
- const result = await scanDocument(a.image, a.doc_type);
7792
- if (a.auto_save && a.contact_id && isVaultUnlocked()) {
7793
- try {
7794
- const doc = addDocument({
7795
- contact_id: a.contact_id,
7796
- doc_type: result.document_type || "other",
7797
- label: `Scanned ${result.document_type}`,
7798
- value: JSON.stringify(result.fields),
7799
- metadata: { raw_text: result.raw_text, confidence: result.confidence }
7800
- });
7801
- return { content: [{ type: "text", text: JSON.stringify({ scan: result, saved_document: doc }, null, 2) }] };
7802
- } catch (saveErr) {
7803
- return { content: [{ type: "text", text: JSON.stringify({ scan: result, save_error: saveErr instanceof Error ? saveErr.message : String(saveErr) }, null, 2) }] };
7804
- }
7805
- }
7806
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
7807
- }
7808
- case "set_health_data": {
7809
- const health = setHealthData(a.contact_id, {
7810
- blood_type: a.blood_type,
7811
- allergies: a.allergies,
7812
- medical_conditions: a.medical_conditions,
7813
- medications: a.medications,
7814
- emergency_contacts: a.emergency_contacts,
7815
- health_insurance_provider: a.health_insurance_provider,
7816
- health_insurance_id: a.health_insurance_id,
7817
- primary_physician: a.primary_physician,
7818
- primary_physician_phone: a.primary_physician_phone,
7819
- organ_donor: a.organ_donor,
7820
- notes: a.notes
7821
- });
7822
- return { content: [{ type: "text", text: JSON.stringify(health, null, 2) }] };
7823
- }
7824
- case "get_health_data": {
7825
- const health = getHealthData(a.contact_id);
7826
- return { content: [{ type: "text", text: JSON.stringify(health, null, 2) }] };
7827
- }
7828
- case "delete_health_data": {
7829
- deleteHealthData(a.contact_id);
7830
- return { content: [{ type: "text", text: JSON.stringify({ deleted: true }) }] };
7831
- }
7832
5975
  default:
7833
5976
  return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true };
7834
5977
  }