@letterstory/cli 0.175.20 → 0.175.22

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
@@ -9,7 +9,8 @@ import {
9
9
  PAYMENT_REQUIRED_CODES,
10
10
  resolveConfig,
11
11
  readConfigFile,
12
- writeConfigFile,
12
+ saveRefreshedSession,
13
+ storedSession,
13
14
  } from "./client.mjs";
14
15
  import { resolveDocumentFlags } from "./documents.mjs";
15
16
  import { checkForUpdate } from "./update-check.mjs";
@@ -78,7 +79,7 @@ import {
78
79
  } from "./commands.mjs";
79
80
 
80
81
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
81
- export const VERSION = "0.175.20";
82
+ export const VERSION = "0.175.22";
82
83
 
83
84
  /** The exit code for a gate refusal (CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS): 1 is a plain error. */
84
85
  export const EXIT_PAYMENT_REQUIRED = 3;
@@ -109,6 +110,8 @@ export const BOOLEAN_FLAGS = new Set([
109
110
  "customers",
110
111
  // build: repeat an open build's ask; post its progress in the org's Slack channel.
111
112
  "again",
113
+ // build list: only Build's Archived tab (--open, already listed, is its Open tab).
114
+ "archived",
112
115
  // ask --web: read the web in the Plan's fit for a recipe the facts can't decide (off by default).
113
116
  "web",
114
117
  "notify-slack",
@@ -242,6 +245,8 @@ export const BOOLEAN_FLAGS = new Set([
242
245
  // `phantom-onboard collection --enable-planner`, `strategy sitemap --posts-only`, and the
243
246
  // `strategy positioning set --clear-*` switches: value-less, and each sits next to a value.
244
247
  "enable-planner",
248
+ // `phantom-onboard collection --start-writing`: value-less, like --enable-planner.
249
+ "start-writing",
245
250
  // `phantom-onboard primitives --retry [<domain>]` re-reads a domain whose read failed.
246
251
  "retry",
247
252
  "posts-only",
@@ -883,7 +888,7 @@ What does this org still need? (the router — reads only, decides nothing):
883
888
  Collection onboarding (your OWN blog, on your org's domain — no provisioning):
884
889
  ${bin === "phantom" ? "onboard" : "phantom-onboard"} collection [--collection <uuid>] [--name "<collection name>"]
885
890
  [--about "the direction"] [--sitemap <url>] [--cms <provider>]
886
- [--enable-planner [--cadence <n/week>] [--approval manual|review_window|autopilot]] [--watch]
891
+ [--start-writing | --enable-planner [--cadence <n/week>] [--approval manual|review_window|autopilot]] [--watch]
887
892
  Import the existing blog from its sitemap
888
893
  (auto-discovered from the org's domain unless
889
894
  --sitemap pins one) OR from a connected CMS with
@@ -897,6 +902,9 @@ Collection onboarding (your OWN blog, on your org's domain — no provisioning):
897
902
  (same activation as the app's Guided review step;
898
903
  needs a user-scoped key). --approval defaults to
899
904
  manual: nothing publishes unreviewed.
905
+ --start-writing instead starts what the blog
906
+ writes once it is read in: the starter
907
+ automations, every draft for review.
900
908
  ${bin === "phantom" ? "onboard" : "phantom-onboard"} sync-sitemap --collection <uuid>
901
909
  Re-check an already-onboarded blog's sitemap
902
910
  right now instead of waiting for its cadence
@@ -959,9 +967,17 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
959
967
  nothing. Exits 1 if any row failed.
960
968
  admin recipes save [<id>] [--file <recipe.json>] [--name …] [--description …] [--recipe …]
961
969
  [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo]
970
+ [--reads llms_txt,github]
962
971
  Create one (no id) or change one; variations come from
963
- --file. Needs recipes:write.
972
+ --file. --reads names the facts its conditions rest on
973
+ (vocab lists them). Needs recipes:write.
964
974
  admin recipes delete <id> --yes Delete for good.
975
+ admin recipes refit [--org <id>,…] [--recipe <id|name>] [--limit 10]
976
+ Decide accounts' recipes again now, not on the hourly
977
+ sweep's turn: --org those accounts (every recipe);
978
+ --recipe every account whose verdict on it is missing
979
+ or stale; neither, every account stale for the library.
980
+ Each is a model call. Needs recipes:write.
965
981
  admin letterpress status [--customers] Letterpress as it runs now: per lens its mode, bar, recipes,
966
982
  runs, model and prompt hash, how often the shadow agreed,
967
983
  how runs grounded (a recipe / none). Needs recipes:read.
@@ -1589,6 +1605,14 @@ Build (a change to your site, or launching what isn't code; the Build box's own
1589
1605
  Staff only. The same prompt on Letterpress-1 (as Build runs it) and on
1590
1606
  stock Claude Code and stock Codex, each a preview to compare
1591
1607
  build benchmarks [--id <uuid>] [--limit <n>] Staff only. Benchmarks, each arm's state, preview, cost and agent time
1608
+ build list [--limit <n>] [--site <host>] [--kind build|fix] [--open|--archived]
1609
+ Your builds, newest first, with where each stands
1610
+ build status <build-id> One build: each change's state, its preview and pull request
1611
+ build follow <build-id> [--json] What its agents do, line by line, until nothing in it is at
1612
+ work (as letterpress follows a build); --json: one line per event
1613
+ build conversations [--limit <n>] Your conversations with Build, most recently active first
1614
+ build conversation <conversation-id> | --build <build-id>
1615
+ Every message in one, oldest first
1592
1616
 
1593
1617
  The Site (one model of your whole marketing site, keyed by host and path):
1594
1618
  site list Mapped hosts, and hosts you already have elsewhere
@@ -1909,13 +1933,22 @@ export async function run(argv, io = defaultIo()) {
1909
1933
  // invocation doesn't have to refresh again — but only when the config we
1910
1934
  // resolved actually came from a saved OAuth session (a --key/env override
1911
1935
  // for this one call shouldn't get written back to disk as a login).
1936
+ //
1937
+ // The session may be refreshed by letterpress or another command at the same time: the client
1938
+ // reads the file again before refreshing and adopts what another process saved (a refresh
1939
+ // token used twice signs every process out), and a refresh is saved to letterpress's orgs[]
1940
+ // entry for the session too, so switching back to it there never restores a spent token.
1941
+ const signedInOrg = config.keySource === "oauth" ? (readConfigFile().org ?? null) : null;
1912
1942
  const onTokensRefreshed =
1913
- config.keySource === "oauth" ? (oauth) => writeConfigFile({ ...readConfigFile(), oauth }) : undefined;
1943
+ config.keySource === "oauth"
1944
+ ? (oauth, spent) => saveRefreshedSession(oauth, signedInOrg, spent)
1945
+ : undefined;
1914
1946
  const client = new LetterstoryClient({
1915
1947
  url: config.url,
1916
1948
  key: config.key,
1917
1949
  oauth: config.oauth,
1918
1950
  onTokensRefreshed,
1951
+ readStoredSession: config.keySource === "oauth" ? () => storedSession(signedInOrg) : undefined,
1919
1952
  verbose: Boolean(flags.verbose),
1920
1953
  verboseLog: io.error,
1921
1954
  bin,
package/lib/client.mjs CHANGED
@@ -27,6 +27,38 @@ export class CliError extends Error {
27
27
  /** The gate refusals' codes (the app's 402 body and an MCP error's structuredContent). */
28
28
  export const PAYMENT_REQUIRED_CODES = ["CARD_REQUIRED", "PAYMENT_FAILED", "OUT_OF_TOKENS"];
29
29
 
30
+ // How long one request waits on Letter before it reads as a lost connection. Discovery, tools/list
31
+ // and a token refresh answer in a second or two; a tool call can work for a while (a plan, a
32
+ // synchronous shred), so it waits longer, and the turns that plan and start a build longest.
33
+ // LETTERSTORY_TIMEOUT_MS overrides all three (a slow link, a long synchronous run).
34
+ export const REQUEST_TIMEOUT_MS = 30_000;
35
+ export const TOOL_TIMEOUT_MS = 120_000;
36
+ export const LONG_TOOL_TIMEOUT_MS = 300_000;
37
+ export const LONG_TOOLS = new Set([
38
+ "start_build",
39
+ "send_build_message",
40
+ "start_build_benchmark",
41
+ "propose_account_plan",
42
+ ]);
43
+
44
+ function timeoutFor(kind, toolName) {
45
+ const env = Number(process.env.LETTERSTORY_TIMEOUT_MS);
46
+ if (Number.isFinite(env) && env > 0) return env;
47
+ if (kind !== "tool") return REQUEST_TIMEOUT_MS;
48
+ return LONG_TOOLS.has(toolName) ? LONG_TOOL_TIMEOUT_MS : TOOL_TIMEOUT_MS;
49
+ }
50
+
51
+ const isTimeout = (err) => err?.name === "TimeoutError" || err?.name === "AbortError";
52
+
53
+ /** Pure: Retry-After (seconds, or an HTTP date) in ms; null when absent or unreadable. */
54
+ export function retryAfterMs(value, now = Date.now()) {
55
+ if (value == null || value === "") return null;
56
+ const seconds = Number(value);
57
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
58
+ const at = Date.parse(String(value));
59
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
60
+ }
61
+
30
62
  // Config lives at ~/.letterstory/config.json. LETTERSTORY_CONFIG_HOME overrides the
31
63
  // home dir (the tests point it at a temp dir so they never touch the real file).
32
64
  export function configPath() {
@@ -54,6 +86,46 @@ export function writeConfigFile(config) {
54
86
  return path;
55
87
  }
56
88
 
89
+ // One sign-in may be refreshed by several processes at once: this CLI, letterpress, a second
90
+ // letterpress window. The server revokes the whole session when a refresh token is used again
91
+ // more than 30s later (src/lib/oauth/core.ts), so a process must never refresh with a token
92
+ // another one already spent: before refreshing it reads the file again, and adopts what is there.
93
+ //
94
+ // `org` is the organization the process started on (the file's `org`, which letterpress sets).
95
+ // The stored session for it is the active one while it is still that org, else its orgs[] entry —
96
+ // never another organization's sign-in that a letterpress /org switch made active meanwhile.
97
+
98
+ /** The saved tokens for the session this process started on, as the file holds them now; null when there are none. */
99
+ export function storedSession(org) {
100
+ const file = readConfigFile();
101
+ if (!org || !file.org || file.org === org) return file.oauth?.access_token ? file.oauth : null;
102
+ const entry = (file.orgs ?? []).find((o) => o?.name === org)?.oauth;
103
+ return entry?.access_token ? entry : null;
104
+ }
105
+
106
+ /**
107
+ * Save refreshed tokens where that session is kept: `oauth` while it is still the active one, and
108
+ * its orgs[] entry (letterpress's list of saved sign-ins) when there is one, so an /org switch back
109
+ * never restores a refresh token that was already spent.
110
+ *
111
+ * @param {object} oauth
112
+ * @param {string | null | undefined} org
113
+ * @param {string | null} [spentRefreshToken]
114
+ */
115
+ export function saveRefreshedSession(oauth, org, spentRefreshToken = null) {
116
+ const file = readConfigFile();
117
+ const name = org ?? file.org ?? null;
118
+ const active = !org || !file.org || file.org === org;
119
+ const orgs = Array.isArray(file.orgs)
120
+ ? file.orgs.map((o) =>
121
+ (name && o?.name === name) || (spentRefreshToken && o?.oauth?.refresh_token === spentRefreshToken)
122
+ ? { ...o, oauth }
123
+ : o
124
+ )
125
+ : undefined;
126
+ writeConfigFile({ ...file, ...(active ? { oauth } : {}), ...(orgs ? { orgs } : {}) });
127
+ }
128
+
57
129
  export function clearConfigFile() {
58
130
  const path = configPath();
59
131
  if (existsSync(path)) rmSync(path);
@@ -81,17 +153,37 @@ export function resolveConfig({ url, key } = {}) {
81
153
  return { url: resolvedUrl, key: file.key || null, oauth: null, keySource: file.key ? "file" : "none" };
82
154
  }
83
155
 
156
+ // The server couldn't be reached, didn't answer in time, or is overloaded or falling over (429,
157
+ // a bare 5xx): a connection problem, not a refusal. `status` and `retryAfterMs` say which, when known.
158
+ export class NetworkError extends CliError {}
159
+
84
160
  export class LetterstoryClient {
85
161
  // `oauth` is { access_token, refresh_token, expires_at, scope } from a
86
162
  // browser login. `onTokensRefreshed(oauth)` is called after a successful
87
163
  // silent refresh so the caller can persist the new tokens to disk —
88
164
  // this class never touches the config file itself.
89
- constructor({ url, key, oauth, fetchImpl, onTokensRefreshed, verbose, verboseLog, bin } = {}) {
165
+ // `readStoredSession()` returns the tokens saved for this session now (storedSession): another
166
+ // process may have refreshed them, and those are adopted instead of refreshing again.
167
+ // `timeoutMs` overrides every request's timeout (tests).
168
+ constructor({
169
+ url,
170
+ key,
171
+ oauth,
172
+ fetchImpl,
173
+ onTokensRefreshed,
174
+ readStoredSession,
175
+ timeoutMs,
176
+ verbose,
177
+ verboseLog,
178
+ bin,
179
+ } = {}) {
90
180
  this.url = (url || DEFAULT_API_URL).replace(/\/+$/, "");
91
181
  this.key = key || null;
92
182
  this.oauth = oauth || null;
93
183
  this.fetch = fetchImpl || globalThis.fetch;
94
184
  this.onTokensRefreshed = onTokensRefreshed || (() => {});
185
+ this.readStoredSession = readStoredSession || (() => null);
186
+ this.timeoutMs = timeoutMs ?? null;
95
187
  this.bin = bin || "letterstory";
96
188
  this.verbose = Boolean(verbose);
97
189
  this.verboseLog = verboseLog || ((m) => process.stderr.write(`${m}\n`));
@@ -107,14 +199,97 @@ export class LetterstoryClient {
107
199
  async discover() {
108
200
  if (this.verbose) this.verboseLog(`» GET ${this.mcpEndpoint}`);
109
201
  let res;
202
+ const ms = this.timeoutMs ?? timeoutFor("request");
110
203
  try {
111
- res = await this.fetch(this.mcpEndpoint, { headers: { accept: "application/json" } });
204
+ res = await this.fetch(this.mcpEndpoint, {
205
+ headers: { accept: "application/json" },
206
+ signal: AbortSignal.timeout(ms),
207
+ });
112
208
  } catch (err) {
113
- throw new CliError(`Could not reach ${this.mcpEndpoint}: ${err.message}`);
209
+ throw this.unreachable(this.mcpEndpoint, err, ms);
114
210
  }
115
211
  if (this.verbose) this.verboseLog(`« ${res.status}`);
116
212
  if (!res.ok) throw new CliError(`Discovery failed (HTTP ${res.status}) at ${this.mcpEndpoint}`);
117
- return res.json();
213
+ try {
214
+ return await res.json();
215
+ } catch (err) {
216
+ throw isTimeout(err)
217
+ ? this.unreachable(this.mcpEndpoint, err, ms)
218
+ : new CliError(`Discovery returned something unreadable at ${this.mcpEndpoint}`);
219
+ }
220
+ }
221
+
222
+ /** A request that never got an answer, said plainly: unreachable, or no answer in time. */
223
+ unreachable(url, err, ms, { tool = null } = {}) {
224
+ if (isTimeout(err)) {
225
+ const after = tool ? ` It may still have gone through: check before running ${tool} again.` : "";
226
+ return new NetworkError(
227
+ `Letter didn't answer within ${Math.round(ms / 1000)}s (${url}). Check your connection and try again.${after}`
228
+ );
229
+ }
230
+ return new NetworkError(`Could not reach ${url}: ${err?.message ?? err}`);
231
+ }
232
+
233
+ /**
234
+ * The failure a response that isn't the answer stands for, or null: too many requests (429, with
235
+ * how long Retry-After says to wait), or the server falling over (a 5xx with no JSON body, an
236
+ * HTML error page from the platform): both are said plainly, as a connection problem, never as
237
+ * "unexpected non-JSON".
238
+ */
239
+ transientFailure(res, body, url) {
240
+ if (res.status === 429) {
241
+ const wait = retryAfterMs(res.headers?.get?.("retry-after"));
242
+ const err = new NetworkError(
243
+ `Letter is getting too many requests right now${wait != null ? `; try again in ${Math.max(1, Math.ceil(wait / 1000))}s` : "; try again in a moment"}.`
244
+ );
245
+ err.status = 429;
246
+ err.retryAfterMs = wait;
247
+ return err;
248
+ }
249
+ if (res.status >= 500 && !body?.error) {
250
+ const err = new NetworkError(
251
+ `Letter is having trouble right now (HTTP ${res.status} from ${url}). Try again in a moment.`
252
+ );
253
+ err.status = res.status;
254
+ return err;
255
+ }
256
+ return null;
257
+ }
258
+
259
+ /** The response's JSON, or null when it has none; a body cut off by the timeout is a lost connection. */
260
+ async readJson(res, url, ms, opts) {
261
+ try {
262
+ return await res.json();
263
+ } catch (err) {
264
+ if (isTimeout(err)) throw this.unreachable(url, err, ms, opts);
265
+ return null;
266
+ }
267
+ }
268
+
269
+ // Recover a rejected session: adopt tokens another process saved since this one read them; else
270
+ // refresh once; and if that refresh fails, adopt what a racing process saved meanwhile.
271
+ async recoverSession(recovery) {
272
+ if (!this.oauth?.refresh_token) return false;
273
+ if (this.adoptStoredSession()) return true;
274
+ if (recovery.refreshed) return false;
275
+ recovery.refreshed = true;
276
+ if (await this.tryRefresh()) return true;
277
+ return this.adoptStoredSession();
278
+ }
279
+
280
+ /** Take the saved tokens when they differ from the ones in memory. */
281
+ adoptStoredSession() {
282
+ let stored = null;
283
+ try {
284
+ stored = this.readStoredSession();
285
+ } catch {
286
+ stored = null;
287
+ }
288
+ if (!stored?.access_token) return false;
289
+ if (stored.access_token === this.oauth?.access_token && stored.refresh_token === this.oauth?.refresh_token)
290
+ return false;
291
+ this.oauth = stored;
292
+ return true;
118
293
  }
119
294
 
120
295
  authHeaders() {
@@ -129,7 +304,7 @@ export class LetterstoryClient {
129
304
  // has no such recovery, since a rejected key is just wrong.
130
305
  // `keyless`: a public tool (start_signup, finish_signup) is called with no credentials at all,
131
306
  // by someone who has no account yet.
132
- async rpc(method, params, { _retried = false, keyless = false } = {}) {
307
+ async rpc(method, params, { _recovery = null, keyless = false } = {}) {
133
308
  const authHeaders = keyless ? {} : this.authHeaders();
134
309
  if (!authHeaders) {
135
310
  throw new CliError(
@@ -137,6 +312,8 @@ export class LetterstoryClient {
137
312
  );
138
313
  }
139
314
  if (this.verbose) this.verboseLog(`» POST ${this.mcpEndpoint} (${method})`);
315
+ const tool = method === "tools/call" ? params?.name : null;
316
+ const ms = this.timeoutMs ?? timeoutFor(tool ? "tool" : "request", tool);
140
317
  let res;
141
318
  try {
142
319
  res = await this.fetch(this.mcpEndpoint, {
@@ -147,22 +324,27 @@ export class LetterstoryClient {
147
324
  ...authHeaders,
148
325
  },
149
326
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
327
+ signal: AbortSignal.timeout(ms),
150
328
  });
151
329
  } catch (err) {
152
- throw new CliError(`Could not reach ${this.mcpEndpoint}: ${err.message}`);
330
+ throw this.unreachable(this.mcpEndpoint, err, ms, { tool });
153
331
  }
154
332
  if (this.verbose) this.verboseLog(`« ${res.status}`);
155
333
  // Auth failures come back as a plain HTTP error, not a JSON-RPC envelope.
156
- if (res.status === 401 || res.status === 403) {
157
- if (!_retried && this.oauth?.refresh_token && (await this.tryRefresh())) {
158
- return this.rpc(method, params, { _retried: true });
334
+ if (!keyless && (res.status === 401 || res.status === 403)) {
335
+ const recovery = _recovery ?? { refreshed: false, tries: 0 };
336
+ if (recovery.tries < 2 && (await this.recoverSession(recovery))) {
337
+ recovery.tries++;
338
+ return this.rpc(method, params, { _recovery: recovery });
159
339
  }
160
340
  const hint = this.oauth
161
341
  ? `Your session has expired. Run \`${this.bin} login\` again.`
162
342
  : "Check your API key and its capabilities.";
163
343
  throw new CliError(`Authentication failed (HTTP ${res.status}). ${hint}`);
164
344
  }
165
- const body = await res.json().catch(() => null);
345
+ const body = await this.readJson(res, this.mcpEndpoint, ms, { tool });
346
+ const transient = this.transientFailure(res, body, this.mcpEndpoint);
347
+ if (transient) throw transient;
166
348
  if (!body) throw new CliError(`Unexpected non-JSON response (HTTP ${res.status}) from ${this.mcpEndpoint}`);
167
349
  if (body.error) {
168
350
  const detail = body.error.data ? `: ${JSON.stringify(body.error.data)}` : "";
@@ -187,7 +369,7 @@ export class LetterstoryClient {
187
369
  * @param {FormData} form
188
370
  * @returns {Promise<any>} the parsed JSON body
189
371
  */
190
- async postForm(path, form, { _retried = false } = {}) {
372
+ async postForm(path, form, { _recovery = null } = {}) {
191
373
  const authHeaders = this.authHeaders();
192
374
  if (!authHeaders) {
193
375
  throw new CliError(
@@ -196,27 +378,34 @@ export class LetterstoryClient {
196
378
  }
197
379
  const url = `${this.url}${path}`;
198
380
  if (this.verbose) this.verboseLog(`» POST ${url} (multipart)`);
381
+ // Bytes going up take longer than a JSON call: the tool-call timeout, not the request one.
382
+ const ms = this.timeoutMs ?? timeoutFor("tool");
199
383
  let res;
200
384
  try {
201
385
  res = await this.fetch(url, {
202
386
  method: "POST",
203
387
  headers: { accept: "application/json", ...authHeaders },
204
388
  body: form,
389
+ signal: AbortSignal.timeout(ms),
205
390
  });
206
391
  } catch (err) {
207
- throw new CliError(`Could not reach ${url}: ${err.message}`);
392
+ throw this.unreachable(url, err, ms);
208
393
  }
209
394
  if (this.verbose) this.verboseLog(`« ${res.status}`);
210
395
  if (res.status === 401 || res.status === 403) {
211
- if (!_retried && this.oauth?.refresh_token && (await this.tryRefresh())) {
212
- return this.postForm(path, form, { _retried: true });
396
+ const recovery = _recovery ?? { refreshed: false, tries: 0 };
397
+ if (recovery.tries < 2 && (await this.recoverSession(recovery))) {
398
+ recovery.tries++;
399
+ return this.postForm(path, form, { _recovery: recovery });
213
400
  }
214
401
  const hint = this.oauth
215
402
  ? `Your session has expired. Run \`${this.bin} login\` again.`
216
403
  : "Check your API key and its capabilities.";
217
404
  throw new CliError(`Authentication failed (HTTP ${res.status}). ${hint}`);
218
405
  }
219
- const body = await res.json().catch(() => null);
406
+ const body = await this.readJson(res, url, ms);
407
+ const transient = this.transientFailure(res, body, url);
408
+ if (transient) throw transient;
220
409
  if (!res.ok) {
221
410
  throw new CliError(body?.error ? String(body.error) : `Request failed (HTTP ${res.status}) at ${url}`, {
222
411
  code: typeof body?.code === "string" ? body.code : null,
@@ -231,18 +420,19 @@ export class LetterstoryClient {
231
420
  async tryRefresh() {
232
421
  try {
233
422
  const { refreshAccessToken } = await import("./oauth.mjs");
423
+ const spent = this.oauth.refresh_token;
234
424
  const tokens = await refreshAccessToken({
235
425
  url: this.url,
236
- refreshToken: this.oauth.refresh_token,
426
+ refreshToken: spent,
237
427
  fetchImpl: this.fetch,
238
428
  });
239
429
  this.oauth = {
240
430
  access_token: tokens.access_token,
241
- refresh_token: tokens.refresh_token || this.oauth.refresh_token,
431
+ refresh_token: tokens.refresh_token || spent,
242
432
  expires_at: Date.now() + (tokens.expires_in ?? 3600) * 1000,
243
433
  scope: tokens.scope,
244
434
  };
245
- this.onTokensRefreshed(this.oauth);
435
+ this.onTokensRefreshed(this.oauth, spent);
246
436
  return true;
247
437
  } catch {
248
438
  return false;
@@ -18,7 +18,7 @@
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|runs|vocab|export|import|save|delete … (recipes:read / recipes:write)
21
+ // admin recipes list|show|runs|vocab|export|import|save|delete|refit … (recipes:read / recipes:write)
22
22
  // admin letterpress companies | company <org-id> | facts <org-id> (the standing fit, per company)
23
23
  // admin letterpress beyond [--limit N] [--before ISO] (what members asked that went past the library)
24
24
  // admin letterpress settings|flip|set … (recipes:read / recipes:write)
@@ -5031,13 +5031,16 @@ const RECIPE_FILE_FIELDS = [
5031
5031
  "when_not_to_use",
5032
5032
  "weight",
5033
5033
  "approaches",
5034
+ "reads",
5034
5035
  "runs",
5036
+ "primitives_access",
5037
+ "immediate",
5035
5038
  "status",
5036
5039
  "needs",
5037
5040
  "variations",
5038
5041
  ];
5039
5042
  const RECIPES_USAGE =
5040
- "Usage: admin recipes list [--kind recipe|known_issue] [--status live|parked] [--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>] [--kind recipe|known_issue] [--name …] [--description …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo,…] [--runs <catalog action id>] [--status live|parked] [--needs <what a parked recipe is missing>] | delete <id> --yes";
5043
+ "Usage: admin recipes list [--kind recipe|known_issue] [--status live|parked] [--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] | refit [--org <id>,…] [--recipe <id|name>] [--limit n] | save [<id>] [--file <recipe.json>] [--kind recipe|known_issue] [--name …] [--description …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo,…] [--reads llms_txt,github,…] [--runs <catalog action id>] [--primitives-access true|false] [--immediate true|false] [--status live|parked] [--needs <what a parked recipe is missing>] | delete <id> --yes";
5041
5044
 
5042
5045
  const recipeForFile = (r) => Object.fromEntries(RECIPE_FILE_FIELDS.map((k) => [k, r[k]]));
5043
5046
 
@@ -5069,8 +5072,11 @@ function recipeDetail(r) {
5069
5072
  `${r.name} weight ${r.weight}/10 ${r.id}`,
5070
5073
  ` kind: ${r.kind === "known_issue" ? "known issue (Fix's list)" : "recipe (the Plan's)"}`,
5071
5074
  ` approaches: ${recipeApproaches(r)}`,
5075
+ ` reads: ${r.reads?.length ? r.reads.join(", ") : "— (not written: every probe runs)"}`,
5072
5076
  ` status: ${r.status === "parked" ? `parked${r.needs ? `, needs ${r.needs}` : ""}` : "live"}`,
5073
5077
  ` runs: ${r.runs || "one change to the site's code, from its own directions"}`,
5078
+ ...(r.primitives_access ? [" letter's tools: its build may use them (primitives_access)"] : []),
5079
+ ...(r.immediate ? [" immediate: a quick win: the Plan puts one in every top three"] : []),
5074
5080
  ...(variations.length > 1
5075
5081
  ? variations.flatMap((v, i) => [` variation ${i + 1}: ${v.name}`, ...fields(v, " ")])
5076
5082
  : fields(r, " ")),
@@ -5120,6 +5126,16 @@ function recipeFromFlags(flags) {
5120
5126
  ?.split(",")
5121
5127
  .map((a) => a.trim())
5122
5128
  .filter(Boolean),
5129
+ // --primitives-access true hands a start's build Letter's own tools; false takes them away.
5130
+ primitives_access:
5131
+ flags["primitives-access"] === undefined ? undefined : String(flags["primitives-access"]) === "true",
5132
+ // --immediate true marks a quick win (live within a day): the Plan puts one in every top three.
5133
+ immediate: flags.immediate === undefined ? undefined : String(flags.immediate) === "true",
5134
+ // --reads llms_txt,github declares the facts its conditions rest on; --reads "" clears them.
5135
+ reads: flagStr(flags.reads)
5136
+ ?.split(",")
5137
+ .map((k) => k.trim())
5138
+ .filter(Boolean),
5123
5139
  });
5124
5140
  }
5125
5141
 
@@ -5677,6 +5693,40 @@ async function cmdAdminRecipes(ctx) {
5677
5693
  printResult(io, flags, result, (r) => recipeDetail(r.recipe));
5678
5694
  return 0;
5679
5695
  }
5696
+ case "refit": {
5697
+ // refit_accounts: the standing fit decided again now, not on the hourly sweep's turn.
5698
+ const orgs = flagStr(flags.org);
5699
+ const key = flagStr(flags.recipe);
5700
+ const limit = flagNum(flags.limit);
5701
+ let recipeId;
5702
+ if (key) {
5703
+ const recipe = (await all()).find((r) => r.id === key || r.name === key);
5704
+ if (!recipe) throw new CliError(`No recipe with id or name "${key}".`);
5705
+ recipeId = recipe.id;
5706
+ }
5707
+ const result = await staffPost(ctx, `${RECIPES}/refit`, {
5708
+ ...(orgs
5709
+ ? {
5710
+ org_ids: orgs
5711
+ .split(",")
5712
+ .map((s) => s.trim())
5713
+ .filter(Boolean),
5714
+ }
5715
+ : {}),
5716
+ ...(recipeId ? { recipe_id: recipeId } : {}),
5717
+ ...(limit !== undefined ? { limit } : {}),
5718
+ });
5719
+ printResult(io, flags, result, (r) =>
5720
+ [
5721
+ ...r.outcomes.map(
5722
+ (o) =>
5723
+ `${o.status.padEnd(11)} ${(o.domain ?? "—").padEnd(28)} ${o.org_id}${o.reason ? ` ${o.reason}` : ""}`
5724
+ ),
5725
+ `${r.picked} account(s) taken (${r.mode})${r.left ? `, ${r.left} more past the limit` : ""}: ${r.outcomes.filter((o) => o.status === "refit").length} refit, ${r.outcomes.filter((o) => o.status === "standing").length} stood, ${r.outcomes.filter((o) => o.status === "failed").length} failed, ${r.outcomes.filter((o) => o.status === "not_reached").length} not reached.`,
5726
+ ].join("\n")
5727
+ );
5728
+ return result.outcomes?.some((o) => o.status === "failed") ? 1 : 0;
5729
+ }
5680
5730
  case "delete": {
5681
5731
  const id = requirePositional(positionals, 1, "id");
5682
5732
  if (!flagBool(flags.yes)) {
@@ -8,9 +8,14 @@
8
8
  // build benchmark <words…> → start_build_benchmark (staff only: Letterpress-1, stock Claude Code
9
9
  // and stock Codex on the same prompt, each a preview)
10
10
  // build benchmarks → list_build_benchmarks (staff only; --id <uuid> for one)
11
+ // build list → list_growth_builds (newest first; --site, --kind, --open/--archived)
12
+ // build status <id> → list_growth_builds (one build: its steps, previews and PRs)
13
+ // build follow <id> → list_growth_builds + get_repo_change_activity, until nothing is at work
14
+ // build conversations → list_build_conversations
15
+ // build conversation <id> → get_build_conversation (--build <id> for the one holding a build)
11
16
 
12
17
  import { CliError } from "../client.mjs";
13
- import { argsFromFlags, flagList, flagStr, ok, printResult, refuseUnknownFlags } from "./shared.mjs";
18
+ import { argsFromFlags, flagList, flagStr, followJob, ok, printResult, refuseUnknownFlags } from "./shared.mjs";
14
19
  import { attachmentUrls, uploadAttachments } from "./repo.mjs";
15
20
 
16
21
  const ARGS = {
@@ -59,6 +64,20 @@ const ARGS = {
59
64
  id: "id",
60
65
  limit: { flag: "limit", type: "num" },
61
66
  },
67
+ // `build list` and `build status <id>` / `build follow <id>` (the id positional).
68
+ list_growth_builds: {
69
+ id: { positional: 0, label: "build-id" },
70
+ limit: { flag: "limit", type: "num" },
71
+ kind: { flag: "kind", enum: ["build", "fix"] },
72
+ domain: "site",
73
+ // --archived: Build's Archived tab; --open: its Open tab; neither: both.
74
+ archived: { flag: "archived", type: "bool", negate: "open" },
75
+ },
76
+ list_build_conversations: { limit: { flag: "limit", type: "num" } },
77
+ get_build_conversation: {
78
+ conversation_id: { positional: 0, label: "conversation-id" },
79
+ build_id: "build",
80
+ },
62
81
  };
63
82
 
64
83
  const FILE_FLAGS = ["attach", "attach-url", "attach-ref", "attach-url-ref"];
@@ -80,6 +99,8 @@ export async function cmdBuild(ctx) {
80
99
  if (ctx.positionals[0] === "cancel") return buildCancel({ ...ctx, positionals: ctx.positionals.slice(1) });
81
100
  if (ctx.positionals[0] === "benchmark") return buildBenchmark({ ...ctx, positionals: ctx.positionals.slice(1) });
82
101
  if (ctx.positionals[0] === "benchmarks") return buildBenchmarks({ ...ctx, positionals: ctx.positionals.slice(1) });
102
+ const read = readCommand(ctx.positionals);
103
+ if (read) return read({ ...ctx, positionals: ctx.positionals.slice(1) });
83
104
  return buildStart(ctx);
84
105
  }
85
106
 
@@ -185,4 +206,184 @@ async function buildTalk(ctx) {
185
206
  return 0;
186
207
  }
187
208
 
209
+ // ——— Reading builds back: what Build's list and a build's page show ———
210
+
211
+ /** A build's change steps as lines: where each stands, then its preview and pull request. */
212
+ export function buildLines(b) {
213
+ const where = b.reading?.detail ?? b.status;
214
+ const lines = [`${b.id} ${b.status} ${b.title}${b.domain ? ` (${b.domain})` : ""}`, ` ${where}`];
215
+ for (const s of b.steps ?? []) {
216
+ lines.push(` ${s.lane ?? s.status} ${s.title ?? "Step"}${s.note ? `: ${s.note}` : ""}`);
217
+ if (s.attention) lines.push(` ${s.attention}`);
218
+ if (s.preview_url) lines.push(` preview: ${s.preview_url}`);
219
+ if (s.pr_url) lines.push(` pull request: ${s.pr_url}`);
220
+ }
221
+ return lines.join("\n");
222
+ }
223
+
224
+ /** One build by id, or a plain refusal. */
225
+ async function readBuild(client, args) {
226
+ const result = await client.callTool("list_growth_builds", args);
227
+ const build = result?.builds?.[0] ?? null;
228
+ if (!build) throw new CliError(`No build ${args.id}. \`letterstory build list\` shows the ones there are.`);
229
+ return build;
230
+ }
231
+
232
+ /** `build list`: the organization's builds, newest first. */
233
+ async function buildList(ctx) {
234
+ const { client, flags, io } = ctx;
235
+ refuseUnknownFlags(ctx, {}, ["limit", "kind", "site", "archived", "open"]);
236
+ const args = argsFromFlags(ARGS.list_growth_builds, flags, []);
237
+ const result = await client.callTool("list_growth_builds", args);
238
+ printResult(io, flags, result, (r) =>
239
+ r.builds.length
240
+ ? r.builds
241
+ .map(
242
+ (b) =>
243
+ `${b.id} ${b.status.padEnd(11)} ${b.created_at.slice(0, 10)} ${b.title}${b.domain ? ` (${b.domain})` : ""}`
244
+ )
245
+ .join("\n")
246
+ : "No builds yet."
247
+ );
248
+ return 0;
249
+ }
250
+
251
+ /** `build status <id>`: one build, its steps, previews and pull requests. */
252
+ async function buildStatus(ctx) {
253
+ const { client, flags, io } = ctx;
254
+ refuseUnknownFlags(ctx, {}, []);
255
+ const args = argsFromFlags(ARGS.list_growth_builds, {}, ctx.positionals);
256
+ if (!args.id) throw new CliError("Missing required <build-id>");
257
+ const build = await readBuild(client, args);
258
+ printResult(io, flags, { build }, (r) => buildLines(r.build));
259
+ return 0;
260
+ }
261
+
262
+ const FEED_MARK = { progress: "·", stage: "▸", say: "»", think: "◇", tool: "$", user: ">", error: "!" };
263
+
264
+ /**
265
+ * `build follow <id>`: what the build's agents do, line by line, until nothing in it is at work —
266
+ * the same reads the letterpress terminal follows a build with (list_growth_builds, then each
267
+ * change's get_repo_change_activity from the last line it printed). --json: one line per event.
268
+ */
269
+ async function buildFollow(ctx) {
270
+ const { client, flags, io } = ctx;
271
+ refuseUnknownFlags(ctx, {}, []);
272
+ const args = argsFromFlags(ARGS.list_growth_builds, {}, ctx.positionals);
273
+ if (!args.id) throw new CliError("Missing required <build-id>");
274
+ const emit = (event, text) => io.log(flags.json ? JSON.stringify(event) : text);
275
+ const since = new Map(); // run id → the newest line's `at`
276
+ const seen = new Map(); // run id → keys of lines printed (lines at `since` come again)
277
+ const ended = new Set();
278
+ const links = new Set();
279
+ const many = (build) => build.steps.filter((s) => s.run_id).length > 1;
280
+ const tick = async () => {
281
+ const build = await readBuild(client, args);
282
+ for (const step of build.steps.filter((s) => s.run_id && !ended.has(s.run_id))) {
283
+ const from = since.get(step.run_id);
284
+ const { activity } = await client.callTool("get_repo_change_activity", {
285
+ run_id: step.run_id,
286
+ ...(from ? { since: from } : {}),
287
+ });
288
+ const keys = seen.get(step.run_id) ?? new Set();
289
+ seen.set(step.run_id, keys);
290
+ for (const l of activity?.lines ?? []) {
291
+ const key = `${l.at}\u0000${l.kind}\u0000${l.text}`;
292
+ if (keys.has(key)) continue;
293
+ keys.add(key);
294
+ const who = many(build) ? `[${step.title ?? step.run_id}] ` : "";
295
+ emit(
296
+ { type: "line", run_id: step.run_id, ...l },
297
+ `${String(l.at).slice(11, 19)} ${FEED_MARK[l.kind] ?? " "} ${who}${l.text}`
298
+ );
299
+ }
300
+ const last = activity?.lines?.at(-1)?.at;
301
+ if (last) since.set(step.run_id, last);
302
+ if (activity && !activity.live) ended.add(step.run_id);
303
+ }
304
+ for (const step of build.steps) {
305
+ for (const [kind, url] of [
306
+ ["preview", step.preview_url],
307
+ ["pr", step.pr_url],
308
+ ]) {
309
+ if (!url || links.has(url)) continue;
310
+ links.add(url);
311
+ emit(
312
+ { type: kind, url, title: step.title ?? null },
313
+ `${kind === "pr" ? "Pull request" : "Preview"}: ${url}`
314
+ );
315
+ }
316
+ }
317
+ const working =
318
+ build.status === "building" ||
319
+ build.steps.some((s) => s.run_id && !ended.has(s.run_id) && s.lane === "building");
320
+ return { done: !working, value: build };
321
+ };
322
+ let { done, value: build } = await tick();
323
+ if (!done) ({ value: build } = await followJob(io, tick, { intervalMs: 5000, ceilingMs: 2 * 60 * 60 * 1000 }));
324
+ emit({ type: "done", status: build.status, build }, buildLines(build));
325
+ return 0;
326
+ }
327
+
328
+ /** `build conversations`: the organization's conversations with Build, most recently active first. */
329
+ async function buildConversations(ctx) {
330
+ const { client, flags, io } = ctx;
331
+ refuseUnknownFlags(ctx, {}, ["limit"]);
332
+ const result = await client.callTool(
333
+ "list_build_conversations",
334
+ argsFromFlags(ARGS.list_build_conversations, flags)
335
+ );
336
+ printResult(io, flags, result, (r) =>
337
+ r.conversations.length
338
+ ? r.conversations
339
+ .map((c) => `${c.id} ${c.updated_at.slice(0, 16).replace("T", " ")} ${c.title}`)
340
+ .join("\n")
341
+ : "No conversations yet."
342
+ );
343
+ return 0;
344
+ }
345
+
346
+ /** `build conversation <id>` (or --build <id>): every message, oldest first. */
347
+ async function buildConversation(ctx) {
348
+ const { client, flags, io } = ctx;
349
+ refuseUnknownFlags(ctx, {}, ["build"]);
350
+ const args = argsFromFlags(ARGS.get_build_conversation, flags, ctx.positionals);
351
+ if (!args.conversation_id && !args.build_id)
352
+ throw new CliError("Name the conversation: build conversation <id> (or --build <build-id>)");
353
+ const result = await client.callTool("get_build_conversation", args);
354
+ printResult(io, flags, result, (r) =>
355
+ [
356
+ `${r.conversation.id} ${r.conversation.title}`,
357
+ ...r.conversation.messages.map((m) =>
358
+ [
359
+ `${m.role === "member" ? ">" : "»"} ${m.body}`,
360
+ m.question ? `? ${m.question}` : null,
361
+ m.build_id ? `Build: ${m.build_id}` : null,
362
+ ]
363
+ .filter(Boolean)
364
+ .join("\n")
365
+ ),
366
+ ].join("\n\n")
367
+ );
368
+ return 0;
369
+ }
370
+
371
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
372
+
373
+ /**
374
+ * Pure: the read a `build …` line asks for, or null for words to build from. Only the exact
375
+ * shapes read ("build list", "build status <uuid>"), so "build follow-up emails for the
376
+ * pricing page" or "build list of integrations" still starts a build as it always did.
377
+ */
378
+ export function readCommand(positionals) {
379
+ const [verb, ...rest] = positionals;
380
+ if ((verb === "list" || verb === "conversations") && rest.length === 0)
381
+ return verb === "list" ? buildList : buildConversations;
382
+ if (verb === "conversation" && rest.length <= 1 && (rest.length === 0 || UUID.test(rest[0])))
383
+ return buildConversation;
384
+ if ((verb === "status" || verb === "follow") && rest.length === 1 && UUID.test(rest[0]))
385
+ return verb === "status" ? buildStatus : buildFollow;
386
+ return null;
387
+ }
388
+
188
389
  export { ARGS };
@@ -89,6 +89,9 @@ export const ARGS = {
89
89
  enable_planner: { flag: "enable-planner", type: "bool" },
90
90
  cadence_per_week: { flag: "cadence", type: "num" },
91
91
  approval_mode: { flag: "approval", enum: APPROVAL_MODES },
92
+ // Start what the blog writes once it is read in (the starter automations, every draft for
93
+ // review), the one accept apply_starter_automations makes. Not with --enable-planner.
94
+ start_writing: { flag: "start-writing", type: "bool" },
92
95
  },
93
96
  get_collection_onboard_status: {
94
97
  job_id: { internal: "the job id onboard_collection just returned" },
@@ -425,9 +428,11 @@ function formatCollectionStatus(s) {
425
428
  ` series: ${r.series ?? 0}`,
426
429
  ` open topics: ${r.spokes_open ?? 0} (${r.spokes_seo_bound ?? 0} SEO-bound)`,
427
430
  ` headlines suggested: ${r.headlines_suggested ?? 0}`,
428
- s.enable_planner
429
- ? ` Planner: ON — ${s.cadence_per_week ?? "?"}/week, ${s.approval_mode ?? "manual"} approval, queue filled.`
430
- : ` Review them in Headlines & Queue — the Planner is configured but OFF (pass --enable-planner to turn it on).`
431
+ r.writing
432
+ ? ` Writing: ${r.writing.note}`
433
+ : s.enable_planner
434
+ ? ` Planner: ON — ${s.cadence_per_week ?? "?"}/week, ${s.approval_mode ?? "manual"} approval, queue filled.`
435
+ : ` Review them in Headlines & Queue — the Planner is configured but OFF (pass --start-writing or --enable-planner to turn it on).`
431
436
  );
432
437
  }
433
438
  return lines.join("\n");
@@ -2,6 +2,7 @@
2
2
  // (src/lib/site). One subcommand per tool:
3
3
  // site list → list_sites site map <host> → map_site
4
4
  // site tree <host> [path] → get_site_tree site page <host> <path> → get_site_page
5
+ // site llms-txt <host> → get_llms_txt (the file Letter writes; --out <file> to save it)
5
6
  // site builds <host> → list_build_suggestions (--limit n)
6
7
  // site research-builds <host> → research_builds (Build's suggestion pass: propose, check, Jev, store)
7
8
  // site research-fixes <host> → research_fixes (Fix's suggestion pass: exact edits on pages that exist)
@@ -14,6 +15,8 @@
14
15
  // site competitors → list_competitor_sites site watch-competitors [d] → watch_competitor_sites
15
16
  // site highlight <domain> [--off] → set_competitor_highlight
16
17
 
18
+ import { writeFileSync } from "node:fs";
19
+
17
20
  import { CliError } from "../client.mjs";
18
21
  import {
19
22
  argsFromFlags,
@@ -66,6 +69,7 @@ const ARGS = {
66
69
  skip_suggest: { flag: "skip-suggest", type: "bool" },
67
70
  },
68
71
  unmap_site: { host: { positional: 0, required: true, label: "host" } },
72
+ get_llms_txt: { host: { positional: 0, required: true, label: "host" } },
69
73
  get_site_tree: {
70
74
  host: { positional: 0, required: true, label: "host" },
71
75
  path: { positional: 1, label: "path" },
@@ -215,6 +219,8 @@ export async function cmdSite(ctx) {
215
219
  return siteUnmap(rest);
216
220
  case "tree":
217
221
  return siteTree(rest);
222
+ case "llms-txt":
223
+ return siteLlmsTxt(rest);
218
224
  case "research-builds":
219
225
  return siteResearchBuilds(rest);
220
226
  case "research-fixes":
@@ -399,6 +405,20 @@ async function siteUnmap(ctx) {
399
405
  return 0;
400
406
  }
401
407
 
408
+ async function siteLlmsTxt(ctx) {
409
+ const { client, flags, io } = ctx;
410
+ refuseUnknownFlags(ctx, ARGS.get_llms_txt, ["out"]);
411
+ const result = await client.callTool("get_llms_txt", argsFromFlags(ARGS.get_llms_txt, flags, ctx.positionals));
412
+ const out = flagStr(flags.out);
413
+ if (out) {
414
+ writeFileSync(out, result.text);
415
+ ok(ctx, `Wrote ${out} (${result.pages} pages). ${result.where}`);
416
+ return 0;
417
+ }
418
+ printResult(io, flags, result, (r) => r.text);
419
+ return 0;
420
+ }
421
+
402
422
  async function siteTree(ctx) {
403
423
  const { client, flags, io } = ctx;
404
424
  refuseUnknownFlags(ctx, ARGS.get_site_tree);
package/lib/oauth.mjs CHANGED
@@ -120,9 +120,15 @@ async function tokenRequest(url, body, fetchImpl) {
120
120
  method: "POST",
121
121
  headers: { "content-type": "application/x-www-form-urlencoded" },
122
122
  body: new URLSearchParams(body).toString(),
123
+ // A token exchange answers in a second; never wait on it forever.
124
+ signal: AbortSignal.timeout(30_000),
123
125
  });
124
126
  } catch (err) {
125
- throw new CliError(`Could not reach ${endpoint}: ${err.message}`);
127
+ throw new CliError(
128
+ err?.name === "TimeoutError"
129
+ ? `${endpoint} didn't answer within 30s. Try again.`
130
+ : `Could not reach ${endpoint}: ${err.message}`
131
+ );
126
132
  }
127
133
  const json = await res.json().catch(() => null);
128
134
  if (!res.ok || !json?.access_token) {
@@ -10,6 +10,9 @@ import { join, dirname } from "node:path";
10
10
 
11
11
  const REGISTRY_URL = "https://registry.npmjs.org/@letterstory/cli/latest";
12
12
  const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
13
+ // A check that failed (offline, the registry down) is tried again after an hour, not on the next
14
+ // command: unrecorded, every command offline paid the whole fetch timeout.
15
+ const RETRY_AFTER_FAILURE_MS = 60 * 60 * 1000;
13
16
  const FETCH_TIMEOUT_MS = 500;
14
17
 
15
18
  function cachePath() {
@@ -77,15 +80,19 @@ export async function checkForUpdate({ currentVersion, fetchImpl = globalThis.fe
77
80
 
78
81
  const cache = readCache();
79
82
  let latest = cache?.latestVersion;
80
- const stale = !cache || typeof cache.checkedAt !== "number" || now - cache.checkedAt > CHECK_INTERVAL_MS;
83
+ const interval = cache?.failed ? RETRY_AFTER_FAILURE_MS : CHECK_INTERVAL_MS;
84
+ const stale = !cache || typeof cache.checkedAt !== "number" || now - cache.checkedAt > interval;
81
85
 
82
86
  if (stale) {
83
87
  const fetched = await fetchLatestVersion(fetchImpl);
84
88
  if (fetched) {
85
89
  latest = fetched;
86
90
  writeCache({ checkedAt: now, latestVersion: fetched });
87
- } else if (!cache) {
88
- return null; // first-ever check failed (e.g. offline) — nothing to compare against yet
91
+ } else {
92
+ // Record the attempt even though it failed, keeping the last version we knew, so the
93
+ // next command doesn't wait on the same timeout again.
94
+ writeCache({ checkedAt: now, latestVersion: cache?.latestVersion ?? null, failed: true });
95
+ if (!latest) return null; // nothing known to compare against yet
89
96
  }
90
97
  }
91
98
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.175.20",
3
+ "version": "0.175.22",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",