outbound-sdk 0.12.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 (67) hide show
  1. package/dist/alerts/index.js +1 -1
  2. package/dist/budget/index.js +1 -1
  3. package/dist/cards/index.js +16 -8
  4. package/dist/chunks/{chunk-AWNH4I5D.js → chunk-6BSFR5SF.js} +3 -0
  5. package/dist/chunks/{chunk-KNWJIJVO.js → chunk-BTIJ24UY.js} +17 -6
  6. package/dist/chunks/{chunk-HDTOGEVN.js → chunk-EAG5NIPM.js} +85 -27
  7. package/dist/chunks/{chunk-B72F56HF.js → chunk-FT6HMMMP.js} +1 -1
  8. package/dist/chunks/{chunk-CTRYCW4G.js → chunk-LJNU4LAR.js} +1471 -857
  9. package/dist/chunks/{chunk-HXCZMMSD.js → chunk-NLYGMVXS.js} +9 -0
  10. package/dist/chunks/{chunk-3DDYXUDG.js → chunk-OE45PREW.js} +1 -1
  11. package/dist/chunks/{chunk-2ADIGC2N.js → chunk-OP2GL7ZT.js} +2 -2
  12. package/dist/chunks/{chunk-UIINRLHQ.js → chunk-PDYE6CWS.js} +130 -62
  13. package/dist/chunks/{chunk-UWNQEQIX.js → chunk-PUIHJFK4.js} +1 -1
  14. package/dist/chunks/{tools-EKLZKXZU.js → tools-VCCH3JNL.js} +11 -5
  15. package/dist/cli/bin.js +9 -9
  16. package/dist/cli/config.d.ts +0 -2
  17. package/dist/cli/index.js +8 -8
  18. package/dist/cli/offered.d.ts +31 -2
  19. package/dist/cli/serve.d.ts +4 -2
  20. package/dist/combine/index.js +26 -4
  21. package/dist/emailbison/index.js +2 -2
  22. package/dist/fixtures/index.js +1 -1
  23. package/dist/heyreach/index.js +4 -1
  24. package/dist/index.js +3 -3
  25. package/dist/insights/capped.d.ts +14 -1
  26. package/dist/insights/define.d.ts +7 -5
  27. package/dist/insights/index.d.ts +1 -1
  28. package/dist/insights/index.js +10 -60
  29. package/dist/insights/inputs.generated.d.ts +26 -14
  30. package/dist/insights/ops/campaign-ranking.d.ts +8 -1
  31. package/dist/insights/ops/client-report.d.ts +28 -18
  32. package/dist/insights/ops/client-runway.d.ts +43 -0
  33. package/dist/insights/ops/index.d.ts +6 -1
  34. package/dist/insights/ops/period-comparison.d.ts +23 -1
  35. package/dist/insights/ops/pipeline-forecast.d.ts +14 -9
  36. package/dist/insights/ops/shared.d.ts +38 -1
  37. package/dist/insights/people/coverage.d.ts +26 -0
  38. package/dist/insights/people/dropped-replies-check.d.ts +5 -1
  39. package/dist/insights/people/dropped-replies.d.ts +6 -2
  40. package/dist/insights/people/index.d.ts +2 -2
  41. package/dist/insights/people/lead-collisions.d.ts +18 -1
  42. package/dist/insights/people/suppression-check.d.ts +18 -1
  43. package/dist/insights/people/thread-contexts.d.ts +2 -2
  44. package/dist/insights/people/thread-read.d.ts +11 -0
  45. package/dist/insights/registry.d.ts +6 -2
  46. package/dist/insights/tools.d.ts +35 -2
  47. package/dist/instantly/index.js +108 -22
  48. package/dist/instantly/lead-ids.d.ts +11 -0
  49. package/dist/instantly/map-lead.d.ts +19 -2
  50. package/dist/internal/entities.d.ts +4 -1
  51. package/dist/internal/fields.d.ts +2 -0
  52. package/dist/internal/reply-people.d.ts +25 -7
  53. package/dist/internal/runway.d.ts +38 -5
  54. package/dist/loader/index.js +1 -1
  55. package/dist/memory/index.js +1 -1
  56. package/dist/redact/index.d.ts +1 -1
  57. package/dist/redact/index.js +59 -28
  58. package/dist/redact/plugin.d.ts +13 -11
  59. package/dist/redact/tokens.d.ts +18 -1
  60. package/dist/smartlead/index.js +4 -1
  61. package/dist/tools/ai-sdk.js +3 -3
  62. package/dist/tools/claude-agent.js +3 -3
  63. package/dist/tools/index.js +4 -4
  64. package/dist/tools/registry.d.ts +8 -1
  65. package/dist/webhooks/index.js +2 -2
  66. package/package.json +1 -1
  67. /package/dist/chunks/{chunk-TOZKA7JR.js → chunk-HNYJO6B4.js} +0 -0
@@ -11,12 +11,13 @@ import {
11
11
  personFields,
12
12
  personOf,
13
13
  routedByCampaign,
14
- runwayDays,
14
+ runwayOf,
15
+ runwayStatus,
15
16
  splitActive,
16
17
  untrusted,
17
18
  warmupAtZero,
18
19
  withCampaign
19
- } from "./chunk-KNWJIJVO.js";
20
+ } from "./chunk-BTIJ24UY.js";
20
21
  import {
21
22
  count,
22
23
  percentOf,
@@ -45,7 +46,7 @@ import {
45
46
  } from "./chunk-FALWG5U3.js";
46
47
  import {
47
48
  leadStatusSchema
48
- } from "./chunk-HXCZMMSD.js";
49
+ } from "./chunk-NLYGMVXS.js";
49
50
  import {
50
51
  CONTACTED_LEADS_LIMIT,
51
52
  contactedBeyondLeads,
@@ -67,13 +68,15 @@ import {
67
68
  } from "./chunk-XYHM4KHC.js";
68
69
  import {
69
70
  emailAddress,
71
+ isJsonObject,
72
+ isString,
70
73
  jsonInput,
71
74
  toJson,
72
75
  unknownKey
73
76
  } from "./chunk-45TXPJW7.js";
74
77
 
75
78
  // src/insights/tools.ts
76
- import { z as z32 } from "zod";
79
+ import { z as z33 } from "zod";
77
80
 
78
81
  // src/insights/cost.ts
79
82
  var UNKNOWN = /* @__PURE__ */ Symbol("unknown cost");
@@ -449,12 +452,13 @@ var track = (cap, now, partialOnCap) => {
449
452
  return stats.rows;
450
453
  }
451
454
  },
452
- // 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.
453
457
  meta: () => ({
454
458
  complete,
455
459
  evidence,
456
460
  notes: [...notes],
457
- requests: absorbed ? Math.max(requests, cap.used()) : requests
461
+ requests: Math.max(requests, cap.used())
458
462
  })
459
463
  };
460
464
  };
@@ -540,7 +544,7 @@ var execute = async (outbound, spec, input29, options = {}) => {
540
544
  }
541
545
  const cap = runCap(target, priced(target, spec, checked), checked, options);
542
546
  const now = options.now ?? Date.now();
543
- const tracker = track(cap, now, spec.partialOnCap === true);
547
+ const tracker = track(cap, now, spec.partialOnCap !== false);
544
548
  const data = await withCampaign(
545
549
  tracker.context.outbound,
546
550
  checked,
@@ -578,108 +582,407 @@ var runInsight = (outbound, definition, input29, options = {}) => (
578
582
  execute(outbound, definition, input29, options)
579
583
  );
580
584
 
585
+ // src/insights/plugin.ts
586
+ import { z as z32 } from "zod";
587
+
581
588
  // src/insights/copy/copy-audit.ts
582
589
  import { z as z4 } from "zod";
583
590
 
584
- // src/insights/people/read.ts
585
- import { z as z2 } from "zod";
586
-
587
- // src/insights/capped.ts
588
- var readCapped = async (context, open, cap, room = cap.max) => {
589
- if (room >= 1) {
590
- const walk = open(room);
591
- const items = await context.all(walk, cap);
592
- return { capped: walk.truncated || wasCutShort(items), items };
593
- }
594
- const probe = open(1);
595
- const left = await context.all(probe, cap);
596
- if (left.length > 0 && !probe.truncated) {
597
- 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;
598
636
  }
599
- 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;
600
641
  };
601
- var campaignsReadOf = (read) => ({
602
- campaignsRead: read.items.length,
603
- moreCampaignsExist: read.capped
604
- });
605
- var settledPage = async (read) => {
606
- try {
607
- return await read;
608
- } catch (error) {
609
- if (isCapStop(error)) {
610
- 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;
611
665
  }
612
- throw error;
613
666
  }
667
+ return { text: out + text.slice(at), unfilled };
614
668
  };
615
- var either = (words) => words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
616
- var othersCounted = (others, more) => {
617
- if (others.length === 0) {
618
- return void 0;
619
- }
620
- const counts = /* @__PURE__ */ new Map();
621
- for (const campaign of others) {
622
- counts.set(campaign.status, (counts.get(campaign.status) ?? 0) + 1);
623
- }
624
- const byStatus = [...counts].toSorted(([a], [b]) => a.localeCompare(b)).map(([status, count2]) => `${count2} ${status}`).join(", ");
625
- 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"
626
691
  };
627
- var noneMatched = (context, wanted, others, more) => {
628
- const counted2 = othersCounted(others, more);
629
- if (counted2 !== void 0) {
630
- context.partial(
631
- `No campaign is ${either(wanted)}, so nothing was checked (${counted2}). Pass statuses to check the others.`
632
- );
633
- }
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;
634
734
  };
635
- var countOthers = async (context, wanted, every) => {
636
- if (every !== void 0) {
637
- noneMatched(context, wanted, every, false);
638
- return;
639
- }
640
- const page = await settledPage(context.outbound.campaigns.list());
641
- if (page === null) {
642
- context.partial(
643
- `No campaign is ${either(wanted)}, so nothing was checked; a request cap stopped the count of the others.`
644
- );
645
- return;
646
- }
647
- 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) ?? []];
648
742
  };
649
- var toolNoneMatched = async (context, label, wanted, every) => {
650
- const none = `${label} has no campaign ${either(wanted)}, so it was not checked`;
651
- let counted2;
652
- if (every === void 0) {
653
- const page = await settledPage(context.outbound.campaigns.list());
654
- if (page === null) {
655
- return `${none}; a request cap stopped the count of its others.`;
656
- }
657
- counted2 = othersCounted(context.page(page), page.cursor !== void 0);
658
- } else {
659
- counted2 = othersCounted(every, false);
660
- }
661
- 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;
662
750
  };
663
- var fairShares = (counts, max) => {
664
- const shares = counts.map(() => 0);
665
- let left = max;
666
- const order2 = counts.map((_, index) => index).toSorted((a, b) => (counts[a] ?? 0) - (counts[b] ?? 0));
667
- for (const [at, index] of order2.entries()) {
668
- const share2 = Math.min(
669
- counts[index] ?? 0,
670
- Math.floor(left / (order2.length - at))
671
- );
672
- shares[index] = share2;
673
- left -= share2;
674
- }
675
- 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;
676
764
  };
