@letterstory/cli 0.168.1 → 0.174.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
@@ -75,7 +75,7 @@ import {
75
75
  } from "./commands.mjs";
76
76
 
77
77
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
78
- export const VERSION = "0.168.1";
78
+ export const VERSION = "0.174.0";
79
79
 
80
80
  /** The exit code for a gate refusal (CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS): 1 is a plain error. */
81
81
  export const EXIT_PAYMENT_REQUIRED = 3;
@@ -333,6 +333,8 @@ export const BOOLEAN_FLAGS = new Set([
333
333
  // admin billing lago payments --open / payments run --dry
334
334
  "open",
335
335
  "dry",
336
+ // admin billing emails --bounced
337
+ "bounced",
336
338
  ]);
337
339
 
338
340
  // Tiny argv parser: `--flag value`, `--flag=value`, boolean `--flag`, and positionals.
@@ -893,20 +895,27 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
893
895
  fleet:query capability on the staff key.
894
896
  admin recipes list | show <id|name> | vocab | stats Recipes: Letter's one library of direction for
895
897
  Letterpress on Plan, Build and Fix (/superadmin/recipes),
896
- five fields each: name, recipe, when to use, when not to
897
- use, weight. vocab says what each field means; stats how
898
+ each a name, a description, the recipe (what Letterpress
899
+ reads), when to use, when not to use, a weight, its tags
900
+ (approaches) and its variations (Letterpress follows one).
901
+ vocab says what each field means; stats how
898
902
  often runs followed each recipe (and the share of the
899
903
  runs that had it) and how its suggestions fare. Needs
900
904
  recipes:read.
901
905
  admin recipes list --approach <seo|geo|agent_conviction|inbound_conversion|outbound|other>
902
- One approach's recipes, read from their own words.
906
+ The recipes tagged with one approach (other: with none).
907
+ admin recipes runs <id|name> [--days 30] [--limit 100]
908
+ The runs that had the recipe to choose from, newest
909
+ first: company, what was asked, who asked, and ✓ on
910
+ the ones that used it.
903
911
  admin recipes export [--out recipes.json] The library as a file import reads back.
904
912
  admin recipes import <file> [--dry-run] Write a library in one call: each recipe matched by id,
905
913
  else name, then changed or created. --dry-run writes
906
914
  nothing. Exits 1 if any row failed.
907
- admin recipes save [<id>] [--file <recipe.json>] [--name …] [--recipe …] [--when-to-use …]
908
- [--when-not-to-use …] [--weight 1..10]
909
- Create one (no id) or change one. Needs recipes:write.
915
+ admin recipes save [<id>] [--file <recipe.json>] [--name …] [--description …] [--recipe …]
916
+ [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo]
917
+ Create one (no id) or change one; variations come from
918
+ --file. Needs recipes:write.
910
919
  admin recipes delete <id> --yes Delete for good.
911
920
  admin letterpress status [--customers] Letterpress as it runs now: per lens its mode, bar, recipes,
912
921
  runs, model and prompt hash, how often the shadow agreed,
@@ -1038,9 +1047,26 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
1038
1047
  Mark legacy orgs: free until migrated, never gated
1039
1048
  by the free paywall (--all: everyone who pays today)
1040
1049
  admin billing legacy unmark <org-id> --why "…" No longer legacy; kept with who, when and why
1050
+ admin billing legacy review | decide <org-id> keep|free|test --why "…" [--tokens N]
1051
+ The legacy orgs no rule decided, most used first;
1052
+ decide each (free: a staff grant; test: a test org)
1041
1053
  admin billing free exposure | backfill --why "…" [--apply]
1042
1054
  Who the free paywall would stop today; the one-time
1043
1055
  signup grant for self-serve orgs with none
1056
+ admin billing free grant <org-id> <tokens> --why "…" [--key k] | grants [--org <org-id>] | revoke <org-id> <ref> --why "…"
1057
+ Give an org free tokens (a Lago org: a one-off wallet),
1058
+ list staff grants, take one back; posted to #billing
1059
+ admin billing visitors opt-out --why "…" [--apply] Turn off identification switched on automatically on
1060
+ billing-gated orgs (owners opt back in); a dry run first
1061
+ admin billing desk [--json] The Billing desk: switches, failed payments, the
1062
+ nightly reconcile, refusals, signups, grants
1063
+ admin billing free preflight [--json] Who the paywall stops the moment it is enforced:
1064
+ out of tokens, low, paying but covered, undecided
1065
+ admin billing emails [--bounced] [--org <org-id>] [--limit N]
1066
+ The invoice and receipt emails we sent for Lago and
1067
+ what became of each, bounced first (--bounced: only
1068
+ bounced, marked as spam or failed). Read only.
1069
+ Needs spend:read.
1044
1070
  admin billing lago catalog [--apply] [--include-drafts]
1045
1071
  | provision <org-id> --plan starter|growth|scale [--ratio 1|2|4|8 (8 needs --why "…")] [--complimentary N] [--stripe-customer cus_…] [--start ISO] [--review D]
1046
1072
  | reconcile [--org <org-id>] | forward
@@ -1081,6 +1107,7 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
1081
1107
  | collections [--org-ids a,b | --account-stages won,active]
