@letterstory/cli 0.175.20 → 0.175.21
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 +23 -3
- package/lib/client.mjs +208 -18
- package/lib/commands/build.mjs +202 -1
- package/lib/oauth.mjs +7 -1
- package/lib/update-check.mjs +10 -3
- package/package.json +1 -1
package/lib/cli.mjs
CHANGED
|
@@ -9,7 +9,8 @@ import {
|
|
|
9
9
|
PAYMENT_REQUIRED_CODES,
|
|
10
10
|
resolveConfig,
|
|
11
11
|
readConfigFile,
|
|
12
|
-
|
|
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.
|
|
82
|
+
export const VERSION = "0.175.21";
|
|
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",
|
|
@@ -1589,6 +1592,14 @@ Build (a change to your site, or launching what isn't code; the Build box's own
|
|
|
1589
1592
|
Staff only. The same prompt on Letterpress-1 (as Build runs it) and on
|
|
1590
1593
|
stock Claude Code and stock Codex, each a preview to compare
|
|
1591
1594
|
build benchmarks [--id <uuid>] [--limit <n>] Staff only. Benchmarks, each arm's state, preview, cost and agent time
|
|
1595
|
+
build list [--limit <n>] [--site <host>] [--kind build|fix] [--open|--archived]
|
|
1596
|
+
Your builds, newest first, with where each stands
|
|
1597
|
+
build status <build-id> One build: each change's state, its preview and pull request
|
|
1598
|
+
build follow <build-id> [--json] What its agents do, line by line, until nothing in it is at
|
|
1599
|
+
work (as letterpress follows a build); --json: one line per event
|
|
1600
|
+
build conversations [--limit <n>] Your conversations with Build, most recently active first
|
|
1601
|
+
build conversation <conversation-id> | --build <build-id>
|
|
1602
|
+
Every message in one, oldest first
|
|
1592
1603
|
|
|
1593
1604
|
The Site (one model of your whole marketing site, keyed by host and path):
|
|
1594
1605
|
site list Mapped hosts, and hosts you already have elsewhere
|
|
@@ -1909,13 +1920,22 @@ export async function run(argv, io = defaultIo()) {
|
|
|
1909
1920
|
// invocation doesn't have to refresh again — but only when the config we
|
|
1910
1921
|
// resolved actually came from a saved OAuth session (a --key/env override
|
|
1911
1922
|
// for this one call shouldn't get written back to disk as a login).
|
|
1923
|
+
//
|
|
1924
|
+
// The session may be refreshed by letterpress or another command at the same time: the client
|
|
1925
|
+
// reads the file again before refreshing and adopts what another process saved (a refresh
|
|
1926
|
+
// token used twice signs every process out), and a refresh is saved to letterpress's orgs[]
|
|
1927
|
+
// entry for the session too, so switching back to it there never restores a spent token.
|
|
1928
|
+
const signedInOrg = config.keySource === "oauth" ? (readConfigFile().org ?? null) : null;
|
|
1912
1929
|
const onTokensRefreshed =
|
|
1913
|
-
config.keySource === "oauth"
|
|
1930
|
+
config.keySource === "oauth"
|
|
1931
|
+
? (oauth, spent) => saveRefreshedSession(oauth, signedInOrg, spent)
|
|
1932
|
+
: undefined;
|
|
1914
1933
|
const client = new LetterstoryClient({
|
|
1915
1934
|
url: config.url,
|
|
1916
1935
|
key: config.key,
|
|
1917
1936
|
oauth: config.oauth,
|
|
1918
1937
|
onTokensRefreshed,
|
|
1938
|
+
readStoredSession: config.keySource === "oauth" ? () => storedSession(signedInOrg) : undefined,
|
|
1919
1939
|
verbose: Boolean(flags.verbose),
|
|
1920
1940
|
verboseLog: io.error,
|
|
1921
1941
|
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
|
-
|
|
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, {
|
|
204
|
+
res = await this.fetch(this.mcpEndpoint, {
|
|
205
|
+
headers: { accept: "application/json" },
|
|
206
|
+
signal: AbortSignal.timeout(ms),
|
|
207
|
+
});
|
|
112
208
|
} catch (err) {
|
|
113
|
-
throw
|
|
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
|
-
|
|
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, {
|
|
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
|
|
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
|
-
|
|
158
|
-
|
|
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
|
|
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, {
|
|
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
|
|
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
|
-
|
|
212
|
-
|
|
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
|
|
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:
|
|
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 ||
|
|
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;
|
package/lib/commands/build.mjs
CHANGED
|
@@ -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 };
|
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(
|
|
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) {
|
package/lib/update-check.mjs
CHANGED
|
@@ -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
|
|
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
|
|
88
|
-
|
|
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
|
|