pi-lean-host 0.1.0 โ†’ 0.2.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,6 +20,7 @@ import {
20
20
  getCatalogText,
21
21
  } from "../core/guide-store.js";
22
22
  import { formatGuideListings, TODAY } from "../core/parse-api-guide.js";
23
+ import { authStatusLine, canonicalStoreDomain } from "../core/auth.js";
23
24
  import type { ApiGuide } from "../core/api-guide-types.js";
24
25
 
25
26
  export const apiGuideTool = defineTool({
@@ -163,11 +164,11 @@ export const apiGuideTool = defineTool({
163
164
  } else if (guideName && opCount !== undefined) {
164
165
  text = theme.fg("accent", theme.bold(`๐Ÿ“– ${guideName}`));
165
166
  text += ` โ€” ${opCount} operations`;
166
- } else if (guideCount !== undefined) {
167
+ } else if (guideCount === undefined) {
168
+ text = theme.fg("dim", "๐Ÿ“– No guide");
169
+ } else {
167
170
  text = theme.fg("dim", theme.bold("๐Ÿ“– catalog"));
168
171
  text += ` โ€” ${guideCount} guides`;
169
- } else {
170
- text = theme.fg("dim", "๐Ÿ“– No guide");
171
172
  }
172
173
 
173
174
  const content = contentText(result);
@@ -197,6 +198,11 @@ function renderGuideDetail(
197
198
  lines.push(` Verified: ${guide.verified} ยท Updated: ${guide.updated}`);
198
199
  if (guide.docs) lines.push(` Docs: ${guide.docs}`);
199
200
  lines.push(` Auth: ${guide.auth.kind}`);
201
+ // Auth status footer โ€” shared with api-fetch. Metadata only (names,
202
+ // never values); nudges provisioning when a required secret is absent.
203
+ // Keyed on the canonical store domain, not the routing `domain`.
204
+ const authStatus = authStatusLine(guide.auth, canonicalStoreDomain(guide));
205
+ if (authStatus) lines.push(` ${authStatus}`);
200
206
  lines.push(
201
207
  ` Response: ${guide.responseShape.format} (${guide.responseShape.charset})`,
202
208
  );
@@ -235,9 +241,7 @@ function renderGuideDetail(
235
241
  // primary guidance for shaping values, so they get their own lines.
236
242
  for (const [k, spec] of qParams) {
237
243
  if (spec.description) {
238
- lines.push(
239
- ` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`,
240
- );
244
+ lines.push(` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`);
241
245
  }
242
246
  }
243
247
  }
@@ -26,6 +26,14 @@ import {
26
26
  fillPathTemplate,
27
27
  joinUrl,
28
28
  } from "../core/path-template.js";
29
+ import {
30
+ resolveSecretHeaders,
31
+ resolveSecretQueryParams,
32
+ } from "../core/auth.js";
33
+ import { listDomains, listNames } from "../core/secrets-store.js";
34
+ import { findGuidesByDomain } from "../core/guide-store.js";
35
+ import { redactSecretParams } from "../core/helpers.js";
36
+ import { isApiLearnEnabled } from "../core/api-toggle.js";
29
37
  import { contentText, renderExpandedText } from "./utils.js";
30
38
 
31
39
  // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
@@ -69,6 +77,17 @@ export interface ProbeOptions {
69
77
  accept?: string;
70
78
  /** On 404, auto-try /v1/ and /v2/ prefixes. Default true. */
71
79
  tryPrefixes?: boolean;
80
+ /**
81
+ * Store-backed auth injection for probing auth-gated endpoints
82
+ * (authoring loop). Injection fields only โ€” no kind/requires/optional.
83
+ * Values resolve from the secrets store and never enter the transcript.
84
+ */
85
+ auth?: {
86
+ secretRefs?: Record<string, string>;
87
+ secretQueryRefs?: Record<string, string>;
88
+ };
89
+ /** Domain for secrets-store lookups; defaults to apiHost's hostname. */
90
+ domain?: string;
72
91
  }
73
92
 
74
93
  // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
@@ -140,7 +159,7 @@ export function summarize(data: unknown): ShapeSummary {
140
159
  }
141
160
 
142
161
  const arrayLen = items?.length ?? 0;
143
- const suggestedVia = items !== null ? "paginate" : "restGet";
162
+ const suggestedVia = items === null ? "restGet" : "paginate";
144
163
 
145
164
  const summary: ShapeSummary = {
146
165
  topLevel,
@@ -184,6 +203,93 @@ function pickRepresentativeId(
184
203
  // IO wrapper โ€” fetches via the shared transport and formats the answer
185
204
  // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
186
205
 
206
+ /** Resolved probe auth โ€” store values + the names/values to redact/scrub. */
207
+ interface ProbeAuthCtx {
208
+ hasAuthBlock: boolean;
209
+ headers: Record<string, string>;
210
+ queryParams: Record<string, string>;
211
+ secretHeaderNames: Set<string>;
212
+ secretQueryParamNames: Set<string>;
213
+ secretValues: string[];
214
+ missingNames: string[];
215
+ }
216
+
217
+ /**
218
+ * Resolve an inline `auth` block against the secrets store. Probe semantics:
219
+ * a store miss is NOT fail-closed (human-in-the-loop authoring tool) โ€” the
220
+ * missing name is reported and the call proceeds with the header/param
221
+ * omitted. `requires`/`optional` are absent from the probe's injection-only
222
+ * block, so every miss lands in the report list.
223
+ */
224
+ function resolveProbeAuth(
225
+ auth: NonNullable<ProbeOptions["auth"]> | undefined,
226
+ domain: string,
227
+ ): ProbeAuthCtx {
228
+ const hasRefs =
229
+ !!auth &&
230
+ (Object.keys(auth.secretRefs ?? {}).length > 0 ||
231
+ Object.keys(auth.secretQueryRefs ?? {}).length > 0);
232
+ if (!hasRefs) {
233
+ return {
234
+ hasAuthBlock: false,
235
+ headers: {},
236
+ queryParams: {},
237
+ secretHeaderNames: new Set(),
238
+ secretQueryParamNames: new Set(),
239
+ secretValues: [],
240
+ missingNames: [],
241
+ };
242
+ }
243
+ const headerRes = resolveSecretHeaders(
244
+ {
245
+ kind: "static-key",
246
+ ...(auth!.secretRefs ? { secretRefs: auth!.secretRefs } : {}),
247
+ },
248
+ domain,
249
+ );
250
+ const queryRes = resolveSecretQueryParams(
251
+ {
252
+ kind: "static-key",
253
+ ...(auth!.secretQueryRefs ? { secretQueryRefs: auth!.secretQueryRefs } : {}),
254
+ },
255
+ domain,
256
+ );
257
+ return {
258
+ hasAuthBlock: true,
259
+ headers: headerRes.headers,
260
+ queryParams: queryRes.queryParams,
261
+ secretHeaderNames: new Set(
262
+ Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
263
+ ),
264
+ secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
265
+ secretValues: [
266
+ ...Object.values(headerRes.headers),
267
+ ...Object.values(queryRes.queryParams),
268
+ ],
269
+ missingNames: [
270
+ ...headerRes.absentRequired,
271
+ ...headerRes.absentOptional,
272
+ ...queryRes.absentRequired,
273
+ ...queryRes.absentOptional,
274
+ ],
275
+ };
276
+ }
277
+
278
+ /** First missing secret name as a one-line note (names only, never values). */
279
+ function missNote(authCtx: ProbeAuthCtx, domain: string): string {
280
+ if (authCtx.missingNames.length === 0) return "";
281
+ return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"`;
282
+ }
283
+
284
+ /** Hostname of an apiHost URL (falls back to the raw string). */
285
+ function hostnameOf(apiHost: string): string {
286
+ try {
287
+ return new URL(apiHost).hostname;
288
+ } catch {
289
+ return apiHost;
290
+ }
291
+ }
292
+
187
293
  export async function probe(
188
294
  apiHost: string,
189
295
  path: string,
@@ -192,13 +298,16 @@ export async function probe(
192
298
  ): Promise<ProbeResult> {
193
299
  const accept = opts.accept ?? "application/json";
194
300
  const tryPrefixes = opts.tryPrefixes ?? true;
301
+ const domain = opts.domain ?? hostnameOf(apiHost);
302
+ const authCtx = resolveProbeAuth(opts.auth, domain);
195
303
 
196
- const base = await fetchOne(apiHost, path, params, accept);
304
+ const base = await fetchOne(apiHost, path, params, accept, authCtx, domain);
197
305
  if (base.status === 404 && tryPrefixes && !/^\/v\d+\//.test(path)) {
198
306
  for (const p of [`/v1${path}`, `/v2${path}`]) {
199
- const tried = await fetchOne(apiHost, p, params, accept);
307
+ const tried = await fetchOne(apiHost, p, params, accept, authCtx, domain);
200
308
  if (tried.status !== 404) {
201
- tried.note = `404 on ${path}; /v*/ prefix hit โ†’ ${p}`;
309
+ const miss = missNote(authCtx, domain);
310
+ tried.note = `${miss ? miss + " โ€” " : ""}404 on ${path}; /v*/ prefix hit โ†’ ${p}`;
202
311
  return tried;
203
312
  }
204
313
  }
@@ -211,17 +320,50 @@ async function fetchOne(
211
320
  path: string,
212
321
  params: Record<string, unknown>,
213
322
  accept: string,
323
+ authCtx: ProbeAuthCtx,
324
+ domain: string,
214
325
  ): Promise<ProbeResult> {
215
- const url = buildUrl(apiHost, path, params);
216
- const res = await fetchUrl(url, { headers: { accept }, fresh: true });
217
- const raw = res.body.slice(0, 800);
218
- const finalUrl = res.finalUrl ?? url;
326
+ // Inject secret query params below the agent-supplied params map, then
327
+ // redact the surfaced URL so the real key never reaches the transcript.
328
+ const rawUrl = buildUrl(apiHost, path, { ...params, ...authCtx.queryParams });
329
+ const url = redactSecretParams(rawUrl, authCtx.secretQueryParamNames);
330
+ const hasQuerySecret = Object.keys(authCtx.queryParams).length > 0;
331
+ const res = await fetchUrl(rawUrl, {
332
+ headers: { accept, ...authCtx.headers },
333
+ fresh: true,
334
+ ...(authCtx.hasAuthBlock
335
+ ? {
336
+ hasQuerySecret,
337
+ secretHeaderNames: authCtx.secretHeaderNames,
338
+ }
339
+ : {}),
340
+ });
341
+ // Probe-local body scrub: the probe bypasses checkResponseStatus, so
342
+ // scrub known secret values from the raw slice directly โ€” a 401 body
343
+ // 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
+ }
348
+ const finalUrl = redactSecretParams(
349
+ res.finalUrl ?? rawUrl,
350
+ authCtx.secretQueryParamNames,
351
+ );
219
352
 
220
353
  if (res.status >= 400) {
221
- const note =
222
- res.status === 401 || res.status === 403
354
+ const is401 = res.status === 401 || res.status === 403;
355
+ const miss = missNote(authCtx, domain);
356
+ 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}` : ""}`;
361
+ } else {
362
+ // No auth block โ†’ the existing auth:none wording.
363
+ note = is401
223
364
  ? `${res.status} โ€” requires authentication? (guide is auth:none)`
224
365
  : `${res.status}`;
366
+ }
225
367
  return {
226
368
  url,
227
369
  finalUrl,
@@ -246,11 +388,13 @@ async function fetchOne(
246
388
  shape: null,
247
389
  draft: "",
248
390
  raw,
249
- note: "non-JSON body (set opts.accept for XML/HTML, or use a different path)",
391
+ note:
392
+ "non-JSON body (set opts.accept for XML/HTML, or use a different path)",
250
393
  };
251
394
  }
252
395
 
253
396
  const shape = summarize(data);
397
+ const miss = missNote(authCtx, domain);
254
398
  return {
255
399
  url,
256
400
  finalUrl,
@@ -259,6 +403,7 @@ async function fetchOne(
259
403
  shape,
260
404
  draft: emitDraft(path, params, shape),
261
405
  raw,
406
+ ...(miss ? { note: miss } : {}),
262
407
  };
263
408
  }
264
409
 
@@ -381,22 +526,90 @@ export const apiProbeTool = defineTool({
381
526
  description: "On 404, auto-try /v1/ and /v2/ prefixes. Default true.",
382
527
  }),
383
528
  ),
529
+ auth: Type.Optional(
530
+ Type.Object(
531
+ {
532
+ secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
533
+ secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
534
+ },
535
+ {
536
+ 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.",
538
+ },
539
+ ),
540
+ ),
541
+ domain: Type.Optional(
542
+ Type.String({
543
+ description:
544
+ "Domain for secrets-store lookups; defaults to apiHost's hostname.",
545
+ }),
546
+ ),
547
+ listSecrets: Type.Optional(
548
+ Type.Boolean({
549
+ description:
550
+ "Learn mode only: list provisioned secret names for the domain (no fetch). Names only, never values. Refused under /api on.",
551
+ }),
552
+ ),
384
553
  }),
385
554
 
386
555
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
387
- const { apiHost, path, tryPrefixes } = params as {
556
+ const { apiHost, path, tryPrefixes, auth, domain, listSecrets } = params as {
388
557
  apiHost: string;
389
558
  path: string;
390
559
  params?: Record<string, unknown>;
391
560
  tryPrefixes?: boolean;
561
+ auth?: {
562
+ secretRefs?: Record<string, string>;
563
+ secretQueryRefs?: Record<string, string>;
564
+ };
565
+ domain?: string;
566
+ listSecrets?: boolean;
392
567
  };
393
568
  const userParams = (params as Record<string, unknown>)["params"] as
394
569
  | Record<string, unknown>
395
570
  | undefined;
396
571
 
572
+ // Learn-gated secrets discovery โ€” short-circuits the fetch entirely.
573
+ // The agent's only programmatic path to the secrets store; /api secrets is
574
+ // user-typed only. Names only, never values.
575
+ if (listSecrets === true) {
576
+ if (!isApiLearnEnabled()) {
577
+ return {
578
+ content: [
579
+ {
580
+ type: "text",
581
+ text:
582
+ "api-probe: listSecrets: true is learn mode only โ€” run /api learn first.",
583
+ },
584
+ ],
585
+ details: { error: "learn_mode_only" },
586
+ };
587
+ }
588
+ // Bare call (no domain, no apiHost): orphan list only. apiHost present:
589
+ // orphan list first, then the per-domain view. domain present: unchanged.
590
+ const unscoped = domain ? undefined : unscopedStoreDomains();
591
+ const blocks: string[] = [];
592
+ if (unscoped !== undefined) blocks.push(formatUnscopedDomains(unscoped));
593
+ const target = domain ?? (apiHost ? hostnameOf(apiHost) : undefined);
594
+ if (target !== undefined) {
595
+ const secrets = listDomainSecrets(target);
596
+ blocks.push(formatSecretsResult(secrets));
597
+ return {
598
+ content: [{ type: "text", text: blocks.join("\n\n") }],
599
+ details: unscoped === undefined ? { secrets } : { secrets, unscoped },
600
+ };
601
+ }
602
+ return {
603
+ content: [{ type: "text", text: blocks.join("\n\n") }],
604
+ details: { unscoped: unscoped! },
605
+ };
606
+ }
607
+
397
608
  try {
398
609
  const result = await probe(apiHost, path, userParams ?? {}, {
399
- ...(tryPrefixes !== undefined ? { tryPrefixes } : {}),
610
+ ...(tryPrefixes === undefined ? {} : { tryPrefixes }),
611
+ ...(auth ? { auth } : {}),
612
+ ...(domain ? { domain } : {}),
400
613
  });
401
614
  return {
402
615
  content: [{ type: "text", text: formatProbeResult(result) }],
@@ -439,6 +652,21 @@ export const apiProbeTool = defineTool({
439
652
  if (d?.error) {
440
653
  return new Text(theme.fg("error", `โš  ${contentText(result, "?")}`), 0, 0);
441
654
  }
655
+ const secrets = d?.secrets as
656
+ | { domain: string; provisioned: string[] }
657
+ | undefined;
658
+ 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);
669
+ }
442
670
  const status = d?.status as number | undefined;
443
671
  const shape = d?.shape as ShapeSummary | null | undefined;
444
672
 
@@ -478,8 +706,7 @@ function formatProbeResult(r: ProbeResult): string {
478
706
  lines.push(` shape: ${s.topLevel}`);
479
707
  if (s.keys.length > 0) lines.push(` keys: ${s.keys.join(", ")}`);
480
708
  lines.push(` via: ${s.suggestedVia}`);
481
- if (s.suggestedItemsPath)
482
- lines.push(` itemsPath: ${s.suggestedItemsPath}`);
709
+ if (s.suggestedItemsPath) lines.push(` itemsPath: ${s.suggestedItemsPath}`);
483
710
  if (s.arrayLen > 0) lines.push(` arrayLen: ${s.arrayLen}`);
484
711
  if (s.paginationMarkers.length > 0)
485
712
  lines.push(` pagination markers: ${s.paginationMarkers.join(", ")}`);
@@ -498,3 +725,59 @@ function formatProbeResult(r: ProbeResult): string {
498
725
  }
499
726
  return lines.join("\n");
500
727
  }
728
+
729
+ /** Store domains that are provisioned but not scoped to any guide.
730
+ * Authoring-loop diagnostic: surfaces bootstrap + migration-orphan
731
+ * secrets. Names only. */
732
+ function unscopedStoreDomains(): string[] {
733
+ return listDomains().filter((d) => findGuidesByDomain(d).length === 0);
734
+ }
735
+
736
+ function formatUnscopedDomains(domains: string[]): string {
737
+ const lines: string[] = ["๐Ÿ—‚ unscoped store domains (provisioned, no guide)"];
738
+ lines.push(` ${domains.length > 0 ? domains.join(", ") : "(none)"}`);
739
+ lines.push(" (names only โ€” values never leave the store)");
740
+ return lines.join("\n");
741
+ }
742
+
743
+ /** List mode: provisioned secret names for a domain (names only). */
744
+ function listDomainSecrets(domain: string): {
745
+ domain: string;
746
+ provisioned: string[];
747
+ declared?: string[];
748
+ } {
749
+ const provisioned = listNames(domain);
750
+ const matches = findGuidesByDomain(domain);
751
+ if (matches.length === 0) return { domain, provisioned };
752
+ const declaredSet = new Set<string>();
753
+ for (const { guide } of matches) {
754
+ for (const n of [
755
+ ...(guide.auth.requires ?? []),
756
+ ...(guide.auth.optional ?? []),
757
+ ]) {
758
+ declaredSet.add(n);
759
+ }
760
+ }
761
+ const declared = [...declaredSet].sort();
762
+ return { domain, provisioned, declared };
763
+ }
764
+
765
+ function formatSecretsResult(s: {
766
+ domain: string;
767
+ provisioned: string[];
768
+ declared?: string[];
769
+ }): string {
770
+ const lines: string[] = [`๐Ÿ”‘ secrets for ${s.domain}`];
771
+ lines.push(
772
+ ` provisioned: ${s.provisioned.length > 0 ? s.provisioned.join(", ") : "(none)"}`,
773
+ );
774
+ if (s.declared !== undefined) {
775
+ lines.push(
776
+ ` declared: ${s.declared.length > 0 ? s.declared.join(", ") : "(none)"}`,
777
+ );
778
+ const gaps = s.declared.filter((d) => !s.provisioned.includes(d));
779
+ if (gaps.length > 0) lines.push(` gaps: ${gaps.join(", ")}`);
780
+ }
781
+ lines.push(" (names only โ€” values never leave the store)");
782
+ return lines.join("\n");
783
+ }