outbound-sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) 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 +635 -2
  8. package/dist/budget/index.d.ts +2 -0
  9. package/dist/budget/index.js +1 -0
  10. package/dist/cards/format.d.ts +1 -1
  11. package/dist/cards/index.js +49 -19
  12. package/dist/cards/parts.d.ts +1 -6
  13. package/dist/chunks/{chunk-7LNJJ2RO.js → chunk-3JOC5DGD.js} +127 -17
  14. package/dist/chunks/chunk-53DCVFUB.js +55 -0
  15. package/dist/chunks/{chunk-E6DSDCPI.js → chunk-BK5SLY32.js} +92 -101
  16. package/dist/chunks/chunk-HPNGSG5E.js +51 -0
  17. package/dist/chunks/chunk-HWHI4LFY.js +102 -0
  18. package/dist/chunks/chunk-MGR6HREO.js +91 -0
  19. package/dist/chunks/{chunk-Y5RAJ6PZ.js → chunk-OLPMBRXM.js} +3 -2
  20. package/dist/chunks/{chunk-IZFTTMJP.js → chunk-PHNQ3WC2.js} +5 -5
  21. package/dist/chunks/chunk-SXGCKCAR.js +678 -0
  22. package/dist/chunks/chunk-TFICTGM2.js +18 -0
  23. package/dist/chunks/{chunk-ZFVHM5JI.js → chunk-UWUPUMM2.js} +11 -4
  24. package/dist/chunks/{chunk-A6WVOCA4.js → chunk-W22SDX6S.js} +4 -4
  25. package/dist/chunks/{chunk-7ZDS6SZD.js → chunk-WH6V3YNN.js} +25 -0
  26. package/dist/chunks/chunk-XL6LJVHJ.js +71 -0
  27. package/dist/chunks/{chunk-5FVKRIEJ.js → chunk-YYCT3NGV.js} +35 -11
  28. package/dist/cli/bin.js +13 -28
  29. package/dist/cli/index.d.ts +3 -0
  30. package/dist/cli/index.js +12 -11
  31. package/dist/cli/output.d.ts +9 -0
  32. package/dist/cli/update.d.ts +15 -0
  33. package/dist/emailbison/account.d.ts +7 -0
  34. package/dist/emailbison/adapter.d.ts +5 -0
  35. package/dist/emailbison/capabilities.d.ts +78 -0
  36. package/dist/emailbison/client.d.ts +29 -0
  37. package/dist/emailbison/index.d.ts +30 -0
  38. package/dist/emailbison/index.js +1018 -0
  39. package/dist/emailbison/mail.d.ts +5 -0
  40. package/dist/emailbison/map-mail.d.ts +13 -0
  41. package/dist/emailbison/map-sequence.d.ts +12 -0
  42. package/dist/emailbison/map-stats.d.ts +47 -0
  43. package/dist/emailbison/map.d.ts +24 -0
  44. package/dist/emailbison/native-params.d.ts +5 -0
  45. package/dist/emailbison/native-workspace.d.ts +167 -0
  46. package/dist/emailbison/native.d.ts +327 -0
  47. package/dist/emailbison/stats.d.ts +4 -0
  48. package/dist/emailbison/webhooks.d.ts +2 -0
  49. package/dist/fixtures/index.js +6 -6
  50. package/dist/heyreach/capabilities.d.ts +3 -0
  51. package/dist/heyreach/index.js +22 -20
  52. package/dist/index.js +19 -18
  53. package/dist/insights/copy/copy-preview.d.ts +58 -0
  54. package/dist/insights/copy/copy-reuse.d.ts +0 -13
  55. package/dist/insights/copy/index.d.ts +9 -0
  56. package/dist/insights/copy/reuse-base.d.ts +0 -2
  57. package/dist/insights/copy/shared.d.ts +3 -8
  58. package/dist/insights/copy/step-funnel.d.ts +1 -12
  59. package/dist/insights/copy/variant-test.d.ts +0 -5
  60. package/dist/insights/cost.d.ts +91 -0
  61. package/dist/insights/define.d.ts +22 -1
  62. package/dist/insights/index.d.ts +4 -3
  63. package/dist/insights/index.js +810 -415
  64. package/dist/insights/inputs.generated.d.ts +21 -24
  65. package/dist/insights/ops/campaign-diagnosis.d.ts +0 -2
  66. package/dist/insights/ops/campaign-ranking.d.ts +3 -3
  67. package/dist/insights/ops/client-report.d.ts +0 -2
  68. package/dist/insights/ops/index.d.ts +2 -6
  69. package/dist/insights/ops/shared.d.ts +10 -2
  70. package/dist/insights/plugin.d.ts +19 -0
  71. package/dist/insights/registry.d.ts +10 -10
  72. package/dist/insights/run-cap.d.ts +35 -0
  73. package/dist/insights/senders/bounce-watch.d.ts +0 -11
  74. package/dist/insights/senders/domain-health.d.ts +0 -7
  75. package/dist/insights/senders/index.d.ts +0 -4
  76. package/dist/insights/senders/sender-load.d.ts +0 -2
  77. package/dist/insights/tools.d.ts +10 -0
  78. package/dist/insights/types.d.ts +1 -1
  79. package/dist/insights/variables.d.ts +33 -0
  80. package/dist/instantly/capabilities.d.ts +13 -0
  81. package/dist/instantly/index.js +43 -28
  82. package/dist/internal/adapter.d.ts +12 -0
  83. package/dist/internal/outbound/outbound.d.ts +5 -1
  84. package/dist/internal/request-cap.d.ts +35 -0
  85. package/dist/loader/index.js +2 -2
  86. package/dist/memory/index.js +10 -10
  87. package/dist/providers/index.d.ts +21 -1
  88. package/dist/providers/index.js +1 -1
  89. package/dist/redact/index.js +4 -4
  90. package/dist/smartlead/capabilities.d.ts +5 -0
  91. package/dist/smartlead/index.js +26 -24
  92. package/dist/tools/ai-sdk.js +5 -3
  93. package/dist/tools/claude-agent.js +5 -3
  94. package/dist/tools/index.d.ts +2 -2
  95. package/dist/tools/index.js +11 -6
  96. package/dist/tools/registry.d.ts +20 -1
  97. package/dist/tools/shared.d.ts +20 -1
  98. package/dist/webhooks/index.js +17 -7
  99. package/package.json +8 -2
  100. package/dist/chunks/chunk-5CFO3CXG.js +0 -176
  101. package/dist/chunks/chunk-K4USHN4C.js +0 -40
  102. package/dist/chunks/chunk-LVQUSKEX.js +0 -17
  103. package/dist/internal/renamed.d.ts +0 -28
  104. package/dist/chunks/{chunk-C4LS2HNV.js → chunk-JWGSB7PT.js} +3 -3
@@ -1,6 +1,8 @@
1
1
  import {
2
+ capNext,
3
+ failure,
2
4
  inputProblem
3
- } from "../chunks/chunk-LVQUSKEX.js";
5
+ } from "../chunks/chunk-HWHI4LFY.js";
4
6
  import {
5
7
  count,
6
8
  percentOf,
@@ -9,16 +11,22 @@ import {
9
11
  import {
10
12
  mapConcurrent
11
13
  } from "../chunks/chunk-HZCTYL22.js";
14
+ import {
15
+ cappedAccess,
16
+ requestCounter,
17
+ withGuard
18
+ } from "../chunks/chunk-HPNGSG5E.js";
12
19
  import {
13
20
  noun,
14
21
  shownKey
15
22
  } from "../chunks/chunk-PTZO4QXR.js";
23
+ import {
24
+ htmlToText,
25
+ looksLikeHtml
26
+ } from "../chunks/chunk-53DCVFUB.js";
16
27
  import {
17
28
  sumCounts
18
29
  } from "../chunks/chunk-PQSTQKRD.js";
19
- import {
20
- profileSlug
21
- } from "../chunks/chunk-NAWZ73QS.js";
22
30
  import {
23
31
  campaignStatusSchema,
24
32
  replyCategorySchema
@@ -27,11 +35,13 @@ import {
27
35
  makeRef,
28
36
  parseRef
29
37
  } from "../chunks/chunk-QAKJ76HB.js";
38
+ import {
39
+ profileSlug
40
+ } from "../chunks/chunk-NAWZ73QS.js";
30
41
  import {
31
42
  OutboundError
32
43
  } from "../chunks/chunk-J7DDZ4C2.js";
33
44
  import {
34
- isJsonObject,
35
45
  jsonInput,
36
46
  toJson,
37
47
  unknownKey
@@ -40,49 +50,193 @@ import {
40
50
  // src/insights/plugin.ts
41
51
  import { z as z31 } from "zod";
42
52
 
43
- // src/insights/copy/copy-audit.ts
44
- import { z as z2 } from "zod";
45
-
46
- // src/internal/renamed.ts
47
- import { z } from "zod";
48
- var REMOVED_IN = "0.5.0";
49
- var renames = z.registry();
50
- var renamed = (to, base) => {
51
- const field = base.optional().meta({
52
- deprecated: true,
53
- description: `Deprecated: renamed to \`${to}\`. Removed in ${REMOVED_IN}.`
54
- });
55
- renames.add(field, { to });
56
- return field;
53
+ // src/insights/cost.ts
54
+ var UNKNOWN = /* @__PURE__ */ Symbol("unknown cost");
55
+ var pages = (cost, records) => cost.pageSize === void 0 ? 1 : Math.max(1, Math.ceil(records / cost.pageSize));
56
+ var pricer = (outbound, costs, most, found) => {
57
+ const of = (action) => {
58
+ const cost = costs[action];
59
+ if (cost === void 0) {
60
+ throw UNKNOWN;
61
+ }
62
+ return cost;
63
+ };
64
+ const list = (action, max) => {
65
+ const cost = of(action);
66
+ return most ? pages(cost, max) * (cost.perPageAtMost ?? cost.perPage) + max * (cost.perRecord ?? 0) + (cost.perWalk ?? 0) : cost.perPage;
67
+ };
68
+ const { capabilities } = outbound;
69
+ return {
70
+ campaigns: (max) => {
71
+ if (found !== void 0) {
72
+ return Math.min(found, max);
73
+ }
74
+ return most ? max : 0;
75
+ },
76
+ campaignsIn: (statuses, max) => {
77
+ const cost = of("campaigns.list");
78
+ const filtered = capabilities["campaigns.status"] !== false;
79
+ if (most) {
80
+ return filtered ? (statuses - 1) * list("campaigns.list", 1) + list("campaigns.list", max) : list("campaigns.list", max);
81
+ }
82
+ const read = found === void 0 ? 1 : pages(cost, Math.min(found, max));
83
+ return (filtered ? Math.max(statuses, read) : read) * cost.perPage;
84
+ },
85
+ capabilities,
86
+ list,
87
+ lookup: (max) => list(
88
+ costs["leads.lookup"] === void 0 ? "leads.list" : "leads.lookup",
89
+ max
90
+ ),
91
+ one: (action) => {
92
+ const cost = of(action);
93
+ return most ? cost.perPage + (cost.perWalk ?? 0) : cost.perPage;
94
+ },
95
+ upTo: (max) => most ? max : 0,
96
+ walk: (action) => {
97
+ const cost = of(action);
98
+ return list(action, cost.pageSize ?? 1);
99
+ }
100
+ };
57
101
  };
58
- var renamesIn = (fields) => Object.entries(fields).flatMap(([from, schema]) => {
59
- const link = renames.get(schema);
60
- return link === void 0 ? [] : [{ from, to: link.to }];
61
- });
62
- var liveKeys = (fields) => {
63
- const old = new Set(renamesIn(fields).map((each) => each.from));
64
- return Object.keys(fields).filter((key) => !old.has(key));
102
+ var boundsOf = (outbound, cost, input28, found) => {
103
+ const costs = cappedAccess(outbound)?.costs;
104
+ if (cost === void 0 || costs === void 0) {
105
+ return null;
106
+ }
107
+ try {
108
+ return {
109
+ max: cost(input28, pricer(outbound, costs, true, found)),
110
+ min: cost(input28, pricer(outbound, costs, false, found))
111
+ };
112
+ } catch (error) {
113
+ if (error === UNKNOWN) {
114
+ return null;
115
+ }
116
+ throw error;
117
+ }
118
+ };
119
+ var defaultCap = (bounds) => bounds === null ? Infinity : Math.ceil(bounds.max * 1.25) + 4;
120
+ var stops = /* @__PURE__ */ new WeakMap();
121
+ var capStopOf = (cause) => OutboundError.is(cause) ? stops.get(cause) : void 0;
122
+ 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})`;
123
+ var advice = (stop) => {
124
+ const raise = stop.isDefault ? `pass ${stop.setting} to raise it (Infinity removes the default)` : `raise ${stop.setting}`;
125
+ const text = stop.lower === void 0 ? raise : `lower ${stop.lower.input} to ${stop.lower.to}${stop.lower.sure ? "" : " or less"}, or ${raise}`;
126
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`;
127
+ };
128
+ var capError = (message, stop, provider) => {
129
+ const error = new OutboundError("RateLimited", `${message} ${advice(stop)}`, {
130
+ limit: "call",
131
+ provider
132
+ });
133
+ stops.set(error, stop);
134
+ return error;
135
+ };
136
+ var refusal = (name, bounds, room, stop, provider) => {
137
+ const range = bounds.max > bounds.min ? ` (at most ${bounds.max})` : "";
138
+ const cap = stop.isDefault ? `its default cap for this input is ${plural(stop.cap, "request")}` : `its cap is ${plural(stop.cap, "request")} (${stop.setting})`;
139
+ const why = room < stop.cap ? `only ${plural(room, "request")} ${room === 1 ? "is" : "are"} left of budget()'s run` : cap;
140
+ return capError(
141
+ `${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")}` : ""}.`,
142
+ stop,
143
+ provider
144
+ );
65
145
  };
66
- var applyRenames = (fields, input27) => {
67
- if (!isJsonObject(input27)) {
68
- return { input: input27, notes: [] };
146
+ var stopped = (name, stop, provider) => capError(
147
+ `${name} stopped after ${plural(stop.requests, "request")}, at ${capWords(stop)}, before it finished; nothing it read is returned.`,
148
+ stop,
149
+ provider
150
+ );
151
+ var fitting = (outbound, cost, input28, name, room, found) => {
152
+ const fields = input28;
153
+ const current = fields[name];
154
+ if (typeof current !== "number" || current <= 1) {
155
+ return void 0;
69
156
  }
70
- const moved = new Map(Object.entries(input27));
71
- const notes = [];
72
- for (const { from, to } of renamesIn(fields)) {
73
- const value = moved.get(from);
74
- moved.delete(from);
75
- if (value !== void 0) {
76
- if (moved.get(to) !== void 0) {
77
- return { conflict: { from, to } };
157
+ const fits = (value, bound) => {
158
+ const lowered = { ...fields, [name]: value };
159
+ const bounds = boundsOf(outbound, cost, lowered, found);
160
+ return bounds !== null && bounds[bound] <= room;
161
+ };
162
+ const largest = (bound) => {
163
+ let low = 0;
164
+ let high = current - 1;
165
+ while (low < high) {
166
+ const middle = Math.ceil((low + high) / 2);
167
+ if (fits(middle, bound)) {
168
+ low = middle;
169
+ } else {
170
+ high = middle - 1;
78
171
  }
79
- moved.set(to, value);
80
- notes.push(
81
- `\`${from}\` is deprecated and will be removed in ${REMOVED_IN}; use \`${to}\`.`
82
- );
83
172
  }
173
+ return low >= 1 && fits(low, bound) ? low : 0;
174
+ };
175
+ const sure = largest("max");
176
+ if (sure > 0) {
177
+ return { input: name, sure: true, to: sure };
84
178
  }
85
- return { input: Object.fromEntries(moved), notes };
179
+ const maybe = largest("min");
180
+ return maybe > 0 ? { input: name, sure: false, to: maybe } : void 0;
181
+ };
182
+
183
+ // src/insights/copy/copy-audit.ts
184
+ import { z } from "zod";
185
+
186
+ // src/insights/run-cap.ts
187
+ var capFor = (outbound, name, max, options) => {
188
+ const set = options.maxRequests;
189
+ if (set !== void 0 && set !== Infinity && (!Number.isInteger(set) || set < 1)) {
190
+ throw new OutboundError(
191
+ "Invalid",
192
+ `${name}: maxRequests must be a positive integer, or Infinity for no default cap`,
193
+ { provider: outbound.provider }
194
+ );
195
+ }
196
+ const setting = options.capSetting ?? "maxRequests";
197
+ return set === void 0 ? {
198
+ cap: Math.min(max, options.capCeiling ?? Infinity),
199
+ isDefault: true,
200
+ setting
201
+ } : { cap: set, isDefault: false, setting };
202
+ };
203
+ var hasRunBudget = (outbound) => "requestBudget" in outbound;
204
+ var runBudgetLeft = (outbound) => hasRunBudget(outbound) && outbound.requestBudget.per === "run" ? outbound.requestBudget.remaining() : Infinity;
205
+ var runCap = (outbound, spec, input28, options) => {
206
+ const bounds = boundsOf(outbound, spec.cost, input28);
207
+ const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
208
+ const stop = (room, found) => ({
209
+ ...effect,
210
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input28, spec.scales, room, found),
211
+ requests: counter.used()
212
+ });
213
+ const counter = requestCounter(
214
+ effect.cap,
215
+ (provider) => stopped(spec.name, stop(effect.cap), provider)
216
+ );
217
+ const check = (found) => {
218
+ const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
219
+ const least = boundsOf(outbound, spec.cost, input28, found);
220
+ if (least !== null && least.min > room) {
221
+ throw refusal(
222
+ spec.name,
223
+ least,
224
+ room,
225
+ stop(room, found),
226
+ outbound.provider
227
+ );
228
+ }
229
+ };
230
+ check();
231
+ const isStopped = () => counter.stopped();
232
+ return {
233
+ campaignsFound: check,
234
+ failed: (cause) => {
235
+ throw isStopped() ? stopped(spec.name, stop(effect.cap), outbound.provider) : cause;
236
+ },
237
+ outbound: withGuard(outbound, counter),
238
+ 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
239
+ };
86
240
  };
