outbound-sdk 0.6.0 → 0.7.1

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 (119) hide show
  1. package/dist/alerts/check-schema.d.ts +1 -1
  2. package/dist/alerts/index.js +6 -6
  3. package/dist/audit/index.js +2 -2
  4. package/dist/benchmarks/index.js +4 -4
  5. package/dist/budget/index.js +2 -2
  6. package/dist/cards/index.js +54 -44
  7. package/dist/chunks/{chunk-BLCJHP5H.js → chunk-45TXPJW7.js} +1 -0
  8. package/dist/chunks/chunk-4AVYRVN5.js +239 -0
  9. package/dist/chunks/{chunk-YYCT3NGV.js → chunk-65YAGEWZ.js} +24 -7
  10. package/dist/chunks/{chunk-3JOC5DGD.js → chunk-6NSCPTOY.js} +488 -127
  11. package/dist/chunks/{chunk-W22SDX6S.js → chunk-7I3EPR23.js} +3 -3
  12. package/dist/chunks/{chunk-MGR6HREO.js → chunk-BNDHEDHD.js} +2 -2
  13. package/dist/chunks/chunk-DNPNTD5W.js +81 -0
  14. package/dist/chunks/{chunk-53DCVFUB.js → chunk-FALWG5U3.js} +1 -0
  15. package/dist/chunks/{chunk-OLPMBRXM.js → chunk-GL7BABF2.js} +2 -2
  16. package/dist/chunks/{chunk-ZOAG2C6V.js → chunk-HIAK2GCI.js} +9 -2
  17. package/dist/chunks/{chunk-SXGCKCAR.js → chunk-I7DXXGNZ.js} +40 -9
  18. package/dist/chunks/{chunk-BK5SLY32.js → chunk-JRL3QRBS.js} +264 -76
  19. package/dist/chunks/{chunk-PHNQ3WC2.js → chunk-KTYTE2BU.js} +4 -3
  20. package/dist/chunks/{chunk-JWGSB7PT.js → chunk-LD6F46UT.js} +2 -2
  21. package/dist/chunks/{chunk-2D42TQFU.js → chunk-LVZGIKNF.js} +2 -2
  22. package/dist/chunks/{chunk-PQSTQKRD.js → chunk-M2VXGLLZ.js} +35 -2
  23. package/dist/chunks/{chunk-UWUPUMM2.js → chunk-MW4C6LTN.js} +2 -2
  24. package/dist/chunks/chunk-OK3GAZMT.js +51 -0
  25. package/dist/chunks/{chunk-BOWXGMN3.js → chunk-POBAY3TI.js} +80 -4
  26. package/dist/chunks/{chunk-J7DDZ4C2.js → chunk-QFC4ZHD3.js} +1 -1
  27. package/dist/chunks/{chunk-TFICTGM2.js → chunk-T5MJMW3R.js} +1 -1
  28. package/dist/chunks/{chunk-GFDNRWR3.js → chunk-UFQ4WMLU.js} +1 -1
  29. package/dist/chunks/{chunk-QAKJ76HB.js → chunk-YW6FFVSZ.js} +1 -1
  30. package/dist/cli/bin.js +14 -14
  31. package/dist/cli/by-name.d.ts +28 -0
  32. package/dist/cli/commands.d.ts +2 -1
  33. package/dist/cli/config.d.ts +3 -2
  34. package/dist/cli/envelope.d.ts +50 -0
  35. package/dist/cli/index.d.ts +5 -0
  36. package/dist/cli/index.js +13 -13
  37. package/dist/cli/listing.d.ts +13 -0
  38. package/dist/cli/native.d.ts +4 -0
  39. package/dist/cli/options.d.ts +88 -0
  40. package/dist/cli/output.d.ts +13 -1
  41. package/dist/cli/suggest.d.ts +10 -0
  42. package/dist/cli/update.d.ts +25 -2
  43. package/dist/clients/index.js +6 -6
  44. package/dist/combine/index.js +7 -7
  45. package/dist/emailbison/capabilities.d.ts +1 -0
  46. package/dist/emailbison/index.js +38 -14
  47. package/dist/emailbison/map-stats.d.ts +10 -0
  48. package/dist/exporter/index.js +2 -2
  49. package/dist/failover/index.js +2 -2
  50. package/dist/fixtures/index.js +4 -4
  51. package/dist/heyreach/capabilities.d.ts +3 -0
  52. package/dist/heyreach/index.js +34 -12
  53. package/dist/heyreach/map-account.d.ts +2 -2
  54. package/dist/identity/index.js +2 -2
  55. package/dist/index.js +9 -7
  56. package/dist/insights/copy/audit-samples.d.ts +24 -0
  57. package/dist/insights/copy/audit-variant.d.ts +34 -0
  58. package/dist/insights/copy/copy-audit.d.ts +26 -12
  59. package/dist/insights/copy/copy-preview.d.ts +16 -3
  60. package/dist/insights/copy/index.d.ts +6 -0
  61. package/dist/insights/copy/reply-timing.d.ts +4 -0
  62. package/dist/insights/copy/shared.d.ts +4 -1
  63. package/dist/insights/copy/step-funnel.d.ts +20 -6
  64. package/dist/insights/copy/variant-test.d.ts +2 -3
  65. package/dist/insights/index.js +1138 -589
  66. package/dist/insights/inputs.generated.d.ts +47 -11
  67. package/dist/insights/ops/campaign-diagnosis.d.ts +2 -0
  68. package/dist/insights/ops/diagnosis-checks.d.ts +20 -1
  69. package/dist/insights/ops/index.d.ts +2 -0
  70. package/dist/insights/ops/pipeline-forecast.d.ts +17 -6
  71. package/dist/insights/people/account-summary.d.ts +14 -1
  72. package/dist/insights/people/auto-replies.d.ts +14 -0
  73. package/dist/insights/people/dropped-replies.d.ts +1 -1
  74. package/dist/insights/people/hot-leads.d.ts +5 -1
  75. package/dist/insights/people/index.d.ts +4 -0
  76. package/dist/insights/people/lead-collisions.d.ts +11 -2
  77. package/dist/insights/people/person-summary.d.ts +19 -3
  78. package/dist/insights/people/personalization-gaps.d.ts +14 -8
  79. package/dist/insights/people/suppression-check.d.ts +9 -0
  80. package/dist/insights/registry.d.ts +12 -0
  81. package/dist/insights/step.d.ts +15 -0
  82. package/dist/insights/variables.d.ts +2 -0
  83. package/dist/instantly/capabilities.d.ts +4 -0
  84. package/dist/instantly/index.js +263 -53
  85. package/dist/instantly/map-stats.d.ts +4 -0
  86. package/dist/instantly/stats-tracking.d.ts +19 -0
  87. package/dist/instantly/thread.d.ts +9 -0
  88. package/dist/internal/adapter.d.ts +5 -0
  89. package/dist/internal/auto-reply.d.ts +20 -0
  90. package/dist/internal/capabilities.d.ts +2 -0
  91. package/dist/internal/entities-account.d.ts +1 -0
  92. package/dist/internal/entities.d.ts +79 -2
  93. package/dist/internal/fields.d.ts +37 -1
  94. package/dist/internal/metrics.d.ts +23 -1
  95. package/dist/internal/outbound/api.d.ts +2 -0
  96. package/dist/internal/records.d.ts +2 -2
  97. package/dist/internal/reply-people.d.ts +37 -0
  98. package/dist/internal/runway.d.ts +42 -0
  99. package/dist/internal/sender-screen.d.ts +9 -0
  100. package/dist/internal/tracking.d.ts +33 -0
  101. package/dist/loader/index.js +4 -4
  102. package/dist/memory/data.d.ts +2 -1
  103. package/dist/memory/index.js +23 -12
  104. package/dist/redact/index.js +3 -3
  105. package/dist/smartlead/capabilities.d.ts +4 -0
  106. package/dist/smartlead/index.js +152 -38
  107. package/dist/smartlead/map-account.d.ts +3 -0
  108. package/dist/smartlead/stats-tracking.d.ts +22 -0
  109. package/dist/sync/index.js +2 -2
  110. package/dist/tools/ai-sdk.js +8 -7
  111. package/dist/tools/by-name.d.ts +18 -0
  112. package/dist/tools/campaign-tools.d.ts +6 -2
  113. package/dist/tools/claude-agent.js +8 -7
  114. package/dist/tools/index.js +9 -8
  115. package/dist/tools/shared.d.ts +7 -0
  116. package/dist/tracing/index.js +2 -2
  117. package/dist/webhooks/index.js +12 -11
  118. package/package.json +1 -1
  119. package/dist/chunks/chunk-HWHI4LFY.js +0 -102
