# LumiPath Public API — Full Reference for Coding Agents > This is the single consolidated prose reference for the LumiPath public API. > The machine-readable contract (request/response shapes, every parameter) is > the generated OpenAPI 3.1 spec at **GET https://app.lumipath.cn/api/v1/openapi.json**. > When this prose and the spec disagree on a *shape*, the spec wins. This file > is authoritative for *behavior and mental model*. LumiPath is a multi-platform social-content tool (publish, localize/dub, moderate comments, read analytics, automate posting) for TikTok, YouTube, Instagram, Facebook, Threads, X, and Reddit. This document describes the public HTTP API for programmatic/agent use over plain HTTP (NOT MCP). --- ## 1. Quickstart / mental model **Host.** Base URL is `https://app.lumipath.cn`. Every endpoint lives under `/api/v1/`. **Auth — Bearer key.** Send your per-user API key as a Bearer token on every request: ``` Authorization: Bearer lumi_xxxxxxxx ``` Keys are generated in the dashboard at **Settings → API Keys** (`/dashboard/api-keys`) and start with `lumi_`. Browser callers may use a NextAuth session cookie instead. (The `X-Api-Key` header is a *separate* internal service-token mechanism — it is NOT for per-user keys.) There is no role requirement; every call is scoped to the key's owner. **The connectionId model.** A `connectionId` is the MongoDB ObjectId (24-char hex) of a linked social account. **The platform is inferred** from the `connectionId` — you never pass a `platform` parameter to a per-connection endpoint. List your connections first with `GET /api/v1/connections` and use the returned ids as `connectionId` everywhere. A foreign or non-existent id returns `404` and does not reveal whether it exists (IDOR-safe). An id that is not a valid 24-char hex ObjectId returns `VALIDATION_FAILED` (400) without a DB hit. **Two response envelopes — be honest, there are BOTH.** This is the single most important fact for parsing responses: 1. **Wrapped — `{ "success": true, "data": }`.** Used by the comments, insights, posts, connections, and the read/list content routes (`/videos` GET, `/localization` GET, `/tts`) plus `POST /videos`. 2. **Bare object — NO `{success,data}` wrapper.** Used by: - all **automation** routes (`{ isDemo, list, pagination, … }`, `{ task }`, raw strategy/draft docs, `{ status: "paused" }`, `{ deleted: true }`, `{ draftId, status }`, …), - `POST /videos/upload` → `{ url, vid, mediaType }`, - `POST /localization` → `{ ok: true }`, - `POST /repurpose` → `{ success: true, localProjectId, data }` (note: this has a `success` key but is FLAT — it is NOT the `{success,data}` envelope), - `POST /social-posts` → `{ success: true, results }` (also flat). Do not assume a universal envelope. The OpenAPI spec documents each route's actual wire shape; check the response schema per operation. **Errors — branch on the machine code, not the message.** Non-2xx responses are ```json { "error": "MACHINE_CODE", "message": "english, for debugging only", "field": "..." } ``` Routes may attach extra context keys (`platform`, `resetsAt`, `details`, `runningCount`, `upgradeUrl`, `used`, `limit`, …). Branch on the `error` machine code + HTTP status, never on `message`. ### Machine-code error table | Code | Typical HTTP | Meaning | Retryable? | |------|------|---------|-----------| | `VALIDATION_FAILED` | 400 | Bad/missing input (see `field`) | No | | `INVALID_SOURCE_URL` / `INVALID_URL` / `INVALID_VIDEO_URL` | 400 | URL rejected | No (fix the URL) | | `UNSUPPORTED_PLATFORM` | 400 | Connection's platform not supported here | No | | `UNSUPPORTED_SOURCE` | 400 | Source host not supported | No | | `INVALID_CRON` | 400 | Schedule expression invalid | No | | `UNAUTHORIZED` / `Unauthorized` | 401 | Missing/invalid key or session | No (fix auth) | | `ACCOUNT_UNLINKED` | 401 | Connection has no token | No (re-link) | | `TOKEN_EXPIRED` | 401 | Token present but rejected upstream | **Yes, after re-auth** | | `AUTH_EXPIRES_BEFORE_SCHEDULE` | 400 | Scheduled post: the connection's token can't be renewed past `scheduleAt` (see `platform`, `connectionId`) | No (re-authorize or schedule earlier) | | `UPGRADE_REQUIRED` / `QUOTA_EXCEEDED` | 402 | VIP/plan/quota gate (see `upgradeUrl`) | No (upgrade) | | `FORBIDDEN` / `FEATURE_DISABLED` | 403 | Not allowed / feature off | No | | `ACCOUNT_NOT_OWNED` | 403 | Named account belongs to another user | No | | `NOT_FOUND` / `ACCOUNT_NOT_FOUND` | 404 | Not found (also foreign ids) | No | | `STRATEGY_EXISTS` | 409 | A strategy already exists on this account | Retry with `replace:true` | | `STRATEGY_OWNED_BY_OTHER` | 409 | Strategy owned by another user | No | | `HAS_RUNNING_TASKS` | 409 | Can't delete; tasks in-flight (`runningCount`) | Retry later | | `NOT_READY` / `ALREADY_DISCARDED` | 4xx | Draft lifecycle state | No | | `RATE_LIMITED` | 429 | Too many requests (see `Retry-After`, `resetsAt`) | **Yes, after wait** | | `UPSTREAM_ERROR` | 502 | Platform API failed after a successful auth | **Yes** (transient) | | `INTERNAL_ERROR` | 500 | Server error | Maybe (transient) | ### Rate limits & retry rules - **Retryable:** `UPSTREAM_ERROR` (502, transient platform failure), `TOKEN_EXPIRED` (401, after the user re-authorizes the connection), and `RATE_LIMITED` (429, after the `Retry-After` / `resetsAt` window). Treat 5xx as possibly-transient with backoff. - **NOT retryable:** any 4xx validation error (`VALIDATION_FAILED`, `UNSUPPORTED_*`, `INVALID_*`), `402` upgrade/quota gates, `403`, and `404`. - Specific limits: strategy create is 10/hour/user; AI-strategy draft create is 10/day AND 5/hour/user (the tightest window is reported in `X-RateLimit-*` headers and `resetsAt`). Honor `Retry-After` when present. - Platform read/reply endpoints (`posts`, `posts/{postId}`, `insights`, `insights/post`, `connections/{id}`, `comments`, `comments/reply`) are limited to **120 requests/minute/user** and **20 requests/minute per connection** (`comments/reply`: 30/minute). List results are server-cached for ~1 minute, so polling one connection more often than that returns identical data. - **Request/response only — no webhooks.** Poll where you need freshness. **Supported platforms for comments:** TikTok, YouTube, Instagram, Facebook, Threads, X, LinkedIn (company pages only) — Pinterest and Reddit return `UNSUPPORTED_PLATFORM`. **For insights:** TikTok, YouTube, Instagram, Facebook, Threads, and Pinterest; X (Twitter), Reddit, and LinkedIn return `UNSUPPORTED_PLATFORM` there. **Posts & profile (`/posts`, `/connections/{id}`)** cover 8 platforms: TikTok, YouTube, Instagram, Facebook, Threads, X, Reddit, and Pinterest. A Pinterest connection represents one Board, so `/posts` is scoped to owned Pins on that Board and detail reads reject Pins belonging to another Board. `/posts`, `/posts/{postId}` and `/connections/{id}` also cover LinkedIn company pages (profile: `followers` and `bio` = page description; `following`/`postsCount` null). **Normalized-null convention.** On the normalized shapes (`PostSummary`, `PostDetail`, `PostInsight`, `Profile`, `PostStats`) every documented field is ALWAYS present; a metric a platform doesn't supply is `null` — never `0` or `""`. So you can tell "zero" from "unsupported". The one exception: `PostDetail.mediaUrls` is `[]` (empty array) when none resolvable, never `null`. --- ## 2. Endpoints (grouped by tag) All paths below are relative to `https://app.lumipath.cn`. Full parameter and shape detail is in the OpenAPI spec; this section is the behavioral prose. ### meta - `GET /api/v1/openapi.json` — the generated OpenAPI 3.1 contract. **No auth required** (it is the discovery document; it carries zero user data). `Cache-Control: public, max-age=3600`. ### comments *(wrapped envelope)* - `GET /api/v1/comments` — Comment inbox for a connection, aggregated across its posts. Query: `connectionId` (required), `videoId?` (filter to one post; Threads = media id), `page` (default 1), `limit` (1–100, default 10). `data: { comments: BaseComment[], pagination: CommentsPagination }`. `BaseComment.replies` is a self-recursive array of `BaseComment`. A present-but-garbage `page` 400s; a missing one defaults; `limit>100` clamps. **Pagination semantics.** With `videoId` set (single-post), the server cursor-pages the platform live until your requested `page × limit` slice is satisfied, so deeper pages return new comments (walk depth capped at ~500 comments per request). `pagination.totalPages` is a **has-more signal, not an exact count**: `totalPages = page + 1` means at least one more page exists; once `totalPages` equals the current `page` you have reached the end. `total` is the size of the window gathered so far, not a platform-wide comment count. Without `videoId` (account-wide inbox), aggregation covers a bounded window of recent posts (posts published through LumiPath; on TikTok, the account's recent native posts) — a working inbox, not a full historical archive. **X.** Account-wide (no `videoId`) returns replies to the account from its mention timeline. Pass `sinceId` = the previous response's `data.newestId` to get only newer replies (X bills per post and per user returned, so polling without it re-buys the whole window); with no `sinceId`, `startTime` (ISO 8601, default 7 days ago) bounds it. `newestId` is always present for X (null when nothing came back). If `data.hasMore` is true, fetch the older rest with `untilId = data.oldestId` and the same `sinceId` before advancing your cursor to `newestId`. If the connection has not published an X video through LumiPath in the last 7 days, the account-wide X inbox returns no comments without calling X and sets `data.skipped = "NO_RECENT_X_VIDEO"`. With `videoId` (a tweet id), only that conversation's replies from the last 7 days are searched. - `POST /api/v1/comments/reply` — Reply to a comment. Body: `{ connectionId, commentId, text, videoId? }`. `videoId` is **required for TikTok**, ignored elsewhere. `text` must be non-empty after trimming. `data: { id, platform }`. ### connections *(wrapped envelope)* - `GET /api/v1/connections` — List the caller's linked social accounts. Query: `platform?` (optional, lowercased filter — unknown platform yields an empty list, no error). `data: ConnectionListItem[]` — the lean list item `{ connectionId, platform, username, displayName, avatarUrl, status, createdAt, profileUrl, reauthBy, renewsOnUse }`. `profileUrl` is the account's public homepage URL, built by string concatenation (no upstream call); `null` when it can't be derived (unknown platform or missing username/page id). `status: "expired"` means the token is already dead and the user must re-authorize. `reauthBy` (ISO 8601 or `null`) is the latest time the connection must be re-authorized by; `null` when unknown or it never expires. `renewsOnUse: true` (Instagram, Threads) means the token is renewed every time it is used, so `reauthBy` keeps moving forward and is not a hard deadline. - `GET /api/v1/connections/{id}` — Connection profile, richer than the list item. `data: Profile`. Reddit's `followers`/`following`/`postsCount` are always `null` (karma is not substituted). Pinterest returns the owning account's username, business name, avatar, follower/following counts, and Pin count; multiple Board connections for one login therefore share a profile. ### insights *(wrapped envelope)* - `GET /api/v1/insights` — Account-level insights (followers/views/likes totals). Query: `connectionId`. `data` is **free-form per platform** (keys vary by platform; documented as a permissive object). Covers TikTok, YouTube, Instagram, Facebook, Threads, and Pinterest. Pinterest includes profile counts plus a rolling 30-day organic summary: impressions, engagements, saves, Pin clicks, and outbound clicks. Facebook returns `page{...}` (id, name, fans, followers, pictureUrl) plus `insights{...}` — a rolling **28-day** Page Insights block: `pageViews`, `pageFollows`, `pagePostEngagements`, `pageVideoViews`. Each is `null` when the Page has no data for that window or the metric is unavailable on the token — `null` means unavailable, `0` means a real zero. - `GET /api/v1/insights/post` — Per-post insights, normalized across the 6 platforms above. Query: `connectionId`, `postId` (native id). `data: PostInsight` with explicit nulls for unsupported metrics. Pinterest maps lifetime impressions to `views`, plus lifetime comments and saves. Facebook fields depend on the id shape, because Graph exposes different metrics per node: `/api/v1/posts` lists Facebook from the Page's video edge, so the `postId` it returns is a **video id** → `views` (Reels plays), `reach` (unique impressions), `likes`, `comments`; `shares` is `null` (not a field on a video node). A **Page post id** (`_`) instead returns `views` (3s+ video views), `likes`, `comments`, `shares`, and `reach` `null`. `saves` is always `null`. ### posts *(wrapped envelope)* - `GET /api/v1/posts` — List a connection's natively-published posts (all 8 platforms). Query: `connectionId` (required), `page` (default 1, advisory), `limit` (1–50, default 20), `cursor?` (opaque, from a prior `pagination.nextCursor`). `data: { posts: PostSummary[], pagination: Pagination }`. **page/limit are fully lenient** — garbage coerces to the default, never 400s. Paginate by echoing `pagination.nextCursor` back as `?cursor=` (forward-only; the cursor is platform-guarded — never reuse one connection's cursor on another). Pinterest connections are Board-scoped: only owned Pins on that Board are returned, and the native `bookmark` is wrapped in the opaque cursor. Facebook: `postId` is a bare VIDEO id. `pagePostId` (Facebook only, nullable) is the Page post behind it as `_` — use that, never `_`, for Meta Ads `object_story_id`. LinkedIn (company pages): `postId` is the post URN (`urn:li:share:…` / `urn:li:ugcPost:…`; URL-encode it in the detail path). Only PUBLISHED posts are listed. `stats` are lifetime organic counts (`views` = impressions) and are `null` when the page role can't read statistics (content administrator). `thumbnailUrl` is always `null`. LinkedIn's daily API quota is small — poll a LinkedIn connection's `/posts` no more than every few hours. - `GET /api/v1/posts/{postId}` — Single post detail. Path: `postId` (native id). Query: `connectionId`. `data: PostDetail` = `PostSummary` + `{ description, mediaUrls: string[], durationSec, visibility }`. Unknown `postId` → `NOT_FOUND`. `visibility` is effectively YouTube-only; `durationSec` is null for non-video. Pinterest also returns `NOT_FOUND` when the Pin belongs to a different Board. ### content *(mixed envelopes — read carefully)* - `GET /api/v1/videos` *(wrapped)* — List your uploaded videos. Query: `page`, `limit` (1–50, default 10), `search?`. `data: { videos: VideoListItem[], pagination: OffsetPagination }`. page/limit fully lenient. Image assets uploaded through `/videos/upload` are excluded. - `POST /api/v1/videos` *(wrapped)* — Register a video by remote URL. Body: `{ url (required), filename?, title? }`. SSRF-guarded; size is probed from the host. `data: VideoDoc` (the created video). - `POST /api/v1/videos/upload` *(BARE → `{ url, vid, mediaType }`)* — Upload a video, image, or document. Two request bodies: `application/json { url, filename?, title? }` OR `multipart/form-data { file, filename?, title? }`. Supported video extensions: `.mp4`, `.avi`, `.mov`, `.mkv`, `.webm`, `.flv`, `.wmv`; supported image extensions: `.jpg`, `.jpeg`, `.png`, `.webp`. Images are capped at 8 MB, byte-sniffed, stored under the OSS `images/` prefix, and saved in `media_assets`; videos stay under OSS `videos/` and the `videos` collection. Supported document extensions: `.pdf`, `.docx`, `.md`, `.markdown` (`mediaType: "document"`). Documents are capped at 100 MB, byte-checked (PDF `%PDF-` header; DOCX a Word ZIP package; Markdown UTF-8 text — `text/plain` is accepted for `.md`), stored per format under OSS `documents/pdf/`, `documents/docx/`, `documents/markdown/`, saved in `media_assets`, and do not count toward the daily video upload quota. The returned PDF `url` is on the allow-listed host (`*.aliyuncs.com`), so it can go straight into `social-posts` `contentType: "DOCUMENT"` (LinkedIn) `mediaUrls`. (The internal service-token caller passes the user via an `x-user-id` header; key/session callers don't.) - `GET /api/v1/localization` *(wrapped)* — List localization tasks. Query: `page`, `limit` (1–50, default 10), `vid?`, `taskId?`, `status?`. `data: { tasks: LocalizationTask[], pagination: OffsetPagination }`. page/limit lenient; a malformed `taskId` 400s. - `POST /api/v1/localization` *(BARE → `{ ok: true }`)* — Create a localization task for an existing draft Project. Body: `{ localProjectId (required), aiConfig (required, free-form object), durationSeconds? }`. - `GET /api/v1/tts` *(wrapped)* — List available TTS voices. `data` is an opaque platform voice-list payload (permissive object). - `POST /api/v1/repurpose` *(BARE → flat `{ success, localProjectId, data }`)* — Localize / dub / repurpose a source video end to end. Body: `{ sourceUrl, sourceLang, targetLang }` (the three required), plus optional `dubbing`, `dubbingVoiceId`, `backgroundMusic` (0|1|2), `subtitle`, `subtitleStyle`, `ocr`, `copyright`, `autoPublish` (free-form), `title`, `translateTitle`, `durationSeconds`. At least one of `dubbing` / `subtitle` / `ocr` must be set. ### publishing *(bare)* - `POST /api/v1/social-posts` — All-in-one publish: one **video** OR one **image post (图文)** OR one **LinkedIn PDF document post** in a single request. VIDEO → TikTok, YouTube, Instagram, Threads, X, Pinterest, LinkedIn, and/or Facebook. IMAGE → Instagram, Threads, TikTok, X, Pinterest, LinkedIn, and/or Facebook (YouTube does not support image posts here and is rejected; Pinterest supports one image per Pin; LinkedIn publishes to a linked company page only; Facebook publishes to a linked Page). DOCUMENT → LinkedIn only (one PDF, published as a swipeable document/carousel post). Pinterest requires `pinterestConnectionIds` (each connection is bound to a single board server-side — see §3); optional `pinterestConfigs[]` with `{ connectionId, description? }`. User API keys are supported for user-owned Pinterest connections, while service-token callers are rejected. See §3 for the full body schema and per-platform behavior. Returns `{ success: true, results }` (bare, flat — not the `{success,data}` envelope), with a per-account result array per platform. HTTP 200 even when individual accounts fail — check each entry's `status`. Every result item also carries a `jobId` (additive; the existing `publishId`/`mediaId` fields and their semantics are unchanged) — pass those to `POST /api/v1/social-posts/status` to query the final outcome. Pass `scheduleAt` (ISO 8601 **with** a timezone offset; 1 min–365 days out) to schedule instead of publishing now — the response becomes `{ success: true, scheduled: true, scheduleJobId, scheduledAt }` (no `results`) and a background worker fires it at that time. Send an optional `Idempotency-Key` header (1–200 chars of `[A-Za-z0-9:_.-]`, scoped to your user, kept 7 days) to make a retry safe: re-sending the same body with the same key returns the first request's stored response (header `Idempotent-Replayed: true`, same `jobId`s) instead of publishing again. If the first request is still running, or ended in a 5xx, the retry gets `409 IDEMPOTENCY_IN_PROGRESS` (outcome unknown — do not publish again with a new key without checking the account). Same key + different body → `422 IDEMPOTENCY_KEY_REUSED`. - `POST /api/v1/social-posts/status` — Query publish status by `jobId`. Body `{ jobIds: string[] }` (0..100 ids; `[]` → `{ results: {} }`). Auth: session, user API key, or service token (service-token callers pass the `x-user-id` header, same as publish). Returns `{ results }` grouped by platform, each item `{ connectionId?, jobId, status, postId?, postUrl?, error?, errorCode?, stage? }` with `status` ∈ `success | processing | failed | not_found`. TikTok jobs are live-polled against the platform; every other platform reports the state its background publish last wrote. `stage` is how far a background publish got — `preparing` (nothing sent to the platform), `uploading` (media upload / container; no post exists yet) or `creating` (the create call was sent — the post MAY exist even if the job failed; check the account before republishing). A background publish that makes no progress within its platform's budget (30–60 min) is failed by a server-side watchdog with `errorCode: "PUBLISH_STALLED"`; a platform call that exceeds its time limit fails with `errorCode: "PUBLISH_TIMEOUT"`. Instagram / Facebook / X never stay `processing` indefinitely; X-IMAGE / Pinterest-IMAGE / LinkedIn-IMAGE / Facebook-IMAGE are terminal from publish time. Unknown / foreign / malformed ids resolve to `not_found` under an `UNKNOWN` group (a foreign jobId is indistinguishable from a never-existed one — no cross-tenant leak). Always HTTP 200 for a well-formed body; one bad id never fails the batch. Over 100 ids → 400. - `POST /api/v1/social-posts/schedule/status` — Status of scheduled posts (from `scheduleAt` on `/social-posts`). Body `{ scheduleJobIds?: string[] }` (max 100): pass the `scheduleJobId`s from the schedule response to resolve specific posts, or omit them to list all your pending scheduled posts. Auth: session, user API key, or service token (`x-user-id`). Returns `{ items }`, each `{ scheduleJobId, status, scheduledAt?, platforms?, contentType?, publishJobIds?, error? }` with `status` ∈ `scheduled | firing | fired | failed | not_found`. A fire that comes more than 2 h after `scheduledAt` (e.g. after a queue outage) is skipped: `status: "failed"` with an `error` starting `SCHEDULE_MISSED:` — nothing was published. Once `fired`, `publishJobIds` carries the per-account publish jobIds — feed those to `POST /api/v1/social-posts/status` for the final post URLs. Foreign / unknown ids resolve to `not_found` (no cross-tenant leak). - `POST /api/v1/social-posts/schedule/cancel` — Cancel a pending scheduled post. Body `{ scheduleJobId }`. Owner-scoped: a foreign / unknown / already-fired id → 404; a post that is mid-fire → 409. Returns `{ success: true, cancelled: true }`. ### automation *(all bare)* Schedule and manage automated posting strategies and their tasks. All routes are caller-scoped to the key's owner. Free-tier users receive demo data on the list endpoints (`isDemo: true`). - `GET /api/v1/automation/strategies` — List strategies. `{ isDemo, list: StrategyDoc[], pagination, quota, upgradeUrl? }`. - `POST /api/v1/automation/strategies` — Create / upsert a strategy (VIP-gated; 10/hour). The body is the strict strategy payload; set `replace: true` to overwrite an existing strategy on the same account (otherwise a second create returns `STRATEGY_EXISTS` 409). Returns `{ strategy_id, _id, created, upsert: true }`. - `GET | PATCH | DELETE /api/v1/automation/strategies/{id}` — Read / edit (VIP-gated; immutable keys stripped) / delete (refuses while tasks are in-flight → `HAS_RUNNING_TASKS`). GET/PATCH return the raw `StrategyDoc`; DELETE returns `{ deleted: true }`. - `POST /api/v1/automation/strategies/{id}/execute` — Run now → `{ queued: true, strategy_id, upstream }`. `.../pause` → `{ status: "paused" }`; `.../resume` → `{ status: "active" }`. - `GET /api/v1/automation/tasks` — List tasks. Query: `strategy_id?`, `username?`, `platform?`, `step?`, `status?`, `from?`, `to?`, `page`, `limit` (1–100, default 20). `{ isDemo, list: TaskDoc[], pagination }`. - `POST /api/v1/automation/tasks/{id}/confirm | retry | reprocess | cancel | title-description` — Task lifecycle actions → `{ task: TaskDoc }`. `reprocess` and `title-description` take a strict body (unknown keys rejected). - `GET /api/v1/automation/quota` — Current automation quota usage: `{ plan, maxActiveStrategies, currentActive, maxConcurrentTasks, currentRunning, rateLimit }`. - `GET /api/v1/automation/dispatch-failures` — Today's strategy dispatch failures: `{ items, total, active_total, dispatched_total, date }`. - `POST /api/v1/automation/ai-strategy/drafts` — Create an AI-generated strategy draft (rate-limited 10/day and 5/hour per user; `X-RateLimit-*` headers). Idempotent on a 5-minute replay. → `{ draftId, status, idempotent }`. - `GET /api/v1/automation/ai-strategy/drafts/{draftId}` — Read a draft (`Cache-Control: no-store`). `.../regenerate` → `{ draftId, status: "drafting" }`; `.../discard` → `{ ok: true }`. ### meta-ads *(wrapped envelope)* - `GET /api/v1/meta/ads-token` — Facebook token (personal or system-user), for a Lumi/agent instance to inject into a Meta Ads MCP. No query params; scoped to the caller's own LumiPath account. Persisted from the dedicated ads entry (`POST`/`DELETE /api/link/facebook/ads`) — independent of whatever Facebook Pages the same LumiPath user has linked from the social page. This is distinct from the per-Page tokens behind `/social-posts`/`/comments` — those are scoped to posting/moderating on a Page, this one carries whatever user-/business-level permissions were granted at OAuth time (e.g. `ads_management`/`ads_read`). Returns `{ accessToken, expiresAt, scopes, tokenType, userId, userName, businessId }`: `expiresAt` is ISO 8601 or `null` if the token never expires; `scopes` is the actual granted-scope list from Facebook's `/debug_token`. `tokenType` distinguishes the two shapes: - `"user"` — a personal long-lived token. **Current default** (2026-08-23 product decision: ads reverted to a personal token; the `"system_user"` row below is kept behind an env switch, not deleted). `userId`/`userName` are the Facebook user's id/display name (NOT the LumiPath user); `businessId` is `null`. - `"system_user"` — a BISU (Business Integration System User) token, kept behind the env switch, not currently the default. `businessId` (the Business Portfolio's `client_business_id`) is set; `userId`/`userName` are `null` (BISU has no user identity). Defaults to never expiring. Errors: `404 META_ADS_NOT_CONNECTED` if ads was never authorized in LumiPath, or was authorized without ads permissions granted (message distinguishes the two cases); `401 TOKEN_EXPIRED` if the previously-stored token has since expired. Either error means: re-authorize from LumiPath's 广告 (ads) page. **Meta dashboard prerequisite:** the Meta App's Facebook Login for Business configuration used by the ads entry's `config_id` must have `ads_management` / `ads_read` / `business_management` enabled (and, only when the system-user switch is on, `response_type=code` — BISU only supports the code flow), or the token Facebook issues will not carry ads scope even after a successful OAuth round-trip. ### tiktok-ads *(wrapped envelope)* Two TikTok ads tokens for two different transports. They are **not** interchangeable — the MCP token below is scoped to TikTok's Ads MCP server, and calling `https://business-api.tiktok.com/open_api/v1.3/...` with it comes back `code: 40105` ("Access token is incorrect or has been revoked"). A user may have authorized either, both, or neither; each returns its own 404 code. - `GET /api/v1/tiktok/ads-token` — TikTok **Ads MCP** access token (scope `mcp:tt4b`), for a Lumi/agent instance to connect TikTok's official Ads MCP server. No query params; scoped to the caller's own LumiPath account. Persisted from the dedicated TikTok ads entry (`POST`/`DELETE /api/link/tiktok/mcp`), which registers a public OAuth client via Dynamic Client Registration and runs a PKCE authorization-code flow. Returns `{ accessToken, expiresAt, scope, serverUrl }`: `expiresAt` is ISO 8601 or `null` if it never expires; `serverUrl` is the MCP server the token is bound to (RFC 8707 resource indicator). Unlike Meta's, this token has a refresh token — the route refreshes it server-side when it is expired or within 5 minutes of expiring, and only fails if the refresh itself fails. Errors: `404 TIKTOK_MCP_NOT_CONNECTED` if TikTok Ads MCP was never authorized in LumiPath, or was disconnected; `401 TOKEN_EXPIRED` if the stored token expired and could not be refreshed. Either means: re-authorize from LumiPath's 广告 (ads) page. - `GET /api/v1/tiktok/marketing-token` — TikTok **Marketing API** (Business API) access token, for a Lumi/agent instance to call `https://business-api.tiktok.com/open_api/v1.3/...` directly. Send it as the `Access-Token` request header (not as a bearer token, not as a query param). No query params; scoped to the caller's own LumiPath account. Persisted from the TikTok Marketing entry (`POST`/`DELETE /api/link/tiktok/marketing`), which runs the TikTok for Business authorization-code flow against a developer app holding Marketing API scopes (ad account information, campaign/ad group/ad, ad insight report). Returns `{ accessToken, advertiserIds, scope, authorizedAt, appId }`: - `advertiserIds` — string ids of the ad accounts (advertisers) the user granted on TikTok's authorization page. Possibly `[]` if none were picked; never `null`. - `scope` — TikTok's numeric permission list, passed through as-is (TikTok identifies permissions by number, not by name). - `authorizedAt` — when the user last completed the authorization, ISO 8601 or `null`. - `appId` — the TikTok for Business developer app that issued the token. The token is long-lived: **no refresh token, no expiry.** It stays valid until the user revokes it in TikTok Business Center or re-authorizes, so this route never returns `TOKEN_EXPIRED` — a revoked token only surfaces as `code: 40105` from TikTok itself when you call the Business API. Errors: `404 TIKTOK_MARKETING_NOT_CONNECTED` if it was never authorized in LumiPath, or was disconnected — re-authorize from LumiPath's 广告 (ads) page. **Deployment prerequisite:** this flow reuses the same TikTok for Business developer app as content publishing (`TIKTOK_CLIENT_KEY`/`TIKTOK_CLIENT_SECRET` — that key is the Business app's numeric `app_id`), so no new secrets are needed; `TIKTOK_MARKETING_APP_ID`/`TIKTOK_MARKETING_APP_SECRET` exist only as an optional override pair for deployments that split the two apps. It does, however, need its **own** redirect URI registered: `https://app.lumipath.cn/api/link/tiktok/marketing/callback`, filled into the Marketing API product's **Advertiser redirect URL** field in the TikTok developer console. Marketing API 的广告主授权回调在开发者后台是单独一栏 (Advertiser redirect URL),和社媒登录不共用 —— 2026-09-23 实测共用被 TikTok 拒。That callback accepts only its own flow: an `auth_code` without the Marketing CSRF state cookie, or with a mismatched `state`, is rejected without any token exchange. Once the URL is registered, the only remaining step is authorizing once from LumiPath's 广告 (ads) page. With neither credential pair present the connect entry answers `503 TIKTOK_MARKETING_NOT_CONFIGURED` and no authorization can be started. ### ads-link-sessions *(wrapped envelope)* Lets a Lumi workspace run the Facebook / TikTok **ads** authorization in a popup, without sending the user to LumiPath's 广告 (ads) page and without relying on whoever is logged in to LumiPath in that browser. - `POST /api/v1/ads/link-sessions` — user API key only. Body `{ platform: "meta" | "tiktok", openerOrigin }`. `openerOrigin` is the workspace page's origin (`scheme://host[:port]`, no path); it must match the allowlist in `ADS_LINK_OPENER_ORIGINS` (comma-separated; `https://*.x.y` matches exactly one subdomain label; default `https://*.agent.lumipath.cn`), otherwise `400 VALIDATION_FAILED`. Same beta gate as the ads page (`meta-ads-login`, judged by the API key's user): `403 FORBIDDEN` otherwise. Rate limit 10 per minute per user (`429 RATE_LIMITED`). Returns `{ linkId, url, expiresAt }`. `url` is valid for 10 minutes and can be opened once; only its hash is stored. Opening it goes straight to the provider's authorization page, and the resulting token is stored for **the API key's user** — the same row `GET /api/v1/meta/ads-token` / `GET /api/v1/tiktok/ads-token` read. The link must be opened from a page on `openerOrigin` (open a popup, then set its `location` from that page): the open checks that the `Referer` origin equals `openerOrigin`. A forwarded link, a pasted link or a link-preview fetch has no matching `Referer` and is refused **without consuming the link**. So the workspace page must not send `Referrer-Policy: no-referrer`, and the link must not be opened through `rel="noreferrer"`. When the flow ends, the popup page calls `window.opener.postMessage({ type: "lumipath:ads-link", linkId, platform, ok, error }, openerOrigin)` and closes itself on success. The message never carries a token. - `GET /api/v1/ads/link-sessions/{linkId}` — user API key only; only links issued to the same user (`404 NOT_FOUND` otherwise). Returns `{ status, error, platform }`: `status` is `pending` (not opened yet), `opened` (on the provider's page), `completed` or `failed`; `error` is `denied`, `expired`, `exchange_failed`, `no_business`, `csrf_failed`, `missing_code` or `null`. A link past its expiry that never finished reports `failed` / `expired`. Poll this as well as listening for the message: after the popup visits facebook.com / tiktok.com the browser may drop `window.opener`, and then the message cannot be delivered. --- ## 3. Publishing behavior (`POST /api/v1/social-posts`) **Body.** Required: `platforms` (array of `"TIKTOK" | "YOUTUBE" | "INSTAGRAM" | "THREADS" | "X" | "PINTEREST" | "LINKEDIN" | "FACEBOOK"`), `contentType: "VIDEO" | "IMAGE" | "DOCUMENT"`, `text` (caption / title), `mediaUrls` (non-empty; max 35; each must be a URL). Per platform you supply either `*ConnectionIds` (24-char hex ObjectIds) OR `*AccountNames` (the account username/display name — resolved to ids server-side); a declared platform with neither returns 400. Optional per-account overrides: `tiktokConfigs[]` (`{ connectionId, title?, allowComments?, allowDuet?, allowStitch?, privacyLevel? }`), `youtubeConfigs[]` (`{ connectionId, title?, visibility? }`), `xConfigs[]` (`{ connectionId }`, reserved — no options in v1), and `pinterestConfigs[]` (`{ connectionId, description? }` — the target board is the selected Pinterest connection itself; there is no `boardId`). **`advanceConfig` (optional) — platform-native advanced settings.** A single top-level object keyed by platform (`youtube`, `tiktok`, `instagram`, `threads`, `x`, `pinterest`, `linkedin`, `facebook`); each is a **strict allow-list** (an unknown/misspelled key returns 400) that applies to **all targeted accounts of that platform** (unlike the per-account `*Configs[]` above). Every field is optional, and omitting `advanceConfig` reproduces the prior defaults exactly. - `youtube`: `categoryId` (defaults to `"22"` = People & Blogs), `tags[]`, `description` (else the title is reused), `defaultLanguage`, `defaultAudioLanguage`, `license` (`"youtube"|"creativeCommon"`), `embeddable`, `publicStatsViewable`, `madeForKids`, `publishAt` (ISO 8601; forces `private` until it fires), `playlistId` (best-effort add), `thumbnailUrl` (best-effort), `firstComment` (best-effort auto-comment). `location` (`{ latitude, longitude, description? }`) is **accepted but NOT persisted by YouTube** — the Data API no longer stores recording coordinates, so it is a no-op today. - `tiktok`: `isAigc`, `brandContentToggle`, `brandOrganicToggle`, `videoCoverTimestampMs` (cover frame offset, default 1000), `customThumbnailUrl` (must be an allow-listed host). - `instagram`: `locationId`, `userTags` (`[{ username, x?, y? }]`), `collaborators` (usernames), `shareToFeed` (Reels), `coverUrl` (Reels), `altText` (images). - `threads`: `replyControl` (`"everyone"|"accounts_you_follow"|"mentioned_only"`), `topicTag`, `altText`. - `x`: `replySettings` (`"following"|"mentionedUsers"|"subscribers"`), `quoteTweetId`, `forSuperFollowersOnly`, `geoPlaceId`. - `pinterest`: `link` (pin destination URL), `altText`, `boardSectionId`, `dominantColor` (hex), `note` (private). - `linkedin`: `visibility` (`"PUBLIC"|"LOGGED_IN"`, default PUBLIC), `feedDistribution` (`"MAIN_FEED"|"NONE"`), `lifecycleState` (only `"PUBLISHED"` — LinkedIn's API cannot create drafts; may be omitted), `videoTitle`, `altText`, `documentTitle` (DOCUMENT only, and **required** there — the title shown on the PDF document post). - `facebook`: `firstComment` (best-effort auto-comment on the video/photo), `coverUrl` (VIDEO only — custom cover, downloaded server-side, best-effort). - **VIDEO** — **only `mediaUrls[0]` is used**. Valid platforms: TikTok, YouTube, Instagram, Threads, X, Pinterest, LinkedIn (company page), Facebook (Page). - **IMAGE** (image post / 图文) — `mediaUrls` is **1..N image URLs** (JPEG/PNG/WebP); single-vs-carousel is decided by **count**, not a separate type. Valid platforms: Instagram, Threads, TikTok, X, Pinterest, LinkedIn, Facebook. **YouTube + IMAGE is rejected with 400.** Per-platform image-count ceilings (**X ≤ 4, Instagram ≤ 10, Threads ≤ 20, TikTok ≤ 35, Pinterest ≤ 1, LinkedIn ≤ 20, Facebook ≤ 10**) are enforced **per account**: exceeding one platform's limit fails only that platform (`status:"failed"` with a precise message) while the others still publish. `tiktokConfigs.title` is the TikTok Photo title (derived from `text`, ≤90 chars, if omitted). **URL reachability differs by platform:** for X, TikTok, and LinkedIn any URL the server can download works (TikTok images are re-hosted to a verified CDN first; LinkedIn media bytes are fetched server-side and must be on the allow-listed host); for Instagram, Threads, and Facebook the URL must be **publicly reachable by Meta's servers** (a private/presigned/internal URL fails for those only, as a per-account `failed`). - **DOCUMENT** (LinkedIn PDF document / carousel post) — **LinkedIn only**: `platforms` must be exactly `["LINKEDIN"]`, `mediaUrls` must be **exactly one PDF URL**, and `advanceConfig.linkedin.documentTitle` is required (any violation → 400 `VALIDATION_FAILED`). The PDF is fetched server-side, so its host must be on the allow-list (`*.lumipath.cn` or `*.aliyuncs.com`; other hosts → 400) — upload a local PDF with `POST /api/v1/videos/upload` first and use the returned `url`. LinkedIn limits: **≤ 100 MB, ≤ 300 pages**. Returns `status:"processing"`; the server downloads the PDF, uploads it via LinkedIn's Documents API, waits for LinkedIn to finish processing it, then creates the post — poll `jobId` on `POST /social-posts/status` for the post URN / URL. A file that is not a PDF, is over 100 MB, or that LinkedIn fails to process (e.g. > 300 pages) ends as `failed` with a precise `error`. `text` is the post commentary; `visibility` / `feedDistribution` / `lifecycleState` apply as for other LinkedIn posts. Example: `{ "platforms": ["LINKEDIN"], "contentType": "DOCUMENT", "text": "…", "mediaUrls": ["https://.oss-ap-southeast-1.aliyuncs.com/report.pdf"], "linkedinConnectionIds": [""], "advanceConfig": { "linkedin": { "documentTitle": "Q3 market report" } } }`. **Scheduling.** Pass `scheduleAt` (ISO 8601 **with** a timezone offset, e.g. `2026-07-11T10:00:00Z` or `+08:00`; 1 minute–365 days out) to schedule the post instead of publishing now. The whole request is validated immediately (auth, ownership, feature flags, media URL), then the response becomes `{ success: true, scheduled: true, scheduleJobId, scheduledAt }` with **no** `results` — a background worker publishes it at `scheduleAt`. Track it via `POST /api/v1/social-posts/schedule/status` (`scheduled | firing | fired | failed`; once `fired`, `publishJobIds` are the per-account ids to poll on `/social-posts/status`), and cancel a still-pending post via `POST /api/v1/social-posts/schedule/cancel`. Instagram / Threads tokens are renewed at schedule time; if one still expires before `scheduleAt` the request fails with `400 AUTH_EXPIRES_BEFORE_SCHEDULE` (or `401 TOKEN_EXPIRED` if it is already dead; `404 ACCOUNT_NOT_FOUND` if the connection isn't yours). **Response.** `{ success: true, results: { TIKTOK?: [...], YOUTUBE?: [...], INSTAGRAM?: [...], THREADS?: [...], X?: [...], PINTEREST?: [...], LINKEDIN?: [...], FACEBOOK?: [...] } }`. HTTP 200 even if individual accounts fail. A foreign/invalid `connectionId` does NOT 400 the whole request — that account's entry gets `status: "failed"` while others proceed. Each entry is `{ connectionId, status, jobId, publishId?, mediaId?, info?, error? }` — `jobId` is an **additive** internal tracking id present on every item (including failed ones); all other fields keep their exact prior values. Pass the `jobId`s to `POST /api/v1/social-posts/status` to resolve the current status/URL of each account (TikTok is live-polled; other platforms report the state their background publish last wrote). A background publish that stops making progress is failed by a server-side watchdog (`errorCode: "PUBLISH_STALLED"`, 30–60 min depending on platform) — check `stage` before republishing: `creating` means the post may already be live. Do not treat prolonged `processing` as success. **Per-platform timing — critical for agents:** | Platform | Synchronous? | What the result means | |----------|-------------|-----------------------| | **TikTok** | **No — accepted, then reviewed asynchronously** | Returns `status: "processing"` with `publishId` (VIDEO: `share_id`; IMAGE/Photo Mode: the publish id) once TikTok accepts the task. TikTok's verdict (published, or rejected with e.g. `spam_risk`) lands minutes later — poll `POST /social-posts/status` with the `jobId`; it live-polls TikTok and returns `success` (with `postId` when TikTok exposes it) or `failed` with TikTok's reason in `error`. Never treat the accept-time response as live. `privacy_level` is required by TikTok — the route discovers the creator's allowed values and defaults to the first if you don't pass one. IMAGE images are re-hosted to a TikTok-verified CDN before publish. | | **YouTube** | **No — fire-and-forget, background upload** | VIDEO only. Returns `status: "processing"`; the upload runs in the background (no webhook). When it finishes, the terminal state (videoId + watch URL) is written to the job — poll it via `POST /social-posts/status`, same as X/Pinterest/LinkedIn/Facebook video. There is no live handle; a background failure is written to the job, and a job with no progress for 60 min is failed by the watchdog (`errorCode: "PUBLISH_STALLED"`). Don't treat `processing` as success. | | **Instagram** | **No — background polling** | Container is created synchronously (returns `mediaId` + `status: "processing"`), then the server polls the container for up to **~8 minutes** before publishing. Media type is `REELS` for VIDEO; `IMAGE` (single) or `CAROUSEL` (multi) for IMAGE. No client-facing poll endpoint. | | **Threads** | **No — background polling** | Same model as Instagram: container created synchronously (`status: "processing"`), then polled in the background. VIDEO or IMAGE/carousel. | | **X** | VIDEO: background upload + polling. IMAGE: synchronous. | VIDEO returns `status:"processing"` — the server downloads the media, runs X's chunked upload (INIT/APPEND/FINALIZE) + processing poll, then creates the tweet; the terminal state (tweet id / URL) is written to the job, poll it via `/social-posts/status`. Size/duration caps are enforced BEFORE the billed upload (≤512 MB, ≤140 s). IMAGE is synchronous: the server uploads the image bytes then creates the tweet; `status:"success"` carries `publishId` (tweet id), up to 4 images. | | **Pinterest** | VIDEO: background upload + polling. IMAGE: synchronous. | The target board is bound to the Pinterest connection server-side — there is **no** `boardId` parameter. A connection with no board configured fails that account with `status:"failed"` (`Pinterest board not configured; reconnect this account`); re-link the account to bind a board. VIDEO returns `status:"processing"` once the background upload starts, then the server uploads the video to Pinterest, polls media processing, and creates the pin. IMAGE creates a standard image Pin directly from `media_source: { source_type:"image_url", url, is_standard:true }`; only one image is supported per Pinterest account result. API-key callers are supported; service-token callers are rejected. | | **LinkedIn** | VIDEO / DOCUMENT: background upload. IMAGE: synchronous. | **Company page only** — personal profiles are rejected. VIDEO returns `status:"processing"` while the server downloads the media and uploads it to LinkedIn in the background. DOCUMENT (one PDF → swipeable document post) is also background: `status:"processing"`, final URN via `/social-posts/status`. IMAGE is synchronous: single image → single-image post; 2–20 → `multiImage` carousel; `status:"success"` carries the post URN. Media bytes are fetched server-side, so media URLs must be on the allow-listed host. | | **Facebook** | VIDEO: background upload. IMAGE: synchronous. | Publishes to a linked **Page** (feed video / photo post). VIDEO returns `status:"processing"`; Facebook pulls the `file_url` and the server writes the terminal job state when the video id is known (`advanceConfig.facebook.coverUrl`/`firstComment` are best-effort). IMAGE is synchronous: one image → `/photos`; 2–10 → unpublished photos attached to a `/feed` post; `status:"success"` carries the post id. Facebook pulls each media URL, so URLs must be publicly reachable. | Pass multiple ids per platform to fan out to several accounts; each gets its own result entry. --- ## 4. Security note (read before pointing an agent at this API) **API keys are full-access.** A `lumi_` key can do everything its owner can: publish videos to live social accounts, create and DELETE automation strategies, cancel and reprocess tasks, and spend localization/upload quota. An autonomous agent holding a key can therefore **publish content and cancel work** on the user's behalf — there is no read-only or scoped key today. Recommendations: - **Use a dedicated per-agent key** so you can revoke it independently and attribute its actions. Generate one at `/dashboard/api-keys`. - Treat the key as a publishing credential, not a read token. Gate any agent action that publishes or deletes behind your own confirmation step. - **Scoped / read-only keys are a planned future feature**, not available yet. --- ## 5. Where to go next - **Machine contract:** `GET https://app.lumipath.cn/api/v1/openapi.json` (OpenAPI 3.1; ingest/codegen from this). - **This prose:** `GET https://app.lumipath.cn/docs/llms-full.txt`. - **Short index:** `GET https://app.lumipath.cn/llms.txt`. - The MCP transport (`/api/v1/public/[transport]`) is intentionally **absent** from the public spec — this API is consumed over plain HTTP, not MCP.