outbound-sdk 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/alerts/index.js +1 -1
  2. package/dist/cards/index.js +201 -92
  3. package/dist/cards/sender-tool-cards.d.ts +6 -0
  4. package/dist/chunks/{chunk-MEEJIIIA.js → chunk-2ADIGC2N.js} +77 -8
  5. package/dist/chunks/{chunk-NAYVG7SI.js → chunk-3DDYXUDG.js} +1 -1
  6. package/dist/chunks/{chunk-UAHYPASH.js → chunk-3LRIWQEJ.js} +2 -1
  7. package/dist/chunks/{chunk-UZLFZZ2U.js → chunk-AWNH4I5D.js} +11 -2
  8. package/dist/chunks/{chunk-A7DLJUA6.js → chunk-B72F56HF.js} +3 -1
  9. package/dist/chunks/{chunk-KMQHXFIZ.js → chunk-CTRYCW4G.js} +648 -182
  10. package/dist/chunks/{chunk-OVTYA3IB.js → chunk-HDTOGEVN.js} +532 -182
  11. package/dist/chunks/{chunk-POBAY3TI.js → chunk-HXCZMMSD.js} +21 -0
  12. package/dist/chunks/chunk-I7GBBHD2.js +80 -0
  13. package/dist/chunks/{chunk-FTK4JS65.js → chunk-KNWJIJVO.js} +73 -4
  14. package/dist/chunks/{chunk-UOJG4VYF.js → chunk-LD5OAELW.js} +1 -1
  15. package/dist/chunks/{chunk-YFJ3OQZS.js → chunk-OPLXELPS.js} +5 -1
  16. package/dist/chunks/{chunk-KQCIF5IT.js → chunk-UIINRLHQ.js} +23 -9
  17. package/dist/chunks/{chunk-OMCDMELK.js → chunk-UWNQEQIX.js} +1 -1
  18. package/dist/chunks/{chunk-MPE6VLLY.js → chunk-UZ4YWUZ7.js} +1 -1
  19. package/dist/chunks/{tools-AVJ3XJ5A.js → tools-EKLZKXZU.js} +5 -4
  20. package/dist/cli/bin.js +11 -10
  21. package/dist/cli/config.d.ts +2 -0
  22. package/dist/cli/index.js +10 -9
  23. package/dist/combine/index.js +36 -2
  24. package/dist/emailbison/index.js +4 -4
  25. package/dist/fixtures/index.js +4 -4
  26. package/dist/heyreach/index.js +14 -6
  27. package/dist/identity/index.js +46 -11
  28. package/dist/identity/keys.d.ts +1 -1
  29. package/dist/index.js +8 -6
  30. package/dist/insights/define.d.ts +1 -1
  31. package/dist/insights/index.js +5 -4
  32. package/dist/insights/inputs.generated.d.ts +68 -5
  33. package/dist/insights/ops/channel-mix.d.ts +8 -1
  34. package/dist/insights/ops/period-comparison.d.ts +13 -2
  35. package/dist/insights/ops/shared.d.ts +11 -1
  36. package/dist/insights/ops/tag-rollup.d.ts +8 -1
  37. package/dist/insights/people/dropped-replies-check.d.ts +14 -2
  38. package/dist/insights/people/find.d.ts +5 -4
  39. package/dist/insights/people/hot-leads.d.ts +10 -1
  40. package/dist/insights/people/index.d.ts +26 -2
  41. package/dist/insights/people/person-summary.d.ts +15 -3
  42. package/dist/insights/people/thread-context.d.ts +79 -0
  43. package/dist/insights/people/thread-contexts.d.ts +59 -0
  44. package/dist/insights/people/thread-read.d.ts +22 -0
  45. package/dist/insights/registry.d.ts +25 -3
  46. package/dist/insights/senders/domain-health.d.ts +1 -1
  47. package/dist/insights/senders/index.d.ts +1 -1
  48. package/dist/insights/senders/read.d.ts +9 -0
  49. package/dist/instantly/adapter.d.ts +3 -2
  50. package/dist/instantly/capabilities.d.ts +5 -0
  51. package/dist/instantly/index.js +148 -45
  52. package/dist/instantly/senders.d.ts +3 -0
  53. package/dist/internal/adapter.d.ts +7 -0
  54. package/dist/internal/capabilities.d.ts +8 -0
  55. package/dist/internal/entities.d.ts +20 -0
  56. package/dist/internal/fields.d.ts +8 -0
  57. package/dist/internal/outbound/api.d.ts +12 -0
  58. package/dist/internal/outbound/operations-account.d.ts +4 -1
  59. package/dist/internal/outbound/outbound.d.ts +2 -1
  60. package/dist/internal/outbound/specs-account.d.ts +2 -1
  61. package/dist/internal/person.d.ts +32 -0
  62. package/dist/internal/records.d.ts +2 -2
  63. package/dist/internal/url.d.ts +2 -1
  64. package/dist/loader/index.js +1 -1
  65. package/dist/memory/data.d.ts +2 -1
  66. package/dist/memory/index.js +6 -4
  67. package/dist/redact/index.d.ts +1 -1
  68. package/dist/redact/index.js +48 -26
  69. package/dist/redact/plugin.d.ts +12 -4
  70. package/dist/redact/tokens.d.ts +21 -0
  71. package/dist/smartlead/index.js +18 -7
  72. package/dist/tools/account-tools.d.ts +0 -5
  73. package/dist/tools/ai-sdk.js +5 -3
  74. package/dist/tools/campaign-tools.d.ts +0 -4
  75. package/dist/tools/claude-agent.js +5 -3
  76. package/dist/tools/deliverability-check.d.ts +9 -0
  77. package/dist/tools/index.js +6 -4
  78. package/dist/tools/people-tools.d.ts +4 -1
  79. package/dist/tools/person-input.d.ts +17 -0
  80. package/dist/tools/sender-health.d.ts +8 -0
  81. package/dist/tools/sender-impact.d.ts +38 -0
  82. package/dist/tools/shared.d.ts +5 -0
  83. package/dist/webhooks/index.js +6 -6
  84. package/package.json +1 -1
  85. /package/dist/chunks/{chunk-5XLR6XVV.js → chunk-TOZKA7JR.js} +0 -0
@@ -1,23 +1,32 @@
1
1
  import {
2
2
  SCREENED_AT_MOST,
3
3
  capNext,
4
+ checkPerson,
4
5
  failure,
5
6
  inputProblem,
6
7
  leadsToStart,
7
8
  namesCampaign,
8
9
  newLeadsPerDay,
9
10
  paceWindow,
11
+ personFields,
12
+ personOf,
10
13
  routedByCampaign,
11
14
  runwayDays,
12
15
  splitActive,
16
+ untrusted,
13
17
  warmupAtZero,
14
18
  withCampaign
15
- } from "./chunk-FTK4JS65.js";
19
+ } from "./chunk-KNWJIJVO.js";
16
20
  import {
17
21
  count,
18
22
  percentOf,
19
23
  plural
20
24
  } from "./chunk-4PA526S7.js";
25
+ import {
26
+ assertRefReadable,
27
+ leadRefParts,
28
+ parsePerson
29
+ } from "./chunk-I7GBBHD2.js";
21
30
  import {
22
31
  mapConcurrent
23
32
  } from "./chunk-HZCTYL22.js";
@@ -36,7 +45,7 @@ import {
36
45
  } from "./chunk-FALWG5U3.js";
37
46
  import {
38
47
  leadStatusSchema
39
- } from "./chunk-POBAY3TI.js";
48
+ } from "./chunk-HXCZMMSD.js";
40
49
  import {
41
50
  CONTACTED_LEADS_LIMIT,
42
51
  contactedBeyondLeads,
@@ -46,13 +55,13 @@ import {
46
55
  campaignStatusSchema,
47
56
  replyCategorySchema
48
57
  } from "./chunk-QGRZDTX4.js";
58
+ import {
59
+ profileSlug
60
+ } from "./chunk-OPLXELPS.js";
49
61
  import {
50
62
  makeRef,
51
63
  parseRef
52
64
  } from "./chunk-HXB2IOJJ.js";
53
- import {
54
- profileSlug
55
- } from "./chunk-YFJ3OQZS.js";
56
65
  import {
57
66
  OutboundError
58
67
  } from "./chunk-XYHM4KHC.js";
@@ -64,7 +73,7 @@ import {
64
73
  } from "./chunk-45TXPJW7.js";
65
74
 
66
75
  // src/insights/tools.ts
67
- import { z as z31 } from "zod";
76
+ import { z as z32 } from "zod";
68
77
 
69
78
  // src/insights/cost.ts
70
79
  var UNKNOWN = /* @__PURE__ */ Symbol("unknown cost");
@@ -119,15 +128,15 @@ var pricer = (outbound, costs, most, found) => {
119
128
  }
120
129
  };
121
130
  };
