@curviate/cli 0.47.0 → 0.49.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 (48) hide show
  1. package/CHANGELOG.md +231 -1
  2. package/README.md +136 -88
  3. package/dist/{account-RFJ63QYL.js → account-2BH2Q6VG.js} +41 -31
  4. package/dist/chunk-3RCW7URJ.js +41 -0
  5. package/dist/{chunk-UJOTQPL6.js → chunk-5ZGTU4VD.js} +47 -14
  6. package/dist/chunk-D2S5OCYU.js +38 -0
  7. package/dist/{chunk-HOQ7EUHJ.js → chunk-FDJMAF7D.js} +1 -0
  8. package/dist/{chunk-ERBYEC5P.js → chunk-JYKYD57J.js} +1 -1
  9. package/dist/chunk-MGB6FE4A.js +58 -0
  10. package/dist/chunk-NNV2OYEF.js +23 -0
  11. package/dist/{chunk-76SWLAZ6.js → chunk-RXWODUWA.js} +43 -1
  12. package/dist/{chunk-V3MVOVQT.js → chunk-SA2QHAXG.js} +8 -1
  13. package/dist/chunk-TEAWYLPO.js +1493 -0
  14. package/dist/{chunk-PD2I5TYC.js → chunk-V7FJWTZW.js} +3 -3
  15. package/dist/{chunk-TC4ZPUWI.js → chunk-Y7MZZRYR.js} +21 -80
  16. package/dist/{chunk-FXYK2GTO.js → chunk-Z7OQSWBD.js} +38 -33
  17. package/dist/chunk-ZYURL5VK.js +83 -0
  18. package/dist/cli.js +79 -98
  19. package/dist/{comment-MCXE7B7V.js → comment-MRDPDA33.js} +29 -24
  20. package/dist/{company-EUUN372H.js → company-2AEHSGHA.js} +57 -52
  21. package/dist/{config-K4G3VSBA.js → config-NRBKHXES.js} +13 -5
  22. package/dist/{connect-2AL7XVJO.js → connect-4XEBV5V3.js} +42 -38
  23. package/dist/core-RGU2SCBN.js +46 -0
  24. package/dist/{doctor-WPYI7X2T.js → doctor-BZ4DA7DV.js} +9 -5
  25. package/dist/document-RKHRWXNT.js +27 -0
  26. package/dist/{draft-G65DVXT7.js → draft-C5N6EOO5.js} +27 -22
  27. package/dist/enrollment-BNQOUKI7.js +472 -0
  28. package/dist/examples-NIMSIXMV.js +53 -0
  29. package/dist/{exit-codes-AW6KHDDN.js → exit-codes-TLMKTLRI.js} +1 -1
  30. package/dist/{feed-HV24WME4.js → feed-DFUU7SUJ.js} +15 -11
  31. package/dist/{group-HADXNVJW.js → group-CSD2OWOZ.js} +17 -13
  32. package/dist/{inbox-G3EE54OB.js → inbox-SNSPWI7J.js} +23 -19
  33. package/dist/{inboxes-237XOBTP.js → inboxes-RIRHPS4H.js} +18 -14
  34. package/dist/{job-LIN6RWD7.js → job-6PNXXZNF.js} +31 -27
  35. package/dist/{login-OHAHNBRW.js → login-Y7JBAHCW.js} +10 -5
  36. package/dist/{message-U2O2JQSW.js → message-2IK4MBBG.js} +10 -8
  37. package/dist/motion-7ATUXO6R.js +946 -0
  38. package/dist/{notification-3VG32LWM.js → notification-VYK5NDEB.js} +19 -15
  39. package/dist/{post-ECDK2KJL.js → post-AN6T2OJF.js} +35 -30
  40. package/dist/{profile-JOHS6SDW.js → profile-UQY64642.js} +46 -42
  41. package/dist/{recruiter-7VXEIXN3.js → recruiter-OY4RN5HH.js} +122 -119
  42. package/dist/{sales-nav-K4BMBH7R.js → sales-nav-KLODLYMW.js} +36 -30
  43. package/dist/{search-C2UYO6PI.js → search-NWP5S6CF.js} +68 -58
  44. package/dist/{setup-GYEZFDEN.js → setup-YPPFLH2N.js} +14 -9
  45. package/dist/{webhook-KCOQOH7D.js → webhook-OHKBL3YS.js} +51 -55
  46. package/package.json +2 -2
  47. package/dist/chunk-KJ24DIAJ.js +0 -60
  48. package/dist/examples-IJL3A6SZ.js +0 -18
