@foleo/cli 0.1.16 → 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
@@ -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
@@ -138,15 +140,60 @@ export async function runCli(argv, deps = {
138
140
  return await skill(rest, commandDeps);
139
141
  if (command === "doctor")
140
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
+ }
141
149
  commandDeps.stderr(help());
142
150
  return 2;
143
151
  }
144
152
  catch (error) {
145
- deps.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
146
- 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;
159
+ }
160
+ }
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);
147
172
  }
173
+ return error;
148
174
  }
149
- class UsageError extends Error {
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>`;
150
197
  }
151
198
  function warnDeprecatedAlias(deps, alias, canonical) {
152
199
  deps.stderr(`warning: \`foleo ${alias}\` is a deprecated alias; use \`foleo ${canonical}\`.\n`);
@@ -495,6 +542,7 @@ async function login(args, deps) {
495
542
  return 0;
496
543
  }
497
544
  async function htmlPublish(args, deps) {
545
+ resolveUploadRate(deps);
498
546
  const parsed = parseFlags(args);
499
547
  const root = parsed.positionals[0];
500
548
  if (!root || parsed.positionals.length !== 1 || !parsed.acceptHostingRisk)
@@ -503,7 +551,7 @@ async function htmlPublish(args, deps) {
503
551
  if (parsed.passwordStdin) {
504
552
  const password = stripTrailingNewline(await readStdinText(deps));
505
553
  if (password.length < 12 || password.length > 256) {
506
- 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 });
507
555
  }
508
556
  settings.password = password;
509
557
  }
@@ -513,6 +561,7 @@ async function htmlPublish(args, deps) {
513
561
  return 0;
514
562
  }
515
563
  async function htmlUpdate(args, deps) {
564
+ resolveUploadRate(deps);
516
565
  const parsed = parseFlags(args);
517
566
  const [id, root] = parsed.positionals;
518
567
  const revision = legacyRevision(parsed.revision);
@@ -564,7 +613,7 @@ async function htmlPassword(args, deps) {
564
613
  }
565
614
  const password = stripTrailingNewline(await readStdinText(deps));
566
615
  if (password.length < 12 || password.length > 256) {
567
- 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 });
568
617
  }
569
618
  announceApi(deps, parsed.json);