122
- var boundsOf = (outbound, cost, input28, found) => {
131
+ var boundsOf = (outbound, cost, input29, found) => {
123
132
  const costs = cappedAccess(outbound)?.costs;
124
133
  if (cost === void 0 || costs === void 0) {
125
134
  return null;
126
135
  }
127
136
  try {
128
137
  return {
129
- max: cost(input28, pricer(outbound, costs, true, found)),
130
- min: cost(input28, pricer(outbound, costs, false, found))
138
+ max: cost(input29, pricer(outbound, costs, true, found)),
139
+ min: cost(input29, pricer(outbound, costs, false, found))
131
140
  };
132
141
  } catch (error) {
133
142
  if (error === UNKNOWN) {
@@ -169,8 +178,8 @@ var stopped = (name, stop, provider) => capError(
169
178
  stop,
170
179
  provider
171
180
  );
172
- var fitting = (outbound, cost, input28, name, room, found) => {
173
- const fields = input28;
181
+ var fitting = (outbound, cost, input29, name, room, found) => {
182
+ const fields = input29;
174
183
  const current = fields[name];
175
184
  if (typeof current !== "number" || current <= 1) {
176
185
  return void 0;
@@ -221,12 +230,12 @@ var capFor = (outbound, name, max, options) => {
221
230
  };
222
231
  var hasRunBudget = (outbound) => "requestBudget" in outbound;
223
232
  var runBudgetLeft = (outbound) => hasRunBudget(outbound) && outbound.requestBudget.per === "run" ? outbound.requestBudget.remaining() : Infinity;
224
- var runCap = (outbound, spec, input28, options) => {
225
- const bounds = boundsOf(outbound, spec.cost, input28);
233
+ var runCap = (outbound, spec, input29, options) => {
234
+ const bounds = boundsOf(outbound, spec.cost, input29);
226
235
  const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
227
236
  const stop = (room, found) => ({
228
237
  ...effect,
229
- lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input28, spec.scales, room, found),
238
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input29, spec.scales, room, found),
230
239
  requests: counter.used()
231
240
  });
232
241
  const outgrown = () => ({
@@ -240,7 +249,7 @@ var runCap = (outbound, spec, input28, options) => {
240
249
  );
241
250
  const check2 = (found) => {
242
251
  const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
243
- const least = boundsOf(outbound, spec.cost, input28, found);
252
+ const least = boundsOf(outbound, spec.cost, input29, found);
244
253
  if (least !== null && least.min > room) {
245
254
  throw refusal(
246
255
  spec.name,
@@ -450,19 +459,19 @@ var track = (cap, now, partialOnCap) => {
450
459
  };
451
460
  };
452
461
  var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
453
- var prepare = (outbound, spec, input28) => {
454
- const stray = unknownKey(Object.keys(spec.inputSchema.shape), input28);
462
+ var prepare = (outbound, spec, input29) => {
463
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input29);
455
464
  if (stray !== void 0) {
456
465
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
457
466
  provider: outbound.provider
458
467
  });
459
468
  }
460
- const parsed = spec.inputSchema.safeParse(input28 ?? {});
469
+ const parsed = spec.inputSchema.safeParse(input29 ?? {});
461
470
  if (!parsed.success) {
462
471
  const [issue] = parsed.error.issues;
463
472
  throw new OutboundError(
464
473
  "Invalid",
465
- `${spec.name}: ${inputProblem(input28, issue)}`,
474
+ `${spec.name}: ${inputProblem(input29, issue)}`,
466
475
  { provider: outbound.provider }
467
476
  );
468
477
  }
@@ -476,7 +485,7 @@ var prepare = (outbound, spec, input28) => {
476
485
  }
477
486
  return parsed.data;
478
487
  };
479
- var refuseUnsupported = (outbound, spec, input28) => {
488
+ var refuseUnsupported = (outbound, spec, input29) => {
480
489
  const lacked = spec.lacks?.(outbound) ?? null;
481
490
  if (lacked !== null) {
482
491
  throw new OutboundError(
@@ -486,7 +495,7 @@ var refuseUnsupported = (outbound, spec, input28) => {
486
495
  );
487
496
  }
488
497
  const absent = missing(outbound, spec.needs);
489
- const forInput = missing(outbound, spec.needsFor?.(input28) ?? []);
498
+ const forInput = missing(outbound, spec.needsFor?.(input29) ?? []);
490
499
  if (absent.length > 0 || forInput.length > 0) {
491
500
  throw new OutboundError(
492
501
  "Unsupported",
@@ -496,14 +505,14 @@ var refuseUnsupported = (outbound, spec, input28) => {
496
505
  }
497
506
  };
498
507
  var COMBINED = "combined";
499
- var someMemberServes = async (outbound, spec, input28) => {
508
+ var someMemberServes = async (outbound, spec, input29) => {
500
509
  const { items } = await outbound.workspaces.list();
501
510
  return items.some((tool) => {
502
511
  try {
503
512
  refuseUnsupported(
504
513
  outbound.workspace(`${tool.provider}:${tool.workspaceId}`),
505
514
  spec,
506
- input28
515
+ input29
507
516
  );
508
517
  return true;
509
518
  } catch (error) {
@@ -515,16 +524,16 @@ var someMemberServes = async (outbound, spec, input28) => {
515
524
  });
516
525
  };
517
526
  var NAMED_AMONG = 1e3;
518
- var priced = (outbound, spec, input28) => {
527
+ var priced = (outbound, spec, input29) => {
519
528
  const { cost } = spec;
520
- return cost === void 0 || !namesCampaign(outbound, input28) ? spec : {
529
+ return cost === void 0 || !namesCampaign(outbound, input29) ? spec : {
521
530
  ...spec,
522
531
  cost: (values, price) => cost(values, price) + price.list("campaigns.list", NAMED_AMONG)
523
532
  };
524
533
  };
525
- var execute = async (outbound, spec, input28, options = {}) => {
526
- const target = routedByCampaign(outbound, input28);
527
- const checked = prepare(target, spec, input28);
534
+ var execute = async (outbound, spec, input29, options = {}) => {
535
+ const target = routedByCampaign(outbound, input29);
536
+ const checked = prepare(target, spec, input29);
528
537
  const later = namesCampaign(target, checked) && target.provider === COMBINED;
529
538
  if (!later || !await someMemberServes(target, spec, checked)) {
530
539
  refuseUnsupported(target, spec, checked);
@@ -559,14 +568,14 @@ var execute = async (outbound, spec, input28, options = {}) => {
559
568
  };
560
569
  var defineInsight = (spec) => ({
561
570
  ...spec,
562
- execute: async (outbound, input28, options) => {
563
- const result = await execute(outbound, spec, input28, options);
571
+ execute: async (outbound, input29, options) => {
572
+ const result = await execute(outbound, spec, input29, options);
564
573
  return { ...result, data: toJson(result.data) };
565
574
  }
566
575
  });
567
- var runInsight = (outbound, definition, input28, options = {}) => (
576
+ var runInsight = (outbound, definition, input29, options = {}) => (
568
577
  // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
569
- execute(outbound, definition, input28, options)
578
+ execute(outbound, definition, input29, options)
570
579
  );
571
580
 
572
581
  // src/insights/copy/copy-audit.ts
@@ -744,9 +753,9 @@ var readShared = async (context, wanted, cap) => {
744
753
  items
745
754
  };
746
755
  };
747
- var readCampaignsIn = async (context, statuses, max, input28 = "max_campaigns") => {
756
+ var readCampaignsIn = async (context, statuses, max, input29 = "max_campaigns") => {
748
757
  const wanted = [...new Set(statuses)];
749
- const cap = { input: input28, max, what: "campaigns" };
758
+ const cap = { input: input29, max, what: "campaigns" };
750
759
  const read = context.outbound.provider === "combined" ? await readShared(context, wanted, cap) : await readOne(context, wanted, cap);
751
760
  context.campaignsFound(read.items.length);
752
761
  if (read.items.length === 0 && !read.capped) {
@@ -766,7 +775,7 @@ var statusesInput = (fallback) => z.array(campaignStatusSchema).min(1).default([
766
775
  );
767
776
 
768
777
  // src/insights/people/read.ts
769
- var readCappedFlag = (context, open, max, what, input28) => readCapped(context, open, { input: input28, max, what });
778
+ var readCappedFlag = (context, open, max, what, input29) => readCapped(context, open, { input: input29, max, what });
770
779
  var readByRef = async (context, refs, read, what, effect) => {
771
780
  if (refs.length === 0) {
772
781
  return /* @__PURE__ */ new Map();
@@ -790,13 +799,13 @@ var campaignsIn = async (context, statuses, max) => {
790
799
  const { items } = await readCampaignsIn(context, statuses, max);
791
800
  return items;
792
801
  };
793
- var leadsOf = async (context, campaign, max, input28) => {
802
+ var leadsOf = async (context, campaign, max, input29) => {
794
803
  const { items } = await readCappedFlag(
795
804
  context,
796
805
  (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
797
806
  max,
798
807
  "leads of a campaign",
799
- input28
808
+ input29
800
809
  );
801
810
  return items;
802
811
  };
@@ -1493,12 +1502,12 @@ var copyAudit = defineInsight({
1493
1502
  ].toSorted(
1494
1503
  (left, right) => RANK2[left.severity] - RANK2[right.severity] || left.stepIndex - right.stepIndex || left.variantKey.localeCompare(right.variantKey) || left.check.localeCompare(right.check) || (left.lead ?? "").localeCompare(right.lead ?? "")
1495
1504
  );
1496
- const withoutBody = variants.filter(
1505
+ const withoutBody2 = variants.filter(
1497
1506
  ({ variant }) => variant.body === null
1498
1507
  ).length;
1499
- if (withoutBody > 0) {
1508
+ if (withoutBody2 > 0) {
1500
1509
  context.note(
1501
- withoutBody === 1 ? "1 variant has no body in the vendor's answer, so its body checks were skipped." : `${withoutBody} variants have no body in the vendor's answer, so their body checks were skipped.`
1510
+ withoutBody2 === 1 ? "1 variant has no body in the vendor's answer, so its body checks were skipped." : `${withoutBody2} variants have no body in the vendor's answer, so their body checks were skipped.`
1502
1511
  );
1503
1512
  }
1504
1513
  noteSamples(context, perLead2, samples, sampled);
@@ -1518,7 +1527,7 @@ var copyAudit = defineInsight({
1518
1527
  stepsChecked: sequence2.steps.length,
1519
1528
  variantsChecked: variants.length,
1520
1529
  leadsAudited: sampled.leads,
1521
- variantsWithoutBody: withoutBody,
1530
+ variantsWithoutBody: withoutBody2,
1522
1531
  variantsNotAudited: sampled.unaudited,
1523
1532
  variantsWrittenPerLead: perLead2
1524
1533
  };
@@ -1596,12 +1605,12 @@ var compareRates = (first, second, alpha = 0.05) => {
1596
1605
  if (error === 0) {
1597
1606
  return null;
1598
1607
  }
1599
- const z32 = (first.successes / first.trials - second.successes / second.trials) / error;
1600
- const pValue = 1 - erf(Math.abs(z32) / Math.SQRT2);
1608
+ const z33 = (first.successes / first.trials - second.successes / second.trials) / error;
1609
+ const pValue = 1 - erf(Math.abs(z33) / Math.SQRT2);
1601
1610
  return {
1602
1611
  pValue: round(pValue) ?? 0,
1603
1612
  significant: pValue < alpha,
1604
- z: round(z32) ?? 0
1613
+ z: round(z33) ?? 0
1605
1614
  };
1606
1615
  };
1607
1616
  var percent = (value) => value === null ? "unknown" : percentOf(value);
@@ -2571,9 +2580,9 @@ var lastDays = (now, days, back = 0) => ({
2571
2580
  from: dayOf(now - days * (back + 1) * DAY_MS2),
2572
2581
  to: dayOf(now - (days * back + 1) * DAY_MS2)
2573
2582
  });
2574
- var campaignTotalsCost = (input28, price) => {
2575
- const campaigns = price.campaigns(input28.max_campaigns);
2576
- return price.campaignsIn(new Set(input28.statuses).size, input28.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
2583
+ var campaignTotalsCost = (input29, price) => {
2584
+ const campaigns = price.campaigns(input29.max_campaigns);
2585
+ return price.campaignsIn(new Set(input29.statuses).size, input29.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
2577
2586
  };
2578
2587
  var LIST_DEFAULTS = { maxCampaigns: 50, statuses: ["active"] };
2579
2588
  var listFields = (costPerCampaign, defaults = LIST_DEFAULTS) => ({
@@ -2607,6 +2616,9 @@ var measure2 = (count2, of) => {
2607
2616
  var baseIn2 = (basis) => (counts) => counts[basis];
2608
2617
  var perLeadBasis = (counts) => counts.contacted !== null && counts.contacted > 0 ? "contacted" : "sent";
2609
2618
  var perLeadBase = (counts) => counts[perLeadBasis(counts)];
2619
+ var replyBasisAcross = (rows) => rows.some(
2620
+ (row) => (row.contacted ?? 0) === 0 && (row.replied ?? 0) > 0 && row.sent !== null
2621
+ ) ? "sent" : "contacted";
2610
2622
  var periodBasis = (current, previous) => current.sent !== null && previous.sent !== null ? "sent" : "contacted";
2611
2623
  var RATE_WORDS = {
2612
2624
  contacted: "Replies per lead contacted",
@@ -2632,9 +2644,9 @@ var measureAcross = (rows, countOf3, baseOf) => {
2632
2644
  };
2633
2645
  };
2634
2646
  var partialRate = (name, across) => across.counted > 0 && across.counted < across.of ? [`${name} (${across.counted} of ${across.of})`] : [];
2635
- var ratesAcross = (rows, base = perLeadBase) => {
2636
- const reply = measureAcross(rows, (row) => row.replied, base);
2637
- const positive = measureAcross(rows, (row) => row.positive, base);
2647
+ var ratesAcross = (rows, basis = replyBasisAcross(rows)) => {
2648
+ const reply = measureAcross(rows, (row) => row.replied, baseIn2(basis));
2649
+ const positive = measureAcross(rows, (row) => row.positive, baseIn2(basis));
2638
2650
  const bounce = measureAcross(
2639
2651
  rows,
2640
2652
  (row) => row.bounced,
@@ -2650,7 +2662,8 @@ var ratesAcross = (rows, base = perLeadBase) => {
2650
2662
  bounceRate: bounce.measured,
2651
2663
  positiveRate: positive.measured,
2652
2664
  replyRate: reply.measured
2653
- }
2665
+ },
2666
+ replyRateBasis: basis
2654
2667
  };
2655
2668
  };
2656
2669
  var partialNote = (where, partial, rows = "campaigns") => `${where}: ${partial.join(", ")} ${partial.length === 1 ? "counts" : "count"} only the ${rows} that report both the count and what it is divided by. The others are left out of the rate, not counted as 0.`;
@@ -2688,19 +2701,19 @@ var readAllTotals = async (context, range) => {
2688
2701
  [...byCampaign].map(([ref, counts]) => [ref, sumMeasured(counts)])
2689
2702
  );
2690
2703
  };
2691
- var readCampaignTotals = async (context, input28) => {
2704
+ var readCampaignTotals = async (context, input29) => {
2692
2705
  const listed2 = await readCampaignsIn(
2693
2706
  context,
2694
- input28.statuses,
2695
- input28.max_campaigns
2707
+ input29.statuses,
2708
+ input29.max_campaigns
2696
2709
  );
2697
2710
  const campaigns = listed2.items;
2698
- const reported = campaigns.length > 1 ? await readAllTotals(context, input28) : void 0;
2711
+ const reported = campaigns.length > 1 ? await readAllTotals(context, input29) : void 0;
2699
2712
  const entries = await context.each(
2700
2713
  campaigns,
2701
2714
  async (campaign) => ({
2702
2715
  campaign,
2703
- counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input28)
2716
+ counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input29)
2704
2717
  }),
2705
2718
  "campaigns"
2706
2719
  );
@@ -3430,10 +3443,11 @@ var input10 = z13.object({
3430
3443
  "The p-value under which a difference counts as more than chance"
3431
3444
  )
3432
3445
  });
3433
- var groupOf = (channel, entries) => {
3446
+ var groupOf = (channel, entries, basis) => {
3434
3447
  const counts = entries.map((entry) => entry.counts);
3435
- const reply = measureAcross(counts, (row) => row.replied, perLeadBase);
3436
- const positive = measureAcross(counts, (row) => row.positive, perLeadBase);
3448
+ const base = baseIn2(basis);
3449
+ const reply = measureAcross(counts, (row) => row.replied, base);
3450
+ const positive = measureAcross(counts, (row) => row.positive, base);
3437
3451
  const acceptance = measureAcross(
3438
3452
  counts,
3439
3453
  (row) => row.connectionsAccepted,
@@ -3456,15 +3470,16 @@ var groupOf = (channel, entries) => {
3456
3470
  };
3457
3471
  };
3458
3472
  var CHANNELS = ["email", "linkedin"];
3459
- var byChannel = (entries) => CHANNELS.flatMap((channel) => {
3473
+ var byChannel = (entries, basis) => CHANNELS.flatMap((channel) => {
3460
3474
  const members = entries.filter(
3461
3475
  (entry) => entry.campaign.channel === channel
3462
3476
  );
3463
- return members.length === 0 ? [] : [groupOf(channel, members)];
3477
+ return members.length === 0 ? [] : [groupOf(channel, members, basis)];
3464
3478
  });
3465
- var byProvider = (entries) => [...new Set(entries.map((entry) => entry.campaign.provider))].toSorted().flatMap(
3479
+ var byProvider = (entries, basis) => [...new Set(entries.map((entry) => entry.campaign.provider))].toSorted().flatMap(
3466
3480
  (provider) => byChannel(
3467
- entries.filter((entry) => entry.campaign.provider === provider)
3481
+ entries.filter((entry) => entry.campaign.provider === provider),
3482
+ basis
3468
3483
  ).map(({ group, partial }) => ({
3469
3484
  group: { ...group, provider },
3470
3485
  partial
@@ -3507,7 +3522,7 @@ var compare = (groups, alpha, read, statuses) => {
3507
3522
  };
3508
3523
  };
3509
3524
  var channelMix = defineInsight({
3510
- description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. It reads active, paused and completed campaigns by default, since a channel's finished campaigns hold most of its evidence. With one channel present it returns that channel and says there is nothing to compare; on several tools, a note names a tool with no campaign in the states read. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
3525
+ description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. It reads active, paused and completed campaigns by default, since a channel's finished campaigns hold most of its evidence. With one channel present it returns that channel and says there is nothing to compare; on several tools, a note names a tool with no campaign in the states read. replyRateBasis names what every reply rate divides by, the same for every campaign: leads contacted, or messages sent when a campaign has replies in the range but contacted no new lead in it. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
3511
3526
  inputSchema: input10,
3512
3527
  key: "channelMix",
3513
3528
  cost: campaignTotalsCost,
@@ -3517,8 +3532,9 @@ var channelMix = defineInsight({
3517
3532
  next: "Use campaign_ranking to see which campaigns carry the better channel.",
3518
3533
  run: async (context, options) => {
3519
3534
  const { entries, read } = await readCampaignTotals(context, options);
3520
- const channels = byChannel(entries);
3521
- const providers = byProvider(entries);
3535
+ const basis = replyBasisAcross(entries.map((entry) => entry.counts));
3536
+ const channels = byChannel(entries, basis);
3537
+ const providers = byProvider(entries, basis);
3522
3538
  for (const { group, partial } of channels) {
3523
3539
  if (partial.length > 0) {
3524
3540
  context.note(partialNote(`Channel ${group.channel}`, partial));
@@ -3541,7 +3557,8 @@ var channelMix = defineInsight({
3541
3557
  ),
3542
3558
  byProvider: providers.map((each) => each.group),
3543
3559
  channels: channels.map((each) => each.group),
3544
- period: { from: options.from, to: options.to }
3560
+ period: { from: options.from, to: options.to },
3561
+ replyRateBasis: basis
3545
3562
  };
3546
3563
  return mix;
3547
3564
  }
@@ -3603,6 +3620,7 @@ var compare2 = (current, previous, basis, alpha) => {
3603
3620
  current: numbers,
3604
3621
  finding: test === null ? `${rateName} cannot be compared: a period has no reply count or nothing to divide it by, or neither has a reply.` : `${moved}; ${test.significant ? "more than chance" : "within what chance would give"} (${pText(test.pValue)}).`,
3605
3622
  previous: earlier,
3623
+ rates: { current: current.rates, previous: previous.rates },
3606
3624
  replyRateBasis: basis,
3607
3625
  replyRateTest: test,
3608
3626
  verdict: verdictOf(test)
@@ -3620,8 +3638,8 @@ var comparePeriods = (current, previous, alpha) => {
3620
3638
  var compareAcross = (current, previous, alpha) => {
3621
3639
  const counts = [sumMeasured(current), sumMeasured(previous)];
3622
3640
  const basis = periodBasis(...counts);
3623
- const now = ratesAcross(current, baseIn2(basis));
3624
- const before = ratesAcross(previous, baseIn2(basis));
3641
+ const now = ratesAcross(current, basis);
3642
+ const before = ratesAcross(previous, basis);
3625
3643
  return {
3626
3644
  comparison: compare2(
3627
3645
  { counts: counts[0], rates: now.rates },
@@ -4125,9 +4143,9 @@ var input14 = z17.object({
4125
4143
  ...listFields("one stats request"),
4126
4144
  min_sent: z17.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
4127
4145
  });
4128
- var groupOf2 = (tag, entries) => {
4146
+ var groupOf2 = (tag, entries, basis) => {
4129
4147
  const counts = entries.map((entry) => entry.counts);
4130
- const { partial, rates } = ratesAcross(counts);
4148
+ const { partial, rates } = ratesAcross(counts, basis);
4131
4149
  return {
4132
4150
  group: {
4133
4151
  ...totalsOf(sumMeasured(counts)),
@@ -4140,7 +4158,7 @@ var groupOf2 = (tag, entries) => {
4140
4158
  };
4141
4159
  var named = (group) => group.tag ?? "";
4142
4160
  var tagRollup = defineInsight({
4143
- description: "Results by campaign tag (for example one tag per client, offer or audience): for each tag the campaigns, messages sent, leads contacted, replies, positive replies and bounces, with reply, positive reply and bounce rates and their 95% intervals, sorted by the low end of the reply rate interval. A campaign with two tags counts in both; campaigns with none are grouped under a null tag. Tags under min_sent sends are listed apart. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a tag whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
4161
+ description: "Results by campaign tag (for example one tag per client, offer or audience): for each tag the campaigns, messages sent, leads contacted, replies, positive replies and bounces, with reply, positive reply and bounce rates and their 95% intervals, sorted by the low end of the reply rate interval. A campaign with two tags counts in both; campaigns with none are grouped under a null tag. Tags under min_sent sends are listed apart. replyRateBasis names what every reply rate divides by, the same for every campaign: leads contacted, or messages sent when a campaign has replies in the range but contacted no new lead in it. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a tag whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
4144
4162
  inputSchema: input14,
4145
4163
  key: "tagRollup",
4146
4164
  // A tool whose campaigns carry no tags would put every campaign under one
@@ -4161,7 +4179,10 @@ var tagRollup = defineInsight({
4161
4179
  members.set(tag, [...members.get(tag) ?? [], entry]);
4162
4180
  }
4163
4181
  }
4164
- const grouped = [...members].map(([tag, group]) => groupOf2(tag, group));
4182
+ const basis = replyBasisAcross(entries.map((entry) => entry.counts));
4183
+ const grouped = [...members].map(
4184
+ ([tag, group]) => groupOf2(tag, group, basis)
4185
+ );
4165
4186
  for (const { group, partial } of grouped) {
4166
4187
  if (partial.length > 0) {
4167
4188
  context.note(
@@ -4180,6 +4201,7 @@ var tagRollup = defineInsight({
4180
4201
  ...read,
4181
4202
  campaigns: entries.length,
4182
4203
  period: { from: options.from, to: options.to },
4204
+ replyRateBasis: basis,
4183
4205
  tags: groups.filter(enough2),
4184
4206
  tooFewSends: groups.filter((group) => !enough2(group))
4185
4207
  };
@@ -4442,9 +4464,149 @@ var accountSummary = defineInsight({
4442
4464
  // src/insights/people/dropped-replies.ts
4443
4465
  import { z as z19 } from "zod";
4444
4466
 
4445
- // src/insights/people/dropped-replies-check.ts
4467
+ // src/insights/people/thread-context.ts
4446
4468
  var HOUR = 36e5;
4447
4469
  var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
4470
+ var recordsMeetings = (outbound) => outbound.fields.lead?.meeting !== false;
4471
+ var timeOf2 = (message) => message.sentAt === null ? Number.NaN : Date.parse(message.sentAt);
4472
+ var lastAt = (messages, direction) => messages.findLast((message) => message.direction === direction)?.sentAt ?? null;
4473
+ var withoutBody = ({
4474
+ bodyHtml: _html,
4475
+ bodyText: _text,
4476
+ ...rest
4477
+ }) => rest;
4478
+ var activityOf = (messages) => {
4479
+ const timed = (messages ?? []).filter((message) => !Number.isNaN(timeOf2(message))).toSorted((left, right) => timeOf2(left) - timeOf2(right));
4480
+ const newest = timed.at(-1);
4481
+ return {
4482
+ lastInboundAt: lastAt(timed, "in"),
4483
+ lastOutboundAt: lastAt(timed, "out"),
4484
+ latest: newest === void 0 ? null : withoutBody(newest),
4485
+ messagesRead: messages?.length ?? 0
4486
+ };
4487
+ };
4488
+ var MEETING_WORDS = {
4489
+ booked: "booked",
4490
+ completed: "held",
4491
+ no_show: "missed (no-show)",
4492
+ won: "won"
4493
+ };
4494
+ var shown = (at) => at === null ? "at an unknown time" : `${at.slice(0, 10)} ${at.slice(11, 16)} UTC`;
4495
+ var hoursSince = (at, now) => Math.max(0, now - Date.parse(at)) / HOUR;
4496
+ var latestSentence = (latest2, now) => {
4497
+ const ago = waited(hoursSince(latest2.sentAt ?? "", now));
4498
+ if (latest2.direction === "out") {
4499
+ return `The latest message is outbound, sent ${ago} ago (${shown(latest2.sentAt)}).`;
4500
+ }
4501
+ return latest2.isAuto === true ? `The latest message is an automatic reply, received ${ago} ago (${shown(latest2.sentAt)}).` : `The latest message is inbound and unanswered for ${ago} (received ${shown(latest2.sentAt)}).`;
4502
+ };
4503
+ var labelSentence = (labelled, latest2) => {
4504
+ if (labelled === null || labelled === void 0 || labelled.ref === latest2.ref || labelled.sentAt === null || latest2.sentAt === null) {
4505
+ return [];
4506
+ }
4507
+ const gap = waited(
4508
+ Math.max(0, Date.parse(latest2.sentAt) - Date.parse(labelled.sentAt)) / HOUR
4509
+ );
4510
+ return [
4511
+ `The vendor's ${labelled.category} label is on an earlier reply (${shown(labelled.sentAt)}), ${gap} before the latest message, so it may not describe the conversation now.`
4512
+ ];
4513
+ };
4514
+ var meetingFacts = (facts) => {
4515
+ const { lead, provider } = facts;
4516
+ if (!facts.meetingsRecorded) {
4517
+ return {
4518
+ evidence: [],
4519
+ unchecked: [
4520
+ `Whether a meeting was booked: ${provider} records no meeting status on a lead.`
4521
+ ]
4522
+ };
4523
+ }
4524
+ if (lead === null) {
4525
+ return {
4526
+ evidence: [],
4527
+ unchecked: ["Whether a meeting was booked: the lead was not read."]
4528
+ };
4529
+ }
4530
+ const meeting = lead.meeting ?? null;
4531
+ return {
4532
+ evidence: [
4533
+ meeting === null ? `${provider} records no meeting for the lead.` : `${provider} records the lead's meeting as ${MEETING_WORDS[meeting]}.`
4534
+ ],
4535
+ unchecked: []
4536
+ };
4537
+ };
4538
+ var tagsUnchecked = (lead) => lead === null || lead.tags.length === 0 ? [] : [
4539
+ `The lead's tags (${lead.tags.join(", ")}) were not interpreted; a tag can record a meeting or a decision the rules do not read.`
4540
+ ];
4541
+ var READ_IT = "What the messages say: the rules read who wrote last and when, never the words, so read the latest message before acting.";
4542
+ var decide = (latest2, booked) => {
4543
+ if (booked) {
4544
+ return { basis: "meeting", needed: false };
4545
+ }
4546
+ if (latest2.direction === "out") {
4547
+ return { basis: "answered", needed: false };
4548
+ }
4549
+ return latest2.isAuto === true ? { basis: "automatic", needed: null } : { basis: "inbound_unanswered", needed: true };
4550
+ };
4551
+ var meetingRecorded = (lead) => {
4552
+ const meeting = lead?.meeting ?? null;
4553
+ return meeting !== null && meeting !== "no_show";
4554
+ };
4555
+ var assessFollowUp = (facts, activity) => {
4556
+ const meeting = meetingFacts(facts);
4557
+ const tags = tagsUnchecked(facts.lead);
4558
+ const booked = meetingRecorded(facts.lead);
4559
+ if (facts.messages === null) {
4560
+ return {
4561
+ basis: booked ? "meeting" : "not_read",
4562
+ evidence: meeting.evidence,
4563
+ needed: booked ? false : null,
4564
+ unchecked: [
4565
+ `The conversation was not read${facts.notRead === void 0 ? "" : ` (${facts.notRead})`}, so who wrote last is unknown; a vendor label alone does not show a reply is owed.`,
4566
+ ...meeting.unchecked,
4567
+ ...tags
4568
+ ]
4569
+ };
4570
+ }
4571
+ const { latest: latest2 } = activity;
4572
+ if (latest2 === null) {
4573
+ return {
4574
+ basis: booked ? "meeting" : "no_messages",
4575
+ evidence: meeting.evidence,
4576
+ needed: booked ? false : null,
4577
+ unchecked: [
4578
+ "Who wrote last: the conversation read holds no message with a time.",
4579
+ ...meeting.unchecked,
4580
+ ...tags
4581
+ ]
4582
+ };
4583
+ }
4584
+ return {
4585
+ ...decide(latest2, booked),
4586
+ evidence: [
4587
+ latestSentence(latest2, facts.now),
4588
+ ...labelSentence(facts.labelled, latest2),
4589
+ ...meeting.evidence
4590
+ ],
4591
+ unchecked: [READ_IT, ...meeting.unchecked, ...tags]
4592
+ };
4593
+ };
4594
+ var threadContext = (facts) => {
4595
+ const activity = activityOf(facts.messages);
4596
+ return {
4597
+ activity,
4598
+ followUp: assessFollowUp(facts, activity),
4599
+ meeting: facts.lead?.meeting ?? null,
4600
+ vendorSentiment: {
4601
+ leadCategory: facts.lead?.interestCategory ?? null,
4602
+ leadLabel: facts.lead?.interest ?? null,
4603
+ replyCategory: facts.labelled?.category ?? null
4604
+ }
4605
+ };
4606
+ };
4607
+
4608
+ // src/insights/people/dropped-replies-check.ts
4609
+ var HOUR2 = 36e5;
4448
4610
  var unanswered = (replies2, messages) => {
4449
4611
  const lastSent = Math.max(
4450
4612
  Number.NEGATIVE_INFINITY,
@@ -4458,12 +4620,12 @@ var unanswered = (replies2, messages) => {
4458
4620
  (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "")
4459
4621
  );
4460
4622
  };
4461
- var toDropped = (open, by, now) => {
4623
+ var toDropped = (open, by, now, messages) => {
4462
4624
  const [first] = open;
4463
4625
  if (first === void 0 || first.sentAt === null) {
4464
4626
  return [];
4465
4627
  }
4466
- const hoursWaiting = round((now - Date.parse(first.sentAt)) / HOUR) ?? 0;
4628
+ const hoursWaiting = round((now - Date.parse(first.sentAt)) / HOUR2) ?? 0;
4467
4629
  return [
4468
4630
  {
4469
4631
  campaign: first.campaignRef,
@@ -4474,8 +4636,14 @@ var toDropped = (open, by, now) => {
4474
4636
  finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${waited(hoursWaiting)} with nothing sent after it.`,
4475
4637
  hoursWaiting,
4476
4638
  email: null,
4639
+ labelled: {
4640
+ category: first.category,
4641
+ ref: first.ref,
4642
+ sentAt: first.sentAt
4643
+ },
4477
4644
  lead: first.leadRef,
4478
4645
  linkedinUrl: null,
4646
+ messages,
4479
4647
  name: null,
4480
4648
  provider: first.provider,
4481
4649
  receivedAt: first.sentAt,
@@ -4515,7 +4683,8 @@ var check = async (context, checkable, sent, olderThanHours) => {
4515
4683
  const openIn = (conversation, messages) => toDropped(
4516
4684
  unanswered(conversation.replies, messages),
4517
4685
  conversation.by,
4518
- context.now
4686
+ context.now,
4687
+ messages
4519
4688
  );
4520
4689
  const settle = (found, whole) => {
4521
4690
  if (found.length === 0) {
@@ -4569,7 +4738,7 @@ var check = async (context, checkable, sent, olderThanHours) => {
4569
4738
  };
4570
4739
 
4571
4740
  // src/insights/people/dropped-replies.ts
4572
- var DAY = 24 * HOUR;
4741
+ var DAY = 24 * HOUR2;
4573
4742
  var DEFAULT_DAYS = 14;
4574
4743
  var WINDOW_REPLIES = 2e3;
4575
4744
  var input16 = z19.object({
@@ -4621,6 +4790,12 @@ var conversationsOf = (replies2, readers) => {
4621
4790
  var refsOf = (refs) => [
4622
4791
  ...new Set(refs.flatMap((ref) => ref === null ? [] : [ref]))
4623
4792
  ];
4793
+ var findingOf2 = (finding, reply, found) => {
4794
+ const [latest2] = found.followUp.evidence;
4795
+ const latestIsReply = found.activity.latest?.ref === reply;
4796
+ const meeting = found.followUp.basis === "meeting" ? ` ${found.followUp.evidence.at(-1) ?? ""} Check it before following up.` : "";
4797
+ return latestIsReply || latest2 === void 0 ? `${finding}${meeting}` : `${finding} ${latest2} Read it before following up.${meeting}`;
4798
+ };
4624
4799
  var named2 = async (context, dropped) => {
4625
4800
  const { outbound } = context;
4626
4801
  const readLeads2 = outbound.capabilities["leads.get"];
@@ -4652,13 +4827,23 @@ var named2 = async (context, dropped) => {
4652
4827
  "names are null"
4653
4828
  )
4654
4829
  ]);
4655
- return dropped.map((each) => {
4830
+ return dropped.map(({ labelled, messages, ...each }) => {
4656
4831
  const lead = each.lead === null ? void 0 : leads.get(each.lead);
4657
4832
  const campaign = each.campaign === null ? void 0 : campaigns.get(each.campaign);
4833
+ const found = threadContext({
4834
+ labelled,
4835
+ lead: lead ?? null,
4836
+ meetingsRecorded: recordsMeetings(outbound),
4837
+ messages,
4838
+ now: context.now,
4839
+ provider: each.provider
4840
+ });
4658
4841
  return {
4659
4842
  ...each,
4843
+ ...found,
4660
4844
  campaignName: campaign?.name ?? null,
4661
4845
  email: lead?.email ?? null,
4846
+ finding: findingOf2(each.finding, each.reply, found),
4662
4847
  linkedinUrl: lead?.linkedinUrl ?? null,
4663
4848
  name: lead === void 0 ? null : nameOf(lead)
4664
4849
  };
@@ -4683,7 +4868,7 @@ var readReplies = (context, since, given) => {
4683
4868
  );
4684
4869
  };
4685
4870
  var droppedReplies = defineInsight({
4686
- description: "Replies from prospects that nobody answered. Reads every reply since a date (14 days before now by default, up to 2,000 or max_replies), keeps the categories that need an answer, and reports a conversation as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Where the tool lists the messages sent by hand (messages.byHand), one listing of those in the window settles every answered conversation; a conversation is read in full, by its thread or the lead's timeline, only when it may be dropped, or when that listing stopped at its max and did not answer it. Replies in conversations that belong to no campaign, such as a LinkedIn account's own messages on HeyReach, are set aside and counted in totals.notInCampaign unless include_inbox is true. Returns the dropped replies longest waiting first with hours waiting, category, the campaign and its name, and the lead with their name, email and LinkedIn profile. A reply that could not be checked, including one whose conversation could not be read, is counted in totals.unchecked with a note, never reported as dropped. Costs one request per page of replies and of messages sent by hand, one per conversation read in full, and one per lead and per campaign among the dropped replies to name them. totals.moreRepliesExist is true when the read stopped with replies left unread.",
4871
+ description: "Replies from prospects that nobody answered. Reads every reply since a date (14 days before now by default, up to 2,000 or max_replies), keeps the categories that need an answer, and reports a conversation as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Where the tool lists the messages sent by hand (messages.byHand), one listing of those in the window settles every answered conversation; a conversation is read in full, by its thread or the lead's timeline, only when it may be dropped, or when that listing stopped at its max and did not answer it. Replies in conversations that belong to no campaign, such as a LinkedIn account's own messages on HeyReach, are set aside and counted in totals.notInCampaign unless include_inbox is true. Returns the dropped replies longest waiting first with hours waiting, category, the campaign and its name, and the lead with their name, email and LinkedIn profile. A reply that could not be checked, including one whose conversation could not be read, is counted in totals.unchecked with a note and meta.complete: false, never reported as dropped. Costs one request per page of replies and of messages sent by hand, one per conversation read in full, and one per lead and per campaign among the dropped replies to name them. totals.moreRepliesExist is true when the read stopped with replies left unread. Dropped means only that nothing was sent after the reply: each one also carries the conversation's activity (its latest message, which can be a later message than the labelled reply), meeting (what the vendor records on the lead, Instantly only, so a prospect who booked through a calendar link shows as booked), vendorSentiment (the vendor's labels, kept apart) and followUp, a fixed-rule assessment with its evidence and what it could not check. No rule reads what a message says, so read the latest message with thread_context before following up.",
4687
4872
  inputSchema: input16,
4688
4873
  key: "droppedReplies",
4689
4874
  cost: (values, price) => {
@@ -4693,7 +4878,7 @@ var droppedReplies = defineInsight({
4693
4878
  scales: "max_replies",
4694
4879
  name: "dropped_replies",
4695
4880
  needs: ["replies.list"],
4696
- next: "Use person_summary with the lead's ref or email address to read what was sent before answering. Use hot_leads to see who else to contact first.",
4881
+ next: "Use thread_context with the dropped replies' lead refs to read the latest messages before answering. Use hot_leads to see who else to contact first.",
4697
4882
  run: async (context, values) => {
4698
4883
  const since = new Date(
4699
4884
  values.since === null ? context.now - DEFAULT_DAYS * DAY : Date.parse(values.since)
@@ -4737,6 +4922,12 @@ var droppedReplies = defineInsight({
4737
4922
  values.older_than_hours
4738
4923
  );
4739
4924
  const withNames = await named2(context, dropped);
4925
+ const notChecked = unchecked + unread;
4926
+ if (notChecked > 0) {
4927
+ context.partial(
4928
+ notChecked === conversations.length ? `None of the ${plural(notChecked, "conversation")} could be checked, so dropped counts none of them. totals.unchecked counts them, as neither dropped nor answered.` : `${plural(notChecked, "conversation")} of ${conversations.length} could not be checked, so dropped counts only the ${conversations.length - notChecked} that were. totals.unchecked counts the rest, as neither dropped nor answered.`
4929
+ );
4930
+ }
4740
4931
  const answer = {
4741
4932
  dropped: withNames.toSorted(
4742
4933
  (left, right) => right.hoursWaiting - left.hoursWaiting || left.reply.localeCompare(right.reply)
@@ -4753,7 +4944,7 @@ var droppedReplies = defineInsight({
4753
4944
  skippedAuto: wanted.length - kept.length,
4754
4945
  skippedByCategory: replies2.length - wanted.length,
4755
4946
  tooRecent,
4756
- unchecked: unchecked + unread
4947
+ unchecked: notChecked
4757
4948
  }
4758
4949
  };
4759
4950
  return answer;
@@ -5015,6 +5206,55 @@ var readCandidates = async (context, values) => {
5015
5206
  };
5016
5207
  };
5017
5208
 
5209
+ // src/insights/people/thread-read.ts
5210
+ var readConversation = async (context, target, bodies) => {
5211
+ const options = bodies ? { include: ["body"] } : {};
5212
+ try {
5213
+ const page = await (target.kind === "thread" ? context.outbound.thread(target.id).messages(options) : context.outbound.lead(target.id).timeline(options));
5214
+ return { failed: null, messages: context.page(page), target };
5215
+ } catch (error) {
5216
+ if (isCapStop(error)) {
5217
+ throw error;
5218
+ }
5219
+ return {
5220
+ failed: `the read failed with ${OutboundError.is(error) ? error.code : "an unexpected error"}`,
5221
+ messages: null,
5222
+ target
5223
+ };
5224
+ }
5225
+ };
5226
+ var inCampaign = (messages, lead) => messages.filter(
5227
+ (message) => message.campaignRef === null || lead === null || lead === void 0 || lead.campaignRef === null || message.campaignRef === lead.campaignRef
5228
+ );
5229
+ var leadContexts = async (context, leads, skipped = null) => {
5230
+ const { capabilities } = context.outbound;
5231
+ const unread = skipped ?? (capabilities["messages.list"] && capabilities["leads.timeline"] ? null : "this tool cannot read a lead's timeline (leads.timeline)");
5232
+ const reads = unread === null ? await mapConcurrent(
5233
+ leads,
5234
+ (lead) => readConversation(context, { id: lead.ref, kind: "lead" }, false)
5235
+ ) : leads.map((lead) => ({
5236
+ failed: unread,
5237
+ messages: null,
5238
+ target: { id: lead.ref, kind: "lead" }
5239
+ }));
5240
+ return new Map(
5241
+ reads.map((read, index) => {
5242
+ const lead = leads[index] ?? null;
5243
+ return [
5244
+ read.target.id,
5245
+ threadContext({
5246
+ lead,
5247
+ meetingsRecorded: recordsMeetings(context.outbound),
5248
+ messages: read.messages === null ? null : inCampaign(read.messages, lead),
5249
+ notRead: read.failed ?? void 0,
5250
+ now: context.now,
5251
+ provider: lead?.provider ?? context.outbound.provider
5252
+ })
5253
+ ];
5254
+ })
5255
+ );
5256
+ };
5257
+
5018
5258
  // src/insights/people/hot-leads.ts
5019
5259
  var DAY3 = 864e5;
5020
5260
  var weight = (value, what) => z20.number().min(0).default(value).describe(what);
@@ -5039,6 +5279,9 @@ var input17 = z20.object({
5039
5279
  "Also walk the lead list up to max_leads, to rank leads whose only signal is opens or clicks. Where the tool cannot filter leads by interest the list is walked anyway."
5040
5280
  ),
5041
5281
  positive_labels: positiveLabelsField,
5282
+ read_threads: z20.boolean().default(false).describe(
5283
+ "Set to true to read each returned lead's conversation (one walk of messages each, up to limit) for who wrote last and a follow-up assessment. false leaves followUp.needed null with basis not_read; thread_context reads them later."
5284
+ ),
5042
5285
  recency_days: z20.number().min(1).default(14).describe(
5043
5286
  "A reply today earns the full recency points, fading evenly to none after this many days"
5044
5287
  ),
@@ -5153,14 +5396,14 @@ var staleOf = (leads, values, now) => new Set(
5153
5396
  );
5154
5397
  var hotLeads = defineInsight({
5155
5398
  partialOnCap: true,
5156
- description: "Who to call first: leads ranked by a score built from a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. Candidates come from the signal: every reply within recency_days (up to max_replies, a safety ceiling, so complete means complete for the window) and, where the tool filters leads by interest (leads.byInterest), the leads it labels positive, up to max_leads. Leads behind those replies that no listing read are then looked up, many addresses in one request where the tool can (leads.lookupMany), otherwise one request each for the newest limit of them; one that cannot be read is counted in totals.unreadable. Where the tool cannot filter by interest, positive_labels names a label beyond Interested, Meeting Booked, Meeting Completed and Won, or include_engagement_only is true, the lead list is walked too, up to max_leads, for leads whose only signal is opens or clicks; totals.moreLeadsExist says that cap left leads unread. A reply read in the window fills a lead's reply count and last reply time when its record reports less. A positive label keeps its points while the last reply is within recency_days and fades to nothing at max_age_days, and a lead whose last reply is older than that is listed after every fresher one (totals.stale). A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign (an unknown one is refused with NotFound), or none to rank every lead. A lead the vendor labels out-of-office or bounced earns no reply or recency points, and so does a lead whose every reply in the window is flagged automatic (isAuto, from the vendor or a fixed rule); both are counted in totals.autoReplied. A lead labelled negative (not interested, wrong person, unsubscribed, do not contact) earns no points at all and is listed after every lead with a score above 0 while limit leaves room; its reason names the label. While the redact plugin masks email addresses, which a reply can name its lead by, the lead behind a reply is read through the plugin, which puts the address back on the call and masks the answer; a token it no longer remembers is not looked up, which a note says, and the answer is marked incomplete. A part that is null means the vendor does not report that signal.",
5399
+ description: "Who to call first: leads ranked by a score built from a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. Candidates come from the signal: every reply within recency_days (up to max_replies, a safety ceiling, so complete means complete for the window) and, where the tool filters leads by interest (leads.byInterest), the leads it labels positive, up to max_leads. Leads behind those replies that no listing read are then looked up, many addresses in one request where the tool can (leads.lookupMany), otherwise one request each for the newest limit of them; one that cannot be read is counted in totals.unreadable. Where the tool cannot filter by interest, positive_labels names a label beyond Interested, Meeting Booked, Meeting Completed and Won, or include_engagement_only is true, the lead list is walked too, up to max_leads, for leads whose only signal is opens or clicks; totals.moreLeadsExist says that cap left leads unread. A reply read in the window fills a lead's reply count and last reply time when its record reports less. A positive label keeps its points while the last reply is within recency_days and fades to nothing at max_age_days, and a lead whose last reply is older than that is listed after every fresher one (totals.stale). A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign (an unknown one is refused with NotFound), or none to rank every lead. A lead the vendor labels out-of-office or bounced earns no reply or recency points, and so does a lead whose every reply in the window is flagged automatic (isAuto, from the vendor or a fixed rule); both are counted in totals.autoReplied. A lead labelled negative (not interested, wrong person, unsubscribed, do not contact) earns no points at all and is listed after every lead with a score above 0 while limit leaves room; its reason names the label. While the redact plugin masks email addresses, which a reply can name its lead by, the lead behind a reply is read through the plugin, which puts the address back on the call and masks the answer; a token it no longer remembers is not looked up, which a note says, and the answer is marked incomplete. A part that is null means the vendor does not report that signal. The score ranks the vendor's signals and is not a verdict that a reply is owed. Each lead carries meeting (what the vendor records on the lead, Instantly only) and vendorSentiment (the vendor's labels, kept apart); with read_threads each returned lead's conversation is also read, one walk of messages each, and the lead carries activity (the latest message, who sent it and when), meeting (what the vendor records on the lead, Instantly only), vendorSentiment (the vendor's labels, kept apart) and followUp, a fixed-rule assessment whose needed is true only when the latest message is inbound, not automatic and no meeting is recorded, with its evidence and what it could not check. No rule reads what a message says.",
5157
5400
  inputSchema: input17,
5158
5401
  key: "hotLeads",
5159
5402
  cost: (values, price) => {
5160
5403
  const { capabilities } = price;
5161
5404
  const filtered = capabilities["leads.byInterest"] === true;
5162
5405
  const replies2 = capabilities["replies.list"] !== false;
5163
- return (filtered ? price.list("leads.list", values.max_leads) : 0) + (!filtered || values.include_engagement_only ? price.list("leads.list", values.max_leads) : 0) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (replies2 ? price.list("replies.list", values.max_replies) : 0) + (replies2 && capabilities["leads.lookupMany"] === true ? price.upTo(Math.ceil(values.max_replies / 100)) * price.list("leads.list", 100) : 0) + (replies2 && capabilities["leads.get"] !== false ? price.upTo(values.limit) * price.one("leads.get") : 0);
5406
+ return (filtered ? price.list("leads.list", values.max_leads) : 0) + (!filtered || values.include_engagement_only ? price.list("leads.list", values.max_leads) : 0) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (replies2 ? price.list("replies.list", values.max_replies) : 0) + (replies2 && capabilities["leads.lookupMany"] === true ? price.upTo(Math.ceil(values.max_replies / 100)) * price.list("leads.list", 100) : 0) + (replies2 && capabilities["leads.get"] !== false ? price.upTo(values.limit) * price.one("leads.get") : 0) + (values.read_threads && capabilities["leads.timeline"] ? price.upTo(values.limit) * price.walk("messages.list") : 0);
5164
5407
  },
5165
5408
  scales: "max_replies",
5166
5409
  name: "hot_leads",
@@ -5207,8 +5450,18 @@ var hotLeads = defineInsight({
5207
5450
  const negative = open.filter((lead) => saidNo(lead, scoring));
5208
5451
  const refused = new Set(negative.map((lead) => lead.ref));
5209
5452
  const after = scored.filter((lead) => lead.score <= 0 && refused.has(lead.lead)).toSorted(hottestFirst);
5453
+ const ranked = [...hot, ...after].slice(0, values.limit);
5454
+ const byRef = new Map(open.map((lead) => [lead.ref, lead]));
5455
+ const contexts = await leadContexts(
5456
+ context,
5457
+ ranked.flatMap((each) => {
5458
+ const lead = byRef.get(each.lead);
5459
+ return lead === void 0 ? [] : [lead];
5460
+ }),
5461
+ values.read_threads ? null : "read_threads is false; pass the lead refs to thread_context"
5462
+ );
5210
5463
  const answer = {
5211
- leads: [...hot, ...after].slice(0, values.limit),
5464
+ leads: ranked.map((each) => ({ ...each, ...contexts.get(each.lead) })),
5212
5465
  totals: {
5213
5466
  autoReplied: open.filter(
5214
5467
  (lead) => scoring.automatic(lead) && repliesOf(lead) > 0
@@ -5234,24 +5487,6 @@ var hotLeads = defineInsight({
5234
5487
  import { z as z21 } from "zod";
5235
5488
 
5236
5489
  // src/insights/people/find.ts
5237
- var EMAIL = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/u;
5238
- var DOMAIN2 = /^@?[^\s@/:]+(?:\.[^\s@/:.]+)+$/u;
5239
- var bare = (identifier) => identifier.trim().replace(/^mailto:/iu, "");
5240
- var personKey = (identifier) => {
5241
- const value = bare(identifier);
5242
- const slug = profileSlug(value);
5243
- if (slug !== null) {
5244
- return `linkedin:${slug}`;
5245
- }
5246
- return EMAIL.test(value) ? `email:${value.toLowerCase()}` : null;
5247
- };
5248
- var notAPerson = (identifier) => {
5249
- const value = bare(identifier);
5250
- if (DOMAIN2.test(value)) {
5251
- return `"${value}" is a company domain, not a person. Use account_summary for a company domain`;
5252
- }
5253
- return value.includes("@") ? `"${value}" is not a valid email address` : "Give an email address, a LinkedIn profile URL or a lead ref";
5254
- };
5255
5490
  var keysOfLead = (lead) => {
5256
5491
  const slug = profileSlug(lead.linkedinUrl);
5257
5492
  return [
@@ -5282,7 +5517,14 @@ var refuse = (outbound, masked, why) => new OutboundError(
5282
5517
  `A person cannot be looked up while the redact plugin masks ${maskedWords(masked)}: ${why}`,
5283
5518
  { provider: outbound.provider }
5284
5519
  );
5285
- var isLeadRef = (identifier) => personKey(identifier) === null && parseRef(identifier.trim()) !== null;
5520
+ var refNeedsRead = (identifier) => {
5521
+ try {
5522
+ const parsed = parsePerson(identifier, "");
5523
+ return parsed.ref !== null && parsed.key === null;
5524
+ } catch {
5525
+ return false;
5526
+ }
5527
+ };
5286
5528
  var PROFILE = "https://www.linkedin.com/in/";
5287
5529
  var formsOf = (key, given) => {
5288
5530
  const value = key.slice(key.indexOf(":") + 1);
@@ -5295,7 +5537,10 @@ var formsOf = (key, given) => {
5295
5537
  };
5296
5538
  var startFrom = async (context, identifier, { hash, masked }) => {
5297
5539
  const { outbound } = context;
5298
- const key = personKey(identifier);
5540
+ const { key, ref } = parsePerson(identifier, outbound.provider);
5541
+ if (ref !== null) {
5542
+ assertRefReadable(outbound, ref);
5543
+ }
5299
5544
  if (key !== null) {
5300
5545
  if (!masked.includes(kindOf(key))) {
5301
5546
  return { hashed: null, keys: [key], records: [] };
@@ -5307,7 +5552,7 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5307
5552
  "the records could not be matched to the identifier"
5308
5553
  );
5309
5554
  }
5310
- const tokens = formsOf(key, identifier).map(hash);
5555
+ const tokens = formsOf(key, ref?.sourceId ?? identifier).map(hash);
5311
5556
  return {
5312
5557
  hashed: {
5313
5558
  shown: `${kindOf(key)}:${tokens[0] ?? ""}`,
@@ -5317,11 +5562,6 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5317
5562
  records: []
5318
5563
  };
5319
5564
  }
5320
- if (!isLeadRef(identifier)) {
5321
- throw new OutboundError("Invalid", notAPerson(identifier), {
5322
- provider: outbound.provider
5323
- });
5324
- }
5325
5565
  const instead = hash === void 0 ? null : "a lead's identifiers are hashed on its record, so give the email address or LinkedIn profile URL instead";
5326
5566
  if (masked.length === 2) {
5327
5567
  throw refuse(
@@ -5330,7 +5570,7 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5330
5570
  instead ?? "a lead ref has no identifier left to look the person up by"
5331
5571
  );
5332
5572
  }
5333
- const lead = context.one(await outbound.leads.get(identifier.trim()));
5573
+ const lead = context.one(await outbound.leads.get(ref?.text ?? identifier));
5334
5574
  const keys = keysOfLead(lead).filter(
5335
5575
  (each) => !masked.includes(kindOf(each))
5336
5576
  );
@@ -5405,11 +5645,11 @@ var findPerson = async (context, identifier, maxRecords) => {
5405
5645
  }
5406
5646
  }
5407
5647
  }
5408
- const shown = [...keys].map(
5648
+ const shown2 = [...keys].map(
5409
5649
  (key) => start.hashed !== null && start.keys.includes(key) ? start.hashed.shown : key
5410
5650
  );
5411
5651
  return {
5412
- keys: shown.toSorted(),
5652
+ keys: shown2.toSorted(),
5413
5653
  records: [...records.values()].slice(0, maxRecords)
5414
5654
  };
5415
5655
  };
@@ -5472,7 +5712,7 @@ var toCollision = (group) => {
5472
5712
  campaignCount: campaigns.length,
5473
5713
  campaigns,
5474
5714
  channels,
5475
- finding: findingOf2(shownKey(identifiers[0] ?? ""), campaigns, {
5715
+ finding: findingOf3(shownKey(identifiers[0] ?? ""), campaigns, {
5476
5716
  channels,
5477
5717
  providers
5478
5718
  }),
@@ -5488,7 +5728,7 @@ var named3 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName
5488
5728
  var withStatus = (campaigns) => listed(
5489
5729
  campaigns.map((each) => `"${each.campaignName}" (${each.leadStatus})`)
5490
5730
  );
5491
- var findingOf2 = (who, campaigns, tools) => {
5731
+ var findingOf3 = (who, campaigns, tools) => {
5492
5732
  const active = campaigns.filter((each) => each.leadStatus === "active");
5493
5733
  const past = campaigns.filter((each) => each.leadStatus !== "active");
5494
5734
  if (active.length >= 2) {
@@ -5559,11 +5799,11 @@ var leadCollisions = defineInsight({
5559
5799
  // src/insights/people/person-summary.ts
5560
5800
  import { z as z22 } from "zod";
5561
5801
  var input19 = z22.object({
5562
- max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
5563
- person: z22.string().min(3).describe(
5564
- "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
5565
- )
5566
- });
5802
+ max_campaigns: z22.number().int().min(1).max(50).default(20).describe(
5803
+ "The most campaigns to report on. Each costs up to 2 requests."
5804
+ ),
5805
+ ...personFields
5806
+ }).superRefine(checkPerson);
5567
5807
  var times2 = (messages, direction) => messages.flatMap(
5568
5808
  (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
5569
5809
  );
@@ -5584,7 +5824,7 @@ var repliedSteps = (lead, messages) => {
5584
5824
  }
5585
5825
  return [...steps].toSorted((left, right) => left - right);
5586
5826
  };
5587
- var activityOf = (lead, messages) => {
5827
+ var activityOf2 = (lead, messages) => {
5588
5828
  const sent = times2(messages, "out");
5589
5829
  const received = times2(
5590
5830
  messages.filter((message) => !isAutoMessage(message)),
@@ -5639,7 +5879,7 @@ var summarize2 = async (context, timelines, lead) => {
5639
5879
  timelineOf(context, timelines, lead),
5640
5880
  lead.campaignRef === null ? null : outbound.campaigns.get(lead.campaignRef).then(context.one)
5641
5881
  ]);
5642
- const { automatic, threadIsShort, ...counted2 } = activityOf(lead, messages);
5882
+ const { automatic, threadIsShort, ...counted2 } = activityOf2(lead, messages);
5643
5883
  const autoReplied = isAutoReplied(lead) || automatic > 0 && counted2.replies === 0;
5644
5884
  const activity = autoReplied ? { ...counted2, lastRepliedAt: null, replies: 0 } : counted2;
5645
5885
  noteAutomatic(context, lead, counted2.replies + automatic, automatic);
@@ -5654,6 +5894,13 @@ var summarize2 = async (context, timelines, lead) => {
5654
5894
  );
5655
5895
  return {
5656
5896
  ...activity,
5897
+ ...threadContext({
5898
+ lead,
5899
+ meetingsRecorded: recordsMeetings(outbound),
5900
+ messages,
5901
+ now: context.now,
5902
+ provider: lead.provider
5903
+ }),
5657
5904
  campaign: lead.campaignRef,
5658
5905
  campaignName: campaign?.name ?? null,
5659
5906
  campaignStatus: campaign?.status ?? null,
@@ -5688,10 +5935,10 @@ var byChannel2 = (campaigns) => {
5688
5935
  return channels;
5689
5936
  };
5690
5937
  var personSummary = defineInsight({
5691
- description: "Everything about one person across campaigns and channels, from their email address, LinkedIn profile or a lead ref: each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic, and a reply in the thread flagged automatic (isAuto, from the vendor or a fixed rule) is not counted either. Costs one lookup per identifier, one request to read a lead ref, then up to 2 requests per campaign.",
5938
+ description: "Everything about one person across campaigns and channels, from one of lead_ref (a lead ref exactly as another tool returned it), email, linkedin_url, or person (any of the three): each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic, and a reply in the thread flagged automatic (isAuto, from the vendor or a fixed rule) is not counted either. A lead ref from a tool or workspace the instance does not read is refused before any request. Costs one lookup per identifier, one request to read a lead ref whose id is not already an address or profile (an Instantly reply's leadRef and a HeyReach ref need none), then up to 2 requests per campaign. Each campaign also carries its conversation's context: activity (the latest message, who sent it and when), meeting (what the vendor records on the lead, Instantly only), vendorSentiment (the vendor's labels, kept apart) and followUp, a fixed-rule assessment whose needed is true only when the latest message is inbound, not automatic and no meeting is recorded, with its evidence and what it could not check.",
5692
5939
  inputSchema: input19,
5693
5940
  key: "personSummary",
5694
- cost: (values, price) => (isLeadRef(values.person) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
5941
+ cost: (values, price) => (refNeedsRead(personOf(values)) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
5695
5942
  scales: "max_campaigns",
5696
5943
  name: "person_summary",
5697
5944
  maskedOut: (masking) => {
@@ -5699,10 +5946,11 @@ var personSummary = defineInsight({
5699
5946
  return masked.has("email") && masked.has("linkedin") && masking.strategy === "mask" ? "email addresses and LinkedIn profiles, which it looks a person up by" : null;
5700
5947
  },
5701
5948
  needs: ["leads.lookup", "leads.timeline"],
5702
- needsFor: ({ person }) => isLeadRef(person) ? ["leads.get"] : [],
5949
+ needsFor: (values) => refNeedsRead(personOf(values)) ? ["leads.get"] : [],
5703
5950
  next: "Use account_summary with their email domain to see everyone at the same company.",
5704
- run: async (context, { max_campaigns: maxCampaigns, person }) => {
5705
- const found = await findPerson(context, person, maxCampaigns);
5951
+ run: async (context, values) => {
5952
+ const maxCampaigns = values.max_campaigns;
5953
+ const found = await findPerson(context, personOf(values), maxCampaigns);
5706
5954
  const timelines = /* @__PURE__ */ new Map();
5707
5955
  const campaigns = await mapConcurrent(
5708
5956
  found.records,
@@ -6053,6 +6301,195 @@ var suppressionCheck = defineInsight({
6053
6301
  }
6054
6302
  });
6055
6303
 
6304
+ // src/insights/people/thread-contexts.ts
6305
+ import { z as z25 } from "zod";
6306
+ var SNIPPET_CHARS = 280;
6307
+ var ids = (what) => z25.array(z25.string().min(1)).max(100).default([]).describe(what);
6308
+ var input22 = z25.object({
6309
+ bodies: z25.enum(["none", "snippet"]).default("snippet").describe(
6310
+ "snippet returns the first 280 characters of each message, wrapped as untrusted content; none returns no text"
6311
+ ),
6312
+ cursor: z25.string().min(1).nullable().default(null).describe(
6313
+ "coverage.nextCursor from the previous call with the same leads and threads, to read the next page of conversations"
6314
+ ),
6315
+ leads: ids(
6316
+ "Lead refs (provider:workspace:id), as dropped_replies, hot_leads and person_summary return them. Each lead's conversation in its campaign is read."
6317
+ ),
6318
+ max_messages: z25.number().int().min(1).max(100).default(10).describe(
6319
+ "The newest messages returned per conversation. Every message is still read, so the latest is always found."
6320
+ ),
6321
+ page_size: z25.number().int().min(1).max(50).default(20).describe(
6322
+ "Conversations read per call. Each costs one walk of its messages."
6323
+ ),
6324
+ threads: ids("Thread ids, from a message's or reply's threadId")
6325
+ });
6326
+ var targetsOf = (values) => [
6327
+ ...[...new Set(values.leads)].map((id) => ({ id, kind: "lead" })),
6328
+ ...[...new Set(values.threads)].map((id) => ({
6329
+ id,
6330
+ kind: "thread"
6331
+ }))
6332
+ ];
6333
+ var startOf = (cursor, total2) => {
6334
+ if (cursor === null) {
6335
+ return 0;
6336
+ }
6337
+ const [offset, of] = cursor.split("/").map(Number);
6338
+ if (offset === void 0 || of !== total2 || !Number.isInteger(offset) || offset < 0 || offset >= total2) {
6339
+ throw new OutboundError(
6340
+ "Invalid",
6341
+ "thread_context: cursor does not belong to these leads and threads; pass the nextCursor of a call with the same leads and threads"
6342
+ );
6343
+ }
6344
+ return offset;
6345
+ };
6346
+ var leadRefOf = (read) => read.target.kind === "lead" ? read.target.id : read.messages?.find((message) => message.leadRef !== null)?.leadRef ?? null;
6347
+ var toMessage = (message, bodies) => ({
6348
+ ...withoutBody(message),
6349
+ snippet: bodies ? untrusted(
6350
+ message.bodyText?.replaceAll(/\s+/gu, " ").trim() || null,
6351
+ SNIPPET_CHARS
6352
+ ) : null
6353
+ });
6354
+ var partyOf = (lead, messages) => ({
6355
+ campaign: lead?.campaignRef ?? messages.find((message) => message.campaignRef !== null)?.campaignRef ?? null,
6356
+ email: lead?.email ?? null,
6357
+ linkedinUrl: lead?.linkedinUrl ?? null,
6358
+ threadIds: [
6359
+ ...new Set(
6360
+ messages.flatMap(
6361
+ (message) => message.threadId === null ? [] : [message.threadId]
6362
+ )
6363
+ )
6364
+ ]
6365
+ });
6366
+ var recordOf = (context, read, lead, values) => {
6367
+ const messages = read.messages === null ? null : inCampaign(read.messages, lead).toSorted(
6368
+ (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "")
6369
+ );
6370
+ const all = messages ?? [];
6371
+ const shown2 = all.slice(-values.max_messages);
6372
+ return {
6373
+ ...threadContext({
6374
+ lead: lead ?? null,
6375
+ meetingsRecorded: recordsMeetings(context.outbound),
6376
+ messages,
6377
+ notRead: read.failed ?? void 0,
6378
+ now: context.now,
6379
+ provider: lead?.provider ?? all[0]?.provider ?? context.outbound.provider
6380
+ }),
6381
+ ...partyOf(lead, all),
6382
+ lead: leadRefOf(read),
6383
+ messages: shown2.map(
6384
+ (message) => toMessage(message, values.bodies === "snippet")
6385
+ ),
6386
+ messagesOmitted: all.length - shown2.length,
6387
+ target: read.target
6388
+ };
6389
+ };
6390
+ var coverageOf = (records, reads, page) => {
6391
+ const end = page.start + reads.length;
6392
+ return {
6393
+ checked: reads.filter((read) => read.failed === null).length,
6394
+ found: records.filter((record) => record.activity.messagesRead > 0).length,
6395
+ nextCursor: end < page.total ? `${end}/${page.total}` : null,
6396
+ notFound: records.flatMap(
6397
+ (record, index) => reads[index]?.failed === null && record.activity.messagesRead === 0 ? [{ reason: "read, with no messages", target: record.target }] : []
6398
+ ),
6399
+ remaining: page.total - end,
6400
+ requested: page.total,
6401
+ unchecked: reads.flatMap(
6402
+ (read) => read.failed === null ? [] : [{ reason: read.failed, target: read.target }]
6403
+ )
6404
+ };
6405
+ };
6406
+ var threadContexts = defineInsight({
6407
+ description: "Reads the conversations behind given lead refs or thread ids, in pages, without a campaign-wide reply read: each conversation's newest messages (a 280-character snippet each, wrapped as untrusted content, unless bodies is none), who wrote last and when, the meeting the vendor records on the lead (Instantly's interest status; other vendors record none, which the answer says), the vendor's own labels kept apart in vendorSentiment, and a follow-up assessment from fixed rules: needed is true only when the latest message is inbound, not automatic and no meeting is recorded, false when the latest message is outbound or a meeting is recorded, null otherwise, with the evidence it used and what it could not check. No rule reads what a message says, so read the latest message before acting on it. coverage gives how many were requested, read and found, which could not be read and why, and nextCursor for the next page. Costs one walk of messages per conversation and up to one lead read per conversation.",
6408
+ inputSchema: input22,
6409
+ key: "threadContext",
6410
+ cost: (values, price) => {
6411
+ const conversations = Math.min(
6412
+ values.page_size,
6413
+ new Set(values.leads).size + new Set(values.threads).size
6414
+ );
6415
+ return conversations * price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.upTo(conversations) * price.one("leads.get"));
6416
+ },
6417
+ name: "thread_context",
6418
+ needs: ["messages.list"],
6419
+ needsFor: ({ leads, threads }) => [
6420
+ ...leads.length > 0 ? ["leads.timeline"] : [],
6421
+ ...threads.length > 0 ? ["messages.byThread"] : []
6422
+ ],
6423
+ next: "Read each record's latest message before following up. Use person_summary with a lead ref for the person's other campaigns.",
6424
+ run: async (context, values) => {
6425
+ const targets = targetsOf(values);
6426
+ if (targets.length === 0) {
6427
+ context.note(
6428
+ "No lead refs or thread ids were given, so nothing was read. Pass leads or threads."
6429
+ );
6430
+ }
6431
+ if (values.bodies === "snippet" && (maskingOf(context.outbound)?.fields.includes("body") ?? false)) {
6432
+ throw new OutboundError(
6433
+ "Unsupported",
6434
+ "thread_context: the redact plugin masks message bodies, so snippets cannot be returned; pass bodies: none"
6435
+ );
6436
+ }
6437
+ for (const target of targets) {
6438
+ const parts = target.kind === "lead" ? leadRefParts(target.id) : null;
6439
+ if (target.kind === "lead" && parts === null) {
6440
+ throw new OutboundError(
6441
+ "Invalid",
6442
+ `thread_context: "${target.id}" is not a lead ref (provider:workspace:id); pass the lead ref another tool returned`,
6443
+ { provider: context.outbound.provider }
6444
+ );
6445
+ }
6446
+ if (parts !== null) {
6447
+ assertRefReadable(context.outbound, { ...parts, text: target.id });
6448
+ }
6449
+ }
6450
+ const start = startOf(values.cursor, targets.length);
6451
+ const page = targets.slice(start, start + values.page_size);
6452
+ const reads = await mapConcurrent(
6453
+ page,
6454
+ (target) => readConversation(context, target, values.bodies === "snippet")
6455
+ );
6456
+ const refs = [
6457
+ ...new Set(
6458
+ reads.flatMap((read) => {
6459
+ const ref = leadRefOf(read);
6460
+ return ref === null ? [] : [ref];
6461
+ })
6462
+ )
6463
+ ];
6464
+ const leads = context.outbound.capabilities["leads.get"] ? await readByRef(
6465
+ context,
6466
+ refs,
6467
+ (each) => context.outbound.leads.getMany(each),
6468
+ ["lead", "leads"],
6469
+ "meetings and labels are unknown"
6470
+ ) : /* @__PURE__ */ new Map();
6471
+ const records = reads.map((read) => {
6472
+ const ref = leadRefOf(read);
6473
+ return recordOf(
6474
+ context,
6475
+ read,
6476
+ ref === null ? void 0 : leads.get(ref),
6477
+ values
6478
+ );
6479
+ });
6480
+ if (start + page.length < targets.length) {
6481
+ context.partial(
6482
+ `Read ${start + page.length} of ${targets.length} conversations; pass coverage.nextCursor for the rest.`
6483
+ );
6484
+ }
6485
+ const answer = {
6486
+ coverage: coverageOf(records, reads, { start, total: targets.length }),
6487
+ threads: records
6488
+ };
6489
+ return answer;
6490
+ }
6491
+ });
6492
+
6056
6493
  // src/insights/people/index.ts
6057
6494
  var PEOPLE_INSIGHTS = [
6058
6495
  personSummary,
@@ -6061,22 +6498,23 @@ var PEOPLE_INSIGHTS = [
6061
6498
  suppressionCheck,
6062
6499
  droppedReplies,
6063
6500
  hotLeads,
6501
+ threadContexts,
6064
6502
  personalizationGaps
6065
6503
  ];
6066
6504
 
6067
6505
  // src/insights/senders/bounce-watch.ts
6068
- import { z as z25 } from "zod";
6506
+ import { z as z26 } from "zod";
6069
6507
 
6070
6508
  // src/insights/senders/read.ts
6071
6509
  var readCampaigns = async (context, statuses, max) => {
6072
6510
  const { items } = await readCampaignsIn(context, statuses, max);
6073
6511
  return items;
6074
6512
  };
6075
- var readCampaignSenders = async (context, campaign, max, input28) => {
6513
+ var readCampaignSenders = async (context, campaign, max, input29) => {
6076
6514
  const { items } = await readCapped(
6077
6515
  context,
6078
6516
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
6079
- { input: input28, max, per: "campaigns", what: "senders" }
6517
+ { input: input29, max, per: "campaigns", what: "senders" }
6080
6518
  );
6081
6519
  return items;
6082
6520
  };
@@ -6098,6 +6536,24 @@ var readHealth = async (context, sender) => {
6098
6536
  return null;
6099
6537
  }
6100
6538
  };
6539
+ var readHealthInPages = async (context, senders2, max) => {
6540
+ const { items } = await readCapped(
6541
+ context,
6542
+ (cap) => context.outbound.senderHealth.listAll({ max: cap }),
6543
+ { input: "max_senders", max, what: "senders' health" }
6544
+ );
6545
+ const byRef = new Map(items.map((health) => [health.senderRef, health]));
6546
+ const missing2 = senders2.filter((sender) => !byRef.has(sender.ref)).length;
6547
+ if (missing2 > 0) {
6548
+ context.partial(
6549
+ `Left out ${missing2} of ${senders2.length} senders: the vendor returned no health for them.`
6550
+ );
6551
+ }
6552
+ return senders2.map((sender) => ({
6553
+ health: byRef.get(sender.ref) ?? null,
6554
+ sender
6555
+ }));
6556
+ };
6101
6557
  var domainOf2 = (address2) => {
6102
6558
  const domain = address2?.split("@")[1]?.trim().toLowerCase() ?? "";
6103
6559
  return domain === "" ? null : domain;
@@ -6120,15 +6576,15 @@ var countEach = (keys, count2) => (
6120
6576
  );
6121
6577
 
6122
6578
  // src/insights/senders/bounce-watch.ts
6123
- var input22 = z25.object({
6579
+ var input23 = z26.object({
6124
6580
  ...rangeFields,
6125
- include_senders: z25.boolean().default(true).describe(
6581
+ include_senders: z26.boolean().default(true).describe(
6126
6582
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
6127
6583
  ),
6128
- max_bounce_rate: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
6129
- max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
6130
- max_senders_per_campaign: z25.number().int().min(1).max(200).default(10).describe("The most senders to check for one campaign over the threshold"),
6131
- min_sent: z25.number().int().min(0).default(100).describe(
6584
+ max_bounce_rate: z26.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
6585
+ max_campaigns: z26.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
6586
+ max_senders_per_campaign: z26.number().int().min(1).max(200).default(10).describe("The most senders to check for one campaign over the threshold"),
6587
+ min_sent: z26.number().int().min(0).default(100).describe(
6132
6588
  "A campaign or sender with fewer sends than this is too small to judge"
6133
6589
  ),
6134
6590
  statuses: statusesInput(["active"])
@@ -6200,7 +6656,7 @@ var canCheckSenders = (context, wanted) => {
6200
6656
  };
6201
6657
  var bounceWatch = defineInsight({
6202
6658
  description: "Where bounces are too high: the campaigns whose bounce rate (bounced divided by sent) is over a threshold, worst first, each with bounced, sent, the rate and its Wilson interval, and the senders of each such campaign that are themselves over the threshold. Campaigns with too few sends to judge and campaigns with no reported bounce count are listed apart, never as clean. Use it daily, or when a domain's reputation is in doubt. Costs one listing of campaigns and 1 request per campaign, plus 1 listing and up to 1 request per sender for each campaign over the threshold. A null rate means nothing was sent.",
6203
- inputSchema: input22,
6659
+ inputSchema: input23,
6204
6660
  key: "bounceWatch",
6205
6661
  cost: (values, price) => {
6206
6662
  const campaigns = price.campaigns(values.max_campaigns);
@@ -6307,10 +6763,15 @@ var bounceWatch = defineInsight({
6307
6763
  });
6308
6764
 
6309
6765
  // src/insights/senders/domain-health.ts
6310
- import { z as z26 } from "zod";
6311
- var input23 = z26.object({
6312
- max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
6313
- max_spam_rate: z26.number().min(0).max(1).default(0.1).describe(
6766
+ import { z as z27 } from "zod";
6767
+ var CHECKED_ONE_BY_ONE = 50;
6768
+ var inPages = (capabilities) => capabilities["senders.healthList"];
6769
+ var sendersToCheck = (capabilities, max) => max ?? (inPages(capabilities) ? SCREENED_AT_MOST : CHECKED_ONE_BY_ONE);
6770
+ var input24 = z27.object({
6771
+ max_senders: z27.number().int().min(1).max(500).optional().describe(
6772
+ `The most senders to check. Leave out for ${SCREENED_AT_MOST} where the vendor reads health a page at a time (a few requests per 100 senders), or ${CHECKED_ONE_BY_ONE} where each sender costs 1 to 3 requests.`
6773
+ ),
6774
+ max_spam_rate: z27.number().min(0).max(1).default(0.1).describe(
6314
6775
  "A domain whose warmup emails land in spam more often than this share is high risk"
6315
6776
  )
6316
6777
  });
@@ -6405,20 +6866,24 @@ var seatRank = (seat) => {
6405
6866
  return seat.connected === null ? 1 : 2;
6406
6867
  };
6407
6868
  var domainHealth = defineInsight({
6408
- description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Costs one listing of senders plus 1 request per sender. A null count or rate means the vendor does not report it; a domain with no DNS record reported has the risk `unknown`, not `low`.",
6409
- inputSchema: input23,
6869
+ description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Every sender is checked where the vendor reads health a page at a time (Instantly: about 3 requests per 100 senders); otherwise up to 50 by default, at 1 to 3 requests each. A null count or rate means the vendor does not report it; a domain with no DNS record reported has the risk `unknown`, not `low`.",
6870
+ inputSchema: input24,
6410
6871
  key: "domainHealth",
6411
- cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
6872
+ cost: (values, price) => {
6873
+ const max = sendersToCheck(price.capabilities, values.max_senders);
6874
+ return price.list("senders.list", max) + (inPages(price.capabilities) ? price.list("senders.healthList", max) : price.upTo(max) * price.one("senders.health"));
6875
+ },
6412
6876
  scales: "max_senders",
6413
6877
  name: "domain_health",
6414
6878
  needs: ["senders.list", "senders.health"],
6415
6879
  next: "Use warmup_readiness to see which mailboxes of a risky domain are not ready, or bounce_watch to see whether bounces already rose.",
6416
6880
  run: async (context, { max_senders: maxSenders, max_spam_rate: threshold }) => {
6417
- const { items: senders2 } = await readSenders(context, maxSenders);
6881
+ const max = sendersToCheck(context.outbound.capabilities, maxSenders);
6882
+ const { items: senders2 } = await readSenders(context, max);
6418
6883
  const byDomain = /* @__PURE__ */ new Map();
6419
6884
  const linkedinSeats = [];
6420
6885
  const mailboxesWithoutDomain = [];
6421
- const read = await mapConcurrent(senders2, async (sender) => ({
6886
+ const read = inPages(context.outbound.capabilities) ? await readHealthInPages(context, senders2, max) : await mapConcurrent(senders2, async (sender) => ({
6422
6887
  health: await readHealth(context, sender),
6423
6888
  sender
6424
6889
  }));
@@ -6468,7 +6933,7 @@ var domainHealth = defineInsight({
6468
6933
  });
6469
6934
 
6470
6935
  // src/insights/senders/sender-capacity.ts
6471
- import { z as z27 } from "zod";
6936
+ import { z as z28 } from "zod";
6472
6937
 
6473
6938
  // src/insights/senders/capacity-sends.ts
6474
6939
  var dailyRows = async (context, campaigns, range) => {
@@ -6568,15 +7033,15 @@ var readSends = async (context, campaigns, days, senders2, split) => {
6568
7033
  };
6569
7034
 
6570
7035
  // src/insights/senders/sender-capacity.ts
6571
- var input24 = z27.object({
6572
- days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
6573
- max_campaigns: z27.number().int().min(1).max(200).default(50).describe(
7036
+ var input25 = z28.object({
7037
+ days: z28.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
7038
+ max_campaigns: z28.number().int().min(1).max(200).default(50).describe(
6574
7039
  "The most active campaigns to read. Each costs one read of its settings and one listing of its senders, plus 1 request when the vendor has no workspace totals."
6575
7040
  ),
6576
- max_senders: z27.number().int().min(1).max(1e3).default(1e3).describe(
7041
+ max_senders: z28.number().int().min(1).max(1e3).default(1e3).describe(
6577
7042
  "The most senders to read for the workspace, and for each campaign. A listing costs 1 request per 100 senders, and on Instantly a campaign's listing costs 2 per 100 mailboxes in the workspace."
6578
7043
  ),
6579
- split_uncounted: z27.boolean().default(false).describe(
7044
+ split_uncounted: z28.boolean().default(false).describe(
6580
7045
  "Read the stats of each inactive or unlimited sender (1 request each) so utilization can leave their sends out. Off, utilization is null whenever such a sender exists."
6581
7046
  )
6582
7047
  });
@@ -6642,7 +7107,7 @@ var askOf = (reads) => {
6642
7107
  withoutLimit: reads.length - withLimit
6643
7108
  };
6644
7109
  };
6645
- var findingOf3 = (capacity, ask, sends) => {
7110
+ var findingOf4 = (capacity, ask, sends) => {
6646
7111
  if (capacity.daily === null) {
6647
7112
  return "No active sender reports a daily limit, so capacity is unknown.";
6648
7113
  }
@@ -6664,7 +7129,7 @@ var findingOf3 = (capacity, ask, sends) => {
6664
7129
  };
6665
7130
  var senderCapacity = defineInsight({
6666
7131
  description: "Whether the senders can send what the campaigns ask: total daily capacity (the daily limits of active senders added up), the total daily ask of active campaigns, the average messages sent per day over the last days, utilization, and the campaigns whose own senders cannot cover their daily limit. Use it before adding campaigns or when sends fall short. Costs one listing of senders and of active campaigns, then up to 2 requests per campaign and 1 for daily stats, plus 1 per inactive or unlimited sender with split_uncounted. Utilization counts only the sends of the senders in capacity. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
6667
- inputSchema: input24,
7132
+ inputSchema: input25,
6668
7133
  key: "senderCapacity",
6669
7134
  cost: (values, price) => {
6670
7135
  const { capabilities } = price;
@@ -6712,7 +7177,7 @@ var senderCapacity = defineInsight({
6712
7177
  ask,
6713
7178
  askRatio: rate(ask?.daily ?? null, capacity.daily),
6714
7179
  capacity,
6715
- finding: findingOf3(capacity, ask, sends),
7180
+ finding: findingOf4(capacity, ask, sends),
6716
7181
  sends,
6717
7182
  shortCampaigns: canCompare ? shortfalls.flatMap(
6718
7183
  (each) => each === null || each === "unchecked" ? [] : [each]
@@ -6728,13 +7193,13 @@ var senderCapacity = defineInsight({
6728
7193
  });
6729
7194
 
6730
7195
  // src/insights/senders/sender-load.ts
6731
- import { z as z28 } from "zod";
6732
- var input25 = z28.object({
6733
- max_campaigns: z28.number().int().min(1).max(200).default(50).describe(
7196
+ import { z as z29 } from "zod";
7197
+ var input26 = z29.object({
7198
+ max_campaigns: z29.number().int().min(1).max(200).default(50).describe(
6734
7199
  "The most campaigns to read. Each costs one listing of its senders."
6735
7200
  ),
6736
- max_campaigns_per_sender: z28.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
6737
- max_senders: z28.number().int().min(1).max(1e3).default(1e3).describe(
7201
+ max_campaigns_per_sender: z29.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
7202
+ max_senders: z29.number().int().min(1).max(1e3).default(1e3).describe(
6738
7203
  "The most senders to read for the workspace, and for each campaign. A listing costs 1 request per 100 senders, and on Instantly a campaign's listing costs 2 per 100 mailboxes in the workspace."
6739
7204
  ),
6740
7205
  statuses: statusesInput(["active"])
@@ -6768,7 +7233,7 @@ var riskOf = (campaign, senders2) => {
6768
7233
  };
6769
7234
  var senderLoad = defineInsight({
6770
7235
  description: "Senders that are overused or unused: the senders attached to more campaigns than allowed, the active senders attached to no campaign, and the campaigns that run on a single sender, on none, or on a sender that is not active. Use it when sends are uneven or before adding a campaign. Costs one listing of senders and of campaigns, then one listing of each campaign's senders. Only campaigns in the given statuses are counted, so a sender used only by a paused campaign shows as unused unless paused is included.",
6771
- inputSchema: input25,
7236
+ inputSchema: input26,
6772
7237
  key: "senderLoad",
6773
7238
  cost: (values, price) => price.list("senders.list", values.max_senders) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.campaignSenders(values.max_senders),
6774
7239
  scales: "max_campaigns",
@@ -6848,18 +7313,18 @@ var senderLoad = defineInsight({
6848
7313
  });
6849
7314
 
6850
7315
  // src/insights/senders/settings-audit.ts
6851
- import { z as z29 } from "zod";
6852
- var input26 = z29.object({
6853
- max_campaigns: z29.number().int().min(1).max(200).default(25).describe(
7316
+ import { z as z30 } from "zod";
7317
+ var input27 = z30.object({
7318
+ max_campaigns: z30.number().int().min(1).max(200).default(25).describe(
6854
7319
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
6855
7320
  ),
6856
- max_daily_limit_per_sender: z29.number().min(1).default(50).describe(
7321
+ max_daily_limit_per_sender: z30.number().min(1).default(50).describe(
6857
7322
  "The sends a day assumed for an attached sender when the senders' own daily limits are not reported"
6858
7323
  ),
6859
- max_senders_per_campaign: z29.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
6860
- max_window_hours: z29.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
6861
- min_gap_minutes: z29.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
6862
- min_window_hours: z29.number().min(0).max(24).default(2).describe("A sending window shorter than this many hours is flagged"),
7324
+ max_senders_per_campaign: z30.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
7325
+ max_window_hours: z30.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
7326
+ min_gap_minutes: z30.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
7327
+ min_window_hours: z30.number().min(0).max(24).default(2).describe("A sending window shorter than this many hours is flagged"),
6863
7328
  statuses: statusesInput(["active"])
6864
7329
  });
6865
7330
  var SEVERITY2 = {
@@ -6999,7 +7464,7 @@ var countChecks = (campaigns) => countEach(
6999
7464
  );
7000
7465
  var settingsAudit = defineInsight({
7001
7466
  description: "Risky campaign settings, per campaign and by severity: no sending window, a window that includes the weekend or is too long or too short, no timezone, open or click tracking on, a reply that does not stop the sequence, no daily limit, sends too close together, an end date in the past on an active campaign, and a daily limit too high for the number of senders. Returns the findings per campaign, worst first, and a count per check. Use it before launching a campaign or when deliverability drops. Costs one listing of campaigns, then 1 request per campaign, or 2 when its senders can be listed. A setting the vendor reports nothing for is skipped, except a missing window, timezone or daily limit, which the vendor cannot tell apart from one that is not set.",
7002
- inputSchema: input26,
7467
+ inputSchema: input27,
7003
7468
  key: "settingsAudit",
7004
7469
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("campaigns.settings") + (price.capabilities["senders.byCampaign"] === false ? 0 : price.campaignSenders(values.max_senders_per_campaign))),
7005
7470
  scales: "max_campaigns",
@@ -7065,18 +7530,18 @@ var settingsAudit = defineInsight({
7065
7530
  });
7066
7531
 
7067
7532
  // src/insights/senders/warmup-readiness.ts
7068
- import { z as z30 } from "zod";
7069
- var input27 = z30.object({
7070
- check_health: z30.boolean().default(false).describe(
7533
+ import { z as z31 } from "zod";
7534
+ var input28 = z31.object({
7535
+ check_health: z31.boolean().default(false).describe(
7071
7536
  "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
7072
7537
  ),
7073
- max_senders: z30.number().int().min(1).max(1e3).default(1e3).describe(
7538
+ max_senders: z31.number().int().min(1).max(1e3).default(1e3).describe(
7074
7539
  "The most senders to check. The listing costs 1 request per 100 senders."
7075
7540
  ),
7076
- max_spam_rate: z30.number().min(0).max(1).default(0.1).describe(
7541
+ max_spam_rate: z31.number().min(0).max(1).default(0.1).describe(
7077
7542
  "With check_health, a mailbox whose warmup emails land in spam more often than this share is not ready"
7078
7543
  ),
7079
- min_score: z30.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
7544
+ min_score: z31.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
7080
7545
  });
7081
7546
  var READINESS_REASONS = [
7082
7547
  "not_active",
@@ -7143,7 +7608,7 @@ var countReasons = (judged) => countEach(
7143
7608
  );
7144
7609
  var warmupReadiness = defineInsight({
7145
7610
  description: "Which senders are not ready to send, each with its reasons: warmup off, warmup score under the bar or not reported, status not active, no daily limit and, with check_health, failing DNS records or too many warmup emails in spam. Returns counts by reason and how many are ready. A LinkedIn seat is judged on its status only. Use it before attaching mailboxes to a campaign or raising their limits. Costs one listing of senders, plus 1 request per mailbox with check_health. A null score means the vendor does not report one, which counts as not ready, not as 0.",
7146
- inputSchema: input27,
7611
+ inputSchema: input28,
7147
7612
  key: "warmupReadiness",
7148
7613
  cost: (values, price) => price.list("senders.list", values.max_senders) + (values.check_health && price.capabilities["senders.health"] !== false ? price.upTo(values.max_senders) * price.one("senders.health") : 0),
7149
7614
  scales: "max_senders",
@@ -7224,8 +7689,8 @@ var toTool = (outbound, definition, next, options) => ({
7224
7689
  const set = callOptions?.maxRequests ?? options.maxRequestsPerToolCall;
7225
7690
  const capSetting = options.capSetting ?? "maxRequestsPerToolCall";
7226
7691
  try {
7227
- const input28 = jsonInput(given);
7228
- if (input28 === void 0) {
7692
+ const input29 = jsonInput(given);
7693
+ if (input29 === void 0) {
7229
7694
  throw new OutboundError(
7230
7695
  "Invalid",
7231
7696
  `${definition.name}: the input is not JSON`
@@ -7233,13 +7698,14 @@ var toTool = (outbound, definition, next, options) => ({
7233
7698
  }
7234
7699
  const result = await definition.execute(
7235
7700
  outbound,
7236
- input28,
7701
+ input29,
7237
7702
  set === void 0 ? { capCeiling: INSIGHT_TOOL_CEILING, capSetting } : { capSetting, maxRequests: set }
7238
7703
  );
7239
7704
  return {
7240
7705
  data: result.data,
7241
7706
  meta: {
7242
7707
  complete: result.meta.complete,
7708
+ computedAt: result.meta.computedAt,
7243
7709
  evidence: result.meta.evidence,
7244
7710
  notes: [...result.meta.notes],
7245
7711
  provider: result.meta.provider,
@@ -7269,7 +7735,7 @@ var toTool = (outbound, definition, next, options) => ({
7269
7735
  name: definition.name,
7270
7736
  needs: [...definition.needs],
7271
7737
  // SAFETY: a JSON Schema document is JSON by definition.
7272
- parameters: z31.toJSONSchema(definition.inputSchema, { io: "input" })
7738
+ parameters: z32.toJSONSchema(definition.inputSchema, { io: "input" })
7273
7739
  });
7274
7740
  var insightLeftOutReason = (outbound, name) => {
7275
7741
  const definition = ENTRIES.find((entry) => entry.name === name);