outbound-sdk 0.5.0 → 0.7.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 (130) hide show
  1. package/dist/alerts/check-schema.d.ts +1 -1
  2. package/dist/alerts/index.js +6 -6
  3. package/dist/audit/index.js +2 -2
  4. package/dist/benchmarks/index.js +4 -4
  5. package/dist/budget/index.js +2 -2
  6. package/dist/cards/format.d.ts +1 -1
  7. package/dist/cards/index.js +101 -62
  8. package/dist/cards/parts.d.ts +1 -6
  9. package/dist/chunks/{chunk-BLCJHP5H.js → chunk-45TXPJW7.js} +1 -0
  10. package/dist/chunks/chunk-4AVYRVN5.js +239 -0
  11. package/dist/chunks/{chunk-YYCT3NGV.js → chunk-65YAGEWZ.js} +24 -7
  12. package/dist/chunks/{chunk-BN6WCAWX.js → chunk-7I3EPR23.js} +3 -3
  13. package/dist/chunks/{chunk-3S32R2MH.js → chunk-BNDHEDHD.js} +2 -53
  14. package/dist/chunks/chunk-DNPNTD5W.js +81 -0
  15. package/dist/chunks/chunk-FALWG5U3.js +56 -0
  16. package/dist/chunks/{chunk-OLPMBRXM.js → chunk-GL7BABF2.js} +2 -2
  17. package/dist/chunks/{chunk-ZOAG2C6V.js → chunk-HIAK2GCI.js} +9 -2
  18. package/dist/chunks/{chunk-6TKFISG4.js → chunk-I7DXXGNZ.js} +42 -9
  19. package/dist/chunks/{chunk-BK5SLY32.js → chunk-JRL3QRBS.js} +264 -76
  20. package/dist/chunks/{chunk-EHSJGQ5K.js → chunk-KTYTE2BU.js} +4 -3
  21. package/dist/chunks/{chunk-JWGSB7PT.js → chunk-LD6F46UT.js} +2 -2
  22. package/dist/chunks/{chunk-2D42TQFU.js → chunk-LVZGIKNF.js} +2 -2
  23. package/dist/chunks/{chunk-PQSTQKRD.js → chunk-M2VXGLLZ.js} +35 -2
  24. package/dist/chunks/{chunk-5J7GGV62.js → chunk-MW4C6LTN.js} +2 -2
  25. package/dist/chunks/chunk-OK3GAZMT.js +51 -0
  26. package/dist/chunks/{chunk-BOWXGMN3.js → chunk-POBAY3TI.js} +80 -4
  27. package/dist/chunks/{chunk-J7DDZ4C2.js → chunk-QFC4ZHD3.js} +1 -1
  28. package/dist/chunks/{chunk-GFDNRWR3.js → chunk-UFQ4WMLU.js} +1 -1
  29. package/dist/chunks/{chunk-WGW3ROLY.js → chunk-Y7KECJAV.js} +1 -1
  30. package/dist/chunks/{chunk-QAKJ76HB.js → chunk-YW6FFVSZ.js} +1 -1
  31. package/dist/chunks/{chunk-X4RDBD4J.js → chunk-ZJCVLBAE.js} +445 -119
  32. package/dist/cli/bin.js +14 -14
  33. package/dist/cli/by-name.d.ts +28 -0
  34. package/dist/cli/commands.d.ts +2 -1
  35. package/dist/cli/config.d.ts +3 -2
  36. package/dist/cli/envelope.d.ts +50 -0
  37. package/dist/cli/index.d.ts +3 -0
  38. package/dist/cli/index.js +13 -13
  39. package/dist/cli/listing.d.ts +13 -0
  40. package/dist/cli/native.d.ts +4 -0
  41. package/dist/cli/options.d.ts +88 -0
  42. package/dist/cli/output.d.ts +21 -0
  43. package/dist/cli/suggest.d.ts +10 -0
  44. package/dist/clients/index.js +6 -6
  45. package/dist/combine/index.js +7 -7
  46. package/dist/emailbison/capabilities.d.ts +1 -0
  47. package/dist/emailbison/index.js +38 -13
  48. package/dist/emailbison/map-stats.d.ts +10 -0
  49. package/dist/exporter/index.js +2 -2
  50. package/dist/failover/index.js +2 -2
  51. package/dist/fixtures/index.js +4 -4
  52. package/dist/heyreach/capabilities.d.ts +3 -0
  53. package/dist/heyreach/index.js +36 -12
  54. package/dist/heyreach/map-account.d.ts +2 -2
  55. package/dist/identity/index.js +2 -2
  56. package/dist/index.js +9 -7
  57. package/dist/insights/copy/audit-samples.d.ts +24 -0
  58. package/dist/insights/copy/audit-variant.d.ts +34 -0
  59. package/dist/insights/copy/copy-audit.d.ts +26 -12
  60. package/dist/insights/copy/copy-preview.d.ts +71 -0
  61. package/dist/insights/copy/copy-reuse.d.ts +0 -13
  62. package/dist/insights/copy/index.d.ts +15 -0
  63. package/dist/insights/copy/reply-timing.d.ts +4 -0
  64. package/dist/insights/copy/reuse-base.d.ts +0 -2
  65. package/dist/insights/copy/shared.d.ts +7 -9
  66. package/dist/insights/copy/step-funnel.d.ts +21 -18
  67. package/dist/insights/copy/variant-test.d.ts +2 -8
  68. package/dist/insights/index.js +1357 -717
  69. package/dist/insights/inputs.generated.d.ts +67 -34
  70. package/dist/insights/ops/campaign-diagnosis.d.ts +2 -2
  71. package/dist/insights/ops/client-report.d.ts +0 -2
  72. package/dist/insights/ops/diagnosis-checks.d.ts +20 -1
  73. package/dist/insights/ops/index.d.ts +2 -4
  74. package/dist/insights/ops/pipeline-forecast.d.ts +17 -6
  75. package/dist/insights/ops/shared.d.ts +0 -2
  76. package/dist/insights/people/account-summary.d.ts +14 -1
  77. package/dist/insights/people/auto-replies.d.ts +14 -0
  78. package/dist/insights/people/dropped-replies.d.ts +1 -1
  79. package/dist/insights/people/hot-leads.d.ts +5 -1
  80. package/dist/insights/people/index.d.ts +4 -0
  81. package/dist/insights/people/lead-collisions.d.ts +11 -2
  82. package/dist/insights/people/person-summary.d.ts +19 -3
  83. package/dist/insights/people/personalization-gaps.d.ts +14 -8
  84. package/dist/insights/people/suppression-check.d.ts +9 -0
  85. package/dist/insights/registry.d.ts +20 -8
  86. package/dist/insights/senders/bounce-watch.d.ts +0 -11
  87. package/dist/insights/senders/domain-health.d.ts +0 -7
  88. package/dist/insights/senders/index.d.ts +0 -4
  89. package/dist/insights/senders/sender-load.d.ts +0 -2
  90. package/dist/insights/step.d.ts +15 -0
  91. package/dist/insights/types.d.ts +1 -1
  92. package/dist/insights/variables.d.ts +35 -0
  93. package/dist/instantly/capabilities.d.ts +4 -0
  94. package/dist/instantly/index.js +265 -53
  95. package/dist/instantly/map-stats.d.ts +4 -0
  96. package/dist/instantly/stats-tracking.d.ts +19 -0
  97. package/dist/instantly/thread.d.ts +9 -0
  98. package/dist/internal/adapter.d.ts +5 -0
  99. package/dist/internal/auto-reply.d.ts +20 -0
  100. package/dist/internal/capabilities.d.ts +2 -0
  101. package/dist/internal/entities-account.d.ts +1 -0
  102. package/dist/internal/entities.d.ts +79 -2
  103. package/dist/internal/fields.d.ts +37 -1
  104. package/dist/internal/metrics.d.ts +23 -1
  105. package/dist/internal/outbound/api.d.ts +2 -0
  106. package/dist/internal/records.d.ts +2 -2
  107. package/dist/internal/reply-people.d.ts +37 -0
  108. package/dist/internal/runway.d.ts +42 -0
  109. package/dist/internal/sender-screen.d.ts +9 -0
  110. package/dist/internal/tracking.d.ts +33 -0
  111. package/dist/loader/index.js +4 -4
  112. package/dist/memory/data.d.ts +2 -1
  113. package/dist/memory/index.js +23 -12
  114. package/dist/redact/index.js +3 -3
  115. package/dist/smartlead/capabilities.d.ts +4 -0
  116. package/dist/smartlead/index.js +154 -38
  117. package/dist/smartlead/map-account.d.ts +3 -0
  118. package/dist/smartlead/stats-tracking.d.ts +22 -0
  119. package/dist/sync/index.js +2 -2
  120. package/dist/tools/ai-sdk.js +8 -7
  121. package/dist/tools/by-name.d.ts +18 -0
  122. package/dist/tools/campaign-tools.d.ts +6 -2
  123. package/dist/tools/claude-agent.js +8 -7
  124. package/dist/tools/index.js +9 -8
  125. package/dist/tools/shared.d.ts +7 -0
  126. package/dist/tracing/index.js +2 -2
  127. package/dist/webhooks/index.js +12 -10
  128. package/package.json +1 -1
  129. package/dist/chunks/chunk-HWHI4LFY.js +0 -102
  130. package/dist/internal/renamed.d.ts +0 -28
@@ -1,8 +1,17 @@
1
1
  import {
2
+ SCREENED_AT_MOST,
2
3
  capNext,
3
4
  failure,
4
- inputProblem
5
- } from "../chunks/chunk-HWHI4LFY.js";
5
+ inputProblem,
6
+ leadsToStart,
7
+ namesCampaign,
8
+ newLeadsPerDay,
9
+ paceWindow,
10
+ runwayDays,
11
+ splitActive,
12
+ warmupAtZero,
13
+ withCampaign
14
+ } from "../chunks/chunk-4AVYRVN5.js";
6
15
  import {
7
16
  count,
8
17
  percentOf,
@@ -21,8 +30,17 @@ import {
21
30
  shownKey
22
31
  } from "../chunks/chunk-PTZO4QXR.js";
23
32
  import {
24
- sumCounts
25
- } from "../chunks/chunk-PQSTQKRD.js";
33
+ htmlToText,
34
+ looksLikeHtml
35
+ } from "../chunks/chunk-FALWG5U3.js";
36
+ import {
37
+ leadStatusSchema
38
+ } from "../chunks/chunk-POBAY3TI.js";
39
+ import {
40
+ CONTACTED_LEADS_LIMIT,
41
+ contactedBeyondLeads,
42
+ sumMeasured
43
+ } from "../chunks/chunk-M2VXGLLZ.js";
26
44
  import {
27
45
  campaignStatusSchema,
28
46
  replyCategorySchema
@@ -30,19 +48,18 @@ import {
30
48
  import {
31
49
  makeRef,
32
50
  parseRef
33
- } from "../chunks/chunk-QAKJ76HB.js";
51
+ } from "../chunks/chunk-YW6FFVSZ.js";
34
52
  import {
35
53
  profileSlug
36
54
  } from "../chunks/chunk-NAWZ73QS.js";
37
55
  import {
38
56
  OutboundError
39
- } from "../chunks/chunk-J7DDZ4C2.js";
57
+ } from "../chunks/chunk-QFC4ZHD3.js";
40
58
  import {
41
- isJsonObject,
42
59
  jsonInput,
43
60
  toJson,
44
61
  unknownKey
45
- } from "../chunks/chunk-BLCJHP5H.js";
62
+ } from "../chunks/chunk-45TXPJW7.js";
46
63
 
47
64
  // src/insights/plugin.ts
48
65
  import { z as z31 } from "zod";
@@ -96,15 +113,15 @@ var pricer = (outbound, costs, most, found) => {
96
113
  }
97
114
  };
98
115
  };
