@yoonion/mimi-seed-mcp 0.25.4 → 0.25.6

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/LICENSE CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
4
 
5
- Required Notice: Copyright 2026 Pryzm GG (https://mimi-seed.pryzm.gg)
5
+ Required Notice: Copyright 2026 Lucas Foundation (https://mimi-seed.oddbout.com)
6
6
 
7
7
  ## Acceptance
8
8
 
package/README.md CHANGED
@@ -143,7 +143,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
143
143
  ---
144
144
 
145
145
  <!-- generated:readme-tools-heading:start — edit scripts/docs-spec.mjs, then npm run plugin:sync -->
146
- ## 제공 도구 (150+ 개 · 24개 영역)
146
+ ## 제공 도구 (150+ 개 · 25개 영역)
147
147
  <!-- generated:readme-tools-heading:end -->
148
148
 
149
149
  <!-- generated:readme-tools-table:start — edit scripts/docs-spec.mjs, then npm run plugin:sync -->
@@ -166,6 +166,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
166
166
  | GCP Billing | 4 | `gcp_get_billing_info` / `gcp_list_billing_projects` / `gcp_list_budgets` / `gcp_create_budget` |
167
167
  | Threads | 7 | `threads_post` / `threads_post_video` / `threads_post_carousel` / `threads_refresh_token` |
168
168
  | TikTok Business | 7 | `tiktok_business_plan_video_post` / `tiktok_business_publish_video` / `tiktok_business_get_publish_status` |
169
+ | 소셜 통합 게시 | 1 | `social_publish` |
169
170
  | 출시 점검 | 5 | `playstore_check_submission_risks` / `appstore_check_submission_risks` / `android_check_billing_compliance` / `screenshot_validate` / `release_status` |
170
171
  | Instagram | 4 | `instagram_post_image` / `instagram_post_carousel` / `instagram_save_config` |
171
172
  | Android 서명 | 3 | `android_signing_setup` / `android_generate_keystore` / `jenkins_upload_playstore_sa` |
@@ -90,6 +90,7 @@ Use the table to find tool names, then select only the active tools needed for t
90
90
  | Search indexing (Search Console / Naver) | `select:gsc_list_sites,gsc_list_sitemaps,gsc_get_sitemap,gsc_submit_sitemap,gsc_inspect_url,gsc_search_analytics,naver_check_page,naver_indexnow_submit` |
91
91
  | Social posting (Facebook / Instagram / Threads) | `select:facebook_current_config,facebook_save_config,facebook_list_pages,facebook_get_page,facebook_post_photo,facebook_post_multi_photo,instagram_save_config,instagram_get_account,instagram_post_image,instagram_post_carousel,threads_current_config,threads_save_config,threads_refresh_token,threads_get_account,threads_post,threads_post_video,threads_post_carousel` |
92
92
  | TikTok Business video publish | `select:tiktok_business_auth_status,tiktok_business_get_account,tiktok_business_get_video_settings,tiktok_business_plan_video_post,tiktok_business_publish_video,tiktok_business_get_publish_status,tiktok_business_list_publish_audits` |
93
+ | Cross-post one announcement to several platforms | `select:mimi_seed_status,tiktok_business_plan_video_post,social_publish` |
93
94
  | Jenkins credentials + jobs | `select:jenkins_status,jenkins_save_config,jenkins_list_credentials,jenkins_create_credential,jenkins_delete_credential,jenkins_upload_keystore,jenkins_upload_playstore_sa,jenkins_list_jobs,jenkins_get_job_config,jenkins_create_job,jenkins_update_job` |
94
95
  | Jenkins build run + track | `select:jenkins_status,jenkins_trigger_build,jenkins_get_queue_item,jenkins_get_build_status` |
95
96
  | CI (GitHub/GitLab) | `select:ci_save_config,ci_list_workflows,ci_trigger_build,ci_get_build_status,ci_list_recent_builds,ci_cancel_build` |
@@ -138,6 +139,34 @@ all three Meta platforms in one pass. `mimi-seed auth social` does the same for
138
139
  Facebook, Instagram, Threads, TikTok), skipping connected ones and reconnecting expiring tokens. It connects YouTube to
139
140
  the `youtube` Google profile, so pass `profile: "youtube"` to `youtube_*` tools when `mimi_seed_status` names it.
140
141
 
142
+ **Posting to several platforms.** When the user wants the same announcement on more than one platform, use
143
+ `social_publish` instead of calling each `*_post_*` tool:
144
+
145
+ 1. Call `mimi_seed_status` to see which channels are connected (and which Google profile holds YouTube).
146
+ 2. For TikTok, first make a plan with `tiktok_business_plan_video_post` and pass its `planId` as `tiktok.planId`.
147
+ 3. Call `social_publish` **without** `confirm`. It returns a plan per target, and `ok: false` with `problems` if any
148
+ target cannot post. Fix those (per-platform `text`, images, `youtube.title`, …) and preview again.
149
+ 4. Show the plan, including YouTube's privacy, to the user and get explicit approval, then call again with the same
150
+ arguments plus `confirm: true`.
151
+ 5. Report the per-platform `results`. The same post (same platform, account, and content) is never posted twice, so
152
+ if something `failed`, fix it if needed (e.g. that platform's own `threads.text`) and call again: platforms that
153
+ already posted are skipped. Approvals name one record by the `at` the plan showed for that platform's post and
154
+ account (after changing the content, preview again and use the new plan's `at`); an approval stays valid until its
155
+ action succeeds (or ends unknown), after which that record changes and the same arguments no longer match:
156
+ - To post identical content again on purpose, get the user's go-ahead and pass
157
+ `repost: [{ "platform": "<platform>", "at": "<at of that posted record>" }]` (TikTok needs a new plan instead).
158
+ - If a result is `unknown_outcome`, do **not** retry on your own: that account stays blocked, even for edited
159
+ content. Ask the user to check the platform. If the post **is** there, pass
160
+ `markPosted: [{ "platform": "<platform>", "at": "<at the plan shows>" }]` (it is recorded as posted, nothing is
161
+ sent); if it is **not**, pass `resendUnknown` with the same shape (it also resends an unknown repost). On TikTok,
162
+ which never republishes a plan, a resend needs a new plan sent with that `resendUnknown`. `markPosted` with
163
+ `confirm: true` is recorded even if the plan is blocked by something else (e.g. the rendered video was moved);
164
+ the result lists it under `marks`.
165
+ A `posted` result with a `warning` that it could not be recorded is handled the same way (`markPosted`); a
166
+ `failed` one whose error says it could not be recorded is resent with the `resendUnknown` the error names. A failed
167
+ pre-send check (an expired token, a bad video file) means nothing was posted anywhere; "another call is publishing
168
+ to this account" means wait and call again.
169
+
141
170
  All three Meta platforms can use named local profiles. Save one with
142
171
  `mimi-seed auth facebook|instagram|threads --profile <id>`, then select it per project with `.mimi-seed.json` →
143
172
  `socialProfiles.facebook` / `.instagram` / `.threads`. MCP tools also accept an explicit
@@ -252,6 +281,7 @@ per-domain inventory is [`docs/domain/tool-catalog.md`](domain/tool-catalog.md).
252
281
  | **Android signing** | `android_signing_setup` · `android_generate_keystore` · `jenkins_upload_playstore_sa` |
253
282
  | **Facebook / Instagram / Threads** | `facebook_post_photo` · `instagram_post_carousel` · `threads_post` · `threads_post_video` · `threads_refresh_token` |
254
283
  | **TikTok Business** | `tiktok_business_auth_status` · `tiktok_business_plan_video_post` · `tiktok_business_publish_video` · `tiktok_business_get_publish_status` |
284
+ | **Cross-post** | `social_publish` — one post to several platforms; see "Posting to several platforms" below |
255
285
  | **Checks** | `playstore_check_submission_risks` · `appstore_check_submission_risks` · `android_check_billing_compliance` · `screenshot_validate` · `release_status` |
256
286
  | **AI / Auth** | `generate_release_notes_from_commits` · `generate_review_reply` · `mimi_seed_status` · `mimi_seed_auth_start` · `mimi_seed_auth_status` · `mimi_seed_remote_sync_credentials` |
257
287
  | **Video production** | `youtube_upload_video` · `youtube_get_video_status` · `youtube_update_video_privacy` · `video_save_plan` · `video_plan_from_story` · `video_research_youtube` · `video_search_stock_assets` · `video_synthesize_research` · `video_generate_image` · `video_build_timeline` · `video_render` · `video_job_status` · `video_validate` |
@@ -365,7 +395,7 @@ setup, beta invites — is
365
395
  3. Call again with the **same arguments** plus `confirm: true`.
366
396
 
367
397
  Some **D** tools gate themselves (`ownGate` in the manifest) and ask for confirmation only on the dangerous
368
- path: `tiktok_business_publish_video` uses `confirmPublish`; `appstore_phased_release` runs
398
+ path: `tiktok_business_publish_video` uses `confirmPublish`; `social_publish` returns its own per-platform dry-run plan and posts only with `confirm: true`; `appstore_phased_release` runs
369
399
  `pause`/`resume`/`enable`/`status` directly; `jenkins_create_credential` / `jenkins_upload_keystore` /
370
400
  `jenkins_upload_playstore_sa` send nothing without `confirm: true` — their dry-run says whether the id is **new**
371
401
  (it will be created) or **already exists** (it will be replaced, which cannot be undone).
@@ -402,7 +432,7 @@ build is already in the queue, so track its `queue_id` and do not retrigger.
402
432
  | `appstore_delete_screenshot_set`, `playstore_delete_all_images`, `playstore_replace_images` | Deletes assets. |
403
433
  | `playstore_delete_product`, `jenkins_delete_credential`, `firebase_delete_*_app` | Destructive. |
404
434
  | `jenkins_trigger_build` | Runs a Jenkins job, which may deploy or publish. |
405
- | `facebook_post_*`, `instagram_post_*`, `threads_post*`, `*_reply_review`, `youtube_reply_comment` | Public, outward-facing. |
435
+ | `facebook_post_*`, `instagram_post_*`, `threads_post*`, `social_publish`, `*_reply_review`, `youtube_reply_comment` | Public, outward-facing. |
406
436
  | `iam_create_key`, `iam_add_iam_policy_binding` | Issues a permanent credential / changes project IAM. |
407
437
 
408
438
  General rules:
@@ -0,0 +1,52 @@
1
+ export type SocialTarget = 'facebook' | 'instagram' | 'threads' | 'youtube' | 'tiktok';
2
+ export type PostState = 'sending' | 'posted' | 'failed' | 'unknown';
3
+ export interface PostRecord {
4
+ state: PostState;
5
+ at: string;
6
+ id?: string;
7
+ url?: string;
8
+ error?: string;
9
+ /**
10
+ * The `attempt` of the send whose outcome this record settled (posted, cleanly failed, or marked posted). A marker
11
+ * naming that attempt is settled even if clearing it failed. Matched by id, never by time: clocks tie and step back.
12
+ */
13
+ settledAttempt?: string;
14
+ }
15
+ /** An account with a send whose outcome is not known yet (or never became known). */
16
+ export interface PendingRecord {
17
+ postKey: string;
18
+ state: 'sending' | 'unknown';
19
+ at: string;
20
+ /** Random id of this send. Without one (written by an earlier build) the marker is never treated as settled. */
21
+ attempt?: string;
22
+ }
23
+ export declare function recordPath(platform: SocialTarget, postKey: string): string;
24
+ export declare function readRecord(platform: SocialTarget, postKey: string): PostRecord | null;
25
+ export declare function writeRecord(platform: SocialTarget, postKey: string, record: PostRecord): void;
26
+ export declare function readPending(platform: SocialTarget, account: string): PendingRecord | null;
27
+ export declare function writePending(platform: SocialTarget, account: string, pending: PendingRecord): void;
28
+ export declare function clearPending(platform: SocialTarget, account: string): void;
29
+ /**
30
+ * Compare-and-set on the account marker: replace it with `next` (or remove it, for null) only if it is still the
31
+ * one this send wrote (same postKey, `at`, and attempt). Returns false — and changes nothing — when another call has replaced
32
+ * it meanwhile (possible only after this call's lock went stale), so one call's outcome never erases another's.
33
+ */
34
+ export declare function replacePendingIfOurs(platform: SocialTarget, account: string, ours: {
35
+ postKey: string;
36
+ at: string;
37
+ attempt?: string;
38
+ }, next: PendingRecord | null): boolean;
39
+ export interface AccountLock {
40
+ /** Throws if the lock is no longer ours; refreshes it otherwise. Call right before each publishing call. */
41
+ confirmHeld(): void;
42
+ release(): void;
43
+ }
44
+ /** True while a live call holds this account's lock (it is publishing to it right now). */
45
+ export declare function isAccountLocked(platform: SocialTarget, account: string): boolean;
46
+ export declare function inProgressMessage(): string;
47
+ /**
48
+ * Reserve an account for this process; throws "in progress" if another live call holds it. A stale lock is replaced
49
+ * only while holding a breaker directory (mkdir, so one caller at a time) and after re-checking it. A breaker is never
50
+ * removed by anyone but its creator; one left by a run that died is reported for a person to delete.
51
+ */
52
+ export declare function acquireAccountLock(platform: SocialTarget, account: string): AccountLock;
@@ -0,0 +1,271 @@
1
+ // social_publish's at-most-once records.
2
+ //
3
+ // ~/.mimi-seed/social-publish/targets/<sha256(platform:postKey)>.json one per **post** (platform + account +
4
+ // exact content): { state, at, id?, url?, error?,
5
+ // settledAttempt? }
6
+ // ~/.mimi-seed/social-publish/accounts/<sha256(platform:account)>.json one per **account** while a send to it is
7
+ // unresolved: { postKey, state, at, attempt? }
8
+ // ~/.mimi-seed/social-publish/accounts/<sha256(platform:account)>.lock/ held while publishing to that account
9
+ //
10
+ // The account marker exists from just before a publishing call until its outcome is known. A `sending` or `unknown`
11
+ // marker blocks every post to that account — even edited content — until a person checks the platform and passes
12
+ // markPosted (it is live) or resendUnknown (it is not), so a post whose outcome is unknown can never go out a second
13
+ // time in another form.
14
+ // Not a credential, but it lives under ~/.mimi-seed and uses the same atomic 0600 writer. This module is its only
15
+ // writer.
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { createHash, randomUUID } from 'node:crypto';
20
+ import { CREDENTIAL_DIR_MODE, writeCredentialFile, writeCredentialJson } from '#core/atomic-write.js';
21
+ import { readCredentialFileSync } from '#core/credential-read.js';
22
+ import { catalog } from '#core/lang.js';
23
+ const M = catalog({
24
+ unreadable: (file) => `게시 기록 파일을 읽을 수 없어 이미 게시됐는지 판단할 수 없습니다: ${file}. 파일을 확인한 뒤 다시 시도하세요.`,
25
+ inProgress: '이 계정에 지금 다른 호출이 게시하고 있습니다. 끝난 뒤 다시 보내세요 — 이미 게시된 곳은 건너뜁니다.',
26
+ deadBreaker: (dir) => `이전 실행이 잠금 정리 도중 종료되어 표시가 남았습니다. 다른 게시가 진행 중이 아니라면 ${dir} 폴더를 지우고 다시 보내세요.`,
27
+ }, {
28
+ unreadable: (file) => `Cannot read the publish record, so it is unknown whether this was already posted: ${file}. Check the file, then try again.`,
29
+ inProgress: 'Another call is publishing to this account right now. Send again once it finishes — whatever it posted is skipped.',
30
+ deadBreaker: (dir) => `An earlier run stopped while clearing a lock and left a marker behind. If nothing else is publishing, delete the folder ${dir} and send again.`,
31
+ });
32
+ /** Without a heartbeat for this long, a lock's owner is gone (it refreshes the lock every HEARTBEAT_MS). */
33
+ const STALE_LOCK_MS = 30 * 60 * 1000;
34
+ const HEARTBEAT_MS = 60 * 1000;
35
+ /** A breaker held longer than this belongs to a process that died while replacing a stale lock (it takes ms). */
36
+ const STALE_BREAKER_MS = 60 * 1000;
37
+ function root() {
38
+ return path.join(os.homedir(), '.mimi-seed', 'social-publish');
39
+ }
40
+ function hashed(dir, platform, id) {
41
+ return path.join(root(), dir, createHash('sha256').update(`${platform}:${id}`).digest('hex'));
42
+ }
43
+ export function recordPath(platform, postKey) {
44
+ return `${hashed('targets', platform, postKey)}.json`;
45
+ }
46
+ function pendingPath(platform, account) {
47
+ return `${hashed('accounts', platform, account)}.json`;
48
+ }
49
+ function lockPath(platform, account) {
50
+ return `${hashed('accounts', platform, account)}.lock`;
51
+ }
52
+ /** An `at` must be a date: every later `at` is computed from it, and an approval names a record by it. */
53
+ const isDate = (value) => typeof value === 'string' && !Number.isNaN(Date.parse(value));
54
+ /** Missing → null. Unreadable → throw: treating it as missing could post again what it recorded. */
55
+ function readJsonRecord(file, valid) {
56
+ if (!fs.existsSync(file))
57
+ return null;
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(readCredentialFileSync(file));
61
+ }
62
+ catch (error) {
63
+ throw new Error(M().unreadable(file), { cause: error });
64
+ }
65
+ if (!parsed || typeof parsed !== 'object' || !valid(parsed))
66
+ throw new Error(M().unreadable(file));
67
+ return parsed;
68
+ }
69
+ export function readRecord(platform, postKey) {
70
+ return readJsonRecord(recordPath(platform, postKey), (r) => typeof r.state === 'string' && isDate(r.at));
71
+ }
72
+ export function writeRecord(platform, postKey, record) {
73
+ writeCredentialJson(recordPath(platform, postKey), record);
74
+ }
75
+ export function readPending(platform, account) {
76
+ return readJsonRecord(pendingPath(platform, account), (r) => typeof r.postKey === 'string' && (r.state === 'sending' || r.state === 'unknown') && isDate(r.at)
77
+ && (r.attempt === undefined || typeof r.attempt === 'string'));
78
+ }
79
+ export function writePending(platform, account, pending) {
80
+ writeCredentialJson(pendingPath(platform, account), pending);
81
+ }
82
+ export function clearPending(platform, account) {
83
+ fs.rmSync(pendingPath(platform, account), { force: true });
84
+ }
85
+ /**
86
+ * Compare-and-set on the account marker: replace it with `next` (or remove it, for null) only if it is still the
87
+ * one this send wrote (same postKey, `at`, and attempt). Returns false — and changes nothing — when another call has replaced
88
+ * it meanwhile (possible only after this call's lock went stale), so one call's outcome never erases another's.
89
+ */
90
+ export function replacePendingIfOurs(platform, account, ours, next) {
91
+ const current = readPending(platform, account);
92
+ if (!current || current.postKey !== ours.postKey || current.at !== ours.at || current.attempt !== ours.attempt)
93
+ return false;
94
+ if (next)
95
+ writePending(platform, account, next);
96
+ else
97
+ clearPending(platform, account);
98
+ return true;
99
+ }
100
+ // ── account lock ─────────────────────────────────────────────────────────────
101
+ /** Locks this process holds right now. A lock naming our pid that is not here was left by an earlier run. */
102
+ const heldHere = new Set();
103
+ const isCode = (error, code) => error.code === code;
104
+ /** The owner file holds "<pid> <token>": the pid says whether the holder is alive, the token which acquisition it is. */
105
+ function readOwner(lock) {
106
+ try {
107
+ const [pidText, token = ''] = readCredentialFileSync(path.join(lock, 'owner')).trim().split(' ');
108
+ const pid = Number(pidText);
109
+ return Number.isInteger(pid) && pid > 0 ? { pid, token } : null;
110
+ }
111
+ catch {
112
+ // No owner file: one caught between mkdir and the owner write. Decided by age instead.
113
+ return null;
114
+ }
115
+ }
116
+ function lockOwner(lock) {
117
+ return readOwner(lock)?.pid ?? null;
118
+ }
119
+ /**
120
+ * 'missing' (released meanwhile), true (its owner is gone), or false (in use). A holder refreshes the lock's mtime
121
+ * every minute, so a lock not refreshed for STALE_LOCK_MS is stale whatever its pid says (pids are reused).
122
+ */
123
+ function lockState(lock) {
124
+ let age;
125
+ try {
126
+ age = Date.now() - fs.statSync(lock).mtimeMs;
127
+ }
128
+ catch (error) {
129
+ if (isCode(error, 'ENOENT'))
130
+ return 'missing';
131
+ throw error;
132
+ }
133
+ if (age >= STALE_LOCK_MS)
134
+ return true;
135
+ const pid = lockOwner(lock);
136
+ if (pid === null)
137
+ return false;
138
+ // Our own pid: ours only if we hold it now. Otherwise an earlier run of this server, with the same pid, died.
139
+ if (pid === process.pid)
140
+ return !heldHere.has(lock);
141
+ try {
142
+ process.kill(pid, 0);
143
+ return false;
144
+ }
145
+ catch (error) {
146
+ // EPERM: the process exists but belongs to someone else — still in use. ESRCH: gone.
147
+ return !isCode(error, 'EPERM');
148
+ }
149
+ }
150
+ function takeLock(lock) {
151
+ fs.mkdirSync(lock, { mode: CREDENTIAL_DIR_MODE });
152
+ // A pid alone cannot tell two acquisitions in this same process apart (e.g. after a long suspend, another call
153
+ // here judged this lock stale and took it): the token can.
154
+ const token = randomUUID();
155
+ const ours = () => {
156
+ const owner = readOwner(lock);
157
+ return owner?.pid === process.pid && owner.token === token;
158
+ };
159
+ try {
160
+ writeCredentialFile(path.join(lock, 'owner'), `${process.pid} ${token}`);
161
+ }
162
+ catch (error) {
163
+ // Without the owner file the lock would block this account until it ages out; drop it before rethrowing.
164
+ fs.rmSync(lock, { recursive: true, force: true });
165
+ throw error;
166
+ }
167
+ heldHere.add(lock);
168
+ const refresh = () => {
169
+ const now = new Date();
170
+ fs.utimesSync(lock, now, now);
171
+ };
172
+ // Keep the lock fresh while a long upload runs, so it never looks stale to another caller.
173
+ const heartbeat = setInterval(() => {
174
+ try {
175
+ refresh();
176
+ }
177
+ catch {
178
+ // Removed under us (judged stale after a long suspend): confirmHeld() before each send catches that.
179
+ }
180
+ }, HEARTBEAT_MS);
181
+ heartbeat.unref();
182
+ return {
183
+ confirmHeld() {
184
+ // Before every publishing call: after a suspend, another caller may have judged this lock stale and taken it.
185
+ if (!ours())
186
+ throw new Error(M().inProgress);
187
+ refresh();
188
+ },
189
+ release() {
190
+ clearInterval(heartbeat);
191
+ // Remove it (and its in-process entry) only if it is still this acquisition: after a suspend, another caller —
192
+ // possibly in this same process — may have replaced it legitimately.
193
+ if (ours()) {
194
+ heldHere.delete(lock);
195
+ fs.rmSync(lock, { recursive: true, force: true });
196
+ }
197
+ },
198
+ };
199
+ }
200
+ /** True while a live call holds this account's lock (it is publishing to it right now). */
201
+ export function isAccountLocked(platform, account) {
202
+ return lockState(lockPath(platform, account)) === false;
203
+ }
204
+ export function inProgressMessage() {
205
+ return M().inProgress;
206
+ }
207
+ /**
208
+ * Reserve an account for this process; throws "in progress" if another live call holds it. A stale lock is replaced
209
+ * only while holding a breaker directory (mkdir, so one caller at a time) and after re-checking it. A breaker is never
210
+ * removed by anyone but its creator; one left by a run that died is reported for a person to delete.
211
+ */
212
+ export function acquireAccountLock(platform, account) {
213
+ fs.mkdirSync(path.join(root(), 'accounts'), { recursive: true, mode: CREDENTIAL_DIR_MODE });
214
+ const lock = lockPath(platform, account);
215
+ const breaker = `${lock}.break`;
216
+ for (let attempt = 0; attempt < 3; attempt += 1) {
217
+ try {
218
+ return takeLock(lock);
219
+ }
220
+ catch (error) {
221
+ if (!isCode(error, 'EEXIST'))
222
+ throw error;
223
+ }
224
+ const state = lockState(lock);
225
+ if (state === 'missing')
226
+ continue;
227
+ if (!state)
228
+ throw new Error(M().inProgress);
229
+ try {
230
+ fs.mkdirSync(breaker, { mode: CREDENTIAL_DIR_MODE });
231
+ }
232
+ catch (error) {
233
+ if (!isCode(error, 'EEXIST'))
234
+ throw error;
235
+ let breakerAge;
236
+ try {
237
+ breakerAge = Date.now() - fs.statSync(breaker).mtimeMs;
238
+ }
239
+ catch (statError) {
240
+ if (!isCode(statError, 'ENOENT'))
241
+ throw statError;
242
+ continue; // the other breaker finished: look again
243
+ }
244
+ // A breaker is held for milliseconds; an old one means a run died in that instant. Removing it automatically
245
+ // cannot be made race-free (whatever is at the path may already be someone else's fresh one), so a person does.
246
+ if (breakerAge >= STALE_BREAKER_MS)
247
+ throw new Error(M().deadBreaker(breaker), { cause: error });
248
+ throw new Error(M().inProgress, { cause: error });
249
+ }
250
+ try {
251
+ const again = lockState(lock);
252
+ if (again === false)
253
+ throw new Error(M().inProgress);
254
+ if (again === true)
255
+ fs.rmSync(lock, { recursive: true, force: true });
256
+ try {
257
+ return takeLock(lock);
258
+ }
259
+ catch (error) {
260
+ // Someone took it the ordinary way after we removed the stale one: it is theirs.
261
+ if (isCode(error, 'EEXIST'))
262
+ throw new Error(M().inProgress, { cause: error });
263
+ throw error;
264
+ }
265
+ }
266
+ finally {
267
+ fs.rmSync(breaker, { recursive: true, force: true });
268
+ }
269
+ }
270
+ throw new Error(M().inProgress);
271
+ }
@@ -0,0 +1,151 @@
1
+ import { type PendingRecord, type PostRecord, type SocialTarget } from './ledger.js';
2
+ export declare const SOCIAL_TARGETS: readonly ["facebook", "instagram", "threads", "youtube", "tiktok"];
3
+ export interface SocialPublishInput {
4
+ targets: SocialTarget[];
5
+ text: string;
6
+ imageUrls?: string[];
7
+ videoUrl?: string;
8
+ videoFilePath?: string;
9
+ facebook?: {
10
+ profile?: string;
11
+ text?: string;
12
+ };
13
+ instagram?: {
14
+ profile?: string;
15
+ text?: string;
16
+ };
17
+ threads?: {
18
+ profile?: string;
19
+ text?: string;
20
+ };
21
+ youtube?: {
22
+ profile?: string;
23
+ expectedChannelId: string;
24
+ title?: string;
25
+ description?: string;
26
+ tags?: string[];
27
+ privacyStatus?: 'private' | 'unlisted' | 'public';
28
+ madeForKids?: boolean;
29
+ containsSyntheticMedia?: boolean;
30
+ };
31
+ tiktok?: {
32
+ planId: string;
33
+ };
34
+ /**
35
+ * Unknown outcomes a person has checked are not live, each named by the platform and the `at` the plan showed for
36
+ * it: send again. A newer unknown outcome (a different `at`) stays blocked.
37
+ */
38
+ resendUnknown?: Approval[];
39
+ /** Posts to make again on purpose though that content already went out, each named by the posted record's `at`. */
40
+ repost?: Approval[];
41
+ /**
42
+ * Unknown outcomes a person checked and found **live**, each named by the `at` the plan showed: they are recorded as
43
+ * posted (nothing is sent for them) and their account is no longer blocked.
44
+ */
45
+ markPosted?: Approval[];
46
+ }
47
+ /** An approval for one specific record: the platform and the `at` the plan showed for that record. */
48
+ export interface Approval {
49
+ platform: SocialTarget;
50
+ at: string;
51
+ }
52
+ export interface PlannedPost {
53
+ platform: SocialTarget;
54
+ /** What would be called, e.g. "threads carousel (3 images)". */
55
+ action: string;
56
+ text?: string;
57
+ media?: string[];
58
+ /** Why this target cannot be posted. Any problem in any target blocks the whole publish. */
59
+ problems: string[];
60
+ /** What an earlier call recorded for this exact post, if anything. */
61
+ record?: PostRecord;
62
+ /** An unresolved send to this account (its `at` is what resendUnknown must name). */
63
+ pending?: PendingRecord;
64
+ }
65
+ export interface PublishPlan {
66
+ ok: boolean;
67
+ posts: PlannedPost[];
68
+ }
69
+ export type PublishOutcome = {
70
+ platform: SocialTarget;
71
+ status: 'posted';
72
+ id?: string;
73
+ url?: string;
74
+ warning?: string;
75
+ } | {
76
+ platform: SocialTarget;
77
+ status: 'already_posted';
78
+ id?: string;
79
+ url?: string;
80
+ at: string;
81
+ } | {
82
+ platform: SocialTarget;
83
+ status: 'unknown_outcome';
84
+ error?: string;
85
+ at: string;
86
+ } | {
87
+ platform: SocialTarget;
88
+ status: 'failed';
89
+ error: string;
90
+ };
91
+ /**
92
+ * The identity of one post: exactly what one platform would receive (the account, text, media, and options). Null
93
+ * when a Meta target's account cannot be resolved (not connected): its identity is unknown, and the plan blocks it.
94
+ */
95
+ export declare function targetKey(platform: SocialTarget, input: SocialPublishInput,
96
+ /** The video file's identity, captured once per call so the key and the upload check describe the same file. */
97
+ videoFile?: {
98
+ size: number;
99
+ mtimeMs: number;
100
+ } | {
101
+ missing: true;
102
+ } | null): string | null;
103
+ /**
104
+ * The account a target posts to: the resolved Page/user (Meta), the channel (YouTube), the TikTok account the plan
105
+ * belongs to. Null when it cannot be resolved; the plan blocks such a target.
106
+ */
107
+ export declare function accountKey(platform: SocialTarget, input: SocialPublishInput): string | null;
108
+ type Decision = {
109
+ kind: 'send';
110
+ note?: string;
111
+ } | {
112
+ kind: 'skip';
113
+ outcome: PublishOutcome;
114
+ } | {
115
+ kind: 'block';
116
+ problem: string;
117
+ };
118
+ interface DecideOptions {
119
+ resendUnknown: readonly Approval[];
120
+ repost: readonly Approval[];
121
+ markPosted: readonly Approval[];
122
+ }
123
+ /** The single rule — the table at the top of this file. Same answer in the plan, under the lock, and before each send. */
124
+ export declare function decide(platform: SocialTarget, record: PostRecord | null, pending: PendingRecord | null, { resendUnknown, repost }: DecideOptions,
125
+ /** This post's key: a marker naming it on a `posted` record is a repost of it, which resendUnknown may resend. */
126
+ key?: string): Decision;
127
+ /** No network: config files, the TikTok plan file, and the post and account records are all local. */
128
+ export declare function planPublish(input: SocialPublishInput): PublishPlan;
129
+ export interface MarkOutcome {
130
+ platform: SocialTarget;
131
+ /** The pending `at` recorded as posted; absent when nothing on the account matched. */
132
+ marked?: string;
133
+ error?: string;
134
+ }
135
+ /**
136
+ * markPosted for a plan that is blocked (nothing will be sent): record the approved pending sends of each target's
137
+ * account anyway. A person confirmed they are live, and that does not depend on the content still being postable —
138
+ * e.g. the rendered video was moved after an upload whose outcome was unknown, which would otherwise leave the
139
+ * channel blocked for good.
140
+ */
141
+ export declare function recordMarksOnly(input: SocialPublishInput): MarkOutcome[];
142
+ /**
143
+ * Publish to every target in order. Call only with an approved plan whose `ok` is true.
144
+ * 1. Lock every account that a post will be sent to (posts that are only skipped need no lock), then re-apply
145
+ * decide() to the records under the locks.
146
+ * 2. Preflight every post that will be sent; if one fails, nothing is sent.
147
+ * 3. Before each publishing call, confirm the lock is still ours and decide() once more (a long earlier upload, or
148
+ * a suspend, may have let another call in); mark the account pending; send; record the outcome.
149
+ */
150
+ export declare function executePublish(input: SocialPublishInput, plan: PublishPlan): Promise<PublishOutcome[]>;
151
+ export {};