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