@@ -1,30 +1,42 @@
1
1
  import {
2
- createTools
3
- } from "./chunk-BK5SLY32.js";
2
+ countReplies,
3
+ createTools,
4
+ describeReplyCounts,
5
+ repliesByPerson
6
+ } from "./chunk-JRL3QRBS.js";
4
7
  import {
5
- plural
8
+ resolveCampaign,
9
+ resolveList
10
+ } from "./chunk-4AVYRVN5.js";
11
+ import {
12
+ plural as plural2
6
13
  } from "./chunk-4PA526S7.js";
7
14
  import {
8
15
  createOutbound
9
- } from "./chunk-YYCT3NGV.js";
16
+ } from "./chunk-65YAGEWZ.js";
17
+ import {
18
+ plural
19
+ } from "./chunk-PTZO4QXR.js";
10
20
  import {
11
21
  campaignStatusSchema,
12
22
  replyCategorySchema
13
23
  } from "./chunk-QGRZDTX4.js";
14
24
  import {
15
25
  fromEnv
16
- } from "./chunk-UWUPUMM2.js";
26
+ } from "./chunk-MW4C6LTN.js";
17
27
  import {
18
28
  OutboundError
19
- } from "./chunk-J7DDZ4C2.js";
29
+ } from "./chunk-QFC4ZHD3.js";
20
30
  import {
21
31
  field,
32
+ isBoolean,
33
+ isJsonArray,
22
34
  isJsonObject,
23
35
  isNumber,
24
36
  isString,
25
37
  parseJson,
26
38
  toJson
27
- } from "./chunk-BLCJHP5H.js";
39
+ } from "./chunk-45TXPJW7.js";
28
40
  import {
29
41
  providers
30
42
  } from "./chunk-WH6V3YNN.js";
