@letterstory/cli 0.163.1 → 0.165.0

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/lib/cli.mjs CHANGED
@@ -1,8 +1,16 @@
1
1
  // Argument parsing, help, and command routing for the Letter CLI. `run(argv)`
2
2
  // is the single entry the bin and the tests both call; it returns an exit code and
3
- // never throws for user-facing problems (those become a printed CliError + code 1).
3
+ // never throws for user-facing problems (those become a printed CliError + code 1, or EXIT_PAYMENT_REQUIRED, 3,
4
+ // for a gate refusal: CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS).
4
5
 
5
- import { LetterstoryClient, CliError, resolveConfig, readConfigFile, writeConfigFile } from "./client.mjs";
6
+ import {
7
+ LetterstoryClient,
8
+ CliError,
9
+ PAYMENT_REQUIRED_CODES,
10
+ resolveConfig,
11
+ readConfigFile,
12
+ writeConfigFile,
13
+ } from "./client.mjs";
6
14
  import { resolveDocumentFlags } from "./documents.mjs";
7
15
  import { checkForUpdate } from "./update-check.mjs";
8
16
  import {
@@ -66,8 +74,10 @@ import {
66
74
  } from "./commands.mjs";
67
75
 
68
76
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
69
- // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
70
- export const VERSION = "0.163.1";
77
+ export const VERSION = "0.165.0";
78
+
79
+ /** The exit code for a gate refusal (CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS): 1 is a plain error. */
80
+ export const EXIT_PAYMENT_REQUIRED = 3;
71
81
 
72
82
  // Flags that never take a value. Listing them explicitly means `deploy get --json <id>`
73
83
  // can't accidentally swallow the id as --json's value. Every `type: "bool"` flag (and its
@@ -1023,6 +1033,7 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
1023
1033
  admin billing legacy mark <org-id> --why "…" | --all --why "…" [--apply]
1024
1034
  Mark legacy orgs: free until migrated, never gated
1025
1035
  by the free paywall (--all: everyone who pays today)
1036
+ admin billing legacy unmark <org-id> --why "…" No longer legacy; kept with who, when and why
1026
1037
  admin billing free exposure | backfill --why "…" [--apply]
1027
1038
  Who the free paywall would stop today; the one-time
1028
1039
  signup grant for self-serve orgs with none
@@ -1803,6 +1814,12 @@ export async function run(argv, io = defaultIo()) {
1803
1814
  return typeof code === "number" ? code : 0;
1804
1815
  } catch (err) {
1805
1816
  if (err instanceof CliError) {
1817
+ // A gate's refusal (needs a card, a payment that didn't go through, the spend cap) is its own
1818
+ // exit code, with its code printed: not the 1 of a bad argument.
1819
+ if (err.code && PAYMENT_REQUIRED_CODES.includes(err.code)) {
1820
+ io.error(`Error [${err.code}]: ${err.message}`);
1821
+ return EXIT_PAYMENT_REQUIRED;
1822
+ }
1806
1823
  io.error(`Error: ${err.message}`);
1807
1824
  return 1;
1808
1825
  }
package/lib/client.mjs CHANGED
@@ -11,7 +11,21 @@ export const DEFAULT_API_URL = "https://app.letterstory.com";
11
11
 
12
12
  // A CliError is a message we've already made human-friendly; the entry point prints
13
13
  // its message and exits 1 without a stack trace. Anything else is a real bug.
14
- export class CliError extends Error {}
14
+ export class CliError extends Error {
15
+ /**
16
+ * @param {string} message
17
+ * @param {{ code?: string | null }} [opts] A gate refusal's code (CARD_REQUIRED, PAYMENT_FAILED,
18
+ * OUT_OF_TOKENS): the CLI exits with EXIT_PAYMENT_REQUIRED for it, so an agent can tell "needs a
19
+ * card" from a bad argument without reading the text.
20
+ */
21
+ constructor(message, opts = {}) {
22
+ super(message);
23
+ this.code = opts.code ?? null;
24
+ }
25
+ }
26
+
27
+ /** The gate refusals' codes (the app's 402 body and an MCP error's structuredContent). */
28
+ export const PAYMENT_REQUIRED_CODES = ["CARD_REQUIRED", "PAYMENT_FAILED", "OUT_OF_TOKENS"];
15
29
 
16
30
  // Config lives at ~/.letterstory/config.json. LETTERSTORY_CONFIG_HOME overrides the
17
31
  // home dir (the tests point it at a temp dir so they never touch the real file).
@@ -202,7 +216,9 @@ export class LetterstoryClient {
202
216
  }
203
217
  const body = await res.json().catch(() => null);
204
218
  if (!res.ok) {
205
- throw new CliError(body?.error ? String(body.error) : `Request failed (HTTP ${res.status}) at ${url}`);
219
+ throw new CliError(body?.error ? String(body.error) : `Request failed (HTTP ${res.status}) at ${url}`, {
220
+ code: typeof body?.code === "string" ? body.code : null,
221
+ });
206
222
  }
207
223
  if (!body) throw new CliError(`Unexpected non-JSON response (HTTP ${res.status}) from ${url}`);
208
224
  return body;
@@ -242,7 +258,8 @@ export class LetterstoryClient {
242
258
  async callTool(name, args = {}) {
243
259
  const result = await this.rpc("tools/call", { name, arguments: args });
244
260
  const text = result?.content?.[0]?.text ?? "";
245
- if (result?.isError) throw new CliError(text || `Tool ${name} failed`);
261
+ if (result?.isError)
262
+ throw new CliError(text || `Tool ${name} failed`, { code: result.structuredContent?.code ?? null });
246
263
  if (!text) return {};
247
264
  try {
248
265
  return JSON.parse(text);
@@ -5352,23 +5352,26 @@ const LAGO_USAGE = `Usage: admin billing lago <command>
5352
5352
  payments retry <lago-invoice-id> charge one failed invoice again now
5353
5353
  payments run [--dry] one pass of the failed-payment loop now (--dry: report only)
5354
5354
  signups [--status open|card_saved|provisioned|paid|abandoned|canceled] new paying orgs on their way onto Lago
5355
+ signups end <org-id> --why "…" end an org's signup in flight (not yet provisioned), so one on other terms can open
5355
5356
  cap <org-id> <dollars|off> [--why "…"] set an account's monthly spend cap on overage (off: no cap)
5356
- cancel <org-id> --why "…" --yes end an account's Lago plan now and refund its first invoice
5357
+ cancel <org-id> --why "…" --yes end an account's Lago plan now (its plan fee refunded in its first month, once per org)
5357
5358
  move <org-id> --plan starter [--ratio 4] [--why "…" above 4x] [--reason "…"] [--complimentary 20000] [--review 2027-05-01] [--stripe-subscription sub_…] [--dry]
5358
5359
  move an existing customer from Stripe to Lago at their renewal
5359
5360
  changes [--org <org-id>] term changes waiting to take effect (moves, cheaper plans, new ratios)
5360
5361
  changes cancel <org-id> take back an org's scheduled change before it takes effect`;
5361
5362
 
5362
5363
  const LEGACY_USAGE = `Usage: admin billing legacy mark <org-id> --why "…" mark one org legacy (free until migrated)
5363
- admin billing legacy mark --all --why "…" [--apply] every org that pays today; a dry run unless --apply`;
5364
+ admin billing legacy mark --all --why "…" [--apply] every org that pays today; a dry run unless --apply
5365
+ admin billing legacy unmark <org-id> --why "…" no longer legacy (kept with who, when and why)`;
5364
5366
 
5365
5367
  /**
5366
5368
  * admin billing legacy mark … — legacy orgs (decisions 2026-10-27): free until migrated, never gated
5367
5369
  * by the free paywall. --all covers the $0 Lago trial, Stripe payers and billing-exempt orgs; it only
5368
- * reports unless --apply.
5370
+ * reports unless --apply. unmark ends one org's mark, kept with who, when and why.
5369
5371
  */
5370
5372
  async function cmdAdminBillingLegacy(ctx) {
5371
5373
  const { flags, positionals, io } = ctx;
5374
+ if (positionals[1] === "unmark") return cmdAdminBillingLegacyUnmark(ctx);
5372
5375
  if (positionals[1] !== "mark") throw new CliError(LEGACY_USAGE);
5373
5376
  const why = flagStr(flags.why);
5374
5377
  if (!why) throw new CliError(`Say why (--why "…"): it is kept with the mark.\n${LEGACY_USAGE}`);
@@ -5393,6 +5396,19 @@ async function cmdAdminBillingLegacy(ctx) {
5393
5396
  return 0;
5394
5397
  }
5395
5398
 
5399
+ async function cmdAdminBillingLegacyUnmark(ctx) {
5400
+ const { flags, positionals, io } = ctx;
5401
+ const why = flagStr(flags.why);
5402
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the unmark.\n${LEGACY_USAGE}`);
5403
+ const orgId = positionals[2];
5404
+ if (!orgId) throw new CliError(LEGACY_USAGE);
5405
+ const result = await staffRequest(ctx, "DELETE", "/api/superadmin/billing/legacy", { orgId, why });
5406
+ printResult(io, flags, result, (r) =>
5407
+ r.unmarked ? `Unmarked ${r.orgId}: no longer legacy.` : `${r.orgId} was not legacy; nothing changed.`
5408
+ );
5409
+ return 0;
5410
+ }
5411
+
5396
5412
  const FREE_USAGE = `Usage: admin billing free exposure [--json] who the free paywall covers, and who is unassigned
5397
5413
  admin billing free backfill --why "…" [--apply] signup grant for self-serve orgs with none; a dry run unless --apply`;
5398
5414
 
@@ -5563,6 +5579,19 @@ async function cmdAdminBilling(ctx) {
5563
5579
  return 0;
5564
5580
  }
5565
5581
  case "signups": {
5582
+ if (positionals[2] === "end") {
5583
+ const orgId = requirePositional(positionals, 3, "org-id");
5584
+ if (!flagStr(flags.why)) throw new CliError(LAGO_USAGE);
5585
+ const result = await staffRequest(ctx, "DELETE", `${LAGO}/signups`, { orgId, why: flagStr(flags.why) });
5586
+ printResult(
5587
+ io,
5588
+ flags,
5589
+ result,
5590
+ (r) =>
5591
+ `Signup ended: ${r.ended.plan_code}${r.ended.ratio !== 1 ? ` ${r.ended.ratio}x` : ""}${r.ended.coupon_cents ? `, $${(r.ended.coupon_cents / 100).toFixed(2)} off` : ""} from ${r.ended.source}. A new signup can be opened on other terms.`
5592
+ );
5593
+ return 0;
5594
+ }
5566
5595
  const params = new URLSearchParams(compact({ status: flagStr(flags.status) }));
5567
5596
  const result = await staffRequest(ctx, "GET", `${LAGO}/signups${params.size ? `?${params}` : ""}`);
5568
5597
  printResult(io, flags, result, (r) =>
@@ -5583,7 +5612,7 @@ async function cmdAdminBilling(ctx) {
5583
5612
  if (!orgId || !flagStr(flags.why)) throw new CliError(LAGO_USAGE);
5584
5613
  if (!flagBool(flags.yes))
5585
5614
  throw new CliError(
5586
- "This ends the plan now and refunds its first invoice. Run again with --yes to do it."
5615
+ "This ends the plan now. In its first month the plan fee is refunded, once per org; usage is invoiced. Run again with --yes to do it."
5587
5616
  );
5588
5617
  const result = await staffRequest(ctx, "POST", `${LAGO}/cancel`, { orgId, reason: flagStr(flags.why) });
5589
5618
  printResult(
@@ -141,18 +141,10 @@ async function orgBilling(ctx) {
141
141
  refuseUnknownFlags(ctx, ARGS.cancel_billing_plan, ["yes"]);
142
142
  if (!flagBool(flags.yes))
143
143
  throw new CliError(
144
- "This ends the plan now and refunds its first invoice (and any overage charged this month). Run again with --yes to do it."
144
+ "In the plan's first month this ends it now and refunds the plan fee, once per workspace (usage so far is billed; overage already charged isn't refunded). If the workspace had that refund before, the plan ends at the end of this billing period instead, with no refund. Run again with --yes to do it."
145
145
  );
146
146
  const result = await client.callTool("cancel_billing_plan", argsFromFlags(ARGS.cancel_billing_plan, flags, []));
147
- printResult(io, flags, result, (r) =>
148
- [
149
- "Plan cancelled",
150
- r.firstInvoice === "voided" ? "; its unpaid first invoice is voided" : "",
151
- r.refundedCents ? `; $${(r.refundedCents / 100).toFixed(2)} refunded to the card` : "",
152
- r.topUpsRefundedCents ? ` ($${(r.topUpsRefundedCents / 100).toFixed(2)} of it overage)` : "",
153
- ".",
154
- ].join("")
155
- );
147
+ printResult(io, flags, result, (r) => r.message);
156
148
  return 0;
157
149
  }
158
150
  if (positionals[0] === "card") {
@@ -223,7 +215,7 @@ export function billingAccountText(r) {
223
215
  const f = r.free;
224
216
  return [
225
217
  r.plan
226
- ? `Plan: ${r.plan.name}${r.plan.ratio !== 1 ? ` (${r.plan.ratio}x)` : ""}${ended ? `, cancelled${r.canceledAt ? ` on ${r.canceledAt.slice(0, 10)}` : ""}.` : ""}`
218
+ ? `Plan: ${r.plan.name}${r.plan.ratio !== 1 ? ` (${r.plan.ratio}x)` : ""}${ended ? `, cancelled${r.canceledAt ? ` on ${r.canceledAt.slice(0, 10)}` : ""}.` : r.endsAt ? `, cancelled: ends on ${r.endsAt.slice(0, 10)}.` : ""}`
227
219
  : f
228
220
  ? "On free tokens: no card yet."
229
221
  : "Not billed by usage yet.",
@@ -267,6 +259,8 @@ export function billingAccountText(r) {
267
259
 
268
260
  /** `org billing rewards` as text: each action, its tokens, claimed or how to claim. */
269
261
  function tokenRewardsText(r) {
262
+ if (r.eligible === false)
263
+ return "Free tokens for actions are for workspaces on free tokens; this one is on a plan.";
270
264
  const lines = r.rewards.map(
271
265
  (x) =>
272
266
  ` ${x.claimed ? "✓" : x.ready === false ? "·" : "○"} ${x.action.padEnd(18)} ${String(x.tokens).padStart(6)} tokens ${x.title}${x.claimed ? " (claimed)" : x.ready === false ? " (not done yet)" : ""}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.163.1",
3
+ "version": "0.165.0",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",