outbound-sdk 0.11.0 → 0.13.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 (105) hide show
  1. package/dist/alerts/index.js +1 -1
  2. package/dist/budget/index.js +1 -1
  3. package/dist/cards/index.js +217 -100
  4. package/dist/cards/sender-tool-cards.d.ts +6 -0
  5. package/dist/chunks/{chunk-UAHYPASH.js → chunk-3LRIWQEJ.js} +2 -1
  6. package/dist/chunks/{chunk-UZLFZZ2U.js → chunk-6BSFR5SF.js} +14 -2
  7. package/dist/chunks/{chunk-FTK4JS65.js → chunk-BTIJ24UY.js} +89 -9
  8. package/dist/chunks/{chunk-OVTYA3IB.js → chunk-EAG5NIPM.js} +614 -206
  9. package/dist/chunks/{chunk-A7DLJUA6.js → chunk-FT6HMMMP.js} +3 -1
  10. package/dist/chunks/chunk-I7GBBHD2.js +80 -0
  11. package/dist/chunks/{chunk-UOJG4VYF.js → chunk-LD5OAELW.js} +1 -1
  12. package/dist/chunks/{chunk-KMQHXFIZ.js → chunk-LJNU4LAR.js} +2094 -1014
  13. package/dist/chunks/{chunk-POBAY3TI.js → chunk-NLYGMVXS.js} +30 -0
  14. package/dist/chunks/{chunk-V7JKTNRO.js → chunk-OE45PREW.js} +1 -1
  15. package/dist/chunks/{chunk-MEEJIIIA.js → chunk-OP2GL7ZT.js} +77 -8
  16. package/dist/chunks/{chunk-YFJ3OQZS.js → chunk-OPLXELPS.js} +5 -1
  17. package/dist/chunks/{chunk-CVLGFVDC.js → chunk-PDYE6CWS.js} +136 -64
  18. package/dist/chunks/{chunk-OMCDMELK.js → chunk-PUIHJFK4.js} +1 -1
  19. package/dist/chunks/{chunk-MPE6VLLY.js → chunk-UZ4YWUZ7.js} +1 -1
  20. package/dist/chunks/{tools-AVJ3XJ5A.js → tools-VCCH3JNL.js} +13 -6
  21. package/dist/cli/bin.js +11 -10
  22. package/dist/cli/config.d.ts +0 -2
  23. package/dist/cli/index.js +10 -9
  24. package/dist/cli/offered.d.ts +31 -2
  25. package/dist/cli/serve.d.ts +4 -2
  26. package/dist/combine/index.js +60 -4
  27. package/dist/emailbison/index.js +4 -4
  28. package/dist/fixtures/index.js +4 -4
  29. package/dist/heyreach/index.js +17 -6
  30. package/dist/identity/index.js +46 -11
  31. package/dist/identity/keys.d.ts +1 -1
  32. package/dist/index.js +8 -6
  33. package/dist/insights/capped.d.ts +14 -1
  34. package/dist/insights/define.d.ts +8 -6
  35. package/dist/insights/index.d.ts +1 -1
  36. package/dist/insights/index.js +12 -61
  37. package/dist/insights/inputs.generated.d.ts +91 -16
  38. package/dist/insights/ops/campaign-ranking.d.ts +8 -1
  39. package/dist/insights/ops/channel-mix.d.ts +8 -1
  40. package/dist/insights/ops/client-report.d.ts +28 -18
  41. package/dist/insights/ops/client-runway.d.ts +43 -0
  42. package/dist/insights/ops/index.d.ts +6 -1
  43. package/dist/insights/ops/period-comparison.d.ts +35 -2
  44. package/dist/insights/ops/pipeline-forecast.d.ts +14 -9
  45. package/dist/insights/ops/shared.d.ts +49 -2
  46. package/dist/insights/ops/tag-rollup.d.ts +8 -1
  47. package/dist/insights/people/coverage.d.ts +26 -0
  48. package/dist/insights/people/dropped-replies-check.d.ts +19 -3
  49. package/dist/insights/people/dropped-replies.d.ts +6 -2
  50. package/dist/insights/people/find.d.ts +5 -4
  51. package/dist/insights/people/hot-leads.d.ts +10 -1
  52. package/dist/insights/people/index.d.ts +26 -2
  53. package/dist/insights/people/lead-collisions.d.ts +18 -1
  54. package/dist/insights/people/person-summary.d.ts +15 -3
  55. package/dist/insights/people/suppression-check.d.ts +18 -1
  56. package/dist/insights/people/thread-context.d.ts +79 -0
  57. package/dist/insights/people/thread-contexts.d.ts +59 -0
  58. package/dist/insights/people/thread-read.d.ts +33 -0
  59. package/dist/insights/registry.d.ts +29 -3
  60. package/dist/insights/senders/domain-health.d.ts +1 -1
  61. package/dist/insights/senders/index.d.ts +1 -1
  62. package/dist/insights/senders/read.d.ts +9 -0
  63. package/dist/insights/tools.d.ts +35 -2
  64. package/dist/instantly/adapter.d.ts +3 -2
  65. package/dist/instantly/capabilities.d.ts +5 -0
  66. package/dist/instantly/index.js +255 -66
  67. package/dist/instantly/lead-ids.d.ts +11 -0
  68. package/dist/instantly/map-lead.d.ts +19 -2
  69. package/dist/instantly/senders.d.ts +3 -0
  70. package/dist/internal/adapter.d.ts +7 -0
  71. package/dist/internal/capabilities.d.ts +8 -0
  72. package/dist/internal/entities.d.ts +24 -1
  73. package/dist/internal/fields.d.ts +10 -0
  74. package/dist/internal/outbound/api.d.ts +12 -0
  75. package/dist/internal/outbound/operations-account.d.ts +4 -1
  76. package/dist/internal/outbound/outbound.d.ts +2 -1
  77. package/dist/internal/outbound/specs-account.d.ts +2 -1
  78. package/dist/internal/person.d.ts +32 -0
  79. package/dist/internal/records.d.ts +2 -2
  80. package/dist/internal/reply-people.d.ts +25 -7
  81. package/dist/internal/runway.d.ts +38 -5
  82. package/dist/internal/url.d.ts +2 -1
  83. package/dist/loader/index.js +1 -1
  84. package/dist/memory/data.d.ts +2 -1
  85. package/dist/memory/index.js +6 -4
  86. package/dist/redact/index.d.ts +1 -1
  87. package/dist/redact/index.js +62 -31
  88. package/dist/redact/plugin.d.ts +13 -11
  89. package/dist/redact/tokens.d.ts +18 -1
  90. package/dist/smartlead/index.js +21 -7
  91. package/dist/tools/account-tools.d.ts +0 -5
  92. package/dist/tools/ai-sdk.js +5 -3
  93. package/dist/tools/campaign-tools.d.ts +0 -4
  94. package/dist/tools/claude-agent.js +5 -3
  95. package/dist/tools/deliverability-check.d.ts +9 -0
  96. package/dist/tools/index.js +6 -4
  97. package/dist/tools/people-tools.d.ts +4 -1
  98. package/dist/tools/person-input.d.ts +17 -0
  99. package/dist/tools/registry.d.ts +8 -1
  100. package/dist/tools/sender-health.d.ts +8 -0
  101. package/dist/tools/sender-impact.d.ts +38 -0
  102. package/dist/tools/shared.d.ts +5 -0
  103. package/dist/webhooks/index.js +6 -6
  104. package/package.json +1 -1
  105. /package/dist/chunks/{chunk-5XLR6XVV.js → chunk-HNYJO6B4.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  EVENT_TYPES,
3
3
  instantlyEvents
4
- } from "../chunks/chunk-MPE6VLLY.js";
4
+ } from "../chunks/chunk-UZ4YWUZ7.js";
5
5
  import {
6
6
  applyTracking,
7
7
  ownTracking,
@@ -24,7 +24,7 @@ import {
24
24
  listIn,
25
25
  toVariant,
26
26
  variantKey
27
- } from "../chunks/chunk-UOJG4VYF.js";
27
+ } from "../chunks/chunk-LD5OAELW.js";
28
28
  import {
29
29
  normalizeBody
30
30
  } from "../chunks/chunk-FALWG5U3.js";
