lumnisai 0.1.20 → 0.1.22

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.
package/dist/index.cjs CHANGED
@@ -1116,23 +1116,97 @@ class MessagingResource {
1116
1116
  }
1117
1117
  }
1118
1118
  /**
1119
- * Create drafts for multiple prospects with AI generation
1119
+ * Create drafts for multiple prospects with AI generation.
1120
+ *
1121
+ * **Default behavior (async):**
1122
+ * Returns immediately with a job_id (202 response). Poll `getBatchDraftJobStatus()`
1123
+ * for progress and results. The job continues processing in the background even
1124
+ * if the client disconnects.
1125
+ *
1126
+ * **Legacy behavior (sync):**
1127
+ * Set `wait: true` to block until completion. Not recommended for large batches
1128
+ * as the request may timeout.
1129
+ *
1130
+ * @param userId - User ID or email
1131
+ * @param request - Batch draft creation request
1132
+ * @param options - Optional parameters
1133
+ * @param options.wait - If true, wait for completion (legacy behavior)
1134
+ * @returns BatchDraftJobResponse (async) or BatchDraftResponse (sync with wait=true)
1135
+ *
1136
+ * @example
1137
+ * ```typescript
1138
+ * // Async (recommended) - returns immediately with job_id
1139
+ * const job = await client.messaging.createBatchDrafts(userId, request);
1140
+ * if ('jobId' in job) {
1141
+ * // Poll for status
1142
+ * const status = await client.messaging.getBatchDraftJobStatus(userId, job.jobId);
1143
+ * }
1144
+ *
1145
+ * // Sync (legacy) - blocks until complete
1146
+ * const result = await client.messaging.createBatchDrafts(userId, request, { wait: true });
1147
+ * console.log(result.drafts); // All drafts available immediately
1148
+ * ```
1120
1149
  */
