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.
@@ -34,7 +34,14 @@
34
34
  */
35
35
 
36
36
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
37
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
37
+ import {
38
+ existsSync,
39
+ mkdtempSync,
40
+ readFileSync,
41
+ rmSync,
42
+ writeFileSync,
43
+ } from "node:fs";
44
+ import { tmpdir } from "node:os";
38
45
  import { join } from "node:path";
39
46
  import {
40
47
  findGuidesByDomain,
@@ -61,6 +68,13 @@ import {
61
68
  } from "./helpers.js";
62
69
  import type { Operation } from "./api-guide-types.js";
63
70
 
71
+ /** Byte-budget for the download probe: a `download: true` op verifies by
72
+ * streaming a bounded prefix to a temp file — a pass proves the endpoint
73
+ * serves bytes, never a full multi-GB transfer (and a budgeted run skips
74
+ * the Content-Length preflight, so a target bigger than free disk space
75
+ * still verifies). */
76
+ const VERIFY_DOWNLOAD_BUDGET = 1024 * 1024;
77
+
64
78
  /** Usage + cost note, surfaced by `--help`. */
65
79
  function helpText(): string {
66
80
  return [
@@ -157,7 +171,11 @@ export async function handleVerifySubcommand(
157
171
  const headerRes = resolveSecretHeaders(guide.auth, storeDomain);
158
172
  const queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
159
173
  const pathRes = resolveSecretPathParams(guide.auth, storeDomain);
160
- const missingRequired = missingRequiredSecrets(headerRes, queryRes, pathRes);
174
+ const missingRequired = missingRequiredSecrets(
175
+ headerRes,
176
+ queryRes,
177
+ pathRes,
178
+ );
161
179
  if (missingRequired.length > 0) {
162
180
  ctx.ui.notify(
163
181
  `šŸ”‘ ${guide.shortName} requires a secret not yet provisioned: ` +
@@ -260,56 +278,94 @@ export async function handleVerifySubcommand(
260
278
  : [{ params: supplied, tag: undefined }];
261
279
 
262
280
  for (const run of runs) {
263
- let outcome: ResolveOpResult;
281
+ // Download probe: a `download: true` op verifies by writing a
282
+ // budget-bounded prefix to a temp file — bytes recorded as pass
283
+ // evidence, deleted in a finally (a mid-probe failure leaves
284
+ // nothing behind; the executor's own temp is cleaned on any
285
+ // pre-rename failure). No full transfer regardless of file size.
286
+ const isDownload = op.download === true;
287
+ let downloadTemp: string | undefined;
288
+ if (isDownload) {
289
+ // Per-run scratch dir: the probe temp and its rename target must
290
+ // not collide across concurrent verifies of the same op name —
291
+ // two sessions, or the same op name in two guides.
292
+ downloadTemp = mkdtempSync(join(tmpdir(), "pi-lean-host-verify-"));
293
+ }
264
294
  try {
265
- outcome = await resolveOpForExecution(guide, op, dirName, {
266
- userParams: run.params,
267
- // Verify's whole point is a live check — never validate against
268
- // a cached body. Auth-bearing ops never touch the cache anyway;
269
- // this is belt-and-braces for no-auth guides.
270
- fresh: true,
271
- });
272
- } catch (err) {
273
- failed++;
274
- const msg =
275
- err instanceof HelperError
276
- ? err.message
277
- : err instanceof Error
295
+ let outcome: ResolveOpResult;
296
+ try {
297
+ outcome = await resolveOpForExecution(guide, op, dirName, {
298
+ userParams: run.params,
299
+ // Verify's whole point is a live check — never validate against
300
+ // a cached body. Auth-bearing ops never touch the cache anyway;
301
+ // this is belt-and-braces for no-auth guides.
302
+ fresh: true,
303
+ ...(downloadTemp === undefined
304
+ ? {}
305
+ : {
306
+ saveTo: join(downloadTemp, "probe.bin"),
307
+ byteBudget: VERIFY_DOWNLOAD_BUDGET,
308
+ }),
309
+ });
310
+ } catch (err) {
311
+ failed++;
312
+ const msg =
313
+ err instanceof HelperError
278
314
  ? err.message
279
- : String(err);
280
- report.push(` āœ— ${opTag(op.name, run.tag)} — ${msg}`);
281
- continue;
282
- }
315
+ : String(err instanceof Error ? err.message : err);
316
+ report.push(` āœ— ${opTag(op.name, run.tag)} — ${msg}`);
317
+ continue;
318
+ }
283
319
 
284
- if (!outcome.ok) {
285
- if (outcome.reason === "helper_disabled") {
286
- // Session-persistent condition — unverifiable this session, not broken.
287
- skipped++;
320
+ if (!outcome.ok) {
321
+ if (outcome.reason === "helper_disabled") {
322
+ // Session-persistent condition — unverifiable this session, not broken.
323
+ skipped++;
324
+ report.push(
325
+ ` ā­ ${opTag(op.name, run.tag)} — skipped: local helper disabled this session (${outcome.message})`,
326
+ );
327
+ // Disabled helpers are session-persistent and deterministic — the
328
+ // remaining fan-out runs would skip identically, so stop here.
329
+ break;
330
+ }
331
+ if (outcome.reason === "oauth_token_missing") {
332
+ // Unmintable OAuth2 token — same nudge for every op, so fail once
333
+ // (the auth precheck will fail-fast before the loop).
334
+ failed++;
335
+ report.push(` āœ— ${opTag(op.name, run.tag)} — ${outcome.message}`);
336
+ continue;
337
+ }
338
+ // auth_required_not_provisioned — unreachable after the precheck
339
+ // (auth is per-guide constant); defensive.
340
+ failed++;
288
341
  report.push(
289
- ` ā­ ${opTag(op.name, run.tag)} — skipped: local helper disabled this session (${outcome.message})`,
342
+ ` āœ— ${opTag(op.name, run.tag)} — requires secret not provisioned: ${outcome.missing.join(", ")}`,
290
343
  );
291
- // Disabled helpers are session-persistent and deterministic — the
292
- // remaining fan-out runs would skip identically, so stop here.
293
- break;
294
- }
295
- if (outcome.reason === "oauth_token_missing") {
296
- // Unmintable OAuth2 token — same nudge for every op, so fail once
297
- // (the auth precheck will fail-fast before the loop).
298
- failed++;
299
- report.push(` āœ— ${opTag(op.name, run.tag)} — ${outcome.message}`);
300
344
  continue;
301
345
  }
302
- // auth_required_not_provisioned — unreachable after the precheck
303
- // (auth is per-guide constant); defensive.
304
- failed++;
305
- report.push(
306
- ` āœ— ${opTag(op.name, run.tag)} — requires secret not provisioned: ${outcome.missing.join(", ")}`,
307
- );
308
- continue;
309
- }
310
346
 
311
- ran++;
312
- report.push(opLine(outcome, op, run.tag));
347
+ // Download pass rule: bytes > 0 on a 2xx = pass (a budget-reached
348
+ // stop is pass evidence by construction); a 0-byte 2xx = failure
349
+ // naming the empty body. A stream that ended before the budget
350
+ // records its real count — same rule, smaller number.
351
+ if (isDownload) {
352
+ const r = outcome.result as RestGetResult;
353
+ if (!r.file || r.file.bytes === 0) {
354
+ failed++;
355
+ report.push(
356
+ ` āœ— ${opTag(op.name, run.tag)} — 0-byte 2xx body (empty download)`,
357
+ );
358
+ continue;
359
+ }
360
+ }
361
+
362
+ ran++;
363
+ report.push(opLine(outcome, op, run.tag));
364
+ } finally {
365
+ if (downloadTemp !== undefined) {
366
+ rmSync(downloadTemp, { recursive: true, force: true });
367
+ }
368
+ }
313
369
  }
314
370
  }
315
371
 
@@ -415,28 +471,16 @@ export function unsatisfiable(
415
471
 
416
472
  /** Render unsatisfiable entries exactly as the verify report shows them. */
417
473
  function renderForReport(items: Unsatisfiable[]): string[] {
418
- return items.map((item) => {
419
- switch (item.kind) {
420
- case "group":
421
- return `one of: ${item.members.join(", ")}`;
422
- case "path":
423
- case "query":
424
- return item.param;
425
- }
426
- });
474
+ return items.map((item) =>
475
+ item.kind === "group" ? `one of: ${item.members.join(", ")}` : item.param,
476
+ );
427
477
  }
428
478
 
429
479
  /** Render unsatisfiable entries as one sentinel key per param. */
430
480
  export function renderForSentinels(items: Unsatisfiable[]): string[] {
431
- return items.flatMap((item) => {
432
- switch (item.kind) {
433
- case "group":
434
- return item.members;
435
- case "path":
436
- case "query":
437
- return [item.param];
438
- }
439
- });
481
+ return items.flatMap((item) =>
482
+ item.kind === "group" ? item.members : [item.param],
483
+ );
440
484
  }
441
485
 
442
486
  /** Load the co-located verify.json sidecar, best-effort. */
@@ -478,6 +522,17 @@ function opLine(
478
522
  r.transformWarning === undefined
479
523
  ? ""
480
524
  : ` — transform warning: ${r.transformWarning}`;
525
+ // A download op's pass evidence is the observed byte count (a
526
+ // budget-bounded probe wrote them to a since-deleted temp).
527
+ if (r.file) {
528
+ // Hitting the budget exactly means the probe was truncated there —
529
+ // the real file may be larger.
530
+ const size =
531
+ r.file.bytes === VERIFY_DOWNLOAD_BUDGET
532
+ ? `≄ ${r.file.bytes.toLocaleString("en-US")} bytes (probe budget)`
533
+ : `${r.file.bytes.toLocaleString("en-US")} bytes`;
534
+ return ` āœ“ ${name} — ${size} (restGet)${warn}`;
535
+ }
481
536
  return ` āœ“ ${name} — ${op.path} (restGet)${warn}`;
482
537
  }
483
538
  const r = outcome.result as PaginateResult;
@@ -1,7 +1,7 @@
1
1
  # Migrating guides to schema v1
2
2
 
3
- > Fix for guides rejected with `schemaVersion: 0` (or no `schemaVersion`
4
- > line). One breaking change: static-key auth went flat → nested.
3
+ > Fix for guides rejected with `schemaVersion: 0` (or no `schemaVersion` line).
4
+ > One breaking change: static-key auth went flat → nested.
5
5
 
6
6
  ## Before (v0) → After (v1)
7
7
 
@@ -9,10 +9,10 @@
9
9
  # v0
10
10
  auth:
11
11
  kind: static-key
12
- requires: [api_key] # deleted
13
- optional: [user_key] # deleted
12
+ requires: [api_key] # deleted
13
+ optional: [user_key] # deleted
14
14
  headerPrefixes:
15
- Authorization: "Bearer " # deleted
15
+ Authorization: "Bearer " # deleted
16
16
  secretRefs:
17
17
  Authorization: api_key
18
18
  X-Api-Key: user_key
@@ -25,32 +25,31 @@ auth:
25
25
  kind: static-key
26
26
  secretRefs:
27
27
  Authorization:
28
- secret: api_key # store name (was a bare string)
29
- prefix: "Bearer " # from headerPrefixes
28
+ secret: api_key # store name (was a bare string)
29
+ prefix: "Bearer " # from headerPrefixes
30
30
  X-Api-Key:
31
31
  secret: user_key
32
- optional: true # from the optional roster
32
+ optional: true # from the optional roster
33
33
  ```
34
34
 
35
- | v0 | v1 |
36
- |----|-----|
37
- | `secretRefs: {<header>: <name>}` | `secretRefs: {<header>: {secret: <name>}}` |
38
- | `requires: [<name>]` | delete — required is the default |
39
- | `optional: [<name>]` | `optional: true` on the ref that uses it |
40
- | `headerPrefixes: {<header>: "<p>"}` | `prefix: "<p>"` on that header's ref |
41
- | no `schemaVersion` line | add `schemaVersion: 1` |
35
+ | v0 | v1 |
36
+ | ----------------------------------- | ------------------------------------------ |
37
+ | `secretRefs: {<header>: <name>}` | `secretRefs: {<header>: {secret: <name>}}` |
38
+ | `requires: [<name>]` | delete — required is the default |
39
+ | `optional: [<name>]` | `optional: true` on the ref that uses it |
40
+ | `headerPrefixes: {<header>: "<p>"}` | `prefix: "<p>"` on that header's ref |
41
+ | no `schemaVersion` line | add `schemaVersion: 1` |
42
42
 
43
43
  Fix = stamp `schemaVersion: 1`, wrap each flat `secretRefs` value as
44
44
  `{secret: <name>}`, merge in `requires`/`optional`/`headerPrefixes`.
45
45
 
46
46
  ## Non-events
47
47
 
48
- Additive changes (optional fields, new enum values, relaxed constraints)
49
- never bump the version. Guides saved via current `api-learn` are stamped
50
- already.
48
+ Additive changes (optional fields, new enum values, relaxed constraints) never
49
+ bump the version. Guides saved via current `api-learn` are stamped already.
51
50
 
52
51
  ## Shelf life
53
52
 
54
53
  Stays as long as v0 guides can exist: user-authored local guides
55
- (`~/.pi/agent/pi-lean-host/api-guides/`) can hit the gate long after it
56
- ships. Superseded only by a v2 migration doc.
54
+ (`~/.pi/agent/pi-lean-host/api-guides/`) can hit the gate long after it ships.
55
+ Superseded only by a v2 migration doc.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "Read-only REST API client for Pi. Your agent authors and calls YAML recipes handling the tedious parts: pagination, OAuth2, rate limits, backoff. Credentials live in a local store, injected in code, never in agent context. Churn-free research + retrieval",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -73,7 +73,8 @@
73
73
  "tools/api-probe.ts",
74
74
  "tools/utils.ts",
75
75
  "docs/migration-v1.md",
76
- "README.md"
76
+ "README.md",
77
+ "CHANGELOG.md"
77
78
  ],
78
79
  "pi": {
79
80
  "extensions": [
@@ -92,9 +92,15 @@ export const apiFetchTool = defineTool({
92
92
  "When true, bypass the response cache and force a full network fetch. Responses are cached only when the server grants freshness (Cache-Control: max-age, or an ETag that revalidates via 304); pass fresh: true when you need guaranteed-current data (e.g. polling a status).",
93
93
  }),
94
94
  ),
95
+ saveTo: Type.Optional(
96
+ Type.String({
97
+ description:
98
+ "Write the response body to this file instead of returning it (byte downloads). Required on operations declared `download: true` in the guide; also accepted on any other operation to force download mode (parse/transform are skipped for that call). Pass an absolute path, or a path relative to the pi process's cwd — NOT the agent's own notion of cwd. A successful download OVERWRITES an existing file at the path; a failed or cancelled run leaves any pre-existing file untouched (the body is written to a temp file and renamed only on completion).",
99
+ }),
100
+ ),
95
101
  }),
96
102
 
97
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
103
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
98
104
  const sessionKey = ctx?.sessionManager?.getSessionId?.() ?? "api-default";
99
105
  const { domain, operation } = params as {
100
106
  domain: string;
@@ -103,21 +109,25 @@ export const apiFetchTool = defineTool({
103
109
  gatherAll?: boolean;
104
110
  };
105
111
 
106
- // `gatherAll` and `fresh` may be passed at the tool's top level (the
107
- // documented positions) or nested inside `params` (the natural place,
108
- // since `params` holds the operation arguments). Resolve both, preferring
109
- // the top level, and strip both out of the forwarded params so they can't
110
- // leak onto a `passthrough` query string or reach a domain helper. This
111
- // must happen before `executeParams` is built below.
112
+ // `gatherAll`, `fresh`, and `saveTo` may be passed at the tool's top level
113
+ // (the documented positions) or nested inside `params` (the natural place,
114
+ // since `params` holds the operation arguments). Resolve all three,
115
+ // preferring the top level, and strip them out of the forwarded params so
116
+ // they can't leak onto a `passthrough` query string or reach a domain
117
+ // helper. This must happen before `executeParams` is built below.
112
118
  const rawParams = (params as Record<string, unknown>)["params"] as
113
119
  | Record<string, unknown>
114
120
  | undefined;
115
121
  const gatherAll =
116
- ((params as Record<string, unknown>)["gatherAll"] as boolean | undefined) ??
117
- (rawParams?.gatherAll as boolean | undefined);
122
+ ((params as Record<string, unknown>)["gatherAll"] as
123
+ | boolean
124
+ | undefined) ?? (rawParams?.gatherAll as boolean | undefined);
118
125
  const fresh =
119
126
  ((params as Record<string, unknown>)["fresh"] as boolean | undefined) ??
120
127
  (rawParams?.fresh as boolean | undefined);
128
+ const saveTo =
129
+ ((params as Record<string, unknown>)["saveTo"] as string | undefined) ??
130
+ (rawParams?.saveTo as string | undefined);
121
131
  const userParams = rawParams ? { ...rawParams } : undefined;
122
132
  if (userParams && "gatherAll" in userParams) {
123
133
  delete userParams.gatherAll;
@@ -125,6 +135,9 @@ export const apiFetchTool = defineTool({
125
135
  if (userParams && "fresh" in userParams) {
126
136
  delete userParams.fresh;
127
137
  }
138
+ if (userParams && "saveTo" in userParams) {
139
+ delete userParams.saveTo;
140
+ }
128
141
 
129
142
  // 1. Resolve guides by domain — a domain may be claimed by more than
130
143
  // one guide (one domain, multiple APIs). Search every match for the
@@ -193,10 +206,26 @@ export const apiFetchTool = defineTool({
193
206
  // /api verify both route through it so the sequence can't drift.
194
207
  let outcome: ResolveOpResult;
195
208
  try {
209
+ // saveTo + paginate — explicit combo rejection before dispatch (a
210
+ // paginate walk has no single body to save; gatherAll is paginate
211
+ // machinery and needs no separate rule).
212
+ if (saveTo !== undefined && op.via === "paginate") {
213
+ throw new HelperError(
214
+ "saveTo",
215
+ "saveTo cannot be combined with a paginated operation — a paginate walk has no single body to save",
216
+ "a restGet operation",
217
+ `via: ${op.via}`,
218
+ "Drop saveTo, or call a non-paginated operation.",
219
+ );
220
+ }
196
221
  const execOpts: ResolveOpOptions = { skipSsrfGuard: _bypassUrlSafety };
197
222
  if (userParams) execOpts.userParams = userParams;
198
223
  if (gatherAll !== undefined) execOpts.gatherAll = gatherAll;
199
224
  if (fresh !== undefined) execOpts.fresh = fresh;
225
+ if (saveTo !== undefined) execOpts.saveTo = saveTo;
226
+ // pi's tool-call cancellation signal — aborting the call kills the
227
+ // in-flight request at every stage (connect, hops, body, backoff).
228
+ if (signal) execOpts.signal = signal;
200
229
  outcome = await resolveOpForExecution(guide, op, helperDirName, execOpts);
201
230
  } catch (err) {
202
231
  if (err instanceof HelperError) {
@@ -286,6 +315,50 @@ export const apiFetchTool = defineTool({
286
315
 
287
316
  if (via === "restGet") {
288
317
  const r = result as RestGetResult;
318
+ // Shared details for both restGet arms — a future restGet detail
319
+ // field must land on download and normal results alike.
320
+ const baseDetails = {
321
+ domain,
322
+ operation,
323
+ shortName: guide.shortName,
324
+ via: "restGet" as const,
325
+ request: { method: "GET", url: r.url, params: r.params },
326
+ ...(r.finalUrl === undefined ? {} : { finalUrl: r.finalUrl }),
327
+ // Output-channel audit: drop response headers that echo a
328
+ // known secret value (an auth-bearing server must not leak
329
+ // the key).
330
+ headers: scrubSecretHeaders(r.headers, outcome.authOpts.secretValues),
331
+ };
332
+ // Download result — branched BEFORE formatResult: a download result
333
+ // carries `data: undefined`, and JSON.stringify(undefined) is not a
334
+ // string, so formatJsonSnippet would throw on `json.length`. The
335
+ // file-present side renders the one line; the arm's existing tail
336
+ // (auth footer, gatherAll warning) still appends after it. The
337
+ // cache-served line is unreachable here (sink mode skips the cache
338
+ // arms).
339
+ if (r.file) {
340
+ let text = `šŸ“„ wrote ${r.file.bytes.toLocaleString("en-US")} bytes → ${r.file.path} (${r.file.contentType || "unknown content type"})`;
341
+ if (r.downloadWarning !== undefined) {
342
+ text = `⚠ ${r.downloadWarning}\n${text}`;
343
+ }
344
+ if (r.finalUrl !== undefined) {
345
+ text += `\n${formatRequestLine("GET", r.finalUrl)}`;
346
+ }
347
+ if (gatherAll) {
348
+ text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
349
+ }
350
+ if (authFooter) text += `\n${authFooter}`;
351
+ return {
352
+ content: [{ type: "text", text }],
353
+ details: {
354
+ ...baseDetails,
355
+ file: r.file,
356
+ ...(r.downloadWarning === undefined
357
+ ? {}
358
+ : { downloadWarning: r.downloadWarning }),
359
+ },
360
+ };
361
+ }
289
362
  let text = formatResult(r.data, guide, op, sessionKey, r.url);
290
363
  if (r.transformWarning !== undefined) {
291
364
  text =
@@ -296,20 +369,16 @@ export const apiFetchTool = defineTool({
296
369
  text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
297
370
  }
298
371
  if (authFooter) text += `\n${authFooter}`;
372
+ if (r.finalUrl !== undefined) {
373
+ text += `\n${formatRequestLine("GET", r.finalUrl)}`;
374
+ }
299
375
  if (r.cached === true)
300
376
  text += `\nā± cache-served (hit or 304-validated) — pass fresh: true to force a full refetch`;
301
377
  return {
302
378
  content: [{ type: "text", text }],
303
379
  details: {
304
- domain,
305
- operation,
306
- shortName: guide.shortName,
307
- via: "restGet",
308
- request: { method: "GET", url: r.url, params: r.params },
380
+ ...baseDetails,
309
381
  ...(r.cached === true ? { cached: true } : {}),
310
- // Output-channel audit: drop response headers that echo a known
311
- // secret value (an auth-bearing server must not leak the key).
312
- headers: scrubSecretHeaders(r.headers, outcome.authOpts.secretValues),
313
382
  },
314
383
  };
315
384
  }
@@ -360,7 +429,9 @@ export const apiFetchTool = defineTool({
360
429
 
361
430
  // TypeScript guard — all ExecutorVia values handled above.
362
431
  return {
363
- content: [{ type: "text", text: `Unhandled executor '${via as string}'.` }],
432
+ content: [
433
+ { type: "text", text: `Unhandled executor '${via as string}'.` },
434
+ ],
364
435
  details: { error: "unhandled_via", via },
365
436
  };
366
437
  },
@@ -400,7 +471,8 @@ export const apiFetchTool = defineTool({
400
471
 
401
472
  const shortName = (d?.shortName as string) || (d?.domain as string) || "?";
402
473
  const operation = (d?.operation as string) || "?";
403
- const reqUrl = ((d?.request as Record<string, unknown>)?.url as string) || "";
474
+ const reqUrl =
475
+ ((d?.request as Record<string, unknown>)?.url as string) || "";
404
476
  const totalFetched = d?.totalFetched as number | undefined;
405
477
 
406
478
  let text = theme.fg("accent", theme.bold(`šŸ“” ${shortName}`));
@@ -440,10 +512,10 @@ function cutAtNewline(s: string, limit: number): number {
440
512
  function formatJsonSnippet(json: string, sessionKey: string): string {
441
513
  const tooLarge = json.length > INLINE_LIMIT;
442
514
  const cut = tooLarge ? cutAtNewline(json, INLINE_LIMIT) : json.length;
443
- const snippet = tooLarge ? json.slice(0, cut) + "\n…" : json;
515
+ const snippet = tooLarge ? `${json.slice(0, cut)}\n…` : json;
444
516
  if (!tooLarge) return snippet;
445
517
  const spill = spillResponse(json, sessionKey);
446
- return snippet + "\n" + formatSpillNotice(spill, json.length);
518
+ return `${snippet}\n${formatSpillNotice(spill, json.length)}`;
447
519
  }
448
520
 
449
521
  function formatResult(
@@ -549,7 +621,9 @@ function formatAmbiguousOperation(
549
621
  lines.push(
550
622
  `then re-author one guide via api-learn({dir: …}) with the colliding operation renamed so the names no longer clash.`,
551
623
  );
552
- lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
624
+ lines.push(
625
+ `Note: api-learn rewrites a whole recipe, not a single operation.`,
626
+ );
553
627
  return lines.join("\n");
554
628
  }
555
629
 
@@ -185,6 +185,13 @@ function renderGuideDetail(
185
185
  lines.push(` ${op.name}`);
186
186
  lines.push(` via: ${op.via}`);
187
187
  lines.push(` path: ${op.path}`);
188
+ // Download-class op — the agent must learn the op writes a file and
189
+ // needs saveTo (today it surfaces only via:).
190
+ if (op.download === true) {
191
+ lines.push(
192
+ ` download: true — returns raw bytes; api-fetch requires saveTo: <path> to write the file`,
193
+ );
194
+ }
188
195
  // Path-param docs — `{token}` semantics (format, example values).
189
196
  // Declared as `params.<token>.description`; shown next to the path
190
197
  // line since the token lives in the path, not the query string.
@@ -217,7 +224,9 @@ function renderGuideDetail(
217
224
  // primary guidance for shaping values, so they get their own lines.
218
225
  for (const [k, spec] of qParams) {
219
226
  if (spec.description) {
220
- lines.push(` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`);
227
+ lines.push(
228
+ ` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`,
229
+ );
221
230
  }
222
231
  }
223
232
  }
@@ -492,7 +492,10 @@ export const apiLearnTool = defineTool({
492
492
  content: [
493
493
  {
494
494
  type: "text",
495
- text: err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
495
+ text:
496
+ err instanceof Error
497
+ ? err.message
498
+ : `Invalid domain '${domain}'.`,
496
499
  },
497
500
  ],
498
501
  details: { error: "invalid_domain", domain },
@@ -926,7 +929,8 @@ export const apiLearnTool = defineTool({
926
929
  const opCount = parsed.guide.operations.length;
927
930
  const opNames = parsed.guide.operations.map((o) => o.name).join(", ");
928
931
 
929
- const warningBlock = warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
932
+ const warningBlock =
933
+ warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
930
934
 
931
935
  return {
932
936
  content: [