pi-lean-host 0.7.2 → 0.8.0

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/core/helpers.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  /** Expand shorthand Accept names: json → application/json, xml → application/xml; else pass through. */
2
2
  function expandAccept(accept: string): string {
3
- return accept === "json"
4
- ? "application/json"
5
- : accept === "xml"
6
- ? "application/xml"
7
- : accept;
3
+ if (accept === "json") return "application/json";
4
+ if (accept === "xml") return "application/xml";
5
+ return accept;
8
6
  }
9
7
 
10
8
  /**
@@ -19,7 +17,20 @@ function expandAccept(accept: string): string {
19
17
  * Every helper returns a structured `HelperResult` or throws `HelperError`.
20
18
  */
21
19
 
20
+ import { randomBytes } from "node:crypto";
22
21
  import { XMLParser } from "fast-xml-parser";
22
+ import {
23
+ createWriteStream,
24
+ openSync,
25
+ renameSync,
26
+ statfsSync,
27
+ statSync,
28
+ unlinkSync,
29
+ type StatsFs,
30
+ type WriteStream,
31
+ } from "node:fs";
32
+ import { dirname, isAbsolute, join } from "node:path";
33
+ import type { Writable } from "node:stream";
23
34
  import { ssrfGuard } from "./ssrf-guard.js";
24
35
  import { scrubSecretValues } from "./auth.js";
25
36
  import { serverMessage, isPlanGated } from "./status-hint.js";
@@ -27,7 +38,9 @@ import {
27
38
  fetchUrl,
28
39
  redactSecretParams,
29
40
  redactSecretPathValues,
41
+ TransportRefusalError,
30
42
  type FetchOptions,
43
+ type StopBound,
31
44
  } from "./transport.js";
