pi-lean-host 0.3.1 → 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.
@@ -12,7 +12,7 @@ import { parse as yamlParse } from "yaml";
12
12
  import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
13
13
  import { join } from "node:path";
14
14
  import type { Guide } from "./guide-loader.js";
15
- import { extractPathTokens } from "./path-template.js";
15
+ import { extractPathTokens, slug } from "./path-template.js";
16
16
  import {
17
17
  GATHER_ALL_MAX_FALLBACK,
18
18
  GUIDE_SCHEMA_VERSION,
@@ -34,6 +34,7 @@ import {
34
34
  type AcceptType,
35
35
  type QueryParamSpec,
36
36
  type LoadedApiGuides,
37
+ type NotifyFn,
37
38
  } from "./api-guide-types.js";
38
39
 
39
40
  // ═══════════════════════════════════════════════════════════════════
@@ -193,21 +194,47 @@ interface ReservedPlainHit {
193
194
  * relative to the frontmatter block (matching yamlParse) and count from the
194
195
  * raw line, indentation included. Advisory: only fires on the reserved-char
195
196
  * class, which the parser would reject anyway.
197
+ *
198
+ * Block-scalar aware: a `key: >` / `key: |` line opens a folded/literal block
199
+ * whose continuation lines are free-form prose (markdown backticks, `field:
200
+ * value` snippets) — not `key: value` pairs — so they are skipped until a line
201
+ * dedents back to the header's indentation. Without this, a folded
202
+ * `description: >` block containing e.g. `` `all:` `` would be misread as a
203
+ * plain scalar starting with a reserved char.
196
204
  */
197
205
  function scanReservedPlainStarts(fm: string): ReservedPlainHit[] {
198
206
  const hits: ReservedPlainHit[] = [];
199
207
  const lines = fm.split("\n");
208
+ // Indentation of the currently-open block scalar header line, or -1 when
209
+ // not inside one. Content stays inside until a line dedents to <= this.
210
+ let blockIndent = -1;
200
211
  for (let i = 0; i < lines.length; i++) {
201
212
  const raw = lines[i] ?? "";
213
+ const indent = raw.length - raw.trimStart().length;
202
214
  const line = raw.trimStart();
203
- // Skip blank, comment, and list-item lines (op headers like
204
- // `- name: …` — the backtick footgun lives in `description:`-style
205
- // value lines, which are never `- `-prefixed).
206
- if (line === "" || line.startsWith("#") || line.startsWith("- ")) continue;
215
+ if (blockIndent >= 0) {
216
+ // Blank lines are block content too; only a non-blank dedent ends it.
217
+ if (line === "" || indent > blockIndent) continue;
218
+ blockIndent = -1;
219
+ }
220
+ // Skip blank and comment lines.
221
+ if (line === "" || line.startsWith("#")) continue;
207
222
  const m = /^[^:#]+: /.exec(line);
208
223
  if (!m) continue;
209
224
  const ch = line[m[0].length];
210
- if (ch === undefined || !RESERVED_PLAIN_START.has(ch)) continue;
225
+ if (ch === undefined) continue;
226
+ // `>` / `|` value → block scalar opener (also on `- `-prefixed list
227
+ // items like `- description: >`). Enter block mode; its content lines
228
+ // are prose and must not be scanned.
229
+ if (ch === ">" || ch === "|") {
230
+ blockIndent = indent;
231
+ continue;
232
+ }
233
+ // List-item lines (op headers like `- name: …`) are not top-level
234
+ // `key:` pairs — the backtick footgun lives in `description:`-style
235
+ // value lines, which are never `- `-prefixed.
236
+ if (line.startsWith("- ")) continue;
237
+ if (!RESERVED_PLAIN_START.has(ch)) continue;
211
238
  hits.push({
212
239
  line: i + 1,
213
240
  col: raw.length - line.length + m[0].length + 1,
@@ -540,65 +567,6 @@ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
540
567
  );
541
568
  }
542
569
 
543
- /** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
544
- * `requires`) so the unknown-key error can say "did you mean X?" instead of a
545
- * bare rejection. */
546
- function editDistance(a: string, b: string): number {
547
- const m = a.length;
548
- const n = b.length;
549
- if (m === 0) return n;
550
- if (n === 0) return m;
551
- let prev = Array.from({ length: n + 1 }, (_, j) => j);
552
- for (let i = 1; i <= m; i++) {
553
- const cur = new Array<number>(n + 1);
554
- cur[0] = i;
555
- for (let j = 1; j <= n; j++) {
556
- cur[j] = Math.min(
557
- prev[j]! + 1,
558
- cur[j - 1]! + 1,
559
- prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
560
- );
561
- }
562
- prev = cur;
563
- }
564
- return prev[n]!;
565
- }
566
-
567
- /** Nearest known auth key within edit distance ≤ 2, or undefined. */
568
- function nearestKnownKey(
569
- key: string,
570
- known: ReadonlySet<string>,
571
- ): string | undefined {
572
- let best: string | undefined;
573
- let bestDist = Infinity;
574
- for (const k of known) {
575
- const d = editDistance(key, k);
576
- if (d < bestDist) {
577
- bestDist = d;
578
- best = k;
579
- }
580
- }
581
- return bestDist <= 2 ? best : undefined;
582
- }
583
-
584
- /**
585
- * Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
586
- * X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
587
- * the real secretRefs/requires shape; anything else → list the known keys.
588
- */
589
- function authUnknownKeyFix(unknownKeys: string[]): string {
590
- for (const key of unknownKeys) {
591
- const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
592
- if (known !== undefined) {
593
- return `Unknown auth key "${key}" — did you mean "${known}"?`;
594
- }
595
- }
596
- if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
597
- return `The keyed-header shape is auth.secretRefs: { <header>: <secret-name> } with the secret declared in auth.requires (or auth.optional) — replace name/secret with secretRefs + requires.`;
598
- }
599
- return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
600
- }
601
-
602
570
  function validateAuth(
603
571
  raw: unknown,
604
572
  file: string | undefined,
@@ -645,8 +613,8 @@ function validateAuth(
645
613
  // Strict auth schema — reject unknown keys. The parser used to
646
614
  // silently drop unknown keys (a wrong-but-plausible shape like
647
615
  // `name`/`secret` saved a guide the executor then silently couldn't
648
- // honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
649
- // mean X?", wrong shape → secretRefs/requires).
616
+ // honor). Reject, don't infer: `expected` already lists the known keys
617
+ // and `found` names the offenders — no separate fix needed.
650
618
  const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
651
619
  if (unknownKeys.length > 0) {
652
620
  const first = unknownKeys[0]!;
@@ -657,7 +625,6 @@ function validateAuth(
657
625
  `unknown key(s): ${unknownKeys.join(", ")}`,
658
626
  {
659
627
  snippet: snippetFor(fm, "auth"),
660
- fix: authUnknownKeyFix(unknownKeys),
661
628
  },
662
629
  );
663
630
  }
@@ -743,10 +710,11 @@ function validateAuth(
743
710
  optional = optRaw as string[];
744
711
  }
745
712
 
746
- // static-key header prefixes: header name → non-empty prefix string
747
- // prepended to the resolved secret value. Same mapping shape as secretRefs;
748
- // every key must also be a secretRefs header (a prefix for a non-secret
749
- // header is a mistake).
713
+ // static-key header prefixes: header name → prefix string prepended to the
714
+ // resolved secret value (empty allowed — a bare-key header like CMC's
715
+ // X-CMC_PRO_API_KEY has no scheme). Same mapping shape as secretRefs; every
716
+ // key must also be a secretRefs header (a prefix for a non-secret header is
717
+ // a mistake).
750
718
  let headerPrefixes: Record<string, string> | undefined;
751
719
  if (a["headerPrefixes"] !== undefined) {
752
720
  const hp = parseStringRecord(
@@ -754,9 +722,8 @@ function validateAuth(
754
722
  file,
755
723
  fm,
756
724
  "auth.headerPrefixes",
757
- "a YAML mapping of header name → non-empty prefix string",
758
- (v) =>
759
- typeof v === "string" && v.length > 0 && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
725
+ "a YAML mapping of header name → prefix string (empty allowed for bare-key headers)",
726
+ (v) => typeof v === "string" && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
760
727
  );
761
728
  if (isParseErr(hp)) return hp;
762
729
  headerPrefixes = hp;
@@ -1638,12 +1605,38 @@ export function projectToGuide(guide: ApiGuide): Guide {
1638
1605
  // ═══════════════════════════════════════════════════════════════════
1639
1606
  // Directory loader — one malformed guide doesn't block the store.
1640
1607
  //
1641
- // Loads from per-domain subdirectories: <dir>/<domain>/guide.md.
1642
- // Flat top-level .md files are no longer loaded (pre-ship break;
1643
- // no production user guides exist before this change).
1608
+ // Loads from per-guide subdirectories: <dir>/<slug(shortName)>/guide.md.
1609
+ // The folder name must equal slug(shortName) — a divergent folder routes to
1610
+ // malformed (enforced), so the active set holds at most one guide per
1611
+ // shortName. Flat top-level .md files are not loaded.
1644
1612
  // ═══════════════════════════════════════════════════════════════════
1645
1613
 
1646
- export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1614
+ /**
1615
+ * Push a malformed guide and warn about it. One helper owns both the catalog
1616
+ * entry and the load-time warn, so every malformed guide — parse
1617
+ * failure, illegal shortName, divergent folder — surfaces the same signal
1618
+ * (and its actionable `fix` when present) instead of being silently
1619
+ * quarantined. Fires once per cached scan, same channel as the duplicate-
1620
+ * shortName check.
1621
+ */
1622
+ function pushMalformed(
1623
+ result: LoadedApiGuides,
1624
+ file: string,
1625
+ filename: string,
1626
+ error: ParseError,
1627
+ warn: (msg: string) => void,
1628
+ ): void {
1629
+ result.malformed.push({ file, filename, error });
1630
+ warn(
1631
+ `⚠ Malformed guide '${filename}': ${error.field} — expected ${error.expected}; found ${error.found}.` +
1632
+ (error.fix ? ` ${error.fix}` : ""),
1633
+ );
1634
+ }
1635
+
1636
+ export function loadApiGuidesFromDir(
1637
+ dir: string,
1638
+ notify?: NotifyFn,
1639
+ ): LoadedApiGuides {
1647
1640
  const result: LoadedApiGuides = { guides: {}, malformed: [] };
1648
1641
  if (!existsSync(dir)) return result;
1649
1642
  let entries: string[];
@@ -1652,6 +1645,35 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1652
1645
  } catch {
1653
1646
  return result;
1654
1647
  }
1648
+ // Scan-local duplicate-shortName tracker (migration-window check only).
1649
+ // shortName → the first folder that declared it, so the duplicate warning
1650
+ // can name both folders. Not a field on LoadedApiGuides.
1651
+ const seenShortNames = new Map<string, string>();
1652
+
1653
+ // Every load-time diagnostic routes through one channel: ctx.ui.notify
1654
+ // when the caller has a UI context (renders via the Text component —
1655
+ // wraps long lines, honors newlines), else console.warn. One fallback
1656
+ // here, not one repeated per call site.
1657
+ const warn = (msg: string) => {
1658
+ if (notify) notify(msg, "warning");
1659
+ else console.warn(msg);
1660
+ };
1661
+
1662
+ // TODO(0.5.0): remove — migration banner for the 0.4.0 folder-structure
1663
+ // change only. The permanent divergence + illegal-shortName checks below
1664
+ // stay; only this prelude and the duplicate-shortName check are 0.5.0
1665
+ // deletions. Fires once, immediately before the first identity warning, so
1666
+ // it prepends the wall of migration warnings with the agent instructions.
1667
+ let bannerEmitted = false;
1668
+ const emitMigrationBanner = () => {
1669
+ if (bannerEmitted) return;
1670
+ bannerEmitted = true;
1671
+ const msg =
1672
+ `\n⚠ pi-lean-host 0.4.0 changed the guide folder structure: each guide must now live ` +
1673
+ `in a folder named slug(shortName). Pass the warnings below to the ` +
1674
+ `agent to fix them (rename the folder or set a valid shortName), then /reload.\n`;
1675
+ warn(msg);
1676
+ };
1655
1677
  for (const entry of entries) {
1656
1678
  const entryPath = join(dir, entry);
1657
1679
  try {
@@ -1665,7 +1687,7 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1665
1687
  } catch {
1666
1688
  continue;
1667
1689
  }
1668
- const name = entry; // domain name = subdir name
1690
+ const name = entry; // folder name = slug(shortName) in steady state
1669
1691
  let raw: string;
1670
1692
  try {
1671
1693
  raw = readFileSync(guidePath, "utf-8");
@@ -1677,13 +1699,69 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1677
1699
  filename: name,
1678
1700
  });
1679
1701
  if (parsed.ok) {
1680
- result.guides[name] = parsed.guide;
1702
+ const guide = parsed.guide;
1703
+ // Illegal-shortName + divergence checks (permanent). One try/catch
1704
+ // owns the slug() call: a throw (empty or all-symbol shortName) is
1705
+ // routed to malformed, never escaped. This wrapping lives in the
1706
+ // permanent checks so the loader stays safe after the 0.5.0
1707
+ // duplicate-check deletion.
1708
+ let slugged: string;
1709
+ try {
1710
+ slugged = slug(guide.shortName);
1711
+ } catch {
1712
+ emitMigrationBanner();
1713
+ pushMalformed(
1714
+ result,
1715
+ guidePath,
1716
+ name,
1717
+ {
1718
+ field: "shortName",
1719
+ expected: "a shortName that slugs to a non-empty safe directory name",
1720
+ found: `"${guide.shortName}"`,
1721
+ fix: "Set a valid shortName (lowercase letters, digits, and '-') in the guide's frontmatter.",
1722
+ },
1723
+ warn,
1724
+ );
1725
+ continue;
1726
+ }
1727
+ // TODO(0.5.0): remove — save-time slug() makes duplicate shortNames
1728
+ // unreachable once all folders are migrated. Tracked on guides that
1729
+ // pass the slug (before divergence routing) so the migration window —
1730
+ // two divergent folders sharing a valid shortName — still surfaces a
1731
+ // clear "delete one" warning instead of two opaque malformed entries.
1732
+ const first = seenShortNames.get(guide.shortName);
1733
+ if (first === undefined) {
1734
+ seenShortNames.set(guide.shortName, entry);
1735
+ } else {
1736
+ emitMigrationBanner();
1737
+ const dupMsg =
1738
+ `⚠ Duplicate shortName '${guide.shortName}' in folders '${first}' and '${entry}'. ` +
1739
+ `Delete one: /api delete <one>`;
1740
+ warn(dupMsg);
1741
+ }
1742
+ // Divergence check (permanent) — ENFORCED, not advisory: the folder
1743
+ // name must equal slug(shortName); the coupling IS the identity. A
1744
+ // divergent guide routes to malformed (never loads), so the active
1745
+ // set structurally holds at most one guide per shortName.
1746
+ if (entry !== slugged) {
1747
+ emitMigrationBanner();
1748
+ pushMalformed(
1749
+ result,
1750
+ guidePath,
1751
+ name,
1752
+ {
1753
+ field: "shortName",
1754
+ expected: `a folder named slug(shortName) ('${slugged}')`,
1755
+ found: `folder '${entry}'`,
1756
+ fix: `Rename the folder to '${slugged}': mv ${entryPath} ${join(dir, slugged)}`,
1757
+ },
1758
+ warn,
1759
+ );
1760
+ continue;
1761
+ }
1762
+ result.guides[entry] = guide;
1681
1763
  } else {
1682
- result.malformed.push({
1683
- file: guidePath,
1684
- filename: name,
1685
- error: parsed.error,
1686
- });
1764
+ pushMalformed(result, guidePath, name, parsed.error, warn);
1687
1765
  }
1688
1766
  }
1689
1767
  return result;
@@ -1892,11 +1970,13 @@ export function formatApiGuideCatalog(
1892
1970
  lines.push(
1893
1971
  ` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
1894
1972
  );
1973
+ // Actionable advice on its own line, matching api-fetch/api-learn's
1974
+ // `Fix:` convention — multi-line fixes (e.g. the frontmatter template)
1975
+ // render naturally instead of being inlined into the summary line.
1976
+ if (mal.error.fix) lines.push(` fix: ${mal.error.fix}`);
1895
1977
  }
1896
1978
  if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
1897
- lines.push(
1898
- " (no guides — call api-learn({domain, recipeFile}) to author one)",
1899
- );
1979
+ lines.push(" (no guides — call api-learn({domain, dir}) to author one)");
1900
1980
  }
1901
1981
  lines.push("");
1902
1982
  lines.push(
@@ -77,3 +77,49 @@ export function assertSafeDomain(domain: string): string {
77
77
  }
78
78
  return domain;
79
79
  }
80
+
81
+ /**
82
+ * Non-decomposable Latin letters NFD can't split (single codepoints with no
83
+ * canonical decomposition: ø ß æ œ ð þ ł). NFD handles the rest of the Latin
84
+ * diacritic set (é ü å ñ ç …) via combining-mark strip. Non-Latin scripts
85
+ * (Cyrillic/CJK) still collapse to '-'; add a transliteration lib if a real
86
+ * guide ever needs them.
87
+ */
88
+ const NON_DECOMPOSABLE: Record<string, string> = {
89
+ ø: "o",
90
+ ß: "ss",
91
+ æ: "ae",
92
+ œ: "oe",
93
+ ð: "d",
94
+ þ: "th",
95
+ ł: "l",
96
+ };
97
+
98
+ /**
99
+ * Slugify a guide `shortName` into the safe single path segment that names
100
+ * its identity folder (`<guidesDir>/<slug(shortName)>/guide.md`). Lowercase;
101
+ * replace every run of non-`[a-z0-9-]` chars with `-`; collapse repeated `-`;
102
+ * strip leading/trailing `-`. The result is passed through `assertSafeDomain`
103
+ * as the single safety guard (it already rejects `/`, `\`, `\0`, `.`, `..`,
104
+ * and empty), so domains and slugs share one safety surface. After the
105
+ * transform the only reachable failure is empty (an empty or all-symbol
106
+ * `shortName`), so the throw is wrapped with a prescriptive message that
107
+ * names `shortName` rather than `domain`.
108
+ */
109
+ export function slug(shortName: string): string {
110
+ const s = shortName
111
+ .normalize("NFD")
112
+ .replace(/[\u0300-\u036f]/g, "")
113
+ .toLowerCase()
114
+ .replace(/[øßæœðþł]/g, (c) => NON_DECOMPOSABLE[c]!)
115
+ .replace(/[^a-z0-9-]+/g, "-")
116
+ .replace(/-+/g, "-")
117
+ .replace(/^-+|-+$/g, "");
118
+ try {
119
+ return assertSafeDomain(s);
120
+ } catch {
121
+ throw new Error(
122
+ `Invalid shortName '${shortName}': must slug to a non-empty directory name (lowercase letters, digits, and '-').`,
123
+ );
124
+ }
125
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Shared HTTP-error classification for the probe and fetch paths.
3
+ *
4
+ * Both api-probe and api-fetch (/api verify) hit the same real-world 403
5
+ * reality: an authenticated-but-forbidden response whose body carries the
6
+ * server's own reason. One classifier keeps the two paths from drifting —
7
+ * probe used to surface the server message while fetch threw a bare status,
8
+ * which made plan-gated 403s read as recipe bugs.
9
+ */
10
+
11
+ /** Structured "plan not authorized" signal — a 403 whose extracted reason
12
+ * mentions any of these is a key/subscription limitation, not a recipe bug.
13
+ * ponytail: keyword match, not a per-API catalog — error-code 1006 is the
14
+ * motivating case; add provider error-code regexes here if one uses a code
15
+ * without a matching word. */
16
+ const PLAN_GATING = /plan|subscription|tier|not authorized|insufficient|1006/i;
17
+
18
+ function isObj(data: unknown): data is object {
19
+ return typeof data === "object" && data !== null && !Array.isArray(data);
20
+ }
21
+
22
+ /** Extracts the server's own human-readable reason from an error body — the
23
+ * note says what the API actually means instead of a synthesized
24
+ * classification. Returns undefined when the body isn't JSON or carries no
25
+ * message field; the caller falls back to the bare status.
26
+ * ponytail: secret-scrub invariant — callers MUST pass the scrubbed body,
27
+ * never the raw one, or a key echoed in the body would leak into agent
28
+ * context. */
29
+ export function serverMessage(raw: string): string | undefined {
30
+ let data: unknown;
31
+ try {
32
+ data = JSON.parse(raw);
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ if (!isObj(data)) return undefined;
37
+ const d = data as Record<string, unknown>;
38
+ const status = isObj(d["status"])
39
+ ? (d["status"] as Record<string, unknown>)
40
+ : undefined;
41
+ const candidates: unknown[] = [
42
+ d["message"],
43
+ d["error"],
44
+ d["error_message"],
45
+ d["detail"],
46
+ status?.["error_message"],
47
+ ];
48
+ const msg = candidates.find(
49
+ (c) => typeof c === "string" && c.trim().length > 0,
50
+ );
51
+ return typeof msg === "string" ? msg.trim().slice(0, 200) : undefined;
52
+ }
53
+
54
+ /** True when the body signals a plan/subscription limitation rather than a
55
+ * recipe or credential problem. Tests the whole body (not just the
56
+ * extracted message) so bare error codes like 1006 are caught even when no
57
+ * message field exists. Callers pass the scrubbed body, per the invariant
58
+ * on `serverMessage`. */
59
+ export function isPlanGated(raw: string): boolean {
60
+ return PLAN_GATING.test(raw);
61
+ }
package/core/transport.ts CHANGED
@@ -433,7 +433,7 @@ export async function fetchUrl(
433
433
  const reqHeaders: Record<string, string> = { ...opts?.headers };
434
434
  if (!reqHeaders["user-agent"]) {
435
435
  reqHeaders["user-agent"] =
436
- "pi-lean-host/0.3.1 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
436
+ "pi-lean-host/0.4.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
437
437
  }
438
438
 
439
439
  if (!opts?.fresh && !hasAuth) {