pi-lean-host 0.4.0 → 0.6.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.
@@ -18,24 +18,43 @@
18
18
  */
19
19
 
20
20
  import { defineTool } from "@earendil-works/pi-coding-agent";
21
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
+ import { confirmTokenUrl } from "../core/oauth-flow.js";
21
23
  import { Type } from "@earendil-works/pi-ai";
22
24
  import { Text } from "@earendil-works/pi-tui";
23
- import { fetchUrl, redactSecretParams } from "../core/transport.js";
25
+ import {
26
+ fetchUrl,
27
+ redactSecretParams,
28
+ redactSecretPathValues,
29
+ } from "../core/transport.js";
30
+ import { splitPathSecretParams } from "../core/helpers.js";
24
31
  import {
25
32
  extractPathTokens,
26
33
  fillPathTemplate,
27
34
  joinUrl,
28
35
  } from "../core/path-template.js";
29
36
  import {
37
+ assertNoBearerCollision,
38
+ buildSyntheticOAuth2Auth,
39
+ hostnameOf,
40
+ isTokenExpired,
41
+ pathScrubValues,
42
+ resolveAccessToken,
43
+ resolveProvisionedParentDomain,
30
44
  resolveSecretHeaders,
45
+ resolveSecretPathParams,
31
46
  resolveSecretQueryParams,
32
47
  scrubSecretValues,
33
48
  } from "../core/auth.js";
34
- import { listDomains, listNames } from "../core/secrets-store.js";
35
- import { findGuidesByDomain } from "../core/guide-store.js";
36
- import { isApiLearnEnabled } from "../core/api-toggle.js";
49
+ import { readToken } from "../core/oauth-store.js";
50
+ import { provisionedDomainsSuffix } from "../core/secrets-store.js";
37
51
  import { serverMessage, isPlanGated } from "../core/status-hint.js";
38
52
  import { appendFooter, contentText } from "./utils.js";
53
+ import type {
54
+ SecretRef,
55
+ StaticKeyAuth,
56
+ OAuth2Grant,
57
+ } from "../core/api-guide-types.js";
39
58
 
40
59
  // ═══════════════════════════════════════════════════════════════════
41
60
  // Types
@@ -74,8 +93,6 @@ export interface ProbeResult {
74
93
  }
75
94
 
76
95
  export interface ProbeOptions {
77
- /** Accept header (default application/json). */
78
- accept?: string;
79
96
  /** On 404, walk the apiHost version backward (vN→v1). Default true. */
80
97
  walkVersions?: boolean;
81
98
  /**
@@ -87,12 +104,56 @@ export interface ProbeOptions {
87
104
  /** Maps header name → secret name, same direction as the guide schema. */
88
105
  secretRefs?: Record<string, string>;
89
106
  secretQueryRefs?: Record<string, string>;
107
+ /**
108
+ * Maps path token → secret name (Telegram-class token-in-path APIs:
109
+ * `/bot{token}/getMe`). Store value fills `{token}` below the agent
110
+ * params map; any agent-supplied value for the name is dropped, and the
111
+ * token is redacted from every surfaced URL.
112
+ */
113
+ secretPathRefs?: Record<string, string>;
90
114
  /**
91
115
  * Header name → prefix prepended to the resolved secret value (e.g.
92
116
  * `Authorization: "Bearer "`). The store holds the raw token; the prefix
93
117
  * is API knowledge. Keys must be present in `secretRefs`.
94
118
  */
95
119
  headerPrefixes?: Record<string, string>;
120
+ /**
121
+ * Read the OAuth2 access token from the token store (the domain the
122
+ * probe resolved) and inject `Authorization: Bearer <token>` — values
123
+ * never enter the transcript. Bearer-header only (ponytail: query
124
+ * paramStyle waits for a recipe that needs it). No/expired token →
125
+ * the note nudges `/api oauth <domain>` and the probe proceeds
126
+ * unauthenticated (probe misses are never fail-closed). With mint
127
+ * fields below, the miss mints instead of nudging. Requires `grant` +
128
+ * `tokenUrl` (the slot key) — omitting either is a validation error.
129
+ */
130
+ useTokenStore?: boolean;
131
+ /**
132
+ * The token slot to read: slots are keyed `(domain, grant, tokenUrl)`,
133
+ * so a store read needs the same grant + token endpoint facts the mint
134
+ * arm already carries. Required with useTokenStore — a call without
135
+ * them is a loud validation error, not a silent store miss.
136
+ */
137
+ grant?: OAuth2Grant;
138
+ /**
139
+ * Mint-on-demand (client-credentials authoring bootstrap): when the
140
+ * token store has no usable token, the probe POSTs `tokenUrl` once
141
+ * (client-credentials grant), stamps the token store, and injects the
142
+ * fresh Bearer. `clientId`/`clientSecret` are secrets-store NAMES —
143
+ * values resolve from the store, never the transcript. Implies
144
+ * useTokenStore. auth-code cannot be inlined (needs the interactive
145
+ * paste dance) — save a draft guide and use `/api oauth` for that.
146
+ * `tokenUrl` is load-bearing beyond minting: it keys the token-store
147
+ * slot read (with `grant`).
148
+ */
149
+ tokenUrl?: string;
150
+ clientId?: string;
151
+ clientSecret?: string;
152
+ scopes?: string[];
153
+ tokenEndpointAuthMethod?:
154
+ | "client_secret_basic"
155
+ | "client_secret_post"
156
+ | "none";
96
157
  };
97
158
  /** Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain). */
98
159
  domain?: string;
