@seguelac/aca-cli 0.6.2 → 0.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  All notable changes to `aca-cli` are documented here. Format loosely follows [Keep a Changelog](https://keepachangelog.com/).
4
4
 
5
+ ## [0.8.0] - 2026-11-04
6
+
7
+ ### Added
8
+ - **`aca scheduler` (alias `aca posts`): the Social Scheduler from the terminal.** `accounts`, `ls`, `show`, `create`, `edit`, `rm`, `approve`, `publish`, `retry`, `stats`, `plan` and `connect`, backed by the `api-scheduler` edge function (the same operations as `/v1/scheduler` and the ACA MCP tools). A post that would fail on a platform is refused with the reason unless saved as a draft.
9
+ - `fnRequest()` in `api.ts`: any method against an edge function, with query parameters, unwrapping `{ success, data }`.
10
+
11
+ ## [0.7.0] - 2026-10-19
12
+
13
+ ### Changed
14
+ - **`aca enroll -l` runs as a server-side background job.** Sending a whole list in one request died past ~50k members (the platform kills a request at 150s). The CLI now starts an enrollment job and follows it, printing progress (a 193k list takes about 4 minutes). Ctrl-C stops watching, not the job. The final output adds a breakdown of skips: already enrolled, active in another sequence, suppressed, no email.
15
+ - `--contacts` with more than 2,500 ids uses the same background job. Smaller batches still enroll synchronously and return counts straight away.
16
+
17
+ ### Added
18
+ - `-l` takes several comma-separated lists (enrolls their union).
19
+ - `--no-wait` starts the job and prints its id without following it.
20
+ - Contact ids can be piped on stdin (comma- or whitespace-separated) when neither `-l` nor `--contacts` is given.
21
+
5
22
  ## [0.6.2] - 2026-09-09
6
23
 
7
24
  ### Added
package/README.md CHANGED
@@ -65,8 +65,8 @@ aca campaign leads <campaignId> --stuck --json | jq '.[] | .contact_id'
65
65
  | `aca lists add -l <listId> --contacts <ids>` | Bulk-add contacts to a list. |
66
66
  | `aca lists members -l <listId>` | List members of a list. |
67
67
  | `aca lists remove -l <listId> --contacts <ids>` | Remove contacts from a list. |
68
- | `aca enroll -c <campaignId> -l <listId>` | Enroll an entire list into a campaign. |
69
- | `aca enroll -c <campaignId> --contacts <ids>` | Enroll specific contacts. |
68
+ | `aca enroll -c <campaignId> -l <listId>` | Enroll an entire list (or several, comma-separated) as a background job and follow its progress. `--no-wait` returns the job id. |
69
+ | `aca enroll -c <campaignId> --contacts <ids>` | Enroll specific contacts (or pipe ids on stdin). Over 2,500 ids runs as a background job. |
70
70
 
71
71
  ### Inbox & replies
72
72
  | Command | What it does |
@@ -105,6 +105,24 @@ aca campaign leads <campaignId> --stuck --json | jq '.[] | .contact_id'
105
105
  | `aca autopilot pause <conversationId> --hours 48` | Pause AI on a conversation. |
106
106
  | `aca autopilot resume <conversationId>` | Re-enable AI. |
107
107
 
108
+ ### Social Scheduler
109
+ Schedule, approve and track posts on every channel (Instagram, Facebook, TikTok, YouTube, Google Business, Threads, Pinterest and X through your Zernio key; LinkedIn; GHL). `aca posts` is an alias.
110
+
111
+ | Command | What it does |
112
+ |---|---|
113
+ | `aca scheduler accounts` | Accounts you can post to, with the ids the other commands take. |
114
+ | `aca scheduler ls --status scheduled,failed` | The calendar (default: last 7 days and next 30). `--from`, `--to`, `--platform`. |
115
+ | `aca scheduler show <id>` | One post: captions, destinations, errors, stats. |
116
+ | `aca scheduler create --accounts <ids> --caption "…" --image <url> --at 2026-11-10T09:00+01:00` | Schedule a post. `--now`, `--draft`, `--for twitter="short version"`, `--video`, `--first-comment`, `--story`. The caption can be piped in. |
117
+ | `aca scheduler edit <id> --at <datetime>` | Reschedule or edit until it goes out (same flags; `--accounts` replaces them). |
118
+ | `aca scheduler approve <ids…>` | Drafts and agent proposals go out at their time. |
119
+ | `aca scheduler publish <id>` / `retry <id>` / `rm <id>` | Publish now, retry a failure, remove. |
120
+ | `aca scheduler stats <id> --refresh` | Reach, likes, comments, engagement of a published post. |
121
+ | `aca scheduler plan "5 LinkedIn posts next week about X"` | The scheduling agent drafts posts into the best free slots. |
122
+ | `aca scheduler connect instagram` | A sign-in link to connect an account through Zernio. |
123
+
124
+ A post that would fail on a platform (Instagram with no picture, X over 280 characters) is refused with the reason, unless you save it with `--draft`.
125
+
108
126
  ### Config & completion
109
127
  | Command | What it does |
110
128
  |---|---|
package/dist/api.js CHANGED
@@ -86,3 +86,28 @@ export async function invokeFn(name, body) {
86
86
  }
87
87
  return parsed;
88
88
  }
