@letterstory/cli 0.154.1 → 0.158.1

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
@@ -66,7 +66,7 @@ import {
66
66
 
67
67
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
68
68
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
69
- export const VERSION = "0.154.1";
69
+ export const VERSION = "0.158.1";
70
70
 
71
71
  // Flags that never take a value. Listing them explicitly means `deploy get --json <id>`
72
72
  // can't accidentally swallow the id as --json's value. Every `type: "bool"` flag (and its
@@ -370,6 +370,35 @@ export function binName() {
370
370
  return process.env.LETTERSTORY_CLI_BRAND === "phantom" ? "phantom" : "letterstory";
371
371
  }
372
372
 
373
+ /**
374
+ * The help entries for the longest leading part of `positionals` that names any: an entry is a line
375
+ * indented two spaces, with the lines indented further under it. Null when none matches.
376
+ * @param {string} help
377
+ * @param {string[]} positionals
378
+ * @returns {string | null}
379
+ */
380
+ export function helpFor(help, positionals) {
381
+ const lines = help.split("\n");
382
+ for (let k = positionals.length; k >= 1; k--) {
383
+ const prefix = positionals.slice(0, k).join(" ");
384
+ const out = [];
385
+ let taking = false;
386
+ for (const line of lines) {
387
+ if (/^ \S/.test(line)) {
388
+ const text = line.slice(2);
389
+ taking = text === prefix || text.startsWith(`${prefix} `);
390
+ if (taking) out.push(line);
391
+ } else if (taking && /^ +\S/.test(line)) {
392
+ out.push(line);
393
+ } else {
394
+ taking = false;
395
+ }
396
+ }
397
+ if (out.length > 0) return out.join("\n");
398
+ }
399
+ return null;
400
+ }
401
+
373
402
  function buildHelp(bin) {
374
403
  const heading =
375
404
  bin === "phantom"
@@ -1139,6 +1168,8 @@ Seers (event-driven signals -> drafts):
1139
1168
  the admins for more
1140
1169
  org billing usage This period by product and collection: quantities,
1141
1170
  and tokens and dollars when billed by usage
1171
+ org billing invoices Every invoice (paid, open, failed, refunded) and the
1172
+ next one: when it issues and what it comes to
1142
1173
  org linear [teams [--team <id|key>] | set --team <id|key> [--project <id>|none] | disconnect]
1143
1174
  Where Letter files Linear issues (connect in Settings)
1144
1175
  org diff <file|dir> What applying a bundle would change (reads only)
@@ -1675,7 +1706,11 @@ export async function run(argv, io = defaultIo()) {
1675
1706
  return 0;
1676
1707
  }
1677
1708
  if (!command || command === "help" || flags.help) {
1678
- io.log(buildHelp(bin));
1709
+ // `<command> … --help` shows that command's own lines, not the whole manual's first screen
1710
+ // (billing agent pass AGENT-5: `org billing request --help` printed Auth and Collections).
1711
+ const help = buildHelp(bin);
1712
+ const own = command && command !== "help" ? helpFor(help, positionals) : null;
1713
+ io.log(own ? `${own}\n\nRun \`${bin} help\` for every command.` : help);
1679
1714
  return 0;
1680
1715
  }
1681
1716
 
@@ -5473,9 +5473,12 @@ async function cmdAdminBilling(ctx) {
5473
5473
  compact({ orgId, cap_usd: capUsd, reason: flagStr(flags.why) })
5474
5474
  );
5475
5475
  printResult(io, flags, result, (r) =>
5476
- r.spendCap
5477
- ? `Spend cap: $${r.spendCap.usd} of overage a month (alerts: ${r.alert}).`
5478
- : "No spend cap: overage is on."
5476
+ [
5477
+ r.spendCap
5478
+ ? `Spend cap: $${r.spendCap.usd} of overage a month (alerts: ${r.alert}).`
5479
+ : "No spend cap: overage is on.",
5480
+ ...(r.standing?.note ? [r.standing.note] : []),
5481
+ ].join("\n")
5479
5482
  );
5480
5483
  return 0;
5481
5484
  }
@@ -29,6 +29,7 @@ export const ARGS = {
29
29
  get_org_config_source: {},
30
30
  get_billing_payments: {},
31
31
  get_billing: {},
32
+ get_billing_invoices: {},
32
33
  set_billing_spend_cap: {
33
34
  cap_usd: { value: (_flags, positionals) => capFrom(requirePositional(positionals, 0, "dollars|off")) },
34
35
  reason: { flag: "why" },
@@ -114,7 +115,8 @@ const usd = (n) => `$${Number(n).toFixed(2)}`;
114
115
  * it is past due, and its failed payments (get_billing_payments). `org billing cap <dollars|off>`
115
116
  * sets the cap (set_billing_spend_cap, admins); `org billing card` links to Stripe's page for a new
116
117
  * card (update_billing_card, admins); `org billing request` asks the admins for more
117
- * (request_billing_tokens); `org billing usage` is this period by product and collection (get_billing).
118
+ * (request_billing_tokens); `org billing usage` is this period by product and collection (get_billing);
119
+ * `org billing invoices` is what was charged and the next invoice (get_billing_invoices).
118
120
  */
119
121
  async function orgBilling(ctx) {
120
122
  const { client, flags, io, positionals } = ctx;
@@ -123,9 +125,13 @@ async function orgBilling(ctx) {
123
125
  const args = argsFromFlags(ARGS.set_billing_spend_cap, flags, positionals.slice(1));
124
126
  const result = await client.callTool("set_billing_spend_cap", args);
125
127
  printResult(io, flags, result, (r) =>
126
- r.spendCap
127
- ? `Spend cap: ${usd(r.spendCap.usd)} of overage a month${r.spendCap.usd === 0 ? " (work stops at the allowance)" : ""}.${r.alert === "failed" ? " The alerts couldn't be moved; the cap holds." : ""}`
128
- : "No spend cap: overage is on."
128
+ [
129
+ r.spendCap
130
+ ? `Spend cap: ${usd(r.spendCap.usd)} of overage a month${r.spendCap.usd === 0 ? " (work stops at the allowance)" : ""}.${r.alert === "failed" ? " The alerts couldn't be moved; the cap holds." : ""}`
131
+ : "No spend cap: overage is on.",
132
+ // The period as the cap leaves it: a cap under the overage already used stops new work now.
133
+ ...(r.standing?.note ? [r.standing.note] : []),
134
+ ].join("\n")
129
135
  );
130
136
  return 0;
131
137
  }
@@ -168,6 +174,15 @@ async function orgBilling(ctx) {
168
174
  printResult(io, flags, result, (r) => `Asked ${r.emailedTo} admin${r.emailedTo === 1 ? "" : "s"} for more.`);
169
175
  return 0;
170
176
  }
177
+ if (positionals[0] === "invoices") {
178
+ refuseUnknownFlags(ctx, ARGS.get_billing_invoices, []);
179
+ const result = await client.callTool(
180
+ "get_billing_invoices",
181
+ argsFromFlags(ARGS.get_billing_invoices, flags, [])
182
+ );
183
+ printResult(io, flags, result, billingInvoicesText);
184
+ return 0;
185
+ }
171
186
  if (positionals[0] === "usage") {
172
187
  refuseUnknownFlags(ctx, ARGS.get_billing, []);
173
188
  const result = await client.callTool("get_billing", argsFromFlags(ARGS.get_billing, flags, []));
@@ -207,24 +222,55 @@ export function billingAccountText(r) {
207
222
  ` ${p.invoiceNumber ?? p.invoiceId} $${(p.amountCents / 100).toFixed(2)} ${p.status}${p.nextAttemptAt ? `, next try ${p.nextAttemptAt}` : ""}${p.payUrl ? ` pay: ${p.payUrl}` : ""}`
208
223
  )
209
224
  : ["No failed payments."]),
225
+ r.plan ? "Every invoice (paid too) and the next one: letterstory org billing invoices." : null,
210
226
  ]
211
227
  .filter((line) => line !== null)
212
228
  .join("\n");
213
229
  }
214
230
 
231
+ const INVOICE_KIND = {
232
+ subscription: "plan",
233
+ one_off: "one-off",
234
+ overage_top_up: "overage top-up",
235
+ overage: "overage",
236
+ other: "other",
237
+ };
238
+
239
+ /** `org billing invoices` as text: the next invoice, then every invoice, newest first. */
240
+ function billingInvoicesText(r) {
241
+ if (!r.billed) return "Not billed by usage: no invoices.";
242
+ const lines = [];
243
+ if (r.upcoming)
244
+ lines.push(
245
+ `Next invoice ${r.upcoming.issuesOn}: ${usd(r.upcoming.totalUsd)} (plan ${usd(r.upcoming.planFeeUsd)} in advance + overage ${usd(r.upcoming.overageUsd)}${r.upcoming.overagePrepaidUsd ? `, ${usd(r.upcoming.overagePrepaidUsd)} of it already charged` : ""}).`,
246
+ ""
247
+ );
248
+ if (r.invoices.length === 0) return [...lines, "No invoices yet."].join("\n");
249
+ for (const i of r.invoices) {
250
+ const when = i.paidAt ? `paid ${i.paidAt.slice(0, 10)}` : i.dueOn ? `due ${i.dueOn}` : "";
251
+ lines.push(
252
+ `${i.issuedOn ?? ""} ${i.number} ${INVOICE_KIND[i.kind] ?? i.kind} ${usd(i.amountUsd)} ${i.status.replace("_", " ")}${when ? ` ${when}` : ""}${i.refundedUsd ? ` refunded ${usd(i.refundedUsd)}` : ""}`
253
+ );
254
+ }
255
+ return lines.join("\n");
256
+ }
257
+
215
258
  const tokensOrQty = (p) => `${p.billableQuantity}${p.tokens === null ? "" : ` ${p.tokens} tokens`}`;
216
259
 
217
260
  /** `org billing usage` as text: the period, the totals, then each product and each collection. */
218
261
  function billingUsageText(r) {
219
262
  const lines = [
220
- `${r.plan ? `Plan: ${r.plan.name}${r.plan.ratio !== 1 ? ` (${r.plan.ratio}x)` : ""}. ` : ""}This period: ${r.period.from.slice(0, 10)} to ${r.period.to.slice(0, 10)}${r.period.basis === "ours" ? " (Lago unreadable: our own rating)" : ""}.`,
263
+ `${r.plan ? `Plan: ${r.plan.name}${r.plan.ratio !== 1 ? ` (${r.plan.ratio}x)` : ""}. ` : ""}This period: ${r.period.from.slice(0, 10)} to ${r.period.to.slice(0, 10)}${r.period.basis === "ours" ? " (Lago unreadable: our own rating)" : r.period.basis === "ours_split" ? " (split by product and collection by our own rating: Lago has the total, no breakdown yet)" : ""}.`,
221
264
  ];
222
265
  if (r.tokens)
223
266
  lines.push(
224
267
  `Tokens: ${r.tokens.used} used of ${r.tokens.allowance} included${r.tokens.complimentary ? ` (+${r.tokens.complimentary} complimentary)` : ""}${r.tokens.arriving ? ` (${r.tokens.arriving} of them still being counted)` : ""}${r.tokens.running ? `, ${r.tokens.running} held by running work` : ""}.`
225
268
  );
226
269
  else lines.push("Not billed by usage: quantities only.");
227
- if (r.usd) lines.push(`Plan fee ${usd(r.usd.planFee)}; overage so far ${usd(r.usd.overage)}.`);
270
+ if (r.usd)
271
+ lines.push(
272
+ `Plan fee ${usd(r.usd.planFee)}; overage so far ${usd(r.usd.overage)}. What was charged and the next invoice: letterstory org billing invoices.`
273
+ );
228
274
  if (r.byProduct.length === 0) return [...lines, "No usage this period."].join("\n");
229
275
  lines.push("", "By product:", ...r.byProduct.map((p) => ` ${p.label} ${tokensOrQty(p)}`));
230
276
  lines.push("", "By collection:");
@@ -11,6 +11,9 @@
11
11
  // letterstory sim seed <id> --prompt "a 3-person content team with two blogs" --activate
12
12
  // letterstory sim seed <id> --use <seed-id|none>
13
13
  // letterstory sim limits <id> --daily-calls 5000 --daily-sessions 100
14
+ // letterstory sim runs-import --file /tmp/dr1/graded.json --tasks scripts/driven-runs/packs/letter-mcp/tasks.json --suite letter-mcp
15
+ // letterstory sim runs --live
16
+ // letterstory sim run <run-id>
14
17
  // letterstory sim report <id> --since 7d
15
18
  // letterstory sim sessions <id>
16
19
  // letterstory sim session <session-id>
@@ -97,8 +100,76 @@ export const ARGS = {
97
100
  list_simulation_sessions: { simulation_id: simulationId, limit: { flag: "limit", type: "num" } },
98
101
  get_simulation_session: { session_id: { positional: 0, label: "session-id", required: true } },
99
102
  get_simulation_report: { simulation_id: simulationId, days: { value: (flags) => sinceDays(flags.since) } },
103
+ list_simulation_runs: {
104
+ simulation_id: {
105
+ value: (flags) => (flags.live === true ? null : flagStr(flags.simulation)),
106
+ },
107
+ suite: "suite",
108
+ limit: { flag: "limit", type: "num" },
109
+ },
110
+ get_simulation_run: { run_id: { positional: 0, label: "run-id", required: true } },
111
+ record_simulation_runs: {
112
+ simulation_id: "simulation",
113
+ suite: "suite",
114
+ runs: { value: (flags) => runsFromGrader(flagStr(flags.file), flagStr(flags.tasks), flagStr(flags.target)) },
115
+ },
100
116
  };
101
117
 
118
+ /**
119
+ * The driven-runs grader's graded.json, joined with its pack's tasks.json, as the runs
120
+ * record_simulation_runs stores. A run id is `<task>.<agent label>.<n>` (claude-sonnet, codex).
121
+ */
122
+ export function runsFromGrader(file, tasksFile, target) {
123
+ if (!file) return undefined;
124
+ const read = (path, what) => {
125
+ try {
126
+ return JSON.parse(readFileSync(path, "utf8"));
127
+ } catch {
128
+ throw new CliError(`--${what} must be the grader's JSON (could not read ${path})`);
129
+ }
130
+ };
131
+ const graded = read(file, "file");
132
+ if (!Array.isArray(graded)) throw new CliError("--file must be graded.json: a list of graded runs");
133
+ const tasks = new Map(tasksFile ? read(tasksFile, "tasks").map((t) => [t.id, t]) : []);
134
+ return graded.map((g) => {
135
+ const [taskKey, label = ""] = String(g.id ?? "").split(".");
136
+ const task = tasks.get(g.task ?? taskKey);
137
+ const errors = [...(g.errors ?? [])];
138
+ const calls = (g.calls ?? []).map((tool) => {
139
+ const i = errors.findIndex((e) => String(e).startsWith(`${tool}:`));
140
+ const error =
141
+ i >= 0
142
+ ? String(errors.splice(i, 1)[0])
143
+ .slice(tool.length + 1)
144
+ .trim()
145
+ : null;
146
+ return { tool: String(tool), error };
147
+ });
148
+ const [kind, ...model] = label.split("-");
149
+ return {
150
+ task_key: g.task ?? taskKey,
151
+ task_prompt: task?.prompt ?? g.prompt ?? g.task ?? taskKey,
152
+ ...(task?.truth ? { truth: task.truth } : {}),
153
+ agent: kind === "claude" ? "claude-code" : kind || "unknown",
154
+ ...(model.length ? { model: model.join("-") } : {}),
155
+ ...(target ? { target } : {}),
156
+ outcome: g.answer ? "completed" : "error",
157
+ ...(["pass", "partial", "fail"].includes(g.verdict) ? { verdict: g.verdict } : {}),
158
+ ...(g.reason ? { verdict_reason: String(g.reason).slice(0, 1000) } : {}),
159
+ ...(g.cause ? { cause: g.cause } : {}),
160
+ ...(typeof g.turns === "number" ? { turns: g.turns } : {}),
161
+ ...(typeof g.secs === "number" ? { secs: g.secs } : {}),
162
+ ...(typeof g.costUsd === "number" ? { cost_usd: g.costUsd } : {}),
163
+ tool_calls: calls,
164
+ invented: (g.invented ?? []).map((v) => ({
165
+ value: String(v.value ?? v),
166
+ ...(v.why ? { why: String(v.why) } : {}),
167
+ })),
168
+ ...(g.answer ? { answer: String(g.answer).slice(0, 20000) } : {}),
169
+ };
170
+ });
171
+ }
172
+
102
173
  function call(ctx, tool) {
103
174
  return ctx.client.callTool(tool, argsFromFlags(ARGS[tool], ctx.flags, ctx.positionals));
104
175
  }
@@ -136,9 +207,15 @@ export async function cmdSim(ctx) {
136
207
  return simSession(rest);
137
208
  case "report":
138
209
  return simReport(rest);
210
+ case "runs":
211
+ return simRuns(rest);
212
+ case "run":
213
+ return simRun(rest);
214
+ case "runs-import":
215
+ return simRunsImport(rest);
139
216
  default:
140
217
  throw new CliError(
141
- "Usage: sim [list|create|show|rule|pause|resume|limits|seed|key|sessions|session|report]"
218
+ "Usage: sim [list|create|show|rule|pause|resume|limits|seed|key|sessions|session|report|runs|run|runs-import]"
142
219
  );
143
220
  }
144
221
  }
@@ -254,6 +331,72 @@ async function simSession(ctx) {
254
331
  return 0;
255
332
  }
256
333
 
334
+ /** `sim runs [--simulation <id> | --live] [--suite <pack>]`: driven runs and how they went. */
335
+ async function simRuns(ctx) {
336
+ const result = await call(ctx, "list_simulation_runs");
337
+ printResult(ctx.io, ctx.flags, result, ({ runs, totals: t }) => {
338
+ if (!runs.length)
339
+ return "No runs yet. Import a graded round: sim runs-import --file graded.json --tasks tasks.json";
340
+ const causes = Object.entries(t.causes)
341
+ .map(([c, n]) => `${c} ${n}`)
342
+ .join(", ");
343
+ return [
344
+ `${t.runs} runs: ${t.pass} pass, ${t.partial} partial, ${t.fail} fail${t.ungraded ? `, ${t.ungraded} ungraded` : ""}; ${t.invented} invented values; $${t.cost_usd}`,
345
+ ...(causes ? [`Misses by cause: ${causes}`] : []),
346
+ "",
347
+ ...runs.map(
348
+ (r) =>
349
+ `${r.id} ${(r.verdict ?? r.status).padEnd(8)} ${(r.cause && r.cause !== "none" ? r.cause : "").padEnd(12)} ${`${r.agent}${r.model ? `:${r.model}` : ""}`.padEnd(20)} ${r.task_key}`
350
+ ),
351
+ ].join("\n");
352
+ });
353
+ return 0;
354
+ }
355
+
356
+ /** `sim run <run-id>`: one run in full. */
357
+ async function simRun(ctx) {
358
+ const result = await call(ctx, "get_simulation_run");
359
+ printResult(ctx.io, ctx.flags, result, ({ run: r }) =>
360
+ [
361
+ `${r.task_key} — ${r.agent}${r.model ? `:${r.model}` : ""}: ${r.verdict ?? "ungraded"}${r.cause && r.cause !== "none" ? ` (${r.cause})` : ""}, stopped: ${r.outcome ?? r.status}`,
362
+ `Task: ${r.task_prompt}`,
363
+ ...(r.verdict_reason ? [`Why: ${r.verdict_reason}`] : []),
364
+ `${r.tool_calls.length} tool calls, ${r.turns ?? "–"} turns, ${r.secs ?? "–"}s, $${r.cost_usd ?? "–"}`,
365
+ ...r.tool_calls.map(
366
+ (c, i) => ` ${String(i + 1).padStart(3)}. ${c.tool}${c.error ? ` ✗ ${c.error}` : ""}`
367
+ ),
368
+ ...(r.invented.length
369
+ ? ["Invented values:", ...r.invented.map((v) => ` ${v.value}${v.why ? ` (${v.why})` : ""}`)]
370
+ : []),
371
+ ...(r.answer ? ["", "Answer:", r.answer] : []),
372
+ ].join("\n")
373
+ );
374
+ return 0;
375
+ }
376
+
377
+ /** `sim runs-import --file graded.json --tasks tasks.json [--suite <pack>] [--simulation <id>] [--target <url>]` */
378
+ async function simRunsImport(ctx) {
379
+ refuseUnknownFlags(ctx, ARGS.record_simulation_runs, ["file", "tasks", "target"]);
380
+ const args = argsFromFlags(ARGS.record_simulation_runs, ctx.flags, ctx.positionals);
381
+ if (!args.runs?.length)
382
+ throw new CliError(
383
+ "Usage: sim runs-import --file graded.json --tasks tasks.json [--suite <pack>] [--simulation <id>]"
384
+ );
385
+ let recorded = 0;
386
+ for (let i = 0; i < args.runs.length; i += 200) {
387
+ const res = await ctx.client.callTool("record_simulation_runs", { ...args, runs: args.runs.slice(i, i + 200) });
388
+ recorded += res.recorded ?? 0;
389
+ }
390
+ printResult(
391
+ ctx.io,
392
+ ctx.flags,
393
+ { recorded },
394
+ (r) =>
395
+ `Recorded ${r.recorded} runs. See them: sim runs${args.simulation_id ? ` --simulation ${args.simulation_id}` : " --live"}`
396
+ );
397
+ return 0;
398
+ }
399
+
257
400
  async function simReport(ctx) {
258
401
  const result = await call(ctx, "get_simulation_report");
259
402
  printResult(ctx.io, ctx.flags, result, ({ report: r }) => {
@@ -5,7 +5,7 @@
5
5
  // site builds <host> → list_build_suggestions (--limit n)
6
6
  // site research-builds <host> → research_builds (Build's suggestion pass: propose, check, Jev, store)
7
7
  // site research-fixes <host> → research_fixes (Fix's suggestion pass: exact edits on pages that exist)
8
- // site metrics <host> [path] → get_site_metrics (--window 7d|28d|90d, --page <path>…, --no-compare)
8
+ // site metrics <host> [path] → get_site_metrics (--window 1d|7d|28d|90d, --page <path>…, --no-compare)
9
9
  // site observations <host> → list_site_observations site observe <host> → observe_site
10
10
  // site dismiss <host> <id> → dismiss_site_observation
11
11
  // site families <host> → list_site_families site decide-family <id> → decide_site_family
@@ -96,7 +96,7 @@ const ARGS = {
96
96
  host: { positional: 0, required: true, label: "host" },
97
97
  path: { positional: 1, label: "path" },
98
98
  paths: { flag: "page", type: "list" },
99
- window: { flag: "window", enum: ["7d", "28d", "90d"] },
99
+ window: { flag: "window", enum: ["1d", "7d", "28d", "90d"] },
100
100
  compare: { flag: "no-compare", type: "bool", invert: true },
101
101
  },
102
102
  list_competitor_sites: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.154.1",
3
+ "version": "0.158.1",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",