pi-lean-host 0.2.0 → 0.2.1

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.
@@ -20,7 +20,7 @@
20
20
  import { defineTool } from "@earendil-works/pi-coding-agent";
21
21
  import { Type } from "@earendil-works/pi-ai";
22
22
  import { Text } from "@earendil-works/pi-tui";
23
- import { fetchUrl } from "../core/transport.js";
23
+ import { fetchUrl, redactSecretParams } from "../core/transport.js";
24
24
  import {
25
25
  extractPathTokens,
26
26
  fillPathTemplate,
@@ -29,12 +29,16 @@ import {
29
29
  import {
30
30
  resolveSecretHeaders,
31
31
  resolveSecretQueryParams,
32
+ scrubSecretValues,
32
33
  } from "../core/auth.js";
33
- import { listDomains, listNames } from "../core/secrets-store.js";
34
+ import {
35
+ listDomains,
36
+ listNames,
37
+ provisionedDomainsSuffix,
38
+ } from "../core/secrets-store.js";
34
39
  import { findGuidesByDomain } from "../core/guide-store.js";
35
- import { redactSecretParams } from "../core/helpers.js";
36
40
  import { isApiLearnEnabled } from "../core/api-toggle.js";
37
- import { contentText, renderExpandedText } from "./utils.js";
41
+ import { appendFooter, contentText } from "./utils.js";
38
42
 
39
43
  // ═══════════════════════════════════════════════════════════════════
40
44
  // Types
@@ -75,8 +79,8 @@ export interface ProbeResult {
75
79
  export interface ProbeOptions {
76
80
  /** Accept header (default application/json). */
77
81
  accept?: string;
78
- /** On 404, auto-try /v1/ and /v2/ prefixes. Default true. */
79
- tryPrefixes?: boolean;
82
+ /** On 404, walk the apiHost version backward (vN→v1). Default true. */
83
+ walkVersions?: boolean;
80
84
  /**
81
85
  * Store-backed auth injection for probing auth-gated endpoints
82
86
  * (authoring loop). Injection fields only — no kind/requires/optional.
@@ -85,6 +89,12 @@ export interface ProbeOptions {
85
89
  auth?: {
86
90
  secretRefs?: Record<string, string>;
87
91
  secretQueryRefs?: Record<string, string>;
92
+ /**
93
+ * Header name → prefix prepended to the resolved secret value (e.g.
94
+ * `Authorization: "Bearer "`). The store holds the raw token; the prefix
95
+ * is API knowledge. Keys must be present in `secretRefs`.
96
+ */
97
+ headerPrefixes?: Record<string, string>;
88
98
  };
89
99
  /** Domain for secrets-store lookups; defaults to apiHost's hostname. */
90
100
  domain?: string;
@@ -159,7 +169,9 @@ export function summarize(data: unknown): ShapeSummary {
159
169
  }
160
170
 
161
171
  const arrayLen = items?.length ?? 0;
162
- const suggestedVia = items === null ? "restGet" : "paginate";
172
+ const hasPaginationSignal = paginationMarkers.length > 0;
173
+ const suggestedVia =
174
+ items === null || !hasPaginationSignal ? "restGet" : "paginate";
163
175
 
164
176
  const summary: ShapeSummary = {
165
177
  topLevel,
@@ -167,7 +179,7 @@ export function summarize(data: unknown): ShapeSummary {
167
179
  keys,
168
180
  arrayLen,
169
181
  suggestedVia,
170
- suggestedItemsPath: suggestedVia === "paginate" ? itemsPath : "",
182
+ suggestedItemsPath: items === null ? "" : itemsPath,
171
183
  paginationMarkers,
172
184
  };
173
185
  const representativeId = pickRepresentativeId(items);
@@ -244,6 +256,7 @@ function resolveProbeAuth(
244
256
  {
245
257
  kind: "static-key",
246
258
  ...(auth!.secretRefs ? { secretRefs: auth!.secretRefs } : {}),
259
+ ...(auth!.headerPrefixes ? { headerPrefixes: auth!.headerPrefixes } : {}),
247
260
  },
248
261
  domain,
249
262
  );
@@ -264,6 +277,7 @@ function resolveProbeAuth(
264
277
  secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
265
278
  secretValues: [
266
279
  ...Object.values(headerRes.headers),
280
+ ...headerRes.rawHeaderValues,
267
281
  ...Object.values(queryRes.queryParams),
268
282
  ],
269
283
  missingNames: [
@@ -278,7 +292,10 @@ function resolveProbeAuth(
278
292
  /** First missing secret name as a one-line note (names only, never values). */
279
293
  function missNote(authCtx: ProbeAuthCtx, domain: string): string {
280
294
  if (authCtx.missingNames.length === 0) return "";
281
- return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"`;
295
+ return (
296
+ `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"` +
297
+ provisionedDomainsSuffix(domain)
298
+ );
282
299
  }
283
300
 
284
301
  /** Hostname of an apiHost URL (falls back to the raw string). */
@@ -290,6 +307,17 @@ function hostnameOf(apiHost: string): string {
290
307
  }
291
308
  }
292
309
 
310
+ /** Trailing path of an apiHost URL (e.g. `/v3`), or `""` when empty/root.
311
+ * Trailing slashes stripped so `.../v3/` + `/items` → `/v3/items`, not `/v3//items`.
312
+ * Lets the probe draft carry the version prefix that was actually fetched. */
313
+ function versionPrefixOf(apiHost: string): string {
314
+ try {
315
+ return new URL(apiHost).pathname.replace(/\/+$/, "");
316
+ } catch {
317
+ return "";
318
+ }
319
+ }
320
+
293
321
  export async function probe(
294
322
  apiHost: string,
295
323
  path: string,
@@ -297,22 +325,102 @@ export async function probe(
297
325
  opts: ProbeOptions = {},
298
326
  ): Promise<ProbeResult> {
299
327
  const accept = opts.accept ?? "application/json";
300
- const tryPrefixes = opts.tryPrefixes ?? true;
328
+ const walkVersions = opts.walkVersions ?? true;
301
329
  const domain = opts.domain ?? hostnameOf(apiHost);
302
330
  const authCtx = resolveProbeAuth(opts.auth, domain);
303
331
 
304
- const base = await fetchOne(apiHost, path, params, accept, authCtx, domain);
305
- if (base.status === 404 && tryPrefixes && !/^\/v\d+\//.test(path)) {
306
- for (const p of [`/v1${path}`, `/v2${path}`]) {
307
- const tried = await fetchOne(apiHost, p, params, accept, authCtx, domain);
308
- if (tried.status !== 404) {
309
- const miss = missNote(authCtx, domain);
310
- tried.note = `${miss ? miss + " — " : ""}404 on ${path}; /v*/ prefix hit → ${p}`;
311
- return tried;
312
- }
332
+ // Base case only carries the apiHost version prefix; a walk-hit draft
333
+ // embeds its walked version in the prefix passed to fetchOne.
334
+ const base = await fetchOne(
335
+ apiHost,
336
+ path,
337
+ params,
338
+ accept,
339
+ authCtx,
340
+ domain,
341
+ versionPrefixOf(apiHost),
342
+ );
343
+ if (base.status !== 404 || !walkVersions || /^\/v\d+\//.test(path)) {
344
+ return base;
345
+ }
346
+ // Recover an over-claimed version by walking the apiHost version backward
347
+ // (vN-1 → … → 1). Only fires on 404 — never a poller on a live 200.
348
+ const stated = VERSION_PATHNAME_RE.exec(versionPrefixOf(apiHost))?.[1];
349
+ if (stated === undefined) {
350
+ // Gate excludes a bare / non-integer / subdomain-versioned host — no
351
+ // walk to run, so tell the agent why rather than a silent bare 404.
352
+ base.note = walkSkipNote(authCtx, domain);
353
+ return base;
354
+ }
355
+ const hit = await walkBackward(
356
+ { apiHost, path, params, accept, authCtx, domain },
357
+ Number(stated),
358
+ );
359
+ return hit ?? base;
360
+ }
361
+
362
+ // ponytail: MAX_VERSION_WALK caps a high-version host's request burst
363
+ // (a /v10 host fires at most 5 backward walks, not 9); raise it if a longer
364
+ // version-gap chain is ever needed.
365
+ export const MAX_VERSION_WALK = 5;
366
+
367
+ /** Matches a pure integer version pathname (`/v3`), excluding date/non-numeric
368
+ * /subdomain /multi-segment conventions — the only form the walk can swap. */
369
+ const VERSION_PATHNAME_RE = /^\/v(\d+)$/;
370
+
371
+ /** Backward version walk: refetch the same bare path with /vN-… swapped into
372
+ * apiHost; return the first non-404 (with a version-walk note) or null. */
373
+ async function walkBackward(
374
+ ctx: {
375
+ apiHost: string;
376
+ path: string;
377
+ params: Record<string, unknown>;
378
+ accept: string;
379
+ authCtx: ProbeAuthCtx;
380
+ domain: string;
381
+ },
382
+ start: number,
383
+ ): Promise<ProbeResult | null> {
384
+ const miss = missNote(ctx.authCtx, ctx.domain);
385
+ const floor = Math.max(start - MAX_VERSION_WALK, 1);
386
+ for (let k = start - 1; k >= floor; k--) {
387
+ const tried = await fetchOne(
388
+ withVersion(ctx.apiHost, k),
389
+ ctx.path,
390
+ ctx.params,
391
+ ctx.accept,
392
+ ctx.authCtx,
393
+ ctx.domain,
394
+ `/v${k}`,
395
+ );
396
+ if (tried.status !== 404) {
397
+ // A walk hit may itself have redirected (e.g. /v2 301→ /v3); the
398
+ // draft carries /v${k} while the body came from elsewhere — flag
399
+ // it so the agent checks finalUrl instead of trusting the prefix.
400
+ const redirected = tried.finalUrl !== tried.url;
401
+ tried.note = `${miss ? miss + " — " : ""}404 on /v${start}${ctx.path}; version walk → /v${k}${redirected ? " — verify finalUrl (redirect target)" : ""}`;
402
+ return tried;
313
403
  }
314
404
  }
315
- return base;
405
+ return null;
406
+ }
407
+
408
+ /** apiHost with the version segment swapped via the URL API — never a
409
+ * string-replace (the version string could appear elsewhere in the host). */
410
+ function withVersion(apiHost: string, k: number): string {
411
+ try {
412
+ const u = new URL(apiHost);
413
+ u.pathname = `/v${k}`;
414
+ return `${u.origin}${u.pathname}`;
415
+ } catch {
416
+ return apiHost;
417
+ }
418
+ }
419
+
420
+ /** The gate-excluded 404 note (bare / non-integer / subdomain version hosts). */
421
+ function walkSkipNote(authCtx: ProbeAuthCtx, domain: string): string {
422
+ const miss = missNote(authCtx, domain);
423
+ return `${miss ? miss + " — " : ""}404 — no version walk (apiHost has no /vN prefix)`;
316
424
  }
317
425
 
318
426
  async function fetchOne(
@@ -322,6 +430,7 @@ async function fetchOne(
322
430
  accept: string,
323
431
  authCtx: ProbeAuthCtx,
324
432
  domain: string,
433
+ prefix = "",
325
434
  ): Promise<ProbeResult> {
326
435
  // Inject secret query params below the agent-supplied params map, then
327
436
  // redact the surfaced URL so the real key never reaches the transcript.
@@ -341,10 +450,7 @@ async function fetchOne(
341
450
  // Probe-local body scrub: the probe bypasses checkResponseStatus, so
342
451
  // scrub known secret values from the raw slice directly — a 401 body
343
452
  // echoing the key must not leak it into agent context.
344
- let raw = res.body.slice(0, 800);
345
- for (const v of authCtx.secretValues) {
346
- if (v && v.length > 0) raw = raw.split(v).join("***");
347
- }
453
+ const raw = scrubSecretValues(res.body.slice(0, 800), authCtx.secretValues);
348
454
  const finalUrl = redactSecretParams(
349
455
  res.finalUrl ?? rawUrl,
350
456
  authCtx.secretQueryParamNames,
@@ -401,17 +507,26 @@ async function fetchOne(
401
507
  status: res.status,
402
508
  ok: true,
403
509
  shape,
404
- draft: emitDraft(path, params, shape),
510
+ draft: emitDraft(path, params, shape, prefix),
405
511
  raw,
406
512
  ...(miss ? { note: miss } : {}),
407
513
  };
408
514
  }
409
515
 
516
+ const RESERVED_PARAM_NAMES = new Set(["domain", "apiHost", "path", "auth"]);
517
+
410
518
  function buildUrl(
411
519
  apiHost: string,
412
520
  path: string,
413
521
  params: Record<string, unknown>,
414
522
  ): string {
523
+ for (const key of Object.keys(params)) {
524
+ if (RESERVED_PARAM_NAMES.has(key)) {
525
+ throw new Error(
526
+ `"${key}" is a top-level param, not a query param — move it out of params`,
527
+ );
528
+ }
529
+ }
415
530
  // Substitute {token} → params[token] BEFORE building the URL, so a
416
531
  // templated path fetches real values instead of literal %7Bowner%7D.
417
532
  // Missing tokens stay literal ({token}) — fine for probing an unfilled path.
@@ -435,7 +550,11 @@ export function emitDraft(
435
550
  path: string,
436
551
  params: Record<string, unknown>,
437
552
  shape: ShapeSummary,
553
+ prefix = "",
438
554
  ): string {
555
+ // Idempotent: only prepend when the path doesn't already carry the prefix,
556
+ // so `apiHost: .../v3` + `path: /v3/items` doesn't become `/v3/v3/items`.
557
+ if (prefix && !path.startsWith(prefix)) path = prefix + path;
439
558
  const name = suggestName(path);
440
559
  const pathTokens = extractPathTokens(path);
441
560
  const queryParamKeys = Object.keys(params).filter(
@@ -466,6 +585,11 @@ export function emitDraft(
466
585
  lines.push(` pageSizeParam: ${pageSizeParam}`);
467
586
  lines.push(" pageSize: 30");
468
587
  }
588
+ if (shape.suggestedVia === "restGet" && shape.suggestedItemsPath !== "") {
589
+ lines.push(
590
+ " # array response with no pagination markers — if the API documents paging, prefer paginate; otherwise use restGet.",
591
+ );
592
+ }
469
593
  if (queryParamKeys.length > 0) {
470
594
  lines.push(" params:");
471
595
  for (const k of queryParamKeys) {
@@ -504,26 +628,45 @@ export const apiProbeTool = defineTool({
504
628
  "a draft YAML operation block to paste into a guide recipe. " +
505
629
  "It only suggests — it never writes the guide, and the operation must still be " +
506
630
  "traceable to your plan source. Pre-guide: pass apiHost + path. After a guide " +
507
- "exists, use api-guide({domain}) to get apiHost, or api-fetch to execute.",
631
+ "exists, use api-guide({domain}) to get apiHost, or api-fetch to execute. " +
632
+ "Before the first auth-gated probe, call with listSecrets: true (and no domain) " +
633
+ "to list every provisioned store domain and which already have guides — pass that " +
634
+ "domain up front so a store-miss round-trip is avoided. " +
635
+ "Before authoring a new guide, read the provider's docs index (llms.txt, " +
636
+ "openapi.json at the API root, or the docs page) to learn the current API " +
637
+ "version — then probe that version explicitly. Do not default the version from " +
638
+ "memory: a stale version that still returns 200 is not detected as old (the " +
639
+ "backward walk only fires on 404). The probe recovers an over-claimed version " +
640
+ "but cannot detect a stale-but-working one.",
508
641
 
509
642
  parameters: Type.Object({
510
- apiHost: Type.String({
511
- description:
512
- "Base URL including version prefix, e.g. 'https://api.github.com'.",
513
- }),
514
- path: Type.String({
515
- description:
516
- "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
517
- }),
643
+ apiHost: Type.Optional(
644
+ Type.String({
645
+ description:
646
+ "Base URL including the API's current version prefix, e.g. " +
647
+ "'https://api.example.com/v3'. Find the latest version before probing: " +
648
+ "check the API's docs page, openapi.json/swagger.json at the API root, " +
649
+ "or llms.txt. Supply the newest version you can verify — if it 404s, the " +
650
+ "probe walks backward (v3→v2→v1) to recover. Do not default to /v1 from " +
651
+ "memory; a stale version that still returns 200 is not detected as old.",
652
+ }),
653
+ ),
654
+ path: Type.Optional(
655
+ Type.String({
656
+ description:
657
+ "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
658
+ }),
659
+ ),
518
660
  params: Type.Optional(
519
661
  Type.Record(Type.String(), Type.Unknown(), {
520
662
  description:
521
663
  "Values for {token} path placeholders and query parameters. Path tokens are not re-declared as query params.",
522
664
  }),
523
665
  ),
524
- tryPrefixes: Type.Optional(
666
+ walkVersions: Type.Optional(
525
667
  Type.Boolean({
526
- description: "On 404, auto-try /v1/ and /v2/ prefixes. Default true.",
668
+ description:
669
+ "On 404, walk the apiHost version backward (vN→v1) to find the highest live version. Default true.",
527
670
  }),
528
671
  ),
529
672
  auth: Type.Optional(
@@ -531,10 +674,13 @@ export const apiProbeTool = defineTool({
531
674
  {
532
675
  secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
533
676
  secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
677
+ headerPrefixes: Type.Optional(Type.Record(Type.String(), Type.String())),
534
678
  },
535
679
  {
536
680
  description:
537
681
  "Store-backed auth injection for probing auth-gated endpoints (authoring loop). Injection fields only — values resolve from the secrets store and never enter the transcript; a store miss fetches unauthenticated and reports the miss in the note.",
682
+ // Tight: unknown keys (e.g. a stray `domain`) are rejected before execute runs.
683
+ additionalProperties: false,
538
684
  },
539
685
  ),
540
686
  ),
@@ -547,17 +693,21 @@ export const apiProbeTool = defineTool({
547
693
  listSecrets: Type.Optional(
548
694
  Type.Boolean({
549
695
  description:
550
- "Learn mode only: list provisioned secret names for the domain (no fetch). Names only, never values. Refused under /api on.",
696
+ "Names only, never values. Two modes: with no domain/apiHost, lists " +
697
+ "provisioned-but-guideless store domains (authoring-bootstrap view — " +
698
+ "call this empty first to see what's provisioned); with a domain (or " +
699
+ "apiHost), lists provisioned secret names for that domain, with " +
700
+ "declared-vs-stored gaps when a guide exists.",
551
701
  }),
552
702
  ),
553
703
  }),
554
704
 
555
705
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
556
- const { apiHost, path, tryPrefixes, auth, domain, listSecrets } = params as {
557
- apiHost: string;
558
- path: string;
706
+ const { apiHost, path, walkVersions, auth, domain, listSecrets } = params as {
707
+ apiHost?: string;
708
+ path?: string;
559
709
  params?: Record<string, unknown>;
560
- tryPrefixes?: boolean;
710
+ walkVersions?: boolean;
561
711
  auth?: {
562
712
  secretRefs?: Record<string, string>;
563
713
  secretQueryRefs?: Record<string, string>;
@@ -594,6 +744,11 @@ export const apiProbeTool = defineTool({
594
744
  if (target !== undefined) {
595
745
  const secrets = listDomainSecrets(target);
596
746
  blocks.push(formatSecretsResult(secrets));
747
+ // apiHost/domain present means a real probe was suppressed by
748
+ // listSecrets: true — say so, or the author silently loses the probe.
749
+ blocks.push(
750
+ "probe suppressed because listSecrets: true — drop listSecrets to probe.",
751
+ );
597
752
  return {
598
753
  content: [{ type: "text", text: blocks.join("\n\n") }],
599
754
  details: unscoped === undefined ? { secrets } : { secrets, unscoped },
@@ -605,9 +760,26 @@ export const apiProbeTool = defineTool({
605
760
  };
606
761
  }
607
762
 
763
+ // apiHost/path are optional in the schema so the bare listSecrets call is
764
+ // legal; every real probe needs both. The schema no longer enforces it,
765
+ // so guard here before falling through to probe(). (The listSecrets:true
766
+ // branch always returns above, so this guard only sees non-listSecrets.)
767
+ if (!apiHost || !path) {
768
+ return {
769
+ content: [
770
+ {
771
+ type: "text",
772
+ text:
773
+ "api-probe: apiHost and path are required unless listSecrets: true.",
774
+ },
775
+ ],
776
+ details: { error: "missing_apiHost_or_path" },
777
+ };
778
+ }
779
+
608
780
  try {
609
781
  const result = await probe(apiHost, path, userParams ?? {}, {
610
- ...(tryPrefixes === undefined ? {} : { tryPrefixes }),
782
+ ...(walkVersions === undefined ? {} : { walkVersions }),
611
783
  ...(auth ? { auth } : {}),
612
784
  ...(domain ? { domain } : {}),
613
785
  });
@@ -652,20 +824,41 @@ export const apiProbeTool = defineTool({
652
824
  if (d?.error) {
653
825
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
654
826
  }
827
+ // Secrets first: the domain-scoped view is the primary output and is present
828
+ // for both the per-domain and combined (apiHost-no-domain) shapes. Only the
829
+ // bare call (no domain/apiHost) carries unscoped alone.
655
830
  const secrets = d?.secrets as
656
831
  | { domain: string; provisioned: string[] }
657
832
  | undefined;
658
833
  if (secrets) {
659
- let text = theme.fg("accent", theme.bold("🔑 api-probe"));
660
- text += ` — secrets for ${secrets.domain} · ${secrets.provisioned.length} provisioned`;
661
- const content = contentText(result);
662
- if (expanded) {
663
- text += "\n";
664
- text = renderExpandedText(text, theme, content, 1000);
665
- } else {
666
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
667
- }
668
- return new Text(text, 0, 0);
834
+ const text = theme.fg("accent", theme.bold("🔑 api-probe"));
835
+ return new Text(
836
+ appendFooter(
837
+ text +
838
+ ` — secrets for ${secrets.domain} · ${secrets.provisioned.length} provisioned`,
839
+ expanded,
840
+ result,
841
+ theme,
842
+ 1000,
843
+ ),
844
+ 0,
845
+ 0,
846
+ );
847
+ }
848
+ const unscoped = d?.unscoped as string[] | undefined;
849
+ if (unscoped) {
850
+ const text = theme.fg("accent", theme.bold("🔑 api-probe"));
851
+ return new Text(
852
+ appendFooter(
853
+ text + ` — ${unscoped.length} unscoped domains`,
854
+ expanded,
855
+ result,
856
+ theme,
857
+ 1000,
858
+ ),
859
+ 0,
860
+ 0,
861
+ );
669
862
  }
670
863
  const status = d?.status as number | undefined;
671
864
  const shape = d?.shape as ShapeSummary | null | undefined;
@@ -679,15 +872,7 @@ export const apiProbeTool = defineTool({
679
872
  : "";
680
873
  text += `\n${theme.fg("dim", `${shape.suggestedVia}${items}`)}`;
681
874
  }
682
-
683
- const content = contentText(result);
684
- if (expanded) {
685
- text += "\n";
686
- text = renderExpandedText(text, theme, content, 1000);
687
- } else {
688
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
689
- }
690
- return new Text(text, 0, 0);
875
+ return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
691
876
  },
692
877
  });
693
878
 
@@ -695,7 +880,12 @@ export const apiProbeTool = defineTool({
695
880
  // Result formatting
696
881
  // ═══════════════════════════════════════════════════════════════════
697
882
 
698
- function formatProbeResult(r: ProbeResult): string {
883
+ const DOCS_NUDGE = [
884
+ "probe validates shape only — it cannot enumerate endpoints.",
885
+ "For a full guide, read the API's docs index (e.g. llms.txt or per-endpoint .md).",
886
+ ];
887
+
888
+ export function formatProbeResult(r: ProbeResult): string {
699
889
  const lines: string[] = [];
700
890
  lines.push(`🔬 api-probe — ${r.url}`);
701
891
  lines.push(` status: ${r.status}`);
@@ -723,6 +913,8 @@ function formatProbeResult(r: ProbeResult): string {
723
913
  lines.push(` raw (truncated):`);
724
914
  lines.push(r.raw);
725
915
  }
916
+ lines.push("");
917
+ lines.push(` ${DOCS_NUDGE.join("\n ")}`);
726
918
  return lines.join("\n");
727
919
  }
728
920
 
package/tools/utils.ts CHANGED
@@ -32,3 +32,24 @@ export function renderExpandedText(
32
32
  text += `\n${theme.fg("muted", `… ${content.length - limit} more chars`)}`;
33
33
  return text;
34
34
  }
35
+
36
+ /**
37
+ * Append the shared collapsed/expanded body footer to a render string:
38
+ * expanded shows the content preview; collapsed shows a "chars (expand)" hint.
39
+ */
40
+ export function appendFooter(
41
+ text: string,
42
+ expanded: boolean,
43
+ result: AgentToolResult<unknown>,
44
+ theme: { fg: (c: ThemeColor, t: string) => string },
45
+ limit: number,
46
+ ): string {
47
+ const content = contentText(result);
48
+ if (expanded) {
49
+ text += "\n";
50
+ text = renderExpandedText(text, theme, content, limit);
51
+ } else {
52
+ text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
53
+ }
54
+ return text;
55
+ }