@foleo/cli 0.1.16 → 0.1.20

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/dist/index.js CHANGED
@@ -8,6 +8,7 @@ import { lstat, readdir } from "node:fs/promises";
8
8
  import { createServer } from "node:http";
9
9
  import { dirname, join, relative, resolve, sep } from "node:path";
10
10
  import { fileURLToPath, pathToFileURL } from "node:url";
11
+ import { FoleoError, LocalError, renderFailure, UsageError } from "./errors.js";
11
12
  const KEYCHAIN_SERVICE = "com.contraverse.foleo.cli";
12
13
  const CLI_KEY_SCOPES = [
13
14
  "artifacts:read",
@@ -60,6 +61,7 @@ export async function runCli(argv, deps = {
60
61
  stdout: (message) => process.stdout.write(message),
61
62
  stderr: (message) => process.stderr.write(message),
62
63
  }) {
64
+ const wantsJson = argv.includes("--json");
63
65
  try {
64
66
  const global = parseGlobalFlags(argv);
65
67
  const commandDeps = global.environment
@@ -122,6 +124,8 @@ export async function runCli(argv, deps = {
122
124
  warnDeprecatedAlias(commandDeps, "html-unpublish", "unpublish <id>");
123
125
  return await htmlUnpublish(rest, commandDeps);
124
126
  }
127
+ if (command === "name-check")
128
+ return await nameCheck(rest, commandDeps);
125
129
  if (command === "settings")
126
130
  return await settingsCommand(rest, commandDeps);
127
131
  if (command === "limits")
@@ -138,15 +142,122 @@ export async function runCli(argv, deps = {
138
142
  return await skill(rest, commandDeps);
139
143
  if (command === "doctor")
140
144
  return await doctor(rest, commandDeps);
145
+ if (wantsJson) {
146
+ const rendered = renderFailure(new UsageError(`Unknown command: ${describeArgvToken(command)}`, "unknown_command", { command: describeArgvToken(command) }), true);
147
+ if (rendered.stdout !== null)
148
+ commandDeps.stdout(rendered.stdout);
149
+ return rendered.exitCode;
150
+ }
141
151
  commandDeps.stderr(help());
142
152
  return 2;
143
153
  }
144
154
  catch (error) {
145
- deps.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
146
- return error instanceof UsageError ? 2 : 1;
155
+ const rendered = renderFailure(normalizeThrown(error), wantsJson);
156
+ if (rendered.stdout !== null)
157
+ deps.stdout(rendered.stdout);
158
+ if (rendered.stderr !== null)
159
+ deps.stderr(rendered.stderr);
160
+ return rendered.exitCode;
161
+ }
162
+ }
163
+ /**
164
+ * Usage-shaped failures exit 2 even when they were thrown as a plain `Error`.
165
+ * Twenty-six call sites throw `Usage: foleo …` prose directly, and normalising
166
+ * them one by one would leave the contract depending on nobody forgetting; the
167
+ * message prefix is the shape the CLI already commits to in `help()`.
168
+ */
169
+ function normalizeThrown(error) {
170
+ if (error instanceof FoleoError)
171
+ return error;
172
+ if (error instanceof Error && error.message.startsWith("Usage:")) {
173
+ return new UsageError(error.message);
147
174
  }
175
+ return error;
176
+ }
177
+ /**
178
+ * argv is echoed back by the "unknown command/option" errors, and those messages
179
+ * now reach *stdout* under `--json`. A shell expands secrets into argv easily
180
+ * (`foleo "$FOLEO_TOKEN"`, `--token=…`), so only a value already shaped like a
181
+ * command or flag name is echoed; anything else is redacted. Keeping the shape
182
+ * preserves the typo hint that makes the message useful.
183
+ */
184
+ // Deliberately narrower than "looks like a word": every real command and flag
185
+ // name in this CLI is short lowercase letters and hyphens, while credentials are
186
+ // long and almost always carry digits. An earlier version of this pattern
187
+ // allowed digits and 32 characters, and a test proved it happily echoed
188
+ // `sk-live-9f2c41aa8bd34e0197c6` verbatim.
189
+ const ARGV_NAME_PATTERN = /^[a-z][a-z-]{0,19}$/;
190
+ function describeArgvToken(raw) {
191
+ if (!raw.startsWith("-")) {
192
+ return ARGV_NAME_PATTERN.test(raw) ? raw : "<redacted>";
193
+ }
194
+ const dashes = raw.startsWith("--") ? "--" : "-";
195
+ const name = raw.replace(/^-+/, "").split("=")[0] ?? "";
196
+ return ARGV_NAME_PATTERN.test(name)
197
+ ? `${dashes}${name}`
198
+ : `${dashes}<redacted>`;
199
+ }
200
+ const ARTIFACT_NAME_MIN_LENGTH = 3;
201
+ const ARTIFACT_NAME_MAX_LENGTH = 63;
202
+ const ARTIFACT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
203
+ /**
204
+ * Local DNS-label validation, mirroring the rules the desktop app and the API
205
+ * already enforce (`apps/desktop/src/lib/publish-artifact-name.ts`). It runs
206
+ * before any network call so an invalid label costs nothing: the create-attempt
207
+ * budget is ten per day and is charged even on failure, so trial-and-error
208
+ * naming against the server can lock an account out of publishing for the day.
209
+ *
210
+ * The CLI cannot import the desktop module (separate package, separate release
211
+ * train), so these rules are duplicated deliberately and pinned by a test.
212
+ */
213
+ function validateArtifactName(raw) {
214
+ const label = raw.trim().toLowerCase();
215
+ if (label.length === 0)
216
+ return { ok: false, reason: "empty" };
217
+ if (label.length < ARTIFACT_NAME_MIN_LENGTH)
218
+ return { ok: false, reason: "too_short" };
219
+ if (label.length > ARTIFACT_NAME_MAX_LENGTH)
220
+ return { ok: false, reason: "too_long" };
221
+ if (label.includes("--"))
222
+ return { ok: false, reason: "consecutive_hyphens" };
223
+ if (!ARTIFACT_NAME_PATTERN.test(label))
224
+ return { ok: false, reason: "invalid_charset" };
225
+ return { ok: true, label };
148
226
  }
149
- class UsageError extends Error {
227
+ /**
228
+ * The whole naming model in one screen, because an agent that hits this has no
229
+ * other way to learn it: the rules, the permanence, the free way to check, and
230
+ * the fact that a permanent address exists either way.
231
+ */
232
+ const NAME_MISSING_MESSAGE = [
233
+ "Missing --name.",
234
+ "",
235
+ "HTML artifacts get their own subdomain, and the name is permanent — Foleo has",
236
+ "no rename. Choose it now, or changing the URL later means republishing under a",
237
+ "new id and the old link stops working.",
238
+ "",
239
+ " foleo name-check leadtube --json # free, no quota cost",
240
+ " foleo publish ./site --accept-hosting-risk --name leadtube --dry-run",
241
+ "",
242
+ `Rules: ${ARTIFACT_NAME_MIN_LENGTH}-${ARTIFACT_NAME_MAX_LENGTH} characters, a-z 0-9 and hyphens, no leading, trailing, or doubled hyphen.`,
243
+ "Every artifact also keeps a permanent a-<id>.foleo.site address for stable linking.",
244
+ ].join("\n");
245
+ /**
246
+ * Resolve the vanity name for a real (non-dry-run) HTML publish.
247
+ *
248
+ * Required only here. A Markdown publish keeps its derived, reversible slug and
249
+ * must never be asked for a name (spec 089 D4) — the requirement follows the
250
+ * inferred source format, never the command spelling.
251
+ */
252
+ function requireArtifactName(raw) {
253
+ if (raw === undefined) {
254
+ throw new UsageError(NAME_MISSING_MESSAGE, "name_missing");
255
+ }
256
+ const validated = validateArtifactName(raw);
257
+ if (!validated.ok) {
258
+ throw new UsageError(`Invalid --name "${raw}": ${validated.reason.replace(/_/g, " ")}. Rules: ${ARTIFACT_NAME_MIN_LENGTH}-${ARTIFACT_NAME_MAX_LENGTH} characters, a-z 0-9 and hyphens, no leading, trailing, or doubled hyphen.`, "name_invalid", { value: raw, reason: validated.reason });
259
+ }
260
+ return validated.label;
150
261
  }
151
262
  function warnDeprecatedAlias(deps, alias, canonical) {
152
263
  deps.stderr(`warning: \`foleo ${alias}\` is a deprecated alias; use \`foleo ${canonical}\`.\n`);
@@ -494,16 +605,150 @@ async function login(args, deps) {
494
605
  deps.stdout(`Signed in to ${loginResult.org}. Credential saved in macOS Keychain.\n`);
495
606
  return 0;
496
607
  }
608
+ /**
609
+ * `name-check <label>` — free availability probe.
610
+ *
611
+ * Consumes no product quota: it is a read against `GET /v1/subdomains/{label}`,
612
+ * separately fenced at 30/minute. A locally invalid label never reaches the
613
+ * network, so an agent cannot burn the read fence learning the character rules.
614
+ */
615
+ async function nameCheck(args, deps) {
616
+ const parsed = parseFlags(args);
617
+ const raw = parsed.positionals[0];
618
+ if (!raw || parsed.positionals.length !== 1)
619
+ throw new Error("Usage: foleo name-check <label> [--json]");
620
+ const validated = validateArtifactName(raw);
621
+ if (!validated.ok) {
622
+ const payload = {
623
+ label: raw.trim().toLowerCase(),
624
+ status: "invalid",
625
+ reason: validated.reason,
626
+ };
627
+ if (parsed.json)
628
+ deps.stdout(`${JSON.stringify(payload, null, 2)}\n`);
629
+ else
630
+ deps.stdout(`invalid ${payload.label} (${validated.reason.replace(/_/g, " ")})\n`);
631
+ return 1;
632
+ }
633
+ const result = await requestJson(deps, `/subdomains/${encodeURIComponent(validated.label)}`, { method: "GET", body: undefined });
634
+ const payload = { label: validated.label, status: result.status };
635
+ if (parsed.json)
636
+ deps.stdout(`${JSON.stringify(payload, null, 2)}\n`);
637
+ else
638
+ deps.stdout(`${payload.status} ${payload.label}\n`);
639
+ return payload.status === "available" ? 0 : 1;
640
+ }
641
+ /**
642
+ * `publish --dry-run` — plan without consuming product quota.
643
+ *
644
+ * Issues no `POST /v1/uploads`, no file PUT and no create. It scans the bundle
645
+ * locally, checks the name when one is in play, and reads `/v1/usage`. Exit 0
646
+ * means the local plan is valid; `executable` reports whether the server state
647
+ * currently admits it, because an unauthenticated or degraded plan must never
648
+ * read as permission to publish (spec 089 D2).
649
+ */
650
+ async function htmlPublishDryRun(root, name, parsed, deps) {
651
+ const files = await scanBundle(root, deps);
652
+ const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
653
+ const derived = name ?? deriveNameFromBundle(root);
654
+ let availability = "unknown";
655
+ let checkedAt = null;
656
+ let cost = null;
657
+ let executable = false;
658
+ try {
659
+ const result = await requestJson(deps, `/subdomains/${encodeURIComponent(derived)}`, { method: "GET", body: undefined });
660
+ availability = result.status;
661
+ checkedAt = new Date((deps.now ?? Date.now)()).toISOString();
662
+ cost = await requestJson(deps, "/usage", {
663
+ method: "GET",
664
+ body: undefined,
665
+ });
666
+ executable = availability === "available";
667
+ }
668
+ catch (error) {
669
+ // Only a missing credential may degrade to a bundle-only plan (D2). An
670
+ // expired key, a 500, or a throttle is a real failure: swallowing it into a
671
+ // benign exit-0 "unknown" plan is how an agent concludes a name is free and
672
+ // publishes over the top of something.
673
+ if (!(error instanceof FoleoError) || error.code !== "credential_missing") {
674
+ throw error;
675
+ }
676
+ availability = "unknown";
677
+ deps.stderr("Not signed in: this plan is bundle-only and cannot tell you whether the name is free. Run `foleo login` and plan again before publishing.\n");
678
+ }
679
+ const plan = {
680
+ ok: true,
681
+ plan: {
682
+ action: "create",
683
+ scope: cost === null ? "bundle-only" : "full",
684
+ executable,
685
+ name: {
686
+ requested: name ?? null,
687
+ resolved: derived,
688
+ resolvedFrom: name ? "flag" : "derived",
689
+ availability,
690
+ checkedAt,
691
+ },
692
+ bundle: {
693
+ fileCount: files.length,
694
+ htmlFileCount: htmlFiles.length,
695
+ totalBytes: files.reduce((n, file) => n + file.byteSize, 0),
696
+ entry: "/index.html",
697
+ notFoundPage: files.some((file) => file.path === "/404.html")
698
+ ? "/404.html"
699
+ : null,
700
+ },
701
+ cost,
702
+ },
703
+ };
704
+ if (parsed.json)
705
+ deps.stdout(`${JSON.stringify(plan, null, 2)}\n`);
706
+ else {
707
+ deps.stdout(`plan: create ${derived} (${availability})\n` +
708
+ `files: ${files.length} (${htmlFiles.length} html)\n` +
709
+ `executable: ${executable}\n`);
710
+ }
711
+ if (name === undefined) {
712
+ deps.stderr("No --name given; the label above is only a suggestion. Pass it explicitly to publish.\n");
713
+ }
714
+ // Exit 0 means local validation succeeded, not that the server admits it —
715
+ // `executable` is the signal. A name the server will refuse is a real failure.
716
+ return availability === "taken" || availability === "reserved" ? 1 : 0;
717
+ }
718
+ /** Suggestion only. Foleo never auto-claims a derived global name. */
719
+ function deriveNameFromBundle(root) {
720
+ const leaf = root.replace(/\/+$/, "").split(/[\\/]/).pop() ?? "site";
721
+ const sanitized = leaf
722
+ .trim()
723
+ .toLowerCase()
724
+ .replace(/[^a-z0-9]+/g, "-")
725
+ .replace(/^-+|-+$/g, "")
726
+ .slice(0, ARTIFACT_NAME_MAX_LENGTH)
727
+ .replace(/-+$/g, "");
728
+ return sanitized.length >= ARTIFACT_NAME_MIN_LENGTH ? sanitized : "site";
729
+ }
497
730
  async function htmlPublish(args, deps) {
731
+ resolveUploadRate(deps);
498
732
  const parsed = parseFlags(args);
499
733
  const root = parsed.positionals[0];
500
734
  if (!root || parsed.positionals.length !== 1 || !parsed.acceptHostingRisk)
501
- throw new Error("Usage: foleo html-publish <bundle-root> --accept-hosting-risk [--settings <json>] [--password-stdin] [--publish-separately] [--json]\nHosted HTML is executable and may run JavaScript, show forms, or initiate downloads. A human must inspect the source and explicitly approve this risk; an agent must not infer approval.");
735
+ throw new Error("Usage: foleo html-publish <bundle-root> --accept-hosting-risk --name <label> [--settings <json>] [--password-stdin] [--publish-separately] [--dry-run] [--json]\nHosted HTML is executable and may run JavaScript, show forms, or initiate downloads. A human must inspect the source and explicitly approve this risk; an agent must not infer approval.");
502
736
  const settings = { ...(parsed.settings ?? {}) };
737
+ // A dry run may omit --name to obtain a derived suggestion; a real create
738
+ // may not (spec 089 §B).
739
+ const name = parsed.dryRun
740
+ ? parsed.name === undefined
741
+ ? undefined
742
+ : requireArtifactName(parsed.name)
743
+ : requireArtifactName(parsed.name);
744
+ if (parsed.dryRun) {
745
+ return htmlPublishDryRun(root, name, parsed, deps);
746
+ }
747
+ settings.name = name;
503
748
  if (parsed.passwordStdin) {
504
749
  const password = stripTrailingNewline(await readStdinText(deps));
505
750
  if (password.length < 12 || password.length > 256) {
506
- throw new Error("Password must be 12–256 characters.");
751
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
507
752
  }
508
753
  settings.password = password;
509
754
  }
@@ -513,6 +758,7 @@ async function htmlPublish(args, deps) {
513
758
  return 0;
514
759
  }
515
760
  async function htmlUpdate(args, deps) {
761
+ resolveUploadRate(deps);
516
762
  const parsed = parseFlags(args);
517
763
  const [id, root] = parsed.positionals;
518
764
  const revision = legacyRevision(parsed.revision);
@@ -564,7 +810,7 @@ async function htmlPassword(args, deps) {
564
810
  }
565
811
  const password = stripTrailingNewline(await readStdinText(deps));
566
812
  if (password.length < 12 || password.length > 256) {
567
- throw new Error("Password must be 12–256 characters.");
813
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
568
814
  }
569
815
  announceApi(deps, parsed.json);
570
816
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/password`, {
@@ -585,7 +831,7 @@ async function settingsCommand(args, deps) {
585
831
  if (parsed.passwordStdin) {
586
832
  const password = stripTrailingNewline(await readStdinText(deps));
587
833
  if (password.length < 12 || password.length > 256) {
588
- throw new Error("Password must be 12–256 characters.");
834
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
589
835
  }
590
836
  patch.password = password;
591
837
  }
@@ -621,8 +867,11 @@ async function limitsCommand(args, deps) {
621
867
  method: "GET",
622
868
  });
623
869
  const service = await response.json().catch(() => null);
870
+ if (RETRYABLE_STATUSES.has(response.status)) {
871
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(service), service);
872
+ }
624
873
  if (!response.ok) {
625
- throw new Error(`Foleo API error: HTTP ${response.status} reading /v1/capabilities`);
874
+ throw new ApiRequestError(response.status, apiErrorCode(service, response.status), service);
626
875
  }
627
876
  const serviceVersion = service !== null &&
628
877
  typeof service === "object" &&
@@ -648,15 +897,15 @@ function parseSettingsSets(sets) {
648
897
  for (const entry of sets) {
649
898
  const separator = entry.indexOf("=");
650
899
  if (separator <= 0) {
651
- throw new Error(`Invalid --set ${entry}; expected key=value`);
900
+ throw new UsageError(`Invalid --set ${describeArgvToken(entry.split("=")[0] ?? entry)}; expected key=value`, "settings_set_invalid");
652
901
  }
653
902
  const key = entry.slice(0, separator);
654
903
  const raw = entry.slice(separator + 1);
655
904
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
656
- throw new Error(`Unknown settings field: ${key}`);
905
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
657
906
  }
658
907
  if (key === "password") {
659
- throw new Error("Passwords are not accepted as --set password=…. Use --password-stdin.");
908
+ throw new UsageError("Passwords are not accepted as --set password=…. Use --password-stdin.", "password_flag_unsupported");
660
909
  }
661
910
  patch[key] = coerceSettingsValue(raw);
662
911
  }
@@ -677,19 +926,19 @@ function parseSettingsJson(raw) {
677
926
  parsed = JSON.parse(raw);
678
927
  }
679
928
  catch {
680
- throw new Error("--settings requires a JSON object");
929
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
681
930
  }
682
931
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
683
- throw new Error("--settings requires a JSON object");
932
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
684
933
  }
685
934
  const settings = parsed;
686
935
  for (const key of Object.keys(settings)) {
687
936
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
688
- throw new Error(`Unknown settings field: ${key}`);
937
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
689
938
  }
690
939
  }
691
940
  if ("password" in settings) {
692
- throw new Error("Passwords are not accepted inside --settings. Use --password-stdin with foleo settings.");
941
+ throw new UsageError("Passwords are not accepted inside --settings. Use --password-stdin with foleo settings.", "password_flag_unsupported");
693
942
  }
694
943
  return settings;
695
944
  }
@@ -733,24 +982,32 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
733
982
  // counts the session create and complete calls against the same budget as the
734
983
  // file PUTs, so pacing only the PUTs overspends it.
735
984
  const pace = createHtmlUploadPacer(deps);
985
+ // One budget for the whole publish, and pacing inside each retry attempt: a
986
+ // retry is another request against the same fence, so pacing only the first
987
+ // attempt spends the budget it was meant to protect.
988
+ const budget = createRetryBudget();
736
989
  const uploadKey = randomUUID();
737
- await pace();
738
- const upload = await withRateLimitRetry(deps, "starting the upload", () => requestJson(deps, "/uploads", {
739
- method: "POST",
740
- body: {
741
- kind: "html-artifact-bundle",
742
- manifest,
743
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
744
- },
745
- headers: { "idempotency-key": uploadKey },
746
- }));
990
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
991
+ await pace();
992
+ return requestJson(deps, "/uploads", {
993
+ method: "POST",
994
+ body: {
995
+ kind: "html-artifact-bundle",
996
+ manifest,
997
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
998
+ },
999
+ headers: { "idempotency-key": uploadKey },
1000
+ });
1001
+ }, budget);
747
1002
  let uploaded = 0;
748
1003
  for (const plan of upload.files) {
749
1004
  const file = files.find((candidate) => candidate.path === plan.path);
750
1005
  if (!file)
751
- throw new Error("Server returned an unexpected upload file");
752
- await pace();
753
- await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
1006
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1007
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1008
+ await pace();
1009
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1010
+ }, budget);
754
1011
  uploaded += 1;
755
1012
  // A large bundle is paced to well under a minute's worth of requests, so a
756
1013
  // silent multi-minute publish reads as a hang. Progress goes to stderr so
@@ -760,55 +1017,67 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
760
1017
  }
761
1018
  }
762
1019
  const completeKey = randomUUID();
763
- await pace();
764
- await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
765
- method: "POST",
766
- body: {},
767
- headers: { "idempotency-key": completeKey },
768
- }));
1020
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1021
+ await pace();
1022
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1023
+ method: "POST",
1024
+ body: {},
1025
+ headers: { "idempotency-key": completeKey },
1026
+ });
1027
+ }, budget);
1028
+ if (update)
1029
+ await pace();
769
1030
  const sourceId = update
770
1031
  ? await ownerArtifactSourceId(deps, update.id)
771
1032
  : undefined;
772
1033
  const source = publishSourcePayload(upload.manifestHash, sourceId);
773
- if (update?.family === "compatibility") {
774
- return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
775
- method: "PUT",
776
- body: {
777
- uploadId: upload.uploadId,
778
- manifestHash: upload.manifestHash,
779
- source,
780
- },
781
- headers: {
782
- "if-match": `"r${update.revision}"`,
783
- "idempotency-key": randomUUID(),
784
- },
785
- });
786
- }
787
- if (update?.family === "generic") {
788
- return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
789
- method: "PUT",
1034
+ // The whole bundle is already uploaded by the time we get here, so losing this
1035
+ // one request to a throttle discards the entire publish — the exact failure
1036
+ // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1037
+ // so a retry reuses it and cannot double-create.
1038
+ const createKey = randomUUID();
1039
+ return withRateLimitRetry(deps, "creating the artifact", async () => {
1040
+ await pace();
1041
+ if (update?.family === "compatibility") {
1042
+ return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1043
+ method: "PUT",
1044
+ body: {
1045
+ uploadId: upload.uploadId,
1046
+ manifestHash: upload.manifestHash,
1047
+ source,
1048
+ },
1049
+ headers: {
1050
+ "if-match": `"r${update.revision}"`,
1051
+ "idempotency-key": createKey,
1052
+ },
1053
+ });
1054
+ }
1055
+ if (update?.family === "generic") {
1056
+ return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1057
+ method: "PUT",
1058
+ body: {
1059
+ sourceFormat: "html",
1060
+ uploadId: upload.uploadId,
1061
+ manifestHash: upload.manifestHash,
1062
+ source,
1063
+ },
1064
+ headers: artifactMutationHeaders(update.etag, createKey),
1065
+ });
1066
+ }
1067
+ return requestJson(deps, "/artifacts", {
1068
+ method: "POST",
790
1069
  body: {
791
1070
  sourceFormat: "html",
792
1071
  uploadId: upload.uploadId,
793
1072
  manifestHash: upload.manifestHash,
1073
+ hostingRiskAcknowledged,
794
1074
  source,
1075
+ ...(publishSeparately ? { allowDuplicate: true } : {}),
1076
+ ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
795
1077
  },
796
- headers: artifactMutationHeaders(update.etag, randomUUID()),
1078
+ headers: { "idempotency-key": createKey },
797
1079
  });
798
- }
799
- return requestJson(deps, "/artifacts", {
800
- method: "POST",
801
- body: {
802
- sourceFormat: "html",
803
- uploadId: upload.uploadId,
804
- manifestHash: upload.manifestHash,
805
- hostingRiskAcknowledged,
806
- source,
807
- ...(publishSeparately ? { allowDuplicate: true } : {}),
808
- ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
809
- },
810
- headers: { "idempotency-key": randomUUID() },
811
- });
1080
+ }, budget);
812
1081
  }
813
1082
  function revisionHeaders(revision) {
814
1083
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -859,6 +1128,7 @@ function artifactMutationHeaders(revision, idempotencyKey) {
859
1128
  * budget.
860
1129
  */
861
1130
  function createHtmlUploadPacer(deps) {
1131
+ const limit = resolveUploadRate(deps);
862
1132
  const now = deps.now ?? Date.now;
863
1133
  const sleep = deps.sleep ??
864
1134
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
@@ -869,7 +1139,7 @@ function createHtmlUploadPacer(deps) {
869
1139
  const cutoff = now() - HTML_UPLOAD_FILE_WINDOW_MS;
870
1140
  while (recent.length > 0 && recent[0] <= cutoff)
871
1141
  recent.shift();
872
- if (recent.length < HTML_UPLOAD_FILE_PUTS_PER_WINDOW)
1142
+ if (recent.length < limit)
873
1143
  break;
874
1144
  // Wait for the oldest request to age out of the window, plus a little
875
1145
  // jitter so retries from separate processes do not re-align.
@@ -879,6 +1149,35 @@ function createHtmlUploadPacer(deps) {
879
1149
  recent.push(now());
880
1150
  };
881
1151
  }
1152
+ const HTML_UPLOAD_RATE_MIN = 1;
1153
+ const HTML_UPLOAD_RATE_MAX = 60;
1154
+ /**
1155
+ * `FOLEO_UPLOAD_RATE` caps the total `/v1/*` requests this process places in one
1156
+ * rolling 10-second window — total requests, not files per second, because the
1157
+ * fence counts session create/complete calls too. It exists so a user throttled
1158
+ * by an intermediary can slow down without waiting for a release.
1159
+ *
1160
+ * The default stays at the shipped 7 rather than spec 089's originally-drafted
1161
+ * 5: `5404a47` simulated the window and chose 7 against a fence of 10, and that
1162
+ * simulation postdates the draft. Lowering it would cost every publish time to
1163
+ * fix a cause the retraction in §F already disproved.
1164
+ */
1165
+ function resolveUploadRate(deps) {
1166
+ const raw = deps.env.FOLEO_UPLOAD_RATE;
1167
+ if (raw === undefined || raw.trim() === "")
1168
+ return HTML_UPLOAD_FILE_PUTS_PER_WINDOW;
1169
+ const value = Number(raw.trim());
1170
+ if (!Number.isInteger(value) ||
1171
+ value < HTML_UPLOAD_RATE_MIN ||
1172
+ value > HTML_UPLOAD_RATE_MAX) {
1173
+ throw new UsageError(`FOLEO_UPLOAD_RATE must be a whole number from ${HTML_UPLOAD_RATE_MIN} to ${HTML_UPLOAD_RATE_MAX}; received ${raw}.`, "invalid_upload_rate", {
1174
+ value: raw,
1175
+ minimum: HTML_UPLOAD_RATE_MIN,
1176
+ maximum: HTML_UPLOAD_RATE_MAX,
1177
+ });
1178
+ }
1179
+ return value;
1180
+ }
882
1181
  /**
883
1182
  * Retry a request that the edge or API refused for rate-limiting reasons.
884
1183
  *
@@ -898,39 +1197,118 @@ function createHtmlUploadPacer(deps) {
898
1197
  */
899
1198
  const RETRYABLE_STATUSES = new Set([429, 503]);
900
1199
  const MAX_RATE_LIMIT_RETRIES = 6;
901
- async function withRateLimitRetry(deps, describe, attempt) {
1200
+ /**
1201
+ * Total wall-clock this CLI will sleep inside one operation before handing the
1202
+ * decision back to the caller. Without it, `Retry-After` was honoured verbatim
1203
+ * and unbounded: a quota rejection advertising ~24h parked the process for a
1204
+ * day per attempt, six attempts deep, which reads to an agent as a hang.
1205
+ */
1206
+ const RATE_LIMIT_TOTAL_BUDGET_MS = 120_000;
1207
+ /**
1208
+ * One sleep budget for a whole publish, not for each request inside it.
1209
+ *
1210
+ * Scoping it per call looked bounded and was not: a 119-file bundle makes one
1211
+ * retry call per file, each starting from zero, so the "120s budget" was really
1212
+ * 120s x 121 requests — hours of sleeping presented to the caller as a bound.
1213
+ */
1214
+ function createRetryBudget() {
1215
+ let slept = 0;
1216
+ return {
1217
+ remaining: () => RATE_LIMIT_TOTAL_BUDGET_MS - slept,
1218
+ spend: (ms) => {
1219
+ slept += ms;
1220
+ },
1221
+ };
1222
+ }
1223
+ async function withRateLimitRetry(deps, describe, attempt, budget = createRetryBudget()) {
902
1224
  const sleep = deps.sleep ??
903
1225
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
904
1226
  for (let retry = 0;; retry++) {
905
1227
  try {
906
- return await attempt();
1228
+ return await attempt(retry);
907
1229
  }
908
1230
  catch (error) {
909
1231
  if (!(error instanceof RateLimitedError) ||
910
1232
  !RETRYABLE_STATUSES.has(error.status)) {
911
1233
  throw error;
912
1234
  }
913
- if (retry >= MAX_RATE_LIMIT_RETRIES) {
914
- throw new Error(`${describe} was rate limited ${retry + 1} times; giving up. Try again shortly.`);
915
- }
1235
+ // A spent quota window is not a transient burst: waiting cannot help
1236
+ // inside any budget a foreground command may spend, so surface it.
1237
+ if (!error.retryable)
1238
+ throw error;
1239
+ if (retry >= MAX_RATE_LIMIT_RETRIES)
1240
+ throw error;
916
1241
  const backoff = Math.min(30_000, 1_000 * 2 ** retry);
917
1242
  const wait = (error.retryAfterMs ?? backoff) +
918
1243
  Math.floor((deps.random ?? Math.random)() * 500);
1244
+ if (wait > budget.remaining())
1245
+ throw error;
1246
+ budget.spend(wait);
919
1247
  deps.stderr(`Rate limited on ${describe}; retrying in ${Math.ceil(wait / 1000)}s (attempt ${retry + 2}).\n`);
920
1248
  await sleep(wait);
921
1249
  }
922
1250
  }
923
1251
  }
924
- class RateLimitedError extends Error {
1252
+ /**
1253
+ * The three actionable 429 classes of spec 089 §E.
1254
+ *
1255
+ * The API answers a spent *quota* window and a *burst* rejection with the same
1256
+ * `rate_limited` code today — `reserveHtmlQuota` returns
1257
+ * `apiError(429, "rate_limited")` with `retry-after` set to the window end,
1258
+ * which for a daily create-attempt budget is hours away. So the advertised
1259
+ * delay, not the code, is what separates them: anything the retry budget cannot
1260
+ * absorb is a quota window by definition. A response with no Foleo envelope at
1261
+ * all came from an intermediary rather than the Worker, and is reported as
1262
+ * `upstream_rate_limited` without asserting which one.
1263
+ */
1264
+ class RateLimitedError extends FoleoError {
925
1265
  status;
926
1266
  retryAfterMs;
927
- constructor(status, retryAfterMs) {
928
- super(`Foleo API error: HTTP ${status}`);
1267
+ constructor(status, retryAfterMs, apiCode, body) {
1268
+ // The delay heuristic applies ONLY to a 429 carrying a Foleo envelope. A 503
1269
+ // is `quota_initializing` in this API — the quota system warming up, which is
1270
+ // transient and retryable — so reading a long delay there as an exhausted
1271
+ // budget would both mislabel it and suppress a retry that should happen.
1272
+ const exhausted = status === 429 &&
1273
+ apiCode !== null &&
1274
+ (apiCode === "quota_attempts_exhausted" ||
1275
+ (retryAfterMs !== null && retryAfterMs > RATE_LIMIT_TOTAL_BUDGET_MS));
1276
+ const code = exhausted
1277
+ ? "quota_attempts_exhausted"
1278
+ : apiCode !== null
1279
+ ? apiCode
1280
+ : status === 429
1281
+ ? "upstream_rate_limited"
1282
+ : "service_unavailable";
1283
+ const seconds = retryAfterMs === null ? null : Math.ceil(retryAfterMs / 1_000);
1284
+ super({
1285
+ code,
1286
+ message: exhausted
1287
+ ? "Foleo publishing quota is exhausted for this window."
1288
+ : status === 429
1289
+ ? "Too many requests to the Foleo API."
1290
+ : "The Foleo API is temporarily unavailable.",
1291
+ next: exhausted
1292
+ ? `Do not retry automatically${seconds === null ? "" : `; the window reopens in about ${describeDelay(seconds)}`}. Publish again after it reopens, or ask the account owner to raise the limit.`
1293
+ : `Wait ${seconds ?? 10} seconds and run the same command again.`,
1294
+ retryable: !exhausted,
1295
+ retryAfterSeconds: seconds,
1296
+ httpStatus: status,
1297
+ source: apiCode === null ? "upstream" : "api",
1298
+ ...(body === undefined ? {} : { context: { apiCode } }),
1299
+ });
1300
+ this.name = "RateLimitedError";
929
1301
  this.status = status;
930
1302
  this.retryAfterMs = retryAfterMs;
931
- this.name = "RateLimitedError";
932
1303
  }
933
1304
  }
1305
+ function describeDelay(seconds) {
1306
+ if (seconds < 90)
1307
+ return `${seconds} seconds`;
1308
+ if (seconds < 5_400)
1309
+ return `${Math.round(seconds / 60)} minutes`;
1310
+ return `${Math.round(seconds / 3_600)} hours`;
1311
+ }
934
1312
  /** `Retry-After` is seconds or an HTTP-date; both are valid per RFC 9110. */
935
1313
  function retryAfterMs(header, now) {
936
1314
  if (header === null)
@@ -977,14 +1355,40 @@ export async function scanBundle(root, deps) {
977
1355
  pathSegments.length > HTML_BUNDLE_MAX_PATH_SEGMENTS ||
978
1356
  pathSegments.some((segment) => new TextEncoder().encode(segment).byteLength >
979
1357
  HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
980
- throw new Error(`Invalid bundle path: ${path}`);
1358
+ throw new LocalError("bundle_path_invalid", `Invalid bundle path: ${path}`, {
1359
+ context: {
1360
+ path,
1361
+ limitPathBytes: HTML_BUNDLE_MAX_PATH_BYTES,
1362
+ limitSegments: HTML_BUNDLE_MAX_PATH_SEGMENTS,
1363
+ limitSegmentBytes: HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES,
1364
+ },
1365
+ });
981
1366
  if (!info.isFile())
982
- throw new Error(`Unsupported bundle file: ${path}`);
983
- if (info.size > HTML_BUNDLE_MAX_FILE_BYTES ||
984
- totalBytes + info.size > HTML_BUNDLE_MAX_BYTES)
985
- throw new Error("Bundle exceeds Foleo limits");
1367
+ throw new LocalError("bundle_file_not_regular", `Unsupported bundle file: ${path}`, { context: { path } });
1368
+ if (info.size > HTML_BUNDLE_MAX_FILE_BYTES)
1369
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, {
1370
+ context: {
1371
+ path,
1372
+ bytes: info.size,
1373
+ limitBytes: HTML_BUNDLE_MAX_FILE_BYTES,
1374
+ },
1375
+ });
1376
+ if (totalBytes + info.size > HTML_BUNDLE_MAX_BYTES)
1377
+ throw new LocalError("bundle_total_too_large", "Bundle exceeds the total size limit.", {
1378
+ context: {
1379
+ path,
1380
+ bytes: totalBytes + info.size,
1381
+ limitBytes: HTML_BUNDLE_MAX_BYTES,
1382
+ },
1383
+ });
986
1384
  if (fileCount + 1 > HTML_BUNDLE_MAX_FILES)
987
- throw new Error("Bundle exceeds Foleo limits");
1385
+ throw new LocalError("bundle_too_many_files", "Bundle exceeds the file-count limit.", {
1386
+ context: {
1387
+ path,
1388
+ fileCount: fileCount + 1,
1389
+ limitFiles: HTML_BUNDLE_MAX_FILES,
1390
+ },
1391
+ });
988
1392
  const mediaType = mediaTypeFor(path);
989
1393
  // Collect every unsupported path and report them together after the walk.
990
1394
  // Failing on the first one turned a Next/Astro export with three stray file
@@ -995,12 +1399,34 @@ export async function scanBundle(root, deps) {
995
1399
  continue;
996
1400
  }
997
1401
  const bytes = await bytesFor(absolute);
998
- if (mediaType === "text/html; charset=utf-8" &&
999
- (bytes.byteLength > HTML_BUNDLE_MAX_HTML_BYTES || !isValidUtf8(bytes)))
1000
- throw new Error(`Invalid HTML document: ${path}`);
1001
- if (bytes.byteLength > HTML_BUNDLE_MAX_FILE_BYTES ||
1002
- totalBytes + bytes.byteLength > HTML_BUNDLE_MAX_BYTES)
1003
- throw new Error("Bundle exceeds Foleo limits");
1402
+ if (mediaType === "text/html; charset=utf-8") {
1403
+ if (bytes.byteLength > HTML_BUNDLE_MAX_HTML_BYTES)
1404
+ throw new LocalError("bundle_html_too_large", `HTML document exceeds the per-document limit: ${path}`, {
1405
+ context: {
1406
+ path,
1407
+ bytes: bytes.byteLength,
1408
+ limitBytes: HTML_BUNDLE_MAX_HTML_BYTES,
1409
+ },
1410
+ });
1411
+ if (!isValidUtf8(bytes))
1412
+ throw new LocalError("bundle_html_invalid_utf8", `HTML document is not valid UTF-8: ${path}`, { context: { path } });
1413
+ }
1414
+ if (bytes.byteLength > HTML_BUNDLE_MAX_FILE_BYTES)
1415
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, {
1416
+ context: {
1417
+ path,
1418
+ bytes: bytes.byteLength,
1419
+ limitBytes: HTML_BUNDLE_MAX_FILE_BYTES,
1420
+ },
1421
+ });
1422
+ if (totalBytes + bytes.byteLength > HTML_BUNDLE_MAX_BYTES)
1423
+ throw new LocalError("bundle_total_too_large", "Bundle exceeds the total size limit.", {
1424
+ context: {
1425
+ path,
1426
+ bytes: totalBytes + bytes.byteLength,
1427
+ limitBytes: HTML_BUNDLE_MAX_BYTES,
1428
+ },
1429
+ });
1004
1430
  fileCount += 1;
1005
1431
  totalBytes += bytes.byteLength;
1006
1432
  files.push({
@@ -1016,13 +1442,20 @@ export async function scanBundle(root, deps) {
1016
1442
  if (unsupported.length > 0) {
1017
1443
  const shown = unsupported.slice(0, 10).join(", ");
1018
1444
  const rest = unsupported.length > 10 ? ` (+${unsupported.length - 10} more)` : "";
1019
- throw new Error(`Unsupported bundle file${unsupported.length > 1 ? "s" : ""}: ${shown}${rest}`);
1445
+ throw new LocalError("bundle_unsupported_media_type", `Unsupported bundle file${unsupported.length > 1 ? "s" : ""}: ${shown}${rest}`, {
1446
+ context: { paths: unsupported.slice(0, 10), count: unsupported.length },
1447
+ });
1020
1448
  }
1021
1449
  if (!files.some((file) => file.path === "/index.html"))
1022
- throw new Error("Bundle root must contain index.html");
1450
+ throw new LocalError("bundle_missing_entry", "Bundle root must contain index.html", { context: { expected: "/index.html" } });
1023
1451
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
1024
1452
  if (htmlFiles.length > HTML_BUNDLE_MAX_HTML_FILES)
1025
- throw new Error("Bundle exceeds Foleo limits");
1453
+ throw new LocalError("bundle_too_many_html_files", "Bundle exceeds the HTML-document count limit.", {
1454
+ context: {
1455
+ htmlFileCount: htmlFiles.length,
1456
+ limitHtmlFiles: HTML_BUNDLE_MAX_HTML_FILES,
1457
+ },
1458
+ });
1026
1459
  const routes = new Set();
1027
1460
  for (const file of htmlFiles) {
1028
1461
  const route = file.path === "/index.html"
@@ -1031,7 +1464,7 @@ export async function scanBundle(root, deps) {
1031
1464
  ? `${file.path.slice(0, -"/index.html".length)}/`
1032
1465
  : file.path.replace(/\.html?$/i, "");
1033
1466
  if (routes.has(route))
1034
- throw new Error(`Ambiguous HTML route: ${route}`);
1467
+ throw new LocalError("bundle_ambiguous_route", `Ambiguous HTML route: ${route}`, { context: { route, path: file.path } });
1035
1468
  routes.add(route);
1036
1469
  }
1037
1470
  return files.sort((a, b) => a.path.localeCompare(b.path));
@@ -1090,11 +1523,11 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1090
1523
  try {
1091
1524
  const stat = await file.stat();
1092
1525
  if (!stat.isFile())
1093
- throw new Error("Bundle path is not a regular file");
1526
+ throw new LocalError("bundle_file_not_regular", "Bundle path is not a regular file", { context: { path } });
1094
1527
  if (stat.nlink > 1)
1095
- throw new Error("Bundle path has multiple hard links");
1528
+ throw new LocalError("bundle_file_hard_linked", "Bundle path has multiple hard links", { context: { path } });
1096
1529
  if (stat.size > maxBytes)
1097
- throw new Error("Bundle exceeds Foleo limits");
1530
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, { context: { path, bytes: stat.size, limitBytes: maxBytes } });
1098
1531
  const resolved = await realpath(path);
1099
1532
  if (resolved !== realBase && !resolved.startsWith(`${realBase}${sep}`))
1100
1533
  throw new Error("Bundle path escaped root");
@@ -1108,7 +1541,7 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1108
1541
  break;
1109
1542
  total += bytesRead;
1110
1543
  if (total > maxBytes)
1111
- throw new Error("Bundle exceeds Foleo limits");
1544
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, { context: { path, limitBytes: maxBytes } });
1112
1545
  chunks.push(new Uint8Array(buffer.subarray(0, bytesRead)));
1113
1546
  }
1114
1547
  }
@@ -1124,19 +1557,23 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1124
1557
  return result;
1125
1558
  }
1126
1559
  async function publish(args, deps) {
1560
+ resolveUploadRate(deps);
1127
1561
  const parsed = parseFlags(args);
1128
1562
  const file = parsed.positionals[0];
1129
1563
  if (!file || parsed.positionals.length !== 1)
1130
- throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--json]");
1564
+ throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
1131
1565
  const isDirectory = await pathIsDirectory(file, deps);
1566
+ if (!isDirectory && parsed.dryRun) {
1567
+ throw new UsageError("--dry-run is only implemented for HTML site bundles (a directory with --accept-hosting-risk). A Markdown publish is not previewable yet; run it without --dry-run, or use `foleo publish <dir> --accept-hosting-risk --name <label> --dry-run`.", "dry_run_unsupported", { sourceFormat: "markdown" });
1568
+ }
1132
1569
  if (isDirectory) {
1133
1570
  if (!parsed.acceptHostingRisk) {
1134
- throw new Error("foleo publish <path> --accept-hosting-risk is required for an HTML site bundle. The deprecated alias is: foleo html-publish <bundle-root> --accept-hosting-risk");
1571
+ throw new UsageError("foleo publish <path> --accept-hosting-risk is required for an HTML site bundle. The deprecated alias is: foleo html-publish <bundle-root> --accept-hosting-risk", "hosting_risk_unacknowledged");
1135
1572
  }
1136
1573
  return htmlPublish(args, deps);
1137
1574
  }
1138
1575
  if (!file.toLowerCase().endsWith(".md")) {
1139
- throw new Error("Unsupported publish input. Use a .md file for Markdown or an HTML site directory with --accept-hosting-risk.");
1576
+ throw new LocalError("publish_input_unsupported", "Unsupported publish input. Use a .md file for Markdown or an HTML site directory with --accept-hosting-risk.", { context: { path: file } });
1140
1577
  }
1141
1578
  const markdown = await deps.readFile(file, "utf8");
1142
1579
  const assets = await uploadMarkdownAssets(file, markdown, deps);
@@ -1160,7 +1597,13 @@ async function publish(args, deps) {
1160
1597
  return 0;
1161
1598
  }
1162
1599
  async function update(args, deps) {
1600
+ resolveUploadRate(deps);
1163
1601
  const parsed = parseFlags(args);
1602
+ // Asking for a plan must never mutate. Until an update plan exists, refuse
1603
+ // the flag rather than silently performing the real update.
1604
+ if (parsed.dryRun) {
1605
+ throw new UsageError("--dry-run is not implemented for update. Run the update without it.", "dry_run_unsupported", { operation: "update" });
1606
+ }
1164
1607
  const [id, file] = parsed.positionals;
1165
1608
  if (!id || !file || parsed.positionals.length !== 2) {
1166
1609
  throw new Error("Usage: foleo update <id> <path> --revision <etag> [--json] (or Markdown compatibility --version <version>)");
@@ -1187,7 +1630,7 @@ async function update(args, deps) {
1187
1630
  }
1188
1631
  const opaqueRevision = parsed.revision === undefined ? null : artifactRevision(parsed.revision);
1189
1632
  if (parsed.revision !== undefined && opaqueRevision === null) {
1190
- throw new Error("--revision requires an opaque Artifact ETag");
1633
+ throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
1191
1634
  }
1192
1635
  const markdown = await deps.readFile(file, "utf8");
1193
1636
  const assets = await uploadMarkdownAssets(file, markdown, deps);
@@ -1275,13 +1718,29 @@ export async function scanMarkdownAssets(markdownPath, markdown, deps) {
1275
1718
  throw error;
1276
1719
  }
1277
1720
  if (bytes.byteLength > LIVE_DOC_ASSET_MAX_FILE_BYTES) {
1278
- throw new Error("Live-doc assets exceed Foleo limits");
1721
+ throw new LocalError("asset_file_too_large", `Linked asset exceeds the per-file limit: ${logical}`, {
1722
+ context: {
1723
+ path: logical,
1724
+ bytes: bytes.byteLength,
1725
+ limitBytes: LIVE_DOC_ASSET_MAX_FILE_BYTES,
1726
+ },
1727
+ });
1279
1728
  }
1280
1729
  if (files.length + 1 > LIVE_DOC_ASSET_MAX_FILES) {
1281
- throw new Error("Live-doc assets exceed Foleo limits");
1730
+ throw new LocalError("asset_too_many_files", "Linked assets exceed the file-count limit.", {
1731
+ context: {
1732
+ fileCount: files.length + 1,
1733
+ limitFiles: LIVE_DOC_ASSET_MAX_FILES,
1734
+ },
1735
+ });
1282
1736
  }
1283
1737
  if (totalBytes + bytes.byteLength > LIVE_DOC_ASSET_MAX_BYTES) {
1284
- throw new Error("Live-doc assets exceed Foleo limits");
1738
+ throw new LocalError("asset_total_too_large", "Linked assets exceed the total size limit.", {
1739
+ context: {
1740
+ bytes: totalBytes + bytes.byteLength,
1741
+ limitBytes: LIVE_DOC_ASSET_MAX_BYTES,
1742
+ },
1743
+ });
1285
1744
  }
1286
1745
  seen.add(logical);
1287
1746
  totalBytes += bytes.byteLength;
@@ -1348,32 +1807,43 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
1348
1807
  if (files.length === 0)
1349
1808
  return null;
1350
1809
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
1351
- const upload = await requestJson(deps, "/uploads", {
1352
- method: "POST",
1353
- body: {
1354
- kind: "live-doc-assets",
1355
- manifest,
1356
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1357
- },
1358
- headers: { "idempotency-key": randomUUID() },
1359
- });
1360
1810
  // Same pacing and retry contract as the HTML bundle path: this loop hits the
1361
- // same /v1/ fence and previously discarded the whole upload on one 429.
1811
+ // same /v1/ fence and previously discarded the whole upload on one 429. The
1812
+ // pacer and budget are built before the first request, because the session
1813
+ // create counts against the same fence as the PUTs that follow it.
1362
1814
  const pace = createHtmlUploadPacer(deps);
1815
+ const budget = createRetryBudget();
1816
+ const uploadKey = randomUUID();
1817
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1818
+ await pace();
1819
+ return requestJson(deps, "/uploads", {
1820
+ method: "POST",
1821
+ body: {
1822
+ kind: "live-doc-assets",
1823
+ manifest,
1824
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1825
+ },
1826
+ headers: { "idempotency-key": uploadKey },
1827
+ });
1828
+ }, budget);
1363
1829
  for (const plan of upload.files) {
1364
1830
  const file = files.find((candidate) => candidate.path === plan.path);
1365
1831
  if (!file)
1366
- throw new Error("Server returned an unexpected upload file");
1367
- await pace();
1368
- await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
1832
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1833
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1834
+ await pace();
1835
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1836
+ }, budget);
1369
1837
  }
1370
1838
  const completeKey = randomUUID();
1371
- await pace();
1372
- await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1373
- method: "POST",
1374
- body: {},
1375
- headers: { "idempotency-key": completeKey },
1376
- }));
1839
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1840
+ await pace();
1841
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1842
+ method: "POST",
1843
+ body: {},
1844
+ headers: { "idempotency-key": completeKey },
1845
+ });
1846
+ }, budget);
1377
1847
  return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
1378
1848
  }
1379
1849
  async function unpublish(args, deps) {
@@ -1504,7 +1974,9 @@ async function list(args, deps) {
1504
1974
  }
1505
1975
  const credential = await resolveCredentialWithSource(deps);
1506
1976
  if (!credential)
1507
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
1977
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
1978
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
1979
+ });
1508
1980
  const query = new URLSearchParams();
1509
1981
  if (kind && legacyFormat === null)
1510
1982
  query.set("kind", kind);
@@ -1540,7 +2012,9 @@ async function whoami(args, deps) {
1540
2012
  throw new Error("Usage: foleo whoami [--json]");
1541
2013
  const credential = await resolveCredentialWithSource(deps);
1542
2014
  if (!credential)
1543
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
2015
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
2016
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
2017
+ });
1544
2018
  const result = await requestJsonWithToken(deps, "/me", credential.token, {
1545
2019
  method: "GET",
1546
2020
  body: undefined,
@@ -1566,7 +2040,9 @@ function environmentCommand(args, deps) {
1566
2040
  async function requestJson(deps, path, init) {
1567
2041
  const credential = await resolveCredentialWithSource(deps);
1568
2042
  if (!credential)
1569
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
2043
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
2044
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
2045
+ });
1570
2046
  return requestJsonWithToken(deps, path, credential.token, init);
1571
2047
  }
1572
2048
  async function requestJsonWithToken(deps, path, token, init) {
@@ -1586,36 +2062,51 @@ async function requestJsonWithToken(deps, path, token, init) {
1586
2062
  if (RETRYABLE_STATUSES.has(response.status)) {
1587
2063
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
1588
2064
  // zone fence in front of this API answers with a Cloudflare error page rather
1589
- // than the API's JSON envelope, so the status is the only reliable signal.
1590
- throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
2065
+ // than the API's JSON envelope, so an absent envelope is itself the signal
2066
+ // that some intermediary, not the Worker, produced this.
2067
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(body), body);
1591
2068
  }
1592
2069
  if (!response.ok) {
1593
- const code = body !== null &&
1594
- typeof body === "object" &&
1595
- "error" in body &&
1596
- typeof body.error === "object" &&
1597
- body.error !== null &&
1598
- "code" in body.error
1599
- ? String(body.error.code)
1600
- : `HTTP ${response.status}`;
1601
- throw new ApiRequestError(response.status, code, body);
2070
+ throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
1602
2071
  }
1603
2072
  return body;
1604
2073
  }
1605
- class ApiRequestError extends Error {
2074
+ class ApiRequestError extends FoleoError {
1606
2075
  status;
1607
- code;
1608
2076
  body;
1609
2077
  constructor(status, code, body) {
1610
- super(code === "matching_source_exists"
1611
- ? matchingSourceExistsMessage(body)
1612
- : `Foleo API error: ${code}`);
2078
+ const next = apiErrorNext(body);
2079
+ super({
2080
+ code,
2081
+ message: code === "matching_source_exists"
2082
+ ? matchingSourceExistsMessage(body)
2083
+ : `Foleo API error: ${code}`,
2084
+ httpStatus: status,
2085
+ source: "api",
2086
+ ...(next === null ? {} : { next }),
2087
+ });
2088
+ this.name = "ApiRequestError";
1613
2089
  this.status = status;
1614
- this.code = code;
1615
2090
  this.body = body;
1616
- this.name = "ApiRequestError";
1617
2091
  }
1618
2092
  }
2093
+ /**
2094
+ * `code` from an API envelope, falling back to a status-derived code. Never
2095
+ * emit a bare `HTTP {n}` when a body could have said more (§E rule 7): the
2096
+ * fallback is still a stable snake_case code, not a sentence.
2097
+ */
2098
+ function apiErrorCode(body, status) {
2099
+ return apiEnvelopeCode(body) ?? `http_${status}`;
2100
+ }
2101
+ /** `null` means the response carried no Foleo error envelope at all. */
2102
+ function apiEnvelopeCode(body) {
2103
+ const envelope = isRecord(body) && isRecord(body.error) ? body.error : null;
2104
+ return envelope && typeof envelope.code === "string" ? envelope.code : null;
2105
+ }
2106
+ function apiErrorNext(body) {
2107
+ const envelope = isRecord(body) && isRecord(body.error) ? body.error : null;
2108
+ return envelope && typeof envelope.next === "string" ? envelope.next : null;
2109
+ }
1619
2110
  function matchingSourceExistsMessage(body) {
1620
2111
  const errorBody = isRecord(body) && isRecord(body.error) ? body.error : null;
1621
2112
  const matches = errorBody && Array.isArray(errorBody.matches)
@@ -1640,36 +2131,54 @@ async function requestPublicJson(deps, path, body) {
1640
2131
  body: JSON.stringify(body),
1641
2132
  });
1642
2133
  const parsed = await response.json().catch(() => null);
2134
+ if (RETRYABLE_STATUSES.has(response.status)) {
2135
+ // login and other unauthenticated calls previously dropped `retry-after`
2136
+ // and reported every throttle as a flat, non-retryable API error.
2137
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(parsed), parsed);
2138
+ }
1643
2139
  if (!response.ok)
1644
2140
  throw apiResponseError(response.status, parsed);
1645
2141
  return parsed;
1646
2142
  }
