outbound-sdk 0.2.1 → 0.5.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 (175) hide show
  1. package/README.md +2 -2
  2. package/dist/alerts/check-evaluate.d.ts +53 -0
  3. package/dist/alerts/check-measure.d.ts +100 -0
  4. package/dist/alerts/check-schema.d.ts +184 -0
  5. package/dist/alerts/check-validate.d.ts +18 -0
  6. package/dist/alerts/index.d.ts +7 -0
  7. package/dist/alerts/index.js +684 -20
  8. package/dist/alerts/plugin.d.ts +20 -3
  9. package/dist/audit/index.js +2 -2
  10. package/dist/benchmarks/index.js +5 -5
  11. package/dist/budget/index.d.ts +5 -2
  12. package/dist/budget/index.js +12 -10
  13. package/dist/cards/content.d.ts +6 -1
  14. package/dist/cards/format.d.ts +17 -2
  15. package/dist/cards/index.d.ts +1 -1
  16. package/dist/cards/index.js +298 -132
  17. package/dist/cards/parts.d.ts +9 -2
  18. package/dist/cards/render.d.ts +20 -3
  19. package/dist/chunks/{chunk-U2D34ARZ.js → chunk-2D42TQFU.js} +3 -3
  20. package/dist/chunks/{chunk-6CVZOUHB.js → chunk-3S32R2MH.js} +53 -63
  21. package/dist/chunks/chunk-4PA526S7.js +17 -0
  22. package/dist/chunks/{chunk-RCZ7ZZFU.js → chunk-5J7GGV62.js} +12 -5
  23. package/dist/chunks/chunk-6TKFISG4.js +676 -0
  24. package/dist/chunks/{chunk-AFU5E5QB.js → chunk-BK5SLY32.js} +104 -84
  25. package/dist/chunks/{chunk-VQSCHOBV.js → chunk-BLCJHP5H.js} +11 -4
  26. package/dist/chunks/{chunk-SBIZDCRY.js → chunk-BN6WCAWX.js} +7 -7
  27. package/dist/chunks/{chunk-4PSO6JEK.js → chunk-BOWXGMN3.js} +6 -21
  28. package/dist/chunks/{chunk-PURHK3JU.js → chunk-EHSJGQ5K.js} +8 -8
  29. package/dist/chunks/{chunk-IPUYZD4O.js → chunk-GFDNRWR3.js} +1 -1
  30. package/dist/chunks/chunk-HPNGSG5E.js +51 -0
  31. package/dist/chunks/chunk-HWHI4LFY.js +102 -0
  32. package/dist/chunks/{chunk-E7JHLNLG.js → chunk-J7DDZ4C2.js} +15 -2
  33. package/dist/chunks/{chunk-DJ2IUQEU.js → chunk-JWGSB7PT.js} +6 -6
  34. package/dist/chunks/{chunk-R3Y56YVF.js → chunk-OLPMBRXM.js} +4 -3
  35. package/dist/chunks/{chunk-YOTW5ESM.js → chunk-PQSTQKRD.js} +2 -2
  36. package/dist/chunks/chunk-PTZO4QXR.js +15 -0
  37. package/dist/chunks/{chunk-LVYG7XZJ.js → chunk-QAKJ76HB.js} +1 -1
  38. package/dist/chunks/chunk-QGRZDTX4.js +26 -0
  39. package/dist/chunks/chunk-WGW3ROLY.js +18 -0
  40. package/dist/chunks/{chunk-XC6CZP73.js → chunk-WH6V3YNN.js} +32 -1
  41. package/dist/chunks/{chunk-P3IJBJUI.js → chunk-X4RDBD4J.js} +296 -62
  42. package/dist/chunks/chunk-XL6LJVHJ.js +71 -0
  43. package/dist/chunks/{chunk-XNFESPZH.js → chunk-YYCT3NGV.js} +200 -39
  44. package/dist/chunks/{chunk-UAT3JSJZ.js → chunk-ZOAG2C6V.js} +2 -2
  45. package/dist/cli/bin.js +19 -30
  46. package/dist/cli/commands.d.ts +11 -0
  47. package/dist/cli/index.d.ts +3 -0
  48. package/dist/cli/index.js +18 -13
  49. package/dist/cli/mcp.d.ts +5 -0
  50. package/dist/cli/update.d.ts +15 -0
  51. package/dist/clients/index.d.ts +1 -1
  52. package/dist/clients/index.js +35 -10
  53. package/dist/clients/plugin.d.ts +9 -2
  54. package/dist/combine/index.js +7 -6
  55. package/dist/emailbison/account.d.ts +7 -0
  56. package/dist/emailbison/adapter.d.ts +5 -0
  57. package/dist/emailbison/capabilities.d.ts +78 -0
  58. package/dist/emailbison/client.d.ts +29 -0
  59. package/dist/emailbison/index.d.ts +30 -0
  60. package/dist/emailbison/index.js +1017 -0
  61. package/dist/emailbison/mail.d.ts +5 -0
  62. package/dist/emailbison/map-mail.d.ts +13 -0
  63. package/dist/emailbison/map-sequence.d.ts +12 -0
  64. package/dist/emailbison/map-stats.d.ts +47 -0
  65. package/dist/emailbison/map.d.ts +24 -0
  66. package/dist/emailbison/native-params.d.ts +5 -0
  67. package/dist/emailbison/native-workspace.d.ts +167 -0
  68. package/dist/emailbison/native.d.ts +327 -0
  69. package/dist/emailbison/stats.d.ts +4 -0
  70. package/dist/emailbison/webhooks.d.ts +2 -0
  71. package/dist/exporter/index.d.ts +5 -2
  72. package/dist/exporter/index.js +2 -2
  73. package/dist/failover/index.js +3 -3
  74. package/dist/fixtures/index.js +10 -9
  75. package/dist/heyreach/capabilities.d.ts +3 -0
  76. package/dist/heyreach/client.d.ts +2 -0
  77. package/dist/heyreach/index.js +83 -51
  78. package/dist/heyreach/map.d.ts +5 -2
  79. package/dist/identity/index.js +33 -17
  80. package/dist/identity/plugin.d.ts +2 -0
  81. package/dist/index.d.ts +2 -2
  82. package/dist/index.js +29 -25
  83. package/dist/insights/campaign.d.ts +3 -0
  84. package/dist/insights/capped.d.ts +29 -0
  85. package/dist/insights/copy/copy-audit.d.ts +2 -0
  86. package/dist/insights/copy/copy-reuse.d.ts +27 -3
  87. package/dist/insights/copy/index.d.ts +8 -8
  88. package/dist/insights/copy/reply-timing.d.ts +8 -0
  89. package/dist/insights/copy/reuse-base.d.ts +32 -0
  90. package/dist/insights/copy/shared.d.ts +39 -15
  91. package/dist/insights/copy/step-funnel.d.ts +16 -5
  92. package/dist/insights/copy/variant-test.d.ts +19 -8
  93. package/dist/insights/cost.d.ts +91 -0
  94. package/dist/insights/define.d.ts +78 -3
  95. package/dist/insights/fields.d.ts +16 -0
  96. package/dist/insights/index.d.ts +6 -4
  97. package/dist/insights/index.js +1816 -748
  98. package/dist/insights/inputs.generated.d.ts +951 -0
  99. package/dist/insights/ops/campaign-diagnosis.d.ts +3 -1
  100. package/dist/insights/ops/campaign-ranking.d.ts +15 -7
  101. package/dist/insights/ops/channel-mix.d.ts +2 -1
  102. package/dist/insights/ops/client-report.d.ts +18 -5
  103. package/dist/insights/ops/index.d.ts +8 -4
  104. package/dist/insights/ops/period-comparison.d.ts +14 -3
  105. package/dist/insights/ops/pipeline-forecast.d.ts +14 -4
  106. package/dist/insights/ops/shared.d.ts +39 -24
  107. package/dist/insights/ops/tag-rollup.d.ts +2 -1
  108. package/dist/insights/people/account-summary.d.ts +13 -0
  109. package/dist/insights/people/dropped-replies.d.ts +8 -0
  110. package/dist/insights/people/find.d.ts +7 -1
  111. package/dist/insights/people/hot-leads.d.ts +16 -1
  112. package/dist/insights/people/person-summary.d.ts +6 -0
  113. package/dist/insights/people/read.d.ts +26 -10
  114. package/dist/insights/people/suppression-check.d.ts +11 -2
  115. package/dist/insights/plugin.d.ts +26 -5
  116. package/dist/insights/ref.d.ts +6 -0
  117. package/dist/insights/registry.d.ts +30 -18
  118. package/dist/insights/run-cap.d.ts +35 -0
  119. package/dist/insights/senders/bounce-watch.d.ts +25 -8
  120. package/dist/insights/senders/capacity-sends.d.ts +22 -0
  121. package/dist/insights/senders/domain-health.d.ts +10 -4
  122. package/dist/insights/senders/index.d.ts +14 -6
  123. package/dist/insights/senders/read.d.ts +15 -14
  124. package/dist/insights/senders/sender-capacity.d.ts +5 -13
  125. package/dist/insights/senders/sender-load.d.ts +2 -0
  126. package/dist/insights/stats.d.ts +8 -0
  127. package/dist/insights/tools.d.ts +13 -2
  128. package/dist/instantly/capabilities.d.ts +13 -0
  129. package/dist/instantly/client.d.ts +2 -0
  130. package/dist/instantly/index.js +77 -49
  131. package/dist/instantly/map.d.ts +6 -2
  132. package/dist/internal/adapter.d.ts +12 -0
  133. package/dist/internal/engine/request.d.ts +5 -0
  134. package/dist/internal/entities.d.ts +3 -20
  135. package/dist/internal/errors.d.ts +44 -0
  136. package/dist/internal/fields.d.ts +1 -1
  137. package/dist/internal/json.d.ts +9 -2
  138. package/dist/internal/lists.d.ts +24 -0
  139. package/dist/internal/numbers.d.ts +8 -0
  140. package/dist/internal/outbound/collections.d.ts +4 -0
  141. package/dist/internal/outbound/create.d.ts +24 -3
  142. package/dist/internal/outbound/outbound.d.ts +18 -2
  143. package/dist/internal/outbound/validate.d.ts +4 -0
  144. package/dist/internal/outbound/walker.d.ts +3 -2
  145. package/dist/internal/plural.d.ts +12 -0
  146. package/dist/internal/renamed.d.ts +28 -0
  147. package/dist/internal/request-cap.d.ts +35 -0
  148. package/dist/internal/vocabulary.d.ts +20 -0
  149. package/dist/loader/index.js +5 -5
  150. package/dist/memory/adapter.d.ts +7 -0
  151. package/dist/memory/demo-stats.d.ts +3 -0
  152. package/dist/memory/demo.d.ts +14 -3
  153. package/dist/memory/index.d.ts +1 -0
  154. package/dist/memory/index.js +209 -104
  155. package/dist/providers/index.d.ts +92 -0
  156. package/dist/providers/index.js +3 -1
  157. package/dist/reconcile/index.js +5 -4
  158. package/dist/redact/index.js +13 -7
  159. package/dist/redact/plugin.d.ts +7 -0
  160. package/dist/smartlead/capabilities.d.ts +5 -0
  161. package/dist/smartlead/index.js +119 -66
  162. package/dist/smartlead/shared.d.ts +13 -0
  163. package/dist/sync/index.js +2 -2
  164. package/dist/tools/ai-sdk.js +10 -6
  165. package/dist/tools/campaign-tools.d.ts +1 -1
  166. package/dist/tools/claude-agent.js +10 -6
  167. package/dist/tools/index.d.ts +2 -2
  168. package/dist/tools/index.js +16 -9
  169. package/dist/tools/input-problem.d.ts +8 -0
  170. package/dist/tools/registry.d.ts +26 -2
  171. package/dist/tools/shared.d.ts +27 -1
  172. package/dist/tracing/index.js +2 -2
  173. package/dist/webhooks/index.js +22 -12
  174. package/package.json +8 -2
  175. package/dist/chunks/chunk-FKH5N47I.js +0 -40
@@ -1,38 +1,307 @@
1
+ import {
2
+ capNext,
3
+ failure,
4
+ inputProblem
5
+ } from "../chunks/chunk-HWHI4LFY.js";
6
+ import {
7
+ count,
8
+ percentOf,
9
+ plural
10
+ } from "../chunks/chunk-4PA526S7.js";
1
11
  import {
2
12
  mapConcurrent
3
13
  } from "../chunks/chunk-HZCTYL22.js";
4
14
  import {
5
- sumCounts
6
- } from "../chunks/chunk-YOTW5ESM.js";
15
+ cappedAccess,
16
+ requestCounter,
17
+ withGuard
18
+ } from "../chunks/chunk-HPNGSG5E.js";
7
19
  import {
8
- profileSlug
9
- } from "../chunks/chunk-NAWZ73QS.js";
20
+ noun,
21
+ shownKey
22
+ } from "../chunks/chunk-PTZO4QXR.js";
23
+ import {
24
+ sumCounts
25
+ } from "../chunks/chunk-PQSTQKRD.js";
10
26
  import {
11
27
  campaignStatusSchema,
12
28
  replyCategorySchema
13
- } from "../chunks/chunk-4PSO6JEK.js";
14
- import "../chunks/chunk-LVYG7XZJ.js";
29
+ } from "../chunks/chunk-QGRZDTX4.js";
30
+ import {
31
+ makeRef,
32
+ parseRef
33
+ } from "../chunks/chunk-QAKJ76HB.js";
34
+ import {
35
+ profileSlug
36
+ } from "../chunks/chunk-NAWZ73QS.js";
15
37
  import {
16
38
  OutboundError
17
- } from "../chunks/chunk-E7JHLNLG.js";
39
+ } from "../chunks/chunk-J7DDZ4C2.js";
18
40
  import {
41
+ isJsonObject,
42
+ jsonInput,
19
43
  toJson,
20
44
  unknownKey
21
- } from "../chunks/chunk-VQSCHOBV.js";
45
+ } from "../chunks/chunk-BLCJHP5H.js";
22
46
 
23
47
  // src/insights/plugin.ts
24
48
  import { z as z31 } from "zod";
25
49
 
50
+ // src/insights/cost.ts
51
+ var UNKNOWN = /* @__PURE__ */ Symbol("unknown cost");
52
+ var pages = (cost, records) => cost.pageSize === void 0 ? 1 : Math.max(1, Math.ceil(records / cost.pageSize));
53
+ var pricer = (outbound, costs, most, found) => {
54
+ const of = (action) => {
55
+ const cost = costs[action];
56
+ if (cost === void 0) {
57
+ throw UNKNOWN;
58
+ }
59
+ return cost;
60
+ };
61
+ const list = (action, max) => {
62
+ const cost = of(action);
63
+ return most ? pages(cost, max) * (cost.perPageAtMost ?? cost.perPage) + max * (cost.perRecord ?? 0) + (cost.perWalk ?? 0) : cost.perPage;
64
+ };
65
+ const { capabilities } = outbound;
66
+ return {
67
+ campaigns: (max) => {
68
+ if (found !== void 0) {
69
+ return Math.min(found, max);
70
+ }
71
+ return most ? max : 0;
72
+ },
73
+ campaignsIn: (statuses, max) => {
74
+ const cost = of("campaigns.list");
75
+ const filtered = capabilities["campaigns.status"] !== false;
76
+ if (most) {
77
+ return filtered ? (statuses - 1) * list("campaigns.list", 1) + list("campaigns.list", max) : list("campaigns.list", max);
78
+ }
79
+ const read = found === void 0 ? 1 : pages(cost, Math.min(found, max));
80
+ return (filtered ? Math.max(statuses, read) : read) * cost.perPage;
81
+ },
82
+ capabilities,
83
+ list,
84
+ lookup: (max) => list(
85
+ costs["leads.lookup"] === void 0 ? "leads.list" : "leads.lookup",
86
+ max
87
+ ),
88
+ one: (action) => {
89
+ const cost = of(action);
90
+ return most ? cost.perPage + (cost.perWalk ?? 0) : cost.perPage;
91
+ },
92
+ upTo: (max) => most ? max : 0,
93
+ walk: (action) => {
94
+ const cost = of(action);
95
+ return list(action, cost.pageSize ?? 1);
96
+ }
97
+ };
98
+ };
99
+ var boundsOf = (outbound, cost, input27, found) => {
100
+ const costs = cappedAccess(outbound)?.costs;
101
+ if (cost === void 0 || costs === void 0) {
102
+ return null;
103
+ }
104
+ try {
105
+ return {
106
+ max: cost(input27, pricer(outbound, costs, true, found)),
107
+ min: cost(input27, pricer(outbound, costs, false, found))
108
+ };
109
+ } catch (error) {
110
+ if (error === UNKNOWN) {
111
+ return null;
112
+ }
113
+ throw error;
114
+ }
115
+ };
116
+ var defaultCap = (bounds) => bounds === null ? Infinity : Math.ceil(bounds.max * 1.25) + 4;
117
+ var stops = /* @__PURE__ */ new WeakMap();
118
+ var capStopOf = (cause) => OutboundError.is(cause) ? stops.get(cause) : void 0;
119
+ var capWords = (effect) => effect.isDefault ? `its default cap of ${plural(effect.cap, "request")} for this input` : `the cap of ${plural(effect.cap, "request")} (${effect.setting})`;
120
+ var advice = (stop) => {
121
+ const raise = stop.isDefault ? `pass ${stop.setting} to raise it (Infinity removes the default)` : `raise ${stop.setting}`;
122
+ const text = stop.lower === void 0 ? raise : `lower ${stop.lower.input} to ${stop.lower.to}${stop.lower.sure ? "" : " or less"}, or ${raise}`;
123
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`;
124
+ };
125
+ var capError = (message, stop, provider) => {
126
+ const error = new OutboundError("RateLimited", `${message} ${advice(stop)}`, {
127
+ limit: "call",
128
+ provider
129
+ });
130
+ stops.set(error, stop);
131
+ return error;
132
+ };
133
+ var refusal = (name, bounds, room, stop, provider) => {
134
+ const range = bounds.max > bounds.min ? ` (at most ${bounds.max})` : "";
135
+ const cap = stop.isDefault ? `its default cap for this input is ${plural(stop.cap, "request")}` : `its cap is ${plural(stop.cap, "request")} (${stop.setting})`;
136
+ const why = room < stop.cap ? `only ${plural(room, "request")} ${room === 1 ? "is" : "are"} left of budget()'s run` : cap;
137
+ return capError(
138
+ `${name} needs at least ${plural(bounds.min, "request")} for this input${range}, and ${why}. No request was sent${stop.requests > 0 ? ` after the first ${plural(stop.requests, "request")}` : ""}.`,
139
+ stop,
140
+ provider
141
+ );
142
+ };
143
+ var stopped = (name, stop, provider) => capError(
144
+ `${name} stopped after ${plural(stop.requests, "request")}, at ${capWords(stop)}, before it finished; nothing it read is returned.`,
145
+ stop,
146
+ provider
147
+ );
148
+ var fitting = (outbound, cost, input27, name, room, found) => {
149
+ const fields = input27;
150
+ const current = fields[name];
151
+ if (typeof current !== "number" || current <= 1) {
152
+ return void 0;
153
+ }
154
+ const fits = (value, bound) => {
155
+ const lowered = { ...fields, [name]: value };
156
+ const bounds = boundsOf(outbound, cost, lowered, found);
157
+ return bounds !== null && bounds[bound] <= room;
158
+ };
159
+ const largest = (bound) => {
160
+ let low = 0;
161
+ let high = current - 1;
162
+ while (low < high) {
163
+ const middle = Math.ceil((low + high) / 2);
164
+ if (fits(middle, bound)) {
165
+ low = middle;
166
+ } else {
167
+ high = middle - 1;
168
+ }
169
+ }
170
+ return low >= 1 && fits(low, bound) ? low : 0;
171
+ };
172
+ const sure = largest("max");
173
+ if (sure > 0) {
174
+ return { input: name, sure: true, to: sure };
175
+ }
176
+ const maybe = largest("min");
177
+ return maybe > 0 ? { input: name, sure: false, to: maybe } : void 0;
178
+ };
179
+
26
180
  // src/insights/copy/copy-audit.ts
181
+ import { z as z2 } from "zod";
182
+
183
+ // src/internal/renamed.ts
27
184
  import { z } from "zod";
185
+ var REMOVED_IN = "0.6.0";
186
+ var renames = z.registry();
187
+ var renamed = (to, base) => {
188
+ const field = base.optional().meta({
189
+ deprecated: true,
190
+ description: `Deprecated: renamed to \`${to}\`. Removed in ${REMOVED_IN}.`
191
+ });
192
+ renames.add(field, { to });
193
+ return field;
194
+ };
195
+ var renamesIn = (fields) => Object.entries(fields).flatMap(([from, schema]) => {
196
+ const link = renames.get(schema);
197
+ return link === void 0 ? [] : [{ from, to: link.to }];
198
+ });
199
+ var liveKeys = (fields) => {
200
+ const old = new Set(renamesIn(fields).map((each) => each.from));
201
+ return Object.keys(fields).filter((key) => !old.has(key));
202
+ };
203
+ var applyRenames = (fields, input27) => {
204
+ if (!isJsonObject(input27)) {
205
+ return { input: input27, notes: [] };
206
+ }
207
+ const moved = new Map(Object.entries(input27));
208
+ const notes = [];
209
+ for (const { from, to } of renamesIn(fields)) {
210
+ const value = moved.get(from);
211
+ moved.delete(from);
212
+ if (value !== void 0) {
213
+ if (moved.get(to) !== void 0) {
214
+ return { conflict: { from, to } };
215
+ }
216
+ moved.set(to, value);
217
+ notes.push(
218
+ `\`${from}\` is deprecated and will be removed in ${REMOVED_IN}; use \`${to}\`.`
219
+ );
220
+ }
221
+ }
222
+ return { input: Object.fromEntries(moved), notes };
223
+ };
224
+
225
+ // src/insights/run-cap.ts
226
+ var capFor = (outbound, name, max, options) => {
227
+ const set = options.maxRequests;
228
+ if (set !== void 0 && set !== Infinity && (!Number.isInteger(set) || set < 1)) {
229
+ throw new OutboundError(
230
+ "Invalid",
231
+ `${name}: maxRequests must be a positive integer, or Infinity for no default cap`,
232
+ { provider: outbound.provider }
233
+ );
234
+ }
235
+ const setting = options.capSetting ?? "maxRequests";
236
+ return set === void 0 ? {
237
+ cap: Math.min(max, options.capCeiling ?? Infinity),
238
+ isDefault: true,
239
+ setting
240
+ } : { cap: set, isDefault: false, setting };
241
+ };
242
+ var hasRunBudget = (outbound) => "requestBudget" in outbound;
243
+ var runBudgetLeft = (outbound) => hasRunBudget(outbound) && outbound.requestBudget.per === "run" ? outbound.requestBudget.remaining() : Infinity;
244
+ var runCap = (outbound, spec, input27, options) => {
245
+ const bounds = boundsOf(outbound, spec.cost, input27);
246
+ const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
247
+ const stop = (room, found) => ({
248
+ ...effect,
249
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input27, spec.scales, room, found),
250
+ requests: counter.used()
251
+ });
252
+ const counter = requestCounter(
253
+ effect.cap,
254
+ (provider) => stopped(spec.name, stop(effect.cap), provider)
255
+ );
256
+ const check = (found) => {
257
+ const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
258
+ const least = boundsOf(outbound, spec.cost, input27, found);
259
+ if (least !== null && least.min > room) {
260
+ throw refusal(
261
+ spec.name,
262
+ least,
263
+ room,
264
+ stop(room, found),
265
+ outbound.provider
266
+ );
267
+ }
268
+ };
269
+ check();
270
+ const isStopped = () => counter.stopped();
271
+ return {
272
+ campaignsFound: check,
273
+ failed: (cause) => {
274
+ throw isStopped() ? stopped(spec.name, stop(effect.cap), outbound.provider) : cause;
275
+ },
276
+ outbound: withGuard(outbound, counter),
277
+ shortNote: () => isStopped() ? `Reads past ${counter.used()} requests were stopped at ${effect.isDefault ? "the default cap for this input" : `the cap (${effect.setting})`}; the answer leaves them out.` : void 0
278
+ };
279
+ };
28
280
 
29
281
  // src/insights/define.ts
282
+ var isRedacted = (outbound) => "redacted" in outbound;
283
+ var maskingOf = (outbound) => isRedacted(outbound) ? outbound.redacted : null;
284
+ var maskedOutBy = (outbound, entry) => {
285
+ const masking = maskingOf(outbound);
286
+ return masking === null || entry.maskedOut === void 0 ? null : entry.maskedOut(masking);
287
+ };
288
+ var stopNote = (cap) => {
289
+ if (cap === void 0) {
290
+ return "A listing was cut off at its cap; more records exist.";
291
+ }
292
+ return typeof cap === "string" ? `Stopped at ${cap}; more exist.` : capNote(cap);
293
+ };
294
+ var oneOf = (what) => what.replace(
295
+ /\b(?<stem>\w+?)(?<end>ies|s)\b/u,
296
+ (_match, stem, end) => end === "ies" ? `${stem}y` : stem
297
+ );
298
+ var capNote = (cap) => `Stopped at ${plural(cap.max, oneOf(cap.what), cap.what)} (${cap.input ?? "a fixed cap"}); more exist.`;
30
299
  var RANK = {
31
300
  derived: 2,
32
301
  exact: 0,
33
302
  sampled: 1
34
303
  };
35
- var track = (outbound, now) => {
304
+ var track = (outbound, now, campaignsFound) => {
36
305
  const notes = [];
37
306
  let requests = 0;
38
307
  let evidence = "exact";
@@ -59,12 +328,11 @@ var track = (outbound, now) => {
59
328
  const items = await walk.toArray();
60
329
  seen(walk.meta);
61
330
  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
- );
331
+ partial(stopNote(cap));
65
332
  }
66
333
  return items;
67
334
  },
335
+ campaignsFound,
68
336
  note,
69
337
  now,
70
338
  one: (item) => {
@@ -89,8 +357,23 @@ var track = (outbound, now) => {
89
357
  };
90
358
  };
91
359
  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);
