outbound-sdk 0.0.0-stage → 0.1.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 (271) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -2
  3. package/dist/alerts/index.d.ts +2 -0
  4. package/dist/alerts/index.js +136 -0
  5. package/dist/alerts/plugin.d.ts +58 -0
  6. package/dist/audit/index.d.ts +33 -0
  7. package/dist/audit/index.js +60 -0
  8. package/dist/benchmarks/index.d.ts +29 -0
  9. package/dist/benchmarks/index.js +70 -0
  10. package/dist/budget/index.d.ts +21 -0
  11. package/dist/budget/index.js +50 -0
  12. package/dist/cache/index.d.ts +31 -0
  13. package/dist/cache/index.js +11 -0
  14. package/dist/cards/content.d.ts +43 -0
  15. package/dist/cards/copy-cards.d.ts +2 -0
  16. package/dist/cards/format.d.ts +39 -0
  17. package/dist/cards/index.d.ts +9 -0
  18. package/dist/cards/index.js +2070 -0
  19. package/dist/cards/notify-cards.d.ts +14 -0
  20. package/dist/cards/ops-cards.d.ts +2 -0
  21. package/dist/cards/parts.d.ts +22 -0
  22. package/dist/cards/people-cards.d.ts +2 -0
  23. package/dist/cards/render.d.ts +28 -0
  24. package/dist/cards/sender-cards.d.ts +2 -0
  25. package/dist/cards/slack-rich.d.ts +19 -0
  26. package/dist/cards/slack-text.d.ts +10 -0
  27. package/dist/cards/slack.d.ts +21 -0
  28. package/dist/cards/spec.d.ts +86 -0
  29. package/dist/cards/tool-cards.d.ts +4 -0
  30. package/dist/chunks/chunk-4O2HRTTI.js +75 -0
  31. package/dist/chunks/chunk-7BCYLIDG.js +483 -0
  32. package/dist/chunks/chunk-B7V6EOAC.js +2273 -0
  33. package/dist/chunks/chunk-CMQ5ZHLZ.js +25 -0
  34. package/dist/chunks/chunk-F7MKFVIG.js +43 -0
  35. package/dist/chunks/chunk-FZF6CLPX.js +232 -0
  36. package/dist/chunks/chunk-GPEJG34O.js +53 -0
  37. package/dist/chunks/chunk-HEC7XFFH.js +65 -0
  38. package/dist/chunks/chunk-IBC52BX3.js +24 -0
  39. package/dist/chunks/chunk-LNCOGBMI.js +144 -0
  40. package/dist/chunks/chunk-LOXBLQ3I.js +180 -0
  41. package/dist/chunks/chunk-NAWZ73QS.js +22 -0
  42. package/dist/chunks/chunk-OCV66TS2.js +705 -0
  43. package/dist/chunks/chunk-Q465X22Y.js +548 -0
  44. package/dist/chunks/chunk-QTB747K4.js +100 -0
  45. package/dist/chunks/chunk-QZNNCXXD.js +92 -0
  46. package/dist/chunks/chunk-R6AM4GJR.js +105 -0
  47. package/dist/chunks/chunk-TIJKJJDW.js +6 -0
  48. package/dist/chunks/chunk-VURTOVGI.js +61 -0
  49. package/dist/chunks/chunk-WAM6N4OF.js +269 -0
  50. package/dist/chunks/chunk-WW746NJF.js +94 -0
  51. package/dist/chunks/chunk-XC6CZP73.js +80 -0
  52. package/dist/chunks/chunk-ZGHQYZEH.js +45 -0
  53. package/dist/cli/bin.d.ts +2 -0
  54. package/dist/cli/bin.js +34 -0
  55. package/dist/cli/commands.d.ts +16 -0
  56. package/dist/cli/index.d.ts +13 -0
  57. package/dist/cli/index.js +25 -0
  58. package/dist/cli/mcp.d.ts +14 -0
  59. package/dist/clients/index.d.ts +2 -0
  60. package/dist/clients/index.js +107 -0
  61. package/dist/clients/plugin.d.ts +42 -0
  62. package/dist/combine/account.d.ts +4 -0
  63. package/dist/combine/adapter.d.ts +9 -0
  64. package/dist/combine/index.d.ts +2 -0
  65. package/dist/combine/index.js +345 -0
  66. package/dist/combine/route.d.ts +17 -0
  67. package/dist/exporter/index.d.ts +29 -0
  68. package/dist/exporter/index.js +77 -0
  69. package/dist/failover/index.d.ts +11 -0
  70. package/dist/failover/index.js +45 -0
  71. package/dist/fixtures/index.d.ts +27 -0
  72. package/dist/fixtures/index.js +241 -0
  73. package/dist/fixtures/scrub.d.ts +5 -0
  74. package/dist/heyreach/account.d.ts +11 -0
  75. package/dist/heyreach/adapter.d.ts +5 -0
  76. package/dist/heyreach/capabilities.d.ts +68 -0
  77. package/dist/heyreach/client.d.ts +20 -0
  78. package/dist/heyreach/inbox.d.ts +7 -0
  79. package/dist/heyreach/index.d.ts +18 -0
  80. package/dist/heyreach/index.js +1708 -0
  81. package/dist/heyreach/lookup.d.ts +15 -0
  82. package/dist/heyreach/map-account.d.ts +25 -0
  83. package/dist/heyreach/map-sequence.d.ts +5 -0
  84. package/dist/heyreach/map-stats.d.ts +10 -0
  85. package/dist/heyreach/map.d.ts +35 -0
  86. package/dist/heyreach/native-organization.d.ts +128 -0
  87. package/dist/heyreach/native-voice.d.ts +106 -0
  88. package/dist/heyreach/native.d.ts +496 -0
  89. package/dist/heyreach/paging.d.ts +7 -0
  90. package/dist/heyreach/webhooks.d.ts +2 -0
  91. package/dist/identity/index.d.ts +3 -0
  92. package/dist/identity/index.js +148 -0
  93. package/dist/identity/keys.d.ts +9 -0
  94. package/dist/identity/plugin.d.ts +34 -0
  95. package/dist/index.d.ts +36 -0
  96. package/dist/index.js +119 -0
  97. package/dist/insights/copy/copy-audit.d.ts +55 -0
  98. package/dist/insights/copy/copy-checks.d.ts +44 -0
  99. package/dist/insights/copy/copy-reuse.d.ts +59 -0
  100. package/dist/insights/copy/index.d.ts +67 -0
  101. package/dist/insights/copy/reply-timing.d.ts +63 -0
  102. package/dist/insights/copy/shared.d.ts +53 -0
  103. package/dist/insights/copy/step-funnel.d.ts +66 -0
  104. package/dist/insights/copy/variant-test.d.ts +64 -0
  105. package/dist/insights/define.d.ts +98 -0
  106. package/dist/insights/index.d.ts +10 -0
  107. package/dist/insights/index.js +4873 -0
  108. package/dist/insights/ops/anomalies.d.ts +80 -0
  109. package/dist/insights/ops/campaign-diagnosis.d.ts +39 -0
  110. package/dist/insights/ops/campaign-ranking.d.ts +56 -0
  111. package/dist/insights/ops/channel-mix.d.ts +44 -0
  112. package/dist/insights/ops/client-report.d.ts +76 -0
  113. package/dist/insights/ops/diagnosis-checks.d.ts +48 -0
  114. package/dist/insights/ops/index.d.ts +135 -0
  115. package/dist/insights/ops/period-comparison.d.ts +86 -0
  116. package/dist/insights/ops/pipeline-forecast.d.ts +44 -0
  117. package/dist/insights/ops/shared.d.ts +149 -0
  118. package/dist/insights/ops/tag-rollup.d.ts +32 -0
  119. package/dist/insights/people/account-summary.d.ts +68 -0
  120. package/dist/insights/people/dropped-replies.d.ts +51 -0
  121. package/dist/insights/people/find.d.ts +18 -0
  122. package/dist/insights/people/hot-leads.d.ts +67 -0
  123. package/dist/insights/people/index.d.ts +88 -0
  124. package/dist/insights/people/lead-collisions.d.ts +43 -0
  125. package/dist/insights/people/person-summary.d.ts +46 -0
  126. package/dist/insights/people/personalization-gaps.d.ts +60 -0
  127. package/dist/insights/people/read.d.ts +40 -0
  128. package/dist/insights/people/suppression-check.d.ts +53 -0
  129. package/dist/insights/plugin.d.ts +40 -0
  130. package/dist/insights/registry.d.ts +335 -0
  131. package/dist/insights/senders/bounce-watch.d.ts +70 -0
  132. package/dist/insights/senders/domain-health.d.ts +69 -0
  133. package/dist/insights/senders/index.d.ts +74 -0
  134. package/dist/insights/senders/read.d.ts +37 -0
  135. package/dist/insights/senders/sender-capacity.d.ts +67 -0
  136. package/dist/insights/senders/sender-load.d.ts +52 -0
  137. package/dist/insights/senders/settings-audit.d.ts +48 -0
  138. package/dist/insights/senders/warmup-readiness.d.ts +39 -0
  139. package/dist/insights/stats.d.ts +45 -0
  140. package/dist/insights/tools.d.ts +16 -0
  141. package/dist/insights/types.d.ts +4 -0
  142. package/dist/instantly/adapter-account.d.ts +5 -0
  143. package/dist/instantly/adapter-mail.d.ts +3 -0
  144. package/dist/instantly/adapter.d.ts +7 -0
  145. package/dist/instantly/capabilities.d.ts +83 -0
  146. package/dist/instantly/client.d.ts +29 -0
  147. package/dist/instantly/index.d.ts +20 -0
  148. package/dist/instantly/index.js +2372 -0
  149. package/dist/instantly/map-account.d.ts +23 -0
  150. package/dist/instantly/map-lead.d.ts +18 -0
  151. package/dist/instantly/map-stats.d.ts +22 -0
  152. package/dist/instantly/map.d.ts +24 -0
  153. package/dist/instantly/native-agents-sales.d.ts +161 -0
  154. package/dist/instantly/native-agents.d.ts +156 -0
  155. package/dist/instantly/native-campaigns.d.ts +101 -0
  156. package/dist/instantly/native-leads.d.ts +93 -0
  157. package/dist/instantly/native-params.d.ts +24 -0
  158. package/dist/instantly/native-search.d.ts +82 -0
  159. package/dist/instantly/native-senders.d.ts +182 -0
  160. package/dist/instantly/native-supersearch.d.ts +149 -0
  161. package/dist/instantly/native-workspace.d.ts +170 -0
  162. package/dist/instantly/native.d.ts +1081 -0
  163. package/dist/instantly/pages.d.ts +29 -0
  164. package/dist/instantly/stats.d.ts +5 -0
  165. package/dist/instantly/webhooks.d.ts +2 -0
  166. package/dist/internal/adapter.d.ts +189 -0
  167. package/dist/internal/capabilities.d.ts +86 -0
  168. package/dist/internal/cursor.d.ts +10 -0
  169. package/dist/internal/engine/budget.d.ts +44 -0
  170. package/dist/internal/engine/engine.d.ts +45 -0
  171. package/dist/internal/engine/rate-store.d.ts +25 -0
  172. package/dist/internal/engine/request.d.ts +27 -0
  173. package/dist/internal/engine/retry.d.ts +21 -0
  174. package/dist/internal/engine/runtime.d.ts +13 -0
  175. package/dist/internal/entities-account.d.ts +135 -0
  176. package/dist/internal/entities.d.ts +389 -0
  177. package/dist/internal/env.d.ts +4 -0
  178. package/dist/internal/errors.d.ts +57 -0
  179. package/dist/internal/hooks.d.ts +55 -0
  180. package/dist/internal/json.d.ts +40 -0
  181. package/dist/internal/limits.d.ts +34 -0
  182. package/dist/internal/metrics.d.ts +52 -0
  183. package/dist/internal/native.d.ts +66 -0
  184. package/dist/internal/outbound/api.d.ts +267 -0
  185. package/dist/internal/outbound/collections.d.ts +31 -0
  186. package/dist/internal/outbound/core.d.ts +36 -0
  187. package/dist/internal/outbound/create.d.ts +16 -0
  188. package/dist/internal/outbound/handles.d.ts +7 -0
  189. package/dist/internal/outbound/native.d.ts +4 -0
  190. package/dist/internal/outbound/operation-shared.d.ts +28 -0
  191. package/dist/internal/outbound/operations-account.d.ts +29 -0
  192. package/dist/internal/outbound/operations.d.ts +42 -0
  193. package/dist/internal/outbound/outbound.d.ts +64 -0
  194. package/dist/internal/outbound/plugins.d.ts +40 -0
  195. package/dist/internal/outbound/raw.d.ts +9 -0
  196. package/dist/internal/outbound/specs-account.d.ts +16 -0
  197. package/dist/internal/outbound/specs.d.ts +14 -0
  198. package/dist/internal/outbound/stats.d.ts +7 -0
  199. package/dist/internal/outbound/validate.d.ts +5 -0
  200. package/dist/internal/outbound/walker.d.ts +22 -0
  201. package/dist/internal/record.d.ts +19 -0
  202. package/dist/internal/redact.d.ts +18 -0
  203. package/dist/internal/ref.d.ts +16 -0
  204. package/dist/internal/sha256.d.ts +4 -0
  205. package/dist/internal/text.d.ts +11 -0
  206. package/dist/internal/url.d.ts +9 -0
  207. package/dist/loader/index.d.ts +12 -0
  208. package/dist/loader/index.js +12 -0
  209. package/dist/memory/account-reads.d.ts +5 -0
  210. package/dist/memory/account.d.ts +67 -0
  211. package/dist/memory/adapter.d.ts +16 -0
  212. package/dist/memory/data.d.ts +122 -0
  213. package/dist/memory/demo.d.ts +7 -0
  214. package/dist/memory/index.d.ts +5 -0
  215. package/dist/memory/index.js +792 -0
  216. package/dist/memory/stats.d.ts +6 -0
  217. package/dist/memory/store.d.ts +18 -0
  218. package/dist/providers/index.d.ts +22 -0
  219. package/dist/providers/index.js +10 -0
  220. package/dist/reconcile/index.d.ts +2 -0
  221. package/dist/reconcile/index.js +72 -0
  222. package/dist/reconcile/plugin.d.ts +55 -0
  223. package/dist/redact/index.d.ts +2 -0
  224. package/dist/redact/index.js +192 -0
  225. package/dist/redact/plugin.d.ts +22 -0
  226. package/dist/redis/index.d.ts +41 -0
  227. package/dist/redis/index.js +114 -0
  228. package/dist/smartlead/account.d.ts +5 -0
  229. package/dist/smartlead/adapter.d.ts +5 -0
  230. package/dist/smartlead/capabilities.d.ts +85 -0
  231. package/dist/smartlead/client.d.ts +23 -0
  232. package/dist/smartlead/hmac.d.ts +9 -0
  233. package/dist/smartlead/index.d.ts +17 -0
  234. package/dist/smartlead/index.js +2170 -0
  235. package/dist/smartlead/leads.d.ts +6 -0
  236. package/dist/smartlead/lookup.d.ts +8 -0
  237. package/dist/smartlead/mail.d.ts +5 -0
  238. package/dist/smartlead/map-account.d.ts +22 -0
  239. package/dist/smartlead/map-messages.d.ts +31 -0
  240. package/dist/smartlead/map-stats.d.ts +37 -0
  241. package/dist/smartlead/map.d.ts +52 -0
  242. package/dist/smartlead/native-analytics.d.ts +242 -0
  243. package/dist/smartlead/native-campaigns.d.ts +211 -0
  244. package/dist/smartlead/native-inbox.d.ts +141 -0
  245. package/dist/smartlead/native-params.d.ts +33 -0
  246. package/dist/smartlead/native-services.d.ts +204 -0
  247. package/dist/smartlead/native.d.ts +785 -0
  248. package/dist/smartlead/shared.d.ts +28 -0
  249. package/dist/smartlead/stats.d.ts +5 -0
  250. package/dist/smartlead/webhooks.d.ts +2 -0
  251. package/dist/sync/index.d.ts +2 -0
  252. package/dist/sync/index.js +158 -0
  253. package/dist/sync/plugin.d.ts +58 -0
  254. package/dist/tools/account-tools.d.ts +21 -0
  255. package/dist/tools/ai-sdk.d.ts +8 -0
  256. package/dist/tools/ai-sdk.js +26 -0
  257. package/dist/tools/campaign-tools.d.ts +59 -0
  258. package/dist/tools/claude-agent.d.ts +18 -0
  259. package/dist/tools/claude-agent.js +40 -0
  260. package/dist/tools/index.d.ts +28 -0
  261. package/dist/tools/index.js +20 -0
  262. package/dist/tools/people-tools.d.ts +19 -0
  263. package/dist/tools/registry.d.ts +34 -0
  264. package/dist/tools/shared.d.ts +75 -0
  265. package/dist/tracing/index.d.ts +25 -0
  266. package/dist/tracing/index.js +69 -0
  267. package/dist/webhooks/index.d.ts +3 -0
  268. package/dist/webhooks/index.js +226 -0
  269. package/dist/webhooks/parse.d.ts +41 -0
  270. package/dist/webhooks/secret.d.ts +4 -0
  271. package/package.json +181 -4