99
- var boundsOf = (outbound, cost, input27, found) => {
116
+ var boundsOf = (outbound, cost, input28, found) => {
100
117
  const costs = cappedAccess(outbound)?.costs;
101
118
  if (cost === void 0 || costs === void 0) {
102
119
  return null;
103
120
  }
104
121
  try {
105
122
  return {
106
- max: cost(input27, pricer(outbound, costs, true, found)),
107
- min: cost(input27, pricer(outbound, costs, false, found))
123
+ max: cost(input28, pricer(outbound, costs, true, found)),
124
+ min: cost(input28, pricer(outbound, costs, false, found))
108
125
  };
109
126
  } catch (error) {
110
127
  if (error === UNKNOWN) {
@@ -145,8 +162,8 @@ var stopped = (name, stop, provider) => capError(
145
162
  stop,
146
163
  provider
147
164
  );
148
- var fitting = (outbound, cost, input27, name, room, found) => {
149
- const fields = input27;
165
+ var fitting = (outbound, cost, input28, name, room, found) => {
166
+ const fields = input28;
150
167
  const current = fields[name];
151
168
  if (typeof current !== "number" || current <= 1) {
152
169
  return void 0;
@@ -178,49 +195,7 @@ var fitting = (outbound, cost, input27, name, room, found) => {
178
195
  };
179
196
 
180
197
  // src/insights/copy/copy-audit.ts
181
- import { z as z2 } from "zod";
182
-
183
- // src/internal/renamed.ts
184
- import { z } from "zod";
185
- var REMOVED_IN = "0.6.0";
186
- var renames = z.registry();
187
- var renamed = (to, base) => {
188
- const field = base.optional().meta({
189
- deprecated: true,
190
- description: `Deprecated: renamed to \`${to}\`. Removed in ${REMOVED_IN}.`
191
- });
192
- renames.add(field, { to });
193
- return field;
194
- };
195
- var renamesIn = (fields) => Object.entries(fields).flatMap(([from, schema]) => {
196
- const link = renames.get(schema);
197
- return link === void 0 ? [] : [{ from, to: link.to }];
198
- });
199
- var liveKeys = (fields) => {
200
- const old = new Set(renamesIn(fields).map((each) => each.from));
201
- return Object.keys(fields).filter((key) => !old.has(key));
202
- };
203
- var applyRenames = (fields, input27) => {
204
- if (!isJsonObject(input27)) {
205
- return { input: input27, notes: [] };
206
- }
207
- const moved = new Map(Object.entries(input27));
208
- const notes = [];
209
- for (const { from, to } of renamesIn(fields)) {
210
- const value = moved.get(from);
211
- moved.delete(from);
212
- if (value !== void 0) {
213
- if (moved.get(to) !== void 0) {
214
- return { conflict: { from, to } };
215
- }
216
- moved.set(to, value);
217
- notes.push(
218
- `\`${from}\` is deprecated and will be removed in ${REMOVED_IN}; use \`${to}\`.`
219
- );
220
- }
221
- }
222
- return { input: Object.fromEntries(moved), notes };
223
- };
198
+ import { z as z4 } from "zod";
224
199
 
225
200
  // src/insights/run-cap.ts
226
201
  var capFor = (outbound, name, max, options) => {
@@ -241,12 +216,12 @@ var capFor = (outbound, name, max, options) => {
241
216
  };
242
217
  var hasRunBudget = (outbound) => "requestBudget" in outbound;
243
218
  var runBudgetLeft = (outbound) => hasRunBudget(outbound) && outbound.requestBudget.per === "run" ? outbound.requestBudget.remaining() : Infinity;
244
- var runCap = (outbound, spec, input27, options) => {
245
- const bounds = boundsOf(outbound, spec.cost, input27);
219
+ var runCap = (outbound, spec, input28, options) => {
220
+ const bounds = boundsOf(outbound, spec.cost, input28);
246
221
  const effect = capFor(outbound, spec.name, defaultCap(bounds), options);
247
222
  const stop = (room, found) => ({
248
223
  ...effect,
249
- lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input27, spec.scales, room, found),
224
+ lower: spec.cost === void 0 || spec.scales === void 0 ? void 0 : fitting(outbound, spec.cost, input28, spec.scales, room, found),
250
225
  requests: counter.used()
251
226
  });
252
227
  const counter = requestCounter(
@@ -255,7 +230,7 @@ var runCap = (outbound, spec, input27, options) => {
255
230
  );
256
231
  const check = (found) => {
257
232
  const room = Math.min(effect.cap, counter.used() + runBudgetLeft(outbound));
258
- const least = boundsOf(outbound, spec.cost, input27, found);
233
+ const least = boundsOf(outbound, spec.cost, input28, found);
259
234
  if (least !== null && least.min > room) {
260
235
  throw refusal(
261
236
  spec.name,
@@ -357,34 +332,19 @@ var track = (outbound, now, campaignsFound) => {
357
332
  };
358
333
  };
359
334
  var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
360
- var withRenames = (outbound, spec, given) => {
361
- const renamed2 = applyRenames(spec.inputSchema.shape, given);
362
- if ("conflict" in renamed2) {
363
- const { from, to } = renamed2.conflict;
364
- throw new OutboundError(
365
- "Invalid",
366
- `${spec.name}: pass \`${to}\` only; \`${from}\` is its old name`,
367
- { provider: outbound.provider }
368
- );
369
- }
370
- return renamed2;
371
- };
372
- var prepare = (outbound, spec, given) => {
373
- const fields = spec.inputSchema.shape;
374
- const renamed2 = withRenames(outbound, spec, given);
375
- const { input: input27 } = renamed2;
376
- const stray = unknownKey(liveKeys(fields), input27);
335
+ var prepare = (outbound, spec, input28) => {
336
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input28);
377
337
  if (stray !== void 0) {
378
338
  throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
379
339
  provider: outbound.provider
380
340
  });
381
341
  }
382
- const parsed = spec.inputSchema.safeParse(input27 ?? {});
342
+ const parsed = spec.inputSchema.safeParse(input28 ?? {});
383
343
  if (!parsed.success) {
384
344
  const [issue] = parsed.error.issues;
385
345
  throw new OutboundError(
386
346
  "Invalid",
387
- `${spec.name}: ${inputProblem(input27, issue)}`,
347
+ `${spec.name}: ${inputProblem(input28, issue)}`,
388
348
  { provider: outbound.provider }
389
349
  );
390
350
  }
@@ -413,17 +373,31 @@ var prepare = (outbound, spec, given) => {
413
373
  { provider: outbound.provider }
414
374
  );
415
375
  }
416
- return { input: parsed.data, notes: renamed2.notes };
376
+ return parsed.data;
377
+ };
378
+ var NAMED_AMONG = 1e3;
379
+ var priced = (outbound, spec, input28) => {
380
+ const { cost } = spec;
381
+ return cost === void 0 || !namesCampaign(outbound, input28) ? spec : {
382
+ ...spec,
383
+ cost: (values, price) => cost(values, price) + price.list("campaigns.list", NAMED_AMONG)
384
+ };
417
385
  };
418
- var execute = async (outbound, spec, input27, options = {}) => {
419
- const checked = prepare(outbound, spec, input27);
420
- const cap = runCap(outbound, spec, checked.input, options);
386
+ var execute = async (outbound, spec, input28, options = {}) => {
387
+ const checked = prepare(outbound, spec, input28);
388
+ const cap = runCap(
389
+ outbound,
390
+ priced(outbound, spec, checked),
391
+ checked,
392
+ options
393
+ );
421
394
  const now = options.now ?? Date.now();
422
395
  const tracker = track(cap.outbound, now, cap.campaignsFound);
423
- for (const note of checked.notes) {
424
- tracker.context.note(note);
425
- }
426
- const data = await spec.run(tracker.context, checked.input).catch(cap.failed);
396
+ const data = await withCampaign(
397
+ tracker.context.outbound,
398
+ checked,
399
+ (walk) => tracker.context.all(walk)
400
+ ).then((resolved) => spec.run(tracker.context, resolved)).catch(cap.failed);
427
401
  const short = cap.shortNote();
428
402
  if (short !== void 0) {
429
403
  tracker.context.partial(short);
@@ -440,15 +414,252 @@ var execute = async (outbound, spec, input27, options = {}) => {
440
414
  };
441
415
  var defineInsight = (spec) => ({
442
416
  ...spec,
443
- execute: async (outbound, input27, options) => {
444
- const result = await execute(outbound, spec, input27, options);
417
+ execute: async (outbound, input28, options) => {
418
+ const result = await execute(outbound, spec, input28, options);
445
419
  return { ...result, data: toJson(result.data) };
446
420
  }
447
421
  });
448
- var runInsight = (outbound, definition, input27, options = {}) => (
422
+ var runInsight = (outbound, definition, input28, options = {}) => (
449
423
  // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
450
- execute(outbound, definition, input27, options)
424
+ execute(outbound, definition, input28, options)
425
+ );
426
+
427
+ // src/insights/people/read.ts
428
+ import { z as z2 } from "zod";
429
+
430
+ // src/insights/capped.ts
431
+ var readCapped = async (context, open, cap, room = cap.max) => {
432
+ if (room >= 1) {
433
+ const walk = open(room);
434
+ const items = await context.all(walk, cap);
435
+ return { capped: walk.truncated, items };
436
+ }
437
+ const probe = open(1);
438
+ const left = await context.all(probe, cap);
439
+ if (left.length > 0 && !probe.truncated) {
440
+ context.partial(capNote(cap));
441
+ }
442
+ return { capped: left.length > 0, items: [] };
443
+ };
444
+ var campaignsReadOf = (read) => ({
445
+ campaignsRead: read.items.length,
446
+ moreCampaignsExist: read.capped
447
+ });
448
+ var readCampaignsIn = async (context, statuses, max, input28 = "max_campaigns") => {
449
+ const { campaigns } = context.outbound;
450
+ const wanted = [...new Set(statuses)];
451
+ const cap = { input: input28, max, what: "campaigns" };
452
+ if (context.outbound.capabilities["campaigns.status"] === false) {
453
+ const every = await readCapped(
454
+ context,
455
+ (room) => campaigns.listAll({ max: room }),
456
+ cap
457
+ );
458
+ const items = every.items.filter(
459
+ (campaign) => wanted.includes(campaign.status)
460
+ );
461
+ context.campaignsFound(items.length);
462
+ return { capped: every.capped, items };
463
+ }
464
+ const found = [];
465
+ let capped2 = false;
466
+ for (const status of wanted) {
467
+ const listed2 = await readCapped(
468
+ context,
469
+ (room) => campaigns.listAll({ max: room, status }),
470
+ cap,
471
+ max - found.length
472
+ );
473
+ found.push(...listed2.items);
474
+ capped2 ||= listed2.capped;
475
+ }
476
+ context.campaignsFound(found.length);
477
+ return { capped: capped2, items: found };
478
+ };
479
+
480
+ // src/insights/fields.ts
481
+ import { z } from "zod";
482
+ var rangeFields = {
483
+ from: z.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
484
+ to: z.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
485
+ };
486
+ var statusesInput = (fallback) => z.array(campaignStatusSchema).min(1).default([...fallback]).describe(
487
+ "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
488
+ );
489
+
490
+ // src/insights/people/read.ts
491
+ var readCappedFlag = (context, open, max, what, input28) => readCapped(context, open, { input: input28, max, what });
492
+ var readByRef = async (context, refs, read, what, effect) => {
493
+ if (refs.length === 0) {
494
+ return /* @__PURE__ */ new Map();
495
+ }
496
+ const found = await read(refs);
497
+ if (found.errors.length > 0) {
498
+ context.note(
499
+ `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
500
+ );
501
+ }
502
+ const [costliest] = found.results.toSorted(
503
+ (left, right) => right.value.meta.requests - left.value.meta.requests
504
+ );
505
+ if (costliest !== void 0) {
506
+ context.one(costliest.value);
507
+ }
508
+ return new Map(found.results.map(({ id, value }) => [id, value]));
509
+ };
510
+ var statusesField = statusesInput(["active"]);
511
+ var campaignsIn = async (context, statuses, max) => {
512
+ const { items } = await readCampaignsIn(context, statuses, max);
513
+ return items;
514
+ };
515
+ var leadsOf = async (context, campaign, max, input28) => {
516
+ const { items } = await readCappedFlag(
517
+ context,
518
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
519
+ max,
520
+ "leads of a campaign",
521
+ input28
522
+ );
523
+ return items;
524
+ };
525
+ var nameOf = (lead) => {
526
+ const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
527
+ return name === "" ? null : name;
528
+ };
529
+ var domainOf = (email) => {
530
+ const domain = email?.split("@").at(-1) ?? "";
531
+ return email === null || !email.includes("@") || domain === "" ? null : domain;
532
+ };
533
+ var DEFAULT_POSITIVE_LABELS = [
534
+ "Interested",
535
+ "Meeting Booked",
536
+ "Meeting Completed"
537
+ ];
538
+ var positiveLabelsField = z2.array(z2.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
539
+ "Vendor interest labels that count as interested, matched without regard to case"
451
540
  );
541
+ var isPositive = (label, labels) => label === null ? null : labels.some(
542
+ (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
543
+ );
544
+ var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
545
+ var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
546
+ var AUTOMATIC = /* @__PURE__ */ new Set([
547
+ "bounce",
548
+ "ooo"
549
+ ]);
550
+ 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.
551
+ lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
552
+ var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
553
+ var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
554
+ var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
555
+ var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
556
+ var COUNTS = "no per-lead open, click or reply counts";
557
+ var noteEngagement = (context, leads, effect) => {
558
+ const { outbound } = context;
559
+ if (outbound.capabilities["leads.engagement"]) {
560
+ return;
561
+ }
562
+ if (leads.every((lead) => lead.provider === outbound.provider)) {
563
+ context.note(`This tool reports ${COUNTS}, so ${effect}.`);
564
+ return;
565
+ }
566
+ const reporting = new Set(
567
+ leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
568
+ );
569
+ const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
570
+ if (lacking.length > 0) {
571
+ context.note(
572
+ `${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.`
573
+ );
574
+ }
575
+ };
576
+
577
+ // src/insights/variables.ts
578
+ var PATTERNS = [
579
+ /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
580
+ /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
581
+ /%(?<name>[A-Za-z_][\w-]*)%/gu
582
+ ];
583
+ var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
584
+ var BUILTINS = /* @__PURE__ */ new Map([
585
+ ["company", (lead) => lead.company],
586
+ ["companyname", (lead) => lead.company],
587
+ ["email", (lead) => lead.email],
588
+ ["firstname", (lead) => lead.firstName],
589
+ ["jobtitle", (lead) => lead.title],
590
+ ["lastname", (lead) => lead.lastName],
591
+ ["title", (lead) => lead.title]
592
+ ]);
593
+ var isBuiltin = (key) => BUILTINS.has(key);
594
+ var SENDER = /* @__PURE__ */ new Map([
595
+ [
596
+ "instantly",
597
+ /* @__PURE__ */ new Set([
598
+ "accountsignature",
599
+ "sendingaccountemail",
600
+ "sendingaccountfirstname",
601
+ "sendingaccountname"
602
+ ])
603
+ ]
604
+ ]);
605
+ var isSender = (provider, key) => SENDER.get(provider)?.has(key) ?? false;
606
+ var variablesIn = (text) => PATTERNS.flatMap(
607
+ (pattern) => [...text.matchAll(pattern)].map((match) => {
608
+ const fallback = match.groups?.fallback;
609
+ return {
610
+ fallback: fallback === void 0 ? null : fallback.slice(1).trim(),
611
+ index: match.index,
612
+ name: match.groups?.name ?? "",
613
+ raw: match[0]
614
+ };
615
+ })
616
+ );
617
+ var filled = (value) => value !== null && value !== void 0 && value.trim() !== "";
618
+ var valueOf = (lead, key) => {
619
+ const builtin = BUILTINS.get(key)?.(lead);
620
+ if (filled(builtin)) {
621
+ return builtin;
622
+ }
623
+ const custom = Object.entries(lead.custom).find(
624
+ ([name, value]) => keyOf(name) === key && filled(value)
625
+ );
626
+ return custom?.[1] ?? null;
627
+ };
628
+ var keysWithValue = (lead) => /* @__PURE__ */ new Set([
629
+ ...[...BUILTINS].flatMap(
630
+ ([key, read]) => filled(read(lead)) ? [key] : []
631
+ ),
632
+ ...Object.entries(lead.custom).flatMap(
633
+ ([key, value]) => filled(value) ? [keyOf(key)] : []
634
+ )
635
+ ]);
636
+ var fillVariables = (text, lead) => {
637
+ const matches = variablesIn(text).toSorted(
638
+ (left, right) => left.index - right.index
639
+ );
640
+ const unfilled = [];
641
+ let out = "";
642
+ let at = 0;
643
+ for (const match of matches) {
644
+ if (match.index >= at) {
645
+ const value = valueOf(lead, keyOf(match.name)) ?? match.fallback;
646
+ if (value === null && !unfilled.includes(match.name)) {
647
+ unfilled.push(match.name);
648
+ }
649
+ out += text.slice(at, match.index) + (value ?? match.raw);
650
+ at = match.index + match.raw.length;
651
+ }
652
+ }
653
+ return { text: out + text.slice(at), unfilled };
654
+ };
655
+
656
+ // src/insights/step.ts
657
+ var stepAt = (index) => ({
658
+ step: index,
659
+ stepIndex: index,
660
+ stepNumber: index + 1
661
+ });
662
+ var stepLabel = (index, of = null) => of === null || of < index + 1 ? `step ${index + 1}` : `step ${index + 1} (of ${of})`;
452
663
 
453
664
  // src/insights/copy/copy-checks.ts
454
665
  var CHECKS = {
@@ -524,12 +735,12 @@ var tooManyLinks = (body, limits) => {
524
735
  } : null;
525
736
  };
526
737
  var spamWords = (text, limits) => {
527
- const plain = visible(text);
738
+ const plain2 = visible(text);
528
739
  const hits = limits.spamWords.filter(
529
740
  (word) => word.trim() !== "" && new RegExp(
530
741
  String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
531
742
  "iu"
532
- ).test(plain)
743
+ ).test(plain2)
533
744
  );
534
745
  return hits.length > 0 ? {
535
746
  check: "spam_words",
@@ -582,17 +793,298 @@ var image = (body) => {
582
793
  text: clip(first)
583
794
  };
584
795
  };
585
- var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
586
- var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
587
- check: "connection_request_too_long",
588
- finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
589
- text: clip(body)
590
- } : null;
796
+ var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
797
+ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
798
+ check: "connection_request_too_long",
799
+ finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
800
+ text: clip(body)
801
+ } : null;
802
+
803
+ // src/insights/copy/audit-variant.ts
804
+ var emailChecks = (step, variant, limits, thread) => {
805
+ const subject = variant.subject?.trim() ?? "";
806
+ const body = variant.body ?? "";
807
+ const key = threadKey(subject);
808
+ const problems = [
809
+ subject === "" ? null : subjectTooLong(subject, limits),
810
+ spamWords(`${subject}
811
+ ${body}`, limits),
812
+ tooManyLinks(body, limits),
813
+ image(body)
814
+ ];
815
+ if (step.index === thread.first && subject === "") {
816
+ problems.push({
817
+ check: "missing_subject",
818
+ finding: "The first email has no subject.",
819
+ text: ""
820
+ });
821
+ }
822
+ if (step.index !== thread.first && key !== "" && thread.subjects !== null && !thread.subjects.has(key)) {
823
+ problems.push({
824
+ check: "subject_breaks_thread",
825
+ finding: "This follow-up has a subject that differs from the first email's, so it starts a new thread instead of continuing the first.",
826
+ text: subject
827
+ });
828
+ }
829
+ return problems;
830
+ };
831
+ var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
832
+ var auditVariant = (step, variant, limits, thread, lead) => {
833
+ const body = variant.body ?? "";
834
+ const whole = `${variant.subject ?? ""}
835
+ ${body}`;
836
+ const problems = [
837
+ malformedVariable(whole),
838
+ bodyTooLong(body, limits),
839
+ allCaps(whole, limits),
840
+ exclamationMarks(whole, limits),
841
+ ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
842
+ ];
843
+ return problems.flatMap(
844
+ (problem) => problem === null ? [] : [
845
+ {
846
+ ...problem,
847
+ action: step.action,
848
+ lead,
849
+ severity: CHECKS[problem.check],
850
+ ...stepAt(step.index),
851
+ variantKey: variant.variantKey
852
+ }
853
+ ]
854
+ );
855
+ };
856
+ var threadOf = (steps, perLead2) => {
857
+ const [first] = steps.toSorted((left, right) => left.index - right.index);
858
+ const variants = first?.variants ?? [];
859
+ return {
860
+ first: first?.index ?? null,
861
+ subjects: first !== void 0 && variants.some((variant) => perLead2(variant)) ? null : new Set(
862
+ variants.flatMap((variant) => {
863
+ const key = threadKey(variant.subject);
864
+ return key === "" ? [] : [key];
865
+ })
866
+ )
867
+ };
868
+ };
869
+
870
+ // src/insights/copy/copy-preview.ts
871
+ import { z as z3 } from "zod";
872
+
873
+ // src/insights/ref.ts
874
+ var refOf = (outbound, id) => {
875
+ const provider = parseRef(id)?.provider;
876
+ return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
877
+ };
878
+
879
+ // src/insights/copy/copy-preview.ts
880
+ var input = z3.object({
881
+ campaign: z3.string().min(1).describe(
882
+ "The campaign's ref, for example `instantly:acme:abc123`, or its name"
883
+ ),
884
+ lead: z3.string().min(1).nullable().default(null).describe(
885
+ "The lead's ref to render the copy for. null picks the lead read with the most variables filled."
886
+ ),
887
+ max_leads: z3.number().int().min(1).max(1e3).default(100).describe(
888
+ "The most leads to read when picking one. Ignored when `lead` is given."
889
+ )
890
+ });
891
+ var LEAD_FIELDS = /* @__PURE__ */ new Set(["company", "custom", "email", "name"]);
892
+ var keysIn = (sequence2) => new Set(
893
+ sequence2.steps.flatMap(
894
+ (step) => step.variants.flatMap(
895
+ (variant) => [variant.subject ?? "", variant.body ?? ""].flatMap(
896
+ (text) => variablesIn(text).map((match) => keyOf(match.name))
897
+ )
898
+ )
899
+ )
900
+ );
901
+ var rankLeads = (leads, keys) => leads.map((lead) => {
902
+ const has = keysWithValue(lead);
903
+ return { lead, score: [...keys].filter((key) => has.has(key)).length };
904
+ }).toSorted((left, right) => right.score - left.score).map(({ lead }) => lead);
905
+ var render = (text, lead, unfilled) => {
906
+ if (text === null) {
907
+ return null;
908
+ }
909
+ if (lead === void 0) {
910
+ for (const match of variablesIn(text)) {
911
+ if (match.fallback === null) {
912
+ unfilled.add(match.name);
913
+ }
914
+ }
915
+ return text;
916
+ }
917
+ const filled2 = fillVariables(text, lead);
918
+ for (const name of filled2.unfilled) {
919
+ unfilled.add(name);
920
+ }
921
+ return filled2.text;
922
+ };
923
+ var plain = (body) => {
924
+ if (body === null) {
925
+ return null;
926
+ }
927
+ return looksLikeHtml(body) ? htmlToText(body) : body.trim();
928
+ };
929
+ var renderVariant = (variant, lead) => {
930
+ const unfilled = /* @__PURE__ */ new Set();
931
+ const subject = render(variant.subject, lead, unfilled);
932
+ const body = render(variant.body, lead, unfilled);
933
+ return { body, subject, unfilled: [...unfilled] };
934
+ };
935
+ var previewStep = (step, lead) => ({
936
+ action: step.action,
937
+ delayDays: step.delayDays,
938
+ ...stepAt(step.index),
939
+ variants: step.variants.map((variant) => {
940
+ const { body, subject, unfilled } = renderVariant(variant, lead);
941
+ return {
942
+ rendered: { body, bodyText: plain(body), subject },
943
+ template: { body: variant.body, subject: variant.subject },
944
+ unfilled,
945
+ variantKey: variant.variantKey
946
+ };
947
+ })
948
+ });
949
+ var copyPreview = defineInsight({
950
+ 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.",
951
+ inputSchema: input,
952
+ key: "copyPreview",
953
+ cost: (values, price) => price.one("sequence.get") + (values.lead === null ? price.upTo(1) * price.list("leads.list", values.max_leads) : price.one("leads.get")),
954
+ scales: "max_leads",
955
+ name: "copy_preview",
956
+ needs: ["sequence", "leads.byCampaign"],
957
+ next: "Use personalization_gaps to find every lead who would get a variable left as written.",
958
+ run: async (context, values) => {
959
+ const sequence2 = context.one(
960
+ await context.outbound.campaign(values.campaign).sequence()
961
+ );
962
+ const keys = keysIn(sequence2);
963
+ let lead;
964
+ if (values.lead !== null) {
965
+ lead = context.one(await context.outbound.lead(values.lead).get());
966
+ } else if (keys.size === 0) {
967
+ context.note("The copy uses no variables, so no lead was read.");
968
+ } else {
969
+ [lead] = rankLeads(
970
+ await leadsOf(context, values.campaign, values.max_leads, "max_leads"),
971
+ keys
972
+ );
973
+ if (lead === void 0) {
974
+ context.note(
975
+ "The campaign has no leads, so the copy is shown as written."
976
+ );
977
+ }
978
+ }
979
+ const masked = maskingOf(context.outbound)?.fields.some(
980
+ (field) => LEAD_FIELDS.has(field)
981
+ );
982
+ if (lead !== void 0 && masked === true) {
983
+ context.note(
984
+ "The redact plugin masks the lead's fields, so the rendered copy shows them masked. Read it without redact to see the values."
985
+ );
986
+ }
987
+ const steps = sequence2.steps.map((step) => previewStep(step, lead));
988
+ const unfilled = new Set(
989
+ steps.flatMap(
990
+ (step) => step.variants.flatMap((variant) => variant.unfilled.map(keyOf))
991
+ )
992
+ );
993
+ const has = lead === void 0 ? null : keysWithValue(lead);
994
+ const answer = {
995
+ campaign: refOf(context.outbound, values.campaign),
996
+ lead: lead === void 0 || has === null ? null : {
997
+ email: lead.email,
998
+ lead: lead.ref,
999
+ linkedinUrl: lead.linkedinUrl,
1000
+ variablesFilled: [...keys].filter((key) => has.has(key)).length
1001
+ },
1002
+ steps,
1003
+ totals: {
1004
+ steps: steps.length,
1005
+ unfilled: unfilled.size,
1006
+ variables: keys.size,
1007
+ variants: steps.reduce((sum, step) => sum + step.variants.length, 0)
1008
+ }
1009
+ };
1010
+ return answer;
1011
+ }
1012
+ });
1013
+
1014
+ // src/insights/copy/audit-samples.ts
1015
+ var PER_LEAD_SHARE = 0.8;
1016
+ var variableShare = (text) => {
1017
+ if (text === null) {
1018
+ return 0;
1019
+ }
1020
+ const plain2 = (looksLikeHtml(text) ? htmlToText(text) : text).replaceAll(
1021
+ /\s/gu,
1022
+ ""
1023
+ );
1024
+ if (plain2 === "") {
1025
+ return 0;
1026
+ }
1027
+ const inVariables = variablesIn(plain2).reduce(
1028
+ (sum, match) => sum + match.raw.length,
1029
+ 0
1030
+ );
1031
+ return inVariables / plain2.length;
1032
+ };
1033
+ var writtenPerLead = (variant) => variableShare(variant.subject) > PER_LEAD_SHARE || variableShare(variant.body) > PER_LEAD_SHARE;
1034
+ var perLeadKeys = (steps) => new Set(
1035
+ steps.flatMap(
1036
+ (step) => step.variants.filter(writtenPerLead).flatMap(
1037
+ (variant) => [variant.subject ?? "", variant.body ?? ""].flatMap(
1038
+ (text) => variablesIn(text).map((match) => keyOf(match.name))
1039
+ )
1040
+ )
1041
+ )
1042
+ );
1043
+ var pickSamples = (leads, keys, samples) => rankLeads(leads, keys).slice(0, samples);
1044
+ var renderSteps = (steps, lead) => steps.map((step) => ({
1045
+ ...step,
1046
+ variants: step.variants.map((variant) => {
1047
+ const { body, subject } = renderVariant(variant, lead);
1048
+ return { ...variant, body, subject };
1049
+ })
1050
+ }));
1051
+ var auditSamples = (steps, leads, limits, isEmail) => {
1052
+ const audited = /* @__PURE__ */ new Set();
1053
+ const findings = [];
1054
+ const refs = [];
1055
+ for (const lead of leads) {
1056
+ const rendered = renderSteps(steps, lead);
1057
+ const thread = isEmail ? threadOf(rendered, writtenPerLead) : null;
1058
+ let any = false;
1059
+ for (const [at, step] of rendered.entries()) {
1060
+ for (const [index, variant] of step.variants.entries()) {
1061
+ const template = steps[at]?.variants[index];
1062
+ if (template !== void 0 && writtenPerLead(template) && !writtenPerLead(variant)) {
1063
+ any = true;
1064
+ audited.add(`${step.index}:${variant.variantKey}`);
1065
+ findings.push(
1066
+ ...auditVariant(step, variant, limits, thread, lead.ref)
1067
+ );
1068
+ }
1069
+ }
1070
+ }
1071
+ if (any) {
1072
+ refs.push(lead.ref);
1073
+ }
1074
+ }
1075
+ const perLead2 = steps.reduce(
1076
+ (sum, step) => sum + step.variants.filter(writtenPerLead).length,
1077
+ 0
1078
+ );
1079
+ return { findings, leads: refs, unaudited: perLead2 - audited.size };
1080
+ };
591
1081
 
592
1082
  // src/insights/copy/copy-audit.ts
593
- var limit = (fallback, description) => z2.number().int().min(0).default(fallback).describe(description);
594
- var input = z2.object({
595
- campaign: z2.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1083
+ var limit = (fallback, description) => z4.number().int().min(0).default(fallback).describe(description);
1084
+ var input2 = z4.object({
1085
+ campaign: z4.string().min(1).describe(
1086
+ "The campaign's ref, for example `instantly:acme:abc123`, or its name"
1087
+ ),
596
1088
  max_body_words: limit(150, "The most words a body may have."),
597
1089
  max_caps_words: limit(
598
1090
  1,
@@ -604,8 +1096,14 @@ var input = z2.object({
604
1096
  ),
605
1097
  max_exclamations: limit(1, "How many exclamation marks a message may have."),
606
1098
  max_links: limit(1, "The most links an email body may have."),
1099
+ max_leads: z4.number().int().min(1).max(1e3).default(100).describe(
1100
+ "The most leads to read when picking the samples. Read only when copy is written per lead."
1101
+ ),
607
1102
  max_subject_chars: limit(60, "The most characters a subject may have."),
608
- spam_words: z2.array(z2.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
1103
+ samples: z4.number().int().min(0).max(20).default(3).describe(
1104
+ "How many leads' rendered copy to audit when a subject or body is mostly variables, such as {{body_1}} filled from a custom field. The leads that fill the most of those variables are used. 0 audits the copy as stored only."
1105
+ ),
1106
+ spam_words: z4.array(z4.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
609
1107
  "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
610
1108
  )
611
1109
  });
@@ -619,69 +1117,7 @@ var EMAIL_ONLY = [
619
1117
  "too_many_links"
620
1118
  ];
621
1119
  var LINKEDIN_ONLY = ["connection_request_too_long"];
622
- var emailChecks = (step, variant, limits, thread) => {
623
- const subject = variant.subject?.trim() ?? "";
624
- const body = variant.body ?? "";
625
- const key = threadKey(subject);
626
- const problems = [
627
- subject === "" ? null : subjectTooLong(subject, limits),
628
- spamWords(`${subject}
629
- ${body}`, limits),
630
- tooManyLinks(body, limits),
631
- image(body)
632
- ];
633
- if (step.index === thread.first && subject === "") {
634
- problems.push({
635
- check: "missing_subject",
636
- finding: "The first email has no subject.",
637
- text: ""
638
- });
639
- }
640
- if (step.index !== thread.first && key !== "" && !thread.subjects.has(key)) {
641
- problems.push({
642
- check: "subject_breaks_thread",
643
- finding: "This follow-up has a subject that differs from the first email's, so it starts a new thread instead of continuing the first.",
644
- text: subject
645
- });
646
- }
647
- return problems;
648
- };
649
- var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
650
- var auditVariant = (step, variant, limits, thread) => {
651
- const body = variant.body ?? "";
652
- const whole = `${variant.subject ?? ""}
653
- ${body}`;
654
- const problems = [
655
- malformedVariable(whole),
656
- bodyTooLong(body, limits),
657
- allCaps(whole, limits),
658
- exclamationMarks(whole, limits),
659
- ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
660
- ];
661
- return problems.flatMap(
662
- (problem) => problem === null ? [] : [
663
- {
664
- ...problem,
665
- action: step.action,
666
- severity: CHECKS[problem.check],
667
- step: step.index,
668
- variantKey: variant.variantKey
669
- }
670
- ]
671
- );
672
- };
673
- var threadOf = (steps) => {
674
- const [first] = steps.toSorted((left, right) => left.index - right.index);
675
- return {
676
- first: first?.index ?? null,
677
- subjects: new Set(
678
- (first?.variants ?? []).flatMap((variant) => {
679
- const key = threadKey(variant.subject);
680
- return key === "" ? [] : [key];
681
- })
682
- )
683
- };
684
- };
1120
+ var cleanOf = (findings, unaudited) => findings === 0 && unaudited === 0;
685
1121
  var CHECK_NAMES = Object.keys(CHECKS);
686
1122
  var countsOf = (findings, isEmail) => CHECK_NAMES.filter(
687
1123
  (check) => !(isEmail ? LINKEDIN_ONLY : EMAIL_ONLY).includes(check)
@@ -692,11 +1128,54 @@ var countsOf = (findings, isEmail) => CHECK_NAMES.filter(
692
1128
  })).toSorted(
693
1129
  (left, right) => right.count - left.count || RANK2[left.severity] - RANK2[right.severity] || left.check.localeCompare(right.check)
694
1130
  );
1131
+ var readSamples = async (context, args, sequence2) => {
1132
+ if (!sequence2.steps.some((step) => step.variants.some(writtenPerLead))) {
1133
+ return { leads: [], reason: null };
1134
+ }
1135
+ if (args.samples === 0) {
1136
+ return { leads: [], reason: "samples is 0" };
1137
+ }
1138
+ if (context.outbound.capabilities["leads.byCampaign"] === false) {
1139
+ return { leads: [], reason: "this tool does not list a campaign's leads" };
1140
+ }
1141
+ const leads = await leadsOf(
1142
+ context,
1143
+ args.campaign,
1144
+ args.max_leads,
1145
+ "max_leads"
1146
+ );
1147
+ return leads.length === 0 ? { leads: [], reason: "the campaign has no leads" } : {
1148
+ leads: pickSamples(leads, perLeadKeys(sequence2.steps), args.samples),
1149
+ reason: null
1150
+ };
1151
+ };
1152
+ var noteSamples = (context, perLead2, samples, audit2) => {
1153
+ if (perLead2 === 0) {
1154
+ return;
1155
+ }
1156
+ const variants = plural(perLead2, "variant");
1157
+ const reason = samples.reason ?? "no lead read has values for their variables";
1158
+ if (audit2.leads.length === 0) {
1159
+ context.note(
1160
+ `${variants} ${perLead2 === 1 ? "is" : "are"} written per lead in variables, and the copy could not be audited as any lead receives it: ${reason}.`
1161
+ );
1162
+ return;
1163
+ }
1164
+ context.note(
1165
+ `${variants} ${perLead2 === 1 ? "is" : "are"} written per lead in variables, so the rendered copy of ${plural(audit2.leads.length, "sample lead")} was audited; each finding names its lead.`
1166
+ );
1167
+ if (audit2.unaudited > 0) {
1168
+ context.note(
1169
+ `${plural(audit2.unaudited, "variant")} written per lead could not be audited: no sample lead has values for ${audit2.unaudited === 1 ? "its" : "their"} variables.`
1170
+ );
1171
+ }
1172
+ };
695
1173
  var copyAudit = defineInsight({
696
- description: "Problems in a campaign's copy before it sends. Checks every step and variant for a long subject, a long body, too many links, spam words, unbalanced or empty {{ }} variables, words in capitals, repeated exclamation marks, an image or tracking pixel, a missing subject on the first email, and a follow-up whose subject breaks the thread; a LinkedIn campaign skips the email-only checks and flags a connection request over the character limit. Returns each finding with a severity and the text that triggered it, and a count per check. Costs 2 requests. Fixed rules only, no model. A variant whose body the vendor does not return is counted, not judged.",
697
- inputSchema: input,
1174
+ 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. When a subject or body is mostly variables, such as {{body_1}} filled from a custom field, that variant is audited as sample leads receive it, rendered as copy_preview renders it, and each such finding names its lead; when a variant cannot be rendered for any sample lead, clean is false and variantsNotAudited counts it, never a bare clean true. Costs 2 requests, plus one per page of leads read when copy is written per lead. Fixed rules only, no model. A variant whose body the vendor does not return is counted, not judged.",
1175
+ inputSchema: input2,
698
1176
  key: "copyAudit",
699
- cost: (_input, price) => price.one("campaigns.get") + price.one("sequence.get"),
1177
+ cost: (values, price) => price.one("campaigns.get") + price.one("sequence.get") + (values.samples === 0 ? 0 : price.upTo(1) * price.list("leads.list", values.max_leads)),
1178
+ scales: "max_leads",
700
1179
  name: "copy_audit",
701
1180
  needs: ["sequence"],
702
1181
  next: "Use step_funnel to see whether the steps with findings are also the ones with few replies.",
@@ -714,14 +1193,27 @@ var copyAudit = defineInsight({
714
1193
  maxSubjectChars: args.max_subject_chars,
715
1194
  spamWords: args.spam_words
716
1195
  };
717
- const thread = isEmail ? threadOf(sequence2.steps) : null;
1196
+ const thread = isEmail ? threadOf(sequence2.steps, writtenPerLead) : null;
718
1197
  const variants = sequence2.steps.flatMap(
719
1198
  (step) => step.variants.map((variant) => ({ step, variant }))
720
1199
  );
721
- const findings = variants.flatMap(
722
- ({ step, variant }) => auditVariant(step, variant, limits, thread)
723
- ).toSorted(
724
- (left, right) => RANK2[left.severity] - RANK2[right.severity] || left.step - right.step || left.variantKey.localeCompare(right.variantKey) || left.check.localeCompare(right.check)
1200
+ const perLead2 = variants.filter(
1201
+ ({ variant }) => writtenPerLead(variant)
1202
+ ).length;
1203
+ const samples = await readSamples(context, args, sequence2);
1204
+ const sampled = auditSamples(
1205
+ sequence2.steps,
1206
+ samples.leads,
1207
+ limits,
1208
+ isEmail
1209
+ );
1210
+ const findings = [
1211
+ ...variants.flatMap(
1212
+ ({ step, variant }) => writtenPerLead(variant) ? [] : auditVariant(step, variant, limits, thread, null)
1213
+ ),
1214
+ ...sampled.findings
1215
+ ].toSorted(
1216
+ (left, right) => RANK2[left.severity] - RANK2[right.severity] || left.stepIndex - right.stepIndex || left.variantKey.localeCompare(right.variantKey) || left.check.localeCompare(right.check) || (left.lead ?? "").localeCompare(right.lead ?? "")
725
1217
  );
726
1218
  const withoutBody = variants.filter(
727
1219
  ({ variant }) => variant.body === null
@@ -731,6 +1223,7 @@ var copyAudit = defineInsight({
731
1223
  withoutBody === 1 ? "1 variant has no body in the vendor's answer, so its body checks were skipped." : `${withoutBody} variants have no body in the vendor's answer, so their body checks were skipped.`
732
1224
  );
733
1225
  }
1226
+ noteSamples(context, perLead2, samples, sampled);
734
1227
  const severity = (level) => findings.filter((finding) => finding.severity === level).length;
735
1228
  const audit2 = {
736
1229
  byCheck: countsOf(findings, isEmail),
@@ -742,78 +1235,21 @@ var copyAudit = defineInsight({
742
1235
  campaign: campaign.ref,
743
1236
  campaignName: campaign.name,
744
1237
  channel: campaign.channel,
745
- clean: findings.length === 0,
1238
+ clean: cleanOf(findings.length, sampled.unaudited),
746
1239
  findings,
747
1240
  stepsChecked: sequence2.steps.length,
748
1241
  variantsChecked: variants.length,
749
- variantsWithoutBody: withoutBody
1242
+ leadsAudited: sampled.leads,
1243
+ variantsWithoutBody: withoutBody,
1244
+ variantsNotAudited: sampled.unaudited,
1245
+ variantsWrittenPerLead: perLead2
750
1246
  };
751
1247
  return audit2;
752
1248
  }
753
1249
  });
754
1250
 
755
1251
  // src/insights/copy/copy-reuse.ts
756
- import { z as z4 } from "zod";
757
-
758
- // src/insights/capped.ts
759
- var readCapped = async (context, open, cap, room = cap.max) => {
760
- if (room >= 1) {
761
- const walk = open(room);
762
- const items = await context.all(walk, cap);
763
- return { capped: walk.truncated, items };
764
- }
765
- const probe = open(1);
766
- const left = await context.all(probe, cap);
767
- if (left.length > 0 && !probe.truncated) {
768
- context.partial(capNote(cap));
769
- }
770
- return { capped: left.length > 0, items: [] };
771
- };
772
- var campaignsReadOf = (read) => ({
773
- campaignsRead: read.items.length,
774
- moreCampaignsExist: read.capped
775
- });
776
- var readCampaignsIn = async (context, statuses, max, input27 = "max_campaigns") => {
777
- const { campaigns } = context.outbound;
778
- const wanted = [...new Set(statuses)];
779
- const cap = { input: input27, max, what: "campaigns" };
780
- if (context.outbound.capabilities["campaigns.status"] === false) {
781
- const every = await readCapped(
782
- context,
783
- (room) => campaigns.listAll({ max: room }),
784
- cap
785
- );
786
- const items = every.items.filter(
787
- (campaign) => wanted.includes(campaign.status)
788
- );
789
- context.campaignsFound(items.length);
790
- return { capped: every.capped, items };
791
- }
792
- const found = [];
793
- let capped2 = false;
794
- for (const status of wanted) {
795
- const listed = await readCapped(
796
- context,
797
- (room) => campaigns.listAll({ max: room, status }),
798
- cap,
799
- max - found.length
800
- );
801
- found.push(...listed.items);
802
- capped2 ||= listed.capped;
803
- }
804
- context.campaignsFound(found.length);
805
- return { capped: capped2, items: found };
806
- };
807
-
808
- // src/insights/fields.ts
809
- import { z as z3 } from "zod";
810
- var rangeFields = {
811
- from: z3.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
812
- to: z3.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
813
- };
814
- var statusesInput = (fallback) => z3.array(campaignStatusSchema).min(1).default([...fallback]).describe(
815
- "Only campaigns in one of these states are read: active, paused, completed, draft, archived or unknown"
816
- );
1252
+ import { z as z5 } from "zod";
817
1253
 
818
1254
  // src/insights/stats.ts
819
1255
  var PLACES = 1e4;
@@ -946,7 +1382,7 @@ var BASIS_WORDS = {
946
1382
  delivered: "per message delivered",
947
1383
  sent: "per message sent"
948
1384
  };
949
- var basesInWords = (named3) => named3.map(
1385
+ var basesInWords = (named4) => named4.map(
950
1386
  ({ basis, name }) => `${name} ${basis === null ? "with no base" : BASIS_WORDS[basis]}`
951
1387
  ).join(", ");
952
1388
  var measure = (count2, base) => {
@@ -955,11 +1391,9 @@ var measure = (count2, base) => {
955
1391
  basis: base.basis,
956
1392
  count: count2,
957
1393
  high: interval?.high ?? null,
958
- interval,
959
1394
  low: interval?.low ?? null,
960
1395
  of: base.trials,
961
- rate: rate(count2, base.trials),
962
- trials: base.trials
1396
+ rate: rate(count2, base.trials)
963
1397
  };
964
1398
  };
965
1399
  var NO_RATE = {
@@ -978,7 +1412,7 @@ var replyRateOf = (measured2) => measured2 === null ? NO_RATE : {
978
1412
  of: measured2.of,
979
1413
  rate: measured2.rate
980
1414
  };
981
- var sumRows = (rows) => sumCounts(rows);
1415
+ var sumRows = (rows) => sumMeasured(rows);
982
1416
  var groupBy = (values, keyOf2) => {
983
1417
  const groups = /* @__PURE__ */ new Map();
984
1418
  for (const value of values) {
@@ -1021,7 +1455,7 @@ var pooled = (counts, baseOf) => {
1021
1455
  return one === null || one.rate === null ? [] : [one];
1022
1456
  });
1023
1457
  const replies2 = total(measured2.map((each) => each.count));
1024
- const trials = total(measured2.map((each) => each.trials));
1458
+ const trials = total(measured2.map((each) => each.of));
1025
1459
  const bases = new Set(measured2.map((each) => each.basis));
1026
1460
  const [basis = null] = bases.size === 1 ? bases : [];
1027
1461
  return {
@@ -1058,11 +1492,11 @@ var sharedBaseOf = (context, counted2) => {
1058
1492
  };
1059
1493
 
1060
1494
  // src/insights/copy/copy-reuse.ts
1061
- var input2 = z4.object({
1062
- max_campaigns: z4.number().int().min(1).max(200).default(20).describe(
1495
+ var input3 = z5.object({
1496
+ max_campaigns: z5.number().int().min(1).max(200).default(20).describe(
1063
1497
  "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
1064
1498
  ),
1065
- min_sent: z4.number().int().min(1).default(100).describe(
1499
+ min_sent: z5.number().int().min(1).default(100).describe(
1066
1500
  "The smallest base (sends, or leads contacted when the vendor counts those) a campaign needs to count in the spread, and a piece of copy needs to be named the best."
1067
1501
  ),
1068
1502
  statuses: statusesInput(["active", "paused", "completed"])
@@ -1105,10 +1539,7 @@ var useOf = (placements, baseOf) => {
1105
1539
  provider: first.campaign.provider,
1106
1540
  rates: { replyRate: replyRateOf(sum) },
1107
1541
  replies: sum.count,
1108
- replyRate: sum.rate,
1109
- replyRateInterval: sum.interval,
1110
- sent: sum.sent,
1111
- trials: sum.trials
1542
+ sent: sum.sent
1112
1543
  }
1113
1544
  ];
1114
1545
  };
@@ -1129,18 +1560,15 @@ var pieceOf = (placements, uses, baseOf) => {
1129
1560
  contentHash: first.contentHash,
1130
1561
  rates: { replyRate: replyRateOf(sum) },
1131
1562
  replies: sum.count,
1132
- replyRate: sum.rate,
1133
- replyRateInterval: sum.interval,
1134
1563
  sent: sum.sent,
1135
- subject: first.subject,
1136
- trials: sum.trials
1564
+ subject: first.subject
1137
1565
  }
1138
1566
  ];
1139
1567
  };
1140
- var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
1568
+ var byRate = ({ rates: { replyRate: left } }, { rates: { replyRate: right } }) => (right.rate ?? -1) - (left.rate ?? -1) || (right.of ?? 0) - (left.of ?? 0);
1141
1569
  var spreadOf = (uses, minSent, comparable) => {
1142
1570
  const judged = uses.filter(
1143
- (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
1571
+ (use) => use.rates.replyRate.rate !== null && (use.rates.replyRate.of ?? 0) >= minSent
1144
1572
  );
1145
1573
  const [best] = judged;
1146
1574
  const worst = judged.at(-1);
@@ -1155,14 +1583,16 @@ var spreadOf = (uses, minSent, comparable) => {
1155
1583
  };
1156
1584
  }
1157
1585
  const test = compareRates(
1158
- { successes: best.replies, trials: best.trials },
1159
- { successes: worst.replies, trials: worst.trials }
1586
+ { successes: best.replies, trials: best.rates.replyRate.of },
1587
+ { successes: worst.replies, trials: worst.rates.replyRate.of }
1160
1588
  );
1161
1589
  const real = test?.significant ?? false;
1162
1590
  return {
1163
1591
  best: best.campaign,
1164
- finding: real ? `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${percent(best.replyRate)} in ${best.campaignName} and ${percent(worst.replyRate)} in ${worst.campaignName}; a gap this size could be chance.`,
1165
- spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
1592
+ 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.`,
1593
+ spread: round(
1594
+ (best.rates.replyRate.rate ?? 0) - (worst.rates.replyRate.rate ?? 0)
1595
+ ),
1166
1596
  spreadIsReal: real,
1167
1597
  spreadPValue: test?.pValue ?? null,
1168
1598
  worst: worst.campaign
@@ -1185,7 +1615,7 @@ var readPlacements = async (context, campaigns) => {
1185
1615
  };
1186
1616
  var copyReuse = defineInsight({
1187
1617
  description: "How the same piece of copy performs in different campaigns. Reads each campaign's sequence and step stats, matches variants by the hash of their subject and body, and returns every piece of copy used in two or more campaigns with its totals, its reply rate per campaign and the spread between its best and worst campaign, plus the copy with the highest pooled reply rate. Use it to tell a copy problem from an audience problem. Every rate is divided by the same base, leads contacted when every campaign counts them and messages sent otherwise; campaigns with no base in common are listed but not compared. Costs 2 requests per campaign plus the campaign listing. A null count means the vendor does not report it for that variant; it is never 0.",
1188
- inputSchema: input2,
1618
+ inputSchema: input3,
1189
1619
  key: "copyReuse",
1190
1620
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("sequence.get") + price.one("stats")),
1191
1621
  scales: "max_campaigns",
@@ -1193,8 +1623,8 @@ var copyReuse = defineInsight({
1193
1623
  needs: ["sequence", "stats.byStep"],
1194
1624
  next: "Use step_funnel on the campaign where the copy does worst, or variant_test where the copy runs against another variant.",
1195
1625
  run: async (context, { max_campaigns, min_sent, statuses }) => {
1196
- const listed = await readCampaignsIn(context, statuses, max_campaigns);
1197
- const campaigns = listed.items;
1626
+ const listed2 = await readCampaignsIn(context, statuses, max_campaigns);
1627
+ const campaigns = listed2.items;
1198
1628
  const placements = await readPlacements(context, campaigns);
1199
1629
  const without = placements.filter((each) => each.counts === null).length;
1200
1630
  if (without > 0) {
@@ -1220,13 +1650,13 @@ var copyReuse = defineInsight({
1220
1650
  (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
1221
1651
  );
1222
1652
  const [bestCopy] = pieces.flatMap(
1223
- ({ piece }) => comparable && piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
1653
+ ({ piece }) => comparable && piece.rates.replyRate.rate !== null && (piece.rates.replyRate.of ?? 0) >= min_sent ? [piece] : []
1224
1654
  ).toSorted(byRate);
1225
1655
  const result = {
1226
1656
  basis,
1227
1657
  bestCopy: bestCopy ?? null,
1228
1658
  campaignsRead: campaigns.length,
1229
- moreCampaignsExist: listed.capped,
1659
+ moreCampaignsExist: listed2.capped,
1230
1660
  piecesOfCopy: pieces.length,
1231
1661
  reused,
1232
1662
  variantsWithoutStats: without
@@ -1236,35 +1666,32 @@ var copyReuse = defineInsight({
1236
1666
  });
1237
1667
 
1238
1668
  // src/insights/copy/reply-timing.ts
1239
- import { z as z5 } from "zod";
1669
+ import { z as z6 } from "zod";
1240
1670
 
1241
1671
  // src/insights/campaign.ts
1242
1672
  var confirmCampaign = async (context, campaign) => {
1243
1673
  context.one(await context.outbound.campaigns.get(campaign));
1244
1674
  };
1245
1675
 
1246
- // src/insights/ref.ts
1247
- var refOf = (outbound, id) => {
1248
- const provider = parseRef(id)?.provider;
1249
- return provider === outbound.provider || provider !== void 0 && outbound.provider === "combined" ? id : makeRef(outbound.provider, outbound.workspaceId, id);
1250
- };
1251
-
1252
1676
  // src/insights/copy/reply-timing.ts
1253
1677
  var DAY_MS = 864e5;
1254
1678
  var MAX_UNPAIRED_SHARE = 0.25;
1255
1679
  var HOUR_MS = 36e5;
1256
1680
  var MINUTE_MS = 6e4;
1257
- var input3 = z5.object({
1258
- campaign: z5.string().min(1).nullable().default(null).describe(
1681
+ var input4 = z6.object({
1682
+ campaign: z6.string().min(1).nullable().default(null).describe(
1259
1683
  "A campaign's ref to look at one campaign; an unknown one is refused with NotFound. null looks at every campaign."
1260
1684
  ),
1261
- max_messages: z5.number().int().min(1).max(5e4).default(2e3).describe(
1685
+ include_auto: z6.boolean().default(false).describe(
1686
+ "Count replies flagged automatic (isAuto true), such as out-of-office messages and autoresponders. false leaves them out of every figure and counts them in counts.autoReplies."
1687
+ ),
1688
+ max_messages: z6.number().int().min(1).max(5e4).default(2e3).describe(
1262
1689
  "The most messages to read, sent and received together. A page of messages costs 1 request."
1263
1690
  ),
1264
- since: z5.iso.datetime({ offset: true }).nullable().default(null).describe(
1691
+ since: z6.iso.datetime({ offset: true }).nullable().default(null).describe(
1265
1692
  "Only messages from this time on, ISO 8601. null means 30 days before now."
1266
1693
  ),
1267
- timezone_offset_minutes: z5.number().int().min(-720).max(840).default(0).describe(
1694
+ timezone_offset_minutes: z6.number().int().min(-720).max(840).default(0).describe(
1268
1695
  "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
1269
1696
  )
1270
1697
  });
@@ -1369,22 +1796,29 @@ var readMessages = async (context, campaign, since, max) => {
1369
1796
  (message) => message.sentAt === null || message.sentAt >= since
1370
1797
  );
1371
1798
  };
1372
- var noteGaps = (context, unpaired, received) => {
1373
- const share2 = rate(unpaired, received);
1799
+ var noteGaps = (context, unpaired, received, includeAuto) => {
1800
+ const share2 = rate(unpaired, received.length);
1374
1801
  if (share2 !== null && share2 > MAX_UNPAIRED_SHARE) {
1375
1802
  context.partial(
1376
- `${unpaired} of ${received} replies (${percent(share2)}) were not paired with a send, often because the send went out before since. Time to reply leaves them out, so it may look faster than it is; set since earlier to pair more.`
1803
+ `${unpaired} of ${received.length} replies (${percent(share2)}) were not paired with a send, often because the send went out before since. Time to reply leaves them out, so it may look faster than it is; set since earlier to pair more.`
1377
1804
  );
1378
1805
  }
1379
- if (received > 0) {
1806
+ const unflagged = received.filter(
1807
+ (message) => message.isAuto === null || message.isAuto === void 0
1808
+ ).length;
1809
+ if (includeAuto && received.length > 0) {
1810
+ context.note(
1811
+ "Automatic replies such as out-of-office messages are counted as replies (include_auto). A fast median can be auto-replies."
1812
+ );
1813
+ } else if (unflagged > 0) {
1380
1814
  context.note(
1381
- "Automatic replies such as out-of-office messages are counted as replies: messages carry no auto flag, so they cannot be told apart. A fast median can be auto-replies."
1815
+ `${unflagged} of ${received.length} replies carry no auto flag, so an automatic one among them is counted as a reply. A fast median can be auto-replies.`
1382
1816
  );
1383
1817
  }
1384
1818
  };
1385
1819
  var replyTiming = defineInsight({
1386
- description: "How fast people reply and when. Pairs each received message with the last message sent before it in the same thread (or to the same lead) and returns the median, 75th and 90th percentile of hours to reply, the share of replies within 1, 24 and 72 hours, replies by weekday and by hour of day, the weekday and hour of the sends that drew replies, and how many replies could not be paired; over a quarter unpaired, the answer is marked partial, since a reply to a send from before `since` cannot pair and those are the slow ones. Use it to choose follow-up delays and sending hours. Costs 1 request per page of messages, up to max_messages. A null figure means no reply could be paired; auto-replies are not separated, because messages carry no auto flag.",
1387
- inputSchema: input3,
1820
+ 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. A received message flagged automatic (isAuto true: the vendor's flag, or a fixed rule on the sender, subject, canned phrases or a reply within a minute of the send) is left out and counted in counts.autoReplies unless include_auto is true; a message with no flag is counted as a reply.",
1821
+ inputSchema: input4,
1388
1822
  key: "replyTiming",
1389
1823
  cost: (values, price) => price.list("messages.list", values.max_messages) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")),
1390
1824
  scales: "max_messages",
@@ -1393,24 +1827,28 @@ var replyTiming = defineInsight({
1393
1827
  next: "Use step_funnel to see which step the replies answer, then set follow-up delays near the median time to reply.",
1394
1828
  run: async (context, args) => {
1395
1829
  const since = args.since === null ? new Date(context.now - 30 * DAY_MS).toISOString() : new Date(args.since).toISOString();
1396
- const messages = await readMessages(
1830
+ const read = await readMessages(
1397
1831
  context,
1398
1832
  args.campaign,
1399
1833
  since,
1400
1834
  args.max_messages
1401
1835
  );
1836
+ const messages = args.include_auto ? read : read.filter(
1837
+ (message) => message.direction === "out" || message.isAuto !== true
1838
+ );
1402
1839
  const paired = pair(messages);
1403
1840
  const hours = paired.pairs.map((each) => (each.at - each.sentAt) / HOUR_MS);
1404
- const within = (limit3) => rate(hours.filter((value) => value <= limit3).length, hours.length);
1841
+ const within = (limit2) => rate(hours.filter((value) => value <= limit2).length, hours.length);
1405
1842
  const received = messages.filter((message) => message.direction === "in");
1406
1843
  const untimed = received.length - paired.replyTimes.length;
1407
1844
  const unpaired = paired.unpaired + untimed;
1408
- noteGaps(context, unpaired, received.length);
1845
+ noteGaps(context, unpaired, received, args.include_auto);
1409
1846
  const timing = {
1410
1847
  campaign: args.campaign === null ? null : refOf(context.outbound, args.campaign),
1411
1848
  counts: {
1849
+ autoReplies: read.length - messages.length,
1412
1850
  followOnReplies: paired.followOn,
1413
- messagesRead: messages.length,
1851
+ messagesRead: read.length,
1414
1852
  paired: paired.pairs.length,
1415
1853
  received: received.length,
1416
1854
  sent: messages.length - received.length,
@@ -1439,12 +1877,15 @@ var replyTiming = defineInsight({
1439
1877
  });
1440
1878
 
1441
1879
  // src/insights/copy/step-funnel.ts
1442
- import { z as z6 } from "zod";
1443
- var input4 = z6.object({
1444
- campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1880
+ import { z as z7 } from "zod";
1881
+ var MIN_REPLIES = 5;
1882
+ var input5 = z7.object({
1883
+ campaign: z7.string().min(1).describe(
1884
+ "The campaign's ref, for example `instantly:acme:abc123`, or its name"
1885
+ ),
1445
1886
  ...rangeFields,
1446
- min_reply_rate: z6.number().min(0).max(1).default(0).describe(
1447
- "A step earns its place when the low end of its reply rate interval is above this. 0 asks only that the rate is reliably above zero."
1887
+ min_reply_rate: z7.number().min(0).max(1).default(0).describe(
1888
+ `A step earns its place when the low end of its reply rate interval is above this and it has at least ${MIN_REPLIES} replies. 0 asks only that the rate is reliably above zero.`
1448
1889
  )
1449
1890
  });
1450
1891
  var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, counts]) => {
@@ -1453,34 +1894,37 @@ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, c
1453
1894
  contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
1454
1895
  rates: { replyRate: replyRateOf(measured2) },
1455
1896
  replies: counts.replied,
1456
- replyRate: measured2.rate,
1457
- replyRateInterval: measured2.interval,
1458
1897
  sent: counts.sent,
1459
1898
  variantKey
1460
1899
  };
1461
1900
  });
1901
+ var earnsPlaceOf = (low, counts, minReplyRate) => {
1902
+ if (low === null) {
1903
+ return null;
1904
+ }
1905
+ if (low <= minReplyRate) {
1906
+ return false;
1907
+ }
1908
+ return (counts?.replied ?? 0) >= MIN_REPLIES ? true : null;
1909
+ };
1462
1910
  var draftOf = (index, step, stats, minReplyRate) => {
1463
1911
  const counts = stats?.total ?? null;
1464
1912
  const measured2 = counts === null ? null : measure(counts.replied, perLead(counts));
1465
- const interval = measured2?.interval ?? null;
1466
1913
  return {
1467
1914
  action: step?.action ?? null,
1468
1915
  delayDays: step?.delayDays ?? null,
1469
- earnsPlace: interval === null ? null : interval.low > minReplyRate,
1916
+ earnsPlace: earnsPlaceOf(measured2?.low ?? null, counts, minReplyRate),
1470
1917
  inSequence: step !== void 0,
1471
1918
  parent: step === void 0 ? null : step.parentIndex,
1472
1919
  rates: { replyRate: replyRateOf(measured2) },
1473
1920
  replies: counts?.replied ?? null,
1474
- replyRate: measured2?.rate ?? null,
1475
- replyRateBasis: measured2?.basis ?? null,
1476
- replyRateInterval: interval,
1477
1921
  sent: counts?.sent ?? null,
1478
- step: index,
1922
+ ...stepAt(index),
1479
1923
  variants: variantsOf(stats, step)
1480
1924
  };
1481
1925
  };
1482
1926
  var finish = (drafts, allReplies) => drafts.map(({ parent, ...draft }, position) => {
1483
- const before = draft.inSequence ? drafts.find((other) => other.step === parent) : drafts[position - 1];
1927
+ const before = draft.inSequence ? drafts.find((other) => other.stepIndex === parent) : drafts[position - 1];
1484
1928
  const drop = before === void 0 || before.sent === null || draft.sent === null ? null : before.sent - draft.sent;
1485
1929
  return {
1486
1930
  ...draft,
@@ -1498,6 +1942,7 @@ var topOf2 = (steps) => {
1498
1942
  }
1499
1943
  return top;
1500
1944
  };
1945
+ var sentence = (text) => `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
1501
1946
  var describe = (steps, top, last, allReplies) => {
1502
1947
  if (steps.every((step) => step.sent === null)) {
1503
1948
  return "No step has stats yet, so there is nothing to compare.";
@@ -1505,22 +1950,26 @@ var describe = (steps, top, last, allReplies) => {
1505
1950
  if (top === null) {
1506
1951
  return "No step has a reply in this range.";
1507
1952
  }
1508
- const lead = `Step ${top.step + 1} brings the most replies: ${top.replies} of ${allReplies}.`;
1953
+ const length = steps.filter((step) => step.inSequence).length || null;
1954
+ const lead = `${sentence(stepLabel(top.stepIndex, length))} brings the most replies: ${top.replies} of ${allReplies}.`;
1509
1955
  if (last === null) {
1510
- return `${lead} No step's reply rate is reliably above the bar yet.`;
1956
+ const tooFew = steps.some(
1957
+ (step) => step.earnsPlace === null && step.rates.replyRate.low !== null
1958
+ );
1959
+ return tooFew ? `${lead} Too few replies to tell whether any step's reply rate is reliably above the bar: a step needs at least ${MIN_REPLIES}.` : `${lead} No step's reply rate is reliably above the bar yet.`;
1511
1960
  }
1512
1961
  const later = steps.filter(
1513
- (step) => step.step > last.step && step.sent !== null
1962
+ (step) => step.stepIndex > last.stepIndex && step.sent !== null
1514
1963
  );
1515
- return later.length === 0 ? `${lead} Every step up to step ${last.step + 1} still earns its place.` : `${lead} Step ${last.step + 1} is the last whose reply rate is reliably above the bar; the ${later.length === 1 ? "1 later step" : `${later.length} later steps`} sent ${total(later.map((step) => step.sent))} messages for ${total(later.map((step) => step.replies)) ?? "an unknown number of"} replies.`;
1964
+ return later.length === 0 ? `${lead} Every step up to ${stepLabel(last.stepIndex, length)} still earns its place.` : `${lead} ${sentence(stepLabel(last.stepIndex, length))} is the last whose reply rate is reliably above the bar; the ${later.length === 1 ? "1 later step" : `${later.length} later steps`} sent ${total(later.map((step) => step.sent))} messages for ${total(later.map((step) => step.replies)) ?? "an unknown number of"} replies.`;
1516
1965
  };
1517
1966
  var unattributedOf = (rows) => {
1518
1967
  const counts = sumRows(rows);
1519
1968
  return { replies: counts.replied, rows: rows.length, sent: counts.sent };
1520
1969
  };
1521
1970
  var stepFunnel = defineInsight({
1522
- description: "Where a campaign's replies come from: one row per sequence step with its action, delay, sends, replies, reply rate with a 95% interval, its share of all replies and how far sends fell from the step before, plus rows per variant when the vendor splits them. Names the step with the most replies and the last step that still earns its place. Use it to decide whether to cut or rewrite follow-ups. Costs 2 requests. A null count means the vendor does not report it; it is never 0.",
1523
- inputSchema: input4,
1971
+ 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. Each step has stepIndex (counted from 0) and stepNumber (counted from 1, as a person counts); step is a deprecated copy of stepIndex. Names the step with the most replies and the last step that still earns its place; a step needs at least 5 replies to earn it. 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.",
1972
+ inputSchema: input5,
1524
1973
  key: "stepFunnel",
1525
1974
  cost: (_input, price) => price.one("sequence.get") + price.one("stats"),
1526
1975
  name: "step_funnel",
@@ -1563,9 +2012,13 @@ var stepFunnel = defineInsight({
1563
2012
  const funnel = {
1564
2013
  campaign: refOf(context.outbound, campaign),
1565
2014
  finding: describe(steps, top, last, allReplies),
1566
- lastStepEarningPlace: last?.step ?? null,
2015
+ lastStepEarningPlace: last?.stepIndex ?? null,
2016
+ lastStepEarningPlaceIndex: last?.stepIndex ?? null,
2017
+ lastStepEarningPlaceNumber: last?.stepNumber ?? null,
1567
2018
  steps,
1568
- topStep: top?.step ?? null,
2019
+ topStep: top?.stepIndex ?? null,
2020
+ topStepIndex: top?.stepIndex ?? null,
2021
+ topStepNumber: top?.stepNumber ?? null,
1569
2022
  totals: {
1570
2023
  replies: allReplies,
1571
2024
  sent: total([...drafts.map((draft) => draft.sent), unattributed.sent])
@@ -1577,18 +2030,20 @@ var stepFunnel = defineInsight({
1577
2030
  });
1578
2031
 
1579
2032
  // src/insights/copy/variant-test.ts
1580
- import { z as z7 } from "zod";
2033
+ import { z as z8 } from "zod";
1581
2034
  var METRICS = ["replied", "positive", "opened", "clicked"];
1582
- var input5 = z7.object({
1583
- alpha: z7.number().gt(0).max(0.5).default(0.05).describe(
2035
+ var input6 = z8.object({
2036
+ alpha: z8.number().gt(0).max(0.5).default(0.05).describe(
1584
2037
  "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1585
2038
  ),
1586
- campaign: z7.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
2039
+ campaign: z8.string().min(1).describe(
2040
+ "The campaign's ref, for example `instantly:acme:abc123`, or its name"
2041
+ ),
1587
2042
  ...rangeFields,
1588
- metric: z7.enum(METRICS).default("replied").describe(
2043
+ metric: z8.enum(METRICS).default("replied").describe(
1589
2044
  "What a variant is judged on. Replies and positive replies are divided by leads contacted (or sends); opens and clicks by messages delivered (or sends)."
1590
2045
  ),
1591
- min_sent: z7.number().int().min(1).default(100).describe(
2046
+ min_sent: z8.number().int().min(1).default(100).describe(
1592
2047
  "A variant with a smaller base than this (sends, or leads contacted when the vendor counts those) is not compared."
1593
2048
  )
1594
2049
  });
@@ -1606,7 +2061,7 @@ var candidateOf = (variantKey, counts, base, minSent, metric) => {
1606
2061
  const measured2 = measure(counts[metric], base);
1607
2062
  return {
1608
2063
  ...measured2,
1609
- enoughData: measured2.rate !== null && measured2.trials !== null && measured2.trials >= minSent,
2064
+ enoughData: measured2.rate !== null && measured2.of !== null && measured2.of >= minSent,
1610
2065
  sent: counts.sent,
1611
2066
  variantKey
1612
2067
  };
@@ -1616,7 +2071,7 @@ var shortfall = (candidates, minSent) => {
1616
2071
  return null;
1617
2072
  }
1618
2073
  return candidates.reduce(
1619
- (sum, each) => sum + Math.max(0, minSent - (each.trials ?? 0)),
2074
+ (sum, each) => sum + Math.max(0, minSent - (each.of ?? 0)),
1620
2075
  0
1621
2076
  );
1622
2077
  };
@@ -1634,7 +2089,7 @@ var tooLittle = (step, candidates, settings, comparable) => ({
1634
2089
  moreSendsNeeded: comparable ? shortfall(candidates, settings.minSent) : null,
1635
2090
  pValue: null,
1636
2091
  reason: reasonFor(candidates, settings, comparable),
1637
- step,
2092
+ ...stepAt(step),
1638
2093
  variants: candidates.map((each) => ({ ...each, pValueVsLeader: null })),
1639
2094
  verdict: "too_little_data"
1640
2095
  });
@@ -1643,7 +2098,7 @@ var testStep = (step, candidates, settings, comparable) => {
1643
2098
  return tooLittle(step, candidates, settings, false);
1644
2099
  }
1645
2100
  const ready = candidates.filter((each) => each.enoughData).toSorted(
1646
- (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
2101
+ (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.of ?? 0) - (left.of ?? 0)
1647
2102
  );
1648
2103
  const [leader, rival] = ready;
1649
2104
  if (leader === void 0 || rival === void 0) {
@@ -1653,8 +2108,8 @@ var testStep = (step, candidates, settings, comparable) => {
1653
2108
  ready.slice(1).map((other) => [
1654
2109
  other.variantKey,
1655
2110
  compareRates(
1656
- { successes: leader.count, trials: leader.trials },
1657
- { successes: other.count, trials: other.trials },
2111
+ { successes: leader.count, trials: leader.of },
2112
+ { successes: other.count, trials: other.of },
1658
2113
  settings.alpha
1659
2114
  )
1660
2115
  ])
@@ -1673,7 +2128,7 @@ var testStep = (step, candidates, settings, comparable) => {
1673
2128
  moreSendsNeeded: null,
1674
2129
  pValue: closest?.pValue ?? null,
1675
2130
  reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1676
- step,
2131
+ ...stepAt(step),
1677
2132
  variants,
1678
2133
  verdict: "winner"
1679
2134
  };
@@ -1682,12 +2137,12 @@ var testStep = (step, candidates, settings, comparable) => {
1682
2137
  leader: leader.variantKey,
1683
2138
  moreSendsNeeded: closest === null ? null : sendsToSignificance(
1684
2139
  closest.z,
1685
- (leader.trials ?? 0) + (rival.trials ?? 0),
2140
+ (leader.of ?? 0) + (rival.of ?? 0),
1686
2141
  settings.alpha
1687
2142
  ),
1688
2143
  pValue: closest?.pValue ?? null,
1689
2144
  reason: `Variant ${leader.variantKey} (${percent(leader.rate)}) leads variant ${rival.variantKey} (${percent(rival.rate)}), but a gap this size could be chance.${aside}`,
1690
- step,
2145
+ ...stepAt(step),
1691
2146
  variants,
1692
2147
  verdict: "no_difference_yet"
1693
2148
  };
@@ -1727,7 +2182,7 @@ var variantsReported = (context, rows) => {
1727
2182
  var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1728
2183
  var variantTest = defineInsight({
1729
2184
  description: "Whether a campaign's A/B winner is real. For each step with two or more variants, compares every variant with the leader by a two-proportion test and returns the variants with rates and 95% intervals, the leader, and a verdict: winner, no_difference_yet or too_little_data, with the p-value and a rough number of sends still needed when there is no verdict. Use it before pausing a variant. Costs 1 request. A null count or rate means the vendor does not report it; an empty list means the vendor does not split step stats by variant (variantStatsReported false) or reported no step stats in the date range (null). Variants of a step are divided by the same base; variants with no base in common are not compared.",
1730
- inputSchema: input5,
2185
+ inputSchema: input6,
1731
2186
  key: "variantTest",
1732
2187
  cost: (_input, price) => price.one("stats"),
1733
2188
  name: "variant_test",
@@ -1742,7 +2197,7 @@ var variantTest = defineInsight({
1742
2197
  const steps = [...split.steps].flatMap(
1743
2198
  ([step, stats]) => stats.variants.size < 2 ? [] : [stepTest(step, stats.variants, settings)]
1744
2199
  ).toSorted(
1745
- (left, right) => ORDER2[left.verdict] - ORDER2[right.verdict] || left.step - right.step
2200
+ (left, right) => ORDER2[left.verdict] - ORDER2[right.verdict] || left.stepIndex - right.stepIndex
1746
2201
  );
1747
2202
  const reported = variantsReported(context, rows);
1748
2203
  const result = {
@@ -1767,15 +2222,16 @@ var COPY_INSIGHTS = [
1767
2222
  stepFunnel,
1768
2223
  variantTest,
1769
2224
  copyAudit,
2225
+ copyPreview,
1770
2226
  copyReuse,
1771
2227
  replyTiming
1772
2228
  ];
1773
2229
 
1774
2230
  // src/insights/ops/anomalies.ts
1775
- import { z as z9 } from "zod";
2231
+ import { z as z10 } from "zod";
1776
2232
 
1777
2233
  // src/insights/ops/shared.ts
1778
- import { z as z8 } from "zod";
2234
+ import { z as z9 } from "zod";
1779
2235
  var DAY_MS2 = 864e5;
1780
2236
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1781
2237
  var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
@@ -1783,19 +2239,18 @@ var lastDays = (now, days, back = 0) => ({
1783
2239
  from: dayOf(now - days * (back + 1) * DAY_MS2),
1784
2240
  to: dayOf(now - (days * back + 1) * DAY_MS2)
1785
2241
  });
1786
- var campaignTotalsCost = (input27, price) => {
1787
- const campaigns = price.campaigns(input27.max_campaigns);
1788
- return price.campaignsIn(new Set(input27.statuses).size, input27.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
2242
+ var campaignTotalsCost = (input28, price) => {
2243
+ const campaigns = price.campaigns(input28.max_campaigns);
2244
+ return price.campaignsIn(new Set(input28.statuses).size, input28.max_campaigns) + (price.capabilities["stats.allCampaigns"] === "full" ? price.upTo(1) * price.one("stats") + price.upTo(campaigns) * price.one("stats") : campaigns * price.one("stats"));
1789
2245
  };
1790
2246
  var listFields = (costPerCampaign) => ({
1791
- max_campaigns: z8.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
2247
+ max_campaigns: z9.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1792
2248
  statuses: statusesInput(["active", "paused", "completed"])
1793
2249
  });
1794
2250
  var labelOf = (campaign) => ({
1795
2251
  campaign: campaign.ref,
1796
2252
  campaignName: campaign.name,
1797
2253
  channel: campaign.channel,
1798
- name: campaign.name,
1799
2254
  provider: campaign.provider,
1800
2255
  status: campaign.status
1801
2256
  });
@@ -1873,7 +2328,7 @@ var descending = (left, right) => {
1873
2328
  }
1874
2329
  return right - left;
1875
2330
  };
1876
- var readTotals = async (context, campaign, range) => sumCounts(
2331
+ var readTotals = async (context, campaign, range) => sumMeasured(
1877
2332
  context.rows(
1878
2333
  await context.outbound.campaign(campaign).stats({ from: range.from ?? void 0, to: range.to ?? void 0 })
1879
2334
  )
@@ -1897,25 +2352,25 @@ var readAllTotals = async (context, range) => {
1897
2352
  ]);
1898
2353
  }
1899
2354
  return new Map(
1900
- [...byCampaign].map(([ref, counts]) => [ref, sumCounts(counts)])
2355
+ [...byCampaign].map(([ref, counts]) => [ref, sumMeasured(counts)])
1901
2356
  );
1902
2357
  };
1903
- var readCampaignTotals = async (context, input27) => {
1904
- const listed = await readCampaignsIn(
2358
+ var readCampaignTotals = async (context, input28) => {
2359
+ const listed2 = await readCampaignsIn(
1905
2360
  context,
1906
- input27.statuses,
1907
- input27.max_campaigns
2361
+ input28.statuses,
2362
+ input28.max_campaigns
1908
2363
  );
1909
- const campaigns = listed.items;
1910
- const reported = campaigns.length > 1 ? await readAllTotals(context, input27) : void 0;
2364
+ const campaigns = listed2.items;
2365
+ const reported = campaigns.length > 1 ? await readAllTotals(context, input28) : void 0;
1911
2366
  const entries = await mapConcurrent(
1912
2367
  campaigns,
1913
2368
  async (campaign) => ({
1914
2369
  campaign,
1915
- counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input27)
2370
+ counts: reported?.get(campaign.ref) ?? await readTotals(context, campaign.ref, input28)
1916
2371
  })
1917
2372
  );
1918
- return { entries, read: campaignsReadOf(listed) };
2373
+ return { entries, read: campaignsReadOf(listed2) };
1919
2374
  };
1920
2375
  var readDaily = async (context, campaign, range) => {
1921
2376
  const options = { by: "day", from: range.from, to: range.to };
@@ -1928,11 +2383,11 @@ var readDaily = async (context, campaign, range) => {
1928
2383
  days.set(row.date, [...days.get(row.date) ?? [], row]);
1929
2384
  }
1930
2385
  }
1931
- return [...days].map(([date, group]) => ({ counts: sumCounts(group), date })).toSorted((left, right) => left.date.localeCompare(right.date));
2386
+ return [...days].map(([date, group]) => ({ counts: sumMeasured(group), date })).toSorted((left, right) => left.date.localeCompare(right.date));
1932
2387
  };
1933
2388
 
1934
2389
  // src/insights/ops/anomalies.ts
1935
- var metricSchema = z9.enum([
2390
+ var metricSchema = z10.enum([
1936
2391
  "sent",
1937
2392
  "contacted",
1938
2393
  "replied",
@@ -1942,13 +2397,13 @@ var metricSchema = z9.enum([
1942
2397
  "clicked",
1943
2398
  "unsubscribed"
1944
2399
  ]);
1945
- var input6 = z9.object({
1946
- baseline_days: z9.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1947
- campaign: z9.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1948
- days: z9.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1949
- metrics: z9.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1950
- min_baseline_points: z9.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1951
- threshold: z9.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
2400
+ var input7 = z10.object({
2401
+ 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"),
2402
+ campaign: z10.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
2403
+ days: z10.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
2404
+ metrics: z10.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
2405
+ min_baseline_points: z10.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2406
+ threshold: z10.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1952
2407
  });
1953
2408
  var reasonFor2 = (metric, daysWithData) => daysWithData === 0 ? `The vendor reports no ${metric} count for these days.` : "Too few earlier days with data to form a baseline.";
1954
2409
  var judge = (metric, point, baseline, threshold) => {
@@ -2023,7 +2478,7 @@ var findAnomalies = (series, options) => {
2023
2478
  };
2024
2479
  var anomalies = defineInsight({
2025
2480
  description: "Days that broke from trend, for one campaign or the whole workspace: each of the last `days` complete days is held to the `baseline_days` before it, and a daily count `threshold` standard deviations or more from that baseline's mean is returned, newest first, with the metric, the value, the baseline mean, the z-score, the direction and how it was judged. When every baseline day has the same count there is no standard deviation: a day with another count is returned with a null z-score and judgedBy flat_baseline. Use it to spot a sending outage, a bounce spike or a reply surge. Days the vendor has no count for are skipped, never read as zero. With no campaign it reads workspace stats, so it then also needs stats.workspace. Costs one stats request.",
2026
- inputSchema: input6,
2481
+ inputSchema: input7,
2027
2482
  key: "anomalies",
2028
2483
  cost: (_input, price) => price.one("stats"),
2029
2484
  name: "anomalies",
@@ -2054,7 +2509,7 @@ var anomalies = defineInsight({
2054
2509
  });
2055
2510
 
2056
2511
  // src/insights/ops/campaign-diagnosis.ts
2057
- import { z as z10 } from "zod";
2512
+ import { z as z11 } from "zod";
2058
2513
 
2059
2514
  // src/insights/ops/diagnosis-checks.ts
2060
2515
  var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
@@ -2131,11 +2586,48 @@ var positives = (facts, limits) => {
2131
2586
  }
2132
2587
  ];
2133
2588
  };
2134
- var recentSends = (facts, limits) => {
2135
- const { recent } = facts;
2589
+ var RUNNING_OUT_DAYS = 1;
2590
+ var dropOf = (recent) => recent.sent === null || recent.before === null || recent.before <= 0 ? null : round(1 - recent.sent / recent.before);
2591
+ var sendsFellOrStopped = (campaign, recent, limits) => {
2136
2592
  if (recent === null) {
2593
+ return false;
2594
+ }
2595
+ if (recent.sent === null || recent.sent === 0) {
2596
+ return campaign.status === "active";
2597
+ }
2598
+ const drop = dropOf(recent);
2599
+ return drop !== null && drop > limits.maxSendDrop;
2600
+ };
2601
+ var runningOut = (leads) => leads !== null && leads.daysLeft !== null && leads.daysLeft < RUNNING_OUT_DAYS;
2602
+ var outOfLeads = (recent, leads) => {
2603
+ const left = leads.toStart === 0 ? "no lead is left to start" : `only ${plural(leads.toStart, "lead")} ${noun(leads.toStart, "is", "are")} left to start, under a day at the recent pace of ${spoken(recent.startedPerDay)} new ${noun(recent.startedPerDay ?? 0, "lead", "leads")} a day`;
2604
+ const fell = recent.sent === null || recent.sent === 0 ? `The vendor reports no sends in the last ${recent.days} days` : `Sends fell from ${recent.before} to ${recent.sent} over the last ${recent.days} days against the ${recent.days} before`;
2605
+ const finishing = leads.inSequence === null || leads.inSequence === 0 ? "" : ` ${plural(leads.inSequence, "lead")} ${noun(leads.inSequence, "is", "are")} still finishing the sequence.`;
2606
+ return {
2607
+ code: "out_of_leads",
2608
+ finding: `${fell} because the campaign is running out of leads: ${left}.${finishing} This is lead runout, not a sending fault.`,
2609
+ next: "Add leads to keep the campaign sending; pipeline_forecast shows what the leads left should produce.",
2610
+ numbers: {
2611
+ activeLeads: leads.active,
2612
+ before: recent.before,
2613
+ daysLeft: leads.daysLeft,
2614
+ drop: dropOf(recent),
2615
+ inSequence: leads.inSequence,
2616
+ leadsToStart: leads.toStart,
2617
+ newLeadsPerDay: recent.startedPerDay,
2618
+ sent: recent.sent
2619
+ },
2620
+ severity: "high"
2621
+ };
2622
+ };
2623
+ var recentSends = (facts, limits) => {
2624
+ const { leads, recent } = facts;
2625
+ if (recent === null || !sendsFellOrStopped(facts.campaign, recent, limits)) {
2137
2626
  return [];
2138
2627
  }
2628
+ if (runningOut(leads)) {
2629
+ return [outOfLeads(recent, leads)];
2630
+ }
2139
2631
  if (recent.sent === null || recent.sent === 0) {
2140
2632
  return facts.campaign.status === "active" ? [
2141
2633
  {
@@ -2147,8 +2639,8 @@ var recentSends = (facts, limits) => {
2147
2639
  }
2148
2640
  ] : [];
2149
2641
  }
2150
- const drop = recent.before === null || recent.before <= 0 ? null : round(1 - recent.sent / recent.before);
2151
- return drop === null || drop <= limits.maxSendDrop ? [] : [
2642
+ const drop = dropOf(recent);
2643
+ return [
2152
2644
  {
2153
2645
  code: "falling_sends",
2154
2646
  finding: `Sends fell from ${recent.before} to ${recent.sent} over the last ${recent.days} days against the ${recent.days} before, a drop of ${percent(drop)}.`,
@@ -2167,30 +2659,72 @@ var sequence = ({ steps }) => steps === null || steps < 1 || steps > 2 ? [] : [
2167
2659
  severity: "medium"
2168
2660
  }
2169
2661
  ];
2662
+ var senderProblems = (sender) => [
2663
+ ...sender.status === "active" ? [] : [sender.status],
2664
+ ...warmupAtZero(sender) ? ["warmup score 0"] : []
2665
+ ];
2170
2666
  var senders = (facts) => {
2171
2667
  const all = facts.senders ?? [];
2172
- const inactive = all.filter((sender) => sender.status !== "active");
2173
- return inactive.length === 0 ? [] : [
2668
+ const flagged = all.flatMap((sender) => {
2669
+ const problems = senderProblems(sender);
2670
+ return problems.length === 0 ? [] : [{ problems, sender }];
2671
+ });
2672
+ const inactive = flagged.filter(({ sender }) => sender.status !== "active");
2673
+ const warmupZero = all.filter(warmupAtZero).length;
2674
+ const what = warmupZero === 0 ? "not active" : "not fit to send";
2675
+ return flagged.length === 0 ? [] : [
2174
2676
  {
2175
2677
  code: "inactive_sender",
2176
- finding: `${inactive.length} of ${plural(all.length, "sender")} ${noun(inactive.length, "is", "are")} not active: ${inactive.map(
2177
- (sender) => `${sender.address ?? sender.name ?? sender.ref} (${sender.status})`
2678
+ finding: `${flagged.length} of ${plural(all.length, "sender")} ${noun(flagged.length, "is", "are")} ${what}: ${flagged.map(
2679
+ ({ problems, sender }) => `${sender.address ?? sender.name ?? sender.ref} (${problems.join(", ")})`
2178
2680
  ).join(", ")}.`,
2179
2681
  next: "Reconnect or replace them; warmup_readiness shows which mailboxes are fit to send.",
2180
- numbers: { inactive: inactive.length, senders: all.length },
2682
+ numbers: {
2683
+ inactive: inactive.length,
2684
+ senders: all.length,
2685
+ warmupZero
2686
+ },
2181
2687
  severity: "high"
2182
2688
  }
2183
2689
  ];
2184
2690
  };
2185
- var tracking = ({ opened, settings }) => settings?.tracking.opens === false && (opened ?? 0) === 0 ? [
2186
- {
2187
- code: "tracking_off",
2188
- finding: "Open tracking is off, so the missing open count is expected and not a fault.",
2189
- next: "Judge this campaign on replies, not opens.",
2190
- numbers: { opened },
2191
- severity: "low"
2691
+ var TRACKING_OFF = {
2692
+ both: [
2693
+ "Open and click tracking are off, so missing open and click counts are expected and not a fault.",
2694
+ "Judge this campaign on replies, not opens or clicks."
2695
+ ],
2696
+ clicks: [
2697
+ "Click tracking is off, so no link click is counted; that is expected and not a fault.",
2698
+ "Judge this campaign on replies, not clicks."
2699
+ ],
2700
+ opens: [
2701
+ "Open tracking is off, so the missing open count is expected and not a fault.",
2702
+ "Judge this campaign on replies, not opens."
2703
+ ]
2704
+ };
2705
+ var offWhich = (opens, clicks) => {
2706
+ if (opens && clicks) {
2707
+ return "both";
2708
+ }
2709
+ return opens ? "opens" : "clicks";
2710
+ };
2711
+ var tracking = ({ opened, settings }) => {
2712
+ const opens = settings?.tracking.opens === false && (opened ?? 0) === 0;
2713
+ const clicks = settings?.tracking.clicks === false;
2714
+ if (!opens && !clicks) {
2715
+ return [];
2192
2716
  }
2193
- ] : [];
2717
+ const [finding, next] = TRACKING_OFF[offWhich(opens, clicks)];
2718
+ return [
2719
+ {
2720
+ code: "tracking_off",
2721
+ finding,
2722
+ next,
2723
+ numbers: { opened },
2724
+ severity: "low"
2725
+ }
2726
+ ];
2727
+ };
2194
2728
  var minutesOf = (clock) => {
2195
2729
  const [hours, minutes] = (clock ?? "").split(":").map(Number);
2196
2730
  return hours === void 0 || minutes === void 0 ? null : hours * 60 + minutes;
@@ -2235,7 +2769,20 @@ var schedule = ({ recent, settings }, limits) => {
2235
2769
  }
2236
2770
  ];
2237
2771
  };
2772
+ var contactedLeads = ({
2773
+ campaignLeads: leads,
2774
+ totals: { contacted }
2775
+ }) => contacted !== null && leads !== null && contactedBeyondLeads(contacted, leads) ? [
2776
+ {
2777
+ code: "contacted_exceeds_leads",
2778
+ finding: `The vendor reports ${contacted} leads contacted against ${plural(leads, "lead")} in the campaign, more than ${CONTACTED_LEADS_LIMIT} times as many. Leads contacted cannot be that far over the leads, so that count is not unique leads and the per-lead rates are not to be trusted.`,
2779
+ next: "Report it as an adapter fault, and judge the campaign on sends until it is fixed.",
2780
+ numbers: { contacted, leads, limit: CONTACTED_LEADS_LIMIT },
2781
+ severity: "high"
2782
+ }
2783
+ ] : [];
2238
2784
  var CHECKS2 = [
2785
+ contactedLeads,
2239
2786
  bounces,
2240
2787
  recentSends,
2241
2788
  senders,
@@ -2257,12 +2804,11 @@ var unknownRates = (facts) => [
2257
2804
  ];
2258
2805
 
2259
2806
  // src/insights/ops/campaign-diagnosis.ts
2260
- var share = (fallback, text) => z10.number().min(0).max(1).default(fallback).describe(text);
2261
- var recentDays = z10.number().int().min(1).max(30);
2262
- var input7 = z10.object({
2807
+ var share = (fallback, text) => z11.number().min(0).max(1).default(fallback).describe(text);
2808
+ var input8 = z11.object({
2263
2809
  ...rangeFields,
2264
- campaign: z10.string().min(3).describe("The campaign's ref"),
2265
- days: recentDays.default(7).describe(
2810
+ campaign: z11.string().min(3).describe("The campaign's ref or name"),
2811
+ days: z11.number().int().min(1).max(30).default(7).describe(
2266
2812
  "The days, ending yesterday, held against the same number before"
2267
2813
  ),
2268
2814
  daily_limit_share: share(
@@ -2274,15 +2820,19 @@ var input7 = z10.object({
2274
2820
  0.3,
2275
2821
  "A fall in sends, recent days against the days before, over this share is a finding"
2276
2822
  ),
2277
- max_senders: z10.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
2823
+ max_leads: z11.number().int().min(1).max(5e4).default(2e3).describe(
2824
+ "The most leads to read when sends fell or stopped, to tell lead runout from a fault. A page of leads is one request."
2825
+ ),
2826
+ max_senders: z11.number().int().min(1).max(SCREENED_AT_MOST).default(SCREENED_AT_MOST).describe(
2827
+ "The most of the campaign's own senders to read and screen for a status that is not active or a warmup score of 0"
2828
+ ),
2278
2829
  min_positive_share: share(
2279
2830
  0.2,
2280
2831
  "A share of replies that are positive under this is a finding"
2281
2832
  ),
2282
2833
  min_reply_rate: share(0.01, "A reply rate under this is a finding"),
2283
- min_sent: z10.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2284
- min_weekly_hours: z10.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
2285
- recent_days: renamed("days", recentDays)
2834
+ min_sent: z11.number().int().min(0).default(50).describe("Under this many sends, rates are not judged"),
2835
+ min_weekly_hours: z11.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume")
2286
2836
  });
2287
2837
  var readRecent = async (context, campaign, days) => {
2288
2838
  const recent = lastDays(context.now, days);
@@ -2295,11 +2845,42 @@ var readRecent = async (context, campaign, days) => {
2295
2845
  (day) => day.date >= from && day.date <= to ? [day.counts.sent] : []
2296
2846
  );
2297
2847
  const sends = sentIn(recent.from, recent.to);
2848
+ const started = newLeadsPerDay(
2849
+ series.flatMap(
2850
+ (day) => day.date >= recent.from && day.date <= recent.to ? [day.counts] : []
2851
+ ),
2852
+ days
2853
+ );
2298
2854
  return {
2299
2855
  before: total(sentIn(before.from, before.to)),
2300
2856
  days,
2301
2857
  daysWithData: sends.filter((value) => value !== null).length,
2302
- sent: total(sends)
2858
+ sent: total(sends),
2859
+ startedPerDay: started
2860
+ };
2861
+ };
2862
+ var readLeadsLeft = async (context, campaign, recent, maxLeads) => {
2863
+ if (!context.outbound.capabilities["leads.byCampaign"]) {
2864
+ context.note(
2865
+ "Lead runout: the adapter cannot list a campaign's leads, so a fall in sends was not checked against the leads left."
2866
+ );
2867
+ return null;
2868
+ }
2869
+ const { capped: capped2, items: leads } = await readCapped(
2870
+ context,
2871
+ (max) => context.outbound.campaign(campaign).leads.listAll({ max }),
2872
+ { input: "max_leads", max: maxLeads, what: "leads" }
2873
+ );
2874
+ if (capped2 || leads.length === 0) {
2875
+ return null;
2876
+ }
2877
+ const split = splitActive(leads);
2878
+ const unknown = leads.filter((lead) => lead.status === "unknown").length;
2879
+ return {
2880
+ active: split.active,
2881
+ daysLeft: runwayDays(split, { unknown }, true, recent.startedPerDay),
2882
+ inSequence: split.inSequence,
2883
+ toStart: leadsToStart(split)
2303
2884
  };
2304
2885
  };
2305
2886
  var readExtras = async (context, campaign, options) => {
@@ -2329,11 +2910,16 @@ var readExtras = async (context, campaign, options) => {
2329
2910
  max: options.maxSenders,
2330
2911
  what: "senders"
2331
2912
  }) : null;
2913
+ const campaignLeads = unless(
2914
+ !capabilities["campaigns.progress"],
2915
+ "Leads contacted against the campaign's leads: the adapter does not serve campaign progress."
2916
+ ) ? context.one(await handle.progress()).leads : null;
2332
2917
  const recent = unless(
2333
2918
  capabilities["stats.byDay"] === false,
2334
2919
  "Recent sending trend: the adapter has no stats by day."
2335
2920
  ) ? await readRecent(context, campaign, options.recentDays) : null;
2336
2921
  return {
2922
+ campaignLeads,
2337
2923
  notChecked,
2338
2924
  recent,
2339
2925
  senders: senders2?.items ?? null,
@@ -2341,17 +2927,19 @@ var readExtras = async (context, campaign, options) => {
2341
2927
  steps
2342
2928
  };
2343
2929
  };
2930
+ var leadsIfSendsFell = async (context, campaign, recent, options) => recent !== null && sendsFellOrStopped(campaign, recent, { maxSendDrop: options.maxSendDrop }) ? await readLeadsLeft(context, campaign.ref, recent, options.maxLeads) : null;
2344
2931
  var summarize = (findings) => {
2345
2932
  const [first] = findings;
2346
2933
  return first === void 0 ? "No problem was found in what could be checked." : `${findings.length} ${findings.length === 1 ? "finding" : "findings"}. Most serious: ${first.finding}`;
2347
2934
  };
2348
2935
  var campaignDiagnosis = defineInsight({
2349
- description: "Why one campaign is underperforming: a list of findings, most serious first, each with a code, a plain-language finding, the numbers behind it and what to look at next. It checks for too little volume to judge, a low reply rate (with its 95% interval), a high bounce rate, few positive replies among replies, sends falling or stopped over the last days, a one or two step sequence, a sender that is not active, open tracking being off, and a schedule or daily limit that holds volume back. Also returns what could not be checked; an empty list means nothing was found, not that all is well. Costs up to 7 requests.",
2350
- inputSchema: input7,
2936
+ 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, told apart from the campaign running out of leads (under a day of new leads left to start at the recent pace, the pace lead_runway uses), a one or two step sequence, any of the campaign's own senders (up to 500) that is not active or has a warmup score of 0, open or click tracking being off, a schedule or daily limit that holds volume back, and a count of leads contacted more than twice the campaign's leads, which means the count is wrong. Also returns what could not be checked; an empty list means nothing was found, not that all is well. Costs up to 7 requests, plus one per page of the campaign's senders and, only when sends fell or stopped, one per page of its leads.",
2937
+ inputSchema: input8,
2351
2938
  key: "campaignDiagnosis",
2352
2939
  cost: (values, price) => {
2353
2940
  const { capabilities } = price;
2354
- return price.one("campaigns.get") + price.one("stats") + (capabilities["campaigns.settings"] === false ? 0 : price.one("campaigns.settings")) + (capabilities.sequence === false ? 0 : price.one("sequence.get")) + (capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders)) + (capabilities["stats.byDay"] === false ? 0 : price.one("stats"));
2941
+ return price.one("campaigns.get") + price.one("stats") + (capabilities["campaigns.settings"] === false ? 0 : price.one("campaigns.settings")) + (capabilities["campaigns.progress"] === false ? 0 : price.one("campaigns.progress")) + (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")) + // The leads are read only when sends fell or stopped, which the data decides.
2942
+ (capabilities["stats.byDay"] === false || capabilities["leads.byCampaign"] === false ? 0 : price.upTo(1) * price.list("leads.list", values.max_leads));
2355
2943
  },
2356
2944
  scales: "max_senders",
2357
2945
  name: "campaign_diagnosis",
@@ -2366,9 +2954,14 @@ var campaignDiagnosis = defineInsight({
2366
2954
  maxSenders: options.max_senders,
2367
2955
  recentDays: options.days
2368
2956
  });
2957
+ const leads = await leadsIfSendsFell(context, campaign, extras.recent, {
2958
+ maxLeads: options.max_leads,
2959
+ maxSendDrop: options.max_send_drop
2960
+ });
2369
2961
  const facts = {
2370
2962
  ...extras,
2371
2963
  campaign,
2964
+ leads,
2372
2965
  opened: counts.opened,
2373
2966
  rates: ratesOf(counts),
2374
2967
  totals: totalsOf(counts)
@@ -2396,17 +2989,17 @@ var campaignDiagnosis = defineInsight({
2396
2989
  });
2397
2990
 
2398
2991
  // src/insights/ops/campaign-ranking.ts
2399
- import { z as z11 } from "zod";
2400
- var metricSchema2 = z11.enum([
2992
+ import { z as z12 } from "zod";
2993
+ var metricSchema2 = z12.enum([
2401
2994
  "reply_rate",
2402
2995
  "positive_reply_rate",
2403
2996
  "bounce_rate"
2404
2997
  ]);
2405
- var input8 = z11.object({
2998
+ var input9 = z12.object({
2406
2999
  ...rangeFields,
2407
3000
  ...listFields("one stats request"),
2408
3001
  metric: metricSchema2.default("reply_rate").describe("The rate to rank by. For bounce_rate, lower is better."),
2409
- min_sent: z11.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
3002
+ min_sent: z12.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
2410
3003
  });
2411
3004
  var measured = (counts, metric, basis) => {
2412
3005
  const rates = ratesOf(counts, baseIn2(basis));
@@ -2415,7 +3008,7 @@ var measured = (counts, metric, basis) => {
2415
3008
  }
2416
3009
  return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
2417
3010
  };
2418
- var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.name.localeCompare(right.name);
3011
+ var order = (metric) => (left, right) => (metric === "bounce_rate" ? descending(right.high, left.high) || descending(right.rate, left.rate) : descending(left.low, right.low) || descending(left.rate, right.rate)) || left.campaignName.localeCompare(right.campaignName);
2419
3012
  var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2420
3013
  const scored = [];
2421
3014
  const tooFewSends = [];
@@ -2463,7 +3056,7 @@ var rankCampaigns = (entries, metric, minSent, replyBasis) => {
2463
3056
  };
2464
3057
  var campaignRanking = defineInsight({
2465
3058
  description: "Which campaigns are best, ranked fairly: by the low end of the 95% Wilson interval of the reply rate (or positive reply rate; for bounce rate, by the high end, lowest first), so 2 replies from 10 sends cannot outrank 150 from 1,000. Use it to pick winners and losers across a workspace. Returns each campaign with its count, rate, interval and rank, the campaigns left out for too few sends, those whose count the vendor does not report (a null rate is unknown, not zero), and the gap between the top and the median. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2466
- inputSchema: input8,
3059
+ inputSchema: input9,
2467
3060
  key: "campaignRanking",
2468
3061
  cost: campaignTotalsCost,
2469
3062
  scales: "max_campaigns",
@@ -2484,11 +3077,11 @@ var campaignRanking = defineInsight({
2484
3077
  });
2485
3078
 
2486
3079
  // src/insights/ops/channel-mix.ts
2487
- import { z as z12 } from "zod";
2488
- var input9 = z12.object({
3080
+ import { z as z13 } from "zod";
3081
+ var input10 = z13.object({
2489
3082
  ...rangeFields,
2490
3083
  ...listFields("one stats request"),
2491
- alpha: z12.number().gt(0).lt(1).default(0.05).describe(
3084
+ alpha: z13.number().gt(0).lt(1).default(0.05).describe(
2492
3085
  "The p-value under which a difference counts as more than chance"
2493
3086
  )
2494
3087
  });
@@ -2503,7 +3096,7 @@ var groupOf = (channel, entries) => {
2503
3096
  );
2504
3097
  return {
2505
3098
  group: {
2506
- ...totalsOf(sumCounts(counts)),
3099
+ ...totalsOf(sumMeasured(counts)),
2507
3100
  acceptance: channel === "linkedin" ? acceptance.measured : null,
2508
3101
  campaigns: entries.length,
2509
3102
  channel,
@@ -2570,7 +3163,7 @@ var compare = (groups, alpha) => {
2570
3163
  };
2571
3164
  var channelMix = defineInsight({
2572
3165
  description: "Email against LinkedIn: campaign totals added up per channel, with campaigns, leads contacted, messages sent, replies, positive replies, the reply rate with its 95% interval and, for LinkedIn, the connection acceptance rate; whether the difference in reply rate is more than chance (a two-proportion test); and the same numbers per tool. Use it to decide where to put volume. With one channel present it returns that channel and says there is nothing to compare. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a group whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
2573
- inputSchema: input9,
3166
+ inputSchema: input10,
2574
3167
  key: "channelMix",
2575
3168
  cost: campaignTotalsCost,
2576
3169
  scales: "max_campaigns",
@@ -2608,15 +3201,15 @@ var channelMix = defineInsight({
2608
3201
  });
2609
3202
 
2610
3203
  // src/insights/ops/client-report.ts
2611
- import { z as z15 } from "zod";
3204
+ import { z as z16 } from "zod";
2612
3205
 
2613
3206
  // src/insights/ops/period-comparison.ts
2614
- import { z as z13 } from "zod";
2615
- var input10 = z13.object({
3207
+ import { z as z14 } from "zod";
3208
+ var input11 = z14.object({
2616
3209
  ...listFields("two stats requests"),
2617
- alpha: z13.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2618
- days: z13.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2619
- min_sent: z13.number().int().min(0).default(50).describe(
3210
+ alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3211
+ days: z14.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
3212
+ min_sent: z14.number().int().min(0).default(50).describe(
2620
3213
  "A campaign under this many sends in either period is listed apart"
2621
3214
  )
2622
3215
  });
@@ -2678,7 +3271,7 @@ var comparePeriods = (current, previous, alpha) => {
2678
3271
  );
2679
3272
  };
2680
3273
  var compareAcross = (current, previous, alpha) => {
2681
- const counts = [sumCounts(current), sumCounts(previous)];
3274
+ const counts = [sumMeasured(current), sumMeasured(previous)];
2682
3275
  const basis = periodBasis(...counts);
2683
3276
  const now = ratesAcross(current, baseIn2(basis));
2684
3277
  const before = ratesAcross(previous, baseIn2(basis));
@@ -2698,13 +3291,13 @@ var compareAcross = (current, previous, alpha) => {
2698
3291
  var readPeriods = async (context, options) => {
2699
3292
  const current = lastDays(context.now, options.days);
2700
3293
  const previous = lastDays(context.now, options.days, 1);
2701
- const listed = await readCampaignsIn(
3294
+ const listed2 = await readCampaignsIn(
2702
3295
  context,
2703
3296
  options.statuses,
2704
3297
  options.max_campaigns
2705
3298
  );
2706
3299
  const campaigns = await mapConcurrent(
2707
- listed.items,
3300
+ listed2.items,
2708
3301
  async (campaign) => {
2709
3302
  const [now, before] = await Promise.all([
2710
3303
  readTotals(context, campaign.ref, current),
@@ -2713,7 +3306,7 @@ var readPeriods = async (context, options) => {
2713
3306
  return { campaign, current: now, previous: before };
2714
3307
  }
2715
3308
  );
2716
- return { campaigns, current, previous, read: campaignsReadOf(listed) };
3309
+ return { campaigns, current, previous, read: campaignsReadOf(listed2) };
2717
3310
  };
2718
3311
  var totalOf = (campaigns, alpha) => compareAcross(
2719
3312
  campaigns.map((entry) => entry.current),
@@ -2745,7 +3338,7 @@ var workspaceOf = async (context, periods, alpha) => {
2745
3338
  };
2746
3339
  var periodComparison = defineInsight({
2747
3340
  description: "This period against the last: for each campaign, counts and rates for the last `days` complete days and for the `days` before, the change in each, and whether the change in the reply rate is more than chance (a two-proportion test), with the campaigns sorted by the size of that change. Also the same for every campaign added together and, where the adapter has them, for the vendor's workspace totals. Reply and positive reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly review. Campaigns under min_sent sends in either period are listed apart; a null is a count the vendor does not report, and a rate of a total counts only the campaigns that report both its count and what it divides by (a note says when some are left out). Costs two stats requests per campaign plus two for the workspace.",
2748
- inputSchema: input10,
3341
+ inputSchema: input11,
2749
3342
  key: "periodComparison",
2750
3343
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + 2 * price.campaigns(values.max_campaigns) * price.one("stats") + (price.capabilities["stats.workspace"] === false ? 0 : 2 * price.one("stats")),
2751
3344
  scales: "max_campaigns",
@@ -2777,7 +3370,7 @@ var periodComparison = defineInsight({
2777
3370
  (left, right) => descending(
2778
3371
  left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
2779
3372
  right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
2780
- ) || left.name.localeCompare(right.name)
3373
+ ) || left.campaignName.localeCompare(right.campaignName)
2781
3374
  ),
2782
3375
  current: periods.current,
2783
3376
  days: options.days,
@@ -2795,11 +3388,11 @@ var periodComparison = defineInsight({
2795
3388
  });
2796
3389
 
2797
3390
  // src/insights/ops/pipeline-forecast.ts
2798
- import { z as z14 } from "zod";
2799
- var input11 = z14.object({
2800
- campaign: z14.string().min(3).describe("The campaign's ref"),
2801
- days: z14.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2802
- max_leads: z14.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
3391
+ import { z as z15 } from "zod";
3392
+ var input12 = z15.object({
3393
+ campaign: z15.string().min(3).describe("The campaign's ref or name"),
3394
+ days: z15.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
3395
+ max_leads: z15.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2803
3396
  });
2804
3397
  var countStatuses = (leads) => {
2805
3398
  const counts = {
@@ -2808,6 +3401,7 @@ var countStatuses = (leads) => {
2808
3401
  completed: 0,
2809
3402
  paused: 0,
2810
3403
  replied: 0,
3404
+ skipped: 0,
2811
3405
  unknown: 0,
2812
3406
  unsubscribed: 0
2813
3407
  };
@@ -2832,26 +3426,21 @@ var paceOf = async (context, campaign, days) => {
2832
3426
  const series = await readDaily(
2833
3427
  context,
2834
3428
  campaign,
2835
- lastDays(context.now, days)
3429
+ paceWindow(context.now, days)
3430
+ );
3431
+ return newLeadsPerDay(
3432
+ series.map((day) => day.counts),
3433
+ days
2836
3434
  );
2837
- const contacted = total(series.map((day) => day.counts.contacted));
2838
- return contacted === null ? null : round(contacted / days);
2839
3435
  };
2840
3436
  var ASSUMPTIONS = [
2841
3437
  "Every remaining lead is contacted.",
2842
3438
  "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
2843
- "The daily pace stays what it was over the recent days. Days with no report count as no sends."
3439
+ "The daily pace of new leads started stays what it was over the recent days. Days with no report count as none started."
2844
3440
  ];
2845
- var daysLeftOf = (byStatus, complete, pace) => {
2846
- const remaining = byStatus.active;
2847
- if (remaining === 0) {
2848
- return complete && byStatus.unknown === 0 ? 0 : null;
2849
- }
2850
- return pace === null || pace <= 0 ? null : round(remaining / pace);
2851
- };
2852
- var describe2 = ({ complete, daysLeft, remaining }, forecast) => {
3441
+ var describe2 = ({ complete, daysLeft, inSequence, remaining }, forecast) => {
2853
3442
  if (daysLeft === 0) {
2854
- return "No leads are left to contact; add leads to keep the campaign sending.";
3443
+ return remaining === 0 ? "No leads are left to contact; add leads to keep the campaign sending." : `No new leads are left to start; ${plural(inSequence ?? remaining, "lead")} ${noun(inSequence ?? remaining, "is", "are")} finishing the sequence. Add leads to keep the campaign starting new ones.`;
2855
3444
  }
2856
3445
  const leads = `${complete ? "" : "At least "}${plural(remaining, "lead")} ${noun(remaining, "remains", "remain")}`;
2857
3446
  if (forecast.expected === null) {
@@ -2882,9 +3471,10 @@ var forecastCampaign = async (context, campaign, options) => {
2882
3471
  const rates = ratesOf(
2883
3472
  await readTotals(context, campaign.ref, { from: null, to: null })
2884
3473
  );
3474
+ const split = splitActive(leads);
2885
3475
  const pace = await paceOf(context, campaign.ref, options.days);
2886
3476
  const expectedReplies = project(remaining, rates.replyRate);
2887
- const daysLeft = daysLeftOf(byStatus, complete, pace);
3477
+ const daysLeft = runwayDays(split, byStatus, complete, pace);
2888
3478
  return {
2889
3479
  ...labelOf(campaign),
2890
3480
  assumptions: [
@@ -2897,17 +3487,22 @@ var forecastCampaign = async (context, campaign, options) => {
2897
3487
  estimate: true,
2898
3488
  expectedPositive: project(remaining, rates.positiveRate),
2899
3489
  expectedReplies,
2900
- finding: describe2({ complete, daysLeft, remaining }, expectedReplies),
3490
+ finding: describe2(
3491
+ { complete, daysLeft, inSequence: split.inSequence, remaining },
3492
+ expectedReplies
3493
+ ),
3494
+ inSequence: split.inSequence,
2901
3495
  leadsComplete: complete,
2902
3496
  leadsRead: leads.length,
3497
+ notStarted: split.notStarted,
2903
3498
  positiveRate: rates.positiveRate,
2904
3499
  remaining,
2905
3500
  replyRate: rates.replyRate
2906
3501
  };
2907
3502
  };
2908
3503
  var pipelineForecast = defineInsight({
2909
- description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, the days of sending left at the recent daily contact rate, and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
2910
- inputSchema: input11,
3504
+ description: "The leads one campaign has left and what they should produce: leads counted by status, the leads still active, split into those not yet started and those partway through the sequence, the days until no lead is left to start at the recent pace of new leads started per day (the same figure lead_runway gives), and the replies and positive replies to expect from the remaining leads at the campaign's reply rate so far, each with a low and a high figure from the 95% interval. Use it to decide when to load more leads. It is an estimate and lists what it assumes; a null means the vendor does not report the count behind it. Costs one request per page of leads, plus two stats requests.",
3505
+ inputSchema: input12,
2911
3506
  key: "pipelineForecast",
2912
3507
  cost: (values, price) => price.one("campaigns.get") + price.list("leads.list", values.max_leads) + price.one("stats") + (price.capabilities["stats.byDay"] === false ? 0 : price.one("stats")),
2913
3508
  scales: "max_leads",
@@ -2928,24 +3523,22 @@ var pipelineForecast = defineInsight({
2928
3523
  });
2929
3524
 
2930
3525
  // src/insights/ops/client-report.ts
2931
- var limit2 = z15.number().int().min(1).max(20);
2932
- var input12 = z15.object({
3526
+ var input13 = z16.object({
2933
3527
  ...listFields(
2934
3528
  "two stats requests, and three more plus its leads when active"
2935
3529
  ),
2936
- alpha: z15.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2937
- anomaly_threshold: z15.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2938
- baseline_days: z15.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2939
- days: z15.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2940
- limit: limit2.default(3).describe("How many best and worst campaigns to show"),
2941
- max_bounce_rate: z15.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2942
- max_leads_per_campaign: z15.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2943
- min_baseline_points: z15.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2944
- min_sent: z15.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2945
- runway_days: z15.number().min(0).default(7).describe(
3530
+ alpha: z16.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
3531
+ anomaly_threshold: z16.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
3532
+ baseline_days: z16.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
3533
+ days: z16.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
3534
+ limit: z16.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show"),
3535
+ max_bounce_rate: z16.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
3536
+ 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"),
3537
+ min_baseline_points: z16.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
3538
+ min_sent: z16.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
3539
+ runway_days: z16.number().min(0).default(7).describe(
2946
3540
  "A campaign with this many days of leads left or fewer is flagged"
2947
- ),
2948
- top: renamed("limit", limit2)
3541
+ )
2949
3542
  });
2950
3543
  var sendingLeft = (daysLeft) => {
2951
3544
  if (daysLeft !== null && daysLeft < 0.05) {
@@ -3065,7 +3658,7 @@ var actionsOf = (report) => {
3065
3658
  };
3066
3659
  var clientReport = defineInsight({
3067
3660
  description: "One report for one client or workspace over the last `days` complete days: totals and the change from the period before, the best and worst campaigns by the low end of the interval of the reply rate, campaigns with a bounce problem, unusual days, active campaigns running out of leads, and a short list of action items in plain language, each naming the campaign and the number behind it. Reply rates divide by messages sent (`replyRateBasis`), since a period's replies also answer leads contacted before it, and by leads contacted for both periods only when a period does not report messages sent. Use it for a weekly client update. A section the adapter cannot serve is null and named in `leftOut`, and a null count is one the vendor does not report. Costs two stats requests per campaign, one for the workspace, and for each active campaign two more plus its pages of leads.",
3068
- inputSchema: input12,
3661
+ inputSchema: input13,
3069
3662
  key: "clientReport",
3070
3663
  cost: (values, price) => {
3071
3664
  const { capabilities } = price;
@@ -3126,18 +3719,18 @@ var clientReport = defineInsight({
3126
3719
  });
3127
3720
 
3128
3721
  // src/insights/ops/tag-rollup.ts
3129
- import { z as z16 } from "zod";
3130
- var input13 = z16.object({
3722
+ import { z as z17 } from "zod";
3723
+ var input14 = z17.object({
3131
3724
  ...rangeFields,
3132
3725
  ...listFields("one stats request"),
3133
- min_sent: z16.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
3726
+ min_sent: z17.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
3134
3727
  });
3135
3728
  var groupOf2 = (tag, entries) => {
3136
3729
  const counts = entries.map((entry) => entry.counts);
3137
3730
  const { partial, rates } = ratesAcross(counts);
3138
3731
  return {
3139
3732
  group: {
3140
- ...totalsOf(sumCounts(counts)),
3733
+ ...totalsOf(sumMeasured(counts)),
3141
3734
  ...rates,
3142
3735
  campaigns: entries.length,
3143
3736
  tag
@@ -3148,7 +3741,7 @@ var groupOf2 = (tag, entries) => {
3148
3741
  var named = (group) => group.tag ?? "";
3149
3742
  var tagRollup = defineInsight({
3150
3743
  description: "Results by campaign tag (for example one tag per client, offer or audience): for each tag the campaigns, messages sent, leads contacted, replies, positive replies and bounces, with reply, positive reply and bounce rates and their 95% intervals, sorted by the low end of the reply rate interval. A campaign with two tags counts in both; campaigns with none are grouped under a null tag. Tags under min_sent sends are listed apart. A null count is one the vendor does not report; a rate counts only the campaigns that report both its count and what it divides by, and a note names a tag whose rate leaves campaigns out. Costs one listing per status plus one stats request per campaign (one for all of them on a vendor that reports every campaign in one call with every count).",
3151
- inputSchema: input13,
3744
+ inputSchema: input14,
3152
3745
  key: "tagRollup",
3153
3746
  // A tool whose campaigns carry no tags would put every campaign under one
3154
3747
  // null tag, which reads as an answer. On a combined instance one tool with
@@ -3208,97 +3801,7 @@ var OPS_INSIGHTS = [
3208
3801
 
3209
3802
  // src/insights/people/account-summary.ts
3210
3803
  import { z as z18 } from "zod";
3211
-
3212
- // src/insights/people/read.ts
3213
- import { z as z17 } from "zod";
3214
- var readCappedFlag = (context, open, max, what, input27) => readCapped(context, open, { input: input27, max, what });
3215
- var readByRef = async (context, refs, read, what, effect) => {
3216
- if (refs.length === 0) {
3217
- return /* @__PURE__ */ new Map();
3218
- }
3219
- const found = await read(refs);
3220
- if (found.errors.length > 0) {
3221
- context.note(
3222
- `${plural(found.errors.length, ...what)} could not be read, so ${noun(found.errors.length, "its", "their")} ${effect}.`
3223
- );
3224
- }
3225
- const [costliest] = found.results.toSorted(
3226
- (left, right) => right.value.meta.requests - left.value.meta.requests
3227
- );
3228
- if (costliest !== void 0) {
3229
- context.one(costliest.value);
3230
- }
3231
- return new Map(found.results.map(({ id, value }) => [id, value]));
3232
- };
3233
- var statusesField = statusesInput(["active"]);
3234
- var campaignsIn = async (context, statuses, max) => {
3235
- const { items } = await readCampaignsIn(context, statuses, max);
3236
- return items;
3237
- };
3238
- var leadsOf = async (context, campaign, max, input27) => {
3239
- const { items } = await readCappedFlag(
3240
- context,
3241
- (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
3242
- max,
3243
- "leads of a campaign",
3244
- input27
3245
- );
3246
- return items;
3247
- };
3248
- var nameOf = (lead) => {
3249
- const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
3250
- return name === "" ? null : name;
3251
- };
3252
- var domainOf = (email) => {
3253
- const domain = email?.split("@").at(-1) ?? "";
3254
- return email === null || !email.includes("@") || domain === "" ? null : domain;
3255
- };
3256
- var DEFAULT_POSITIVE_LABELS = [
3257
- "Interested",
3258
- "Meeting Booked",
3259
- "Meeting Completed"
3260
- ];
3261
- var positiveLabelsField = z17.array(z17.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
3262
- "Vendor interest labels that count as interested, matched without regard to case"
3263
- );
3264
- var isPositive = (label, labels) => label === null ? null : labels.some(
3265
- (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
3266
- );
3267
- var hasReplied = (lead) => lead.replied === true || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
3268
- var OUT_OF_OFFICE = /\bout[\s-]+of[\s-]+(?:the\s+)?office\b/iu;
3269
- var AUTOMATIC = /* @__PURE__ */ new Set([
3270
- "bounce",
3271
- "ooo"
3272
- ]);
3273
- var isAutoReplied = (lead) => lead.interestCategory !== null && AUTOMATIC.has(lead.interestCategory) || // A label the vendor did not map to a category is read by a fixed rule.
3274
- lead.interestCategory === null && OUT_OF_OFFICE.test(lead.interest ?? "");
3275
- var hasHumanReply = (lead) => hasReplied(lead) && !isAutoReplied(lead);
3276
- var NEGATIVE_CATEGORIES = /* @__PURE__ */ new Set(["negative", "unsubscribe"]);
3277
- var NEGATIVE_LABEL = /\b(?:not[\s-]+interested|wrong[\s-]+person|unsubscribed?|do[\s-]+not[\s-]+contact)\b/iu;
3278
- var isNegative = (lead) => lead.interestCategory !== null && NEGATIVE_CATEGORIES.has(lead.interestCategory) || lead.interestCategory === null && NEGATIVE_LABEL.test(lead.interest ?? "");
3279
- var COUNTS = "no per-lead open, click or reply counts";
3280
- var noteEngagement = (context, leads, effect) => {
3281
- const { outbound } = context;
3282
- if (outbound.capabilities["leads.engagement"]) {
3283
- return;
3284
- }
3285
- if (leads.every((lead) => lead.provider === outbound.provider)) {
3286
- context.note(`This tool reports ${COUNTS}, so ${effect}.`);
3287
- return;
3288
- }
3289
- const reporting = new Set(
3290
- leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
3291
- );
3292
- const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
3293
- if (lacking.length > 0) {
3294
- context.note(
3295
- `${lacking.join(", ")} ${lacking.length === 1 ? "reports" : "report"} ${COUNTS}, so ${effect} for ${lacking.length === 1 ? "its" : "their"} records. Records from the other tools carry what their vendor reports.`
3296
- );
3297
- }
3298
- };
3299
-
3300
- // src/insights/people/account-summary.ts
3301
- var input14 = z18.object({
3804
+ var input15 = z18.object({
3302
3805
  allow_free_domains: z18.boolean().default(false).describe(
3303
3806
  "Set to true to accept an email provider domain such as gmail.com, which is not one company"
3304
3807
  ),
@@ -3344,7 +3847,24 @@ var parseDomain = (text, provider) => {
3344
3847
  }
3345
3848
  return host;
3346
3849
  };
3347
- var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLeads }) => {
3850
+ var readLeads = async (context, domain, { max_campaigns: maxCampaigns, max_leads: maxLeads }) => {
3851
+ const { outbound } = context;
3852
+ if (outbound.capabilities["leads.byDomain"]) {
3853
+ const found = await readCappedFlag(
3854
+ context,
3855
+ (cap) => outbound.leads.listAll({ domain, max: cap }),
3856
+ maxLeads,
3857
+ "leads at the domain",
3858
+ "max_leads"
3859
+ );
3860
+ return { ...found, foundBy: "search" };
3861
+ }
3862
+ return {
3863
+ ...await scanLeads(context, maxCampaigns, maxLeads),
3864
+ foundBy: "scan"
3865
+ };
3866
+ };
3867
+ var scanLeads = async (context, maxCampaigns, maxLeads) => {
3348
3868
  const { outbound } = context;
3349
3869
  if (outbound.capabilities["leads.list"]) {
3350
3870
  return await readCappedFlag(
@@ -3358,7 +3878,7 @@ var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLea
3358
3878
  if (!outbound.capabilities["leads.byCampaign"]) {
3359
3879
  throw new OutboundError(
3360
3880
  "Unsupported",
3361
- `account_summary is not available: the ${outbound.provider} adapter supports neither leads.list nor leads.byCampaign`,
3881
+ `account_summary is not available: the ${outbound.provider} adapter supports none of leads.byDomain, leads.list and leads.byCampaign`,
3362
3882
  { provider: outbound.provider }
3363
3883
  );
3364
3884
  }
@@ -3431,6 +3951,18 @@ var toPerson = (email, leads, labels) => {
3431
3951
  title: pick((lead) => lead.title)
3432
3952
  };
3433
3953
  };
3954
+ var findingOf = (domain, people, read) => {
3955
+ const replied = people.filter((person) => person.replied).length;
3956
+ const found = `${plural(people.length, "person", "people")} at ${domain}; ${count(replied)} replied`;
3957
+ if (!read.capped) {
3958
+ if (people.length > 0) {
3959
+ return `${found}.`;
3960
+ }
3961
+ return read.foundBy === "search" ? `No lead at ${domain} was found.` : `Checked all ${plural(read.leadsRead, "lead")}; none is at ${domain}.`;
3962
+ }
3963
+ const checked = read.foundBy === "search" ? `Read ${plural(read.leadsRead, "lead")} at ${domain} (max_leads) and more exist` : `Checked the first ${plural(read.leadsRead, "lead")} and more exist`;
3964
+ return people.length === 0 ? `${checked}; none matched. This does not mean nobody at ${domain} is in a campaign.` : `${found} in the leads read. ${checked}, so others at ${domain} may be missing.`;
3965
+ };
3434
3966
  var byLastReply = (left, right) => (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || Number(right.replied) - Number(left.replied) || left.email.localeCompare(right.email);
3435
3967
  var lastReplyOf = (people) => {
3436
3968
  const [person] = people;
@@ -3445,8 +3977,8 @@ var lastReplyOf = (people) => {
3445
3977
  };
3446
3978
  };
3447
3979
  var accountSummary = defineInsight({
3448
- description: "Everyone at one company across campaigns and tools, from the company's domain or any email address at it: each person with their name, title, campaigns, status, interest label and open, click and reply counts, plus totals and who replied most recently. People are matched by exact email domain, so a lead with only a LinkedIn profile is not found, and an email provider domain such as gmail.com is refused unless allow_free_domains is true. A record the vendor labels out-of-office or bounced is marked autoReplied and its replies do not count as the person replying. Costs one request per page of leads read (max_leads sets the ceiling); totals.moreLeadsExist is true when that ceiling left leads unread. A count the vendor does not report is null.",
3449
- inputSchema: input14,
3980
+ 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. Where the tool can search leads by domain (leads.byDomain) it finds them wherever they are; otherwise it reads leads in order up to max_leads, and finding says when that left the company possibly unread. 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.",
3981
+ inputSchema: input15,
3450
3982
  key: "accountSummary",
3451
3983
  // Every address is masked, so no lead's domain can be read. A hash keeps
3452
3984
  // exact matching but not the domain.
@@ -3456,7 +3988,7 @@ var accountSummary = defineInsight({
3456
3988
  }
3457
3989
  return strategy === "hash" ? 'email addresses, whose domain it matches people by (under strategy "hash" too: a hashed address keeps no domain)' : "email addresses, whose domain it matches people by";
3458
3990
  },
3459
- cost: (values, price) => price.capabilities["leads.list"] === false ? price.list("campaigns.list", values.max_campaigns) + price.upTo(values.max_campaigns - 1) * price.list("leads.list", 1) + price.upTo(1) * price.list("leads.list", values.max_leads) : price.list("leads.list", values.max_leads),
3991
+ cost: (values, price) => price.capabilities["leads.list"] === false && !price.capabilities["leads.byDomain"] ? price.list("campaigns.list", values.max_campaigns) + price.upTo(values.max_campaigns - 1) * price.list("leads.list", 1) + price.upTo(1) * price.list("leads.list", values.max_leads) : price.list("leads.list", values.max_leads),
3460
3992
  scales: "max_leads",
3461
3993
  name: "account_summary",
3462
3994
  needs: [],
@@ -3470,7 +4002,7 @@ var accountSummary = defineInsight({
3470
4002
  { provider: context.outbound.provider }
3471
4003
  );
3472
4004
  }
3473
- const read = await readLeads(context, values);
4005
+ const read = await readLeads(context, domain, values);
3474
4006
  const leads = read.items;
3475
4007
  noteEngagement(context, leads, "those are null");
3476
4008
  const byEmail = /* @__PURE__ */ new Map();
@@ -3484,6 +4016,12 @@ var accountSummary = defineInsight({
3484
4016
  ).toSorted(byLastReply);
3485
4017
  const summary = {
3486
4018
  domain,
4019
+ finding: findingOf(domain, people, {
4020
+ capped: read.capped,
4021
+ foundBy: read.foundBy,
4022
+ leadsRead: leads.length
4023
+ }),
4024
+ foundBy: read.foundBy,
3487
4025
  lastReply: lastReplyOf(people),
3488
4026
  people,
3489
4027
  totals: {
@@ -3507,12 +4045,12 @@ var HOUR = 36e5;
3507
4045
  var DAY = 24 * HOUR;
3508
4046
  var waited = (hours) => hours >= 48 ? plural(Math.floor(hours / 24), "day") : plural(Math.floor(hours), "hour");
3509
4047
  var DEFAULT_DAYS = 14;
3510
- var input15 = z19.object({
4048
+ var input16 = z19.object({
3511
4049
  categories: z19.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
3512
4050
  "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
3513
4051
  ),
3514
4052
  include_auto: z19.boolean().default(false).describe(
3515
- "Set to true to also check replies the vendor marks as automatic"
4053
+ "Set to true to also check replies flagged automatic, by the vendor or by a fixed rule"
3516
4054
  ),
3517
4055
  max_replies: z19.number().int().min(1).max(1e3).default(50).describe(
3518
4056
  "The most replies to read. Each conversation among them costs one more request to check."
@@ -3654,7 +4192,7 @@ var readReplies = (context, since, max) => {
3654
4192
  };
3655
4193
  var droppedReplies = defineInsight({
3656
4194
  description: "Replies from prospects that nobody answered. Reads the replies since a date (14 days before now by default), keeps the categories that need an answer, and for each conversation reads its thread, or the lead's timeline when there is no thread, and reports it as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Returns the dropped replies longest waiting first with hours waiting, category, the campaign and its name, and the lead with their name, email and LinkedIn profile. A reply that could not be checked is counted in totals.unchecked, never reported as dropped. Costs one request per page of replies, one per conversation checked, and one per lead and per campaign among the dropped replies to name them, so at most about three times max_replies requests. totals.moreRepliesExist is true when max_replies left replies unread.",
3657
- inputSchema: input15,
4195
+ inputSchema: input16,
3658
4196
  key: "droppedReplies",
3659
4197
  cost: (values, price) => price.list("replies.list", values.max_replies) + price.upTo(values.max_replies) * (price.walk("messages.list") + (price.capabilities["leads.get"] === false ? 0 : price.one("leads.get")) + price.one("campaigns.get")),
3660
4198
  scales: "max_replies",
@@ -3671,8 +4209,8 @@ var droppedReplies = defineInsight({
3671
4209
  "This tool can read neither a conversation nor a lead's timeline, so no reply could be checked."
3672
4210
  );
3673
4211
  }
3674
- const listed = await readReplies(context, since, values.max_replies);
3675
- const read = listed.items;
4212
+ const listed2 = await readReplies(context, since, values.max_replies);
4213
+ const read = listed2.items;
3676
4214
  const replies2 = read.filter(
3677
4215
  (reply) => reply.sentAt === null || Date.parse(reply.sentAt) >= Date.parse(since)
3678
4216
  );
@@ -3720,7 +4258,7 @@ var droppedReplies = defineInsight({
3720
4258
  answered,
3721
4259
  conversations: conversations.length,
3722
4260
  dropped: dropped.length,
3723
- moreRepliesExist: listed.capped,
4261
+ moreRepliesExist: listed2.capped,
3724
4262
  repliesRead: read.length,
3725
4263
  skippedAuto: wanted.length - kept.length,
3726
4264
  skippedByCategory: replies2.length - wanted.length,
@@ -3734,6 +4272,42 @@ var droppedReplies = defineInsight({
3734
4272
 
3735
4273
  // src/insights/people/hot-leads.ts
3736
4274
  import { z as z20 } from "zod";
4275
+
4276
+ // src/insights/people/auto-replies.ts
4277
+ var AUTO_CHECK_REPLIES = 200;
4278
+ var refsOf2 = (lead) => lead.email === null ? [lead.ref] : [lead.ref, makeRef(lead.provider, lead.workspaceId, lead.email)];
4279
+ var autoOnlyRefs = async (context, campaign, leads) => {
4280
+ const { outbound } = context;
4281
+ const replied = leads.filter(
4282
+ (lead) => (lead.engagement?.replies ?? 0) > 0 || lead.replied === true
4283
+ );
4284
+ if (replied.length === 0 || !outbound.capabilities["replies.list"]) {
4285
+ return /* @__PURE__ */ new Set();
4286
+ }
4287
+ const replies2 = await context.all(
4288
+ campaign === null ? outbound.replies.listAll({ max: AUTO_CHECK_REPLIES }) : outbound.campaign(campaign).replies.listAll({ max: AUTO_CHECK_REPLIES }),
4289
+ {
4290
+ input: null,
4291
+ max: AUTO_CHECK_REPLIES,
4292
+ what: "replies read to tell automatic replies from people"
4293
+ }
4294
+ );
4295
+ const automatic = /* @__PURE__ */ new Set();
4296
+ const human = /* @__PURE__ */ new Set();
4297
+ for (const reply of replies2) {
4298
+ if (reply.leadRef !== null) {
4299
+ (reply.isAuto === true ? automatic : human).add(reply.leadRef);
4300
+ }
4301
+ }
4302
+ return new Set(
4303
+ replied.flatMap((lead) => {
4304
+ const refs = refsOf2(lead);
4305
+ return refs.some((ref) => automatic.has(ref)) && !refs.some((ref) => human.has(ref)) ? refs : [];
4306
+ })
4307
+ );
4308
+ };
4309
+
4310
+ // src/insights/people/hot-leads.ts
3737
4311
  var DAY2 = 864e5;
3738
4312
  var RECENT_REPLIES = 100;
3739
4313
  var NOT_ENGAGED = /* @__PURE__ */ new Set([
@@ -3742,7 +4316,7 @@ var NOT_ENGAGED = /* @__PURE__ */ new Set([
3742
4316
  "unsubscribe"
3743
4317
  ]);
3744
4318
  var weight = (value, what) => z20.number().min(0).default(value).describe(what);
3745
- var input16 = z20.object({
4319
+ var input17 = z20.object({
3746
4320
  campaign: z20.string().min(1).nullable().default(null).describe(
3747
4321
  "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3748
4322
  ),
@@ -3764,10 +4338,10 @@ var input16 = z20.object({
3764
4338
  weight_reply: weight(10, "Points for each reply, up to count_cap")
3765
4339
  });
3766
4340
  var capped = (count2, points, cap) => count2 === null ? null : Math.min(count2, cap) * points;
3767
- var saidNo = (lead, labels) => !isAutoReplied(lead) && isNegative(lead) && isPositive(lead.interest, labels) !== true;
3768
- var repliesDiscounted = (lead, labels) => isAutoReplied(lead) || saidNo(lead, labels);
4341
+ var saidNo = (lead, values) => !values.automatic(lead) && isNegative(lead) && isPositive(lead.interest, values.positive_labels) !== true;
4342
+ var repliesDiscounted = (lead, values) => values.automatic(lead) || saidNo(lead, values);
3769
4343
  var engagementParts = (lead, values) => {
3770
- const unwanted = saidNo(lead, values.positive_labels);
4344
+ const unwanted = saidNo(lead, values);
3771
4345
  return {
3772
4346
  clicks: capped(
3773
4347
  lead.engagement?.clicks ?? null,
@@ -3784,7 +4358,7 @@ var engagementParts = (lead, values) => {
3784
4358
  var partsOf = (lead, values, now) => {
3785
4359
  const engagement = lead.engagement ?? null;
3786
4360
  const positive = isPositive(lead.interest, values.positive_labels);
3787
- const automatic = repliesDiscounted(lead, values.positive_labels);
4361
+ const automatic = repliesDiscounted(lead, values);
3788
4362
  const counted2 = engagement?.replies ?? (lead.replied === true ? 1 : null);
3789
4363
  const replies2 = automatic && counted2 !== null ? 0 : counted2;
3790
4364
  const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
@@ -3799,15 +4373,20 @@ var partsOf = (lead, values, now) => {
3799
4373
  replies: capped(replies2, values.weight_reply, values.count_cap)
3800
4374
  };
3801
4375
  };
3802
- var discountedReason = (lead) => isAutoReplied(lead) ? `marked ${lead.interest ?? "out of office"}, so replies earn nothing` : `marked ${lead.interest ?? "not interested"}, so it earns no points`;
4376
+ var discountedReason = (lead, values) => {
4377
+ if (isAutoReplied(lead)) {
4378
+ return `marked ${lead.interest ?? "out of office"}, so replies earn nothing`;
4379
+ }
4380
+ return values.automatic(lead) ? "every reply read was automatic, so replies earn nothing" : `marked ${lead.interest ?? "not interested"}, so it earns no points`;
4381
+ };
3803
4382
  var counted = (points, amount, what) => (points ?? 0) > 0 ? plural(amount ?? 0, what) : null;
3804
- var reasonOf = (lead, parts, now, labels) => {
4383
+ var reasonOf = (lead, parts, now, values) => {
3805
4384
  const engagement = lead.engagement ?? null;
3806
- const automatic = repliesDiscounted(lead, labels);
4385
+ const automatic = repliesDiscounted(lead, values);
3807
4386
  const repliedAt = automatic ? null : engagement?.lastRepliedAt ?? null;
3808
4387
  const facts = [
3809
4388
  (parts.interest ?? 0) > 0 ? `marked ${lead.interest}` : null,
3810
- automatic ? discountedReason(lead) : null,
4389
+ automatic ? discountedReason(lead, values) : null,
3811
4390
  (parts.replies ?? 0) > 0 ? `replied ${plural(engagement?.replies ?? 1, "time")}` : null,
3812
4391
  repliedAt === null ? null : `last reply ${plural(Math.floor(Math.max(0, now - Date.parse(repliedAt)) / DAY2), "day")} ago`,
3813
4392
  counted(parts.clicks, engagement?.clicks, "click"),
@@ -3831,7 +4410,7 @@ var toHotLead = (lead, values, now) => {
3831
4410
  name: nameOf(lead),
3832
4411
  opens: lead.engagement?.opens ?? null,
3833
4412
  parts,
3834
- reason: reasonOf(lead, parts, now, values.positive_labels),
4413
+ reason: reasonOf(lead, parts, now, values),
3835
4414
  replies: lead.engagement?.replies ?? null,
3836
4415
  score: round(score) ?? 0,
3837
4416
  status: lead.status,
@@ -3878,13 +4457,13 @@ var repliedPastCap = async (context, values, read) => {
3878
4457
  what: "recent replies looked through for leads past max_leads"
3879
4458
  }
3880
4459
  );
3881
- const listed = new Set(read.map((lead) => lead.ref));
4460
+ const listed2 = new Set(read.flatMap((lead) => refsOf2(lead)));
3882
4461
  const refs = replies2.filter(
3883
4462
  (reply) => reply.isAuto !== true && !NOT_ENGAGED.has(reply.category) && reply.sentAt !== null && Date.parse(reply.sentAt) >= since && (values.campaign === null || reply.campaignRef === values.campaign)
3884
4463
  ).toSorted(
3885
4464
  (left, right) => (right.sentAt ?? "").localeCompare(left.sentAt ?? "")
3886
4465
  ).flatMap(
3887
- (reply) => reply.leadRef === null || listed.has(reply.leadRef) ? [] : [reply.leadRef]
4466
+ (reply) => reply.leadRef === null || listed2.has(reply.leadRef) ? [] : [reply.leadRef]
3888
4467
  );
3889
4468
  const found = await readByRef(
3890
4469
  context,
@@ -3898,18 +4477,18 @@ var repliedPastCap = async (context, values, read) => {
3898
4477
  var repliesOf = (lead) => lead.engagement?.replies ?? (lead.replied === true ? 1 : 0);
3899
4478
  var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3900
4479
  var hotLeads = defineInsight({
3901
- description: "Who to call first: leads ranked by a score built from what the vendor reports, namely a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign (an unknown one is refused with NotFound), or none to rank every lead the tool lists. A lead the vendor labels out-of-office or bounced (its interest category, or a label reading out of office) earns no reply or recency points, since a vendor's reply count may include automatic replies; a lead it labels negative (the negative or unsubscribe category, or a label reading not interested, wrong person, unsubscribed or do not contact) earns no points at all, from clicks and opens either, and is listed after every lead with a score above 0 while limit leaves room; its reason names the label. Costs one request per page of leads read (max_leads sets the ceiling). When max_leads stops the listing with more leads left, totals.moreLeadsExist is true and it also reads up to 100 replies from the last recency_days days and one request per replied lead the listing missed, at most limit of them, so engaged leads past the cap are still ranked. A part that is null means the vendor does not report that signal.",
3902
- inputSchema: input16,
4480
+ 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, and so does a lead whose every reply read is flagged automatic (isAuto, from the vendor or a fixed rule), for which it reads up to 200 of the newest replies, the campaign's when one is given, once a lead has replies; both are counted in totals.autoReplied; 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.",
4481
+ inputSchema: input17,
3903
4482
  key: "hotLeads",
3904
- cost: (values, price) => price.list("leads.list", values.max_leads) + (values.campaign === null ? 0 : price.upTo(1) * price.one("campaigns.get")) + (price.capabilities["replies.list"] === false || price.capabilities["leads.get"] === false ? 0 : price.upTo(1) * (price.list("replies.list", 100) + price.upTo(values.limit) * price.one("leads.get"))),
4483
+ 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 ? 0 : price.upTo(1) * price.list("replies.list", AUTO_CHECK_REPLIES)) + (price.capabilities["replies.list"] === false || price.capabilities["leads.get"] === false ? 0 : price.upTo(1) * (price.list("replies.list", 100) + price.upTo(values.limit) * price.one("leads.get"))),
3905
4484
  scales: "max_leads",
3906
4485
  name: "hot_leads",
3907
4486
  needs: [],
3908
4487
  next: "Use person_summary with a lead's ref, email address or LinkedIn profile to read the conversation before calling.",
3909
4488
  run: async (context, values) => {
3910
- const listed = await listLeads(context, values);
3911
- const extra = listed.capped ? await repliedPastCap(context, values, listed.leads) : [];
3912
- const leads = [...listed.leads, ...extra];
4489
+ const listed2 = await listLeads(context, values);
4490
+ const extra = listed2.capped ? await repliedPastCap(context, values, listed2.leads) : [];
4491
+ const leads = [...listed2.leads, ...extra];
3913
4492
  noteEngagement(
3914
4493
  context,
3915
4494
  leads,
@@ -3918,23 +4497,32 @@ var hotLeads = defineInsight({
3918
4497
  const open = leads.filter(
3919
4498
  (lead) => lead.unsubscribed !== true && lead.bounced !== true
3920
4499
  );
3921
- const scored = open.flatMap((lead) => toHotLead(lead, values, context.now));
3922
- const hot = scored.filter((lead) => lead.score > 0).toSorted(hottestFirst);
3923
- const negative = open.filter(
3924
- (lead) => saidNo(lead, values.positive_labels)
4500
+ const autoOnly = await autoOnlyRefs(
4501
+ context,
4502
+ values.campaign,
4503
+ open.filter((lead) => !isAutoReplied(lead))
4504
+ );
4505
+ const scoring = {
4506
+ ...values,
4507
+ automatic: (lead) => isAutoReplied(lead) || autoOnly.has(lead.ref)
4508
+ };
4509
+ const scored = open.flatMap(
4510
+ (lead) => toHotLead(lead, scoring, context.now)
3925
4511
  );
4512
+ const hot = scored.filter((lead) => lead.score > 0).toSorted(hottestFirst);
4513
+ const negative = open.filter((lead) => saidNo(lead, scoring));
3926
4514
  const refused = new Set(negative.map((lead) => lead.ref));
3927
4515
  const after = scored.filter((lead) => lead.score <= 0 && refused.has(lead.lead)).toSorted(hottestFirst);
3928
4516
  const answer = {
3929
4517
  leads: [...hot, ...after].slice(0, values.limit),
3930
4518
  totals: {
3931
4519
  autoReplied: open.filter(
3932
- (lead) => isAutoReplied(lead) && repliesOf(lead) > 0
4520
+ (lead) => scoring.automatic(lead) && repliesOf(lead) > 0
3933
4521
  ).length,
3934
4522
  excluded: leads.length - open.length,
3935
4523
  fromReplies: extra.length,
3936
4524
  hot: hot.length,
3937
- moreLeadsExist: listed.capped,
4525
+ moreLeadsExist: listed2.capped,
3938
4526
  negative: negative.length,
3939
4527
  leadsRead: leads.length,
3940
4528
  scored: scored.length,
@@ -3949,13 +4537,23 @@ var hotLeads = defineInsight({
3949
4537
  import { z as z21 } from "zod";
3950
4538
 
3951
4539
  // src/insights/people/find.ts
4540
+ var EMAIL = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/u;
4541
+ var DOMAIN2 = /^@?[^\s@/:]+(?:\.[^\s@/:.]+)+$/u;
4542
+ var bare = (identifier) => identifier.trim().replace(/^mailto:/iu, "");
3952
4543
  var personKey = (identifier) => {
3953
- const value = identifier.trim();
4544
+ const value = bare(identifier);
3954
4545
  const slug = profileSlug(value);
3955
4546
  if (slug !== null) {
3956
4547
  return `linkedin:${slug}`;
3957
4548
  }
3958
- return value.includes("@") && !value.includes(" ") ? `email:${value.toLowerCase()}` : null;
4549
+ return EMAIL.test(value) ? `email:${value.toLowerCase()}` : null;
4550
+ };
4551
+ var notAPerson = (identifier) => {
4552
+ const value = bare(identifier);
4553
+ if (DOMAIN2.test(value)) {
4554
+ return `"${value}" is a company domain, not a person. Use account_summary for a company domain`;
4555
+ }
4556
+ return value.includes("@") ? `"${value}" is not a valid email address` : "Give an email address, a LinkedIn profile URL or a lead ref";
3959
4557
  };
3960
4558
  var keysOfLead = (lead) => {
3961
4559
  const slug = profileSlug(lead.linkedinUrl);
@@ -4023,11 +4621,9 @@ var startFrom = async (context, identifier, { hash, masked }) => {
4023
4621
  };
4024
4622
  }
4025
4623
  if (!isLeadRef(identifier)) {
4026
- throw new OutboundError(
4027
- "Invalid",
4028
- "Give an email address, a LinkedIn profile URL or a lead ref",
4029
- { provider: outbound.provider }
4030
- );
4624
+ throw new OutboundError("Invalid", notAPerson(identifier), {
4625
+ provider: outbound.provider
4626
+ });
4031
4627
  }
4032
4628
  const instead = hash === void 0 ? null : "a lead's identifiers are hashed on its record, so give the email address or LinkedIn profile URL instead";
4033
4629
  if (masked.length === 2) {
@@ -4060,10 +4656,18 @@ var carries = (lead, key, start) => {
4060
4656
  }
4061
4657
  return keysOfLead(lead).includes(key);
4062
4658
  };
4659
+ var noteNoProfiles = (context, keys) => {
4660
+ if (context.outbound.fields.lead?.linkedinUrl === false && keys.some((key) => kindOf(key) === "linkedin")) {
4661
+ context.note(
4662
+ `${context.outbound.provider} leads have no LinkedIn field, so a LinkedIn profile finds no one there; search by email instead.`
4663
+ );
4664
+ }
4665
+ };
4063
4666
  var findPerson = async (context, identifier, maxRecords) => {
4064
4667
  const lookup = lookupOf(context.outbound);
4065
4668
  const { masked } = lookup;
4066
4669
  const start = await startFrom(context, identifier, lookup);
4670
+ noteNoProfiles(context, start.keys);
4067
4671
  if (masked.length > 0) {
4068
4672
  context.partial(
4069
4673
  `The redact plugin masks ${maskedWords(masked)}, so records found only under that identifier were not linked.`
@@ -4114,7 +4718,10 @@ var findPerson = async (context, identifier, maxRecords) => {
4114
4718
  };
4115
4719
 
4116
4720
  // src/insights/people/lead-collisions.ts
4117
- var input17 = z21.object({
4721
+ var input18 = z21.object({
4722
+ include_past: z21.boolean().default(false).describe(
4723
+ "Also report a person in two or more campaigns of whom fewer than two memberships are still active, for example one who completed one campaign and is now in another. By default only people active in two or more campaigns at once are reported."
4724
+ ),
4118
4725
  max_campaigns: z21.number().int().min(1).max(200).default(20).describe(
4119
4726
  "The most campaigns to read. Each costs one request per page of its leads."
4120
4727
  ),
@@ -4158,23 +4765,42 @@ var toCollision = (group) => {
4158
4765
  const channels = [...new Set(campaigns.map((each) => each.channel))];
4159
4766
  const scope = providers.length > 1 ? "across_tools" : "within_tool";
4160
4767
  const identifiers = [...group.keys].toSorted();
4768
+ const active = campaigns.filter((each) => each.leadStatus === "active");
4161
4769
  return [
4162
4770
  {
4163
4771
  campaignCount: campaigns.length,
4164
4772
  campaigns,
4165
4773
  channels,
4166
- finding: scope === "across_tools" ? `${shownKey(identifiers[0] ?? "")} is in ${campaigns.length} campaigns across ${providers.join(" and ")} (${channels.join(" and ")}).` : `${shownKey(identifiers[0] ?? "")} is in ${campaigns.length} ${providers[0]} campaigns at once.`,
4774
+ finding: findingOf2(shownKey(identifiers[0] ?? ""), campaigns, {
4775
+ channels,
4776
+ providers
4777
+ }),
4167
4778
  identifiers,
4168
4779
  providers,
4169
4780
  scope,
4170
- stillActive: campaigns.filter((each) => each.leadStatus === "active").length
4781
+ stillActive: active.length
4171
4782
  }
4172
4783
  ];
4173
4784
  };
4174
- var worstFirst = (left, right) => right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
4785
+ var listed = (parts) => parts.length < 2 ? parts[0] ?? "" : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
4786
+ var named3 = (campaigns) => listed(campaigns.map((each) => `"${each.campaignName}"`));
4787
+ var withStatus = (campaigns) => listed(
4788
+ campaigns.map((each) => `"${each.campaignName}" (${each.leadStatus})`)
4789
+ );
4790
+ var findingOf2 = (who, campaigns, tools) => {
4791
+ const active = campaigns.filter((each) => each.leadStatus === "active");
4792
+ const past = campaigns.filter((each) => each.leadStatus !== "active");
4793
+ if (active.length >= 2) {
4794
+ const where = tools.providers.length > 1 ? `campaigns across ${tools.providers.join(" and ")} (${tools.channels.join(" and ")})` : `${tools.providers[0]} campaigns`;
4795
+ const also = past.length === 0 ? "" : `, and was in ${withStatus(past)}`;
4796
+ return `${who} is in ${active.length} ${where} at once${also}.`;
4797
+ }
4798
+ return active.length === 0 ? `${who} was in ${withStatus(past)}, and is active in none of them now.` : `${who} was in ${withStatus(past)} and is now active in ${named3(active)}.`;
4799
+ };
4800
+ var worstFirst = (left, right) => right.stillActive - left.stillActive || right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
4175
4801
  var leadCollisions = defineInsight({
4176
- description: "People who are in two or more campaigns at once, so they get overlapping outreach. Reads the campaigns in the given statuses (active by default) and their leads, matches people by exact email address or LinkedIn profile, and returns each person with their campaigns, channel and tool, most campaigns first. A collision across tools (for example email in one and LinkedIn in another) is marked across_tools; one inside a tool is within_tool. Costs one request per page of campaigns plus one per page of each campaign's leads; the caps make the answer incomplete rather than slow.",
4177
- inputSchema: input17,
4802
+ description: "People who are in two or more campaigns at once, so they get overlapping outreach. Reads the campaigns in the given statuses (active by default) and their leads, matches people by exact email address or LinkedIn profile, and returns each person with their campaigns, channel and tool, most active campaigns first. By default a person counts only when their own status is active in two or more of the campaigns; include_past also reports people who finished, replied to or left one campaign and are in another, counted in totals.pastOverlaps either way. A collision across tools (for example email in one and LinkedIn in another) is marked across_tools; one inside a tool is within_tool. Costs one request per page of campaigns plus one per page of each campaign's leads; the caps make the answer incomplete rather than slow.",
4803
+ inputSchema: input18,
4178
4804
  key: "leadCollisions",
4179
4805
  // A masked address is the same text for every lead, so every lead would
4180
4806
  // collide with every other. A hashed one still tells people apart.
@@ -4205,7 +4831,9 @@ var leadCollisions = defineInsight({
4205
4831
  return leads.map((lead) => ({ campaign, lead }));
4206
4832
  });
4207
4833
  const entries = perCampaign.flat();
4208
- const collisions = groupPeople(entries).flatMap(toCollision).toSorted(worstFirst);
4834
+ const overlaps = groupPeople(entries).flatMap(toCollision);
4835
+ const pastOverlaps = overlaps.filter((each) => each.stillActive < 2).length;
4836
+ const collisions = overlaps.filter((each) => values.include_past || each.stillActive >= 2).toSorted(worstFirst);
4209
4837
  const acrossTools = collisions.filter(
4210
4838
  (each) => each.scope === "across_tools"
4211
4839
  ).length;
@@ -4215,10 +4843,12 @@ var leadCollisions = defineInsight({
4215
4843
  acrossTools,
4216
4844
  campaignsRead: campaigns.length,
4217
4845
  collisions: collisions.length,
4846
+ concurrent: collisions.filter((each) => each.stillActive >= 2).length,
4218
4847
  leadsRead: entries.length,
4219
4848
  leadsWithoutIdentifier: entries.filter(
4220
4849
  (entry) => keysOfLead(entry.lead).length === 0
4221
4850
  ).length,
4851
+ pastOverlaps,
4222
4852
  withinTool: collisions.length - acrossTools
4223
4853
  }
4224
4854
  };
@@ -4228,7 +4858,7 @@ var leadCollisions = defineInsight({
4228
4858
 
4229
4859
  // src/insights/people/person-summary.ts
4230
4860
  import { z as z22 } from "zod";
4231
- var input18 = z22.object({
4861
+ var input19 = z22.object({
4232
4862
  max_campaigns: z22.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
4233
4863
  person: z22.string().min(3).describe(
4234
4864
  "The person's email address or LinkedIn profile URL, or a lead ref as the other people insights return"
@@ -4237,6 +4867,7 @@ var input18 = z22.object({
4237
4867
  var times2 = (messages, direction) => messages.flatMap(
4238
4868
  (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
4239
4869
  );
4870
+ var isAutoMessage = (message) => message.direction === "in" && message.isAuto === true;
4240
4871
  var repliedSteps = (lead, messages) => {
4241
4872
  const steps = /* @__PURE__ */ new Set();
4242
4873
  let lastSent = null;
@@ -4247,15 +4878,19 @@ var repliedSteps = (lead, messages) => {
4247
4878
  steps.add(message.stepIndex ?? lastSent ?? 0);
4248
4879
  }
4249
4880
  }
4250
- const named3 = lead.engagement?.repliedStepIndex ?? null;
4251
- if (named3 !== null) {
4252
- steps.add(named3);
4881
+ const named4 = lead.engagement?.repliedStepIndex ?? null;
4882
+ if (named4 !== null) {
4883
+ steps.add(named4);
4253
4884
  }
4254
4885
  return [...steps].toSorted((left, right) => left - right);
4255
4886
  };
4256
4887
  var activityOf = (lead, messages) => {
4257
4888
  const sent = times2(messages, "out");
4258
- const received = times2(messages, "in");
4889
+ const received = times2(
4890
+ messages.filter((message) => !isAutoMessage(message)),
4891
+ "in"
4892
+ );
4893
+ const automatic = messages.filter(isAutoMessage).length;
4259
4894
  const counted2 = lead.engagement;
4260
4895
  return {
4261
4896
  firstContactedAt: sent[0] ?? null,
@@ -4267,11 +4902,26 @@ var activityOf = (lead, messages) => {
4267
4902
  // A vendor's thread can hold fewer messages than were sent; the last
4268
4903
  // step sent (counted from 0) is then the better count.
4269
4904
  messagesSent: Math.max(sent.length, (counted2?.stepIndex ?? -1) + 1),
4270
- // A vendor that keeps no thread still counts replies on the lead.
4271
- replies: Math.max(received.length, counted2?.replies ?? 0),
4905
+ automatic,
4906
+ // A vendor that keeps no thread still counts replies on the lead, and
4907
+ // that count can include the automatic replies the thread holds.
4908
+ replies: Math.max(received.length, (counted2?.replies ?? 0) - automatic),
4272
4909
  threadIsShort: sent.length < (counted2?.stepIndex ?? -1) + 1
4273
4910
  };
4274
4911
  };
4912
+ var noteAutomatic = (context, lead, replies2, flagged) => {
4913
+ if (isAutoReplied(lead)) {
4914
+ if (replies2 > 0) {
4915
+ context.note(
4916
+ "A record the vendor labels out-of-office or bounced had replies; they were automatic, so they are not counted as replies."
4917
+ );
4918
+ }
4919
+ } else if (flagged > 0) {
4920
+ context.note(
4921
+ "A record's thread held replies flagged automatic, by the vendor or by a fixed rule; they are not counted as replies."
4922
+ );
4923
+ }
4924
+ };
4275
4925
  var timelineOf = async (context, timelines, lead) => {
4276
4926
  let all = timelines.get(lead.ref);
4277
4927
  if (all === void 0) {
@@ -4289,19 +4939,19 @@ var summarize2 = async (context, timelines, lead) => {
4289
4939
  timelineOf(context, timelines, lead),
4290
4940
  lead.campaignRef === null ? null : outbound.campaigns.get(lead.campaignRef).then(context.one)
4291
4941
  ]);
4292
- const { threadIsShort, ...counted2 } = activityOf(lead, messages);
4293
- const autoReplied = isAutoReplied(lead);
4942
+ const { automatic, threadIsShort, ...counted2 } = activityOf(lead, messages);
4943
+ const autoReplied = isAutoReplied(lead) || automatic > 0 && counted2.replies === 0;
4294
4944
  const activity = autoReplied ? { ...counted2, lastRepliedAt: null, replies: 0 } : counted2;
4295
- if (autoReplied && counted2.replies > 0) {
4296
- context.note(
4297
- "A record the vendor labels out-of-office or bounced had replies; they were automatic, so they are not counted as replies."
4298
- );
4299
- }
4945
+ noteAutomatic(context, lead, counted2.replies + automatic, automatic);
4300
4946
  if (threadIsShort) {
4301
4947
  context.note(
4302
4948
  "A thread held fewer sent messages than the lead's last step, so messages sent is counted from the last step."
4303
4949
  );
4304
4950
  }
4951
+ const steps = autoReplied ? [] : repliedSteps(
4952
+ lead,
4953
+ messages.filter((message) => !isAutoMessage(message))
4954
+ );
4305
4955
  return {
4306
4956
  ...activity,
4307
4957
  campaign: lead.campaignRef,
@@ -4310,11 +4960,17 @@ var summarize2 = async (context, timelines, lead) => {
4310
4960
  channel: campaign?.channel ?? (lead.email === null ? "linkedin" : "email"),
4311
4961
  interest: lead.interest,
4312
4962
  lead: lead.ref,
4313
- leadStatus: lead.status,
4963
+ // The vendor's "replied" can count an out-of-office; the person did not reply.
4964
+ leadStatus: autoReplied && lead.status === "replied" ? lead.progress : lead.status,
4314
4965
  provider: lead.provider,
4315
4966
  autoReplied,
4316
4967
  replied: !autoReplied && (activity.replies > 0 || lead.replied === true),
4317
- repliedSteps: autoReplied ? [] : repliedSteps(lead, messages)
4968
+ lastStepIndex: activity.lastStep,
4969
+ lastStepNumber: activity.lastStep === null ? null : activity.lastStep + 1,
4970
+ repliedStepIndexes: steps,
4971
+ repliedStepNumbers: steps.map((index) => index + 1),
4972
+ repliedSteps: steps,
4973
+ vendorLeadStatus: lead.status
4318
4974
  };
4319
4975
  };
4320
4976
  var byChannel2 = (campaigns) => {
@@ -4332,8 +4988,8 @@ var byChannel2 = (campaigns) => {
4332
4988
  return channels;
4333
4989
  };
4334
4990
  var personSummary = defineInsight({
4335
- description: "Everything about one person across campaigns and channels, from their email address, LinkedIn profile or a lead ref: each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. A record the vendor labels out-of-office or bounced counts no replies, since they were automatic. Costs one lookup per identifier, one request to read a lead ref, then up to 2 requests per campaign.",
4336
- inputSchema: input18,
4991
+ 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, and a reply in the thread flagged automatic (isAuto, from the vendor or a fixed rule) is not counted either. Costs one lookup per identifier, one request to read a lead ref, then up to 2 requests per campaign.",
4992
+ inputSchema: input19,
4337
4993
  key: "personSummary",
4338
4994
  cost: (values, price) => (isLeadRef(values.person) ? price.one("leads.get") + price.upTo(2) * price.lookup(values.max_campaigns) : price.lookup(values.max_campaigns) + price.upTo(1) * price.lookup(values.max_campaigns)) + price.upTo(values.max_campaigns) * (price.one("campaigns.get") + price.walk("messages.list")),
4339
4995
  scales: "max_campaigns",
@@ -4379,85 +5035,63 @@ var personSummary = defineInsight({
4379
5035
 
4380
5036
  // src/insights/people/personalization-gaps.ts
4381
5037
  import { z as z23 } from "zod";
4382
- var input19 = z23.object({
4383
- campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
5038
+ var input20 = z23.object({
5039
+ campaign: z23.string().min(1).describe("The campaign's ref (provider:workspace:id) or name"),
4384
5040
  limit: z23.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
4385
5041
  max_leads: z23.number().int().min(1).max(2e4).default(500).describe(
4386
5042
  "The most leads to check. A vendor request returns about 50 to 100 leads."
4387
5043
  )
4388
5044
  });
4389
- var PATTERNS = [
4390
- /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
4391
- /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
4392
- /%(?<name>[A-Za-z_][\w-]*)%/gu
4393
- ];
4394
- var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
4395
- var BUILTINS = /* @__PURE__ */ new Map([
4396
- ["company", (lead) => lead.company],
4397
- ["companyname", (lead) => lead.company],
4398
- ["email", (lead) => lead.email],
4399
- ["firstname", (lead) => lead.firstName],
4400
- ["jobtitle", (lead) => lead.title],
4401
- ["lastname", (lead) => lead.lastName],
4402
- ["title", (lead) => lead.title]
4403
- ]);
4404
5045
  var FIELDS = ["subject", "body"];
4405
- var variablesIn = (text) => PATTERNS.flatMap(
4406
- (pattern) => [...text.matchAll(pattern)].map((match) => ({
4407
- fallback: match.groups?.fallback !== void 0,
4408
- name: match.groups?.name ?? ""
4409
- }))
4410
- );
4411
5046
  var findVariables = (sequence2) => {
4412
5047
  const found = /* @__PURE__ */ new Map();
4413
5048
  const texts = sequence2.steps.flatMap(
4414
5049
  (step) => step.variants.flatMap(
4415
5050
  (variant) => FIELDS.map((field) => ({
4416
5051
  field,
4417
- step: step.index,
5052
+ stepIndex: step.index,
4418
5053
  text: variant[field] ?? "",
4419
5054
  variant: variant.variantKey
4420
5055
  }))
4421
5056
  )
4422
5057
  );
4423
- for (const { field, step, text, variant } of texts) {
5058
+ for (const { field, stepIndex, text, variant } of texts) {
4424
5059
  for (const { fallback, name } of variablesIn(text)) {
4425
5060
  const entry = found.get(keyOf(name)) ?? { name, uses: [] };
4426
- entry.uses.push({ fallback, field, step, variant });
5061
+ entry.uses.push({
5062
+ ...stepAt(stepIndex),
5063
+ fallback: fallback !== null,
5064
+ field,
5065
+ variant
5066
+ });
4427
5067
  found.set(keyOf(name), entry);
4428
5068
  }
4429
5069
  }
4430
5070
  return found;
4431
5071
  };
4432
- var filled = (value) => value !== null && value.trim() !== "";
4433
- var valuesOf = (lead) => /* @__PURE__ */ new Set([
4434
- ...[...BUILTINS].flatMap(
4435
- ([key, read]) => filled(read(lead)) ? [key] : []
4436
- ),
4437
- ...Object.entries(lead.custom).flatMap(
4438
- ([key, value]) => filled(value) ? [keyOf(key)] : []
4439
- )
4440
- ]);
4441
5072
  var sourceOf = (key, customKeys) => {
4442
- if (BUILTINS.has(key)) {
5073
+ if (isBuiltin(key)) {
4443
5074
  return "builtin";
4444
5075
  }
4445
5076
  return customKeys.has(key) ? "custom" : "unknown";
4446
5077
  };
4447
- var toVariable = (key, { name, uses }, leads, customKeys) => {
4448
- const source = sourceOf(key, customKeys);
5078
+ var toVariable = (provider, key, { name, uses }, leads, customKeys) => {
5079
+ const sender = isSender(provider, key);
5080
+ const source = sender ? "unknown" : sourceOf(key, customKeys);
4449
5081
  const known2 = source !== "unknown";
4450
5082
  const needed = uses.some((use) => !use.fallback);
4451
5083
  const without = leads.filter((values) => !values.has(key)).length;
5084
+ const affected = known2 ? Number(needed) * without : null;
4452
5085
  return {
4453
5086
  key,
4454
5087
  variable: {
4455
- gap: known2 && needed,
4456
- leadsAffected: known2 ? Number(needed) * without : null,
5088
+ gap: affected !== null && affected > 0,
5089
+ leadsAffected: affected,
4457
5090
  leadsWithoutValue: known2 ? without : null,
4458
5091
  name,
5092
+ sender,
4459
5093
  source,
4460
- steps: [...new Set(uses.map((use) => use.step))].toSorted(
5094
+ steps: [...new Set(uses.map((use) => use.stepIndex))].toSorted(
4461
5095
  (left, right) => left - right
4462
5096
  ),
4463
5097
  uses
@@ -4479,8 +5113,8 @@ var missingOf = (lead, values, gaps) => {
4479
5113
  ];
4480
5114
  };
4481
5115
  var personalizationGaps = defineInsight({
4482
- description: "Leads in one campaign who will get broken copy because a merge variable has no value for them. Reads the campaign's sequence, finds every {{variable}}, {variable} and %variable% in subjects and bodies, and checks each lead for a value: first name, last name, company, title, email, or a custom field of the same name without regard to case, spaces, underscores or hyphens. Returns the variables with the steps that use them, how many leads each one affects, and the leads missing at least one. A variable with a fallback such as {{firstName|there}} is not a gap. A variable no lead has, such as a sender signature the tool fills in, is listed as unknown, not counted against leads. Costs one request for the sequence plus one per page of leads.",
4483
- inputSchema: input19,
5116
+ 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 the tool fills from the sending account, such as Instantly's {{accountSignature}}, is marked sender: true and left out of unknownVariables; any other variable no lead has is listed as unknown. Neither is counted against leads. Costs one request for the sequence plus one per page of leads.",
5117
+ inputSchema: input20,
4484
5118
  key: "personalizationGaps",
4485
5119
  cost: (values, price) => price.one("sequence.get") + price.upTo(1) * price.list("leads.list", values.max_leads),
4486
5120
  scales: "max_leads",
@@ -4505,13 +5139,19 @@ var personalizationGaps = defineInsight({
4505
5139
  leads.flatMap((lead) => Object.keys(lead.custom).map(keyOf))
4506
5140
  );
4507
5141
  const keyed = [...found].map(
4508
- ([key, entry]) => toVariable(key, entry, leads.map(valuesOf), customKeys)
5142
+ ([key, entry]) => toVariable(
5143
+ sequence2.provider,
5144
+ key,
5145
+ entry,
5146
+ leads.map(keysWithValue),
5147
+ customKeys
5148
+ )
4509
5149
  );
4510
5150
  const variables = keyed.map((each) => each.variable).toSorted(
4511
5151
  (left, right) => (right.leadsAffected ?? -1) - (left.leadsAffected ?? -1) || left.name.localeCompare(right.name)
4512
5152
  );
4513
5153
  const gaps = keyed.filter((each) => each.variable.gap);
4514
- const affected = leads.flatMap((lead) => missingOf(lead, valuesOf(lead), gaps)).toSorted(
5154
+ const affected = leads.flatMap((lead) => missingOf(lead, keysWithValue(lead), gaps)).toSorted(
4515
5155
  (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
4516
5156
  );
4517
5157
  const answer = {
@@ -4525,7 +5165,7 @@ var personalizationGaps = defineInsight({
4525
5165
  variables: variables.length
4526
5166
  },
4527
5167
  unknownVariables: variables.flatMap(
4528
- (each) => each.source === "unknown" ? [each.name] : []
5168
+ (each) => each.source === "unknown" && each.sender !== true ? [each.name] : []
4529
5169
  ),
4530
5170
  variables
4531
5171
  };
@@ -4535,7 +5175,15 @@ var personalizationGaps = defineInsight({
4535
5175
 
4536
5176
  // src/insights/people/suppression-check.ts
4537
5177
  import { z as z24 } from "zod";
4538
- var input20 = z24.object({
5178
+ var SENDABLE = [
5179
+ "active",
5180
+ "paused",
5181
+ "unknown"
5182
+ ];
5183
+ var input21 = z24.object({
5184
+ lead_statuses: z24.array(leadStatusSchema).min(1).default([...SENDABLE]).describe(
5185
+ "Only a matching lead in one of these states is a violation: active, paused, unknown (not yet started, or the tool does not say), completed, skipped (the tool decided never to send), replied, bounced or unsubscribed. Other matches are counted in totals.alreadyStopped. Defaults to the leads still being sent to."
5186
+ ),
4539
5187
  max_block_entries: z24.number().int().min(1).max(1e5).default(2e3).describe(
4540
5188
  "The most block list entries to read. A vendor request returns about 50 to 100."
4541
5189
  ),
@@ -4610,8 +5258,8 @@ var maskNote = (outbound) => {
4610
5258
  };
4611
5259
  var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
4612
5260
  var suppressionCheck = defineInsight({
4613
- description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. Returns each violation with the lead, the campaign, the entry and how it matched, counts per campaign, and how many block entries were read; totals.moreBlockEntriesExist is true when max_block_entries left entries unread, which were not checked. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
4614
- inputSchema: input20,
5261
+ description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. A match is a violation only when the lead's own status is in lead_statuses (active, paused or unknown by default, the leads still being sent to); a lead that already unsubscribed, bounced, replied or completed is counted in totals.alreadyStopped instead. Returns each violation with the lead, the campaign, the entry and how it matched, counts per campaign, and how many block entries were read; totals.moreBlockEntriesExist is true when max_block_entries left entries unread, which were not checked. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
5262
+ inputSchema: input21,
4615
5263
  key: "suppressionCheck",
4616
5264
  // A masked address is the same text for every lead, so nothing can match.
4617
5265
  // A hashed one still matches the same address on the list.
@@ -4622,14 +5270,14 @@ var suppressionCheck = defineInsight({
4622
5270
  needs: ["blocklist", "leads.byCampaign"],
4623
5271
  next: "Use person_summary with a violating lead's ref or email address to see what they were already sent.",
4624
5272
  run: async (context, values) => {
4625
- const listed = await readCappedFlag(
5273
+ const listed2 = await readCappedFlag(
4626
5274
  context,
4627
5275
  (cap) => context.outbound.blocklist.listAll({ max: cap }),
4628
5276
  values.max_block_entries,
4629
5277
  "block list entries",
4630
5278
  "max_block_entries"
4631
5279
  );
4632
- const entries = listed.items;
5280
+ const entries = listed2.items;
4633
5281
  const blocked = indexEntries(entries);
4634
5282
  const unmatched = maskNote(context.outbound);
4635
5283
  if (unmatched !== null) {
@@ -4640,8 +5288,10 @@ var suppressionCheck = defineInsight({
4640
5288
  values.statuses,
4641
5289
  values.max_campaigns
4642
5290
  );
5291
+ const sendable = new Set(values.lead_statuses);
4643
5292
  const violations = [];
4644
5293
  const byCampaign = [];
5294
+ let alreadyStopped = 0;
4645
5295
  const read = await mapConcurrent(campaigns, async (campaign) => ({
4646
5296
  campaign,
4647
5297
  ...await readCappedFlag(
@@ -4653,10 +5303,12 @@ var suppressionCheck = defineInsight({
4653
5303
  )
4654
5304
  }));
4655
5305
  for (const { campaign, items: leads } of read) {
4656
- const found = leads.flatMap((lead) => {
5306
+ const matched = leads.flatMap((lead) => {
4657
5307
  const hit = matchLead(lead, blocked);
4658
5308
  return hit === null ? [] : [toViolation(lead, campaign, hit)];
4659
5309
  });
5310
+ const found = matched.filter((each) => sendable.has(each.leadStatus));
5311
+ alreadyStopped += matched.length - found.length;
4660
5312
  violations.push(...found);
4661
5313
  byCampaign.push({
4662
5314
  campaign: campaign.ref,
@@ -4671,7 +5323,8 @@ var suppressionCheck = defineInsight({
4671
5323
  (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
4672
5324
  ),
4673
5325
  totals: {
4674
- blockEntriesNotChecked: listed.capped ? null : blocked.notChecked,
5326
+ alreadyStopped,
5327
+ blockEntriesNotChecked: listed2.capped ? null : blocked.notChecked,
4675
5328
  blockEntriesRead: entries.length,
4676
5329
  byMatch: {
4677
5330
  domain: matches.get("domain") ?? 0,
@@ -4680,7 +5333,7 @@ var suppressionCheck = defineInsight({
4680
5333
  },
4681
5334
  campaignsRead: campaigns.length,
4682
5335
  leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
4683
- moreBlockEntriesExist: listed.capped,
5336
+ moreBlockEntriesExist: listed2.capped,
4684
5337
  moreLeadsExist: read.some((each) => each.capped),
4685
5338
  violations: violations.length
4686
5339
  },
@@ -4705,20 +5358,20 @@ var PEOPLE_INSIGHTS = [
4705
5358
  import { z as z25 } from "zod";
4706
5359
 
4707
5360
  // src/insights/senders/read.ts
4708
- var readCapped2 = async (context, walk, max, what, input27) => {
4709
- const { items } = await readCapped(context, walk, { input: input27, max, what });
5361
+ var readCapped2 = async (context, walk, max, what, input28) => {
5362
+ const { items } = await readCapped(context, walk, { input: input28, max, what });
4710
5363
  return items;
4711
5364
  };
4712
5365
  var readCampaigns = async (context, statuses, max) => {
4713
5366
  const { items } = await readCampaignsIn(context, statuses, max);
4714
5367
  return items;
4715
5368
  };
4716
- var readCampaignSenders = (context, campaign, max, input27) => readCapped2(
5369
+ var readCampaignSenders = (context, campaign, max, input28) => readCapped2(
4717
5370
  context,
4718
5371
  (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
4719
5372
  max,
4720
5373
  `senders of campaign ${campaign.name}`,
4721
- input27
5374
+ input28
4722
5375
  );
4723
5376
  var readSenders = (context, max) => readCapped(context, (cap) => context.outbound.senders.listAll({ max: cap }), {
4724
5377
  input: "max_senders",
@@ -4760,25 +5413,22 @@ var countEach = (keys, count2) => (
4760
5413
  );
4761
5414
 
4762
5415
  // src/insights/senders/bounce-watch.ts
4763
- var maxBounceRate = z25.number().min(0).max(1);
4764
- var input21 = z25.object({
5416
+ var input22 = z25.object({
4765
5417
  ...rangeFields,
4766
5418
  include_senders: z25.boolean().default(true).describe(
4767
5419
  "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
4768
5420
  ),
4769
- max_bounce_rate: maxBounceRate.default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
5421
+ max_bounce_rate: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
4770
5422
  max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
4771
5423
  max_senders_per_campaign: z25.number().int().min(1).max(200).default(10).describe("The most senders to check for one campaign over the threshold"),
4772
5424
  min_sent: z25.number().int().min(0).default(100).describe(
4773
5425
  "A campaign or sender with fewer sends than this is too small to judge"
4774
5426
  ),
4775
- threshold: renamed("max_bounce_rate", maxBounceRate),
4776
5427
  statuses: statusesInput(["active"])
4777
5428
  });
4778
5429
  var countsOf2 = (bounced, sent) => ({
4779
5430
  ...measure2(bounced, sent),
4780
5431
  bounced,
4781
- interval: wilson(bounced, sent),
4782
5432
  sent
4783
5433
  });
4784
5434
  var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
@@ -4843,7 +5493,7 @@ var canCheckSenders = (context, wanted) => {
4843
5493
  };
4844
5494
  var bounceWatch = defineInsight({
4845
5495
  description: "Where bounces are too high: the campaigns whose bounce rate (bounced divided by sent) is over a threshold, worst first, each with bounced, sent, the rate and its Wilson interval, and the senders of each such campaign that are themselves over the threshold. Campaigns with too few sends to judge and campaigns with no reported bounce count are listed apart, never as clean. Use it daily, or when a domain's reputation is in doubt. Costs one listing of campaigns and 1 request per campaign, plus 1 listing and up to 1 request per sender for each campaign over the threshold. A null rate means nothing was sent.",
4846
- inputSchema: input21,
5496
+ inputSchema: input22,
4847
5497
  key: "bounceWatch",
4848
5498
  cost: (values, price) => {
4849
5499
  const campaigns = price.campaigns(values.max_campaigns);
@@ -4879,7 +5529,6 @@ var bounceWatch = defineInsight({
4879
5529
  const entry = {
4880
5530
  campaign: campaign.ref,
4881
5531
  campaignName: campaign.name,
4882
- name: campaign.name,
4883
5532
  status: campaign.status
4884
5533
  };
4885
5534
  if (counts === null) {
@@ -4933,7 +5582,6 @@ var bounceWatch = defineInsight({
4933
5582
  minSent,
4934
5583
  over: over.toSorted(byRate2),
4935
5584
  sendersRead: withSenders ? seen.read.size : null,
4936
- threshold,
4937
5585
  tooFewSends: tooFewSends.toSorted(byRate2),
4938
5586
  totals: {
4939
5587
  bounced,
@@ -4953,13 +5601,11 @@ var bounceWatch = defineInsight({
4953
5601
 
4954
5602
  // src/insights/senders/domain-health.ts
4955
5603
  import { z as z26 } from "zod";
4956
- var maxSpamRate = z26.number().min(0).max(1);
4957
- var input22 = z26.object({
5604
+ var input23 = z26.object({
4958
5605
  max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
4959
- max_spam_rate: maxSpamRate.default(0.1).describe(
5606
+ max_spam_rate: z26.number().min(0).max(1).default(0.1).describe(
4960
5607
  "A domain whose warmup emails land in spam more often than this share is high risk"
4961
- ),
4962
- spam_rate_threshold: renamed("max_spam_rate", maxSpamRate)
5608
+ )
4963
5609
  });
4964
5610
  var RISK_ORDER = ["high", "medium", "low", "unknown"];
4965
5611
  var pooledWarmup = (checked) => {
@@ -4970,11 +5616,9 @@ var pooledWarmup = (checked) => {
4970
5616
  if (reported.length === 0) {
4971
5617
  return {
4972
5618
  ...measure2(null, null),
4973
- interval: null,
4974
5619
  mailboxes: 0,
4975
5620
  sent: null,
4976
- spam: null,
4977
- spamRate: null
5621
+ spam: null
4978
5622
  };
4979
5623
  }
4980
5624
  const sent = reported.reduce((sum, each) => sum + each.sent, 0);
@@ -4982,11 +5626,9 @@ var pooledWarmup = (checked) => {
4982
5626
  const measured2 = measure2(spam, sent);
4983
5627
  return {
4984
5628
  ...measured2,
4985
- interval: wilson(spam, sent),
4986
5629
  mailboxes: reported.length,
4987
5630
  sent,
4988
- spam,
4989
- spamRate: measured2.rate
5631
+ spam
4990
5632
  };
4991
5633
  };
4992
5634
  var missingChecks = (checked, warmup) => [
@@ -5057,7 +5699,7 @@ var seatRank = (seat) => {
5057
5699
  };
5058
5700
  var domainHealth = defineInsight({
5059
5701
  description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Costs one listing of senders plus 1 request per sender. A null count or rate means the vendor does not report it; a domain with no DNS record reported has the risk `unknown`, not `low`.",
5060
- inputSchema: input22,
5702
+ inputSchema: input23,
5061
5703
  key: "domainHealth",
5062
5704
  cost: (values, price) => price.list("senders.list", values.max_senders) + price.upTo(values.max_senders) * price.one("senders.health"),
5063
5705
  scales: "max_senders",
@@ -5219,7 +5861,7 @@ var readSends = async (context, campaigns, days, senders2, split) => {
5219
5861
  };
5220
5862
 
5221
5863
  // src/insights/senders/sender-capacity.ts
5222
- var input23 = z27.object({
5864
+ var input24 = z27.object({
5223
5865
  days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
5224
5866
  max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
5225
5867
  "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
@@ -5285,7 +5927,7 @@ var shortfallOf = (read) => {
5285
5927
  };
5286
5928
  var askOf = (reads) => {
5287
5929
  const limits = reads.map((read) => read.dailyLimit);
5288
- const withLimit = limits.filter((limit3) => limit3 !== null).length;
5930
+ const withLimit = limits.filter((limit2) => limit2 !== null).length;
5289
5931
  return {
5290
5932
  campaigns: reads.length,
5291
5933
  daily: total(limits),
@@ -5293,7 +5935,7 @@ var askOf = (reads) => {
5293
5935
  withoutLimit: reads.length - withLimit
5294
5936
  };
5295
5937
  };
5296
- var findingOf = (capacity, ask, sends) => {
5938
+ var findingOf3 = (capacity, ask, sends) => {
5297
5939
  if (capacity.daily === null) {
5298
5940
  return "No active sender reports a daily limit, so capacity is unknown.";
5299
5941
  }
@@ -5315,7 +5957,7 @@ var findingOf = (capacity, ask, sends) => {
5315
5957
  };
5316
5958
  var senderCapacity = defineInsight({
5317
5959
  description: "Whether the senders can send what the campaigns ask: total daily capacity (the daily limits of active senders added up), the total daily ask of active campaigns, the average messages sent per day over the last days, utilization, and the campaigns whose own senders cannot cover their daily limit. Use it before adding campaigns or when sends fall short. Costs one listing of senders and of active campaigns, then up to 2 requests per campaign and 1 for daily stats, plus 1 per inactive or unlimited sender with split_uncounted. Utilization counts only the sends of the senders in capacity. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
5318
- inputSchema: input23,
5960
+ inputSchema: input24,
5319
5961
  key: "senderCapacity",
5320
5962
  cost: (values, price) => {
5321
5963
  const { capabilities } = price;
@@ -5335,8 +5977,8 @@ var senderCapacity = defineInsight({
5335
5977
  }) => {
5336
5978
  const { outbound } = context;
5337
5979
  const { capabilities } = outbound;
5338
- const listed = await readSenders(context, maxSenders);
5339
- const senders2 = listed.items;
5980
+ const listed2 = await readSenders(context, maxSenders);
5981
+ const senders2 = listed2.items;
5340
5982
  const campaigns = await readCampaigns(context, ["active"], maxCampaigns);
5341
5983
  const reads = await mapConcurrent(
5342
5984
  campaigns,
@@ -5355,13 +5997,13 @@ var senderCapacity = defineInsight({
5355
5997
  }
5356
5998
  const capacity = capacityOf(senders2);
5357
5999
  const ask = hasSettings ? askOf(reads) : null;
5358
- const sends = await readSends(context, campaigns, days, listed, split);
6000
+ const sends = await readSends(context, campaigns, days, listed2, split);
5359
6001
  const shortfalls = reads.map(shortfallOf);
5360
6002
  const answer = {
5361
6003
  ask,
5362
6004
  askRatio: rate(ask?.daily ?? null, capacity.daily),
5363
6005
  capacity,
5364
- finding: findingOf(capacity, ask, sends),
6006
+ finding: findingOf3(capacity, ask, sends),
5365
6007
  sends,
5366
6008
  shortCampaigns: canCompare ? shortfalls.flatMap(
5367
6009
  (each) => each === null || each === "unchecked" ? [] : [each]
@@ -5378,7 +6020,7 @@ var senderCapacity = defineInsight({
5378
6020
 
5379
6021
  // src/insights/senders/sender-load.ts
5380
6022
  import { z as z28 } from "zod";
5381
- var input24 = z28.object({
6023
+ var input25 = z28.object({
5382
6024
  max_campaigns: z28.number().int().min(1).max(200).default(25).describe("The most campaigns to read. Each costs 1 request."),
5383
6025
  max_campaigns_per_sender: z28.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
5384
6026
  max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
@@ -5410,13 +6052,12 @@ var riskOf = (campaign, senders2) => {
5410
6052
  finding: inactive.length > 0 ? `${campaign.name} has ${count2}, ${inactive.length} of them not active.` : `${campaign.name} has ${count2}.`,
5411
6053
  inactive: inactive.map(loaded),
5412
6054
  issues,
5413
- name: campaign.name,
5414
6055
  senders: senders2.length
5415
6056
  };
5416
6057
  };
5417
6058
  var senderLoad = defineInsight({
5418
6059
  description: "Senders that are overused or unused: the senders attached to more campaigns than allowed, the active senders attached to no campaign, and the campaigns that run on a single sender, on none, or on a sender that is not active. Use it when sends are uneven or before adding a campaign. Costs one listing of senders and of campaigns, then 1 request per campaign. Only campaigns in the given statuses are counted, so a sender used only by a paused campaign shows as unused unless paused is included.",
5419
- inputSchema: input24,
6060
+ inputSchema: input25,
5420
6061
  key: "senderLoad",
5421
6062
  cost: (values, price) => price.list("senders.list", values.max_senders) + price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * price.list("senders.list", values.max_senders),
5422
6063
  scales: "max_campaigns",
@@ -5492,7 +6133,7 @@ var senderLoad = defineInsight({
5492
6133
 
5493
6134
  // src/insights/senders/settings-audit.ts
5494
6135
  import { z as z29 } from "zod";
5495
- var input25 = z29.object({
6136
+ var input26 = z29.object({
5496
6137
  max_campaigns: z29.number().int().min(1).max(200).default(25).describe(
5497
6138
  "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
5498
6139
  ),
@@ -5642,7 +6283,7 @@ var countChecks = (campaigns) => countEach(
5642
6283
  );
5643
6284
  var settingsAudit = defineInsight({
5644
6285
  description: "Risky campaign settings, per campaign and by severity: no sending window, a window that includes the weekend or is too long or too short, no timezone, open or click tracking on, a reply that does not stop the sequence, no daily limit, sends too close together, an end date in the past on an active campaign, and a daily limit too high for the number of senders. Returns the findings per campaign, worst first, and a count per check. Use it before launching a campaign or when deliverability drops. Costs one listing of campaigns, then 1 request per campaign, or 2 when its senders can be listed. A setting the vendor reports nothing for is skipped, except a missing window, timezone or daily limit, which the vendor cannot tell apart from one that is not set.",
5645
- inputSchema: input25,
6286
+ inputSchema: input26,
5646
6287
  key: "settingsAudit",
5647
6288
  cost: (values, price) => price.campaignsIn(new Set(values.statuses).size, values.max_campaigns) + price.campaigns(values.max_campaigns) * (price.one("campaigns.settings") + (price.capabilities["senders.byCampaign"] === false ? 0 : price.list("senders.list", values.max_senders_per_campaign))),
5648
6289
  scales: "max_campaigns",
@@ -5709,7 +6350,7 @@ var settingsAudit = defineInsight({
5709
6350
 
5710
6351
  // src/insights/senders/warmup-readiness.ts
5711
6352
  import { z as z30 } from "zod";
5712
- var input26 = z30.object({
6353
+ var input27 = z30.object({
5713
6354
  check_health: z30.boolean().default(false).describe(
5714
6355
  "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
5715
6356
  ),
@@ -5784,7 +6425,7 @@ var countReasons = (judged) => countEach(
5784
6425
  );
5785
6426
  var warmupReadiness = defineInsight({
5786
6427
  description: "Which senders are not ready to send, each with its reasons: warmup off, warmup score under the bar or not reported, status not active, no daily limit and, with check_health, failing DNS records or too many warmup emails in spam. Returns counts by reason and how many are ready. A LinkedIn seat is judged on its status only. Use it before attaching mailboxes to a campaign or raising their limits. Costs one listing of senders, plus 1 request per mailbox with check_health. A null score means the vendor does not report one, which counts as not ready, not as 0.",
5787
- inputSchema: input26,
6428
+ inputSchema: input27,
5788
6429
  key: "warmupReadiness",
5789
6430
  cost: (values, price) => price.list("senders.list", values.max_senders) + (values.check_health && price.capabilities["senders.health"] !== false ? price.upTo(values.max_senders) * price.one("senders.health") : 0),
5790
6431
  scales: "max_senders",
@@ -5863,10 +6504,10 @@ var entryNamed = (outbound, name) => {
5863
6504
  }
5864
6505
  return entry;
5865
6506
  };
5866
- var runInsightByName = async (outbound, name, input27 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input27, options);
5867
- var insightCost = (outbound, name, input27 = {}) => {
6507
+ var runInsightByName = async (outbound, name, input28 = {}, options = {}) => await entryNamed(outbound, name).execute(outbound, input28, options);
6508
+ var insightCost = (outbound, name, input28 = {}) => {
5868
6509
  const entry = entryNamed(outbound, name);
5869
- const parsed = entry.inputSchema.safeParse(input27);
6510
+ const parsed = entry.inputSchema.safeParse(input28);
5870
6511
  if (!parsed.success) {
5871
6512
  throw new OutboundError(
5872
6513
  "Invalid",
@@ -5889,9 +6530,9 @@ var insights = () => ({
5889
6530
  extend: (outbound) => {
5890
6531
  const methods = {};
5891
6532
  for (const entry of ENTRIES) {
5892
- methods[entry.key] = (input27, options) => (
6533
+ methods[entry.key] = (input28, options) => (
5893
6534
  // SAFETY: the answer is the entry's own, typed per key by Insights.
5894
- entry.execute(outbound, input27, options)
6535
+ entry.execute(outbound, input28, options)
5895
6536
  );
5896
6537
  }
5897
6538
  return { insights: methods };
@@ -5903,19 +6544,20 @@ var insights = () => ({
5903
6544
  import { z as z32 } from "zod";
5904
6545
  var INSIGHT_TOOL_CEILING = 500;
5905
6546
  var NEXT_FALLBACK = "Pick another of the listed tools to go further.";
6547
+ var ANSWER_NOTE = "The answer is in data, in camelCase like every insight's answer. meta.complete: false means it covers part of the data, and meta.notes says why.";
5906
6548
  var hintFor = (next, offered) => {
5907
6549
  const hidden = ENTRIES.flatMap(
5908
6550
  (entry) => offered.has(entry.name) ? [] : [entry.name]
5909
6551
  );
5910
- const kept = next.split(/(?<=\.)\s+/u).filter((sentence) => !hidden.some((name) => sentence.includes(name)));
6552
+ const kept = next.split(/(?<=\.)\s+/u).filter((sentence2) => !hidden.some((name) => sentence2.includes(name)));
5911
6553
  return kept.length === 0 ? NEXT_FALLBACK : kept.join(" ");
5912
6554
  };
5913
6555
  var toTool = (outbound, definition, next, perCall) => ({
5914
6556
  call: async (given, callOptions) => {
5915
6557
  const set = callOptions?.maxRequests ?? perCall;
5916
6558
  try {
5917
- const input27 = jsonInput(given);
5918
- if (input27 === void 0) {
6559
+ const input28 = jsonInput(given);
6560
+ if (input28 === void 0) {
5919
6561
  throw new OutboundError(
5920
6562
  "Invalid",
5921
6563
  `${definition.name}: the input is not JSON`
@@ -5923,20 +6565,18 @@ var toTool = (outbound, definition, next, perCall) => ({
5923
6565
  }
5924
6566
  const result = await definition.execute(
5925
6567
  outbound,
5926
- input27,
6568
+ input28,
5927
6569
  set === void 0 ? {
5928
6570
  capCeiling: INSIGHT_TOOL_CEILING,
5929
6571
  capSetting: "maxRequestsPerToolCall"
5930
6572
  } : { capSetting: "maxRequestsPerToolCall", maxRequests: set }
5931
6573
  );
5932
6574
  return {
5933
- data: {
5934
- complete: result.meta.complete,
5935
- notes: [...result.meta.notes],
5936
- result: result.data
5937
- },
6575
+ data: result.data,
5938
6576
  meta: {
6577
+ complete: result.meta.complete,
5939
6578
  evidence: result.meta.evidence,
6579
+ notes: [...result.meta.notes],
5940
6580
  provider: result.meta.provider,
5941
6581
  requests: result.meta.requests
5942
6582
  },
@@ -5959,7 +6599,7 @@ var toTool = (outbound, definition, next, perCall) => ({
5959
6599
  );
5960
6600
  }
5961
6601
  },
5962
- description: definition.description,
6602
+ description: `${definition.description} ${ANSWER_NOTE}`,
5963
6603
  fields: definition.inputSchema.shape,
5964
6604
  name: definition.name,
5965
6605
  needs: [...definition.needs],