360
+ var withRenames = (outbound, spec, given) => {
361
+ const renamed2 = applyRenames(spec.inputSchema.shape, given);
362
+ if ("conflict" in renamed2) {
363
+ const { from, to } = renamed2.conflict;
364
+ throw new OutboundError(
365
+ "Invalid",
366
+ `${spec.name}: pass \`${to}\` only; \`${from}\` is its old name`,
367
+ { provider: outbound.provider }
368
+ );
369
+ }
370
+ return renamed2;
371
+ };
372
+ var prepare = (outbound, spec, given) => {
373
+ const fields = spec.inputSchema.shape;
374
+ const renamed2 = withRenames(outbound, spec, given);
375
+ const { input: input27 } = renamed2;
376
+ const stray = unknownKey(liveKeys(fields), input27);
94
377
  if (stray !== void 0) {
95
378
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
96
379
  provider: outbound.provider
@@ -101,7 +384,23 @@ var prepare = (outbound, spec, input27) => {
101
384
  const [issue] = parsed.error.issues;
102
385
  throw new OutboundError(
103
386
  "Invalid",
104
- `${spec.name}: ${issue?.path.join(".") || "input"} ${issue?.message ?? "is invalid"}`,
387
+ `${spec.name}: ${inputProblem(input27, issue)}`,
388
+ { provider: outbound.provider }
389
+ );
390
+ }
391
+ const blocked = maskedOutBy(outbound, spec);
392
+ if (blocked !== null) {
393
+ throw new OutboundError(
394
+ "Unsupported",
395
+ `${spec.name} is not available while the redact plugin masks ${blocked}`,
396
+ { provider: outbound.provider }
397
+ );
398
+ }
399
+ const lacked = spec.lacks?.(outbound) ?? null;
400
+ if (lacked !== null) {
401
+ throw new OutboundError(
402
+ "Unsupported",
403
+ `${spec.name} is not available: the ${outbound.provider} adapter does not report ${lacked}`,
105
404
  { provider: outbound.provider }
106
405
  );
107
406
  }
@@ -114,13 +413,21 @@ var prepare = (outbound, spec, input27) => {
114
413
  { provider: outbound.provider }
115
414
  );
116
415
  }
117
- return parsed.data;
416
+ return { input: parsed.data, notes: renamed2.notes };
118
417
  };
119
418
  var execute = async (outbound, spec, input27, options = {}) => {
120
419
  const checked = prepare(outbound, spec, input27);
420
+ const cap = runCap(outbound, spec, checked.input, options);
121
421
  const now = options.now ?? Date.now();
122
- const tracker = track(outbound, now);
123
- const data = await spec.run(tracker.context, checked);
422
+ const tracker = track(cap.outbound, now, cap.campaignsFound);
423
+ for (const note of checked.notes) {
424
+ tracker.context.note(note);
425
+ }
426
+ const data = await spec.run(tracker.context, checked.input).catch(cap.failed);
427
+ const short = cap.shortNote();
428
+ if (short !== void 0) {
429
+ tracker.context.partial(short);
430
+ }
124
431
  return {
125
432
  data,
126
433
  insight: spec.name,
@@ -177,6 +484,8 @@ var TAG = /<[^>]+>/gu;
177
484
  var IMAGE = /<img\b[^>]*>/giu;
178
485
  var VARIABLE = /\{\{[^{}]*\}\}/gu;
179
486
  var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
487
+ var ANCHOR = /<a\b(?<attributes>[^>]*)>[\s\S]*?<\/a\s*>/giu;
488
+ var HREF = /\bhref\s*=\s*["']?(?<target>[^"'\s>]+)/iu;
180
489
  var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
181
490
  var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
182
491
  var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
@@ -187,22 +496,30 @@ var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== ""
187
496
  var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
188
497
  var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
189
498
  check: "subject_too_long",
190
- finding: `The subject is ${subject.length} characters; the limit is ${limits.maxSubjectChars}.`,
499
+ finding: `The subject is ${plural(subject.length, "character")}; the limit is ${limits.maxSubjectChars}.`,
191
500
  text: clip(subject)
192
501
  } : null;
193
502
  var bodyTooLong = (body, limits) => {
194
503
  const words = wordsOf(body);
195
504
  return words.length > limits.maxBodyWords ? {
196
505
  check: "body_too_long",
197
- finding: `The body is ${words.length} words; the limit is ${limits.maxBodyWords}.`,
506
+ finding: `The body is ${plural(words.length, "word")}; the limit is ${limits.maxBodyWords}.`,
198
507
  text: clip(words.slice(0, 12).join(" "))
199
508
  } : null;
200
509
  };
510
+ var linksOf = (body) => {
511
+ const html = body.replaceAll(IMAGE, " ");
512
+ const anchored = [...html.matchAll(ANCHOR)].flatMap((anchor) => {
513
+ const target = HREF.exec(anchor.groups?.attributes ?? "")?.groups?.target;
514
+ return target === void 0 ? [] : [target];
515
+ });
516
+ return [...anchored, ...html.replaceAll(ANCHOR, " ").match(LINK) ?? []];
517
+ };
201
518
  var tooManyLinks = (body, limits) => {
202
- const links = body.replaceAll(IMAGE, " ").match(LINK) ?? [];
519
+ const links = linksOf(body);
203
520
  return links.length > limits.maxLinks ? {
204
521
  check: "too_many_links",
205
- finding: `The body has ${links.length} links; the limit is ${limits.maxLinks}.`,
522
+ finding: `The body has ${plural(links.length, "link")}; the limit is ${limits.maxLinks}.`,
206
523
  text: clip(links.join(" "))
207
524
  } : null;
208
525
  };
@@ -216,7 +533,7 @@ var spamWords = (text, limits) => {
216
533
  );
217
534
  return hits.length > 0 ? {
218
535
  check: "spam_words",
219
- finding: `The copy uses ${hits.length} word(s) or phrase(s) that spam filters weigh.`,
536
+ finding: `The copy uses ${plural(hits.length, "word or phrase", "words or phrases")} that spam filters weigh.`,
220
537
  text: hits.join(", ")
221
538
  } : null;
222
539
  };
@@ -242,7 +559,7 @@ var allCaps = (text, limits) => {
242
559
  const found = words ?? [];
243
560
  return found.length > limits.maxCapsWords ? {
244
561
  check: "all_caps",
245
- finding: `${found.length} word(s) of four or more letters are in capitals; the limit is ${limits.maxCapsWords}.`,
562
+ finding: `${plural(found.length, "word")} of four or more letters ${noun(found.length, "is", "are")} in capitals; the limit is ${limits.maxCapsWords}.`,
246
563
  text: clip(found.join(" "))
247
564
  } : null;
248
565
  };
@@ -273,9 +590,9 @@ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChar
273
590
  } : null;
274
591
 
275
592
  // 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`"),
