@autoposting.ai/cli 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +283 -66
- package/dist/cli.cjs.map +1 -1
- package/package.json +1 -1
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../sdk/src/resource.ts","../../sdk/src/resources/account-onboarding.ts","../../sdk/src/version.ts","../../sdk/src/errors.ts","../../sdk/src/resources/media.ts","../../sdk/src/resources/agents.ts","../../sdk/src/resources/billing.ts","../../sdk/src/resources/brands.ts","../../sdk/src/resources/carousels.ts","../../sdk/src/resources/clips.ts","../../sdk/src/resources/posts.ts","../../sdk/src/resources/kb.ts","../../sdk/src/resources/ideas.ts","../../sdk/src/resources/usage.ts","../../sdk/src/resources/webhooks.ts","../../sdk/src/resources/workspaces.ts","../../sdk/src/client.ts","../src/lib/media-flags.ts","../src/mcp/tools.ts","../src/lib/api-routes.ts","../src/mcp/handler.ts","../src/mcp/server.ts","../src/cli.ts","../src/commands/agents.ts","../src/auth/credential-store.ts","../src/auth/auth-manager.ts","../src/output/formatter.ts","../src/output/spinner.ts","../src/output/printer.ts","../src/output/exit-codes.ts","../src/commands/auth.ts","../src/auth/device-code-client.ts","../src/commands/billing.ts","../src/commands/accounts.ts","../src/commands/brands.ts","../src/auth/config-store.ts","../src/commands/carousels.ts","../src/commands/clips.ts","../src/commands/posts.ts","../src/lib/post-create.ts","../src/lib/account-select.ts","../src/lib/post-bulk.ts","../src/commands/kb.ts","../src/commands/ideas.ts","../src/commands/usage.ts","../src/commands/webhooks.ts","../src/commands/workspaces.ts","../src/commands/doctor.ts","../src/commands/whoami.ts","../src/commands/open.ts","../src/commands/update.ts","../src/commands/completion.ts","../src/commands/mcp.ts","../src/commands/config.ts","../src/commands/api.ts"],"sourcesContent":["import type { Autoposting } from './client'\n\nexport abstract class Resource {\n constructor(protected client: Autoposting) {}\n\n protected get<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.client.request<T>('GET', path, undefined, query)\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('POST', path, body)\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('PUT', path, body)\n }\n\n protected patch<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('PATCH', path, body)\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.client.request<T>('DELETE', path)\n }\n}\n","import { Resource } from '../resource'\nimport type { Platform } from '../types'\nexport interface AccountImportRow {\n brand_name: string\n brand_slug?: string\n platform: Platform\n account_url: string\n timezone?: string\n account_type?: 'personal' | 'organization'\n}\nexport interface AccountImport {\n id: string\n total: number\n next: string\n}\nexport type AccountImportRowStatus =\n | 'unprepared'\n | 'permission_denied'\n | 'pending_authorization'\n | 'needs_confirmation'\n | 'connected'\n | 'reconnect_required'\n | 'authorization_failed'\n | 'account_mismatch'\nexport interface AccountImportStatus {\n id: string\n total: number\n nextOffset: number | null\n connected: number\n unprepared: number\n capacity: {\n plan: string\n limit: number | null\n currentCount: number\n remaining: number | null\n }\n rows: Array<{\n id: string\n brandName?: string\n brandSlug?: string\n platform?: Platform\n accountUrl?: string\n status: AccountImportRowStatus\n error?: string\n lastError?: string\n accounts?: Array<{\n tokenId: string\n accountId?: string\n name?: string\n usable: boolean\n }>\n }>\n}\nexport interface AccountApproval {\n id: string\n rowId: string\n url: string\n accountUrl: string\n expiresInSeconds: number\n instructions: string\n}\nconst segment = (value: string) => {\n if (!/^[a-f0-9]{24}$/.test(value))\n throw new Error(\n 'Import and row identifiers must be 24-character hexadecimal strings',\n )\n return value\n}\nexport class AccountOnboardingResource extends Resource {\n remove(id: string): Promise<{ id: string; deleted: boolean }> {\n return this.delete(`/account-onboarding/${segment(id)}`)\n }\n create(\n input: { csv: string } | { rows: AccountImportRow[] },\n ): Promise<AccountImport> {\n return this.post('/account-onboarding', input)\n }\n status(\n id: string,\n query?: { offset?: number; limit?: number },\n ): Promise<AccountImportStatus> {\n return this.get(`/account-onboarding/${segment(id)}`, query)\n }\n prepare(\n id: string,\n offset = 0,\n ): Promise<{\n id: string\n rows: Array<{\n id: string\n brandSlug: string\n prepared: boolean\n error?: string\n }>\n nextOffset: number | null\n }> {\n return this.post(`/account-onboarding/${segment(id)}/prepare`, { offset })\n }\n authorize(id: string, rowId: string): Promise<AccountApproval> {\n return this.post(\n `/account-onboarding/${segment(id)}/rows/${segment(rowId)}/authorize`,\n )\n }\n confirm(\n id: string,\n rowId: string,\n tokenId: string,\n ): Promise<{ rowId: string; status: string; tokenId: string }> {\n return this.post(\n `/account-onboarding/${segment(id)}/rows/${segment(rowId)}/confirm`,\n { tokenId: segment(tokenId) },\n )\n }\n}\n","// ponytail: version injected at build from package.json via tsup `env` (see tsup.config.ts),\n// so package.json is the single source of truth and `changeset version` bumps flow through\n// automatically — no hand-edited constant to drift. Fallback covers running src directly\n// (vitest/ts-node) without a build.\nexport const VERSION = process.env.AUTOPOSTING_SDK_VERSION ?? '0.0.0-dev'\n","export class AutopostingError extends Error {\n status: number\n code: string\n\n constructor(message: string, status: number, code: string) {\n super(message)\n this.name = this.constructor.name\n this.status = status\n this.code = code\n // Restore prototype chain (required for custom Error subclasses in TS)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\nexport class AuthenticationError extends AutopostingError {}\nexport class ScopeError extends AutopostingError {}\nexport class NotFoundError extends AutopostingError {}\nexport class ValidationError extends AutopostingError {}\n\nexport class RateLimitError extends AutopostingError {\n retryAfter?: number\n}\n\nexport class ServerError extends AutopostingError {}\n\nexport function createError(\n status: number,\n body: { error?: string; code?: string },\n): AutopostingError {\n const message = body.error ?? 'An error occurred'\n const code = body.code ?? 'UNKNOWN'\n\n if (status === 401) return new AuthenticationError(message, status, code)\n if (status === 403) return new ScopeError(message, status, code)\n if (status === 404) return new NotFoundError(message, status, code)\n if (status === 400 || status === 422) return new ValidationError(message, status, code)\n if (status === 429) return new RateLimitError(message, status, code)\n if (status >= 500) return new ServerError(message, status, code)\n\n return new AutopostingError(message, status, code)\n}\n","import { Resource } from '../resource'\n\nexport interface MediaUpload {\n data: Uint8Array<ArrayBuffer> | Blob\n filename: string\n contentType?: string\n}\n\nexport interface UploadedMedia {\n url: string\n type: 'image' | 'video' | 'gif'\n filename: string\n}\n\nexport class MediaResource extends Resource {\n /** POST /media/upload — multipart/form-data, ≤20MB, image/* | video/*. */\n upload(file: MediaUpload): Promise<UploadedMedia> {\n const form = new FormData()\n const blob =\n file.data instanceof Blob\n ? file.data\n : new Blob([file.data], { type: file.contentType })\n form.append('file', blob, file.filename)\n return this.client.request<UploadedMedia>('POST', '/media/upload', form)\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Agent, AgentRun, CreateAgentParams, UpdateAgentParams } from '../types/agents'\n\nexport class AgentsResource extends Resource {\n /** GET /agents — backend returns `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Agent>> {\n return this.get<Paginated<Agent>>('/agents')\n }\n\n retrieve(id: string): Promise<Agent> {\n return this.get<Agent>(`/agents/${id}`)\n }\n\n create(params: CreateAgentParams): Promise<Agent> {\n return this.post<Agent>('/agents', params)\n }\n\n update(id: string, params: UpdateAgentParams): Promise<Agent> {\n return this.patch<Agent>(`/agents/${id}`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/agents/${id}`)\n }\n\n /** POST /agents/:id/run — queues a run; returns `{ runId, status }`, not a full AgentRun. */\n run(id: string): Promise<{ runId: string; status: string }> {\n return this.post<{ runId: string; status: string }>(`/agents/${id}/run`)\n }\n\n toggle(id: string): Promise<Agent> {\n return this.post<Agent>(`/agents/${id}/toggle`)\n }\n\n /** GET /agents/:id/runs — backend returns `{ items, total, limit, offset }`. */\n runs(id: string): Promise<Paginated<AgentRun>> {\n return this.get<Paginated<AgentRun>>(`/agents/${id}/runs`)\n }\n}\n","import { Resource } from '../resource'\nimport type { BillingStatus, CreditBalance } from '../types/billing'\n\nexport class BillingResource extends Resource {\n status(): Promise<BillingStatus> {\n return this.get<BillingStatus>('/billing/status')\n }\n\n credits(): Promise<CreditBalance> {\n return this.get<CreditBalance>('/billing/credits')\n }\n}\n","import { Resource } from '../resource'\nimport type { Brand, CreateBrandParams, PlatformConnection, UpdateBrandParams } from '../types/brands'\n\nexport class BrandsResource extends Resource {\n list(): Promise<Brand[]> {\n return this.get<Brand[]>('/brands')\n }\n\n retrieve(slug: string): Promise<Brand> {\n return this.get<Brand>(`/brands/${slug}`)\n }\n\n create(params: CreateBrandParams): Promise<Brand> {\n return this.post<Brand>('/brands', params)\n }\n\n update(slug: string, params: UpdateBrandParams): Promise<Brand> {\n return this.patch<Brand>(`/brands/${slug}`, params)\n }\n\n remove(slug: string): Promise<void> {\n return this.delete<void>(`/brands/${slug}`)\n }\n\n authStatus(slug: string): Promise<PlatformConnection[]> {\n return this.get<PlatformConnection[]>(`/brands/${slug}/auth/status`)\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Carousel, CreateCarouselParams, GenerateCarouselParams } from '../types/carousels'\n\nexport class CarouselsResource extends Resource {\n /** GET /carousels — backend paginates: `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Carousel>> {\n return this.get<Paginated<Carousel>>('/carousels')\n }\n\n retrieve(id: string): Promise<Carousel> {\n return this.get<Carousel>(`/carousels/${id}`)\n }\n\n create(params?: CreateCarouselParams): Promise<Carousel> {\n return this.post<Carousel>('/carousels', params)\n }\n\n generate(params: GenerateCarouselParams): Promise<Carousel> {\n return this.post<Carousel>('/carousels/generate', params)\n }\n\n /** POST /carousels/:id/create-draft — converts carousel to a post draft */\n draft(id: string): Promise<Carousel> {\n return this.post<Carousel>(`/carousels/${id}/create-draft`)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/carousels/${id}`)\n }\n}\n","import { Resource } from '../resource'\nimport { AutopostingError } from '../errors'\nimport type { Clip, CreateClipDraftParams, ImportClipParams, RenderClipParams } from '../types/clips'\n\n// R2/S3 multipart: every part except the last must be ≥5MB; at most 10,000 parts.\nconst MIN_PART_SIZE = 5 * 1024 * 1024\nconst DEFAULT_PART_SIZE = 16 * 1024 * 1024\nconst MAX_PARTS = 10_000\n\nconst VIDEO_MIME: Record<string, string> = {\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n avi: 'video/x-msvideo',\n m4v: 'video/x-m4v',\n}\n\nexport interface UploadClipOptions {\n /** Brand the clip belongs to (required by the backend). */\n brandId: string\n /** Display title; defaults to the file name. */\n title?: string\n /** Override the detected MIME type. */\n contentType?: string\n /** Multipart chunk size in bytes (clamped to the 5MB..10k-part range). */\n partSize?: number\n /** Called after each part with overall percent uploaded (0–100). */\n onProgress?: (pct: number) => void\n}\n\nexport class ClipsResource extends Resource {\n /** GET /clips — backend returns `{ clips, pagination }`, not a bare array. */\n list(): Promise<{\n clips: Clip[]\n pagination: { page: number; limit: number; total: number; totalPages: number }\n }> {\n return this.client.request('GET', '/clips')\n }\n\n retrieve(id: string): Promise<Clip> {\n return this.client.request<Clip>('GET', `/clips/${id}`)\n }\n\n /**\n * Upload a local video file as a clip by driving the backend multipart flow:\n * `init → presign → PUT each part → complete`. On any failure after init, the\n * multipart upload is aborted so it leaves no dangling clip. Returns the created clip.\n *\n * Node-only: reads the file in chunks (memory-bounded for multi-GB videos). `node:fs`\n * is imported dynamically so the rest of the SDK stays runtime-agnostic.\n */\n async upload(filePath: string, options: UploadClipOptions): Promise<Clip> {\n if (!options?.brandId) {\n throw new AutopostingError('brandId is required to upload a clip.', 0, 'VALIDATION_ERROR')\n }\n\n const { open, stat } = await import('node:fs/promises')\n const { basename } = await import('node:path')\n\n const fileName = basename(filePath)\n const title = options.title ?? fileName\n const mimeType = options.contentType ?? guessVideoMime(fileName)\n const { size: fileSize } = await stat(filePath)\n if (fileSize <= 0) {\n throw new AutopostingError(`File is empty: ${filePath}`, 0, 'VALIDATION_ERROR')\n }\n\n const partSize = resolvePartSize(fileSize, options.partSize)\n const partNumbers = Array.from(\n { length: Math.max(1, Math.ceil(fileSize / partSize)) },\n (_, i) => i + 1,\n )\n\n const { clipId, uploadId, key } = await this.client.request<{\n clipId: string\n uploadId: string\n key: string\n }>('POST', '/clips/upload/init', { brandId: options.brandId, title, fileName, fileSize, mimeType })\n\n let completed: { clipId: string; status: string }\n const handle = await open(filePath, 'r')\n try {\n const { presignedUrls } = await this.client.request<{\n presignedUrls: { partNumber: number; url: string }[]\n }>('POST', '/clips/upload/presign', { clipId, uploadId, key, partNumbers })\n const urlByPart = new Map(presignedUrls.map((p) => [p.partNumber, p.url]))\n\n // ponytail: parts upload sequentially with no per-part retry — simple and correct for a\n // CLI. Add bounded concurrency / retry here if throughput on large files matters.\n const parts: { partNumber: number; etag: string }[] = []\n let uploaded = 0\n for (const partNumber of partNumbers) {\n const url = urlByPart.get(partNumber)\n if (!url) {\n throw new AutopostingError(`Missing presigned URL for part ${partNumber}.`, 0, 'UPLOAD_FAILED')\n }\n const offset = (partNumber - 1) * partSize\n const length = Math.min(partSize, fileSize - offset)\n const buffer = Buffer.allocUnsafe(length)\n await handle.read(buffer, 0, length, offset)\n parts.push({ partNumber, etag: await putPart(url, buffer) })\n uploaded += length\n options.onProgress?.(Math.round((uploaded / fileSize) * 100))\n }\n\n completed = await this.client.request<{ clipId: string; status: string }>(\n 'POST',\n '/clips/upload/complete',\n { clipId, uploadId, key, parts },\n )\n } catch (err) {\n // Best-effort abort so a failed upload doesn't strand a multipart upload + 'uploading' clip.\n // Only the init→presign→PUT→complete steps reach here; once complete succeeds the upload is\n // done, so a later retrieve() failure (below) must NOT trigger an abort of a good clip.\n await this.client.request('POST', '/clips/upload/abort', { clipId, uploadId, key }).catch(() => {})\n throw err\n } finally {\n await handle.close()\n }\n return this.retrieve(completed.clipId)\n }\n\n /** POST /clips/import-url — backend returns `{ clipId }`, not a full Clip. */\n importUrl(params: ImportClipParams): Promise<{ clipId: string }> {\n return this.client.request<{ clipId: string }>('POST', '/clips/import-url', params)\n }\n\n /** POST /clips/:id/render — backend returns render job ids, not a Clip. */\n async render(\n id: string,\n params: RenderClipParams = {},\n ): Promise<{ jobIds: string[]; activeJobIds: string[]; reusedJobIds: string[] }> {\n const editRevision = params.editRevision ?? (await this.retrieve(id)).editRevision ?? 0\n return this.client.request('POST', `/clips/${id}/render`, {\n editRevision,\n ...(params.candidateId ? { candidateId: params.candidateId } : {}),\n })\n }\n\n /** POST /clips/:id/create-draft — turns a rendered clip into a draft post. */\n createDraft(id: string, params: CreateClipDraftParams = {}): Promise<{ postId: string }> {\n return this.client.request<{ postId: string }>('POST', `/clips/${id}/create-draft`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/clips/${id}`)\n }\n}\n\n/** Pick a chunk size that respects the 5MB minimum and the 10,000-part ceiling. */\nfunction resolvePartSize(fileSize: number, requested?: number): number {\n let size = requested && requested > 0 ? requested : DEFAULT_PART_SIZE\n if (Math.ceil(fileSize / size) > MAX_PARTS) size = Math.ceil(fileSize / MAX_PARTS)\n return Math.max(size, MIN_PART_SIZE)\n}\n\nfunction guessVideoMime(fileName: string): string {\n const ext = fileName.split('.').pop()?.toLowerCase() ?? ''\n return VIDEO_MIME[ext] ?? 'video/mp4'\n}\n\n/**\n * PUT one part to its presigned URL with a raw fetch — the URL is pre-authorized, so the\n * SDK's Bearer token and base URL must NOT be attached. Returns the part's ETag (kept\n * verbatim, quotes included, as CompleteMultipartUpload expects).\n */\nasync function putPart(url: string, body: Buffer): Promise<string> {\n let res: Response\n try {\n res = await fetch(url, { method: 'PUT', body })\n } catch (err) {\n throw new AutopostingError(\n `Failed to upload part: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n 'UPLOAD_FAILED',\n )\n }\n if (!res.ok) {\n throw new AutopostingError(\n `Failed to upload part: HTTP ${res.status} ${res.statusText}`,\n res.status,\n 'UPLOAD_FAILED',\n )\n }\n const etag = res.headers.get('etag')\n if (!etag) {\n throw new AutopostingError('Upload part response is missing the ETag header.', res.status, 'UPLOAD_FAILED')\n }\n return etag\n}\n","import { Resource } from '../resource'\nimport type { Post, CreatePostParams, UpdatePostParams, ListPostsParams } from '../types/posts'\n\n// PostsResource methods `get` and `delete` cannot directly override the base class\n// protected generics (`get<T>`, `delete<T>`) due to TypeScript generic covariance rules.\n// We call `this.client.request` directly and expose public methods with unambiguous names.\n// The public API surface is: list, get, create, update, delete, publish, schedule, unschedule, retry, rewrite, score.\nexport class PostsResource extends Resource {\n /** GET /posts — backend returns a bare array (no pagination metadata). */\n list(params: ListPostsParams = {}): Promise<Post[]> {\n const { brandSlug, status, limit, page } = params\n const query: Record<string, unknown> = {}\n if (brandSlug) query.brandSlug = brandSlug\n if (status) query.status = status\n if (limit !== undefined) query.limit = limit\n // The backend paginates by `offset`, not `page` — translate so `--page` actually\n // advances results instead of being silently ignored.\n if (page !== undefined && page > 1) query.offset = (page - 1) * (limit ?? 20)\n return this.client.request<Post[]>('GET', '/posts', undefined, query)\n }\n\n /** GET /posts/:id */\n getById(id: string): Promise<Post> {\n return this.client.request<Post>('GET', `/posts/${id}`)\n }\n\n create(params: CreatePostParams): Promise<Post> {\n return this.client.request<Post>('POST', '/posts', params)\n }\n\n update(id: string, params: UpdatePostParams): Promise<Post> {\n return this.client.request<Post>('PUT', `/posts/${id}`, params)\n }\n\n /** DELETE /posts/:id */\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/posts/${id}`)\n }\n\n publish(id: string): Promise<Post> {\n return this.client.request<Post>('POST', `/posts/${id}/publish`)\n }\n\n schedule(id: string, scheduledAt: string): Promise<Post> {\n return this.client.request<Post>('PUT', `/posts/${id}/schedule`, { scheduledAt })\n }\n\n /** PUT /posts/:id/schedule with { cancel: true } — returns the post to draft. */\n unschedule(id: string): Promise<Post> {\n return this.client.request<Post>('PUT', `/posts/${id}/schedule`, { cancel: true })\n }\n\n retry(id: string): Promise<Post> {\n return this.client.request<Post>('POST', `/posts/${id}/retry`)\n }\n\n rewrite(id: string): Promise<Post> {\n return this.client.request<Post>('POST', `/posts/${id}/rewrite`)\n }\n\n /** POST /posts/:id/score — backend returns `{ score }` only (no feedback). */\n score(id: string): Promise<{ score: number }> {\n return this.client.request<{ score: number }>('POST', `/posts/${id}/score`)\n }\n}\n","import { Resource } from '../resource'\nimport type { KnowledgeBase, KbDocument, CreateKbParams, SearchResult } from '../types/kb'\n\nexport class KbResource extends Resource {\n list(): Promise<KnowledgeBase[]> {\n return this.get<KnowledgeBase[]>('/kbs')\n }\n\n retrieve(id: string): Promise<KnowledgeBase> {\n return this.get<KnowledgeBase>(`/kbs/${id}`)\n }\n\n create(params: CreateKbParams): Promise<KnowledgeBase> {\n return this.post<KnowledgeBase>('/kbs', params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/kbs/${id}`)\n }\n\n search(\n id: string,\n query: string,\n ): Promise<{ query: string; limit: number; total: number; results: SearchResult[] }> {\n return this.post<{ query: string; limit: number; total: number; results: SearchResult[] }>(\n `/kbs/${id}/search`,\n { query },\n )\n }\n\n ingestUrl(id: string, url: string): Promise<KbDocument> {\n return this.post<KbDocument>(`/kbs/${id}/docs/ingest-url`, { url })\n }\n\n docs(id: string): Promise<KbDocument[]> {\n return this.get<KbDocument[]>(`/kbs/${id}/docs`)\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Idea, GenerateIdeasParams, GenerateIdeasResult, EnrichIdeaParams } from '../types/kb'\n\nexport class IdeasResource extends Resource {\n /** POST /ideas/generate-topic — returns an object whose `ideas` holds the generated ideas. */\n generate(params: GenerateIdeasParams = {}): Promise<GenerateIdeasResult> {\n return this.post<GenerateIdeasResult>('/ideas/generate-topic', params)\n }\n\n /** GET /ideas — backend paginates: `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Idea>> {\n return this.get<Paginated<Idea>>('/ideas')\n }\n\n /**\n * POST /ideas/enrich — enrich an idea (title/hook/angle) across 1..5 platforms.\n * Async: returns a job id (202). NOTE: the backend enriches the idea *object*, not an\n * id — there is no enrich-by-id route. Poll the result separately (not yet wrapped).\n */\n enrich(params: EnrichIdeaParams): Promise<{ jobId: string }> {\n return this.post<{ jobId: string }>('/ideas/enrich', params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/ideas/${id}`)\n }\n}\n","import { Resource } from '../resource'\nimport type { UsageSummary } from '../types/usage'\n\nexport class UsageResource extends Resource {\n summary(): Promise<UsageSummary> {\n return this.get<UsageSummary>('/usage/summary')\n }\n}\n","import { Resource } from '../resource'\nimport type { Webhook, CreateWebhookParams, UpdateWebhookParams } from '../types/webhooks'\n\nexport class WebhooksResource extends Resource {\n list(): Promise<Webhook[]> {\n return this.get<Webhook[]>('/webhooks')\n }\n\n // NOTE: the backend has no GET /webhooks/:id route — this 404s until front-back adds it.\n retrieve(id: string): Promise<Webhook> {\n return this.get<Webhook>(`/webhooks/${id}`)\n }\n\n create(params: CreateWebhookParams): Promise<Webhook> {\n return this.post<Webhook>('/webhooks', params)\n }\n\n update(id: string, params: UpdateWebhookParams): Promise<Webhook> {\n return this.patch<Webhook>(`/webhooks/${id}`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/webhooks/${id}`)\n }\n\n // POST /webhooks/:id/test — backend returns `{ delivered, httpStatus }`.\n test(id: string): Promise<{ delivered: boolean; httpStatus: number }> {\n return this.post<{ delivered: boolean; httpStatus: number }>(`/webhooks/${id}/test`)\n }\n}\n","import { Resource } from '../resource'\nimport type { Workspace } from '../types/workspaces'\nimport type { Autoposting } from '../client'\n\nexport class WorkspacesResource extends Resource {\n constructor(client: Autoposting) {\n super(client)\n }\n\n /**\n * GET /orgs — backend returns `{ organizations, activeOrgId }`, not a bare array.\n * This route is session-only (better-auth session); an API key receives a bare 401,\n * so guard up front with accurate guidance instead of an opaque \"Unauthorized\".\n */\n list(): Promise<{ organizations: Workspace[]; activeOrgId: string }> {\n if (this.client.authSource === 'api-key') {\n return Promise.reject(\n new Error(\n 'Listing workspaces requires session auth. An API key is scoped to a single workspace ' +\n 'and cannot list organizations — manage workspaces from the web dashboard.',\n ),\n )\n }\n return this.get<{ organizations: Workspace[]; activeOrgId: string }>('/orgs')\n }\n\n switchWorkspace(id: string): Promise<void> {\n // API keys are scoped to a single workspace at creation time.\n // Switching requires a session token that can act across orgs.\n if (this.client.authSource === 'api-key') {\n return Promise.reject(\n new Error(\n 'API keys are bound to a single workspace. Use session auth to switch.',\n ),\n )\n }\n return this.client.request<void>('PUT', '/orgs/active', { organizationId: id })\n }\n}\n","import { AccountOnboardingResource } from './resources/account-onboarding'\nimport { VERSION } from './version'\nimport type { ApiResponse } from './types'\nimport { createError, RateLimitError, AutopostingError } from './errors'\nimport { MediaResource } from './resources/media'\nimport { AgentsResource } from './resources/agents'\nimport { BillingResource } from './resources/billing'\nimport { BrandsResource } from './resources/brands'\nimport { CarouselsResource } from './resources/carousels'\nimport { ClipsResource } from './resources/clips'\nimport { PostsResource } from './resources/posts'\nimport { KbResource } from './resources/kb'\nimport { IdeasResource } from './resources/ideas'\nimport { UsageResource } from './resources/usage'\nimport { WebhooksResource } from './resources/webhooks'\nimport { WorkspacesResource } from './resources/workspaces'\n\nexport interface AutopostingConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n headers?: Record<string, string>\n /** Mark the auth source so workspace-switching can enforce API key restrictions. */\n authSource?: 'api-key' | 'session'\n /** Max automatic retries for idempotent requests on transient failures. Default 2. */\n maxRetries?: number\n /** Base backoff in ms for retries (exponential ×2 per attempt, plus jitter). Default 300. */\n retryBaseMs?: number\n}\n\n/** Server-resolved identity behind a credential (GET /auth/profile). */\nexport interface AuthProfile {\n id: string\n orgId: string\n name: string\n email: string\n authType: 'api_key' | 'session'\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n// Only idempotent methods are safe to retry — retrying a POST/PATCH could double-create.\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>(['GET', 'PUT', 'DELETE'])\n// HTTP statuses that represent a transient server/proxy condition worth retrying.\n// 429 is intentionally excluded: it carries Retry-After and is surfaced to the caller\n// (auto-retrying it could hang for the full Retry-After window).\nconst RETRYABLE_STATUS: ReadonlySet<number> = new Set([500, 502, 503, 504])\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport class Autoposting {\n /** @internal Not part of the public API — use SDK methods to make requests. */\n private readonly _apiKey: string\n readonly baseUrl: string\n readonly timeout: number\n private readonly extraHeaders: Record<string, string>\n /** Indicates how the client was authenticated; used by WorkspacesResource. */\n readonly authSource: 'api-key' | 'session'\n readonly maxRetries: number\n private readonly retryBaseMs: number\n readonly media: MediaResource\n readonly agents: AgentsResource\n readonly billing: BillingResource\n readonly accountOnboarding: AccountOnboardingResource\n readonly brands: BrandsResource\n readonly carousels: CarouselsResource\n readonly clips: ClipsResource\n readonly posts: PostsResource\n readonly kb: KbResource\n readonly ideas: IdeasResource\n readonly usage: UsageResource\n readonly webhooks: WebhooksResource\n readonly workspaces: WorkspacesResource\n\n constructor(config: AutopostingConfig = {}) {\n const key = config.apiKey ?? process.env.AUTOPOSTING_API_KEY\n if (!key) {\n throw new Error(\n 'API key is required. Pass apiKey in config or set AUTOPOSTING_API_KEY env var.',\n )\n }\n this._apiKey = key\n // Resolution order: explicit config → AUTOPOSTING_BASE_URL env → default.\n // Production API is served by the backend behind the Next.js frontend's\n // /api-proxy rewrite (app.autoposting.ai/api-proxy/* -> backend/*). The bare\n // app.autoposting.ai host serves the dashboard SPA, not the JSON API.\n this.baseUrl = (\n config.baseUrl ||\n process.env.AUTOPOSTING_BASE_URL ||\n 'https://app.autoposting.ai/api-proxy'\n ).replace(/\\/$/, '')\n this.timeout = config.timeout ?? 30_000\n this.extraHeaders = config.headers ?? {}\n this.authSource = config.authSource ?? 'api-key'\n this.maxRetries = Math.max(0, config.maxRetries ?? 2)\n this.retryBaseMs = Math.max(0, config.retryBaseMs ?? 300)\n this.media = new MediaResource(this)\n this.agents = new AgentsResource(this)\n this.billing = new BillingResource(this)\n this.accountOnboarding = new AccountOnboardingResource(this)\n this.brands = new BrandsResource(this)\n this.carousels = new CarouselsResource(this)\n this.clips = new ClipsResource(this)\n this.posts = new PostsResource(this)\n this.kb = new KbResource(this)\n this.ideas = new IdeasResource(this)\n this.usage = new UsageResource(this)\n this.webhooks = new WebhooksResource(this)\n this.workspaces = new WorkspacesResource(this)\n }\n\n /**\n * GET /auth/profile — resolve the server-side identity behind the current credential.\n * Validates the key (401 on reject) and returns who/what it's scoped to.\n */\n getProfile(): Promise<AuthProfile> {\n return this.request<AuthProfile>('GET', '/auth/profile')\n }\n\n /**\n * Public entry point. Retries idempotent requests (GET/PUT/DELETE) on transient\n * failures — network errors, timeouts, and 5xx — with exponential backoff + jitter.\n * Non-idempotent methods (POST/PATCH) are never retried, to avoid duplicate side effects.\n */\n async request<T = unknown>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n query?: Record<string, unknown>,\n ): Promise<T> {\n let lastErr: unknown\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n // Exponential backoff (base × 2^(attempt-1)) plus jitter to avoid thundering herds.\n const backoff = this.retryBaseMs * 2 ** (attempt - 1)\n await sleep(backoff + Math.floor(Math.random() * this.retryBaseMs))\n }\n try {\n return await this._send<T>(method, path, body, query)\n } catch (err) {\n lastErr = err\n if (attempt < this.maxRetries && this.isRetryable(method, err)) continue\n throw err\n }\n }\n throw lastErr\n }\n\n private isRetryable(method: HttpMethod, err: unknown): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false\n if (!(err instanceof AutopostingError)) return false\n if (err.code === 'NETWORK_ERROR' || err.code === 'TIMEOUT') return true\n return RETRYABLE_STATUS.has(err.status)\n }\n\n private async _send<T = unknown>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n query?: Record<string, unknown>,\n ): Promise<T> {\n let url = `${this.baseUrl}${path}`\n\n if (query && Object.keys(query).length > 0) {\n const params = new URLSearchParams()\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined && v !== null) {\n params.set(k, String(v))\n }\n }\n url = `${url}?${params.toString()}`\n }\n\n // FormData must not have a content-type header — fetch sets it with the multipart boundary.\n const isFormData = body instanceof FormData\n // Spread caller headers first so the auth, source, and content-type headers below\n // always win — a stray `headers` override must never strip authentication.\n const headers: Record<string, string> = {\n ...this.extraHeaders,\n authorization: `Bearer ${this._apiKey}`,\n 'user-agent': `autoposting-sdk/${VERSION}`,\n 'x-source': 'sdk',\n }\n if (!isFormData) {\n headers['content-type'] = 'application/json'\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeout)\n\n // Keep the abort timer armed through the body read, not just the fetch — a\n // response whose body stream stalls would otherwise hang past the timeout.\n try {\n let response: Response\n try {\n response = await fetch(url, {\n method,\n headers,\n body: isFormData ? body : body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n } catch (err) {\n // fetch rejects on network failure or abort (timeout) — wrap both so callers\n // always get an AutopostingError, never a raw TypeError / DOMException.\n if (err instanceof Error && err.name === 'AbortError') {\n throw new AutopostingError(\n `Request to ${method} ${path} timed out after ${this.timeout}ms.`,\n 0,\n 'TIMEOUT',\n )\n }\n throw new AutopostingError(\n `Network request to ${method} ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n 'NETWORK_ERROR',\n )\n }\n\n if (!response.ok) {\n const raw = await response.text()\n let errorBody: { error?: string; code?: string } = {}\n if (raw) {\n try {\n errorBody = JSON.parse(raw) as { error?: string; code?: string }\n } catch {\n // non-JSON error body (e.g. an HTML page from a wrong base URL or a proxy/5xx)\n }\n }\n if (!errorBody.error) {\n const snippet = raw.replace(/\\s+/g, ' ').trim().slice(0, 120)\n errorBody.error = snippet\n ? `HTTP ${response.status} ${response.statusText}: ${snippet}`\n : `HTTP ${response.status} ${response.statusText}`\n }\n\n const err = createError(response.status, errorBody)\n\n if (err instanceof RateLimitError) {\n const retryAfter = response.headers.get('Retry-After')\n if (retryAfter) {\n // Retry-After is delta-seconds OR an HTTP-date (RFC 7231) — handle both.\n const seconds = Number(retryAfter)\n if (Number.isFinite(seconds)) {\n err.retryAfter = Math.max(0, Math.round(seconds))\n } else {\n const dateMs = Date.parse(retryAfter)\n if (!Number.isNaN(dateMs)) {\n err.retryAfter = Math.max(0, Math.round((dateMs - Date.now()) / 1000))\n }\n }\n }\n }\n\n throw err\n }\n\n // 204 No Content — return empty object\n if (response.status === 204) {\n return {} as T\n }\n\n const text = await response.text()\n if (!text) return {} as T\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n // A 2xx with a non-JSON body almost always means the base URL points at the\n // web app (HTML) instead of the JSON API — surface that, not a raw parse error.\n throw new AutopostingError(\n `Expected a JSON response from ${method} ${path} but received non-JSON (HTTP ${response.status}). ` +\n `Verify the API base URL (AUTOPOSTING_BASE_URL / --base-url) points at the API, not the web app.`,\n response.status,\n 'INVALID_RESPONSE',\n )\n }\n // The backend wraps every success response as `{ success: true, data: <payload> }`.\n // Unwrap to the payload so resource return types describe the real data, not the\n // envelope. Void endpoints (e.g. some deletes) return `{ success: true }` with no\n // `data` — yield `{}` for those. A body without `success` passes through unchanged.\n // ponytail: relies on no real payload carrying its own top-level `success` field —\n // true for this API; revisit if an endpoint returns raw `{ success, ... }` data.\n if (typeof parsed === 'object' && parsed !== null && (parsed as ApiResponse).success === true) {\n const env = parsed as ApiResponse<T>\n return env.data !== undefined ? env.data : ({} as T)\n }\n return parsed as T\n } catch (err) {\n // A timer abort during the body read surfaces here as a raw AbortError (the\n // fetch-phase abort is already wrapped above). Convert it to TIMEOUT so callers\n // never receive a raw DOMException; already-wrapped AutopostingErrors pass through.\n if (err instanceof Error && err.name === 'AbortError') {\n throw new AutopostingError(\n `Request to ${method} ${path} timed out after ${this.timeout}ms.`,\n 0,\n 'TIMEOUT',\n )\n }\n throw err\n } finally {\n clearTimeout(timer)\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport type { Platform, MediaInput, InstagramOptions, ThreadsOptions, YoutubeOptions } from '@autoposting.ai/sdk'\n\nexport type { MediaInput, InstagramOptions, ThreadsOptions, YoutubeOptions }\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube']\n\nconst EXT_TO_MIME: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n}\n\n/** Maps a filename's extension to a MIME type. Throws on unknown extensions. */\nexport function extToMime(filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase() ?? ''\n const mime = EXT_TO_MIME[ext]\n if (!mime) {\n throw new Error(\n `Unsupported file extension \".${ext || '(none)'}\" in \"${filename}\". ` +\n `Supported: ${Object.keys(EXT_TO_MIME).join(', ')}`,\n )\n }\n return mime\n}\n\n/** Parses \"platform=value\" strings into a platform-keyed record. */\nexport function parsePairs(flag: string, vals: string[]): Partial<Record<Platform, string>> {\n const result: Partial<Record<Platform, string>> = {}\n for (const val of vals) {\n const eqIdx = val.indexOf('=')\n if (eqIdx < 1) {\n throw new Error(`${flag}: expected \"platform=value\" format, got \"${val}\"`)\n }\n const p = val.slice(0, eqIdx).trim()\n const v = val.slice(eqIdx + 1)\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw new Error(`${flag}: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`)\n }\n result[p as Platform] = v\n }\n return result\n}\n\n/** Parses \"platform=path1[,path2,...]\" strings into a platform-keyed path-array record. */\nexport function parsePlatformMediaPairs(\n flag: string,\n vals: string[],\n): Partial<Record<Platform, string[]>> {\n const result: Partial<Record<Platform, string[]>> = {}\n for (const val of vals) {\n const eqIdx = val.indexOf('=')\n if (eqIdx < 1) {\n throw new Error(`${flag}: expected \"platform=path[,path...]\" format, got \"${val}\"`)\n }\n const p = val.slice(0, eqIdx).trim()\n const paths = val\n .slice(eqIdx + 1)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw new Error(`${flag}: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`)\n }\n result[p as Platform] = paths\n }\n return result\n}\n\n/** Validates that every path has a supported extension. Throws on the first bad one.\n * Lets `posts create` reject unsupported media before any network call/upload. */\nexport function validateMediaExtensions(paths: string[]): void {\n for (const p of paths) extToMime(p)\n}\n\n/** Throws if more than 10 media paths are provided (backend limit). */\nexport function validateMediaCount(paths: string[]): void {\n if (paths.length > 10) {\n throw new Error(`--media accepts at most 10 files (received ${paths.length}).`)\n }\n}\n\n/** Validates that all media file paths exist on disk. */\nexport function validateMediaPaths(paths: string[]): void {\n for (const p of paths) {\n if (!existsSync(p)) {\n throw new Error(`Media file not found: \"${p}\"`)\n }\n }\n}\n\n/**\n * Aligns alt-text strings to media paths by index.\n * Returns undefined for indices with no alt-text.\n * Throws if altTexts.length > mediaPaths.length.\n */\nexport function alignAltText(\n mediaPaths: string[],\n altTexts: string[],\n): Array<string | undefined> {\n if (altTexts.length > mediaPaths.length) {\n throw new Error(\n `--alt-text has more values (${altTexts.length}) than --media (${mediaPaths.length}). ` +\n `Alt text aligns to media by index.`,\n )\n }\n return mediaPaths.map((_, i) => altTexts[i])\n}\n\n/** Builds YoutubeOptions from CLI flag values; returns undefined if all fields are empty. */\nexport function buildYoutubeOptions(opts: {\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n}): YoutubeOptions | undefined {\n const { ytTitle, ytDescription, ytTags, ytPrivacy, ytCategory, ytMadeForKids } = opts\n const o: YoutubeOptions = {}\n if (ytTitle) o.title = ytTitle\n if (ytDescription) o.description = ytDescription\n if (ytTags) o.tags = ytTags.split(',').map((t) => t.trim()).filter(Boolean)\n if (ytPrivacy) o.privacyStatus = ytPrivacy\n if (ytCategory) o.categoryId = ytCategory\n if (ytMadeForKids !== undefined) o.madeForKids = ytMadeForKids\n return Object.keys(o).length > 0 ? o : undefined\n}\n\n/** Builds InstagramOptions from CLI flag values; returns undefined if no IG flags are set. */\nexport function buildInstagramOptions(opts: {\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n}): InstagramOptions | undefined {\n const { igReel, igShareToFeed, igCoverUrl, igThumbOffsetMs, igCollaborators } = opts\n const hasAnyReelFlag = igReel !== undefined || igShareToFeed !== undefined ||\n igCoverUrl !== undefined || igThumbOffsetMs !== undefined || igCollaborators !== undefined\n if (!hasAnyReelFlag) return undefined\n\n const reel: NonNullable<InstagramOptions['reel']> = {}\n // --ig-reel presence alone signals reel mode to the backend; no field to set\n if (igShareToFeed !== undefined) reel.shareToFeed = igShareToFeed\n if (igCoverUrl) reel.coverUrl = igCoverUrl\n if (igThumbOffsetMs !== undefined) {\n const n = Number(igThumbOffsetMs)\n if (!Number.isFinite(n) || n < 0) {\n throw new Error(\n `--ig-thumb-offset-ms must be a non-negative number (received \"${igThumbOffsetMs}\")`,\n )\n }\n reel.thumbOffsetMs = n\n }\n if (igCollaborators) {\n reel.collaborators = igCollaborators.split(',').map((s) => s.trim()).filter(Boolean)\n }\n return { reel }\n}\n\n/** Builds ThreadsOptions from CLI flag values; returns undefined if no flags are set. */\nexport function buildThreadsOptions(opts: {\n threadsReplyTo?: string\n threadsReplyControl?: string\n}): ThreadsOptions | undefined {\n const { threadsReplyTo, threadsReplyControl } = opts\n if (!threadsReplyTo && !threadsReplyControl) return undefined\n const o: ThreadsOptions = {}\n if (threadsReplyTo) o.replyToId = threadsReplyTo\n if (threadsReplyControl) o.replyControl = threadsReplyControl\n return o\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js'\n\n// MCP carries JSON, not file bytes: media must already be at a public https URL.\nconst MEDIA_ITEMS = {\n type: 'array',\n maxItems: 10,\n description:\n 'Images or videos to attach, as https URLs. For a local file, call upload-media first and pass its result here.',\n items: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'Public https URL of the image or video' },\n type: { type: 'string', enum: ['image', 'video', 'gif'] },\n altText: { type: 'string', description: 'Optional alt text' },\n },\n required: ['url', 'type'],\n additionalProperties: false,\n },\n}\n\nexport const ALL_TOOLS: Tool[] = [\n {name:'delete-account-import',description:'Delete import progress only. Connected accounts and brands remain. Ask the user before discarding their progress.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'}},required:['id']}},\n { name: 'import-accounts', description: 'Import 1–1000 social account rows from CSV. Headers: brand_name, platform, account_url; optional brand_slug, timezone, account_type. Returns a durable import id. Repeating the same import reuses progress. No passwords or provider tokens.', inputSchema: {type:'object',properties:{csv:{type:'string',maxLength:90000,description:'CSV contents, including header row'}},required:['csv']} },\n {name:'prepare-account-import',description:'Create or reuse up to 25 brands. Repeat with nextOffset until null; safe to resume.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},offset:{type:'integer',minimum:0,description:'Next row offset; default 0'}},required:['id']}},\n {name:'account-import-status',description:'Check actual imported account connections and plan capacity. A link alone is not a connection. Vanity URLs may need explicit account confirmation.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},offset:{type:'integer',minimum:0,description:'Row offset; default 0'},limit:{type:'integer',minimum:1,maximum:100,description:'Rows per page; default 50'}},required:['id']}},\n {name:'authorize-import-account',description:'Generate a fresh provider approval link for one row. Present it to the user, who opens it in their browser and approves the intended account. Then check status. Links expire after 10 minutes.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},rowId:{type:'string',description:'Row id from status'}},required:['id','rowId']}},\n {name:'confirm-import-account',description:'For needs_confirmation rows ONLY: show the actual account id/name and CSV URL to the user. Call only after the user explicitly confirms they match. tokenId must come from status; this never creates a connection.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},rowId:{type:'string',description:'Row id'},tokenId:{type:'string',description:'User-confirmed tokenId from status'}},required:['id','rowId','tokenId']}},\n\n // Posts\n {\n name: 'list-posts',\n description: 'List posts with optional filters by brand, status, limit, and page.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Filter by brand slug' },\n status: {\n type: 'string',\n enum: ['draft', 'scheduled', 'published', 'failed'],\n description: 'Filter by post status',\n },\n limit: { type: 'number', description: 'Max results per page (default 20)' },\n page: { type: 'number', description: 'Page number (default 1)' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'get-post',\n description: 'Get a post by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-post',\n description: 'Create a new post draft for a brand on one or more platforms.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to post under' },\n text: { type: 'string', description: 'Post text content' },\n platforms: {\n type: 'string',\n description: 'Comma-separated platform list (e.g. x,linkedin)',\n },\n scheduledAt: {\n type: 'string',\n description: 'ISO 8601 datetime to schedule the post',\n },\n media: MEDIA_ITEMS,\n },\n required: ['brandSlug', 'text', 'platforms'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-post',\n description: 'Update the text, platforms, scheduled time, or media of an existing post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID' },\n text: { type: 'string', description: 'New post text' },\n platforms: { type: 'string', description: 'Comma-separated new platform list' },\n scheduledAt: { type: 'string', description: 'New ISO 8601 scheduled datetime' },\n media: MEDIA_ITEMS,\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-post',\n description: 'Permanently delete a post by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'publish-post',\n description: 'Immediately publish a post to all its platforms.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to publish' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'schedule-post',\n description: 'Schedule a post to be published at a specific date and time.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to schedule' },\n scheduledAt: { type: 'string', description: 'ISO 8601 datetime for publishing' },\n },\n required: ['id', 'scheduledAt'],\n additionalProperties: false,\n },\n },\n {\n name: 'retry-post',\n description: 'Retry publishing a failed post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to retry' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'rewrite-post',\n description: 'AI-rewrite the text of a post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to rewrite' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'score-post',\n description: 'Score a post with AI feedback and return a numeric score with explanation.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to score' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Brands\n {\n name: 'list-brands',\n description: 'List all brands in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-brand',\n description: 'Get a brand by its slug.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-brand',\n description: 'Create a new brand in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Brand display name' },\n timezone: { type: 'string', description: 'IANA timezone (e.g. America/New_York)' },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-brand',\n description: 'Update a brand name or timezone.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to update' },\n name: { type: 'string', description: 'New display name' },\n timezone: { type: 'string', description: 'New IANA timezone' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-brand',\n description: 'Permanently delete a brand by slug.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to delete' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'brand-auth-status',\n description: 'Show the platform connection status for a brand.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n\n // Agents\n {\n name: 'list-agents',\n description: 'List all agents in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-agent',\n description: 'Get an agent by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-agent',\n description: 'Create a new publish or research agent.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Agent name' },\n type: {\n type: 'string',\n enum: ['publish', 'research'],\n description: 'Agent type',\n },\n brandSlug: { type: 'string', description: 'Brand slug to associate with' },\n prompt: { type: 'string', description: 'Agent instructions or prompt' },\n frequency: {\n type: 'string',\n enum: ['manual', 'daily', 'weekly'],\n description: 'Run frequency',\n },\n time: { type: 'string', description: 'Time of day to run (HH:MM)' },\n weekday: { type: 'string', description: 'Day of week (required for weekly frequency)' },\n kbId: { type: 'string', description: 'Knowledge base ID to attach' },\n },\n required: ['name', 'type', 'prompt', 'frequency'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-agent',\n description: 'Update an agent name, prompt, frequency, or schedule.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n name: { type: 'string', description: 'New agent name' },\n prompt: { type: 'string', description: 'New prompt' },\n frequency: { type: 'string', description: 'New frequency: manual, daily, or weekly' },\n time: { type: 'string', description: 'New time of day (HH:MM)' },\n weekday: { type: 'string', description: 'New day of week' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-agent',\n description: 'Permanently delete an agent by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'run-agent',\n description: 'Trigger an immediate run of an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to run' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'toggle-agent',\n description: 'Enable or disable an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to toggle' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'agent-runs',\n description: 'List the run history for an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Knowledge Bases\n {\n name: 'list-kbs',\n description: 'List all knowledge bases in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-kb',\n description: 'Get a knowledge base by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-kb',\n description: 'Create a new knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', minLength: 4, maxLength: 20, description: 'Knowledge base name' },\n description: { type: 'string', minLength: 20, maxLength: 500, description: 'Knowledge base description' },\n },\n required: ['name', 'description'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-kb',\n description: 'Permanently delete a knowledge base by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'search-kb',\n description: 'Search a knowledge base with a text query.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to search' },\n query: { type: 'string', description: 'Search query text' },\n },\n required: ['id', 'query'],\n additionalProperties: false,\n },\n },\n {\n name: 'ingest-kb',\n description: 'Ingest a URL into a knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to ingest into' },\n url: { type: 'string', description: 'URL to ingest' },\n },\n required: ['id', 'url'],\n additionalProperties: false,\n },\n },\n {\n name: 'kb-docs',\n description: 'List documents stored in a knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Ideas\n {\n name: 'generate-ideas',\n description: 'AI-generate content ideas, optionally seeded from a knowledge base or topic.',\n inputSchema: {\n type: 'object',\n properties: {\n kbId: { type: 'string', description: 'Knowledge base ID to draw context from' },\n topic: { type: 'string', description: 'Topic or theme for idea generation' },\n count: { type: 'number', description: 'Number of ideas to generate (default 5)' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'list-ideas',\n description: 'List all saved content ideas.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'enrich-idea',\n description:\n 'Enrich an idea (title/hook/angle) into platform-ready drafts across 1..5 platforms. Async — returns a job ID.',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Idea title' },\n hook: { type: 'string', description: 'Idea hook' },\n angle: { type: 'string', description: 'Idea angle' },\n platforms: {\n type: 'array',\n description: 'Target platforms (1..5)',\n items: {\n type: 'string',\n enum: ['twitter', 'linkedin', 'instagram', 'youtube', 'threads'],\n },\n minItems: 1,\n maxItems: 5,\n },\n kbId: { type: 'string', description: 'Optional knowledge base ID for context' },\n },\n required: ['title', 'hook', 'angle', 'platforms'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-idea',\n description: 'Permanently delete an idea by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Idea ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Clips\n {\n name: 'list-clips',\n description: 'List all video clips in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-clip',\n description: 'Get a video clip by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'import-clip',\n description:\n 'Start AI clipping: import a long video from a public URL (e.g. a YouTube video). Poll get-clip until status is ready.',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL of the video to import' },\n brandId: { type: 'string', description: 'Brand ID (the `id` from list-brands)' },\n name: { type: 'string', description: 'Optional name for the imported clip' },\n },\n required: ['url', 'brandId'],\n additionalProperties: false,\n },\n },\n {\n name: 'render-clip',\n description: 'Render a clip (uses credits). Call get-clip first for its editRevision and candidates.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID to render' },\n editRevision: { type: 'number', description: 'Current editRevision from get-clip' },\n candidateId: { type: 'string', description: 'Optional: render only this candidate' },\n },\n required: ['id', 'editRevision'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-clip-draft',\n description: 'Create a draft post from a rendered clip. Publish it with publish-post or schedule it.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n candidateId: { type: 'string', description: 'Optional candidate ID (defaults to the first rendered one)' },\n aspectRatio: { type: 'string', enum: ['9:16', '16:9', '1:1', '4:5'], description: 'Optional render format' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'upload-clip',\n description:\n 'Upload a local video file for AI clipping (multipart, any size). Poll get-clip until status is ready, then render-clip.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: { type: 'string', description: 'Absolute path to the video file on this machine' },\n brandId: { type: 'string', description: 'Brand ID (the `id` from list-brands)' },\n title: { type: 'string', description: 'Optional clip title' },\n },\n required: ['filePath', 'brandId'],\n additionalProperties: false,\n },\n },\n {\n name: 'publish-clip',\n description: 'Publish, schedule, or save as a draft a rendered clip candidate.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n mode: { type: 'string', enum: ['publish', 'schedule', 'draft'] },\n candidateId: { type: 'string', description: 'Candidate to post (defaults to the best rendered one)' },\n platforms: { type: 'string', description: 'Comma-separated platforms, e.g. \"x,linkedin\"' },\n text: { type: 'string', description: 'Post caption' },\n brandSlug: { type: 'string', description: 'Brand slug' },\n scheduledAt: { type: 'string', description: 'ISO 8601 time, for mode \"schedule\"' },\n aspectRatio: { type: 'string', enum: ['9:16', '4:5', '1:1', '16:9'] },\n },\n required: ['id', 'mode'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-clip',\n description: 'Permanently delete a video clip by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Media\n {\n name: 'upload-media',\n description:\n 'Upload a local image or video and get back a media item ({url, type, altText}) to pass in create-post or update-post `media`.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: { type: 'string', description: 'Absolute path to the file on this machine' },\n altText: { type: 'string', description: 'Optional alt text' },\n },\n required: ['filePath'],\n additionalProperties: false,\n },\n },\n\n // Any other REST route\n {\n name: 'list-api-routes',\n description: 'List the REST routes api-request may call, as \"METHOD /path/:param\". Optional prefix filter, e.g. \"/clips\".',\n inputSchema: {\n type: 'object',\n properties: { prefix: { type: 'string', description: 'Only routes whose path starts with this' } },\n additionalProperties: false,\n },\n },\n {\n name: 'api-request',\n description:\n 'Call any Autoposting REST route on the allow-list (see list-api-routes) with your API key. Replace :params with real IDs.',\n inputSchema: {\n type: 'object',\n properties: {\n method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },\n path: { type: 'string', description: 'Path such as /clips/abc123/jobs, no query string' },\n query: { type: 'object', description: 'Query string parameters' },\n body: { type: 'object', description: 'JSON body for POST, PUT and PATCH' },\n },\n required: ['method', 'path'],\n additionalProperties: false,\n },\n },\n\n // Carousels\n {\n name: 'list-carousels',\n description: 'List all carousels in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-carousel',\n description: 'Get a carousel by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-carousel',\n description: 'Create a new empty carousel.',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Optional carousel title' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'generate-carousel',\n description: 'AI-generate a carousel from a topic.',\n inputSchema: {\n type: 'object',\n properties: {\n topic: { type: 'string', description: 'Topic to generate slides for' },\n brandSlug: { type: 'string', description: 'Brand slug for brand voice' },\n slideCount: { type: 'number', description: 'Number of slides to generate' },\n },\n required: ['topic'],\n additionalProperties: false,\n },\n },\n {\n name: 'draft-carousel',\n description: 'Convert a carousel into a post draft.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID to convert' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-carousel',\n description: 'Permanently delete a carousel by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Webhooks\n {\n name: 'list-webhooks',\n description: 'List all webhooks in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-webhook',\n description: 'Get a webhook by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-webhook',\n description: 'Create a new webhook endpoint for receiving events.',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'HTTPS endpoint URL to receive events' },\n events: {\n type: 'string',\n description: 'Comma-separated event types (e.g. post.published,post.failed)',\n },\n secret: { type: 'string', description: 'Optional HMAC signing secret' },\n },\n required: ['url', 'events'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-webhook',\n description: 'Update the URL, events, or active state of a webhook.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID' },\n url: { type: 'string', description: 'New endpoint URL' },\n events: { type: 'string', description: 'New comma-separated event types' },\n active: { type: 'boolean', description: 'Whether the webhook is active' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-webhook',\n description: 'Permanently delete a webhook by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'test-webhook',\n description: 'Send a test event to a webhook endpoint.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID to send the test event to' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Billing\n {\n name: 'billing-status',\n description: 'Get the current billing plan and subscription status.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'billing-credits',\n description: 'Get the current AI credit balance and usage breakdown.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n\n // Usage\n {\n name: 'usage-summary',\n description: 'Get a summary of post and publishing usage for the current period.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n]\n","import type { Autoposting } from '@autoposting.ai/sdk'\n\ntype Requester = Pick<Autoposting, 'request'>\n\n/**\n * The allow-list of REST routes an assistant may call is owned by the hosted /mcp server\n * (list-api-routes). `ap api` and local `ap mcp` fetch it from there so it has one owner.\n */\nexport async function fetchApiRoutes(client: Requester): Promise<string[]> {\n const res = await client.request<{\n result?: { content?: { text?: string }[] }\n error?: { message?: string }\n }>('POST', '/mcp', {\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/call',\n params: { name: 'list-api-routes', arguments: {} },\n })\n try {\n const routes = (JSON.parse(res.result?.content?.[0]?.text ?? '') as { routes?: unknown }).routes\n if (Array.isArray(routes)) return routes as string[]\n } catch {\n // fall through to the error below\n }\n throw new Error(`Could not load the API allow-list from the server${res.error?.message ? `: ${res.error.message}` : ''}.`)\n}\n\nconst SAFE_SEGMENT = /^[\\w\\-.~]+$/\n\n/** Throws unless METHOD PATH matches an allow-list entry (`:param` matches one segment). */\nexport function assertApiRoute(routes: readonly string[], method: string, path: string): void {\n const m = method.toUpperCase()\n const segs = path.startsWith('/') ? path.slice(1).split('/') : []\n const safe = segs.length > 0 && segs.every((s) => SAFE_SEGMENT.test(s) && s !== '.' && s !== '..')\n const match = safe && routes.some((r) => {\n const [rm, rp] = r.split(' ')\n const rs = rp.slice(1).split('/')\n return rm === m && rs.length === segs.length && rs.every((s, i) => s.startsWith(':') || s === segs[i])\n })\n if (!match) throw new Error(`${m} ${path} is not available. Run list-api-routes (or \\`ap api --list\\`) to see what is.`)\n}\n","import type { Autoposting } from '@autoposting.ai/sdk'\nimport type { CreateClipDraftParams, MediaInput, Platform } from '@autoposting.ai/sdk'\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport { readFile } from 'node:fs/promises'\nimport { basename } from 'node:path'\nimport { assertApiRoute, fetchApiRoutes } from '../lib/api-routes.js'\nimport { extToMime } from '../lib/media-flags.js'\n\ntype ToolArgs = Record<string, unknown>\nconst PLATFORMS: Platform[] = [\n 'x',\n 'linkedin',\n 'instagram',\n 'threads',\n 'youtube',\n]\nconst PLATFORM_SET = new Set<string>(PLATFORMS)\n\nfunction ok(data: unknown): CallToolResult {\n return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }\n}\n\nfunction fail(error: unknown): CallToolResult {\n const message = error instanceof Error ? error.message : String(error)\n return { content: [{ type: 'text', text: message }], isError: true }\n}\n\nfunction parsePlatforms(raw: unknown): Platform[] {\n if (typeof raw !== 'string') return []\n const platforms = raw\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean)\n const invalid = platforms.filter((platform) => !PLATFORM_SET.has(platform))\n if (invalid.length > 0) {\n throw new Error(\n `Invalid platform(s): ${invalid.join(', ')}. Expected one of: ${PLATFORMS.join(', ')}.`,\n )\n }\n return platforms as Platform[]\n}\n\n// One allow-list fetch per server process; a failed fetch is not cached, so the next call retries.\nconst routeCache = new WeakMap<object, Promise<string[]>>()\nfunction apiRoutes(client: Autoposting): Promise<string[]> {\n let routes = routeCache.get(client)\n if (!routes) {\n routes = fetchApiRoutes(client)\n routeCache.set(client, routes)\n routes.catch(() => routeCache.delete(client))\n }\n return routes\n}\n\nfunction parseEvents(raw: unknown): string[] {\n if (typeof raw !== 'string') return []\n return raw.split(',').map((e) => e.trim())\n}\n\nexport async function handleToolCall(\n name: string,\n args: ToolArgs,\n client: Autoposting,\n): Promise<CallToolResult> {\n try {\n return await dispatchToolCall(name, args, client)\n } catch (error) {\n return fail(error)\n }\n}\n\nasync function dispatchToolCall(\n name: string,\n args: ToolArgs,\n client: Autoposting,\n): Promise<CallToolResult> {\n switch (name) {\n case 'delete-account-import': return ok(await client.accountOnboarding.remove(args.id as string))\n case 'import-accounts': return ok(await client.accountOnboarding.create({ csv: args.csv as string }))\n case 'prepare-account-import': return ok(await client.accountOnboarding.prepare(args.id as string, args.offset as number | undefined))\n case 'account-import-status': return ok(await client.accountOnboarding.status(args.id as string, { ...(args.offset !== undefined ? {offset:args.offset as number}:{}), ...(args.limit !== undefined ? {limit:args.limit as number}:{}) }))\n case 'authorize-import-account': return ok(await client.accountOnboarding.authorize(args.id as string, args.rowId as string))\n case 'confirm-import-account': return ok(await client.accountOnboarding.confirm(args.id as string, args.rowId as string, args.tokenId as string))\n // Posts\n case 'list-posts': {\n const result = await client.posts.list({\n brandSlug: args.brandSlug as string | undefined,\n status: args.status as\n | 'draft'\n | 'scheduled'\n | 'published'\n | 'failed'\n | undefined,\n limit: args.limit as number | undefined,\n page: args.page as number | undefined,\n })\n return ok(result)\n }\n case 'get-post': {\n const result = await client.posts.getById(args.id as string)\n return ok(result)\n }\n case 'create-post': {\n const result = await client.posts.create({\n brandSlug: args.brandSlug as string,\n text: args.text as string,\n platforms: parsePlatforms(args.platforms),\n ...(args.scheduledAt\n ? { scheduledAt: args.scheduledAt as string }\n : {}),\n ...(args.media ? { media: args.media as MediaInput[] } : {}),\n })\n return ok(result)\n }\n case 'update-post': {\n const result = await client.posts.update(args.id as string, {\n ...(args.text ? { text: args.text as string } : {}),\n ...(args.platforms\n ? {\n platforms: parsePlatforms(args.platforms),\n }\n : {}),\n ...(args.scheduledAt\n ? { scheduledAt: args.scheduledAt as string }\n : {}),\n ...(args.media ? { media: args.media as MediaInput[] } : {}),\n })\n return ok(result)\n }\n case 'delete-post': {\n await client.posts.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'publish-post': {\n const result = await client.posts.publish(args.id as string)\n return ok(result)\n }\n case 'schedule-post': {\n const result = await client.posts.schedule(\n args.id as string,\n args.scheduledAt as string,\n )\n return ok(result)\n }\n case 'retry-post': {\n const result = await client.posts.retry(args.id as string)\n return ok(result)\n }\n case 'rewrite-post': {\n const result = await client.posts.rewrite(args.id as string)\n return ok(result)\n }\n case 'score-post': {\n const result = await client.posts.score(args.id as string)\n return ok(result)\n }\n\n // Brands\n case 'list-brands': {\n const result = await client.brands.list()\n return ok(result)\n }\n case 'get-brand': {\n const result = await client.brands.retrieve(args.brandSlug as string)\n return ok(result)\n }\n case 'create-brand': {\n const result = await client.brands.create({\n name: args.name as string,\n ...(args.timezone ? { timezone: args.timezone as string } : {}),\n })\n return ok(result)\n }\n case 'update-brand': {\n const result = await client.brands.update(args.brandSlug as string, {\n ...(args.name ? { name: args.name as string } : {}),\n ...(args.timezone ? { timezone: args.timezone as string } : {}),\n })\n return ok(result)\n }\n case 'delete-brand': {\n await client.brands.remove(args.brandSlug as string)\n return ok({ deleted: true, brandSlug: args.brandSlug })\n }\n case 'brand-auth-status': {\n const result = await client.brands.authStatus(args.brandSlug as string)\n return ok(result)\n }\n\n // Agents\n case 'list-agents': {\n const result = await client.agents.list()\n return ok(result)\n }\n case 'get-agent': {\n const result = await client.agents.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-agent': {\n const result = await client.agents.create({\n name: args.name as string,\n type: args.type as 'publish' | 'research',\n prompt: args.prompt as string,\n frequency: args.frequency as 'manual' | 'daily' | 'weekly',\n ...(args.brandSlug ? { brandSlug: args.brandSlug as string } : {}),\n ...(args.time ? { time: args.time as string } : {}),\n ...(args.weekday ? { weekday: args.weekday as string } : {}),\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n })\n return ok(result)\n }\n case 'update-agent': {\n const result = await client.agents.update(args.id as string, {\n ...(args.name ? { name: args.name as string } : {}),\n ...(args.prompt ? { prompt: args.prompt as string } : {}),\n ...(args.frequency ? { frequency: args.frequency as string } : {}),\n ...(args.time ? { time: args.time as string } : {}),\n ...(args.weekday ? { weekday: args.weekday as string } : {}),\n })\n return ok(result)\n }\n case 'delete-agent': {\n await client.agents.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'run-agent': {\n const result = await client.agents.run(args.id as string)\n return ok(result)\n }\n case 'toggle-agent': {\n const result = await client.agents.toggle(args.id as string)\n return ok(result)\n }\n case 'agent-runs': {\n const result = await client.agents.runs(args.id as string)\n return ok(result)\n }\n\n // Knowledge Bases\n case 'list-kbs': {\n const result = await client.kb.list()\n return ok(result)\n }\n case 'get-kb': {\n const result = await client.kb.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-kb': {\n const result = await client.kb.create({ name: args.name as string, description: args.description as string })\n return ok(result)\n }\n case 'delete-kb': {\n await client.kb.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'search-kb': {\n const result = await client.kb.search(\n args.id as string,\n args.query as string,\n )\n return ok(result)\n }\n case 'ingest-kb': {\n const result = await client.kb.ingestUrl(\n args.id as string,\n args.url as string,\n )\n return ok(result)\n }\n case 'kb-docs': {\n const result = await client.kb.docs(args.id as string)\n return ok(result)\n }\n\n // Ideas\n case 'generate-ideas': {\n const result = await client.ideas.generate({\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n ...(args.topic ? { topic: args.topic as string } : {}),\n ...(args.count ? { count: args.count as number } : {}),\n })\n return ok(result)\n }\n case 'list-ideas': {\n const result = await client.ideas.list()\n return ok(result)\n }\n case 'enrich-idea': {\n const result = await client.ideas.enrich({\n idea: {\n title: args.title as string,\n hook: args.hook as string,\n angle: args.angle as string,\n },\n platforms: (args.platforms as string[]).map((platform) => ({\n platform: platform as 'twitter' | 'linkedin' | 'instagram' | 'youtube' | 'threads',\n })),\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n })\n return ok(result)\n }\n case 'delete-idea': {\n await client.ideas.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Clips\n case 'list-clips': {\n const result = await client.clips.list()\n return ok(result)\n }\n case 'get-clip': {\n const result = await client.clips.retrieve(args.id as string)\n return ok(result)\n }\n case 'import-clip': {\n const result = await client.clips.importUrl({\n url: args.url as string,\n brandId: args.brandId as string,\n ...(args.name ? { title: args.name as string } : {}),\n })\n return ok(result)\n }\n case 'render-clip': {\n const result = await client.clips.render(args.id as string, {\n editRevision: args.editRevision as number,\n ...(args.candidateId ? { candidateId: args.candidateId as string } : {}),\n })\n return ok(result)\n }\n case 'create-clip-draft': {\n const result = await client.clips.createDraft(args.id as string, {\n ...(args.candidateId ? { candidateId: args.candidateId as string } : {}),\n ...(args.aspectRatio ? { aspectRatio: args.aspectRatio as CreateClipDraftParams['aspectRatio'] } : {}),\n })\n return ok(result)\n }\n case 'upload-clip': {\n const result = await client.clips.upload(args.filePath as string, {\n brandId: args.brandId as string,\n ...(args.title ? { title: args.title as string } : {}),\n })\n return ok(result)\n }\n case 'publish-clip': {\n const body: Record<string, unknown> = { mode: args.mode }\n for (const k of ['candidateId', 'text', 'brandSlug', 'scheduledAt', 'aspectRatio']) {\n if (args[k] !== undefined) body[k] = args[k]\n }\n if (args.platforms !== undefined) body.platforms = parsePlatforms(args.platforms)\n return ok(await client.request('POST', `/clips/${encodeURIComponent(args.id as string)}/publish`, body))\n }\n case 'delete-clip': {\n await client.clips.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Carousels\n case 'list-carousels': {\n const result = await client.carousels.list()\n return ok(result)\n }\n case 'get-carousel': {\n const result = await client.carousels.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-carousel': {\n const result = await client.carousels.create(\n args.title ? { title: args.title as string } : undefined,\n )\n return ok(result)\n }\n case 'generate-carousel': {\n const result = await client.carousels.generate({\n topic: args.topic as string,\n ...(args.brandSlug ? { brandSlug: args.brandSlug as string } : {}),\n ...(args.slideCount ? { slideCount: args.slideCount as number } : {}),\n })\n return ok(result)\n }\n case 'draft-carousel': {\n const result = await client.carousels.draft(args.id as string)\n return ok(result)\n }\n case 'delete-carousel': {\n await client.carousels.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Webhooks\n case 'list-webhooks': {\n const result = await client.webhooks.list()\n return ok(result)\n }\n case 'get-webhook': {\n const result = await client.webhooks.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-webhook': {\n const result = await client.webhooks.create({\n url: args.url as string,\n events: parseEvents(args.events),\n ...(args.secret ? { secret: args.secret as string } : {}),\n })\n return ok(result)\n }\n case 'update-webhook': {\n const result = await client.webhooks.update(args.id as string, {\n ...(args.url ? { url: args.url as string } : {}),\n ...(args.events ? { events: parseEvents(args.events) } : {}),\n ...(args.active !== undefined\n ? { active: args.active as boolean }\n : {}),\n })\n return ok(result)\n }\n case 'delete-webhook': {\n await client.webhooks.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'test-webhook': {\n await client.webhooks.test(args.id as string)\n return ok({ sent: true, id: args.id })\n }\n\n // Media\n case 'upload-media': {\n const filePath = args.filePath as string\n const filename = basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(await readFile(filePath)),\n filename,\n contentType: extToMime(filename),\n })\n return ok({ url: uploaded.url, type: uploaded.type, ...(args.altText ? { altText: args.altText } : {}) })\n }\n\n // Any other REST route on the server's allow-list\n case 'list-api-routes': {\n const prefix = typeof args.prefix === 'string' ? args.prefix : '/'\n const routes = await apiRoutes(client)\n return ok({ routes: routes.filter((r) => r.split(' ')[1].startsWith(prefix)) })\n }\n case 'api-request': {\n const method = String(args.method ?? '').toUpperCase()\n const path = String(args.path ?? '')\n assertApiRoute(await apiRoutes(client), method, path)\n const query = typeof args.query === 'object' && args.query ? (args.query as Record<string, unknown>) : undefined\n const body = method !== 'GET' && method !== 'DELETE' && typeof args.body === 'object' && args.body ? args.body : undefined\n return ok(await client.request(method as never, path, body, query))\n }\n\n // Billing\n case 'billing-status': {\n const result = await client.billing.status()\n return ok(result)\n }\n case 'billing-credits': {\n const result = await client.billing.credits()\n return ok(result)\n }\n\n // Usage\n case 'usage-summary': {\n const result = await client.usage.summary()\n return ok(result)\n }\n\n default:\n return {\n content: [{ type: 'text', text: `Unknown tool: ${name}` }],\n isError: true,\n }\n }\n}\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { Autoposting, VERSION } from '@autoposting.ai/sdk'\nimport { ALL_TOOLS } from './tools.js'\nimport { handleToolCall } from './handler.js'\n\nexport async function startMcpServer(): Promise<void> {\n const client = new Autoposting() // reads AUTOPOSTING_API_KEY from env\n\n const server = new Server(\n { name: 'autoposting-mcp', version: VERSION },\n { capabilities: { tools: {} } },\n )\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: ALL_TOOLS,\n }))\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n return handleToolCall(name, (args ?? {}) as Record<string, unknown>, client)\n })\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","#!/usr/bin/env node\nimport { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { createAgentsCommand } from './commands/agents.js'\nimport { createAuthCommand } from './commands/auth.js'\nimport { createBillingCommand } from './commands/billing.js'\nimport { createAccountsCommand } from './commands/accounts.js'\nimport { createBrandsCommand } from './commands/brands.js'\nimport { createCarouselsCommand } from './commands/carousels.js'\nimport { createClipsCommand } from './commands/clips.js'\nimport { createPostsCommand } from './commands/posts.js'\nimport { createKbCommand } from './commands/kb.js'\nimport { createIdeasCommand } from './commands/ideas.js'\nimport { createUsageCommand } from './commands/usage.js'\nimport { createWebhooksCommand } from './commands/webhooks.js'\nimport { createWorkspacesCommand } from './commands/workspaces.js'\nimport { createDoctorCommand } from './commands/doctor.js'\nimport { createWhoamiCommand } from './commands/whoami.js'\nimport { createOpenCommand } from './commands/open.js'\nimport { createUpdateCommand } from './commands/update.js'\nimport { createCompletionCommand } from './commands/completion.js'\nimport { createMcpCommand } from './commands/mcp.js'\nimport { createConfigCommand } from './commands/config.js'\nimport { createApiCommand } from './commands/api.js'\nimport { disableColor } from './output/index.js'\n\nconst program = new Command()\n .name('autoposting')\n .description('Autoposting CLI — manage social media from the terminal')\n .version(VERSION)\n .option('--json', 'Output as JSON')\n .option('--quiet', 'Suppress spinners and non-essential output')\n .option('--format <type>', 'Output format: auto (table on a terminal, JSON when piped), table, json', 'auto')\n .option('--jq <expr>', 'Filter JSON output with a minimal jq expression (e.g. \".[].id\")')\n .option('--api-key <key>', 'API key (overrides env/stored credentials)')\n .option('--no-color', 'Disable color output')\n .hook('preAction', (thisCommand) => {\n const opts = thisCommand.opts<{ color: boolean }>()\n if (!opts.color) disableColor()\n })\n\nprogram.addCommand(createAuthCommand())\nprogram.addCommand(createBillingCommand())\nprogram.addCommand(createAccountsCommand())\nprogram.addCommand(createBrandsCommand())\nprogram.addCommand(createCarouselsCommand())\nprogram.addCommand(createClipsCommand())\nprogram.addCommand(createApiCommand())\nprogram.addCommand(createPostsCommand())\nprogram.addCommand(createAgentsCommand())\nprogram.addCommand(createKbCommand())\nprogram.addCommand(createIdeasCommand())\nprogram.addCommand(createUsageCommand())\nprogram.addCommand(createWebhooksCommand())\nprogram.addCommand(createWorkspacesCommand())\nprogram.addCommand(createDoctorCommand())\nprogram.addCommand(createWhoamiCommand())\nprogram.addCommand(createOpenCommand())\nprogram.addCommand(createUpdateCommand())\nprogram.addCommand(createCompletionCommand())\nprogram.addCommand(createMcpCommand())\nprogram.addCommand(createConfigCommand())\n\nprogram.parse()\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createAgentsCommand(): Command {\n const agents = new Command('agents').description('Manage agents')\n\n // ap agents list\n agents\n .command('list')\n .description('List all agents')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching agents…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.agents.list()\n spinner.stop()\n const rows = list.items.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n brand: a.brandSlug ?? '—',\n frequency: a.frequency,\n enabled: a.enabled ? 'yes' : 'no',\n }))\n printer.table(rows, ['id', 'name', 'type', 'brand', 'frequency', 'enabled'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents get <id>\n agents\n .command('get <id>')\n .description('Get an agent by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.retrieve(id)\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents create --name <name> --type <publish|research> [--brand <slug>] --prompt <text> --frequency <manual|daily|weekly>\n agents\n .command('create')\n .description('Create a new agent')\n .requiredOption('--name <name>', 'Agent name')\n .requiredOption('--type <type>', 'Agent type: publish or research')\n .option('--brand <slug>', 'Brand slug to associate with')\n .requiredOption('--prompt <text>', 'Agent prompt / instructions')\n .requiredOption('--frequency <freq>', 'Run frequency: manual, daily, or weekly')\n .option('--time <HH:MM>', 'Time of day to run (required for daily/weekly)')\n .option('--weekday <day>', 'Day of week to run (required for weekly)')\n .option('--kb <id>', 'Knowledge base ID to attach')\n .action(\n async (\n opts: {\n name: string\n type: string\n brand?: string\n prompt: string\n frequency: string\n time?: string\n weekday?: string\n kb?: string\n },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating agent…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.create({\n name: opts.name,\n type: opts.type as 'publish' | 'research',\n prompt: opts.prompt,\n frequency: opts.frequency as 'manual' | 'daily' | 'weekly',\n ...(opts.brand ? { brandSlug: opts.brand } : {}),\n ...(opts.time ? { time: opts.time } : {}),\n ...(opts.weekday ? { weekday: opts.weekday } : {}),\n ...(opts.kb ? { kbId: opts.kb } : {}),\n })\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap agents update <id> [--name] [--prompt] [--frequency] [--time] [--weekday]\n agents\n .command('update <id>')\n .description('Update an agent')\n .option('--name <name>', 'New agent name')\n .option('--prompt <text>', 'New prompt / instructions')\n .option('--frequency <freq>', 'New frequency: manual, daily, or weekly')\n .option('--time <HH:MM>', 'New time of day')\n .option('--weekday <day>', 'New day of week')\n .action(\n async (\n id: string,\n opts: { name?: string; prompt?: string; frequency?: string; time?: string; weekday?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.update(id, {\n ...(opts.name ? { name: opts.name } : {}),\n ...(opts.prompt ? { prompt: opts.prompt } : {}),\n ...(opts.frequency ? { frequency: opts.frequency } : {}),\n ...(opts.time ? { time: opts.time } : {}),\n ...(opts.weekday ? { weekday: opts.weekday } : {}),\n })\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap agents delete <id> --force\n agents\n .command('delete <id>')\n .description('Delete an agent (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete an agent. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.agents.remove(id)\n spinner.stop()\n printer.log(`Agent \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents run <id>\n agents\n .command('run <id>')\n .description('Trigger an agent run immediately')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Running agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const queued = await client.agents.run(id)\n spinner.stop()\n printer.log({ runId: queued.runId, status: queued.status })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents toggle <id>\n agents\n .command('toggle <id>')\n .description('Enable or disable an agent')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Toggling agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.toggle(id)\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents runs <id>\n agents\n .command('runs <id>')\n .description('List run history for an agent')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching runs for agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.agents.runs(id)\n spinner.stop()\n const rows = list.items.map((r) => ({\n id: r.id,\n status: r.status,\n output: r.output ? (r.output.length > 60 ? `${r.output.slice(0, 57)}…` : r.output) : '—',\n createdAt: r.createdAt,\n }))\n printer.table(rows, ['id', 'status', 'output', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return agents\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nexport interface StoredProfile {\n apiKey: string\n workspace?: string\n email?: string\n createdAt: string\n}\n\nexport interface CredentialsFile {\n activeProfile: string\n profiles: Record<string, StoredProfile>\n}\n\nexport function getCredentialsPath(): string {\n // Per the XDG spec, XDG_CONFIG_HOME is honoured only when set to an absolute path;\n // empty or relative values must be ignored and fall back to ~/.config.\n const xdg = process.env.XDG_CONFIG_HOME\n const configBase = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config')\n return path.join(configBase, 'autoposting', 'credentials.json')\n}\n\nexport function readCredentials(): CredentialsFile | null {\n const filePath = getCredentialsPath()\n try {\n const raw = fs.readFileSync(filePath, 'utf8')\n return JSON.parse(raw) as CredentialsFile\n } catch {\n // Missing or corrupt file — return null gracefully\n return null\n }\n}\n\nexport function writeCredentials(creds: CredentialsFile): void {\n const filePath = getCredentialsPath()\n const dir = path.dirname(filePath)\n\n // Use { recursive: true } so mkdirSync is idempotent (avoids TOCTOU race between\n // existsSync + mkdirSync). Mode 0o700 ensures only the owning user can read the dir.\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n\n // Write to a temp file then rename — an atomic swap on the same filesystem, so a\n // crash or a concurrent writer can never leave a half-written credentials file.\n const tmpPath = `${filePath}.${process.pid}.tmp`\n try {\n fs.writeFileSync(tmpPath, JSON.stringify(creds, null, 2), { encoding: 'utf8', mode: 0o600 })\n fs.renameSync(tmpPath, filePath)\n } catch (err) {\n // Don't leave a half-written temp file behind on a disk-full / permission failure.\n try {\n fs.unlinkSync(tmpPath)\n } catch {\n // temp file never created or already gone — nothing to clean up\n }\n throw err\n }\n\n // Ensure 0600 even if file already existed before\n fs.chmodSync(filePath, 0o600)\n}\n\nexport function saveProfile(name: string, profile: StoredProfile): void {\n const existing = readCredentials()\n // readCredentials() returns null for BOTH missing and corrupt files. If the file is\n // present but unparseable, preserve it (rename to .corrupt) instead of silently\n // dropping every other stored profile by overwriting with a fresh file.\n if (!existing && fs.existsSync(getCredentialsPath())) {\n try {\n fs.renameSync(getCredentialsPath(), `${getCredentialsPath()}.corrupt`)\n } catch {\n // best-effort backup — proceed to write a fresh file regardless\n }\n }\n const creds: CredentialsFile = existing ?? { activeProfile: name, profiles: {} }\n creds.profiles[name] = profile\n creds.activeProfile = name\n writeCredentials(creds)\n}\n\nexport function deleteProfile(name: string): void {\n const creds = readCredentials()\n if (!creds) return\n\n delete creds.profiles[name]\n\n // If deleted profile was active, clear active or pick another\n if (creds.activeProfile === name) {\n const remaining = Object.keys(creds.profiles)\n creds.activeProfile = remaining[0] ?? ''\n }\n\n writeCredentials(creds)\n}\n\nexport function deleteAllProfiles(): void {\n writeCredentials({ activeProfile: '', profiles: {} })\n}\n\nexport function getActiveProfile(): StoredProfile | null {\n const creds = readCredentials()\n if (!creds || !creds.activeProfile) return null\n return creds.profiles[creds.activeProfile] ?? null\n}\n\nexport function setActiveProfile(name: string): void {\n const creds = readCredentials()\n if (!creds) throw new Error(`Profile \"${name}\" does not exist (no credentials file)`)\n if (!creds.profiles[name]) throw new Error(`Profile \"${name}\" does not exist`)\n creds.activeProfile = name\n writeCredentials(creds)\n}\n","import { getActiveProfile, getCredentialsPath } from './credential-store.js'\n\nexport interface AuthCredentials {\n apiKey: string\n source: 'flag' | 'env' | 'stored'\n profile?: string\n}\n\nexport { getCredentialsPath }\n\n/**\n * Resolves credentials using priority chain:\n * 1. --api-key flag (explicit)\n * 2. AUTOPOSTING_API_KEY env var\n * 3. Stored credentials from file (active profile)\n *\n * Throws with exit-code-2-compatible error when no auth is available.\n */\nexport function resolveAuth(options?: { apiKey?: string }): AuthCredentials {\n // 1. Explicit flag\n if (options?.apiKey) {\n return { apiKey: options.apiKey, source: 'flag' }\n }\n\n // 2. Env var\n const envKey = process.env.AUTOPOSTING_API_KEY\n if (envKey) {\n return { apiKey: envKey, source: 'env' }\n }\n\n // 3. Stored profile\n const profile = getActiveProfile()\n if (profile?.apiKey) {\n return { apiKey: profile.apiKey, source: 'stored' }\n }\n\n const err = new Error(\n 'No API key found. Run `ap auth login --api-key <key>` or set AUTOPOSTING_API_KEY.',\n )\n ;(err as NodeJS.ErrnoException & { exitCode?: number }).exitCode = 2\n throw err\n}\n","// ANSI color codes — no chalk dependency to keep bundle small\nconst RED = '\\x1b[31m'\nconst RESET = '\\x1b[0m'\n\nlet colorEnabled = true\n\nexport function disableColor(): void {\n colorEnabled = false\n}\n\nfunction red(text: string): string {\n if (!colorEnabled || !process.stdout.isTTY) return text\n return `${RED}${text}${RESET}`\n}\n\nexport type OutputMode = 'tty' | 'json' | 'quiet'\n\nexport interface OutputOptions {\n json?: boolean\n quiet?: boolean\n format?: 'auto' | 'table' | 'json'\n jq?: string\n color?: boolean\n}\n\nexport function detectOutputMode(options: OutputOptions): OutputMode {\n if (options.quiet) return 'quiet'\n // An explicit --format/--json wins over auto-detection; otherwise (auto/unset)\n // fall back to JSON when output is piped (non-TTY) and a human table when\n // attached to a terminal — the gh/clig.dev \"machine-readable when not a TTY\" rule.\n if (options.format === 'json' || options.json) return 'json'\n if (options.format === 'table') return 'tty'\n if (!process.stdout.isTTY) return 'json'\n return 'tty'\n}\n\nexport function formatOutput(data: unknown, mode: OutputMode): string {\n if (mode === 'quiet') return ''\n if (mode === 'json') return JSON.stringify(data, null, 2)\n // tty: pretty-print objects or stringify primitives\n if (typeof data === 'string') return data\n return JSON.stringify(data, null, 2)\n}\n\nexport function formatTable(\n rows: Record<string, unknown>[],\n columns?: string[],\n): string {\n if (rows.length === 0) return ''\n\n const cols = columns ?? Object.keys(rows[0]!)\n const widths: number[] = cols.map((col) => col.length)\n\n // Compute max widths\n for (const row of rows) {\n for (let i = 0; i < cols.length; i++) {\n const val = String(row[cols[i]!] ?? '')\n if (val.length > widths[i]!) widths[i] = val.length\n }\n }\n\n const pad = (s: string, w: number) => s.padEnd(w, ' ')\n const separator = widths.map((w) => '-'.repeat(w)).join(' ')\n\n const header = cols.map((c, i) => pad(c.toUpperCase(), widths[i]!)).join(' ')\n const dataRows = rows.map((row) =>\n cols.map((c, i) => pad(String(row[c] ?? ''), widths[i]!)).join(' '),\n )\n\n return [header, separator, ...dataRows].join('\\n')\n}\n\nexport function formatError(error: Error | string, mode: OutputMode): string {\n const message = error instanceof Error ? error.message : error\n if (mode === 'tty') return red(`Error: ${message}`)\n // json and quiet both return JSON error — errors always show\n return JSON.stringify({ error: message }, null, 2)\n}\n\ntype JqOp = { type: 'prop'; name: string } | { type: 'iter' } | { type: 'index'; n: number }\n\n// ponytail: minimal jq subset — `.`, `.a.b`, `.[]`, `.foo[]`, `.[0]`, and any\n// chain of those (covers the `.[].id` / `.field` cases the scripting ICP pipes).\n// NOT real jq: no pipes, filters, functions, or object construction. If users\n// need those, add the `jaq`/`node-jq` dependency and delegate — don't grow this.\nfunction parseJq(expr: string): JqOp[] {\n const e = expr.trim()\n if (e === '' || e === '.') return []\n if (!e.startsWith('.')) {\n throw new Error(`--jq: expression must start with \".\" (got \"${expr}\")`)\n }\n const body = e.slice(1)\n const ops: JqOp[] = []\n let i = 0\n while (i < body.length) {\n const ch = body[i]!\n if (ch === '.') {\n i++\n continue\n }\n if (ch === '[') {\n const close = body.indexOf(']', i)\n if (close === -1) throw new Error(`--jq: unclosed \"[\" in \"${expr}\"`)\n const inner = body.slice(i + 1, close).trim()\n if (inner === '') {\n ops.push({ type: 'iter' })\n } else {\n const n = Number(inner)\n if (!Number.isInteger(n)) throw new Error(`--jq: invalid index \"[${inner}]\" in \"${expr}\"`)\n ops.push({ type: 'index', n })\n }\n i = close + 1\n continue\n }\n const m = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(body.slice(i))\n if (!m) throw new Error(`--jq: unexpected character \"${ch}\" in \"${expr}\"`)\n ops.push({ type: 'prop', name: m[0] })\n i += m[0].length\n }\n return ops\n}\n\n/**\n * Applies a minimal jq-subset expression to a value, returning the output stream\n * (one entry per produced value). Throws on a malformed expression or an op that\n * doesn't fit the value (e.g. iterating a scalar) so callers exit non-zero.\n */\nexport function applyJq(data: unknown, expr: string): unknown[] {\n const ops = parseJq(expr)\n let stream: unknown[] = [data]\n for (const op of ops) {\n const next: unknown[] = []\n for (const v of stream) {\n if (op.type === 'prop') {\n next.push(v == null ? null : ((v as Record<string, unknown>)[op.name] ?? null))\n } else if (op.type === 'index') {\n if (!Array.isArray(v)) throw new Error(`--jq: cannot index non-array with [${op.n}]`)\n const idx = op.n < 0 ? v.length + op.n : op.n\n next.push(v[idx] ?? null)\n } else {\n if (Array.isArray(v)) next.push(...v)\n else if (v && typeof v === 'object') next.push(...Object.values(v))\n else throw new Error(`--jq: cannot iterate over ${v === null ? 'null' : typeof v} — .[] needs an array or object`)\n }\n }\n stream = next\n }\n return stream\n}\n\n/** Renders a jq output stream: raw strings (unquoted, for piping), JSON for the rest. */\nexport function formatJq(data: unknown, expr: string): string {\n return applyJq(data, expr)\n .map((r) => (typeof r === 'string' ? r : r === undefined ? 'null' : JSON.stringify(r)))\n .join('\\n')\n}\n","import type { OutputMode } from './formatter.js'\n\nexport interface Spinner {\n start(message: string): void\n stop(message?: string): void\n // Mark the in-flight operation as failed (✖). Message optional: a catch block\n // typically fails the spinner, then prints the real error separately.\n fail(message?: string): void\n}\n\n// No-op spinner for JSON/quiet modes — no TTY output during machine-readable runs\nconst NO_OP_SPINNER: Spinner = {\n start: () => {},\n stop: () => {},\n fail: () => {},\n}\n\n// TTY spinner backed by ora (dynamic import for CJS compatibility)\nclass OraSpinner implements Spinner {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private instance: any = null\n\n start(message: string): void {\n import('ora').then(({ default: ora }) => {\n this.instance = ora(message).start()\n }).catch(() => {\n // ora unavailable — fall back to plain stdout\n process.stdout.write(`${message}\\n`)\n })\n }\n\n stop(message?: string): void {\n if (this.instance) {\n this.instance.succeed(message)\n this.instance = null\n } else if (message) {\n process.stdout.write(`${message}\\n`)\n }\n }\n\n fail(message?: string): void {\n if (this.instance) {\n // ora.fail(undefined) keeps the original spinner text but marks it ✖.\n this.instance.fail(message)\n this.instance = null\n } else if (message) {\n process.stderr.write(`${message}\\n`)\n }\n }\n}\n\nexport function createSpinner(mode: OutputMode): Spinner {\n if (mode === 'tty') return new OraSpinner()\n return NO_OP_SPINNER\n}\n","import { type OutputMode, type OutputOptions, formatOutput, formatTable, formatError, formatJq, detectOutputMode } from './formatter.js'\nimport { createSpinner, type Spinner } from './spinner.js'\n\nexport class Printer {\n constructor(\n private mode: OutputMode,\n // When set, every log/table is run through the minimal jq filter instead of\n // the human/JSON renderer. A bad expression throws — caught by the command's\n // catch block, which prints the message and exits non-zero (no stack trace).\n private jq?: string,\n ) {}\n\n /** True only for human-readable output, where extra hint lines are safe to print. */\n isTty(): boolean {\n return this.mode === 'tty' && !this.jq\n }\n\n log(data: unknown): void {\n if (this.jq) return this.emitJq(data)\n const out = formatOutput(data, this.mode)\n if (out !== '') console.log(out)\n }\n\n table(rows: Record<string, unknown>[], columns?: string[]): void {\n if (this.jq) return this.emitJq(rows)\n if (this.mode === 'quiet') return\n if (this.mode === 'json') {\n console.log(formatOutput(rows, 'json'))\n return\n }\n const out = formatTable(rows, columns)\n if (out !== '') console.log(out)\n }\n\n private emitJq(data: unknown): void {\n // --jq implies machine output regardless of TTY; a bad expr throws here.\n const out = formatJq(data, this.jq!)\n if (out !== '') console.log(out)\n }\n\n error(err: Error | string): void {\n // Errors never run through jq — they go to stderr as plain/JSON per mode.\n const out = formatError(err, this.jq ? 'json' : this.mode)\n console.error(out)\n }\n\n spinner(message: string): Spinner {\n // A jq run is machine output — suppress the spinner so it can't leak into stdout.\n const s = createSpinner(this.jq ? 'json' : this.mode)\n s.start(message)\n return s\n }\n}\n\nexport function createPrinter(options: OutputOptions): Printer {\n const mode = detectOutputMode(options)\n return new Printer(mode, options.jq)\n}\n","export const EXIT_CODES = {\n SUCCESS: 0,\n GENERAL_ERROR: 1,\n AUTH_ERROR: 2,\n SCOPE_ERROR: 3,\n NOT_FOUND: 4,\n RATE_LIMITED: 5,\n VALIDATION_ERROR: 6,\n NETWORK_ERROR: 7,\n} as const\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES]\n\n// Named sentinel classes used for instanceof checks against @autoposting.ai/sdk errors.\n// We match by constructor name so this works even if the SDK hasn't shipped error\n// classes yet (dynamic require would silently fail). When the SDK exports these\n// classes they will inherit from AutopostingError and carry the same names.\nfunction matchesClass(error: unknown, className: string): boolean {\n if (error == null || typeof error !== 'object') return false\n // Walk prototype chain checking constructor names\n let proto = Object.getPrototypeOf(error) as object | null\n while (proto !== null) {\n const ctor = (proto as { constructor?: { name?: string } }).constructor\n if (ctor?.name === className) return true\n proto = Object.getPrototypeOf(proto) as object | null\n }\n return false\n}\n\nexport function exitCodeFromError(error: unknown): ExitCode {\n // An explicit numeric `exitCode` (e.g. attached by resolveAuth for missing/invalid\n // credentials) takes precedence over class-name matching, so every command — not\n // just the ones with a local wrapper — exits with the right code.\n const attached = (error as { exitCode?: number } | null)?.exitCode\n if (typeof attached === 'number' && Number.isInteger(attached) && attached >= 0) {\n return attached as ExitCode\n }\n if (matchesClass(error, 'AuthenticationError')) return EXIT_CODES.AUTH_ERROR\n if (matchesClass(error, 'ScopeError')) return EXIT_CODES.SCOPE_ERROR\n if (matchesClass(error, 'NotFoundError')) return EXIT_CODES.NOT_FOUND\n if (matchesClass(error, 'RateLimitError')) return EXIT_CODES.RATE_LIMITED\n if (matchesClass(error, 'ValidationError')) return EXIT_CODES.VALIDATION_ERROR\n if (matchesClass(error, 'NetworkError')) return EXIT_CODES.NETWORK_ERROR\n // SDK transport failures are an AutopostingError carrying a string `code`, not a\n // dedicated class — match on the code so timeouts/network drops map to exit 7.\n const code = (error as { code?: unknown } | null)?.code\n if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return EXIT_CODES.NETWORK_ERROR\n return EXIT_CODES.GENERAL_ERROR\n}\n","import { Command } from 'commander'\nimport { execSync } from 'node:child_process'\nimport {\n deleteAllProfiles,\n deleteProfile,\n getActiveProfile,\n readCredentials,\n saveProfile,\n setActiveProfile,\n} from '../auth/credential-store.js'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { requestDeviceCode, pollDeviceCode } from '../auth/device-code-client.js'\n\n// Backend auth routes (/auth/cli/*) are reached via the frontend /api-proxy rewrite.\nconst DEFAULT_BASE_URL = 'https://app.autoposting.ai/api-proxy'\n\nfunction resolveBaseUrl(globals: { baseUrl?: string }): string {\n return globals.baseUrl ?? process.env.AUTOPOSTING_BASE_URL ?? DEFAULT_BASE_URL\n}\n\nfunction tryOpenUrl(url: string): void {\n try {\n // Attempt to open browser; ignore failures (CI, headless, etc.)\n const platform = process.platform\n if (platform === 'darwin') execSync(`open \"${url}\"`, { stdio: 'ignore' })\n else if (platform === 'win32') execSync(`start \"\" \"${url}\"`, { stdio: 'ignore' })\n else execSync(`xdg-open \"${url}\"`, { stdio: 'ignore' })\n } catch {\n // Non-fatal: user can open URL manually\n }\n}\n\nexport function createAuthCommand(): Command {\n const auth = new Command('auth').description('Manage authentication and profiles')\n\n // ap auth login [--api-key <key>] [--profile <name>] [--base-url <url>]\n // Note: --api-key is also a root-level global option on the program. Commander consumes\n // options left-to-right so the root picks it up first. We use optsWithGlobals() to\n // merge root + local options and read whichever level captured the flag.\n auth\n .command('login')\n .description('Log in via browser device code flow, or store an API key directly with --api-key')\n .option('--api-key <key>', 'API key to store directly (skips device code flow)')\n .option('--profile <name>', 'Profile name to save under', 'default')\n .option('--base-url <url>', 'API base URL (overrides AUTOPOSTING_BASE_URL)')\n .action(async (localOpts: { apiKey?: string; profile: string; baseUrl?: string }, cmd: Command) => {\n const opts = cmd.optsWithGlobals<{ apiKey?: string; profile: string; baseUrl?: string }>()\n\n // Fast path: --api-key provided, store directly\n if (opts.apiKey) {\n saveProfile(opts.profile, {\n apiKey: opts.apiKey,\n createdAt: new Date().toISOString(),\n })\n console.log(`Logged in. Profile \"${opts.profile}\" saved.`)\n return\n }\n\n // Device code flow\n const baseUrl = resolveBaseUrl(opts)\n\n let deviceCodeResp\n try {\n deviceCodeResp = await requestDeviceCode(baseUrl)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n\n const { deviceCode, userCode, verificationUri } = deviceCodeResp\n let pollInterval = deviceCodeResp.interval\n\n console.log(`\\nEnter code ${userCode} at ${verificationUri}\\n`)\n tryOpenUrl(verificationUri)\n\n // Spinner-style wait indicator using process.stdout so we can overwrite it\n const frames = ['|', '/', '-', '\\\\']\n let frameIdx = 0\n const spinnerInterval = setInterval(() => {\n process.stdout.write(`\\rWaiting for authorization... ${frames[frameIdx++ % frames.length]}`)\n }, 100)\n\n const clearSpinner = () => {\n clearInterval(spinnerInterval)\n process.stdout.write('\\r\\x1b[K') // clear spinner line\n }\n\n // Poll loop\n while (true) {\n await new Promise<void>((resolve) => setTimeout(resolve, pollInterval * 1000))\n\n let result\n try {\n result = await pollDeviceCode(baseUrl, deviceCode)\n } catch (err) {\n clearSpinner()\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n\n switch (result.status) {\n case 'complete': {\n clearSpinner()\n const token = result.sessionToken!\n saveProfile(opts.profile, {\n apiKey: token,\n createdAt: new Date().toISOString(),\n })\n console.log(`Logged in. Profile \"${opts.profile}\" saved.`)\n return\n }\n\n case 'expired_token':\n clearSpinner()\n console.error('Error: Authorization expired. Run `ap auth login` again.')\n process.exit(2)\n break\n\n case 'access_denied':\n clearSpinner()\n console.error('Error: Access denied.')\n process.exit(2)\n break\n\n case 'slow_down':\n // Double the interval as instructed by server\n pollInterval = result.interval ?? pollInterval * 2\n break\n\n case 'authorization_pending':\n default:\n // Continue polling\n break\n }\n }\n })\n\n // ap auth logout [--all]\n auth\n .command('logout')\n .description('Remove the active profile (or all profiles with --all)')\n .option('--all', 'Remove all stored profiles')\n .action((opts: { all?: boolean }) => {\n if (opts.all) {\n deleteAllProfiles()\n console.log('All profiles removed.')\n return\n }\n\n const creds = readCredentials()\n const active = creds?.activeProfile\n if (!active) {\n console.log('No active profile to log out from.')\n return\n }\n\n deleteProfile(active)\n console.log(`Profile \"${active}\" removed.`)\n })\n\n // ap auth switch <profile>\n auth\n .command('switch <profile>')\n .description('Switch the active profile')\n .action((profile: string) => {\n try {\n setActiveProfile(profile)\n console.log(`Switched to profile \"${profile}\".`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n // ap auth whoami\n auth\n .command('whoami')\n .description('Show current authentication method and identity')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n try {\n const globals = cmd.optsWithGlobals<{ apiKey?: string }>()\n const cred = resolveAuth({ apiKey: globals.apiKey })\n\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n const creds = readCredentials()\n const profileName = creds?.activeProfile ?? 'unknown'\n const profile = creds?.profiles[profileName]\n console.log(`Profile: ${profileName}`)\n if (profile?.workspace) console.log(`Workspace: ${profile.workspace}`)\n if (profile?.email) console.log(`Email: ${profile.email}`)\n }\n // Never print the raw API key\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n console.log(`API key: ${masked}`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n // ap auth status — alias for whoami\n auth\n .command('status')\n .description('Alias for whoami — show current authentication status')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n try {\n const globals = cmd.optsWithGlobals<{ apiKey?: string }>()\n const cred = resolveAuth({ apiKey: globals.apiKey })\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n const creds = readCredentials()\n const profileName = creds?.activeProfile ?? 'unknown'\n console.log(`Profile: ${profileName}`)\n }\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n console.log(`API key: ${masked}`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n return auth\n}\n","export interface DeviceCodeResponse {\n deviceCode: string\n userCode: string\n verificationUri: string\n expiresIn: number\n interval: number\n}\n\nexport interface PollResult {\n status: 'authorization_pending' | 'complete' | 'expired_token' | 'access_denied' | 'slow_down'\n sessionToken?: string\n orgId?: string\n interval?: number\n}\n\nasync function fetchWithTimeout(\n url: string,\n init: RequestInit = {},\n timeoutMs = 30_000,\n): Promise<Response> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n return await fetch(url, { ...init, signal: controller.signal })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(`Request to ${url} timed out after ${timeoutMs}ms`)\n }\n throw err\n } finally {\n clearTimeout(timer)\n }\n}\n\nasync function parseJson<T>(res: Response): Promise<T> {\n const text = await res.text()\n try {\n return JSON.parse(text) as T\n } catch {\n throw new Error(\n `Expected a JSON response (HTTP ${res.status}) but received non-JSON. ` +\n `Verify the API base URL points at the API, not the web app.`,\n )\n }\n}\n\nexport async function requestDeviceCode(baseUrl: string): Promise<DeviceCodeResponse> {\n const res = await fetchWithTimeout(`${baseUrl}/auth/cli/device-code`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText)\n throw new Error(`Device code request failed (${res.status}): ${text}`)\n }\n\n // The server wraps the fields in its usual {success, data} envelope.\n const { data } = await parseJson<{ data?: DeviceCodeResponse }>(res)\n if (!data?.deviceCode || !data.userCode || !data.verificationUri) {\n throw new Error('Device code response is missing deviceCode, userCode or verificationUri.')\n }\n return data\n}\n\nexport async function pollDeviceCode(baseUrl: string, deviceCode: string): Promise<PollResult> {\n const url = `${baseUrl}/auth/cli/poll?device_code=${encodeURIComponent(deviceCode)}`\n const res = await fetchWithTimeout(url)\n\n const text = await res.text().catch(() => res.statusText)\n let body: Partial<PollResult> = {}\n try {\n body = JSON.parse(text) as Partial<PollResult>\n } catch {\n // handled below\n }\n // The server answers slow_down, expired_token and access_denied with HTTP 400 and a status.\n if (res.ok || (res.status === 400 && body.status)) {\n if (!body.status) throw new Error(`Poll response (HTTP ${res.status}) has no status.`)\n return body as PollResult\n }\n throw new Error(`Poll request failed (${res.status}): ${text}`)\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createBillingCommand(): Command {\n const billing = new Command('billing').description('View billing information')\n\n // ap billing status\n billing\n .command('status')\n .description('Show current plan and subscription status')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching billing status…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const status = await client.billing.status()\n spinner.stop()\n printer.table(\n [\n {\n plan: status.planName,\n status: status.status ?? '—',\n cycle: status.billingCycle ?? '—',\n accounts: `${status.accountsUsed}/${status.accountLimit === -1 ? '∞' : status.accountLimit}`,\n credits: status.creditBalance,\n renews: status.currentPeriodEnd ?? '—',\n 'trial ends': status.trialEnd ?? '—',\n },\n ],\n ['plan', 'status', 'cycle', 'accounts', 'credits', 'renews', 'trial ends'],\n )\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap billing credits\n billing\n .command('credits')\n .description('Show credit balance and usage breakdown')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching credit balance…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const credits = await client.billing.credits()\n spinner.stop()\n if (!printer.isTty()) {\n printer.log(credits)\n return\n }\n printer.table(\n [\n {\n balance: credits.balanceFormatted,\n 'spent (30d)': credits.totalSpent30d,\n },\n ],\n ['balance', 'spent (30d)'],\n )\n if (credits.recentUsage.length > 0) {\n const usageRows = credits.recentUsage.map((e) => ({\n date: e.date,\n description: e.description,\n amount: e.amount,\n type: e.type,\n }))\n printer.table(usageRows, ['date', 'description', 'amount', 'type'])\n }\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return billing\n}\n","import { Command } from 'commander'\nimport { readFile } from 'node:fs/promises'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\ntype Globals = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\nasync function run(\n cmd: Command,\n action: (client: Autoposting) => Promise<unknown>,\n) {\n const globals = cmd.optsWithGlobals<Globals>()\n const printer = createPrinter(globals)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n printer.log(await action(new Autoposting({ apiKey: cred.apiKey })))\n } catch (err) {\n printer.error(err as Error)\n process.exitCode = exitCodeFromError(err)\n }\n}\nexport function createAccountsCommand() {\n const command = new Command('accounts').description(\n 'Import account CSVs and connect through browser approval; progress lives in the workspace',\n )\n command\n .command('import')\n .requiredOption(\n '--from <csv>',\n 'CSV with brand_name,platform,account_url; optional brand_slug,timezone',\n )\n .action(async (opts: { from: string }, cmd: Command) =>\n run(cmd, async (client) =>\n client.accountOnboarding.create({\n csv: await readFile(opts.from, 'utf8'),\n }),\n ),\n )\n command\n .command('prepare <importId>')\n .option('--offset <number>', 'Resume at this row offset', '0')\n .description(\n 'Create/reuse the next 25 brands; repeat with nextOffset until null',\n )\n .action(async (id: string, opts: { offset: string }, cmd: Command) =>\n run(cmd, async (client) => {\n const offset = Number(opts.offset)\n if (!Number.isInteger(offset) || offset < 0)\n throw new Error('offset must be a nonnegative integer')\n return client.accountOnboarding.prepare(id, offset)\n }),\n )\n command\n .command('status <importId>')\n .option('--offset <number>', 'Row offset', '0')\n .option('--limit <number>', 'Rows per page (1–100)', '50')\n .description('Show connected, pending, reconnect and confirmation rows')\n .action(\n async (\n id: string,\n opts: { offset: string; limit: string },\n cmd: Command,\n ) =>\n run(cmd, (client) =>\n client.accountOnboarding.status(id, {\n offset: Number(opts.offset),\n limit: Number(opts.limit),\n }),\n ),\n )\n command\n .command('authorize <importId> <rowId>')\n .description(\n 'Print a fresh approval link. Open it in your browser, select the CSV account, then check status',\n )\n .action(async (id: string, rowId: string, _opts: unknown, cmd: Command) =>\n run(cmd, (client) => client.accountOnboarding.authorize(id, rowId)),\n )\n command\n .command('confirm <importId> <rowId>')\n .requiredOption(\n '--token-id <id>',\n 'Actual account tokenId from status; confirm only after comparing it with the CSV account',\n )\n .action(\n async (\n id: string,\n rowId: string,\n opts: { tokenId: string },\n cmd: Command,\n ) =>\n run(cmd, (client) =>\n client.accountOnboarding.confirm(id, rowId, opts.tokenId),\n ),\n )\n command\n .command('delete <importId>')\n .requiredOption(\n '--force',\n 'Discard import progress; keeps brands and connected accounts',\n )\n .action(async (id: string, _opts: unknown, cmd: Command) =>\n run(cmd, (client) => client.accountOnboarding.remove(id)),\n )\n return command\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport type { PlatformConnection } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\nimport { parsePairs } from '../lib/media-flags.js'\nimport {\n getDefaultAccounts,\n setDefaultAccount,\n clearDefaultAccounts,\n} from '../auth/config-store.js'\n\n/**\n * Classify a platform connection's token. A connection is only \"ok\" when it's\n * connected, has no refresh failure, and isn't past its expiry — otherwise the\n * token can't actually post, so reporting \"ok\" (the old behavior) was misleading.\n */\nexport function tokenStatus(c: PlatformConnection, now: number = Date.now()): string {\n if (!c.connected) return '—'\n if (c.refreshError) return 'expired'\n if (c.expiresAt) {\n const expMs = Date.parse(c.expiresAt)\n if (Number.isNaN(expMs) || expMs <= now) return 'expired'\n }\n return 'ok'\n}\n\nexport function buildAuthStatusRow(c: PlatformConnection, now: number = Date.now()) {\n return {\n platform: c.platform,\n connected: c.connected ? 'yes' : 'no',\n username: c.platformUsername ?? '—',\n 'token status': tokenStatus(c, now),\n expires: c.expiresAt ?? '—',\n }\n}\n\nexport function createBrandsCommand(): Command {\n const brands = new Command('brands').description('Manage brands')\n\n // ap brands list\n brands\n .command('list')\n .description('List all brands')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching brands…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.brands.list()\n spinner.stop()\n const rows = list.map((b) => ({\n slug: b.slug,\n name: b.name,\n platforms: b.platforms\n .filter((p) => p.connected)\n .map((p) => p.platform)\n .join(', ') || '—',\n timezone: b.timezone,\n }))\n printer.table(rows, ['slug', 'name', 'platforms', 'timezone'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands get <slug>\n brands\n .command('get <slug>')\n .description('Get a brand by slug')\n .action(async (slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.retrieve(slug)\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands create --name <name> [--timezone <tz>]\n brands\n .command('create')\n .description('Create a new brand')\n .requiredOption('--name <name>', 'Brand display name')\n .option('--timezone <tz>', 'IANA timezone (e.g. America/New_York)')\n .action(async (opts: { name: string; timezone?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating brand…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.create({\n name: opts.name,\n ...(opts.timezone ? { timezone: opts.timezone } : {}),\n })\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands update <slug> [--name <name>] [--timezone <tz>]\n brands\n .command('update <slug>')\n .description('Update a brand')\n .option('--name <name>', 'New display name')\n .option('--timezone <tz>', 'New IANA timezone')\n .action(async (slug: string, opts: { name?: string; timezone?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.update(slug, {\n ...(opts.name ? { name: opts.name } : {}),\n ...(opts.timezone ? { timezone: opts.timezone } : {}),\n })\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands delete <slug> [--force]\n brands\n .command('delete <slug>')\n .description('Delete a brand (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (slug: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a brand. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.brands.remove(slug)\n spinner.stop()\n printer.log(`Brand \"${slug}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands auth-status <slug>\n brands\n .command('auth-status <slug>')\n .description('Show platform connection status for a brand')\n .action(async (slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching auth status for \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const connections = await client.brands.authStatus(slug)\n spinner.stop()\n const rows = connections.map((c) => buildAuthStatusRow(c))\n printer.table(rows, ['platform', 'connected', 'username', 'token status', 'expires'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands set-default-account <slug> <p=handle|id|all...>\n // Local-only: saves the account to target per platform when --account is omitted.\n brands\n .command('set-default-account <slug> <pairs...>')\n .description('Save default target account(s) for a brand, e.g. x=@handle linkedin=all')\n .action((slug: string, pairs: string[], _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n try {\n const parsed = parsePairs('--account', pairs)\n for (const [platform, value] of Object.entries(parsed)) {\n setDefaultAccount(slug, platform as keyof typeof parsed, value as string)\n }\n printer.log(getDefaultAccounts(slug))\n } catch (err) {\n printer.error(err as Error)\n process.exit(1)\n }\n })\n\n // ap brands get-default-account <slug>\n brands\n .command('get-default-account <slug>')\n .description('Show saved default account(s) for a brand')\n .action((slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n printer.log(getDefaultAccounts(slug))\n })\n\n // ap brands clear-default-account <slug>\n brands\n .command('clear-default-account <slug>')\n .description('Remove all saved default accounts for a brand')\n .action((slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n clearDefaultAccounts(slug)\n printer.log(getDefaultAccounts(slug))\n })\n\n return brands\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport type { Platform } from '@autoposting.ai/sdk'\n\nexport interface ConfigFile {\n /** Default context applied when a per-call flag is absent (N1). */\n context?: { brand?: string }\n /** Per-brand, per-platform default account: handle | platformUserId | 'all' (M5). */\n defaultAccounts?: Record<string, Partial<Record<Platform, string>>>\n}\n\nexport function getConfigPath(): string {\n // Same XDG resolution as the credential store; a sibling file so config never\n // shares storage with secrets (credentials.json).\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config')\n return path.join(base, 'autoposting', 'config.json')\n}\n\nexport function readConfig(): ConfigFile | null {\n try {\n return JSON.parse(fs.readFileSync(getConfigPath(), 'utf8')) as ConfigFile\n } catch {\n // Missing or corrupt — callers start from {}. config.json holds regenerable\n // defaults (not secrets), so a corrupt read is non-fatal.\n return null\n }\n}\n\n// ponytail: mirrors credential-store's atomic temp-write+rename+chmod. Kept as a\n// separate file (not a shared helper) so refactoring the tested, shipped\n// credential store can't regress; the security pattern is ~12 lines.\nexport function writeConfig(cfg: ConfigFile): void {\n const filePath = getConfigPath()\n fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 })\n const tmp = `${filePath}.${process.pid}.tmp`\n try {\n fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { encoding: 'utf8', mode: 0o600 })\n fs.renameSync(tmp, filePath)\n } catch (err) {\n try {\n fs.unlinkSync(tmp)\n } catch {\n // temp never created — nothing to clean up\n }\n throw err\n }\n fs.chmodSync(filePath, 0o600)\n}\n\n// ── Default context (N1) ───────────────────────────────────────────────────\nexport function getContextBrand(): string | null {\n return readConfig()?.context?.brand ?? null\n}\n\nexport function setContextBrand(brand: string): void {\n const cfg = readConfig() ?? {}\n cfg.context = { ...cfg.context, brand }\n writeConfig(cfg)\n}\n\nexport function unsetContextBrand(): void {\n const cfg = readConfig()\n if (!cfg?.context?.brand) return\n delete cfg.context.brand\n writeConfig(cfg)\n}\n\n/** Brand for a command: an explicit --brand wins, else the saved context, else null. */\nexport function resolveBrand(optBrand?: string): string | null {\n return optBrand ?? getContextBrand()\n}\n\n// ── Per-brand default accounts (M5) ────────────────────────────────────────\nexport function getDefaultAccount(brand: string, platform: Platform): string | null {\n return readConfig()?.defaultAccounts?.[brand]?.[platform] ?? null\n}\n\nexport function getDefaultAccounts(brand: string): Partial<Record<Platform, string>> {\n return readConfig()?.defaultAccounts?.[brand] ?? {}\n}\n\nexport function setDefaultAccount(brand: string, platform: Platform, value: string): void {\n const cfg = readConfig() ?? {}\n cfg.defaultAccounts ??= {}\n cfg.defaultAccounts[brand] = { ...cfg.defaultAccounts[brand], [platform]: value }\n writeConfig(cfg)\n}\n\nexport function clearDefaultAccounts(brand: string): void {\n const cfg = readConfig()\n if (!cfg?.defaultAccounts?.[brand]) return\n delete cfg.defaultAccounts[brand]\n writeConfig(cfg)\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createCarouselsCommand(): Command {\n const carousels = new Command('carousels').description('Manage carousels')\n\n // ap carousels list\n carousels\n .command('list')\n .description('List all carousels')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching carousels…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.carousels.list()\n spinner.stop()\n const rows = list.items.map((c) => ({\n id: c.id,\n title: c.title ?? '—',\n slides: c.slides.length,\n status: c.status,\n createdAt: c.createdAt,\n }))\n printer.table(rows, ['id', 'title', 'slides', 'status', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels get <id>\n carousels\n .command('get <id>')\n .description('Get a carousel by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching carousel \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.retrieve(id)\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels create [--title <title>]\n carousels\n .command('create')\n .description('Create a new carousel')\n .option('--title <title>', 'Carousel title')\n .action(async (opts: { title?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating carousel…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.create(\n opts.title ? { title: opts.title } : undefined,\n )\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels generate --topic <topic> [--brand <slug>] [--slides <n>]\n carousels\n .command('generate')\n .description('AI-generate a carousel from a topic')\n .requiredOption('--topic <topic>', 'Topic to generate slides for')\n .option('--brand <slug>', 'Brand slug for brand voice')\n .option('--slides <n>', 'Number of slides to generate')\n .action(async (opts: { topic: string; brand?: string; slides?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Generating carousel…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.generate({\n topic: opts.topic,\n ...(opts.brand ? { brandSlug: opts.brand } : {}),\n ...(opts.slides ? { slideCount: parseInt(opts.slides, 10) } : {}),\n })\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels draft <id>\n carousels\n .command('draft <id>')\n .description('Convert a carousel to a post draft')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Converting carousel \"${id}\" to draft…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.carousels.draft(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels delete <id> --force\n carousels\n .command('delete <id>')\n .description('Delete a carousel (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a carousel. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting carousel \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.carousels.remove(id)\n spinner.stop()\n printer.log(`Carousel \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return carousels\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\n/**\n * Resolve the brand for an upload: use --brand if given, else auto-pick when the\n * workspace has exactly one brand. Zero or many brands → ask the user to pass --brand.\n */\nasync function resolveBrandId(client: Autoposting, explicit?: string): Promise<string> {\n if (explicit) return explicit\n const brands = await client.brands.list()\n if (brands.length === 1) return brands[0].id\n if (brands.length === 0) {\n throw new Error('No brands found. Create a brand first, then pass --brand <id>.')\n }\n throw new Error(\n `Multiple brands found — pass --brand <id>. Available: ${brands.map((b) => `${b.name} (${b.id})`).join(', ')}`,\n )\n}\n\nexport function createClipsCommand(): Command {\n const clips = new Command('clips').description('Manage video clips')\n\n // ap clips list\n clips\n .command('list')\n .description('List all clips')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching clips…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.clips.list()\n spinner.stop()\n const rows = list.clips.map((c) => ({\n id: c.id,\n name: c.name,\n status: c.status,\n duration: c.duration !== undefined ? `${c.duration}s` : '—',\n }))\n printer.table(rows, ['id', 'name', 'status', 'duration'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips get <id>\n clips\n .command('get <id>')\n .description('Get a clip by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const clip = await client.clips.retrieve(id)\n spinner.stop()\n printer.log(clip)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips upload <file> [--brand <id>] [--name <name>]\n clips\n .command('upload <file>')\n .description('Upload a video file as a clip')\n .option('--brand <id>', 'Brand to attach the clip to (defaults to your only brand)')\n .option('--name <name>', 'Override the clip title (defaults to filename)')\n .action(async (file: string, opts: { brand?: string; name?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Uploading clip…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brandId = await resolveBrandId(client, opts.brand)\n const clip = await client.clips.upload(file, {\n brandId,\n ...(opts.name ? { title: opts.name } : {}),\n onProgress: (pct) => {\n if (pct > 0 && pct < 100) spinner.stop()\n },\n })\n spinner.stop()\n printer.log(clip)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips import --url <url> [--brand <id>] [--name <name>]\n clips\n .command('import')\n .description('Start AI clipping from a video URL (e.g. a YouTube video)')\n .requiredOption('--url <url>', 'URL of the video to import')\n .option('--brand <id>', 'Brand ID (auto-picked when the workspace has exactly one brand)')\n .option('--name <name>', 'Name for the imported clip')\n .action(async (opts: { url: string; brand?: string; name?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Importing clip…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brandId = await resolveBrandId(client, opts.brand)\n const { clipId } = await client.clips.importUrl({\n url: opts.url,\n brandId,\n ...(opts.name ? { title: opts.name } : {}),\n })\n spinner.stop()\n printer.log({ clipId })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips render <id> [--candidate <id>] [--revision <n>]\n clips\n .command('render <id>')\n .description('Render a clip (uses credits)')\n .option('--candidate <id>', 'Render only this candidate')\n .option('--revision <n>', 'Clip editRevision (read from the clip when omitted)', (v) => Number(v))\n .action(async (id: string, opts: { candidate?: string; revision?: number }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Rendering clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { jobIds, activeJobIds, reusedJobIds } = await client.clips.render(id, {\n ...(opts.revision !== undefined ? { editRevision: opts.revision } : {}),\n ...(opts.candidate ? { candidateId: opts.candidate } : {}),\n })\n spinner.stop()\n printer.log({ jobIds, activeJobIds, reusedJobIds })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips draft <id> [--candidate <id>] [--aspect-ratio <ratio>]\n clips\n .command('draft <id>')\n .description('Create a draft post from a rendered clip')\n .option('--candidate <id>', 'Candidate to use (defaults to the first rendered one)')\n .option('--aspect-ratio <ratio>', 'Render format: 9:16, 16:9, 1:1 or 4:5')\n .action(async (id: string, opts: { candidate?: string; aspectRatio?: '9:16' | '16:9' | '1:1' | '4:5' }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Creating draft from clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { postId } = await client.clips.createDraft(id, {\n ...(opts.candidate ? { candidateId: opts.candidate } : {}),\n ...(opts.aspectRatio ? { aspectRatio: opts.aspectRatio } : {}),\n })\n spinner.stop()\n printer.log({ postId })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips delete <id> --force\n clips\n .command('delete <id>')\n .description('Delete a clip (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a clip. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.clips.remove(id)\n spinner.stop()\n printer.log(`Clip \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return clips\n}\n","import { Command } from 'commander'\nimport { Autoposting, NotFoundError } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport type { Spinner } from '../output/spinner.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\nimport { parsePlatforms, validateScheduledAt, buildAndCreatePost } from '../lib/post-create.js'\nimport { parseBulkFile, createPostsBulk } from '../lib/post-bulk.js'\nimport { resolveBrand } from '../auth/config-store.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction parsePositiveInt(value: string, flag: string): number {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 1) {\n throw new Error(`${flag} must be a positive integer (received \"${value}\").`)\n }\n return n\n}\n\n/**\n * Resolves the process exit code for a caught error.\n * Honours the `exitCode` property set by `resolveAuth` (exit 2 for auth errors)\n * before falling back to the SDK error class mapping.\n */\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createPostsCommand(): Command {\n const posts = new Command('posts').description('Manage posts')\n\n // ap posts list [--brand <slug>] [--status <status>] [--limit <n>] [--page <n>]\n posts\n .command('list')\n .description('List posts')\n .option('--brand <slug>', 'Filter by brand slug (defaults to the saved context)')\n .option('--status <status>', 'Filter by status (draft|scheduled|published|failed)')\n .option('--limit <n>', 'Max results per page', '20')\n .option('--page <n>', 'Page number', '1')\n .action(async (opts: { brand?: string; status?: string; limit: string; page: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching posts…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.posts.list({\n brandSlug: resolveBrand(opts.brand) ?? undefined,\n status: opts.status as 'draft' | 'scheduled' | 'published' | 'failed' | undefined,\n limit: parsePositiveInt(opts.limit, '--limit'),\n page: parsePositiveInt(opts.page, '--page'),\n })\n spinner.stop()\n const rows = result.map((p) => ({\n id: p.id,\n brand: p.brandSlug,\n status: p.status,\n platforms: p.platforms.join(', '),\n text: p.text.length > 60 ? `${p.text.slice(0, 57)}…` : p.text,\n scheduledAt: p.scheduledAt ?? '—',\n }))\n printer.table(rows, ['id', 'brand', 'status', 'platforms', 'text', 'scheduledAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts get <id>\n posts\n .command('get <id>')\n .description('Get a post by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.getById(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts create --brand <slug> --text <text> --platforms <x,linkedin,...>\n posts\n .command('create')\n .description('Create a new post')\n .option('--brand <slug>', 'Brand slug (defaults to the saved context: ap config set-context)')\n // Not requiredOption: --from supplies text/platforms per row. Required-ness for\n // the single-post path is enforced manually below so --from can omit them.\n .option('--text <text>', 'Post text content (required unless --from)')\n .option('--platforms <list>', 'Comma-separated platforms, e.g. x,linkedin (required unless --from)')\n .option('--from <file>', 'Create posts in bulk from a CSV or JSON file (one post per row)')\n .option('--at <iso>', 'Schedule date/time (ISO 8601)')\n .option(\n '--thread <text...>',\n 'Additional posts appended after --text to form a thread (X/Threads only, max 25)',\n )\n // v0.3.3 — media\n .option('--media <path...>', 'Media file paths to attach (max 10)')\n .option('--alt-text <text...>', 'Alt text for --media files, aligned by index')\n .option('--platform-text <pairs...>', 'Per-platform text, e.g. x=Hello linkedin=World')\n .option('--platform-media <pairs...>', 'Per-platform media, e.g. instagram=photo.jpg x=banner.png')\n // v0.3.3 — YouTube\n .option('--yt-title <t>', 'YouTube video title')\n .option('--yt-description <d>', 'YouTube video description')\n .option('--yt-tags <list>', 'YouTube tags (comma-separated)')\n .option('--yt-privacy <v>', 'YouTube privacy status (public|unlisted|private)')\n .option('--yt-category <id>', 'YouTube category ID')\n .option('--yt-made-for-kids', 'Mark YouTube video as made for kids')\n // v0.3.3 — Instagram\n .option('--ig-reel', 'Post as an Instagram Reel')\n .option('--ig-share-to-feed', 'Share Reel to feed')\n .option('--ig-cover-url <url>', 'Reel cover image URL')\n .option('--ig-thumb-offset-ms <n>', 'Reel thumbnail offset in milliseconds')\n .option('--ig-collaborators <list>', 'Reel collaborator handles (comma-separated)')\n // v0.3.3 — Threads\n .option('--threads-reply-to <id>', 'Threads post ID to reply to')\n .option('--threads-reply-control <v>', 'Threads reply control (everyone|accounts_you_follow|mentioned_only)')\n // v0.3.3 — account selector\n .option('--account <p=handle|id...>', 'Target specific account per platform, e.g. x=@handle')\n // v0.3.4 — preview the resolved request without uploading or posting\n .option('--dry-run', 'Print the resolved request body without uploading media or creating the post')\n .option('--preview', 'Alias for --dry-run')\n .action(\n async (\n opts: {\n brand?: string\n text?: string\n platforms?: string\n from?: string\n at?: string\n thread?: string[]\n // v0.3.3\n media?: string[]\n altText?: string[]\n platformText?: string[]\n platformMedia?: string[]\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n threadsReplyTo?: string\n threadsReplyControl?: string\n account?: string[]\n dryRun?: boolean\n preview?: boolean\n },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n // Spinner is started only after the account picker (via onBeforeNetwork) — ora's\n // repaint loop fights the interactive prompt and can obscure the selection.\n let spinner: Spinner | undefined\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n\n // ── Bulk path: --from <file> creates one post per row ──────────────\n if (opts.from) {\n const rows = parseBulkFile(opts.from)\n const records = await createPostsBulk(client, rows, {\n cliBrand: resolveBrand(opts.brand) ?? undefined,\n })\n // Truncate text only for the human table; JSON/jq/quiet keep it full\n // (lossless echo for scripting consumers).\n const truncate = printer.isTty()\n printer.table(\n records.map((r) => ({\n '#': r.index + 1,\n status: r.status,\n id: r.id || '—',\n text: truncate && r.text.length > 40 ? `${r.text.slice(0, 37)}…` : r.text,\n error: r.error,\n })),\n ['#', 'status', 'id', 'text', 'error'],\n )\n if (records.some((r) => r.status === 'failed')) {\n process.exit(1)\n }\n return\n }\n\n // Resolve the brand before any validation so a missing brand fails first.\n const brand = resolveBrand(opts.brand)\n if (!brand) {\n throw new Error(\n 'No brand specified. Pass --brand <slug> or set a default with: ap config set-context --brand <slug>',\n )\n }\n if (!opts.text) {\n throw new Error('--text is required (or use --from <file> to create posts in bulk).')\n }\n if (!opts.platforms) {\n throw new Error('--platforms is required (or use --from <file> to create posts in bulk).')\n }\n\n const result = await buildAndCreatePost(\n client,\n { ...opts, brandSlug: brand, text: opts.text, platforms: opts.platforms },\n {\n // Picker reads stdin — gate on a real interactive terminal, not the\n // output mode (printer.isTty() is true even when stdin is piped).\n isTty: Boolean(process.stdin.isTTY),\n // --dry-run/--preview: resolve + validate, then return the request body\n // without uploading media or POSTing (onBeforeNetwork never fires).\n dryRun: Boolean(opts.dryRun || opts.preview),\n // Picker done — start the spinner now (covers uploads + create).\n onBeforeNetwork: () => {\n spinner = printer.spinner('Creating post…')\n },\n },\n )\n spinner?.stop()\n printer.log(result)\n } catch (err) {\n spinner?.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap posts update <id> [--text <text>] [--platforms <list>] [--at <iso>]\n posts\n .command('update <id>')\n .description('Update a post')\n .option('--text <text>', 'New post text')\n .option('--platforms <list>', 'New comma-separated platforms')\n .option('--at <iso>', 'New scheduled date/time (ISO 8601)')\n .action(\n async (\n id: string,\n opts: { text?: string; platforms?: string; at?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.update(id, {\n ...(opts.text ? { text: opts.text } : {}),\n ...(opts.platforms ? { platforms: parsePlatforms(opts.platforms) } : {}),\n ...(opts.at ? { scheduledAt: validateScheduledAt(opts.at) } : {}),\n })\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap posts delete <id> [--force]\n posts\n .command('delete <id>')\n .description('Delete a post (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a post. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.posts.remove(id)\n spinner.stop()\n printer.log(`Post \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n // A failed delete (after the SDK's transient-retry gives up) may have left the\n // post in place — a NotFound means it's already gone, anything else is ambiguous.\n // Tell the user to verify so a still-scheduled post isn't silently orphaned.\n // Goes to stderr in every mode — a CI/piped run needs this safety hint too.\n if (!(err instanceof NotFoundError)) {\n printer.error(`The post may not have been deleted — verify with: ap posts get \"${id}\"`)\n }\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts publish <id>\n posts\n .command('publish <id>')\n .description('Publish a post immediately')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Publishing post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.publish(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts schedule <id> (--at <iso-datetime> | --cancel)\n posts\n .command('schedule <id>')\n .description('Schedule a post for a specific time, or --cancel to unschedule it')\n .option('--at <iso>', 'ISO 8601 datetime to schedule the post')\n .option('--cancel', 'Unschedule the post (return it to draft)')\n .action(async (id: string, opts: { at?: string; cancel?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(\n opts.cancel ? `Unscheduling post \"${id}\"…` : `Scheduling post \"${id}\"…`,\n )\n try {\n // Exactly one of --at / --cancel — they are opposite operations.\n if (opts.cancel && opts.at) {\n throw new Error('Cannot use --at together with --cancel — choose one.')\n }\n if (!opts.cancel && !opts.at) {\n throw new Error('Provide either --at <iso> to schedule, or --cancel to unschedule.')\n }\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = opts.cancel\n ? await client.posts.unschedule(id)\n : await client.posts.schedule(id, validateScheduledAt(opts.at!))\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts retry <id>\n posts\n .command('retry <id>')\n .description('Retry a failed post')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Retrying post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.retry(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts rewrite <id>\n posts\n .command('rewrite <id>')\n .description('AI-rewrite a post')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Rewriting post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.rewrite(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts score <id>\n posts\n .command('score <id>')\n .description('Score a post with AI feedback')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Scoring post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.posts.score(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return posts\n}\n","import fs from 'node:fs/promises'\nimport nodePath from 'node:path'\nimport type { Autoposting, MediaInput, Platform } from '@autoposting.ai/sdk'\nimport {\n extToMime,\n parsePairs,\n parsePlatformMediaPairs,\n validateMediaCount,\n validateMediaPaths,\n validateMediaExtensions,\n alignAltText,\n buildYoutubeOptions,\n buildInstagramOptions,\n buildThreadsOptions,\n} from './media-flags.js'\nimport { resolveTargetAccounts } from './account-select.js'\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube']\n\nexport function parsePlatforms(raw: string): Platform[] {\n const parts = raw.split(',').map((p) => p.trim()).filter(Boolean)\n if (parts.length === 0) {\n throw new Error('No platforms provided. Pass a comma-separated list, e.g. --platforms x,linkedin')\n }\n const invalid = parts.filter((p) => !VALID_PLATFORMS.includes(p as Platform))\n if (invalid.length > 0) {\n throw new Error(\n `Unsupported platform(s): ${invalid.join(', ')}. Valid platforms: ${VALID_PLATFORMS.join(', ')}`,\n )\n }\n return parts as Platform[]\n}\n\nexport function validateScheduledAt(value: string): string {\n // Require a real ISO 8601 datetime. Date.parse alone is lenient (accepts locale formats\n // like \"01/02/2026\"), so also require the YYYY-MM-DDTHH:MM prefix the API expects.\n const ms = Date.parse(value)\n if (Number.isNaN(ms) || !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}/.test(value)) {\n throw new Error(\n `--at must be a valid ISO 8601 datetime, e.g. 2026-06-30T14:00:00Z (received \"${value}\").`,\n )\n }\n // A past time means the post would publish immediately on submit — almost never intended,\n // and irreversible for an instant publish. Reject it here, before any create/schedule call.\n if (ms <= Date.now()) {\n throw new Error(\n `--at must be in the future (received \"${value}\", which is in the past). ` +\n `A past schedule time publishes immediately.`,\n )\n }\n return value\n}\n\n/** One post's inputs — same field names as `posts create` opts, brand already resolved. */\nexport interface PostFields {\n brandSlug: string\n text: string\n platforms: string\n at?: string\n thread?: string[]\n media?: string[]\n altText?: string[]\n platformText?: string[]\n platformMedia?: string[]\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n threadsReplyTo?: string\n threadsReplyControl?: string\n account?: string[]\n}\n\nexport interface BuildOptions {\n isTty: boolean\n /** When true: validate + resolve accounts, then return the request body — no upload, no POST. */\n dryRun?: boolean\n /** Human-facing hints sink (fan-out count); defaults to stderr inside resolveTargetAccounts. */\n emit?: (message: string) => void\n /** Called after account resolution, before any upload/POST — used to start the spinner (M3). */\n onBeforeNetwork?: () => void\n}\n\n/**\n * Validates one post's inputs, resolves target accounts, then either creates it\n * (uploading media first) or — in dry-run — returns the resolved request body with\n * media left as local paths. Shared by `posts create` (single) and `--from` (bulk).\n */\nexport async function buildAndCreatePost(\n client: Autoposting,\n fields: PostFields,\n opts: BuildOptions,\n): Promise<unknown> {\n // ── Pure validation pass (synchronous/disk-only) — runs before any network call ──\n const platforms = parsePlatforms(fields.platforms)\n const scheduledAt = fields.at ? validateScheduledAt(fields.at) : undefined\n\n if (fields.media && fields.media.length > 0) {\n validateMediaCount(fields.media)\n validateMediaPaths(fields.media)\n validateMediaExtensions(fields.media)\n }\n\n const platformTexts =\n fields.platformText && fields.platformText.length > 0\n ? parsePairs('--platform-text', fields.platformText)\n : undefined\n\n const platformMediaPaths =\n fields.platformMedia && fields.platformMedia.length > 0\n ? parsePlatformMediaPairs('--platform-media', fields.platformMedia)\n : {}\n for (const paths of Object.values(platformMediaPaths)) {\n validateMediaPaths(paths)\n validateMediaExtensions(paths)\n }\n\n const altTexts = alignAltText(fields.media ?? [], fields.altText ?? [])\n\n const youtubeOptions = buildYoutubeOptions({\n ytTitle: fields.ytTitle,\n ytDescription: fields.ytDescription,\n ytTags: fields.ytTags,\n ytPrivacy: fields.ytPrivacy,\n ytCategory: fields.ytCategory,\n ytMadeForKids: fields.ytMadeForKids,\n })\n const instagramOptions = buildInstagramOptions({\n igReel: fields.igReel,\n igShareToFeed: fields.igShareToFeed,\n igCoverUrl: fields.igCoverUrl,\n igThumbOffsetMs: fields.igThumbOffsetMs,\n igCollaborators: fields.igCollaborators,\n })\n const threadsOptions = buildThreadsOptions({\n threadsReplyTo: fields.threadsReplyTo,\n threadsReplyControl: fields.threadsReplyControl,\n })\n\n // ── Account resolution (network: brands.authStatus + optional picker) ──\n const targetAccountIds = await resolveTargetAccounts({\n brandSlug: fields.brandSlug,\n platforms,\n accountFlags: fields.account ?? [],\n client,\n isTty: opts.isTty,\n emit: opts.emit,\n })\n\n const common = {\n brandSlug: fields.brandSlug,\n text: fields.text,\n platforms,\n ...(scheduledAt ? { scheduledAt } : {}),\n ...(fields.thread && fields.thread.length > 0 ? { thread: fields.thread } : {}),\n ...(platformTexts && Object.keys(platformTexts).length > 0 ? { platformTexts } : {}),\n ...(Object.keys(targetAccountIds).length > 0 ? { targetAccountIds } : {}),\n ...(instagramOptions ? { instagramOptions } : {}),\n ...(threadsOptions ? { threadsOptions } : {}),\n ...(youtubeOptions ? { youtubeOptions } : {}),\n source: 'cli' as const,\n }\n\n if (opts.dryRun) {\n // Show the resolved request with media as LOCAL paths — nothing uploaded, nothing POSTed.\n return {\n dryRun: true,\n request: {\n ...common,\n ...(fields.media && fields.media.length > 0\n ? {\n media: fields.media.map((path, i) => ({\n path,\n ...(altTexts[i] ? { altText: altTexts[i] } : {}),\n })),\n }\n : {}),\n ...(Object.keys(platformMediaPaths).length > 0 ? { platformMedia: platformMediaPaths } : {}),\n },\n }\n }\n\n opts.onBeforeNetwork?.()\n\n // Upload global media.\n const mediaInputs: MediaInput[] = []\n for (let i = 0; i < (fields.media ?? []).length; i++) {\n const filePath = fields.media![i]!\n const data = await fs.readFile(filePath)\n const filename = nodePath.basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(data),\n filename,\n contentType: extToMime(filename),\n })\n mediaInputs.push({\n url: uploaded.url,\n type: uploaded.type,\n ...(altTexts[i] ? { altText: altTexts[i] } : {}),\n })\n }\n\n // Upload per-platform media.\n const platformMediaResult: Partial<Record<Platform, MediaInput[]>> = {}\n for (const [p, paths] of Object.entries(platformMediaPaths) as [Platform, string[]][]) {\n const uploads: MediaInput[] = []\n for (const filePath of paths) {\n const data = await fs.readFile(filePath)\n const filename = nodePath.basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(data),\n filename,\n contentType: extToMime(filename),\n })\n uploads.push({ url: uploaded.url, type: uploaded.type })\n }\n platformMediaResult[p] = uploads\n }\n\n return client.posts.create({\n ...common,\n ...(mediaInputs.length > 0 ? { media: mediaInputs } : {}),\n ...(Object.keys(platformMediaResult).length > 0 ? { platformMedia: platformMediaResult } : {}),\n })\n}\n","import type { Autoposting, Platform, PlatformConnection } from '@autoposting.ai/sdk'\nimport { getDefaultAccount } from '../auth/config-store.js'\n\n// PlatformConnection v0.3.3 already has platformUserId, platformAccountType, profileImageUrl.\ntype AccountEntry = PlatformConnection\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube']\n\n// Fan-out (=all) larger than this prompts for confirmation on a TTY (M5).\nconst FANOUT_CONFIRM_THRESHOLD = 5\n// At/above this many accounts the picker pages instead of dumping the whole list.\nconst PAGED_PICKER_THRESHOLD = 8\n\nconst isAll = (v: string): boolean => v === 'all' || v === '*'\n\n/**\n * Whether to interactively confirm a fan-out. Only an explicit `--account p=all`\n * over the threshold on a real TTY prompts — a saved default is a standing opt-in\n * and a non-TTY run can't prompt (it proceeds with the count printed).\n */\nexport function needsFanoutConfirm(count: number, isTty: boolean, explicit: boolean): boolean {\n return isTty && explicit && count > FANOUT_CONFIRM_THRESHOLD\n}\n\n/**\n * Resolves --account p=handle|id flags + interactive picker into targetAccountIds.\n *\n * Logic per targeted platform (an explicit --account flag wins, else a saved\n * default for this brand+platform, else the picker/throw):\n * - value is `all`/`*` → fan out to every connected account (print count; an\n * explicit fan-out over the threshold confirms on a TTY)\n * - value is a handle/id → resolve → push platformUserId (unknown → throw)\n * - ≥2 connected accounts, TTY → checkbox multiselect via @inquirer/prompts\n * - ≥2 connected accounts, non-TTY → throw with list + usage hint\n * - 0 or 1 account → omit platform (backend defaults to all connected)\n */\nexport async function resolveTargetAccounts({\n brandSlug,\n platforms,\n accountFlags,\n client,\n isTty,\n emit = (m) => process.stderr.write(`${m}\\n`),\n}: {\n brandSlug: string\n platforms: Platform[]\n accountFlags: string[]\n client: Autoposting\n isTty: boolean\n // Human-facing hints (fan-out count, etc.) — stderr by default so stdout stays\n // clean for JSON consumers; printed in every mode, including non-TTY.\n emit?: (message: string) => void\n}): Promise<Partial<Record<Platform, string[]>>> {\n // Validate flag format BEFORE any network call (fast fail on bad input).\n const accountMap: Partial<Record<Platform, string>> = {}\n for (const flag of accountFlags) {\n const eqIdx = flag.indexOf('=')\n if (eqIdx < 1) {\n throw Object.assign(\n new Error(`--account: expected \"platform=handle|id\" format, got \"${flag}\"`),\n { exitCode: 1 },\n )\n }\n const p = flag.slice(0, eqIdx).trim()\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw Object.assign(\n new Error(`--account: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`),\n { exitCode: 1 },\n )\n }\n accountMap[p as Platform] = flag.slice(eqIdx + 1).trim()\n }\n\n // If no --account flags and platforms all would get 0-1 connections, skip the API call\n // only if we know there's nothing to resolve. We can't know without fetching, so always fetch.\n const connections = (await client.brands.authStatus(brandSlug)) as AccountEntry[]\n\n // Group connected accounts by platform.\n const byPlatform: Partial<Record<Platform, AccountEntry[]>> = {}\n for (const conn of connections) {\n if (!conn.connected) continue\n const p = conn.platform as Platform\n if (!byPlatform[p]) byPlatform[p] = []\n byPlatform[p]!.push(conn)\n }\n\n const result: Partial<Record<Platform, string[]>> = {}\n\n for (const platform of platforms) {\n const accounts = byPlatform[platform] ?? []\n // An explicit --account flag wins; otherwise fall back to a saved default.\n const flagValue = accountMap[platform]\n const explicit = flagValue !== undefined\n const specifiedValue = flagValue ?? getDefaultAccount(brandSlug, platform) ?? undefined\n\n if (specifiedValue !== undefined && isAll(specifiedValue)) {\n // Fan out to every connected account for this platform.\n const ids = accounts\n .map((a) => a.platformUserId)\n .filter((id): id is string => Boolean(id))\n emit(`${platform}: posting to all ${ids.length} connected account(s).`)\n if (needsFanoutConfirm(ids.length, isTty, explicit)) {\n // ponytail: lazy import keeps @inquirer/prompts out of non-TTY/test paths\n const { confirm } = await import('@inquirer/prompts')\n const ok = await confirm({\n message: `Post to all ${ids.length} ${platform} accounts?`,\n default: false,\n })\n if (!ok) {\n throw Object.assign(new Error('Aborted: fan-out not confirmed.'), { exitCode: 1 })\n }\n }\n if (ids.length > 0) result[platform] = ids\n } else if (specifiedValue !== undefined) {\n // Resolve handle (strip leading @, case-insensitive) or platformUserId.\n const normalized = specifiedValue.startsWith('@') ? specifiedValue.slice(1) : specifiedValue\n const match = accounts.find(\n (a) =>\n a.platformUsername?.toLowerCase() === normalized.toLowerCase() ||\n a.platformUserId === specifiedValue,\n )\n if (!match?.platformUserId) {\n const valid = accounts\n .map((a) => ` @${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`)\n .join('\\n')\n throw Object.assign(\n new Error(\n `--account: unknown ${platform} account \"${specifiedValue}\".\\n` +\n `Connected accounts:\\n${valid || ' (none)'}`,\n ),\n { exitCode: 1 },\n )\n }\n if (!result[platform]) result[platform] = []\n result[platform]!.push(match.platformUserId)\n } else if (accounts.length >= 2) {\n if (isTty) {\n // ponytail: lazy import keeps @inquirer/prompts out of non-TTY/test paths\n const { checkbox } = await import('@inquirer/prompts')\n const choices = accounts.map((a) => ({\n name: `@${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`,\n value: a.platformUserId ?? '',\n }))\n const selected: string[] = await checkbox({\n message: `Multiple ${platform} accounts connected — select which to post to:`,\n choices,\n // ponytail: paged scroll for long lists (23 LinkedIn orgs). @inquirer's\n // checkbox has no type-to-filter; if many-account users need it, swap in\n // a search-capable multiselect dep — or save a default to skip the picker.\n pageSize: accounts.length >= PAGED_PICKER_THRESHOLD ? 12 : 7,\n loop: false,\n })\n const valid = selected.filter(Boolean)\n if (valid.length > 0) result[platform] = valid\n } else {\n const list = accounts\n .map((a) => ` @${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`)\n .join('\\n')\n throw Object.assign(\n new Error(\n `Multiple ${platform} accounts connected but no --account specified (non-interactive mode).\\n` +\n `Connected accounts:\\n${list}\\n` +\n `Pass --account ${platform}=<handle|id> to select.`,\n ),\n { exitCode: 1 },\n )\n }\n }\n // 0 or 1 account: omit from targetAccountIds — backend posts to all connected.\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport type { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveBrand } from '../auth/config-store.js'\nimport { buildAndCreatePost, type PostFields } from './post-create.js'\n\nexport interface BulkRecordResult {\n index: number\n status: 'created' | 'failed'\n id: string\n text: string\n error: string\n}\n\n/**\n * Parse a bulk input file into an array of raw post rows. JSON (an array of\n * post objects) is lossless — array fields like `media`/`thread` pass straight\n * through. CSV is for flat rows; see parseCsvRows for its ceiling.\n */\nexport function parseBulkFile(filePath: string): Record<string, unknown>[] {\n const raw = fs.readFileSync(filePath, 'utf8')\n const isJson = filePath.toLowerCase().endsWith('.json') || raw.trimStart().startsWith('[')\n const rows = isJson ? parseJsonRows(raw) : parseCsvRows(raw)\n if (rows.length === 0) {\n throw new Error(`No records found in ${filePath}.`)\n }\n return rows\n}\n\nfunction parseJsonRows(raw: string): Record<string, unknown>[] {\n let data: unknown\n try {\n data = JSON.parse(raw)\n } catch (e) {\n throw new Error(`Invalid JSON bulk input: ${(e as Error).message}`)\n }\n if (!Array.isArray(data)) {\n throw new Error('JSON bulk input must be an array of post objects.')\n }\n return data as Record<string, unknown>[]\n}\n\n// ponytail: minimal CSV — comma separator, double-quote escaping (\"\" = literal\n// quote), no newlines inside quoted cells. Multi-value fields (thread, media,\n// account, alt-text) aren't expressible in flat CSV — use JSON for those.\nfunction parseCsvRows(raw: string): Record<string, unknown>[] {\n const lines = raw.split(/\\r?\\n/).filter((l) => l.trim().length > 0)\n if (lines.length === 0) return []\n const headers = splitCsvLine(lines[0])\n return lines.slice(1).map((line) => {\n const cells = splitCsvLine(line)\n const row: Record<string, unknown> = {}\n headers.forEach((h, i) => {\n if (cells[i] !== undefined && cells[i] !== '') row[h] = cells[i]\n })\n return row\n })\n}\n\nfunction splitCsvLine(line: string): string[] {\n const out: string[] = []\n let cur = ''\n let inQuotes = false\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (inQuotes) {\n if (c === '\"' && line[i + 1] === '\"') {\n cur += '\"'\n i++\n } else if (c === '\"') {\n inQuotes = false\n } else {\n cur += c\n }\n } else if (c === '\"') {\n inQuotes = true\n } else if (c === ',') {\n out.push(cur)\n cur = ''\n } else {\n cur += c\n }\n }\n out.push(cur)\n return out.map((s) => s.trim())\n}\n\n/** Build PostFields from one raw row, falling back to the CLI/context brand. */\nfunction rowToFields(row: Record<string, unknown>, cliBrand?: string): PostFields {\n const platformsRaw = row.platforms\n const platforms = Array.isArray(platformsRaw) ? platformsRaw.join(',') : platformsRaw\n const brand = resolveBrand((row.brand as string) ?? (row.brandSlug as string) ?? cliBrand)\n if (!brand) {\n throw new Error('No brand: set \"brand\" in the row, pass --brand, or set a default context.')\n }\n if (!row.text) throw new Error('Missing \"text\".')\n if (!platforms) throw new Error('Missing \"platforms\".')\n // Array-typed fields can't be expressed in flat CSV (cells are always strings),\n // so a scalar here would misparse downstream (e.g. media.length = char count).\n // Reject with guidance instead of a confusing per-character failure.\n for (const key of ['media', 'thread', 'account', 'altText'] as const) {\n if (row[key] !== undefined && !Array.isArray(row[key])) {\n throw new Error(`\"${key}\" is multi-value — use a JSON input file with an array (CSV can't express it).`)\n }\n }\n return {\n ...(row as Partial<PostFields>),\n brandSlug: brand,\n text: String(row.text),\n platforms: String(platforms),\n }\n}\n\n/**\n * Create posts in bulk. Each row is independent — a failure is captured and the\n * loop continues — so the caller maps any failed record to a non-zero exit.\n * Runs non-interactively (no per-row account picker): a row whose platform has\n * multiple accounts and no selector fails fast and is reported.\n *\n * ponytail: no idempotency key — re-running a partially-failed batch re-creates\n * the rows that already succeeded. Split the file or de-dupe upstream to re-run.\n */\nexport async function createPostsBulk(\n client: Autoposting,\n rows: Record<string, unknown>[],\n opts: { cliBrand?: string } = {},\n): Promise<BulkRecordResult[]> {\n const results: BulkRecordResult[] = []\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!\n try {\n const fields = rowToFields(row, opts.cliBrand)\n const created = (await buildAndCreatePost(client, fields, { isTty: false })) as { id?: string }\n results.push({ index: i, status: 'created', id: created?.id ?? '', text: fields.text, error: '' })\n } catch (err) {\n results.push({\n index: i,\n status: 'failed',\n id: '',\n text: String(row.text ?? ''),\n error: (err as Error).message,\n })\n }\n }\n return results\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createKbCommand(): Command {\n const kb = new Command('kb').description('Manage knowledge bases')\n\n // ap kb list\n kb\n .command('list')\n .description('List all knowledge bases')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching knowledge bases…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.kb.list()\n spinner.stop()\n const rows = list.map((k) => ({\n id: k.id,\n name: k.name,\n docs: k.docCount ?? 0,\n createdAt: k.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'docs', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb get <id>\n kb\n .command('get <id>')\n .description('Get a knowledge base by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.kb.retrieve(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb create --name <name> --description <description>\n kb\n .command('create')\n .description('Create a new knowledge base')\n .requiredOption('--name <name>', 'Knowledge base name')\n .requiredOption('--description <description>', 'Knowledge base description (20–500 characters)')\n .action(async (opts: { name: string; description: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating knowledge base…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.kb.create({ name: opts.name, description: opts.description })\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb delete <id> [--force]\n kb\n .command('delete <id>')\n .description('Delete a knowledge base (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a knowledge base. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.kb.remove(id)\n spinner.stop()\n printer.log(`Knowledge base \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb search <id> --query <text>\n kb\n .command('search <id>')\n .description('Search a knowledge base')\n .requiredOption('--query <text>', 'Search query')\n .action(async (id: string, opts: { query: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Searching knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const res = await client.kb.search(id, opts.query)\n spinner.stop()\n const rows = res.results.map((r) => ({\n kind: r.kind,\n score: r.score != null ? r.score.toFixed(3) : '—',\n uri: r.uri ?? '—',\n content: r.content.length > 80 ? `${r.content.slice(0, 77)}…` : r.content,\n }))\n printer.table(rows, ['kind', 'score', 'uri', 'content'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb ingest <id> --url <url>\n kb\n .command('ingest <id>')\n .description('Ingest a URL into a knowledge base')\n .requiredOption('--url <url>', 'URL to ingest')\n .action(async (id: string, opts: { url: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Ingesting URL into knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const doc = await client.kb.ingestUrl(id, opts.url)\n spinner.stop()\n printer.log(doc)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb docs <id>\n kb\n .command('docs <id>')\n .description('List documents in a knowledge base')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching documents for knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const docs = await client.kb.docs(id)\n spinner.stop()\n const rows = docs.map((d) => ({\n id: d.id,\n name: d.name,\n type: d.type,\n status: d.status,\n createdAt: d.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'type', 'status', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return kb\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\n// The ideas/enrich domain uses `twitter` (NOT the posts domain's `x`); backend caps at 5.\nconst VALID_IDEA_PLATFORMS = ['twitter', 'linkedin', 'instagram', 'youtube', 'threads'] as const\n\nfunction parseIdeaPlatforms(raw: string): Array<{ platform: (typeof VALID_IDEA_PLATFORMS)[number] }> {\n const parts = raw.split(',').map((p) => p.trim()).filter(Boolean)\n if (parts.length === 0) {\n throw new Error('No platforms provided. e.g. --platforms twitter,linkedin')\n }\n if (parts.length > 5) {\n throw new Error('At most 5 platforms allowed per enrichment request.')\n }\n const invalid = parts.filter((p) => !VALID_IDEA_PLATFORMS.includes(p as never))\n if (invalid.length > 0) {\n throw new Error(\n `Unsupported platform(s): ${invalid.join(', ')}. Valid: ${VALID_IDEA_PLATFORMS.join(', ')}`,\n )\n }\n return parts.map((platform) => ({ platform: platform as (typeof VALID_IDEA_PLATFORMS)[number] }))\n}\n\nexport function createIdeasCommand(): Command {\n const ideas = new Command('ideas').description('Manage content ideas')\n\n // ap ideas generate [--kb <id>] [--topic <text>] [--count <n>]\n ideas\n .command('generate')\n .description('Generate content ideas')\n .option('--kb <id>', 'Knowledge base ID to draw context from')\n .option('--topic <text>', 'Topic or theme for ideas')\n .option('--count <n>', 'Number of ideas to generate', '5')\n .action(async (opts: { kb?: string; topic?: string; count: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Generating ideas…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.ideas.generate({\n ...(opts.kb ? { kbId: opts.kb } : {}),\n ...(opts.topic ? { topic: opts.topic } : {}),\n count: parseInt(opts.count, 10),\n })\n spinner.stop()\n const rows = (result.ideas ?? []).map((i) => ({\n id: i.id ?? '—',\n platform: i.targetPlatform,\n score: i.viralityScore,\n title: i.title.length > 80 ? `${i.title.slice(0, 77)}…` : i.title,\n }))\n printer.table(rows, ['id', 'platform', 'score', 'title'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap ideas list\n ideas\n .command('list')\n .description('List all ideas')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching ideas…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.ideas.list()\n spinner.stop()\n const rows = list.items.map((i) => ({\n id: i.id,\n topic: i.topic || '—',\n platform: i.targetPlatform,\n score: i.viralityScore,\n status: i.status,\n title: i.title.length > 60 ? `${i.title.slice(0, 57)}…` : i.title,\n }))\n printer.table(rows, ['id', 'topic', 'platform', 'score', 'status', 'title'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap ideas enrich --title <t> --hook <h> --angle <a> --platforms <list> [--kb <id>]\n // Backend enriches the idea object (not an id) across 1..5 platforms; async → job id.\n ideas\n .command('enrich')\n .description('Enrich an idea into platform-ready drafts (async; returns a job ID)')\n .requiredOption('--title <text>', 'Idea title')\n .requiredOption('--hook <text>', 'Idea hook')\n .requiredOption('--angle <text>', 'Idea angle')\n .requiredOption('--platforms <list>', `Comma-separated platforms (${VALID_IDEA_PLATFORMS.join(',')})`)\n .option('--kb <id>', 'Knowledge base ID for additional context')\n .action(\n async (\n opts: { title: string; hook: string; angle: string; platforms: string; kb?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Queuing enrichment…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { jobId } = await client.ideas.enrich({\n idea: { title: opts.title, hook: opts.hook, angle: opts.angle },\n platforms: parseIdeaPlatforms(opts.platforms),\n ...(opts.kb ? { kbId: opts.kb } : {}),\n })\n spinner.stop()\n printer.log(`Enrichment queued. Job ID: ${jobId}`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap ideas delete <id> [--force]\n ideas\n .command('delete <id>')\n .description('Delete an idea (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete an idea. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting idea \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.ideas.remove(id)\n spinner.stop()\n printer.log(`Idea \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return ideas\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createUsageCommand(): Command {\n const usage = new Command('usage').description('View usage statistics')\n\n // ap usage summary\n usage\n .command('summary')\n .description('Show usage summary for the current period')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching usage summary…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const summary = await client.usage.summary()\n spinner.stop()\n if (!printer.isTty()) {\n printer.log(summary)\n return\n }\n printer.log(`Period: ${summary.range.from.slice(0, 10)} → ${summary.range.to.slice(0, 10)}`)\n printer.table(\n [\n {\n posts: summary.posts.total,\n published: summary.posts.published,\n agents: summary.agents.total,\n 'active agents': summary.agents.active,\n 'ai cost (usd)': summary.ai.totalCostUsd,\n 'ai requests': summary.ai.requests,\n },\n ],\n ['posts', 'published', 'agents', 'active agents', 'ai cost (usd)', 'ai requests'],\n )\n const sourceRows = Object.entries(summary.posts.bySource).map(([source, count]) => ({\n source,\n posts: count,\n }))\n printer.table(sourceRows, ['source', 'posts'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return usage\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createWebhooksCommand(): Command {\n const webhooks = new Command('webhooks').description('Manage webhooks')\n\n // ap webhooks list\n webhooks\n .command('list')\n .description('List all webhooks')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching webhooks…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.webhooks.list()\n spinner.stop()\n const rows = list.map((w) => ({\n id: w.id,\n url: w.url,\n events: w.events.join(', '),\n active: w.active ? 'yes' : 'no',\n createdAt: w.createdAt,\n }))\n printer.table(rows, ['id', 'url', 'events', 'active', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks get <id>\n webhooks\n .command('get <id>')\n .description('Get a webhook by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.retrieve(id)\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks create --url <url> --events <post.published,post.failed,...>\n webhooks\n .command('create')\n .description('Create a new webhook')\n .requiredOption('--url <url>', 'Endpoint URL to receive events')\n .requiredOption('--events <list>', 'Comma-separated event types (e.g. post.published,post.failed)')\n .option('--secret <secret>', 'Signing secret for HMAC verification')\n .action(\n async (opts: { url: string; events: string; secret?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating webhook…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.create({\n url: opts.url,\n events: opts.events.split(',').map((e) => e.trim()),\n ...(opts.secret ? { secret: opts.secret } : {}),\n })\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap webhooks update <id> [--url <url>] [--events <events>] [--active]\n webhooks\n .command('update <id>')\n .description('Update a webhook')\n .option('--url <url>', 'New endpoint URL')\n .option('--events <list>', 'New comma-separated event types')\n .option('--active', 'Set webhook as active')\n .option('--no-active', 'Set webhook as inactive')\n .action(\n async (\n id: string,\n opts: { url?: string; events?: string; active?: boolean },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.update(id, {\n ...(opts.url ? { url: opts.url } : {}),\n ...(opts.events ? { events: opts.events.split(',').map((e) => e.trim()) } : {}),\n ...(opts.active !== undefined ? { active: opts.active } : {}),\n })\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap webhooks delete <id> --force\n webhooks\n .command('delete <id>')\n .description('Delete a webhook (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a webhook. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.webhooks.remove(id)\n spinner.stop()\n printer.log(`Webhook \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks test <id>\n webhooks\n .command('test <id>')\n .description('Send a test event to a webhook')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Sending test event to webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.webhooks.test(id)\n spinner.stop()\n printer.log(\n `Test event sent to webhook \"${id}\" — delivered: ${result.delivered ? 'yes' : 'no'} (HTTP ${result.httpStatus}).`,\n )\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return webhooks\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createWorkspacesCommand(): Command {\n const workspaces = new Command('workspaces').description('Manage workspaces')\n\n // ap workspaces list\n workspaces\n .command('list')\n .description('List all workspaces')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching workspaces…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n // CLI auth is always an API key, so the SDK's default authSource ('api-key')\n // makes workspaces.list() fail fast with guidance instead of a bare 401.\n const client = new Autoposting({ apiKey: cred.apiKey })\n const res = await client.workspaces.list()\n spinner.stop()\n const rows = res.organizations.map((w) => ({\n id: w.id,\n name: w.name,\n slug: w.slug,\n active: w.id === res.activeOrgId ? 'yes' : 'no',\n createdAt: w.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'slug', 'active', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap workspaces switch <id>\n workspaces\n .command('switch <id>')\n .description('Switch the active workspace (session auth only)')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Switching to workspace \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n // CLI auth is always an API key; the SDK's default authSource ('api-key')\n // makes switchWorkspace() reject with guidance (switching needs session auth).\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.workspaces.switchWorkspace(id)\n spinner.stop()\n printer.log(`Switched to workspace \"${id}\".`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return workspaces\n}\n","import { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { getCredentialsPath } from '../auth/credential-store.js'\nimport fs from 'node:fs'\n\nconst API_HEALTH_URL = 'https://app.autoposting.ai/api-proxy/health'\n\ntype CheckResult = {\n name: string\n status: 'pass' | 'fail' | 'warn'\n value: string\n}\n\nasync function runChecks(): Promise<CheckResult[]> {\n const results: CheckResult[] = []\n\n // CLI Version\n results.push({ name: 'CLI Version', status: 'pass', value: VERSION })\n\n // Node.js\n const nodeVersion = process.version\n const nodeMajor = parseInt(nodeVersion.slice(1), 10)\n results.push({\n name: 'Node.js',\n status: nodeMajor >= 20 ? 'pass' : 'fail',\n value: nodeVersion,\n })\n\n // Auth (local credential presence only — server validation happens in `whoami`)\n try {\n resolveAuth()\n results.push({ name: 'Auth', status: 'pass', value: 'credentials configured' })\n } catch {\n results.push({ name: 'Auth', status: 'fail', value: 'not configured' })\n }\n\n // Credentials file permissions\n const credPath = getCredentialsPath()\n try {\n const stat = fs.statSync(credPath)\n const mode = stat.mode & 0o777\n const isSecure = mode === 0o600\n results.push({\n name: 'Credentials',\n status: isSecure ? 'pass' : 'warn',\n value: isSecure\n ? `${credPath} (0600)`\n : `${credPath} (mode ${mode.toString(8)} — expected 0600)`,\n })\n } catch {\n results.push({\n name: 'Credentials',\n status: 'warn',\n value: 'no credentials file found',\n })\n }\n\n // API health\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 5000)\n const res = await fetch(API_HEALTH_URL, { signal: controller.signal })\n clearTimeout(timeout)\n results.push({\n name: 'API',\n status: res.ok ? 'pass' : 'fail',\n value: `HTTP ${res.status}`,\n })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n results.push({ name: 'API', status: 'fail', value: `unreachable: ${msg}` })\n }\n\n return results\n}\n\nexport function createDoctorCommand(): Command {\n const cmd = new Command('doctor')\n .description('Run diagnostic checks on your CLI setup')\n .option('--json', 'Output results as JSON')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{ json?: boolean }>()\n const results = await runChecks()\n\n if (globals.json) {\n console.log(JSON.stringify(results, null, 2))\n } else {\n for (const r of results) {\n const icon =\n r.status === 'pass' ? '✓' : r.status === 'warn' ? '!' : '✗'\n const label =\n r.status === 'pass' ? 'pass' : r.status === 'warn' ? 'warn' : 'FAIL'\n console.log(` ${icon} ${r.name.padEnd(16)} [${label}] ${r.value}`)\n }\n }\n\n const anyFail = results.some((r) => r.status === 'fail')\n if (anyFail) process.exit(1)\n })\n\n return cmd\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport type { AuthProfile } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { readCredentials } from '../auth/credential-store.js'\nimport { EXIT_CODES, exitCodeFromError } from '../output/exit-codes.js'\n\nexport function createWhoamiCommand(): Command {\n return new Command('whoami')\n .description('Show the current identity and validate the key against the server')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{ apiKey?: string; json?: boolean }>()\n\n let cred: ReturnType<typeof resolveAuth>\n try {\n cred = resolveAuth({ apiKey: globals.apiKey })\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exitCode = exitCodeFromError(err)\n return\n }\n\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n\n // Validate the key AND resolve the server-side identity in one call. /auth/profile runs\n // the shared authenticate middleware (accepts the Bearer API key), so a valid key returns\n // 200 + identity (orgId, authType) and an invalid/revoked one returns 401. A network/\n // transport failure must NOT fail whoami: degrade to \"unverified\" so it still works\n // offline; only a definitive rejection (401/403) exits non-zero.\n let validity: 'valid' | 'rejected' | 'unverified' = 'unverified'\n let identity: AuthProfile | undefined\n try {\n const client = new Autoposting({ apiKey: cred.apiKey, maxRetries: 0 })\n identity = await client.getProfile()\n validity = 'valid'\n } catch (err) {\n const code = exitCodeFromError(err)\n validity =\n code === EXIT_CODES.AUTH_ERROR || code === EXIT_CODES.SCOPE_ERROR\n ? 'rejected'\n : 'unverified'\n }\n\n const exitCode = validity === 'rejected' ? EXIT_CODES.AUTH_ERROR : 0\n\n const creds = cred.source === 'stored' ? readCredentials() : undefined\n const profileName = creds?.activeProfile ?? 'unknown'\n const email = creds?.profiles[profileName]?.email\n\n if (globals.json) {\n const out: Record<string, unknown> = {\n source: cred.source,\n apiKey: masked,\n valid: validity === 'valid',\n validity,\n }\n if (identity?.orgId) {\n out.orgId = identity.orgId\n out.authType = identity.authType\n if (identity.email) out.email = identity.email\n }\n if (cred.source === 'stored') {\n out.profile = profileName\n if (email) out.email = email\n }\n console.log(JSON.stringify(out, null, 2))\n // Set exitCode (not process.exit) so a piped --json stream flushes fully before exit.\n process.exitCode = exitCode\n return\n }\n\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n console.log(`Profile: ${profileName}`)\n if (email) console.log(`Email: ${email}`)\n }\n if (identity?.orgId) {\n console.log(`Org: ${identity.orgId}`)\n console.log(`Auth: ${identity.authType}`)\n }\n const tag =\n validity === 'valid'\n ? '✓ valid'\n : validity === 'rejected'\n ? '✗ rejected by server'\n : '⚠ unverified (could not reach server)'\n console.log(`API key: ${masked} ${tag}`)\n process.exitCode = exitCode\n })\n}\n","import { Command } from 'commander'\nimport open from 'open'\n\nconst URLS: Record<string, string> = {\n '': 'https://app.autoposting.ai',\n posts: 'https://app.autoposting.ai/posts',\n brands: 'https://app.autoposting.ai/brands',\n agents: 'https://app.autoposting.ai/agents',\n settings: 'https://app.autoposting.ai/settings',\n billing: 'https://app.autoposting.ai/settings/billing',\n}\n\nconst VALID_SECTIONS = Object.keys(URLS).filter((k) => k !== '')\n\nexport function createOpenCommand(): Command {\n return new Command('open')\n .description(`Open the Autoposting dashboard in your browser. Sections: ${VALID_SECTIONS.join(', ')}`)\n .argument('[section]', `Dashboard section to open (${VALID_SECTIONS.join('|')})`, '')\n .option('--no-browser', 'Print URL only, do not open browser')\n .action(async (section: string, opts: { browser: boolean }) => {\n const key = section ?? ''\n if (!(key in URLS)) {\n console.error(`Error: unknown section \"${key}\". Valid sections: ${VALID_SECTIONS.join(', ')}`)\n process.exit(1)\n }\n\n const url = URLS[key]\n\n if (!opts.browser) {\n console.log(url)\n return\n }\n\n console.log(`Opening ${url}`)\n try {\n await open(url)\n } catch (err) {\n console.error(`Error: failed to open browser — ${(err as Error).message}`)\n console.log(`Visit manually: ${url}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { execSync } from 'node:child_process'\n\nconst REGISTRY_URL = 'https://registry.npmjs.org/@autoposting.ai%2fcli/latest'\n\nexport function createUpdateCommand(): Command {\n return new Command('update')\n .description(\n 'Check for a newer version of the CLI and optionally install it',\n )\n .option('--yes', 'Install the latest version without prompting')\n .action(async (opts: { yes?: boolean }) => {\n let latest: string\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 8000)\n const res = await fetch(REGISTRY_URL, { signal: controller.signal })\n clearTimeout(timeout)\n if (!res.ok) {\n console.error(`Error: registry returned HTTP ${res.status}`)\n process.exit(1)\n }\n const data = (await res.json()) as { version: string }\n latest = data.version\n } catch (err) {\n console.error(\n `Error: could not reach npm registry — ${(err as Error).message}`,\n )\n process.exit(1)\n }\n\n if (latest === VERSION) {\n console.log(`You are already on the latest version (${VERSION}).`)\n return\n }\n\n console.log(`Current version: ${VERSION}`)\n console.log(`Latest version: ${latest}`)\n\n if (!opts.yes) {\n console.log(`Run \\`ap update --yes\\` to install v${latest}.`)\n return\n }\n\n console.log(`Installing @autoposting.ai/cli@${latest}…`)\n try {\n execSync(`npm install -g @autoposting.ai/cli@${latest}`, {\n stdio: 'inherit',\n })\n console.log(`Updated to v${latest}.`)\n } catch (err) {\n console.error(`Error: install failed — ${(err as Error).message}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\n\nconst ALL_COMMANDS = [\n 'posts',\n 'brands',\n 'accounts',\n 'agents',\n 'kb',\n 'ideas',\n 'clips',\n 'carousels',\n 'webhooks',\n 'billing',\n 'usage',\n 'workspaces',\n 'auth',\n 'doctor',\n 'whoami',\n 'open',\n 'update',\n 'completion',\n]\n\nconst SHELLS = ['bash', 'zsh', 'fish', 'pwsh'] as const\ntype Shell = (typeof SHELLS)[number]\n\nconst TEMPLATES: Record<Shell, (cmds: string[]) => string> = {\n bash: (cmds) => `# bash completion for ap / autoposting\n# Add to ~/.bashrc or ~/.bash_profile:\n# source <(ap completion bash)\n_ap_completions() {\n local cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n local commands=\"${cmds.join(' ')}\"\n COMPREPLY=( $(compgen -W \"$commands\" -- \"$cur\") )\n}\ncomplete -F _ap_completions ap\ncomplete -F _ap_completions autoposting\n`,\n\n zsh: (cmds) => `# zsh completion for ap / autoposting\n# Add to ~/.zshrc:\n# source <(ap completion zsh)\n# Or append directly:\n# ap completion zsh >> ~/.zshrc\n_ap() {\n compadd ${cmds.join(' ')}\n}\ncompdef _ap ap autoposting\n`,\n\n fish: (cmds) => `# fish completion for ap / autoposting\n# Save to ~/.config/fish/completions/ap.fish or run:\n# ap completion fish | source\n${cmds.map((c) => `complete -c ap -f -a '${c}'`).join('\\n')}\n${cmds.map((c) => `complete -c autoposting -f -a '${c}'`).join('\\n')}\n`,\n\n pwsh: (cmds) => `# PowerShell completion for ap / autoposting\n# Add to your $PROFILE:\n# ap completion pwsh | Invoke-Expression\nRegister-ArgumentCompleter -Native -CommandName @('ap', 'autoposting') -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $commands = @(${cmds.map((c) => `'${c}'`).join(', ')})\n $commands | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n`,\n}\n\nexport function createCompletionCommand(): Command {\n return new Command('completion')\n .description(`Generate shell completion script. Shells: ${SHELLS.join(', ')}`)\n .argument('<shell>', `Shell type (${SHELLS.join('|')})`)\n .action((shell: string) => {\n if (!SHELLS.includes(shell as Shell)) {\n console.error(`Error: unsupported shell \"${shell}\". Supported: ${SHELLS.join(', ')}`)\n process.exit(1)\n }\n process.stdout.write(TEMPLATES[shell as Shell](ALL_COMMANDS))\n })\n}\n","import { Command } from 'commander'\n\nexport function createMcpCommand(): Command {\n return new Command('mcp')\n .description('Start MCP stdio server for AI agent integration')\n .action(async () => {\n const { startMcpServer } = await import('../mcp/server.js')\n await startMcpServer()\n })\n}\n","import { Command } from 'commander'\nimport { createPrinter } from '../output/printer.js'\nimport { getContextBrand, setContextBrand, unsetContextBrand } from '../auth/config-store.js'\n\ntype GlobalOpts = {\n json?: boolean\n quiet?: boolean\n format?: 'auto' | 'table' | 'json'\n jq?: string\n}\n\nexport function createConfigCommand(): Command {\n const config = new Command('config').description('Manage CLI defaults (stored in config.json)')\n\n // ap config set-context --brand <slug>\n config\n .command('set-context')\n .description('Set the default brand used when --brand is omitted')\n .requiredOption('--brand <slug>', 'Brand slug to use as the default context')\n .action((opts: { brand: string }, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n setContextBrand(opts.brand)\n printer.log({ brand: opts.brand })\n })\n\n // ap config get-context\n config\n .command('get-context')\n .description('Show the default brand context')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n const brand = getContextBrand()\n if (!brand) {\n printer.error('No brand context set. Set one with: ap config set-context --brand <slug>')\n process.exit(1)\n }\n printer.log({ brand })\n })\n\n // ap config unset-context\n config\n .command('unset-context')\n .description('Clear the default brand context')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n unsetContextBrand()\n printer.log({ brand: null })\n })\n\n return config\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { EXIT_CODES, exitCodeFromError } from '../output/exit-codes.js'\nimport { assertApiRoute, fetchApiRoutes } from '../lib/api-routes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\ntype ApiOpts = { data?: string; field: string[]; query: string[]; list?: boolean }\n\nfunction validationError(message: string): Error {\n return Object.assign(new Error(message), { exitCode: EXIT_CODES.VALIDATION_ERROR })\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value]\n}\n\n/** `key=value` pairs; a value that parses as JSON (number, boolean, null, object) is used as such. */\nexport function parseFields(pairs: string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const pair of pairs) {\n const i = pair.indexOf('=')\n if (i < 1) throw validationError(`Expected key=value, got \"${pair}\".`)\n const raw = pair.slice(i + 1)\n let value: unknown = raw\n try {\n value = JSON.parse(raw)\n } catch {\n // keep as string\n }\n out[pair.slice(0, i)] = value\n }\n return out\n}\n\nexport function createApiCommand(): Command {\n return new Command('api')\n .description('Call any Autoposting REST route on the server allow-list, like `gh api`')\n .argument('[method]', 'GET, POST, PUT, PATCH or DELETE')\n .argument('[path]', 'Route path, e.g. /clips/abc123/jobs')\n .option('-d, --data <json>', 'JSON request body')\n .option('-f, --field <key=value>', 'Body field (repeatable)', collect, [])\n .option('-q, --query <key=value>', 'Query parameter (repeatable)', collect, [])\n .option('--list [prefix]', 'List the routes you may call')\n .action(async (method: string | undefined, path: string | undefined, opts: ApiOpts, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n let body: Record<string, unknown> | undefined\n if (opts.data !== undefined) {\n try {\n body = JSON.parse(opts.data) as Record<string, unknown>\n } catch {\n throw validationError('--data is not valid JSON.')\n }\n }\n if (opts.field.length > 0) body = { ...body, ...parseFields(opts.field) }\n const query = opts.query.length > 0 ? parseFields(opts.query) : undefined\n\n const client = new Autoposting({ apiKey: cred.apiKey })\n const routes = await fetchApiRoutes(client)\n if (opts.list !== undefined) {\n const prefix = typeof opts.list === 'string' ? opts.list : '/'\n printer.log(routes.filter((r) => r.split(' ')[1].startsWith(prefix)))\n return\n }\n if (!method || !path) throw validationError('Usage: ap api <METHOD> <path>, or ap api --list.')\n const m = method.toUpperCase()\n try {\n assertApiRoute(routes, m, path)\n } catch (err) {\n throw validationError((err as Error).message)\n }\n const sendBody = m === 'GET' || m === 'DELETE' ? undefined : body\n printer.log(await client.request(m as never, path, sendBody, query))\n } catch (err) {\n printer.error(err as Error)\n const attached = (err as { exitCode?: number }).exitCode\n process.exit(typeof attached === 'number' ? attached : exitCodeFromError(err))\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AGyBO,SAAS,YACd,QACA,MACkB;AAClB,QAAM,UAAU,KAAK,SAAS;AAC9B,QAAM,OAAO,KAAK,QAAQ;AAE1B,MAAI,WAAW,IAAK,QAAO,IAAI,oBAAoB,SAAS,QAAQ,IAAI;AACxE,MAAI,WAAW,IAAK,QAAO,IAAI,WAAW,SAAS,QAAQ,IAAI;AAC/D,MAAI,WAAW,IAAK,QAAO,IAAI,cAAc,SAAS,QAAQ,IAAI;AAClE,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,IAAI,gBAAgB,SAAS,QAAQ,IAAI;AACtF,MAAI,WAAW,IAAK,QAAO,IAAI,eAAe,SAAS,QAAQ,IAAI;AACnE,MAAI,UAAU,IAAK,QAAO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AAsB,CAAC;AAC1C,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,uBAAuB,CAAC;AAC3C,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,iBAAiB,CAAC;AACrC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,gBAAgB,CAAC;AACpC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,sBAAsB,CAAC;AAC1C,QAAQ,WAAW,wBAAwB,CAAC;AAC5C,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,kBAAkB,CAAC;AACtC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,wBAAwB,CAAC;AAC5C,QAAQ,WAAW,iBAAiB,CAAC;AACrC,QAAQ,WAAW,oBAAoB,CAAC;AAExC,QAAQ,MAAM;","names":["path","open","basename","import_node_fs","path","parsePlatforms","path","import_promises","import_node_path","import_commander","path","os","fs","import_commander","import_commander","resolveExitCode","import_commander","import_commander","import_node_fs","import_node_os","import_node_path","path","os","fs","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","import_promises","import_node_path","VALID_PLATFORMS","ok","VALID_PLATFORMS","path","fs","nodePath","import_node_fs","fs","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","import_node_fs","fs","cmd","import_commander","import_commander","open","import_commander","import_node_child_process","import_commander","import_commander","startMcpServer","import_commander","import_commander","path"]}
|
|
1
|
+
{"version":3,"sources":["../../sdk/src/resource.ts","../../sdk/src/resources/account-onboarding.ts","../../sdk/src/version.ts","../../sdk/src/errors.ts","../../sdk/src/resources/media.ts","../../sdk/src/resources/agents.ts","../../sdk/src/resources/billing.ts","../../sdk/src/resources/brands.ts","../../sdk/src/resources/carousels.ts","../../sdk/src/resources/clips.ts","../../sdk/src/resources/posts.ts","../../sdk/src/resources/kb.ts","../../sdk/src/resources/ideas.ts","../../sdk/src/resources/usage.ts","../../sdk/src/resources/webhooks.ts","../../sdk/src/resources/workspaces.ts","../../sdk/src/client.ts","../src/lib/media-flags.ts","../src/mcp/tools.ts","../src/lib/api-routes.ts","../src/mcp/handler.ts","../src/mcp/server.ts","../src/cli.ts","../src/commands/agents.ts","../src/auth/credential-store.ts","../src/auth/auth-manager.ts","../src/output/formatter.ts","../src/output/spinner.ts","../src/output/printer.ts","../src/output/exit-codes.ts","../src/commands/auth.ts","../src/auth/device-code-client.ts","../src/commands/billing.ts","../src/commands/accounts.ts","../src/commands/brands.ts","../src/auth/config-store.ts","../src/commands/carousels.ts","../src/commands/clips.ts","../src/commands/posts.ts","../src/lib/post-create.ts","../src/lib/account-select.ts","../src/lib/post-bulk.ts","../src/commands/kb.ts","../src/commands/ideas.ts","../src/commands/usage.ts","../src/commands/webhooks.ts","../src/commands/workspaces.ts","../src/commands/doctor.ts","../src/commands/whoami.ts","../src/commands/open.ts","../src/commands/update.ts","../src/commands/completion.ts","../src/commands/mcp.ts","../src/commands/config.ts","../src/commands/api.ts"],"sourcesContent":["import type { Autoposting } from './client'\n\nexport abstract class Resource {\n constructor(protected client: Autoposting) {}\n\n protected get<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.client.request<T>('GET', path, undefined, query)\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('POST', path, body)\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('PUT', path, body)\n }\n\n protected patch<T>(path: string, body?: unknown): Promise<T> {\n return this.client.request<T>('PATCH', path, body)\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.client.request<T>('DELETE', path)\n }\n}\n","import { Resource } from '../resource'\nimport type { Platform } from '../types'\nexport interface AccountImportRow {\n brand_name: string\n brand_slug?: string\n platform: Platform\n account_url: string\n timezone?: string\n account_type?: 'personal' | 'organization'\n}\nexport interface AccountImport {\n id: string\n total: number\n next: string\n}\nexport type AccountImportRowStatus =\n | 'unprepared'\n | 'permission_denied'\n | 'pending_authorization'\n | 'needs_confirmation'\n | 'connected'\n | 'reconnect_required'\n | 'authorization_failed'\n | 'account_mismatch'\nexport interface AccountImportStatus {\n id: string\n total: number\n nextOffset: number | null\n connected: number\n unprepared: number\n capacity: {\n plan: string\n limit: number | null\n currentCount: number\n remaining: number | null\n }\n rows: Array<{\n id: string\n brandName?: string\n brandSlug?: string\n platform?: Platform\n accountUrl?: string\n status: AccountImportRowStatus\n error?: string\n lastError?: string\n accounts?: Array<{\n tokenId: string\n accountId?: string\n name?: string\n usable: boolean\n }>\n }>\n}\nexport interface AccountApproval {\n id: string\n rowId: string\n url: string\n accountUrl: string\n expiresInSeconds: number\n instructions: string\n}\nconst segment = (value: string) => {\n if (!/^[a-f0-9]{24}$/.test(value))\n throw new Error(\n 'Import and row identifiers must be 24-character hexadecimal strings',\n )\n return value\n}\nexport class AccountOnboardingResource extends Resource {\n remove(id: string): Promise<{ id: string; deleted: boolean }> {\n return this.delete(`/account-onboarding/${segment(id)}`)\n }\n create(\n input: { csv: string } | { rows: AccountImportRow[] },\n ): Promise<AccountImport> {\n return this.post('/account-onboarding', input)\n }\n status(\n id: string,\n query?: { offset?: number; limit?: number },\n ): Promise<AccountImportStatus> {\n return this.get(`/account-onboarding/${segment(id)}`, query)\n }\n prepare(\n id: string,\n offset = 0,\n ): Promise<{\n id: string\n rows: Array<{\n id: string\n brandSlug: string\n prepared: boolean\n error?: string\n }>\n nextOffset: number | null\n }> {\n return this.post(`/account-onboarding/${segment(id)}/prepare`, { offset })\n }\n authorize(id: string, rowId: string): Promise<AccountApproval> {\n return this.post(\n `/account-onboarding/${segment(id)}/rows/${segment(rowId)}/authorize`,\n )\n }\n confirm(\n id: string,\n rowId: string,\n tokenId: string,\n ): Promise<{ rowId: string; status: string; tokenId: string }> {\n return this.post(\n `/account-onboarding/${segment(id)}/rows/${segment(rowId)}/confirm`,\n { tokenId: segment(tokenId) },\n )\n }\n}\n","// ponytail: version injected at build from package.json via tsup `env` (see tsup.config.ts),\n// so package.json is the single source of truth and `changeset version` bumps flow through\n// automatically — no hand-edited constant to drift. Fallback covers running src directly\n// (vitest/ts-node) without a build.\nexport const VERSION = process.env.AUTOPOSTING_SDK_VERSION ?? '0.0.0-dev'\n","export class AutopostingError extends Error {\n status: number\n code: string\n\n constructor(message: string, status: number, code: string) {\n super(message)\n this.name = this.constructor.name\n this.status = status\n this.code = code\n // Restore prototype chain (required for custom Error subclasses in TS)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\nexport class AuthenticationError extends AutopostingError {}\nexport class ScopeError extends AutopostingError {}\nexport class NotFoundError extends AutopostingError {}\nexport class ValidationError extends AutopostingError {}\n\nexport class RateLimitError extends AutopostingError {\n retryAfter?: number\n}\n\nexport class ServerError extends AutopostingError {}\n\nexport function createError(\n status: number,\n body: { error?: string; code?: string },\n): AutopostingError {\n const message = body.error ?? 'An error occurred'\n const code = body.code ?? 'UNKNOWN'\n\n if (status === 401) return new AuthenticationError(message, status, code)\n if (status === 403) return new ScopeError(message, status, code)\n if (status === 404) return new NotFoundError(message, status, code)\n if (status === 400 || status === 422) return new ValidationError(message, status, code)\n if (status === 429) return new RateLimitError(message, status, code)\n if (status >= 500) return new ServerError(message, status, code)\n\n return new AutopostingError(message, status, code)\n}\n","import { Resource } from '../resource'\n\nexport interface MediaUpload {\n data: Uint8Array<ArrayBuffer> | Blob\n filename: string\n contentType?: string\n}\n\nexport interface UploadedMedia {\n url: string\n type: 'image' | 'video' | 'gif'\n filename: string\n}\n\nexport class MediaResource extends Resource {\n /** POST /media/upload — multipart/form-data, ≤20MB, image/* | video/*. */\n upload(file: MediaUpload): Promise<UploadedMedia> {\n const form = new FormData()\n const blob =\n file.data instanceof Blob\n ? file.data\n : new Blob([file.data], { type: file.contentType })\n form.append('file', blob, file.filename)\n return this.client.request<UploadedMedia>('POST', '/media/upload', form)\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Agent, AgentRun, CreateAgentParams, UpdateAgentParams } from '../types/agents'\n\nexport class AgentsResource extends Resource {\n /** GET /agents — backend returns `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Agent>> {\n return this.get<Paginated<Agent>>('/agents')\n }\n\n retrieve(id: string): Promise<Agent> {\n return this.get<Agent>(`/agents/${id}`)\n }\n\n create(params: CreateAgentParams): Promise<Agent> {\n return this.post<Agent>('/agents', params)\n }\n\n update(id: string, params: UpdateAgentParams): Promise<Agent> {\n return this.patch<Agent>(`/agents/${id}`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/agents/${id}`)\n }\n\n /** POST /agents/:id/run — queues a run; returns `{ runId, status }`, not a full AgentRun. */\n run(id: string): Promise<{ runId: string; status: string }> {\n return this.post<{ runId: string; status: string }>(`/agents/${id}/run`)\n }\n\n toggle(id: string): Promise<Agent> {\n return this.post<Agent>(`/agents/${id}/toggle`)\n }\n\n /** GET /agents/:id/runs — backend returns `{ items, total, limit, offset }`. */\n runs(id: string): Promise<Paginated<AgentRun>> {\n return this.get<Paginated<AgentRun>>(`/agents/${id}/runs`)\n }\n}\n","import { Resource } from '../resource'\nimport type { BillingStatus, CreditBalance } from '../types/billing'\n\nexport class BillingResource extends Resource {\n status(): Promise<BillingStatus> {\n return this.get<BillingStatus>('/billing/status')\n }\n\n credits(): Promise<CreditBalance> {\n return this.get<CreditBalance>('/billing/credits')\n }\n}\n","import { Resource } from '../resource'\nimport type { Brand, CreateBrandParams, PlatformConnection, UpdateBrandParams } from '../types/brands'\n\nexport class BrandsResource extends Resource {\n list(): Promise<Brand[]> {\n return this.get<Brand[]>('/brands')\n }\n\n retrieve(slug: string): Promise<Brand> {\n return this.get<Brand>(`/brands/${slug}`)\n }\n\n create(params: CreateBrandParams): Promise<Brand> {\n return this.post<Brand>('/brands', params)\n }\n\n update(slug: string, params: UpdateBrandParams): Promise<Brand> {\n return this.patch<Brand>(`/brands/${slug}`, params)\n }\n\n remove(slug: string): Promise<void> {\n return this.delete<void>(`/brands/${slug}`)\n }\n\n authStatus(slug: string): Promise<PlatformConnection[]> {\n return this.get<PlatformConnection[]>(`/brands/${slug}/auth/status`)\n }\n\n /** Browser session owns beta checks, official authorization and explicit Page selection. */\n async facebookConnection(slug: string): Promise<{ url: string; brandSlug: string; platform: 'facebook' }> {\n const brand = await this.retrieve(slug)\n const url = new URL('/brands', this.client.baseUrl)\n url.searchParams.set('brand', brand.slug)\n url.searchParams.set('platform', 'facebook')\n return { url: url.toString(), brandSlug: brand.slug, platform: 'facebook' }\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Carousel, CreateCarouselParams, GenerateCarouselParams } from '../types/carousels'\n\nexport class CarouselsResource extends Resource {\n /** GET /carousels — backend paginates: `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Carousel>> {\n return this.get<Paginated<Carousel>>('/carousels')\n }\n\n retrieve(id: string): Promise<Carousel> {\n return this.get<Carousel>(`/carousels/${id}`)\n }\n\n create(params?: CreateCarouselParams): Promise<Carousel> {\n return this.post<Carousel>('/carousels', params)\n }\n\n generate(params: GenerateCarouselParams): Promise<Carousel> {\n return this.post<Carousel>('/carousels/generate', params)\n }\n\n /** POST /carousels/:id/create-draft — converts carousel to a post draft */\n draft(id: string): Promise<Carousel> {\n return this.post<Carousel>(`/carousels/${id}/create-draft`)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/carousels/${id}`)\n }\n}\n","import { Resource } from '../resource'\nimport { AutopostingError } from '../errors'\nimport type { Clip, CreateClipDraftParams, ImportClipParams, RenderClipParams } from '../types/clips'\n\n// R2/S3 multipart: every part except the last must be ≥5MB; at most 10,000 parts.\nconst MIN_PART_SIZE = 5 * 1024 * 1024\nconst DEFAULT_PART_SIZE = 16 * 1024 * 1024\nconst MAX_PARTS = 10_000\n\nconst VIDEO_MIME: Record<string, string> = {\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n avi: 'video/x-msvideo',\n m4v: 'video/x-m4v',\n}\n\nexport interface UploadClipOptions {\n /** Brand the clip belongs to (required by the backend). */\n brandId: string\n /** Display title; defaults to the file name. */\n title?: string\n /** Override the detected MIME type. */\n contentType?: string\n /** Multipart chunk size in bytes (clamped to the 5MB..10k-part range). */\n partSize?: number\n /** Called after each part with overall percent uploaded (0–100). */\n onProgress?: (pct: number) => void\n}\n\nexport class ClipsResource extends Resource {\n /** GET /clips — backend returns `{ clips, pagination }`, not a bare array. */\n list(): Promise<{\n clips: Clip[]\n pagination: { page: number; limit: number; total: number; totalPages: number }\n }> {\n return this.client.request('GET', '/clips')\n }\n\n retrieve(id: string): Promise<Clip> {\n return this.client.request<Clip>('GET', `/clips/${id}`)\n }\n\n /**\n * Upload a local video file as a clip by driving the backend multipart flow:\n * `init → presign → PUT each part → complete`. On any failure after init, the\n * multipart upload is aborted so it leaves no dangling clip. Returns the created clip.\n *\n * Node-only: reads the file in chunks (memory-bounded for multi-GB videos). `node:fs`\n * is imported dynamically so the rest of the SDK stays runtime-agnostic.\n */\n async upload(filePath: string, options: UploadClipOptions): Promise<Clip> {\n if (!options?.brandId) {\n throw new AutopostingError('brandId is required to upload a clip.', 0, 'VALIDATION_ERROR')\n }\n\n const { open, stat } = await import('node:fs/promises')\n const { basename } = await import('node:path')\n\n const fileName = basename(filePath)\n const title = options.title ?? fileName\n const mimeType = options.contentType ?? guessVideoMime(fileName)\n const { size: fileSize } = await stat(filePath)\n if (fileSize <= 0) {\n throw new AutopostingError(`File is empty: ${filePath}`, 0, 'VALIDATION_ERROR')\n }\n\n const partSize = resolvePartSize(fileSize, options.partSize)\n const partNumbers = Array.from(\n { length: Math.max(1, Math.ceil(fileSize / partSize)) },\n (_, i) => i + 1,\n )\n\n const { clipId, uploadId, key } = await this.client.request<{\n clipId: string\n uploadId: string\n key: string\n }>('POST', '/clips/upload/init', { brandId: options.brandId, title, fileName, fileSize, mimeType })\n\n let completed: { clipId: string; status: string }\n const handle = await open(filePath, 'r')\n try {\n const { presignedUrls } = await this.client.request<{\n presignedUrls: { partNumber: number; url: string }[]\n }>('POST', '/clips/upload/presign', { clipId, uploadId, key, partNumbers })\n const urlByPart = new Map(presignedUrls.map((p) => [p.partNumber, p.url]))\n\n // ponytail: parts upload sequentially with no per-part retry — simple and correct for a\n // CLI. Add bounded concurrency / retry here if throughput on large files matters.\n const parts: { partNumber: number; etag: string }[] = []\n let uploaded = 0\n for (const partNumber of partNumbers) {\n const url = urlByPart.get(partNumber)\n if (!url) {\n throw new AutopostingError(`Missing presigned URL for part ${partNumber}.`, 0, 'UPLOAD_FAILED')\n }\n const offset = (partNumber - 1) * partSize\n const length = Math.min(partSize, fileSize - offset)\n const buffer = Buffer.allocUnsafe(length)\n await handle.read(buffer, 0, length, offset)\n parts.push({ partNumber, etag: await putPart(url, buffer) })\n uploaded += length\n options.onProgress?.(Math.round((uploaded / fileSize) * 100))\n }\n\n completed = await this.client.request<{ clipId: string; status: string }>(\n 'POST',\n '/clips/upload/complete',\n { clipId, uploadId, key, parts },\n )\n } catch (err) {\n // Best-effort abort so a failed upload doesn't strand a multipart upload + 'uploading' clip.\n // Only the init→presign→PUT→complete steps reach here; once complete succeeds the upload is\n // done, so a later retrieve() failure (below) must NOT trigger an abort of a good clip.\n await this.client.request('POST', '/clips/upload/abort', { clipId, uploadId, key }).catch(() => {})\n throw err\n } finally {\n await handle.close()\n }\n return this.retrieve(completed.clipId)\n }\n\n /** POST /clips/import-url — backend returns `{ clipId }`, not a full Clip. */\n importUrl(params: ImportClipParams): Promise<{ clipId: string }> {\n return this.client.request<{ clipId: string }>('POST', '/clips/import-url', params)\n }\n\n /** POST /clips/:id/render — backend returns render job ids, not a Clip. */\n async render(\n id: string,\n params: RenderClipParams = {},\n ): Promise<{ jobIds: string[]; activeJobIds: string[]; reusedJobIds: string[] }> {\n const editRevision = params.editRevision ?? (await this.retrieve(id)).editRevision ?? 0\n return this.client.request('POST', `/clips/${id}/render`, {\n editRevision,\n ...(params.candidateId ? { candidateId: params.candidateId } : {}),\n })\n }\n\n /** POST /clips/:id/create-draft — turns a rendered clip into a draft post. */\n createDraft(id: string, params: CreateClipDraftParams = {}): Promise<{ postId: string }> {\n return this.client.request<{ postId: string }>('POST', `/clips/${id}/create-draft`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/clips/${id}`)\n }\n}\n\n/** Pick a chunk size that respects the 5MB minimum and the 10,000-part ceiling. */\nfunction resolvePartSize(fileSize: number, requested?: number): number {\n let size = requested && requested > 0 ? requested : DEFAULT_PART_SIZE\n if (Math.ceil(fileSize / size) > MAX_PARTS) size = Math.ceil(fileSize / MAX_PARTS)\n return Math.max(size, MIN_PART_SIZE)\n}\n\nfunction guessVideoMime(fileName: string): string {\n const ext = fileName.split('.').pop()?.toLowerCase() ?? ''\n return VIDEO_MIME[ext] ?? 'video/mp4'\n}\n\n/**\n * PUT one part to its presigned URL with a raw fetch — the URL is pre-authorized, so the\n * SDK's Bearer token and base URL must NOT be attached. Returns the part's ETag (kept\n * verbatim, quotes included, as CompleteMultipartUpload expects).\n */\nasync function putPart(url: string, body: Buffer): Promise<string> {\n let res: Response\n try {\n res = await fetch(url, { method: 'PUT', body })\n } catch (err) {\n throw new AutopostingError(\n `Failed to upload part: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n 'UPLOAD_FAILED',\n )\n }\n if (!res.ok) {\n throw new AutopostingError(\n `Failed to upload part: HTTP ${res.status} ${res.statusText}`,\n res.status,\n 'UPLOAD_FAILED',\n )\n }\n const etag = res.headers.get('etag')\n if (!etag) {\n throw new AutopostingError('Upload part response is missing the ETag header.', res.status, 'UPLOAD_FAILED')\n }\n return etag\n}\n","import type { Platform } from '../types'\nimport { Resource } from '../resource'\nimport type { Post, CreatePostParams, UpdatePostParams, ListPostsParams, FacebookRetryResult, FacebookRecoveryScheduleResult } from '../types/posts'\n\n// PostsResource methods `get` and `delete` cannot directly override the base class\n// protected generics (`get<T>`, `delete<T>`) due to TypeScript generic covariance rules.\n// We call `this.client.request` directly and expose public methods with unambiguous names.\n// The public API surface is: list, get, create, update, delete, publish, schedule, unschedule, retry, rewrite, score.\nexport class PostsResource extends Resource {\n /** GET /posts — backend returns a bare array (no pagination metadata). */\n list(params: ListPostsParams = {}): Promise<Post[]> {\n const { brandSlug, status, limit, page } = params\n const query: Record<string, unknown> = {}\n if (brandSlug) query.brandSlug = brandSlug\n if (status) query.status = status\n if (limit !== undefined) query.limit = limit\n // The backend paginates by `offset`, not `page` — translate so `--page` actually\n // advances results instead of being silently ignored.\n if (page !== undefined && page > 1) query.offset = (page - 1) * (limit ?? 20)\n return this.client.request<Post[]>('GET', '/posts', undefined, query)\n }\n\n /** GET /posts/:id */\n getById(id: string): Promise<Post> {\n return this.client.request<Post>('GET', `/posts/${id}`)\n }\n\n create(params: CreatePostParams): Promise<Post> {\n return this.client.request<Post>('POST', '/posts', params)\n }\n\n update(id: string, params: UpdatePostParams): Promise<Post> {\n return this.client.request<Post>('PUT', `/posts/${id}`, params)\n }\n\n /** DELETE /posts/:id */\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/posts/${id}`)\n }\n\n publish(id: string): Promise<Post> {\n return this.client.request<Post>('POST', `/posts/${id}/publish`)\n }\n\n schedule(id: string, scheduledAt: string): Promise<Post>\n schedule(id: string, scheduledAt: string, platform: 'facebook'): Promise<FacebookRecoveryScheduleResult>\n schedule(id: string, scheduledAt: string, platform?: 'facebook'): Promise<Post | FacebookRecoveryScheduleResult> {\n return this.client.request<Post | FacebookRecoveryScheduleResult>('PUT', `/posts/${id}/schedule`, { scheduledAt, ...(platform ? { platform } : {}) })\n }\n\n /** PUT /posts/:id/schedule with { cancel: true } — cancels scheduling; recovery restores the previous outcome. */\n unschedule(id: string): Promise<Post> {\n return this.client.request<Post>('PUT', `/posts/${id}/schedule`, { cancel: true })\n }\n\n retry(id: string): Promise<Post>\n retry(id: string, platform: 'facebook'): Promise<FacebookRetryResult>\n retry(id: string, platform: Platform): Promise<Post | FacebookRetryResult>\n retry(id: string, platform?: Platform): Promise<Post | FacebookRetryResult> {\n return this.client.request<Post | FacebookRetryResult>('POST', `/posts/${id}/retry`, undefined,\n platform ? { platform } : undefined)\n }\n\n rewrite(id: string): Promise<Post> {\n return this.client.request<Post>('POST', `/posts/${id}/rewrite`)\n }\n\n /** POST /posts/:id/score — backend returns `{ score }` only (no feedback). */\n score(id: string): Promise<{ score: number }> {\n return this.client.request<{ score: number }>('POST', `/posts/${id}/score`)\n }\n}\n","import { Resource } from '../resource'\nimport type { KnowledgeBase, KbDocument, CreateKbParams, SearchResult } from '../types/kb'\n\nexport class KbResource extends Resource {\n list(): Promise<KnowledgeBase[]> {\n return this.get<KnowledgeBase[]>('/kbs')\n }\n\n retrieve(id: string): Promise<KnowledgeBase> {\n return this.get<KnowledgeBase>(`/kbs/${id}`)\n }\n\n create(params: CreateKbParams): Promise<KnowledgeBase> {\n return this.post<KnowledgeBase>('/kbs', params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/kbs/${id}`)\n }\n\n search(\n id: string,\n query: string,\n ): Promise<{ query: string; limit: number; total: number; results: SearchResult[] }> {\n return this.post<{ query: string; limit: number; total: number; results: SearchResult[] }>(\n `/kbs/${id}/search`,\n { query },\n )\n }\n\n ingestUrl(id: string, url: string): Promise<KbDocument> {\n return this.post<KbDocument>(`/kbs/${id}/docs/ingest-url`, { url })\n }\n\n docs(id: string): Promise<KbDocument[]> {\n return this.get<KbDocument[]>(`/kbs/${id}/docs`)\n }\n}\n","import { Resource } from '../resource'\nimport type { Paginated } from '../types'\nimport type { Idea, GenerateIdeasParams, GenerateIdeasResult, EnrichIdeaParams } from '../types/kb'\n\nexport class IdeasResource extends Resource {\n /** POST /ideas/generate-topic — returns an object whose `ideas` holds the generated ideas. */\n generate(params: GenerateIdeasParams = {}): Promise<GenerateIdeasResult> {\n return this.post<GenerateIdeasResult>('/ideas/generate-topic', params)\n }\n\n /** GET /ideas — backend paginates: `{ items, total, limit, offset }`. */\n list(): Promise<Paginated<Idea>> {\n return this.get<Paginated<Idea>>('/ideas')\n }\n\n /**\n * POST /ideas/enrich — enrich an idea (title/hook/angle) across 1..5 platforms.\n * Async: returns a job id (202). NOTE: the backend enriches the idea *object*, not an\n * id — there is no enrich-by-id route. Poll the result separately (not yet wrapped).\n */\n enrich(params: EnrichIdeaParams): Promise<{ jobId: string }> {\n return this.post<{ jobId: string }>('/ideas/enrich', params)\n }\n\n remove(id: string): Promise<void> {\n return this.delete<void>(`/ideas/${id}`)\n }\n}\n","import { Resource } from '../resource'\nimport type { UsageSummary } from '../types/usage'\n\nexport class UsageResource extends Resource {\n summary(): Promise<UsageSummary> {\n return this.get<UsageSummary>('/usage/summary')\n }\n}\n","import { Resource } from '../resource'\nimport type { Webhook, CreateWebhookParams, UpdateWebhookParams } from '../types/webhooks'\n\nexport class WebhooksResource extends Resource {\n list(): Promise<Webhook[]> {\n return this.get<Webhook[]>('/webhooks')\n }\n\n // NOTE: the backend has no GET /webhooks/:id route — this 404s until front-back adds it.\n retrieve(id: string): Promise<Webhook> {\n return this.get<Webhook>(`/webhooks/${id}`)\n }\n\n create(params: CreateWebhookParams): Promise<Webhook> {\n return this.post<Webhook>('/webhooks', params)\n }\n\n update(id: string, params: UpdateWebhookParams): Promise<Webhook> {\n return this.patch<Webhook>(`/webhooks/${id}`, params)\n }\n\n remove(id: string): Promise<void> {\n return this.client.request<void>('DELETE', `/webhooks/${id}`)\n }\n\n // POST /webhooks/:id/test — backend returns `{ delivered, httpStatus }`.\n test(id: string): Promise<{ delivered: boolean; httpStatus: number }> {\n return this.post<{ delivered: boolean; httpStatus: number }>(`/webhooks/${id}/test`)\n }\n}\n","import { Resource } from '../resource'\nimport type { Workspace } from '../types/workspaces'\nimport type { Autoposting } from '../client'\n\nexport class WorkspacesResource extends Resource {\n constructor(client: Autoposting) {\n super(client)\n }\n\n /**\n * GET /orgs — backend returns `{ organizations, activeOrgId }`, not a bare array.\n * This route is session-only (better-auth session); an API key receives a bare 401,\n * so guard up front with accurate guidance instead of an opaque \"Unauthorized\".\n */\n list(): Promise<{ organizations: Workspace[]; activeOrgId: string }> {\n if (this.client.authSource === 'api-key') {\n return Promise.reject(\n new Error(\n 'Listing workspaces requires session auth. An API key is scoped to a single workspace ' +\n 'and cannot list organizations — manage workspaces from the web dashboard.',\n ),\n )\n }\n return this.get<{ organizations: Workspace[]; activeOrgId: string }>('/orgs')\n }\n\n switchWorkspace(id: string): Promise<void> {\n // API keys are scoped to a single workspace at creation time.\n // Switching requires a session token that can act across orgs.\n if (this.client.authSource === 'api-key') {\n return Promise.reject(\n new Error(\n 'API keys are bound to a single workspace. Use session auth to switch.',\n ),\n )\n }\n return this.client.request<void>('PUT', '/orgs/active', { organizationId: id })\n }\n}\n","import { AccountOnboardingResource } from './resources/account-onboarding'\nimport { VERSION } from './version'\nimport type { ApiResponse } from './types'\nimport { createError, RateLimitError, AutopostingError } from './errors'\nimport { MediaResource } from './resources/media'\nimport { AgentsResource } from './resources/agents'\nimport { BillingResource } from './resources/billing'\nimport { BrandsResource } from './resources/brands'\nimport { CarouselsResource } from './resources/carousels'\nimport { ClipsResource } from './resources/clips'\nimport { PostsResource } from './resources/posts'\nimport { KbResource } from './resources/kb'\nimport { IdeasResource } from './resources/ideas'\nimport { UsageResource } from './resources/usage'\nimport { WebhooksResource } from './resources/webhooks'\nimport { WorkspacesResource } from './resources/workspaces'\n\nexport interface AutopostingConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n headers?: Record<string, string>\n /** Mark the auth source so workspace-switching can enforce API key restrictions. */\n authSource?: 'api-key' | 'session'\n /** Max automatic retries for idempotent requests on transient failures. Default 2. */\n maxRetries?: number\n /** Base backoff in ms for retries (exponential ×2 per attempt, plus jitter). Default 300. */\n retryBaseMs?: number\n}\n\n/** Server-resolved identity behind a credential (GET /auth/profile). */\nexport interface AuthProfile {\n id: string\n orgId: string\n name: string\n email: string\n authType: 'api_key' | 'session'\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n// Only idempotent methods are safe to retry — retrying a POST/PATCH could double-create.\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>(['GET', 'PUT', 'DELETE'])\n// HTTP statuses that represent a transient server/proxy condition worth retrying.\n// 429 is intentionally excluded: it carries Retry-After and is surfaced to the caller\n// (auto-retrying it could hang for the full Retry-After window).\nconst RETRYABLE_STATUS: ReadonlySet<number> = new Set([500, 502, 503, 504])\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport class Autoposting {\n /** @internal Not part of the public API — use SDK methods to make requests. */\n private readonly _apiKey: string\n readonly baseUrl: string\n readonly timeout: number\n private readonly extraHeaders: Record<string, string>\n /** Indicates how the client was authenticated; used by WorkspacesResource. */\n readonly authSource: 'api-key' | 'session'\n readonly maxRetries: number\n private readonly retryBaseMs: number\n readonly media: MediaResource\n readonly agents: AgentsResource\n readonly billing: BillingResource\n readonly accountOnboarding: AccountOnboardingResource\n readonly brands: BrandsResource\n readonly carousels: CarouselsResource\n readonly clips: ClipsResource\n readonly posts: PostsResource\n readonly kb: KbResource\n readonly ideas: IdeasResource\n readonly usage: UsageResource\n readonly webhooks: WebhooksResource\n readonly workspaces: WorkspacesResource\n\n constructor(config: AutopostingConfig = {}) {\n const key = config.apiKey ?? process.env.AUTOPOSTING_API_KEY\n if (!key) {\n throw new Error(\n 'API key is required. Pass apiKey in config or set AUTOPOSTING_API_KEY env var.',\n )\n }\n this._apiKey = key\n // Resolution order: explicit config → AUTOPOSTING_BASE_URL env → default.\n // Production API is served by the backend behind the Next.js frontend's\n // /api-proxy rewrite (app.autoposting.ai/api-proxy/* -> backend/*). The bare\n // app.autoposting.ai host serves the dashboard SPA, not the JSON API.\n this.baseUrl = (\n config.baseUrl ||\n process.env.AUTOPOSTING_BASE_URL ||\n 'https://app.autoposting.ai/api-proxy'\n ).replace(/\\/$/, '')\n this.timeout = config.timeout ?? 30_000\n this.extraHeaders = config.headers ?? {}\n this.authSource = config.authSource ?? 'api-key'\n this.maxRetries = Math.max(0, config.maxRetries ?? 2)\n this.retryBaseMs = Math.max(0, config.retryBaseMs ?? 300)\n this.media = new MediaResource(this)\n this.agents = new AgentsResource(this)\n this.billing = new BillingResource(this)\n this.accountOnboarding = new AccountOnboardingResource(this)\n this.brands = new BrandsResource(this)\n this.carousels = new CarouselsResource(this)\n this.clips = new ClipsResource(this)\n this.posts = new PostsResource(this)\n this.kb = new KbResource(this)\n this.ideas = new IdeasResource(this)\n this.usage = new UsageResource(this)\n this.webhooks = new WebhooksResource(this)\n this.workspaces = new WorkspacesResource(this)\n }\n\n /**\n * GET /auth/profile — resolve the server-side identity behind the current credential.\n * Validates the key (401 on reject) and returns who/what it's scoped to.\n */\n getProfile(): Promise<AuthProfile> {\n return this.request<AuthProfile>('GET', '/auth/profile')\n }\n\n /**\n * Public entry point. Retries idempotent requests (GET/PUT/DELETE) on transient\n * failures — network errors, timeouts, and 5xx — with exponential backoff + jitter.\n * Non-idempotent methods (POST/PATCH) are never retried, to avoid duplicate side effects.\n */\n async request<T = unknown>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n query?: Record<string, unknown>,\n ): Promise<T> {\n let lastErr: unknown\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n // Exponential backoff (base × 2^(attempt-1)) plus jitter to avoid thundering herds.\n const backoff = this.retryBaseMs * 2 ** (attempt - 1)\n await sleep(backoff + Math.floor(Math.random() * this.retryBaseMs))\n }\n try {\n return await this._send<T>(method, path, body, query)\n } catch (err) {\n lastErr = err\n if (attempt < this.maxRetries && this.isRetryable(method, err)) continue\n throw err\n }\n }\n throw lastErr\n }\n\n private isRetryable(method: HttpMethod, err: unknown): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false\n if (!(err instanceof AutopostingError)) return false\n if (err.code === 'NETWORK_ERROR' || err.code === 'TIMEOUT') return true\n return RETRYABLE_STATUS.has(err.status)\n }\n\n private async _send<T = unknown>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n query?: Record<string, unknown>,\n ): Promise<T> {\n let url = `${this.baseUrl}${path}`\n\n if (query && Object.keys(query).length > 0) {\n const params = new URLSearchParams()\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined && v !== null) {\n params.set(k, String(v))\n }\n }\n url = `${url}?${params.toString()}`\n }\n\n // FormData must not have a content-type header — fetch sets it with the multipart boundary.\n const isFormData = body instanceof FormData\n // Spread caller headers first so the auth, source, and content-type headers below\n // always win — a stray `headers` override must never strip authentication.\n const headers: Record<string, string> = {\n ...this.extraHeaders,\n authorization: `Bearer ${this._apiKey}`,\n 'user-agent': `autoposting-sdk/${VERSION}`,\n 'x-source': 'sdk',\n }\n if (!isFormData) {\n headers['content-type'] = 'application/json'\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeout)\n\n // Keep the abort timer armed through the body read, not just the fetch — a\n // response whose body stream stalls would otherwise hang past the timeout.\n try {\n let response: Response\n try {\n response = await fetch(url, {\n method,\n headers,\n body: isFormData ? body : body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n } catch (err) {\n // fetch rejects on network failure or abort (timeout) — wrap both so callers\n // always get an AutopostingError, never a raw TypeError / DOMException.\n if (err instanceof Error && err.name === 'AbortError') {\n throw new AutopostingError(\n `Request to ${method} ${path} timed out after ${this.timeout}ms.`,\n 0,\n 'TIMEOUT',\n )\n }\n throw new AutopostingError(\n `Network request to ${method} ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n 'NETWORK_ERROR',\n )\n }\n\n if (!response.ok) {\n const raw = await response.text()\n let errorBody: { error?: string; code?: string } = {}\n if (raw) {\n try {\n errorBody = JSON.parse(raw) as { error?: string; code?: string }\n } catch {\n // non-JSON error body (e.g. an HTML page from a wrong base URL or a proxy/5xx)\n }\n }\n if (!errorBody.error) {\n const snippet = raw.replace(/\\s+/g, ' ').trim().slice(0, 120)\n errorBody.error = snippet\n ? `HTTP ${response.status} ${response.statusText}: ${snippet}`\n : `HTTP ${response.status} ${response.statusText}`\n }\n\n const err = createError(response.status, errorBody)\n\n if (err instanceof RateLimitError) {\n const retryAfter = response.headers.get('Retry-After')\n if (retryAfter) {\n // Retry-After is delta-seconds OR an HTTP-date (RFC 7231) — handle both.\n const seconds = Number(retryAfter)\n if (Number.isFinite(seconds)) {\n err.retryAfter = Math.max(0, Math.round(seconds))\n } else {\n const dateMs = Date.parse(retryAfter)\n if (!Number.isNaN(dateMs)) {\n err.retryAfter = Math.max(0, Math.round((dateMs - Date.now()) / 1000))\n }\n }\n }\n }\n\n throw err\n }\n\n // 204 No Content — return empty object\n if (response.status === 204) {\n return {} as T\n }\n\n const text = await response.text()\n if (!text) return {} as T\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n // A 2xx with a non-JSON body almost always means the base URL points at the\n // web app (HTML) instead of the JSON API — surface that, not a raw parse error.\n throw new AutopostingError(\n `Expected a JSON response from ${method} ${path} but received non-JSON (HTTP ${response.status}). ` +\n `Verify the API base URL (AUTOPOSTING_BASE_URL / --base-url) points at the API, not the web app.`,\n response.status,\n 'INVALID_RESPONSE',\n )\n }\n // The backend wraps every success response as `{ success: true, data: <payload> }`.\n // Unwrap to the payload so resource return types describe the real data, not the\n // envelope. Void endpoints (e.g. some deletes) return `{ success: true }` with no\n // `data` — yield `{}` for those. A body without `success` passes through unchanged.\n // ponytail: relies on no real payload carrying its own top-level `success` field —\n // true for this API; revisit if an endpoint returns raw `{ success, ... }` data.\n if (typeof parsed === 'object' && parsed !== null && (parsed as ApiResponse).success === true) {\n const env = parsed as ApiResponse<T>\n return env.data !== undefined ? env.data : ({} as T)\n }\n return parsed as T\n } catch (err) {\n // A timer abort during the body read surfaces here as a raw AbortError (the\n // fetch-phase abort is already wrapped above). Convert it to TIMEOUT so callers\n // never receive a raw DOMException; already-wrapped AutopostingErrors pass through.\n if (err instanceof Error && err.name === 'AbortError') {\n throw new AutopostingError(\n `Request to ${method} ${path} timed out after ${this.timeout}ms.`,\n 0,\n 'TIMEOUT',\n )\n }\n throw err\n } finally {\n clearTimeout(timer)\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport type { Platform, MediaInput, InstagramOptions, ThreadsOptions, YoutubeOptions } from '@autoposting.ai/sdk'\n\nexport type { MediaInput, InstagramOptions, ThreadsOptions, YoutubeOptions }\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube', 'facebook']\n\nconst EXT_TO_MIME: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n}\n\n/** Maps a filename's extension to a MIME type. Throws on unknown extensions. */\nexport function extToMime(filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase() ?? ''\n const mime = EXT_TO_MIME[ext]\n if (!mime) {\n throw new Error(\n `Unsupported file extension \".${ext || '(none)'}\" in \"${filename}\". ` +\n `Supported: ${Object.keys(EXT_TO_MIME).join(', ')}`,\n )\n }\n return mime\n}\n\n/** Parses \"platform=value\" strings into a platform-keyed record. */\nexport function parsePairs(flag: string, vals: string[]): Partial<Record<Platform, string>> {\n const result: Partial<Record<Platform, string>> = {}\n for (const val of vals) {\n const eqIdx = val.indexOf('=')\n if (eqIdx < 1) {\n throw new Error(`${flag}: expected \"platform=value\" format, got \"${val}\"`)\n }\n const p = val.slice(0, eqIdx).trim()\n const v = val.slice(eqIdx + 1)\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw new Error(`${flag}: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`)\n }\n result[p as Platform] = v\n }\n return result\n}\n\n/** Parses \"platform=path1[,path2,...]\" strings into a platform-keyed path-array record. */\nexport function parsePlatformMediaPairs(\n flag: string,\n vals: string[],\n): Partial<Record<Platform, string[]>> {\n const result: Partial<Record<Platform, string[]>> = {}\n for (const val of vals) {\n const eqIdx = val.indexOf('=')\n if (eqIdx < 1) {\n throw new Error(`${flag}: expected \"platform=path[,path...]\" format, got \"${val}\"`)\n }\n const p = val.slice(0, eqIdx).trim()\n const paths = val\n .slice(eqIdx + 1)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw new Error(`${flag}: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`)\n }\n result[p as Platform] = paths\n }\n return result\n}\n\n/** Validates that every path has a supported extension. Throws on the first bad one.\n * Lets `posts create` reject unsupported media before any network call/upload. */\nexport function validateMediaExtensions(paths: string[]): void {\n for (const p of paths) extToMime(p)\n}\n\n/** Throws if more than 10 media paths are provided (backend limit). */\nexport function validateMediaCount(paths: string[]): void {\n if (paths.length > 10) {\n throw new Error(`--media accepts at most 10 files (received ${paths.length}).`)\n }\n}\n\n/** Validates that all media file paths exist on disk. */\nexport function validateMediaPaths(paths: string[]): void {\n for (const p of paths) {\n if (!existsSync(p)) {\n throw new Error(`Media file not found: \"${p}\"`)\n }\n }\n}\n\n/**\n * Aligns alt-text strings to media paths by index.\n * Returns undefined for indices with no alt-text.\n * Throws if altTexts.length > mediaPaths.length.\n */\nexport function alignAltText(\n mediaPaths: string[],\n altTexts: string[],\n): Array<string | undefined> {\n if (altTexts.length > mediaPaths.length) {\n throw new Error(\n `--alt-text has more values (${altTexts.length}) than --media (${mediaPaths.length}). ` +\n `Alt text aligns to media by index.`,\n )\n }\n return mediaPaths.map((_, i) => altTexts[i])\n}\n\n/** Builds YoutubeOptions from CLI flag values; returns undefined if all fields are empty. */\nexport function buildYoutubeOptions(opts: {\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n}): YoutubeOptions | undefined {\n const { ytTitle, ytDescription, ytTags, ytPrivacy, ytCategory, ytMadeForKids } = opts\n const o: YoutubeOptions = {}\n if (ytTitle) o.title = ytTitle\n if (ytDescription) o.description = ytDescription\n if (ytTags) o.tags = ytTags.split(',').map((t) => t.trim()).filter(Boolean)\n if (ytPrivacy) o.privacyStatus = ytPrivacy\n if (ytCategory) o.categoryId = ytCategory\n if (ytMadeForKids !== undefined) o.madeForKids = ytMadeForKids\n return Object.keys(o).length > 0 ? o : undefined\n}\n\n/** Builds InstagramOptions from CLI flag values; returns undefined if no IG flags are set. */\nexport function buildInstagramOptions(opts: {\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n}): InstagramOptions | undefined {\n const { igReel, igShareToFeed, igCoverUrl, igThumbOffsetMs, igCollaborators } = opts\n const hasAnyReelFlag = igReel !== undefined || igShareToFeed !== undefined ||\n igCoverUrl !== undefined || igThumbOffsetMs !== undefined || igCollaborators !== undefined\n if (!hasAnyReelFlag) return undefined\n\n const reel: NonNullable<InstagramOptions['reel']> = {}\n // --ig-reel presence alone signals reel mode to the backend; no field to set\n if (igShareToFeed !== undefined) reel.shareToFeed = igShareToFeed\n if (igCoverUrl) reel.coverUrl = igCoverUrl\n if (igThumbOffsetMs !== undefined) {\n const n = Number(igThumbOffsetMs)\n if (!Number.isFinite(n) || n < 0) {\n throw new Error(\n `--ig-thumb-offset-ms must be a non-negative number (received \"${igThumbOffsetMs}\")`,\n )\n }\n reel.thumbOffsetMs = n\n }\n if (igCollaborators) {\n reel.collaborators = igCollaborators.split(',').map((s) => s.trim()).filter(Boolean)\n }\n return { reel }\n}\n\n/** Builds ThreadsOptions from CLI flag values; returns undefined if no flags are set. */\nexport function buildThreadsOptions(opts: {\n threadsReplyTo?: string\n threadsReplyControl?: string\n}): ThreadsOptions | undefined {\n const { threadsReplyTo, threadsReplyControl } = opts\n if (!threadsReplyTo && !threadsReplyControl) return undefined\n const o: ThreadsOptions = {}\n if (threadsReplyTo) o.replyToId = threadsReplyTo\n if (threadsReplyControl) o.replyControl = threadsReplyControl\n return o\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js'\n\n// MCP carries JSON, not file bytes: media must already be at a public https URL.\nconst MEDIA_ITEMS = {\n type: 'array',\n maxItems: 10,\n description:\n 'Images or videos to attach, as https URLs. For a local file, call upload-media first and pass its result here.',\n items: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'Public https URL of the image or video' },\n type: { type: 'string', enum: ['image', 'video', 'gif'] },\n altText: { type: 'string', description: 'Optional alt text' },\n },\n required: ['url', 'type'],\n additionalProperties: false,\n },\n}\n\nconst FACEBOOK_AUTHORING = {\n facebookOptions: { type: 'object', properties: {\n format: { type: 'string', enum: ['text', 'link', 'photo', 'multi-photo', 'video', 'reel'] },\n link: { type: 'string', description: 'Public HTTPS article URL for link format' },\n }, required: ['format'], additionalProperties: false },\n targetAccountIds: { type: 'object', description: 'Explicit selected connected Page IDs, including a sole Page',\n properties: { facebook: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true } },\n additionalProperties: { type: 'array', items: { type: 'string' } } },\n platformTexts: { type: 'object', additionalProperties: { type: 'string' }, description: 'Platform captions; empty Facebook caption is intentional' },\n platformMedia: { type: 'object', additionalProperties: MEDIA_ITEMS, description: 'Platform media; empty Facebook array excludes shared attachments' },\n}\n\nexport const ALL_TOOLS: Tool[] = [\n {name:'delete-account-import',description:'Delete import progress only. Connected accounts and brands remain. Ask the user before discarding their progress.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'}},required:['id']}},\n { name: 'import-accounts', description: 'Import 1–1000 social account rows from CSV. Headers: brand_name, platform, account_url; optional brand_slug, timezone, account_type. Returns a durable import id. Repeating the same import reuses progress. No passwords or provider tokens.', inputSchema: {type:'object',properties:{csv:{type:'string',maxLength:90000,description:'CSV contents, including header row'}},required:['csv']} },\n {name:'prepare-account-import',description:'Create or reuse up to 25 brands. Repeat with nextOffset until null; safe to resume.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},offset:{type:'integer',minimum:0,description:'Next row offset; default 0'}},required:['id']}},\n {name:'account-import-status',description:'Check actual imported account connections and plan capacity. A link alone is not a connection. Vanity URLs may need explicit account confirmation.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},offset:{type:'integer',minimum:0,description:'Row offset; default 0'},limit:{type:'integer',minimum:1,maximum:100,description:'Rows per page; default 50'}},required:['id']}},\n {name:'authorize-import-account',description:'Generate a fresh provider approval link for one row. Present it to the user, who opens it in their browser and approves the intended account. Then check status. Links expire after 10 minutes.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},rowId:{type:'string',description:'Row id from status'}},required:['id','rowId']}},\n {name:'confirm-import-account',description:'For needs_confirmation rows ONLY: show the actual account id/name and CSV URL to the user. Call only after the user explicitly confirms they match. tokenId must come from status; this never creates a connection.',inputSchema:{type:'object',properties:{id:{type:'string',description:'Import id'},rowId:{type:'string',description:'Row id'},tokenId:{type:'string',description:'User-confirmed tokenId from status'}},required:['id','rowId','tokenId']}},\n\n // Posts\n {\n name: 'list-posts',\n description: 'List posts with optional filters by brand, status, limit, and page.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Filter by brand slug' },\n status: {\n type: 'string',\n enum: ['draft', 'scheduled', 'published', 'failed'],\n description: 'Filter by post status',\n },\n limit: { type: 'number', description: 'Max results per page (default 20)' },\n page: { type: 'number', description: 'Page number (default 1)' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'get-post',\n description: 'Get a post by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-post',\n description: 'Create a new post draft for a brand on one or more platforms.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to post under' },\n text: { type: 'string', description: 'Post text content' },\n platforms: {\n type: ['string', 'array'], items: { type: 'string' },\n description: 'Platform array or comma-separated platform list (e.g. x,linkedin)',\n },\n scheduledAt: {\n type: 'string',\n description: 'ISO 8601 datetime to schedule the post',\n },\n media: MEDIA_ITEMS,\n ...FACEBOOK_AUTHORING,\n },\n required: ['brandSlug', 'text', 'platforms'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-post',\n description: 'Update the text, platforms, scheduled time, or media of an existing post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID' },\n text: { type: 'string', description: 'New post text' },\n platforms: { type: ['string', 'array'], items: { type: 'string' }, description: 'Platform array or comma-separated new platform list' },\n scheduledAt: { type: 'string', description: 'New ISO 8601 scheduled datetime' },\n media: MEDIA_ITEMS,\n ...FACEBOOK_AUTHORING,\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-post',\n description: 'Permanently delete a post by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'publish-post',\n description: 'Immediately publish a post to all its platforms.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to publish' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'schedule-post',\n description: 'Schedule a post to be published at a specific date and time.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to schedule' },\n scheduledAt: { type: 'string', description: 'ISO 8601 datetime for publishing' },\n platform: { type: 'string', enum: ['facebook'], description: 'Explicit failed-Page recovery; preserves Published and Unknown outcomes' },\n },\n required: ['id', 'scheduledAt'],\n additionalProperties: false,\n },\n },\n {\n name: 'retry-post',\n description: 'Retry publishing a failed post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to retry' },\n platform: { type: 'string', enum: ['x', 'linkedin', 'instagram', 'threads', 'youtube', 'facebook'], description: 'Optional explicit platform; facebook retries only failed Pages without remote evidence, preserving Published and Unknown outcomes.' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'rewrite-post',\n description: 'AI-rewrite the text of a post.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to rewrite' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'score-post',\n description: 'Score a post with AI feedback and return a numeric score with explanation.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Post ID to score' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Brands\n {\n name: 'list-brands',\n description: 'List all brands in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-brand',\n description: 'Get a brand by its slug.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-brand',\n description: 'Create a new brand in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Brand display name' },\n timezone: { type: 'string', description: 'IANA timezone (e.g. America/New_York)' },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-brand',\n description: 'Update a brand name or timezone.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to update' },\n name: { type: 'string', description: 'New display name' },\n timezone: { type: 'string', description: 'New IANA timezone' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-brand',\n description: 'Permanently delete a brand by slug.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug to delete' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n {\n name: 'brand-auth-status',\n description: 'Show the platform connection status for a brand.',\n inputSchema: {\n type: 'object',\n properties: {\n brandSlug: { type: 'string', description: 'Brand slug' },\n },\n required: ['brandSlug'],\n additionalProperties: false,\n },\n },\n\n // Agents\n {\n name: 'list-agents',\n description: 'List all agents in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-agent',\n description: 'Get an agent by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-agent',\n description: 'Create a new publish or research agent.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Agent name' },\n type: {\n type: 'string',\n enum: ['publish', 'research'],\n description: 'Agent type',\n },\n brandSlug: { type: 'string', description: 'Brand slug to associate with' },\n prompt: { type: 'string', description: 'Agent instructions or prompt' },\n frequency: {\n type: 'string',\n enum: ['manual', 'daily', 'weekly'],\n description: 'Run frequency',\n },\n time: { type: 'string', description: 'Time of day to run (HH:MM)' },\n weekday: { type: 'string', description: 'Day of week (required for weekly frequency)' },\n kbId: { type: 'string', description: 'Knowledge base ID to attach' },\n },\n required: ['name', 'type', 'prompt', 'frequency'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-agent',\n description: 'Update an agent name, prompt, frequency, or schedule.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n name: { type: 'string', description: 'New agent name' },\n prompt: { type: 'string', description: 'New prompt' },\n frequency: { type: 'string', description: 'New frequency: manual, daily, or weekly' },\n time: { type: 'string', description: 'New time of day (HH:MM)' },\n weekday: { type: 'string', description: 'New day of week' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-agent',\n description: 'Permanently delete an agent by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'run-agent',\n description: 'Trigger an immediate run of an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to run' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'toggle-agent',\n description: 'Enable or disable an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID to toggle' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'agent-runs',\n description: 'List the run history for an agent.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Agent ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Knowledge Bases\n {\n name: 'list-kbs',\n description: 'List all knowledge bases in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-kb',\n description: 'Get a knowledge base by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-kb',\n description: 'Create a new knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', minLength: 4, maxLength: 20, description: 'Knowledge base name' },\n description: { type: 'string', minLength: 20, maxLength: 500, description: 'Knowledge base description' },\n },\n required: ['name', 'description'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-kb',\n description: 'Permanently delete a knowledge base by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'search-kb',\n description: 'Search a knowledge base with a text query.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to search' },\n query: { type: 'string', description: 'Search query text' },\n },\n required: ['id', 'query'],\n additionalProperties: false,\n },\n },\n {\n name: 'ingest-kb',\n description: 'Ingest a URL into a knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID to ingest into' },\n url: { type: 'string', description: 'URL to ingest' },\n },\n required: ['id', 'url'],\n additionalProperties: false,\n },\n },\n {\n name: 'kb-docs',\n description: 'List documents stored in a knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Knowledge base ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Ideas\n {\n name: 'generate-ideas',\n description: 'AI-generate content ideas, optionally seeded from a knowledge base or topic.',\n inputSchema: {\n type: 'object',\n properties: {\n kbId: { type: 'string', description: 'Knowledge base ID to draw context from' },\n topic: { type: 'string', description: 'Topic or theme for idea generation' },\n count: { type: 'number', description: 'Number of ideas to generate (default 5)' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'list-ideas',\n description: 'List all saved content ideas.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'enrich-idea',\n description:\n 'Enrich an idea (title/hook/angle) into platform-ready drafts across 1..5 platforms. Async — returns a job ID.',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Idea title' },\n hook: { type: 'string', description: 'Idea hook' },\n angle: { type: 'string', description: 'Idea angle' },\n platforms: {\n type: 'array',\n description: 'Target platforms (1..5)',\n items: {\n type: 'string',\n enum: ['twitter', 'linkedin', 'instagram', 'youtube', 'threads'],\n },\n minItems: 1,\n maxItems: 5,\n },\n kbId: { type: 'string', description: 'Optional knowledge base ID for context' },\n },\n required: ['title', 'hook', 'angle', 'platforms'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-idea',\n description: 'Permanently delete an idea by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Idea ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Clips\n {\n name: 'list-clips',\n description: 'List all video clips in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-clip',\n description: 'Get a video clip by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'import-clip',\n description:\n 'Start AI clipping: import a long video from a public URL (e.g. a YouTube video). Poll get-clip until status is ready.',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL of the video to import' },\n brandId: { type: 'string', description: 'Brand ID (the `id` from list-brands)' },\n name: { type: 'string', description: 'Optional name for the imported clip' },\n },\n required: ['url', 'brandId'],\n additionalProperties: false,\n },\n },\n {\n name: 'render-clip',\n description: 'Render a clip (uses credits). Call get-clip first for its editRevision and candidates.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID to render' },\n editRevision: { type: 'number', description: 'Current editRevision from get-clip' },\n candidateId: { type: 'string', description: 'Optional: render only this candidate' },\n },\n required: ['id', 'editRevision'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-clip-draft',\n description: 'Create a draft post from a rendered clip. Publish it with publish-post or schedule it.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n candidateId: { type: 'string', description: 'Optional candidate ID (defaults to the first rendered one)' },\n aspectRatio: { type: 'string', enum: ['9:16', '16:9', '1:1', '4:5'], description: 'Optional render format' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'upload-clip',\n description:\n 'Upload a local video file for AI clipping (multipart, any size). Poll get-clip until status is ready, then render-clip.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: { type: 'string', description: 'Absolute path to the video file on this machine' },\n brandId: { type: 'string', description: 'Brand ID (the `id` from list-brands)' },\n title: { type: 'string', description: 'Optional clip title' },\n },\n required: ['filePath', 'brandId'],\n additionalProperties: false,\n },\n },\n {\n name: 'publish-clip',\n description: 'Publish, schedule, or save as a draft a rendered clip candidate.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID' },\n mode: { type: 'string', enum: ['publish', 'schedule', 'draft'] },\n candidateId: { type: 'string', description: 'Candidate to post (defaults to the best rendered one)' },\n platforms: { type: 'string', description: 'Comma-separated platforms, e.g. \"x,linkedin\"' },\n text: { type: 'string', description: 'Post caption' },\n brandSlug: { type: 'string', description: 'Brand slug' },\n scheduledAt: { type: 'string', description: 'ISO 8601 time, for mode \"schedule\"' },\n aspectRatio: { type: 'string', enum: ['9:16', '4:5', '1:1', '16:9'] },\n },\n required: ['id', 'mode'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-clip',\n description: 'Permanently delete a video clip by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Clip ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Media\n {\n name: 'upload-media',\n description:\n 'Upload a local image or video and get back a media item ({url, type, altText}) to pass in create-post or update-post `media`.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: { type: 'string', description: 'Absolute path to the file on this machine' },\n altText: { type: 'string', description: 'Optional alt text' },\n },\n required: ['filePath'],\n additionalProperties: false,\n },\n },\n\n // Any other REST route\n {\n name: 'list-api-routes',\n description: 'List the REST routes api-request may call, as \"METHOD /path/:param\". Optional prefix filter, e.g. \"/clips\".',\n inputSchema: {\n type: 'object',\n properties: { prefix: { type: 'string', description: 'Only routes whose path starts with this' } },\n additionalProperties: false,\n },\n },\n {\n name: 'api-request',\n description:\n 'Call any Autoposting REST route on the allow-list (see list-api-routes) with your API key. Replace :params with real IDs.',\n inputSchema: {\n type: 'object',\n properties: {\n method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },\n path: { type: 'string', description: 'Path such as /clips/abc123/jobs, no query string' },\n query: { type: 'object', description: 'Query string parameters' },\n body: { type: 'object', description: 'JSON body for POST, PUT and PATCH' },\n },\n required: ['method', 'path'],\n additionalProperties: false,\n },\n },\n\n // Carousels\n {\n name: 'list-carousels',\n description: 'List all carousels in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-carousel',\n description: 'Get a carousel by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-carousel',\n description: 'Create a new empty carousel.',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Optional carousel title' },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'generate-carousel',\n description: 'AI-generate a carousel from a topic.',\n inputSchema: {\n type: 'object',\n properties: {\n topic: { type: 'string', description: 'Topic to generate slides for' },\n brandSlug: { type: 'string', description: 'Brand slug for brand voice' },\n slideCount: { type: 'number', description: 'Number of slides to generate' },\n },\n required: ['topic'],\n additionalProperties: false,\n },\n },\n {\n name: 'draft-carousel',\n description: 'Convert a carousel into a post draft.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID to convert' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-carousel',\n description: 'Permanently delete a carousel by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Carousel ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Webhooks\n {\n name: 'list-webhooks',\n description: 'List all webhooks in the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get-webhook',\n description: 'Get a webhook by its ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'create-webhook',\n description: 'Create a new webhook endpoint for receiving events.',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'HTTPS endpoint URL to receive events' },\n events: {\n type: 'string',\n description: 'Comma-separated event types (e.g. post.published,post.failed)',\n },\n secret: { type: 'string', description: 'Optional HMAC signing secret' },\n },\n required: ['url', 'events'],\n additionalProperties: false,\n },\n },\n {\n name: 'update-webhook',\n description: 'Update the URL, events, or active state of a webhook.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID' },\n url: { type: 'string', description: 'New endpoint URL' },\n events: { type: 'string', description: 'New comma-separated event types' },\n active: { type: 'boolean', description: 'Whether the webhook is active' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'delete-webhook',\n description: 'Permanently delete a webhook by ID.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID to delete' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n {\n name: 'test-webhook',\n description: 'Send a test event to a webhook endpoint.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Webhook ID to send the test event to' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n\n // Billing\n {\n name: 'billing-status',\n description: 'Get the current billing plan and subscription status.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'billing-credits',\n description: 'Get the current AI credit balance and usage breakdown.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n\n // Usage\n {\n name: 'usage-summary',\n description: 'Get a summary of post and publishing usage for the current period.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n]\n","import type { Autoposting } from '@autoposting.ai/sdk'\n\ntype Requester = Pick<Autoposting, 'request'>\n\n/**\n * The allow-list of REST routes an assistant may call is owned by the hosted /mcp server\n * (list-api-routes). `ap api` and local `ap mcp` fetch it from there so it has one owner.\n */\nexport async function fetchApiRoutes(client: Requester): Promise<string[]> {\n const res = await client.request<{\n result?: { content?: { text?: string }[] }\n error?: { message?: string }\n }>('POST', '/mcp', {\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/call',\n params: { name: 'list-api-routes', arguments: {} },\n })\n try {\n const routes = (JSON.parse(res.result?.content?.[0]?.text ?? '') as { routes?: unknown }).routes\n if (Array.isArray(routes)) return routes as string[]\n } catch {\n // fall through to the error below\n }\n throw new Error(`Could not load the API allow-list from the server${res.error?.message ? `: ${res.error.message}` : ''}.`)\n}\n\nconst SAFE_SEGMENT = /^[\\w\\-.~]+$/\n\n/** Throws unless METHOD PATH matches an allow-list entry (`:param` matches one segment). */\nexport function assertApiRoute(routes: readonly string[], method: string, path: string): void {\n const m = method.toUpperCase()\n const segs = path.startsWith('/') ? path.slice(1).split('/') : []\n const safe = segs.length > 0 && segs.every((s) => SAFE_SEGMENT.test(s) && s !== '.' && s !== '..')\n const match = safe && routes.some((r) => {\n const [rm, rp] = r.split(' ')\n const rs = rp.slice(1).split('/')\n return rm === m && rs.length === segs.length && rs.every((s, i) => s.startsWith(':') || s === segs[i])\n })\n if (!match) throw new Error(`${m} ${path} is not available. Run list-api-routes (or \\`ap api --list\\`) to see what is.`)\n}\n","import type { Autoposting } from '@autoposting.ai/sdk'\nimport type { CreateClipDraftParams, MediaInput, Platform, CreatePostParams } from '@autoposting.ai/sdk'\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport { readFile } from 'node:fs/promises'\nimport { basename } from 'node:path'\nimport { assertApiRoute, fetchApiRoutes } from '../lib/api-routes.js'\nimport { extToMime } from '../lib/media-flags.js'\n\ntype ToolArgs = Record<string, unknown>\nconst PLATFORMS: Platform[] = [\n 'x',\n 'linkedin',\n 'instagram',\n 'threads',\n 'youtube',\n 'facebook',\n]\nconst PLATFORM_SET = new Set<string>(PLATFORMS)\n\nfunction validateAuthoringIntent(args: ToolArgs): void {\n const object = (value: unknown, field: string): Record<string, unknown> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${field} must be an object.`)\n return value as Record<string, unknown>\n }\n if (args.facebookOptions !== undefined) {\n const options = object(args.facebookOptions, 'facebookOptions')\n if (!['text', 'link', 'photo', 'multi-photo', 'video', 'reel'].includes(options.format as string)) {\n throw new Error('facebookOptions.format must be a supported Facebook format.')\n }\n if (options.link !== undefined && typeof options.link !== 'string') throw new Error('facebookOptions.link must be a string.')\n if (Object.keys(options).some(key => !['format', 'link'].includes(key))) throw new Error('Unknown facebookOptions field.')\n }\n for (const field of ['targetAccountIds', 'platformTexts', 'platformMedia'] as const) {\n if (args[field] === undefined) continue\n for (const [platform, value] of Object.entries(object(args[field], field))) {\n if (!PLATFORM_SET.has(platform)) throw new Error(`Invalid platform in ${field}.`)\n if (field === 'platformTexts') {\n if (typeof value !== 'string') throw new Error('Platform captions must be strings.')\n } else if (field === 'targetAccountIds') {\n if (!Array.isArray(value) || value.length === 0 || value.some(id => typeof id !== 'string' || !id.trim()) || new Set(value).size !== value.length) {\n throw new Error('Target account IDs must be a nonempty array of unique IDs.')\n }\n } else {\n if (!Array.isArray(value)) throw new Error('Platform media must be an array.')\n for (const item of value) {\n const media = object(item, 'Media item')\n if (typeof media.url !== 'string' || !media.url.trim() || !['image', 'video', 'gif'].includes(media.type as string)) {\n throw new Error('Media items require a URL and image, video or gif type.')\n }\n if (media.altText !== undefined && typeof media.altText !== 'string') throw new Error('Media altText must be a string.')\n }\n }\n }\n }\n}\n\nfunction ok(data: unknown): CallToolResult {\n return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }\n}\n\nfunction fail(error: unknown): CallToolResult {\n const message = error instanceof Error ? error.message : String(error)\n return { content: [{ type: 'text', text: message }], isError: true }\n}\n\nfunction parsePlatforms(raw: unknown): Platform[] {\n if (raw === undefined) return []\n if (typeof raw !== 'string' && !Array.isArray(raw)) {\n throw new Error('Platforms must be a comma-separated string or an array of platform names.')\n }\n const values = typeof raw === 'string' ? raw.split(',') : raw\n if (values.some((value) => typeof value !== 'string')) {\n throw new Error('Every platform must be a platform name.')\n }\n const platforms = (values as string[])\n .map((p) => p.trim())\n .filter(Boolean)\n const invalid = platforms.filter((platform) => !PLATFORM_SET.has(platform))\n if (invalid.length > 0) {\n throw new Error(\n `Invalid platform(s): ${invalid.join(', ')}. Expected one of: ${PLATFORMS.join(', ')}.`,\n )\n }\n return platforms as Platform[]\n}\n\n// One allow-list fetch per server process; a failed fetch is not cached, so the next call retries.\nconst routeCache = new WeakMap<object, Promise<string[]>>()\nfunction apiRoutes(client: Autoposting): Promise<string[]> {\n let routes = routeCache.get(client)\n if (!routes) {\n routes = fetchApiRoutes(client)\n routeCache.set(client, routes)\n routes.catch(() => routeCache.delete(client))\n }\n return routes\n}\n\nfunction parseEvents(raw: unknown): string[] {\n if (typeof raw !== 'string') return []\n return raw.split(',').map((e) => e.trim())\n}\n\nexport async function handleToolCall(\n name: string,\n args: ToolArgs,\n client: Autoposting,\n): Promise<CallToolResult> {\n try {\n return await dispatchToolCall(name, args, client)\n } catch (error) {\n return fail(error)\n }\n}\n\nasync function dispatchToolCall(\n name: string,\n args: ToolArgs,\n client: Autoposting,\n): Promise<CallToolResult> {\n if (name === 'create-post' || name === 'update-post') validateAuthoringIntent(args)\n switch (name) {\n case 'delete-account-import': return ok(await client.accountOnboarding.remove(args.id as string))\n case 'import-accounts': return ok(await client.accountOnboarding.create({ csv: args.csv as string }))\n case 'prepare-account-import': return ok(await client.accountOnboarding.prepare(args.id as string, args.offset as number | undefined))\n case 'account-import-status': return ok(await client.accountOnboarding.status(args.id as string, { ...(args.offset !== undefined ? {offset:args.offset as number}:{}), ...(args.limit !== undefined ? {limit:args.limit as number}:{}) }))\n case 'authorize-import-account': return ok(await client.accountOnboarding.authorize(args.id as string, args.rowId as string))\n case 'confirm-import-account': return ok(await client.accountOnboarding.confirm(args.id as string, args.rowId as string, args.tokenId as string))\n // Posts\n case 'list-posts': {\n const result = await client.posts.list({\n brandSlug: args.brandSlug as string | undefined,\n status: args.status as\n | 'draft'\n | 'scheduled'\n | 'published'\n | 'failed'\n | undefined,\n limit: args.limit as number | undefined,\n page: args.page as number | undefined,\n })\n return ok(result)\n }\n case 'get-post': {\n const result = await client.posts.getById(args.id as string)\n return ok(result)\n }\n case 'create-post': {\n const result = await client.posts.create({\n brandSlug: args.brandSlug as string,\n text: args.text as string,\n platforms: parsePlatforms(args.platforms),\n ...(args.scheduledAt\n ? { scheduledAt: args.scheduledAt as string }\n : {}),\n ...(args.media ? { media: args.media as MediaInput[] } : {}),\n ...(args.facebookOptions !== undefined ? { facebookOptions: args.facebookOptions as CreatePostParams['facebookOptions'] } : {}),\n ...(args.targetAccountIds !== undefined ? { targetAccountIds: args.targetAccountIds as CreatePostParams['targetAccountIds'] } : {}),\n ...(args.platformTexts !== undefined ? { platformTexts: args.platformTexts as CreatePostParams['platformTexts'] } : {}),\n ...(args.platformMedia !== undefined ? { platformMedia: args.platformMedia as CreatePostParams['platformMedia'] } : {}),\n })\n return ok(result)\n }\n case 'update-post': {\n const result = await client.posts.update(args.id as string, {\n ...(args.text !== undefined ? { text: args.text as string } : {}),\n ...(args.platforms\n ? {\n platforms: parsePlatforms(args.platforms),\n }\n : {}),\n ...(args.scheduledAt\n ? { scheduledAt: args.scheduledAt as string }\n : {}),\n ...(args.media ? { media: args.media as MediaInput[] } : {}),\n ...(args.facebookOptions !== undefined ? { facebookOptions: args.facebookOptions as CreatePostParams['facebookOptions'] } : {}),\n ...(args.targetAccountIds !== undefined ? { targetAccountIds: args.targetAccountIds as CreatePostParams['targetAccountIds'] } : {}),\n ...(args.platformTexts !== undefined ? { platformTexts: args.platformTexts as CreatePostParams['platformTexts'] } : {}),\n ...(args.platformMedia !== undefined ? { platformMedia: args.platformMedia as CreatePostParams['platformMedia'] } : {}),\n })\n return ok(result)\n }\n case 'delete-post': {\n await client.posts.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'publish-post': {\n const result = await client.posts.publish(args.id as string)\n return ok(result)\n }\n case 'schedule-post': {\n if (args.platform !== undefined && args.platform !== 'facebook') throw new Error('Scheduled recovery requires platform facebook')\n const result = args.platform === 'facebook'\n ? await client.posts.schedule(args.id as string, args.scheduledAt as string, 'facebook')\n : await client.posts.schedule(args.id as string, args.scheduledAt as string)\n return ok(result)\n }\n case 'retry-post': {\n const platforms = args.platform === undefined ? undefined : parsePlatforms(args.platform)\n if (platforms && platforms.length !== 1) throw new Error('Retry requires exactly one platform')\n const result = platforms ? await client.posts.retry(args.id as string, platforms[0]!) : await client.posts.retry(args.id as string)\n return ok(result)\n }\n case 'rewrite-post': {\n const result = await client.posts.rewrite(args.id as string)\n return ok(result)\n }\n case 'score-post': {\n const result = await client.posts.score(args.id as string)\n return ok(result)\n }\n\n // Brands\n case 'list-brands': {\n const result = await client.brands.list()\n return ok(result)\n }\n case 'get-brand': {\n const result = await client.brands.retrieve(args.brandSlug as string)\n return ok(result)\n }\n case 'create-brand': {\n const result = await client.brands.create({\n name: args.name as string,\n ...(args.timezone ? { timezone: args.timezone as string } : {}),\n })\n return ok(result)\n }\n case 'update-brand': {\n const result = await client.brands.update(args.brandSlug as string, {\n ...(args.name ? { name: args.name as string } : {}),\n ...(args.timezone ? { timezone: args.timezone as string } : {}),\n })\n return ok(result)\n }\n case 'delete-brand': {\n await client.brands.remove(args.brandSlug as string)\n return ok({ deleted: true, brandSlug: args.brandSlug })\n }\n case 'brand-auth-status': {\n const result = await client.brands.authStatus(args.brandSlug as string)\n return ok(result)\n }\n\n // Agents\n case 'list-agents': {\n const result = await client.agents.list()\n return ok(result)\n }\n case 'get-agent': {\n const result = await client.agents.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-agent': {\n const result = await client.agents.create({\n name: args.name as string,\n type: args.type as 'publish' | 'research',\n prompt: args.prompt as string,\n frequency: args.frequency as 'manual' | 'daily' | 'weekly',\n ...(args.brandSlug ? { brandSlug: args.brandSlug as string } : {}),\n ...(args.time ? { time: args.time as string } : {}),\n ...(args.weekday ? { weekday: args.weekday as string } : {}),\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n })\n return ok(result)\n }\n case 'update-agent': {\n const result = await client.agents.update(args.id as string, {\n ...(args.name ? { name: args.name as string } : {}),\n ...(args.prompt ? { prompt: args.prompt as string } : {}),\n ...(args.frequency ? { frequency: args.frequency as string } : {}),\n ...(args.time ? { time: args.time as string } : {}),\n ...(args.weekday ? { weekday: args.weekday as string } : {}),\n })\n return ok(result)\n }\n case 'delete-agent': {\n await client.agents.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'run-agent': {\n const result = await client.agents.run(args.id as string)\n return ok(result)\n }\n case 'toggle-agent': {\n const result = await client.agents.toggle(args.id as string)\n return ok(result)\n }\n case 'agent-runs': {\n const result = await client.agents.runs(args.id as string)\n return ok(result)\n }\n\n // Knowledge Bases\n case 'list-kbs': {\n const result = await client.kb.list()\n return ok(result)\n }\n case 'get-kb': {\n const result = await client.kb.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-kb': {\n const result = await client.kb.create({ name: args.name as string, description: args.description as string })\n return ok(result)\n }\n case 'delete-kb': {\n await client.kb.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'search-kb': {\n const result = await client.kb.search(\n args.id as string,\n args.query as string,\n )\n return ok(result)\n }\n case 'ingest-kb': {\n const result = await client.kb.ingestUrl(\n args.id as string,\n args.url as string,\n )\n return ok(result)\n }\n case 'kb-docs': {\n const result = await client.kb.docs(args.id as string)\n return ok(result)\n }\n\n // Ideas\n case 'generate-ideas': {\n const result = await client.ideas.generate({\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n ...(args.topic ? { topic: args.topic as string } : {}),\n ...(args.count ? { count: args.count as number } : {}),\n })\n return ok(result)\n }\n case 'list-ideas': {\n const result = await client.ideas.list()\n return ok(result)\n }\n case 'enrich-idea': {\n const result = await client.ideas.enrich({\n idea: {\n title: args.title as string,\n hook: args.hook as string,\n angle: args.angle as string,\n },\n platforms: (args.platforms as string[]).map((platform) => ({\n platform: platform as 'twitter' | 'linkedin' | 'instagram' | 'youtube' | 'threads',\n })),\n ...(args.kbId ? { kbId: args.kbId as string } : {}),\n })\n return ok(result)\n }\n case 'delete-idea': {\n await client.ideas.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Clips\n case 'list-clips': {\n const result = await client.clips.list()\n return ok(result)\n }\n case 'get-clip': {\n const result = await client.clips.retrieve(args.id as string)\n return ok(result)\n }\n case 'import-clip': {\n const result = await client.clips.importUrl({\n url: args.url as string,\n brandId: args.brandId as string,\n ...(args.name ? { title: args.name as string } : {}),\n })\n return ok(result)\n }\n case 'render-clip': {\n const result = await client.clips.render(args.id as string, {\n editRevision: args.editRevision as number,\n ...(args.candidateId ? { candidateId: args.candidateId as string } : {}),\n })\n return ok(result)\n }\n case 'create-clip-draft': {\n const result = await client.clips.createDraft(args.id as string, {\n ...(args.candidateId ? { candidateId: args.candidateId as string } : {}),\n ...(args.aspectRatio ? { aspectRatio: args.aspectRatio as CreateClipDraftParams['aspectRatio'] } : {}),\n })\n return ok(result)\n }\n case 'upload-clip': {\n const result = await client.clips.upload(args.filePath as string, {\n brandId: args.brandId as string,\n ...(args.title ? { title: args.title as string } : {}),\n })\n return ok(result)\n }\n case 'publish-clip': {\n const body: Record<string, unknown> = { mode: args.mode }\n for (const k of ['candidateId', 'text', 'brandSlug', 'scheduledAt', 'aspectRatio']) {\n if (args[k] !== undefined) body[k] = args[k]\n }\n if (args.platforms !== undefined) body.platforms = parsePlatforms(args.platforms)\n return ok(await client.request('POST', `/clips/${encodeURIComponent(args.id as string)}/publish`, body))\n }\n case 'delete-clip': {\n await client.clips.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Carousels\n case 'list-carousels': {\n const result = await client.carousels.list()\n return ok(result)\n }\n case 'get-carousel': {\n const result = await client.carousels.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-carousel': {\n const result = await client.carousels.create(\n args.title ? { title: args.title as string } : undefined,\n )\n return ok(result)\n }\n case 'generate-carousel': {\n const result = await client.carousels.generate({\n topic: args.topic as string,\n ...(args.brandSlug ? { brandSlug: args.brandSlug as string } : {}),\n ...(args.slideCount ? { slideCount: args.slideCount as number } : {}),\n })\n return ok(result)\n }\n case 'draft-carousel': {\n const result = await client.carousels.draft(args.id as string)\n return ok(result)\n }\n case 'delete-carousel': {\n await client.carousels.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n\n // Webhooks\n case 'list-webhooks': {\n const result = await client.webhooks.list()\n return ok(result)\n }\n case 'get-webhook': {\n const result = await client.webhooks.retrieve(args.id as string)\n return ok(result)\n }\n case 'create-webhook': {\n const result = await client.webhooks.create({\n url: args.url as string,\n events: parseEvents(args.events),\n ...(args.secret ? { secret: args.secret as string } : {}),\n })\n return ok(result)\n }\n case 'update-webhook': {\n const result = await client.webhooks.update(args.id as string, {\n ...(args.url ? { url: args.url as string } : {}),\n ...(args.events ? { events: parseEvents(args.events) } : {}),\n ...(args.active !== undefined\n ? { active: args.active as boolean }\n : {}),\n })\n return ok(result)\n }\n case 'delete-webhook': {\n await client.webhooks.remove(args.id as string)\n return ok({ deleted: true, id: args.id })\n }\n case 'test-webhook': {\n await client.webhooks.test(args.id as string)\n return ok({ sent: true, id: args.id })\n }\n\n // Media\n case 'upload-media': {\n const filePath = args.filePath as string\n const filename = basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(await readFile(filePath)),\n filename,\n contentType: extToMime(filename),\n })\n return ok({ url: uploaded.url, type: uploaded.type, ...(args.altText ? { altText: args.altText } : {}) })\n }\n\n // Any other REST route on the server's allow-list\n case 'list-api-routes': {\n const prefix = typeof args.prefix === 'string' ? args.prefix : '/'\n const routes = await apiRoutes(client)\n return ok({ routes: routes.filter((r) => r.split(' ')[1].startsWith(prefix)) })\n }\n case 'api-request': {\n const method = String(args.method ?? '').toUpperCase()\n const path = String(args.path ?? '')\n assertApiRoute(await apiRoutes(client), method, path)\n const query = typeof args.query === 'object' && args.query ? (args.query as Record<string, unknown>) : undefined\n const body = method !== 'GET' && method !== 'DELETE' && typeof args.body === 'object' && args.body ? args.body : undefined\n return ok(await client.request(method as never, path, body, query))\n }\n\n // Billing\n case 'billing-status': {\n const result = await client.billing.status()\n return ok(result)\n }\n case 'billing-credits': {\n const result = await client.billing.credits()\n return ok(result)\n }\n\n // Usage\n case 'usage-summary': {\n const result = await client.usage.summary()\n return ok(result)\n }\n\n default:\n return {\n content: [{ type: 'text', text: `Unknown tool: ${name}` }],\n isError: true,\n }\n }\n}\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { Autoposting, VERSION } from '@autoposting.ai/sdk'\nimport { ALL_TOOLS } from './tools.js'\nimport { handleToolCall } from './handler.js'\n\nexport async function startMcpServer(): Promise<void> {\n const client = new Autoposting() // reads AUTOPOSTING_API_KEY from env\n\n const server = new Server(\n { name: 'autoposting-mcp', version: VERSION },\n { capabilities: { tools: {} } },\n )\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: ALL_TOOLS,\n }))\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n return handleToolCall(name, (args ?? {}) as Record<string, unknown>, client)\n })\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","#!/usr/bin/env node\nimport { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { createAgentsCommand } from './commands/agents.js'\nimport { createAuthCommand } from './commands/auth.js'\nimport { createBillingCommand } from './commands/billing.js'\nimport { createAccountsCommand } from './commands/accounts.js'\nimport { createBrandsCommand } from './commands/brands.js'\nimport { createCarouselsCommand } from './commands/carousels.js'\nimport { createClipsCommand } from './commands/clips.js'\nimport { createPostsCommand } from './commands/posts.js'\nimport { createKbCommand } from './commands/kb.js'\nimport { createIdeasCommand } from './commands/ideas.js'\nimport { createUsageCommand } from './commands/usage.js'\nimport { createWebhooksCommand } from './commands/webhooks.js'\nimport { createWorkspacesCommand } from './commands/workspaces.js'\nimport { createDoctorCommand } from './commands/doctor.js'\nimport { createWhoamiCommand } from './commands/whoami.js'\nimport { createOpenCommand } from './commands/open.js'\nimport { createUpdateCommand } from './commands/update.js'\nimport { createCompletionCommand } from './commands/completion.js'\nimport { createMcpCommand } from './commands/mcp.js'\nimport { createConfigCommand } from './commands/config.js'\nimport { createApiCommand } from './commands/api.js'\nimport { disableColor } from './output/index.js'\n\nconst program = new Command()\n .name('autoposting')\n .description('Autoposting CLI — manage social media from the terminal')\n .version(VERSION)\n .option('--json', 'Output as JSON')\n .option('--quiet', 'Suppress spinners and non-essential output')\n .option('--format <type>', 'Output format: auto (table on a terminal, JSON when piped), table, json', 'auto')\n .option('--jq <expr>', 'Filter JSON output with a minimal jq expression (e.g. \".[].id\")')\n .option('--api-key <key>', 'API key (overrides env/stored credentials)')\n .option('--no-color', 'Disable color output')\n .hook('preAction', (thisCommand) => {\n const opts = thisCommand.opts<{ color: boolean }>()\n if (!opts.color) disableColor()\n })\n\nprogram.addCommand(createAuthCommand())\nprogram.addCommand(createBillingCommand())\nprogram.addCommand(createAccountsCommand())\nprogram.addCommand(createBrandsCommand())\nprogram.addCommand(createCarouselsCommand())\nprogram.addCommand(createClipsCommand())\nprogram.addCommand(createApiCommand())\nprogram.addCommand(createPostsCommand())\nprogram.addCommand(createAgentsCommand())\nprogram.addCommand(createKbCommand())\nprogram.addCommand(createIdeasCommand())\nprogram.addCommand(createUsageCommand())\nprogram.addCommand(createWebhooksCommand())\nprogram.addCommand(createWorkspacesCommand())\nprogram.addCommand(createDoctorCommand())\nprogram.addCommand(createWhoamiCommand())\nprogram.addCommand(createOpenCommand())\nprogram.addCommand(createUpdateCommand())\nprogram.addCommand(createCompletionCommand())\nprogram.addCommand(createMcpCommand())\nprogram.addCommand(createConfigCommand())\n\nprogram.parse()\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createAgentsCommand(): Command {\n const agents = new Command('agents').description('Manage agents')\n\n // ap agents list\n agents\n .command('list')\n .description('List all agents')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching agents…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.agents.list()\n spinner.stop()\n const rows = list.items.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n brand: a.brandSlug ?? '—',\n frequency: a.frequency,\n enabled: a.enabled ? 'yes' : 'no',\n }))\n printer.table(rows, ['id', 'name', 'type', 'brand', 'frequency', 'enabled'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents get <id>\n agents\n .command('get <id>')\n .description('Get an agent by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.retrieve(id)\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents create --name <name> --type <publish|research> [--brand <slug>] --prompt <text> --frequency <manual|daily|weekly>\n agents\n .command('create')\n .description('Create a new agent')\n .requiredOption('--name <name>', 'Agent name')\n .requiredOption('--type <type>', 'Agent type: publish or research')\n .option('--brand <slug>', 'Brand slug to associate with')\n .requiredOption('--prompt <text>', 'Agent prompt / instructions')\n .requiredOption('--frequency <freq>', 'Run frequency: manual, daily, or weekly')\n .option('--time <HH:MM>', 'Time of day to run (required for daily/weekly)')\n .option('--weekday <day>', 'Day of week to run (required for weekly)')\n .option('--kb <id>', 'Knowledge base ID to attach')\n .action(\n async (\n opts: {\n name: string\n type: string\n brand?: string\n prompt: string\n frequency: string\n time?: string\n weekday?: string\n kb?: string\n },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating agent…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.create({\n name: opts.name,\n type: opts.type as 'publish' | 'research',\n prompt: opts.prompt,\n frequency: opts.frequency as 'manual' | 'daily' | 'weekly',\n ...(opts.brand ? { brandSlug: opts.brand } : {}),\n ...(opts.time ? { time: opts.time } : {}),\n ...(opts.weekday ? { weekday: opts.weekday } : {}),\n ...(opts.kb ? { kbId: opts.kb } : {}),\n })\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap agents update <id> [--name] [--prompt] [--frequency] [--time] [--weekday]\n agents\n .command('update <id>')\n .description('Update an agent')\n .option('--name <name>', 'New agent name')\n .option('--prompt <text>', 'New prompt / instructions')\n .option('--frequency <freq>', 'New frequency: manual, daily, or weekly')\n .option('--time <HH:MM>', 'New time of day')\n .option('--weekday <day>', 'New day of week')\n .action(\n async (\n id: string,\n opts: { name?: string; prompt?: string; frequency?: string; time?: string; weekday?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.update(id, {\n ...(opts.name ? { name: opts.name } : {}),\n ...(opts.prompt ? { prompt: opts.prompt } : {}),\n ...(opts.frequency ? { frequency: opts.frequency } : {}),\n ...(opts.time ? { time: opts.time } : {}),\n ...(opts.weekday ? { weekday: opts.weekday } : {}),\n })\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap agents delete <id> --force\n agents\n .command('delete <id>')\n .description('Delete an agent (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete an agent. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.agents.remove(id)\n spinner.stop()\n printer.log(`Agent \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents run <id>\n agents\n .command('run <id>')\n .description('Trigger an agent run immediately')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Running agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const queued = await client.agents.run(id)\n spinner.stop()\n printer.log({ runId: queued.runId, status: queued.status })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents toggle <id>\n agents\n .command('toggle <id>')\n .description('Enable or disable an agent')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Toggling agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const agent = await client.agents.toggle(id)\n spinner.stop()\n printer.log(agent)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap agents runs <id>\n agents\n .command('runs <id>')\n .description('List run history for an agent')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching runs for agent \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.agents.runs(id)\n spinner.stop()\n const rows = list.items.map((r) => ({\n id: r.id,\n status: r.status,\n output: r.output ? (r.output.length > 60 ? `${r.output.slice(0, 57)}…` : r.output) : '—',\n createdAt: r.createdAt,\n }))\n printer.table(rows, ['id', 'status', 'output', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return agents\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nexport interface StoredProfile {\n apiKey: string\n workspace?: string\n email?: string\n createdAt: string\n}\n\nexport interface CredentialsFile {\n activeProfile: string\n profiles: Record<string, StoredProfile>\n}\n\nexport function getCredentialsPath(): string {\n // Per the XDG spec, XDG_CONFIG_HOME is honoured only when set to an absolute path;\n // empty or relative values must be ignored and fall back to ~/.config.\n const xdg = process.env.XDG_CONFIG_HOME\n const configBase = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config')\n return path.join(configBase, 'autoposting', 'credentials.json')\n}\n\nexport function readCredentials(): CredentialsFile | null {\n const filePath = getCredentialsPath()\n try {\n const raw = fs.readFileSync(filePath, 'utf8')\n return JSON.parse(raw) as CredentialsFile\n } catch {\n // Missing or corrupt file — return null gracefully\n return null\n }\n}\n\nexport function writeCredentials(creds: CredentialsFile): void {\n const filePath = getCredentialsPath()\n const dir = path.dirname(filePath)\n\n // Use { recursive: true } so mkdirSync is idempotent (avoids TOCTOU race between\n // existsSync + mkdirSync). Mode 0o700 ensures only the owning user can read the dir.\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n\n // Write to a temp file then rename — an atomic swap on the same filesystem, so a\n // crash or a concurrent writer can never leave a half-written credentials file.\n const tmpPath = `${filePath}.${process.pid}.tmp`\n try {\n fs.writeFileSync(tmpPath, JSON.stringify(creds, null, 2), { encoding: 'utf8', mode: 0o600 })\n fs.renameSync(tmpPath, filePath)\n } catch (err) {\n // Don't leave a half-written temp file behind on a disk-full / permission failure.\n try {\n fs.unlinkSync(tmpPath)\n } catch {\n // temp file never created or already gone — nothing to clean up\n }\n throw err\n }\n\n // Ensure 0600 even if file already existed before\n fs.chmodSync(filePath, 0o600)\n}\n\nexport function saveProfile(name: string, profile: StoredProfile): void {\n const existing = readCredentials()\n // readCredentials() returns null for BOTH missing and corrupt files. If the file is\n // present but unparseable, preserve it (rename to .corrupt) instead of silently\n // dropping every other stored profile by overwriting with a fresh file.\n if (!existing && fs.existsSync(getCredentialsPath())) {\n try {\n fs.renameSync(getCredentialsPath(), `${getCredentialsPath()}.corrupt`)\n } catch {\n // best-effort backup — proceed to write a fresh file regardless\n }\n }\n const creds: CredentialsFile = existing ?? { activeProfile: name, profiles: {} }\n creds.profiles[name] = profile\n creds.activeProfile = name\n writeCredentials(creds)\n}\n\nexport function deleteProfile(name: string): void {\n const creds = readCredentials()\n if (!creds) return\n\n delete creds.profiles[name]\n\n // If deleted profile was active, clear active or pick another\n if (creds.activeProfile === name) {\n const remaining = Object.keys(creds.profiles)\n creds.activeProfile = remaining[0] ?? ''\n }\n\n writeCredentials(creds)\n}\n\nexport function deleteAllProfiles(): void {\n writeCredentials({ activeProfile: '', profiles: {} })\n}\n\nexport function getActiveProfile(): StoredProfile | null {\n const creds = readCredentials()\n if (!creds || !creds.activeProfile) return null\n return creds.profiles[creds.activeProfile] ?? null\n}\n\nexport function setActiveProfile(name: string): void {\n const creds = readCredentials()\n if (!creds) throw new Error(`Profile \"${name}\" does not exist (no credentials file)`)\n if (!creds.profiles[name]) throw new Error(`Profile \"${name}\" does not exist`)\n creds.activeProfile = name\n writeCredentials(creds)\n}\n","import { getActiveProfile, getCredentialsPath } from './credential-store.js'\n\nexport interface AuthCredentials {\n apiKey: string\n source: 'flag' | 'env' | 'stored'\n profile?: string\n}\n\nexport { getCredentialsPath }\n\n/**\n * Resolves credentials using priority chain:\n * 1. --api-key flag (explicit)\n * 2. AUTOPOSTING_API_KEY env var\n * 3. Stored credentials from file (active profile)\n *\n * Throws with exit-code-2-compatible error when no auth is available.\n */\nexport function resolveAuth(options?: { apiKey?: string }): AuthCredentials {\n // 1. Explicit flag\n if (options?.apiKey) {\n return { apiKey: options.apiKey, source: 'flag' }\n }\n\n // 2. Env var\n const envKey = process.env.AUTOPOSTING_API_KEY\n if (envKey) {\n return { apiKey: envKey, source: 'env' }\n }\n\n // 3. Stored profile\n const profile = getActiveProfile()\n if (profile?.apiKey) {\n return { apiKey: profile.apiKey, source: 'stored' }\n }\n\n const err = new Error(\n 'No API key found. Run `ap auth login --api-key <key>` or set AUTOPOSTING_API_KEY.',\n )\n ;(err as NodeJS.ErrnoException & { exitCode?: number }).exitCode = 2\n throw err\n}\n","// ANSI color codes — no chalk dependency to keep bundle small\nconst RED = '\\x1b[31m'\nconst RESET = '\\x1b[0m'\n\nlet colorEnabled = true\n\nexport function disableColor(): void {\n colorEnabled = false\n}\n\nfunction red(text: string): string {\n if (!colorEnabled || !process.stdout.isTTY) return text\n return `${RED}${text}${RESET}`\n}\n\nexport type OutputMode = 'tty' | 'json' | 'quiet'\n\nexport interface OutputOptions {\n json?: boolean\n quiet?: boolean\n format?: 'auto' | 'table' | 'json'\n jq?: string\n color?: boolean\n}\n\nexport function detectOutputMode(options: OutputOptions): OutputMode {\n if (options.quiet) return 'quiet'\n // An explicit --format/--json wins over auto-detection; otherwise (auto/unset)\n // fall back to JSON when output is piped (non-TTY) and a human table when\n // attached to a terminal — the gh/clig.dev \"machine-readable when not a TTY\" rule.\n if (options.format === 'json' || options.json) return 'json'\n if (options.format === 'table') return 'tty'\n if (!process.stdout.isTTY) return 'json'\n return 'tty'\n}\n\nexport function formatOutput(data: unknown, mode: OutputMode): string {\n if (mode === 'quiet') return ''\n if (mode === 'json') return JSON.stringify(data, null, 2)\n // tty: pretty-print objects or stringify primitives\n if (typeof data === 'string') return data\n return JSON.stringify(data, null, 2)\n}\n\nexport function formatTable(\n rows: Record<string, unknown>[],\n columns?: string[],\n): string {\n if (rows.length === 0) return ''\n\n const cols = columns ?? Object.keys(rows[0]!)\n const widths: number[] = cols.map((col) => col.length)\n\n // Compute max widths\n for (const row of rows) {\n for (let i = 0; i < cols.length; i++) {\n const val = String(row[cols[i]!] ?? '')\n if (val.length > widths[i]!) widths[i] = val.length\n }\n }\n\n const pad = (s: string, w: number) => s.padEnd(w, ' ')\n const separator = widths.map((w) => '-'.repeat(w)).join(' ')\n\n const header = cols.map((c, i) => pad(c.toUpperCase(), widths[i]!)).join(' ')\n const dataRows = rows.map((row) =>\n cols.map((c, i) => pad(String(row[c] ?? ''), widths[i]!)).join(' '),\n )\n\n return [header, separator, ...dataRows].join('\\n')\n}\n\nexport function formatError(error: Error | string, mode: OutputMode): string {\n const message = error instanceof Error ? error.message : error\n if (mode === 'tty') return red(`Error: ${message}`)\n // json and quiet both return JSON error — errors always show\n return JSON.stringify({ error: message }, null, 2)\n}\n\ntype JqOp = { type: 'prop'; name: string } | { type: 'iter' } | { type: 'index'; n: number }\n\n// ponytail: minimal jq subset — `.`, `.a.b`, `.[]`, `.foo[]`, `.[0]`, and any\n// chain of those (covers the `.[].id` / `.field` cases the scripting ICP pipes).\n// NOT real jq: no pipes, filters, functions, or object construction. If users\n// need those, add the `jaq`/`node-jq` dependency and delegate — don't grow this.\nfunction parseJq(expr: string): JqOp[] {\n const e = expr.trim()\n if (e === '' || e === '.') return []\n if (!e.startsWith('.')) {\n throw new Error(`--jq: expression must start with \".\" (got \"${expr}\")`)\n }\n const body = e.slice(1)\n const ops: JqOp[] = []\n let i = 0\n while (i < body.length) {\n const ch = body[i]!\n if (ch === '.') {\n i++\n continue\n }\n if (ch === '[') {\n const close = body.indexOf(']', i)\n if (close === -1) throw new Error(`--jq: unclosed \"[\" in \"${expr}\"`)\n const inner = body.slice(i + 1, close).trim()\n if (inner === '') {\n ops.push({ type: 'iter' })\n } else {\n const n = Number(inner)\n if (!Number.isInteger(n)) throw new Error(`--jq: invalid index \"[${inner}]\" in \"${expr}\"`)\n ops.push({ type: 'index', n })\n }\n i = close + 1\n continue\n }\n const m = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(body.slice(i))\n if (!m) throw new Error(`--jq: unexpected character \"${ch}\" in \"${expr}\"`)\n ops.push({ type: 'prop', name: m[0] })\n i += m[0].length\n }\n return ops\n}\n\n/**\n * Applies a minimal jq-subset expression to a value, returning the output stream\n * (one entry per produced value). Throws on a malformed expression or an op that\n * doesn't fit the value (e.g. iterating a scalar) so callers exit non-zero.\n */\nexport function applyJq(data: unknown, expr: string): unknown[] {\n const ops = parseJq(expr)\n let stream: unknown[] = [data]\n for (const op of ops) {\n const next: unknown[] = []\n for (const v of stream) {\n if (op.type === 'prop') {\n next.push(v == null ? null : ((v as Record<string, unknown>)[op.name] ?? null))\n } else if (op.type === 'index') {\n if (!Array.isArray(v)) throw new Error(`--jq: cannot index non-array with [${op.n}]`)\n const idx = op.n < 0 ? v.length + op.n : op.n\n next.push(v[idx] ?? null)\n } else {\n if (Array.isArray(v)) next.push(...v)\n else if (v && typeof v === 'object') next.push(...Object.values(v))\n else throw new Error(`--jq: cannot iterate over ${v === null ? 'null' : typeof v} — .[] needs an array or object`)\n }\n }\n stream = next\n }\n return stream\n}\n\n/** Renders a jq output stream: raw strings (unquoted, for piping), JSON for the rest. */\nexport function formatJq(data: unknown, expr: string): string {\n return applyJq(data, expr)\n .map((r) => (typeof r === 'string' ? r : r === undefined ? 'null' : JSON.stringify(r)))\n .join('\\n')\n}\n","import type { OutputMode } from './formatter.js'\n\nexport interface Spinner {\n start(message: string): void\n stop(message?: string): void\n // Mark the in-flight operation as failed (✖). Message optional: a catch block\n // typically fails the spinner, then prints the real error separately.\n fail(message?: string): void\n}\n\n// No-op spinner for JSON/quiet modes — no TTY output during machine-readable runs\nconst NO_OP_SPINNER: Spinner = {\n start: () => {},\n stop: () => {},\n fail: () => {},\n}\n\n// TTY spinner backed by ora (dynamic import for CJS compatibility)\nclass OraSpinner implements Spinner {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private instance: any = null\n\n start(message: string): void {\n import('ora').then(({ default: ora }) => {\n this.instance = ora(message).start()\n }).catch(() => {\n // ora unavailable — fall back to plain stdout\n process.stdout.write(`${message}\\n`)\n })\n }\n\n stop(message?: string): void {\n if (this.instance) {\n this.instance.succeed(message)\n this.instance = null\n } else if (message) {\n process.stdout.write(`${message}\\n`)\n }\n }\n\n fail(message?: string): void {\n if (this.instance) {\n // ora.fail(undefined) keeps the original spinner text but marks it ✖.\n this.instance.fail(message)\n this.instance = null\n } else if (message) {\n process.stderr.write(`${message}\\n`)\n }\n }\n}\n\nexport function createSpinner(mode: OutputMode): Spinner {\n if (mode === 'tty') return new OraSpinner()\n return NO_OP_SPINNER\n}\n","import { type OutputMode, type OutputOptions, formatOutput, formatTable, formatError, formatJq, detectOutputMode } from './formatter.js'\nimport { createSpinner, type Spinner } from './spinner.js'\n\nexport class Printer {\n constructor(\n private mode: OutputMode,\n // When set, every log/table is run through the minimal jq filter instead of\n // the human/JSON renderer. A bad expression throws — caught by the command's\n // catch block, which prints the message and exits non-zero (no stack trace).\n private jq?: string,\n ) {}\n\n /** True only for human-readable output, where extra hint lines are safe to print. */\n isTty(): boolean {\n return this.mode === 'tty' && !this.jq\n }\n\n log(data: unknown): void {\n if (this.jq) return this.emitJq(data)\n const out = formatOutput(data, this.mode)\n if (out !== '') console.log(out)\n }\n\n table(rows: Record<string, unknown>[], columns?: string[]): void {\n if (this.jq) return this.emitJq(rows)\n if (this.mode === 'quiet') return\n if (this.mode === 'json') {\n console.log(formatOutput(rows, 'json'))\n return\n }\n const out = formatTable(rows, columns)\n if (out !== '') console.log(out)\n }\n\n private emitJq(data: unknown): void {\n // --jq implies machine output regardless of TTY; a bad expr throws here.\n const out = formatJq(data, this.jq!)\n if (out !== '') console.log(out)\n }\n\n error(err: Error | string): void {\n // Errors never run through jq — they go to stderr as plain/JSON per mode.\n const out = formatError(err, this.jq ? 'json' : this.mode)\n console.error(out)\n }\n\n spinner(message: string): Spinner {\n // A jq run is machine output — suppress the spinner so it can't leak into stdout.\n const s = createSpinner(this.jq ? 'json' : this.mode)\n s.start(message)\n return s\n }\n}\n\nexport function createPrinter(options: OutputOptions): Printer {\n const mode = detectOutputMode(options)\n return new Printer(mode, options.jq)\n}\n","export const EXIT_CODES = {\n SUCCESS: 0,\n GENERAL_ERROR: 1,\n AUTH_ERROR: 2,\n SCOPE_ERROR: 3,\n NOT_FOUND: 4,\n RATE_LIMITED: 5,\n VALIDATION_ERROR: 6,\n NETWORK_ERROR: 7,\n} as const\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES]\n\n// Named sentinel classes used for instanceof checks against @autoposting.ai/sdk errors.\n// We match by constructor name so this works even if the SDK hasn't shipped error\n// classes yet (dynamic require would silently fail). When the SDK exports these\n// classes they will inherit from AutopostingError and carry the same names.\nfunction matchesClass(error: unknown, className: string): boolean {\n if (error == null || typeof error !== 'object') return false\n // Walk prototype chain checking constructor names\n let proto = Object.getPrototypeOf(error) as object | null\n while (proto !== null) {\n const ctor = (proto as { constructor?: { name?: string } }).constructor\n if (ctor?.name === className) return true\n proto = Object.getPrototypeOf(proto) as object | null\n }\n return false\n}\n\nexport function exitCodeFromError(error: unknown): ExitCode {\n // An explicit numeric `exitCode` (e.g. attached by resolveAuth for missing/invalid\n // credentials) takes precedence over class-name matching, so every command — not\n // just the ones with a local wrapper — exits with the right code.\n const attached = (error as { exitCode?: number } | null)?.exitCode\n if (typeof attached === 'number' && Number.isInteger(attached) && attached >= 0) {\n return attached as ExitCode\n }\n if (matchesClass(error, 'AuthenticationError')) return EXIT_CODES.AUTH_ERROR\n if (matchesClass(error, 'ScopeError')) return EXIT_CODES.SCOPE_ERROR\n if (matchesClass(error, 'NotFoundError')) return EXIT_CODES.NOT_FOUND\n if (matchesClass(error, 'RateLimitError')) return EXIT_CODES.RATE_LIMITED\n if (matchesClass(error, 'ValidationError')) return EXIT_CODES.VALIDATION_ERROR\n if (matchesClass(error, 'NetworkError')) return EXIT_CODES.NETWORK_ERROR\n // SDK transport failures are an AutopostingError carrying a string `code`, not a\n // dedicated class — match on the code so timeouts/network drops map to exit 7.\n const code = (error as { code?: unknown } | null)?.code\n if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return EXIT_CODES.NETWORK_ERROR\n return EXIT_CODES.GENERAL_ERROR\n}\n","import { Command } from 'commander'\nimport { execSync } from 'node:child_process'\nimport {\n deleteAllProfiles,\n deleteProfile,\n getActiveProfile,\n readCredentials,\n saveProfile,\n setActiveProfile,\n} from '../auth/credential-store.js'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { requestDeviceCode, pollDeviceCode } from '../auth/device-code-client.js'\n\n// Backend auth routes (/auth/cli/*) are reached via the frontend /api-proxy rewrite.\nconst DEFAULT_BASE_URL = 'https://app.autoposting.ai/api-proxy'\n\nfunction resolveBaseUrl(globals: { baseUrl?: string }): string {\n return globals.baseUrl ?? process.env.AUTOPOSTING_BASE_URL ?? DEFAULT_BASE_URL\n}\n\nfunction tryOpenUrl(url: string): void {\n try {\n // Attempt to open browser; ignore failures (CI, headless, etc.)\n const platform = process.platform\n if (platform === 'darwin') execSync(`open \"${url}\"`, { stdio: 'ignore' })\n else if (platform === 'win32') execSync(`start \"\" \"${url}\"`, { stdio: 'ignore' })\n else execSync(`xdg-open \"${url}\"`, { stdio: 'ignore' })\n } catch {\n // Non-fatal: user can open URL manually\n }\n}\n\nexport function createAuthCommand(): Command {\n const auth = new Command('auth').description('Manage authentication and profiles')\n\n // ap auth login [--api-key <key>] [--profile <name>] [--base-url <url>]\n // Note: --api-key is also a root-level global option on the program. Commander consumes\n // options left-to-right so the root picks it up first. We use optsWithGlobals() to\n // merge root + local options and read whichever level captured the flag.\n auth\n .command('login')\n .description('Log in via browser device code flow, or store an API key directly with --api-key')\n .option('--api-key <key>', 'API key to store directly (skips device code flow)')\n .option('--profile <name>', 'Profile name to save under', 'default')\n .option('--base-url <url>', 'API base URL (overrides AUTOPOSTING_BASE_URL)')\n .action(async (localOpts: { apiKey?: string; profile: string; baseUrl?: string }, cmd: Command) => {\n const opts = cmd.optsWithGlobals<{ apiKey?: string; profile: string; baseUrl?: string }>()\n\n // Fast path: --api-key provided, store directly\n if (opts.apiKey) {\n saveProfile(opts.profile, {\n apiKey: opts.apiKey,\n createdAt: new Date().toISOString(),\n })\n console.log(`Logged in. Profile \"${opts.profile}\" saved.`)\n return\n }\n\n // Device code flow\n const baseUrl = resolveBaseUrl(opts)\n\n let deviceCodeResp\n try {\n deviceCodeResp = await requestDeviceCode(baseUrl)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n\n const { deviceCode, userCode, verificationUri } = deviceCodeResp\n let pollInterval = deviceCodeResp.interval\n\n console.log(`\\nEnter code ${userCode} at ${verificationUri}\\n`)\n tryOpenUrl(verificationUri)\n\n // Spinner-style wait indicator using process.stdout so we can overwrite it\n const frames = ['|', '/', '-', '\\\\']\n let frameIdx = 0\n const spinnerInterval = setInterval(() => {\n process.stdout.write(`\\rWaiting for authorization... ${frames[frameIdx++ % frames.length]}`)\n }, 100)\n\n const clearSpinner = () => {\n clearInterval(spinnerInterval)\n process.stdout.write('\\r\\x1b[K') // clear spinner line\n }\n\n // Poll loop\n while (true) {\n await new Promise<void>((resolve) => setTimeout(resolve, pollInterval * 1000))\n\n let result\n try {\n result = await pollDeviceCode(baseUrl, deviceCode)\n } catch (err) {\n clearSpinner()\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n\n switch (result.status) {\n case 'complete': {\n clearSpinner()\n const token = result.sessionToken!\n saveProfile(opts.profile, {\n apiKey: token,\n createdAt: new Date().toISOString(),\n })\n console.log(`Logged in. Profile \"${opts.profile}\" saved.`)\n return\n }\n\n case 'expired_token':\n clearSpinner()\n console.error('Error: Authorization expired. Run `ap auth login` again.')\n process.exit(2)\n break\n\n case 'access_denied':\n clearSpinner()\n console.error('Error: Access denied.')\n process.exit(2)\n break\n\n case 'slow_down':\n // Double the interval as instructed by server\n pollInterval = result.interval ?? pollInterval * 2\n break\n\n case 'authorization_pending':\n default:\n // Continue polling\n break\n }\n }\n })\n\n // ap auth logout [--all]\n auth\n .command('logout')\n .description('Remove the active profile (or all profiles with --all)')\n .option('--all', 'Remove all stored profiles')\n .action((opts: { all?: boolean }) => {\n if (opts.all) {\n deleteAllProfiles()\n console.log('All profiles removed.')\n return\n }\n\n const creds = readCredentials()\n const active = creds?.activeProfile\n if (!active) {\n console.log('No active profile to log out from.')\n return\n }\n\n deleteProfile(active)\n console.log(`Profile \"${active}\" removed.`)\n })\n\n // ap auth switch <profile>\n auth\n .command('switch <profile>')\n .description('Switch the active profile')\n .action((profile: string) => {\n try {\n setActiveProfile(profile)\n console.log(`Switched to profile \"${profile}\".`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n // ap auth whoami\n auth\n .command('whoami')\n .description('Show current authentication method and identity')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n try {\n const globals = cmd.optsWithGlobals<{ apiKey?: string }>()\n const cred = resolveAuth({ apiKey: globals.apiKey })\n\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n const creds = readCredentials()\n const profileName = creds?.activeProfile ?? 'unknown'\n const profile = creds?.profiles[profileName]\n console.log(`Profile: ${profileName}`)\n if (profile?.workspace) console.log(`Workspace: ${profile.workspace}`)\n if (profile?.email) console.log(`Email: ${profile.email}`)\n }\n // Never print the raw API key\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n console.log(`API key: ${masked}`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n // ap auth status — alias for whoami\n auth\n .command('status')\n .description('Alias for whoami — show current authentication status')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n try {\n const globals = cmd.optsWithGlobals<{ apiKey?: string }>()\n const cred = resolveAuth({ apiKey: globals.apiKey })\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n const creds = readCredentials()\n const profileName = creds?.activeProfile ?? 'unknown'\n console.log(`Profile: ${profileName}`)\n }\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n console.log(`API key: ${masked}`)\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exit(2)\n }\n })\n\n return auth\n}\n","export interface DeviceCodeResponse {\n deviceCode: string\n userCode: string\n verificationUri: string\n expiresIn: number\n interval: number\n}\n\nexport interface PollResult {\n status: 'authorization_pending' | 'complete' | 'expired_token' | 'access_denied' | 'slow_down'\n sessionToken?: string\n orgId?: string\n interval?: number\n}\n\nasync function fetchWithTimeout(\n url: string,\n init: RequestInit = {},\n timeoutMs = 30_000,\n): Promise<Response> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n return await fetch(url, { ...init, signal: controller.signal })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(`Request to ${url} timed out after ${timeoutMs}ms`)\n }\n throw err\n } finally {\n clearTimeout(timer)\n }\n}\n\nasync function parseJson<T>(res: Response): Promise<T> {\n const text = await res.text()\n try {\n return JSON.parse(text) as T\n } catch {\n throw new Error(\n `Expected a JSON response (HTTP ${res.status}) but received non-JSON. ` +\n `Verify the API base URL points at the API, not the web app.`,\n )\n }\n}\n\nexport async function requestDeviceCode(baseUrl: string): Promise<DeviceCodeResponse> {\n const res = await fetchWithTimeout(`${baseUrl}/auth/cli/device-code`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText)\n throw new Error(`Device code request failed (${res.status}): ${text}`)\n }\n\n // The server wraps the fields in its usual {success, data} envelope.\n const { data } = await parseJson<{ data?: DeviceCodeResponse }>(res)\n if (!data?.deviceCode || !data.userCode || !data.verificationUri) {\n throw new Error('Device code response is missing deviceCode, userCode or verificationUri.')\n }\n return data\n}\n\nexport async function pollDeviceCode(baseUrl: string, deviceCode: string): Promise<PollResult> {\n const url = `${baseUrl}/auth/cli/poll?device_code=${encodeURIComponent(deviceCode)}`\n const res = await fetchWithTimeout(url)\n\n const text = await res.text().catch(() => res.statusText)\n let body: Partial<PollResult> = {}\n try {\n body = JSON.parse(text) as Partial<PollResult>\n } catch {\n // handled below\n }\n // The server answers slow_down, expired_token and access_denied with HTTP 400 and a status.\n if (res.ok || (res.status === 400 && body.status)) {\n if (!body.status) throw new Error(`Poll response (HTTP ${res.status}) has no status.`)\n return body as PollResult\n }\n throw new Error(`Poll request failed (${res.status}): ${text}`)\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createBillingCommand(): Command {\n const billing = new Command('billing').description('View billing information')\n\n // ap billing status\n billing\n .command('status')\n .description('Show current plan and subscription status')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching billing status…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const status = await client.billing.status()\n spinner.stop()\n printer.table(\n [\n {\n plan: status.planName,\n status: status.status ?? '—',\n cycle: status.billingCycle ?? '—',\n accounts: `${status.accountsUsed}/${status.accountLimit === -1 ? '∞' : status.accountLimit}`,\n credits: status.creditBalance,\n renews: status.currentPeriodEnd ?? '—',\n 'trial ends': status.trialEnd ?? '—',\n },\n ],\n ['plan', 'status', 'cycle', 'accounts', 'credits', 'renews', 'trial ends'],\n )\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap billing credits\n billing\n .command('credits')\n .description('Show credit balance and usage breakdown')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching credit balance…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const credits = await client.billing.credits()\n spinner.stop()\n if (!printer.isTty()) {\n printer.log(credits)\n return\n }\n printer.table(\n [\n {\n balance: credits.balanceFormatted,\n 'spent (30d)': credits.totalSpent30d,\n },\n ],\n ['balance', 'spent (30d)'],\n )\n if (credits.recentUsage.length > 0) {\n const usageRows = credits.recentUsage.map((e) => ({\n date: e.date,\n description: e.description,\n amount: e.amount,\n type: e.type,\n }))\n printer.table(usageRows, ['date', 'description', 'amount', 'type'])\n }\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return billing\n}\n","import { Command } from 'commander'\nimport { readFile } from 'node:fs/promises'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\ntype Globals = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\nasync function run(\n cmd: Command,\n action: (client: Autoposting) => Promise<unknown>,\n) {\n const globals = cmd.optsWithGlobals<Globals>()\n const printer = createPrinter(globals)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n printer.log(await action(new Autoposting({ apiKey: cred.apiKey })))\n } catch (err) {\n printer.error(err as Error)\n process.exitCode = exitCodeFromError(err)\n }\n}\nexport function createAccountsCommand() {\n const command = new Command('accounts').description(\n 'Import account CSVs and connect through browser approval; progress lives in the workspace',\n )\n command\n .command('import')\n .requiredOption(\n '--from <csv>',\n 'CSV with brand_name,platform,account_url; optional brand_slug,timezone',\n )\n .action(async (opts: { from: string }, cmd: Command) =>\n run(cmd, async (client) =>\n client.accountOnboarding.create({\n csv: await readFile(opts.from, 'utf8'),\n }),\n ),\n )\n command\n .command('prepare <importId>')\n .option('--offset <number>', 'Resume at this row offset', '0')\n .description(\n 'Create/reuse the next 25 brands; repeat with nextOffset until null',\n )\n .action(async (id: string, opts: { offset: string }, cmd: Command) =>\n run(cmd, async (client) => {\n const offset = Number(opts.offset)\n if (!Number.isInteger(offset) || offset < 0)\n throw new Error('offset must be a nonnegative integer')\n return client.accountOnboarding.prepare(id, offset)\n }),\n )\n command\n .command('status <importId>')\n .option('--offset <number>', 'Row offset', '0')\n .option('--limit <number>', 'Rows per page (1–100)', '50')\n .description('Show connected, pending, reconnect and confirmation rows')\n .action(\n async (\n id: string,\n opts: { offset: string; limit: string },\n cmd: Command,\n ) =>\n run(cmd, (client) =>\n client.accountOnboarding.status(id, {\n offset: Number(opts.offset),\n limit: Number(opts.limit),\n }),\n ),\n )\n command\n .command('authorize <importId> <rowId>')\n .description(\n 'Print a fresh approval link. Open it in your browser, select the CSV account, then check status',\n )\n .action(async (id: string, rowId: string, _opts: unknown, cmd: Command) =>\n run(cmd, (client) => client.accountOnboarding.authorize(id, rowId)),\n )\n command\n .command('confirm <importId> <rowId>')\n .requiredOption(\n '--token-id <id>',\n 'Actual account tokenId from status; confirm only after comparing it with the CSV account',\n )\n .action(\n async (\n id: string,\n rowId: string,\n opts: { tokenId: string },\n cmd: Command,\n ) =>\n run(cmd, (client) =>\n client.accountOnboarding.confirm(id, rowId, opts.tokenId),\n ),\n )\n command\n .command('delete <importId>')\n .requiredOption(\n '--force',\n 'Discard import progress; keeps brands and connected accounts',\n )\n .action(async (id: string, _opts: unknown, cmd: Command) =>\n run(cmd, (client) => client.accountOnboarding.remove(id)),\n )\n return command\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport type { PlatformConnection } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\nimport { parsePairs } from '../lib/media-flags.js'\nimport {\n getDefaultAccounts,\n setDefaultAccount,\n clearDefaultAccounts,\n} from '../auth/config-store.js'\n\n/**\n * Classify a platform connection's token. A connection is only \"ok\" when it's\n * connected, has no refresh failure, and isn't past its expiry — otherwise the\n * token can't actually post, so reporting \"ok\" (the old behavior) was misleading.\n */\nexport function tokenStatus(c: PlatformConnection, now: number = Date.now()): string {\n if (!c.connected) return '—'\n if (c.refreshError) return 'expired'\n if (c.expiresAt) {\n const expMs = Date.parse(c.expiresAt)\n if (Number.isNaN(expMs) || expMs <= now) return 'expired'\n }\n return 'ok'\n}\n\nexport function buildAuthStatusRow(c: PlatformConnection, now: number = Date.now()) {\n return {\n platform: c.platform,\n connected: c.connected ? 'yes' : 'no',\n username: c.platformUsername ?? '—',\n 'token status': tokenStatus(c, now),\n expires: c.expiresAt ?? '—',\n }\n}\n\nexport function createBrandsCommand(): Command {\n const brands = new Command('brands').description('Manage brands')\n\n brands.command('connect-facebook <slug>')\n .description('Open the app to connect Facebook Pages; sign in, check beta access and explicitly select Pages there')\n .option('--no-browser', 'Print the application link without opening a browser')\n .action(async (slug: string, opts: { browser: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{ apiKey?: string; json?: boolean; quiet?: boolean; format?: 'table' | 'json' }>()\n const printer = createPrinter(globals)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const handoff = await client.brands.facebookConnection(slug)\n printer.log(handoff)\n if (opts.browser) {\n try {\n const { default: open } = await import('open')\n await open(handoff.url, { wait: true })\n } catch {\n printer.error(`Could not open the browser. Open ${handoff.url} manually, then check ap brands auth-status ${slug}.`)\n process.exitCode = 1\n }\n }\n } catch (error) {\n printer.error(error as Error)\n process.exitCode = exitCodeFromError(error)\n }\n })\n\n // ap brands list\n brands\n .command('list')\n .description('List all brands')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching brands…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.brands.list()\n spinner.stop()\n const rows = list.map((b) => ({\n slug: b.slug,\n name: b.name,\n platforms: b.platforms\n .filter((p) => p.connected)\n .map((p) => p.platform)\n .join(', ') || '—',\n timezone: b.timezone,\n }))\n printer.table(rows, ['slug', 'name', 'platforms', 'timezone'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands get <slug>\n brands\n .command('get <slug>')\n .description('Get a brand by slug')\n .action(async (slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.retrieve(slug)\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands create --name <name> [--timezone <tz>]\n brands\n .command('create')\n .description('Create a new brand')\n .requiredOption('--name <name>', 'Brand display name')\n .option('--timezone <tz>', 'IANA timezone (e.g. America/New_York)')\n .action(async (opts: { name: string; timezone?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating brand…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.create({\n name: opts.name,\n ...(opts.timezone ? { timezone: opts.timezone } : {}),\n })\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands update <slug> [--name <name>] [--timezone <tz>]\n brands\n .command('update <slug>')\n .description('Update a brand')\n .option('--name <name>', 'New display name')\n .option('--timezone <tz>', 'New IANA timezone')\n .action(async (slug: string, opts: { name?: string; timezone?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brand = await client.brands.update(slug, {\n ...(opts.name ? { name: opts.name } : {}),\n ...(opts.timezone ? { timezone: opts.timezone } : {}),\n })\n spinner.stop()\n printer.log(brand)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands delete <slug> [--force]\n brands\n .command('delete <slug>')\n .description('Delete a brand (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (slug: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a brand. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting brand \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.brands.remove(slug)\n spinner.stop()\n printer.log(`Brand \"${slug}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands auth-status <slug>\n brands\n .command('auth-status <slug>')\n .description('Show platform connection status for a brand')\n .action(async (slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n }>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching auth status for \"${slug}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const connections = await client.brands.authStatus(slug)\n spinner.stop()\n const rows = connections.map((c) => buildAuthStatusRow(c))\n printer.table(rows, ['platform', 'connected', 'username', 'token status', 'expires'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(exitCodeFromError(err))\n }\n })\n\n // ap brands set-default-account <slug> <p=handle|id|all...>\n // Local-only: saves the account to target per platform when --account is omitted.\n brands\n .command('set-default-account <slug> <pairs...>')\n .description('Save default target account(s) for a brand, e.g. x=@handle linkedin=all')\n .action((slug: string, pairs: string[], _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n try {\n const parsed = parsePairs('--account', pairs)\n for (const [platform, value] of Object.entries(parsed)) {\n setDefaultAccount(slug, platform as keyof typeof parsed, value as string)\n }\n printer.log(getDefaultAccounts(slug))\n } catch (err) {\n printer.error(err as Error)\n process.exit(1)\n }\n })\n\n // ap brands get-default-account <slug>\n brands\n .command('get-default-account <slug>')\n .description('Show saved default account(s) for a brand')\n .action((slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n printer.log(getDefaultAccounts(slug))\n })\n\n // ap brands clear-default-account <slug>\n brands\n .command('clear-default-account <slug>')\n .description('Remove all saved default accounts for a brand')\n .action((slug: string, _opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals())\n clearDefaultAccounts(slug)\n printer.log(getDefaultAccounts(slug))\n })\n\n return brands\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport type { Platform } from '@autoposting.ai/sdk'\n\nexport interface ConfigFile {\n /** Default context applied when a per-call flag is absent (N1). */\n context?: { brand?: string }\n /** Per-brand, per-platform default account: handle | platformUserId | 'all' (M5). */\n defaultAccounts?: Record<string, Partial<Record<Platform, string>>>\n}\n\nexport function getConfigPath(): string {\n // Same XDG resolution as the credential store; a sibling file so config never\n // shares storage with secrets (credentials.json).\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config')\n return path.join(base, 'autoposting', 'config.json')\n}\n\nexport function readConfig(): ConfigFile | null {\n try {\n return JSON.parse(fs.readFileSync(getConfigPath(), 'utf8')) as ConfigFile\n } catch {\n // Missing or corrupt — callers start from {}. config.json holds regenerable\n // defaults (not secrets), so a corrupt read is non-fatal.\n return null\n }\n}\n\n// ponytail: mirrors credential-store's atomic temp-write+rename+chmod. Kept as a\n// separate file (not a shared helper) so refactoring the tested, shipped\n// credential store can't regress; the security pattern is ~12 lines.\nexport function writeConfig(cfg: ConfigFile): void {\n const filePath = getConfigPath()\n fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 })\n const tmp = `${filePath}.${process.pid}.tmp`\n try {\n fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { encoding: 'utf8', mode: 0o600 })\n fs.renameSync(tmp, filePath)\n } catch (err) {\n try {\n fs.unlinkSync(tmp)\n } catch {\n // temp never created — nothing to clean up\n }\n throw err\n }\n fs.chmodSync(filePath, 0o600)\n}\n\n// ── Default context (N1) ───────────────────────────────────────────────────\nexport function getContextBrand(): string | null {\n return readConfig()?.context?.brand ?? null\n}\n\nexport function setContextBrand(brand: string): void {\n const cfg = readConfig() ?? {}\n cfg.context = { ...cfg.context, brand }\n writeConfig(cfg)\n}\n\nexport function unsetContextBrand(): void {\n const cfg = readConfig()\n if (!cfg?.context?.brand) return\n delete cfg.context.brand\n writeConfig(cfg)\n}\n\n/** Brand for a command: an explicit --brand wins, else the saved context, else null. */\nexport function resolveBrand(optBrand?: string): string | null {\n return optBrand ?? getContextBrand()\n}\n\n// ── Per-brand default accounts (M5) ────────────────────────────────────────\nexport function getDefaultAccount(brand: string, platform: Platform): string | null {\n return readConfig()?.defaultAccounts?.[brand]?.[platform] ?? null\n}\n\nexport function getDefaultAccounts(brand: string): Partial<Record<Platform, string>> {\n return readConfig()?.defaultAccounts?.[brand] ?? {}\n}\n\nexport function setDefaultAccount(brand: string, platform: Platform, value: string): void {\n const cfg = readConfig() ?? {}\n cfg.defaultAccounts ??= {}\n cfg.defaultAccounts[brand] = { ...cfg.defaultAccounts[brand], [platform]: value }\n writeConfig(cfg)\n}\n\nexport function clearDefaultAccounts(brand: string): void {\n const cfg = readConfig()\n if (!cfg?.defaultAccounts?.[brand]) return\n delete cfg.defaultAccounts[brand]\n writeConfig(cfg)\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createCarouselsCommand(): Command {\n const carousels = new Command('carousels').description('Manage carousels')\n\n // ap carousels list\n carousels\n .command('list')\n .description('List all carousels')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching carousels…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.carousels.list()\n spinner.stop()\n const rows = list.items.map((c) => ({\n id: c.id,\n title: c.title ?? '—',\n slides: c.slides.length,\n status: c.status,\n createdAt: c.createdAt,\n }))\n printer.table(rows, ['id', 'title', 'slides', 'status', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels get <id>\n carousels\n .command('get <id>')\n .description('Get a carousel by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching carousel \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.retrieve(id)\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels create [--title <title>]\n carousels\n .command('create')\n .description('Create a new carousel')\n .option('--title <title>', 'Carousel title')\n .action(async (opts: { title?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating carousel…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.create(\n opts.title ? { title: opts.title } : undefined,\n )\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels generate --topic <topic> [--brand <slug>] [--slides <n>]\n carousels\n .command('generate')\n .description('AI-generate a carousel from a topic')\n .requiredOption('--topic <topic>', 'Topic to generate slides for')\n .option('--brand <slug>', 'Brand slug for brand voice')\n .option('--slides <n>', 'Number of slides to generate')\n .action(async (opts: { topic: string; brand?: string; slides?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Generating carousel…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const carousel = await client.carousels.generate({\n topic: opts.topic,\n ...(opts.brand ? { brandSlug: opts.brand } : {}),\n ...(opts.slides ? { slideCount: parseInt(opts.slides, 10) } : {}),\n })\n spinner.stop()\n printer.log(carousel)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels draft <id>\n carousels\n .command('draft <id>')\n .description('Convert a carousel to a post draft')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Converting carousel \"${id}\" to draft…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.carousels.draft(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap carousels delete <id> --force\n carousels\n .command('delete <id>')\n .description('Delete a carousel (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a carousel. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting carousel \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.carousels.remove(id)\n spinner.stop()\n printer.log(`Carousel \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return carousels\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\n/**\n * Resolve the brand for an upload: use --brand if given, else auto-pick when the\n * workspace has exactly one brand. Zero or many brands → ask the user to pass --brand.\n */\nasync function resolveBrandId(client: Autoposting, explicit?: string): Promise<string> {\n if (explicit) return explicit\n const brands = await client.brands.list()\n if (brands.length === 1) return brands[0].id\n if (brands.length === 0) {\n throw new Error('No brands found. Create a brand first, then pass --brand <id>.')\n }\n throw new Error(\n `Multiple brands found — pass --brand <id>. Available: ${brands.map((b) => `${b.name} (${b.id})`).join(', ')}`,\n )\n}\n\nexport function createClipsCommand(): Command {\n const clips = new Command('clips').description('Manage video clips')\n\n // ap clips list\n clips\n .command('list')\n .description('List all clips')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching clips…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.clips.list()\n spinner.stop()\n const rows = list.clips.map((c) => ({\n id: c.id,\n name: c.name,\n status: c.status,\n duration: c.duration !== undefined ? `${c.duration}s` : '—',\n }))\n printer.table(rows, ['id', 'name', 'status', 'duration'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips get <id>\n clips\n .command('get <id>')\n .description('Get a clip by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const clip = await client.clips.retrieve(id)\n spinner.stop()\n printer.log(clip)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips upload <file> [--brand <id>] [--name <name>]\n clips\n .command('upload <file>')\n .description('Upload a video file as a clip')\n .option('--brand <id>', 'Brand to attach the clip to (defaults to your only brand)')\n .option('--name <name>', 'Override the clip title (defaults to filename)')\n .action(async (file: string, opts: { brand?: string; name?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Uploading clip…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brandId = await resolveBrandId(client, opts.brand)\n const clip = await client.clips.upload(file, {\n brandId,\n ...(opts.name ? { title: opts.name } : {}),\n onProgress: (pct) => {\n if (pct > 0 && pct < 100) spinner.stop()\n },\n })\n spinner.stop()\n printer.log(clip)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips import --url <url> [--brand <id>] [--name <name>]\n clips\n .command('import')\n .description('Start AI clipping from a video URL (e.g. a YouTube video)')\n .requiredOption('--url <url>', 'URL of the video to import')\n .option('--brand <id>', 'Brand ID (auto-picked when the workspace has exactly one brand)')\n .option('--name <name>', 'Name for the imported clip')\n .action(async (opts: { url: string; brand?: string; name?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Importing clip…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const brandId = await resolveBrandId(client, opts.brand)\n const { clipId } = await client.clips.importUrl({\n url: opts.url,\n brandId,\n ...(opts.name ? { title: opts.name } : {}),\n })\n spinner.stop()\n printer.log({ clipId })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips render <id> [--candidate <id>] [--revision <n>]\n clips\n .command('render <id>')\n .description('Render a clip (uses credits)')\n .option('--candidate <id>', 'Render only this candidate')\n .option('--revision <n>', 'Clip editRevision (read from the clip when omitted)', (v) => Number(v))\n .action(async (id: string, opts: { candidate?: string; revision?: number }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Rendering clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { jobIds, activeJobIds, reusedJobIds } = await client.clips.render(id, {\n ...(opts.revision !== undefined ? { editRevision: opts.revision } : {}),\n ...(opts.candidate ? { candidateId: opts.candidate } : {}),\n })\n spinner.stop()\n printer.log({ jobIds, activeJobIds, reusedJobIds })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips draft <id> [--candidate <id>] [--aspect-ratio <ratio>]\n clips\n .command('draft <id>')\n .description('Create a draft post from a rendered clip')\n .option('--candidate <id>', 'Candidate to use (defaults to the first rendered one)')\n .option('--aspect-ratio <ratio>', 'Render format: 9:16, 16:9, 1:1 or 4:5')\n .action(async (id: string, opts: { candidate?: string; aspectRatio?: '9:16' | '16:9' | '1:1' | '4:5' }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Creating draft from clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { postId } = await client.clips.createDraft(id, {\n ...(opts.candidate ? { candidateId: opts.candidate } : {}),\n ...(opts.aspectRatio ? { aspectRatio: opts.aspectRatio } : {}),\n })\n spinner.stop()\n printer.log({ postId })\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap clips delete <id> --force\n clips\n .command('delete <id>')\n .description('Delete a clip (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a clip. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting clip \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.clips.remove(id)\n spinner.stop()\n printer.log(`Clip \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return clips\n}\n","import { Command } from 'commander'\nimport { readFile } from 'node:fs/promises'\nimport { Autoposting, NotFoundError } from '@autoposting.ai/sdk'\nimport type { UpdatePostParams } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport type { Spinner } from '../output/spinner.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\nimport { parsePlatforms, validateScheduledAt, buildAndCreatePost } from '../lib/post-create.js'\nimport { parseBulkFile, createPostsBulk } from '../lib/post-bulk.js'\nimport { resolveBrand } from '../auth/config-store.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction parsePositiveInt(value: string, flag: string): number {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 1) {\n throw new Error(`${flag} must be a positive integer (received \"${value}\").`)\n }\n return n\n}\n\n/**\n * Resolves the process exit code for a caught error.\n * Honours the `exitCode` property set by `resolveAuth` (exit 2 for auth errors)\n * before falling back to the SDK error class mapping.\n */\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createPostsCommand(): Command {\n const posts = new Command('posts').description('Manage posts')\n\n // ap posts list [--brand <slug>] [--status <status>] [--limit <n>] [--page <n>]\n posts\n .command('list')\n .description('List posts')\n .option('--brand <slug>', 'Filter by brand slug (defaults to the saved context)')\n .option('--status <status>', 'Filter by status (draft|scheduled|published|failed)')\n .option('--limit <n>', 'Max results per page', '20')\n .option('--page <n>', 'Page number', '1')\n .action(async (opts: { brand?: string; status?: string; limit: string; page: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching posts…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.posts.list({\n brandSlug: resolveBrand(opts.brand) ?? undefined,\n status: opts.status as 'draft' | 'scheduled' | 'published' | 'failed' | undefined,\n limit: parsePositiveInt(opts.limit, '--limit'),\n page: parsePositiveInt(opts.page, '--page'),\n })\n spinner.stop()\n const rows = result.map((p) => ({\n id: p.id,\n brand: p.brandSlug,\n status: p.status,\n platforms: p.platforms.join(', '),\n text: p.text.length > 60 ? `${p.text.slice(0, 57)}…` : p.text,\n scheduledAt: p.scheduledAt ?? '—',\n }))\n printer.table(rows, ['id', 'brand', 'status', 'platforms', 'text', 'scheduledAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts get <id>\n posts\n .command('get <id>')\n .description('Get a post by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.getById(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts create --brand <slug> --text <text> --platforms <x,linkedin,...>\n posts\n .command('create')\n .description('Create a new post')\n .option('--brand <slug>', 'Brand slug (defaults to the saved context: ap config set-context)')\n // Not requiredOption: --from supplies text/platforms per row. Required-ness for\n // the single-post path is enforced manually below so --from can omit them.\n .option('--text <text>', 'Post text content (required unless --from)')\n .option('--platforms <list>', 'Comma-separated platforms, e.g. x,linkedin (required unless --from)')\n .option('--from <file>', 'Create posts in bulk from a CSV or JSON file (one post per row)')\n .option('--at <iso>', 'Schedule date/time (ISO 8601)')\n .option(\n '--thread <text...>',\n 'Additional posts appended after --text to form a thread (X/Threads only, max 25)',\n )\n // v0.3.3 — media\n .option('--media <path...>', 'Media file paths to attach (max 10)')\n .option('--alt-text <text...>', 'Alt text for --media files, aligned by index')\n .option('--platform-text <pairs...>', 'Per-platform text, e.g. x=Hello linkedin=World')\n .option('--platform-media <pairs...>', 'Per-platform media, e.g. instagram=photo.jpg x=banner.png')\n // v0.3.3 — YouTube\n .option('--yt-title <t>', 'YouTube video title')\n .option('--yt-description <d>', 'YouTube video description')\n .option('--yt-tags <list>', 'YouTube tags (comma-separated)')\n .option('--yt-privacy <v>', 'YouTube privacy status (public|unlisted|private)')\n .option('--yt-category <id>', 'YouTube category ID')\n .option('--yt-made-for-kids', 'Mark YouTube video as made for kids')\n // v0.3.3 — Instagram\n .option('--ig-reel', 'Post as an Instagram Reel')\n .option('--ig-share-to-feed', 'Share Reel to feed')\n .option('--ig-cover-url <url>', 'Reel cover image URL')\n .option('--ig-thumb-offset-ms <n>', 'Reel thumbnail offset in milliseconds')\n .option('--ig-collaborators <list>', 'Reel collaborator handles (comma-separated)')\n // v0.3.3 — Threads\n .option('--threads-reply-to <id>', 'Threads post ID to reply to')\n .option('--threads-reply-control <v>', 'Threads reply control (everyone|accounts_you_follow|mentioned_only)')\n // v0.3.3 — account selector\n .option('--facebook-format <format>', 'Facebook Pages: text|link|photo|multi-photo|video|reel')\n .option('--facebook-link <url>', 'Public HTTPS article URL for Facebook link format')\n .option('--account <p=handle|id...>', 'Target specific account per platform, e.g. x=@handle; Facebook Page lists: facebook=page-id-1,page-id-2')\n // v0.3.4 — preview the resolved request without uploading or posting\n .option('--dry-run', 'Print the resolved request body without uploading media or creating the post')\n .option('--preview', 'Alias for --dry-run')\n .action(\n async (\n opts: {\n brand?: string\n text?: string\n platforms?: string\n from?: string\n at?: string\n thread?: string[]\n // v0.3.3\n media?: string[]\n altText?: string[]\n platformText?: string[]\n platformMedia?: string[]\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n threadsReplyTo?: string\n threadsReplyControl?: string\n facebookFormat?: string\n facebookLink?: string\n account?: string[]\n dryRun?: boolean\n preview?: boolean\n },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n // Spinner is started only after the account picker (via onBeforeNetwork) — ora's\n // repaint loop fights the interactive prompt and can obscure the selection.\n let spinner: Spinner | undefined\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n\n // ── Bulk path: --from <file> creates one post per row ──────────────\n if (opts.from) {\n const rows = parseBulkFile(opts.from)\n const records = await createPostsBulk(client, rows, {\n cliBrand: resolveBrand(opts.brand) ?? undefined,\n })\n // Truncate text only for the human table; JSON/jq/quiet keep it full\n // (lossless echo for scripting consumers).\n const truncate = printer.isTty()\n printer.table(\n records.map((r) => ({\n '#': r.index + 1,\n status: r.status,\n id: r.id || '—',\n text: truncate && r.text.length > 40 ? `${r.text.slice(0, 37)}…` : r.text,\n error: r.error,\n })),\n ['#', 'status', 'id', 'text', 'error'],\n )\n if (records.some((r) => r.status === 'failed')) {\n process.exit(1)\n }\n return\n }\n\n // Resolve the brand before any validation so a missing brand fails first.\n const brand = resolveBrand(opts.brand)\n if (!brand) {\n throw new Error(\n 'No brand specified. Pass --brand <slug> or set a default with: ap config set-context --brand <slug>',\n )\n }\n if (!opts.text) {\n throw new Error('--text is required (or use --from <file> to create posts in bulk).')\n }\n if (!opts.platforms) {\n throw new Error('--platforms is required (or use --from <file> to create posts in bulk).')\n }\n\n const result = await buildAndCreatePost(\n client,\n { ...opts, brandSlug: brand, text: opts.text, platforms: opts.platforms },\n {\n // Picker reads stdin — gate on a real interactive terminal, not the\n // output mode (printer.isTty() is true even when stdin is piped).\n isTty: Boolean(process.stdin.isTTY),\n // --dry-run/--preview: resolve + validate, then return the request body\n // without uploading media or POSTing (onBeforeNetwork never fires).\n dryRun: Boolean(opts.dryRun || opts.preview),\n // Picker done — start the spinner now (covers uploads + create).\n onBeforeNetwork: () => {\n spinner = printer.spinner('Creating post…')\n },\n },\n )\n spinner?.stop()\n printer.log(result)\n } catch (err) {\n spinner?.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap posts update <id> [--text <text>] [--platforms <list>] [--at <iso>]\n posts\n .command('update <id>')\n .description('Update a post')\n .option('--from <file>', 'JSON update object with formats, target account IDs, captions and media URLs; explicit flags override file fields')\n .option('--text <text>', 'New post text')\n .option('--platforms <list>', 'New comma-separated platforms')\n .option('--at <iso>', 'New scheduled date/time (ISO 8601)')\n .action(\n async (\n id: string,\n opts: { text?: string; platforms?: string; at?: string; from?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n let patch: UpdatePostParams = {}\n if (opts.from) {\n const parsed: unknown = JSON.parse(await readFile(opts.from, 'utf8'))\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('--from requires one JSON update object')\n const allowed = ['text', 'platforms', 'scheduledAt', 'media', 'platformMedia', 'platformTexts', 'targetAccountIds', 'facebookOptions']\n if (Object.keys(parsed).some(key => !allowed.includes(key))) throw new Error('--from contains an unsupported update field')\n patch = parsed as UpdatePostParams\n if (patch.text !== undefined && typeof patch.text !== 'string') throw new Error('Update text must be a string')\n if (patch.platforms !== undefined) {\n if (!Array.isArray(patch.platforms) || patch.platforms.some(platform => typeof platform !== 'string' || !platform.trim() || platform.includes(','))) throw new Error('Update platforms must be an array of platform names')\n patch.platforms = parsePlatforms(patch.platforms.join(','))\n }\n if (patch.scheduledAt !== undefined) {\n if (typeof patch.scheduledAt !== 'string') throw new Error('Update scheduledAt must be an ISO datetime string')\n patch.scheduledAt = validateScheduledAt(patch.scheduledAt)\n }\n }\n const post = await client.posts.update(id, {\n ...patch,\n ...(opts.text !== undefined ? { text: opts.text } : {}),\n ...(opts.platforms ? { platforms: parsePlatforms(opts.platforms) } : {}),\n ...(opts.at ? { scheduledAt: validateScheduledAt(opts.at) } : {}),\n })\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap posts delete <id> [--force]\n posts\n .command('delete <id>')\n .description('Delete a post (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a post. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.posts.remove(id)\n spinner.stop()\n printer.log(`Post \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n // A failed delete (after the SDK's transient-retry gives up) may have left the\n // post in place — a NotFound means it's already gone, anything else is ambiguous.\n // Tell the user to verify so a still-scheduled post isn't silently orphaned.\n // Goes to stderr in every mode — a CI/piped run needs this safety hint too.\n if (!(err instanceof NotFoundError)) {\n printer.error(`The post may not have been deleted — verify with: ap posts get \"${id}\"`)\n }\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts publish <id>\n posts\n .command('publish <id>')\n .description('Publish a post immediately')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Publishing post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.publish(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts schedule <id> (--at <iso-datetime> | --cancel)\n posts\n .command('schedule <id>')\n .description('Schedule a post for a specific time, or --cancel to unschedule it')\n .option('--at <iso>', 'ISO 8601 datetime to schedule the post')\n .option('--cancel', 'Cancel scheduling')\n .option('--platform <platform>', 'facebook schedules only eligible failed Pages for recovery')\n .action(async (id: string, opts: { at?: string; cancel?: boolean; platform?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(\n opts.cancel ? `Unscheduling post \"${id}\"…` : `Scheduling post \"${id}\"…`,\n )\n try {\n // Exactly one of --at / --cancel — they are opposite operations.\n if (opts.cancel && opts.at) {\n throw new Error('Cannot use --at together with --cancel — choose one.')\n }\n if (!opts.cancel && !opts.at) {\n throw new Error('Provide either --at <iso> to schedule, or --cancel to unschedule.')\n }\n if (opts.platform && (opts.platform !== 'facebook' || opts.cancel)) throw new Error('--platform facebook requires --at and cannot be used with --cancel.')\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = opts.cancel\n ? await client.posts.unschedule(id)\n : opts.platform === 'facebook'\n ? await client.posts.schedule(id, validateScheduledAt(opts.at!), 'facebook')\n : await client.posts.schedule(id, validateScheduledAt(opts.at!))\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts retry <id>\n posts\n .command('retry <id>')\n .description('Retry a failed post')\n .option('--platform <platform>', 'Select a platform; facebook retries only failed Pages without remote evidence')\n .action(async (id: string, opts: { platform?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Retrying post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const platform = opts.platform ? parsePlatforms(opts.platform) : undefined\n if (platform && platform.length !== 1) throw new Error('--platform requires exactly one platform')\n const post = platform ? await client.posts.retry(id, platform[0]!) : await client.posts.retry(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts rewrite <id>\n posts\n .command('rewrite <id>')\n .description('AI-rewrite a post')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Rewriting post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const post = await client.posts.rewrite(id)\n spinner.stop()\n printer.log(post)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap posts score <id>\n posts\n .command('score <id>')\n .description('Score a post with AI feedback')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Scoring post \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.posts.score(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return posts\n}\n","import fs from 'node:fs/promises'\nimport nodePath from 'node:path'\nimport type { Autoposting, MediaInput, Platform, FacebookOptions } from '@autoposting.ai/sdk'\nimport {\n extToMime,\n parsePairs,\n parsePlatformMediaPairs,\n validateMediaCount,\n validateMediaPaths,\n validateMediaExtensions,\n alignAltText,\n buildYoutubeOptions,\n buildInstagramOptions,\n buildThreadsOptions,\n} from './media-flags.js'\nimport { resolveTargetAccounts } from './account-select.js'\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube', 'facebook']\n\nexport function parsePlatforms(raw: string): Platform[] {\n const parts = raw.split(',').map((p) => p.trim()).filter(Boolean)\n if (parts.length === 0) {\n throw new Error('No platforms provided. Pass a comma-separated list, e.g. --platforms x,linkedin')\n }\n const invalid = parts.filter((p) => !VALID_PLATFORMS.includes(p as Platform))\n if (invalid.length > 0) {\n throw new Error(\n `Unsupported platform(s): ${invalid.join(', ')}. Valid platforms: ${VALID_PLATFORMS.join(', ')}`,\n )\n }\n return parts as Platform[]\n}\n\nexport function validateScheduledAt(value: string): string {\n // Require a real ISO 8601 datetime. Date.parse alone is lenient (accepts locale formats\n // like \"01/02/2026\"), so also require the YYYY-MM-DDTHH:MM prefix the API expects.\n const ms = Date.parse(value)\n if (Number.isNaN(ms) || !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}/.test(value)) {\n throw new Error(\n `--at must be a valid ISO 8601 datetime, e.g. 2026-06-30T14:00:00Z (received \"${value}\").`,\n )\n }\n // A past time means the post would publish immediately on submit — almost never intended,\n // and irreversible for an instant publish. Reject it here, before any create/schedule call.\n if (ms <= Date.now()) {\n throw new Error(\n `--at must be in the future (received \"${value}\", which is in the past). ` +\n `A past schedule time publishes immediately.`,\n )\n }\n return value\n}\n\nfunction validateCanonicalMedia(items: MediaInput[]): void {\n for (const item of items) {\n if (!item || typeof item !== 'object' || typeof item.url !== 'string' || !['image', 'video', 'gif'].includes(item.type)) throw new Error('Media items require a URL and supported type')\n let url: URL\n try { url = new URL(item.url) } catch { throw new Error('Media URL must use HTTPS') }\n if (url.protocol !== 'https:' || url.username || url.password) throw new Error('Media URL must use credential-free HTTPS')\n if (item.altText !== undefined && typeof item.altText !== 'string') throw new Error('Media altText must be a string')\n }\n}\n\n/** One post's inputs — same field names as `posts create` opts, brand already resolved. */\nexport interface PostFields {\n brandSlug: string\n text: string\n platforms: string\n at?: string\n thread?: string[]\n media?: string[] | MediaInput[]\n altText?: string[]\n platformText?: string[]\n platformMedia?: string[] | Partial<Record<Platform, MediaInput[]>>\n ytTitle?: string\n ytDescription?: string\n ytTags?: string\n ytPrivacy?: string\n ytCategory?: string\n ytMadeForKids?: boolean\n igReel?: boolean\n igShareToFeed?: boolean\n igCoverUrl?: string\n igThumbOffsetMs?: string\n igCollaborators?: string\n threadsReplyTo?: string\n threadsReplyControl?: string\n facebookFormat?: string\n facebookLink?: string\n account?: string[]\n}\n\nexport interface BuildOptions {\n isTty: boolean\n /** When true: validate + resolve accounts, then return the request body — no upload, no POST. */\n dryRun?: boolean\n /** Human-facing hints sink (fan-out count); defaults to stderr inside resolveTargetAccounts. */\n emit?: (message: string) => void\n /** Called after account resolution, before any upload/POST — used to start the spinner (M3). */\n onBeforeNetwork?: () => void\n}\n\n/**\n * Validates one post's inputs, resolves target accounts, then either creates it\n * (uploading media first) or — in dry-run — returns the resolved request body with\n * media left as local paths. Shared by `posts create` (single) and `--from` (bulk).\n */\nexport async function buildAndCreatePost(\n client: Autoposting,\n fields: PostFields,\n opts: BuildOptions,\n): Promise<unknown> {\n // ── Pure validation pass (synchronous/disk-only) — runs before any network call ──\n const platforms = parsePlatforms(fields.platforms)\n const scheduledAt = fields.at ? validateScheduledAt(fields.at) : undefined\n\n const sharedMedia = fields.media ?? []\n if (!Array.isArray(sharedMedia)) throw new Error('media must be an array')\n const localMedia = sharedMedia.every(item => typeof item === 'string') ? sharedMedia as string[] : []\n const sharedCanonicalMedia = localMedia.length || !sharedMedia.length ? [] : sharedMedia as MediaInput[]\n validateCanonicalMedia(sharedCanonicalMedia)\n if (localMedia.length) {\n validateMediaCount(localMedia)\n validateMediaPaths(localMedia)\n validateMediaExtensions(localMedia)\n }\n\n const platformTexts =\n fields.platformText && fields.platformText.length > 0\n ? parsePairs('--platform-text', fields.platformText)\n : undefined\n\n const suppliedMedia = fields.platformMedia\n const canonicalMedia: Partial<Record<Platform, MediaInput[]>> = {}\n if (suppliedMedia !== undefined && !Array.isArray(suppliedMedia)) {\n if (!suppliedMedia || typeof suppliedMedia !== 'object') throw new Error('platformMedia must be an object or local path flags')\n for (const [platform, items] of Object.entries(suppliedMedia)) {\n if (!VALID_PLATFORMS.includes(platform as Platform) || !Array.isArray(items)) throw new Error('platformMedia requires supported platforms and media arrays')\n validateCanonicalMedia(items)\n canonicalMedia[platform as Platform] = items\n }\n }\n const platformMediaPaths =\n Array.isArray(suppliedMedia) && suppliedMedia.length > 0\n ? parsePlatformMediaPairs('--platform-media', suppliedMedia)\n : {}\n for (const paths of Object.values(platformMediaPaths)) {\n validateMediaPaths(paths)\n validateMediaExtensions(paths)\n }\n\n let facebookOptions: FacebookOptions | undefined\n if (platforms.includes('facebook')) {\n const format = fields.facebookFormat\n if (!format || !['text', 'link', 'photo', 'multi-photo', 'video', 'reel'].includes(format)) {\n throw new Error('--facebook-format must be text, link, photo, multi-photo, video or reel')\n }\n const paths = canonicalMedia.facebook ?? platformMediaPaths.facebook ?? fields.media ?? []\n const images = paths.every(item => typeof item === 'string' ? extToMime(item).startsWith('image/') : item.type === 'image')\n const videos = paths.every(item => typeof item === 'string' ? extToMime(item).startsWith('video/') : item.type === 'video')\n if ((format === 'text' || format === 'link') && paths.length ||\n format === 'photo' && (paths.length !== 1 || !images) ||\n format === 'multi-photo' && (paths.length < 2 || !images) ||\n (format === 'video' || format === 'reel') && (paths.length !== 1 || !videos)) {\n throw new Error('Facebook attachments do not match --facebook-format')\n }\n if (format === 'text' && !(platformTexts?.facebook ?? fields.text).trim()) throw new Error('Facebook text format requires a caption')\n if (format === 'link') {\n let link: URL\n try { link = new URL(fields.facebookLink ?? '') } catch { throw new Error('--facebook-link must be a public HTTPS URL') }\n if (link.protocol !== 'https:' || link.username || link.password) throw new Error('--facebook-link must be a public HTTPS URL')\n }\n facebookOptions = { format: format as FacebookOptions['format'], ...(format === 'link' ? { link: fields.facebookLink } : {}) }\n }\n\n const altTexts = alignAltText(localMedia, fields.altText ?? [])\n\n const youtubeOptions = buildYoutubeOptions({\n ytTitle: fields.ytTitle,\n ytDescription: fields.ytDescription,\n ytTags: fields.ytTags,\n ytPrivacy: fields.ytPrivacy,\n ytCategory: fields.ytCategory,\n ytMadeForKids: fields.ytMadeForKids,\n })\n const instagramOptions = buildInstagramOptions({\n igReel: fields.igReel,\n igShareToFeed: fields.igShareToFeed,\n igCoverUrl: fields.igCoverUrl,\n igThumbOffsetMs: fields.igThumbOffsetMs,\n igCollaborators: fields.igCollaborators,\n })\n const threadsOptions = buildThreadsOptions({\n threadsReplyTo: fields.threadsReplyTo,\n threadsReplyControl: fields.threadsReplyControl,\n })\n\n // ── Account resolution (network: brands.authStatus + optional picker) ──\n const targetAccountIds = await resolveTargetAccounts({\n brandSlug: fields.brandSlug,\n platforms,\n accountFlags: fields.account ?? [],\n client,\n isTty: opts.isTty,\n emit: opts.emit,\n })\n\n const common = {\n brandSlug: fields.brandSlug,\n text: fields.text,\n platforms,\n ...(scheduledAt ? { scheduledAt } : {}),\n ...(fields.thread && fields.thread.length > 0 ? { thread: fields.thread } : {}),\n ...(platformTexts && Object.keys(platformTexts).length > 0 ? { platformTexts } : {}),\n ...(Object.keys(targetAccountIds).length > 0 ? { targetAccountIds } : {}),\n ...(instagramOptions ? { instagramOptions } : {}),\n ...(threadsOptions ? { threadsOptions } : {}),\n ...(youtubeOptions ? { youtubeOptions } : {}),\n ...(facebookOptions ? { facebookOptions } : {}),\n source: 'cli' as const,\n }\n\n if (opts.dryRun) {\n // Show the resolved request with media as LOCAL paths — nothing uploaded, nothing POSTed.\n return {\n dryRun: true,\n request: {\n ...common,\n ...(fields.media && fields.media.length > 0\n ? {\n media: sharedCanonicalMedia.length ? sharedCanonicalMedia : localMedia.map((path, i) => ({\n path,\n ...(altTexts[i] ? { altText: altTexts[i] } : {}),\n })),\n }\n : {}),\n ...(Object.keys(platformMediaPaths).length + Object.keys(canonicalMedia).length > 0 ? { platformMedia: { ...canonicalMedia, ...platformMediaPaths } } : {}),\n },\n }\n }\n\n opts.onBeforeNetwork?.()\n\n // Upload global media.\n const mediaInputs: MediaInput[] = [...sharedCanonicalMedia]\n for (let i = 0; i < localMedia.length; i++) {\n const filePath = localMedia[i]!\n const data = await fs.readFile(filePath)\n const filename = nodePath.basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(data),\n filename,\n contentType: extToMime(filename),\n })\n mediaInputs.push({\n url: uploaded.url,\n type: uploaded.type,\n ...(altTexts[i] ? { altText: altTexts[i] } : {}),\n })\n }\n\n // Upload per-platform media.\n const platformMediaResult: Partial<Record<Platform, MediaInput[]>> = { ...canonicalMedia }\n for (const [p, paths] of Object.entries(platformMediaPaths) as [Platform, string[]][]) {\n const uploads: MediaInput[] = []\n for (const filePath of paths) {\n const data = await fs.readFile(filePath)\n const filename = nodePath.basename(filePath)\n const uploaded = await client.media.upload({\n data: new Uint8Array(data),\n filename,\n contentType: extToMime(filename),\n })\n uploads.push({ url: uploaded.url, type: uploaded.type })\n }\n platformMediaResult[p] = uploads\n }\n\n return client.posts.create({\n ...common,\n ...(mediaInputs.length > 0 ? { media: mediaInputs } : {}),\n ...(Object.keys(platformMediaResult).length > 0 ? { platformMedia: platformMediaResult } : {}),\n })\n}\n","import type { Autoposting, Platform, PlatformConnection } from '@autoposting.ai/sdk'\nimport { getDefaultAccount } from '../auth/config-store.js'\n\n// PlatformConnection v0.3.3 already has platformUserId, platformAccountType, profileImageUrl.\ntype AccountEntry = PlatformConnection\n\nconst VALID_PLATFORMS: readonly Platform[] = ['x', 'linkedin', 'instagram', 'threads', 'youtube', 'facebook']\n\n// Fan-out (=all) larger than this prompts for confirmation on a TTY (M5).\nconst FANOUT_CONFIRM_THRESHOLD = 5\n// At/above this many accounts the picker pages instead of dumping the whole list.\nconst PAGED_PICKER_THRESHOLD = 8\n\nconst isAll = (v: string): boolean => v === 'all' || v === '*'\n\n/**\n * Whether to interactively confirm a fan-out. Only an explicit `--account p=all`\n * over the threshold on a real TTY prompts — a saved default is a standing opt-in\n * and a non-TTY run can't prompt (it proceeds with the count printed).\n */\nexport function needsFanoutConfirm(count: number, isTty: boolean, explicit: boolean): boolean {\n return isTty && explicit && count > FANOUT_CONFIRM_THRESHOLD\n}\n\n/**\n * Resolves --account p=handle|id flags + interactive picker into targetAccountIds.\n *\n * Logic per targeted platform (an explicit --account flag wins, else a saved\n * default for this brand+platform, else the picker/throw):\n * - value is `all`/`*` → fan out to every connected account (print count; an\n * explicit fan-out over the threshold confirms on a TTY)\n * - value is a handle/id → resolve → push platformUserId (unknown → throw)\n * - ≥2 connected accounts, TTY → checkbox multiselect via @inquirer/prompts\n * - ≥2 connected accounts, non-TTY → throw with list + usage hint\n * - Facebook requires explicit selection even with one Page; no connected Pages fail.\n * - Other platforms with 0 or 1 account omit the platform (existing backend default)\n */\nexport async function resolveTargetAccounts({\n brandSlug,\n platforms,\n accountFlags,\n client,\n isTty,\n emit = (m) => process.stderr.write(`${m}\\n`),\n}: {\n brandSlug: string\n platforms: Platform[]\n accountFlags: string[]\n client: Autoposting\n isTty: boolean\n // Human-facing hints (fan-out count, etc.) — stderr by default so stdout stays\n // clean for JSON consumers; printed in every mode, including non-TTY.\n emit?: (message: string) => void\n}): Promise<Partial<Record<Platform, string[]>>> {\n // Validate flag format BEFORE any network call (fast fail on bad input).\n const accountMap: Partial<Record<Platform, string>> = {}\n for (const flag of accountFlags) {\n const eqIdx = flag.indexOf('=')\n if (eqIdx < 1) {\n throw Object.assign(\n new Error(`--account: expected \"platform=handle|id\" format, got \"${flag}\"`),\n { exitCode: 1 },\n )\n }\n const p = flag.slice(0, eqIdx).trim()\n if (!VALID_PLATFORMS.includes(p as Platform)) {\n throw Object.assign(\n new Error(`--account: unknown platform \"${p}\". Valid: ${VALID_PLATFORMS.join(', ')}`),\n { exitCode: 1 },\n )\n }\n accountMap[p as Platform] = flag.slice(eqIdx + 1).trim()\n }\n\n // If no --account flags and platforms all would get 0-1 connections, skip the API call\n // only if we know there's nothing to resolve. We can't know without fetching, so always fetch.\n const connections = (await client.brands.authStatus(brandSlug)) as AccountEntry[]\n\n // Group connected accounts by platform.\n const byPlatform: Partial<Record<Platform, AccountEntry[]>> = {}\n for (const conn of connections) {\n if (!conn.connected) continue\n const p = conn.platform as Platform\n if (!byPlatform[p]) byPlatform[p] = []\n byPlatform[p]!.push(conn)\n }\n\n const result: Partial<Record<Platform, string[]>> = {}\n\n for (const platform of platforms) {\n const accounts = byPlatform[platform] ?? []\n // An explicit --account flag wins; otherwise fall back to a saved default.\n const flagValue = accountMap[platform]\n const explicit = flagValue !== undefined\n const specifiedValue = flagValue ?? getDefaultAccount(brandSlug, platform) ?? undefined\n\n if (specifiedValue !== undefined && isAll(specifiedValue)) {\n // Fan out to every connected account for this platform.\n const ids = accounts\n .map((a) => a.platformUserId)\n .filter((id): id is string => Boolean(id))\n emit(`${platform}: posting to all ${ids.length} connected account(s).`)\n if (needsFanoutConfirm(ids.length, isTty, explicit)) {\n // ponytail: lazy import keeps @inquirer/prompts out of non-TTY/test paths\n const { confirm } = await import('@inquirer/prompts')\n const ok = await confirm({\n message: `Post to all ${ids.length} ${platform} accounts?`,\n default: false,\n })\n if (!ok) {\n throw Object.assign(new Error('Aborted: fan-out not confirmed.'), { exitCode: 1 })\n }\n }\n if (ids.length > 0) result[platform] = ids\n } else if (specifiedValue !== undefined) {\n const values = platform === 'facebook' ? specifiedValue.split(',').map(value => value.trim()) : [specifiedValue]\n for (const value of values) {\n if (!value) throw Object.assign(new Error('--account: Page selection must not contain empty members.'), { exitCode: 1 })\n // Resolve handle (strip leading @, case-insensitive) or platformUserId.\n const normalized = value.startsWith('@') ? value.slice(1) : value\n const match = accounts.find(\n (a) =>\n a.platformUsername?.toLowerCase() === normalized.toLowerCase() ||\n a.platformUserId === value,\n )\n if (!match?.platformUserId) {\n const valid = accounts\n .map((a) => ` @${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`)\n .join('\\n')\n throw Object.assign(\n new Error(\n `--account: unknown ${platform} account \"${value}\".\\n` +\n `Connected accounts:\\n${valid || ' (none)'}`,\n ),\n { exitCode: 1 },\n )\n }\n if (!result[platform]) result[platform] = []\n if (!result[platform]!.includes(match.platformUserId)) result[platform]!.push(match.platformUserId)\n }\n } else if (accounts.length >= 2 || (platform === 'facebook' && accounts.length > 0)) {\n if (isTty) {\n // ponytail: lazy import keeps @inquirer/prompts out of non-TTY/test paths\n const { checkbox } = await import('@inquirer/prompts')\n const choices = accounts.map((a) => ({\n name: `@${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`,\n value: a.platformUserId ?? '',\n }))\n const selected: string[] = await checkbox({\n message: `Multiple ${platform} accounts connected — select which to post to:`,\n choices,\n // ponytail: paged scroll for long lists (23 LinkedIn orgs). @inquirer's\n // checkbox has no type-to-filter; if many-account users need it, swap in\n // a search-capable multiselect dep — or save a default to skip the picker.\n pageSize: accounts.length >= PAGED_PICKER_THRESHOLD ? 12 : 7,\n loop: false,\n })\n const valid = selected.filter(Boolean)\n if (valid.length > 0) result[platform] = valid\n } else {\n const list = accounts\n .map((a) => ` @${a.platformUsername ?? '?'} (${a.platformUserId ?? '?'})`)\n .join('\\n')\n throw Object.assign(\n new Error(\n `Multiple ${platform} accounts connected but no --account specified (non-interactive mode).\\n` +\n `Connected accounts:\\n${list}\\n` +\n `Pass --account ${platform}=<handle|id> to select.`,\n ),\n { exitCode: 1 },\n )\n }\n }\n if (platform === 'facebook' && !result.facebook?.length) {\n throw Object.assign(new Error('Facebook requires at least one explicitly selected connected Page. Pass --account facebook=<handle|id>.'), { exitCode: 1 })\n }\n // Other platforms retain their existing implicit single-account behavior.\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport type { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveBrand } from '../auth/config-store.js'\nimport { buildAndCreatePost, type PostFields } from './post-create.js'\n\nexport interface BulkRecordResult {\n index: number\n status: 'created' | 'failed'\n id: string\n text: string\n error: string\n}\n\n/**\n * Parse a bulk input file into an array of raw post rows. JSON (an array of\n * post objects) is lossless — array fields like `media`/`thread` pass straight\n * through. CSV is for flat rows; see parseCsvRows for its ceiling.\n */\nexport function parseBulkFile(filePath: string): Record<string, unknown>[] {\n const raw = fs.readFileSync(filePath, 'utf8')\n const isJson = filePath.toLowerCase().endsWith('.json') || raw.trimStart().startsWith('[')\n const rows = isJson ? parseJsonRows(raw) : parseCsvRows(raw)\n if (rows.length === 0) {\n throw new Error(`No records found in ${filePath}.`)\n }\n return rows\n}\n\nfunction parseJsonRows(raw: string): Record<string, unknown>[] {\n let data: unknown\n try {\n data = JSON.parse(raw)\n } catch (e) {\n throw new Error(`Invalid JSON bulk input: ${(e as Error).message}`)\n }\n if (!Array.isArray(data)) {\n throw new Error('JSON bulk input must be an array of post objects.')\n }\n return data as Record<string, unknown>[]\n}\n\n// ponytail: minimal CSV — comma separator, double-quote escaping (\"\" = literal\n// quote), no newlines inside quoted cells. Multi-value fields (thread, media,\n// account, alt-text) aren't expressible in flat CSV — use JSON for those.\nfunction parseCsvRows(raw: string): Record<string, unknown>[] {\n const lines = raw.split(/\\r?\\n/).filter((l) => l.trim().length > 0)\n if (lines.length === 0) return []\n const headers = splitCsvLine(lines[0])\n return lines.slice(1).map((line) => {\n const cells = splitCsvLine(line)\n const row: Record<string, unknown> = {}\n headers.forEach((h, i) => {\n if (cells[i] !== undefined && cells[i] !== '') row[h] = cells[i]\n })\n return row\n })\n}\n\nfunction splitCsvLine(line: string): string[] {\n const out: string[] = []\n let cur = ''\n let inQuotes = false\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (inQuotes) {\n if (c === '\"' && line[i + 1] === '\"') {\n cur += '\"'\n i++\n } else if (c === '\"') {\n inQuotes = false\n } else {\n cur += c\n }\n } else if (c === '\"') {\n inQuotes = true\n } else if (c === ',') {\n out.push(cur)\n cur = ''\n } else {\n cur += c\n }\n }\n out.push(cur)\n return out.map((s) => s.trim())\n}\n\n/** Build PostFields from one raw row, falling back to the CLI/context brand. */\nfunction rowToFields(row: Record<string, unknown>, cliBrand?: string): PostFields {\n const platformsRaw = row.platforms\n const platforms = Array.isArray(platformsRaw) ? platformsRaw.join(',') : platformsRaw\n const brand = resolveBrand((row.brand as string) ?? (row.brandSlug as string) ?? cliBrand)\n if (!brand) {\n throw new Error('No brand: set \"brand\" in the row, pass --brand, or set a default context.')\n }\n if (typeof row.text !== 'string') throw new Error('Missing \"text\" or text is not a string.')\n if (!platforms) throw new Error('Missing \"platforms\".')\n // Array-typed fields can't be expressed in flat CSV (cells are always strings),\n // so a scalar here would misparse downstream (e.g. media.length = char count).\n // Reject with guidance instead of a confusing per-character failure.\n for (const key of ['media', 'thread', 'account', 'altText'] as const) {\n if (row[key] !== undefined && !Array.isArray(row[key])) {\n throw new Error(`\"${key}\" is multi-value — use a JSON input file with an array (CSV can't express it).`)\n }\n }\n let platformText = row.platformText as string[] | undefined\n if (row.platformTexts !== undefined) {\n if (!row.platformTexts || typeof row.platformTexts !== 'object' || Array.isArray(row.platformTexts)) throw new Error('platformTexts must map platforms to caption strings')\n const captions = Object.entries(row.platformTexts).map(([platform, text]) => {\n if (typeof text !== 'string') throw new Error('platformTexts values must be strings')\n return `${platform}=${text}`\n })\n platformText = platformText ?? captions\n }\n let facebook: { format?: string; link?: string } | undefined\n if (row.facebookOptions !== undefined) {\n if (!row.facebookOptions || typeof row.facebookOptions !== 'object' || Array.isArray(row.facebookOptions)) throw new Error('facebookOptions must be an object')\n facebook = row.facebookOptions as { format?: string; link?: string }\n if (typeof facebook.format !== 'string' || facebook.link !== undefined && typeof facebook.link !== 'string') throw new Error('facebookOptions requires a string format and optional string link')\n }\n let account = row.account as string[] | undefined\n if (row.targetAccountIds !== undefined) {\n if (!row.targetAccountIds || typeof row.targetAccountIds !== 'object' || Array.isArray(row.targetAccountIds)) throw new Error('targetAccountIds must map platforms to account ID arrays')\n const flags = Object.entries(row.targetAccountIds).map(([platform, ids]) => {\n if (!Array.isArray(ids) || ids.length === 0 || ids.some(id => typeof id !== 'string' || !id.trim() || id.includes(','))) throw new Error('targetAccountIds requires nonempty account ID arrays')\n return `${platform}=${ids.join(',')}`\n })\n account = account ?? flags\n }\n return {\n ...(row as Partial<PostFields>),\n ...(facebook ? { facebookFormat: facebook.format, facebookLink: facebook.link } : {}),\n ...(account ? { account } : {}),\n ...(platformText ? { platformText } : {}),\n brandSlug: brand,\n at: (row.at ?? row.scheduledAt) as string | undefined,\n text: String(row.text),\n platforms: String(platforms),\n }\n}\n\n/**\n * Create posts in bulk. Each row is independent — a failure is captured and the\n * loop continues — so the caller maps any failed record to a non-zero exit.\n * Runs non-interactively (no per-row account picker): a row whose platform has\n * multiple accounts and no selector fails fast and is reported.\n *\n * ponytail: no idempotency key — re-running a partially-failed batch re-creates\n * the rows that already succeeded. Split the file or de-dupe upstream to re-run.\n */\nexport async function createPostsBulk(\n client: Autoposting,\n rows: Record<string, unknown>[],\n opts: { cliBrand?: string } = {},\n): Promise<BulkRecordResult[]> {\n const results: BulkRecordResult[] = []\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!\n try {\n const fields = rowToFields(row, opts.cliBrand)\n const created = (await buildAndCreatePost(client, fields, { isTty: false })) as { id?: string }\n results.push({ index: i, status: 'created', id: created?.id ?? '', text: fields.text, error: '' })\n } catch (err) {\n results.push({\n index: i,\n status: 'failed',\n id: '',\n text: String(row.text ?? ''),\n error: (err as Error).message,\n })\n }\n }\n return results\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createKbCommand(): Command {\n const kb = new Command('kb').description('Manage knowledge bases')\n\n // ap kb list\n kb\n .command('list')\n .description('List all knowledge bases')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching knowledge bases…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.kb.list()\n spinner.stop()\n const rows = list.map((k) => ({\n id: k.id,\n name: k.name,\n docs: k.docCount ?? 0,\n createdAt: k.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'docs', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb get <id>\n kb\n .command('get <id>')\n .description('Get a knowledge base by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.kb.retrieve(id)\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb create --name <name> --description <description>\n kb\n .command('create')\n .description('Create a new knowledge base')\n .requiredOption('--name <name>', 'Knowledge base name')\n .requiredOption('--description <description>', 'Knowledge base description (20–500 characters)')\n .action(async (opts: { name: string; description: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating knowledge base…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.kb.create({ name: opts.name, description: opts.description })\n spinner.stop()\n printer.log(result)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb delete <id> [--force]\n kb\n .command('delete <id>')\n .description('Delete a knowledge base (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a knowledge base. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.kb.remove(id)\n spinner.stop()\n printer.log(`Knowledge base \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb search <id> --query <text>\n kb\n .command('search <id>')\n .description('Search a knowledge base')\n .requiredOption('--query <text>', 'Search query')\n .action(async (id: string, opts: { query: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Searching knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const res = await client.kb.search(id, opts.query)\n spinner.stop()\n const rows = res.results.map((r) => ({\n kind: r.kind,\n score: r.score != null ? r.score.toFixed(3) : '—',\n uri: r.uri ?? '—',\n content: r.content.length > 80 ? `${r.content.slice(0, 77)}…` : r.content,\n }))\n printer.table(rows, ['kind', 'score', 'uri', 'content'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb ingest <id> --url <url>\n kb\n .command('ingest <id>')\n .description('Ingest a URL into a knowledge base')\n .requiredOption('--url <url>', 'URL to ingest')\n .action(async (id: string, opts: { url: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Ingesting URL into knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const doc = await client.kb.ingestUrl(id, opts.url)\n spinner.stop()\n printer.log(doc)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap kb docs <id>\n kb\n .command('docs <id>')\n .description('List documents in a knowledge base')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching documents for knowledge base \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const docs = await client.kb.docs(id)\n spinner.stop()\n const rows = docs.map((d) => ({\n id: d.id,\n name: d.name,\n type: d.type,\n status: d.status,\n createdAt: d.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'type', 'status', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return kb\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\n// The ideas/enrich domain uses `twitter` (NOT the posts domain's `x`); backend caps at 5.\nconst VALID_IDEA_PLATFORMS = ['twitter', 'linkedin', 'instagram', 'youtube', 'threads'] as const\n\nfunction parseIdeaPlatforms(raw: string): Array<{ platform: (typeof VALID_IDEA_PLATFORMS)[number] }> {\n const parts = raw.split(',').map((p) => p.trim()).filter(Boolean)\n if (parts.length === 0) {\n throw new Error('No platforms provided. e.g. --platforms twitter,linkedin')\n }\n if (parts.length > 5) {\n throw new Error('At most 5 platforms allowed per enrichment request.')\n }\n const invalid = parts.filter((p) => !VALID_IDEA_PLATFORMS.includes(p as never))\n if (invalid.length > 0) {\n throw new Error(\n `Unsupported platform(s): ${invalid.join(', ')}. Valid: ${VALID_IDEA_PLATFORMS.join(', ')}`,\n )\n }\n return parts.map((platform) => ({ platform: platform as (typeof VALID_IDEA_PLATFORMS)[number] }))\n}\n\nexport function createIdeasCommand(): Command {\n const ideas = new Command('ideas').description('Manage content ideas')\n\n // ap ideas generate [--kb <id>] [--topic <text>] [--count <n>]\n ideas\n .command('generate')\n .description('Generate content ideas')\n .option('--kb <id>', 'Knowledge base ID to draw context from')\n .option('--topic <text>', 'Topic or theme for ideas')\n .option('--count <n>', 'Number of ideas to generate', '5')\n .action(async (opts: { kb?: string; topic?: string; count: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Generating ideas…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.ideas.generate({\n ...(opts.kb ? { kbId: opts.kb } : {}),\n ...(opts.topic ? { topic: opts.topic } : {}),\n count: parseInt(opts.count, 10),\n })\n spinner.stop()\n const rows = (result.ideas ?? []).map((i) => ({\n id: i.id ?? '—',\n platform: i.targetPlatform,\n score: i.viralityScore,\n title: i.title.length > 80 ? `${i.title.slice(0, 77)}…` : i.title,\n }))\n printer.table(rows, ['id', 'platform', 'score', 'title'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap ideas list\n ideas\n .command('list')\n .description('List all ideas')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching ideas…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.ideas.list()\n spinner.stop()\n const rows = list.items.map((i) => ({\n id: i.id,\n topic: i.topic || '—',\n platform: i.targetPlatform,\n score: i.viralityScore,\n status: i.status,\n title: i.title.length > 60 ? `${i.title.slice(0, 57)}…` : i.title,\n }))\n printer.table(rows, ['id', 'topic', 'platform', 'score', 'status', 'title'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap ideas enrich --title <t> --hook <h> --angle <a> --platforms <list> [--kb <id>]\n // Backend enriches the idea object (not an id) across 1..5 platforms; async → job id.\n ideas\n .command('enrich')\n .description('Enrich an idea into platform-ready drafts (async; returns a job ID)')\n .requiredOption('--title <text>', 'Idea title')\n .requiredOption('--hook <text>', 'Idea hook')\n .requiredOption('--angle <text>', 'Idea angle')\n .requiredOption('--platforms <list>', `Comma-separated platforms (${VALID_IDEA_PLATFORMS.join(',')})`)\n .option('--kb <id>', 'Knowledge base ID for additional context')\n .action(\n async (\n opts: { title: string; hook: string; angle: string; platforms: string; kb?: string },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Queuing enrichment…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const { jobId } = await client.ideas.enrich({\n idea: { title: opts.title, hook: opts.hook, angle: opts.angle },\n platforms: parseIdeaPlatforms(opts.platforms),\n ...(opts.kb ? { kbId: opts.kb } : {}),\n })\n spinner.stop()\n printer.log(`Enrichment queued. Job ID: ${jobId}`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap ideas delete <id> [--force]\n ideas\n .command('delete <id>')\n .description('Delete an idea (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete an idea. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting idea \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.ideas.remove(id)\n spinner.stop()\n printer.log(`Idea \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return ideas\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createUsageCommand(): Command {\n const usage = new Command('usage').description('View usage statistics')\n\n // ap usage summary\n usage\n .command('summary')\n .description('Show usage summary for the current period')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching usage summary…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const summary = await client.usage.summary()\n spinner.stop()\n if (!printer.isTty()) {\n printer.log(summary)\n return\n }\n printer.log(`Period: ${summary.range.from.slice(0, 10)} → ${summary.range.to.slice(0, 10)}`)\n printer.table(\n [\n {\n posts: summary.posts.total,\n published: summary.posts.published,\n agents: summary.agents.total,\n 'active agents': summary.agents.active,\n 'ai cost (usd)': summary.ai.totalCostUsd,\n 'ai requests': summary.ai.requests,\n },\n ],\n ['posts', 'published', 'agents', 'active agents', 'ai cost (usd)', 'ai requests'],\n )\n const sourceRows = Object.entries(summary.posts.bySource).map(([source, count]) => ({\n source,\n posts: count,\n }))\n printer.table(sourceRows, ['source', 'posts'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return usage\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createWebhooksCommand(): Command {\n const webhooks = new Command('webhooks').description('Manage webhooks')\n\n // ap webhooks list\n webhooks\n .command('list')\n .description('List all webhooks')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching webhooks…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const list = await client.webhooks.list()\n spinner.stop()\n const rows = list.map((w) => ({\n id: w.id,\n url: w.url,\n events: w.events.join(', '),\n active: w.active ? 'yes' : 'no',\n createdAt: w.createdAt,\n }))\n printer.table(rows, ['id', 'url', 'events', 'active', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks get <id>\n webhooks\n .command('get <id>')\n .description('Get a webhook by ID')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Fetching webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.retrieve(id)\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks create --url <url> --events <post.published,post.failed,...>\n webhooks\n .command('create')\n .description('Create a new webhook')\n .requiredOption('--url <url>', 'Endpoint URL to receive events')\n .requiredOption('--events <list>', 'Comma-separated event types (e.g. post.published,post.failed)')\n .option('--secret <secret>', 'Signing secret for HMAC verification')\n .action(\n async (opts: { url: string; events: string; secret?: string }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Creating webhook…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.create({\n url: opts.url,\n events: opts.events.split(',').map((e) => e.trim()),\n ...(opts.secret ? { secret: opts.secret } : {}),\n })\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap webhooks update <id> [--url <url>] [--events <events>] [--active]\n webhooks\n .command('update <id>')\n .description('Update a webhook')\n .option('--url <url>', 'New endpoint URL')\n .option('--events <list>', 'New comma-separated event types')\n .option('--active', 'Set webhook as active')\n .option('--no-active', 'Set webhook as inactive')\n .action(\n async (\n id: string,\n opts: { url?: string; events?: string; active?: boolean },\n cmd: Command,\n ) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Updating webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const webhook = await client.webhooks.update(id, {\n ...(opts.url ? { url: opts.url } : {}),\n ...(opts.events ? { events: opts.events.split(',').map((e) => e.trim()) } : {}),\n ...(opts.active !== undefined ? { active: opts.active } : {}),\n })\n spinner.stop()\n printer.log(webhook)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n },\n )\n\n // ap webhooks delete <id> --force\n webhooks\n .command('delete <id>')\n .description('Delete a webhook (requires --force)')\n .option('--force', 'Confirm deletion without interactive prompt')\n .action(async (id: string, opts: { force?: boolean }, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n if (!opts.force) {\n printer.error('--force is required to delete a webhook. Pass --force to confirm.')\n process.exit(1)\n }\n const spinner = printer.spinner(`Deleting webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.webhooks.remove(id)\n spinner.stop()\n printer.log(`Webhook \"${id}\" deleted.`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap webhooks test <id>\n webhooks\n .command('test <id>')\n .description('Send a test event to a webhook')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Sending test event to webhook \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n const client = new Autoposting({ apiKey: cred.apiKey })\n const result = await client.webhooks.test(id)\n spinner.stop()\n printer.log(\n `Test event sent to webhook \"${id}\" — delivered: ${result.delivered ? 'yes' : 'no'} (HTTP ${result.httpStatus}).`,\n )\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return webhooks\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { exitCodeFromError } from '../output/exit-codes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\nfunction resolveExitCode(err: unknown): number {\n const attached = (err as { exitCode?: number }).exitCode\n if (typeof attached === 'number') return attached\n return exitCodeFromError(err)\n}\n\nexport function createWorkspacesCommand(): Command {\n const workspaces = new Command('workspaces').description('Manage workspaces')\n\n // ap workspaces list\n workspaces\n .command('list')\n .description('List all workspaces')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner('Fetching workspaces…')\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n // CLI auth is always an API key, so the SDK's default authSource ('api-key')\n // makes workspaces.list() fail fast with guidance instead of a bare 401.\n const client = new Autoposting({ apiKey: cred.apiKey })\n const res = await client.workspaces.list()\n spinner.stop()\n const rows = res.organizations.map((w) => ({\n id: w.id,\n name: w.name,\n slug: w.slug,\n active: w.id === res.activeOrgId ? 'yes' : 'no',\n createdAt: w.createdAt,\n }))\n printer.table(rows, ['id', 'name', 'slug', 'active', 'createdAt'])\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n // ap workspaces switch <id>\n workspaces\n .command('switch <id>')\n .description('Switch the active workspace (session auth only)')\n .action(async (id: string, _opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n const spinner = printer.spinner(`Switching to workspace \"${id}\"…`)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n // CLI auth is always an API key; the SDK's default authSource ('api-key')\n // makes switchWorkspace() reject with guidance (switching needs session auth).\n const client = new Autoposting({ apiKey: cred.apiKey })\n await client.workspaces.switchWorkspace(id)\n spinner.stop()\n printer.log(`Switched to workspace \"${id}\".`)\n } catch (err) {\n spinner.fail()\n printer.error(err as Error)\n process.exit(resolveExitCode(err))\n }\n })\n\n return workspaces\n}\n","import { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { getCredentialsPath } from '../auth/credential-store.js'\nimport fs from 'node:fs'\n\nconst API_HEALTH_URL = 'https://app.autoposting.ai/api-proxy/health'\n\ntype CheckResult = {\n name: string\n status: 'pass' | 'fail' | 'warn'\n value: string\n}\n\nasync function runChecks(): Promise<CheckResult[]> {\n const results: CheckResult[] = []\n\n // CLI Version\n results.push({ name: 'CLI Version', status: 'pass', value: VERSION })\n\n // Node.js\n const nodeVersion = process.version\n const nodeMajor = parseInt(nodeVersion.slice(1), 10)\n results.push({\n name: 'Node.js',\n status: nodeMajor >= 20 ? 'pass' : 'fail',\n value: nodeVersion,\n })\n\n // Auth (local credential presence only — server validation happens in `whoami`)\n try {\n resolveAuth()\n results.push({ name: 'Auth', status: 'pass', value: 'credentials configured' })\n } catch {\n results.push({ name: 'Auth', status: 'fail', value: 'not configured' })\n }\n\n // Credentials file permissions\n const credPath = getCredentialsPath()\n try {\n const stat = fs.statSync(credPath)\n const mode = stat.mode & 0o777\n const isSecure = mode === 0o600\n results.push({\n name: 'Credentials',\n status: isSecure ? 'pass' : 'warn',\n value: isSecure\n ? `${credPath} (0600)`\n : `${credPath} (mode ${mode.toString(8)} — expected 0600)`,\n })\n } catch {\n results.push({\n name: 'Credentials',\n status: 'warn',\n value: 'no credentials file found',\n })\n }\n\n // API health\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 5000)\n const res = await fetch(API_HEALTH_URL, { signal: controller.signal })\n clearTimeout(timeout)\n results.push({\n name: 'API',\n status: res.ok ? 'pass' : 'fail',\n value: `HTTP ${res.status}`,\n })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n results.push({ name: 'API', status: 'fail', value: `unreachable: ${msg}` })\n }\n\n return results\n}\n\nexport function createDoctorCommand(): Command {\n const cmd = new Command('doctor')\n .description('Run diagnostic checks on your CLI setup')\n .option('--json', 'Output results as JSON')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{ json?: boolean }>()\n const results = await runChecks()\n\n if (globals.json) {\n console.log(JSON.stringify(results, null, 2))\n } else {\n for (const r of results) {\n const icon =\n r.status === 'pass' ? '✓' : r.status === 'warn' ? '!' : '✗'\n const label =\n r.status === 'pass' ? 'pass' : r.status === 'warn' ? 'warn' : 'FAIL'\n console.log(` ${icon} ${r.name.padEnd(16)} [${label}] ${r.value}`)\n }\n }\n\n const anyFail = results.some((r) => r.status === 'fail')\n if (anyFail) process.exit(1)\n })\n\n return cmd\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport type { AuthProfile } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { readCredentials } from '../auth/credential-store.js'\nimport { EXIT_CODES, exitCodeFromError } from '../output/exit-codes.js'\n\nexport function createWhoamiCommand(): Command {\n return new Command('whoami')\n .description('Show the current identity and validate the key against the server')\n .action(async (_opts: Record<string, unknown>, cmd: Command) => {\n const globals = cmd.optsWithGlobals<{ apiKey?: string; json?: boolean }>()\n\n let cred: ReturnType<typeof resolveAuth>\n try {\n cred = resolveAuth({ apiKey: globals.apiKey })\n } catch (err) {\n console.error(`Error: ${(err as Error).message}`)\n process.exitCode = exitCodeFromError(err)\n return\n }\n\n const masked = `${cred.apiKey.slice(0, 8)}${'*'.repeat(Math.max(0, cred.apiKey.length - 8))}`\n\n // Validate the key AND resolve the server-side identity in one call. /auth/profile runs\n // the shared authenticate middleware (accepts the Bearer API key), so a valid key returns\n // 200 + identity (orgId, authType) and an invalid/revoked one returns 401. A network/\n // transport failure must NOT fail whoami: degrade to \"unverified\" so it still works\n // offline; only a definitive rejection (401/403) exits non-zero.\n let validity: 'valid' | 'rejected' | 'unverified' = 'unverified'\n let identity: AuthProfile | undefined\n try {\n const client = new Autoposting({ apiKey: cred.apiKey, maxRetries: 0 })\n identity = await client.getProfile()\n validity = 'valid'\n } catch (err) {\n const code = exitCodeFromError(err)\n validity =\n code === EXIT_CODES.AUTH_ERROR || code === EXIT_CODES.SCOPE_ERROR\n ? 'rejected'\n : 'unverified'\n }\n\n const exitCode = validity === 'rejected' ? EXIT_CODES.AUTH_ERROR : 0\n\n const creds = cred.source === 'stored' ? readCredentials() : undefined\n const profileName = creds?.activeProfile ?? 'unknown'\n const email = creds?.profiles[profileName]?.email\n\n if (globals.json) {\n const out: Record<string, unknown> = {\n source: cred.source,\n apiKey: masked,\n valid: validity === 'valid',\n validity,\n }\n if (identity?.orgId) {\n out.orgId = identity.orgId\n out.authType = identity.authType\n if (identity.email) out.email = identity.email\n }\n if (cred.source === 'stored') {\n out.profile = profileName\n if (email) out.email = email\n }\n console.log(JSON.stringify(out, null, 2))\n // Set exitCode (not process.exit) so a piped --json stream flushes fully before exit.\n process.exitCode = exitCode\n return\n }\n\n console.log(`Source: ${cred.source}`)\n if (cred.source === 'stored') {\n console.log(`Profile: ${profileName}`)\n if (email) console.log(`Email: ${email}`)\n }\n if (identity?.orgId) {\n console.log(`Org: ${identity.orgId}`)\n console.log(`Auth: ${identity.authType}`)\n }\n const tag =\n validity === 'valid'\n ? '✓ valid'\n : validity === 'rejected'\n ? '✗ rejected by server'\n : '⚠ unverified (could not reach server)'\n console.log(`API key: ${masked} ${tag}`)\n process.exitCode = exitCode\n })\n}\n","import { Command } from 'commander'\nimport open from 'open'\n\nconst URLS: Record<string, string> = {\n '': 'https://app.autoposting.ai',\n posts: 'https://app.autoposting.ai/posts',\n brands: 'https://app.autoposting.ai/brands',\n agents: 'https://app.autoposting.ai/agents',\n settings: 'https://app.autoposting.ai/settings',\n billing: 'https://app.autoposting.ai/settings/billing',\n}\n\nconst VALID_SECTIONS = Object.keys(URLS).filter((k) => k !== '')\n\nexport function createOpenCommand(): Command {\n return new Command('open')\n .description(`Open the Autoposting dashboard in your browser. Sections: ${VALID_SECTIONS.join(', ')}`)\n .argument('[section]', `Dashboard section to open (${VALID_SECTIONS.join('|')})`, '')\n .option('--no-browser', 'Print URL only, do not open browser')\n .action(async (section: string, opts: { browser: boolean }) => {\n const key = section ?? ''\n if (!(key in URLS)) {\n console.error(`Error: unknown section \"${key}\". Valid sections: ${VALID_SECTIONS.join(', ')}`)\n process.exit(1)\n }\n\n const url = URLS[key]\n\n if (!opts.browser) {\n console.log(url)\n return\n }\n\n console.log(`Opening ${url}`)\n try {\n await open(url)\n } catch (err) {\n console.error(`Error: failed to open browser — ${(err as Error).message}`)\n console.log(`Visit manually: ${url}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { VERSION } from '@autoposting.ai/sdk'\nimport { execSync } from 'node:child_process'\n\nconst REGISTRY_URL = 'https://registry.npmjs.org/@autoposting.ai%2fcli/latest'\n\nexport function createUpdateCommand(): Command {\n return new Command('update')\n .description(\n 'Check for a newer version of the CLI and optionally install it',\n )\n .option('--yes', 'Install the latest version without prompting')\n .action(async (opts: { yes?: boolean }) => {\n let latest: string\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 8000)\n const res = await fetch(REGISTRY_URL, { signal: controller.signal })\n clearTimeout(timeout)\n if (!res.ok) {\n console.error(`Error: registry returned HTTP ${res.status}`)\n process.exit(1)\n }\n const data = (await res.json()) as { version: string }\n latest = data.version\n } catch (err) {\n console.error(\n `Error: could not reach npm registry — ${(err as Error).message}`,\n )\n process.exit(1)\n }\n\n if (latest === VERSION) {\n console.log(`You are already on the latest version (${VERSION}).`)\n return\n }\n\n console.log(`Current version: ${VERSION}`)\n console.log(`Latest version: ${latest}`)\n\n if (!opts.yes) {\n console.log(`Run \\`ap update --yes\\` to install v${latest}.`)\n return\n }\n\n console.log(`Installing @autoposting.ai/cli@${latest}…`)\n try {\n execSync(`npm install -g @autoposting.ai/cli@${latest}`, {\n stdio: 'inherit',\n })\n console.log(`Updated to v${latest}.`)\n } catch (err) {\n console.error(`Error: install failed — ${(err as Error).message}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\n\nconst ALL_COMMANDS = [\n 'posts',\n 'brands',\n 'accounts',\n 'agents',\n 'kb',\n 'ideas',\n 'clips',\n 'carousels',\n 'webhooks',\n 'billing',\n 'usage',\n 'workspaces',\n 'auth',\n 'doctor',\n 'whoami',\n 'open',\n 'update',\n 'completion',\n]\n\nconst SHELLS = ['bash', 'zsh', 'fish', 'pwsh'] as const\ntype Shell = (typeof SHELLS)[number]\n\nconst TEMPLATES: Record<Shell, (cmds: string[]) => string> = {\n bash: (cmds) => `# bash completion for ap / autoposting\n# Add to ~/.bashrc or ~/.bash_profile:\n# source <(ap completion bash)\n_ap_completions() {\n local cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n local commands=\"${cmds.join(' ')}\"\n COMPREPLY=( $(compgen -W \"$commands\" -- \"$cur\") )\n}\ncomplete -F _ap_completions ap\ncomplete -F _ap_completions autoposting\n`,\n\n zsh: (cmds) => `# zsh completion for ap / autoposting\n# Add to ~/.zshrc:\n# source <(ap completion zsh)\n# Or append directly:\n# ap completion zsh >> ~/.zshrc\n_ap() {\n compadd ${cmds.join(' ')}\n}\ncompdef _ap ap autoposting\n`,\n\n fish: (cmds) => `# fish completion for ap / autoposting\n# Save to ~/.config/fish/completions/ap.fish or run:\n# ap completion fish | source\n${cmds.map((c) => `complete -c ap -f -a '${c}'`).join('\\n')}\n${cmds.map((c) => `complete -c autoposting -f -a '${c}'`).join('\\n')}\n`,\n\n pwsh: (cmds) => `# PowerShell completion for ap / autoposting\n# Add to your $PROFILE:\n# ap completion pwsh | Invoke-Expression\nRegister-ArgumentCompleter -Native -CommandName @('ap', 'autoposting') -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $commands = @(${cmds.map((c) => `'${c}'`).join(', ')})\n $commands | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n`,\n}\n\nexport function createCompletionCommand(): Command {\n return new Command('completion')\n .description(`Generate shell completion script. Shells: ${SHELLS.join(', ')}`)\n .argument('<shell>', `Shell type (${SHELLS.join('|')})`)\n .action((shell: string) => {\n if (!SHELLS.includes(shell as Shell)) {\n console.error(`Error: unsupported shell \"${shell}\". Supported: ${SHELLS.join(', ')}`)\n process.exit(1)\n }\n process.stdout.write(TEMPLATES[shell as Shell](ALL_COMMANDS))\n })\n}\n","import { Command } from 'commander'\n\nexport function createMcpCommand(): Command {\n return new Command('mcp')\n .description('Start MCP stdio server for AI agent integration')\n .action(async () => {\n const { startMcpServer } = await import('../mcp/server.js')\n await startMcpServer()\n })\n}\n","import { Command } from 'commander'\nimport { createPrinter } from '../output/printer.js'\nimport { getContextBrand, setContextBrand, unsetContextBrand } from '../auth/config-store.js'\n\ntype GlobalOpts = {\n json?: boolean\n quiet?: boolean\n format?: 'auto' | 'table' | 'json'\n jq?: string\n}\n\nexport function createConfigCommand(): Command {\n const config = new Command('config').description('Manage CLI defaults (stored in config.json)')\n\n // ap config set-context --brand <slug>\n config\n .command('set-context')\n .description('Set the default brand used when --brand is omitted')\n .requiredOption('--brand <slug>', 'Brand slug to use as the default context')\n .action((opts: { brand: string }, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n setContextBrand(opts.brand)\n printer.log({ brand: opts.brand })\n })\n\n // ap config get-context\n config\n .command('get-context')\n .description('Show the default brand context')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n const brand = getContextBrand()\n if (!brand) {\n printer.error('No brand context set. Set one with: ap config set-context --brand <slug>')\n process.exit(1)\n }\n printer.log({ brand })\n })\n\n // ap config unset-context\n config\n .command('unset-context')\n .description('Clear the default brand context')\n .action((_opts: Record<string, unknown>, cmd: Command) => {\n const printer = createPrinter(cmd.optsWithGlobals<GlobalOpts>())\n unsetContextBrand()\n printer.log({ brand: null })\n })\n\n return config\n}\n","import { Command } from 'commander'\nimport { Autoposting } from '@autoposting.ai/sdk'\nimport { resolveAuth } from '../auth/auth-manager.js'\nimport { createPrinter } from '../output/printer.js'\nimport { EXIT_CODES, exitCodeFromError } from '../output/exit-codes.js'\nimport { assertApiRoute, fetchApiRoutes } from '../lib/api-routes.js'\n\ntype GlobalOpts = {\n apiKey?: string\n json?: boolean\n quiet?: boolean\n format?: 'table' | 'json'\n}\n\ntype ApiOpts = { data?: string; field: string[]; query: string[]; list?: boolean }\n\nfunction validationError(message: string): Error {\n return Object.assign(new Error(message), { exitCode: EXIT_CODES.VALIDATION_ERROR })\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value]\n}\n\n/** `key=value` pairs; a value that parses as JSON (number, boolean, null, object) is used as such. */\nexport function parseFields(pairs: string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const pair of pairs) {\n const i = pair.indexOf('=')\n if (i < 1) throw validationError(`Expected key=value, got \"${pair}\".`)\n const raw = pair.slice(i + 1)\n let value: unknown = raw\n try {\n value = JSON.parse(raw)\n } catch {\n // keep as string\n }\n out[pair.slice(0, i)] = value\n }\n return out\n}\n\nexport function createApiCommand(): Command {\n return new Command('api')\n .description('Call any Autoposting REST route on the server allow-list, like `gh api`')\n .argument('[method]', 'GET, POST, PUT, PATCH or DELETE')\n .argument('[path]', 'Route path, e.g. /clips/abc123/jobs')\n .option('-d, --data <json>', 'JSON request body')\n .option('-f, --field <key=value>', 'Body field (repeatable)', collect, [])\n .option('-q, --query <key=value>', 'Query parameter (repeatable)', collect, [])\n .option('--list [prefix]', 'List the routes you may call')\n .action(async (method: string | undefined, path: string | undefined, opts: ApiOpts, cmd: Command) => {\n const globals = cmd.optsWithGlobals<GlobalOpts>()\n const printer = createPrinter(globals)\n try {\n const cred = resolveAuth({ apiKey: globals.apiKey })\n let body: Record<string, unknown> | undefined\n if (opts.data !== undefined) {\n try {\n body = JSON.parse(opts.data) as Record<string, unknown>\n } catch {\n throw validationError('--data is not valid JSON.')\n }\n }\n if (opts.field.length > 0) body = { ...body, ...parseFields(opts.field) }\n const query = opts.query.length > 0 ? parseFields(opts.query) : undefined\n\n const client = new Autoposting({ apiKey: cred.apiKey })\n const routes = await fetchApiRoutes(client)\n if (opts.list !== undefined) {\n const prefix = typeof opts.list === 'string' ? opts.list : '/'\n printer.log(routes.filter((r) => r.split(' ')[1].startsWith(prefix)))\n return\n }\n if (!method || !path) throw validationError('Usage: ap api <METHOD> <path>, or ap api --list.')\n const m = method.toUpperCase()\n try {\n assertApiRoute(routes, m, path)\n } catch (err) {\n throw validationError((err as Error).message)\n }\n const sendBody = m === 'GET' || m === 'DELETE' ? undefined : body\n printer.log(await client.request(m as never, path, sendBody, query))\n } catch (err) {\n printer.error(err as Error)\n const attached = (err as { exitCode?: number }).exitCode\n process.exit(typeof attached === 'number' ? attached : exitCodeFromError(err))\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AGyBO,SAAS,YACd,QACA,MACkB;AAClB,QAAM,UAAU,KAAK,SAAS;AAC9B,QAAM,OAAO,KAAK,QAAQ;AAE1B,MAAI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O,eAAe,iEAAiE,EACvF,OAAO,mBAAmB,4CAA4C,EACtE,OAAO,cAAc,sBAAsB,EAC3C,KAAK,aAAa,CAAC,gBAAgB;AAClC,QAAM,OAAO,YAAY,KAAyB;AAClD,MAAI,CAAC,KAAK,MAAO,cAAa;AAChC,CAAC;AAEH,QAAQ,WAAW,kBAAkB,CAAC;AACtC,QAAQ,WAAW,qBAAqB,CAAC;AACzC,QAAQ,WAAW,sBAAsB,CAAC;AAC1C,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,uBAAuB,CAAC;AAC3C,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,iBAAiB,CAAC;AACrC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,gBAAgB,CAAC;AACpC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,mBAAmB,CAAC;AACvC,QAAQ,WAAW,sBAAsB,CAAC;AAC1C,QAAQ,WAAW,wBAAwB,CAAC;AAC5C,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,kBAAkB,CAAC;AACtC,QAAQ,WAAW,oBAAoB,CAAC;AACxC,QAAQ,WAAW,wBAAwB,CAAC;AAC5C,QAAQ,WAAW,iBAAiB,CAAC;AACrC,QAAQ,WAAW,oBAAoB,CAAC;AAExC,QAAQ,MAAM;","names":["path","open","basename","import_node_fs","path","parsePlatforms","path","import_promises","import_node_path","import_commander","path","os","fs","import_commander","import_commander","resolveExitCode","import_commander","import_commander","import_node_fs","import_node_os","import_node_path","path","os","fs","open","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","import_promises","import_promises","import_node_path","VALID_PLATFORMS","ok","VALID_PLATFORMS","path","fs","nodePath","import_node_fs","fs","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","resolveExitCode","import_commander","import_node_fs","fs","cmd","import_commander","import_commander","open","import_commander","import_node_child_process","import_commander","import_commander","startMcpServer","import_commander","import_commander","path"]}
|