@postonus/cli 0.1.31 → 0.1.33

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/index.js CHANGED
@@ -226,6 +226,16 @@ var FILE_TYPE_EXTENSIONS = {
226
226
  var FILE_SCENARIOS = ["post_attachments", "user_avatar"];
227
227
  var MAX_FILE_SIZE_BYTES = Math.max(...Object.values(scenarios).map((s) => s.maxSize));
228
228
 
229
+ // ../../packages/app-config/src/timezone.ts
230
+ var isValidTimezone = (timezone) => {
231
+ try {
232
+ Intl.DateTimeFormat(void 0, { timeZone: timezone });
233
+ return true;
234
+ } catch {
235
+ return false;
236
+ }
237
+ };
238
+
229
239
  // src/index.ts
230
240
  import { Command, Option } from "commander";
231
241
 
@@ -9458,14 +9468,6 @@ var AnalyticsPreferences = object({
9458
9468
  dataRetentionDays: number2().min(30).max(365).default(90)
9459
9469
  });
9460
9470
  var TimezoneSource = _enum(["auto", "manual"]);
9461
- var isValidTimezone = (timezone) => {
9462
- try {
9463
- Intl.DateTimeFormat(void 0, { timeZone: timezone });
9464
- return true;
9465
- } catch {
9466
- return false;
9467
- }
9468
- };
9469
9471
  var TimezoneSchema = string2().refine(isValidTimezone, { error: "Invalid timezone identifier" });
9470
9472
  var UserPreferencesSchema = object({
9471
9473
  locale: string2().default("en"),
@@ -12197,7 +12199,7 @@ var schemaConverters = [new ZodToJsonSchemaConverter()];
12197
12199
  var generator = new OpenAPIGenerator({ schemaConverters });
12198
12200
 
12199
12201
  // src/config.ts
12200
- import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
12202
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from "fs/promises";
12201
12203
  import { homedir } from "os";
12202
12204
  import { dirname, join } from "path";
12203
12205
  var DEFAULT_API_URL = "https://app.postonus.com";
@@ -12248,12 +12250,68 @@ async function clearConfig() {
12248
12250
  function resolveApiUrl(config2) {
12249
12251
  return (process.env[CLI_API_URL_ENV] || config2.apiUrl || DEFAULT_API_URL).replace(/\/$/, "");
12250
12252
  }
12251
- function resolveApiKey() {
12252
- return process.env[CLI_API_KEY_ENV] || void 0;
12253
+ function resolveApiKey(cliToken) {
12254
+ return cliToken || process.env[CLI_API_KEY_ENV] || process.env.POSTONUS_TOKEN || void 0;
12255
+ }
12256
+ async function findProjectConfigDir(startDir = process.cwd()) {
12257
+ let current = startDir;
12258
+ while (true) {
12259
+ const candidate = join(current, ".postonus", "config.json");
12260
+ try {
12261
+ const stats = await stat(candidate);
12262
+ if (stats.isFile()) return join(current, ".postonus");
12263
+ } catch {
12264
+ }
12265
+ const parent = dirname(current);
12266
+ if (parent === current) break;
12267
+ current = parent;
12268
+ }
12269
+ return null;
12270
+ }
12271
+ async function readProjectConfig(startDir = process.cwd()) {
12272
+ const dir = await findProjectConfigDir(startDir);
12273
+ if (!dir) return null;
12274
+ try {
12275
+ const raw = await readFile(join(dir, "config.json"), "utf8");
12276
+ const parsed = JSON.parse(raw);
12277
+ if (isRecord(parsed) && isString(parsed.workspaceId)) {
12278
+ return {
12279
+ workspaceId: parsed.workspaceId,
12280
+ workspaceName: isString(parsed.workspaceName) ? parsed.workspaceName : void 0,
12281
+ defaultPlatforms: Array.isArray(parsed.defaultPlatforms) ? parsed.defaultPlatforms.filter(isString) : void 0
12282
+ };
12283
+ }
12284
+ } catch {
12285
+ return null;
12286
+ }
12287
+ return null;
12288
+ }
12289
+ async function writeProjectConfig(config2, inDir = process.cwd()) {
12290
+ const dir = join(inDir, ".postonus");
12291
+ const path = join(dir, "config.json");
12292
+ await mkdir(dir, { recursive: true, mode: 493 });
12293
+ await writeFile(path, `${JSON.stringify(config2, null, 2)}
12294
+ `, { mode: 420 });
12295
+ return path;
12296
+ }
12297
+ async function clearProjectConfig(inDir = process.cwd()) {
12298
+ const dir = join(inDir, ".postonus");
12299
+ try {
12300
+ await rm(join(dir, "config.json"), { force: true });
12301
+ return true;
12302
+ } catch {
12303
+ return false;
12304
+ }
12305
+ }
12306
+ async function resolveWorkspaceId(cliWorkspace) {
12307
+ if (cliWorkspace) return cliWorkspace;
12308
+ if (process.env.POSTONUS_WORKSPACE) return process.env.POSTONUS_WORKSPACE;
12309
+ const project = await readProjectConfig();
12310
+ return project?.workspaceId;
12253
12311
  }
12254
12312
 
12255
12313
  // src/output.ts
12256
- var EXIT = { ok: 0, failure: 1, usage: 2, auth: 3, plan: 4, rateLimited: 5 };
12314
+ var EXIT = { ok: 0, failure: 1, usage: 2, auth: 3, plan: 4, rateLimited: 5, canceled: 130 };
12257
12315
  var globals = {};
12258
12316
  function setGlobalOptions(options) {
12259
12317
  globals = options;
@@ -12262,7 +12320,21 @@ function isJsonMode() {
12262
12320
  return globals.json === true;
12263
12321
  }
12264
12322
  function isInteractive() {
12265
- if (globals.json || globals.input === false) return false;
12323
+ if (globals.json || globals.input === false || globals.nonInteractive === true) return false;
12324
+ if (process.env.CI || process.env.CLAUDE_CODE || process.env.CURSOR_AGENT || process.env.CODEX_ENV) return false;
12325
+ return process.stdout.isTTY && process.stdin.isTTY;
12326
+ }
12327
+ function hasConsent() {
12328
+ return globals.yes === true;
12329
+ }
12330
+ function isDebug() {
12331
+ return globals.debug === true;
12332
+ }
12333
+ function tokenOption() {
12334
+ return globals.token;
12335
+ }
12336
+ function shouldUseColor() {
12337
+ if (globals.color === false || process.env.NO_COLOR) return false;
12266
12338
  return process.stdout.isTTY;
12267
12339
  }
12268
12340
  function printJson(data) {
@@ -12278,6 +12350,26 @@ function printStatus(line) {
12278
12350
  process.stderr.write(`${line}
12279
12351
  `);
12280
12352
  }
12353
+ var GLYPH = {
12354
+ success: "\u2713",
12355
+ warning: "!",
12356
+ error: "\u2717",
12357
+ prompt: "?"
12358
+ };
12359
+ function printSuccess(headline) {
12360
+ if (globals.quiet || globals.json) return;
12361
+ const symbol = shouldUseColor() ? `\x1B[32m${GLYPH.success}\x1B[0m` : GLYPH.success;
12362
+ process.stderr.write(`${symbol} ${headline}
12363
+ `);
12364
+ }
12365
+ function printDebug(message) {
12366
+ if (!globals.debug) return;
12367
+ process.stderr.write(`[debug] ${message}
12368
+ `);
12369
+ }
12370
+ function formatRow(label, value2) {
12371
+ return ` ${label.padEnd(14)} ${value2}`;
12372
+ }
12281
12373
  function workspaceOption() {
12282
12374
  return globals.workspace;
12283
12375
  }
@@ -12286,7 +12378,7 @@ function exitCodeFor(error2, status) {
12286
12378
  if (error2.code === "RATE_LIMITED" || status === 429) return EXIT.rateLimited;
12287
12379
  if (PLAN_CODES.has(error2.code) || status === 402) return EXIT.plan;
12288
12380
  if (error2.code === "UNAUTHORIZED" || status === 401) return EXIT.auth;
12289
- if (status === 400) return EXIT.usage;
12381
+ if (status === 400 || error2.code === "BAD_REQUEST") return EXIT.usage;
12290
12382
  return EXIT.failure;
12291
12383
  }
12292
12384
  function failWith(error2, exitCode) {
@@ -12294,11 +12386,29 @@ function failWith(error2, exitCode) {
12294
12386
  process.stdout.write(`${JSON.stringify(error2, null, 2)}
12295
12387
  `);
12296
12388
  } else {
12297
- process.stderr.write(`Error: ${error2.message}
12389
+ const symbol = shouldUseColor() ? `\x1B[31m${GLYPH.error}\x1B[0m` : GLYPH.error;
12390
+ process.stderr.write(`${symbol} ${error2.message}
12391
+ `);
12392
+ if (error2.data.violations.length > 0) {
12393
+ for (const violation of error2.data.violations) {
12394
+ process.stderr.write(` - ${violation.message}
12395
+ `);
12396
+ }
12397
+ }
12398
+ if (error2.context) {
12399
+ for (const [key, val] of Object.entries(error2.context)) {
12400
+ process.stderr.write(`${formatRow(key, val)}
12401
+ `);
12402
+ }
12403
+ }
12404
+ if (error2.next && error2.next.length > 0) {
12405
+ process.stderr.write("\n Next steps:\n");
12406
+ for (const action of error2.next) {
12407
+ if (action.when) process.stderr.write(` ${action.when}:
12298
12408
  `);
12299
- if (error2.data.violations.length > 1) {
12300
- for (const violation of error2.data.violations) process.stderr.write(` - ${violation.message}
12409
+ process.stderr.write(` ${action.command}
12301
12410
  `);
12411
+ }
12302
12412
  }
12303
12413
  }
12304
12414
  process.exit(exitCode);
@@ -12309,8 +12419,8 @@ function fail(message, exitCode = EXIT.failure) {
12309
12419
  exitCode
12310
12420
  );
12311
12421
  }
12312
- function failUsage(message) {
12313
- return failWith({ code: "BAD_REQUEST", message, data: { violations: [{ message }] } }, EXIT.usage);
12422
+ function failUsage(message, next) {
12423
+ return failWith({ code: "BAD_REQUEST", message, next, data: { violations: [{ message }] } }, EXIT.usage);
12314
12424
  }
12315
12425
  var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
12316
12426
  function parseInstant(value2, flag) {
@@ -12323,9 +12433,14 @@ function parseInstant(value2, flag) {
12323
12433
  }
12324
12434
  function requireInteractive(what) {
12325
12435
  if (isInteractive()) return;
12326
- fail(`${what} needs an interactive terminal. Pass the required flags instead, or run without --json / --no-input.`);
12436
+ fail(
12437
+ `${what} needs an interactive terminal. Pass the required flags instead, or run without --json / --non-interactive.`
12438
+ );
12327
12439
  }
12328
- function formatTable(headers, rows) {
12440
+ function formatTable(headers, rows, isTty = process.stdout.isTTY) {
12441
+ if (!isTty) {
12442
+ return [headers.join(" "), ...rows.map((row) => row.join(" "))].join("\n");
12443
+ }
12329
12444
  const widths = headers.map(
12330
12445
  (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
12331
12446
  );
@@ -12334,7 +12449,7 @@ function formatTable(headers, rows) {
12334
12449
  }
12335
12450
 
12336
12451
  // src/version.ts
12337
- var CLI_VERSION = "0.1.31";
12452
+ var CLI_VERSION = "0.1.33";
12338
12453
 
12339
12454
  // src/client.ts
12340
12455
  var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -12398,8 +12513,21 @@ function persistRefreshedTokens(apiUrl, oauth) {
12398
12513
  });
12399
12514
  };
12400
12515
  }
12401
- function buildClient(apiUrl, auth) {
12516
+ function buildClient(apiUrl, auth, workspaceId) {
12402
12517
  const oauth = auth.kind === "oauth" ? { accessToken: auth.accessToken, refreshToken: auth.refreshToken, clientId: auth.clientId } : null;
12518
+ const baseFetch = oauth ? createOAuthFetch(apiUrl, oauth, persistRefreshedTokens(apiUrl, oauth)) : (request, init) => fetch(request, init);
12519
+ const instrumentedFetch = async (request, init) => {
12520
+ if (!isDebug()) {
12521
+ return baseFetch(request, init);
12522
+ }
12523
+ const start = Date.now();
12524
+ printDebug(`-> ${request.method} ${request.url}`);
12525
+ const response = await baseFetch(request, init);
12526
+ const duration3 = Date.now() - start;
12527
+ const reqId = response.headers.get("x-request-id");
12528
+ printDebug(`<- ${response.status} ${response.statusText} (${duration3}ms)${reqId ? ` [request-id:${reqId}]` : ""}`);
12529
+ return response;
12530
+ };
12403
12531
  const link = new OpenAPILink(contract, {
12404
12532
  url: `${apiUrl}/api/v1`,
12405
12533
  headers: () => {
@@ -12408,21 +12536,22 @@ function buildClient(apiUrl, auth) {
12408
12536
  "x-postonus-client": "cli",
12409
12537
  ...auth.kind === "api-key" ? { "x-api-key": auth.apiKey } : { authorization: `Bearer ${oauth?.accessToken}` }
12410
12538
  });
12411
- const workspace = workspaceOption();
12539
+ const workspace = workspaceId || workspaceOption();
12412
12540
  if (workspace) headers.set("x-workspace-id", workspace);
12413
12541
  return Object.fromEntries(headers);
12414
12542
  },
12415
- fetch: oauth ? createOAuthFetch(apiUrl, oauth, persistRefreshedTokens(apiUrl, oauth)) : (request, init) => fetch(request, init)
12543
+ fetch: instrumentedFetch
12416
12544
  });
12417
12545
  return createORPCClient(link);
12418
12546
  }
12419
12547
  async function getApi() {
12420
12548
  const config2 = await readConfig();
12421
12549
  const apiUrl = resolveApiUrl(config2);
12422
- const apiKey = resolveApiKey();
12550
+ const apiKey = resolveApiKey(tokenOption());
12551
+ const workspaceId = await resolveWorkspaceId(workspaceOption());
12423
12552
  if (apiKey) {
12424
12553
  const auth2 = { kind: "api-key", apiKey };
12425
- return { api: buildClient(apiUrl, auth2), apiUrl, auth: auth2, config: config2 };
12554
+ return { api: buildClient(apiUrl, auth2, workspaceId), apiUrl, auth: auth2, config: config2, workspaceId };
12426
12555
  }
12427
12556
  if (!config2.accessToken || !config2.refreshToken || !config2.clientId) {
12428
12557
  fail(`Not signed in. Run \`postonus login\`, or set ${CLI_API_KEY_ENV} for non-interactive use.`);
@@ -12442,7 +12571,7 @@ async function getApi() {
12442
12571
  }
12443
12572
  }
12444
12573
  const auth = { kind: "oauth", accessToken, refreshToken, clientId };
12445
- return { api: buildClient(apiUrl, auth), apiUrl, auth, config: config2 };
12574
+ return { api: buildClient(apiUrl, auth, workspaceId), apiUrl, auth, config: config2, workspaceId };
12446
12575
  }
12447
12576
  function describeError(cause) {
12448
12577
  if (cause instanceof ORPCError3) {
@@ -12465,9 +12594,25 @@ function describeError(cause) {
12465
12594
  function failApi(cause) {
12466
12595
  if (cause instanceof ORPCError3) {
12467
12596
  const data = cause.data;
12597
+ const nextActions = [];
12598
+ if (cause.code === "UNAUTHORIZED") {
12599
+ nextActions.push({
12600
+ command: "postonus login",
12601
+ argv: ["postonus", "login"],
12602
+ when: "Re-authenticate your terminal session"
12603
+ });
12604
+ } else if (cause.code === "CONTENT_TOO_LONG") {
12605
+ nextActions.push({
12606
+ command: "postonus post --thread-file <path>",
12607
+ when: "Split long text into a thread"
12608
+ });
12609
+ }
12468
12610
  const error2 = {
12469
12611
  code: cause.code,
12470
12612
  message: describeError(cause),
12613
+ status: cause.code === "BAD_REQUEST" || cause.code === "UNAUTHORIZED" ? "action_required" : "error",
12614
+ reason: cause.code.toLowerCase(),
12615
+ next: nextActions.length > 0 ? nextActions : void 0,
12471
12616
  data: { violations: data?.violations ?? [] }
12472
12617
  };
12473
12618
  return failWith(error2, exitCodeFor(error2, cause.status));
@@ -12557,6 +12702,17 @@ async function renderOnce(node2) {
12557
12702
  await instance.waitUntilRenderFlush();
12558
12703
  instance.unmount();
12559
12704
  }
12705
+ async function confirmPrompt(message) {
12706
+ const readline = await import("readline/promises");
12707
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
12708
+ try {
12709
+ const answer = await rl.question(`? ${message} (y/N) `);
12710
+ const normalized = answer.trim().toLowerCase();
12711
+ return normalized === "y" || normalized === "yes";
12712
+ } finally {
12713
+ rl.close();
12714
+ }
12715
+ }
12560
12716
 
12561
12717
  // src/commands/auth.tsx
12562
12718
  import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
@@ -12808,7 +12964,7 @@ async function listChannels() {
12808
12964
  return;
12809
12965
  }
12810
12966
  if (channels2.length === 0) {
12811
- printStatus("No channels connected. Run `postonus channels connect` to add one.");
12967
+ printStatus("No channels connected in this workspace.\n\nConnect a channel:\n postonus channels connect");
12812
12968
  return;
12813
12969
  }
12814
12970
  const rows = channels2.map(toRow);
@@ -12912,7 +13068,103 @@ async function connectChannel(options) {
12912
13068
  if (!added) {
12913
13069
  fail("Timed out waiting for the channel to appear. Check `postonus channels list`.");
12914
13070
  }
12915
- printLine(`Connected ${added.platform} \u2014 ${added.name} (${added.id})`);
13071
+ printSuccess(`Connected ${added.platform} \u2014 ${added.name} (${added.id})`);
13072
+ printStatus(
13073
+ `
13074
+ Next: schedule a post to this channel:
13075
+ postonus post "First post" --to ${added.platform.toLowerCase()}`
13076
+ );
13077
+ }
13078
+
13079
+ // src/commands/link.ts
13080
+ import { render as render4 } from "ink";
13081
+ import * as React3 from "react";
13082
+ async function linkWorkspace(options) {
13083
+ const { api } = await getApi();
13084
+ let workspaces = [];
13085
+ try {
13086
+ workspaces = await api.workspace.list();
13087
+ } catch (error2) {
13088
+ return fail(`Could not list workspaces: ${error2 instanceof Error ? error2.message : String(error2)}`);
13089
+ }
13090
+ if (workspaces.length === 0) {
13091
+ return fail("No workspaces available for your account.");
13092
+ }
13093
+ let selectedId = options.workspace || workspaceOption();
13094
+ if (selectedId) {
13095
+ const match = workspaces.find((w) => w.id === selectedId || w.name.toLowerCase() === selectedId?.toLowerCase());
13096
+ if (!match) {
13097
+ failUsage(`Workspace "${selectedId}" not found. Available: ${workspaces.map((w) => w.id).join(", ")}`);
13098
+ }
13099
+ selectedId = match.id;
13100
+ } else {
13101
+ if (!isInteractive()) {
13102
+ failUsage("Missing workspace. Pass -w, --workspace <id> in non-interactive mode.");
13103
+ }
13104
+ if (workspaces.length === 1 && workspaces[0]) {
13105
+ selectedId = workspaces[0].id;
13106
+ } else {
13107
+ selectedId = await new Promise((resolve) => {
13108
+ const items = workspaces.map((w) => ({
13109
+ value: w.id,
13110
+ label: w.name,
13111
+ hint: w.role
13112
+ }));
13113
+ const instance = render4(
13114
+ React3.createElement(Select, {
13115
+ label: "Which workspace would you like to link to this directory?",
13116
+ items,
13117
+ onSelect: (val) => {
13118
+ instance.unmount();
13119
+ resolve(val ?? void 0);
13120
+ }
13121
+ })
13122
+ );
13123
+ });
13124
+ }
13125
+ }
13126
+ if (!selectedId) {
13127
+ printStatus("Canceled.");
13128
+ return;
13129
+ }
13130
+ const workspace = workspaces.find((w) => w.id === selectedId);
13131
+ if (!workspace) {
13132
+ return fail(`Workspace ${selectedId} is not available.`);
13133
+ }
13134
+ const path = await writeProjectConfig({
13135
+ workspaceId: workspace.id,
13136
+ workspaceName: workspace.name
13137
+ });
13138
+ if (isJsonMode()) {
13139
+ printJson({
13140
+ status: "linked",
13141
+ workspaceId: workspace.id,
13142
+ workspaceName: workspace.name,
13143
+ configPath: path
13144
+ });
13145
+ return;
13146
+ }
13147
+ printSuccess(`Linked directory to ${workspace.name} (${workspace.id})`);
13148
+ printStatus(
13149
+ "Configuration saved to .postonus/config.json\n\nNext: schedule posts or inspect queue:\n postonus queue list"
13150
+ );
13151
+ }
13152
+ async function unlinkWorkspace() {
13153
+ const current = await readProjectConfig();
13154
+ if (!current) {
13155
+ if (isJsonMode()) {
13156
+ printJson({ status: "not_linked" });
13157
+ return;
13158
+ }
13159
+ printStatus("This directory is not linked to any Postonus workspace.");
13160
+ return;
13161
+ }
13162
+ await clearProjectConfig();
13163
+ if (isJsonMode()) {
13164
+ printJson({ status: "unlinked", workspaceId: current.workspaceId });
13165
+ return;
13166
+ }
13167
+ printSuccess(`Unlinked directory from ${current.workspaceName || current.workspaceId}`);
12916
13168
  }
12917
13169
 
12918
13170
  // src/commands/mcp.ts
@@ -12951,7 +13203,7 @@ function parseIncoming(message) {
12951
13203
  var write = (message) => process.stdout.write(`${message}
12952
13204
  `);
12953
13205
  async function mcpServe() {
12954
- const { apiUrl, auth } = await getApi();
13206
+ const { apiUrl, auth, workspaceId } = await getApi();
12955
13207
  const endpoint = `${apiUrl}/api/mcp`;
12956
13208
  if (auth.kind === "oauth" && !tokenAudiences(auth.accessToken).includes(endpoint)) {
12957
13209
  fail("This sign-in does not cover the MCP endpoint. Run `postonus login` again to grant it.");
@@ -12968,6 +13220,9 @@ async function mcpServe() {
12968
13220
  accept: "application/json, text/event-stream",
12969
13221
  [CLI_VERSION_HEADER]: CLI_VERSION
12970
13222
  });
13223
+ if (workspaceId) {
13224
+ headers.set("x-workspace-id", workspaceId);
13225
+ }
12971
13226
  if (currentAuth.kind === "api-key") {
12972
13227
  headers.set("x-api-key", currentAuth.apiKey);
12973
13228
  } else if (oauth?.accessToken) {
@@ -13022,7 +13277,7 @@ async function mcpServe() {
13022
13277
 
13023
13278
  // src/commands/media.ts
13024
13279
  import { createHash } from "crypto";
13025
- import { open as openFile, stat } from "fs/promises";
13280
+ import { open as openFile, stat as stat2 } from "fs/promises";
13026
13281
  import { basename, extname } from "path";
13027
13282
  var SCENARIO = "post_attachments";
13028
13283
  function contentTypeFor(path) {
@@ -13058,7 +13313,7 @@ async function putBytes(url2, body, headers) {
13058
13313
  }
13059
13314
  async function uploadMedia(api, path) {
13060
13315
  const contentType = contentTypeFor(path);
13061
- const info = await stat(path).catch(() => {
13316
+ const info = await stat2(path).catch(() => {
13062
13317
  fail(`No such file: ${path}`);
13063
13318
  });
13064
13319
  if (!info.isFile()) fail(`Not a file: ${path}`);
@@ -13198,12 +13453,15 @@ async function openEditor(initial) {
13198
13453
  await rm2(directory, { recursive: true, force: true });
13199
13454
  }
13200
13455
  }
13201
- function readTargets(options) {
13456
+ function readTargets(options, defaultPlatforms) {
13457
+ const rawChannels = options.channel ?? [];
13458
+ const channelIds = (Array.isArray(rawChannels) ? rawChannels : [rawChannels]).flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
13202
13459
  const platforms = (options.to ?? "").split(",").map((value2) => value2.trim()).filter(Boolean).map(parsePlatform);
13203
- if (platforms.length > 0 && options.channel?.length) failUsage("Use --to or --channel, not both.");
13460
+ if (platforms.length > 0 && channelIds.length > 0) failUsage("Use --to or --channel, not both.");
13461
+ const resolvedPlatforms = platforms.length > 0 ? platforms : channelIds.length === 0 && defaultPlatforms && defaultPlatforms.length > 0 ? defaultPlatforms.map(parsePlatform) : void 0;
13204
13462
  return {
13205
- platforms: platforms.length > 0 ? platforms : void 0,
13206
- selectedIntegrations: options.channel?.length ? options.channel : void 0
13463
+ platforms: resolvedPlatforms,
13464
+ selectedIntegrations: channelIds.length > 0 ? channelIds : void 0
13207
13465
  };
13208
13466
  }
13209
13467
  function readCopy(pairs) {
@@ -13242,22 +13500,24 @@ function printState(state, verb) {
13242
13500
  printJson(state);
13243
13501
  return;
13244
13502
  }
13245
- printLine(
13503
+ printSuccess(
13246
13504
  `${state.dryRun ? `Would ${verb.toLowerCase()}` : verb} ${state.postId}${state.review ? " (waiting for review)" : ""}`
13247
13505
  );
13248
13506
  for (const schedule of state.schedules) {
13249
13507
  printLine(
13250
- ` ${schedule.platform.toLowerCase()} ${schedule.channelName} ${schedule.status.toLowerCase()} ${schedule.scheduledAt ?? "\u2014"} ${schedule.scheduleId}`
13508
+ ` ${schedule.platform.toLowerCase().padEnd(10)} ${schedule.channelName.padEnd(18)} ${schedule.status.toLowerCase().padEnd(10)} ${schedule.scheduledAt ?? "\u2014"} ${schedule.scheduleId}`
13251
13509
  );
13252
13510
  }
13253
- if (!state.dryRun) printStatus(state.url);
13511
+ if (!state.dryRun) printStatus(`
13512
+ Post URL: ${state.url}`);
13254
13513
  }
13255
13514
  async function post(text, options) {
13256
13515
  const thread = options.threadFile ? await readThread(options.threadFile) : void 0;
13257
13516
  const content = thread ? void 0 : await readContent(text, options);
13258
13517
  if (!thread && !content) failUsage("No content. Pass text, --file, --thread-file, --editor, or pipe it in.");
13259
13518
  const timing = readTiming(options);
13260
- const targets = readTargets(options);
13519
+ const project = await readProjectConfig();
13520
+ const targets = readTargets(options, project?.defaultPlatforms);
13261
13521
  if (timing.postAction !== "DRAFT" && !targets.platforms && !targets.selectedIntegrations) {
13262
13522
  failUsage("Say where to post: --to x,linkedin or --channel <id> (or use --draft).");
13263
13523
  }
@@ -13279,6 +13539,15 @@ async function post(text, options) {
13279
13539
  const created = posts[0];
13280
13540
  if (!created) return fail("The server created no post.");
13281
13541
  printState(created, timing.postAction === "DRAFT" ? "Saved draft" : "Scheduled");
13542
+ if (!options.dryRun) {
13543
+ if (timing.postAction === "DRAFT") {
13544
+ printStatus(`
13545
+ Next: schedule this draft when ready:
13546
+ postonus queue schedule ${created.postId} --optimal`);
13547
+ } else {
13548
+ printStatus("\nNext: inspect your queue:\n postonus queue list");
13549
+ }
13550
+ }
13282
13551
  } catch (error2) {
13283
13552
  failApi(error2);
13284
13553
  }
@@ -13311,6 +13580,34 @@ async function editPost(postId, text, options) {
13311
13580
  }
13312
13581
  }
13313
13582
  async function deletePost(postId, options) {
13583
+ const confirmed = options.yes || hasConsent();
13584
+ if (!confirmed) {
13585
+ if (!isInteractive()) {
13586
+ failWith(
13587
+ {
13588
+ code: "BAD_REQUEST",
13589
+ status: "action_required",
13590
+ reason: "missing_consent",
13591
+ message: `Cannot delete post ${postId} in non-interactive mode without confirmation.`,
13592
+ next: [
13593
+ {
13594
+ command: `postonus post delete ${postId}${options.remote ? " --remote" : ""} --yes`,
13595
+ argv: ["postonus", "post", "delete", postId, ...options.remote ? ["--remote"] : [], "--yes"],
13596
+ when: "Confirm deletion of post and schedules"
13597
+ }
13598
+ ],
13599
+ data: { violations: [{ message: "Pass -y or --yes to confirm deletion in non-interactive mode." }] }
13600
+ },
13601
+ EXIT.usage
13602
+ );
13603
+ }
13604
+ const message = options.remote ? `Delete post ${postId} and remove copies from platforms? This cannot be undone.` : `Delete post ${postId} and every scheduled copy in your workspace?`;
13605
+ const ok = await confirmPrompt(message);
13606
+ if (!ok) {
13607
+ printStatus("Canceled.");
13608
+ process.exit(EXIT.canceled);
13609
+ }
13610
+ }
13314
13611
  const { api } = await getApi();
13315
13612
  try {
13316
13613
  const state = await api.posts.delete({ id: postId, deleteRemote: options.remote ?? false });
@@ -13318,7 +13615,7 @@ async function deletePost(postId, options) {
13318
13615
  printJson(state);
13319
13616
  return;
13320
13617
  }
13321
- printLine(`Deleted ${postId}${state.deletedFromPlatforms ? ", and on its platforms" : ""}`);
13618
+ printSuccess(`Deleted ${postId}${state.deletedFromPlatforms ? ", and on its platforms" : ""}`);
13322
13619
  } catch (error2) {
13323
13620
  failApi(error2);
13324
13621
  }
@@ -13334,8 +13631,9 @@ async function retrySchedule(scheduleId, options) {
13334
13631
  async function bestTimes(options) {
13335
13632
  const platforms = (options.to ?? "").split(",").map((value2) => value2.trim()).filter(Boolean).map(parsePlatform);
13336
13633
  if (platforms.length === 0) failUsage("Which platforms? e.g. --to x,linkedin");
13337
- const count = Number.parseInt(options.count ?? "5", 10);
13338
- if (!Number.isInteger(count) || count < 1 || count > 20) failUsage("--count must be between 1 and 20.");
13634
+ const countStr = options.limit ?? options.count ?? "5";
13635
+ const count = Number.parseInt(countStr, 10);
13636
+ if (!Number.isInteger(count) || count < 1 || count > 20) failUsage("--limit must be between 1 and 20.");
13339
13637
  const { api } = await getApi();
13340
13638
  try {
13341
13639
  const result = await api.platforms.bestTimes({ platforms, count });
@@ -13418,15 +13716,22 @@ async function listQueue(options) {
13418
13716
  return;
13419
13717
  }
13420
13718
  if (schedules.length === 0) {
13421
- printStatus("Queue is empty.");
13719
+ if (isJsonMode()) {
13720
+ printJson({ queue: [] });
13721
+ return;
13722
+ }
13723
+ printStatus(
13724
+ 'No posts found in queue.\n\nSchedule your first post:\n postonus post "Hello world" --to x,linkedin --optimal'
13725
+ );
13422
13726
  return;
13423
13727
  }
13728
+ const isTty = process.stdout.isTTY;
13424
13729
  const rows = schedules.map((schedule) => [
13425
- formatWhen(schedule.scheduledAt),
13730
+ isTty ? formatWhen(schedule.scheduledAt) : schedule.scheduledAt ?? "\u2014",
13426
13731
  schedule.integration.platform.toLowerCase(),
13427
13732
  schedule.integration.name,
13428
13733
  schedule.status.toLowerCase(),
13429
- truncate(schedule.post.content),
13734
+ isTty ? truncate(schedule.post.content) : schedule.post.content.replace(WHITESPACE_RUN_REGEX, " ").trim(),
13430
13735
  schedule.id
13431
13736
  ]);
13432
13737
  if (isInteractive()) {
@@ -13453,7 +13758,10 @@ async function scheduleDraft(postId, options) {
13453
13758
  return;
13454
13759
  }
13455
13760
  const when = state.schedules.find((schedule) => schedule.scheduledAt)?.scheduledAt;
13456
- printLine(`${state.dryRun ? "Would schedule" : "Scheduled"} ${postId} for ${when ?? "its next window"}`);
13761
+ printSuccess(`${state.dryRun ? "Would schedule" : "Scheduled"} ${postId} for ${when ?? "its next window"}`);
13762
+ if (!state.dryRun) {
13763
+ printStatus("\nNext: inspect your queue:\n postonus queue list");
13764
+ }
13457
13765
  } catch (error2) {
13458
13766
  failApi(error2);
13459
13767
  }
@@ -13467,7 +13775,7 @@ async function moveQueueItem(scheduleId, options) {
13467
13775
  printJson(state);
13468
13776
  return;
13469
13777
  }
13470
- printLine(`Moved ${scheduleId} to ${scheduledAt}`);
13778
+ printSuccess(`Moved ${scheduleId} to ${scheduledAt}`);
13471
13779
  } catch (error2) {
13472
13780
  failApi(error2);
13473
13781
  }
@@ -13475,19 +13783,34 @@ async function moveQueueItem(scheduleId, options) {
13475
13783
 
13476
13784
  // src/commands/workspaces.ts
13477
13785
  async function listWorkspaces() {
13478
- const { api } = await getApi();
13786
+ const { api, workspaceId } = await getApi();
13479
13787
  try {
13480
13788
  const workspaces = await api.workspace.list();
13481
13789
  if (isJsonMode()) {
13482
- printJson({ workspaces: workspaces.map(({ id, name, role }) => ({ id, name, role })) });
13790
+ printJson({
13791
+ activeWorkspaceId: workspaceId ?? null,
13792
+ workspaces: workspaces.map(({ id, name, role }) => ({
13793
+ id,
13794
+ name,
13795
+ role,
13796
+ active: id === workspaceId
13797
+ }))
13798
+ });
13483
13799
  return;
13484
13800
  }
13485
13801
  printLine(
13486
13802
  formatTable(
13487
- ["NAME", "ROLE", "ID"],
13488
- workspaces.map((w) => [w.name, w.role, w.id])
13803
+ ["NAME", "ROLE", "ID", "STATUS"],
13804
+ workspaces.map((w) => [w.name, w.role, w.id, w.id === workspaceId ? "linked/active" : ""])
13489
13805
  )
13490
13806
  );
13807
+ if (workspaceId) {
13808
+ const active = workspaces.find((w) => w.id === workspaceId);
13809
+ if (active) {
13810
+ printStatus(`
13811
+ Active workspace: ${active.name} (${active.id})`);
13812
+ }
13813
+ }
13491
13814
  } catch (error2) {
13492
13815
  failApi(error2);
13493
13816
  }
@@ -13498,7 +13821,7 @@ var program = new Command();
13498
13821
  program.exitOverride((error2) => {
13499
13822
  process.exit(error2.exitCode === 0 ? EXIT.ok : EXIT.usage);
13500
13823
  });
13501
- program.name("postonus").description("Schedule and publish social posts from your terminal").version(CLI_VERSION, "-v, --version").option("--json", "output machine-readable JSON on stdout").option("-q, --quiet", "suppress progress output on stderr").option("--no-color", "disable coloured output").option("--no-input", "never prompt; fail instead of waiting for input").option("-w, --workspace <id>", "workspace to act in (from `postonus workspaces list`); sent as x-workspace-id").addHelpText(
13824
+ program.name("postonus").description("Schedule and publish social posts from your terminal").version(CLI_VERSION, "-v, --version").option("--json", "output machine-readable JSON on stdout").option("-q, --quiet", "suppress progress output on stderr").option("--no-color", "disable coloured output").option("-d, --debug", "print debug diagnostics on stderr").option("-y, --yes", "grant consent for destructive or non-interactive actions").option("-t, --token <token>", "API key or token override; takes precedence over login").option("--non-interactive", "never prompt; fail instead of waiting for input").option("--no-input", "alias for --non-interactive").option("-w, --workspace <id>", "workspace to act in (from `postonus workspaces list`); sent as x-workspace-id").addHelpText(
13502
13825
  "after",
13503
13826
  `
13504
13827
  Environment:
@@ -13510,11 +13833,12 @@ Environment:
13510
13833
  Times are RFC 3339 with an offset: 2026-08-01T09:30:00Z or 2026-08-01T11:30:00+02:00.
13511
13834
 
13512
13835
  Exit codes:
13513
- 0 ok, 1 other failure, 2 usage or validation, 3 auth, 4 plan or quota, 5 rate limit.
13836
+ 0 ok, 1 other failure, 2 usage or validation, 3 auth, 4 plan or quota, 5 rate limit, 130 canceled.
13514
13837
  With --json a failure prints { code, message, data: { violations } } on stdout.
13515
13838
 
13516
13839
  Examples:
13517
13840
  $ postonus login
13841
+ $ postonus link
13518
13842
  $ postonus post "shipping today" --to x,linkedin --optimal
13519
13843
  $ postonus post --file notes.md --to linkedin --at 2026-08-01T09:30:00Z
13520
13844
  $ postonus post --thread-file thread.md --channel <id> --at 2026-08-01T09:30:00Z --dry-run
@@ -13526,21 +13850,25 @@ MCP:
13526
13850
  "postonus": { "command": "postonus", "args": ["mcp"] }
13527
13851
  It reuses this machine's stored login \u2014 the editor runs no OAuth of its own.`
13528
13852
  ).hook("preAction", (command) => {
13529
- setGlobalOptions(command.opts());
13853
+ const opts = command.opts();
13854
+ if (opts.input === false) opts.nonInteractive = true;
13855
+ setGlobalOptions(opts);
13530
13856
  });
13531
13857
  program.command("login").description("sign in via your browser").action(login);
13532
13858
  program.command("logout").description("remove the stored credentials").action(logout);
13533
13859
  program.command("whoami").description("show the signed-in account").action(whoami);
13534
- var channels = program.command("channels").description("manage connected channels");
13860
+ var channels = program.command("channels").alias("channel").description("manage connected channels");
13535
13861
  channels.command("list").alias("ls").description("list connected channels").action(listChannels);
13536
13862
  channels.command("connect").description("connect a new channel via OAuth").option("-p, --platform <platform>", "platform to connect (prompts when omitted)").option("--no-wait", "return immediately instead of waiting for approval").action(connectChannel);
13863
+ program.command("link").description("link current directory to a Postonus workspace").option("-w, --workspace <id>", "workspace to link to").action(linkWorkspace);
13864
+ program.command("unlink").description("unlink current directory from its Postonus workspace").action(unlinkWorkspace);
13537
13865
  var collect = (value2, previous = []) => [...previous, value2];
13538
- var postCommand = program.command("post").description("create a post: scheduled, now, at the next optimal time, or as a draft").argument("[text]", "post content; also accepts piped stdin").option("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-c, --channel <id>", "a channel id from `postonus channels list`; repeatable", collect).option("-a, --at <time>", "RFC 3339 time with an offset").option("-o, --optimal", "the next recommended window").option("--now", "publish as soon as the queue picks it up").option("-d, --draft", "save as a draft without scheduling").option("-f, --file <path>", "read content from a file").option("--thread-file <path>", "read a thread: segments separated by a line of ---").option("-e, --editor", "compose in $EDITOR").option("-m, --media <path...>", "attach local image or video files").option("--copy <channelId=text>", "text that replaces the body on one channel; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(post);
13539
- postCommand.command("edit").description("change a post; only the flags given change").argument("<postId>", "post id from `postonus queue list`").argument("[text]", "new content").option("-t, --to <platforms>", "replace the channels with these platforms").option("-c, --channel <id>", "replace the channels with these ids; repeatable", collect).option("-a, --at <time>", "move every channel to this RFC 3339 time").option("-f, --file <path>", "read new content from a file").option("--thread-file <path>", "replace the body with a thread file").option("-m, --media <path...>", "replace the media with these files").option("--copy <channelId=text>", "replace one channel's copy; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(editPost);
13540
- postCommand.command("delete").description("delete a post and every schedule on it").argument("<postId>", "post id from `postonus queue list`").option("--remote", "also delete published copies on their platforms").action(deletePost);
13866
+ var postCommand = program.command("post").alias("posts").description("create a post: scheduled, now, at the next optimal time, or as a draft").argument("[text]", "post content; also accepts piped stdin").option("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-c, --channel <id>", "a channel id from `postonus channels list`; repeatable", collect).option("--channels <ids>", "channel ids; comma-separated or repeatable", collect).option("-a, --at <time>", "RFC 3339 time with an offset").option("-o, --optimal", "the next recommended window").option("--now", "publish as soon as the queue picks it up").option("-d, --draft", "save as a draft without scheduling").option("-f, --file <path>", "read content from a file").option("--thread-file <path>", "read a thread: segments separated by a line of ---").option("-e, --editor", "compose in $EDITOR").option("-m, --media <path...>", "attach local image or video files").option("--copy <channelId=text>", "text that replaces the body on one channel; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(post);
13867
+ postCommand.command("edit").description("change a post; only the flags given change").argument("<postId>", "post id from `postonus queue list`").argument("[text]", "new content").option("-t, --to <platforms>", "replace the channels with these platforms").option("-c, --channel <id>", "replace the channels with these ids; repeatable", collect).option("--channels <ids>", "alias for --channel", collect).option("-a, --at <time>", "move every channel to this RFC 3339 time").option("-f, --file <path>", "read new content from a file").option("--thread-file <path>", "replace the body with a thread file").option("-m, --media <path...>", "replace the media with these files").option("--copy <channelId=text>", "replace one channel's copy; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(editPost);
13868
+ postCommand.command("delete").alias("rm").alias("del").description("delete a post and every schedule on it").argument("<postId>", "post id from `postonus queue list`").option("--remote", "also delete published copies on their platforms").option("-y, --yes", "skip confirmation prompt").action(deletePost);
13541
13869
  postCommand.command("retry").description("queue a failed schedule to publish again").argument("<scheduleId>", "schedule id from `postonus queue list --status failed`").option("--content <text>", "replacement copy for this channel only").action(retrySchedule);
13542
- program.command("best-times").description("recommended posting windows for the given platforms").requiredOption("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-n, --count <count>", "how many times to list (1-20)", "5").action(bestTimes);
13543
- program.command("workspaces").description("workspaces you belong to").command("list").alias("ls").description("list workspaces and their ids").action(listWorkspaces);
13870
+ program.command("best-times").description("recommended posting windows for the given platforms").requiredOption("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-n, --limit <count>", "how many times to list (1-20)", "5").option("--count <count>", "alias for --limit (deprecated)").action(bestTimes);
13871
+ program.command("workspaces").alias("workspace").description("workspaces you belong to").command("list").alias("ls").description("list workspaces and their ids").action(listWorkspaces);
13544
13872
  var queue = program.command("queue").description("inspect and adjust scheduled posts");
13545
13873
  queue.command("list").alias("ls").description("list drafts, scheduled posts and failures").addOption(new Option("-n, --limit <count>", "how many to show (10-100)").default("20")).option("-t, --to <platforms>", "filter by comma-separated platforms").option("-s, --status <statuses>", "filter by comma-separated statuses").action(listQueue);
13546
13874
  queue.command("schedule").description("give a draft its send time").argument("<postId>", "post id from `postonus queue list --status draft` or `postonus post --draft`").option("-a, --at <time>", "RFC 3339 time with an offset").option("-o, --optimal", "next recommended window").option("--dry-run", "run every server check and show the result without saving").option(