pi-lean-host 0.2.0 → 0.3.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.
@@ -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,13 @@ import {
29
29
  import {
30
30
  resolveSecretHeaders,
31
31
  resolveSecretQueryParams,
32
+ scrubSecretValues,
32
33
  } from "../core/auth.js";
33
34
  import { listDomains, listNames } from "../core/secrets-store.js";
34
35
  import { findGuidesByDomain } from "../core/guide-store.js";
35
- import { redactSecretParams } from "../core/helpers.js";
36
+ import { GUIDE_SCHEMA_VERSION } from "../core/api-guide-types.js";
36
37
  import { isApiLearnEnabled } from "../core/api-toggle.js";
37
- import { contentText, renderExpandedText } from "./utils.js";
38
+ import { appendFooter, contentText } from "./utils.js";
38
39
 
39
40
  // ═══════════════════════════════════════════════════════════════════
40
41
  // Types
@@ -70,24 +71,41 @@ export interface ProbeResult {
70
71
  raw: string;
71
72
  /** Human note (auth-required, 404, version-prefix hit, non-JSON, …). */
72
73
  note?: string;
74
+ /** True when the caller didn't pass scaffold: true and no guide claims the
75
+ * domain yet — the authoring loop should surface the skeleton option. */
76
+ scaffoldNudge?: boolean;
73
77
  }
74
78
 
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.
83
87
  * Values resolve from the secrets store and never enter the transcript.
84
88
  */
85
89
  auth?: {
90
+ /** Maps header name → secret name, same direction as the guide schema. */
86
91
  secretRefs?: Record<string, string>;
87
92
  secretQueryRefs?: Record<string, string>;
93
+ /**
94
+ * Header name → prefix prepended to the resolved secret value (e.g.
95
+ * `Authorization: "Bearer "`). The store holds the raw token; the prefix
96
+ * is API knowledge. Keys must be present in `secretRefs`.
97
+ */
98
+ headerPrefixes?: Record<string, string>;
88
99
  };
89
- /** Domain for secrets-store lookups; defaults to apiHost's hostname. */
100
+ /** Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain). */
90
101
  domain?: string;
102
+ /**
103
+ * Emit a full recipe skeleton (frontmatter + auth + operations) when no
104
+ * guide exists for the domain; auto-degrades to a single op block + merge
105
+ * note when one or more guides already claim the domain. Opt-in —
106
+ * without it the output is today's op-block-only draft.
107
+ */
108
+ scaffold?: boolean;
91
109
  }
92
110
 
93
111
  // ═══════════════════════════════════════════════════════════════════
@@ -159,7 +177,9 @@ export function summarize(data: unknown): ShapeSummary {
159
177
  }
160
178
 
161
179
  const arrayLen = items?.length ?? 0;
162
- const suggestedVia = items === null ? "restGet" : "paginate";
180
+ const hasPaginationSignal = paginationMarkers.length > 0;
181
+ const suggestedVia =
182
+ items === null || !hasPaginationSignal ? "restGet" : "paginate";
163
183
 
