outbound-sdk 0.12.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 (67) hide show
  1. package/dist/alerts/index.js +1 -1
  2. package/dist/budget/index.js +1 -1
  3. package/dist/cards/index.js +16 -8
  4. package/dist/chunks/{chunk-AWNH4I5D.js → chunk-6BSFR5SF.js} +3 -0
  5. package/dist/chunks/{chunk-KNWJIJVO.js → chunk-BTIJ24UY.js} +17 -6
  6. package/dist/chunks/{chunk-HDTOGEVN.js → chunk-EAG5NIPM.js} +85 -27
  7. package/dist/chunks/{chunk-B72F56HF.js → chunk-FT6HMMMP.js} +1 -1
  8. package/dist/chunks/{chunk-CTRYCW4G.js → chunk-LJNU4LAR.js} +1471 -857
  9. package/dist/chunks/{chunk-HXCZMMSD.js → chunk-NLYGMVXS.js} +9 -0
  10. package/dist/chunks/{chunk-3DDYXUDG.js → chunk-OE45PREW.js} +1 -1
  11. package/dist/chunks/{chunk-2ADIGC2N.js → chunk-OP2GL7ZT.js} +2 -2
  12. package/dist/chunks/{chunk-UIINRLHQ.js → chunk-PDYE6CWS.js} +130 -62
  13. package/dist/chunks/{chunk-UWNQEQIX.js → chunk-PUIHJFK4.js} +1 -1
  14. package/dist/chunks/{tools-EKLZKXZU.js → tools-VCCH3JNL.js} +11 -5
  15. package/dist/cli/bin.js +9 -9
  16. package/dist/cli/config.d.ts +0 -2
  17. package/dist/cli/index.js +8 -8
  18. package/dist/cli/offered.d.ts +31 -2
  19. package/dist/cli/serve.d.ts +4 -2
  20. package/dist/combine/index.js +26 -4
  21. package/dist/emailbison/index.js +2 -2
  22. package/dist/fixtures/index.js +1 -1
  23. package/dist/heyreach/index.js +4 -1
  24. package/dist/index.js +3 -3
  25. package/dist/insights/capped.d.ts +14 -1
  26. package/dist/insights/define.d.ts +7 -5
  27. package/dist/insights/index.d.ts +1 -1
  28. package/dist/insights/index.js +10 -60
  29. package/dist/insights/inputs.generated.d.ts +26 -14
  30. package/dist/insights/ops/campaign-ranking.d.ts +8 -1
  31. package/dist/insights/ops/client-report.d.ts +28 -18
  32. package/dist/insights/ops/client-runway.d.ts +43 -0
  33. package/dist/insights/ops/index.d.ts +6 -1
  34. package/dist/insights/ops/period-comparison.d.ts +23 -1
  35. package/dist/insights/ops/pipeline-forecast.d.ts +14 -9
  36. package/dist/insights/ops/shared.d.ts +38 -1
  37. package/dist/insights/people/coverage.d.ts +26 -0
  38. package/dist/insights/people/dropped-replies-check.d.ts +5 -1
  39. package/dist/insights/people/dropped-replies.d.ts +6 -2
  40. package/dist/insights/people/index.d.ts +2 -2
  41. package/dist/insights/people/lead-collisions.d.ts +18 -1
  42. package/dist/insights/people/suppression-check.d.ts +18 -1
  43. package/dist/insights/people/thread-contexts.d.ts +2 -2
  44. package/dist/insights/people/thread-read.d.ts +11 -0
  45. package/dist/insights/registry.d.ts +6 -2
  46. package/dist/insights/tools.d.ts +35 -2
  47. package/dist/instantly/index.js +108 -22
  48. package/dist/instantly/lead-ids.d.ts +11 -0
  49. package/dist/instantly/map-lead.d.ts +19 -2
  50. package/dist/internal/entities.d.ts +4 -1
  51. package/dist/internal/fields.d.ts +2 -0
  52. package/dist/internal/reply-people.d.ts +25 -7
  53. package/dist/internal/runway.d.ts +38 -5
  54. package/dist/loader/index.js +1 -1
  55. package/dist/memory/index.js +1 -1
  56. package/dist/redact/index.d.ts +1 -1
  57. package/dist/redact/index.js +59 -28
  58. package/dist/redact/plugin.d.ts +13 -11
  59. package/dist/redact/tokens.d.ts +18 -1
  60. package/dist/smartlead/index.js +4 -1
  61. package/dist/tools/ai-sdk.js +3 -3
  62. package/dist/tools/claude-agent.js +3 -3
  63. package/dist/tools/index.js +4 -4
  64. package/dist/tools/registry.d.ts +8 -1
  65. package/dist/webhooks/index.js +2 -2
  66. package/package.json +1 -1
  67. /package/dist/chunks/{chunk-TOZKA7JR.js → chunk-HNYJO6B4.js} +0 -0
