pi-lean-host 0.7.1 → 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.
@@ -369,7 +369,9 @@ export async function handleOauthSubcommand(
369
369
  );
370
370
  return;
371
371
  }
372
- const matches = allMatches.filter(({ guide }) => guide.auth.kind === "oauth2");
372
+ const matches = allMatches.filter(
373
+ ({ guide }) => guide.auth.kind === "oauth2",
374
+ );
373
375
  if (matches.length === 0) {
374
376
  ctx.ui.notify(
375
377
  `No OAuth2 guide for '${domain}' (${allMatches.length} guide(s) found, none with auth.kind: oauth2). ` +
@@ -442,7 +444,9 @@ export async function handleOauthSubcommand(
442
444
  await mintAuthCodeToken(auth, storeDomain, ctx, {
443
445
  ...(codeArg === undefined ? {} : { code: codeArg }),
444
446
  ...(refreshFlag ? { refresh: true } : {}),
445
- ...(redirectUriArg === undefined ? {} : { redirectUri: redirectUriArg }),
447
+ ...(redirectUriArg === undefined
448
+ ? {}
449
+ : { redirectUri: redirectUriArg }),
446
450
  });
447
451
  } else {
448
452
  // Cached token resolves as-is; the delete is conditional on --refresh
@@ -499,6 +503,7 @@ const INIT_FLAG_NAMES: readonly string[] = [
499
503
  "--scopes",
500
504
  "--token-endpoint-auth-method",
501
505
  "--redirect-uri",
506
+ "--authorize-params",
502
507
  "--code",
503
508
  ];
504
509
 
@@ -521,16 +526,43 @@ export function initFlagsFromFields(fields: SyntheticOAuth2Fields): string[] {
521
526
  ...(fields.tokenEndpointAuthMethod === undefined
522
527
  ? []
523
528
  : [`--token-endpoint-auth-method ${fields.tokenEndpointAuthMethod}`]),
529
+ ...(fields.authorizeParams === undefined
530
+ ? []
531
+ : [
532
+ `--authorize-params ${Object.entries(fields.authorizeParams)
533
+ .map(([k, v]) => `${k}=${v}`)
534
+ .join(",")}`,
535
+ ]),
524
536
  ];
525
537
  }
526
538
 
539
+ /**
540
+ * Parse the `--authorize-params` flag value — comma-separated `k=v` pairs —
541
+ * into the SyntheticOAuth2Fields record. Undefined on any malformed entry
542
+ * (missing `=`, empty key, empty value) so the caller can notify with usage
543
+ * instead of provisioning a half-specified flow.
544
+ */
545
+ export function parseAuthorizeParamsFlag(
546
+ raw: string,
547
+ ): Record<string, string> | undefined {
548
+ const out: Record<string, string> = {};
549
+ for (const pair of raw.split(",")) {
550
+ const eq = pair.indexOf("=");
551
+ if (eq <= 0) return undefined;
552
+ const key = pair.slice(0, eq).trim();
553
+ const value = pair.slice(eq + 1).trim();
554
+ if (!key || !value) return undefined;
555
+ out[key] = value;
556
+ }
557
+ return Object.keys(out).length > 0 ? out : undefined;
558
+ }
559
+
527
560
  /** Wizard picker option meaning "no client secret" (PKCE public client). */
528
561
  const OMIT_SECRET = "(omit — PKCE public client)";
529
562
 
530
563
  /**
531
564
  * `/api oauth init <domain>` — provision a token WITHOUT an oauth2 guide.
532
- * The interactive grant's bootstrap previously required authoring a
533
- * throwaway draft guide first; the wizard dissolves that asymmetry with
565
+ * The wizard provisions directly — no draft guide needed — using
534
566
  * client-credentials (which probe mint-on-demand already solved). The wizard collects flow facts (grant, tokenUrl, authorizeUrl,
535
567
  * store-NAME credentials) into a synthetic oauth2 auth and feeds the
536
568
  * EXISTING flow machinery (`mintAuthCodeToken` / `resolveAccessToken`) —
@@ -581,6 +613,18 @@ async function handleOauthInit(
581
613
  // not silently).
582
614
  const storeDomain = resolveProvisionedParentDomain(domain);
583
615
  const viaFlags = Object.keys(flags).length > 0;
616
+ const authorizeParamsRaw = flags["--authorize-params"];
617
+ const authorizeParams =
618
+ authorizeParamsRaw === undefined
619
+ ? undefined
620
+ : parseAuthorizeParamsFlag(authorizeParamsRaw);
621
+ if (authorizeParamsRaw !== undefined && authorizeParams === undefined) {
622
+ ctx.ui.notify(
623
+ `⚡ --authorize-params expects comma-separated k=v pairs (e.g. access_type=offline,prompt=consent).\n\n${INIT_USAGE}`,
624
+ "warning",
625
+ );
626
+ return;
627
+ }
584
628
 
585
629
  let fields: SyntheticOAuth2Fields;
586
630
  let wizardRedirectUri: string | undefined;
@@ -617,6 +661,7 @@ async function handleOauthInit(
617
661
  SyntheticOAuth2Fields["tokenEndpointAuthMethod"]
618
662
  >,
619
663
  }),
664
+ ...(authorizeParams === undefined ? {} : { authorizeParams }),
620
665
  };
621
666
  } else if (ctx.hasUI) {
622
667
  const gathered = await wizardFields(ctx, storeDomain);
@@ -673,7 +718,10 @@ async function handleOauthInit(
673
718
  synthetic.grant !== "authorization_code" &&
674
719
  (codeArg !== undefined || flags["--redirect-uri"] !== undefined)
675
720
  ) {
676
- ctx.ui.notify(authCodeOnlyFlagsNote(storeDomain, synthetic.grant), "warning");
721
+ ctx.ui.notify(
722
+ authCodeOnlyFlagsNote(storeDomain, synthetic.grant),
723
+ "warning",
724
+ );
677
725
  return;
678
726
  }
679
727
 
@@ -750,7 +798,8 @@ const GRANT_ITEMS: SelectItem[] = [
750
798
  {
751
799
  value: "client_credentials",
752
800
  label: "client_credentials",
753
- description: "Server-to-server — no browser; one POST to the token endpoint.",
801
+ description:
802
+ "Server-to-server — no browser; one POST to the token endpoint.",
754
803
  },
755
804
  {
756
805
  value: "authorization_code",
@@ -898,6 +947,27 @@ async function wizardFields(
898
947
  .split(",")
899
948
  .map((s) => s.trim())
900
949
  .filter(Boolean);
950
+ // Extra authorize-URL parameters (refresh-token availability — e.g. Google's
951
+ // access_type=offline + prompt=consent). Empty skips; malformed notifies.
952
+ const authorizeParamsRaw = await ctx.ui.input(
953
+ `Authorize-URL parameters for '${storeDomain}' (comma-separated k=v)`,
954
+ "e.g. access_type=offline,prompt=consent — empty to skip",
955
+ );
956
+ if (authorizeParamsRaw === undefined) {
957
+ cancelled();
958
+ return undefined;
959
+ }
960
+ const authorizeParams =
961
+ authorizeParamsRaw.trim() === ""
962
+ ? undefined
963
+ : parseAuthorizeParamsFlag(authorizeParamsRaw);
964
+ if (authorizeParamsRaw.trim() !== "" && authorizeParams === undefined) {
965
+ ctx.ui.notify(
966
+ "⚡ Authorize-URL parameters expect comma-separated k=v pairs (e.g. access_type=offline,prompt=consent).",
967
+ "warning",
968
+ );
969
+ return undefined;
970
+ }
901
971
  return {
902
972
  fields: {
903
973
  grant: grant as SyntheticOAuth2Fields["grant"],
@@ -906,6 +976,7 @@ async function wizardFields(
906
976
  ...(clientSecret === OMIT_SECRET ? {} : { clientSecret: clientSecret! }),
907
977
  authorizeUrl,
908
978
  ...(scopes.length > 0 ? { scopes } : {}),
979
+ ...(authorizeParams === undefined ? {} : { authorizeParams }),
909
980
  tokenEndpointAuthMethod,
910
981
  },
911
982
  ...(redirectUri === undefined ? {} : { redirectUri }),
@@ -20,7 +20,11 @@
20
20
  import { createHash, randomBytes } from "node:crypto";
21
21
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
22
  import { getCapabilities, hyperlink } from "@earendil-works/pi-tui";
23
- import type { OAuth2Auth } from "./api-guide-types.js";
23
+ import {
24
+ type OAuth2Auth,
25
+ authorizeParamsBuiltInCollision,
26
+ OAUTH2_AUTHORIZE_URL_BUILTINS,
27
+ } from "./api-guide-types.js";
24
28
  import {
25
29
  exchangeAuthCode,
26
30
  forceRefreshToken,
@@ -98,6 +102,22 @@ export function buildAuthorizeUrl(
98
102
  url.searchParams.set("state", state);
99
103
  url.searchParams.set("code_challenge", challenge);
100
104
  url.searchParams.set("code_challenge_method", "S256");
105
+ // Guide-declared extras spread AFTER the built-ins — a built-in-colliding
106
+ // key is rejected first, so the spread can never silently override a
107
+ // security-bearing built-in. This is the one site every mint path passes
108
+ // through, so the collision check covers all of them at mint time.
109
+ if (auth.authorizeParams !== undefined) {
110
+ const collision = authorizeParamsBuiltInCollision(auth.authorizeParams);
111
+ if (collision !== null) {
112
+ throw new Error(
113
+ `authorizeParams key '${collision}' collides with a built-in authorize URL parameter ` +
114
+ `(${OAUTH2_AUTHORIZE_URL_BUILTINS.join(", ")}) — remove it; the flow sets that value itself.`,
115
+ );
116
+ }
117
+ for (const [key, value] of Object.entries(auth.authorizeParams)) {
118
+ url.searchParams.set(key, value);
119
+ }
120
+ }
101
121
  return url.toString();
102
122
  }
103
123
 
@@ -251,26 +271,19 @@ export async function mintAuthCodeToken(
251
271
  }
252
272
 
253
273
  /**
254
- * The authorize URL as the user should see it. With OSC 8 support the visible
255
- * text is just origin + path (always fits one line — no wrapping, so no
256
- * space-inserted copies and no link split across lines); the hyperlink
257
- * target carries the FULL URL, so click / copy-link always gets the intact
258
- * authorize URL including the query string. Without OSC 8 the visible text
259
- * is all the user gets, so print the full URL — plus a wrap warning, since
260
- * the long query string will wrap and terminal copy inserts spaces at the
261
- * breaks.
274
+ * The authorize URL as the user should see it. The visible text is always
275
+ * the FULL URL — some terminals (e.g. kitty with mouse click-to-open) can
276
+ * corrupt or hijack the hyperlink target, and not every terminal exposes a
277
+ * copy-link action, so the plain text must carry everything. When OSC 8 is
278
+ * supported the same text is wrapped in a hyperlink targeting itself, as a
279
+ * bonus click-to-open for terminals that behave. The URL is long enough to
280
+ * wrap in narrow terminals, so keep the wrap warning.
262
281
  */
263
282
  function printableAuthorizeUrl(url: string): string {
264
- if (getCapabilities().hyperlinks) {
265
- try {
266
- const u = new URL(url);
267
- return hyperlink(`\x1b[1m${u.origin}${u.pathname}\x1b[22m`, url);
268
- } catch {
269
- // unreachable — buildAuthorizeUrl already validated the URL
270
- }
271
- }
283
+ const text = `\x1b[1m${url}\x1b[22m`;
284
+ const link = getCapabilities().hyperlinks ? hyperlink(text, url) : text;
272
285
  return (
273
- `\x1b[1m${url}\x1b[22m` +
286
+ link +
274
287
  `\n(if the URL wraps across lines, remove the extra spaces at each line break after copying)`
275
288
  );
276
289
  }
@@ -41,6 +41,8 @@ import {
41
41
  isOAuth2TokenEndpointAuthMethod,
42
42
  isListStyle,
43
43
  LIST_STYLES,
44
+ authorizeParamsBuiltInCollision,
45
+ OAUTH2_AUTHORIZE_URL_BUILTINS,
44
46
  oauth2GrantIssue,
45
47
  OAUTH2_GRANTS,
46
48
  OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
@@ -147,6 +149,7 @@ export const AUTH_ALLOWLISTS: Record<AuthKind, ReadonlySet<string>> = {
147
149
  "paramStyle",
148
150
  "tokenEndpointAuthMethod",
149
151
  "authorizeUrl",
152
+ "authorizeParams",
150
153
  "revokeUrl",
151
154
  ]),
152
155
  };
@@ -237,6 +240,7 @@ export const OP_ALLOWLIST: ReadonlySet<string> = new Set([
237
240
  "passthrough",
238
241
  "parse",
239
242
  "errorPath",
243
+ "download",
240
244
  "pagination",
241
245
  "gatherAllMax",
242
246
  ]);
@@ -436,14 +440,22 @@ function requireHttpUrl(
436
440
  try {
437
441
  const u = new URL(value);
438
442
  if (u.protocol !== "http:" && u.protocol !== "https:") {
439
- return fail(file, key, "an http or https URL", `protocol "${u.protocol}"`, {
440
- ...(opts?.protocolFix ? { fix: opts.protocolFix } : {}),
441
- });
443
+ return fail(
444
+ file,
445
+ key,
446
+ "an http or https URL",
447
+ `protocol "${u.protocol}"`,
448
+ opts?.protocolFix === undefined ? {} : { fix: opts.protocolFix },
449
+ );
442
450
  }
443
451
  } catch {
444
- return fail(file, key, "a valid http/https URL", `"${value}"`, {
445
- ...(opts?.invalidFix ? { fix: opts.invalidFix } : {}),
446
- });
452
+ return fail(
453
+ file,
454
+ key,
455
+ "a valid http/https URL",
456
+ `"${value}"`,
457
+ opts?.invalidFix === undefined ? {} : { fix: opts.invalidFix },
458
+ );
447
459
  }
448
460
  return value;
449
461
  }
@@ -457,9 +469,13 @@ function requireStringArray(
457
469
  ): string[] | ParseApiGuideResult {
458
470
  const v = m[key];
459
471
  if (v === undefined) {
460
- return fail(file, key, "a list of strings", "missing", {
461
- ...(opts?.missingFix ? { fix: opts.missingFix } : {}),
462
- });
472
+ return fail(
473
+ file,
474
+ key,
475
+ "a list of strings",
476
+ "missing",
477
+ opts?.missingFix === undefined ? {} : { fix: opts.missingFix },
478
+ );
463
479
  }
464
480
  if (!Array.isArray(v) || v.length === 0) {
465
481
  return fail(file, key, "a non-empty list of strings", describeFound(v), {
@@ -823,9 +839,15 @@ function validateAuth(
823
839
  return { kind: "none" };
824
840
  }
825
841
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
826
- return fail(file, "auth", "a YAML mapping (kind: ...)", describeFound(raw), {
827
- snippet: snippetFor(fm, "auth"),
828
- });
842
+ return fail(
843
+ file,
844
+ "auth",
845
+ "a YAML mapping (kind: ...)",
846
+ describeFound(raw),
847
+ {
848
+ snippet: snippetFor(fm, "auth"),
849
+ },
850
+ );
829
851
  }
830
852
  const a = raw as Record<string, unknown>;
831
853
  const kindRaw = a["kind"];
@@ -1146,7 +1168,12 @@ function validateOAuth2Auth(
1146
1168
  },
1147
1169
  );
1148
1170
  }
1149
- const clientId = parseSecretRefValue(a["clientId"], file, fm, "auth.clientId");
1171
+ const clientId = parseSecretRefValue(
1172
+ a["clientId"],
1173
+ file,
1174
+ fm,
1175
+ "auth.clientId",
1176
+ );
1150
1177
  if (isParseErr(clientId)) return clientId;
1151
1178
  if (clientId.prefix !== undefined || clientId.optional !== undefined) {
1152
1179
  return fail(
@@ -1250,6 +1277,40 @@ function validateOAuth2Auth(
1250
1277
  if (typeof au !== "string") return au;
1251
1278
  authorizeUrl = au;
1252
1279
  }
1280
+ let authorizeParams: Record<string, string> | undefined;
1281
+ if (a["authorizeParams"] !== undefined) {
1282
+ const raw = a["authorizeParams"];
1283
+ if (
1284
+ typeof raw !== "object" ||
1285
+ raw === null ||
1286
+ Array.isArray(raw) ||
1287
+ !Object.values(raw).every((v) => typeof v === "string")
1288
+ ) {
1289
+ return fail(
1290
+ file,
1291
+ "auth.authorizeParams",
1292
+ "a map of string → string (extra authorize-URL query parameters)",
1293
+ describeFound(raw),
1294
+ { snippet: snippetFor(fm, "auth") },
1295
+ );
1296
+ }
1297
+ authorizeParams = raw as Record<string, string>;
1298
+ // Built-in collision — the shared predicate (same one buildAuthorizeUrl
1299
+ // calls at mint time), so a colliding guide fails at parse/save rather
1300
+ // than at first mint.
1301
+ const collision = authorizeParamsBuiltInCollision(authorizeParams);
1302
+ if (collision !== null) {
1303
+ return fail(
1304
+ file,
1305
+ "auth.authorizeParams",
1306
+ `a key outside the built-in authorize-URL parameters (${OAUTH2_AUTHORIZE_URL_BUILTINS.join(", ")})`,
1307
+ `"${collision}" collides with a built-in`,
1308
+ {
1309
+ fix: `Remove authorizeParams.${collision} — the flow sets that built-in itself.`,
1310
+ },
1311
+ );
1312
+ }
1313
+ }
1253
1314
  let revokeUrl: string | undefined;
1254
1315
  if (a["revokeUrl"] !== undefined) {
1255
1316
  const rv = requireHttpUrl(a["revokeUrl"], "auth.revokeUrl", file, fm);
@@ -1266,6 +1327,7 @@ function validateOAuth2Auth(
1266
1327
  hasClientSecret: clientSecret !== undefined,
1267
1328
  authorizeUrl,
1268
1329
  tokenEndpointAuthMethod,
1330
+ authorizeParams,
1269
1331
  });
1270
1332
  if (issue) {
1271
1333
  switch (issue.code) {
@@ -1311,12 +1373,24 @@ function validateOAuth2Auth(
1311
1373
  fix: "Add authorizeUrl — the provider's authorization endpoint. The redirect URI is the runtime convention http://127.0.0.1/callback (RFC 8252 §7.3); register it on your OAuth app.",
1312
1374
  },
1313
1375
  );
1376
+ case "authorizeParamsOnCc":
1377
+ return fail(
1378
+ file,
1379
+ "auth.authorizeParams",
1380
+ "absent for grant: client_credentials (no authorize URL exists to carry them)",
1381
+ "authorizeParams present",
1382
+ {
1383
+ fix: "Remove authorizeParams — it is authorization_code-only (it customizes the consent-page URL).",
1384
+ },
1385
+ );
1314
1386
  default: {
1315
1387
  // Compile-time exhaustiveness tripwire: a new OAuth2GrantIssue
1316
1388
  // code must extend this switch (the builder's message map is
1317
1389
  // already forced via its return type). Unreachable at runtime.
1318
1390
  const uncovered: never = issue.code;
1319
- throw new Error(`unhandled OAuth2 grant invariant: ${String(uncovered)}`);
1391
+ throw new Error(
1392
+ `unhandled OAuth2 grant invariant: ${String(uncovered)}`,
1393
+ );
1320
1394
  }
1321
1395
  }
1322
1396
  }
@@ -1334,6 +1408,7 @@ function validateOAuth2Auth(
1334
1408
  if (tokenEndpointAuthMethod !== undefined)
1335
1409
  result.tokenEndpointAuthMethod = tokenEndpointAuthMethod;
1336
1410
  if (authorizeUrl !== undefined) result.authorizeUrl = authorizeUrl;
1411
+ if (authorizeParams !== undefined) result.authorizeParams = authorizeParams;
1337
1412
  if (revokeUrl !== undefined) result.revokeUrl = revokeUrl;
1338
1413
  return result;
1339
1414
  }
@@ -1424,9 +1499,31 @@ function validateOperation(
1424
1499
  }
1425
1500
  const pathParams = extractPathTokens(path);
1426
1501
 
1427
- // accept — any media-type string, default "json"
1502
+ // download — declares "this op returns a byte stream, not data." Read
1503
+ // BEFORE the accept default site: the substitution below keys on
1504
+ // acceptRaw === undefined, a distinction that dies once the default is
1505
+ // applied (Operation.accept is a required field, so the executor cannot
1506
+ // tell an omitted accept from an explicit "json").
1507
+ const downloadRaw = o["download"];
1508
+ let download: boolean | undefined;
1509
+ if (downloadRaw !== undefined) {
1510
+ if (typeof downloadRaw !== "boolean") {
1511
+ return fail(
1512
+ file,
1513
+ fieldPath("download"),
1514
+ "true or omitted",
1515
+ describeFound(downloadRaw),
1516
+ );
1517
+ }
1518
+ download = downloadRaw;
1519
+ }
1520
+
1521
+ // accept — any media-type string, default "json".
1522
+ // A download op with no authored accept gets "*/*" instead of the "json"
1523
+ // default: application/json on a binary endpoint can 406, and an
1524
+ // explicit accept (including json, including */*) is honored verbatim.
1428
1525
  const acceptRaw = o["accept"];
1429
- let accept: AcceptType = "json";
1526
+ let accept: AcceptType = download === true ? "*/*" : "json";
1430
1527
  if (acceptRaw !== undefined) {
1431
1528
  if (typeof acceptRaw !== "string") {
1432
1529
  return fail(
@@ -1478,7 +1575,8 @@ function validateOperation(
1478
1575
  );
1479
1576
  }
1480
1577
  const s = spec as Record<string, unknown>;
1481
- const onlyDescription = Object.keys(s).length === 1 && "description" in s;
1578
+ const onlyDescription =
1579
+ Object.keys(s).length === 1 && "description" in s;
1482
1580
  if (!onlyDescription) {
1483
1581
  return fail(
1484
1582
  file,
@@ -1877,7 +1975,11 @@ function validateOperation(
1877
1975
  const opPaginationRaw = o["pagination"];
1878
1976
  let opPagination: PaginationConfig | undefined;
1879
1977
  if (opPaginationRaw !== undefined) {
1880
- const pr = validatePagination(opPaginationRaw, fieldPath("pagination"), file);
1978
+ const pr = validatePagination(
1979
+ opPaginationRaw,
1980
+ fieldPath("pagination"),
1981
+ file,
1982
+ );
1881
1983
  if (!("style" in pr && typeof pr.style === "string")) {
1882
1984
  return pr as ParseApiGuideResult;
1883
1985
  }
@@ -2008,6 +2110,83 @@ function validateOperation(
2008
2110
  opGatherAllMax = opGatherAllMaxRaw;
2009
2111
  }
2010
2112
 
2113
+ // download-class shape rules — fail-fast, closed-schema style. The
2114
+ // download executor skips parse/errorPath/transform by declaration, so
2115
+ // declaring them together is a contradiction; a pagination block and
2116
+ // gatherAllMax are paginate machinery with no walk to configure here
2117
+ // (gatherAllMax is parser-read for any op today, so it is equally dead).
2118
+ // Tolerance for these keys on plain restGet ops is deliberate — do not
2119
+ // extend this refusal to them.
2120
+ if (download === true) {
2121
+ if (via !== "restGet") {
2122
+ return fail(
2123
+ file,
2124
+ fieldPath("download"),
2125
+ "a restGet op (a paginate walk has no single body to save)",
2126
+ `via: ${via}`,
2127
+ {
2128
+ fix: `Set via: restGet on operations[${index}] — download is legal only on a single-request op.`,
2129
+ },
2130
+ );
2131
+ }
2132
+ const downloadExclusions: Array<
2133
+ [
2134
+ key: string,
2135
+ present: boolean,
2136
+ reason: string,
2137
+ found: string,
2138
+ fix: string,
2139
+ ]
2140
+ > = [
2141
+ [
2142
+ "parse",
2143
+ parseOverride !== undefined,
2144
+ "the download executor skips parse by declaration",
2145
+ "parse override present",
2146
+ "a download op has no parsed response shape.",
2147
+ ],
2148
+ [
2149
+ "transform",
2150
+ transform === true,
2151
+ "the download executor skips transform by declaration",
2152
+ "transform: true",
2153
+ "there is no parsed data for a transform to run on.",
2154
+ ],
2155
+ [
2156
+ "errorPath",
2157
+ errorPath !== undefined,
2158
+ "the download executor skips errorPath by declaration",
2159
+ "errorPath present",
2160
+ "a download op never parses an error envelope.",
2161
+ ],
2162
+ [
2163
+ "pagination",
2164
+ opPagination !== undefined,
2165
+ "no paginate walk exists to configure",
2166
+ "an op-level pagination block",
2167
+ "a download op is never walked.",
2168
+ ],
2169
+ [
2170
+ "gatherAllMax",
2171
+ opGatherAllMax !== undefined,
2172
+ "gatherAll is paginate machinery — nothing here gathers",
2173
+ "gatherAllMax present",
2174
+ "a download op has no walk to cap.",
2175
+ ],
2176
+ ];
2177
+ for (const [key, present, reason, found, fix] of downloadExclusions) {
2178
+ if (present) {
2179
+ return fail(
2180
+ file,
2181
+ fieldPath(key),
2182
+ `absent on a download: true op (${reason})`,
2183
+ found,
2184
+ { fix: `Remove operations[${index}].${key} — ${fix}` },
2185
+ );
2186
+ }
2187
+ }
2188
+ }
2189
+
2011
2190
  const operation: Operation = {
2012
2191
  name,
2013
2192
  via,
@@ -2023,6 +2202,7 @@ function validateOperation(
2023
2202
  ...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
2024
2203
  ...(parseOverride ? { parse: parseOverride } : {}),
2025
2204
  ...(errorPath === undefined ? {} : { errorPath }),
2205
+ ...(download === undefined ? {} : { download }),
2026
2206
  ...(opPagination ? { pagination: opPagination } : {}),
2027
2207
  ...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
2028
2208
  };
@@ -37,7 +37,12 @@ import {
37
37
  canonicalStoreDomain,
38
38
  OAuthTokenMissingError,
39
39
  } from "./auth.js";
40
- import type { ApiGuide, ExecutorVia, Operation } from "./api-guide-types.js";
40
+ import {
41
+ isDownloadClass,
42
+ type ApiGuide,
43
+ type ExecutorVia,
44
+ type Operation,
45
+ } from "./api-guide-types.js";
41
46
 
42
47
  // ═══════════════════════════════════════════════════════════════════
43
48
  // Types
@@ -55,6 +60,19 @@ export interface ResolveOpOptions {
55
60
  fresh?: boolean;
56
61
  /** paginate: bypass the nextLink SSRF guard (test hook only). */
57
62
  skipSsrfGuard?: boolean;
63
+ /** Caller's abort signal (tool-call cancellation), threaded to the
64
+ * executors' fetches — a cancelled call aborts the in-flight request
65
+ * instead of waiting out its timeout. */
66
+ signal?: AbortSignal | undefined;
67
+ /** Destination for a download-class call (a `download: true` op, or any
68
+ * op called with saveTo — explicit caller intent wins). Forwarded to
69
+ * the executor; a paginate op with saveTo is rejected at the tool
70
+ * layer (a walk has no single body to save). */
71
+ saveTo?: string | undefined;
72
+ /** Byte-budget stop bound for the /api verify download probe — the
73
+ * counting Transform stops cleanly at the budget instead of consulting
74
+ * the cap. Executor input, not schema. */
75
+ byteBudget?: number | undefined;
58
76
  }
59
77
 
60
78
  /** Store-injected auth opts, forwarded to the executor and reused by the
@@ -122,9 +140,17 @@ export async function resolveOpForExecution(
122
140
  // skip, not a failure — the op is unverifiable this session, not broken.
123
141
  let executeParams = userParams;
124
142
  if (op.helper === true) {
125
- const helperResult = await callHelper(helperDirName, op.name, executeParams);
143
+ const helperResult = await callHelper(
144
+ helperDirName,
145
+ op.name,
146
+ executeParams,
147
+ );
126
148
  if (!helperResult.ok) {
127
- return { ok: false, reason: "helper_disabled", message: helperResult.error };
149
+ return {
150
+ ok: false,
151
+ reason: "helper_disabled",
152
+ message: helperResult.error,
153
+ };
128
154
  }
129
155
  executeParams = helperResult.params;
130
156
  }
@@ -132,9 +158,17 @@ export async function resolveOpForExecution(
132
158
  // 2. Post-response transform (op.transform === true). Loaded once before
133
159
  // dispatch; the executor owns the invocation + its try/catch (a throw
134
160
  // never escapes — it surfaces as a non-blocking transformWarning).
161
+ // Skipped on a download-class call: the download arm skips the
162
+ // transform by declaration (isDownloadClass) — loading it would only
163
+ // produce the no-helper warning for a transform that will never run.
164
+ // The local PRE-call helper (step 1) still runs: it builds the params
165
+ // the download URL needs.
166
+ const downloadClass = isDownloadClass(op, opts?.saveTo);
135
167
  const transformFn =
136
- op.transform === true ? await loadTransform(helperDirName) : null;
137
- if (op.transform === true && transformFn === null) {
168
+ op.transform === true && !downloadClass
169
+ ? await loadTransform(helperDirName)
170
+ : null;
171
+ if (op.transform === true && transformFn === null && !downloadClass) {
138
172
  console.warn(
139
173
  `⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
140
174
  );
@@ -153,7 +187,11 @@ export async function resolveOpForExecution(
153
187
  const headerRes = resolveSecretHeaders(guide.auth, storeDomain);
154
188
  const queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
155
189
  const pathRes = resolveSecretPathParams(guide.auth, storeDomain);
156
- const missingRequired = missingRequiredSecrets(headerRes, queryRes, pathRes);
190
+ const missingRequired = missingRequiredSecrets(
191
+ headerRes,
192
+ queryRes,
193
+ pathRes,
194
+ );
157
195
  if (missingRequired.length > 0) {
158
196
  return {
159
197
  ok: false,
@@ -228,6 +266,11 @@ export async function resolveOpForExecution(
228
266
  transformFn: transformFn ?? undefined,
229
267
  dirName: helperDirName,
230
268
  ...(opts?.fresh === undefined ? {} : { fresh: opts.fresh }),
269
+ ...(opts?.signal === undefined ? {} : { signal: opts.signal }),
270
+ ...(opts?.saveTo === undefined ? {} : { saveTo: opts.saveTo }),
271
+ ...(opts?.byteBudget === undefined
272
+ ? {}
273
+ : { byteBudget: opts.byteBudget }),
231
274
  });
232
275
  return {
233
276
  ok: true,
@@ -244,6 +287,7 @@ export async function resolveOpForExecution(
244
287
  ...(opts?.skipSsrfGuard ? { skipSsrfGuard: true } : {}),
245
288
  ...(opts?.gatherAll === undefined ? {} : { gatherAll: opts.gatherAll }),
246
289
  ...(opts?.fresh === undefined ? {} : { fresh: opts.fresh }),
290
+ ...(opts?.signal === undefined ? {} : { signal: opts.signal }),
247
291
  transformFn: transformFn ?? undefined,
248
292
  dirName: helperDirName,
249
293
  };
@@ -119,7 +119,10 @@ export function spillResponse(
119
119
  // Evict oldest if over limit
120
120
  if (entries.length > MAX_FILES_PER_SESSION) {
121
121
  entries.sort((a, b) => a.timestamp - b.timestamp);
122
- const toRemove = entries.splice(0, entries.length - MAX_FILES_PER_SESSION);
122
+ const toRemove = entries.splice(
123
+ 0,
124
+ entries.length - MAX_FILES_PER_SESSION,
125
+ );
123
126
  for (const entry of toRemove) {
124
127
  try {
125
128
  rmSync(entry.path, { force: true });
@@ -143,5 +143,7 @@ export function listNames(domain: string): string[] {
143
143
  */
144
144
  export function provisionedDomainsSuffix(domain: string): string {
145
145
  const others = listDomains().filter((d) => d !== domain);
146
- return others.length > 0 ? ` — provisioned domains: ${others.join(", ")}` : "";
146
+ return others.length > 0
147
+ ? ` — provisioned domains: ${others.join(", ")}`
148
+ : "";
147
149
  }