outbound-sdk 0.2.0 → 0.4.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 (140) hide show
  1. package/dist/alerts/index.js +50 -19
  2. package/dist/alerts/plugin.d.ts +20 -3
  3. package/dist/audit/index.js +2 -2
  4. package/dist/benchmarks/index.js +5 -5
  5. package/dist/budget/index.d.ts +3 -2
  6. package/dist/budget/index.js +11 -10
  7. package/dist/cards/content.d.ts +6 -1
  8. package/dist/cards/format.d.ts +17 -2
  9. package/dist/cards/index.d.ts +1 -1
  10. package/dist/cards/index.js +297 -132
  11. package/dist/cards/parts.d.ts +9 -2
  12. package/dist/cards/render.d.ts +20 -3
  13. package/dist/chunks/{chunk-U2D34ARZ.js → chunk-2D42TQFU.js} +3 -3
  14. package/dist/chunks/chunk-4PA526S7.js +17 -0
  15. package/dist/chunks/{chunk-6CVZOUHB.js → chunk-5CFO3CXG.js} +24 -0
  16. package/dist/chunks/{chunk-XNFESPZH.js → chunk-5FVKRIEJ.js} +168 -31
  17. package/dist/chunks/{chunk-PMSSUWD7.js → chunk-7LNJJ2RO.js} +217 -58
  18. package/dist/chunks/{chunk-XC6CZP73.js → chunk-7ZDS6SZD.js} +7 -1
  19. package/dist/chunks/{chunk-SBIZDCRY.js → chunk-A6WVOCA4.js} +4 -4
  20. package/dist/chunks/{chunk-VQSCHOBV.js → chunk-BLCJHP5H.js} +11 -4
  21. package/dist/chunks/{chunk-4PSO6JEK.js → chunk-BOWXGMN3.js} +6 -21
  22. package/dist/chunks/{chunk-DJ2IUQEU.js → chunk-C4LS2HNV.js} +3 -3
  23. package/dist/chunks/{chunk-AFU5E5QB.js → chunk-E6DSDCPI.js} +98 -69
  24. package/dist/chunks/{chunk-IPUYZD4O.js → chunk-GFDNRWR3.js} +1 -1
  25. package/dist/chunks/{chunk-PURHK3JU.js → chunk-IZFTTMJP.js} +4 -4
  26. package/dist/chunks/{chunk-E7JHLNLG.js → chunk-J7DDZ4C2.js} +15 -2
  27. package/dist/chunks/{chunk-FKH5N47I.js → chunk-K4USHN4C.js} +1 -1
  28. package/dist/chunks/chunk-LVQUSKEX.js +17 -0
  29. package/dist/chunks/{chunk-YOTW5ESM.js → chunk-PQSTQKRD.js} +2 -2
  30. package/dist/chunks/chunk-PTZO4QXR.js +15 -0
  31. package/dist/chunks/{chunk-LVYG7XZJ.js → chunk-QAKJ76HB.js} +1 -1
  32. package/dist/chunks/chunk-QGRZDTX4.js +26 -0
  33. package/dist/chunks/{chunk-R3Y56YVF.js → chunk-Y5RAJ6PZ.js} +2 -2
  34. package/dist/chunks/{chunk-RCZ7ZZFU.js → chunk-ZFVHM5JI.js} +3 -3
  35. package/dist/chunks/{chunk-UAT3JSJZ.js → chunk-ZOAG2C6V.js} +2 -2
  36. package/dist/cli/bin.js +17 -13
  37. package/dist/cli/commands.d.ts +11 -0
  38. package/dist/cli/index.js +17 -13
  39. package/dist/cli/mcp.d.ts +5 -0
  40. package/dist/cli/version.d.ts +2 -0
  41. package/dist/clients/index.d.ts +1 -1
  42. package/dist/clients/index.js +35 -10
  43. package/dist/clients/plugin.d.ts +9 -2
  44. package/dist/combine/index.js +7 -6
  45. package/dist/exporter/index.d.ts +5 -2
  46. package/dist/exporter/index.js +2 -2
  47. package/dist/failover/index.js +3 -3
  48. package/dist/fixtures/index.js +5 -4
  49. package/dist/heyreach/client.d.ts +2 -0
  50. package/dist/heyreach/index.js +71 -39
  51. package/dist/heyreach/map.d.ts +5 -2
  52. package/dist/identity/index.js +33 -17
  53. package/dist/identity/plugin.d.ts +2 -0
  54. package/dist/index.d.ts +2 -2
  55. package/dist/index.js +13 -10
  56. package/dist/insights/campaign.d.ts +3 -0
  57. package/dist/insights/capped.d.ts +29 -0
  58. package/dist/insights/copy/copy-audit.d.ts +2 -0
  59. package/dist/insights/copy/copy-reuse.d.ts +27 -3
  60. package/dist/insights/copy/index.d.ts +8 -8
  61. package/dist/insights/copy/reply-timing.d.ts +8 -0
  62. package/dist/insights/copy/reuse-base.d.ts +32 -0
  63. package/dist/insights/copy/shared.d.ts +39 -15
  64. package/dist/insights/copy/step-funnel.d.ts +16 -5
  65. package/dist/insights/copy/variant-test.d.ts +19 -8
  66. package/dist/insights/define.d.ts +56 -2
  67. package/dist/insights/fields.d.ts +16 -0
  68. package/dist/insights/index.d.ts +2 -1
  69. package/dist/insights/index.js +1494 -730
  70. package/dist/insights/inputs.generated.d.ts +951 -0
  71. package/dist/insights/ops/campaign-diagnosis.d.ts +3 -1
  72. package/dist/insights/ops/campaign-ranking.d.ts +12 -4
  73. package/dist/insights/ops/channel-mix.d.ts +2 -1
  74. package/dist/insights/ops/client-report.d.ts +18 -5
  75. package/dist/insights/ops/index.d.ts +6 -2
  76. package/dist/insights/ops/period-comparison.d.ts +14 -3
  77. package/dist/insights/ops/pipeline-forecast.d.ts +14 -4
  78. package/dist/insights/ops/shared.d.ts +29 -24
  79. package/dist/insights/ops/tag-rollup.d.ts +2 -1
  80. package/dist/insights/people/account-summary.d.ts +13 -0
  81. package/dist/insights/people/dropped-replies.d.ts +8 -0
  82. package/dist/insights/people/find.d.ts +7 -1
  83. package/dist/insights/people/hot-leads.d.ts +16 -1
  84. package/dist/insights/people/person-summary.d.ts +6 -0
  85. package/dist/insights/people/read.d.ts +26 -10
  86. package/dist/insights/people/suppression-check.d.ts +11 -2
  87. package/dist/insights/plugin.d.ts +7 -5
  88. package/dist/insights/ref.d.ts +6 -0
  89. package/dist/insights/registry.d.ts +28 -16
  90. package/dist/insights/senders/bounce-watch.d.ts +25 -8
  91. package/dist/insights/senders/capacity-sends.d.ts +22 -0
  92. package/dist/insights/senders/domain-health.d.ts +10 -4
  93. package/dist/insights/senders/index.d.ts +14 -6
  94. package/dist/insights/senders/read.d.ts +15 -14
  95. package/dist/insights/senders/sender-capacity.d.ts +5 -13
  96. package/dist/insights/senders/sender-load.d.ts +2 -0
  97. package/dist/insights/stats.d.ts +8 -0
  98. package/dist/insights/tools.d.ts +3 -2
  99. package/dist/instantly/client.d.ts +2 -0
  100. package/dist/instantly/index.js +44 -29
  101. package/dist/instantly/map.d.ts +6 -2
  102. package/dist/internal/engine/request.d.ts +5 -0
  103. package/dist/internal/entities.d.ts +3 -20
  104. package/dist/internal/errors.d.ts +44 -0
  105. package/dist/internal/fields.d.ts +1 -1
  106. package/dist/internal/json.d.ts +9 -2
  107. package/dist/internal/lists.d.ts +24 -0
  108. package/dist/internal/numbers.d.ts +8 -0
  109. package/dist/internal/outbound/collections.d.ts +4 -0
  110. package/dist/internal/outbound/create.d.ts +24 -3
  111. package/dist/internal/outbound/outbound.d.ts +13 -1
  112. package/dist/internal/outbound/validate.d.ts +4 -0
  113. package/dist/internal/outbound/walker.d.ts +3 -2
  114. package/dist/internal/plural.d.ts +12 -0
  115. package/dist/internal/renamed.d.ts +28 -0
  116. package/dist/internal/vocabulary.d.ts +20 -0
  117. package/dist/loader/index.js +5 -5
  118. package/dist/memory/adapter.d.ts +7 -0
  119. package/dist/memory/demo-stats.d.ts +3 -0
  120. package/dist/memory/demo.d.ts +14 -3
  121. package/dist/memory/index.d.ts +1 -0
  122. package/dist/memory/index.js +200 -95
  123. package/dist/providers/index.d.ts +72 -0
  124. package/dist/providers/index.js +3 -1
  125. package/dist/reconcile/index.js +5 -4
  126. package/dist/redact/index.js +10 -4
  127. package/dist/redact/plugin.d.ts +7 -0
  128. package/dist/smartlead/index.js +102 -49
  129. package/dist/smartlead/shared.d.ts +13 -0
  130. package/dist/sync/index.js +2 -2
  131. package/dist/tools/ai-sdk.js +8 -6
  132. package/dist/tools/campaign-tools.d.ts +1 -1
  133. package/dist/tools/claude-agent.js +8 -6
  134. package/dist/tools/index.js +9 -7
  135. package/dist/tools/input-problem.d.ts +8 -0
  136. package/dist/tools/registry.d.ts +7 -2
  137. package/dist/tools/shared.d.ts +7 -0
  138. package/dist/tracing/index.js +2 -2
  139. package/dist/webhooks/index.js +10 -9
  140. package/package.json +1 -1
@@ -1,32 +1,108 @@
1
+ import {
2
+ inputProblem
3
+ } from "../chunks/chunk-LVQUSKEX.js";
4
+ import {
5
+ count,
6
+ percentOf,
7
+ plural
8
+ } from "../chunks/chunk-4PA526S7.js";
1
9
  import {
2
10
  mapConcurrent
3
11
  } from "../chunks/chunk-HZCTYL22.js";
12
+ import {
13
+ noun,
14
+ shownKey
15
+ } from "../chunks/chunk-PTZO4QXR.js";
4
16
  import {
5
17
  sumCounts
6
- } from "../chunks/chunk-YOTW5ESM.js";
18
+ } from "../chunks/chunk-PQSTQKRD.js";
7
19
  import {
8
20
  profileSlug
9
21
  } from "../chunks/chunk-NAWZ73QS.js";
10
22
  import {
11
23
  campaignStatusSchema,
12
24
  replyCategorySchema
13
- } from "../chunks/chunk-4PSO6JEK.js";
14
- import "../chunks/chunk-LVYG7XZJ.js";
25
+ } from "../chunks/chunk-QGRZDTX4.js";
26
+ import {
27
+ makeRef,
28
+ parseRef
29
+ } from "../chunks/chunk-QAKJ76HB.js";
15
30
  import {
16
31
  OutboundError
17
- } from "../chunks/chunk-E7JHLNLG.js";
32
+ } from "../chunks/chunk-J7DDZ4C2.js";
18
33
  import {
34
+ isJsonObject,
35
+ jsonInput,
19
36
  toJson,
20
37
  unknownKey
21
- } from "../chunks/chunk-VQSCHOBV.js";
38
+ } from "../chunks/chunk-BLCJHP5H.js";
22
39
 
23
40
  // src/insights/plugin.ts
24
41
  import { z as z31 } from "zod";
25
42
 
26
43
  // src/insights/copy/copy-audit.ts
44
+ import { z as z2 } from "zod";
45
+
46
+ // src/internal/renamed.ts
27
47
  import { z } from "zod";
48
+ var REMOVED_IN = "0.5.0";
49
+ var renames = z.registry();
50
+ var renamed = (to, base) => {
51
+ const field = base.optional().meta({
52
+ deprecated: true,
53
+ description: `Deprecated: renamed to \`${to}\`. Removed in ${REMOVED_IN}.`
54
+ });
55
+ renames.add(field, { to });
56
+ return field;
57
+ };
58
+ var renamesIn = (fields) => Object.entries(fields).flatMap(([from, schema]) => {
59
+ const link = renames.get(schema);
60
+ return link === void 0 ? [] : [{ from, to: link.to }];
61
+ });
62
+ var liveKeys = (fields) => {
63
+ const old = new Set(renamesIn(fields).map((each) => each.from));
64
+ return Object.keys(fields).filter((key) => !old.has(key));
65
+ };
66
+ var applyRenames = (fields, input27) => {
67
+ if (!isJsonObject(input27)) {
68
+ return { input: input27, notes: [] };
69
+ }
70
+ const moved = new Map(Object.entries(input27));
71
+ const notes = [];
72
+ for (const { from, to } of renamesIn(fields)) {
73
+ const value = moved.get(from);
74
+ moved.delete(from);
75
+ if (value !== void 0) {
76
+ if (moved.get(to) !== void 0) {
77
+ return { conflict: { from, to } };
78
+ }
79
+ moved.set(to, value);
80
+ notes.push(
81
+ `\`${from}\` is deprecated and will be removed in ${REMOVED_IN}; use \`${to}\`.`
82
+ );
83
+ }
84
+ }
85
+ return { input: Object.fromEntries(moved), notes };
86
+ };
28
87
 
29
88
  // src/insights/define.ts
89
+ var isRedacted = (outbound) => "redacted" in outbound;
90
+ var maskingOf = (outbound) => isRedacted(outbound) ? outbound.redacted : null;
91
+ var maskedOutBy = (outbound, entry) => {
92
+ const masking = maskingOf(outbound);
93
+ return masking === null || entry.maskedOut === void 0 ? null : entry.maskedOut(masking);
94
+ };
95
+ var stopNote = (cap) => {
96
+ if (cap === void 0) {
97
+ return "A listing was cut off at its cap; more records exist.";
98
+ }
99
+ return typeof cap === "string" ? `Stopped at ${cap}; more exist.` : capNote(cap);
100
+ };
101
+ var oneOf = (what) => what.replace(
102
+ /\b(?<stem>\w+?)(?<end>ies|s)\b/u,
103
+ (_match, stem, end) => end === "ies" ? `${stem}y` : stem
104
+ );
105
+ var capNote = (cap) => `Stopped at ${plural(cap.max, oneOf(cap.what), cap.what)} (${cap.input ?? "a fixed cap"}); more exist.`;
30
106
  var RANK = {
31
107
  derived: 2,
32
108
  exact: 0,
@@ -59,9 +135,7 @@ var track = (outbound, now) => {
59
135
  const items = await walk.toArray();
60
136
  seen(walk.meta);
61
137
  if (walk.truncated) {
62
- partial(
63
- cap === void 0 ? "A listing was cut off at its cap; more records exist." : `Stopped at ${cap}; more exist.`
64
- );
138
+ partial(stopNote(cap));
65
139
  }
66
140
  return items;
67
141
  },
@@ -89,8 +163,23 @@ var track = (outbound, now) => {
89
163
  };
90
164
  };
91
165
  var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
