pi-lean-host 0.3.0 → 0.4.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.
@@ -33,8 +33,8 @@ import {
33
33
  } from "../core/auth.js";
34
34
  import { listDomains, listNames } from "../core/secrets-store.js";
35
35
  import { findGuidesByDomain } from "../core/guide-store.js";
36
- import { GUIDE_SCHEMA_VERSION } from "../core/api-guide-types.js";
37
36
  import { isApiLearnEnabled } from "../core/api-toggle.js";
37
+ import { serverMessage, isPlanGated } from "../core/status-hint.js";
38
38
  import { appendFooter, contentText } from "./utils.js";
39
39
 
40
40
  // ═══════════════════════════════════════════════════════════════════
@@ -71,9 +71,6 @@ export interface ProbeResult {
71
71
  raw: string;
72
72
  /** Human note (auth-required, 404, version-prefix hit, non-JSON, …). */
73
73
  note?: string;
74
- /** True when the caller didn't pass scaffold: true and no guide claims the
75
- * domain yet — the authoring loop should surface the skeleton option. */
76
- scaffoldNudge?: boolean;
77
74
  }
78
75
 
79
76
  export interface ProbeOptions {
@@ -99,13 +96,6 @@ export interface ProbeOptions {
99
96
  };
100
97
  /** Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain). */
101
98
  domain?: string;
102
- /**
103
- * Emit a full recipe skeleton (frontmatter + auth + operations) when no
104
- * guide exists for the domain; auto-degrades to a single op block + merge
105
- * note when one or more guides already claim the domain. Opt-in —
106
- * without it the output is today's op-block-only draft.
107
- */
108
- scaffold?: boolean;
109
99
  }
110
100
 
111
101
  // ═══════════════════════════════════════════════════════════════════
@@ -388,7 +378,6 @@ export async function probe(
388
378
  authCtx,
389
379
  domain,
390
380
  versionPrefixOf(apiHost),
391
- opts,
392
381
  );