164
184
  const summary: ShapeSummary = {
165
185
  topLevel,
@@ -167,7 +187,7 @@ export function summarize(data: unknown): ShapeSummary {
167
187
  keys,
168
188
  arrayLen,
169
189
  suggestedVia,
170
- suggestedItemsPath: suggestedVia === "paginate" ? itemsPath : "",
190
+ suggestedItemsPath: items === null ? "" : itemsPath,
171
191
  paginationMarkers,
172
192
  };
173
193
  const representativeId = pickRepresentativeId(items);
@@ -212,6 +232,9 @@ interface ProbeAuthCtx {
212
232
  secretQueryParamNames: Set<string>;
213
233
  secretValues: string[];
214
234
  missingNames: string[];
235
+ /** headerPrefixes declared but no secretRefs to apply them to — the
236
+ * prefixes would be silently dropped. Surfaced as a note, not an error. */
237
+ misconfiguredPrefixes: boolean;
215
238
  }
216
239
 
217
240
  /**
@@ -225,6 +248,16 @@ function resolveProbeAuth(
225
248
  auth: NonNullable<ProbeOptions["auth"]> | undefined,
226
249
  domain: string,
227
250
  ): ProbeAuthCtx {
251
+ // Computed before the hasRefs check so the flag survives both paths: a
252
+ // headerPrefixes-only block (hasRefs false → early return) and a
253
+ // secretQueryRefs block with prefixes but no secretRefs (hasRefs true →
254
+ // normal path, where resolveSecretHeaders would silently drop the
255
+ // prefixes). Query secrets never take prefixes, so secretQueryRefs is
256
+ // deliberately excluded from the flag.
257
+ const misconfiguredPrefixes =
258
+ !!auth &&
259
+ Object.keys(auth.headerPrefixes ?? {}).length > 0 &&
260
+ Object.keys(auth.secretRefs ?? {}).length === 0;
228
261
  const hasRefs =
229
262
  !!auth &&
230
263
  (Object.keys(auth.secretRefs ?? {}).length > 0 ||
@@ -238,12 +271,14 @@ function resolveProbeAuth(
238
271
  secretQueryParamNames: new Set(),
239
272
  secretValues: [],
240
273
  missingNames: [],
274
+ misconfiguredPrefixes,
241
275
  };
242
276
  }
243
277
  const headerRes = resolveSecretHeaders(
244
278
  {
245
279
  kind: "static-key",
246
280
  ...(auth!.secretRefs ? { secretRefs: auth!.secretRefs } : {}),
281
+ ...(auth!.headerPrefixes ? { headerPrefixes: auth!.headerPrefixes } : {}),
247
282
  },
248
283
  domain,
249
284
  );
@@ -264,6 +299,7 @@ function resolveProbeAuth(
264
299
  secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
265
300
  secretValues: [
266
301
  ...Object.values(headerRes.headers),
302
+ ...headerRes.rawHeaderValues,
267
303
  ...Object.values(queryRes.queryParams),
268
304
  ],
269
305
  missingNames: [
@@ -272,13 +308,43 @@ function resolveProbeAuth(
272
308
  ...queryRes.absentRequired,
273
309
  ...queryRes.absentOptional,
274
310
  ],
311
+ misconfiguredPrefixes,
275
312
  };
276
313
  }
277
314
 
278
- /** First missing secret name as a one-line note (names only, never values). */
315
+ /** Root-cause note for a headerPrefixes-only auth block (no secretRefs to
316
+ * apply the prefixes to). `:`/`;` internal separators keep the combined
317
+ * error note from stacking three ` — ` joins when it composes with the
318
+ * 401/403 wording. */
319
+ const MISCONFIGURED_PREFIXES_NOTE =
320
+ "headerPrefixes ignored: no secretRefs to apply them to; put the secret name in auth.secretRefs";
321
+
322
+ /** First missing secret name as a one-line note (names only, never values).
323
+ * Prescriptive: names the other provisioned domains and tells the author to
324
+ * pass `domain:` — the probe's domain is inferred from apiHost, so a miss is
325
+ * usually a domain-mismatch, not a missing secret. */
279
326
  function missNote(authCtx: ProbeAuthCtx, domain: string): string {
280
327
  if (authCtx.missingNames.length === 0) return "";
281
- return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"`;
328
+ const others = listDomains().filter((d) => d !== domain);
329
+ const tail =
330
+ others.length > 0
331
+ ? ` — provisioned domains: ${others.join(", ")}; pass domain: <one> to use its secret`
332
+ : "";
333
+ return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"${tail}`;
334
+ }
335
+
336
+ /** Resolve the secrets-store domain for a probe: the apiHost hostname when it
337
+ * is itself provisioned, else the longest provisioned parent domain
338
+ * (pro-api.coinmarketcap.com → coinmarketcap.com), else the hostname as-is.
339
+ * ponytail: parent-suffix match against the store, not a public-suffix list —
340
+ * no dep, and the store is the source of truth for where secrets live. */
341
+ export function resolveProbeStoreDomain(hostname: string): string {
342
+ const domains = listDomains();
343
+ if (domains.includes(hostname)) return hostname;
344
+ const parent = domains
345
+ .filter((d) => hostname.endsWith(`.${d}`))
346
+ .sort((a, b) => b.length - a.length)[0];
347
+ return parent ?? hostname;
282
348
  }
283
349
 
284
350
  /** Hostname of an apiHost URL (falls back to the raw string). */
@@ -290,6 +356,17 @@ function hostnameOf(apiHost: string): string {
290
356
  }
291
357
  }
292
358
 