1647
- async function requestRaw(deps, path, body, headers) {
2143
+ async function requestRaw(deps, path, body, headers,
2144
+ /**
2145
+ * Only a *retry* may treat a replay as success. On a first attempt this
2146
+ * process has not yet sent these bytes, so `upload_file_replayed` means
2147
+ * something else consumed the token and must surface as the conflict it is.
2148
+ */
2149
+ allowReplay = false) {
1648
2150
  const credential = await resolveCredentialWithSource(deps);
1649
2151
  if (!credential)
1650
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
2152
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
2153
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
2154
+ });
1651
2155
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
1652
2156
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
1653
2157
  method: "PUT",
1654
2158
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
1655
2159
  body: bytes,
1656
2160
  });
1657
- if (RETRYABLE_STATUSES.has(response.status)) {
1658
- throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
2161
+ if (!response.ok) {
2162
+ // The raw PUT path never parsed a response body, so every failure here was
2163
+ // reported as a bare `HTTP {n}` — the exact string the audited incident
2164
+ // gave the agent instead of a reason (§E rule 7).
2165
+ const body = await response.json().catch(() => null);
2166
+ if (RETRYABLE_STATUSES.has(response.status)) {
2167
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(body), body);
2168
+ }
2169
+ // A replay of *this* upload token, path, and content hash means the server
2170
+ // already holds the bytes we are trying to send. After a retried transport
2171
+ // failure that is confirmation of the earlier success, not a conflict.
2172
+ if (allowReplay &&
2173
+ response.status === 409 &&
2174
+ apiEnvelopeCode(body) === "upload_file_replayed") {
2175
+ return;
2176
+ }
2177
+ throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
1659
2178
  }