@@ -0,0 +1,4873 @@
1
+ import {
2
+ sumCounts
3
+ } from "../chunks/chunk-WW746NJF.js";
4
+ import {
5
+ profileSlug
6
+ } from "../chunks/chunk-NAWZ73QS.js";
7
+ import {
8
+ campaignStatusSchema,
9
+ replyCategorySchema
10
+ } from "../chunks/chunk-WAM6N4OF.js";
11
+ import {
12
+ OutboundError
13
+ } from "../chunks/chunk-LOXBLQ3I.js";
14
+ import {
15
+ toJson,
16
+ unknownKey
17
+ } from "../chunks/chunk-QZNNCXXD.js";
18
+
19
+ // src/insights/plugin.ts
20
+ import { z as z31 } from "zod";
21
+
22
+ // src/insights/copy/copy-audit.ts
23
+ import { z } from "zod";
24
+
25
+ // src/insights/define.ts
26
+ var RANK = {
27
+ derived: 2,
28
+ exact: 0,
29
+ sampled: 1
30
+ };
31
+ var track = (outbound, now) => {
32
+ const notes = [];
33
+ let requests = 0;
34
+ let evidence = "exact";
35
+ let complete = true;
36
+ const seen = (meta) => {
37
+ if (meta === void 0) {
38
+ return;
39
+ }
40
+ requests += meta.requests;
41
+ evidence = RANK[meta.evidence] > RANK[evidence] ? meta.evidence : evidence;
42
+ };
43
+ const note = (text) => {
44
+ if (!notes.includes(text)) {
45
+ notes.push(text);
46
+ }
47
+ };
48
+ const partial = (reason) => {
49
+ complete = false;
50
+ note(reason);
51
+ };
52
+ return {
53
+ context: {
54
+ all: async (walk, cap) => {
55
+ const items = await walk.toArray();
56
+ seen(walk.meta);
57
+ if (walk.truncated) {
58
+ partial(
59
+ cap === void 0 ? "A listing was cut off at its cap; more records exist." : `Stopped at ${cap}; more exist.`
60
+ );
61
+ }
62
+ return items;
63
+ },
64
+ note,
65
+ now,
66
+ one: (item) => {
67
+ seen(item.meta);
68
+ return item;
69
+ },
70
+ outbound,
71
+ page: (page) => {
72
+ seen(page.meta);
73
+ if (!page.complete) {
74
+ partial("Only the first page of a listing was read.");
75
+ }
76
+ return page.items;
77
+ },
78
+ partial,
79
+ rows: (stats) => {
80
+ seen(stats.meta);
81
+ return stats.rows;
82
+ }
83
+ },
84
+ meta: () => ({ complete, evidence, notes: [...notes], requests })
85
+ };
86
+ };
87
+ var missing = (outbound, needs) => needs.filter((key) => outbound.capabilities[key] === false);
88
+ var prepare = (outbound, spec, input27) => {
89
+ const stray = unknownKey(Object.keys(spec.inputSchema.shape), input27);
90
+ if (stray !== void 0) {
91
+ throw new OutboundError("Invalid", `${spec.name}: ${stray}`, {
92
+ provider: outbound.provider
93
+ });
94
+ }
95
+ const parsed = spec.inputSchema.safeParse(input27 ?? {});
96
+ if (!parsed.success) {
97
+ const [issue] = parsed.error.issues;
98
+ throw new OutboundError(
99
+ "Invalid",
100
+ `${spec.name}: ${issue?.path.join(".") || "input"} ${issue?.message ?? "is invalid"}`,
101
+ { provider: outbound.provider }
102
+ );
103
+ }
104
+ const absent = missing(outbound, spec.needs);
105
+ const forInput = missing(outbound, spec.needsFor?.(parsed.data) ?? []);
106
+ if (absent.length > 0 || forInput.length > 0) {
107
+ throw new OutboundError(
108
+ "Unsupported",
109
+ `${spec.name} is not available${absent.length > 0 ? "" : " for this input"}: the ${outbound.provider} adapter does not support ${[.../* @__PURE__ */ new Set([...absent, ...forInput])].join(", ")}`,
110
+ { provider: outbound.provider }
111
+ );
112
+ }
113
+ return parsed.data;
114
+ };
115
+ var execute = async (outbound, spec, input27, options = {}) => {
116
+ const checked = prepare(outbound, spec, input27);
117
+ const now = options.now ?? Date.now();
118
+ const tracker = track(outbound, now);
119
+ const data = await spec.run(tracker.context, checked);
120
+ return {
121
+ data,
122
+ insight: spec.name,
123
+ meta: {
124
+ ...tracker.meta(),
125
+ computedAt: new Date(now).toISOString(),
126
+ provider: outbound.provider
127
+ }
128
+ };
129
+ };
130
+ var defineInsight = (spec) => ({
131
+ ...spec,
132
+ execute: async (outbound, input27, options) => {
133
+ const result = await execute(outbound, spec, input27, options);
134
+ return { ...result, data: toJson(result.data) };
135
+ }
136
+ });
137
+ var runInsight = (outbound, definition, input27, options = {}) => (
138
+ // SAFETY: an insight's input is a plain object of JSON values, and it is parsed before use.
139
+ execute(outbound, definition, input27, options)
140
+ );
141
+
142
+ // src/insights/copy/copy-checks.ts
143
+ var CHECKS = {
144
+ all_caps: "low",
145
+ body_too_long: "low",
146
+ connection_request_too_long: "high",
147
+ exclamation_marks: "low",
148
+ image: "medium",
149
+ malformed_variable: "high",
150
+ missing_subject: "high",
151
+ spam_words: "medium",
152
+ subject_breaks_thread: "medium",
153
+ subject_too_long: "low",
154
+ too_many_links: "medium"
155
+ };
156
+ var DEFAULT_SPAM_WORDS = [
157
+ "100% free",
158
+ "act now",
159
+ "buy now",
160
+ "cash bonus",
161
+ "click here",
162
+ "double your",
163
+ "earn money",
164
+ "free trial",
165
+ "guarantee",
166
+ "limited time",
167
+ "no obligation",
168
+ "risk-free",
169
+ "urgent",
170
+ "winner"
171
+ ];
172
+ var TAG = /<[^>]+>/gu;
173
+ var IMAGE = /<img\b[^>]*>/giu;
174
+ var VARIABLE = /\{\{[^{}]*\}\}/gu;
175
+ var LINK = /\b(?:https?:\/\/|www\.)[^\s"'<>)]+/giu;
176
+ var CAPS_WORD = /\b[A-Z]{4,}\b/gu;
177
+ var PIXEL = /(?:width|height)\s*[=:]\s*["']?[01](?:px)?\b|pixel|track/iu;
178
+ var REPLY_PREFIX = /^(?:re|fwd?)\s*:\s*/iu;
179
+ var SNIPPET = 80;
180
+ var clip = (text) => text.length > SNIPPET ? `${text.slice(0, SNIPPET)}\u2026` : text;
181
+ var visible = (text) => text.replaceAll(TAG, " ").replaceAll(VARIABLE, " variable ");
182
+ var wordsOf = (text) => visible(text).split(/\s+/u).filter((word) => word !== "");
183
+ var escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
184
+ var subjectTooLong = (subject, limits) => subject.length > limits.maxSubjectChars ? {
185
+ check: "subject_too_long",
186
+ finding: `The subject is ${subject.length} characters; the limit is ${limits.maxSubjectChars}.`,
187
+ text: clip(subject)
188
+ } : null;
189
+ var bodyTooLong = (body, limits) => {
190
+ const words = wordsOf(body);
191
+ return words.length > limits.maxBodyWords ? {
192
+ check: "body_too_long",
193
+ finding: `The body is ${words.length} words; the limit is ${limits.maxBodyWords}.`,
194
+ text: clip(words.slice(0, 12).join(" "))
195
+ } : null;
196
+ };
197
+ var tooManyLinks = (body, limits) => {
198
+ const links = body.replaceAll(IMAGE, " ").match(LINK) ?? [];
199
+ return links.length > limits.maxLinks ? {
200
+ check: "too_many_links",
201
+ finding: `The body has ${links.length} links; the limit is ${limits.maxLinks}.`,
202
+ text: clip(links.join(" "))
203
+ } : null;
204
+ };
205
+ var spamWords = (text, limits) => {
206
+ const plain = visible(text);
207
+ const hits = limits.spamWords.filter(
208
+ (word) => word.trim() !== "" && new RegExp(
209
+ String.raw`(?<![\w])${escape(word.trim())}(?![\w])`,
210
+ "iu"
211
+ ).test(plain)
212
+ );
213
+ return hits.length > 0 ? {
214
+ check: "spam_words",
215
+ finding: `The copy uses ${hits.length} word(s) or phrase(s) that spam filters weigh.`,
216
+ text: hits.join(", ")
217
+ } : null;
218
+ };
219
+ var malformedVariable = (text) => {
220
+ const empty = (text.match(VARIABLE) ?? []).filter(
221
+ (token) => token.slice(2, -2).trim() === ""
222
+ );
223
+ const rest = text.replaceAll(VARIABLE, "");
224
+ const stray = /\{\{|\}\}/u.exec(rest);
225
+ if (stray === null && empty.length === 0) {
226
+ return null;
227
+ }
228
+ return {
229
+ check: "malformed_variable",
230
+ finding: stray === null ? "A variable has no name between its braces, so it sends as blank or as raw braces." : "A variable's braces are not balanced, so it sends as raw text.",
231
+ text: stray === null ? empty[0] ?? "" : clip(
232
+ rest.slice(Math.max(0, stray.index - 20), stray.index + 30).trim()
233
+ )
234
+ };
235
+ };
236
+ var allCaps = (text, limits) => {
237
+ const words = text.replaceAll(TAG, " ").replaceAll(VARIABLE, " ").match(CAPS_WORD);
238
+ const found = words ?? [];
239
+ return found.length > limits.maxCapsWords ? {
240
+ check: "all_caps",
241
+ finding: `${found.length} word(s) of four or more letters are in capitals; the limit is ${limits.maxCapsWords}.`,
242
+ text: clip(found.join(" "))
243
+ } : null;
244
+ };
245
+ var exclamationMarks = (text, limits) => {
246
+ const marks = visible(text).split("!").length - 1;
247
+ return marks > limits.maxExclamations ? {
248
+ check: "exclamation_marks",
249
+ finding: `The copy has ${marks} exclamation marks; the limit is ${limits.maxExclamations}.`,
250
+ text: "!".repeat(marks)
251
+ } : null;
252
+ };
253
+ var image = (body) => {
254
+ const [first] = body.match(IMAGE) ?? [];
255
+ if (first === void 0) {
256
+ return null;
257
+ }
258
+ return {
259
+ check: "image",
260
+ finding: PIXEL.test(first) ? "The body holds a tracking pixel, which spam filters and privacy tools flag." : "The body holds an image, which cold email filters weigh against.",
261
+ text: clip(first)
262
+ };
263
+ };
264
+ var threadKey = (subject) => (subject ?? "").trim().replace(REPLY_PREFIX, "").trim().toLowerCase();
265
+ var connectionTooLong = (body, limits) => body.length > limits.maxConnectionChars ? {
266
+ check: "connection_request_too_long",
267
+ finding: `The connection request is ${body.length} characters; LinkedIn cuts it at ${limits.maxConnectionChars}.`,
268
+ text: clip(body)
269
+ } : null;
270
+
271
+ // src/insights/copy/copy-audit.ts
272
+ var limit = (fallback, description) => z.number().int().min(0).default(fallback).describe(description);
273
+ var input = z.object({
274
+ campaign: z.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
275
+ max_body_words: limit(150, "The most words a body may have."),
276
+ max_caps_words: limit(
277
+ 1,
278
+ "How many words of four or more letters may be in capitals, so one acronym is not a finding."
279
+ ),
280
+ max_connection_chars: limit(
281
+ 300,
282
+ "The most characters a LinkedIn connection request may have."
283
+ ),
284
+ max_exclamations: limit(1, "How many exclamation marks a message may have."),
285
+ max_links: limit(1, "The most links an email body may have."),
286
+ max_subject_chars: limit(60, "The most characters a subject may have."),
287
+ spam_words: z.array(z.string().min(1)).default([...DEFAULT_SPAM_WORDS]).describe(
288
+ "Words and phrases to flag in email copy, matched whole and without case. Replaces the default list."
289
+ )
290
+ });
291
+ var RANK2 = { high: 0, low: 2, medium: 1 };
292
+ var EMAIL_ONLY = [
293
+ "image",
294
+ "missing_subject",
295
+ "spam_words",
296
+ "subject_breaks_thread",
297
+ "subject_too_long",
298
+ "too_many_links"
299
+ ];
300
+ var LINKEDIN_ONLY = ["connection_request_too_long"];
301
+ var emailChecks = (step, variant, limits, thread) => {
302
+ const subject = variant.subject?.trim() ?? "";
303
+ const body = variant.body ?? "";
304
+ const key = threadKey(subject);
305
+ const problems = [
306
+ subject === "" ? null : subjectTooLong(subject, limits),
307
+ spamWords(`${subject}
308
+ ${body}`, limits),
309
+ tooManyLinks(body, limits),
310
+ image(body)
311
+ ];
312
+ if (step.index === thread.first && subject === "") {
313
+ problems.push({
314
+ check: "missing_subject",
315
+ finding: "The first email has no subject.",
316
+ text: ""
317
+ });
318
+ }
319
+ if (step.index !== thread.first && key !== "" && !thread.subjects.has(key)) {
320
+ problems.push({
321
+ check: "subject_breaks_thread",
322
+ 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.",
323
+ text: subject
324
+ });
325
+ }
326
+ return problems;
327
+ };
328
+ var linkedinChecks = (step, variant, limits) => step.action.toLowerCase().includes("connect") && variant.body !== null ? [connectionTooLong(variant.body, limits)] : [];
329
+ var auditVariant = (step, variant, limits, thread) => {
330
+ const body = variant.body ?? "";
331
+ const whole = `${variant.subject ?? ""}
332
+ ${body}`;
333
+ const problems = [
334
+ malformedVariable(whole),
335
+ bodyTooLong(body, limits),
336
+ allCaps(whole, limits),
337
+ exclamationMarks(whole, limits),
338
+ ...thread === null ? linkedinChecks(step, variant, limits) : emailChecks(step, variant, limits, thread)
339
+ ];
340
+ return problems.flatMap(
341
+ (problem) => problem === null ? [] : [
342
+ {
343
+ ...problem,
344
+ action: step.action,
345
+ severity: CHECKS[problem.check],
346
+ step: step.index,
347
+ variantKey: variant.variantKey
348
+ }
349
+ ]
350
+ );
351
+ };
352
+ var threadOf = (steps) => {
353
+ const [first] = steps.toSorted((left, right) => left.index - right.index);
354
+ return {
355
+ first: first?.index ?? null,
356
+ subjects: new Set(
357
+ (first?.variants ?? []).flatMap((variant) => {
358
+ const key = threadKey(variant.subject);
359
+ return key === "" ? [] : [key];
360
+ })
361
+ )
362
+ };
363
+ };
364
+ var CHECK_NAMES = Object.keys(CHECKS);
365
+ var countsOf = (findings, isEmail) => CHECK_NAMES.filter(
366
+ (check) => !(isEmail ? LINKEDIN_ONLY : EMAIL_ONLY).includes(check)
367
+ ).map((check) => ({
368
+ check,
369
+ count: findings.filter((finding) => finding.check === check).length,
370
+ severity: CHECKS[check]
371
+ })).toSorted(
372
+ (left, right) => right.count - left.count || RANK2[left.severity] - RANK2[right.severity] || left.check.localeCompare(right.check)
373
+ );
374
+ var copyAudit = defineInsight({
375
+ 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.",
376
+ inputSchema: input,
377
+ key: "copyAudit",
378
+ name: "copy_audit",
379
+ needs: ["sequence"],
380
+ next: "Use step_funnel to see whether the steps with findings are also the ones with few replies.",
381
+ run: async (context, args) => {
382
+ const handle = context.outbound.campaign(args.campaign);
383
+ const campaign = context.one(await handle.get());
384
+ const sequence2 = context.one(await handle.sequence());
385
+ const isEmail = campaign.channel === "email";
386
+ const limits = {
387
+ maxBodyWords: args.max_body_words,
388
+ maxCapsWords: args.max_caps_words,
389
+ maxConnectionChars: args.max_connection_chars,
390
+ maxExclamations: args.max_exclamations,
391
+ maxLinks: args.max_links,
392
+ maxSubjectChars: args.max_subject_chars,
393
+ spamWords: args.spam_words
394
+ };
395
+ const thread = isEmail ? threadOf(sequence2.steps) : null;
396
+ const variants = sequence2.steps.flatMap(
397
+ (step) => step.variants.map((variant) => ({ step, variant }))
398
+ );
399
+ const findings = variants.flatMap(
400
+ ({ step, variant }) => auditVariant(step, variant, limits, thread)
401
+ ).toSorted(
402
+ (left, right) => RANK2[left.severity] - RANK2[right.severity] || left.step - right.step || left.variantKey.localeCompare(right.variantKey) || left.check.localeCompare(right.check)
403
+ );
404
+ const withoutBody = variants.filter(
405
+ ({ variant }) => variant.body === null
406
+ ).length;
407
+ if (withoutBody > 0) {
408
+ context.note(
409
+ `${withoutBody} variant(s) have no body in the vendor's answer, so their body checks were skipped.`
410
+ );
411
+ }
412
+ const severity = (level) => findings.filter((finding) => finding.severity === level).length;
413
+ const audit2 = {
414
+ byCheck: countsOf(findings, isEmail),
415
+ bySeverity: {
416
+ high: severity("high"),
417
+ low: severity("low"),
418
+ medium: severity("medium")
419
+ },
420
+ campaign: args.campaign,
421
+ channel: campaign.channel,
422
+ clean: findings.length === 0,
423
+ findings,
424
+ stepsChecked: sequence2.steps.length,
425
+ variantsChecked: variants.length,
426
+ variantsWithoutBody: withoutBody
427
+ };
428
+ return audit2;
429
+ }
430
+ });
431
+
432
+ // src/insights/copy/copy-reuse.ts
433
+ import { z as z3 } from "zod";
434
+
435
+ // src/insights/stats.ts
436
+ var PLACES = 1e4;
437
+ var round = (value) => value === null || !Number.isFinite(value) ? null : Math.round(value * PLACES) / PLACES;
438
+ var rate = (part, whole) => part === null || whole === null || whole <= 0 ? null : round(part / whole);
439
+ var total = (values) => {
440
+ const known2 = values.filter((value) => value !== null);
441
+ return known2.length === 0 ? null : known2.reduce((sum, value) => sum + value, 0);
442
+ };
443
+ var mean = (values) => values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length;
444
+ var percentile = (values, fraction) => {
445
+ if (values.length === 0) {
446
+ return null;
447
+ }
448
+ const sorted = values.toSorted((left, right) => left - right);
449
+ const position = (sorted.length - 1) * Math.min(Math.max(fraction, 0), 1);
450
+ const below = Math.floor(position);
451
+ const low = sorted[below] ?? 0;
452
+ const high = sorted[Math.ceil(position)] ?? low;
453
+ return low + (high - low) * (position - below);
454
+ };
455
+ var median = (values) => percentile(values, 0.5);
456
+ var deviation = (values) => {
457
+ const center = mean(values);
458
+ if (center === null || values.length < 2) {
459
+ return null;
460
+ }
461
+ const squares = values.reduce((sum, value) => sum + (value - center) ** 2, 0);
462
+ return Math.sqrt(squares / (values.length - 1));
463
+ };
464
+ var zScore = (value, history) => {
465
+ const center = mean(history);
466
+ const spread = deviation(history);
467
+ return center === null || spread === null || spread === 0 ? null : (value - center) / spread;
468
+ };
469
+ var Z_95 = 1.96;
470
+ var wilson = (successes, trials) => {
471
+ if (successes === null || trials === null || trials <= 0) {
472
+ return null;
473
+ }
474
+ const share2 = Math.min(successes / trials, 1);
475
+ const square = Z_95 ** 2;
476
+ const denominator = 1 + square / trials;
477
+ const center = share2 + square / (2 * trials);
478
+ const margin = Z_95 * Math.sqrt(share2 * (1 - share2) / trials + square / (4 * trials ** 2));
479
+ return {
480
+ high: round(Math.min(1, (center + margin) / denominator)) ?? 1,
481
+ low: round(Math.max(0, (center - margin) / denominator)) ?? 0
482
+ };
483
+ };
484
+ var erf = (value) => {
485
+ const sign = value < 0 ? -1 : 1;
486
+ const x = Math.abs(value);
487
+ const t = 1 / (1 + 0.3275911 * x);
488
+ const polynomial = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t;
489
+ return sign * (1 - polynomial * Math.exp(-x * x));
490
+ };
491
+ var compareRates = (first, second, alpha = 0.05) => {
492
+ if (first.successes === null || first.trials === null || second.successes === null || second.trials === null || first.trials <= 0 || second.trials <= 0) {
493
+ return null;
494
+ }
495
+ const pooled2 = (first.successes + second.successes) / (first.trials + second.trials);
496
+ const error = Math.sqrt(
497
+ pooled2 * (1 - pooled2) * (1 / first.trials + 1 / second.trials)
498
+ );
499
+ if (error === 0) {
500
+ return null;
501
+ }
502
+ const z33 = (first.successes / first.trials - second.successes / second.trials) / error;
503
+ const pValue = 1 - erf(Math.abs(z33) / Math.SQRT2);
504
+ return {
505
+ pValue: round(pValue) ?? 0,
506
+ significant: pValue < alpha,
507
+ z: round(z33) ?? 0
508
+ };
509
+ };
510
+ var pText = (pValue) => pValue < 1 / PLACES ? `p < ${1 / PLACES}` : `p = ${pValue}`;
511
+ var tally = (values) => {
512
+ const counts = /* @__PURE__ */ new Map();
513
+ for (const value of values) {
514
+ counts.set(value, (counts.get(value) ?? 0) + 1);
515
+ }
516
+ return counts;
517
+ };
518
+
519
+ // src/insights/copy/shared.ts
520
+ import { z as z2 } from "zod";
521
+ var dayInput = (description) => z2.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "must be YYYY-MM-DD").nullable().default(null).describe(description);
522
+ var rangeOf = (from, to) => ({
523
+ from: from ?? void 0,
524
+ to: to ?? void 0
525
+ });
526
+ var readCapped = (context, walk, max) => context.all(walk(max));
527
+ var campaignsIn = async (context, statuses, max) => {
528
+ const { outbound } = context;
529
+ if (outbound.capabilities["campaigns.status"] === false) {
530
+ const every = await readCapped(
531
+ context,
532
+ (cap) => outbound.campaigns.listAll({ max: cap }),
533
+ max
534
+ );
535
+ return every.filter((campaign) => statuses.includes(campaign.status));
536
+ }
537
+ const found = [];
538
+ for (const status of new Set(statuses)) {
539
+ const page = await readCapped(
540
+ context,
541
+ (cap) => outbound.campaigns.listAll({ max: cap, status }),
542
+ max - found.length
543
+ );
544
+ found.push(...page);
545
+ }
546
+ return found;
547
+ };
548
+ var firstKnown = (candidates) => {
549
+ for (const [basis, value] of candidates) {
550
+ if (value !== null && value > 0) {
551
+ return { basis, trials: value };
552
+ }
553
+ }
554
+ return { basis: null, trials: null };
555
+ };
556
+ var perLead = (counts) => firstKnown([
557
+ ["contacted", counts.contacted],
558
+ ["sent", counts.sent]
559
+ ]);
560
+ var perMessage = (counts) => firstKnown([
561
+ ["delivered", counts.delivered],
562
+ ["sent", counts.sent]
563
+ ]);
564
+ var measure = (count, base) => ({
565
+ basis: base.basis,
566
+ count,
567
+ interval: wilson(count, base.trials),
568
+ rate: rate(count, base.trials),
569
+ trials: base.trials
570
+ });
571
+ var sumRows = (rows) => sumCounts(rows);
572
+ var groupBy = (values, keyOf2) => {
573
+ const groups = /* @__PURE__ */ new Map();
574
+ for (const value of values) {
575
+ const key = keyOf2(value);
576
+ const group = groups.get(key);
577
+ if (group === void 0) {
578
+ groups.set(key, [value]);
579
+ } else {
580
+ group.push(value);
581
+ }
582
+ }
583
+ return groups;
584
+ };
585
+ var stepStats = (rows) => {
586
+ const whole = rows.filter((row) => row.variantKey === null);
587
+ const variants = new Map(
588
+ [...groupBy(rows, (row) => row.variantKey)].flatMap(
589
+ ([key, group]) => key === null ? [] : [[key, sumRows(group)]]
590
+ )
591
+ );
592
+ return {
593
+ total: sumRows(whole.length > 0 ? whole : rows),
594
+ variants
595
+ };
596
+ };
597
+ var splitStats = (rows) => {
598
+ const byStep = groupBy(rows, (row) => row.stepIndex);
599
+ const steps = new Map(
600
+ [...byStep].flatMap(
601
+ ([index, group]) => index === null ? [] : [[index, stepStats(group)]]
602
+ )
603
+ );
604
+ return { steps, unattributed: byStep.get(null) ?? [] };
605
+ };
606
+
607
+ // src/insights/copy/copy-reuse.ts
608
+ var input2 = z3.object({
609
+ max_campaigns: z3.number().int().min(1).max(200).default(20).describe(
610
+ "The most campaigns to read. Each costs 2 requests: its sequence and its step stats."
611
+ ),
612
+ min_sent: z3.number().int().min(1).default(100).describe(
613
+ "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."
614
+ ),
615
+ statuses: z3.array(campaignStatusSchema).min(1).default(["active", "paused", "completed"]).describe("The campaign statuses to read.")
616
+ });
617
+ var PREVIEW = 120;
618
+ var placementsOf = (campaign, sequence2, stats) => sequence2.steps.flatMap((step) => {
619
+ const found = stats.steps.get(step.index);
620
+ return step.variants.flatMap((variant) => {
621
+ if ((variant.subject ?? "") === "" && (variant.body ?? "") === "") {
622
+ return [];
623
+ }
624
+ const whole = step.variants.length === 1 ? found?.total ?? null : null;
625
+ return [
626
+ {
627
+ body: variant.body,
628
+ campaign,
629
+ contentHash: variant.contentHash,
630
+ counts: found?.variants.get(variant.variantKey) ?? whole,
631
+ place: `${step.index}:${variant.variantKey}`,
632
+ subject: variant.subject
633
+ }
634
+ ];
635
+ });
636
+ });
637
+ var pooled = (counts) => {
638
+ const measured2 = counts.flatMap((each) => {
639
+ const one = each === null ? null : measure(each.replied, perLead(each));
640
+ return one === null || one.rate === null ? [] : [one];
641
+ });
642
+ const replies2 = total(measured2.map((each) => each.count));
643
+ const trials = total(measured2.map((each) => each.trials));
644
+ return {
645
+ ...measure(replies2, { basis: null, trials }),
646
+ sent: total(counts.map((each) => each?.sent ?? null))
647
+ };
648
+ };
649
+ var useOf = (placements) => {
650
+ const [first] = placements;
651
+ if (first === void 0) {
652
+ return [];
653
+ }
654
+ const sum = pooled(placements.map((placement) => placement.counts));
655
+ return [
656
+ {
657
+ campaign: first.campaign.ref,
658
+ campaignName: first.campaign.name,
659
+ places: placements.map((placement) => placement.place),
660
+ provider: first.campaign.provider,
661
+ replies: sum.count,
662
+ replyRate: sum.rate,
663
+ replyRateInterval: sum.interval,
664
+ sent: sum.sent,
665
+ trials: sum.trials
666
+ }
667
+ ];
668
+ };
669
+ var pieceOf = (placements, uses) => {
670
+ const [first] = placements;
671
+ if (first === void 0) {
672
+ return [];
673
+ }
674
+ const sum = pooled(placements.map((placement) => placement.counts));
675
+ return [
676
+ {
677
+ bodyPreview: first.body?.slice(0, PREVIEW) ?? null,
678
+ campaigns: uses.length,
679
+ contentHash: first.contentHash,
680
+ replies: sum.count,
681
+ replyRate: sum.rate,
682
+ replyRateInterval: sum.interval,
683
+ sent: sum.sent,
684
+ subject: first.subject,
685
+ trials: sum.trials
686
+ }
687
+ ];
688
+ };
689
+ var byRate = (left, right) => (right.replyRate ?? -1) - (left.replyRate ?? -1) || (right.trials ?? 0) - (left.trials ?? 0);
690
+ var spreadOf = (uses, minSent) => {
691
+ const judged = uses.filter(
692
+ (use) => use.replyRate !== null && (use.trials ?? 0) >= minSent
693
+ );
694
+ const [best] = judged;
695
+ const worst = judged.at(-1);
696
+ if (best === void 0 || worst === void 0 || judged.length < 2) {
697
+ return {
698
+ best: null,
699
+ finding: `Fewer than two campaigns have a base of ${minSent}, so the spread is not judged.`,
700
+ spread: null,
701
+ spreadIsReal: null,
702
+ spreadPValue: null,
703
+ worst: null
704
+ };
705
+ }
706
+ const test = compareRates(
707
+ { successes: best.replies, trials: best.trials },
708
+ { successes: worst.replies, trials: worst.trials }
709
+ );
710
+ const real = test?.significant ?? false;
711
+ return {
712
+ best: best.campaign,
713
+ finding: real ? `The same copy gets ${best.replyRate} in ${best.campaignName} and ${worst.replyRate} in ${worst.campaignName}; the gap is more than chance, so the audience or the sender differs, not the copy.` : `The same copy gets ${best.replyRate} in ${best.campaignName} and ${worst.replyRate} in ${worst.campaignName}; a gap this size could be chance.`,
714
+ spread: round((best.replyRate ?? 0) - (worst.replyRate ?? 0)),
715
+ spreadIsReal: real,
716
+ spreadPValue: test?.pValue ?? null,
717
+ worst: worst.campaign
718
+ };
719
+ };
720
+ var readPlacements = async (context, campaigns) => {
721
+ const placements = [];
722
+ for (const campaign of campaigns) {
723
+ const handle = context.outbound.campaign(campaign.ref);
724
+ const sequence2 = context.one(await handle.sequence());
725
+ const rows = context.rows(await handle.stats({ scope: "step" }));
726
+ placements.push(...placementsOf(campaign, sequence2, splitStats(rows)));
727
+ }
728
+ return placements;
729
+ };
730
+ var copyReuse = defineInsight({
731
+ description: "How the same piece of copy performs in different campaigns. Reads each campaign's sequence and step stats, matches variants by the hash of their subject and body, and returns every piece of copy used in two or more campaigns with its totals, its reply rate per campaign and the spread between its best and worst campaign, plus the copy with the highest pooled reply rate. Use it to tell a copy problem from an audience problem. Costs 2 requests per campaign plus the campaign listing. A null count means the vendor does not report it for that variant; it is never 0.",
732
+ inputSchema: input2,
733
+ key: "copyReuse",
734
+ name: "copy_reuse",
735
+ needs: ["sequence", "stats.byStep"],
736
+ next: "Use step_funnel on the campaign where the copy does worst, or variant_test where the copy runs against another variant.",
737
+ run: async (context, { max_campaigns, min_sent, statuses }) => {
738
+ const campaigns = await campaignsIn(context, statuses, max_campaigns);
739
+ const placements = await readPlacements(context, campaigns);
740
+ const without = placements.filter((each) => each.counts === null).length;
741
+ if (without > 0) {
742
+ context.note(
743
+ `${without} variant(s) have no counts of their own: the vendor reports their step as a whole, or not at all. Their copy is listed without numbers.`
744
+ );
745
+ }
746
+ const pieces = [...groupBy(placements, (each) => each.contentHash)].flatMap(
747
+ ([, group]) => {
748
+ const uses = [...groupBy(group, (each) => each.campaign.ref).values()].flatMap(useOf).toSorted(byRate);
749
+ return pieceOf(group, uses).map((piece) => ({ piece, uses }));
750
+ }
751
+ );
752
+ const reused = pieces.flatMap(
753
+ ({ piece, uses }) => uses.length < 2 ? [] : [{ ...piece, ...spreadOf(uses, min_sent), uses }]
754
+ ).toSorted(
755
+ (left, right) => (right.spread ?? -1) - (left.spread ?? -1) || (right.sent ?? 0) - (left.sent ?? 0)
756
+ );
757
+ const [bestCopy] = pieces.flatMap(
758
+ ({ piece }) => piece.replyRate !== null && (piece.trials ?? 0) >= min_sent ? [piece] : []
759
+ ).toSorted(byRate);
760
+ const result = {
761
+ bestCopy: bestCopy ?? null,
762
+ campaignsRead: campaigns.length,
763
+ piecesOfCopy: pieces.length,
764
+ reused,
765
+ variantsWithoutStats: without
766
+ };
767
+ return result;
768
+ }
769
+ });
770
+
771
+ // src/insights/copy/reply-timing.ts
772
+ import { z as z4 } from "zod";
773
+ var DAY_MS = 864e5;
774
+ var HOUR_MS = 36e5;
775
+ var MINUTE_MS = 6e4;
776
+ var input3 = z4.object({
777
+ campaign: z4.string().min(1).nullable().default(null).describe(
778
+ "A campaign's ref to look at one campaign. null looks at every campaign."
779
+ ),
780
+ max_messages: z4.number().int().min(1).max(5e4).default(2e3).describe(
781
+ "The most messages to read, sent and received together. A page of messages costs 1 request."
782
+ ),
783
+ since: z4.iso.datetime({ offset: true }).nullable().default(null).describe(
784
+ "Only messages from this time on, ISO 8601. null means 30 days before now."
785
+ ),
786
+ timezone_offset_minutes: z4.number().int().min(-720).max(840).default(0).describe(
787
+ "Minutes to add to UTC for the weekday and hour tables, for example -300 for New York in winter."
788
+ )
789
+ });
790
+ var WEEKDAYS = [
791
+ "Sunday",
792
+ "Monday",
793
+ "Tuesday",
794
+ "Wednesday",
795
+ "Thursday",
796
+ "Friday",
797
+ "Saturday"
798
+ ];
799
+ var timeOf = (message) => message.sentAt === null ? null : Date.parse(message.sentAt);
800
+ var pair = (messages) => {
801
+ const byThread = /* @__PURE__ */ new Map();
802
+ const byLead = /* @__PURE__ */ new Map();
803
+ const pairs = [];
804
+ const replyTimes = [];
805
+ let followOn = 0;
806
+ let unpaired = 0;
807
+ const timed = messages.flatMap((message) => {
808
+ const at = timeOf(message);
809
+ return at === null ? [] : [{ at, message }];
810
+ }).toSorted((left, right) => left.at - right.at);
811
+ for (const { at, message } of timed) {
812
+ const { leadRef } = message;
813
+ const threadId = message.threadId === null ? null : `${message.provider}:${message.workspaceId}:${message.threadId}`;
814
+ if (message.direction === "out") {
815
+ const sent = { answered: false, at };
816
+ if (threadId !== null) {
817
+ byThread.set(threadId, sent);
818
+ }
819
+ if (leadRef !== null) {
820
+ byLead.set(leadRef, sent);
821
+ }
822
+ } else {
823
+ replyTimes.push(at);
824
+ const sent = (threadId === null ? void 0 : byThread.get(threadId)) ?? (leadRef === null ? void 0 : byLead.get(leadRef));
825
+ if (sent === void 0) {
826
+ unpaired += 1;
827
+ } else if (sent.answered) {
828
+ followOn += 1;
829
+ } else {
830
+ sent.answered = true;
831
+ pairs.push({ at, sentAt: sent.at });
832
+ }
833
+ }
834
+ }
835
+ return { followOn, pairs, replyTimes, unpaired };
836
+ };
837
+ var topOf = (entries) => {
838
+ let top = null;
839
+ for (const entry of entries) {
840
+ if (entry.count > (top?.count ?? 0)) {
841
+ top = entry;
842
+ }
843
+ }
844
+ return top;
845
+ };
846
+ var tableOf = (times3, offsetMinutes) => {
847
+ const days = Array.from({ length: 7 }, () => 0);
848
+ const hours = Array.from({ length: 24 }, () => 0);
849
+ for (const time of times3) {
850
+ const local = new Date(time + offsetMinutes * MINUTE_MS);
851
+ days[local.getUTCDay()] = (days[local.getUTCDay()] ?? 0) + 1;
852
+ hours[local.getUTCHours()] = (hours[local.getUTCHours()] ?? 0) + 1;
853
+ }
854
+ const byWeekday = [1, 2, 3, 4, 5, 6, 0].map((day) => ({
855
+ count: days[day] ?? 0,
856
+ share: rate(days[day] ?? 0, times3.length),
857
+ weekday: WEEKDAYS[day] ?? "Sunday"
858
+ }));
859
+ const byHour = hours.map((count, hour) => ({
860
+ count,
861
+ hour,
862
+ share: rate(count, times3.length)
863
+ }));
864
+ return {
865
+ byHour,
866
+ byWeekday,
867
+ topHour: topOf(byHour)?.hour ?? null,
868
+ topWeekday: topOf(byWeekday)?.weekday ?? null
869
+ };
870
+ };
871
+ var readMessages = async (context, campaign, since, max) => {
872
+ const { outbound } = context;
873
+ const filters = outbound.capabilities["messages.since"] === false ? {} : { since };
874
+ const messages = await readCapped(
875
+ context,
876
+ (cap) => campaign === null ? outbound.messages.listAll({ ...filters, max: cap }) : outbound.campaign(campaign).messages.listAll({ ...filters, max: cap }),
877
+ max
878
+ );
879
+ if (outbound.capabilities["messages.since"] === false) {
880
+ context.note(
881
+ "This tool cannot filter messages by date, so the cap applies to all messages and older ones were dropped after reading."
882
+ );
883
+ }
884
+ return messages.filter(
885
+ (message) => message.sentAt === null || message.sentAt >= since
886
+ );
887
+ };
888
+ var replyTiming = defineInsight({
889
+ description: "How fast people reply and when. Pairs each received message with the last message sent before it in the same thread (or to the same lead) and returns the median, 75th and 90th percentile of hours to reply, the share of replies within 1, 24 and 72 hours, replies by weekday and by hour of day, the weekday and hour of the sends that drew replies, and how many replies could not be paired. Use it to choose follow-up delays and sending hours. Costs 1 request per page of messages, up to max_messages. A null figure means no reply could be paired; auto-replies are not separated, because messages carry no auto flag.",
890
+ inputSchema: input3,
891
+ key: "replyTiming",
892
+ name: "reply_timing",
893
+ needs: ["messages.list"],
894
+ next: "Use step_funnel to see which step the replies answer, then set follow-up delays near the median time to reply.",
895
+ run: async (context, args) => {
896
+ const since = args.since === null ? new Date(context.now - 30 * DAY_MS).toISOString() : new Date(args.since).toISOString();
897
+ const messages = await readMessages(
898
+ context,
899
+ args.campaign,
900
+ since,
901
+ args.max_messages
902
+ );
903
+ const paired = pair(messages);
904
+ const hours = paired.pairs.map((each) => (each.at - each.sentAt) / HOUR_MS);
905
+ const within = (limit2) => rate(hours.filter((value) => value <= limit2).length, hours.length);
906
+ const received = messages.filter((message) => message.direction === "in");
907
+ const untimed = received.length - paired.replyTimes.length;
908
+ const timing = {
909
+ campaign: args.campaign,
910
+ counts: {
911
+ followOnReplies: paired.followOn,
912
+ messagesRead: messages.length,
913
+ paired: paired.pairs.length,
914
+ received: received.length,
915
+ sent: messages.length - received.length,
916
+ unpaired: paired.unpaired + untimed
917
+ },
918
+ replies: tableOf(paired.replyTimes, args.timezone_offset_minutes),
919
+ sendsThatDrewReplies: tableOf(
920
+ paired.pairs.map((each) => each.sentAt),
921
+ args.timezone_offset_minutes
922
+ ),
923
+ since,
924
+ timeToReply: {
925
+ medianHours: round(median(hours)),
926
+ p75Hours: round(percentile(hours, 0.75)),
927
+ p90Hours: round(percentile(hours, 0.9)),
928
+ sample: paired.pairs.length,
929
+ within1Hour: within(1),
930
+ within24Hours: within(24),
931
+ within72Hours: within(72)
932
+ },
933
+ timezoneOffsetMinutes: args.timezone_offset_minutes
934
+ };
935
+ return timing;
936
+ }
937
+ });
938
+
939
+ // src/insights/copy/step-funnel.ts
940
+ import { z as z5 } from "zod";
941
+ var input4 = z5.object({
942
+ campaign: z5.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
943
+ from: dayInput("First day to count, YYYY-MM-DD. null counts from the start."),
944
+ min_reply_rate: z5.number().min(0).max(1).default(0).describe(
945
+ "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."
946
+ ),
947
+ to: dayInput("Last day to count, YYYY-MM-DD. null counts to today.")
948
+ });
949
+ var variantsOf = (stats, step) => [...stats?.variants ?? []].map(([variantKey, counts]) => {
950
+ const measured2 = measure(counts.replied, perLead(counts));
951
+ return {
952
+ contentHash: step?.variants.find((variant) => variant.variantKey === variantKey)?.contentHash ?? null,
953
+ replies: counts.replied,
954
+ replyRate: measured2.rate,
955
+ replyRateInterval: measured2.interval,
956
+ sent: counts.sent,
957
+ variantKey
958
+ };
959
+ });
960
+ var draftOf = (index, step, stats, minReplyRate) => {
961
+ const counts = stats?.total ?? null;
962
+ const measured2 = counts === null ? null : measure(counts.replied, perLead(counts));
963
+ const interval = measured2?.interval ?? null;
964
+ return {
965
+ action: step?.action ?? null,
966
+ delayDays: step?.delayDays ?? null,
967
+ earnsPlace: interval === null ? null : interval.low > minReplyRate,
968
+ inSequence: step !== void 0,
969
+ parent: step === void 0 ? null : step.parentIndex,
970
+ replies: counts?.replied ?? null,
971
+ replyRate: measured2?.rate ?? null,
972
+ replyRateBasis: measured2?.basis ?? null,
973
+ replyRateInterval: interval,
974
+ sent: counts?.sent ?? null,
975
+ step: index,
976
+ variants: variantsOf(stats, step)
977
+ };
978
+ };
979
+ var finish = (drafts, allReplies) => drafts.map(({ parent, ...draft }, position) => {
980
+ const before = draft.inSequence ? drafts.find((other) => other.step === parent) : drafts[position - 1];
981
+ const drop = before === void 0 || before.sent === null || draft.sent === null ? null : before.sent - draft.sent;
982
+ return {
983
+ ...draft,
984
+ sentDrop: drop,
985
+ sentDropRate: rate(drop, before?.sent ?? null),
986
+ shareOfReplies: rate(draft.replies, allReplies)
987
+ };
988
+ });
989
+ var topOf2 = (steps) => {
990
+ let top = null;
991
+ for (const step of steps) {
992
+ if ((step.replies ?? 0) > (top?.replies ?? 0)) {
993
+ top = step;
994
+ }
995
+ }
996
+ return top;
997
+ };
998
+ var describe = (steps, top, last, allReplies) => {
999
+ if (steps.every((step) => step.sent === null)) {
1000
+ return "No step has stats yet, so there is nothing to compare.";
1001
+ }
1002
+ if (top === null) {
1003
+ return "No step has a reply in this range.";
1004
+ }
1005
+ const lead = `Step ${top.step} (counted from 0) brings the most replies: ${top.replies} of ${allReplies}.`;
1006
+ if (last === null) {
1007
+ return `${lead} No step's reply rate is reliably above the bar yet.`;
1008
+ }
1009
+ const later = steps.filter(
1010
+ (step) => step.step > last.step && step.sent !== null
1011
+ );
1012
+ return later.length === 0 ? `${lead} Every step up to step ${last.step} still earns its place.` : `${lead} Step ${last.step} is the last whose reply rate is reliably above the bar; the ${later.length} later step(s) sent ${total(later.map((step) => step.sent))} messages for ${total(later.map((step) => step.replies)) ?? "an unknown number of"} replies.`;
1013
+ };
1014
+ var unattributedOf = (rows) => {
1015
+ const counts = sumRows(rows);
1016
+ return { replies: counts.replied, rows: rows.length, sent: counts.sent };
1017
+ };
1018
+ var stepFunnel = defineInsight({
1019
+ 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.",
1020
+ inputSchema: input4,
1021
+ key: "stepFunnel",
1022
+ name: "step_funnel",
1023
+ needs: ["sequence", "stats.byStep"],
1024
+ next: "Use variant_test on the same campaign to see whether a step's A/B winner is real, or copy_audit to check the copy of a weak step.",
1025
+ run: async (context, { campaign, from, min_reply_rate: bar, to }) => {
1026
+ const handle = context.outbound.campaign(campaign);
1027
+ const sequence2 = context.one(await handle.sequence());
1028
+ const rows = context.rows(
1029
+ await handle.stats({ ...rangeOf(from, to), scope: "step" })
1030
+ );
1031
+ const split = splitStats(rows);
1032
+ const indexes = [
1033
+ .../* @__PURE__ */ new Set([
1034
+ ...sequence2.steps.map((step) => step.index),
1035
+ ...split.steps.keys()
1036
+ ])
1037
+ ].toSorted((left, right) => left - right);
1038
+ const drafts = indexes.map(
1039
+ (index) => draftOf(
1040
+ index,
1041
+ sequence2.steps.find((step) => step.index === index),
1042
+ split.steps.get(index),
1043
+ bar
1044
+ )
1045
+ );
1046
+ const unattributed = unattributedOf(split.unattributed);
1047
+ const allReplies = total([
1048
+ ...drafts.map((draft) => draft.replies),
1049
+ unattributed.replies
1050
+ ]);
1051
+ const steps = finish(drafts, allReplies);
1052
+ const top = topOf2(steps);
1053
+ const last = steps.findLast((step) => step.earnsPlace === true) ?? null;
1054
+ if (unattributed.rows > 0) {
1055
+ context.note(
1056
+ "Some counts are tied to no step by the vendor; they are reported as unattributed and are in no step's row."
1057
+ );
1058
+ }
1059
+ const funnel = {
1060
+ campaign,
1061
+ finding: describe(steps, top, last, allReplies),
1062
+ lastStepEarningPlace: last?.step ?? null,
1063
+ steps,
1064
+ topStep: top?.step ?? null,
1065
+ totals: {
1066
+ replies: allReplies,
1067
+ sent: total([...drafts.map((draft) => draft.sent), unattributed.sent])
1068
+ },
1069
+ unattributed
1070
+ };
1071
+ return funnel;
1072
+ }
1073
+ });
1074
+
1075
+ // src/insights/copy/variant-test.ts
1076
+ import { z as z6 } from "zod";
1077
+ var METRICS = ["replied", "positive", "opened", "clicked"];
1078
+ var input5 = z6.object({
1079
+ alpha: z6.number().gt(0).max(0.5).default(0.05).describe(
1080
+ "The chance of calling a winner that is not one. A difference with a p-value under this is a winner."
1081
+ ),
1082
+ campaign: z6.string().min(1).describe("The campaign's ref, for example `instantly:acme:abc123`"),
1083
+ from: dayInput("First day to count, YYYY-MM-DD. null counts from the start."),
1084
+ metric: z6.enum(METRICS).default("replied").describe(
1085
+ "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)."
1086
+ ),
1087
+ min_sent: z6.number().int().min(1).default(100).describe(
1088
+ "A variant with a smaller base than this (sends, or leads contacted when the vendor counts those) is not compared."
1089
+ ),
1090
+ to: dayInput("Last day to count, YYYY-MM-DD. null counts to today.")
1091
+ });
1092
+ var ORDER = {
1093
+ no_difference_yet: 1,
1094
+ too_little_data: 2,
1095
+ winner: 0
1096
+ };
1097
+ var quantile = (tail) => {
1098
+ const t = Math.sqrt(-2 * Math.log(tail));
1099
+ return t - (2.515517 + 0.802853 * t + 0.010328 * t ** 2) / (1 + 1.432788 * t + 0.189269 * t ** 2 + 1308e-6 * t ** 3);
1100
+ };
1101
+ var sendsToSignificance = (score, trials, alpha) => score === 0 ? null : Math.max(0, Math.ceil(((quantile(alpha / 2) / score) ** 2 - 1) * trials));
1102
+ var candidateOf = (variantKey, counts, metric, minSent) => {
1103
+ const base = metric === "replied" || metric === "positive" ? perLead(counts) : perMessage(counts);
1104
+ const measured2 = measure(counts[metric], base);
1105
+ return {
1106
+ ...measured2,
1107
+ enoughData: measured2.rate !== null && measured2.trials !== null && measured2.trials >= minSent,
1108
+ sent: counts.sent,
1109
+ variantKey
1110
+ };
1111
+ };
1112
+ var shortfall = (candidates, minSent) => {
1113
+ if (candidates.some((each) => each.count === null)) {
1114
+ return null;
1115
+ }
1116
+ return candidates.reduce(
1117
+ (sum, each) => sum + Math.max(0, minSent - (each.trials ?? 0)),
1118
+ 0
1119
+ );
1120
+ };
1121
+ var tooLittle = (step, candidates, settings) => {
1122
+ const unreported = candidates.some((each) => each.count === null);
1123
+ return {
1124
+ leader: null,
1125
+ moreSendsNeeded: shortfall(candidates, settings.minSent),
1126
+ pValue: null,
1127
+ reason: unreported ? `The vendor does not report ${settings.metric} for every variant of this step, so they cannot be compared.` : `Fewer than two variants have a base of ${settings.minSent}, so no comparison is made.`,
1128
+ step,
1129
+ variants: candidates.map((each) => ({ ...each, pValueVsLeader: null })),
1130
+ verdict: "too_little_data"
1131
+ };
1132
+ };
1133
+ var testStep = (step, candidates, settings) => {
1134
+ const ready = candidates.filter((each) => each.enoughData).toSorted(
1135
+ (left, right) => (right.rate ?? 0) - (left.rate ?? 0) || (right.trials ?? 0) - (left.trials ?? 0)
1136
+ );
1137
+ const [leader, rival] = ready;
1138
+ if (leader === void 0 || rival === void 0) {
1139
+ return tooLittle(step, candidates, settings);
1140
+ }
1141
+ const tests = new Map(
1142
+ ready.slice(1).map((other) => [
1143
+ other.variantKey,
1144
+ compareRates(
1145
+ { successes: leader.count, trials: leader.trials },
1146
+ { successes: other.count, trials: other.trials },
1147
+ settings.alpha
1148
+ )
1149
+ ])
1150
+ );
1151
+ const closest = tests.get(rival.variantKey) ?? null;
1152
+ const beatsAll = [...tests.values()].every((test) => test?.significant);
1153
+ const skipped = candidates.length - ready.length;
1154
+ const aside = skipped === 0 ? "" : ` ${skipped} variant(s) with too little data were left out.`;
1155
+ const variants = candidates.map((each) => ({
1156
+ ...each,
1157
+ pValueVsLeader: tests.get(each.variantKey)?.pValue ?? null
1158
+ }));
1159
+ if (beatsAll) {
1160
+ return {
1161
+ leader: leader.variantKey,
1162
+ moreSendsNeeded: null,
1163
+ pValue: closest?.pValue ?? null,
1164
+ reason: `Variant ${leader.variantKey} (${leader.rate}) beats every other variant by more than chance at alpha ${settings.alpha}.${aside}`,
1165
+ step,
1166
+ variants,
1167
+ verdict: "winner"
1168
+ };
1169
+ }
1170
+ return {
1171
+ leader: leader.variantKey,
1172
+ moreSendsNeeded: closest === null ? null : sendsToSignificance(
1173
+ closest.z,
1174
+ (leader.trials ?? 0) + (rival.trials ?? 0),
1175
+ settings.alpha
1176
+ ),
1177
+ pValue: closest?.pValue ?? null,
1178
+ reason: `Variant ${leader.variantKey} (${leader.rate}) leads variant ${rival.variantKey} (${rival.rate}), but a gap this size could be chance.${aside}`,
1179
+ step,
1180
+ variants,
1181
+ verdict: "no_difference_yet"
1182
+ };
1183
+ };
1184
+ var countOf = (steps, verdict) => steps.filter((step) => step.verdict === verdict).length;
1185
+ var variantTest = defineInsight({
1186
+ 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.",
1187
+ inputSchema: input5,
1188
+ key: "variantTest",
1189
+ name: "variant_test",
1190
+ needs: ["stats.byStep"],
1191
+ next: "Use step_funnel to see how much of the campaign's replies the tested step brings, or copy_audit to check the losing variant's copy.",
1192
+ run: async (context, { alpha, campaign, from, metric, min_sent, to }) => {
1193
+ const rows = context.rows(
1194
+ await context.outbound.campaign(campaign).stats({ ...rangeOf(from, to), scope: "step" })
1195
+ );
1196
+ const split = splitStats(rows);
1197
+ const settings = { alpha, metric, minSent: min_sent };
1198
+ const steps = [...split.steps].flatMap(
1199
+ ([step, stats]) => stats.variants.size < 2 ? [] : [
1200
+ testStep(
1201
+ step,
1202
+ [...stats.variants].map(
1203
+ ([key, counts]) => candidateOf(key, counts, metric, min_sent)
1204
+ ),
1205
+ settings
1206
+ )
1207
+ ]
1208
+ ).toSorted(
1209
+ (left, right) => ORDER[left.verdict] - ORDER[right.verdict] || left.step - right.step
1210
+ );
1211
+ const reported = rows.some((row) => row.variantKey !== null);
1212
+ if (!reported) {
1213
+ context.note(
1214
+ "The step stats carry no variant rows, so there is nothing to compare."
1215
+ );
1216
+ }
1217
+ const result = {
1218
+ alpha,
1219
+ campaign,
1220
+ metric,
1221
+ steps,
1222
+ totals: {
1223
+ noDifferenceYet: countOf(steps, "no_difference_yet"),
1224
+ stepsTested: steps.length,
1225
+ tooLittleData: countOf(steps, "too_little_data"),
1226
+ winners: countOf(steps, "winner")
1227
+ },
1228
+ variantStatsReported: reported
1229
+ };
1230
+ return result;
1231
+ }
1232
+ });
1233
+
1234
+ // src/insights/copy/index.ts
1235
+ var COPY_INSIGHTS = [
1236
+ stepFunnel,
1237
+ variantTest,
1238
+ copyAudit,
1239
+ copyReuse,
1240
+ replyTiming
1241
+ ];
1242
+
1243
+ // src/insights/ops/anomalies.ts
1244
+ import { z as z8 } from "zod";
1245
+
1246
+ // src/insights/ops/shared.ts
1247
+ import { z as z7 } from "zod";
1248
+ var DAY_MS2 = 864e5;
1249
+ var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1250
+ var shiftDay = (day, days) => dayOf(Date.parse(`${day}T00:00:00.000Z`) + days * DAY_MS2);
1251
+ var lastDays = (now, days, back = 0) => ({
1252
+ from: dayOf(now - days * (back + 1) * DAY_MS2),
1253
+ to: dayOf(now - (days * back + 1) * DAY_MS2)
1254
+ });
1255
+ var listFields = (costPerCampaign) => ({
1256
+ max_campaigns: z7.number().int().min(1).max(200).default(25).describe(`The most campaigns to read. Each costs ${costPerCampaign}.`),
1257
+ statuses: z7.array(campaignStatusSchema).min(1).default(["active", "paused", "completed"]).describe("Only campaigns in one of these states are read")
1258
+ });
1259
+ var rangeFields = {
1260
+ from: z7.iso.date().nullable().default(null).describe("First day counted, YYYY-MM-DD. null for the whole history."),
1261
+ to: z7.iso.date().nullable().default(null).describe("Last day counted, YYYY-MM-DD. null for up to today.")
1262
+ };
1263
+ var labelOf = (campaign) => ({
1264
+ campaign: campaign.ref,
1265
+ channel: campaign.channel,
1266
+ name: campaign.name,
1267
+ provider: campaign.provider,
1268
+ status: campaign.status
1269
+ });
1270
+ var totalsOf = (counts) => ({
1271
+ bounced: counts.bounced,
1272
+ contacted: counts.contacted,
1273
+ positive: counts.positive,
1274
+ replied: counts.replied,
1275
+ sent: counts.sent
1276
+ });
1277
+ var measure2 = (count, of) => {
1278
+ const interval = wilson(count, of);
1279
+ return {
1280
+ count,
1281
+ high: interval?.high ?? null,
1282
+ low: interval?.low ?? null,
1283
+ of,
1284
+ rate: rate(count, of)
1285
+ };
1286
+ };
1287
+ var perLeadBase = (counts) => counts.contacted !== null && counts.contacted > 0 ? counts.contacted : counts.sent;
1288
+ var ratesOf = (counts) => ({
1289
+ bounceRate: measure2(counts.bounced, counts.sent),
1290
+ positiveRate: measure2(counts.positive, perLeadBase(counts)),
1291
+ replyRate: measure2(counts.replied, perLeadBase(counts))
1292
+ });
1293
+ var measureAcross = (rows, countOf3, baseOf) => {
1294
+ const sides = rows.map((row) => ({ base: baseOf(row), count: countOf3(row) }));
1295
+ const pairs = sides.flatMap(
1296
+ ({ base, count }) => count === null || base === null ? [] : [{ base, count }]
1297
+ );
1298
+ return {
1299
+ counted: pairs.length,
1300
+ measured: pairs.length === 0 ? measure2(total(sides.map((side) => side.count)), null) : measure2(
1301
+ total(pairs.map((pair2) => pair2.count)),
1302
+ total(pairs.map((pair2) => pair2.base))
1303
+ ),
1304
+ of: sides.filter((side) => side.base !== null || side.count !== null).length
1305
+ };
1306
+ };
1307
+ var partialRate = (name, across) => across.counted > 0 && across.counted < across.of ? [`${name} (${across.counted} of ${across.of})`] : [];
1308
+ var ratesAcross = (rows) => {
1309
+ const reply = measureAcross(rows, (row) => row.replied, perLeadBase);
1310
+ const positive = measureAcross(rows, (row) => row.positive, perLeadBase);
1311
+ const bounce = measureAcross(
1312
+ rows,
1313
+ (row) => row.bounced,
1314
+ (row) => row.sent
1315
+ );
1316
+ return {
1317
+ partial: [
1318
+ ...partialRate("reply rate", reply),
1319
+ ...partialRate("positive reply rate", positive),
1320
+ ...partialRate("bounce rate", bounce)
1321
+ ],
1322
+ rates: {
1323
+ bounceRate: bounce.measured,
1324
+ positiveRate: positive.measured,
1325
+ replyRate: reply.measured
1326
+ }
1327
+ };
1328
+ };
1329
+ var partialNote = (where, partial, rows = "campaigns") => `${where}: ${partial.join(", ")} ${partial.length === 1 ? "counts" : "count"} only the ${rows} that report both the count and what it is divided by. The others are left out of the rate, not counted as 0.`;
1330
+ var volumeOf = (counts) => counts.sent ?? counts.contacted;
1331
+ var percent = (value) => value === null ? "unknown" : `${Math.round(value * 1e3) / 10}%`;
1332
+ var descending = (left, right) => {
1333
+ if (left === null || right === null) {
1334
+ return Number(left === null) - Number(right === null);
1335
+ }
1336
+ return right - left;
1337
+ };
1338
+ var readUpTo = async (context, list, max) => {
1339
+ const walk = list(max);
1340
+ const items = await context.all(walk);
1341
+ return { complete: !walk.truncated, items };
1342
+ };
1343
+ var readCampaigns = async (context, statuses, max) => {
1344
+ const { campaigns } = context.outbound;
1345
+ const wanted = [...new Set(statuses)];
1346
+ if (context.outbound.capabilities["campaigns.status"] === false) {
1347
+ const every = await readUpTo(
1348
+ context,
1349
+ (cap) => campaigns.listAll({ max: cap }),
1350
+ max
1351
+ );
1352
+ return every.items.filter((campaign) => wanted.includes(campaign.status));
1353
+ }
1354
+ const found = [];
1355
+ for (const status of wanted) {
1356
+ const listed = await readUpTo(
1357
+ context,
1358
+ (cap) => campaigns.listAll({ max: cap, status }),
1359
+ max - found.length
1360
+ );
1361
+ found.push(...listed.items);
1362
+ }
1363
+ return found;
1364
+ };
1365
+ var readTotals = async (context, campaign, range) => sumCounts(
1366
+ context.rows(
1367
+ await context.outbound.campaign(campaign).stats({ from: range.from ?? void 0, to: range.to ?? void 0 })
1368
+ )
1369
+ );
1370
+ var readCampaignTotals = async (context, input27) => {
1371
+ const campaigns = await readCampaigns(
1372
+ context,
1373
+ input27.statuses,
1374
+ input27.max_campaigns
1375
+ );
1376
+ const entries = [];
1377
+ for (const campaign of campaigns) {
1378
+ entries.push({
1379
+ campaign,
1380
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
1381
+ counts: await readTotals(context, campaign.ref, input27)
1382
+ });
1383
+ }
1384
+ return entries;
1385
+ };
1386
+ var readDaily = async (context, campaign, range) => {
1387
+ const options = { by: "day", from: range.from, to: range.to };
1388
+ const rows = context.rows(
1389
+ campaign === null ? await context.outbound.stats(options) : await context.outbound.campaign(campaign).stats(options)
1390
+ );
1391
+ const days = /* @__PURE__ */ new Map();
1392
+ for (const row of rows) {
1393
+ if (row.date !== null) {
1394
+ days.set(row.date, [...days.get(row.date) ?? [], row]);
1395
+ }
1396
+ }
1397
+ return [...days].map(([date, group]) => ({ counts: sumCounts(group), date })).toSorted((left, right) => left.date.localeCompare(right.date));
1398
+ };
1399
+
1400
+ // src/insights/ops/anomalies.ts
1401
+ var metricSchema = z8.enum([
1402
+ "sent",
1403
+ "contacted",
1404
+ "replied",
1405
+ "positive",
1406
+ "bounced",
1407
+ "opened",
1408
+ "clicked",
1409
+ "unsubscribed"
1410
+ ]);
1411
+ var input6 = z8.object({
1412
+ baseline_days: z8.number().int().min(5).max(60).default(14).describe("How many days before a day form the baseline it is held to"),
1413
+ campaign: z8.string().min(3).nullable().default(null).describe("A campaign ref. null checks the whole workspace."),
1414
+ days: z8.number().int().min(1).max(90).default(30).describe("How many complete days, ending yesterday, are checked"),
1415
+ metrics: z8.array(metricSchema).min(1).default(["sent", "replied", "bounced"]).describe("The daily counts to check"),
1416
+ min_baseline_points: z8.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
1417
+ threshold: z8.number().positive().default(2.5).describe("How many standard deviations from the baseline mean is unusual")
1418
+ });
1419
+ var reasonFor = (metric, daysWithData) => daysWithData === 0 ? `The vendor reports no ${metric} count for these days.` : "Too few earlier days with data to form a baseline.";
1420
+ var judge = (metric, point, baseline, threshold) => {
1421
+ const center = round(mean(baseline)) ?? 0;
1422
+ const score = zScore(point.value, baseline);
1423
+ const shared = {
1424
+ baselineMean: center,
1425
+ baselinePoints: baseline.length,
1426
+ date: point.date,
1427
+ direction: point.value > center ? "above" : "below",
1428
+ metric,
1429
+ value: point.value
1430
+ };
1431
+ if (score === null) {
1432
+ return point.value === baseline[0] ? null : {
1433
+ ...shared,
1434
+ finding: `${metric} was ${point.value} on ${point.date}, against ${center} on each of the ${baseline.length} days with data before it (a flat baseline has no z-score: any other count is flagged).`,
1435
+ judgedBy: "flat_baseline",
1436
+ zScore: null
1437
+ };
1438
+ }
1439
+ return Math.abs(score) < threshold ? null : {
1440
+ ...shared,
1441
+ finding: `${metric} was ${point.value} on ${point.date}, against an average of ${center} over the ${baseline.length} days with data before it (z = ${round(score)}).`,
1442
+ judgedBy: "z_score",
1443
+ zScore: round(score) ?? 0
1444
+ };
1445
+ };
1446
+ var scanMetric = (series, metric, options) => {
1447
+ const points = series.flatMap((day) => {
1448
+ const value = day.counts[metric];
1449
+ return value === null ? [] : [{ date: day.date, value }];
1450
+ });
1451
+ const checked = points.filter((point) => point.date >= options.firstDay);
1452
+ const anomalies2 = [];
1453
+ let tested = 0;
1454
+ for (const point of checked) {
1455
+ const start = shiftDay(point.date, -options.baselineDays);
1456
+ const baseline = points.flatMap(
1457
+ (other) => other.date >= start && other.date < point.date ? [other.value] : []
1458
+ );
1459
+ if (baseline.length >= options.minBaselinePoints) {
1460
+ tested += 1;
1461
+ const anomaly = judge(metric, point, baseline, options.threshold);
1462
+ if (anomaly !== null) {
1463
+ anomalies2.push(anomaly);
1464
+ }
1465
+ }
1466
+ }
1467
+ return {
1468
+ anomalies: anomalies2,
1469
+ coverage: {
1470
+ daysTested: tested,
1471
+ daysWithData: checked.length,
1472
+ metric,
1473
+ reason: tested > 0 ? null : reasonFor(metric, checked.length),
1474
+ testable: tested > 0
1475
+ }
1476
+ };
1477
+ };
1478
+ var sizeOf = (anomaly) => anomaly.zScore === null ? Number.POSITIVE_INFINITY : Math.abs(anomaly.zScore);
1479
+ var findAnomalies = (series, options) => {
1480
+ const scans = [...new Set(options.metrics)].map(
1481
+ (metric) => scanMetric(series, metric, options)
1482
+ );
1483
+ return {
1484
+ anomalies: scans.flatMap((scan) => scan.anomalies).toSorted(
1485
+ (left, right) => right.date.localeCompare(left.date) || descending(sizeOf(left), sizeOf(right))
1486
+ ),
1487
+ metrics: scans.map((scan) => scan.coverage)
1488
+ };
1489
+ };
1490
+ var anomalies = defineInsight({
1491
+ 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.",
1492
+ inputSchema: input6,
1493
+ key: "anomalies",
1494
+ name: "anomalies",
1495
+ needs: ["stats.byDay"],
1496
+ // The whole workspace is read from workspace stats, a campaign from its own.
1497
+ needsFor: (options) => options.campaign === null ? ["stats.workspace"] : ["stats.campaign"],
1498
+ next: "Use campaign_diagnosis on the campaign, or bounce_watch when the break is in bounces.",
1499
+ run: async (context, options) => {
1500
+ const period = lastDays(context.now, options.days);
1501
+ const series = await readDaily(context, options.campaign, {
1502
+ from: shiftDay(period.from, -options.baseline_days),
1503
+ to: period.to
1504
+ });
1505
+ const answer = {
1506
+ ...findAnomalies(series, {
1507
+ baselineDays: options.baseline_days,
1508
+ firstDay: period.from,
1509
+ metrics: options.metrics,
1510
+ minBaselinePoints: options.min_baseline_points,
1511
+ threshold: options.threshold
1512
+ }),
1513
+ period,
1514
+ scope: options.campaign ?? "workspace",
1515
+ threshold: options.threshold
1516
+ };
1517
+ return answer;
1518
+ }
1519
+ });
1520
+
1521
+ // src/insights/ops/campaign-diagnosis.ts
1522
+ import { z as z9 } from "zod";
1523
+
1524
+ // src/insights/ops/diagnosis-checks.ts
1525
+ var enough = (facts, limits) => (volumeOf(facts.totals) ?? -1) >= limits.minSent;
1526
+ var volume = (facts, limits) => {
1527
+ const sent = volumeOf(facts.totals);
1528
+ return enough(facts, limits) ? [] : [
1529
+ {
1530
+ code: "too_little_volume",
1531
+ finding: sent === null ? "The vendor reports no sends for this period, so no rate can be judged." : `Only ${sent} sends, under the ${limits.minSent} needed to judge a rate; reply and bounce rates are not assessed.`,
1532
+ next: "Let the campaign run longer, or widen the date range.",
1533
+ numbers: { minSent: limits.minSent, sent },
1534
+ severity: "medium"
1535
+ }
1536
+ ];
1537
+ };
1538
+ var bounces = (facts, limits) => {
1539
+ const { count, high, low, of, rate: rate2 } = facts.rates.bounceRate;
1540
+ return !enough(facts, limits) || rate2 === null || rate2 <= limits.maxBounceRate ? [] : [
1541
+ {
1542
+ code: "high_bounce_rate",
1543
+ finding: `Bounce rate is ${percent(rate2)} (${count} of ${of} sends), over the ${percent(limits.maxBounceRate)} limit.`,
1544
+ next: "Use bounce_watch to find the senders behind it, and verify the lead list.",
1545
+ numbers: {
1546
+ bounced: count,
1547
+ high,
1548
+ limit: limits.maxBounceRate,
1549
+ low,
1550
+ rate: rate2,
1551
+ sent: of
1552
+ },
1553
+ severity: "high"
1554
+ }
1555
+ ];
1556
+ };
1557
+ var replies = (facts, limits) => {
1558
+ const { count, high, low, of, rate: rate2 } = facts.rates.replyRate;
1559
+ if (!enough(facts, limits) || rate2 === null || rate2 >= limits.minReplyRate) {
1560
+ return [];
1561
+ }
1562
+ const clearly = high !== null && high < limits.minReplyRate;
1563
+ return [
1564
+ {
1565
+ code: "low_reply_rate",
1566
+ finding: `Reply rate is ${percent(rate2)} (${count} of ${of}), under the ${percent(limits.minReplyRate)} floor. The 95% interval is ${percent(low)} to ${percent(high)}, ${clearly ? "so it is below the floor beyond chance" : "which still reaches the floor, so more sends are needed to be sure"}.`,
1567
+ next: "Use step_funnel and copy_audit to see where replies are lost.",
1568
+ numbers: {
1569
+ floor: limits.minReplyRate,
1570
+ high,
1571
+ low,
1572
+ rate: rate2,
1573
+ replied: count,
1574
+ sample: of
1575
+ },
1576
+ severity: clearly ? "high" : "medium"
1577
+ }
1578
+ ];
1579
+ };
1580
+ var positives = (facts, limits) => {
1581
+ const share2 = measure2(facts.totals.positive, facts.totals.replied);
1582
+ return !enough(facts, limits) || share2.rate === null || share2.rate >= limits.minPositiveShare ? [] : [
1583
+ {
1584
+ code: "few_positive_replies",
1585
+ finding: `Only ${share2.count} of ${share2.of} replies (${percent(share2.rate)}) are positive, under the ${percent(limits.minPositiveShare)} expected. With ${share2.of} replies the 95% interval is ${percent(share2.low)} to ${percent(share2.high)}.`,
1586
+ next: "Read the replies: the offer or the audience may be off.",
1587
+ numbers: {
1588
+ high: share2.high,
1589
+ limit: limits.minPositiveShare,
1590
+ low: share2.low,
1591
+ positive: share2.count,
1592
+ sample: share2.of,
1593
+ share: share2.rate
1594
+ },
1595
+ severity: "medium"
1596
+ }
1597
+ ];
1598
+ };
1599
+ var recentSends = (facts, limits) => {
1600
+ const { recent } = facts;
1601
+ if (recent === null) {
1602
+ return [];
1603
+ }
1604
+ if (recent.sent === null || recent.sent === 0) {
1605
+ return facts.campaign.status === "active" ? [
1606
+ {
1607
+ code: "no_recent_sends",
1608
+ finding: `The campaign is active but the vendor reports no sends in the last ${recent.days} days.`,
1609
+ next: "Check its senders and schedule, and whether leads remain (pipeline_forecast).",
1610
+ numbers: { days: recent.days, sent: recent.sent },
1611
+ severity: "high"
1612
+ }
1613
+ ] : [];
1614
+ }
1615
+ const drop = recent.before === null || recent.before <= 0 ? null : round(1 - recent.sent / recent.before);
1616
+ return drop === null || drop <= limits.maxSendDrop ? [] : [
1617
+ {
1618
+ code: "falling_sends",
1619
+ 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)}.`,
1620
+ next: "Use pipeline_forecast to check the leads left, and sender_capacity for the mailboxes.",
1621
+ numbers: { before: recent.before, drop, sent: recent.sent },
1622
+ severity: "medium"
1623
+ }
1624
+ ];
1625
+ };
1626
+ var sequence = ({ steps }) => steps === null || steps < 1 || steps > 2 ? [] : [
1627
+ {
1628
+ code: "short_sequence",
1629
+ finding: `The sequence has ${steps} ${steps === 1 ? "step" : "steps"}; follow-ups usually bring a large share of the replies.`,
1630
+ next: "Add follow-up steps; step_funnel shows what each step earns.",
1631
+ numbers: { steps },
1632
+ severity: "medium"
1633
+ }
1634
+ ];
1635
+ var senders = (facts) => {
1636
+ const all = facts.senders ?? [];
1637
+ const inactive = all.filter((sender) => sender.status !== "active");
1638
+ return inactive.length === 0 ? [] : [
1639
+ {
1640
+ code: "inactive_sender",
1641
+ finding: `${inactive.length} of ${all.length} senders are not active: ${inactive.map(
1642
+ (sender) => `${sender.address ?? sender.name ?? sender.ref} (${sender.status})`
1643
+ ).join(", ")}.`,
1644
+ next: "Reconnect or replace them; warmup_readiness shows which mailboxes are fit to send.",
1645
+ numbers: { inactive: inactive.length, senders: all.length },
1646
+ severity: "high"
1647
+ }
1648
+ ];
1649
+ };
1650
+ var tracking = ({ opened, settings }) => settings?.tracking.opens === false && (opened ?? 0) === 0 ? [
1651
+ {
1652
+ code: "tracking_off",
1653
+ finding: "Open tracking is off, so the missing open count is expected and not a fault.",
1654
+ next: "Judge this campaign on replies, not opens.",
1655
+ numbers: { opened },
1656
+ severity: "low"
1657
+ }
1658
+ ] : [];
1659
+ var minutesOf = (clock) => {
1660
+ const [hours, minutes] = (clock ?? "").split(":").map(Number);
1661
+ return hours === void 0 || minutes === void 0 ? null : hours * 60 + minutes;
1662
+ };
1663
+ var weeklyHours = (settings) => {
1664
+ let minutes = 0;
1665
+ for (const window of settings.schedule) {
1666
+ const from = minutesOf(window.from);
1667
+ const to = minutesOf(window.to);
1668
+ if (from === null || to === null || to <= from) {
1669
+ return null;
1670
+ }
1671
+ minutes += (to - from) * window.days.length;
1672
+ }
1673
+ return settings.schedule.length === 0 ? null : round(minutes / 60);
1674
+ };
1675
+ var schedule = ({ recent, settings }, limits) => {
1676
+ if (settings === null) {
1677
+ return [];
1678
+ }
1679
+ const hours = weeklyHours(settings);
1680
+ const average = recent === null || recent.sent === null || recent.daysWithData === 0 ? null : round(recent.sent / recent.daysWithData);
1681
+ const reasons = [
1682
+ ...hours !== null && hours < limits.minWeeklyHours ? [
1683
+ `The sending windows are open ${hours} hours a week, under ${limits.minWeeklyHours}.`
1684
+ ] : [],
1685
+ ...settings.dailyLimit !== null && average !== null && average >= settings.dailyLimit * limits.dailyLimitShare ? [
1686
+ `Recent sending days average ${average} sends against a daily limit of ${settings.dailyLimit}, so the limit is what holds volume back.`
1687
+ ] : []
1688
+ ];
1689
+ return reasons.length === 0 ? [] : [
1690
+ {
1691
+ code: "schedule_limits_volume",
1692
+ finding: reasons.join(" "),
1693
+ next: "Use settings_audit to review the schedule and the limits.",
1694
+ numbers: {
1695
+ averageDailySent: average,
1696
+ dailyLimit: settings.dailyLimit,
1697
+ weeklyHours: hours
1698
+ },
1699
+ severity: "low"
1700
+ }
1701
+ ];
1702
+ };
1703
+ var CHECKS2 = [
1704
+ bounces,
1705
+ recentSends,
1706
+ senders,
1707
+ replies,
1708
+ volume,
1709
+ positives,
1710
+ sequence,
1711
+ schedule,
1712
+ tracking
1713
+ ];
1714
+ var SEVERITY = { high: 0, low: 2, medium: 1 };
1715
+ var diagnose = (facts, limits) => CHECKS2.flatMap((check) => check(facts, limits)).toSorted(
1716
+ (left, right) => SEVERITY[left.severity] - SEVERITY[right.severity]
1717
+ );
1718
+ var unknownRates = (facts) => [
1719
+ ...facts.rates.replyRate.rate === null ? ["Reply rate: the vendor reports no reply or volume count."] : [],
1720
+ ...facts.rates.bounceRate.rate === null ? ["Bounce rate: the vendor reports no bounce or send count."] : [],
1721
+ ...facts.totals.positive === null ? ["Positive replies: the vendor reports no positive reply count."] : []
1722
+ ];
1723
+
1724
+ // src/insights/ops/campaign-diagnosis.ts
1725
+ var share = (fallback, text) => z9.number().min(0).max(1).default(fallback).describe(text);
1726
+ var input7 = z9.object({
1727
+ ...rangeFields,
1728
+ campaign: z9.string().min(3).describe("The campaign's ref"),
1729
+ daily_limit_share: share(
1730
+ 0.9,
1731
+ "Average daily sends at or over this share of the daily limit mean the limit holds volume back"
1732
+ ),
1733
+ max_bounce_rate: share(0.03, "A bounce rate over this is a finding"),
1734
+ max_send_drop: share(
1735
+ 0.3,
1736
+ "A fall in sends, recent days against the days before, over this share is a finding"
1737
+ ),
1738
+ max_senders: z9.number().int().min(1).max(500).default(50).describe("The most senders of the campaign to read"),
1739
+ min_positive_share: share(
1740
+ 0.2,
1741
+ "A share of replies that are positive under this is a finding"
1742
+ ),
1743
+ min_reply_rate: share(0.01, "A reply rate under this is a finding"),
1744
+ min_sent: z9.number().int().min(0).default(100).describe("Under this many sends, rates are not judged"),
1745
+ min_weekly_hours: z9.number().min(0).max(168).default(20).describe("Sending windows open fewer hours a week than this limit volume"),
1746
+ recent_days: z9.number().int().min(1).max(30).default(7).describe(
1747
+ "The days, ending yesterday, held against the same number before"
1748
+ )
1749
+ });
1750
+ var readRecent = async (context, campaign, days) => {
1751
+ const recent = lastDays(context.now, days);
1752
+ const before = lastDays(context.now, days, 1);
1753
+ const series = await readDaily(context, campaign, {
1754
+ from: before.from,
1755
+ to: recent.to
1756
+ });
1757
+ const sentIn = (from, to) => series.flatMap(
1758
+ (day) => day.date >= from && day.date <= to ? [day.counts.sent] : []
1759
+ );
1760
+ const sends = sentIn(recent.from, recent.to);
1761
+ return {
1762
+ before: total(sentIn(before.from, before.to)),
1763
+ days,
1764
+ daysWithData: sends.filter((value) => value !== null).length,
1765
+ sent: total(sends)
1766
+ };
1767
+ };
1768
+ var readExtras = async (context, campaign, options) => {
1769
+ const { capabilities } = context.outbound;
1770
+ const handle = context.outbound.campaign(campaign);
1771
+ const notChecked = [];
1772
+ const unless = (missing2, what) => {
1773
+ if (missing2) {
1774
+ notChecked.push(what);
1775
+ context.note(what);
1776
+ }
1777
+ return !missing2;
1778
+ };
1779
+ const settings = unless(
1780
+ !capabilities["campaigns.settings"],
1781
+ "Schedule and tracking: the adapter does not serve campaign settings."
1782
+ ) ? context.one(await handle.settings()) : null;
1783
+ const steps = unless(
1784
+ !capabilities.sequence,
1785
+ "Sequence length: the adapter does not serve sequences."
1786
+ ) ? context.one(await handle.sequence()).steps.length : null;
1787
+ const senders2 = unless(
1788
+ !capabilities["senders.byCampaign"],
1789
+ "Sender status: the adapter cannot list a campaign's senders."
1790
+ ) ? await readUpTo(
1791
+ context,
1792
+ (max) => handle.senders.listAll({ max }),
1793
+ options.maxSenders
1794
+ ) : null;
1795
+ const recent = unless(
1796
+ capabilities["stats.byDay"] === false,
1797
+ "Recent sending trend: the adapter has no stats by day."
1798
+ ) ? await readRecent(context, campaign, options.recentDays) : null;
1799
+ return {
1800
+ notChecked,
1801
+ recent,
1802
+ senders: senders2?.items ?? null,
1803
+ settings,
1804
+ steps
1805
+ };
1806
+ };
1807
+ var summarize = (findings) => {
1808
+ const [first] = findings;
1809
+ return first === void 0 ? "No problem was found in what could be checked." : `${findings.length} ${findings.length === 1 ? "finding" : "findings"}. Most serious: ${first.finding}`;
1810
+ };
1811
+ var campaignDiagnosis = defineInsight({
1812
+ 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.",
1813
+ inputSchema: input7,
1814
+ key: "campaignDiagnosis",
1815
+ name: "campaign_diagnosis",
1816
+ needs: ["stats.campaign"],
1817
+ next: "Follow the `next` of the first finding, for example bounce_watch, step_funnel or pipeline_forecast.",
1818
+ run: async (context, options) => {
1819
+ const campaign = context.one(
1820
+ await context.outbound.campaigns.get(options.campaign)
1821
+ );
1822
+ const counts = await readTotals(context, campaign.ref, options);
1823
+ const extras = await readExtras(context, campaign.ref, {
1824
+ maxSenders: options.max_senders,
1825
+ recentDays: options.recent_days
1826
+ });
1827
+ const facts = {
1828
+ ...extras,
1829
+ campaign,
1830
+ opened: counts.opened,
1831
+ rates: ratesOf(counts),
1832
+ totals: totalsOf(counts)
1833
+ };
1834
+ const findings = diagnose(facts, {
1835
+ dailyLimitShare: options.daily_limit_share,
1836
+ maxBounceRate: options.max_bounce_rate,
1837
+ maxSendDrop: options.max_send_drop,
1838
+ minPositiveShare: options.min_positive_share,
1839
+ minReplyRate: options.min_reply_rate,
1840
+ minSent: options.min_sent,
1841
+ minWeeklyHours: options.min_weekly_hours
1842
+ });
1843
+ const diagnosis = {
1844
+ ...labelOf(campaign),
1845
+ findings,
1846
+ notChecked: [...extras.notChecked, ...unknownRates(facts)],
1847
+ period: { from: options.from, to: options.to },
1848
+ rates: facts.rates,
1849
+ summary: summarize(findings),
1850
+ totals: facts.totals
1851
+ };
1852
+ return diagnosis;
1853
+ }
1854
+ });
1855
+
1856
+ // src/insights/ops/campaign-ranking.ts
1857
+ import { z as z10 } from "zod";
1858
+ var metricSchema2 = z10.enum([
1859
+ "reply_rate",
1860
+ "positive_reply_rate",
1861
+ "bounce_rate"
1862
+ ]);
1863
+ var input8 = z10.object({
1864
+ ...rangeFields,
1865
+ ...listFields("one stats request"),
1866
+ metric: metricSchema2.default("reply_rate").describe("The rate to rank by. For bounce_rate, lower is better."),
1867
+ min_sent: z10.number().int().min(0).default(50).describe("Campaigns with fewer sends than this are left out of the rank")
1868
+ });
1869
+ var measured = (counts, metric) => {
1870
+ const rates = ratesOf(counts);
1871
+ if (metric === "bounce_rate") {
1872
+ return rates.bounceRate;
1873
+ }
1874
+ return metric === "reply_rate" ? rates.replyRate : rates.positiveRate;
1875
+ };
1876
+ 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);
1877
+ var rankCampaigns = (entries, metric, minSent) => {
1878
+ const scored = [];
1879
+ const tooFewSends = [];
1880
+ const unknown = [];
1881
+ for (const { campaign, counts } of entries) {
1882
+ const label = labelOf(campaign);
1883
+ const volume2 = volumeOf(counts);
1884
+ const result = measured(counts, metric);
1885
+ if (volume2 === null) {
1886
+ unknown.push({
1887
+ ...label,
1888
+ reason: "The vendor reports no sends for this period.",
1889
+ sent: null
1890
+ });
1891
+ } else if (volume2 < minSent) {
1892
+ tooFewSends.push({
1893
+ ...label,
1894
+ reason: `${volume2} sends, under the ${minSent} needed to rank.`,
1895
+ sent: volume2
1896
+ });
1897
+ } else if (result.rate === null) {
1898
+ unknown.push({
1899
+ ...label,
1900
+ reason: "The vendor does not report the count behind this rate.",
1901
+ sent: volume2
1902
+ });
1903
+ } else {
1904
+ scored.push({ ...label, ...result, sent: volume2 });
1905
+ }
1906
+ }
1907
+ const ranked = scored.toSorted(order(metric)).map((entry, index) => ({ ...entry, rank: index + 1 }));
1908
+ const top = ranked[0]?.rate ?? null;
1909
+ const middle = median(ranked.flatMap((entry) => entry.rate ?? []));
1910
+ return {
1911
+ gap: {
1912
+ difference: top === null || middle === null ? null : round(top - middle),
1913
+ median: round(middle),
1914
+ top
1915
+ },
1916
+ ranked,
1917
+ tooFewSends,
1918
+ unknown
1919
+ };
1920
+ };
1921
+ var campaignRanking = defineInsight({
1922
+ 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.",
1923
+ inputSchema: input8,
1924
+ key: "campaignRanking",
1925
+ name: "campaign_ranking",
1926
+ needs: ["stats.campaign"],
1927
+ next: "Use campaign_diagnosis on the campaign ranked last to see why it is behind.",
1928
+ run: async (context, options) => {
1929
+ const entries = await readCampaignTotals(context, options);
1930
+ const ranking = {
1931
+ ...rankCampaigns(entries, options.metric, options.min_sent),
1932
+ better: options.metric === "bounce_rate" ? "lower" : "higher",
1933
+ metric: options.metric,
1934
+ period: { from: options.from, to: options.to }
1935
+ };
1936
+ return ranking;
1937
+ }
1938
+ });
1939
+
1940
+ // src/insights/ops/channel-mix.ts
1941
+ import { z as z11 } from "zod";
1942
+ var input9 = z11.object({
1943
+ ...rangeFields,
1944
+ ...listFields("one stats request"),
1945
+ alpha: z11.number().gt(0).lt(1).default(0.05).describe(
1946
+ "The p-value under which a difference counts as more than chance"
1947
+ )
1948
+ });
1949
+ var groupOf = (channel, entries) => {
1950
+ const counts = entries.map((entry) => entry.counts);
1951
+ const reply = measureAcross(counts, (row) => row.replied, perLeadBase);
1952
+ const positive = measureAcross(counts, (row) => row.positive, perLeadBase);
1953
+ const acceptance = measureAcross(
1954
+ counts,
1955
+ (row) => row.connectionsAccepted,
1956
+ (row) => row.connectionsSent
1957
+ );
1958
+ return {
1959
+ group: {
1960
+ ...totalsOf(sumCounts(counts)),
1961
+ acceptance: channel === "linkedin" ? acceptance.measured : null,
1962
+ campaigns: entries.length,
1963
+ channel,
1964
+ positiveRate: positive.measured,
1965
+ replyRate: reply.measured
1966
+ },
1967
+ partial: [
1968
+ ...partialRate("reply rate", reply),
1969
+ ...partialRate("positive reply rate", positive),
1970
+ ...channel === "linkedin" ? partialRate("acceptance rate", acceptance) : []
1971
+ ]
1972
+ };
1973
+ };
1974
+ var CHANNELS = ["email", "linkedin"];
1975
+ var byChannel = (entries) => CHANNELS.flatMap((channel) => {
1976
+ const members = entries.filter(
1977
+ (entry) => entry.campaign.channel === channel
1978
+ );
1979
+ return members.length === 0 ? [] : [groupOf(channel, members)];
1980
+ });
1981
+ var byProvider = (entries) => [...new Set(entries.map((entry) => entry.campaign.provider))].toSorted().flatMap(
1982
+ (provider) => byChannel(
1983
+ entries.filter((entry) => entry.campaign.provider === provider)
1984
+ ).map(({ group, partial }) => ({
1985
+ group: { ...group, provider },
1986
+ partial
1987
+ }))
1988
+ );
1989
+ var NAMES = { email: "email", linkedin: "LinkedIn" };
1990
+ var compare = (groups, alpha) => {
1991
+ const [first, second] = groups;
1992
+ if (first === void 0) {
1993
+ return {
1994
+ comparison: null,
1995
+ finding: "No campaigns were found, so there is nothing to compare."
1996
+ };
1997
+ }
1998
+ if (second === void 0) {
1999
+ return {
2000
+ comparison: null,
2001
+ finding: `Only ${NAMES[first.channel]} campaigns were found, so there is nothing to compare.`
2002
+ };
2003
+ }
2004
+ const test = compareRates(
2005
+ { successes: first.replyRate.count, trials: first.replyRate.of },
2006
+ { successes: second.replyRate.count, trials: second.replyRate.of },
2007
+ alpha
2008
+ );
2009
+ if (test === null) {
2010
+ return {
2011
+ comparison: null,
2012
+ finding: "Reply rates cannot be compared: a channel has no reply or volume counts, or neither has a reply."
2013
+ };
2014
+ }
2015
+ const [higher, lower] = test.z >= 0 ? [first, second] : [second, first];
2016
+ return {
2017
+ comparison: {
2018
+ difference: round((higher.replyRate.rate ?? 0) - (lower.replyRate.rate ?? 0)) ?? 0,
2019
+ higher: higher.channel,
2020
+ test
2021
+ },
2022
+ finding: `The reply rate is ${percent(higher.replyRate.rate)} on ${NAMES[higher.channel]} against ${percent(lower.replyRate.rate)} on ${NAMES[lower.channel]}; ${test.significant ? "the difference is more than chance" : "the difference could be chance"} (${pText(test.pValue)}).`
2023
+ };
2024
+ };
2025
+ var channelMix = defineInsight({
2026
+ 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.",
2027
+ inputSchema: input9,
2028
+ key: "channelMix",
2029
+ name: "channel_mix",
2030
+ needs: ["stats.campaign"],
2031
+ next: "Use campaign_ranking to see which campaigns carry the better channel.",
2032
+ run: async (context, options) => {
2033
+ const entries = await readCampaignTotals(context, options);
2034
+ const channels = byChannel(entries);
2035
+ const providers = byProvider(entries);
2036
+ for (const { group, partial } of channels) {
2037
+ if (partial.length > 0) {
2038
+ context.note(partialNote(`Channel ${group.channel}`, partial));
2039
+ }
2040
+ }
2041
+ for (const { group, partial } of providers) {
2042
+ if (partial.length > 0) {
2043
+ context.note(
2044
+ partialNote(`${group.provider} ${group.channel}`, partial)
2045
+ );
2046
+ }
2047
+ }
2048
+ const mix = {
2049
+ ...compare(
2050
+ channels.map((each) => each.group),
2051
+ options.alpha
2052
+ ),
2053
+ byProvider: providers.map((each) => each.group),
2054
+ channels: channels.map((each) => each.group),
2055
+ period: { from: options.from, to: options.to }
2056
+ };
2057
+ return mix;
2058
+ }
2059
+ });
2060
+
2061
+ // src/insights/ops/client-report.ts
2062
+ import { z as z14 } from "zod";
2063
+
2064
+ // src/insights/ops/period-comparison.ts
2065
+ import { z as z12 } from "zod";
2066
+ var input10 = z12.object({
2067
+ ...listFields("two stats requests"),
2068
+ alpha: z12.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2069
+ days: z12.number().int().min(1).max(90).default(7).describe("The length of each period, in complete days ending yesterday"),
2070
+ min_sent: z12.number().int().min(0).default(50).describe(
2071
+ "A campaign under this many sends in either period is listed apart"
2072
+ )
2073
+ });
2074
+ var numbersOf = (counts, rates) => ({
2075
+ ...totalsOf(counts),
2076
+ bounceRate: rates.bounceRate.rate,
2077
+ positiveRate: rates.positiveRate.rate,
2078
+ replyRate: rates.replyRate.rate
2079
+ });
2080
+ var minus = (current, previous) => current === null || previous === null ? null : round(current - previous);
2081
+ var changeOf = (current, previous) => ({
2082
+ bounceRate: minus(current.bounceRate, previous.bounceRate),
2083
+ bounced: minus(current.bounced, previous.bounced),
2084
+ contacted: minus(current.contacted, previous.contacted),
2085
+ positive: minus(current.positive, previous.positive),
2086
+ positiveRate: minus(current.positiveRate, previous.positiveRate),
2087
+ replied: minus(current.replied, previous.replied),
2088
+ replyRate: minus(current.replyRate, previous.replyRate),
2089
+ sent: minus(current.sent, previous.sent)
2090
+ });
2091
+ var verdictOf = (test) => {
2092
+ if (test === null) {
2093
+ return "unknown";
2094
+ }
2095
+ if (!test.significant) {
2096
+ return "no_real_change";
2097
+ }
2098
+ return test.z > 0 ? "up" : "down";
2099
+ };
2100
+ var compare2 = (current, previous, alpha) => {
2101
+ const now = current.rates.replyRate;
2102
+ const before = previous.rates.replyRate;
2103
+ const test = compareRates(
2104
+ { successes: now.count, trials: now.of },
2105
+ { successes: before.count, trials: before.of },
2106
+ alpha
2107
+ );
2108
+ const moved = `Reply rate went from ${percent(before.rate)} to ${percent(now.rate)}`;
2109
+ const numbers = numbersOf(current.counts, current.rates);
2110
+ const earlier = numbersOf(previous.counts, previous.rates);
2111
+ return {
2112
+ change: changeOf(numbers, earlier),
2113
+ current: numbers,
2114
+ finding: test === null ? "Reply rate cannot be compared: a period has no reply or volume counts, or neither has a reply." : `${moved}; ${test.significant ? "more than chance" : "within what chance would give"} (${pText(test.pValue)}).`,
2115
+ previous: earlier,
2116
+ replyRateTest: test,
2117
+ verdict: verdictOf(test)
2118
+ };
2119
+ };
2120
+ var comparePeriods = (current, previous, alpha) => compare2(
2121
+ { counts: current, rates: ratesOf(current) },
2122
+ { counts: previous, rates: ratesOf(previous) },
2123
+ alpha
2124
+ );
2125
+ var compareAcross = (current, previous, alpha) => {
2126
+ const now = ratesAcross(current);
2127
+ const before = ratesAcross(previous);
2128
+ return {
2129
+ comparison: compare2(
2130
+ { counts: sumCounts(current), rates: now.rates },
2131
+ { counts: sumCounts(previous), rates: before.rates },
2132
+ alpha
2133
+ ),
2134
+ partial: [
2135
+ ...now.partial.map((each) => `this period's ${each}`),
2136
+ ...before.partial.map((each) => `the earlier period's ${each}`)
2137
+ ]
2138
+ };
2139
+ };
2140
+ var readPeriods = async (context, options) => {
2141
+ const current = lastDays(context.now, options.days);
2142
+ const previous = lastDays(context.now, options.days, 1);
2143
+ const campaigns = [];
2144
+ const found = await readCampaigns(
2145
+ context,
2146
+ options.statuses,
2147
+ options.max_campaigns
2148
+ );
2149
+ for (const campaign of found) {
2150
+ campaigns.push({
2151
+ campaign,
2152
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
2153
+ current: await readTotals(context, campaign.ref, current),
2154
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
2155
+ previous: await readTotals(context, campaign.ref, previous)
2156
+ });
2157
+ }
2158
+ return { campaigns, current, previous };
2159
+ };
2160
+ var totalOf = (campaigns, alpha) => compareAcross(
2161
+ campaigns.map((entry) => entry.current),
2162
+ campaigns.map((entry) => entry.previous),
2163
+ alpha
2164
+ );
2165
+ var noted = (context, where, across, rows) => {
2166
+ if (across.partial.length > 0) {
2167
+ context.note(partialNote(where, across.partial, rows));
2168
+ }
2169
+ return across.comparison;
2170
+ };
2171
+ var workspaceOf = async (context, periods, alpha) => {
2172
+ const { outbound } = context;
2173
+ if (outbound.capabilities["stats.workspace"] === false) {
2174
+ context.note(
2175
+ "Workspace totals were left out: the adapter has no workspace stats. `total` adds up the campaigns read."
2176
+ );
2177
+ return null;
2178
+ }
2179
+ const current = context.rows(await outbound.stats(periods.current));
2180
+ const previous = context.rows(await outbound.stats(periods.previous));
2181
+ return noted(
2182
+ context,
2183
+ "Workspace totals",
2184
+ compareAcross(current, previous, alpha),
2185
+ "tools"
2186
+ );
2187
+ };
2188
+ var periodComparison = defineInsight({
2189
+ description: "This period against the last: for each campaign, counts and rates for the last `days` complete days and for the `days` before, the change in each, and whether the change in reply rate is more than chance (a two-proportion test), with the campaigns sorted by the size of that change. Also the same for every campaign added together and, where the adapter has them, for the vendor's workspace totals. Use it for a weekly review. Campaigns under min_sent sends in either period are listed apart; a null is a count the vendor does not report, and a rate of a total counts only the campaigns that report both its count and what it divides by (a note says when some are left out). Costs two stats requests per campaign plus two for the workspace.",
2190
+ inputSchema: input10,
2191
+ key: "periodComparison",
2192
+ name: "period_comparison",
2193
+ needs: ["stats.campaign"],
2194
+ next: "Use campaign_diagnosis on the campaign whose reply rate fell the most.",
2195
+ run: async (context, options) => {
2196
+ const periods = await readPeriods(context, options);
2197
+ const campaigns = [];
2198
+ const tooFewSends = [];
2199
+ for (const { campaign, current, previous } of periods.campaigns) {
2200
+ const sent = [volumeOf(current), volumeOf(previous)];
2201
+ if (sent.some((volume2) => (volume2 ?? -1) < options.min_sent)) {
2202
+ tooFewSends.push({
2203
+ ...labelOf(campaign),
2204
+ currentSent: sent[0],
2205
+ previousSent: sent[1]
2206
+ });
2207
+ } else {
2208
+ campaigns.push({
2209
+ ...labelOf(campaign),
2210
+ ...comparePeriods(current, previous, options.alpha)
2211
+ });
2212
+ }
2213
+ }
2214
+ const comparison = {
2215
+ campaigns: campaigns.toSorted(
2216
+ (left, right) => descending(
2217
+ left.change.replyRate === null ? null : Math.abs(left.change.replyRate),
2218
+ right.change.replyRate === null ? null : Math.abs(right.change.replyRate)
2219
+ ) || left.name.localeCompare(right.name)
2220
+ ),
2221
+ current: periods.current,
2222
+ days: options.days,
2223
+ previous: periods.previous,
2224
+ tooFewSends,
2225
+ total: noted(
2226
+ context,
2227
+ "Every campaign added together",
2228
+ totalOf(periods.campaigns, options.alpha)
2229
+ ),
2230
+ workspace: await workspaceOf(context, periods, options.alpha)
2231
+ };
2232
+ return comparison;
2233
+ }
2234
+ });
2235
+
2236
+ // src/insights/ops/pipeline-forecast.ts
2237
+ import { z as z13 } from "zod";
2238
+ var input11 = z13.object({
2239
+ campaign: z13.string().min(3).describe("The campaign's ref"),
2240
+ days: z13.number().int().min(1).max(60).default(7).describe("How many complete days, ending yesterday, set the daily pace"),
2241
+ max_leads: z13.number().int().min(1).max(5e4).default(2e3).describe("The most leads to read. A page of leads is one request.")
2242
+ });
2243
+ var countStatuses = (leads) => {
2244
+ const counts = {
2245
+ active: 0,
2246
+ bounced: 0,
2247
+ completed: 0,
2248
+ paused: 0,
2249
+ replied: 0,
2250
+ unknown: 0,
2251
+ unsubscribed: 0
2252
+ };
2253
+ for (const lead of leads) {
2254
+ counts[lead.status] += 1;
2255
+ }
2256
+ return counts;
2257
+ };
2258
+ var times = (leads, share2) => share2 === null ? null : round(leads * share2);
2259
+ var project = (leads, measured2) => ({
2260
+ expected: times(leads, measured2.rate),
2261
+ high: times(leads, measured2.high),
2262
+ low: times(leads, measured2.low)
2263
+ });
2264
+ var paceOf = async (context, campaign, days) => {
2265
+ if (context.outbound.capabilities["stats.byDay"] === false) {
2266
+ context.note(
2267
+ "Days of sending left were not estimated: the adapter has no stats by day."
2268
+ );
2269
+ return null;
2270
+ }
2271
+ const series = await readDaily(
2272
+ context,
2273
+ campaign,
2274
+ lastDays(context.now, days)
2275
+ );
2276
+ const contacted = total(series.map((day) => day.counts.contacted));
2277
+ return contacted === null ? null : round(contacted / days);
2278
+ };
2279
+ var ASSUMPTIONS = [
2280
+ "Every remaining lead is contacted.",
2281
+ "Remaining leads reply at the rate the campaign has had so far; leads already partway through the sequence may reply less.",
2282
+ "The daily pace stays what it was over the recent days. Days with no report count as no sends."
2283
+ ];
2284
+ var describe2 = (remaining, complete, forecast) => {
2285
+ const leads = `${complete ? "" : "At least "}${remaining} leads remain`;
2286
+ return forecast.expected === null ? `${leads}; replies cannot be estimated because the vendor reports no reply rate yet.` : `${leads}; expect about ${forecast.expected} replies (between ${forecast.low} and ${forecast.high}). This is an estimate.`;
2287
+ };
2288
+ var forecastCampaign = async (context, campaign, options) => {
2289
+ const handle = context.outbound.campaign(campaign.ref);
2290
+ const { complete, items: leads } = await readUpTo(
2291
+ context,
2292
+ (max) => handle.leads.listAll({ max }),
2293
+ options.maxLeads
2294
+ );
2295
+ const byStatus = countStatuses(leads);
2296
+ const remaining = byStatus.active;
2297
+ const rates = ratesOf(
2298
+ await readTotals(context, campaign.ref, { from: null, to: null })
2299
+ );
2300
+ const pace = await paceOf(context, campaign.ref, options.days);
2301
+ const expectedReplies = project(remaining, rates.replyRate);
2302
+ return {
2303
+ ...labelOf(campaign),
2304
+ assumptions: [
2305
+ ...ASSUMPTIONS,
2306
+ `The reply rate so far is ${percent(rates.replyRate.rate)}, from ${rates.replyRate.count ?? "unknown"} replies over ${rates.replyRate.of ?? "unknown"}.`
2307
+ ],
2308
+ byStatus,
2309
+ dailyContactRate: pace,
2310
+ daysLeft: pace === null || pace <= 0 ? null : round(remaining / pace),
2311
+ estimate: true,
2312
+ expectedPositive: project(remaining, rates.positiveRate),
2313
+ expectedReplies,
2314
+ finding: describe2(remaining, complete, expectedReplies),
2315
+ leadsComplete: complete,
2316
+ leadsRead: leads.length,
2317
+ positiveRate: rates.positiveRate,
2318
+ remaining,
2319
+ replyRate: rates.replyRate
2320
+ };
2321
+ };
2322
+ var pipelineForecast = defineInsight({
2323
+ 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.",
2324
+ inputSchema: input11,
2325
+ key: "pipelineForecast",
2326
+ name: "pipeline_forecast",
2327
+ needs: ["leads.byCampaign", "stats.campaign"],
2328
+ next: "Use client_report to see every campaign that is running out of leads.",
2329
+ run: async (context, options) => {
2330
+ const campaign = context.one(
2331
+ await context.outbound.campaigns.get(options.campaign)
2332
+ );
2333
+ return await forecastCampaign(context, campaign, {
2334
+ days: options.days,
2335
+ maxLeads: options.max_leads
2336
+ });
2337
+ }
2338
+ });
2339
+
2340
+ // src/insights/ops/client-report.ts
2341
+ var input12 = z14.object({
2342
+ ...listFields(
2343
+ "two stats requests, and three more plus its leads when active"
2344
+ ),
2345
+ alpha: z14.number().gt(0).lt(1).default(0.05).describe("The p-value under which a change counts as more than chance"),
2346
+ anomaly_threshold: z14.number().positive().default(2.5).describe("Standard deviations from the baseline that make a day unusual"),
2347
+ baseline_days: z14.number().int().min(5).max(60).default(14).describe("Days before the period that form the anomaly baseline"),
2348
+ days: z14.number().int().min(1).max(90).default(7).describe("The length of the period, in complete days ending yesterday"),
2349
+ max_bounce_rate: z14.number().min(0).max(1).default(0.03).describe("A campaign bounce rate over this is a bounce problem"),
2350
+ max_leads_per_campaign: z14.number().int().min(1).max(5e4).default(500).describe("The most leads to read per active campaign, for leads left"),
2351
+ min_baseline_points: z14.number().int().min(2).default(5).describe("The fewest baseline days with data a day needs to be tested"),
2352
+ min_sent: z14.number().int().min(0).default(50).describe("Campaigns under this many sends in the period are not judged"),
2353
+ runway_days: z14.number().min(0).default(7).describe(
2354
+ "A campaign with this many days of leads left or fewer is flagged"
2355
+ ),
2356
+ top: z14.number().int().min(1).max(20).default(3).describe("How many best and worst campaigns to show")
2357
+ });
2358
+ var bounceProblems = (campaigns, options) => campaigns.flatMap(({ campaign, current }) => {
2359
+ const { count, high, low, of, rate: rate2 } = ratesOf(current).bounceRate;
2360
+ return rate2 !== null && rate2 > options.max_bounce_rate && (volumeOf(current) ?? -1) >= options.min_sent ? [{ ...labelOf(campaign), bounced: count, high, low, rate: rate2, sent: of }] : [];
2361
+ }).toSorted((left, right) => right.rate - left.rate);
2362
+ var readAnomalies = async (context, period, options) => {
2363
+ const { capabilities } = context.outbound;
2364
+ if (capabilities["stats.byDay"] === false || capabilities["stats.workspace"] === false) {
2365
+ return null;
2366
+ }
2367
+ const series = await readDaily(context, null, {
2368
+ from: shiftDay(period.from, -options.baseline_days),
2369
+ to: period.to
2370
+ });
2371
+ return [
2372
+ ...findAnomalies(series, {
2373
+ baselineDays: options.baseline_days,
2374
+ firstDay: period.from,
2375
+ metrics: ["sent", "replied", "bounced"],
2376
+ minBaselinePoints: options.min_baseline_points,
2377
+ threshold: options.anomaly_threshold
2378
+ }).anomalies
2379
+ ];
2380
+ };
2381
+ var readRunways = async (context, campaigns, options) => {
2382
+ const { capabilities } = context.outbound;
2383
+ if (!capabilities["leads.byCampaign"] || capabilities["stats.byDay"] === false) {
2384
+ return null;
2385
+ }
2386
+ const runways = [];
2387
+ for (const { campaign } of campaigns) {
2388
+ if (campaign.status === "active") {
2389
+ const forecast = await forecastCampaign(context, campaign, {
2390
+ days: options.days,
2391
+ maxLeads: options.max_leads_per_campaign
2392
+ });
2393
+ if (forecast.leadsComplete && forecast.daysLeft !== null && forecast.daysLeft <= options.runway_days) {
2394
+ runways.push({
2395
+ ...labelOf(campaign),
2396
+ dailyContactRate: forecast.dailyContactRate,
2397
+ daysLeft: forecast.daysLeft,
2398
+ remaining: forecast.remaining
2399
+ });
2400
+ }
2401
+ }
2402
+ }
2403
+ return runways.toSorted((left, right) => left.daysLeft - right.daysLeft);
2404
+ };
2405
+ var actionsOf = (report) => {
2406
+ const [worst] = report.bottom;
2407
+ const { current, previous } = report.totals;
2408
+ return [
2409
+ ...report.bounceProblems.map((problem) => ({
2410
+ action: `Fix the bounces of ${problem.name}: its bounce rate is ${percent(problem.rate)} (${problem.bounced} of ${problem.sent} sends).`,
2411
+ campaign: problem.campaign,
2412
+ campaignName: problem.name,
2413
+ kind: "fix_bounces",
2414
+ number: problem.rate
2415
+ })),
2416
+ ...(report.runningOutOfLeads ?? []).map((runway) => ({
2417
+ action: `Add leads to ${runway.name}: ${runway.remaining} leads remain, about ${runway.daysLeft} days of sending.`,
2418
+ campaign: runway.campaign,
2419
+ campaignName: runway.name,
2420
+ kind: "add_leads",
2421
+ number: runway.daysLeft
2422
+ })),
2423
+ ...report.totals.verdict === "down" ? [
2424
+ {
2425
+ action: `Find out what changed: the reply rate fell from ${percent(previous.replyRate)} to ${percent(current.replyRate)}, more than chance would give.`,
2426
+ campaign: null,
2427
+ campaignName: null,
2428
+ kind: "reply_rate_fell",
2429
+ number: report.totals.change.replyRate
2430
+ }
2431
+ ] : [],
2432
+ ...worst === void 0 ? [] : [
2433
+ {
2434
+ action: `Review the copy and the audience of ${worst.name}: it has the weakest reply rate, ${percent(worst.rate)} (${worst.count} of ${worst.of}).`,
2435
+ campaign: worst.campaign,
2436
+ campaignName: worst.name,
2437
+ kind: "review_campaign",
2438
+ number: worst.rate
2439
+ }
2440
+ ],
2441
+ ...(report.anomalies ?? []).map((anomaly) => ({
2442
+ action: `Check what happened on ${anomaly.date}: ${anomaly.finding}`,
2443
+ campaign: null,
2444
+ campaignName: null,
2445
+ kind: "check_anomaly",
2446
+ number: anomaly.value
2447
+ }))
2448
+ ];
2449
+ };
2450
+ var clientReport = defineInsight({
2451
+ description: "One report for one client or workspace over the last `days` complete days: totals and the change from the period before, the best and worst campaigns by the low end of the reply rate interval, campaigns with a bounce problem, unusual days, active campaigns running out of leads, and a short list of action items in plain language, each naming the campaign and the number behind it. Use it for a weekly client update. A section the adapter cannot serve is null and named in `leftOut`, and a null count is one the vendor does not report. Costs two stats requests per campaign, one for the workspace, and for each active campaign two more plus its pages of leads.",
2452
+ inputSchema: input12,
2453
+ key: "clientReport",
2454
+ name: "client_report",
2455
+ needs: ["stats.campaign"],
2456
+ next: "Use campaign_diagnosis on a campaign an action item names, or period_comparison for every campaign's change.",
2457
+ run: async (context, options) => {
2458
+ const periods = await readPeriods(context, options);
2459
+ const ranking = rankCampaigns(
2460
+ periods.campaigns.map((entry) => ({
2461
+ campaign: entry.campaign,
2462
+ counts: entry.current
2463
+ })),
2464
+ "reply_rate",
2465
+ options.min_sent
2466
+ );
2467
+ const sections = {
2468
+ anomalies: await readAnomalies(context, periods.current, options),
2469
+ bottom: ranking.ranked.slice(options.top).slice(-options.top).toReversed(),
2470
+ bounceProblems: bounceProblems(periods.campaigns, options),
2471
+ runningOutOfLeads: await readRunways(context, periods.campaigns, options),
2472
+ totals: noted(
2473
+ context,
2474
+ "Totals",
2475
+ totalOf(periods.campaigns, options.alpha)
2476
+ )
2477
+ };
2478
+ const leftOut = [
2479
+ ...sections.anomalies === null ? ["Unusual days: the adapter has no workspace stats by day."] : [],
2480
+ ...sections.runningOutOfLeads === null ? [
2481
+ "Campaigns running out of leads: the adapter cannot list a campaign's leads or has no stats by day."
2482
+ ] : []
2483
+ ];
2484
+ for (const section of leftOut) {
2485
+ context.note(`Left out. ${section}`);
2486
+ }
2487
+ const report = {
2488
+ ...sections,
2489
+ actions: actionsOf(sections),
2490
+ campaigns: periods.campaigns.length,
2491
+ days: options.days,
2492
+ leftOut,
2493
+ period: periods.current,
2494
+ previousPeriod: periods.previous,
2495
+ top: ranking.ranked.slice(0, options.top)
2496
+ };
2497
+ return report;
2498
+ }
2499
+ });
2500
+
2501
+ // src/insights/ops/tag-rollup.ts
2502
+ import { z as z15 } from "zod";
2503
+ var input13 = z15.object({
2504
+ ...rangeFields,
2505
+ ...listFields("one stats request"),
2506
+ min_sent: z15.number().int().min(0).default(50).describe("Tags with fewer sends than this are listed apart, unsorted")
2507
+ });
2508
+ var groupOf2 = (tag, entries) => {
2509
+ const counts = entries.map((entry) => entry.counts);
2510
+ const { partial, rates } = ratesAcross(counts);
2511
+ return {
2512
+ group: {
2513
+ ...totalsOf(sumCounts(counts)),
2514
+ ...rates,
2515
+ campaigns: entries.length,
2516
+ tag
2517
+ },
2518
+ partial
2519
+ };
2520
+ };
2521
+ var named = (group) => group.tag ?? "";
2522
+ var tagRollup = defineInsight({
2523
+ 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.",
2524
+ inputSchema: input13,
2525
+ key: "tagRollup",
2526
+ name: "tag_rollup",
2527
+ needs: ["stats.campaign"],
2528
+ next: "Use campaign_ranking to see the campaigns inside the best and the worst tag.",
2529
+ run: async (context, options) => {
2530
+ const entries = await readCampaignTotals(context, options);
2531
+ const members = /* @__PURE__ */ new Map();
2532
+ for (const entry of entries) {
2533
+ const tags = entry.campaign.tags.length === 0 ? [null] : entry.campaign.tags;
2534
+ for (const tag of new Set(tags)) {
2535
+ members.set(tag, [...members.get(tag) ?? [], entry]);
2536
+ }
2537
+ }
2538
+ const grouped = [...members].map(([tag, group]) => groupOf2(tag, group));
2539
+ for (const { group, partial } of grouped) {
2540
+ if (partial.length > 0) {
2541
+ context.note(
2542
+ partialNote(
2543
+ group.tag === null ? "Untagged campaigns" : `Tag ${group.tag}`,
2544
+ partial
2545
+ )
2546
+ );
2547
+ }
2548
+ }
2549
+ const groups = grouped.map((each) => each.group).toSorted(
2550
+ (left, right) => descending(left.replyRate.low, right.replyRate.low) || named(left).localeCompare(named(right))
2551
+ );
2552
+ const enough2 = (group) => (volumeOf(group) ?? 0) >= options.min_sent;
2553
+ const rollup = {
2554
+ campaigns: entries.length,
2555
+ period: { from: options.from, to: options.to },
2556
+ tags: groups.filter(enough2),
2557
+ tooFewSends: groups.filter((group) => !enough2(group))
2558
+ };
2559
+ return rollup;
2560
+ }
2561
+ });
2562
+
2563
+ // src/insights/ops/index.ts
2564
+ var OPS_INSIGHTS = [
2565
+ campaignDiagnosis,
2566
+ pipelineForecast,
2567
+ anomalies,
2568
+ periodComparison,
2569
+ campaignRanking,
2570
+ channelMix,
2571
+ tagRollup,
2572
+ clientReport
2573
+ ];
2574
+
2575
+ // src/insights/people/account-summary.ts
2576
+ import { z as z17 } from "zod";
2577
+
2578
+ // src/insights/people/read.ts
2579
+ import { z as z16 } from "zod";
2580
+ var readCapped2 = (context, open, max, what) => context.all(open(max), `${max} ${what}`);
2581
+ var statusesField = z16.array(campaignStatusSchema).min(1).default(["active"]).describe("Campaign statuses to consider, for example active or paused");
2582
+ var campaignsIn2 = async (context, statuses, max) => {
2583
+ const { outbound } = context;
2584
+ const wanted = [...new Set(statuses)];
2585
+ if (outbound.capabilities["campaigns.status"] === false) {
2586
+ const every = await readCapped2(
2587
+ context,
2588
+ (cap) => outbound.campaigns.listAll({ max: cap }),
2589
+ max,
2590
+ "campaigns"
2591
+ );
2592
+ return every.filter((campaign) => wanted.includes(campaign.status));
2593
+ }
2594
+ const campaigns = [];
2595
+ for (const status of wanted) {
2596
+ const room = max - campaigns.length;
2597
+ if (room <= 0) {
2598
+ context.partial(`Stopped at ${max} campaigns; more may exist.`);
2599
+ break;
2600
+ }
2601
+ const found = await readCapped2(
2602
+ context,
2603
+ (cap) => outbound.campaigns.listAll({ max: cap, status }),
2604
+ room,
2605
+ "campaigns"
2606
+ );
2607
+ campaigns.push(...found);
2608
+ }
2609
+ return campaigns;
2610
+ };
2611
+ var leadsOf = (context, campaign, max) => readCapped2(
2612
+ context,
2613
+ (cap) => context.outbound.campaign(campaign).leads.listAll({ max: cap }),
2614
+ max,
2615
+ "leads of a campaign"
2616
+ );
2617
+ var nameOf = (lead) => {
2618
+ const name = [lead.firstName, lead.lastName].flatMap((part) => part === null || part.trim() === "" ? [] : [part]).join(" ");
2619
+ return name === "" ? null : name;
2620
+ };
2621
+ var domainOf = (email) => {
2622
+ const domain = email?.split("@").at(-1) ?? "";
2623
+ return email === null || !email.includes("@") || domain === "" ? null : domain;
2624
+ };
2625
+ var DEFAULT_POSITIVE_LABELS = [
2626
+ "Interested",
2627
+ "Meeting Booked",
2628
+ "Meeting Completed"
2629
+ ];
2630
+ var positiveLabelsField = z16.array(z16.string().min(1)).default(DEFAULT_POSITIVE_LABELS).describe(
2631
+ "Vendor interest labels that count as interested, matched without regard to case"
2632
+ );
2633
+ var isPositive = (label, labels) => label === null ? null : labels.some(
2634
+ (each) => each.trim().toLowerCase() === label.trim().toLowerCase()
2635
+ );
2636
+ var hasReplied = (lead) => lead.status === "replied" || (lead.engagement?.replies ?? 0) > 0 || (lead.engagement?.lastRepliedAt ?? null) !== null;
2637
+ var COUNTS = "no per-lead open, click or reply counts";
2638
+ var noteEngagement = (context, leads, effect) => {
2639
+ const { outbound } = context;
2640
+ if (outbound.capabilities["leads.engagement"]) {
2641
+ return;
2642
+ }
2643
+ if (leads.every((lead) => lead.provider === outbound.provider)) {
2644
+ context.note(`This tool reports ${COUNTS}, so ${effect}.`);
2645
+ return;
2646
+ }
2647
+ const reporting = new Set(
2648
+ leads.flatMap((lead) => lead.engagement === null ? [] : [lead.provider])
2649
+ );
2650
+ const lacking = [...new Set(leads.map((lead) => lead.provider))].filter((provider) => !reporting.has(provider)).toSorted();
2651
+ if (lacking.length > 0) {
2652
+ context.note(
2653
+ `${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.`
2654
+ );
2655
+ }
2656
+ };
2657
+
2658
+ // src/insights/people/account-summary.ts
2659
+ var input14 = z17.object({
2660
+ allow_free_domains: z17.boolean().default(false).describe(
2661
+ "Set to true to accept an email provider domain such as gmail.com, which is not one company"
2662
+ ),
2663
+ domain: z17.string().min(3).describe(
2664
+ "The company's domain, for example acme.com, or an email address whose domain is used"
2665
+ ),
2666
+ max_campaigns: z17.number().int().min(1).max(200).default(20).describe(
2667
+ "The most campaigns to read leads from when the tool cannot list every lead at once"
2668
+ ),
2669
+ max_leads: z17.number().int().min(1).max(2e4).default(1e3).describe(
2670
+ "The most leads to read in all. A vendor request returns about 50 to 100 leads."
2671
+ ),
2672
+ positive_labels: positiveLabelsField
2673
+ });
2674
+ var FREE_DOMAINS = /* @__PURE__ */ new Set([
2675
+ "aol.com",
2676
+ "gmail.com",
2677
+ "gmx.com",
2678
+ "googlemail.com",
2679
+ "hotmail.com",
2680
+ "icloud.com",
2681
+ "live.com",
2682
+ "mail.com",
2683
+ "me.com",
2684
+ "msn.com",
2685
+ "outlook.com",
2686
+ "proton.me",
2687
+ "protonmail.com",
2688
+ "yahoo.com",
2689
+ "yandex.com",
2690
+ "zoho.com"
2691
+ ]);
2692
+ var DOMAIN = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/u;
2693
+ var parseDomain = (text, provider) => {
2694
+ const value = text.trim().toLowerCase();
2695
+ const host = value.includes("@") ? value.split("@").at(-1) ?? "" : value.replace(/^[a-z]+:\/\//u, "").replace(/^www\./u, "").split(/[/?#]/u)[0] ?? "";
2696
+ if (!DOMAIN.test(host)) {
2697
+ throw new OutboundError(
2698
+ "Invalid",
2699
+ `"${text}" is not a domain or an email address`,
2700
+ { provider }
2701
+ );
2702
+ }
2703
+ return host;
2704
+ };
2705
+ var readLeads = async (context, { max_campaigns: maxCampaigns, max_leads: maxLeads }) => {
2706
+ const { outbound } = context;
2707
+ if (outbound.capabilities["leads.list"]) {
2708
+ return await readCapped2(
2709
+ context,
2710
+ (cap) => outbound.leads.listAll({ max: cap }),
2711
+ maxLeads,
2712
+ "leads"
2713
+ );
2714
+ }
2715
+ if (!outbound.capabilities["leads.byCampaign"]) {
2716
+ throw new OutboundError(
2717
+ "Unsupported",
2718
+ `account_summary is not available: the ${outbound.provider} adapter supports neither leads.list nor leads.byCampaign`,
2719
+ { provider: outbound.provider }
2720
+ );
2721
+ }
2722
+ const campaigns = await readCapped2(
2723
+ context,
2724
+ (cap) => outbound.campaigns.listAll({ max: cap }),
2725
+ maxCampaigns,
2726
+ "campaigns"
2727
+ );
2728
+ const leads = [];
2729
+ for (const campaign of campaigns) {
2730
+ if (leads.length >= maxLeads) {
2731
+ context.partial(`Stopped at ${maxLeads} leads; more campaigns remain.`);
2732
+ break;
2733
+ }
2734
+ const found = await leadsOf(context, campaign.ref, maxLeads - leads.length);
2735
+ leads.push(...found);
2736
+ }
2737
+ return leads;
2738
+ };
2739
+ var toRecord = (lead) => ({
2740
+ campaign: lead.campaignRef,
2741
+ clicks: lead.engagement?.clicks ?? null,
2742
+ interest: lead.interest,
2743
+ lastContactedAt: lead.engagement?.lastContactedAt ?? null,
2744
+ lastRepliedAt: lead.engagement?.lastRepliedAt ?? null,
2745
+ lead: lead.ref,
2746
+ opens: lead.engagement?.opens ?? null,
2747
+ provider: lead.provider,
2748
+ replies: lead.engagement?.replies ?? null,
2749
+ status: lead.status
2750
+ });
2751
+ var latest = (times3) => times3.flatMap((time) => time === null ? [] : [time]).toSorted().at(-1) ?? null;
2752
+ var toPerson = (email, leads, labels) => {
2753
+ const records = leads.map(toRecord);
2754
+ const verdicts = leads.map((lead) => isPositive(lead.interest, labels));
2755
+ const pick = (read) => leads.map(read).find((value) => value !== null) ?? null;
2756
+ return {
2757
+ campaigns: [
2758
+ ...new Set(
2759
+ records.flatMap(
2760
+ (record) => record.campaign === null ? [] : [record.campaign]
2761
+ )
2762
+ )
2763
+ ],
2764
+ clicks: total(records.map((record) => record.clicks)),
2765
+ company: pick((lead) => lead.company),
2766
+ email,
2767
+ interested: verdicts.includes(true) ? true : verdicts.find((verdict) => verdict !== null) ?? null,
2768
+ lastRepliedAt: latest(records.map((record) => record.lastRepliedAt)),
2769
+ name: pick(nameOf),
2770
+ opens: total(records.map((record) => record.opens)),
2771
+ records,
2772
+ replied: leads.some(hasReplied),
2773
+ replies: total(records.map((record) => record.replies)),
2774
+ title: pick((lead) => lead.title)
2775
+ };
2776
+ };
2777
+ var byLastReply = (left, right) => (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || Number(right.replied) - Number(left.replied) || left.email.localeCompare(right.email);
2778
+ var lastReplyOf = (people) => {
2779
+ const [person] = people;
2780
+ const at = person?.lastRepliedAt ?? null;
2781
+ const record = person?.records.find((each) => each.lastRepliedAt === at);
2782
+ return person === void 0 || record === void 0 || at === null ? null : {
2783
+ at,
2784
+ campaign: record.campaign,
2785
+ email: person.email,
2786
+ lead: record.lead,
2787
+ name: person.name
2788
+ };
2789
+ };
2790
+ var accountSummary = defineInsight({
2791
+ description: "Everyone at one company across campaigns and tools, from the company's domain or any email address at it: each person with their name, title, campaigns, status, interest label and open, click and reply counts, plus totals and who replied most recently. People are matched by exact email domain, so a lead with only a LinkedIn profile is not found, and an email provider domain such as gmail.com is refused unless allow_free_domains is true. Costs one request per page of leads read (max_leads sets the ceiling); a count the vendor does not report is null.",
2792
+ inputSchema: input14,
2793
+ key: "accountSummary",
2794
+ name: "account_summary",
2795
+ needs: [],
2796
+ next: "Use person_summary with one person's email address for their full history, message by message.",
2797
+ run: async (context, values) => {
2798
+ const domain = parseDomain(values.domain, context.outbound.provider);
2799
+ if (FREE_DOMAINS.has(domain) && !values.allow_free_domains) {
2800
+ throw new OutboundError(
2801
+ "Invalid",
2802
+ `${domain} is an email provider, not one company. Pass allow_free_domains: true to read it anyway.`,
2803
+ { provider: context.outbound.provider }
2804
+ );
2805
+ }
2806
+ const leads = await readLeads(context, values);
2807
+ noteEngagement(context, leads, "those are null");
2808
+ const byEmail = /* @__PURE__ */ new Map();
2809
+ for (const lead of leads) {
2810
+ if (lead.email !== null && domainOf(lead.email) === domain) {
2811
+ byEmail.set(lead.email, [...byEmail.get(lead.email) ?? [], lead]);
2812
+ }
2813
+ }
2814
+ const people = [...byEmail].map(
2815
+ ([email, records]) => toPerson(email, records, values.positive_labels)
2816
+ ).toSorted(byLastReply);
2817
+ const summary = {
2818
+ domain,
2819
+ lastReply: lastReplyOf(people),
2820
+ people,
2821
+ totals: {
2822
+ campaigns: new Set(people.flatMap((person) => person.campaigns)).size,
2823
+ interested: people.filter((person) => person.interested === true).length,
2824
+ leadsRead: leads.length,
2825
+ leadsWithoutEmail: leads.filter((lead) => lead.email === null).length,
2826
+ people: people.length,
2827
+ records: people.reduce((sum, each) => sum + each.records.length, 0),
2828
+ replied: people.filter((person) => person.replied).length
2829
+ }
2830
+ };
2831
+ return summary;
2832
+ }
2833
+ });
2834
+
2835
+ // src/insights/people/dropped-replies.ts
2836
+ import { z as z18 } from "zod";
2837
+ var HOUR = 36e5;
2838
+ var DAY = 24 * HOUR;
2839
+ var DEFAULT_DAYS = 14;
2840
+ var input15 = z18.object({
2841
+ categories: z18.array(replyCategorySchema).min(1).default(["positive", "neutral", "unknown"]).describe(
2842
+ "Reply categories that need an answer. Out-of-office, bounce, unsubscribe and negative replies are left out by default."
2843
+ ),
2844
+ include_auto: z18.boolean().default(false).describe(
2845
+ "Set to true to also check replies the vendor marks as automatic"
2846
+ ),
2847
+ max_replies: z18.number().int().min(1).max(1e3).default(50).describe(
2848
+ "The most replies to read. Each conversation among them costs one more request to check."
2849
+ ),
2850
+ older_than_hours: z18.number().min(0).default(24).describe(
2851
+ "A reply counts as dropped only after waiting this many hours without an answer"
2852
+ ),
2853
+ since: z18.union([z18.iso.datetime({ offset: true }), z18.iso.date()]).nullable().default(null).describe(
2854
+ "Only replies received at or after this ISO 8601 time. Null means 14 days before now."
2855
+ )
2856
+ });
2857
+ var readersOf = (context) => {
2858
+ const { capabilities } = context.outbound;
2859
+ const messages = capabilities["messages.list"];
2860
+ return {
2861
+ thread: messages && capabilities["messages.byThread"],
2862
+ timeline: messages && capabilities["leads.timeline"]
2863
+ };
2864
+ };
2865
+ var conversationsOf = (replies2, readers) => {
2866
+ const groups = /* @__PURE__ */ new Map();
2867
+ for (const reply of replies2) {
2868
+ const thread = readers.thread ? reply.threadId : null;
2869
+ const lead = readers.timeline ? reply.leadRef : null;
2870
+ const by = thread === null ? "timeline" : "thread";
2871
+ const id = thread ?? lead;
2872
+ const key = id === null ? `none:${reply.ref}` : `${by}:${id}`;
2873
+ const group = groups.get(key) ?? {
2874
+ by: id === null ? null : by,
2875
+ id: id ?? reply.ref,
2876
+ replies: []
2877
+ };
2878
+ group.replies.push(reply);
2879
+ groups.set(key, group);
2880
+ }
2881
+ return [...groups.values()];
2882
+ };
2883
+ var unanswered = (replies2, messages) => {
2884
+ const lastSent = Math.max(
2885
+ Number.NEGATIVE_INFINITY,
2886
+ ...messages.flatMap(
2887
+ (message) => message.direction === "out" && message.sentAt !== null ? [Date.parse(message.sentAt)] : []
2888
+ )
2889
+ );
2890
+ return replies2.filter(
2891
+ (reply) => reply.sentAt !== null && Date.parse(reply.sentAt) > lastSent
2892
+ ).toSorted(
2893
+ (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "")
2894
+ );
2895
+ };
2896
+ var toDropped = (open, by, now) => {
2897
+ const [first] = open;
2898
+ if (first === void 0 || first.sentAt === null) {
2899
+ return [];
2900
+ }
2901
+ const hoursWaiting = round((now - Date.parse(first.sentAt)) / HOUR) ?? 0;
2902
+ return [
2903
+ {
2904
+ campaign: first.campaignRef,
2905
+ category: first.category,
2906
+ channel: first.channel,
2907
+ checkedBy: by,
2908
+ finding: `${/^[aeiou]/u.test(first.category) ? "An" : "A"} ${first.category} reply has waited ${Math.floor(hoursWaiting)} hours with nothing sent after it.`,
2909
+ hoursWaiting,
2910
+ lead: first.leadRef,
2911
+ provider: first.provider,
2912
+ receivedAt: first.sentAt,
2913
+ reply: first.ref,
2914
+ subject: first.subject,
2915
+ unansweredReplies: open.length
2916
+ }
2917
+ ];
2918
+ };
2919
+ var readReplies = (context, since, max) => {
2920
+ const { outbound } = context;
2921
+ const filtered = outbound.capabilities["replies.since"] !== false;
2922
+ if (!filtered) {
2923
+ context.note(
2924
+ "This tool cannot filter replies by date, so the newest replies were read and filtered here."
2925
+ );
2926
+ }
2927
+ return readCapped2(
2928
+ context,
2929
+ (cap) => outbound.replies.listAll(filtered ? { max: cap, since } : { max: cap }),
2930
+ max,
2931
+ "replies"
2932
+ );
2933
+ };
2934
+ var droppedReplies = defineInsight({
2935
+ description: "Replies from prospects that nobody answered. Reads the replies since a date (14 days before now by default), keeps the categories that need an answer, and for each conversation reads its thread, or the lead's timeline when there is no thread, and reports it as dropped when nothing was sent after the reply and it has waited longer than older_than_hours. Returns the dropped replies longest waiting first with hours waiting, category, campaign and lead. A reply that could not be checked is counted in totals.unchecked, never reported as dropped. Costs one request per page of replies plus one per conversation checked, so at most about max_replies requests.",
2936
+ inputSchema: input15,
2937
+ key: "droppedReplies",
2938
+ name: "dropped_replies",
2939
+ needs: ["replies.list"],
2940
+ next: "Use person_summary with the lead's email address to read what was sent before answering, or hot_leads to see who else to contact first.",
2941
+ run: async (context, values) => {
2942
+ const since = new Date(
2943
+ values.since === null ? context.now - DEFAULT_DAYS * DAY : Date.parse(values.since)
2944
+ ).toISOString();
2945
+ const readers = readersOf(context);
2946
+ if (!(readers.thread || readers.timeline)) {
2947
+ context.note(
2948
+ "This tool can read neither a conversation nor a lead's timeline, so no reply could be checked."
2949
+ );
2950
+ }
2951
+ const read = await readReplies(context, since, values.max_replies);
2952
+ const replies2 = read.filter(
2953
+ (reply) => reply.sentAt === null || Date.parse(reply.sentAt) >= Date.parse(since)
2954
+ );
2955
+ const wanted = replies2.filter(
2956
+ (reply) => values.categories.includes(reply.category)
2957
+ );
2958
+ const kept = wanted.filter(
2959
+ (reply) => values.include_auto || reply.isAuto !== true
2960
+ );
2961
+ const conversations = conversationsOf(kept, readers);
2962
+ const dropped = [];
2963
+ let answered = 0;
2964
+ let unchecked = 0;
2965
+ let tooRecent = 0;
2966
+ for (const conversation of conversations) {
2967
+ const timed = conversation.replies.some((each) => each.sentAt !== null);
2968
+ if (conversation.by === null || !timed) {
2969
+ unchecked += 1;
2970
+ } else {
2971
+ const messages = context.page(
2972
+ // oxlint-disable-next-line no-await-in-loop -- one conversation at a time keeps the rate budget predictable.
2973
+ await (conversation.by === "thread" ? context.outbound.thread(conversation.id).messages() : context.outbound.lead(conversation.id).timeline())
2974
+ );
2975
+ const found = toDropped(
2976
+ unanswered(conversation.replies, messages),
2977
+ conversation.by,
2978
+ context.now
2979
+ );
2980
+ const old = found.filter(
2981
+ (each) => each.hoursWaiting >= values.older_than_hours
2982
+ );
2983
+ dropped.push(...old);
2984
+ answered += found.length === 0 ? 1 : 0;
2985
+ tooRecent += found.length - old.length;
2986
+ }
2987
+ }
2988
+ const answer = {
2989
+ dropped: dropped.toSorted(
2990
+ (left, right) => right.hoursWaiting - left.hoursWaiting || left.reply.localeCompare(right.reply)
2991
+ ),
2992
+ olderThanHours: values.older_than_hours,
2993
+ since,
2994
+ totals: {
2995
+ answered,
2996
+ conversations: conversations.length,
2997
+ dropped: dropped.length,
2998
+ repliesRead: read.length,
2999
+ skippedAuto: wanted.length - kept.length,
3000
+ skippedByCategory: replies2.length - wanted.length,
3001
+ tooRecent,
3002
+ unchecked
3003
+ }
3004
+ };
3005
+ return answer;
3006
+ }
3007
+ });
3008
+
3009
+ // src/insights/people/hot-leads.ts
3010
+ import { z as z19 } from "zod";
3011
+ var DAY2 = 864e5;
3012
+ var weight = (value, what) => z19.number().min(0).default(value).describe(what);
3013
+ var input16 = z19.object({
3014
+ campaign: z19.string().min(1).nullable().default(null).describe(
3015
+ "A campaign ref (provider:workspace:id) to rank the leads of. Null ranks every lead the tool lists."
3016
+ ),
3017
+ count_cap: z19.number().int().min(1).default(5).describe(
3018
+ "The most replies, clicks or opens that earn points, so 40 opens do not outrank a reply"
3019
+ ),
3020
+ limit: z19.number().int().min(1).max(500).default(20).describe("How many leads to return"),
3021
+ max_leads: z19.number().int().min(1).max(2e4).default(500).describe(
3022
+ "The most leads to read and score. A vendor request returns about 50 to 100 leads."
3023
+ ),
3024
+ positive_labels: positiveLabelsField,
3025
+ recency_days: z19.number().min(1).default(14).describe(
3026
+ "A reply today earns the full recency points, fading evenly to none after this many days"
3027
+ ),
3028
+ weight_click: weight(5, "Points for each click, up to count_cap"),
3029
+ weight_interest: weight(50, "Points for carrying a positive interest label"),
3030
+ weight_open: weight(1, "Points for each open, up to count_cap"),
3031
+ weight_recency: weight(20, "Points for a reply received right now"),
3032
+ weight_reply: weight(10, "Points for each reply, up to count_cap")
3033
+ });
3034
+ var capped = (count, points, cap) => count === null ? null : Math.min(count, cap) * points;
3035
+ var partsOf = (lead, values, now) => {
3036
+ const engagement = lead.engagement ?? null;
3037
+ const positive = isPositive(lead.interest, values.positive_labels);
3038
+ const replies2 = engagement?.replies ?? (lead.status === "replied" ? 1 : null);
3039
+ const repliedAt = engagement?.lastRepliedAt ?? null;
3040
+ const age = repliedAt === null ? null : Math.max(0, now - Date.parse(repliedAt)) / DAY2 / values.recency_days;
3041
+ return {
3042
+ clicks: capped(
3043
+ engagement?.clicks ?? null,
3044
+ values.weight_click,
3045
+ values.count_cap
3046
+ ),
3047
+ interest: positive === null ? null : Number(positive) * values.weight_interest,
3048
+ opens: capped(
3049
+ engagement?.opens ?? null,
3050
+ values.weight_open,
3051
+ values.count_cap
3052
+ ),
3053
+ recency: age === null ? null : round(Math.max(0, 1 - age) * values.weight_recency),
3054
+ replies: capped(replies2, values.weight_reply, values.count_cap)
3055
+ };
3056
+ };
3057
+ var reasonOf = (lead, parts, now) => {
3058
+ const engagement = lead.engagement ?? null;
3059
+ const repliedAt = engagement?.lastRepliedAt ?? null;
3060
+ const facts = [
3061
+ (parts.interest ?? 0) > 0 ? `marked ${lead.interest}` : null,
3062
+ (parts.replies ?? 0) > 0 ? `replied ${engagement?.replies ?? 1} time(s)` : null,
3063
+ repliedAt === null ? null : `last reply ${Math.floor(Math.max(0, now - Date.parse(repliedAt)) / DAY2)} day(s) ago`,
3064
+ (parts.clicks ?? 0) > 0 ? `${engagement?.clicks} click(s)` : null,
3065
+ (parts.opens ?? 0) > 0 ? `${engagement?.opens} open(s)` : null
3066
+ ].flatMap((fact) => fact === null ? [] : [fact]);
3067
+ return `${facts.join(", ")}.`;
3068
+ };
3069
+ var toHotLead = (lead, values, now) => {
3070
+ const parts = partsOf(lead, values, now);
3071
+ const score = total(Object.values(parts));
3072
+ return score === null ? [] : [
3073
+ {
3074
+ campaign: lead.campaignRef,
3075
+ clicks: lead.engagement?.clicks ?? null,
3076
+ company: lead.company,
3077
+ email: lead.email,
3078
+ interest: lead.interest,
3079
+ lastRepliedAt: lead.engagement?.lastRepliedAt ?? null,
3080
+ lead: lead.ref,
3081
+ linkedinUrl: lead.linkedinUrl,
3082
+ name: nameOf(lead),
3083
+ opens: lead.engagement?.opens ?? null,
3084
+ parts,
3085
+ reason: reasonOf(lead, parts, now),
3086
+ replies: lead.engagement?.replies ?? null,
3087
+ score: round(score) ?? 0,
3088
+ status: lead.status,
3089
+ title: lead.title
3090
+ }
3091
+ ];
3092
+ };
3093
+ var readLeads2 = (context, { campaign, max_leads: maxLeads }) => {
3094
+ const { outbound } = context;
3095
+ if (campaign !== null) {
3096
+ return leadsOf(context, campaign, maxLeads);
3097
+ }
3098
+ if (!outbound.capabilities["leads.list"]) {
3099
+ throw new OutboundError(
3100
+ "Unsupported",
3101
+ `hot_leads needs a campaign here: the ${outbound.provider} adapter cannot list every lead (leads.list)`,
3102
+ { provider: outbound.provider }
3103
+ );
3104
+ }
3105
+ return readCapped2(
3106
+ context,
3107
+ (cap) => outbound.leads.listAll({ max: cap }),
3108
+ maxLeads,
3109
+ "leads"
3110
+ );
3111
+ };
3112
+ var hottestFirst = (left, right) => right.score - left.score || (right.lastRepliedAt ?? "").localeCompare(left.lastRepliedAt ?? "") || left.lead.localeCompare(right.lead);
3113
+ var hotLeads = defineInsight({
3114
+ description: "Who to call first: leads ranked by a score built from what the vendor reports, namely a positive interest label, replies, clicks, opens and how recent the last reply is. Every score comes with its parts, and the weights are inputs. A lead with no label and no engagement data is left out and counted in totals.withoutData, never scored 0; unsubscribed and bounced leads are left out too. Give a campaign ref to rank one campaign, or none to rank every lead the tool lists. Costs one request per page of leads read (max_leads sets the ceiling). A part that is null means the vendor does not report that signal.",
3115
+ inputSchema: input16,
3116
+ key: "hotLeads",
3117
+ name: "hot_leads",
3118
+ needs: [],
3119
+ next: "Use person_summary with a lead's email address or LinkedIn profile to read the conversation before calling.",
3120
+ run: async (context, values) => {
3121
+ const leads = await readLeads2(context, values);
3122
+ noteEngagement(
3123
+ context,
3124
+ leads,
3125
+ "scores rest on the interest label and the lead's status"
3126
+ );
3127
+ const open = leads.filter(
3128
+ (lead) => lead.status !== "unsubscribed" && lead.status !== "bounced"
3129
+ );
3130
+ const scored = open.flatMap((lead) => toHotLead(lead, values, context.now));
3131
+ const hot = scored.filter((lead) => lead.score > 0).toSorted(hottestFirst);
3132
+ const answer = {
3133
+ leads: hot.slice(0, values.limit),
3134
+ totals: {
3135
+ excluded: leads.length - open.length,
3136
+ hot: hot.length,
3137
+ leadsRead: leads.length,
3138
+ scored: scored.length,
3139
+ withoutData: open.length - scored.length
3140
+ }
3141
+ };
3142
+ return answer;
3143
+ }
3144
+ });
3145
+
3146
+ // src/insights/people/lead-collisions.ts
3147
+ import { z as z20 } from "zod";
3148
+
3149
+ // src/insights/people/find.ts
3150
+ var personKey = (identifier) => {
3151
+ const value = identifier.trim();
3152
+ const slug = profileSlug(value);
3153
+ if (slug !== null) {
3154
+ return `linkedin:${slug}`;
3155
+ }
3156
+ return value.includes("@") && !value.includes(" ") ? `email:${value.toLowerCase()}` : null;
3157
+ };
3158
+ var keysOfLead = (lead) => {
3159
+ const slug = profileSlug(lead.linkedinUrl);
3160
+ return [
3161
+ ...lead.email === null ? [] : [`email:${lead.email}`],
3162
+ ...slug === null ? [] : [`linkedin:${slug}`]
3163
+ ];
3164
+ };
3165
+ var filterFor = (key) => key.startsWith("email:") ? { email: key.slice("email:".length) } : {
3166
+ linkedinUrl: `https://www.linkedin.com/in/${key.slice("linkedin:".length)}`
3167
+ };
3168
+ var findPerson = async (context, identifier, maxRecords) => {
3169
+ const first = personKey(identifier);
3170
+ if (first === null) {
3171
+ throw new OutboundError(
3172
+ "Invalid",
3173
+ "Give an email address or a LinkedIn profile URL",
3174
+ { provider: context.outbound.provider }
3175
+ );
3176
+ }
3177
+ const keys = /* @__PURE__ */ new Set([first]);
3178
+ const asked = /* @__PURE__ */ new Set();
3179
+ const records = /* @__PURE__ */ new Map();
3180
+ for (let next = [...keys].find((key) => !asked.has(key)); next !== void 0; next = [...keys].find((key) => !asked.has(key))) {
3181
+ asked.add(next);
3182
+ const leads = await context.all(
3183
+ context.outbound.leads.listAll({ ...filterFor(next), max: maxRecords }),
3184
+ `${maxRecords} records of the person`
3185
+ );
3186
+ for (const lead of leads) {
3187
+ const leadKeys = keysOfLead(lead);
3188
+ if (leadKeys.includes(next)) {
3189
+ records.set(`${lead.ref} ${lead.campaignRef ?? ""}`, lead);
3190
+ for (const key of leadKeys) {
3191
+ keys.add(key);
3192
+ }
3193
+ }
3194
+ }
3195
+ }
3196
+ return {
3197
+ keys: [...keys].toSorted(),
3198
+ records: [...records.values()].slice(0, maxRecords)
3199
+ };
3200
+ };
3201
+
3202
+ // src/insights/people/lead-collisions.ts
3203
+ var input17 = z20.object({
3204
+ max_campaigns: z20.number().int().min(1).max(200).default(20).describe(
3205
+ "The most campaigns to read. Each costs one request per page of its leads."
3206
+ ),
3207
+ max_leads_per_campaign: z20.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3208
+ statuses: statusesField
3209
+ });
3210
+ var groupPeople = (entries) => {
3211
+ const byKey = /* @__PURE__ */ new Map();
3212
+ for (const entry of entries) {
3213
+ const keys = keysOfLead(entry.lead);
3214
+ const found = new Set(keys.flatMap((key) => byKey.get(key) ?? []));
3215
+ const group = { entries: [entry], keys: new Set(keys) };
3216
+ for (const other of found) {
3217
+ group.entries.unshift(...other.entries);
3218
+ for (const key of other.keys) {
3219
+ group.keys.add(key);
3220
+ }
3221
+ }
3222
+ for (const key of group.keys) {
3223
+ byKey.set(key, group);
3224
+ }
3225
+ }
3226
+ return [...new Set(byKey.values())];
3227
+ };
3228
+ var toCollision = (group) => {
3229
+ const perCampaign = new Map(
3230
+ group.entries.map((entry) => [entry.campaign.ref, entry])
3231
+ );
3232
+ if (perCampaign.size < 2) {
3233
+ return [];
3234
+ }
3235
+ const campaigns = [...perCampaign.values()].map(({ campaign, lead }) => ({
3236
+ campaign: campaign.ref,
3237
+ campaignName: campaign.name,
3238
+ channel: campaign.channel,
3239
+ lead: lead.ref,
3240
+ leadStatus: lead.status,
3241
+ provider: campaign.provider
3242
+ }));
3243
+ const providers = [...new Set(campaigns.map((each) => each.provider))];
3244
+ const channels = [...new Set(campaigns.map((each) => each.channel))];
3245
+ const scope = providers.length > 1 ? "across_tools" : "within_tool";
3246
+ const identifiers = [...group.keys].toSorted();
3247
+ return [
3248
+ {
3249
+ campaignCount: campaigns.length,
3250
+ campaigns,
3251
+ channels,
3252
+ finding: scope === "across_tools" ? `${identifiers[0]} is in ${campaigns.length} campaigns across ${providers.join(" and ")} (${channels.join(" and ")}).` : `${identifiers[0]} is in ${campaigns.length} ${providers[0]} campaigns at once.`,
3253
+ identifiers,
3254
+ providers,
3255
+ scope,
3256
+ stillActive: campaigns.filter((each) => each.leadStatus === "active").length
3257
+ }
3258
+ ];
3259
+ };
3260
+ var worstFirst = (left, right) => right.campaignCount - left.campaignCount || left.scope.localeCompare(right.scope) || (left.identifiers[0] ?? "").localeCompare(right.identifiers[0] ?? "");
3261
+ var leadCollisions = defineInsight({
3262
+ 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.",
3263
+ inputSchema: input17,
3264
+ key: "leadCollisions",
3265
+ name: "lead_collisions",
3266
+ needs: ["leads.byCampaign"],
3267
+ next: "Use person_summary with one of the identifiers to see what that person was sent and whether they replied.",
3268
+ run: async (context, values) => {
3269
+ const campaigns = await campaignsIn2(
3270
+ context,
3271
+ values.statuses,
3272
+ values.max_campaigns
3273
+ );
3274
+ const entries = [];
3275
+ for (const campaign of campaigns) {
3276
+ const leads = await leadsOf(
3277
+ context,
3278
+ campaign.ref,
3279
+ values.max_leads_per_campaign
3280
+ );
3281
+ entries.push(...leads.map((lead) => ({ campaign, lead })));
3282
+ }
3283
+ const collisions = groupPeople(entries).flatMap(toCollision).toSorted(worstFirst);
3284
+ const acrossTools = collisions.filter(
3285
+ (each) => each.scope === "across_tools"
3286
+ ).length;
3287
+ const answer = {
3288
+ collisions,
3289
+ totals: {
3290
+ acrossTools,
3291
+ campaignsRead: campaigns.length,
3292
+ collisions: collisions.length,
3293
+ leadsRead: entries.length,
3294
+ leadsWithoutIdentifier: entries.filter(
3295
+ (entry) => keysOfLead(entry.lead).length === 0
3296
+ ).length,
3297
+ withinTool: collisions.length - acrossTools
3298
+ }
3299
+ };
3300
+ return answer;
3301
+ }
3302
+ });
3303
+
3304
+ // src/insights/people/person-summary.ts
3305
+ import { z as z21 } from "zod";
3306
+ var input18 = z21.object({
3307
+ max_campaigns: z21.number().int().min(1).max(50).default(20).describe("The most campaigns to report on. Each costs up to 2 requests."),
3308
+ person: z21.string().min(3).describe("The person's email address or LinkedIn profile URL")
3309
+ });
3310
+ var times2 = (messages, direction) => messages.flatMap(
3311
+ (message) => message.direction === direction && message.sentAt !== null ? [message.sentAt] : []
3312
+ );
3313
+ var repliedSteps = (lead, messages) => {
3314
+ const steps = /* @__PURE__ */ new Set();
3315
+ let lastSent = null;
3316
+ for (const message of messages) {
3317
+ if (message.direction === "out") {
3318
+ lastSent = message.stepIndex ?? lastSent;
3319
+ } else if ((message.stepIndex ?? lastSent) !== null) {
3320
+ steps.add(message.stepIndex ?? lastSent ?? 0);
3321
+ }
3322
+ }
3323
+ const named2 = lead.engagement?.repliedStepIndex ?? null;
3324
+ if (named2 !== null) {
3325
+ steps.add(named2);
3326
+ }
3327
+ return [...steps].toSorted((left, right) => left - right);
3328
+ };
3329
+ var activityOf = (lead, messages) => {
3330
+ const sent = times2(messages, "out");
3331
+ const received = times2(messages, "in");
3332
+ const counted = lead.engagement;
3333
+ return {
3334
+ firstContactedAt: sent[0] ?? null,
3335
+ lastContactedAt: sent.at(-1) ?? counted?.lastContactedAt ?? null,
3336
+ lastRepliedAt: received.at(-1) ?? counted?.lastRepliedAt ?? null,
3337
+ lastStep: counted?.stepIndex ?? messages.findLast(
3338
+ (message) => message.direction === "out" && message.stepIndex !== null
3339
+ )?.stepIndex ?? null,
3340
+ // A vendor's thread can hold fewer messages than were sent; the last
3341
+ // step sent (counted from 0) is then the better count.
3342
+ messagesSent: Math.max(sent.length, (counted?.stepIndex ?? -1) + 1),
3343
+ // A vendor that keeps no thread still counts replies on the lead.
3344
+ replies: Math.max(received.length, counted?.replies ?? 0),
3345
+ threadIsShort: sent.length < (counted?.stepIndex ?? -1) + 1
3346
+ };
3347
+ };
3348
+ var timelineOf = async (context, timelines, lead) => {
3349
+ const known2 = timelines.get(lead.ref);
3350
+ const all = known2 ?? context.page(await context.outbound.lead(lead.ref).timeline());
3351
+ timelines.set(lead.ref, all);
3352
+ return all.filter(
3353
+ (message) => message.campaignRef === null || lead.campaignRef === null || message.campaignRef === lead.campaignRef
3354
+ );
3355
+ };
3356
+ var summarize2 = async (context, timelines, lead) => {
3357
+ const { outbound } = context;
3358
+ const messages = await timelineOf(context, timelines, lead);
3359
+ const campaign = lead.campaignRef === null ? null : context.one(await outbound.campaigns.get(lead.campaignRef));
3360
+ const { threadIsShort, ...activity } = activityOf(lead, messages);
3361
+ if (threadIsShort) {
3362
+ context.note(
3363
+ "A thread held fewer sent messages than the lead's last step, so messages sent is counted from the last step."
3364
+ );
3365
+ }
3366
+ return {
3367
+ ...activity,
3368
+ campaign: lead.campaignRef,
3369
+ campaignName: campaign?.name ?? null,
3370
+ campaignStatus: campaign?.status ?? null,
3371
+ channel: campaign?.channel ?? (lead.email === null ? "linkedin" : "email"),
3372
+ interest: lead.interest,
3373
+ lead: lead.ref,
3374
+ leadStatus: lead.status,
3375
+ provider: lead.provider,
3376
+ replied: activity.replies > 0 || lead.status === "replied",
3377
+ repliedSteps: repliedSteps(lead, messages)
3378
+ };
3379
+ };
3380
+ var byChannel2 = (campaigns) => {
3381
+ const channels = {};
3382
+ for (const campaign of campaigns) {
3383
+ const before = channels[campaign.channel] ?? {
3384
+ messagesSent: 0,
3385
+ replies: 0
3386
+ };
3387
+ channels[campaign.channel] = {
3388
+ messagesSent: before.messagesSent + campaign.messagesSent,
3389
+ replies: before.replies + campaign.replies
3390
+ };
3391
+ }
3392
+ return channels;
3393
+ };
3394
+ var personSummary = defineInsight({
3395
+ description: "Everything about one person across campaigns and channels, from their email address or LinkedIn profile: each campaign they are in, how many messages they were sent, whether and how often they replied, which steps they replied to, their interest label, and totals by channel. Records are linked by exact identifier only, so an email finds a LinkedIn record only when a tool holds both for that person. Costs one lookup per identifier, then up to 2 requests per campaign.",
3396
+ inputSchema: input18,
3397
+ key: "personSummary",
3398
+ name: "person_summary",
3399
+ needs: ["leads.lookup", "leads.timeline"],
3400
+ next: "Use account_summary with their email domain to see everyone at the same company.",
3401
+ run: async (context, { max_campaigns: maxCampaigns, person }) => {
3402
+ const found = await findPerson(context, person, maxCampaigns);
3403
+ const campaigns = [];
3404
+ const timelines = /* @__PURE__ */ new Map();
3405
+ for (const lead of found.records) {
3406
+ campaigns.push(await summarize2(context, timelines, lead));
3407
+ }
3408
+ const contacted = campaigns.filter((entry) => entry.messagesSent > 0);
3409
+ const replied = campaigns.filter((entry) => entry.replied);
3410
+ const summary = {
3411
+ campaigns,
3412
+ found: campaigns.length > 0,
3413
+ identifiers: found.keys,
3414
+ totals: {
3415
+ byChannel: byChannel2(campaigns),
3416
+ campaignReplyRate: rate(
3417
+ contacted.filter((entry) => entry.replied).length,
3418
+ contacted.length
3419
+ ),
3420
+ campaigns: campaigns.length,
3421
+ campaignsReplied: replied.length,
3422
+ messagesSent: campaigns.reduce(
3423
+ (sum, entry) => sum + entry.messagesSent,
3424
+ 0
3425
+ ),
3426
+ replies: campaigns.reduce((sum, entry) => sum + entry.replies, 0)
3427
+ }
3428
+ };
3429
+ return summary;
3430
+ }
3431
+ });
3432
+
3433
+ // src/insights/people/personalization-gaps.ts
3434
+ import { z as z22 } from "zod";
3435
+ var input19 = z22.object({
3436
+ campaign: z22.string().min(1).describe("The campaign's ref (provider:workspace:id)"),
3437
+ limit: z22.number().int().min(1).max(5e3).default(100).describe("How many affected leads to list. The counts cover all of them."),
3438
+ max_leads: z22.number().int().min(1).max(2e4).default(500).describe(
3439
+ "The most leads to check. A vendor request returns about 50 to 100 leads."
3440
+ )
3441
+ });
3442
+ var PATTERNS = [
3443
+ /\{\{\s*(?<name>[^{}|]+?)\s*(?<fallback>\|[^{}]*)?\}\}/gu,
3444
+ /(?<!\{)\{(?<name>[A-Za-z_][\w .-]*)\}(?!\})/gu,
3445
+ /%(?<name>[A-Za-z_][\w-]*)%/gu
3446
+ ];
3447
+ var keyOf = (name) => name.toLowerCase().replaceAll(/[\s_-]/gu, "");
3448
+ var BUILTINS = /* @__PURE__ */ new Map([
3449
+ ["company", (lead) => lead.company],
3450
+ ["companyname", (lead) => lead.company],
3451
+ ["email", (lead) => lead.email],
3452
+ ["firstname", (lead) => lead.firstName],
3453
+ ["jobtitle", (lead) => lead.title],
3454
+ ["lastname", (lead) => lead.lastName],
3455
+ ["title", (lead) => lead.title]
3456
+ ]);
3457
+ var FIELDS = ["subject", "body"];
3458
+ var variablesIn = (text) => PATTERNS.flatMap(
3459
+ (pattern) => [...text.matchAll(pattern)].map((match) => ({
3460
+ fallback: match.groups?.fallback !== void 0,
3461
+ name: match.groups?.name ?? ""
3462
+ }))
3463
+ );
3464
+ var findVariables = (sequence2) => {
3465
+ const found = /* @__PURE__ */ new Map();
3466
+ const texts = sequence2.steps.flatMap(
3467
+ (step) => step.variants.flatMap(
3468
+ (variant) => FIELDS.map((field) => ({
3469
+ field,
3470
+ step: step.index,
3471
+ text: variant[field] ?? "",
3472
+ variant: variant.variantKey
3473
+ }))
3474
+ )
3475
+ );
3476
+ for (const { field, step, text, variant } of texts) {
3477
+ for (const { fallback, name } of variablesIn(text)) {
3478
+ const entry = found.get(keyOf(name)) ?? { name, uses: [] };
3479
+ entry.uses.push({ fallback, field, step, variant });
3480
+ found.set(keyOf(name), entry);
3481
+ }
3482
+ }
3483
+ return found;
3484
+ };
3485
+ var filled = (value) => value !== null && value.trim() !== "";
3486
+ var valuesOf = (lead) => /* @__PURE__ */ new Set([
3487
+ ...[...BUILTINS].flatMap(
3488
+ ([key, read]) => filled(read(lead)) ? [key] : []
3489
+ ),
3490
+ ...Object.entries(lead.custom).flatMap(
3491
+ ([key, value]) => filled(value) ? [keyOf(key)] : []
3492
+ )
3493
+ ]);
3494
+ var sourceOf = (key, customKeys) => {
3495
+ if (BUILTINS.has(key)) {
3496
+ return "builtin";
3497
+ }
3498
+ return customKeys.has(key) ? "custom" : "unknown";
3499
+ };
3500
+ var toVariable = (key, { name, uses }, leads, customKeys) => {
3501
+ const source = sourceOf(key, customKeys);
3502
+ const known2 = source !== "unknown";
3503
+ const needed = uses.some((use) => !use.fallback);
3504
+ const without = leads.filter((values) => !values.has(key)).length;
3505
+ return {
3506
+ key,
3507
+ variable: {
3508
+ gap: known2 && needed,
3509
+ leadsAffected: known2 ? Number(needed) * without : null,
3510
+ leadsWithoutValue: known2 ? without : null,
3511
+ name,
3512
+ source,
3513
+ steps: [...new Set(uses.map((use) => use.step))].toSorted(
3514
+ (left, right) => left - right
3515
+ ),
3516
+ uses
3517
+ }
3518
+ };
3519
+ };
3520
+ var missingOf = (lead, values, gaps) => {
3521
+ const missing2 = gaps.flatMap(
3522
+ (gap) => values.has(gap.key) ? [] : [gap.variable.name]
3523
+ );
3524
+ return missing2.length === 0 ? [] : [
3525
+ {
3526
+ email: lead.email,
3527
+ lead: lead.ref,
3528
+ linkedinUrl: lead.linkedinUrl,
3529
+ missing: missing2,
3530
+ status: lead.status
3531
+ }
3532
+ ];
3533
+ };
3534
+ var personalizationGaps = defineInsight({
3535
+ 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.",
3536
+ inputSchema: input19,
3537
+ key: "personalizationGaps",
3538
+ name: "personalization_gaps",
3539
+ needs: ["sequence", "leads.byCampaign"],
3540
+ next: "Fix the leads' fields or add a fallback in the tool, then use lead_collisions to check the same leads are not in another campaign.",
3541
+ run: async (context, values) => {
3542
+ const sequence2 = context.one(
3543
+ await context.outbound.campaign(values.campaign).sequence()
3544
+ );
3545
+ const found = findVariables(sequence2);
3546
+ const leads = found.size === 0 ? [] : await leadsOf(context, values.campaign, values.max_leads);
3547
+ if (found.size === 0) {
3548
+ context.note("The sequence uses no variables, so no lead was read.");
3549
+ }
3550
+ const customKeys = new Set(
3551
+ leads.flatMap((lead) => Object.keys(lead.custom).map(keyOf))
3552
+ );
3553
+ const keyed = [...found].map(
3554
+ ([key, entry]) => toVariable(key, entry, leads.map(valuesOf), customKeys)
3555
+ );
3556
+ const variables = keyed.map((each) => each.variable).toSorted(
3557
+ (left, right) => (right.leadsAffected ?? -1) - (left.leadsAffected ?? -1) || left.name.localeCompare(right.name)
3558
+ );
3559
+ const gaps = keyed.filter((each) => each.variable.gap);
3560
+ const affected = leads.flatMap((lead) => missingOf(lead, valuesOf(lead), gaps)).toSorted(
3561
+ (left, right) => right.missing.length - left.missing.length || left.lead.localeCompare(right.lead)
3562
+ );
3563
+ const answer = {
3564
+ campaign: values.campaign,
3565
+ leads: affected.slice(0, values.limit),
3566
+ totals: {
3567
+ affectedRate: rate(affected.length, leads.length),
3568
+ leadsAffected: affected.length,
3569
+ leadsRead: leads.length,
3570
+ steps: sequence2.steps.length,
3571
+ variables: variables.length
3572
+ },
3573
+ unknownVariables: variables.flatMap(
3574
+ (each) => each.source === "unknown" ? [each.name] : []
3575
+ ),
3576
+ variables
3577
+ };
3578
+ return answer;
3579
+ }
3580
+ });
3581
+
3582
+ // src/insights/people/suppression-check.ts
3583
+ import { z as z23 } from "zod";
3584
+ var input20 = z23.object({
3585
+ max_block_entries: z23.number().int().min(1).max(1e5).default(2e3).describe(
3586
+ "The most block list entries to read. A vendor request returns about 50 to 100."
3587
+ ),
3588
+ max_campaigns: z23.number().int().min(1).max(200).default(20).describe(
3589
+ "The most campaigns to check. Each costs one request per page of its leads."
3590
+ ),
3591
+ max_leads_per_campaign: z23.number().int().min(1).max(2e4).default(500).describe("The most leads to read from each campaign"),
3592
+ statuses: statusesField
3593
+ });
3594
+ var slugOfEntry = (value) => profileSlug(value) ?? value.trim().replaceAll(/^\/+|\/+$/gu, "").toLowerCase();
3595
+ var indexEntries = (entries) => {
3596
+ const blocked = {
3597
+ domain: /* @__PURE__ */ new Map(),
3598
+ email: /* @__PURE__ */ new Map(),
3599
+ linkedin: /* @__PURE__ */ new Map(),
3600
+ notChecked: entries.filter(
3601
+ (entry) => entry.kind === "company" || entry.kind === "other"
3602
+ ).length
3603
+ };
3604
+ for (const entry of entries) {
3605
+ if (entry.kind === "email") {
3606
+ blocked.email.set(entry.value.trim().toLowerCase(), entry);
3607
+ } else if (entry.kind === "domain") {
3608
+ blocked.domain.set(
3609
+ entry.value.trim().toLowerCase().replace(/^@/u, ""),
3610
+ entry
3611
+ );
3612
+ } else if (entry.kind === "linkedin") {
3613
+ blocked.linkedin.set(slugOfEntry(entry.value), entry);
3614
+ }
3615
+ }
3616
+ return blocked;
3617
+ };
3618
+ var matchLead = (lead, blocked) => {
3619
+ const slug = profileSlug(lead.linkedinUrl);
3620
+ const candidates = [
3621
+ ["email", blocked.email.get(lead.email ?? "")],
3622
+ ["linkedin", blocked.linkedin.get(slug ?? "")],
3623
+ ["domain", blocked.domain.get(domainOf(lead.email) ?? "")]
3624
+ ];
3625
+ const hits = candidates.flatMap(
3626
+ ([matchedBy, entry]) => entry === void 0 ? [] : [{ entry, matchedBy }]
3627
+ );
3628
+ return hits[0] ?? null;
3629
+ };
3630
+ var toViolation = (lead, campaign, { entry, matchedBy }) => ({
3631
+ campaign: campaign.ref,
3632
+ campaignName: campaign.name,
3633
+ email: lead.email,
3634
+ entry: entry.ref,
3635
+ entryValue: entry.value,
3636
+ finding: `${lead.email ?? lead.linkedinUrl ?? lead.ref} is in "${campaign.name}" but the block list holds the ${matchedBy} ${entry.value}.`,
3637
+ lead: lead.ref,
3638
+ leadStatus: lead.status,
3639
+ linkedinUrl: lead.linkedinUrl,
3640
+ matchedBy,
3641
+ sameTool: entry.provider === lead.provider && entry.workspaceId === lead.workspaceId
3642
+ });
3643
+ var activeFirst = (left, right) => Number(right.leadStatus === "active") - Number(left.leadStatus === "active") || left.campaign.localeCompare(right.campaign) || left.lead.localeCompare(right.lead);
3644
+ var suppressionCheck = defineInsight({
3645
+ description: "Leads sitting in campaigns although they are on the block list. Reads the block list, then the leads of each campaign in the given statuses (active by default), and matches a lead by exact email address, by email domain against domain entries, and by LinkedIn profile against profile entries. Returns each violation with the lead, the campaign, the entry and how it matched, counts per campaign, and how many block entries were read. On several tools an entry on one tool's list is also matched against the other tools' leads and marked sameTool false. Costs one request per page of block entries plus one per page of each campaign's leads.",
3646
+ inputSchema: input20,
3647
+ key: "suppressionCheck",
3648
+ name: "suppression_check",
3649
+ needs: ["blocklist", "leads.byCampaign"],
3650
+ next: "Use person_summary with a violating lead's email address to see what they were already sent.",
3651
+ run: async (context, values) => {
3652
+ const entries = await readCapped2(
3653
+ context,
3654
+ (cap) => context.outbound.blocklist.listAll({ max: cap }),
3655
+ values.max_block_entries,
3656
+ "block list entries"
3657
+ );
3658
+ const blocked = indexEntries(entries);
3659
+ const campaigns = await campaignsIn2(
3660
+ context,
3661
+ values.statuses,
3662
+ values.max_campaigns
3663
+ );
3664
+ const violations = [];
3665
+ const byCampaign = [];
3666
+ for (const campaign of campaigns) {
3667
+ const leads = await leadsOf(
3668
+ context,
3669
+ campaign.ref,
3670
+ values.max_leads_per_campaign
3671
+ );
3672
+ const found = leads.flatMap((lead) => {
3673
+ const hit = matchLead(lead, blocked);
3674
+ return hit === null ? [] : [toViolation(lead, campaign, hit)];
3675
+ });
3676
+ violations.push(...found);
3677
+ byCampaign.push({
3678
+ campaign: campaign.ref,
3679
+ campaignName: campaign.name,
3680
+ leadsRead: leads.length,
3681
+ violations: found.length
3682
+ });
3683
+ }
3684
+ const matches = tally(violations.map((each) => each.matchedBy));
3685
+ const answer = {
3686
+ byCampaign: byCampaign.toSorted(
3687
+ (left, right) => right.violations - left.violations || left.campaign.localeCompare(right.campaign)
3688
+ ),
3689
+ totals: {
3690
+ blockEntriesNotChecked: blocked.notChecked,
3691
+ blockEntriesRead: entries.length,
3692
+ byMatch: {
3693
+ domain: matches.get("domain") ?? 0,
3694
+ email: matches.get("email") ?? 0,
3695
+ linkedin: matches.get("linkedin") ?? 0
3696
+ },
3697
+ campaignsRead: campaigns.length,
3698
+ leadsRead: byCampaign.reduce((sum, each) => sum + each.leadsRead, 0),
3699
+ violations: violations.length
3700
+ },
3701
+ violations: violations.toSorted(activeFirst)
3702
+ };
3703
+ return answer;
3704
+ }
3705
+ });
3706
+
3707
+ // src/insights/people/index.ts
3708
+ var PEOPLE_INSIGHTS = [
3709
+ personSummary,
3710
+ accountSummary,
3711
+ leadCollisions,
3712
+ suppressionCheck,
3713
+ droppedReplies,
3714
+ hotLeads,
3715
+ personalizationGaps
3716
+ ];
3717
+
3718
+ // src/insights/senders/bounce-watch.ts
3719
+ import { z as z25 } from "zod";
3720
+
3721
+ // src/insights/senders/read.ts
3722
+ import { z as z24 } from "zod";
3723
+ var statusesInput = z24.array(campaignStatusSchema).min(1).default(["active"]).describe(
3724
+ "Campaign statuses to look at: active, paused, draft, completed, archived or unknown"
3725
+ );
3726
+ var dayInput2 = (what) => z24.string().regex(/^\d{4}-\d{2}-\d{2}$/u).optional().describe(
3727
+ `${what}, as YYYY-MM-DD. Leave out for the vendor's whole history.`
3728
+ );
3729
+ var readCapped3 = (context, walk, max, what) => context.all(walk(max), `${max} ${what}`);
3730
+ var readCampaigns2 = async (context, statuses, max) => {
3731
+ const { outbound } = context;
3732
+ if (outbound.capabilities["campaigns.status"] === false) {
3733
+ const every = await readCapped3(
3734
+ context,
3735
+ (cap) => outbound.campaigns.listAll({ max: cap }),
3736
+ max,
3737
+ "campaigns"
3738
+ );
3739
+ return every.filter((campaign) => statuses.includes(campaign.status));
3740
+ }
3741
+ const found = [];
3742
+ for (const status of new Set(statuses)) {
3743
+ const room = max - found.length;
3744
+ if (room <= 0) {
3745
+ context.partial(
3746
+ `The cap of ${max} campaigns was reached before ${status} campaigns were read.`
3747
+ );
3748
+ break;
3749
+ }
3750
+ found.push(
3751
+ ...await readCapped3(
3752
+ context,
3753
+ (cap) => outbound.campaigns.listAll({ max: cap, status }),
3754
+ room,
3755
+ "campaigns"
3756
+ )
3757
+ );
3758
+ }
3759
+ return found;
3760
+ };
3761
+ var readCampaignSenders = (context, campaign, max) => readCapped3(
3762
+ context,
3763
+ (cap) => context.outbound.campaign(campaign.ref).senders.listAll({ max: cap }),
3764
+ max,
3765
+ `senders of campaign ${campaign.name}`
3766
+ );
3767
+ var domainOf2 = (address) => {
3768
+ const domain = address?.split("@")[1]?.trim().toLowerCase() ?? "";
3769
+ return domain === "" ? null : domain;
3770
+ };
3771
+ var DNS_RECORDS = ["spf", "dkim", "dmarc", "mx"];
3772
+ var failingDns = (health) => DNS_RECORDS.filter((record) => health.dns[record] === false);
3773
+ var unknownDns = (health) => DNS_RECORDS.filter((record) => health.dns[record] === null);
3774
+ var warmupSpam = (health) => {
3775
+ const { warmup } = health;
3776
+ if (warmup === null || warmup.spam === null) {
3777
+ return null;
3778
+ }
3779
+ const sent = warmup.sent ?? (warmup.inbox === null ? null : warmup.inbox + warmup.spam);
3780
+ return sent === null ? null : { sent, spam: warmup.spam };
3781
+ };
3782
+ var dayFrom = (now, offsetDays) => new Date(now + offsetDays * 864e5).toISOString().slice(0, 10);
3783
+
3784
+ // src/insights/senders/bounce-watch.ts
3785
+ var input21 = z25.object({
3786
+ from: dayInput2("First day to count"),
3787
+ include_senders: z25.boolean().default(true).describe(
3788
+ "Also check the senders of each campaign over the threshold. Costs 1 listing per such campaign and 1 request per sender."
3789
+ ),
3790
+ max_campaigns: z25.number().int().min(1).max(500).default(50).describe("The most campaigns to check. Each costs 1 request."),
3791
+ 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"),
3792
+ min_sent: z25.number().int().min(0).default(100).describe("A campaign with fewer sends than this is too small to judge"),
3793
+ threshold: z25.number().min(0).max(1).default(0.03).describe("The bounce rate, bounced divided by sent, that is too high"),
3794
+ to: dayInput2("Last day to count")
3795
+ });
3796
+ var countsOf2 = (bounced, sent) => ({
3797
+ bounced,
3798
+ interval: wilson(bounced, sent),
3799
+ rate: rate(bounced, sent),
3800
+ sent
3801
+ });
3802
+ var known = (row) => row === void 0 || row.sent === null || row.bounced === null ? null : countsOf2(row.bounced, row.sent);
3803
+ var isOver = (counts, threshold) => counts.rate !== null && counts.rate > threshold;
3804
+ var whyUnknown = (row) => {
3805
+ if (row === void 0) {
3806
+ return "The vendor returned no stats for the period.";
3807
+ }
3808
+ return row.sent === null ? "The vendor does not report a sent count." : "The vendor does not report a bounce count.";
3809
+ };
3810
+ var senderReader = (context, range) => {
3811
+ const seen = /* @__PURE__ */ new Map();
3812
+ return async (ref) => {
3813
+ if (!seen.has(ref)) {
3814
+ const [row] = context.rows(
3815
+ await context.outbound.sender(ref).stats(range)
3816
+ );
3817
+ seen.set(ref, known(row));
3818
+ }
3819
+ return seen.get(ref) ?? null;
3820
+ };
3821
+ };
3822
+ var sendersOver = async (context, campaign, options) => {
3823
+ const senders2 = await readCampaignSenders(context, campaign, options.max);
3824
+ const over = [];
3825
+ for (const sender of senders2) {
3826
+ const counts = await options.read(sender.ref);
3827
+ if (counts !== null && isOver(counts, options.threshold)) {
3828
+ over.push({
3829
+ ...counts,
3830
+ address: sender.address,
3831
+ name: sender.name,
3832
+ sender: sender.ref
3833
+ });
3834
+ }
3835
+ }
3836
+ return over.toSorted((left, right) => (right.rate ?? 0) - (left.rate ?? 0));
3837
+ };
3838
+ var canCheckSenders = (context, wanted) => {
3839
+ const { capabilities } = context.outbound;
3840
+ if (!wanted) {
3841
+ return false;
3842
+ }
3843
+ if (capabilities["stats.bySender"] === false || !capabilities["senders.byCampaign"]) {
3844
+ context.note(
3845
+ "Senders were not checked: the adapter needs stats per sender and the list of a campaign's senders."
3846
+ );
3847
+ return false;
3848
+ }
3849
+ return true;
3850
+ };
3851
+ var bounceWatch = defineInsight({
3852
+ 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.",
3853
+ inputSchema: input21,
3854
+ key: "bounceWatch",
3855
+ name: "bounce_watch",
3856
+ needs: ["stats.campaign"],
3857
+ next: "Use domain_health on the senders named here, and settings_audit on the campaigns over the threshold.",
3858
+ run: async (context, options) => {
3859
+ const { outbound } = context;
3860
+ const { min_sent: minSent, threshold } = options;
3861
+ const range = { from: options.from, to: options.to };
3862
+ const campaigns = await readCapped3(
3863
+ context,
3864
+ (cap) => outbound.campaigns.listAll({ max: cap }),
3865
+ options.max_campaigns,
3866
+ "campaigns"
3867
+ );
3868
+ const withSenders = campaigns.length > 0 && canCheckSenders(context, options.include_senders);
3869
+ const read = senderReader(context, range);
3870
+ const over = [];
3871
+ const tooFewSends = [];
3872
+ const unknown = [];
3873
+ const counted = [];
3874
+ for (const campaign of campaigns) {
3875
+ const [row] = context.rows(
3876
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
3877
+ await outbound.campaign(campaign.ref).stats(range)
3878
+ );
3879
+ const counts = known(row);
3880
+ const entry = {
3881
+ campaign: campaign.ref,
3882
+ name: campaign.name,
3883
+ status: campaign.status
3884
+ };
3885
+ if (counts === null) {
3886
+ unknown.push({ ...entry, reason: whyUnknown(row) });
3887
+ } else if (counts.sent < minSent || counts.sent === 0) {
3888
+ counted.push(counts);
3889
+ tooFewSends.push({
3890
+ ...entry,
3891
+ ...counts,
3892
+ finding: `${counts.bounced} of ${counts.sent} sends bounced; under ${minSent} sends is too few to judge.`,
3893
+ senders: null
3894
+ });
3895
+ } else {
3896
+ counted.push(counts);
3897
+ if (isOver(counts, threshold)) {
3898
+ over.push({
3899
+ ...entry,
3900
+ ...counts,
3901
+ finding: `${counts.bounced} of ${counts.sent} sends bounced (${counts.rate}), over the ${threshold} threshold.`,
3902
+ senders: withSenders ? (
3903
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
3904
+ await sendersOver(context, campaign, {
3905
+ max: options.max_senders_per_campaign,
3906
+ read,
3907
+ threshold
3908
+ })
3909
+ ) : null
3910
+ });
3911
+ }
3912
+ }
3913
+ }
3914
+ const bounced = total(counted.map((each) => each.bounced));
3915
+ const sent = total(counted.map((each) => each.sent));
3916
+ const byRate2 = (left, right) => (right.rate ?? -1) - (left.rate ?? -1);
3917
+ const answer = {
3918
+ minSent,
3919
+ over: over.toSorted(byRate2),
3920
+ threshold,
3921
+ tooFewSends: tooFewSends.toSorted(byRate2),
3922
+ totals: {
3923
+ bounced,
3924
+ campaigns: campaigns.length,
3925
+ clean: counted.length - over.length - tooFewSends.length,
3926
+ over: over.length,
3927
+ rate: rate(bounced, sent),
3928
+ sent,
3929
+ tooFewSends: tooFewSends.length,
3930
+ unknown: unknown.length
3931
+ },
3932
+ unknown
3933
+ };
3934
+ return answer;
3935
+ }
3936
+ });
3937
+
3938
+ // src/insights/senders/domain-health.ts
3939
+ import { z as z26 } from "zod";
3940
+ var input22 = z26.object({
3941
+ max_senders: z26.number().int().min(1).max(500).default(50).describe("The most senders to check. Each costs 1 request."),
3942
+ spam_rate_threshold: z26.number().min(0).max(1).default(0.1).describe(
3943
+ "A domain whose warmup emails land in spam more often than this share is high risk"
3944
+ )
3945
+ });
3946
+ var RISK_ORDER = ["high", "medium", "low", "unknown"];
3947
+ var pooledWarmup = (checked) => {
3948
+ const reported = checked.flatMap(({ health }) => {
3949
+ const spam2 = warmupSpam(health);
3950
+ return spam2 === null ? [] : [spam2];
3951
+ });
3952
+ if (reported.length === 0) {
3953
+ return {
3954
+ interval: null,
3955
+ mailboxes: 0,
3956
+ sent: null,
3957
+ spam: null,
3958
+ spamRate: null
3959
+ };
3960
+ }
3961
+ const sent = reported.reduce((sum, each) => sum + each.sent, 0);
3962
+ const spam = reported.reduce((sum, each) => sum + each.spam, 0);
3963
+ return {
3964
+ interval: wilson(spam, sent),
3965
+ mailboxes: reported.length,
3966
+ sent,
3967
+ spam,
3968
+ spamRate: rate(spam, sent)
3969
+ };
3970
+ };
3971
+ var missingChecks = (checked, warmup) => [
3972
+ ...DNS_RECORDS.filter(
3973
+ (record) => checked.every(({ health }) => unknownDns(health).includes(record))
3974
+ ),
3975
+ ...checked.every(({ health }) => health.connected === null) ? ["connection"] : [],
3976
+ ...checked.every(({ health }) => health.blacklisted === null) ? ["blocklist"] : [],
3977
+ ...warmup.mailboxes === 0 ? ["warmup"] : []
3978
+ ];
3979
+ var CHECKS3 = DNS_RECORDS.length + 3;
3980
+ var reportFor = (domain, checked, threshold) => {
3981
+ const failing = DNS_RECORDS.filter(
3982
+ (record) => checked.some(({ health }) => health.dns[record] === false)
3983
+ );
3984
+ const blacklisted = checked.filter(
3985
+ ({ health }) => health.blacklisted === true
3986
+ ).length;
3987
+ const disconnected = checked.filter(
3988
+ ({ health }) => health.connected === false
3989
+ ).length;
3990
+ const warmup = pooledWarmup(checked);
3991
+ const authFailing = failing.filter((record) => record !== "dmarc");
3992
+ const spamHigh = warmup.spamRate !== null && warmup.spamRate > threshold;
3993
+ const high = [
3994
+ ...blacklisted > 0 ? [`${blacklisted} of ${checked.length} mailboxes are on a block list`] : [],
3995
+ ...authFailing.length > 0 ? [`${authFailing.join(", ").toUpperCase()} failing`] : [],
3996
+ ...spamHigh ? [
3997
+ `${warmup.spam} of ${warmup.sent} warmup emails landed in spam (${warmup.spamRate}, over ${threshold})`
3998
+ ] : []
3999
+ ];
4000
+ const medium = [
4001
+ ...failing.includes("dmarc") ? ["DMARC failing"] : [],
4002
+ ...disconnected > 0 ? [`${disconnected} of ${checked.length} mailboxes are disconnected`] : []
4003
+ ];
4004
+ const notReported = missingChecks(checked, warmup);
4005
+ const calm = notReported.length === CHECKS3 ? "unknown" : "low";
4006
+ const lesser = medium.length > 0 ? "medium" : calm;
4007
+ return {
4008
+ blacklisted,
4009
+ disconnected,
4010
+ domain,
4011
+ failingDns: failing,
4012
+ mailboxes: checked.map(({ health, sender }) => ({
4013
+ address: sender.address,
4014
+ blacklisted: health.blacklisted,
4015
+ connected: health.connected,
4016
+ failingDns: failingDns(health),
4017
+ issues: health.issues,
4018
+ sender: sender.ref,
4019
+ status: sender.status
4020
+ })),
4021
+ notReported,
4022
+ reasons: [...high, ...medium],
4023
+ risk: high.length > 0 ? "high" : lesser,
4024
+ warmup
4025
+ };
4026
+ };
4027
+ var worstFirst2 = (left, right) => RISK_ORDER.indexOf(left.risk) - RISK_ORDER.indexOf(right.risk) || right.reasons.length - left.reasons.length || (right.warmup.spamRate ?? -1) - (left.warmup.spamRate ?? -1) || left.domain.localeCompare(right.domain);
4028
+ var seatRank = (seat) => {
4029
+ if (seat.connected === false) {
4030
+ return 0;
4031
+ }
4032
+ return seat.connected === null ? 1 : 2;
4033
+ };
4034
+ var domainHealth = defineInsight({
4035
+ description: "Deliverability per sending domain: for each domain its mailboxes, which DNS records (SPF, DKIM, DMARC, MX) fail, how many mailboxes are disconnected or on a block list, the share of warmup emails landing in spam pooled over its mailboxes, and a risk level with the reasons, worst domain first. LinkedIn seats are listed apart with their connection state. Use it before scaling volume or when replies drop. Costs one listing of senders plus 1 request per sender. A null count or rate means the vendor does not report it; a domain with nothing reported has the risk `unknown`, not `low`.",
4036
+ inputSchema: input22,
4037
+ key: "domainHealth",
4038
+ name: "domain_health",
4039
+ needs: ["senders.list", "senders.health"],
4040
+ next: "Use warmup_readiness to see which mailboxes of a risky domain are not ready, or bounce_watch to see whether bounces already rose.",
4041
+ run: async (context, { max_senders: maxSenders, spam_rate_threshold: threshold }) => {
4042
+ const { outbound } = context;
4043
+ const senders2 = await readCapped3(
4044
+ context,
4045
+ (cap) => outbound.senders.listAll({ max: cap }),
4046
+ maxSenders,
4047
+ "senders"
4048
+ );
4049
+ const byDomain = /* @__PURE__ */ new Map();
4050
+ const linkedinSeats = [];
4051
+ const mailboxesWithoutDomain = [];
4052
+ for (const sender of senders2) {
4053
+ const health = context.one(await outbound.sender(sender.ref).health());
4054
+ const domain = health.domain ?? domainOf2(sender.address);
4055
+ if (sender.kind === "linkedin") {
4056
+ linkedinSeats.push({
4057
+ connected: health.connected,
4058
+ issues: health.issues,
4059
+ linkedinUrl: sender.linkedinUrl,
4060
+ name: sender.name,
4061
+ sender: sender.ref,
4062
+ status: sender.status
4063
+ });
4064
+ } else if (domain === null) {
4065
+ mailboxesWithoutDomain.push(sender.ref);
4066
+ } else {
4067
+ byDomain.set(domain, [
4068
+ ...byDomain.get(domain) ?? [],
4069
+ { health, sender }
4070
+ ]);
4071
+ }
4072
+ }
4073
+ const domains = [...byDomain].map(([domain, checked]) => reportFor(domain, checked, threshold)).toSorted(worstFirst2);
4074
+ const count = (risk) => domains.filter((domain) => domain.risk === risk).length;
4075
+ const answer = {
4076
+ domains,
4077
+ linkedinSeats: linkedinSeats.toSorted(
4078
+ (left, right) => seatRank(left) - seatRank(right)
4079
+ ),
4080
+ mailboxesWithoutDomain,
4081
+ totals: {
4082
+ domains: domains.length,
4083
+ high: count("high"),
4084
+ linkedinSeats: linkedinSeats.length,
4085
+ low: count("low"),
4086
+ medium: count("medium"),
4087
+ senders: senders2.length,
4088
+ unknown: count("unknown")
4089
+ }
4090
+ };
4091
+ return answer;
4092
+ }
4093
+ });
4094
+
4095
+ // src/insights/senders/sender-capacity.ts
4096
+ import { z as z27 } from "zod";
4097
+ var input23 = z27.object({
4098
+ days: z27.number().int().min(1).max(90).default(7).describe("How many full days before today to average the sends over"),
4099
+ max_campaigns: z27.number().int().min(1).max(200).default(25).describe(
4100
+ "The most active campaigns to read. Each costs up to 2 requests, or 3 when the vendor has no workspace totals."
4101
+ ),
4102
+ max_senders: z27.number().int().min(1).max(1e3).default(200).describe(
4103
+ "The most senders to read for the workspace, and for each campaign"
4104
+ )
4105
+ });
4106
+ var limitsOf = (senders2) => senders2.map((sender) => sender.dailyLimit);
4107
+ var capacityOf = (senders2) => {
4108
+ const active = senders2.filter((sender) => sender.status === "active");
4109
+ const withLimit = active.filter((sender) => sender.dailyLimit !== null);
4110
+ const ofKind = (kind) => total(limitsOf(active.filter((sender) => sender.kind === kind)));
4111
+ return {
4112
+ activeSenders: active.length,
4113
+ daily: total(limitsOf(active)),
4114
+ inactiveSenders: senders2.length - active.length,
4115
+ linkedinDaily: ofKind("linkedin"),
4116
+ mailboxDaily: ofKind("mailbox"),
4117
+ withLimit: withLimit.length,
4118
+ withoutLimit: active.length - withLimit.length
4119
+ };
4120
+ };
4121
+ var readOne = async (context, campaign, maxSenders) => {
4122
+ const { capabilities } = context.outbound;
4123
+ const settings = capabilities["campaigns.settings"] ? context.one(await context.outbound.campaign(campaign.ref).settings()) : null;
4124
+ return {
4125
+ campaign,
4126
+ dailyLimit: settings?.dailyLimit ?? null,
4127
+ // The senders are only compared with the campaign's own limit.
4128
+ senders: settings !== null && capabilities["senders.byCampaign"] ? await readCampaignSenders(context, campaign, maxSenders) : null
4129
+ };
4130
+ };
4131
+ var dailyRows = async (context, campaigns, range) => {
4132
+ const { outbound } = context;
4133
+ const { capabilities } = outbound;
4134
+ if (capabilities["stats.byDay"] === false) {
4135
+ context.note(
4136
+ "Average daily sends left out: the adapter has no daily stats."
4137
+ );
4138
+ return null;
4139
+ }
4140
+ if (capabilities["stats.workspace"] !== false) {
4141
+ return {
4142
+ rows: [...context.rows(await outbound.stats({ ...range, by: "day" }))],
4143
+ scope: "workspace"
4144
+ };
4145
+ }
4146
+ if (capabilities["stats.campaign"] === false) {
4147
+ context.note(
4148
+ "Average daily sends left out: the adapter has no workspace or campaign stats."
4149
+ );
4150
+ return null;
4151
+ }
4152
+ const rows = [];
4153
+ for (const campaign of campaigns) {
4154
+ rows.push(
4155
+ ...context.rows(
4156
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
4157
+ await outbound.campaign(campaign.ref).stats({ ...range, by: "day" })
4158
+ )
4159
+ );
4160
+ }
4161
+ context.note(
4162
+ "Average daily sends cover the active campaigns read, not the whole workspace."
4163
+ );
4164
+ return { rows, scope: "campaigns" };
4165
+ };
4166
+ var readSends = async (context, campaigns, days) => {
4167
+ const range = {
4168
+ from: dayFrom(context.now, -days),
4169
+ to: dayFrom(context.now, -1)
4170
+ };
4171
+ const read = await dailyRows(context, campaigns, range);
4172
+ if (read === null) {
4173
+ return null;
4174
+ }
4175
+ const sent = total(read.rows.map((row) => row.sent));
4176
+ const reported = read.rows.flatMap(
4177
+ (row) => row.date === null || row.sent === null ? [] : [row.date]
4178
+ );
4179
+ return {
4180
+ ...range,
4181
+ averageDaily: sent === null ? null : round(sent / days),
4182
+ days,
4183
+ daysWithData: new Set(reported).size,
4184
+ scope: read.scope,
4185
+ total: sent
4186
+ };
4187
+ };
4188
+ var shortfallOf = (read) => {
4189
+ const active = (read.senders ?? []).filter(
4190
+ (sender) => sender.status === "active"
4191
+ );
4192
+ if (read.dailyLimit === null || active.some((sender) => sender.dailyLimit === null)) {
4193
+ return "unchecked";
4194
+ }
4195
+ const senderCapacity2 = total(limitsOf(active)) ?? 0;
4196
+ if (senderCapacity2 >= read.dailyLimit) {
4197
+ return null;
4198
+ }
4199
+ return {
4200
+ activeSenders: active.length,
4201
+ campaign: read.campaign.ref,
4202
+ dailyLimit: read.dailyLimit,
4203
+ finding: `${read.campaign.name} asks for ${read.dailyLimit} a day but its ${active.length} active senders can send ${senderCapacity2}.`,
4204
+ name: read.campaign.name,
4205
+ senderCapacity: senderCapacity2,
4206
+ senders: read.senders?.length ?? 0,
4207
+ shortBy: read.dailyLimit - senderCapacity2
4208
+ };
4209
+ };
4210
+ var askOf = (reads) => {
4211
+ const limits = reads.map((read) => read.dailyLimit);
4212
+ const withLimit = limits.filter((limit2) => limit2 !== null).length;
4213
+ return {
4214
+ campaigns: reads.length,
4215
+ daily: total(limits),
4216
+ withLimit,
4217
+ withoutLimit: reads.length - withLimit
4218
+ };
4219
+ };
4220
+ var findingOf = (capacity, ask, sends) => {
4221
+ if (capacity.daily === null) {
4222
+ return "No active sender reports a daily limit, so capacity is unknown.";
4223
+ }
4224
+ const senders2 = `active ${capacity.withLimit === 1 ? "sender" : "senders"}`;
4225
+ const parts = [
4226
+ capacity.withoutLimit === 0 ? `${capacity.withLimit} ${senders2} can send ${capacity.daily} a day.` : `The ${capacity.withLimit} ${senders2} that ${capacity.withLimit === 1 ? "reports" : "report"} a daily limit can send ${capacity.daily} a day; ${capacity.withoutLimit} more ${capacity.withoutLimit === 1 ? "reports" : "report"} no limit and ${capacity.withoutLimit === 1 ? "is" : "are"} not counted.`
4227
+ ];
4228
+ if (ask !== null && ask.daily !== null) {
4229
+ parts.push(
4230
+ ask.daily > capacity.daily ? `Active campaigns ask for ${ask.daily}, which is ${ask.daily - capacity.daily} more than that.` : `Active campaigns ask for ${ask.daily}, which fits.`
4231
+ );
4232
+ }
4233
+ if (sends !== null && sends.averageDaily !== null) {
4234
+ parts.push(
4235
+ `${sends.averageDaily} a day were sent on average over the last ${sends.days} days.`
4236
+ );
4237
+ }
4238
+ return parts.join(" ");
4239
+ };
4240
+ var senderCapacity = defineInsight({
4241
+ description: "Whether the senders can send what the campaigns ask: total daily capacity (the daily limits of active senders added up), the total daily ask of active campaigns, the average messages sent per day over the last days, utilization, and the campaigns whose own senders cannot cover their daily limit. Use it before adding campaigns or when sends fall short. Costs one listing of senders and of active campaigns, then up to 2 requests per campaign and 1 for daily stats. A null means the vendor does not report the number; a sender or campaign with no reported limit is counted apart, never as 0.",
4242
+ inputSchema: input23,
4243
+ key: "senderCapacity",
4244
+ name: "sender_capacity",
4245
+ needs: ["senders.list"],
4246
+ next: "Use sender_load to see which senders are shared by too many campaigns, or warmup_readiness before raising a sender's limit.",
4247
+ run: async (context, { days, max_campaigns: maxCampaigns, max_senders: maxSenders }) => {
4248
+ const { outbound } = context;
4249
+ const { capabilities } = outbound;
4250
+ const senders2 = await readCapped3(
4251
+ context,
4252
+ (cap) => outbound.senders.listAll({ max: cap }),
4253
+ maxSenders,
4254
+ "senders"
4255
+ );
4256
+ const campaigns = await readCampaigns2(context, ["active"], maxCampaigns);
4257
+ const reads = [];
4258
+ for (const campaign of campaigns) {
4259
+ reads.push(await readOne(context, campaign, maxSenders));
4260
+ }
4261
+ const hasSettings = capabilities["campaigns.settings"];
4262
+ const canCompare = hasSettings && capabilities["senders.byCampaign"];
4263
+ if (!hasSettings) {
4264
+ context.note(
4265
+ "The daily ask and the campaigns short of senders were left out: the adapter cannot read campaign settings."
4266
+ );
4267
+ } else if (!canCompare) {
4268
+ context.note(
4269
+ "The campaigns short of senders were left out: the adapter cannot list a campaign's senders."
4270
+ );
4271
+ }
4272
+ const capacity = capacityOf(senders2);
4273
+ const ask = hasSettings ? askOf(reads) : null;
4274
+ const sends = await readSends(context, campaigns, days);
4275
+ const shortfalls = reads.map(shortfallOf);
4276
+ const answer = {
4277
+ ask,
4278
+ askRatio: rate(ask?.daily ?? null, capacity.daily),
4279
+ capacity,
4280
+ finding: findingOf(capacity, ask, sends),
4281
+ sends,
4282
+ shortCampaigns: canCompare ? shortfalls.flatMap(
4283
+ (each) => each === null || each === "unchecked" ? [] : [each]
4284
+ ).toSorted((left, right) => right.shortBy - left.shortBy) : null,
4285
+ uncheckedCampaigns: canCompare ? shortfalls.filter((each) => each === "unchecked").length : null,
4286
+ utilization: rate(sends?.averageDaily ?? null, capacity.daily)
4287
+ };
4288
+ return answer;
4289
+ }
4290
+ });
4291
+
4292
+ // src/insights/senders/sender-load.ts
4293
+ import { z as z28 } from "zod";
4294
+ var input24 = z28.object({
4295
+ max_campaigns: z28.number().int().min(1).max(200).default(25).describe("The most campaigns to read. Each costs 1 request."),
4296
+ max_campaigns_per_sender: z28.number().int().min(1).default(3).describe("A sender attached to more campaigns than this is overused"),
4297
+ max_senders: z28.number().int().min(1).max(1e3).default(200).describe(
4298
+ "The most senders to read for the workspace, and for each campaign"
4299
+ ),
4300
+ statuses: statusesInput
4301
+ });
4302
+ var loaded = (sender) => ({
4303
+ address: sender.address,
4304
+ dailyLimit: sender.dailyLimit,
4305
+ name: sender.name,
4306
+ sender: sender.ref,
4307
+ status: sender.status
4308
+ });
4309
+ var riskOf = (campaign, senders2) => {
4310
+ const inactive = senders2.filter((sender) => sender.status !== "active");
4311
+ const issues = [
4312
+ ...senders2.length === 0 ? ["no_sender"] : [],
4313
+ ...senders2.length === 1 ? ["single_sender"] : [],
4314
+ ...inactive.length > 0 ? ["inactive_sender"] : []
4315
+ ];
4316
+ if (issues.length === 0) {
4317
+ return null;
4318
+ }
4319
+ const count = senders2.length === 1 ? "1 sender" : `${senders2.length} senders`;
4320
+ return {
4321
+ campaign: campaign.ref,
4322
+ finding: inactive.length > 0 ? `${campaign.name} has ${count}, ${inactive.length} of them not active.` : `${campaign.name} has ${count}.`,
4323
+ inactive: inactive.map(loaded),
4324
+ issues,
4325
+ name: campaign.name,
4326
+ senders: senders2.length
4327
+ };
4328
+ };
4329
+ var senderLoad = defineInsight({
4330
+ 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.",
4331
+ inputSchema: input24,
4332
+ key: "senderLoad",
4333
+ name: "sender_load",
4334
+ needs: ["senders.list", "senders.byCampaign"],
4335
+ next: "Use sender_capacity to see whether the senders can cover the campaigns' daily limits, or warmup_readiness for the senders that are not active.",
4336
+ run: async (context, options) => {
4337
+ const { outbound } = context;
4338
+ const allowed = options.max_campaigns_per_sender;
4339
+ const senders2 = await readCapped3(
4340
+ context,
4341
+ (cap) => outbound.senders.listAll({ max: cap }),
4342
+ options.max_senders,
4343
+ "senders"
4344
+ );
4345
+ const campaigns = await readCampaigns2(
4346
+ context,
4347
+ options.statuses,
4348
+ options.max_campaigns
4349
+ );
4350
+ const known2 = new Map(senders2.map((sender) => [sender.ref, sender]));
4351
+ const attached = /* @__PURE__ */ new Map();
4352
+ const risks = [];
4353
+ for (const campaign of campaigns) {
4354
+ const own = await readCampaignSenders(
4355
+ context,
4356
+ campaign,
4357
+ options.max_senders
4358
+ );
4359
+ const risk = riskOf(campaign, own);
4360
+ if (risk !== null) {
4361
+ risks.push(risk);
4362
+ }
4363
+ for (const sender of own) {
4364
+ known2.set(sender.ref, sender);
4365
+ attached.set(sender.ref, [
4366
+ ...attached.get(sender.ref) ?? [],
4367
+ campaign.ref
4368
+ ]);
4369
+ }
4370
+ }
4371
+ const overused = [...attached].flatMap(([ref, refs]) => {
4372
+ const sender = known2.get(ref);
4373
+ return sender === void 0 || refs.length <= allowed ? [] : [
4374
+ {
4375
+ ...loaded(sender),
4376
+ campaignRefs: refs,
4377
+ campaigns: refs.length,
4378
+ finding: `${sender.address ?? sender.name ?? ref} is attached to ${refs.length} campaigns, ${refs.length - allowed} over the limit of ${allowed}.`,
4379
+ over: refs.length - allowed
4380
+ }
4381
+ ];
4382
+ }).toSorted((left, right) => right.campaigns - left.campaigns);
4383
+ const active = senders2.filter((sender) => sender.status === "active");
4384
+ const unused = active.filter((sender) => !attached.has(sender.ref));
4385
+ const answer = {
4386
+ campaigns: risks.toSorted(
4387
+ (left, right) => right.issues.length - left.issues.length
4388
+ ),
4389
+ maxCampaignsPerSender: allowed,
4390
+ overused,
4391
+ totals: {
4392
+ activeSenders: active.length,
4393
+ campaigns: campaigns.length,
4394
+ campaignsAtRisk: risks.length,
4395
+ overused: overused.length,
4396
+ senders: senders2.length,
4397
+ unused: unused.length
4398
+ },
4399
+ unused: unused.map(loaded)
4400
+ };
4401
+ return answer;
4402
+ }
4403
+ });
4404
+
4405
+ // src/insights/senders/settings-audit.ts
4406
+ import { z as z29 } from "zod";
4407
+ var input25 = z29.object({
4408
+ max_campaigns: z29.number().int().min(1).max(200).default(25).describe(
4409
+ "The most campaigns to audit. Each costs 1 request, or 2 when its senders can be listed."
4410
+ ),
4411
+ max_daily_limit_per_sender: z29.number().min(1).default(50).describe(
4412
+ "A campaign's daily limit should not exceed this many sends per attached sender"
4413
+ ),
4414
+ max_senders_per_campaign: z29.number().int().min(1).max(1e3).default(100).describe("The most senders to count for one campaign"),
4415
+ max_window_hours: z29.number().min(1).max(24).default(12).describe("A sending window longer than this many hours is flagged"),
4416
+ min_gap_minutes: z29.number().min(0).default(5).describe("A wait between two sends shorter than this is flagged"),
4417
+ min_window_hours: z29.number().min(0).max(24).default(2).describe("A sending window shorter than this many hours is flagged"),
4418
+ statuses: statusesInput
4419
+ });
4420
+ var SEVERITY2 = {
4421
+ click_tracking: "medium",
4422
+ end_date_passed: "high",
4423
+ gap_short: "medium",
4424
+ limit_over_senders: "high",
4425
+ no_daily_limit: "medium",
4426
+ no_timezone: "low",
4427
+ no_window: "medium",
4428
+ open_tracking: "medium",
4429
+ reply_does_not_stop: "high",
4430
+ weekend: "low",
4431
+ window_long: "medium",
4432
+ window_short: "low"
4433
+ };
4434
+ var ORDER2 = ["high", "medium", "low"];
4435
+ var when = (hit, check, finding, value = null) => hit ? [{ check, finding, severity: SEVERITY2[check], value }] : [];
4436
+ var minutesOf2 = (clock) => Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3));
4437
+ var hoursOf = (window) => {
4438
+ if (window.from === null || window.to === null) {
4439
+ return null;
4440
+ }
4441
+ const minutes = minutesOf2(window.to) - minutesOf2(window.from);
4442
+ return Math.round((minutes > 0 ? minutes : minutes + 1440) / 60 * 100) / 100;
4443
+ };
4444
+ var scheduleFindings = ({ bars, settings }) => {
4445
+ const { schedule: schedule2 } = settings;
4446
+ if (schedule2.length === 0) {
4447
+ return when(
4448
+ true,
4449
+ "no_window",
4450
+ "No sending window is set or reported, so it can send at any hour."
4451
+ );
4452
+ }
4453
+ const hours = schedule2.flatMap((window) => hoursOf(window) ?? []);
4454
+ const longest = Math.max(...hours);
4455
+ const shortest = Math.min(...hours);
4456
+ const weekend = schedule2.find(
4457
+ (window) => window.days.includes(0) || window.days.includes(6)
4458
+ );
4459
+ return [
4460
+ ...when(
4461
+ weekend !== void 0,
4462
+ "weekend",
4463
+ "A sending window includes Saturday or Sunday.",
4464
+ weekend?.days.join(",")
4465
+ ),
4466
+ ...when(
4467
+ longest > bars.maxWindowHours,
4468
+ "window_long",
4469
+ `A sending window is ${longest} hours long, over ${bars.maxWindowHours}.`,
4470
+ longest
4471
+ ),
4472
+ ...when(
4473
+ shortest < bars.minWindowHours,
4474
+ "window_short",
4475
+ `A sending window is ${shortest} hours long, under ${bars.minWindowHours}.`,
4476
+ shortest
4477
+ ),
4478
+ ...when(
4479
+ schedule2.some((window) => window.timezone === null),
4480
+ "no_timezone",
4481
+ "A sending window has no timezone."
4482
+ )
4483
+ ];
4484
+ };
4485
+ var limitFindings = (audit2) => {
4486
+ const { bars, campaign, senders: senders2, settings, today } = audit2;
4487
+ const { dailyLimit, endDate, gapMinutes } = settings;
4488
+ const allowed = (senders2 ?? 0) * bars.maxPerSender;
4489
+ return [
4490
+ ...when(
4491
+ dailyLimit === null,
4492
+ "no_daily_limit",
4493
+ "No daily limit is set or reported."
4494
+ ),
4495
+ ...when(
4496
+ dailyLimit !== null && allowed > 0 && dailyLimit > allowed,
4497
+ "limit_over_senders",
4498
+ `The daily limit of ${dailyLimit} is over ${bars.maxPerSender} a day for each of its ${senders2} senders (${allowed}).`,
4499
+ dailyLimit
4500
+ ),
4501
+ ...when(
4502
+ gapMinutes !== null && gapMinutes < bars.minGapMinutes,
4503
+ "gap_short",
4504
+ `Sends are ${gapMinutes} minutes apart, under ${bars.minGapMinutes}.`,
4505
+ gapMinutes
4506
+ ),
4507
+ ...when(
4508
+ campaign.status === "active" && endDate !== null && endDate < today,
4509
+ "end_date_passed",
4510
+ `The campaign is active but its end date ${endDate} has passed.`,
4511
+ endDate
4512
+ )
4513
+ ];
4514
+ };
4515
+ var ruleFindings = ({ settings }) => [
4516
+ ...when(
4517
+ settings.stopOnReply === false,
4518
+ "reply_does_not_stop",
4519
+ "A lead who replies keeps getting the next steps."
4520
+ ),
4521
+ ...when(
4522
+ settings.tracking.opens === true,
4523
+ "open_tracking",
4524
+ "Open tracking is on, a deliverability risk."
4525
+ ),
4526
+ ...when(
4527
+ settings.tracking.clicks === true,
4528
+ "click_tracking",
4529
+ "Click tracking is on; it rewrites links, a deliverability risk."
4530
+ )
4531
+ ];
4532
+ var audit = (subject) => ({
4533
+ campaign: subject.campaign.ref,
4534
+ findings: [
4535
+ ...scheduleFindings(subject),
4536
+ ...limitFindings(subject),
4537
+ ...ruleFindings(subject)
4538
+ ].toSorted(
4539
+ (left, right) => ORDER2.indexOf(left.severity) - ORDER2.indexOf(right.severity)
4540
+ ),
4541
+ name: subject.campaign.name,
4542
+ status: subject.campaign.status
4543
+ });
4544
+ var countOf2 = (campaign, severity) => campaign.findings.filter((finding) => finding.severity === severity).length;
4545
+ var worstFirst3 = (left, right) => countOf2(right, "high") - countOf2(left, "high") || countOf2(right, "medium") - countOf2(left, "medium") || right.findings.length - left.findings.length;
4546
+ var countChecks = (campaigns) => {
4547
+ const count = (check) => campaigns.filter(
4548
+ (campaign) => campaign.findings.some((finding) => finding.check === check)
4549
+ ).length;
4550
+ return {
4551
+ click_tracking: count("click_tracking"),
4552
+ end_date_passed: count("end_date_passed"),
4553
+ gap_short: count("gap_short"),
4554
+ limit_over_senders: count("limit_over_senders"),
4555
+ no_daily_limit: count("no_daily_limit"),
4556
+ no_timezone: count("no_timezone"),
4557
+ no_window: count("no_window"),
4558
+ open_tracking: count("open_tracking"),
4559
+ reply_does_not_stop: count("reply_does_not_stop"),
4560
+ weekend: count("weekend"),
4561
+ window_long: count("window_long"),
4562
+ window_short: count("window_short")
4563
+ };
4564
+ };
4565
+ var settingsAudit = defineInsight({
4566
+ 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.",
4567
+ inputSchema: input25,
4568
+ key: "settingsAudit",
4569
+ name: "settings_audit",
4570
+ needs: ["campaigns.settings"],
4571
+ next: "Use sender_capacity to size a daily limit against the senders, or bounce_watch to see whether a flagged campaign already bounces.",
4572
+ run: async (context, options) => {
4573
+ const { outbound } = context;
4574
+ const countSenders = outbound.capabilities["senders.byCampaign"];
4575
+ const bars = {
4576
+ maxPerSender: options.max_daily_limit_per_sender,
4577
+ maxWindowHours: options.max_window_hours,
4578
+ minGapMinutes: options.min_gap_minutes,
4579
+ minWindowHours: options.min_window_hours
4580
+ };
4581
+ const campaigns = await readCampaigns2(
4582
+ context,
4583
+ options.statuses,
4584
+ options.max_campaigns
4585
+ );
4586
+ if (!countSenders) {
4587
+ context.note(
4588
+ "The daily limit was not compared with the sender count: the adapter cannot list a campaign's senders."
4589
+ );
4590
+ }
4591
+ const audited = [];
4592
+ for (const campaign of campaigns) {
4593
+ const settings = context.one(
4594
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
4595
+ await outbound.campaign(campaign.ref).settings()
4596
+ );
4597
+ const senders2 = countSenders ? (
4598
+ // oxlint-disable-next-line no-await-in-loop -- one campaign at a time keeps the rate budget predictable.
4599
+ await readCampaignSenders(
4600
+ context,
4601
+ campaign,
4602
+ options.max_senders_per_campaign
4603
+ )
4604
+ ) : null;
4605
+ audited.push(
4606
+ audit({
4607
+ bars,
4608
+ campaign,
4609
+ senders: senders2?.length ?? null,
4610
+ settings,
4611
+ today: dayFrom(context.now, 0)
4612
+ })
4613
+ );
4614
+ }
4615
+ const flagged = audited.filter((campaign) => campaign.findings.length > 0).toSorted(worstFirst3);
4616
+ const sum = (severity) => flagged.reduce((all, campaign) => all + countOf2(campaign, severity), 0);
4617
+ const answer = {
4618
+ byCheck: countChecks(flagged),
4619
+ campaigns: flagged,
4620
+ totals: {
4621
+ campaigns: audited.length,
4622
+ clean: audited.length - flagged.length,
4623
+ high: sum("high"),
4624
+ low: sum("low"),
4625
+ medium: sum("medium"),
4626
+ withFindings: flagged.length
4627
+ }
4628
+ };
4629
+ return answer;
4630
+ }
4631
+ });
4632
+
4633
+ // src/insights/senders/warmup-readiness.ts
4634
+ import { z as z30 } from "zod";
4635
+ var input26 = z30.object({
4636
+ check_health: z30.boolean().default(false).describe(
4637
+ "Also check each mailbox's DNS records and warmup spam. Costs 1 more request per mailbox."
4638
+ ),
4639
+ max_senders: z30.number().int().min(1).max(1e3).default(100).describe("The most senders to check"),
4640
+ max_spam_rate: z30.number().min(0).max(1).default(0.1).describe(
4641
+ "With check_health, a mailbox whose warmup emails land in spam more often than this share is not ready"
4642
+ ),
4643
+ min_score: z30.number().min(0).max(100).default(90).describe("The warmup score a mailbox needs to be ready")
4644
+ });
4645
+ var healthReasons = (health, bars) => {
4646
+ const failing = failingDns(health);
4647
+ const spam = warmupSpam(health);
4648
+ const spamRate = spam === null ? null : rate(spam.spam, spam.sent);
4649
+ return [
4650
+ ...failing.length > 0 ? [
4651
+ [
4652
+ "dns_failing",
4653
+ `${failing.join(", ").toUpperCase()} failing`
4654
+ ]
4655
+ ] : [],
4656
+ ...spam !== null && spamRate !== null && spamRate > bars.maxSpamRate ? [
4657
+ [
4658
+ "warmup_spam_high",
4659
+ `${spam.spam} of ${spam.sent} warmup emails landed in spam (${spamRate}, over ${bars.maxSpamRate})`
4660
+ ]
4661
+ ] : []
4662
+ ];
4663
+ };
4664
+ var mailboxReasons = (sender, score, bars) => [
4665
+ ...sender.warmup?.enabled === false ? [["warmup_off", "Warmup is off"]] : [],
4666
+ ...score !== null && score < bars.minScore ? [
4667
+ [
4668
+ "score_low",
4669
+ `Warmup score ${score} is under ${bars.minScore}`
4670
+ ]
4671
+ ] : [],
4672
+ ...score === null ? [["score_unknown", "The vendor reports no warmup score"]] : [],
4673
+ ...sender.dailyLimit === null ? [["no_daily_limit", "No daily limit is set or reported"]] : []
4674
+ ];
4675
+ var judge2 = (sender, health, bars) => {
4676
+ const score = sender.warmup?.score ?? health?.warmup?.score ?? null;
4677
+ const reasons = [
4678
+ ...sender.status === "active" ? [] : [["not_active", `Status is ${sender.status}`]],
4679
+ ...sender.kind === "mailbox" ? mailboxReasons(sender, score, bars) : [],
4680
+ ...health === null ? [] : healthReasons(health, bars)
4681
+ ];
4682
+ return {
4683
+ address: sender.address,
4684
+ dailyLimit: sender.dailyLimit,
4685
+ findings: reasons.map(([, finding]) => finding),
4686
+ kind: sender.kind,
4687
+ name: sender.name,
4688
+ reasons: reasons.map(([reason]) => reason),
4689
+ score,
4690
+ sender: sender.ref,
4691
+ status: sender.status,
4692
+ warmupEnabled: sender.warmup?.enabled ?? null
4693
+ };
4694
+ };
4695
+ var countReasons = (judged) => {
4696
+ const count = (reason) => judged.filter((sender) => sender.reasons.includes(reason)).length;
4697
+ return {
4698
+ dns_failing: count("dns_failing"),
4699
+ no_daily_limit: count("no_daily_limit"),
4700
+ not_active: count("not_active"),
4701
+ score_low: count("score_low"),
4702
+ score_unknown: count("score_unknown"),
4703
+ warmup_off: count("warmup_off"),
4704
+ warmup_spam_high: count("warmup_spam_high")
4705
+ };
4706
+ };
4707
+ var warmupReadiness = defineInsight({
4708
+ 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.",
4709
+ inputSchema: input26,
4710
+ key: "warmupReadiness",
4711
+ name: "warmup_readiness",
4712
+ needs: ["senders.list"],
4713
+ next: "Use domain_health for the domains of the mailboxes that are not ready, or sender_capacity to see what the ready ones can send.",
4714
+ run: async (context, options) => {
4715
+ const { outbound } = context;
4716
+ const bars = {
4717
+ maxSpamRate: options.max_spam_rate,
4718
+ minScore: options.min_score
4719
+ };
4720
+ const senders2 = await readCapped3(
4721
+ context,
4722
+ (cap) => outbound.senders.listAll({ max: cap }),
4723
+ options.max_senders,
4724
+ "senders"
4725
+ );
4726
+ const healthChecked = options.check_health && outbound.capabilities["senders.health"];
4727
+ if (options.check_health && !healthChecked) {
4728
+ context.note(
4729
+ "DNS records and warmup spam were not checked: the adapter cannot read a sender's health."
4730
+ );
4731
+ }
4732
+ const judged = [];
4733
+ for (const sender of senders2) {
4734
+ const health = healthChecked && sender.kind === "mailbox" ? (
4735
+ // oxlint-disable-next-line no-await-in-loop -- one sender at a time keeps the rate budget predictable.
4736
+ context.one(await outbound.sender(sender.ref).health())
4737
+ ) : null;
4738
+ judged.push(judge2(sender, health, bars));
4739
+ }
4740
+ const notReady = judged.filter((sender) => sender.reasons.length > 0).toSorted((left, right) => right.reasons.length - left.reasons.length);
4741
+ const answer = {
4742
+ byReason: countReasons(notReady),
4743
+ healthChecked,
4744
+ linkedinSeats: senders2.filter((sender) => sender.kind === "linkedin").length,
4745
+ notReady,
4746
+ ready: judged.length - notReady.length,
4747
+ total: judged.length
4748
+ };
4749
+ return answer;
4750
+ }
4751
+ });
4752
+
4753
+ // src/insights/senders/index.ts
4754
+ var SENDERS_INSIGHTS = [
4755
+ domainHealth,
4756
+ senderCapacity,
4757
+ bounceWatch,
4758
+ warmupReadiness,
4759
+ senderLoad,
4760
+ settingsAudit
4761
+ ];
4762
+
4763
+ // src/insights/registry.ts
4764
+ var INSIGHTS = [
4765
+ ...PEOPLE_INSIGHTS,
4766
+ ...COPY_INSIGHTS,
4767
+ ...SENDERS_INSIGHTS,
4768
+ ...OPS_INSIGHTS
4769
+ ];
4770
+ var ENTRIES = INSIGHTS;
4771
+
4772
+ // src/insights/plugin.ts
4773
+ var runInsightByName = async (outbound, name, input27 = {}, options = {}) => {
4774
+ const entry = ENTRIES.find(
4775
+ (candidate) => candidate.name === name || candidate.key === name
4776
+ );
4777
+ if (entry === void 0) {
4778
+ throw new OutboundError(
4779
+ "Invalid",
4780
+ `There is no insight "${name}". Known: ${ENTRIES.map((each) => each.name).join(", ")}`,
4781
+ { provider: outbound.provider }
4782
+ );
4783
+ }
4784
+ return await entry.execute(outbound, input27, options);
4785
+ };
4786
+ var listInsights = () => ENTRIES.map((entry) => ({
4787
+ description: entry.description,
4788
+ key: entry.key,
4789
+ name: entry.name,
4790
+ needs: [...entry.needs],
4791
+ // SAFETY: a JSON Schema document is JSON by definition.
4792
+ parameters: z31.toJSONSchema(entry.inputSchema, { io: "input" })
4793
+ }));
4794
+ var insights = () => ({
4795
+ extend: (outbound) => {
4796
+ const methods = {};
4797
+ for (const entry of ENTRIES) {
4798
+ methods[entry.key] = (input27, options) => (
4799
+ // SAFETY: the answer is the entry's own, typed per key by Insights.
4800
+ entry.execute(outbound, input27, options)
4801
+ );
4802
+ }
4803
+ return { insights: methods };
4804
+ },
4805
+ name: "insights"
4806
+ });
4807
+
4808
+ // src/insights/tools.ts
4809
+ import { z as z32 } from "zod";
4810
+ var toTool = (outbound, definition) => ({
4811
+ call: async (input27) => {
4812
+ try {
4813
+ const result = await definition.execute(outbound, input27);
4814
+ return {
4815
+ data: {
4816
+ complete: result.meta.complete,
4817
+ notes: [...result.meta.notes],
4818
+ result: result.data
4819
+ },
4820
+ meta: {
4821
+ evidence: result.meta.evidence,
4822
+ provider: result.meta.provider,
4823
+ requests: result.meta.requests
4824
+ },
4825
+ next: definition.next,
4826
+ ok: true
4827
+ };
4828
+ } catch (error) {
4829
+ const known2 = OutboundError.is(error);
4830
+ return {
4831
+ error: {
4832
+ code: known2 ? error.code : "Provider",
4833
+ message: error instanceof Error ? error.message : String(error)
4834
+ },
4835
+ next: known2 && error.code === "Unsupported" ? "This insight is not available with the current adapter. Try another tool." : "Check the input and try again.",
4836
+ ok: false
4837
+ };
4838
+ }
4839
+ },
4840
+ description: definition.description,
4841
+ fields: definition.inputSchema.shape,
4842
+ name: definition.name,
4843
+ needs: [...definition.needs],
4844
+ // SAFETY: a JSON Schema document is JSON by definition.
4845
+ parameters: z32.toJSONSchema(definition.inputSchema, { io: "input" })
4846
+ });
4847
+ var insightTools = (outbound, options = {}) => {
4848
+ const wanted = options.only === void 0 ? void 0 : new Set(options.only);
4849
+ return ENTRIES.flatMap((definition) => {
4850
+ const offered = (wanted === void 0 || wanted.has(definition.name)) && definition.needs.every((key) => outbound.capabilities[key] !== false);
4851
+ return offered ? [toTool(outbound, definition)] : [];
4852
+ });
4853
+ };
4854
+ export {
4855
+ INSIGHTS,
4856
+ compareRates,
4857
+ defineInsight,
4858
+ deviation,
4859
+ insightTools,
4860
+ insights,
4861
+ listInsights,
4862
+ mean,
4863
+ median,
4864
+ percentile,
4865
+ rate,
4866
+ round,
4867
+ runInsight,
4868
+ runInsightByName,
4869
+ tally,
4870
+ total,
4871
+ wilson,
4872
+ zScore
4873
+ };