pi-lean-host 0.1.1 → 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.
package/core/transport.ts CHANGED
@@ -43,12 +43,28 @@ export interface FetchOptions {
43
43
  maxRetries?: number;
44
44
  /** Skip cache (force fresh fetch). */
45
45
  fresh?: boolean;
46
- /** SSRF-check each redirect target before following it. Use only for
46
+ /** SSRF-check each redirect target before following it. Use it for
47
47
  * server-supplied URLs (paginate nextLink) — a malicious API can 302
48
48
  * to an internal host, and when auth headers ship the Authorization
49
49
  * header would attach to the redirect. Agent-supplied URLs don't need
50
- * this (the agent already has bash). */
50
+ * this (the agent already has bash). Forced on automatically for any
51
+ * auth-bearing request (hasAuth), so a keyed call is always guarded. */
51
52
  guardRedirects?: boolean;
53
+ /**
54
+ * Lowercased header names whose values are secrets injected from the
55
+ * secrets store (kind: static-key). Stripped — along with `authorization`
56
+ * — on cross-domain redirect hops so a secret can't leak to another host.
57
+ * Only honored while the guarded-redirect path is active (forced for any
58
+ * auth-bearing request, so this always applies to keyed calls).
59
+ */
60
+ secretHeaderNames?: Set<string>;
61
+ /**
62
+ * True when this request carries a store-injected query-param secret
63
+ * (kind: static-key). Broadens `hasAuth` to cover query-secret-only
64
+ * guides (header-secret callers never set this): the response becomes
65
+ * private (never cached / served from cache) and redirects are guarded.
66
+ */
67
+ hasQuerySecret?: boolean;
52
68
  /** Charset to decode the body with when the response's Content-Type
53
69
  * header omits one. Honors a guide's `responseShape.charset` for APIs
54
70
  * that serve e.g. ISO-8859-1 bytes without a charset parameter. An
@@ -126,6 +142,32 @@ function cacheKey(url: string, opts?: FetchOptions): string {
126
142
  return suffix ? `${url}${suffix}` : url;
127
143
  }
128
144
 
145
+ /**
146
+ * Output-channel audit — URL channel: redact every secret query param's
147
+ * value to `***` in a URL for surfacing. Returns the URL unchanged when no
148
+ * secret param names are in play (so non-secret guides never get URL-
149
+ * normalized by this). Defined here so the transport layer — the one place
150
+ * that holds a raw request URL and may embed it in an error message — can
151
+ * self-redact instead of relying on callers to remember. `helpers.ts`
152
+ * re-exports it for the capture points it owns (result.url, urls[],
153
+ * HelperError.url).
154
+ */
155
+ export function redactSecretParams(
156
+ url: string,
157
+ secretParamNames?: Set<string>,
158
+ ): string {
159
+ if (!secretParamNames || secretParamNames.size === 0) return url;
160
+ try {
161
+ const u = new URL(url);
162
+ for (const name of secretParamNames) {
163
+ if (u.searchParams.has(name)) u.searchParams.set(name, "***");
164
+ }
165
+ return u.toString();
166
+ } catch {
167
+ return url;
168
+ }
169
+ }
170
+
129
171
  function parseHeaders(
130
172
  hdrs: Dispatcher.ResponseData["headers"],
131
173
  ): Record<string, string> {
@@ -250,17 +292,50 @@ async function singleGet(
250
292
  }
251
293
  }
252
294
 
295
+ /** Host of a URL, or null when unparseable — treated as cross-domain (strip). */
296
+ function hostOf(url: string): string | null {
297
+ try {
298
+ return new URL(url).host;
299
+ } catch {
300
+ return null;
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Drop store-injected secret headers (plus `authorization`) from a request
306
+ * before it leaves the request's original host. Literal auth.headers (not in
307
+ * secretHeaderNames) survive. Used on cross-domain redirect hops only.
308
+ * Exported for the output-channel/SSRF structural tests (case c: cross-domain).
309
+ */
310
+ export function stripSecretHeaders(
311
+ headers: Record<string, string>,
312
+ secretHeaderNames?: Set<string>,
313
+ ): Record<string, string> {
314
+ const drop = new Set<string>(["authorization"]);
315
+ if (secretHeaderNames)
316
+ for (const h of secretHeaderNames) drop.add(h.toLowerCase());
317
+ const out: Record<string, string> = {};
318
+ for (const [k, v] of Object.entries(headers)) {
319
+ if (drop.has(k.toLowerCase())) continue;
320
+ out[k] = v;
321
+ }
322
+ return out;
323
+ }
324
+
253
325
  /**
254
- * Follow redirects manually, SSRF-checking each target. Used only for
255
- * server-supplied URLs (paginate nextLink). GET-only, so method is
256
- * preserved across 301/302/303/307/308 trivially. Returns the final
257
- * response; a redirect to a blocked host throws before it is fetched.
326
+ * Follow redirects manually, SSRF-checking each target. Used for
327
+ * server-supplied URLs (paginate nextLink) and — forced — any auth-bearing
328
+ * request. GET-only, so method is preserved across 301/302/303/307/308
329
+ * trivially. Returns the final response; a redirect to a blocked host
330
+ * throws before it is fetched. Store-injected secrets are stripped on
331
+ * cross-domain hops so a key can't attach to a different host.
258
332
  */
259
333
  async function getWithGuardedRedirects(
260
334
  url: string,
261
335
  reqHeaders: Record<string, string>,
262
336
  startTime: number,
263
337
  timeoutMs: number,
338
+ secretHeaderNames?: Set<string>,
264
339
  ): Promise<{
265
340
  status: number;
266
341
  headers: Record<string, string>;
@@ -268,14 +343,16 @@ async function getWithGuardedRedirects(
268
343
  finalUrl: string;
269
344
  }> {
270
345
  let current = url;
346
+ const originalHost = hostOf(url);
271
347
  for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
348
+ // Strip store-injected secrets (and Authorization) once a hop leaves
349
+ // the request's original host — a secret must never cross domains.
350
+ const hopHeaders =
351
+ hostOf(current) === originalHost
352
+ ? reqHeaders
353
+ : stripSecretHeaders(reqHeaders, secretHeaderNames);
272
354
  const remaining = timeoutMs - (Date.now() - startTime);
273
- const res = await singleGet(
274
- current,
275
- reqHeaders,
276
- remaining,
277
- noRedirectAgent,
278
- );
355
+ const res = await singleGet(current, hopHeaders, remaining, noRedirectAgent);
279
356
  const isRedirect =
280
357
  res.status >= 300 && res.status < 400 && res.status !== 304;
281
358
  if (!isRedirect || hops === MAX_REDIRECTS) return res;
@@ -337,10 +414,15 @@ export async function fetchUrl(
337
414
  const hasAuthHeaders =
338
415
  !!opts?.headers &&
339
416
  Object.keys(opts.headers).some((h) => h.toLowerCase() !== "accept");
417
+ // Broader hasAuth gate: header-secrets ∨ query-secrets. A query-secret-only
418
+ // guide carries no non-accept header, so hasAuthHeaders alone would
419
+ // miss it — hasQuerySecret closes that gap. Every auth gate below keys on
420
+ // hasAuth: cache-skip, If-None-Match, and the guarded-redirect force.
421
+ const hasAuth = hasAuthHeaders || (opts?.hasQuerySecret ?? false);
340
422
 
341
423
  // ── cache hit ───────────────────────────────────────────────
342
424
  const key = cacheKey(url, opts);
343
- if (!opts?.fresh && !hasAuthHeaders) {
425
+ if (!opts?.fresh && !hasAuth) {
344
426
  const entry = cache.get(key);
345
427
  if (entry && Date.now() < entry.expiresAt) {
346
428
  return { status: 200, headers: {}, body: entry.body, cached: true };
@@ -351,10 +433,10 @@ export async function fetchUrl(
351
433
  const reqHeaders: Record<string, string> = { ...opts?.headers };
352
434
  if (!reqHeaders["user-agent"]) {
353
435
  reqHeaders["user-agent"] =
354
- "pi-lean-host/0.1.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
436
+ "pi-lean-host/0.2.1 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
355
437
  }
356
438
 
357
- if (!opts?.fresh && !hasAuthHeaders) {
439
+ if (!opts?.fresh && !hasAuth) {
358
440
  const entry = cache.get(key);
359
441
  if (entry?.etag) {
360
442
  reqHeaders["If-None-Match"] = entry.etag;
@@ -363,21 +445,29 @@ export async function fetchUrl(
363
445
 
364
446
  const startTime = Date.now();
365
447
 
366
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
448
+ for (let attempt = 0; ; attempt++) {
367
449
  const remaining = timeout - (Date.now() - startTime);
368
450
  if (remaining <= 0) throw new Error("Request timeout");
369
451
 
370
452
  try {
371
- // When guardRedirects is set, follow redirects manually and SSRF-
372
- // check each target (server-supplied URLs only). Otherwise let
373
- // undici auto-follow up to 5 redirects.
453
+ // Guarded redirects when explicitly requested (server-supplied
454
+ // nextLink) OR when the request is auth-bearing (hasAuth) — a keyed
455
+ // call is always SSRF-checked hop-by-hop and its secrets stripped on
456
+ // cross-domain redirects. Otherwise let undici auto-follow up to 5.
457
+ const useGuarded = (opts?.guardRedirects ?? false) || hasAuth;
374
458
  const {
375
459
  status,
376
460
  headers: respHeaders,
377
461
  rawBody,
378
462
  finalUrl,
379
- } = opts?.guardRedirects
380
- ? await getWithGuardedRedirects(url, reqHeaders, startTime, timeout)
463
+ } = useGuarded
464
+ ? await getWithGuardedRedirects(
465
+ url,
466
+ reqHeaders,
467
+ startTime,
468
+ timeout,
469
+ opts?.secretHeaderNames,
470
+ )
381
471
  : await singleGet(url, reqHeaders, remaining, redirectAgent);
382
472
 
383
473
  // ── 304 Not Modified ────────────────────────────────
@@ -393,7 +483,7 @@ export async function fetchUrl(
393
483
  headers: respHeaders,
394
484
  body: entry.body,
395
485
  cached: true,
396
- ...(finalUrl !== url ? { finalUrl } : {}),
486
+ ...(finalUrl === url ? {} : { finalUrl }),
397
487
  };
398
488
  }
399
489
  // No cached entry → fall through to process body.
@@ -412,7 +502,7 @@ export async function fetchUrl(
412
502
  const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
413
503
  const body = decodeBuffer(rawBody, charset);
414
504
 
415
- if (status >= 200 && status < 300 && !hasAuthHeaders) {
505
+ if (status >= 200 && status < 300 && !hasAuth) {
416
506
  const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
417
507
  const etag = respHeaders["etag"];
418
508
 
@@ -427,7 +517,7 @@ export async function fetchUrl(
427
517
  headers: respHeaders,
428
518
  body,
429
519
  cached: false,
430
- ...(finalUrl !== url ? { finalUrl } : {}),
520
+ ...(finalUrl === url ? {} : { finalUrl }),
431
521
  };
432
522
  } catch (err) {
433
523
  const e = err instanceof Error ? err : new Error(String(err));
@@ -446,6 +536,4 @@ export async function fetchUrl(
446
536
  throw e;
447
537
  }
448
538
  }
449
-
450
- throw new Error(`Failed to fetch ${url} after ${maxRetries + 1} attempts`);
451
539
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "REST API client for Pi. A YAML file per API covers endpoints and pagination; the agent calls through a fixed executor so an API encoded once is reusable forever, not re-derived each session. It can probe a live endpoint and write the YAML for you, and a TypeScript file alongside can add custom auth or reshape the request and response freely.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -21,6 +21,16 @@
21
21
  "publishConfig": {
22
22
  "access": "public"
23
23
  },
24
+ "exports": {
25
+ ".": "./index.ts",
26
+ "./core/helpers.js": "./core/helpers.ts",
27
+ "./core/parse-api-guide.js": "./core/parse-api-guide.ts",
28
+ "./core/guide-store.js": "./core/guide-store.ts",
29
+ "./core/local-helpers.js": "./core/local-helpers.ts",
30
+ "./core/api-guide-types.js": "./core/api-guide-types.ts",
31
+ "./core/transport.js": "./core/transport.ts",
32
+ "./core/auth.js": "./core/auth.ts"
33
+ },
24
34
  "files": [
25
35
  "index.ts",
26
36
  "LICENSE",
@@ -35,6 +45,9 @@
35
45
  "core/local-helpers.ts",
36
46
  "core/helpers-command.ts",
37
47
  "core/api-toggle.ts",
48
+ "core/secrets-store.ts",
49
+ "core/secrets-command.ts",
50
+ "core/auth.ts",
38
51
  "core/portal-projection.ts",
39
52
  "core/response-spill.ts",
40
53
  "core/verify-ship-manifest.ts",
@@ -20,9 +20,19 @@ import { Text } from "@earendil-works/pi-tui";
20
20
  import { restGet, paginate, HelperError } from "../core/helpers.js";
21
21
  import { findGuidesByDomain } from "../core/guide-store.js";
22
22
  import { callHelper, loadTransform } from "../core/local-helpers.js";
23
+ import {
24
+ resolveSecretHeaders,
25
+ resolveSecretQueryParams,
26
+ authStatusLine,
27
+ canonicalStoreDomain,
28
+ containsSecret,
29
+ type SecretResolution,
30
+ type QuerySecretResolution,
31
+ } from "../core/auth.js";
32
+ import { provisionedDomainsSuffix } from "../core/secrets-store.js";
23
33
  import { formatGuideListings } from "../core/parse-api-guide.js";
24
34
  import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
25
- import { contentText, renderExpandedText } from "./utils.js";
35
+ import { appendFooter, contentText } from "./utils.js";
26
36
  import type { Operation, ApiGuide } from "../core/api-guide-types.js";
27
37
 
28
38
  // ═══════════════════════════════════════════════════════════════════
@@ -92,9 +102,8 @@ export const apiFetchTool = defineTool({
92
102
  | Record<string, unknown>
93
103
  | undefined;
94
104
  const gatherAll =
95
- ((params as Record<string, unknown>)["gatherAll"] as
96
- | boolean
97
- | undefined) ?? (rawParams?.gatherAll as boolean | undefined);
105
+ ((params as Record<string, unknown>)["gatherAll"] as boolean | undefined) ??
106
+ (rawParams?.gatherAll as boolean | undefined);
98
107
  const userParams = rawParams ? { ...rawParams } : undefined;
99
108
  if (userParams && "gatherAll" in userParams) {
100
109
  delete userParams.gatherAll;
@@ -158,6 +167,12 @@ export const apiFetchTool = defineTool({
158
167
 
159
168
  const { guide, dirName: helperDirName, op } = opMatches[0]!;
160
169
 
170
+ // 2.5.5 The canonical secret-store key: `guide.domains[0]` (the plain
171
+ // browsable domain). Independent of the routing `domain` the agent
172
+ // passed — auth resolution, the fail-closed error, and the footer all
173
+ // key the store on this canonical value, not on `domain`.
174
+ const storeDomain = canonicalStoreDomain(guide);
175
+
161
176
  // 2.5 Resolve local helper if the operation declares one.
162
177
  // The helper is resolved by the matched guide's directory name
163
178
  // (helperDirName), not by a helper name — one helper per guide lives
@@ -165,11 +180,7 @@ export const apiFetchTool = defineTool({
165
180
  // routing `domain` in the multi-recipe case.
166
181
  let executeParams = userParams ?? {};
167
182
  if (op.helper === true) {
168
- const helperResult = await callHelper(
169
- helperDirName,
170
- op.name,
171
- executeParams,
172
- );
183
+ const helperResult = await callHelper(helperDirName, op.name, executeParams);
173
184
  if (!helperResult.ok) {
174
185
  return {
175
186
  content: [
@@ -207,6 +218,68 @@ export const apiFetchTool = defineTool({
207
218
  );
208
219
  }
209
220
 
221
+ // 2.7 Authentication (kind: static-key): resolve store-injected secret
222
+ // headers AND query params up front so a missing required secret
223
+ // fails closed BEFORE any request is made. Values never leave this
224
+ // scope — only header/param and secret NAMES ever surface to the agent.
225
+ let headerRes: SecretResolution | undefined;
226
+ let queryRes: QuerySecretResolution | undefined;
227
+ if (guide.auth.kind === "static-key") {
228
+ headerRes = resolveSecretHeaders(guide.auth, storeDomain);
229
+ queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
230
+ const missingRequired = [
231
+ ...(headerRes.absentRequired ?? []),
232
+ ...(queryRes.absentRequired ?? []),
233
+ ];
234
+ if (missingRequired.length > 0) {
235
+ const text =
236
+ `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
237
+ `${missingRequired.join(", ")}.\n` +
238
+ `Run /api secrets ${storeDomain} to provision it, then retry this call.` +
239
+ provisionedDomainsSuffix(storeDomain);
240
+ return {
241
+ content: [{ type: "text", text }],
242
+ details: {
243
+ error: "auth_required_not_provisioned",
244
+ domain,
245
+ operation,
246
+ missing: missingRequired,
247
+ },
248
+ };
249
+ }
250
+ }
251
+ const headerValues = headerRes
252
+ ? [...Object.values(headerRes.headers), ...headerRes.rawHeaderValues]
253
+ : [];
254
+ const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
255
+ const authOpts: {
256
+ authHeaders?: Record<string, string>;
257
+ secretHeaderNames?: Set<string>;
258
+ secretValues?: string[];
259
+ secretQueryParams?: Record<string, string>;
260
+ secretQueryParamNames?: Set<string>;
261
+ } =
262
+ headerRes || queryRes
263
+ ? {
264
+ ...(headerRes
265
+ ? {
266
+ authHeaders: headerRes.headers,
267
+ secretHeaderNames: new Set(
268
+ Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
269
+ ),
270
+ }
271
+ : {}),
272
+ ...(queryRes
273
+ ? {
274
+ secretQueryParams: queryRes.queryParams,
275
+ secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
276
+ }
277
+ : {}),
278
+ secretValues: [...headerValues, ...queryValues],
279
+ }
280
+ : {};
281
+ const authFooter = authStatusLine(guide.auth, storeDomain);
282
+
210
283
  // 3. Execute via the declared helper.
211
284
  try {
212
285
  const helperOpts = {
@@ -219,7 +292,7 @@ export const apiFetchTool = defineTool({
219
292
  op,
220
293
  executeParams,
221
294
  guide,
222
- undefined, // opts — restGet has no SSRF guard to bypass
295
+ authOpts, // opts — restGet has no SSRF bypass; auth headers injected here
223
296
  transformFn ?? undefined,
224
297
  helperDirName,
225
298
  );
@@ -232,6 +305,7 @@ export const apiFetchTool = defineTool({
232
305
  if (gatherAll) {
233
306
  text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
234
307
  }
308
+ if (authFooter) text += `\n${authFooter}`;
235
309
  return {
236
310
  content: [{ type: "text", text }],
237
311
  details: {
@@ -240,7 +314,9 @@ export const apiFetchTool = defineTool({
240
314
  shortName: guide.shortName,
241
315
  via: "restGet",
242
316
  request: { method: "GET", url: result.url, params: result.params },
243
- headers: result.headers,
317
+ // Output-channel audit: drop response headers that echo a known
318
+ // secret value (an auth-bearing server must not leak the key).
319
+ headers: scrubSecretHeaders(result.headers, authOpts.secretValues),
244
320
  },
245
321
  };
246
322
  }
@@ -248,6 +324,7 @@ export const apiFetchTool = defineTool({
248
324
  if (op.via === "paginate") {
249
325
  const paginateOpts: Parameters<typeof paginate>[4] = {
250
326
  ...helperOpts,
327
+ ...authOpts,
251
328
  };
252
329
  if (gatherAll !== undefined) paginateOpts.gatherAll = gatherAll;
253
330
  const result = await paginate(
@@ -261,7 +338,7 @@ export const apiFetchTool = defineTool({
261
338
  );
262
339
  const firstUrl = result.urls[0] ?? "";
263
340
  const serverTotal = result.serverTotal;
264
- const text =
341
+ let text =
265
342
  result.items.length === 0 && !result.failedItems
266
343
  ? [
267
344
  `📦 0 item(s) fetched`,
@@ -279,6 +356,7 @@ export const apiFetchTool = defineTool({
279
356
  serverTotal,
280
357
  result.failedItems,
281
358
  );
359
+ if (authFooter) text += `\n${authFooter}`;
282
360
  return {
283
361
  content: [{ type: "text", text }],
284
362
  details: {
@@ -294,7 +372,7 @@ export const apiFetchTool = defineTool({
294
372
  urls: result.urls,
295
373
  },
296
374
  totalFetched: result.totalFetched,
297
- ...(serverTotal !== undefined ? { serverTotal } : {}),
375
+ ...(serverTotal === undefined ? {} : { serverTotal }),
298
376
  ceilingHit: result.ceilingHit,
299
377
  },
300
378
  };
@@ -372,8 +450,7 @@ export const apiFetchTool = defineTool({
372
450
 
373
451
  const shortName = (d?.shortName as string) || (d?.domain as string) || "?";
374
452
  const operation = (d?.operation as string) || "?";
375
- const reqUrl =
376
- ((d?.request as Record<string, unknown>)?.url as string) || "";
453
+ const reqUrl = ((d?.request as Record<string, unknown>)?.url as string) || "";
377
454
  const totalFetched = d?.totalFetched as number | undefined;
378
455
 
379
456
  let text = theme.fg("accent", theme.bold(`📡 ${shortName}`));
@@ -382,14 +459,7 @@ export const apiFetchTool = defineTool({
382
459
  text += `\n📦 ${totalFetched} item(s) fetched`;
383
460
  }
384
461
 
385
- const content = contentText(result);
386
- if (expanded) {
387
- text += "\n";
388
- text = renderExpandedText(text, theme, content, 1000);
389
- } else {
390
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
391
- }
392
- return new Text(text, 0, 0);
462
+ return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
393
463
  },
394
464
  });
395
465
 
@@ -531,9 +601,7 @@ function formatAmbiguousOperation(
531
601
  lines.push(
532
602
  `then re-author one guide via api-learn({domain: "${first.dirName}", recipe: …}) with the colliding operation renamed so the names no longer clash.`,
533
603
  );
534
- lines.push(
535
- `Note: api-learn rewrites a whole recipe, not a single operation.`,
536
- );
604
+ lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
537
605
  return lines.join("\n");
538
606
  }
539
607
 
@@ -556,6 +624,25 @@ function formatHelperDisabled(
556
624
  return lines.join("\n");
557
625
  }
558
626
 
627
+ /**
628
+ * Output-channel audit — response-header echo: drop any response header
629
+ * whose value contains a known store-injected secret. An auth-bearing
630
+ * server must not echo the key back into `details.headers`. Returns the
631
+ * original map unchanged when no secrets are in play.
632
+ */
633
+ function scrubSecretHeaders(
634
+ headers: Record<string, string>,
635
+ secretValues?: string[],
636
+ ): Record<string, string> {
637
+ if (!secretValues || secretValues.length === 0) return headers;
638
+ const out: Record<string, string> = {};
639
+ for (const [k, v] of Object.entries(headers)) {
640
+ if (containsSecret(v, secretValues)) continue;
641
+ out[k] = v;
642
+ }
643
+ return out;
644
+ }
645
+
559
646
  function formatHelperError(
560
647
  err: HelperError,
561
648
  domain: string,
@@ -13,13 +13,14 @@ import {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
  import { Type } from "@earendil-works/pi-ai";
15
15
  import { Text } from "@earendil-works/pi-tui";
16
- import { contentText, renderExpandedText } from "./utils.js";
16
+ import { appendFooter, contentText } from "./utils.js";
17
17
  import {
18
18
  loadAllGuides,
19
19
  findGuidesByDomain,
20
20
  getCatalogText,
21
21
  } from "../core/guide-store.js";
22
22
  import { formatGuideListings, TODAY } from "../core/parse-api-guide.js";
23
+ import { authStatusLine, canonicalStoreDomain } from "../core/auth.js";
23
24
  import type { ApiGuide } from "../core/api-guide-types.js";
24
25
 
25
26
  export const apiGuideTool = defineTool({
@@ -163,21 +164,14 @@ export const apiGuideTool = defineTool({
163
164
  } else if (guideName && opCount !== undefined) {
164
165
  text = theme.fg("accent", theme.bold(`📖 ${guideName}`));
165
166
  text += ` — ${opCount} operations`;
166
- } else if (guideCount !== undefined) {
167
+ } else if (guideCount === undefined) {
168
+ text = theme.fg("dim", "📖 No guide");
169
+ } else {
167
170
  text = theme.fg("dim", theme.bold("📖 catalog"));
168
171
  text += ` — ${guideCount} guides`;
169
- } else {
170
- text = theme.fg("dim", "📖 No guide");
171
172
  }
172
173
 
173
- const content = contentText(result);
174
- if (expanded) {
175
- text += "\n";
176
- text = renderExpandedText(text, theme, content, 800);
177
- } else {
178
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
179
- }
180
- return new Text(text, 0, 0);
174
+ return new Text(appendFooter(text, expanded, result, theme, 800), 0, 0);
181
175
  },
182
176
  });
183
177
 
@@ -197,6 +191,11 @@ function renderGuideDetail(
197
191
  lines.push(` Verified: ${guide.verified} · Updated: ${guide.updated}`);
198
192
  if (guide.docs) lines.push(` Docs: ${guide.docs}`);
199
193
  lines.push(` Auth: ${guide.auth.kind}`);
194
+ // Auth status footer — shared with api-fetch. Metadata only (names,
195
+ // never values); nudges provisioning when a required secret is absent.
196
+ // Keyed on the canonical store domain, not the routing `domain`.
197
+ const authStatus = authStatusLine(guide.auth, canonicalStoreDomain(guide));
198
+ if (authStatus) lines.push(` ${authStatus}`);
200
199
  lines.push(
201
200
  ` Response: ${guide.responseShape.format} (${guide.responseShape.charset})`,
202
201
  );
@@ -235,9 +234,7 @@ function renderGuideDetail(
235
234
  // primary guidance for shaping values, so they get their own lines.
236
235
  for (const [k, spec] of qParams) {
237
236
  if (spec.description) {
238
- lines.push(
239
- ` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`,
240
- );
237
+ lines.push(` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`);
241
238
  }
242
239
  }
243
240
  }
@@ -248,6 +245,7 @@ function renderGuideDetail(
248
245
  if (pagCfg.pageParam) bits.push(pagCfg.pageParam);
249
246
  if (pagCfg.pageSizeParam)
250
247
  bits.push(`${pagCfg.pageSizeParam}=${pagCfg.pageSize ?? 50}`);
248
+ if (pagCfg.base !== undefined) bits.push(`base=${pagCfg.base}`);
251
249
  lines.push(` pagination: ${bits.join(" ")}`);
252
250
  }
253
251
  }