@foleo/cli 0.1.15 → 0.1.18

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
@@ -2,15 +2,18 @@
2
2
  import { spawn } from "node:child_process";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { constants } from "node:fs";
5
- import { lstat as defaultLstat, readFile, realpath } from "node:fs/promises";
5
+ import { lstat as defaultLstat, readFile, realpath, stat as defaultStat, } from "node:fs/promises";
6
6
  import { open } from "node:fs/promises";
7
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",
15
+ "artifacts:publish",
16
+ "artifacts:settings",
14
17
  "artifacts:unpublish",
15
18
  "docs:write",
16
19
  "docs:unpublish",
@@ -58,6 +61,7 @@ export async function runCli(argv, deps = {
58
61
  stdout: (message) => process.stdout.write(message),
59
62
  stderr: (message) => process.stderr.write(message),
60
63
  }) {
64
+ const wantsJson = argv.includes("--json");
61
65
  try {
62
66
  const global = parseGlobalFlags(argv);
63
67
  const commandDeps = global.environment
@@ -96,18 +100,30 @@ export async function runCli(argv, deps = {
96
100
  return await status(rest, commandDeps);
97
101
  if (command === "get")
98
102
  return await status(rest, commandDeps);
99
- if (command === "html-publish")
103
+ if (command === "html-publish") {
104
+ warnDeprecatedAlias(commandDeps, "html-publish", "publish <path> --accept-hosting-risk");
100
105
  return await htmlPublish(rest, commandDeps);
101
- if (command === "html-update")
106
+ }
107
+ if (command === "html-update") {
108
+ warnDeprecatedAlias(commandDeps, "html-update", "update <id> <path>");
102
109
  return await htmlUpdate(rest, commandDeps);
103
- if (command === "html-status")
110
+ }
111
+ if (command === "html-status") {
112
+ warnDeprecatedAlias(commandDeps, "html-status", "status <id>");
104
113
  return await htmlStatus(rest, commandDeps);
105
- if (command === "html-visibility")
114
+ }
115
+ if (command === "html-visibility") {
116
+ warnDeprecatedAlias(commandDeps, "html-visibility", "settings <id> --set visibility=...");
106
117
  return await htmlVisibility(rest, commandDeps);
107
- if (command === "html-password")
118
+ }
119
+ if (command === "html-password") {
120
+ warnDeprecatedAlias(commandDeps, "html-password", "settings <id> --password-stdin");
108
121
  return await htmlPassword(rest, commandDeps);
109
- if (command === "html-unpublish")
122
+ }
123
+ if (command === "html-unpublish") {
124
+ warnDeprecatedAlias(commandDeps, "html-unpublish", "unpublish <id>");
110
125
  return await htmlUnpublish(rest, commandDeps);
126
+ }
111
127
  if (command === "settings")
112
128
  return await settingsCommand(rest, commandDeps);
113
129
  if (command === "limits")
@@ -124,15 +140,63 @@ export async function runCli(argv, deps = {
124
140
  return await skill(rest, commandDeps);
125
141
  if (command === "doctor")
126
142
  return await doctor(rest, commandDeps);
143
+ if (wantsJson) {
144
+ const rendered = renderFailure(new UsageError(`Unknown command: ${describeArgvToken(command)}`, "unknown_command", { command: describeArgvToken(command) }), true);
145
+ if (rendered.stdout !== null)
146
+ commandDeps.stdout(rendered.stdout);
147
+ return rendered.exitCode;
148
+ }
127
149
  commandDeps.stderr(help());
128
150
  return 2;
129
151
  }
130
152
  catch (error) {
131
- deps.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
132
- return error instanceof UsageError ? 2 : 1;
153
+ const rendered = renderFailure(normalizeThrown(error), wantsJson);
154
+ if (rendered.stdout !== null)
155
+ deps.stdout(rendered.stdout);
156
+ if (rendered.stderr !== null)
157
+ deps.stderr(rendered.stderr);
158
+ return rendered.exitCode;
133
159
  }
134
160
  }
135
- class UsageError extends Error {
161
+ /**
162
+ * Usage-shaped failures exit 2 even when they were thrown as a plain `Error`.
163
+ * Twenty-six call sites throw `Usage: foleo …` prose directly, and normalising
164
+ * them one by one would leave the contract depending on nobody forgetting; the
165
+ * message prefix is the shape the CLI already commits to in `help()`.
166
+ */
167
+ function normalizeThrown(error) {
168
+ if (error instanceof FoleoError)
169
+ return error;
170
+ if (error instanceof Error && error.message.startsWith("Usage:")) {
171
+ return new UsageError(error.message);
172
+ }
173
+ return error;
174
+ }
175
+ /**
176
+ * argv is echoed back by the "unknown command/option" errors, and those messages
177
+ * now reach *stdout* under `--json`. A shell expands secrets into argv easily
178
+ * (`foleo "$FOLEO_TOKEN"`, `--token=…`), so only a value already shaped like a
179
+ * command or flag name is echoed; anything else is redacted. Keeping the shape
180
+ * preserves the typo hint that makes the message useful.
181
+ */
182
+ // Deliberately narrower than "looks like a word": every real command and flag
183
+ // name in this CLI is short lowercase letters and hyphens, while credentials are
184
+ // long and almost always carry digits. An earlier version of this pattern
185
+ // allowed digits and 32 characters, and a test proved it happily echoed
186
+ // `sk-live-9f2c41aa8bd34e0197c6` verbatim.
187
+ const ARGV_NAME_PATTERN = /^[a-z][a-z-]{0,19}$/;
188
+ function describeArgvToken(raw) {
189
+ if (!raw.startsWith("-")) {
190
+ return ARGV_NAME_PATTERN.test(raw) ? raw : "<redacted>";
191
+ }
192
+ const dashes = raw.startsWith("--") ? "--" : "-";
193
+ const name = raw.replace(/^-+/, "").split("=")[0] ?? "";
194
+ return ARGV_NAME_PATTERN.test(name)
195
+ ? `${dashes}${name}`
196
+ : `${dashes}<redacted>`;
197
+ }
198
+ function warnDeprecatedAlias(deps, alias, canonical) {
199
+ deps.stderr(`warning: \`foleo ${alias}\` is a deprecated alias; use \`foleo ${canonical}\`.\n`);
136
200
  }
137
201
  const SKILL_PATH = fileURLToPath(new URL("../skills/foleo/SKILL.md", import.meta.url));
138
202
  const PACKAGE_JSON_PATH = fileURLToPath(new URL("../package.json", import.meta.url));
@@ -315,9 +379,12 @@ async function doctor(args, deps) {
315
379
  const bootstrapRequired = me.bootstrapRequired === true;
316
380
  const scopes = stringArray(me.scopes);
317
381
  const entitlements = stringArray(me.entitlements);
318
- const markdown = !bootstrapRequired && scopes.includes("docs:write");
382
+ const markdown = !bootstrapRequired &&
383
+ (scopes.includes("artifacts:publish") || scopes.includes("docs:write"));
319
384
  const html = !bootstrapRequired &&
320
385
  (scopes.includes("html:write") ||
386
+ (scopes.includes("artifacts:publish") &&
387
+ scopes.includes("artifacts:publish:active")) ||
321
388
  entitlements.includes("publish.html_artifact.create"));
322
389
  checks.push({
323
390
  key: "account",
@@ -475,6 +542,7 @@ async function login(args, deps) {
475
542
  return 0;
476
543
  }
477
544
  async function htmlPublish(args, deps) {
545
+ resolveUploadRate(deps);
478
546
  const parsed = parseFlags(args);
479
547
  const root = parsed.positionals[0];
480
548
  if (!root || parsed.positionals.length !== 1 || !parsed.acceptHostingRisk)
@@ -483,7 +551,7 @@ async function htmlPublish(args, deps) {
483
551
  if (parsed.passwordStdin) {
484
552
  const password = stripTrailingNewline(await readStdinText(deps));
485
553
  if (password.length < 12 || password.length > 256) {
486
- throw new Error("Password must be 12–256 characters.");
554
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
487
555
  }
488
556
  settings.password = password;
489
557
  }
@@ -493,12 +561,14 @@ async function htmlPublish(args, deps) {
493
561
  return 0;
494
562
  }
495
563
  async function htmlUpdate(args, deps) {
564
+ resolveUploadRate(deps);
496
565
  const parsed = parseFlags(args);
497
566
  const [id, root] = parsed.positionals;
498
567
  const revision = legacyRevision(parsed.revision);
499
568
  if (!id || !root || parsed.positionals.length !== 2 || revision === null)
500
569
  throw new Error("Usage: foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]");
501
570
  const result = await publishBundle(root, deps, {
571
+ family: "compatibility",
502
572
  id,
503
573
  revision,
504
574
  });
@@ -543,7 +613,7 @@ async function htmlPassword(args, deps) {
543
613
  }
544
614
  const password = stripTrailingNewline(await readStdinText(deps));
545
615
  if (password.length < 12 || password.length > 256) {
546
- throw new Error("Password must be 12–256 characters.");
616
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
547
617
  }
548
618
  announceApi(deps, parsed.json);
549
619
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/password`, {
@@ -564,7 +634,7 @@ async function settingsCommand(args, deps) {
564
634
  if (parsed.passwordStdin) {
565
635
  const password = stripTrailingNewline(await readStdinText(deps));
566
636
  if (password.length < 12 || password.length > 256) {
567
- throw new Error("Password must be 12–256 characters.");
637
+ throw new UsageError("Password must be 12–256 characters.", "password_invalid_length", { minimum: 12, maximum: 256 });
568
638
  }
569
639
  patch.password = password;
570
640
  }
@@ -600,8 +670,11 @@ async function limitsCommand(args, deps) {
600
670
  method: "GET",
601
671
  });
602
672
  const service = await response.json().catch(() => null);
673
+ if (RETRYABLE_STATUSES.has(response.status)) {
674
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(service), service);
675
+ }
603
676
  if (!response.ok) {
604
- throw new Error(`Foleo API error: HTTP ${response.status} reading /v1/capabilities`);
677
+ throw new ApiRequestError(response.status, apiErrorCode(service, response.status), service);
605
678
  }
606
679
  const serviceVersion = service !== null &&
607
680
  typeof service === "object" &&
@@ -627,15 +700,15 @@ function parseSettingsSets(sets) {
627
700
  for (const entry of sets) {
628
701
  const separator = entry.indexOf("=");
629
702
  if (separator <= 0) {
630
- throw new Error(`Invalid --set ${entry}; expected key=value`);
703
+ throw new UsageError(`Invalid --set ${describeArgvToken(entry.split("=")[0] ?? entry)}; expected key=value`, "settings_set_invalid");
631
704
  }
632
705
  const key = entry.slice(0, separator);
633
706
  const raw = entry.slice(separator + 1);
634
707
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
635
- throw new Error(`Unknown settings field: ${key}`);
708
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
636
709
  }
637
710
  if (key === "password") {
638
- throw new Error("Passwords are not accepted as --set password=…. Use --password-stdin.");
711
+ throw new UsageError("Passwords are not accepted as --set password=…. Use --password-stdin.", "password_flag_unsupported");
639
712
  }
640
713
  patch[key] = coerceSettingsValue(raw);
641
714
  }
@@ -656,19 +729,19 @@ function parseSettingsJson(raw) {
656
729
  parsed = JSON.parse(raw);
657
730
  }
658
731
  catch {
659
- throw new Error("--settings requires a JSON object");
732
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
660
733
  }
661
734
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
662
- throw new Error("--settings requires a JSON object");
735
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
663
736
  }
664
737
  const settings = parsed;
665
738
  for (const key of Object.keys(settings)) {
666
739
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
667
- throw new Error(`Unknown settings field: ${key}`);
740
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
668
741
  }
669
742
  }
670
743
  if ("password" in settings) {
671
- throw new Error("Passwords are not accepted inside --settings. Use --password-stdin with foleo settings.");
744
+ throw new UsageError("Passwords are not accepted inside --settings. Use --password-stdin with foleo settings.", "password_flag_unsupported");
672
745
  }
673
746
  return settings;
674
747
  }
@@ -712,24 +785,32 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
712
785
  // counts the session create and complete calls against the same budget as the
713
786
  // file PUTs, so pacing only the PUTs overspends it.
714
787
  const pace = createHtmlUploadPacer(deps);
788
+ // One budget for the whole publish, and pacing inside each retry attempt: a
789
+ // retry is another request against the same fence, so pacing only the first
790
+ // attempt spends the budget it was meant to protect.
791
+ const budget = createRetryBudget();
715
792
  const uploadKey = randomUUID();
716
- await pace();
717
- const upload = await withRateLimitRetry(deps, "starting the upload", () => requestJson(deps, "/uploads", {
718
- method: "POST",
719
- body: {
720
- kind: "html-artifact-bundle",
721
- manifest,
722
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
723
- },
724
- headers: { "idempotency-key": uploadKey },
725
- }));
793
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
794
+ await pace();
795
+ return requestJson(deps, "/uploads", {
796
+ method: "POST",
797
+ body: {
798
+ kind: "html-artifact-bundle",
799
+ manifest,
800
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
801
+ },
802
+ headers: { "idempotency-key": uploadKey },
803
+ });
804
+ }, budget);
726
805
  let uploaded = 0;
727
806
  for (const plan of upload.files) {
728
807
  const file = files.find((candidate) => candidate.path === plan.path);
729
808
  if (!file)
730
- throw new Error("Server returned an unexpected upload file");
731
- await pace();
732
- await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
809
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
810
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
811
+ await pace();
812
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
813
+ }, budget);
733
814
  uploaded += 1;
734
815
  // A large bundle is paced to well under a minute's worth of requests, so a
735
816
  // silent multi-minute publish reads as a hang. Progress goes to stderr so
@@ -739,32 +820,57 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
739
820
  }
740
821
  }
741
822
  const completeKey = randomUUID();
742
- await pace();
743
- await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
744
- method: "POST",
745
- body: {},
746
- headers: { "idempotency-key": completeKey },
747
- }));
823
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
824
+ await pace();
825
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
826
+ method: "POST",
827
+ body: {},
828
+ headers: { "idempotency-key": completeKey },
829
+ });
830
+ }, budget);
831
+ if (update)
832
+ await pace();
748
833
  const sourceId = update
749
834
  ? await ownerArtifactSourceId(deps, update.id)
750
835
  : undefined;
751
836
  const source = publishSourcePayload(upload.manifestHash, sourceId);
752
- return update
753
- ? requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
754
- method: "PUT",
755
- body: {
756
- uploadId: upload.uploadId,
757
- manifestHash: upload.manifestHash,
758
- source,
759
- },
760
- headers: {
761
- "if-match": `"r${update.revision}"`,
762
- "idempotency-key": randomUUID(),
763
- },
764
- })
765
- : requestJson(deps, "/artifacts/html", {
837
+ // The whole bundle is already uploaded by the time we get here, so losing this
838
+ // one request to a throttle discards the entire publish — the exact failure
839
+ // spec 089 exists to close. The key is minted ONCE outside the retry closure,
840
+ // so a retry reuses it and cannot double-create.
841
+ const createKey = randomUUID();
842
+ return withRateLimitRetry(deps, "creating the artifact", async () => {
843
+ await pace();
844
+ if (update?.family === "compatibility") {
845
+ return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
846
+ method: "PUT",
847
+ body: {
848
+ uploadId: upload.uploadId,
849
+ manifestHash: upload.manifestHash,
850
+ source,
851
+ },
852
+ headers: {
853
+ "if-match": `"r${update.revision}"`,
854
+ "idempotency-key": createKey,
855
+ },
856
+ });
857
+ }
858
+ if (update?.family === "generic") {
859
+ return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
860
+ method: "PUT",
861
+ body: {
862
+ sourceFormat: "html",
863
+ uploadId: upload.uploadId,
864
+ manifestHash: upload.manifestHash,
865
+ source,
866
+ },
867
+ headers: artifactMutationHeaders(update.etag, createKey),
868
+ });
869
+ }
870
+ return requestJson(deps, "/artifacts", {
766
871
  method: "POST",
767
872
  body: {
873
+ sourceFormat: "html",
768
874
  uploadId: upload.uploadId,
769
875
  manifestHash: upload.manifestHash,
770
876
  hostingRiskAcknowledged,
@@ -772,8 +878,9 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
772
878
  ...(publishSeparately ? { allowDuplicate: true } : {}),
773
879
  ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
774
880
  },
775
- headers: { "idempotency-key": randomUUID() },
881
+ headers: { "idempotency-key": createKey },
776
882
  });
883
+ }, budget);
777
884
  }
778
885
  function revisionHeaders(revision) {
779
886
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -824,6 +931,7 @@ function artifactMutationHeaders(revision, idempotencyKey) {
824
931
  * budget.
825
932
  */
826
933
  function createHtmlUploadPacer(deps) {
934
+ const limit = resolveUploadRate(deps);
827
935
  const now = deps.now ?? Date.now;
828
936
  const sleep = deps.sleep ??
829
937
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
@@ -834,7 +942,7 @@ function createHtmlUploadPacer(deps) {
834
942
  const cutoff = now() - HTML_UPLOAD_FILE_WINDOW_MS;
835
943
  while (recent.length > 0 && recent[0] <= cutoff)
836
944
  recent.shift();
837
- if (recent.length < HTML_UPLOAD_FILE_PUTS_PER_WINDOW)
945
+ if (recent.length < limit)
838
946
  break;
839
947
  // Wait for the oldest request to age out of the window, plus a little
840
948
  // jitter so retries from separate processes do not re-align.
@@ -844,6 +952,35 @@ function createHtmlUploadPacer(deps) {
844
952
  recent.push(now());
845
953
  };
846
954
  }
955
+ const HTML_UPLOAD_RATE_MIN = 1;
956
+ const HTML_UPLOAD_RATE_MAX = 60;
957
+ /**
958
+ * `FOLEO_UPLOAD_RATE` caps the total `/v1/*` requests this process places in one
959
+ * rolling 10-second window — total requests, not files per second, because the
960
+ * fence counts session create/complete calls too. It exists so a user throttled
961
+ * by an intermediary can slow down without waiting for a release.
962
+ *
963
+ * The default stays at the shipped 7 rather than spec 089's originally-drafted
964
+ * 5: `5404a47` simulated the window and chose 7 against a fence of 10, and that
965
+ * simulation postdates the draft. Lowering it would cost every publish time to
966
+ * fix a cause the retraction in §F already disproved.
967
+ */
968
+ function resolveUploadRate(deps) {
969
+ const raw = deps.env.FOLEO_UPLOAD_RATE;
970
+ if (raw === undefined || raw.trim() === "")
971
+ return HTML_UPLOAD_FILE_PUTS_PER_WINDOW;
972
+ const value = Number(raw.trim());
973
+ if (!Number.isInteger(value) ||
974
+ value < HTML_UPLOAD_RATE_MIN ||
975
+ value > HTML_UPLOAD_RATE_MAX) {
976
+ 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", {
977
+ value: raw,
978
+ minimum: HTML_UPLOAD_RATE_MIN,
979
+ maximum: HTML_UPLOAD_RATE_MAX,
980
+ });
981
+ }
982
+ return value;
983
+ }
847
984
  /**
848
985
  * Retry a request that the edge or API refused for rate-limiting reasons.
849
986
  *
@@ -863,39 +1000,118 @@ function createHtmlUploadPacer(deps) {
863
1000
  */
864
1001
  const RETRYABLE_STATUSES = new Set([429, 503]);
865
1002
  const MAX_RATE_LIMIT_RETRIES = 6;
866
- async function withRateLimitRetry(deps, describe, attempt) {
1003
+ /**
1004
+ * Total wall-clock this CLI will sleep inside one operation before handing the
1005
+ * decision back to the caller. Without it, `Retry-After` was honoured verbatim
1006
+ * and unbounded: a quota rejection advertising ~24h parked the process for a
1007
+ * day per attempt, six attempts deep, which reads to an agent as a hang.
1008
+ */
1009
+ const RATE_LIMIT_TOTAL_BUDGET_MS = 120_000;
1010
+ /**
1011
+ * One sleep budget for a whole publish, not for each request inside it.
1012
+ *
1013
+ * Scoping it per call looked bounded and was not: a 119-file bundle makes one
1014
+ * retry call per file, each starting from zero, so the "120s budget" was really
1015
+ * 120s x 121 requests — hours of sleeping presented to the caller as a bound.
1016
+ */
1017
+ function createRetryBudget() {
1018
+ let slept = 0;
1019
+ return {
1020
+ remaining: () => RATE_LIMIT_TOTAL_BUDGET_MS - slept,
1021
+ spend: (ms) => {
1022
+ slept += ms;
1023
+ },
1024
+ };
1025
+ }
1026
+ async function withRateLimitRetry(deps, describe, attempt, budget = createRetryBudget()) {
867
1027
  const sleep = deps.sleep ??
868
1028
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
869
1029
  for (let retry = 0;; retry++) {
870
1030
  try {
871
- return await attempt();
1031
+ return await attempt(retry);
872
1032
  }
873
1033
  catch (error) {
874
1034
  if (!(error instanceof RateLimitedError) ||
875
1035
  !RETRYABLE_STATUSES.has(error.status)) {
876
1036
  throw error;
877
1037
  }
878
- if (retry >= MAX_RATE_LIMIT_RETRIES) {
879
- throw new Error(`${describe} was rate limited ${retry + 1} times; giving up. Try again shortly.`);
880
- }
1038
+ // A spent quota window is not a transient burst: waiting cannot help
1039
+ // inside any budget a foreground command may spend, so surface it.
1040
+ if (!error.retryable)
1041
+ throw error;
1042
+ if (retry >= MAX_RATE_LIMIT_RETRIES)
1043
+ throw error;
881
1044
  const backoff = Math.min(30_000, 1_000 * 2 ** retry);
882
1045
  const wait = (error.retryAfterMs ?? backoff) +
883
1046
  Math.floor((deps.random ?? Math.random)() * 500);
1047
+ if (wait > budget.remaining())
1048
+ throw error;
1049
+ budget.spend(wait);
884
1050
  deps.stderr(`Rate limited on ${describe}; retrying in ${Math.ceil(wait / 1000)}s (attempt ${retry + 2}).\n`);
885
1051
  await sleep(wait);
886
1052
  }
887
1053
  }
888
1054
  }
889
- class RateLimitedError extends Error {
1055
+ /**
1056
+ * The three actionable 429 classes of spec 089 §E.
1057
+ *
1058
+ * The API answers a spent *quota* window and a *burst* rejection with the same
1059
+ * `rate_limited` code today — `reserveHtmlQuota` returns
1060
+ * `apiError(429, "rate_limited")` with `retry-after` set to the window end,
1061
+ * which for a daily create-attempt budget is hours away. So the advertised
1062
+ * delay, not the code, is what separates them: anything the retry budget cannot
1063
+ * absorb is a quota window by definition. A response with no Foleo envelope at
1064
+ * all came from an intermediary rather than the Worker, and is reported as
1065
+ * `upstream_rate_limited` without asserting which one.
1066
+ */
1067
+ class RateLimitedError extends FoleoError {
890
1068
  status;
891
1069
  retryAfterMs;
892
- constructor(status, retryAfterMs) {
893
- super(`Foleo API error: HTTP ${status}`);
1070
+ constructor(status, retryAfterMs, apiCode, body) {
1071
+ // The delay heuristic applies ONLY to a 429 carrying a Foleo envelope. A 503
1072
+ // is `quota_initializing` in this API — the quota system warming up, which is
1073
+ // transient and retryable — so reading a long delay there as an exhausted
1074
+ // budget would both mislabel it and suppress a retry that should happen.
1075
+ const exhausted = status === 429 &&
1076
+ apiCode !== null &&
1077
+ (apiCode === "quota_attempts_exhausted" ||
1078
+ (retryAfterMs !== null && retryAfterMs > RATE_LIMIT_TOTAL_BUDGET_MS));
1079
+ const code = exhausted
1080
+ ? "quota_attempts_exhausted"
1081
+ : apiCode !== null
1082
+ ? apiCode
1083
+ : status === 429
1084
+ ? "upstream_rate_limited"
1085
+ : "service_unavailable";
1086
+ const seconds = retryAfterMs === null ? null : Math.ceil(retryAfterMs / 1_000);
1087
+ super({
1088
+ code,
1089
+ message: exhausted
1090
+ ? "Foleo publishing quota is exhausted for this window."
1091
+ : status === 429
1092
+ ? "Too many requests to the Foleo API."
1093
+ : "The Foleo API is temporarily unavailable.",
1094
+ next: exhausted
1095
+ ? `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.`
1096
+ : `Wait ${seconds ?? 10} seconds and run the same command again.`,
1097
+ retryable: !exhausted,
1098
+ retryAfterSeconds: seconds,
1099
+ httpStatus: status,
1100
+ source: apiCode === null ? "upstream" : "api",
1101
+ ...(body === undefined ? {} : { context: { apiCode } }),
1102
+ });
1103
+ this.name = "RateLimitedError";
894
1104
  this.status = status;
895
1105
  this.retryAfterMs = retryAfterMs;
896
- this.name = "RateLimitedError";
897
1106
  }
898
1107
  }
1108
+ function describeDelay(seconds) {
1109
+ if (seconds < 90)
1110
+ return `${seconds} seconds`;
1111
+ if (seconds < 5_400)
1112
+ return `${Math.round(seconds / 60)} minutes`;
1113
+ return `${Math.round(seconds / 3_600)} hours`;
1114
+ }
899
1115
  /** `Retry-After` is seconds or an HTTP-date; both are valid per RFC 9110. */
900
1116
  function retryAfterMs(header, now) {
901
1117
  if (header === null)
@@ -942,14 +1158,40 @@ export async function scanBundle(root, deps) {
942
1158
  pathSegments.length > HTML_BUNDLE_MAX_PATH_SEGMENTS ||
943
1159
  pathSegments.some((segment) => new TextEncoder().encode(segment).byteLength >
944
1160
  HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
945
- throw new Error(`Invalid bundle path: ${path}`);
1161
+ throw new LocalError("bundle_path_invalid", `Invalid bundle path: ${path}`, {
1162
+ context: {
1163
+ path,
1164
+ limitPathBytes: HTML_BUNDLE_MAX_PATH_BYTES,
1165
+ limitSegments: HTML_BUNDLE_MAX_PATH_SEGMENTS,
1166
+ limitSegmentBytes: HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES,
1167
+ },
1168
+ });
946
1169
  if (!info.isFile())
947
- throw new Error(`Unsupported bundle file: ${path}`);
948
- if (info.size > HTML_BUNDLE_MAX_FILE_BYTES ||
949
- totalBytes + info.size > HTML_BUNDLE_MAX_BYTES)
950
- throw new Error("Bundle exceeds Foleo limits");
1170
+ throw new LocalError("bundle_file_not_regular", `Unsupported bundle file: ${path}`, { context: { path } });
1171
+ if (info.size > HTML_BUNDLE_MAX_FILE_BYTES)
1172
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, {
1173
+ context: {
1174
+ path,
1175
+ bytes: info.size,
1176
+ limitBytes: HTML_BUNDLE_MAX_FILE_BYTES,
1177
+ },
1178
+ });
1179
+ if (totalBytes + info.size > HTML_BUNDLE_MAX_BYTES)
1180
+ throw new LocalError("bundle_total_too_large", "Bundle exceeds the total size limit.", {
1181
+ context: {
1182
+ path,
1183
+ bytes: totalBytes + info.size,
1184
+ limitBytes: HTML_BUNDLE_MAX_BYTES,
1185
+ },
1186
+ });
951
1187
  if (fileCount + 1 > HTML_BUNDLE_MAX_FILES)
952
- throw new Error("Bundle exceeds Foleo limits");
1188
+ throw new LocalError("bundle_too_many_files", "Bundle exceeds the file-count limit.", {
1189
+ context: {
1190
+ path,
1191
+ fileCount: fileCount + 1,
1192
+ limitFiles: HTML_BUNDLE_MAX_FILES,
1193
+ },
1194
+ });
953
1195
  const mediaType = mediaTypeFor(path);
954
1196
  // Collect every unsupported path and report them together after the walk.
955
1197
  // Failing on the first one turned a Next/Astro export with three stray file
@@ -960,12 +1202,34 @@ export async function scanBundle(root, deps) {
960
1202
  continue;
961
1203
  }
962
1204
  const bytes = await bytesFor(absolute);
963
- if (mediaType === "text/html; charset=utf-8" &&
964
- (bytes.byteLength > HTML_BUNDLE_MAX_HTML_BYTES || !isValidUtf8(bytes)))
965
- throw new Error(`Invalid HTML document: ${path}`);
966
- if (bytes.byteLength > HTML_BUNDLE_MAX_FILE_BYTES ||
967
- totalBytes + bytes.byteLength > HTML_BUNDLE_MAX_BYTES)
968
- throw new Error("Bundle exceeds Foleo limits");
1205
+ if (mediaType === "text/html; charset=utf-8") {
1206
+ if (bytes.byteLength > HTML_BUNDLE_MAX_HTML_BYTES)
1207
+ throw new LocalError("bundle_html_too_large", `HTML document exceeds the per-document limit: ${path}`, {
1208
+ context: {
1209
+ path,
1210
+ bytes: bytes.byteLength,
1211
+ limitBytes: HTML_BUNDLE_MAX_HTML_BYTES,
1212
+ },
1213
+ });
1214
+ if (!isValidUtf8(bytes))
1215
+ throw new LocalError("bundle_html_invalid_utf8", `HTML document is not valid UTF-8: ${path}`, { context: { path } });
1216
+ }
1217
+ if (bytes.byteLength > HTML_BUNDLE_MAX_FILE_BYTES)
1218
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, {
1219
+ context: {
1220
+ path,
1221
+ bytes: bytes.byteLength,
1222
+ limitBytes: HTML_BUNDLE_MAX_FILE_BYTES,
1223
+ },
1224
+ });
1225
+ if (totalBytes + bytes.byteLength > HTML_BUNDLE_MAX_BYTES)
1226
+ throw new LocalError("bundle_total_too_large", "Bundle exceeds the total size limit.", {
1227
+ context: {
1228
+ path,
1229
+ bytes: totalBytes + bytes.byteLength,
1230
+ limitBytes: HTML_BUNDLE_MAX_BYTES,
1231
+ },
1232
+ });
969
1233
  fileCount += 1;
970
1234
  totalBytes += bytes.byteLength;
971
1235
  files.push({
@@ -981,13 +1245,20 @@ export async function scanBundle(root, deps) {
981
1245
  if (unsupported.length > 0) {
982
1246
  const shown = unsupported.slice(0, 10).join(", ");
983
1247
  const rest = unsupported.length > 10 ? ` (+${unsupported.length - 10} more)` : "";
984
- throw new Error(`Unsupported bundle file${unsupported.length > 1 ? "s" : ""}: ${shown}${rest}`);
1248
+ throw new LocalError("bundle_unsupported_media_type", `Unsupported bundle file${unsupported.length > 1 ? "s" : ""}: ${shown}${rest}`, {
1249
+ context: { paths: unsupported.slice(0, 10), count: unsupported.length },
1250
+ });
985
1251
  }
986
1252
  if (!files.some((file) => file.path === "/index.html"))
987
- throw new Error("Bundle root must contain index.html");
1253
+ throw new LocalError("bundle_missing_entry", "Bundle root must contain index.html", { context: { expected: "/index.html" } });
988
1254
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
989
1255
  if (htmlFiles.length > HTML_BUNDLE_MAX_HTML_FILES)
990
- throw new Error("Bundle exceeds Foleo limits");
1256
+ throw new LocalError("bundle_too_many_html_files", "Bundle exceeds the HTML-document count limit.", {
1257
+ context: {
1258
+ htmlFileCount: htmlFiles.length,
1259
+ limitHtmlFiles: HTML_BUNDLE_MAX_HTML_FILES,
1260
+ },
1261
+ });
991
1262
  const routes = new Set();
992
1263
  for (const file of htmlFiles) {
993
1264
  const route = file.path === "/index.html"
@@ -996,7 +1267,7 @@ export async function scanBundle(root, deps) {
996
1267
  ? `${file.path.slice(0, -"/index.html".length)}/`
997
1268
  : file.path.replace(/\.html?$/i, "");
998
1269
  if (routes.has(route))
999
- throw new Error(`Ambiguous HTML route: ${route}`);
1270
+ throw new LocalError("bundle_ambiguous_route", `Ambiguous HTML route: ${route}`, { context: { route, path: file.path } });
1000
1271
  routes.add(route);
1001
1272
  }
1002
1273
  return files.sort((a, b) => a.path.localeCompare(b.path));
@@ -1055,11 +1326,11 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1055
1326
  try {
1056
1327
  const stat = await file.stat();
1057
1328
  if (!stat.isFile())
1058
- throw new Error("Bundle path is not a regular file");
1329
+ throw new LocalError("bundle_file_not_regular", "Bundle path is not a regular file", { context: { path } });
1059
1330
  if (stat.nlink > 1)
1060
- throw new Error("Bundle path has multiple hard links");
1331
+ throw new LocalError("bundle_file_hard_linked", "Bundle path has multiple hard links", { context: { path } });
1061
1332
  if (stat.size > maxBytes)
1062
- throw new Error("Bundle exceeds Foleo limits");
1333
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, { context: { path, bytes: stat.size, limitBytes: maxBytes } });
1063
1334
  const resolved = await realpath(path);
1064
1335
  if (resolved !== realBase && !resolved.startsWith(`${realBase}${sep}`))
1065
1336
  throw new Error("Bundle path escaped root");
@@ -1073,7 +1344,7 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1073
1344
  break;
1074
1345
  total += bytesRead;
1075
1346
  if (total > maxBytes)
1076
- throw new Error("Bundle exceeds Foleo limits");
1347
+ throw new LocalError("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${path}`, { context: { path, limitBytes: maxBytes } });
1077
1348
  chunks.push(new Uint8Array(buffer.subarray(0, bytesRead)));
1078
1349
  }
1079
1350
  }
@@ -1089,15 +1360,27 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1089
1360
  return result;
1090
1361
  }
1091
1362
  async function publish(args, deps) {
1363
+ resolveUploadRate(deps);
1092
1364
  const parsed = parseFlags(args);
1093
1365
  const file = parsed.positionals[0];
1094
1366
  if (!file || parsed.positionals.length !== 1)
1095
- throw new Error("Usage: foleo publish <file> [--title <title>] [--settings <json>] [--publish-separately] [--json]");
1367
+ throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--json]");
1368
+ const isDirectory = await pathIsDirectory(file, deps);
1369
+ if (isDirectory) {
1370
+ if (!parsed.acceptHostingRisk) {
1371
+ 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");
1372
+ }
1373
+ return htmlPublish(args, deps);
1374
+ }
1375
+ if (!file.toLowerCase().endsWith(".md")) {
1376
+ 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 } });
1377
+ }
1096
1378
  const markdown = await deps.readFile(file, "utf8");
1097
1379
  const assets = await uploadMarkdownAssets(file, markdown, deps);
1098
- const result = await requestJson(deps, "/docs", {
1380
+ const result = await requestJson(deps, "/artifacts", {
1099
1381
  method: "POST",
1100
1382
  body: {
1383
+ sourceFormat: "markdown",
1101
1384
  markdown,
1102
1385
  source: publishSourcePayload(sha256Utf8(markdown)),
1103
1386
  ...(parsed.publishSeparately ? { allowDuplicate: true } : {}),
@@ -1114,31 +1397,81 @@ async function publish(args, deps) {
1114
1397
  return 0;
1115
1398
  }
1116
1399
  async function update(args, deps) {
1400
+ resolveUploadRate(deps);
1117
1401
  const parsed = parseFlags(args);
1118
1402
  const [id, file] = parsed.positionals;
1119
- if (!id ||
1120
- !file ||
1121
- parsed.positionals.length !== 2 ||
1122
- parsed.version === undefined) {
1123
- throw new Error("Usage: foleo update <id> <file> --version <version> [--json]");
1403
+ if (!id || !file || parsed.positionals.length !== 2) {
1404
+ throw new Error("Usage: foleo update <id> <path> --revision <etag> [--json] (or Markdown compatibility --version <version>)");
1405
+ }
1406
+ const isDirectory = await pathIsDirectory(file, deps);
1407
+ if (isDirectory) {
1408
+ const revision = artifactRevision(parsed.revision);
1409
+ if (revision === null) {
1410
+ throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--json]");
1411
+ }
1412
+ const result = await publishBundle(file, deps, {
1413
+ family: "generic",
1414
+ id,
1415
+ etag: revision,
1416
+ });
1417
+ writeResult(deps, result, parsed.json);
1418
+ return 0;
1419
+ }
1420
+ if (!file.toLowerCase().endsWith(".md")) {
1421
+ throw new Error("Unsupported update input. Use a .md file or an HTML site directory.");
1422
+ }
1423
+ if (parsed.version === undefined && parsed.revision === undefined) {
1424
+ throw new Error("Usage: foleo update <id> <file> --revision <etag> [--json] (or compatibility --version <version>)");
1425
+ }
1426
+ const opaqueRevision = parsed.revision === undefined ? null : artifactRevision(parsed.revision);
1427
+ if (parsed.revision !== undefined && opaqueRevision === null) {
1428
+ throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
1124
1429
  }
1125
1430
  const markdown = await deps.readFile(file, "utf8");
1126
1431
  const assets = await uploadMarkdownAssets(file, markdown, deps);
1127
1432
  const sourceId = await ownerArtifactSourceId(deps, id);
1128
- const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
1129
- method: "PUT",
1130
- body: {
1131
- markdown,
1132
- version: parsed.version,
1133
- source: publishSourcePayload(sha256Utf8(markdown), sourceId),
1134
- ...(assets
1135
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
1136
- : {}),
1137
- },
1138
- });
1433
+ const source = publishSourcePayload(sha256Utf8(markdown), sourceId);
1434
+ const result = opaqueRevision !== null
1435
+ ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
1436
+ method: "PUT",
1437
+ body: {
1438
+ sourceFormat: "markdown",
1439
+ markdown,
1440
+ source,
1441
+ ...(assets
1442
+ ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
1443
+ : {}),
1444
+ },
1445
+ headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
1446
+ })
1447
+ : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
1448
+ method: "PUT",
1449
+ body: {
1450
+ markdown,
1451
+ version: parsed.version,
1452
+ source,
1453
+ ...(assets
1454
+ ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
1455
+ : {}),
1456
+ },
1457
+ });
1139
1458
  writeResult(deps, result, parsed.json);
1140
1459
  return 0;
1141
1460
  }
1461
+ async function pathIsDirectory(path, deps) {
1462
+ try {
1463
+ const info = await (deps.lstat ?? defaultLstat)(path);
1464
+ if (info.isDirectory())
1465
+ return true;
1466
+ if (info.isSymbolicLink()) {
1467
+ return (await (deps.stat ?? defaultStat)(path)).isDirectory();
1468
+ }
1469
+ }
1470
+ catch {
1471
+ // Preserve the existing read error for absent, inaccessible, or invalid paths.
1472
+ }
1473
+ return false;
1474
+ }
1142
1475
  /**
1143
1476
  * Scan Markdown for relative raster image references and build a live-doc
1144
1477
  * assets manifest (spec 065). Absolute http(s) / data: / rooted paths skipped.
@@ -1180,13 +1513,29 @@ export async function scanMarkdownAssets(markdownPath, markdown, deps) {
1180
1513
  throw error;
1181
1514
  }
1182
1515
  if (bytes.byteLength > LIVE_DOC_ASSET_MAX_FILE_BYTES) {
1183
- throw new Error("Live-doc assets exceed Foleo limits");
1516
+ throw new LocalError("asset_file_too_large", `Linked asset exceeds the per-file limit: ${logical}`, {
1517
+ context: {
1518
+ path: logical,
1519
+ bytes: bytes.byteLength,
1520
+ limitBytes: LIVE_DOC_ASSET_MAX_FILE_BYTES,
1521
+ },
1522
+ });
1184
1523
  }
1185
1524
  if (files.length + 1 > LIVE_DOC_ASSET_MAX_FILES) {
1186
- throw new Error("Live-doc assets exceed Foleo limits");
1525
+ throw new LocalError("asset_too_many_files", "Linked assets exceed the file-count limit.", {
1526
+ context: {
1527
+ fileCount: files.length + 1,
1528
+ limitFiles: LIVE_DOC_ASSET_MAX_FILES,
1529
+ },
1530
+ });
1187
1531
  }
1188
1532
  if (totalBytes + bytes.byteLength > LIVE_DOC_ASSET_MAX_BYTES) {
1189
- throw new Error("Live-doc assets exceed Foleo limits");
1533
+ throw new LocalError("asset_total_too_large", "Linked assets exceed the total size limit.", {
1534
+ context: {
1535
+ bytes: totalBytes + bytes.byteLength,
1536
+ limitBytes: LIVE_DOC_ASSET_MAX_BYTES,
1537
+ },
1538
+ });
1190
1539
  }
1191
1540
  seen.add(logical);
1192
1541
  totalBytes += bytes.byteLength;
@@ -1253,32 +1602,43 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
1253
1602
  if (files.length === 0)
1254
1603
  return null;
1255
1604
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
1256
- const upload = await requestJson(deps, "/uploads", {
1257
- method: "POST",
1258
- body: {
1259
- kind: "live-doc-assets",
1260
- manifest,
1261
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1262
- },
1263
- headers: { "idempotency-key": randomUUID() },
1264
- });
1265
1605
  // Same pacing and retry contract as the HTML bundle path: this loop hits the
1266
- // same /v1/ fence and previously discarded the whole upload on one 429.
1606
+ // same /v1/ fence and previously discarded the whole upload on one 429. The
1607
+ // pacer and budget are built before the first request, because the session
1608
+ // create counts against the same fence as the PUTs that follow it.
1267
1609
  const pace = createHtmlUploadPacer(deps);
1610
+ const budget = createRetryBudget();
1611
+ const uploadKey = randomUUID();
1612
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1613
+ await pace();
1614
+ return requestJson(deps, "/uploads", {
1615
+ method: "POST",
1616
+ body: {
1617
+ kind: "live-doc-assets",
1618
+ manifest,
1619
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1620
+ },
1621
+ headers: { "idempotency-key": uploadKey },
1622
+ });
1623
+ }, budget);
1268
1624
  for (const plan of upload.files) {
1269
1625
  const file = files.find((candidate) => candidate.path === plan.path);
1270
1626
  if (!file)
1271
- throw new Error("Server returned an unexpected upload file");
1272
- await pace();
1273
- await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
1627
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1628
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1629
+ await pace();
1630
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1631
+ }, budget);
1274
1632
  }
1275
1633
  const completeKey = randomUUID();
1276
- await pace();
1277
- await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1278
- method: "POST",
1279
- body: {},
1280
- headers: { "idempotency-key": completeKey },
1281
- }));
1634
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1635
+ await pace();
1636
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1637
+ method: "POST",
1638
+ body: {},
1639
+ headers: { "idempotency-key": completeKey },
1640
+ });
1641
+ }, budget);
1282
1642
  return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
1283
1643
  }
1284
1644
  async function unpublish(args, deps) {
@@ -1409,7 +1769,9 @@ async function list(args, deps) {
1409
1769
  }
1410
1770
  const credential = await resolveCredentialWithSource(deps);
1411
1771
  if (!credential)
1412
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
1772
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
1773
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
1774
+ });
1413
1775
  const query = new URLSearchParams();
1414
1776
  if (kind && legacyFormat === null)
1415
1777
  query.set("kind", kind);
@@ -1445,7 +1807,9 @@ async function whoami(args, deps) {
1445
1807
  throw new Error("Usage: foleo whoami [--json]");
1446
1808
  const credential = await resolveCredentialWithSource(deps);
1447
1809
  if (!credential)
1448
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
1810
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
1811
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
1812
+ });
1449
1813
  const result = await requestJsonWithToken(deps, "/me", credential.token, {
1450
1814
  method: "GET",
1451
1815
  body: undefined,
@@ -1471,7 +1835,9 @@ function environmentCommand(args, deps) {
1471
1835
  async function requestJson(deps, path, init) {
1472
1836
  const credential = await resolveCredentialWithSource(deps);
1473
1837
  if (!credential)
1474
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
1838
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
1839
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
1840
+ });
1475
1841
  return requestJsonWithToken(deps, path, credential.token, init);
1476
1842
  }
1477
1843
  async function requestJsonWithToken(deps, path, token, init) {
@@ -1491,36 +1857,51 @@ async function requestJsonWithToken(deps, path, token, init) {
1491
1857
  if (RETRYABLE_STATUSES.has(response.status)) {
1492
1858
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
1493
1859
  // zone fence in front of this API answers with a Cloudflare error page rather
1494
- // than the API's JSON envelope, so the status is the only reliable signal.
1495
- throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
1860
+ // than the API's JSON envelope, so an absent envelope is itself the signal
1861
+ // that some intermediary, not the Worker, produced this.
1862
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(body), body);
1496
1863
  }
1497
1864
  if (!response.ok) {
1498
- const code = body !== null &&
1499
- typeof body === "object" &&
1500
- "error" in body &&
1501
- typeof body.error === "object" &&
1502
- body.error !== null &&
1503
- "code" in body.error
1504
- ? String(body.error.code)
1505
- : `HTTP ${response.status}`;
1506
- throw new ApiRequestError(response.status, code, body);
1865
+ throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
1507
1866
  }
1508
1867
  return body;
1509
1868
  }
1510
- class ApiRequestError extends Error {
1869
+ class ApiRequestError extends FoleoError {
1511
1870
  status;
1512
- code;
1513
1871
  body;
1514
1872
  constructor(status, code, body) {
1515
- super(code === "matching_source_exists"
1516
- ? matchingSourceExistsMessage(body)
1517
- : `Foleo API error: ${code}`);
1873
+ const next = apiErrorNext(body);
1874
+ super({
1875
+ code,
1876
+ message: code === "matching_source_exists"
1877
+ ? matchingSourceExistsMessage(body)
1878
+ : `Foleo API error: ${code}`,
1879
+ httpStatus: status,
1880
+ source: "api",
1881
+ ...(next === null ? {} : { next }),
1882
+ });
1883
+ this.name = "ApiRequestError";
1518
1884
  this.status = status;
1519
- this.code = code;
1520
1885
  this.body = body;
1521
- this.name = "ApiRequestError";
1522
1886
  }
1523
1887
  }
1888
+ /**
1889
+ * `code` from an API envelope, falling back to a status-derived code. Never
1890
+ * emit a bare `HTTP {n}` when a body could have said more (§E rule 7): the
1891
+ * fallback is still a stable snake_case code, not a sentence.
1892
+ */
1893
+ function apiErrorCode(body, status) {
1894
+ return apiEnvelopeCode(body) ?? `http_${status}`;
1895
+ }
1896
+ /** `null` means the response carried no Foleo error envelope at all. */
1897
+ function apiEnvelopeCode(body) {
1898
+ const envelope = isRecord(body) && isRecord(body.error) ? body.error : null;
1899
+ return envelope && typeof envelope.code === "string" ? envelope.code : null;
1900
+ }
1901
+ function apiErrorNext(body) {
1902
+ const envelope = isRecord(body) && isRecord(body.error) ? body.error : null;
1903
+ return envelope && typeof envelope.next === "string" ? envelope.next : null;
1904
+ }
1524
1905
  function matchingSourceExistsMessage(body) {
1525
1906
  const errorBody = isRecord(body) && isRecord(body.error) ? body.error : null;
1526
1907
  const matches = errorBody && Array.isArray(errorBody.matches)
@@ -1545,36 +1926,54 @@ async function requestPublicJson(deps, path, body) {
1545
1926
  body: JSON.stringify(body),
1546
1927
  });
1547
1928
  const parsed = await response.json().catch(() => null);
1929
+ if (RETRYABLE_STATUSES.has(response.status)) {
1930
+ // login and other unauthenticated calls previously dropped `retry-after`
1931
+ // and reported every throttle as a flat, non-retryable API error.
1932
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(parsed), parsed);
1933
+ }
1548
1934
  if (!response.ok)
1549
1935
  throw apiResponseError(response.status, parsed);
1550
1936
  return parsed;
1551
1937
  }
1552
- async function requestRaw(deps, path, body, headers) {
1938
+ async function requestRaw(deps, path, body, headers,
1939
+ /**
1940
+ * Only a *retry* may treat a replay as success. On a first attempt this
1941
+ * process has not yet sent these bytes, so `upload_file_replayed` means
1942
+ * something else consumed the token and must surface as the conflict it is.
1943
+ */
1944
+ allowReplay = false) {
1553
1945
  const credential = await resolveCredentialWithSource(deps);
1554
1946
  if (!credential)
1555
- throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
1947
+ throw new LocalError("credential_missing", "No Foleo credential found.", {
1948
+ next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
1949
+ });
1556
1950
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
1557
1951
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
1558
1952
  method: "PUT",
1559
1953
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
1560
1954
  body: bytes,
1561
1955
  });
1562
- if (RETRYABLE_STATUSES.has(response.status)) {
1563
- throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
1956
+ if (!response.ok) {
1957
+ // The raw PUT path never parsed a response body, so every failure here was
1958
+ // reported as a bare `HTTP {n}` — the exact string the audited incident
1959
+ // gave the agent instead of a reason (§E rule 7).
1960
+ const body = await response.json().catch(() => null);
1961
+ if (RETRYABLE_STATUSES.has(response.status)) {
1962
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()), apiEnvelopeCode(body), body);
1963
+ }
1964
+ // A replay of *this* upload token, path, and content hash means the server
1965
+ // already holds the bytes we are trying to send. After a retried transport
1966
+ // failure that is confirmation of the earlier success, not a conflict.
1967
+ if (allowReplay &&
1968
+ response.status === 409 &&
1969
+ apiEnvelopeCode(body) === "upload_file_replayed") {
1970
+ return;
1971
+ }
1972
+ throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
1564
1973
  }
1565
- if (!response.ok)
1566
- throw new Error(`Foleo API error: HTTP ${response.status}`);
1567
1974
  }
1568
1975
  function apiResponseError(status, body) {
1569
- const code = body !== null &&
1570
- typeof body === "object" &&
1571
- "error" in body &&
1572
- typeof body.error === "object" &&
1573
- body.error !== null &&
1574
- "code" in body.error
1575
- ? String(body.error.code)
1576
- : `HTTP ${status}`;
1577
- return new Error(`Foleo API error: ${code}`);
1976
+ return new ApiRequestError(status, apiErrorCode(body, status), body);
1578
1977
  }
1579
1978
  function apiBase(deps) {
1580
1979
  const selected = deps.env.FOLEO_ENV ?? "production";
@@ -1787,8 +2186,15 @@ async function ownerArtifactSourceId(deps, id) {
1787
2186
  ? source.id
1788
2187
  : undefined;
1789
2188
  }
1790
- catch {
2189
+ catch (error) {
1791
2190
  // Old servers or a missing catalog field: still send the hash without an id.
2191
+ // A throttle or an auth failure is NOT that case — swallowing those sent an
2192
+ // update with no source id and hid the failed request behind a success.
2193
+ if (error instanceof RateLimitedError ||
2194
+ (error instanceof ApiRequestError &&
2195
+ (error.status === 401 || error.status === 403))) {
2196
+ throw error;
2197
+ }
1792
2198
  return undefined;
1793
2199
  }
1794
2200
  }
@@ -2009,12 +2415,12 @@ function parseFlags(args, options = {}) {
2009
2415
  if (arg === "--settings") {
2010
2416
  const raw = args[++i];
2011
2417
  if (!raw)
2012
- throw new Error("--settings requires a value");
2418
+ throw new UsageError("--settings requires a value", "settings_json_invalid");
2013
2419
  settings = parseSettingsJson(raw);
2014
2420
  continue;
2015
2421
  }
2016
2422
  if (arg === "--password" || arg.startsWith("--password=")) {
2017
- throw new Error("Passwords are not accepted as --password <value>. Use --password-stdin.");
2423
+ throw new UsageError("Passwords are not accepted as --password <value>. Use --password-stdin.", "password_flag_unsupported");
2018
2424
  }
2019
2425
  if (arg === "--password-stdin") {
2020
2426
  passwordStdin = true;
@@ -2049,7 +2455,7 @@ function parseFlags(args, options = {}) {
2049
2455
  continue;
2050
2456
  }
2051
2457
  if (arg.startsWith("-"))
2052
- throw new Error(`Unknown option: ${arg}`);
2458
+ throw new UsageError(`Unknown option: ${describeArgvToken(arg)}`, "unknown_option", { option: describeArgvToken(arg) });
2053
2459
  positionals.push(arg);
2054
2460
  }
2055
2461
  return {
@@ -2094,8 +2500,9 @@ function help() {
2094
2500
  " foleo environment [--json]",
2095
2501
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
2096
2502
  " foleo get <id> [--json]",
2097
- " foleo publish <file> [--title <title>] [--settings <json>] [--publish-separately] [--json]",
2098
- " foleo update <id> <file> --version <version> [--json]",
2503
+ " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--json]",
2504
+ " foleo update <id> <path> --revision <etag> [--json]",
2505
+ " foleo update <id> <file.md> --version <version> [--json] (compatibility)",
2099
2506
  " foleo status <id> [--json]",
2100
2507
  " foleo settings <id> [--json]",
2101
2508
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--json]",
@@ -2105,12 +2512,12 @@ function help() {
2105
2512
  " foleo restore <id> --revision <etag> [--json]",
2106
2513
  " foleo purge <id> --revision <etag> --confirm <id> [--json]",
2107
2514
  " foleo deletion-status <id> [--json]",
2108
- " foleo html-publish <bundle-root> --accept-hosting-risk [--settings <json>] [--password-stdin] [--publish-separately] [--json]",
2109
- " foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]",
2110
- " foleo html-status <id> [--json]",
2111
- " foleo html-visibility <id> --set unlisted|password|private --revision <stateRevision> [--json]",
2112
- " foleo html-password <id> --password-stdin --revision <stateRevision> [--json]",
2113
- " foleo html-unpublish <id> --revision <stateRevision> [--json]",
2515
+ " foleo html-publish <bundle-root> --accept-hosting-risk (deprecated alias of publish)",
2516
+ " foleo html-update <id> <bundle-root> --revision <stateRevision> (deprecated alias of update)",
2517
+ " foleo html-status <id> (deprecated alias of status)",
2518
+ " foleo html-visibility <id> --set unlisted|password|private --revision <stateRevision> (deprecated alias of settings)",
2519
+ " foleo html-password <id> --password-stdin --revision <stateRevision> (deprecated alias of settings)",
2520
+ " foleo html-unpublish <id> --revision <stateRevision> (deprecated alias of unpublish)",
2114
2521
  "",
2115
2522
  "Environment:",
2116
2523
  " --production (default), --staging, or --local selects a known API.",