outbound-sdk 0.5.0 → 0.6.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 (42) hide show
  1. package/dist/cards/format.d.ts +1 -1
  2. package/dist/cards/index.js +47 -18
  3. package/dist/cards/parts.d.ts +1 -6
  4. package/dist/chunks/{chunk-X4RDBD4J.js → chunk-3JOC5DGD.js} +26 -7
  5. package/dist/chunks/chunk-53DCVFUB.js +55 -0
  6. package/dist/chunks/{chunk-3S32R2MH.js → chunk-MGR6HREO.js} +0 -51
  7. package/dist/chunks/{chunk-EHSJGQ5K.js → chunk-PHNQ3WC2.js} +1 -1
  8. package/dist/chunks/{chunk-6TKFISG4.js → chunk-SXGCKCAR.js} +4 -2
  9. package/dist/chunks/{chunk-WGW3ROLY.js → chunk-TFICTGM2.js} +1 -1
  10. package/dist/chunks/{chunk-BN6WCAWX.js → chunk-W22SDX6S.js} +1 -1
  11. package/dist/cli/bin.js +3 -3
  12. package/dist/cli/index.js +2 -2
  13. package/dist/cli/output.d.ts +9 -0
  14. package/dist/emailbison/index.js +3 -2
  15. package/dist/heyreach/index.js +4 -2
  16. package/dist/insights/copy/copy-preview.d.ts +58 -0
  17. package/dist/insights/copy/copy-reuse.d.ts +0 -13
  18. package/dist/insights/copy/index.d.ts +9 -0
  19. package/dist/insights/copy/reuse-base.d.ts +0 -2
  20. package/dist/insights/copy/shared.d.ts +3 -8
  21. package/dist/insights/copy/step-funnel.d.ts +1 -12
  22. package/dist/insights/copy/variant-test.d.ts +0 -5
  23. package/dist/insights/index.js +504 -413
  24. package/dist/insights/inputs.generated.d.ts +21 -24
  25. package/dist/insights/ops/campaign-diagnosis.d.ts +0 -2
  26. package/dist/insights/ops/client-report.d.ts +0 -2
  27. package/dist/insights/ops/index.d.ts +0 -4
  28. package/dist/insights/ops/shared.d.ts +0 -2
  29. package/dist/insights/registry.d.ts +8 -8
  30. package/dist/insights/senders/bounce-watch.d.ts +0 -11
  31. package/dist/insights/senders/domain-health.d.ts +0 -7
  32. package/dist/insights/senders/index.d.ts +0 -4
  33. package/dist/insights/senders/sender-load.d.ts +0 -2
  34. package/dist/insights/types.d.ts +1 -1
  35. package/dist/insights/variables.d.ts +33 -0
  36. package/dist/instantly/index.js +5 -3
  37. package/dist/loader/index.js +1 -1
  38. package/dist/smartlead/index.js +5 -3
  39. package/dist/webhooks/index.js +5 -4
  40. package/package.json +1 -1
  41. package/dist/internal/renamed.d.ts +0 -28
  42. /package/dist/chunks/{chunk-5J7GGV62.js → chunk-UWUPUMM2.js} +0 -0
@@ -20,6 +20,10 @@ import {
20
20
  noun,
21
21
  shownKey
22
22
  } from "../chunks/chunk-PTZO4QXR.js";
23
+ import {
24
+ htmlToText,
25
+ looksLikeHtml
26
+ } from "../chunks/chunk-53DCVFUB.js";
23
27
  import {
24
28
  sumCounts
25
29
  } from "../chunks/chunk-PQSTQKRD.js";
@@ -38,7 +42,6 @@ import {
38
42
  OutboundError
39
43
  } from "../chunks/chunk-J7DDZ4C2.js";
40
44
  import {
41
- isJsonObject,
42
45
  jsonInput,
43
46
  toJson,
44
47
  unknownKey
@@ -96,15 +99,15 @@ var pricer = (outbound, costs, most, found) => {
96
99
  }
97
100
  };
98
101
  };