32
45
  import {
33
46
  fillPathTemplate,
@@ -36,6 +49,7 @@ import {
36
49
  wireParamName,
37
50
  } from "./path-template.js";
38
51
  import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
52
+ import { isDownloadClass } from "./api-guide-types.js";
39
53
  import type {
40
54
  ApiGuide,
41
55
  DateParamFormat,
@@ -89,6 +103,18 @@ export interface RestGetResult {
89
103
  /** True when the transport served this response from cache (header hit
90
104
  * or 304 revalidation). Absent for live fetches. */
91
105
  cached?: boolean;
106
+ /** Present on download-class calls only: where the body was written and
107
+ * its decompressed size. `data` stays undefined on these results — the
108
+ * body went to disk, never into context. */
109
+ file?: { path: string; bytes: number; contentType: string };
110
+ /** Final URL after redirects — present only when the response landed on
111
+ * a URL other than the requested one (e.g. a version walk or a Drive →
112
+ * *.googleusercontent.com hop). Redacted through both channels. */
113
+ finalUrl?: string;
114
+ /** Download-specific warning — e.g. a 2xx whose content-type is JSON-ish
115
+ * (an API response written as if it were the file). Separate from
116
+ * transformWarning so it doesn't render "⚠ Transform failed:". */
117
+ downloadWarning?: string;
92
118
  }
93
119
 
94
120
  export interface PaginateResult {
@@ -573,10 +599,22 @@ interface FetchWithOptsArgs {
573
599
  hasQuerySecret?: boolean | undefined;
574
600
  /** Injected query-secret names — redacted from every surfaced URL. */
575
601
  secretQueryParamNames?: Set<string> | undefined;
602
+ /** Caller's abort signal (tool-call cancellation), forwarded to the
603
+ * transport's composed request signal. */
604
+ signal?: AbortSignal | undefined;
576
605
  /** Path secrets present — cache-skip + guarded redirects. */
577
606
  hasPathSecret?: boolean | undefined;
578
607
  /** Redaction closure for cross-domain redirect hops. */
579
608
  redactPathSecret?: ((url: string) => string) | undefined;
609
+ /** Download mode: the caller-supplied writable the response body is
610
+ * piped into (the executor opened the run temp; the transport never
611
+ * sees a path). Present ⇒ sink mode — the manual redirect loop, cache
612
+ * arms skipped, headers-only abort timing. */
613
+ sink?: Writable | undefined;
614
+ /** The run's single stop bound (sink mode), resolved by the executor
615
+ * from the byte budget (if set) or the free-disk cap — passed through
616
+ * to the transport. */
617
+ stop?: StopBound | undefined;
580
618
  }
581
619
 
582
620
  function fetchWithOpts(
@@ -595,6 +633,9 @@ function fetchWithOpts(
595
633
  opts.secretQueryParamNames = args.secretQueryParamNames;
596
634
  if (args.hasPathSecret) opts.hasPathSecret = true;
597
635
  if (args.redactPathSecret) opts.redactPathSecret = args.redactPathSecret;
636
+ if (args.signal) opts.signal = args.signal;
637
+ if (args.sink !== undefined) opts.sink = args.sink;
638
+ if (args.stop !== undefined) opts.stop = args.stop;
598
639
  return fetchUrl(url, opts);
599
640
  }
600
641
 
@@ -753,6 +794,337 @@ function buildExecutorEnv(
753
794
  }
754
795
 
755
796
  // ═══════════════════════════════════════════════════════════════════
797
+ // ─────────── Download write layer ───────────
798
+ // The executor owns the file; the transport never writes. The download
799
+ // arm writes a unique per-run temp, the transport pipes the body into
800
+ // it through the shared decompress/count chain, and renameSync lands it
801
+ // on the destination at stream end. A failed or interrupted transfer
802
+ // never destroys a pre-existing file at the target path.
803
+
804
+ /** Clamp for filesystems whose free-space report cannot be trusted
805
+ * (overlayfs and some container stacks over-report) — set above the
806
+ * documented workload, never the operative bound on a healthy
807
+ * filesystem. Also the fallback when statfs fails. */
808
+ const MAX_DOWNLOAD_BYTES = 8 * 1024 * 1024 * 1024;
809
+ /** Fixed free-space headroom subtracted before the clamp. */
810
+ const DOWNLOAD_HEADROOM_BYTES = 256 * 1024 * 1024;
811
+
812
+ /** Per-run temp counter — two concurrent runs to one saveTo each own a
813
+ * temp, so both may complete and the last rename wins with a complete
814
+ * file (no interleaved bytes). */
815
+ let downloadTempCounter = 0;
816
+
817
+ /** Test seam — swap the statfs source used by computeDownloadCap (mirrors
818
+ * transport's `_setClockForTest`). Pass undefined to restore the real one. */
819
+ let _statfs: (path: string) => StatsFs = (p) => statfsSync(p);
820
+ export function _setStatfsForTest(
821
+ fn: ((path: string) => StatsFs) | undefined,
822
+ ): void {
823
+ _statfs = fn ?? ((p) => statfsSync(p));
824
+ }
825
+
826
+ /**
827
+ * The run's effective cap: min(statfs free space of the saveTo parent −
828
+ * headroom, MAX_DOWNLOAD_BYTES). A statfs failure falls back to the clamp;
829
+ * a computed cap ≤ 0 (free space already below headroom) is an intended
830
+ * refusal the caller renders as disk pressure.
831
+ */
832
+ function computeDownloadCap(saveTo: string): number {
833
+ try {
834
+ const s = _statfs(dirname(saveTo));
835
+ const free = s.bsize * s.bfree;
836
+ return Math.min(free - DOWNLOAD_HEADROOM_BYTES, MAX_DOWNLOAD_BYTES);
837
+ } catch {
838
+ return MAX_DOWNLOAD_BYTES;
839
+ }
840
+ }
841
+
842
+ /**
843
+ * Map a header-time transport refusal to executor vocabulary — one catch
844
+ * site shared by api-fetch and /api verify (both route through restGet's
845
+ * download arm). The transport never throws HelperError itself: importing
846
+ * it would create a transport → helpers → transport cycle.
847
+ */
848
+ function mapTransportRefusal(
849
+ err: TransportRefusalError,
850
+ url: string,
851
+ ): HelperError {
852
+ if (err.code === "lengthOverCap") {
853
+ return new HelperError(
854
+ "response",
855
+ `${err.message} — no file was written`,
856
+ "a target within the effective download cap (free disk space minus headroom)",
857
+ "content longer than the cap",
858
+ "Free up disk space or fetch a smaller file — the target exceeds the effective download cap.",
859
+ url,
860
+ );
861
+ }
862
+ return new HelperError(
863
+ "response",
864
+ `${err.message} — no file was written`,
865
+ "a supported Content-Encoding (gzip, identity, or none)",
866
+ err.message,
867
+ "The download arm decodes gzip only and fails closed on every other Content-Encoding — fetch from an endpoint that serves gzip or uncompressed bytes.",
868
+ url,
869
+ );
870
+ }
871
+
872
+ /** Arguments the download arm needs from its restGet call site — the
873
+ * pre-computed request state (steps 1–5) plus the download options. */
874
+ interface DownloadArmArgs {
875
+ /** Raw fetch URL (the fetch uses it; `url` is the redacted copy). */
876
+ fetchUrlRaw: string;
877
+ /** The redacted surfaced URL for errors and results. */
878
+ url: string;
879
+ /** Effective query params (the result's `params`). */
880
+ query: Record<string, string | string[]>;
881
+ /** Expanded Accept header. */
882
+ accept: string;
883
+ /** Env-owned fetch args (headers, secret channels, redirect flags). */
884
+ baseFetchArgs: Omit<FetchWithOptsArgs, "accept">;
885
+ /** Charset fallback for the non-2xx excerpt decode. */
886
+ fallbackCharset: string;
887
+ secretValues?: string[] | undefined;
888
+ secretParamNames: Set<string>;
889
+ pathValues: string[];
890
+ saveTo: string;
891
+ byteBudget?: number | undefined;
892
+ signal?: AbortSignal | undefined;
893
+ }
894
+
895
+ /**
896
+ * The plain download arm: stream the response body to a unique per-run
897
+ * temp, rename onto saveTo at stream end, return file metadata. Status
898
+ * handling has one ordering: checkResponseStatus first (its richer 4xx/5xx
899
+ * rendering — the scrubbed excerpt, the 403 plan-gating classifier — would
900
+ * be silently defeated on the 401/403 paths if the 2xx window ran first),
901
+ * then the explicit 2xx window throws for every status it still holds (a
902
+ * 304 or a terminal 3xx with no Location passes checkResponseStatus's <400
903
+ * gate silently — the window turns it into a named failure instead of a
904
+ * success-shaped bytes: 0 result). No file is ever written outside the
905
+ * window.
906
+ */
907
+ async function downloadRestGet(args: DownloadArmArgs): Promise<RestGetResult> {
908
+ const {
909
+ fetchUrlRaw,
910
+ url,
911
+ query,
912
+ accept,
913
+ baseFetchArgs,
914
+ fallbackCharset,
915
+ secretValues,
916
+ secretParamNames,
917
+ pathValues,
918
+ signal,
919
+ } = args;
920
+
921
+ // Destination checks BEFORE dispatch — a destination error thrown after
922
+ // headers arrive would leave a live response body undrained, and the
923
+ // executor holds no stream it could drain.
924
+ const parent = dirname(args.saveTo);
925
+ let parentOk = false;
926
+ try {
927
+ parentOk = statSync(parent).isDirectory();
928
+ } catch {
929
+ // missing parent → handled below
930
+ }
931
+ if (!parentOk) {
932
+ throw new HelperError(
933
+ "saveTo",
934
+ `Parent directory does not exist: ${parent}`,
935
+ "an existing parent directory",
936
+ "missing",
937
+ "create the parent directory first",
938
+ url,
939
+ );
940
+ }
941
+ let destIsDir = false;
942
+ try {
943
+ destIsDir = statSync(args.saveTo).isDirectory();
944
+ } catch {
945
+ // absent destination → created by the open below
946
+ }
947
+ if (destIsDir) {
948
+ throw new HelperError(
949
+ "saveTo",
950
+ `saveTo is an existing directory: ${args.saveTo}`,
951
+ "a file path",
952
+ "destination is a directory",
953
+ "pass a file path, not a directory",
954
+ url,
955
+ );
956
+ }
957
+ let stop: StopBound;
958
+ if (args.byteBudget === undefined) {
959
+ const cap = computeDownloadCap(args.saveTo);
960
+ if (cap <= 0) {
961
+ throw new HelperError(
962
+ "saveTo",
963
+ `Free disk space at ${parent} is below the download headroom (${DOWNLOAD_HEADROOM_BYTES} bytes) — refusing before any transfer`,
964
+ "a destination with enough free disk space",
965
+ "free space below headroom",
966
+ "Free up disk space, or fetch a smaller file.",
967
+ url,
968
+ );
969
+ }
970
+ stop = { bytes: cap, kind: "cap" };
971
+ } else {
972
+ // A budgeted call is intentionally partial — the free-disk cap is
973
+ // not consulted.
974
+ stop = { bytes: args.byteBudget, kind: "budget" };
975
+ }
976
+
977
+ // Unique per-run temp opened 'wx': an orphaned temp is never re-entered
978
+ // (each run gets its own name and starts from zero), a hostile directory
979
+ // can't pre-plant the path, and the sync open means the file always exists
980
+ // before any await — cleanup can never miss it.
981
+ let tempPath: string;
982
+ let sink: WriteStream;
983
+ try {
984
+ tempPath = `${args.saveTo}.${process.pid}.${++downloadTempCounter}.${randomBytes(6).toString("hex")}.part`;
985
+ // Default mode (0666 & ~umask) — curl parity. The temp's unique per-run
986
+ // name means a restrictive mode here would only carry through the rename
987
+ // to the destination, whose mode is the caller's business.
988
+ const fd = openSync(tempPath, "wx");
989
+ // createWriteStream drops .path when constructed from an fd — re-attach
990
+ // it so the stream stays self-describing.
991
+ sink = createWriteStream(tempPath, { fd });
992
+ sink.path = tempPath;
993
+ } catch (err) {
994
+ throw new HelperError(
995
+ "saveTo",
996
+ `Cannot create the download temp file: ${err instanceof Error ? err.message : String(err)}`,
997
+ "a writable destination path",
998
+ "unwritable",
999
+ "check the destination path's write permissions",
1000
+ url,
1001
+ );
1002
+ }
1003
+
1004
+ // Cancellation: on abort, unlink the run's temp and surface a clean
1005
+ // cancelled failure (the threaded signal also reaches the transport, so
1006
+ // the mid-body stream is aborted there — this listener owns the file).
1007
+ const onAbort = () => {
1008
+ try {
1009
+ unlinkSync(tempPath);
1010
+ } catch {
1011
+ // already gone / never created — nothing to clean
1012
+ }
1013
+ };
1014
+ signal?.addEventListener("abort", onAbort, { once: true });
1015
+ let renamed = false;
1016
+ try {
1017
+ let result: Awaited<ReturnType<typeof fetchUrl>>;
1018
+ try {
1019
+ result = await fetchWithOpts(fetchUrlRaw, {
1020
+ ...baseFetchArgs,
1021
+ accept,
1022
+ fallbackCharset,
1023
+ sink,
1024
+ stop,
1025
+ signal,
1026
+ });
1027
+ } catch (err) {
1028
+ if (signal?.aborted) {
1029
+ throw new HelperError(
1030
+ "signal",
1031
+ "Download cancelled — the partial transfer was discarded",
1032
+ "a completed transfer",
1033
+ "cancelled",
1034
+ "Re-call api-fetch to retry the download.",
1035
+ url,
1036
+ );
1037
+ }
1038
+ if (err instanceof TransportRefusalError) {
1039
+ throw mapTransportRefusal(err, url);
1040
+ }
1041
+ // Mid-body cap overrun — reachable when the header preflight was
1042
+ // skipped (gzip body, or no Content-Length) — gets the same
1043
+ // structured refusal as the header-time path; ENOSPC is the sink's
1044
+ // own write failure. The temp is unlinked in the finally below.
1045
+ if (err instanceof Error && err.name === "BodyTooLargeError") {
1046
+ throw mapTransportRefusal(
1047
+ new TransportRefusalError("lengthOverCap", err.message),
1048
+ url,
1049
+ );
1050
+ }
1051
+ if ((err as NodeJS.ErrnoException).code === "ENOSPC") {
1052
+ throw new HelperError(
1053
+ "saveTo",
1054
+ `Disk filled while writing the download: ${err instanceof Error ? err.message : String(err)}`,
1055
+ "a destination with enough free disk space",
1056
+ "ENOSPC",
1057
+ "Free up disk space, or fetch a smaller file.",
1058
+ url,
1059
+ );
1060
+ }
1061
+ throw err;
1062
+ }
1063
+
1064
+ // Status handling, one ordering (see the doc comment above).
1065
+ checkResponseStatus({ ...result, url }, secretValues);
1066
+ if (!(result.status >= 200 && result.status < 300)) {
1067
+ throw new HelperError(
1068
+ "response",
1069
+ `Download refused: HTTP ${result.status} is outside the 2xx window — a 304 or a terminal redirect is not a file`,
1070
+ "HTTP 2xx",
1071
+ String(result.status),
1072
+ undefined,
1073
+ url,
1074
+ );
1075
+ }
1076
+ // The file's true size, not the transport's counter — a budget stop
1077
+ // destroys the sink with buffered writes still unflushed, so counter
1078
+ // bytes can exceed what reached disk.
1079
+ const bytes = statSync(tempPath).size;
1080
+ renameSync(tempPath, args.saveTo);
1081
+ renamed = true;
1082
+
1083
+ const contentType = result.headers["content-type"] ?? "";
1084
+ // Wrong-op traps: a 200 JSON error body written as if it were the
1085
+ // file, or a 2xx that carried no bytes at all. An empty file is a
1086
+ // legal artifact, so the download still succeeds — but say so.
1087
+ let downloadWarning: string | undefined;
1088
+ if (/json/i.test(contentType)) {
1089
+ downloadWarning = `response is ${contentType} — wrote an API response, not a file; check the op/params`;
1090
+ } else if (bytes === 0) {
1091
+ downloadWarning =
1092
+ "empty body — the endpoint returned no bytes; check the op/params";
1093
+ }
1094
+ return {
1095
+ data: undefined,
1096
+ headers: result.headers,
1097
+ url,
1098
+ params: query,
1099
+ file: {
1100
+ path: args.saveTo,
1101
+ bytes,
1102
+ contentType,
1103
+ },
1104
+ ...(result.finalUrl === undefined
1105
+ ? {}
1106
+ : {
1107
+ finalUrl: redactSurfacedUrl(
1108
+ result.finalUrl,
1109
+ secretParamNames,
1110
+ pathValues,
1111
+ ),
1112
+ }),
1113
+ ...(downloadWarning === undefined ? {} : { downloadWarning }),
1114
+ };
1115
+ } finally {
1116
+ signal?.removeEventListener("abort", onAbort);
1117
+ if (!renamed) {
1118
+ try {
1119
+ unlinkSync(tempPath);
1120
+ } catch {
1121
+ // already unlinked (abort path) or never created
1122
+ }
1123
+ sink.destroy();
1124
+ }
1125
+ }
1126
+ }
1127
+
756
1128
  // restGet
757
1129
  // ═══════════════════════════════════════════════════════════════════
758
1130
 
@@ -786,6 +1158,16 @@ export interface RestGetOptions extends SecretAuthOpts {
786
1158
  transformFn?: TransformFn | undefined;
787
1159
  /** Guide directory name — transform context domain / helper routing. */
788
1160
  dirName?: string | undefined;
1161
+ /** Caller's abort signal (tool-call cancellation). */
1162
+ signal?: AbortSignal | undefined;
1163
+ /** Destination for a download-class call (op.download === true, or any
1164
+ * call with saveTo — explicit caller intent wins). Absolute, or relative
1165
+ * to the pi process's cwd, resolved at call time. */
1166
+ saveTo?: string | undefined;
1167
+ /** Byte-budget stop bound (the /api verify download probe): the counting
1168
+ * Transform stops cleanly at the budget — a pass signal, and the cap
1169
+ * plus the Content-Length preflight are both skipped for the run. */
1170
+ byteBudget?: number | undefined;
789
1171
  }
790
1172
 
791
1173
  /**
@@ -796,12 +1178,18 @@ export interface RestGetOptions extends SecretAuthOpts {
796
1178
  * 3. Checks auth dispatch (`none` / `static-key` realized; `oauth2` rejected at parse).
797
1179
  * 4. Constructs the full URL.
798
1180
  * 5. Builds the Accept header.
799
- * 6. Fetches via the transport layer.
800
- * 7. Checks HTTP status — raises HelperError on 4xx/5xx.
801
- * 8. Parses the response based on the operation's `parse` override or
1181
+ * 6. Download arm — a declared download op, or any call with `saveTo`:
1182
+ * streams the body to a temp file and renames onto the destination;
1183
+ * parse/errorPath/transform are skipped for this call.
1184
+ * 7. Fetches via the transport layer.
1185
+ * 8. Checks HTTP status — raises HelperError on 4xx/5xx.
1186
+ * 9. Parses the response based on the operation's `parse` override or
802
1187
  * the guide's `responseShape`.
1188
+ * 10. Post-response transform (optional).
803
1189
  *
804
- * @returns The parsed response data and response headers.
1190
+ * @returns The parsed response data and response headers — or, on a
1191
+ * download-class call, file metadata (`file.path/bytes/contentType`)
1192
+ * with no parsed body.
805
1193
  */
806
1194
  export async function restGet(
807
1195
  apiHost: string,
@@ -848,18 +1236,56 @@ export async function restGet(
848
1236
  // else passes through as-is (e.g. application/atom+xml, */*).
849
1237
  const accept = expandAccept(operation.accept);
850
1238
 
851
- // 6. Fetch. Pass the effective shape's charset as a transport fallback
1239
+ // Effective response shape — op-level parse override ?? guide-level.
1240
+ // (Computed before the download branch too: the non-2xx excerpt decode
1241
+ // uses its charset.)
1242
+ const shape = operation.parse ?? guide.responseShape;
1243
+
1244
+ // 6. Download arm — a download-class call (isDownloadClass: a declared
1245
+ // download op, or any call with saveTo — explicit caller intent wins).
1246
+ // saveTo is resolved here (relative ⇒ the pi process's cwd at
1247
+ // call time); the destination checks run inside the arm BEFORE dispatch.
1248
+ if (isDownloadClass(operation, opts?.saveTo)) {
1249
+ if (opts?.saveTo === undefined || opts.saveTo === "") {
1250
+ throw new HelperError(
1251
+ "saveTo",
1252
+ "Missing download destination — this operation returns a byte stream, not data",
1253
+ "a saveTo path (absolute, or relative to the pi process's cwd)",
1254
+ opts?.saveTo === "" ? "an empty string" : "missing",
1255
+ "pass saveTo: <path>",
1256
+ );
1257
+ }
1258
+ const saveTo = isAbsolute(opts.saveTo)
1259
+ ? opts.saveTo
1260
+ : join(process.cwd(), opts.saveTo);
1261
+ return downloadRestGet({
1262
+ fetchUrlRaw,
1263
+ url,
1264
+ query,
1265
+ accept,
1266
+ baseFetchArgs,
1267
+ fallbackCharset: shape.charset,
1268
+ secretValues: opts.secretValues,
1269
+ secretParamNames,
1270
+ pathValues,
1271
+ saveTo,
1272
+ byteBudget: opts.byteBudget,
1273
+ signal: opts.signal,
1274
+ });
1275
+ }
1276
+
1277
+ // 7. Fetch. Pass the effective shape's charset as a transport fallback
852
1278
  // for servers that omit a Content-Type charset (e.g. legacy Latin-1
853
1279
  // APIs); an explicit header charset always wins.
854
- const shape = operation.parse ?? guide.responseShape;
855
1280
  const result = await fetchWithOpts(fetchUrlRaw, {
856
1281
  ...baseFetchArgs,
857
1282
  accept,
858
1283
  fresh: opts?.fresh,
859
1284
  fallbackCharset: shape.charset,
1285
+ signal: opts?.signal,
860
1286
  });
861
1287
 
862
- // 7. Check HTTP status before attempting to parse the body.
1288
+ // 8. Check HTTP status before attempting to parse the body.
863
1289
  // This turns "Invalid JSON response: <?xml..." into a clean
864
1290
  // "Unexpected HTTP 400: El parámetro fecha..." message. Secret values are
865
1291
  // scrubbed from the error excerpt so an auth-echo body can't leak a key.
@@ -867,16 +1293,16 @@ export async function restGet(
867
1293
  // upstream of checkResponseStatus) so the secret never reaches the error.
868
1294
  checkResponseStatus({ ...result, url }, opts?.secretValues);
869
1295
 
870
- // 8. Parse response using the effective shape resolved above.
1296
+ // 9. Parse response using the effective shape resolved above.
871
1297
  let data = parseResponse(result.body, shape);
872
1298
 
873
- // 8b. 200-with-error-envelope check (op.errorPath) — post-parse,
1299
+ // 9b. 200-with-error-envelope check (op.errorPath) — post-parse,
874
1300
  // pre-transform: the error envelope is the raw parsed shape.
875
1301
  if (operation.errorPath !== undefined) {
876
1302
  checkErrorEnvelope(data, operation.errorPath, url, opts?.secretValues);
877
1303
  }
878
1304
 
879
- // 9. Post-response transform (optional). When api-fetch supplied a
1305
+ // 10. Post-response transform (optional). When api-fetch supplied a
880
1306
  // `transformFn` (op.transform === true), apply it. A throwing transform is
881
1307
  // caught: keep the raw `data` and carry a `transformWarning` so the caller
882
1308
  // can surface "⚠ Transform failed:" — the op is NOT disabled, so a
@@ -898,6 +1324,15 @@ export async function restGet(
898
1324
  headers: result.headers,
899
1325
  url,
900
1326
  params: query,
1327
+ ...(result.finalUrl === undefined
1328
+ ? {}
1329
+ : {
1330
+ finalUrl: redactSurfacedUrl(
1331
+ result.finalUrl,
1332
+ secretParamNames,
1333
+ pathValues,
1334
+ ),
1335
+ }),
901
1336
  ...(transformWarning === undefined ? {} : { transformWarning }),
902
1337
  ...(result.cached ? { cached: true } : {}),
903
1338
  };
@@ -920,6 +1355,9 @@ export interface PaginateOptions extends SecretAuthOpts {
920
1355
  transformFn?: TransformFn | undefined;
921
1356
  /** Guide directory name — transform context domain / helper routing. */
922
1357
  dirName?: string | undefined;
1358
+ /** Caller's abort signal (tool-call cancellation), honored by every
1359
+ * page fetch — a cancelled walk stops at the in-flight page. */
1360
+ signal?: AbortSignal | undefined;
923
1361
  }
924
1362
 
925
1363
  /**
@@ -1000,7 +1438,8 @@ export async function paginate(
1000
1438
  pagCfg.base ??
1001
1439
  operation.params[pagCfg.pageParam!]?.default ??
1002
1440
  fallback;
1003
- page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
1441
+ page =
1442
+ typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
1004
1443
  if (Number.isNaN(page)) page = fallback;
1005
1444
  }
1006
1445
 
@@ -1023,7 +1462,8 @@ export async function paginate(
1023
1462
  const rawSize =
1024
1463
  pagCfg.pageSizeParam === undefined
1025
1464
  ? undefined
1026
- : (params[pagCfg.pageSizeParam] ?? effectiveParams[pagCfg.pageSizeParam]);
1465
+ : (params[pagCfg.pageSizeParam] ??
1466
+ effectiveParams[pagCfg.pageSizeParam]);
1027
1467
  effectivePageSize =
1028
1468
  rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
1029
1469
  if (Number.isNaN(effectivePageSize)) effectivePageSize = 50;
@@ -1127,6 +1567,7 @@ export async function paginate(
1127
1567
  fresh: opts?.fresh,
1128
1568
  guardRedirects: guardThisFetch,
1129
1569
  fallbackCharset: shape.charset,
1570
+ signal: opts?.signal,
1130
1571
  });
1131
1572
 
1132
1573
  // Check HTTP status before attempting to parse. Secret values scrubbed