1082
1108
  | delivery-flags [--org-ids a,b | --account-stages won,active] [--include collections] [--since 2026-10-19T20:00:00Z]
1083
1109
  | pulse [--ids a,b] [--since 2026-10-19T20:00:00Z] how each client is doing, worst churn risk first
1110
+ | client-health [--since 2026-10-19T20:00:00Z] can we reach each fleet client in Slack, problems first
1084
1111
  | case <account-id> [--outcome <outcome-id>]
1085
1112
  | onboard <account-id> --domain acme.com [--name "Acme"] [--site "<direction>"]… [--sites N]
1086
1113
  [--slack a@acme.com,b@acme.com] [--invite a@acme.com[:admin]]… [--no-checklist]
@@ -14,11 +14,11 @@
14
14
  // The old names — evals, eval-add, eval-set, proposals, propose-eval, capture-eval, reject-eval — still work.)
15
15
  // admin evals scoreboard|cases|runs|run|triage|guard|retire … (fleet:read / tuning:experiment)
16
16
  // admin fleet-experiments list|articles|clients|mark|unmark|new|assign|assign-eligible|assign-orgs|spin-up|apply|start|stop|decide … (fleet:read / fleet:experiment)
17
- // admin crm import|capture|outreach|signals|record|signal|add|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|case|onboard|onboarding|retry-onboarding|onboard-plan|payment-link … (crm:read / crm:write)
17
+ // admin crm import|capture|outreach|signals|record|signal|add|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|client-health|case|onboard|onboarding|retry-onboarding|onboard-plan|payment-link … (crm:read / crm:write)
18
18
  // admin spend summary|reconcile|pnl|margin|pricing|entries|add|import|usage|remove|reference|stripe-sync|services|service … (spend:read / spend:write)
19
19
  // admin brand-detection <org-id> (fleet:read)
20
20
  // admin brand-detection <org-id> [--term t]... [--exact t]... [--exclude p]... [--note "…"] | --clear [--note "…"] (fleet:instrument)
21
- // admin recipes list|show|vocab|export|import|save|delete … (recipes:read / recipes:write)
21
+ // admin recipes list|show|runs|vocab|export|import|save|delete … (recipes:read / recipes:write)
22
22
  // admin letterpress settings|flip|set … (recipes:read / recipes:write)
23
23
  // admin demo guide|list|show|set|reset|check … (demo:read / demo:write)
24
24
  // admin models runs|run|star|unstar|scoreboard|requests|request|sampling … (models:read / models:write)
@@ -3463,7 +3463,7 @@ async function cmdAdminCrm(ctx) {
3463
3463
  r.headline
3464
3464
  ? `${r.headline.month}: NRR ${pct(r.headline.nrr)} · GRR ${pct(r.headline.grr)} · expansion ${usd(r.headline.expansionCents)} · avg ${r.headline.avgCents == null ? "—" : usd(r.headline.avgCents)}/client`
3465
3465
  : "No complete month yet.",
3466
- `Clients counted: ${r.coverage.counted} (${r.coverage.stripe} Stripe, ${r.coverage.deal} deal) · comp ${r.coverage.comp} · ${usd(r.coverage.countedCents)}/mo`,
3466
+ `Clients counted: ${r.coverage.counted} (${r.coverage.lago ?? 0} Lago plan, ${r.coverage.stripe} Stripe, ${r.coverage.deal} deal) · comp ${r.coverage.comp} · ${usd(r.coverage.countedCents)}/mo`,
3467
3467
  "",
3468
3468
  ...r.periods.map(
3469
3469
  (p) =>
@@ -3737,6 +3737,33 @@ async function cmdAdminCrm(ctx) {
3737
3737
  );
3738
3738
  });
3739
3739
  }
3740
+ case "client-health": {
3741
+ // admin crm client-health [--since <ISO time, e.g. 2026-10-19T20:00:00Z>]
3742
+ // — can we reach each fleet client in Slack? Clients with something wrong first,
3743
+ // then every client without a channel. From a snapshot (~10 min); --since skips one older than that.
3744
+ const params = new URLSearchParams(compact({ since: flagStr(flags.since) }));
3745
+ return out(await staffRequest(ctx, "GET", `/api/superadmin/client-health?${params}`), (r) => {
3746
+ const flag = (f) =>
3747
+ f.kind === "invite_expired"
3748
+ ? `invitation expired (${f.emails.join(", ")})`
3749
+ : f.kind === "invite_pending"
3750
+ ? `invitation unanswered ${f.oldestDays}d (${f.emails.join(", ")})`
3751
+ : f.kind === "nobody_joined"
3752
+ ? "nobody from the client has joined"
3753
+ : `everyone left (${f.emails.join(", ")})`;
3754
+ const asOf = r.snapshot
3755
+ ? `(as of ${r.snapshot.computedAt}${r.snapshot.stale ? ", STALE: the refresh is failing" : ""})\n`
3756
+ : "";
3757
+ return [
3758
+ `${asOf}${r.covered} of ${r.total} fleet clients have a Slack channel`,
3759
+ ...r.atRisk.map((a) => `risk ${a.orgName} ${a.flags.map(flag).join("; ")} ${a.orgId}`),
3760
+ ...r.channels
3761
+ .filter((c) => c.state === "bot_missing")
3762
+ .map((c) => `no bot ${c.orgName} the Watchdog has never seen ${c.channelId} ${c.orgId}`),
3763
+ ...r.missingChannel.map((m) => `no room ${m.orgName} ${m.orgId}`),
3764
+ ].join("\n");
3765
+ });
3766
+ }
3740
3767
  case "case": {
3741
3768
  // admin crm case <account-id> [--outcome <id>] — the 90 days before an outcome, or before today.
3742
3769
  if (!id) throw new CliError("Usage: admin crm case <account-id> [--outcome <outcome-id>]");
@@ -3851,7 +3878,7 @@ async function cmdAdminCrm(ctx) {
3851
3878
  }
3852
3879
  default:
3853
3880
  throw new CliError(
3854
- "Usage: admin crm import|capture|outreach|signals|record|signal|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|case|onboard|onboarding|retry-onboarding|onboard-plan|prospect-org|prospect-orgs|payment-link … (see --help)"
3881
+ "Usage: admin crm import|capture|outreach|signals|record|signal|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|client-health|case|onboard|onboarding|retry-onboarding|onboard-plan|prospect-org|prospect-orgs|payment-link … (see --help)"
3855
3882
  );
3856
3883
  }