570
619
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/password`, {
@@ -585,7 +634,7 @@ async function settingsCommand(args, deps) {
585
634
  if (parsed.passwordStdin) {
586
635
  const password = stripTrailingNewline(await readStdinText(deps));
587
636
  if (password.length < 12 || password.length > 256) {
588
- 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 });
589
638
  }
590
639
  patch.password = password;
591
640
  }
@@ -621,8 +670,11 @@ async function limitsCommand(args, deps) {
621
670
  method: "GET",
622
671
  });
623
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
+ }
624
676
  if (!response.ok) {
625
- throw new Error(`Foleo API error: HTTP ${response.status} reading /v1/capabilities`);
677
+ throw new ApiRequestError(response.status, apiErrorCode(service, response.status), service);
626
678
  }
627
679
  const serviceVersion = service !== null &&
628
680
  typeof service === "object" &&
@@ -648,15 +700,15 @@ function parseSettingsSets(sets) {
648
700
  for (const entry of sets) {
649
701
  const separator = entry.indexOf("=");
650
702
  if (separator <= 0) {
651
- 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");
652
704
  }
653
705
  const key = entry.slice(0, separator);
654
706
  const raw = entry.slice(separator + 1);
655
707
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
656
- throw new Error(`Unknown settings field: ${key}`);
708
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
657
709
  }
658
710
  if (key === "password") {
659
- 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");
660
712
  }
661
713
  patch[key] = coerceSettingsValue(raw);
662
714
  }
@@ -677,19 +729,19 @@ function parseSettingsJson(raw) {
677
729
  parsed = JSON.parse(raw);
678
730
  }
679
731
  catch {
680
- throw new Error("--settings requires a JSON object");
732
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
681
733
  }
682
734
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
683
- throw new Error("--settings requires a JSON object");
735
+ throw new UsageError("--settings requires a JSON object", "settings_json_invalid");
684
736
  }
685
737
  const settings = parsed;
686
738
  for (const key of Object.keys(settings)) {
687
739
  if (!SETTINGS_SURFACE_FIELD_IDS.includes(key)) {
688
- throw new Error(`Unknown settings field: ${key}`);
740
+ throw new UsageError(`Unknown settings field: ${describeArgvToken(key)}`, "settings_field_unknown", { field: describeArgvToken(key) });
689
741
  }
690
742
  }
691
743
  if ("password" in settings) {
692
- 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");
693
745
  }
694
746
  return settings;
695
747
  }
@@ -733,24 +785,32 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
733
785
  // counts the session create and complete calls against the same budget as the
734
786
  // file PUTs, so pacing only the PUTs overspends it.
735
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();
736
792
  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
- }));
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);
747
805
  let uploaded = 0;
748
806
  for (const plan of upload.files) {
749
807
  const file = files.find((candidate) => candidate.path === plan.path);
750
808
  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) }));
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);
754
814
  uploaded += 1;
755
815
  // A large bundle is paced to well under a minute's worth of requests, so a
756
816
  // silent multi-minute publish reads as a hang. Progress goes to stderr so
@@ -760,55 +820,67 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
760
820
  }
761
821
  }
762
822
  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
- }));
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();
769
833
  const sourceId = update
770
834
  ? await ownerArtifactSourceId(deps, update.id)
771
835
  : undefined;
772
836
  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",
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", {
871
+ method: "POST",
790
872
  body: {
791
873
  sourceFormat: "html",
792
874
  uploadId: upload.uploadId,
793
875
  manifestHash: upload.manifestHash,
876
+ hostingRiskAcknowledged,
794
877
  source,
878
+ ...(publishSeparately ? { allowDuplicate: true } : {}),
879
+ ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
795
880
  },
796
- headers: artifactMutationHeaders(update.etag, randomUUID()),
881
+ headers: { "idempotency-key": createKey },
797
882
  });
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
- });
883
+ }, budget);
812
884
  }
813
885
  function revisionHeaders(revision) {
814
886
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -859,6 +931,7 @@ function artifactMutationHeaders(revision, idempotencyKey) {
859
931
  * budget.
860
932
  */
861
933
  function createHtmlUploadPacer(deps) {
934
+ const limit = resolveUploadRate(deps);
862
935
  const now = deps.now ?? Date.now;
863
936
  const sleep = deps.sleep ??
864
937
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
@@ -869,7 +942,7 @@ function createHtmlUploadPacer(deps) {
869
942
  const cutoff = now() - HTML_UPLOAD_FILE_WINDOW_MS;
870
943
  while (recent.length > 0 && recent[0] <= cutoff)
871
944
  recent.shift();
872
- if (recent.length < HTML_UPLOAD_FILE_PUTS_PER_WINDOW)
945
+ if (recent.length < limit)
873
946
  break;
874
947
  // Wait for the oldest request to age out of the window, plus a little
875
948
  // jitter so retries from separate processes do not re-align.
@@ -879,6 +952,35 @@ function createHtmlUploadPacer(deps) {
879
952
  recent.push(now());
880
953
  };
881
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
+ }
882
984
  /**
883
985
  * Retry a request that the edge or API refused for rate-limiting reasons.
884
986
  *
@@ -898,39 +1000,118 @@ function createHtmlUploadPacer(deps) {
898
1000
  */
899
1001
  const RETRYABLE_STATUSES = new Set([429, 503]);
900
1002
  const MAX_RATE_LIMIT_RETRIES = 6;
901
- 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()) {
902
1027
  const sleep = deps.sleep ??
903
1028
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
904
1029
  for (let retry = 0;; retry++) {
905
1030
  try {
906
- return await attempt();
1031
+ return await attempt(retry);
907
1032
  }
908
1033
  catch (error) {
909
1034
  if (!(error instanceof RateLimitedError) ||
910
1035
  !RETRYABLE_STATUSES.has(error.status)) {
911
1036
  throw error;
912
1037
  }
913
- if (retry >= MAX_RATE_LIMIT_RETRIES) {
914
- throw new Error(`${describe} was rate limited ${retry + 1} times; giving up. Try again shortly.`);
915
- }
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;
916
1044
  const backoff = Math.min(30_000, 1_000 * 2 ** retry);
917
1045
  const wait = (error.retryAfterMs ?? backoff) +
918
1046
  Math.floor((deps.random ?? Math.random)() * 500);
1047
+ if (wait > budget.remaining())
1048
+ throw error;
1049
+ budget.spend(wait);
919
1050
  deps.stderr(`Rate limited on ${describe}; retrying in ${Math.ceil(wait / 1000)}s (attempt ${retry + 2}).\n`);
920
1051
  await sleep(wait);
921
1052
  }
922
1053
  }
923
1054
  }
924
- 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 {
925
1068
  status;
926
1069
  retryAfterMs;
927
- constructor(status, retryAfterMs) {
928
- 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";
929
1104
  this.status = status;
930
1105
  this.retryAfterMs = retryAfterMs;
931
- this.name = "RateLimitedError";
932
1106
  }
933
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
+ }
934
1115
  /** `Retry-After` is seconds or an HTTP-date; both are valid per RFC 9110. */
935
1116
  function retryAfterMs(header, now) {
936
1117
  if (header === null)
@@ -977,14 +1158,40 @@ export async function scanBundle(root, deps) {
977
1158
  pathSegments.length > HTML_BUNDLE_MAX_PATH_SEGMENTS ||
978
1159
  pathSegments.some((segment) => new TextEncoder().encode(segment).byteLength >
979
1160
  HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
980
- 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
+ });
981
1169
  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");
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
+ });
986
1187
  if (fileCount + 1 > HTML_BUNDLE_MAX_FILES)
987
- 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
+ });
988
1195
  const mediaType = mediaTypeFor(path);
989
1196
  // Collect every unsupported path and report them together after the walk.
990
1197
  // Failing on the first one turned a Next/Astro export with three stray file
@@ -995,12 +1202,34 @@ export async function scanBundle(root, deps) {
995
1202
  continue;
996
1203
  }
997
1204
  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");
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
+ });
1004
1233
  fileCount += 1;
1005
1234
  totalBytes += bytes.byteLength;
1006
1235
  files.push({
@@ -1016,13 +1245,20 @@ export async function scanBundle(root, deps) {
1016
1245
  if (unsupported.length > 0) {
1017
1246
  const shown = unsupported.slice(0, 10).join(", ");
1018
1247
  const rest = unsupported.length > 10 ? ` (+${unsupported.length - 10} more)` : "";
1019
- 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
+ });
1020
1251
  }
1021
1252
  if (!files.some((file) => file.path === "/index.html"))
1022
- 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" } });
1023
1254
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
1024
1255
  if (htmlFiles.length > HTML_BUNDLE_MAX_HTML_FILES)
1025
- 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
+ });
1026
1262
  const routes = new Set();
1027
1263
  for (const file of htmlFiles) {
1028
1264
  const route = file.path === "/index.html"
@@ -1031,7 +1267,7 @@ export async function scanBundle(root, deps) {
1031
1267
  ? `${file.path.slice(0, -"/index.html".length)}/`
1032
1268
  : file.path.replace(/\.html?$/i, "");
1033
1269
  if (routes.has(route))
1034
- throw new Error(`Ambiguous HTML route: ${route}`);
1270
+ throw new LocalError("bundle_ambiguous_route", `Ambiguous HTML route: ${route}`, { context: { route, path: file.path } });
1035
1271
  routes.add(route);
1036
1272
  }
1037
1273
  return files.sort((a, b) => a.path.localeCompare(b.path));
@@ -1090,11 +1326,11 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1090
1326
  try {
1091
1327
  const stat = await file.stat();
1092
1328
  if (!stat.isFile())
1093
- 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 } });
1094
1330
  if (stat.nlink > 1)
1095
- 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 } });
1096
1332
  if (stat.size > maxBytes)
1097
- 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 } });
1098
1334
  const resolved = await realpath(path);
1099
1335
  if (resolved !== realBase && !resolved.startsWith(`${realBase}${sep}`))
1100
1336
  throw new Error("Bundle path escaped root");
@@ -1108,7 +1344,7 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1108
1344
  break;
1109
1345
  total += bytesRead;
1110
1346
  if (total > maxBytes)
1111
- 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 } });
1112
1348
  chunks.push(new Uint8Array(buffer.subarray(0, bytesRead)));
1113
1349
  }
1114
1350
  }
@@ -1124,6 +1360,7 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
1124
1360
  return result;
1125
1361
  }
1126
1362
  async function publish(args, deps) {
1363
+ resolveUploadRate(deps);
1127
1364
  const parsed = parseFlags(args);
1128
1365
  const file = parsed.positionals[0];
1129
1366
  if (!file || parsed.positionals.length !== 1)
@@ -1131,12 +1368,12 @@ async function publish(args, deps) {
1131
1368
  const isDirectory = await pathIsDirectory(file, deps);
1132
1369
  if (isDirectory) {
1133
1370
  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");
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");
1135
1372
  }
1136
1373
  return htmlPublish(args, deps);
1137
1374
  }
1138
1375
  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.");
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 } });
1140
1377
  }
1141
1378
  const markdown = await deps.readFile(file, "utf8");
1142
1379
  const assets = await uploadMarkdownAssets(file, markdown, deps);
@@ -1160,6 +1397,7 @@ async function publish(args, deps) {
1160
1397
  return 0;
1161
1398
  }
1162
1399
  async function update(args, deps) {
1400
+ resolveUploadRate(deps);
1163
1401
  const parsed = parseFlags(args);
1164
1402
  const [id, file] = parsed.positionals;
1165
1403
  if (!id || !file || parsed.positionals.length !== 2) {
@@ -1187,7 +1425,7 @@ async function update(args, deps) {
1187
1425
  }
1188
1426
  const opaqueRevision = parsed.revision === undefined ? null : artifactRevision(parsed.revision);
1189
1427
  if (parsed.revision !== undefined && opaqueRevision === null) {
1190
- throw new Error("--revision requires an opaque Artifact ETag");
1428
+ throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
1191
1429
  }
1192
1430
  const markdown = await deps.readFile(file, "utf8");
1193
1431
  const assets = await uploadMarkdownAssets(file, markdown, deps);
@@ -1275,13 +1513,29 @@ export async function scanMarkdownAssets(markdownPath, markdown, deps) {
1275
1513
  throw error;
1276
1514
  }
1277
1515
  if (bytes.byteLength > LIVE_DOC_ASSET_MAX_FILE_BYTES) {
1278
- 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
+ });
1279
1523
  }
1280
1524
  if (files.length + 1 > LIVE_DOC_ASSET_MAX_FILES) {
1281
- 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
+ });
1282
1531
  }
1283
1532
  if (totalBytes + bytes.byteLength > LIVE_DOC_ASSET_MAX_BYTES) {
1284
- 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
+ });
1285
1539
  }
1286
1540
  seen.add(logical);
1287
1541
  totalBytes += bytes.byteLength;
@@ -1348,32 +1602,43 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
1348
1602
  if (files.length === 0)
1349
1603
  return null;
1350
1604
  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
1605
  // 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.
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.
1362
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);
1363
1624
  for (const plan of upload.files) {
1364
1625
  const file = files.find((candidate) => candidate.path === plan.path);
1365
1626
  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) }));
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);
1369
1632
  }
1370
1633
  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
- }));
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);
1377
1642
  return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
1378
1643
  }
1379
1644
  async function unpublish(args, deps) {
@@ -1504,7 +1769,9 @@ async function list(args, deps) {
1504
1769
  }
1505
1770
  const credential = await resolveCredentialWithSource(deps);
1506
1771
  if (!credential)
1507
- 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
+ });
1508
1775
  const query = new URLSearchParams();
1509
1776
  if (kind && legacyFormat === null)
1510
1777
  query.set("kind", kind);
@@ -1540,7 +1807,9 @@ async function whoami(args, deps) {
1540
1807
  throw new Error("Usage: foleo whoami [--json]");
1541
1808
  const credential = await resolveCredentialWithSource(deps);
1542
1809
  if (!credential)
1543
- 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
+ });
1544
1813
  const result = await requestJsonWithToken(deps, "/me", credential.token, {
1545
1814
  method: "GET",
1546
1815
  body: undefined,
@@ -1566,7 +1835,9 @@ function environmentCommand(args, deps) {
1566
1835
  async function requestJson(deps, path, init) {
1567
1836
  const credential = await resolveCredentialWithSource(deps);
1568
1837
  if (!credential)
1569
- 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
+ });
1570
1841
  return requestJsonWithToken(deps, path, credential.token, init);
1571
1842
  }
1572
1843
  async function requestJsonWithToken(deps, path, token, init) {
@@ -1586,36 +1857,51 @@ async function requestJsonWithToken(deps, path, token, init) {
1586
1857
  if (RETRYABLE_STATUSES.has(response.status)) {
1587
1858
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
1588
1859
  // 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)()));
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);
1591
1863
  }
1592
1864
  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);
1865
+ throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
1602
1866
  }
1603
1867
  return body;
1604
1868
  }
1605
- class ApiRequestError extends Error {
1869
+ class ApiRequestError extends FoleoError {
1606
1870
  status;
1607
- code;
1608
1871
  body;
1609
1872
  constructor(status, code, body) {
1610
- super(code === "matching_source_exists"
1611
- ? matchingSourceExistsMessage(body)
1612
- : `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";
1613
1884
  this.status = status;