99
- var boundsOf = (outbound, cost, input27, found) => {
102
+ var boundsOf = (outbound, cost, input28, found) => {
100
103
  const costs = cappedAccess(outbound)?.costs;
101
104
  if (cost === void 0 || costs === void 0) {
102
105
  return null;
103
106
  }
104
107
  try {
105
108
  return {
106
- max: cost(input27, pricer(outbound, costs, true, found)),
107
- min: cost(input27, pricer(outbound, costs, false, found))
109
+ max: cost(input28, pricer(outbound, costs, true, found)),
110
+ min: cost(input28, pricer(outbound, costs, false, found))
108
111
  };
109
112
  } catch (error) {
110
113
  if (error === UNKNOWN) {
@@ -145,8 +148,8 @@ var stopped = (name, stop, provider) => capError(
145
148
  stop,
146
149
  provider
147
150
  );
148
- var fitting = (outbound, cost, input27, name, room, found) => {
149
- const fields = input27;
151
+ var fitting = (outbound, cost, input28, name, room, found) => {
152
+ const fields = input28;
150
153
  const current = fields[name];
151
154
  if (typeof current !== "number" || current <= 1) {
152
155
  return void 0;
@@ -178,49 +181,7 @@ var fitting = (outbound, cost, input27, name, room, found) => {
178
181
  };
179
182
 
180
183
  // src/insights/copy/copy-audit.ts
181
- import { z as z2 } from "zod";
182
-
183
- // src/internal/renamed.ts
184
184
  import { z } from "zod";
185
- var REMOVED_IN = "0.6.0";
186
- var renames = z.registry();
187
- var renamed = (to, base) => {
188
- const field = base.optional().meta({
189
- deprecated: true,
190
- description: `Deprecated: renamed to \`${to}\`. Removed in ${REMOVED_IN}.`
191
- });
192
- renames.add(field, { to });
193
- return field;
194
- };
195
- var renamesIn = (fields) => Object.entries(fields).flatMap(([from, schema]) => {
196
- const link = renames.get(schema);
197
- return link === void 0 ? [] : [{ from, to: link.to }];
198
- });
199
- var liveKeys = (fields) => {
200
- const old = new Set(renamesIn(fields).map((each) => each.from));
201
- return Object.keys(fields).filter((key) => !old.has(key));
202
- };
203
- var applyRenames = (fields, input27) => {
204
- if (!isJsonObject(input27)) {
205
- return { input: input27, notes: [] };
206
- }
207
- const moved = new Map(Object.entries(input27));
208
- const notes = [];
209
- for (const { from, to } of renamesIn(fields)) {
210
- const value = moved.get(from);
211
- moved.delete(from);
212
- if (value !== void 0) {
213
- if (moved.get(to) !== void 0) {
214
- return { conflict: { from, to } };
215
- }
216
- moved.set(to, value);
217
- notes.push(
218
- `\`${from}\` is deprecated and will be removed in ${REMOVED_IN}; use \`${to}\`.`
219
- );
220
- }
221
- }
222
- return { input: Object.fromEntries(moved), notes };
223
- };
224
185
 
225
186
  // src/insights/run-cap.ts
226
187
  var capFor = (outbound, name, max, options) => {
@@ -241,12 +202,12 @@ var capFor = (outbound, name, max, options) => {
241
202
  };
242
203
  var hasRunBudget = (outbound) => "requestBudget" in outbound;
243
204
  var runBudgetLeft = (outbound) => hasRunBudget(outbound) && outbound.requestBudget.per === "run" ? outbound.requestBudget.remaining() : Infinity;
244
- var runCap = (outbound, spec, input27, options) => {
245
- const bounds = boundsOf(outbound, spec.cost, input27);
205
+ var runCap = (outbound, spec, input28, options) => {
206
+ const bounds = boundsOf(outbound, spec.cost, input28);
246
207
  const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
247
208
  const stop = (room, found) => ({
248
209
  ...effect,
249
- lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input27, spec.scales, room, found),
210
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input28, spec.scales, room, found),
250
211
  requests: counter.used()
251
212
  });
252
213
  const counter = requestCounter(
@@ -255,7 +216,7 @@ var runCap = (outbound, spec, input27, options) => {
255
216
  );
256
217
  const check = (found) => {
257
218
  const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
258
- const least = boundsOf(outbound, spec.cost, input27, found);
219
+ const least = boundsOf(outbound, spec.cost, input28, found);
259
220
  if (least !== null && least.min > room) {
260
221
  throw refusal(
261
222
  spec.name,
@@ -357,34 +318,19 @@ var track = (outbound, now, campaignsFound) => {
357
318
  };
358
319
  };
359
320
  var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
360
- var withRenames = (outbound, spec, given) => {
361
- const renamed2 = applyRenames(spec.inputSchema.shape, given);
362
- if ("conflict" in renamed2) {
363
- const { from, to } = renamed2.conflict;
364
- throw new OutboundError(
365
- "Invalid",
366
- `${spec.name}: pass \`${to}\` only; \`${from}\` is its old name`,
367
- { provider: outbound.provider }
368
- );
369
- }
370
- return renamed2;
371
- };
372
- var prepare = (outbound, spec, given) => {
373
- const fields = spec.inputSchema.shape;
374
- const renamed2 = withRenames(outbound, spec, given);
375
- const { input: input27 } = renamed2;
376
- const stray = unknownKey(liveKeys(fields), input27);
321
+ var prepare = (outbound, spec, input28) => {
322
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input28);
377
323
  if (stray !== void 0) {
378
324
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
379
325
  provider: outbound.provider
380
326
  });
381
327
  }
382
- const parsed = spec.inputSchema.safeParse(input27 ?? {});
328
+ const parsed = spec.inputSchema.safeParse(input28 ?? {});
383
329
  if (!parsed.success) {
384
330
  const [issue] = parsed.error.issues;
385
331
  throw new OutboundError(
386
332
  "Invalid",
387
- `${spec.name}: ${inputProblem(input27, issue)}`,
333
+ `${spec.name}: ${inputProblem(input28, issue)}`,
388
334
  { provider: outbound.provider }
389
335
  );
390
336
  }
@@ -413,17 +359,14 @@ var prepare = (outbound, spec, given) => {
413
359
  { provider: outbound.provider }
414
360
  );
415
361
  }
416
- return { input: parsed.data, notes: renamed2.notes };
362
+ return parsed.data;
417
363
  };
418
- var execute = async (outbound, spec, input27, options = {}) => {
419
- const checked = prepare(outbound, spec, input27);
420
- const cap = runCap(outbound, spec, checked.input, options);
364
+ var execute = async (outbound, spec, input28, options = {}) => {
365
+ const checked = prepare(outbound, spec, input28);
366
+ const cap = runCap(outbound, spec, checked, options);
421
367
  const now = options.now ?? Date.now();
422
368
  const tracker = track(cap.outbound, now, cap.campaignsFound);
423
- for (const note of checked.notes) {
424
- tracker.context.note(note);
425
- }
426
- const data = await spec.run(tracker.context, checked.input).catch(cap.failed);
369
+ const data = await spec.run(tracker.context, checked).catch(cap.failed);
427
370
  const short = cap.shortNote();
428
371
  if (short !== void 0) {
429
372
  tracker.context.partial(short);
@@ -440,14 +383,14 @@ var execute = async (outbound, spec, input27, options = {}) => {
440
383
  };
441
384
  var defineInsight = (spec) => ({
442
385
  ...spec,
443
- execute: async (outbound, input27, options) => {
444
- const result = await execute(outbound, spec, input27, options);
386
+ execute: async (outbound, input28, options) => {
387
+ const result = await execute(outbound, spec, input28, options);
445
388
  return { ...result, data: toJson(result.data) };
446
389
  }
447
390
  });
448
- var runInsight = (outbound, definition, input27, options = {}) => (
391
+ var runInsight = (outbound, definition, input28, options = {}) => (
449
392
  // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
450
- execute(outbound, definition, input27, options)
393
+ execute(outbound, definition, input28, options)
451
394
  );
452
395
 
453
396
  // src/insights/copy/copy-checks.ts
@@ -524,12 +467,12 @@ var tooManyLinks = (body, limits) => {
524
467
  } : null;
525
468
  };
526
469
  var spamWords = (text, limits) => {
527
- const plain = visible(text);
470
+ const plain2 = visible(text);
528
471
  const hits = limits.spamWords.filter(
529
472
  (word) => word.trim() !== "" && new RegExp(
530
473
  String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
531
474
  "iu"
532
- ).test(plain)
475
+ ).test(plain2)
533
476
  );
534
477
  return hits.length > 0 ? {
535
478
  check: "spam_words",
@@ -590,9 +533,9 @@ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChar
590
533
  } : null;
591
534
 
592
535
  // src/insights/copy/copy-audit.ts
593
- var limit = (fallback, description) => z2.number().int().min(0).default(fallback).describe(description);
594
- var input = z2.object({
595
- campaign: z2.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
536
+ var limit = (fallback, description) => z.number().int().min(0).default(fallback).describe(description);
537
+ var input = z.object({
538
+ campaign: z.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
596
539
  max_body_words: limit(150, "The most words a body may have."),
597
540
  max_caps_words: limit(
598
541
  1,
@@ -605,7 +548,7 @@ var input = z2.object({
605
548
  max_exclamations: limit(1, "How many exclamation marks a message may have."),
606
549
  max_links: limit(1, "The most links an email body may have."),
607
550
  max_subject_chars: limit(60, "The most characters a subject may have."),
608
- spam_words: z2.array(z2.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
551
+ spam_words: z.array(z.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
609
552
  "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
610
553
  )
611
554
  });
@@ -752,9 +695,12 @@ var copyAudit = defineInsight({
752
695
  }
753
696
  });
754
697
 
755
- // src/insights/copy/copy-reuse.ts
698
+ // src/insights/copy/copy-preview.ts
756
699
  import { z as z4 } from "zod";
757
700
 
701
+ // src/insights/people/read.ts
702
+ import { z as z3 } from "zod";
703
+
758
704
  // src/insights/capped.ts
759
705
  var readCapped = async (context, open, cap, room = cap.max) => {
760
706
  if (room >= 1) {
@@ -773,10 +719,10 @@ var campaignsReadOf = (read) => ({
773
719
  campaignsRead: read.items.length,
774
720
  moreCampaignsExist: read.capped
775
721
  });
776
- var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns") => {
722
+ var readCampaignsIn = async (context, statuses, max, input28 = "max_campaigns") => {
777
723
  const { campaigns } = context.outbound;
778
724
  const wanted = [...new Set(statuses)];
779
- const cap = { input: input27, max, what: "campaigns" };
725
+ const cap = { input: input28, max, what: "campaigns" };
780
726
  if (context.outbound.capabilities["campaigns.status"] === false) {
781
727
  const every = await readCapped(
782
728
  context,
@@ -806,15 +752,314 @@ var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns")
806
752
  };
807
753
 
808
754
  // src/insights/fields.ts
809
- import { z as z3 } from "zod";
755
+ import { z as z2 } from "zod";
810
756
  var rangeFields = {
811
- from: z3.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
812
- to: z3.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
757
+ from: z2.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
758
+ to: z2.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
813
759
  };
814
- var statusesInput = (fallback) => z3.array(campaignStatusSchema).min(1).default([...fallback]).describe(
760
+ var statusesInput = (fallback) => z2.array(campaignStatusSchema).min(1).default([...fallback]).describe(
815
761
  "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
816
762
  );
817
763
 
764
+ // src/insights/people/read.ts
765
+ var readCappedFlag = (context, open, max, what, input28) => readCapped(context, open, { input: input28, max, what });
766
+ var readByRef = async (context, refs, read, what, effect) => {
767
+ if (refs.length === 0) {
768
+ return /* @__PURE__ */ new Map();
769
+ }
770
+ const found = await read(refs);
771
+ if (found.errors.length > 0) {
772
+ context.note(
773
+ `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
774
+ );
775
+ }
776
+ const [costliest] = found.results.toSorted(
777
+ (left, right) => right.value.meta.requests - left.value.meta.requests
778
+ );
779
+ if (costliest !== void 0) {
780
+ context.one(costliest.value);
781
+ }
782
+ return new Map(found.results.map(({ id, value }) => [id, value]));
783
+ };
784
+ var statusesField = statusesInput(["active"]);
785
+ var campaignsIn = async (context, statuses, max) => {
786
+ const { items } = await readCampaignsIn(context, statuses, max);
787
+ return items;
788
+ };
789
+ var leadsOf = async (context, campaign, max, input28) => {
790
+ const { items } = await readCappedFlag(
791
+ context,
792
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
793
+ max,
794
+ "leads of a campaign",
795
+ input28
796
+ );
797
+ return items;
798
+ };
799
+ var nameOf = (lead) => {
800
+ const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
801
+ return name === "" ? null : name;
802
+ };
803
+ var domainOf = (email) => {
804
+ const domain = email?.split("@").at(-1) ?? "";
805
+ return email === null || !email.includes("@") || domain === "" ? null : domain;
806
+ };
807
+ var DEFAULT_POSITIVE_LABELS = [
808
+ "Interested",
809
+ "Meeting Booked",
810
+ "Meeting Completed"
811
+ ];
812
+ var positiveLabelsField = z3.array(z3.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
813
+ "Vendor interest labels that count as interested, matched without regard to case"
814
+ );
815
+ var isPositive = (label, labels) => label === null ? null : labels.some(
816
+ (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
817
+ );
818
+ var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
819
+ var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
820
+ var AUTOMATIC = /* @__PURE__ */ new Set([
821
+ "bounce",
822
+ "ooo"
823
+ ]);
824
+ var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
825
+ lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
826
+ var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
827
+ var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
828
+ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
829
+ var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
830
+ var COUNTS = "no per-lead open, click or reply counts";
831
+ var noteEngagement = (context, leads, effect) => {
832
+ const { outbound } = context;
833
+ if (outbound.capabilities["leads.engagement"]) {
834
+ return;
835
+ }
836
+ if (leads.every((lead) => lead.provider === outbound.provider)) {
837
+ context.note(`This tool reports ${COUNTS}, so ${effect}.`);
838
+ return;
839
+ }
840
+ const reporting = new Set(
841
+ leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
842
+ );
843
+ const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
844
+ if (lacking.length > 0) {
845
+ context.note(
846
+ `${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.`
847
+ );
848
+ }
849
+ };
850
+
851
+ // src/insights/ref.ts
852
+ var refOf = (outbound, id) => {
853
+ const provider = parseRef(id)?.provider;
854
+ return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
855
+ };
856
+
857
+ // src/insights/variables.ts
858
+ var PATTERNS = [
859
+ /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
860
+ /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
861
+ /%(?<name>[A-Za-z_][\w-]*)%/gu
862
+ ];
863
+ var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
864
+ var BUILTINS = /* @__PURE__ */ new Map([
865
+ ["company", (lead) => lead.company],
866
+ ["companyname", (lead) => lead.company],
867
+ ["email", (lead) => lead.email],
868
+ ["firstname", (lead) => lead.firstName],
869
+ ["jobtitle", (lead) => lead.title],
870
+ ["lastname", (lead) => lead.lastName],
871
+ ["title", (lead) => lead.title]
872
+ ]);
873
+ var isBuiltin = (key) => BUILTINS.has(key);
874
+ var variablesIn = (text) => PATTERNS.flatMap(
875
+ (pattern) => [...text.matchAll(pattern)].map((match) => {
876
+ const fallback = match.groups?.fallback;
877
+ return {
878
+ fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
879
+ index: match.index,
880
+ name: match.groups?.name ?? "",
881
+ raw: match[0]
882
+ };
883
+ })
884
+ );
885
+ var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
886
+ var valueOf = (lead, key) => {
887
+ const builtin = BUILTINS.get(key)?.(lead);
888
+ if (filled(builtin)) {
889
+ return builtin;
890
+ }
891
+ const custom = Object.entries(lead.custom).find(
892
+ ([name, value]) => keyOf(name) === key && filled(value)
893
+ );
894
+ return custom?.[1] ?? null;
895
+ };
896
+ var keysWithValue = (lead) => /* @__PURE__ */ new Set([
897
+ ...[...BUILTINS].flatMap(
898
+ ([key, read]) => filled(read(lead)) ? [key] : []
899
+ ),
900
+ ...Object.entries(lead.custom).flatMap(
901
+ ([key, value]) => filled(value) ? [keyOf(key)] : []
902
+ )
903
+ ]);
904
+ var fillVariables = (text, lead) => {
905
+ const matches = variablesIn(text).toSorted(
906
+ (left, right) => left.index - right.index
907
+ );
908
+ const unfilled = [];
909
+ let out = "";
910
+ let at = 0;
911
+ for (const match of matches) {
912
+ if (match.index >= at) {
913
+ const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
914
+ if (value === null && !unfilled.includes(match.name)) {
915
+ unfilled.push(match.name);
916
+ }
917
+ out += text.slice(at, match.index) + (value ?? match.raw);
918
+ at = match.index + match.raw.length;
919
+ }
920
+ }
921
+ return { text: out + text.slice(at), unfilled };
922
+ };
923
+
924
+ // src/insights/copy/copy-preview.ts
925
+ var input2 = z4.object({
926
+ campaign: z4.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
927
+ lead: z4.string().min(1).nullable().default(null).describe(
928
+ "The lead's ref to render the copy for. null picks the lead read with the most variables filled."
929
+ ),
930
+ max_leads: z4.number().int().min(1).max(1e3).default(100).describe(
931
+ "The most leads to read when picking one. Ignored when `lead` is given."
932
+ )
933
+ });
934
+ var LEAD_FIELDS = /* @__PURE__ */ new Set(["company", "custom", "email", "name"]);
935
+ var keysIn = (sequence2) => new Set(
936
+ sequence2.steps.flatMap(
937
+ (step) => step.variants.flatMap(
938
+ (variant) => [variant.subject ?? "", variant.body ?? ""].flatMap(
939
+ (text) => variablesIn(text).map((match) => keyOf(match.name))
940
+ )
941
+ )
942
+ )
943
+ );
944
+ var bestLead = (leads, keys) => {
945
+ let best;
946
+ for (const lead of leads) {
947
+ const has = keysWithValue(lead);
948
+ const score = [...keys].filter((key) => has.has(key)).length;
949
+ if (best === void 0 || score > best.score) {
950
+ best = { lead, score };
951
+ }
952
+ }
953
+ return best?.lead;
954
+ };
955
+ var render = (text, lead, unfilled) => {
956
+ if (text === null) {
957
+ return null;
958
+ }
959
+ if (lead === void 0) {
960
+ for (const match of variablesIn(text)) {
961
+ if (match.fallback === null) {
962
+ unfilled.add(match.name);
963
+ }
964
+ }
965
+ return text;
966
+ }
967
+ const filled2 = fillVariables(text, lead);
968
+ for (const name of filled2.unfilled) {
969
+ unfilled.add(name);
970
+ }
971
+ return filled2.text;
972
+ };
973
+ var plain = (body) => {
974
+ if (body === null) {
975
+ return null;
976
+ }
977
+ return looksLikeHtml(body) ? htmlToText(body) : body.trim();
978
+ };
979
+ var previewStep = (step, lead) => ({
980
+ action: step.action,
981
+ delayDays: step.delayDays,
982
+ step: step.index,
983
+ variants: step.variants.map((variant) => {
984
+ const unfilled = /* @__PURE__ */ new Set();
985
+ const subject = render(variant.subject, lead, unfilled);
986
+ const body = render(variant.body, lead, unfilled);
987
+ return {
988
+ rendered: { body, bodyText: plain(body), subject },
989
+ template: { body: variant.body, subject: variant.subject },
990
+ unfilled: [...unfilled],
991
+ variantKey: variant.variantKey
992
+ };
993
+ })
994
+ });
995
+ var copyPreview = defineInsight({
996
+ description: "A campaign's copy as written and as one real lead receives it. Returns every step and variant with its subject and body exactly as stored, the same copy with the lead's values put into each {{variable}}, {variable} and %variable%, and the rendered body as plain text. Use it to read copy that is all or partly templated, such as {{subject1}} and {{content1}} filled from custom fields. Values come from first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens; a missing value falls back to the copy's own fallback, such as {{firstName|there}}, and otherwise the variable is left as written and listed as unfilled. Pass a lead's ref to choose the lead, or leave it out to use the lead read with the most variables filled. A sender signature or other variable the tool fills itself at send time stays as written. Spintax is not resolved. Costs one request for the sequence plus one for a given lead, or one per page of leads read.",
997
+ inputSchema: input2,
998
+ key: "copyPreview",
999
+ cost: (values, price) => price.one("sequence.get") + (values.lead === null ? price.upTo(1) * price.list("leads.list", values.max_leads) : price.one("leads.get")),
1000
+ scales: "max_leads",
1001
+ name: "copy_preview",
1002
+ needs: ["sequence", "leads.byCampaign"],
1003
+ next: "Use personalization_gaps to find every lead who would get a variable left as written.",
1004
+ run: async (context, values) => {
1005
+ const sequence2 = context.one(
1006
+ await context.outbound.campaign(values.campaign).sequence()
1007
+ );
1008
+ const keys = keysIn(sequence2);
1009
+ let lead;
1010
+ if (values.lead !== null) {
1011
+ lead = context.one(await context.outbound.lead(values.lead).get());
1012
+ } else if (keys.size === 0) {
1013
+ context.note("The copy uses no variables, so no lead was read.");
1014
+ } else {
1015
+ lead = bestLead(
1016
+ await leadsOf(context, values.campaign, values.max_leads, "max_leads"),
1017
+ keys
1018
+ );
1019
+ if (lead === void 0) {
1020
+ context.note(
1021
+ "The campaign has no leads, so the copy is shown as written."
1022
+ );
1023
+ }
1024
+ }
1025
+ const masked = maskingOf(context.outbound)?.fields.some(
1026
+ (field) => LEAD_FIELDS.has(field)
1027
+ );
1028
+ if (lead !== void 0 && masked === true) {
1029
+ context.note(
1030
+ "The redact plugin masks the lead's fields, so the rendered copy shows them masked. Read it without redact to see the values."
1031
+ );
1032
+ }
1033
+ const steps = sequence2.steps.map((step) => previewStep(step, lead));
1034
+ const unfilled = new Set(
1035
+ steps.flatMap(
1036
+ (step) => step.variants.flatMap((variant) => variant.unfilled.map(keyOf))
1037
+ )
1038
+ );
1039
+ const has = lead === void 0 ? null : keysWithValue(lead);
1040
+ const answer = {
1041
+ campaign: refOf(context.outbound, values.campaign),
1042
+ lead: lead === void 0 || has === null ? null : {
1043
+ email: lead.email,
1044
+ lead: lead.ref,
1045
+ linkedinUrl: lead.linkedinUrl,
1046
+ variablesFilled: [...keys].filter((key) => has.has(key)).length
1047
+ },
1048
+ steps,
1049
+ totals: {
1050
+ steps: steps.length,
1051
+ unfilled: unfilled.size,
1052
+ variables: keys.size,
1053
+ variants: steps.reduce((sum, step) => sum + step.variants.length, 0)
1054
+ }
1055
+ };
1056
+ return answer;
1057
+ }
1058
+ });
1059
+
1060
+ // src/insights/copy/copy-reuse.ts
1061
+ import { z as z5 } from "zod";
1062
+
818
1063
  // src/insights/stats.ts
819
1064
  var PLACES = 1e4;
820
1065
  var round = (value) => value === null || !Number.isFinite(value) ? null : Math.round(value * PLACES) / PLACES;
@@ -955,11 +1200,9 @@ var measure = (count2, base) => {
955
1200
  basis: base.basis,
956
1201
  count: count2,
957
1202
  high: interval?.high ?? null,
958
- interval,
959
1203
  low: interval?.low ?? null,
960
1204
  of: base.trials,
961
- rate: rate(count2, base.trials),
962
- trials: base.trials
1205
+ rate: rate(count2, base.trials)
963
1206
  };
964
1207
  };
965
1208
  var NO_RATE = {
@@ -1021,7 +1264,7 @@ var pooled = (counts, baseOf) => {
1021
1264
  return one === null || one.rate === null ? [] : [one];
1022
1265
  });
1023
1266
  const replies2 = total(measured2.map((each) => each.count));
1024
- const trials = total(measured2.map((each) => each.trials));
1267
+ const trials = total(measured2.map((each) => each.of));
1025
1268
  const bases = new Set(measured2.map((each) => each.basis));
1026
1269
  const [basis = null] = bases.size === 1 ? bases : [];
1027
1270
  return {
@@ -1058,11 +1301,11 @@ var sharedBaseOf = (context, counted2) => {
1058
1301
  };
1059
1302
 
1060
1303
  // src/insights/copy/copy-reuse.ts
1061
- var input2 = z4.object({
1062
- max_campaigns: z4.number().int().min(1).max(200).default(20).describe(
1304
+ var input3 = z5.object({
1305
+ max_campaigns: z5.number().int().min(1).max(200).default(20).describe(
1063
1306
  "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
1064
1307
  ),
1065
- min_sent: z4.number().int().min(1).default(100).describe(
1308
+ min_sent: z5.number().int().min(1).default(100).describe(
1066
1309
  "The smallest base (sends, or leads contacted when the vendor counts those) a campaign needs to count in the spread, and a piece of copy needs to be named the best."
1067
1310
  ),
1068
1311
  statuses: statusesInput(["active", "paused", "completed"])
@@ -1105,10 +1348,7 @@ var useOf = (placements, baseOf) => {
1105
1348
  provider: first.campaign.provider,
1106
1349
  rates: { replyRate: replyRateOf(sum) },
1107
1350
  replies: sum.count,
1108
- replyRate: sum.rate,
1109
- replyRateInterval: sum.interval,
1110
- sent: sum.sent,
1111
- trials: sum.trials
1351
+ sent: sum.sent
1112
1352
  }
1113
1353
  ];
1114
1354
  };
@@ -1129,18 +1369,15 @@ var pieceOf = (placements, uses, baseOf) => {
1129
1369
  contentHash: first.contentHash,
1130
1370
  rates: { replyRate: replyRateOf(sum) },
1131
1371
  replies: sum.count,
1132
- replyRate: sum.rate,
1133
- replyRateInterval: sum.interval,
1134
1372
  sent: sum.sent,
1135
- subject: first.subject,
1136
- trials: sum.trials
1373
+ subject: first.subject
1137
1374
  }
1138
1375
  ];
1139
1376
  };
1140
- var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
1377
+ var byRate = ({ rates: { replyRate: left } }, { rates: { replyRate: right } }) => (right.rate ?? -1) - (left.rate ?? -1) || (right.of ?? 0) - (left.of ?? 0);
1141
1378
  var spreadOf = (uses, minSent, comparable) => {
1142
1379
  const judged = uses.filter(
1143
- (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
1380
+ (use) => use.rates.replyRate.rate !== null && (use.rates.replyRate.of ?? 0) >= minSent
1144
1381
  );
1145
1382
  const [best] = judged;
1146
1383
  const worst = judged.at(-1);
@@ -1155,14 +1392,16 @@ var spreadOf = (uses, minSent, comparable) => {
1155
1392
  };
1156
1393
  }
1157
1394
  const test = compareRates(
1158
- { successes: best.replies, trials: best.trials },
1159
- { successes: worst.replies, trials: worst.trials }
1395
+ { successes: best.replies, trials: best.rates.replyRate.of },
1396
+ { successes: worst.replies, trials: worst.rates.replyRate.of }
1160
1397
  );
1161
1398
  const real = test?.significant ?? false;
1162
1399
  return {
1163
1400
  best: best.campaign,
1164
- finding: real ? `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; a gap this size could be chance.`,
1165
- spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
1401
+ finding: real ? `The same copy gets ${percent(best.rates.replyRate.rate)} in ${best.campaignName} and ${percent(worst.rates.replyRate.rate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.rates.replyRate.rate)} in ${best.campaignName} and ${percent(worst.rates.replyRate.rate)} in ${worst.campaignName}; a gap this size could be chance.`,
1402
+ spread: round(
1403
+ (best.rates.replyRate.rate ?? 0) - (worst.rates.replyRate.rate ?? 0)
1404
+ ),
1166
1405
  spreadIsReal: real,
1167
1406
  spreadPValue: test?.pValue ?? null,
1168
1407
  worst: worst.campaign
@@ -1185,7 +1424,7 @@ var readPlacements = async (context, campaigns) => {
1185
1424
  };
1186
1425
  var copyReuse = defineInsight({
1187
1426
  description: "How the same piece of copy performs in different campaigns. Reads each campaign's sequence and step stats, matches variants by the hash of their subject and body, and returns every piece of copy used in two or more campaigns with its totals, its reply rate per campaign and the spread between its best and worst campaign, plus the copy with the highest pooled reply rate. Use it to tell a copy problem from an audience problem. Every rate is divided by the same base, leads contacted when every campaign counts them and messages sent otherwise; campaigns with no base in common are listed but not compared. Costs 2 requests per campaign plus the campaign listing. A null count means the vendor does not report it for that variant; it is never 0.",
1188
- inputSchema: input2,
1427
+ inputSchema: input3,
1189
1428
  key: "copyReuse",
1190
1429
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("sequence.get") + price.one("stats")),
1191
1430
  scales: "max_campaigns",
@@ -1220,7 +1459,7 @@ var copyReuse = defineInsight({
1220
1459
  (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
1221
1460
  );
1222
1461
  const [bestCopy] = pieces.flatMap(
1223
- ({ piece }) => comparable && piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
1462
+ ({ piece }) => comparable && piece.rates.replyRate.rate !== null && (piece.rates.replyRate.of ?? 0) >= min_sent ? [piece] : []
1224
1463
  ).toSorted(byRate);
1225
1464
  const result = {
1226
1465
  basis,
@@ -1236,35 +1475,29 @@ var copyReuse = defineInsight({
1236
1475
  });
1237
1476
 
1238
1477
  // src/insights/copy/reply-timing.ts
1239
- import { z as z5 } from "zod";
1478
+ import { z as z6 } from "zod";
1240
1479
 
1241
1480
  // src/insights/campaign.ts
1242
1481
  var confirmCampaign = async (context, campaign) => {
1243
1482
  context.one(await context.outbound.campaigns.get(campaign));
1244
1483
  };
1245
1484
 
1246
- // src/insights/ref.ts
1247
- var refOf = (outbound, id) => {
1248
- const provider = parseRef(id)?.provider;
1249
- return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
1250
- };
1251
-
1252
1485
  // src/insights/copy/reply-timing.ts
1253
1486
  var DAY_MS = 864e5;
1254
1487
  var MAX_UNPAIRED_SHARE = 0.25;
1255
1488
  var HOUR_MS = 36e5;
1256
1489
  var MINUTE_MS = 6e4;
1257
- var input3 = z5.object({
1258
- campaign: z5.string().min(1).nullable().default(null).describe(
1490
+ var input4 = z6.object({
1491
+ campaign: z6.string().min(1).nullable().default(null).describe(
1259
1492
  "A campaign's ref to look at one campaign; an unknown one is refused with NotFound. null looks at every campaign."
1260
1493
  ),
1261
- max_messages: z5.number().int().min(1).max(5e4).default(2e3).describe(
1494
+ max_messages: z6.number().int().min(1).max(5e4).default(2e3).describe(
1262
1495
  "The most messages to read, sent and received together. A page of messages costs 1 request."
1263
1496
  ),
1264
- since: z5.iso.datetime({ offset: true }).nullable().default(null).describe(
1497
+ since: z6.iso.datetime({ offset: true }).nullable().default(null).describe(
1265
1498
  "Only messages from this time on, ISO 8601. null means 30 days before now."
1266
1499
  ),
1267
- timezone_offset_minutes: z5.number().int().min(-720).max(840).default(0).describe(
1500
+ timezone_offset_minutes: z6.number().int().min(-720).max(840).default(0).describe(
1268
1501
  "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
1269
1502
  )
1270
1503
  });
@@ -1384,7 +1617,7 @@ var noteGaps = (context, unpaired, received) => {
1384
1617
  };
1385
1618
  var replyTiming = defineInsight({
1386
1619
  description: "How fast people reply and when. Pairs each received message with the last message sent before it in the same thread (or to the same lead) and returns the median, 75th and 90th percentile of hours to reply, the share of replies within 1, 24 and 72 hours, replies by weekday and by hour of day, the weekday and hour of the sends that drew replies, and how many replies could not be paired; over a quarter unpaired, the answer is marked partial, since a reply to a send from before `since` cannot pair and those are the slow ones. Use it to choose follow-up delays and sending hours. Costs 1 request per page of messages, up to max_messages. A null figure means no reply could be paired; auto-replies are not separated, because messages carry no auto flag.",
1387
- inputSchema: input3,
1620
+ inputSchema: input4,
1388
1621
  key: "replyTiming",
1389
1622
  cost: (values, price) => price.list("messages.list", values.max_messages) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")),
1390
1623
  scales: "max_messages",
@@ -1401,7 +1634,7 @@ var replyTiming = defineInsight({
1401
1634
  );
1402
1635
  const paired = pair(messages);
1403
1636
  const hours = paired.pairs.map((each) => (each.at - each.sentAt) / HOUR_MS);
1404
- const within = (limit3) => rate(hours.filter((value) => value <= limit3).length, hours.length);
1637
+ const within = (limit2) => rate(hours.filter((value) => value <= limit2).length, hours.length);
1405
1638
  const received = messages.filter((message) => message.direction === "in");
1406
1639
  const untimed = received.length - paired.replyTimes.length;
1407
1640
  const unpaired = paired.unpaired + untimed;
@@ -1439,11 +1672,11 @@ var replyTiming = defineInsight({
1439
1672
  });
1440
1673
 
1441
1674
  // src/insights/copy/step-funnel.ts
1442
- import { z as z6 } from "zod";
1443
- var input4 = z6.object({
1444
- campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1675
+ import { z as z7 } from "zod";
1676
+ var input5 = z7.object({
1677
+ campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1445
1678
  ...rangeFields,
1446
- min_reply_rate: z6.number().min(0).max(1).default(0).describe(
1679
+ min_reply_rate: z7.number().min(0).max(1).default(0).describe(
1447
1680
  "A step earns its place when the low end of its reply rate interval is above this. 0 asks only that the rate is reliably above zero."
1448
1681
  )
1449
1682
  });
@@ -1453,8 +1686,6 @@ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, c
1453
1686
  contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
1454
1687
  rates: { replyRate: replyRateOf(measured2) },
1455
1688
  replies: counts.replied,
1456
- replyRate: measured2.rate,
1457
- replyRateInterval: measured2.interval,
1458
1689
  sent: counts.sent,
1459
1690
  variantKey
1460
1691
  };
@@ -1462,18 +1693,14 @@ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, c
1462
1693
  var draftOf = (index, step, stats, minReplyRate) => {
1463
1694
  const counts = stats?.total ?? null;
1464
1695
  const measured2 = counts === null ? null : measure(counts.replied, perLead(counts));
1465
- const interval = measured2?.interval ?? null;
1466
1696
  return {
1467
1697
  action: step?.action ?? null,
1468
1698
  delayDays: step?.delayDays ?? null,
1469
- earnsPlace: interval === null ? null : interval.low > minReplyRate,
1699
+ earnsPlace: measured2 === null || measured2.low === null ? null : measured2.low > minReplyRate,
1470
1700
  inSequence: step !== void 0,
1471
1701
  parent: step === void 0 ? null : step.parentIndex,
1472
1702
  rates: { replyRate: replyRateOf(measured2) },
1473
1703
  replies: counts?.replied ?? null,
1474
- replyRate: measured2?.rate ?? null,
1475
- replyRateBasis: measured2?.basis ?? null,
1476
- replyRateInterval: interval,
1477
1704
  sent: counts?.sent ?? null,
1478
1705
  step: index,
1479
1706
  variants: variantsOf(stats, step)
@@ -1520,7 +1747,7 @@ var unattributedOf = (rows) => {
1520
1747
  };
1521
1748
  var stepFunnel = defineInsight({
1522
1749
  description: "Where a campaign's replies come from: one row per sequence step with its action, delay, sends, replies, reply rate with a 95% interval, its share of all replies and how far sends fell from the step before, plus rows per variant when the vendor splits them. Names the step with the most replies and the last step that still earns its place. Use it to decide whether to cut or rewrite follow-ups. Costs 2 requests. A null count means the vendor does not report it; it is never 0.",
1523
- inputSchema: input4,
1750
+ inputSchema: input5,
1524
1751
  key: "stepFunnel",
1525
1752
  cost: (_input, price) => price.one("sequence.get") + price.one("stats"),
1526
1753
  name: "step_funnel",
@@ -1577,18 +1804,18 @@ var stepFunnel = defineInsight({
1577
1804
  });
1578
1805
 
1579
1806
  // src/insights/copy/variant-test.ts
1580
- import { z as z7 } from "zod";
1807
+ import { z as z8 } from "zod";
1581
1808
  var METRICS = ["replied", "positive", "opened", "clicked"];
1582
- var input5 = z7.object({
1583
- alpha: z7.number().gt(0).max(0.5).default(0.05).describe(
1809
+ var input6 = z8.object({
1810
+ alpha: z8.number().gt(0).max(0.5).default(0.05).describe(
1584
1811
  "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1585
1812
  ),
1586
- campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1813
+ campaign: z8.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1587
1814
  ...rangeFields,
1588
- metric: z7.enum(METRICS).default("replied").describe(
1815
+ metric: z8.enum(METRICS).default("replied").describe(
1589
1816
  "What a variant is judged on. Replies and positive replies are divided by leads contacted (or sends); opens and clicks by messages delivered (or sends)."
1590
1817
  ),
1591
- min_sent: z7.number().int().min(1).default(100).describe(
1818
+ min_sent: z8.number().int().min(1).default(100).describe(
1592
1819
  "A variant with a smaller base than this (sends, or leads contacted when the vendor counts those) is not compared."
1593
1820
  )
1594
1821
  });
@@ -1606,7 +1833,7 @@ var candidateOf = (variantKey, counts, base, minSent, metric) => {
1606
1833
  const measured2 = measure(counts[metric], base);
1607
1834
  return {
1608
1835
  ...measured2,
1609
- enoughData: measured2.rate !== null && measured2.trials !== null && measured2.trials >= minSent,
1836
+ enoughData: measured2.rate !== null && measured2.of !== null && measured2.of >= minSent,
1610
1837
  sent: counts.sent,
1611
1838
  variantKey
1612
1839
  };
@@ -1616,7 +1843,7 @@ var shortfall = (candidates, minSent) => {
1616
1843
  return null;
1617
1844
  }
1618
1845
  return candidates.reduce(
1619
- (sum, each) => sum + Math.max(0, minSent - (each.trials ?? 0)),
1846
+ (sum, each) => sum + Math.max(0, minSent - (each.of ?? 0)),
1620
1847
  0
1621
1848
  );
1622
1849
  };
@@ -1643,7 +1870,7 @@ var testStep = (step, candidates, settings, comparable) => {
1643
1870
  return tooLittle(step, candidates, settings, false);
1644
1871
  }
1645
1872
  const ready = candidates.filter((each) => each.enoughData).toSorted(
1646
- (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
1873
+ (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.of ?? 0) - (left.of ?? 0)
1647
1874
  );
1648
1875
  const [leader, rival] = ready;
1649
1876
  if (leader === void 0 || rival === void 0) {
@@ -1653,8 +1880,8 @@ var testStep = (step, candidates, settings, comparable) => {
1653
1880
  ready.slice(1).map((other) => [
1654
1881
  other.variantKey,
1655
1882
  compareRates(
1656
- { successes: leader.count, trials: leader.trials },
1657
- { successes: other.count, trials: other.trials },
1883
+ { successes: leader.count, trials: leader.of },
1884
+ { successes: other.count, trials: other.of },
1658
1885
  settings.alpha
1659
1886
  )
1660
1887
  ])
@@ -1682,7 +1909,7 @@ var testStep = (step, candidates, settings, comparable) => {
1682
1909
  leader: leader.variantKey,
1683
1910
  moreSendsNeeded: closest === null ? null : sendsToSignificance(
1684
1911
  closest.z,
1685
- (leader.trials ?? 0) + (rival.trials ?? 0),
1912
+ (leader.of ?? 0) + (rival.of ?? 0),
1686
1913
  settings.alpha
1687
1914
  ),
1688
1915
  pValue: closest?.pValue ?? null,
@@ -1727,7 +1954,7 @@ var variantsReported = (context, rows) => {
1727
1954
  var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1728
1955
  var variantTest = defineInsight({
1729
1956
  description: "Whether a campaign's A/B winner is real. For each step with two or more variants, compares every variant with the leader by a two-proportion test and returns the variants with rates and 95% intervals, the leader, and a verdict: winner, no_difference_yet or too_little_data, with the p-value and a rough number of sends still needed when there is no verdict. Use it before pausing a variant. Costs 1 request. A null count or rate means the vendor does not report it; an empty list means the vendor does not split step stats by variant (variantStatsReported false) or reported no step stats in the date range (null). Variants of a step are divided by the same base; variants with no base in common are not compared.",
1730
- inputSchema: input5,
1957
+ inputSchema: input6,
1731
1958
  key: "variantTest",
1732
1959
  cost: (_input, price) => price.one("stats"),
1733
1960
  name: "variant_test",
@@ -1767,15 +1994,16 @@ var COPY_INSIGHTS = [
1767
1994
  stepFunnel,
1768
1995
  variantTest,
1769
1996
  copyAudit,
1997
+ copyPreview,
1770
1998
  copyReuse,
1771
1999
  replyTiming
1772
2000
  ];
1773
2001
 
1774
2002
  // src/insights/ops/anomalies.ts
1775
- import { z as z9 } from "zod";
2003
+ import { z as z10 } from "zod";
1776
2004
 
1777
2005
  // src/insights/ops/shared.ts
1778
- import { z as z8 } from "zod";
2006
+ import { z as z9 } from "zod";
1779
2007
  var DAY_MS2 = 864e5;
1780
2008
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1781
2009
  var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
@@ -1783,19 +2011,18 @@ var lastDays = (now, days, back = 0) => ({
1783
2011
  from: dayOf(now - days * (back + 1) * DAY_MS2),
1784
2012
  to: dayOf(now - (days * back + 1) * DAY_MS2)
1785
2013
  });
1786
- var campaignTotalsCost = (input27, price) => {
1787
- const campaigns = price.campaigns(input27.max_campaigns);
1788
- return price.campaignsIn(new Set(input27.statuses).size, input27.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
2014
+ var campaignTotalsCost = (input28, price) => {
2015
+ const campaigns = price.campaigns(input28.max_campaigns);
2016
+ return price.campaignsIn(new Set(input28.statuses).size, input28.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
1789
2017
  };
1790
2018
  var listFields = (costPerCampaign) => ({
1791
- max_campaigns: z8.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
2019
+ max_campaigns: z9.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1792
2020
  statuses: statusesInput(["active", "paused", "completed"])
1793
2021
  });
1794
2022
  var labelOf = (campaign) => ({
1795
2023
  campaign: campaign.ref,
1796
2024
  campaignName: campaign.name,
1797
2025
  channel: campaign.channel,
1798
- name: campaign.name,
1799
2026
  provider: campaign.provider,
1800
2027
  status: campaign.status
1801
2028
  });
@@ -1900,19 +2127,19 @@ var readAllTotals = async (context, range) => {
1900
2127
  [...byCampaign].map(([ref, counts]) => [ref, sumCounts(counts)])
1901
2128
  );
1902
2129
  };
1903
- var readCampaignTotals = async (context, input27) => {
2130
+ var readCampaignTotals = async (context, input28) => {
1904
2131
  const listed = await readCampaignsIn(
1905
2132
  context,
1906
- input27.statuses,
1907
- input27.max_campaigns
2133
+ input28.statuses,
2134
+ input28.max_campaigns
1908
2135
  );
1909
2136
  const campaigns = listed.items;
1910
- const reported = campaigns.length > 1 ? await readAllTotals(context, input27) : void 0;
2137
+ const reported = campaigns.length > 1 ? await readAllTotals(context, input28) : void 0;
1911
2138
  const entries = await mapConcurrent(
1912
2139
  campaigns,
1913
2140
  async (campaign) => ({
1914
2141
  campaign,
1915
- counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input27)
2142
+ counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input28)
1916
2143
  })
1917
2144
  );
1918
2145
  return { entries, read: campaignsReadOf(listed) };
@@ -1932,7 +2159,7 @@ var readDaily = async (context, campaign, range) => {
1932
2159
  };
1933
2160
 
1934
2161
  // src/insights/ops/anomalies.ts
1935
- var metricSchema = z9.enum([
2162
+ var metricSchema = z10.enum([
1936
2163
  "sent",
1937
2164
  "contacted",
1938
2165
  "replied",
@@ -1942,13 +2169,13 @@ var metricSchema = z9.enum([
1942
2169
  "clicked",
1943
2170
  "unsubscribed"
1944
2171
  ]);
1945
- var input6 = z9.object({
1946
- baseline_days: z9.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1947
- campaign: z9.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1948
- days: z9.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1949
- metrics: z9.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1950
- min_baseline_points: z9.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1951
- threshold: z9.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
2172
+ var input7 = z10.object({
2173
+ baseline_days: z10.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
2174
+ campaign: z10.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
2175
+ days: z10.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
2176
+ metrics: z10.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
2177
+ min_baseline_points: z10.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2178
+ threshold: z10.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1952
2179
  });
1953
2180
  var reasonFor2 = (metric, daysWithData) => daysWithData === 0 ? `The vendor reports no ${metric} count for these days.` : "Too few earlier days with data to form a baseline.";
1954
2181
  var judge = (metric, point, baseline, threshold) => {
@@ -2023,7 +2250,7 @@ var findAnomalies = (series, options) => {
2023
2250
  };
2024
2251
  var anomalies = defineInsight({
2025
2252
  description: "Days that broke from trend, for one campaign or the whole workspace: each of the last `days` complete days is held to the `baseline_days` before it, and a daily count `threshold` standard deviations or more from that baseline's mean is returned, newest first, with the metric, the value, the baseline mean, the z-score, the direction and how it was judged. When every baseline day has the same count there is no standard deviation: a day with another count is returned with a null z-score and judgedBy flat_baseline. Use it to spot a sending outage, a bounce spike or a reply surge. Days the vendor has no count for are skipped, never read as zero. With no campaign it reads workspace stats, so it then also needs stats.workspace. Costs one stats request.",
2026
- inputSchema: input6,
2253
+ inputSchema: input7,
2027
2254
  key: "anomalies",
2028
2255
  cost: (_input, price) => price.one("stats"),
2029
2256
  name: "anomalies",
@@ -2054,7 +2281,7 @@ var anomalies = defineInsight({
2054
2281
  });
2055
2282
 
2056
2283
  // src/insights/ops/campaign-diagnosis.ts
2057
- import { z as z10 } from "zod";
2284
+ import { z as z11 } from "zod";
2058
2285
 
2059
2286
  // src/insights/ops/diagnosis-checks.ts
2060
2287
  var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
@@ -2257,12 +2484,11 @@ var unknownRates = (facts) => [
2257
2484
  ];
2258
2485
 
2259
2486
  // src/insights/ops/campaign-diagnosis.ts
2260
- var share = (fallback, text) => z10.number().min(0).max(1).default(fallback).describe(text);
2261
- var recentDays = z10.number().int().min(1).max(30);
2262
- var input7 = z10.object({
2487
+ var share = (fallback, text) => z11.number().min(0).max(1).default(fallback).describe(text);
2488
+ var input8 = z11.object({
2263
2489
  ...rangeFields,
2264
- campaign: z10.string().min(3).describe("The campaign's ref"),
2265
- days: recentDays.default(7).describe(
2490
+ campaign: z11.string().min(3).describe("The campaign's ref"),
2491
+ days: z11.number().int().min(1).max(30).default(7).describe(
2266
2492
  "The days, ending yesterday, held against the same number before"
2267
2493
  ),
2268
2494
  daily_limit_share: share(
@@ -2274,15 +2500,14 @@ var input7 = z10.object({
2274
2500
  0.3,
2275
2501
  "A fall in sends, recent days against the days before, over this share is a finding"
2276
2502
  ),
2277
- max_senders: z10.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2503
+ max_senders: z11.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2278
2504
  min_positive_share: share(
2279
2505
  0.2,
2280
2506
  "A share of replies that are positive under this is a finding"
2281
2507
  ),
2282
2508
  min_reply_rate: share(0.01, "A reply rate under this is a finding"),
2283
- min_sent: z10.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2284
- min_weekly_hours: z10.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
2285
- recent_days: renamed("days", recentDays)
2509
+ min_sent: z11.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2510
+ min_weekly_hours: z11.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume")
2286
2511
  });
2287
2512
  var readRecent = async (context, campaign, days) => {
2288
2513
  const recent = lastDays(context.now, days);
@@ -2347,7 +2572,7 @@ var summarize = (findings) => {
2347
2572
  };
2348
2573
  var campaignDiagnosis = defineInsight({
2349
2574
  description: "Why one campaign is underperforming: a list of findings, most serious first, each with a code, a plain-language finding, the numbers behind it and what to look at next. It checks for too little volume to judge, a low reply rate (with its 95% interval), a high bounce rate, few positive replies among replies, sends falling or stopped over the last days, a one or two step sequence, a sender that is not active, open tracking being off, and a schedule or daily limit that holds volume back. Also returns what could not be checked; an empty list means nothing was found, not that all is well. Costs up to 7 requests.",
2350
- inputSchema: input7,
2575
+ inputSchema: input8,
2351
2576
  key: "campaignDiagnosis",
2352
2577
  cost: (values, price) => {
2353
2578
  const { capabilities } = price;
@@ -2396,17 +2621,17 @@ var campaignDiagnosis = defineInsight({
2396
2621
  });
2397
2622
 
2398
2623
  // src/insights/ops/campaign-ranking.ts
2399
- import { z as z11 } from "zod";
2400
- var metricSchema2 = z11.enum([
2624
+ import { z as z12 } from "zod";
2625
+ var metricSchema2 = z12.enum([
2401
2626
  "reply_rate",
2402
2627
  "positive_reply_rate",
2403
2628
  "bounce_rate"
2404
2629
  ]);
2405
- var input8 = z11.object({
2630
+ var input9 = z12.object({
2406
2631
  ...rangeFields,
2407
2632
  ...listFields("one stats request"),
2408
2633
  metric: metricSchema2.default("reply_rate").describe("The rate to rank by. For bounce_rate, lower is better."),
2409
- min_sent: z11.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2634
+ min_sent: z12.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2410
2635
  });
2411
2636
  var measured = (counts, metric, basis) => {
2412
2637
  const rates = ratesOf(counts, baseIn2(basis));
@@ -2415,7 +2640,7 @@ var measured = (counts, metric, basis) => {
2415
2640
  }
2416
2641
  return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
2417
2642
  };
2418
- var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.name.localeCompare(right.name);
2643
+ var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.campaignName.localeCompare(right.campaignName);
2419
2644
  var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2420
2645
  const scored = [];
2421
2646
  const tooFewSends = [];
@@ -2463,7 +2688,7 @@ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2463
2688
  };
2464
2689
  var campaignRanking = defineInsight({
2465
2690
  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).",
2466
- inputSchema: input8,
2691
+ inputSchema: input9,
2467
2692
  key: "campaignRanking",
2468
2693
  cost: campaignTotalsCost,
2469
2694
  scales: "max_campaigns",
@@ -2484,11 +2709,11 @@ var campaignRanking = defineInsight({
2484
2709
  });
2485
2710
 
2486
2711
  // src/insights/ops/channel-mix.ts
2487
- import { z as z12 } from "zod";
2488
- var input9 = z12.object({
2712
+ import { z as z13 } from "zod";
2713
+ var input10 = z13.object({
2489
2714
  ...rangeFields,
2490
2715
  ...listFields("one stats request"),
2491
- alpha: z12.number().gt(0).lt(1).default(0.05).describe(
2716
+ alpha: z13.number().gt(0).lt(1).default(0.05).describe(
2492
2717
  "The p-value under which a difference counts as more than chance"
2493
2718
  )
2494
2719
  });
@@ -2570,7 +2795,7 @@ var compare = (groups, alpha) => {
2570
2795
  };
2571
2796
  var channelMix = defineInsight({
2572
2797
  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. With one channel present it returns that channel and says there is nothing to compare. 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).",
2573
- inputSchema: input9,
2798
+ inputSchema: input10,
2574
2799
  key: "channelMix",
2575
2800
  cost: campaignTotalsCost,
2576
2801
  scales: "max_campaigns",
@@ -2608,15 +2833,15 @@ var channelMix = defineInsight({
2608
2833
  });
2609
2834
 
2610
2835
  // src/insights/ops/client-report.ts
2611
- import { z as z15 } from "zod";
2836
+ import { z as z16 } from "zod";
2612
2837
 
2613
2838
  // src/insights/ops/period-comparison.ts
2614
- import { z as z13 } from "zod";
2615
- var input10 = z13.object({
2839
+ import { z as z14 } from "zod";
2840
+ var input11 = z14.object({
2616
2841
  ...listFields("two stats requests"),
2617
- alpha: z13.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2618
- days: z13.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2619
- min_sent: z13.number().int().min(0).default(50).describe(
2842
+ alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2843
+ days: z14.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2844
+ min_sent: z14.number().int().min(0).default(50).describe(
2620
2845
  "A campaign under this many sends in either period is listed apart"
2621
2846
  )
2622
2847
  });
@@ -2745,7 +2970,7 @@ var workspaceOf = async (context, periods, alpha) => {
2745
2970
  };
2746
2971
  var periodComparison = defineInsight({
2747
2972
  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.",
2748
- inputSchema: input10,
2973
+ inputSchema: input11,
2749
2974
  key: "periodComparison",
2750
2975
  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")),
2751
2976
  scales: "max_campaigns",
@@ -2777,7 +3002,7 @@ var periodComparison = defineInsight({
2777
3002
  (left, right) => descending(
2778
3003
  left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
2779
3004
  right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
2780
- ) || left.name.localeCompare(right.name)
3005
+ ) || left.campaignName.localeCompare(right.campaignName)
2781
3006
  ),
2782
3007
  current: periods.current,
2783
3008
  days: options.days,
@@ -2795,11 +3020,11 @@ var periodComparison = defineInsight({
2795
3020
  });
2796
3021
 
2797
3022
  // src/insights/ops/pipeline-forecast.ts
2798
- import { z as z14 } from "zod";
2799
- var input11 = z14.object({
2800
- campaign: z14.string().min(3).describe("The campaign's ref"),
2801
- days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2802
- max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3023
+ import { z as z15 } from "zod";
3024
+ var input12 = z15.object({
3025
+ campaign: z15.string().min(3).describe("The campaign's ref"),
3026
+ days: z15.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3027
+ max_leads: z15.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2803
3028
  });
2804
3029
  var countStatuses = (leads) => {
2805
3030
  const counts = {
@@ -2907,7 +3132,7 @@ var forecastCampaign = async (context, campaign, options) => {
2907
3132
  };
2908
3133
  var pipelineForecast = defineInsight({
2909
3134
  description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, the days of sending left at the recent daily contact rate, 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.",
2910
- inputSchema: input11,
3135
+ inputSchema: input12,
2911
3136
  key: "pipelineForecast",
2912
3137
  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")),
2913
3138
  scales: "max_leads",
@@ -2928,24 +3153,22 @@ var pipelineForecast = defineInsight({
2928
3153
  });
2929
3154
 
2930
3155
  // src/insights/ops/client-report.ts
2931
- var limit2 = z15.number().int().min(1).max(20);
2932
- var input12 = z15.object({
3156
+ var input13 = z16.object({
2933
3157
  ...listFields(
2934
3158
  "two stats requests, and three more plus its leads when active"
2935
3159
  ),
2936
- alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2937
- anomaly_threshold: z15.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2938
- baseline_days: z15.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2939
- days: z15.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2940
- limit: limit2.default(3).describe("How many best and worst campaigns to show"),
2941
- max_bounce_rate: z15.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2942
- max_leads_per_campaign: z15.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2943
- min_baseline_points: z15.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2944
- min_sent: z15.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2945
- runway_days: z15.number().min(0).default(7).describe(
3160
+ alpha: z16.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3161
+ anomaly_threshold: z16.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
3162
+ baseline_days: z16.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
3163
+ days: z16.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
3164
+ limit: z16.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show"),
3165
+ max_bounce_rate: z16.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
3166
+ max_leads_per_campaign: z16.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
3167
+ min_baseline_points: z16.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
3168
+ min_sent: z16.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
3169
+ runway_days: z16.number().min(0).default(7).describe(
2946
3170
  "A campaign with this many days of leads left or fewer is flagged"
2947
- ),
2948
- top: renamed("limit", limit2)
3171
+ )
2949
3172
  });
2950
3173
  var sendingLeft = (daysLeft) => {
2951
3174
  if (daysLeft !== null && daysLeft < 0.05) {
@@ -3065,7 +3288,7 @@ var actionsOf = (report) => {
3065
3288
  };
3066
3289
  var clientReport = defineInsight({
3067
3290
  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 two more plus its pages of leads.",
3068
- inputSchema: input12,
3291
+ inputSchema: input13,
3069
3292
  key: "clientReport",
3070
3293
  cost: (values, price) => {
3071
3294
  const { capabilities } = price;
@@ -3126,11 +3349,11 @@ var clientReport = defineInsight({
3126
3349
  });
3127
3350
 
3128
3351
  // src/insights/ops/tag-rollup.ts
3129
- import { z as z16 } from "zod";
3130
- var input13 = z16.object({
3352
+ import { z as z17 } from "zod";
3353
+ var input14 = z17.object({
3131
3354
  ...rangeFields,
3132
3355
  ...listFields("one stats request"),
3133
- min_sent: z16.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
3356
+ min_sent: z17.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
3134
3357
  });
3135
3358
  var groupOf2 = (tag, entries) => {
3136
3359
  const counts = entries.map((entry) => entry.counts);
@@ -3148,7 +3371,7 @@ var groupOf2 = (tag, entries) => {
3148
3371
  var named = (group) => group.tag ?? "";
3149
3372
  var tagRollup = defineInsight({
3150
3373
  description: "Results by campaign tag (for example one tag per client, offer or audience): for each tag the campaigns, messages sent, leads contacted, replies, positive replies and bounces, with reply, positive reply and bounce rates and their 95% intervals, sorted by the low end of the reply rate interval. A campaign with two tags counts in both; campaigns with none are grouped under a null tag. Tags under min_sent sends are listed apart. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a tag whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
3151
- inputSchema: input13,
3374
+ inputSchema: input14,
3152
3375
  key: "tagRollup",
3153
3376
  // A tool whose campaigns carry no tags would put every campaign under one
3154
3377
  // null tag, which reads as an answer. On a combined instance one tool with
@@ -3208,97 +3431,7 @@ var OPS_INSIGHTS = [
3208
3431
 
3209
3432
  // src/insights/people/account-summary.ts
3210
3433
  import { z as z18 } from "zod";
3211
-
3212
- // src/insights/people/read.ts
3213
- import { z as z17 } from "zod";
3214
- var readCappedFlag = (context, open, max, what, input27) => readCapped(context, open, { input: input27, max, what });
3215
- var readByRef = async (context, refs, read, what, effect) => {
3216
- if (refs.length === 0) {
3217
- return /* @__PURE__ */ new Map();
3218
- }
3219
- const found = await read(refs);
3220
- if (found.errors.length > 0) {
3221
- context.note(
3222
- `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
3223
- );
3224
- }
3225
- const [costliest] = found.results.toSorted(
3226
- (left, right) => right.value.meta.requests - left.value.meta.requests
3227
- );
3228
- if (costliest !== void 0) {
3229
- context.one(costliest.value);
3230
- }
3231
- return new Map(found.results.map(({ id, value }) => [id, value]));
3232
- };
3233
- var statusesField = statusesInput(["active"]);
3234
- var campaignsIn = async (context, statuses, max) => {
3235
- const { items } = await readCampaignsIn(context, statuses, max);
3236
- return items;
3237
- };
3238
- var leadsOf = async (context, campaign, max, input27) => {
3239
- const { items } = await readCappedFlag(
3240
- context,
3241
- (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
3242
- max,
3243
- "leads of a campaign",
3244
- input27
3245
- );
3246
- return items;
3247
- };
3248
- var nameOf = (lead) => {
3249
- const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
3250
- return name === "" ? null : name;
3251
- };
3252
- var domainOf = (email) => {
3253
- const domain = email?.split("@").at(-1) ?? "";
3254
- return email === null || !email.includes("@") || domain === "" ? null : domain;
3255
- };
3256
- var DEFAULT_POSITIVE_LABELS = [
3257
- "Interested",
3258
- "Meeting Booked",
3259
- "Meeting Completed"
3260
- ];
3261
- var positiveLabelsField = z17.array(z17.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
3262
- "Vendor interest labels that count as interested, matched without regard to case"
3263
- );
3264
- var isPositive = (label, labels) => label === null ? null : labels.some(
3265
- (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
3266
- );
3267
- var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
3268
- var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
3269
- var AUTOMATIC = /* @__PURE__ */ new Set([
3270
- "bounce",
3271
- "ooo"
3272
- ]);
3273
- var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
3274
- lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
3275
- var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
3276
- var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
3277
- var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
3278
- var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
3279
- var COUNTS = "no per-lead open, click or reply counts";
3280
- var noteEngagement = (context, leads, effect) => {
3281
- const { outbound } = context;
3282
- if (outbound.capabilities["leads.engagement"]) {
3283
- return;
3284
- }
3285
- if (leads.every((lead) => lead.provider === outbound.provider)) {
3286
- context.note(`This tool reports ${COUNTS}, so ${effect}.`);
3287
- return;
3288
- }
3289
- const reporting = new Set(
3290
- leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
3291
- );
3292
- const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
3293
- if (lacking.length > 0) {
3294
- context.note(
3295
- `${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.`
3296
- );
3297
- }
3298
- };
3299
-
3300
- // src/insights/people/account-summary.ts
3301
- var input14 = z18.object({
3434
+ var input15 = z18.object({
3302
3435
  allow_free_domains: z18.boolean().default(false).describe(
3303
3436
  "Set to true to accept an email provider domain such as gmail.com, which is not one company"
3304
3437
  ),
@@ -3446,7 +3579,7 @@ var lastReplyOf = (people) => {
3446
3579
  };
3447
3580
  var accountSummary = defineInsight({
3448
3581
  description: "Everyone at one company across campaigns and tools, from the company's domain or any email address at it: each person with their name, title, campaigns, status, interest label and open, click and reply counts, plus totals and who replied most recently. People are matched by exact email domain, so a lead with only a LinkedIn profile is not found, and an email provider domain such as gmail.com is refused unless allow_free_domains is true. A record the vendor labels out-of-office or bounced is marked autoReplied and its replies do not count as the person replying. Costs one request per page of leads read (max_leads sets the ceiling); totals.moreLeadsExist is true when that ceiling left leads unread. A count the vendor does not report is null.",
3449
- inputSchema: input14,
3582
+ inputSchema: input15,
3450
3583
  key: "accountSummary",
3451
3584
  // Every address is masked, so no lead's domain can be read. A hash keeps
3452
3585
  // exact matching but not the domain.
@@ -3507,7 +3640,7 @@ var HOUR = 36e5;
3507
3640
  var DAY = 24 * HOUR;
3508
3641
  var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
3509
3642
  var DEFAULT_DAYS = 14;
3510
- var input15 = z19.object({
3643
+ var input16 = z19.object({
3511
3644
  categories: z19.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
3512
3645
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
3513
3646
  ),
@@ -3654,7 +3787,7 @@ var readReplies = (context, since, max) => {
3654
3787
  };
3655
3788
  var droppedReplies = defineInsight({
3656
3789
  description: "Replies from prospects that nobody answered. Reads the replies since a date (14 days before now by default), keeps the categories that need an answer, and for each conversation reads its thread, or the lead's timeline when there is no thread, and reports it as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. 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 is counted in totals.unchecked, never reported as dropped. Costs one request per page of replies, one per conversation checked, and one per lead and per campaign among the dropped replies to name them, so at most about three times max_replies requests. totals.moreRepliesExist is true when max_replies left replies unread.",
3657
- inputSchema: input15,
3790
+ inputSchema: input16,
3658
3791
  key: "droppedReplies",
3659
3792
  cost: (values, price) => price.list("replies.list", values.max_replies) + price.upTo(values.max_replies) * (price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.one("leads.get")) + price.one("campaigns.get")),
3660
3793
  scales: "max_replies",
@@ -3742,7 +3875,7 @@ var NOT_ENGAGED = /* @__PURE__ */ new Set([
3742
3875
  "unsubscribe"
3743
3876
  ]);
3744
3877
  var weight = (value, what) => z20.number().min(0).default(value).describe(what);
3745
- var input16 = z20.object({
3878
+ var input17 = z20.object({
3746
3879
  campaign: z20.string().min(1).nullable().default(null).describe(
3747
3880
  "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3748
3881
  ),
@@ -3899,7 +4032,7 @@ var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1
3899
4032
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3900
4033
  var hotLeads = defineInsight({
3901
4034
  description: "Who to call first: leads ranked by a score built from what the vendor reports, namely a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign (an unknown one is refused with NotFound), or none to rank every lead the tool lists. A lead the vendor labels out-of-office or bounced (its interest category, or a label reading out of office) earns no reply or recency points, since a vendor's reply count may include automatic replies; a lead it labels negative (the negative or unsubscribe category, or a label reading not interested, wrong person, unsubscribed or do not contact) earns no points at all, from clicks and opens either, and is listed after every lead with a score above 0 while limit leaves room; its reason names the label. Costs one request per page of leads read (max_leads sets the ceiling). When max_leads stops the listing with more leads left, totals.moreLeadsExist is true and it also reads up to 100 replies from the last recency_days days and one request per replied lead the listing missed, at most limit of them, so engaged leads past the cap are still ranked. A part that is null means the vendor does not report that signal.",
3902
- inputSchema: input16,
4035
+ inputSchema: input17,
3903
4036
  key: "hotLeads",
3904
4037
  cost: (values, price) => price.list("leads.list", values.max_leads) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (price.capabilities["replies.list"] === false || price.capabilities["leads.get"] === false ? 0 : price.upTo(1) * (price.list("replies.list", 100) + price.upTo(values.limit) * price.one("leads.get"))),
3905
4038
  scales: "max_leads",
@@ -4114,7 +4247,7 @@ var findPerson = async (context, identifier, maxRecords) => {
4114
4247
  };
4115
4248
 
4116
4249
  // src/insights/people/lead-collisions.ts
4117
- var input17 = z21.object({
4250
+ var input18 = z21.object({
4118
4251
  max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
4119
4252
  "The most campaigns to read. Each costs one request per page of its leads."
4120
4253
  ),
@@ -4174,7 +4307,7 @@ var toCollision = (group) => {
4174
4307
  var worstFirst = (left, right) => right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
4175
4308
  var leadCollisions = defineInsight({
4176
4309
  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 campaigns first. 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.",
4177
- inputSchema: input17,
4310
+ inputSchema: input18,
4178
4311
  key: "leadCollisions",
4179
4312
  // A masked address is the same text for every lead, so every lead would
4180
4313
  // collide with every other. A hashed one still tells people apart.
@@ -4228,7 +4361,7 @@ var leadCollisions = defineInsight({
4228
4361
 
4229
4362
  // src/insights/people/person-summary.ts
4230
4363
  import { z as z22 } from "zod";
4231
- var input18 = z22.object({
4364
+ var input19 = z22.object({
4232
4365
  max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
4233
4366
  person: z22.string().min(3).describe(
4234
4367
  "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
@@ -4333,7 +4466,7 @@ var byChannel2 = (campaigns) => {
4333
4466
  };
4334
4467
  var personSummary = defineInsight({
4335
4468
  description: "Everything about one person across campaigns and channels, from their email address, LinkedIn profile or a lead ref: each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic. Costs one lookup per identifier, one request to read a lead ref, then up to 2 requests per campaign.",
4336
- inputSchema: input18,
4469
+ inputSchema: input19,
4337
4470
  key: "personSummary",
4338
4471
  cost: (values, price) => (isLeadRef(values.person) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
4339
4472
  scales: "max_campaigns",
@@ -4379,35 +4512,14 @@ var personSummary = defineInsight({
4379
4512
 
4380
4513
  // src/insights/people/personalization-gaps.ts
4381
4514
  import { z as z23 } from "zod";
4382
- var input19 = z23.object({
4515
+ var input20 = z23.object({
4383
4516
  campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
4384
4517
  limit: z23.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
4385
4518
  max_leads: z23.number().int().min(1).max(2e4).default(500).describe(
4386
4519
  "The most leads to check. A vendor request returns about 50 to 100 leads."
4387
4520
  )
4388
4521
  });
4389
- var PATTERNS = [
4390
- /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
4391
- /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
4392
- /%(?<name>[A-Za-z_][\w-]*)%/gu
4393
- ];
4394
- var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
4395
- var BUILTINS = /* @__PURE__ */ new Map([
4396
- ["company", (lead) => lead.company],
4397
- ["companyname", (lead) => lead.company],
4398
- ["email", (lead) => lead.email],
4399
- ["firstname", (lead) => lead.firstName],
4400
- ["jobtitle", (lead) => lead.title],
4401
- ["lastname", (lead) => lead.lastName],
4402
- ["title", (lead) => lead.title]
4403
- ]);
4404
4522
  var FIELDS = ["subject", "body"];
4405
- var variablesIn = (text) => PATTERNS.flatMap(
4406
- (pattern) => [...text.matchAll(pattern)].map((match) => ({
4407
- fallback: match.groups?.fallback !== void 0,
4408
- name: match.groups?.name ?? ""
4409
- }))
4410
- );
4411
4523
  var findVariables = (sequence2) => {
4412
4524
  const found = /* @__PURE__ */ new Map();
4413
4525
  const texts = sequence2.steps.flatMap(
@@ -4423,23 +4535,14 @@ var findVariables = (sequence2) => {
4423
4535
  for (const { field, step, text, variant } of texts) {
4424
4536
  for (const { fallback, name } of variablesIn(text)) {
4425
4537
  const entry = found.get(keyOf(name)) ?? { name, uses: [] };
4426
- entry.uses.push({ fallback, field, step, variant });
4538
+ entry.uses.push({ fallback: fallback !== null, field, step, variant });
4427
4539
  found.set(keyOf(name), entry);
4428
4540
  }
4429
4541
  }
4430
4542
  return found;
4431
4543
  };
4432
- var filled = (value) => value !== null && value.trim() !== "";
4433
- var valuesOf = (lead) => /* @__PURE__ */ new Set([
4434
- ...[...BUILTINS].flatMap(
4435
- ([key, read]) => filled(read(lead)) ? [key] : []
4436
- ),
4437
- ...Object.entries(lead.custom).flatMap(
4438
- ([key, value]) => filled(value) ? [keyOf(key)] : []
4439
- )
4440
- ]);
4441
4544
  var sourceOf = (key, customKeys) => {
4442
- if (BUILTINS.has(key)) {
4545
+ if (isBuiltin(key)) {
4443
4546
  return "builtin";
4444
4547
  }
4445
4548
  return customKeys.has(key) ? "custom" : "unknown";
@@ -4480,7 +4583,7 @@ var missingOf = (lead, values, gaps) => {
4480
4583
  };
4481
4584
  var personalizationGaps = defineInsight({
4482
4585
  description: "Leads in one campaign who will get broken copy because a merge variable has no value for them. Reads the campaign's sequence, finds every {{variable}}, {variable} and %variable% in subjects and bodies, and checks each lead for a value: first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens. Returns the variables with the steps that use them, how many leads each one affects, and the leads missing at least one. A variable with a fallback such as {{firstName|there}} is not a gap. A variable no lead has, such as a sender signature the tool fills in, is listed as unknown, not counted against leads. Costs one request for the sequence plus one per page of leads.",
4483
- inputSchema: input19,
4586
+ inputSchema: input20,
4484
4587
  key: "personalizationGaps",
4485
4588
  cost: (values, price) => price.one("sequence.get") + price.upTo(1) * price.list("leads.list", values.max_leads),
4486
4589
  scales: "max_leads",
@@ -4505,13 +4608,13 @@ var personalizationGaps = defineInsight({
4505
4608
  leads.flatMap((lead) => Object.keys(lead.custom).map(keyOf))
4506
4609
  );
4507
4610
  const keyed = [...found].map(
4508
- ([key, entry]) => toVariable(key, entry, leads.map(valuesOf), customKeys)
4611
+ ([key, entry]) => toVariable(key, entry, leads.map(keysWithValue), customKeys)
4509
4612
  );
4510
4613
  const variables = keyed.map((each) => each.variable).toSorted(
4511
4614
  (left, right) => (right.leadsAffected ?? -1) - (left.leadsAffected ?? -1) || left.name.localeCompare(right.name)
4512
4615
  );
4513
4616
  const gaps = keyed.filter((each) => each.variable.gap);
4514
- const affected = leads.flatMap((lead) => missingOf(lead, valuesOf(lead), gaps)).toSorted(
4617
+ const affected = leads.flatMap((lead) => missingOf(lead, keysWithValue(lead), gaps)).toSorted(
4515
4618
  (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
4516
4619
  );
4517
4620
  const answer = {
@@ -4535,7 +4638,7 @@ var personalizationGaps = defineInsight({
4535
4638
 
4536
4639
  // src/insights/people/suppression-check.ts
4537
4640
  import { z as z24 } from "zod";
4538
- var input20 = z24.object({
4641
+ var input21 = z24.object({
4539
4642
  max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
4540
4643
  "The most block list entries to read. A vendor request returns about 50 to 100."
4541
4644
  ),
@@ -4611,7 +4714,7 @@ var maskNote = (outbound) => {
4611
4714
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
4612
4715
  var suppressionCheck = defineInsight({
4613
4716
  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. 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.",
4614
- inputSchema: input20,
4717
+ inputSchema: input21,
4615
4718
  key: "suppressionCheck",
4616
4719
  // A masked address is the same text for every lead, so nothing can match.
4617
4720
  // A hashed one still matches the same address on the list.
@@ -4705,20 +4808,20 @@ var PEOPLE_INSIGHTS = [
4705
4808
  import { z as z25 } from "zod";
4706
4809
 
4707
4810
  // src/insights/senders/read.ts
4708
- var readCapped2 = async (context, walk, max, what, input27) => {
4709
- const { items } = await readCapped(context, walk, { input: input27, max, what });
4811
+ var readCapped2 = async (context, walk, max, what, input28) => {
4812
+ const { items } = await readCapped(context, walk, { input: input28, max, what });
4710
4813
  return items;
4711
4814
  };
4712
4815
  var readCampaigns = async (context, statuses, max) => {
4713
4816
  const { items } = await readCampaignsIn(context, statuses, max);
4714
4817
  return items;
4715
4818
  };
4716
- var readCampaignSenders = (context, campaign, max, input27) => readCapped2(
4819
+ var readCampaignSenders = (context, campaign, max, input28) => readCapped2(
4717
4820
  context,
4718
4821
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
4719
4822
  max,
4720
4823
  `senders of campaign ${campaign.name}`,
4721
- input27
4824
+ input28
4722
4825
  );
4723
4826
  var readSenders = (context, max) => readCapped(context, (cap) => context.outbound.senders.listAll({ max: cap }), {
4724
4827
  input: "max_senders",
@@ -4760,25 +4863,22 @@ var countEach = (keys, count2) => (
4760
4863
  );
4761
4864
 
4762
4865
  // src/insights/senders/bounce-watch.ts
4763
- var maxBounceRate = z25.number().min(0).max(1);
4764
- var input21 = z25.object({
4866
+ var input22 = z25.object({
4765
4867
  ...rangeFields,
4766
4868
  include_senders: z25.boolean().default(true).describe(
4767
4869
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
4768
4870
  ),
4769
- max_bounce_rate: maxBounceRate.default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
4871
+ max_bounce_rate: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
4770
4872
  max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
4771
4873
  max_senders_per_campaign: z25.number().int().min(1).max(200).default(10).describe("The most senders to check for one campaign over the threshold"),
4772
4874
  min_sent: z25.number().int().min(0).default(100).describe(
4773
4875
  "A campaign or sender with fewer sends than this is too small to judge"
4774
4876
  ),
4775
- threshold: renamed("max_bounce_rate", maxBounceRate),
4776
4877
  statuses: statusesInput(["active"])
4777
4878
  });
4778
4879
  var countsOf2 = (bounced, sent) => ({
4779
4880
  ...measure2(bounced, sent),
4780
4881
  bounced,
4781
- interval: wilson(bounced, sent),
4782
4882
  sent
4783
4883
  });
4784
4884
  var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
@@ -4843,7 +4943,7 @@ var canCheckSenders = (context, wanted) => {
4843
4943
  };
4844
4944
  var bounceWatch = defineInsight({
4845
4945
  description: "Where bounces are too high: the campaigns whose bounce rate (bounced divided by sent) is over a threshold, worst first, each with bounced, sent, the rate and its Wilson interval, and the senders of each such campaign that are themselves over the threshold. Campaigns with too few sends to judge and campaigns with no reported bounce count are listed apart, never as clean. Use it daily, or when a domain's reputation is in doubt. Costs one listing of campaigns and 1 request per campaign, plus 1 listing and up to 1 request per sender for each campaign over the threshold. A null rate means nothing was sent.",
4846
- inputSchema: input21,
4946
+ inputSchema: input22,
4847
4947
  key: "bounceWatch",
4848
4948
  cost: (values, price) => {
4849
4949
  const campaigns = price.campaigns(values.max_campaigns);
@@ -4879,7 +4979,6 @@ var bounceWatch = defineInsight({
4879
4979
  const entry = {
4880
4980
  campaign: campaign.ref,
4881
4981
  campaignName: campaign.name,
4882
- name: campaign.name,
4883
4982
  status: campaign.status
4884
4983
  };
4885
4984
  if (counts === null) {
@@ -4933,7 +5032,6 @@ var bounceWatch = defineInsight({
4933
5032
  minSent,
4934
5033
  over: over.toSorted(byRate2),
4935
5034
  sendersRead: withSenders ? seen.read.size : null,
4936
- threshold,
4937
5035
  tooFewSends: tooFewSends.toSorted(byRate2),
4938
5036
  totals: {
4939
5037
  bounced,
@@ -4953,13 +5051,11 @@ var bounceWatch = defineInsight({
4953
5051
 
4954
5052
  // src/insights/senders/domain-health.ts
4955
5053
  import { z as z26 } from "zod";
4956
- var maxSpamRate = z26.number().min(0).max(1);
4957
- var input22 = z26.object({
5054
+ var input23 = z26.object({
4958
5055
  max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
4959
- max_spam_rate: maxSpamRate.default(0.1).describe(
5056
+ max_spam_rate: z26.number().min(0).max(1).default(0.1).describe(
4960
5057
  "A domain whose warmup emails land in spam more often than this share is high risk"
4961
- ),
4962
- spam_rate_threshold: renamed("max_spam_rate", maxSpamRate)
5058
+ )
4963
5059
  });
4964
5060
  var RISK_ORDER = ["high", "medium", "low", "unknown"];
4965
5061
  var pooledWarmup = (checked) => {
@@ -4970,11 +5066,9 @@ var pooledWarmup = (checked) => {
4970
5066
  if (reported.length === 0) {
4971
5067
  return {
4972
5068
  ...measure2(null, null),
4973
- interval: null,
4974
5069
  mailboxes: 0,
4975
5070
  sent: null,
4976
- spam: null,
4977
- spamRate: null
5071
+ spam: null
4978
5072
  };
4979
5073
  }
4980
5074
  const sent = reported.reduce((sum, each) => sum + each.sent, 0);
@@ -4982,11 +5076,9 @@ var pooledWarmup = (checked) => {
4982
5076
  const measured2 = measure2(spam, sent);
4983
5077
  return {
4984
5078
  ...measured2,
4985
- interval: wilson(spam, sent),
4986
5079
  mailboxes: reported.length,
4987
5080
  sent,
4988
- spam,
4989
- spamRate: measured2.rate
5081
+ spam
4990
5082
  };
4991
5083
  };
4992
5084
  var missingChecks = (checked, warmup) => [
@@ -5057,7 +5149,7 @@ var seatRank = (seat) => {
5057
5149
  };
5058
5150
  var domainHealth = defineInsight({
5059
5151
  description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Costs one listing of senders plus 1 request per sender. A null count or rate means the vendor does not report it; a domain with no DNS record reported has the risk `unknown`, not `low`.",
5060
- inputSchema: input22,
5152
+ inputSchema: input23,
5061
5153
  key: "domainHealth",
5062
5154
  cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
5063
5155
  scales: "max_senders",
@@ -5219,7 +5311,7 @@ var readSends = async (context, campaigns, days, senders2, split) => {
5219
5311
  };
5220
5312
 
5221
5313
  // src/insights/senders/sender-capacity.ts
5222
- var input23 = z27.object({
5314
+ var input24 = z27.object({
5223
5315
  days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
5224
5316
  max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
5225
5317
  "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
@@ -5285,7 +5377,7 @@ var shortfallOf = (read) => {
5285
5377
  };
5286
5378
  var askOf = (reads) => {
5287
5379
  const limits = reads.map((read) => read.dailyLimit);
5288
- const withLimit = limits.filter((limit3) => limit3 !== null).length;
5380
+ const withLimit = limits.filter((limit2) => limit2 !== null).length;
5289
5381
  return {
5290
5382
  campaigns: reads.length,
5291
5383
  daily: total(limits),
@@ -5315,7 +5407,7 @@ var findingOf = (capacity, ask, sends) => {
5315
5407
  };
5316
5408
  var senderCapacity = defineInsight({
5317
5409
  description: "Whether the senders can send what the campaigns ask: total daily capacity (the daily limits of active senders added up), the total daily ask of active campaigns, the average messages sent per day over the last days, utilization, and the campaigns whose own senders cannot cover their daily limit. Use it before adding campaigns or when sends fall short. Costs one listing of senders and of active campaigns, then up to 2 requests per campaign and 1 for daily stats, plus 1 per inactive or unlimited sender with split_uncounted. Utilization counts only the sends of the senders in capacity. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
5318
- inputSchema: input23,
5410
+ inputSchema: input24,
5319
5411
  key: "senderCapacity",
5320
5412
  cost: (values, price) => {
5321
5413
  const { capabilities } = price;
@@ -5378,7 +5470,7 @@ var senderCapacity = defineInsight({
5378
5470
 
5379
5471
  // src/insights/senders/sender-load.ts
5380
5472
  import { z as z28 } from "zod";
5381
- var input24 = z28.object({
5473
+ var input25 = z28.object({
5382
5474
  max_campaigns: z28.number().int().min(1).max(200).default(25).describe("The most campaigns to read. Each costs 1 request."),
5383
5475
  max_campaigns_per_sender: z28.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
5384
5476
  max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
@@ -5410,13 +5502,12 @@ var riskOf = (campaign, senders2) => {
5410
5502
  finding: inactive.length > 0 ? `${campaign.name} has ${count2}, ${inactive.length} of them not active.` : `${campaign.name} has ${count2}.`,
5411
5503
  inactive: inactive.map(loaded),
5412
5504
  issues,
5413
- name: campaign.name,
5414
5505
  senders: senders2.length
5415
5506
  };
5416
5507
  };
5417
5508
  var senderLoad = defineInsight({
5418
5509
  description: "Senders that are overused or unused: the senders attached to more campaigns than allowed, the active senders attached to no campaign, and the campaigns that run on a single sender, on none, or on a sender that is not active. Use it when sends are uneven or before adding a campaign. Costs one listing of senders and of campaigns, then 1 request per campaign. Only campaigns in the given statuses are counted, so a sender used only by a paused campaign shows as unused unless paused is included.",
5419
- inputSchema: input24,
5510
+ inputSchema: input25,
5420
5511
  key: "senderLoad",
5421
5512
  cost: (values, price) => price.list("senders.list", values.max_senders) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("senders.list", values.max_senders),
5422
5513
  scales: "max_campaigns",
@@ -5492,7 +5583,7 @@ var senderLoad = defineInsight({
5492
5583
 
5493
5584
  // src/insights/senders/settings-audit.ts
5494
5585
  import { z as z29 } from "zod";
5495
- var input25 = z29.object({
5586
+ var input26 = z29.object({
5496
5587
  max_campaigns: z29.number().int().min(1).max(200).default(25).describe(
5497
5588
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
5498
5589
  ),
@@ -5642,7 +5733,7 @@ var countChecks = (campaigns) => countEach(
5642
5733
  );
5643
5734
  var settingsAudit = defineInsight({
5644
5735
  description: "Risky campaign settings, per campaign and by severity: no sending window, a window that includes the weekend or is too long or too short, no timezone, open or click tracking on, a reply that does not stop the sequence, no daily limit, sends too close together, an end date in the past on an active campaign, and a daily limit too high for the number of senders. Returns the findings per campaign, worst first, and a count per check. Use it before launching a campaign or when deliverability drops. Costs one listing of campaigns, then 1 request per campaign, or 2 when its senders can be listed. A setting the vendor reports nothing for is skipped, except a missing window, timezone or daily limit, which the vendor cannot tell apart from one that is not set.",
5645
- inputSchema: input25,
5736
+ inputSchema: input26,
5646
5737
  key: "settingsAudit",
5647
5738
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("campaigns.settings") + (price.capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders_per_campaign))),
5648
5739
  scales: "max_campaigns",
@@ -5709,7 +5800,7 @@ var settingsAudit = defineInsight({
5709
5800
 
5710
5801
  // src/insights/senders/warmup-readiness.ts
5711
5802
  import { z as z30 } from "zod";
5712
- var input26 = z30.object({
5803
+ var input27 = z30.object({
5713
5804
  check_health: z30.boolean().default(false).describe(
5714
5805
  "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
5715
5806
  ),
@@ -5784,7 +5875,7 @@ var countReasons = (judged) => countEach(
5784
5875
  );
5785
5876
  var warmupReadiness = defineInsight({
5786
5877
  description: "Which senders are not ready to send, each with its reasons: warmup off, warmup score under the bar or not reported, status not active, no daily limit and, with check_health, failing DNS records or too many warmup emails in spam. Returns counts by reason and how many are ready. A LinkedIn seat is judged on its status only. Use it before attaching mailboxes to a campaign or raising their limits. Costs one listing of senders, plus 1 request per mailbox with check_health. A null score means the vendor does not report one, which counts as not ready, not as 0.",
5787
- inputSchema: input26,
5878
+ inputSchema: input27,
5788
5879
  key: "warmupReadiness",
5789
5880
  cost: (values, price) => price.list("senders.list", values.max_senders) + (values.check_health && price.capabilities["senders.health"] !== false ? price.upTo(values.max_senders) * price.one("senders.health") : 0),
5790
5881
  scales: "max_senders",
@@ -5863,10 +5954,10 @@ var entryNamed = (outbound, name) => {
5863
5954
  }
5864
5955
  return entry;
5865
5956
  };
5866
- var runInsightByName = async (outbound, name, input27 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input27, options);
5867
- var insightCost = (outbound, name, input27 = {}) => {
5957
+ var runInsightByName = async (outbound, name, input28 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input28, options);
5958
+ var insightCost = (outbound, name, input28 = {}) => {
5868
5959
  const entry = entryNamed(outbound, name);
5869
- const parsed = entry.inputSchema.safeParse(input27);
5960
+ const parsed = entry.inputSchema.safeParse(input28);
5870
5961
  if (!parsed.success) {
5871
5962
  throw new OutboundError(
5872
5963
  "Invalid",
@@ -5889,9 +5980,9 @@ var insights = () => ({
5889
5980
  extend: (outbound) => {
5890
5981
  const methods = {};
5891
5982
  for (const entry of ENTRIES) {
5892
- methods[entry.key] = (input27, options) => (
5983
+ methods[entry.key] = (input28, options) => (
5893
5984
  // SAFETY: the answer is the entry's own, typed per key by Insights.
5894
- entry.execute(outbound, input27, options)
5985
+ entry.execute(outbound, input28, options)
5895
5986
  );
5896
5987
  }
5897
5988
  return { insights: methods };
@@ -5914,8 +6005,8 @@ var toTool = (outbound, definition, next, perCall) => ({
5914
6005
  call: async (given, callOptions) => {
5915
6006
  const set = callOptions?.maxRequests ?? perCall;
5916
6007
  try {
5917
- const input27 = jsonInput(given);
5918
- if (input27 === void 0) {
6008
+ const input28 = jsonInput(given);
6009
+ if (input28 === void 0) {
5919
6010
  throw new OutboundError(
5920
6011
  "Invalid",
5921
6012
  `${definition.name}: the input is not JSON`
@@ -5923,7 +6014,7 @@ var toTool = (outbound, definition, next, perCall) => ({
5923
6014
  }
5924
6015
  const result = await definition.execute(
5925
6016
  outbound,
5926
- input27,
6017
+ input28,
5927
6018
  set === void 0 ? {
5928
6019
  capCeiling: INSIGHT_TOOL_CEILING,
5929
6020
  capSetting: "maxRequestsPerToolCall"