@chaouidz/postpilot 1.0.0 → 1.1.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/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  Thin Node.js 20+ client for the same approval-based API used by MCP. No bundled server or provider credentials. Public docs: https://postpilot.yktis.com/docs.
4
4
 
5
- Install from npm: `npm install -g @chaouidz/postpilot@1.0.0`, then run `postpilot help`.
6
- Without a global install: `npx @chaouidz/postpilot@1.0.0 help`.
5
+ Install from npm: `npm install -g @chaouidz/postpilot@1.1.0`, then run `postpilot help`.
6
+ Without a global install: `npx @chaouidz/postpilot@1.1.0 help`.
7
7
  Package: https://www.npmjs.com/package/@chaouidz/postpilot.
8
8
  The original versioned download remains available: `npm install -g https://postpilot.yktis.com/downloads/postpilot-1.0.0.tgz`.
9
- For source review: run `npm pack` in `packages/cli`, then `npm install -g ./chaouidz-postpilot-1.0.0.tgz`. Packing does not publish to npm.
9
+ For source review: run `npm pack` in `packages/cli`, then `npm install -g ./chaouidz-postpilot-1.1.0.tgz`. Packing does not publish to npm.
10
10
 
11
11
  Python, PHP and other languages can call the HTTP API directly or invoke this CLI as a subprocess. npm distributes the Node.js CLI; it does not require your application to use JavaScript. There is no separate pip or Composer package.
12
12
 