1614
- this.code = code;
1615
1885
  this.body = body;
1616
- this.name = "ApiRequestError";
1617
1886
  }
1618
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
+ }
1619
1905
  function matchingSourceExistsMessage(body) {
1620
1906
  const errorBody = isRecord(body) && isRecord(body.error) ? body.error : null;
1621
1907
  const matches = errorBody && Array.isArray(errorBody.matches)
@@ -1640,36 +1926,54 @@ async function requestPublicJson(deps, path, body) {
1640
1926
  body: JSON.stringify(body),
1641
1927
  });
1642
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
+ }
1643
1934
  if (!response.ok)
1644
1935
  throw apiResponseError(response.status, parsed);
1645
1936
  return parsed;
1646
1937
  }
1647
- 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) {
1648
1945
  const credential = await resolveCredentialWithSource(deps);
1649
1946
  if (!credential)
1650
- 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
+ });
1651
1950
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
1652
1951
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
1653
1952
  method: "PUT",
1654
1953
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
1655
1954
  body: bytes,
1656
1955
  });
1657
- if (RETRYABLE_STATUSES.has(response.status)) {
1658
- 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);
1659
1973
  }
1660
- if (!response.ok)
1661
- throw new Error(`Foleo API error: HTTP ${response.status}`);
1662
1974
  }