593
+ var limit = (fallback, description) => z2.number().int().min(0).default(fallback).describe(description);
594
+ var input = z2.object({
595
+ campaign: z2.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
279
596
  max_body_words: limit(150, "The most words a body may have."),
280
597
  max_caps_words: limit(
281
598
  1,
@@ -288,7 +605,7 @@ var input = z.object({
288
605
  max_exclamations: limit(1, "How many exclamation marks a message may have."),
289
606
  max_links: limit(1, "The most links an email body may have."),
290
607
  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(
608
+ spam_words: z2.array(z2.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
292
609
  "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
293
610
  )
294
611
  });
@@ -379,6 +696,7 @@ var copyAudit = defineInsight({
379
696
  description: "Problems in a campaign's copy before it sends. Checks every step and variant for a long subject, a long body, too many links, spam words, unbalanced or empty {{ }} variables, words in capitals, repeated exclamation marks, an image or tracking pixel, a missing subject on the first email, and a follow-up whose subject breaks the thread; a LinkedIn campaign skips the email-only checks and flags a connection request over the character limit. Returns each finding with a severity and the text that triggered it, and a count per check. Costs 2 requests. Fixed rules only, no model. A variant whose body the vendor does not return is counted, not judged.",
380
697
  inputSchema: input,
381
698
  key: "copyAudit",
699
+ cost: (_input, price) => price.one("campaigns.get") + price.one("sequence.get"),
382
700
  name: "copy_audit",
383
701
  needs: ["sequence"],
384
702
  next: "Use step_funnel to see whether the steps with findings are also the ones with few replies.",
@@ -410,7 +728,7 @@ var copyAudit = defineInsight({
410
728
  ).length;
411
729
  if (withoutBody > 0) {
412
730
  context.note(
413
- `${withoutBody} variant(s) have no body in the vendor's answer, so their body checks were skipped.`
731
+ 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
732
  );
415
733
  }
416
734
  const severity = (level) => findings.filter((finding) => finding.severity === level).length;
@@ -421,7 +739,8 @@ var copyAudit = defineInsight({
421
739
  low: severity("low"),
422
740
  medium: severity("medium")
423
741
  },
424
- campaign: args.campaign,
742
+ campaign: campaign.ref,
743
+ campaignName: campaign.name,
425
744
  channel: campaign.channel,
426
745
  clean: findings.length === 0,
427
746
  findings,
@@ -434,7 +753,67 @@ var copyAudit = defineInsight({
434
753
  });
435
754
 
436
755
  // src/insights/copy/copy-reuse.ts
756
+ import { z as z4 } from "zod";
757
+
758
+ // src/insights/capped.ts
759
+ var readCapped = async (context, open, cap, room = cap.max) => {
760
+ if (room >= 1) {
761
+ const walk = open(room);
762
+ const items = await context.all(walk, cap);
763
+ return { capped: walk.truncated, items };
764
+ }
765
+ const probe = open(1);
766
+ const left = await context.all(probe, cap);
767
+ if (left.length > 0 && !probe.truncated) {
768
+ context.partial(capNote(cap));
769
+ }
770
+ return { capped: left.length > 0, items: [] };
771
+ };
772
+ var campaignsReadOf = (read) => ({
773
+ campaignsRead: read.items.length,
774
+ moreCampaignsExist: read.capped
775
+ });
776
+ var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns") => {
777
+ const { campaigns } = context.outbound;
778
+ const wanted = [...new Set(statuses)];
779
+ const cap = { input: input27, max, what: "campaigns" };
780
+ if (context.outbound.capabilities["campaigns.status"] === false) {
781
+ const every = await readCapped(
782
+ context,
783
+ (room) => campaigns.listAll({ max: room }),
784
+ cap
785
+ );
786
+ const items = every.items.filter(
787
+ (campaign) => wanted.includes(campaign.status)
788
+ );
789
+ context.campaignsFound(items.length);
790
+ return { capped: every.capped, items };
791
+ }
792
+ const found = [];
793
+ let capped2 = false;
794
+ for (const status of wanted) {
795
+ const listed = await readCapped(
796
+ context,
797
+ (room) => campaigns.listAll({ max: room, status }),
798
+ cap,
799
+ max - found.length
800
+ );
801
+ found.push(...listed.items);
802
+ capped2 ||= listed.capped;
803
+ }
804
+ context.campaignsFound(found.length);
805
+ return { capped: capped2, items: found };
806
+ };
807
+
808
+ // src/insights/fields.ts
437
809
  import { z as z3 } from "zod";
810
+ var rangeFields = {
811
+ from: z3.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
812
+ to: z3.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
813
+ };
814
+ var statusesInput = (fallback) => z3.array(campaignStatusSchema).min(1).default([...fallback]).describe(
815
+ "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
816
+ );
438
817
 
439
818
  // src/insights/stats.ts
440
819
  var PLACES = 1e4;
@@ -511,6 +890,8 @@ var compareRates = (first, second, alpha = 0.05) => {
511
890
  z: round(z33) ?? 0
512
891
  };
513
892
  };
893
+ var percent = (value) => value === null ? "unknown" : percentOf(value);
894
+ var spoken = (value) => value === null ? "unknown" : count(value);
514
895
  var pText = (pValue) => pValue < 1 / PLACES ? `p < ${1 / PLACES}` : `p = ${pValue}`;
515
896
  var tally = (values) => {
516
897
  const counts = /* @__PURE__ */ new Map();
@@ -521,34 +902,10 @@ var tally = (values) => {
521
902
  };
522
903
 
523
904
  // 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
905
  var rangeOf = (from, to) => ({
527
906
  from: from ?? void 0,
528
907
  to: to ?? void 0
529
908
  });
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
909
  var firstKnown = (candidates) => {
553
910
  for (const [basis, value] of candidates) {
554
911
  if (value !== null && value > 0) {
@@ -565,13 +922,62 @@ var perMessage = (counts) => firstKnown([
565
922
  ["delivered", counts.delivered],
566
923
  ["sent", counts.sent]
567
924
  ]);
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
- });
925
+ var baseIn = (counts, basis) => firstKnown([[basis, counts[basis]]]);
926
+ var ORDER = {
927
+ lead: ["contacted", "sent"],
928
+ message: ["delivered", "sent"]
929
+ };
930
+ var sharedBases = (counts, per) => {
931
+ const own = counts.map(per === "lead" ? perLead : perMessage);
932
+ const based = counts.filter((_, index) => own[index]?.basis !== null);
933
+ for (const basis of ORDER[per]) {
934
+ if (based.every((each) => (each[basis] ?? 0) > 0)) {
935
+ return {
936
+ bases: counts.map((each) => baseIn(each, basis)),
937
+ basis: based.length === 0 ? null : basis,
938
+ comparable: true
939
+ };
940
+ }
941
+ }
942
+ return { bases: own, basis: null, comparable: false };
943
+ };
944
+ var BASIS_WORDS = {
945
+ contacted: "per lead contacted",
946
+ delivered: "per message delivered",
947
+ sent: "per message sent"
948
+ };
949
+ var basesInWords = (named3) => named3.map(
950
+ ({ basis, name }) => `${name} ${basis === null ? "with no base" : BASIS_WORDS[basis]}`
951
+ ).join(", ");
952
+ var measure = (count2, base) => {
953
+ const interval = wilson(count2, base.trials);
954
+ return {
955
+ basis: base.basis,
956
+ count: count2,
957
+ high: interval?.high ?? null,
958
+ interval,
959
+ low: interval?.low ?? null,
960
+ of: base.trials,
961
+ rate: rate(count2, base.trials),
962
+ trials: base.trials
963
+ };
964
+ };
965
+ var NO_RATE = {
966
+ basis: null,
967
+ count: null,
968
+ high: null,
969
+ low: null,
970
+ of: null,
971
+ rate: null
972
+ };
973
+ var replyRateOf = (measured2) => measured2 === null ? NO_RATE : {
974
+ basis: measured2.basis,
975
+ count: measured2.count,
976
+ high: measured2.high,
977
+ low: measured2.low,
978
+ of: measured2.of,
979
+ rate: measured2.rate
980
+ };
575
981
  var sumRows = (rows) => sumCounts(rows);
576
982
  var groupBy = (values, keyOf2) => {
577
983
  const groups = /* @__PURE__ */ new Map();
@@ -608,15 +1014,58 @@ var splitStats = (rows) => {
608
1014
  return { steps, unattributed: byStep.get(null) ?? [] };
609
1015
  };
610
1016
 
1017
+ // src/insights/copy/reuse-base.ts
1018
+ var pooled = (counts, baseOf) => {
1019
+ const measured2 = counts.flatMap((each) => {
1020
+ const one = each === null ? null : measure(each.replied, baseOf(each));
1021
+ return one === null || one.rate === null ? [] : [one];
1022
+ });
1023
+ const replies2 = total(measured2.map((each) => each.count));
1024
+ const trials = total(measured2.map((each) => each.trials));
1025
+ const bases = new Set(measured2.map((each) => each.basis));
1026
+ const [basis = null] = bases.size === 1 ? bases : [];
1027
+ return {
1028
+ ...measure(replies2, { basis, trials }),
1029
+ sent: total(counts.map((each) => each?.sent ?? null))
1030
+ };
1031
+ };
1032
+ var basesByCampaign = (counted2) => [...groupBy(counted2, (each) => each.campaign.ref).values()].flatMap(
1033
+ (group) => {
1034
+ const [first] = group;
1035
+ const bases = new Set(group.map((each) => perLead(each.counts).basis));
1036
+ const [basis = null] = bases.size === 1 ? bases : [];
1037
+ return first === void 0 ? [] : [{ basis, name: first.campaign.name }];
1038
+ }
1039
+ );
1040
+ var sharedBaseOf = (context, counted2) => {
1041
+ const shared = sharedBases(
1042
+ counted2.map((each) => each.counts),
1043
+ "lead"
1044
+ );
1045
+ const { basis } = shared;
1046
+ if (!shared.comparable) {
1047
+ context.note(
1048
+ `The campaigns report different bases (${basesInWords(
1049
+ basesByCampaign(counted2)
1050
+ )}), so their reply rates are not compared: no spread is judged and no best copy is named.`
1051
+ );
1052
+ }
1053
+ return {
1054
+ baseOf: basis === null ? perLead : (counts) => baseIn(counts, basis),
1055
+ basis,
1056
+ comparable: shared.comparable
1057
+ };
1058
+ };
1059
+
611
1060
  // src/insights/copy/copy-reuse.ts
612
- var input2 = z3.object({
613
- max_campaigns: z3.number().int().min(1).max(200).default(20).describe(
1061
+ var input2 = z4.object({
1062
+ max_campaigns: z4.number().int().min(1).max(200).default(20).describe(
614
1063
  "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
615
1064
  ),
616
- min_sent: z3.number().int().min(1).default(100).describe(
1065
+ min_sent: z4.number().int().min(1).default(100).describe(
617
1066
  "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
1067
  ),
619
- statuses: z3.array(campaignStatusSchema).min(1).default(["active", "paused", "completed"]).describe("The campaign statuses to read.")
1068
+ statuses: statusesInput(["active", "paused", "completed"])
620
1069
  });
621
1070
  var PREVIEW = 120;
622
1071
  var placementsOf = (campaign, sequence2, stats) => sequence2.steps.flatMap((step) => {
@@ -638,30 +1087,23 @@ var placementsOf = (campaign, sequence2, stats) => sequence2.steps.flatMap((step
638
1087
  ];
639
1088
  });
640
1089
  });
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) => {
1090
+ var useOf = (placements, baseOf) => {
654
1091
  const [first] = placements;
655
1092
  if (first === void 0) {
656
1093
  return [];
657
1094
  }
658
- const sum = pooled(placements.map((placement) => placement.counts));
1095
+ const sum = pooled(
1096
+ placements.map((placement) => placement.counts),
1097
+ baseOf
1098
+ );
659
1099
  return [
660
1100
  {
661
1101
  campaign: first.campaign.ref,
662
1102
  campaignName: first.campaign.name,
663
1103
  places: placements.map((placement) => placement.place),
1104
+ basis: sum.basis,
664
1105
  provider: first.campaign.provider,
1106
+ rates: { replyRate: replyRateOf(sum) },
665
1107
  replies: sum.count,
666
1108
  replyRate: sum.rate,
667
1109
  replyRateInterval: sum.interval,
@@ -670,17 +1112,22 @@ var useOf = (placements) => {
670
1112
  }
671
1113
  ];
672
1114
  };
673
- var pieceOf = (placements, uses) => {
1115
+ var pieceOf = (placements, uses, baseOf) => {
674
1116
  const [first] = placements;
675
1117
  if (first === void 0) {
676
1118
  return [];
677
1119
  }
678
- const sum = pooled(placements.map((placement) => placement.counts));
1120
+ const sum = pooled(
1121
+ placements.map((placement) => placement.counts),
1122
+ baseOf
1123
+ );
679
1124
  return [
680
1125
  {
1126
+ basis: sum.basis,
681
1127
  bodyPreview: first.body?.slice(0, PREVIEW) ?? null,
682
1128
  campaigns: uses.length,
683
1129
  contentHash: first.contentHash,
1130
+ rates: { replyRate: replyRateOf(sum) },
684
1131
  replies: sum.count,
685
1132
  replyRate: sum.rate,
686
1133
  replyRateInterval: sum.interval,
@@ -691,16 +1138,16 @@ var pieceOf = (placements, uses) => {
691
1138
  ];
692
1139
  };
693
1140
  var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
694
- var spreadOf = (uses, minSent) => {
1141
+ var spreadOf = (uses, minSent, comparable) => {
695
1142
  const judged = uses.filter(
696
1143
  (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
697
1144
  );
698
1145
  const [best] = judged;
699
1146
  const worst = judged.at(-1);
700
- if (best === void 0 || worst === void 0 || judged.length < 2) {
1147
+ if (!comparable || best === void 0 || worst === void 0 || judged.length < 2) {
701
1148
  return {
702
1149
  best: null,
703
- finding: `Fewer than two campaigns have a base of ${minSent}, so the spread is not judged.`,
1150
+ 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
1151
  spread: null,
705
1152
  spreadIsReal: null,
706
1153
  spreadPValue: null,
@@ -714,7 +1161,7 @@ var spreadOf = (uses, minSent) => {
714
1161
  const real = test?.significant ?? false;
715
1162
  return {
716
1163
  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.`,
1164
+ finding: real ? `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; a gap this size could be chance.`,
718
1165
  spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
719
1166
  spreadIsReal: real,
720
1167
  spreadPValue: test?.pValue ?? null,
@@ -737,38 +1184,49 @@ var readPlacements = async (context, campaigns) => {
737
1184
  return perCampaign.flat();
738
1185
  };
739
1186
  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.",
1187
+ 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
1188
  inputSchema: input2,
742
1189
  key: "copyReuse",
1190
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("sequence.get") + price.one("stats")),
1191
+ scales: "max_campaigns",
743
1192
  name: "copy_reuse",
744
1193
  needs: ["sequence", "stats.byStep"],
745
1194
  next: "Use step_funnel on the campaign where the copy does worst, or variant_test where the copy runs against another variant.",
746
1195
  run: async (context, { max_campaigns, min_sent, statuses }) => {
747
- const campaigns = await campaignsIn(context, statuses, max_campaigns);
1196
+ const listed = await readCampaignsIn(context, statuses, max_campaigns);
1197
+ const campaigns = listed.items;
748
1198
  const placements = await readPlacements(context, campaigns);
749
1199
  const without = placements.filter((each) => each.counts === null).length;
750
1200
  if (without > 0) {
751
1201
  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.`
1202
+ `${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
1203
  );
754
1204
  }
1205
+ const { baseOf, basis, comparable } = sharedBaseOf(
1206
+ context,
1207
+ placements.flatMap(
1208
+ (each) => each.counts === null ? [] : [{ campaign: each.campaign, counts: each.counts }]
1209
+ )
1210
+ );
755
1211
  const pieces = [...groupBy(placements, (each) => each.contentHash)].flatMap(
756
1212
  ([, group]) => {
757
- const uses = [...groupBy(group, (each) => each.campaign.ref).values()].flatMap(useOf).toSorted(byRate);
758
- return pieceOf(group, uses).map((piece) => ({ piece, uses }));
1213
+ const uses = [...groupBy(group, (each) => each.campaign.ref).values()].flatMap((each) => useOf(each, baseOf)).toSorted(byRate);
1214
+ return pieceOf(group, uses, baseOf).map((piece) => ({ piece, uses }));
759
1215
  }
760
1216
  );
761
1217
  const reused = pieces.flatMap(
762
- ({ piece, uses }) => uses.length < 2 ? [] : [{ ...piece, ...spreadOf(uses, min_sent), uses }]
1218
+ ({ piece, uses }) => uses.length < 2 ? [] : [{ ...piece, ...spreadOf(uses, min_sent, comparable), uses }]
763
1219
  ).toSorted(
764
1220
  (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
765
1221
  );
766
1222
  const [bestCopy] = pieces.flatMap(
767
- ({ piece }) => piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
1223
+ ({ piece }) => comparable && piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
768
1224
  ).toSorted(byRate);
769
1225
  const result = {
1226
+ basis,
770
1227
  bestCopy: bestCopy ?? null,
771
1228
  campaignsRead: campaigns.length,
1229
+ moreCampaignsExist: listed.capped,
772
1230
  piecesOfCopy: pieces.length,
773
1231
  reused,
774
1232
  variantsWithoutStats: without
@@ -778,21 +1236,35 @@ var copyReuse = defineInsight({
778
1236
  });
779
1237
 
780
1238
  // src/insights/copy/reply-timing.ts
781
- import { z as z4 } from "zod";
1239
+ import { z as z5 } from "zod";
1240
+
1241
+ // src/insights/campaign.ts
1242
+ var confirmCampaign = async (context, campaign) => {
1243
+ context.one(await context.outbound.campaigns.get(campaign));
1244
+ };
1245
+
1246
+ // src/insights/ref.ts
1247
+ var refOf = (outbound, id) => {
1248
+ const provider = parseRef(id)?.provider;
1249
+ return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
1250
+ };
1251
+
1252
+ // src/insights/copy/reply-timing.ts
782
1253
  var DAY_MS = 864e5;
1254
+ var MAX_UNPAIRED_SHARE = 0.25;
783
1255
  var HOUR_MS = 36e5;
784
1256
  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."
1257
+ var input3 = z5.object({
1258
+ campaign: z5.string().min(1).nullable().default(null).describe(
1259
+ "A campaign's ref to look at one campaign; an unknown one is refused with NotFound. null looks at every campaign."
788
1260
  ),
789
- max_messages: z4.number().int().min(1).max(5e4).default(2e3).describe(
1261
+ max_messages: z5.number().int().min(1).max(5e4).default(2e3).describe(
790
1262
  "The most messages to read, sent and received together. A page of messages costs 1 request."
791
1263
  ),
792
- since: z4.iso.datetime({ offset: true }).nullable().default(null).describe(
1264
+ since: z5.iso.datetime({ offset: true }).nullable().default(null).describe(
793
1265
  "Only messages from this time on, ISO 8601. null means 30 days before now."
794
1266
  ),
795
- timezone_offset_minutes: z4.number().int().min(-720).max(840).default(0).describe(
1267
+ timezone_offset_minutes: z5.number().int().min(-720).max(840).default(0).describe(
796
1268
  "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
797
1269
  )
798
1270
  });
@@ -865,10 +1337,10 @@ var tableOf = (times3, offsetMinutes) => {
865
1337
  share: rate(days[day] ?? 0, times3.length),
866
1338
  weekday: WEEKDAYS[day] ?? "Sunday"
867
1339
  }));
868
- const byHour = hours.map((count, hour) => ({
869
- count,
1340
+ const byHour = hours.map((count2, hour) => ({
1341
+ count: count2,
870
1342
  hour,
871
- share: rate(count, times3.length)
1343
+ share: rate(count2, times3.length)
872
1344
  }));
873
1345
  return {
874
1346
  byHour,
@@ -880,11 +1352,14 @@ var tableOf = (times3, offsetMinutes) => {
880
1352
  var readMessages = async (context, campaign, since, max) => {
881
1353
  const { outbound } = context;
882
1354
  const filters = outbound.capabilities["messages.since"] === false ? {} : { since };
883
- const messages = await readCapped(
1355
+ const { items: messages } = await readCapped(
884
1356
  context,
885
1357
  (cap) => campaign === null ? outbound.messages.listAll({ ...filters, max: cap }) : outbound.campaign(campaign).messages.listAll({ ...filters, max: cap }),
886
- max
1358
+ { input: "max_messages", max, what: "messages" }
887
1359
  );
1360
+ if (campaign !== null && messages.length === 0) {
1361
+ await confirmCampaign(context, campaign);
1362
+ }
888
1363
  if (outbound.capabilities["messages.since"] === false) {
889
1364
  context.note(
890
1365
  "This tool cannot filter messages by date, so the cap applies to all messages and older ones were dropped after reading."
@@ -894,10 +1369,25 @@ var readMessages = async (context, campaign, since, max) => {
894
1369
  (message) => message.sentAt === null || message.sentAt >= since
895
1370
  );
896
1371
  };
1372
+ var noteGaps = (context, unpaired, received) => {
1373
+ const share2 = rate(unpaired, received);
1374
+ if (share2 !== null && share2 > MAX_UNPAIRED_SHARE) {
1375
+ context.partial(
1376
+ `${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.`
1377
+ );
1378
+ }
1379
+ if (received > 0) {
1380
+ context.note(
1381
+ "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."
1382
+ );
1383
+ }
1384
+ };
897
1385
  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.",
1386
+ 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
1387
  inputSchema: input3,
900
1388
  key: "replyTiming",
1389
+ cost: (values, price) => price.list("messages.list", values.max_messages) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")),
1390
+ scales: "max_messages",
901
1391
  name: "reply_timing",
902
1392
  needs: ["messages.list"],
903
1393
  next: "Use step_funnel to see which step the replies answer, then set follow-up delays near the median time to reply.",
@@ -911,18 +1401,21 @@ var replyTiming = defineInsight({
911
1401
  );
912
1402
  const paired = pair(messages);
913
1403
  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);
1404
+ const within = (limit3) => rate(hours.filter((value) => value <= limit3).length, hours.length);
915
1405
  const received = messages.filter((message) => message.direction === "in");
916
1406
  const untimed = received.length - paired.replyTimes.length;
1407
+ const unpaired = paired.unpaired + untimed;
1408
+ noteGaps(context, unpaired, received.length);
917
1409
  const timing = {
918
- campaign: args.campaign,
1410
+ campaign: args.campaign === null ? null : refOf(context.outbound, args.campaign),
919
1411
  counts: {
920
1412
  followOnReplies: paired.followOn,
921
1413
  messagesRead: messages.length,
922
1414
  paired: paired.pairs.length,
923
1415
  received: received.length,
924
1416
  sent: messages.length - received.length,
925
- unpaired: paired.unpaired + untimed
1417
+ unpaired,
1418
+ unpairedShare: rate(unpaired, received.length)
926
1419
  },
927
1420
  replies: tableOf(paired.replyTimes, args.timezone_offset_minutes),
928
1421
  sendsThatDrewReplies: tableOf(
@@ -946,19 +1439,19 @@ var replyTiming = defineInsight({
946
1439
  });
947
1440
 
948
1441
  // 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(
1442
+ import { z as z6 } from "zod";
1443
+ var input4 = z6.object({
1444
+ campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1445
+ ...rangeFields,
1446
+ min_reply_rate: z6.number().min(0).max(1).default(0).describe(
954
1447
  "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.")
1448
+ )
957
1449
  });
958
1450
  var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, counts]) => {
959
1451
  const measured2 = measure(counts.replied, perLead(counts));
960
1452
  return {
961
1453
  contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
1454
+ rates: { replyRate: replyRateOf(measured2) },
962
1455
  replies: counts.replied,
963
1456
  replyRate: measured2.rate,
964
1457
  replyRateInterval: measured2.interval,
@@ -976,6 +1469,7 @@ var draftOf = (index, step, stats, minReplyRate) => {
976
1469
  earnsPlace: interval === null ? null : interval.low > minReplyRate,
977
1470
  inSequence: step !== void 0,
978
1471
  parent: step === void 0 ? null : step.parentIndex,
1472
+ rates: { replyRate: replyRateOf(measured2) },
979
1473
  replies: counts?.replied ?? null,
980
1474
  replyRate: measured2?.rate ?? null,
981
1475
  replyRateBasis: measured2?.basis ?? null,
@@ -1011,14 +1505,14 @@ var describe = (steps, top, last, allReplies) => {
1011
1505
  if (top === null) {
1012
1506
  return "No step has a reply in this range.";
1013
1507
  }
1014
- const lead = `Step ${top.step} (counted from 0) brings the most replies: ${top.replies} of ${allReplies}.`;
1508
+ const lead = `Step ${top.step + 1} brings the most replies: ${top.replies} of ${allReplies}.`;
1015
1509
  if (last === null) {
1016
1510
  return `${lead} No step's reply rate is reliably above the bar yet.`;
1017
1511
  }
1018
1512
  const later = steps.filter(
1019
1513
  (step) => step.step > last.step && step.sent !== null
1020
1514
  );
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.`;
1515
+ 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
1516
  };
1023
1517
  var unattributedOf = (rows) => {
1024
1518
  const counts = sumRows(rows);
@@ -1028,6 +1522,7 @@ var stepFunnel = defineInsight({
1028
1522
  description: "Where a campaign's replies come from: one row per sequence step with its action, delay, sends, replies, reply rate with a 95% interval, its share of all replies and how far sends fell from the step before, plus rows per variant when the vendor splits them. Names the step with the most replies and the last step that still earns its place. Use it to decide whether to cut or rewrite follow-ups. Costs 2 requests. A null count means the vendor does not report it; it is never 0.",
1029
1523
  inputSchema: input4,
1030
1524
  key: "stepFunnel",
1525
+ cost: (_input, price) => price.one("sequence.get") + price.one("stats"),
1031
1526
  name: "step_funnel",
1032
1527
  needs: ["sequence", "stats.byStep"],
1033
1528
  next: "Use variant_test on the same campaign to see whether a step's A/B winner is real, or copy_audit to check the copy of a weak step.",
@@ -1066,7 +1561,7 @@ var stepFunnel = defineInsight({
1066
1561
  );
1067
1562
  }
1068
1563
  const funnel = {
1069
- campaign,
1564
+ campaign: refOf(context.outbound, campaign),
1070
1565
  finding: describe(steps, top, last, allReplies),
1071
1566
  lastStepEarningPlace: last?.step ?? null,
1072
1567
  steps,
@@ -1082,23 +1577,22 @@ var stepFunnel = defineInsight({
1082
1577
  });
1083
1578
 
1084
1579
  // src/insights/copy/variant-test.ts
1085
- import { z as z6 } from "zod";
1580
+ import { z as z7 } from "zod";
1086
1581
  var METRICS = ["replied", "positive", "opened", "clicked"];
1087
- var input5 = z6.object({
1088
- alpha: z6.number().gt(0).max(0.5).default(0.05).describe(
1582
+ var input5 = z7.object({
1583
+ alpha: z7.number().gt(0).max(0.5).default(0.05).describe(
1089
1584
  "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1090
1585
  ),
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(
1586
+ campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1587
+ ...rangeFields,
1588
+ metric: z7.enum(METRICS).default("replied").describe(
1094
1589
  "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
1590
  ),
1096
- min_sent: z6.number().int().min(1).default(100).describe(
1591
+ min_sent: z7.number().int().min(1).default(100).describe(
1097
1592
  "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.")
1593
+ )
1100
1594
  });
1101
- var ORDER = {
1595
+ var ORDER2 = {
1102
1596
  no_difference_yet: 1,
1103
1597
  too_little_data: 2,
1104
1598
  winner: 0
@@ -1108,8 +1602,7 @@ var quantile = (tail) => {
1108
1602
  return t - (2.515517 + 0.802853 * t + 0.010328 * t ** 2) / (1 + 1.432788 * t + 0.189269 * t ** 2 + 1308e-6 * t ** 3);
1109
1603
  };
1110
1604
  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);
1605
+ var candidateOf = (variantKey, counts, base, minSent, metric) => {
1113
1606
  const measured2 = measure(counts[metric], base);
1114
1607
  return {
1115
1608
  ...measured2,
@@ -1127,25 +1620,34 @@ var shortfall = (candidates, minSent) => {
1127
1620
  0
1128
1621
  );
1129
1622
  };
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) => {
1623
+ var reasonFor = (candidates, settings, comparable) => {
1624
+ if (!comparable) {
1625
+ return `The variants of this step report different bases (${basesInWords(
1626
+ candidates.map((each) => ({ basis: each.basis, name: each.variantKey }))
1627
+ )}), so their rates cannot be compared.`;
1628
+ }
1629
+ 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.`;
1630
+ };
1631
+ var tooLittle = (step, candidates, settings, comparable) => ({
1632
+ leader: null,
1633
+ // More sends do not give variants with different bases a common one.
1634
+ moreSendsNeeded: comparable ? shortfall(candidates, settings.minSent) : null,
1635
+ pValue: null,
1636
+ reason: reasonFor(candidates, settings, comparable),
1637
+ step,
1638
+ variants: candidates.map((each) => ({ ...each, pValueVsLeader: null })),
1639
+ verdict: "too_little_data"
1640
+ });
1641
+ var testStep = (step, candidates, settings, comparable) => {
1642
+ if (!comparable) {
1643
+ return tooLittle(step, candidates, settings, false);
1644
+ }
1143
1645
  const ready = candidates.filter((each) => each.enoughData).toSorted(
1144
1646
  (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
1145
1647
  );
1146
1648
  const [leader, rival] = ready;
1147
1649
  if (leader === void 0 || rival === void 0) {
1148
- return tooLittle(step, candidates, settings);
1650
+ return tooLittle(step, candidates, settings, true);
1149
1651
  }
1150
1652
  const tests = new Map(
1151
1653
  ready.slice(1).map((other) => [
@@ -1160,7 +1662,7 @@ var testStep = (step, candidates, settings) => {
1160
1662
  const closest = tests.get(rival.variantKey) ?? null;
1161
1663
  const beatsAll = [...tests.values()].every((test) => test?.significant);
1162
1664
  const skipped = candidates.length - ready.length;
1163
- const aside = skipped === 0 ? "" : ` ${skipped} variant(s) with too little data were left out.`;
1665
+ const aside = skipped === 0 ? "" : ` ${plural(skipped, "variant")} with too little data ${noun(skipped, "was", "were")} left out.`;
1164
1666
  const variants = candidates.map((each) => ({
1165
1667
  ...each,
1166
1668
  pValueVsLeader: tests.get(each.variantKey)?.pValue ?? null
@@ -1170,7 +1672,7 @@ var testStep = (step, candidates, settings) => {
1170
1672
  leader: leader.variantKey,
1171
1673
  moreSendsNeeded: null,
1172
1674
  pValue: closest?.pValue ?? null,
1173
- reason: `Variant ${leader.variantKey} (${leader.rate}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1675
+ reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1174
1676
  step,
1175
1677
  variants,
1176
1678
  verdict: "winner"
@@ -1184,17 +1686,50 @@ var testStep = (step, candidates, settings) => {
1184
1686
  settings.alpha
1185
1687
  ),
1186
1688
  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}`,
1689
+ reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) leads variant ${rival.variantKey} (${percent(rival.rate)}), but a gap this size could be chance.${aside}`,
1188
1690
  step,
1189
1691
  variants,
1190
1692
  verdict: "no_difference_yet"
1191
1693
  };
1192
1694
  };
1695
+ var stepTest = (step, variants, settings) => {
1696
+ const entries = [...variants];
1697
+ const { bases, comparable } = sharedBases(
1698
+ entries.map(([, counts]) => counts),
1699
+ settings.metric === "replied" || settings.metric === "positive" ? "lead" : "message"
1700
+ );
1701
+ const candidates = entries.map(
1702
+ ([key, counts], index) => candidateOf(
1703
+ key,
1704
+ counts,
1705
+ bases[index] ?? { basis: null, trials: null },
1706
+ settings.minSent,
1707
+ settings.metric
1708
+ )
1709
+ );
1710
+ return testStep(step, candidates, settings, comparable);
1711
+ };
1712
+ var variantsReported = (context, rows) => {
1713
+ if (rows.length === 0) {
1714
+ context.note(
1715
+ "The vendor reported no step stats for this campaign in the date range, so there is nothing to compare."
1716
+ );
1717
+ return null;
1718
+ }
1719
+ const reported = rows.some((row) => row.variantKey !== null);
1720
+ if (!reported) {
1721
+ context.note(
1722
+ "The step stats carry no variant rows, so there is nothing to compare."
1723
+ );
1724
+ }
1725
+ return reported;
1726
+ };
1193
1727
  var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1194
1728
  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.",
1729
+ 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
1730
  inputSchema: input5,
1197
1731
  key: "variantTest",
1732
+ cost: (_input, price) => price.one("stats"),
1198
1733
  name: "variant_test",
1199
1734
  needs: ["stats.byStep"],
1200
1735
  next: "Use step_funnel to see how much of the campaign's replies the tested step brings, or copy_audit to check the losing variant's copy.",
@@ -1205,27 +1740,14 @@ var variantTest = defineInsight({
1205
1740
  const split = splitStats(rows);
1206
1741
  const settings = { alpha, metric, minSent: min_sent };
1207
1742
  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
- ]
1743
+ ([step, stats]) => stats.variants.size < 2 ? [] : [stepTest(step, stats.variants, settings)]
1217
1744
  ).toSorted(
1218
- (left, right) => ORDER[left.verdict] - ORDER[right.verdict] || left.step - right.step
1745
+ (left, right) => ORDER2[left.verdict] - ORDER2[right.verdict] || left.step - right.step
1219
1746
  );
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
- }
1747
+ const reported = variantsReported(context, rows);
1226
1748
  const result = {
1227
1749
  alpha,
1228
- campaign,
1750
+ campaign: refOf(context.outbound, campaign),
1229
1751
  metric,
1230
1752
  steps,
1231
1753
  totals: {
@@ -1250,10 +1772,10 @@ var COPY_INSIGHTS = [
1250
1772
  ];
1251
1773
 
1252
1774
  // src/insights/ops/anomalies.ts
1253
- import { z as z8 } from "zod";
1775
+ import { z as z9 } from "zod";
1254
1776
 
1255
1777
  // src/insights/ops/shared.ts
1256
- import { z as z7 } from "zod";
1778
+ import { z as z8 } from "zod";
1257
1779
  var DAY_MS2 = 864e5;
1258
1780
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1259
1781
  var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
@@ -1261,16 +1783,17 @@ var lastDays = (now, days, back = 0) => ({
1261
1783
  from: dayOf(now - days * (back + 1) * DAY_MS2),
1262
1784
  to: dayOf(now - (days * back + 1) * DAY_MS2)
1263
1785
  });
1786
+ var campaignTotalsCost = (input27, price) => {
1787
+ const campaigns = price.campaigns(input27.max_campaigns);
1788
+ return price.campaignsIn(new Set(input27.statuses).size, input27.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
1789
+ };
1264
1790
  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")
1791
+ max_campaigns: z8.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1792
+ statuses: statusesInput(["active", "paused", "completed"])
1267
1793
  });
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
1794
  var labelOf = (campaign) => ({
1273
1795
  campaign: campaign.ref,
1796
+ campaignName: campaign.name,
1274
1797
  channel: campaign.channel,
1275
1798
  name: campaign.name,
1276
1799
  provider: campaign.provider,
@@ -1283,26 +1806,33 @@ var totalsOf = (counts) => ({
1283
1806
  replied: counts.replied,
1284
1807
  sent: counts.sent
1285
1808
  });
1286
- var measure2 = (count, of) => {
1287
- const interval = wilson(count, of);
1809
+ var measure2 = (count2, of) => {
1810
+ const interval = wilson(count2, of);
1288
1811
  return {
1289
- count,
1812
+ count: count2,
1290
1813
  high: interval?.high ?? null,
1291
1814
  low: interval?.low ?? null,
1292
1815
  of,
1293
- rate: rate(count, of)
1816
+ rate: rate(count2, of)
1294
1817
  };
1295
1818
  };
1296
- var perLeadBase = (counts) => counts.contacted !== null && counts.contacted > 0 ? counts.contacted : counts.sent;
1297
- var ratesOf = (counts) => ({
1819
+ var baseIn2 = (basis) => (counts) => counts[basis];
1820
+ var perLeadBasis = (counts) => counts.contacted !== null && counts.contacted > 0 ? "contacted" : "sent";
1821
+ var perLeadBase = (counts) => counts[perLeadBasis(counts)];
1822
+ var periodBasis = (current, previous) => current.sent !== null && previous.sent !== null ? "sent" : "contacted";
1823
+ var RATE_WORDS = {
1824
+ contacted: "Replies per lead contacted",
1825
+ sent: "Replies per message sent"
1826
+ };
1827
+ var ratesOf = (counts, base = perLeadBase) => ({
1298
1828
  bounceRate: measure2(counts.bounced, counts.sent),
1299
- positiveRate: measure2(counts.positive, perLeadBase(counts)),
1300
- replyRate: measure2(counts.replied, perLeadBase(counts))
1829
+ positiveRate: measure2(counts.positive, base(counts)),
1830
+ replyRate: measure2(counts.replied, base(counts))
1301
1831
  });
1302
1832
  var measureAcross = (rows, countOf3, baseOf) => {
1303
1833
  const sides = rows.map((row) => ({ base: baseOf(row), count: countOf3(row) }));
1304
1834
  const pairs = sides.flatMap(
1305
- ({ base, count }) => count === null || base === null ? [] : [{ base, count }]
1835
+ ({ base, count: count2 }) => count2 === null || base === null ? [] : [{ base, count: count2 }]
1306
1836
  );
1307
1837
  return {
1308
1838
  counted: pairs.length,
@@ -1314,9 +1844,9 @@ var measureAcross = (rows, countOf3, baseOf) => {
1314
1844
  };
1315
1845
  };
1316
1846
  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);
1847
+ var ratesAcross = (rows, base = perLeadBase) => {
1848
+ const reply = measureAcross(rows, (row) => row.replied, base);
1849
+ const positive = measureAcross(rows, (row) => row.positive, base);
1320
1850
  const bounce = measureAcross(
1321
1851
  rows,
1322
1852
  (row) => row.bounced,
@@ -1337,40 +1867,12 @@ var ratesAcross = (rows) => {
1337
1867
  };
1338
1868
  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
1869
  var volumeOf = (counts) => counts.sent ?? counts.contacted;
1340
- var percent = (value) => value === null ? "unknown" : `${Math.round(value * 1e3) / 10}%`;
1341
1870
  var descending = (left, right) => {
1342
1871
  if (left === null || right === null) {
1343
1872
  return Number(left === null) - Number(right === null);
1344
1873
  }
1345
1874
  return right - left;
1346
1875
  };
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
1876
  var readTotals = async (context, campaign, range) => sumCounts(
1375
1877
  context.rows(
1376
1878
  await context.outbound.campaign(campaign).stats({ from: range.from ?? void 0, to: range.to ?? void 0 })
@@ -1399,19 +1901,21 @@ var readAllTotals = async (context, range) => {
1399
1901
  );
1400
1902
  };
1401
1903
  var readCampaignTotals = async (context, input27) => {
1402
- const campaigns = await readCampaigns(
1904
+ const listed = await readCampaignsIn(
1403
1905
  context,
1404
1906
  input27.statuses,
1405
1907
  input27.max_campaigns
1406
1908
  );
1909
+ const campaigns = listed.items;
1407
1910
  const reported = campaigns.length > 1 ? await readAllTotals(context, input27) : void 0;
1408
- return await mapConcurrent(
1911
+ const entries = await mapConcurrent(
1409
1912
  campaigns,
1410
1913
  async (campaign) => ({
1411
1914
  campaign,
1412
1915
  counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input27)
1413
1916
  })
1414
1917
  );
1918
+ return { entries, read: campaignsReadOf(listed) };
1415
1919
  };
1416
1920
  var readDaily = async (context, campaign, range) => {
1417
1921
  const options = { by: "day", from: range.from, to: range.to };
@@ -1428,7 +1932,7 @@ var readDaily = async (context, campaign, range) => {
1428
1932
  };
1429
1933
 
1430
1934
  // src/insights/ops/anomalies.ts
1431
- var metricSchema = z8.enum([
1935
+ var metricSchema = z9.enum([
1432
1936
  "sent",
1433
1937
  "contacted",
1434
1938
  "replied",
@@ -1438,15 +1942,15 @@ var metricSchema = z8.enum([
1438
1942
  "clicked",
1439
1943
  "unsubscribed"
1440
1944
  ]);
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")
1945
+ var input6 = z9.object({
1946
+ baseline_days: z9.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1947
+ campaign: z9.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1948
+ days: z9.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1949
+ metrics: z9.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1950
+ min_baseline_points: z9.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1951
+ threshold: z9.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1448
1952
  });
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.";
1953
+ 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
1954
  var judge = (metric, point, baseline, threshold) => {
1451
1955
  const center = round(mean(baseline)) ?? 0;
1452
1956
  const score = zScore(point.value, baseline);
@@ -1461,14 +1965,14 @@ var judge = (metric, point, baseline, threshold) => {
1461
1965
  if (score === null) {
1462
1966
  return point.value === baseline[0] ? null : {
1463
1967
  ...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).`,
1968
+ 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
1969
  judgedBy: "flat_baseline",
1466
1970
  zScore: null
1467
1971
  };
1468
1972
  }
1469
1973
  return Math.abs(score) < threshold ? null : {
1470
1974
  ...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)}).`,
1975
+ 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
1976
  judgedBy: "z_score",
1473
1977
  zScore: round(score) ?? 0
1474
1978
  };
@@ -1500,7 +2004,7 @@ var scanMetric = (series, metric, options) => {
1500
2004
  daysTested: tested,
1501
2005
  daysWithData: checked.length,
1502
2006
  metric,
1503
- reason: tested > 0 ? null : reasonFor(metric, checked.length),
2007
+ reason: tested > 0 ? null : reasonFor2(metric, checked.length),
1504
2008
  testable: tested > 0
1505
2009
  }
1506
2010
  };
@@ -1521,6 +2025,7 @@ var anomalies = defineInsight({
1521
2025
  description: "Days that broke from trend, for one campaign or the whole workspace: each of the last `days` complete days is held to the `baseline_days` before it, and a daily count `threshold` standard deviations or more from that baseline's mean is returned, newest first, with the metric, the value, the baseline mean, the z-score, the direction and how it was judged. When every baseline day has the same count there is no standard deviation: a day with another count is returned with a null z-score and judgedBy flat_baseline. Use it to spot a sending outage, a bounce spike or a reply surge. Days the vendor has no count for are skipped, never read as zero. With no campaign it reads workspace stats, so it then also needs stats.workspace. Costs one stats request.",
1522
2026
  inputSchema: input6,
1523
2027
  key: "anomalies",
2028
+ cost: (_input, price) => price.one("stats"),
1524
2029
  name: "anomalies",
1525
2030
  needs: ["stats.byDay"],
1526
2031
  // The whole workspace is read from workspace stats, a campaign from its own.
@@ -1541,7 +2046,7 @@ var anomalies = defineInsight({
1541
2046
  threshold: options.threshold
1542
2047
  }),
1543
2048
  period,
1544
- scope: options.campaign ?? "workspace",
2049
+ scope: options.campaign === null ? "workspace" : refOf(context.outbound, options.campaign),
1545
2050
  threshold: options.threshold
1546
2051
  };
1547
2052
  return answer;
@@ -1549,7 +2054,7 @@ var anomalies = defineInsight({
1549
2054
  });
1550
2055
 
1551
2056
  // src/insights/ops/campaign-diagnosis.ts
1552
- import { z as z9 } from "zod";
2057
+ import { z as z10 } from "zod";
1553
2058
 
1554
2059
  // src/insights/ops/diagnosis-checks.ts
1555
2060
  var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
@@ -1566,14 +2071,14 @@ var volume = (facts, limits) => {
1566
2071
  ];
1567
2072
  };
1568
2073
  var bounces = (facts, limits) => {
1569
- const { count, high, low, of, rate: rate2 } = facts.rates.bounceRate;
2074
+ const { count: count2, high, low, of, rate: rate2 } = facts.rates.bounceRate;
1570
2075
  return !enough(facts, limits) || rate2 === null || rate2 <= limits.maxBounceRate ? [] : [
1571
2076
  {
1572
2077
  code: "high_bounce_rate",
1573
- finding: `Bounce rate is ${percent(rate2)} (${count} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
2078
+ finding: `Bounce rate is ${percent(rate2)} (${count2} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
1574
2079
  next: "Use bounce_watch to find the senders behind it, and verify the lead list.",
1575
2080
  numbers: {
1576
- bounced: count,
2081
+ bounced: count2,
1577
2082
  high,
1578
2083
  limit: limits.maxBounceRate,
1579
2084
  low,
@@ -1585,7 +2090,7 @@ var bounces = (facts, limits) => {
1585
2090
  ];
1586
2091
  };
1587
2092
  var replies = (facts, limits) => {
1588
- const { count, high, low, of, rate: rate2 } = facts.rates.replyRate;
2093
+ const { count: count2, high, low, of, rate: rate2 } = facts.rates.replyRate;
1589
2094
  if (!enough(facts, limits) || rate2 === null || rate2 >= limits.minReplyRate) {
1590
2095
  return [];
1591
2096
  }
@@ -1593,14 +2098,14 @@ var replies = (facts, limits) => {
1593
2098
  return [
1594
2099
  {
1595
2100
  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"}.`,
2101
+ 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
2102
  next: "Use step_funnel and copy_audit to see where replies are lost.",
1598
2103
  numbers: {
1599
2104
  floor: limits.minReplyRate,
1600
2105
  high,
1601
2106
  low,
1602
2107
  rate: rate2,
1603
- replied: count,
2108
+ replied: count2,
1604
2109
  sample: of
1605
2110
  },
1606
2111
  severity: clearly ? "high" : "medium"
@@ -1668,7 +2173,7 @@ var senders = (facts) => {
1668
2173
  return inactive.length === 0 ? [] : [
1669
2174
  {
1670
2175
  code: "inactive_sender",
1671
- finding: `${inactive.length} of ${all.length} senders are not active: ${inactive.map(
2176
+ finding: `${inactive.length} of ${plural(all.length, "sender")} ${noun(inactive.length, "is", "are")} not active: ${inactive.map(
1672
2177
  (sender) => `${sender.address ?? sender.name ?? sender.ref} (${sender.status})`
1673
2178
  ).join(", ")}.`,
1674
2179
  next: "Reconnect or replace them; warmup_readiness shows which mailboxes are fit to send.",
@@ -1710,10 +2215,10 @@ var schedule = ({ recent, settings }, limits) => {
1710
2215
  const average = recent === null || recent.sent === null || recent.daysWithData === 0 ? null : round(recent.sent / recent.daysWithData);
1711
2216
  const reasons = [
1712
2217
  ...hours !== null && hours < limits.minWeeklyHours ? [
1713
- `The sending windows are open ${hours} hours a week, under ${limits.minWeeklyHours}.`
2218
+ `The sending windows are open ${spoken(hours)} hours a week, under ${limits.minWeeklyHours}.`
1714
2219
  ] : [],
1715
2220
  ...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.`
2221
+ `Recent sending days average ${spoken(average)} sends against a daily limit of ${settings.dailyLimit}, so the limit is what holds volume back.`
1717
2222
  ] : []
1718
2223
  ];
1719
2224
  return reasons.length === 0 ? [] : [
@@ -1752,10 +2257,14 @@ var unknownRates = (facts) => [
1752
2257
  ];
1753
2258
 
1754
2259
  // 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({
2260
+ var share = (fallback, text) => z10.number().min(0).max(1).default(fallback).describe(text);
2261
+ var recentDays = z10.number().int().min(1).max(30);
2262
+ var input7 = z10.object({
1757
2263
  ...rangeFields,
1758
- campaign: z9.string().min(3).describe("The campaign's ref"),
2264
+ campaign: z10.string().min(3).describe("The campaign's ref"),
2265
+ days: recentDays.default(7).describe(
2266
+ "The days, ending yesterday, held against the same number before"
2267
+ ),
1759
2268
  daily_limit_share: share(
1760
2269
  0.9,
1761
2270
  "Average daily sends at or over this share of the daily limit mean the limit holds volume back"
@@ -1765,17 +2274,15 @@ var input7 = z9.object({
1765
2274
  0.3,
1766
2275
  "A fall in sends, recent days against the days before, over this share is a finding"
1767
2276
  ),
1768
- max_senders: z9.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2277
+ max_senders: z10.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
1769
2278
  min_positive_share: share(
1770
2279
  0.2,
1771
2280
  "A share of replies that are positive under this is a finding"
1772
2281
  ),
1773
2282
  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
- )
2283
+ min_sent: z10.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2284
+ min_weekly_hours: z10.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
2285
+ recent_days: renamed("days", recentDays)
1779
2286
  });
1780
2287
  var readRecent = async (context, campaign, days) => {
1781
2288
  const recent = lastDays(context.now, days);
@@ -1817,11 +2324,11 @@ var readExtras = async (context, campaign, options) => {
1817
2324
  const senders2 = unless(
1818
2325
  !capabilities["senders.byCampaign"],
1819
2326
  "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;
2327
+ ) ? await readCapped(context, (max) => handle.senders.listAll({ max }), {
2328
+ input: "max_senders",
2329
+ max: options.maxSenders,
2330
+ what: "senders"
2331
+ }) : null;
1825
2332
  const recent = unless(
1826
2333
  capabilities["stats.byDay"] === false,
1827
2334
  "Recent sending trend: the adapter has no stats by day."
@@ -1842,6 +2349,11 @@ var campaignDiagnosis = defineInsight({
1842
2349
  description: "Why one campaign is underperforming: a list of findings, most serious first, each with a code, a plain-language finding, the numbers behind it and what to look at next. It checks for too little volume to judge, a low reply rate (with its 95% interval), a high bounce rate, few positive replies among replies, sends falling or stopped over the last days, a one or two step sequence, a sender that is not active, open tracking being off, and a schedule or daily limit that holds volume back. Also returns what could not be checked; an empty list means nothing was found, not that all is well. Costs up to 7 requests.",
1843
2350
  inputSchema: input7,
1844
2351
  key: "campaignDiagnosis",
2352
+ cost: (values, price) => {
2353
+ const { capabilities } = price;
2354
+ return price.one("campaigns.get") + price.one("stats") + (capabilities["campaigns.settings"] === false ? 0 : price.one("campaigns.settings")) + (capabilities.sequence === false ? 0 : price.one("sequence.get")) + (capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders)) + (capabilities["stats.byDay"] === false ? 0 : price.one("stats"));
2355
+ },
2356
+ scales: "max_senders",
1845
2357
  name: "campaign_diagnosis",
1846
2358
  needs: ["stats.campaign"],
1847
2359
  next: "Follow the `next` of the first finding, for example bounce_watch, step_funnel or pipeline_forecast.",
@@ -1852,7 +2364,7 @@ var campaignDiagnosis = defineInsight({
1852
2364
  const counts = await readTotals(context, campaign.ref, options);
1853
2365
  const extras = await readExtras(context, campaign.ref, {
1854
2366
  maxSenders: options.max_senders,
1855
- recentDays: options.recent_days
2367
+ recentDays: options.days
1856
2368
  });
1857
2369
  const facts = {
1858
2370
  ...extras,
@@ -1884,34 +2396,35 @@ var campaignDiagnosis = defineInsight({
1884
2396
  });
1885
2397
 
1886
2398
  // src/insights/ops/campaign-ranking.ts
1887
- import { z as z10 } from "zod";
1888
- var metricSchema2 = z10.enum([
2399
+ import { z as z11 } from "zod";
2400
+ var metricSchema2 = z11.enum([
1889
2401
  "reply_rate",
1890
2402
  "positive_reply_rate",
1891
2403
  "bounce_rate"
1892
2404
  ]);
1893
- var input8 = z10.object({
2405
+ var input8 = z11.object({
1894
2406
  ...rangeFields,
1895
2407
  ...listFields("one stats request"),
1896
2408
  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")
2409
+ min_sent: z11.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
1898
2410
  });
1899
- var measured = (counts, metric) => {
1900
- const rates = ratesOf(counts);
2411
+ var measured = (counts, metric, basis) => {
2412
+ const rates = ratesOf(counts, baseIn2(basis));
1901
2413
  if (metric === "bounce_rate") {
1902
2414
  return rates.bounceRate;
1903
2415
  }
1904
2416
  return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
1905
2417
  };
1906
2418
  var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.name.localeCompare(right.name);
1907
- var rankCampaigns = (entries, metric, minSent) => {
2419
+ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
1908
2420
  const scored = [];
1909
2421
  const tooFewSends = [];
1910
2422
  const unknown = [];
1911
2423
  for (const { campaign, counts } of entries) {
1912
2424
  const label = labelOf(campaign);
1913
2425
  const volume2 = volumeOf(counts);
1914
- const result = measured(counts, metric);
2426
+ const basis = metric === "bounce_rate" ? "sent" : replyBasis ?? perLeadBasis(counts);
2427
+ const result = measured(counts, metric, basis);
1915
2428
  if (volume2 === null) {
1916
2429
  unknown.push({
1917
2430
  ...label,
@@ -1931,7 +2444,7 @@ var rankCampaigns = (entries, metric, minSent) => {
1931
2444
  sent: volume2
1932
2445
  });
1933
2446
  } else {
1934
- scored.push({ ...label, ...result, sent: volume2 });
2447
+ scored.push({ ...label, ...result, basis, sent: counts.sent });
1935
2448
  }
1936
2449
  }
1937
2450
  const ranked = scored.toSorted(order(metric)).map((entry, index) => ({ ...entry, rank: index + 1 }));
@@ -1952,13 +2465,16 @@ var campaignRanking = defineInsight({
1952
2465
  description: "Which campaigns are best, ranked fairly: by the low end of the 95% Wilson interval of the reply rate (or positive reply rate; for bounce rate, by the high end, lowest first), so 2 replies from 10 sends cannot outrank 150 from 1,000. Use it to pick winners and losers across a workspace. Returns each campaign with its count, rate, interval and rank, the campaigns left out for too few sends, those whose count the vendor does not report (a null rate is unknown, not zero), and the gap between the top and the median. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
1953
2466
  inputSchema: input8,
1954
2467
  key: "campaignRanking",
2468
+ cost: campaignTotalsCost,
2469
+ scales: "max_campaigns",
1955
2470
  name: "campaign_ranking",
1956
2471
  needs: ["stats.campaign"],
1957
2472
  next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
1958
2473
  run: async (context, options) => {
1959
- const entries = await readCampaignTotals(context, options);
2474
+ const { entries, read } = await readCampaignTotals(context, options);
1960
2475
  const ranking = {
1961
2476
  ...rankCampaigns(entries, options.metric, options.min_sent),
2477
+ ...read,
1962
2478
  better: options.metric === "bounce_rate" ? "lower" : "higher",
1963
2479
  metric: options.metric,
1964
2480
  period: { from: options.from, to: options.to }
@@ -1968,11 +2484,11 @@ var campaignRanking = defineInsight({
1968
2484
  });
1969
2485
 
1970
2486
  // src/insights/ops/channel-mix.ts
1971
- import { z as z11 } from "zod";
1972
- var input9 = z11.object({
2487
+ import { z as z12 } from "zod";
2488
+ var input9 = z12.object({
1973
2489
  ...rangeFields,
1974
2490
  ...listFields("one stats request"),
1975
- alpha: z11.number().gt(0).lt(1).default(0.05).describe(
2491
+ alpha: z12.number().gt(0).lt(1).default(0.05).describe(
1976
2492
  "The p-value under which a difference counts as more than chance"
1977
2493
  )
1978
2494
  });
@@ -2056,11 +2572,13 @@ var channelMix = defineInsight({
2056
2572
  description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. With one channel present it returns that channel and says there is nothing to compare. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2057
2573
  inputSchema: input9,
2058
2574
  key: "channelMix",
2575
+ cost: campaignTotalsCost,
2576
+ scales: "max_campaigns",
2059
2577
  name: "channel_mix",
2060
2578
  needs: ["stats.campaign"],
2061
2579
  next: "Use campaign_ranking to see which campaigns carry the better channel.",
2062
2580
  run: async (context, options) => {
2063
- const entries = await readCampaignTotals(context, options);
2581
+ const { entries, read } = await readCampaignTotals(context, options);
2064
2582
  const channels = byChannel(entries);
2065
2583
  const providers = byProvider(entries);
2066
2584
  for (const { group, partial } of channels) {
@@ -2076,6 +2594,7 @@ var channelMix = defineInsight({
2076
2594
  }
2077
2595
  }
2078
2596
  const mix = {
2597
+ ...read,
2079
2598
  ...compare(
2080
2599
  channels.map((each) => each.group),
2081
2600
  options.alpha
@@ -2089,15 +2608,15 @@ var channelMix = defineInsight({
2089
2608
  });
2090
2609
 
2091
2610
  // src/insights/ops/client-report.ts
2092
- import { z as z14 } from "zod";
2611
+ import { z as z15 } from "zod";
2093
2612
 
2094
2613
  // src/insights/ops/period-comparison.ts
2095
- import { z as z12 } from "zod";
2096
- var input10 = z12.object({
2614
+ import { z as z13 } from "zod";
2615
+ var input10 = z13.object({
2097
2616
  ...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(
2617
+ alpha: z13.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2618
+ days: z13.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2619
+ min_sent: z13.number().int().min(0).default(50).describe(
2101
2620
  "A campaign under this many sends in either period is listed apart"
2102
2621
  )
2103
2622
  });
@@ -2127,7 +2646,7 @@ var verdictOf = (test) => {
2127
2646
  }
2128
2647
  return test.z > 0 ? "up" : "down";
2129
2648
  };
2130
- var compare2 = (current, previous, alpha) => {
2649
+ var compare2 = (current, previous, basis, alpha) => {
2131
2650
  const now = current.rates.replyRate;
2132
2651
  const before = previous.rates.replyRate;
2133
2652
  const test = compareRates(
@@ -2135,30 +2654,39 @@ var compare2 = (current, previous, alpha) => {
2135
2654
  { successes: before.count, trials: before.of },
2136
2655
  alpha
2137
2656
  );
2138
- const moved = `Reply rate went from ${percent(before.rate)} to ${percent(now.rate)}`;
2657
+ const rateName = RATE_WORDS[basis];
2658
+ const moved = `${rateName} went from ${percent(before.rate)} to ${percent(now.rate)}`;
2139
2659
  const numbers = numbersOf(current.counts, current.rates);
2140
2660
  const earlier = numbersOf(previous.counts, previous.rates);
2141
2661
  return {
2142
2662
  change: changeOf(numbers, earlier),
2143
2663
  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)}).`,
2664
+ 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
2665
  previous: earlier,
2666
+ replyRateBasis: basis,
2146
2667
  replyRateTest: test,
2147
2668
  verdict: verdictOf(test)
2148
2669
  };
2149
2670
  };
2150
- var comparePeriods = (current, previous, alpha) => compare2(
2151
- { counts: current, rates: ratesOf(current) },
2152
- { counts: previous, rates: ratesOf(previous) },
2153
- alpha
2154
- );
2671
+ var comparePeriods = (current, previous, alpha) => {
2672
+ const basis = periodBasis(current, previous);
2673
+ return compare2(
2674
+ { counts: current, rates: ratesOf(current, baseIn2(basis)) },
2675
+ { counts: previous, rates: ratesOf(previous, baseIn2(basis)) },
2676
+ basis,
2677
+ alpha
2678
+ );
2679
+ };
2155
2680
  var compareAcross = (current, previous, alpha) => {
2156
- const now = ratesAcross(current);
2157
- const before = ratesAcross(previous);
2681
+ const counts = [sumCounts(current), sumCounts(previous)];
2682
+ const basis = periodBasis(...counts);
2683
+ const now = ratesAcross(current, baseIn2(basis));
2684
+ const before = ratesAcross(previous, baseIn2(basis));
2158
2685
  return {
2159
2686
  comparison: compare2(
2160
- { counts: sumCounts(current), rates: now.rates },
2161
- { counts: sumCounts(previous), rates: before.rates },
2687
+ { counts: counts[0], rates: now.rates },
2688
+ { counts: counts[1], rates: before.rates },
2689
+ basis,
2162
2690
  alpha
2163
2691
  ),
2164
2692
  partial: [
@@ -2170,13 +2698,13 @@ var compareAcross = (current, previous, alpha) => {
2170
2698
  var readPeriods = async (context, options) => {
2171
2699
  const current = lastDays(context.now, options.days);
2172
2700
  const previous = lastDays(context.now, options.days, 1);
2173
- const found = await readCampaigns(
2701
+ const listed = await readCampaignsIn(
2174
2702
  context,
2175
2703
  options.statuses,
2176
2704
  options.max_campaigns
2177
2705
  );
2178
2706
  const campaigns = await mapConcurrent(
2179
- found,
2707
+ listed.items,
2180
2708
  async (campaign) => {
2181
2709
  const [now, before] = await Promise.all([
2182
2710
  readTotals(context, campaign.ref, current),
@@ -2185,7 +2713,7 @@ var readPeriods = async (context, options) => {
2185
2713
  return { campaign, current: now, previous: before };
2186
2714
  }
2187
2715
  );
2188
- return { campaigns, current, previous };
2716
+ return { campaigns, current, previous, read: campaignsReadOf(listed) };
2189
2717
  };
2190
2718
  var totalOf = (campaigns, alpha) => compareAcross(
2191
2719
  campaigns.map((entry) => entry.current),
@@ -2216,9 +2744,11 @@ var workspaceOf = async (context, periods, alpha) => {
2216
2744
  );
2217
2745
  };
2218
2746
  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.",
2747
+ 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
2748
  inputSchema: input10,
2221
2749
  key: "periodComparison",
2750
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + 2 * price.campaigns(values.max_campaigns) * price.one("stats") + (price.capabilities["stats.workspace"] === false ? 0 : 2 * price.one("stats")),
2751
+ scales: "max_campaigns",
2222
2752
  name: "period_comparison",
2223
2753
  needs: ["stats.campaign"],
2224
2754
  next: "Use campaign_diagnosis on the campaign whose reply rate fell the most.",
@@ -2242,6 +2772,7 @@ var periodComparison = defineInsight({
2242
2772
  }
2243
2773
  }
2244
2774
  const comparison = {
2775
+ ...periods.read,
2245
2776
  campaigns: campaigns.toSorted(
2246
2777
  (left, right) => descending(
2247
2778
  left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
@@ -2264,11 +2795,11 @@ var periodComparison = defineInsight({
2264
2795
  });
2265
2796
 
2266
2797
  // 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.")
2798
+ import { z as z14 } from "zod";
2799
+ var input11 = z14.object({
2800
+ campaign: z14.string().min(3).describe("The campaign's ref"),
2801
+ days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2802
+ max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2272
2803
  });
2273
2804
  var countStatuses = (leads) => {
2274
2805
  const counts = {
@@ -2311,17 +2842,41 @@ var ASSUMPTIONS = [
2311
2842
  "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
2312
2843
  "The daily pace stays what it was over the recent days. Days with no report count as no sends."
2313
2844
  ];
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.`;
2845
+ var daysLeftOf = (byStatus, complete, pace) => {
2846
+ const remaining = byStatus.active;
2847
+ if (remaining === 0) {
2848
+ return complete && byStatus.unknown === 0 ? 0 : null;
2849
+ }
2850
+ return pace === null || pace <= 0 ? null : round(remaining / pace);
2851
+ };
2852
+ var describe2 = ({ complete, daysLeft, remaining }, forecast) => {
2853
+ if (daysLeft === 0) {
2854
+ return "No leads are left to contact; add leads to keep the campaign sending.";
2855
+ }
2856
+ const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
2857
+ if (forecast.expected === null) {
2858
+ return `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.`;
2859
+ }
2860
+ const [expected, low, high] = [
2861
+ forecast.expected,
2862
+ forecast.low,
2863
+ forecast.high
2864
+ ].map((value) => spoken(value));
2865
+ const range = low === high ? "" : ` (between ${low} and ${high})`;
2866
+ return `${leads}; expect about ${expected} ${noun(Number(expected), "reply", "replies")}${range}. This is an estimate.`;
2317
2867
  };
2318
2868
  var forecastCampaign = async (context, campaign, options) => {
2319
2869
  const handle = context.outbound.campaign(campaign.ref);
2320
- const { complete, items: leads } = await readUpTo(
2870
+ const { capped: capped2, items: leads } = await readCapped(
2321
2871
  context,
2322
2872
  (max) => handle.leads.listAll({ max }),
2323
- options.maxLeads
2873
+ {
2874
+ input: options.leadsInput,
2875
+ max: options.maxLeads,
2876
+ what: options.leadsWhat
2877
+ }
2324
2878
  );
2879
+ const complete = !capped2;
2325
2880
  const byStatus = countStatuses(leads);
2326
2881
  const remaining = byStatus.active;
2327
2882
  const rates = ratesOf(
@@ -2329,19 +2884,20 @@ var forecastCampaign = async (context, campaign, options) => {
2329
2884
  );
2330
2885
  const pace = await paceOf(context, campaign.ref, options.days);
2331
2886
  const expectedReplies = project(remaining, rates.replyRate);
2887
+ const daysLeft = daysLeftOf(byStatus, complete, pace);
2332
2888
  return {
2333
2889
  ...labelOf(campaign),
2334
2890
  assumptions: [
2335
2891
  ...ASSUMPTIONS,
2336
- `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count ?? "unknown"} replies over ${rates.replyRate.of ?? "unknown"}.`
2892
+ `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
2893
  ],
2338
2894
  byStatus,
2339
2895
  dailyContactRate: pace,
2340
- daysLeft: pace === null || pace <= 0 ? null : round(remaining / pace),
2896
+ daysLeft,
2341
2897
  estimate: true,
2342
2898
  expectedPositive: project(remaining, rates.positiveRate),
2343
2899
  expectedReplies,
2344
- finding: describe2(remaining, complete, expectedReplies),
2900
+ finding: describe2({ complete, daysLeft, remaining }, expectedReplies),
2345
2901
  leadsComplete: complete,
2346
2902
  leadsRead: leads.length,
2347
2903
  positiveRate: rates.positiveRate,
@@ -2353,6 +2909,8 @@ var pipelineForecast = defineInsight({
2353
2909
  description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, the days of sending left at the recent daily contact rate, and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
2354
2910
  inputSchema: input11,
2355
2911
  key: "pipelineForecast",
2912
+ cost: (values, price) => price.one("campaigns.get") + price.list("leads.list", values.max_leads) + price.one("stats") + (price.capabilities["stats.byDay"] === false ? 0 : price.one("stats")),
2913
+ scales: "max_leads",
2356
2914
  name: "pipeline_forecast",
2357
2915
  needs: ["leads.byCampaign", "stats.campaign"],
2358
2916
  next: "Use client_report to see every campaign that is running out of leads.",
@@ -2362,32 +2920,54 @@ var pipelineForecast = defineInsight({
2362
2920
  );
2363
2921
  return await forecastCampaign(context, campaign, {
2364
2922
  days: options.days,
2923
+ leadsInput: "max_leads",
2924
+ leadsWhat: "leads",
2365
2925
  maxLeads: options.max_leads
2366
2926
  });
2367
2927
  }
2368
2928
  });
2369
2929
 
2370
2930
  // src/insights/ops/client-report.ts
2371
- var input12 = z14.object({
2931
+ var limit2 = z15.number().int().min(1).max(20);
2932
+ var input12 = z15.object({
2372
2933
  ...listFields(
2373
2934
  "two stats requests, and three more plus its leads when active"
2374
2935
  ),
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(
2936
+ alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2937
+ anomaly_threshold: z15.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2938
+ baseline_days: z15.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2939
+ days: z15.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2940
+ limit: limit2.default(3).describe("How many best and worst campaigns to show"),
2941
+ max_bounce_rate: z15.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2942
+ max_leads_per_campaign: z15.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2943
+ min_baseline_points: z15.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2944
+ min_sent: z15.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2945
+ runway_days: z15.number().min(0).default(7).describe(
2384
2946
  "A campaign with this many days of leads left or fewer is flagged"
2385
2947
  ),
2386
- top: z14.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show")
2948
+ top: renamed("limit", limit2)
2387
2949
  });
2950
+ var sendingLeft = (daysLeft) => {
2951
+ if (daysLeft !== null && daysLeft < 0.05) {
2952
+ return "less than a day of sending";
2953
+ }
2954
+ const days = spoken(daysLeft);
2955
+ return `about ${days} ${days === "1" ? "day" : "days"} of sending`;
2956
+ };
2388
2957
  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 }] : [];
2958
+ const { count: count2, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
2959
+ return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [
2960
+ {
2961
+ ...labelOf(campaign),
2962
+ bounced: count2,
2963
+ count: count2,
2964
+ high,
2965
+ low,
2966
+ of,
2967
+ rate: rate2,
2968
+ sent: of
2969
+ }
2970
+ ] : [];
2391
2971
  }).toSorted((left, right) => right.rate - left.rate);
2392
2972
  var readAnomalies = async (context, period, options) => {
2393
2973
  const { capabilities } = context.outbound;
@@ -2420,6 +3000,8 @@ var readRunways = async (context, campaigns, options) => {
2420
3000
  campaign,
2421
3001
  forecast: await forecastCampaign(context, campaign, {
2422
3002
  days: options.days,
3003
+ leadsInput: "max_leads_per_campaign",
3004
+ leadsWhat: "leads of a campaign",
2423
3005
  maxLeads: options.max_leads_per_campaign
2424
3006
  })
2425
3007
  }));
@@ -2437,25 +3019,26 @@ var readRunways = async (context, campaigns, options) => {
2437
3019
  };
2438
3020
  var actionsOf = (report) => {
2439
3021
  const [worst] = report.bottom;
2440
- const { current, previous } = report.totals;
3022
+ const { current, previous, replyRateBasis } = report.totals;
3023
+ const perWhat = RATE_WORDS[replyRateBasis].toLowerCase();
2441
3024
  return [
2442
3025
  ...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).`,
3026
+ action: `Fix the bounces of ${problem.campaignName}: its bounce rate is ${percent(problem.rate)} (${problem.count} of ${problem.of} sends).`,
2444
3027
  campaign: problem.campaign,
2445
- campaignName: problem.name,
3028
+ campaignName: problem.campaignName,
2446
3029
  kind: "fix_bounces",
2447
3030
  number: problem.rate
2448
3031
  })),
2449
3032
  ...(report.runningOutOfLeads ?? []).map((runway) => ({
2450
- action: `Add leads to ${runway.name}: ${runway.remaining} leads remain, about ${runway.daysLeft} days of sending.`,
3033
+ 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
3034
  campaign: runway.campaign,
2452
- campaignName: runway.name,
3035
+ campaignName: runway.campaignName,
2453
3036
  kind: "add_leads",
2454
3037
  number: runway.daysLeft
2455
3038
  })),
2456
3039
  ...report.totals.verdict === "down" ? [
2457
3040
  {
2458
- action: `Find out what changed: the reply rate fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
3041
+ action: `Find out what changed: ${perWhat} fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
2459
3042
  campaign: null,
2460
3043
  campaignName: null,
2461
3044
  kind: "reply_rate_fell",
@@ -2464,9 +3047,9 @@ var actionsOf = (report) => {
2464
3047
  ] : [],
2465
3048
  ...worst === void 0 ? [] : [
2466
3049
  {
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}).`,
3050
+ action: `Review the copy and the audience of ${worst.campaignName}: it has the fewest ${perWhat}, ${percent(worst.rate)} (${worst.count} of ${worst.of}).`,
2468
3051
  campaign: worst.campaign,
2469
- campaignName: worst.name,
3052
+ campaignName: worst.campaignName,
2470
3053
  kind: "review_campaign",
2471
3054
  number: worst.rate
2472
3055
  }
@@ -2481,32 +3064,41 @@ var actionsOf = (report) => {
2481
3064
  ];
2482
3065
  };
2483
3066
  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.",
3067
+ 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
3068
  inputSchema: input12,
2486
3069
  key: "clientReport",
3070
+ cost: (values, price) => {
3071
+ const { capabilities } = price;
3072
+ const campaigns = price.campaigns(values.max_campaigns);
3073
+ const byDay = capabilities["stats.byDay"] !== false;
3074
+ return price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + 2 * campaigns * price.one("stats") + (byDay && capabilities["stats.workspace"] !== false ? price.one("stats") : 0) + (byDay && capabilities["leads.byCampaign"] !== false ? price.upTo(campaigns) * (price.list("leads.list", values.max_leads_per_campaign) + 2 * price.one("stats")) : 0);
3075
+ },
3076
+ scales: "max_campaigns",
2487
3077
  name: "client_report",
2488
3078
  needs: ["stats.campaign"],
2489
- next: "Use campaign_diagnosis on a campaign an action item names, or period_comparison for every campaign's change.",
3079
+ 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
3080
  run: async (context, options) => {
2491
3081
  const periods = await readPeriods(context, options);
3082
+ const totals = noted(
3083
+ context,
3084
+ "Totals",
3085
+ totalOf(periods.campaigns, options.alpha)
3086
+ );
2492
3087
  const ranking = rankCampaigns(
2493
3088
  periods.campaigns.map((entry) => ({
2494
3089
  campaign: entry.campaign,
2495
3090
  counts: entry.current
2496
3091
  })),
2497
3092
  "reply_rate",
2498
- options.min_sent
3093
+ options.min_sent,
3094
+ totals.replyRateBasis
2499
3095
  );
2500
3096
  const sections = {
2501
3097
  anomalies: await readAnomalies(context, periods.current, options),
2502
- bottom: ranking.ranked.slice(options.top).slice(-options.top).toReversed(),
3098
+ bottom: ranking.ranked.slice(options.limit).slice(-options.limit).toReversed(),
2503
3099
  bounceProblems: bounceProblems(periods.campaigns, options),
2504
3100
  runningOutOfLeads: await readRunways(context, periods.campaigns, options),
2505
- totals: noted(
2506
- context,
2507
- "Totals",
2508
- totalOf(periods.campaigns, options.alpha)
2509
- )
3101
+ totals
2510
3102
  };
2511
3103
  const leftOut = [
2512
3104
  ...sections.anomalies === null ? ["Unusual days: the adapter has no workspace stats by day."] : [],
@@ -2519,24 +3111,26 @@ var clientReport = defineInsight({
2519
3111
  }
2520
3112
  const report = {
2521
3113
  ...sections,
3114
+ ...periods.read,
2522
3115
  actions: actionsOf(sections),
2523
3116
  campaigns: periods.campaigns.length,
2524
3117
  days: options.days,
2525
3118
  leftOut,
2526
3119
  period: periods.current,
2527
3120
  previousPeriod: periods.previous,
2528
- top: ranking.ranked.slice(0, options.top)
3121
+ replyRateBasis: totals.replyRateBasis,
3122
+ top: ranking.ranked.slice(0, options.limit)
2529
3123
  };
2530
3124
  return report;
2531
3125
  }
2532
3126
  });
2533
3127
 
2534
3128
  // src/insights/ops/tag-rollup.ts
2535
- import { z as z15 } from "zod";
2536
- var input13 = z15.object({
3129
+ import { z as z16 } from "zod";
3130
+ var input13 = z16.object({
2537
3131
  ...rangeFields,
2538
3132
  ...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")
3133
+ min_sent: z16.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
2540
3134
  });
2541
3135
  var groupOf2 = (tag, entries) => {
2542
3136
  const counts = entries.map((entry) => entry.counts);
@@ -2556,11 +3150,17 @@ var tagRollup = defineInsight({
2556
3150
  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
3151
  inputSchema: input13,
2558
3152
  key: "tagRollup",
3153
+ // A tool whose campaigns carry no tags would put every campaign under one
3154
+ // null tag, which reads as an answer. On a combined instance one tool with
3155
+ // tags is enough.
3156
+ lacks: (outbound) => outbound.fields.campaign["tags"] === false ? "campaign tags" : null,
3157
+ cost: campaignTotalsCost,
3158
+ scales: "max_campaigns",
2559
3159
  name: "tag_rollup",
2560
3160
  needs: ["stats.campaign"],
2561
3161
  next: "Use campaign_ranking to see the campaigns inside the best and the worst tag.",
2562
3162
  run: async (context, options) => {
2563
- const entries = await readCampaignTotals(context, options);
3163
+ const { entries, read } = await readCampaignTotals(context, options);
2564
3164
  const members = /* @__PURE__ */ new Map();
2565
3165
  for (const entry of entries) {
2566
3166
  const tags = entry.campaign.tags.length === 0 ? [null] : entry.campaign.tags;
@@ -2584,6 +3184,7 @@ var tagRollup = defineInsight({
2584
3184
  );
2585
3185
  const enough2 = (group) => (volumeOf(group) ?? 0) >= options.min_sent;
2586
3186
  const rollup = {
3187
+ ...read,
2587
3188
  campaigns: entries.length,
2588
3189
  period: { from: options.from, to: options.to },
2589
3190
  tags: groups.filter(enough2),
@@ -2606,47 +3207,44 @@ var OPS_INSIGHTS = [
2606
3207
  ];
2607
3208
 
2608
3209
  // src/insights/people/account-summary.ts
2609
- import { z as z17 } from "zod";
3210
+ import { z as z18 } from "zod";
2610
3211
 
2611
3212
  // 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"
2624
- );
2625
- return every.filter((campaign) => wanted.includes(campaign.status));
3213
+ import { z as z17 } from "zod";
3214
+ var readCappedFlag = (context, open, max, what, input27) => readCapped(context, open, { input: input27, max, what });
3215
+ var readByRef = async (context, refs, read, what, effect) => {
3216
+ if (refs.length === 0) {
3217
+ return /* @__PURE__ */ new Map();
2626
3218
  }
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"
3219
+ const found = await read(refs);
3220
+ if (found.errors.length > 0) {
3221
+ context.note(
3222
+ `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
2639
3223
  );
2640
- campaigns.push(...found);
2641
3224
  }
2642
- return campaigns;
3225
+ const [costliest] = found.results.toSorted(
3226
+ (left, right) => right.value.meta.requests - left.value.meta.requests
3227
+ );
3228
+ if (costliest !== void 0) {
3229
+ context.one(costliest.value);
3230
+ }
3231
+ return new Map(found.results.map(({ id, value }) => [id, value]));
3232
+ };
3233
+ var statusesField = statusesInput(["active"]);
3234
+ var campaignsIn = async (context, statuses, max) => {
3235
+ const { items } = await readCampaignsIn(context, statuses, max);
3236
+ return items;
3237
+ };
3238
+ var leadsOf = async (context, campaign, max, input27) => {
3239
+ const { items } = await readCappedFlag(
3240
+ context,
3241
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
3242
+ max,
3243
+ "leads of a campaign",
3244
+ input27
3245
+ );
3246
+ return items;
2643
3247
  };
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
3248
  var nameOf = (lead) => {
2651
3249
  const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
2652
3250
  return name === "" ? null : name;
@@ -2660,13 +3258,24 @@ var DEFAULT_POSITIVE_LABELS = [
2660
3258
  "Meeting Booked",
2661
3259
  "Meeting Completed"
2662
3260
  ];
2663
- var positiveLabelsField = z16.array(z16.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
3261
+ var positiveLabelsField = z17.array(z17.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
2664
3262
  "Vendor interest labels that count as interested, matched without regard to case"
2665
3263
  );
2666
3264
  var isPositive = (label, labels) => label === null ? null : labels.some(
2667
3265
  (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
2668
3266
  );
2669
3267
  var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
3268
+ var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
3269
+ var AUTOMATIC = /* @__PURE__ */ new Set([
3270
+ "bounce",
3271
+ "ooo"
3272
+ ]);
3273
+ var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
3274
+ lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
3275
+ var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
3276
+ var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
3277
+ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
3278
+ var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
2670
3279
  var COUNTS = "no per-lead open, click or reply counts";
2671
3280
  var noteEngagement = (context, leads, effect) => {
2672
3281
  const { outbound } = context;
@@ -2689,17 +3298,17 @@ var noteEngagement = (context, leads, effect) => {
2689
3298
  };
2690
3299
 
2691
3300
  // src/insights/people/account-summary.ts
2692
- var input14 = z17.object({
2693
- allow_free_domains: z17.boolean().default(false).describe(
3301
+ var input14 = z18.object({
3302
+ allow_free_domains: z18.boolean().default(false).describe(
2694
3303
  "Set to true to accept an email provider domain such as gmail.com, which is not one company"
2695
3304
  ),
2696
- domain: z17.string().min(3).describe(
3305
+ domain: z18.string().min(3).describe(
2697
3306
  "The company's domain, for example acme.com, or an email address whose domain is used"
2698
3307
  ),
2699
- max_campaigns: z17.number().int().min(1).max(200).default(20).describe(
3308
+ max_campaigns: z18.number().int().min(1).max(200).default(20).describe(
2700
3309
  "The most campaigns to read leads from when the tool cannot list every lead at once"
2701
3310
  ),
2702
- max_leads: z17.number().int().min(1).max(2e4).default(1e3).describe(
3311
+ max_leads: z18.number().int().min(1).max(2e4).default(1e3).describe(
2703
3312
  "The most leads to read in all. A vendor request returns about 50 to 100 leads."
2704
3313
  ),
2705
3314
  positive_labels: positiveLabelsField
@@ -2738,11 +3347,12 @@ var parseDomain = (text, provider) => {
2738
3347
  var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLeads }) => {
2739
3348
  const { outbound } = context;
2740
3349
  if (outbound.capabilities["leads.list"]) {
2741
- return await readCapped2(
3350
+ return await readCappedFlag(
2742
3351
  context,
2743
3352
  (cap) => outbound.leads.listAll({ max: cap }),
2744
3353
  maxLeads,
2745
- "leads"
3354
+ "leads",
3355
+ "max_leads"
2746
3356
  );
2747
3357
  }
2748
3358
  if (!outbound.capabilities["leads.byCampaign"]) {
@@ -2752,22 +3362,34 @@ var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLea
2752
3362
  { provider: outbound.provider }
2753
3363
  );
2754
3364
  }
2755
- const campaigns = await readCapped2(
3365
+ const campaigns = await readCappedFlag(
2756
3366
  context,
2757
3367
  (cap) => outbound.campaigns.listAll({ max: cap }),
2758
3368
  maxCampaigns,
2759
- "campaigns"
3369
+ "campaigns",
3370
+ "max_campaigns"
2760
3371
  );
2761
3372
  const leads = [];
2762
- for (const campaign of campaigns) {
3373
+ let { capped: capped2 } = campaigns;
3374
+ for (const campaign of campaigns.items) {
2763
3375
  if (leads.length >= maxLeads) {
2764
- context.partial(`Stopped at ${maxLeads} leads; more campaigns remain.`);
3376
+ context.partial(
3377
+ `Stopped at ${plural(maxLeads, "lead")} (max_leads); more campaigns remain.`
3378
+ );
3379
+ capped2 = true;
2765
3380
  break;
2766
3381
  }
2767
- const found = await leadsOf(context, campaign.ref, maxLeads - leads.length);
2768
- leads.push(...found);
3382
+ const found = await readCappedFlag(
3383
+ context,
3384
+ (cap) => outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
3385
+ maxLeads - leads.length,
3386
+ "leads of a campaign",
3387
+ "max_leads"
3388
+ );
3389
+ leads.push(...found.items);
3390
+ capped2 ||= found.capped;
2769
3391
  }
2770
- return leads;
3392
+ return { capped: capped2, items: leads };
2771
3393
  };
2772
3394
  var toRecord = (lead) => ({
2773
3395
  campaign: lead.campaignRef,
@@ -2779,11 +3401,13 @@ var toRecord = (lead) => ({
2779
3401
  opens: lead.engagement?.opens ?? null,
2780
3402
  provider: lead.provider,
2781
3403
  replies: lead.engagement?.replies ?? null,
3404
+ autoReplied: isAutoReplied(lead),
2782
3405
  status: lead.status
2783
3406
  });
2784
3407
  var latest = (times3) => times3.flatMap((time) => time === null ? [] : [time]).toSorted().at(-1) ?? null;
2785
3408
  var toPerson = (email, leads, labels) => {
2786
3409
  const records = leads.map(toRecord);
3410
+ const human = records.filter((record) => !record.autoReplied);
2787
3411
  const verdicts = leads.map((lead) => isPositive(lead.interest, labels));
2788
3412
  const pick = (read) => leads.map(read).find((value) => value !== null) ?? null;
2789
3413
  return {
@@ -2798,12 +3422,12 @@ var toPerson = (email, leads, labels) => {
2798
3422
  company: pick((lead) => lead.company),
2799
3423
  email,
2800
3424
  interested: verdicts.includes(true) ? true : verdicts.find((verdict) => verdict !== null) ?? null,
2801
- lastRepliedAt: latest(records.map((record) => record.lastRepliedAt)),
3425
+ lastRepliedAt: latest(human.map((record) => record.lastRepliedAt)),
2802
3426
  name: pick(nameOf),
2803
3427
  opens: total(records.map((record) => record.opens)),
2804
3428
  records,
2805
- replied: leads.some(hasReplied),
2806
- replies: total(records.map((record) => record.replies)),
3429
+ replied: leads.some(hasHumanReply),
3430
+ replies: total(human.map((record) => record.replies)),
2807
3431
  title: pick((lead) => lead.title)
2808
3432
  };
2809
3433
  };
@@ -2821,12 +3445,22 @@ var lastReplyOf = (people) => {
2821
3445
  };
2822
3446
  };
2823
3447
  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.",
3448
+ 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
3449
  inputSchema: input14,
2826
3450
  key: "accountSummary",
3451
+ // Every address is masked, so no lead's domain can be read. A hash keeps
3452
+ // exact matching but not the domain.
3453
+ maskedOut: ({ fields, strategy }) => {
3454
+ if (!fields.includes("email")) {
3455
+ return null;
3456
+ }
3457
+ 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";
3458
+ },
3459
+ cost: (values, price) => price.capabilities["leads.list"] === false ? price.list("campaigns.list", values.max_campaigns) + price.upTo(values.max_campaigns - 1) * price.list("leads.list", 1) + price.upTo(1) * price.list("leads.list", values.max_leads) : price.list("leads.list", values.max_leads),
3460
+ scales: "max_leads",
2827
3461
  name: "account_summary",
2828
3462
  needs: [],
2829
- next: "Use person_summary with one person's email address for their full history, message by message.",
3463
+ next: "Use person_summary with one person's email address or lead ref for their full history, message by message.",
2830
3464
  run: async (context, values) => {
2831
3465
  const domain = parseDomain(values.domain, context.outbound.provider);
2832
3466
  if (FREE_DOMAINS.has(domain) && !values.allow_free_domains) {
@@ -2836,7 +3470,8 @@ var accountSummary = defineInsight({
2836
3470
  { provider: context.outbound.provider }
2837
3471
  );
2838
3472
  }
2839
- const leads = await readLeads(context, values);
3473
+ const read = await readLeads(context, values);
3474
+ const leads = read.items;
2840
3475
  noteEngagement(context, leads, "those are null");
2841
3476
  const byEmail = /* @__PURE__ */ new Map();
2842
3477
  for (const lead of leads) {
@@ -2856,6 +3491,7 @@ var accountSummary = defineInsight({
2856
3491
  interested: people.filter((person) => person.interested === true).length,
2857
3492
  leadsRead: leads.length,
2858
3493
  leadsWithoutEmail: leads.filter((lead) => lead.email === null).length,
3494
+ moreLeadsExist: read.capped,
2859
3495
  people: people.length,
2860
3496
  records: people.reduce((sum, each) => sum + each.records.length, 0),
2861
3497
  replied: people.filter((person) => person.replied).length
@@ -2866,24 +3502,25 @@ var accountSummary = defineInsight({
2866
3502
  });
2867
3503
 
2868
3504
  // src/insights/people/dropped-replies.ts
2869
- import { z as z18 } from "zod";
3505
+ import { z as z19 } from "zod";
2870
3506
  var HOUR = 36e5;
2871
3507
  var DAY = 24 * HOUR;
3508
+ var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
2872
3509
  var DEFAULT_DAYS = 14;
2873
- var input15 = z18.object({
2874
- categories: z18.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
3510
+ var input15 = z19.object({
3511
+ categories: z19.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
2875
3512
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
2876
3513
  ),
2877
- include_auto: z18.boolean().default(false).describe(
3514
+ include_auto: z19.boolean().default(false).describe(
2878
3515
  "Set to true to also check replies the vendor marks as automatic"
2879
3516
  ),
2880
- max_replies: z18.number().int().min(1).max(1e3).default(50).describe(
3517
+ max_replies: z19.number().int().min(1).max(1e3).default(50).describe(
2881
3518
  "The most replies to read. Each conversation among them costs one more request to check."
2882
3519
  ),
2883
- older_than_hours: z18.number().min(0).default(24).describe(
3520
+ older_than_hours: z19.number().min(0).default(24).describe(
2884
3521
  "A reply counts as dropped only after waiting this many hours without an answer"
2885
3522
  ),
2886
- since: z18.union([z18.iso.datetime({ offset: true }), z18.iso.date()]).nullable().default(null).describe(
3523
+ since: z19.union([z19.iso.datetime({ offset: true }), z19.iso.date()]).nullable().default(null).describe(
2887
3524
  "Only replies received at or after this ISO 8601 time. Null means 14 days before now."
2888
3525
  )
2889
3526
  });
@@ -2935,12 +3572,16 @@ var toDropped = (open, by, now) => {
2935
3572
  return [
2936
3573
  {
2937
3574
  campaign: first.campaignRef,
3575
+ campaignName: null,
2938
3576
  category: first.category,
2939
3577
  channel: first.channel,
2940
3578
  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.`,
3579
+ finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${waited(hoursWaiting)} with nothing sent after it.`,
2942
3580
  hoursWaiting,
3581
+ email: null,
2943
3582
  lead: first.leadRef,
3583
+ linkedinUrl: null,
3584
+ name: null,
2944
3585
  provider: first.provider,
2945
3586
  receivedAt: first.sentAt,
2946
3587
  reply: first.ref,
@@ -2949,6 +3590,52 @@ var toDropped = (open, by, now) => {
2949
3590
  }
2950
3591
  ];
2951
3592
  };
3593
+ var refsOf = (refs) => [
3594
+ ...new Set(refs.flatMap((ref) => ref === null ? [] : [ref]))
3595
+ ];
3596
+ var named2 = async (context, dropped) => {
3597
+ const { outbound } = context;
3598
+ const readLeads2 = outbound.capabilities["leads.get"];
3599
+ const leadRefs = readLeads2 ? refsOf(dropped.map((each) => each.lead)) : [];
3600
+ if (!readLeads2 && dropped.length > 0) {
3601
+ context.note(
3602
+ "This tool cannot read one lead (leads.get), so name, email and linkedinUrl are null."
3603
+ );
3604
+ }
3605
+ const unlinked = dropped.filter((each) => each.lead === null).length;
3606
+ if (unlinked > 0) {
3607
+ context.note(
3608
+ `${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.`
3609
+ );
3610
+ }
3611
+ const [leads, campaigns] = await Promise.all([
3612
+ readByRef(
3613
+ context,
3614
+ leadRefs,
3615
+ (refs) => outbound.leads.getMany(refs),
3616
+ ["lead", "leads"],
3617
+ "names are null"
3618
+ ),
3619
+ readByRef(
3620
+ context,
3621
+ refsOf(dropped.map((each) => each.campaign)),
3622
+ (refs) => outbound.campaigns.getMany(refs),
3623
+ ["campaign", "campaigns"],
3624
+ "names are null"
3625
+ )
3626
+ ]);
3627
+ return dropped.map((each) => {
3628
+ const lead = each.lead === null ? void 0 : leads.get(each.lead);
3629
+ const campaign = each.campaign === null ? void 0 : campaigns.get(each.campaign);
3630
+ return {
3631
+ ...each,
3632
+ campaignName: campaign?.name ?? null,
3633
+ email: lead?.email ?? null,
3634
+ linkedinUrl: lead?.linkedinUrl ?? null,
3635
+ name: lead === void 0 ? null : nameOf(lead)
3636
+ };
3637
+ });
3638
+ };
2952
3639
  var readReplies = (context, since, max) => {
2953
3640
  const { outbound } = context;
2954
3641
  const filtered = outbound.capabilities["replies.since"] !== false;
@@ -2957,20 +3644,23 @@ var readReplies = (context, since, max) => {
2957
3644
  "This tool cannot filter replies by date, so the newest replies were read and filtered here."
2958
3645
  );
2959
3646
  }
2960
- return readCapped2(
3647
+ return readCappedFlag(
2961
3648
  context,
2962
3649
  (cap) => outbound.replies.listAll(filtered ? { max: cap, since } : { max: cap }),
2963
3650
  max,
2964
- "replies"
3651
+ "replies",
3652
+ "max_replies"
2965
3653
  );
2966
3654
  };
2967
3655
  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.",
3656
+ 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
3657
  inputSchema: input15,
2970
3658
  key: "droppedReplies",
3659
+ cost: (values, price) => price.list("replies.list", values.max_replies) + price.upTo(values.max_replies) * (price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.one("leads.get")) + price.one("campaigns.get")),
3660
+ scales: "max_replies",
2971
3661
  name: "dropped_replies",
2972
3662
  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.",
3663
+ 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
3664
  run: async (context, values) => {
2975
3665
  const since = new Date(
2976
3666
  values.since === null ? context.now - DEFAULT_DAYS * DAY : Date.parse(values.since)
@@ -2981,7 +3671,8 @@ var droppedReplies = defineInsight({
2981
3671
  "This tool can read neither a conversation nor a lead's timeline, so no reply could be checked."
2982
3672
  );
2983
3673
  }
2984
- const read = await readReplies(context, since, values.max_replies);
3674
+ const listed = await readReplies(context, since, values.max_replies);
3675
+ const read = listed.items;
2985
3676
  const replies2 = read.filter(
2986
3677
  (reply) => reply.sentAt === null || Date.parse(reply.sentAt) >= Date.parse(since)
2987
3678
  );
@@ -3018,8 +3709,9 @@ var droppedReplies = defineInsight({
3018
3709
  answered += found.length === 0 ? 1 : 0;
3019
3710
  tooRecent += found.length - old.length;
3020
3711
  }
3712
+ const withNames = await named2(context, dropped);
3021
3713
  const answer = {
3022
- dropped: dropped.toSorted(
3714
+ dropped: withNames.toSorted(
3023
3715
  (left, right) => right.hoursWaiting - left.hoursWaiting || left.reply.localeCompare(right.reply)
3024
3716
  ),
3025
3717
  olderThanHours: values.older_than_hours,
@@ -3028,6 +3720,7 @@ var droppedReplies = defineInsight({
3028
3720
  answered,
3029
3721
  conversations: conversations.length,
3030
3722
  dropped: dropped.length,
3723
+ moreRepliesExist: listed.capped,
3031
3724
  repliesRead: read.length,
3032
3725
  skippedAuto: wanted.length - kept.length,
3033
3726
  skippedByCategory: replies2.length - wanted.length,
@@ -3040,22 +3733,28 @@ var droppedReplies = defineInsight({
3040
3733
  });
3041
3734
 
3042
3735
  // src/insights/people/hot-leads.ts
3043
- import { z as z19 } from "zod";
3736
+ import { z as z20 } from "zod";
3044
3737
  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(
3738
+ var RECENT_REPLIES = 100;
3739
+ var NOT_ENGAGED = /* @__PURE__ */ new Set([
3740
+ "bounce",
3741
+ "ooo",
3742
+ "unsubscribe"
3743
+ ]);
3744
+ var weight = (value, what) => z20.number().min(0).default(value).describe(what);
3745
+ var input16 = z20.object({
3746
+ campaign: z20.string().min(1).nullable().default(null).describe(
3048
3747
  "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3049
3748
  ),
3050
- count_cap: z19.number().int().min(1).default(5).describe(
3749
+ count_cap: z20.number().int().min(1).default(5).describe(
3051
3750
  "The most replies, clicks or opens that earn points, so 40 opens do not outrank a reply"
3052
3751
  ),
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."
3752
+ limit: z20.number().int().min(1).max(500).default(20).describe("How many leads to return"),
3753
+ max_leads: z20.number().int().min(1).max(2e4).default(500).describe(
3754
+ "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
3755
  ),
3057
3756
  positive_labels: positiveLabelsField,
3058
- recency_days: z19.number().min(1).default(14).describe(
3757
+ recency_days: z20.number().min(1).default(14).describe(
3059
3758
  "A reply today earns the full recency points, fading evenly to none after this many days"
3060
3759
  ),
3061
3760
  weight_click: weight(5, "Points for each click, up to count_cap"),
@@ -3064,38 +3763,55 @@ var input16 = z19.object({
3064
3763
  weight_recency: weight(20, "Points for a reply received right now"),
3065
3764
  weight_reply: weight(10, "Points for each reply, up to count_cap")
3066
3765
  });
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;
3766
+ var capped = (count2, points, cap) => count2 === null ? null : Math.min(count2, cap) * points;
3767
+ var saidNo = (lead, labels) => !isAutoReplied(lead) && isNegative(lead) && isPositive(lead.interest, labels) !== true;
3768
+ var repliesDiscounted = (lead, labels) => isAutoReplied(lead) || saidNo(lead, labels);
3769
+ var engagementParts = (lead, values) => {
3770
+ const unwanted = saidNo(lead, values.positive_labels);
3074
3771
  return {
3075
3772
  clicks: capped(
3076
- engagement?.clicks ?? null,
3077
- values.weight_click,
3773
+ lead.engagement?.clicks ?? null,
3774
+ unwanted ? 0 : values.weight_click,
3078
3775
  values.count_cap
3079
3776
  ),
3080
- interest: positive === null ? null : Number(positive) * values.weight_interest,
3081
3777
  opens: capped(
3082
- engagement?.opens ?? null,
3083
- values.weight_open,
3778
+ lead.engagement?.opens ?? null,
3779
+ unwanted ? 0 : values.weight_open,
3084
3780
  values.count_cap
3085
- ),
3086
- recency: age === null ? null : round(Math.max(0, 1 - age) * values.weight_recency),
3781
+ )
3782
+ };
3783
+ };
3784
+ var partsOf = (lead, values, now) => {
3785
+ const engagement = lead.engagement ?? null;
3786
+ const positive = isPositive(lead.interest, values.positive_labels);
3787
+ const automatic = repliesDiscounted(lead, values.positive_labels);
3788
+ const counted2 = engagement?.replies ?? (lead.replied === true ? 1 : null);
3789
+ const replies2 = automatic && counted2 !== null ? 0 : counted2;
3790
+ const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
3791
+ const age = repliedAt === null ? null : Math.max(0, now - Date.parse(repliedAt)) / DAY2 / values.recency_days;
3792
+ const fresh = age === null ? null : Math.max(0, 1 - age);
3793
+ const { clicks, opens } = engagementParts(lead, values);
3794
+ return {
3795
+ clicks,
3796
+ interest: positive === null ? null : Number(positive) * values.weight_interest,
3797
+ opens,
3798
+ recency: automatic && counted2 !== null ? 0 : round(fresh === null ? null : fresh * values.weight_recency),
3087
3799
  replies: capped(replies2, values.weight_reply, values.count_cap)
3088
3800
  };
3089
3801
  };
3090
- var reasonOf = (lead, parts, now) => {
3802
+ 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`;
3803
+ var counted = (points, amount, what) => (points ?? 0) > 0 ? plural(amount ?? 0, what) : null;
3804
+ var reasonOf = (lead, parts, now, labels) => {
3091
3805
  const engagement = lead.engagement ?? null;
3092
- const repliedAt = engagement?.lastRepliedAt ?? null;
3806
+ const automatic = repliesDiscounted(lead, labels);
3807
+ const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
3093
3808
  const facts = [
3094
3809
  (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
3810
+ automatic ? discountedReason(lead) : null,
3811
+ (parts.replies ?? 0) > 0 ? `replied ${plural(engagement?.replies ?? 1, "time")}` : null,
3812
+ repliedAt === null ? null : `last reply ${plural(Math.floor(Math.max(0, now - Date.parse(repliedAt)) / DAY2), "day")} ago`,
3813
+ counted(parts.clicks, engagement?.clicks, "click"),
3814
+ counted(parts.opens, engagement?.opens, "open")
3099
3815
  ].flatMap((fact) => fact === null ? [] : [fact]);
3100
3816
  return `${facts.join(", ")}.`;
3101
3817
  };
@@ -3115,7 +3831,7 @@ var toHotLead = (lead, values, now) => {
3115
3831
  name: nameOf(lead),
3116
3832
  opens: lead.engagement?.opens ?? null,
3117
3833
  parts,
3118
- reason: reasonOf(lead, parts, now),
3834
+ reason: reasonOf(lead, parts, now, values.positive_labels),
3119
3835
  replies: lead.engagement?.replies ?? null,
3120
3836
  score: round(score) ?? 0,
3121
3837
  status: lead.status,
@@ -3123,35 +3839,77 @@ var toHotLead = (lead, values, now) => {
3123
3839
  }
3124
3840
  ];
3125
3841
  };
3126
- var readLeads2 = (context, { campaign, max_leads: maxLeads }) => {
3842
+ var listLeads = async (context, { campaign, max_leads: maxLeads }) => {
3127
3843
  const { outbound } = context;
3128
- if (campaign !== null) {
3129
- return leadsOf(context, campaign, maxLeads);
3130
- }
3131
- if (!outbound.capabilities["leads.list"]) {
3844
+ if (campaign === null && !outbound.capabilities["leads.list"]) {
3132
3845
  throw new OutboundError(
3133
3846
  "Unsupported",
3134
3847
  `hot_leads needs a campaign here: the ${outbound.provider} adapter cannot list every lead (leads.list)`,
3135
3848
  { provider: outbound.provider }
3136
3849
  );
3137
3850
  }
3138
- return readCapped2(
3851
+ const walk = campaign === null ? outbound.leads.listAll({ max: maxLeads }) : outbound.campaign(campaign).leads.listAll({ max: maxLeads });
3852
+ const leads = await context.all(walk, {
3853
+ input: "max_leads",
3854
+ max: maxLeads,
3855
+ what: campaign === null ? "leads" : "leads of a campaign"
3856
+ });
3857
+ if (campaign !== null && leads.length === 0) {
3858
+ await confirmCampaign(context, campaign);
3859
+ }
3860
+ return { capped: walk.truncated, leads };
3861
+ };
3862
+ var repliedPastCap = async (context, values, read) => {
3863
+ const { outbound } = context;
3864
+ if (!(outbound.capabilities["replies.list"] && outbound.capabilities["leads.get"])) {
3865
+ context.note(
3866
+ "This tool cannot list replies or read one lead, so leads past max_leads that replied were not looked for."
3867
+ );
3868
+ return [];
3869
+ }
3870
+ const since = context.now - values.recency_days * DAY2;
3871
+ const filtered = outbound.capabilities["replies.since"] !== false;
3872
+ const range = filtered ? { since: new Date(since).toISOString() } : {};
3873
+ const replies2 = await context.all(
3874
+ outbound.replies.listAll({ max: RECENT_REPLIES, ...range }),
3875
+ {
3876
+ input: null,
3877
+ max: RECENT_REPLIES,
3878
+ what: "recent replies looked through for leads past max_leads"
3879
+ }
3880
+ );
3881
+ const listed = new Set(read.map((lead) => lead.ref));
3882
+ const refs = replies2.filter(
3883
+ (reply) => reply.isAuto !== true && !NOT_ENGAGED.has(reply.category) && reply.sentAt !== null && Date.parse(reply.sentAt) >= since && (values.campaign === null || reply.campaignRef === values.campaign)
3884
+ ).toSorted(
3885
+ (left, right) => (right.sentAt ?? "").localeCompare(left.sentAt ?? "")
3886
+ ).flatMap(
3887
+ (reply) => reply.leadRef === null || listed.has(reply.leadRef) ? [] : [reply.leadRef]
3888
+ );
3889
+ const found = await readByRef(
3139
3890
  context,
3140
- (cap) => outbound.leads.listAll({ max: cap }),
3141
- maxLeads,
3142
- "leads"
3891
+ [...new Set(refs)].slice(0, values.limit),
3892
+ (ids) => outbound.leads.getMany(ids),
3893
+ ["lead that replied", "leads that replied"],
3894
+ "scores are missing"
3143
3895
  );
3896
+ return [...found.values()];
3144
3897
  };
3898
+ var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1 : 0);
3145
3899
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3146
3900
  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.",
3901
+ 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
3902
  inputSchema: input16,
3149
3903
  key: "hotLeads",
3904
+ cost: (values, price) => price.list("leads.list", values.max_leads) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (price.capabilities["replies.list"] === false || price.capabilities["leads.get"] === false ? 0 : price.upTo(1) * (price.list("replies.list", 100) + price.upTo(values.limit) * price.one("leads.get"))),
3905
+ scales: "max_leads",
3150
3906
  name: "hot_leads",
3151
3907
  needs: [],
3152
- next: "Use person_summary with a lead's email address or LinkedIn profile to read the conversation before calling.",
3908
+ next: "Use person_summary with a lead's ref, email address or LinkedIn profile to read the conversation before calling.",
3153
3909
  run: async (context, values) => {
3154
- const leads = await readLeads2(context, values);
3910
+ const listed = await listLeads(context, values);
3911
+ const extra = listed.capped ? await repliedPastCap(context, values, listed.leads) : [];
3912
+ const leads = [...listed.leads, ...extra];
3155
3913
  noteEngagement(
3156
3914
  context,
3157
3915
  leads,
@@ -3162,11 +3920,22 @@ var hotLeads = defineInsight({
3162
3920
  );
3163
3921
  const scored = open.flatMap((lead) => toHotLead(lead, values, context.now));
3164
3922
  const hot = scored.filter((lead) => lead.score > 0).toSorted(hottestFirst);
3923
+ const negative = open.filter(
3924
+ (lead) => saidNo(lead, values.positive_labels)
3925
+ );
3926
+ const refused = new Set(negative.map((lead) => lead.ref));
3927
+ const after = scored.filter((lead) => lead.score <= 0 && refused.has(lead.lead)).toSorted(hottestFirst);
3165
3928
  const answer = {
3166
- leads: hot.slice(0, values.limit),
3929
+ leads: [...hot, ...after].slice(0, values.limit),
3167
3930
  totals: {
3931
+ autoReplied: open.filter(
3932
+ (lead) => isAutoReplied(lead) && repliesOf(lead) > 0
3933
+ ).length,
3168
3934
  excluded: leads.length - open.length,
3935
+ fromReplies: extra.length,
3169
3936
  hot: hot.length,
3937
+ moreLeadsExist: listed.capped,
3938
+ negative: negative.length,
3170
3939
  leadsRead: leads.length,
3171
3940
  scored: scored.length,
3172
3941
  withoutData: open.length - scored.length
@@ -3177,7 +3946,7 @@ var hotLeads = defineInsight({
3177
3946
  });
3178
3947
 
3179
3948
  // src/insights/people/lead-collisions.ts
3180
- import { z as z20 } from "zod";
3949
+ import { z as z21 } from "zod";
3181
3950
 
3182
3951
  // src/insights/people/find.ts
3183
3952
  var personKey = (identifier) => {
@@ -3195,33 +3964,116 @@ var keysOfLead = (lead) => {
3195
3964
  ...slug === null ? [] : [`linkedin:${slug}`]
3196
3965
  ];
3197
3966
  };
3198
- var filterFor = (key) => key.startsWith("email:") ? { email: key.slice("email:".length) } : {
3199
- linkedinUrl: `https://www.linkedin.com/in/${key.slice("linkedin:".length)}`
3967
+ var filterFor = (key) => key.startsWith("email:") ? { email: key.slice("email:".length) } : {
3968
+ linkedinUrl: `https://www.linkedin.com/in/${key.slice("linkedin:".length)}`
3969
+ };
3970
+ var kindOf = (key) => key.startsWith("email:") ? "email" : "linkedin";
3971
+ var lookupOf = (outbound) => {
3972
+ const masking = maskingOf(outbound);
3973
+ return {
3974
+ hash: masking?.strategy === "hash" ? masking.hash : void 0,
3975
+ masked: (masking?.fields ?? []).flatMap(
3976
+ (field) => field === "email" || field === "linkedin" ? [field] : []
3977
+ )
3978
+ };
3979
+ };
3980
+ var WORDS = {
3981
+ email: "email addresses",
3982
+ linkedin: "LinkedIn profiles"
3983
+ };
3984
+ var maskedWords = (masked) => masked.map((kind) => WORDS[kind]).join(" and ");
3985
+ var refuse = (outbound, masked, why) => new OutboundError(
3986
+ "Unsupported",
3987
+ `A person cannot be looked up while the redact plugin masks ${maskedWords(masked)}: ${why}`,
3988
+ { provider: outbound.provider }
3989
+ );
3990
+ var isLeadRef = (identifier) => personKey(identifier) === null && parseRef(identifier.trim()) !== null;
3991
+ var PROFILE = "https://www.linkedin.com/in/";
3992
+ var formsOf = (key, given) => {
3993
+ const value = key.slice(key.indexOf(":") + 1);
3994
+ return kindOf(key) === "email" ? [value] : [
3995
+ `${PROFILE}${value}`,
3996
+ `${PROFILE}${value}/`,
3997
+ `https://linkedin.com/in/${value}`,
3998
+ given.trim()
3999
+ ];
3200
4000
  };
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) {
4001
+ var startFrom = async (context, identifier, { hash, masked }) => {
4002
+ const { outbound } = context;
4003
+ const key = personKey(identifier);
4004
+ if (key !== null) {
4005
+ if (!masked.includes(kindOf(key))) {
4006
+ return { hashed: null, keys: [key], records: [] };
4007
+ }
4008
+ if (hash === void 0) {
4009
+ throw refuse(
4010
+ outbound,
4011
+ masked,
4012
+ "the records could not be matched to the identifier"
4013
+ );
4014
+ }
4015
+ const tokens = formsOf(key, identifier).map(hash);
4016
+ return {
4017
+ hashed: {
4018
+ shown: `${kindOf(key)}:${tokens[0] ?? ""}`,
4019
+ tokens: new Set(tokens)
4020
+ },
4021
+ keys: [key],
4022
+ records: []
4023
+ };
4024
+ }
4025
+ if (!isLeadRef(identifier)) {
3208
4026
  throw new OutboundError(
3209
4027
  "Invalid",
3210
- "Give an email address or a LinkedIn profile URL",
3211
- { provider: context.outbound.provider }
4028
+ "Give an email address, a LinkedIn profile URL or a lead ref",
4029
+ { provider: outbound.provider }
4030
+ );
4031
+ }
4032
+ 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";
4033
+ if (masked.length === 2) {
4034
+ throw refuse(
4035
+ outbound,
4036
+ masked,
4037
+ instead ?? "a lead ref has no identifier left to look the person up by"
4038
+ );
4039
+ }
4040
+ const lead = context.one(await outbound.leads.get(identifier.trim()));
4041
+ const keys = keysOfLead(lead).filter(
4042
+ (each) => !masked.includes(kindOf(each))
4043
+ );
4044
+ if (keys.length === 0 && masked.length > 0) {
4045
+ const other = ["email", "linkedin"].find(
4046
+ (kind) => !masked.includes(kind)
4047
+ );
4048
+ throw refuse(
4049
+ outbound,
4050
+ masked,
4051
+ instead ?? `the lead has no ${other === "email" ? "email address" : "LinkedIn profile"} to look it up by`
3212
4052
  );
3213
4053
  }
3214
- const masked = maskedIdentifiers(context.outbound);
4054
+ return { hashed: null, keys, records: [lead] };
4055
+ };
4056
+ var carries = (lead, key, start) => {
4057
+ if (start.hashed !== null && start.keys.includes(key)) {
4058
+ const field = kindOf(key) === "email" ? lead.email : lead.linkedinUrl;
4059
+ return field !== null && start.hashed.tokens.has(field);
4060
+ }
4061
+ return keysOfLead(lead).includes(key);
4062
+ };
4063
+ var findPerson = async (context, identifier, maxRecords) => {
4064
+ const lookup = lookupOf(context.outbound);
4065
+ const { masked } = lookup;
4066
+ const start = await startFrom(context, identifier, lookup);
3215
4067
  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 }
4068
+ context.partial(
4069
+ `The redact plugin masks ${maskedWords(masked)}, so records found only under that identifier were not linked.`
3220
4070
  );
3221
4071
  }
3222
- const keys = /* @__PURE__ */ new Set([first]);
4072
+ const keys = new Set(start.keys);
3223
4073
  const asked = /* @__PURE__ */ new Set();
3224
- const records = /* @__PURE__ */ new Map();
4074
+ const records = new Map(
4075
+ start.records.map((lead) => [`${lead.ref} ${lead.campaignRef ?? ""}`, lead])
4076
+ );
3225
4077
  for (let round2 = [...keys].filter((key) => !asked.has(key)); round2.length > 0; round2 = [...keys].filter((key) => !asked.has(key))) {
3226
4078
  for (const key of round2) {
3227
4079
  asked.add(key);
@@ -3230,34 +4082,43 @@ var findPerson = async (context, identifier, maxRecords) => {
3230
4082
  round2,
3231
4083
  (key) => context.all(
3232
4084
  context.outbound.leads.listAll({ ...filterFor(key), max: maxRecords }),
3233
- `${maxRecords} records of the person`
4085
+ {
4086
+ input: "max_campaigns",
4087
+ max: maxRecords,
4088
+ what: "records of the person"
4089
+ }
3234
4090
  )
3235
4091
  );
3236
4092
  for (const [index, leads] of answers.entries()) {
3237
4093
  const asking = round2[index];
3238
4094
  for (const lead of leads) {
3239
4095
  const leadKeys = keysOfLead(lead);
3240
- if (asking !== void 0 && leadKeys.includes(asking)) {
4096
+ if (asking !== void 0 && carries(lead, asking, start)) {
3241
4097
  records.set(`${lead.ref} ${lead.campaignRef ?? ""}`, lead);
3242
4098
  for (const key of leadKeys) {
3243
- keys.add(key);
4099
+ if (!masked.includes(kindOf(key))) {
4100
+ keys.add(key);
4101
+ }
3244
4102
  }
3245
4103
  }
3246
4104
  }
3247
4105
  }
3248
4106
  }
4107
+ const shown = [...keys].map(
4108
+ (key) => start.hashed !== null && start.keys.includes(key) ? start.hashed.shown : key
4109
+ );
3249
4110
  return {
3250
- keys: [...keys].toSorted(),
4111
+ keys: shown.toSorted(),
3251
4112
  records: [...records.values()].slice(0, maxRecords)
3252
4113
  };
3253
4114
  };
3254
4115
 
3255
4116
  // src/insights/people/lead-collisions.ts
3256
- var input17 = z20.object({
3257
- max_campaigns: z20.number().int().min(1).max(200).default(20).describe(
4117
+ var input17 = z21.object({
4118
+ max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
3258
4119
  "The most campaigns to read. Each costs one request per page of its leads."
3259
4120
  ),
3260
- max_leads_per_campaign: z20.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
4121
+ max_leads_per_campaign: z21.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3261
4122
  statuses: statusesField
3262
4123
  });
3263
4124
  var groupPeople = (entries) => {
@@ -3302,7 +4163,7 @@ var toCollision = (group) => {
3302
4163
  campaignCount: campaigns.length,
3303
4164
  campaigns,
3304
4165
  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.`,
4166
+ 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
4167
  identifiers,
3307
4168
  providers,
3308
4169
  scope,
@@ -3315,11 +4176,21 @@ var leadCollisions = defineInsight({
3315
4176
  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
4177
  inputSchema: input17,
3317
4178
  key: "leadCollisions",
4179
+ // A masked address is the same text for every lead, so every lead would
4180
+ // collide with every other. A hashed one still tells people apart.
4181
+ maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches people by" : null,
4182
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("leads.list", values.max_leads_per_campaign),
4183
+ scales: "max_campaigns",
3318
4184
  name: "lead_collisions",
3319
4185
  needs: ["leads.byCampaign"],
3320
- next: "Use person_summary with one of the identifiers to see what that person was sent and whether they replied.",
4186
+ next: "Use person_summary with one of the identifiers or lead refs to see what that person was sent and whether they replied.",
3321
4187
  run: async (context, values) => {
3322
- const campaigns = await campaignsIn2(
4188
+ if (maskingOf(context.outbound)?.fields.includes("linkedin") === true) {
4189
+ context.partial(
4190
+ "The redact plugin masks LinkedIn profiles, so people were matched by email address only."
4191
+ );
4192
+ }
4193
+ const campaigns = await campaignsIn(
3323
4194
  context,
3324
4195
  values.statuses,
3325
4196
  values.max_campaigns
@@ -3328,7 +4199,8 @@ var leadCollisions = defineInsight({
3328
4199
  const leads = await leadsOf(
3329
4200
  context,
3330
4201
  campaign.ref,
3331
- values.max_leads_per_campaign
4202
+ values.max_leads_per_campaign,
4203
+ "max_leads_per_campaign"
3332
4204
  );
3333
4205
  return leads.map((lead) => ({ campaign, lead }));
3334
4206
  });
@@ -3355,10 +4227,12 @@ var leadCollisions = defineInsight({
3355
4227
  });
3356
4228
 
3357
4229
  // 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")
4230
+ import { z as z22 } from "zod";
4231
+ var input18 = z22.object({
4232
+ max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
4233
+ person: z22.string().min(3).describe(
4234
+ "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
4235
+ )
3362
4236
  });
3363
4237
  var times2 = (messages, direction) => messages.flatMap(
3364
4238
  (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
@@ -3373,29 +4247,29 @@ var repliedSteps = (lead, messages) => {
3373
4247
  steps.add(message.stepIndex ?? lastSent ?? 0);
3374
4248
  }
3375
4249
  }
3376
- const named2 = lead.engagement?.repliedStepIndex ?? null;
3377
- if (named2 !== null) {
3378
- steps.add(named2);
4250
+ const named3 = lead.engagement?.repliedStepIndex ?? null;
4251
+ if (named3 !== null) {
4252
+ steps.add(named3);
3379
4253
  }
3380
4254
  return [...steps].toSorted((left, right) => left - right);
3381
4255
  };
3382
4256
  var activityOf = (lead, messages) => {
3383
4257
  const sent = times2(messages, "out");
3384
4258
  const received = times2(messages, "in");
3385
- const counted = lead.engagement;
4259
+ const counted2 = lead.engagement;
3386
4260
  return {
3387
4261
  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(
4262
+ lastContactedAt: sent.at(-1) ?? counted2?.lastContactedAt ?? null,
4263
+ lastRepliedAt: received.at(-1) ?? counted2?.lastRepliedAt ?? null,
4264
+ lastStep: counted2?.stepIndex ?? messages.findLast(
3391
4265
  (message) => message.direction === "out" && message.stepIndex !== null
3392
4266
  )?.stepIndex ?? null,
3393
4267
  // A vendor's thread can hold fewer messages than were sent; the last
3394
4268
  // step sent (counted from 0) is then the better count.
3395
- messagesSent: Math.max(sent.length, (counted?.stepIndex ?? -1) + 1),
4269
+ messagesSent: Math.max(sent.length, (counted2?.stepIndex ?? -1) + 1),
3396
4270
  // 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
4271
+ replies: Math.max(received.length, counted2?.replies ?? 0),
4272
+ threadIsShort: sent.length < (counted2?.stepIndex ?? -1) + 1
3399
4273
  };
3400
4274
  };
3401
4275
  var timelineOf = async (context, timelines, lead) => {
@@ -3415,7 +4289,14 @@ var summarize2 = async (context, timelines, lead) => {
3415
4289
  timelineOf(context, timelines, lead),
3416
4290
  lead.campaignRef === null ? null : outbound.campaigns.get(lead.campaignRef).then(context.one)
3417
4291
  ]);
3418
- const { threadIsShort, ...activity } = activityOf(lead, messages);
4292
+ const { threadIsShort, ...counted2 } = activityOf(lead, messages);
4293
+ const autoReplied = isAutoReplied(lead);
4294
+ const activity = autoReplied ? { ...counted2, lastRepliedAt: null, replies: 0 } : counted2;
4295
+ if (autoReplied && counted2.replies > 0) {
4296
+ context.note(
4297
+ "A record the vendor labels out-of-office or bounced had replies; they were automatic, so they are not counted as replies."
4298
+ );
4299
+ }
3419
4300
  if (threadIsShort) {
3420
4301
  context.note(
3421
4302
  "A thread held fewer sent messages than the lead's last step, so messages sent is counted from the last step."
@@ -3431,8 +4312,9 @@ var summarize2 = async (context, timelines, lead) => {
3431
4312
  lead: lead.ref,
3432
4313
  leadStatus: lead.status,
3433
4314
  provider: lead.provider,
3434
- replied: activity.replies > 0 || lead.replied === true,
3435
- repliedSteps: repliedSteps(lead, messages)
4315
+ autoReplied,
4316
+ replied: !autoReplied && (activity.replies > 0 || lead.replied === true),
4317
+ repliedSteps: autoReplied ? [] : repliedSteps(lead, messages)
3436
4318
  };
3437
4319
  };
3438
4320
  var byChannel2 = (campaigns) => {
@@ -3450,11 +4332,18 @@ var byChannel2 = (campaigns) => {
3450
4332
  return channels;
3451
4333
  };
3452
4334
  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.",
4335
+ 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
4336
  inputSchema: input18,
3455
4337
  key: "personSummary",
4338
+ cost: (values, price) => (isLeadRef(values.person) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
4339
+ scales: "max_campaigns",
3456
4340
  name: "person_summary",
4341
+ maskedOut: (masking) => {
4342
+ const masked = new Set(masking.fields);
4343
+ return masked.has("email") && masked.has("linkedin") && masking.strategy === "mask" ? "email addresses and LinkedIn profiles, which it looks a person up by" : null;
4344
+ },
3457
4345
  needs: ["leads.lookup", "leads.timeline"],
4346
+ needsFor: ({ person }) => isLeadRef(person) ? ["leads.get"] : [],
3458
4347
  next: "Use account_summary with their email domain to see everyone at the same company.",
3459
4348
  run: async (context, { max_campaigns: maxCampaigns, person }) => {
3460
4349
  const found = await findPerson(context, person, maxCampaigns);
@@ -3489,11 +4378,11 @@ var personSummary = defineInsight({
3489
4378
  });
3490
4379
 
3491
4380
  // 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(
4381
+ import { z as z23 } from "zod";
4382
+ var input19 = z23.object({
4383
+ campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
4384
+ limit: z23.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
4385
+ max_leads: z23.number().int().min(1).max(2e4).default(500).describe(
3497
4386
  "The most leads to check. A vendor request returns about 50 to 100 leads."
3498
4387
  )
3499
4388
  });
@@ -3593,6 +4482,8 @@ var personalizationGaps = defineInsight({
3593
4482
  description: "Leads in one campaign who will get broken copy because a merge variable has no value for them. Reads the campaign's sequence, finds every {{variable}}, {variable} and %variable% in subjects and bodies, and checks each lead for a value: first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens. Returns the variables with the steps that use them, how many leads each one affects, and the leads missing at least one. A variable with a fallback such as {{firstName|there}} is not a gap. A variable no lead has, such as a sender signature the tool fills in, is listed as unknown, not counted against leads. Costs one request for the sequence plus one per page of leads.",
3594
4483
  inputSchema: input19,
3595
4484
  key: "personalizationGaps",
4485
+ cost: (values, price) => price.one("sequence.get") + price.upTo(1) * price.list("leads.list", values.max_leads),
4486
+ scales: "max_leads",
3596
4487
  name: "personalization_gaps",
3597
4488
  needs: ["sequence", "leads.byCampaign"],
3598
4489
  next: "Fix the leads' fields or add a fallback in the tool, then use lead_collisions to check the same leads are not in another campaign.",
@@ -3601,7 +4492,12 @@ var personalizationGaps = defineInsight({
3601
4492
  await context.outbound.campaign(values.campaign).sequence()
3602
4493
  );
3603
4494
  const found = findVariables(sequence2);
3604
- const leads = found.size === 0 ? [] : await leadsOf(context, values.campaign, values.max_leads);
4495
+ const leads = found.size === 0 ? [] : await leadsOf(
4496
+ context,
4497
+ values.campaign,
4498
+ values.max_leads,
4499
+ "max_leads"
4500
+ );
3605
4501
  if (found.size === 0) {
3606
4502
  context.note("The sequence uses no variables, so no lead was read.");
3607
4503
  }
@@ -3619,7 +4515,7 @@ var personalizationGaps = defineInsight({
3619
4515
  (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
3620
4516
  );
3621
4517
  const answer = {
3622
- campaign: values.campaign,
4518
+ campaign: refOf(context.outbound, values.campaign),
3623
4519
  leads: affected.slice(0, values.limit),
3624
4520
  totals: {
3625
4521
  affectedRate: rate(affected.length, leads.length),
@@ -3638,15 +4534,15 @@ var personalizationGaps = defineInsight({
3638
4534
  });
3639
4535
 
3640
4536
  // 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(
4537
+ import { z as z24 } from "zod";
4538
+ var input20 = z24.object({
4539
+ max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
3644
4540
  "The most block list entries to read. A vendor request returns about 50 to 100."
3645
4541
  ),
3646
- max_campaigns: z23.number().int().min(1).max(200).default(20).describe(
4542
+ max_campaigns: z24.number().int().min(1).max(200).default(20).describe(
3647
4543
  "The most campaigns to check. Each costs one request per page of its leads."
3648
4544
  ),
3649
- max_leads_per_campaign: z23.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
4545
+ max_leads_per_campaign: z24.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3650
4546
  statuses: statusesField
3651
4547
  });
3652
4548
  var slugOfEntry = (value) => profileSlug(value) ?? value.trim().replaceAll(/^\/+|\/+$/gu, "").toLowerCase();
@@ -3698,23 +4594,48 @@ var toViolation = (lead, campaign, { entry, matchedBy }) => ({
3698
4594
  matchedBy,
3699
4595
  sameTool: entry.provider === lead.provider && entry.workspaceId === lead.workspaceId
3700
4596
  });
4597
+ var maskNote = (outbound) => {
4598
+ const fields = maskingOf(outbound)?.fields ?? [];
4599
+ const email = fields.includes("email");
4600
+ const linkedin = fields.includes("linkedin");
4601
+ const masked = [
4602
+ ...email ? ["email addresses"] : [],
4603
+ ...linkedin ? ["LinkedIn profiles"] : []
4604
+ ];
4605
+ const lost = [
4606
+ ...email ? ["domain entries"] : [],
4607
+ ...linkedin ? ["LinkedIn profile entries"] : []
4608
+ ];
4609
+ return masked.length === 0 ? null : `The redact plugin masks ${masked.join(" and ")}, so ${lost.join(" and ")} could not be matched to leads.`;
4610
+ };
3701
4611
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
3702
4612
  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.",
4613
+ 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
4614
  inputSchema: input20,
3705
4615
  key: "suppressionCheck",
4616
+ // A masked address is the same text for every lead, so nothing can match.
4617
+ // A hashed one still matches the same address on the list.
4618
+ maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches leads to the block list by" : null,
4619
+ cost: (values, price) => price.list("blocklist.list", values.max_block_entries) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("leads.list", values.max_leads_per_campaign),
4620
+ scales: "max_campaigns",
3706
4621
  name: "suppression_check",
3707
4622
  needs: ["blocklist", "leads.byCampaign"],
3708
- next: "Use person_summary with a violating lead's email address to see what they were already sent.",
4623
+ next: "Use person_summary with a violating lead's ref or email address to see what they were already sent.",
3709
4624
  run: async (context, values) => {
3710
- const entries = await readCapped2(
4625
+ const listed = await readCappedFlag(
3711
4626
  context,
3712
4627
  (cap) => context.outbound.blocklist.listAll({ max: cap }),
3713
4628
  values.max_block_entries,
3714
- "block list entries"
4629
+ "block list entries",
4630
+ "max_block_entries"
3715
4631
  );
4632
+ const entries = listed.items;
3716
4633
  const blocked = indexEntries(entries);
3717
- const campaigns = await campaignsIn2(
4634
+ const unmatched = maskNote(context.outbound);
4635
+ if (unmatched !== null) {
4636
+ context.partial(unmatched);
4637
+ }
4638
+ const campaigns = await campaignsIn(
3718
4639
  context,
3719
4640
  values.statuses,
3720
4641
  values.max_campaigns
@@ -3723,13 +4644,15 @@ var suppressionCheck = defineInsight({
3723
4644
  const byCampaign = [];
3724
4645
  const read = await mapConcurrent(campaigns, async (campaign) => ({
3725
4646
  campaign,
3726
- leads: await leadsOf(
4647
+ ...await readCappedFlag(
3727
4648
  context,
3728
- campaign.ref,
3729
- values.max_leads_per_campaign
4649
+ (cap) => context.outbound.campaign(campaign.ref).leads.listAll({ max: cap }),
4650
+ values.max_leads_per_campaign,
4651
+ "leads of a campaign",
4652
+ "max_leads_per_campaign"
3730
4653
  )
3731
4654
  }));
3732
- for (const { campaign, leads } of read) {
4655
+ for (const { campaign, items: leads } of read) {
3733
4656
  const found = leads.flatMap((lead) => {
3734
4657
  const hit = matchLead(lead, blocked);
3735
4658
  return hit === null ? [] : [toViolation(lead, campaign, hit)];
@@ -3748,7 +4671,7 @@ var suppressionCheck = defineInsight({
3748
4671
  (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
3749
4672
  ),
3750
4673
  totals: {
3751
- blockEntriesNotChecked: blocked.notChecked,
4674
+ blockEntriesNotChecked: listed.capped ? null : blocked.notChecked,
3752
4675
  blockEntriesRead: entries.length,
3753
4676
  byMatch: {
3754
4677
  domain: matches.get("domain") ?? 0,
@@ -3757,6 +4680,8 @@ var suppressionCheck = defineInsight({
3757
4680
  },
3758
4681
  campaignsRead: campaigns.length,
3759
4682
  leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
4683
+ moreBlockEntriesExist: listed.capped,
4684
+ moreLeadsExist: read.some((each) => each.capped),
3760
4685
  violations: violations.length
3761
4686
  },
3762
4687
  violations: violations.toSorted(activeFirst)
@@ -3780,51 +4705,39 @@ var PEOPLE_INSIGHTS = [
3780
4705
  import { z as z25 } from "zod";
3781
4706
 
3782
4707
  // 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;
4708
+ var readCapped2 = async (context, walk, max, what, input27) => {
4709
+ const { items } = await readCapped(context, walk, { input: input27, max, what });
4710
+ return items;
4711
+ };
4712
+ var readCampaigns = async (context, statuses, max) => {
4713
+ const { items } = await readCampaignsIn(context, statuses, max);
4714
+ return items;
3821
4715
  };
3822
- var readCampaignSenders = (context, campaign, max) => readCapped3(
4716
+ var readCampaignSenders = (context, campaign, max, input27) => readCapped2(
3823
4717
  context,
3824
4718
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
3825
4719
  max,
3826
- `senders of campaign ${campaign.name}`
4720
+ `senders of campaign ${campaign.name}`,
4721
+ input27
3827
4722
  );
4723
+ var readSenders = (context, max) => readCapped(context, (cap) => context.outbound.senders.listAll({ max: cap }), {
4724
+ input: "max_senders",
4725
+ max,
4726
+ what: "senders"
4727
+ });
4728
+ var readHealth = async (context, sender) => {
4729
+ try {
4730
+ return context.one(await context.outbound.sender(sender.ref).health());
4731
+ } catch (error) {
4732
+ if (!OutboundError.is(error) || error.code !== "NotFound") {
4733
+ throw error;
4734
+ }
4735
+ context.partial(
4736
+ `Left out ${sender.address ?? sender.ref}: the vendor no longer finds this sender.`
4737
+ );
4738
+ return null;
4739
+ }
4740
+ };
3828
4741
  var domainOf2 = (address) => {
3829
4742
  const domain = address?.split("@")[1]?.trim().toLowerCase() ?? "";
3830
4743
  return domain === "" ? null : domain;
@@ -3841,23 +4754,31 @@ var warmupSpam = (health) => {
3841
4754
  return sent === null ? null : { sent, spam: warmup.spam };
3842
4755
  };
3843
4756
  var dayFrom = (now, offsetDays) => new Date(now + offsetDays * 864e5).toISOString().slice(0, 10);
4757
+ var countEach = (keys, count2) => (
4758
+ // SAFETY: the entries cover every key of the record.
4759
+ Object.fromEntries(keys.toSorted().map((key) => [key, count2(key)]))
4760
+ );
3844
4761
 
3845
4762
  // src/insights/senders/bounce-watch.ts
4763
+ var maxBounceRate = z25.number().min(0).max(1);
3846
4764
  var input21 = z25.object({
3847
- from: dayInput2("First day to count"),
4765
+ ...rangeFields,
3848
4766
  include_senders: z25.boolean().default(true).describe(
3849
4767
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
3850
4768
  ),
4769
+ max_bounce_rate: maxBounceRate.default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
3851
4770
  max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
3852
4771
  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")
4772
+ min_sent: z25.number().int().min(0).default(100).describe(
4773
+ "A campaign or sender with fewer sends than this is too small to judge"
4774
+ ),
4775
+ threshold: renamed("max_bounce_rate", maxBounceRate),
4776
+ statuses: statusesInput(["active"])
3856
4777
  });
3857
4778
  var countsOf2 = (bounced, sent) => ({
4779
+ ...measure2(bounced, sent),
3858
4780
  bounced,
3859
4781
  interval: wilson(bounced, sent),
3860
- rate: rate(bounced, sent),
3861
4782
  sent
3862
4783
  });
3863
4784
  var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
@@ -3880,13 +4801,23 @@ var senderReader = (context, range) => {
3880
4801
  };
3881
4802
  };
3882
4803
  var sendersOver = async (context, campaign, options) => {
3883
- const senders2 = await readCampaignSenders(context, campaign, options.max);
4804
+ const senders2 = await readCampaignSenders(
4805
+ context,
4806
+ campaign,
4807
+ options.max,
4808
+ "max_senders_per_campaign"
4809
+ );
3884
4810
  const read = await mapConcurrent(senders2, async (sender) => ({
3885
4811
  counts: await options.read(sender.ref),
3886
4812
  sender
3887
4813
  }));
4814
+ for (const { counts, sender } of read) {
4815
+ options.seen[counts === null ? "unread" : "read"].add(
4816
+ sender.address ?? sender.name ?? sender.ref
4817
+ );
4818
+ }
3888
4819
  const over = read.flatMap(
3889
- ({ counts, sender }) => counts !== null && isOver(counts, options.threshold) ? [
4820
+ ({ counts, sender }) => counts !== null && counts.sent >= options.minSent && isOver(counts, options.threshold) ? [
3890
4821
  {
3891
4822
  ...counts,
3892
4823
  address: sender.address,
@@ -3914,25 +4845,31 @@ var bounceWatch = defineInsight({
3914
4845
  description: "Where bounces are too high: the campaigns whose bounce rate (bounced divided by sent) is over a threshold, worst first, each with bounced, sent, the rate and its Wilson interval, and the senders of each such campaign that are themselves over the threshold. Campaigns with too few sends to judge and campaigns with no reported bounce count are listed apart, never as clean. Use it daily, or when a domain's reputation is in doubt. Costs one listing of campaigns and 1 request per campaign, plus 1 listing and up to 1 request per sender for each campaign over the threshold. A null rate means nothing was sent.",
3915
4846
  inputSchema: input21,
3916
4847
  key: "bounceWatch",
4848
+ cost: (values, price) => {
4849
+ const campaigns = price.campaigns(values.max_campaigns);
4850
+ const bySender = values.include_senders && price.capabilities["stats.bySender"] !== false && price.capabilities["senders.byCampaign"] !== false;
4851
+ return price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + campaigns * price.one("stats") + (bySender ? price.upTo(campaigns) * (price.list("senders.list", values.max_senders_per_campaign) + values.max_senders_per_campaign * price.one("stats")) : 0);
4852
+ },
4853
+ scales: "max_campaigns",
3917
4854
  name: "bounce_watch",
3918
4855
  needs: ["stats.campaign"],
3919
4856
  next: "Use domain_health on the senders named here, and settings_audit on the campaigns over the threshold.",
3920
4857
  run: async (context, options) => {
3921
4858
  const { outbound } = context;
3922
- const { min_sent: minSent, threshold } = options;
3923
- const range = { from: options.from, to: options.to };
3924
- const campaigns = await readCapped3(
4859
+ const { max_bounce_rate: threshold, min_sent: minSent } = options;
4860
+ const range = rangeOf(options.from, options.to);
4861
+ const campaigns = await readCampaigns(
3925
4862
  context,
3926
- (cap) => outbound.campaigns.listAll({ max: cap }),
3927
- options.max_campaigns,
3928
- "campaigns"
4863
+ options.statuses,
4864
+ options.max_campaigns
3929
4865
  );
3930
4866
  const withSenders = campaigns.length > 0 && canCheckSenders(context, options.include_senders);
3931
4867
  const read = senderReader(context, range);
4868
+ const seen = { read: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() };
3932
4869
  const overBy = [];
3933
4870
  const tooFewSends = [];
3934
4871
  const unknown = [];
3935
- const counted = [];
4872
+ const counted2 = [];
3936
4873
  const rows = await mapConcurrent(campaigns, async (campaign) => ({
3937
4874
  campaign,
3938
4875
  row: context.rows(await outbound.campaign(campaign.ref).stats(range))[0]
@@ -3941,13 +4878,14 @@ var bounceWatch = defineInsight({
3941
4878
  const counts = known(row);
3942
4879
  const entry = {
3943
4880
  campaign: campaign.ref,
4881
+ campaignName: campaign.name,
3944
4882
  name: campaign.name,
3945
4883
  status: campaign.status
3946
4884
  };
3947
4885
  if (counts === null) {
3948
4886
  unknown.push({ ...entry, reason: whyUnknown(row) });
3949
4887
  } else if (counts.sent < minSent || counts.sent === 0) {
3950
- counted.push(counts);
4888
+ counted2.push(counts);
3951
4889
  tooFewSends.push({
3952
4890
  ...entry,
3953
4891
  ...counts,
@@ -3955,14 +4893,14 @@ var bounceWatch = defineInsight({
3955
4893
  senders: null
3956
4894
  });
3957
4895
  } else {
3958
- counted.push(counts);
4896
+ counted2.push(counts);
3959
4897
  if (isOver(counts, threshold)) {
3960
4898
  overBy.push({
3961
4899
  campaign,
3962
4900
  entry: {
3963
4901
  ...entry,
3964
4902
  ...counts,
3965
- finding: `${counts.bounced} of ${counts.sent} sends bounced (${counts.rate}), over the ${threshold} threshold.`,
4903
+ finding: `${counts.bounced} of ${counts.sent} sends bounced (${percent(counts.rate)}), over the ${percent(threshold)} threshold.`,
3966
4904
  senders: null
3967
4905
  }
3968
4906
  });
@@ -3975,23 +4913,32 @@ var bounceWatch = defineInsight({
3975
4913
  ...entry,
3976
4914
  senders: await sendersOver(context, campaign, {
3977
4915
  max: options.max_senders_per_campaign,
4916
+ minSent,
3978
4917
  read,
4918
+ seen,
3979
4919
  threshold
3980
4920
  })
3981
4921
  } : entry
3982
4922
  );
3983
- const bounced = total(counted.map((each) => each.bounced));
3984
- const sent = total(counted.map((each) => each.sent));
4923
+ if (seen.unread.size > 0) {
4924
+ context.note(
4925
+ `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(", ")}.`
4926
+ );
4927
+ }
4928
+ const bounced = total(counted2.map((each) => each.bounced));
4929
+ const sent = total(counted2.map((each) => each.sent));
3985
4930
  const byRate2 = (left, right) => (right.rate ?? -1) - (left.rate ?? -1);
3986
4931
  const answer = {
4932
+ maxBounceRate: threshold,
3987
4933
  minSent,
3988
4934
  over: over.toSorted(byRate2),
4935
+ sendersRead: withSenders ? seen.read.size : null,
3989
4936
  threshold,
3990
4937
  tooFewSends: tooFewSends.toSorted(byRate2),
3991
4938
  totals: {
3992
4939
  bounced,
3993
4940
  campaigns: campaigns.length,
3994
- clean: counted.length - over.length - tooFewSends.length,
4941
+ clean: counted2.length - over.length - tooFewSends.length,
3995
4942
  over: over.length,
3996
4943
  rate: rate(bounced, sent),
3997
4944
  sent,
@@ -4006,11 +4953,13 @@ var bounceWatch = defineInsight({
4006
4953
 
4007
4954
  // src/insights/senders/domain-health.ts
4008
4955
  import { z as z26 } from "zod";
4956
+ var maxSpamRate = z26.number().min(0).max(1);
4009
4957
  var input22 = z26.object({
4010
4958
  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(
4959
+ max_spam_rate: maxSpamRate.default(0.1).describe(
4012
4960
  "A domain whose warmup emails land in spam more often than this share is high risk"
4013
- )
4961
+ ),
4962
+ spam_rate_threshold: renamed("max_spam_rate", maxSpamRate)
4014
4963
  });
4015
4964
  var RISK_ORDER = ["high", "medium", "low", "unknown"];
4016
4965
  var pooledWarmup = (checked) => {
@@ -4020,6 +4969,7 @@ var pooledWarmup = (checked) => {
4020
4969
  });
4021
4970
  if (reported.length === 0) {
4022
4971
  return {
4972
+ ...measure2(null, null),
4023
4973
  interval: null,
4024
4974
  mailboxes: 0,
4025
4975
  sent: null,
@@ -4029,12 +4979,14 @@ var pooledWarmup = (checked) => {
4029
4979
  }
4030
4980
  const sent = reported.reduce((sum, each) => sum + each.sent, 0);
4031
4981
  const spam = reported.reduce((sum, each) => sum + each.spam, 0);
4982
+ const measured2 = measure2(spam, sent);
4032
4983
  return {
4984
+ ...measured2,
4033
4985
  interval: wilson(spam, sent),
4034
4986
  mailboxes: reported.length,
4035
4987
  sent,
4036
4988
  spam,
4037
- spamRate: rate(spam, sent)
4989
+ spamRate: measured2.rate
4038
4990
  };
4039
4991
  };
4040
4992
  var missingChecks = (checked, warmup) => [
@@ -4045,33 +4997,36 @@ var missingChecks = (checked, warmup) => [
4045
4997
  ...checked.every(({ health }) => health.blacklisted === null) ? ["blocklist"] : [],
4046
4998
  ...warmup.mailboxes === 0 ? ["warmup"] : []
4047
4999
  ];
4048
- var CHECKS3 = DNS_RECORDS.length + 3;
4049
5000
  var reportFor = (domain, checked, threshold) => {
4050
5001
  const failing = DNS_RECORDS.filter(
4051
5002
  (record) => checked.some(({ health }) => health.dns[record] === false)
4052
5003
  );
4053
- const blacklisted = checked.filter(
4054
- ({ health }) => health.blacklisted === true
4055
- ).length;
5004
+ const warmup = pooledWarmup(checked);
5005
+ const notReported = missingChecks(checked, warmup);
5006
+ const blacklisted = notReported.includes("blocklist") ? null : checked.filter(({ health }) => health.blacklisted === true).length;
4056
5007
  const disconnected = checked.filter(
4057
5008
  ({ health }) => health.connected === false
4058
5009
  ).length;
4059
- const warmup = pooledWarmup(checked);
4060
5010
  const authFailing = failing.filter((record) => record !== "dmarc");
4061
- const spamHigh = warmup.spamRate !== null && warmup.spamRate > threshold;
5011
+ const spamHigh = warmup.rate !== null && warmup.rate > threshold;
4062
5012
  const high = [
4063
- ...blacklisted > 0 ? [`${blacklisted} of ${checked.length} mailboxes are on a block list`] : [],
5013
+ ...(blacklisted ?? 0) > 0 ? [
5014
+ `${blacklisted} of ${plural(checked.length, "mailbox", "mailboxes")} ${noun(blacklisted ?? 0, "is", "are")} on a block list`
5015
+ ] : [],
4064
5016
  ...authFailing.length > 0 ? [`${authFailing.join(", ").toUpperCase()} failing`] : [],
4065
5017
  ...spamHigh ? [
4066
- `${warmup.spam} of ${warmup.sent} warmup emails landed in spam (${warmup.spamRate}, over ${threshold})`
5018
+ `${warmup.spam} of ${warmup.sent} warmup emails landed in spam (${percent(warmup.rate)}, over ${percent(threshold)})`
4067
5019
  ] : []
4068
5020
  ];
4069
5021
  const medium = [
4070
5022
  ...failing.includes("dmarc") ? ["DMARC failing"] : [],
4071
- ...disconnected > 0 ? [`${disconnected} of ${checked.length} mailboxes are disconnected`] : []
5023
+ ...disconnected > 0 ? [
5024
+ `${disconnected} of ${plural(checked.length, "mailbox", "mailboxes")} ${noun(disconnected, "is", "are")} disconnected`
5025
+ ] : []
4072
5026
  ];
4073
- const notReported = missingChecks(checked, warmup);
4074
- const calm = notReported.length === CHECKS3 ? "unknown" : "low";
5027
+ const calm = DNS_RECORDS.every(
5028
+ (record) => notReported.includes(record)
5029
+ ) ? "unknown" : "low";
4075
5030
  const lesser = medium.length > 0 ? "medium" : calm;
4076
5031
  return {
4077
5032
  blacklisted,
@@ -4093,7 +5048,7 @@ var reportFor = (domain, checked, threshold) => {
4093
5048
  warmup
4094
5049
  };
4095
5050
  };
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);
5051
+ 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
5052
  var seatRank = (seat) => {
4098
5053
  if (seat.connected === false) {
4099
5054
  return 0;
@@ -4101,27 +5056,26 @@ var seatRank = (seat) => {
4101
5056
  return seat.connected === null ? 1 : 2;
4102
5057
  };
4103
5058
  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`.",
5059
+ 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
5060
  inputSchema: input22,
4106
5061
  key: "domainHealth",
5062
+ cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
5063
+ scales: "max_senders",
4107
5064
  name: "domain_health",
4108
5065
  needs: ["senders.list", "senders.health"],
4109
5066
  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
- );
5067
+ run: async (context, { max_senders: maxSenders, max_spam_rate: threshold }) => {
5068
+ const { items: senders2 } = await readSenders(context, maxSenders);
4118
5069
  const byDomain = /* @__PURE__ */ new Map();
4119
5070
  const linkedinSeats = [];
4120
5071
  const mailboxesWithoutDomain = [];
4121
- const checks = await mapConcurrent(senders2, async (sender) => ({
4122
- health: context.one(await outbound.sender(sender.ref).health()),
5072
+ const read = await mapConcurrent(senders2, async (sender) => ({
5073
+ health: await readHealth(context, sender),
4123
5074
  sender
4124
5075
  }));
5076
+ const checks = read.flatMap(
5077
+ ({ health, sender }) => health === null ? [] : [{ health, sender }]
5078
+ );
4125
5079
  for (const { health, sender } of checks) {
4126
5080
  const domain = health.domain ?? domainOf2(sender.address);
4127
5081
  if (sender.kind === "linkedin") {
@@ -4143,7 +5097,7 @@ var domainHealth = defineInsight({
4143
5097
  }
4144
5098
  }
4145
5099
  const domains = [...byDomain].map(([domain, checked]) => reportFor(domain, checked, threshold)).toSorted(worstFirst2);
4146
- const count = (risk) => domains.filter((domain) => domain.risk === risk).length;
5100
+ const count2 = (risk) => domains.filter((domain) => domain.risk === risk).length;
4147
5101
  const answer = {
4148
5102
  domains,
4149
5103
  linkedinSeats: linkedinSeats.toSorted(
@@ -4152,12 +5106,12 @@ var domainHealth = defineInsight({
4152
5106
  mailboxesWithoutDomain,
4153
5107
  totals: {
4154
5108
  domains: domains.length,
4155
- high: count("high"),
5109
+ high: count2("high"),
4156
5110
  linkedinSeats: linkedinSeats.length,
4157
- low: count("low"),
4158
- medium: count("medium"),
4159
- senders: senders2.length,
4160
- unknown: count("unknown")
5111
+ low: count2("low"),
5112
+ medium: count2("medium"),
5113
+ senders: checks.length,
5114
+ unknown: count2("unknown")
4161
5115
  }
4162
5116
  };
4163
5117
  return answer;
@@ -4166,40 +5120,8 @@ var domainHealth = defineInsight({
4166
5120
 
4167
5121
  // src/insights/senders/sender-capacity.ts
4168
5122
  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
- };
5123
+
5124
+ // src/insights/senders/capacity-sends.ts
4203
5125
  var dailyRows = async (context, campaigns, range) => {
4204
5126
  const { outbound } = context;
4205
5127
  const { capabilities } = outbound;
@@ -4233,7 +5155,37 @@ var dailyRows = async (context, campaigns, range) => {
4233
5155
  );
4234
5156
  return { rows, scope: "campaigns" };
4235
5157
  };
4236
- var readSends = async (context, campaigns, days) => {
5158
+ 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.";
5159
+ var uncountedSends = async (context, senders2, window) => {
5160
+ const others = senders2.items.filter(
5161
+ (sender) => sender.status !== "active" || sender.dailyLimit === null
5162
+ );
5163
+ if (!senders2.capped && others.length === 0) {
5164
+ return 0;
5165
+ }
5166
+ const untold = senders2.capped || window.scope !== "workspace" || context.outbound.capabilities["stats.bySender"] === false;
5167
+ if (!untold && !window.split) {
5168
+ context.note(
5169
+ `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).`
5170
+ );
5171
+ return null;
5172
+ }
5173
+ const each = untold ? [null] : await mapConcurrent(
5174
+ others,
5175
+ async (sender) => total(
5176
+ context.rows(
5177
+ await context.outbound.sender(sender.ref).stats({ from: window.from, to: window.to })
5178
+ ).map((row) => row.sent)
5179
+ )
5180
+ );
5181
+ const sent = total(each) ?? 0;
5182
+ if (each.includes(null) || sent > window.sent) {
5183
+ context.note(UNTOLD);
5184
+ return null;
5185
+ }
5186
+ return sent;
5187
+ };
5188
+ var readSends = async (context, campaigns, days, senders2, split) => {
4237
5189
  const range = {
4238
5190
  from: dayFrom(context.now, -days),
4239
5191
  to: dayFrom(context.now, -1)
@@ -4242,8 +5194,17 @@ var readSends = async (context, campaigns, days) => {
4242
5194
  if (read === null) {
4243
5195
  return null;
4244
5196
  }
4245
- const sent = total(read.rows.map((row) => row.sent));
4246
- const reported = read.rows.flatMap(
5197
+ const rows = read.rows.filter(
5198
+ (row) => row.date === null || row.date >= range.from && row.date <= range.to
5199
+ );
5200
+ const sent = total(rows.map((row) => row.sent));
5201
+ const fromUncounted = sent === null ? null : await uncountedSends(context, senders2, {
5202
+ ...range,
5203
+ scope: read.scope,
5204
+ sent,
5205
+ split
5206
+ });
5207
+ const reported = rows.flatMap(
4247
5208
  (row) => row.date === null || row.sent === null ? [] : [row.date]
4248
5209
  );
4249
5210
  return {
@@ -4251,10 +5212,55 @@ var readSends = async (context, campaigns, days) => {
4251
5212
  averageDaily: sent === null ? null : round(sent / days),
4252
5213
  days,
4253
5214
  daysWithData: new Set(reported).size,
5215
+ fromUncounted,
4254
5216
  scope: read.scope,
4255
5217
  total: sent
4256
5218
  };
4257
5219
  };
5220
+
5221
+ // src/insights/senders/sender-capacity.ts
5222
+ var input23 = z27.object({
5223
+ days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
5224
+ max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
5225
+ "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
5226
+ ),
5227
+ max_senders: z27.number().int().min(1).max(1e3).default(200).describe(
5228
+ "The most senders to read for the workspace, and for each campaign"
5229
+ ),
5230
+ split_uncounted: z27.boolean().default(false).describe(
5231
+ "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."
5232
+ )
5233
+ });
5234
+ var limitsOf = (senders2) => senders2.map((sender) => sender.dailyLimit);
5235
+ var capacityOf = (senders2) => {
5236
+ const active = senders2.filter((sender) => sender.status === "active");
5237
+ const withLimit = active.filter((sender) => sender.dailyLimit !== null);
5238
+ const ofKind = (kind) => total(limitsOf(active.filter((sender) => sender.kind === kind)));
5239
+ return {
5240
+ activeSenders: active.length,
5241
+ daily: total(limitsOf(active)),
5242
+ inactiveSenders: senders2.length - active.length,
5243
+ linkedinDaily: ofKind("linkedin"),
5244
+ mailboxDaily: ofKind("mailbox"),
5245
+ withLimit: withLimit.length,
5246
+ withoutLimit: active.length - withLimit.length
5247
+ };
5248
+ };
5249
+ var readOne = async (context, campaign, maxSenders) => {
5250
+ const { capabilities } = context.outbound;
5251
+ const settings = capabilities["campaigns.settings"] ? context.one(await context.outbound.campaign(campaign.ref).settings()) : null;
5252
+ return {
5253
+ campaign,
5254
+ dailyLimit: settings?.dailyLimit ?? null,
5255
+ // The senders are only compared with the campaign's own limit.
5256
+ senders: settings !== null && capabilities["senders.byCampaign"] ? await readCampaignSenders(
5257
+ context,
5258
+ campaign,
5259
+ maxSenders,
5260
+ "max_senders"
5261
+ ) : null
5262
+ };
5263
+ };
4258
5264
  var shortfallOf = (read) => {
4259
5265
  const active = (read.senders ?? []).filter(
4260
5266
  (sender) => sender.status === "active"
@@ -4279,7 +5285,7 @@ var shortfallOf = (read) => {
4279
5285
  };
4280
5286
  var askOf = (reads) => {
4281
5287
  const limits = reads.map((read) => read.dailyLimit);
4282
- const withLimit = limits.filter((limit2) => limit2 !== null).length;
5288
+ const withLimit = limits.filter((limit3) => limit3 !== null).length;
4283
5289
  return {
4284
5290
  campaigns: reads.length,
4285
5291
  daily: total(limits),
@@ -4302,28 +5308,36 @@ var findingOf = (capacity, ask, sends) => {
4302
5308
  }
4303
5309
  if (sends !== null && sends.averageDaily !== null) {
4304
5310
  parts.push(
4305
- `${sends.averageDaily} a day were sent on average over the last ${sends.days} days.`
5311
+ `${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
5312
  );
4307
5313
  }
4308
5314
  return parts.join(" ");
4309
5315
  };
4310
5316
  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.",
5317
+ 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
5318
  inputSchema: input23,
4313
5319
  key: "senderCapacity",
5320
+ cost: (values, price) => {
5321
+ const { capabilities } = price;
5322
+ const campaigns = price.campaigns(values.max_campaigns);
5323
+ const sends = capabilities["stats.workspace"] === false ? campaigns * price.one("stats") : price.one("stats") + (values.split_uncounted && capabilities["stats.bySender"] !== false ? price.upTo(values.max_senders) * price.one("stats") : 0);
5324
+ return price.list("senders.list", values.max_senders) + price.campaignsIn(1, values.max_campaigns) + (capabilities["campaigns.settings"] === false ? 0 : campaigns * (price.one("campaigns.settings") + (capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders)))) + (capabilities["stats.byDay"] === false ? 0 : sends);
5325
+ },
5326
+ scales: "max_campaigns",
4314
5327
  name: "sender_capacity",
4315
5328
  needs: ["senders.list"],
4316
5329
  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 }) => {
5330
+ run: async (context, {
5331
+ days,
5332
+ max_campaigns: maxCampaigns,
5333
+ max_senders: maxSenders,
5334
+ split_uncounted: split
5335
+ }) => {
4318
5336
  const { outbound } = context;
4319
5337
  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);
5338
+ const listed = await readSenders(context, maxSenders);
5339
+ const senders2 = listed.items;
5340
+ const campaigns = await readCampaigns(context, ["active"], maxCampaigns);
4327
5341
  const reads = await mapConcurrent(
4328
5342
  campaigns,
4329
5343
  (campaign) => readOne(context, campaign, maxSenders)
@@ -4341,7 +5355,7 @@ var senderCapacity = defineInsight({
4341
5355
  }
4342
5356
  const capacity = capacityOf(senders2);
4343
5357
  const ask = hasSettings ? askOf(reads) : null;
4344
- const sends = await readSends(context, campaigns, days);
5358
+ const sends = await readSends(context, campaigns, days, listed, split);
4345
5359
  const shortfalls = reads.map(shortfallOf);
4346
5360
  const answer = {
4347
5361
  ask,
@@ -4353,7 +5367,10 @@ var senderCapacity = defineInsight({
4353
5367
  (each) => each === null || each === "unchecked" ? [] : [each]
4354
5368
  ).toSorted((left, right) => right.shortBy - left.shortBy) : null,
4355
5369
  uncheckedCampaigns: canCompare ? shortfalls.filter((each) => each === "unchecked").length : null,
4356
- utilization: rate(sends?.averageDaily ?? null, capacity.daily)
5370
+ utilization: rate(
5371
+ sends?.total === null || sends?.total === void 0 || sends.fromUncounted === null ? null : (sends.total - sends.fromUncounted) / sends.days,
5372
+ capacity.daily
5373
+ )
4357
5374
  };
4358
5375
  return answer;
4359
5376
  }
@@ -4367,7 +5384,7 @@ var input24 = z28.object({
4367
5384
  max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
4368
5385
  "The most senders to read for the workspace, and for each campaign"
4369
5386
  ),
4370
- statuses: statusesInput
5387
+ statuses: statusesInput(["active"])
4371
5388
  });
4372
5389
  var loaded = (sender) => ({
4373
5390
  address: sender.address,
@@ -4386,10 +5403,11 @@ var riskOf = (campaign, senders2) => {
4386
5403
  if (issues.length === 0) {
4387
5404
  return null;
4388
5405
  }
4389
- const count = senders2.length === 1 ? "1 sender" : `${senders2.length} senders`;
5406
+ const count2 = senders2.length === 1 ? "1 sender" : `${senders2.length} senders`;
4390
5407
  return {
4391
5408
  campaign: campaign.ref,
4392
- finding: inactive.length > 0 ? `${campaign.name} has ${count}, ${inactive.length} of them not active.` : `${campaign.name} has ${count}.`,
5409
+ campaignName: campaign.name,
5410
+ finding: inactive.length > 0 ? `${campaign.name} has ${count2}, ${inactive.length} of them not active.` : `${campaign.name} has ${count2}.`,
4393
5411
  inactive: inactive.map(loaded),
4394
5412
  issues,
4395
5413
  name: campaign.name,
@@ -4400,19 +5418,15 @@ var senderLoad = defineInsight({
4400
5418
  description: "Senders that are overused or unused: the senders attached to more campaigns than allowed, the active senders attached to no campaign, and the campaigns that run on a single sender, on none, or on a sender that is not active. Use it when sends are uneven or before adding a campaign. Costs one listing of senders and of campaigns, then 1 request per campaign. Only campaigns in the given statuses are counted, so a sender used only by a paused campaign shows as unused unless paused is included.",
4401
5419
  inputSchema: input24,
4402
5420
  key: "senderLoad",
5421
+ cost: (values, price) => price.list("senders.list", values.max_senders) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("senders.list", values.max_senders),
5422
+ scales: "max_campaigns",
4403
5423
  name: "sender_load",
4404
5424
  needs: ["senders.list", "senders.byCampaign"],
4405
5425
  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
5426
  run: async (context, options) => {
4407
- const { outbound } = context;
4408
5427
  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(
5428
+ const { items: senders2 } = await readSenders(context, options.max_senders);
5429
+ const campaigns = await readCampaigns(
4416
5430
  context,
4417
5431
  options.statuses,
4418
5432
  options.max_campaigns
@@ -4422,7 +5436,12 @@ var senderLoad = defineInsight({
4422
5436
  const risks = [];
4423
5437
  const read = await mapConcurrent(campaigns, async (campaign) => ({
4424
5438
  campaign,
4425
- own: await readCampaignSenders(context, campaign, options.max_senders)
5439
+ own: await readCampaignSenders(
5440
+ context,
5441
+ campaign,
5442
+ options.max_senders,
5443
+ "max_senders"
5444
+ )
4426
5445
  }));
4427
5446
  for (const { campaign, own } of read) {
4428
5447
  const risk = riskOf(campaign, own);
@@ -4478,13 +5497,13 @@ var input25 = z29.object({
4478
5497
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
4479
5498
  ),
4480
5499
  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"
5500
+ "The sends a day assumed for an attached sender when the senders' own daily limits are not reported"
4482
5501
  ),
4483
5502
  max_senders_per_campaign: z29.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
4484
5503
  max_window_hours: z29.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
4485
5504
  min_gap_minutes: z29.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
4486
5505
  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
5506
+ statuses: statusesInput(["active"])
4488
5507
  });
4489
5508
  var SEVERITY2 = {
4490
5509
  click_tracking: "medium",
@@ -4500,7 +5519,7 @@ var SEVERITY2 = {
4500
5519
  window_long: "medium",
4501
5520
  window_short: "low"
4502
5521
  };
4503
- var ORDER2 = ["high", "medium", "low"];
5522
+ var ORDER3 = ["high", "medium", "low"];
4504
5523
  var when = (hit, check, finding, value = null) => hit ? [{ check, finding, severity: SEVERITY2[check], value }] : [];
4505
5524
  var minutesOf2 = (clock) => Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3));
4506
5525
  var hoursOf = (window) => {
@@ -4535,13 +5554,13 @@ var scheduleFindings = ({ bars, settings }) => {
4535
5554
  ...when(
4536
5555
  longest > bars.maxWindowHours,
4537
5556
  "window_long",
4538
- `A sending window is ${longest} hours long, over ${bars.maxWindowHours}.`,
5557
+ `A sending window is ${spoken(longest)} hours long, over ${bars.maxWindowHours}.`,
4539
5558
  longest
4540
5559
  ),
4541
5560
  ...when(
4542
5561
  shortest < bars.minWindowHours,
4543
5562
  "window_short",
4544
- `A sending window is ${shortest} hours long, under ${bars.minWindowHours}.`,
5563
+ `A sending window is ${spoken(shortest)} hours long, under ${bars.minWindowHours}.`,
4545
5564
  shortest
4546
5565
  ),
4547
5566
  ...when(
@@ -4554,7 +5573,9 @@ var scheduleFindings = ({ bars, settings }) => {
4554
5573
  var limitFindings = (audit2) => {
4555
5574
  const { bars, campaign, senders: senders2, settings, today } = audit2;
4556
5575
  const { dailyLimit, endDate, gapMinutes } = settings;
4557
- const allowed = (senders2 ?? 0) * bars.maxPerSender;
5576
+ const count2 = senders2?.length ?? 0;
5577
+ const own = senders2?.every((sender) => sender.dailyLimit !== null) === true ? senders2.reduce((sum, sender) => sum + (sender.dailyLimit ?? 0), 0) : null;
5578
+ const allowed = own ?? count2 * bars.maxPerSender;
4558
5579
  return [
4559
5580
  ...when(
4560
5581
  dailyLimit === null,
@@ -4564,7 +5585,7 @@ var limitFindings = (audit2) => {
4564
5585
  ...when(
4565
5586
  dailyLimit !== null && allowed > 0 && dailyLimit > allowed,
4566
5587
  "limit_over_senders",
4567
- `The daily limit of ${dailyLimit} is over ${bars.maxPerSender} a day for each of its ${senders2} senders (${allowed}).`,
5588
+ 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
5589
  dailyLimit
4569
5590
  ),
4570
5591
  ...when(
@@ -4605,36 +5626,26 @@ var audit = (subject) => ({
4605
5626
  ...limitFindings(subject),
4606
5627
  ...ruleFindings(subject)
4607
5628
  ].toSorted(
4608
- (left, right) => ORDER2.indexOf(left.severity) - ORDER2.indexOf(right.severity)
5629
+ (left, right) => ORDER3.indexOf(left.severity) - ORDER3.indexOf(right.severity)
4609
5630
  ),
4610
5631
  name: subject.campaign.name,
4611
5632
  status: subject.campaign.status
4612
5633
  });
4613
5634
  var countOf2 = (campaign, severity) => campaign.findings.filter((finding) => finding.severity === severity).length;
4614
5635
  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(
5636
+ var countChecks = (campaigns) => countEach(
5637
+ // SAFETY: SEVERITY has exactly one key per check.
5638
+ Object.keys(SEVERITY2),
5639
+ (check) => campaigns.filter(
4617
5640
  (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
- };
5641
+ ).length
5642
+ );
4634
5643
  var settingsAudit = defineInsight({
4635
5644
  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
5645
  inputSchema: input25,
4637
5646
  key: "settingsAudit",
5647
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("campaigns.settings") + (price.capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders_per_campaign))),
5648
+ scales: "max_campaigns",
4638
5649
  name: "settings_audit",
4639
5650
  needs: ["campaigns.settings"],
4640
5651
  next: "Use sender_capacity to size a daily limit against the senders, or bounce_watch to see whether a flagged campaign already bounces.",
@@ -4647,7 +5658,7 @@ var settingsAudit = defineInsight({
4647
5658
  minGapMinutes: options.min_gap_minutes,
4648
5659
  minWindowHours: options.min_window_hours
4649
5660
  };
4650
- const campaigns = await readCampaigns2(
5661
+ const campaigns = await readCampaigns(
4651
5662
  context,
4652
5663
  options.statuses,
4653
5664
  options.max_campaigns
@@ -4665,13 +5676,14 @@ var settingsAudit = defineInsight({
4665
5676
  countSenders ? readCampaignSenders(
4666
5677
  context,
4667
5678
  campaign,
4668
- options.max_senders_per_campaign
5679
+ options.max_senders_per_campaign,
5680
+ "max_senders_per_campaign"
4669
5681
  ) : null
4670
5682
  ]);
4671
5683
  return audit({
4672
5684
  bars,
4673
5685
  campaign,
4674
- senders: senders2?.length ?? null,
5686
+ senders: senders2,
4675
5687
  settings: context.one(settings),
4676
5688
  today: dayFrom(context.now, 0)
4677
5689
  });
@@ -4707,6 +5719,15 @@ var input26 = z30.object({
4707
5719
  ),
4708
5720
  min_score: z30.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
4709
5721
  });
5722
+ var READINESS_REASONS = [
5723
+ "not_active",
5724
+ "warmup_off",
5725
+ "score_low",
5726
+ "score_unknown",
5727
+ "no_daily_limit",
5728
+ "dns_failing",
5729
+ "warmup_spam_high"
5730
+ ];
4710
5731
  var healthReasons = (health, bars) => {
4711
5732
  const failing = failingDns(health);
4712
5733
  const spam = warmupSpam(health);
@@ -4721,7 +5742,7 @@ var healthReasons = (health, bars) => {
4721
5742
  ...spam !== null && spamRate !== null && spamRate > bars.maxSpamRate ? [
4722
5743
  [
4723
5744
  "warmup_spam_high",
4724
- `${spam.spam} of ${spam.sent} warmup emails landed in spam (${spamRate}, over ${bars.maxSpamRate})`
5745
+ `${spam.spam} of ${spam.sent} warmup emails landed in spam (${percent(spamRate)}, over ${percent(bars.maxSpamRate)})`
4725
5746
  ]
4726
5747
  ] : []
4727
5748
  ];
@@ -4731,7 +5752,7 @@ var mailboxReasons = (sender, score, bars) => [
4731
5752
  ...score !== null && score < bars.minScore ? [
4732
5753
  [
4733
5754
  "score_low",
4734
- `Warmup score ${score} is under ${bars.minScore}`
5755
+ `Warmup score ${spoken(score)} is under ${spoken(bars.minScore)}`
4735
5756
  ]
4736
5757
  ] : [],
4737
5758
  ...score === null ? [["score_unknown", "The vendor reports no warmup score"]] : [],
@@ -4757,22 +5778,16 @@ var judge2 = (sender, health, bars) => {
4757
5778
  warmupEnabled: sender.warmup?.enabled ?? null
4758
5779
  };
4759
5780
  };
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
- };
5781
+ var countReasons = (judged) => countEach(
5782
+ READINESS_REASONS,
5783
+ (reason) => judged.filter((sender) => sender.reasons.includes(reason)).length
5784
+ );
4772
5785
  var warmupReadiness = defineInsight({
4773
5786
  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
5787
  inputSchema: input26,
4775
5788
  key: "warmupReadiness",
5789
+ cost: (values, price) => price.list("senders.list", values.max_senders) + (values.check_health && price.capabilities["senders.health"] !== false ? price.upTo(values.max_senders) * price.one("senders.health") : 0),
5790
+ scales: "max_senders",
4776
5791
  name: "warmup_readiness",
4777
5792
  needs: ["senders.list"],
4778
5793
  next: "Use domain_health for the domains of the mailboxes that are not ready, or sender_capacity to see what the ready ones can send.",
@@ -4782,25 +5797,26 @@ var warmupReadiness = defineInsight({
4782
5797
  maxSpamRate: options.max_spam_rate,
4783
5798
  minScore: options.min_score
4784
5799
  };
4785
- const senders2 = await readCapped3(
4786
- context,
4787
- (cap) => outbound.senders.listAll({ max: cap }),
4788
- options.max_senders,
4789
- "senders"
4790
- );
5800
+ const { items: senders2 } = await readSenders(context, options.max_senders);
4791
5801
  const healthChecked = options.check_health && outbound.capabilities["senders.health"];
4792
5802
  if (options.check_health && !healthChecked) {
4793
5803
  context.note(
4794
5804
  "DNS records and warmup spam were not checked: the adapter cannot read a sender's health."
4795
5805
  );
4796
5806
  }
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);
5807
+ if (!options.check_health && outbound.capabilities["senders.health"] && senders2.some((sender) => sender.kind === "mailbox")) {
5808
+ context.note(
5809
+ "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."
5810
+ );
5811
+ }
5812
+ const each = await mapConcurrent(senders2, async (sender) => {
5813
+ if (!healthChecked || sender.kind !== "mailbox") {
5814
+ return [judge2(sender, null, bars)];
4802
5815
  }
4803
- );
5816
+ const health = await readHealth(context, sender);
5817
+ return health === null ? [] : [judge2(sender, health, bars)];
5818
+ });
5819
+ const judged = each.flat();
4804
5820
  const notReady = judged.filter((sender) => sender.reasons.length > 0).toSorted((left, right) => right.reasons.length - left.reasons.length);
4805
5821
  const answer = {
4806
5822
  byReason: countReasons(notReady),
@@ -4834,7 +5850,7 @@ var INSIGHTS = [
4834
5850
  var ENTRIES = INSIGHTS;
4835
5851
 
4836
5852
  // src/insights/plugin.ts
4837
- var runInsightByName = async (outbound, name, input27 = {}, options = {}) => {
5853
+ var entryNamed = (outbound, name) => {
4838
5854
  const entry = ENTRIES.find(
4839
5855
  (candidate) => candidate.name === name || candidate.key === name
4840
5856
  );
@@ -4845,7 +5861,21 @@ var runInsightByName = async (outbound, name, input27 = {}, options = {}) => {
4845
5861
  { provider: outbound.provider }
4846
5862
  );
4847
5863
  }
4848
- return await entry.execute(outbound, input27, options);
5864
+ return entry;
5865
+ };
5866
+ var runInsightByName = async (outbound, name, input27 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input27, options);
5867
+ var insightCost = (outbound, name, input27 = {}) => {
5868
+ const entry = entryNamed(outbound, name);
5869
+ const parsed = entry.inputSchema.safeParse(input27);
5870
+ if (!parsed.success) {
5871
+ throw new OutboundError(
5872
+ "Invalid",
5873
+ `${entry.name}: ${parsed.error.issues[0]?.message ?? "the input is not valid"}`,
5874
+ { provider: outbound.provider }
5875
+ );
5876
+ }
5877
+ const bounds = boundsOf(outbound, entry.cost, parsed.data);
5878
+ return bounds === null ? null : { ...bounds, defaultCap: defaultCap(bounds) };
4849
5879
  };
4850
5880
  var listInsights = () => ENTRIES.map((entry) => ({
4851
5881
  description: entry.description,
@@ -4871,10 +5901,34 @@ var insights = () => ({
4871
5901
 
4872
5902
  // src/insights/tools.ts
4873
5903
  import { z as z32 } from "zod";
4874
- var toTool = (outbound, definition) => ({
4875
- call: async (input27) => {
5904
+ var INSIGHT_TOOL_CEILING = 500;
5905
+ var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
5906
+ var hintFor = (next, offered) => {
5907
+ const hidden = ENTRIES.flatMap(
5908
+ (entry) => offered.has(entry.name) ? [] : [entry.name]
5909
+ );
5910
+ const kept = next.split(/(?<=\.)\s+/u).filter((sentence) => !hidden.some((name) => sentence.includes(name)));
5911
+ return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
5912
+ };
5913
+ var toTool = (outbound, definition, next, perCall) => ({
5914
+ call: async (given, callOptions) => {
5915
+ const set = callOptions?.maxRequests ?? perCall;
4876
5916
  try {
4877
- const result = await definition.execute(outbound, input27);
5917
+ const input27 = jsonInput(given);
5918
+ if (input27 === void 0) {
5919
+ throw new OutboundError(
5920
+ "Invalid",
5921
+ `${definition.name}: the input is not JSON`
5922
+ );
5923
+ }
5924
+ const result = await definition.execute(
5925
+ outbound,
5926
+ input27,
5927
+ set === void 0 ? {
5928
+ capCeiling: INSIGHT_TOOL_CEILING,
5929
+ capSetting: "maxRequestsPerToolCall"
5930
+ } : { capSetting: "maxRequestsPerToolCall", maxRequests: set }
5931
+ );
4878
5932
  return {
4879
5933
  data: {
4880
5934
  complete: result.meta.complete,
@@ -4886,19 +5940,23 @@ var toTool = (outbound, definition) => ({
4886
5940
  provider: result.meta.provider,
4887
5941
  requests: result.meta.requests
4888
5942
  },
4889
- next: definition.next,
5943
+ next,
4890
5944
  ok: true
4891
5945
  };
4892
5946
  } catch (error) {
4893
- const known2 = OutboundError.is(error);
4894
- return {
4895
- error: {
4896
- code: known2 ? error.code : "Provider",
4897
- message: error instanceof Error ? error.message : String(error)
4898
- },
4899
- next: known2 && error.code === "Unsupported" ? "This insight is not available with the current adapter. Try another tool." : "Check the input and try again.",
4900
- ok: false
4901
- };
5947
+ const stop = capStopOf(error);
5948
+ if (stop !== void 0) {
5949
+ return failure(
5950
+ error,
5951
+ stop.requests,
5952
+ capNext(stop.cap, stop.isDefault, stop.lower)
5953
+ );
5954
+ }
5955
+ return failure(
5956
+ error,
5957
+ void 0,
5958
+ OutboundError.is(error) && error.code === "Unsupported" ? "This insight cannot answer here; the message says why. Try another tool." : void 0
5959
+ );
4902
5960
  }
4903
5961
  },
4904
5962
  description: definition.description,
@@ -4910,16 +5968,26 @@ var toTool = (outbound, definition) => ({
4910
5968
  });
4911
5969
  var insightTools = (outbound, options = {}) => {
4912
5970
  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
- });
5971
+ const offered = ENTRIES.filter(
5972
+ (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
5973
+ );
5974
+ const names = new Set(offered.map((definition) => definition.name));
5975
+ return offered.map(
5976
+ (definition) => toTool(
5977
+ outbound,
5978
+ definition,
5979
+ hintFor(definition.next, names),
5980
+ options.maxRequestsPerToolCall
5981
+ )
5982
+ );
4917
5983
  };
4918
5984
  export {
4919
5985
  INSIGHTS,
5986
+ INSIGHT_TOOL_CEILING,
4920
5987
  compareRates,
4921
5988
  defineInsight,
4922
5989
  deviation,
5990
+ insightCost,
4923
5991
  insightTools,
4924
5992
  insights,
4925
5993
  listInsights,