@@ -32,6 +44,230 @@ import {
32
44
  // src/cli/index.ts
33
45
  import { parseArgs } from "node:util";
34
46
 
47
+ // src/cli/by-name.ts
48
+ var campaignOption = (outbound, value) => value === void 0 ? Promise.resolve(void 0) : resolveCampaign(outbound, value);
49
+ var listOption = (outbound, value) => value === void 0 ? Promise.resolve(void 0) : resolveList(outbound, value);
50
+ var confirmScope = async (outbound, scope, found) => {
51
+ if (found > 0) {
52
+ return;
53
+ }
54
+ if (scope.campaignId !== void 0) {
55
+ await outbound.campaign(scope.campaignId).get();
56
+ }
57
+ if (scope.listId !== void 0 && outbound.capabilities["lists.get"]) {
58
+ await outbound.list(scope.listId).get();
59
+ }
60
+ };
61
+ var searchCampaigns = async (outbound, { max, note, search, status }) => {
62
+ const wanted = search.trim().toLowerCase();
63
+ const all = await outbound.campaigns.listAll({ status }).toArray();
64
+ const matches = all.filter(
65
+ (campaign) => campaign.name.toLowerCase().includes(wanted)
66
+ );
67
+ if (matches.length > max) {
68
+ note(
69
+ `Stopped at ${plural(max, "campaign")} of ${matches.length} that match. Pass --limit to read more.`
70
+ );
71
+ }
72
+ return matches.slice(0, max);
73
+ };
74
+
75
+ // src/cli/envelope.ts
76
+ var Answer = class {
77
+ value;
78
+ coverage;
79
+ /** `true` for a list, which the envelope puts in `data.items`. */
80
+ list;
81
+ constructor(value, coverage, list = false) {
82
+ this.value = value;
83
+ this.coverage = coverage;
84
+ this.list = list;
85
+ }
86
+ /** How many records a list holds; 0 for an answer that is not a list. */
87
+ get size() {
88
+ return this.list && isJsonArray(this.value) ? this.value.length : 0;
89
+ }
90
+ };
91
+ var valueOf = (printed) => printed instanceof Answer ? printed.value : printed;
92
+ var notesOf = (value) => isJsonArray(value) ? value.filter(isString) : [];
93
+ var isToolResult = (value) => isJsonObject(value) && isBoolean(value.ok) && isString(value.next) && ("data" in value || "error" in value);
94
+ var coverageOf = (printed) => {
95
+ if (printed instanceof Answer) {
96
+ return printed.coverage;
97
+ }
98
+ const meta = isJsonObject(printed) ? printed.meta : void 0;
99
+ const stated = isJsonObject(meta) ? meta.complete : void 0;
100
+ if (isBoolean(stated)) {
101
+ return { complete: stated, notes: notesOf(field(meta, "notes")) };
102
+ }
103
+ if (isToolResult(printed)) {
104
+ return { complete: false, notes: [] };
105
+ }
106
+ return { complete: true, notes: [] };
107
+ };
108
+ var sections = (entries) => {
109
+ const all = entries.map(([, printed]) => coverageOf(printed));
110
+ const complete = all.every((each) => each.complete);
111
+ return new Answer(
112
+ Object.fromEntries(
113
+ entries.map(([name, printed]) => [name, valueOf(printed)])
114
+ ),
115
+ { complete, notes: all.flatMap((each) => each.notes) }
116
+ );
117
+ };
118
+ var requestCounter = () => {
119
+ let sent = 0;
120
+ return {
121
+ hooks: {
122
+ onRequest: () => {
123
+ sent += 1;
124
+ }
125
+ },
126
+ name: "cli-request-count",
127
+ sent: () => sent
128
+ };
129
+ };
130
+ var WRAPPER_KEYS = /* @__PURE__ */ new Set(["data", "insight", "meta"]);
131
+ var isWrapper = (value) => "data" in value && "meta" in value && Object.keys(value).every((key) => WRAPPER_KEYS.has(key));
132
+ var withoutMeta = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => key !== "meta"));
133
+ var dataOf = (printed) => {
134
+ const value = valueOf(printed);
135
+ if (printed instanceof Answer && printed.list || isJsonArray(value)) {
136
+ return { items: value };
137
+ }
138
+ if (!isJsonObject(value)) {
139
+ return value;
140
+ }
141
+ if (isWrapper(value)) {
142
+ return value.data ?? null;
143
+ }
144
+ return withoutMeta(value);
145
+ };
146
+ var envelope = (printed, facts) => {
147
+ const value = valueOf(printed);
148
+ const { complete, notes } = coverageOf(printed);
149
+ const own = field(value, "meta");
150
+ const insight = field(value, "insight");
151
+ const meta = {
152
+ ...isJsonObject(own) ? own : void 0,
153
+ complete,
154
+ notes: [...notes],
155
+ provider: facts.provider ?? field(own, "provider") ?? null,
156
+ requests: facts.requests
157
+ };
158
+ if (isString(insight)) {
159
+ meta.insight = insight;
160
+ }
161
+ if (isToolResult(value)) {
162
+ const ok = value.ok === true;
163
+ const wrapped = {
164
+ data: ok ? value.data ?? null : null,
165
+ meta,
166
+ next: value.next ?? null,
167
+ ok
168
+ };
169
+ if (!ok) {
170
+ wrapped.error = value.error ?? null;
171
+ }
172
+ return wrapped;
173
+ }
174
+ return { data: dataOf(printed), meta, ok: true };
175
+ };
176
+ var failedEnvelope = (failure2, facts) => ({
177
+ data: null,
178
+ error: { code: failure2.code, message: failure2.message },
179
+ meta: {
180
+ complete: false,
181
+ notes: [],
182
+ provider: facts.provider,
183
+ requests: facts.requests
184
+ },
185
+ ok: false
186
+ });
187
+
188
+ // src/cli/listing.ts
189
+ var listed = async (walk, input, one, many) => {
190
+ const items = await walk.toArray();
191
+ if (!walk.truncated) {
192
+ return {
193
+ coverage: { complete: walk.meta?.complete ?? true, notes: [] },
194
+ items
195
+ };
196
+ }
197
+ const note = `Stopped at ${plural2(items.length, one, many)}; more exist. Pass --limit to read more.`;
198
+ input.note(note);
199
+ return { coverage: { complete: false, notes: [note] }, items };
200
+ };
201
+ var listing = async (walk, input, one, many) => {
202
+ const { coverage, items } = await listed(walk, input, one, many);
203
+ return new Answer(toJson(items), coverage, true);
204
+ };
205
+ var listedReplies = async (walk, input, byPerson) => {
206
+ const { coverage, items } = await listed(walk, input, "reply", "replies");
207
+ const counted = `${describeReplyCounts(countReplies(items))}.`;
208
+ input.note(counted);
209
+ return new Answer(
210
+ toJson(byPerson ? repliesByPerson(items) : items),
211
+ { ...coverage, notes: [...coverage.notes, counted] },
212
+ true
213
+ );
214
+ };
215
+
216
+ // src/cli/suggest.ts
217
+ var distance = (from, to) => {
218
+ const rows = Array.from(
219
+ { length: from.length + 1 },
220
+ (_row, row) => Array.from(
221
+ { length: to.length + 1 },
222
+ (_cell, column) => row === 0 || column === 0 ? row + column : 0
223
+ )
224
+ );
225
+ const at = (row, column) => rows[row]?.[column] ?? Infinity;
226
+ for (let row = 1; row <= from.length; row += 1) {
227
+ for (let column = 1; column <= to.length; column += 1) {
228
+ const cost = from[row - 1] === to[column - 1] ? 0 : 1;
229
+ const swapped = row > 1 && column > 1 && from[row - 1] === to[column - 2] && from[row - 2] === to[column - 1];
230
+ const best = Math.min(
231
+ at(row - 1, column) + 1,
232
+ at(row, column - 1) + 1,
233
+ at(row - 1, column - 1) + cost,
234
+ swapped ? at(row - 2, column - 2) + 1 : Infinity
235
+ );
236
+ const line = rows[row];
237
+ if (line !== void 0) {
238
+ line[column] = best;
239
+ }
240
+ }
241
+ }
242
+ return at(from.length, to.length);
243
+ };
244
+ var MAX_EDITS = 2;
245
+ var SHOWN = 3;
246
+ var closest = (typed, known) => [...new Set(known)].flatMap((word) => {
247
+ const edits = distance(typed, word);
248
+ return edits <= MAX_EDITS ? [{ edits, word }] : [];
249
+ }).toSorted((one, other) => one.edits - other.edits).slice(0, SHOWN).map(({ word }) => word);
250
+ var didYouMean = (typed, known, prefix = "") => {
251
+ const near = closest(typed, known).map((word) => `"${prefix}${word}"`);
252
+ return near.length === 0 ? "" : ` Did you mean ${near.join(" or ")}?`;
253
+ };
254
+
255
+ // src/cli/native.ts
256
+ var readNative = async (outbound, name, params) => {
257
+ const known = Object.keys(outbound.native.catalog);
258
+ if (outbound.capabilities.native && !known.includes(name)) {
259
+ throw new OutboundError(
260
+ "Invalid",
261
+ `${outbound.provider} has no native read "${name}".${didYouMean(name, known)} Run "outbound native" to list them`
262
+ );
263
+ }
264
+ const given = params();
265
+ if (!isJsonObject(given)) {
266
+ throw new OutboundError("Invalid", "--input must be a JSON object");
267
+ }
268
+ return toJson(await outbound.native.read(name, given));
269
+ };
270
+
35
271
  // src/cli/commands.ts
