@chaouidz/postpilot 1.0.0 → 1.1.1

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/src/client.mjs CHANGED
@@ -1,145 +1,168 @@
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.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
- requestId: response.headers.get("X-Request-Id"),
68
- retryAfter: response.headers.get("Retry-After"),
69
- }
70
- );
71
- if (body.error)
72
- throw new CliError(
73
- error?.message || "MCP request failed",
74
- error?.code || "INVALID_PARAMETERS",
75
- error
76
- );
77
- if (body.result?.isError) {
78
- const detail = body.result.structuredContent?.error || {};
79
- throw new CliError(
80
- detail.message || body.result.content?.[0]?.text || "Tool failed",
81
- detail.code || "INTERNAL_FAILURE",
82
- detail
83
- );
84
- }
85
- return body;
86
- }
87
- async tool(name, args = {}) {
88
- const body = await this.request("/api/mcp", {
89
- method: "POST",
90
- headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
91
- body: JSON.stringify({
92
- jsonrpc: "2.0",
93
- id: randomUUID(),
94
- method: "tools/call",
95
- params: { name, arguments: args },
96
- }),
97
- });
98
- return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
99
- }
100
- async account(selector) {
101
- const data = await this.tool("accounts_list");
102
- const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
103
- const exact = items.filter((a) => a.id === selector);
104
- const matches = exact.length
105
- ? exact
106
- : items.filter(
107
- (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
108
- );
109
- if (matches.length !== 1)
110
- throw new CliError(
111
- "Choose exactly one account ID or a unique channel name from accounts list."
112
- );
113
- return matches[0];
114
- }
115
- async upload(file, key) {
116
- const info = await stat(file);
117
- if (!info.isFile()) throw new CliError("Select one regular file.");
118
- const mime =
119
- extname(file).toLowerCase() === ".png"
120
- ? "image/png"
121
- : extname(file).toLowerCase() === ".mp4"
122
- ? "video/mp4"
123
- : null;
124
- if (!mime)
125
- throw new CliError(
126
- "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
127
- );
128
- if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
129
- throw new CliError("File exceeds the raw media upload size limit.");
130
- const hash = createHash("sha256");
131
- for await (const chunk of createReadStream(file)) hash.update(chunk);
132
- return this.request("/api/mcp/media", {
133
- method: "POST",
134
- headers: {
135
- "Content-Type": mime,
136
- "Content-Length": String(info.size),
137
- "X-File-Name": encodeURIComponent(basename(file)),
138
- "Idempotency-Key": key || randomUUID(),
139
- "X-Content-SHA256": hash.digest("hex"),
140
- },
141
- body: createReadStream(file),
142
- duplex: "half",
143
- });
144
- }
145
- }
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
+ // 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;
27
+ }
28
+ }
29
+ export const EXIT_CODES = {
30
+ INVALID_PARAMETERS: 2,
31
+ AUTHENTICATION_EXPIRED: 3,
32
+ INSUFFICIENT_SCOPE: 3,
33
+ NOT_FOUND: 4,
34
+ PENDING_APPROVAL: 5,
35
+ RATE_LIMITED: 6,
36
+ CAPACITY_EXCEEDED: 8,
37
+ PROVIDER_REJECTED: 7,
38
+ INTERNAL_FAILURE: 7,
39
+ };
40
+ export class Client {
41
+ constructor(origin, token, fetcher = fetch) {
42
+ this.origin = new URL(origin).origin;
43
+ this.token = token;
44
+ this.fetch = fetcher;
45
+ if (!token)
46
+ throw new CliError(
47
+ "Run postpilot login or configure POSTPILOT_TOKEN.",
48
+ "AUTHENTICATION_EXPIRED"
49
+ );
50
+ if (
51
+ !/^https:/.test(this.origin) &&
52
+ !["127.0.0.1", "localhost", "[::1]"].includes(new URL(origin).hostname)
53
+ )
54
+ throw new CliError("Remote API connections require HTTPS.");
55
+ }
56
+ async request(path, init = {}) {
57
+ let response;
58
+ try {
59
+ response = await this.fetch(this.origin + path, {
60
+ ...init,
61
+ redirect: "error",
62
+ signal: AbortSignal.timeout(150000),
63
+ headers: { ...init.headers, Authorization: `Bearer ${this.token}` },
64
+ });
65
+ } catch {
66
+ throw new CliError(
67
+ "Could not reach PostPilot. Check the URL and network; do not blindly retry publication.",
68
+ "INTERNAL_FAILURE"
69
+ );
70
+ }
71
+ const body = await response.json().catch(() => ({}));
72
+ const error =
73
+ (body.result?.isError ? body.result.structuredContent?.error : null) ||
74
+ body.error?.data ||
75
+ body.error;
76
+ if (!response.ok)
77
+ throw new CliError(
78
+ typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
79
+ error?.code ||
80
+ (response.status === 401
81
+ ? "AUTHENTICATION_EXPIRED"
82
+ : response.status === 403
83
+ ? "INSUFFICIENT_SCOPE"
84
+ : response.status === 429
85
+ ? "RATE_LIMITED"
86
+ : "INTERNAL_FAILURE"),
87
+ {
88
+ ...error?.details,
89
+ requestId: response.headers.get("X-Request-Id") || error?.requestId,
90
+ retryAfter:
91
+ response.headers.get("Retry-After") || error?.retryAfter || error?.details?.retryAfter,
92
+ }
93
+ );
94
+ if (body.error)
95
+ throw new CliError(
96
+ error?.message || "MCP request failed",
97
+ error?.code || "INVALID_PARAMETERS",
98
+ error
99
+ );
100
+ if (body.result?.isError) {
101
+ const detail = body.result.structuredContent?.error || {};
102
+ throw new CliError(
103
+ detail.message || body.result.content?.[0]?.text || "Tool failed",
104
+ detail.code || "INTERNAL_FAILURE",
105
+ detail
106
+ );
107
+ }
108
+ return body;
109
+ }
110
+ async tool(name, args = {}) {
111
+ const body = await this.request("/api/mcp", {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
114
+ body: JSON.stringify({
115
+ jsonrpc: "2.0",
116
+ id: randomUUID(),
117
+ method: "tools/call",
118
+ params: { name, arguments: args },
119
+ }),
120
+ });
121
+ return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
122
+ }
123
+ async account(selector) {
124
+ const data = await this.tool("accounts_list");
125
+ const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
126
+ const exact = items.filter((a) => a.id === selector);
127
+ const matches = exact.length
128
+ ? exact
129
+ : items.filter(
130
+ (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
131
+ );
132
+ if (matches.length !== 1)
133
+ throw new CliError(
134
+ "Choose exactly one account ID or a unique channel name from accounts list."
135
+ );
136
+ return matches[0];
137
+ }
138
+ async upload(file, key) {
139
+ const info = await stat(file);
140
+ if (!info.isFile()) throw new CliError("Select one regular file.");
141
+ const mime =
142
+ extname(file).toLowerCase() === ".png"
143
+ ? "image/png"
144
+ : extname(file).toLowerCase() === ".mp4"
145
+ ? "video/mp4"
146
+ : null;
147
+ if (!mime)
148
+ throw new CliError(
149
+ "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
150
+ );
151
+ if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
152
+ throw new CliError("File exceeds the raw media upload size limit.");
153
+ const hash = createHash("sha256");
154
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
155
+ return this.request("/api/mcp/media", {
156
+ method: "POST",
157
+ headers: {
158
+ "Content-Type": mime,
159
+ "Content-Length": String(info.size),
160
+ "X-File-Name": encodeURIComponent(basename(file)),
161
+ "Idempotency-Key": key || randomUUID(),
162
+ "X-Content-SHA256": hash.digest("hex"),
163
+ },
164
+ body: createReadStream(file),
165
+ duplex: "half",
166
+ });
167
+ }
168
+ }
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
+ }