1663
1975
  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}`);
1976
+ return new ApiRequestError(status, apiErrorCode(body, status), body);
1673
1977
  }
1674
1978
  function apiBase(deps) {
1675
1979
  const selected = deps.env.FOLEO_ENV ?? "production";
@@ -1882,8 +2186,15 @@ async function ownerArtifactSourceId(deps, id) {
1882
2186
  ? source.id
1883
2187
  : undefined;
1884
2188
  }
1885
- catch {
2189
+ catch (error) {
1886
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
+ }
1887
2198
  return undefined;
1888
2199
  }
1889
2200
  }
@@ -2104,12 +2415,12 @@ function parseFlags(args, options = {}) {
2104
2415
  if (arg === "--settings") {
2105
2416
  const raw = args[++i];
2106
2417
  if (!raw)
2107
- throw new Error("--settings requires a value");
2418
+ throw new UsageError("--settings requires a value", "settings_json_invalid");
2108
2419
  settings = parseSettingsJson(raw);
2109
2420
  continue;
2110
2421
  }
2111
2422
  if (arg === "--password" || arg.startsWith("--password=")) {
2112
- 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");
2113
2424
  }
2114
2425
  if (arg === "--password-stdin") {
2115
2426
  passwordStdin = true;
@@ -2144,7 +2455,7 @@ function parseFlags(args, options = {}) {
2144
2455
  continue;
2145
2456
  }
2146
2457
  if (arg.startsWith("-"))
2147
- throw new Error(`Unknown option: ${arg}`);
2458
+ throw new UsageError(`Unknown option: ${describeArgvToken(arg)}`, "unknown_option", { option: describeArgvToken(arg) });
2148
2459
  positionals.push(arg);
2149
2460
  }
2150
2461
  return {