36
272
  var text = (input, name) => {
37
273
  const value = input.flags[name];
@@ -60,6 +296,7 @@ var choice = (input, name, allowed) => {
60
296
  return match;
61
297
  };
62
298
  var BY = ["day", "total"];
299
+ var REPLIES_BY = ["person"];
63
300
  var parseInput = (source) => {
64
301
  const parsed = source === void 0 ? {} : parseJson(source);
65
302
  if (parsed === void 0) {
@@ -83,15 +320,6 @@ var fieldExceptions = (outbound) => Object.fromEntries(
83
320
  return stated.length === 0 ? [] : [[record, Object.fromEntries(stated)]];
84
321
  })
85
322
  );
86
- var listing = async (walk, input, one, many) => {
87
- const items = await walk.toArray();
88
- if (walk.truncated) {
89
- input.note(
90
- `Stopped at ${plural(items.length, one, many)}; more exist. Pass --limit to read more.`
91
- );
92
- }
93
- return asJson(items);
94
- };
95
323
  var wantsCard = (input) => input.flags.slack === true || input.flags.card === true;
96
324
  var drawn = async (name, result2, input) => {
97
325
  if (!wantsCard(input)) {
@@ -99,12 +327,24 @@ var drawn = async (name, result2, input) => {
99
327
  }
100
328
  const { cardFor, toSlackMessage } = await import("../cards/index.js");
101
329
  const card = cardFor(name, result2);
102
- return asJson(input.flags.slack === true ? toSlackMessage(card) : card);
330
+ return new Answer(
331
+ asJson(input.flags.slack === true ? toSlackMessage(card) : card),
332
+ coverageOf(asJson(result2))
333
+ );
103
334
  };
104
335
  var offeredTools = async (outbound) => {
105
336
  const { insightTools } = await import("../insights/index.js");
106
337
  return createTools(outbound, { extra: insightTools(outbound) });
107
338
  };
339
+ var describeTool = (tool) => ({
340
+ description: tool.description,
341
+ name: tool.name,
342
+ parameters: tool.parameters
343
+ });
344
+ var requiresInput = (tool) => {
345
+ const { parameters } = tool;
346
+ return isJsonObject(parameters) && Array.isArray(parameters.required) && parameters.required.length > 0;
347
+ };
108
348
  var runInsight = async (outbound, input) => {
109
349
  const { insightTools, listInsights, runInsightByName } = await import("../insights/index.js");
110
350
  const [name] = input.positionals;
@@ -131,9 +371,10 @@ var checkFlags = (name, flags, given) => {
131
371
  (flag) => !GLOBAL_FLAGS.includes(flag) && !flags.includes(flag)
132
372
  );
133
373
  if (stray !== void 0) {
374
+ const hint = didYouMean(stray, [...flags, ...GLOBAL_FLAGS], "--");
134
375
  throw new OutboundError(
135
376
  "Invalid",
136
- `--${stray} is not an option of ${name}`
377
+ `--${stray} is not an option of ${name}${hint === "" ? "" : `.${hint}`}`
137
378
  );
138
379
  }
139
380
  };
@@ -159,9 +400,14 @@ var COMMAND_TABLE = {
159
400
  "subsequences",
160
401
  "to"
161
402
  ],
162
- help: "campaign <id> [--stats] [--sequence] [--subsequences] [--settings] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--by day|total]",
403
+ help: "campaign <id or name> [--stats] [--sequence] [--subsequences] [--settings] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--by day|total]",
163
404
  run: async (outbound, input) => {
164
- const campaign = outbound.campaign(required(input, 0, "a campaign id"));
405
+ const campaign = outbound.campaign(
406
+ await resolveCampaign(
407
+ outbound,
408
+ required(input, 0, "a campaign id or name")
409
+ )
410
+ );
165
411
  const by = choice(input, "by", BY);
166
412
  const read = {
167
413
  sequence: async () => asJson(await campaign.sequence()),
@@ -184,20 +430,28 @@ var COMMAND_TABLE = {
184
430
  const answers = await Promise.all(
185
431
  wanted.map(async (section) => [section, await read[section]()])
186
432
  );
187
- return answers.length === 1 ? answers[0]?.[1] ?? null : Object.fromEntries(answers);
433
+ return answers.length === 1 ? answers[0]?.[1] ?? null : sections(answers);
188
434
  }
189
435
  },
190
436
  campaigns: {
191
- flags: ["limit", "status"],
192
- help: "campaigns [--status active|paused|draft|completed|archived] [--limit N]",
193
- run: (outbound, input) => listing(
194
- outbound.campaigns.listAll({
437
+ flags: ["limit", "search", "status"],
438
+ help: "campaigns [--status active|paused|draft|completed|archived] [--search TEXT] [--limit N]",
439
+ run: (outbound, input) => {
440
+ const search = text(input, "search");
441
+ return search === void 0 ? listing(
442
+ outbound.campaigns.listAll({
443
+ max: count(input, "limit", 50),
444
+ status: choice(input, "status", campaignStatusSchema.options)
445
+ }),
446
+ input,
447
+ "campaign"
448
+ ) : searchCampaigns(outbound, {
195
449
  max: count(input, "limit", 50),
450
+ note: input.note,
451
+ search,
196
452
  status: choice(input, "status", campaignStatusSchema.options)
197
- }),
198
- input,
199
- "campaign"
200
- )
453
+ }).then(asJson);
454
+ }
201
455
  },
202
456
  capabilities: {
203
457
  flags: [],
@@ -223,16 +477,20 @@ var COMMAND_TABLE = {
223
477
  },
224
478
  leads: {
225
479
  flags: ["campaign", "limit", "list"],
226
- help: "leads [--campaign ID | --list ID] [--limit N]",
227
- run: (outbound, input) => listing(
228
- outbound.leads.listAll({
229
- campaignId: text(input, "campaign"),
230
- listId: text(input, "list"),
480
+ help: "leads [--campaign ID|NAME | --list ID|NAME] [--limit N]",
481
+ run: async (outbound, input) => {
482
+ const scope = {
483
+ campaignId: await campaignOption(outbound, text(input, "campaign")),
484
+ listId: await listOption(outbound, text(input, "list"))
485
+ };
486
+ const walk = outbound.leads.listAll({
487
+ ...scope,
231
488
  max: count(input, "limit", 50)
232
- }),
233
- input,
234
- "lead"
235
- )
489
+ });
490
+ const answer = await listing(walk, input, "lead");
491
+ await confirmScope(outbound, scope, answer.size);
492
+ return answer;
493
+ }
236
494
  },
237
495
  lists: {
238
496
  flags: ["limit"],
@@ -251,16 +509,9 @@ var COMMAND_TABLE = {
251
509
  native: {
252
510
  flags: ["input"],
253
511
  help: "native [name] [--input JSON] the vendor's own reads; no name lists them",
254
- run: async (outbound, input) => {
512
+ run: (outbound, input) => {
255
513
  const [name] = input.positionals;
256
- if (name === void 0) {
257
- return asJson(outbound.native.catalog);
258
- }
259
- const params = parseInput(text(input, "input"));
260
- if (!isJsonObject(params)) {
261
- throw new OutboundError("Invalid", "--input must be a JSON object");
262
- }
263
- return asJson(await outbound.native.read(name, params));
514
+ return name === void 0 ? Promise.resolve(asJson(outbound.native.catalog)) : readNative(outbound, name, () => parseInput(text(input, "input")));
264
515
  }
265
516
  },
266
517
  person: {
@@ -280,20 +531,19 @@ var COMMAND_TABLE = {
280
531
  })
281
532
  },
282
533
  replies: {
283
- flags: ["bodies", "campaign", "category", "limit", "since"],
284
- help: "replies [--campaign ID] [--category positive|negative|neutral|ooo|...] [--since ISO] [--limit N] [--bodies]",
285
- run: (outbound, input) => listing(
286
- outbound.replies.listAll({
287
- campaignId: text(input, "campaign"),
534
+ flags: ["bodies", "by", "campaign", "category", "limit", "since"],
535
+ help: "replies [--campaign ID|NAME] [--category positive|negative|neutral|ooo|...] [--since ISO] [--limit N] [--bodies] [--by person] one record per message; --by person gives one row per person",
536
+ run: async (outbound, input) => {
537
+ const by = choice(input, "by", REPLIES_BY);
538
+ const walk = outbound.replies.listAll({
539
+ campaignId: await campaignOption(outbound, text(input, "campaign")),
288
540
  category: choice(input, "category", replyCategorySchema.options),
289
541
  include: input.flags.bodies === true ? ["body"] : void 0,
290
542
  max: count(input, "limit", 50),
291
543
  since: text(input, "since")
292
- }),
293
- input,
294
- "reply",
295
- "replies"
296
- )
544
+ });
545
+ return listedReplies(walk, input, by === "person");
546
+ }
297
547
  },
298
548
  senders: {
299
549
  flags: ["limit"],
@@ -327,15 +577,29 @@ var COMMAND_TABLE = {
327
577
  thread: {
328
578
  flags: ["bodies"],
329
579
  help: "thread <id> [--bodies]",
330
- run: async (outbound, input) => asJson(
331
- await outbound.thread(required(input, 0, "a thread id")).messages({
580
+ run: async (outbound, input) => {
581
+ const id = required(input, 0, "a thread id");
582
+ const thread = await outbound.thread(id).messages({
332
583
  include: input.flags.bodies === true ? ["body"] : void 0
333
- })
334
- )
584
+ });
585
+ if (thread.items.length === 0) {
586
+ throw new OutboundError(
587
+ "NotFound",
588
+ `No thread ${id}, or it has no messages`
589
+ );
590
+ }
591
+ return new Answer(
592
+ asJson(thread.items),
593
+ coverageOf(
594
+ asJson({ meta: { ...thread.meta, complete: thread.complete } })
595
+ ),
596
+ true
597
+ );
598
+ }
335
599
  },
336
600
  tool: {
337
601
  flags: ["card", "input", "slack"],
338
- help: "tool <name> [--input JSON] [--card | --slack]",
602
+ help: "tool <name> [--input JSON] [--card | --slack] without --input, a tool that needs input prints what it takes",
339
603
  run: async (outbound, input) => {
340
604
  const name = required(input, 0, "a tool name");
341
605
  const offered = await offeredTools(outbound);
@@ -343,14 +607,17 @@ var COMMAND_TABLE = {
343
607
  if (tool === void 0) {
344
608
  throw new OutboundError(
345
609
  "Invalid",
346
- `Unknown tool "${name}". Run "outbound tools" to list them`
610
+ `Unknown tool "${name}".${didYouMean(
611
+ name,
612
+ offered.map((each) => each.name)
613
+ )} Run "outbound tools" to list them`
347
614
  );
348
615
  }
349
- return drawn(
350
- name,
351
- await tool.call(parseInput(text(input, "input"))),
352
- input
353
- );
616
+ const given = text(input, "input");
617
+ if (given === void 0 && requiresInput(tool)) {
618
+ return describeTool(tool);
619
+ }
620
+ return drawn(name, await tool.call(parseInput(given)), input);
354
621
  }
355
622
  },
356
623
  tools: {
@@ -358,18 +625,15 @@ var COMMAND_TABLE = {
358
625
  help: "tools",
359
626
  run: async (outbound) => {
360
627
  const offered = await offeredTools(outbound);
361
- return offered.map((tool) => ({
362
- description: tool.description,
363
- name: tool.name
364
- }));
628
+ return offered.map(describeTool);
365
629
  }
366
630
  },
367
631
  webhooks: {
368
632
  flags: ["campaign", "limit"],
369
- help: "webhooks [--campaign ID] [--limit N]",
370
- run: (outbound, input) => listing(
633
+ help: "webhooks [--campaign ID|NAME] [--limit N]",
634
+ run: async (outbound, input) => listing(
371
635
  outbound.webhooks.listAll({
372
- campaignId: text(input, "campaign"),
636
+ campaignId: await campaignOption(outbound, text(input, "campaign")),
373
637
  max: count(input, "limit", 50)
374
638
  }),
375
639
  input,
@@ -399,7 +663,7 @@ var GLOBAL_HELP = [
399
663
  " --config <file> load plugins from a file whose default export is defineConfig({ plugins })",
400
664
  " --redact mask personal fields (on by default for mcp)",
401
665
  " --no-redact do not mask personal fields, even for mcp",
402
- " --cache <seconds> reuse an answer for this long",
666
+ " --cache <seconds> reuse an answer for this long, within this process (for mcp; use a config-file store to persist)",
403
667
  " --max-requests <n> the most vendor requests one command, or one MCP tool call, may make",
404
668
  "",
405
669
  "Each adapter reads its own key from the environment, for example INSTANTLY_API_KEY."
@@ -480,7 +744,7 @@ var wantsRedact = (flags, fromConfig, mcp) => {
480
744
  }
481
745
  return !fromConfig && (flags.redact === true || mcp);
482
746
  };
483
- var pluginsFor = async (flags, mcp) => {
747
+ var pluginsFor = async (flags, mcp, note) => {
484
748
  const configured = flags.config === void 0 ? [] : await loadConfig(flags.config);
485
749
  const fromConfig = configured.some((plugin) => plugin.name === "redact");
486
750
  const plugins = [];
@@ -493,6 +757,11 @@ var pluginsFor = async (flags, mcp) => {
493
757
  const ttl = positiveInteger("cache", flags.cache);
494
758
  const { cache } = await import("../cache/index.js");
495
759
  plugins.push(cache({ ttl }));
760
+ if (!mcp) {
761
+ note(
762
+ "--cache lasts one process, so the next run reads from the vendor again. It helps outbound mcp; to persist, list cache({ ttl, store }) in a --config file."
763
+ );
764
+ }
496
765
  }
497
766
  if (flags["max-requests"] !== void 0) {
498
767
  const maxRequests = positiveInteger("max-requests", flags["max-requests"]);
@@ -525,6 +794,17 @@ var describePlugins = (outbound) => {
525
794
  const masked = names.includes("redact") ? ` redact masks personal fields such as emails and names${outbound.capabilities["messages.body"] ? "" : ", and reply text is not available"}.` : " Personal fields such as emails and names are not masked.";
526
795
  return `Plugins on: ${names.join(", ")}.${masked}`;
527
796
  };
797
+ var describeLeftOut = (outbound, leftOut) => {
798
+ const names = Object.keys(leftOut ?? {});
799
+ if (names.length === 0) {
800
+ return "";
801
+ }
802
+ if (!outbound.plugins.some((plugin) => plugin.name === "redact")) {
803
+ return ` Left out of this server: ${names.join(", ")}. A call to one returns the reason.`;
804
+ }
805
+ const native = names.includes("vendor_read") ? " (vendor_read returns unmasked vendor payloads)" : "";
806
+ return ` Left out while redact is on: ${names.join(", ")}. They match people by email or LinkedIn profile, which redact masks${native}. Start the server with --no-redact to offer them; personal fields are then not masked.`;
807
+ };
528
808
  var hasRequestBudget = (value) => "requestBudget" in value && typeof value.requestBudget === "object" && value.requestBudget !== null && "reset" in value.requestBudget && typeof value.requestBudget.reset === "function";
529
809
  var budgetOf = (outbound) => hasRequestBudget(outbound) ? outbound.requestBudget : void 0;
530
810
  var result = (id, value) => ({
@@ -544,7 +824,7 @@ var idOf = (message) => {
544
824
  var createMcpServer = (outbound, options = {}) => {
545
825
  const tools = createTools(outbound, options);
546
826
  const byName = new Map(tools.map((tool) => [tool.name, tool]));
547
- const instructions = `${INSTRUCTIONS} ${describePlugins(outbound)}`;
827
+ const instructions = `${INSTRUCTIONS} ${describePlugins(outbound)}${describeLeftOut(outbound, options.leftOut)}`;
548
828
  const budget = budgetOf(outbound);
549
829
  const initialize = (id, params) => {
550
830
  const requested = field(params, "protocolVersion");
@@ -628,6 +908,38 @@ var createMcpServer = (outbound, options = {}) => {
628
908
  };
629
909
  };
630
910
 
911
+ // src/cli/options.ts
912
+ var OPTIONS = {
913
+ bodies: { type: "boolean" },
914
+ by: { type: "string" },
915
+ cache: { type: "string" },
916
+ campaign: { type: "string" },
917
+ card: { type: "boolean" },
918
+ category: { type: "string" },
919
+ compact: { type: "boolean" },
920
+ config: { type: "string" },
921
+ from: { type: "string" },
922
+ help: { short: "h", type: "boolean" },
923
+ input: { type: "string" },
924
+ limit: { type: "string" },
925
+ list: { type: "string" },
926
+ "max-requests": { type: "string" },
927
+ "no-redact": { type: "boolean" },
928
+ provider: { type: "string" },
929
+ raw: { type: "boolean" },
930
+ redact: { type: "boolean" },
931
+ search: { type: "string" },
932
+ sequence: { type: "boolean" },
933
+ settings: { type: "boolean" },
934
+ since: { type: "string" },
935
+ slack: { type: "boolean" },
936
+ stats: { type: "boolean" },
937
+ status: { type: "string" },
938
+ subsequences: { type: "boolean" },
939
+ to: { type: "string" },
940
+ version: { short: "v", type: "boolean" }
941
+ };
942
+
631
943
  // src/cli/output.ts
632
944
  var isRecord = (value) => isJsonObject(value) && "ref" in value && "schemaVersion" in value;
633
945
  var withoutRaw = (value) => {
@@ -641,12 +953,27 @@ var withoutRaw = (value) => {
641
953
  Object.entries(value).filter(([key]) => !(key === "raw" && isRecord(value))).map(([key, item]) => [key, withoutRaw(item)])
642
954
  );
643
955
  };
644
- var printAnswer = (write, value, options) => {
956
+ var printJson = (write, value, options) => {
645
957
  const shown = options.raw === true ? value : withoutRaw(value);
646
958
  write(
647
959
  options.compact === true ? JSON.stringify(shown) : JSON.stringify(shown, null, 2)
648
960
  );
649
961
  };
962
+ var printAnswer = (write, printed, options, facts) => {
963
+ printJson(write, envelope(printed, facts), options);
964
+ };
965
+ var TEXT_COMMANDS = /* @__PURE__ */ new Set([
966
+ "mcp",
967
+ "update",
968
+ "version"
969
+ ]);
970
+ var printFailure = (write, run2, failure2, facts) => {
971
+ if (!TEXT_COMMANDS.has(run2.name ?? "")) {
972
+ printJson(write, failedEnvelope(failure2, facts), {
973
+ compact: run2.argv.includes("--compact")
974
+ });
975
+ }
976
+ };
650
977
 
651
978
  // src/cli/stdio.ts
652
979
  import process from "node:process";
@@ -669,6 +996,7 @@ var serveStdio = async (server, options = {}) => {
669
996
  import { execFile } from "node:child_process";
670
997
  import path2 from "node:path";
671
998
  import process2 from "node:process";
999
+ import { setTimeout as setTimeoutPromise } from "node:timers/promises";
672
1000
  import { fileURLToPath } from "node:url";
673
1001
  import { promisify } from "node:util";
674
1002
 
@@ -694,6 +1022,28 @@ var STANDALONE = /* @__PURE__ */ new Map([
694
1022
  ["version", ["version"]]
695
1023
  ]);
696
1024
  var execFileAsync = promisify(execFile);
1025
+ var NpmFailedError = class extends Error {
1026
+ code;
1027
+ constructor(message, code, cause) {
1028
+ super(message, { cause });
1029
+ this.name = "NpmFailedError";
1030
+ this.code = code;
1031
+ }
1032
+ };
1033
+ var NPM_LINE = /^npm (?:error|ERR!) ?(?<said>.*)$/u;
1034
+ var NPM_CODE = /^code (?<code>E[A-Z0-9]+)$/u;
1035
+ var NPM_DETAIL = /^(?:code|syscall|path|errno|signal|cmd|cwd|command) /u;
1036
+ var npmReason = (stderr) => {
1037
+ const lines = stderr.split("\n").map((line) => NPM_LINE.exec(line.trim())?.groups?.said?.trim() ?? "").filter((line) => line !== "" && !line.startsWith("A complete log"));
1038
+ const code = lines.map((line) => NPM_CODE.exec(line)?.groups?.code).find((found) => found !== void 0);
1039
+ const tags = /* @__PURE__ */ new Set(["notarget", code?.toLowerCase()]);
1040
+ const untag = (line) => {
1041
+ const [first = "", ...rest] = line.split(" ");
1042
+ return /^\d{3}$/u.test(first) || tags.has(first) ? rest.join(" ").trim() : line;
1043
+ };
1044
+ const said = lines.filter((line) => !NPM_DETAIL.test(line)).map(untag).find((line) => line !== "") ?? stderr.trim().split("\n").at(-1) ?? "";
1045
+ return { code, said };
1046
+ };
697
1047
  var runNpm = async (args) => {
698
1048
  try {
699
1049
  const { stdout } = await execFileAsync("npm", [...args], {
@@ -702,13 +1052,44 @@ var runNpm = async (args) => {
702
1052
  return stdout;
703
1053
  } catch (error) {
704
1054
  const stderr = error instanceof Error && "stderr" in error ? String(error.stderr) : "";
705
- const said = stderr.trim().split("\n").at(-1) ?? "";
706
- throw new Error(
707
- `npm ${args.join(" ")} failed${said === "" ? "" : `: ${said}`}`,
708
- { cause: error }
1055
+ const { code, said } = npmReason(stderr);
1056
+ const label = code === void 0 ? "" : ` (${code})`;
1057
+ throw new NpmFailedError(
1058
+ `npm ${args.join(" ")} failed${label}${said === "" ? "" : `: ${said}`}`,
1059
+ code,
1060
+ error
709
1061
  );
710
1062
  }
711
1063
  };
1064
+ var sleep = async (ms) => {
1065
+ await setTimeoutPromise(ms);
1066
+ };
1067
+ var NOT_YET_SERVED = /* @__PURE__ */ new Set(["E404", "ETARGET"]);
1068
+ var RETRY_EVERY_MS = 3e4;
1069
+ var RETRY_FOR_MS = 15 * 6e4;
1070
+ var installGlobal = async (npm, say, wait, version) => {
1071
+ const target = `${PACKAGE}@${version}`;
1072
+ const tries = RETRY_FOR_MS / RETRY_EVERY_MS;
1073
+ for (let attempt = 1; ; attempt += 1) {
1074
+ try {
1075
+ await npm(
1076
+ attempt === 1 ? ["install", "--global", target] : ["install", "--global", "--prefer-online", target]
1077
+ );
1078
+ return;
1079
+ } catch (error) {
1080
+ const code = error instanceof NpmFailedError ? error.code : void 0;
1081
+ if (code === void 0 || !NOT_YET_SERVED.has(code) || attempt > tries) {
1082
+ throw error;
1083
+ }
1084
+ if (attempt === 1) {
1085
+ say(
1086
+ `npm lists ${version} but is not serving it yet, which happens for a few minutes after a release. Trying again every ${RETRY_EVERY_MS / 1e3} seconds for up to ${RETRY_FOR_MS / 6e4} minutes; Ctrl-C stops.`
1087
+ );
1088
+ }
1089
+ await wait(RETRY_EVERY_MS);
1090
+ }
1091
+ }
1092
+ };
712
1093
  var packageDir = () => path2.dirname(fileURLToPath(new URL("../../package.json", import.meta.url)));
713
1094
  var parts = (version) => version.split("-")[0]?.split(".").map((part) => Math.trunc(Number(part)) || 0) ?? [];
714
1095
  var older = (a, b) => {
@@ -729,7 +1110,7 @@ var installKind = async (npm, dir) => {
729
1110
  const globalRoot = printed.trim();
730
1111
  return globalRoot !== "" && path2.dirname(dir) === path2.resolve(globalRoot) ? "global" : "project";
731
1112
  };
732
- var update = async (npm, say) => {
1113
+ var update = async (npm, say, wait = sleep) => {
733
1114
  const installed = packageVersion();
734
1115
  const viewed = await npm(["view", PACKAGE, "version"]);
735
1116
  const latest = viewed.trim();
@@ -747,52 +1128,23 @@ var update = async (npm, say) => {
747
1128
  say(`Run "npm install ${PACKAGE}@latest" in this project to update it.`);
748
1129
  return;
749
1130
  }
750
- say(`Running "npm install --global ${PACKAGE}@latest"...`);
751
- await npm(["install", "--global", `${PACKAGE}@latest`]);
1131
+ say(`Running "npm install --global ${PACKAGE}@${latest}"...`);
1132
+ await installGlobal(npm, say, wait, latest);
752
1133
  say(`Updated ${PACKAGE} to ${latest}.`);
753
1134
  };
754
- var runSelf = async (name, flags, npm, say) => {
1135
+ var runSelf = async (name, flags, npm, say, wait = sleep) => {
755
1136
  if (name === "version" || name === void 0 && flags.version === true) {
756
1137
  say(packageVersion());
757
1138
  return true;
758
1139
  }
759
1140
  if (name === "update" && flags.help !== true) {
760
- await update(npm, say);
1141
+ await update(npm, say, wait);
761
1142
  return true;
762
1143
  }
763
1144
  return false;
764
1145
  };
765
1146
 
766
1147
  // src/cli/index.ts
767
- var OPTIONS = {
768
- bodies: { type: "boolean" },
769
- by: { type: "string" },
770
- cache: { type: "string" },
771
- campaign: { type: "string" },
772
- card: { type: "boolean" },
773
- category: { type: "string" },
774
- compact: { type: "boolean" },
775
- config: { type: "string" },
776
- from: { type: "string" },
777
- help: { short: "h", type: "boolean" },
778
- input: { type: "string" },
779
- limit: { type: "string" },
780
- list: { type: "string" },
781
- "max-requests": { type: "string" },
782
- "no-redact": { type: "boolean" },
783
- provider: { type: "string" },
784
- raw: { type: "boolean" },
785
- redact: { type: "boolean" },
786
- sequence: { type: "boolean" },
787
- settings: { type: "boolean" },
788
- since: { type: "string" },
789
- slack: { type: "boolean" },
790
- stats: { type: "boolean" },
791
- status: { type: "string" },
792
- subsequences: { type: "boolean" },
793
- to: { type: "string" },
794
- version: { short: "v", type: "boolean" }
795
- };
796
1148
  var serve = async (outbound, io, unmasked) => {
797
1149
  const { insightTools } = await import("../insights/index.js");
798
1150
  const offered = (instance) => createTools(instance, { extra: insightTools(instance) }).map(
@@ -834,7 +1186,7 @@ var parse = (argv) => {
834
1186
  if (named && !command && !STANDALONE.has(name)) {
835
1187
  throw new OutboundError(
836
1188
  "Invalid",
837
- `Unknown command "${name}". Run "outbound help"`
1189
+ `Unknown command "${name}".${didYouMean(name, [...COMMANDS.keys(), ...STANDALONE.keys(), "help", "providers"])} Run "outbound help"`
838
1190
  );
839
1191
  }
840
1192
  if (named) {
@@ -855,9 +1207,14 @@ var parse = (argv) => {
855
1207
  };
856
1208
  };
857
1209
  var run = async (argv, io) => {
1210
+ const counter = requestCounter();
1211
+ let provider = null;
1212
+ const facts = () => ({ provider, requests: counter.sent() });
1213
+ let named;
858
1214
  try {
859
1215
  const { help, name, rest, values } = parse(argv);
860
- if (await runSelf(name, values, io.npm ?? runNpm, io.stdout)) {
1216
+ named = name;
1217
+ if (await runSelf(name, values, io.npm ?? runNpm, io.stdout, io.sleep)) {
861
1218
  return 0;
862
1219
  }
863
1220
  if (help !== void 0) {
@@ -865,13 +1222,17 @@ var run = async (argv, io) => {
865
1222
  return 0;
866
1223
  }
867
1224
  if (name === "providers") {
868
- printAnswer(io.stdout, listProviders(), values);
1225
+ printAnswer(io.stdout, listProviders(), values, facts());
869
1226
  return 0;
870
1227
  }
871
1228
  const command = name === void 0 ? void 0 : COMMANDS.get(name);
872
1229
  const adapter = io.adapter ?? await fromEnv({ provider: values.provider });
873
- const plugins = await pluginsFor(values, command === void 0);
874
- const outbound = createOutbound({ adapter, plugins });
1230
+ const plugins = await pluginsFor(values, command === void 0, io.stderr);
1231
+ if (command !== void 0) {
1232
+ plugins.push(counter);
1233
+ }
1234
+ const outbound = createOutbound({ adapter, fetch: io.fetch, plugins });
1235
+ ({ provider } = outbound);
875
1236
  if (command === void 0) {
876
1237
  const unmasked = plugins.some((plugin) => plugin.name === "redact") ? createOutbound({
877
1238
  adapter,
@@ -885,13 +1246,13 @@ var run = async (argv, io) => {
885
1246
  note: io.stderr,
886
1247
  positionals: rest
887
1248
  });
888
- printAnswer(io.stdout, answer, values);
889
- return name === "tool" && field(answer, "ok") === false ? 1 : 0;
1249
+ printAnswer(io.stdout, answer, values, facts());
1250
+ return name === "tool" && field(valueOf(answer), "ok") === false ? 1 : 0;
890
1251
  } catch (error) {
891
1252
  const code = OutboundError.is(error) ? error.code : "Error";
892
- io.stderr(
893
- `${code}: ${error instanceof Error ? error.message : String(error)}`
894
- );
1253
+ const message = error instanceof Error ? error.message : String(error);
1254
+ printFailure(io.stdout, { argv, name: named }, { code, message }, facts());
1255
+ io.stderr(`${code}: ${message}`);
895
1256
  return 1;
896
1257
  }
897
1258
  };