@chaouidz/postpilot 1.1.0 → 1.1.2
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 +32 -63
- package/bin/postpilot.mjs +27 -3
- package/package.json +2 -2
- package/src/bootstrap.mjs +53 -0
- package/src/client.mjs +26 -4
- package/src/plan.mjs +333 -331
package/README.md
CHANGED
|
@@ -1,87 +1,56 @@
|
|
|
1
|
-
# PostPilot CLI
|
|
1
|
+
# PostPilot CLI 1.1.2
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node.js 20+ on Windows, macOS and Linux. Install `npm install -g @chaouidz/postpilot@1.1.2` or the matching versioned archive at https://postpilot.yktis.com/downloads/chaouidz-postpilot-1.1.2.tgz. Existing versioned downloads remain available.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
Without a global install: `npx @chaouidz/postpilot@1.1.0 help`.
|
|
7
|
-
Package: https://www.npmjs.com/package/@chaouidz/postpilot.
|
|
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.1.0.tgz`. Packing does not publish to npm.
|
|
5
|
+
## Authenticate
|
|
10
6
|
|
|
11
|
-
|
|
7
|
+
Use `postpilot login` for a hidden token prompt, `postpilot login --token-stdin --non-interactive --json` for piped tokens, or set POSTPILOT_TOKEN from a protected runtime secret store. The OS keychain stores tokens with no plaintext fallback.
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
Browserless setup for an existing email/password account: pipe protected JSON into `postpilot login --credentials-stdin --non-interactive --json`. Required JSON fields: email and password. Optional: tokenName, scopes (default social:read and social:write), allowedAccountIds, expiresInDays (7, 30, 90 or null), requireHumanApproval (default false). It uses the existing CSRF-protected session/token APIs. No password is saved. OAuth-only login and initial provider consent can require provider interaction. Users do not need an npm account.
|
|
14
10
|
|
|
15
|
-
|
|
11
|
+
## Schedule one Short to one named channel
|
|
16
12
|
|
|
17
|
-
|
|
13
|
+
The runnable https://postpilot.yktis.com/downloads/agent-short.mjs parses resource IDs automatically. Set POSTPILOT_TOKEN, POSTPILOT_FILE, POSTPILOT_CHANNEL, POSTPILOT_SCHEDULED_AT (future ISO-8601 offset) and POSTPILOT_OPERATION_KEY in your runtime. Run `node agent-short.mjs cli` or `node agent-short.mjs mcp`. It resolves one exact channel, uploads MP4, creates a private Short draft, validates, schedules and polls status. No browser action or manual copy-paste occurs in that flow.
|
|
18
14
|
|
|
19
|
-
|
|
15
|
+
## Schedule a plan
|
|
20
16
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
## Schedule a Short to ONE named channel
|
|
17
|
+
A plan is an array or {"posts": [...]} of 1-100 items with video, title, description, tags, scheduledAt and account. Paths are relative to the plan file; account is an exact ID or unique name. --account supplies a fallback.
|
|
24
18
|
|
|
25
19
|
```sh
|
|
26
|
-
postpilot
|
|
20
|
+
postpilot help --json
|
|
27
21
|
postpilot whoami --json
|
|
28
22
|
postpilot accounts list --json
|
|
29
|
-
postpilot
|
|
30
|
-
|
|
31
|
-
postpilot
|
|
32
|
-
# Copy the returned id as DRAFT_ID. Pick a FUTURE ISO timestamp with an offset.
|
|
33
|
-
postpilot schedule --post DRAFT_ID --account "My Tutorials" --at "2027-01-10T09:00:00+01:00" --timezone Europe/Zurich --dry-run --json
|
|
34
|
-
postpilot schedule --post DRAFT_ID --account "My Tutorials" --at "2027-01-10T09:00:00+01:00" --timezone Europe/Zurich --idempotency-key my-short-schedule-001 --json
|
|
35
|
-
# Exit code 5 means PENDING_APPROVAL. Open the returned approvalUrl while signed in.
|
|
36
|
-
# Review the exact single account, private visibility and time, then approve.
|
|
37
|
-
postpilot status --post DRAFT_ID --json
|
|
23
|
+
postpilot schedule --file plan.json --json
|
|
24
|
+
postpilot schedule --file plan.json --yes --json
|
|
25
|
+
postpilot status --post POST_ID --json
|
|
38
26
|
```
|
|
39
27
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
Other commands: `assets list [--limit 1-100] [--cursor CURSOR]`, `publish --post ID --account ID [--dry-run]`, `cancel --post ID`, `prepare-video input.mov --output compatible.mp4` (offline, requires ffmpeg, never overwrites an existing file). Set privacy on the draft before scheduling; the approval payload and stored draft determine publication privacy. Image/raw uploads accept PNG up to 20 MiB and MP4 up to 90 MiB. Preparation may produce larger files, which the raw upload API will reject.
|
|
43
|
-
|
|
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.
|
|
28
|
+
Batch files default to read-only preview. --yes uploads, creates drafts and schedules automatically. --yes --dry-run is invalid. Human review is optional per-token requireHumanApproval, default OFF. Existing tokens and legacy tool names remain valid. Opt-in review returns PENDING_APPROVAL; schedule review expires in 24 hours, publish-now review in 15 minutes. Successful posts retain their scheduled time. Scheduled/queued does not mean published.
|
|
45
29
|
|
|
46
|
-
|
|
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
|
-
```
|
|
30
|
+
Default capacity is 10 posts/account/calendar day, configurable by plan. Account metadata timezone falls back to owner timezone. Billing entitlements and provider quotas remain enforced. CAPACITY_EXCEEDED is not retryable unchanged and has no retryAfter. Move the identified items to another account day. RATE_LIMITED is genuine throttling with Retry-After.
|
|
70
31
|
|
|
71
|
-
|
|
32
|
+
Uploads accept PNG up to 20 MiB or MP4 up to 90 MiB. Only HTTP 429 uploads retry, up to five times, honoring Retry-After; waits above five minutes stop. Stable per-item keys and credential-free .postpilot-*.json checkpoints resume interrupted runs without duplicate uploads, drafts or schedules. Do not change keys merely to retry an ambiguous result. Inspect failed/EXECUTING results; retry failed destinations only. Existing CLI 1.1.1 remains compatible with automatic batch responses through the legacy approvalId/approvalUrl fields (the URL is a status read, not a manual approval action).
|
|
72
33
|
|
|
73
|
-
|
|
34
|
+
YouTube privacy defaults to private. TikTok needs explicit privacy, allowComments, allowDuet and allowStitch in tiktokSettings. Pinterest needs pinterestSettings.boardIds. Media rules and provider consent are rechecked at execution.
|
|
74
35
|
|
|
75
|
-
|
|
36
|
+
## Commands and exit codes
|
|
76
37
|
|
|
77
|
-
|
|
38
|
+
Every command supports --json and --non-interactive. Non-TTY stdin never triggers a prompt.
|
|
78
39
|
|
|
79
|
-
|
|
40
|
+
- login [--token-stdin | --credentials-stdin], whoami, logout
|
|
41
|
+
- accounts list; assets list [--limit 1-100] [--cursor CURSOR]
|
|
42
|
+
- upload FILE; prepare-video FILE --output FILE (offline, ffmpeg required)
|
|
43
|
+
- draft create --account ID_OR_NAME --asset ID --title TITLE --privacy private
|
|
44
|
+
- schedule --post ID --account ID_OR_NAME --at ISO_OFFSET [--dry-run]
|
|
45
|
+
- publish --post ID --account ID_OR_NAME [--dry-run]
|
|
46
|
+
- status --post ID; status --approval ID; cancel --post ID
|
|
80
47
|
|
|
81
|
-
|
|
48
|
+
Exit codes: 0 success, 2 invalid input, 3 auth/scope, 4 not found, 5 optional pending approval, 6 rate limit, 7 provider/network/server, 8 capacity exceeded. --idempotency-key is stable across identical retries. --timezone returns the requested IANA zone; timestamp offsets determine the instant. JSON errors keep code/message and available retry/request details.
|
|
82
49
|
|
|
83
|
-
|
|
50
|
+
MCP analytics tools are available; this public CLI has no dedicated TikTok statistics command. Python, Rust and PHP can invoke it or use HTTPS directly. Internal repository scripts are separate interfaces.
|
|
84
51
|
|
|
85
|
-
|
|
52
|
+
Full public reference: https://postpilot.yktis.com/cli.md
|
|
53
|
+
Tool names, scopes and per-tool limits: https://postpilot.yktis.com/mcp-tools.json
|
|
54
|
+
Plans: https://postpilot.yktis.com/pricing.json
|
|
86
55
|
|
|
87
|
-
`npm test` uses
|
|
56
|
+
`npm test` uses fixtures and mock servers. Native keychain tests are opt-in with POSTPILOT_TEST_NATIVE_KEYCHAIN=true and clean up their unique fixture credential. No real social account is published, scheduled or deleted.
|
package/bin/postpilot.mjs
CHANGED
|
@@ -4,10 +4,11 @@ import { promisify } from "node:util";
|
|
|
4
4
|
import { Client, CliError, EXIT_CODES } from "../src/client.mjs";
|
|
5
5
|
import { schedulePlan } from "../src/plan.mjs";
|
|
6
6
|
import { keychain } from "../src/keychain.mjs";
|
|
7
|
+
import { bootstrapToken } from "../src/bootstrap.mjs";
|
|
7
8
|
const args = process.argv.slice(2),
|
|
8
9
|
options = {},
|
|
9
10
|
positionals = [];
|
|
10
|
-
const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "help", "yes"]);
|
|
11
|
+
const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "credentials-stdin", "help", "yes"]);
|
|
11
12
|
const valued = new Set([
|
|
12
13
|
"url",
|
|
13
14
|
"file",
|
|
@@ -89,8 +90,14 @@ try {
|
|
|
89
90
|
if (!command || command === "help" || options.help) {
|
|
90
91
|
output({
|
|
91
92
|
usage: "postpilot <command> [--json] [--non-interactive]",
|
|
93
|
+
requires: {
|
|
94
|
+
node: ">=20",
|
|
95
|
+
operatingSystems: ["Windows", "macOS", "Linux"],
|
|
96
|
+
installRuntime:
|
|
97
|
+
"Install current Node.js LTS from https://nodejs.org/en/download, then reopen your terminal.",
|
|
98
|
+
},
|
|
92
99
|
commands: [
|
|
93
|
-
"login [--token-stdin]",
|
|
100
|
+
"login [--token-stdin | --credentials-stdin]",
|
|
94
101
|
"whoami",
|
|
95
102
|
"logout",
|
|
96
103
|
"accounts list",
|
|
@@ -116,6 +123,7 @@ try {
|
|
|
116
123
|
"--idempotency-key",
|
|
117
124
|
"--timezone",
|
|
118
125
|
"--url",
|
|
126
|
+
"--credentials-stdin",
|
|
119
127
|
],
|
|
120
128
|
exitCodes: {
|
|
121
129
|
success: 0,
|
|
@@ -125,6 +133,7 @@ try {
|
|
|
125
133
|
approvalPending: 5,
|
|
126
134
|
rateLimited: 6,
|
|
127
135
|
providerOrNetwork: 7,
|
|
136
|
+
capacityExceeded: 8,
|
|
128
137
|
},
|
|
129
138
|
docs: "https://postpilot.yktis.com/cli",
|
|
130
139
|
});
|
|
@@ -189,7 +198,22 @@ try {
|
|
|
189
198
|
"Local credential removed. Revoke the token in Settings to invalidate it everywhere.",
|
|
190
199
|
});
|
|
191
200
|
} else if (command === "login") {
|
|
192
|
-
|
|
201
|
+
if (options["token-stdin"] && options["credentials-stdin"])
|
|
202
|
+
throw new CliError("Choose --token-stdin or --credentials-stdin.");
|
|
203
|
+
let token;
|
|
204
|
+
if (options["credentials-stdin"]) {
|
|
205
|
+
if (process.stdin.isTTY) throw new CliError("Pipe credentials JSON from a protected secret store.");
|
|
206
|
+
let value = "";
|
|
207
|
+
for await (const chunk of process.stdin) {
|
|
208
|
+
value += chunk;
|
|
209
|
+
if (value.length > 16384) throw new CliError("Credentials JSON is too large.");
|
|
210
|
+
}
|
|
211
|
+
let credentials;
|
|
212
|
+
try { credentials = JSON.parse(value); } catch { throw new CliError("Credentials input must be JSON."); }
|
|
213
|
+
token = await bootstrapToken(origin, credentials);
|
|
214
|
+
value = "";
|
|
215
|
+
credentials = null;
|
|
216
|
+
} else token = await tokenInput();
|
|
193
217
|
const client = new Client(origin, token);
|
|
194
218
|
await client.tool("social_get_profile");
|
|
195
219
|
await keychain("set", origin, token);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chaouidz/postpilot",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"description": "PostPilot CLI for scoped,
|
|
3
|
+
"version": "1.1.2",
|
|
4
|
+
"description": "PostPilot CLI for scoped, autonomous social publishing and batch scheduling",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"postpilot": "bin/postpilot.mjs"
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { CliError } from "./client.mjs";
|
|
2
|
+
|
|
3
|
+
// Uses the existing credentials/session and token APIs. No new auth endpoint,
|
|
4
|
+
// password store, provider-consent bypass or account privilege is introduced.
|
|
5
|
+
export async function bootstrapToken(url, credentials, fetcher = fetch) {
|
|
6
|
+
const origin = new URL(url).origin;
|
|
7
|
+
if (!origin.startsWith("https:") && !["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname))
|
|
8
|
+
throw new CliError("Remote authentication requires HTTPS.");
|
|
9
|
+
if (!credentials || typeof credentials.email !== "string" || typeof credentials.password !== "string")
|
|
10
|
+
throw new CliError("Credentials JSON requires email and password strings.");
|
|
11
|
+
const cookies = new Map();
|
|
12
|
+
async function request(path, init = {}) {
|
|
13
|
+
let response;
|
|
14
|
+
try {
|
|
15
|
+
response = await fetcher(origin + path, {
|
|
16
|
+
...init, redirect: "error", signal: AbortSignal.timeout(30_000),
|
|
17
|
+
headers: { ...init.headers, Origin: origin, Cookie: [...cookies].map(([key, value]) => `${key}=${value}`).join("; ") },
|
|
18
|
+
});
|
|
19
|
+
} catch { throw new CliError("Could not reach PostPilot during login.", "INTERNAL_FAILURE"); }
|
|
20
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
21
|
+
const pair = cookie.split(";", 1)[0];
|
|
22
|
+
const index = pair.indexOf("=");
|
|
23
|
+
if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1));
|
|
24
|
+
}
|
|
25
|
+
const data = await response.json().catch(() => ({}));
|
|
26
|
+
if (!response.ok) throw new CliError("PostPilot login or token creation failed. Check credentials and token policy.", response.status === 429 ? "RATE_LIMITED" : "AUTHENTICATION_EXPIRED");
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const { csrfToken } = await request("/api/auth/csrf");
|
|
31
|
+
if (!csrfToken) throw new CliError("PostPilot did not provide a CSRF challenge.", "AUTHENTICATION_EXPIRED");
|
|
32
|
+
const result = await request("/api/auth/callback/credentials", {
|
|
33
|
+
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "X-Auth-Return-Redirect": "1" },
|
|
34
|
+
body: new URLSearchParams({ csrfToken, email: credentials.email, password: credentials.password, callbackUrl: origin }).toString(),
|
|
35
|
+
});
|
|
36
|
+
if (result.error || (result.url && new URL(result.url, origin).searchParams.has("error")))
|
|
37
|
+
throw new CliError("PostPilot credentials were not accepted.", "AUTHENTICATION_EXPIRED");
|
|
38
|
+
const session = await request("/api/auth/session");
|
|
39
|
+
if (!session.user?.id) throw new CliError("PostPilot credentials did not establish a session.", "AUTHENTICATION_EXPIRED");
|
|
40
|
+
const data = await request("/api/mcp/tokens", {
|
|
41
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
42
|
+
body: JSON.stringify({
|
|
43
|
+
name: credentials.tokenName || "PostPilot CLI",
|
|
44
|
+
scopes: credentials.scopes || ["social:read", "social:write"],
|
|
45
|
+
allowedAccountIds: credentials.allowedAccountIds ?? null,
|
|
46
|
+
expiresInDays: credentials.expiresInDays ?? null,
|
|
47
|
+
requireHumanApproval: credentials.requireHumanApproval === true,
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
50
|
+
if (!data.token) throw new CliError("PostPilot did not return a token.", "AUTHENTICATION_EXPIRED");
|
|
51
|
+
return data.token;
|
|
52
|
+
} finally { cookies.clear(); }
|
|
53
|
+
}
|
package/src/client.mjs
CHANGED
|
@@ -5,8 +5,25 @@ import { basename, extname } from "node:path";
|
|
|
5
5
|
export class CliError extends Error {
|
|
6
6
|
constructor(message, code = "INVALID_PARAMETERS", details = {}) {
|
|
7
7
|
super(message);
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
// Older servers labeled plan capacity as throttling. Normalize that precise
|
|
9
|
+
// legacy classification during rollout; never infer it from a message.
|
|
10
|
+
const capacity =
|
|
11
|
+
code === "CAPACITY_EXCEEDED" ||
|
|
12
|
+
(code === "RATE_LIMITED" &&
|
|
13
|
+
(details.limitType === "ACCOUNT_CALENDAR_DAY" ||
|
|
14
|
+
details.details?.limitType === "ACCOUNT_CALENDAR_DAY"));
|
|
15
|
+
this.code = capacity ? "CAPACITY_EXCEEDED" : code;
|
|
16
|
+
this.details = { ...details };
|
|
17
|
+
delete this.details.code;
|
|
18
|
+
delete this.details.message;
|
|
19
|
+
if (this.code !== "RATE_LIMITED") {
|
|
20
|
+
delete this.details.retryAfter;
|
|
21
|
+
if (this.details.details) {
|
|
22
|
+
this.details.details = { ...this.details.details };
|
|
23
|
+
delete this.details.details.retryAfter;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (capacity) this.details.retryable = false;
|
|
10
27
|
}
|
|
11
28
|
}
|
|
12
29
|
export const EXIT_CODES = {
|
|
@@ -16,6 +33,7 @@ export const EXIT_CODES = {
|
|
|
16
33
|
NOT_FOUND: 4,
|
|
17
34
|
PENDING_APPROVAL: 5,
|
|
18
35
|
RATE_LIMITED: 6,
|
|
36
|
+
CAPACITY_EXCEEDED: 8,
|
|
19
37
|
PROVIDER_REJECTED: 7,
|
|
20
38
|
INTERNAL_FAILURE: 7,
|
|
21
39
|
};
|
|
@@ -51,7 +69,10 @@ export class Client {
|
|
|
51
69
|
);
|
|
52
70
|
}
|
|
53
71
|
const body = await response.json().catch(() => ({}));
|
|
54
|
-
const error =
|
|
72
|
+
const error =
|
|
73
|
+
(body.result?.isError ? body.result.structuredContent?.error : null) ||
|
|
74
|
+
body.error?.data ||
|
|
75
|
+
body.error;
|
|
55
76
|
if (!response.ok)
|
|
56
77
|
throw new CliError(
|
|
57
78
|
typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
|
|
@@ -66,7 +87,8 @@ export class Client {
|
|
|
66
87
|
{
|
|
67
88
|
...error?.details,
|
|
68
89
|
requestId: response.headers.get("X-Request-Id") || error?.requestId,
|
|
69
|
-
retryAfter:
|
|
90
|
+
retryAfter:
|
|
91
|
+
response.headers.get("Retry-After") || error?.retryAfter || error?.details?.retryAfter,
|
|
70
92
|
}
|
|
71
93
|
);
|
|
72
94
|
if (body.error)
|
package/src/plan.mjs
CHANGED
|
@@ -1,331 +1,333 @@
|
|
|
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
|
|
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
|
|
321
|
-
"INTERNAL_FAILURE"
|
|
322
|
-
);
|
|
323
|
-
Object.assign(state, { approvalId: approval.approvalId, approvalUrl: approval.approvalUrl });
|
|
324
|
-
await saveState();
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
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 upload, create drafts and schedule this plan.",
|
|
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 || !["SUCCEEDED", "PENDING_APPROVAL", "PARTIALLY_FAILED", "FAILED"].includes(approval.status) || (approval.status === "PENDING_APPROVAL" && !approval.approvalUrl))
|
|
319
|
+
throw new CliError(
|
|
320
|
+
"Batch did not return a completed operation or optional review link. Inspect the operation before retrying.",
|
|
321
|
+
"INTERNAL_FAILURE"
|
|
322
|
+
);
|
|
323
|
+
Object.assign(state, { approvalId: approval.approvalId, approvalUrl: approval.approvalUrl });
|
|
324
|
+
await saveState();
|
|
325
|
+
if (["PARTIALLY_FAILED", "FAILED"].includes(approval.status))
|
|
326
|
+
throw new CliError("Some plan items failed. Inspect results before retrying failed destinations only.", "CONFLICT", { result: approval });
|
|
327
|
+
return { ...approval, planId: root, preparedPosts: drafts };
|
|
328
|
+
} catch (error) {
|
|
329
|
+
if (error instanceof CliError)
|
|
330
|
+
Object.assign(error.details, { planId: root, preparedPosts: drafts });
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
}
|