outbound-sdk 0.11.0 → 0.13.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 (105) hide show
  1. package/dist/alerts/index.js +1 -1
  2. package/dist/budget/index.js +1 -1
  3. package/dist/cards/index.js +217 -100
  4. package/dist/cards/sender-tool-cards.d.ts +6 -0
  5. package/dist/chunks/{chunk-UAHYPASH.js → chunk-3LRIWQEJ.js} +2 -1
  6. package/dist/chunks/{chunk-UZLFZZ2U.js → chunk-6BSFR5SF.js} +14 -2
  7. package/dist/chunks/{chunk-FTK4JS65.js → chunk-BTIJ24UY.js} +89 -9
  8. package/dist/chunks/{chunk-OVTYA3IB.js → chunk-EAG5NIPM.js} +614 -206
  9. package/dist/chunks/{chunk-A7DLJUA6.js → chunk-FT6HMMMP.js} +3 -1
  10. package/dist/chunks/chunk-I7GBBHD2.js +80 -0
  11. package/dist/chunks/{chunk-UOJG4VYF.js → chunk-LD5OAELW.js} +1 -1
  12. package/dist/chunks/{chunk-KMQHXFIZ.js → chunk-LJNU4LAR.js} +2094 -1014
  13. package/dist/chunks/{chunk-POBAY3TI.js → chunk-NLYGMVXS.js} +30 -0
  14. package/dist/chunks/{chunk-V7JKTNRO.js → chunk-OE45PREW.js} +1 -1
  15. package/dist/chunks/{chunk-MEEJIIIA.js → chunk-OP2GL7ZT.js} +77 -8
  16. package/dist/chunks/{chunk-YFJ3OQZS.js → chunk-OPLXELPS.js} +5 -1
  17. package/dist/chunks/{chunk-CVLGFVDC.js → chunk-PDYE6CWS.js} +136 -64
  18. package/dist/chunks/{chunk-OMCDMELK.js → chunk-PUIHJFK4.js} +1 -1
  19. package/dist/chunks/{chunk-MPE6VLLY.js → chunk-UZ4YWUZ7.js} +1 -1
  20. package/dist/chunks/{tools-AVJ3XJ5A.js → tools-VCCH3JNL.js} +13 -6
  21. package/dist/cli/bin.js +11 -10
  22. package/dist/cli/config.d.ts +0 -2
  23. package/dist/cli/index.js +10 -9
  24. package/dist/cli/offered.d.ts +31 -2
  25. package/dist/cli/serve.d.ts +4 -2
  26. package/dist/combine/index.js +60 -4
  27. package/dist/emailbison/index.js +4 -4
  28. package/dist/fixtures/index.js +4 -4
  29. package/dist/heyreach/index.js +17 -6
  30. package/dist/identity/index.js +46 -11
  31. package/dist/identity/keys.d.ts +1 -1
  32. package/dist/index.js +8 -6
  33. package/dist/insights/capped.d.ts +14 -1
  34. package/dist/insights/define.d.ts +8 -6
  35. package/dist/insights/index.d.ts +1 -1
  36. package/dist/insights/index.js +12 -61
  37. package/dist/insights/inputs.generated.d.ts +91 -16
  38. package/dist/insights/ops/campaign-ranking.d.ts +8 -1
  39. package/dist/insights/ops/channel-mix.d.ts +8 -1
  40. package/dist/insights/ops/client-report.d.ts +28 -18
  41. package/dist/insights/ops/client-runway.d.ts +43 -0
  42. package/dist/insights/ops/index.d.ts +6 -1
  43. package/dist/insights/ops/period-comparison.d.ts +35 -2
  44. package/dist/insights/ops/pipeline-forecast.d.ts +14 -9
  45. package/dist/insights/ops/shared.d.ts +49 -2
  46. package/dist/insights/ops/tag-rollup.d.ts +8 -1
  47. package/dist/insights/people/coverage.d.ts +26 -0
  48. package/dist/insights/people/dropped-replies-check.d.ts +19 -3
  49. package/dist/insights/people/dropped-replies.d.ts +6 -2
  50. package/dist/insights/people/find.d.ts +5 -4
  51. package/dist/insights/people/hot-leads.d.ts +10 -1
  52. package/dist/insights/people/index.d.ts +26 -2
  53. package/dist/insights/people/lead-collisions.d.ts +18 -1
  54. package/dist/insights/people/person-summary.d.ts +15 -3
  55. package/dist/insights/people/suppression-check.d.ts +18 -1
  56. package/dist/insights/people/thread-context.d.ts +79 -0
  57. package/dist/insights/people/thread-contexts.d.ts +59 -0
  58. package/dist/insights/people/thread-read.d.ts +33 -0
  59. package/dist/insights/registry.d.ts +29 -3
  60. package/dist/insights/senders/domain-health.d.ts +1 -1
  61. package/dist/insights/senders/index.d.ts +1 -1
  62. package/dist/insights/senders/read.d.ts +9 -0
  63. package/dist/insights/tools.d.ts +35 -2
  64. package/dist/instantly/adapter.d.ts +3 -2
  65. package/dist/instantly/capabilities.d.ts +5 -0
  66. package/dist/instantly/index.js +255 -66
  67. package/dist/instantly/lead-ids.d.ts +11 -0
  68. package/dist/instantly/map-lead.d.ts +19 -2
  69. package/dist/instantly/senders.d.ts +3 -0
  70. package/dist/internal/adapter.d.ts +7 -0
  71. package/dist/internal/capabilities.d.ts +8 -0
  72. package/dist/internal/entities.d.ts +24 -1
  73. package/dist/internal/fields.d.ts +10 -0
  74. package/dist/internal/outbound/api.d.ts +12 -0
  75. package/dist/internal/outbound/operations-account.d.ts +4 -1
  76. package/dist/internal/outbound/outbound.d.ts +2 -1
  77. package/dist/internal/outbound/specs-account.d.ts +2 -1
  78. package/dist/internal/person.d.ts +32 -0
  79. package/dist/internal/records.d.ts +2 -2
  80. package/dist/internal/reply-people.d.ts +25 -7
  81. package/dist/internal/runway.d.ts +38 -5
  82. package/dist/internal/url.d.ts +2 -1
  83. package/dist/loader/index.js +1 -1
  84. package/dist/memory/data.d.ts +2 -1
  85. package/dist/memory/index.js +6 -4
  86. package/dist/redact/index.d.ts +1 -1
  87. package/dist/redact/index.js +62 -31
  88. package/dist/redact/plugin.d.ts +13 -11
  89. package/dist/redact/tokens.d.ts +18 -1
  90. package/dist/smartlead/index.js +21 -7
  91. package/dist/tools/account-tools.d.ts +0 -5
  92. package/dist/tools/ai-sdk.js +5 -3
  93. package/dist/tools/campaign-tools.d.ts +0 -4
  94. package/dist/tools/claude-agent.js +5 -3
  95. package/dist/tools/deliverability-check.d.ts +9 -0
  96. package/dist/tools/index.js +6 -4
  97. package/dist/tools/people-tools.d.ts +4 -1
  98. package/dist/tools/person-input.d.ts +17 -0
  99. package/dist/tools/registry.d.ts +8 -1
  100. package/dist/tools/sender-health.d.ts +8 -0
  101. package/dist/tools/sender-impact.d.ts +38 -0
  102. package/dist/tools/shared.d.ts +5 -0
  103. package/dist/webhooks/index.js +6 -6
  104. package/package.json +1 -1
  105. /package/dist/chunks/{chunk-5XLR6XVV.js → chunk-HNYJO6B4.js} +0 -0
@@ -1,23 +1,33 @@
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
- runwayDays,
14
+ runwayOf,
15
+ runwayStatus,
12
16
  splitActive,
17
+ untrusted,
13
18
  warmupAtZero,
14
19
  withCampaign
15
- } from "./chunk-FTK4JS65.js";
20
+ } from "./chunk-BTIJ24UY.js";
16
21
  import {
17
22
  count,
18
23
  percentOf,
19
24
  plural
20
25
  } from "./chunk-4PA526S7.js";
26
+ import {
27
+ assertRefReadable,
28
+ leadRefParts,
29
+ parsePerson
30
+ } from "./chunk-I7GBBHD2.js";
21
31
  import {
22
32
  mapConcurrent
23
33
  } from "./chunk-HZCTYL22.js";
@@ -36,7 +46,7 @@ import {
36
46
  } from "./chunk-FALWG5U3.js";
37
47
  import {
38
48
  leadStatusSchema
39
- } from "./chunk-POBAY3TI.js";
49
+ } from "./chunk-NLYGMVXS.js";
40
50
  import {
41
51
  CONTACTED_LEADS_LIMIT,
42
52
  contactedBeyondLeads,
@@ -46,25 +56,27 @@ import {
46
56
  campaignStatusSchema,
47
57
  replyCategorySchema
48
58
  } from "./chunk-QGRZDTX4.js";
59
+ import {
60
+ profileSlug
61
+ } from "./chunk-OPLXELPS.js";
49
62
  import {
50
63
  makeRef,
51
64
  parseRef
52
65
  } from "./chunk-HXB2IOJJ.js";
53
- import {
54
- profileSlug
55
- } from "./chunk-YFJ3OQZS.js";
56
66
  import {
57
67
  OutboundError
58
68
  } from "./chunk-XYHM4KHC.js";
59
69
  import {
60
70
  emailAddress,
71
+ isJsonObject,
72
+ isString,
61
73
  jsonInput,
62
74
  toJson,
63
75
  unknownKey
64
76
  } from "./chunk-45TXPJW7.js";
65
77
 
66
78
  // src/insights/tools.ts
67
- import { z as z31 } from "zod";
79
+ import { z as z33 } from "zod";
68
80
 
69
81
  // src/insights/cost.ts
70
82
  var UNKNOWN = /* @__PURE__ */ Symbol("unknown cost");
@@ -119,15 +131,15 @@ var pricer = (outbound, costs, most, found) => {
119
131
  }
120
132
  };
121
133
  };
