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.
@@ -20,13 +20,25 @@
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,
27
27
  joinUrl,
28
28
  } from "../core/path-template.js";
29
- import { contentText, renderExpandedText } from "./utils.js";
29
+ import {
30
+ resolveSecretHeaders,
31
+ resolveSecretQueryParams,
32
+ scrubSecretValues,
33
+ } from "../core/auth.js";
34
+ import {
35
+ listDomains,
36
+ listNames,
37
+ provisionedDomainsSuffix,
38
+ } from "../core/secrets-store.js";
39
+ import { findGuidesByDomain } from "../core/guide-store.js";
40
+ import { isApiLearnEnabled } from "../core/api-toggle.js";
41
+ import { appendFooter, contentText } from "./utils.js";
30
42
 
31
43
  // ═══════════════════════════════════════════════════════════════════
32
44
  // Types
@@ -67,8 +79,25 @@ export interface ProbeResult {
67
79
  export interface ProbeOptions {
68
80
  /** Accept header (default application/json). */
69
81
  accept?: string;
70
- /** On 404, auto-try /v1/ and /v2/ prefixes. Default true. */
71
- tryPrefixes?: boolean;
82
+ /** On 404, walk the apiHost version backward (vN→v1). Default true. */
83
+ walkVersions?: boolean;
84
+ /**
85
+ * Store-backed auth injection for probing auth-gated endpoints
86
+ * (authoring loop). Injection fields only — no kind/requires/optional.
87
+ * Values resolve from the secrets store and never enter the transcript.
88
+ */
89
+ auth?: {
90
+ secretRefs?: Record<string, string>;
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>;
98
+ };
99
+ /** Domain for secrets-store lookups; defaults to apiHost's hostname. */
100
+ domain?: string;
72
101
  }
73
102
 
74
103
  // ═══════════════════════════════════════════════════════════════════
@@ -140,7 +169,9 @@ export function summarize(data: unknown): ShapeSummary {
140
169
  }
141
170
 
142
171
  const arrayLen = items?.length ?? 0;
143
- const suggestedVia = items !== null ? "paginate" : "restGet";
172
+ const hasPaginationSignal = paginationMarkers.length > 0;
173
+ const suggestedVia =
174
+ items === null || !hasPaginationSignal ? "restGet" : "paginate";
144
175
 
145
176
  const summary: ShapeSummary = {
146
177
  topLevel,
@@ -148,7 +179,7 @@ export function summarize(data: unknown): ShapeSummary {
148
179
  keys,
149
180
  arrayLen,
150
181
  suggestedVia,
151
- suggestedItemsPath: suggestedVia === "paginate" ? itemsPath : "",
182
+ suggestedItemsPath: items === null ? "" : itemsPath,
152
183
  paginationMarkers,
153
184
  };
154
185
  const representativeId = pickRepresentativeId(items);
@@ -184,6 +215,109 @@ function pickRepresentativeId(
184
215
  // IO wrapper — fetches via the shared transport and formats the answer
185
216
  // ═══════════════════════════════════════════════════════════════════
186
217
 
218
+ /** Resolved probe auth — store values + the names/values to redact/scrub. */
219
+ interface ProbeAuthCtx {
220
+ hasAuthBlock: boolean;
221
+ headers: Record<string, string>;
222
+ queryParams: Record<string, string>;
223
+ secretHeaderNames: Set<string>;
224
+ secretQueryParamNames: Set<string>;
225
+ secretValues: string[];
226
+ missingNames: string[];
227
+ }
228
+
229
+ /**
230
+ * Resolve an inline `auth` block against the secrets store. Probe semantics:
231
+ * a store miss is NOT fail-closed (human-in-the-loop authoring tool) — the
232
+ * missing name is reported and the call proceeds with the header/param
233
+ * omitted. `requires`/`optional` are absent from the probe's injection-only
234
+ * block, so every miss lands in the report list.
235
+ */
236
+ function resolveProbeAuth(
237
+ auth: NonNullable<ProbeOptions["auth"]> | undefined,
238
+ domain: string,
239
+ ): ProbeAuthCtx {
240
+ const hasRefs =
241
+ !!auth &&
242
+ (Object.keys(auth.secretRefs ?? {}).length > 0 ||
243
+ Object.keys(auth.secretQueryRefs ?? {}).length > 0);
244
+ if (!hasRefs) {
245
+ return {
246
+ hasAuthBlock: false,
247
+ headers: {},
248
+ queryParams: {},
249
+ secretHeaderNames: new Set(),
250
+ secretQueryParamNames: new Set(),
251
+ secretValues: [],
252
+ missingNames: [],
253
+ };
254
+ }
255
+ const headerRes = resolveSecretHeaders(
256
+ {
257
+ kind: "static-key",
258
+ ...(auth!.secretRefs ? { secretRefs: auth!.secretRefs } : {}),
259
+ ...(auth!.headerPrefixes ? { headerPrefixes: auth!.headerPrefixes } : {}),
260
+ },
261
+ domain,
262
+ );
263
+ const queryRes = resolveSecretQueryParams(
264
+ {
265
+ kind: "static-key",
266
+ ...(auth!.secretQueryRefs ? { secretQueryRefs: auth!.secretQueryRefs } : {}),
267
+ },
268
+ domain,
269
+ );
270
+ return {
271
+ hasAuthBlock: true,
272
+ headers: headerRes.headers,
273
+ queryParams: queryRes.queryParams,
274
+ secretHeaderNames: new Set(
275
+ Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
276
+ ),
277
+ secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
278
+ secretValues: [
279
+ ...Object.values(headerRes.headers),
280
+ ...headerRes.rawHeaderValues,
281
+ ...Object.values(queryRes.queryParams),
282
+ ],
283
+ missingNames: [
284
+ ...headerRes.absentRequired,
285
+ ...headerRes.absentOptional,
286
+ ...queryRes.absentRequired,
287
+ ...queryRes.absentOptional,
288
+ ],
289
+ };
290
+ }
291
+
292
+ /** First missing secret name as a one-line note (names only, never values). */
293
+ function missNote(authCtx: ProbeAuthCtx, domain: string): string {
294
+ if (authCtx.missingNames.length === 0) return "";
295
+ return (
296
+ `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"` +
297
+ provisionedDomainsSuffix(domain)
298
+ );
299
+ }
300
+
301
+ /** Hostname of an apiHost URL (falls back to the raw string). */
302
+ function hostnameOf(apiHost: string): string {
303
+ try {
304
+ return new URL(apiHost).hostname;
305
+ } catch {
306
+ return apiHost;
307
+ }
308
+ }
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
+
187
321
  export async function probe(
188
322
  apiHost: string,
189
323
  path: string,
@@ -191,19 +325,102 @@ export async function probe(
191
325
  opts: ProbeOptions = {},
192
326
  ): Promise<ProbeResult> {
193
327
  const accept = opts.accept ?? "application/json";
194
- const tryPrefixes = opts.tryPrefixes ?? true;
195
-
196
- const base = await fetchOne(apiHost, path, params, accept);
197
- if (base.status === 404 && tryPrefixes && !/^\/v\d+\//.test(path)) {
198
- for (const p of [`/v1${path}`, `/v2${path}`]) {
199
- const tried = await fetchOne(apiHost, p, params, accept);
200
- if (tried.status !== 404) {
201
- tried.note = `404 on ${path}; /v*/ prefix hit → ${p}`;
202
- return tried;
203
- }
328
+ const walkVersions = opts.walkVersions ?? true;
329
+ const domain = opts.domain ?? hostnameOf(apiHost);
330
+ const authCtx = resolveProbeAuth(opts.auth, domain);
331
+
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;
204
403
  }
205
404
  }
206
- 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)`;
207
424
  }
208
425
 
209
426
  async function fetchOne(
@@ -211,17 +428,48 @@ async function fetchOne(
211
428
  path: string,
212
429
  params: Record<string, unknown>,
213
430
  accept: string,
431
+ authCtx: ProbeAuthCtx,
432
+ domain: string,
433
+ prefix = "",
214
434
  ): Promise<ProbeResult> {
215
- const url = buildUrl(apiHost, path, params);
216
- const res = await fetchUrl(url, { headers: { accept }, fresh: true });
217
- const raw = res.body.slice(0, 800);
218
- const finalUrl = res.finalUrl ?? url;
435
+ // Inject secret query params below the agent-supplied params map, then
436
+ // redact the surfaced URL so the real key never reaches the transcript.
437
+ const rawUrl = buildUrl(apiHost, path, { ...params, ...authCtx.queryParams });
438
+ const url = redactSecretParams(rawUrl, authCtx.secretQueryParamNames);
439
+ const hasQuerySecret = Object.keys(authCtx.queryParams).length > 0;
440
+ const res = await fetchUrl(rawUrl, {
441
+ headers: { accept, ...authCtx.headers },
442
+ fresh: true,
443
+ ...(authCtx.hasAuthBlock
444
+ ? {
445
+ hasQuerySecret,
446
+ secretHeaderNames: authCtx.secretHeaderNames,
447
+ }
448
+ : {}),
449
+ });
450
+ // Probe-local body scrub: the probe bypasses checkResponseStatus, so
451
+ // scrub known secret values from the raw slice directly — a 401 body
452
+ // echoing the key must not leak it into agent context.
453
+ const raw = scrubSecretValues(res.body.slice(0, 800), authCtx.secretValues);
454
+ const finalUrl = redactSecretParams(
455
+ res.finalUrl ?? rawUrl,
456
+ authCtx.secretQueryParamNames,
457
+ );
219
458
 
220
459
  if (res.status >= 400) {
221
- const note =
222
- res.status === 401 || res.status === 403
460
+ const is401 = res.status === 401 || res.status === 403;
461
+ const miss = missNote(authCtx, domain);
462
+ let note: string;
463
+ if (authCtx.hasAuthBlock) {
464
+ // Auth block present → never the stale auth:none text; report the
465
+ // store miss (or a bare requires-auth hint when nothing was missing).
466
+ note = `${res.status}${is401 ? " — requires authentication?" : ""}${miss ? ` ${miss}` : ""}`;
467
+ } else {
468
+ // No auth block → the existing auth:none wording.
469
+ note = is401
223
470
  ? `${res.status} — requires authentication? (guide is auth:none)`
224
471
  : `${res.status}`;
472
+ }
225
473
  return {
226
474
  url,
227
475
  finalUrl,
@@ -246,27 +494,39 @@ async function fetchOne(
246
494
  shape: null,
247
495
  draft: "",
248
496
  raw,
249
- note: "non-JSON body (set opts.accept for XML/HTML, or use a different path)",
497
+ note:
498
+ "non-JSON body (set opts.accept for XML/HTML, or use a different path)",
250
499
  };
251
500
  }
252
501
 
253
502
  const shape = summarize(data);
503
+ const miss = missNote(authCtx, domain);
254
504
  return {
255
505
  url,
256
506
  finalUrl,
257
507
  status: res.status,
258
508
  ok: true,
259
509
  shape,
260
- draft: emitDraft(path, params, shape),
510
+ draft: emitDraft(path, params, shape, prefix),
261
511
  raw,
512
+ ...(miss ? { note: miss } : {}),
262
513
  };
263
514
  }
264
515
 
516
+ const RESERVED_PARAM_NAMES = new Set(["domain", "apiHost", "path", "auth"]);
517
+
265
518
  function buildUrl(
266
519
  apiHost: string,
267
520
  path: string,
268
521
  params: Record<string, unknown>,
269
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
+ }
270
530
  // Substitute {token} → params[token] BEFORE building the URL, so a
271
531
  // templated path fetches real values instead of literal %7Bowner%7D.
272
532
  // Missing tokens stay literal ({token}) — fine for probing an unfilled path.
@@ -290,7 +550,11 @@ export function emitDraft(
290
550
  path: string,
291
551
  params: Record<string, unknown>,
292
552
  shape: ShapeSummary,
553
+ prefix = "",
293
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;
294
558
  const name = suggestName(path);
295
559
  const pathTokens = extractPathTokens(path);
296
560
  const queryParamKeys = Object.keys(params).filter(
@@ -321,6 +585,11 @@ export function emitDraft(
321
585
  lines.push(` pageSizeParam: ${pageSizeParam}`);
322
586
  lines.push(" pageSize: 30");
323
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
+ }
324
593
  if (queryParamKeys.length > 0) {
325
594
  lines.push(" params:");
326
595
  for (const k of queryParamKeys) {
@@ -359,44 +628,160 @@ export const apiProbeTool = defineTool({
359
628
  "a draft YAML operation block to paste into a guide recipe. " +
360
629
  "It only suggests — it never writes the guide, and the operation must still be " +
361
630
  "traceable to your plan source. Pre-guide: pass apiHost + path. After a guide " +
362
- "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.",
363
641
 
364
642
  parameters: Type.Object({
365
- apiHost: Type.String({
366
- description:
367
- "Base URL including version prefix, e.g. 'https://api.github.com'.",
368
- }),
369
- path: Type.String({
370
- description:
371
- "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
372
- }),
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
+ ),
373
660
  params: Type.Optional(
374
661
  Type.Record(Type.String(), Type.Unknown(), {
375
662
  description:
376
663
  "Values for {token} path placeholders and query parameters. Path tokens are not re-declared as query params.",
377
664
  }),
378
665
  ),
379
- tryPrefixes: Type.Optional(
666
+ walkVersions: Type.Optional(
380
667
  Type.Boolean({
381
- 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.",
670
+ }),
671
+ ),
672
+ auth: Type.Optional(
673
+ Type.Object(
674
+ {
675
+ secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
676
+ secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
677
+ headerPrefixes: Type.Optional(Type.Record(Type.String(), Type.String())),
678
+ },
679
+ {
680
+ description:
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,
684
+ },
685
+ ),
686
+ ),
687
+ domain: Type.Optional(
688
+ Type.String({
689
+ description:
690
+ "Domain for secrets-store lookups; defaults to apiHost's hostname.",
691
+ }),
692
+ ),
693
+ listSecrets: Type.Optional(
694
+ Type.Boolean({
695
+ description:
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.",
382
701
  }),
383
702
  ),
384
703
  }),
385
704
 
386
705
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
387
- const { apiHost, path, tryPrefixes } = params as {
388
- apiHost: string;
389
- path: string;
706
+ const { apiHost, path, walkVersions, auth, domain, listSecrets } = params as {
707
+ apiHost?: string;
708
+ path?: string;
390
709
  params?: Record<string, unknown>;
391
- tryPrefixes?: boolean;
710
+ walkVersions?: boolean;
711
+ auth?: {
712
+ secretRefs?: Record<string, string>;
713
+ secretQueryRefs?: Record<string, string>;
714
+ };
715
+ domain?: string;
716
+ listSecrets?: boolean;
392
717
  };
393
718
  const userParams = (params as Record<string, unknown>)["params"] as
394
719
  | Record<string, unknown>
395
720
  | undefined;
396
721
 
722
+ // Learn-gated secrets discovery — short-circuits the fetch entirely.
723
+ // The agent's only programmatic path to the secrets store; /api secrets is
724
+ // user-typed only. Names only, never values.
725
+ if (listSecrets === true) {
726
+ if (!isApiLearnEnabled()) {
727
+ return {
728
+ content: [
729
+ {
730
+ type: "text",
731
+ text:
732
+ "api-probe: listSecrets: true is learn mode only — run /api learn first.",
733
+ },
734
+ ],
735
+ details: { error: "learn_mode_only" },
736
+ };
737
+ }
738
+ // Bare call (no domain, no apiHost): orphan list only. apiHost present:
739
+ // orphan list first, then the per-domain view. domain present: unchanged.
740
+ const unscoped = domain ? undefined : unscopedStoreDomains();
741
+ const blocks: string[] = [];
742
+ if (unscoped !== undefined) blocks.push(formatUnscopedDomains(unscoped));
743
+ const target = domain ?? (apiHost ? hostnameOf(apiHost) : undefined);
744
+ if (target !== undefined) {
745
+ const secrets = listDomainSecrets(target);
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
+ );
752
+ return {
753
+ content: [{ type: "text", text: blocks.join("\n\n") }],
754
+ details: unscoped === undefined ? { secrets } : { secrets, unscoped },
755
+ };
756
+ }
757
+ return {
758
+ content: [{ type: "text", text: blocks.join("\n\n") }],
759
+ details: { unscoped: unscoped! },
760
+ };
761
+ }
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
+
397
780
  try {
398
781
  const result = await probe(apiHost, path, userParams ?? {}, {
399
- ...(tryPrefixes !== undefined ? { tryPrefixes } : {}),
782
+ ...(walkVersions === undefined ? {} : { walkVersions }),
783
+ ...(auth ? { auth } : {}),
784
+ ...(domain ? { domain } : {}),
400
785
  });
401
786
  return {
402
787
  content: [{ type: "text", text: formatProbeResult(result) }],
@@ -439,6 +824,42 @@ export const apiProbeTool = defineTool({
439
824
  if (d?.error) {
440
825
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
441
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.
830
+ const secrets = d?.secrets as
831
+ | { domain: string; provisioned: string[] }
832
+ | undefined;
833
+ if (secrets) {
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
+ );
862
+ }
442
863
  const status = d?.status as number | undefined;
443
864
  const shape = d?.shape as ShapeSummary | null | undefined;
444
865
 
@@ -451,15 +872,7 @@ export const apiProbeTool = defineTool({
451
872
  : "";
452
873
  text += `\n${theme.fg("dim", `${shape.suggestedVia}${items}`)}`;
453
874
  }
454
-
455
- const content = contentText(result);
456
- if (expanded) {
457
- text += "\n";
458
- text = renderExpandedText(text, theme, content, 1000);
459
- } else {
460
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
461
- }
462
- return new Text(text, 0, 0);
875
+ return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
463
876
  },
464
877
  });
465
878
 
@@ -467,7 +880,12 @@ export const apiProbeTool = defineTool({
467
880
  // Result formatting
468
881
  // ═══════════════════════════════════════════════════════════════════
469
882
 
470
- 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 {
471
889
  const lines: string[] = [];
472
890
  lines.push(`🔬 api-probe — ${r.url}`);
473
891
  lines.push(` status: ${r.status}`);
@@ -478,8 +896,7 @@ function formatProbeResult(r: ProbeResult): string {
478
896
  lines.push(` shape: ${s.topLevel}`);
479
897
  if (s.keys.length > 0) lines.push(` keys: ${s.keys.join(", ")}`);
480
898
  lines.push(` via: ${s.suggestedVia}`);
481
- if (s.suggestedItemsPath)
482
- lines.push(` itemsPath: ${s.suggestedItemsPath}`);
899
+ if (s.suggestedItemsPath) lines.push(` itemsPath: ${s.suggestedItemsPath}`);
483
900
  if (s.arrayLen > 0) lines.push(` arrayLen: ${s.arrayLen}`);
484
901
  if (s.paginationMarkers.length > 0)
485
902
  lines.push(` pagination markers: ${s.paginationMarkers.join(", ")}`);
@@ -496,5 +913,63 @@ function formatProbeResult(r: ProbeResult): string {
496
913
  lines.push(` raw (truncated):`);
497
914
  lines.push(r.raw);
498
915
  }
916
+ lines.push("");
917
+ lines.push(` ${DOCS_NUDGE.join("\n ")}`);
918
+ return lines.join("\n");
919
+ }
920
+
921
+ /** Store domains that are provisioned but not scoped to any guide.
922
+ * Authoring-loop diagnostic: surfaces bootstrap + migration-orphan
923
+ * secrets. Names only. */
924
+ function unscopedStoreDomains(): string[] {
925
+ return listDomains().filter((d) => findGuidesByDomain(d).length === 0);
926
+ }
927
+
928
+ function formatUnscopedDomains(domains: string[]): string {
929
+ const lines: string[] = ["🗂 unscoped store domains (provisioned, no guide)"];
930
+ lines.push(` ${domains.length > 0 ? domains.join(", ") : "(none)"}`);
931
+ lines.push(" (names only — values never leave the store)");
932
+ return lines.join("\n");
933
+ }
934
+
935
+ /** List mode: provisioned secret names for a domain (names only). */
936
+ function listDomainSecrets(domain: string): {
937
+ domain: string;
938
+ provisioned: string[];
939
+ declared?: string[];
940
+ } {
941
+ const provisioned = listNames(domain);
942
+ const matches = findGuidesByDomain(domain);
943
+ if (matches.length === 0) return { domain, provisioned };
944
+ const declaredSet = new Set<string>();
945
+ for (const { guide } of matches) {
946
+ for (const n of [
947
+ ...(guide.auth.requires ?? []),
948
+ ...(guide.auth.optional ?? []),
949
+ ]) {
950
+ declaredSet.add(n);
951
+ }
952
+ }
953
+ const declared = [...declaredSet].sort();
954
+ return { domain, provisioned, declared };
955
+ }
956
+
957
+ function formatSecretsResult(s: {
958
+ domain: string;
959
+ provisioned: string[];
960
+ declared?: string[];
961
+ }): string {
962
+ const lines: string[] = [`🔑 secrets for ${s.domain}`];
963
+ lines.push(
964
+ ` provisioned: ${s.provisioned.length > 0 ? s.provisioned.join(", ") : "(none)"}`,
965
+ );
966
+ if (s.declared !== undefined) {
967
+ lines.push(
968
+ ` declared: ${s.declared.length > 0 ? s.declared.join(", ") : "(none)"}`,
969
+ );
970
+ const gaps = s.declared.filter((d) => !s.provisioned.includes(d));
971
+ if (gaps.length > 0) lines.push(` gaps: ${gaps.join(", ")}`);
972
+ }
973
+ lines.push(" (names only — values never leave the store)");
499
974
  return lines.join("\n");
500
975
  }