359
+ /** Trailing path of an apiHost URL (e.g. `/v3`), or `""` when empty/root.
360
+ * Trailing slashes stripped so `.../v3/` + `/items` → `/v3/items`, not `/v3//items`.
361
+ * Lets the probe draft carry the version prefix that was actually fetched. */
362
+ function versionPrefixOf(apiHost: string): string {
363
+ try {
364
+ return new URL(apiHost).pathname.replace(/\/+$/, "");
365
+ } catch {
366
+ return "";
367
+ }
368
+ }
369
+
293
370
  export async function probe(
294
371
  apiHost: string,
295
372
  path: string,
@@ -297,22 +374,105 @@ export async function probe(
297
374
  opts: ProbeOptions = {},
298
375
  ): Promise<ProbeResult> {
299
376
  const accept = opts.accept ?? "application/json";
300
- const tryPrefixes = opts.tryPrefixes ?? true;
301
- const domain = opts.domain ?? hostnameOf(apiHost);
377
+ const walkVersions = opts.walkVersions ?? true;
378
+ const domain = opts.domain ?? resolveProbeStoreDomain(hostnameOf(apiHost));
302
379
  const authCtx = resolveProbeAuth(opts.auth, domain);
303
380
 
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
- }
381
+ // Base case only carries the apiHost version prefix; a walk-hit draft
382
+ // embeds its walked version in the prefix passed to fetchOne.
383
+ const base = await fetchOne(
384
+ apiHost,
385
+ path,
386
+ params,
387
+ accept,
388
+ authCtx,
389
+ domain,
390
+ versionPrefixOf(apiHost),
391
+ opts,
392
+ );
393
+ if (base.status !== 404 || !walkVersions || /^\/v\d+\//.test(path)) {
394
+ return base;
395
+ }
396
+ // Recover an over-claimed version by walking the apiHost version backward
397
+ // (vN-1 → … → 1). Only fires on 404 — never a poller on a live 200.
398
+ const stated = VERSION_PATHNAME_RE.exec(versionPrefixOf(apiHost))?.[1];
399
+ if (stated === undefined) {
400
+ // Gate excludes a bare / non-integer / subdomain-versioned host — no
401
+ // walk to run, so tell the agent why rather than a silent bare 404.
402
+ base.note = walkSkipNote(authCtx, domain);
403
+ return base;
404
+ }
405
+ const hit = await walkBackward(
406
+ { apiHost, path, params, accept, authCtx, domain, opts },
407
+ Number(stated),
408
+ );
409
+ return hit ?? base;
410
+ }
411
+
412
+ // ponytail: MAX_VERSION_WALK caps a high-version host's request burst
413
+ // (a /v10 host fires at most 5 backward walks, not 9); raise it if a longer
414
+ // version-gap chain is ever needed.
415
+ export const MAX_VERSION_WALK = 5;
416
+
417
+ /** Matches a pure integer version pathname (`/v3`), excluding date/non-numeric
418
+ * /subdomain /multi-segment conventions — the only form the walk can swap. */
419
+ const VERSION_PATHNAME_RE = /^\/v(\d+)$/;
420
+
421
+ /** Backward version walk: refetch the same bare path with /vN-… swapped into
422
+ * apiHost; return the first non-404 (with a version-walk note) or null. */
423
+ async function walkBackward(
424
+ ctx: {
425
+ apiHost: string;
426
+ path: string;
427
+ params: Record<string, unknown>;
428
+ accept: string;
429
+ authCtx: ProbeAuthCtx;
430
+ domain: string;
431
+ opts: ProbeOptions;
432
+ },
433
+ start: number,
434
+ ): Promise<ProbeResult | null> {
435
+ const miss = missNote(ctx.authCtx, ctx.domain);
436
+ const floor = Math.max(start - MAX_VERSION_WALK, 1);
437
+ for (let k = start - 1; k >= floor; k--) {
438
+ const tried = await fetchOne(
439
+ withVersion(ctx.apiHost, k),
440
+ ctx.path,
441
+ ctx.params,
442
+ ctx.accept,
443
+ ctx.authCtx,
444
+ ctx.domain,
445
+ `/v${k}`,
446
+ ctx.opts,
447
+ );
448
+ if (tried.status !== 404) {
449
+ // A walk hit may itself have redirected (e.g. /v2 301→ /v3); the
450
+ // draft carries /v${k} while the body came from elsewhere — flag
451
+ // it so the agent checks finalUrl instead of trusting the prefix.
452
+ const redirected = tried.finalUrl !== tried.url;
453
+ tried.note = `${miss ? miss + " — " : ""}404 on /v${start}${ctx.path}; version walk → /v${k}${redirected ? " — verify finalUrl (redirect target)" : ""}`;
454
+ return tried;
313
455
  }
314
456
  }
315
- return base;
457
+ return null;
458
+ }
459
+
460
+ /** apiHost with the version segment swapped via the URL API — never a
461
+ * string-replace (the version string could appear elsewhere in the host). */
462
+ function withVersion(apiHost: string, k: number): string {
463
+ try {
464
+ const u = new URL(apiHost);
465
+ u.pathname = `/v${k}`;
466
+ return `${u.origin}${u.pathname}`;
467
+ } catch {
468
+ return apiHost;
469
+ }
470
+ }
471
+
472
+ /** The gate-excluded 404 note (bare / non-integer / subdomain version hosts). */
473
+ function walkSkipNote(authCtx: ProbeAuthCtx, domain: string): string {
474
+ const miss = missNote(authCtx, domain);
475
+ return `${miss ? miss + " — " : ""}404 — no version walk (apiHost has no /vN prefix)`;
316
476
  }
317
477
 