122
- var boundsOf = (outbound, cost, input28, found) => {
134
+ var boundsOf = (outbound, cost, input29, found) => {
123
135
  const costs = cappedAccess(outbound)?.costs;
124
136
  if (cost === void 0 || costs === void 0) {
125
137
  return null;
126
138
  }
127
139
  try {
128
140
  return {
129
- max: cost(input28, pricer(outbound, costs, true, found)),
130
- min: cost(input28, pricer(outbound, costs, false, found))
141
+ max: cost(input29, pricer(outbound, costs, true, found)),
142
+ min: cost(input29, pricer(outbound, costs, false, found))
131
143
  };
132
144
  } catch (error) {
133
145
  if (error === UNKNOWN) {
@@ -169,8 +181,8 @@ var stopped = (name, stop, provider) => capError(
169
181
  stop,
170
182
  provider
171
183
  );
172
- var fitting = (outbound, cost, input28, name, room, found) => {
173
- const fields = input28;
184
+ var fitting = (outbound, cost, input29, name, room, found) => {
185
+ const fields = input29;
174
186
  const current = fields[name];
175
187
  if (typeof current !== "number" || current <= 1) {
176
188
  return void 0;
@@ -221,12 +233,12 @@ var capFor = (outbound, name, max, options) => {
221
233
  };
222
234
  var hasRunBudget = (outbound) => "requestBudget" in outbound;
223
235
  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);
236
+ var runCap = (outbound, spec, input29, options) => {
237
+ const bounds = boundsOf(outbound, spec.cost, input29);
226
238
  const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
227
239
  const stop = (room, found) => ({
228
240
  ...effect,
229
- lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input28, spec.scales, room, found),
241
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input29, spec.scales, room, found),
230
242
  requests: counter.used()
231
243
  });
232
244
  const outgrown = () => ({
@@ -240,7 +252,7 @@ var runCap = (outbound, spec, input28, options) => {
240
252
  );
241
253
  const check2 = (found) => {
242
254
  const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
243
- const least = boundsOf(outbound, spec.cost, input28, found);
255
+ const least = boundsOf(outbound, spec.cost, input29, found);
244
256
  if (least !== null && least.min > room) {
245
257
  throw refusal(
246
258
  spec.name,
@@ -440,29 +452,30 @@ var track = (cap, now, partialOnCap) => {
440
452
  return stats.rows;
441
453
  }
442
454
  },
443
- // A read the cap stopped part way recorded no cost, so the cap's own count is the total.
455
+ // A read that failed, or that a cap stopped part way, recorded no cost,
456
+ // so the run's own count of what it sent is the total.
444
457
  meta: () => ({
445
458
  complete,
446
459
  evidence,
447
460
  notes: [...notes],
448
- requests: absorbed ? Math.max(requests, cap.used()) : requests
461
+ requests: Math.max(requests, cap.used())
449
462
  })
450
463
  };
451
464
  };
452
465
  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);
466
+ var prepare = (outbound, spec, input29) => {
467
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input29);
455
468
  if (stray !== void 0) {
456
469
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
457
470
  provider: outbound.provider
458
471
  });
459
472
  }
460
- const parsed = spec.inputSchema.safeParse(input28 ?? {});
473
+ const parsed = spec.inputSchema.safeParse(input29 ?? {});
461
474
  if (!parsed.success) {
462
475
  const [issue] = parsed.error.issues;
463
476
  throw new OutboundError(
464
477
  "Invalid",
465
- `${spec.name}: ${inputProblem(input28, issue)}`,
478
+ `${spec.name}: ${inputProblem(input29, issue)}`,
466
479
  { provider: outbound.provider }
467
480
  );
468
481
  }
@@ -476,7 +489,7 @@ var prepare = (outbound, spec, input28) => {
476
489
  }
477
490
  return parsed.data;
478
491
  };
479
- var refuseUnsupported = (outbound, spec, input28) => {
492
+ var refuseUnsupported = (outbound, spec, input29) => {
480
493
  const lacked = spec.lacks?.(outbound) ?? null;
481
494
  if (lacked !== null) {
482
495
  throw new OutboundError(
@@ -486,7 +499,7 @@ var refuseUnsupported = (outbound, spec, input28) => {
486
499
  );
487
500
  }
488
501
  const absent = missing(outbound, spec.needs);
489
- const forInput = missing(outbound, spec.needsFor?.(input28) ?? []);
502
+ const forInput = missing(outbound, spec.needsFor?.(input29) ?? []);
490
503
  if (absent.length > 0 || forInput.length > 0) {
491
504
  throw new OutboundError(
492
505
  "Unsupported",
@@ -496,14 +509,14 @@ var refuseUnsupported = (outbound, spec, input28) => {
496
509
  }
497
510
  };
498
511
  var COMBINED = "combined";
499
- var someMemberServes = async (outbound, spec, input28) => {
512
+ var someMemberServes = async (outbound, spec, input29) => {
500
513
  const { items } = await outbound.workspaces.list();
501
514
  return items.some((tool) => {
502
515
  try {
503
516
  refuseUnsupported(
504
517
  outbound.workspace(`${tool.provider}:${tool.workspaceId}`),
505
518
  spec,
506
- input28
519
+ input29
507
520
  );
508
521
  return true;
509
522
  } catch (error) {
@@ -515,23 +528,23 @@ var someMemberServes = async (outbound, spec, input28) => {
515
528
  });
516
529
  };
517
530
  var NAMED_AMONG = 1e3;
518
- var priced = (outbound, spec, input28) => {
531
+ var priced = (outbound, spec, input29) => {
519
532
  const { cost } = spec;
520
- return cost === void 0 || !namesCampaign(outbound, input28) ? spec : {
533
+ return cost === void 0 || !namesCampaign(outbound, input29) ? spec : {
521
534
  ...spec,
522
535
  cost: (values, price) => cost(values, price) + price.list("campaigns.list", NAMED_AMONG)
523
536
  };
524
537
  };
525
- var execute = async (outbound, spec, input28, options = {}) => {
526
- const target = routedByCampaign(outbound, input28);
527
- const checked = prepare(target, spec, input28);
538
+ var execute = async (outbound, spec, input29, options = {}) => {
539
+ const target = routedByCampaign(outbound, input29);
540
+ const checked = prepare(target, spec, input29);
528
541
  const later = namesCampaign(target, checked) && target.provider === COMBINED;
529
542
  if (!later || !await someMemberServes(target, spec, checked)) {
530
543
  refuseUnsupported(target, spec, checked);
531
544
  }
532
545
  const cap = runCap(target, priced(target, spec, checked), checked, options);
533
546
  const now = options.now ?? Date.now();
534
- const tracker = track(cap, now, spec.partialOnCap === true);
547
+ const tracker = track(cap, now, spec.partialOnCap !== false);
535
548
  const data = await withCampaign(
536
549
  tracker.context.outbound,
537
550
  checked,
@@ -559,114 +572,413 @@ var execute = async (outbound, spec, input28, options = {}) => {
559
572
  };
560
573
  var defineInsight = (spec) => ({
561
574
  ...spec,
562
- execute: async (outbound, input28, options) => {
563
- const result = await execute(outbound, spec, input28, options);
575
+ execute: async (outbound, input29, options) => {
576
+ const result = await execute(outbound, spec, input29, options);
564
577
  return { ...result, data: toJson(result.data) };
565
578
  }
566
579
  });
567
- var runInsight = (outbound, definition, input28, options = {}) => (
580
+ var runInsight = (outbound, definition, input29, options = {}) => (
568
581
  // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
569
- execute(outbound, definition, input28, options)
582
+ execute(outbound, definition, input29, options)
570
583
  );
571
584
 
585
+ // src/insights/plugin.ts
586
+ import { z as z32 } from "zod";
587
+
572
588
  // src/insights/copy/copy-audit.ts
573
589
  import { z as z4 } from "zod";
574
590
 
575
- // src/insights/people/read.ts
576
- import { z as z2 } from "zod";
577
-
578
- // src/insights/capped.ts
579
- var readCapped = async (context, open, cap, room = cap.max) => {
580
- if (room >= 1) {
581
- const walk = open(room);
582
- const items = await context.all(walk, cap);
583
- return { capped: walk.truncated || wasCutShort(items), items };
584
- }
585
- const probe = open(1);
586
- const left = await context.all(probe, cap);
587
- if (left.length > 0 && !probe.truncated) {
588
- context.partial(capNote(cap));
591
+ // src/insights/variables.ts
592
+ var PATTERNS = [
593
+ /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
594
+ /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
595
+ /%(?<name>[A-Za-z_][\w-]*)%/gu
596
+ ];
597
+ var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
598
+ var BUILTINS = /* @__PURE__ */ new Map([
599
+ ["company", (lead) => lead.company],
600
+ ["companyname", (lead) => lead.company],
601
+ ["email", (lead) => lead.email],
602
+ ["firstname", (lead) => lead.firstName],
603
+ ["jobtitle", (lead) => lead.title],
604
+ ["lastname", (lead) => lead.lastName],
605
+ ["title", (lead) => lead.title]
606
+ ]);
607
+ var isBuiltin = (key) => BUILTINS.has(key);
608
+ var SENDER = /* @__PURE__ */ new Map([
609
+ [
610
+ "instantly",
611
+ /* @__PURE__ */ new Set([
612
+ "accountsignature",
613
+ "sendingaccountemail",
614
+ "sendingaccountfirstname",
615
+ "sendingaccountname"
616
+ ])
617
+ ]
618
+ ]);
619
+ var isSender = (provider, key) => SENDER.get(provider)?.has(key) ?? false;
620
+ var variablesIn = (text) => PATTERNS.flatMap(
621
+ (pattern) => [...text.matchAll(pattern)].map((match) => {
622
+ const fallback = match.groups?.fallback;
623
+ return {
624
+ fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
625
+ index: match.index,
626
+ name: match.groups?.name ?? "",
627
+ raw: match[0]
628
+ };
629
+ })
630
+ );
631
+ var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
632
+ var valueOf = (lead, key) => {
633
+ const builtin = BUILTINS.get(key)?.(lead);
634
+ if (filled(builtin)) {
635
+ return builtin;
589
636
  }
590
- return { capped: left.length > 0, items: [] };
637
+ const custom = Object.entries(lead.custom).find(
638
+ ([name, value]) => keyOf(name) === key && filled(value)
639
+ );
640
+ return custom?.[1] ?? null;
591
641
  };
592
- var campaignsReadOf = (read) => ({
593
- campaignsRead: read.items.length,
594
- moreCampaignsExist: read.capped
595
- });
596
- var settledPage = async (read) => {
597
- try {
598
- return await read;
599
- } catch (error) {
600
- if (isCapStop(error)) {
601
- return null;
642
+ var keysWithValue = (lead) => /* @__PURE__ */ new Set([
643
+ ...[...BUILTINS].flatMap(
644
+ ([key, read]) => filled(read(lead)) ? [key] : []
645
+ ),
646
+ ...Object.entries(lead.custom).flatMap(
647
+ ([key, value]) => filled(value) ? [keyOf(key)] : []
648
+ )
649
+ ]);
650
+ var fillVariables = (text, lead) => {
651
+ const matches = variablesIn(text).toSorted(
652
+ (left, right) => left.index - right.index
653
+ );
654
+ const unfilled = [];
655
+ let out = "";
656
+ let at = 0;
657
+ for (const match of matches) {
658
+ if (match.index >= at) {
659
+ const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
660
+ if (value === null && !unfilled.includes(match.name)) {
661
+ unfilled.push(match.name);
662
+ }
663
+ out += text.slice(at, match.index) + (value ?? match.raw);
664
+ at = match.index + match.raw.length;
602
665
  }
603
- throw error;
604
666
  }
667
+ return { text: out + text.slice(at), unfilled };
605
668
  };
606
- var either = (words) => words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
607
- var othersCounted = (others, more) => {
608
- if (others.length === 0) {
609
- return void 0;
610
- }
611
- const counts = /* @__PURE__ */ new Map();
612
- for (const campaign of others) {
613
- counts.set(campaign.status, (counts.get(campaign.status) ?? 0) + 1);
614
- }
615
- const byStatus = [...counts].toSorted(([a], [b]) => a.localeCompare(b)).map(([status, count2]) => `${count2} ${status}`).join(", ");
616
- return `${more ? "the first " : ""}${others.length} campaign${others.length === 1 ? "" : "s"}: ${byStatus}`;
669
+
670
+ // src/insights/step.ts
671
+ var stepAt = (index) => ({
672
+ step: index,
673
+ stepIndex: index,
674
+ stepNumber: index + 1
675
+ });
676
+ var stepLabel = (index, of = null) => of === null || of < index + 1 ? `step ${index + 1}` : `step ${index + 1} (of ${of})`;
677
+
678
+ // src/insights/copy/copy-checks.ts
679
+ var CHECKS = {
680
+ all_caps: "low",
681
+ body_too_long: "low",
682
+ connection_request_too_long: "high",
683
+ exclamation_marks: "low",
684
+ image: "medium",
685
+ malformed_variable: "high",
686
+ missing_subject: "high",
687
+ spam_words: "medium",
688
+ subject_breaks_thread: "medium",
689
+ subject_too_long: "low",
690
+ too_many_links: "medium"
617
691
  };
618
- var noneMatched = (context, wanted, others, more) => {
619
- const counted2 = othersCounted(others, more);
620
- if (counted2 !== void 0) {
621
- context.partial(
622
- `No campaign is ${either(wanted)}, so nothing was checked (${counted2}). Pass statuses to check the others.`
623
- );
624
- }
692
+ var DEFAULT_SPAM_WORDS = [
693
+ "100% free",
694
+ "act now",
695
+ "buy now",
696
+ "cash bonus",
697
+ "click here",
698
+ "double your",
699
+ "earn money",
700
+ "free trial",
701
+ "guarantee",
702
+ "limited time",
703
+ "no obligation",
704
+ "risk-free",
705
+ "urgent",
706
+ "winner"
707
+ ];
708
+ var TAG = /<[^>]+>/gu;
709
+ var IMAGE = /<img\b[^>]*>/giu;
710
+ var VARIABLE = /\{\{[^{}]*\}\}/gu;
711
+ var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
712
+ var ANCHOR = /<a\b(?<attributes>[^>]*)>[\s\S]*?<\/a\s*>/giu;
713
+ var HREF = /\bhref\s*=\s*["']?(?<target>[^"'\s>]+)/iu;
714
+ var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
715
+ var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
716
+ var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
717
+ var SNIPPET = 80;
718
+ var clip = (text) => text.length > SNIPPET ? `${text.slice(0, SNIPPET)}\u2026` : text;
719
+ var visible = (text) => text.replaceAll(TAG, " ").replaceAll(VARIABLE, " variable ");
720
+ var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== "");
721
+ var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
722
+ var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
723
+ check: "subject_too_long",
724
+ finding: `The subject is ${plural(subject.length, "character")}; the limit is ${limits.maxSubjectChars}.`,
725
+ text: clip(subject)
726
+ } : null;
727
+ var bodyTooLong = (body, limits) => {
728
+ const words = wordsOf(body);
729
+ return words.length > limits.maxBodyWords ? {
730
+ check: "body_too_long",
731
+ finding: `The body is ${plural(words.length, "word")}; the limit is ${limits.maxBodyWords}.`,
732
+ text: clip(words.slice(0, 12).join(" "))
733
+ } : null;
625
734
  };
626
- var countOthers = async (context, wanted, every) => {
627
- if (every !== void 0) {
628
- noneMatched(context, wanted, every, false);
629
- return;
630
- }
631
- const page = await settledPage(context.outbound.campaigns.list());
632
- if (page === null) {
633
- context.partial(
634
- `No campaign is ${either(wanted)}, so nothing was checked; a request cap stopped the count of the others.`
635
- );
636
- return;
637
- }
638
- noneMatched(context, wanted, context.page(page), page.cursor !== void 0);
735
+ var linksOf = (body) => {
736
+ const html = body.replaceAll(IMAGE, " ");
737
+ const anchored = [...html.matchAll(ANCHOR)].flatMap((anchor) => {
738
+ const target = HREF.exec(anchor.groups?.attributes ?? "")?.groups?.target;
739
+ return target === void 0 ? [] : [target];
740
+ });
741
+ return [...anchored, ...html.replaceAll(ANCHOR, " ").match(LINK) ?? []];
639
742
  };
640
- var toolNoneMatched = async (context, label, wanted, every) => {
641
- const none = `${label} has no campaign ${either(wanted)}, so it was not checked`;
642
- let counted2;
643
- if (every === void 0) {
644
- const page = await settledPage(context.outbound.campaigns.list());
645
- if (page === null) {
646
- return `${none}; a request cap stopped the count of its others.`;
647
- }
648
- counted2 = othersCounted(context.page(page), page.cursor !== void 0);
649
- } else {
650
- counted2 = othersCounted(every, false);
651
- }
652
- return counted2 === void 0 ? `${none}: it has no campaigns.` : `${none} (${counted2}). Pass statuses to check them.`;
743
+ var tooManyLinks = (body, limits) => {
744
+ const links = linksOf(body);
745
+ return links.length > limits.maxLinks ? {
746
+ check: "too_many_links",
747
+ finding: `The body has ${plural(links.length, "link")}; the limit is ${limits.maxLinks}.`,
748
+ text: clip(links.join(" "))
749
+ } : null;
653
750
  };
654
- var fairShares = (counts, max) => {
655
- const shares = counts.map(() => 0);
656
- let left = max;
657
- const order2 = counts.map((_, index) => index).toSorted((a, b) => (counts[a] ?? 0) - (counts[b] ?? 0));
658
- for (const [at, index] of order2.entries()) {
659
- const share2 = Math.min(
660
- counts[index] ?? 0,
661
- Math.floor(left / (order2.length - at))
662
- );
663
- shares[index] = share2;
664
- left -= share2;
665
- }
666
- return shares;
751
+ var spamWords = (text, limits) => {
752
+ const plain2 = visible(text);
753
+ const hits = limits.spamWords.filter(
754
+ (word) => word.trim() !== "" && new RegExp(
755
+ String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
756
+ "iu"
757
+ ).test(plain2)
758
+ );
759
+ return hits.length > 0 ? {
760
+ check: "spam_words",
761
+ finding: `The copy uses ${plural(hits.length, "word or phrase", "words or phrases")} that spam filters weigh.`,
762
+ text: hits.join(", ")
763
+ } : null;
667
764
  };
668
- var readOne = async (context, wanted, cap) => {
669
- const { campaigns } = context.outbound;
765
+ var malformedVariable = (text) => {
766
+ const empty = (text.match(VARIABLE) ?? []).filter(
767
+ (token) => token.slice(2, -2).trim() === ""
768
+ );
769
+ const rest = text.replaceAll(VARIABLE, "");
770
+ const stray = /\{\{|\}\}/u.exec(rest);
771
+ if (stray === null && empty.length === 0) {
772
+ return null;
773
+ }
774
+ return {
775
+ check: "malformed_variable",
776
+ finding: stray === null ? "A variable has no name between its braces, so it sends as blank or as raw braces." : "A variable's braces are not balanced, so it sends as raw text.",
777
+ text: stray === null ? empty[0] ?? "" : clip(
778
+ rest.slice(Math.max(0, stray.index - 20), stray.index + 30).trim()
779
+ )
780
+ };
781
+ };
782
+ var allCaps = (text, limits) => {
783
+ const words = text.replaceAll(TAG, " ").replaceAll(VARIABLE, " ").match(CAPS_WORD);
784
+ const found = words ?? [];
785
+ return found.length > limits.maxCapsWords ? {
786
+ check: "all_caps",
787
+ finding: `${plural(found.length, "word")} of four or more letters ${noun(found.length, "is", "are")} in capitals; the limit is ${limits.maxCapsWords}.`,
788
+ text: clip(found.join(" "))
789
+ } : null;
790
+ };
791
+ var exclamationMarks = (text, limits) => {
792
+ const marks = visible(text).split("!").length - 1;
793
+ return marks > limits.maxExclamations ? {
794
+ check: "exclamation_marks",
795
+ finding: `The copy has ${marks} exclamation marks; the limit is ${limits.maxExclamations}.`,
796
+ text: "!".repeat(marks)
797
+ } : null;
798
+ };
799
+ var image = (body) => {
800
+ const [first] = body.match(IMAGE) ?? [];
801
+ if (first === void 0) {
802
+ return null;
803
+ }
804
+ return {
805
+ check: "image",
806
+ finding: PIXEL.test(first) ? "The body holds a tracking pixel, which spam filters and privacy tools flag." : "The body holds an image, which cold email filters weigh against.",
807
+ text: clip(first)
808
+ };
809
+ };
810
+ var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
811
+ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
812
+ check: "connection_request_too_long",
813
+ finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
814
+ text: clip(body)
815
+ } : null;
816
+
817
+ // src/insights/copy/audit-variant.ts
818
+ var emailChecks = (step, variant, limits, thread) => {
819
+ const subject = variant.subject?.trim() ?? "";
820
+ const body = variant.body ?? "";
821
+ const key = threadKey(subject);
822
+ const problems = [
823
+ subject === "" ? null : subjectTooLong(subject, limits),
824
+ spamWords(`${subject}
825
+ ${body}`, limits),
826
+ tooManyLinks(body, limits),
827
+ image(body)
828
+ ];
829
+ if (step.index === thread.first && subject === "") {
830
+ problems.push({
831
+ check: "missing_subject",
832
+ finding: "The first email has no subject.",
833
+ text: ""
834
+ });
835
+ }
836
+ if (step.index !== thread.first && key !== "" && thread.subjects !== null && !thread.subjects.has(key)) {
837
+ problems.push({
838
+ check: "subject_breaks_thread",
839
+ finding: "This follow-up has a subject that differs from the first email's, so it starts a new thread instead of continuing the first.",
840
+ text: subject
841
+ });
842
+ }
843
+ return problems;
844
+ };
845
+ var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
846
+ var auditVariant = (step, variant, limits, thread, lead) => {
847
+ const body = variant.body ?? "";
848
+ const whole = `${variant.subject ?? ""}
849
+ ${body}`;
850
+ const problems = [
851
+ malformedVariable(whole),
852
+ bodyTooLong(body, limits),
853
+ allCaps(whole, limits),
854
+ exclamationMarks(whole, limits),
855
+ ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
856
+ ];
857
+ return problems.flatMap(
858
+ (problem) => problem === null ? [] : [
859
+ {
860
+ ...problem,
861
+ action: step.action,
862
+ lead,
863
+ severity: CHECKS[problem.check],
864
+ ...stepAt(step.index),
865
+ variantKey: variant.variantKey
866
+ }
867
+ ]
868
+ );
869
+ };
870
+ var threadOf = (steps, perLead2) => {
871
+ const [first] = steps.toSorted((left, right) => left.index - right.index);
872
+ const variants = first?.variants ?? [];
873
+ return {
874
+ first: first?.index ?? null,
875
+ subjects: first !== void 0 && variants.some((variant) => perLead2(variant)) ? null : new Set(
876
+ variants.flatMap((variant) => {
877
+ const key = threadKey(variant.subject);
878
+ return key === "" ? [] : [key];
879
+ })
880
+ )
881
+ };
882
+ };
883
+
884
+ // src/insights/copy/copy-preview.ts
885
+ import { z as z3 } from "zod";
886
+
887
+ // src/insights/people/read.ts
888
+ import { z as z2 } from "zod";
889
+
890
+ // src/insights/capped.ts
891
+ var readCapped = async (context, open, cap, room = cap.max) => {
892
+ if (room >= 1) {
893
+ const walk = open(room);
894
+ const items = await context.all(walk, cap);
895
+ return { capped: walk.truncated || wasCutShort(items), items };
896
+ }
897
+ const probe = open(1);
898
+ const left = await context.all(probe, cap);
899
+ if (left.length > 0 && !probe.truncated) {
900
+ context.partial(capNote(cap));
901
+ }
902
+ return { capped: left.length > 0, items: [] };
903
+ };
904
+ var campaignsReadOf = (read) => ({
905
+ campaignsRead: read.items.length,
906
+ moreCampaignsExist: read.capped
907
+ });
908
+ var settledPage = async (read) => {
909
+ try {
910
+ return await read;
911
+ } catch (error) {
912
+ if (isCapStop(error)) {
913
+ return null;
914
+ }
915
+ throw error;
916
+ }
917
+ };
918
+ var either = (words) => words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
919
+ var othersCounted = (others, more) => {
920
+ if (others.length === 0) {
921
+ return void 0;
922
+ }
923
+ const counts = /* @__PURE__ */ new Map();
924
+ for (const campaign of others) {
925
+ counts.set(campaign.status, (counts.get(campaign.status) ?? 0) + 1);
926
+ }
927
+ const byStatus = [...counts].toSorted(([a], [b]) => a.localeCompare(b)).map(([status, count2]) => `${count2} ${status}`).join(", ");
928
+ return `${more ? "the first " : ""}${others.length} campaign${others.length === 1 ? "" : "s"}: ${byStatus}`;
929
+ };
930
+ var noneMatched = (context, wanted, others, more) => {
931
+ const counted2 = othersCounted(others, more);
932
+ if (counted2 !== void 0) {
933
+ context.partial(
934
+ `No campaign is ${either(wanted)}, so nothing was checked (${counted2}). Pass statuses to check the others.`
935
+ );
936
+ }
937
+ };
938
+ var countOthers = async (context, wanted, every) => {
939
+ if (every !== void 0) {
940
+ noneMatched(context, wanted, every, false);
941
+ return;
942
+ }
943
+ const page = await settledPage(context.outbound.campaigns.list());
944
+ if (page === null) {
945
+ context.partial(
946
+ `No campaign is ${either(wanted)}, so nothing was checked; a request cap stopped the count of the others.`
947
+ );
948
+ return;
949
+ }
950
+ noneMatched(context, wanted, context.page(page), page.cursor !== void 0);
951
+ };
952
+ var toolNoneMatched = async (context, label, wanted, every) => {
953
+ const none = `${label} has no campaign ${either(wanted)}, so it was not checked`;
954
+ let counted2;
955
+ if (every === void 0) {
956
+ const page = await settledPage(context.outbound.campaigns.list());
957
+ if (page === null) {
958
+ return `${none}; a request cap stopped the count of its others.`;
959
+ }
960
+ counted2 = othersCounted(context.page(page), page.cursor !== void 0);
961
+ } else {
962
+ counted2 = othersCounted(every, false);
963
+ }
964
+ return counted2 === void 0 ? `${none}: it has no campaigns.` : `${none} (${counted2}). Pass statuses to check them.`;
965
+ };
966
+ var fairShares = (counts, max) => {
967
+ const shares = counts.map(() => 0);
968
+ let left = max;
969
+ const order2 = counts.map((_, index) => index).toSorted((a, b) => (counts[a] ?? 0) - (counts[b] ?? 0));
970
+ for (const [at, index] of order2.entries()) {
971
+ const share2 = Math.min(
972
+ counts[index] ?? 0,
973
+ Math.floor(left / (order2.length - at))
974
+ );
975
+ shares[index] = share2;
976
+ left -= share2;
977
+ }
978
+ return shares;
979
+ };
980
+ var readOne = async (context, wanted, cap) => {
981
+ const { campaigns } = context.outbound;
670
982
  if (context.outbound.capabilities["campaigns.status"] === false) {
671
983
  const every = await readCapped(
672
984
  context,
@@ -700,6 +1012,8 @@ var readShared = async (context, wanted, cap) => {
700
1012
  const label = `${tool.provider}:${tool.workspaceId}`;
701
1013
  return {
702
1014
  label,
1015
+ provider: tool.provider,
1016
+ workspaceId: tool.workspaceId,
703
1017
  read: await readOne(
704
1018
  { ...context, outbound: outbound.workspace(label) },
705
1019
  wanted,
@@ -739,20 +1053,35 @@ var readShared = async (context, wanted, cap) => {
739
1053
  `${cap.input ?? "The cap"} is shared among the tools: ${read.map((each, index) => `${each.label} ${shares[index] ?? 0}`).join(", ")}.`
740
1054
  );
741
1055
  }
1056
+ const skipped = read.flatMap(
1057
+ (each) => each.read.items.length === 0 && !each.read.capped ? [
1058
+ {
1059
+ provider: each.provider,
1060
+ reason: `It has no campaign ${either(wanted)}.`,
1061
+ tool: each.label,
1062
+ workspaceId: each.workspaceId
1063
+ }
1064
+ ] : []
1065
+ );
742
1066
  return {
743
1067
  capped: dropped || read.some((each) => each.read.capped),
744
- items
1068
+ items,
1069
+ skipped
745
1070
  };
746
1071
  };
747
- var readCampaignsIn = async (context, statuses, max, input28 = "max_campaigns") => {
1072
+ var readCampaignsIn = async (context, statuses, max, input29 = "max_campaigns") => {
748
1073
  const wanted = [...new Set(statuses)];
749
- const cap = { input: input28, max, what: "campaigns" };
1074
+ const cap = { input: input29, max, what: "campaigns" };
750
1075
  const read = context.outbound.provider === "combined" ? await readShared(context, wanted, cap) : await readOne(context, wanted, cap);
751
1076
  context.campaignsFound(read.items.length);
752
1077
  if (read.items.length === 0 && !read.capped) {
753
1078
  await countOthers(context, wanted, read.every);
754
1079
  }
755
- return { capped: read.capped, items: read.items };
1080
+ return {
1081
+ capped: read.capped,
1082
+ items: read.items,
1083
+ skipped: read.skipped ?? []
1084
+ };
756
1085
  };
757
1086
 
758
1087
  // src/insights/fields.ts
@@ -766,15 +1095,23 @@ var statusesInput = (fallback) => z.array(campaignStatusSchema).min(1).default([
766
1095
  );
767
1096
 
768
1097
  // src/insights/people/read.ts
769
- var readCappedFlag = (context, open, max, what, input28) => readCapped(context, open, { input: input28, max, what });
1098
+ var readCappedFlag = (context, open, max, what, input29) => readCapped(context, open, { input: input29, max, what });
770
1099
  var readByRef = async (context, refs, read, what, effect) => {
771
1100
  if (refs.length === 0) {
772
1101
  return /* @__PURE__ */ new Map();
773
1102
  }
774
1103
  const found = await read(refs);
775
- if (found.errors.length > 0) {
1104
+ const capped2 = found.errors.filter(({ error }) => isCapStop(error));
1105
+ const failed = found.errors.length - capped2.length;
1106
+ if (failed > 0) {
776
1107
  context.note(
777
- `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
1108
+ `${plural(failed, ...what)} could not be read, so ${noun(failed, "its", "their")} ${effect}.`
1109
+ );
1110
+ }
1111
+ const [stop] = capped2;
1112
+ if (stop !== void 0) {
1113
+ context.partial(
1114
+ `A request cap stopped the reads of ${plural(capped2.length, ...what)}, so ${noun(capped2.length, "its", "their")} ${effect}: ${stop.error.message}`
778
1115
  );
779
1116
  }
780
1117
  const [costliest] = found.results.toSorted(
@@ -786,17 +1123,13 @@ var readByRef = async (context, refs, read, what, effect) => {
786
1123
  return new Map(found.results.map(({ id, value }) => [id, value]));
787
1124
  };
788
1125
  var statusesField = statusesInput(["active"]);
789
- var campaignsIn = async (context, statuses, max) => {
790
- const { items } = await readCampaignsIn(context, statuses, max);
791
- return items;
792
- };
793
- var leadsOf = async (context, campaign, max, input28) => {
1126
+ var leadsOf = async (context, campaign, max, input29) => {
794
1127
  const { items } = await readCappedFlag(
795
1128
  context,
796
1129
  (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
797
1130
  max,
798
1131
  "leads of a campaign",
799
- input28
1132
+ input29
800
1133
  );
801
1134
  return items;
802
1135
  };
@@ -852,302 +1185,6 @@ var noteEngagement = (context, leads, effect, counts = COUNTS) => {
852
1185
  }
853
1186
  };
854
1187
 
855
- // src/insights/variables.ts
856
- var PATTERNS = [
857
- /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
858
- /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
859
- /%(?<name>[A-Za-z_][\w-]*)%/gu
860
- ];
861
- var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
862
- var BUILTINS = /* @__PURE__ */ new Map([
863
- ["company", (lead) => lead.company],
864
- ["companyname", (lead) => lead.company],
865
- ["email", (lead) => lead.email],
866
- ["firstname", (lead) => lead.firstName],
867
- ["jobtitle", (lead) => lead.title],
868
- ["lastname", (lead) => lead.lastName],
869
- ["title", (lead) => lead.title]
870
- ]);
871
- var isBuiltin = (key) => BUILTINS.has(key);
872
- var SENDER = /* @__PURE__ */ new Map([
873
- [
874
- "instantly",
875
- /* @__PURE__ */ new Set([
876
- "accountsignature",
877
- "sendingaccountemail",
878
- "sendingaccountfirstname",
879
- "sendingaccountname"
880
- ])
881
- ]
882
- ]);
883
- var isSender = (provider, key) => SENDER.get(provider)?.has(key) ?? false;
884
- var variablesIn = (text) => PATTERNS.flatMap(
885
- (pattern) => [...text.matchAll(pattern)].map((match) => {
886
- const fallback = match.groups?.fallback;
887
- return {
888
- fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
889
- index: match.index,
890
- name: match.groups?.name ?? "",
891
- raw: match[0]
892
- };
893
- })
894
- );
895
- var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
896
- var valueOf = (lead, key) => {
897
- const builtin = BUILTINS.get(key)?.(lead);
898
- if (filled(builtin)) {
899
- return builtin;
900
- }
901
- const custom = Object.entries(lead.custom).find(
902
- ([name, value]) => keyOf(name) === key && filled(value)
903
- );
904
- return custom?.[1] ?? null;
905
- };
906
- var keysWithValue = (lead) => /* @__PURE__ */ new Set([
907
- ...[...BUILTINS].flatMap(
908
- ([key, read]) => filled(read(lead)) ? [key] : []
909
- ),
910
- ...Object.entries(lead.custom).flatMap(
911
- ([key, value]) => filled(value) ? [keyOf(key)] : []
912
- )
913
- ]);
914
- var fillVariables = (text, lead) => {
915
- const matches = variablesIn(text).toSorted(
916
- (left, right) => left.index - right.index
917
- );
918
- const unfilled = [];
919
- let out = "";
920
- let at = 0;
921
- for (const match of matches) {
922
- if (match.index >= at) {
923
- const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
924
- if (value === null && !unfilled.includes(match.name)) {
925
- unfilled.push(match.name);
926
- }
927
- out += text.slice(at, match.index) + (value ?? match.raw);
928
- at = match.index + match.raw.length;
929
- }
930
- }
931
- return { text: out + text.slice(at), unfilled };
932
- };
933
-
934
- // src/insights/step.ts
935
- var stepAt = (index) => ({
936
- step: index,
937
- stepIndex: index,
938
- stepNumber: index + 1
939
- });
940
- var stepLabel = (index, of = null) => of === null || of < index + 1 ? `step ${index + 1}` : `step ${index + 1} (of ${of})`;
941
-
942
- // src/insights/copy/copy-checks.ts
943
- var CHECKS = {
944
- all_caps: "low",
945
- body_too_long: "low",
946
- connection_request_too_long: "high",
947
- exclamation_marks: "low",
948
- image: "medium",
949
- malformed_variable: "high",
950
- missing_subject: "high",
951
- spam_words: "medium",
952
- subject_breaks_thread: "medium",
953
- subject_too_long: "low",
954
- too_many_links: "medium"
955
- };
956
- var DEFAULT_SPAM_WORDS = [
957
- "100% free",
958
- "act now",
959
- "buy now",
960
- "cash bonus",
961
- "click here",
962
- "double your",
963
- "earn money",
964
- "free trial",
965
- "guarantee",
966
- "limited time",
967
- "no obligation",
968
- "risk-free",
969
- "urgent",
970
- "winner"
971
- ];
972
- var TAG = /<[^>]+>/gu;
973
- var IMAGE = /<img\b[^>]*>/giu;
974
- var VARIABLE = /\{\{[^{}]*\}\}/gu;
975
- var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
976
- var ANCHOR = /<a\b(?<attributes>[^>]*)>[\s\S]*?<\/a\s*>/giu;
977
- var HREF = /\bhref\s*=\s*["']?(?<target>[^"'\s>]+)/iu;
978
- var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
979
- var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
980
- var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
981
- var SNIPPET = 80;
982
- var clip = (text) => text.length > SNIPPET ? `${text.slice(0, SNIPPET)}\u2026` : text;
983
- var visible = (text) => text.replaceAll(TAG, " ").replaceAll(VARIABLE, " variable ");
984
- var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== "");
985
- var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
986
- var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
987
- check: "subject_too_long",
988
- finding: `The subject is ${plural(subject.length, "character")}; the limit is ${limits.maxSubjectChars}.`,
989
- text: clip(subject)
990
- } : null;
991
- var bodyTooLong = (body, limits) => {
992
- const words = wordsOf(body);
993
- return words.length > limits.maxBodyWords ? {
994
- check: "body_too_long",
995
- finding: `The body is ${plural(words.length, "word")}; the limit is ${limits.maxBodyWords}.`,
996
- text: clip(words.slice(0, 12).join(" "))
997
- } : null;
998
- };
999
- var linksOf = (body) => {
1000
- const html = body.replaceAll(IMAGE, " ");
1001
- const anchored = [...html.matchAll(ANCHOR)].flatMap((anchor) => {
1002
- const target = HREF.exec(anchor.groups?.attributes ?? "")?.groups?.target;
1003
- return target === void 0 ? [] : [target];
1004
- });
1005
- return [...anchored, ...html.replaceAll(ANCHOR, " ").match(LINK) ?? []];
1006
- };
1007
- var tooManyLinks = (body, limits) => {
1008
- const links = linksOf(body);
1009
- return links.length > limits.maxLinks ? {
1010
- check: "too_many_links",
1011
- finding: `The body has ${plural(links.length, "link")}; the limit is ${limits.maxLinks}.`,
1012
- text: clip(links.join(" "))
1013
- } : null;
1014
- };
1015
- var spamWords = (text, limits) => {
1016
- const plain2 = visible(text);
1017
- const hits = limits.spamWords.filter(
1018
- (word) => word.trim() !== "" && new RegExp(
1019
- String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
1020
- "iu"
1021
- ).test(plain2)
1022
- );
1023
- return hits.length > 0 ? {
1024
- check: "spam_words",
1025
- finding: `The copy uses ${plural(hits.length, "word or phrase", "words or phrases")} that spam filters weigh.`,
1026
- text: hits.join(", ")
1027
- } : null;
1028
- };
1029
- var malformedVariable = (text) => {
1030
- const empty = (text.match(VARIABLE) ?? []).filter(
1031
- (token) => token.slice(2, -2).trim() === ""
1032
- );
1033
- const rest = text.replaceAll(VARIABLE, "");
1034
- const stray = /\{\{|\}\}/u.exec(rest);
1035
- if (stray === null && empty.length === 0) {
1036
- return null;
1037
- }
1038
- return {
1039
- check: "malformed_variable",
1040
- finding: stray === null ? "A variable has no name between its braces, so it sends as blank or as raw braces." : "A variable's braces are not balanced, so it sends as raw text.",
1041
- text: stray === null ? empty[0] ?? "" : clip(
1042
- rest.slice(Math.max(0, stray.index - 20), stray.index + 30).trim()
1043
- )
1044
- };
1045
- };
1046
- var allCaps = (text, limits) => {
1047
- const words = text.replaceAll(TAG, " ").replaceAll(VARIABLE, " ").match(CAPS_WORD);
1048
- const found = words ?? [];
1049
- return found.length > limits.maxCapsWords ? {
1050
- check: "all_caps",
1051
- finding: `${plural(found.length, "word")} of four or more letters ${noun(found.length, "is", "are")} in capitals; the limit is ${limits.maxCapsWords}.`,
1052
- text: clip(found.join(" "))
1053
- } : null;
1054
- };
1055
- var exclamationMarks = (text, limits) => {
1056
- const marks = visible(text).split("!").length - 1;
1057
- return marks > limits.maxExclamations ? {
1058
- check: "exclamation_marks",
1059
- finding: `The copy has ${marks} exclamation marks; the limit is ${limits.maxExclamations}.`,
1060
- text: "!".repeat(marks)
1061
- } : null;
1062
- };
1063
- var image = (body) => {
1064
- const [first] = body.match(IMAGE) ?? [];
1065
- if (first === void 0) {
1066
- return null;
1067
- }
1068
- return {
1069
- check: "image",
1070
- finding: PIXEL.test(first) ? "The body holds a tracking pixel, which spam filters and privacy tools flag." : "The body holds an image, which cold email filters weigh against.",
1071
- text: clip(first)
1072
- };
1073
- };
1074
- var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
1075
- var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
1076
- check: "connection_request_too_long",
1077
- finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
1078
- text: clip(body)
1079
- } : null;
1080
-
1081
- // src/insights/copy/audit-variant.ts
1082
- var emailChecks = (step, variant, limits, thread) => {
1083
- const subject = variant.subject?.trim() ?? "";
1084
- const body = variant.body ?? "";
1085
- const key = threadKey(subject);
1086
- const problems = [
1087
- subject === "" ? null : subjectTooLong(subject, limits),
1088
- spamWords(`${subject}
1089
- ${body}`, limits),
1090
- tooManyLinks(body, limits),
1091
- image(body)
1092
- ];
1093
- if (step.index === thread.first && subject === "") {
1094
- problems.push({
1095
- check: "missing_subject",
1096
- finding: "The first email has no subject.",
1097
- text: ""
1098
- });
1099
- }
1100
- if (step.index !== thread.first && key !== "" && thread.subjects !== null && !thread.subjects.has(key)) {
1101
- problems.push({
1102
- check: "subject_breaks_thread",
1103
- finding: "This follow-up has a subject that differs from the first email's, so it starts a new thread instead of continuing the first.",
1104
- text: subject
1105
- });
1106
- }
1107
- return problems;
1108
- };
1109
- var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
1110
- var auditVariant = (step, variant, limits, thread, lead) => {
1111
- const body = variant.body ?? "";
1112
- const whole = `${variant.subject ?? ""}
1113
- ${body}`;
1114
- const problems = [
1115
- malformedVariable(whole),
1116
- bodyTooLong(body, limits),
1117
- allCaps(whole, limits),
1118
- exclamationMarks(whole, limits),
1119
- ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
1120
- ];
1121
- return problems.flatMap(
1122
- (problem) => problem === null ? [] : [
1123
- {
1124
- ...problem,
1125
- action: step.action,
1126
- lead,
1127
- severity: CHECKS[problem.check],
1128
- ...stepAt(step.index),
1129
- variantKey: variant.variantKey
1130
- }
1131
- ]
1132
- );
1133
- };
1134
- var threadOf = (steps, perLead2) => {
1135
- const [first] = steps.toSorted((left, right) => left.index - right.index);
1136
- const variants = first?.variants ?? [];
1137
- return {
1138
- first: first?.index ?? null,
1139
- subjects: first !== void 0 && variants.some((variant) => perLead2(variant)) ? null : new Set(
1140
- variants.flatMap((variant) => {
1141
- const key = threadKey(variant.subject);
1142
- return key === "" ? [] : [key];
1143
- })
1144
- )
1145
- };
1146
- };
1147
-
1148
- // src/insights/copy/copy-preview.ts
1149
- import { z as z3 } from "zod";
1150
-
1151
1188
  // src/insights/ref.ts
1152
1189
  var refOf = (outbound, id) => {
1153
1190
  const provider = parseRef(id)?.provider;
@@ -1408,21 +1445,25 @@ var countsOf = (findings, isEmail) => CHECK_NAMES.filter(
1408
1445
  );
1409
1446
  var readSamples = async (context, args, sequence2) => {
1410
1447
  if (!sequence2.steps.some((step) => step.variants.some(writtenPerLead))) {
1411
- return { leads: [], reason: null };
1448
+ return { capped: false, leads: [], reason: null };
1412
1449
  }
1413
1450
  if (args.samples === 0) {
1414
- return { leads: [], reason: "samples is 0" };
1451
+ return { capped: false, leads: [], reason: "samples is 0" };
1415
1452
  }
1416
1453
  if (context.outbound.capabilities["leads.byCampaign"] === false) {
1417
- return { leads: [], reason: "this tool does not list a campaign's leads" };
1454
+ return {
1455
+ capped: false,
1456
+ leads: [],
1457
+ reason: "this tool does not list a campaign's leads"
1458
+ };
1418
1459
  }
1419
- const leads = await leadsOf(
1420
- context,
1421
- args.campaign,
1422
- args.max_leads,
1423
- "max_leads"
1424
- );
1425
- return leads.length === 0 ? { leads: [], reason: "the campaign has no leads" } : {
1460
+ const walk = context.outbound.campaign(args.campaign).leads.listAll({ max: args.max_leads });
1461
+ const leads = await walk.toArray();
1462
+ if (walk.meta !== void 0) {
1463
+ context.one({ meta: walk.meta });
1464
+ }
1465
+ return leads.length === 0 ? { capped: false, leads: [], reason: "the campaign has no leads" } : {
1466
+ capped: walk.truncated,
1426
1467
  leads: pickSamples(leads, perLeadKeys(sequence2.steps), args.samples),
1427
1468
  reason: null
1428
1469
  };
@@ -1493,15 +1534,20 @@ var copyAudit = defineInsight({
1493
1534
  ].toSorted(
1494
1535
  (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
1536
  );
1496
- const withoutBody = variants.filter(
1537
+ const withoutBody2 = variants.filter(
1497
1538
  ({ variant }) => variant.body === null
1498
1539
  ).length;
1499
- if (withoutBody > 0) {
1540
+ if (withoutBody2 > 0) {
1500
1541
  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.`
1542
+ 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
1543
  );
1503
1544
  }
1504
1545
  noteSamples(context, perLead2, samples, sampled);
1546
+ if (samples.capped && (sampled.unaudited > 0 || sampled.leads.length < args.samples)) {
1547
+ context.partial(
1548
+ capNote({ input: "max_leads", max: args.max_leads, what: "leads" })
1549
+ );
1550
+ }
1505
1551
  const severity = (level) => findings.filter((finding) => finding.severity === level).length;
1506
1552
  const audit2 = {
1507
1553
  byCheck: countsOf(findings, isEmail),
@@ -1518,7 +1564,7 @@ var copyAudit = defineInsight({
1518
1564
  stepsChecked: sequence2.steps.length,
1519
1565
  variantsChecked: variants.length,
1520
1566
  leadsAudited: sampled.leads,
1521
- variantsWithoutBody: withoutBody,
1567
+ variantsWithoutBody: withoutBody2,
1522
1568
  variantsNotAudited: sampled.unaudited,
1523
1569
  variantsWrittenPerLead: perLead2
1524
1570
  };
@@ -1596,12 +1642,12 @@ var compareRates = (first, second, alpha = 0.05) => {
1596
1642
  if (error === 0) {
1597
1643
  return null;
1598
1644
  }
1599
- const z32 = (first.successes / first.trials - second.successes / second.trials) / error;
1600
- const pValue = 1 - erf(Math.abs(z32) / Math.SQRT2);
1645
+ const z34 = (first.successes / first.trials - second.successes / second.trials) / error;
1646
+ const pValue = 1 - erf(Math.abs(z34) / Math.SQRT2);
1601
1647
  return {
1602
1648
  pValue: round(pValue) ?? 0,
1603
1649
  significant: pValue < alpha,
1604
- z: round(z32) ?? 0
1650
+ z: round(z34) ?? 0
1605
1651
  };
1606
1652
  };
1607
1653
  var percent = (value) => value === null ? "unknown" : percentOf(value);
@@ -1660,7 +1706,7 @@ var BASIS_WORDS = {
1660
1706
  delivered: "per message delivered",
1661
1707
  sent: "per message sent"
1662
1708
  };
1663
- var basesInWords = (named4) => named4.map(
1709
+ var basesInWords = (named5) => named5.map(
1664
1710
  ({ basis, name }) => `${name} ${basis === null ? "with no base" : BASIS_WORDS[basis]}`
1665
1711
  ).join(", ");
1666
1712
  var measure = (count2, base) => {
@@ -2571,9 +2617,9 @@ var lastDays = (now, days, back = 0) => ({
2571
2617
  from: dayOf(now - days * (back + 1) * DAY_MS2),
2572
2618
  to: dayOf(now - (days * back + 1) * DAY_MS2)
2573
2619
  });
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"));
2620
+ var campaignTotalsCost = (input29, price) => {
2621
+ const campaigns = price.campaigns(input29.max_campaigns);
2622
+ 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
2623
  };
2578
2624
  var LIST_DEFAULTS = { maxCampaigns: 50, statuses: ["active"] };
2579
2625
  var listFields = (costPerCampaign, defaults = LIST_DEFAULTS) => ({
@@ -2607,6 +2653,9 @@ var measure2 = (count2, of) => {
2607
2653
  var baseIn2 = (basis) => (counts) => counts[basis];
2608
2654
  var perLeadBasis = (counts) => counts.contacted !== null && counts.contacted > 0 ? "contacted" : "sent";
2609
2655
  var perLeadBase = (counts) => counts[perLeadBasis(counts)];
2656
+ var replyBasisAcross = (rows) => rows.some(
2657
+ (row) => (row.contacted ?? 0) === 0 && (row.replied ?? 0) > 0 && row.sent !== null
2658
+ ) ? "sent" : "contacted";
2610
2659
  var periodBasis = (current, previous) => current.sent !== null && previous.sent !== null ? "sent" : "contacted";
2611
2660
  var RATE_WORDS = {
2612
2661
  contacted: "Replies per lead contacted",
@@ -2632,9 +2681,9 @@ var measureAcross = (rows, countOf3, baseOf) => {
2632
2681
  };
2633
2682
  };
2634
2683
  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);
2684
+ var ratesAcross = (rows, basis = replyBasisAcross(rows)) => {
2685
+ const reply = measureAcross(rows, (row) => row.replied, baseIn2(basis));
2686
+ const positive = measureAcross(rows, (row) => row.positive, baseIn2(basis));
2638
2687
  const bounce = measureAcross(
2639
2688
  rows,
2640
2689
  (row) => row.bounced,
@@ -2650,7 +2699,8 @@ var ratesAcross = (rows, base = perLeadBase) => {
2650
2699
  bounceRate: bounce.measured,
2651
2700
  positiveRate: positive.measured,
2652
2701
  replyRate: reply.measured
2653
- }
2702
+ },
2703
+ replyRateBasis: basis
2654
2704
  };
2655
2705
  };
2656
2706
  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,23 +2738,61 @@ var readAllTotals = async (context, range) => {
2688
2738
  [...byCampaign].map(([ref, counts]) => [ref, sumMeasured(counts)])
2689
2739
  );
2690
2740
  };
2691
- var readCampaignTotals = async (context, input28) => {
2741
+ var readCampaignTotals = async (context, input29) => {
2692
2742
  const listed2 = await readCampaignsIn(
2693
2743
  context,
2694
- input28.statuses,
2695
- input28.max_campaigns
2744
+ input29.statuses,
2745
+ input29.max_campaigns
2696
2746
  );
2697
2747
  const campaigns = listed2.items;
2698
- const reported = campaigns.length > 1 ? await readAllTotals(context, input28) : void 0;
2748
+ const reported = campaigns.length > 1 ? await readAllTotals(context, input29) : void 0;
2699
2749
  const entries = await context.each(
2700
2750
  campaigns,
2701
2751
  async (campaign) => ({
2702
2752
  campaign,
2703
- counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input28)
2753
+ counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input29)
2704
2754
  }),
2705
2755
  "campaigns"
2706
2756
  );
2707
- return { entries, read: campaignsReadOf(listed2) };
2757
+ return { entries, read: campaignsReadOf(listed2), skipped: listed2.skipped };
2758
+ };
2759
+ var toolsLeftOut = async (context, skipped, range) => {
2760
+ const left = await Promise.all(
2761
+ skipped.map(async (tool) => {
2762
+ const outbound = context.outbound.workspace(tool.tool);
2763
+ if (outbound.capabilities["stats.workspace"] === false) {
2764
+ return { ...tool, counts: null };
2765
+ }
2766
+ const rows = context.rows(
2767
+ await outbound.stats({
2768
+ from: range.from ?? void 0,
2769
+ to: range.to ?? void 0
2770
+ })
2771
+ );
2772
+ return { ...tool, counts: totalsOf(sumMeasured(rows)) };
2773
+ })
2774
+ );
2775
+ const active = left.filter(
2776
+ ({ counts }) => (counts?.sent ?? 0) > 0 || (counts?.replied ?? 0) > 0
2777
+ );
2778
+ if (active.length > 0) {
2779
+ context.note(
2780
+ `Left out of the totals: ${active.map(({ counts, tool }) => `${tool} (${counts?.sent ?? "unknown"} sent, ${counts?.replied ?? "unknown"} replied)`).join(", ")}, which had activity in the period but no campaign in the states asked for. Their counts are in toolsLeftOut; pass statuses to read their campaigns.`
2781
+ );
2782
+ }
2783
+ return left;
2784
+ };
2785
+ var campaignsBasis = (campaigns, statuses) => ({
2786
+ autoReplies: "excluded",
2787
+ covers: "campaigns",
2788
+ description: `The ${campaigns} ${campaigns === 1 ? "campaign" : "campaigns"} read (${either(statuses)}) added together. replied and positive count leads who replied, not reply messages, with automatic replies left out of replied.`,
2789
+ replies: "people"
2790
+ });
2791
+ var WORKSPACE_BASIS = {
2792
+ autoReplies: "excluded",
2793
+ covers: "workspace",
2794
+ description: "The vendor's own workspace totals: every campaign, whatever its state. replied and positive count leads who replied, not reply messages, with automatic replies left out of replied.",
2795
+ replies: "people"
2708
2796
  };
2709
2797
  var readDaily = async (context, campaign, range) => {
2710
2798
  const options = { by: "day", from: range.from, to: range.to };
@@ -2872,7 +2960,7 @@ var bounces = (facts, limits) => {
2872
2960
  {
2873
2961
  code: "high_bounce_rate",
2874
2962
  finding: `Bounce rate is ${percent(rate2)} (${count2} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
2875
- next: "Use bounce_watch to find the senders behind it, and verify the lead list.",
2963
+ next: "Verify the lead list. Use bounce_watch to find the senders behind it.",
2876
2964
  numbers: {
2877
2965
  bounced: count2,
2878
2966
  high,
@@ -2895,7 +2983,7 @@ var replies = (facts, limits) => {
2895
2983
  {
2896
2984
  code: "low_reply_rate",
2897
2985
  finding: `Reply rate is ${percent(rate2)} (${count2} of ${of}), under the ${percent(limits.minReplyRate)} floor. The 95% interval is ${percent(low)} to ${percent(high)}, ${clearly ? "so it is below the floor beyond chance" : "which still reaches the floor, so more sends are needed to be sure"}.`,
2898
- next: "Use step_funnel and copy_audit to see where replies are lost.",
2986
+ next: "Use step_funnel to see which step loses replies. Use copy_audit to check the copy.",
2899
2987
  numbers: {
2900
2988
  floor: limits.minReplyRate,
2901
2989
  high,
@@ -2947,7 +3035,7 @@ var outOfLeads = (recent, leads) => {
2947
3035
  return {
2948
3036
  code: "out_of_leads",
2949
3037
  finding: `${fell} because the campaign is running out of leads: ${left}.${finishing} This is lead runout, not a sending fault.`,
2950
- next: "Add leads to keep the campaign sending; pipeline_forecast shows what the leads left should produce.",
3038
+ next: "Add leads to keep the campaign sending. pipeline_forecast shows what the leads left should produce.",
2951
3039
  numbers: {
2952
3040
  activeLeads: leads.active,
2953
3041
  before: recent.before,
@@ -2974,7 +3062,7 @@ var recentSends = (facts, limits) => {
2974
3062
  {
2975
3063
  code: "no_recent_sends",
2976
3064
  finding: `The campaign is active but the vendor reports no sends in the last ${recent.days} days.`,
2977
- next: "Check its senders and schedule, and whether leads remain (pipeline_forecast).",
3065
+ next: "Check its senders, its schedule and whether leads remain. pipeline_forecast shows the leads left.",
2978
3066
  numbers: { days: recent.days, sent: recent.sent },
2979
3067
  severity: "high"
2980
3068
  }
@@ -2985,7 +3073,7 @@ var recentSends = (facts, limits) => {
2985
3073
  {
2986
3074
  code: "falling_sends",
2987
3075
  finding: `Sends fell from ${recent.before} to ${recent.sent} over the last ${recent.days} days against the ${recent.days} before, a drop of ${percent(drop)}.`,
2988
- next: "Use pipeline_forecast to check the leads left, and sender_capacity for the mailboxes.",
3076
+ next: "Use pipeline_forecast to check the leads left. Use sender_capacity for the mailboxes.",
2989
3077
  numbers: { before: recent.before, drop, sent: recent.sent },
2990
3078
  severity: "medium"
2991
3079
  }
@@ -2995,7 +3083,7 @@ var sequence = ({ steps }) => steps === null || steps < 1 || steps > 2 ? [] : [
2995
3083
  {
2996
3084
  code: "short_sequence",
2997
3085
  finding: `The sequence has ${steps} ${steps === 1 ? "step" : "steps"}; follow-ups usually bring a large share of the replies.`,
2998
- next: "Add follow-up steps; step_funnel shows what each step earns.",
3086
+ next: "Add follow-up steps. step_funnel shows what each step earns.",
2999
3087
  numbers: { steps },
3000
3088
  severity: "medium"
3001
3089
  }
@@ -3217,9 +3305,10 @@ var readLeadsLeft = async (context, campaign, recent, maxLeads) => {
3217
3305
  }
3218
3306
  const split = splitActive(leads);
3219
3307
  const unknown = leads.filter((lead) => lead.status === "unknown").length;
3308
+ const runway = runwayOf(split, { unknown }, true, recent.startedPerDay);
3220
3309
  return {
3221
3310
  active: split.active,
3222
- daysLeft: runwayDays(split, { unknown }, true, recent.startedPerDay),
3311
+ daysLeft: runway.state === "out_of_leads" ? 0 : runway.daysLeft,
3223
3312
  inSequence: split.inSequence,
3224
3313
  toStart: leadsToStart(split)
3225
3314
  };
@@ -3396,7 +3485,7 @@ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
3396
3485
  };
3397
3486
  };
3398
3487
  var campaignRanking = defineInsight({
3399
- description: "Which campaigns are best, ranked fairly: by the low end of the 95% Wilson interval of the reply rate (or positive reply rate; for bounce rate, by the high end, lowest first), so 2 replies from 10 sends cannot outrank 150 from 1,000. Use it to pick winners and losers across a workspace. Returns each campaign with its count, rate, interval and rank, the campaigns left out for too few sends, those whose count the vendor does not report (a null rate is unknown, not zero), and the gap between the top and the median. 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).",
3488
+ description: "Which campaigns are best, ranked fairly: by the low end of the 95% Wilson interval of the reply rate (or positive reply rate; for bounce rate, by the high end, lowest first), so 2 replies from 10 sends cannot outrank 150 from 1,000. Use it to pick winners and losers across a workspace. Returns each campaign with its count, rate, interval and rank, the campaigns left out for too few sends, those whose count the vendor does not report (a null rate is unknown, not zero), and the gap between the top and the median. On a combined instance a tool with no campaign in statuses is named in toolsLeftOut with its own totals for the period, one stats request each. 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).",
3400
3489
  inputSchema: input9,
3401
3490
  key: "campaignRanking",
3402
3491
  cost: campaignTotalsCost,
@@ -3406,13 +3495,18 @@ var campaignRanking = defineInsight({
3406
3495
  partialOnCap: true,
3407
3496
  next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
3408
3497
  run: async (context, options) => {
3409
- const { entries, read } = await readCampaignTotals(context, options);
3498
+ const { entries, read, skipped } = await readCampaignTotals(
3499
+ context,
3500
+ options
3501
+ );
3502
+ const period = { from: options.from, to: options.to };
3410
3503
  const ranking = {
3411
3504
  ...rankCampaigns(entries, options.metric, options.min_sent),
3412
3505
  ...read,
3413
3506
  better: options.metric === "bounce_rate" ? "lower" : "higher",
3414
3507
  metric: options.metric,
3415
- period: { from: options.from, to: options.to }
3508
+ period,
3509
+ toolsLeftOut: await toolsLeftOut(context, skipped, period)
3416
3510
  };
3417
3511
  return ranking;
3418
3512
  }
@@ -3430,10 +3524,11 @@ var input10 = z13.object({
3430
3524
  "The p-value under which a difference counts as more than chance"
3431
3525
  )
3432
3526
  });
3433
- var groupOf = (channel, entries) => {
3527
+ var groupOf = (channel, entries, basis) => {
3434
3528
  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);
3529
+ const base = baseIn2(basis);
3530
+ const reply = measureAcross(counts, (row) => row.replied, base);
3531
+ const positive = measureAcross(counts, (row) => row.positive, base);
3437
3532
  const acceptance = measureAcross(
3438
3533
  counts,
3439
3534
  (row) => row.connectionsAccepted,
@@ -3456,15 +3551,16 @@ var groupOf = (channel, entries) => {
3456
3551
  };
3457
3552
  };
3458
3553
  var CHANNELS = ["email", "linkedin"];
3459
- var byChannel = (entries) => CHANNELS.flatMap((channel) => {
3554
+ var byChannel = (entries, basis) => CHANNELS.flatMap((channel) => {
3460
3555
  const members = entries.filter(
3461
3556
  (entry) => entry.campaign.channel === channel
3462
3557
  );
3463
- return members.length === 0 ? [] : [groupOf(channel, members)];
3558
+ return members.length === 0 ? [] : [groupOf(channel, members, basis)];
3464
3559
  });
3465
- var byProvider = (entries) => [...new Set(entries.map((entry) => entry.campaign.provider))].toSorted().flatMap(
3560
+ var byProvider = (entries, basis) => [...new Set(entries.map((entry) => entry.campaign.provider))].toSorted().flatMap(
3466
3561
  (provider) => byChannel(
3467
- entries.filter((entry) => entry.campaign.provider === provider)
3562
+ entries.filter((entry) => entry.campaign.provider === provider),
3563
+ basis
3468
3564
  ).map(({ group, partial }) => ({
3469
3565
  group: { ...group, provider },
3470
3566
  partial
@@ -3490,76 +3586,358 @@ var compare = (groups, alpha, read, statuses) => {
3490
3586
  { successes: second.replyRate.count, trials: second.replyRate.of },
3491
3587
  alpha
3492
3588
  );
3493
- if (test === null) {
3494
- return {
3495
- comparison: null,
3496
- finding: "Reply rates cannot be compared: a channel has no reply or volume counts, or neither has a reply."
3497
- };
3589
+ if (test === null) {
3590
+ return {
3591
+ comparison: null,
3592
+ finding: "Reply rates cannot be compared: a channel has no reply or volume counts, or neither has a reply."
3593
+ };
3594
+ }
3595
+ const [higher, lower] = test.z >= 0 ? [first, second] : [second, first];
3596
+ return {
3597
+ comparison: {
3598
+ difference: round((higher.replyRate.rate ?? 0) - (lower.replyRate.rate ?? 0)) ?? 0,
3599
+ higher: higher.channel,
3600
+ test
3601
+ },
3602
+ finding: `The reply rate is ${percent(higher.replyRate.rate)} on ${NAMES[higher.channel]} against ${percent(lower.replyRate.rate)} on ${NAMES[lower.channel]}; ${test.significant ? "the difference is more than chance" : "the difference could be chance"} (${pText(test.pValue)}).`
3603
+ };
3604
+ };
3605
+ var channelMix = defineInsight({
3606
+ 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).",
3607
+ inputSchema: input10,
3608
+ key: "channelMix",
3609
+ cost: campaignTotalsCost,
3610
+ scales: "max_campaigns",
3611
+ name: "channel_mix",
3612
+ needs: ["stats.campaign"],
3613
+ next: "Use campaign_ranking to see which campaigns carry the better channel.",
3614
+ run: async (context, options) => {
3615
+ const { entries, read } = await readCampaignTotals(context, options);
3616
+ const basis = replyBasisAcross(entries.map((entry) => entry.counts));
3617
+ const channels = byChannel(entries, basis);
3618
+ const providers = byProvider(entries, basis);
3619
+ for (const { group, partial } of channels) {
3620
+ if (partial.length > 0) {
3621
+ context.note(partialNote(`Channel ${group.channel}`, partial));
3622
+ }
3623
+ }
3624
+ for (const { group, partial } of providers) {
3625
+ if (partial.length > 0) {
3626
+ context.note(
3627
+ partialNote(`${group.provider} ${group.channel}`, partial)
3628
+ );
3629
+ }
3630
+ }
3631
+ const mix = {
3632
+ ...read,
3633
+ ...compare(
3634
+ channels.map((each) => each.group),
3635
+ options.alpha,
3636
+ read,
3637
+ options.statuses
3638
+ ),
3639
+ byProvider: providers.map((each) => each.group),
3640
+ channels: channels.map((each) => each.group),
3641
+ period: { from: options.from, to: options.to },
3642
+ replyRateBasis: basis
3643
+ };
3644
+ return mix;
3645
+ }
3646
+ });
3647
+
3648
+ // src/insights/ops/client-report.ts
3649
+ import { z as z16 } from "zod";
3650
+
3651
+ // src/insights/ops/pipeline-forecast.ts
3652
+ import { z as z14 } from "zod";
3653
+ var input11 = z14.object({
3654
+ campaign: z14.string().min(3).describe("The campaign's ref or name"),
3655
+ days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3656
+ max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3657
+ });
3658
+ var countStatuses = (leads) => {
3659
+ const counts = {
3660
+ active: 0,
3661
+ bounced: 0,
3662
+ completed: 0,
3663
+ paused: 0,
3664
+ replied: 0,
3665
+ skipped: 0,
3666
+ unknown: 0,
3667
+ unsubscribed: 0
3668
+ };
3669
+ for (const lead of leads) {
3670
+ counts[lead.status] += 1;
3671
+ }
3672
+ return counts;
3673
+ };
3674
+ var times = (leads, share2) => share2 === null ? null : round(leads * share2);
3675
+ var project = (leads, measured2) => ({
3676
+ expected: times(leads, measured2.rate),
3677
+ high: times(leads, measured2.high),
3678
+ low: times(leads, measured2.low)
3679
+ });
3680
+ var paceOf = async (context, campaign, days) => {
3681
+ if (context.outbound.capabilities["stats.byDay"] === false) {
3682
+ context.note(
3683
+ "Days of sending left were not estimated: the adapter has no stats by day."
3684
+ );
3685
+ return null;
3686
+ }
3687
+ const series = await readDaily(
3688
+ context,
3689
+ campaign,
3690
+ paceWindow(context.now, days)
3691
+ );
3692
+ return newLeadsPerDay(
3693
+ series.map((day) => day.counts),
3694
+ days
3695
+ );
3696
+ };
3697
+ var ASSUMPTIONS = [
3698
+ "Every remaining lead is contacted.",
3699
+ "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
3700
+ "The daily pace of new leads started stays what it was over the recent days. Days with no report count as none started."
3701
+ ];
3702
+ var describe2 = ({ complete, remaining, runway }, forecast) => {
3703
+ if (runway.state === "out_of_leads") {
3704
+ return remaining === 0 ? "No leads are left to contact; add leads to keep the campaign sending." : `No new leads are left to start; ${plural(runway.inSequence ?? remaining, "lead")} ${noun(runway.inSequence ?? remaining, "is", "are")} finishing the sequence. Add leads to keep the campaign starting new ones.`;
3705
+ }
3706
+ const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
3707
+ if (forecast.expected === null) {
3708
+ return `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.`;
3709
+ }
3710
+ const [expected, low, high] = [
3711
+ forecast.expected,
3712
+ forecast.low,
3713
+ forecast.high
3714
+ ].map((value) => spoken(value));
3715
+ const range = low === high ? "" : ` (between ${low} and ${high})`;
3716
+ return `${leads}; expect about ${expected} ${noun(Number(expected), "reply", "replies")}${range}. This is an estimate.`;
3717
+ };
3718
+ var ownerOf = (context, campaign) => context.outbound.provider === "combined" ? context.outbound.workspace(`${campaign.provider}:${campaign.workspaceId}`) : context.outbound;
3719
+ var readRunway = async (context, campaign, options) => {
3720
+ const owner = ownerOf(context, campaign);
3721
+ const status = options.activeOnly === true ? runwayStatus(owner.capabilities) : void 0;
3722
+ const { capped: capped2, items: leads } = await readCapped(
3723
+ context,
3724
+ (max) => owner.campaign(campaign.ref).leads.listAll({ max, status }),
3725
+ {
3726
+ input: options.leadsInput,
3727
+ max: options.maxLeads,
3728
+ what: options.leadsWhat
3729
+ }
3730
+ );
3731
+ const complete = !capped2;
3732
+ const byStatus = countStatuses(leads);
3733
+ const split = splitActive(leads);
3734
+ const pace = await paceOf(context, campaign.ref, options.days);
3735
+ return {
3736
+ active: byStatus.active,
3737
+ byStatus,
3738
+ complete,
3739
+ leadsRead: leads.length,
3740
+ runway: runwayOf(split, byStatus, complete, pace),
3741
+ split
3742
+ };
3743
+ };
3744
+ var forecastCampaign = async (context, campaign, options) => {
3745
+ const {
3746
+ active: remaining,
3747
+ byStatus,
3748
+ complete,
3749
+ leadsRead,
3750
+ runway,
3751
+ split
3752
+ } = await readRunway(context, campaign, options);
3753
+ const rates = ratesOf(
3754
+ await readTotals(context, campaign.ref, { from: null, to: null })
3755
+ );
3756
+ const expectedReplies = project(remaining, rates.replyRate);
3757
+ return {
3758
+ ...labelOf(campaign),
3759
+ assumptions: [
3760
+ ...ASSUMPTIONS,
3761
+ `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count === null ? "an unknown number of replies" : plural(rates.replyRate.count, "reply", "replies")} over ${rates.replyRate.of ?? "unknown"}.`
3762
+ ],
3763
+ byStatus,
3764
+ dailyContactRate: runway.pace,
3765
+ daysLeft: runway.daysLeft,
3766
+ estimate: true,
3767
+ expectedPositive: project(remaining, rates.positiveRate),
3768
+ expectedReplies,
3769
+ finding: describe2({ complete, remaining, runway }, expectedReplies),
3770
+ inSequence: split.inSequence,
3771
+ leadsComplete: complete,
3772
+ leadsRead,
3773
+ notStarted: split.notStarted,
3774
+ positiveRate: rates.positiveRate,
3775
+ remaining,
3776
+ replyRate: rates.replyRate,
3777
+ runwayState: runway.state
3778
+ };
3779
+ };
3780
+ var pipelineForecast = defineInsight({
3781
+ description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, split into those not yet started and those partway through the sequence, the days until no lead is left to start at the recent pace of new leads started per day (the same figure lead_runway gives), and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
3782
+ inputSchema: input11,
3783
+ key: "pipelineForecast",
3784
+ cost: (values, price) => price.one("campaigns.get") + price.list("leads.list", values.max_leads) + price.one("stats") + (price.capabilities["stats.byDay"] === false ? 0 : price.one("stats")),
3785
+ scales: "max_leads",
3786
+ name: "pipeline_forecast",
3787
+ needs: ["leads.byCampaign", "stats.campaign"],
3788
+ next: "Use client_report to see every campaign that is running out of leads.",
3789
+ run: async (context, options) => {
3790
+ const campaign = context.one(
3791
+ await context.outbound.campaigns.get(options.campaign)
3792
+ );
3793
+ return await forecastCampaign(context, campaign, {
3794
+ days: options.days,
3795
+ leadsInput: "max_leads",
3796
+ leadsWhat: "leads",
3797
+ maxLeads: options.max_leads
3798
+ });
3799
+ }
3800
+ });
3801
+
3802
+ // src/insights/ops/client-runway.ts
3803
+ var startingLeft = (daysLeft) => {
3804
+ if (daysLeft !== null && daysLeft < 0.05) {
3805
+ return "less than a day";
3806
+ }
3807
+ const days = spoken(daysLeft);
3808
+ return `about ${days} ${days === "1" ? "day" : "days"}`;
3809
+ };
3810
+ var NAMED = 10;
3811
+ var named = (names) => {
3812
+ const shown2 = names.slice(0, NAMED);
3813
+ const rest = names.length - shown2.length;
3814
+ return `${shown2.join(", ")}${rest > 0 ? ` and ${rest} more` : ""}`;
3815
+ };
3816
+ var readRunways = async (context, campaigns, options) => {
3817
+ const { capabilities } = context.outbound;
3818
+ if (!capabilities["leads.byCampaign"] || capabilities["stats.byDay"] === false) {
3819
+ return null;
3820
+ }
3821
+ const active = campaigns.flatMap(
3822
+ ({ campaign }) => campaign.status === "active" ? [campaign] : []
3823
+ );
3824
+ const forecasts = await context.each(
3825
+ active,
3826
+ async (campaign) => ({
3827
+ campaign,
3828
+ forecast: await readRunway(context, campaign, {
3829
+ activeOnly: true,
3830
+ days: options.days,
3831
+ leadsInput: "max_leads_per_campaign",
3832
+ leadsWhat: "leads of a campaign",
3833
+ maxLeads: options.max_leads_per_campaign
3834
+ })
3835
+ }),
3836
+ "active campaigns' leads"
3837
+ );
3838
+ const uncounted = forecasts.flatMap(
3839
+ ({ campaign, forecast }) => forecast.complete ? [] : [campaign.name]
3840
+ );
3841
+ if (uncounted.length > 0) {
3842
+ context.note(
3843
+ `The leads left were not fully counted for ${plural(uncounted.length, "active campaign")}, so runningOutOfLeads and stalled leave ${uncounted.length === 1 ? "it" : "them"} out: ${named(uncounted)}. Raise max_leads_per_campaign to count them.`
3844
+ );
3498
3845
  }
3499
- const [higher, lower] = test.z >= 0 ? [first, second] : [second, first];
3846
+ const runways = forecasts.flatMap(({ campaign, forecast }) => {
3847
+ const { daysLeft, inSequence, pace, remaining, state } = forecast.runway;
3848
+ return forecast.complete && state !== "unknown" ? [
3849
+ {
3850
+ ...labelOf(campaign),
3851
+ dailyContactRate: pace,
3852
+ daysLeft,
3853
+ inSequence,
3854
+ remaining,
3855
+ state
3856
+ }
3857
+ ] : [];
3858
+ });
3500
3859
  return {
3501
- comparison: {
3502
- difference: round((higher.replyRate.rate ?? 0) - (lower.replyRate.rate ?? 0)) ?? 0,
3503
- higher: higher.channel,
3504
- test
3505
- },
3506
- finding: `The reply rate is ${percent(higher.replyRate.rate)} on ${NAMES[higher.channel]} against ${percent(lower.replyRate.rate)} on ${NAMES[lower.channel]}; ${test.significant ? "the difference is more than chance" : "the difference could be chance"} (${pText(test.pValue)}).`
3860
+ // A campaign with no lead left to start is first: it has stopped starting new ones already.
3861
+ runningOut: runways.filter(
3862
+ (runway) => runway.state === "out_of_leads" || runway.state === "draining" && (runway.daysLeft ?? Infinity) <= options.runway_days
3863
+ ).toSorted(
3864
+ (left, right) => Number(right.state === "out_of_leads") - Number(left.state === "out_of_leads") || (left.daysLeft ?? 0) - (right.daysLeft ?? 0)
3865
+ ),
3866
+ stalled: runways.filter((runway) => runway.state === "stalled")
3507
3867
  };
3508
3868
  };
3509
- 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).",
3511
- inputSchema: input10,
3512
- key: "channelMix",
3513
- cost: campaignTotalsCost,
3514
- scales: "max_campaigns",
3515
- name: "channel_mix",
3516
- needs: ["stats.campaign"],
3517
- next: "Use campaign_ranking to see which campaigns carry the better channel.",
3518
- run: async (context, options) => {
3519
- const { entries, read } = await readCampaignTotals(context, options);
3520
- const channels = byChannel(entries);
3521
- const providers = byProvider(entries);
3522
- for (const { group, partial } of channels) {
3523
- if (partial.length > 0) {
3524
- context.note(partialNote(`Channel ${group.channel}`, partial));
3525
- }
3526
- }
3527
- for (const { group, partial } of providers) {
3528
- if (partial.length > 0) {
3529
- context.note(
3530
- partialNote(`${group.provider} ${group.channel}`, partial)
3531
- );
3532
- }
3869
+ var oneRunwayAction = (runway) => {
3870
+ if (runway.state === "draining") {
3871
+ return `Add leads to ${runway.campaignName}: ${plural(runway.remaining, "lead")} ${runway.remaining === 1 ? "is" : "are"} left to start, ${startingLeft(runway.daysLeft)} at its recent pace.`;
3872
+ }
3873
+ const finishing = runway.inSequence ?? 0;
3874
+ return finishing > 0 ? `Add leads to ${runway.campaignName}: no lead is left to start, and ${plural(finishing, "lead")} ${finishing === 1 ? "is" : "are"} finishing the sequence.` : `Add leads to ${runway.campaignName}: no lead is left to start, so it is not sending to anyone new.`;
3875
+ };
3876
+ var runwayAction = (runways, runwayDays) => {
3877
+ const [first] = runways;
3878
+ if (first === void 0) {
3879
+ return [];
3880
+ }
3881
+ const one = runways.length === 1;
3882
+ const out = runways.filter((runway) => runway.state === "out_of_leads");
3883
+ const draining = runways.filter((runway) => runway.state === "draining");
3884
+ const parts = [
3885
+ ...out.length > 0 ? [
3886
+ `${plural(out.length, "has", "have")} no lead left to start (${named(out.map((runway) => runway.campaignName))})`
3887
+ ] : [],
3888
+ ...draining.length > 0 ? [
3889
+ `${plural(draining.length, "runs", "run")} out within ${plural(runwayDays, "day")} at the recent pace (${named(draining.map((runway) => `${runway.campaignName} in ${startingLeft(runway.daysLeft)}`))})`
3890
+ ] : []
3891
+ ];
3892
+ return [
3893
+ {
3894
+ action: one ? oneRunwayAction(first) : `Add leads to ${runways.length} campaigns: ${parts.join("; ")}.`,
3895
+ campaign: one ? first.campaign : null,
3896
+ campaignName: one ? first.campaignName : null,
3897
+ kind: "add_leads",
3898
+ number: runways.length
3533
3899
  }
3534
- const mix = {
3535
- ...read,
3536
- ...compare(
3537
- channels.map((each) => each.group),
3538
- options.alpha,
3539
- read,
3540
- options.statuses
3541
- ),
3542
- byProvider: providers.map((each) => each.group),
3543
- channels: channels.map((each) => each.group),
3544
- period: { from: options.from, to: options.to }
3545
- };
3546
- return mix;
3900
+ ];
3901
+ };
3902
+ var stalledAction = (stalled, days) => {
3903
+ const [first] = stalled;
3904
+ if (first === void 0) {
3905
+ return [];
3547
3906
  }
3548
- });
3549
-
3550
- // src/insights/ops/client-report.ts
3551
- import { z as z16 } from "zod";
3907
+ const one = stalled.length === 1;
3908
+ return [
3909
+ {
3910
+ action: `Find out why ${one ? first.campaignName : `${stalled.length} campaigns (${named(stalled.map((runway) => runway.campaignName))})`} started no new lead in the last ${plural(days, "day")}, though ${one ? `${plural(first.remaining, "lead")} ${first.remaining === 1 ? "is" : "are"}` : "leads are"} left to start.`,
3911
+ campaign: one ? first.campaign : null,
3912
+ campaignName: one ? first.campaignName : null,
3913
+ kind: "check_stalled",
3914
+ number: stalled.length
3915
+ }
3916
+ ];
3917
+ };
3918
+ var runwayActions = (runways, options) => [
3919
+ ...runwayAction(runways.runningOut, options.runway_days),
3920
+ ...stalledAction(runways.stalled, options.days)
3921
+ ];
3552
3922
 
3553
3923
  // src/insights/ops/period-comparison.ts
3554
- import { z as z14 } from "zod";
3555
- var input11 = z14.object({
3924
+ import { z as z15 } from "zod";
3925
+ var input12 = z15.object({
3556
3926
  ...listFields("two stats requests"),
3557
- alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3558
- days: z14.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
3559
- min_sent: z14.number().int().min(0).default(50).describe(
3927
+ alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3928
+ days: z15.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
3929
+ min_sent: z15.number().int().min(0).default(50).describe(
3560
3930
  "A campaign under this many sends in either period is listed apart"
3561
3931
  )
3562
3932
  });
3933
+ var noteRepliesApart = (context, campaigns, workspace, read) => {
3934
+ if (campaigns.replied === null || workspace.replied === null || campaigns.replied === workspace.replied) {
3935
+ return;
3936
+ }
3937
+ context.note(
3938
+ `This period has ${campaigns.replied} replied across the ${read.campaigns === 1 ? "campaign" : `${read.campaigns} campaigns`} read (${either(read.statuses)}) and ${workspace.replied} in the workspace totals, which count every campaign whatever its state. Both count leads who replied, not reply messages.`
3939
+ );
3940
+ };
3563
3941
  var numbersOf = (counts, rates) => ({
3564
3942
  ...totalsOf(counts),
3565
3943
  bounceRate: rates.bounceRate.rate,
@@ -3603,6 +3981,7 @@ var compare2 = (current, previous, basis, alpha) => {
3603
3981
  current: numbers,
3604
3982
  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
3983
  previous: earlier,
3984
+ rates: { current: current.rates, previous: previous.rates },
3606
3985
  replyRateBasis: basis,
3607
3986
  replyRateTest: test,
3608
3987
  verdict: verdictOf(test)
@@ -3620,8 +3999,8 @@ var comparePeriods = (current, previous, alpha) => {
3620
3999
  var compareAcross = (current, previous, alpha) => {
3621
4000
  const counts = [sumMeasured(current), sumMeasured(previous)];
3622
4001
  const basis = periodBasis(...counts);
3623
- const now = ratesAcross(current, baseIn2(basis));
3624
- const before = ratesAcross(previous, baseIn2(basis));
4002
+ const now = ratesAcross(current, basis);
4003
+ const before = ratesAcross(previous, basis);
3625
4004
  return {
3626
4005
  comparison: compare2(
3627
4006
  { counts: counts[0], rates: now.rates },
@@ -3689,8 +4068,8 @@ var workspaceOf = (context, rows, alpha) => {
3689
4068
  );
3690
4069
  };
3691
4070
  var periodComparison = defineInsight({
3692
- description: "This period against the last: for each campaign, counts and rates for the last `days` complete days and for the `days` before, the change in each, and whether the change in the reply rate is more than chance (a two-proportion test), with the campaigns sorted by the size of that change. Also the same for every campaign added together and, where the adapter has them, for the vendor's workspace totals. Reply and positive reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly review. Campaigns under min_sent sends in either period are listed apart; a null is a count the vendor does not report, and a rate of a total counts only the campaigns that report both its count and what it divides by (a note says when some are left out). Costs two stats requests per campaign plus two for the workspace.",
3693
- inputSchema: input11,
4071
+ description: "This period against the last: for each campaign, counts and rates for the last `days` complete days and for the `days` before, the change in each, and whether the change in the reply rate is more than chance (a two-proportion test), with the campaigns sorted by the size of that change. Also the same for every campaign added together and, where the adapter has them, for the vendor's workspace totals. Reply and positive reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly review. Campaigns under min_sent sends in either period are listed apart; a null is a count the vendor does not report, and a rate of a total counts only the campaigns that report both its count and what it divides by (a note says when some are left out). totalBasis and workspaceBasis say what each counts: the total adds up only the campaigns read, the workspace totals every campaign, and both count leads who replied, not reply messages. On a combined instance a tool with no campaign in statuses is named in toolsLeftOut with its own totals for the period. Costs two stats requests per campaign plus two for the workspace, and one for each tool left out.",
4072
+ inputSchema: input12,
3694
4073
  key: "periodComparison",
3695
4074
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + 2 * price.campaigns(values.max_campaigns) * price.one("stats") + (price.capabilities["stats.workspace"] === false ? 0 : 2 * price.one("stats")),
3696
4075
  scales: "max_campaigns",
@@ -3702,194 +4081,63 @@ var periodComparison = defineInsight({
3702
4081
  const listed2 = await readCampaignsIn(
3703
4082
  context,
3704
4083
  options.statuses,
3705
- options.max_campaigns
3706
- );
3707
- const workspace = await readWorkspace(context, options.days);
3708
- const periods = await readPeriods(context, listed2, options.days);
3709
- const campaigns = [];
3710
- const tooFewSends = [];
3711
- for (const { campaign, current, previous } of periods.campaigns) {
3712
- const sent = [volumeOf(current), volumeOf(previous)];
3713
- if (sent.some((volume2) => (volume2 ?? -1) < options.min_sent)) {
3714
- tooFewSends.push({
3715
- ...labelOf(campaign),
3716
- currentSent: sent[0],
3717
- previousSent: sent[1]
3718
- });
3719
- } else {
3720
- campaigns.push({
3721
- ...labelOf(campaign),
3722
- ...comparePeriods(current, previous, options.alpha)
3723
- });
3724
- }
3725
- }
3726
- const comparison = {
3727
- ...periods.read,
3728
- campaigns: campaigns.toSorted(
3729
- (left, right) => descending(
3730
- left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
3731
- right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
3732
- ) || left.campaignName.localeCompare(right.campaignName)
3733
- ),
3734
- current: periods.current,
3735
- days: options.days,
3736
- previous: periods.previous,
3737
- tooFewSends,
3738
- total: noted(
3739
- context,
3740
- "Every campaign added together",
3741
- totalOf(periods.campaigns, options.alpha)
3742
- ),
3743
- workspace: workspaceOf(context, workspace, options.alpha)
3744
- };
3745
- return comparison;
3746
- }
3747
- });
3748
-
3749
- // src/insights/ops/pipeline-forecast.ts
3750
- import { z as z15 } from "zod";
3751
- var input12 = z15.object({
3752
- campaign: z15.string().min(3).describe("The campaign's ref or name"),
3753
- days: z15.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3754
- max_leads: z15.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3755
- });
3756
- var countStatuses = (leads) => {
3757
- const counts = {
3758
- active: 0,
3759
- bounced: 0,
3760
- completed: 0,
3761
- paused: 0,
3762
- replied: 0,
3763
- skipped: 0,
3764
- unknown: 0,
3765
- unsubscribed: 0
3766
- };
3767
- for (const lead of leads) {
3768
- counts[lead.status] += 1;
3769
- }
3770
- return counts;
3771
- };
3772
- var times = (leads, share2) => share2 === null ? null : round(leads * share2);
3773
- var project = (leads, measured2) => ({
3774
- expected: times(leads, measured2.rate),
3775
- high: times(leads, measured2.high),
3776
- low: times(leads, measured2.low)
3777
- });
3778
- var paceOf = async (context, campaign, days) => {
3779
- if (context.outbound.capabilities["stats.byDay"] === false) {
3780
- context.note(
3781
- "Days of sending left were not estimated: the adapter has no stats by day."
3782
- );
3783
- return null;
3784
- }
3785
- const series = await readDaily(
3786
- context,
3787
- campaign,
3788
- paceWindow(context.now, days)
3789
- );
3790
- return newLeadsPerDay(
3791
- series.map((day) => day.counts),
3792
- days
3793
- );
3794
- };
3795
- var ASSUMPTIONS = [
3796
- "Every remaining lead is contacted.",
3797
- "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
3798
- "The daily pace of new leads started stays what it was over the recent days. Days with no report count as none started."
3799
- ];
3800
- var describe2 = ({ complete, daysLeft, inSequence, remaining }, forecast) => {
3801
- if (daysLeft === 0) {
3802
- return remaining === 0 ? "No leads are left to contact; add leads to keep the campaign sending." : `No new leads are left to start; ${plural(inSequence ?? remaining, "lead")} ${noun(inSequence ?? remaining, "is", "are")} finishing the sequence. Add leads to keep the campaign starting new ones.`;
3803
- }
3804
- const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
3805
- if (forecast.expected === null) {
3806
- return `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.`;
3807
- }
3808
- const [expected, low, high] = [
3809
- forecast.expected,
3810
- forecast.low,
3811
- forecast.high
3812
- ].map((value) => spoken(value));
3813
- const range = low === high ? "" : ` (between ${low} and ${high})`;
3814
- return `${leads}; expect about ${expected} ${noun(Number(expected), "reply", "replies")}${range}. This is an estimate.`;
3815
- };
3816
- var ownerOf = (context, campaign) => context.outbound.provider === "combined" ? context.outbound.workspace(`${campaign.provider}:${campaign.workspaceId}`) : context.outbound;
3817
- var runwayOf = async (context, campaign, options) => {
3818
- const owner = ownerOf(context, campaign);
3819
- const status = options.activeOnly === true && owner.capabilities["leads.byStatus"] ? "active" : void 0;
3820
- const { capped: capped2, items: leads } = await readCapped(
3821
- context,
3822
- (max) => owner.campaign(campaign.ref).leads.listAll({ max, status }),
3823
- {
3824
- input: options.leadsInput,
3825
- max: options.maxLeads,
3826
- what: options.leadsWhat
3827
- }
3828
- );
3829
- const complete = !capped2;
3830
- const byStatus = countStatuses(leads);
3831
- const split = splitActive(leads);
3832
- const pace = await paceOf(context, campaign.ref, options.days);
3833
- return {
3834
- byStatus,
3835
- complete,
3836
- daysLeft: runwayDays(split, byStatus, complete, pace),
3837
- leadsRead: leads.length,
3838
- pace,
3839
- remaining: byStatus.active,
3840
- split
3841
- };
3842
- };
3843
- var forecastCampaign = async (context, campaign, options) => {
3844
- const { byStatus, complete, daysLeft, leadsRead, pace, remaining, split } = await runwayOf(context, campaign, options);
3845
- const rates = ratesOf(
3846
- await readTotals(context, campaign.ref, { from: null, to: null })
3847
- );
3848
- const expectedReplies = project(remaining, rates.replyRate);
3849
- return {
3850
- ...labelOf(campaign),
3851
- assumptions: [
3852
- ...ASSUMPTIONS,
3853
- `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count === null ? "an unknown number of replies" : plural(rates.replyRate.count, "reply", "replies")} over ${rates.replyRate.of ?? "unknown"}.`
3854
- ],
3855
- byStatus,
3856
- dailyContactRate: pace,
3857
- daysLeft,
3858
- estimate: true,
3859
- expectedPositive: project(remaining, rates.positiveRate),
3860
- expectedReplies,
3861
- finding: describe2(
3862
- { complete, daysLeft, inSequence: split.inSequence, remaining },
3863
- expectedReplies
3864
- ),
3865
- inSequence: split.inSequence,
3866
- leadsComplete: complete,
3867
- leadsRead,
3868
- notStarted: split.notStarted,
3869
- positiveRate: rates.positiveRate,
3870
- remaining,
3871
- replyRate: rates.replyRate
3872
- };
3873
- };
3874
- var pipelineForecast = defineInsight({
3875
- description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, split into those not yet started and those partway through the sequence, the days until no lead is left to start at the recent pace of new leads started per day (the same figure lead_runway gives), and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
3876
- inputSchema: input12,
3877
- key: "pipelineForecast",
3878
- cost: (values, price) => price.one("campaigns.get") + price.list("leads.list", values.max_leads) + price.one("stats") + (price.capabilities["stats.byDay"] === false ? 0 : price.one("stats")),
3879
- scales: "max_leads",
3880
- name: "pipeline_forecast",
3881
- needs: ["leads.byCampaign", "stats.campaign"],
3882
- next: "Use client_report to see every campaign that is running out of leads.",
3883
- run: async (context, options) => {
3884
- const campaign = context.one(
3885
- await context.outbound.campaigns.get(options.campaign)
4084
+ options.max_campaigns
3886
4085
  );
3887
- return await forecastCampaign(context, campaign, {
4086
+ const workspace = await readWorkspace(context, options.days);
4087
+ const periods = await readPeriods(context, listed2, options.days);
4088
+ const leftOut = await toolsLeftOut(
4089
+ context,
4090
+ listed2.skipped,
4091
+ periods.current
4092
+ );
4093
+ const campaigns = [];
4094
+ const tooFewSends = [];
4095
+ for (const { campaign, current, previous } of periods.campaigns) {
4096
+ const sent = [volumeOf(current), volumeOf(previous)];
4097
+ if (sent.some((volume2) => (volume2 ?? -1) < options.min_sent)) {
4098
+ tooFewSends.push({
4099
+ ...labelOf(campaign),
4100
+ currentSent: sent[0],
4101
+ previousSent: sent[1]
4102
+ });
4103
+ } else {
4104
+ campaigns.push({
4105
+ ...labelOf(campaign),
4106
+ ...comparePeriods(current, previous, options.alpha)
4107
+ });
4108
+ }
4109
+ }
4110
+ const total2 = noted(
4111
+ context,
4112
+ "Every campaign added together",
4113
+ totalOf(periods.campaigns, options.alpha)
4114
+ );
4115
+ const workspaceTotals = workspaceOf(context, workspace, options.alpha);
4116
+ if (workspaceTotals !== null) {
4117
+ noteRepliesApart(context, total2.current, workspaceTotals.current, {
4118
+ campaigns: periods.campaigns.length,
4119
+ statuses: options.statuses
4120
+ });
4121
+ }
4122
+ const comparison = {
4123
+ ...periods.read,
4124
+ campaigns: campaigns.toSorted(
4125
+ (left, right) => descending(
4126
+ left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
4127
+ right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
4128
+ ) || left.campaignName.localeCompare(right.campaignName)
4129
+ ),
4130
+ current: periods.current,
3888
4131
  days: options.days,
3889
- leadsInput: "max_leads",
3890
- leadsWhat: "leads",
3891
- maxLeads: options.max_leads
3892
- });
4132
+ previous: periods.previous,
4133
+ tooFewSends,
4134
+ toolsLeftOut: leftOut,
4135
+ total: total2,
4136
+ totalBasis: campaignsBasis(periods.campaigns.length, options.statuses),
4137
+ workspace: workspaceTotals,
4138
+ workspaceBasis: workspaceTotals === null ? null : WORKSPACE_BASIS
4139
+ };
4140
+ return comparison;
3893
4141
  }
3894
4142
  });
3895
4143
 
@@ -3909,17 +4157,16 @@ var input13 = z16.object({
3909
4157
  ),
3910
4158
  min_baseline_points: z16.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
3911
4159
  min_sent: z16.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
4160
+ provider: z16.string().min(1).optional().describe(
4161
+ "Read only one tool of a combined instance: its provider (instantly) or provider:workspace. Leave out for every tool."
4162
+ ),
3912
4163
  runway_days: z16.number().min(0).default(7).describe(
3913
4164
  "A campaign with this many days of leads left or fewer is flagged"
4165
+ ),
4166
+ tag: z16.string().min(1).optional().describe(
4167
+ "Read only the campaigns with this tag, for example one client's. Unusual days are then left out, since they are workspace-wide."
3914
4168
  )
3915
4169
  });
3916
- var sendingLeft = (daysLeft) => {
3917
- if (daysLeft !== null && daysLeft < 0.05) {
3918
- return "less than a day of sending";
3919
- }
3920
- const days = spoken(daysLeft);
3921
- return `about ${days} ${days === "1" ? "day" : "days"} of sending`;
3922
- };
3923
4170
  var bounceProblems = (campaigns, options) => campaigns.flatMap(({ campaign, current }) => {
3924
4171
  const { count: count2, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
3925
4172
  return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [
@@ -3954,52 +4201,7 @@ var readAnomalies = async (context, period, options) => {
3954
4201
  }).anomalies
3955
4202
  ];
3956
4203
  };
3957
- var NAMED = 10;
3958
- var readRunways = async (context, campaigns, options) => {
3959
- const { capabilities } = context.outbound;
3960
- if (!capabilities["leads.byCampaign"] || capabilities["stats.byDay"] === false) {
3961
- return null;
3962
- }
3963
- const active = campaigns.flatMap(
3964
- ({ campaign }) => campaign.status === "active" ? [campaign] : []
3965
- );
3966
- const forecasts = await context.each(
3967
- active,
3968
- async (campaign) => ({
3969
- campaign,
3970
- forecast: await runwayOf(context, campaign, {
3971
- activeOnly: true,
3972
- days: options.days,
3973
- leadsInput: "max_leads_per_campaign",
3974
- leadsWhat: "leads of a campaign",
3975
- maxLeads: options.max_leads_per_campaign
3976
- })
3977
- }),
3978
- "active campaigns' leads"
3979
- );
3980
- const uncounted = forecasts.flatMap(
3981
- ({ campaign, forecast }) => forecast.complete ? [] : [campaign.name]
3982
- );
3983
- if (uncounted.length > 0) {
3984
- const named4 = uncounted.slice(0, NAMED);
3985
- const rest = uncounted.length - named4.length;
3986
- context.note(
3987
- `The leads left were not fully counted for ${plural(uncounted.length, "active campaign")}, so runningOutOfLeads leaves ${uncounted.length === 1 ? "it" : "them"} out: ${named4.join(", ")}${rest > 0 ? ` and ${rest} more` : ""}. Raise max_leads_per_campaign to count them.`
3988
- );
3989
- }
3990
- const runways = forecasts.flatMap(
3991
- ({ campaign, forecast }) => forecast.complete && forecast.daysLeft !== null && forecast.daysLeft <= options.runway_days ? [
3992
- {
3993
- ...labelOf(campaign),
3994
- dailyContactRate: forecast.pace,
3995
- daysLeft: forecast.daysLeft,
3996
- remaining: forecast.remaining
3997
- }
3998
- ] : []
3999
- );
4000
- return runways.toSorted((left, right) => left.daysLeft - right.daysLeft);
4001
- };
4002
- var actionsOf = (report) => {
4204
+ var actionsOf = (report, options) => {
4003
4205
  const [worst] = report.bottom;
4004
4206
  const { current, previous, replyRateBasis } = report.totals;
4005
4207
  const perWhat = RATE_WORDS[replyRateBasis].toLowerCase();
@@ -4011,13 +4213,6 @@ var actionsOf = (report) => {
4011
4213
  kind: "fix_bounces",
4012
4214
  number: problem.rate
4013
4215
  })),
4014
- ...(report.runningOutOfLeads ?? []).map((runway) => ({
4015
- action: runway.remaining === 0 ? `Add leads to ${runway.campaignName}: no leads are left to contact, so it is not sending.` : `Add leads to ${runway.campaignName}: ${runway.remaining} ${runway.remaining === 1 ? "lead remains" : "leads remain"}, ${sendingLeft(runway.daysLeft)}.`,
4016
- campaign: runway.campaign,
4017
- campaignName: runway.campaignName,
4018
- kind: "add_leads",
4019
- number: runway.daysLeft
4020
- })),
4021
4216
  ...report.totals.verdict === "down" ? [
4022
4217
  {
4023
4218
  action: `Find out what changed: ${perWhat} fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
@@ -4042,11 +4237,48 @@ var actionsOf = (report) => {
4042
4237
  campaignName: null,
4043
4238
  kind: "check_anomaly",
4044
4239
  number: anomaly.value
4045
- }))
4240
+ })),
4241
+ ...runwayActions(
4242
+ {
4243
+ runningOut: report.runningOutOfLeads ?? [],
4244
+ stalled: report.stalled ?? []
4245
+ },
4246
+ options
4247
+ )
4046
4248
  ];
4047
4249
  };
4250
+ var scopedTo = async (context, provider) => {
4251
+ if (provider === void 0) {
4252
+ return context;
4253
+ }
4254
+ const { outbound } = context;
4255
+ if (outbound.provider !== "combined") {
4256
+ if (provider === outbound.provider || provider === `${outbound.provider}:${outbound.workspaceId}`) {
4257
+ return context;
4258
+ }
4259
+ throw new OutboundError(
4260
+ "Invalid",
4261
+ `client_report: provider ${provider} is not this instance's tool, ${outbound.provider}:${outbound.workspaceId}`,
4262
+ { provider: outbound.provider }
4263
+ );
4264
+ }
4265
+ const { items } = await outbound.workspaces.list();
4266
+ const labels = items.map((tool) => `${tool.provider}:${tool.workspaceId}`);
4267
+ const matches = labels.filter(
4268
+ (label) => label === provider || label.startsWith(`${provider}:`)
4269
+ );
4270
+ const [only] = matches;
4271
+ if (only === void 0 || matches.length > 1) {
4272
+ throw new OutboundError(
4273
+ "Invalid",
4274
+ `client_report: provider ${provider} ${only === void 0 ? "names no tool" : "names more than one tool"} of this instance. Pass one of ${either(labels)}.`,
4275
+ { provider: outbound.provider }
4276
+ );
4277
+ }
4278
+ return { ...context, outbound: outbound.workspace(only) };
4279
+ };
4048
4280
  var clientReport = defineInsight({
4049
- description: "One report for one client or workspace over the last `days` complete days: totals and the change from the period before, the best and worst campaigns by the low end of the interval of the reply rate, campaigns with a bounce problem, unusual days, active campaigns running out of leads, and a short list of action items in plain language, each naming the campaign and the number behind it. Reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly client update. A section the adapter cannot serve is null and named in `leftOut`, and a null count is one the vendor does not report. Costs two stats requests per campaign, one for the workspace, and for each active campaign one more plus its pages of leads, its active leads only where the tool lists them alone (leads.byStatus). On Instantly a stats read is 2 requests, since it also reads the campaign's tracking settings, so each active campaign costs about 7.",
4281
+ description: "One report for one client or workspace over the last `days` complete days: totals and the change from the period before, the best and worst campaigns by the low end of the interval of the reply rate, campaigns with a bounce problem, unusual days, active campaigns running out of leads (none left to start, or running out within runway_days at the recent pace of new leads started) and, apart, stalled ones (leads left to start but none started in the period), and a short list of action items in plain language, each naming the campaign and the number behind it, with the campaigns that need leads in one item at the end. `remaining` counts leads not yet started; leads partway through the sequence are `inSequence`. Pass provider to read one tool of a combined instance, and tag for one client's campaigns. totalsBasis says what the totals count, and on a combined instance a tool with no campaign in statuses is named in toolsLeftOut with its own totals for the period, one stats request each. Reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly client update. A section the adapter cannot serve is null and named in `leftOut`, and a null count is one the vendor does not report. Costs two stats requests per campaign, one for the workspace, and for each active campaign one more plus its pages of leads, its active leads only where the tool lists them alone (leads.byStatus). On Instantly a stats read is 2 requests, since it also reads the campaign's tracking settings, so each active campaign costs about 7.",
4050
4282
  inputSchema: input13,
4051
4283
  key: "clientReport",
4052
4284
  cost: (values, price) => {
@@ -4060,18 +4292,38 @@ var clientReport = defineInsight({
4060
4292
  needs: ["stats.campaign"],
4061
4293
  partialOnCap: true,
4062
4294
  next: "Use campaign_diagnosis on a campaign an action item names, with from and to set to this report's `period`, or period_comparison for every campaign's change.",
4063
- run: async (context, options) => {
4295
+ run: async (given, options) => {
4296
+ const context = await scopedTo(given, options.provider);
4297
+ const { tag } = options;
4298
+ if (tag !== void 0 && context.outbound.fields.campaign["tags"] === false) {
4299
+ throw new OutboundError(
4300
+ "Unsupported",
4301
+ `client_report: the ${context.outbound.provider} adapter reports no campaign tags, so tag cannot be used`,
4302
+ { provider: context.outbound.provider }
4303
+ );
4304
+ }
4064
4305
  const listed2 = await readCampaignsIn(
4065
4306
  context,
4066
4307
  options.statuses,
4067
4308
  options.max_campaigns
4068
4309
  );
4069
- const anomalies2 = await readAnomalies(
4310
+ const items = tag === void 0 ? listed2.items : listed2.items.filter((campaign) => campaign.tags.includes(tag));
4311
+ if (tag !== void 0 && items.length === 0 && listed2.items.length > 0) {
4312
+ context.note(
4313
+ `None of the ${plural(listed2.items.length, "campaign")} read carries the tag ${tag}, so the report covers no campaign.`
4314
+ );
4315
+ }
4316
+ const anomalies2 = tag === void 0 ? await readAnomalies(
4070
4317
  context,
4071
4318
  lastDays(context.now, options.days),
4072
4319
  options
4320
+ ) : null;
4321
+ const periods = await readPeriods(
4322
+ context,
4323
+ { ...listed2, items },
4324
+ options.days
4073
4325
  );
4074
- const periods = await readPeriods(context, listed2, options.days);
4326
+ const left = await toolsLeftOut(context, listed2.skipped, periods.current);
4075
4327
  const totals = noted(
4076
4328
  context,
4077
4329
  "Totals",
@@ -4086,16 +4338,20 @@ var clientReport = defineInsight({
4086
4338
  options.min_sent,
4087
4339
  totals.replyRateBasis
4088
4340
  );
4341
+ const runways = await readRunways(context, periods.campaigns, options);
4089
4342
  const sections = {
4090
4343
  anomalies: anomalies2,
4091
4344
  bottom: ranking.ranked.slice(options.limit).slice(-options.limit).toReversed(),
4092
4345
  bounceProblems: bounceProblems(periods.campaigns, options),
4093
- runningOutOfLeads: await readRunways(context, periods.campaigns, options),
4346
+ runningOutOfLeads: runways?.runningOut ?? null,
4347
+ stalled: runways?.stalled ?? null,
4094
4348
  totals
4095
4349
  };
4096
4350
  const leftOut = [
4097
- ...sections.anomalies === null ? ["Unusual days: the adapter has no workspace stats by day."] : [],
4098
- ...sections.runningOutOfLeads === null ? [
4351
+ ...sections.anomalies === null ? [
4352
+ tag === void 0 ? "Unusual days: the adapter has no workspace stats by day." : "Unusual days: they are workspace-wide, so a tag leaves them out."
4353
+ ] : [],
4354
+ ...runways === null ? [
4099
4355
  "Campaigns running out of leads: the adapter cannot list a campaign's leads or has no stats by day."
4100
4356
  ] : []
4101
4357
  ];
@@ -4105,14 +4361,16 @@ var clientReport = defineInsight({
4105
4361
  const report = {
4106
4362
  ...sections,
4107
4363
  ...periods.read,
4108
- actions: actionsOf(sections),
4364
+ actions: actionsOf(sections, options),
4109
4365
  campaigns: periods.campaigns.length,
4110
4366
  days: options.days,
4111
4367
  leftOut,
4112
4368
  period: periods.current,
4113
4369
  previousPeriod: periods.previous,
4114
4370
  replyRateBasis: totals.replyRateBasis,
4115
- top: ranking.ranked.slice(0, options.limit)
4371
+ toolsLeftOut: left,
4372
+ top: ranking.ranked.slice(0, options.limit),
4373
+ totalsBasis: campaignsBasis(periods.campaigns.length, options.statuses)
4116
4374
  };
4117
4375
  return report;
4118
4376
  }
@@ -4125,9 +4383,9 @@ var input14 = z17.object({
4125
4383
  ...listFields("one stats request"),
4126
4384
  min_sent: z17.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
4127
4385
  });
4128
- var groupOf2 = (tag, entries) => {
4386
+ var groupOf2 = (tag, entries, basis) => {
4129
4387
  const counts = entries.map((entry) => entry.counts);
4130
- const { partial, rates } = ratesAcross(counts);
4388
+ const { partial, rates } = ratesAcross(counts, basis);
4131
4389
  return {
4132
4390
  group: {
4133
4391
  ...totalsOf(sumMeasured(counts)),
@@ -4138,9 +4396,9 @@ var groupOf2 = (tag, entries) => {
4138
4396
  partial
4139
4397
  };
4140
4398
  };
4141
- var named = (group) => group.tag ?? "";
4399
+ var named2 = (group) => group.tag ?? "";
4142
4400
  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).",
4401
+ 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
4402
  inputSchema: input14,
4145
4403
  key: "tagRollup",
4146
4404
  // A tool whose campaigns carry no tags would put every campaign under one
@@ -4161,7 +4419,10 @@ var tagRollup = defineInsight({
4161
4419
  members.set(tag, [...members.get(tag) ?? [], entry]);
4162
4420
  }
4163
4421
  }
4164
- const grouped = [...members].map(([tag, group]) => groupOf2(tag, group));
4422
+ const basis = replyBasisAcross(entries.map((entry) => entry.counts));
4423
+ const grouped = [...members].map(
4424
+ ([tag, group]) => groupOf2(tag, group, basis)
4425
+ );
4165
4426
  for (const { group, partial } of grouped) {
4166
4427
  if (partial.length > 0) {
4167
4428
  context.note(
@@ -4173,13 +4434,14 @@ var tagRollup = defineInsight({
4173
4434
  }
4174
4435
  }
4175
4436
  const groups = grouped.map((each) => each.group).toSorted(
4176
- (left, right) => descending(left.replyRate.low, right.replyRate.low) || named(left).localeCompare(named(right))
4437
+ (left, right) => descending(left.replyRate.low, right.replyRate.low) || named2(left).localeCompare(named2(right))
4177
4438
  );
4178
4439
  const enough2 = (group) => (volumeOf(group) ?? 0) >= options.min_sent;
4179
4440
  const rollup = {
4180
4441
  ...read,
4181
4442
  campaigns: entries.length,
4182
4443
  period: { from: options.from, to: options.to },
4444
+ replyRateBasis: basis,
4183
4445
  tags: groups.filter(enough2),
4184
4446
  tooFewSends: groups.filter((group) => !enough2(group))
4185
4447
  };
@@ -4442,9 +4704,149 @@ var accountSummary = defineInsight({
4442
4704
  // src/insights/people/dropped-replies.ts
4443
4705
  import { z as z19 } from "zod";
4444
4706
 
4445
- // src/insights/people/dropped-replies-check.ts
4707
+ // src/insights/people/thread-context.ts
4446
4708
  var HOUR = 36e5;
4447
4709
  var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
4710
+ var recordsMeetings = (outbound) => outbound.fields.lead?.meeting !== false;
4711
+ var timeOf2 = (message) => message.sentAt === null ? Number.NaN : Date.parse(message.sentAt);
4712
+ var lastAt = (messages, direction) => messages.findLast((message) => message.direction === direction)?.sentAt ?? null;
4713
+ var withoutBody = ({
4714
+ bodyHtml: _html,
4715
+ bodyText: _text,
4716
+ ...rest
4717
+ }) => rest;
4718
+ var activityOf = (messages) => {
4719
+ const timed = (messages ?? []).filter((message) => !Number.isNaN(timeOf2(message))).toSorted((left, right) => timeOf2(left) - timeOf2(right));
4720
+ const newest = timed.at(-1);
4721
+ return {
4722
+ lastInboundAt: lastAt(timed, "in"),
4723
+ lastOutboundAt: lastAt(timed, "out"),
4724
+ latest: newest === void 0 ? null : withoutBody(newest),
4725
+ messagesRead: messages?.length ?? 0
4726
+ };
4727
+ };
4728
+ var MEETING_WORDS = {
4729
+ booked: "booked",
4730
+ completed: "held",
4731
+ no_show: "missed (no-show)",
4732
+ won: "won"
4733
+ };
4734
+ var shown = (at) => at === null ? "at an unknown time" : `${at.slice(0, 10)} ${at.slice(11, 16)} UTC`;
4735
+ var hoursSince = (at, now) => Math.max(0, now - Date.parse(at)) / HOUR;
4736
+ var latestSentence = (latest2, now) => {
4737
+ const ago = waited(hoursSince(latest2.sentAt ?? "", now));
4738
+ if (latest2.direction === "out") {
4739
+ return `The latest message is outbound, sent ${ago} ago (${shown(latest2.sentAt)}).`;
4740
+ }
4741
+ 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)}).`;
4742
+ };
4743
+ var labelSentence = (labelled, latest2) => {
4744
+ if (labelled === null || labelled === void 0 || labelled.ref === latest2.ref || labelled.sentAt === null || latest2.sentAt === null) {
4745
+ return [];
4746
+ }
4747
+ const gap = waited(
4748
+ Math.max(0, Date.parse(latest2.sentAt) - Date.parse(labelled.sentAt)) / HOUR
4749
+ );
4750
+ return [
4751
+ `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.`
4752
+ ];
4753
+ };
4754
+ var meetingFacts = (facts) => {
4755
+ const { lead, provider } = facts;
4756
+ if (!facts.meetingsRecorded) {
4757
+ return {
4758
+ evidence: [],
4759
+ unchecked: [
4760
+ `Whether a meeting was booked: ${provider} records no meeting status on a lead.`
4761
+ ]
4762
+ };
4763
+ }
4764
+ if (lead === null) {
4765
+ return {
4766
+ evidence: [],
4767
+ unchecked: ["Whether a meeting was booked: the lead was not read."]
4768
+ };
4769
+ }
4770
+ const meeting = lead.meeting ?? null;
4771
+ return {
4772
+ evidence: [
4773
+ meeting === null ? `${provider} records no meeting for the lead.` : `${provider} records the lead's meeting as ${MEETING_WORDS[meeting]}.`
4774
+ ],
4775
+ unchecked: []
4776
+ };
4777
+ };
4778
+ var tagsUnchecked = (lead) => lead === null || lead.tags.length === 0 ? [] : [
4779
+ `The lead's tags (${lead.tags.join(", ")}) were not interpreted; a tag can record a meeting or a decision the rules do not read.`
4780
+ ];
4781
+ 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.";
4782
+ var decide = (latest2, booked) => {
4783
+ if (booked) {
4784
+ return { basis: "meeting", needed: false };
4785
+ }
4786
+ if (latest2.direction === "out") {
4787
+ return { basis: "answered", needed: false };
4788
+ }
4789
+ return latest2.isAuto === true ? { basis: "automatic", needed: null } : { basis: "inbound_unanswered", needed: true };
4790
+ };
4791
+ var meetingRecorded = (lead) => {
4792
+ const meeting = lead?.meeting ?? null;
4793
+ return meeting !== null && meeting !== "no_show";
4794
+ };
4795
+ var assessFollowUp = (facts, activity) => {
4796
+ const meeting = meetingFacts(facts);
4797
+ const tags = tagsUnchecked(facts.lead);
4798
+ const booked = meetingRecorded(facts.lead);
4799
+ if (facts.messages === null) {
4800
+ return {
4801
+ basis: booked ? "meeting" : "not_read",
4802
+ evidence: meeting.evidence,
4803
+ needed: booked ? false : null,
4804
+ unchecked: [
4805
+ `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.`,
4806
+ ...meeting.unchecked,
4807
+ ...tags
4808
+ ]
4809
+ };
4810
+ }
4811
+ const { latest: latest2 } = activity;
4812
+ if (latest2 === null) {
4813
+ return {
4814
+ basis: booked ? "meeting" : "no_messages",
4815
+ evidence: meeting.evidence,
4816
+ needed: booked ? false : null,
4817
+ unchecked: [
4818
+ "Who wrote last: the conversation read holds no message with a time.",
4819
+ ...meeting.unchecked,
4820
+ ...tags
4821
+ ]
4822
+ };
4823
+ }
4824
+ return {
4825
+ ...decide(latest2, booked),
4826
+ evidence: [
4827
+ latestSentence(latest2, facts.now),
4828
+ ...labelSentence(facts.labelled, latest2),
4829
+ ...meeting.evidence
4830
+ ],
4831
+ unchecked: [READ_IT, ...meeting.unchecked, ...tags]
4832
+ };
4833
+ };
4834
+ var threadContext = (facts) => {
4835
+ const activity = activityOf(facts.messages);
4836
+ return {
4837
+ activity,
4838
+ followUp: assessFollowUp(facts, activity),
4839
+ meeting: facts.lead?.meeting ?? null,
4840
+ vendorSentiment: {
4841
+ leadCategory: facts.lead?.interestCategory ?? null,
4842
+ leadLabel: facts.lead?.interest ?? null,
4843
+ replyCategory: facts.labelled?.category ?? null
4844
+ }
4845
+ };
4846
+ };
4847
+
4848
+ // src/insights/people/dropped-replies-check.ts
4849
+ var HOUR2 = 36e5;
4448
4850
  var unanswered = (replies2, messages) => {
4449
4851
  const lastSent = Math.max(
4450
4852
  Number.NEGATIVE_INFINITY,
@@ -4458,12 +4860,12 @@ var unanswered = (replies2, messages) => {
4458
4860
  (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "")
4459
4861
  );
4460
4862
  };
4461
- var toDropped = (open, by, now) => {
4863
+ var toDropped = (open, by, now, messages) => {
4462
4864
  const [first] = open;
4463
4865
  if (first === void 0 || first.sentAt === null) {
4464
4866
  return [];
4465
4867
  }
4466
- const hoursWaiting = round((now - Date.parse(first.sentAt)) / HOUR) ?? 0;
4868
+ const hoursWaiting = round((now - Date.parse(first.sentAt)) / HOUR2) ?? 0;
4467
4869
  return [
4468
4870
  {
4469
4871
  campaign: first.campaignRef,
@@ -4474,8 +4876,14 @@ var toDropped = (open, by, now) => {
4474
4876
  finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${waited(hoursWaiting)} with nothing sent after it.`,
4475
4877
  hoursWaiting,
4476
4878
  email: null,
4879
+ labelled: {
4880
+ category: first.category,
4881
+ ref: first.ref,
4882
+ sentAt: first.sentAt
4883
+ },
4477
4884
  lead: first.leadRef,
4478
4885
  linkedinUrl: null,
4886
+ messages,
4479
4887
  name: null,
4480
4888
  provider: first.provider,
4481
4889
  receivedAt: first.sentAt,
@@ -4491,7 +4899,14 @@ var sentByHand = async (context, since, max) => {
4491
4899
  return null;
4492
4900
  }
4493
4901
  const walk = messages.listAll({ byHand: true, max, since });
4494
- const found = await walk.toArray();
4902
+ const [found] = await context.each(
4903
+ [walk],
4904
+ async (each) => await each.toArray(),
4905
+ "listings of the messages sent by hand"
4906
+ );
4907
+ if (found === void 0) {
4908
+ return null;
4909
+ }
4495
4910
  if (walk.meta !== void 0) {
4496
4911
  context.one({ meta: walk.meta });
4497
4912
  }
@@ -4505,9 +4920,30 @@ var sentByHand = async (context, since, max) => {
4505
4920
  var answersIn = (conversation, sent) => sent.filter(
4506
4921
  (message) => conversation.by === "thread" ? message.threadId === conversation.id : message.leadRef === conversation.id
4507
4922
  );
4508
- var check = async (context, checkable, sent, olderThanHours) => {
4923
+ var readFully = async (context, conversations) => await context.each(
4924
+ conversations,
4925
+ async (conversation) => {
4926
+ try {
4927
+ const read = await (conversation.by === "thread" ? context.outbound.thread(conversation.id).messages() : context.outbound.lead(conversation.id).timeline());
4928
+ return { conversation, failed: null, messages: context.page(read) };
4929
+ } catch (error) {
4930
+ if (isCapStop(error)) {
4931
+ throw error;
4932
+ }
4933
+ return {
4934
+ conversation,
4935
+ failed: OutboundError.is(error) ? error.code : "an unexpected error",
4936
+ messages: []
4937
+ };
4938
+ }
4939
+ },
4940
+ "conversations"
4941
+ );
4942
+ var check = async (context, checkable, sent, olderThanHours, includeAuto) => {
4509
4943
  const checked = {
4510
4944
  answered: 0,
4945
+ automatic: 0,
4946
+ automaticReplies: 0,
4511
4947
  dropped: [],
4512
4948
  tooRecent: 0,
4513
4949
  unread: 0
@@ -4515,13 +4951,17 @@ var check = async (context, checkable, sent, olderThanHours) => {
4515
4951
  const openIn = (conversation, messages) => toDropped(
4516
4952
  unanswered(conversation.replies, messages),
4517
4953
  conversation.by,
4518
- context.now
4954
+ context.now,
4955
+ messages
4519
4956
  );
4520
- const settle = (found, whole) => {
4957
+ const settle = (found, whole, automaticReplies = 0) => {
4521
4958
  if (found.length === 0) {
4522
4959
  checked.answered += 1;
4523
4960
  } else if (found.every((each) => each.hoursWaiting < olderThanHours)) {
4524
4961
  checked.tooRecent += 1;
4962
+ } else if (automaticReplies > 0) {
4963
+ checked.automatic += 1;
4964
+ checked.automaticReplies += automaticReplies;
4525
4965
  } else if (whole) {
4526
4966
  checked.dropped.push(...found);
4527
4967
  } else {
@@ -4536,30 +4976,31 @@ var check = async (context, checkable, sent, olderThanHours) => {
4536
4976
  );
4537
4977
  return !((found.length === 0 || sent.whole) && settle(found, false));
4538
4978
  });
4539
- const threads = await mapConcurrent(toRead, async (conversation) => {
4540
- try {
4541
- const read = await (conversation.by === "thread" ? context.outbound.thread(conversation.id).messages() : context.outbound.lead(conversation.id).timeline());
4542
- return { conversation, failed: null, messages: context.page(read) };
4543
- } catch (error) {
4544
- if (isCapStop(error)) {
4545
- throw error;
4546
- }
4547
- return {
4548
- conversation,
4549
- failed: OutboundError.is(error) ? error.code : "an unexpected error",
4550
- messages: []
4551
- };
4552
- }
4553
- });
4554
- const reasons = /* @__PURE__ */ new Set();
4979
+ const threads = await readFully(context, toRead);
4980
+ const stopped2 = toRead.length - threads.length;
4981
+ const reasons = new Set(
4982
+ stopped2 > 0 ? ["the request cap stopped the read"] : []
4983
+ );
4984
+ checked.unread += stopped2;
4555
4985
  for (const { conversation, failed, messages } of threads) {
4556
4986
  if (failed === null) {
4557
- settle(openIn(conversation, messages), true);
4987
+ const { latest: latest2 } = activityOf(messages);
4988
+ const endsAutomatic = !includeAuto && latest2?.direction === "in" && latest2.isAuto === true;
4989
+ settle(
4990
+ openIn(conversation, messages),
4991
+ true,
4992
+ endsAutomatic ? conversation.replies.length : 0
4993
+ );
4558
4994
  } else {
4559
4995
  checked.unread += 1;
4560
4996
  reasons.add(failed);
4561
4997
  }
4562
4998
  }
4999
+ if (checked.automatic > 0) {
5000
+ context.note(
5001
+ `${plural(checked.automatic, "conversation")} ended in an automatic reply once read in full (such as one within a minute of the email it answers), so ${noun(checked.automatic, "its", "their")} ${plural(checked.automaticReplies, "reply", "replies")} ${noun(checked.automaticReplies, "is", "are")} counted in totals.skippedAuto, not as dropped. Pass include_auto: true to list them.`
5002
+ );
5003
+ }
4563
5004
  if (checked.unread > 0) {
4564
5005
  context.note(
4565
5006
  `${plural(checked.unread, "conversation")} could not be read, so ${noun(checked.unread, "it is", "they are")} counted in totals.unchecked, not as dropped (${[...reasons].join("; ")}).`
@@ -4569,7 +5010,7 @@ var check = async (context, checkable, sent, olderThanHours) => {
4569
5010
  };
4570
5011
 
4571
5012
  // src/insights/people/dropped-replies.ts
4572
- var DAY = 24 * HOUR;
5013
+ var DAY = 24 * HOUR2;
4573
5014
  var DEFAULT_DAYS = 14;
4574
5015
  var WINDOW_REPLIES = 2e3;
4575
5016
  var input16 = z19.object({
@@ -4577,7 +5018,7 @@ var input16 = z19.object({
4577
5018
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
4578
5019
  ),
4579
5020
  include_auto: z19.boolean().default(false).describe(
4580
- "Set to true to also check replies flagged automatic, by the vendor or by a fixed rule"
5021
+ "Set to true to also check replies flagged automatic, by the vendor or by a fixed rule, and to list conversations whose latest message is an automatic reply"
4581
5022
  ),
4582
5023
  include_inbox: z19.boolean().default(false).describe(
4583
5024
  "Set to true to also check replies in conversations that belong to no campaign, such as a LinkedIn account's own messages on HeyReach. false sets them aside and counts them in totals.notInCampaign."
@@ -4621,7 +5062,13 @@ var conversationsOf = (replies2, readers) => {
4621
5062
  var refsOf = (refs) => [
4622
5063
  ...new Set(refs.flatMap((ref) => ref === null ? [] : [ref]))
4623
5064
  ];
4624
- var named2 = async (context, dropped) => {
5065
+ var findingOf2 = (finding, reply, found) => {
5066
+ const [latest2] = found.followUp.evidence;
5067
+ const latestIsReply = found.activity.latest?.ref === reply;
5068
+ const meeting = found.followUp.basis === "meeting" ? ` ${found.followUp.evidence.at(-1) ?? ""} Check it before following up.` : "";
5069
+ return latestIsReply || latest2 === void 0 ? `${finding}${meeting}` : `${finding} ${latest2} Read it before following up.${meeting}`;
5070
+ };
5071
+ var named3 = async (context, dropped) => {
4625
5072
  const { outbound } = context;
4626
5073
  const readLeads2 = outbound.capabilities["leads.get"];
4627
5074
  const leadRefs = readLeads2 ? refsOf(dropped.map((each) => each.lead)) : [];
@@ -4652,13 +5099,23 @@ var named2 = async (context, dropped) => {
4652
5099
  "names are null"
4653
5100
  )
4654
5101
  ]);
4655
- return dropped.map((each) => {
5102
+ return dropped.map(({ labelled, messages, ...each }) => {
4656
5103
  const lead = each.lead === null ? void 0 : leads.get(each.lead);
4657
5104
  const campaign = each.campaign === null ? void 0 : campaigns.get(each.campaign);
5105
+ const found = threadContext({
5106
+ labelled,
5107
+ lead: lead ?? null,
5108
+ meetingsRecorded: recordsMeetings(outbound),
5109
+ messages,
5110
+ now: context.now,
5111
+ provider: each.provider
5112
+ });
4658
5113
  return {
4659
5114
  ...each,
5115
+ ...found,
4660
5116
  campaignName: campaign?.name ?? null,
4661
5117
  email: lead?.email ?? null,
5118
+ finding: findingOf2(each.finding, each.reply, found),
4662
5119
  linkedinUrl: lead?.linkedinUrl ?? null,
4663
5120
  name: lead === void 0 ? null : nameOf(lead)
4664
5121
  };
@@ -4683,7 +5140,7 @@ var readReplies = (context, since, given) => {
4683
5140
  );
4684
5141
  };
4685
5142
  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.",
5143
+ 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 conversation that, read in full, ends in an automatic reply (such as one within a minute of the email it answers) counts in totals.skippedAuto, not as dropped, unless include_auto is true. 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
5144
  inputSchema: input16,
4688
5145
  key: "droppedReplies",
4689
5146
  cost: (values, price) => {
@@ -4693,7 +5150,7 @@ var droppedReplies = defineInsight({
4693
5150
  scales: "max_replies",
4694
5151
  name: "dropped_replies",
4695
5152
  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.",
5153
+ 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
5154
  run: async (context, values) => {
4698
5155
  const since = new Date(
4699
5156
  values.since === null ? context.now - DEFAULT_DAYS * DAY : Date.parse(values.since)
@@ -4730,13 +5187,28 @@ var droppedReplies = defineInsight({
4730
5187
  since,
4731
5188
  values.max_replies ?? WINDOW_REPLIES
4732
5189
  );
4733
- const { answered, dropped, tooRecent, unread } = await check(
5190
+ const {
5191
+ answered,
5192
+ automatic,
5193
+ automaticReplies,
5194
+ dropped,
5195
+ tooRecent,
5196
+ unread
5197
+ } = await check(
4734
5198
  context,
4735
5199
  checkable,
4736
5200
  sent,
4737
- values.older_than_hours
5201
+ values.older_than_hours,
5202
+ values.include_auto
4738
5203
  );
4739
- const withNames = await named2(context, dropped);
5204
+ const withNames = await named3(context, dropped);
5205
+ const notChecked = unchecked + unread;
5206
+ const owedOrUnknown = conversations.length - automatic;
5207
+ if (notChecked > 0) {
5208
+ context.partial(
5209
+ notChecked === owedOrUnknown ? `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 ${owedOrUnknown} could not be checked, so dropped counts only the ${owedOrUnknown - notChecked} that were. totals.unchecked counts the rest, as neither dropped nor answered.`
5210
+ );
5211
+ }
4740
5212
  const answer = {
4741
5213
  dropped: withNames.toSorted(
4742
5214
  (left, right) => right.hoursWaiting - left.hoursWaiting || left.reply.localeCompare(right.reply)
@@ -4745,15 +5217,15 @@ var droppedReplies = defineInsight({
4745
5217
  since,
4746
5218
  totals: {
4747
5219
  answered,
4748
- conversations: conversations.length,
5220
+ conversations: owedOrUnknown,
4749
5221
  dropped: dropped.length,
4750
5222
  moreRepliesExist: listed2.capped,
4751
5223
  notInCampaign: separates ? inWindow.length - replies2.length : null,
4752
5224
  repliesRead: read.length,
4753
- skippedAuto: wanted.length - kept.length,
5225
+ skippedAuto: wanted.length - kept.length + automaticReplies,
4754
5226
  skippedByCategory: replies2.length - wanted.length,
4755
5227
  tooRecent,
4756
- unchecked: unchecked + unread
5228
+ unchecked: notChecked
4757
5229
  }
4758
5230
  };
4759
5231
  return answer;
@@ -4842,11 +5314,13 @@ var listedLeads = async (context, { campaign, max_leads: max }) => {
4842
5314
  });
4843
5315
  return { capped: walk.truncated || wasCutShort(leads), leads };
4844
5316
  };
5317
+ var leadOfReply = (reply) => reply.leadRef ?? (reply.leadEmail === null || reply.leadEmail === void 0 ? null : makeRef(reply.provider, reply.workspaceId, reply.leadEmail));
4845
5318
  var repliedRefs = (replies2, campaign, listed2) => {
4846
5319
  const refs = /* @__PURE__ */ new Map();
4847
5320
  for (const reply of replies2) {
4848
- if (reply.leadRef !== null && reply.isAuto !== true && !NOT_ENGAGED.has(reply.category) && (campaign === null || reply.campaignRef === campaign) && !refs.has(reply.leadRef) && !listed2.some((lead) => belongs(lead, reply))) {
4849
- refs.set(reply.leadRef, reply.campaignRef);
5321
+ const ref = leadOfReply(reply);
5322
+ if (ref !== null && reply.isAuto !== true && !NOT_ENGAGED.has(reply.category) && (campaign === null || reply.campaignRef === campaign) && !refs.has(ref) && !listed2.some((lead) => belongs(lead, reply))) {
5323
+ refs.set(ref, reply.campaignRef);
4850
5324
  }
4851
5325
  }
4852
5326
  return refs;
@@ -4865,10 +5339,26 @@ var byAddress = (found, campaigns) => {
4865
5339
  }
4866
5340
  return [...chosen.values()];
4867
5341
  };
4868
- var address = (ref, resolves) => {
4869
- const id = parseRef(ref)?.sourceId;
4870
- return emailAddress(id) ?? (id !== void 0 && resolves(id) === "email" ? id : null);
5342
+ var isToken = (value) => value?.startsWith("redacted:") ?? false;
5343
+ var address = (ref, resolves, emails) => {
5344
+ for (const value of [emails.get(ref), parseRef(ref)?.sourceId]) {
5345
+ const found = emailAddress(value) ?? (value !== void 0 && resolves(value) === "email" ? value : null);
5346
+ if (found !== null) {
5347
+ return found;
5348
+ }
5349
+ }
5350
+ return null;
5351
+ };
5352
+ var readable = (ref, resolves, emails) => {
5353
+ const id = parseRef(ref)?.sourceId ?? ref;
5354
+ return (!isToken(id) || resolves(id) !== null) && (!isToken(emails.get(ref)) || address(ref, resolves, emails) !== null);
4871
5355
  };
5356
+ var emailsOf = (replies2) => new Map(
5357
+ replies2.flatMap((reply) => {
5358
+ const ref = leadOfReply(reply);
5359
+ return ref === null || reply.leadEmail === null || reply.leadEmail === void 0 ? [] : [[ref, reply.leadEmail]];
5360
+ })
5361
+ );
4872
5362
  var lookUp = async (context, addresses, campaign) => {
4873
5363
  const found = [];
4874
5364
  const byToken = addressesMasked(context) ? maskingOf(context.outbound)?.leadsByToken : void 0;
@@ -4891,11 +5381,8 @@ var repliedLeads = async (context, values, replies2, listed2) => {
4891
5381
  const masking = maskingOf(outbound);
4892
5382
  const resolves = masking?.resolves ?? (() => null);
4893
5383
  const replied = repliedRefs(replies2, values.campaign, listed2);
4894
- const wanted = addressesMasked(context) ? new Map(
4895
- [...replied].filter(
4896
- ([ref]) => resolves(parseRef(ref)?.sourceId ?? ref) !== null
4897
- )
4898
- ) : replied;
5384
+ const emails = emailsOf(replies2);
5385
+ const wanted = addressesMasked(context) ? new Map([...replied].filter(([ref]) => readable(ref, resolves, emails))) : replied;
4899
5386
  if (wanted.size < replied.size) {
4900
5387
  context.partial(
4901
5388
  `${ADDRESSES_MASKED} leads that replied within recency_days and were not otherwise listed were not looked for.`
@@ -4905,12 +5392,16 @@ var repliedLeads = async (context, values, replies2, listed2) => {
4905
5392
  return { leads: [], unreadable: 0 };
4906
5393
  }
4907
5394
  const many = outbound.capabilities["leads.lookupMany"] === true;
4908
- const byAddressRefs = many ? [...wanted.keys()].filter((ref) => address(ref, resolves) !== null) : [];
5395
+ const byAddressRefs = many ? [...wanted.keys()].filter(
5396
+ (ref) => address(ref, resolves, emails) !== null
5397
+ ) : [];
4909
5398
  const addresses = [
4910
- ...new Set(byAddressRefs.flatMap((ref) => address(ref, resolves) ?? []))
5399
+ ...new Set(
5400
+ byAddressRefs.flatMap((ref) => address(ref, resolves, emails) ?? [])
5401
+ )
4911
5402
  ];
4912
5403
  const byRef = [...wanted.keys()].filter(
4913
- (ref) => !many || address(ref, resolves) === null
5404
+ (ref) => !many || address(ref, resolves, emails) === null
4914
5405
  );
4915
5406
  if (!outbound.capabilities["leads.get"] && byRef.length > 0) {
4916
5407
  context.partial(
@@ -5006,13 +5497,114 @@ var readCandidates = async (context, values) => {
5006
5497
  if (!confirmed && values.campaign !== null && leads.length === 0) {
5007
5498
  await confirmCampaign(context, values.campaign);
5008
5499
  }
5009
- return {
5010
- fromReplies: leads.length - listed2.length,
5500
+ return {
5501
+ fromReplies: leads.length - listed2.length,
5502
+ leads,
5503
+ moreLeadsExist: positive.capped || walked.capped,
5504
+ replies: replies2,
5505
+ unreadable: extra.unreadable
5506
+ };
5507
+ };
5508
+
5509
+ // src/insights/people/thread-read.ts
5510
+ var REDACT_TOKEN = /redacted:[0-9a-f]{16}/gu;
5511
+ var NAMED_REFS = 3;
5512
+ var readConversation = async (context, target, bodies) => {
5513
+ const options = bodies ? { include: ["body"] } : {};
5514
+ try {
5515
+ const page = await (target.kind === "thread" ? context.outbound.thread(target.id).messages(options) : context.outbound.lead(target.id).timeline(options));
5516
+ return { failed: null, messages: context.page(page), target };
5517
+ } catch (error) {
5518
+ if (isCapStop(error)) {
5519
+ throw error;
5520
+ }
5521
+ return {
5522
+ failed: `the read failed with ${OutboundError.is(error) ? error.code : "an unexpected error"}`,
5523
+ messages: null,
5524
+ target
5525
+ };
5526
+ }
5527
+ };
5528
+ var bodiesOf = (context, asked) => {
5529
+ const masksBodies = maskingOf(context.outbound)?.fields.includes("body") ?? false;
5530
+ if (asked === "snippet" && masksBodies) {
5531
+ throw new OutboundError(
5532
+ "Unsupported",
5533
+ "thread_context: the redact plugin masks message bodies, so snippets cannot be returned; pass bodies: none"
5534
+ );
5535
+ }
5536
+ if (asked === null && masksBodies) {
5537
+ context.note(
5538
+ "The redact plugin masks message bodies, so no snippets are returned (bodies: none)."
5539
+ );
5540
+ }
5541
+ return asked ?? (masksBodies ? "none" : "snippet");
5542
+ };
5543
+ var staleOf = (context, targets) => {
5544
+ const resolves = maskingOf(context.outbound)?.resolves;
5545
+ return resolves === void 0 ? [] : targets.filter(
5546
+ (target) => [...target.id.matchAll(REDACT_TOKEN)].some(
5547
+ ([token]) => resolves(token) === null
5548
+ )
5549
+ );
5550
+ };
5551
+ var refuseUnreadable = (context, targets) => {
5552
+ const { provider } = context.outbound;
5553
+ const stale = staleOf(context, targets);
5554
+ if (stale.length > 0) {
5555
+ const named5 = stale.slice(0, NAMED_REFS).map((target) => `"${target.id}"`).join(", ");
5556
+ const more = stale.length > NAMED_REFS ? ` and ${stale.length - NAMED_REFS} more` : "";
5557
+ const one = stale.length === 1;
5558
+ throw new OutboundError(
5559
+ "NotFound",
5560
+ `thread_context: ${named5}${more} ${one ? "holds a redacted token" : "hold redacted tokens"} from another session or process, so ${one ? "it is" : "they are"} not sent to the vendor. The redact plugin keeps what each token stands for in memory, only in the process that wrote it. Run the tool that returned ${one ? "it" : "them"} (such as dropped_replies) again in this session and pass the refs it returns. The redact key (redact's key option, or OUTBOUND_REDACT_KEY in the environment) keeps tokens the same across runs, so a ref you kept matches again once its records are read in the new session.`,
5561
+ { provider }
5562
+ );
5563
+ }
5564
+ for (const target of targets) {
5565
+ const parts = target.kind === "lead" ? leadRefParts(target.id) : null;
5566
+ if (target.kind === "lead" && parts === null) {
5567
+ throw new OutboundError(
5568
+ "Invalid",
5569
+ `thread_context: "${target.id}" is not a lead ref (provider:workspace:id); pass the lead ref another tool returned`,
5570
+ { provider }
5571
+ );
5572
+ }
5573
+ if (parts !== null) {
5574
+ assertRefReadable(context.outbound, { ...parts, text: target.id });
5575
+ }
5576
+ }
5577
+ };
5578
+ var inCampaign = (messages, lead) => messages.filter(
5579
+ (message) => message.campaignRef === null || lead === null || lead === void 0 || lead.campaignRef === null || message.campaignRef === lead.campaignRef
5580
+ );
5581
+ var leadContexts = async (context, leads, skipped = null) => {
5582
+ const { capabilities } = context.outbound;
5583
+ const unread = skipped ?? (capabilities["messages.list"] && capabilities["leads.timeline"] ? null : "this tool cannot read a lead's timeline (leads.timeline)");
5584
+ const reads = unread === null ? await mapConcurrent(
5011
5585
  leads,
5012
- moreLeadsExist: positive.capped || walked.capped,
5013
- replies: replies2,
5014
- unreadable: extra.unreadable
5015
- };
5586
+ (lead) => readConversation(context, { id: lead.ref, kind: "lead" }, false)
5587
+ ) : leads.map((lead) => ({
5588
+ failed: unread,
5589
+ messages: null,
5590
+ target: { id: lead.ref, kind: "lead" }
5591
+ }));
5592
+ return new Map(
5593
+ reads.map((read, index) => {
5594
+ const lead = leads[index] ?? null;
5595
+ return [
5596
+ read.target.id,
5597
+ threadContext({
5598
+ lead,
5599
+ meetingsRecorded: recordsMeetings(context.outbound),
5600
+ messages: read.messages === null ? null : inCampaign(read.messages, lead),
5601
+ notRead: read.failed ?? void 0,
5602
+ now: context.now,
5603
+ provider: lead?.provider ?? context.outbound.provider
5604
+ })
5605
+ ];
5606
+ })
5607
+ );
5016
5608
  };
5017
5609
 
5018
5610
  // src/insights/people/hot-leads.ts
@@ -5039,6 +5631,9 @@ var input17 = z20.object({
5039
5631
  "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
5632
  ),
5041
5633
  positive_labels: positiveLabelsField,
5634
+ read_threads: z20.boolean().default(false).describe(
5635
+ "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."
5636
+ ),
5042
5637
  recency_days: z20.number().min(1).default(14).describe(
5043
5638
  "A reply today earns the full recency points, fading evenly to none after this many days"
5044
5639
  ),
@@ -5145,7 +5740,7 @@ var toHotLead = (lead, values, now) => {
5145
5740
  };
5146
5741
  var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1 : 0);
5147
5742
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
5148
- var staleOf = (leads, values, now) => new Set(
5743
+ var staleOf2 = (leads, values, now) => new Set(
5149
5744
  leads.flatMap((lead) => {
5150
5745
  const age = ageOf(lead, now);
5151
5746
  return age !== null && age > values.max_age_days ? [lead.ref] : [];
@@ -5153,14 +5748,14 @@ var staleOf = (leads, values, now) => new Set(
5153
5748
  );
5154
5749
  var hotLeads = defineInsight({
5155
5750
  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.",
5751
+ 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
5752
  inputSchema: input17,
5158
5753
  key: "hotLeads",
5159
5754
  cost: (values, price) => {
5160
5755
  const { capabilities } = price;
5161
5756
  const filtered = capabilities["leads.byInterest"] === true;
5162
5757
  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);
5758
+ 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
5759
  },
5165
5760
  scales: "max_replies",
5166
5761
  name: "hot_leads",
@@ -5198,7 +5793,7 @@ var hotLeads = defineInsight({
5198
5793
  const scored = open.flatMap(
5199
5794
  (lead) => toHotLead(lead, scoring, context.now)
5200
5795
  );
5201
- const stale = staleOf(open, scoring, context.now);
5796
+ const stale = staleOf2(open, scoring, context.now);
5202
5797
  const positive = scored.filter((lead) => lead.score > 0);
5203
5798
  const hot = [
5204
5799
  ...positive.filter((lead) => !stale.has(lead.lead)).toSorted(hottestFirst),
@@ -5207,8 +5802,18 @@ var hotLeads = defineInsight({
5207
5802
  const negative = open.filter((lead) => saidNo(lead, scoring));
5208
5803
  const refused = new Set(negative.map((lead) => lead.ref));
5209
5804
  const after = scored.filter((lead) => lead.score <= 0 && refused.has(lead.lead)).toSorted(hottestFirst);
5805
+ const ranked = [...hot, ...after].slice(0, values.limit);
5806
+ const byRef = new Map(open.map((lead) => [lead.ref, lead]));
5807
+ const contexts = await leadContexts(
5808
+ context,
5809
+ ranked.flatMap((each) => {
5810
+ const lead = byRef.get(each.lead);
5811
+ return lead === void 0 ? [] : [lead];
5812
+ }),
5813
+ values.read_threads ? null : "read_threads is false; pass the lead refs to thread_context"
5814
+ );
5210
5815
  const answer = {
5211
- leads: [...hot, ...after].slice(0, values.limit),
5816
+ leads: ranked.map((each) => ({ ...each, ...contexts.get(each.lead) })),
5212
5817
  totals: {
5213
5818
  autoReplied: open.filter(
5214
5819
  (lead) => scoring.automatic(lead) && repliesOf(lead) > 0
@@ -5233,25 +5838,46 @@ var hotLeads = defineInsight({
5233
5838
  // src/insights/people/lead-collisions.ts
5234
5839
  import { z as z21 } from "zod";
5235
5840
 
5236
- // 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;
5841
+ // src/insights/people/coverage.ts
5842
+ var campaignGaps = (read) => {
5843
+ const leadsCapped = read.campaignsWithMoreLeads - read.leadsCut;
5844
+ return [
5845
+ ...read.moreCampaignsExist ? [
5846
+ {
5847
+ input: read.campaignsCut ? null : "max_campaigns",
5848
+ read: `${plural(read.campaigns, "campaign")}, with more in those statuses unread`
5849
+ }
5850
+ ] : [],
5851
+ ...leadsCapped > 0 ? [
5852
+ {
5853
+ input: "max_leads_per_campaign",
5854
+ read: `the first ${plural(read.maxLeads, "lead")} of ${plural(leadsCapped, "campaign that has", "campaigns that have")} more`
5855
+ }
5856
+ ] : [],
5857
+ ...read.leadsCut > 0 ? [
5858
+ {
5859
+ input: null,
5860
+ read: `part of the leads of ${plural(read.leadsCut, "campaign")}`
5861
+ }
5862
+ ] : []
5863
+ ];
5247
5864
  };
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`;
5865
+ var joined = (parts) => parts.length < 2 ? parts[0] ?? "" : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
5866
+ var gapsSentence = (gaps) => {
5867
+ if (gaps.length === 0) {
5868
+ return null;
5252
5869
  }
5253
- return value.includes("@") ? `"${value}" is not a valid email address` : "Give an email address, a LinkedIn profile URL or a lead ref";
5870
+ const inputs = [
5871
+ ...new Set(gaps.flatMap((gap) => gap.input === null ? [] : [gap.input]))
5872
+ ];
5873
+ const raise = [
5874
+ ...inputs.length > 0 ? [`raise ${joined(inputs)}`] : [],
5875
+ ...gaps.some((gap) => gap.input === null) ? ["raise the request cap the notes name"] : []
5876
+ ];
5877
+ return `The check is incomplete: it read only ${joined(gaps.map((gap) => `${gap.read} (${gap.input ?? "a request cap"})`))}. To check the rest, ${joined(raise)}.`;
5254
5878
  };
5879
+
5880
+ // src/insights/people/find.ts
5255
5881
  var keysOfLead = (lead) => {
5256
5882
  const slug = profileSlug(lead.linkedinUrl);
5257
5883
  return [
@@ -5267,6 +5893,7 @@ var lookupOf = (outbound) => {
5267
5893
  const masking = maskingOf(outbound);
5268
5894
  return {
5269
5895
  hash: masking?.strategy === "hash" ? masking.hash : void 0,
5896
+ known: (key) => masking?.strategy === "mask" && (masking.resolves?.(key.slice(key.indexOf(":") + 1)) ?? null) !== null,
5270
5897
  masked: (masking?.fields ?? []).flatMap(
5271
5898
  (field) => field === "email" || field === "linkedin" ? [field] : []
5272
5899
  )
@@ -5282,7 +5909,14 @@ var refuse = (outbound, masked, why) => new OutboundError(
5282
5909
  `A person cannot be looked up while the redact plugin masks ${maskedWords(masked)}: ${why}`,
5283
5910
  { provider: outbound.provider }
5284
5911
  );
5285
- var isLeadRef = (identifier) => personKey(identifier) === null && parseRef(identifier.trim()) !== null;
5912
+ var refNeedsRead = (identifier) => {
5913
+ try {
5914
+ const parsed = parsePerson(identifier, "");
5915
+ return parsed.ref !== null && parsed.key === null;
5916
+ } catch {
5917
+ return false;
5918
+ }
5919
+ };
5286
5920
  var PROFILE = "https://www.linkedin.com/in/";
5287
5921
  var formsOf = (key, given) => {
5288
5922
  const value = key.slice(key.indexOf(":") + 1);
@@ -5293,9 +5927,13 @@ var formsOf = (key, given) => {
5293
5927
  given.trim()
5294
5928
  ];
5295
5929
  };
5296
- var startFrom = async (context, identifier, { hash, masked }) => {
5930
+ var startFrom = async (context, identifier, lookup) => {
5931
+ const { hash, masked } = lookup;
5297
5932
  const { outbound } = context;
5298
- const key = personKey(identifier);
5933
+ const { key, ref } = parsePerson(identifier, outbound.provider);
5934
+ if (ref !== null) {
5935
+ assertRefReadable(outbound, ref);
5936
+ }
5299
5937
  if (key !== null) {
5300
5938
  if (!masked.includes(kindOf(key))) {
5301
5939
  return { hashed: null, keys: [key], records: [] };
@@ -5304,10 +5942,10 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5304
5942
  throw refuse(
5305
5943
  outbound,
5306
5944
  masked,
5307
- "the records could not be matched to the identifier"
5945
+ "the records come back masked and cannot be matched to the identifier, so give the lead ref another tool returned instead"
5308
5946
  );
5309
5947
  }
5310
- const tokens = formsOf(key, identifier).map(hash);
5948
+ const tokens = formsOf(key, ref?.sourceId ?? identifier).map(hash);
5311
5949
  return {
5312
5950
  hashed: {
5313
5951
  shown: `${kindOf(key)}:${tokens[0] ?? ""}`,
@@ -5317,23 +5955,15 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5317
5955
  records: []
5318
5956
  };
5319
5957
  }
5320
- if (!isLeadRef(identifier)) {
5321
- throw new OutboundError("Invalid", notAPerson(identifier), {
5322
- provider: outbound.provider
5323
- });
5324
- }
5325
5958
  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
- if (masked.length === 2) {
5327
- throw refuse(
5328
- outbound,
5329
- masked,
5330
- instead ?? "a lead ref has no identifier left to look the person up by"
5331
- );
5959
+ if (masked.length === 2 && instead !== null) {
5960
+ throw refuse(outbound, masked, instead);
5332
5961
  }
5333
- const lead = context.one(await outbound.leads.get(identifier.trim()));
5334
- const keys = keysOfLead(lead).filter(
5962
+ const lead = context.one(await outbound.leads.get(ref?.text ?? identifier));
5963
+ const open = keysOfLead(lead).filter(
5335
5964
  (each) => !masked.includes(kindOf(each))
5336
5965
  );
5966
+ const keys = open.length > 0 ? open : keysOfLead(lead).filter((each) => lookup.known(each));
5337
5967
  if (keys.length === 0 && masked.length > 0) {
5338
5968
  const other = ["email", "linkedin"].find(
5339
5969
  (kind) => !masked.includes(kind)
@@ -5353,6 +5983,7 @@ var carries = (lead, key, start) => {
5353
5983
  }
5354
5984
  return keysOfLead(lead).includes(key);
5355
5985
  };
5986
+ var followed = (key, lookup, byToken) => !lookup.masked.includes(kindOf(key)) || byToken && lookup.known(key);
5356
5987
  var noteNoProfiles = (context, keys) => {
5357
5988
  if (context.outbound.fields.lead?.linkedinUrl === false && keys.some((key) => kindOf(key) === "linkedin")) {
5358
5989
  context.note(
@@ -5372,6 +6003,7 @@ var findPerson = async (context, identifier, maxRecords) => {
5372
6003
  }
5373
6004
  const keys = new Set(start.keys);
5374
6005
  const asked = /* @__PURE__ */ new Set();
6006
+ const byToken = start.keys.some((key) => masked.includes(kindOf(key)));
5375
6007
  const records = new Map(
5376
6008
  start.records.map((lead) => [`${lead.ref} ${lead.campaignRef ?? ""}`, lead])
5377
6009
  );
@@ -5397,7 +6029,7 @@ var findPerson = async (context, identifier, maxRecords) => {
5397
6029
  if (asking !== void 0 && carries(lead, asking, start)) {
5398
6030
  records.set(`${lead.ref} ${lead.campaignRef ?? ""}`, lead);
5399
6031
  for (const key of leadKeys) {
5400
- if (!masked.includes(kindOf(key))) {
6032
+ if (followed(key, lookup, byToken)) {
5401
6033
  keys.add(key);
5402
6034
  }
5403
6035
  }
@@ -5405,11 +6037,11 @@ var findPerson = async (context, identifier, maxRecords) => {
5405
6037
  }
5406
6038
  }
5407
6039
  }
5408
- const shown = [...keys].map(
6040
+ const shown2 = [...keys].map(
5409
6041
  (key) => start.hashed !== null && start.keys.includes(key) ? start.hashed.shown : key
5410
6042
  );
5411
6043
  return {
5412
- keys: shown.toSorted(),
6044
+ keys: shown2.toSorted(),
5413
6045
  records: [...records.values()].slice(0, maxRecords)
5414
6046
  };
5415
6047
  };
@@ -5419,10 +6051,12 @@ var input18 = z21.object({
5419
6051
  include_past: z21.boolean().default(false).describe(
5420
6052
  "Also report a person in two or more campaigns of whom fewer than two memberships are still active, for example one who completed one campaign and is now in another. By default only people active in two or more campaigns at once are reported."
5421
6053
  ),
5422
- max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
5423
- "The most campaigns to read. Each costs one request per page of its leads."
6054
+ max_campaigns: z21.number().int().min(1).max(200).default(200).describe(
6055
+ "The most campaigns to read. Each costs one request per page of its leads. Defaults to the most allowed, so every campaign in the statuses is read."
6056
+ ),
6057
+ max_leads_per_campaign: z21.number().int().min(1).max(2e4).default(1e3).describe(
6058
+ "The most leads to read from each campaign. A campaign with more is read only in part, so totals.collisions is null."
5424
6059
  ),
5425
- max_leads_per_campaign: z21.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
5426
6060
  statuses: statusesField
5427
6061
  });
5428
6062
  var keysFor = (masking) => masking?.strategy === "mask" && masking.fields.includes("linkedin") ? (lead) => [
@@ -5472,7 +6106,7 @@ var toCollision = (group) => {
5472
6106
  campaignCount: campaigns.length,
5473
6107
  campaigns,
5474
6108
  channels,
5475
- finding: findingOf2(shownKey(identifiers[0] ?? ""), campaigns, {
6109
+ finding: findingOf3(shownKey(identifiers[0] ?? ""), campaigns, {
5476
6110
  channels,
5477
6111
  providers
5478
6112
  }),
@@ -5484,11 +6118,11 @@ var toCollision = (group) => {
5484
6118
  ];
5485
6119
  };
5486
6120
  var listed = (parts) => parts.length < 2 ? parts[0] ?? "" : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
5487
- var named3 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName}"`));
6121
+ var named4 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName}"`));
5488
6122
  var withStatus = (campaigns) => listed(
5489
6123
  campaigns.map((each) => `"${each.campaignName}" (${each.leadStatus})`)
5490
6124
  );
5491
- var findingOf2 = (who, campaigns, tools) => {
6125
+ var findingOf3 = (who, campaigns, tools) => {
5492
6126
  const active = campaigns.filter((each) => each.leadStatus === "active");
5493
6127
  const past = campaigns.filter((each) => each.leadStatus !== "active");
5494
6128
  if (active.length >= 2) {
@@ -5496,11 +6130,22 @@ var findingOf2 = (who, campaigns, tools) => {
5496
6130
  const also = past.length === 0 ? "" : `, and was in ${withStatus(past)}`;
5497
6131
  return `${who} is in ${active.length} ${where} at once${also}.`;
5498
6132
  }
5499
- return active.length === 0 ? `${who} was in ${withStatus(past)}, and is active in none of them now.` : `${who} was in ${withStatus(past)} and is now active in ${named3(active)}.`;
6133
+ return active.length === 0 ? `${who} was in ${withStatus(past)}, and is active in none of them now.` : `${who} was in ${withStatus(past)} and is now active in ${named4(active)}.`;
5500
6134
  };
5501
6135
  var worstFirst = (left, right) => right.stillActive - left.stillActive || right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
6136
+ var overallOf = (found, campaigns, past, incomplete) => {
6137
+ const where = past ? "in two or more of the campaigns" : "active in two or more of the campaigns at once";
6138
+ const people = `${plural(found, "person is", "people are")} ${where}`;
6139
+ if (incomplete === null && campaigns === 0) {
6140
+ return `Nobody is ${where}: no campaign in those statuses was found to read.`;
6141
+ }
6142
+ if (incomplete === null) {
6143
+ return found === 0 ? `Nobody is ${where}: every lead of ${plural(campaigns, "campaign")} was read.` : `${people}, among every lead of ${plural(campaigns, "campaign")}.`;
6144
+ }
6145
+ return found === 0 ? `Not a clean result. No collision was found in what was read, but ${incomplete.charAt(0).toLowerCase()}${incomplete.slice(1)}` : `At least ${people}. ${incomplete}`;
6146
+ };
5502
6147
  var leadCollisions = defineInsight({
5503
- description: "People who are in two or more campaigns at once, so they get overlapping outreach. Reads the campaigns in the given statuses (active by default) and their leads, matches people by exact email address or LinkedIn profile, and returns each person with their campaigns, channel and tool, most active campaigns first. By default a person counts only when their own status is active in two or more of the campaigns; include_past also reports people who finished, replied to or left one campaign and are in another, counted in totals.pastOverlaps either way. A collision across tools (for example email in one and LinkedIn in another) is marked across_tools; one inside a tool is within_tool. Costs one request per page of campaigns plus one per page of each campaign's leads; the caps make the answer incomplete rather than slow.",
6148
+ description: "People who are in two or more campaigns at once, so they get overlapping outreach. Reads the campaigns in the given statuses (active by default) and their leads, matches people by exact email address or LinkedIn profile, and returns each person with their campaigns, channel and tool, most active campaigns first. By default a person counts only when their own status is active in two or more of the campaigns; include_past also reports people who finished, replied to or left one campaign and are in another, counted in totals.pastOverlaps either way. A collision across tools (for example email in one and LinkedIn in another) is marked across_tools; one inside a tool is within_tool. Every campaign in the statuses is read by default. Returns a finding sentence that leads with what was read; when a cap leaves campaigns or leads unread, totals.collisions is null, totals.collisionsFound counts what was found and the finding names each cap to raise, never a bare 0. Costs one request per page of campaigns plus one per page of each campaign's leads.",
5504
6149
  inputSchema: input18,
5505
6150
  key: "leadCollisions",
5506
6151
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("leads.list", values.max_leads_per_campaign),
@@ -5516,21 +6161,40 @@ var leadCollisions = defineInsight({
5516
6161
  "The redact plugin masks LinkedIn profiles, so people were matched by email address only."
5517
6162
  );
5518
6163
  }
5519
- const campaigns = await campaignsIn(
6164
+ const campaignsRead = await readCampaignsIn(
5520
6165
  context,
5521
6166
  values.statuses,
5522
6167
  values.max_campaigns
5523
6168
  );
6169
+ const campaigns = campaignsRead.items;
5524
6170
  const perCampaign = await mapConcurrent(campaigns, async (campaign) => {
5525
- const leads = await leadsOf(
6171
+ const leads = await readCappedFlag(
5526
6172
  context,
5527
- campaign.ref,
6173
+ (cap) => context.outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
5528
6174
  values.max_leads_per_campaign,
6175
+ "leads of a campaign",
5529
6176
  "max_leads_per_campaign"
5530
6177
  );
5531
- return leads.map((lead) => ({ campaign, lead }));
6178
+ return {
6179
+ capped: leads.capped,
6180
+ cut: wasCutShort(leads.items),
6181
+ entries: leads.items.map((lead) => ({ campaign, lead }))
6182
+ };
5532
6183
  });
5533
- const entries = perCampaign.flat();
6184
+ const entries = perCampaign.flatMap((each) => each.entries);
6185
+ const campaignsWithMoreLeads = perCampaign.filter(
6186
+ (each) => each.capped
6187
+ ).length;
6188
+ const incomplete = gapsSentence(
6189
+ campaignGaps({
6190
+ campaigns: campaigns.length,
6191
+ campaignsCut: wasCutShort(campaigns),
6192
+ leadsCut: perCampaign.filter((each) => each.cut).length,
6193
+ campaignsWithMoreLeads,
6194
+ maxLeads: values.max_leads_per_campaign,
6195
+ moreCampaignsExist: campaignsRead.capped
6196
+ })
6197
+ );
5534
6198
  const overlaps = groupPeople(entries, keysOf).flatMap(toCollision);
5535
6199
  const pastOverlaps = overlaps.filter((each) => each.stillActive < 2).length;
5536
6200
  const collisions = overlaps.filter((each) => values.include_past || each.stillActive >= 2).toSorted(worstFirst);
@@ -5539,15 +6203,24 @@ var leadCollisions = defineInsight({
5539
6203
  ).length;
5540
6204
  const answer = {
5541
6205
  collisions,
6206
+ finding: overallOf(
6207
+ collisions.length,
6208
+ campaigns.length,
6209
+ values.include_past,
6210
+ incomplete
6211
+ ),
5542
6212
  totals: {
5543
6213
  acrossTools,
5544
6214
  campaignsRead: campaigns.length,
5545
- collisions: collisions.length,
6215
+ campaignsWithMoreLeads,
6216
+ collisions: incomplete === null ? collisions.length : null,
6217
+ collisionsFound: collisions.length,
5546
6218
  concurrent: collisions.filter((each) => each.stillActive >= 2).length,
5547
6219
  leadsRead: entries.length,
5548
6220
  leadsWithoutIdentifier: entries.filter(
5549
6221
  (entry) => keysOf(entry.lead).length === 0
5550
6222
  ).length,
6223
+ moreCampaignsExist: campaignsRead.capped,
5551
6224
  pastOverlaps,
5552
6225
  withinTool: collisions.length - acrossTools
5553
6226
  }
@@ -5559,11 +6232,11 @@ var leadCollisions = defineInsight({
5559
6232
  // src/insights/people/person-summary.ts
5560
6233
  import { z as z22 } from "zod";
5561
6234
  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
- });
6235
+ max_campaigns: z22.number().int().min(1).max(50).default(20).describe(
6236
+ "The most campaigns to report on. Each costs up to 2 requests."
6237
+ ),
6238
+ ...personFields
6239
+ }).superRefine(checkPerson);
5567
6240
  var times2 = (messages, direction) => messages.flatMap(
5568
6241
  (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
5569
6242
  );
@@ -5578,13 +6251,13 @@ var repliedSteps = (lead, messages) => {
5578
6251
  steps.add(message.stepIndex ?? lastSent ?? 0);
5579
6252
  }
5580
6253
  }
5581
- const named4 = lead.engagement?.repliedStepIndex ?? null;
5582
- if (named4 !== null) {
5583
- steps.add(named4);
6254
+ const named5 = lead.engagement?.repliedStepIndex ?? null;
6255
+ if (named5 !== null) {
6256
+ steps.add(named5);
5584
6257
  }
5585
6258
  return [...steps].toSorted((left, right) => left - right);
5586
6259
  };
5587
- var activityOf = (lead, messages) => {
6260
+ var activityOf2 = (lead, messages) => {
5588
6261
  const sent = times2(messages, "out");
5589
6262
  const received = times2(
5590
6263
  messages.filter((message) => !isAutoMessage(message)),
@@ -5639,7 +6312,7 @@ var summarize2 = async (context, timelines, lead) => {
5639
6312
  timelineOf(context, timelines, lead),
5640
6313
  lead.campaignRef === null ? null : outbound.campaigns.get(lead.campaignRef).then(context.one)
5641
6314
  ]);
5642
- const { automatic, threadIsShort, ...counted2 } = activityOf(lead, messages);
6315
+ const { automatic, threadIsShort, ...counted2 } = activityOf2(lead, messages);
5643
6316
  const autoReplied = isAutoReplied(lead) || automatic > 0 && counted2.replies === 0;
5644
6317
  const activity = autoReplied ? { ...counted2, lastRepliedAt: null, replies: 0 } : counted2;
5645
6318
  noteAutomatic(context, lead, counted2.replies + automatic, automatic);
@@ -5654,6 +6327,13 @@ var summarize2 = async (context, timelines, lead) => {
5654
6327
  );
5655
6328
  return {
5656
6329
  ...activity,
6330
+ ...threadContext({
6331
+ lead,
6332
+ meetingsRecorded: recordsMeetings(outbound),
6333
+ messages,
6334
+ now: context.now,
6335
+ provider: lead.provider
6336
+ }),
5657
6337
  campaign: lead.campaignRef,
5658
6338
  campaignName: campaign?.name ?? null,
5659
6339
  campaignStatus: campaign?.status ?? null,
@@ -5688,21 +6368,18 @@ var byChannel2 = (campaigns) => {
5688
6368
  return channels;
5689
6369
  };
5690
6370
  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.",
6371
+ 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 (a HeyReach ref needs 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
6372
  inputSchema: input19,
5693
6373
  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")),
6374
+ 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
6375
  scales: "max_campaigns",
5696
6376
  name: "person_summary",
5697
- maskedOut: (masking) => {
5698
- const masked = new Set(masking.fields);
5699
- return masked.has("email") && masked.has("linkedin") && masking.strategy === "mask" ? "email addresses and LinkedIn profiles, which it looks a person up by" : null;
5700
- },
5701
6377
  needs: ["leads.lookup", "leads.timeline"],
5702
- needsFor: ({ person }) => isLeadRef(person) ? ["leads.get"] : [],
6378
+ needsFor: (values) => refNeedsRead(personOf(values)) ? ["leads.get"] : [],
5703
6379
  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);
6380
+ run: async (context, values) => {
6381
+ const maxCampaigns = values.max_campaigns;
6382
+ const found = await findPerson(context, personOf(values), maxCampaigns);
5706
6383
  const timelines = /* @__PURE__ */ new Map();
5707
6384
  const campaigns = await mapConcurrent(
5708
6385
  found.records,
@@ -5884,13 +6561,15 @@ var input21 = z24.object({
5884
6561
  lead_statuses: z24.array(leadStatusSchema).min(1).default([...SENDABLE]).describe(
5885
6562
  "Only a matching lead in one of these states is a violation: active, paused, unknown (not yet started, or the tool does not say), completed, skipped (the tool decided never to send), replied, bounced or unsubscribed. Other matches are counted in totals.alreadyStopped. Defaults to the leads still being sent to."
5886
6563
  ),
5887
- max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
5888
- "The most block list entries to read. A vendor request returns about 50 to 100."
6564
+ max_block_entries: z24.number().int().min(1).max(1e5).default(1e4).describe(
6565
+ "The most block list entries to read. A vendor request returns about 50 to 100. A lead on an entry past this cap is not found, so violations is null when entries are left unread."
5889
6566
  ),
5890
- max_campaigns: z24.number().int().min(1).max(200).default(20).describe(
5891
- "The most campaigns to check. Each costs one request per page of its leads."
6567
+ max_campaigns: z24.number().int().min(1).max(200).default(200).describe(
6568
+ "The most campaigns to check. Each costs one request per page of its leads. Defaults to the most allowed, so every campaign in the statuses is checked."
6569
+ ),
6570
+ max_leads_per_campaign: z24.number().int().min(1).max(2e4).default(1e3).describe(
6571
+ "The most leads to read from each campaign. A campaign with more is checked only in part, so violations is null."
5892
6572
  ),
5893
- max_leads_per_campaign: z24.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
5894
6573
  statuses: statusesField
5895
6574
  });
5896
6575
  var slugOfEntry = (value) => profileSlug(value) ?? value.trim().replaceAll(/^\/+|\/+$/gu, "").toLowerCase();
@@ -5964,8 +6643,29 @@ var maskNote = (outbound) => {
5964
6643
  return masked.length === 0 ? null : `The redact plugin masks ${masked.join(" and ")}, so ${lost.join(" and ")} could not be matched to leads.`;
5965
6644
  };
5966
6645
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
6646
+ var gapsOf = (checked, entries) => [
6647
+ ...campaignGaps(checked),
6648
+ ...entries === null ? [] : [
6649
+ {
6650
+ input: entries.cut ? null : "max_block_entries",
6651
+ read: `${plural(entries.read, "block list entry", "block list entries")}, with more unread`
6652
+ }
6653
+ ]
6654
+ ];
6655
+ var findingOf4 = (violations, campaigns, gaps) => {
6656
+ const incomplete = gapsSentence(gaps);
6657
+ const inCampaigns = new Set(violations.map((each) => each.campaign)).size;
6658
+ const found = `${plural(violations.length, "lead still being sent to is", "leads still being sent to are")} on the block list, in ${plural(inCampaigns, "campaign")}`;
6659
+ if (incomplete === null) {
6660
+ if (campaigns === 0) {
6661
+ return "No lead still being sent to is on the block list: no campaign in those statuses was found to check.";
6662
+ }
6663
+ return violations.length === 0 ? `No lead still being sent to is on the block list: every lead of ${plural(campaigns, "campaign")} was checked against every entry.` : `${found} of ${campaigns}.`;
6664
+ }
6665
+ return violations.length === 0 ? `Not a clean result. No violation was found in what was read, but ${incomplete.charAt(0).toLowerCase()}${incomplete.slice(1)}` : `At least ${found}. ${incomplete}`;
6666
+ };
5967
6667
  var suppressionCheck = defineInsight({
5968
- description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. A match is a violation only when the lead's own status is in lead_statuses (active, paused or unknown by default, the leads still being sent to); a lead that already unsubscribed, bounced, replied or completed is counted in totals.alreadyStopped instead. Returns each violation with the lead, the campaign, the entry and how it matched, counts per campaign, and how many block entries were read; totals.moreBlockEntriesExist is true when max_block_entries left entries unread, which were not checked. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
6668
+ description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. A match is a violation only when the lead's own status is in lead_statuses (active, paused or unknown by default, the leads still being sent to); a lead that already unsubscribed, bounced, replied or completed is counted in totals.alreadyStopped instead. Returns a finding sentence that leads with what was checked, each violation with the lead, the campaign, the entry and how it matched, and counts per campaign. Every campaign in the statuses is checked by default; when a cap leaves campaigns, leads or block entries unread, totals.violations is null, totals.violationsFound counts what was found, and the finding names each cap to raise, never a bare 0. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
5969
6669
  inputSchema: input21,
5970
6670
  key: "suppressionCheck",
5971
6671
  cost: (values, price) => price.list("blocklist.list", values.max_block_entries) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("leads.list", values.max_leads_per_campaign),
@@ -5988,11 +6688,12 @@ var suppressionCheck = defineInsight({
5988
6688
  if (unmatched !== null) {
5989
6689
  context.partial(unmatched);
5990
6690
  }
5991
- const campaigns = await campaignsIn(
6691
+ const listedCampaigns = await readCampaignsIn(
5992
6692
  context,
5993
6693
  values.statuses,
5994
6694
  values.max_campaigns
5995
6695
  );
6696
+ const campaigns = listedCampaigns.items;
5996
6697
  const sendable = new Set(values.lead_statuses);
5997
6698
  const violations = [];
5998
6699
  const byCampaign = [];
@@ -6028,7 +6729,20 @@ var suppressionCheck = defineInsight({
6028
6729
  `${blocked.notChecked} of the block entries read name a company or another kind of entry no lead can be matched on, so they were not checked.`
6029
6730
  );
6030
6731
  }
6732
+ const campaignsWithMoreLeads = read.filter((each) => each.capped).length;
6733
+ const gaps = gapsOf(
6734
+ {
6735
+ campaigns: campaigns.length,
6736
+ campaignsCut: wasCutShort(campaigns),
6737
+ campaignsWithMoreLeads,
6738
+ leadsCut: read.filter((each) => wasCutShort(each.items)).length,
6739
+ maxLeads: values.max_leads_per_campaign,
6740
+ moreCampaignsExist: listedCampaigns.capped
6741
+ },
6742
+ listed2.capped ? { cut: wasCutShort(entries), read: entries.length } : null
6743
+ );
6031
6744
  const answer = {
6745
+ finding: findingOf4(violations, campaigns.length, gaps),
6032
6746
  byCampaign: byCampaign.toSorted(
6033
6747
  (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
6034
6748
  ),
@@ -6042,10 +6756,13 @@ var suppressionCheck = defineInsight({
6042
6756
  linkedin: matches.get("linkedin") ?? 0
6043
6757
  },
6044
6758
  campaignsRead: campaigns.length,
6759
+ campaignsWithMoreLeads,
6045
6760
  leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
6046
6761
  moreBlockEntriesExist: listed2.capped,
6047
- moreLeadsExist: read.some((each) => each.capped),
6048
- violations: violations.length
6762
+ moreCampaignsExist: listedCampaigns.capped,
6763
+ moreLeadsExist: campaignsWithMoreLeads > 0,
6764
+ violations: gaps.length === 0 ? violations.length : null,
6765
+ violationsFound: violations.length
6049
6766
  },
6050
6767
  violations: violations.toSorted(activeFirst)
6051
6768
  };
@@ -6053,6 +6770,193 @@ var suppressionCheck = defineInsight({
6053
6770
  }
6054
6771
  });
6055
6772
 
6773
+ // src/insights/people/thread-contexts.ts
6774
+ import { z as z25 } from "zod";
6775
+ var SNIPPET_CHARS = 280;
6776
+ var ids = (what) => z25.array(z25.string().min(1)).max(100).default([]).describe(what);
6777
+ var input22 = z25.object({
6778
+ bodies: z25.enum(["none", "snippet"]).nullable().default(null).describe(
6779
+ "snippet returns the first 280 characters of each message, wrapped as untrusted content; none returns no text. Null means snippet, or none when the redact plugin masks message bodies"
6780
+ ),
6781
+ cursor: z25.string().min(1).nullable().default(null).describe(
6782
+ "coverage.nextCursor from the previous call with the same leads and threads, to read the next page of conversations"
6783
+ ),
6784
+ leads: ids(
6785
+ "Lead refs (provider:workspace:id), as dropped_replies, hot_leads and person_summary return them. Each lead's conversation in its campaign is read."
6786
+ ),
6787
+ max_messages: z25.number().int().min(1).max(100).default(10).describe(
6788
+ "The newest messages returned per conversation. Every message is still read, so the latest is always found."
6789
+ ),
6790
+ page_size: z25.number().int().min(1).max(50).default(20).describe(
6791
+ "Conversations read per call. Each costs one walk of its messages."
6792
+ ),
6793
+ threads: ids("Thread ids, from a message's or reply's threadId")
6794
+ });
6795
+ var targetsOf = (values) => [
6796
+ ...[...new Set(values.leads)].map((id) => ({ id, kind: "lead" })),
6797
+ ...[...new Set(values.threads)].map((id) => ({
6798
+ id,
6799
+ kind: "thread"
6800
+ }))
6801
+ ];
6802
+ var startOf = (cursor, total2) => {
6803
+ if (cursor === null) {
6804
+ return 0;
6805
+ }
6806
+ const [offset, of] = cursor.split("/").map(Number);
6807
+ if (offset === void 0 || of !== total2 || !Number.isInteger(offset) || offset < 0 || offset >= total2) {
6808
+ throw new OutboundError(
6809
+ "Invalid",
6810
+ "thread_context: cursor does not belong to these leads and threads; pass the nextCursor of a call with the same leads and threads"
6811
+ );
6812
+ }
6813
+ return offset;
6814
+ };
6815
+ var leadRefOf = (read) => read.target.kind === "lead" ? read.target.id : read.messages?.find((message) => message.leadRef !== null)?.leadRef ?? null;
6816
+ var toMessage = (message, bodies) => ({
6817
+ ...withoutBody(message),
6818
+ snippet: bodies ? untrusted(
6819
+ message.bodyText?.replaceAll(/\s+/gu, " ").trim() || null,
6820
+ SNIPPET_CHARS
6821
+ ) : null
6822
+ });
6823
+ var partyOf = (lead, messages) => ({
6824
+ campaign: lead?.campaignRef ?? messages.find((message) => message.campaignRef !== null)?.campaignRef ?? null,
6825
+ email: lead?.email ?? null,
6826
+ linkedinUrl: lead?.linkedinUrl ?? null,
6827
+ threadIds: [
6828
+ ...new Set(
6829
+ messages.flatMap(
6830
+ (message) => message.threadId === null ? [] : [message.threadId]
6831
+ )
6832
+ )
6833
+ ]
6834
+ });
6835
+ var recordOf = (context, read, lead, values) => {
6836
+ const messages = read.messages === null ? null : inCampaign(read.messages, lead).toSorted(
6837
+ (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "")
6838
+ );
6839
+ const all = messages ?? [];
6840
+ const shown2 = all.slice(-values.max_messages);
6841
+ return {
6842
+ ...threadContext({
6843
+ lead: lead ?? null,
6844
+ meetingsRecorded: recordsMeetings(context.outbound),
6845
+ messages,
6846
+ notRead: read.failed ?? void 0,
6847
+ now: context.now,
6848
+ provider: lead?.provider ?? all[0]?.provider ?? context.outbound.provider
6849
+ }),
6850
+ ...partyOf(lead, all),
6851
+ lead: leadRefOf(read),
6852
+ messages: shown2.map(
6853
+ (message) => toMessage(message, values.bodies === "snippet")
6854
+ ),
6855
+ messagesOmitted: all.length - shown2.length,
6856
+ target: read.target
6857
+ };
6858
+ };
6859
+ var coverageOf = (records, reads, page) => {
6860
+ const end = page.start + reads.length;
6861
+ return {
6862
+ checked: reads.filter((read) => read.failed === null).length,
6863
+ found: records.filter((record) => record.activity.messagesRead > 0).length,
6864
+ nextCursor: end < page.total ? `${end}/${page.total}` : null,
6865
+ notFound: records.flatMap(
6866
+ (record, index) => reads[index]?.failed === null && record.activity.messagesRead === 0 ? [{ reason: "read, with no messages", target: record.target }] : []
6867
+ ),
6868
+ remaining: page.total - end,
6869
+ requested: page.total,
6870
+ unchecked: reads.flatMap(
6871
+ (read) => read.failed === null ? [] : [{ reason: read.failed, target: read.target }]
6872
+ )
6873
+ };
6874
+ };
6875
+ var markUnread = (context, reads, refs, leads) => {
6876
+ const failed = reads.filter((read) => read.failed !== null).length;
6877
+ if (failed > 0) {
6878
+ context.partial(
6879
+ `${failed} of ${plural(reads.length, "conversation")} on this page could not be read, so who wrote last is unknown there; coverage.unchecked names each with why.`
6880
+ );
6881
+ }
6882
+ const leadsUnread = context.outbound.capabilities["leads.get"] ? refs.filter((ref) => !leads.has(ref)).length : 0;
6883
+ if (leadsUnread > 0) {
6884
+ context.partial(
6885
+ `${leadsUnread} of ${plural(refs.length, "lead")} could not be read, so their meetings and labels are unknown; each record's followUp.unchecked says so.`
6886
+ );
6887
+ }
6888
+ };
6889
+ var threadContexts = defineInsight({
6890
+ 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.",
6891
+ inputSchema: input22,
6892
+ key: "threadContext",
6893
+ cost: (values, price) => {
6894
+ const conversations = Math.min(
6895
+ values.page_size,
6896
+ new Set(values.leads).size + new Set(values.threads).size
6897
+ );
6898
+ return conversations * price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.upTo(conversations) * price.one("leads.get"));
6899
+ },
6900
+ name: "thread_context",
6901
+ needs: ["messages.list"],
6902
+ needsFor: ({ leads, threads }) => [
6903
+ ...leads.length > 0 ? ["leads.timeline"] : [],
6904
+ ...threads.length > 0 ? ["messages.byThread"] : []
6905
+ ],
6906
+ next: "Read each record's latest message before following up. Use person_summary with a lead ref for the person's other campaigns.",
6907
+ run: async (context, values) => {
6908
+ const targets = targetsOf(values);
6909
+ if (targets.length === 0) {
6910
+ context.note(
6911
+ "No lead refs or thread ids were given, so nothing was read. Pass leads or threads."
6912
+ );
6913
+ }
6914
+ const bodies = bodiesOf(context, values.bodies);
6915
+ refuseUnreadable(context, targets);
6916
+ const start = startOf(values.cursor, targets.length);
6917
+ const page = targets.slice(start, start + values.page_size);
6918
+ const reads = await mapConcurrent(
6919
+ page,
6920
+ (target) => readConversation(context, target, bodies === "snippet")
6921
+ );
6922
+ const refs = [
6923
+ ...new Set(
6924
+ reads.flatMap((read) => {
6925
+ const ref = leadRefOf(read);
6926
+ return ref === null ? [] : [ref];
6927
+ })
6928
+ )
6929
+ ];
6930
+ const leads = context.outbound.capabilities["leads.get"] ? await readByRef(
6931
+ context,
6932
+ refs,
6933
+ (each) => context.outbound.leads.getMany(each),
6934
+ ["lead", "leads"],
6935
+ "meetings and labels are unknown"
6936
+ ) : /* @__PURE__ */ new Map();
6937
+ const records = reads.map((read) => {
6938
+ const ref = leadRefOf(read);
6939
+ return recordOf(
6940
+ context,
6941
+ read,
6942
+ ref === null ? void 0 : leads.get(ref),
6943
+ { ...values, bodies }
6944
+ );
6945
+ });
6946
+ markUnread(context, reads, refs, leads);
6947
+ if (start + page.length < targets.length) {
6948
+ context.partial(
6949
+ `Read ${start + page.length} of ${targets.length} conversations; pass coverage.nextCursor for the rest.`
6950
+ );
6951
+ }
6952
+ const answer = {
6953
+ coverage: coverageOf(records, reads, { start, total: targets.length }),
6954
+ threads: records
6955
+ };
6956
+ return answer;
6957
+ }
6958
+ });
6959
+
6056
6960
  // src/insights/people/index.ts
6057
6961
  var PEOPLE_INSIGHTS = [
6058
6962
  personSummary,
@@ -6061,22 +6965,23 @@ var PEOPLE_INSIGHTS = [
6061
6965
  suppressionCheck,
6062
6966
  droppedReplies,
6063
6967
  hotLeads,
6968
+ threadContexts,
6064
6969
  personalizationGaps
6065
6970
  ];
6066
6971
 
6067
6972
  // src/insights/senders/bounce-watch.ts
6068
- import { z as z25 } from "zod";
6973
+ import { z as z26 } from "zod";
6069
6974
 
6070
6975
  // src/insights/senders/read.ts
6071
6976
  var readCampaigns = async (context, statuses, max) => {
6072
6977
  const { items } = await readCampaignsIn(context, statuses, max);
6073
6978
  return items;
6074
6979
  };
6075
- var readCampaignSenders = async (context, campaign, max, input28) => {
6980
+ var readCampaignSenders = async (context, campaign, max, input29) => {
6076
6981
  const { items } = await readCapped(
6077
6982
  context,
6078
6983
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
6079
- { input: input28, max, per: "campaigns", what: "senders" }
6984
+ { input: input29, max, per: "campaigns", what: "senders" }
6080
6985
  );
6081
6986
  return items;
6082
6987
  };
@@ -6098,6 +7003,24 @@ var readHealth = async (context, sender) => {
6098
7003
  return null;
6099
7004
  }
6100
7005
  };
7006
+ var readHealthInPages = async (context, senders2, max) => {
7007
+ const { items } = await readCapped(
7008
+ context,
7009
+ (cap) => context.outbound.senderHealth.listAll({ max: cap }),
7010
+ { input: "max_senders", max, what: "senders' health" }
7011
+ );
7012
+ const byRef = new Map(items.map((health) => [health.senderRef, health]));
7013
+ const missing2 = senders2.filter((sender) => !byRef.has(sender.ref)).length;
7014
+ if (missing2 > 0) {
7015
+ context.partial(
7016
+ `Left out ${missing2} of ${senders2.length} senders: the vendor returned no health for them.`
7017
+ );
7018
+ }
7019
+ return senders2.map((sender) => ({
7020
+ health: byRef.get(sender.ref) ?? null,
7021
+ sender
7022
+ }));
7023
+ };
6101
7024
  var domainOf2 = (address2) => {
6102
7025
  const domain = address2?.split("@")[1]?.trim().toLowerCase() ?? "";
6103
7026
  return domain === "" ? null : domain;
@@ -6120,15 +7043,15 @@ var countEach = (keys, count2) => (
6120
7043
  );
6121
7044
 
6122
7045
  // src/insights/senders/bounce-watch.ts
6123
- var input22 = z25.object({
7046
+ var input23 = z26.object({
6124
7047
  ...rangeFields,
6125
- include_senders: z25.boolean().default(true).describe(
7048
+ include_senders: z26.boolean().default(true).describe(
6126
7049
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
6127
7050
  ),
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(
7051
+ max_bounce_rate: z26.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
7052
+ max_campaigns: z26.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
7053
+ 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"),
7054
+ min_sent: z26.number().int().min(0).default(100).describe(
6132
7055
  "A campaign or sender with fewer sends than this is too small to judge"
6133
7056
  ),
6134
7057
  statuses: statusesInput(["active"])
@@ -6200,7 +7123,7 @@ var canCheckSenders = (context, wanted) => {
6200
7123
  };
6201
7124
  var bounceWatch = defineInsight({
6202
7125
  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,
7126
+ inputSchema: input23,
6204
7127
  key: "bounceWatch",
6205
7128
  cost: (values, price) => {
6206
7129
  const campaigns = price.campaigns(values.max_campaigns);
@@ -6307,10 +7230,15 @@ var bounceWatch = defineInsight({
6307
7230
  });
6308
7231
 
6309
7232
  // 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(
7233
+ import { z as z27 } from "zod";
7234
+ var CHECKED_ONE_BY_ONE = 50;
7235
+ var inPages = (capabilities) => capabilities["senders.healthList"];
7236
+ var sendersToCheck = (capabilities, max) => max ?? (inPages(capabilities) ? SCREENED_AT_MOST : CHECKED_ONE_BY_ONE);
7237
+ var input24 = z27.object({
7238
+ max_senders: z27.number().int().min(1).max(500).optional().describe(
7239
+ `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.`
7240
+ ),
7241
+ max_spam_rate: z27.number().min(0).max(1).default(0.1).describe(
6314
7242
  "A domain whose warmup emails land in spam more often than this share is high risk"
6315
7243
  )
6316
7244
  });
@@ -6405,20 +7333,24 @@ var seatRank = (seat) => {
6405
7333
  return seat.connected === null ? 1 : 2;
6406
7334
  };
6407
7335
  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,
7336
+ 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`.",
7337
+ inputSchema: input24,
6410
7338
  key: "domainHealth",
6411
- cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
7339
+ cost: (values, price) => {
7340
+ const max = sendersToCheck(price.capabilities, values.max_senders);
7341
+ return price.list("senders.list", max) + (inPages(price.capabilities) ? price.list("senders.healthList", max) : price.upTo(max) * price.one("senders.health"));
7342
+ },
6412
7343
  scales: "max_senders",
6413
7344
  name: "domain_health",
6414
7345
  needs: ["senders.list", "senders.health"],
6415
7346
  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
7347
  run: async (context, { max_senders: maxSenders, max_spam_rate: threshold }) => {
6417
- const { items: senders2 } = await readSenders(context, maxSenders);
7348
+ const max = sendersToCheck(context.outbound.capabilities, maxSenders);
7349
+ const { items: senders2 } = await readSenders(context, max);
6418
7350
  const byDomain = /* @__PURE__ */ new Map();
6419
7351
  const linkedinSeats = [];
6420
7352
  const mailboxesWithoutDomain = [];
6421
- const read = await mapConcurrent(senders2, async (sender) => ({
7353
+ const read = inPages(context.outbound.capabilities) ? await readHealthInPages(context, senders2, max) : await mapConcurrent(senders2, async (sender) => ({
6422
7354
  health: await readHealth(context, sender),
6423
7355
  sender
6424
7356
  }));
@@ -6468,7 +7400,7 @@ var domainHealth = defineInsight({
6468
7400
  });
6469
7401
 
6470
7402
  // src/insights/senders/sender-capacity.ts
6471
- import { z as z27 } from "zod";
7403
+ import { z as z28 } from "zod";
6472
7404
 
6473
7405
  // src/insights/senders/capacity-sends.ts
6474
7406
  var dailyRows = async (context, campaigns, range) => {
@@ -6568,15 +7500,15 @@ var readSends = async (context, campaigns, days, senders2, split) => {
6568
7500
  };
6569
7501
 
6570
7502
  // 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(
7503
+ var input25 = z28.object({
7504
+ days: z28.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
7505
+ max_campaigns: z28.number().int().min(1).max(200).default(50).describe(
6574
7506
  "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
7507
  ),
6576
- max_senders: z27.number().int().min(1).max(1e3).default(1e3).describe(
7508
+ max_senders: z28.number().int().min(1).max(1e3).default(1e3).describe(
6577
7509
  "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
7510
  ),
6579
- split_uncounted: z27.boolean().default(false).describe(
7511
+ split_uncounted: z28.boolean().default(false).describe(
6580
7512
  "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
7513
  )
6582
7514
  });
@@ -6642,7 +7574,7 @@ var askOf = (reads) => {
6642
7574
  withoutLimit: reads.length - withLimit
6643
7575
  };
6644
7576
  };
6645
- var findingOf3 = (capacity, ask, sends) => {
7577
+ var findingOf5 = (capacity, ask, sends) => {
6646
7578
  if (capacity.daily === null) {
6647
7579
  return "No active sender reports a daily limit, so capacity is unknown.";
6648
7580
  }
@@ -6664,7 +7596,7 @@ var findingOf3 = (capacity, ask, sends) => {
6664
7596
  };
6665
7597
  var senderCapacity = defineInsight({
6666
7598
  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,
7599
+ inputSchema: input25,
6668
7600
  key: "senderCapacity",
6669
7601
  cost: (values, price) => {
6670
7602
  const { capabilities } = price;
@@ -6712,7 +7644,7 @@ var senderCapacity = defineInsight({
6712
7644
  ask,
6713
7645
  askRatio: rate(ask?.daily ?? null, capacity.daily),
6714
7646
  capacity,
6715
- finding: findingOf3(capacity, ask, sends),
7647
+ finding: findingOf5(capacity, ask, sends),
6716
7648
  sends,
6717
7649
  shortCampaigns: canCompare ? shortfalls.flatMap(
6718
7650
  (each) => each === null || each === "unchecked" ? [] : [each]
@@ -6728,13 +7660,13 @@ var senderCapacity = defineInsight({
6728
7660
  });
6729
7661
 
6730
7662
  // 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(
7663
+ import { z as z29 } from "zod";
7664
+ var input26 = z29.object({
7665
+ max_campaigns: z29.number().int().min(1).max(200).default(50).describe(
6734
7666
  "The most campaigns to read. Each costs one listing of its senders."
6735
7667
  ),
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(
7668
+ max_campaigns_per_sender: z29.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
7669
+ max_senders: z29.number().int().min(1).max(1e3).default(1e3).describe(
6738
7670
  "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
7671
  ),
6740
7672
  statuses: statusesInput(["active"])
@@ -6768,7 +7700,7 @@ var riskOf = (campaign, senders2) => {
6768
7700
  };
6769
7701
  var senderLoad = defineInsight({
6770
7702
  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,
7703
+ inputSchema: input26,
6772
7704
  key: "senderLoad",
6773
7705
  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
7706
  scales: "max_campaigns",
@@ -6848,18 +7780,18 @@ var senderLoad = defineInsight({
6848
7780
  });
6849
7781
 
6850
7782
  // 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(
7783
+ import { z as z30 } from "zod";
7784
+ var input27 = z30.object({
7785
+ max_campaigns: z30.number().int().min(1).max(200).default(25).describe(
6854
7786
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
6855
7787
  ),
6856
- max_daily_limit_per_sender: z29.number().min(1).default(50).describe(
7788
+ max_daily_limit_per_sender: z30.number().min(1).default(50).describe(
6857
7789
  "The sends a day assumed for an attached sender when the senders' own daily limits are not reported"
6858
7790
  ),
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"),
7791
+ max_senders_per_campaign: z30.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
7792
+ max_window_hours: z30.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
7793
+ min_gap_minutes: z30.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
7794
+ min_window_hours: z30.number().min(0).max(24).default(2).describe("A sending window shorter than this many hours is flagged"),
6863
7795
  statuses: statusesInput(["active"])
6864
7796
  });
6865
7797
  var SEVERITY2 = {
@@ -6999,7 +7931,7 @@ var countChecks = (campaigns) => countEach(
6999
7931
  );
7000
7932
  var settingsAudit = defineInsight({
7001
7933
  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,
7934
+ inputSchema: input27,
7003
7935
  key: "settingsAudit",
7004
7936
  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
7937
  scales: "max_campaigns",
@@ -7065,18 +7997,18 @@ var settingsAudit = defineInsight({
7065
7997
  });
7066
7998
 
7067
7999
  // 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(
8000
+ import { z as z31 } from "zod";
8001
+ var input28 = z31.object({
8002
+ check_health: z31.boolean().default(false).describe(
7071
8003
  "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
7072
8004
  ),
7073
- max_senders: z30.number().int().min(1).max(1e3).default(1e3).describe(
8005
+ max_senders: z31.number().int().min(1).max(1e3).default(1e3).describe(
7074
8006
  "The most senders to check. The listing costs 1 request per 100 senders."
7075
8007
  ),
7076
- max_spam_rate: z30.number().min(0).max(1).default(0.1).describe(
8008
+ max_spam_rate: z31.number().min(0).max(1).default(0.1).describe(
7077
8009
  "With check_health, a mailbox whose warmup emails land in spam more often than this share is not ready"
7078
8010
  ),
7079
- min_score: z30.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
8011
+ min_score: z31.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
7080
8012
  });
7081
8013
  var READINESS_REASONS = [
7082
8014
  "not_active",
@@ -7143,7 +8075,7 @@ var countReasons = (judged) => countEach(
7143
8075
  );
7144
8076
  var warmupReadiness = defineInsight({
7145
8077
  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,
8078
+ inputSchema: input28,
7147
8079
  key: "warmupReadiness",
7148
8080
  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
8081
  scales: "max_senders",
@@ -7208,10 +8140,102 @@ var INSIGHTS = [
7208
8140
  ];
7209
8141
  var ENTRIES = INSIGHTS;
7210
8142
 
8143
+ // src/insights/plugin.ts
8144
+ var entryNamed = (outbound, name) => {
8145
+ const entry = ENTRIES.find(
8146
+ (candidate) => candidate.name === name || candidate.key === name
8147
+ );
8148
+ if (entry === void 0) {
8149
+ throw new OutboundError(
8150
+ "Invalid",
8151
+ `There is no insight "${name}". Known: ${ENTRIES.map((each) => each.name).join(", ")}`,
8152
+ { provider: outbound.provider }
8153
+ );
8154
+ }
8155
+ return entry;
8156
+ };
8157
+ var runInsightByName = async (outbound, name, input29 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input29, options);
8158
+ var insightCost = (outbound, name, input29 = {}) => {
8159
+ const entry = entryNamed(outbound, name);
8160
+ const parsed = entry.inputSchema.safeParse(input29);
8161
+ if (!parsed.success) {
8162
+ throw new OutboundError(
8163
+ "Invalid",
8164
+ `${entry.name}: ${parsed.error.issues[0]?.message ?? "the input is not valid"}`,
8165
+ { provider: outbound.provider }
8166
+ );
8167
+ }
8168
+ const bounds = boundsOf(outbound, entry.cost, parsed.data);
8169
+ return bounds === null ? null : { ...bounds, defaultCap: defaultCap(bounds) };
8170
+ };
8171
+ var listInsights = () => ENTRIES.map((entry) => ({
8172
+ description: entry.description,
8173
+ key: entry.key,
8174
+ name: entry.name,
8175
+ needs: [...entry.needs],
8176
+ // SAFETY: a JSON Schema document is JSON by definition.
8177
+ parameters: z32.toJSONSchema(entry.inputSchema, { io: "input" })
8178
+ }));
8179
+ var insights = () => ({
8180
+ extend: (outbound) => {
8181
+ const methods = {};
8182
+ for (const entry of ENTRIES) {
8183
+ methods[entry.key] = (input29, options) => (
8184
+ // SAFETY: the answer is the entry's own, typed per key by Insights.
8185
+ entry.execute(outbound, input29, options)
8186
+ );
8187
+ }
8188
+ return { insights: methods };
8189
+ },
8190
+ name: "insights"
8191
+ });
8192
+
7211
8193
  // src/insights/tools.ts
7212
8194
  var INSIGHT_TOOL_CEILING = 500;
7213
8195
  var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
7214
8196
  var ANSWER_NOTE = "The answer is in data, in camelCase like every insight's answer. meta.complete: false means it covers part of the data, and meta.notes says why.";
8197
+ var COMBINED2 = "combined";
8198
+ var membersOf = async (outbound) => {
8199
+ if (outbound.provider !== COMBINED2) {
8200
+ return [];
8201
+ }
8202
+ const { items } = await outbound.workspaces.list();
8203
+ return items.map(
8204
+ (tool) => outbound.workspace(`${tool.provider}:${tool.workspaceId}`)
8205
+ );
8206
+ };
8207
+ var labelOf2 = (outbound) => `${outbound.provider}:${outbound.workspaceId}`;
8208
+ var servesOn = (outbound, definition) => definition.needs.every((key) => outbound.capabilities[key] !== false) && (definition.lacks?.(outbound) ?? null) === null && maskedOutBy(outbound, definition) === null;
8209
+ var takesCampaign = (definition) => Object.hasOwn(definition.inputSchema.shape, "campaign");
8210
+ var placementOf = (outbound, definition, members) => {
8211
+ if (servesOn(outbound, definition)) {
8212
+ return { servers: [], target: outbound };
8213
+ }
8214
+ const servers = members.filter((member) => servesOn(member, definition));
8215
+ const [only] = servers;
8216
+ if (only === void 0) {
8217
+ return void 0;
8218
+ }
8219
+ if (takesCampaign(definition)) {
8220
+ return { servers, target: outbound };
8221
+ }
8222
+ return servers.length === 1 ? { servers, target: only } : void 0;
8223
+ };
8224
+ var insightPlacement = (outbound, name, members) => {
8225
+ const definition = ENTRIES.find((entry) => entry.name === name);
8226
+ const placed = definition === void 0 ? void 0 : placementOf(outbound, definition, members);
8227
+ if (placed === void 0 || placed.target === outbound) {
8228
+ return placed === void 0 ? void 0 : { ...placed, note: null };
8229
+ }
8230
+ const others = members.flatMap((member) => {
8231
+ const why = member === placed.target ? void 0 : insightLeftOutReason(member, name);
8232
+ return why === void 0 ? [] : [why];
8233
+ });
8234
+ return {
8235
+ ...placed,
8236
+ note: `Covers ${labelOf2(placed.target)} only, the one tool on this instance that serves ${name}. ${others.join(". ")}.`
8237
+ };
8238
+ };
7215
8239
  var hintFor = (next, offered) => {
7216
8240
  const hidden = ENTRIES.flatMap(
7217
8241
  (entry) => offered.has(entry.name) ? [] : [entry.name]
@@ -7219,33 +8243,58 @@ var hintFor = (next, offered) => {
7219
8243
  const kept = next.split(/(?<=\.)\s+/u).filter((sentence2) => !hidden.some((name) => sentence2.includes(name)));
7220
8244
  return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
7221
8245
  };
7222
- var toTool = (outbound, definition, next, options) => ({
8246
+ var withOfferedNext = (value, offered) => {
8247
+ if (Array.isArray(value)) {
8248
+ return value.map((item) => withOfferedNext(item, offered));
8249
+ }
8250
+ if (!isJsonObject(value)) {
8251
+ return value;
8252
+ }
8253
+ return Object.fromEntries(
8254
+ Object.entries(value).map(([key, item]) => [
8255
+ key,
8256
+ key === "next" && isString(item) ? hintFor(item, offered) : withOfferedNext(item, offered)
8257
+ ])
8258
+ );
8259
+ };
8260
+ var REMEDY = /(?:[:;.]|,\s*so)\s+(?<remedy>(?:pass|give|use|start|run|name|ask)\s[^;]*?)\.?$/iu;
8261
+ var unsupportedNext = (name, message, servers) => {
8262
+ if (servers.length > 0) {
8263
+ return `On this instance only ${servers.map(labelOf2).join(" and ")} can serve ${name}: call it again with a campaign of ${servers.length === 1 ? "that tool" : "one of them"}, by its ref or name.`;
8264
+ }
8265
+ const remedy = REMEDY.exec(message)?.groups?.remedy;
8266
+ return remedy === void 0 ? "This insight cannot answer here, and the message says why. Pick another of the listed tools." : `Call ${name} again and ${remedy}.`;
8267
+ };
8268
+ var toTool = (outbound, definition, placement, offered, options) => ({
7223
8269
  call: async (given, callOptions) => {
7224
8270
  const set = callOptions?.maxRequests ?? options.maxRequestsPerToolCall;
7225
8271
  const capSetting = options.capSetting ?? "maxRequestsPerToolCall";
7226
8272
  try {
7227
- const input28 = jsonInput(given);
7228
- if (input28 === void 0) {
8273
+ const input29 = jsonInput(given);
8274
+ if (input29 === void 0) {
7229
8275
  throw new OutboundError(
7230
8276
  "Invalid",
7231
8277
  `${definition.name}: the input is not JSON`
7232
8278
  );
7233
8279
  }
8280
+ const { target } = placement;
8281
+ const note = target === outbound ? null : insightPlacement(outbound, definition.name, options.members ?? [])?.note ?? null;
7234
8282
  const result = await definition.execute(
7235
- outbound,
7236
- input28,
8283
+ target,
8284
+ input29,
7237
8285
  set === void 0 ? { capCeiling: INSIGHT_TOOL_CEILING, capSetting } : { capSetting, maxRequests: set }
7238
8286
  );
7239
8287
  return {
7240
- data: result.data,
8288
+ data: withOfferedNext(result.data, offered),
7241
8289
  meta: {
7242
- complete: result.meta.complete,
8290
+ complete: result.meta.complete && note === null,
8291
+ computedAt: result.meta.computedAt,
7243
8292
  evidence: result.meta.evidence,
7244
- notes: [...result.meta.notes],
8293
+ notes: note === null ? [...result.meta.notes] : [note, ...result.meta.notes],
7245
8294
  provider: result.meta.provider,
7246
8295
  requests: result.meta.requests
7247
8296
  },
7248
- next,
8297
+ next: hintFor(definition.next, offered),
7249
8298
  ok: true
7250
8299
  };
7251
8300
  } catch (error) {
@@ -7260,7 +8309,7 @@ var toTool = (outbound, definition, next, options) => ({
7260
8309
  return failure(
7261
8310
  error,
7262
8311
  void 0,
7263
- OutboundError.is(error) && error.code === "Unsupported" ? "This insight cannot answer here; the message says why. Try another tool." : void 0
8312
+ OutboundError.is(error) && error.code === "Unsupported" ? unsupportedNext(definition.name, error.message, placement.servers) : void 0
7264
8313
  );
7265
8314
  }
7266
8315
  },
@@ -7269,13 +8318,17 @@ var toTool = (outbound, definition, next, options) => ({
7269
8318
  name: definition.name,
7270
8319
  needs: [...definition.needs],
7271
8320
  // SAFETY: a JSON Schema document is JSON by definition.
7272
- parameters: z31.toJSONSchema(definition.inputSchema, { io: "input" })
8321
+ parameters: z33.toJSONSchema(definition.inputSchema, { io: "input" })
7273
8322
  });
7274
- var insightLeftOutReason = (outbound, name) => {
8323
+ var insightLeftOutReason = (outbound, name, members = []) => {
7275
8324
  const definition = ENTRIES.find((entry) => entry.name === name);
7276
- if (definition === void 0) {
8325
+ if (definition === void 0 || placementOf(outbound, definition, members) !== void 0) {
7277
8326
  return void 0;
7278
8327
  }
8328
+ const servers = members.filter((member) => servesOn(member, definition));
8329
+ if (servers.length > 1) {
8330
+ return `${name} is not available on a combined instance: it reads every campaign, and only ${servers.map(labelOf2).join(" and ")} can serve it. Ask one of them`;
8331
+ }
7279
8332
  const lacked = definition.lacks?.(outbound) ?? null;
7280
8333
  const absent = definition.needs.filter(
7281
8334
  (key) => outbound.capabilities[key] === false
@@ -7283,22 +8336,43 @@ var insightLeftOutReason = (outbound, name) => {
7283
8336
  if (lacked !== null) {
7284
8337
  return `${name} is not available: the ${outbound.provider} adapter does not report ${lacked}`;
7285
8338
  }
7286
- return absent.length > 0 ? `${name} is not available: the ${outbound.provider} adapter does not support ${absent.join(", ")}` : maskedOutBy(outbound, definition) ?? void 0;
8339
+ if (absent.length > 0) {
8340
+ return `${name} is not available: the ${outbound.provider} adapter does not support ${absent.join(", ")}`;
8341
+ }
8342
+ const masked = maskedOutBy(outbound, definition);
8343
+ return masked === null ? void 0 : `${name} is not available while the redact plugin masks ${masked}`;
7287
8344
  };
7288
8345
  var insightTools = (outbound, options = {}) => {
7289
8346
  const wanted = options.only === void 0 ? void 0 : new Set(options.only);
7290
- const offered = ENTRIES.filter(
7291
- (definition) => (wanted === void 0 || wanted.has(definition.name)) && definition.needs.every((key) => outbound.capabilities[key] !== false) && (definition.lacks?.(outbound) ?? null) === null && maskedOutBy(outbound, definition) === null
7292
- );
7293
- const names = new Set(offered.map((definition) => definition.name));
8347
+ const members = options.members ?? [];
8348
+ const offered = ENTRIES.flatMap((definition) => {
8349
+ const placement = wanted === void 0 || wanted.has(definition.name) ? placementOf(outbound, definition, members) : void 0;
8350
+ return placement === void 0 ? [] : [{ definition, placement }];
8351
+ });
8352
+ const names = new Set(offered.map(({ definition }) => definition.name));
7294
8353
  return offered.map(
7295
- (definition) => toTool(outbound, definition, hintFor(definition.next, names), options)
8354
+ ({ definition, placement }) => toTool(outbound, definition, placement, names, options)
8355
+ );
8356
+ };
8357
+ var runPlaced = async (outbound, name, input29, members, options) => {
8358
+ const placed = insightPlacement(outbound, name, members);
8359
+ const result = await runInsightByName(
8360
+ placed?.target ?? outbound,
8361
+ name,
8362
+ input29,
8363
+ options
7296
8364
  );
8365
+ return placed?.note === null || placed?.note === void 0 ? result : {
8366
+ ...result,
8367
+ meta: {
8368
+ ...result.meta,
8369
+ complete: false,
8370
+ notes: [placed.note, ...result.meta.notes]
8371
+ }
8372
+ };
7297
8373
  };
7298
8374
 
7299
8375
  export {
7300
- boundsOf,
7301
- defaultCap,
7302
8376
  defineInsight,
7303
8377
  runInsight,
7304
8378
  round,
@@ -7313,8 +8387,14 @@ export {
7313
8387
  compareRates,
7314
8388
  tally,
7315
8389
  INSIGHTS,
7316
- ENTRIES,
8390
+ runInsightByName,
8391
+ insightCost,
8392
+ listInsights,
8393
+ insights,
7317
8394
  INSIGHT_TOOL_CEILING,
8395
+ membersOf,
8396
+ insightPlacement,
7318
8397
  insightLeftOutReason,
7319
- insightTools
8398
+ insightTools,
8399
+ runPlaced
7320
8400
  };