87
241
 
88
242
  // src/insights/define.ts
@@ -108,7 +262,7 @@ var RANK = {
108
262
  exact: 0,
109
263
  sampled: 1
110
264
  };
111
- var track = (outbound, now) => {
265
+ var track = (outbound, now, campaignsFound) => {
112
266
  const notes = [];
113
267
  let requests = 0;
114
268
  let evidence = "exact";
@@ -139,6 +293,7 @@ var track = (outbound, now) => {
139
293
  }
140
294
  return items;
141
295
  },
296
+ campaignsFound,
142
297
  note,
143
298
  now,
144
299
  one: (item) => {
@@ -163,34 +318,19 @@ var track = (outbound, now) => {
163
318
  };
164
319
  };
165
320
  var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
166
- var withRenames = (outbound, spec, given) => {
167
- const renamed2 = applyRenames(spec.inputSchema.shape, given);
168
- if ("conflict" in renamed2) {
169
- const { from, to } = renamed2.conflict;
170
- throw new OutboundError(
171
- "Invalid",
172
- `${spec.name}: pass \`${to}\` only; \`${from}\` is its old name`,
173
- { provider: outbound.provider }
174
- );
175
- }
176
- return renamed2;
177
- };
178
- var prepare = (outbound, spec, given) => {
179
- const fields = spec.inputSchema.shape;
180
- const renamed2 = withRenames(outbound, spec, given);
181
- const { input: input27 } = renamed2;
182
- const stray = unknownKey(liveKeys(fields), input27);
321
+ var prepare = (outbound, spec, input28) => {
322
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input28);
183
323
  if (stray !== void 0) {
184
324
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
185
325
  provider: outbound.provider
186
326
  });
187
327
  }
188
- const parsed = spec.inputSchema.safeParse(input27 ?? {});
328
+ const parsed = spec.inputSchema.safeParse(input28 ?? {});
189
329
  if (!parsed.success) {
190
330
  const [issue] = parsed.error.issues;
191
331
  throw new OutboundError(
192
332
  "Invalid",
193
- `${spec.name}: ${inputProblem(input27, issue)}`,
333
+ `${spec.name}: ${inputProblem(input28, issue)}`,
194
334
  { provider: outbound.provider }
195
335
  );
196
336
  }
@@ -219,16 +359,18 @@ var prepare = (outbound, spec, given) => {
219
359
  { provider: outbound.provider }
220
360
  );
221
361
  }
222
- return { input: parsed.data, notes: renamed2.notes };
362
+ return parsed.data;
223
363
  };