318
478
  async function fetchOne(
@@ -322,6 +482,8 @@ async function fetchOne(
322
482
  accept: string,
323
483
  authCtx: ProbeAuthCtx,
324
484
  domain: string,
485
+ prefix = "",
486
+ opts: ProbeOptions = {},
325
487
  ): Promise<ProbeResult> {
326
488
  // Inject secret query params below the agent-supplied params map, then
327
489
  // redact the surfaced URL so the real key never reaches the transcript.
@@ -341,10 +503,7 @@ async function fetchOne(
341
503
  // Probe-local body scrub: the probe bypasses checkResponseStatus, so
342
504
  // scrub known secret values from the raw slice directly — a 401 body
343
505
  // 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
- }
506
+ const raw = scrubSecretValues(res.body.slice(0, 800), authCtx.secretValues);
348
507
  const finalUrl = redactSecretParams(
349
508
  res.finalUrl ?? rawUrl,
350
509
  authCtx.secretQueryParamNames,
@@ -354,16 +513,26 @@ async function fetchOne(
354
513
  const is401 = res.status === 401 || res.status === 403;
355
514
  const miss = missNote(authCtx, domain);
356
515
  let note: string;
357
- if (authCtx.hasAuthBlock) {
358
- // Auth block present → never the stale auth:none text; report the
359
- // store miss (or a bare requires-auth hint when nothing was missing).
360
- note = `${res.status}${is401 ? " — requires authentication?" : ""}${miss ? ` ${miss}` : ""}`;
516
+ if (!authCtx.hasAuthBlock) {
517
+ // No auth injected — a 401/403 means the endpoint is gated and the
518
+ // probe sent nothing. Pre-guide authoring tool: no guide in scope,
519
+ // so no stale "(guide is auth:none)" wording.
520
+ note = is401
521
+ ? `${res.status} — endpoint requires auth; configure auth injection (auth.secretRefs)`
522
+ : `${res.status}`;
523
+ } else if (miss) {
524
+ // Auth injected but a required secret was missing — the miss names it.
525
+ note = `${res.status}${is401 ? " — auth rejected;" : ""} ${miss}`;
361
526
  } else {
362
- // No auth block → the existing auth:none wording.
527
+ // Auth injected, nothing missing — rejection means the credentials
528
+ // were wrong (header name / secret value), not the endpoint.
363
529
  note = is401
364
- ? `${res.status} — requires authentication? (guide is auth:none)`
530
+ ? `${res.status} — auth injected but rejected; verify header name and secret value`
365
531
  : `${res.status}`;
366
532
  }
533
+ if (authCtx.misconfiguredPrefixes) {
534
+ note += ` — ${MISCONFIGURED_PREFIXES_NOTE}`;
535
+ }
367
536
  return {
368
537
  url,
369
538
  finalUrl,
@@ -395,23 +564,48 @@ async function fetchOne(
395
564
 
396
565
  const shape = summarize(data);
397
566
  const miss = missNote(authCtx, domain);
567
+ let draft = emitDraft(path, params, shape, prefix);
568
+ let note: string | undefined = miss;
569
+ if (opts.scaffold && draft) {
570
+ const sc = emitScaffold({ apiHost, domain, draft, auth: opts.auth });
571
+ draft = sc.draft;
572
+ if (sc.note) note = [note, sc.note].filter(Boolean).join(" — ");
573
+ }
574
+ if (authCtx.misconfiguredPrefixes) {
575
+ note = [note, MISCONFIGURED_PREFIXES_NOTE].filter(Boolean).join(" — ");
576
+ }
577
+ // Targeted scaffold nudge: only when the caller didn't pass
578
+ // scaffold: true AND no guide claims the domain yet — authors who already
579
+ // used the skeleton (or who have a guide) see no noise.
580
+ const scaffoldNudge =
581
+ opts.scaffold !== true && findGuidesByDomain(domain).length === 0;
398
582
  return {
399
583
  url,
400
584
  finalUrl,
401
585
  status: res.status,
402
586
  ok: true,
403
587
  shape,
404
- draft: emitDraft(path, params, shape),
588
+ draft,
405
589
  raw,
406
- ...(miss ? { note: miss } : {}),
590
+ ...(note ? { note } : {}),
591
+ ...(scaffoldNudge ? { scaffoldNudge } : {}),
407
592
  };
408
593
  }
409
594
 
595
+ const RESERVED_PARAM_NAMES = new Set(["domain", "apiHost", "path", "auth"]);
596
+
410
597
  function buildUrl(
411
598
  apiHost: string,
412
599
  path: string,
413
600
  params: Record<string, unknown>,
414
601
  ): string {
602
+ for (const key of Object.keys(params)) {
603
+ if (RESERVED_PARAM_NAMES.has(key)) {
604
+ throw new Error(
605
+ `"${key}" is a top-level param, not a query param — move it out of params`,
606
+ );
607
+ }
608
+ }
415
609
  // Substitute {token} → params[token] BEFORE building the URL, so a
416
610
  // templated path fetches real values instead of literal %7Bowner%7D.
417
611
  // Missing tokens stay literal ({token}) — fine for probing an unfilled path.
@@ -435,7 +629,11 @@ export function emitDraft(
435
629
  path: string,
436
630
  params: Record<string, unknown>,
437
631
  shape: ShapeSummary,
632
+ prefix = "",
438
633
  ): string {
634
+ // Idempotent: only prepend when the path doesn't already carry the prefix,
635
+ // so `apiHost: .../v3` + `path: /v3/items` doesn't become `/v3/v3/items`.
636
+ if (prefix && !path.startsWith(prefix)) path = prefix + path;
439
637
  const name = suggestName(path);
440
638
  const pathTokens = extractPathTokens(path);
441
639
  const queryParamKeys = Object.keys(params).filter(
@@ -452,19 +650,34 @@ export function emitDraft(
452
650
  lines.push(
453
651
  " # unverified — pagination params are guessed from response keys; confirm the API accepts them",
454
652
  );
455
- const style =
456
- shape.paginationMarkers.includes("page") ||
457
- shape.paginationMarkers.includes("per_page")
458
- ? "page"
459
- : "offset-limit";
460
- const pageParam = style === "page" ? "page" : "offset";
461
- const pageSizeParam = style === "page" ? "per_page" : "limit";
653
+ const markers = shape.paginationMarkers;
654
+ const isPageStyle = markers.includes("page") || markers.includes("per_page");
655
+ const style = isPageStyle ? "page" : "offset-limit";
656
+ // `start` marker ⇒ 1-based row offset (CMC, GBIF) — emit base: 1 so the
657
+ // first page starts at 1, not the 0 default. `offset` ⇒ 0-based, no base.
658
+ let pageParam: string;
659
+ if (isPageStyle) pageParam = "page";
660
+ else if (markers.includes("start")) pageParam = "start";
661
+ else pageParam = "offset";
662
+ const pageSizeParam = isPageStyle ? "per_page" : "limit";
663
+ if (style === "offset-limit") {
664
+ lines.push(
665
+ " # offset-limit advances the page param by pageSize each page (row-offset semantics); base seeds the start (1 for `start` params, 0 for `offset`)",
666
+ );
667
+ }
462
668
  lines.push(" pagination:");
463
669
  lines.push(` style: ${style}`);
464
670
  lines.push(` itemsPath: ${shape.suggestedItemsPath}`);
465
671
  lines.push(` pageParam: ${pageParam}`);
466
672
  lines.push(` pageSizeParam: ${pageSizeParam}`);
467
673
  lines.push(" pageSize: 30");
674
+ if (pageParam === "start") lines.push(" base: 1");
675
+ }
676
+ if (shape.suggestedVia === "restGet" && shape.suggestedItemsPath !== "") {
677
+ lines.push(
678
+ " # array response with no pagination markers — if the API documents paging, prefer paginate:",
679
+ " # offset-limit advances the page param by pageSize each page (use base: 1 for 1-based `start` APIs like CMC); page increments the page param by 1.",
680
+ );
468
681
  }
469
682
  if (queryParamKeys.length > 0) {
470
683
  lines.push(" params:");
@@ -490,6 +703,112 @@ function suggestName(path: string): string {
490
703
  .replace(/[^a-zA-Z0-9]/g, "");
491
704
  }
492
705
 
706
+ // ═══════════════════════════════════════════════════════════════════
707
+ // Scaffold emission — full skeleton vs op-block + merge note
708
+ // ═══════════════════════════════════════════════════════════════════
709
+
710
+ /**
711
+ * Translate the probe's auth-injection params into a `kind: static-key` auth
712
+ * block (probe auth shape matches the guide schema).
713
+ * `requires` = the union of secret names referenced by the refs. Returns
714
+ * undefined when no injection refs are declared (auth: none default).
715
+ */
716
+ function emitAuthBlock(
717
+ auth: NonNullable<ProbeOptions["auth"]> | undefined,
718
+ ): string | undefined {
719
+ const refs = auth?.secretRefs ?? {};
720
+ const queryRefs = auth?.secretQueryRefs ?? {};
721
+ const prefixes = auth?.headerPrefixes ?? {};
722
+ const names = [
723
+ ...new Set([...Object.values(refs), ...Object.values(queryRefs)]),
724
+ ];
725
+ if (names.length === 0) return undefined;
726
+ const lines = [
727
+ "auth:",
728
+ " kind: static-key",
729
+ ` requires: [${names.join(", ")}]`,
730
+ ];
731
+ if (Object.keys(refs).length > 0) {
732
+ lines.push(" secretRefs:");
733
+ for (const [header, secret] of Object.entries(refs))
734
+ lines.push(` ${header}: ${secret}`);
735
+ }
736
+ if (Object.keys(queryRefs).length > 0) {
737
+ lines.push(" secretQueryRefs:");
738
+ for (const [param, secret] of Object.entries(queryRefs))
739
+ lines.push(` ${param}: ${secret}`);
740
+ }
741
+ if (Object.keys(prefixes).length > 0) {
742
+ lines.push(" headerPrefixes:");
743
+ for (const [header, prefix] of Object.entries(prefixes))
744
+ lines.push(` ${header}: "${prefix}"`);
745
+ }
746
+ return lines.join("\n");
747
+ }
748
+
749
+ /**
750
+ * Full recipe skeleton (bootstrap): frontmatter + auth + the probe's op
751
+ * block. `schemaVersion` literal matches what api-learn stamps on save, so a
752
+ * scaffolded guide is detection-ready the moment it's saved. Pagination stays
753
+ * op-level only (a single probe justifies one op's pagination, never a
754
+ * top-level default).
755
+ */
756
+ function emitScaffoldSkeleton(opts: {
757
+ apiHost: string;
758
+ domain: string;
759
+ draft: string;
760
+ auth: ProbeOptions["auth"];
761
+ }): string {
762
+ const lines = [
763
+ "---",
764
+ "kind: api",
765
+ `domains: [${opts.domain}]`,
766
+ `apiHost: ${opts.apiHost}`,
767
+ "responseShape:",
768
+ " format: json",
769
+ "gatherAllMax: 1000",
770
+ `schemaVersion: ${GUIDE_SCHEMA_VERSION}`,
771
+ ];
772
+ const authBlock = emitAuthBlock(opts.auth);
773
+ if (authBlock) lines.push("", authBlock);
774
+ // Op-level hint for the new constraint field — commented so a fresh
775
+ // scaffold surfaces the mechanism (mirrors placeholderSkeleton).
776
+ lines.push(
777
+ "",
778
+ "# requiresAnyOf: [id, slug, code] # at least one of these params must be supplied",
779
+ "operations:",
780
+ opts.draft,
781
+ "---",
782
+ "",
783
+ );
784
+ return lines.join("\n");
785
+ }
786
+
787
+ /**
788
+ * Scaffold decision, driven by findGuidesByDomain(domain): 0 guides →
789
+ * full skeleton (bootstrap); 1 guide → op block + merge note naming the one
790
+ * dirName; N guides → op block + merge note listing every candidate dirName
791
+ * (the merge-target choice defers to api-learn's selector). Returns the
792
+ * paste-able draft + an optional human merge note.
793
+ */
794
+ function emitScaffold(opts: {
795
+ apiHost: string;
796
+ domain: string;
797
+ draft: string;
798
+ auth: ProbeOptions["auth"];
799
+ }): { draft: string; note?: string } {
800
+ const matches = findGuidesByDomain(opts.domain);
801
+ if (matches.length === 0) {
802
+ return { draft: emitScaffoldSkeleton(opts) };
803
+ }
804
+ const dirs = matches.map((m) => m.dirName);
805
+ const note =
806
+ matches.length === 1
807
+ ? `scaffold: guide already exists — merge into \`${dirs[0]}\``
808
+ : `scaffold: ${matches.length} guides already exist — merge into one of: ${dirs.join(", ")}`;
809
+ return { draft: opts.draft, note };
810
+ }
811
+
493
812
  // ═══════════════════════════════════════════════════════════════════
494
813
  // Tool definition
495
814
  // ═══════════════════════════════════════════════════════════════════
@@ -504,26 +823,56 @@ export const apiProbeTool = defineTool({
504
823
  "a draft YAML operation block to paste into a guide recipe. " +
505
824
  "It only suggests — it never writes the guide, and the operation must still be " +
506
825
  "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.",
826
+ "exists, use api-guide({domain}) to get apiHost, or api-fetch to execute. " +
827
+ "Before the first auth-gated probe, call with listSecrets: true (and no domain) " +
828
+ "to list every provisioned store domain and which already have guides — pass that " +
829
+ "domain up front so a store-miss round-trip is avoided. " +
830
+ "Before authoring a new guide, read the provider's docs index (llms.txt, " +
831
+ "openapi.json at the API root, or the docs page) to learn the current API " +
832
+ "version — then probe that version explicitly. Do not default the version from " +
833
+ "memory: a stale version that still returns 200 is not detected as old (the " +
834
+ "backward walk only fires on 404). The probe recovers an over-claimed version " +
835
+ "but cannot detect a stale-but-working one. " +
836
+ "Pass scaffold: true to emit a full recipe skeleton (frontmatter + auth + " +
837
+ "operations) when no guide exists for the domain; it auto-degrades to a single " +
838
+ "op block + merge note when one or more guides already claim the domain.",
508
839
 
509
840
  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
- }),
841
+ apiHost: Type.Optional(
842
+ Type.String({
843
+ description:
844
+ "Base URL including the API's current version prefix, e.g. " +
845
+ "'https://api.example.com/v3'. Find the latest version before probing: " +
846
+ "check the API's docs page, openapi.json/swagger.json at the API root, " +
847
+ "or llms.txt. Supply the newest version you can verify — if it 404s, the " +
848
+ "probe walks backward (v3→v2→v1) to recover. Do not default to /v1 from " +
849
+ "memory; a stale version that still returns 200 is not detected as old.",
850
+ }),
851
+ ),
852
+ path: Type.Optional(
853
+ Type.String({
854
+ description:
855
+ "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
856
+ }),
857
+ ),
518
858
  params: Type.Optional(
519
859
  Type.Record(Type.String(), Type.Unknown(), {
520
860
  description:
521
861
  "Values for {token} path placeholders and query parameters. Path tokens are not re-declared as query params.",
522
862
  }),
523
863
  ),
524
- tryPrefixes: Type.Optional(
864
+ walkVersions: Type.Optional(
865
+ Type.Boolean({
866
+ description:
867
+ "On 404, walk the apiHost version backward (vN→v1) to find the highest live version. Default true.",
868
+ }),
869
+ ),
870
+ scaffold: Type.Optional(
525
871
  Type.Boolean({
526
- description: "On 404, auto-try /v1/ and /v2/ prefixes. Default true.",
872
+ description:
873
+ "Emit a full recipe skeleton (frontmatter + auth + operations) when no guide exists for the domain; " +
874
+ "auto-degrades to a single op block + merge note when one or more guides already claim the domain. " +
875
+ "Opt-in — without it the output is today's op-block-only draft.",
527
876
  }),
528
877
  ),
529
878
  auth: Type.Optional(
@@ -531,40 +880,52 @@ export const apiProbeTool = defineTool({
531
880
  {
532
881
  secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
533
882
  secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
883
+ headerPrefixes: Type.Optional(Type.Record(Type.String(), Type.String())),
534
884
  },
535
885
  {
536
886
  description:
537
- "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.",
887
+ "Store-backed auth injection for probing auth-gated endpoints (authoring loop). Accepts only secretRefs, secretQueryRefs, and headerPrefixes. Values resolve from the secrets store and never enter the transcript; a store miss fetches unauthenticated and reports the miss in the note.",
888
+ // Tight: unknown keys (e.g. a stray `domain`) are rejected before execute runs.
889
+ // The description above names the allowed fields explicitly — keep it in
890
+ // sync when adding/renaming a field here, or the prose lies to agents.
891
+ additionalProperties: false,
538
892
  },
539
893
  ),
540
894
  ),
541
895
  domain: Type.Optional(
542
896
  Type.String({
543
897
  description:
544
- "Domain for secrets-store lookups; defaults to apiHost's hostname.",
898
+ "Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain).",
545
899
  }),
546
900
  ),
547
901
  listSecrets: Type.Optional(
548
902
  Type.Boolean({
549
903
  description:
550
- "Learn mode only: list provisioned secret names for the domain (no fetch). Names only, never values. Refused under /api on.",
904
+ "Names only, never values. Two modes: with no domain/apiHost, lists " +
905
+ "provisioned-but-guideless store domains (authoring-bootstrap view — " +
906
+ "call this empty first to see what's provisioned); with a domain (or " +
907
+ "apiHost), lists provisioned secret names for that domain, with " +
908
+ "declared-vs-stored gaps when a guide exists.",
551
909
  }),
552
910
  ),
553
911
  }),
554
912
 
555
913
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
556
- const { apiHost, path, tryPrefixes, auth, domain, listSecrets } = params as {
557
- apiHost: string;
558
- path: string;
559
- params?: Record<string, unknown>;
560
- tryPrefixes?: boolean;
561
- auth?: {
562
- secretRefs?: Record<string, string>;
563
- secretQueryRefs?: Record<string, string>;
914
+ const { apiHost, path, walkVersions, auth, domain, listSecrets, scaffold } =
915
+ params as {
916
+ apiHost?: string;
917
+ path?: string;
918
+ params?: Record<string, unknown>;
919
+ walkVersions?: boolean;
920
+ auth?: {
921
+ secretRefs?: Record<string, string>;
922
+ secretQueryRefs?: Record<string, string>;
923
+ headerPrefixes?: Record<string, string>;
924
+ };
925
+ domain?: string;
926
+ listSecrets?: boolean;
927
+ scaffold?: boolean;
564
928
  };
565
- domain?: string;
566
- listSecrets?: boolean;
567
- };
568
929
  const userParams = (params as Record<string, unknown>)["params"] as
569
930
  | Record<string, unknown>
570
931
  | undefined;
@@ -590,10 +951,17 @@ export const apiProbeTool = defineTool({
590
951
  const unscoped = domain ? undefined : unscopedStoreDomains();
591
952
  const blocks: string[] = [];
592
953
  if (unscoped !== undefined) blocks.push(formatUnscopedDomains(unscoped));
593
- const target = domain ?? (apiHost ? hostnameOf(apiHost) : undefined);
954
+ const target =
955
+ domain ??
956
+ (apiHost ? resolveProbeStoreDomain(hostnameOf(apiHost)) : undefined);
594
957
  if (target !== undefined) {
595
958
  const secrets = listDomainSecrets(target);
596
959
  blocks.push(formatSecretsResult(secrets));
960
+ // apiHost/domain present means a real probe was suppressed by
961
+ // listSecrets: true — say so, or the author silently loses the probe.
962
+ blocks.push(
963
+ "probe suppressed because listSecrets: true — drop listSecrets to probe.",
964
+ );
597
965
  return {
598
966
  content: [{ type: "text", text: blocks.join("\n\n") }],
599
967
  details: unscoped === undefined ? { secrets } : { secrets, unscoped },
@@ -605,11 +973,29 @@ export const apiProbeTool = defineTool({
605
973
  };
606
974
  }
607
975
 
976
+ // apiHost/path are optional in the schema so the bare listSecrets call is
977
+ // legal; every real probe needs both. The schema no longer enforces it,
978
+ // so guard here before falling through to probe(). (The listSecrets:true
979
+ // branch always returns above, so this guard only sees non-listSecrets.)
980
+ if (!apiHost || !path) {
981
+ return {
982
+ content: [
983
+ {
984
+ type: "text",
985
+ text:
986
+ "api-probe: apiHost and path are required unless listSecrets: true.",
987
+ },
988
+ ],
989
+ details: { error: "missing_apiHost_or_path" },
990
+ };
991
+ }
992
+
608
993
  try {
609
994
  const result = await probe(apiHost, path, userParams ?? {}, {
610
- ...(tryPrefixes === undefined ? {} : { tryPrefixes }),
995
+ ...(walkVersions === undefined ? {} : { walkVersions }),
611
996
  ...(auth ? { auth } : {}),
612
997
  ...(domain ? { domain } : {}),
998
+ ...(scaffold === undefined ? {} : { scaffold }),
613
999
  });
614
1000
  return {
615
1001
  content: [{ type: "text", text: formatProbeResult(result) }],
@@ -643,6 +1029,7 @@ export const apiProbeTool = defineTool({
643
1029
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-probe "))];
644
1030
  if (args.apiHost) parts.push(theme.fg("accent", `"${args.apiHost}"`));
645
1031
  if (args.path) parts.push(theme.fg("dim", `› ${args.path}`));
1032
+ if (args.scaffold) parts.push(theme.fg("dim", "· scaffold"));
646
1033
  return new Text(parts.join(" "), 0, 0);
647
1034
  },
648
1035
 
@@ -652,20 +1039,41 @@ export const apiProbeTool = defineTool({
652
1039
  if (d?.error) {
653
1040
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
654
1041
  }
1042
+ // Secrets first: the domain-scoped view is the primary output and is present
1043
+ // for both the per-domain and combined (apiHost-no-domain) shapes. Only the
1044
+ // bare call (no domain/apiHost) carries unscoped alone.
655
1045
  const secrets = d?.secrets as
656
1046
  | { domain: string; provisioned: string[] }
657
1047
  | undefined;
658
1048
  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);
1049
+ const text = theme.fg("accent", theme.bold("🔑 api-probe"));
1050
+ return new Text(
1051
+ appendFooter(
1052
+ text +
1053
+ ` — secrets for ${secrets.domain} · ${secrets.provisioned.length} provisioned`,
1054
+ expanded,
1055
+ result,
1056
+ theme,
1057
+ 1000,
1058
+ ),
1059
+ 0,
1060
+ 0,
1061
+ );
1062
+ }
1063
+ const unscoped = d?.unscoped as string[] | undefined;
1064
+ if (unscoped) {
1065
+ const text = theme.fg("accent", theme.bold("🔑 api-probe"));
1066
+ return new Text(
1067
+ appendFooter(
1068
+ text + ` — ${unscoped.length} unscoped domains`,
1069
+ expanded,
1070
+ result,
1071
+ theme,
1072
+ 1000,
1073
+ ),
1074
+ 0,
1075
+ 0,
1076
+ );
669
1077
  }
670
1078
  const status = d?.status as number | undefined;
671
1079
  const shape = d?.shape as ShapeSummary | null | undefined;
@@ -679,15 +1087,7 @@ export const apiProbeTool = defineTool({
679
1087
  : "";
680
1088
  text += `\n${theme.fg("dim", `${shape.suggestedVia}${items}`)}`;
681
1089
  }
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);
1090
+ return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
691
1091
  },
692
1092
  });
693
1093
 
@@ -695,7 +1095,12 @@ export const apiProbeTool = defineTool({
695
1095
  // Result formatting
696
1096
  // ═══════════════════════════════════════════════════════════════════
697
1097
 
698
- function formatProbeResult(r: ProbeResult): string {
1098
+ const DOCS_NUDGE = [
1099
+ "probe validates shape only — it cannot enumerate endpoints.",
1100
+ "For a full guide, read the API's docs index (e.g. llms.txt or per-endpoint .md).",
1101
+ ];
1102
+
1103
+ export function formatProbeResult(r: ProbeResult): string {
699
1104
  const lines: string[] = [];
700
1105
  lines.push(`🔬 api-probe — ${r.url}`);
701
1106
  lines.push(` status: ${r.status}`);
@@ -723,6 +1128,14 @@ function formatProbeResult(r: ProbeResult): string {
723
1128
  lines.push(` raw (truncated):`);
724
1129
  lines.push(r.raw);
725
1130
  }
1131
+ lines.push("");
1132
+ const footer = [...DOCS_NUDGE];
1133
+ if (r.scaffoldNudge) {
1134
+ footer.push(
1135
+ "No guide for this domain yet — pass scaffold: true to emit a full recipe skeleton.",
1136
+ );
1137
+ }
1138
+ lines.push(` ${footer.join("\n ")}`);
726
1139
  return lines.join("\n");
727
1140
  }
728
1141