92
- var prepare = (outbound, spec, input27) => {
93
- const stray = unknownKey(Object.keys(spec.inputSchema.shape), input27);
166
+ var withRenames = (outbound, spec, given) => {
167
+ const renamed2 = applyRenames(spec.inputSchema.shape, given);
168
+ if ("conflict" in renamed2) {
169
+ const { from, to } = renamed2.conflict;
170
+ throw new OutboundError(
171
+ "Invalid",
172
+ `${spec.name}: pass \`${to}\` only; \`${from}\` is its old name`,
173
+ { provider: outbound.provider }
174
+ );
175
+ }
176
+ return renamed2;
177
+ };
178
+ var prepare = (outbound, spec, given) => {
179
+ const fields = spec.inputSchema.shape;
180
+ const renamed2 = withRenames(outbound, spec, given);
181
+ const { input: input27 } = renamed2;
182
+ const stray = unknownKey(liveKeys(fields), input27);
94
183
  if (stray !== void 0) {
95
184
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
96
185
  provider: outbound.provider
@@ -101,7 +190,23 @@ var prepare = (outbound, spec, input27) => {
101
190
  const [issue] = parsed.error.issues;
102
191
  throw new OutboundError(
103
192
  "Invalid",
104
- `${spec.name}: ${issue?.path.join(".") || "input"} ${issue?.message ?? "is invalid"}`,
193
+ `${spec.name}: ${inputProblem(input27, issue)}`,
194
+ { provider: outbound.provider }
195
+ );
196
+ }
197
+ const blocked = maskedOutBy(outbound, spec);
198
+ if (blocked !== null) {
199
+ throw new OutboundError(
200
+ "Unsupported",
201
+ `${spec.name} is not available while the redact plugin masks ${blocked}`,
202
+ { provider: outbound.provider }
203
+ );
204
+ }
205
+ const lacked = spec.lacks?.(outbound) ?? null;
206
+ if (lacked !== null) {
207
+ throw new OutboundError(
208
+ "Unsupported",
209
+ `${spec.name} is not available: the ${outbound.provider} adapter does not report ${lacked}`,
105
210
  { provider: outbound.provider }
106
211
  );
107
212
  }
@@ -114,13 +219,16 @@ var prepare = (outbound, spec, input27) => {
114
219
  { provider: outbound.provider }
115
220
  );
116
221
  }
117
- return parsed.data;
222
+ return { input: parsed.data, notes: renamed2.notes };
118
223
  };
119
224
  var execute = async (outbound, spec, input27, options = {}) => {
120
225
  const checked = prepare(outbound, spec, input27);
121
226
  const now = options.now ?? Date.now();
122
227
  const tracker = track(outbound, now);
123
- const data = await spec.run(tracker.context, checked);
228
+ for (const note of checked.notes) {
229
+ tracker.context.note(note);
230
+ }
231
+ const data = await spec.run(tracker.context, checked.input);
124
232
  return {
125
233
  data,
126
234
  insight: spec.name,
@@ -177,6 +285,8 @@ var TAG = /<[^>]+>/gu;
177
285
  var IMAGE = /<img\b[^>]*>/giu;
178
286
  var VARIABLE = /\{\{[^{}]*\}\}/gu;
179
287
  var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
288
+ var ANCHOR = /<a\b(?<attributes>[^>]*)>[\s\S]*?<\/a\s*>/giu;
289
+ var HREF = /\bhref\s*=\s*["']?(?<target>[^"'\s>]+)/iu;
180
290
  var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
181
291
  var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
182
292
  var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
@@ -187,22 +297,30 @@ var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== ""
187
297
  var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
188
298
  var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
189
299
  check: "subject_too_long",
190
- finding: `The subject is ${subject.length} characters; the limit is ${limits.maxSubjectChars}.`,
300
+ finding: `The subject is ${plural(subject.length, "character")}; the limit is ${limits.maxSubjectChars}.`,
191
301
  text: clip(subject)
192
302
  } : null;
193
303
  var bodyTooLong = (body, limits) => {
194
304
  const words = wordsOf(body);
195
305
  return words.length > limits.maxBodyWords ? {
196
306
  check: "body_too_long",
197
- finding: `The body is ${words.length} words; the limit is ${limits.maxBodyWords}.`,
307
+ finding: `The body is ${plural(words.length, "word")}; the limit is ${limits.maxBodyWords}.`,
198
308
  text: clip(words.slice(0, 12).join(" "))
199
309
  } : null;
200
310
  };
311
+ var linksOf = (body) => {
312
+ const html = body.replaceAll(IMAGE, " ");
313
+ const anchored = [...html.matchAll(ANCHOR)].flatMap((anchor) => {
314
+ const target = HREF.exec(anchor.groups?.attributes ?? "")?.groups?.target;
315
+ return target === void 0 ? [] : [target];
316
+ });
317
+ return [...anchored, ...html.replaceAll(ANCHOR, " ").match(LINK) ?? []];
318
+ };
201
319
  var tooManyLinks = (body, limits) => {
202
- const links = body.replaceAll(IMAGE, " ").match(LINK) ?? [];
320
+ const links = linksOf(body);
203
321
  return links.length > limits.maxLinks ? {
204
322
  check: "too_many_links",
205
- finding: `The body has ${links.length} links; the limit is ${limits.maxLinks}.`,
323
+ finding: `The body has ${plural(links.length, "link")}; the limit is ${limits.maxLinks}.`,
206
324
  text: clip(links.join(" "))
207
325
  } : null;
208
326
  };
@@ -216,7 +334,7 @@ var spamWords = (text, limits) => {
216
334
  );
217
335
  return hits.length > 0 ? {
218
336
  check: "spam_words",
219
- finding: `The copy uses ${hits.length} word(s) or phrase(s) that spam filters weigh.`,
337
+ finding: `The copy uses ${plural(hits.length, "word or phrase", "words or phrases")} that spam filters weigh.`,
220
338
  text: hits.join(", ")
221
339
  } : null;
222
340
  };
@@ -242,7 +360,7 @@ var allCaps = (text, limits) => {
242
360
  const found = words ?? [];
243
361
  return found.length > limits.maxCapsWords ? {
244
362
  check: "all_caps",
245
- finding: `${found.length} word(s) of four or more letters are in capitals; the limit is ${limits.maxCapsWords}.`,
363
+ finding: `${plural(found.length, "word")} of four or more letters ${noun(found.length, "is", "are")} in capitals; the limit is ${limits.maxCapsWords}.`,
246
364
  text: clip(found.join(" "))
247
365
  } : null;
248
366
  };
@@ -273,9 +391,9 @@ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChar
273
391
  } : null;
274
392
 
275
393
  // src/insights/copy/copy-audit.ts
276
- var limit = (fallback, description) => z.number().int().min(0).default(fallback).describe(description);
277
- var input = z.object({
278
- campaign: z.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
394
+ var limit = (fallback, description) => z2.number().int().min(0).default(fallback).describe(description);
395
+ var input = z2.object({
396
+ campaign: z2.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
279
397
  max_body_words: limit(150, "The most words a body may have."),
280
398
  max_caps_words: limit(
281
399
  1,
@@ -288,7 +406,7 @@ var input = z.object({
288
406
  max_exclamations: limit(1, "How many exclamation marks a message may have."),
289
407
  max_links: limit(1, "The most links an email body may have."),
290
408
  max_subject_chars: limit(60, "The most characters a subject may have."),
291
- spam_words: z.array(z.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
409
+ spam_words: z2.array(z2.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
292
410
  "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
293
411
  )
294
412
  });
@@ -410,7 +528,7 @@ var copyAudit = defineInsight({
410
528
  ).length;
411
529
  if (withoutBody > 0) {
412
530
  context.note(
413
- `${withoutBody} variant(s) have no body in the vendor's answer, so their body checks were skipped.`
531
+ withoutBody === 1 ? "1 variant has no body in the vendor's answer, so its body checks were skipped." : `${withoutBody} variants have no body in the vendor's answer, so their body checks were skipped.`
414
532
  );
415
533
  }
416
534
  const severity = (level) => findings.filter((finding) => finding.severity === level).length;
@@ -421,7 +539,8 @@ var copyAudit = defineInsight({
421
539
  low: severity("low"),
422
540
  medium: severity("medium")
423
541
  },
424
- campaign: args.campaign,
542
+ campaign: campaign.ref,
543
+ campaignName: campaign.name,
425
544
  channel: campaign.channel,
426
545
  clean: findings.length === 0,
427
546
  findings,
@@ -434,7 +553,65 @@ var copyAudit = defineInsight({
434
553
  });
435
554
 
436
555
  // src/insights/copy/copy-reuse.ts
556
+ import { z as z4 } from "zod";
557
+
558
+ // src/insights/capped.ts
559
+ var readCapped = async (context, open, cap, room = cap.max) => {
560
+ if (room >= 1) {
561
+ const walk = open(room);
562
+ const items = await context.all(walk, cap);
563
+ return { capped: walk.truncated, items };
564
+ }
565
+ const probe = open(1);
566
+ const left = await context.all(probe, cap);
567
+ if (left.length > 0 && !probe.truncated) {
568
+ context.partial(capNote(cap));
569
+ }
570
+ return { capped: left.length > 0, items: [] };
571
+ };
572
+ var campaignsReadOf = (read) => ({
573
+ campaignsRead: read.items.length,
574
+ moreCampaignsExist: read.capped
575
+ });
576
+ var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns") => {
577
+ const { campaigns } = context.outbound;
578
+ const wanted = [...new Set(statuses)];
579
+ const cap = { input: input27, max, what: "campaigns" };
580
+ if (context.outbound.capabilities["campaigns.status"] === false) {
581
+ const every = await readCapped(
582
+ context,
583
+ (room) => campaigns.listAll({ max: room }),
584
+ cap
585
+ );
586
+ return {
587
+ capped: every.capped,
588
+ items: every.items.filter((campaign) => wanted.includes(campaign.status))
589
+ };
590
+ }
591
+ const found = [];
592
+ let capped2 = false;
593
+ for (const status of wanted) {
594
+ const listed = await readCapped(
595
+ context,
596
+ (room) => campaigns.listAll({ max: room, status }),
597
+ cap,
598
+ max - found.length
599
+ );
600
+ found.push(...listed.items);
601
+ capped2 ||= listed.capped;
602
+ }
603
+ return { capped: capped2, items: found };
604
+ };
605
+
606
+ // src/insights/fields.ts
437
607
  import { z as z3 } from "zod";
608
+ var rangeFields = {
609
+ from: z3.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
610
+ to: z3.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
611
+ };
612
+ var statusesInput = (fallback) => z3.array(campaignStatusSchema).min(1).default([...fallback]).describe(
613
+ "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
614
+ );
438
615
 
439
616
  // src/insights/stats.ts
440
617
  var PLACES = 1e4;
@@ -511,6 +688,8 @@ var compareRates = (first, second, alpha = 0.05) => {
511
688
  z: round(z33) ?? 0
512
689
  };
513
690
  };
691
+ var percent = (value) => value === null ? "unknown" : percentOf(value);
692
+ var spoken = (value) => value === null ? "unknown" : count(value);
514
693
  var pText = (pValue) => pValue < 1 / PLACES ? `p < ${1 / PLACES}` : `p = ${pValue}`;
515
694
  var tally = (values) => {
516
695
  const counts = /* @__PURE__ */ new Map();
@@ -521,34 +700,10 @@ var tally = (values) => {
521
700
  };
522
701
 
523
702
  // src/insights/copy/shared.ts
524
- import { z as z2 } from "zod";
525
- var dayInput = (description) => z2.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "must be YYYY-MM-DD").nullable().default(null).describe(description);
526
703
  var rangeOf = (from, to) => ({
527
704
  from: from ?? void 0,
528
705
  to: to ?? void 0
529
706
  });
530
- var readCapped = (context, walk, max) => context.all(walk(max));
531
- var campaignsIn = async (context, statuses, max) => {
532
- const { outbound } = context;
533
- if (outbound.capabilities["campaigns.status"] === false) {
534
- const every = await readCapped(
535
- context,
536
- (cap) => outbound.campaigns.listAll({ max: cap }),
537
- max
538
- );
539
- return every.filter((campaign) => statuses.includes(campaign.status));
540
- }
541
- const found = [];
542
- for (const status of new Set(statuses)) {
543
- const page = await readCapped(
544
- context,
545
- (cap) => outbound.campaigns.listAll({ max: cap, status }),
546
- max - found.length
547
- );
548
- found.push(...page);
549
- }
550
- return found;
551
- };
552
707
  var firstKnown = (candidates) => {
553
708
  for (const [basis, value] of candidates) {
554
709
  if (value !== null && value > 0) {
@@ -565,13 +720,62 @@ var perMessage = (counts) => firstKnown([
565
720
  ["delivered", counts.delivered],
566
721
  ["sent", counts.sent]
567
722
  ]);
568
- var measure = (count, base) => ({
569
- basis: base.basis,
570
- count,
571
- interval: wilson(count, base.trials),
572
- rate: rate(count, base.trials),
573
- trials: base.trials
574
- });
723
+ var baseIn = (counts, basis) => firstKnown([[basis, counts[basis]]]);
724
+ var ORDER = {
725
+ lead: ["contacted", "sent"],
726
+ message: ["delivered", "sent"]
727
+ };
728
+ var sharedBases = (counts, per) => {
729
+ const own = counts.map(per === "lead" ? perLead : perMessage);
730
+ const based = counts.filter((_, index) => own[index]?.basis !== null);
731
+ for (const basis of ORDER[per]) {
732
+ if (based.every((each) => (each[basis] ?? 0) > 0)) {
733
+ return {
734
+ bases: counts.map((each) => baseIn(each, basis)),
735
+ basis: based.length === 0 ? null : basis,
736
+ comparable: true
737
+ };
738
+ }
739
+ }
740
+ return { bases: own, basis: null, comparable: false };
741
+ };
742
+ var BASIS_WORDS = {
743
+ contacted: "per lead contacted",
744
+ delivered: "per message delivered",
745
+ sent: "per message sent"
746
+ };
747
+ var basesInWords = (named3) => named3.map(
748
+ ({ basis, name }) => `${name} ${basis === null ? "with no base" : BASIS_WORDS[basis]}`
749
+ ).join(", ");
750
+ var measure = (count2, base) => {
751
+ const interval = wilson(count2, base.trials);
752
+ return {
753
+ basis: base.basis,
754
+ count: count2,
755
+ high: interval?.high ?? null,
756
+ interval,
757
+ low: interval?.low ?? null,
758
+ of: base.trials,
759
+ rate: rate(count2, base.trials),
760
+ trials: base.trials
761
+ };
762
+ };
763
+ var NO_RATE = {
764
+ basis: null,
765
+ count: null,
766
+ high: null,
767
+ low: null,
768
+ of: null,
769
+ rate: null
770
+ };
771
+ var replyRateOf = (measured2) => measured2 === null ? NO_RATE : {
772
+ basis: measured2.basis,
773
+ count: measured2.count,
774
+ high: measured2.high,
775
+ low: measured2.low,
776
+ of: measured2.of,
777
+ rate: measured2.rate
778
+ };
575
779
  var sumRows = (rows) => sumCounts(rows);
576
780
  var groupBy = (values, keyOf2) => {
577
781
  const groups = /* @__PURE__ */ new Map();
@@ -608,15 +812,58 @@ var splitStats = (rows) => {
608
812
  return { steps, unattributed: byStep.get(null) ?? [] };
609
813
  };
610
814
 
815
+ // src/insights/copy/reuse-base.ts
816
+ var pooled = (counts, baseOf) => {
817
+ const measured2 = counts.flatMap((each) => {
818
+ const one = each === null ? null : measure(each.replied, baseOf(each));
819
+ return one === null || one.rate === null ? [] : [one];
820
+ });
821
+ const replies2 = total(measured2.map((each) => each.count));
822
+ const trials = total(measured2.map((each) => each.trials));
823
+ const bases = new Set(measured2.map((each) => each.basis));
824
+ const [basis = null] = bases.size === 1 ? bases : [];
825
+ return {
826
+ ...measure(replies2, { basis, trials }),
827
+ sent: total(counts.map((each) => each?.sent ?? null))
828
+ };
829
+ };
830
+ var basesByCampaign = (counted2) => [...groupBy(counted2, (each) => each.campaign.ref).values()].flatMap(
831
+ (group) => {
832
+ const [first] = group;
833
+ const bases = new Set(group.map((each) => perLead(each.counts).basis));
834
+ const [basis = null] = bases.size === 1 ? bases : [];
835
+ return first === void 0 ? [] : [{ basis, name: first.campaign.name }];
836
+ }
837
+ );
838
+ var sharedBaseOf = (context, counted2) => {
839
+ const shared = sharedBases(
840
+ counted2.map((each) => each.counts),
841
+ "lead"
842
+ );
843
+ const { basis } = shared;
844
+ if (!shared.comparable) {
845
+ context.note(
846
+ `The campaigns report different bases (${basesInWords(
847
+ basesByCampaign(counted2)
848
+ )}), so their reply rates are not compared: no spread is judged and no best copy is named.`
849
+ );
850
+ }
851
+ return {
852
+ baseOf: basis === null ? perLead : (counts) => baseIn(counts, basis),
853
+ basis,
854
+ comparable: shared.comparable
855
+ };
856
+ };
857
+
611
858
  // src/insights/copy/copy-reuse.ts
612
- var input2 = z3.object({
613
- max_campaigns: z3.number().int().min(1).max(200).default(20).describe(
859
+ var input2 = z4.object({
860
+ max_campaigns: z4.number().int().min(1).max(200).default(20).describe(
614
861
  "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
615
862
  ),
616
- min_sent: z3.number().int().min(1).default(100).describe(
863
+ min_sent: z4.number().int().min(1).default(100).describe(
617
864
  "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."
618
865
  ),
619
- statuses: z3.array(campaignStatusSchema).min(1).default(["active", "paused", "completed"]).describe("The campaign statuses to read.")
866
+ statuses: statusesInput(["active", "paused", "completed"])
620
867
  });
621
868
  var PREVIEW = 120;
622
869
  var placementsOf = (campaign, sequence2, stats) => sequence2.steps.flatMap((step) => {
@@ -638,30 +885,23 @@ var placementsOf = (campaign, sequence2, stats) => sequence2.steps.flatMap((step
638
885
  ];
639
886
  });
640
887
  });
641
- var pooled = (counts) => {
642
- const measured2 = counts.flatMap((each) => {
643
- const one = each === null ? null : measure(each.replied, perLead(each));
644
- return one === null || one.rate === null ? [] : [one];
645
- });
646
- const replies2 = total(measured2.map((each) => each.count));
647
- const trials = total(measured2.map((each) => each.trials));
648
- return {
649
- ...measure(replies2, { basis: null, trials }),
650
- sent: total(counts.map((each) => each?.sent ?? null))
651
- };
652
- };
653
- var useOf = (placements) => {
888
+ var useOf = (placements, baseOf) => {
654
889
  const [first] = placements;
655
890
  if (first === void 0) {
656
891
  return [];
657
892
  }
658
- const sum = pooled(placements.map((placement) => placement.counts));
893
+ const sum = pooled(
894
+ placements.map((placement) => placement.counts),
895
+ baseOf
896
+ );
659
897
  return [
660
898
  {
661
899
  campaign: first.campaign.ref,
662
900
  campaignName: first.campaign.name,
663
901
  places: placements.map((placement) => placement.place),
902
+ basis: sum.basis,
664
903
  provider: first.campaign.provider,
904
+ rates: { replyRate: replyRateOf(sum) },
665
905
  replies: sum.count,
666
906
  replyRate: sum.rate,
667
907
  replyRateInterval: sum.interval,
@@ -670,17 +910,22 @@ var useOf = (placements) => {
670
910
  }
671
911
  ];
672
912
  };
673
- var pieceOf = (placements, uses) => {
913
+ var pieceOf = (placements, uses, baseOf) => {
674
914
  const [first] = placements;
675
915
  if (first === void 0) {
676
916
  return [];
677
917
  }
678
- const sum = pooled(placements.map((placement) => placement.counts));
918
+ const sum = pooled(
919
+ placements.map((placement) => placement.counts),
920
+ baseOf
921
+ );
679
922
  return [
680
923
  {
924
+ basis: sum.basis,
681
925
  bodyPreview: first.body?.slice(0, PREVIEW) ?? null,
682
926
  campaigns: uses.length,
683
927
  contentHash: first.contentHash,
928
+ rates: { replyRate: replyRateOf(sum) },
684
929
  replies: sum.count,
685
930
  replyRate: sum.rate,
686
931
  replyRateInterval: sum.interval,
@@ -691,16 +936,16 @@ var pieceOf = (placements, uses) => {
691
936
  ];
692
937
  };
693
938
  var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
694
- var spreadOf = (uses, minSent) => {
939
+ var spreadOf = (uses, minSent, comparable) => {
695
940
  const judged = uses.filter(
696
941
  (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
697
942
  );
698
943
  const [best] = judged;
699
944
  const worst = judged.at(-1);
700
- if (best === void 0 || worst === void 0 || judged.length < 2) {
945
+ if (!comparable || best === void 0 || worst === void 0 || judged.length < 2) {
701
946
  return {
702
947
  best: null,
703
- finding: `Fewer than two campaigns have a base of ${minSent}, so the spread is not judged.`,
948
+ finding: comparable ? `Fewer than two campaigns have a base of ${minSent}, so the spread is not judged.` : "The campaigns report different bases, so the spread is not judged.",
704
949
  spread: null,
705
950
  spreadIsReal: null,
706
951
  spreadPValue: null,
@@ -714,7 +959,7 @@ var spreadOf = (uses, minSent) => {
714
959
  const real = test?.significant ?? false;
715
960
  return {
716
961
  best: best.campaign,
717
- finding: real ? `The same copy gets ${best.replyRate} in ${best.campaignName} and ${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 ${best.replyRate} in ${best.campaignName} and ${worst.replyRate} in ${worst.campaignName}; a gap this size could be chance.`,
962
+ 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.`,
718
963
  spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
719
964
  spreadIsReal: real,
720
965
  spreadPValue: test?.pValue ?? null,
@@ -737,38 +982,47 @@ var readPlacements = async (context, campaigns) => {
737
982
  return perCampaign.flat();
738
983
  };
739
984
  var copyReuse = defineInsight({
740
- 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. 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.",
985
+ 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.",
741
986
  inputSchema: input2,
742
987
  key: "copyReuse",
743
988
  name: "copy_reuse",
744
989
  needs: ["sequence", "stats.byStep"],
745
990
  next: "Use step_funnel on the campaign where the copy does worst, or variant_test where the copy runs against another variant.",
746
991
  run: async (context, { max_campaigns, min_sent, statuses }) => {
747
- const campaigns = await campaignsIn(context, statuses, max_campaigns);
992
+ const listed = await readCampaignsIn(context, statuses, max_campaigns);
993
+ const campaigns = listed.items;
748
994
  const placements = await readPlacements(context, campaigns);
749
995
  const without = placements.filter((each) => each.counts === null).length;
750
996
  if (without > 0) {
751
997
  context.note(
752
- `${without} variant(s) have no counts of their own: the vendor reports their step as a whole, or not at all. Their copy is listed without numbers.`
998
+ `${without === 1 ? "1 variant has" : `${without} variants have`} no counts of their own: the vendor reports their step as a whole, or not at all. Their copy is listed without numbers.`
753
999
  );
754
1000
  }
1001
+ const { baseOf, basis, comparable } = sharedBaseOf(
1002
+ context,
1003
+ placements.flatMap(
1004
+ (each) => each.counts === null ? [] : [{ campaign: each.campaign, counts: each.counts }]
1005
+ )
1006
+ );
755
1007
  const pieces = [...groupBy(placements, (each) => each.contentHash)].flatMap(
756
1008
  ([, group]) => {
757
- const uses = [...groupBy(group, (each) => each.campaign.ref).values()].flatMap(useOf).toSorted(byRate);
758
- return pieceOf(group, uses).map((piece) => ({ piece, uses }));
1009
+ const uses = [...groupBy(group, (each) => each.campaign.ref).values()].flatMap((each) => useOf(each, baseOf)).toSorted(byRate);
1010
+ return pieceOf(group, uses, baseOf).map((piece) => ({ piece, uses }));
759
1011
  }
760
1012
  );
761
1013
  const reused = pieces.flatMap(
762
- ({ piece, uses }) => uses.length < 2 ? [] : [{ ...piece, ...spreadOf(uses, min_sent), uses }]
1014
+ ({ piece, uses }) => uses.length < 2 ? [] : [{ ...piece, ...spreadOf(uses, min_sent, comparable), uses }]
763
1015
  ).toSorted(
764
1016
  (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
765
1017
  );
766
1018
  const [bestCopy] = pieces.flatMap(
767
- ({ piece }) => piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
1019
+ ({ piece }) => comparable && piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
768
1020
  ).toSorted(byRate);
769
1021
  const result = {
1022
+ basis,
770
1023
  bestCopy: bestCopy ?? null,
771
1024
  campaignsRead: campaigns.length,
1025
+ moreCampaignsExist: listed.capped,
772
1026
  piecesOfCopy: pieces.length,
773
1027
  reused,
774
1028
  variantsWithoutStats: without
@@ -778,21 +1032,35 @@ var copyReuse = defineInsight({
778
1032
  });
779
1033
 
780
1034
  // src/insights/copy/reply-timing.ts
781
- import { z as z4 } from "zod";
1035
+ import { z as z5 } from "zod";
1036
+
1037
+ // src/insights/campaign.ts
1038
+ var confirmCampaign = async (context, campaign) => {
1039
+ context.one(await context.outbound.campaigns.get(campaign));
1040
+ };
1041
+
1042
+ // src/insights/ref.ts
1043
+ var refOf = (outbound, id) => {
1044
+ const provider = parseRef(id)?.provider;
1045
+ return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
1046
+ };
1047
+
1048
+ // src/insights/copy/reply-timing.ts
782
1049
  var DAY_MS = 864e5;
1050
+ var MAX_UNPAIRED_SHARE = 0.25;
783
1051
  var HOUR_MS = 36e5;
784
1052
  var MINUTE_MS = 6e4;
785
- var input3 = z4.object({
786
- campaign: z4.string().min(1).nullable().default(null).describe(
787
- "A campaign's ref to look at one campaign. null looks at every campaign."
1053
+ var input3 = z5.object({
1054
+ campaign: z5.string().min(1).nullable().default(null).describe(
1055
+ "A campaign's ref to look at one campaign; an unknown one is refused with NotFound. null looks at every campaign."
788
1056
  ),
789
- max_messages: z4.number().int().min(1).max(5e4).default(2e3).describe(
1057
+ max_messages: z5.number().int().min(1).max(5e4).default(2e3).describe(
790
1058
  "The most messages to read, sent and received together. A page of messages costs 1 request."
791
1059
  ),
792
- since: z4.iso.datetime({ offset: true }).nullable().default(null).describe(
1060
+ since: z5.iso.datetime({ offset: true }).nullable().default(null).describe(
793
1061
  "Only messages from this time on, ISO 8601. null means 30 days before now."
794
1062
  ),
795
- timezone_offset_minutes: z4.number().int().min(-720).max(840).default(0).describe(
1063
+ timezone_offset_minutes: z5.number().int().min(-720).max(840).default(0).describe(
796
1064
  "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
797
1065
  )
798
1066
  });
@@ -865,10 +1133,10 @@ var tableOf = (times3, offsetMinutes) => {
865
1133
  share: rate(days[day] ?? 0, times3.length),
866
1134
  weekday: WEEKDAYS[day] ?? "Sunday"
867
1135
  }));
868
- const byHour = hours.map((count, hour) => ({
869
- count,
1136
+ const byHour = hours.map((count2, hour) => ({
1137
+ count: count2,
870
1138
  hour,
871
- share: rate(count, times3.length)
1139
+ share: rate(count2, times3.length)
872
1140
  }));
873
1141
  return {
874
1142
  byHour,
@@ -880,11 +1148,14 @@ var tableOf = (times3, offsetMinutes) => {
880
1148
  var readMessages = async (context, campaign, since, max) => {
881
1149
  const { outbound } = context;
882
1150
  const filters = outbound.capabilities["messages.since"] === false ? {} : { since };
883
- const messages = await readCapped(
1151
+ const { items: messages } = await readCapped(
884
1152
  context,
885
1153
  (cap) => campaign === null ? outbound.messages.listAll({ ...filters, max: cap }) : outbound.campaign(campaign).messages.listAll({ ...filters, max: cap }),
886
- max
1154
+ { input: "max_messages", max, what: "messages" }
887
1155
  );
1156
+ if (campaign !== null && messages.length === 0) {
1157
+ await confirmCampaign(context, campaign);
1158
+ }
888
1159
  if (outbound.capabilities["messages.since"] === false) {
889
1160
  context.note(
890
1161
  "This tool cannot filter messages by date, so the cap applies to all messages and older ones were dropped after reading."
@@ -894,8 +1165,21 @@ var readMessages = async (context, campaign, since, max) => {
894
1165
  (message) => message.sentAt === null || message.sentAt >= since
895
1166
  );
896
1167
  };
1168
+ var noteGaps = (context, unpaired, received) => {
1169
+ const share2 = rate(unpaired, received);
1170
+ if (share2 !== null && share2 > MAX_UNPAIRED_SHARE) {
1171
+ context.partial(
1172
+ `${unpaired} of ${received} replies (${percent(share2)}) were not paired with a send, often because the send went out before since. Time to reply leaves them out, so it may look faster than it is; set since earlier to pair more.`
1173
+ );
1174
+ }
1175
+ if (received > 0) {
1176
+ context.note(
1177
+ "Automatic replies such as out-of-office messages are counted as replies: messages carry no auto flag, so they cannot be told apart. A fast median can be auto-replies."
1178
+ );
1179
+ }
1180
+ };
897
1181
  var replyTiming = defineInsight({
898
- 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. 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.",
1182
+ 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.",
899
1183
  inputSchema: input3,
900
1184
  key: "replyTiming",
901
1185
  name: "reply_timing",
@@ -911,18 +1195,21 @@ var replyTiming = defineInsight({
911
1195
  );
912
1196
  const paired = pair(messages);
913
1197
  const hours = paired.pairs.map((each) => (each.at - each.sentAt) / HOUR_MS);
914
- const within = (limit2) => rate(hours.filter((value) => value <= limit2).length, hours.length);
1198
+ const within = (limit3) => rate(hours.filter((value) => value <= limit3).length, hours.length);
915
1199
  const received = messages.filter((message) => message.direction === "in");
916
1200
  const untimed = received.length - paired.replyTimes.length;
1201
+ const unpaired = paired.unpaired + untimed;
1202
+ noteGaps(context, unpaired, received.length);
917
1203
  const timing = {
918
- campaign: args.campaign,
1204
+ campaign: args.campaign === null ? null : refOf(context.outbound, args.campaign),
919
1205
  counts: {
920
1206
  followOnReplies: paired.followOn,
921
1207
  messagesRead: messages.length,
922
1208
  paired: paired.pairs.length,
923
1209
  received: received.length,
924
1210
  sent: messages.length - received.length,
925
- unpaired: paired.unpaired + untimed
1211
+ unpaired,
1212
+ unpairedShare: rate(unpaired, received.length)
926
1213
  },
927
1214
  replies: tableOf(paired.replyTimes, args.timezone_offset_minutes),
928
1215
  sendsThatDrewReplies: tableOf(
@@ -946,19 +1233,19 @@ var replyTiming = defineInsight({
946
1233
  });
947
1234
 
948
1235
  // src/insights/copy/step-funnel.ts
949
- import { z as z5 } from "zod";
950
- var input4 = z5.object({
951
- campaign: z5.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
952
- from: dayInput("First day to count, YYYY-MM-DD. null counts from the start."),
953
- min_reply_rate: z5.number().min(0).max(1).default(0).describe(
1236
+ import { z as z6 } from "zod";
1237
+ var input4 = z6.object({
1238
+ campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1239
+ ...rangeFields,
1240
+ min_reply_rate: z6.number().min(0).max(1).default(0).describe(
954
1241
  "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."
955
- ),
956
- to: dayInput("Last day to count, YYYY-MM-DD. null counts to today.")
1242
+ )
957
1243
  });
958
1244
  var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, counts]) => {
959
1245
  const measured2 = measure(counts.replied, perLead(counts));
960
1246
  return {
961
1247
  contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
1248
+ rates: { replyRate: replyRateOf(measured2) },
962
1249
  replies: counts.replied,
963
1250
  replyRate: measured2.rate,
964
1251
  replyRateInterval: measured2.interval,
@@ -976,6 +1263,7 @@ var draftOf = (index, step, stats, minReplyRate) => {
976
1263
  earnsPlace: interval === null ? null : interval.low > minReplyRate,
977
1264
  inSequence: step !== void 0,
978
1265
  parent: step === void 0 ? null : step.parentIndex,
1266
+ rates: { replyRate: replyRateOf(measured2) },
979
1267
  replies: counts?.replied ?? null,
980
1268
  replyRate: measured2?.rate ?? null,
981
1269
  replyRateBasis: measured2?.basis ?? null,
@@ -1011,14 +1299,14 @@ var describe = (steps, top, last, allReplies) => {
1011
1299
  if (top === null) {
1012
1300
  return "No step has a reply in this range.";
1013
1301
  }
1014
- const lead = `Step ${top.step} (counted from 0) brings the most replies: ${top.replies} of ${allReplies}.`;
1302
+ const lead = `Step ${top.step + 1} brings the most replies: ${top.replies} of ${allReplies}.`;
1015
1303
  if (last === null) {
1016
1304
  return `${lead} No step's reply rate is reliably above the bar yet.`;
1017
1305
  }
1018
1306
  const later = steps.filter(
1019
1307
  (step) => step.step > last.step && step.sent !== null
1020
1308
  );
1021
- return later.length === 0 ? `${lead} Every step up to step ${last.step} still earns its place.` : `${lead} Step ${last.step} is the last whose reply rate is reliably above the bar; the ${later.length} later step(s) sent ${total(later.map((step) => step.sent))} messages for ${total(later.map((step) => step.replies)) ?? "an unknown number of"} replies.`;
1309
+ return later.length === 0 ? `${lead} Every step up to step ${last.step + 1} still earns its place.` : `${lead} Step ${last.step + 1} is the last whose reply rate is reliably above the bar; the ${later.length === 1 ? "1 later step" : `${later.length} later steps`} sent ${total(later.map((step) => step.sent))} messages for ${total(later.map((step) => step.replies)) ?? "an unknown number of"} replies.`;
1022
1310
  };
1023
1311
  var unattributedOf = (rows) => {
1024
1312
  const counts = sumRows(rows);
@@ -1066,7 +1354,7 @@ var stepFunnel = defineInsight({
1066
1354
  );
1067
1355
  }
1068
1356
  const funnel = {
1069
- campaign,
1357
+ campaign: refOf(context.outbound, campaign),
1070
1358
  finding: describe(steps, top, last, allReplies),
1071
1359
  lastStepEarningPlace: last?.step ?? null,
1072
1360
  steps,
@@ -1082,23 +1370,22 @@ var stepFunnel = defineInsight({
1082
1370
  });
1083
1371
 
1084
1372
  // src/insights/copy/variant-test.ts
1085
- import { z as z6 } from "zod";
1373
+ import { z as z7 } from "zod";
1086
1374
  var METRICS = ["replied", "positive", "opened", "clicked"];
1087
- var input5 = z6.object({
1088
- alpha: z6.number().gt(0).max(0.5).default(0.05).describe(
1375
+ var input5 = z7.object({
1376
+ alpha: z7.number().gt(0).max(0.5).default(0.05).describe(
1089
1377
  "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1090
1378
  ),
1091
- campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1092
- from: dayInput("First day to count, YYYY-MM-DD. null counts from the start."),
1093
- metric: z6.enum(METRICS).default("replied").describe(
1379
+ campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1380
+ ...rangeFields,
1381
+ metric: z7.enum(METRICS).default("replied").describe(
1094
1382
  "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)."
1095
1383
  ),
1096
- min_sent: z6.number().int().min(1).default(100).describe(
1384
+ min_sent: z7.number().int().min(1).default(100).describe(
1097
1385
  "A variant with a smaller base than this (sends, or leads contacted when the vendor counts those) is not compared."
1098
- ),
1099
- to: dayInput("Last day to count, YYYY-MM-DD. null counts to today.")
1386
+ )
1100
1387
  });
1101
- var ORDER = {
1388
+ var ORDER2 = {
1102
1389
  no_difference_yet: 1,
1103
1390
  too_little_data: 2,
1104
1391
  winner: 0
@@ -1108,8 +1395,7 @@ var quantile = (tail) => {
1108
1395
  return t - (2.515517 + 0.802853 * t + 0.010328 * t ** 2) / (1 + 1.432788 * t + 0.189269 * t ** 2 + 1308e-6 * t ** 3);
1109
1396
  };
1110
1397
  var sendsToSignificance = (score, trials, alpha) => score === 0 ? null : Math.max(0, Math.ceil(((quantile(alpha / 2) / score) ** 2 - 1) * trials));
1111
- var candidateOf = (variantKey, counts, metric, minSent) => {
1112
- const base = metric === "replied" || metric === "positive" ? perLead(counts) : perMessage(counts);
1398
+ var candidateOf = (variantKey, counts, base, minSent, metric) => {
1113
1399
  const measured2 = measure(counts[metric], base);
1114
1400
  return {
1115
1401
  ...measured2,
@@ -1127,25 +1413,34 @@ var shortfall = (candidates, minSent) => {
1127
1413
  0
1128
1414
  );
1129
1415
  };
1130
- var tooLittle = (step, candidates, settings) => {
1131
- const unreported = candidates.some((each) => each.count === null);
1132
- return {
1133
- leader: null,
1134
- moreSendsNeeded: shortfall(candidates, settings.minSent),
1135
- pValue: null,
1136
- reason: unreported ? `The vendor does not report ${settings.metric} for every variant of this step, so they cannot be compared.` : `Fewer than two variants have a base of ${settings.minSent}, so no comparison is made.`,
1137
- step,
1138
- variants: candidates.map((each) => ({ ...each, pValueVsLeader: null })),
1139
- verdict: "too_little_data"
1140
- };
1141
- };
1142
- var testStep = (step, candidates, settings) => {
1416
+ var reasonFor = (candidates, settings, comparable) => {
1417
+ if (!comparable) {
1418
+ return `The variants of this step report different bases (${basesInWords(
1419
+ candidates.map((each) => ({ basis: each.basis, name: each.variantKey }))
1420
+ )}), so their rates cannot be compared.`;
1421
+ }
1422
+ return candidates.some((each) => each.count === null) ? `The vendor does not report ${settings.metric} for every variant of this step, so they cannot be compared.` : `Fewer than two variants have a base of ${settings.minSent}, so no comparison is made.`;
1423
+ };
1424
+ var tooLittle = (step, candidates, settings, comparable) => ({
1425
+ leader: null,
1426
+ // More sends do not give variants with different bases a common one.
1427
+ moreSendsNeeded: comparable ? shortfall(candidates, settings.minSent) : null,
1428
+ pValue: null,
1429
+ reason: reasonFor(candidates, settings, comparable),
1430
+ step,
1431
+ variants: candidates.map((each) => ({ ...each, pValueVsLeader: null })),
1432
+ verdict: "too_little_data"
1433
+ });
1434
+ var testStep = (step, candidates, settings, comparable) => {
1435
+ if (!comparable) {
1436
+ return tooLittle(step, candidates, settings, false);
1437
+ }
1143
1438
  const ready = candidates.filter((each) => each.enoughData).toSorted(
1144
1439
  (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
1145
1440
  );
1146
1441
  const [leader, rival] = ready;
1147
1442
  if (leader === void 0 || rival === void 0) {
1148
- return tooLittle(step, candidates, settings);
1443
+ return tooLittle(step, candidates, settings, true);
1149
1444
  }
1150
1445
  const tests = new Map(
1151
1446
  ready.slice(1).map((other) => [
@@ -1160,7 +1455,7 @@ var testStep = (step, candidates, settings) => {
1160
1455
  const closest = tests.get(rival.variantKey) ?? null;
1161
1456
  const beatsAll = [...tests.values()].every((test) => test?.significant);
1162
1457
  const skipped = candidates.length - ready.length;
1163
- const aside = skipped === 0 ? "" : ` ${skipped} variant(s) with too little data were left out.`;
1458
+ const aside = skipped === 0 ? "" : ` ${plural(skipped, "variant")} with too little data ${noun(skipped, "was", "were")} left out.`;
1164
1459
  const variants = candidates.map((each) => ({
1165
1460
  ...each,
1166
1461
  pValueVsLeader: tests.get(each.variantKey)?.pValue ?? null
@@ -1170,7 +1465,7 @@ var testStep = (step, candidates, settings) => {
1170
1465
  leader: leader.variantKey,
1171
1466
  moreSendsNeeded: null,
1172
1467
  pValue: closest?.pValue ?? null,
1173
- reason: `Variant ${leader.variantKey} (${leader.rate}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1468
+ reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1174
1469
  step,
1175
1470
  variants,
1176
1471
  verdict: "winner"
@@ -1184,15 +1479,47 @@ var testStep = (step, candidates, settings) => {
1184
1479
  settings.alpha
1185
1480
  ),
1186
1481
  pValue: closest?.pValue ?? null,
1187
- reason: `Variant ${leader.variantKey} (${leader.rate}) leads variant ${rival.variantKey} (${rival.rate}), but a gap this size could be chance.${aside}`,
1482
+ reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) leads variant ${rival.variantKey} (${percent(rival.rate)}), but a gap this size could be chance.${aside}`,
1188
1483
  step,
1189
1484
  variants,
1190
1485
  verdict: "no_difference_yet"
1191
1486
  };
1192
1487
  };
1488
+ var stepTest = (step, variants, settings) => {
1489
+ const entries = [...variants];
1490
+ const { bases, comparable } = sharedBases(
1491
+ entries.map(([, counts]) => counts),
1492
+ settings.metric === "replied" || settings.metric === "positive" ? "lead" : "message"
1493
+ );
1494
+ const candidates = entries.map(
1495
+ ([key, counts], index) => candidateOf(
1496
+ key,
1497
+ counts,
1498
+ bases[index] ?? { basis: null, trials: null },
1499
+ settings.minSent,
1500
+ settings.metric
1501
+ )
1502
+ );
1503
+ return testStep(step, candidates, settings, comparable);
1504
+ };
1505
+ var variantsReported = (context, rows) => {
1506
+ if (rows.length === 0) {
1507
+ context.note(
1508
+ "The vendor reported no step stats for this campaign in the date range, so there is nothing to compare."
1509
+ );
1510
+ return null;
1511
+ }
1512
+ const reported = rows.some((row) => row.variantKey !== null);
1513
+ if (!reported) {
1514
+ context.note(
1515
+ "The step stats carry no variant rows, so there is nothing to compare."
1516
+ );
1517
+ }
1518
+ return reported;
1519
+ };
1193
1520
  var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1194
1521
  var variantTest = defineInsight({
1195
- 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.",
1522
+ 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.",
1196
1523
  inputSchema: input5,
1197
1524
  key: "variantTest",
1198
1525
  name: "variant_test",
@@ -1205,27 +1532,14 @@ var variantTest = defineInsight({
1205
1532
  const split = splitStats(rows);
1206
1533
  const settings = { alpha, metric, minSent: min_sent };
1207
1534
  const steps = [...split.steps].flatMap(
1208
- ([step, stats]) => stats.variants.size < 2 ? [] : [
1209
- testStep(
1210
- step,
1211
- [...stats.variants].map(
1212
- ([key, counts]) => candidateOf(key, counts, metric, min_sent)
1213
- ),
1214
- settings
1215
- )
1216
- ]
1535
+ ([step, stats]) => stats.variants.size < 2 ? [] : [stepTest(step, stats.variants, settings)]
1217
1536
  ).toSorted(
1218
- (left, right) => ORDER[left.verdict] - ORDER[right.verdict] || left.step - right.step
1537
+ (left, right) => ORDER2[left.verdict] - ORDER2[right.verdict] || left.step - right.step
1219
1538
  );
1220
- const reported = rows.some((row) => row.variantKey !== null);
1221
- if (!reported) {
1222
- context.note(
1223
- "The step stats carry no variant rows, so there is nothing to compare."
1224
- );
1225
- }
1539
+ const reported = variantsReported(context, rows);
1226
1540
  const result = {
1227
1541
  alpha,
1228
- campaign,
1542
+ campaign: refOf(context.outbound, campaign),
1229
1543
  metric,
1230
1544
  steps,
1231
1545
  totals: {
@@ -1250,10 +1564,10 @@ var COPY_INSIGHTS = [
1250
1564
  ];
1251
1565
 
1252
1566
  // src/insights/ops/anomalies.ts
1253
- import { z as z8 } from "zod";
1567
+ import { z as z9 } from "zod";
1254
1568
 
1255
1569
  // src/insights/ops/shared.ts
1256
- import { z as z7 } from "zod";
1570
+ import { z as z8 } from "zod";
1257
1571
  var DAY_MS2 = 864e5;
1258
1572
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1259
1573
  var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
@@ -1262,15 +1576,12 @@ var lastDays = (now, days, back = 0) => ({
1262
1576
  to: dayOf(now - (days * back + 1) * DAY_MS2)
1263
1577
  });
1264
1578
  var listFields = (costPerCampaign) => ({
1265
- max_campaigns: z7.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1266
- statuses: z7.array(campaignStatusSchema).min(1).default(["active", "paused", "completed"]).describe("Only campaigns in one of these states are read")
1579
+ max_campaigns: z8.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1580
+ statuses: statusesInput(["active", "paused", "completed"])
1267
1581
  });
1268
- var rangeFields = {
1269
- from: z7.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
1270
- to: z7.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
1271
- };
1272
1582
  var labelOf = (campaign) => ({
1273
1583
  campaign: campaign.ref,
1584
+ campaignName: campaign.name,
1274
1585
  channel: campaign.channel,
1275
1586
  name: campaign.name,
1276
1587
  provider: campaign.provider,
@@ -1283,26 +1594,33 @@ var totalsOf = (counts) => ({
1283
1594
  replied: counts.replied,
1284
1595
  sent: counts.sent
1285
1596
  });
1286
- var measure2 = (count, of) => {
1287
- const interval = wilson(count, of);
1597
+ var measure2 = (count2, of) => {
1598
+ const interval = wilson(count2, of);
1288
1599
  return {
1289
- count,
1600
+ count: count2,
1290
1601
  high: interval?.high ?? null,
1291
1602
  low: interval?.low ?? null,
1292
1603
  of,
1293
- rate: rate(count, of)
1604
+ rate: rate(count2, of)
1294
1605
  };
1295
1606
  };
1296
- var perLeadBase = (counts) => counts.contacted !== null && counts.contacted > 0 ? counts.contacted : counts.sent;
1297
- var ratesOf = (counts) => ({
1607
+ var baseIn2 = (basis) => (counts) => counts[basis];
1608
+ var perLeadBasis = (counts) => counts.contacted !== null && counts.contacted > 0 ? "contacted" : "sent";
1609
+ var perLeadBase = (counts) => counts[perLeadBasis(counts)];
1610
+ var periodBasis = (current, previous) => current.sent !== null && previous.sent !== null ? "sent" : "contacted";
1611
+ var RATE_WORDS = {
1612
+ contacted: "Replies per lead contacted",
1613
+ sent: "Replies per message sent"
1614
+ };
1615
+ var ratesOf = (counts, base = perLeadBase) => ({
1298
1616
  bounceRate: measure2(counts.bounced, counts.sent),
1299
- positiveRate: measure2(counts.positive, perLeadBase(counts)),
1300
- replyRate: measure2(counts.replied, perLeadBase(counts))
1617
+ positiveRate: measure2(counts.positive, base(counts)),
1618
+ replyRate: measure2(counts.replied, base(counts))
1301
1619
  });
1302
1620
  var measureAcross = (rows, countOf3, baseOf) => {
1303
1621
  const sides = rows.map((row) => ({ base: baseOf(row), count: countOf3(row) }));
1304
1622
  const pairs = sides.flatMap(
1305
- ({ base, count }) => count === null || base === null ? [] : [{ base, count }]
1623
+ ({ base, count: count2 }) => count2 === null || base === null ? [] : [{ base, count: count2 }]
1306
1624
  );
1307
1625
  return {
1308
1626
  counted: pairs.length,
@@ -1314,9 +1632,9 @@ var measureAcross = (rows, countOf3, baseOf) => {
1314
1632
  };
1315
1633
  };
1316
1634
  var partialRate = (name, across) => across.counted > 0 && across.counted < across.of ? [`${name} (${across.counted} of ${across.of})`] : [];
1317
- var ratesAcross = (rows) => {
1318
- const reply = measureAcross(rows, (row) => row.replied, perLeadBase);
1319
- const positive = measureAcross(rows, (row) => row.positive, perLeadBase);
1635
+ var ratesAcross = (rows, base = perLeadBase) => {
1636
+ const reply = measureAcross(rows, (row) => row.replied, base);
1637
+ const positive = measureAcross(rows, (row) => row.positive, base);
1320
1638
  const bounce = measureAcross(
1321
1639
  rows,
1322
1640
  (row) => row.bounced,
@@ -1337,40 +1655,12 @@ var ratesAcross = (rows) => {
1337
1655
  };
1338
1656
  var partialNote = (where, partial, rows = "campaigns") => `${where}: ${partial.join(", ")} ${partial.length === 1 ? "counts" : "count"} only the ${rows} that report both the count and what it is divided by. The others are left out of the rate, not counted as 0.`;
1339
1657
  var volumeOf = (counts) => counts.sent ?? counts.contacted;
1340
- var percent = (value) => value === null ? "unknown" : `${Math.round(value * 1e3) / 10}%`;
1341
1658
  var descending = (left, right) => {
1342
1659
  if (left === null || right === null) {
1343
1660
  return Number(left === null) - Number(right === null);
1344
1661
  }
1345
1662
  return right - left;
1346
1663
  };
1347
- var readUpTo = async (context, list, max) => {
1348
- const walk = list(max);
1349
- const items = await context.all(walk);
1350
- return { complete: !walk.truncated, items };
1351
- };
1352
- var readCampaigns = async (context, statuses, max) => {
1353
- const { campaigns } = context.outbound;
1354
- const wanted = [...new Set(statuses)];
1355
- if (context.outbound.capabilities["campaigns.status"] === false) {
1356
- const every = await readUpTo(
1357
- context,
1358
- (cap) => campaigns.listAll({ max: cap }),
1359
- max
1360
- );
1361
- return every.items.filter((campaign) => wanted.includes(campaign.status));
1362
- }
1363
- const found = [];
1364
- for (const status of wanted) {
1365
- const listed = await readUpTo(
1366
- context,
1367
- (cap) => campaigns.listAll({ max: cap, status }),
1368
- max - found.length
1369
- );
1370
- found.push(...listed.items);
1371
- }
1372
- return found;
1373
- };
1374
1664
  var readTotals = async (context, campaign, range) => sumCounts(
1375
1665
  context.rows(
1376
1666
  await context.outbound.campaign(campaign).stats({ from: range.from ?? void 0, to: range.to ?? void 0 })
@@ -1399,19 +1689,21 @@ var readAllTotals = async (context, range) => {
1399
1689
  );
1400
1690
  };
1401
1691
  var readCampaignTotals = async (context, input27) => {
1402
- const campaigns = await readCampaigns(
1692
+ const listed = await readCampaignsIn(
1403
1693
  context,
1404
1694
  input27.statuses,
1405
1695
  input27.max_campaigns
1406
1696
  );
1697
+ const campaigns = listed.items;
1407
1698
  const reported = campaigns.length > 1 ? await readAllTotals(context, input27) : void 0;
1408
- return await mapConcurrent(
1699
+ const entries = await mapConcurrent(
1409
1700
  campaigns,
1410
1701
  async (campaign) => ({
1411
1702
  campaign,
1412
1703
  counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input27)
1413
1704
  })
1414
1705
  );
1706
+ return { entries, read: campaignsReadOf(listed) };
1415
1707
  };
1416
1708
  var readDaily = async (context, campaign, range) => {
1417
1709
  const options = { by: "day", from: range.from, to: range.to };
@@ -1428,7 +1720,7 @@ var readDaily = async (context, campaign, range) => {
1428
1720
  };
1429
1721
 
1430
1722
  // src/insights/ops/anomalies.ts
1431
- var metricSchema = z8.enum([
1723
+ var metricSchema = z9.enum([
1432
1724
  "sent",
1433
1725
  "contacted",
1434
1726
  "replied",
@@ -1438,15 +1730,15 @@ var metricSchema = z8.enum([
1438
1730
  "clicked",
1439
1731
  "unsubscribed"
1440
1732
  ]);
1441
- var input6 = z8.object({
1442
- baseline_days: z8.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1443
- campaign: z8.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1444
- days: z8.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1445
- metrics: z8.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1446
- min_baseline_points: z8.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1447
- threshold: z8.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1733
+ var input6 = z9.object({
1734
+ 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"),
1735
+ campaign: z9.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1736
+ days: z9.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1737
+ metrics: z9.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1738
+ min_baseline_points: z9.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1739
+ threshold: z9.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1448
1740
  });
1449
- var reasonFor = (metric, daysWithData) => daysWithData === 0 ? `The vendor reports no ${metric} count for these days.` : "Too few earlier days with data to form a baseline.";
1741
+ 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.";
1450
1742
  var judge = (metric, point, baseline, threshold) => {
1451
1743
  const center = round(mean(baseline)) ?? 0;
1452
1744
  const score = zScore(point.value, baseline);
@@ -1461,14 +1753,14 @@ var judge = (metric, point, baseline, threshold) => {
1461
1753
  if (score === null) {
1462
1754
  return point.value === baseline[0] ? null : {
1463
1755
  ...shared,
1464
- finding: `${metric} was ${point.value} on ${point.date}, against ${center} on each of the ${baseline.length} days with data before it (a flat baseline has no z-score: any other count is flagged).`,
1756
+ finding: `${metric} was ${point.value} on ${point.date}, against ${spoken(center)} on each of the ${baseline.length} days with data before it (a flat baseline has no z-score: any other count is flagged).`,
1465
1757
  judgedBy: "flat_baseline",
1466
1758
  zScore: null
1467
1759
  };
1468
1760
  }
1469
1761
  return Math.abs(score) < threshold ? null : {
1470
1762
  ...shared,
1471
- finding: `${metric} was ${point.value} on ${point.date}, against an average of ${center} over the ${baseline.length} days with data before it (z = ${round(score)}).`,
1763
+ finding: `${metric} was ${point.value} on ${point.date}, against an average of ${spoken(center)} over the ${baseline.length} days with data before it (z = ${spoken(score)}).`,
1472
1764
  judgedBy: "z_score",
1473
1765
  zScore: round(score) ?? 0
1474
1766
  };
@@ -1500,7 +1792,7 @@ var scanMetric = (series, metric, options) => {
1500
1792
  daysTested: tested,
1501
1793
  daysWithData: checked.length,
1502
1794
  metric,
1503
- reason: tested > 0 ? null : reasonFor(metric, checked.length),
1795
+ reason: tested > 0 ? null : reasonFor2(metric, checked.length),
1504
1796
  testable: tested > 0
1505
1797
  }
1506
1798
  };
@@ -1541,7 +1833,7 @@ var anomalies = defineInsight({
1541
1833
  threshold: options.threshold
1542
1834
  }),
1543
1835
  period,
1544
- scope: options.campaign ?? "workspace",
1836
+ scope: options.campaign === null ? "workspace" : refOf(context.outbound, options.campaign),
1545
1837
  threshold: options.threshold
1546
1838
  };
1547
1839
  return answer;
@@ -1549,7 +1841,7 @@ var anomalies = defineInsight({
1549
1841
  });
1550
1842
 
1551
1843
  // src/insights/ops/campaign-diagnosis.ts
1552
- import { z as z9 } from "zod";
1844
+ import { z as z10 } from "zod";
1553
1845
 
1554
1846
  // src/insights/ops/diagnosis-checks.ts
1555
1847
  var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
@@ -1566,14 +1858,14 @@ var volume = (facts, limits) => {
1566
1858
  ];
1567
1859
  };
1568
1860
  var bounces = (facts, limits) => {
1569
- const { count, high, low, of, rate: rate2 } = facts.rates.bounceRate;
1861
+ const { count: count2, high, low, of, rate: rate2 } = facts.rates.bounceRate;
1570
1862
  return !enough(facts, limits) || rate2 === null || rate2 <= limits.maxBounceRate ? [] : [
1571
1863
  {
1572
1864
  code: "high_bounce_rate",
1573
- finding: `Bounce rate is ${percent(rate2)} (${count} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
1865
+ finding: `Bounce rate is ${percent(rate2)} (${count2} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
1574
1866
  next: "Use bounce_watch to find the senders behind it, and verify the lead list.",
1575
1867
  numbers: {
1576
- bounced: count,
1868
+ bounced: count2,
1577
1869
  high,
1578
1870
  limit: limits.maxBounceRate,
1579
1871
  low,
@@ -1585,7 +1877,7 @@ var bounces = (facts, limits) => {
1585
1877
  ];
1586
1878
  };
1587
1879
  var replies = (facts, limits) => {
1588
- const { count, high, low, of, rate: rate2 } = facts.rates.replyRate;
1880
+ const { count: count2, high, low, of, rate: rate2 } = facts.rates.replyRate;
1589
1881
  if (!enough(facts, limits) || rate2 === null || rate2 >= limits.minReplyRate) {
1590
1882
  return [];
1591
1883
  }
@@ -1593,14 +1885,14 @@ var replies = (facts, limits) => {
1593
1885
  return [
1594
1886
  {
1595
1887
  code: "low_reply_rate",
1596
- finding: `Reply rate is ${percent(rate2)} (${count} of ${of}), under the ${percent(limits.minReplyRate)} floor. The 95% interval is ${percent(low)} to ${percent(high)}, ${clearly ? "so it is below the floor beyond chance" : "which still reaches the floor, so more sends are needed to be sure"}.`,
1888
+ finding: `Reply rate is ${percent(rate2)} (${count2} of ${of}), under the ${percent(limits.minReplyRate)} floor. The 95% interval is ${percent(low)} to ${percent(high)}, ${clearly ? "so it is below the floor beyond chance" : "which still reaches the floor, so more sends are needed to be sure"}.`,
1597
1889
  next: "Use step_funnel and copy_audit to see where replies are lost.",
1598
1890
  numbers: {
1599
1891
  floor: limits.minReplyRate,
1600
1892
  high,
1601
1893
  low,
1602
1894
  rate: rate2,
1603
- replied: count,
1895
+ replied: count2,
1604
1896
  sample: of
1605
1897
  },
1606
1898
  severity: clearly ? "high" : "medium"
@@ -1668,7 +1960,7 @@ var senders = (facts) => {
1668
1960
  return inactive.length === 0 ? [] : [
1669
1961
  {
1670
1962
  code: "inactive_sender",
1671
- finding: `${inactive.length} of ${all.length} senders are not active: ${inactive.map(
1963
+ finding: `${inactive.length} of ${plural(all.length, "sender")} ${noun(inactive.length, "is", "are")} not active: ${inactive.map(
1672
1964
  (sender) => `${sender.address ?? sender.name ?? sender.ref} (${sender.status})`
1673
1965
  ).join(", ")}.`,
1674
1966
  next: "Reconnect or replace them; warmup_readiness shows which mailboxes are fit to send.",
@@ -1710,10 +2002,10 @@ var schedule = ({ recent, settings }, limits) => {
1710
2002
  const average = recent === null || recent.sent === null || recent.daysWithData === 0 ? null : round(recent.sent / recent.daysWithData);
1711
2003
  const reasons = [
1712
2004
  ...hours !== null && hours < limits.minWeeklyHours ? [
1713
- `The sending windows are open ${hours} hours a week, under ${limits.minWeeklyHours}.`
2005
+ `The sending windows are open ${spoken(hours)} hours a week, under ${limits.minWeeklyHours}.`
1714
2006
  ] : [],
1715
2007
  ...settings.dailyLimit !== null && average !== null && average >= settings.dailyLimit * limits.dailyLimitShare ? [
1716
- `Recent sending days average ${average} sends against a daily limit of ${settings.dailyLimit}, so the limit is what holds volume back.`
2008
+ `Recent sending days average ${spoken(average)} sends against a daily limit of ${settings.dailyLimit}, so the limit is what holds volume back.`
1717
2009
  ] : []
1718
2010
  ];
1719
2011
  return reasons.length === 0 ? [] : [
@@ -1752,10 +2044,14 @@ var unknownRates = (facts) => [
1752
2044
  ];
1753
2045
 
1754
2046
  // src/insights/ops/campaign-diagnosis.ts
1755
- var share = (fallback, text) => z9.number().min(0).max(1).default(fallback).describe(text);
1756
- var input7 = z9.object({
2047
+ var share = (fallback, text) => z10.number().min(0).max(1).default(fallback).describe(text);
2048
+ var recentDays = z10.number().int().min(1).max(30);
2049
+ var input7 = z10.object({
1757
2050
  ...rangeFields,
1758
- campaign: z9.string().min(3).describe("The campaign's ref"),
2051
+ campaign: z10.string().min(3).describe("The campaign's ref"),
2052
+ days: recentDays.default(7).describe(
2053
+ "The days, ending yesterday, held against the same number before"
2054
+ ),
1759
2055
  daily_limit_share: share(
1760
2056
  0.9,
1761
2057
  "Average daily sends at or over this share of the daily limit mean the limit holds volume back"
@@ -1765,17 +2061,15 @@ var input7 = z9.object({
1765
2061
  0.3,
1766
2062
  "A fall in sends, recent days against the days before, over this share is a finding"
1767
2063
  ),
1768
- max_senders: z9.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2064
+ max_senders: z10.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
1769
2065
  min_positive_share: share(
1770
2066
  0.2,
1771
2067
  "A share of replies that are positive under this is a finding"
1772
2068
  ),
1773
2069
  min_reply_rate: share(0.01, "A reply rate under this is a finding"),
1774
- min_sent: z9.number().int().min(0).default(100).describe("Under this many sends, rates are not judged"),
1775
- min_weekly_hours: z9.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
1776
- recent_days: z9.number().int().min(1).max(30).default(7).describe(
1777
- "The days, ending yesterday, held against the same number before"
1778
- )
2070
+ min_sent: z10.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2071
+ min_weekly_hours: z10.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
2072
+ recent_days: renamed("days", recentDays)
1779
2073
  });
1780
2074
  var readRecent = async (context, campaign, days) => {
1781
2075
  const recent = lastDays(context.now, days);
@@ -1817,11 +2111,11 @@ var readExtras = async (context, campaign, options) => {
1817
2111
  const senders2 = unless(
1818
2112
  !capabilities["senders.byCampaign"],
1819
2113
  "Sender status: the adapter cannot list a campaign's senders."
1820
- ) ? await readUpTo(
1821
- context,
1822
- (max) => handle.senders.listAll({ max }),
1823
- options.maxSenders
1824
- ) : null;
2114
+ ) ? await readCapped(context, (max) => handle.senders.listAll({ max }), {
2115
+ input: "max_senders",
2116
+ max: options.maxSenders,
2117
+ what: "senders"
2118
+ }) : null;
1825
2119
  const recent = unless(
1826
2120
  capabilities["stats.byDay"] === false,
1827
2121
  "Recent sending trend: the adapter has no stats by day."
@@ -1852,7 +2146,7 @@ var campaignDiagnosis = defineInsight({
1852
2146
  const counts = await readTotals(context, campaign.ref, options);
1853
2147
  const extras = await readExtras(context, campaign.ref, {
1854
2148
  maxSenders: options.max_senders,
1855
- recentDays: options.recent_days
2149
+ recentDays: options.days
1856
2150
  });
1857
2151
  const facts = {
1858
2152
  ...extras,
@@ -1884,34 +2178,35 @@ var campaignDiagnosis = defineInsight({
1884
2178
  });
1885
2179
 
1886
2180
  // src/insights/ops/campaign-ranking.ts
1887
- import { z as z10 } from "zod";
1888
- var metricSchema2 = z10.enum([
2181
+ import { z as z11 } from "zod";
2182
+ var metricSchema2 = z11.enum([
1889
2183
  "reply_rate",
1890
2184
  "positive_reply_rate",
1891
2185
  "bounce_rate"
1892
2186
  ]);
1893
- var input8 = z10.object({
2187
+ var input8 = z11.object({
1894
2188
  ...rangeFields,
1895
2189
  ...listFields("one stats request"),
1896
2190
  metric: metricSchema2.default("reply_rate").describe("The rate to rank by. For bounce_rate, lower is better."),
1897
- min_sent: z10.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2191
+ min_sent: z11.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
1898
2192
  });
1899
- var measured = (counts, metric) => {
1900
- const rates = ratesOf(counts);
2193
+ var measured = (counts, metric, basis) => {
2194
+ const rates = ratesOf(counts, baseIn2(basis));
1901
2195
  if (metric === "bounce_rate") {
1902
2196
  return rates.bounceRate;
1903
2197
  }
1904
2198
  return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
1905
2199
  };
1906
2200
  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);
1907
- var rankCampaigns = (entries, metric, minSent) => {
2201
+ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
1908
2202
  const scored = [];
1909
2203
  const tooFewSends = [];
1910
2204
  const unknown = [];
1911
2205
  for (const { campaign, counts } of entries) {
1912
2206
  const label = labelOf(campaign);
1913
2207
  const volume2 = volumeOf(counts);
1914
- const result = measured(counts, metric);
2208
+ const basis = metric === "bounce_rate" ? "sent" : replyBasis ?? perLeadBasis(counts);
2209
+ const result = measured(counts, metric, basis);
1915
2210
  if (volume2 === null) {
1916
2211
  unknown.push({
1917
2212
  ...label,
@@ -1931,7 +2226,7 @@ var rankCampaigns = (entries, metric, minSent) => {
1931
2226
  sent: volume2
1932
2227
  });
1933
2228
  } else {
1934
- scored.push({ ...label, ...result, sent: volume2 });
2229
+ scored.push({ ...label, ...result, basis, sent: counts.sent });
1935
2230
  }
1936
2231
  }
1937
2232
  const ranked = scored.toSorted(order(metric)).map((entry, index) => ({ ...entry, rank: index + 1 }));
@@ -1956,9 +2251,10 @@ var campaignRanking = defineInsight({
1956
2251
  needs: ["stats.campaign"],
1957
2252
  next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
1958
2253
  run: async (context, options) => {
1959
- const entries = await readCampaignTotals(context, options);
2254
+ const { entries, read } = await readCampaignTotals(context, options);
1960
2255
  const ranking = {
1961
2256
  ...rankCampaigns(entries, options.metric, options.min_sent),
2257
+ ...read,
1962
2258
  better: options.metric === "bounce_rate" ? "lower" : "higher",
1963
2259
  metric: options.metric,
1964
2260
  period: { from: options.from, to: options.to }
@@ -1968,11 +2264,11 @@ var campaignRanking = defineInsight({
1968
2264
  });
1969
2265
 
1970
2266
  // src/insights/ops/channel-mix.ts
1971
- import { z as z11 } from "zod";
1972
- var input9 = z11.object({
2267
+ import { z as z12 } from "zod";
2268
+ var input9 = z12.object({
1973
2269
  ...rangeFields,
1974
2270
  ...listFields("one stats request"),
1975
- alpha: z11.number().gt(0).lt(1).default(0.05).describe(
2271
+ alpha: z12.number().gt(0).lt(1).default(0.05).describe(
1976
2272
  "The p-value under which a difference counts as more than chance"
1977
2273
  )
1978
2274
  });
@@ -2060,7 +2356,7 @@ var channelMix = defineInsight({
2060
2356
  needs: ["stats.campaign"],
2061
2357
  next: "Use campaign_ranking to see which campaigns carry the better channel.",
2062
2358
  run: async (context, options) => {
2063
- const entries = await readCampaignTotals(context, options);
2359
+ const { entries, read } = await readCampaignTotals(context, options);
2064
2360
  const channels = byChannel(entries);
2065
2361
  const providers = byProvider(entries);
2066
2362
  for (const { group, partial } of channels) {
@@ -2076,6 +2372,7 @@ var channelMix = defineInsight({
2076
2372
  }
2077
2373
  }
2078
2374
  const mix = {
2375
+ ...read,
2079
2376
  ...compare(
2080
2377
  channels.map((each) => each.group),
2081
2378
  options.alpha
@@ -2089,15 +2386,15 @@ var channelMix = defineInsight({
2089
2386
  });
2090
2387
 
2091
2388
  // src/insights/ops/client-report.ts
2092
- import { z as z14 } from "zod";
2389
+ import { z as z15 } from "zod";
2093
2390
 
2094
2391
  // src/insights/ops/period-comparison.ts
2095
- import { z as z12 } from "zod";
2096
- var input10 = z12.object({
2392
+ import { z as z13 } from "zod";
2393
+ var input10 = z13.object({
2097
2394
  ...listFields("two stats requests"),
2098
- alpha: z12.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2099
- days: z12.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2100
- min_sent: z12.number().int().min(0).default(50).describe(
2395
+ alpha: z13.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2396
+ days: z13.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2397
+ min_sent: z13.number().int().min(0).default(50).describe(
2101
2398
  "A campaign under this many sends in either period is listed apart"
2102
2399
  )
2103
2400
  });
@@ -2127,7 +2424,7 @@ var verdictOf = (test) => {
2127
2424
  }
2128
2425
  return test.z > 0 ? "up" : "down";
2129
2426
  };
2130
- var compare2 = (current, previous, alpha) => {
2427
+ var compare2 = (current, previous, basis, alpha) => {
2131
2428
  const now = current.rates.replyRate;
2132
2429
  const before = previous.rates.replyRate;
2133
2430
  const test = compareRates(
@@ -2135,30 +2432,39 @@ var compare2 = (current, previous, alpha) => {
2135
2432
  { successes: before.count, trials: before.of },
2136
2433
  alpha
2137
2434
  );
2138
- const moved = `Reply rate went from ${percent(before.rate)} to ${percent(now.rate)}`;
2435
+ const rateName = RATE_WORDS[basis];
2436
+ const moved = `${rateName} went from ${percent(before.rate)} to ${percent(now.rate)}`;
2139
2437
  const numbers = numbersOf(current.counts, current.rates);
2140
2438
  const earlier = numbersOf(previous.counts, previous.rates);
2141
2439
  return {
2142
2440
  change: changeOf(numbers, earlier),
2143
2441
  current: numbers,
2144
- finding: test === null ? "Reply rate cannot be compared: a period has no reply or volume counts, or neither has a reply." : `${moved}; ${test.significant ? "more than chance" : "within what chance would give"} (${pText(test.pValue)}).`,
2442
+ finding: test === null ? `${rateName} cannot be compared: a period has no reply count or nothing to divide it by, or neither has a reply.` : `${moved}; ${test.significant ? "more than chance" : "within what chance would give"} (${pText(test.pValue)}).`,
2145
2443
  previous: earlier,
2444
+ replyRateBasis: basis,
2146
2445
  replyRateTest: test,
2147
2446
  verdict: verdictOf(test)
2148
2447
  };
2149
2448
  };
2150
- var comparePeriods = (current, previous, alpha) => compare2(
2151
- { counts: current, rates: ratesOf(current) },
2152
- { counts: previous, rates: ratesOf(previous) },
2153
- alpha
2154
- );
2449
+ var comparePeriods = (current, previous, alpha) => {
2450
+ const basis = periodBasis(current, previous);
2451
+ return compare2(
2452
+ { counts: current, rates: ratesOf(current, baseIn2(basis)) },
2453
+ { counts: previous, rates: ratesOf(previous, baseIn2(basis)) },
2454
+ basis,
2455
+ alpha
2456
+ );
2457
+ };
2155
2458
  var compareAcross = (current, previous, alpha) => {
2156
- const now = ratesAcross(current);
2157
- const before = ratesAcross(previous);
2459
+ const counts = [sumCounts(current), sumCounts(previous)];
2460
+ const basis = periodBasis(...counts);
2461
+ const now = ratesAcross(current, baseIn2(basis));
2462
+ const before = ratesAcross(previous, baseIn2(basis));
2158
2463
  return {
2159
2464
  comparison: compare2(
2160
- { counts: sumCounts(current), rates: now.rates },
2161
- { counts: sumCounts(previous), rates: before.rates },
2465
+ { counts: counts[0], rates: now.rates },
2466
+ { counts: counts[1], rates: before.rates },
2467
+ basis,
2162
2468
  alpha
2163
2469
  ),
2164
2470
  partial: [
@@ -2170,13 +2476,13 @@ var compareAcross = (current, previous, alpha) => {
2170
2476
  var readPeriods = async (context, options) => {
2171
2477
  const current = lastDays(context.now, options.days);
2172
2478
  const previous = lastDays(context.now, options.days, 1);
2173
- const found = await readCampaigns(
2479
+ const listed = await readCampaignsIn(
2174
2480
  context,
2175
2481
  options.statuses,
2176
2482
  options.max_campaigns
2177
2483
  );
2178
2484
  const campaigns = await mapConcurrent(
2179
- found,
2485
+ listed.items,
2180
2486
  async (campaign) => {
2181
2487
  const [now, before] = await Promise.all([
2182
2488
  readTotals(context, campaign.ref, current),
@@ -2185,7 +2491,7 @@ var readPeriods = async (context, options) => {
2185
2491
  return { campaign, current: now, previous: before };
2186
2492
  }
2187
2493
  );
2188
- return { campaigns, current, previous };
2494
+ return { campaigns, current, previous, read: campaignsReadOf(listed) };
2189
2495
  };
2190
2496
  var totalOf = (campaigns, alpha) => compareAcross(
2191
2497
  campaigns.map((entry) => entry.current),
@@ -2216,7 +2522,7 @@ var workspaceOf = async (context, periods, alpha) => {
2216
2522
  );
2217
2523
  };
2218
2524
  var periodComparison = defineInsight({
2219
- 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 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. 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.",
2525
+ 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.",
2220
2526
  inputSchema: input10,
2221
2527
  key: "periodComparison",
2222
2528
  name: "period_comparison",
@@ -2242,6 +2548,7 @@ var periodComparison = defineInsight({
2242
2548
  }
2243
2549
  }
2244
2550
  const comparison = {
2551
+ ...periods.read,
2245
2552
  campaigns: campaigns.toSorted(
2246
2553
  (left, right) => descending(
2247
2554
  left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
@@ -2264,11 +2571,11 @@ var periodComparison = defineInsight({
2264
2571
  });
2265
2572
 
2266
2573
  // src/insights/ops/pipeline-forecast.ts
2267
- import { z as z13 } from "zod";
2268
- var input11 = z13.object({
2269
- campaign: z13.string().min(3).describe("The campaign's ref"),
2270
- days: z13.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2271
- max_leads: z13.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2574
+ import { z as z14 } from "zod";
2575
+ var input11 = z14.object({
2576
+ campaign: z14.string().min(3).describe("The campaign's ref"),
2577
+ days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2578
+ max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2272
2579
  });
2273
2580
  var countStatuses = (leads) => {
2274
2581
  const counts = {
@@ -2311,17 +2618,41 @@ var ASSUMPTIONS = [
2311
2618
  "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
2312
2619
  "The daily pace stays what it was over the recent days. Days with no report count as no sends."
2313
2620
  ];
2314
- var describe2 = (remaining, complete, forecast) => {
2315
- const leads = `${complete ? "" : "At least "}${remaining} leads remain`;
2316
- return forecast.expected === null ? `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.` : `${leads}; expect about ${forecast.expected} replies (between ${forecast.low} and ${forecast.high}). This is an estimate.`;
2621
+ var daysLeftOf = (byStatus, complete, pace) => {
2622
+ const remaining = byStatus.active;
2623
+ if (remaining === 0) {
2624
+ return complete && byStatus.unknown === 0 ? 0 : null;
2625
+ }
2626
+ return pace === null || pace <= 0 ? null : round(remaining / pace);
2627
+ };
2628
+ var describe2 = ({ complete, daysLeft, remaining }, forecast) => {
2629
+ if (daysLeft === 0) {
2630
+ return "No leads are left to contact; add leads to keep the campaign sending.";
2631
+ }
2632
+ const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
2633
+ if (forecast.expected === null) {
2634
+ return `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.`;
2635
+ }
2636
+ const [expected, low, high] = [
2637
+ forecast.expected,
2638
+ forecast.low,
2639
+ forecast.high
2640
+ ].map((value) => spoken(value));
2641
+ const range = low === high ? "" : ` (between ${low} and ${high})`;
2642
+ return `${leads}; expect about ${expected} ${noun(Number(expected), "reply", "replies")}${range}. This is an estimate.`;
2317
2643
  };
2318
2644
  var forecastCampaign = async (context, campaign, options) => {
2319
2645
  const handle = context.outbound.campaign(campaign.ref);
2320
- const { complete, items: leads } = await readUpTo(
2646
+ const { capped: capped2, items: leads } = await readCapped(
2321
2647
  context,
2322
2648
  (max) => handle.leads.listAll({ max }),
2323
- options.maxLeads
2649
+ {
2650
+ input: options.leadsInput,
2651
+ max: options.maxLeads,
2652
+ what: options.leadsWhat
2653
+ }
2324
2654
  );
2655
+ const complete = !capped2;
2325
2656
  const byStatus = countStatuses(leads);
2326
2657
  const remaining = byStatus.active;
2327
2658
  const rates = ratesOf(
@@ -2329,19 +2660,20 @@ var forecastCampaign = async (context, campaign, options) => {
2329
2660
  );
2330
2661
  const pace = await paceOf(context, campaign.ref, options.days);
2331
2662
  const expectedReplies = project(remaining, rates.replyRate);
2663
+ const daysLeft = daysLeftOf(byStatus, complete, pace);
2332
2664
  return {
2333
2665
  ...labelOf(campaign),
2334
2666
  assumptions: [
2335
2667
  ...ASSUMPTIONS,
2336
- `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count ?? "unknown"} replies over ${rates.replyRate.of ?? "unknown"}.`
2668
+ `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count === null ? "an unknown number of replies" : plural(rates.replyRate.count, "reply", "replies")} over ${rates.replyRate.of ?? "unknown"}.`
2337
2669
  ],
2338
2670
  byStatus,
2339
2671
  dailyContactRate: pace,
2340
- daysLeft: pace === null || pace <= 0 ? null : round(remaining / pace),
2672
+ daysLeft,
2341
2673
  estimate: true,
2342
2674
  expectedPositive: project(remaining, rates.positiveRate),
2343
2675
  expectedReplies,
2344
- finding: describe2(remaining, complete, expectedReplies),
2676
+ finding: describe2({ complete, daysLeft, remaining }, expectedReplies),
2345
2677
  leadsComplete: complete,
2346
2678
  leadsRead: leads.length,
2347
2679
  positiveRate: rates.positiveRate,
@@ -2362,32 +2694,54 @@ var pipelineForecast = defineInsight({
2362
2694
  );
2363
2695
  return await forecastCampaign(context, campaign, {
2364
2696
  days: options.days,
2697
+ leadsInput: "max_leads",
2698
+ leadsWhat: "leads",
2365
2699
  maxLeads: options.max_leads
2366
2700
  });
2367
2701
  }
2368
2702
  });
2369
2703
 
2370
2704
  // src/insights/ops/client-report.ts
2371
- var input12 = z14.object({
2705
+ var limit2 = z15.number().int().min(1).max(20);
2706
+ var input12 = z15.object({
2372
2707
  ...listFields(
2373
2708
  "two stats requests, and three more plus its leads when active"
2374
2709
  ),
2375
- alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2376
- anomaly_threshold: z14.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2377
- baseline_days: z14.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2378
- days: z14.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2379
- max_bounce_rate: z14.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2380
- max_leads_per_campaign: z14.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2381
- min_baseline_points: z14.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2382
- min_sent: z14.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2383
- runway_days: z14.number().min(0).default(7).describe(
2710
+ alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2711
+ anomaly_threshold: z15.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2712
+ baseline_days: z15.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2713
+ days: z15.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2714
+ limit: limit2.default(3).describe("How many best and worst campaigns to show"),
2715
+ max_bounce_rate: z15.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2716
+ 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"),
2717
+ min_baseline_points: z15.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2718
+ min_sent: z15.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2719
+ runway_days: z15.number().min(0).default(7).describe(
2384
2720
  "A campaign with this many days of leads left or fewer is flagged"
2385
2721
  ),
2386
- top: z14.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show")
2722
+ top: renamed("limit", limit2)
2387
2723
  });
2724
+ var sendingLeft = (daysLeft) => {
2725
+ if (daysLeft !== null && daysLeft < 0.05) {
2726
+ return "less than a day of sending";
2727
+ }
2728
+ const days = spoken(daysLeft);
2729
+ return `about ${days} ${days === "1" ? "day" : "days"} of sending`;
2730
+ };
2388
2731
  var bounceProblems = (campaigns, options) => campaigns.flatMap(({ campaign, current }) => {
2389
- const { count, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
2390
- return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [{ ...labelOf(campaign), bounced: count, high, low, rate: rate2, sent: of }] : [];
2732
+ const { count: count2, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
2733
+ return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [
2734
+ {
2735
+ ...labelOf(campaign),
2736
+ bounced: count2,
2737
+ count: count2,
2738
+ high,
2739
+ low,
2740
+ of,
2741
+ rate: rate2,
2742
+ sent: of
2743
+ }
2744
+ ] : [];
2391
2745
  }).toSorted((left, right) => right.rate - left.rate);
2392
2746
  var readAnomalies = async (context, period, options) => {
2393
2747
  const { capabilities } = context.outbound;
@@ -2420,6 +2774,8 @@ var readRunways = async (context, campaigns, options) => {
2420
2774
  campaign,
2421
2775
  forecast: await forecastCampaign(context, campaign, {
2422
2776
  days: options.days,
2777
+ leadsInput: "max_leads_per_campaign",
2778
+ leadsWhat: "leads of a campaign",
2423
2779
  maxLeads: options.max_leads_per_campaign
2424
2780
  })
2425
2781
  }));
@@ -2437,25 +2793,26 @@ var readRunways = async (context, campaigns, options) => {
2437
2793
  };
2438
2794
  var actionsOf = (report) => {
2439
2795
  const [worst] = report.bottom;
2440
- const { current, previous } = report.totals;
2796
+ const { current, previous, replyRateBasis } = report.totals;
2797
+ const perWhat = RATE_WORDS[replyRateBasis].toLowerCase();
2441
2798
  return [
2442
2799
  ...report.bounceProblems.map((problem) => ({
2443
- action: `Fix the bounces of ${problem.name}: its bounce rate is ${percent(problem.rate)} (${problem.bounced} of ${problem.sent} sends).`,
2800
+ action: `Fix the bounces of ${problem.campaignName}: its bounce rate is ${percent(problem.rate)} (${problem.count} of ${problem.of} sends).`,
2444
2801
  campaign: problem.campaign,
2445
- campaignName: problem.name,
2802
+ campaignName: problem.campaignName,
2446
2803
  kind: "fix_bounces",
2447
2804
  number: problem.rate
2448
2805
  })),
2449
2806
  ...(report.runningOutOfLeads ?? []).map((runway) => ({
2450
- action: `Add leads to ${runway.name}: ${runway.remaining} leads remain, about ${runway.daysLeft} days of sending.`,
2807
+ action: runway.remaining === 0 ? `Add leads to ${runway.campaignName}: no leads are left to contact, so it is not sending.` : `Add leads to ${runway.campaignName}: ${runway.remaining} ${runway.remaining === 1 ? "lead remains" : "leads remain"}, ${sendingLeft(runway.daysLeft)}.`,
2451
2808
  campaign: runway.campaign,
2452
- campaignName: runway.name,
2809
+ campaignName: runway.campaignName,
2453
2810
  kind: "add_leads",
2454
2811
  number: runway.daysLeft
2455
2812
  })),
2456
2813
  ...report.totals.verdict === "down" ? [
2457
2814
  {
2458
- action: `Find out what changed: the reply rate fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
2815
+ action: `Find out what changed: ${perWhat} fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
2459
2816
  campaign: null,
2460
2817
  campaignName: null,
2461
2818
  kind: "reply_rate_fell",
@@ -2464,9 +2821,9 @@ var actionsOf = (report) => {
2464
2821
  ] : [],
2465
2822
  ...worst === void 0 ? [] : [
2466
2823
  {
2467
- action: `Review the copy and the audience of ${worst.name}: it has the weakest reply rate, ${percent(worst.rate)} (${worst.count} of ${worst.of}).`,
2824
+ action: `Review the copy and the audience of ${worst.campaignName}: it has the fewest ${perWhat}, ${percent(worst.rate)} (${worst.count} of ${worst.of}).`,
2468
2825
  campaign: worst.campaign,
2469
- campaignName: worst.name,
2826
+ campaignName: worst.campaignName,
2470
2827
  kind: "review_campaign",
2471
2828
  number: worst.rate
2472
2829
  }
@@ -2481,32 +2838,34 @@ var actionsOf = (report) => {
2481
2838
  ];
2482
2839
  };
2483
2840
  var clientReport = defineInsight({
2484
- 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 reply rate interval, 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. 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.",
2841
+ 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.",
2485
2842
  inputSchema: input12,
2486
2843
  key: "clientReport",
2487
2844
  name: "client_report",
2488
2845
  needs: ["stats.campaign"],
2489
- next: "Use campaign_diagnosis on a campaign an action item names, or period_comparison for every campaign's change.",
2846
+ next: "Use campaign_diagnosis on a campaign an action item names, with from and to set to this report's `period`, or period_comparison for every campaign's change.",
2490
2847
  run: async (context, options) => {
2491
2848
  const periods = await readPeriods(context, options);
2849
+ const totals = noted(
2850
+ context,
2851
+ "Totals",
2852
+ totalOf(periods.campaigns, options.alpha)
2853
+ );
2492
2854
  const ranking = rankCampaigns(
2493
2855
  periods.campaigns.map((entry) => ({
2494
2856
  campaign: entry.campaign,
2495
2857
  counts: entry.current
2496
2858
  })),
2497
2859
  "reply_rate",
2498
- options.min_sent
2860
+ options.min_sent,
2861
+ totals.replyRateBasis
2499
2862
  );
2500
2863
  const sections = {
2501
2864
  anomalies: await readAnomalies(context, periods.current, options),
2502
- bottom: ranking.ranked.slice(options.top).slice(-options.top).toReversed(),
2865
+ bottom: ranking.ranked.slice(options.limit).slice(-options.limit).toReversed(),
2503
2866
  bounceProblems: bounceProblems(periods.campaigns, options),
2504
2867
  runningOutOfLeads: await readRunways(context, periods.campaigns, options),
2505
- totals: noted(
2506
- context,
2507
- "Totals",
2508
- totalOf(periods.campaigns, options.alpha)
2509
- )
2868
+ totals
2510
2869
  };
2511
2870
  const leftOut = [
2512
2871
  ...sections.anomalies === null ? ["Unusual days: the adapter has no workspace stats by day."] : [],
@@ -2519,24 +2878,26 @@ var clientReport = defineInsight({
2519
2878
  }
2520
2879
  const report = {
2521
2880
  ...sections,
2881
+ ...periods.read,
2522
2882
  actions: actionsOf(sections),
2523
2883
  campaigns: periods.campaigns.length,
2524
2884
  days: options.days,
2525
2885
  leftOut,
2526
2886
  period: periods.current,
2527
2887
  previousPeriod: periods.previous,
2528
- top: ranking.ranked.slice(0, options.top)
2888
+ replyRateBasis: totals.replyRateBasis,
2889
+ top: ranking.ranked.slice(0, options.limit)
2529
2890
  };
2530
2891
  return report;
2531
2892
  }
2532
2893
  });
2533
2894
 
2534
2895
  // src/insights/ops/tag-rollup.ts
2535
- import { z as z15 } from "zod";
2536
- var input13 = z15.object({
2896
+ import { z as z16 } from "zod";
2897
+ var input13 = z16.object({
2537
2898
  ...rangeFields,
2538
2899
  ...listFields("one stats request"),
2539
- min_sent: z15.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
2900
+ min_sent: z16.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
2540
2901
  });
2541
2902
  var groupOf2 = (tag, entries) => {
2542
2903
  const counts = entries.map((entry) => entry.counts);
@@ -2556,11 +2917,15 @@ var tagRollup = defineInsight({
2556
2917
  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).",
2557
2918
  inputSchema: input13,
2558
2919
  key: "tagRollup",
2920
+ // A tool whose campaigns carry no tags would put every campaign under one
2921
+ // null tag, which reads as an answer. On a combined instance one tool with
2922
+ // tags is enough.
2923
+ lacks: (outbound) => outbound.fields.campaign["tags"] === false ? "campaign tags" : null,
2559
2924
  name: "tag_rollup",
2560
2925
  needs: ["stats.campaign"],
2561
2926
  next: "Use campaign_ranking to see the campaigns inside the best and the worst tag.",
2562
2927
  run: async (context, options) => {
2563
- const entries = await readCampaignTotals(context, options);
2928
+ const { entries, read } = await readCampaignTotals(context, options);
2564
2929
  const members = /* @__PURE__ */ new Map();
2565
2930
  for (const entry of entries) {
2566
2931
  const tags = entry.campaign.tags.length === 0 ? [null] : entry.campaign.tags;
@@ -2584,6 +2949,7 @@ var tagRollup = defineInsight({
2584
2949
  );
2585
2950
  const enough2 = (group) => (volumeOf(group) ?? 0) >= options.min_sent;
2586
2951
  const rollup = {
2952
+ ...read,
2587
2953
  campaigns: entries.length,
2588
2954
  period: { from: options.from, to: options.to },
2589
2955
  tags: groups.filter(enough2),
@@ -2606,47 +2972,44 @@ var OPS_INSIGHTS = [
2606
2972
  ];
2607
2973
 
2608
2974
  // src/insights/people/account-summary.ts
2609
- import { z as z17 } from "zod";
2975
+ import { z as z18 } from "zod";
2610
2976
 
2611
2977
  // src/insights/people/read.ts
2612
- import { z as z16 } from "zod";
2613
- var readCapped2 = (context, open, max, what) => context.all(open(max), `${max} ${what}`);
2614
- var statusesField = z16.array(campaignStatusSchema).min(1).default(["active"]).describe("Campaign statuses to consider, for example active or paused");
2615
- var campaignsIn2 = async (context, statuses, max) => {
2616
- const { outbound } = context;
2617
- const wanted = [...new Set(statuses)];
2618
- if (outbound.capabilities["campaigns.status"] === false) {
2619
- const every = await readCapped2(
2620
- context,
2621
- (cap) => outbound.campaigns.listAll({ max: cap }),
2622
- max,
2623
- "campaigns"
2978
+ import { z as z17 } from "zod";
2979
+ var readCappedFlag = (context, open, max, what, input27) => readCapped(context, open, { input: input27, max, what });
2980
+ var readByRef = async (context, refs, read, what, effect) => {
2981
+ if (refs.length === 0) {
2982
+ return /* @__PURE__ */ new Map();
2983
+ }
2984
+ const found = await read(refs);
2985
+ if (found.errors.length > 0) {
2986
+ context.note(
2987
+ `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
2624
2988
  );
2625
- return every.filter((campaign) => wanted.includes(campaign.status));
2626
2989
  }
2627
- const campaigns = [];
2628
- for (const status of wanted) {
2629
- const room = max - campaigns.length;
2630
- if (room <= 0) {
2631
- context.partial(`Stopped at ${max} campaigns; more may exist.`);
2632
- break;
2633
- }
2634
- const found = await readCapped2(
2635
- context,
2636
- (cap) => outbound.campaigns.listAll({ max: cap, status }),
2637
- room,
2638
- "campaigns"
2639
- );
2640
- campaigns.push(...found);
2990
+ const [costliest] = found.results.toSorted(
2991
+ (left, right) => right.value.meta.requests - left.value.meta.requests
2992
+ );
2993
+ if (costliest !== void 0) {
2994
+ context.one(costliest.value);
2641
2995
  }
2642
- return campaigns;
2996
+ return new Map(found.results.map(({ id, value }) => [id, value]));
2997
+ };
2998
+ var statusesField = statusesInput(["active"]);
2999
+ var campaignsIn = async (context, statuses, max) => {
3000
+ const { items } = await readCampaignsIn(context, statuses, max);
3001
+ return items;
3002
+ };
3003
+ var leadsOf = async (context, campaign, max, input27) => {
3004
+ const { items } = await readCappedFlag(
3005
+ context,
3006
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
3007
+ max,
3008
+ "leads of a campaign",
3009
+ input27
3010
+ );
3011
+ return items;
2643
3012
  };
2644
- var leadsOf = (context, campaign, max) => readCapped2(
2645
- context,
2646
- (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
2647
- max,
2648
- "leads of a campaign"
2649
- );
2650
3013
  var nameOf = (lead) => {
2651
3014
  const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
2652
3015
  return name === "" ? null : name;
@@ -2660,13 +3023,24 @@ var DEFAULT_POSITIVE_LABELS = [
2660
3023
  "Meeting Booked",
2661
3024
  "Meeting Completed"
2662
3025
  ];
2663
- var positiveLabelsField = z16.array(z16.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
3026
+ var positiveLabelsField = z17.array(z17.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
2664
3027
  "Vendor interest labels that count as interested, matched without regard to case"
2665
3028
  );
2666
3029
  var isPositive = (label, labels) => label === null ? null : labels.some(
2667
3030
  (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
2668
3031
  );
2669
3032
  var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
3033
+ var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
3034
+ var AUTOMATIC = /* @__PURE__ */ new Set([
3035
+ "bounce",
3036
+ "ooo"
3037
+ ]);
3038
+ 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.
3039
+ lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
3040
+ var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
3041
+ var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
3042
+ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
3043
+ var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
2670
3044
  var COUNTS = "no per-lead open, click or reply counts";
2671
3045
  var noteEngagement = (context, leads, effect) => {
2672
3046
  const { outbound } = context;
@@ -2689,17 +3063,17 @@ var noteEngagement = (context, leads, effect) => {
2689
3063
  };
2690
3064
 
2691
3065
  // src/insights/people/account-summary.ts
2692
- var input14 = z17.object({
2693
- allow_free_domains: z17.boolean().default(false).describe(
3066
+ var input14 = z18.object({
3067
+ allow_free_domains: z18.boolean().default(false).describe(
2694
3068
  "Set to true to accept an email provider domain such as gmail.com, which is not one company"
2695
3069
  ),
2696
- domain: z17.string().min(3).describe(
3070
+ domain: z18.string().min(3).describe(
2697
3071
  "The company's domain, for example acme.com, or an email address whose domain is used"
2698
3072
  ),
2699
- max_campaigns: z17.number().int().min(1).max(200).default(20).describe(
3073
+ max_campaigns: z18.number().int().min(1).max(200).default(20).describe(
2700
3074
  "The most campaigns to read leads from when the tool cannot list every lead at once"
2701
3075
  ),
2702
- max_leads: z17.number().int().min(1).max(2e4).default(1e3).describe(
3076
+ max_leads: z18.number().int().min(1).max(2e4).default(1e3).describe(
2703
3077
  "The most leads to read in all. A vendor request returns about 50 to 100 leads."
2704
3078
  ),
2705
3079
  positive_labels: positiveLabelsField
@@ -2738,11 +3112,12 @@ var parseDomain = (text, provider) => {
2738
3112
  var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLeads }) => {
2739
3113
  const { outbound } = context;
2740
3114
  if (outbound.capabilities["leads.list"]) {
2741
- return await readCapped2(
3115
+ return await readCappedFlag(
2742
3116
  context,
2743
3117
  (cap) => outbound.leads.listAll({ max: cap }),
2744
3118
  maxLeads,
2745
- "leads"
3119
+ "leads",
3120
+ "max_leads"
2746
3121
  );
2747
3122
  }
2748
3123
  if (!outbound.capabilities["leads.byCampaign"]) {
@@ -2752,22 +3127,34 @@ var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLea
2752
3127
  { provider: outbound.provider }
2753
3128
  );
2754
3129
  }
2755
- const campaigns = await readCapped2(
3130
+ const campaigns = await readCappedFlag(
2756
3131
  context,
2757
3132
  (cap) => outbound.campaigns.listAll({ max: cap }),
2758
3133
  maxCampaigns,
2759
- "campaigns"
3134
+ "campaigns",
3135
+ "max_campaigns"
2760
3136
  );
2761
3137
  const leads = [];
2762
- for (const campaign of campaigns) {
3138
+ let { capped: capped2 } = campaigns;
3139
+ for (const campaign of campaigns.items) {
2763
3140
  if (leads.length >= maxLeads) {
2764
- context.partial(`Stopped at ${maxLeads} leads; more campaigns remain.`);
3141
+ context.partial(
3142
+ `Stopped at ${plural(maxLeads, "lead")} (max_leads); more campaigns remain.`
3143
+ );
3144
+ capped2 = true;
2765
3145
  break;
2766
3146
  }
2767
- const found = await leadsOf(context, campaign.ref, maxLeads - leads.length);
2768
- leads.push(...found);
3147
+ const found = await readCappedFlag(
3148
+ context,
3149
+ (cap) => outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
3150
+ maxLeads - leads.length,
3151
+ "leads of a campaign",
3152
+ "max_leads"
3153
+ );
3154
+ leads.push(...found.items);
3155
+ capped2 ||= found.capped;
2769
3156
  }
2770
- return leads;
3157
+ return { capped: capped2, items: leads };
2771
3158
  };
2772
3159
  var toRecord = (lead) => ({
2773
3160
  campaign: lead.campaignRef,
@@ -2779,11 +3166,13 @@ var toRecord = (lead) => ({
2779
3166
  opens: lead.engagement?.opens ?? null,
2780
3167
  provider: lead.provider,
2781
3168
  replies: lead.engagement?.replies ?? null,
3169
+ autoReplied: isAutoReplied(lead),
2782
3170
  status: lead.status
2783
3171
  });
2784
3172
  var latest = (times3) => times3.flatMap((time) => time === null ? [] : [time]).toSorted().at(-1) ?? null;
2785
3173
  var toPerson = (email, leads, labels) => {
2786
3174
  const records = leads.map(toRecord);
3175
+ const human = records.filter((record) => !record.autoReplied);
2787
3176
  const verdicts = leads.map((lead) => isPositive(lead.interest, labels));
2788
3177
  const pick = (read) => leads.map(read).find((value) => value !== null) ?? null;
2789
3178
  return {
@@ -2798,12 +3187,12 @@ var toPerson = (email, leads, labels) => {
2798
3187
  company: pick((lead) => lead.company),
2799
3188
  email,
2800
3189
  interested: verdicts.includes(true) ? true : verdicts.find((verdict) => verdict !== null) ?? null,
2801
- lastRepliedAt: latest(records.map((record) => record.lastRepliedAt)),
3190
+ lastRepliedAt: latest(human.map((record) => record.lastRepliedAt)),
2802
3191
  name: pick(nameOf),
2803
3192
  opens: total(records.map((record) => record.opens)),
2804
3193
  records,
2805
- replied: leads.some(hasReplied),
2806
- replies: total(records.map((record) => record.replies)),
3194
+ replied: leads.some(hasHumanReply),
3195
+ replies: total(human.map((record) => record.replies)),
2807
3196
  title: pick((lead) => lead.title)
2808
3197
  };
2809
3198
  };
@@ -2821,12 +3210,20 @@ var lastReplyOf = (people) => {
2821
3210
  };
2822
3211
  };
2823
3212
  var accountSummary = defineInsight({
2824
- 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. Costs one request per page of leads read (max_leads sets the ceiling); a count the vendor does not report is null.",
3213
+ 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.",
2825
3214
  inputSchema: input14,
2826
3215
  key: "accountSummary",
3216
+ // Every address is masked, so no lead's domain can be read. A hash keeps
3217
+ // exact matching but not the domain.
3218
+ maskedOut: ({ fields, strategy }) => {
3219
+ if (!fields.includes("email")) {
3220
+ return null;
3221
+ }
3222
+ return strategy === "hash" ? 'email addresses, whose domain it matches people by (under strategy "hash" too: a hashed address keeps no domain)' : "email addresses, whose domain it matches people by";
3223
+ },
2827
3224
  name: "account_summary",
2828
3225
  needs: [],
2829
- next: "Use person_summary with one person's email address for their full history, message by message.",
3226
+ next: "Use person_summary with one person's email address or lead ref for their full history, message by message.",
2830
3227
  run: async (context, values) => {
2831
3228
  const domain = parseDomain(values.domain, context.outbound.provider);
2832
3229
  if (FREE_DOMAINS.has(domain) && !values.allow_free_domains) {
@@ -2836,7 +3233,8 @@ var accountSummary = defineInsight({
2836
3233
  { provider: context.outbound.provider }
2837
3234
  );
2838
3235
  }
2839
- const leads = await readLeads(context, values);
3236
+ const read = await readLeads(context, values);
3237
+ const leads = read.items;
2840
3238
  noteEngagement(context, leads, "those are null");
2841
3239
  const byEmail = /* @__PURE__ */ new Map();
2842
3240
  for (const lead of leads) {
@@ -2856,6 +3254,7 @@ var accountSummary = defineInsight({
2856
3254
  interested: people.filter((person) => person.interested === true).length,
2857
3255
  leadsRead: leads.length,
2858
3256
  leadsWithoutEmail: leads.filter((lead) => lead.email === null).length,
3257
+ moreLeadsExist: read.capped,
2859
3258
  people: people.length,
2860
3259
  records: people.reduce((sum, each) => sum + each.records.length, 0),
2861
3260
  replied: people.filter((person) => person.replied).length
@@ -2866,24 +3265,25 @@ var accountSummary = defineInsight({
2866
3265
  });
2867
3266
 
2868
3267
  // src/insights/people/dropped-replies.ts
2869
- import { z as z18 } from "zod";
3268
+ import { z as z19 } from "zod";
2870
3269
  var HOUR = 36e5;
2871
3270
  var DAY = 24 * HOUR;
3271
+ var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
2872
3272
  var DEFAULT_DAYS = 14;
2873
- var input15 = z18.object({
2874
- categories: z18.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
3273
+ var input15 = z19.object({
3274
+ categories: z19.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
2875
3275
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
2876
3276
  ),
2877
- include_auto: z18.boolean().default(false).describe(
3277
+ include_auto: z19.boolean().default(false).describe(
2878
3278
  "Set to true to also check replies the vendor marks as automatic"
2879
3279
  ),
2880
- max_replies: z18.number().int().min(1).max(1e3).default(50).describe(
3280
+ max_replies: z19.number().int().min(1).max(1e3).default(50).describe(
2881
3281
  "The most replies to read. Each conversation among them costs one more request to check."
2882
3282
  ),
2883
- older_than_hours: z18.number().min(0).default(24).describe(
3283
+ older_than_hours: z19.number().min(0).default(24).describe(
2884
3284
  "A reply counts as dropped only after waiting this many hours without an answer"
2885
3285
  ),
2886
- since: z18.union([z18.iso.datetime({ offset: true }), z18.iso.date()]).nullable().default(null).describe(
3286
+ since: z19.union([z19.iso.datetime({ offset: true }), z19.iso.date()]).nullable().default(null).describe(
2887
3287
  "Only replies received at or after this ISO 8601 time. Null means 14 days before now."
2888
3288
  )
2889
3289
  });
@@ -2935,12 +3335,16 @@ var toDropped = (open, by, now) => {
2935
3335
  return [
2936
3336
  {
2937
3337
  campaign: first.campaignRef,
3338
+ campaignName: null,
2938
3339
  category: first.category,
2939
3340
  channel: first.channel,
2940
3341
  checkedBy: by,
2941
- finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${Math.floor(hoursWaiting)} hours with nothing sent after it.`,
3342
+ finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${waited(hoursWaiting)} with nothing sent after it.`,
2942
3343
  hoursWaiting,
3344
+ email: null,
2943
3345
  lead: first.leadRef,
3346
+ linkedinUrl: null,
3347
+ name: null,
2944
3348
  provider: first.provider,
2945
3349
  receivedAt: first.sentAt,
2946
3350
  reply: first.ref,
@@ -2949,6 +3353,52 @@ var toDropped = (open, by, now) => {
2949
3353
  }
2950
3354
  ];
2951
3355
  };
3356
+ var refsOf = (refs) => [
3357
+ ...new Set(refs.flatMap((ref) => ref === null ? [] : [ref]))
3358
+ ];
3359
+ var named2 = async (context, dropped) => {
3360
+ const { outbound } = context;
3361
+ const readLeads2 = outbound.capabilities["leads.get"];
3362
+ const leadRefs = readLeads2 ? refsOf(dropped.map((each) => each.lead)) : [];
3363
+ if (!readLeads2 && dropped.length > 0) {
3364
+ context.note(
3365
+ "This tool cannot read one lead (leads.get), so name, email and linkedinUrl are null."
3366
+ );
3367
+ }
3368
+ const unlinked = dropped.filter((each) => each.lead === null).length;
3369
+ if (unlinked > 0) {
3370
+ context.note(
3371
+ `${unlinked} dropped ${unlinked === 1 ? "reply carries" : "replies carry"} no lead ref, since the vendor does not tie a reply to its lead, so name, email and linkedinUrl are null there.`
3372
+ );
3373
+ }
3374
+ const [leads, campaigns] = await Promise.all([
3375
+ readByRef(
3376
+ context,
3377
+ leadRefs,
3378
+ (refs) => outbound.leads.getMany(refs),
3379
+ ["lead", "leads"],
3380
+ "names are null"
3381
+ ),
3382
+ readByRef(
3383
+ context,
3384
+ refsOf(dropped.map((each) => each.campaign)),
3385
+ (refs) => outbound.campaigns.getMany(refs),
3386
+ ["campaign", "campaigns"],
3387
+ "names are null"
3388
+ )
3389
+ ]);
3390
+ return dropped.map((each) => {
3391
+ const lead = each.lead === null ? void 0 : leads.get(each.lead);
3392
+ const campaign = each.campaign === null ? void 0 : campaigns.get(each.campaign);
3393
+ return {
3394
+ ...each,
3395
+ campaignName: campaign?.name ?? null,
3396
+ email: lead?.email ?? null,
3397
+ linkedinUrl: lead?.linkedinUrl ?? null,
3398
+ name: lead === void 0 ? null : nameOf(lead)
3399
+ };
3400
+ });
3401
+ };
2952
3402
  var readReplies = (context, since, max) => {
2953
3403
  const { outbound } = context;
2954
3404
  const filtered = outbound.capabilities["replies.since"] !== false;
@@ -2957,20 +3407,21 @@ var readReplies = (context, since, max) => {
2957
3407
  "This tool cannot filter replies by date, so the newest replies were read and filtered here."
2958
3408
  );
2959
3409
  }
2960
- return readCapped2(
3410
+ return readCappedFlag(
2961
3411
  context,
2962
3412
  (cap) => outbound.replies.listAll(filtered ? { max: cap, since } : { max: cap }),
2963
3413
  max,
2964
- "replies"
3414
+ "replies",
3415
+ "max_replies"
2965
3416
  );
2966
3417
  };
2967
3418
  var droppedReplies = defineInsight({
2968
- 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, campaign and lead. A reply that could not be checked is counted in totals.unchecked, never reported as dropped. Costs one request per page of replies plus one per conversation checked, so at most about max_replies requests.",
3419
+ 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.",
2969
3420
  inputSchema: input15,
2970
3421
  key: "droppedReplies",
2971
3422
  name: "dropped_replies",
2972
3423
  needs: ["replies.list"],
2973
- next: "Use person_summary with the lead's email address to read what was sent before answering, or hot_leads to see who else to contact first.",
3424
+ next: "Use person_summary with the lead's ref or email address to read what was sent before answering. Use hot_leads to see who else to contact first.",
2974
3425
  run: async (context, values) => {
2975
3426
  const since = new Date(
2976
3427
  values.since === null ? context.now - DEFAULT_DAYS * DAY : Date.parse(values.since)
@@ -2981,7 +3432,8 @@ var droppedReplies = defineInsight({
2981
3432
  "This tool can read neither a conversation nor a lead's timeline, so no reply could be checked."
2982
3433
  );
2983
3434
  }
2984
- const read = await readReplies(context, since, values.max_replies);
3435
+ const listed = await readReplies(context, since, values.max_replies);
3436
+ const read = listed.items;
2985
3437
  const replies2 = read.filter(
2986
3438
  (reply) => reply.sentAt === null || Date.parse(reply.sentAt) >= Date.parse(since)
2987
3439
  );
@@ -3018,8 +3470,9 @@ var droppedReplies = defineInsight({
3018
3470
  answered += found.length === 0 ? 1 : 0;
3019
3471
  tooRecent += found.length - old.length;
3020
3472
  }
3473
+ const withNames = await named2(context, dropped);
3021
3474
  const answer = {
3022
- dropped: dropped.toSorted(
3475
+ dropped: withNames.toSorted(
3023
3476
  (left, right) => right.hoursWaiting - left.hoursWaiting || left.reply.localeCompare(right.reply)
3024
3477
  ),
3025
3478
  olderThanHours: values.older_than_hours,
@@ -3028,6 +3481,7 @@ var droppedReplies = defineInsight({
3028
3481
  answered,
3029
3482
  conversations: conversations.length,
3030
3483
  dropped: dropped.length,
3484
+ moreRepliesExist: listed.capped,
3031
3485
  repliesRead: read.length,
3032
3486
  skippedAuto: wanted.length - kept.length,
3033
3487
  skippedByCategory: replies2.length - wanted.length,
@@ -3040,22 +3494,28 @@ var droppedReplies = defineInsight({
3040
3494
  });
3041
3495
 
3042
3496
  // src/insights/people/hot-leads.ts
3043
- import { z as z19 } from "zod";
3497
+ import { z as z20 } from "zod";
3044
3498
  var DAY2 = 864e5;
3045
- var weight = (value, what) => z19.number().min(0).default(value).describe(what);
3046
- var input16 = z19.object({
3047
- campaign: z19.string().min(1).nullable().default(null).describe(
3499
+ var RECENT_REPLIES = 100;
3500
+ var NOT_ENGAGED = /* @__PURE__ */ new Set([
3501
+ "bounce",
3502
+ "ooo",
3503
+ "unsubscribe"
3504
+ ]);
3505
+ var weight = (value, what) => z20.number().min(0).default(value).describe(what);
3506
+ var input16 = z20.object({
3507
+ campaign: z20.string().min(1).nullable().default(null).describe(
3048
3508
  "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3049
3509
  ),
3050
- count_cap: z19.number().int().min(1).default(5).describe(
3510
+ count_cap: z20.number().int().min(1).default(5).describe(
3051
3511
  "The most replies, clicks or opens that earn points, so 40 opens do not outrank a reply"
3052
3512
  ),
3053
- limit: z19.number().int().min(1).max(500).default(20).describe("How many leads to return"),
3054
- max_leads: z19.number().int().min(1).max(2e4).default(500).describe(
3055
- "The most leads to read and score. A vendor request returns about 50 to 100 leads."
3513
+ limit: z20.number().int().min(1).max(500).default(20).describe("How many leads to return"),
3514
+ max_leads: z20.number().int().min(1).max(2e4).default(500).describe(
3515
+ "The most leads to read and score. A vendor request returns about 50 to 100 leads. When more exist, the leads behind recent replies are read as well, so engaged leads past the cap are still ranked."
3056
3516
  ),
3057
3517
  positive_labels: positiveLabelsField,
3058
- recency_days: z19.number().min(1).default(14).describe(
3518
+ recency_days: z20.number().min(1).default(14).describe(
3059
3519
  "A reply today earns the full recency points, fading evenly to none after this many days"
3060
3520
  ),
3061
3521
  weight_click: weight(5, "Points for each click, up to count_cap"),
@@ -3064,38 +3524,55 @@ var input16 = z19.object({
3064
3524
  weight_recency: weight(20, "Points for a reply received right now"),
3065
3525
  weight_reply: weight(10, "Points for each reply, up to count_cap")
3066
3526
  });
3067
- var capped = (count, points, cap) => count === null ? null : Math.min(count, cap) * points;
3068
- var partsOf = (lead, values, now) => {
3069
- const engagement = lead.engagement ?? null;
3070
- const positive = isPositive(lead.interest, values.positive_labels);
3071
- const replies2 = engagement?.replies ?? (lead.replied === true ? 1 : null);
3072
- const repliedAt = engagement?.lastRepliedAt ?? null;
3073
- const age = repliedAt === null ? null : Math.max(0, now - Date.parse(repliedAt)) / DAY2 / values.recency_days;
3527
+ var capped = (count2, points, cap) => count2 === null ? null : Math.min(count2, cap) * points;
3528
+ var saidNo = (lead, labels) => !isAutoReplied(lead) && isNegative(lead) && isPositive(lead.interest, labels) !== true;
3529
+ var repliesDiscounted = (lead, labels) => isAutoReplied(lead) || saidNo(lead, labels);
3530
+ var engagementParts = (lead, values) => {
3531
+ const unwanted = saidNo(lead, values.positive_labels);
3074
3532
  return {
3075
3533
  clicks: capped(
3076
- engagement?.clicks ?? null,
3077
- values.weight_click,
3534
+ lead.engagement?.clicks ?? null,
3535
+ unwanted ? 0 : values.weight_click,
3078
3536
  values.count_cap
3079
3537
  ),
3080
- interest: positive === null ? null : Number(positive) * values.weight_interest,
3081
3538
  opens: capped(
3082
- engagement?.opens ?? null,
3083
- values.weight_open,
3539
+ lead.engagement?.opens ?? null,
3540
+ unwanted ? 0 : values.weight_open,
3084
3541
  values.count_cap
3085
- ),
3086
- recency: age === null ? null : round(Math.max(0, 1 - age) * values.weight_recency),
3542
+ )
3543
+ };
3544
+ };
3545
+ var partsOf = (lead, values, now) => {
3546
+ const engagement = lead.engagement ?? null;
3547
+ const positive = isPositive(lead.interest, values.positive_labels);
3548
+ const automatic = repliesDiscounted(lead, values.positive_labels);
3549
+ const counted2 = engagement?.replies ?? (lead.replied === true ? 1 : null);
3550
+ const replies2 = automatic && counted2 !== null ? 0 : counted2;
3551
+ const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
3552
+ const age = repliedAt === null ? null : Math.max(0, now - Date.parse(repliedAt)) / DAY2 / values.recency_days;
3553
+ const fresh = age === null ? null : Math.max(0, 1 - age);
3554
+ const { clicks, opens } = engagementParts(lead, values);
3555
+ return {
3556
+ clicks,
3557
+ interest: positive === null ? null : Number(positive) * values.weight_interest,
3558
+ opens,
3559
+ recency: automatic && counted2 !== null ? 0 : round(fresh === null ? null : fresh * values.weight_recency),
3087
3560
  replies: capped(replies2, values.weight_reply, values.count_cap)
3088
3561
  };
3089
3562
  };
3090
- var reasonOf = (lead, parts, now) => {
3563
+ var discountedReason = (lead) => isAutoReplied(lead) ? `marked ${lead.interest ?? "out of office"}, so replies earn nothing` : `marked ${lead.interest ?? "not interested"}, so it earns no points`;
3564
+ var counted = (points, amount, what) => (points ?? 0) > 0 ? plural(amount ?? 0, what) : null;
3565
+ var reasonOf = (lead, parts, now, labels) => {
3091
3566
  const engagement = lead.engagement ?? null;
3092
- const repliedAt = engagement?.lastRepliedAt ?? null;
3567
+ const automatic = repliesDiscounted(lead, labels);
3568
+ const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
3093
3569
  const facts = [
3094
3570
  (parts.interest ?? 0) > 0 ? `marked ${lead.interest}` : null,
3095
- (parts.replies ?? 0) > 0 ? `replied ${engagement?.replies ?? 1} time(s)` : null,
3096
- repliedAt === null ? null : `last reply ${Math.floor(Math.max(0, now - Date.parse(repliedAt)) / DAY2)} day(s) ago`,
3097
- (parts.clicks ?? 0) > 0 ? `${engagement?.clicks} click(s)` : null,
3098
- (parts.opens ?? 0) > 0 ? `${engagement?.opens} open(s)` : null
3571
+ automatic ? discountedReason(lead) : null,
3572
+ (parts.replies ?? 0) > 0 ? `replied ${plural(engagement?.replies ?? 1, "time")}` : null,
3573
+ repliedAt === null ? null : `last reply ${plural(Math.floor(Math.max(0, now - Date.parse(repliedAt)) / DAY2), "day")} ago`,
3574
+ counted(parts.clicks, engagement?.clicks, "click"),
3575
+ counted(parts.opens, engagement?.opens, "open")
3099
3576
  ].flatMap((fact) => fact === null ? [] : [fact]);
3100
3577
  return `${facts.join(", ")}.`;
3101
3578
  };
@@ -3115,7 +3592,7 @@ var toHotLead = (lead, values, now) => {
3115
3592
  name: nameOf(lead),
3116
3593
  opens: lead.engagement?.opens ?? null,
3117
3594
  parts,
3118
- reason: reasonOf(lead, parts, now),
3595
+ reason: reasonOf(lead, parts, now, values.positive_labels),
3119
3596
  replies: lead.engagement?.replies ?? null,
3120
3597
  score: round(score) ?? 0,
3121
3598
  status: lead.status,
@@ -3123,35 +3600,75 @@ var toHotLead = (lead, values, now) => {
3123
3600
  }
3124
3601
  ];
3125
3602
  };
3126
- var readLeads2 = (context, { campaign, max_leads: maxLeads }) => {
3603
+ var listLeads = async (context, { campaign, max_leads: maxLeads }) => {
3127
3604
  const { outbound } = context;
3128
- if (campaign !== null) {
3129
- return leadsOf(context, campaign, maxLeads);
3130
- }
3131
- if (!outbound.capabilities["leads.list"]) {
3605
+ if (campaign === null && !outbound.capabilities["leads.list"]) {
3132
3606
  throw new OutboundError(
3133
3607
  "Unsupported",
3134
3608
  `hot_leads needs a campaign here: the ${outbound.provider} adapter cannot list every lead (leads.list)`,
3135
3609
  { provider: outbound.provider }
3136
3610
  );
3137
3611
  }
3138
- return readCapped2(
3612
+ const walk = campaign === null ? outbound.leads.listAll({ max: maxLeads }) : outbound.campaign(campaign).leads.listAll({ max: maxLeads });
3613
+ const leads = await context.all(walk, {
3614
+ input: "max_leads",
3615
+ max: maxLeads,
3616
+ what: campaign === null ? "leads" : "leads of a campaign"
3617
+ });
3618
+ if (campaign !== null && leads.length === 0) {
3619
+ await confirmCampaign(context, campaign);
3620
+ }
3621
+ return { capped: walk.truncated, leads };
3622
+ };
3623
+ var repliedPastCap = async (context, values, read) => {
3624
+ const { outbound } = context;
3625
+ if (!(outbound.capabilities["replies.list"] && outbound.capabilities["leads.get"])) {
3626
+ context.note(
3627
+ "This tool cannot list replies or read one lead, so leads past max_leads that replied were not looked for."
3628
+ );
3629
+ return [];
3630
+ }
3631
+ const since = context.now - values.recency_days * DAY2;
3632
+ const filtered = outbound.capabilities["replies.since"] !== false;
3633
+ const range = filtered ? { since: new Date(since).toISOString() } : {};
3634
+ const replies2 = await context.all(
3635
+ outbound.replies.listAll({ max: RECENT_REPLIES, ...range }),
3636
+ {
3637
+ input: null,
3638
+ max: RECENT_REPLIES,
3639
+ what: "recent replies looked through for leads past max_leads"
3640
+ }
3641
+ );
3642
+ const listed = new Set(read.map((lead) => lead.ref));
3643
+ const refs = replies2.filter(
3644
+ (reply) => reply.isAuto !== true && !NOT_ENGAGED.has(reply.category) && reply.sentAt !== null && Date.parse(reply.sentAt) >= since && (values.campaign === null || reply.campaignRef === values.campaign)
3645
+ ).toSorted(
3646
+ (left, right) => (right.sentAt ?? "").localeCompare(left.sentAt ?? "")
3647
+ ).flatMap(
3648
+ (reply) => reply.leadRef === null || listed.has(reply.leadRef) ? [] : [reply.leadRef]
3649
+ );
3650
+ const found = await readByRef(
3139
3651
  context,
3140
- (cap) => outbound.leads.listAll({ max: cap }),
3141
- maxLeads,
3142
- "leads"
3652
+ [...new Set(refs)].slice(0, values.limit),
3653
+ (ids) => outbound.leads.getMany(ids),
3654
+ ["lead that replied", "leads that replied"],
3655
+ "scores are missing"
3143
3656
  );
3657
+ return [...found.values()];
3144
3658
  };
3659
+ var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1 : 0);
3145
3660
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3146
3661
  var hotLeads = defineInsight({
3147
- 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, or none to rank every lead the tool lists. Costs one request per page of leads read (max_leads sets the ceiling). A part that is null means the vendor does not report that signal.",
3662
+ 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.",
3148
3663
  inputSchema: input16,
3149
3664
  key: "hotLeads",
3150
3665
  name: "hot_leads",
3151
3666
  needs: [],
3152
- next: "Use person_summary with a lead's email address or LinkedIn profile to read the conversation before calling.",
3667
+ next: "Use person_summary with a lead's ref, email address or LinkedIn profile to read the conversation before calling.",
3153
3668
  run: async (context, values) => {
3154
- const leads = await readLeads2(context, values);
3669
+ const listed = await listLeads(context, values);
3670
+ const extra = listed.capped ? await repliedPastCap(context, values, listed.leads) : [];
3671
+ const leads = [...listed.leads, ...extra];
3155
3672
  noteEngagement(
3156
3673
  context,
3157
3674
  leads,
@@ -3162,11 +3679,22 @@ var hotLeads = defineInsight({
3162
3679
  );
3163
3680
  const scored = open.flatMap((lead) => toHotLead(lead, values, context.now));
3164
3681
  const hot = scored.filter((lead) => lead.score > 0).toSorted(hottestFirst);
3682
+ const negative = open.filter(
3683
+ (lead) => saidNo(lead, values.positive_labels)
3684
+ );
3685
+ const refused = new Set(negative.map((lead) => lead.ref));
3686
+ const after = scored.filter((lead) => lead.score <= 0 && refused.has(lead.lead)).toSorted(hottestFirst);
3165
3687
  const answer = {
3166
- leads: hot.slice(0, values.limit),
3688
+ leads: [...hot, ...after].slice(0, values.limit),
3167
3689
  totals: {
3690
+ autoReplied: open.filter(
3691
+ (lead) => isAutoReplied(lead) && repliesOf(lead) > 0
3692
+ ).length,
3168
3693
  excluded: leads.length - open.length,
3694
+ fromReplies: extra.length,
3169
3695
  hot: hot.length,
3696
+ moreLeadsExist: listed.capped,
3697
+ negative: negative.length,
3170
3698
  leadsRead: leads.length,
3171
3699
  scored: scored.length,
3172
3700
  withoutData: open.length - scored.length
@@ -3177,7 +3705,7 @@ var hotLeads = defineInsight({
3177
3705
  });
3178
3706
 
3179
3707
  // src/insights/people/lead-collisions.ts
3180
- import { z as z20 } from "zod";
3708
+ import { z as z21 } from "zod";
3181
3709
 
3182
3710
  // src/insights/people/find.ts
3183
3711
  var personKey = (identifier) => {
@@ -3198,30 +3726,113 @@ var keysOfLead = (lead) => {
3198
3726
  var filterFor = (key) => key.startsWith("email:") ? { email: key.slice("email:".length) } : {
3199
3727
  linkedinUrl: `https://www.linkedin.com/in/${key.slice("linkedin:".length)}`
3200
3728
  };
3201
- var isRedacted = (outbound) => "redacted" in outbound;
3202
- var maskedIdentifiers = (outbound) => isRedacted(outbound) ? outbound.redacted.fields.filter(
3203
- (field) => field === "email" || field === "linkedin"
3204
- ) : [];
3205
- var findPerson = async (context, identifier, maxRecords) => {
3206
- const first = personKey(identifier);
3207
- if (first === null) {
3729
+ var kindOf = (key) => key.startsWith("email:") ? "email" : "linkedin";
3730
+ var lookupOf = (outbound) => {
3731
+ const masking = maskingOf(outbound);
3732
+ return {
3733
+ hash: masking?.strategy === "hash" ? masking.hash : void 0,
3734
+ masked: (masking?.fields ?? []).flatMap(
3735
+ (field) => field === "email" || field === "linkedin" ? [field] : []
3736
+ )
3737
+ };
3738
+ };
3739
+ var WORDS = {
3740
+ email: "email addresses",
3741
+ linkedin: "LinkedIn profiles"
3742
+ };
3743
+ var maskedWords = (masked) => masked.map((kind) => WORDS[kind]).join(" and ");
3744
+ var refuse = (outbound, masked, why) => new OutboundError(
3745
+ "Unsupported",
3746
+ `A person cannot be looked up while the redact plugin masks ${maskedWords(masked)}: ${why}`,
3747
+ { provider: outbound.provider }
3748
+ );
3749
+ var isLeadRef = (identifier) => personKey(identifier) === null && parseRef(identifier.trim()) !== null;
3750
+ var PROFILE = "https://www.linkedin.com/in/";
3751
+ var formsOf = (key, given) => {
3752
+ const value = key.slice(key.indexOf(":") + 1);
3753
+ return kindOf(key) === "email" ? [value] : [
3754
+ `${PROFILE}${value}`,
3755
+ `${PROFILE}${value}/`,
3756
+ `https://linkedin.com/in/${value}`,
3757
+ given.trim()
3758
+ ];
3759
+ };
3760
+ var startFrom = async (context, identifier, { hash, masked }) => {
3761
+ const { outbound } = context;
3762
+ const key = personKey(identifier);
3763
+ if (key !== null) {
3764
+ if (!masked.includes(kindOf(key))) {
3765
+ return { hashed: null, keys: [key], records: [] };
3766
+ }
3767
+ if (hash === void 0) {
3768
+ throw refuse(
3769
+ outbound,
3770
+ masked,
3771
+ "the records could not be matched to the identifier"
3772
+ );
3773
+ }
3774
+ const tokens = formsOf(key, identifier).map(hash);
3775
+ return {
3776
+ hashed: {
3777
+ shown: `${kindOf(key)}:${tokens[0] ?? ""}`,
3778
+ tokens: new Set(tokens)
3779
+ },
3780
+ keys: [key],
3781
+ records: []
3782
+ };
3783
+ }
3784
+ if (!isLeadRef(identifier)) {
3208
3785
  throw new OutboundError(
3209
3786
  "Invalid",
3210
- "Give an email address or a LinkedIn profile URL",
3211
- { provider: context.outbound.provider }
3787
+ "Give an email address, a LinkedIn profile URL or a lead ref",
3788
+ { provider: outbound.provider }
3789
+ );
3790
+ }
3791
+ const instead = hash === void 0 ? null : "a lead's identifiers are hashed on its record, so give the email address or LinkedIn profile URL instead";
3792
+ if (masked.length === 2) {
3793
+ throw refuse(
3794
+ outbound,
3795
+ masked,
3796
+ instead ?? "a lead ref has no identifier left to look the person up by"
3797
+ );
3798
+ }
3799
+ const lead = context.one(await outbound.leads.get(identifier.trim()));
3800
+ const keys = keysOfLead(lead).filter(
3801
+ (each) => !masked.includes(kindOf(each))
3802
+ );
3803
+ if (keys.length === 0 && masked.length > 0) {
3804
+ const other = ["email", "linkedin"].find(
3805
+ (kind) => !masked.includes(kind)
3806
+ );
3807
+ throw refuse(
3808
+ outbound,
3809
+ masked,
3810
+ instead ?? `the lead has no ${other === "email" ? "email address" : "LinkedIn profile"} to look it up by`
3212
3811
  );
3213
3812
  }
3214
- const masked = maskedIdentifiers(context.outbound);
3813
+ return { hashed: null, keys, records: [lead] };
3814
+ };
3815
+ var carries = (lead, key, start) => {
3816
+ if (start.hashed !== null && start.keys.includes(key)) {
3817
+ const field = kindOf(key) === "email" ? lead.email : lead.linkedinUrl;
3818
+ return field !== null && start.hashed.tokens.has(field);
3819
+ }
3820
+ return keysOfLead(lead).includes(key);
3821
+ };
3822
+ var findPerson = async (context, identifier, maxRecords) => {
3823
+ const lookup = lookupOf(context.outbound);
3824
+ const { masked } = lookup;
3825
+ const start = await startFrom(context, identifier, lookup);
3215
3826
  if (masked.length > 0) {
3216
- throw new OutboundError(
3217
- "Unsupported",
3218
- `A person cannot be looked up while the redact plugin masks ${masked.join(" and ")}: the records could not be matched to the identifier`,
3219
- { provider: context.outbound.provider }
3827
+ context.partial(
3828
+ `The redact plugin masks ${maskedWords(masked)}, so records found only under that identifier were not linked.`
3220
3829
  );
3221
3830
  }
3222
- const keys = /* @__PURE__ */ new Set([first]);
3831
+ const keys = new Set(start.keys);
3223
3832
  const asked = /* @__PURE__ */ new Set();
3224
- const records = /* @__PURE__ */ new Map();
3833
+ const records = new Map(
3834
+ start.records.map((lead) => [`${lead.ref} ${lead.campaignRef ?? ""}`, lead])
3835
+ );
3225
3836
  for (let round2 = [...keys].filter((key) => !asked.has(key)); round2.length > 0; round2 = [...keys].filter((key) => !asked.has(key))) {
3226
3837
  for (const key of round2) {
3227
3838
  asked.add(key);
@@ -3230,34 +3841,43 @@ var findPerson = async (context, identifier, maxRecords) => {
3230
3841
  round2,
3231
3842
  (key) => context.all(
3232
3843
  context.outbound.leads.listAll({ ...filterFor(key), max: maxRecords }),
3233
- `${maxRecords} records of the person`
3844
+ {
3845
+ input: "max_campaigns",
3846
+ max: maxRecords,
3847
+ what: "records of the person"
3848
+ }
3234
3849
  )
3235
3850
  );
3236
3851
  for (const [index, leads] of answers.entries()) {
3237
3852
  const asking = round2[index];
3238
3853
  for (const lead of leads) {
3239
3854
  const leadKeys = keysOfLead(lead);
3240
- if (asking !== void 0 && leadKeys.includes(asking)) {
3855
+ if (asking !== void 0 && carries(lead, asking, start)) {
3241
3856
  records.set(`${lead.ref} ${lead.campaignRef ?? ""}`, lead);
3242
3857
  for (const key of leadKeys) {
3243
- keys.add(key);
3858
+ if (!masked.includes(kindOf(key))) {
3859
+ keys.add(key);
3860
+ }
3244
3861
  }
3245
3862
  }
3246
3863
  }
3247
3864
  }
3248
3865
  }
3866
+ const shown = [...keys].map(
3867
+ (key) => start.hashed !== null && start.keys.includes(key) ? start.hashed.shown : key
3868
+ );
3249
3869
  return {
3250
- keys: [...keys].toSorted(),
3870
+ keys: shown.toSorted(),
3251
3871
  records: [...records.values()].slice(0, maxRecords)
3252
3872
  };
3253
3873
  };
3254
3874
 
3255
3875
  // src/insights/people/lead-collisions.ts
3256
- var input17 = z20.object({
3257
- max_campaigns: z20.number().int().min(1).max(200).default(20).describe(
3876
+ var input17 = z21.object({
3877
+ max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
3258
3878
  "The most campaigns to read. Each costs one request per page of its leads."
3259
3879
  ),
3260
- max_leads_per_campaign: z20.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3880
+ max_leads_per_campaign: z21.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3261
3881
  statuses: statusesField
3262
3882
  });
3263
3883
  var groupPeople = (entries) => {
@@ -3302,7 +3922,7 @@ var toCollision = (group) => {
3302
3922
  campaignCount: campaigns.length,
3303
3923
  campaigns,
3304
3924
  channels,
3305
- finding: scope === "across_tools" ? `${identifiers[0]} is in ${campaigns.length} campaigns across ${providers.join(" and ")} (${channels.join(" and ")}).` : `${identifiers[0]} is in ${campaigns.length} ${providers[0]} campaigns at once.`,
3925
+ finding: scope === "across_tools" ? `${shownKey(identifiers[0] ?? "")} is in ${campaigns.length} campaigns across ${providers.join(" and ")} (${channels.join(" and ")}).` : `${shownKey(identifiers[0] ?? "")} is in ${campaigns.length} ${providers[0]} campaigns at once.`,
3306
3926
  identifiers,
3307
3927
  providers,
3308
3928
  scope,
@@ -3315,11 +3935,19 @@ var leadCollisions = defineInsight({
3315
3935
  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.",
3316
3936
  inputSchema: input17,
3317
3937
  key: "leadCollisions",
3938
+ // A masked address is the same text for every lead, so every lead would
3939
+ // collide with every other. A hashed one still tells people apart.
3940
+ maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches people by" : null,
3318
3941
  name: "lead_collisions",
3319
3942
  needs: ["leads.byCampaign"],
3320
- next: "Use person_summary with one of the identifiers to see what that person was sent and whether they replied.",
3943
+ next: "Use person_summary with one of the identifiers or lead refs to see what that person was sent and whether they replied.",
3321
3944
  run: async (context, values) => {
3322
- const campaigns = await campaignsIn2(
3945
+ if (maskingOf(context.outbound)?.fields.includes("linkedin") === true) {
3946
+ context.partial(
3947
+ "The redact plugin masks LinkedIn profiles, so people were matched by email address only."
3948
+ );
3949
+ }
3950
+ const campaigns = await campaignsIn(
3323
3951
  context,
3324
3952
  values.statuses,
3325
3953
  values.max_campaigns
@@ -3328,7 +3956,8 @@ var leadCollisions = defineInsight({
3328
3956
  const leads = await leadsOf(
3329
3957
  context,
3330
3958
  campaign.ref,
3331
- values.max_leads_per_campaign
3959
+ values.max_leads_per_campaign,
3960
+ "max_leads_per_campaign"
3332
3961
  );
3333
3962
  return leads.map((lead) => ({ campaign, lead }));
3334
3963
  });
@@ -3355,10 +3984,12 @@ var leadCollisions = defineInsight({
3355
3984
  });
3356
3985
 
3357
3986
  // src/insights/people/person-summary.ts
3358
- import { z as z21 } from "zod";
3359
- var input18 = z21.object({
3360
- max_campaigns: z21.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
3361
- person: z21.string().min(3).describe("The person's email address or LinkedIn profile URL")
3987
+ import { z as z22 } from "zod";
3988
+ var input18 = z22.object({
3989
+ max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
3990
+ person: z22.string().min(3).describe(
3991
+ "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
3992
+ )
3362
3993
  });
3363
3994
  var times2 = (messages, direction) => messages.flatMap(
3364
3995
  (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
@@ -3373,29 +4004,29 @@ var repliedSteps = (lead, messages) => {
3373
4004
  steps.add(message.stepIndex ?? lastSent ?? 0);
3374
4005
  }
3375
4006
  }
3376
- const named2 = lead.engagement?.repliedStepIndex ?? null;
3377
- if (named2 !== null) {
3378
- steps.add(named2);
4007
+ const named3 = lead.engagement?.repliedStepIndex ?? null;
4008
+ if (named3 !== null) {
4009
+ steps.add(named3);
3379
4010
  }
3380
4011
  return [...steps].toSorted((left, right) => left - right);
3381
4012
  };
3382
4013
  var activityOf = (lead, messages) => {
3383
4014
  const sent = times2(messages, "out");
3384
4015
  const received = times2(messages, "in");
3385
- const counted = lead.engagement;
4016
+ const counted2 = lead.engagement;
3386
4017
  return {
3387
4018
  firstContactedAt: sent[0] ?? null,
3388
- lastContactedAt: sent.at(-1) ?? counted?.lastContactedAt ?? null,
3389
- lastRepliedAt: received.at(-1) ?? counted?.lastRepliedAt ?? null,
3390
- lastStep: counted?.stepIndex ?? messages.findLast(
4019
+ lastContactedAt: sent.at(-1) ?? counted2?.lastContactedAt ?? null,
4020
+ lastRepliedAt: received.at(-1) ?? counted2?.lastRepliedAt ?? null,
4021
+ lastStep: counted2?.stepIndex ?? messages.findLast(
3391
4022
  (message) => message.direction === "out" && message.stepIndex !== null
3392
4023
  )?.stepIndex ?? null,
3393
4024
  // A vendor's thread can hold fewer messages than were sent; the last
3394
4025
  // step sent (counted from 0) is then the better count.
3395
- messagesSent: Math.max(sent.length, (counted?.stepIndex ?? -1) + 1),
4026
+ messagesSent: Math.max(sent.length, (counted2?.stepIndex ?? -1) + 1),
3396
4027
  // A vendor that keeps no thread still counts replies on the lead.
3397
- replies: Math.max(received.length, counted?.replies ?? 0),
3398
- threadIsShort: sent.length < (counted?.stepIndex ?? -1) + 1
4028
+ replies: Math.max(received.length, counted2?.replies ?? 0),
4029
+ threadIsShort: sent.length < (counted2?.stepIndex ?? -1) + 1
3399
4030
  };
3400
4031
  };
3401
4032
  var timelineOf = async (context, timelines, lead) => {
@@ -3415,7 +4046,14 @@ var summarize2 = async (context, timelines, lead) => {
3415
4046
  timelineOf(context, timelines, lead),
3416
4047
  lead.campaignRef === null ? null : outbound.campaigns.get(lead.campaignRef).then(context.one)
3417
4048
  ]);
3418
- const { threadIsShort, ...activity } = activityOf(lead, messages);
4049
+ const { threadIsShort, ...counted2 } = activityOf(lead, messages);
4050
+ const autoReplied = isAutoReplied(lead);
4051
+ const activity = autoReplied ? { ...counted2, lastRepliedAt: null, replies: 0 } : counted2;
4052
+ if (autoReplied && counted2.replies > 0) {
4053
+ context.note(
4054
+ "A record the vendor labels out-of-office or bounced had replies; they were automatic, so they are not counted as replies."
4055
+ );
4056
+ }
3419
4057
  if (threadIsShort) {
3420
4058
  context.note(
3421
4059
  "A thread held fewer sent messages than the lead's last step, so messages sent is counted from the last step."
@@ -3431,8 +4069,9 @@ var summarize2 = async (context, timelines, lead) => {
3431
4069
  lead: lead.ref,
3432
4070
  leadStatus: lead.status,
3433
4071
  provider: lead.provider,
3434
- replied: activity.replies > 0 || lead.replied === true,
3435
- repliedSteps: repliedSteps(lead, messages)
4072
+ autoReplied,
4073
+ replied: !autoReplied && (activity.replies > 0 || lead.replied === true),
4074
+ repliedSteps: autoReplied ? [] : repliedSteps(lead, messages)
3436
4075
  };
3437
4076
  };
3438
4077
  var byChannel2 = (campaigns) => {
@@ -3450,11 +4089,16 @@ var byChannel2 = (campaigns) => {
3450
4089
  return channels;
3451
4090
  };
3452
4091
  var personSummary = defineInsight({
3453
- description: "Everything about one person across campaigns and channels, from their email address or LinkedIn profile: 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. Costs one lookup per identifier, then up to 2 requests per campaign.",
4092
+ 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.",
3454
4093
  inputSchema: input18,
3455
4094
  key: "personSummary",
3456
4095
  name: "person_summary",
4096
+ maskedOut: (masking) => {
4097
+ const masked = new Set(masking.fields);
4098
+ return masked.has("email") && masked.has("linkedin") && masking.strategy === "mask" ? "email addresses and LinkedIn profiles, which it looks a person up by" : null;
4099
+ },
3457
4100
  needs: ["leads.lookup", "leads.timeline"],
4101
+ needsFor: ({ person }) => isLeadRef(person) ? ["leads.get"] : [],
3458
4102
  next: "Use account_summary with their email domain to see everyone at the same company.",
3459
4103
  run: async (context, { max_campaigns: maxCampaigns, person }) => {
3460
4104
  const found = await findPerson(context, person, maxCampaigns);
@@ -3489,11 +4133,11 @@ var personSummary = defineInsight({
3489
4133
  });
3490
4134
 
3491
4135
  // src/insights/people/personalization-gaps.ts
3492
- import { z as z22 } from "zod";
3493
- var input19 = z22.object({
3494
- campaign: z22.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
3495
- limit: z22.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
3496
- max_leads: z22.number().int().min(1).max(2e4).default(500).describe(
4136
+ import { z as z23 } from "zod";
4137
+ var input19 = z23.object({
4138
+ campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
4139
+ limit: z23.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
4140
+ max_leads: z23.number().int().min(1).max(2e4).default(500).describe(
3497
4141
  "The most leads to check. A vendor request returns about 50 to 100 leads."
3498
4142
  )
3499
4143
  });
@@ -3601,7 +4245,12 @@ var personalizationGaps = defineInsight({
3601
4245
  await context.outbound.campaign(values.campaign).sequence()
3602
4246
  );
3603
4247
  const found = findVariables(sequence2);
3604
- const leads = found.size === 0 ? [] : await leadsOf(context, values.campaign, values.max_leads);
4248
+ const leads = found.size === 0 ? [] : await leadsOf(
4249
+ context,
4250
+ values.campaign,
4251
+ values.max_leads,
4252
+ "max_leads"
4253
+ );
3605
4254
  if (found.size === 0) {
3606
4255
  context.note("The sequence uses no variables, so no lead was read.");
3607
4256
  }
@@ -3619,7 +4268,7 @@ var personalizationGaps = defineInsight({
3619
4268
  (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
3620
4269
  );
3621
4270
  const answer = {
3622
- campaign: values.campaign,
4271
+ campaign: refOf(context.outbound, values.campaign),
3623
4272
  leads: affected.slice(0, values.limit),
3624
4273
  totals: {
3625
4274
  affectedRate: rate(affected.length, leads.length),
@@ -3638,15 +4287,15 @@ var personalizationGaps = defineInsight({
3638
4287
  });
3639
4288
 
3640
4289
  // src/insights/people/suppression-check.ts
3641
- import { z as z23 } from "zod";
3642
- var input20 = z23.object({
3643
- max_block_entries: z23.number().int().min(1).max(1e5).default(2e3).describe(
4290
+ import { z as z24 } from "zod";
4291
+ var input20 = z24.object({
4292
+ max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
3644
4293
  "The most block list entries to read. A vendor request returns about 50 to 100."
3645
4294
  ),
3646
- max_campaigns: z23.number().int().min(1).max(200).default(20).describe(
4295
+ max_campaigns: z24.number().int().min(1).max(200).default(20).describe(
3647
4296
  "The most campaigns to check. Each costs one request per page of its leads."
3648
4297
  ),
3649
- max_leads_per_campaign: z23.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
4298
+ max_leads_per_campaign: z24.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3650
4299
  statuses: statusesField
3651
4300
  });
3652
4301
  var slugOfEntry = (value) => profileSlug(value) ?? value.trim().replaceAll(/^\/+|\/+$/gu, "").toLowerCase();
@@ -3698,23 +4347,46 @@ var toViolation = (lead, campaign, { entry, matchedBy }) => ({
3698
4347
  matchedBy,
3699
4348
  sameTool: entry.provider === lead.provider && entry.workspaceId === lead.workspaceId
3700
4349
  });
4350
+ var maskNote = (outbound) => {
4351
+ const fields = maskingOf(outbound)?.fields ?? [];
4352
+ const email = fields.includes("email");
4353
+ const linkedin = fields.includes("linkedin");
4354
+ const masked = [
4355
+ ...email ? ["email addresses"] : [],
4356
+ ...linkedin ? ["LinkedIn profiles"] : []
4357
+ ];
4358
+ const lost = [
4359
+ ...email ? ["domain entries"] : [],
4360
+ ...linkedin ? ["LinkedIn profile entries"] : []
4361
+ ];
4362
+ return masked.length === 0 ? null : `The redact plugin masks ${masked.join(" and ")}, so ${lost.join(" and ")} could not be matched to leads.`;
4363
+ };
3701
4364
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
3702
4365
  var suppressionCheck = defineInsight({
3703
- 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. 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.",
4366
+ 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.",
3704
4367
  inputSchema: input20,
3705
4368
  key: "suppressionCheck",
4369
+ // A masked address is the same text for every lead, so nothing can match.
4370
+ // A hashed one still matches the same address on the list.
4371
+ maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches leads to the block list by" : null,
3706
4372
  name: "suppression_check",
3707
4373
  needs: ["blocklist", "leads.byCampaign"],
3708
- next: "Use person_summary with a violating lead's email address to see what they were already sent.",
4374
+ next: "Use person_summary with a violating lead's ref or email address to see what they were already sent.",
3709
4375
  run: async (context, values) => {
3710
- const entries = await readCapped2(
4376
+ const listed = await readCappedFlag(
3711
4377
  context,
3712
4378
  (cap) => context.outbound.blocklist.listAll({ max: cap }),
3713
4379
  values.max_block_entries,
3714
- "block list entries"
4380
+ "block list entries",
4381
+ "max_block_entries"
3715
4382
  );
4383
+ const entries = listed.items;
3716
4384
  const blocked = indexEntries(entries);
3717
- const campaigns = await campaignsIn2(
4385
+ const unmatched = maskNote(context.outbound);
4386
+ if (unmatched !== null) {
4387
+ context.partial(unmatched);
4388
+ }
4389
+ const campaigns = await campaignsIn(
3718
4390
  context,
3719
4391
  values.statuses,
3720
4392
  values.max_campaigns
@@ -3723,13 +4395,15 @@ var suppressionCheck = defineInsight({
3723
4395
  const byCampaign = [];
3724
4396
  const read = await mapConcurrent(campaigns, async (campaign) => ({
3725
4397
  campaign,
3726
- leads: await leadsOf(
4398
+ ...await readCappedFlag(
3727
4399
  context,
3728
- campaign.ref,
3729
- values.max_leads_per_campaign
4400
+ (cap) => context.outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
4401
+ values.max_leads_per_campaign,
4402
+ "leads of a campaign",
4403
+ "max_leads_per_campaign"
3730
4404
  )
3731
4405
  }));
3732
- for (const { campaign, leads } of read) {
4406
+ for (const { campaign, items: leads } of read) {
3733
4407
  const found = leads.flatMap((lead) => {
3734
4408
  const hit = matchLead(lead, blocked);
3735
4409
  return hit === null ? [] : [toViolation(lead, campaign, hit)];
@@ -3748,7 +4422,7 @@ var suppressionCheck = defineInsight({
3748
4422
  (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
3749
4423
  ),
3750
4424
  totals: {
3751
- blockEntriesNotChecked: blocked.notChecked,
4425
+ blockEntriesNotChecked: listed.capped ? null : blocked.notChecked,
3752
4426
  blockEntriesRead: entries.length,
3753
4427
  byMatch: {
3754
4428
  domain: matches.get("domain") ?? 0,
@@ -3757,6 +4431,8 @@ var suppressionCheck = defineInsight({
3757
4431
  },
3758
4432
  campaignsRead: campaigns.length,
3759
4433
  leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
4434
+ moreBlockEntriesExist: listed.capped,
4435
+ moreLeadsExist: read.some((each) => each.capped),
3760
4436
  violations: violations.length
3761
4437
  },
3762
4438
  violations: violations.toSorted(activeFirst)
@@ -3780,51 +4456,39 @@ var PEOPLE_INSIGHTS = [
3780
4456
  import { z as z25 } from "zod";
3781
4457
 
3782
4458
  // src/insights/senders/read.ts
3783
- import { z as z24 } from "zod";
3784
- var statusesInput = z24.array(campaignStatusSchema).min(1).default(["active"]).describe(
3785
- "Campaign statuses to look at: active, paused, draft, completed, archived or unknown"
3786
- );
3787
- var dayInput2 = (what) => z24.string().regex(/^\d{4}-\d{2}-\d{2}$/u).optional().describe(
3788
- `${what}, as YYYY-MM-DD. Leave out for the vendor's whole history.`
3789
- );
3790
- var readCapped3 = (context, walk, max, what) => context.all(walk(max), `${max} ${what}`);
3791
- var readCampaigns2 = async (context, statuses, max) => {
3792
- const { outbound } = context;
3793
- if (outbound.capabilities["campaigns.status"] === false) {
3794
- const every = await readCapped3(
3795
- context,
3796
- (cap) => outbound.campaigns.listAll({ max: cap }),
3797
- max,
3798
- "campaigns"
3799
- );
3800
- return every.filter((campaign) => statuses.includes(campaign.status));
3801
- }
3802
- const found = [];
3803
- for (const status of new Set(statuses)) {
3804
- const room = max - found.length;
3805
- if (room <= 0) {
3806
- context.partial(
3807
- `The cap of ${max} campaigns was reached before ${status} campaigns were read.`
3808
- );
3809
- break;
3810
- }
3811
- found.push(
3812
- ...await readCapped3(
3813
- context,
3814
- (cap) => outbound.campaigns.listAll({ max: cap, status }),
3815
- room,
3816
- "campaigns"
3817
- )
3818
- );
3819
- }
3820
- return found;
4459
+ var readCapped2 = async (context, walk, max, what, input27) => {
4460
+ const { items } = await readCapped(context, walk, { input: input27, max, what });
4461
+ return items;
4462
+ };
4463
+ var readCampaigns = async (context, statuses, max) => {
4464
+ const { items } = await readCampaignsIn(context, statuses, max);
4465
+ return items;
3821
4466
  };
3822
- var readCampaignSenders = (context, campaign, max) => readCapped3(
4467
+ var readCampaignSenders = (context, campaign, max, input27) => readCapped2(
3823
4468
  context,
3824
4469
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
3825
4470
  max,
3826
- `senders of campaign ${campaign.name}`
4471
+ `senders of campaign ${campaign.name}`,
4472
+ input27
3827
4473
  );
4474
+ var readSenders = (context, max) => readCapped(context, (cap) => context.outbound.senders.listAll({ max: cap }), {
4475
+ input: "max_senders",
4476
+ max,
4477
+ what: "senders"
4478
+ });
4479
+ var readHealth = async (context, sender) => {
4480
+ try {
4481
+ return context.one(await context.outbound.sender(sender.ref).health());
4482
+ } catch (error) {
4483
+ if (!OutboundError.is(error) || error.code !== "NotFound") {
4484
+ throw error;
4485
+ }
4486
+ context.partial(
4487
+ `Left out ${sender.address ?? sender.ref}: the vendor no longer finds this sender.`
4488
+ );
4489
+ return null;
4490
+ }
4491
+ };
3828
4492
  var domainOf2 = (address) => {
3829
4493
  const domain = address?.split("@")[1]?.trim().toLowerCase() ?? "";
3830
4494
  return domain === "" ? null : domain;
@@ -3841,23 +4505,31 @@ var warmupSpam = (health) => {
3841
4505
  return sent === null ? null : { sent, spam: warmup.spam };
3842
4506
  };
3843
4507
  var dayFrom = (now, offsetDays) => new Date(now + offsetDays * 864e5).toISOString().slice(0, 10);
4508
+ var countEach = (keys, count2) => (
4509
+ // SAFETY: the entries cover every key of the record.
4510
+ Object.fromEntries(keys.toSorted().map((key) => [key, count2(key)]))
4511
+ );
3844
4512
 
3845
4513
  // src/insights/senders/bounce-watch.ts
4514
+ var maxBounceRate = z25.number().min(0).max(1);
3846
4515
  var input21 = z25.object({
3847
- from: dayInput2("First day to count"),
4516
+ ...rangeFields,
3848
4517
  include_senders: z25.boolean().default(true).describe(
3849
4518
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
3850
4519
  ),
4520
+ max_bounce_rate: maxBounceRate.default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
3851
4521
  max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
3852
4522
  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"),
3853
- min_sent: z25.number().int().min(0).default(100).describe("A campaign with fewer sends than this is too small to judge"),
3854
- threshold: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
3855
- to: dayInput2("Last day to count")
4523
+ min_sent: z25.number().int().min(0).default(100).describe(
4524
+ "A campaign or sender with fewer sends than this is too small to judge"
4525
+ ),
4526
+ threshold: renamed("max_bounce_rate", maxBounceRate),
4527
+ statuses: statusesInput(["active"])
3856
4528
  });
3857
4529
  var countsOf2 = (bounced, sent) => ({
4530
+ ...measure2(bounced, sent),
3858
4531
  bounced,
3859
4532
  interval: wilson(bounced, sent),
3860
- rate: rate(bounced, sent),
3861
4533
  sent
3862
4534
  });
3863
4535
  var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
@@ -3880,13 +4552,23 @@ var senderReader = (context, range) => {
3880
4552
  };
3881
4553
  };
3882
4554
  var sendersOver = async (context, campaign, options) => {
3883
- const senders2 = await readCampaignSenders(context, campaign, options.max);
4555
+ const senders2 = await readCampaignSenders(
4556
+ context,
4557
+ campaign,
4558
+ options.max,
4559
+ "max_senders_per_campaign"
4560
+ );
3884
4561
  const read = await mapConcurrent(senders2, async (sender) => ({
3885
4562
  counts: await options.read(sender.ref),
3886
4563
  sender
3887
4564
  }));
4565
+ for (const { counts, sender } of read) {
4566
+ options.seen[counts === null ? "unread" : "read"].add(
4567
+ sender.address ?? sender.name ?? sender.ref
4568
+ );
4569
+ }
3888
4570
  const over = read.flatMap(
3889
- ({ counts, sender }) => counts !== null && isOver(counts, options.threshold) ? [
4571
+ ({ counts, sender }) => counts !== null && counts.sent >= options.minSent && isOver(counts, options.threshold) ? [
3890
4572
  {
3891
4573
  ...counts,
3892
4574
  address: sender.address,
@@ -3919,20 +4601,20 @@ var bounceWatch = defineInsight({
3919
4601
  next: "Use domain_health on the senders named here, and settings_audit on the campaigns over the threshold.",
3920
4602
  run: async (context, options) => {
3921
4603
  const { outbound } = context;
3922
- const { min_sent: minSent, threshold } = options;
3923
- const range = { from: options.from, to: options.to };
3924
- const campaigns = await readCapped3(
4604
+ const { max_bounce_rate: threshold, min_sent: minSent } = options;
4605
+ const range = rangeOf(options.from, options.to);
4606
+ const campaigns = await readCampaigns(
3925
4607
  context,
3926
- (cap) => outbound.campaigns.listAll({ max: cap }),
3927
- options.max_campaigns,
3928
- "campaigns"
4608
+ options.statuses,
4609
+ options.max_campaigns
3929
4610
  );
3930
4611
  const withSenders = campaigns.length > 0 && canCheckSenders(context, options.include_senders);
3931
4612
  const read = senderReader(context, range);
4613
+ const seen = { read: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() };
3932
4614
  const overBy = [];
3933
4615
  const tooFewSends = [];
3934
4616
  const unknown = [];
3935
- const counted = [];
4617
+ const counted2 = [];
3936
4618
  const rows = await mapConcurrent(campaigns, async (campaign) => ({
3937
4619
  campaign,
3938
4620
  row: context.rows(await outbound.campaign(campaign.ref).stats(range))[0]
@@ -3941,13 +4623,14 @@ var bounceWatch = defineInsight({
3941
4623
  const counts = known(row);
3942
4624
  const entry = {
3943
4625
  campaign: campaign.ref,
4626
+ campaignName: campaign.name,
3944
4627
  name: campaign.name,
3945
4628
  status: campaign.status
3946
4629
  };
3947
4630
  if (counts === null) {
3948
4631
  unknown.push({ ...entry, reason: whyUnknown(row) });
3949
4632
  } else if (counts.sent < minSent || counts.sent === 0) {
3950
- counted.push(counts);
4633
+ counted2.push(counts);
3951
4634
  tooFewSends.push({
3952
4635
  ...entry,
3953
4636
  ...counts,
@@ -3955,14 +4638,14 @@ var bounceWatch = defineInsight({
3955
4638
  senders: null
3956
4639
  });
3957
4640
  } else {
3958
- counted.push(counts);
4641
+ counted2.push(counts);
3959
4642
  if (isOver(counts, threshold)) {
3960
4643
  overBy.push({
3961
4644
  campaign,
3962
4645
  entry: {
3963
4646
  ...entry,
3964
4647
  ...counts,
3965
- finding: `${counts.bounced} of ${counts.sent} sends bounced (${counts.rate}), over the ${threshold} threshold.`,
4648
+ finding: `${counts.bounced} of ${counts.sent} sends bounced (${percent(counts.rate)}), over the ${percent(threshold)} threshold.`,
3966
4649
  senders: null
3967
4650
  }
3968
4651
  });
@@ -3975,23 +4658,32 @@ var bounceWatch = defineInsight({
3975
4658
  ...entry,
3976
4659
  senders: await sendersOver(context, campaign, {
3977
4660
  max: options.max_senders_per_campaign,
4661
+ minSent,
3978
4662
  read,
4663
+ seen,
3979
4664
  threshold
3980
4665
  })
3981
4666
  } : entry
3982
4667
  );
3983
- const bounced = total(counted.map((each) => each.bounced));
3984
- const sent = total(counted.map((each) => each.sent));
4668
+ if (seen.unread.size > 0) {
4669
+ context.note(
4670
+ `No sent or bounce count could be read for ${seen.unread.size === 1 ? "1 sender, so it was" : `${seen.unread.size} senders, so they were`} not checked: ${[...seen.unread].join(", ")}.`
4671
+ );
4672
+ }
4673
+ const bounced = total(counted2.map((each) => each.bounced));
4674
+ const sent = total(counted2.map((each) => each.sent));
3985
4675
  const byRate2 = (left, right) => (right.rate ?? -1) - (left.rate ?? -1);
3986
4676
  const answer = {
4677
+ maxBounceRate: threshold,
3987
4678
  minSent,
3988
4679
  over: over.toSorted(byRate2),
4680
+ sendersRead: withSenders ? seen.read.size : null,
3989
4681
  threshold,
3990
4682
  tooFewSends: tooFewSends.toSorted(byRate2),
3991
4683
  totals: {
3992
4684
  bounced,
3993
4685
  campaigns: campaigns.length,
3994
- clean: counted.length - over.length - tooFewSends.length,
4686
+ clean: counted2.length - over.length - tooFewSends.length,
3995
4687
  over: over.length,
3996
4688
  rate: rate(bounced, sent),
3997
4689
  sent,
@@ -4006,11 +4698,13 @@ var bounceWatch = defineInsight({
4006
4698
 
4007
4699
  // src/insights/senders/domain-health.ts
4008
4700
  import { z as z26 } from "zod";
4701
+ var maxSpamRate = z26.number().min(0).max(1);
4009
4702
  var input22 = z26.object({
4010
4703
  max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
4011
- spam_rate_threshold: z26.number().min(0).max(1).default(0.1).describe(
4704
+ max_spam_rate: maxSpamRate.default(0.1).describe(
4012
4705
  "A domain whose warmup emails land in spam more often than this share is high risk"
4013
- )
4706
+ ),
4707
+ spam_rate_threshold: renamed("max_spam_rate", maxSpamRate)
4014
4708
  });
4015
4709
  var RISK_ORDER = ["high", "medium", "low", "unknown"];
4016
4710
  var pooledWarmup = (checked) => {
@@ -4020,6 +4714,7 @@ var pooledWarmup = (checked) => {
4020
4714
  });
4021
4715
  if (reported.length === 0) {
4022
4716
  return {
4717
+ ...measure2(null, null),
4023
4718
  interval: null,
4024
4719
  mailboxes: 0,
4025
4720
  sent: null,
@@ -4029,12 +4724,14 @@ var pooledWarmup = (checked) => {
4029
4724
  }
4030
4725
  const sent = reported.reduce((sum, each) => sum + each.sent, 0);
4031
4726
  const spam = reported.reduce((sum, each) => sum + each.spam, 0);
4727
+ const measured2 = measure2(spam, sent);
4032
4728
  return {
4729
+ ...measured2,
4033
4730
  interval: wilson(spam, sent),
4034
4731
  mailboxes: reported.length,
4035
4732
  sent,
4036
4733
  spam,
4037
- spamRate: rate(spam, sent)
4734
+ spamRate: measured2.rate
4038
4735
  };
4039
4736
  };
4040
4737
  var missingChecks = (checked, warmup) => [
@@ -4045,33 +4742,36 @@ var missingChecks = (checked, warmup) => [
4045
4742
  ...checked.every(({ health }) => health.blacklisted === null) ? ["blocklist"] : [],
4046
4743
  ...warmup.mailboxes === 0 ? ["warmup"] : []
4047
4744
  ];
4048
- var CHECKS3 = DNS_RECORDS.length + 3;
4049
4745
  var reportFor = (domain, checked, threshold) => {
4050
4746
  const failing = DNS_RECORDS.filter(
4051
4747
  (record) => checked.some(({ health }) => health.dns[record] === false)
4052
4748
  );
4053
- const blacklisted = checked.filter(
4054
- ({ health }) => health.blacklisted === true
4055
- ).length;
4749
+ const warmup = pooledWarmup(checked);
4750
+ const notReported = missingChecks(checked, warmup);
4751
+ const blacklisted = notReported.includes("blocklist") ? null : checked.filter(({ health }) => health.blacklisted === true).length;
4056
4752
  const disconnected = checked.filter(
4057
4753
  ({ health }) => health.connected === false
4058
4754
  ).length;
4059
- const warmup = pooledWarmup(checked);
4060
4755
  const authFailing = failing.filter((record) => record !== "dmarc");
4061
- const spamHigh = warmup.spamRate !== null && warmup.spamRate > threshold;
4756
+ const spamHigh = warmup.rate !== null && warmup.rate > threshold;
4062
4757
  const high = [
4063
- ...blacklisted > 0 ? [`${blacklisted} of ${checked.length} mailboxes are on a block list`] : [],
4758
+ ...(blacklisted ?? 0) > 0 ? [
4759
+ `${blacklisted} of ${plural(checked.length, "mailbox", "mailboxes")} ${noun(blacklisted ?? 0, "is", "are")} on a block list`
4760
+ ] : [],
4064
4761
  ...authFailing.length > 0 ? [`${authFailing.join(", ").toUpperCase()} failing`] : [],
4065
4762
  ...spamHigh ? [
4066
- `${warmup.spam} of ${warmup.sent} warmup emails landed in spam (${warmup.spamRate}, over ${threshold})`
4763
+ `${warmup.spam} of ${warmup.sent} warmup emails landed in spam (${percent(warmup.rate)}, over ${percent(threshold)})`
4067
4764
  ] : []
4068
4765
  ];
4069
4766
  const medium = [
4070
4767
  ...failing.includes("dmarc") ? ["DMARC failing"] : [],
4071
- ...disconnected > 0 ? [`${disconnected} of ${checked.length} mailboxes are disconnected`] : []
4768
+ ...disconnected > 0 ? [
4769
+ `${disconnected} of ${plural(checked.length, "mailbox", "mailboxes")} ${noun(disconnected, "is", "are")} disconnected`
4770
+ ] : []
4072
4771
  ];
4073
- const notReported = missingChecks(checked, warmup);
4074
- const calm = notReported.length === CHECKS3 ? "unknown" : "low";
4772
+ const calm = DNS_RECORDS.every(
4773
+ (record) => notReported.includes(record)
4774
+ ) ? "unknown" : "low";
4075
4775
  const lesser = medium.length > 0 ? "medium" : calm;
4076
4776
  return {
4077
4777
  blacklisted,
@@ -4093,7 +4793,7 @@ var reportFor = (domain, checked, threshold) => {
4093
4793
  warmup
4094
4794
  };
4095
4795
  };
4096
- var worstFirst2 = (left, right) => RISK_ORDER.indexOf(left.risk) - RISK_ORDER.indexOf(right.risk) || right.reasons.length - left.reasons.length || (right.warmup.spamRate ?? -1) - (left.warmup.spamRate ?? -1) || left.domain.localeCompare(right.domain);
4796
+ var worstFirst2 = (left, right) => RISK_ORDER.indexOf(left.risk) - RISK_ORDER.indexOf(right.risk) || right.reasons.length - left.reasons.length || (right.warmup.rate ?? -1) - (left.warmup.rate ?? -1) || left.domain.localeCompare(right.domain);
4097
4797
  var seatRank = (seat) => {
4098
4798
  if (seat.connected === false) {
4099
4799
  return 0;
@@ -4101,27 +4801,24 @@ var seatRank = (seat) => {
4101
4801
  return seat.connected === null ? 1 : 2;
4102
4802
  };
4103
4803
  var domainHealth = defineInsight({
4104
- 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 nothing reported has the risk `unknown`, not `low`.",
4804
+ 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`.",
4105
4805
  inputSchema: input22,
4106
4806
  key: "domainHealth",
4107
4807
  name: "domain_health",
4108
4808
  needs: ["senders.list", "senders.health"],
4109
4809
  next: "Use warmup_readiness to see which mailboxes of a risky domain are not ready, or bounce_watch to see whether bounces already rose.",
4110
- run: async (context, { max_senders: maxSenders, spam_rate_threshold: threshold }) => {
4111
- const { outbound } = context;
4112
- const senders2 = await readCapped3(
4113
- context,
4114
- (cap) => outbound.senders.listAll({ max: cap }),
4115
- maxSenders,
4116
- "senders"
4117
- );
4810
+ run: async (context, { max_senders: maxSenders, max_spam_rate: threshold }) => {
4811
+ const { items: senders2 } = await readSenders(context, maxSenders);
4118
4812
  const byDomain = /* @__PURE__ */ new Map();
4119
4813
  const linkedinSeats = [];
4120
4814
  const mailboxesWithoutDomain = [];
4121
- const checks = await mapConcurrent(senders2, async (sender) => ({
4122
- health: context.one(await outbound.sender(sender.ref).health()),
4815
+ const read = await mapConcurrent(senders2, async (sender) => ({
4816
+ health: await readHealth(context, sender),
4123
4817
  sender
4124
4818
  }));
4819
+ const checks = read.flatMap(
4820
+ ({ health, sender }) => health === null ? [] : [{ health, sender }]
4821
+ );
4125
4822
  for (const { health, sender } of checks) {
4126
4823
  const domain = health.domain ?? domainOf2(sender.address);
4127
4824
  if (sender.kind === "linkedin") {
@@ -4143,7 +4840,7 @@ var domainHealth = defineInsight({
4143
4840
  }
4144
4841
  }
4145
4842
  const domains = [...byDomain].map(([domain, checked]) => reportFor(domain, checked, threshold)).toSorted(worstFirst2);
4146
- const count = (risk) => domains.filter((domain) => domain.risk === risk).length;
4843
+ const count2 = (risk) => domains.filter((domain) => domain.risk === risk).length;
4147
4844
  const answer = {
4148
4845
  domains,
4149
4846
  linkedinSeats: linkedinSeats.toSorted(
@@ -4152,12 +4849,12 @@ var domainHealth = defineInsight({
4152
4849
  mailboxesWithoutDomain,
4153
4850
  totals: {
4154
4851
  domains: domains.length,
4155
- high: count("high"),
4852
+ high: count2("high"),
4156
4853
  linkedinSeats: linkedinSeats.length,
4157
- low: count("low"),
4158
- medium: count("medium"),
4159
- senders: senders2.length,
4160
- unknown: count("unknown")
4854
+ low: count2("low"),
4855
+ medium: count2("medium"),
4856
+ senders: checks.length,
4857
+ unknown: count2("unknown")
4161
4858
  }
4162
4859
  };
4163
4860
  return answer;
@@ -4166,40 +4863,8 @@ var domainHealth = defineInsight({
4166
4863
 
4167
4864
  // src/insights/senders/sender-capacity.ts
4168
4865
  import { z as z27 } from "zod";
4169
- var input23 = z27.object({
4170
- days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
4171
- max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
4172
- "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
4173
- ),
4174
- max_senders: z27.number().int().min(1).max(1e3).default(200).describe(
4175
- "The most senders to read for the workspace, and for each campaign"
4176
- )
4177
- });
4178
- var limitsOf = (senders2) => senders2.map((sender) => sender.dailyLimit);
4179
- var capacityOf = (senders2) => {
4180
- const active = senders2.filter((sender) => sender.status === "active");
4181
- const withLimit = active.filter((sender) => sender.dailyLimit !== null);
4182
- const ofKind = (kind) => total(limitsOf(active.filter((sender) => sender.kind === kind)));
4183
- return {
4184
- activeSenders: active.length,
4185
- daily: total(limitsOf(active)),
4186
- inactiveSenders: senders2.length - active.length,
4187
- linkedinDaily: ofKind("linkedin"),
4188
- mailboxDaily: ofKind("mailbox"),
4189
- withLimit: withLimit.length,
4190
- withoutLimit: active.length - withLimit.length
4191
- };
4192
- };
4193
- var readOne = async (context, campaign, maxSenders) => {
4194
- const { capabilities } = context.outbound;
4195
- const settings = capabilities["campaigns.settings"] ? context.one(await context.outbound.campaign(campaign.ref).settings()) : null;
4196
- return {
4197
- campaign,
4198
- dailyLimit: settings?.dailyLimit ?? null,
4199
- // The senders are only compared with the campaign's own limit.
4200
- senders: settings !== null && capabilities["senders.byCampaign"] ? await readCampaignSenders(context, campaign, maxSenders) : null
4201
- };
4202
- };
4866
+
4867
+ // src/insights/senders/capacity-sends.ts
4203
4868
  var dailyRows = async (context, campaigns, range) => {
4204
4869
  const { outbound } = context;
4205
4870
  const { capabilities } = outbound;
@@ -4233,7 +4898,37 @@ var dailyRows = async (context, campaigns, range) => {
4233
4898
  );
4234
4899
  return { rows, scope: "campaigns" };
4235
4900
  };
4236
- var readSends = async (context, campaigns, days) => {
4901
+ var UNTOLD = "Capacity in use left out: some sends may come from senders not counted in capacity (inactive, with no daily limit, or past max_senders), and they could not be told apart.";
4902
+ var uncountedSends = async (context, senders2, window) => {
4903
+ const others = senders2.items.filter(
4904
+ (sender) => sender.status !== "active" || sender.dailyLimit === null
4905
+ );
4906
+ if (!senders2.capped && others.length === 0) {
4907
+ return 0;
4908
+ }
4909
+ const untold = senders2.capped || window.scope !== "workspace" || context.outbound.capabilities["stats.bySender"] === false;
4910
+ if (!untold && !window.split) {
4911
+ context.note(
4912
+ `Capacity in use left out: ${others.length} inactive or unlimited ${others.length === 1 ? "sender" : "senders"} may have sent some of these messages. Pass split_uncounted: true to read their sends (1 request each).`
4913
+ );
4914
+ return null;
4915
+ }
4916
+ const each = untold ? [null] : await mapConcurrent(
4917
+ others,
4918
+ async (sender) => total(
4919
+ context.rows(
4920
+ await context.outbound.sender(sender.ref).stats({ from: window.from, to: window.to })
4921
+ ).map((row) => row.sent)
4922
+ )
4923
+ );
4924
+ const sent = total(each) ?? 0;
4925
+ if (each.includes(null) || sent > window.sent) {
4926
+ context.note(UNTOLD);
4927
+ return null;
4928
+ }
4929
+ return sent;
4930
+ };
4931
+ var readSends = async (context, campaigns, days, senders2, split) => {
4237
4932
  const range = {
4238
4933
  from: dayFrom(context.now, -days),
4239
4934
  to: dayFrom(context.now, -1)
@@ -4242,8 +4937,17 @@ var readSends = async (context, campaigns, days) => {
4242
4937
  if (read === null) {
4243
4938
  return null;
4244
4939
  }
4245
- const sent = total(read.rows.map((row) => row.sent));
4246
- const reported = read.rows.flatMap(
4940
+ const rows = read.rows.filter(
4941
+ (row) => row.date === null || row.date >= range.from && row.date <= range.to
4942
+ );
4943
+ const sent = total(rows.map((row) => row.sent));
4944
+ const fromUncounted = sent === null ? null : await uncountedSends(context, senders2, {
4945
+ ...range,
4946
+ scope: read.scope,
4947
+ sent,
4948
+ split
4949
+ });
4950
+ const reported = rows.flatMap(
4247
4951
  (row) => row.date === null || row.sent === null ? [] : [row.date]
4248
4952
  );
4249
4953
  return {
@@ -4251,10 +4955,55 @@ var readSends = async (context, campaigns, days) => {
4251
4955
  averageDaily: sent === null ? null : round(sent / days),
4252
4956
  days,
4253
4957
  daysWithData: new Set(reported).size,
4958
+ fromUncounted,
4254
4959
  scope: read.scope,
4255
4960
  total: sent
4256
4961
  };
4257
4962
  };
4963
+
4964
+ // src/insights/senders/sender-capacity.ts
4965
+ var input23 = z27.object({
4966
+ days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
4967
+ max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
4968
+ "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
4969
+ ),
4970
+ max_senders: z27.number().int().min(1).max(1e3).default(200).describe(
4971
+ "The most senders to read for the workspace, and for each campaign"
4972
+ ),
4973
+ split_uncounted: z27.boolean().default(false).describe(
4974
+ "Read the stats of each inactive or unlimited sender (1 request each) so utilization can leave their sends out. Off, utilization is null whenever such a sender exists."
4975
+ )
4976
+ });
4977
+ var limitsOf = (senders2) => senders2.map((sender) => sender.dailyLimit);
4978
+ var capacityOf = (senders2) => {
4979
+ const active = senders2.filter((sender) => sender.status === "active");
4980
+ const withLimit = active.filter((sender) => sender.dailyLimit !== null);
4981
+ const ofKind = (kind) => total(limitsOf(active.filter((sender) => sender.kind === kind)));
4982
+ return {
4983
+ activeSenders: active.length,
4984
+ daily: total(limitsOf(active)),
4985
+ inactiveSenders: senders2.length - active.length,
4986
+ linkedinDaily: ofKind("linkedin"),
4987
+ mailboxDaily: ofKind("mailbox"),
4988
+ withLimit: withLimit.length,
4989
+ withoutLimit: active.length - withLimit.length
4990
+ };
4991
+ };
4992
+ var readOne = async (context, campaign, maxSenders) => {
4993
+ const { capabilities } = context.outbound;
4994
+ const settings = capabilities["campaigns.settings"] ? context.one(await context.outbound.campaign(campaign.ref).settings()) : null;
4995
+ return {
4996
+ campaign,
4997
+ dailyLimit: settings?.dailyLimit ?? null,
4998
+ // The senders are only compared with the campaign's own limit.
4999
+ senders: settings !== null && capabilities["senders.byCampaign"] ? await readCampaignSenders(
5000
+ context,
5001
+ campaign,
5002
+ maxSenders,
5003
+ "max_senders"
5004
+ ) : null
5005
+ };
5006
+ };
4258
5007
  var shortfallOf = (read) => {
4259
5008
  const active = (read.senders ?? []).filter(
4260
5009
  (sender) => sender.status === "active"
@@ -4279,7 +5028,7 @@ var shortfallOf = (read) => {
4279
5028
  };
4280
5029
  var askOf = (reads) => {
4281
5030
  const limits = reads.map((read) => read.dailyLimit);
4282
- const withLimit = limits.filter((limit2) => limit2 !== null).length;
5031
+ const withLimit = limits.filter((limit3) => limit3 !== null).length;
4283
5032
  return {
4284
5033
  campaigns: reads.length,
4285
5034
  daily: total(limits),
@@ -4302,28 +5051,29 @@ var findingOf = (capacity, ask, sends) => {
4302
5051
  }
4303
5052
  if (sends !== null && sends.averageDaily !== null) {
4304
5053
  parts.push(
4305
- `${sends.averageDaily} a day were sent on average over the last ${sends.days} days.`
5054
+ `${spoken(sends.averageDaily)} a day were sent on average over the last ${sends.days} days${(sends.fromUncounted ?? 0) > 0 ? `; senders not counted in capacity sent ${sends.fromUncounted} of the ${sends.total}` : ""}.`
4306
5055
  );
4307
5056
  }
4308
5057
  return parts.join(" ");
4309
5058
  };
4310
5059
  var senderCapacity = defineInsight({
4311
- 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. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
5060
+ 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.",
4312
5061
  inputSchema: input23,
4313
5062
  key: "senderCapacity",
4314
5063
  name: "sender_capacity",
4315
5064
  needs: ["senders.list"],
4316
5065
  next: "Use sender_load to see which senders are shared by too many campaigns, or warmup_readiness before raising a sender's limit.",
4317
- run: async (context, { days, max_campaigns: maxCampaigns, max_senders: maxSenders }) => {
5066
+ run: async (context, {
5067
+ days,
5068
+ max_campaigns: maxCampaigns,
5069
+ max_senders: maxSenders,
5070
+ split_uncounted: split
5071
+ }) => {
4318
5072
  const { outbound } = context;
4319
5073
  const { capabilities } = outbound;
4320
- const senders2 = await readCapped3(
4321
- context,
4322
- (cap) => outbound.senders.listAll({ max: cap }),
4323
- maxSenders,
4324
- "senders"
4325
- );
4326
- const campaigns = await readCampaigns2(context, ["active"], maxCampaigns);
5074
+ const listed = await readSenders(context, maxSenders);
5075
+ const senders2 = listed.items;
5076
+ const campaigns = await readCampaigns(context, ["active"], maxCampaigns);
4327
5077
  const reads = await mapConcurrent(
4328
5078
  campaigns,
4329
5079
  (campaign) => readOne(context, campaign, maxSenders)
@@ -4341,7 +5091,7 @@ var senderCapacity = defineInsight({
4341
5091
  }
4342
5092
  const capacity = capacityOf(senders2);
4343
5093
  const ask = hasSettings ? askOf(reads) : null;
4344
- const sends = await readSends(context, campaigns, days);
5094
+ const sends = await readSends(context, campaigns, days, listed, split);
4345
5095
  const shortfalls = reads.map(shortfallOf);
4346
5096
  const answer = {
4347
5097
  ask,
@@ -4353,7 +5103,10 @@ var senderCapacity = defineInsight({
4353
5103
  (each) => each === null || each === "unchecked" ? [] : [each]
4354
5104
  ).toSorted((left, right) => right.shortBy - left.shortBy) : null,
4355
5105
  uncheckedCampaigns: canCompare ? shortfalls.filter((each) => each === "unchecked").length : null,
4356
- utilization: rate(sends?.averageDaily ?? null, capacity.daily)
5106
+ utilization: rate(
5107
+ sends?.total === null || sends?.total === void 0 || sends.fromUncounted === null ? null : (sends.total - sends.fromUncounted) / sends.days,
5108
+ capacity.daily
5109
+ )
4357
5110
  };
4358
5111
  return answer;
4359
5112
  }
@@ -4367,7 +5120,7 @@ var input24 = z28.object({
4367
5120
  max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
4368
5121
  "The most senders to read for the workspace, and for each campaign"
4369
5122
  ),
4370
- statuses: statusesInput
5123
+ statuses: statusesInput(["active"])
4371
5124
  });
4372
5125
  var loaded = (sender) => ({
4373
5126
  address: sender.address,
@@ -4386,10 +5139,11 @@ var riskOf = (campaign, senders2) => {
4386
5139
  if (issues.length === 0) {
4387
5140
  return null;
4388
5141
  }
4389
- const count = senders2.length === 1 ? "1 sender" : `${senders2.length} senders`;
5142
+ const count2 = senders2.length === 1 ? "1 sender" : `${senders2.length} senders`;
4390
5143
  return {
4391
5144
  campaign: campaign.ref,
4392
- finding: inactive.length > 0 ? `${campaign.name} has ${count}, ${inactive.length} of them not active.` : `${campaign.name} has ${count}.`,
5145
+ campaignName: campaign.name,
5146
+ finding: inactive.length > 0 ? `${campaign.name} has ${count2}, ${inactive.length} of them not active.` : `${campaign.name} has ${count2}.`,
4393
5147
  inactive: inactive.map(loaded),
4394
5148
  issues,
4395
5149
  name: campaign.name,
@@ -4404,15 +5158,9 @@ var senderLoad = defineInsight({
4404
5158
  needs: ["senders.list", "senders.byCampaign"],
4405
5159
  next: "Use sender_capacity to see whether the senders can cover the campaigns' daily limits, or warmup_readiness for the senders that are not active.",
4406
5160
  run: async (context, options) => {
4407
- const { outbound } = context;
4408
5161
  const allowed = options.max_campaigns_per_sender;
4409
- const senders2 = await readCapped3(
4410
- context,
4411
- (cap) => outbound.senders.listAll({ max: cap }),
4412
- options.max_senders,
4413
- "senders"
4414
- );
4415
- const campaigns = await readCampaigns2(
5162
+ const { items: senders2 } = await readSenders(context, options.max_senders);
5163
+ const campaigns = await readCampaigns(
4416
5164
  context,
4417
5165
  options.statuses,
4418
5166
  options.max_campaigns
@@ -4422,7 +5170,12 @@ var senderLoad = defineInsight({
4422
5170
  const risks = [];
4423
5171
  const read = await mapConcurrent(campaigns, async (campaign) => ({
4424
5172
  campaign,
4425
- own: await readCampaignSenders(context, campaign, options.max_senders)
5173
+ own: await readCampaignSenders(
5174
+ context,
5175
+ campaign,
5176
+ options.max_senders,
5177
+ "max_senders"
5178
+ )
4426
5179
  }));
4427
5180
  for (const { campaign, own } of read) {
4428
5181
  const risk = riskOf(campaign, own);
@@ -4478,13 +5231,13 @@ var input25 = z29.object({
4478
5231
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
4479
5232
  ),
4480
5233
  max_daily_limit_per_sender: z29.number().min(1).default(50).describe(
4481
- "A campaign's daily limit should not exceed this many sends per attached sender"
5234
+ "The sends a day assumed for an attached sender when the senders' own daily limits are not reported"
4482
5235
  ),
4483
5236
  max_senders_per_campaign: z29.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
4484
5237
  max_window_hours: z29.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
4485
5238
  min_gap_minutes: z29.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
4486
5239
  min_window_hours: z29.number().min(0).max(24).default(2).describe("A sending window shorter than this many hours is flagged"),
4487
- statuses: statusesInput
5240
+ statuses: statusesInput(["active"])
4488
5241
  });
4489
5242
  var SEVERITY2 = {
4490
5243
  click_tracking: "medium",
@@ -4500,7 +5253,7 @@ var SEVERITY2 = {
4500
5253
  window_long: "medium",
4501
5254
  window_short: "low"
4502
5255
  };
4503
- var ORDER2 = ["high", "medium", "low"];
5256
+ var ORDER3 = ["high", "medium", "low"];
4504
5257
  var when = (hit, check, finding, value = null) => hit ? [{ check, finding, severity: SEVERITY2[check], value }] : [];
4505
5258
  var minutesOf2 = (clock) => Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3));
4506
5259
  var hoursOf = (window) => {
@@ -4535,13 +5288,13 @@ var scheduleFindings = ({ bars, settings }) => {
4535
5288
  ...when(
4536
5289
  longest > bars.maxWindowHours,
4537
5290
  "window_long",
4538
- `A sending window is ${longest} hours long, over ${bars.maxWindowHours}.`,
5291
+ `A sending window is ${spoken(longest)} hours long, over ${bars.maxWindowHours}.`,
4539
5292
  longest
4540
5293
  ),
4541
5294
  ...when(
4542
5295
  shortest < bars.minWindowHours,
4543
5296
  "window_short",
4544
- `A sending window is ${shortest} hours long, under ${bars.minWindowHours}.`,
5297
+ `A sending window is ${spoken(shortest)} hours long, under ${bars.minWindowHours}.`,
4545
5298
  shortest
4546
5299
  ),
4547
5300
  ...when(
@@ -4554,7 +5307,9 @@ var scheduleFindings = ({ bars, settings }) => {
4554
5307
  var limitFindings = (audit2) => {
4555
5308
  const { bars, campaign, senders: senders2, settings, today } = audit2;
4556
5309
  const { dailyLimit, endDate, gapMinutes } = settings;
4557
- const allowed = (senders2 ?? 0) * bars.maxPerSender;
5310
+ const count2 = senders2?.length ?? 0;
5311
+ const own = senders2?.every((sender) => sender.dailyLimit !== null) === true ? senders2.reduce((sum, sender) => sum + (sender.dailyLimit ?? 0), 0) : null;
5312
+ const allowed = own ?? count2 * bars.maxPerSender;
4558
5313
  return [
4559
5314
  ...when(
4560
5315
  dailyLimit === null,
@@ -4564,7 +5319,7 @@ var limitFindings = (audit2) => {
4564
5319
  ...when(
4565
5320
  dailyLimit !== null && allowed > 0 && dailyLimit > allowed,
4566
5321
  "limit_over_senders",
4567
- `The daily limit of ${dailyLimit} is over ${bars.maxPerSender} a day for each of its ${senders2} senders (${allowed}).`,
5322
+ own === null ? `The daily limit of ${dailyLimit} is over ${allowed} a day: its ${count2} senders do not all report a daily limit, so ${bars.maxPerSender} each was assumed.` : `The daily limit of ${dailyLimit} is over the ${own} a day its ${count2} senders can send.`,
4568
5323
  dailyLimit
4569
5324
  ),
4570
5325
  ...when(
@@ -4605,32 +5360,20 @@ var audit = (subject) => ({
4605
5360
  ...limitFindings(subject),
4606
5361
  ...ruleFindings(subject)
4607
5362
  ].toSorted(
4608
- (left, right) => ORDER2.indexOf(left.severity) - ORDER2.indexOf(right.severity)
5363
+ (left, right) => ORDER3.indexOf(left.severity) - ORDER3.indexOf(right.severity)
4609
5364
  ),
4610
5365
  name: subject.campaign.name,
4611
5366
  status: subject.campaign.status
4612
5367
  });
4613
5368
  var countOf2 = (campaign, severity) => campaign.findings.filter((finding) => finding.severity === severity).length;
4614
5369
  var worstFirst3 = (left, right) => countOf2(right, "high") - countOf2(left, "high") || countOf2(right, "medium") - countOf2(left, "medium") || right.findings.length - left.findings.length;
4615
- var countChecks = (campaigns) => {
4616
- const count = (check) => campaigns.filter(
5370
+ var countChecks = (campaigns) => countEach(
5371
+ // SAFETY: SEVERITY has exactly one key per check.
5372
+ Object.keys(SEVERITY2),
5373
+ (check) => campaigns.filter(
4617
5374
  (campaign) => campaign.findings.some((finding) => finding.check === check)
4618
- ).length;
4619
- return {
4620
- click_tracking: count("click_tracking"),
4621
- end_date_passed: count("end_date_passed"),
4622
- gap_short: count("gap_short"),
4623
- limit_over_senders: count("limit_over_senders"),
4624
- no_daily_limit: count("no_daily_limit"),
4625
- no_timezone: count("no_timezone"),
4626
- no_window: count("no_window"),
4627
- open_tracking: count("open_tracking"),
4628
- reply_does_not_stop: count("reply_does_not_stop"),
4629
- weekend: count("weekend"),
4630
- window_long: count("window_long"),
4631
- window_short: count("window_short")
4632
- };
4633
- };
5375
+ ).length
5376
+ );
4634
5377
  var settingsAudit = defineInsight({
4635
5378
  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.",
4636
5379
  inputSchema: input25,
@@ -4647,7 +5390,7 @@ var settingsAudit = defineInsight({
4647
5390
  minGapMinutes: options.min_gap_minutes,
4648
5391
  minWindowHours: options.min_window_hours
4649
5392
  };
4650
- const campaigns = await readCampaigns2(
5393
+ const campaigns = await readCampaigns(
4651
5394
  context,
4652
5395
  options.statuses,
4653
5396
  options.max_campaigns
@@ -4665,13 +5408,14 @@ var settingsAudit = defineInsight({
4665
5408
  countSenders ? readCampaignSenders(
4666
5409
  context,
4667
5410
  campaign,
4668
- options.max_senders_per_campaign
5411
+ options.max_senders_per_campaign,
5412
+ "max_senders_per_campaign"
4669
5413
  ) : null
4670
5414
  ]);
4671
5415
  return audit({
4672
5416
  bars,
4673
5417
  campaign,
4674
- senders: senders2?.length ?? null,
5418
+ senders: senders2,
4675
5419
  settings: context.one(settings),
4676
5420
  today: dayFrom(context.now, 0)
4677
5421
  });
@@ -4707,6 +5451,15 @@ var input26 = z30.object({
4707
5451
  ),
4708
5452
  min_score: z30.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
4709
5453
  });
5454
+ var READINESS_REASONS = [
5455
+ "not_active",
5456
+ "warmup_off",
5457
+ "score_low",
5458
+ "score_unknown",
5459
+ "no_daily_limit",
5460
+ "dns_failing",
5461
+ "warmup_spam_high"
5462
+ ];
4710
5463
  var healthReasons = (health, bars) => {
4711
5464
  const failing = failingDns(health);
4712
5465
  const spam = warmupSpam(health);
@@ -4721,7 +5474,7 @@ var healthReasons = (health, bars) => {
4721
5474
  ...spam !== null && spamRate !== null && spamRate > bars.maxSpamRate ? [
4722
5475
  [
4723
5476
  "warmup_spam_high",
4724
- `${spam.spam} of ${spam.sent} warmup emails landed in spam (${spamRate}, over ${bars.maxSpamRate})`
5477
+ `${spam.spam} of ${spam.sent} warmup emails landed in spam (${percent(spamRate)}, over ${percent(bars.maxSpamRate)})`
4725
5478
  ]
4726
5479
  ] : []
4727
5480
  ];
@@ -4731,7 +5484,7 @@ var mailboxReasons = (sender, score, bars) => [
4731
5484
  ...score !== null && score < bars.minScore ? [
4732
5485
  [
4733
5486
  "score_low",
4734
- `Warmup score ${score} is under ${bars.minScore}`
5487
+ `Warmup score ${spoken(score)} is under ${spoken(bars.minScore)}`
4735
5488
  ]
4736
5489
  ] : [],
4737
5490
  ...score === null ? [["score_unknown", "The vendor reports no warmup score"]] : [],
@@ -4757,18 +5510,10 @@ var judge2 = (sender, health, bars) => {
4757
5510
  warmupEnabled: sender.warmup?.enabled ?? null
4758
5511
  };
4759
5512
  };
4760
- var countReasons = (judged) => {
4761
- const count = (reason) => judged.filter((sender) => sender.reasons.includes(reason)).length;
4762
- return {
4763
- dns_failing: count("dns_failing"),
4764
- no_daily_limit: count("no_daily_limit"),
4765
- not_active: count("not_active"),
4766
- score_low: count("score_low"),
4767
- score_unknown: count("score_unknown"),
4768
- warmup_off: count("warmup_off"),
4769
- warmup_spam_high: count("warmup_spam_high")
4770
- };
4771
- };
5513
+ var countReasons = (judged) => countEach(
5514
+ READINESS_REASONS,
5515
+ (reason) => judged.filter((sender) => sender.reasons.includes(reason)).length
5516
+ );
4772
5517
  var warmupReadiness = defineInsight({
4773
5518
  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.",
4774
5519
  inputSchema: input26,
@@ -4782,25 +5527,26 @@ var warmupReadiness = defineInsight({
4782
5527
  maxSpamRate: options.max_spam_rate,
4783
5528
  minScore: options.min_score
4784
5529
  };
4785
- const senders2 = await readCapped3(
4786
- context,
4787
- (cap) => outbound.senders.listAll({ max: cap }),
4788
- options.max_senders,
4789
- "senders"
4790
- );
5530
+ const { items: senders2 } = await readSenders(context, options.max_senders);
4791
5531
  const healthChecked = options.check_health && outbound.capabilities["senders.health"];
4792
5532
  if (options.check_health && !healthChecked) {
4793
5533
  context.note(
4794
5534
  "DNS records and warmup spam were not checked: the adapter cannot read a sender's health."
4795
5535
  );
4796
5536
  }
4797
- const judged = await mapConcurrent(
4798
- senders2,
4799
- async (sender) => {
4800
- const health = healthChecked && sender.kind === "mailbox" ? context.one(await outbound.sender(sender.ref).health()) : null;
4801
- return judge2(sender, health, bars);
5537
+ if (!options.check_health && outbound.capabilities["senders.health"] && senders2.some((sender) => sender.kind === "mailbox")) {
5538
+ context.note(
5539
+ "DNS records and warmup spam were not checked, so a ready mailbox is ready on warmup alone. Pass check_health: true to check them, at 1 more request per mailbox."
5540
+ );
5541
+ }
5542
+ const each = await mapConcurrent(senders2, async (sender) => {
5543
+ if (!healthChecked || sender.kind !== "mailbox") {
5544
+ return [judge2(sender, null, bars)];
4802
5545
  }
4803
- );
5546
+ const health = await readHealth(context, sender);
5547
+ return health === null ? [] : [judge2(sender, health, bars)];
5548
+ });
5549
+ const judged = each.flat();
4804
5550
  const notReady = judged.filter((sender) => sender.reasons.length > 0).toSorted((left, right) => right.reasons.length - left.reasons.length);
4805
5551
  const answer = {
4806
5552
  byReason: countReasons(notReady),
@@ -4871,9 +5617,24 @@ var insights = () => ({
4871
5617
 
4872
5618
  // src/insights/tools.ts
4873
5619
  import { z as z32 } from "zod";
4874
- var toTool = (outbound, definition) => ({
4875
- call: async (input27) => {
5620
+ var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
5621
+ var hintFor = (next, offered) => {
5622
+ const hidden = ENTRIES.flatMap(
5623
+ (entry) => offered.has(entry.name) ? [] : [entry.name]
5624
+ );
5625
+ const kept = next.split(/(?<=\.)\s+/u).filter((sentence) => !hidden.some((name) => sentence.includes(name)));
5626
+ return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
5627
+ };
5628
+ var toTool = (outbound, definition, next) => ({
5629
+ call: async (given) => {
4876
5630
  try {
5631
+ const input27 = jsonInput(given);
5632
+ if (input27 === void 0) {
5633
+ throw new OutboundError(
5634
+ "Invalid",
5635
+ `${definition.name}: the input is not JSON`
5636
+ );
5637
+ }
4877
5638
  const result = await definition.execute(outbound, input27);
4878
5639
  return {
4879
5640
  data: {
@@ -4886,7 +5647,7 @@ var toTool = (outbound, definition) => ({
4886
5647
  provider: result.meta.provider,
4887
5648
  requests: result.meta.requests
4888
5649
  },
4889
- next: definition.next,
5650
+ next,
4890
5651
  ok: true
4891
5652
  };
4892
5653
  } catch (error) {
@@ -4896,7 +5657,7 @@ var toTool = (outbound, definition) => ({
4896
5657
  code: known2 ? error.code : "Provider",
4897
5658
  message: error instanceof Error ? error.message : String(error)
4898
5659
  },
4899
- next: known2 && error.code === "Unsupported" ? "This insight is not available with the current adapter. Try another tool." : "Check the input and try again.",
5660
+ next: known2 && error.code === "Unsupported" ? "This insight cannot answer here; the message says why. Try another tool." : "Check the input and try again.",
4900
5661
  ok: false
4901
5662
  };
4902
5663
  }
@@ -4910,10 +5671,13 @@ var toTool = (outbound, definition) => ({
4910
5671
  });
4911
5672
  var insightTools = (outbound, options = {}) => {
4912
5673
  const wanted = options.only === void 0 ? void 0 : new Set(options.only);
4913
- return ENTRIES.flatMap((definition) => {
4914
- const offered = (wanted === void 0 || wanted.has(definition.name)) && definition.needs.every((key) => outbound.capabilities[key] !== false);
4915
- return offered ? [toTool(outbound, definition)] : [];
4916
- });
5674
+ const offered = ENTRIES.filter(
5675
+ (definition) => (wanted === void 0 || wanted.has(definition.name)) && definition.needs.every((key) => outbound.capabilities[key] !== false) && (definition.lacks?.(outbound) ?? null) === null && maskedOutBy(outbound, definition) === null
5676
+ );
5677
+ const names = new Set(offered.map((definition) => definition.name));
5678
+ return offered.map(
5679
+ (definition) => toTool(outbound, definition, hintFor(definition.next, names))
5680
+ );
4917
5681
  };
4918
5682
  export {
4919
5683
  INSIGHTS,