1660
- if (!response.ok)
1661
- throw new Error(`Foleo API error: HTTP ${response.status}`);
1662
2179
  }
1663
2180
  function apiResponseError(status, body) {
1664
- const code = body !== null &&
1665
- typeof body === "object" &&
1666
- "error" in body &&
1667
- typeof body.error === "object" &&
1668
- body.error !== null &&
1669
- "code" in body.error
1670
- ? String(body.error.code)
1671
- : `HTTP ${status}`;
1672
- return new Error(`Foleo API error: ${code}`);
2181
+ return new ApiRequestError(status, apiErrorCode(body, status), body);
1673
2182
  }
1674
2183
  function apiBase(deps) {
1675
2184
  const selected = deps.env.FOLEO_ENV ?? "production";
@@ -1882,8 +2391,15 @@ async function ownerArtifactSourceId(deps, id) {
1882
2391
  ? source.id
1883
2392
  : undefined;
1884
2393
  }
1885
- catch {
2394
+ catch (error) {
1886
2395
  // Old servers or a missing catalog field: still send the hash without an id.
2396
+ // A throttle or an auth failure is NOT that case — swallowing those sent an
2397
+ // update with no source id and hid the failed request behind a success.
2398
+ if (error instanceof RateLimitedError ||
2399
+ (error instanceof ApiRequestError &&
2400
+ (error.status === 401 || error.status === 403))) {
2401
+ throw error;
2402
+ }
1887
2403
  return undefined;
1888
2404
  }
1889
2405
  }
@@ -2043,6 +2559,8 @@ function parseFlags(args, options = {}) {
2043
2559
  let publishSeparately = false;
2044
2560
  let allowDelete = false;
2045
2561
  let allowPurge = false;
2562
+ let name;
2563
+ let dryRun = false;
2046
2564
  for (let i = 0; i < args.length; i++) {
2047
2565
  const arg = args[i];
2048
2566
  if (arg === "--json") {
@@ -2055,6 +2573,16 @@ function parseFlags(args, options = {}) {
2055
2573
  throw new Error("--title requires a value");
2056
2574
  continue;
2057
2575
  }
2576
+ if (arg === "--name") {
2577
+ name = args[++i];
2578
+ if (!name)
2579
+ throw new UsageError("--name requires a value", "name_missing");
2580
+ continue;
2581
+ }
2582
+ if (arg === "--dry-run") {
2583
+ dryRun = true;
2584
+ continue;
2585
+ }
2058
2586
  if (arg === "--version") {
2059
2587
  const raw = args[++i];
2060
2588
  const parsed = raw === undefined ? Number.NaN : Number(raw);
@@ -2104,12 +2632,12 @@ function parseFlags(args, options = {}) {
2104
2632
  if (arg === "--settings") {
2105
2633
  const raw = args[++i];
2106
2634
  if (!raw)
2107
- throw new Error("--settings requires a value");
2635
+ throw new UsageError("--settings requires a value", "settings_json_invalid");
2108
2636
  settings = parseSettingsJson(raw);
2109
2637
  continue;
2110
2638
  }
2111
2639
  if (arg === "--password" || arg.startsWith("--password=")) {
2112
- throw new Error("Passwords are not accepted as --password <value>. Use --password-stdin.");
2640
+ throw new UsageError("Passwords are not accepted as --password <value>. Use --password-stdin.", "password_flag_unsupported");
2113
2641
  }
2114
2642
  if (arg === "--password-stdin") {
2115
2643
  passwordStdin = true;
@@ -2144,7 +2672,7 @@ function parseFlags(args, options = {}) {
2144
2672
  continue;
2145
2673
  }
2146
2674
  if (arg.startsWith("-"))
2147
- throw new Error(`Unknown option: ${arg}`);
2675
+ throw new UsageError(`Unknown option: ${describeArgvToken(arg)}`, "unknown_option", { option: describeArgvToken(arg) });
2148
2676
  positionals.push(arg);
2149
2677
  }
2150
2678
  return {
@@ -2166,6 +2694,8 @@ function parseFlags(args, options = {}) {
2166
2694
  publishSeparately,
2167
2695
  allowDelete,
2168
2696
  allowPurge,
2697
+ ...(name === undefined ? {} : { name }),
2698
+ dryRun,
2169
2699
  };
2170
2700
  }
2171
2701
  function parseGlobalFlags(argv) {
@@ -2189,9 +2719,11 @@ function help() {
2189
2719
  " foleo environment [--json]",
2190
2720
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
2191
2721
  " foleo get <id> [--json]",
2192
- " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--json]",
2722
+ " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--json]",
2723
+ " foleo publish <dir> --accept-hosting-risk --name <label> [--dry-run] [--json]",
2193
2724
  " foleo update <id> <path> --revision <etag> [--json]",
2194
2725
  " foleo update <id> <file.md> --version <version> [--json] (compatibility)",
2726
+ " foleo name-check <label> [--json]",
2195
2727
  " foleo status <id> [--json]",
2196
2728
  " foleo settings <id> [--json]",
2197
2729
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--json]",