89
+ export async function fnRequest(method, name, params = {}, body) {
90
+ const headers = await authHeaders();
91
+ const query = new URLSearchParams();
92
+ for (const [k, v] of Object.entries(params))
93
+ if (v !== undefined && v !== '')
94
+ query.set(k, String(v));
95
+ const qs = query.toString();
96
+ const res = await fetch(`${SUPABASE_URL}/functions/v1/${name}${qs ? `?${qs}` : ''}`, {
97
+ method,
98
+ headers: { ...headers, 'Content-Type': 'application/json' },
99
+ body: body === undefined ? undefined : JSON.stringify(body),
100
+ });
101
+ const text = await res.text();
102
+ let parsed;
103
+ try {
104
+ parsed = text ? JSON.parse(text) : null;
105
+ }
106
+ catch {
107
+ parsed = { error: text };
108
+ }
109
+ if (!res.ok || parsed?.success === false) {
110
+ throw new Error(parsed?.error || `${name} -> ${res.status}`);
111
+ }
112
+ return (parsed?.data ?? parsed);
113
+ }
@@ -1,32 +1,102 @@
1
- import { invokeFn } from '../api.js';
1
+ import { invokeFn, restGet } from '../api.js';
2
2
  import { readConfig } from '../config.js';
3
3
  import { output, fail } from '../output.js';