@@ -42,17 +42,17 @@ import {
42
42
  refTo,
43
43
  refsTo
44
44
  } from "../chunks/chunk-U5AK6OJM.js";
45
- import "../chunks/chunk-POBAY3TI.js";
45
+ import "../chunks/chunk-NLYGMVXS.js";
46
46
  import {
47
47
  emptyCounts,
48
48
  metricRow,
49
49
  sumCounts
50
50
  } from "../chunks/chunk-CPACP4YD.js";
51
51
  import "../chunks/chunk-QGRZDTX4.js";
52
+ import "../chunks/chunk-OPLXELPS.js";
52
53
  import {
53
54
  assertWorkspaceId
54
55
  } from "../chunks/chunk-HXB2IOJJ.js";
55
- import "../chunks/chunk-YFJ3OQZS.js";
56
56
  import "../chunks/chunk-KVAG5GM2.js";
57
57
  import {
58
58
  readEnv,
@@ -501,6 +501,7 @@ var capabilities = {
501
501
  "senders.byCampaign": true,
502
502
  "senders.get": true,
503
503
  "senders.health": true,
504
+ "senders.healthList": true,
504
505
  "senders.list": true,
505
506
  "senders.warmup": true,
506
507
  sequence: true,
@@ -508,6 +509,8 @@ var capabilities = {
508
509
  "stats.byDay": "exact",
509
510
  // Per-mailbox numbers exist by day only; a total is summed by the adapter.
510
511
  "stats.bySender": "derived",
512
+ // GET /accounts/analytics/daily names up to 200 mailboxes in one read.
513
+ "stats.bySenders": "derived",
511
514
  "stats.byStep": "exact",
512
515
  // GET /campaigns/analytics with no id: a row per campaign, totals only.
513
516
  // Partial: it has no count of interested leads and no total of opens.
@@ -537,8 +540,9 @@ var fields = {
537
540
  tags: false
538
541
  },
539
542
  // No email carried is_auto_reply live: a fixed rule decides, and in a
540
- // timeline the step comes from the send a reply answers.
541
- message: { isAuto: "derived", isAutoSource: "derived" },
543
+ // timeline the step comes from the send a reply answers. The Unibox link is
544
+ // built from the thread and workspace, as Instantly's own unibox_url is.
545
+ message: { isAuto: "derived", isAutoSource: "derived", url: "derived" },
542
546
  metricRow: {
543
547
  connectionsAccepted: false,
544
548
  connectionsSent: false,
@@ -549,7 +553,12 @@ var fields = {
549
553
  },
550
554
  // A test has a creation time and a next run, and no start or end date.
551
555
  placementTest: { endsAt: false, startsAt: false },
552
- reply: { isAuto: "derived", isAutoSource: "derived", leftCompany: "derived" },
556
+ reply: {
557
+ isAuto: "derived",
558
+ isAutoSource: "derived",
559
+ leftCompany: "derived",
560
+ url: "derived"
561
+ },
553
562
  sender: { linkedinUrl: false },
554
563
  senderHealth: { blacklisted: false, checkedAt: false }
555
564
  };
@@ -596,6 +605,10 @@ var costs = {
596
605
  "senders.get": { perPage: 1 },
597
606
  // The account, its DNS test, then its warmup analytics.
598
607
  "senders.health": { perPage: 3 },
608
+ // Every mailbox's health: a page of accounts, one DNS test for the page's
609
+ // domains and one warmup report for its mailboxes. A campaign's page reads
610
+ // the campaign again first.
611
+ "senders.healthList": { pageSize: PAGE_SIZE, perPage: 3, perPageAtMost: 4 },
599
612
  // A campaign's senders: the campaign again with each page of every mailbox,
600
613
  // kept when the campaign names it (see the caveats). Pages follow the
601
614
  // workspace's mailboxes, not the senders kept.
@@ -617,7 +630,7 @@ var caveats = [
617
630
  "A lead's progress is its status when that is 1 (active), 2 (paused) or 3 (completed). Status -1 is bounced and -2 unsubscribed: they say what came back, so progress is then unknown. replied is email_reply_count above 0, and a lead that replied has the status replied whatever its progress.",
618
631
  "A placement test's kind reads type 1 as a one-time test and 2 as an automated one: the reference names the two kinds in that order and gives the numbers no names. A test's results stay native, because Instantly reports them as one row per test email.",
619
632
  "Instantly sends next_starting_after on a last page too (seen live), and the page after it is empty. A listing therefore ends one request late; the small lookups for tags and labels stop at the first page that is not full.",
620
- `A reply's category is read from the email's i_status using the lead interest status values (seen live: 0, 1, -1 and -2). An email names its lead by address (lead_id was absent live), so a message's or reply's leadRef holds the lead's lowercased address, from lead or, on a received email, from_address_email. leads.get and leads.timeline take that ref; leads.get then returns the first record with the address, one of several when the person is in several campaigns. No live email carried the documented is_auto_reply and the email list cannot filter by it, so when it is missing isAuto is decided by a fixed rule (isAutoSource rule): a machine sender address (noreply, auto-responder, mailer-daemon), an automatic subject (OOO, Out of Office, Automatic reply, "is no longer at"), a canned autoresponder phrase in the body, or, in a timeline or thread, a reply within a minute of the send it answers. An Out of Office i_status counts as the vendor saying so. leftCompany is true when the reply says the person left or the contact changed. In a timeline or thread a received email takes its stepIndex from the send it answers, since its own step lags on the last step.`,
633
+ `A reply's category is read from the email's i_status using the lead interest status values (seen live: 0, 1, -1 and -2). An email names its lead by address only (lead_id was absent live), so each page of emails looks up its leads' ids with one POST /leads/list per 100 addresses, matched by campaign (OUT-149): a message's or reply's leadRef is then the same ref leads.list returns, null when no lead has the address (a deleted lead), and leadEmail holds the lowercased address, from lead or, on a received email, from_address_email. The lookup is one request per page on the default lane. A ref made before that, holding an address, still reads leads.get and leads.timeline; leads.get then returns the first record with the address. No live email carried the documented is_auto_reply and the email list cannot filter by it, so when it is missing isAuto is decided by a fixed rule (isAutoSource rule): a machine sender address (noreply, auto-responder, mailer-daemon), an automatic subject (OOO, Out of Office, Automatic reply, "is no longer at"), a canned autoresponder phrase in the body, or, in a timeline or thread, a reply within a minute of the send it answers. An Out of Office i_status counts as the vendor saying so. leftCompany is true when the reply says the person left or the contact changed. In a timeline or thread a received email takes its stepIndex from the send it answers, since its own step lags on the last step.`,
621
634
  "Messages sent by hand (byHand) are read with email_type=manual on GET /emails, which the reference names but does not describe, and only emails with ue_type 3 (Sent) are kept: a campaign send is ue_type 1. Not run against a live workspace.",
622
635
  "An email's step and a lead's last step are ids of the form sequence_step_variant, each counted from 0 (seen live, not documented); any other form gives a null step. Step analytics count steps from 0 too, and can hold a row with no step for counts Instantly could not tie to one.",
623
636
  "Whether reply_count includes automatic replies is not documented; replied uses the unique reply count and repliedAuto the unique automatic count.",
@@ -629,6 +642,7 @@ var caveats = [
629
642
  "A campaign's settings, sequence and senders each read the whole campaign object. A sending window's days are assumed to be numbered 0 for Sunday to 6 for Saturday; the documentation only shows the keys 0 to 6.",
630
643
  "A campaign's senders are found by reading every mailbox and keeping those named in the campaign's email_list or carrying a tag in its email_tag_list, at two requests per page of mailboxes. A campaign that names tags only is filtered by Instantly.",
631
644
  "Sender health is three reads: the account, POST /accounts/test/vitals (a live DNS test, which Instantly may throttle) and POST /accounts/warmup-analytics. The warmup window is not documented. blacklisted and checkedAt are not reported. A DNS record Instantly could not resolve is null, not false.",
645
+ "Every mailbox's health (senderHealth) is read a page of 100 accounts at a time: the page, one POST /accounts/test/vitals naming one mailbox of each domain on it, and one POST /accounts/warmup-analytics naming every mailbox on it. The DNS test answers per domain, so each mailbox gets its domain's answer. Seen live on 2026-11-17: one test of 137 domains answered in about 2 seconds.",
632
646
  "connected is true for an Active account and false for a Connection Error; every other account status is null.",
633
647
  "A lead's engagement.stepIndex is the last step sent, read from its status summary; lastOpenedAt is null when open tracking is off. A lead has no tags in Instantly, and the lead object was seen without a job title.",
634
648
  "A lead is found by email with the contacts filter of POST /leads/list, documented only as the emails a lead needs to have. Whether it compares whole addresses and ignores case is not documented and was not run live, so the adapter keeps only the records whose address equals the one asked for, and a page can hold fewer records than Instantly returned. One record comes back per campaign or list the address is in. A lead has no LinkedIn profile: a lookup by profile returns nothing and sends no request.",
@@ -640,7 +654,8 @@ var caveats = [
640
654
  "A webhook made for a custom lead label has no event_type, so its events are empty; custom_interest_value stays in raw. The headers Instantly sends with a delivery can carry a credential, so they are left out of a webhook record's raw. The native read webhook returns them and is not offered to the vendor_read tool; outbound.raw returns a response as it is.",
641
655
  "A truncated message body costs one more read of that email (GET /emails/{id}) when bodies are asked for. That read is assumed to share the 20-per-minute limit of the email list.",
642
656
  "Messages of a thread are found with the documented search value thread:<id>.",
643
- "Instantly's email list does not hold every email a campaign sent (seen live: a lead on its sixth step had one sent email and two replies). A timeline or a thread can therefore be shorter than the sequence; a lead's engagement.stepIndex says how far it got. A received email carries the step it replies to."
657
+ "Instantly's email list does not hold every email a campaign sent (seen live: a lead on its sixth step had one sent email and two replies). A timeline or a thread can therefore be shorter than the sequence; a lead's engagement.stepIndex says how far it got. A received email carries the step it replies to.",
658
+ `A message's or reply's url opens its thread in the Unibox: https://app.instantly.ai/app/unibox?thread_search=thread:<thread_id>&selected_wks=<organization_id>. Instantly documents unibox_url on reply webhooks ("URL to view the conversation in Unibox") but not how it is built; on 2026-11-17 the unibox_url of four live reply_received deliveries, all naming one email, was exactly this, from that email's thread_id and organization_id. The link needs a signed-in Instantly session, and was not opened in a browser. An email without a thread_id or organization_id has a null url.`
644
659
  ];
645
660
 
646
661
  // src/instantly/map-lead.ts
@@ -655,6 +670,12 @@ var INTEREST = /* @__PURE__ */ new Map([
655
670
  [3, ["Meeting Completed", "positive"]],
656
671
  [4, ["Won", "positive"]]
657
672
  ]);
673
+ var MEETING = /* @__PURE__ */ new Map([
674
+ [-4, "no_show"],
675
+ [2, "booked"],
676
+ [3, "completed"],
677
+ [4, "won"]
678
+ ]);
658
679
  var NO_LABELS = /* @__PURE__ */ new Map();
659
680
  var isCustomInterest = (value) => {
660
681
  const code = count(value);
@@ -755,6 +776,7 @@ var toLead = (identity, raw, labels = NO_LABELS) => ({
755
776
  lastName: text(raw.last_name),
756
777
  linkedinUrl: null,
757
778
  location: null,
779
+ meeting: MEETING.get(count(raw.lt_interest_status) ?? Number.NaN) ?? null,
758
780
  phone: text(raw.phone),
759
781
  recipientMailProvider: RECIPIENT_PROVIDER.get(count(raw.esp_code) ?? Number.NaN) ?? null,
760
782
  // Instantly tags mailboxes and campaigns, never leads.
@@ -765,19 +787,32 @@ var toLead = (identity, raw, labels = NO_LABELS) => ({
765
787
  var SCHEDULED = 4;
766
788
  var RECEIVED = 2;
767
789
  var SENT_BY_HAND = 3;
768
- var leadOf = (raw) => emailAddress(raw.lead) ?? (count(raw.ue_type) === RECEIVED ? emailAddress(raw.from_address_email) : null) ?? text(raw.lead_id);
769
- var messageFields = (identity, raw, includeBody) => {
790
+ var leadAddressOf = (raw) => emailAddress(raw.lead) ?? (count(raw.ue_type) === RECEIVED ? emailAddress(raw.from_address_email) : null);
791
+ var leadIdKey = (address, campaign) => `${address} ${campaign ?? ""}`;
792
+ var NO_LEAD_IDS = /* @__PURE__ */ new Map();
793
+ var leadIdOf = (raw, leadIds) => {
794
+ const address = leadAddressOf(raw);
795
+ return text(raw.lead_id) ?? (address === null ? null : leadIds.get(leadIdKey(address, text(raw.campaign_id))) ?? null);
796
+ };
797
+ var uniboxUrl = (raw) => {
798
+ const thread = text(raw.thread_id);
799
+ const workspace = text(raw.organization_id);
800
+ return thread === null || workspace === null ? null : `https://app.instantly.ai/app/unibox?thread_search=thread:${encodeURIComponent(thread)}&selected_wks=${encodeURIComponent(workspace)}`;
801
+ };
802
+ var messageFields = (identity, raw, includeBody, leadIds) => {
770
803
  const body = field(raw.body, "html") ?? field(raw.body, "text");
771
804
  return {
772
805
  ...recordBase(identity, text(raw.id) ?? "", raw),
773
806
  ...normalizeBody(text(body), includeBody),
774
807
  campaignRef: refTo(identity, text(raw.campaign_id)),
775
808
  channel: "email",
776
- leadRef: refTo(identity, leadOf(raw)),
809
+ leadEmail: leadAddressOf(raw),
810
+ leadRef: refTo(identity, leadIdOf(raw, leadIds)),
777
811
  senderRef: refTo(identity, emailAddress(raw.eaccount)),
778
812
  sentAt: timestamp(raw.timestamp_email) ?? timestamp(raw.timestamp_created),
779
813
  subject: text(raw.subject),
780
814
  threadId: text(raw.thread_id),
815
+ url: uniboxUrl(raw),
781
816
  ...stepPosition(raw.step)
782
817
  };
783
818
  };
@@ -799,25 +834,28 @@ var autoOf = (raw, mapped) => {
799
834
  leftCompany: verdict.leftCompany
800
835
  };
801
836
  };
802
- var toMessage = (identity, raw, includeBody) => {
837
+ var toMessage = (identity, raw, includeBody, leadIds = NO_LEAD_IDS) => {
803
838
  if (count(raw.ue_type) !== RECEIVED) {
804
- return { ...messageFields(identity, raw, includeBody), direction: "out" };
839
+ return {
840
+ ...messageFields(identity, raw, includeBody, leadIds),
841
+ direction: "out"
842
+ };
805
843
  }
806
844
  const { isAuto, isAutoSource } = autoOf(
807
845
  raw,
808
846
  category(raw.i_status, NO_LABELS)
809
847
  );
810
848
  return {
811
- ...messageFields(identity, raw, includeBody),
849
+ ...messageFields(identity, raw, includeBody, leadIds),
812
850
  direction: "in",
813
851
  isAuto,
814
852
  isAutoSource
815
853
  };
816
854
  };
817
- var toReply = (identity, raw, includeBody, labels = NO_LABELS) => {
855
+ var toReply = (identity, raw, includeBody, labels = NO_LABELS, leadIds = NO_LEAD_IDS) => {
818
856
  const mapped = category(raw.i_status, labels);
819
857
  return {
820
- ...messageFields(identity, raw, includeBody),
858
+ ...messageFields(identity, raw, includeBody, leadIds),
821
859
  category: mapped ?? "unknown",
822
860
  categorySource: mapped === void 0 ? null : "vendor",
823
861
  direction: "in",
@@ -956,6 +994,66 @@ var accountReaders = (client) => {
956
994
  };
957
995
  };
958
996
 
997
+ // src/instantly/lead-ids.ts
998
+ var leadsWith = async (client, ctx, addresses) => {
999
+ const found = [];
1000
+ let after2;
1001
+ do {
1002
+ const body = { contacts: [...addresses], limit: PAGE_SIZE };
1003
+ if (after2 !== void 0) {
1004
+ body.starting_after = after2;
1005
+ }
1006
+ const envelope = listEnvelope(
1007
+ // oxlint-disable-next-line no-await-in-loop -- each page's cursor comes from the one before.
1008
+ await client.post(ctx, "/leads/list", body),
1009
+ client.identity.provider,
1010
+ "/leads/list"
1011
+ );
1012
+ for (const item of envelope.items) {
1013
+ const address = emailAddress(item.email);
1014
+ const id = text(item.id);
1015
+ if (address !== null && id !== null && addresses.includes(address)) {
1016
+ found.push({ address, campaign: text(item.campaign), id });
1017
+ }
1018
+ }
1019
+ after2 = envelope.items.length >= PAGE_SIZE ? envelope.next : void 0;
1020
+ } while (after2 !== void 0);
1021
+ return found;
1022
+ };
1023
+ var leadIdsFor = async (client, ctx, items) => {
1024
+ const addresses = [
1025
+ ...new Set(
1026
+ items.flatMap(
1027
+ (item) => text(item.lead_id) === null ? leadAddressOf(item) ?? [] : []
1028
+ )
1029
+ )
1030
+ ];
1031
+ const ids = /* @__PURE__ */ new Map();
1032
+ const perAddress = /* @__PURE__ */ new Map();
1033
+ for (let at = 0; at < addresses.length; at += PAGE_SIZE) {
1034
+ const leads = await leadsWith(
1035
+ client,
1036
+ ctx,
1037
+ addresses.slice(at, at + PAGE_SIZE)
1038
+ );
1039
+ for (const { address, campaign, id } of leads) {
1040
+ ids.set(leadIdKey(address, campaign), id);
1041
+ perAddress.set(address, (perAddress.get(address) ?? /* @__PURE__ */ new Set()).add(id));
1042
+ }
1043
+ }
1044
+ for (const [address, found] of perAddress) {
1045
+ const [only] = found;
1046
+ if (found.size === 1 && only !== void 0) {
1047
+ ids.set(leadIdKey(address, null), only);
1048
+ }
1049
+ }
1050
+ return ids;
1051
+ };
1052
+ var oneLead = (address, campaign, id) => /* @__PURE__ */ new Map([
1053
+ [leadIdKey(address, campaign), id],
1054
+ [leadIdKey(address, null), id]
1055
+ ]);
1056
+
959
1057
  // src/instantly/thread.ts
960
1058
  var timeOf = (message) => message.sentAt === null ? Number.NaN : Date.parse(message.sentAt);
961
1059
  var answering = (message, answered) => {
@@ -994,27 +1092,36 @@ var withAnsweredSteps = (messages) => {
994
1092
  // src/instantly/adapter-mail.ts
995
1093
  var emailCursor = (next) => ({
996
1094
  after: text(field(next, "after")) ?? void 0,
1095
+ campaign: text(field(next, "campaign")) ?? void 0,
1096
+ id: text(field(next, "id")) ?? void 0,
997
1097
  lead: text(field(next, "lead")) ?? void 0
998
1098
  });
999
- var leadAddress = async (client, ctx, leadId, cursor) => {
1000
- if (leadId === void 0 || cursor.lead !== void 0) {
1001
- return cursor.lead;
1099
+ var timelineLead = async (client, ctx, leadId, cursor) => {
1100
+ if (cursor.lead !== void 0) {
1101
+ return { address: cursor.lead, campaign: cursor.campaign, id: cursor.id };
1102
+ }
1103
+ if (leadId === void 0) {
1104
+ return void 0;
1002
1105
  }
1003
1106
  const given = emailAddress(leadId);
1004
1107
  if (given !== null) {
1005
- return given;
1108
+ return { address: given, campaign: void 0, id: void 0 };
1006
1109
  }
1007
1110
  const lead = await client.getObject(
1008
1111
  ctx,
1009
1112
  `/leads/${encodeURIComponent(leadId)}`
1010
1113
  );
1011
- const address = text(lead.email);
1114
+ const address = emailAddress(lead.email);
1012
1115
  if (address === null) {
1013
1116
  throw new OutboundError("NotFound", `Lead ${leadId} has no email address`, {
1014
1117
  provider: client.identity.provider
1015
1118
  });
1016
1119
  }
1017
- return address;
1120
+ return {
1121
+ address,
1122
+ campaign: text(lead.campaign) ?? void 0,
1123
+ id: leadId
1124
+ };
1018
1125
  };
1019
1126
  var withFullBody = async (client, ctx, item) => {
1020
1127
  const id = text(item.id);
@@ -1022,21 +1129,27 @@ var withFullBody = async (client, ctx, item) => {
1022
1129
  lane: EMAILS_LANE
1023
1130
  });
1024
1131
  };
1132
+ var nextCursor = (after2, lead) => after2 === void 0 ? void 0 : {
1133
+ after: after2,
1134
+ campaign: lead?.campaign ?? null,
1135
+ id: lead?.id ?? null,
1136
+ lead: lead?.address ?? null
1137
+ };
1025
1138
  var listEmails = async (client, ctx, query, received) => {
1026
1139
  const cursor = emailCursor(query.next);
1027
1140
  const leadId = "leadId" in query ? query.leadId : void 0;
1028
1141
  const threadId = "threadId" in query ? query.threadId : void 0;
1029
1142
  const byHand = "byHand" in query && query.byHand === true;
1030
1143
  const sentByHand = byHand ? "manual" : void 0;
1031
- const lead = await leadAddress(client, ctx, leadId, cursor);
1144
+ const lead = await timelineLead(client, ctx, leadId, cursor);
1032
1145
  const envelope = listEnvelope(
1033
1146
  await client.get(ctx, "/emails", {
1034
1147
  lane: EMAILS_LANE,
1035
1148
  query: {
1036
- campaign_id: query.campaignId,
1149
+ campaign_id: query.campaignId ?? lead?.campaign,
1037
1150
  email_type: received ? "received" : sentByHand,
1038
1151
  is_unread: "unread" in query ? query.unread : void 0,
1039
- lead,
1152
+ lead: lead?.address,
1040
1153
  limit: pageSize(query.limit),
1041
1154
  max_timestamp_created: query.until,
1042
1155
  min_timestamp_created: query.since,
@@ -1054,7 +1167,8 @@ var listEmails = async (client, ctx, query, received) => {
1054
1167
  items: query.includeBody ? await Promise.all(
1055
1168
  sent.map(async (item) => await withFullBody(client, ctx, item))
1056
1169
  ) : sent,
1057
- next: envelope.next === void 0 ? void 0 : { after: envelope.next, lead: lead ?? null }
1170
+ leadIds: lead?.id === void 0 ? await leadIdsFor(client, ctx, sent) : oneLead(lead.address, lead.campaign ?? null, lead.id),
1171
+ next: nextCursor(envelope.next, lead)
1058
1172
  };
1059
1173
  };
1060
1174
  var mailReaders = (client) => ({
@@ -1062,7 +1176,7 @@ var mailReaders = (client) => ({
1062
1176
  const page = await listEmails(client, ctx, query, false);
1063
1177
  const mapped = mapPage(
1064
1178
  page,
1065
- (item) => toMessage(client.identity, item, query.includeBody)
1179
+ (item) => toMessage(client.identity, item, query.includeBody, page.leadIds)
1066
1180
  );
1067
1181
  return { ...mapped, items: withAnsweredSteps(mapped.items) };
1068
1182
  },
@@ -1074,7 +1188,7 @@ var mailReaders = (client) => ({
1074
1188
  page.items.map((item) => item.i_status)
1075
1189
  );
1076
1190
  const replies = page.items.map(
1077
- (item) => toReply(client.identity, item, query.includeBody, labels)
1191
+ (item) => toReply(client.identity, item, query.includeBody, labels, page.leadIds)
1078
1192
  );
1079
1193
  return {
1080
1194
  // One i_status value fits in the query but a category maps to several, so
@@ -1085,6 +1199,84 @@ var mailReaders = (client) => ({
1085
1199
  }
1086
1200
  });
1087
1201
 
1202
+ // src/instantly/senders.ts
1203
+ var campaignAccounts = async (client, ctx, query) => {
1204
+ const campaign = await client.getObject(
1205
+ ctx,
1206
+ `/campaigns/${encodeURIComponent(query.campaignId)}`
1207
+ );
1208
+ const addresses = new Set(
1209
+ list(campaign.email_list).flatMap((value) => emailAddress(value) ?? [])
1210
+ );
1211
+ const tagIds = new Set(
1212
+ list(campaign.email_tag_list).flatMap((value) => text(value) ?? [])
1213
+ );
1214
+ if (addresses.size === 0 && tagIds.size === 0) {
1215
+ return { items: [] };
1216
+ }
1217
+ const byTagOnly = addresses.size === 0;
1218
+ const page = await listPage(client, ctx, "/accounts", query, {
1219
+ include_tags: byTagOnly || tagIds.size === 0 ? void 0 : true,
1220
+ tag_ids: byTagOnly ? [...tagIds].join(",") : void 0
1221
+ });
1222
+ const attached = (account) => byTagOnly || addresses.has(emailAddress(account.email) ?? "") || objects(account.tags).some((tag) => tagIds.has(text(tag.id) ?? ""));
1223
+ return { items: page.items.filter(attached), next: page.next };
1224
+ };
1225
+ var accountsPage = async (client, ctx, query) => query.campaignId === void 0 ? await listPage(client, ctx, "/accounts", query, { include_tags: true }) : await campaignAccounts(client, ctx, {
1226
+ ...query,
1227
+ campaignId: query.campaignId
1228
+ });
1229
+ var domainOf = (address) => address.split("@").at(-1) ?? "";
1230
+ var vitalsOf = (vitals, domain) => {
1231
+ const mine = (key) => objects(field(vitals, key)).filter(
1232
+ (entry) => text(entry.domain)?.toLowerCase() === domain
1233
+ );
1234
+ return {
1235
+ failure_list: mine("failure_list"),
1236
+ success_list: mine("success_list")
1237
+ };
1238
+ };
1239
+ var healthOf = async (client, ctx, accounts) => {
1240
+ const addresses = accounts.flatMap(
1241
+ (account) => emailAddress(account.email) ?? []
1242
+ );
1243
+ if (addresses.length === 0) {
1244
+ return [];
1245
+ }
1246
+ const firstOfDomain = /* @__PURE__ */ new Map();
1247
+ for (const address of addresses) {
1248
+ if (!firstOfDomain.has(domainOf(address))) {
1249
+ firstOfDomain.set(domainOf(address), address);
1250
+ }
1251
+ }
1252
+ const vitals = await client.post(ctx, "/accounts/test/vitals", {
1253
+ accounts: [...firstOfDomain.values()]
1254
+ });
1255
+ const warmup = await client.post(ctx, "/accounts/warmup-analytics", {
1256
+ emails: addresses
1257
+ });
1258
+ return accounts.flatMap((account) => {
1259
+ const address = emailAddress(account.email);
1260
+ return address === null ? [] : [
1261
+ toSenderHealth(client.identity, address, {
1262
+ account,
1263
+ vitals: vitalsOf(vitals, domainOf(address)),
1264
+ warmup
1265
+ })
1266
+ ];
1267
+ });
1268
+ };
1269
+ var senderReaders = (client) => ({
1270
+ listSenderHealth: async (query, ctx) => {
1271
+ const page = await accountsPage(client, ctx, query);
1272
+ return { items: await healthOf(client, ctx, page.items), next: page.next };
1273
+ },
1274
+ listSenders: async (query, ctx) => mapPage(
1275
+ await accountsPage(client, ctx, query),
1276
+ (account) => toSender(client.identity, account, ctx.note)
1277
+ )
1278
+ });
1279
+
1088
1280
  // src/instantly/map-stats.ts
1089
1281
  var overviewRow = (scope, raw) => metricRow(scope, {
1090
1282
  ...emptyCounts(),
@@ -1215,6 +1407,36 @@ var senderStats = async (client, ctx, scope, query) => {
1215
1407
  await workspaceTracking(client, ctx, range(query))
1216
1408
  );
1217
1409
  };
1410
+ var EMAILS_AT_MOST = 200;
1411
+ var sendersStats = async (client, ctx, query, scopeIds) => {
1412
+ const chunks = Array.from(
1413
+ { length: Math.ceil(scopeIds.length / EMAILS_AT_MOST) },
1414
+ (_, index) => scopeIds.slice(index * EMAILS_AT_MOST, (index + 1) * EMAILS_AT_MOST)
1415
+ );
1416
+ const batches = await Promise.all(
1417
+ chunks.map(
1418
+ (emails) => client.getRows(ctx, "/accounts/analytics/daily", {
1419
+ query: { ...range(query), emails }
1420
+ })
1421
+ )
1422
+ );
1423
+ const days2 = batches.flat();
1424
+ const byEmail = new Map(scopeIds.map((id) => [id.toLowerCase(), id]));
1425
+ const rows = scopeIds.flatMap((scopeId) => {
1426
+ const own = days2.filter(
1427
+ (day) => byEmail.get(text(day.email_account)?.toLowerCase() ?? "") === scopeId
1428
+ );
1429
+ const scope = { ...client.identity, scope: "sender", scopeId };
1430
+ if (query.by === "day") {
1431
+ return own.map((day) => dailyRow(scope, day));
1432
+ }
1433
+ return own.length === 0 ? [] : [summedRow(scope, own)];
1434
+ });
1435
+ return applyTracking(
1436
+ rows,
1437
+ await workspaceTracking(client, ctx, range(query))
1438
+ );
1439
+ };
1218
1440
  var ownRows = async (client, ctx, campaignId, rows) => {
1219
1441
  const flags = await campaignFlags(client, ctx, campaignId);
1220
1442
  return applyTracking(
@@ -1230,6 +1452,9 @@ var readStats = async (client, ctx, query) => {
1230
1452
  scope: query.scope,
1231
1453
  scopeId: query.scopeId ?? identity.workspaceId
1232
1454
  };
1455
+ if (query.scope === "sender" && query.scopeIds !== void 0) {
1456
+ return await sendersStats(client, ctx, query, query.scopeIds);
1457
+ }
1233
1458
  if (query.scope === "sender") {
1234
1459
  return await senderStats(client, ctx, scope, query);
1235
1460
  }
@@ -1381,31 +1606,6 @@ var listCampaigns = async (client, ctx, query) => {
1381
1606
  next: page.next
1382
1607
  };
1383
1608
  };
1384
- var campaignSenders = async (client, ctx, query) => {
1385
- const campaign = await client.getObject(
1386
- ctx,
1387
- `/campaigns/${encodeURIComponent(query.campaignId)}`
1388
- );
1389
- const addresses = new Set(
1390
- list(campaign.email_list).flatMap((value) => emailAddress(value) ?? [])
1391
- );
1392
- const tagIds = new Set(
1393
- list(campaign.email_tag_list).flatMap((value) => text(value) ?? [])
1394
- );
1395
- if (addresses.size === 0 && tagIds.size === 0) {
1396
- return { items: [] };
1397
- }
1398
- const byTagOnly = addresses.size === 0;
1399
- const page = await listPage(client, ctx, "/accounts", query, {
1400
- include_tags: byTagOnly || tagIds.size === 0 ? void 0 : true,
1401
- tag_ids: byTagOnly ? [...tagIds].join(",") : void 0
1402
- });
1403
- const attached = (account) => byTagOnly || addresses.has(emailAddress(account.email) ?? "") || texts(objects(account.tags), "id").some((id) => tagIds.has(id));
1404
- return {
1405
- items: page.items.filter((account) => attached(account)).map((account) => toSender(client.identity, account, ctx.note)),
1406
- next: page.next
1407
- };
1408
- };
1409
1609
  var POSITIVE_FILTERS = [
1410
1610
  "FILTER_LEAD_INTERESTED",
1411
1611
  "FILTER_LEAD_MEETING_BOOKED",
@@ -1515,6 +1715,7 @@ var readers = (client) => {
1515
1715
  ...accountReaders(client),
1516
1716
  ...leadReaders(client),
1517
1717
  ...mailReaders(client),
1718
+ ...senderReaders(client),
1518
1719
  getCampaign: async (id, ctx) => {
1519
1720
  const campaign = await client.getObject(
1520
1721
  ctx,
@@ -1534,18 +1735,6 @@ var readers = (client) => {
1534
1735
  ctx.note
1535
1736
  ),
1536
1737
  listCampaigns: async (query, ctx) => await listCampaigns(client, ctx, query),
1537
- listSenders: async (query, ctx) => {
1538
- if (query.campaignId !== void 0) {
1539
- return await campaignSenders(client, ctx, {
1540
- ...query,
1541
- campaignId: query.campaignId
1542
- });
1543
- }
1544
- const page = await listPage(client, ctx, "/accounts", query, {
1545
- include_tags: true
1546
- });
1547
- return mapPage(page, (item) => toSender(identity, item, ctx.note));
1548
- },
1549
1738
  listWorkspaces: async (_query, ctx) => {
1550
1739
  const workspace = await client.get(ctx, "/workspaces/current");
1551
1740
  return {
@@ -0,0 +1,11 @@
1
+ import type { AdapterContext } from "../internal/adapter.ts";
2
+ import type { JsonObject } from "../internal/json.ts";
3
+ import type { InstantlyClient } from "./client.ts";
4
+ import type { LeadIds } from "./map-lead.ts";
5
+ /**
6
+ * The lead ids of the emails that name their lead by address only. An
7
+ * address with one lead also stands for an email that names no campaign.
8
+ */
9
+ export declare const leadIdsFor: (client: InstantlyClient, ctx: AdapterContext, items: readonly JsonObject[]) => Promise<LeadIds>;
10
+ /** The ids of one known lead's emails: no lookup is needed. */
11
+ export declare const oneLead: (address: string, campaign: string | null, id: string) => LeadIds;
@@ -11,9 +11,26 @@ export declare const toLabels: (items: readonly JsonObject[]) => Labels;
11
11
  export declare const toLead: (identity: Identity, raw: JsonObject, labels?: Labels) => Lead;
12
12
  /** `ue_type`: 1 sent from a campaign, 2 received, 3 sent by hand, 4 scheduled. */
13
13
  export declare const SCHEDULED = 4;
14
+ /**
15
+ * The address an email names its lead by, in `lead`. On a received email the
16
+ * sender is the lead, so `from_address_email` stands in when `lead` is
17
+ * missing.
18
+ */
19
+ export declare const leadAddressOf: (raw: JsonObject) => string | null;
20
+ /**
21
+ * Lead ids by address and campaign, from `leadIdKey`. An email documents
22
+ * `lead_id` only "(if any)" and none carried it live, so the adapter looks the
23
+ * leads up by address.
24
+ */
25
+ export type LeadIds = ReadonlyMap<string, string>;
26
+ /**
27
+ * One lead per address and campaign. `campaign` `null` stands for the
28
+ * address's only lead, for an email that names no campaign.
29
+ */
30
+ export declare const leadIdKey: (address: string, campaign: string | null) => string;
14
31
  export declare const isScheduled: (raw: JsonObject) => boolean;
15
32
  export declare const isSentByHand: (raw: JsonObject) => boolean;
16
33
  /** `true` when a list response holds an excerpt instead of the whole body. */
17
34
  export declare const isTruncated: (raw: JsonObject) => boolean;
18
- export declare const toMessage: (identity: Identity, raw: JsonObject, includeBody: boolean) => Message;
19
- export declare const toReply: (identity: Identity, raw: JsonObject, includeBody: boolean, labels?: Labels) => Reply;
35
+ export declare const toMessage: (identity: Identity, raw: JsonObject, includeBody: boolean, leadIds?: LeadIds) => Message;
36
+ export declare const toReply: (identity: Identity, raw: JsonObject, includeBody: boolean, labels?: Labels, leadIds?: LeadIds) => Reply;
@@ -0,0 +1,3 @@
1
+ import type { Adapter } from "../internal/adapter.ts";
2
+ import type { InstantlyClient } from "./client.ts";
3
+ export declare const senderReaders: (client: InstantlyClient) => Pick<Adapter, "listSenderHealth" | "listSenders">;
@@ -112,6 +112,11 @@ export interface StatsQuery {
112
112
  * campaign scope without one asks for a row per campaign.
113
113
  */
114
114
  readonly scopeId?: string | undefined;
115
+ /**
116
+ * Several senders, for the sender scope in place of `scopeId`, where the
117
+ * adapter declares `stats.bySenders`. Each row's `scopeRef` is its sender.
118
+ */
119
+ readonly scopeIds?: readonly string[] | undefined;
115
120
  /** Inclusive `YYYY-MM-DD`. */
116
121
  readonly from?: string | undefined;
117
122
  /** Inclusive `YYYY-MM-DD`. */
@@ -237,6 +242,8 @@ export interface Adapter<Native extends NativeCatalog = NoNative> {
237
242
  readonly getCampaignProgress?: (campaignId: string, ctx: AdapterContext) => Promise<CampaignProgress>;
238
243
  readonly listSubsequences?: (query: SubsequenceQuery, ctx: AdapterContext) => Promise<Page<Sequence>>;
239
244
  readonly getSenderHealth?: (senderId: string, ctx: AdapterContext) => Promise<SenderHealth>;
245
+ /** A page of senders' health, the senders listed as `listSenders` lists them. */
246
+ readonly listSenderHealth?: (query: SenderQuery, ctx: AdapterContext) => Promise<Page<SenderHealth>>;
240
247
  readonly listLists?: (query: PageQuery, ctx: AdapterContext) => Promise<Page<LeadList>>;
241
248
  readonly getList?: (id: string, ctx: AdapterContext) => Promise<LeadList>;
242
249
  readonly listBlocklist?: (query: PageQuery, ctx: AdapterContext) => Promise<Page<BlockEntry>>;
@@ -23,6 +23,8 @@ export interface Capabilities {
23
23
  "senders.warmup": boolean;
24
24
  /** DNS records, connection state and warmup traffic for one sender. */
25
25
  "senders.health": boolean;
26
+ /** The same health for every sender, a page at a time, in a few requests a page instead of a few per sender. */
27
+ "senders.healthList": boolean;
26
28
  /** List every lead on the credential, across campaigns. */
27
29
  "leads.list": boolean;
28
30
  "leads.get": boolean;
@@ -81,6 +83,12 @@ export interface Capabilities {
81
83
  "stats.byDay": StatGrade;
82
84
  "stats.byStep": StatGrade;
83
85
  "stats.bySender": StatGrade;
86
+ /**
87
+ * Several senders in one read: `stats({ scope: "sender", scopeIds })`,
88
+ * a row per sender (and day) in a few requests instead of a few per sender.
89
+ * Graded like `stats.bySender`.
90
+ */
91
+ "stats.bySenders": StatGrade;
84
92
  workspaces: boolean;
85
93
  /** The addresses, domains and profiles the account never contacts. */
86
94
  blocklist: boolean;