677
- var readOne = async (context, wanted, cap) => {
678
- const { campaigns } = context.outbound;
679
- if (context.outbound.capabilities["campaigns.status"] === false) {
680
- const every = await readCapped(
681
- context,
682
- (room) => campaigns.listAll({ max: room }),
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;
982
+ if (context.outbound.capabilities["campaigns.status"] === false) {
983
+ const every = await readCapped(
984
+ context,
985
+ (room) => campaigns.listAll({ max: room }),
683
986
  cap
684
987
  );
685
988
  const items = every.items.filter(
@@ -709,6 +1012,8 @@ var readShared = async (context, wanted, cap) => {
709
1012
  const label = `${tool.provider}:${tool.workspaceId}`;
710
1013
  return {
711
1014
  label,
1015
+ provider: tool.provider,
1016
+ workspaceId: tool.workspaceId,
712
1017
  read: await readOne(
713
1018
  { ...context, outbound: outbound.workspace(label) },
714
1019
  wanted,
@@ -748,9 +1053,20 @@ var readShared = async (context, wanted, cap) => {
748
1053
  `${cap.input ?? "The cap"} is shared among the tools: ${read.map((each, index) => `${each.label} ${shares[index] ?? 0}`).join(", ")}.`
749
1054
  );
750
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
+ );
751
1066
  return {
752
1067
  capped: dropped || read.some((each) => each.read.capped),
753
- items
1068
+ items,
1069
+ skipped
754
1070
  };
755
1071
  };
756
1072
  var readCampaignsIn = async (context, statuses, max, input29 = "max_campaigns") => {
@@ -761,7 +1077,11 @@ var readCampaignsIn = async (context, statuses, max, input29 = "max_campaigns")
761
1077
  if (read.items.length === 0 && !read.capped) {
762
1078
  await countOthers(context, wanted, read.every);
763
1079
  }
764
- return { capped: read.capped, items: read.items };
1080
+ return {
1081
+ capped: read.capped,
1082
+ items: read.items,
1083
+ skipped: read.skipped ?? []
1084
+ };
765
1085
  };
766
1086
 
767
1087
  // src/insights/fields.ts
@@ -781,9 +1101,17 @@ var readByRef = async (context, refs, read, what, effect) => {
781
1101
  return /* @__PURE__ */ new Map();
782
1102
  }
783
1103
  const found = await read(refs);
784
- 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) {
785
1107
  context.note(
786
- `${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}`
787
1115
  );
788
1116
  }
789
1117
  const [costliest] = found.results.toSorted(
@@ -795,10 +1123,6 @@ var readByRef = async (context, refs, read, what, effect) => {
795
1123
  return new Map(found.results.map(({ id, value }) => [id, value]));
796
1124
  };
797
1125
  var statusesField = statusesInput(["active"]);
798
- var campaignsIn = async (context, statuses, max) => {
799
- const { items } = await readCampaignsIn(context, statuses, max);
800
- return items;
801
- };
802
1126
  var leadsOf = async (context, campaign, max, input29) => {
803
1127
  const { items } = await readCappedFlag(
804
1128
  context,
@@ -842,321 +1166,25 @@ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|d
842
1166
  var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
843
1167
  var COUNTS = "no per-lead open, click or reply counts";
844
1168
  var noteEngagement = (context, leads, effect, counts = COUNTS) => {
845
- const { outbound } = context;
846
- if (outbound.capabilities["leads.engagement"]) {
847
- return;
848
- }
849
- if (leads.every((lead) => lead.provider === outbound.provider)) {
850
- context.note(`This tool reports ${counts}, so ${effect}.`);
851
- return;
852
- }
853
- const reporting = new Set(
854
- leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
855
- );
856
- const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
857
- if (lacking.length > 0) {
858
- context.note(
859
- `${lacking.join(", ")} ${lacking.length === 1 ? "reports" : "report"} ${counts}, so ${effect} for ${lacking.length === 1 ? "its" : "their"} records. Records from the other tools carry what their vendor reports.`
860
- );
861
- }
862
- };
863
-
864
- // src/insights/variables.ts
865
- var PATTERNS = [
866
- /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
867
- /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
868
- /%(?<name>[A-Za-z_][\w-]*)%/gu
869
- ];
870
- var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
871
- var BUILTINS = /* @__PURE__ */ new Map([
872
- ["company", (lead) => lead.company],
873
- ["companyname", (lead) => lead.company],
874
- ["email", (lead) => lead.email],
875
- ["firstname", (lead) => lead.firstName],
876
- ["jobtitle", (lead) => lead.title],
877
- ["lastname", (lead) => lead.lastName],
878
- ["title", (lead) => lead.title]
879
- ]);
880
- var isBuiltin = (key) => BUILTINS.has(key);
881
- var SENDER = /* @__PURE__ */ new Map([
882
- [
883
- "instantly",
884
- /* @__PURE__ */ new Set([
885
- "accountsignature",
886
- "sendingaccountemail",
887
- "sendingaccountfirstname",
888
- "sendingaccountname"
889
- ])
890
- ]
891
- ]);
892
- var isSender = (provider, key) => SENDER.get(provider)?.has(key) ?? false;
893
- var variablesIn = (text) => PATTERNS.flatMap(
894
- (pattern) => [...text.matchAll(pattern)].map((match) => {
895
- const fallback = match.groups?.fallback;
896
- return {
897
- fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
898
- index: match.index,
899
- name: match.groups?.name ?? "",
900
- raw: match[0]
901
- };
902
- })
903
- );
904
- var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
905
- var valueOf = (lead, key) => {
906
- const builtin = BUILTINS.get(key)?.(lead);
907
- if (filled(builtin)) {
908
- return builtin;
909
- }
910
- const custom = Object.entries(lead.custom).find(
911
- ([name, value]) => keyOf(name) === key && filled(value)
912
- );
913
- return custom?.[1] ?? null;
914
- };
915
- var keysWithValue = (lead) => /* @__PURE__ */ new Set([
916
- ...[...BUILTINS].flatMap(
917
- ([key, read]) => filled(read(lead)) ? [key] : []
918
- ),
919
- ...Object.entries(lead.custom).flatMap(
920
- ([key, value]) => filled(value) ? [keyOf(key)] : []
921
- )
922
- ]);
923
- var fillVariables = (text, lead) => {
924
- const matches = variablesIn(text).toSorted(
925
- (left, right) => left.index - right.index
926
- );
927
- const unfilled = [];
928
- let out = "";
929
- let at = 0;
930
- for (const match of matches) {
931
- if (match.index >= at) {
932
- const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
933
- if (value === null && !unfilled.includes(match.name)) {
934
- unfilled.push(match.name);
935
- }
936
- out += text.slice(at, match.index) + (value ?? match.raw);
937
- at = match.index + match.raw.length;
938
- }
939
- }
940
- return { text: out + text.slice(at), unfilled };
941
- };
942
-
943
- // src/insights/step.ts
944
- var stepAt = (index) => ({
945
- step: index,
946
- stepIndex: index,
947
- stepNumber: index + 1
948
- });
949
- var stepLabel = (index, of = null) => of === null || of < index + 1 ? `step ${index + 1}` : `step ${index + 1} (of ${of})`;
950
-
951
- // src/insights/copy/copy-checks.ts
952
- var CHECKS = {
953
- all_caps: "low",
954
- body_too_long: "low",
955
- connection_request_too_long: "high",
956
- exclamation_marks: "low",
957
- image: "medium",
958
- malformed_variable: "high",
959
- missing_subject: "high",
960
- spam_words: "medium",
961
- subject_breaks_thread: "medium",
962
- subject_too_long: "low",
963
- too_many_links: "medium"
964
- };
965
- var DEFAULT_SPAM_WORDS = [
966
- "100% free",
967
- "act now",
968
- "buy now",
969
- "cash bonus",
970
- "click here",
971
- "double your",
972
- "earn money",
973
- "free trial",
974
- "guarantee",
975
- "limited time",
976
- "no obligation",
977
- "risk-free",
978
- "urgent",
979
- "winner"
980
- ];
981
- var TAG = /<[^>]+>/gu;
982
- var IMAGE = /<img\b[^>]*>/giu;
983
- var VARIABLE = /\{\{[^{}]*\}\}/gu;
984
- var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
985
- var ANCHOR = /<a\b(?<attributes>[^>]*)>[\s\S]*?<\/a\s*>/giu;
986
- var HREF = /\bhref\s*=\s*["']?(?<target>[^"'\s>]+)/iu;
987
- var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
988
- var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
989
- var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
990
- var SNIPPET = 80;
991
- var clip = (text) => text.length > SNIPPET ? `${text.slice(0, SNIPPET)}\u2026` : text;
992
- var visible = (text) => text.replaceAll(TAG, " ").replaceAll(VARIABLE, " variable ");
993
- var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== "");
994
- var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
995
- var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
996
- check: "subject_too_long",
997
- finding: `The subject is ${plural(subject.length, "character")}; the limit is ${limits.maxSubjectChars}.`,
998
- text: clip(subject)
999
- } : null;
1000
- var bodyTooLong = (body, limits) => {
1001
- const words = wordsOf(body);
1002
- return words.length > limits.maxBodyWords ? {
1003
- check: "body_too_long",
1004
- finding: `The body is ${plural(words.length, "word")}; the limit is ${limits.maxBodyWords}.`,
1005
- text: clip(words.slice(0, 12).join(" "))
1006
- } : null;
1007
- };
1008
- var linksOf = (body) => {
1009
- const html = body.replaceAll(IMAGE, " ");
1010
- const anchored = [...html.matchAll(ANCHOR)].flatMap((anchor) => {
1011
- const target = HREF.exec(anchor.groups?.attributes ?? "")?.groups?.target;
1012
- return target === void 0 ? [] : [target];
1013
- });
1014
- return [...anchored, ...html.replaceAll(ANCHOR, " ").match(LINK) ?? []];
1015
- };
1016
- var tooManyLinks = (body, limits) => {
1017
- const links = linksOf(body);
1018
- return links.length > limits.maxLinks ? {
1019
- check: "too_many_links",
1020
- finding: `The body has ${plural(links.length, "link")}; the limit is ${limits.maxLinks}.`,
1021
- text: clip(links.join(" "))
1022
- } : null;
1023
- };
1024
- var spamWords = (text, limits) => {
1025
- const plain2 = visible(text);
1026
- const hits = limits.spamWords.filter(
1027
- (word) => word.trim() !== "" && new RegExp(
1028
- String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
1029
- "iu"
1030
- ).test(plain2)
1031
- );
1032
- return hits.length > 0 ? {
1033
- check: "spam_words",
1034
- finding: `The copy uses ${plural(hits.length, "word or phrase", "words or phrases")} that spam filters weigh.`,
1035
- text: hits.join(", ")
1036
- } : null;
1037
- };
1038
- var malformedVariable = (text) => {
1039
- const empty = (text.match(VARIABLE) ?? []).filter(
1040
- (token) => token.slice(2, -2).trim() === ""
1041
- );
1042
- const rest = text.replaceAll(VARIABLE, "");
1043
- const stray = /\{\{|\}\}/u.exec(rest);
1044
- if (stray === null && empty.length === 0) {
1045
- return null;
1046
- }
1047
- return {
1048
- check: "malformed_variable",
1049
- 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.",
1050
- text: stray === null ? empty[0] ?? "" : clip(
1051
- rest.slice(Math.max(0, stray.index - 20), stray.index + 30).trim()
1052
- )
1053
- };
1054
- };
1055
- var allCaps = (text, limits) => {
1056
- const words = text.replaceAll(TAG, " ").replaceAll(VARIABLE, " ").match(CAPS_WORD);
1057
- const found = words ?? [];
1058
- return found.length > limits.maxCapsWords ? {
1059
- check: "all_caps",
1060
- finding: `${plural(found.length, "word")} of four or more letters ${noun(found.length, "is", "are")} in capitals; the limit is ${limits.maxCapsWords}.`,
1061
- text: clip(found.join(" "))
1062
- } : null;
1063
- };
1064
- var exclamationMarks = (text, limits) => {
1065
- const marks = visible(text).split("!").length - 1;
1066
- return marks > limits.maxExclamations ? {
1067
- check: "exclamation_marks",
1068
- finding: `The copy has ${marks} exclamation marks; the limit is ${limits.maxExclamations}.`,
1069
- text: "!".repeat(marks)
1070
- } : null;
1071
- };
1072
- var image = (body) => {
1073
- const [first] = body.match(IMAGE) ?? [];
1074
- if (first === void 0) {
1075
- return null;
1076
- }
1077
- return {
1078
- check: "image",
1079
- 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.",
1080
- text: clip(first)
1081
- };
1082
- };
1083
- var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
1084
- var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
1085
- check: "connection_request_too_long",
1086
- finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
1087
- text: clip(body)
1088
- } : null;
1089
-
1090
- // src/insights/copy/audit-variant.ts
1091
- var emailChecks = (step, variant, limits, thread) => {
1092
- const subject = variant.subject?.trim() ?? "";
1093
- const body = variant.body ?? "";
1094
- const key = threadKey(subject);
1095
- const problems = [
1096
- subject === "" ? null : subjectTooLong(subject, limits),
1097
- spamWords(`${subject}
1098
- ${body}`, limits),
1099
- tooManyLinks(body, limits),
1100
- image(body)
1101
- ];
1102
- if (step.index === thread.first && subject === "") {
1103
- problems.push({
1104
- check: "missing_subject",
1105
- finding: "The first email has no subject.",
1106
- text: ""
1107
- });
1108
- }
1109
- if (step.index !== thread.first && key !== "" && thread.subjects !== null && !thread.subjects.has(key)) {
1110
- problems.push({
1111
- check: "subject_breaks_thread",
1112
- 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.",
1113
- text: subject
1114
- });
1115
- }
1116
- return problems;
1117
- };
1118
- var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
1119
- var auditVariant = (step, variant, limits, thread, lead) => {
1120
- const body = variant.body ?? "";
1121
- const whole = `${variant.subject ?? ""}
1122
- ${body}`;
1123
- const problems = [
1124
- malformedVariable(whole),
1125
- bodyTooLong(body, limits),
1126
- allCaps(whole, limits),
1127
- exclamationMarks(whole, limits),
1128
- ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
1129
- ];
1130
- return problems.flatMap(
1131
- (problem) => problem === null ? [] : [
1132
- {
1133
- ...problem,
1134
- action: step.action,
1135
- lead,
1136
- severity: CHECKS[problem.check],
1137
- ...stepAt(step.index),
1138
- variantKey: variant.variantKey
1139
- }
1140
- ]
1141
- );
1142
- };
1143
- var threadOf = (steps, perLead2) => {
1144
- const [first] = steps.toSorted((left, right) => left.index - right.index);
1145
- const variants = first?.variants ?? [];
1146
- return {
1147
- first: first?.index ?? null,
1148
- subjects: first !== void 0 && variants.some((variant) => perLead2(variant)) ? null : new Set(
1149
- variants.flatMap((variant) => {
1150
- const key = threadKey(variant.subject);
1151
- return key === "" ? [] : [key];
1152
- })
1153
- )
1154
- };
1169
+ const { outbound } = context;
1170
+ if (outbound.capabilities["leads.engagement"]) {
1171
+ return;
1172
+ }
1173
+ if (leads.every((lead) => lead.provider === outbound.provider)) {
1174
+ context.note(`This tool reports ${counts}, so ${effect}.`);
1175
+ return;
1176
+ }
1177
+ const reporting = new Set(
1178
+ leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
1179
+ );
1180
+ const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
1181
+ if (lacking.length > 0) {
1182
+ context.note(
1183
+ `${lacking.join(", ")} ${lacking.length === 1 ? "reports" : "report"} ${counts}, so ${effect} for ${lacking.length === 1 ? "its" : "their"} records. Records from the other tools carry what their vendor reports.`
1184
+ );
1185
+ }
1155
1186
  };
1156
1187
 
1157
- // src/insights/copy/copy-preview.ts
1158
- import { z as z3 } from "zod";
1159
-
1160
1188
  // src/insights/ref.ts
1161
1189
  var refOf = (outbound, id) => {
1162
1190
  const provider = parseRef(id)?.provider;
@@ -1417,21 +1445,25 @@ var countsOf = (findings, isEmail) => CHECK_NAMES.filter(
1417
1445
  );
1418
1446
  var readSamples = async (context, args, sequence2) => {
1419
1447
  if (!sequence2.steps.some((step) => step.variants.some(writtenPerLead))) {
1420
- return { leads: [], reason: null };
1448
+ return { capped: false, leads: [], reason: null };
1421
1449
  }
1422
1450
  if (args.samples === 0) {
1423
- return { leads: [], reason: "samples is 0" };
1451
+ return { capped: false, leads: [], reason: "samples is 0" };
1424
1452
  }
1425
1453
  if (context.outbound.capabilities["leads.byCampaign"] === false) {
1426
- 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
+ };
1427
1459
  }
1428
- const leads = await leadsOf(
1429
- context,
1430
- args.campaign,
1431
- args.max_leads,
1432
- "max_leads"
1433
- );
1434
- 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,
1435
1467
  leads: pickSamples(leads, perLeadKeys(sequence2.steps), args.samples),
1436
1468
  reason: null
1437
1469
  };
@@ -1511,6 +1543,11 @@ var copyAudit = defineInsight({
1511
1543
  );
1512
1544
  }
1513
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
+ }
1514
1551
  const severity = (level) => findings.filter((finding) => finding.severity === level).length;
1515
1552
  const audit2 = {
1516
1553
  byCheck: countsOf(findings, isEmail),
@@ -1605,12 +1642,12 @@ var compareRates = (first, second, alpha = 0.05) => {
1605
1642
  if (error === 0) {
1606
1643
  return null;
1607
1644
  }
1608
- const z33 = (first.successes / first.trials - second.successes / second.trials) / error;
1609
- const pValue = 1 - erf(Math.abs(z33) / Math.SQRT2);
1645
+ const z34 = (first.successes / first.trials - second.successes / second.trials) / error;
1646
+ const pValue = 1 - erf(Math.abs(z34) / Math.SQRT2);
1610
1647
  return {
1611
1648
  pValue: round(pValue) ?? 0,
1612
1649
  significant: pValue < alpha,
1613
- z: round(z33) ?? 0
1650
+ z: round(z34) ?? 0
1614
1651
  };
1615
1652
  };
1616
1653
  var percent = (value) => value === null ? "unknown" : percentOf(value);
@@ -1669,7 +1706,7 @@ var BASIS_WORDS = {
1669
1706
  delivered: "per message delivered",
1670
1707
  sent: "per message sent"
1671
1708
  };
1672
- var basesInWords = (named4) => named4.map(
1709
+ var basesInWords = (named5) => named5.map(
1673
1710
  ({ basis, name }) => `${name} ${basis === null ? "with no base" : BASIS_WORDS[basis]}`
1674
1711
  ).join(", ");
1675
1712
  var measure = (count2, base) => {
@@ -2717,7 +2754,45 @@ var readCampaignTotals = async (context, input29) => {
2717
2754
  }),
2718
2755
  "campaigns"
2719
2756
  );
2720
- 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"
2721
2796
  };
2722
2797
  var readDaily = async (context, campaign, range) => {
2723
2798
  const options = { by: "day", from: range.from, to: range.to };
@@ -2885,7 +2960,7 @@ var bounces = (facts, limits) => {
2885
2960
  {
2886
2961
  code: "high_bounce_rate",
2887
2962
  finding: `Bounce rate is ${percent(rate2)} (${count2} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
2888
- 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.",
2889
2964
  numbers: {
2890
2965
  bounced: count2,
2891
2966
  high,
@@ -2908,7 +2983,7 @@ var replies = (facts, limits) => {
2908
2983
  {
2909
2984
  code: "low_reply_rate",
2910
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"}.`,
2911
- 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.",
2912
2987
  numbers: {
2913
2988
  floor: limits.minReplyRate,
2914
2989
  high,
@@ -2960,7 +3035,7 @@ var outOfLeads = (recent, leads) => {
2960
3035
  return {
2961
3036
  code: "out_of_leads",
2962
3037
  finding: `${fell} because the campaign is running out of leads: ${left}.${finishing} This is lead runout, not a sending fault.`,
2963
- 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.",
2964
3039
  numbers: {
2965
3040
  activeLeads: leads.active,
2966
3041
  before: recent.before,
@@ -2987,7 +3062,7 @@ var recentSends = (facts, limits) => {
2987
3062
  {
2988
3063
  code: "no_recent_sends",
2989
3064
  finding: `The campaign is active but the vendor reports no sends in the last ${recent.days} days.`,
2990
- 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.",
2991
3066
  numbers: { days: recent.days, sent: recent.sent },
2992
3067
  severity: "high"
2993
3068
  }
@@ -2998,7 +3073,7 @@ var recentSends = (facts, limits) => {
2998
3073
  {
2999
3074
  code: "falling_sends",
3000
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)}.`,
3001
- 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.",
3002
3077
  numbers: { before: recent.before, drop, sent: recent.sent },
3003
3078
  severity: "medium"
3004
3079
  }
@@ -3008,7 +3083,7 @@ var sequence = ({ steps }) => steps === null || steps < 1 || steps > 2 ? [] : [
3008
3083
  {
3009
3084
  code: "short_sequence",
3010
3085
  finding: `The sequence has ${steps} ${steps === 1 ? "step" : "steps"}; follow-ups usually bring a large share of the replies.`,
3011
- 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.",
3012
3087
  numbers: { steps },
3013
3088
  severity: "medium"
3014
3089
  }
@@ -3230,9 +3305,10 @@ var readLeadsLeft = async (context, campaign, recent, maxLeads) => {
3230
3305
  }
3231
3306
  const split = splitActive(leads);
3232
3307
  const unknown = leads.filter((lead) => lead.status === "unknown").length;
3308
+ const runway = runwayOf(split, { unknown }, true, recent.startedPerDay);
3233
3309
  return {
3234
3310
  active: split.active,
3235
- daysLeft: runwayDays(split, { unknown }, true, recent.startedPerDay),
3311
+ daysLeft: runway.state === "out_of_leads" ? 0 : runway.daysLeft,
3236
3312
  inSequence: split.inSequence,
3237
3313
  toStart: leadsToStart(split)
3238
3314
  };
@@ -3409,7 +3485,7 @@ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
3409
3485
  };
3410
3486
  };
3411
3487
  var campaignRanking = defineInsight({
3412
- 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).",
3413
3489
  inputSchema: input9,
3414
3490
  key: "campaignRanking",
3415
3491
  cost: campaignTotalsCost,
@@ -3419,13 +3495,18 @@ var campaignRanking = defineInsight({
3419
3495
  partialOnCap: true,
3420
3496
  next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
3421
3497
  run: async (context, options) => {
3422
- 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 };
3423
3503
  const ranking = {
3424
3504
  ...rankCampaigns(entries, options.metric, options.min_sent),
3425
3505
  ...read,
3426
3506
  better: options.metric === "bounce_rate" ? "lower" : "higher",
3427
3507
  metric: options.metric,
3428
- period: { from: options.from, to: options.to }
3508
+ period,
3509
+ toolsLeftOut: await toolsLeftOut(context, skipped, period)
3429
3510
  };
3430
3511
  return ranking;
3431
3512
  }
@@ -3505,78 +3586,358 @@ var compare = (groups, alpha, read, statuses) => {
3505
3586
  { successes: second.replyRate.count, trials: second.replyRate.of },
3506
3587
  alpha
3507
3588
  );
3508
- if (test === null) {
3509
- return {
3510
- comparison: null,
3511
- finding: "Reply rates cannot be compared: a channel has no reply or volume counts, or neither has a reply."
3512
- };
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
+ );
3513
3845
  }
3514
- 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
+ });
3515
3859
  return {
3516
- comparison: {
3517
- difference: round((higher.replyRate.rate ?? 0) - (lower.replyRate.rate ?? 0)) ?? 0,
3518
- higher: higher.channel,
3519
- test
3520
- },
3521
- 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")
3522
3867
  };
3523
3868
  };
3524
- var channelMix = defineInsight({
3525
- description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. It reads active, paused and completed campaigns by default, since a channel's finished campaigns hold most of its evidence. With one channel present it returns that channel and says there is nothing to compare; on several tools, a note names a tool with no campaign in the states read. replyRateBasis names what every reply rate divides by, the same for every campaign: leads contacted, or messages sent when a campaign has replies in the range but contacted no new lead in it. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
3526
- inputSchema: input10,
3527
- key: "channelMix",
3528
- cost: campaignTotalsCost,
3529
- scales: "max_campaigns",
3530
- name: "channel_mix",
3531
- needs: ["stats.campaign"],
3532
- next: "Use campaign_ranking to see which campaigns carry the better channel.",
3533
- run: async (context, options) => {
3534
- const { entries, read } = await readCampaignTotals(context, options);
3535
- const basis = replyBasisAcross(entries.map((entry) => entry.counts));
3536
- const channels = byChannel(entries, basis);
3537
- const providers = byProvider(entries, basis);
3538
- for (const { group, partial } of channels) {
3539
- if (partial.length > 0) {
3540
- context.note(partialNote(`Channel ${group.channel}`, partial));
3541
- }
3542
- }
3543
- for (const { group, partial } of providers) {
3544
- if (partial.length > 0) {
3545
- context.note(
3546
- partialNote(`${group.provider} ${group.channel}`, partial)
3547
- );
3548
- }
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
3549
3899
  }
3550
- const mix = {
3551
- ...read,
3552
- ...compare(
3553
- channels.map((each) => each.group),
3554
- options.alpha,
3555
- read,
3556
- options.statuses
3557
- ),
3558
- byProvider: providers.map((each) => each.group),
3559
- channels: channels.map((each) => each.group),
3560
- period: { from: options.from, to: options.to },
3561
- replyRateBasis: basis
3562
- };
3563
- return mix;
3900
+ ];
3901
+ };
3902
+ var stalledAction = (stalled, days) => {
3903
+ const [first] = stalled;
3904
+ if (first === void 0) {
3905
+ return [];
3564
3906
  }
3565
- });
3566
-
3567
- // src/insights/ops/client-report.ts
3568
- 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
+ ];
3569
3922
 
3570
3923
  // src/insights/ops/period-comparison.ts
3571
- import { z as z14 } from "zod";
3572
- var input11 = z14.object({
3924
+ import { z as z15 } from "zod";
3925
+ var input12 = z15.object({
3573
3926
  ...listFields("two stats requests"),
3574
- alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3575
- days: z14.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
3576
- 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(
3577
3930
  "A campaign under this many sends in either period is listed apart"
3578
3931
  )
3579
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
+ };
3580
3941
  var numbersOf = (counts, rates) => ({
3581
3942
  ...totalsOf(counts),
3582
3943
  bounceRate: rates.bounceRate.rate,
@@ -3707,8 +4068,8 @@ var workspaceOf = (context, rows, alpha) => {
3707
4068
  );
3708
4069
  };
3709
4070
  var periodComparison = defineInsight({
3710
- 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.",
3711
- 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,
3712
4073
  key: "periodComparison",
3713
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")),
3714
4075
  scales: "max_campaigns",
@@ -3724,6 +4085,11 @@ var periodComparison = defineInsight({
3724
4085
  );
3725
4086
  const workspace = await readWorkspace(context, options.days);
3726
4087
  const periods = await readPeriods(context, listed2, options.days);
4088
+ const leftOut = await toolsLeftOut(
4089
+ context,
4090
+ listed2.skipped,
4091
+ periods.current
4092
+ );
3727
4093
  const campaigns = [];
3728
4094
  const tooFewSends = [];
3729
4095
  for (const { campaign, current, previous } of periods.campaigns) {
@@ -3741,6 +4107,18 @@ var periodComparison = defineInsight({
3741
4107
  });
3742
4108
  }
3743
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
+ }
3744
4122
  const comparison = {
3745
4123
  ...periods.read,
3746
4124
  campaigns: campaigns.toSorted(
@@ -3753,164 +4131,16 @@ var periodComparison = defineInsight({
3753
4131
  days: options.days,
3754
4132
  previous: periods.previous,
3755
4133
  tooFewSends,
3756
- total: noted(
3757
- context,
3758
- "Every campaign added together",
3759
- totalOf(periods.campaigns, options.alpha)
3760
- ),
3761
- workspace: workspaceOf(context, workspace, options.alpha)
4134
+ toolsLeftOut: leftOut,
4135
+ total: total2,
4136
+ totalBasis: campaignsBasis(periods.campaigns.length, options.statuses),
4137
+ workspace: workspaceTotals,
4138
+ workspaceBasis: workspaceTotals === null ? null : WORKSPACE_BASIS
3762
4139
  };
3763
4140
  return comparison;
3764
4141
  }
3765
4142
  });
3766
4143
 
3767
- // src/insights/ops/pipeline-forecast.ts
3768
- import { z as z15 } from "zod";
3769
- var input12 = z15.object({
3770
- campaign: z15.string().min(3).describe("The campaign's ref or name"),
3771
- days: z15.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3772
- max_leads: z15.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3773
- });
3774
- var countStatuses = (leads) => {
3775
- const counts = {
3776
- active: 0,
3777
- bounced: 0,
3778
- completed: 0,
3779
- paused: 0,
3780
- replied: 0,
3781
- skipped: 0,
3782
- unknown: 0,
3783
- unsubscribed: 0
3784
- };
3785
- for (const lead of leads) {
3786
- counts[lead.status] += 1;
3787
- }
3788
- return counts;
3789
- };
3790
- var times = (leads, share2) => share2 === null ? null : round(leads * share2);
3791
- var project = (leads, measured2) => ({
3792
- expected: times(leads, measured2.rate),
3793
- high: times(leads, measured2.high),
3794
- low: times(leads, measured2.low)
3795
- });
3796
- var paceOf = async (context, campaign, days) => {
3797
- if (context.outbound.capabilities["stats.byDay"] === false) {
3798
- context.note(
3799
- "Days of sending left were not estimated: the adapter has no stats by day."
3800
- );
3801
- return null;
3802
- }
3803
- const series = await readDaily(
3804
- context,
3805
- campaign,
3806
- paceWindow(context.now, days)
3807
- );
3808
- return newLeadsPerDay(
3809
- series.map((day) => day.counts),
3810
- days
3811
- );
3812
- };
3813
- var ASSUMPTIONS = [
3814
- "Every remaining lead is contacted.",
3815
- "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
3816
- "The daily pace of new leads started stays what it was over the recent days. Days with no report count as none started."
3817
- ];
3818
- var describe2 = ({ complete, daysLeft, inSequence, remaining }, forecast) => {
3819
- if (daysLeft === 0) {
3820
- 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.`;
3821
- }
3822
- const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
3823
- if (forecast.expected === null) {
3824
- return `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.`;
3825
- }
3826
- const [expected, low, high] = [
3827
- forecast.expected,
3828
- forecast.low,
3829
- forecast.high
3830
- ].map((value) => spoken(value));
3831
- const range = low === high ? "" : ` (between ${low} and ${high})`;
3832
- return `${leads}; expect about ${expected} ${noun(Number(expected), "reply", "replies")}${range}. This is an estimate.`;
3833
- };
3834
- var ownerOf = (context, campaign) => context.outbound.provider === "combined" ? context.outbound.workspace(`${campaign.provider}:${campaign.workspaceId}`) : context.outbound;
3835
- var runwayOf = async (context, campaign, options) => {
3836
- const owner = ownerOf(context, campaign);
3837
- const status = options.activeOnly === true && owner.capabilities["leads.byStatus"] ? "active" : void 0;
3838
- const { capped: capped2, items: leads } = await readCapped(
3839
- context,
3840
- (max) => owner.campaign(campaign.ref).leads.listAll({ max, status }),
3841
- {
3842
- input: options.leadsInput,
3843
- max: options.maxLeads,
3844
- what: options.leadsWhat
3845
- }
3846
- );
3847
- const complete = !capped2;
3848
- const byStatus = countStatuses(leads);
3849
- const split = splitActive(leads);
3850
- const pace = await paceOf(context, campaign.ref, options.days);
3851
- return {
3852
- byStatus,
3853
- complete,
3854
- daysLeft: runwayDays(split, byStatus, complete, pace),
3855
- leadsRead: leads.length,
3856
- pace,
3857
- remaining: byStatus.active,
3858
- split
3859
- };
3860
- };
3861
- var forecastCampaign = async (context, campaign, options) => {
3862
- const { byStatus, complete, daysLeft, leadsRead, pace, remaining, split } = await runwayOf(context, campaign, options);
3863
- const rates = ratesOf(
3864
- await readTotals(context, campaign.ref, { from: null, to: null })
3865
- );
3866
- const expectedReplies = project(remaining, rates.replyRate);
3867
- return {
3868
- ...labelOf(campaign),
3869
- assumptions: [
3870
- ...ASSUMPTIONS,
3871
- `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"}.`
3872
- ],
3873
- byStatus,
3874
- dailyContactRate: pace,
3875
- daysLeft,
3876
- estimate: true,
3877
- expectedPositive: project(remaining, rates.positiveRate),
3878
- expectedReplies,
3879
- finding: describe2(
3880
- { complete, daysLeft, inSequence: split.inSequence, remaining },
3881
- expectedReplies
3882
- ),
3883
- inSequence: split.inSequence,
3884
- leadsComplete: complete,
3885
- leadsRead,
3886
- notStarted: split.notStarted,
3887
- positiveRate: rates.positiveRate,
3888
- remaining,
3889
- replyRate: rates.replyRate
3890
- };
3891
- };
3892
- var pipelineForecast = defineInsight({
3893
- 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.",
3894
- inputSchema: input12,
3895
- key: "pipelineForecast",
3896
- 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")),
3897
- scales: "max_leads",
3898
- name: "pipeline_forecast",
3899
- needs: ["leads.byCampaign", "stats.campaign"],
3900
- next: "Use client_report to see every campaign that is running out of leads.",
3901
- run: async (context, options) => {
3902
- const campaign = context.one(
3903
- await context.outbound.campaigns.get(options.campaign)
3904
- );
3905
- return await forecastCampaign(context, campaign, {
3906
- days: options.days,
3907
- leadsInput: "max_leads",
3908
- leadsWhat: "leads",
3909
- maxLeads: options.max_leads
3910
- });
3911
- }
3912
- });
3913
-
3914
4144
  // src/insights/ops/client-report.ts
3915
4145
  var input13 = z16.object({
3916
4146
  ...listFields(
@@ -3927,17 +4157,16 @@ var input13 = z16.object({
3927
4157
  ),
3928
4158
  min_baseline_points: z16.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
3929
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
+ ),
3930
4163
  runway_days: z16.number().min(0).default(7).describe(
3931
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."
3932
4168
  )
3933
4169
  });
3934
- var sendingLeft = (daysLeft) => {
3935
- if (daysLeft !== null && daysLeft < 0.05) {
3936
- return "less than a day of sending";
3937
- }
3938
- const days = spoken(daysLeft);
3939
- return `about ${days} ${days === "1" ? "day" : "days"} of sending`;
3940
- };
3941
4170
  var bounceProblems = (campaigns, options) => campaigns.flatMap(({ campaign, current }) => {
3942
4171
  const { count: count2, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
3943
4172
  return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [
@@ -3972,52 +4201,7 @@ var readAnomalies = async (context, period, options) => {
3972
4201
  }).anomalies
3973
4202
  ];
3974
4203
  };
3975
- var NAMED = 10;
3976
- var readRunways = async (context, campaigns, options) => {
3977
- const { capabilities } = context.outbound;
3978
- if (!capabilities["leads.byCampaign"] || capabilities["stats.byDay"] === false) {
3979
- return null;
3980
- }
3981
- const active = campaigns.flatMap(
3982
- ({ campaign }) => campaign.status === "active" ? [campaign] : []
3983
- );
3984
- const forecasts = await context.each(
3985
- active,
3986
- async (campaign) => ({
3987
- campaign,
3988
- forecast: await runwayOf(context, campaign, {
3989
- activeOnly: true,
3990
- days: options.days,
3991
- leadsInput: "max_leads_per_campaign",
3992
- leadsWhat: "leads of a campaign",
3993
- maxLeads: options.max_leads_per_campaign
3994
- })
3995
- }),
3996
- "active campaigns' leads"
3997
- );
3998
- const uncounted = forecasts.flatMap(
3999
- ({ campaign, forecast }) => forecast.complete ? [] : [campaign.name]
4000
- );
4001
- if (uncounted.length > 0) {
4002
- const named4 = uncounted.slice(0, NAMED);
4003
- const rest = uncounted.length - named4.length;
4004
- context.note(
4005
- `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.`
4006
- );
4007
- }
4008
- const runways = forecasts.flatMap(
4009
- ({ campaign, forecast }) => forecast.complete && forecast.daysLeft !== null && forecast.daysLeft <= options.runway_days ? [
4010
- {
4011
- ...labelOf(campaign),
4012
- dailyContactRate: forecast.pace,
4013
- daysLeft: forecast.daysLeft,
4014
- remaining: forecast.remaining
4015
- }
4016
- ] : []
4017
- );
4018
- return runways.toSorted((left, right) => left.daysLeft - right.daysLeft);
4019
- };
4020
- var actionsOf = (report) => {
4204
+ var actionsOf = (report, options) => {
4021
4205
  const [worst] = report.bottom;
4022
4206
  const { current, previous, replyRateBasis } = report.totals;
4023
4207
  const perWhat = RATE_WORDS[replyRateBasis].toLowerCase();
@@ -4029,13 +4213,6 @@ var actionsOf = (report) => {
4029
4213
  kind: "fix_bounces",
4030
4214
  number: problem.rate
4031
4215
  })),
4032
- ...(report.runningOutOfLeads ?? []).map((runway) => ({
4033
- 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)}.`,
4034
- campaign: runway.campaign,
4035
- campaignName: runway.campaignName,
4036
- kind: "add_leads",
4037
- number: runway.daysLeft
4038
- })),
4039
4216
  ...report.totals.verdict === "down" ? [
4040
4217
  {
4041
4218
  action: `Find out what changed: ${perWhat} fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
@@ -4060,11 +4237,48 @@ var actionsOf = (report) => {
4060
4237
  campaignName: null,
4061
4238
  kind: "check_anomaly",
4062
4239
  number: anomaly.value
4063
- }))
4240
+ })),
4241
+ ...runwayActions(
4242
+ {
4243
+ runningOut: report.runningOutOfLeads ?? [],
4244
+ stalled: report.stalled ?? []
4245
+ },
4246
+ options
4247
+ )
4064
4248
  ];
4065
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
+ };
4066
4280
  var clientReport = defineInsight({
4067
- 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.",
4068
4282
  inputSchema: input13,
4069
4283
  key: "clientReport",
4070
4284
  cost: (values, price) => {
@@ -4078,18 +4292,38 @@ var clientReport = defineInsight({
4078
4292
  needs: ["stats.campaign"],
4079
4293
  partialOnCap: true,
4080
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.",
4081
- 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
+ }
4082
4305
  const listed2 = await readCampaignsIn(
4083
4306
  context,
4084
4307
  options.statuses,
4085
4308
  options.max_campaigns
4086
4309
  );
4087
- 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(
4088
4317
  context,
4089
4318
  lastDays(context.now, options.days),
4090
4319
  options
4320
+ ) : null;
4321
+ const periods = await readPeriods(
4322
+ context,
4323
+ { ...listed2, items },
4324
+ options.days
4091
4325
  );
4092
- const periods = await readPeriods(context, listed2, options.days);
4326
+ const left = await toolsLeftOut(context, listed2.skipped, periods.current);
4093
4327
  const totals = noted(
4094
4328
  context,
4095
4329
  "Totals",
@@ -4104,16 +4338,20 @@ var clientReport = defineInsight({
4104
4338
  options.min_sent,
4105
4339
  totals.replyRateBasis
4106
4340
  );
4341
+ const runways = await readRunways(context, periods.campaigns, options);
4107
4342
  const sections = {
4108
4343
  anomalies: anomalies2,
4109
4344
  bottom: ranking.ranked.slice(options.limit).slice(-options.limit).toReversed(),
4110
4345
  bounceProblems: bounceProblems(periods.campaigns, options),
4111
- runningOutOfLeads: await readRunways(context, periods.campaigns, options),
4346
+ runningOutOfLeads: runways?.runningOut ?? null,
4347
+ stalled: runways?.stalled ?? null,
4112
4348
  totals
4113
4349
  };
4114
4350
  const leftOut = [
4115
- ...sections.anomalies === null ? ["Unusual days: the adapter has no workspace stats by day."] : [],
4116
- ...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 ? [
4117
4355
  "Campaigns running out of leads: the adapter cannot list a campaign's leads or has no stats by day."
4118
4356
  ] : []
4119
4357
  ];
@@ -4123,14 +4361,16 @@ var clientReport = defineInsight({
4123
4361
  const report = {
4124
4362
  ...sections,
4125
4363
  ...periods.read,
4126
- actions: actionsOf(sections),
4364
+ actions: actionsOf(sections, options),
4127
4365
  campaigns: periods.campaigns.length,
4128
4366
  days: options.days,
4129
4367
  leftOut,
4130
4368
  period: periods.current,
4131
4369
  previousPeriod: periods.previous,
4132
4370
  replyRateBasis: totals.replyRateBasis,
4133
- 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)
4134
4374
  };
4135
4375
  return report;
4136
4376
  }
@@ -4156,7 +4396,7 @@ var groupOf2 = (tag, entries, basis) => {
4156
4396
  partial
4157
4397
  };
4158
4398
  };
4159
- var named = (group) => group.tag ?? "";
4399
+ var named2 = (group) => group.tag ?? "";
4160
4400
  var tagRollup = defineInsight({
4161
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).",
4162
4402
  inputSchema: input14,
@@ -4194,7 +4434,7 @@ var tagRollup = defineInsight({
4194
4434
  }
4195
4435
  }
4196
4436
  const groups = grouped.map((each) => each.group).toSorted(
4197
- (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))
4198
4438
  );
4199
4439
  const enough2 = (group) => (volumeOf(group) ?? 0) >= options.min_sent;
4200
4440
  const rollup = {
@@ -4659,7 +4899,14 @@ var sentByHand = async (context, since, max) => {
4659
4899
  return null;
4660
4900
  }
4661
4901
  const walk = messages.listAll({ byHand: true, max, since });
4662
- 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
+ }
4663
4910
  if (walk.meta !== void 0) {
4664
4911
  context.one({ meta: walk.meta });
4665
4912
  }
@@ -4673,9 +4920,30 @@ var sentByHand = async (context, since, max) => {
4673
4920
  var answersIn = (conversation, sent) => sent.filter(
4674
4921
  (message) => conversation.by === "thread" ? message.threadId === conversation.id : message.leadRef === conversation.id
4675
4922
  );
4676
- 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) => {
4677
4943
  const checked = {
4678
4944
  answered: 0,
4945
+ automatic: 0,
4946
+ automaticReplies: 0,
4679
4947
  dropped: [],
4680
4948
  tooRecent: 0,
4681
4949
  unread: 0
@@ -4686,11 +4954,14 @@ var check = async (context, checkable, sent, olderThanHours) => {
4686
4954
  context.now,
4687
4955
  messages
4688
4956
  );
4689
- const settle = (found, whole) => {
4957
+ const settle = (found, whole, automaticReplies = 0) => {
4690
4958
  if (found.length === 0) {
4691
4959
  checked.answered += 1;
4692
4960
  } else if (found.every((each) => each.hoursWaiting < olderThanHours)) {
4693
4961
  checked.tooRecent += 1;
4962
+ } else if (automaticReplies > 0) {
4963
+ checked.automatic += 1;
4964
+ checked.automaticReplies += automaticReplies;
4694
4965
  } else if (whole) {
4695
4966
  checked.dropped.push(...found);
4696
4967
  } else {
@@ -4705,30 +4976,31 @@ var check = async (context, checkable, sent, olderThanHours) => {
4705
4976
  );
4706
4977
  return !((found.length === 0 || sent.whole) && settle(found, false));
4707
4978
  });
4708
- const threads = await mapConcurrent(toRead, async (conversation) => {
4709
- try {
4710
- const read = await (conversation.by === "thread" ? context.outbound.thread(conversation.id).messages() : context.outbound.lead(conversation.id).timeline());
4711
- return { conversation, failed: null, messages: context.page(read) };
4712
- } catch (error) {
4713
- if (isCapStop(error)) {
4714
- throw error;
4715
- }
4716
- return {
4717
- conversation,
4718
- failed: OutboundError.is(error) ? error.code : "an unexpected error",
4719
- messages: []
4720
- };
4721
- }
4722
- });
4723
- 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;
4724
4985
  for (const { conversation, failed, messages } of threads) {
4725
4986
  if (failed === null) {
4726
- 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
+ );
4727
4994
  } else {
4728
4995
  checked.unread += 1;
4729
4996
  reasons.add(failed);
4730
4997
  }
4731
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
+ }
4732
5004
  if (checked.unread > 0) {
4733
5005
  context.note(
4734
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("; ")}).`
@@ -4746,7 +5018,7 @@ var input16 = z19.object({
4746
5018
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
4747
5019
  ),
4748
5020
  include_auto: z19.boolean().default(false).describe(
4749
- "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"
4750
5022
  ),
4751
5023
  include_inbox: z19.boolean().default(false).describe(
4752
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."
@@ -4796,7 +5068,7 @@ var findingOf2 = (finding, reply, found) => {
4796
5068
  const meeting = found.followUp.basis === "meeting" ? ` ${found.followUp.evidence.at(-1) ?? ""} Check it before following up.` : "";
4797
5069
  return latestIsReply || latest2 === void 0 ? `${finding}${meeting}` : `${finding} ${latest2} Read it before following up.${meeting}`;
4798
5070
  };
4799
- var named2 = async (context, dropped) => {
5071
+ var named3 = async (context, dropped) => {
4800
5072
  const { outbound } = context;
4801
5073
  const readLeads2 = outbound.capabilities["leads.get"];
4802
5074
  const leadRefs = readLeads2 ? refsOf(dropped.map((each) => each.lead)) : [];
@@ -4868,7 +5140,7 @@ var readReplies = (context, since, given) => {
4868
5140
  );
4869
5141
  };
4870
5142
  var droppedReplies = defineInsight({
4871
- description: "Replies from prospects that nobody answered. Reads every reply since a date (14 days before now by default, up to 2,000 or max_replies), keeps the categories that need an answer, and reports a conversation as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Where the tool lists the messages sent by hand (messages.byHand), one listing of those in the window settles every answered conversation; a conversation is read in full, by its thread or the lead's timeline, only when it may be dropped, or when that listing stopped at its max and did not answer it. Replies in conversations that belong to no campaign, such as a LinkedIn account's own messages on HeyReach, are set aside and counted in totals.notInCampaign unless include_inbox is true. Returns the dropped replies longest waiting first with hours waiting, category, the campaign and its name, and the lead with their name, email and LinkedIn profile. A reply that could not be checked, including one whose conversation could not be read, is counted in totals.unchecked with a note and meta.complete: false, never reported as dropped. Costs one request per page of replies and of messages sent by hand, one per conversation read in full, and one per lead and per campaign among the dropped replies to name them. totals.moreRepliesExist is true when the read stopped with replies left unread. Dropped means only that nothing was sent after the reply: each one also carries the conversation's activity (its latest message, which can be a later message than the labelled reply), meeting (what the vendor records on the lead, Instantly only, so a prospect who booked through a calendar link shows as booked), vendorSentiment (the vendor's labels, kept apart) and followUp, a fixed-rule assessment with its evidence and what it could not check. No rule reads what a message says, so read the latest message with thread_context before following up.",
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.",
4872
5144
  inputSchema: input16,
4873
5145
  key: "droppedReplies",
4874
5146
  cost: (values, price) => {
@@ -4915,17 +5187,26 @@ var droppedReplies = defineInsight({
4915
5187
  since,
4916
5188
  values.max_replies ?? WINDOW_REPLIES
4917
5189
  );
4918
- const { answered, dropped, tooRecent, unread } = await check(
5190
+ const {
5191
+ answered,
5192
+ automatic,
5193
+ automaticReplies,
5194
+ dropped,
5195
+ tooRecent,
5196
+ unread
5197
+ } = await check(
4919
5198
  context,
4920
5199
  checkable,
4921
5200
  sent,
4922
- values.older_than_hours
5201
+ values.older_than_hours,
5202
+ values.include_auto
4923
5203
  );
4924
- const withNames = await named2(context, dropped);
5204
+ const withNames = await named3(context, dropped);
4925
5205
  const notChecked = unchecked + unread;
5206
+ const owedOrUnknown = conversations.length - automatic;
4926
5207
  if (notChecked > 0) {
4927
5208
  context.partial(
4928
- notChecked === conversations.length ? `None of the ${plural(notChecked, "conversation")} could be checked, so dropped counts none of them. totals.unchecked counts them, as neither dropped nor answered.` : `${plural(notChecked, "conversation")} of ${conversations.length} could not be checked, so dropped counts only the ${conversations.length - notChecked} that were. totals.unchecked counts the rest, as neither dropped nor answered.`
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.`
4929
5210
  );
4930
5211
  }
4931
5212
  const answer = {
@@ -4936,12 +5217,12 @@ var droppedReplies = defineInsight({
4936
5217
  since,
4937
5218
  totals: {
4938
5219
  answered,
4939
- conversations: conversations.length,
5220
+ conversations: owedOrUnknown,
4940
5221
  dropped: dropped.length,
4941
5222
  moreRepliesExist: listed2.capped,
4942
5223
  notInCampaign: separates ? inWindow.length - replies2.length : null,
4943
5224
  repliesRead: read.length,
4944
- skippedAuto: wanted.length - kept.length,
5225
+ skippedAuto: wanted.length - kept.length + automaticReplies,
4945
5226
  skippedByCategory: replies2.length - wanted.length,
4946
5227
  tooRecent,
4947
5228
  unchecked: notChecked
@@ -5033,11 +5314,13 @@ var listedLeads = async (context, { campaign, max_leads: max }) => {
5033
5314
  });
5034
5315
  return { capped: walk.truncated || wasCutShort(leads), leads };
5035
5316
  };
5317
+ var leadOfReply = (reply) => reply.leadRef ?? (reply.leadEmail === null || reply.leadEmail === void 0 ? null : makeRef(reply.provider, reply.workspaceId, reply.leadEmail));
5036
5318
  var repliedRefs = (replies2, campaign, listed2) => {
5037
5319
  const refs = /* @__PURE__ */ new Map();
5038
5320
  for (const reply of replies2) {
5039
- 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))) {
5040
- 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);
5041
5324
  }
5042
5325
  }
5043
5326
  return refs;
@@ -5056,10 +5339,26 @@ var byAddress = (found, campaigns) => {
5056
5339
  }
5057
5340
  return [...chosen.values()];
5058
5341
  };
5059
- var address = (ref, resolves) => {
5060
- const id = parseRef(ref)?.sourceId;
5061
- 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);
5062
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
+ );
5063
5362
  var lookUp = async (context, addresses, campaign) => {
5064
5363
  const found = [];
5065
5364
  const byToken = addressesMasked(context) ? maskingOf(context.outbound)?.leadsByToken : void 0;
@@ -5082,11 +5381,8 @@ var repliedLeads = async (context, values, replies2, listed2) => {
5082
5381
  const masking = maskingOf(outbound);
5083
5382
  const resolves = masking?.resolves ?? (() => null);
5084
5383
  const replied = repliedRefs(replies2, values.campaign, listed2);
5085
- const wanted = addressesMasked(context) ? new Map(
5086
- [...replied].filter(
5087
- ([ref]) => resolves(parseRef(ref)?.sourceId ?? ref) !== null
5088
- )
5089
- ) : replied;
5384
+ const emails = emailsOf(replies2);
5385
+ const wanted = addressesMasked(context) ? new Map([...replied].filter(([ref]) => readable(ref, resolves, emails))) : replied;
5090
5386
  if (wanted.size < replied.size) {
5091
5387
  context.partial(
5092
5388
  `${ADDRESSES_MASKED} leads that replied within recency_days and were not otherwise listed were not looked for.`
@@ -5096,12 +5392,16 @@ var repliedLeads = async (context, values, replies2, listed2) => {
5096
5392
  return { leads: [], unreadable: 0 };
5097
5393
  }
5098
5394
  const many = outbound.capabilities["leads.lookupMany"] === true;
5099
- 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
+ ) : [];
5100
5398
  const addresses = [
5101
- ...new Set(byAddressRefs.flatMap((ref) => address(ref, resolves) ?? []))
5399
+ ...new Set(
5400
+ byAddressRefs.flatMap((ref) => address(ref, resolves, emails) ?? [])
5401
+ )
5102
5402
  ];
5103
5403
  const byRef = [...wanted.keys()].filter(
5104
- (ref) => !many || address(ref, resolves) === null
5404
+ (ref) => !many || address(ref, resolves, emails) === null
5105
5405
  );
5106
5406
  if (!outbound.capabilities["leads.get"] && byRef.length > 0) {
5107
5407
  context.partial(
@@ -5207,6 +5507,8 @@ var readCandidates = async (context, values) => {
5207
5507
  };
5208
5508
 
5209
5509
  // src/insights/people/thread-read.ts
5510
+ var REDACT_TOKEN = /redacted:[0-9a-f]{16}/gu;
5511
+ var NAMED_REFS = 3;
5210
5512
  var readConversation = async (context, target, bodies) => {
5211
5513
  const options = bodies ? { include: ["body"] } : {};
5212
5514
  try {
@@ -5223,6 +5525,56 @@ var readConversation = async (context, target, bodies) => {
5223
5525
  };
5224
5526
  }
5225
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
+ };
5226
5578
  var inCampaign = (messages, lead) => messages.filter(
5227
5579
  (message) => message.campaignRef === null || lead === null || lead === void 0 || lead.campaignRef === null || message.campaignRef === lead.campaignRef
5228
5580
  );
@@ -5388,7 +5740,7 @@ var toHotLead = (lead, values, now) => {
5388
5740
  };
5389
5741
  var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1 : 0);
5390
5742
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
5391
- var staleOf = (leads, values, now) => new Set(
5743
+ var staleOf2 = (leads, values, now) => new Set(
5392
5744
  leads.flatMap((lead) => {
5393
5745
  const age = ageOf(lead, now);
5394
5746
  return age !== null && age > values.max_age_days ? [lead.ref] : [];
@@ -5441,7 +5793,7 @@ var hotLeads = defineInsight({
5441
5793
  const scored = open.flatMap(
5442
5794
  (lead) => toHotLead(lead, scoring, context.now)
5443
5795
  );
5444
- const stale = staleOf(open, scoring, context.now);
5796
+ const stale = staleOf2(open, scoring, context.now);
5445
5797
  const positive = scored.filter((lead) => lead.score > 0);
5446
5798
  const hot = [
5447
5799
  ...positive.filter((lead) => !stale.has(lead.lead)).toSorted(hottestFirst),
@@ -5486,6 +5838,45 @@ var hotLeads = defineInsight({
5486
5838
  // src/insights/people/lead-collisions.ts
5487
5839
  import { z as z21 } from "zod";
5488
5840
 
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
+ ];
5864
+ };
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;
5869
+ }
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)}.`;
5878
+ };
5879
+
5489
5880
  // src/insights/people/find.ts
5490
5881
  var keysOfLead = (lead) => {
5491
5882
  const slug = profileSlug(lead.linkedinUrl);
@@ -5502,6 +5893,7 @@ var lookupOf = (outbound) => {
5502
5893
  const masking = maskingOf(outbound);
5503
5894
  return {
5504
5895
  hash: masking?.strategy === "hash" ? masking.hash : void 0,
5896
+ known: (key) => masking?.strategy === "mask" && (masking.resolves?.(key.slice(key.indexOf(":") + 1)) ?? null) !== null,
5505
5897
  masked: (masking?.fields ?? []).flatMap(
5506
5898
  (field) => field === "email" || field === "linkedin" ? [field] : []
5507
5899
  )
@@ -5535,7 +5927,8 @@ var formsOf = (key, given) => {
5535
5927
  given.trim()
5536
5928
  ];
5537
5929
  };
5538
- var startFrom = async (context, identifier, { hash, masked }) => {
5930
+ var startFrom = async (context, identifier, lookup) => {
5931
+ const { hash, masked } = lookup;
5539
5932
  const { outbound } = context;
5540
5933
  const { key, ref } = parsePerson(identifier, outbound.provider);
5541
5934
  if (ref !== null) {
@@ -5549,7 +5942,7 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5549
5942
  throw refuse(
5550
5943
  outbound,
5551
5944
  masked,
5552
- "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"
5553
5946
  );
5554
5947
  }
5555
5948
  const tokens = formsOf(key, ref?.sourceId ?? identifier).map(hash);
@@ -5563,17 +5956,14 @@ var startFrom = async (context, identifier, { hash, masked }) => {
5563
5956
  };
5564
5957
  }
5565
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";
5566
- if (masked.length === 2) {
5567
- throw refuse(
5568
- outbound,
5569
- masked,
5570
- instead ?? "a lead ref has no identifier left to look the person up by"
5571
- );
5959
+ if (masked.length === 2 && instead !== null) {
5960
+ throw refuse(outbound, masked, instead);
5572
5961
  }
5573
5962
  const lead = context.one(await outbound.leads.get(ref?.text ?? identifier));
5574
- const keys = keysOfLead(lead).filter(
5963
+ const open = keysOfLead(lead).filter(
5575
5964
  (each) => !masked.includes(kindOf(each))
5576
5965
  );
5966
+ const keys = open.length > 0 ? open : keysOfLead(lead).filter((each) => lookup.known(each));
5577
5967
  if (keys.length === 0 && masked.length > 0) {
5578
5968
  const other = ["email", "linkedin"].find(
5579
5969
  (kind) => !masked.includes(kind)
@@ -5593,6 +5983,7 @@ var carries = (lead, key, start) => {
5593
5983
  }
5594
5984
  return keysOfLead(lead).includes(key);
5595
5985
  };
5986
+ var followed = (key, lookup, byToken) => !lookup.masked.includes(kindOf(key)) || byToken && lookup.known(key);
5596
5987
  var noteNoProfiles = (context, keys) => {
5597
5988
  if (context.outbound.fields.lead?.linkedinUrl === false && keys.some((key) => kindOf(key) === "linkedin")) {
5598
5989
  context.note(
@@ -5612,6 +6003,7 @@ var findPerson = async (context, identifier, maxRecords) => {
5612
6003
  }
5613
6004
  const keys = new Set(start.keys);
5614
6005
  const asked = /* @__PURE__ */ new Set();
6006
+ const byToken = start.keys.some((key) => masked.includes(kindOf(key)));
5615
6007
  const records = new Map(
5616
6008
  start.records.map((lead) => [`${lead.ref} ${lead.campaignRef ?? ""}`, lead])
5617
6009
  );
@@ -5637,7 +6029,7 @@ var findPerson = async (context, identifier, maxRecords) => {
5637
6029
  if (asking !== void 0 && carries(lead, asking, start)) {
5638
6030
  records.set(`${lead.ref} ${lead.campaignRef ?? ""}`, lead);
5639
6031
  for (const key of leadKeys) {
5640
- if (!masked.includes(kindOf(key))) {
6032
+ if (followed(key, lookup, byToken)) {
5641
6033
  keys.add(key);
5642
6034
  }
5643
6035
  }
@@ -5659,10 +6051,12 @@ var input18 = z21.object({
5659
6051
  include_past: z21.boolean().default(false).describe(
5660
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."
5661
6053
  ),
5662
- max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
5663
- "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."
5664
6059
  ),
5665
- max_leads_per_campaign: z21.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
5666
6060
  statuses: statusesField
5667
6061
  });
5668
6062
  var keysFor = (masking) => masking?.strategy === "mask" && masking.fields.includes("linkedin") ? (lead) => [
@@ -5724,7 +6118,7 @@ var toCollision = (group) => {
5724
6118
  ];
5725
6119
  };
5726
6120
  var listed = (parts) => parts.length < 2 ? parts[0] ?? "" : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
5727
- var named3 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName}"`));
6121
+ var named4 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName}"`));
5728
6122
  var withStatus = (campaigns) => listed(
5729
6123
  campaigns.map((each) => `"${each.campaignName}" (${each.leadStatus})`)
5730
6124
  );
@@ -5736,11 +6130,22 @@ var findingOf3 = (who, campaigns, tools) => {
5736
6130
  const also = past.length === 0 ? "" : `, and was in ${withStatus(past)}`;
5737
6131
  return `${who} is in ${active.length} ${where} at once${also}.`;
5738
6132
  }
5739
- 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)}.`;
5740
6134
  };
5741
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
+ };
5742
6147
  var leadCollisions = defineInsight({
5743
- 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.",
5744
6149
  inputSchema: input18,
5745
6150
  key: "leadCollisions",
5746
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),
@@ -5756,21 +6161,40 @@ var leadCollisions = defineInsight({
5756
6161
  "The redact plugin masks LinkedIn profiles, so people were matched by email address only."
5757
6162
  );
5758
6163
  }
5759
- const campaigns = await campaignsIn(
6164
+ const campaignsRead = await readCampaignsIn(
5760
6165
  context,
5761
6166
  values.statuses,
5762
6167
  values.max_campaigns
5763
6168
  );
6169
+ const campaigns = campaignsRead.items;
5764
6170
  const perCampaign = await mapConcurrent(campaigns, async (campaign) => {
5765
- const leads = await leadsOf(
6171
+ const leads = await readCappedFlag(
5766
6172
  context,
5767
- campaign.ref,
6173
+ (cap) => context.outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
5768
6174
  values.max_leads_per_campaign,
6175
+ "leads of a campaign",
5769
6176
  "max_leads_per_campaign"
5770
6177
  );
5771
- 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
+ };
5772
6183
  });
5773
- 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
+ );
5774
6198
  const overlaps = groupPeople(entries, keysOf).flatMap(toCollision);
5775
6199
  const pastOverlaps = overlaps.filter((each) => each.stillActive < 2).length;
5776
6200
  const collisions = overlaps.filter((each) => values.include_past || each.stillActive >= 2).toSorted(worstFirst);
@@ -5779,15 +6203,24 @@ var leadCollisions = defineInsight({
5779
6203
  ).length;
5780
6204
  const answer = {
5781
6205
  collisions,
6206
+ finding: overallOf(
6207
+ collisions.length,
6208
+ campaigns.length,
6209
+ values.include_past,
6210
+ incomplete
6211
+ ),
5782
6212
  totals: {
5783
6213
  acrossTools,
5784
6214
  campaignsRead: campaigns.length,
5785
- collisions: collisions.length,
6215
+ campaignsWithMoreLeads,
6216
+ collisions: incomplete === null ? collisions.length : null,
6217
+ collisionsFound: collisions.length,
5786
6218
  concurrent: collisions.filter((each) => each.stillActive >= 2).length,
5787
6219
  leadsRead: entries.length,
5788
6220
  leadsWithoutIdentifier: entries.filter(
5789
6221
  (entry) => keysOf(entry.lead).length === 0
5790
6222
  ).length,
6223
+ moreCampaignsExist: campaignsRead.capped,
5791
6224
  pastOverlaps,
5792
6225
  withinTool: collisions.length - acrossTools
5793
6226
  }
@@ -5818,9 +6251,9 @@ var repliedSteps = (lead, messages) => {
5818
6251
  steps.add(message.stepIndex ?? lastSent ?? 0);
5819
6252
  }
5820
6253
  }
5821
- const named4 = lead.engagement?.repliedStepIndex ?? null;
5822
- if (named4 !== null) {
5823
- steps.add(named4);
6254
+ const named5 = lead.engagement?.repliedStepIndex ?? null;
6255
+ if (named5 !== null) {
6256
+ steps.add(named5);
5824
6257
  }
5825
6258
  return [...steps].toSorted((left, right) => left - right);
5826
6259
  };
@@ -5935,16 +6368,12 @@ var byChannel2 = (campaigns) => {
5935
6368
  return channels;
5936
6369
  };
5937
6370
  var personSummary = defineInsight({
5938
- description: "Everything about one person across campaigns and channels, from one of lead_ref (a lead ref exactly as another tool returned it), email, linkedin_url, or person (any of the three): each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic, and a reply in the thread flagged automatic (isAuto, from the vendor or a fixed rule) is not counted either. A lead ref from a tool or workspace the instance does not read is refused before any request. Costs one lookup per identifier, one request to read a lead ref whose id is not already an address or profile (an Instantly reply's leadRef and a HeyReach ref need none), then up to 2 requests per campaign. Each campaign also carries its conversation's context: activity (the latest message, who sent it and when), meeting (what the vendor records on the lead, Instantly only), vendorSentiment (the vendor's labels, kept apart) and followUp, a fixed-rule assessment whose needed is true only when the latest message is inbound, not automatic and no meeting is recorded, with its evidence and what it could not check.",
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.",
5939
6372
  inputSchema: input19,
5940
6373
  key: "personSummary",
5941
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")),
5942
6375
  scales: "max_campaigns",
5943
6376
  name: "person_summary",
5944
- maskedOut: (masking) => {
5945
- const masked = new Set(masking.fields);
5946
- return masked.has("email") && masked.has("linkedin") && masking.strategy === "mask" ? "email addresses and LinkedIn profiles, which it looks a person up by" : null;
5947
- },
5948
6377
  needs: ["leads.lookup", "leads.timeline"],
5949
6378
  needsFor: (values) => refNeedsRead(personOf(values)) ? ["leads.get"] : [],
5950
6379
  next: "Use account_summary with their email domain to see everyone at the same company.",
@@ -6132,13 +6561,15 @@ var input21 = z24.object({
6132
6561
  lead_statuses: z24.array(leadStatusSchema).min(1).default([...SENDABLE]).describe(
6133
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."
6134
6563
  ),
6135
- max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
6136
- "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."
6137
6566
  ),
6138
- max_campaigns: z24.number().int().min(1).max(200).default(20).describe(
6139
- "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."
6140
6572
  ),
6141
- max_leads_per_campaign: z24.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
6142
6573
  statuses: statusesField
6143
6574
  });
6144
6575
  var slugOfEntry = (value) => profileSlug(value) ?? value.trim().replaceAll(/^\/+|\/+$/gu, "").toLowerCase();
@@ -6212,8 +6643,29 @@ var maskNote = (outbound) => {
6212
6643
  return masked.length === 0 ? null : `The redact plugin masks ${masked.join(" and ")}, so ${lost.join(" and ")} could not be matched to leads.`;
6213
6644
  };
6214
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
+ };
6215
6667
  var suppressionCheck = defineInsight({
6216
- 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.",
6217
6669
  inputSchema: input21,
6218
6670
  key: "suppressionCheck",
6219
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),
@@ -6236,11 +6688,12 @@ var suppressionCheck = defineInsight({
6236
6688
  if (unmatched !== null) {
6237
6689
  context.partial(unmatched);
6238
6690
  }
6239
- const campaigns = await campaignsIn(
6691
+ const listedCampaigns = await readCampaignsIn(
6240
6692
  context,
6241
6693
  values.statuses,
6242
6694
  values.max_campaigns
6243
6695
  );
6696
+ const campaigns = listedCampaigns.items;
6244
6697
  const sendable = new Set(values.lead_statuses);
6245
6698
  const violations = [];
6246
6699
  const byCampaign = [];
@@ -6276,7 +6729,20 @@ var suppressionCheck = defineInsight({
6276
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.`
6277
6730
  );
6278
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
+ );
6279
6744
  const answer = {
6745
+ finding: findingOf4(violations, campaigns.length, gaps),
6280
6746
  byCampaign: byCampaign.toSorted(
6281
6747
  (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
6282
6748
  ),
@@ -6290,10 +6756,13 @@ var suppressionCheck = defineInsight({
6290
6756
  linkedin: matches.get("linkedin") ?? 0
6291
6757
  },
6292
6758
  campaignsRead: campaigns.length,
6759
+ campaignsWithMoreLeads,
6293
6760
  leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
6294
6761
  moreBlockEntriesExist: listed2.capped,
6295
- moreLeadsExist: read.some((each) => each.capped),
6296
- violations: violations.length
6762
+ moreCampaignsExist: listedCampaigns.capped,
6763
+ moreLeadsExist: campaignsWithMoreLeads > 0,
6764
+ violations: gaps.length === 0 ? violations.length : null,
6765
+ violationsFound: violations.length
6297
6766
  },
6298
6767
  violations: violations.toSorted(activeFirst)
6299
6768
  };
@@ -6306,8 +6775,8 @@ import { z as z25 } from "zod";
6306
6775
  var SNIPPET_CHARS = 280;
6307
6776
  var ids = (what) => z25.array(z25.string().min(1)).max(100).default([]).describe(what);
6308
6777
  var input22 = z25.object({
6309
- bodies: z25.enum(["none", "snippet"]).default("snippet").describe(
6310
- "snippet returns the first 280 characters of each message, wrapped as untrusted content; none returns no text"
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"
6311
6780
  ),
6312
6781
  cursor: z25.string().min(1).nullable().default(null).describe(
6313
6782
  "coverage.nextCursor from the previous call with the same leads and threads, to read the next page of conversations"
@@ -6403,6 +6872,20 @@ var coverageOf = (records, reads, page) => {
6403
6872
  )
6404
6873
  };
6405
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
+ };
6406
6889
  var threadContexts = defineInsight({
6407
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.",
6408
6891
  inputSchema: input22,
@@ -6428,30 +6911,13 @@ var threadContexts = defineInsight({
6428
6911
  "No lead refs or thread ids were given, so nothing was read. Pass leads or threads."
6429
6912
  );
6430
6913
  }
6431
- if (values.bodies === "snippet" && (maskingOf(context.outbound)?.fields.includes("body") ?? false)) {
6432
- throw new OutboundError(
6433
- "Unsupported",
6434
- "thread_context: the redact plugin masks message bodies, so snippets cannot be returned; pass bodies: none"
6435
- );
6436
- }
6437
- for (const target of targets) {
6438
- const parts = target.kind === "lead" ? leadRefParts(target.id) : null;
6439
- if (target.kind === "lead" && parts === null) {
6440
- throw new OutboundError(
6441
- "Invalid",
6442
- `thread_context: "${target.id}" is not a lead ref (provider:workspace:id); pass the lead ref another tool returned`,
6443
- { provider: context.outbound.provider }
6444
- );
6445
- }
6446
- if (parts !== null) {
6447
- assertRefReadable(context.outbound, { ...parts, text: target.id });
6448
- }
6449
- }
6914
+ const bodies = bodiesOf(context, values.bodies);
6915
+ refuseUnreadable(context, targets);
6450
6916
  const start = startOf(values.cursor, targets.length);
6451
6917
  const page = targets.slice(start, start + values.page_size);
6452
6918
  const reads = await mapConcurrent(
6453
6919
  page,
6454
- (target) => readConversation(context, target, values.bodies === "snippet")
6920
+ (target) => readConversation(context, target, bodies === "snippet")
6455
6921
  );
6456
6922
  const refs = [
6457
6923
  ...new Set(
@@ -6474,9 +6940,10 @@ var threadContexts = defineInsight({
6474
6940
  context,
6475
6941
  read,
6476
6942
  ref === null ? void 0 : leads.get(ref),
6477
- values
6943
+ { ...values, bodies }
6478
6944
  );
6479
6945
  });
6946
+ markUnread(context, reads, refs, leads);
6480
6947
  if (start + page.length < targets.length) {
6481
6948
  context.partial(
6482
6949
  `Read ${start + page.length} of ${targets.length} conversations; pass coverage.nextCursor for the rest.`
@@ -7107,7 +7574,7 @@ var askOf = (reads) => {
7107
7574
  withoutLimit: reads.length - withLimit
7108
7575
  };
7109
7576
  };
7110
- var findingOf4 = (capacity, ask, sends) => {
7577
+ var findingOf5 = (capacity, ask, sends) => {
7111
7578
  if (capacity.daily === null) {
7112
7579
  return "No active sender reports a daily limit, so capacity is unknown.";
7113
7580
  }
@@ -7177,7 +7644,7 @@ var senderCapacity = defineInsight({
7177
7644
  ask,
7178
7645
  askRatio: rate(ask?.daily ?? null, capacity.daily),
7179
7646
  capacity,
7180
- finding: findingOf4(capacity, ask, sends),
7647
+ finding: findingOf5(capacity, ask, sends),
7181
7648
  sends,
7182
7649
  shortCampaigns: canCompare ? shortfalls.flatMap(
7183
7650
  (each) => each === null || each === "unchecked" ? [] : [each]
@@ -7673,10 +8140,102 @@ var INSIGHTS = [
7673
8140
  ];
7674
8141
  var ENTRIES = INSIGHTS;
7675
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
+
7676
8193
  // src/insights/tools.ts
7677
8194
  var INSIGHT_TOOL_CEILING = 500;
7678
8195
  var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
7679
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
+ };
7680
8239
  var hintFor = (next, offered) => {
7681
8240
  const hidden = ENTRIES.flatMap(
7682
8241
  (entry) => offered.has(entry.name) ? [] : [entry.name]
@@ -7684,7 +8243,29 @@ var hintFor = (next, offered) => {
7684
8243
  const kept = next.split(/(?<=\.)\s+/u).filter((sentence2) => !hidden.some((name) => sentence2.includes(name)));
7685
8244
  return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
7686
8245
  };
7687
- 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) => ({
7688
8269
  call: async (given, callOptions) => {
7689
8270
  const set = callOptions?.maxRequests ?? options.maxRequestsPerToolCall;
7690
8271
  const capSetting = options.capSetting ?? "maxRequestsPerToolCall";
@@ -7696,22 +8277,24 @@ var toTool = (outbound, definition, next, options) => ({
7696
8277
  `${definition.name}: the input is not JSON`
7697
8278
  );
7698
8279
  }
8280
+ const { target } = placement;
8281
+ const note = target === outbound ? null : insightPlacement(outbound, definition.name, options.members ?? [])?.note ?? null;
7699
8282
  const result = await definition.execute(
7700
- outbound,
8283
+ target,
7701
8284
  input29,
7702
8285
  set === void 0 ? { capCeiling: INSIGHT_TOOL_CEILING, capSetting } : { capSetting, maxRequests: set }
7703
8286
  );
7704
8287
  return {
7705
- data: result.data,
8288
+ data: withOfferedNext(result.data, offered),
7706
8289
  meta: {
7707
- complete: result.meta.complete,
8290
+ complete: result.meta.complete && note === null,
7708
8291
  computedAt: result.meta.computedAt,
7709
8292
  evidence: result.meta.evidence,
7710
- notes: [...result.meta.notes],
8293
+ notes: note === null ? [...result.meta.notes] : [note, ...result.meta.notes],
7711
8294
  provider: result.meta.provider,
7712
8295
  requests: result.meta.requests
7713
8296
  },
7714
- next,
8297
+ next: hintFor(definition.next, offered),
7715
8298
  ok: true
7716
8299
  };
7717
8300
  } catch (error) {
@@ -7726,7 +8309,7 @@ var toTool = (outbound, definition, next, options) => ({
7726
8309
  return failure(
7727
8310
  error,
7728
8311
  void 0,
7729
- 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
7730
8313
  );
7731
8314
  }
7732
8315
  },
@@ -7735,13 +8318,17 @@ var toTool = (outbound, definition, next, options) => ({
7735
8318
  name: definition.name,
7736
8319
  needs: [...definition.needs],
7737
8320
  // SAFETY: a JSON Schema document is JSON by definition.
7738
- parameters: z32.toJSONSchema(definition.inputSchema, { io: "input" })
8321
+ parameters: z33.toJSONSchema(definition.inputSchema, { io: "input" })
7739
8322
  });
7740
- var insightLeftOutReason = (outbound, name) => {
8323
+ var insightLeftOutReason = (outbound, name, members = []) => {
7741
8324
  const definition = ENTRIES.find((entry) => entry.name === name);
7742
- if (definition === void 0) {
8325
+ if (definition === void 0 || placementOf(outbound, definition, members) !== void 0) {
7743
8326
  return void 0;
7744
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
+ }
7745
8332
  const lacked = definition.lacks?.(outbound) ?? null;
7746
8333
  const absent = definition.needs.filter(
7747
8334
  (key) => outbound.capabilities[key] === false
@@ -7749,22 +8336,43 @@ var insightLeftOutReason = (outbound, name) => {
7749
8336
  if (lacked !== null) {
7750
8337
  return `${name} is not available: the ${outbound.provider} adapter does not report ${lacked}`;
7751
8338
  }
7752
- 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}`;
7753
8344
  };
7754
8345
  var insightTools = (outbound, options = {}) => {
7755
8346
  const wanted = options.only === void 0 ? void 0 : new Set(options.only);
7756
- const offered = ENTRIES.filter(
7757
- (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
7758
- );
7759
- 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));
7760
8353
  return offered.map(
7761
- (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
7762
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
+ };
7763
8373
  };
7764
8374
 
7765
8375
  export {
7766
- boundsOf,
7767
- defaultCap,
7768
8376
  defineInsight,
7769
8377
  runInsight,
7770
8378
  round,
@@ -7779,8 +8387,14 @@ export {
7779
8387
  compareRates,
7780
8388
  tally,
7781
8389
  INSIGHTS,
7782
- ENTRIES,
8390
+ runInsightByName,
8391
+ insightCost,
8392
+ listInsights,
8393
+ insights,
7783
8394
  INSIGHT_TOOL_CEILING,
8395
+ membersOf,
8396
+ insightPlacement,
7784
8397
  insightLeftOutReason,
7785
- insightTools
8398
+ insightTools,
8399
+ runPlaced
7786
8400
  };