1121
- async createBatchDrafts(userId, request) {
1150
+ async createBatchDrafts(userId, request, options) {
1122
1151
  const queryParams = new URLSearchParams();
1123
1152
  queryParams.append("user_id", userId);
1153
+ if (options?.wait) {
1154
+ queryParams.append("wait", "true");
1155
+ }
1124
1156
  return this.http.post(
1125
1157
  `/messaging/drafts/batch?${queryParams.toString()}`,
1126
1158
  request
1127
1159
  );
1128
1160
  }
1161
+ /**
1162
+ * Get status and results of a batch draft job.
1163
+ *
1164
+ * Poll this endpoint to track progress and retrieve results for batch draft jobs
1165
+ * created via `createBatchDrafts()`. Jobs are retained for 24 hours after creation.
1166
+ *
1167
+ * @param userId - User ID or email
1168
+ * @param jobId - The job ID returned from createBatchDrafts()
1169
+ * @returns BatchDraftJobStatusResponse with progress and results
1170
+ * @throws NotFoundError if job not found or expired
1171
+ *
1172
+ * @example
1173
+ * ```typescript
1174
+ * // Create job
1175
+ * const job = await client.messaging.createBatchDrafts(userId, request);
1176
+ * if ('jobId' in job) {
1177
+ * // Poll until complete
1178
+ * let status;
1179
+ * do {
1180
+ * await new Promise(r => setTimeout(r, 1000)); // Wait 1 second
1181
+ * status = await client.messaging.getBatchDraftJobStatus(userId, job.jobId);
1182
+ * console.log(`Progress: ${status.progress.percentage}%`);
1183
+ * } while (status.status !== 'completed' && status.status !== 'failed');
1184
+ *
1185
+ * console.log(`Created ${status.drafts.length} drafts`);
1186
+ * }
1187
+ * ```
1188
+ */
1189
+ async getBatchDraftJobStatus(userId, jobId) {
1190
+ const queryParams = new URLSearchParams();
1191
+ queryParams.append("user_id", userId);
1192
+ return this.http.get(
1193
+ `/messaging/drafts/batch/jobs/${encodeURIComponent(jobId)}?${queryParams.toString()}`
1194
+ );
1195
+ }
1129
1196
  /**
1130
1197
  * Create drafts for multiple prospects with real-time progress updates via Server-Sent Events (SSE).
1131
1198
  *
1132
1199
  * This method provides real-time progress updates as drafts are being created, significantly
1133
1200
  * improving user experience for large batch operations (30+ prospects).
1134
1201
  *
1202
+ * **Resilience features:**
1203
+ * - Job state is stored in Redis and survives client disconnects
1204
+ * - Background task continues processing even if SSE connection drops
1205
+ * - Client can reconnect using `jobId` option to resume streaming
1206
+ * - Poll `getBatchDraftJobStatus()` as fallback
1207
+ *
1135
1208
  * **Event Types:**
1209
+ * - `job_started`: First event with job_id for reconnection
1136
1210
  * - `progress`: Progress update with percentage and current prospect
1137
1211
  * - `draft_created`: Draft successfully created
1138
1212
  * - `error`: Error occurred for a specific prospect
@@ -1140,6 +1214,8 @@ class MessagingResource {
1140
1214
  *
1141
1215
  * **Example:**
1142
1216
  * ```typescript
1217
+ * let savedJobId: string | undefined;
1218
+ *
1143
1219
  * const result = await client.messaging.createBatchDraftsStream(
1144
1220
  * 'user@example.com',
1145
1221
  * {
@@ -1148,6 +1224,9 @@ class MessagingResource {
1148
1224
  * useAiGeneration: true
1149
1225
  * },
1150
1226
  * {
1227
+ * onJobStarted: (jobId) => {
1228
+ * savedJobId = jobId; // Save for reconnection if disconnected
1229
+ * },
1151
1230
  * onProgress: (processed, total, percentage, prospectName) => {
1152
1231
  * console.log(`${percentage}% - ${prospectName}`)
1153
1232
  * },
@@ -1167,11 +1246,16 @@ class MessagingResource {
1167
1246
  * @param userId - User ID or email
1168
1247
  * @param request - Batch draft creation request
1169
1248
  * @param callbacks - Optional callbacks for stream events
1249
+ * @param options - Optional parameters
1250
+ * @param options.jobId - Existing job ID to resume streaming (for reconnection)
1170
1251
  * @returns Final result with created drafts and error details
1171
1252
  */
1172
- async createBatchDraftsStream(userId, request, callbacks) {
1253
+ async createBatchDraftsStream(userId, request, callbacks, options) {
1173
1254
  const queryParams = new URLSearchParams();
1174
1255
  queryParams.append("user_id", userId);
1256
+ if (options?.jobId) {
1257
+ queryParams.append("job_id", options.jobId);
1258
+ }
1175
1259
  const baseUrl = this.http.options.baseUrl;
1176
1260
  const apiPrefix = this.http.options.apiPrefix || "";
1177
1261
  const path = `/messaging/drafts/batch/stream?${queryParams.toString()}`;
@@ -1237,6 +1321,11 @@ class MessagingResource {
1237
1321
  const eventData = JSON.parse(line.slice(6));
1238
1322
  const { event, data } = eventData;
1239
1323
  switch (event) {
1324
+ case "job_started": {
1325
+ const jobData = toCamelCase(data);
1326
+ callbacks?.onJobStarted?.(jobData.jobId || "");
1327
+ break;
1328
+ }
1240
1329
  case "progress": {
1241
1330
  const progressData = toCamelCase(data);
1242
1331
  callbacks?.onProgress?.(
@@ -1291,8 +1380,15 @@ class MessagingResource {
1291
1380
  *
1292
1381
  * This method yields events as they arrive, providing more control over event handling.
1293
1382
  *
1383
+ * **Resilience features:**
1384
+ * - Job state is stored in Redis and survives client disconnects
1385
+ * - First event is `job_started` with job_id for reconnection
1386
+ * - Client can reconnect using `jobId` option to resume streaming
1387
+ *
1294
1388
  * **Example:**
1295
1389
  * ```typescript
1390
+ * let savedJobId: string | undefined;
1391
+ *
1296
1392
  * for await (const event of client.messaging.createBatchDraftsStreamGenerator(
1297
1393
  * 'user@example.com',
1298
1394
  * {
@@ -1302,6 +1398,9 @@ class MessagingResource {
1302
1398
  * }
1303
1399
  * )) {
1304
1400
  * switch (event.event) {
1401
+ * case 'job_started':
1402
+ * savedJobId = event.data.jobId; // Save for reconnection
1403
+ * break;
1305
1404
  * case 'progress':
1306
1405
  * console.log(`Progress: ${event.data.percentage}%`)
1307
1406
  * break
@@ -1320,12 +1419,17 @@ class MessagingResource {
1320
1419
  *
1321
1420
  * @param userId - User ID or email
1322
1421
  * @param request - Batch draft creation request
1422
+ * @param options - Optional parameters
1423
+ * @param options.jobId - Existing job ID to resume streaming (for reconnection)
1323
1424
  * @yields Stream events with 'event' and 'data' keys
1324
1425
  * @returns Final result with created drafts and error details
1325
1426
  */
1326
- async *createBatchDraftsStreamGenerator(userId, request) {
1427
+ async *createBatchDraftsStreamGenerator(userId, request, options) {
1327
1428
  const queryParams = new URLSearchParams();
1328
1429
  queryParams.append("user_id", userId);
1430
+ if (options?.jobId) {
1431
+ queryParams.append("job_id", options.jobId);
1432
+ }
1329
1433
  const baseUrl = this.http.options.baseUrl;
1330
1434
  const apiPrefix = this.http.options.apiPrefix || "";
1331
1435
  const path = `/messaging/drafts/batch/stream?${queryParams.toString()}`;
@@ -1434,6 +1538,48 @@ class MessagingResource {
1434
1538
  request
1435
1539
  );
1436
1540
  }
1541
+ /**
1542
+ * Cancel a queued draft.
1543
+ *
1544
+ * This cancels a draft that was queued for later sending (status='scheduled').
1545
+ * The draft status will be set to 'discarded' and removed from the send queue.
1546
+ *
1547
+ * Can also cancel drafts in 'pending_review' or 'approved' status.
1548
+ *
1549
+ * @param userId - User ID or email
1550
+ * @param draftId - Draft UUID to cancel
1551
+ * @returns CancelDraftResponse with success status
1552
+ * @throws MessagingValidationError if draft cannot be cancelled (already sent, etc.)
1553
+ * @throws MessagingNotFoundError if draft not found
1554
+ *
1555
+ * @example
1556
+ * ```typescript
1557
+ * // Cancel a queued draft
1558
+ * const result = await client.messaging.cancelDraft('user@example.com', 'draft-uuid');
1559
+ * if (result.success) {
1560
+ * console.log(`Draft cancelled: ${result.draftId}`);
1561
+ * }
1562
+ * ```
1563
+ */
1564
+ async cancelDraft(userId, draftId) {
1565
+ try {
1566
+ const queryParams = new URLSearchParams();
1567
+ queryParams.append("user_id", userId);
1568
+ return await this.http.post(
1569
+ `/messaging/drafts/${encodeURIComponent(draftId)}/cancel?${queryParams.toString()}`
1570
+ );
1571
+ } catch (error) {
1572
+ if (error instanceof NotFoundError) {
1573
+ throw new MessagingNotFoundError(`Draft not found: ${draftId}`);
1574
+ }
1575
+ if (error instanceof ValidationError) {
1576
+ throw new MessagingValidationError(
1577
+ error.message || `Cannot cancel draft: ${draftId}`
1578
+ );
1579
+ }
1580
+ throw error;
1581
+ }
1582
+ }
1437
1583
  /**
1438
1584
  * Delete a single conversation and all its messages.
1439
1585
  *
@@ -2680,6 +2826,13 @@ var SyncJobStatus = /* @__PURE__ */ ((SyncJobStatus2) => {
2680
2826
  SyncJobStatus2["FAILED"] = "failed";
2681
2827
  return SyncJobStatus2;
2682
2828
  })(SyncJobStatus || {});
2829
+ var BatchJobStatus = /* @__PURE__ */ ((BatchJobStatus2) => {
2830
+ BatchJobStatus2["PENDING"] = "pending";
2831
+ BatchJobStatus2["IN_PROGRESS"] = "in_progress";
2832
+ BatchJobStatus2["COMPLETED"] = "completed";
2833
+ BatchJobStatus2["FAILED"] = "failed";
2834
+ return BatchJobStatus2;
2835
+ })(BatchJobStatus || {});
2683
2836
  var QueueItemStatus = /* @__PURE__ */ ((QueueItemStatus2) => {
2684
2837
  QueueItemStatus2["QUEUED"] = "queued";
2685
2838
  QueueItemStatus2["PROCESSING"] = "processing";
@@ -2815,6 +2968,7 @@ function verifyWebhookSignature(payload, signature, secret) {
2815
2968
 
2816
2969
  exports.ACTION_DELAYS = ACTION_DELAYS;
2817
2970
  exports.AuthenticationError = AuthenticationError;
2971
+ exports.BatchJobStatus = BatchJobStatus;
2818
2972
  exports.ChannelType = ChannelType;
2819
2973
  exports.ConversationStatus = ConversationStatus;
2820
2974
  exports.DraftStatus = DraftStatus;
package/dist/index.d.cts CHANGED
@@ -1407,6 +1407,15 @@ declare enum SyncJobStatus {
1407
1407
  COMPLETED = "completed",
1408
1408
  FAILED = "failed"
1409
1409
  }
1410
+ /**
1411
+ * Batch job status types (for batch draft jobs)
1412
+ */
1413
+ declare enum BatchJobStatus {
1414
+ PENDING = "pending",
1415
+ IN_PROGRESS = "in_progress",
1416
+ COMPLETED = "completed",
1417
+ FAILED = "failed"
1418
+ }
1410
1419
  /**
1411
1420
  * Queue item status types
1412
1421
  */
@@ -1557,6 +1566,23 @@ interface ProspectInfo {
1557
1566
  outreachMethod?: 'direct_message' | 'connection_request' | 'inmail' | 'email' | null;
1558
1567
  /** Whether the user is already connected to this prospect on LinkedIn */
1559
1568
  isConnected?: boolean | null;
1569
+ /**
1570
+ * Override batch-level usePriorContact setting for this prospect.
1571
+ * - `true`: Check for prior contact and include in AI context
1572
+ * - `false`: Don't check for prior contact
1573
+ * - `null`/`undefined`: Use batch-level setting
1574
+ */
1575
+ usePriorContact?: boolean | null;
1576
+ /**
1577
+ * Override/extend batch-level aiContext for this prospect.
1578
+ * Merged with batch context (prospect keys take precedence).
1579
+ */
1580
+ aiContext?: Record<string, any> | null;
1581
+ /**
1582
+ * Queue priority (0-10). Higher = processed first when rate limited.
1583
+ * @default 0
1584
+ */
1585
+ priority?: number;
1560
1586
  }
1561
1587
  /**
1562
1588
  * Request to create batch drafts
@@ -1569,15 +1595,30 @@ interface BatchDraftRequest {
1569
1595
  subjectTemplate?: string | null;
1570
1596
  contentTemplate?: string | null;
1571
1597
  useAiGeneration?: boolean;
1598
+ /**
1599
+ * If true and useAiGeneration=true, check for prior contact with each prospect
1600
+ * and include conversation history in AI context for more personalized messages.
1601
+ * Can be overridden per-prospect via ProspectInfo.usePriorContact.
1602
+ * @default true
1603
+ */
1604
+ usePriorContact?: boolean;
1572
1605
  aiContext?: Record<string, any> | null;
1573
1606
  organizationId?: string | null;
1574
1607
  }
1575
1608
  /**
1576
- * Request to batch send drafts
1609
+ * Request to batch send drafts with optional rate limiting and queue priority.
1577
1610
  */
1578
1611
  interface BatchSendRequest {
1579
1612
  draftIds: string[];
1613
+ /**
1614
+ * Daily send limit (1-100). If not provided, uses subscription-based limits for LinkedIn.
1615
+ */
1580
1616
  sendRatePerDay?: number;
1617
+ /**
1618
+ * Queue priority (0-10). Higher = processed first. Only applies to rate-limited items.
1619
+ * @default 0
1620
+ */
1621
+ priority?: number;
1581
1622
  }
1582
1623
  /**
1583
1624
  * Request to update LinkedIn subscription
@@ -1776,6 +1817,7 @@ interface EmailThreadSummary {
1776
1817
  */
1777
1818
  interface DraftResponse {
1778
1819
  id: string;
1820
+ /** Draft status: 'pending_review' | 'approved' | 'scheduled' | 'sending' | 'sent' | 'failed' | 'discarded' */
1779
1821
  status: string;
1780
1822
  content: string;
1781
1823
  createdAt: string;
@@ -1785,9 +1827,13 @@ interface DraftResponse {
1785
1827
  outreachMethod?: 'direct_message' | 'connection_request' | 'inmail' | 'email' | null;
1786
1828
  /** Subject line for email drafts (optional) */
1787
1829
  subject?: string | null;
1830
+ /** ISO timestamp when queued message will be sent (if status is 'scheduled') */
1831
+ scheduledFor?: string | null;
1832
+ /** Error details if status is 'failed' */
1833
+ errorMessage?: string | null;
1788
1834
  }
1789
1835
  /**
1790
- * Response from batch draft creation
1836
+ * Response from batch draft creation (legacy synchronous mode)
1791
1837
  */
1792
1838
  interface BatchDraftResponse {
1793
1839
  drafts: DraftResponse[];
@@ -1795,6 +1841,48 @@ interface BatchDraftResponse {
1795
1841
  errors: number;
1796
1842
  errorDetails?: Array<Record<string, any>> | null;
1797
1843
  }
1844
+ /**
1845
+ * Response when batch draft job is queued (async mode, 202 response).
1846
+ * Poll GET /drafts/batch/jobs/{jobId} for progress and results.
1847
+ */
1848
+ interface BatchDraftJobResponse {
1849
+ jobId: string;
1850
+ status: string;
1851
+ totalProspects: number;
1852
+ pollUrl: string;
1853
+ message?: string;
1854
+ }
1855
+ /**
1856
+ * Progress information for a batch job
1857
+ */
1858
+ interface BatchDraftJobProgress {
1859
+ processed: number;
1860
+ total: number;
1861
+ percentage: number;
1862
+ draftsCreated: number;
1863
+ errors: number;
1864
+ }
1865
+ /**
1866
+ * Response for GET /drafts/batch/jobs/{jobId} (polling endpoint)
1867
+ */
1868
+ interface BatchDraftJobStatusResponse {
1869
+ jobId: string;
1870
+ status: string;
1871
+ progress: BatchDraftJobProgress;
1872
+ drafts: DraftResponse[];
1873
+ errors: Array<Record<string, any>>;
1874
+ createdAt: string;
1875
+ startedAt?: string | null;
1876
+ completedAt?: string | null;
1877
+ errorMessage?: string | null;
1878
+ }
1879
+ /**
1880
+ * Job started event data from streaming batch draft creation.
1881
+ * First event emitted, contains job_id for reconnection.
1882
+ */
1883
+ interface BatchDraftJobStartedData {
1884
+ jobId: string;
1885
+ }
1798
1886
  /**
1799
1887
  * Progress event data from streaming batch draft creation
1800
1888
  */
@@ -1822,6 +1910,7 @@ interface BatchDraftErrorData {
1822
1910
  * Complete event data from streaming batch draft creation
1823
1911
  */
1824
1912
  interface BatchDraftCompleteData {
1913
+ jobId?: string;
1825
1914
  created: number;
1826
1915
  errors: number;
1827
1916
  drafts: DraftResponse[];
@@ -1829,22 +1918,25 @@ interface BatchDraftCompleteData {
1829
1918
  prospect: string;
1830
1919
  error: string;
1831
1920
  }>;
1921
+ errorMessage?: string | null;
1832
1922
  }
1833
1923
  /**
1834
1924
  * Stream event types for batch draft creation
1835
1925
  */
1836
- type BatchDraftStreamEventType = 'progress' | 'draft_created' | 'error' | 'complete';
1926
+ type BatchDraftStreamEventType = 'job_started' | 'progress' | 'draft_created' | 'error' | 'complete';
1837
1927
  /**
1838
1928
  * Stream event from batch draft creation
1839
1929
  */
1840
1930
  interface BatchDraftStreamEvent {
1841
1931
  event: BatchDraftStreamEventType;
1842
- data: BatchDraftProgressData | BatchDraftCreatedData | BatchDraftErrorData | BatchDraftCompleteData;
1932
+ data: BatchDraftJobStartedData | BatchDraftProgressData | BatchDraftCreatedData | BatchDraftErrorData | BatchDraftCompleteData;
1843
1933
  }
1844
1934
  /**
1845
1935
  * Callbacks for batch draft streaming
1846
1936
  */
1847
1937
  interface BatchDraftStreamCallbacks {
1938
+ /** Callback when job starts, provides job_id for reconnection if disconnected */
1939
+ onJobStarted?: (jobId: string) => void;
1848
1940
  /** Callback for progress updates */
1849
1941
  onProgress?: (processed: number, total: number, percentage: number, prospectName: string) => void;
1850
1942
  /** Callback when a draft is created */
@@ -1887,6 +1979,15 @@ interface BatchSendResponse {
1887
1979
  failed: number;
1888
1980
  queued: number;
1889
1981
  }
1982
+ /**
1983
+ * Response from cancelling a draft
1984
+ */
1985
+ interface CancelDraftResponse {
1986
+ success: boolean;
1987
+ draftId?: string;
1988
+ prospectExternalId?: string | null;
1989
+ error?: string;
1990
+ }
1890
1991
  /**
1891
1992
  * Response from deleting a single conversation
1892
1993
  */
@@ -2191,16 +2292,83 @@ declare class MessagingResource {
2191
2292
  */
2192
2293
  getDraft(userId: string, draftId: string): Promise<DraftResponse>;
2193
2294
  /**
2194
- * Create drafts for multiple prospects with AI generation
2295
+ * Create drafts for multiple prospects with AI generation.
2296
+ *
2297
+ * **Default behavior (async):**
2298
+ * Returns immediately with a job_id (202 response). Poll `getBatchDraftJobStatus()`
2299
+ * for progress and results. The job continues processing in the background even
2300
+ * if the client disconnects.
2301
+ *
2302
+ * **Legacy behavior (sync):**
2303
+ * Set `wait: true` to block until completion. Not recommended for large batches
2304
+ * as the request may timeout.
2305
+ *
2306
+ * @param userId - User ID or email
2307
+ * @param request - Batch draft creation request
2308
+ * @param options - Optional parameters
2309
+ * @param options.wait - If true, wait for completion (legacy behavior)
2310
+ * @returns BatchDraftJobResponse (async) or BatchDraftResponse (sync with wait=true)
2311
+ *
2312
+ * @example
2313
+ * ```typescript
2314
+ * // Async (recommended) - returns immediately with job_id
2315
+ * const job = await client.messaging.createBatchDrafts(userId, request);
2316
+ * if ('jobId' in job) {
2317
+ * // Poll for status
2318
+ * const status = await client.messaging.getBatchDraftJobStatus(userId, job.jobId);
2319
+ * }
2320
+ *
2321
+ * // Sync (legacy) - blocks until complete
2322
+ * const result = await client.messaging.createBatchDrafts(userId, request, { wait: true });
2323
+ * console.log(result.drafts); // All drafts available immediately
2324
+ * ```
2325
+ */
2326
+ createBatchDrafts(userId: string, request: BatchDraftRequest, options?: {
2327
+ wait?: boolean;
2328
+ }): Promise<BatchDraftJobResponse | BatchDraftResponse>;
2329
+ /**
2330
+ * Get status and results of a batch draft job.
2331
+ *
2332
+ * Poll this endpoint to track progress and retrieve results for batch draft jobs
2333
+ * created via `createBatchDrafts()`. Jobs are retained for 24 hours after creation.
2334
+ *
2335
+ * @param userId - User ID or email
2336
+ * @param jobId - The job ID returned from createBatchDrafts()
2337
+ * @returns BatchDraftJobStatusResponse with progress and results
2338
+ * @throws NotFoundError if job not found or expired
2339
+ *
2340
+ * @example
2341
+ * ```typescript
2342
+ * // Create job
2343
+ * const job = await client.messaging.createBatchDrafts(userId, request);
2344
+ * if ('jobId' in job) {
2345
+ * // Poll until complete
2346
+ * let status;
2347
+ * do {
2348
+ * await new Promise(r => setTimeout(r, 1000)); // Wait 1 second
2349
+ * status = await client.messaging.getBatchDraftJobStatus(userId, job.jobId);
2350
+ * console.log(`Progress: ${status.progress.percentage}%`);
2351
+ * } while (status.status !== 'completed' && status.status !== 'failed');
2352
+ *
2353
+ * console.log(`Created ${status.drafts.length} drafts`);
2354
+ * }
2355
+ * ```
2195
2356
  */
2196
- createBatchDrafts(userId: string, request: BatchDraftRequest): Promise<BatchDraftResponse>;
2357
+ getBatchDraftJobStatus(userId: string, jobId: string): Promise<BatchDraftJobStatusResponse>;
2197
2358
  /**
2198
2359
  * Create drafts for multiple prospects with real-time progress updates via Server-Sent Events (SSE).
2199
2360
  *
2200
2361
  * This method provides real-time progress updates as drafts are being created, significantly
2201
2362
  * improving user experience for large batch operations (30+ prospects).
2202
2363
  *
2364
+ * **Resilience features:**
2365
+ * - Job state is stored in Redis and survives client disconnects
2366
+ * - Background task continues processing even if SSE connection drops
2367
+ * - Client can reconnect using `jobId` option to resume streaming
2368
+ * - Poll `getBatchDraftJobStatus()` as fallback
2369
+ *
2203
2370
  * **Event Types:**
2371
+ * - `job_started`: First event with job_id for reconnection
2204
2372
  * - `progress`: Progress update with percentage and current prospect
2205
2373
  * - `draft_created`: Draft successfully created
2206
2374
  * - `error`: Error occurred for a specific prospect
@@ -2208,6 +2376,8 @@ declare class MessagingResource {
2208
2376
  *
2209
2377
  * **Example:**
2210
2378
  * ```typescript
2379
+ * let savedJobId: string | undefined;
2380
+ *
2211
2381
  * const result = await client.messaging.createBatchDraftsStream(
2212
2382
  * 'user@example.com',
2213
2383
  * {
@@ -2216,6 +2386,9 @@ declare class MessagingResource {
2216
2386
  * useAiGeneration: true
2217
2387
  * },
2218
2388
  * {
2389
+ * onJobStarted: (jobId) => {
2390
+ * savedJobId = jobId; // Save for reconnection if disconnected
2391
+ * },
2219
2392
  * onProgress: (processed, total, percentage, prospectName) => {
2220
2393
  * console.log(`${percentage}% - ${prospectName}`)
2221
2394
  * },
@@ -2235,16 +2408,27 @@ declare class MessagingResource {
2235
2408
  * @param userId - User ID or email
2236
2409
  * @param request - Batch draft creation request
2237
2410
  * @param callbacks - Optional callbacks for stream events
2411
+ * @param options - Optional parameters
2412
+ * @param options.jobId - Existing job ID to resume streaming (for reconnection)
2238
2413
  * @returns Final result with created drafts and error details
2239
2414
  */
2240
- createBatchDraftsStream(userId: string, request: BatchDraftRequest, callbacks?: BatchDraftStreamCallbacks): Promise<BatchDraftResponse>;
2415
+ createBatchDraftsStream(userId: string, request: BatchDraftRequest, callbacks?: BatchDraftStreamCallbacks, options?: {
2416
+ jobId?: string;
2417
+ }): Promise<BatchDraftResponse>;
2241
2418
  /**
2242
2419
  * Create drafts with streaming events as an async generator.
2243
2420
  *
2244
2421
  * This method yields events as they arrive, providing more control over event handling.
2245
2422
  *
2423
+ * **Resilience features:**
2424
+ * - Job state is stored in Redis and survives client disconnects
2425
+ * - First event is `job_started` with job_id for reconnection
2426
+ * - Client can reconnect using `jobId` option to resume streaming
2427
+ *
2246
2428
  * **Example:**
2247
2429
  * ```typescript
2430
+ * let savedJobId: string | undefined;
2431
+ *
2248
2432
  * for await (const event of client.messaging.createBatchDraftsStreamGenerator(
2249
2433
  * 'user@example.com',
2250
2434
  * {
@@ -2254,6 +2438,9 @@ declare class MessagingResource {
2254
2438
  * }
2255
2439
  * )) {
2256
2440
  * switch (event.event) {
2441
+ * case 'job_started':
2442
+ * savedJobId = event.data.jobId; // Save for reconnection
2443
+ * break;
2257
2444
  * case 'progress':
2258
2445
  * console.log(`Progress: ${event.data.percentage}%`)
2259
2446
  * break
@@ -2272,10 +2459,14 @@ declare class MessagingResource {
2272
2459
  *
2273
2460
  * @param userId - User ID or email
2274
2461
  * @param request - Batch draft creation request
2462
+ * @param options - Optional parameters
2463
+ * @param options.jobId - Existing job ID to resume streaming (for reconnection)
2275
2464
  * @yields Stream events with 'event' and 'data' keys
2276
2465
  * @returns Final result with created drafts and error details
2277
2466
  */
2278
- createBatchDraftsStreamGenerator(userId: string, request: BatchDraftRequest): AsyncGenerator<BatchDraftStreamEvent, BatchDraftResponse>;
2467
+ createBatchDraftsStreamGenerator(userId: string, request: BatchDraftRequest, options?: {
2468
+ jobId?: string;
2469
+ }): AsyncGenerator<BatchDraftStreamEvent, BatchDraftResponse>;
2279
2470
  /**
2280
2471
  * Approve and send a single draft
2281
2472
  */
@@ -2284,6 +2475,30 @@ declare class MessagingResource {
2284
2475
  * Send multiple drafts with rate limiting
2285
2476
  */
2286
2477
  sendBatchDrafts(userId: string, request: BatchSendRequest): Promise<BatchSendResponse>;
2478
+ /**
2479
+ * Cancel a queued draft.
2480
+ *
2481
+ * This cancels a draft that was queued for later sending (status='scheduled').
2482
+ * The draft status will be set to 'discarded' and removed from the send queue.
2483
+ *
2484
+ * Can also cancel drafts in 'pending_review' or 'approved' status.
2485
+ *
2486
+ * @param userId - User ID or email
2487
+ * @param draftId - Draft UUID to cancel
2488
+ * @returns CancelDraftResponse with success status
2489
+ * @throws MessagingValidationError if draft cannot be cancelled (already sent, etc.)
2490
+ * @throws MessagingNotFoundError if draft not found
2491
+ *
2492
+ * @example
2493
+ * ```typescript
2494
+ * // Cancel a queued draft
2495
+ * const result = await client.messaging.cancelDraft('user@example.com', 'draft-uuid');
2496
+ * if (result.success) {
2497
+ * console.log(`Draft cancelled: ${result.draftId}`);
2498
+ * }
2499
+ * ```
2500
+ */
2501
+ cancelDraft(userId: string, draftId: string): Promise<CancelDraftResponse>;
2287
2502
  /**
2288
2503
  * Delete a single conversation and all its messages.
2289
2504
  *
@@ -2985,4 +3200,4 @@ declare class ProgressTracker {
2985
3200
  */
2986
3201
  declare function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean;
2987
3202
 
2988
- export { ACTION_DELAYS, type AgentConfig, type ApiKeyMode, type ApiKeyModeRequest, type ApiKeyModeResponse, type ApiProvider, type AppEnabledResponse, type AppliedFilters, type AppsListResponse, type ArtifactObject, type ArtifactsListResponse, AuthenticationError, type BaseResource, type BatchCheckConnectionRequest, type BatchCheckPriorContactRequest, type BatchCheckPriorContactResponse, type BatchConnectionRequest, type BatchConnectionResponse, type BatchConnectionStatus, type BatchConnectionStatusResponse, type BatchDraftCompleteData, type BatchDraftCreatedData, type BatchDraftErrorData, type BatchDraftProgressData, type BatchDraftRequest, type BatchDraftResponse, type BatchDraftStreamCallbacks, type BatchDraftStreamEvent, type BatchDraftStreamEventType, type BatchProspectIdentifier, type BatchSendRequest, type BatchSendResponse, type BillingStatus, type BulkDeleteRequest, type BulkDeleteResponse, type BulkUploadResponse, type CancelResponseResponse, type ChannelContactHistory, ChannelType, type CheckAppEnabledParams, type CheckLinkedInConnectionRequest, type CheckPriorContactRequest, type CheckPriorContactResponse, type ChunkingStrategy, type ConnectionAcceptedData, type ConnectionCallbackRequest, type ConnectionCallbackResponse, type ConnectionInfo, type ConnectionStatus, type ConnectionStatusResponse, type ConnectionSummary, type ContentType, type ConversationDetail, ConversationStatus, type ConversationSummary, type CreateDraftRequest, type CreateFeedbackRequest, type CreateFeedbackResponse, type CreateResponseRequest, type CreateResponseResponse, type CreateThreadRequest, type DatabaseStatus, type DeleteApiKeyResponse, type DeleteConversationResponse, type DeleteConversationsByProjectResponse, type DisconnectRequest, type DisconnectResponse, type DraftResponse, DraftStatus, type DuplicateHandling, type Email, type EmailThreadSummary, type ErrorResponse, ExternalAPIKeysResource, type ExternalApiKeyResponse, type FeedbackListResponse, type FeedbackObject, type FeedbackType, type FileAttachment, type FileChunk, type FileContentResponse, type FileListResponse, type FileMetadata, type FileScope, type FileScopeUpdateRequest, type FileSearchRequest, type FileSearchResponse, type FileSearchResult, type FileStatisticsResponse, type FileUploadResponse, FilesResource, type FilterLogic, type FilterValue, type GetConnectionStatusParams, type GetToolsRequest, type GetToolsResponse, type GetUserConnectionsParams, type InitiateConnectionRequest, type InitiateConnectionResponse, IntegrationsResource, InternalServerError, LINKEDIN_LIMITS, type LinkedInAccountInfoResponse, type LinkedInConnectionStatus, type LinkedInCreditsResponse, type LinkedInLimitSubscriptionType, type LinkedInLimits, type LinkedInSendRequest, type LinkedInSubscriptionInfo, LinkedInSubscriptionType, type ListProvidersResponse, LocalFileNotSupportedError, LumnisClient, type LumnisClientOptions, LumnisError, type LumnisErrorOptions, type MCPScope, type MCPServerCreateRequest, type MCPServerListResponse, type MCPServerResponse, type MCPServerUpdateRequest, MCPServersResource, type MCPToolListResponse, type MCPToolResponse, type MCPTransport, type Message, type MessageReceivedData, type MessageResponse, type MessageSentData, MessageType, MessagingAPIError, MessagingConnectionError, MessagingNotFoundError, MessagingResource, MessagingSendError, MessagingValidationError, type ModelAvailability, type ModelOverrides, type ModelPreferenceCreate, type ModelPreferencesBulkUpdate, ModelPreferencesResource, type ModelProvider, type ModelType, NetworkDistance, NoDataSourcesError, NotFoundError, OutreachMethod, type PaginationInfo, type PaginationParams, PeopleDataSource, PeopleResource, type PeopleSearchRequest, type PeopleSearchResponse, type PersonResult, type Plan, type PriorContactMessage, type ProcessingStatus, type ProcessingStatusResponse, type ProgressEntry, ProgressTracker, type ProspectConnectionCheck, type ProspectInfo, type ProspectPriorContactResult, type ProspectSyncIdentifier, type ProspectSyncResult, ProviderType, QueueItemStatus, type QuickPeopleSearchOutput, RATE_LIMIT_COOLDOWNS, RateLimitError, type RateLimitErrorOptions, type ResponseArtifact, type ResponseListResponse, type ResponseObject, type ResponseStatus, ResponsesResource, type SalaryRange, type Scope, type SelectedSkill, type SendMessageRequest, type SendMessageResponse, type SendReplyRequest, type SendResult, type SkillAnalyticsRequest, type SkillEffectivenessMetrics, type SkillGuidelineBase, type SkillGuidelineCreate, type SkillGuidelineListResponse, type SkillGuidelineResponse, type SkillGuidelineUpdate, type SkillRetrievalMetadata, type SkillUsageBase, type SkillUsageCreate, type SkillUsageListResponse, type SkillUsageResponse, type SkillUsageUpdate, SkillsResource, SourcesNotAvailableError, type SpecializedAgentParams, type SpecializedAgentType, type StoreApiKeyRequest, type SyncJobResponse, SyncJobStatus, type SyncProspectRequest, type SyncProspectResponse, type SyncRequest, type SyncStats, type TenantDetailsResponse, TenantInfoResource, type TenantModelPreference, type TenantModelPreferencesResponse, type TestConnectionResponse, type ThreadListResponse, type ThreadObject, type ThreadResponsesParams, ThreadsResource, type ToolInfo, UNIPILE_RATE_LIMIT_ERRORS, UNIPILE_SAFE_LIMITS, type UUID, type UnlinkConversationsResponse, type UpdateAppStatusParams, type UpdateAppStatusResponse, type UpdateLinkedInSubscriptionRequest, type UpdateThreadRequest, type UserConnectionsResponse, type UserCreateRequest, type UserDeleteResponse, type UserIdentifier, type UserListResponse, type UserResponse, type UserUpdateRequest, UsersResource, ValidationError, type WebhookEvent, type WebhookPayload, canSendInmail, displayProgress, formatProgressEntry, getBestSubscriptionForAction, getConnectionRequestLimit, getInmailAllowance, getLimits, getMessageLimit, hasOpenProfileMessages, verifyWebhookSignature };
3203
+ export { ACTION_DELAYS, type AgentConfig, type ApiKeyMode, type ApiKeyModeRequest, type ApiKeyModeResponse, type ApiProvider, type AppEnabledResponse, type AppliedFilters, type AppsListResponse, type ArtifactObject, type ArtifactsListResponse, AuthenticationError, type BaseResource, type BatchCheckConnectionRequest, type BatchCheckPriorContactRequest, type BatchCheckPriorContactResponse, type BatchConnectionRequest, type BatchConnectionResponse, type BatchConnectionStatus, type BatchConnectionStatusResponse, type BatchDraftCompleteData, type BatchDraftCreatedData, type BatchDraftErrorData, type BatchDraftJobProgress, type BatchDraftJobResponse, type BatchDraftJobStartedData, type BatchDraftJobStatusResponse, type BatchDraftProgressData, type BatchDraftRequest, type BatchDraftResponse, type BatchDraftStreamCallbacks, type BatchDraftStreamEvent, type BatchDraftStreamEventType, BatchJobStatus, type BatchProspectIdentifier, type BatchSendRequest, type BatchSendResponse, type BillingStatus, type BulkDeleteRequest, type BulkDeleteResponse, type BulkUploadResponse, type CancelDraftResponse, type CancelResponseResponse, type ChannelContactHistory, ChannelType, type CheckAppEnabledParams, type CheckLinkedInConnectionRequest, type CheckPriorContactRequest, type CheckPriorContactResponse, type ChunkingStrategy, type ConnectionAcceptedData, type ConnectionCallbackRequest, type ConnectionCallbackResponse, type ConnectionInfo, type ConnectionStatus, type ConnectionStatusResponse, type ConnectionSummary, type ContentType, type ConversationDetail, ConversationStatus, type ConversationSummary, type CreateDraftRequest, type CreateFeedbackRequest, type CreateFeedbackResponse, type CreateResponseRequest, type CreateResponseResponse, type CreateThreadRequest, type DatabaseStatus, type DeleteApiKeyResponse, type DeleteConversationResponse, type DeleteConversationsByProjectResponse, type DisconnectRequest, type DisconnectResponse, type DraftResponse, DraftStatus, type DuplicateHandling, type Email, type EmailThreadSummary, type ErrorResponse, ExternalAPIKeysResource, type ExternalApiKeyResponse, type FeedbackListResponse, type FeedbackObject, type FeedbackType, type FileAttachment, type FileChunk, type FileContentResponse, type FileListResponse, type FileMetadata, type FileScope, type FileScopeUpdateRequest, type FileSearchRequest, type FileSearchResponse, type FileSearchResult, type FileStatisticsResponse, type FileUploadResponse, FilesResource, type FilterLogic, type FilterValue, type GetConnectionStatusParams, type GetToolsRequest, type GetToolsResponse, type GetUserConnectionsParams, type InitiateConnectionRequest, type InitiateConnectionResponse, IntegrationsResource, InternalServerError, LINKEDIN_LIMITS, type LinkedInAccountInfoResponse, type LinkedInConnectionStatus, type LinkedInCreditsResponse, type LinkedInLimitSubscriptionType, type LinkedInLimits, type LinkedInSendRequest, type LinkedInSubscriptionInfo, LinkedInSubscriptionType, type ListProvidersResponse, LocalFileNotSupportedError, LumnisClient, type LumnisClientOptions, LumnisError, type LumnisErrorOptions, type MCPScope, type MCPServerCreateRequest, type MCPServerListResponse, type MCPServerResponse, type MCPServerUpdateRequest, MCPServersResource, type MCPToolListResponse, type MCPToolResponse, type MCPTransport, type Message, type MessageReceivedData, type MessageResponse, type MessageSentData, MessageType, MessagingAPIError, MessagingConnectionError, MessagingNotFoundError, MessagingResource, MessagingSendError, MessagingValidationError, type ModelAvailability, type ModelOverrides, type ModelPreferenceCreate, type ModelPreferencesBulkUpdate, ModelPreferencesResource, type ModelProvider, type ModelType, NetworkDistance, NoDataSourcesError, NotFoundError, OutreachMethod, type PaginationInfo, type PaginationParams, PeopleDataSource, PeopleResource, type PeopleSearchRequest, type PeopleSearchResponse, type PersonResult, type Plan, type PriorContactMessage, type ProcessingStatus, type ProcessingStatusResponse, type ProgressEntry, ProgressTracker, type ProspectConnectionCheck, type ProspectInfo, type ProspectPriorContactResult, type ProspectSyncIdentifier, type ProspectSyncResult, ProviderType, QueueItemStatus, type QuickPeopleSearchOutput, RATE_LIMIT_COOLDOWNS, RateLimitError, type RateLimitErrorOptions, type ResponseArtifact, type ResponseListResponse, type ResponseObject, type ResponseStatus, ResponsesResource, type SalaryRange, type Scope, type SelectedSkill, type SendMessageRequest, type SendMessageResponse, type SendReplyRequest, type SendResult, type SkillAnalyticsRequest, type SkillEffectivenessMetrics, type SkillGuidelineBase, type SkillGuidelineCreate, type SkillGuidelineListResponse, type SkillGuidelineResponse, type SkillGuidelineUpdate, type SkillRetrievalMetadata, type SkillUsageBase, type SkillUsageCreate, type SkillUsageListResponse, type SkillUsageResponse, type SkillUsageUpdate, SkillsResource, SourcesNotAvailableError, type SpecializedAgentParams, type SpecializedAgentType, type StoreApiKeyRequest, type SyncJobResponse, SyncJobStatus, type SyncProspectRequest, type SyncProspectResponse, type SyncRequest, type SyncStats, type TenantDetailsResponse, TenantInfoResource, type TenantModelPreference, type TenantModelPreferencesResponse, type TestConnectionResponse, type ThreadListResponse, type ThreadObject, type ThreadResponsesParams, ThreadsResource, type ToolInfo, UNIPILE_RATE_LIMIT_ERRORS, UNIPILE_SAFE_LIMITS, type UUID, type UnlinkConversationsResponse, type UpdateAppStatusParams, type UpdateAppStatusResponse, type UpdateLinkedInSubscriptionRequest, type UpdateThreadRequest, type UserConnectionsResponse, type UserCreateRequest, type UserDeleteResponse, type UserIdentifier, type UserListResponse, type UserResponse, type UserUpdateRequest, UsersResource, ValidationError, type WebhookEvent, type WebhookPayload, canSendInmail, displayProgress, formatProgressEntry, getBestSubscriptionForAction, getConnectionRequestLimit, getInmailAllowance, getLimits, getMessageLimit, hasOpenProfileMessages, verifyWebhookSignature };