@@ -220,11 +281,51 @@ interface ProbeAuthCtx {
220
281
  queryParams: Record<string, string>;
221
282
  secretHeaderNames: Set<string>;
222
283
  secretQueryParamNames: Set<string>;
284
+ /** path token → store-filled raw value (empty when no path refs / store miss). */
285
+ pathSecretParams: Record<string, string>;
286
+ /** path token → store secret NAME (for draft emission — never a value). */
287
+ pathSecretNames: Record<string, string>;
223
288
  secretValues: string[];
224
289
  missingNames: string[];
225
290
  /** headerPrefixes declared but no secretRefs to apply them to — the
226
291
  * prefixes would be silently dropped. Surfaced as a note, not an error. */
227
292
  misconfiguredPrefixes: boolean;
293
+ /** useTokenStore declared but no usable token (absent or expired) — the
294
+ * nudge text, composed into the 401/403 note. Empty when fine/unused. */
295
+ tokenNote: string;
296
+ }
297
+
298
+ /**
299
+ * Convert the probe's flat inline `auth` block (tool param — injection
300
+ * fields only) into a nested `StaticKeyAuth` for the shared resolvers.
301
+ * `headerPrefixes` fold inline onto each ref's `prefix`.
302
+ */
303
+ function flatToStaticKeyAuth(
304
+ auth: NonNullable<ProbeOptions["auth"]>,
305
+ ): StaticKeyAuth {
306
+ const secretRefs: Record<string, SecretRef> = {};
307
+ for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
308
+ secretRefs[header] = {
309
+ secret: secretName,
310
+ ...(auth.headerPrefixes?.[header] === undefined
311
+ ? {}
312
+ : { prefix: auth.headerPrefixes[header] }),
313
+ };
314
+ }
315
+ const secretQueryRefs: Record<string, SecretRef> = {};
316
+ for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
317
+ secretQueryRefs[param] = { secret: secretName };
318
+ }
319
+ const secretPathRefs: Record<string, SecretRef> = {};
320
+ for (const [token, secretName] of Object.entries(auth.secretPathRefs ?? {})) {
321
+ secretPathRefs[token] = { secret: secretName };
322
+ }
323
+ return {
324
+ kind: "static-key",
325
+ ...(Object.keys(secretRefs).length > 0 ? { secretRefs } : {}),
326
+ ...(Object.keys(secretQueryRefs).length > 0 ? { secretQueryRefs } : {}),
327
+ ...(Object.keys(secretPathRefs).length > 0 ? { secretPathRefs } : {}),
328
+ };
228
329
  }
229
330
 
230
331
  /**
@@ -234,10 +335,11 @@ interface ProbeAuthCtx {
234
335
  * omitted. `requires`/`optional` are absent from the probe's injection-only
235
336
  * block, so every miss lands in the report list.
236
337
  */