@@ -6,7 +6,11 @@ export interface DroppedReplies {
6
6
  readonly repliesRead: number;
7
7
  /** Left out for a category that needs no answer. */
8
8
  readonly skippedByCategory: number;
9
- /** Left out because they are flagged automatic, by the vendor or by a fixed rule. */
9
+ /**
10
+ * Left out because they are flagged automatic, by the vendor or by a fixed
11
+ * rule, or because their conversation, read in full, ends in an automatic
12
+ * reply. 0 with `include_auto`.
13
+ */
10
14
  readonly skippedAuto: number;
11
15
  /**
12
16
  * Set aside because their conversation belongs to no campaign, such as a
@@ -15,7 +19,7 @@ export interface DroppedReplies {
15
19
  * set by dropped_replies; optional so a value built by hand stays valid.
16
20
  */
17
21
  readonly notInCampaign?: number | null;
18
- /** Conversations the remaining replies belong to. */
22
+ /** Conversations the remaining replies belong to: answered, dropped, tooRecent and unchecked add up to it. */
19
23
  readonly conversations: number;
20
24
  readonly answered: number;
21
25
  readonly dropped: number;
@@ -91,14 +91,14 @@ export declare const PEOPLE_INSIGHTS: readonly [import("../define.ts").InsightDe
91
91
  weight_recency?: number | undefined;
92
92
  weight_reply?: number | undefined;
93
93
  }>, import("../define.ts").InsightDefinition<"threadContext", {
94
- bodies: "none" | "snippet";
94
+ bodies: "none" | "snippet" | null;
95
95
  cursor: string | null;
96
96
  leads: string[];
97
97
  max_messages: number;
98
98
  page_size: number;
99
99
  threads: string[];
100
100
  }, import("./thread-contexts.ts").ThreadContexts, {
101
- bodies?: "none" | "snippet" | undefined;
101
+ bodies?: "none" | "snippet" | null | undefined;
102
102
  cursor?: string | null | undefined;
103
103
  leads?: string[] | undefined;
104
104
  max_messages?: number | undefined;
@@ -20,10 +20,23 @@ export interface LeadCollision {
20
20
  readonly finding: string;
21
21
  }
22
22
  export interface LeadCollisions {
23
+ /**
24
+ * The answer in one sentence, coverage first: how many people overlap, or
25
+ * what the caps left unread when the check is incomplete. Never "nobody"
26
+ * from part of the data.
27
+ */
28
+ readonly finding: string;
23
29
  /** Most active campaigns first, then most campaigns, then collisions across tools, then by identifier. */
24
30
  readonly collisions: readonly LeadCollision[];
25
31
  readonly totals: {
26
- readonly collisions: number;
32
+ /**
33
+ * Collisions returned, or `null` when a cap left campaigns or leads
34
+ * unread: the check is incomplete and `collisionsFound` is only a lower
35
+ * bound. The counts below are of the collisions found.
36
+ */
37
+ readonly collisions: number | null;
38
+ /** Collisions returned among what was read. Raising a cap never lowers it. */
39
+ readonly collisionsFound: number;
27
40
  /** Collisions returned in which two or more memberships are still active. */
28
41
  readonly concurrent: number;
29
42
  /**
@@ -37,6 +50,10 @@ export interface LeadCollisions {
37
50
  readonly leadsRead: number;
38
51
  /** Leads with neither an email address nor a LinkedIn profile, which cannot be matched. */
39
52
  readonly leadsWithoutIdentifier: number;
53
+ /** `true` when `max_campaigns` or a request cap left campaigns in the statuses unread. */
54
+ readonly moreCampaignsExist: boolean;
55
+ /** Campaigns whose leads were read only in part. */
56
+ readonly campaignsWithMoreLeads: number;
40
57
  };
41
58
  }
42
59
  export declare const leadCollisions: import("../define.ts").InsightDefinition<"leadCollisions", {
@@ -23,12 +23,25 @@ export interface SuppressionCampaign {
23
23
  readonly violations: number;
24
24
  }
25
25
  export interface SuppressionCheck {
26
+ /**
27
+ * The answer in one sentence, coverage first: how many violations in how
28
+ * many campaigns, or what the caps left unread when the check is
29
+ * incomplete. Never "none" from part of the data.
30
+ */
31
+ readonly finding: string;
26
32
  /** Leads still `active` first, then by campaign and lead. */
27
33
  readonly violations: readonly SuppressionViolation[];
28
34
  /** Every campaign checked, most violations first. */
29
35
  readonly byCampaign: readonly SuppressionCampaign[];
30
36
  readonly totals: {
31
- readonly violations: number;
37
+ /**
38
+ * Violations in every campaign and against every entry, or `null` when
39
+ * a cap left campaigns, leads or block entries unread: the check is
40
+ * incomplete and `violationsFound` is only a lower bound.
41
+ */
42
+ readonly violations: number | null;
43
+ /** Violations in what was read. Raising a cap never lowers it. */
44
+ readonly violationsFound: number;
32
45
  /**
33
46
  * Leads on the block list whose status is not in `lead_statuses`, so not
34
47
  * counted as violations: most often they unsubscribed (which is why they
@@ -54,6 +67,10 @@ export interface SuppressionCheck {
54
67
  readonly moreBlockEntriesExist: boolean;
55
68
  /** `true` when `max_leads_per_campaign` stopped a campaign's read with more leads left. */
56
69
  readonly moreLeadsExist: boolean;
70
+ /** Campaigns whose leads were read only in part. */
71
+ readonly campaignsWithMoreLeads: number;
72
+ /** `true` when `max_campaigns` or a request cap left campaigns in the statuses unread. */
73
+ readonly moreCampaignsExist: boolean;
57
74
  };
58
75
  }
59
76
  export declare const suppressionCheck: import("../define.ts").InsightDefinition<"suppressionCheck", {
@@ -43,14 +43,14 @@ export interface ThreadContexts {
43
43
  };
44
44
  }
45
45
  export declare const threadContexts: import("../define.ts").InsightDefinition<"threadContext", {
46
- bodies: "none" | "snippet";
46
+ bodies: "none" | "snippet" | null;
47
47
  cursor: string | null;
48
48
  leads: string[];
49
49
  max_messages: number;
50
50
  page_size: number;
51
51
  threads: string[];
52
52
  }, ThreadContexts, {
53
- bodies?: "none" | "snippet" | undefined;
53
+ bodies?: "none" | "snippet" | null | undefined;
54
54
  cursor?: string | null | undefined;
55
55
  leads?: string[] | undefined;
56
56
  max_messages?: number | undefined;
@@ -13,6 +13,17 @@ export interface Read {
13
13
  readonly failed: string | null;
14
14
  }
15
15
  export declare const readConversation: (context: InsightContext, target: Target, bodies: boolean) => Promise<Read>;
16
+ /**
17
+ * Snippets unless asked for none, or none when redact masks message text.
18
+ * Asking for snippets that redact masks is refused.
19
+ */
20
+ export declare const bodiesOf: (context: InsightContext, asked: "none" | "snippet" | null) => "none" | "snippet";
21
+ /**
22
+ * Refuses, before any request, a target this instance cannot read: a redact
23
+ * token from another session, which would reach the vendor as it is and fail
24
+ * there; text that is not a lead ref; a ref of another tool or workspace.
25
+ */
26
+ export declare const refuseUnreadable: (context: InsightContext, targets: readonly Target[]) => void;
16
27
  /** A lead's messages in its own campaign: a vendor that uses one id in every campaign returns them all. */
17
28
  export declare const inCampaign: (messages: readonly Message[], lead: Lead | null | undefined) => Message[];
18
29
  /**
@@ -92,14 +92,14 @@ export declare const INSIGHTS: readonly [import("./define.ts").InsightDefinition
92
92
  weight_recency?: number | undefined;
93
93
  weight_reply?: number | undefined;
94
94
  }>, import("./define.ts").InsightDefinition<"threadContext", {
95
- bodies: "none" | "snippet";
95
+ bodies: "none" | "snippet" | null;
96
96
  cursor: string | null;
97
97
  leads: string[];
98
98
  max_messages: number;
99
99
  page_size: number;
100
100
  threads: string[];
101
101
  }, import("./people/thread-contexts.ts").ThreadContexts, {
102
- bodies?: "none" | "snippet" | undefined;
102
+ bodies?: "none" | "snippet" | null | undefined;
103
103
  cursor?: string | null | undefined;
104
104
  leads?: string[] | undefined;
105
105
  max_messages?: number | undefined;
@@ -374,6 +374,8 @@ export declare const INSIGHTS: readonly [import("./define.ts").InsightDefinition
374
374
  runway_days: number;
375
375
  max_campaigns: number;
376
376
  statuses: ("active" | "archived" | "completed" | "draft" | "paused" | "unknown")[];
377
+ provider?: string | undefined;
378
+ tag?: string | undefined;
377
379
  }, import("./ops/client-report.ts").ClientReport, {
378
380
  alpha?: number | undefined;
379
381
  anomaly_threshold?: number | undefined;
@@ -384,7 +386,9 @@ export declare const INSIGHTS: readonly [import("./define.ts").InsightDefinition
384
386
  max_leads_per_campaign?: number | undefined;
385
387
  min_baseline_points?: number | undefined;
386
388
  min_sent?: number | undefined;
389
+ provider?: string | undefined;
387
390
  runway_days?: number | undefined;
391
+ tag?: string | undefined;
388
392
  max_campaigns?: number | undefined;
389
393
  statuses?: ("active" | "archived" | "completed" | "draft" | "paused" | "unknown")[] | undefined;
390
394
  }>];
@@ -1,5 +1,7 @@
1
+ import type { Json } from "../internal/json.ts";
1
2
  import type { OutboundApi } from "../internal/outbound/api.ts";
2
3
  import type { OutboundTool } from "../tools/index.ts";
4
+ import type { InsightResult, RunOptions } from "./define.ts";
3
5
  export interface InsightToolsOptions {
4
6
  /** Offer only these insights, by tool name. Defaults to every one the adapter can serve. */
5
7
  readonly only?: readonly string[] | undefined;
@@ -17,23 +19,54 @@ export interface InsightToolsOptions {
17
19
  * its own, as `outbound mcp` names `--max-requests`.
18
20
  */
19
21
  readonly capSetting?: string | undefined;
22
+ /**
23
+ * On a combined instance, each of its tools as its own instance, as
24
+ * `outbound.workspace("provider:workspace")` gives them (`membersOf`).
25
+ * With them an insight that only some tools can serve is offered too: one
26
+ * that takes a campaign answers for the campaigns of the tools that serve
27
+ * it and refuses the others' before any request, and one that reads every
28
+ * campaign answers for the one tool that serves it, marked incomplete.
29
+ */
30
+ readonly members?: readonly OutboundApi[] | undefined;
20
31
  }
21
32
  /** The most an insight tool call may send when no cap is set, whatever its input. */
22
33
  export declare const INSIGHT_TOOL_CEILING = 500;
34
+ /** Each tool of a combined instance as its own instance; none for any other instance. */
35
+ export declare const membersOf: (outbound: OutboundApi) => Promise<OutboundApi[]>;
36
+ /** Where an insight runs on this instance, and the tools of a combined one that can serve it. */
37
+ interface Placement {
38
+ /** The instance the insight runs on: this one, or the one tool that serves it. */
39
+ readonly target: OutboundApi;
40
+ /** On a combined instance the insight cannot serve as a whole, the tools that can. */
41
+ readonly servers: readonly OutboundApi[];
42
+ }
43
+ /** The insight entry by its tool name, and where it runs here; `undefined` when it is no insight or cannot run. */
44
+ export declare const insightPlacement: (outbound: OutboundApi, name: string, members: readonly OutboundApi[]) => (Placement & {
45
+ readonly note: string | null;
46
+ }) | undefined;
23
47
  /**
24
48
  * Why `insightTools` leaves an insight out on this instance, in the words of
25
49
  * an `Unsupported` error. `undefined` for a name that is no insight, or one
26
50
  * the instance offers.
27
51
  */
28
- export declare const insightLeftOutReason: (outbound: OutboundApi, name: string) => string | undefined;
52
+ export declare const insightLeftOutReason: (outbound: OutboundApi, name: string, members?: readonly OutboundApi[]) => string | undefined;
29
53
  /**
30
54
  * The insights this instance can serve, as tools. An insight whose adapter
31
55
  * lacks a capability or a field it needs, or that cannot match records while the redact
32
56
  * plugin masks what it matches on, is left out, so a model is never offered a
33
- * tool that cannot work. A `next` hint naming a left-out insight is dropped.
57
+ * tool that cannot work; on a combined instance, `members` brings back what
58
+ * one of its tools can serve. A `next` hint naming a left-out insight is
59
+ * dropped, in the tool's `next` and in every `next` its answer holds.
34
60
  *
35
61
  * ```ts
36
62
  * openaiTools(outbound, { extra: insightTools(outbound) });
37
63
  * ```
38
64
  */
39
65
  export declare const insightTools: (outbound: OutboundApi, options?: InsightToolsOptions) => OutboundTool[];
66
+ /**
67
+ * Runs the insight where it runs here: on a combined instance, one that only
68
+ * one of its tools serves runs on that tool, its answer marked incomplete
69
+ * with a note naming the others.
70
+ */
71
+ export declare const runPlaced: (outbound: OutboundApi, name: string, input: Json | undefined, members: readonly OutboundApi[], options?: RunOptions) => Promise<InsightResult<Json>>;
72
+ export {};
@@ -42,7 +42,7 @@ import {
42
42
  refTo,
43
43
  refsTo
44
44
  } from "../chunks/chunk-U5AK6OJM.js";
45
- import "../chunks/chunk-HXCZMMSD.js";
45
+ import "../chunks/chunk-NLYGMVXS.js";
46
46
  import {
47
47
  emptyCounts,
48
48
  metricRow,
@@ -630,7 +630,7 @@ var caveats = [
630
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.",
631
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.",
632
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.",
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 (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.`,
634
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.",
635
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.",
636
636
  "Whether reply_count includes automatic replies is not documented; replied uses the unique reply count and repliedAuto the unique automatic count.",
@@ -787,20 +787,27 @@ var toLead = (identity, raw, labels = NO_LABELS) => ({
787
787
  var SCHEDULED = 4;
788
788
  var RECEIVED = 2;
789
789
  var SENT_BY_HAND = 3;
790
- var leadOf = (raw) => emailAddress(raw.lead) ?? (count(raw.ue_type) === RECEIVED ? emailAddress(raw.from_address_email) : null) ?? text(raw.lead_id);
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
+ };
791
797
  var uniboxUrl = (raw) => {
792
798
  const thread = text(raw.thread_id);
793
799
  const workspace = text(raw.organization_id);
794
800
  return thread === null || workspace === null ? null : `https://app.instantly.ai/app/unibox?thread_search=thread:${encodeURIComponent(thread)}&selected_wks=${encodeURIComponent(workspace)}`;
795
801
  };
796
- var messageFields = (identity, raw, includeBody) => {
802
+ var messageFields = (identity, raw, includeBody, leadIds) => {
797
803
  const body = field(raw.body, "html") ?? field(raw.body, "text");
798
804
  return {
799
805
  ...recordBase(identity, text(raw.id) ?? "", raw),
800
806
  ...normalizeBody(text(body), includeBody),
801
807
  campaignRef: refTo(identity, text(raw.campaign_id)),
802
808
  channel: "email",
803
- leadRef: refTo(identity, leadOf(raw)),
809
+ leadEmail: leadAddressOf(raw),
810
+ leadRef: refTo(identity, leadIdOf(raw, leadIds)),
804
811
  senderRef: refTo(identity, emailAddress(raw.eaccount)),
805
812
  sentAt: timestamp(raw.timestamp_email) ?? timestamp(raw.timestamp_created),
806
813
  subject: text(raw.subject),
@@ -827,25 +834,28 @@ var autoOf = (raw, mapped) => {
827
834
  leftCompany: verdict.leftCompany
828
835
  };
829
836
  };
830
- var toMessage = (identity, raw, includeBody) => {
837
+ var toMessage = (identity, raw, includeBody, leadIds = NO_LEAD_IDS) => {
831
838
  if (count(raw.ue_type) !== RECEIVED) {
832
- return { ...messageFields(identity, raw, includeBody), direction: "out" };
839
+ return {
840
+ ...messageFields(identity, raw, includeBody, leadIds),
841
+ direction: "out"
842
+ };
833
843
  }
834
844
  const { isAuto, isAutoSource } = autoOf(
835
845
  raw,
836
846
  category(raw.i_status, NO_LABELS)
837
847
  );
838
848
  return {
839
- ...messageFields(identity, raw, includeBody),
849
+ ...messageFields(identity, raw, includeBody, leadIds),
840
850
  direction: "in",
841
851
  isAuto,
842
852
  isAutoSource
843
853
  };
844
854
  };
845
- var toReply = (identity, raw, includeBody, labels = NO_LABELS) => {
855
+ var toReply = (identity, raw, includeBody, labels = NO_LABELS, leadIds = NO_LEAD_IDS) => {
846
856
  const mapped = category(raw.i_status, labels);
847
857
  return {
848
- ...messageFields(identity, raw, includeBody),
858
+ ...messageFields(identity, raw, includeBody, leadIds),
849
859
  category: mapped ?? "unknown",
850
860
  categorySource: mapped === void 0 ? null : "vendor",
851
861
  direction: "in",
@@ -984,6 +994,66 @@ var accountReaders = (client) => {
984
994
  };
985
995
  };
986
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
+
987
1057
  // src/instantly/thread.ts
988
1058
  var timeOf = (message) => message.sentAt === null ? Number.NaN : Date.parse(message.sentAt);
989
1059
  var answering = (message, answered) => {
@@ -1022,27 +1092,36 @@ var withAnsweredSteps = (messages) => {
1022
1092
  // src/instantly/adapter-mail.ts
1023
1093
  var emailCursor = (next) => ({
1024
1094
  after: text(field(next, "after")) ?? void 0,
1095
+ campaign: text(field(next, "campaign")) ?? void 0,
1096
+ id: text(field(next, "id")) ?? void 0,
1025
1097
  lead: text(field(next, "lead")) ?? void 0
1026
1098
  });
1027
- var leadAddress = async (client, ctx, leadId, cursor) => {
1028
- if (leadId === void 0 || cursor.lead !== void 0) {
1029
- 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;
1030
1105
  }
1031
1106
  const given = emailAddress(leadId);
1032
1107
  if (given !== null) {
1033
- return given;
1108
+ return { address: given, campaign: void 0, id: void 0 };
1034
1109
  }
1035
1110
  const lead = await client.getObject(
1036
1111
  ctx,
1037
1112
  `/leads/${encodeURIComponent(leadId)}`
1038
1113
  );
1039
- const address = text(lead.email);
1114
+ const address = emailAddress(lead.email);
1040
1115
  if (address === null) {
1041
1116
  throw new OutboundError("NotFound", `Lead ${leadId} has no email address`, {
1042
1117
  provider: client.identity.provider
1043
1118
  });
1044
1119
  }
1045
- return address;
1120
+ return {
1121
+ address,
1122
+ campaign: text(lead.campaign) ?? void 0,
1123
+ id: leadId
1124
+ };
1046
1125
  };
1047
1126
  var withFullBody = async (client, ctx, item) => {
1048
1127
  const id = text(item.id);
@@ -1050,21 +1129,27 @@ var withFullBody = async (client, ctx, item) => {
1050
1129
  lane: EMAILS_LANE
1051
1130
  });
1052
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
+ };
1053
1138
  var listEmails = async (client, ctx, query, received) => {
1054
1139
  const cursor = emailCursor(query.next);
1055
1140
  const leadId = "leadId" in query ? query.leadId : void 0;
1056
1141
  const threadId = "threadId" in query ? query.threadId : void 0;
1057
1142
  const byHand = "byHand" in query && query.byHand === true;
1058
1143
  const sentByHand = byHand ? "manual" : void 0;
1059
- const lead = await leadAddress(client, ctx, leadId, cursor);
1144
+ const lead = await timelineLead(client, ctx, leadId, cursor);
1060
1145
  const envelope = listEnvelope(
1061
1146
  await client.get(ctx, "/emails", {
1062
1147
  lane: EMAILS_LANE,
1063
1148
  query: {
1064
- campaign_id: query.campaignId,
1149
+ campaign_id: query.campaignId ?? lead?.campaign,
1065
1150
  email_type: received ? "received" : sentByHand,
1066
1151
  is_unread: "unread" in query ? query.unread : void 0,
1067
- lead,
1152
+ lead: lead?.address,
1068
1153
  limit: pageSize(query.limit),
1069
1154
  max_timestamp_created: query.until,
1070
1155
  min_timestamp_created: query.since,
@@ -1082,7 +1167,8 @@ var listEmails = async (client, ctx, query, received) => {
1082
1167
  items: query.includeBody ? await Promise.all(
1083
1168
  sent.map(async (item) => await withFullBody(client, ctx, item))
1084
1169
  ) : sent,
1085
- 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)
1086
1172
  };
1087
1173
  };
1088
1174
  var mailReaders = (client) => ({
@@ -1090,7 +1176,7 @@ var mailReaders = (client) => ({
1090
1176
  const page = await listEmails(client, ctx, query, false);
1091
1177
  const mapped = mapPage(
1092
1178
  page,
1093
- (item) => toMessage(client.identity, item, query.includeBody)
1179
+ (item) => toMessage(client.identity, item, query.includeBody, page.leadIds)
1094
1180
  );
1095
1181
  return { ...mapped, items: withAnsweredSteps(mapped.items) };
1096
1182
  },
@@ -1102,7 +1188,7 @@ var mailReaders = (client) => ({
1102
1188
  page.items.map((item) => item.i_status)
1103
1189
  );
1104
1190
  const replies = page.items.map(
1105
- (item) => toReply(client.identity, item, query.includeBody, labels)
1191
+ (item) => toReply(client.identity, item, query.includeBody, labels, page.leadIds)
1106
1192
  );
1107
1193
  return {
1108
1194
  // One i_status value fits in the query but a category maps to several, so
@@ -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;
@@ -294,6 +294,7 @@ export declare const messageSchema: z.ZodObject<{
294
294
  email: "email";
295
295
  linkedin: "linkedin";
296
296
  }>;
297
+ leadEmail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
297
298
  leadRef: z.ZodNullable<z.ZodString>;
298
299
  senderRef: z.ZodNullable<z.ZodString>;
299
300
  sentAt: z.ZodNullable<z.ZodISODateTime>;
@@ -312,7 +313,8 @@ export declare const messageSchema: z.ZodObject<{
312
313
  export type Message = z.infer<typeof messageSchema>;
313
314
  /**
314
315
  * One received message, not one person: a lead who replies twice in a thread
315
- * is two replies. Count people by `leadRef`, as `MetricRow.replied` does.
316
+ * is two replies. Count people by `leadEmail` where it is present, since
317
+ * one person in two campaigns is two leads, and otherwise by `leadRef`.
316
318
  */
317
319
  export declare const replySchema: z.ZodObject<{
318
320
  category: z.ZodEnum<{
@@ -344,6 +346,7 @@ export declare const replySchema: z.ZodObject<{
344
346
  email: "email";
345
347
  linkedin: "linkedin";
346
348
  }>;
349
+ leadEmail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
347
350
  leadRef: z.ZodNullable<z.ZodString>;
348
351
  senderRef: z.ZodNullable<z.ZodString>;
349
352
  sentAt: z.ZodNullable<z.ZodISODateTime>;
@@ -191,6 +191,7 @@ export declare const RECORD_SCHEMAS: {
191
191
  email: "email";
192
192
  linkedin: "linkedin";
193
193
  }>;
194
+ leadEmail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
194
195
  leadRef: z.ZodNullable<z.ZodString>;
195
196
  senderRef: z.ZodNullable<z.ZodString>;
196
197
  sentAt: z.ZodNullable<z.ZodISODateTime>;
@@ -315,6 +316,7 @@ export declare const RECORD_SCHEMAS: {
315
316
  email: "email";
316
317
  linkedin: "linkedin";
317
318
  }>;
319
+ leadEmail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
318
320
  leadRef: z.ZodNullable<z.ZodString>;
319
321
  senderRef: z.ZodNullable<z.ZodString>;
320
322
  sentAt: z.ZodNullable<z.ZodISODateTime>;
@@ -1,25 +1,42 @@
1
1
  import type { Reply, ReplyCategory } from "./entities.ts";
2
- type Counted = Pick<Reply, "leadRef" | "threadId">;
2
+ type Counted = Pick<Reply, "isAuto" | "leadEmail" | "leadRef" | "threadId">;
3
3
  export interface ReplyCounts {
4
4
  /** Reply messages. */
5
5
  readonly messages: number;
6
- /** Distinct `leadRef`s. `null` when any reply has no `leadRef`. */
6
+ /**
7
+ * Distinct people, by `leadEmail` or else `leadRef`. `null` when any
8
+ * reply has neither.
9
+ */
7
10
  readonly people: number | null;
8
11
  /** Distinct `threadId`s. `null` when any reply has no `threadId`. */
9
12
  readonly threads: number | null;
13
+ /**
14
+ * Replies flagged automatic (`isAuto: true`), counted among `messages`,
15
+ * so a category count can leave them out. `null` when any reply's
16
+ * `isAuto` is unknown.
17
+ */
18
+ readonly automatic: number | null;
10
19
  }
11
20
  /** How many messages, people and threads a list of replies holds. */
12
21
  export declare const countReplies: (replies: readonly Counted[]) => ReplyCounts;
13
- /** `40 messages from 21 people in 9 threads`, leaving out what is unknown. */
22
+ /**
23
+ * `40 messages from 21 people in 9 threads, 4 of them automatic`, leaving out
24
+ * what is unknown.
25
+ */
14
26
  export declare const describeReplyCounts: (counts: ReplyCounts) => string;
15
27
  /** One person's replies, from `repliesByPerson`. */
16
28
  export interface ReplyPerson {
17
29
  /**
18
30
  * The lead who sent them. `null` for replies with no lead: those are
19
- * grouped by thread instead, one row per thread.
31
+ * grouped by thread instead, one row per thread. A person in two
32
+ * campaigns is two leads; this is the first one's.
20
33
  */
21
34
  readonly leadRef: string | null;
35
+ /** Their address, where the vendor names one. */
36
+ readonly leadEmail: string | null;
22
37
  readonly messages: number;
38
+ /** Of `messages`, those flagged automatic. `null` when any one's `isAuto` is unknown. */
39
+ readonly automatic: number | null;
23
40
  /** The earliest and latest `sentAt`. `null` when no reply has one. */
24
41
  readonly firstAt: string | null;
25
42
  readonly lastAt: string | null;
@@ -28,10 +45,11 @@ export interface ReplyPerson {
28
45
  /** Each thread the replies are in, in the order first seen. */
29
46
  readonly threadIds: readonly string[];
30
47
  }
31
- type Grouped = Pick<Reply, "category" | "leadRef" | "sentAt" | "threadId">;
48
+ type Grouped = Pick<Reply, "category" | "isAuto" | "leadEmail" | "leadRef" | "sentAt" | "threadId">;
32
49
  /**
33
- * One row per person, in the order each person first appears. A reply with
34
- * no `leadRef` is grouped by its thread, or stands alone without one.
50
+ * One row per person, by `leadEmail` or else `leadRef`, in the order each
51
+ * person first appears. A reply with neither is grouped by its thread, or
52
+ * stands alone without one.
35
53
  */
36
54
  export declare const repliesByPerson: (replies: readonly Grouped[]) => ReplyPerson[];
37
55
  export {};