3857
3884
  }
@@ -4986,26 +5013,50 @@ async function cmdAdminRepublish(ctx) {
4986
5013
 
4987
5014
  const RECIPES = "/api/superadmin/recipes";
4988
5015
  /** The fields a recipe file carries: what import_recipes reads back. */
4989
- const RECIPE_FILE_FIELDS = ["id", "name", "recipe", "when_to_use", "when_not_to_use", "weight"];
5016
+ const RECIPE_FILE_FIELDS = [
5017
+ "id",
5018
+ "name",
5019
+ "description",
5020
+ "recipe",
5021
+ "when_to_use",
5022
+ "when_not_to_use",
5023
+ "weight",
5024
+ "approaches",
5025
+ "variations",
5026
+ ];
4990
5027
  const RECIPES_USAGE =
4991
- "Usage: admin recipes list [--approach seo|geo|agent_conviction|inbound_conversion|outbound|other] | show <id|name> | vocab | stats | export [--out <file>] | import <file> [--dry-run] | save [<id>] [--file <recipe.json>] [--name …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] | delete <id> --yes";
5028
+ "Usage: admin recipes list [--approach seo|geo|agent_conviction|inbound_conversion|outbound|other] | show <id|name> | runs <id|name> [--days 1..90] [--limit n] | vocab | stats | export [--out <file>] | import <file> [--dry-run] | save [<id>] [--file <recipe.json>] [--name …] [--description …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo,…] | delete <id> --yes";
4992
5029
 
4993
5030
  const recipeForFile = (r) => Object.fromEntries(RECIPE_FILE_FIELDS.map((k) => [k, r[k]]));
4994
5031
 
4995
- /** A recipe's approaches (read from its words by the server), or "other". */
5032
+ /** A recipe's approaches (its tags), or "other". */
4996
5033
  const recipeApproaches = (r) => (r.approaches?.length ? r.approaches.join(", ") : "other");
4997
5034
 
5035
+ /** Every variation of a recipe, its own first; an untitled one takes the recipe's name. */
5036
+ const recipeVariations = (r) => [
5037
+ r,
5038
+ ...(r.variations ?? []).map((v) => ({ ...v, name: v.name || r.name, description: v.description ?? "" })),
5039
+ ];
5040
+
4998
5041
  function recipeLine(r) {
4999
- return `${String(r.weight).padStart(2)}/10 ${r.name} [${recipeApproaches(r)}] ${r.id}`;
5042
+ const more = r.variations?.length ? ` ${r.variations.length + 1} variations` : "";
5043
+ return `${String(r.weight).padStart(2)}/10 ${r.name} [${recipeApproaches(r)}]${more} ${r.id}`;
5000
5044
  }
5001
5045
 
5002
5046
  function recipeDetail(r) {
5047
+ const variations = recipeVariations(r);
5048
+ const fields = (v, pad) => [
5049
+ `${pad}description: ${v.description || "—"}`,
5050
+ `${pad}recipe: ${v.recipe || "—"}`,
5051
+ `${pad}when to use: ${v.when_to_use || "—"}`,
5052
+ `${pad}when not to use: ${v.when_not_to_use || "—"}`,
5053
+ ];
5003
5054
  return [
5004
5055
  `${r.name} weight ${r.weight}/10 ${r.id}`,
5005
- ...(r.approaches ? [` approaches: ${recipeApproaches(r)}`] : []),
5006
- ` recipe: ${r.recipe || "—"}`,
5007
- ` when to use: ${r.when_to_use || "—"}`,
5008
- ` when not to use: ${r.when_not_to_use || "—"}`,
5056
+ ` approaches: ${recipeApproaches(r)}`,
5057
+ ...(variations.length > 1
5058
+ ? variations.flatMap((v, i) => [` variation ${i + 1}: ${v.name}`, ...fields(v, " ")])
5059
+ : fields(r, " ")),
5009
5060
  ].join("\n");
5010
5061
  }
5011
5062
 
@@ -5036,10 +5087,16 @@ function recipeFromFlags(flags) {
5036
5087
  return compact({
5037
5088
  ...compact(recipeForFile(base)),
5038
5089
  name: flagStr(flags.name),
5090
+ description: flagStr(flags.description),
5039
5091
  recipe: flagStr(flags.recipe),
5040
5092
  when_to_use: flagStr(flags["when-to-use"]),
5041
5093
  when_not_to_use: flagStr(flags["when-not-to-use"]),
5042
5094
  weight: flagNum(flags.weight),
5095
+ // --approaches seo,geo sets the tags; --approaches "" clears them.
5096
+ approaches: flagStr(flags.approaches)
5097
+ ?.split(",")
5098
+ .map((a) => a.trim())
5099
+ .filter(Boolean),
5043
5100
  });
5044
5101
  }
5045
5102
 
@@ -5284,6 +5341,27 @@ async function cmdAdminRecipes(ctx) {
5284
5341
  printResult(io, flags, { recipe }, (r) => recipeDetail(r.recipe));
5285
5342
  return 0;
5286
5343
  }
5344
+ case "runs": {
5345
+ const key = requirePositional(positionals, 1, "id|name");
5346
+ const recipe = (await all()).find((r) => r.id === key || r.name === key);
5347
+ if (!recipe) throw new CliError(`No recipe with id or name "${key}".`);
5348
+ const q = new URLSearchParams();
5349
+ const days = flagNum(flags.days);
5350
+ const limit = flagNum(flags.limit);
5351
+ if (days !== undefined) q.set("days", String(days));
5352
+ if (limit !== undefined) q.set("limit", String(limit));
5353
+ const result = await staffRequest(ctx, "GET", `${RECIPES}/${recipe.id}/runs${q.size ? `?${q}` : ""}`);
5354
+ printResult(io, flags, result, (r) =>
5355
+ [
5356
+ `${r.recipe.name}: ${r.offered} run(s) had it over the last ${r.days} days, ${r.used} used it.`,
5357
+ ...r.runs.map(
5358
+ (run) =>
5359
+ `${run.used ? "✓ used" : " - "} ${run.created_at.slice(0, 16).replace("T", " ")} ${run.company.name ?? run.company.domain} (${run.company.domain}) ${run.ask}${run.started_by?.name ? ` by ${run.started_by.name}` : ""}${run.variations.length ? ` variation ${run.variations.join(", ")}` : ""} ${run.id}`
5360
+ ),
5361
+ ].join("\n")
5362
+ );
5363
+ return 0;
5364
+ }
5287
5365
  case "vocab": {
5288
5366
  const v = await staffRequest(ctx, "GET", `${RECIPES}/vocabulary`);
5289
5367
  printResult(io, flags, v, (r) =>
@@ -5359,7 +5437,8 @@ async function cmdAdminRecipes(ctx) {
5359
5437
  }
5360
5438
 
5361
5439
  const LAGO = "/api/superadmin/billing/lago";
5362
- const LAGO_USAGE = `Usage: admin billing lago <command>
5440
+ const LAGO_USAGE = `Usage: admin billing desk [--json] the Billing desk: switches, failed payments, reconcile, refusals, grants
5441
+ admin billing lago <command>
5363
5442
  catalog [--apply] [--include-drafts] what the plan catalog would change in Lago; --apply makes it so
5364
5443
  provision <org-id> --plan starter [--ratio 4] [--why "…" above 4x] [--complimentary 20000] [--stripe-customer cus_…] [--start 2026-11-02T00:00:00Z] [--review 2027-05-01]
5365
5444
  reconcile [--org <org-id>] Lago's tokens this period and last invoice against what we forwarded
@@ -5380,7 +5459,9 @@ const LAGO_USAGE = `Usage: admin billing lago <command>
5380
5459
 
5381
5460
  const LEGACY_USAGE = `Usage: admin billing legacy mark <org-id> --why "…" mark one org legacy (free until migrated)
5382
5461
  admin billing legacy mark --all --why "…" [--apply] every org that pays today; a dry run unless --apply
5383
- admin billing legacy unmark <org-id> --why "…" no longer legacy (kept with who, when and why)`;
5462
+ admin billing legacy unmark <org-id> --why "…" no longer legacy (kept with who, when and why)
5463
+ admin billing legacy review [--json] legacy orgs no rule decided, most used first, and the date they're decided by
5464
+ admin billing legacy decide <org-id> keep|free|test --why "…" [--tokens N] decide one (free: on free tokens; test: a test org)`;
5384
5465
 
5385
5466
  /**
5386
5467
  * admin billing legacy mark … — legacy orgs (decisions 2026-10-27): free until migrated, never gated
@@ -5390,6 +5471,36 @@ const LEGACY_USAGE = `Usage: admin billing legacy mark <org-id> --why "…"
5390
5471
  async function cmdAdminBillingLegacy(ctx) {
5391
5472
  const { flags, positionals, io } = ctx;
5392
5473
  if (positionals[1] === "unmark") return cmdAdminBillingLegacyUnmark(ctx);
5474
+ if (positionals[1] === "review") {
5475
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/legacy/review");
5476
+ printResult(io, flags, r, (x) => {
5477
+ const lines = [
5478
+ `${x.pending.length} legacy org(s) to decide by ${x.by} (${x.reviewed} reviewed so far), most used first:`,
5479
+ ];
5480
+ for (const o of x.pending)
5481
+ lines.push(
5482
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} ${o.events30d.toLocaleString("en-US")} events/30d${o.lastUsedAt ? `, last ${o.lastUsedAt.slice(0, 10)}` : ""} revenue=${o.revenueSource ?? "-"}`
5483
+ );
5484
+ return lines.join("\n");
5485
+ });
5486
+ return 0;
5487
+ }
5488
+ if (positionals[1] === "decide") {
5489
+ const [orgId, decision] = [positionals[2], positionals[3]];
5490
+ if (!orgId || !["keep", "free", "test"].includes(decision)) throw new CliError(LEGACY_USAGE);
5491
+ const why = flagStr(flags.why);
5492
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the decision.\n${LEGACY_USAGE}`);
5493
+ const tokens = flagStr(flags.tokens);
5494
+ const r = await staffPost(ctx, "/api/superadmin/billing/legacy/review", {
5495
+ orgId,
5496
+ decision,
5497
+ why,
5498
+ ...(tokens ? { tokens: Number(tokens.replace(/[,_]/g, "")) } : {}),
5499
+ });
5500
+ const words = { keep: "kept legacy", free: "on free tokens", test: "marked a test org" };
5501
+ printResult(io, flags, r, (x) => `${orgId}: ${words[x.decision]}${x.grantRef ? ` (${x.grantRef})` : ""}.`);
5502
+ return 0;
5503
+ }
5393
5504
  if (positionals[1] !== "mark") throw new CliError(LEGACY_USAGE);
5394
5505
  const why = flagStr(flags.why);
5395
5506
  if (!why) throw new CliError(`Say why (--why "…"): it is kept with the mark.\n${LEGACY_USAGE}`);
@@ -5427,9 +5538,45 @@ async function cmdAdminBillingLegacyUnmark(ctx) {
5427
5538
  return 0;
5428
5539
  }
5429
5540
 
5541
+ const VISITORS_USAGE = `Usage: admin billing visitors opt-out --why "…" [--apply] turn off identification switched on automatically on billing-gated orgs (owners opt back in); a dry run unless --apply`;
5542
+
5543
+ /**
5544
+ * admin billing visitors opt-out — identification is billed per person, so sites switched on
5545
+ * automatically on an org on free tokens or billed on Lago are turned off once, as staff with who and
5546
+ * why; legacy, internal, unassigned and demo orgs and every owner-set site are left alone. A dry run
5547
+ * lists them unless --apply (lib/visitors/identification-opt-out.ts).
5548
+ */
5549
+ async function cmdAdminBillingVisitors(ctx) {
5550
+ const { flags, positionals, io } = ctx;
5551
+ if (positionals[1] !== "opt-out") throw new CliError(VISITORS_USAGE);
5552
+ const why = flagStr(flags.why);
5553
+ if (!why) throw new CliError(`Say why (--why "…").\n${VISITORS_USAGE}`);
5554
+ const r = await staffPost(ctx, "/api/superadmin/billing/visitors/opt-out", { dry: !flagBool(flags.apply), why });
5555
+ printResult(io, flags, r, (x) => {
5556
+ const row = (s) => ` ${s.domain ?? s.siteId} ${s.orgName ?? s.orgId.slice(0, 8)} (${s.standing})`;
5557
+ const lines = [
5558
+ `${x.dry ? "Would turn off" : "Turned off"} ${x.changed.length} site(s):`,
5559
+ ...x.changed.map(row),
5560
+ ];
5561
+ if (x.failed.length) lines.push(`Failed ${x.failed.length}:`, ...x.failed.map((f) => `${row(f)} ${f.error}`));
5562
+ if (x.kept.length)
5563
+ lines.push(
5564
+ `Left on ${x.kept.length} (auto, not billing-gated or a demo):`,
5565
+ ...x.kept.map((k) => `${row(k)} ${k.why}`)
5566
+ );
5567
+ if (x.dry) lines.push("Nothing written. Run again with --apply.");
5568
+ return lines.join("\n");
5569
+ });
5570
+ return 0;
5571
+ }
5572
+
5430
5573
  const FREE_USAGE = `Usage: admin billing free exposure [--json] who the free paywall covers, and who is unassigned
5431
5574
  admin billing free backfill --why "…" [--apply] signup grant for self-serve orgs with none; a dry run unless --apply
5432
- admin billing free repair-subjects --why "…" [--apply] staff-address signup subjects fixed, refused orgs granted (R1); a dry run unless --apply`;
5575
+ admin billing free repair-subjects --why "…" [--apply] staff-address signup subjects fixed, refused orgs granted (R1); a dry run unless --apply
5576
+ admin billing free grant <org-id> <tokens> --why "…" [--key k] give an org free tokens (a Lago org: a one-off wallet); the same key is one grant
5577
+ admin billing free grants [--org <org-id>] [--limit n] staff grants, newest first, live and revoked
5578
+ admin billing free revoke <org-id> <ref> --why "…" take a staff grant back (ref from the list: grant:<id> or wallet:staff_…)
5579
+ admin billing free preflight [--json] who the paywall stops the moment it is enforced, and whether it is ready`;
5433
5580
 
5434
5581
  const EXPOSURE_WORDS = {
5435
5582
  needs_legacy: "pay today: need a legacy mark (admin billing legacy mark --all)",
@@ -5442,7 +5589,7 @@ const EXPOSURE_WORDS = {
5442
5589
  /**
5443
5590
  * admin billing free … — before LETTERBRACE_FREE_TOKENS is set: who the free paywall would stop
5444
5591
  * (exposure, reads only) and the one-time signup grant for self-serve orgs that predate it (backfill,
5445
- * a dry run unless --apply).
5592
+ * a dry run unless --apply). grant / grants / revoke: staff grants of free tokens (lib/billing/staff-grant.ts).
5446
5593
  */
5447
5594
  async function cmdAdminBillingFree(ctx) {
5448
5595
  const { flags, positionals, io } = ctx;
@@ -5462,6 +5609,37 @@ async function cmdAdminBillingFree(ctx) {
5462
5609
  });
5463
5610
  return 0;
5464
5611
  }
5612
+ if (positionals[1] === "preflight") {
5613
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/free-tokens/preflight");
5614
+ printResult(io, flags, r, (x) => {
5615
+ const n = (v) => Number(v).toLocaleString("en-US");
5616
+ const row = (o) =>
5617
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} ${n(o.availableTokens)} left of ${n(o.grantedTokens)} (used ${n(o.usedTokens)}${o.heldTokens ? `, held ${n(o.heldTokens)}` : ""})`;
5618
+ const lines = [
5619
+ `Free paywall: ${x.mode}. ${x.ready ? "READY to enforce." : "NOT ready to enforce:"}`,
5620
+ ...x.blockers.map((b) => ` - ${b}`),
5621
+ `Covered: ${n(x.covered)} free org(s).`,
5622
+ `Refused the moment it's enforced (0 or less left): ${x.refusedNow.length}`,
5623
+ ...x.refusedNow.map(row),
5624
+ `Running low: ${x.low.length}`,
5625
+ ...x.low.map(row),
5626
+ ];
5627
+ if (x.wronglyCovered.length) {
5628
+ lines.push(`Pay us but covered: ${x.wronglyCovered.length}`);
5629
+ for (const o of x.wronglyCovered)
5630
+ lines.push(
5631
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} revenue=${o.revenueSource ?? "-"}${o.paying ? " paying" : ""}`
5632
+ );
5633
+ }
5634
+ if (x.undecided.length) {
5635
+ lines.push(`Undecided: ${x.undecided.length}`);
5636
+ for (const o of x.undecided)
5637
+ lines.push(` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} origin=${o.origin ?? "-"}`);
5638
+ }
5639
+ return lines.join("\n");
5640
+ });
5641
+ return 0;
5642
+ }
5465
5643
  if (positionals[1] === "backfill") {
5466
5644
  const why = flagStr(flags.why);
5467
5645
  if (!why) throw new CliError(`Say why (--why "…"): it is kept with each grant.\n${FREE_USAGE}`);
@@ -5500,14 +5678,176 @@ async function cmdAdminBillingFree(ctx) {
5500
5678
  });
5501
5679
  return 0;
5502
5680
  }
5681
+ if (positionals[1] === "grant") {
5682
+ const [orgId, tokensArg] = [positionals[2], positionals[3]];
5683
+ const tokens = Number(String(tokensArg ?? "").replace(/[,_]/g, ""));
5684
+ if (!orgId || !Number.isInteger(tokens) || tokens <= 0) throw new CliError(FREE_USAGE);
5685
+ const why = flagStr(flags.why);
5686
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the grant.\n${FREE_USAGE}`);
5687
+ const key = flagStr(flags.key);
5688
+ const r = await staffPost(ctx, "/api/superadmin/billing/free-tokens/grants", {
5689
+ orgId,
5690
+ tokens,
5691
+ why,
5692
+ ...(key ? { key } : {}),
5693
+ });
5694
+ printResult(io, flags, r, (x) => {
5695
+ const what = x.kind === "wallet" ? "as a one-off wallet on Lago" : "as a free-token grant";
5696
+ const lines = [
5697
+ x.granted
5698
+ ? `Gave ${x.tokens.toLocaleString("en-US")} tokens ${what} (${x.ref}).`
5699
+ : `Already given under this key (${x.ref}); nothing new.`,
5700
+ ];
5701
+ if (x.standing.before !== x.standing.after)
5702
+ lines.push(`Standing: ${x.standing.before} -> ${x.standing.after} (now on the free paywall).`);
5703
+ return lines.join("\n");
5704
+ });
5705
+ return 0;
5706
+ }
5707
+ if (positionals[1] === "grants") {
5708
+ const org = flagStr(flags.org);
5709
+ const limit = flagStr(flags.limit);
5710
+ const qs = new URLSearchParams({ ...(org ? { orgId: org } : {}), ...(limit ? { limit } : {}) });
5711
+ const r = await staffRequest(
5712
+ ctx,
5713
+ "GET",
5714
+ `/api/superadmin/billing/free-tokens/grants${qs.size ? `?${qs}` : ""}`
5715
+ );
5716
+ printResult(io, flags, r, (x) => {
5717
+ if (!x.grants.length) return "No staff grants.";
5718
+ return x.grants
5719
+ .map(
5720
+ (g) =>
5721
+ `${g.createdAt.slice(0, 10)} ${g.ref.padEnd(24)} ${String(g.tokens.toLocaleString("en-US")).padStart(9)} ${g.orgName ?? g.orgId.slice(0, 8)} by ${g.grantedBy}: ${g.reason ?? "-"}` +
5722
+ (g.revokedAt
5723
+ ? ` [revoked ${g.revokedAt.slice(0, 10)} by ${g.revokedBy}: ${g.revokeReason}]`
5724
+ : "")
5725
+ )
5726
+ .join("\n");
5727
+ });
5728
+ return 0;
5729
+ }
5730
+ if (positionals[1] === "revoke") {
5731
+ const [orgId, ref] = [positionals[2], positionals[3]];
5732
+ if (!orgId || !ref) throw new CliError(FREE_USAGE);
5733
+ const why = flagStr(flags.why);
5734
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the revoke.\n${FREE_USAGE}`);
5735
+ const r = await staffRequest(ctx, "DELETE", "/api/superadmin/billing/free-tokens/grants", { orgId, ref, why });
5736
+ printResult(
5737
+ io,
5738
+ flags,
5739
+ r,
5740
+ (x) =>
5741
+ `Took back ${x.revoked.tokens.toLocaleString("en-US")} tokens (${x.revoked.ref}) from ${x.revoked.orgName ?? orgId}.`
5742
+ );
5743
+ return 0;
5744
+ }
5503
5745
  throw new CliError(FREE_USAGE);
5504
5746
  }
5505
5747
 
5748
+ /**
5749
+ * admin billing desk [--json] — the Billing desk in one read (lib/billing/desk.ts, docs/billing/billing-desk.md):
5750
+ * the switches, what needs a person now, and the week's numbers. The same as GET /api/superadmin/billing/desk
5751
+ * and MCP billing_desk.
5752
+ */
5753
+ async function cmdAdminBillingDesk(ctx) {
5754
+ const { flags, io } = ctx;
5755
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/desk");
5756
+ printResult(io, flags, r, (d) => {
5757
+ const n = (x) => Number(x ?? 0).toLocaleString("en-US");
5758
+ const sw = d.switches;
5759
+ const signup = sw.lagoSignup.active ? "on" : sw.lagoSignup.from ? `from ${sw.lagoSignup.from}` : "off";
5760
+ const forward = sw.forwarding.on ? "on" : "off";
5761
+ const lines = [
5762
+ `Switches: spend cap ${sw.tokenGate}${sw.enforcedOrgs ? ` (+${sw.enforcedOrgs} enforced)` : ""} · free paywall ${sw.freeTokens} · Lago signups ${signup} · forwarding ${forward} · failed payments ${sw.dunning}${sw.lagoConfigured ? "" : " · Lago NOT configured"}`,
5763
+ `Signups: ${n(d.signups.grants.today)} today, ${n(d.signups.grants.week)} this week (${n(d.signups.grants.agentWeek)} by an agent) · Lago this week: ${
5764
+ Object.entries(d.signups.lagoWeek)
5765
+ .filter(([, c]) => c > 0)
5766
+ .map(([s, c]) => `${c} ${s}`)
5767
+ .join(", ") || "none"
5768
+ }`,
5769
+ ];
5770
+ const rec = d.reconcile;
5771
+ const recWhen = rec.meta.computedAt ? rec.meta.computedAt.slice(0, 16).replace("T", " ") : "never";
5772
+ const drifting = (rec.result?.orgs ?? []).filter((o) => o.status !== "ok" && o.status !== "not_started");
5773
+ lines.push(
5774
+ `Reconcile (${recWhen}${rec.meta.stale ? ", STALE" : ""}): ${rec.result ? (rec.result.ok ? `all ${rec.result.orgs.length} agree` : `${drifting.length} need a look`) : "no result yet"}`
5775
+ );
5776
+ for (const o of drifting) lines.push(` ${o.orgId.slice(0, 8)} ${o.status} drift ${o.drift ?? "-"}`);
5777
+ lines.push(`Failed payments open: ${d.payments.length}`);
5778
+ for (const p of d.payments)
5779
+ lines.push(
5780
+ ` ${p.orgName ?? p.orgId.slice(0, 8)} ${p.invoiceNumber ?? p.invoiceId} $${(p.amountCents / 100).toFixed(2)} ${p.status} ${p.attempts} tries${p.lastError ? `: ${p.lastError}` : ""}`
5781
+ );
5782
+ if (d.signups.stuck.length) lines.push(`Stuck signups: ${d.signups.stuck.length}`);
5783
+ for (const s of d.signups.stuck)
5784
+ lines.push(
5785
+ ` ${s.orgName ?? s.orgId.slice(0, 8)} ${s.planCode} ${s.status}${s.lastError ? `: ${s.lastError}` : ""}`
5786
+ );
5787
+ const refusalWords = Object.entries(d.refusals.byReason)
5788
+ .map(([k, c]) => `${c} ${k}`)
5789
+ .join(", ");
5790
+ lines.push(`Gate refusals this week: ${n(d.refusals.total)}${refusalWords ? ` (${refusalWords})` : ""}`);
5791
+ for (const o of d.refusals.orgs.slice(0, 5))
5792
+ lines.push(` ${o.orgName ?? o.orgId.slice(0, 8)} ${o.count} ${o.reasons.join(", ")}`);
5793
+ lines.push(
5794
+ `Free paywall: ${n(d.exposure.counts.granted)} granted · ${d.exposure.waiting.length} waiting on a person (admin billing free exposure)`
5795
+ );
5796
+ if (d.capRequests.length) lines.push(`Cap requests this week: ${d.capRequests.length}`);
5797
+ if (d.termChanges.length)
5798
+ lines.push(`Scheduled term changes: ${d.termChanges.length} (admin billing lago changes)`);
5799
+ const live = d.grants.filter((g) => !g.revokedAt);
5800
+ lines.push(`Staff grants: ${live.length} live of the last ${d.grants.length} (admin billing free grants)`);
5801
+ if (d.emails)
5802
+ lines.push(
5803
+ `Invoice emails: ${d.emails.on ? "ours" : "Lago's"} · ${d.emails.problems.length} didn't arrive${d.emails.problems.length ? " (admin billing emails --bounced)" : ""}`
5804
+ );
5805
+ return lines.join("\n");
5806
+ });
5807
+ return 0;
5808
+ }
5809
+
5810
+ const EMAILS_USAGE = `Usage: admin billing emails [--bounced] [--org <org-id>] [--limit N]
5811
+ the invoice and receipt emails we sent for Lago and what became of each, bounced first
5812
+ (--bounced: only the ones that bounced, were marked as spam or failed)`;
5813
+
5814
+ /**
5815
+ * admin billing emails — the invoice and receipt emails we send for Lago (lib/billing/lago/invoice-emails.ts)
5816
+ * and what Resend said of each. Read only.
5817
+ */
5818
+ async function cmdAdminBillingEmails(ctx) {
5819
+ const { flags, positionals, io } = ctx;
5820
+ if (positionals.length > 1) throw new CliError(EMAILS_USAGE);
5821
+ const params = new URLSearchParams(
5822
+ compact({
5823
+ orgId: flagStr(flags.org),
5824
+ bounced: flagBool(flags.bounced) ? "true" : undefined,
5825
+ limit: flagNum(flags.limit) !== undefined ? String(flagNum(flags.limit)) : undefined,
5826
+ })
5827
+ );
5828
+ const result = await staffRequest(ctx, "GET", `/api/superadmin/billing/emails${params.size ? `?${params}` : ""}`);
5829
+ printResult(io, flags, result, (r) =>
5830
+ [
5831
+ `Invoice and receipt emails: ${r.on ? "on (we send them)" : "off (Lago sends them)"}`,
5832
+ ...(r.emails.length
5833
+ ? r.emails.map(
5834
+ (e) =>
5835
+ ` ${e.status.padEnd(10)} ${e.kind.padEnd(7)} ${e.invoiceNumber ?? e.invoiceId} ${e.orgName ?? e.orgId} $${(e.amountCents / 100).toFixed(2)} ${e.to.join(", ") || "(nobody)"} ${e.sentAt ?? e.createdAt}${e.error ? ` (${e.error})` : ""}`
5836
+ )
5837
+ : [flagBool(flags.bounced) ? " None bounced." : " None sent yet."]),
5838
+ ].join("\n")
5839
+ );
5840
+ return 0;
5841
+ }
5842
+
5506
5843
  /** admin billing lago … — staff operations on Lago (docs/billing/lago-integration.md). */