237
- function resolveProbeAuth(
338
+ async function resolveProbeAuth(
238
339
  auth: NonNullable<ProbeOptions["auth"]> | undefined,
239
340
  domain: string,
240
- ): ProbeAuthCtx {
341
+ ctx?: ExtensionContext,
342
+ ): Promise<ProbeAuthCtx> {
241
343
  // Computed before the hasRefs check so the flag survives both paths: a
242
344
  // headerPrefixes-only block (hasRefs false → early return) and a
243
345
  // secretQueryRefs block with prefixes but no secretRefs (hasRefs true →
@@ -251,54 +353,166 @@ function resolveProbeAuth(
251
353
  const hasRefs =
252
354
  !!auth &&
253
355
  (Object.keys(auth.secretRefs ?? {}).length > 0 ||
254
- Object.keys(auth.secretQueryRefs ?? {}).length > 0);
255
- if (!hasRefs) {
356
+ Object.keys(auth.secretQueryRefs ?? {}).length > 0 ||
357
+ Object.keys(auth.secretPathRefs ?? {}).length > 0);
358
+ const useTokenStore = !!auth?.useTokenStore;
359
+ // Inline mint fields imply the token path even without useTokenStore.
360
+ const hasMintFields = !!auth?.tokenUrl && !!auth?.clientId;
361
+ // tokenUrl is load-bearing for both arms (mint destination AND store slot
362
+ // key), so mint fields + any non-cc grant is an ambiguous mix — refuse
363
+ // loudly instead of silently minting a client_credentials token that
364
+ // overwrites the intent (and stamps a cc slot nobody asked for).
365
+ if (hasMintFields && auth?.grant && auth.grant !== "client_credentials") {
366
+ return {
367
+ hasAuthBlock: true,
368
+ headers: {},
369
+ queryParams: {},
370
+ secretHeaderNames: new Set(),
371
+ secretQueryParamNames: new Set(),
372
+ pathSecretParams: {},
373
+ pathSecretNames: {},
374
+ secretValues: [],
375
+ missingNames: [],
376
+ misconfiguredPrefixes,
377
+ tokenNote:
378
+ `mint fields (tokenUrl + clientId) are client_credentials-only; ` +
379
+ `drop auth.grant ("${auth.grant}") or omit the mint fields and set ` +
380
+ `auth.useTokenStore to read the existing ${auth.grant} slot`,
381
+ };
382
+ }
383
+ if (!hasRefs && !useTokenStore && !hasMintFields) {
256
384
  return {
257
385
  hasAuthBlock: false,
258
386
  headers: {},
259
387
  queryParams: {},
260
388
  secretHeaderNames: new Set(),
261
389
  secretQueryParamNames: new Set(),
390
+ pathSecretParams: {},
391
+ pathSecretNames: {},
262
392
  secretValues: [],
263
393
  missingNames: [],
264
394
  misconfiguredPrefixes,
395
+ tokenNote: "",
265
396
  };
266
397
  }
267
- const headerRes = resolveSecretHeaders(
268
- {
269
- kind: "static-key",
270
- ...(auth!.secretRefs ? { secretRefs: auth!.secretRefs } : {}),
271
- ...(auth!.headerPrefixes ? { headerPrefixes: auth!.headerPrefixes } : {}),
272
- },
273
- domain,
274
- );
275
- const queryRes = resolveSecretQueryParams(
276
- {
277
- kind: "static-key",
278
- ...(auth!.secretQueryRefs ? { secretQueryRefs: auth!.secretQueryRefs } : {}),
279
- },
280
- domain,
281
- );
398
+ const staticKeyAuth = flatToStaticKeyAuth(auth!);
399
+ const headerRes = resolveSecretHeaders(staticKeyAuth, domain);
400
+ const queryRes = resolveSecretQueryParams(staticKeyAuth, domain);
401
+ const pathRes = resolveSecretPathParams(staticKeyAuth, domain);
402
+ // OAuth2 token injection: the token rides the same ctx as secret headers
403
+ // (scrub + redirect-strip cover it). Bearer-header only (ponytail: query
404
+ // paramStyle injection waits for a recipe that needs it). Two modes:
405
+ // store-read-only (useTokenStore, nudge /api oauth on miss) and
406
+ // mint-on-demand (inline tokenUrl + clientId — authoring bootstrap).
407
+ let tokenNote = "";
408
+ const tokenHeader: Record<string, string> = {};
409
+ // Raw (unprefixed) token value for the body scrub — a 401 body can echo
410
+ // the bare credential, not just the `Bearer <token>` header form.
411
+ let rawTokenValue = "";
412
+ if (hasMintFields) {
413
+ // Build a synthetic oauth2 auth and hand it straight to
414
+ // resolveAccessToken so the cache → refresh → mint → stamp machinery is
415
+ // reused wholesale (incl. the per-domain refresh lock). Failures never
416
+ // fail-closed — validation throws included, since
417
+ // buildSyntheticOAuth2Auth runs inside the same try/catch — the message
418
+ // rides the note and the probe proceeds unauthenticated.
419
+ // Interactive sessions re-gate the secret-bearing destination on the
420
+ // human (same trust root as oauth-mint). Headless has no gate — the
421
+ // agent-has-bash posture covers it; documented in AGENTS.md. Decline
422
+ // skips only the mint: tokenHeader stays empty and the shared return
423
+ // below reports the unauthenticated probe + any secret misses.
424
+ if (ctx?.hasUI) {
425
+ const ok = await confirmTokenUrl(
426
+ ctx,
427
+ domain,
428
+ auth!.tokenUrl!,
429
+ auth!.clientId!,
430
+ );
431
+ if (!ok)
432
+ tokenNote = `token-URL confirm declined for "${domain}"; probe proceeding unauthenticated`;
433
+ }
434
+ // Decline skips only the mint (tokenHeader stays empty) — the note and
435
+ // unauthenticated probe are reported by the shared return below.
436
+ if (tokenNote === "") {
437
+ try {
438
+ const oauthAuth = buildSyntheticOAuth2Auth({
439
+ grant: "client_credentials",
440
+ tokenUrl: auth!.tokenUrl!,
441
+ clientId: auth!.clientId!,
442
+ ...(auth!.clientSecret ? { clientSecret: auth!.clientSecret } : {}),
443
+ ...(auth!.scopes?.length ? { scopes: auth!.scopes } : {}),
444
+ ...(auth!.tokenEndpointAuthMethod
445
+ ? { tokenEndpointAuthMethod: auth!.tokenEndpointAuthMethod }
446
+ : {}),
447
+ });
448
+ const result = await resolveAccessToken(oauthAuth, domain);
449
+ const bearer = result.authHeaders?.authorization;
450
+ if (bearer) {
451
+ tokenHeader["authorization"] = bearer;
452
+ rawTokenValue = result.secretValues[0] ?? "";
453
+ } else tokenNote = "oauth2 mint succeeded but produced no bearer header";
454
+ } catch (e) {
455
+ tokenNote = e instanceof Error ? e.message : "oauth2 mint failed";
456
+ }
457
+ }
458
+ } else if (useTokenStore) {
459
+ // Slot-keyed store read: the slot derives from (grant, tokenUrl) — the
460
+ // same facts the mint arm carries. Without them the read would target a
461
+ // slot that never exists; that misconfiguration is a LOUD validation
462
+ // error (the caller's try/catch surfaces it), not a misleading
463
+ // "run /api oauth" note on an unauthenticated fetch.
464
+ if (!auth?.grant || !auth?.tokenUrl) {
465
+ throw new Error(
466
+ "auth.useTokenStore requires auth.grant (client_credentials | authorization_code) " +
467
+ "and auth.tokenUrl — token slots are keyed by (domain, grant, token endpoint).",
468
+ );
469
+ }
470
+ const token = readToken(domain, auth.grant, auth.tokenUrl);
471
+ if (!token) {
472
+ tokenNote = `no cached token for "${domain}"; run /api oauth ${domain} to mint one`;
473
+ } else if (isTokenExpired(token)) {
474
+ tokenNote = `token for "${domain}" is expired; run /api oauth ${domain} --refresh`;
475
+ } else {
476
+ tokenHeader["authorization"] = `Bearer ${token.accessToken}`;
477
+ rawTokenValue = token.accessToken;
478
+ }
479
+ }
480
+ if (Object.keys(tokenHeader).length > 0) {
481
+ assertNoBearerCollision(
482
+ headerRes.headers,
483
+ "the probe auth block's secretRefs",
484
+ );
485
+ }
486
+ const headers = { ...headerRes.headers, ...tokenHeader };
282
487
  return {
283
488
  hasAuthBlock: true,
284
- headers: headerRes.headers,
489
+ headers,
285
490
  queryParams: queryRes.queryParams,
286
- secretHeaderNames: new Set(
287
- Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
288
- ),
491
+ secretHeaderNames: new Set(Object.keys(headers).map((h) => h.toLowerCase())),
289
492
  secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
493
+ pathSecretParams: pathRes.values,
494
+ pathSecretNames: Object.fromEntries(
495
+ Object.entries(staticKeyAuth.secretPathRefs ?? {}).map(([t, r]) => [
496
+ t,
497
+ r.secret,
498
+ ]),
499
+ ),
290
500
  secretValues: [
291
- ...Object.values(headerRes.headers),
501
+ ...Object.values(headers),
292
502
  ...headerRes.rawHeaderValues,
293
503
  ...Object.values(queryRes.queryParams),
504
+ ...pathScrubValues(pathRes.values),
505
+ ...(rawTokenValue ? [rawTokenValue] : []),
294
506
  ],
295
507
  missingNames: [
296
508
  ...headerRes.absentRequired,
297
509
  ...headerRes.absentOptional,
298
510
  ...queryRes.absentRequired,
299
511
  ...queryRes.absentOptional,
512
+ ...pathRes.missing,
300
513
  ],
301
514
  misconfiguredPrefixes,
515
+ tokenNote,
302
516
  };
303
517
  }
304
518
 
@@ -315,35 +529,18 @@ const MISCONFIGURED_PREFIXES_NOTE =
315
529
  * usually a domain-mismatch, not a missing secret. */
316
530
  function missNote(authCtx: ProbeAuthCtx, domain: string): string {
317
531
  if (authCtx.missingNames.length === 0) return "";
318
- const others = listDomains().filter((d) => d !== domain);
319
- const tail =
320
- others.length > 0
321
- ? ` — provisioned domains: ${others.join(", ")}; pass domain: <one> to use its secret`
322
- : "";
532
+ const suffix = provisionedDomainsSuffix(domain);
533
+ const tail = suffix ? `${suffix}; pass domain: <one> to use its secret` : "";
323
534
  return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"${tail}`;
324
535
  }
325
536
 
326
- /** Resolve the secrets-store domain for a probe: the apiHost hostname when it
327
- * is itself provisioned, else the longest provisioned parent domain
328
- * (pro-api.coinmarketcap.com → coinmarketcap.com), else the hostname as-is.
329
- * ponytail: parent-suffix match against the store, not a public-suffix list —
330
- * no dep, and the store is the source of truth for where secrets live. */
331
- export function resolveProbeStoreDomain(hostname: string): string {
332
- const domains = listDomains();
333
- if (domains.includes(hostname)) return hostname;
334
- const parent = domains
335
- .filter((d) => hostname.endsWith(`.${d}`))
336
- .sort((a, b) => b.length - a.length)[0];
337
- return parent ?? hostname;
338
- }
339
-
340
- /** Hostname of an apiHost URL (falls back to the raw string). */
341
- function hostnameOf(apiHost: string): string {
342
- try {
343
- return new URL(apiHost).hostname;
344
- } catch {
345
- return apiHost;
346
- }
537
+ /** missNote + the token-store note, joined — the one miss renderer used at
538
+ * every note site, so a useTokenStore nudge rides along wherever a secret
539
+ * miss would. */
540
+ function authMissNote(authCtx: ProbeAuthCtx, domain: string): string {
541
+ return [missNote(authCtx, domain), authCtx.tokenNote]
542
+ .filter(Boolean)
543
+ .join(" — ");
347
544
  }
348
545
 
349
546
  /** Trailing path of an apiHost URL (e.g. `/v3`), or `""` when empty/root.
@@ -362,11 +559,12 @@ export async function probe(
362
559
  path: string,
363
560
  params: Record<string, unknown> = {},
364
561
  opts: ProbeOptions = {},
562
+ ctx?: ExtensionContext,
365
563
  ): Promise<ProbeResult> {
366
- const accept = opts.accept ?? "application/json";
367
564
  const walkVersions = opts.walkVersions ?? true;
368
- const domain = opts.domain ?? resolveProbeStoreDomain(hostnameOf(apiHost));
369
- const authCtx = resolveProbeAuth(opts.auth, domain);
565
+ const domain =
566
+ opts.domain ?? resolveProvisionedParentDomain(hostnameOf(apiHost));
567
+ const authCtx = await resolveProbeAuth(opts.auth, domain, ctx);
370
568
 
371
569
  // Base case only carries the apiHost version prefix; a walk-hit draft
372
570
  // embeds its walked version in the prefix passed to fetchOne.
@@ -374,7 +572,6 @@ export async function probe(
374
572
  apiHost,
375
573
  path,
376
574
  params,
377
- accept,
378
575
  authCtx,
379
576
  domain,
380
577
  versionPrefixOf(apiHost),
@@ -392,7 +589,7 @@ export async function probe(
392
589
  return base;
393
590
  }
394
591
  const hit = await walkBackward(
395
- { apiHost, path, params, accept, authCtx, domain },
592
+ { apiHost, path, params, authCtx, domain },
396
593
  Number(stated),
397
594
  );
398
595
  return hit ?? base;
@@ -414,20 +611,18 @@ async function walkBackward(
414
611
  apiHost: string;
415
612
  path: string;
416
613
  params: Record<string, unknown>;
417
- accept: string;
418
614
  authCtx: ProbeAuthCtx;
419
615
  domain: string;
420
616
  },
421
617
  start: number,
422
618
  ): Promise<ProbeResult | null> {
423
- const miss = missNote(ctx.authCtx, ctx.domain);
619
+ const miss = authMissNote(ctx.authCtx, ctx.domain);
424
620
  const floor = Math.max(start - MAX_VERSION_WALK, 1);
425
621
  for (let k = start - 1; k >= floor; k--) {
426
622
  const tried = await fetchOne(
427
623
  withVersion(ctx.apiHost, k),
428
624
  ctx.path,
429
625
  ctx.params,
430
- ctx.accept,
431
626
  ctx.authCtx,
432
627
  ctx.domain,
433
628
  `/v${k}`,
@@ -437,7 +632,7 @@ async function walkBackward(
437
632
  // draft carries /v${k} while the body came from elsewhere — flag
438
633
  // it so the agent checks finalUrl instead of trusting the prefix.
439
634
  const redirected = tried.finalUrl !== tried.url;
440
- tried.note = `${miss ? miss + " — " : ""}404 on /v${start}${ctx.path}; version walk → /v${k}${redirected ? " — verify finalUrl (redirect target)" : ""}`;
635
+ tried.note = `${miss ? `${miss} — ` : ""}404 on /v${start}${ctx.path}; version walk → /v${k}${redirected ? " — verify finalUrl (redirect target)" : ""}`;
441
636
  return tried;
442
637
  }
443
638
  }
@@ -458,49 +653,72 @@ function withVersion(apiHost: string, k: number): string {
458
653
 
459
654
  /** The gate-excluded 404 note (bare / non-integer / subdomain version hosts). */
460
655
  function walkSkipNote(authCtx: ProbeAuthCtx, domain: string): string {
461
- const miss = missNote(authCtx, domain);
462
- return `${miss ? miss + " — " : ""}404 — no version walk (apiHost has no /vN prefix)`;
656
+ const miss = authMissNote(authCtx, domain);
657
+ return `${miss ? `${miss} — ` : ""}404 — no version walk (apiHost has no /vN prefix)`;
463
658
  }
464
659
 
465
660
  async function fetchOne(
466
661
  apiHost: string,
467
662
  path: string,
468
663
  params: Record<string, unknown>,
469
- accept: string,
470
664
  authCtx: ProbeAuthCtx,
471
665
  domain: string,
472
666
  prefix = "",
473
667
  ): Promise<ProbeResult> {
474
- // Inject secret query params below the agent-supplied params map, then
475
- // redact the surfaced URL so the real key never reaches the transcript.
476
- const rawUrl = buildUrl(apiHost, path, { ...params, ...authCtx.queryParams });
477
- const url = redactSecretParams(rawUrl, authCtx.secretQueryParamNames);
668
+ // Secret-owned path tokens: the path fill sees the merged map (store
669
+ // wins; agent-supplied values for secret-owned tokens dropped), while the
670
+ // query builder gets a deletion-only copy — a probe whose path lacks the
671
+ // token must not leak the plaintext into the query string.
672
+ const pathSecrets = authCtx.pathSecretParams;
673
+ const pathValues = Object.values(pathSecrets);
674
+ const { fillParams, queryParamsForBuild } = splitPathSecretParams(
675
+ params,
676
+ pathSecrets,
677
+ );
678
+ const rawUrl = buildUrl(apiHost, path, fillParams, {
679
+ ...queryParamsForBuild,
680
+ ...authCtx.queryParams,
681
+ });
682
+ const redactUrl = (u: string) =>
683
+ redactSecretPathValues(
684
+ redactSecretParams(u, authCtx.secretQueryParamNames),
685
+ pathValues,
686
+ );
687
+ const url = redactUrl(rawUrl);
478
688
  const hasQuerySecret = Object.keys(authCtx.queryParams).length > 0;
479
689
  const res = await fetchUrl(rawUrl, {
480
- headers: { accept, ...authCtx.headers },
690
+ headers: { accept: "application/json", ...authCtx.headers },
481
691
  fresh: true,
482
692
  ...(authCtx.hasAuthBlock
483
693
  ? {
484
694
  hasQuerySecret,
695
+ hasPathSecret: pathValues.length > 0,
485
696
  secretHeaderNames: authCtx.secretHeaderNames,
697
+ secretQueryParamNames: authCtx.secretQueryParamNames,
698
+ ...(pathValues.length > 0
699
+ ? {
700
+ // Redaction closure (not raw values): keeps the
701
+ // transport's option surface value-agnostic; used
702
+ // on cross-domain redirect hops.
703
+ redactPathSecret: (u: string) => redactSecretPathValues(u, pathValues),
704
+ }
705
+ : {}),
486
706
  }
487
707
  : {}),
488
708
  });
489
709
  // Probe-local body scrub: the probe bypasses checkResponseStatus, so
490
- // scrub known secret values from the raw slice directly — a 401 body
491
- // echoing the key must not leak it into agent context.
492
- const raw = scrubSecretValues(res.body.slice(0, 800), authCtx.secretValues);
493
- const finalUrl = redactSecretParams(
494
- res.finalUrl ?? rawUrl,
495
- authCtx.secretQueryParamNames,
496
- );
710
+ // scrub known secret values from the full body directly — a 401 body
711
+ // echoing the key must not leak it into agent context. Scrub before
712
+ // slicing so a secret straddling the cut can't leave a partial prefix.
713
+ const raw = scrubSecretValues(res.body, authCtx.secretValues).slice(0, 800);
714
+ const finalUrl = redactUrl(res.finalUrl ?? rawUrl);
497
715
 
498
716
  if (res.status >= 400) {
499
717
  // 401 or 403 — both mean the request was rejected on auth grounds
500
718
  // (gated endpoint, or bad/missing credentials), distinct from other
501
719
  // 4xx/5xx statuses. The name is deliberate: it covers 403 too.
502
720
  const isAuthError = res.status === 401 || res.status === 403;
503
- const miss = missNote(authCtx, domain);
721
+ const miss = authMissNote(authCtx, domain);
504
722
  let note: string;
505
723
  if (!authCtx.hasAuthBlock) {
506
724
  // No auth injected — a 401/403 means the endpoint is gated and the
@@ -562,14 +780,19 @@ async function fetchOne(
562
780
  shape: null,
563
781
  draft: "",
564
782
  raw,
565
- note:
566
- "non-JSON body (set opts.accept for XML/HTML, or use a different path)",
783
+ note: "non-JSON body (use a different path)",
567
784
  };
568
785
  }
569
786
 
570
787
  const shape = summarize(data);
571
- const miss = missNote(authCtx, domain);
572
- const draft = emitDraft(path, params, shape, prefix);
788
+ const miss = authMissNote(authCtx, domain);
789
+ const draft = emitDraft(
790
+ path,
791
+ queryParamsForBuild,
792
+ shape,
793
+ prefix,
794
+ authCtx.pathSecretNames,
795
+ );
573
796
  let note: string | undefined = miss;
574
797
  if (authCtx.misconfiguredPrefixes) {
575
798
  note = [note, MISCONFIGURED_PREFIXES_NOTE].filter(Boolean).join(" — ");
@@ -591,25 +814,37 @@ const RESERVED_PARAM_NAMES = new Set(["domain", "apiHost", "path", "auth"]);
591
814
  function buildUrl(
592
815
  apiHost: string,
593
816
  path: string,
594
- params: Record<string, unknown>,
817
+ fillParams: Record<string, unknown>,
818
+ queryParams: Record<string, unknown>,
595
819
  ): string {
596
- for (const key of Object.keys(params)) {
820
+ for (const key of Object.keys(fillParams).concat(Object.keys(queryParams))) {
597
821
  if (RESERVED_PARAM_NAMES.has(key)) {
598
822
  throw new Error(
599
823
  `"${key}" is a top-level param, not a query param — move it out of params`,
600
824
  );
601
825
  }
602
826
  }
603
- // Substitute {token} → params[token] BEFORE building the URL, so a
827
+ // Substitute {token} → fillParams[token] BEFORE building the URL, so a
604
828
  // templated path fetches real values instead of literal %7Bowner%7D.
605
829
  // Missing tokens stay literal ({token}) — fine for probing an unfilled path.
606
830
  const pathTokens = new Set(extractPathTokens(path));
607
- const substituted = fillPathTemplate(path, params);
831
+ const substituted = fillPathTemplate(path, fillParams);
608
832
  const qs = new URLSearchParams(
609
833
  Object.fromEntries(
610
- Object.entries(params)
611
- .filter(([k, v]) => v !== undefined && !pathTokens.has(k))
612
- .map(([k, v]) => [k, String(v)]),
834
+ Object.entries(queryParams).flatMap(([k, v]): [string, string][] => {
835
+ if (v === undefined || pathTokens.has(k)) return [];
836
+ // Probe has no guide schema to declare listStyle against, so
837
+ // non-scalar values are a loud error — never the silent
838
+ // String(v) wire form (String(["a","b"]) → "a,b" is
839
+ // accidentally comma-correct but misdescribes repeat/bracket
840
+ // APIs; [object Object] is wrong everywhere).
841
+ if (Array.isArray(v) || (typeof v === "object" && v !== null)) {
842
+ throw new Error(
843
+ `Param "${k}" is ${Array.isArray(v) ? "an array" : "an object"} — api-probe sends scalar params only: pre-join list values as a string, or JSON.stringify DSL params`,
844
+ );
845
+ }
846
+ return [[k, String(v)]];
847
+ }),
613
848
  ),
614
849
  ).toString();
615
850
  return joinUrl(apiHost, substituted, qs);
@@ -624,19 +859,20 @@ export function emitDraft(
624
859
  params: Record<string, unknown>,
625
860
  shape: ShapeSummary,
626
861
  prefix = "",
862
+ pathSecretRefs?: Record<string, string>,
627
863
  ): string {
628
864
  // Idempotent: only prepend when the path doesn't already carry the prefix,
629
865
  // so `apiHost: .../v3` + `path: /v3/items` doesn't become `/v3/v3/items`.
630
- if (prefix && !path.startsWith(prefix)) path = prefix + path;
631
- const name = suggestName(path);
632
- const pathTokens = extractPathTokens(path);
866
+ const fullPath = prefix && !path.startsWith(prefix) ? prefix + path : path;
867
+ const name = suggestName(fullPath);
868
+ const pathTokens = extractPathTokens(fullPath);
633
869
  const queryParamKeys = Object.keys(params).filter(
634
870
  (k) => !pathTokens.includes(k),
635
871
  );
636
872
  const lines: string[] = [
637
873
  ` - name: ${name}`,
638
874
  ` via: ${shape.suggestedVia}`,
639
- ` path: ${path}`,
875
+ ` path: ${fullPath}`,
640
876
  ` accept: json`,
641
877
  ];
642
878
 
@@ -672,6 +908,21 @@ export function emitDraft(
672
908
  " # array response with no pagination markers — if the API documents paging, prefer paginate:",
673
909
  " # 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.",
674
910
  );
911
+ if (shape.topLevel === "array") {
912
+ // Bare top-level array — the author would have to hand-convert, and
913
+ // `itemsPath` is parser-required on paginate ops but invisible here.
914
+ // Emit the ready-to-uncomment block so the conversion can't drop it.
915
+ lines.push(
916
+ " # bare top-level array — the paginate equivalent (itemsPath is REQUIRED on paginate ops):",
917
+ " # via: paginate",
918
+ " # pagination:",
919
+ " # style: offset-limit",
920
+ ` # itemsPath: ${shape.suggestedItemsPath}`,
921
+ " # pageParam: offset",
922
+ " # pageSizeParam: limit",
923
+ " # pageSize: 30",
924
+ );
925
+ }
675
926
  }
676
927
  if (queryParamKeys.length > 0) {
677
928
  lines.push(" params:");
@@ -685,6 +936,28 @@ export function emitDraft(
685
936
  ` # representative id: ${shape.representativeId.field}=${shape.representativeId.value}`,
686
937
  );
687
938
  }
939
+ // Path-secret tokens are store-filled (the agent must never hand-bake the
940
+ // token into the path — that's the transcript leak this surface closes),
941
+ // so the draft carries the guide-level auth block that backs them. Auth is
942
+ // frontmatter, not per-op — emitted commented, pasted above `operations:`.
943
+ // Only tokens the emitted path actually uses: a name in no op's path is
944
+ // rejected at parse (declared-but-unused), so emitting one would hand the
945
+ // author a guide that can't parse.
946
+ const pathRefEntries = Object.entries(pathSecretRefs ?? {}).filter(([t]) =>
947
+ pathTokens.includes(t),
948
+ );
949
+ if (pathRefEntries.length > 0) {
950
+ lines.push(
951
+ "# guide-level auth (paste into the frontmatter, above operations:) — the token fills from the secrets store, never params:",
952
+ "# auth:",
953
+ "# kind: static-key",
954
+ "# secretPathRefs:",
955
+ );
956
+ for (const [token, secret] of pathRefEntries) {
957
+ lines.push(`# ${token}:`);
958
+ lines.push(`# secret: ${secret}`);
959
+ }
960
+ }
688
961
  return lines.join("\n");
689
962
  }
690
963
 
@@ -711,9 +984,9 @@ export const apiProbeTool = defineTool({
711
984
  "It only suggests — it never writes the guide, and the operation must still be " +
712
985
  "traceable to your plan source. Pre-guide: pass apiHost + path. After a guide " +
713
986
  "exists, use api-guide({domain}) to get apiHost, or api-fetch to execute. " +
714
- "Before the first auth-gated probe, call with listSecrets: true (and no domain) " +
715
- "to list every provisioned store domain and which already have guides — pass that " +
716
- "domain up front so a store-miss round-trip is avoided. " +
987
+ "Before the first auth-gated probe, use api-store (learn mode) to check what " +
988
+ "credentials exist for the domain — pass that domain up front so a store-miss " +
989
+ "round-trip is avoided. " +
717
990
  "Before authoring a new guide, read the provider's docs index (llms.txt, " +
718
991
  "openapi.json at the API root, or the docs page) to learn the current API " +
719
992
  "version — then probe that version explicitly. Do not default the version from " +
@@ -722,23 +995,19 @@ export const apiProbeTool = defineTool({
722
995
  "but cannot detect a stale-but-working one. ",
723
996
 
724
997
  parameters: Type.Object({
725
- apiHost: Type.Optional(
726
- Type.String({
727
- description:
728
- "Base URL including the API's current version prefix, e.g. " +
729
- "'https://api.example.com/v3'. Find the latest version before probing: " +
730
- "check the API's docs page, openapi.json/swagger.json at the API root, " +
731
- "or llms.txt. Supply the newest version you can verify — if it 404s, the " +
732
- "probe walks backward (v3→v2→v1) to recover. Do not default to /v1 from " +
733
- "memory; a stale version that still returns 200 is not detected as old.",
734
- }),
735
- ),
736
- path: Type.Optional(
737
- Type.String({
738
- description:
739
- "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
740
- }),
741
- ),
998
+ apiHost: Type.String({
999
+ description:
1000
+ "Base URL including the API's current version prefix, e.g. " +
1001
+ "'https://api.example.com/v3'. Find the latest version before probing: " +
1002
+ "check the API's docs page, openapi.json/swagger.json at the API root, " +
1003
+ "or llms.txt. Supply the newest version you can verify — if it 404s, the " +
1004
+ "probe walks backward (v3→v2→v1) to recover. Do not default to /v1 from " +
1005
+ "memory; a stale version that still returns 200 is not detected as old.",
1006
+ }),
1007
+ path: Type.String({
1008
+ description:
1009
+ "Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
1010
+ }),
742
1011
  params: Type.Optional(
743
1012
  Type.Record(Type.String(), Type.Unknown(), {
744
1013
  description:
@@ -756,11 +1025,67 @@ export const apiProbeTool = defineTool({
756
1025
  {
757
1026
  secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
758
1027
  secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
1028
+ secretPathRefs: Type.Optional(
1029
+ Type.Record(Type.String(), Type.String(), {
1030
+ description:
1031
+ "Path token → secret name for token-in-path APIs (e.g. {token: 'bot_token'} for /bot{token}/getMe). The store value fills {token}; agent-supplied values for the name are dropped and the token is redacted from surfaced URLs.",
1032
+ }),
1033
+ ),
759
1034
  headerPrefixes: Type.Optional(Type.Record(Type.String(), Type.String())),
1035
+ useTokenStore: Type.Optional(
1036
+ Type.Boolean({
1037
+ description:
1038
+ "Inject the OAuth2 access token from the token store as 'Authorization: Bearer <token>' (mint it first via /api oauth <domain>). Requires auth.grant + auth.tokenUrl (the token-slot key). Values never enter the transcript; absent/expired token → the note nudges /api oauth and the probe proceeds unauthenticated.",
1039
+ }),
1040
+ ),
1041
+ grant: Type.Optional(
1042
+ Type.Union(
1043
+ [Type.Literal("client_credentials"), Type.Literal("authorization_code")],
1044
+ {
1045
+ description:
1046
+ "The token slot's grant — token slots are keyed (domain, grant, tokenUrl). Required with useTokenStore; the mint arm always uses client_credentials.",
1047
+ },
1048
+ ),
1049
+ ),
1050
+ tokenUrl: Type.Optional(
1051
+ Type.String({
1052
+ description:
1053
+ "Token endpoint URL — load-bearing beyond minting: it keys the token-store slot read (with grant). When the token store has no usable token and mint fields are present, the probe POSTs client-credentials once, stamps the store, and injects the fresh Bearer.",
1054
+ }),
1055
+ ),
1056
+ clientId: Type.Optional(
1057
+ Type.String({
1058
+ description:
1059
+ "Mint-on-demand: secrets-store NAME of the client id (value resolves from the store, never the transcript). Requires tokenUrl.",
1060
+ }),
1061
+ ),
1062
+ clientSecret: Type.Optional(
1063
+ Type.String({
1064
+ description: "Mint-on-demand: secrets-store NAME of the client secret.",
1065
+ }),
1066
+ ),
1067
+ scopes: Type.Optional(
1068
+ Type.Array(Type.String(), {
1069
+ description: "Mint-on-demand: scopes for the token request.",
1070
+ }),
1071
+ ),
1072
+ tokenEndpointAuthMethod: Type.Optional(
1073
+ Type.Union(
1074
+ [
1075
+ Type.Literal("client_secret_basic"),
1076
+ Type.Literal("client_secret_post"),
1077
+ Type.Literal("none"),
1078
+ ],
1079
+ {
1080
+ description:
1081
+ "Mint-on-demand: token-endpoint auth method (default client_secret_post).",
1082
+ },
1083
+ ),
1084
+ ),
760
1085
  },
761
1086
  {
762
1087
  description:
763
- "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.",
1088
+ "Store-backed auth injection for probing auth-gated endpoints (authoring loop). Accepts secretRefs, secretQueryRefs, secretPathRefs (token-in-path APIs), headerPrefixes, useTokenStore (+ grant + tokenUrl, the token-slot key), and client-credentials mint-on-demand fields (tokenUrl + clientId [+ clientSecret, scopes, tokenEndpointAuthMethod]) for bootstrapping a guide-less authoring loop. Values resolve from the secrets/token stores and never enter the transcript; a store miss fetches unauthenticated and reports the miss in the note.",
764
1089
  // Tight: unknown keys (e.g. a stray `domain`) are rejected before execute runs.
765
1090
  // The description above names the allowed fields explicitly — keep it in
766
1091
  // sync when adding/renaming a field here, or the prose lies to agents.
@@ -774,102 +1099,33 @@ export const apiProbeTool = defineTool({
774
1099
  "Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain).",
775
1100
  }),
776
1101
  ),
777
- listSecrets: Type.Optional(
778
- Type.Boolean({
779
- description:
780
- "Names only, never values. Two modes: with no domain/apiHost, lists " +
781
- "provisioned-but-guideless store domains (authoring-bootstrap view — " +
782
- "call this empty first to see what's provisioned); with a domain (or " +
783
- "apiHost), lists provisioned secret names for that domain, with " +
784
- "declared-vs-stored gaps when a guide exists.",
785
- }),
786
- ),
787
1102
  }),
788
1103
 
789
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
790
- const { apiHost, path, walkVersions, auth, domain, listSecrets } = params as {
791
- apiHost?: string;
792
- path?: string;
1104
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1105
+ const { apiHost, path, walkVersions, auth, domain } = params as {
1106
+ apiHost: string;
1107
+ path: string;
793
1108
  params?: Record<string, unknown>;
794
1109
  walkVersions?: boolean;
795
- auth?: {
796
- secretRefs?: Record<string, string>;
797
- secretQueryRefs?: Record<string, string>;
798
- headerPrefixes?: Record<string, string>;
799
- };
1110
+ auth?: ProbeOptions["auth"];
800
1111
  domain?: string;
801
- listSecrets?: boolean;
802
1112
  };
803
1113
  const userParams = (params as Record<string, unknown>)["params"] as
804
1114
  | Record<string, unknown>
805
1115
  | undefined;
806
1116
 
807
- // Learn-gated secrets discovery — short-circuits the fetch entirely.
808
- // The agent's only programmatic path to the secrets store; /api secrets is
809
- // user-typed only. Names only, never values.
810
- if (listSecrets === true) {
811
- if (!isApiLearnEnabled()) {
812
- return {
813
- content: [
814
- {
815
- type: "text",
816
- text:
817
- "api-probe: listSecrets: true is learn mode only — run /api learn first.",
818
- },
819
- ],
820
- details: { error: "learn_mode_only" },
821
- };
822
- }
823
- // Bare call (no domain, no apiHost): orphan list only. apiHost present:
824
- // orphan list first, then the per-domain view. domain present: unchanged.
825
- const unscoped = domain ? undefined : unscopedStoreDomains();
826
- const blocks: string[] = [];
827
- if (unscoped !== undefined) blocks.push(formatUnscopedDomains(unscoped));
828
- const target =
829
- domain ??
830
- (apiHost ? resolveProbeStoreDomain(hostnameOf(apiHost)) : undefined);
831
- if (target !== undefined) {
832
- const secrets = listDomainSecrets(target);
833
- blocks.push(formatSecretsResult(secrets));
834
- // apiHost/domain present means a real probe was suppressed by
835
- // listSecrets: true — say so, or the author silently loses the probe.
836
- blocks.push(
837
- "probe suppressed because listSecrets: true — drop listSecrets to probe.",
838
- );
839
- return {
840
- content: [{ type: "text", text: blocks.join("\n\n") }],
841
- details: unscoped === undefined ? { secrets } : { secrets, unscoped },
842
- };
843
- }
844
- return {
845
- content: [{ type: "text", text: blocks.join("\n\n") }],
846
- details: { unscoped: unscoped! },
847
- };
848
- }
849
-
850
- // apiHost/path are optional in the schema so the bare listSecrets call is
851
- // legal; every real probe needs both. The schema no longer enforces it,
852
- // so guard here before falling through to probe(). (The listSecrets:true
853
- // branch always returns above, so this guard only sees non-listSecrets.)
854
- if (!apiHost || !path) {
855
- return {
856
- content: [
857
- {
858
- type: "text",
859
- text:
860
- "api-probe: apiHost and path are required unless listSecrets: true.",
861
- },
862
- ],
863
- details: { error: "missing_apiHost_or_path" },
864
- };
865
- }
866
-
867
1117
  try {
868
- const result = await probe(apiHost, path, userParams ?? {}, {
869
- ...(walkVersions === undefined ? {} : { walkVersions }),
870
- ...(auth ? { auth } : {}),
871
- ...(domain ? { domain } : {}),
872
- });
1118
+ const result = await probe(
1119
+ apiHost,
1120
+ path,
1121
+ userParams ?? {},
1122
+ {
1123
+ ...(walkVersions === undefined ? {} : { walkVersions }),
1124
+ ...(auth ? { auth } : {}),
1125
+ ...(domain ? { domain } : {}),
1126
+ },
1127
+ ctx,
1128
+ );
873
1129
  return {
874
1130
  content: [{ type: "text", text: formatProbeResult(result) }],
875
1131
  details: {
@@ -911,42 +1167,6 @@ export const apiProbeTool = defineTool({
911
1167
  if (d?.error) {
912
1168
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
913
1169
  }
914
- // Secrets first: the domain-scoped view is the primary output and is present
915
- // for both the per-domain and combined (apiHost-no-domain) shapes. Only the
916
- // bare call (no domain/apiHost) carries unscoped alone.
917
- const secrets = d?.secrets as
918
- | { domain: string; provisioned: string[] }
919
- | undefined;
920
- if (secrets) {
921
- const text = theme.fg("accent", theme.bold("🔑 api-probe"));
922
- return new Text(
923
- appendFooter(
924
- text +
925
- ` — secrets for ${secrets.domain} · ${secrets.provisioned.length} provisioned`,
926
- expanded,
927
- result,
928
- theme,
929
- 1000,
930
- ),
931
- 0,
932
- 0,
933
- );
934
- }
935
- const unscoped = d?.unscoped as string[] | undefined;
936
- if (unscoped) {
937
- const text = theme.fg("accent", theme.bold("🔑 api-probe"));
938
- return new Text(
939
- appendFooter(
940
- text + ` — ${unscoped.length} unscoped domains`,
941
- expanded,
942
- result,
943
- theme,
944
- 1000,
945
- ),
946
- 0,
947
- 0,
948
- );
949
- }
950
1170
  const status = d?.status as number | undefined;
951
1171
  const shape = d?.shape as ShapeSummary | null | undefined;
952
1172
 
@@ -1004,59 +1224,3 @@ export function formatProbeResult(r: ProbeResult): string {
1004
1224
  lines.push(` ${DOCS_NUDGE.join("\n ")}`);
1005
1225
  return lines.join("\n");
1006
1226
  }
1007
-
1008
- /** Store domains that are provisioned but not scoped to any guide.
1009
- * Authoring-loop diagnostic: surfaces bootstrap + migration-orphan
1010
- * secrets. Names only. */
1011
- function unscopedStoreDomains(): string[] {
1012
- return listDomains().filter((d) => findGuidesByDomain(d).length === 0);
1013
- }
1014
-
1015
- function formatUnscopedDomains(domains: string[]): string {
1016
- const lines: string[] = ["🗂 unscoped store domains (provisioned, no guide)"];
1017
- lines.push(` ${domains.length > 0 ? domains.join(", ") : "(none)"}`);
1018
- lines.push(" (names only — values never leave the store)");
1019
- return lines.join("\n");
1020
- }
1021
-
1022
- /** List mode: provisioned secret names for a domain (names only). */
1023
- function listDomainSecrets(domain: string): {
1024
- domain: string;
1025
- provisioned: string[];
1026
- declared?: string[];
1027
- } {
1028
- const provisioned = listNames(domain);
1029
- const matches = findGuidesByDomain(domain);
1030
- if (matches.length === 0) return { domain, provisioned };
1031
- const declaredSet = new Set<string>();
1032
- for (const { guide } of matches) {
1033
- for (const n of [
1034
- ...(guide.auth.requires ?? []),
1035
- ...(guide.auth.optional ?? []),
1036
- ]) {
1037
- declaredSet.add(n);
1038
- }
1039
- }
1040
- const declared = [...declaredSet].sort();
1041
- return { domain, provisioned, declared };
1042
- }
1043
-
1044
- function formatSecretsResult(s: {
1045
- domain: string;
1046
- provisioned: string[];
1047
- declared?: string[];
1048
- }): string {
1049
- const lines: string[] = [`🔑 secrets for ${s.domain}`];
1050
- lines.push(
1051
- ` provisioned: ${s.provisioned.length > 0 ? s.provisioned.join(", ") : "(none)"}`,
1052
- );
1053
- if (s.declared !== undefined) {
1054
- lines.push(
1055
- ` declared: ${s.declared.length > 0 ? s.declared.join(", ") : "(none)"}`,
1056
- );
1057
- const gaps = s.declared.filter((d) => !s.provisioned.includes(d));
1058
- if (gaps.length > 0) lines.push(` gaps: ${gaps.join(", ")}`);
1059
- }
1060
- lines.push(" (names only — values never leave the store)");
1061
- return lines.join("\n");
1062
- }