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.
- package/README.md +101 -54
- package/core/api-guide-types.ts +14 -0
- package/core/api-toggle.ts +9 -9
- package/core/guide-store.ts +20 -5
- package/core/helpers-command.ts +6 -5
- package/core/helpers.ts +22 -6
- package/core/local-helpers.ts +10 -2
- package/core/parse-api-guide.ts +241 -84
- package/core/path-template.ts +46 -0
- package/core/status-hint.ts +61 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +124 -53
- package/index.ts +16 -1
- package/package.json +3 -1
- package/tools/api-fetch.ts +4 -3
- package/tools/api-guide.ts +1 -1
- package/tools/api-learn.ts +447 -147
- package/tools/api-probe.ts +44 -178
- package/tools/api-scaffold.ts +420 -0
- package/tools/index.ts +2 -1
package/core/parse-api-guide.ts
CHANGED
|
@@ -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
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -98,7 +99,7 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
|
98
99
|
"tokenBag",
|
|
99
100
|
]);
|
|
100
101
|
|
|
101
|
-
// Strict auth schema
|
|
102
|
+
// Strict auth schema: the only keys validateAuth reads. Any other key
|
|
102
103
|
// under `auth` is rejected at parse — the parser used to silently drop
|
|
103
104
|
// unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
|
|
104
105
|
// guide the executor then silently couldn't honor.
|
|
@@ -165,6 +166,84 @@ function snippetFor(frontmatter: string, key: string): string | undefined {
|
|
|
165
166
|
return out.join("\n");
|
|
166
167
|
}
|
|
167
168
|
|
|
169
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
170
|
+
// Reserved-char plain-scalar pre-scan
|
|
171
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Chars that make a plain scalar invalid as a value — yaml's
|
|
175
|
+
* "Plain value cannot start with reserved character" error class. Backtick is
|
|
176
|
+
* the observed footgun (markdown-style `` `field` `` refs pasted into
|
|
177
|
+
* descriptions); `%`/`@`/`,` are the same error class and never legitimate at
|
|
178
|
+
* the start of a value. `|`/`>` (block scalars), `[`/`{` (flow), quotes, and
|
|
179
|
+
* `#` (comments) are all legitimate starts and deliberately NOT flagged.
|
|
180
|
+
*/
|
|
181
|
+
const RESERVED_PLAIN_START = new Set(["`", "%", "@", ","]);
|
|
182
|
+
|
|
183
|
+
interface ReservedPlainHit {
|
|
184
|
+
line: number;
|
|
185
|
+
col: number;
|
|
186
|
+
char: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Best-effort one-pass scan for `key: <value>` lines whose plain-scalar value
|
|
191
|
+
* starts with a reserved YAML character. yamlParse throws on the FIRST such
|
|
192
|
+
* value and stops, so a multi-backtick frontmatter needs one save/validate
|
|
193
|
+
* cycle per offender — this lists them all at once. Line/column are reported
|
|
194
|
+
* relative to the frontmatter block (matching yamlParse) and count from the
|
|
195
|
+
* raw line, indentation included. Advisory: only fires on the reserved-char
|
|
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.
|
|
204
|
+
*/
|
|
205
|
+
function scanReservedPlainStarts(fm: string): ReservedPlainHit[] {
|
|
206
|
+
const hits: ReservedPlainHit[] = [];
|
|
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;
|
|
211
|
+
for (let i = 0; i < lines.length; i++) {
|
|
212
|
+
const raw = lines[i] ?? "";
|
|
213
|
+
const indent = raw.length - raw.trimStart().length;
|
|
214
|
+
const line = raw.trimStart();
|
|
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;
|
|
222
|
+
const m = /^[^:#]+: /.exec(line);
|
|
223
|
+
if (!m) continue;
|
|
224
|
+
const ch = line[m[0].length];
|
|
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;
|
|
238
|
+
hits.push({
|
|
239
|
+
line: i + 1,
|
|
240
|
+
col: raw.length - line.length + m[0].length + 1,
|
|
241
|
+
char: ch,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
return hits;
|
|
245
|
+
}
|
|
246
|
+
|
|
168
247
|
// ═══════════════════════════════════════════════════════════════════
|
|
169
248
|
// Field validators
|
|
170
249
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -488,65 +567,6 @@ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
|
|
|
488
567
|
);
|
|
489
568
|
}
|
|
490
569
|
|
|
491
|
-
/** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
|
|
492
|
-
* `requires`) so the unknown-key error can say "did you mean X?" instead of a
|
|
493
|
-
* bare rejection. */
|
|
494
|
-
function editDistance(a: string, b: string): number {
|
|
495
|
-
const m = a.length;
|
|
496
|
-
const n = b.length;
|
|
497
|
-
if (m === 0) return n;
|
|
498
|
-
if (n === 0) return m;
|
|
499
|
-
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
500
|
-
for (let i = 1; i <= m; i++) {
|
|
501
|
-
const cur = new Array<number>(n + 1);
|
|
502
|
-
cur[0] = i;
|
|
503
|
-
for (let j = 1; j <= n; j++) {
|
|
504
|
-
cur[j] = Math.min(
|
|
505
|
-
prev[j]! + 1,
|
|
506
|
-
cur[j - 1]! + 1,
|
|
507
|
-
prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
508
|
-
);
|
|
509
|
-
}
|
|
510
|
-
prev = cur;
|
|
511
|
-
}
|
|
512
|
-
return prev[n]!;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
/** Nearest known auth key within edit distance ≤ 2, or undefined. */
|
|
516
|
-
function nearestKnownKey(
|
|
517
|
-
key: string,
|
|
518
|
-
known: ReadonlySet<string>,
|
|
519
|
-
): string | undefined {
|
|
520
|
-
let best: string | undefined;
|
|
521
|
-
let bestDist = Infinity;
|
|
522
|
-
for (const k of known) {
|
|
523
|
-
const d = editDistance(key, k);
|
|
524
|
-
if (d < bestDist) {
|
|
525
|
-
bestDist = d;
|
|
526
|
-
best = k;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
return bestDist <= 2 ? best : undefined;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
/**
|
|
533
|
-
* Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
|
|
534
|
-
* X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
|
|
535
|
-
* the real secretRefs/requires shape; anything else → list the known keys.
|
|
536
|
-
*/
|
|
537
|
-
function authUnknownKeyFix(unknownKeys: string[]): string {
|
|
538
|
-
for (const key of unknownKeys) {
|
|
539
|
-
const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
|
|
540
|
-
if (known !== undefined) {
|
|
541
|
-
return `Unknown auth key "${key}" — did you mean "${known}"?`;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
|
|
545
|
-
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.`;
|
|
546
|
-
}
|
|
547
|
-
return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
|
|
548
|
-
}
|
|
549
|
-
|
|
550
570
|
function validateAuth(
|
|
551
571
|
raw: unknown,
|
|
552
572
|
file: string | undefined,
|
|
@@ -590,11 +610,11 @@ function validateAuth(
|
|
|
590
610
|
fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
|
|
591
611
|
});
|
|
592
612
|
}
|
|
593
|
-
// Strict auth schema — reject unknown keys
|
|
613
|
+
// Strict auth schema — reject unknown keys. The parser used to
|
|
594
614
|
// silently drop unknown keys (a wrong-but-plausible shape like
|
|
595
615
|
// `name`/`secret` saved a guide the executor then silently couldn't
|
|
596
|
-
// honor). Reject, don't infer:
|
|
597
|
-
//
|
|
616
|
+
// honor). Reject, don't infer: `expected` already lists the known keys
|
|
617
|
+
// and `found` names the offenders — no separate fix needed.
|
|
598
618
|
const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
|
|
599
619
|
if (unknownKeys.length > 0) {
|
|
600
620
|
const first = unknownKeys[0]!;
|
|
@@ -605,7 +625,6 @@ function validateAuth(
|
|
|
605
625
|
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
606
626
|
{
|
|
607
627
|
snippet: snippetFor(fm, "auth"),
|
|
608
|
-
fix: authUnknownKeyFix(unknownKeys),
|
|
609
628
|
},
|
|
610
629
|
);
|
|
611
630
|
}
|
|
@@ -691,10 +710,11 @@ function validateAuth(
|
|
|
691
710
|
optional = optRaw as string[];
|
|
692
711
|
}
|
|
693
712
|
|
|
694
|
-
// static-key header prefixes: header name →
|
|
695
|
-
//
|
|
696
|
-
//
|
|
697
|
-
// header
|
|
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).
|
|
698
718
|
let headerPrefixes: Record<string, string> | undefined;
|
|
699
719
|
if (a["headerPrefixes"] !== undefined) {
|
|
700
720
|
const hp = parseStringRecord(
|
|
@@ -702,9 +722,8 @@ function validateAuth(
|
|
|
702
722
|
file,
|
|
703
723
|
fm,
|
|
704
724
|
"auth.headerPrefixes",
|
|
705
|
-
"a YAML mapping of header name →
|
|
706
|
-
(v) =>
|
|
707
|
-
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),
|
|
708
727
|
);
|
|
709
728
|
if (isParseErr(hp)) return hp;
|
|
710
729
|
headerPrefixes = hp;
|
|
@@ -1285,6 +1304,29 @@ export function parseApiGuide(
|
|
|
1285
1304
|
);
|
|
1286
1305
|
}
|
|
1287
1306
|
|
|
1307
|
+
// One-pass reserved-char pre-scan: yamlParse throws on the FIRST
|
|
1308
|
+
// backtick-leading plain scalar and stops, so a multi-offender
|
|
1309
|
+
// frontmatter costs one save/validate cycle per line. Scan first and
|
|
1310
|
+
// list them all at once. Advisory only — it fires solely on the
|
|
1311
|
+
// "Plain value cannot start with reserved character" class, which
|
|
1312
|
+
// yamlParse would reject anyway — the parser stays the source of truth.
|
|
1313
|
+
const reservedHits = scanReservedPlainStarts(fm);
|
|
1314
|
+
if (reservedHits.length > 0) {
|
|
1315
|
+
const where = reservedHits
|
|
1316
|
+
.map((h) => `line ${h.line}, column ${h.col}: ${h.char}`)
|
|
1317
|
+
.join(" ; ");
|
|
1318
|
+
return fail(
|
|
1319
|
+
file,
|
|
1320
|
+
"frontmatter",
|
|
1321
|
+
"valid YAML",
|
|
1322
|
+
`plain scalar value(s) start with a reserved YAML character — ${where}`,
|
|
1323
|
+
{
|
|
1324
|
+
snippet: fm,
|
|
1325
|
+
fix: 'Quote the value (description: "`the id`") or remove the leading backtick — a plain scalar cannot start with a reserved YAML character.',
|
|
1326
|
+
},
|
|
1327
|
+
);
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1288
1330
|
let meta: unknown;
|
|
1289
1331
|
try {
|
|
1290
1332
|
meta = yamlParse(fm);
|
|
@@ -1563,12 +1605,38 @@ export function projectToGuide(guide: ApiGuide): Guide {
|
|
|
1563
1605
|
// ═══════════════════════════════════════════════════════════════════
|
|
1564
1606
|
// Directory loader — one malformed guide doesn't block the store.
|
|
1565
1607
|
//
|
|
1566
|
-
// Loads from per-
|
|
1567
|
-
//
|
|
1568
|
-
//
|
|
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.
|
|
1569
1612
|
// ═══════════════════════════════════════════════════════════════════
|
|
1570
1613
|
|
|
1571
|
-
|
|
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 {
|
|
1572
1640
|
const result: LoadedApiGuides = { guides: {}, malformed: [] };
|
|
1573
1641
|
if (!existsSync(dir)) return result;
|
|
1574
1642
|
let entries: string[];
|
|
@@ -1577,6 +1645,35 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
|
1577
1645
|
} catch {
|
|
1578
1646
|
return result;
|
|
1579
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
|
+
};
|
|
1580
1677
|
for (const entry of entries) {
|
|
1581
1678
|
const entryPath = join(dir, entry);
|
|
1582
1679
|
try {
|
|
@@ -1590,7 +1687,7 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
|
1590
1687
|
} catch {
|
|
1591
1688
|
continue;
|
|
1592
1689
|
}
|
|
1593
|
-
const name = entry; //
|
|
1690
|
+
const name = entry; // folder name = slug(shortName) in steady state
|
|
1594
1691
|
let raw: string;
|
|
1595
1692
|
try {
|
|
1596
1693
|
raw = readFileSync(guidePath, "utf-8");
|
|
@@ -1602,13 +1699,69 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
|
1602
1699
|
filename: name,
|
|
1603
1700
|
});
|
|
1604
1701
|
if (parsed.ok) {
|
|
1605
|
-
|
|
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;
|
|
1606
1763
|
} else {
|
|
1607
|
-
result.
|
|
1608
|
-
file: guidePath,
|
|
1609
|
-
filename: name,
|
|
1610
|
-
error: parsed.error,
|
|
1611
|
-
});
|
|
1764
|
+
pushMalformed(result, guidePath, name, parsed.error, warn);
|
|
1612
1765
|
}
|
|
1613
1766
|
}
|
|
1614
1767
|
return result;
|
|
@@ -1817,9 +1970,13 @@ export function formatApiGuideCatalog(
|
|
|
1817
1970
|
lines.push(
|
|
1818
1971
|
` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
|
|
1819
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}`);
|
|
1820
1977
|
}
|
|
1821
1978
|
if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
|
|
1822
|
-
lines.push(" (no guides — call api-learn({domain,
|
|
1979
|
+
lines.push(" (no guides — call api-learn({domain, dir}) to author one)");
|
|
1823
1980
|
}
|
|
1824
1981
|
lines.push("");
|
|
1825
1982
|
lines.push(
|
package/core/path-template.ts
CHANGED
|
@@ -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.
|
|
436
|
+
"pi-lean-host/0.4.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
437
437
|
}
|
|
438
438
|
|
|
439
439
|
if (!opts?.fresh && !hasAuth) {
|