@@ -43,6 +43,41 @@ Other commands: `assets list [--limit 1-100] [--cursor CURSOR]`, `publish --post
43
43
 
44
44
  All commands accept `--json` and `--non-interactive`. `--account`, `--at`, `--privacy` and `--dry-run` apply where relevant; help lists the full syntax. Keep an idempotency key identical on retries of one operation. Inspect failed/ambiguous delivery before attempting a new publication.
45
45
 
46
+ ## Schedule a plan with one approval
47
+
48
+ ```json
49
+ [
50
+ {
51
+ "video": "videos/first.mp4",
52
+ "title": "First video",
53
+ "description": "My description",
54
+ "tags": ["tutorial", "workflow"],
55
+ "scheduledAt": "2027-02-01T09:00:00+01:00",
56
+ "account": "My Tutorials"
57
+ }
58
+ ]
59
+ ```
60
+
61
+ Paths are relative to the JSON file. Use an array or `{ "posts": [...] }`, with 1-100 items. Each account must be an exact ID or uniquely named account visible to your token. `--account` supplies a fallback for items without an account.
62
+
63
+ ```sh
64
+ postpilot schedule --file plan.json
65
+ # Default is read-only. Review the preview, then explicitly prepare the plan:
66
+ postpilot schedule --file plan.json --yes
67
+ # Open the single returned approvalUrl and review every video/account/time.
68
+ postpilot status --approval APPROVAL_ID --json
69
+ ```
70
+
71
+ `--yes` prepares uploads and drafts; the batch still needs human approval. It never proves approval or bypasses it. `--yes --dry-run` is rejected. Existing single-post scheduling commands retain their behavior for compatibility.
72
+
73
+ The CLI validates every file and the server calendar-day cap before any upload. Default capacity is 10 posts per account per local calendar day, configurable by plan. A rejected plan identifies the account/day and item numbers to move. Existing billing entitlements and provider quotas still apply. Twenty posts over ten days fit the default daily cap on an eligible plan.
74
+
75
+ MP4 files are limited to 90 MiB each; use `prepare-video` first for other formats. Only HTTP 429 uploads retry, at most five retries, honoring seconds or HTTP-date Retry-After. A wait over five minutes stops with an actionable error. Ambiguous network failures never retry automatically.
76
+
77
+ Stable per-item keys and a `.postpilot-*.json` checkpoint beside the plan allow interrupted runs to resume without uploading or creating drafts again. Checkpoints contain hashes, post IDs and an approval link, never credentials or file contents. Do not edit them. Reusing an explicit `--idempotency-key` for changed content is rejected. Inspect expired/failed/partly failed batch results and prepare only intended retries with a new plan key.
78
+
79
+ YouTube defaults to private visibility; optional `privacy` selects `private`, `unlisted` or `public`. Tags become YouTube keywords and are appended as hashtags to other platform captions. TikTok items must include explicit `tiktokSettings` with `privacy`, `allowComments`, `allowDuet` and `allowStitch`; creator policy is rechecked during approval. Pinterest requires the target board in `pinterestSettings.boardIds`. Existing platform settings can be supplied through `facebookSettings`, `instagramPostType` and `instagramCaption`.
80
+
46
81
  ## Exit codes
47
82
 
48
83
  0 success, 2 invalid usage/input, 3 authentication or scope failure, 4 not found, 5 pending browser approval, 6 rate limited, 7 provider/network/server failure. JSON errors include stable `code`, `message`, and available request/retry details. Honor Retry-After; provider quotas are not unlimited or guaranteed.
package/bin/postpilot.mjs CHANGED
@@ -2,13 +2,15 @@
2
2
  import { execFile } from "node:child_process";
3
3
  import { promisify } from "node:util";
4
4
  import { Client, CliError, EXIT_CODES } from "../src/client.mjs";
5
+ import { schedulePlan } from "../src/plan.mjs";
5
6
  import { keychain } from "../src/keychain.mjs";
6
7
  const args = process.argv.slice(2),
7
8
  options = {},
8
9
  positionals = [];
9
- const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "help"]);
10
+ const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "help", "yes"]);
10
11
  const valued = new Set([
11
12
  "url",
13
+ "file",
12
14
  "account",
13
15
  "at",
14
16
  "privacy",
@@ -96,12 +98,15 @@ try {
96
98
  "upload <file>",
97
99
  "prepare-video <file> --output <file>",
98
100
  "draft create --account <id-or-name> --asset <id>",
101
+ "schedule --file <plan.json> [--account <id-or-name>] [--dry-run | --yes]",
99
102
  "schedule --post <id> --account <id-or-name> --at <ISO-offset>",
100
103
  "publish --post <id> --account <id-or-name>",
101
104
  "status --post <id>",
102
105
  "cancel --post <id>",
103
106
  ],
104
107
  flags: [
108
+ "--file",
109
+ "--yes",
105
110
  "--account",
106
111
  "--at",
107
112
  "--privacy",
@@ -231,6 +236,9 @@ try {
231
236
  };
232
237
  if (options["dry-run"]) output({ dryRun: true, post, created: false });
233
238
  else output(await client.tool("post_create_draft", { post, ...key }));
239
+ } else if (command === "schedule" && options.file) {
240
+ if (options.post || options.at) throw new CliError("Use --file or --post/--at, not both.");
241
+ output(await schedulePlan(client, options.file, options));
234
242
  } else if (["schedule", "publish"].includes(command)) {
235
243
  const account = await client.account(required("account"));
236
244
  const postId = required("post");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaouidz/postpilot",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "PostPilot CLI for scoped, approval-based social publishing and analytics",
5
5
  "type": "module",
6
6
  "bin": {
package/src/client.mjs CHANGED
@@ -51,7 +51,7 @@ export class Client {
51
51
  );
52
52
  }
53
53
  const body = await response.json().catch(() => ({}));
54
- const error = body.error?.data || body.error;
54
+ const error = (body.result?.isError ? body.result.structuredContent?.error : null) || body.error?.data || body.error;
55
55
  if (!response.ok)
56
56
  throw new CliError(
57
57
  typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
@@ -64,8 +64,9 @@ export class Client {
64
64
  ? "RATE_LIMITED"
65
65
  : "INTERNAL_FAILURE"),
66
66
  {
67
- requestId: response.headers.get("X-Request-Id"),
68
- retryAfter: response.headers.get("Retry-After"),
67
+ ...error?.details,
68
+ requestId: response.headers.get("X-Request-Id") || error?.requestId,
69
+ retryAfter: response.headers.get("Retry-After") || error?.retryAfter || error?.details?.retryAfter,
69
70
  }
70
71
  );
71
72
  if (body.error)
package/src/plan.mjs ADDED
@@ -0,0 +1,331 @@
1
+ import { readFile, stat, writeFile, rename } from "node:fs/promises";
2
+ import { createReadStream } from "node:fs";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { dirname, basename, resolve, extname } from "node:path";
5
+ import { setTimeout as sleep } from "node:timers/promises";
6
+ import { CliError } from "./client.mjs";
7
+
8
+ export async function retryUpload(upload, { wait = sleep, maxRetries = 5 } = {}) {
9
+ for (let attempt = 0; ; attempt++) {
10
+ try {
11
+ return await upload();
12
+ } catch (error) {
13
+ if (!(error instanceof CliError) || error.code !== "RATE_LIMITED" || attempt >= maxRetries)
14
+ throw error;
15
+ const raw = error.details.retryAfter;
16
+ const seconds =
17
+ raw !== null && raw !== undefined && /^\d+(?:\.\d+)?$/.test(String(raw))
18
+ ? Number(raw)
19
+ : Number.isFinite(Date.parse(raw))
20
+ ? Math.max(0, (Date.parse(raw) - Date.now()) / 1000)
21
+ : 5 * (attempt + 1);
22
+ if (seconds > 300)
23
+ throw new CliError(
24
+ "Upload rate limit requires a longer wait. Retry this same plan after Retry-After.",
25
+ "RATE_LIMITED",
26
+ error.details
27
+ );
28
+ await wait(Math.max(0, seconds * 1000));
29
+ }
30
+ }
31
+ }
32
+ function chooseAccount(accounts, selector, index) {
33
+ if (typeof selector !== "string" || !selector)
34
+ throw new CliError(`Plan item ${index}: choose an account or supply --account.`);
35
+ const exact = accounts.filter((account) => account.id === selector);
36
+ const matches = exact.length
37
+ ? exact
38
+ : accounts.filter(
39
+ (account) =>
40
+ String(account.platformUsername || account.name || "").toLowerCase() ===
41
+ selector.toLowerCase()
42
+ );
43
+ if (matches.length !== 1)
44
+ throw new CliError(`Plan item ${index}: account must be an exact ID or unique account name.`);
45
+ if (matches[0].status && matches[0].status !== "CONNECTED")
46
+ throw new CliError(`Plan item ${index}: account needs reconnection.`);
47
+ return matches[0];
48
+ }
49
+ export async function schedulePlan(client, file, options = {}) {
50
+ if (options.yes && options["dry-run"]) throw new CliError("Choose --yes or --dry-run, not both.");
51
+ const location = resolve(file);
52
+ if ((await stat(location)).size > 1024 * 1024)
53
+ throw new CliError("Plan JSON must be at most 1 MiB.");
54
+ let raw;
55
+ try {
56
+ raw = JSON.parse((await readFile(location, "utf8")).replace(/^\uFEFF/, ""));
57
+ } catch {
58
+ throw new CliError("Plan must be valid JSON.");
59
+ }
60
+ const items = Array.isArray(raw) ? raw : raw?.posts;
61
+ if (!Array.isArray(items) || !items.length || items.length > 100)
62
+ throw new CliError("Plan must contain 1-100 posts.");
63
+ const listed = await client.tool("accounts_list");
64
+ const accounts = Array.isArray(listed) ? listed : listed.items || listed.accounts || [];
65
+ const prepared = [];
66
+ const allowedKeys = new Set([
67
+ "video",
68
+ "videoPath",
69
+ "title",
70
+ "description",
71
+ "tags",
72
+ "scheduledAt",
73
+ "account",
74
+ "privacy",
75
+ "tiktokSettings",
76
+ "pinterestSettings",
77
+ "facebookSettings",
78
+ "instagramPostType",
79
+ "instagramCaption",
80
+ ]);
81
+ for (const [offset, item] of items.entries()) {
82
+ const index = offset + 1;
83
+ if (
84
+ !item ||
85
+ typeof item !== "object" ||
86
+ Array.isArray(item) ||
87
+ Object.keys(item).some((key) => !allowedKeys.has(key))
88
+ )
89
+ throw new CliError(`Plan item ${index}: invalid or unknown fields.`);
90
+ if (typeof item.title !== "string" || !item.title.trim() || item.title.length > 100)
91
+ throw new CliError(`Plan item ${index}: title must be 1-100 characters.`);
92
+ if (
93
+ item.description !== undefined &&
94
+ (typeof item.description !== "string" || item.description.length > 5000)
95
+ )
96
+ throw new CliError(`Plan item ${index}: description must be at most 5000 characters.`);
97
+ if (
98
+ !Array.isArray(item.tags || []) ||
99
+ (item.tags || []).some((tag) => typeof tag !== "string" || !tag.trim() || tag.length > 80) ||
100
+ (item.tags || []).length > 30 ||
101
+ (item.tags || []).join(",").length > 400
102
+ )
103
+ throw new CliError(
104
+ `Plan item ${index}: use up to 30 tags, 80 characters each and 400 characters total.`
105
+ );
106
+ if (
107
+ typeof item.scheduledAt !== "string" ||
108
+ !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(item.scheduledAt) ||
109
+ !Number.isFinite(Date.parse(item.scheduledAt)) ||
110
+ Date.parse(item.scheduledAt) <= Date.now()
111
+ )
112
+ throw new CliError(
113
+ `Plan item ${index}: scheduledAt must be a future ISO timestamp with an offset.`
114
+ );
115
+ const path = item.video || item.videoPath;
116
+ if (
117
+ typeof path !== "string" ||
118
+ !path ||
119
+ (item.video && item.videoPath && item.video !== item.videoPath)
120
+ )
121
+ throw new CliError(`Plan item ${index}: specify one video path.`);
122
+ const video = resolve(dirname(location), path);
123
+ const info = await stat(video).catch(() => null);
124
+ if (
125
+ !info?.isFile() ||
126
+ info.size < 1 ||
127
+ info.size > 90 * 1024 * 1024 ||
128
+ extname(video).toLowerCase() !== ".mp4"
129
+ )
130
+ throw new CliError(
131
+ `Plan item ${index}: choose an existing MP4 up to 90 MiB. Use prepare-video for other formats.`
132
+ );
133
+ const account = chooseAccount(accounts, item.account || options.account, index);
134
+ const privacy = item.privacy || options.privacy || "private";
135
+ if (!["private", "public", "unlisted"].includes(privacy))
136
+ throw new CliError(`Plan item ${index}: invalid YouTube privacy.`);
137
+ if (
138
+ account.platform === "TIKTOK" &&
139
+ (!item.tiktokSettings ||
140
+ typeof item.tiktokSettings.privacy !== "string" ||
141
+ ["allowComments", "allowDuet", "allowStitch"].some(
142
+ (key) => typeof item.tiktokSettings[key] !== "boolean"
143
+ ))
144
+ )
145
+ throw new CliError(
146
+ `Plan item ${index}: TikTok needs explicit tiktokSettings (privacy, allowComments, allowDuet, allowStitch), reviewed against creator settings.`
147
+ );
148
+ if (account.platform === "PINTEREST" && !item.pinterestSettings?.boardIds?.[account.id])
149
+ throw new CliError(
150
+ `Plan item ${index}: choose the Pinterest board in pinterestSettings.boardIds.`
151
+ );
152
+ const tags = (item.tags || []).map((tag) => tag.trim());
153
+ const description = item.description || "";
154
+ const content =
155
+ account.platform === "YOUTUBE"
156
+ ? description
157
+ : [
158
+ description,
159
+ tags.map((tag) => `#${tag.replace(/^#/, "").replace(/\s+/g, "")}`).join(" "),
160
+ ]
161
+ .filter(Boolean)
162
+ .join("\n\n");
163
+ const max = { TWITTER: 280, BLUESKY: 300, THREADS: 500 }[account.platform] || 5000;
164
+ if ([...content].length > max)
165
+ throw new CliError(
166
+ `Plan item ${index}: description and tags exceed ${account.platform}'s ${max}-character local limit.`
167
+ );
168
+ prepared.push({
169
+ video,
170
+ title: item.title,
171
+ description,
172
+ tags,
173
+ scheduledAt: item.scheduledAt,
174
+ accountId: account.id,
175
+ platform: account.platform,
176
+ privacy,
177
+ content,
178
+ settings: Object.fromEntries(
179
+ [
180
+ "tiktokSettings",
181
+ "pinterestSettings",
182
+ "facebookSettings",
183
+ "instagramPostType",
184
+ "instagramCaption",
185
+ ]
186
+ .filter((key) => item[key] !== undefined)
187
+ .map((key) => [key, item[key]])
188
+ ),
189
+ });
190
+ }
191
+ const hashed = [];
192
+ for (const item of prepared) {
193
+ const hash = createHash("sha256");
194
+ for await (const chunk of createReadStream(item.video)) hash.update(chunk);
195
+ hashed.push({ ...item, sha256: hash.digest("hex") });
196
+ }
197
+ const digest = createHash("sha256").update(JSON.stringify(hashed)).digest("hex");
198
+ const root = options["idempotency-key"] || `plan-${digest}`;
199
+ if (!/^[\w.:-]{8,150}$/.test(root))
200
+ throw new CliError("Plan idempotency key must be 8-150 safe characters.");
201
+ const journal = resolve(
202
+ dirname(location),
203
+ `${basename(location)}.postpilot-${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`
204
+ );
205
+ let state = { planId: root, digest, preparedPosts: [] };
206
+ try {
207
+ state = JSON.parse(await readFile(journal, "utf8"));
208
+ } catch (error) {
209
+ if (error.code !== "ENOENT")
210
+ throw new CliError("Plan checkpoint cannot be read. Inspect it before retrying.");
211
+ }
212
+ if (
213
+ state.planId !== root ||
214
+ state.digest !== digest ||
215
+ !Array.isArray(state.preparedPosts) ||
216
+ state.preparedPosts.some(
217
+ (post, i) =>
218
+ !post.postId ||
219
+ post.accountId !== prepared[i]?.accountId ||
220
+ post.scheduledAt !== prepared[i]?.scheduledAt
221
+ )
222
+ )
223
+ throw new CliError(
224
+ "This plan key or checkpoint belongs to different arguments. Choose a new key only for an intentionally new plan."
225
+ );
226
+ const drafts = [...state.preparedPosts];
227
+ async function saveState() {
228
+ const temporary = `${journal}.${randomUUID()}.tmp`;
229
+ await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
230
+ await rename(temporary, journal);
231
+ }
232
+ if (state.approvalId) {
233
+ const status = await client.tool("approval_status", { approvalId: state.approvalId });
234
+ if (["EXPIRED", "FAILED", "PARTIALLY_FAILED", "CANCELED"].includes(status.status))
235
+ throw new CliError(
236
+ "This batch ended or expired. Inspect per-post results before preparing only the intended retries with a new plan key.",
237
+ "CONFLICT",
238
+ { approvalId: state.approvalId, result: status }
239
+ );
240
+ return {
241
+ ...status,
242
+ approvalUrl: state.approvalUrl,
243
+ alreadyPrepared: true,
244
+ planId: root,
245
+ preparedPosts: drafts,
246
+ dryRun: !options.yes,
247
+ };
248
+ }
249
+ const capacity = await client.tool("plan_validate", {
250
+ items: prepared.map((item, i) => ({
251
+ accountId: item.accountId,
252
+ scheduledAt: item.scheduledAt,
253
+ title: item.title,
254
+ ...(drafts[i] ? { postId: drafts[i].postId } : {}),
255
+ })),
256
+ });
257
+ if (capacity.allowed === false || capacity.validated !== true)
258
+ throw new CliError("The server did not validate this plan. No uploads or drafts were created.");
259
+ if (!options.yes)
260
+ return {
261
+ dryRun: true,
262
+ validated: true,
263
+ requiresYes: true,
264
+ planId: root,
265
+ message:
266
+ "No uploads, drafts or schedules created. Add --yes to prepare this plan for one human approval.",
267
+ items: prepared.map(({ video, title, accountId, scheduledAt }) => ({
268
+ video,
269
+ title,
270
+ accountId,
271
+ scheduledAt,
272
+ })),
273
+ capacity,
274
+ };
275
+
276
+ try {
277
+ for (const [index, item] of hashed.entries()) {
278
+ if (drafts[index]) continue;
279
+ const upload = await retryUpload(() => client.upload(item.video, `${root}.upload.${index}`));
280
+ if (upload.sha256 && upload.sha256 !== item.sha256)
281
+ throw new CliError(
282
+ `Plan item ${index + 1}: video changed after plan validation. Review the file before retrying.`
283
+ );
284
+ const assetId = upload.uploadSessionId || upload.sessionId || upload.id;
285
+ if (!assetId)
286
+ throw new CliError(
287
+ `Plan item ${index + 1}: upload did not return an asset ID.`,
288
+ "INTERNAL_FAILURE"
289
+ );
290
+ const draft = await client.tool("post_create_draft", {
291
+ post: {
292
+ content: item.content,
293
+ videoTitle: item.title,
294
+ videoDescription: item.description,
295
+ videoTags: item.tags,
296
+ youtubePrivacyStatus: item.privacy,
297
+ platformTargets: [item.platform],
298
+ selectedAccountIds: [item.accountId],
299
+ uploadSessionId: assetId,
300
+ mediaType: "VIDEO",
301
+ ...item.settings,
302
+ },
303
+ idempotencyKey: `${root}.draft.${index}`,
304
+ });
305
+ if (!draft.id || draft.status !== "DRAFT")
306
+ throw new CliError(
307
+ `Plan item ${index + 1}: draft creation is incomplete. Inspect the operation before retrying.`,
308
+ "INTERNAL_FAILURE"
309
+ );
310
+ drafts.push({ postId: draft.id, accountId: item.accountId, scheduledAt: item.scheduledAt });
311
+ state.preparedPosts = drafts;
312
+ await saveState();
313
+ }
314
+ const approval = await client.tool("post_schedule_batch", {
315
+ items: drafts,
316
+ idempotencyKey: `${root}.approval`,
317
+ });
318
+ if (!approval.approvalId || !approval.approvalUrl)
319
+ throw new CliError(
320
+ "Batch did not return a human approval link. Inspect the operation before retrying.",
321
+ "INTERNAL_FAILURE"
322
+ );
323
+ Object.assign(state, { approvalId: approval.approvalId, approvalUrl: approval.approvalUrl });
324
+ await saveState();
325
+ return { ...approval, planId: root, preparedPosts: drafts };
326
+ } catch (error) {
327
+ if (error instanceof CliError)
328
+ Object.assign(error.details, { planId: root, preparedPosts: drafts });
329
+ throw error;
330
+ }
331
+ }