pi-lean-host 0.3.1 → 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.
- package/README.md +201 -513
- package/core/api-guide-types.ts +263 -46
- package/core/api-toggle.ts +245 -40
- package/core/auth.ts +996 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +21 -6
- package/core/helpers-command.ts +6 -5
- package/core/helpers.ts +551 -148
- package/core/local-helpers.ts +17 -2
- package/core/oauth-command.ts +911 -0
- package/core/oauth-flow.ts +376 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1153 -542
- package/core/path-template.ts +147 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/status-hint.ts +61 -0
- package/core/transport.ts +321 -34
- package/core/verify-command.ts +215 -116
- package/docs/migration-v1.md +56 -0
- package/index.ts +24 -7
- package/package.json +18 -6
- package/tools/api-fetch.ts +49 -21
- package/tools/api-guide.ts +21 -12
- package/tools/api-learn.ts +515 -126
- package/tools/api-probe.ts +473 -323
- package/tools/api-scaffold.ts +413 -0
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +1 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -7
package/core/delete-command.ts
CHANGED
package/core/fs-0600.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
chmodSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readFileSync,
|
|
6
|
+
renameSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from "node:fs";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
|
|
11
|
+
/** Write a JSON file 0600 atomically: lazy mkdir of the parent + tmp file +
|
|
12
|
+
* rename (atomic on POSIX), so a crash mid-write can't shred the file's
|
|
13
|
+
* existing entries. Shared by the secrets and OAuth token stores. */
|
|
14
|
+
export function writeJson0600(p: string, data: unknown): void {
|
|
15
|
+
if (!existsSync(dirname(p))) mkdirSync(dirname(p), { recursive: true });
|
|
16
|
+
const tmp = `${p}.tmp`;
|
|
17
|
+
writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
|
18
|
+
try {
|
|
19
|
+
chmodSync(tmp, 0o600); // guard against umask overriding the mode
|
|
20
|
+
} catch {
|
|
21
|
+
// best-effort; rename still proceeds
|
|
22
|
+
}
|
|
23
|
+
renameSync(tmp, p);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Read a JSON file as a string-keyed object. Missing/corrupt/non-object
|
|
27
|
+
* (incl. array) file → {}. Read-side counterpart of writeJson0600, shared
|
|
28
|
+
* by the secrets and OAuth token stores. */
|
|
29
|
+
export function readJsonObject(p: string): Record<string, unknown> {
|
|
30
|
+
if (!existsSync(p)) return {};
|
|
31
|
+
try {
|
|
32
|
+
const parsed: unknown = JSON.parse(readFileSync(p, "utf-8"));
|
|
33
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
34
|
+
? (parsed as Record<string, unknown>)
|
|
35
|
+
: {};
|
|
36
|
+
} catch {
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Directory loader + guide catalog / disambiguation rendering — split out of
|
|
3
|
+
* parse-api-guide.ts (pure code motion). The dependency is one-directional:
|
|
4
|
+
* this module imports the parser; the parser never imports this module.
|
|
5
|
+
*
|
|
6
|
+
* `isStaleSchema` deliberately stays in parse-api-guide.ts — it is the
|
|
7
|
+
* parse-time schema gate's predicate, used inside `parseApiGuide()` itself.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { Guide } from "./guide-loader.js";
|
|
13
|
+
import { slug } from "./path-template.js";
|
|
14
|
+
import {
|
|
15
|
+
type ApiGuide,
|
|
16
|
+
type LoadedApiGuides,
|
|
17
|
+
type NotifyFn,
|
|
18
|
+
type ParseError,
|
|
19
|
+
} from "./api-guide-types.js";
|
|
20
|
+
import { parseApiGuide } from "./parse-api-guide.js";
|
|
21
|
+
|
|
22
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
23
|
+
// projectToGuide — strips recipe fields, keeps presentation + kind
|
|
24
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
25
|
+
|
|
26
|
+
export function projectToGuide(guide: ApiGuide): Guide {
|
|
27
|
+
const projection: Guide = {
|
|
28
|
+
content: guide.content,
|
|
29
|
+
updated: guide.updated,
|
|
30
|
+
category: guide.category,
|
|
31
|
+
source: guide.source,
|
|
32
|
+
icon: guide.icon,
|
|
33
|
+
shortName: guide.shortName,
|
|
34
|
+
kind: guide.kind,
|
|
35
|
+
...(guide.domains ? { domains: guide.domains } : {}),
|
|
36
|
+
};
|
|
37
|
+
return projection;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
41
|
+
// Directory loader — one malformed guide doesn't block the store.
|
|
42
|
+
//
|
|
43
|
+
// Loads from per-guide subdirectories: <dir>/<slug(shortName)>/guide.md.
|
|
44
|
+
// The folder name must equal slug(shortName) — a divergent folder routes to
|
|
45
|
+
// malformed (enforced), so the active set holds at most one guide per
|
|
46
|
+
// shortName. Flat top-level .md files are not loaded.
|
|
47
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Push a malformed guide and warn about it. One helper owns both the catalog
|
|
51
|
+
* entry and the load-time warn, so every malformed guide — parse
|
|
52
|
+
* failure, illegal shortName, divergent folder — surfaces the same signal
|
|
53
|
+
* (and its actionable `fix` when present) instead of being silently
|
|
54
|
+
* quarantined. Fires once per cached scan.
|
|
55
|
+
*/
|
|
56
|
+
function pushMalformed(
|
|
57
|
+
result: LoadedApiGuides,
|
|
58
|
+
file: string,
|
|
59
|
+
filename: string,
|
|
60
|
+
error: ParseError,
|
|
61
|
+
warn: (msg: string) => void,
|
|
62
|
+
): void {
|
|
63
|
+
result.malformed.push({ file, filename, error });
|
|
64
|
+
warn(
|
|
65
|
+
`⚠ Malformed guide '${filename}': ${error.field} — expected ${error.expected}; found ${error.found}.` +
|
|
66
|
+
(error.fix ? ` ${error.fix}` : ""),
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function loadApiGuidesFromDir(
|
|
71
|
+
dir: string,
|
|
72
|
+
notify?: NotifyFn,
|
|
73
|
+
): LoadedApiGuides {
|
|
74
|
+
const result: LoadedApiGuides = { guides: {}, malformed: [] };
|
|
75
|
+
if (!existsSync(dir)) return result;
|
|
76
|
+
let entries: string[];
|
|
77
|
+
try {
|
|
78
|
+
entries = readdirSync(dir);
|
|
79
|
+
} catch {
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
// Every load-time diagnostic routes through one channel: ctx.ui.notify
|
|
83
|
+
// when the caller has a UI context (renders via the Text component —
|
|
84
|
+
// wraps long lines, honors newlines), else console.warn. One fallback
|
|
85
|
+
// here, not one repeated per call site.
|
|
86
|
+
const warn = (msg: string) => {
|
|
87
|
+
if (notify) notify(msg, "warning");
|
|
88
|
+
else console.warn(msg);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// One-time schema-gate banner: sets the "pass these to your agent" frame before the first
|
|
92
|
+
// stale-schema malformed warning. Fired only when the parse failure is a
|
|
93
|
+
// schemaVersion gate refusal, so ordinary malformed guides don't drag it
|
|
94
|
+
// in. The per-guide failure already names the file + migration doc in its
|
|
95
|
+
// fix; the banner only sets the frame once per scan.
|
|
96
|
+
let schemaBannerEmitted = false;
|
|
97
|
+
const emitSchemaGateBanner = () => {
|
|
98
|
+
if (schemaBannerEmitted) return;
|
|
99
|
+
schemaBannerEmitted = true;
|
|
100
|
+
warn(
|
|
101
|
+
`\n⚠ One or more guides were authored against an older guide schema and failed to load. ` +
|
|
102
|
+
`Pass the warnings below to the agent to fix them ` +
|
|
103
|
+
`(re-stamp schemaVersion + apply the breaking changes in the migration doc), then /reload.\n`,
|
|
104
|
+
);
|
|
105
|
+
};
|
|
106
|
+
for (const entry of entries) {
|
|
107
|
+
const entryPath = join(dir, entry);
|
|
108
|
+
try {
|
|
109
|
+
if (!statSync(entryPath).isDirectory()) continue;
|
|
110
|
+
} catch {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const guidePath = join(entryPath, "guide.md");
|
|
114
|
+
try {
|
|
115
|
+
if (!statSync(guidePath).isFile()) continue;
|
|
116
|
+
} catch {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const name = entry; // folder name = slug(shortName) in steady state
|
|
120
|
+
let raw: string;
|
|
121
|
+
try {
|
|
122
|
+
raw = readFileSync(guidePath, "utf-8");
|
|
123
|
+
} catch {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const parsed = parseApiGuide(raw, {
|
|
127
|
+
file: guidePath,
|
|
128
|
+
filename: name,
|
|
129
|
+
});
|
|
130
|
+
if (parsed.ok) {
|
|
131
|
+
const guide = parsed.guide;
|
|
132
|
+
// Illegal-shortName + divergence checks (permanent). One try/catch
|
|
133
|
+
// owns the slug() call: a throw (empty or all-symbol shortName) is
|
|
134
|
+
// routed to malformed, never escaped.
|
|
135
|
+
let slugged: string;
|
|
136
|
+
try {
|
|
137
|
+
slugged = slug(guide.shortName);
|
|
138
|
+
} catch {
|
|
139
|
+
pushMalformed(
|
|
140
|
+
result,
|
|
141
|
+
guidePath,
|
|
142
|
+
name,
|
|
143
|
+
{
|
|
144
|
+
field: "shortName",
|
|
145
|
+
expected: "a shortName that slugs to a non-empty safe directory name",
|
|
146
|
+
found: `"${guide.shortName}"`,
|
|
147
|
+
fix: "Set a valid shortName (lowercase letters, digits, and '-') in the guide's frontmatter.",
|
|
148
|
+
},
|
|
149
|
+
warn,
|
|
150
|
+
);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
// Divergence check (permanent) — ENFORCED, not advisory: the folder
|
|
154
|
+
// name must equal slug(shortName); the coupling IS the identity. A
|
|
155
|
+
// divergent guide routes to malformed (never loads), so the active
|
|
156
|
+
// set structurally holds at most one guide per shortName.
|
|
157
|
+
if (entry !== slugged) {
|
|
158
|
+
pushMalformed(
|
|
159
|
+
result,
|
|
160
|
+
guidePath,
|
|
161
|
+
name,
|
|
162
|
+
{
|
|
163
|
+
field: "shortName",
|
|
164
|
+
expected: `a folder named slug(shortName) ('${slugged}')`,
|
|
165
|
+
found: `folder '${entry}'`,
|
|
166
|
+
fix: `Rename the folder to '${slugged}': mv ${entryPath} ${join(dir, slugged)}`,
|
|
167
|
+
},
|
|
168
|
+
warn,
|
|
169
|
+
);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
result.guides[entry] = guide;
|
|
173
|
+
} else {
|
|
174
|
+
if (parsed.error.field === "schemaVersion") emitSchemaGateBanner();
|
|
175
|
+
pushMalformed(result, guidePath, name, parsed.error, warn);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ════════════════════════════════════════════════════════════════════
|
|
182
|
+
// Disambiguation helpers — shared by the api-guide menu and the
|
|
183
|
+
// api-fetch ambiguous-operation error. One rendering of the per-guide
|
|
184
|
+
// listing so the two surfaces stay visually consistent.
|
|
185
|
+
// ════════════════════════════════════════════════════════════════════
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Truncated op-name summary for disambiguation surfaces:
|
|
189
|
+
* "N ops: a, b, c, d, e, +K more" (first 5 names, then the remaining count).
|
|
190
|
+
* A 50-op guide must not dump 50 names into context — the menu exists to
|
|
191
|
+
* help pick a guide cheaply; the full op list is one api-guide call away.
|
|
192
|
+
*/
|
|
193
|
+
function formatOpSummary(ops: { name: string }[]): string {
|
|
194
|
+
const names = ops.map((o) => o.name);
|
|
195
|
+
const count = names.length;
|
|
196
|
+
const head = names.slice(0, 5);
|
|
197
|
+
const remaining = count - head.length;
|
|
198
|
+
const tail = remaining > 0 ? `, +${remaining} more` : "";
|
|
199
|
+
return `${count} ops: ${head.join(", ")}${tail}`;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Per-guide listing lines for a disambiguation surface (the api-guide
|
|
204
|
+
* multi-guide menu and the api-fetch ambiguous-op error). Each entry:
|
|
205
|
+
* `icon shortName` [+ ` — description` when present] then the truncated
|
|
206
|
+
* op-name list. When `description:` is absent the line falls back to
|
|
207
|
+
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
208
|
+
* guides render consistently with those that have a one-line summary.
|
|
209
|
+
*/
|
|
210
|
+
export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
211
|
+
const lines: string[] = [];
|
|
212
|
+
for (const { guide } of entries) {
|
|
213
|
+
lines.push(
|
|
214
|
+
` ${guide.icon} ${guide.shortName}` +
|
|
215
|
+
(guide.description ? ` — ${guide.description}` : ""),
|
|
216
|
+
);
|
|
217
|
+
lines.push(` ${formatOpSummary(guide.operations)}`);
|
|
218
|
+
}
|
|
219
|
+
return lines.join("\n");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Resolve a guide by shortName across a domain's matches (exact,
|
|
224
|
+
* case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
|
|
225
|
+
* /api verify — three call sites, one resolution rule (a drifted copy would
|
|
226
|
+
* ship a known second bug). Returns a structured outcome; each caller renders
|
|
227
|
+
* its own message (tool result vs command notify).
|
|
228
|
+
*/
|
|
229
|
+
export function selectGuideByShortName(
|
|
230
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
231
|
+
selector: string,
|
|
232
|
+
):
|
|
233
|
+
| { ok: true; guide: ApiGuide; dirName: string }
|
|
234
|
+
| { ok: false; reason: "no_match"; valid: string[] }
|
|
235
|
+
| { ok: false; reason: "ambiguous"; directories: string[] } {
|
|
236
|
+
const lc = selector.toLowerCase();
|
|
237
|
+
const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
|
|
238
|
+
if (sel.length === 0) {
|
|
239
|
+
return {
|
|
240
|
+
ok: false,
|
|
241
|
+
reason: "no_match",
|
|
242
|
+
valid: matches.map((m) => m.guide.shortName),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
if (sel.length > 1) {
|
|
246
|
+
return {
|
|
247
|
+
ok: false,
|
|
248
|
+
reason: "ambiguous",
|
|
249
|
+
directories: sel.map((s) => s.dirName),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Render the no-match / ambiguous error text for a failed
|
|
257
|
+
* `selectGuideByShortName` result. `callToAction` is the trailing
|
|
258
|
+
* "how to see the menu" sentence — it differs per surface (tool vs
|
|
259
|
+
* command), so callers pass their own.
|
|
260
|
+
*/
|
|
261
|
+
export function shortNameErrorText(
|
|
262
|
+
sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
|
|
263
|
+
domain: string,
|
|
264
|
+
selector: string,
|
|
265
|
+
callToAction: string,
|
|
266
|
+
): string {
|
|
267
|
+
if (sel.reason === "no_match") {
|
|
268
|
+
return (
|
|
269
|
+
`No guide named '${selector}' for '${domain}'. ` +
|
|
270
|
+
`Available guides: ${sel.valid.join(", ")}. ` +
|
|
271
|
+
callToAction
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
return (
|
|
275
|
+
`Ambiguous guide '${selector}' for '${domain}' — ` +
|
|
276
|
+
`${sel.directories.length} guides share shortName '${selector}' ` +
|
|
277
|
+
`(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
|
|
278
|
+
`disambiguate. ` +
|
|
279
|
+
callToAction
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ════════════════════════════════════════════════════════════════════
|
|
284
|
+
// Catalog rendering — healthy + ⚠ malformed together
|
|
285
|
+
//
|
|
286
|
+
// Base catalog is collapsed by `organization:`: one line per org with its
|
|
287
|
+
// guide count and domain set. Guides without `organization:` fall back to
|
|
288
|
+
// the per-guide line, so the un-backfilled corpus renders unchanged (no
|
|
289
|
+
// forced migration). Op counts live on the per-domain disambiguation menu
|
|
290
|
+
// (api-guide {domain}), where they're useful for picking a guide — not
|
|
291
|
+
// here, where they'd bloat context for orgs with many guides.
|
|
292
|
+
// ════════════════════════════════════════════════════════════════════
|
|
293
|
+
|
|
294
|
+
export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
295
|
+
const lines: string[] = ["API guides:"];
|
|
296
|
+
|
|
297
|
+
// Org-grouped rows preserve first-appearance order; guides without
|
|
298
|
+
// organization fall back to the per-guide line (no forced migration).
|
|
299
|
+
const orgRows: { org: string; guides: ApiGuide[] }[] = [];
|
|
300
|
+
const orgIndex = new Map<string, number>();
|
|
301
|
+
const orgless: { name: string; guide: ApiGuide }[] = [];
|
|
302
|
+
for (const [name, guide] of Object.entries(loaded.guides)) {
|
|
303
|
+
if (guide.organization) {
|
|
304
|
+
const idx = orgIndex.get(guide.organization);
|
|
305
|
+
if (idx === undefined) {
|
|
306
|
+
orgIndex.set(guide.organization, orgRows.length);
|
|
307
|
+
orgRows.push({ org: guide.organization, guides: [guide] });
|
|
308
|
+
} else {
|
|
309
|
+
orgRows[idx]!.guides.push(guide);
|
|
310
|
+
}
|
|
311
|
+
} else {
|
|
312
|
+
orgless.push({ name, guide });
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
for (const row of orgRows) {
|
|
317
|
+
const domains = new Set<string>();
|
|
318
|
+
for (const g of row.guides) {
|
|
319
|
+
for (const d of g.domains ?? []) domains.add(d);
|
|
320
|
+
}
|
|
321
|
+
const domList = domains.size > 0 ? [...domains].join(", ") : "—";
|
|
322
|
+
const n = row.guides.length;
|
|
323
|
+
lines.push(` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})`);
|
|
324
|
+
}
|
|
325
|
+
for (const { name, guide } of orgless) {
|
|
326
|
+
const domains =
|
|
327
|
+
guide.domains && guide.domains.length > 0 ? guide.domains.join(", ") : name;
|
|
328
|
+
lines.push(
|
|
329
|
+
` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
for (const mal of loaded.malformed) {
|
|
333
|
+
lines.push(
|
|
334
|
+
` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
|
|
335
|
+
);
|
|
336
|
+
// Actionable advice on its own line, matching api-fetch/api-learn's
|
|
337
|
+
// `Fix:` convention — multi-line fixes (e.g. the frontmatter template)
|
|
338
|
+
// render naturally instead of being inlined into the summary line.
|
|
339
|
+
if (mal.error.fix) lines.push(` fix: ${mal.error.fix}`);
|
|
340
|
+
}
|
|
341
|
+
if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
|
|
342
|
+
lines.push(" (no guides — call api-learn({domain, dir}) to author one)");
|
|
343
|
+
}
|
|
344
|
+
lines.push("");
|
|
345
|
+
lines.push(
|
|
346
|
+
'Call api-guide({domain: "<name>"}) for detail. Multiple guides for a domain show a disambiguation menu.',
|
|
347
|
+
);
|
|
348
|
+
return lines.join("\n");
|
|
349
|
+
}
|
package/core/guide-picker.ts
CHANGED
|
@@ -1,38 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Interactive guide picker for the /api verify and /api
|
|
2
|
+
* Interactive guide picker for the /api verify, /api delete, and /api oauth
|
|
3
|
+
* commands.
|
|
3
4
|
*
|
|
4
5
|
* When a domain claims N guides and no `guide` selector is supplied, the
|
|
5
|
-
* commands show a
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* commands show a two-column picker (shared `pickWithDescription` helper) —
|
|
7
|
+
* shortName in the primary column, guide description in the second. The user
|
|
8
|
+
* picks with ↑↓/enter instead of retyping the command with a shortName.
|
|
9
|
+
* `value` is the dirName (unique, unlike shortName, which can be ambiguous
|
|
10
|
+
* across sibling guides).
|
|
10
11
|
*
|
|
11
12
|
* Terminal-only: `ctx.mode === "tui"` (custom components don't exist in
|
|
12
13
|
* RPC/print). In headless/RPC/print `pickGuide` returns undefined and the
|
|
13
|
-
* caller keeps today's text menu + retype fallback.
|
|
14
|
-
* (`schemaVersion < current`) gets a `⚠` on its label so stale-guide
|
|
15
|
-
* detection survives the interactive path.
|
|
14
|
+
* caller keeps today's text menu + retype fallback.
|
|
16
15
|
*/
|
|
17
16
|
|
|
18
17
|
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { SelectItem } from "@earendil-works/pi-tui";
|
|
19
|
+
import type { ApiGuide } from "./api-guide-types.js";
|
|
19
20
|
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
} from "
|
|
25
|
-
import { GUIDE_SCHEMA_VERSION, type ApiGuide } from "./api-guide-types.js";
|
|
26
|
-
import { isStaleSchema } from "./parse-api-guide.js";
|
|
21
|
+
formatGuideListings,
|
|
22
|
+
selectGuideByShortName,
|
|
23
|
+
shortNameErrorText,
|
|
24
|
+
} from "./guide-catalog.js";
|
|
25
|
+
import { pickWithDescription } from "./select-picker.js";
|
|
27
26
|
|
|
28
27
|
/**
|
|
29
|
-
* Build the picker rows: `value` = dirName (unique), `label` = shortName
|
|
30
|
-
*
|
|
31
|
-
*
|
|
28
|
+
* Build the picker rows: `value` = dirName (unique), `label` = shortName,
|
|
29
|
+
* `description` = the guide description, falling back to an op-count summary
|
|
30
|
+
* when absent. Pure — tests exercise it without a TUI.
|
|
32
31
|
*/
|
|
33
32
|
export function buildGuidePickerItems(
|
|
34
33
|
matches: { guide: ApiGuide; dirName: string }[],
|
|
35
|
-
current: number = GUIDE_SCHEMA_VERSION,
|
|
36
34
|
): SelectItem[] {
|
|
37
35
|
return matches.map(({ guide, dirName }) => {
|
|
38
36
|
const desc =
|
|
@@ -42,9 +40,7 @@ export function buildGuidePickerItems(
|
|
|
42
40
|
: undefined);
|
|
43
41
|
const item: SelectItem = {
|
|
44
42
|
value: dirName,
|
|
45
|
-
label:
|
|
46
|
-
guide.shortName +
|
|
47
|
-
(isStaleSchema(guide.schemaVersion ?? 0, current) ? " ⚠" : ""),
|
|
43
|
+
label: guide.shortName,
|
|
48
44
|
};
|
|
49
45
|
if (desc !== undefined) item.description = desc;
|
|
50
46
|
return item;
|
|
@@ -52,10 +48,10 @@ export function buildGuidePickerItems(
|
|
|
52
48
|
}
|
|
53
49
|
|
|
54
50
|
/**
|
|
55
|
-
* Let the user pick one of a domain's guides interactively (TUI
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
51
|
+
* Let the user pick one of a domain's guides interactively (TUI gets the
|
|
52
|
+
* two-column SelectList; other modes return undefined so the caller renders
|
|
53
|
+
* its own text menu fallback). Returns the selected `{ guide, dirName }`, or
|
|
54
|
+
* undefined when the picker is unavailable or the user cancelled.
|
|
59
55
|
*/
|
|
60
56
|
export async function pickGuide(
|
|
61
57
|
ctx: ExtensionCommandContext,
|
|
@@ -63,42 +59,61 @@ export async function pickGuide(
|
|
|
63
59
|
): Promise<{ guide: ApiGuide; dirName: string } | undefined> {
|
|
64
60
|
if (ctx.mode !== "tui") return undefined;
|
|
65
61
|
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
(
|
|
70
|
-
const container = new Container();
|
|
71
|
-
container.addChild(
|
|
72
|
-
new Text(theme.fg("accent", theme.bold("Select API guide"))),
|
|
73
|
-
);
|
|
74
|
-
const list = new SelectList(items, Math.min(items.length, 10), {
|
|
75
|
-
selectedPrefix: (text) => theme.fg("accent", text),
|
|
76
|
-
selectedText: (text) => theme.fg("accent", text),
|
|
77
|
-
description: (text) => theme.fg("muted", text),
|
|
78
|
-
scrollInfo: (text) => theme.fg("dim", text),
|
|
79
|
-
noMatch: (text) => theme.fg("warning", text),
|
|
80
|
-
});
|
|
81
|
-
list.onSelect = (item) => done(item.value);
|
|
82
|
-
list.onCancel = () => done(undefined);
|
|
83
|
-
container.addChild(list);
|
|
84
|
-
container.addChild(
|
|
85
|
-
new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel")),
|
|
86
|
-
);
|
|
87
|
-
return {
|
|
88
|
-
render(width: number) {
|
|
89
|
-
return container.render(width);
|
|
90
|
-
},
|
|
91
|
-
invalidate() {
|
|
92
|
-
container.invalidate();
|
|
93
|
-
},
|
|
94
|
-
handleInput(data: string) {
|
|
95
|
-
list.handleInput(data);
|
|
96
|
-
tui.requestRender();
|
|
97
|
-
},
|
|
98
|
-
};
|
|
99
|
-
},
|
|
62
|
+
const picked = await pickWithDescription(
|
|
63
|
+
ctx,
|
|
64
|
+
"Select API guide",
|
|
65
|
+
buildGuidePickerItems(matches),
|
|
100
66
|
);
|
|
101
67
|
|
|
102
68
|
if (picked === undefined) return undefined;
|
|
103
69
|
return matches.find((m) => m.dirName === picked);
|
|
104
70
|
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Shared notify-based guide selection for commands: 1 match → it wins; a
|
|
74
|
+
* selector → resolve by shortName (error + stop on no match); otherwise the
|
|
75
|
+
* interactive picker with the text-menu fallback. Returns undefined when the
|
|
76
|
+
* caller should stop (fallback menu shown or selection error notified).
|
|
77
|
+
* Callers keep their own 0-match branch — those messages genuinely differ.
|
|
78
|
+
* `ctx.ui.notify`-based only (the tool-channel sites — api-guide, api-learn,
|
|
79
|
+
* api-scaffold — keep their own skeletons).
|
|
80
|
+
*/
|
|
81
|
+
export async function pickGuideForCommand(
|
|
82
|
+
ctx: ExtensionCommandContext,
|
|
83
|
+
domain: string,
|
|
84
|
+
selector: string | undefined,
|
|
85
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
86
|
+
command: string,
|
|
87
|
+
label = "API guides",
|
|
88
|
+
): Promise<{ guide: ApiGuide; dirName: string } | undefined> {
|
|
89
|
+
if (matches.length === 1) return matches[0];
|
|
90
|
+
if (selector) {
|
|
91
|
+
const sel = selectGuideByShortName(matches, selector);
|
|
92
|
+
if (!sel.ok) {
|
|
93
|
+
ctx.ui.notify(
|
|
94
|
+
shortNameErrorText(
|
|
95
|
+
sel,
|
|
96
|
+
domain,
|
|
97
|
+
selector,
|
|
98
|
+
`Call ${command} ${domain} to see the menu.`,
|
|
99
|
+
),
|
|
100
|
+
"warning",
|
|
101
|
+
);
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
return sel;
|
|
105
|
+
}
|
|
106
|
+
// N guides, no selector → interactive pick (TUI) or the menu fallback
|
|
107
|
+
// (headless/RPC/print or cancelled), nothing run yet.
|
|
108
|
+
const picked = await pickGuide(ctx, matches);
|
|
109
|
+
if (picked) return picked;
|
|
110
|
+
ctx.ui.notify(
|
|
111
|
+
[
|
|
112
|
+
`${matches.length} ${label} for '${domain}':`,
|
|
113
|
+
formatGuideListings(matches),
|
|
114
|
+
`Call ${command} ${domain} <shortName> to pick one.`,
|
|
115
|
+
].join("\n"),
|
|
116
|
+
"info",
|
|
117
|
+
);
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
package/core/guide-store.ts
CHANGED
|
@@ -11,9 +11,9 @@ import { homedir } from "node:os";
|
|
|
11
11
|
import {
|
|
12
12
|
loadApiGuidesFromDir,
|
|
13
13
|
formatApiGuideCatalog,
|
|
14
|
-
} from "./
|
|
14
|
+
} from "./guide-catalog.js";
|
|
15
15
|
import { buildDomainMap } from "./guide-loader.js";
|
|
16
|
-
import type { ApiGuide, LoadedApiGuides } from "./api-guide-types.js";
|
|
16
|
+
import type { ApiGuide, LoadedApiGuides, NotifyFn } from "./api-guide-types.js";
|
|
17
17
|
|
|
18
18
|
// ═══════════════════════════════════════════════════════════════════
|
|
19
19
|
// Directory resolution
|
|
@@ -33,6 +33,14 @@ let _cache: {
|
|
|
33
33
|
domainMap: Record<string, string[]>;
|
|
34
34
|
} | null = null;
|
|
35
35
|
|
|
36
|
+
// Load-time diagnostics (per-guide malformed warnings) are
|
|
37
|
+
// a startup concern: emit them once per pi process on the first cold scan,
|
|
38
|
+
// then suppress for the rest of the session so navigating chats or running
|
|
39
|
+
// commands doesn't re-warn. A no-op notify (not `undefined`) is what
|
|
40
|
+
// suppresses — `undefined` falls back to console.warn inside the loader.
|
|
41
|
+
let loadWarningsEmitted = false;
|
|
42
|
+
const suppressWarnings: NotifyFn = () => {};
|
|
43
|
+
|
|
36
44
|
// ═══════════════════════════════════════════════════════════════════
|
|
37
45
|
// Public API — override hooks for testing
|
|
38
46
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -50,17 +58,24 @@ export function invalidateCache(): void {
|
|
|
50
58
|
_cache = null;
|
|
51
59
|
}
|
|
52
60
|
|
|
61
|
+
/** @internal Reset once-per-process warning suppression (test helper). */
|
|
62
|
+
export function _resetLoadWarningsForTest(): void {
|
|
63
|
+
loadWarningsEmitted = false;
|
|
64
|
+
}
|
|
65
|
+
|
|
53
66
|
// ═══════════════════════════════════════════════════════════════════
|
|
54
67
|
// Internal load
|
|
55
68
|
// ═══════════════════════════════════════════════════════════════════
|
|
56
69
|
|
|
57
|
-
function load(): {
|
|
70
|
+
function load(notify?: NotifyFn): {
|
|
58
71
|
loaded: LoadedApiGuides;
|
|
59
72
|
domainMap: Record<string, string[]>;
|
|
60
73
|
} {
|
|
61
74
|
if (_cache) return _cache;
|
|
62
75
|
|
|
63
|
-
const
|
|
76
|
+
const warnNotify = loadWarningsEmitted ? suppressWarnings : notify;
|
|
77
|
+
loadWarningsEmitted = true;
|
|
78
|
+
const user = loadApiGuidesFromDir(_userGuidesDir, warnNotify);
|
|
64
79
|
|
|
65
80
|
const loaded: LoadedApiGuides = {
|
|
66
81
|
guides: user.guides,
|
|
@@ -76,8 +91,8 @@ function load(): {
|
|
|
76
91
|
// Public lookup API
|
|
77
92
|
// ═══════════════════════════════════════════════════════════════════
|
|
78
93
|
|
|
79
|
-
export function loadAllGuides(): LoadedApiGuides {
|
|
80
|
-
return load().loaded;
|
|
94
|
+
export function loadAllGuides(notify?: NotifyFn): LoadedApiGuides {
|
|
95
|
+
return load(notify).loaded;
|
|
81
96
|
}
|
|
82
97
|
|
|
83
98
|
export function findGuidesByDomain(
|
package/core/helpers-command.ts
CHANGED
|
@@ -35,8 +35,9 @@ export async function handleHelpersSubcommand(
|
|
|
35
35
|
if (all.length === 0) {
|
|
36
36
|
ctx.ui.notify(
|
|
37
37
|
"No local helpers found. Helpers live alongside their guide: " +
|
|
38
|
-
`api-guides/<
|
|
39
|
-
"
|
|
38
|
+
`api-guides/<dirName>/helper.ts.\n\n` +
|
|
39
|
+
"Scaffold a starter helper via api-scaffold({domain, helper: true}) (writes to the staged /tmp dir), " +
|
|
40
|
+
"uncomment the export you need, and save via api-learn({domain, dir}).",
|
|
40
41
|
"info",
|
|
41
42
|
);
|
|
42
43
|
return;
|
|
@@ -55,7 +56,7 @@ export async function handleHelpersSubcommand(
|
|
|
55
56
|
lines.push(
|
|
56
57
|
"",
|
|
57
58
|
"Call /api helpers <domain> to view a helper's source.",
|
|
58
|
-
"Call api-learn({domain,
|
|
59
|
+
"Call api-learn({domain, dir}) to author or update a guide (and its helper).",
|
|
59
60
|
);
|
|
60
61
|
|
|
61
62
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
@@ -81,8 +82,8 @@ export async function handleHelpersSubcommand(
|
|
|
81
82
|
all.length > 0 ? ` Known helpers: ${all.join(", ")}.` : " No helpers found.";
|
|
82
83
|
ctx.ui.notify(
|
|
83
84
|
`No helper for '${domain}'.${known}\n\n` +
|
|
84
|
-
`Helpers live alongside guides at api-guides
|
|
85
|
-
"
|
|
85
|
+
`Helpers live alongside guides at api-guides/<dirName>/helper.ts.\n` +
|
|
86
|
+
"Scaffold one via api-scaffold({domain, helper: true}), then save via api-learn({domain, dir}).",
|
|
86
87
|
"warning",
|
|
87
88
|
);
|
|
88
89
|
return;
|