@@ -0,0 +1,946 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ fail,
4
+ listFlag,
5
+ outputOpts,
6
+ rootClient,
7
+ usage
8
+ } from "./chunk-MGB6FE4A.js";
9
+ import {
10
+ intFlag
11
+ } from "./chunk-NNV2OYEF.js";
12
+ import {
13
+ buildPreviewOutput
14
+ } from "./chunk-TCUYH5GO.js";
15
+ import {
16
+ pageDelayFromFlags,
17
+ readCursorFlag,
18
+ readMaxPagesFlag,
19
+ readableObject,
20
+ readablePage,
21
+ rejectPaginationModifiersWithoutAll,
22
+ renderSuccess,
23
+ streamAll,
24
+ writeNdjsonItem
25
+ } from "./chunk-SA2QHAXG.js";
26
+ import "./chunk-5ZGTU4VD.js";
27
+ import {
28
+ GLOBAL_FLAGS,
29
+ READ_SINGLE_FLAGS,
30
+ WRITE_SINGLE_FLAGS,
31
+ readOnly
32
+ } from "./chunk-Y7MZZRYR.js";
33
+ import {
34
+ DESCRIPTIONS
35
+ } from "./chunk-D2S5OCYU.js";
36
+ import {
37
+ documentSchema,
38
+ parseDocument,
39
+ readFileFlag,
40
+ reportIssues,
41
+ validate
42
+ } from "./chunk-TEAWYLPO.js";
43
+ import "./chunk-FDJMAF7D.js";
44
+ import {
45
+ isStdinToken
46
+ } from "./chunk-ZYURL5VK.js";
47
+
48
+ // src/commands/motion.ts
49
+ import { defineCommand } from "citty";
50
+ import { writeFile } from "fs/promises";
51
+
52
+ // src/lib/sequence-report.ts
53
+ function valueOffsets(text) {
54
+ const at = /* @__PURE__ */ new Map();
55
+ let i = 0;
56
+ const ws = () => {
57
+ while (i < text.length && /\s/.test(text[i])) i++;
58
+ };
59
+ const str = () => {
60
+ const start = i++;
61
+ while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
62
+ i++;
63
+ return JSON.parse(text.slice(start, i));
64
+ };
65
+ const value = (ptr) => {
66
+ ws();
67
+ at.set(ptr, i);
68
+ const c = text[i];
69
+ if (c === "{" || c === "[") {
70
+ const close = c === "{" ? "}" : "]";
71
+ i++;
72
+ ws();
73
+ if (text[i] === close) return void i++;
74
+ for (let n = 0; ; n++) {
75
+ ws();
76
+ let key = String(n);
77
+ if (c === "{") {
78
+ key = str().replace(/~/g, "~0").replace(/\//g, "~1");
79
+ ws();
80
+ i++;
81
+ }
82
+ value(`${ptr}/${key}`);
83
+ ws();
84
+ if (text[i++] === close) return;
85
+ }
86
+ }
87
+ if (c === '"') return void str();
88
+ while (i < text.length && !/[\s,\]}]/.test(text[i])) i++;
89
+ };
90
+ value("");
91
+ return at;
92
+ }
93
+ function lineCol(text, offsets, pointer) {
94
+ let p = pointer;
95
+ while (!offsets.has(p) && p !== "") p = p.slice(0, p.lastIndexOf("/"));
96
+ const off = offsets.get(p) ?? 0;
97
+ const before = text.slice(0, off);
98
+ return [before.split("\n").length, off - before.lastIndexOf("\n")];
99
+ }
100
+ function compilerLines(file, text, entries, prefix = "") {
101
+ let offsets;
102
+ const line = (kind, e) => {
103
+ offsets ?? (offsets = valueOffsets(text));
104
+ const [l, c] = lineCol(text, offsets, prefix + (e.pointer ?? ""));
105
+ const message = (e.message ?? e.rule).replace(/\.$/, "");
106
+ return `${file}:${l}:${c} ${kind} ${e.code ?? ""} ${e.path}: ${message}.${e.hint ? ` ${e.hint}` : ""}${e.docs_url ? ` -> ${e.docs_url}` : ""}`;
107
+ };
108
+ return [...entries.errors.map((e) => line("error", e)), ...entries.warnings.map((w) => line("warning", w))];
109
+ }
110
+
111
+ // src/lib/chunks.ts
112
+ async function sendInChunks(ids, size, send, f) {
113
+ const total = Math.ceil(ids.length / size);
114
+ const done = [];
115
+ for (let k = 0; k < total; k++) {
116
+ const chunk = ids.slice(k * size, (k + 1) * size);
117
+ try {
118
+ done.push(await send(chunk));
119
+ } catch (err) {
120
+ const { CurviateError } = await import("@curviate/sdk");
121
+ const progress = {
122
+ chunks: { sent: k, total },
123
+ items: { accepted: k * size, total: ids.length },
124
+ failed_chunk: { index: k + 1, first_row: k * size + 1, last_row: k * size + chunk.length }
125
+ };
126
+ if (!(err instanceof CurviateError)) {
127
+ process.stderr.write(`Chunk ${k + 1} of ${total} failed; ${k * size} of ${ids.length} ids were sent before it. Nothing after it was sent.
128
+ `);
129
+ return fail(err, f);
130
+ }
131
+ const { getExitCode } = await import("./exit-codes-TLMKTLRI.js");
132
+ const e = err.toJSON();
133
+ if (outputOpts(f).json) process.stdout.write(JSON.stringify({ error: e, progress }) + "\n");
134
+ process.stderr.write(
135
+ `error [${e.code}] ${e.message}
136
+ Chunk ${k + 1} of ${total} failed (ids ${progress.failed_chunk.first_row} to ${progress.failed_chunk.last_row}); ${progress.items.accepted} of ${ids.length} ids were sent before it. Nothing after it was sent.
137
+ `
138
+ );
139
+ process.exit(getExitCode(err));
140
+ }
141
+ }
142
+ return done;
143
+ }
144
+
145
+ // src/templates/connect-and-converse.json
146
+ var connect_and_converse_default = {
147
+ name: "Connect and converse",
148
+ contact_list_ids: [],
149
+ account_ids: [],
150
+ schedule: {
151
+ timezone: null,
152
+ days: [
153
+ "mon",
154
+ "tue",
155
+ "wed",
156
+ "thu",
157
+ "fri"
158
+ ],
159
+ hours: {
160
+ start: "09:00",
161
+ end: "18:00"
162
+ }
163
+ },
164
+ settings: {
165
+ new_enrollments_per_account_per_day: 20,
166
+ stop_on_engagement: false
167
+ },
168
+ sequence: {
169
+ $schema: "https://docs.curviate.com/schemas/sequence/v1.json",
170
+ on_reply: "replied",
171
+ steps: [
172
+ {
173
+ id: "visit",
174
+ do: "profile.view",
175
+ note: "Warm-up visit before any contact."
176
+ },
177
+ {
178
+ id: "has_post",
179
+ if: {
180
+ "contact.posted_within": "14d"
181
+ },
182
+ then: "w_like",
183
+ else: "w_invite"
184
+ },
185
+ {
186
+ id: "w_like",
187
+ wait: "1d"
188
+ },
189
+ {
190
+ id: "like",
191
+ do: "post.react",
192
+ with: {
193
+ post: "latest",
194
+ newer_than: "14d",
195
+ reaction: "like"
196
+ }
197
+ },
198
+ {
199
+ id: "w_invite",
200
+ wait: "1d"
201
+ },
202
+ {
203
+ id: "invite",
204
+ do: "invite.send",
205
+ with: {
206
+ withdraw_after: "21d"
207
+ },
208
+ note: "No note: blank invites are accepted slightly more often."
209
+ },
210
+ {
211
+ id: "accepted",
212
+ until: "invite.accepted",
213
+ timeout: "21d",
214
+ then: "w_opener",
215
+ else: "end"
216
+ },
217
+ {
218
+ id: "w_opener",
219
+ wait: "1d"
220
+ },
221
+ {
222
+ id: "opener",
223
+ do: "message.send",
224
+ variants: [
225
+ {
226
+ id: "opener_named",
227
+ text: "Hi {{first_name}}, {{opener}}"
228
+ },
229
+ {
230
+ id: "opener_plain",
231
+ text: "{{opener}}"
232
+ }
233
+ ],
234
+ with: {
235
+ fallback: "Hi, glad we are connected. How do you handle LinkedIn outreach today?"
236
+ },
237
+ note: "No link in the first message."
238
+ },
239
+ {
240
+ id: "r_opener",
241
+ until: "message.replied",
242
+ timeout: "4d",
243
+ then: "replied"
244
+ },
245
+ {
246
+ id: "followup",
247
+ do: "message.send",
248
+ with: {
249
+ text: "{{followup}}",
250
+ fallback: "Quick follow-up in case this got buried. Happy to leave it here if the timing is off."
251
+ }
252
+ },
253
+ {
254
+ id: "r_followup",
255
+ until: "message.replied",
256
+ timeout: "7d",
257
+ then: "replied"
258
+ },
259
+ {
260
+ id: "silent",
261
+ tag: "no-reply",
262
+ next: "end"
263
+ },
264
+ {
265
+ id: "replied",
266
+ tag: "in-conversation",
267
+ next: "end"
268
+ }
269
+ ]
270
+ }
271
+ };
272
+
273
+ // src/templates/engage-then-connect.json
274
+ var engage_then_connect_default = {
275
+ name: "Engage then connect",
276
+ contact_list_ids: [],
277
+ account_ids: [],
278
+ schedule: {
279
+ timezone: null,
280
+ days: [
281
+ "mon",
282
+ "tue",
283
+ "wed",
284
+ "thu",
285
+ "fri"
286
+ ],
287
+ hours: {
288
+ start: "09:00",
289
+ end: "18:00"
290
+ }
291
+ },
292
+ settings: {
293
+ new_enrollments_per_account_per_day: 20,
294
+ stop_on_engagement: false
295
+ },
296
+ sequence: {
297
+ on_reply: "replied",
298
+ steps: [
299
+ {
300
+ id: "react",
301
+ do: "post.react",
302
+ with: {
303
+ newer_than: "60d"
304
+ },
305
+ else: "w_invite"
306
+ },
307
+ {
308
+ id: "w_comment",
309
+ wait: "10m"
310
+ },
311
+ {
312
+ id: "comment",
313
+ do: "post.comment",
314
+ with: {
315
+ newer_than: "60d",
316
+ text: "{{comment}}",
317
+ fallback: "skip"
318
+ },
319
+ note: "The agent writes one comment per Contact; no product mention."
320
+ },
321
+ {
322
+ id: "w_invite",
323
+ wait: "30m"
324
+ },
325
+ {
326
+ id: "invite",
327
+ do: "invite.send",
328
+ with: {
329
+ withdraw_after: "21d"
330
+ }
331
+ },
332
+ {
333
+ id: "accepted",
334
+ until: "invite.accepted",
335
+ timeout: "21d",
336
+ then: "w_opener",
337
+ else: "end"
338
+ },
339
+ {
340
+ id: "w_opener",
341
+ wait: "1d"
342
+ },
343
+ {
344
+ id: "opener",
345
+ do: "message.send",
346
+ with: {
347
+ text: "Hi {{first_name}}, {{opener}}",
348
+ fallback: "Hi, thanks for connecting. What are you working on at the moment?"
349
+ }
350
+ },
351
+ {
352
+ id: "r_opener",
353
+ until: "message.replied",
354
+ timeout: "5d",
355
+ then: "replied"
356
+ },
357
+ {
358
+ id: "followup",
359
+ do: "message.send",
360
+ with: {
361
+ text: "{{followup}}",
362
+ fallback: "Following up once in case this got buried. All good if now is not the time."
363
+ }
364
+ },
365
+ {
366
+ id: "r_followup",
367
+ until: "message.replied",
368
+ timeout: "7d",
369
+ then: "replied"
370
+ },
371
+ {
372
+ id: "silent",
373
+ tag: "no-reply",
374
+ next: "end"
375
+ },
376
+ {
377
+ id: "replied",
378
+ tag: "in-conversation",
379
+ next: "end"
380
+ }
381
+ ]
382
+ }
383
+ };
384
+
385
+ // src/templates/nurture-connections.json
386
+ var nurture_connections_default = {
387
+ name: "Nurture connections",
388
+ contact_list_ids: [],
389
+ account_ids: [],
390
+ schedule: {
391
+ timezone: null,
392
+ days: [
393
+ "mon",
394
+ "tue",
395
+ "wed",
396
+ "thu",
397
+ "fri"
398
+ ],
399
+ hours: {
400
+ start: "09:00",
401
+ end: "18:00"
402
+ }
403
+ },
404
+ settings: {
405
+ assign: "already_connected",
406
+ stop_on_engagement: false
407
+ },
408
+ sequence: {
409
+ on_reply: "replied",
410
+ steps: [
411
+ {
412
+ id: "is_connected",
413
+ if: {
414
+ "contact.connected": true
415
+ },
416
+ then: "dm",
417
+ else: "not_connected"
418
+ },
419
+ {
420
+ id: "not_connected",
421
+ tag: "not-connected",
422
+ next: "end"
423
+ },
424
+ {
425
+ id: "dm",
426
+ do: "message.send",
427
+ with: {
428
+ text: "{{dm}}",
429
+ fallback: "Hi, it has been a while. What are you focused on these days?"
430
+ }
431
+ },
432
+ {
433
+ id: "r_dm",
434
+ until: "message.replied",
435
+ timeout: "5d",
436
+ then: "replied"
437
+ },
438
+ {
439
+ id: "seen_dm",
440
+ if: {
441
+ "message.seen": true
442
+ },
443
+ then: "followup",
444
+ else: "end",
445
+ note: "Follow up only when they saw the first message."
446
+ },
447
+ {
448
+ id: "followup",
449
+ do: "message.send",
450
+ with: {
451
+ text: "{{followup}}",
452
+ fallback: "No rush on this, just wanted to check in once more."
453
+ }
454
+ },
455
+ {
456
+ id: "r_followup",
457
+ until: "message.replied",
458
+ timeout: "7d",
459
+ then: "replied",
460
+ else: "end"
461
+ },
462
+ {
463
+ id: "replied",
464
+ tag: "in-conversation",
465
+ next: "end"
466
+ }
467
+ ]
468
+ }
469
+ };
470
+
471
+ // src/commands/motion.ts
472
+ var BULK_MAX_IDS = 1e3;
473
+ var TEMPLATES = {
474
+ "connect-and-converse": connect_and_converse_default,
475
+ "engage-then-connect": engage_then_connect_default,
476
+ "nurture-connections": nurture_connections_default
477
+ };
478
+ var STATUSES = ["draft", "scheduled", "active", "paused", "completed", "archived"];
479
+ function preview(method, args, body = {}) {
480
+ process.stdout.write(JSON.stringify(buildPreviewOutput({ method, args, body })) + "\n");
481
+ }
482
+ var shownFile = (f) => f.file === void 0 || isStdinToken(f.file) ? "-" : f.file;
483
+ async function checkSequence(f, text, sequence, prefix) {
484
+ const { validateSequence } = await import("@curviate/sdk");
485
+ const verdict = validateSequence(sequence);
486
+ const lines = compilerLines(shownFile(f), text, verdict, prefix);
487
+ if (verdict.errors.length) {
488
+ const first = verdict.errors[0];
489
+ const message = `${first.path}: ${first.rule}${verdict.errors.length > 1 ? ` and ${verdict.errors.length - 1} more` : ""}`;
490
+ if (outputOpts(f).json) process.stdout.write(JSON.stringify({ error: { code: "SEQUENCE_INVALID", message, errors: verdict.errors }, warnings: verdict.warnings }) + "\n");
491
+ process.stderr.write(lines.map((l) => `${l}
492
+ `).join(""));
493
+ process.exit(2);
494
+ }
495
+ process.stderr.write(lines.map((l) => `${l}
496
+ `).join(""));
497
+ return verdict;
498
+ }
499
+ async function readMotionFile(f, command) {
500
+ const text = await readFileFlag("file", f.file ?? "", { others: f });
501
+ const doc = parseDocument("file", text);
502
+ const schema = documentSchema(command);
503
+ let body = doc;
504
+ if (doc && typeof doc === "object" && !Array.isArray(doc)) {
505
+ const readOnlyKeys = schema["x-curviate-response-only"];
506
+ const dropped = Object.keys(doc).filter((k) => readOnlyKeys.includes(k));
507
+ if (dropped.length) {
508
+ process.stderr.write(`warning: dropped ${dropped.join(", ")}: set by Curviate, not part of a Motion file (\`curviate motion get\` output carries them).
509
+ `);
510
+ body = Object.fromEntries(Object.entries(doc).filter(([k]) => !dropped.includes(k)));
511
+ }
512
+ }
513
+ const issues = validate(schema, body);
514
+ if (issues.length) reportIssues(issues, outputOpts(f).json);
515
+ if (body["sequence"] != null) await checkSequence(f, text, body["sequence"], "/sequence");
516
+ return { body, text };
517
+ }
518
+ function explain(err, f, text) {
519
+ const e = err;
520
+ if (e.code === "SEQUENCE_INVALID" && e.errors?.length) {
521
+ process.stderr.write(compilerLines(shownFile(f), text, { errors: e.errors, warnings: [] }, "/sequence").map((l) => `${l}
522
+ `).join(""));
523
+ }
524
+ if (e.code === "SEQUENCE_CONFLICT" && e.current) {
525
+ const c = e.current;
526
+ process.stderr.write(
527
+ `The Sequence was saved since revision ${f["if-revision"]}: revision ${c.sequence_revision} by ${c.sequence_updated_by_user_id ?? "an unknown user"} at ${c.updated_at ?? "an unknown time"}. Read it with \`curviate motion get ${f.id}\` and merge, or send yours again with --if-revision ${c.sequence_revision} to replace it.
528
+ `
529
+ );
530
+ }
531
+ }
532
+ async function runList(c, f) {
533
+ rejectPaginationModifiersWithoutAll(f, process);
534
+ const params = {};
535
+ if (f.status !== void 0) {
536
+ const status = listFlag("status", f.status);
537
+ const bad = status.filter((s) => !STATUSES.includes(s));
538
+ if (bad.length) usage(`--status takes a comma list of ${STATUSES.join(", ")}.`);
539
+ params["status"] = status;
540
+ }
541
+ if (f.limit !== void 0) params["limit"] = intFlag("limit", f.limit, 1, 100);
542
+ const cursor = readCursorFlag(f, process);
543
+ if (cursor) params["cursor"] = cursor;
544
+ try {
545
+ if (f.all) {
546
+ const page = (p) => c.motions.list(p);
547
+ for await (const item of streamAll(page, params, { maxPages: readMaxPagesFlag(f, process), out: process, pageDelayMs: pageDelayFromFlags(f) })) writeNdjsonItem(process, item, f.fields);
548
+ } else {
549
+ renderSuccess(readablePage(await c.motions.list(params)), outputOpts(f), process);
550
+ }
551
+ } catch (err) {
552
+ await fail(err, f);
553
+ }
554
+ }
555
+ async function runGet(c, f) {
556
+ try {
557
+ const result = f.version === void 0 ? await c.motions.get(f.id ?? "") : await c.motions.getSequenceVersion(f.id ?? "", { version: intFlag("version", f.version) });
558
+ renderSuccess(readableObject(result), outputOpts(f), process);
559
+ } catch (err) {
560
+ await fail(err, f);
561
+ }
562
+ }
563
+ async function runCreate(c, f) {
564
+ const { body, text } = await readMotionFile(f, "motion create");
565
+ if (f.preview) return preview("motions.create", {}, body);
566
+ try {
567
+ renderSuccess(await c.motions.create(body), outputOpts(f), process);
568
+ } catch (err) {
569
+ explain(err, f, text);
570
+ await fail(err, f);
571
+ }
572
+ }
573
+ async function runUpdate(c, f) {
574
+ const { body, text } = await readMotionFile(f, "motion update");
575
+ if ("if_sequence_revision" in body) {
576
+ process.stderr.write("warning: dropped if_sequence_revision from the file: pass --if-revision <n> to send it.\n");
577
+ delete body["if_sequence_revision"];
578
+ }
579
+ if (f["if-revision"] !== void 0) body["if_sequence_revision"] = intFlag("if-revision", f["if-revision"], 0);
580
+ if (f.preview) return preview("motions.update", { id: f.id }, body);
581
+ try {
582
+ renderSuccess(await c.motions.update(f.id ?? "", body), outputOpts(f), process);
583
+ } catch (err) {
584
+ explain(err, f, text);
585
+ await fail(err, f);
586
+ }
587
+ }
588
+ var lifecycle = (method) => async (c, f) => {
589
+ if (f.preview) return preview(`motions.${method}`, { id: f.id });
590
+ try {
591
+ renderSuccess(await c.motions[method](f.id ?? ""), outputOpts(f), process);
592
+ } catch (err) {
593
+ await fail(err, f);
594
+ }
595
+ };
596
+ async function runPreview(c, f) {
597
+ const params = {};
598
+ if (f.sample !== void 0) params["sample"] = intFlag("sample", f.sample, 1, 20);
599
+ if (f.contact !== void 0) params["contact_ids"] = listFlag("contact", f.contact);
600
+ if (params["sample"] !== void 0 && params["contact_ids"] !== void 0) usage("--sample and --contact cannot be combined: name the Contacts, or let Curviate sample.");
601
+ try {
602
+ renderSuccess(readableObject(await c.motions.preview(f.id ?? "", params)), outputOpts(f), process);
603
+ } catch (err) {
604
+ await fail(err, f);
605
+ }
606
+ }
607
+ var membership = (kind) => async (c, f) => {
608
+ const ids = listFlag("contact", f.contact);
609
+ if (!ids.length) usage("--contact is required: one or more Contact ids (con_...).");
610
+ if (f.account !== void 0 && f.account.trim() === "") usage("--account was given an empty value. Pass an acc_... id of the Motion, or omit it to let Curviate assign one.");
611
+ const body = (chunk) => ({ contact_ids: chunk, ...f.account !== void 0 ? { account_id: f.account } : {} });
612
+ const method = kind === "add" ? "addContacts" : "removeContacts";
613
+ if (f.preview) return preview(`motions.${method}`, { id: f.id }, body(ids.slice(0, BULK_MAX_IDS)));
614
+ const results = await sendInChunks(ids, BULK_MAX_IDS, (chunk) => c.motions[method](f.id ?? "", body(chunk)), f);
615
+ if (results.length === 1) return renderSuccess(results[0], outputOpts(f), process);
616
+ const last = results[results.length - 1] ?? {};
617
+ const merged = kind === "add" ? { ...last, results: results.flatMap((r) => r?.results ?? []) } : {
618
+ ...last,
619
+ removed: results.reduce((n, r) => n + (r?.removed ?? 0), 0),
620
+ not_found: results.flatMap((r) => r?.not_found ?? [])
621
+ };
622
+ renderSuccess(merged, outputOpts(f), process);
623
+ };
624
+ async function runLint(f) {
625
+ const text = await readFileFlag("file", f.file ?? "", { others: f });
626
+ const doc = parseDocument("file", text);
627
+ const motionFile = !!doc && typeof doc === "object" && !Array.isArray(doc) && !("steps" in doc) && ("sequence" in doc || "name" in doc);
628
+ if (motionFile && doc["sequence"] == null) usage("--file: the Motion file has no sequence; there is nothing to lint.");
629
+ const verdict = await checkSequence(f, text, motionFile ? doc["sequence"] : doc, motionFile ? "/sequence" : "");
630
+ if (outputOpts(f).json) process.stdout.write(JSON.stringify({ errors: [], warnings: verdict.warnings }) + "\n");
631
+ }
632
+ async function runInit(f) {
633
+ const tpl = Object.prototype.hasOwnProperty.call(TEMPLATES, f.template ?? "") ? TEMPLATES[f.template] : void 0;
634
+ if (!tpl) usage(`--template takes one of ${Object.keys(TEMPLATES).join(", ")}.`);
635
+ const doc = structuredClone(tpl);
636
+ doc.schedule.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
637
+ const text = JSON.stringify(doc, null, 2) + "\n";
638
+ if (f.output === void 0) return void process.stdout.write(text);
639
+ try {
640
+ await writeFile(f.output, text);
641
+ } catch (err) {
642
+ usage(`--output: cannot write ${f.output}: ${err.code ?? "write error"}.`);
643
+ }
644
+ process.stderr.write(`Wrote ${f.output}. Next: fill contact_list_ids and account_ids, then \`curviate motion create --file ${f.output}\`.
645
+ `);
646
+ }
647
+ var online = (fn) => async ({ args }) => {
648
+ const f = args;
649
+ await fn(await rootClient(f), f);
650
+ };
651
+ var ID = { type: "positional", description: "Motion id (mot_...)." };
652
+ var FILE_DESC = "The Motion file: a path, or - to read it from stdin. `curviate motion get` output is accepted as is.";
653
+ var SEQUENCE_ERRORS = { SEQUENCE_INVALID: "the Sequence breaks a rule; every error is listed, one line each, as `curviate motion lint` prints them." };
654
+ var ROLE_ERRORS = {
655
+ INSUFFICIENT_ROLE: "your role cannot send from a sending Account of this Motion.",
656
+ ACCOUNT_NOT_SHARED: "a sending Account is not shared with you."
657
+ };
658
+ var SEE_LIFECYCLE = ["curviate motion get", "curviate enrollment list"];
659
+ var listCmd = defineCommand({
660
+ meta: {
661
+ name: "list",
662
+ description: "List your Team's Motions, most recently updated first. Items carry no Sequence: read one with `curviate motion get <motion_id>`.",
663
+ risk: "read",
664
+ examples: ["curviate motion list", "curviate motion list --status active,paused"]
665
+ },
666
+ args: {
667
+ ...readOnly(GLOBAL_FLAGS),
668
+ status: { type: "string", description: `Comma list of ${STATUSES.join(", ")}. Default: all but archived.` }
669
+ },
670
+ run: online(runList)
671
+ });
672
+ var getCmd = defineCommand({
673
+ meta: {
674
+ name: "get",
675
+ description: "One Motion with its current Sequence and lint warnings. With --version, that Sequence version instead, and how many Enrollments still run on it.",
676
+ risk: "read",
677
+ output: ["The full Motion, pasteable: `curviate motion create --file -` and `curviate motion update <motion_id> --file -` accept it as is, dropping the keys Curviate sets."],
678
+ examples: ["curviate motion get mot_YOUR_MOTION_ID", "curviate motion get mot_YOUR_MOTION_ID --version 1"]
679
+ },
680
+ args: {
681
+ ...readOnly(READ_SINGLE_FLAGS),
682
+ id: ID,
683
+ version: { type: "string", description: "A Sequence version number (1 or more)." }
684
+ },
685
+ run: online(runGet)
686
+ });
687
+ var MOTION_DOC = `{
688
+ "name": "Q4 webinar follow-up",
689
+ "contact_list_ids": ["cl_YOUR_LIST_ID"],
690
+ "account_ids": ["acc_YOUR_ACCOUNT_ID"],
691
+ "sequence": {
692
+ "on_reply": "end",
693
+ "steps": [
694
+ { "id": "invite", "do": "invite.send", "with": { "note": null }, "next": "end" }
695
+ ]
696
+ }
697
+ }`;
698
+ var createCmd = defineCommand({
699
+ meta: {
700
+ name: "create",
701
+ description: "Create a Motion from a Motion file, always as a draft: nothing runs until `curviate motion start`. The file is checked before anything is sent, its Sequence as `curviate motion lint` checks it.",
702
+ risk: "write",
703
+ rules: {
704
+ changes: "Creates a draft Motion. No Contact is enrolled and nothing reaches LinkedIn until it is started.",
705
+ visible_to: "Your Team.",
706
+ budget_rows: [],
707
+ retry: "A retry creates a second draft: list with `curviate motion list --status draft` first.",
708
+ undo: "`curviate motion delete <motion_id>` deletes a draft."
709
+ },
710
+ errors: { ...SEQUENCE_ERRORS, ...ROLE_ERRORS, TIER_REQUIRED: "Motions need the Automate plan." },
711
+ seeAlso: ["curviate motion lint", "curviate motion init", "curviate motion preview"],
712
+ document: "motion create",
713
+ examples: [
714
+ "curviate motion create --file motion.json",
715
+ `curviate motion create --file - <<'EOF'
716
+ ${MOTION_DOC}
717
+ EOF`
718
+ ]
719
+ },
720
+ args: {
721
+ ...WRITE_SINGLE_FLAGS,
722
+ file: { type: "string", stdinArg: true, required: true, description: FILE_DESC }
723
+ },
724
+ run: online(runCreate)
725
+ });
726
+ var updateCmd = defineCommand({
727
+ meta: {
728
+ name: "update",
729
+ description: "Change a Motion from a Motion file: objects (schedule, settings) merge by key, arrays and the Sequence replace whole, null clears. After start, a structural Sequence change makes a new version; running Enrollments keep theirs. With --if-revision the save is refused when someone saved the Sequence since.",
730
+ risk: "write",
731
+ rules: {
732
+ changes: "Changes the Motion. A running Motion picks the change up at each Enrollment's next Step.",
733
+ visible_to: "Your Team, and the Contacts its next Steps reach.",
734
+ budget_rows: [],
735
+ retry: "Safe: the same file sends the same change. Without --if-revision the last save wins.",
736
+ undo: "Send the previous file again (`curviate motion get <motion_id> --version <n>` reads an earlier Sequence)."
737
+ },
738
+ errors: {
739
+ ...SEQUENCE_ERRORS,
740
+ SEQUENCE_CONFLICT: "with --if-revision: someone saved the Sequence since that revision; the message names the newer revision and who saved it.",
741
+ MOTION_STATUS_CONFLICT: "an archived Motion, or one past its end, cannot change.",
742
+ ...ROLE_ERRORS
743
+ },
744
+ seeAlso: ["curviate motion get", "curviate motion lint"],
745
+ document: "motion update",
746
+ examples: [
747
+ "curviate motion update mot_YOUR_MOTION_ID --file motion.json --if-revision 3",
748
+ `curviate motion update mot_YOUR_MOTION_ID --file - <<'EOF'
749
+ ${MOTION_DOC}
750
+ EOF`
751
+ ]
752
+ },
753
+ args: {
754
+ ...WRITE_SINGLE_FLAGS,
755
+ id: ID,
756
+ file: { type: "string", stdinArg: true, required: true, description: FILE_DESC },
757
+ "if-revision": { type: "string", description: "The sequence_revision you read (`curviate motion get`). The save is refused with SEQUENCE_CONFLICT when the stored Sequence moved past it. Omitted: the last save wins." }
758
+ },
759
+ run: online(runUpdate)
760
+ });
761
+ var lifecycleCmd = (name, meta) => defineCommand({
762
+ meta: { name, ...meta, examples: [`curviate motion ${name} mot_YOUR_MOTION_ID`] },
763
+ args: { ...WRITE_SINGLE_FLAGS, id: ID },
764
+ run: online(lifecycle(name))
765
+ });
766
+ var startCmd = lifecycleCmd("start", {
767
+ description: "Start a draft: scheduled when its start time is ahead, else active. Freezes Sequence version 1. A Motion missing what it needs is refused with every gap listed.",
768
+ risk: "high",
769
+ rules: {
770
+ changes: "The Motion starts enrolling its Contacts and running its Steps from its sending Accounts, paced on its schedule.",
771
+ visible_to: "The Contacts each Step reaches on LinkedIn.",
772
+ budget_rows: [],
773
+ retry: "A retry on a started Motion answers MOTION_STATUS_CONFLICT; nothing runs twice.",
774
+ undo: "`curviate motion pause <motion_id>` stops new Steps; what was sent stays sent.",
775
+ blast_radius: "Every Contact of its Contact lists, from every sending Account, each Step spending that Account's budgets (`curviate account get <account_id>`)."
776
+ },
777
+ errors: { MOTION_NOT_STARTABLE: "a gap stops it (Contact list, sending Account, timezone, Sequence); each is listed.", MOTION_STATUS_CONFLICT: "only a draft starts.", ...ROLE_ERRORS, TIER_REQUIRED: "Motions need the Automate plan." },
778
+ seeAlso: ["curviate motion preview", "curviate motion pause"]
779
+ });
780
+ var pauseCmd = lifecycleCmd("pause", {
781
+ description: "Pause an active or scheduled Motion: no Step runs until it is resumed. Waits keep their time.",
782
+ risk: "write",
783
+ rules: {
784
+ changes: "No Step of the Motion runs while it is paused.",
785
+ visible_to: "Your Team.",
786
+ budget_rows: [],
787
+ retry: "Safe: a paused Motion answers MOTION_STATUS_CONFLICT.",
788
+ undo: "`curviate motion resume <motion_id>`."
789
+ },
790
+ errors: { MOTION_STATUS_CONFLICT: "only an active or scheduled Motion pauses.", ...ROLE_ERRORS },
791
+ seeAlso: SEE_LIFECYCLE
792
+ });
793
+ var resumeCmd = lifecycleCmd("resume", {
794
+ description: "Resume a paused Motion. Runs the start checks again.",
795
+ risk: "high",
796
+ rules: {
797
+ changes: "The Motion's Steps run again from its sending Accounts.",
798
+ visible_to: "The Contacts each Step reaches on LinkedIn.",
799
+ budget_rows: [],
800
+ retry: "A retry on a running Motion answers MOTION_STATUS_CONFLICT.",
801
+ undo: "`curviate motion pause <motion_id>`; what was sent stays sent.",
802
+ blast_radius: "Every open Enrollment of the Motion."
803
+ },
804
+ errors: { MOTION_NOT_STARTABLE: "a gap stops it; each is listed.", MOTION_STATUS_CONFLICT: "only a paused Motion resumes.", ...ROLE_ERRORS, TIER_REQUIRED: "Motions need the Automate plan." },
805
+ seeAlso: SEE_LIFECYCLE
806
+ });
807
+ var archiveCmd = lifecycleCmd("archive", {
808
+ description: "Archive a Motion: its open Enrollments end (motion_archived) and it never runs again.",
809
+ risk: "high",
810
+ rules: {
811
+ changes: "Ends every open Enrollment and freezes the Motion.",
812
+ visible_to: "Your Team.",
813
+ budget_rows: [],
814
+ retry: "A retry answers MOTION_STATUS_CONFLICT.",
815
+ undo: "Cannot be undone. Create a new Motion from `curviate motion get <motion_id>` output.",
816
+ blast_radius: "Every open Enrollment of the Motion."
817
+ },
818
+ errors: { MOTION_STATUS_CONFLICT: "already archived.", ...ROLE_ERRORS },
819
+ seeAlso: SEE_LIFECYCLE
820
+ });
821
+ var deleteCmd = lifecycleCmd("delete", {
822
+ description: "Delete a draft Motion with its Sequence versions. Any other status: archive it instead.",
823
+ risk: "high",
824
+ rules: {
825
+ changes: "Deletes the draft and its Sequence versions.",
826
+ visible_to: "Your Team.",
827
+ budget_rows: [],
828
+ retry: "A retry answers RESOURCE_NOT_FOUND.",
829
+ undo: "Cannot be undone. Keep `curviate motion get <motion_id>` output to create it again.",
830
+ blast_radius: "One draft Motion; it has no Enrollments."
831
+ },
832
+ errors: { RESOURCE_NOT_FOUND: "no Motion with this id.", MOTION_STATUS_CONFLICT: "only a draft is deleted; archive the others.", ...ROLE_ERRORS },
833
+ seeAlso: ["curviate motion archive", "curviate motion list"]
834
+ });
835
+ var previewCmd = defineCommand({
836
+ meta: {
837
+ name: "preview",
838
+ description: "What the Motion would do, in any status: every path through its Sequence, rendered messages for sampled or named Contacts, and the budget projection. A read: never reaches LinkedIn, spends nothing.",
839
+ risk: "read",
840
+ examples: ["curviate motion preview mot_YOUR_MOTION_ID", "curviate motion preview mot_YOUR_MOTION_ID --sample 3"]
841
+ },
842
+ args: {
843
+ ...readOnly(READ_SINGLE_FLAGS),
844
+ id: ID,
845
+ sample: { type: "string", description: "How many Contacts to render (default 5)." },
846
+ contact: { type: "string", description: "A Contact id (con_...) to render; repeatable, or a comma list. Not with --sample." }
847
+ },
848
+ run: online(runPreview)
849
+ });
850
+ var membershipCmd = (kind) => defineCommand({
851
+ meta: {
852
+ name: kind,
853
+ description: kind === "add" ? "Enroll Contacts directly, on an Account of the Motion (--account) or one Curviate assigns. Every exclusion and filter applies; each Contact's outcome says what happened. Sent in requests of up to 1000 ids, in order." : "Take Contacts out of the Motion: their open Enrollments end (removed). Sent in requests of up to 1000 ids, in order.",
854
+ risk: "high",
855
+ rules: kind === "add" ? {
856
+ changes: "Each queued Contact becomes a pending Enrollment; a running Motion reaches it on its schedule.",
857
+ visible_to: "Your Team now; the Contacts once their Steps run.",
858
+ budget_rows: [],
859
+ retry: "Safe: a Contact already in the Motion answers already_enrolled. After a failed request, send the ids from the failed one on.",
860
+ undo: "`curviate motion remove <motion_id> --contact <contact_id>`; what was sent stays sent.",
861
+ blast_radius: "Every Contact given."
862
+ } : {
863
+ changes: "Ends each named Contact's open Enrollments in the Motion (removed).",
864
+ visible_to: "Your Team.",
865
+ budget_rows: [],
866
+ retry: "Safe: a Contact no longer in the Motion is listed in not_found.",
867
+ undo: "`curviate motion add <motion_id> --contact <contact_id>` enrolls it again.",
868
+ blast_radius: "Every Contact given."
869
+ },
870
+ errors: { MOTION_STATUS_CONFLICT: "an archived Motion, or one past its end, takes no Contacts.", ...ROLE_ERRORS },
871
+ seeAlso: ["curviate enrollment list"],
872
+ examples: kind === "add" ? ["curviate motion add mot_YOUR_MOTION_ID --contact con_YOUR_CONTACT_ID", "curviate motion add mot_YOUR_MOTION_ID --contact con_A,con_B --account acc_YOUR_ACCOUNT_ID"] : ["curviate motion remove mot_YOUR_MOTION_ID --contact con_YOUR_CONTACT_ID"]
873
+ },
874
+ args: {
875
+ ...WRITE_SINGLE_FLAGS,
876
+ id: ID,
877
+ contact: { type: "string", required: true, description: "A Contact id (con_...); repeatable, or a comma list." },
878
+ ...kind === "add" ? { account: { type: "string", description: "Enroll them on this sending Account of the Motion (acc_...). Never defaulted: omit it and Curviate assigns one." } } : {}
879
+ },
880
+ run: online(membership(kind))
881
+ });
882
+ var OFFLINE = { notes: ["Offline: no API call."] };
883
+ var lintCmd = defineCommand({
884
+ meta: {
885
+ name: "lint",
886
+ description: "Check a Sequence offline with the rules the API applies: a Motion file (its sequence) or a bare Sequence document. One line per finding, `<file>:<line>:<col> error|warning <code> <path>: <message>. <hint> -> <docs_url>`; exit 2 on any error, 0 otherwise.",
887
+ risk: "read",
888
+ rules: OFFLINE,
889
+ output: ["Findings on stderr. With --json (or piped), stdout carries `{errors, warnings}`, or on errors the SEQUENCE_INVALID refusal the API would send."],
890
+ examples: ["curviate motion lint --file motion.json"]
891
+ },
892
+ args: {
893
+ json: GLOBAL_FLAGS.json,
894
+ file: { type: "string", stdinArg: true, required: true, description: "A Motion file or a Sequence document: a path, or - to read it from stdin." }
895
+ },
896
+ async run({ args }) {
897
+ await runLint(args);
898
+ }
899
+ });
900
+ var initCmd = defineCommand({
901
+ meta: {
902
+ name: "init",
903
+ description: `Write a Motion file from a template (${Object.keys(TEMPLATES).join(", ")}), its schedule in this machine's timezone. Fill contact_list_ids and account_ids, then create it.`,
904
+ risk: "read",
905
+ rules: OFFLINE,
906
+ output: ["The Motion file on stdout, or in the --output file."],
907
+ examples: ["curviate motion init --template connect-and-converse --output motion.json"]
908
+ },
909
+ args: {
910
+ template: { type: "string", required: true, description: `One of ${Object.keys(TEMPLATES).join(", ")}.` },
911
+ output: { type: "string", alias: "o", description: "Write to this path, replacing what is there. Omitted: stdout." }
912
+ },
913
+ async run({ args }) {
914
+ await runInit(args);
915
+ }
916
+ });
917
+ var motionCommand = defineCommand({
918
+ meta: { name: "motion", description: DESCRIPTIONS.motion },
919
+ subCommands: {
920
+ list: listCmd,
921
+ get: getCmd,
922
+ create: createCmd,
923
+ update: updateCmd,
924
+ start: startCmd,
925
+ pause: pauseCmd,
926
+ resume: resumeCmd,
927
+ archive: archiveCmd,
928
+ delete: deleteCmd,
929
+ preview: previewCmd,
930
+ add: membershipCmd("add"),
931
+ remove: membershipCmd("remove"),
932
+ lint: lintCmd,
933
+ init: initCmd
934
+ },
935
+ async run() {
936
+ const { showHelp } = await import("./examples-NIMSIXMV.js");
937
+ await showHelp(motionCommand, ["curviate", "motion"]);
938
+ }
939
+ });
940
+ export {
941
+ BULK_MAX_IDS,
942
+ TEMPLATES,
943
+ motionCommand,
944
+ runInit,
945
+ runLint
946
+ };