4
- import { parseList } from '../util.js';
4
+ import { parseList, readStdinIfPiped } from '../util.js';
5
+ const BACKGROUND_THRESHOLD = 2500;
6
+ const POLL_MS = 3000;
7
+ const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
8
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9
+ async function readJob(jobId) {
10
+ const rows = await restGet(`email_enrollment_jobs?id=eq.${jobId}&select=id,status,total,processed,results,error_message,completed_at`);
11
+ if (!rows[0])
12
+ throw new Error(`Enrollment job ${jobId} not found`);
13
+ return rows[0];
14
+ }
15
+ function summarize(job) {
16
+ const r = job.results ?? {};
17
+ return {
18
+ job_id: job.id,
19
+ status: job.status,
20
+ total: job.total,
21
+ processed: job.processed,
22
+ enrolled: r.enrolled ?? 0,
23
+ skipped_already_enrolled: Math.max(0, (r.skipped ?? 0) - (r.filteredOut ?? 0) - (r.awaitingPipeline ?? 0)),
24
+ skipped_active_elsewhere: r.alreadyInAnotherSequence ?? 0,
25
+ skipped_suppressed: r.suppressed ?? 0,
26
+ skipped_no_email: r.noEmail ?? 0,
27
+ skipped_filtered_out: r.filteredOut ?? 0,
28
+ skipped_awaiting_pipeline: r.awaitingPipeline ?? 0,
29
+ skipped_missing_content: r.missingContent ?? 0,
30
+ ...(job.error_message ? { error: job.error_message } : {}),
31
+ };
32
+ }
5
33
  export function registerEnroll(program) {
6
34
  program
7
35
  .command('enroll')
8
36
  .description('Enroll leads into a campaign sequence')
9
37
  .requiredOption('-c, --campaign <sequenceId>', 'Campaign / sequence ID')
10
- .option('-l, --list <listId>', 'Enroll an entire lead list')
11
- .option('--contacts <ids>', 'Comma-separated contact IDs')
38
+ .option('-l, --list <listIds>', 'Enroll one or more lead lists (comma-separated)')
39
+ .option('--contacts <ids>', 'Comma-separated contact IDs (or pipe ids on stdin)')
12
40
  .option('-o, --organization <orgId>', 'Override active organization')
41
+ .option('--no-wait', 'Start a background enrollment and return its job id without waiting')
13
42
  .option('--json', 'Emit JSON')
14
43
  .action(async (opts) => {
15
44
  const orgId = opts.organization || readConfig().active_org_id;
16
45
  if (!orgId) {
17
46
  fail('No active organization. Run `aca org switch <id>` or pass --organization.');
18
47
  }
48
+ const listIds = parseList(opts.list);
49
+ let contactIds = parseList(opts.contacts);
50
+ if (!listIds.length && !contactIds.length) {
51
+ const piped = await readStdinIfPiped();
52
+ if (piped)
53
+ contactIds = piped.split(/[\s,]+/).filter(Boolean);
54
+ }
55
+ if (!listIds.length && !contactIds.length) {
56
+ fail('Provide either --list <id> or --contacts <id1,id2,...> (or pipe contact ids on stdin)');
57
+ }
19
58
  const body = {
20
59
  sequenceId: opts.campaign,
21
60
  organizationId: orgId,
61
+ ...(listIds.length ? { listIds } : { contactIds }),
22
62
  };
23
- if (opts.list)
24
- body.listId = opts.list;
25
- else if (opts.contacts)
26
- body.contactIds = parseList(opts.contacts);
27
- else
28
- fail('Provide either --list <id> or --contacts <id1,id2,...>');
29
- const result = await invokeFn('enroll-leads', body);
30
- output(result, { json: opts.json });
63
+ if (!listIds.length && contactIds.length <= BACKGROUND_THRESHOLD) {
64
+ output(await invokeFn('enroll-leads', body), { json: opts.json });
65
+ return;
66
+ }
67
+ const started = await invokeFn('enroll-leads', { ...body, background: true });
68
+ if (!started.jobId) {
69
+ output(started, { json: opts.json });
70
+ return;
71
+ }
72
+ if (started.existing && !opts.json) {
73
+ process.stderr.write(`An enrollment is already running for this sequence; following job ${started.jobId}\n`);
74
+ }
75
+ if (!opts.wait) {
76
+ output({ job_id: started.jobId, status: started.status, already_running: started.existing === true }, { json: opts.json });
77
+ return;
78
+ }
79
+ if (!opts.json) {
80
+ process.stderr.write(`Enrolling in the background (job ${started.jobId}). Ctrl-C stops watching, not the job.\n`);
81
+ }
82
+ let lastLine = '';
83
+ for (;;) {
84
+ const job = await readJob(started.jobId);
85
+ if (TERMINAL.has(job.status)) {
86
+ output(summarize(job), { json: opts.json });
87
+ if (job.status === 'failed')
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+ if (!opts.json) {
92
+ const line = job.status === 'running'
93
+ ? ` …${job.processed}/${job.total} checked, ${job.results?.enrolled ?? 0} enrolled`
94
+ : ` …preparing audience (${job.total} contacts so far)`;
95
+ if (line !== lastLine)
96
+ process.stderr.write(`${line}\n`);
97
+ lastLine = line;
98
+ }
99
+ await sleep(POLL_MS);
100
+ }
31
101
  });
32
102
  }
@@ -0,0 +1,158 @@
1
+ import { restGet, restPost } from '../api.js';
2
+ import { readConfig } from '../config.js';
3
+ import { output } from '../output.js';
4
+ function activeOrg(override) {
5
+ const orgId = override || readConfig().active_org_id;
6
+ if (!orgId)
7
+ throw new Error('No active organization. Run `aca org switch <id>` or pass --organization.');
8
+ return orgId;
9
+ }
10
+ function stepRate(part, base, floor) {
11
+ return base >= floor && base > 0 ? Math.round((part / base) * 1000) / 10 : null;
12
+ }
13
+ const DBR_FIRST_SMS = "Hi {{first_name}}, you asked us about this a while back. Is it still something you're looking into?";
14
+ const DBR_LAST_SMS = 'Hi {{first_name}}, last message from me. Should I close your file, or is there a better time to talk?';
15
+ function buildDbrSequence(opts) {
16
+ const steps = [{ id: 'start', type: 'start', data: {} }];
17
+ const handoff = (id, channel) => {
18
+ if (!opts.agentId)
19
+ return;
20
+ steps.push({
21
+ id,
22
+ type: 'handoffToAgent',
23
+ data: { agentProfileId: opts.agentId, exitAfterHandoff: false, channel, continueOnFailure: true },
24
+ });
25
+ };
26
+ if (opts.templateId) {
27
+ steps.push({
28
+ id: 'dbr-whatsapp',
29
+ type: 'whatsappTemplate',
30
+ data: { templateId: opts.templateId, templateName: opts.templateName, continueOnFailure: true },
31
+ });
32
+ handoff('dbr-ai-whatsapp', 'whatsapp');
33
+ steps.push({ id: 'dbr-wait-1', type: 'delay', data: { days: opts.daysAfterWhatsApp, hours: 0, minutes: 0 } });
34
+ }
35
+ steps.push({ id: 'dbr-sms-1', type: 'smsMessage', data: { message: opts.firstSms, messageVariations: [] } });
36
+ handoff('dbr-ai-sms', 'sms');
37
+ steps.push({ id: 'dbr-wait-2', type: 'delay', data: { days: opts.daysBetweenSms, hours: 0, minutes: 0 } });
38
+ steps.push({ id: 'dbr-sms-2', type: 'smsMessage', data: { message: opts.lastSms, messageVariations: [] } });
39
+ steps.push({ id: 'dbr-end', type: 'end', data: {} });
40
+ const nodes = steps.map((s, i) => ({ ...s, position: { x: 450, y: i * 160 } }));
41
+ const edges = nodes.slice(1).map((n, i) => ({
42
+ id: `edge-${nodes[i].id}-${n.id}-default`,
43
+ type: 'sequenceEdge',
44
+ source: nodes[i].id,
45
+ target: n.id,
46
+ sourceHandle: 'default',
47
+ }));
48
+ return { nodes, edges };
49
+ }
50
+ export function registerMessaging(program) {
51
+ const messaging = program
52
+ .command('messaging')
53
+ .description('SMS and WhatsApp Business (Twilio): senders, templates, funnel, DBR campaigns');
54
+ messaging
55
+ .command('senders')
56
+ .description('List Twilio senders (SMS numbers / sender names, WhatsApp Business senders)')
57
+ .option('--channel <channel>', 'sms | whatsapp_business')
58
+ .option('-o, --organization <orgId>', 'Override active organization')
59
+ .option('--json', 'Emit JSON')
60
+ .action(async (opts) => {
61
+ const params = new URLSearchParams({
62
+ select: 'id,channel,address,address_type,country,two_way,daily_new_contact_cap,status,status_detail,wa_display_name,wa_quality_rating,wa_messaging_limit',
63
+ organization_id: `eq.${activeOrg(opts.organization)}`,
64
+ order: 'channel.asc,address.asc',
65
+ });
66
+ if (opts.channel)
67
+ params.append('channel', `eq.${opts.channel}`);
68
+ output(await restGet(`messaging_senders?${params.toString()}`), { json: opts.json });
69
+ });
70
+ messaging
71
+ .command('templates')
72
+ .description('List WhatsApp Business templates and their Meta approval status')
73
+ .option('--status <status>', 'approved | pending | submitted | rejected | draft | paused | disabled')
74
+ .option('-o, --organization <orgId>', 'Override active organization')
75
+ .option('--json', 'Emit JSON')
76
+ .action(async (opts) => {
77
+ const params = new URLSearchParams({
78
+ select: 'id,name,language,category,approval_status,body,variables,rejected_reason',
79
+ organization_id: `eq.${activeOrg(opts.organization)}`,
80
+ order: 'created_at.desc',
81
+ });
82
+ if (opts.status)
83
+ params.append('approval_status', `eq.${opts.status}`);
84
+ output(await restGet(`whatsapp_templates?${params.toString()}`), { json: opts.json });
85
+ });
86
+ messaging
87
+ .command('funnel')
88
+ .description('Sent → delivered → replied → positive → booked for SMS / WhatsApp campaign steps (in leads)')
89
+ .option('--campaign <campaignId>', 'One campaign (default: all)')
90
+ .option('--days <n>', 'Look-back window in days', '90')
91
+ .option('-o, --organization <orgId>', 'Override active organization')
92
+ .option('--json', 'Emit JSON')
93
+ .action(async (opts) => {
94
+ const days = Number(opts.days) || 90;
95
+ const rows = await restPost('rpc/messaging_funnel', {
96
+ p_org_id: activeOrg(opts.organization),
97
+ p_campaign_id: opts.campaign ?? null,
98
+ p_since: new Date(Date.now() - days * 86_400_000).toISOString(),
99
+ });
100
+ const withRates = rows.map((r) => ({
101
+ ...r,
102
+ 'delivered_%_of_sent': stepRate(r.delivered, r.sent, 1),
103
+ 'replied_%_of_delivered': stepRate(r.replied, r.delivered, 1),
104
+ 'positive_%_of_replies': stepRate(r.positive, r.replied, 5),
105
+ 'booked_%_of_positive': stepRate(r.booked, r.positive, 3),
106
+ }));
107
+ output(withRates, { json: opts.json });
108
+ });
109
+ messaging
110
+ .command('dbr')
111
+ .description('Create a draft database reactivation campaign: optional WhatsApp template, then two SMS')
112
+ .option('--name <name>', 'Campaign name', 'Database reactivation')
113
+ .option('--list <listId>', 'Lead list to target (can also be picked in the app)')
114
+ .option('--template <templateId>', 'WhatsApp template (approved or in review); omit for SMS only')
115
+ .option('--first-sms <text>', 'First text', DBR_FIRST_SMS)
116
+ .option('--last-sms <text>', 'Last nudge', DBR_LAST_SMS)
117
+ .option('--days-after-whatsapp <n>', 'Days between the WhatsApp template and the first SMS', '2')
118
+ .option('--days-between-sms <n>', 'Days between the two SMS', '3')
119
+ .option('--agent <agentProfileId>', 'AI agent that answers replies (omit to answer from the inbox)')
120
+ .option('-o, --organization <orgId>', 'Override active organization')
121
+ .option('--json', 'Emit JSON')
122
+ .action(async (opts) => {
123
+ const orgId = activeOrg(opts.organization);
124
+ let templateName;
125
+ if (opts.template) {
126
+ const found = await restGet(`whatsapp_templates?select=name,approval_status&id=eq.${opts.template}&organization_id=eq.${orgId}`);
127
+ if (found.length === 0)
128
+ throw new Error('WhatsApp template not found (aca messaging templates)');
129
+ if (!['approved', 'pending', 'submitted'].includes(found[0].approval_status)) {
130
+ throw new Error(`Template "${found[0].name}" is ${found[0].approval_status}; pick an approved one`);
131
+ }
132
+ templateName = found[0].name;
133
+ }
134
+ const { nodes, edges } = buildDbrSequence({
135
+ templateId: opts.template,
136
+ templateName,
137
+ firstSms: opts.firstSms,
138
+ lastSms: opts.lastSms,
139
+ daysAfterWhatsApp: Number(opts.daysAfterWhatsapp) || 2,
140
+ daysBetweenSms: Number(opts.daysBetweenSms) || 3,
141
+ agentId: opts.agent,
142
+ });
143
+ const created = await restPost('linkedin_campaigns?select=id,name,status', {
144
+ organization_id: orgId,
145
+ name: opts.name,
146
+ description: 'Database reactivation over WhatsApp Business and SMS',
147
+ status: 'draft',
148
+ lead_list_ids: opts.list ? [opts.list] : [],
149
+ sequence_nodes: nodes,
150
+ sequence_edges: edges,
151
+ stop_on_reply: true,
152
+ agent_profile_id: opts.agent ?? null,
153
+ campaign_type: 'sms_whatsapp',
154
+ primary_channel: 'sms',
155
+ });
156
+ output({ ...created[0], next: 'Review it in the app (Automations), then set it active.' }, { json: opts.json });
157
+ });
158
+ }
@@ -7,6 +7,7 @@ export function registerReply(program) {
7
7
  .description('Reply to an existing CRM conversation')
8
8
  .argument('<conversationId>')
9
9
  .option('-m, --message <text>', 'Reply body (or pipe via stdin)')
10
+ .option('--html', 'Send --message/stdin as raw HTML instead of plain text (email channels only) — e.g. an <a href><img></a> snippet to embed a linked thumbnail like a Loom video preview')
10
11
  .option('--subject <text>', 'Email subject (email channels only)')
11
12
  .option('--cc <emails>', 'Comma-separated CC list (email only)')
12
13
  .option('--bcc <emails>', 'Comma-separated BCC list (email only)')
@@ -23,12 +24,16 @@ export function registerReply(program) {
23
24
  if (!conv.external_participant_id) {
24
25
  fail('Conversation is missing external_participant_id — cannot determine recipient.');
25
26
  }
27
+ if (opts.html && conv.channel !== 'email' && !conv.mailbox_id) {
28
+ fail('--html is only meaningful for email conversations — other channels send it as literal text.');
29
+ }
26
30
  const body = {
27
31
  conversation_id: conv.id,
28
32
  contact_id: conv.contact_id,
29
33
  channel: conv.channel,
30
34
  recipient_external_id: conv.external_participant_id,
31
35
  content,
36
+ content_type: opts.html ? 'html' : 'text',
32
37
  };
33
38
  if (conv.channel_account_id)
34
39
  body.channel_account_id = conv.channel_account_id;
@@ -0,0 +1,272 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fnRequest } from '../api.js';
3
+ import { output, fail } from '../output.js';
4
+ import { parseList, readStdinIfPiped } from '../util.js';
5
+ const FN = 'api-scheduler';
6
+ const collect = (value, previous = []) => [...previous, value];
7
+ function row(p) {
8
+ const s = p.stats;
9
+ return {
10
+ id: p.id,
11
+ when: (p.published_at ?? p.scheduled_for).slice(0, 16).replace('T', ' '),
12
+ status: p.status,
13
+ platforms: [...new Set(p.destinations.map((d) => d.platform))].join(','),
14
+ caption: p.caption.replace(/\s+/g, ' ').slice(0, 48),
15
+ stats: s && (s.status === 'synced' || s.status === 'pending') && (s.likes + s.comments + s.reach + s.views) > 0
16
+ ? `${s.likes} likes · ${s.comments} comments · ${s.reach || s.views} reach`
17
+ : s?.status === 'no_access' ? 'no analytics on Zernio plan' : '',
18
+ error: p.error ? p.error.slice(0, 60) : '',
19
+ };
20
+ }
21
+ async function readCaption(opts) {
22
+ if (opts.caption !== undefined)
23
+ return opts.caption;
24
+ if (opts.captionFile)
25
+ return readFileSync(opts.captionFile, 'utf8');
26
+ const piped = await readStdinIfPiped();
27
+ return piped ?? undefined;
28
+ }
29
+ function readCaptionsFor(values) {
30
+ if (!values?.length)
31
+ return undefined;
32
+ const out = {};
33
+ for (const v of values) {
34
+ const i = v.indexOf('=');
35
+ if (i < 1)
36
+ fail(`--for needs platform=text, got "${v}"`);
37
+ out[v.slice(0, i).trim().toLowerCase()] = v.slice(i + 1);
38
+ }
39
+ return out;
40
+ }
41
+ async function postBody(opts, creating) {
42
+ const body = {};
43
+ if (opts.accounts !== undefined)
44
+ body.accounts = parseList(opts.accounts);
45
+ else if (creating)
46
+ fail('--accounts is required (ids from `aca scheduler accounts`)');
47
+ const caption = await readCaption(opts);
48
+ if (caption !== undefined)
49
+ body.caption = caption;
50
+ const captions = readCaptionsFor(opts.for);
51
+ if (captions)
52
+ body.captions = captions;
53
+ if (opts.image?.length)
54
+ body.images = opts.image;
55
+ if (opts.video)
56
+ body.video = opts.video;
57
+ if (opts.firstComment !== undefined)
58
+ body.first_comment = opts.firstComment;
59
+ if (opts.story)
60
+ body.format = 'story';
61
+ if (opts.feed)
62
+ body.format = 'feed';
63
+ if (opts.now)
64
+ body.publish_now = true;
65
+ else if (opts.at) {
66
+ const at = new Date(opts.at);
67
+ if (!Number.isFinite(at.getTime()))
68
+ fail(`--at is not a date: ${opts.at}`);
69
+ body.scheduled_for = at.toISOString();
70
+ }
71
+ if (opts.draft)
72
+ body.status = 'draft';
73
+ if (opts.scheduled)
74
+ body.status = 'scheduled';
75
+ if (opts.title)
76
+ body.title = opts.title;
77
+ return body;
78
+ }
79
+ function postOptions(cmd) {
80
+ return cmd
81
+ .option('--accounts <ids>', 'Comma-separated account ids (from `aca scheduler accounts`)')
82
+ .option('--caption <text>', 'Caption for every platform (or --caption-file, or pipe it in)')
83
+ .option('--caption-file <path>', 'Read the caption from a file')
84
+ .option('--for <platform=text>', 'Caption for one platform, e.g. --for twitter="short version" (repeatable)', collect)
85
+ .option('--image <url>', 'Picture URL, https (repeatable, in order)', collect)
86
+ .option('--video <url>', 'One video URL, https')
87
+ .option('--first-comment <text>', 'Posted as the first comment (LinkedIn, Facebook, Instagram)')
88
+ .option('--story', 'Post Instagram/Facebook as a Story')
89
+ .option('--feed', 'Post to the feed (default)')
90
+ .option('--at <datetime>', 'When, e.g. 2026-11-10T09:00+01:00')
91
+ .option('--now', 'Publish at the next queue run (within 5 minutes)')
92
+ .option('--draft', 'Save as a draft to review instead of scheduling')
93
+ .option('--scheduled', 'Schedule a draft')
94
+ .option('--title <text>', 'Internal label')
95
+ .option('--json', 'Emit JSON');
96
+ }
97
+ function printPost(result, json) {
98
+ if (json)
99
+ return output(result, { json: true });
100
+ const post = 'post' in result && result.post ? result.post : result;
101
+ output(row(post));
102
+ for (const d of post.destinations)
103
+ console.log(` → ${d.platform.padEnd(10)} ${d.status.padEnd(10)} ${d.account_id}${d.error ? ` (${d.error})` : ''}`);
104
+ const extra = result;
105
+ for (const n of extra.notes ?? [])
106
+ console.log(`note: ${n}`);
107
+ for (const i of extra.issues ?? [])
108
+ console.log(`fix before scheduling: ${i.message}`);
109
+ }
110
+ export function registerScheduler(program) {
111
+ const scheduler = program
112
+ .command('scheduler')
113
+ .alias('posts')
114
+ .description('Social Scheduler: schedule, approve and track posts on every channel');
115
+ scheduler
116
+ .command('accounts')
117
+ .description('Accounts you can post to (Zernio, native LinkedIn, GHL, X)')
118
+ .option('--json', 'Emit JSON')
119
+ .action(async (opts) => {
120
+ const data = await fnRequest('GET', FN, { resource: 'accounts' });
121
+ if (opts.json)
122
+ return output(data, { json: true });
123
+ const w = Math.max(2, ...data.accounts.map((a) => String(a.id).length));
124
+ console.log(`${'id'.padEnd(w)} ${'platform'.padEnd(10)} ${'provider'.padEnd(15)} name`);
125
+ for (const a of data.accounts) {
126
+ const handle = a.username ? ` (@${String(a.username).replace(/^@/, '')})` : '';
127
+ console.log(`${String(a.id).padEnd(w)} ${String(a.platform).padEnd(10)} ${String(a.provider).padEnd(15)} ${a.name}${handle}`);
128
+ }
129
+ for (const n of data.notes)
130
+ console.log(`note: ${n}`);
131
+ });
132
+ scheduler
133
+ .command('ls')
134
+ .description('Posts on the calendar (default: last 7 days and next 30)')
135
+ .option('--from <datetime>', 'Window start')
136
+ .option('--to <datetime>', 'Window end (at most 120 days after --from)')
137
+ .option('--status <list>', 'draft,scheduled,publishing,published,failed')
138
+ .option('--platform <name>', 'instagram, linkedin, facebook, tiktok, twitter…')
139
+ .option('--limit <n>', 'Max posts (max 200)', '50')
140
+ .option('--json', 'Emit JSON')
141
+ .action(async (opts) => {
142
+ const data = await fnRequest('GET', FN, {
143
+ resource: 'posts',
144
+ from: opts.from ? new Date(opts.from).toISOString() : undefined,
145
+ to: opts.to ? new Date(opts.to).toISOString() : undefined,
146
+ status: opts.status,
147
+ platform: opts.platform,
148
+ limit: opts.limit,
149
+ });
150
+ if (opts.json)
151
+ return output(data, { json: true });
152
+ output(data.posts.map(row));
153
+ if (data.truncated)
154
+ console.log(`(${data.posts.length} of ${data.total}; raise --limit or narrow the window)`);
155
+ });
156
+ scheduler
157
+ .command('show')
158
+ .description('One post: captions, media, destinations, errors, stats')
159
+ .argument('<id>')
160
+ .option('--history', 'Include the stats history')
161
+ .option('--json', 'Emit JSON')
162
+ .action(async (id, opts) => {
163
+ const post = await fnRequest('GET', FN, { resource: 'posts', id, history: opts.history ? 'true' : undefined });
164
+ if (opts.json)
165
+ return output(post, { json: true });
166
+ printPost(post);
167
+ console.log('');
168
+ console.log(post.caption);
169
+ });
170
+ postOptions(scheduler.command('create').description('Schedule a post (or --draft to review first)'))
171
+ .action(async (opts) => {
172
+ const result = await fnRequest('POST', FN, { resource: 'posts' }, await postBody(opts, true));
173
+ printPost(result, opts.json);
174
+ });
175
+ postOptions(scheduler.command('edit').description('Edit or reschedule a post until it goes out').argument('<id>'))
176
+ .action(async (id, opts) => {
177
+ const body = await postBody(opts, false);
178
+ if (!Object.keys(body).length)
179
+ fail('Nothing to change: give --at, --caption, --image, --accounts…');
180
+ const result = await fnRequest('PATCH', FN, { resource: 'posts', id }, body);
181
+ printPost(result, opts.json);
182
+ });
183
+ scheduler
184
+ .command('rm')
185
+ .description('Remove a post that has not gone out')
186
+ .argument('<id>')
187
+ .option('--json', 'Emit JSON')
188
+ .action(async (id, opts) => {
189
+ output(await fnRequest('DELETE', FN, { resource: 'posts', id }), { json: opts.json });
190
+ });
191
+ scheduler
192
+ .command('approve')
193
+ .description('Approve drafts and agent proposals so they go out')
194
+ .argument('<ids...>')
195
+ .option('--json', 'Emit JSON')
196
+ .action(async (ids, opts) => {
197
+ const data = await fnRequest('POST', FN, { resource: 'posts', action: 'approve' }, { ids: ids.flatMap((i) => parseList(i)) });
198
+ if (opts.json)
199
+ return output(data, { json: true });
200
+ console.log(`approved: ${data.approved.length}`);
201
+ for (const b of data.blocked)
202
+ console.log(`blocked ${b.id}: ${b.reason}`);
203
+ });
204
+ scheduler
205
+ .command('publish')
206
+ .description('Publish now (next queue run, within 5 minutes)')
207
+ .argument('<id>')
208
+ .option('--json', 'Emit JSON')
209
+ .action(async (id, opts) => {
210
+ const data = await fnRequest('POST', FN, { resource: 'posts', id, action: 'publish' });
211
+ printPost(data, opts.json);
212
+ if (!opts.json)
213
+ console.log(data.note);
214
+ });
215
+ scheduler
216
+ .command('retry')
217
+ .description("Put a post's failed destinations back in the queue")
218
+ .argument('<id>')
219
+ .option('--json', 'Emit JSON')
220
+ .action(async (id, opts) => {
221
+ printPost(await fnRequest('POST', FN, { resource: 'posts', id, action: 'retry' }), opts.json);
222
+ });
223
+ scheduler
224
+ .command('stats')
225
+ .description('How a published post did: reach, likes, comments, engagement')
226
+ .argument('<id>')
227
+ .option('--refresh', 'Read the latest numbers from the platform first')
228
+ .option('--json', 'Emit JSON')
229
+ .action(async (id, opts) => {
230
+ const data = await fnRequest('GET', FN, { resource: 'stats', id, refresh: opts.refresh ? 'true' : undefined });
231
+ if (opts.json)
232
+ return output(data, { json: true });
233
+ if (!data.stats)
234
+ return console.log(data.note ?? 'No stats for this post.');
235
+ output(data.stats);
236
+ });
237
+ scheduler
238
+ .command('plan')
239
+ .description('Let the scheduling agent draft posts into the best free slots')
240
+ .argument('<instruction>', 'e.g. "5 LinkedIn posts next week about our new feature"')
241
+ .option('--accounts <ids>', 'Comma-separated account ids (default: all)')
242
+ .option('--from <datetime>', 'Planning window start (default now)')
243
+ .option('--to <datetime>', 'Planning window end (default 7 days)')
244
+ .option('--tz <zone>', 'Timezone for slots', Intl.DateTimeFormat().resolvedOptions().timeZone)
245
+ .option('--json', 'Emit JSON')
246
+ .action(async (instruction, opts) => {
247
+ const data = await fnRequest('POST', FN, { resource: 'plan' }, {
248
+ instruction,
249
+ accounts: opts.accounts ? parseList(opts.accounts) : undefined,
250
+ range_start: opts.from ? new Date(opts.from).toISOString() : undefined,
251
+ range_end: opts.to ? new Date(opts.to).toISOString() : undefined,
252
+ timezone: opts.tz,
253
+ });
254
+ if (opts.json)
255
+ return output(data, { json: true });
256
+ console.log(data.summary);
257
+ output(data.proposals.map(row));
258
+ console.log(`\n${data.next_step.replace('approve_scheduled_posts (POST /v1/scheduler/posts/approve)', '`aca scheduler approve <ids>`')}`);
259
+ });
260
+ scheduler
261
+ .command('connect')
262
+ .description('Get a sign-in link to connect a social account (through Zernio)')
263
+ .argument('<platform>', 'instagram, facebook, tiktok, youtube, google, threads, pinterest, twitter, linkedin')
264
+ .option('--json', 'Emit JSON')
265
+ .action(async (platform, opts) => {
266
+ const data = await fnRequest('POST', FN, { resource: 'accounts', action: 'connect' }, { platform });
267
+ if (opts.json)
268
+ return output(data, { json: true });
269
+ console.log(data.connect_url);
270
+ console.log(data.note);
271
+ });
272
+ }
package/dist/index.js CHANGED
@@ -15,6 +15,8 @@ import { registerSequence } from './commands/sequence.js';
15
15
  import { registerContact } from './commands/contact.js';
16
16
  import { registerSignals } from './commands/signals.js';
17
17
  import { registerAutopilot } from './commands/autopilot.js';
18
+ import { registerMessaging } from './commands/messaging.js';
19
+ import { registerScheduler } from './commands/scheduler.js';
18
20
  import { registerConfig } from './commands/config.js';
19
21
  import { registerCompletion } from './commands/completion.js';
20
22
  import { maybeCheckForUpdate } from './update-check.js';
@@ -38,6 +40,8 @@ registerSequence(program);
38
40
  registerContact(program);
39
41
  registerSignals(program);
40
42
  registerAutopilot(program);
43
+ registerMessaging(program);
44
+ registerScheduler(program);
41
45
  registerConfig(program);
42
46
  registerCompletion(program);
43
47
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seguelac/aca-cli",
3
- "version": "0.6.2",
3
+ "version": "0.8.0",
4
4
  "description": "Command-line interface for ACA (Automated Client Acquisition) — push leads to campaigns, triage replies, manage contacts, all from your terminal.",
5
5
  "type": "module",
6
6
  "bin": {