5507
5844
  async function cmdAdminBilling(ctx) {
5508
5845
  const { flags, positionals, io } = ctx;
5509
5846
  if (positionals[0] === "legacy") return cmdAdminBillingLegacy(ctx);
5510
5847
  if (positionals[0] === "free") return cmdAdminBillingFree(ctx);
5848
+ if (positionals[0] === "desk") return cmdAdminBillingDesk(ctx);
5849
+ if (positionals[0] === "emails") return cmdAdminBillingEmails(ctx);
5850
+ if (positionals[0] === "visitors") return cmdAdminBillingVisitors(ctx);
5511
5851
  if (positionals[0] !== "lago") throw new CliError(LAGO_USAGE);
5512
5852
  const sub = positionals[1];
5513
5853
  switch (sub) {
@@ -87,7 +87,8 @@ const ARGS = {
87
87
  // --with-preview: the PR opens straight away and a preview of the change stays up next to it.
88
88
  with_preview: { flag: "with-preview", type: "bool" },
89
89
  // --harness claude-code|letterpress-1: the coding agent; omitted, the deployment's default.
90
- harness: { flag: "harness", enum: ["claude-code", "letterpress-1"] },
90
+ // codex (OpenAI's Codex CLI) runs only on a test organization, for the harness evals.
91
+ harness: { flag: "harness", enum: ["claude-code", "letterpress-1", "codex"] },
91
92
  // --again: start it even when an open change already asks for the same thing.
92
93
  again: { flag: "again", type: "bool" },
93
94
  // --verifier / --no-verifier: review the change before it goes out; omitted, the deployment's choice.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.168.1",
3
+ "version": "0.174.0",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",