224
- var execute = async (outbound, spec, input27, options = {}) => {
225
- const checked = prepare(outbound, spec, input27);
364
+ var execute = async (outbound, spec, input28, options = {}) => {
365
+ const checked = prepare(outbound, spec, input28);
366
+ const cap = runCap(outbound, spec, checked, options);
226
367
  const now = options.now ?? Date.now();
227
- const tracker = track(outbound, now);
228
- for (const note of checked.notes) {
229
- tracker.context.note(note);
368
+ const tracker = track(cap.outbound, now, cap.campaignsFound);
369
+ const data = await spec.run(tracker.context, checked).catch(cap.failed);
370
+ const short = cap.shortNote();
371
+ if (short !== void 0) {
372
+ tracker.context.partial(short);
230
373
  }
231
- const data = await spec.run(tracker.context, checked.input);
232
374
  return {
233
375
  data,
234
376
  insight: spec.name,
@@ -241,14 +383,14 @@ var execute = async (outbound, spec, input27, options = {}) => {
241
383
  };
242
384
  var defineInsight = (spec) => ({
243
385
  ...spec,
244
- execute: async (outbound, input27, options) => {
245
- const result = await execute(outbound, spec, input27, options);
386
+ execute: async (outbound, input28, options) => {
387
+ const result = await execute(outbound, spec, input28, options);
246
388
  return { ...result, data: toJson(result.data) };
247
389
  }
248
390
  });
249
- var runInsight = (outbound, definition, input27, options = {}) => (
391
+ var runInsight = (outbound, definition, input28, options = {}) => (
250
392
  // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
251
- execute(outbound, definition, input27, options)
393
+ execute(outbound, definition, input28, options)
252
394
  );
253
395
 
254
396
  // src/insights/copy/copy-checks.ts
@@ -325,12 +467,12 @@ var tooManyLinks = (body, limits) => {
325
467
  } : null;
326
468
  };
327
469
  var spamWords = (text, limits) => {
328
- const plain = visible(text);
470
+ const plain2 = visible(text);
329
471
  const hits = limits.spamWords.filter(
330
472
  (word) => word.trim() !== "" && new RegExp(
331
473
  String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
332
474
  "iu"
333
- ).test(plain)
475
+ ).test(plain2)
334
476
  );
335
477
  return hits.length > 0 ? {
336
478
  check: "spam_words",
@@ -391,9 +533,9 @@ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChar
391
533
  } : null;
392
534
 
393
535
  // src/insights/copy/copy-audit.ts
394
- var limit = (fallback, description) => z2.number().int().min(0).default(fallback).describe(description);
395
- var input = z2.object({
396
- campaign: z2.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
536
+ var limit = (fallback, description) => z.number().int().min(0).default(fallback).describe(description);
537
+ var input = z.object({
538
+ campaign: z.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
397
539
  max_body_words: limit(150, "The most words a body may have."),
398
540
  max_caps_words: limit(
399
541
  1,
@@ -406,7 +548,7 @@ var input = z2.object({
406
548
  max_exclamations: limit(1, "How many exclamation marks a message may have."),
407
549
  max_links: limit(1, "The most links an email body may have."),
408
550
  max_subject_chars: limit(60, "The most characters a subject may have."),
409
- spam_words: z2.array(z2.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
551
+ spam_words: z.array(z.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
410
552
  "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
411
553
  )
412
554
  });
@@ -497,6 +639,7 @@ var copyAudit = defineInsight({
497
639
  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.",
498
640
  inputSchema: input,
499
641
  key: "copyAudit",
642
+ cost: (_input, price) => price.one("campaigns.get") + price.one("sequence.get"),
500
643
  name: "copy_audit",
501
644
  needs: ["sequence"],
502
645
  next: "Use step_funnel to see whether the steps with findings are also the ones with few replies.",
@@ -552,9 +695,12 @@ var copyAudit = defineInsight({
552
695
  }
553
696
  });
554
697
 
555
- // src/insights/copy/copy-reuse.ts
698
+ // src/insights/copy/copy-preview.ts
556
699
  import { z as z4 } from "zod";
557
700
 
701
+ // src/insights/people/read.ts
702
+ import { z as z3 } from "zod";
703
+
558
704
  // src/insights/capped.ts
559
705
  var readCapped = async (context, open, cap, room = cap.max) => {
560
706
  if (room >= 1) {
@@ -573,20 +719,21 @@ var campaignsReadOf = (read) => ({
573
719
  campaignsRead: read.items.length,
574
720
  moreCampaignsExist: read.capped
575
721
  });
576
- var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns") => {
722
+ var readCampaignsIn = async (context, statuses, max, input28 = "max_campaigns") => {
577
723
  const { campaigns } = context.outbound;
578
724
  const wanted = [...new Set(statuses)];
579
- const cap = { input: input27, max, what: "campaigns" };
725
+ const cap = { input: input28, max, what: "campaigns" };
580
726
  if (context.outbound.capabilities["campaigns.status"] === false) {
581
727
  const every = await readCapped(
582
728
  context,
583
729
  (room) => campaigns.listAll({ max: room }),
584
730
  cap
585
731
  );
586
- return {
587
- capped: every.capped,
588
- items: every.items.filter((campaign) => wanted.includes(campaign.status))
589
- };
732
+ const items = every.items.filter(
733
+ (campaign) => wanted.includes(campaign.status)
734
+ );
735
+ context.campaignsFound(items.length);
736
+ return { capped: every.capped, items };
590
737
  }
591
738
  const found = [];
592
739
  let capped2 = false;
@@ -600,19 +747,319 @@ var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns")
600
747
  found.push(...listed.items);
601
748
  capped2 ||= listed.capped;
602
749
  }
750
+ context.campaignsFound(found.length);
603
751
  return { capped: capped2, items: found };
604
752
  };
605
753
 
606
754
  // src/insights/fields.ts
607
- import { z as z3 } from "zod";
755
+ import { z as z2 } from "zod";
608
756
  var rangeFields = {
609
- from: z3.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
610
- to: z3.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
757
+ from: z2.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
758
+ to: z2.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
611
759
  };
612
- var statusesInput = (fallback) => z3.array(campaignStatusSchema).min(1).default([...fallback]).describe(
760
+ var statusesInput = (fallback) => z2.array(campaignStatusSchema).min(1).default([...fallback]).describe(
613
761
  "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
614
762
  );
615
763
 
764
+ // src/insights/people/read.ts
765
+ var readCappedFlag = (context, open, max, what, input28) => readCapped(context, open, { input: input28, max, what });
766
+ var readByRef = async (context, refs, read, what, effect) => {
767
+ if (refs.length === 0) {
768
+ return /* @__PURE__ */ new Map();
769
+ }
770
+ const found = await read(refs);
771
+ if (found.errors.length > 0) {
772
+ context.note(
773
+ `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
774
+ );
775
+ }
776
+ const [costliest] = found.results.toSorted(
777
+ (left, right) => right.value.meta.requests - left.value.meta.requests
778
+ );
779
+ if (costliest !== void 0) {
780
+ context.one(costliest.value);
781
+ }
782
+ return new Map(found.results.map(({ id, value }) => [id, value]));
783
+ };
784
+ var statusesField = statusesInput(["active"]);
785
+ var campaignsIn = async (context, statuses, max) => {
786
+ const { items } = await readCampaignsIn(context, statuses, max);
787
+ return items;
788
+ };
789
+ var leadsOf = async (context, campaign, max, input28) => {
790
+ const { items } = await readCappedFlag(
791
+ context,
792
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
793
+ max,
794
+ "leads of a campaign",
795
+ input28
796
+ );
797
+ return items;
798
+ };
799
+ var nameOf = (lead) => {
800
+ const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
801
+ return name === "" ? null : name;
802
+ };
803
+ var domainOf = (email) => {
804
+ const domain = email?.split("@").at(-1) ?? "";
805
+ return email === null || !email.includes("@") || domain === "" ? null : domain;
806
+ };
807
+ var DEFAULT_POSITIVE_LABELS = [
808
+ "Interested",
809
+ "Meeting Booked",
810
+ "Meeting Completed"
811
+ ];
812
+ var positiveLabelsField = z3.array(z3.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
813
+ "Vendor interest labels that count as interested, matched without regard to case"
814
+ );
815
+ var isPositive = (label, labels) => label === null ? null : labels.some(
816
+ (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
817
+ );
818
+ var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
819
+ var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
820
+ var AUTOMATIC = /* @__PURE__ */ new Set([
821
+ "bounce",
822
+ "ooo"
823
+ ]);
824
+ var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
825
+ lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
826
+ var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
827
+ var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
828
+ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
829
+ var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
830
+ var COUNTS = "no per-lead open, click or reply counts";
831
+ var noteEngagement = (context, leads, effect) => {
832
+ const { outbound } = context;
833
+ if (outbound.capabilities["leads.engagement"]) {
834
+ return;
835
+ }
836
+ if (leads.every((lead) => lead.provider === outbound.provider)) {
837
+ context.note(`This tool reports ${COUNTS}, so ${effect}.`);
838
+ return;
839
+ }
840
+ const reporting = new Set(
841
+ leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
842
+ );
843
+ const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
844
+ if (lacking.length > 0) {
845
+ context.note(
846
+ `${lacking.join(", ")} ${lacking.length === 1 ? "reports" : "report"} ${COUNTS}, so ${effect} for ${lacking.length === 1 ? "its" : "their"} records. Records from the other tools carry what their vendor reports.`
847
+ );
848
+ }
849
+ };
850
+
851
+ // src/insights/ref.ts
852
+ var refOf = (outbound, id) => {
853
+ const provider = parseRef(id)?.provider;
854
+ return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
855
+ };
856
+
857
+ // src/insights/variables.ts
858
+ var PATTERNS = [
859
+ /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
860
+ /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
861
+ /%(?<name>[A-Za-z_][\w-]*)%/gu
862
+ ];
863
+ var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
864
+ var BUILTINS = /* @__PURE__ */ new Map([
865
+ ["company", (lead) => lead.company],
866
+ ["companyname", (lead) => lead.company],
867
+ ["email", (lead) => lead.email],
868
+ ["firstname", (lead) => lead.firstName],
869
+ ["jobtitle", (lead) => lead.title],
870
+ ["lastname", (lead) => lead.lastName],
871
+ ["title", (lead) => lead.title]
872
+ ]);
873
+ var isBuiltin = (key) => BUILTINS.has(key);
874
+ var variablesIn = (text) => PATTERNS.flatMap(
875
+ (pattern) => [...text.matchAll(pattern)].map((match) => {
876
+ const fallback = match.groups?.fallback;
877
+ return {
878
+ fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
879
+ index: match.index,
880
+ name: match.groups?.name ?? "",
881
+ raw: match[0]
882
+ };
883
+ })
884
+ );
885
+ var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
886
+ var valueOf = (lead, key) => {
887
+ const builtin = BUILTINS.get(key)?.(lead);
888
+ if (filled(builtin)) {
889
+ return builtin;
890
+ }
891
+ const custom = Object.entries(lead.custom).find(
892
+ ([name, value]) => keyOf(name) === key && filled(value)
893
+ );
894
+ return custom?.[1] ?? null;
895
+ };
896
+ var keysWithValue = (lead) => /* @__PURE__ */ new Set([
897
+ ...[...BUILTINS].flatMap(
898
+ ([key, read]) => filled(read(lead)) ? [key] : []
899
+ ),
900
+ ...Object.entries(lead.custom).flatMap(
901
+ ([key, value]) => filled(value) ? [keyOf(key)] : []
902
+ )
903
+ ]);
904
+ var fillVariables = (text, lead) => {
905
+ const matches = variablesIn(text).toSorted(
906
+ (left, right) => left.index - right.index
907
+ );
908
+ const unfilled = [];
909
+ let out = "";
910
+ let at = 0;
911
+ for (const match of matches) {
912
+ if (match.index >= at) {
913
+ const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
914
+ if (value === null && !unfilled.includes(match.name)) {
915
+ unfilled.push(match.name);
916
+ }
917
+ out += text.slice(at, match.index) + (value ?? match.raw);
918
+ at = match.index + match.raw.length;
919
+ }
920
+ }
921
+ return { text: out + text.slice(at), unfilled };
922
+ };
923
+
924
+ // src/insights/copy/copy-preview.ts
925
+ var input2 = z4.object({
926
+ campaign: z4.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
927
+ lead: z4.string().min(1).nullable().default(null).describe(
928
+ "The lead's ref to render the copy for. null picks the lead read with the most variables filled."
929
+ ),
930
+ max_leads: z4.number().int().min(1).max(1e3).default(100).describe(
931
+ "The most leads to read when picking one. Ignored when `lead` is given."
932
+ )
933
+ });
934
+ var LEAD_FIELDS = /* @__PURE__ */ new Set(["company", "custom", "email", "name"]);
935
+ var keysIn = (sequence2) => new Set(
936
+ sequence2.steps.flatMap(
937
+ (step) => step.variants.flatMap(
938
+ (variant) => [variant.subject ?? "", variant.body ?? ""].flatMap(
939
+ (text) => variablesIn(text).map((match) => keyOf(match.name))
940
+ )
941
+ )
942
+ )
943
+ );
944
+ var bestLead = (leads, keys) => {
945
+ let best;
946
+ for (const lead of leads) {
947
+ const has = keysWithValue(lead);
948
+ const score = [...keys].filter((key) => has.has(key)).length;
949
+ if (best === void 0 || score > best.score) {
950
+ best = { lead, score };
951
+ }
952
+ }
953
+ return best?.lead;
954
+ };
955
+ var render = (text, lead, unfilled) => {
956
+ if (text === null) {
957
+ return null;
958
+ }
959
+ if (lead === void 0) {
960
+ for (const match of variablesIn(text)) {
961
+ if (match.fallback === null) {
962
+ unfilled.add(match.name);
963
+ }
964
+ }
965
+ return text;
966
+ }
967
+ const filled2 = fillVariables(text, lead);
968
+ for (const name of filled2.unfilled) {
969
+ unfilled.add(name);
970
+ }
971
+ return filled2.text;
972
+ };
973
+ var plain = (body) => {
974
+ if (body === null) {
975
+ return null;
976
+ }
977
+ return looksLikeHtml(body) ? htmlToText(body) : body.trim();
978
+ };
979
+ var previewStep = (step, lead) => ({
980
+ action: step.action,
981
+ delayDays: step.delayDays,
982
+ step: step.index,
983
+ variants: step.variants.map((variant) => {
984
+ const unfilled = /* @__PURE__ */ new Set();
985
+ const subject = render(variant.subject, lead, unfilled);
986
+ const body = render(variant.body, lead, unfilled);
987
+ return {
988
+ rendered: { body, bodyText: plain(body), subject },
989
+ template: { body: variant.body, subject: variant.subject },
990
+ unfilled: [...unfilled],
991
+ variantKey: variant.variantKey
992
+ };
993
+ })
994
+ });
995
+ var copyPreview = defineInsight({
996
+ description: "A campaign's copy as written and as one real lead receives it. Returns every step and variant with its subject and body exactly as stored, the same copy with the lead's values put into each {{variable}}, {variable} and %variable%, and the rendered body as plain text. Use it to read copy that is all or partly templated, such as {{subject1}} and {{content1}} filled from custom fields. Values come from first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens; a missing value falls back to the copy's own fallback, such as {{firstName|there}}, and otherwise the variable is left as written and listed as unfilled. Pass a lead's ref to choose the lead, or leave it out to use the lead read with the most variables filled. A sender signature or other variable the tool fills itself at send time stays as written. Spintax is not resolved. Costs one request for the sequence plus one for a given lead, or one per page of leads read.",
997
+ inputSchema: input2,
998
+ key: "copyPreview",
999
+ cost: (values, price) => price.one("sequence.get") + (values.lead === null ? price.upTo(1) * price.list("leads.list", values.max_leads) : price.one("leads.get")),
1000
+ scales: "max_leads",
1001
+ name: "copy_preview",
1002
+ needs: ["sequence", "leads.byCampaign"],
1003
+ next: "Use personalization_gaps to find every lead who would get a variable left as written.",
1004
+ run: async (context, values) => {
1005
+ const sequence2 = context.one(
1006
+ await context.outbound.campaign(values.campaign).sequence()
1007
+ );
1008
+ const keys = keysIn(sequence2);
1009
+ let lead;
1010
+ if (values.lead !== null) {
1011
+ lead = context.one(await context.outbound.lead(values.lead).get());
1012
+ } else if (keys.size === 0) {
1013
+ context.note("The copy uses no variables, so no lead was read.");
1014
+ } else {
1015
+ lead = bestLead(
1016
+ await leadsOf(context, values.campaign, values.max_leads, "max_leads"),
1017
+ keys
1018
+ );
1019
+ if (lead === void 0) {
1020
+ context.note(
1021
+ "The campaign has no leads, so the copy is shown as written."
1022
+ );
1023
+ }
1024
+ }
1025
+ const masked = maskingOf(context.outbound)?.fields.some(
1026
+ (field) => LEAD_FIELDS.has(field)
1027
+ );
1028
+ if (lead !== void 0 && masked === true) {
1029
+ context.note(
1030
+ "The redact plugin masks the lead's fields, so the rendered copy shows them masked. Read it without redact to see the values."
1031
+ );
1032
+ }
1033
+ const steps = sequence2.steps.map((step) => previewStep(step, lead));
1034
+ const unfilled = new Set(
1035
+ steps.flatMap(
1036
+ (step) => step.variants.flatMap((variant) => variant.unfilled.map(keyOf))
1037
+ )
1038
+ );
1039
+ const has = lead === void 0 ? null : keysWithValue(lead);
1040
+ const answer = {
1041
+ campaign: refOf(context.outbound, values.campaign),
1042
+ lead: lead === void 0 || has === null ? null : {
1043
+ email: lead.email,
1044
+ lead: lead.ref,
1045
+ linkedinUrl: lead.linkedinUrl,
1046
+ variablesFilled: [...keys].filter((key) => has.has(key)).length
1047
+ },
1048
+ steps,
1049
+ totals: {
1050
+ steps: steps.length,
1051
+ unfilled: unfilled.size,
1052
+ variables: keys.size,
1053
+ variants: steps.reduce((sum, step) => sum + step.variants.length, 0)
1054
+ }
1055
+ };
1056
+ return answer;
1057
+ }
1058
+ });
1059
+
1060
+ // src/insights/copy/copy-reuse.ts
1061
+ import { z as z5 } from "zod";
1062
+
616
1063
  // src/insights/stats.ts
617
1064
  var PLACES = 1e4;
618
1065
  var round = (value) => value === null || !Number.isFinite(value) ? null : Math.round(value * PLACES) / PLACES;
@@ -753,11 +1200,9 @@ var measure = (count2, base) => {
753
1200
  basis: base.basis,
754
1201
  count: count2,
755
1202
  high: interval?.high ?? null,
756
- interval,
757
1203
  low: interval?.low ?? null,
758
1204
  of: base.trials,
759
- rate: rate(count2, base.trials),
760
- trials: base.trials
1205
+ rate: rate(count2, base.trials)
761
1206
  };
762
1207
  };
763
1208
  var NO_RATE = {
@@ -819,7 +1264,7 @@ var pooled = (counts, baseOf) => {
819
1264
  return one === null || one.rate === null ? [] : [one];
820
1265
  });
821
1266
  const replies2 = total(measured2.map((each) => each.count));
822
- const trials = total(measured2.map((each) => each.trials));
1267
+ const trials = total(measured2.map((each) => each.of));
823
1268
  const bases = new Set(measured2.map((each) => each.basis));
824
1269
  const [basis = null] = bases.size === 1 ? bases : [];
825
1270
  return {
@@ -856,11 +1301,11 @@ var sharedBaseOf = (context, counted2) => {
856
1301
  };
857
1302
 
858
1303
  // src/insights/copy/copy-reuse.ts
859
- var input2 = z4.object({
860
- max_campaigns: z4.number().int().min(1).max(200).default(20).describe(
1304
+ var input3 = z5.object({
1305
+ max_campaigns: z5.number().int().min(1).max(200).default(20).describe(
861
1306
  "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
862
1307
  ),
863
- min_sent: z4.number().int().min(1).default(100).describe(
1308
+ min_sent: z5.number().int().min(1).default(100).describe(
864
1309
  "The smallest base (sends, or leads contacted when the vendor counts those) a campaign needs to count in the spread, and a piece of copy needs to be named the best."
865
1310
  ),
866
1311
  statuses: statusesInput(["active", "paused", "completed"])
@@ -903,10 +1348,7 @@ var useOf = (placements, baseOf) => {
903
1348
  provider: first.campaign.provider,
904
1349
  rates: { replyRate: replyRateOf(sum) },
905
1350
  replies: sum.count,
906
- replyRate: sum.rate,
907
- replyRateInterval: sum.interval,
908
- sent: sum.sent,
909
- trials: sum.trials
1351
+ sent: sum.sent
910
1352
  }
911
1353
  ];
912
1354
  };
@@ -927,18 +1369,15 @@ var pieceOf = (placements, uses, baseOf) => {
927
1369
  contentHash: first.contentHash,
928
1370
  rates: { replyRate: replyRateOf(sum) },
929
1371
  replies: sum.count,
930
- replyRate: sum.rate,
931
- replyRateInterval: sum.interval,
932
1372
  sent: sum.sent,
933
- subject: first.subject,
934
- trials: sum.trials
1373
+ subject: first.subject
935
1374
  }
936
1375
  ];
937
1376
  };
938
- var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
1377
+ var byRate = ({ rates: { replyRate: left } }, { rates: { replyRate: right } }) => (right.rate ?? -1) - (left.rate ?? -1) || (right.of ?? 0) - (left.of ?? 0);
939
1378
  var spreadOf = (uses, minSent, comparable) => {
940
1379
  const judged = uses.filter(
941
- (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
1380
+ (use) => use.rates.replyRate.rate !== null && (use.rates.replyRate.of ?? 0) >= minSent
942
1381
  );
943
1382
  const [best] = judged;
944
1383
  const worst = judged.at(-1);
@@ -953,14 +1392,16 @@ var spreadOf = (uses, minSent, comparable) => {
953
1392
  };
954
1393
  }
955
1394
  const test = compareRates(
956
- { successes: best.replies, trials: best.trials },
957
- { successes: worst.replies, trials: worst.trials }
1395
+ { successes: best.replies, trials: best.rates.replyRate.of },
1396
+ { successes: worst.replies, trials: worst.rates.replyRate.of }
958
1397
  );
959
1398
  const real = test?.significant ?? false;
960
1399
  return {
961
1400
  best: best.campaign,
962
- finding: real ? `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; a gap this size could be chance.`,
963
- spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
1401
+ finding: real ? `The same copy gets ${percent(best.rates.replyRate.rate)} in ${best.campaignName} and ${percent(worst.rates.replyRate.rate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.rates.replyRate.rate)} in ${best.campaignName} and ${percent(worst.rates.replyRate.rate)} in ${worst.campaignName}; a gap this size could be chance.`,
1402
+ spread: round(
1403
+ (best.rates.replyRate.rate ?? 0) - (worst.rates.replyRate.rate ?? 0)
1404
+ ),
964
1405
  spreadIsReal: real,
965
1406
  spreadPValue: test?.pValue ?? null,
966
1407
  worst: worst.campaign
@@ -983,8 +1424,10 @@ var readPlacements = async (context, campaigns) => {
983
1424
  };
984
1425
  var copyReuse = defineInsight({
985
1426
  description: "How the same piece of copy performs in different campaigns. Reads each campaign's sequence and step stats, matches variants by the hash of their subject and body, and returns every piece of copy used in two or more campaigns with its totals, its reply rate per campaign and the spread between its best and worst campaign, plus the copy with the highest pooled reply rate. Use it to tell a copy problem from an audience problem. Every rate is divided by the same base, leads contacted when every campaign counts them and messages sent otherwise; campaigns with no base in common are listed but not compared. Costs 2 requests per campaign plus the campaign listing. A null count means the vendor does not report it for that variant; it is never 0.",
986
- inputSchema: input2,
1427
+ inputSchema: input3,
987
1428
  key: "copyReuse",
1429
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("sequence.get") + price.one("stats")),
1430
+ scales: "max_campaigns",
988
1431
  name: "copy_reuse",
989
1432
  needs: ["sequence", "stats.byStep"],
990
1433
  next: "Use step_funnel on the campaign where the copy does worst, or variant_test where the copy runs against another variant.",
@@ -1016,7 +1459,7 @@ var copyReuse = defineInsight({
1016
1459
  (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
1017
1460
  );
1018
1461
  const [bestCopy] = pieces.flatMap(
1019
- ({ piece }) => comparable && piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
1462
+ ({ piece }) => comparable && piece.rates.replyRate.rate !== null && (piece.rates.replyRate.of ?? 0) >= min_sent ? [piece] : []
1020
1463
  ).toSorted(byRate);
1021
1464
  const result = {
1022
1465
  basis,
@@ -1032,35 +1475,29 @@ var copyReuse = defineInsight({
1032
1475
  });
1033
1476
 
1034
1477
  // src/insights/copy/reply-timing.ts
1035
- import { z as z5 } from "zod";
1478
+ import { z as z6 } from "zod";
1036
1479
 
1037
1480
  // src/insights/campaign.ts
1038
1481
  var confirmCampaign = async (context, campaign) => {
1039
1482
  context.one(await context.outbound.campaigns.get(campaign));
1040
1483
  };
1041
1484
 
1042
- // src/insights/ref.ts
1043
- var refOf = (outbound, id) => {
1044
- const provider = parseRef(id)?.provider;
1045
- return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
1046
- };
1047
-
1048
1485
  // src/insights/copy/reply-timing.ts
1049
1486
  var DAY_MS = 864e5;
1050
1487
  var MAX_UNPAIRED_SHARE = 0.25;
1051
1488
  var HOUR_MS = 36e5;
1052
1489
  var MINUTE_MS = 6e4;
1053
- var input3 = z5.object({
1054
- campaign: z5.string().min(1).nullable().default(null).describe(
1490
+ var input4 = z6.object({
1491
+ campaign: z6.string().min(1).nullable().default(null).describe(
1055
1492
  "A campaign's ref to look at one campaign; an unknown one is refused with NotFound. null looks at every campaign."
1056
1493
  ),
1057
- max_messages: z5.number().int().min(1).max(5e4).default(2e3).describe(
1494
+ max_messages: z6.number().int().min(1).max(5e4).default(2e3).describe(
1058
1495
  "The most messages to read, sent and received together. A page of messages costs 1 request."
1059
1496
  ),
1060
- since: z5.iso.datetime({ offset: true }).nullable().default(null).describe(
1497
+ since: z6.iso.datetime({ offset: true }).nullable().default(null).describe(
1061
1498
  "Only messages from this time on, ISO 8601. null means 30 days before now."
1062
1499
  ),
1063
- timezone_offset_minutes: z5.number().int().min(-720).max(840).default(0).describe(
1500
+ timezone_offset_minutes: z6.number().int().min(-720).max(840).default(0).describe(
1064
1501
  "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
1065
1502
  )
1066
1503
  });
@@ -1180,8 +1617,10 @@ var noteGaps = (context, unpaired, received) => {
1180
1617
  };
1181
1618
  var replyTiming = defineInsight({
1182
1619
  description: "How fast people reply and when. Pairs each received message with the last message sent before it in the same thread (or to the same lead) and returns the median, 75th and 90th percentile of hours to reply, the share of replies within 1, 24 and 72 hours, replies by weekday and by hour of day, the weekday and hour of the sends that drew replies, and how many replies could not be paired; over a quarter unpaired, the answer is marked partial, since a reply to a send from before `since` cannot pair and those are the slow ones. Use it to choose follow-up delays and sending hours. Costs 1 request per page of messages, up to max_messages. A null figure means no reply could be paired; auto-replies are not separated, because messages carry no auto flag.",
1183
- inputSchema: input3,
1620
+ inputSchema: input4,
1184
1621
  key: "replyTiming",
1622
+ cost: (values, price) => price.list("messages.list", values.max_messages) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")),
1623
+ scales: "max_messages",
1185
1624
  name: "reply_timing",
1186
1625
  needs: ["messages.list"],
1187
1626
  next: "Use step_funnel to see which step the replies answer, then set follow-up delays near the median time to reply.",
@@ -1195,7 +1634,7 @@ var replyTiming = defineInsight({
1195
1634
  );
1196
1635
  const paired = pair(messages);
1197
1636
  const hours = paired.pairs.map((each) => (each.at - each.sentAt) / HOUR_MS);
1198
- const within = (limit3) => rate(hours.filter((value) => value <= limit3).length, hours.length);
1637
+ const within = (limit2) => rate(hours.filter((value) => value <= limit2).length, hours.length);
1199
1638
  const received = messages.filter((message) => message.direction === "in");
1200
1639
  const untimed = received.length - paired.replyTimes.length;
1201
1640
  const unpaired = paired.unpaired + untimed;
@@ -1233,11 +1672,11 @@ var replyTiming = defineInsight({
1233
1672
  });
1234
1673
 
1235
1674
  // src/insights/copy/step-funnel.ts
1236
- import { z as z6 } from "zod";
1237
- var input4 = z6.object({
1238
- campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1675
+ import { z as z7 } from "zod";
1676
+ var input5 = z7.object({
1677
+ campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1239
1678
  ...rangeFields,
1240
- min_reply_rate: z6.number().min(0).max(1).default(0).describe(
1679
+ min_reply_rate: z7.number().min(0).max(1).default(0).describe(
1241
1680
  "A step earns its place when the low end of its reply rate interval is above this. 0 asks only that the rate is reliably above zero."
1242
1681
  )
1243
1682
  });
@@ -1247,8 +1686,6 @@ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, c
1247
1686
  contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
1248
1687
  rates: { replyRate: replyRateOf(measured2) },
1249
1688
  replies: counts.replied,
1250
- replyRate: measured2.rate,
1251
- replyRateInterval: measured2.interval,
1252
1689
  sent: counts.sent,
1253
1690
  variantKey
1254
1691
  };
@@ -1256,18 +1693,14 @@ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, c
1256
1693
  var draftOf = (index, step, stats, minReplyRate) => {
1257
1694
  const counts = stats?.total ?? null;
1258
1695
  const measured2 = counts === null ? null : measure(counts.replied, perLead(counts));
1259
- const interval = measured2?.interval ?? null;
1260
1696
  return {
1261
1697
  action: step?.action ?? null,
1262
1698
  delayDays: step?.delayDays ?? null,
1263
- earnsPlace: interval === null ? null : interval.low > minReplyRate,
1699
+ earnsPlace: measured2 === null || measured2.low === null ? null : measured2.low > minReplyRate,
1264
1700
  inSequence: step !== void 0,
1265
1701
  parent: step === void 0 ? null : step.parentIndex,
1266
1702
  rates: { replyRate: replyRateOf(measured2) },
1267
1703
  replies: counts?.replied ?? null,
1268
- replyRate: measured2?.rate ?? null,
1269
- replyRateBasis: measured2?.basis ?? null,
1270
- replyRateInterval: interval,
1271
1704
  sent: counts?.sent ?? null,
1272
1705
  step: index,
1273
1706
  variants: variantsOf(stats, step)
@@ -1314,8 +1747,9 @@ var unattributedOf = (rows) => {
1314
1747
  };
1315
1748
  var stepFunnel = defineInsight({
1316
1749
  description: "Where a campaign's replies come from: one row per sequence step with its action, delay, sends, replies, reply rate with a 95% interval, its share of all replies and how far sends fell from the step before, plus rows per variant when the vendor splits them. Names the step with the most replies and the last step that still earns its place. Use it to decide whether to cut or rewrite follow-ups. Costs 2 requests. A null count means the vendor does not report it; it is never 0.",
1317
- inputSchema: input4,
1750
+ inputSchema: input5,
1318
1751
  key: "stepFunnel",
1752
+ cost: (_input, price) => price.one("sequence.get") + price.one("stats"),
1319
1753
  name: "step_funnel",
1320
1754
  needs: ["sequence", "stats.byStep"],
1321
1755
  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.",
@@ -1370,18 +1804,18 @@ var stepFunnel = defineInsight({
1370
1804
  });
1371
1805
 
1372
1806
  // src/insights/copy/variant-test.ts
1373
- import { z as z7 } from "zod";
1807
+ import { z as z8 } from "zod";
1374
1808
  var METRICS = ["replied", "positive", "opened", "clicked"];
1375
- var input5 = z7.object({
1376
- alpha: z7.number().gt(0).max(0.5).default(0.05).describe(
1809
+ var input6 = z8.object({
1810
+ alpha: z8.number().gt(0).max(0.5).default(0.05).describe(
1377
1811
  "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1378
1812
  ),
1379
- campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1813
+ campaign: z8.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1380
1814
  ...rangeFields,
1381
- metric: z7.enum(METRICS).default("replied").describe(
1815
+ metric: z8.enum(METRICS).default("replied").describe(
1382
1816
  "What a variant is judged on. Replies and positive replies are divided by leads contacted (or sends); opens and clicks by messages delivered (or sends)."
1383
1817
  ),
1384
- min_sent: z7.number().int().min(1).default(100).describe(
1818
+ min_sent: z8.number().int().min(1).default(100).describe(
1385
1819
  "A variant with a smaller base than this (sends, or leads contacted when the vendor counts those) is not compared."
1386
1820
  )
1387
1821
  });
@@ -1399,7 +1833,7 @@ var candidateOf = (variantKey, counts, base, minSent, metric) => {
1399
1833
  const measured2 = measure(counts[metric], base);
1400
1834
  return {
1401
1835
  ...measured2,
1402
- enoughData: measured2.rate !== null && measured2.trials !== null && measured2.trials >= minSent,
1836
+ enoughData: measured2.rate !== null && measured2.of !== null && measured2.of >= minSent,
1403
1837
  sent: counts.sent,
1404
1838
  variantKey
1405
1839
  };
@@ -1409,7 +1843,7 @@ var shortfall = (candidates, minSent) => {
1409
1843
  return null;
1410
1844
  }
1411
1845
  return candidates.reduce(
1412
- (sum, each) => sum + Math.max(0, minSent - (each.trials ?? 0)),
1846
+ (sum, each) => sum + Math.max(0, minSent - (each.of ?? 0)),
1413
1847
  0
1414
1848
  );
1415
1849
  };
@@ -1436,7 +1870,7 @@ var testStep = (step, candidates, settings, comparable) => {
1436
1870
  return tooLittle(step, candidates, settings, false);
1437
1871
  }
1438
1872
  const ready = candidates.filter((each) => each.enoughData).toSorted(
1439
- (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
1873
+ (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.of ?? 0) - (left.of ?? 0)
1440
1874
  );
1441
1875
  const [leader, rival] = ready;
1442
1876
  if (leader === void 0 || rival === void 0) {
@@ -1446,8 +1880,8 @@ var testStep = (step, candidates, settings, comparable) => {
1446
1880
  ready.slice(1).map((other) => [
1447
1881
  other.variantKey,
1448
1882
  compareRates(
1449
- { successes: leader.count, trials: leader.trials },
1450
- { successes: other.count, trials: other.trials },
1883
+ { successes: leader.count, trials: leader.of },
1884
+ { successes: other.count, trials: other.of },
1451
1885
  settings.alpha
1452
1886
  )
1453
1887
  ])
@@ -1475,7 +1909,7 @@ var testStep = (step, candidates, settings, comparable) => {
1475
1909
  leader: leader.variantKey,
1476
1910
  moreSendsNeeded: closest === null ? null : sendsToSignificance(
1477
1911
  closest.z,
1478
- (leader.trials ?? 0) + (rival.trials ?? 0),
1912
+ (leader.of ?? 0) + (rival.of ?? 0),
1479
1913
  settings.alpha
1480
1914
  ),
1481
1915
  pValue: closest?.pValue ?? null,
@@ -1520,8 +1954,9 @@ var variantsReported = (context, rows) => {
1520
1954
  var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1521
1955
  var variantTest = defineInsight({
1522
1956
  description: "Whether a campaign's A/B winner is real. For each step with two or more variants, compares every variant with the leader by a two-proportion test and returns the variants with rates and 95% intervals, the leader, and a verdict: winner, no_difference_yet or too_little_data, with the p-value and a rough number of sends still needed when there is no verdict. Use it before pausing a variant. Costs 1 request. A null count or rate means the vendor does not report it; an empty list means the vendor does not split step stats by variant (variantStatsReported false) or reported no step stats in the date range (null). Variants of a step are divided by the same base; variants with no base in common are not compared.",
1523
- inputSchema: input5,
1957
+ inputSchema: input6,
1524
1958
  key: "variantTest",
1959
+ cost: (_input, price) => price.one("stats"),
1525
1960
  name: "variant_test",
1526
1961
  needs: ["stats.byStep"],
1527
1962
  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.",
@@ -1559,15 +1994,16 @@ var COPY_INSIGHTS = [
1559
1994
  stepFunnel,
1560
1995
  variantTest,
1561
1996
  copyAudit,
1997
+ copyPreview,
1562
1998
  copyReuse,
1563
1999
  replyTiming
1564
2000
  ];
1565
2001
 
1566
2002
  // src/insights/ops/anomalies.ts
1567
- import { z as z9 } from "zod";
2003
+ import { z as z10 } from "zod";
1568
2004
 
1569
2005
  // src/insights/ops/shared.ts
1570
- import { z as z8 } from "zod";
2006
+ import { z as z9 } from "zod";
1571
2007
  var DAY_MS2 = 864e5;
1572
2008
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1573
2009
  var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
@@ -1575,15 +2011,18 @@ var lastDays = (now, days, back = 0) => ({
1575
2011
  from: dayOf(now - days * (back + 1) * DAY_MS2),
1576
2012
  to: dayOf(now - (days * back + 1) * DAY_MS2)
1577
2013
  });
2014
+ var campaignTotalsCost = (input28, price) => {
2015
+ const campaigns = price.campaigns(input28.max_campaigns);
2016
+ return price.campaignsIn(new Set(input28.statuses).size, input28.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
2017
+ };
1578
2018
  var listFields = (costPerCampaign) => ({
1579
- max_campaigns: z8.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
2019
+ max_campaigns: z9.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1580
2020
  statuses: statusesInput(["active", "paused", "completed"])
1581
2021
  });
1582
2022
  var labelOf = (campaign) => ({
1583
2023
  campaign: campaign.ref,
1584
2024
  campaignName: campaign.name,
1585
2025
  channel: campaign.channel,
1586
- name: campaign.name,
1587
2026
  provider: campaign.provider,
1588
2027
  status: campaign.status
1589
2028
  });
@@ -1688,19 +2127,19 @@ var readAllTotals = async (context, range) => {
1688
2127
  [...byCampaign].map(([ref, counts]) => [ref, sumCounts(counts)])
1689
2128
  );
1690
2129
  };
1691
- var readCampaignTotals = async (context, input27) => {
2130
+ var readCampaignTotals = async (context, input28) => {
1692
2131
  const listed = await readCampaignsIn(
1693
2132
  context,
1694
- input27.statuses,
1695
- input27.max_campaigns
2133
+ input28.statuses,
2134
+ input28.max_campaigns
1696
2135
  );
1697
2136
  const campaigns = listed.items;
1698
- const reported = campaigns.length > 1 ? await readAllTotals(context, input27) : void 0;
2137
+ const reported = campaigns.length > 1 ? await readAllTotals(context, input28) : void 0;
1699
2138
  const entries = await mapConcurrent(
1700
2139
  campaigns,
1701
2140
  async (campaign) => ({
1702
2141
  campaign,
1703
- counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input27)
2142
+ counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input28)
1704
2143
  })
1705
2144
  );
1706
2145
  return { entries, read: campaignsReadOf(listed) };
@@ -1720,7 +2159,7 @@ var readDaily = async (context, campaign, range) => {
1720
2159
  };
1721
2160
 
1722
2161
  // src/insights/ops/anomalies.ts
1723
- var metricSchema = z9.enum([
2162
+ var metricSchema = z10.enum([
1724
2163
  "sent",
1725
2164
  "contacted",
1726
2165
  "replied",
@@ -1730,13 +2169,13 @@ var metricSchema = z9.enum([
1730
2169
  "clicked",
1731
2170
  "unsubscribed"
1732
2171
  ]);
1733
- var input6 = z9.object({
1734
- baseline_days: z9.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1735
- campaign: z9.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1736
- days: z9.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1737
- metrics: z9.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1738
- min_baseline_points: z9.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1739
- threshold: z9.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
2172
+ var input7 = z10.object({
2173
+ baseline_days: z10.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
2174
+ campaign: z10.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
2175
+ days: z10.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
2176
+ metrics: z10.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
2177
+ min_baseline_points: z10.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2178
+ threshold: z10.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1740
2179
  });
1741
2180
  var reasonFor2 = (metric, daysWithData) => daysWithData === 0 ? `The vendor reports no ${metric} count for these days.` : "Too few earlier days with data to form a baseline.";
1742
2181
  var judge = (metric, point, baseline, threshold) => {
@@ -1811,8 +2250,9 @@ var findAnomalies = (series, options) => {
1811
2250
  };
1812
2251
  var anomalies = defineInsight({
1813
2252
  description: "Days that broke from trend, for one campaign or the whole workspace: each of the last `days` complete days is held to the `baseline_days` before it, and a daily count `threshold` standard deviations or more from that baseline's mean is returned, newest first, with the metric, the value, the baseline mean, the z-score, the direction and how it was judged. When every baseline day has the same count there is no standard deviation: a day with another count is returned with a null z-score and judgedBy flat_baseline. Use it to spot a sending outage, a bounce spike or a reply surge. Days the vendor has no count for are skipped, never read as zero. With no campaign it reads workspace stats, so it then also needs stats.workspace. Costs one stats request.",
1814
- inputSchema: input6,
2253
+ inputSchema: input7,
1815
2254
  key: "anomalies",
2255
+ cost: (_input, price) => price.one("stats"),
1816
2256
  name: "anomalies",
1817
2257
  needs: ["stats.byDay"],
1818
2258
  // The whole workspace is read from workspace stats, a campaign from its own.
@@ -1841,7 +2281,7 @@ var anomalies = defineInsight({
1841
2281
  });
1842
2282
 
1843
2283
  // src/insights/ops/campaign-diagnosis.ts
1844
- import { z as z10 } from "zod";
2284
+ import { z as z11 } from "zod";
1845
2285
 
1846
2286
  // src/insights/ops/diagnosis-checks.ts
1847
2287
  var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
@@ -2044,12 +2484,11 @@ var unknownRates = (facts) => [
2044
2484
  ];
2045
2485
 
2046
2486
  // src/insights/ops/campaign-diagnosis.ts
2047
- var share = (fallback, text) => z10.number().min(0).max(1).default(fallback).describe(text);
2048
- var recentDays = z10.number().int().min(1).max(30);
2049
- var input7 = z10.object({
2487
+ var share = (fallback, text) => z11.number().min(0).max(1).default(fallback).describe(text);
2488
+ var input8 = z11.object({
2050
2489
  ...rangeFields,
2051
- campaign: z10.string().min(3).describe("The campaign's ref"),
2052
- days: recentDays.default(7).describe(
2490
+ campaign: z11.string().min(3).describe("The campaign's ref"),
2491
+ days: z11.number().int().min(1).max(30).default(7).describe(
2053
2492
  "The days, ending yesterday, held against the same number before"
2054
2493
  ),
2055
2494
  daily_limit_share: share(
@@ -2061,15 +2500,14 @@ var input7 = z10.object({
2061
2500
  0.3,
2062
2501
  "A fall in sends, recent days against the days before, over this share is a finding"
2063
2502
  ),
2064
- max_senders: z10.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2503
+ max_senders: z11.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2065
2504
  min_positive_share: share(
2066
2505
  0.2,
2067
2506
  "A share of replies that are positive under this is a finding"
2068
2507
  ),
2069
2508
  min_reply_rate: share(0.01, "A reply rate under this is a finding"),
2070
- min_sent: z10.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2071
- min_weekly_hours: z10.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
2072
- recent_days: renamed("days", recentDays)
2509
+ min_sent: z11.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2510
+ min_weekly_hours: z11.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume")
2073
2511
  });
2074
2512
  var readRecent = async (context, campaign, days) => {
2075
2513
  const recent = lastDays(context.now, days);
@@ -2134,8 +2572,13 @@ var summarize = (findings) => {
2134
2572
  };
2135
2573
  var campaignDiagnosis = defineInsight({
2136
2574
  description: "Why one campaign is underperforming: a list of findings, most serious first, each with a code, a plain-language finding, the numbers behind it and what to look at next. It checks for too little volume to judge, a low reply rate (with its 95% interval), a high bounce rate, few positive replies among replies, sends falling or stopped over the last days, a one or two step sequence, a sender that is not active, open tracking being off, and a schedule or daily limit that holds volume back. Also returns what could not be checked; an empty list means nothing was found, not that all is well. Costs up to 7 requests.",
2137
- inputSchema: input7,
2575
+ inputSchema: input8,
2138
2576
  key: "campaignDiagnosis",
2577
+ cost: (values, price) => {
2578
+ const { capabilities } = price;
2579
+ 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"));
2580
+ },
2581
+ scales: "max_senders",
2139
2582
  name: "campaign_diagnosis",
2140
2583
  needs: ["stats.campaign"],
2141
2584
  next: "Follow the `next` of the first finding, for example bounce_watch, step_funnel or pipeline_forecast.",
@@ -2178,17 +2621,17 @@ var campaignDiagnosis = defineInsight({
2178
2621
  });
2179
2622
 
2180
2623
  // src/insights/ops/campaign-ranking.ts
2181
- import { z as z11 } from "zod";
2182
- var metricSchema2 = z11.enum([
2624
+ import { z as z12 } from "zod";
2625
+ var metricSchema2 = z12.enum([
2183
2626
  "reply_rate",
2184
2627
  "positive_reply_rate",
2185
2628
  "bounce_rate"
2186
2629
  ]);
2187
- var input8 = z11.object({
2630
+ var input9 = z12.object({
2188
2631
  ...rangeFields,
2189
2632
  ...listFields("one stats request"),
2190
2633
  metric: metricSchema2.default("reply_rate").describe("The rate to rank by. For bounce_rate, lower is better."),
2191
- min_sent: z11.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2634
+ min_sent: z12.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2192
2635
  });
2193
2636
  var measured = (counts, metric, basis) => {
2194
2637
  const rates = ratesOf(counts, baseIn2(basis));
@@ -2197,7 +2640,7 @@ var measured = (counts, metric, basis) => {
2197
2640
  }
2198
2641
  return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
2199
2642
  };
2200
- var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.name.localeCompare(right.name);
2643
+ var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.campaignName.localeCompare(right.campaignName);
2201
2644
  var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2202
2645
  const scored = [];
2203
2646
  const tooFewSends = [];
@@ -2245,8 +2688,10 @@ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2245
2688
  };
2246
2689
  var campaignRanking = defineInsight({
2247
2690
  description: "Which campaigns are best, ranked fairly: by the low end of the 95% Wilson interval of the reply rate (or positive reply rate; for bounce rate, by the high end, lowest first), so 2 replies from 10 sends cannot outrank 150 from 1,000. Use it to pick winners and losers across a workspace. Returns each campaign with its count, rate, interval and rank, the campaigns left out for too few sends, those whose count the vendor does not report (a null rate is unknown, not zero), and the gap between the top and the median. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2248
- inputSchema: input8,
2691
+ inputSchema: input9,
2249
2692
  key: "campaignRanking",
2693
+ cost: campaignTotalsCost,
2694
+ scales: "max_campaigns",
2250
2695
  name: "campaign_ranking",
2251
2696
  needs: ["stats.campaign"],
2252
2697
  next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
@@ -2264,11 +2709,11 @@ var campaignRanking = defineInsight({
2264
2709
  });
2265
2710
 
2266
2711
  // src/insights/ops/channel-mix.ts
2267
- import { z as z12 } from "zod";
2268
- var input9 = z12.object({
2712
+ import { z as z13 } from "zod";
2713
+ var input10 = z13.object({
2269
2714
  ...rangeFields,
2270
2715
  ...listFields("one stats request"),
2271
- alpha: z12.number().gt(0).lt(1).default(0.05).describe(
2716
+ alpha: z13.number().gt(0).lt(1).default(0.05).describe(
2272
2717
  "The p-value under which a difference counts as more than chance"
2273
2718
  )
2274
2719
  });
@@ -2350,8 +2795,10 @@ var compare = (groups, alpha) => {
2350
2795
  };
2351
2796
  var channelMix = defineInsight({
2352
2797
  description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. With one channel present it returns that channel and says there is nothing to compare. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2353
- inputSchema: input9,
2798
+ inputSchema: input10,
2354
2799
  key: "channelMix",
2800
+ cost: campaignTotalsCost,
2801
+ scales: "max_campaigns",
2355
2802
  name: "channel_mix",
2356
2803
  needs: ["stats.campaign"],
2357
2804
  next: "Use campaign_ranking to see which campaigns carry the better channel.",
@@ -2386,15 +2833,15 @@ var channelMix = defineInsight({
2386
2833
  });
2387
2834
 
2388
2835
  // src/insights/ops/client-report.ts
2389
- import { z as z15 } from "zod";
2836
+ import { z as z16 } from "zod";
2390
2837
 
2391
2838
  // src/insights/ops/period-comparison.ts
2392
- import { z as z13 } from "zod";
2393
- var input10 = z13.object({
2839
+ import { z as z14 } from "zod";
2840
+ var input11 = z14.object({
2394
2841
  ...listFields("two stats requests"),
2395
- alpha: z13.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2396
- days: z13.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2397
- min_sent: z13.number().int().min(0).default(50).describe(
2842
+ alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2843
+ days: z14.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2844
+ min_sent: z14.number().int().min(0).default(50).describe(
2398
2845
  "A campaign under this many sends in either period is listed apart"
2399
2846
  )
2400
2847
  });
@@ -2523,8 +2970,10 @@ var workspaceOf = async (context, periods, alpha) => {
2523
2970
  };
2524
2971
  var periodComparison = defineInsight({
2525
2972
  description: "This period against the last: for each campaign, counts and rates for the last `days` complete days and for the `days` before, the change in each, and whether the change in the reply rate is more than chance (a two-proportion test), with the campaigns sorted by the size of that change. Also the same for every campaign added together and, where the adapter has them, for the vendor's workspace totals. Reply and positive reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly review. Campaigns under min_sent sends in either period are listed apart; a null is a count the vendor does not report, and a rate of a total counts only the campaigns that report both its count and what it divides by (a note says when some are left out). Costs two stats requests per campaign plus two for the workspace.",
2526
- inputSchema: input10,
2973
+ inputSchema: input11,
2527
2974
  key: "periodComparison",
2975
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + 2 * price.campaigns(values.max_campaigns) * price.one("stats") + (price.capabilities["stats.workspace"] === false ? 0 : 2 * price.one("stats")),
2976
+ scales: "max_campaigns",
2528
2977
  name: "period_comparison",
2529
2978
  needs: ["stats.campaign"],
2530
2979
  next: "Use campaign_diagnosis on the campaign whose reply rate fell the most.",
@@ -2553,7 +3002,7 @@ var periodComparison = defineInsight({
2553
3002
  (left, right) => descending(
2554
3003
  left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
2555
3004
  right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
2556
- ) || left.name.localeCompare(right.name)
3005
+ ) || left.campaignName.localeCompare(right.campaignName)
2557
3006
  ),
2558
3007
  current: periods.current,
2559
3008
  days: options.days,
@@ -2571,11 +3020,11 @@ var periodComparison = defineInsight({
2571
3020
  });
2572
3021
 
2573
3022
  // src/insights/ops/pipeline-forecast.ts
2574
- import { z as z14 } from "zod";
2575
- var input11 = z14.object({
2576
- campaign: z14.string().min(3).describe("The campaign's ref"),
2577
- days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2578
- max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3023
+ import { z as z15 } from "zod";
3024
+ var input12 = z15.object({
3025
+ campaign: z15.string().min(3).describe("The campaign's ref"),
3026
+ days: z15.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3027
+ max_leads: z15.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2579
3028
  });
2580
3029
  var countStatuses = (leads) => {
2581
3030
  const counts = {
@@ -2683,8 +3132,10 @@ var forecastCampaign = async (context, campaign, options) => {
2683
3132
  };
2684
3133
  var pipelineForecast = defineInsight({
2685
3134
  description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, the days of sending left at the recent daily contact rate, and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
2686
- inputSchema: input11,
3135
+ inputSchema: input12,
2687
3136
  key: "pipelineForecast",
3137
+ cost: (values, price) => price.one("campaigns.get") + price.list("leads.list", values.max_leads) + price.one("stats") + (price.capabilities["stats.byDay"] === false ? 0 : price.one("stats")),
3138
+ scales: "max_leads",
2688
3139
  name: "pipeline_forecast",
2689
3140
  needs: ["leads.byCampaign", "stats.campaign"],
2690
3141
  next: "Use client_report to see every campaign that is running out of leads.",
@@ -2702,24 +3153,22 @@ var pipelineForecast = defineInsight({
2702
3153
  });
2703
3154
 
2704
3155
  // src/insights/ops/client-report.ts
2705
- var limit2 = z15.number().int().min(1).max(20);
2706
- var input12 = z15.object({
3156
+ var input13 = z16.object({
2707
3157
  ...listFields(
2708
3158
  "two stats requests, and three more plus its leads when active"
2709
3159
  ),
2710
- alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2711
- anomaly_threshold: z15.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2712
- baseline_days: z15.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2713
- days: z15.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2714
- limit: limit2.default(3).describe("How many best and worst campaigns to show"),
2715
- max_bounce_rate: z15.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2716
- max_leads_per_campaign: z15.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2717
- min_baseline_points: z15.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2718
- min_sent: z15.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2719
- runway_days: z15.number().min(0).default(7).describe(
3160
+ alpha: z16.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3161
+ anomaly_threshold: z16.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
3162
+ baseline_days: z16.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
3163
+ days: z16.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
3164
+ limit: z16.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show"),
3165
+ max_bounce_rate: z16.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
3166
+ max_leads_per_campaign: z16.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
3167
+ min_baseline_points: z16.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
3168
+ min_sent: z16.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
3169
+ runway_days: z16.number().min(0).default(7).describe(
2720
3170
  "A campaign with this many days of leads left or fewer is flagged"
2721
- ),
2722
- top: renamed("limit", limit2)
3171
+ )
2723
3172
  });
2724
3173
  var sendingLeft = (daysLeft) => {
2725
3174
  if (daysLeft !== null && daysLeft < 0.05) {
@@ -2839,8 +3288,15 @@ var actionsOf = (report) => {
2839
3288
  };
2840
3289
  var clientReport = defineInsight({
2841
3290
  description: "One report for one client or workspace over the last `days` complete days: totals and the change from the period before, the best and worst campaigns by the low end of the interval of the reply rate, campaigns with a bounce problem, unusual days, active campaigns running out of leads, and a short list of action items in plain language, each naming the campaign and the number behind it. Reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly client update. A section the adapter cannot serve is null and named in `leftOut`, and a null count is one the vendor does not report. Costs two stats requests per campaign, one for the workspace, and for each active campaign two more plus its pages of leads.",
2842
- inputSchema: input12,
3291
+ inputSchema: input13,
2843
3292
  key: "clientReport",
3293
+ cost: (values, price) => {
3294
+ const { capabilities } = price;
3295
+ const campaigns = price.campaigns(values.max_campaigns);
3296
+ const byDay = capabilities["stats.byDay"] !== false;
3297
+ 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);
3298
+ },
3299
+ scales: "max_campaigns",
2844
3300
  name: "client_report",
2845
3301
  needs: ["stats.campaign"],
2846
3302
  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.",
@@ -2893,11 +3349,11 @@ var clientReport = defineInsight({
2893
3349
  });
2894
3350
 
2895
3351
  // src/insights/ops/tag-rollup.ts
2896
- import { z as z16 } from "zod";
2897
- var input13 = z16.object({
3352
+ import { z as z17 } from "zod";
3353
+ var input14 = z17.object({
2898
3354
  ...rangeFields,
2899
3355
  ...listFields("one stats request"),
2900
- min_sent: z16.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
3356
+ min_sent: z17.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
2901
3357
  });
2902
3358
  var groupOf2 = (tag, entries) => {
2903
3359
  const counts = entries.map((entry) => entry.counts);
@@ -2915,12 +3371,14 @@ var groupOf2 = (tag, entries) => {
2915
3371
  var named = (group) => group.tag ?? "";
2916
3372
  var tagRollup = defineInsight({
2917
3373
  description: "Results by campaign tag (for example one tag per client, offer or audience): for each tag the campaigns, messages sent, leads contacted, replies, positive replies and bounces, with reply, positive reply and bounce rates and their 95% intervals, sorted by the low end of the reply rate interval. A campaign with two tags counts in both; campaigns with none are grouped under a null tag. Tags under min_sent sends are listed apart. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a tag whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2918
- inputSchema: input13,
3374
+ inputSchema: input14,
2919
3375
  key: "tagRollup",
2920
3376
  // A tool whose campaigns carry no tags would put every campaign under one
2921
3377
  // null tag, which reads as an answer. On a combined instance one tool with
2922
3378
  // tags is enough.
2923
3379
  lacks: (outbound) => outbound.fields.campaign["tags"] === false ? "campaign tags" : null,
3380
+ cost: campaignTotalsCost,
3381
+ scales: "max_campaigns",
2924
3382
  name: "tag_rollup",
2925
3383
  needs: ["stats.campaign"],
2926
3384
  next: "Use campaign_ranking to see the campaigns inside the best and the worst tag.",
@@ -2973,97 +3431,7 @@ var OPS_INSIGHTS = [
2973
3431
 
2974
3432
  // src/insights/people/account-summary.ts
2975
3433
  import { z as z18 } from "zod";
2976
-
2977
- // src/insights/people/read.ts
2978
- import { z as z17 } from "zod";
2979
- var readCappedFlag = (context, open, max, what, input27) => readCapped(context, open, { input: input27, max, what });
2980
- var readByRef = async (context, refs, read, what, effect) => {
2981
- if (refs.length === 0) {
2982
- return /* @__PURE__ */ new Map();
2983
- }
2984
- const found = await read(refs);
2985
- if (found.errors.length > 0) {
2986
- context.note(
2987
- `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
2988
- );
2989
- }
2990
- const [costliest] = found.results.toSorted(
2991
- (left, right) => right.value.meta.requests - left.value.meta.requests
2992
- );
2993
- if (costliest !== void 0) {
2994
- context.one(costliest.value);
2995
- }
2996
- return new Map(found.results.map(({ id, value }) => [id, value]));
2997
- };
2998
- var statusesField = statusesInput(["active"]);
2999
- var campaignsIn = async (context, statuses, max) => {
3000
- const { items } = await readCampaignsIn(context, statuses, max);
3001
- return items;
3002
- };
3003
- var leadsOf = async (context, campaign, max, input27) => {
3004
- const { items } = await readCappedFlag(
3005
- context,
3006
- (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
3007
- max,
3008
- "leads of a campaign",
3009
- input27
3010
- );
3011
- return items;
3012
- };
3013
- var nameOf = (lead) => {
3014
- const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
3015
- return name === "" ? null : name;
3016
- };
3017
- var domainOf = (email) => {
3018
- const domain = email?.split("@").at(-1) ?? "";
3019
- return email === null || !email.includes("@") || domain === "" ? null : domain;
3020
- };
3021
- var DEFAULT_POSITIVE_LABELS = [
3022
- "Interested",
3023
- "Meeting Booked",
3024
- "Meeting Completed"
3025
- ];
3026
- var positiveLabelsField = z17.array(z17.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
3027
- "Vendor interest labels that count as interested, matched without regard to case"
3028
- );
3029
- var isPositive = (label, labels) => label === null ? null : labels.some(
3030
- (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
3031
- );
3032
- var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
3033
- var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
3034
- var AUTOMATIC = /* @__PURE__ */ new Set([
3035
- "bounce",
3036
- "ooo"
3037
- ]);
3038
- var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
3039
- lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
3040
- var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
3041
- var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
3042
- var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
3043
- var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
3044
- var COUNTS = "no per-lead open, click or reply counts";
3045
- var noteEngagement = (context, leads, effect) => {
3046
- const { outbound } = context;
3047
- if (outbound.capabilities["leads.engagement"]) {
3048
- return;
3049
- }
3050
- if (leads.every((lead) => lead.provider === outbound.provider)) {
3051
- context.note(`This tool reports ${COUNTS}, so ${effect}.`);
3052
- return;
3053
- }
3054
- const reporting = new Set(
3055
- leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
3056
- );
3057
- const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
3058
- if (lacking.length > 0) {
3059
- context.note(
3060
- `${lacking.join(", ")} ${lacking.length === 1 ? "reports" : "report"} ${COUNTS}, so ${effect} for ${lacking.length === 1 ? "its" : "their"} records. Records from the other tools carry what their vendor reports.`
3061
- );
3062
- }
3063
- };
3064
-
3065
- // src/insights/people/account-summary.ts
3066
- var input14 = z18.object({
3434
+ var input15 = z18.object({
3067
3435
  allow_free_domains: z18.boolean().default(false).describe(
3068
3436
  "Set to true to accept an email provider domain such as gmail.com, which is not one company"
3069
3437
  ),
@@ -3211,7 +3579,7 @@ var lastReplyOf = (people) => {
3211
3579
  };
3212
3580
  var accountSummary = defineInsight({
3213
3581
  description: "Everyone at one company across campaigns and tools, from the company's domain or any email address at it: each person with their name, title, campaigns, status, interest label and open, click and reply counts, plus totals and who replied most recently. People are matched by exact email domain, so a lead with only a LinkedIn profile is not found, and an email provider domain such as gmail.com is refused unless allow_free_domains is true. A record the vendor labels out-of-office or bounced is marked autoReplied and its replies do not count as the person replying. Costs one request per page of leads read (max_leads sets the ceiling); totals.moreLeadsExist is true when that ceiling left leads unread. A count the vendor does not report is null.",
3214
- inputSchema: input14,
3582
+ inputSchema: input15,
3215
3583
  key: "accountSummary",
3216
3584
  // Every address is masked, so no lead's domain can be read. A hash keeps
3217
3585
  // exact matching but not the domain.
@@ -3221,6 +3589,8 @@ var accountSummary = defineInsight({
3221
3589
  }
3222
3590
  return strategy === "hash" ? 'email addresses, whose domain it matches people by (under strategy "hash" too: a hashed address keeps no domain)' : "email addresses, whose domain it matches people by";
3223
3591
  },
3592
+ 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),
3593
+ scales: "max_leads",
3224
3594
  name: "account_summary",
3225
3595
  needs: [],
3226
3596
  next: "Use person_summary with one person's email address or lead ref for their full history, message by message.",
@@ -3270,7 +3640,7 @@ var HOUR = 36e5;
3270
3640
  var DAY = 24 * HOUR;
3271
3641
  var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
3272
3642
  var DEFAULT_DAYS = 14;
3273
- var input15 = z19.object({
3643
+ var input16 = z19.object({
3274
3644
  categories: z19.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
3275
3645
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
3276
3646
  ),
@@ -3417,8 +3787,10 @@ var readReplies = (context, since, max) => {
3417
3787
  };
3418
3788
  var droppedReplies = defineInsight({
3419
3789
  description: "Replies from prospects that nobody answered. Reads the replies since a date (14 days before now by default), keeps the categories that need an answer, and for each conversation reads its thread, or the lead's timeline when there is no thread, and reports it as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Returns the dropped replies longest waiting first with hours waiting, category, the campaign and its name, and the lead with their name, email and LinkedIn profile. A reply that could not be checked is counted in totals.unchecked, never reported as dropped. Costs one request per page of replies, one per conversation checked, and one per lead and per campaign among the dropped replies to name them, so at most about three times max_replies requests. totals.moreRepliesExist is true when max_replies left replies unread.",
3420
- inputSchema: input15,
3790
+ inputSchema: input16,
3421
3791
  key: "droppedReplies",
3792
+ cost: (values, price) => price.list("replies.list", values.max_replies) + price.upTo(values.max_replies) * (price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.one("leads.get")) + price.one("campaigns.get")),
3793
+ scales: "max_replies",
3422
3794
  name: "dropped_replies",
3423
3795
  needs: ["replies.list"],
3424
3796
  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.",
@@ -3503,7 +3875,7 @@ var NOT_ENGAGED = /* @__PURE__ */ new Set([
3503
3875
  "unsubscribe"
3504
3876
  ]);
3505
3877
  var weight = (value, what) => z20.number().min(0).default(value).describe(what);
3506
- var input16 = z20.object({
3878
+ var input17 = z20.object({
3507
3879
  campaign: z20.string().min(1).nullable().default(null).describe(
3508
3880
  "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3509
3881
  ),
@@ -3660,8 +4032,10 @@ var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1
3660
4032
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3661
4033
  var hotLeads = defineInsight({
3662
4034
  description: "Who to call first: leads ranked by a score built from what the vendor reports, namely a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign (an unknown one is refused with NotFound), or none to rank every lead the tool lists. A lead the vendor labels out-of-office or bounced (its interest category, or a label reading out of office) earns no reply or recency points, since a vendor's reply count may include automatic replies; a lead it labels negative (the negative or unsubscribe category, or a label reading not interested, wrong person, unsubscribed or do not contact) earns no points at all, from clicks and opens either, and is listed after every lead with a score above 0 while limit leaves room; its reason names the label. Costs one request per page of leads read (max_leads sets the ceiling). When max_leads stops the listing with more leads left, totals.moreLeadsExist is true and it also reads up to 100 replies from the last recency_days days and one request per replied lead the listing missed, at most limit of them, so engaged leads past the cap are still ranked. A part that is null means the vendor does not report that signal.",
3663
- inputSchema: input16,
4035
+ inputSchema: input17,
3664
4036
  key: "hotLeads",
4037
+ cost: (values, price) => price.list("leads.list", values.max_leads) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (price.capabilities["replies.list"] === false || price.capabilities["leads.get"] === false ? 0 : price.upTo(1) * (price.list("replies.list", 100) + price.upTo(values.limit) * price.one("leads.get"))),
4038
+ scales: "max_leads",
3665
4039
  name: "hot_leads",
3666
4040
  needs: [],
3667
4041
  next: "Use person_summary with a lead's ref, email address or LinkedIn profile to read the conversation before calling.",
@@ -3873,7 +4247,7 @@ var findPerson = async (context, identifier, maxRecords) => {
3873
4247
  };
3874
4248
 
3875
4249
  // src/insights/people/lead-collisions.ts
3876
- var input17 = z21.object({
4250
+ var input18 = z21.object({
3877
4251
  max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
3878
4252
  "The most campaigns to read. Each costs one request per page of its leads."
3879
4253
  ),
@@ -3933,11 +4307,13 @@ var toCollision = (group) => {
3933
4307
  var worstFirst = (left, right) => right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
3934
4308
  var leadCollisions = defineInsight({
3935
4309
  description: "People who are in two or more campaigns at once, so they get overlapping outreach. Reads the campaigns in the given statuses (active by default) and their leads, matches people by exact email address or LinkedIn profile, and returns each person with their campaigns, channel and tool, most campaigns first. A collision across tools (for example email in one and LinkedIn in another) is marked across_tools; one inside a tool is within_tool. Costs one request per page of campaigns plus one per page of each campaign's leads; the caps make the answer incomplete rather than slow.",
3936
- inputSchema: input17,
4310
+ inputSchema: input18,
3937
4311
  key: "leadCollisions",
3938
4312
  // A masked address is the same text for every lead, so every lead would
3939
4313
  // collide with every other. A hashed one still tells people apart.
3940
4314
  maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches people by" : null,
4315
+ 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),
4316
+ scales: "max_campaigns",
3941
4317
  name: "lead_collisions",
3942
4318
  needs: ["leads.byCampaign"],
3943
4319
  next: "Use person_summary with one of the identifiers or lead refs to see what that person was sent and whether they replied.",
@@ -3985,7 +4361,7 @@ var leadCollisions = defineInsight({
3985
4361
 
3986
4362
  // src/insights/people/person-summary.ts
3987
4363
  import { z as z22 } from "zod";
3988
- var input18 = z22.object({
4364
+ var input19 = z22.object({
3989
4365
  max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
3990
4366
  person: z22.string().min(3).describe(
3991
4367
  "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
@@ -4090,8 +4466,10 @@ var byChannel2 = (campaigns) => {
4090
4466
  };
4091
4467
  var personSummary = defineInsight({
4092
4468
  description: "Everything about one person across campaigns and channels, from their email address, LinkedIn profile or a lead ref: each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic. Costs one lookup per identifier, one request to read a lead ref, then up to 2 requests per campaign.",
4093
- inputSchema: input18,
4469
+ inputSchema: input19,
4094
4470
  key: "personSummary",
4471
+ cost: (values, price) => (isLeadRef(values.person) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
4472
+ scales: "max_campaigns",
4095
4473
  name: "person_summary",
4096
4474
  maskedOut: (masking) => {
4097
4475
  const masked = new Set(masking.fields);
@@ -4134,35 +4512,14 @@ var personSummary = defineInsight({
4134
4512
 
4135
4513
  // src/insights/people/personalization-gaps.ts
4136
4514
  import { z as z23 } from "zod";
4137
- var input19 = z23.object({
4515
+ var input20 = z23.object({
4138
4516
  campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
4139
4517
  limit: z23.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
4140
4518
  max_leads: z23.number().int().min(1).max(2e4).default(500).describe(
4141
4519
  "The most leads to check. A vendor request returns about 50 to 100 leads."
4142
4520
  )
4143
4521
  });
4144
- var PATTERNS = [
4145
- /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
4146
- /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
4147
- /%(?<name>[A-Za-z_][\w-]*)%/gu
4148
- ];
4149
- var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
4150
- var BUILTINS = /* @__PURE__ */ new Map([
4151
- ["company", (lead) => lead.company],
4152
- ["companyname", (lead) => lead.company],
4153
- ["email", (lead) => lead.email],
4154
- ["firstname", (lead) => lead.firstName],
4155
- ["jobtitle", (lead) => lead.title],
4156
- ["lastname", (lead) => lead.lastName],
4157
- ["title", (lead) => lead.title]
4158
- ]);
4159
4522
  var FIELDS = ["subject", "body"];
4160
- var variablesIn = (text) => PATTERNS.flatMap(
4161
- (pattern) => [...text.matchAll(pattern)].map((match) => ({
4162
- fallback: match.groups?.fallback !== void 0,
4163
- name: match.groups?.name ?? ""
4164
- }))
4165
- );
4166
4523
  var findVariables = (sequence2) => {
4167
4524
  const found = /* @__PURE__ */ new Map();
4168
4525
  const texts = sequence2.steps.flatMap(
@@ -4178,23 +4535,14 @@ var findVariables = (sequence2) => {
4178
4535
  for (const { field, step, text, variant } of texts) {
4179
4536
  for (const { fallback, name } of variablesIn(text)) {
4180
4537
  const entry = found.get(keyOf(name)) ?? { name, uses: [] };
4181
- entry.uses.push({ fallback, field, step, variant });
4538
+ entry.uses.push({ fallback: fallback !== null, field, step, variant });
4182
4539
  found.set(keyOf(name), entry);
4183
4540
  }
4184
4541
  }
4185
4542
  return found;
4186
4543
  };
4187
- var filled = (value) => value !== null && value.trim() !== "";
4188
- var valuesOf = (lead) => /* @__PURE__ */ new Set([
4189
- ...[...BUILTINS].flatMap(
4190
- ([key, read]) => filled(read(lead)) ? [key] : []
4191
- ),
4192
- ...Object.entries(lead.custom).flatMap(
4193
- ([key, value]) => filled(value) ? [keyOf(key)] : []
4194
- )
4195
- ]);
4196
4544
  var sourceOf = (key, customKeys) => {
4197
- if (BUILTINS.has(key)) {
4545
+ if (isBuiltin(key)) {
4198
4546
  return "builtin";
4199
4547
  }
4200
4548
  return customKeys.has(key) ? "custom" : "unknown";
@@ -4235,8 +4583,10 @@ var missingOf = (lead, values, gaps) => {
4235
4583
  };
4236
4584
  var personalizationGaps = defineInsight({
4237
4585
  description: "Leads in one campaign who will get broken copy because a merge variable has no value for them. Reads the campaign's sequence, finds every {{variable}}, {variable} and %variable% in subjects and bodies, and checks each lead for a value: first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens. Returns the variables with the steps that use them, how many leads each one affects, and the leads missing at least one. A variable with a fallback such as {{firstName|there}} is not a gap. A variable no lead has, such as a sender signature the tool fills in, is listed as unknown, not counted against leads. Costs one request for the sequence plus one per page of leads.",
4238
- inputSchema: input19,
4586
+ inputSchema: input20,
4239
4587
  key: "personalizationGaps",
4588
+ cost: (values, price) => price.one("sequence.get") + price.upTo(1) * price.list("leads.list", values.max_leads),
4589
+ scales: "max_leads",
4240
4590
  name: "personalization_gaps",
4241
4591
  needs: ["sequence", "leads.byCampaign"],
4242
4592
  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.",
@@ -4258,13 +4608,13 @@ var personalizationGaps = defineInsight({
4258
4608
  leads.flatMap((lead) => Object.keys(lead.custom).map(keyOf))
4259
4609
  );
4260
4610
  const keyed = [...found].map(
4261
- ([key, entry]) => toVariable(key, entry, leads.map(valuesOf), customKeys)
4611
+ ([key, entry]) => toVariable(key, entry, leads.map(keysWithValue), customKeys)
4262
4612
  );
4263
4613
  const variables = keyed.map((each) => each.variable).toSorted(
4264
4614
  (left, right) => (right.leadsAffected ?? -1) - (left.leadsAffected ?? -1) || left.name.localeCompare(right.name)
4265
4615
  );
4266
4616
  const gaps = keyed.filter((each) => each.variable.gap);
4267
- const affected = leads.flatMap((lead) => missingOf(lead, valuesOf(lead), gaps)).toSorted(
4617
+ const affected = leads.flatMap((lead) => missingOf(lead, keysWithValue(lead), gaps)).toSorted(
4268
4618
  (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
4269
4619
  );
4270
4620
  const answer = {
@@ -4288,7 +4638,7 @@ var personalizationGaps = defineInsight({
4288
4638
 
4289
4639
  // src/insights/people/suppression-check.ts
4290
4640
  import { z as z24 } from "zod";
4291
- var input20 = z24.object({
4641
+ var input21 = z24.object({
4292
4642
  max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
4293
4643
  "The most block list entries to read. A vendor request returns about 50 to 100."
4294
4644
  ),
@@ -4364,11 +4714,13 @@ var maskNote = (outbound) => {
4364
4714
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
4365
4715
  var suppressionCheck = defineInsight({
4366
4716
  description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. Returns each violation with the lead, the campaign, the entry and how it matched, counts per campaign, and how many block entries were read; totals.moreBlockEntriesExist is true when max_block_entries left entries unread, which were not checked. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
4367
- inputSchema: input20,
4717
+ inputSchema: input21,
4368
4718
  key: "suppressionCheck",
4369
4719
  // A masked address is the same text for every lead, so nothing can match.
4370
4720
  // A hashed one still matches the same address on the list.
4371
4721
  maskedOut: ({ fields, strategy }) => fields.includes("email") && strategy === "mask" ? "email addresses, which it matches leads to the block list by" : null,
4722
+ 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),
4723
+ scales: "max_campaigns",
4372
4724
  name: "suppression_check",
4373
4725
  needs: ["blocklist", "leads.byCampaign"],
4374
4726
  next: "Use person_summary with a violating lead's ref or email address to see what they were already sent.",
@@ -4456,20 +4808,20 @@ var PEOPLE_INSIGHTS = [
4456
4808
  import { z as z25 } from "zod";
4457
4809
 
4458
4810
  // src/insights/senders/read.ts
4459
- var readCapped2 = async (context, walk, max, what, input27) => {
4460
- const { items } = await readCapped(context, walk, { input: input27, max, what });
4811
+ var readCapped2 = async (context, walk, max, what, input28) => {
4812
+ const { items } = await readCapped(context, walk, { input: input28, max, what });
4461
4813
  return items;
4462
4814
  };
4463
4815
  var readCampaigns = async (context, statuses, max) => {
4464
4816
  const { items } = await readCampaignsIn(context, statuses, max);
4465
4817
  return items;
4466
4818
  };
4467
- var readCampaignSenders = (context, campaign, max, input27) => readCapped2(
4819
+ var readCampaignSenders = (context, campaign, max, input28) => readCapped2(
4468
4820
  context,
4469
4821
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
4470
4822
  max,
4471
4823
  `senders of campaign ${campaign.name}`,
4472
- input27
4824
+ input28
4473
4825
  );
4474
4826
  var readSenders = (context, max) => readCapped(context, (cap) => context.outbound.senders.listAll({ max: cap }), {
4475
4827
  input: "max_senders",
@@ -4511,25 +4863,22 @@ var countEach = (keys, count2) => (
4511
4863
  );
4512
4864
 
4513
4865
  // src/insights/senders/bounce-watch.ts
4514
- var maxBounceRate = z25.number().min(0).max(1);
4515
- var input21 = z25.object({
4866
+ var input22 = z25.object({
4516
4867
  ...rangeFields,
4517
4868
  include_senders: z25.boolean().default(true).describe(
4518
4869
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
4519
4870
  ),
4520
- max_bounce_rate: maxBounceRate.default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
4871
+ max_bounce_rate: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
4521
4872
  max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
4522
4873
  max_senders_per_campaign: z25.number().int().min(1).max(200).default(10).describe("The most senders to check for one campaign over the threshold"),
4523
4874
  min_sent: z25.number().int().min(0).default(100).describe(
4524
4875
  "A campaign or sender with fewer sends than this is too small to judge"
4525
4876
  ),
4526
- threshold: renamed("max_bounce_rate", maxBounceRate),
4527
4877
  statuses: statusesInput(["active"])
4528
4878
  });
4529
4879
  var countsOf2 = (bounced, sent) => ({
4530
4880
  ...measure2(bounced, sent),
4531
4881
  bounced,
4532
- interval: wilson(bounced, sent),
4533
4882
  sent
4534
4883
  });
4535
4884
  var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
@@ -4594,8 +4943,14 @@ var canCheckSenders = (context, wanted) => {
4594
4943
  };
4595
4944
  var bounceWatch = defineInsight({
4596
4945
  description: "Where bounces are too high: the campaigns whose bounce rate (bounced divided by sent) is over a threshold, worst first, each with bounced, sent, the rate and its Wilson interval, and the senders of each such campaign that are themselves over the threshold. Campaigns with too few sends to judge and campaigns with no reported bounce count are listed apart, never as clean. Use it daily, or when a domain's reputation is in doubt. Costs one listing of campaigns and 1 request per campaign, plus 1 listing and up to 1 request per sender for each campaign over the threshold. A null rate means nothing was sent.",
4597
- inputSchema: input21,
4946
+ inputSchema: input22,
4598
4947
  key: "bounceWatch",
4948
+ cost: (values, price) => {
4949
+ const campaigns = price.campaigns(values.max_campaigns);
4950
+ const bySender = values.include_senders && price.capabilities["stats.bySender"] !== false && price.capabilities["senders.byCampaign"] !== false;
4951
+ 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);
4952
+ },
4953
+ scales: "max_campaigns",
4599
4954
  name: "bounce_watch",
4600
4955
  needs: ["stats.campaign"],
4601
4956
  next: "Use domain_health on the senders named here, and settings_audit on the campaigns over the threshold.",
@@ -4624,7 +4979,6 @@ var bounceWatch = defineInsight({
4624
4979
  const entry = {
4625
4980
  campaign: campaign.ref,
4626
4981
  campaignName: campaign.name,
4627
- name: campaign.name,
4628
4982
  status: campaign.status
4629
4983
  };
4630
4984
  if (counts === null) {
@@ -4678,7 +5032,6 @@ var bounceWatch = defineInsight({
4678
5032
  minSent,
4679
5033
  over: over.toSorted(byRate2),
4680
5034
  sendersRead: withSenders ? seen.read.size : null,
4681
- threshold,
4682
5035
  tooFewSends: tooFewSends.toSorted(byRate2),
4683
5036
  totals: {
4684
5037
  bounced,
@@ -4698,13 +5051,11 @@ var bounceWatch = defineInsight({
4698
5051
 
4699
5052
  // src/insights/senders/domain-health.ts
4700
5053
  import { z as z26 } from "zod";
4701
- var maxSpamRate = z26.number().min(0).max(1);
4702
- var input22 = z26.object({
5054
+ var input23 = z26.object({
4703
5055
  max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
4704
- max_spam_rate: maxSpamRate.default(0.1).describe(
5056
+ max_spam_rate: z26.number().min(0).max(1).default(0.1).describe(
4705
5057
  "A domain whose warmup emails land in spam more often than this share is high risk"
4706
- ),
4707
- spam_rate_threshold: renamed("max_spam_rate", maxSpamRate)
5058
+ )
4708
5059
  });
4709
5060
  var RISK_ORDER = ["high", "medium", "low", "unknown"];
4710
5061
  var pooledWarmup = (checked) => {
@@ -4715,11 +5066,9 @@ var pooledWarmup = (checked) => {
4715
5066
  if (reported.length === 0) {
4716
5067
  return {
4717
5068
  ...measure2(null, null),
4718
- interval: null,
4719
5069
  mailboxes: 0,
4720
5070
  sent: null,
4721
- spam: null,
4722
- spamRate: null
5071
+ spam: null
4723
5072
  };
4724
5073
  }
4725
5074
  const sent = reported.reduce((sum, each) => sum + each.sent, 0);
@@ -4727,11 +5076,9 @@ var pooledWarmup = (checked) => {
4727
5076
  const measured2 = measure2(spam, sent);
4728
5077
  return {
4729
5078
  ...measured2,
4730
- interval: wilson(spam, sent),
4731
5079
  mailboxes: reported.length,
4732
5080
  sent,
4733
- spam,
4734
- spamRate: measured2.rate
5081
+ spam
4735
5082
  };
4736
5083
  };
4737
5084
  var missingChecks = (checked, warmup) => [
@@ -4802,8 +5149,10 @@ var seatRank = (seat) => {
4802
5149
  };
4803
5150
  var domainHealth = defineInsight({
4804
5151
  description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Costs one listing of senders plus 1 request per sender. A null count or rate means the vendor does not report it; a domain with no DNS record reported has the risk `unknown`, not `low`.",
4805
- inputSchema: input22,
5152
+ inputSchema: input23,
4806
5153
  key: "domainHealth",
5154
+ cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
5155
+ scales: "max_senders",
4807
5156
  name: "domain_health",
4808
5157
  needs: ["senders.list", "senders.health"],
4809
5158
  next: "Use warmup_readiness to see which mailboxes of a risky domain are not ready, or bounce_watch to see whether bounces already rose.",
@@ -4962,7 +5311,7 @@ var readSends = async (context, campaigns, days, senders2, split) => {
4962
5311
  };
4963
5312
 
4964
5313
  // src/insights/senders/sender-capacity.ts
4965
- var input23 = z27.object({
5314
+ var input24 = z27.object({
4966
5315
  days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
4967
5316
  max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
4968
5317
  "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
@@ -5028,7 +5377,7 @@ var shortfallOf = (read) => {
5028
5377
  };
5029
5378
  var askOf = (reads) => {
5030
5379
  const limits = reads.map((read) => read.dailyLimit);
5031
- const withLimit = limits.filter((limit3) => limit3 !== null).length;
5380
+ const withLimit = limits.filter((limit2) => limit2 !== null).length;
5032
5381
  return {
5033
5382
  campaigns: reads.length,
5034
5383
  daily: total(limits),
@@ -5058,8 +5407,15 @@ var findingOf = (capacity, ask, sends) => {
5058
5407
  };
5059
5408
  var senderCapacity = defineInsight({
5060
5409
  description: "Whether the senders can send what the campaigns ask: total daily capacity (the daily limits of active senders added up), the total daily ask of active campaigns, the average messages sent per day over the last days, utilization, and the campaigns whose own senders cannot cover their daily limit. Use it before adding campaigns or when sends fall short. Costs one listing of senders and of active campaigns, then up to 2 requests per campaign and 1 for daily stats, plus 1 per inactive or unlimited sender with split_uncounted. Utilization counts only the sends of the senders in capacity. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
5061
- inputSchema: input23,
5410
+ inputSchema: input24,
5062
5411
  key: "senderCapacity",
5412
+ cost: (values, price) => {
5413
+ const { capabilities } = price;
5414
+ const campaigns = price.campaigns(values.max_campaigns);
5415
+ 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);
5416
+ 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);
5417
+ },
5418
+ scales: "max_campaigns",
5063
5419
  name: "sender_capacity",
5064
5420
  needs: ["senders.list"],
5065
5421
  next: "Use sender_load to see which senders are shared by too many campaigns, or warmup_readiness before raising a sender's limit.",
@@ -5114,7 +5470,7 @@ var senderCapacity = defineInsight({
5114
5470
 
5115
5471
  // src/insights/senders/sender-load.ts
5116
5472
  import { z as z28 } from "zod";
5117
- var input24 = z28.object({
5473
+ var input25 = z28.object({
5118
5474
  max_campaigns: z28.number().int().min(1).max(200).default(25).describe("The most campaigns to read. Each costs 1 request."),
5119
5475
  max_campaigns_per_sender: z28.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
5120
5476
  max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
@@ -5146,14 +5502,15 @@ var riskOf = (campaign, senders2) => {
5146
5502
  finding: inactive.length > 0 ? `${campaign.name} has ${count2}, ${inactive.length} of them not active.` : `${campaign.name} has ${count2}.`,
5147
5503
  inactive: inactive.map(loaded),
5148
5504
  issues,
5149
- name: campaign.name,
5150
5505
  senders: senders2.length
5151
5506
  };
5152
5507
  };
5153
5508
  var senderLoad = defineInsight({
5154
5509
  description: "Senders that are overused or unused: the senders attached to more campaigns than allowed, the active senders attached to no campaign, and the campaigns that run on a single sender, on none, or on a sender that is not active. Use it when sends are uneven or before adding a campaign. Costs one listing of senders and of campaigns, then 1 request per campaign. Only campaigns in the given statuses are counted, so a sender used only by a paused campaign shows as unused unless paused is included.",
5155
- inputSchema: input24,
5510
+ inputSchema: input25,
5156
5511
  key: "senderLoad",
5512
+ cost: (values, price) => price.list("senders.list", values.max_senders) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("senders.list", values.max_senders),
5513
+ scales: "max_campaigns",
5157
5514
  name: "sender_load",
5158
5515
  needs: ["senders.list", "senders.byCampaign"],
5159
5516
  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.",
@@ -5226,7 +5583,7 @@ var senderLoad = defineInsight({
5226
5583
 
5227
5584
  // src/insights/senders/settings-audit.ts
5228
5585
  import { z as z29 } from "zod";
5229
- var input25 = z29.object({
5586
+ var input26 = z29.object({
5230
5587
  max_campaigns: z29.number().int().min(1).max(200).default(25).describe(
5231
5588
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
5232
5589
  ),
@@ -5376,8 +5733,10 @@ var countChecks = (campaigns) => countEach(
5376
5733
  );
5377
5734
  var settingsAudit = defineInsight({
5378
5735
  description: "Risky campaign settings, per campaign and by severity: no sending window, a window that includes the weekend or is too long or too short, no timezone, open or click tracking on, a reply that does not stop the sequence, no daily limit, sends too close together, an end date in the past on an active campaign, and a daily limit too high for the number of senders. Returns the findings per campaign, worst first, and a count per check. Use it before launching a campaign or when deliverability drops. Costs one listing of campaigns, then 1 request per campaign, or 2 when its senders can be listed. A setting the vendor reports nothing for is skipped, except a missing window, timezone or daily limit, which the vendor cannot tell apart from one that is not set.",
5379
- inputSchema: input25,
5736
+ inputSchema: input26,
5380
5737
  key: "settingsAudit",
5738
+ cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("campaigns.settings") + (price.capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders_per_campaign))),
5739
+ scales: "max_campaigns",
5381
5740
  name: "settings_audit",
5382
5741
  needs: ["campaigns.settings"],
5383
5742
  next: "Use sender_capacity to size a daily limit against the senders, or bounce_watch to see whether a flagged campaign already bounces.",
@@ -5441,7 +5800,7 @@ var settingsAudit = defineInsight({
5441
5800
 
5442
5801
  // src/insights/senders/warmup-readiness.ts
5443
5802
  import { z as z30 } from "zod";
5444
- var input26 = z30.object({
5803
+ var input27 = z30.object({
5445
5804
  check_health: z30.boolean().default(false).describe(
5446
5805
  "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
5447
5806
  ),
@@ -5516,8 +5875,10 @@ var countReasons = (judged) => countEach(
5516
5875
  );
5517
5876
  var warmupReadiness = defineInsight({
5518
5877
  description: "Which senders are not ready to send, each with its reasons: warmup off, warmup score under the bar or not reported, status not active, no daily limit and, with check_health, failing DNS records or too many warmup emails in spam. Returns counts by reason and how many are ready. A LinkedIn seat is judged on its status only. Use it before attaching mailboxes to a campaign or raising their limits. Costs one listing of senders, plus 1 request per mailbox with check_health. A null score means the vendor does not report one, which counts as not ready, not as 0.",
5519
- inputSchema: input26,
5878
+ inputSchema: input27,
5520
5879
  key: "warmupReadiness",
5880
+ cost: (values, price) => price.list("senders.list", values.max_senders) + (values.check_health && price.capabilities["senders.health"] !== false ? price.upTo(values.max_senders) * price.one("senders.health") : 0),
5881
+ scales: "max_senders",
5521
5882
  name: "warmup_readiness",
5522
5883
  needs: ["senders.list"],
5523
5884
  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.",
@@ -5580,7 +5941,7 @@ var INSIGHTS = [
5580
5941
  var ENTRIES = INSIGHTS;
5581
5942
 
5582
5943
  // src/insights/plugin.ts
5583
- var runInsightByName = async (outbound, name, input27 = {}, options = {}) => {
5944
+ var entryNamed = (outbound, name) => {
5584
5945
  const entry = ENTRIES.find(
5585
5946
  (candidate) => candidate.name === name || candidate.key === name
5586
5947
  );
@@ -5591,7 +5952,21 @@ var runInsightByName = async (outbound, name, input27 = {}, options = {}) => {
5591
5952
  { provider: outbound.provider }
5592
5953
  );
5593
5954
  }
5594
- return await entry.execute(outbound, input27, options);
5955
+ return entry;
5956
+ };
5957
+ var runInsightByName = async (outbound, name, input28 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input28, options);
5958
+ var insightCost = (outbound, name, input28 = {}) => {
5959
+ const entry = entryNamed(outbound, name);
5960
+ const parsed = entry.inputSchema.safeParse(input28);
5961
+ if (!parsed.success) {
5962
+ throw new OutboundError(
5963
+ "Invalid",
5964
+ `${entry.name}: ${parsed.error.issues[0]?.message ?? "the input is not valid"}`,
5965
+ { provider: outbound.provider }
5966
+ );
5967
+ }
5968
+ const bounds = boundsOf(outbound, entry.cost, parsed.data);
5969
+ return bounds === null ? null : { ...bounds, defaultCap: defaultCap(bounds) };
5595
5970
  };
5596
5971
  var listInsights = () => ENTRIES.map((entry) => ({
5597
5972
  description: entry.description,
@@ -5605,9 +5980,9 @@ var insights = () => ({
5605
5980
  extend: (outbound) => {
5606
5981
  const methods = {};
5607
5982
  for (const entry of ENTRIES) {
5608
- methods[entry.key] = (input27, options) => (
5983
+ methods[entry.key] = (input28, options) => (
5609
5984
  // SAFETY: the answer is the entry's own, typed per key by Insights.
5610
- entry.execute(outbound, input27, options)
5985
+ entry.execute(outbound, input28, options)
5611
5986
  );
5612
5987
  }
5613
5988
  return { insights: methods };
@@ -5617,6 +5992,7 @@ var insights = () => ({
5617
5992
 
5618
5993
  // src/insights/tools.ts
5619
5994
  import { z as z32 } from "zod";
5995
+ var INSIGHT_TOOL_CEILING = 500;
5620
5996
  var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
5621
5997
  var hintFor = (next, offered) => {
5622
5998
  const hidden = ENTRIES.flatMap(
@@ -5625,17 +6001,25 @@ var hintFor = (next, offered) => {
5625
6001
  const kept = next.split(/(?<=\.)\s+/u).filter((sentence) => !hidden.some((name) => sentence.includes(name)));
5626
6002
  return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
5627
6003
  };
5628
- var toTool = (outbound, definition, next) => ({
5629
- call: async (given) => {
6004
+ var toTool = (outbound, definition, next, perCall) => ({
6005
+ call: async (given, callOptions) => {
6006
+ const set = callOptions?.maxRequests ?? perCall;
5630
6007
  try {
5631
- const input27 = jsonInput(given);
5632
- if (input27 === void 0) {
6008
+ const input28 = jsonInput(given);
6009
+ if (input28 === void 0) {
5633
6010
  throw new OutboundError(
5634
6011
  "Invalid",
5635
6012
  `${definition.name}: the input is not JSON`
5636
6013
  );
5637
6014
  }
5638
- const result = await definition.execute(outbound, input27);
6015
+ const result = await definition.execute(
6016
+ outbound,
6017
+ input28,
6018
+ set === void 0 ? {
6019
+ capCeiling: INSIGHT_TOOL_CEILING,
6020
+ capSetting: "maxRequestsPerToolCall"
6021
+ } : { capSetting: "maxRequestsPerToolCall", maxRequests: set }
6022
+ );
5639
6023
  return {
5640
6024
  data: {
5641
6025
  complete: result.meta.complete,
@@ -5651,15 +6035,19 @@ var toTool = (outbound, definition, next) => ({
5651
6035
  ok: true
5652
6036
  };
5653
6037
  } catch (error) {
5654
- const known2 = OutboundError.is(error);
5655
- return {
5656
- error: {
5657
- code: known2 ? error.code : "Provider",
5658
- message: error instanceof Error ? error.message : String(error)
5659
- },
5660
- next: known2 && error.code === "Unsupported" ? "This insight cannot answer here; the message says why. Try another tool." : "Check the input and try again.",
5661
- ok: false
5662
- };
6038
+ const stop = capStopOf(error);
6039
+ if (stop !== void 0) {
6040
+ return failure(
6041
+ error,
6042
+ stop.requests,
6043
+ capNext(stop.cap, stop.isDefault, stop.lower)
6044
+ );
6045
+ }
6046
+ return failure(
6047
+ error,
6048
+ void 0,
6049
+ OutboundError.is(error) && error.code === "Unsupported" ? "This insight cannot answer here; the message says why. Try another tool." : void 0
6050
+ );
5663
6051
  }
5664
6052
  },
5665
6053
  description: definition.description,
@@ -5676,14 +6064,21 @@ var insightTools = (outbound, options = {}) => {
5676
6064
  );
5677
6065
  const names = new Set(offered.map((definition) => definition.name));
5678
6066
  return offered.map(
5679
- (definition) => toTool(outbound, definition, hintFor(definition.next, names))
6067
+ (definition) => toTool(
6068
+ outbound,
6069
+ definition,
6070
+ hintFor(definition.next, names),
6071
+ options.maxRequestsPerToolCall
6072
+ )
5680
6073
  );
5681
6074
  };
5682
6075
  export {
5683
6076
  INSIGHTS,
6077
+ INSIGHT_TOOL_CEILING,
5684
6078
  compareRates,
5685
6079
  defineInsight,
5686
6080
  deviation,
6081
+ insightCost,
5687
6082
  insightTools,
5688
6083
  insights,
5689
6084
  listInsights,