@letterstory/cli 0.165.2 → 0.167.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
@@ -15,6 +15,7 @@ import { resolveDocumentFlags } from "./documents.mjs";
15
15
  import { checkForUpdate } from "./update-check.mjs";
16
16
  import {
17
17
  cmdLogin,
18
+ cmdSignup,
18
19
  cmdLogout,
19
20
  cmdConfig,
20
21
  cmdWhoami,
@@ -74,7 +75,7 @@ import {
74
75
  } from "./commands.mjs";
75
76
 
76
77
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
77
- export const VERSION = "0.165.2";
78
+ export const VERSION = "0.167.1";
78
79
 
79
80
  /** The exit code for a gate refusal (CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS): 1 is a plain error. */
80
81
  export const EXIT_PAYMENT_REQUIRED = 3;
@@ -430,6 +431,9 @@ Auth:
430
431
  login [--url <url>] Sign in via your browser (default url: https://app.letterstory.com)
431
432
  login --device [--url <url>] Sign in with one link, opened in any browser (for agents and remote shells)
432
433
  login --key <ls_…> [--url <url>] Save a static API key instead (for CI/automation)
434
+ signup --email <work email> [--agent <name>] [--url <url>]
435
+ Sign someone up with no account yet: Letter emails them a link,
436
+ they confirm in a browser, and this saves the new account's session
433
437
  logout Forget saved credentials (revokes an OAuth session, if any)
434
438
  config Show the resolved url + credential source
435
439
 
@@ -919,14 +923,10 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
919
923
  The blind read: mark a shown item; the marks fill the case
920
924
  the run exports and the status's agreement. Needs recipes:write.
921
925
  admin letterpress settings What steers Letterpress beside the recipes: the one
922
- judgement's weights per ask and, per lens, its mode (off,
923
- shadow or live) and bar. Needs recipes:read.
924
- admin letterpress flip <build|fix|plan> <off|shadow|live>
925
- Flip a lens (Build, Fix: the one judgement; Plan: the pick
926
- with recipes as direction). Shadow: both run and are
927
- recorded on every run, today's shown; live: the new one
928
- decides. Recorded as yours. Needs recipes:write.
929
- admin letterpress set <weights.<ask>.<reading>|lenses.<lens>.mode|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|asks.<lens>.ask|asks.<lens>.guidance> <value>
926
+ judgement's weights per ask, each lens's bar and read
927
+ budget, each surface's ask and guidance, the dismissal
928
+ window. Needs recipes:read.
929
+ admin letterpress set <weights.<ask>.<reading>|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|lenses.<lens>.research.turns|lenses.<lens>.research.ms|asks.<lens>.ask|asks.<lens>.guidance|dismissals.block_days|explore.ask|explore.research.turns|explore.every_days> <value>
930
930
  Change one weight, one bar, or a lens's ask and guidance (the
931
931
  opinions Letterpress chooses by, as staff's words); the version
932
932
  bumps and the previous body is kept. Needs recipes:write.
@@ -1670,6 +1670,7 @@ then ~/.letterstory/config.json.`;
1670
1670
 
1671
1671
  const CLIENT_COMMANDS = {
1672
1672
  login: cmdLogin,
1673
+ signup: cmdSignup,
1673
1674
  logout: cmdLogout,
1674
1675
  config: cmdConfig,
1675
1676
  whoami: cmdWhoami,
package/lib/client.mjs CHANGED
@@ -127,8 +127,10 @@ export class LetterstoryClient {
127
127
  // needs no prior initialize handshake. When authenticated via OAuth, a single
128
128
  // 401 triggers one silent refresh-and-retry before giving up — a static key
129
129
  // has no such recovery, since a rejected key is just wrong.
130
- async rpc(method, params, { _retried = false } = {}) {
131
- const authHeaders = this.authHeaders();
130
+ // `keyless`: a public tool (start_signup, finish_signup) is called with no credentials at all,
131
+ // by someone who has no account yet.
132
+ async rpc(method, params, { _retried = false, keyless = false } = {}) {
133
+ const authHeaders = keyless ? {} : this.authHeaders();
132
134
  if (!authHeaders) {
133
135
  throw new CliError(
134
136
  `Not logged in. Run \`${this.bin} login\` (opens your browser) or \`${this.bin} login --key <ls_…>\`.`
@@ -255,8 +257,8 @@ export class LetterstoryClient {
255
257
  // Invoke a tool and unwrap the MCP content envelope. A tool-level failure arrives
256
258
  // as { isError: true, content:[{text}] } on HTTP 200 (e.g. a capability the key
257
259
  // lacks, or a validation error) — surface that text as a CliError.
258
- async callTool(name, args = {}) {
259
- const result = await this.rpc("tools/call", { name, arguments: args });
260
+ async callTool(name, args = {}, { keyless = false } = {}) {
261
+ const result = await this.rpc("tools/call", { name, arguments: args }, { keyless });
260
262
  const text = result?.content?.[0]?.text ?? "";
261
263
  if (result?.isError)
262
264
  throw new CliError(text || `Tool ${name} failed`, { code: result.structuredContent?.code ?? null });
@@ -5048,7 +5048,7 @@ function recipeFromFlags(flags) {
5048
5048
  const ENGINE = "/api/superadmin/engine-settings";
5049
5049
  const LETTERPRESS = "/api/superadmin/letterpress";
5050
5050
  const ENGINE_USAGE =
5051
- "Usage: admin letterpress status | gaps | replay <run-id> | mark <run-id> <item-id> <right|weak|wrong|lead|clear> [--note …] | settings | flip <build|fix|plan> <off|shadow|live> | set <weights.<ask>.<reading>|lenses.<lens>.mode|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|lenses.<lens>.research.turns|lenses.<lens>.research.ms|asks.<lens>.ask|asks.<lens>.guidance> <value>";
5051
+ "Usage: admin letterpress status | gaps | replay <run-id> | mark <run-id> <item-id> <right|weak|wrong|lead|clear> [--note …] | settings | set <weights.<ask>.<reading>|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|lenses.<lens>.research.turns|lenses.<lens>.research.ms|asks.<lens>.ask|asks.<lens>.guidance|dismissals.block_days|explore.ask|explore.research.turns|explore.research.ms|explore.every_days> <value>";
5052
5052
 
5053
5053
  /** One number of the settings from a dotted path and a value: the PUT body save_engine_settings reads. */
5054
5054
  function engineSettingsPatch(path, value) {
@@ -5060,8 +5060,22 @@ function engineSettingsPatch(path, value) {
5060
5060
  }
5061
5061
  if (parts[0] === "asks" && (parts[2] === "ask" || parts[2] === "guidance") && parts.length === 3)
5062
5062
  return { asks: { [parts[1]]: { [parts[2]]: String(value) } } };
5063
- if (parts[0] === "lenses" && parts[2] === "mode" && parts.length === 3)
5064
- return { lenses: { [parts[1]]: { mode: String(value) } } };
5063
+ if (parts[0] === "explore" && parts[1] === "ask" && parts.length === 2) return { explore: { ask: String(value) } };
5064
+ if (parts[0] === "explore" && parts[1] === "research" && parts.length === 3) {
5065
+ const n = Number(value);
5066
+ if (!Number.isFinite(n)) throw new CliError(`${path}: a number`);
5067
+ return { explore: { research: { [parts[2]]: n } } };
5068
+ }
5069
+ if (parts[0] === "explore" && parts[1] === "every_days" && parts.length === 2) {
5070
+ const n = Number(value);
5071
+ if (!Number.isInteger(n)) throw new CliError(`${path}: a whole number of days`);
5072
+ return { explore: { every_days: n } };
5073
+ }
5074
+ if (parts[0] === "dismissals" && parts[1] === "block_days" && parts.length === 2) {
5075
+ const n = Number(value);
5076
+ if (!Number.isInteger(n)) throw new CliError(`${path}: a whole number of days`);
5077
+ return { dismissals: { block_days: n } };
5078
+ }
5065
5079
  if (parts[0] === "lenses" && parts[2] === "bar" && parts.length === 3 && value === "none")
5066
5080
  return { lenses: { [parts[1]]: { bar: null } } };
5067
5081
  if (parts[0] === "lenses" && parts[2] === "bar" && parts.length === 4) {
@@ -5072,12 +5086,12 @@ function engineSettingsPatch(path, value) {
5072
5086
  throw new CliError(ENGINE_USAGE);
5073
5087
  }
5074
5088
 
5075
- /** The settings as a few lines: each lens's judgement and bar, then the weights per ask. */
5089
+ /** The settings as a few lines: each lens's bar and budget, the dismissal window, then the weights per ask. */
5076
5090
  function engineSettingsText(r) {
5077
5091
  const s = r.settings;
5078
5092
  const lenses = Object.entries(s.lenses).map(
5079
5093
  ([lens, l]) =>
5080
- `${lens.padEnd(6)} mode ${l.mode.padEnd(6)} bar ${
5094
+ `${lens.padEnd(6)} reads ${l.research ? `${l.research.turns} turns, ${Math.round(l.research.ms / 1000)}s` : "default"} bar ${
5081
5095
  l.bar
5082
5096
  ? Object.entries(l.bar)
5083
5097
  .map(([k, v]) => `${k}≥${v}`)
@@ -5100,7 +5114,22 @@ function engineSettingsText(r) {
5100
5114
  .map((l) => ` · ${l}`),
5101
5115
  ]);
5102
5116
  const head = `Engine settings v${r.version}${r.defaults_only ? " (the defaults; no row yet)" : ""}${r.updated_by ? ` · by ${r.updated_by}` : ""}${r.changed ? ` · changed: ${r.changed.join(", ") || "nothing"}` : ""}`;
5103
- return [head, ...lenses, "", ...weights, "", ...asks].join("\n");
5117
+ const dismissals = s.dismissals
5118
+ ? `a dismissal blocks for ${s.dismissals.block_days} days, then is dated history`
5119
+ : null;
5120
+ const explore = s.explore
5121
+ ? `explore every ${s.explore.every_days} days, ${s.explore.research.turns} reads, ${Math.round(s.explore.research.ms / 1000)}s: ${s.explore.ask}`
5122
+ : null;
5123
+ return [
5124
+ head,
5125
+ ...lenses,
5126
+ ...(dismissals ? [dismissals] : []),
5127
+ ...(explore ? [explore] : []),
5128
+ "",
5129
+ ...weights,
5130
+ "",
5131
+ ...asks,
5132
+ ].join("\n");
5104
5133
  }
5105
5134
 
5106
5135
  /**
@@ -5191,13 +5220,6 @@ async function cmdAdminLetterpress(ctx) {
5191
5220
  printResult(io, flags, result, engineSettingsText);
5192
5221
  return 0;
5193
5222
  }
5194
- case "flip": {
5195
- const [, lens, mode] = positionals;
5196
- if (!lens || !mode) throw new CliError(ENGINE_USAGE);
5197
- const result = await staffRequest(ctx, "PUT", ENGINE, { lenses: { [lens]: { mode } } });
5198
- printResult(io, flags, result, engineSettingsText);
5199
- return 0;
5200
- }
5201
5223
  case "set": {
5202
5224
  const [, path, value] = positionals;
5203
5225
  if (!path || value === undefined) throw new CliError(ENGINE_USAGE);
@@ -5352,6 +5374,8 @@ const LAGO_USAGE = `Usage: admin billing lago <command>
5352
5374
  payments retry <lago-invoice-id> charge one failed invoice again now
5353
5375
  payments run [--dry] one pass of the failed-payment loop now (--dry: report only)
5354
5376
  signups [--status open|card_saved|provisioned|paid|abandoned|canceled] new paying orgs on their way onto Lago
5377
+ debt <org-id> what an org owes from an ended plan (it blocks the org's own re-signup)
5378
+ debt clear <org-id> --why "…" forgive it, kept with who and why, so the org can sign up again on its own
5355
5379
  signups end <org-id> --why "…" end an org's signup in flight (not yet provisioned), so one on other terms can open
5356
5380
  cap <org-id> <dollars|off> [--why "…"] set an account's monthly spend cap on overage (off: no cap)
5357
5381
  cancel <org-id> --why "…" --yes end an account's Lago plan now (its plan fee refunded in its first month, once per org)
@@ -5410,7 +5434,8 @@ async function cmdAdminBillingLegacyUnmark(ctx) {
5410
5434
  }
5411
5435
 
5412
5436
  const FREE_USAGE = `Usage: admin billing free exposure [--json] who the free paywall covers, and who is unassigned
5413
- admin billing free backfill --why "…" [--apply] signup grant for self-serve orgs with none; a dry run unless --apply`;
5437
+ admin billing free backfill --why "…" [--apply] signup grant for self-serve orgs with none; a dry run unless --apply
5438
+ admin billing free repair-subjects --why "…" [--apply] staff-address signup subjects fixed, refused orgs granted (R1); a dry run unless --apply`;
5414
5439
 
5415
5440
  const EXPOSURE_WORDS = {
5416
5441
  needs_legacy: "pay today: need a legacy mark (admin billing legacy mark --all)",
@@ -5461,6 +5486,26 @@ async function cmdAdminBillingFree(ctx) {
5461
5486
  });
5462
5487
  return 0;
5463
5488
  }
5489
+ if (positionals[1] === "repair-subjects") {
5490
+ const why = flagStr(flags.why);
5491
+ if (!why) throw new CliError(`Say why (--why "…").\n${FREE_USAGE}`);
5492
+ const r = await staffPost(ctx, "/api/superadmin/billing/free-tokens/repair-subjects", {
5493
+ dry: !flagBool(flags.apply),
5494
+ why,
5495
+ });
5496
+ printResult(io, flags, r, (x) => {
5497
+ const granted = x.regranted.filter((g) => g.outcome === "granted" || g.outcome === "would_grant");
5498
+ const lines = [
5499
+ `${x.dry ? "Would fix" : "Fixed"} ${x.fixed.length} staff-address subject(s):`,
5500
+ ...x.fixed.map((f) => ` ${f.orgId.slice(0, 8)} ${f.from} -> ${f.to ?? "(none)"}`),
5501
+ `${x.dry ? "Would grant" : "Granted"} ${granted.length} self-serve org(s) with no signup grant:`,
5502
+ ...x.regranted.map((g) => ` ${g.orgId.slice(0, 8)} ${g.outcome}`),
5503
+ ];
5504
+ if (x.dry) lines.push("Nothing written. Run again with --apply.");
5505
+ return lines.join("\n");
5506
+ });
5507
+ return 0;
5508
+ }
5464
5509
  throw new CliError(FREE_USAGE);
5465
5510
  }
5466
5511
 
@@ -5651,6 +5696,40 @@ async function cmdAdminBilling(ctx) {
5651
5696
  printResult(io, flags, result);
5652
5697
  return 0;
5653
5698
  }
5699
+ case "debt": {
5700
+ const usd = (cents) => `$${(cents / 100).toFixed(2)}`;
5701
+ if (positionals[2] === "clear") {
5702
+ const orgId = requirePositional(positionals, 3, "org-id");
5703
+ if (!flagStr(flags.why))
5704
+ throw new CliError('Say why: debt clear <org-id> --why "…" (it is kept with the account).');
5705
+ const result = await staffRequest(ctx, "POST", `${LAGO}/debt`, { orgId, why: flagStr(flags.why) });
5706
+ printResult(
5707
+ io,
5708
+ flags,
5709
+ result,
5710
+ (r) => `Debt cleared: ${usd(r.clearedCents)} forgiven. The org can sign up again on its own.`
5711
+ );
5712
+ return 0;
5713
+ }
5714
+ const orgId = requirePositional(positionals, 2, "org-id");
5715
+ const result = await staffRequest(ctx, "GET", `${LAGO}/debt?orgId=${encodeURIComponent(orgId)}`);
5716
+ printResult(io, flags, result, (r) =>
5717
+ [
5718
+ r.owedCents > 0
5719
+ ? `Owes ${usd(r.owedCents)} from an earlier plan: its own re-signup is refused until staff clear it.`
5720
+ : "Owes nothing from an earlier plan.",
5721
+ ...r.items.map(
5722
+ (i) => ` ${i.invoice ?? "first invoice (voided by its cancel)"} ${usd(i.cents)} ${i.state}`
5723
+ ),
5724
+ ...(r.cleared
5725
+ ? [
5726
+ `Last cleared ${r.cleared.at.slice(0, 10)} by ${r.cleared.by}: ${usd(r.cleared.cents)} — ${r.cleared.reason}`,
5727
+ ]
5728
+ : []),
5729
+ ].join("\n")
5730
+ );
5731
+ return 0;
5732
+ }
5654
5733
  case "changes": {
5655
5734
  if (positionals[2] === "cancel") {
5656
5735
  const orgId = requirePositional(positionals, 3, "org-id");
@@ -7,8 +7,8 @@
7
7
  // calling get_company_info, same probe `login` uses to verify a fresh key.
8
8
 
9
9
  import { LetterstoryClient, resolveConfig, writeConfigFile, clearConfigFile, configPath } from "../client.mjs";
10
- import { flagStr } from "./shared.mjs";
11
- import { browserLogin, deviceLogin, revokeToken } from "../oauth.mjs";
10
+ import { argsFromFlags, flagStr } from "./shared.mjs";
11
+ import { browserLogin, deviceLogin, pollDeviceToken, revokeToken } from "../oauth.mjs";
12
12
 
13
13
  export async function cmdLogin(ctx) {
14
14
  const { flags, io } = ctx;
@@ -40,6 +40,11 @@ export async function cmdLogin(ctx) {
40
40
  }
41
41
 
42
42
  const tokens = flags.device ? await deviceLogin({ url, io }) : await browserLogin({ url, io });
43
+ return saveSession({ tokens, url, flags, io });
44
+ }
45
+
46
+ // An OAuth session from /token, saved the way every login saves it, then checked with one call.
47
+ async function saveSession({ tokens, url, flags, io }) {
43
48
  const oauth = {
44
49
  access_token: tokens.access_token,
45
50
  refresh_token: tokens.refresh_token,
@@ -60,6 +65,33 @@ export async function cmdLogin(ctx) {
60
65
  return 0;
61
66
  }
62
67
 
68
+ export const ARGS = {
69
+ start_signup: {
70
+ email: { flag: "email", required: true },
71
+ agent: "agent",
72
+ },
73
+ };
74
+
75
+ // signup: an agent signs its user up (docs/architecture/agent-signup.md). No key: `start_signup`
76
+ // emails the person a link, they confirm in a browser, and this polls for the new account's token
77
+ // and saves it like `login --device`.
78
+ export async function cmdSignup(ctx) {
79
+ const { flags, io } = ctx;
80
+ const url = flagStr(flags.url) || resolveConfig({}).url;
81
+ const client = new LetterstoryClient({ url });
82
+ const start = await client.callTool("start_signup", argsFromFlags(ARGS.start_signup, flags), { keyless: true });
83
+ io.log(`Letter emailed ${start.email} a link to create their account.`);
84
+ io.log(`Ask them to open it and confirm. Code: ${start.user_code} (the page shows the same one)`);
85
+ io.log(`${start.free_tokens.note} The confirmation page shows what this account gets.`);
86
+ io.log("Waiting for them to confirm…");
87
+ const tokens = await pollDeviceToken({
88
+ base: url.replace(/\/+$/, ""),
89
+ start,
90
+ again: "Run `signup` again.",
91
+ });
92
+ return saveSession({ tokens, url, flags, io });
93
+ }
94
+
63
95
  export async function cmdLogout(ctx) {
64
96
  const { config, io } = ctx;
65
97
  if (config.oauth?.access_token) {
@@ -225,7 +225,7 @@ export function billingAccountText(r) {
225
225
  `Free tokens: ${Math.max(0, f.availableTokens)} left of ${f.grantedTokens} given (${f.usedTokens} used${f.heldTokens ? `, ${f.heldTokens} held by running work` : ""}).`,
226
226
  ...f.grants.map(
227
227
  (g) =>
228
- ` +${g.tokens} ${g.source}${g.sourceKey !== g.source ? `: ${g.sourceKey}` : ""} ${g.createdAt.slice(0, 10)}`
228
+ ` +${g.tokens} ${g.source}${g.sourceKey !== g.source ? `: ${g.sourceKey}` : ""}${g.channel === "agent" ? " (an agent signed you up)" : ""} ${g.createdAt.slice(0, 10)}`
229
229
  ),
230
230
  f.cardRequired
231
231
  ? "No free tokens left: new work needs a card. An admin adds one in Settings → Billing."
@@ -263,12 +263,13 @@ function tokenRewardsText(r) {
263
263
  return "Free tokens for actions are for workspaces on free tokens; this one is on a plan.";
264
264
  const lines = r.rewards.map(
265
265
  (x) =>
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)" : ""}`
266
+ ` ${x.claimed ? "✓" : x.ready === false ? "·" : "○"} ${x.action.padEnd(18)} ${String(x.tokens).padStart(6)} tokens ${x.title}${x.claimed ? " (earned)" : x.auto ? " (granted when done)" : x.ready === false ? " (not done yet)" : ""}`
267
267
  );
268
268
  return [
269
- `Free tokens for actions: ${r.claimedTokens} claimed, ${r.availableTokens} still to earn.`,
269
+ `Free tokens for actions: ${r.claimedTokens} earned, ${r.availableTokens} still to earn.`,
270
270
  ...lines,
271
- "Claim one: letterstory org billing rewards claim <action>",
271
+ "GitHub, GitLab, Slack and the CLI are granted on their own once done.",
272
+ "Claim the rest: letterstory org billing rewards claim <action>",
272
273
  ].join("\n");
273
274
  }
274
275
 
@@ -1,7 +1,7 @@
1
1
  // `sim` — Simulations from a terminal: a free, simulated copy of your API that agents can
2
2
  // use, and what they did with it. Thin wrappers over the simulation tools (create_simulation,
3
3
  // get_simulation, update_simulation, mint_simulation_key, list_simulation_sessions,
4
- // get_simulation_session, get_simulation_report), the same lib functions the app calls.
4
+ // get_simulation_session, get_simulation_report, the runs tools), the same lib functions the app calls.
5
5
  //
6
6
  // letterstory sim create --name "Attio API" --spec-url https://api.attio.com/openapi/api
7
7
  // letterstory sim show <id>
@@ -13,7 +13,9 @@
13
13
  // letterstory sim limits <id> --daily-calls 5000 --daily-sessions 100
14
14
  // letterstory sim runs-import --file /tmp/dr1/graded.json --tasks scripts/driven-runs/packs/letter-mcp/tasks.json --suite letter-mcp
15
15
  // letterstory sim runs --live
16
- // letterstory sim run <run-id>
16
+ // letterstory sim run <run-id> [--watch]
17
+ // letterstory sim run-start <simulation-id> --task "Find our open deals over $10k" [--truth "..."] [--watch]
18
+ // letterstory sim run-stop <run-id>
17
19
  // letterstory sim report <id> --since 7d
18
20
  // letterstory sim sessions <id>
19
21
  // letterstory sim session <session-id>
@@ -108,6 +110,17 @@ export const ARGS = {
108
110
  limit: { flag: "limit", type: "num" },
109
111
  },
110
112
  get_simulation_run: { run_id: { positional: 0, label: "run-id", required: true } },
113
+ start_simulation_run: {
114
+ simulation_id: simulationId,
115
+ task_prompt: "task",
116
+ truth: "truth",
117
+ task_key: "task-key",
118
+ suite: "suite",
119
+ model: "model",
120
+ budget_usd: { flag: "budget", type: "num" },
121
+ max_turns: { flag: "turns", type: "num" },
122
+ },
123
+ stop_simulation_run: { run_id: { positional: 0, label: "run-id", required: true } },
111
124
  record_simulation_runs: {
112
125
  simulation_id: "simulation",
113
126
  suite: "suite",
@@ -213,9 +226,13 @@ export async function cmdSim(ctx) {
213
226
  return simRun(rest);
214
227
  case "runs-import":
215
228
  return simRunsImport(rest);
229
+ case "run-start":
230
+ return simRunStart(rest);
231
+ case "run-stop":
232
+ return simRunStop(rest);
216
233
  default:
217
234
  throw new CliError(
218
- "Usage: sim [list|create|show|rule|pause|resume|limits|seed|key|sessions|session|report|runs|run|runs-import]"
235
+ "Usage: sim [list|create|show|rule|pause|resume|limits|seed|key|sessions|session|report|runs|run|run-start|run-stop|runs-import]"
219
236
  );
220
237
  }
221
238
  }
@@ -353,11 +370,19 @@ async function simRuns(ctx) {
353
370
  return 0;
354
371
  }
355
372
 
356
- /** `sim run <run-id>`: one run in full. */
373
+ /** `sim run <run-id> [--watch]`: one run in full, or followed live until it ends. */
357
374
  async function simRun(ctx) {
358
- const result = await call(ctx, "get_simulation_run");
375
+ refuseUnknownFlags(ctx, ARGS.get_simulation_run, ["watch"]);
376
+ if (ctx.flags.watch === true) return simWatch(ctx, flagStr(ctx.positionals[0]));
377
+ printRun(ctx, await call(ctx, "get_simulation_run"));
378
+ return 0;
379
+ }
380
+
381
+ function printRun(ctx, result) {
359
382
  printResult(ctx.io, ctx.flags, result, ({ run: r }) =>
360
383
  [
384
+ ...(r.live ? [`Running (${r.phase ?? r.status}). Watch it: sim run ${r.id} --watch`] : []),
385
+ ...(r.error ? [`Error: ${r.error}`] : []),
361
386
  `${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
387
  `Task: ${r.task_prompt}`,
363
388
  ...(r.verdict_reason ? [`Why: ${r.verdict_reason}`] : []),
@@ -371,9 +396,63 @@ async function simRun(ctx) {
371
396
  ...(r.answer ? ["", "Answer:", r.answer] : []),
372
397
  ].join("\n")
373
398
  );
399
+ }
400
+
401
+ /** `sim run-start <simulation-id> --task "..." [--truth "..."] [--task-key <name>] [--budget 2] [--turns 40] [--watch]` */
402
+ async function simRunStart(ctx) {
403
+ refuseUnknownFlags(ctx, ARGS.start_simulation_run, ["watch"]);
404
+ const args = argsFromFlags(ARGS.start_simulation_run, ctx.flags, ctx.positionals);
405
+ if (!args.task_prompt)
406
+ throw new CliError(
407
+ 'Usage: sim run-start <simulation-id> --task "what the agent should do" [--truth "the right answer"]'
408
+ );
409
+ const result = await ctx.client.callTool("start_simulation_run", args);
410
+ if (ctx.flags.watch === true) return simWatch(ctx, result.run.id);
411
+ printResult(
412
+ ctx.io,
413
+ ctx.flags,
414
+ result,
415
+ (r) => `Started run ${r.run.id}. Watch it: sim run ${r.run.id} --watch Stop it: sim run-stop ${r.run.id}`
416
+ );
417
+ return 0;
418
+ }
419
+
420
+ /** `sim run-stop <run-id>`: what the agent did so far is kept. */
421
+ async function simRunStop(ctx) {
422
+ const result = await call(ctx, "stop_simulation_run");
423
+ printResult(ctx.io, ctx.flags, result, (r) =>
424
+ r.stopped
425
+ ? `Stopped run ${r.run.id}. What it did so far is kept.`
426
+ : `Run ${r.run.id} had already ended (${r.run.outcome ?? r.run.status}).`
427
+ );
374
428
  return 0;
375
429
  }
376
430
 
431
+ const WATCH_MS = 3000;
432
+
433
+ /** Follow a run's feed until it ends, then print it in full. Ctrl-C stops watching, not the run. */
434
+ async function simWatch(ctx, runId) {
435
+ if (!runId) throw new CliError("Usage: sim run <run-id> --watch");
436
+ let shown = 0;
437
+ let phase = null;
438
+ for (;;) {
439
+ const result = await ctx.client.callTool("get_simulation_run", { run_id: runId });
440
+ const r = result.run;
441
+ if (r.live && r.phase !== phase) {
442
+ phase = r.phase;
443
+ ctx.io.log(`· ${phase ?? r.status}`);
444
+ }
445
+ for (const line of r.activity.slice(shown)) ctx.io.log(` ${line.kind.padEnd(5)} ${line.text}`);
446
+ shown = r.activity.length;
447
+ if (!r.live) {
448
+ ctx.io.log("");
449
+ printRun(ctx, result);
450
+ return 0;
451
+ }
452
+ await new Promise((resolve) => setTimeout(resolve, WATCH_MS));
453
+ }
454
+ }
455
+
377
456
  /** `sim runs-import --file graded.json --tasks tasks.json [--suite <pack>] [--simulation <id>] [--target <url>]` */
378
457
  async function simRunsImport(ctx) {
379
458
  refuseUnknownFlags(ctx, ARGS.record_simulation_runs, ["file", "tasks", "target"]);
@@ -224,6 +224,14 @@ async function visitsList(ctx) {
224
224
  ` ${a.agent.padEnd(22)} ${String(a.total).padStart(6)}${a.verified !== null && a.verified !== undefined ? ` (${a.verified} verified)` : ""}`
225
225
  );
226
226
  }
227
+ if (r.earlier) {
228
+ lines.push(
229
+ "",
230
+ `Before ${r.baseline} (v1 count, kept apart from the above): ${r.earlier.total} visits, ${r.earlier.verified} verified`
231
+ );
232
+ for (const a of r.earlier.agents.slice(0, 8))
233
+ lines.push(` ${a.agent.padEnd(22)} ${String(a.total).padStart(6)} (${a.verified} verified)`);
234
+ }
227
235
  if (r.top_paths?.length) {
228
236
  lines.push("", "Most read:");
229
237
  for (const p of r.top_paths.slice(0, 10)) lines.push(` ${String(p.total).padStart(6)} ${p.path}`);
package/lib/oauth.mjs CHANGED
@@ -216,8 +216,22 @@ export async function deviceLogin({
216
216
 
217
217
  io.log(`Open this link, pick the organization and click Allow:\n ${start.verification_uri_complete}\n`);
218
218
  io.log(`Code: ${start.user_code} (the page shows the same one)`);
219
+ io.log(
220
+ "No Letter account yet? Run `letterstory signup --email <work email>` instead: Letter emails a link to create one."
221
+ );
219
222
  io.log("Waiting for approval…");
223
+ return pollDeviceToken({ base, start, fetchImpl, sleep, again: "Run `login --device` again." });
224
+ }
220
225
 
226
+ // The device-code poll (RFC 8628 §3.4-3.5), shared by `login --device` and `signup`: polls /token
227
+ // every `interval` seconds until the person approves (or confirms their signup) in a browser.
228
+ export async function pollDeviceToken({
229
+ base,
230
+ start,
231
+ fetchImpl = globalThis.fetch,
232
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
233
+ again,
234
+ }) {
221
235
  let intervalMs = (start.interval ?? 5) * 1000;
222
236
  const deadline = Date.now() + (start.expires_in ?? 600) * 1000;
223
237
  while (Date.now() < deadline) {
@@ -245,10 +259,10 @@ export async function deviceLogin({
245
259
  continue;
246
260
  }
247
261
  if (error === "access_denied") throw new CliError("Sign-in was cancelled in the browser.");
248
- if (error === "expired_token") throw new CliError("The link expired. Run `login --device` again.");
262
+ if (error === "expired_token") throw new CliError(`The link expired. ${again}`);
249
263
  throw new CliError(`Login failed: ${json?.error_description || error || `HTTP ${poll.status}`}`);
250
264
  }
251
- throw new CliError("The link expired before it was approved. Run `login --device` again.");
265
+ throw new CliError(`The link expired before it was approved. ${again}`);
252
266
  }
253
267
 
254
268
  export async function refreshAccessToken({ url, refreshToken, fetchImpl = globalThis.fetch }) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.165.2",
3
+ "version": "0.167.1",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",