393
382
  if (base.status !== 404 || !walkVersions || /^\/v\d+\//.test(path)) {
394
383
  return base;
@@ -403,7 +392,7 @@ export async function probe(
403
392
  return base;
404
393
  }
405
394
  const hit = await walkBackward(
406
- { apiHost, path, params, accept, authCtx, domain, opts },
395
+ { apiHost, path, params, accept, authCtx, domain },
407
396
  Number(stated),
408
397
  );
409
398
  return hit ?? base;
@@ -428,7 +417,6 @@ async function walkBackward(
428
417
  accept: string;
429
418
  authCtx: ProbeAuthCtx;
430
419
  domain: string;
431
- opts: ProbeOptions;
432
420
  },
433
421
  start: number,
434
422
  ): Promise<ProbeResult | null> {
@@ -443,7 +431,6 @@ async function walkBackward(
443
431
  ctx.authCtx,
444
432
  ctx.domain,
445
433
  `/v${k}`,
446
- ctx.opts,
447
434
  );
448
435
  if (tried.status !== 404) {
449
436
  // A walk hit may itself have redirected (e.g. /v2 301→ /v3); the
@@ -483,7 +470,6 @@ async function fetchOne(
483
470
  authCtx: ProbeAuthCtx,
484
471
  domain: string,
485
472
  prefix = "",
486
- opts: ProbeOptions = {},
487
473
  ): Promise<ProbeResult> {
488
474
  // Inject secret query params below the agent-supplied params map, then
489
475
  // redact the surfaced URL so the real key never reaches the transcript.
@@ -510,25 +496,44 @@ async function fetchOne(
510
496
  );
511
497
 
512
498
  if (res.status >= 400) {
513
- const is401 = res.status === 401 || res.status === 403;
499
+ // 401 or 403 — both mean the request was rejected on auth grounds
500
+ // (gated endpoint, or bad/missing credentials), distinct from other
501
+ // 4xx/5xx statuses. The name is deliberate: it covers 403 too.
502
+ const isAuthError = res.status === 401 || res.status === 403;
514
503
  const miss = missNote(authCtx, domain);
515
504
  let note: string;
516
505
  if (!authCtx.hasAuthBlock) {
517
506
  // No auth injected — a 401/403 means the endpoint is gated and the
518
507
  // probe sent nothing. Pre-guide authoring tool: no guide in scope,
519
508
  // so no stale "(guide is auth:none)" wording.
520
- note = is401
509
+ note = isAuthError
521
510
  ? `${res.status} — endpoint requires auth; configure auth injection (auth.secretRefs)`
522
511
  : `${res.status}`;
523
512
  } else if (miss) {
524
513
  // Auth injected but a required secret was missing — the miss names it.
525
- note = `${res.status}${is401 ? " — auth rejected;" : ""} ${miss}`;
514
+ note = `${res.status}${isAuthError ? " — auth rejected;" : ""} ${miss}`;
526
515
  } else {
527
- // Auth injected, nothing missing — rejection means the credentials
528
- // were wrong (header name / secret value), not the endpoint.
529
- note = is401
530
- ? `${res.status} — auth injected but rejected; verify header name and secret value`
531
- : `${res.status}`;
516
+ // Auth injected, nothing missing. A 403 means authenticated but
517
+ // forbidden — "verify header name" is a 401 signal, not a 403 one.
518
+ // Surface the server's own reason (from the scrubbed `raw`, never
519
+ // `res.body`) when we can parse it; fall back to the bare status.
520
+ // When the reason reads as plan-gating, say so — it's the key's
521
+ // plan, not the recipe.
522
+ if (res.status === 403) {
523
+ const msg = serverMessage(raw);
524
+ if (msg) {
525
+ const suffix = isPlanGated(raw)
526
+ ? "plan/subscription limitation on the key, not the recipe"
527
+ : "auth configured correctly; not a header/secret problem";
528
+ note = `${res.status} — ${msg} (${suffix})`;
529
+ } else {
530
+ note = `${res.status}`;
531
+ }
532
+ } else if (res.status === 401) {
533
+ note = `${res.status} — auth injected but rejected; verify header name and secret value`;
534
+ } else {
535
+ note = `${res.status}`;
536
+ }
532
537
  }
533
538
  if (authCtx.misconfiguredPrefixes) {
534
539
  note += ` — ${MISCONFIGURED_PREFIXES_NOTE}`;
@@ -564,21 +569,11 @@ async function fetchOne(
564
569
 
565
570
  const shape = summarize(data);
566
571
  const miss = missNote(authCtx, domain);
567
- let draft = emitDraft(path, params, shape, prefix);
572
+ const draft = emitDraft(path, params, shape, prefix);
568
573
  let note: string | undefined = miss;
569
- if (opts.scaffold && draft) {
570
- const sc = emitScaffold({ apiHost, domain, draft, auth: opts.auth });
571
- draft = sc.draft;
572
- if (sc.note) note = [note, sc.note].filter(Boolean).join(" — ");
573
- }
574
574
  if (authCtx.misconfiguredPrefixes) {
575
575
  note = [note, MISCONFIGURED_PREFIXES_NOTE].filter(Boolean).join(" — ");
576
576
  }
577
- // Targeted scaffold nudge: only when the caller didn't pass
578
- // scaffold: true AND no guide claims the domain yet — authors who already
579
- // used the skeleton (or who have a guide) see no noise.
580
- const scaffoldNudge =
581
- opts.scaffold !== true && findGuidesByDomain(domain).length === 0;
582
577
  return {
583
578
  url,
584
579
  finalUrl,
@@ -588,7 +583,6 @@ async function fetchOne(
588
583
  draft,
589
584
  raw,
590
585
  ...(note ? { note } : {}),
591
- ...(scaffoldNudge ? { scaffoldNudge } : {}),
592
586
  };
593
587
  }
594
588
 
@@ -703,113 +697,6 @@ function suggestName(path: string): string {
703
697
  .replace(/[^a-zA-Z0-9]/g, "");
704
698
  }
705
699
 
706
- // ═══════════════════════════════════════════════════════════════════
707
- // Scaffold emission — full skeleton vs op-block + merge note
708
- // ═══════════════════════════════════════════════════════════════════
709
-
710
- /**
711
- * Translate the probe's auth-injection params into a `kind: static-key` auth
712
- * block (probe auth shape matches the guide schema).
713
- * `requires` = the union of secret names referenced by the refs. Returns
714
- * undefined when no injection refs are declared (auth: none default).
715
- */
716
- function emitAuthBlock(
717
- auth: NonNullable<ProbeOptions["auth"]> | undefined,
718
- ): string | undefined {
719
- const refs = auth?.secretRefs ?? {};
720
- const queryRefs = auth?.secretQueryRefs ?? {};
721
- const prefixes = auth?.headerPrefixes ?? {};
722
- const names = [
723
- ...new Set([...Object.values(refs), ...Object.values(queryRefs)]),
724
- ];
725
- if (names.length === 0) return undefined;
726
- const lines = [
727
- "auth:",
728
- " kind: static-key",
729
- ` requires: [${names.join(", ")}]`,
730
- ];
731
- if (Object.keys(refs).length > 0) {
732
- lines.push(" secretRefs:");
733
- for (const [header, secret] of Object.entries(refs))
734
- lines.push(` ${header}: ${secret}`);
735
- }
736
- if (Object.keys(queryRefs).length > 0) {
737
- lines.push(" secretQueryRefs:");
738
- for (const [param, secret] of Object.entries(queryRefs))
739
- lines.push(` ${param}: ${secret}`);
740
- }
741
- if (Object.keys(prefixes).length > 0) {
742
- lines.push(" headerPrefixes:");
743
- for (const [header, prefix] of Object.entries(prefixes))
744
- lines.push(` ${header}: "${prefix}"`);
745
- }
746
- return lines.join("\n");
747
- }
748
-
749
- /**
750
- * Full recipe skeleton (bootstrap): frontmatter + auth + the probe's op
751
- * block. `schemaVersion` literal matches what api-learn stamps on save, so a
752
- * scaffolded guide is detection-ready the moment it's saved. Pagination stays
753
- * op-level only (a single probe justifies one op's pagination, never a
754
- * top-level default).
755
- */
756
- function emitScaffoldSkeleton(opts: {
757
- apiHost: string;
758
- domain: string;
759
- draft: string;
760
- auth: ProbeOptions["auth"];
761
- }): string {
762
- const lines = [
763
- "---",
764
- "kind: api",
765
- `domains: [${opts.domain}]`,
766
- `apiHost: ${opts.apiHost}`,
767
- "responseShape:",
768
- " format: json",
769
- "gatherAllMax: 1000",
770
- `schemaVersion: ${GUIDE_SCHEMA_VERSION}`,
771
- ];
772
- const authBlock = emitAuthBlock(opts.auth);
773
- if (authBlock) lines.push("", authBlock);
774
- // Op-level hint for the new constraint field — commented so a fresh
775
- // scaffold surfaces the mechanism (mirrors placeholderSkeleton).
776
- lines.push(
777
- "",
778
- "# requiresAnyOf: [id, slug, code] # at least one of these params must be supplied",
779
- "operations:",
780
- opts.draft,
781
- "---",
782
- "",
783
- );
784
- return lines.join("\n");
785
- }
786
-
787
- /**
788
- * Scaffold decision, driven by findGuidesByDomain(domain): 0 guides →
789
- * full skeleton (bootstrap); 1 guide → op block + merge note naming the one
790
- * dirName; N guides → op block + merge note listing every candidate dirName
791
- * (the merge-target choice defers to api-learn's selector). Returns the
792
- * paste-able draft + an optional human merge note.
793
- */
794
- function emitScaffold(opts: {
795
- apiHost: string;
796
- domain: string;
797
- draft: string;
798
- auth: ProbeOptions["auth"];
799
- }): { draft: string; note?: string } {
800
- const matches = findGuidesByDomain(opts.domain);
801
- if (matches.length === 0) {
802
- return { draft: emitScaffoldSkeleton(opts) };
803
- }
804
- const dirs = matches.map((m) => m.dirName);
805
- const note =
806
- matches.length === 1
807
- ? `scaffold: guide already exists — merge into \`${dirs[0]}\``
808
- : `scaffold: ${matches.length} guides already exist — merge into one of: ${dirs.join(", ")}`;
809
- return { draft: opts.draft, note };
810
- }
811
-
812
- // ═══════════════════════════════════════════════════════════════════
813
700
  // Tool definition
814
701
  // ═══════════════════════════════════════════════════════════════════
815
702
 
@@ -832,10 +719,7 @@ export const apiProbeTool = defineTool({
832
719
  "version — then probe that version explicitly. Do not default the version from " +
833
720
  "memory: a stale version that still returns 200 is not detected as old (the " +
834
721
  "backward walk only fires on 404). The probe recovers an over-claimed version " +
835
- "but cannot detect a stale-but-working one. " +
836
- "Pass scaffold: true to emit a full recipe skeleton (frontmatter + auth + " +
837
- "operations) when no guide exists for the domain; it auto-degrades to a single " +
838
- "op block + merge note when one or more guides already claim the domain.",
722
+ "but cannot detect a stale-but-working one. ",
839
723
 
840
724
  parameters: Type.Object({
841
725
  apiHost: Type.Optional(
@@ -867,14 +751,6 @@ export const apiProbeTool = defineTool({
867
751
  "On 404, walk the apiHost version backward (vN→v1) to find the highest live version. Default true.",
868
752
  }),
869
753
  ),
870
- scaffold: Type.Optional(
871
- Type.Boolean({
872
- description:
873
- "Emit a full recipe skeleton (frontmatter + auth + operations) when no guide exists for the domain; " +
874
- "auto-degrades to a single op block + merge note when one or more guides already claim the domain. " +
875
- "Opt-in — without it the output is today's op-block-only draft.",
876
- }),
877
- ),
878
754
  auth: Type.Optional(
879
755
  Type.Object(
880
756
  {
@@ -911,21 +787,19 @@ export const apiProbeTool = defineTool({
911
787
  }),
912
788
 
913
789
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
914
- const { apiHost, path, walkVersions, auth, domain, listSecrets, scaffold } =
915
- params as {
916
- apiHost?: string;
917
- path?: string;
918
- params?: Record<string, unknown>;
919
- walkVersions?: boolean;
920
- auth?: {
921
- secretRefs?: Record<string, string>;
922
- secretQueryRefs?: Record<string, string>;
923
- headerPrefixes?: Record<string, string>;
924
- };
925
- domain?: string;
926
- listSecrets?: boolean;
927
- scaffold?: boolean;
790
+ const { apiHost, path, walkVersions, auth, domain, listSecrets } = params as {
791
+ apiHost?: string;
792
+ path?: string;
793
+ params?: Record<string, unknown>;
794
+ walkVersions?: boolean;
795
+ auth?: {
796
+ secretRefs?: Record<string, string>;
797
+ secretQueryRefs?: Record<string, string>;
798
+ headerPrefixes?: Record<string, string>;
928
799
  };
800
+ domain?: string;
801
+ listSecrets?: boolean;
802
+ };
929
803
  const userParams = (params as Record<string, unknown>)["params"] as
930
804
  | Record<string, unknown>
931
805
  | undefined;
@@ -995,7 +869,6 @@ export const apiProbeTool = defineTool({
995
869
  ...(walkVersions === undefined ? {} : { walkVersions }),
996
870
  ...(auth ? { auth } : {}),
997
871
  ...(domain ? { domain } : {}),
998
- ...(scaffold === undefined ? {} : { scaffold }),
999
872
  });
1000
873
  return {
1001
874
  content: [{ type: "text", text: formatProbeResult(result) }],
@@ -1029,7 +902,6 @@ export const apiProbeTool = defineTool({
1029
902
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-probe "))];
1030
903
  if (args.apiHost) parts.push(theme.fg("accent", `"${args.apiHost}"`));
1031
904
  if (args.path) parts.push(theme.fg("dim", `› ${args.path}`));
1032
- if (args.scaffold) parts.push(theme.fg("dim", "· scaffold"));
1033
905
  return new Text(parts.join(" "), 0, 0);
1034
906
  },
1035
907
 
@@ -1129,13 +1001,7 @@ export function formatProbeResult(r: ProbeResult): string {
1129
1001
  lines.push(r.raw);
1130
1002
  }
1131
1003
  lines.push("");
1132
- const footer = [...DOCS_NUDGE];
1133
- if (r.scaffoldNudge) {
1134
- footer.push(
1135
- "No guide for this domain yet — pass scaffold: true to emit a full recipe skeleton.",
1136
- );
1137
- }
1138
- lines.push(` ${footer.join("\n ")}`);
1004
+ lines.push(` ${DOCS_NUDGE.join("\n ")}`);
1139
1005
  return lines.join("\n");
1140
1006
  }
1141
1007