@chaouidz/postpilot 0.0.0-stage → 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
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # PostPilot CLI
2
+
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
+
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
+ 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.
10
+
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
+
13
+ ## Login and secrets
14
+
15
+ Create a token in PostPilot Settings with `social:read`, `social:write`, an expiry and only the channel you intend to use. Keep trusted automation disabled for human approval.
16
+
17
+ Run `postpilot login` and paste the token at the hidden prompt. Windows uses Credential Manager; macOS uses Keychain via `security`; Linux uses Secret Service via `secret-tool` (install your distribution's libsecret tools and unlock a desktop keychain). A missing/locked keychain fails explicitly. There is no plaintext-file fallback. Piped login requires `--token-stdin` and still stores in the OS keychain.
18
+
19
+ CI/cron: configure `POSTPILOT_TOKEN` through the runtime's secret store and use `--non-interactive --json`. Do not put it in a shell history, command argument, checked-in config or prompt. `POSTPILOT_URL` or `--url` selects an API origin; remote connections require HTTPS. Redirects are not followed with credentials.
20
+
21
+ `logout` removes only the local keychain entry. Revoke the token in PostPilot Settings to invalidate all copies; already scheduled posts must be cancelled separately.
22
+
23
+ ## Schedule a Short to ONE named channel
24
+
25
+ ```sh
26
+ postpilot login
27
+ postpilot whoami --json
28
+ postpilot accounts list --json
29
+ postpilot upload short.mp4 --idempotency-key my-short-import-001 --json
30
+ # Copy the returned uploadSessionId as UPLOAD_ID below.
31
+ postpilot draft create --account "My Tutorials" --asset UPLOAD_ID --title "My Short" --privacy private --idempotency-key my-short-draft-001 --json
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
38
+ ```
39
+
40
+ Exact IDs are preferred. Names must uniquely match one visible channel; an ambiguous name fails. No platform-wide broadcast fallback. A scheduled/queued result does not mean published. Dry-run validates local inputs; dynamic provider capacity and plan allowances are not reserved. Publication is queued only after browser approval, unless this token explicitly enables trusted automation.
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.
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
+
81
+ ## Exit codes
82
+
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.
84
+
85
+ ## Tests
86
+
87
+ `npm test` uses a local mock server, fake account IDs and fixture media. Native keychain integration is opt-in with `POSTPILOT_TEST_NATIVE_KEYCHAIN=true`; it creates and removes only a unique fixture credential. No live publishing or real social-account calls occur.
@@ -0,0 +1,285 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { Client, CliError, EXIT_CODES } from "../src/client.mjs";
5
+ import { schedulePlan } from "../src/plan.mjs";
6
+ import { keychain } from "../src/keychain.mjs";
7
+ const args = process.argv.slice(2),
8
+ options = {},
9
+ positionals = [];
10
+ const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "help", "yes"]);
11
+ const valued = new Set([
12
+ "url",
13
+ "file",
14
+ "account",
15
+ "at",
16
+ "privacy",
17
+ "post",
18
+ "approval",
19
+ "asset",
20
+ "title",
21
+ "content",
22
+ "output",
23
+ "idempotency-key",
24
+ "timezone",
25
+ "limit",
26
+ "cursor",
27
+ ]);
28
+ function required(name) {
29
+ if (!options[name]) throw new CliError(`--${name} is required.`);
30
+ return options[name];
31
+ }
32
+ function output(value) {
33
+ console.log(JSON.stringify(value, null, options.json ? 0 : 2));
34
+ if (value?.status === "PENDING_APPROVAL") process.exitCode = 5;
35
+ }
36
+ async function tokenInput() {
37
+ if (!process.stdin.isTTY) {
38
+ if (!options["token-stdin"])
39
+ throw new CliError("Use --token-stdin for piped login, or paste interactively.");
40
+ let value = "";
41
+ for await (const chunk of process.stdin) {
42
+ value += chunk;
43
+ if (value.length > 1024) throw new CliError("Invalid token length.");
44
+ }
45
+ return value.trim();
46
+ }
47
+ if (options["non-interactive"])
48
+ throw new CliError("Non-interactive login requires --token-stdin.");
49
+ process.stderr.write("Paste your PostPilot token (hidden): ");
50
+ return new Promise((resolve, reject) => {
51
+ let value = "";
52
+ process.stdin.setRawMode(true);
53
+ process.stdin.resume();
54
+ const done = (error) => {
55
+ process.stdin.setRawMode(false);
56
+ process.stdin.pause();
57
+ process.stdin.off("data", onData);
58
+ process.stderr.write("\n");
59
+ error ? reject(error) : resolve(value.trim());
60
+ };
61
+ const onData = (chunk) => {
62
+ for (const char of chunk.toString()) {
63
+ if (char === "\r" || char === "\n") return done();
64
+ if (char === "\u0003") return done(new CliError("Login cancelled."));
65
+ if (char === "\u007f" || char === "\b") value = value.slice(0, -1);
66
+ else value += char;
67
+ if (value.length > 512) return done(new CliError("Invalid token length."));
68
+ }
69
+ };
70
+ process.stdin.on("data", onData);
71
+ });
72
+ }
73
+ try {
74
+ for (let index = 0; index < args.length; index++) {
75
+ const value = args[index];
76
+ if (!value.startsWith("--")) {
77
+ positionals.push(value);
78
+ continue;
79
+ }
80
+ const name = value.slice(2);
81
+ if (boolean.has(name)) options[name] = true;
82
+ else if (valued.has(name) && args[index + 1] && !args[index + 1].startsWith("--"))
83
+ options[name] = args[++index];
84
+ else throw new CliError(`Unknown or incomplete option --${name}.`);
85
+ }
86
+ const [command, subcommand] = positionals;
87
+ const origin = new URL(options.url || process.env.POSTPILOT_URL || "https://postpilot.yktis.com")
88
+ .origin;
89
+ if (!command || command === "help" || options.help) {
90
+ output({
91
+ usage: "postpilot <command> [--json] [--non-interactive]",
92
+ commands: [
93
+ "login [--token-stdin]",
94
+ "whoami",
95
+ "logout",
96
+ "accounts list",
97
+ "assets list",
98
+ "upload <file>",
99
+ "prepare-video <file> --output <file>",
100
+ "draft create --account <id-or-name> --asset <id>",
101
+ "schedule --file <plan.json> [--account <id-or-name>] [--dry-run | --yes]",
102
+ "schedule --post <id> --account <id-or-name> --at <ISO-offset>",
103
+ "publish --post <id> --account <id-or-name>",
104
+ "status --post <id>",
105
+ "cancel --post <id>",
106
+ ],
107
+ flags: [
108
+ "--file",
109
+ "--yes",
110
+ "--account",
111
+ "--at",
112
+ "--privacy",
113
+ "--dry-run",
114
+ "--json",
115
+ "--non-interactive",
116
+ "--idempotency-key",
117
+ "--timezone",
118
+ "--url",
119
+ ],
120
+ exitCodes: {
121
+ success: 0,
122
+ usage: 2,
123
+ auth: 3,
124
+ notFound: 4,
125
+ approvalPending: 5,
126
+ rateLimited: 6,
127
+ providerOrNetwork: 7,
128
+ },
129
+ docs: "https://postpilot.yktis.com/cli",
130
+ });
131
+ } else if (command === "prepare-video") {
132
+ const input = subcommand;
133
+ if (!input) throw new CliError("Choose an input video.");
134
+ const target = required("output");
135
+ const ffargs = [
136
+ "-hide_banner",
137
+ "-loglevel",
138
+ "error",
139
+ "-n",
140
+ "-threads",
141
+ "2",
142
+ "-filter_threads",
143
+ "1",
144
+ "-i",
145
+ input,
146
+ "-map",
147
+ "0:v:0",
148
+ "-map",
149
+ "0:a?",
150
+ "-vf",
151
+ "scale=w=min(1920\\,iw):h=min(1920\\,ih):force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p,fps=30",
152
+ "-c:v",
153
+ "libx264",
154
+ "-crf",
155
+ "20",
156
+ "-pix_fmt",
157
+ "yuv420p",
158
+ "-c:a",
159
+ "aac",
160
+ "-ar",
161
+ "48000",
162
+ "-ac",
163
+ "2",
164
+ "-movflags",
165
+ "+faststart",
166
+ target,
167
+ ];
168
+ if (options["dry-run"]) output({ dryRun: true, command: "ffmpeg", arguments: ffargs });
169
+ else {
170
+ try {
171
+ await promisify(execFile)("ffmpeg", ffargs, {
172
+ timeout: 180000,
173
+ maxBuffer: 1024 * 1024,
174
+ windowsHide: true,
175
+ });
176
+ } catch {
177
+ throw new CliError(
178
+ "Video preparation failed. Install ffmpeg, choose a fresh output path and check the input.",
179
+ "INTERNAL_FAILURE"
180
+ );
181
+ }
182
+ output({ output: target, uploaded: false });
183
+ }
184
+ } else if (command === "logout") {
185
+ await keychain("delete", origin);
186
+ output({
187
+ loggedOut: true,
188
+ message:
189
+ "Local credential removed. Revoke the token in Settings to invalidate it everywhere.",
190
+ });
191
+ } else if (command === "login") {
192
+ const token = await tokenInput();
193
+ const client = new Client(origin, token);
194
+ await client.tool("social_get_profile");
195
+ await keychain("set", origin, token);
196
+ output({ loggedIn: true, storage: "OS keychain", origin });
197
+ } else {
198
+ const client = new Client(
199
+ origin,
200
+ process.env.POSTPILOT_TOKEN || (await keychain("get", origin).catch(() => ""))
201
+ );
202
+ const key = options["idempotency-key"] ? { idempotencyKey: options["idempotency-key"] } : {};
203
+ const common = {
204
+ ...key,
205
+ ...(options.timezone ? { timezone: options.timezone } : {}),
206
+ ...(options["dry-run"] ? { dryRun: true } : {}),
207
+ };
208
+ if (command === "whoami") output(await client.tool("social_get_profile"));
209
+ else if (command === "accounts" && subcommand === "list")
210
+ output(await client.tool("accounts_list"));
211
+ else if (command === "assets" && subcommand === "list")
212
+ output(
213
+ await client.tool("assets_list", {
214
+ ...(options.limit ? { limit: Number(options.limit) } : {}),
215
+ ...(options.cursor ? { cursor: options.cursor } : {}),
216
+ })
217
+ );
218
+ else if (command === "upload") {
219
+ if (!subcommand) throw new CliError("Choose a PNG or MP4 file.");
220
+ if (options["dry-run"]) output({ dryRun: true, file: subcommand, uploaded: false });
221
+ else output(await client.upload(subcommand, options["idempotency-key"]));
222
+ } else if (command === "draft" && subcommand === "create") {
223
+ const account = await client.account(required("account"));
224
+ const post = {
225
+ content: options.content || "",
226
+ videoTitle: options.title || "",
227
+ youtubePrivacyStatus: options.privacy || "private",
228
+ platformTargets: [account.platform],
229
+ selectedAccountIds: [account.id],
230
+ ...(options.asset
231
+ ? {
232
+ uploadSessionId: options.asset,
233
+ mediaType: account.platform === "YOUTUBE" ? "VIDEO_SHORT" : "VIDEO",
234
+ }
235
+ : {}),
236
+ };
237
+ if (options["dry-run"]) output({ dryRun: true, post, created: false });
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));
242
+ } else if (["schedule", "publish"].includes(command)) {
243
+ const account = await client.account(required("account"));
244
+ const postId = required("post");
245
+ if (
246
+ command === "schedule" &&
247
+ (!options.at ||
248
+ !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(options.at) ||
249
+ !Number.isFinite(Date.parse(options.at)))
250
+ )
251
+ throw new CliError("--at requires an ISO timestamp with Z or a numeric offset.");
252
+ if (options.privacy)
253
+ throw new CliError("Set privacy when creating the draft; review it in the approval page.");
254
+ output(
255
+ await client.tool(command === "schedule" ? "post_schedule" : "post_publish", {
256
+ postId,
257
+ accountIds: [account.id],
258
+ ...(command === "schedule" ? { scheduledAt: options.at } : {}),
259
+ ...common,
260
+ })
261
+ );
262
+ } else if (command === "status")
263
+ output(
264
+ await client.tool(
265
+ options.approval ? "approval_status" : "post_status",
266
+ options.approval ? { approvalId: options.approval } : { postId: required("post") }
267
+ )
268
+ );
269
+ else if (command === "cancel")
270
+ output(await client.tool("post_cancel", { postId: required("post"), ...key }));
271
+ else throw new CliError("Unknown command. Run postpilot help.");
272
+ }
273
+ } catch (error) {
274
+ const code = error instanceof CliError ? error.code : "INTERNAL_FAILURE";
275
+ const message =
276
+ error instanceof CliError
277
+ ? error.message
278
+ : "The operation failed. Check your input and OS keychain, then try again.";
279
+ console.error(
280
+ JSON.stringify({
281
+ error: { code, message, ...(error instanceof CliError ? error.details : {}) },
282
+ })
283
+ );
284
+ process.exitCode = EXIT_CODES[code] || 7;
285
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
- {
2
- "name": "@chaouidz/postpilot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@chaouidz/postpilot",
3
+ "version": "1.1.0",
4
+ "description": "PostPilot CLI for scoped, approval-based social publishing and analytics",
5
+ "type": "module",
6
+ "bin": {
7
+ "postpilot": "bin/postpilot.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "license": "UNLICENSED",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/yktis/postpilot.git",
21
+ "directory": "packages/cli"
22
+ },
23
+ "homepage": "https://postpilot.yktis.com/cli",
24
+ "scripts": {
25
+ "test": "node --test test/*.test.mjs"
26
+ }
27
+ }
package/src/client.mjs ADDED
@@ -0,0 +1,146 @@
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { stat } from "node:fs/promises";
4
+ import { basename, extname } from "node:path";
5
+ export class CliError extends Error {
6
+ constructor(message, code = "INVALID_PARAMETERS", details = {}) {
7
+ super(message);
8
+ this.code = code;
9
+ this.details = details;
10
+ }
11
+ }
12
+ export const EXIT_CODES = {
13
+ INVALID_PARAMETERS: 2,
14
+ AUTHENTICATION_EXPIRED: 3,
15
+ INSUFFICIENT_SCOPE: 3,
16
+ NOT_FOUND: 4,
17
+ PENDING_APPROVAL: 5,
18
+ RATE_LIMITED: 6,
19
+ PROVIDER_REJECTED: 7,
20
+ INTERNAL_FAILURE: 7,
21
+ };
22
+ export class Client {
23
+ constructor(origin, token, fetcher = fetch) {
24
+ this.origin = new URL(origin).origin;
25
+ this.token = token;
26
+ this.fetch = fetcher;
27
+ if (!token)
28
+ throw new CliError(
29
+ "Run postpilot login or configure POSTPILOT_TOKEN.",
30
+ "AUTHENTICATION_EXPIRED"
31
+ );
32
+ if (
33
+ !/^https:/.test(this.origin) &&
34
+ !["127.0.0.1", "localhost", "[::1]"].includes(new URL(origin).hostname)
35
+ )
36
+ throw new CliError("Remote API connections require HTTPS.");
37
+ }
38
+ async request(path, init = {}) {
39
+ let response;
40
+ try {
41
+ response = await this.fetch(this.origin + path, {
42
+ ...init,
43
+ redirect: "error",
44
+ signal: AbortSignal.timeout(150000),
45
+ headers: { ...init.headers, Authorization: `Bearer ${this.token}` },
46
+ });
47
+ } catch {
48
+ throw new CliError(
49
+ "Could not reach PostPilot. Check the URL and network; do not blindly retry publication.",
50
+ "INTERNAL_FAILURE"
51
+ );
52
+ }
53
+ const body = await response.json().catch(() => ({}));
54
+ const error = (body.result?.isError ? body.result.structuredContent?.error : null) || body.error?.data || body.error;
55
+ if (!response.ok)
56
+ throw new CliError(
57
+ typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
58
+ error?.code ||
59
+ (response.status === 401
60
+ ? "AUTHENTICATION_EXPIRED"
61
+ : response.status === 403
62
+ ? "INSUFFICIENT_SCOPE"
63
+ : response.status === 429
64
+ ? "RATE_LIMITED"
65
+ : "INTERNAL_FAILURE"),
66
+ {
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,
70
+ }
71
+ );
72
+ if (body.error)
73
+ throw new CliError(
74
+ error?.message || "MCP request failed",
75
+ error?.code || "INVALID_PARAMETERS",
76
+ error
77
+ );
78
+ if (body.result?.isError) {
79
+ const detail = body.result.structuredContent?.error || {};
80
+ throw new CliError(
81
+ detail.message || body.result.content?.[0]?.text || "Tool failed",
82
+ detail.code || "INTERNAL_FAILURE",
83
+ detail
84
+ );
85
+ }
86
+ return body;
87
+ }
88
+ async tool(name, args = {}) {
89
+ const body = await this.request("/api/mcp", {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
92
+ body: JSON.stringify({
93
+ jsonrpc: "2.0",
94
+ id: randomUUID(),
95
+ method: "tools/call",
96
+ params: { name, arguments: args },
97
+ }),
98
+ });
99
+ return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
100
+ }
101
+ async account(selector) {
102
+ const data = await this.tool("accounts_list");
103
+ const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
104
+ const exact = items.filter((a) => a.id === selector);
105
+ const matches = exact.length
106
+ ? exact
107
+ : items.filter(
108
+ (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
109
+ );
110
+ if (matches.length !== 1)
111
+ throw new CliError(
112
+ "Choose exactly one account ID or a unique channel name from accounts list."
113
+ );
114
+ return matches[0];
115
+ }
116
+ async upload(file, key) {
117
+ const info = await stat(file);
118
+ if (!info.isFile()) throw new CliError("Select one regular file.");
119
+ const mime =
120
+ extname(file).toLowerCase() === ".png"
121
+ ? "image/png"
122
+ : extname(file).toLowerCase() === ".mp4"
123
+ ? "video/mp4"
124
+ : null;
125
+ if (!mime)
126
+ throw new CliError(
127
+ "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
128
+ );
129
+ if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
130
+ throw new CliError("File exceeds the raw media upload size limit.");
131
+ const hash = createHash("sha256");
132
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
133
+ return this.request("/api/mcp/media", {
134
+ method: "POST",
135
+ headers: {
136
+ "Content-Type": mime,
137
+ "Content-Length": String(info.size),
138
+ "X-File-Name": encodeURIComponent(basename(file)),
139
+ "Idempotency-Key": key || randomUUID(),
140
+ "X-Content-SHA256": hash.digest("hex"),
141
+ },
142
+ body: createReadStream(file),
143
+ duplex: "half",
144
+ });
145
+ }
146
+ }
@@ -0,0 +1,92 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ export async function keychain(
4
+ action,
5
+ origin,
6
+ token = "",
7
+ platform = process.platform,
8
+ run = runCommand
9
+ ) {
10
+ if (!["get", "set", "delete"].includes(action)) throw Error("Unknown keychain action.");
11
+ const target = `PostPilotCLI:${new URL(origin).origin}`;
12
+ if (token && !/^[\w.:-]{8,512}$/.test(token)) throw Error("Invalid token format.");
13
+ let value;
14
+ if (platform === "win32")
15
+ value = await run(
16
+ "powershell.exe",
17
+ [
18
+ "-NoProfile",
19
+ "-NonInteractive",
20
+ "-File",
21
+ fileURLToPath(new URL("./keychain.ps1", import.meta.url)),
22
+ action,
23
+ target,
24
+ ],
25
+ action === "set" ? token : ""
26
+ );
27
+ else if (platform === "darwin") {
28
+ if (action === "set")
29
+ value = await run(
30
+ "/usr/bin/security",
31
+ ["-i"],
32
+ `add-generic-password -U -a PostPilot -s "${target}" -w "${token}"\n`
33
+ );
34
+ else
35
+ value = await run("/usr/bin/security", [
36
+ action === "get" ? "find-generic-password" : "delete-generic-password",
37
+ "-a",
38
+ "PostPilot",
39
+ "-s",
40
+ target,
41
+ ...(action === "get" ? ["-w"] : []),
42
+ ]);
43
+ } else if (platform === "linux") {
44
+ value = await run(
45
+ "secret-tool",
46
+ [
47
+ action === "set" ? "store" : action === "get" ? "lookup" : "clear",
48
+ ...(action === "set" ? ["--label=PostPilot CLI"] : []),
49
+ "service",
50
+ "postpilot",
51
+ "origin",
52
+ origin,
53
+ ],
54
+ action === "set" ? `${token}\n` : ""
55
+ );
56
+ } else
57
+ throw Error("No supported OS keychain. Use POSTPILOT_TOKEN from your runtime secret store.");
58
+ return action === "get" ? value.trim() : undefined;
59
+ }
60
+ async function runCommand(command, args, input = "") {
61
+ return new Promise((resolve, reject) => {
62
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
63
+ let output = "";
64
+ const timer = setTimeout(() => {
65
+ child.kill();
66
+ reject(Error("OS keychain timed out or is locked."));
67
+ }, 30000);
68
+ child.stdout.on("data", (chunk) => {
69
+ output += chunk;
70
+ if (output.length > 4096) child.kill();
71
+ });
72
+ child.stderr.resume();
73
+ child.on("error", () => {
74
+ clearTimeout(timer);
75
+ reject(
76
+ Error(
77
+ "OS keychain unavailable. Unlock it or use a protected POSTPILOT_TOKEN environment variable."
78
+ )
79
+ );
80
+ });
81
+ child.on("close", (code) => {
82
+ clearTimeout(timer);
83
+ code === 0
84
+ ? resolve(output)
85
+ : reject(
86
+ Error("OS keychain refused the operation or no credential exists. Run postpilot login.")
87
+ );
88
+ });
89
+ child.stdin.on("error", () => {});
90
+ child.stdin.end(input);
91
+ });
92
+ }
@@ -0,0 +1,37 @@
1
+ param([string]$Action,[string]$Target)
2
+ $ErrorActionPreference = 'Stop'
3
+ Add-Type @'
4
+ using System;
5
+ using System.Runtime.InteropServices;
6
+ public static class PostPilotCredential {
7
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
8
+ public struct CREDENTIAL { public int Flags; public int Type; public string TargetName; public string Comment; public long LastWritten; public int CredentialBlobSize; public IntPtr CredentialBlob; public int Persist; public int AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName; }
9
+ [DllImport("advapi32.dll",EntryPoint="CredWriteW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Write(ref CREDENTIAL value,int flags);
10
+ [DllImport("advapi32.dll",EntryPoint="CredReadW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Read(string target,int type,int flags,out IntPtr pointer);
11
+ [DllImport("advapi32.dll",EntryPoint="CredDeleteW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Delete(string target,int type,int flags);
12
+ [DllImport("advapi32.dll")] public static extern void CredFree(IntPtr pointer);
13
+ }
14
+ '@
15
+ if ($Action -eq 'set') {
16
+ $token = [Console]::In.ReadToEnd().Trim()
17
+ $bytes = [Text.Encoding]::Unicode.GetBytes($token)
18
+ $pointer = [Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
19
+ try {
20
+ [Runtime.InteropServices.Marshal]::Copy($bytes,0,$pointer,$bytes.Length)
21
+ $credential = New-Object PostPilotCredential+CREDENTIAL
22
+ $credential.Type=1; $credential.TargetName=$Target; $credential.UserName='PostPilot'; $credential.Persist=2
23
+ $credential.CredentialBlobSize=$bytes.Length; $credential.CredentialBlob=$pointer
24
+ if (-not [PostPilotCredential]::Write([ref]$credential,0)) { exit 1 }
25
+ } finally {
26
+ for ($index=0;$index -lt $bytes.Length;$index++) { [Runtime.InteropServices.Marshal]::WriteByte($pointer,$index,0) }
27
+ [Runtime.InteropServices.Marshal]::FreeHGlobal($pointer)
28
+ }
29
+ } elseif ($Action -eq 'get') {
30
+ $pointer=[IntPtr]::Zero
31
+ if (-not [PostPilotCredential]::Read($Target,1,0,[ref]$pointer)) { exit 1 }
32
+ try {
33
+ $credential=[Runtime.InteropServices.Marshal]::PtrToStructure($pointer,[type][PostPilotCredential+CREDENTIAL])
34
+ [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringUni($credential.CredentialBlob,$credential.CredentialBlobSize/2))
35
+ } finally { [PostPilotCredential]::CredFree($pointer) }
36
+ } elseif ($Action -eq 'delete') { if (-not [PostPilotCredential]::Delete($Target,1,0)) { exit 1 } }
37
+ else { exit 1 }
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
+ }