pi-lean-host 0.2.0 → 0.3.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.
@@ -0,0 +1,399 @@
1
+ /**
2
+ * `/api verify <domain> [guide] [--force]` — verify every runnable operation
3
+ * of a guide against its live API, stamping `verified: today` only when all
4
+ * runnable ops pass.
5
+ *
6
+ * - `verify <domain>` — fetch every op; stamp on all-runnable-pass.
7
+ * - `verify <domain> <guide>` — pick a guide by shortName (N-guide domains).
8
+ * - `verify <domain> --force` — stamp today WITHOUT running any ops
9
+ * (human-typed "human-attested good" escape valve).
10
+ * - `verify --help` — usage + cost note.
11
+ *
12
+ * Strict threshold: any runnable-op failure (partial or all-fail) → no stamp.
13
+ * Skipped ops are NOT failures and don't block the stamp, but are named in
14
+ * the report. Two skip categories: unsatisfiable params (a path `{token}` or
15
+ * required query param with no default, and no verify.json value) and a
16
+ * session-disabled local helper. A post-response transform failure is
17
+ * non-blocking (the HTTP op succeeded — the executor carries it as a
18
+ * `transformWarning`).
19
+ *
20
+ * Opt-in params sidecar: a co-located
21
+ * `~/.pi/agent/pi-lean-host/api-guides/<dirName>/verify.json`,
22
+ * shape `{ "<opName>": { "<param>": "<value>" } }`, supplies the params map
23
+ * verbatim to the executor (pre-helper inputs for `helper: true` ops). It is
24
+ * the only way an op with unsatisfiable params can run.
25
+ *
26
+ * Always-available (runs in **on** mode, not just learn) and not refused by
27
+ * the focus-mode guard — it writes no toolset state (peer of `secrets`).
28
+ * Runs the executor/auth/transport directly, so it works even when the
29
+ * api-fetch / api-guide tools are masked off.
30
+ *
31
+ * Not free: N live HTTP requests against the target API (GET only — no
32
+ * mutation side-effects, but real quota/rate-limit cost). Reuses the
33
+ * transport's existing 429 retry at the default maxRetries.
34
+ */
35
+
36
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
37
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
38
+ import { join } from "node:path";
39
+ import {
40
+ findGuidesByDomain,
41
+ invalidateCache,
42
+ getUserGuidesDir,
43
+ } from "./guide-store.js";
44
+ import {
45
+ formatGuideListings,
46
+ selectGuideByShortName,
47
+ shortNameErrorText,
48
+ stampFrontmatterField,
49
+ TODAY,
50
+ } from "./parse-api-guide.js";
51
+ import { pickGuide } from "./guide-picker.js";
52
+ import {
53
+ resolveSecretHeaders,
54
+ resolveSecretQueryParams,
55
+ canonicalStoreDomain,
56
+ } from "./auth.js";
57
+ import { resolveOpForExecution, type ResolveOpResult } from "./resolve-op.js";
58
+ import {
59
+ HelperError,
60
+ type RestGetResult,
61
+ type PaginateResult,
62
+ } from "./helpers.js";
63
+ import type { ApiGuide, Operation } from "./api-guide-types.js";
64
+
65
+ /** Usage + cost note, surfaced by `--help`. */
66
+ function helpText(): string {
67
+ return [
68
+ "Usage: /api verify <domain> [guide] [--force]",
69
+ " /api verify <domain> fetch every runnable op; stamp verified: today on all-pass",
70
+ " /api verify <domain> <guide> pick a guide by shortName when a domain claims several",
71
+ " /api verify <domain> --force stamp verified: today WITHOUT running any ops (human-attested)",
72
+ " /api verify --help this help",
73
+ "",
74
+ " Ops with unsatisfiable params (a path {token} or required query param with no default)",
75
+ " are skipped, not failed. Supply them via a co-located verify.json:",
76
+ ` ~/.pi/agent/pi-lean-host/api-guides/<domain>/verify.json`,
77
+ ` { "<opName>": { "<param>": "<value>" } }`,
78
+ "",
79
+ " Not free: N live HTTP requests against the target API (GET only — no mutation).",
80
+ " Reuses the transport's 429 retry at the default maxRetries.",
81
+ ].join("\n");
82
+ }
83
+
84
+ /**
85
+ * Handle the `verify` subcommand of `/api`.
86
+ *
87
+ * @param args The text after "verify" ("" / "<domain>" / "<domain> <guide>").
88
+ * @param ctx The extension command context
89
+ */
90
+ export async function handleVerifySubcommand(
91
+ args: string,
92
+ ctx: ExtensionCommandContext,
93
+ ): Promise<void> {
94
+ const parts = args.trim().split(/\s+/).filter(Boolean);
95
+
96
+ if (parts.includes("--help") || parts.includes("help")) {
97
+ ctx.ui.notify(helpText(), "info");
98
+ return;
99
+ }
100
+
101
+ const force = parts.includes("--force");
102
+ const tokens = parts.filter((p) => p !== "--force");
103
+ const domain = tokens[0];
104
+ const guideSelector = tokens[1];
105
+
106
+ if (!domain) {
107
+ ctx.ui.notify(
108
+ "Usage: /api verify <domain> [guide] [--force] — see /api verify --help.",
109
+ "warning",
110
+ );
111
+ return;
112
+ }
113
+
114
+ // Resolve the guide by domain (disambiguation for N-guide domains).
115
+ const matches = findGuidesByDomain(domain);
116
+ if (matches.length === 0) {
117
+ ctx.ui.notify(
118
+ `No API guide for '${domain}'. ` +
119
+ `Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author one.`,
120
+ "warning",
121
+ );
122
+ return;
123
+ }
124
+
125
+ let selected: { guide: ApiGuide; dirName: string };
126
+ if (matches.length === 1) {
127
+ selected = matches[0]!;
128
+ } else if (guideSelector) {
129
+ const sel = selectGuideByShortName(matches, guideSelector);
130
+ if (!sel.ok) {
131
+ ctx.ui.notify(
132
+ shortNameErrorText(
133
+ sel,
134
+ domain,
135
+ guideSelector,
136
+ `Call /api verify ${domain} to see the menu.`,
137
+ ),
138
+ "warning",
139
+ );
140
+ return;
141
+ }
142
+ selected = sel;
143
+ } else {
144
+ // N guides, no selector → interactive pick (TUI) or the menu
145
+ // fallback (headless/RPC/print or cancelled), nothing run yet.
146
+ const picked = await pickGuide(ctx, matches);
147
+ if (!picked) {
148
+ ctx.ui.notify(
149
+ [
150
+ `${matches.length} API guides for '${domain}':`,
151
+ formatGuideListings(matches),
152
+ `Call /api verify ${domain} <shortName> to pick one.`,
153
+ ].join("\n"),
154
+ "info",
155
+ );
156
+ return;
157
+ }
158
+ selected = picked;
159
+ }
160
+
161
+ const { guide, dirName } = selected;
162
+ const storeDomain = canonicalStoreDomain(guide);
163
+
164
+ // --force: human-attested stamp, no HTTP at all.
165
+ if (force) {
166
+ stampVerified(dirName);
167
+ ctx.ui.notify(
168
+ `📡 Verify --force: ${guide.shortName} (${dirName})\n` +
169
+ ` Stamped verified: ${TODAY()} without running any ops — human-attested good.\n` +
170
+ ` Note: this reflects attestation, not a run confirmation.`,
171
+ "info",
172
+ );
173
+ return;
174
+ }
175
+
176
+ // Auth precheck (fail-fast): resolve the same secrets api-fetch does. If
177
+ // any `requires` secret is unprovisioned, short-circuit with ONE message —
178
+ // do not run N ops that all fail identically.
179
+ if (guide.auth.kind === "static-key") {
180
+ const headerRes = resolveSecretHeaders(guide.auth, storeDomain);
181
+ const queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
182
+ const missingRequired = [
183
+ ...headerRes.absentRequired,
184
+ ...queryRes.absentRequired,
185
+ ];
186
+ if (missingRequired.length > 0) {
187
+ ctx.ui.notify(
188
+ `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
189
+ `${missingRequired.join(", ")}.\n` +
190
+ `Run /api secrets ${storeDomain} to provision it, then re-run /api verify.`,
191
+ "warning",
192
+ );
193
+ return;
194
+ }
195
+ }
196
+
197
+ // Best-effort verify.json sidecar: file-miss → no sidecar (today's skip
198
+ // behavior); malformed → parse error caught at load, not a runtime crash.
199
+ const sidecar = loadVerifyJson(dirName);
200
+ if (sidecar && "error" in sidecar) {
201
+ ctx.ui.notify(
202
+ `⚠ verify.json for '${dirName}' is malformed — ignoring it (${sidecar.error}).`,
203
+ "warning",
204
+ );
205
+ }
206
+ const verifyJson = sidecar && "data" in sidecar ? sidecar.data : {};
207
+
208
+ // ── Fetch loop ──────────────────────────────────────────────
209
+ const ops = guide.operations;
210
+ const report: string[] = [];
211
+ let ran = 0;
212
+ let failed = 0;
213
+ let skipped = 0;
214
+
215
+ for (const op of ops) {
216
+ const supplied = verifyJson[op.name] ?? {};
217
+ const missing = unsatisfiableParams(op, supplied);
218
+ if (missing.length > 0) {
219
+ skipped++;
220
+ report.push(
221
+ ` ⏭ ${op.name} — skipped: requires agent-supplied params (${missing.join(", ")}) — verify manually via api-fetch`,
222
+ );
223
+ continue;
224
+ }
225
+
226
+ let outcome: ResolveOpResult;
227
+ try {
228
+ outcome = await resolveOpForExecution(guide, op, dirName, {
229
+ userParams: supplied,
230
+ });
231
+ } catch (err) {
232
+ failed++;
233
+ const msg =
234
+ err instanceof HelperError
235
+ ? err.message
236
+ : err instanceof Error
237
+ ? err.message
238
+ : String(err);
239
+ report.push(` ✗ ${op.name} — ${msg}`);
240
+ continue;
241
+ }
242
+
243
+ if (!outcome.ok) {
244
+ if (outcome.reason === "helper_disabled") {
245
+ // Session-persistent condition — unverifiable this session, not broken.
246
+ skipped++;
247
+ report.push(
248
+ ` ⏭ ${op.name} — skipped: local helper disabled this session (${outcome.message})`,
249
+ );
250
+ continue;
251
+ }
252
+ // auth_required_not_provisioned — unreachable after the precheck
253
+ // (auth is per-guide constant); defensive.
254
+ failed++;
255
+ report.push(
256
+ ` ✗ ${op.name} — requires secret not provisioned: ${outcome.missing.join(", ")}`,
257
+ );
258
+ continue;
259
+ }
260
+
261
+ ran++;
262
+ report.push(opLine(outcome, op));
263
+ }
264
+
265
+ const header = `📡 Verify: ${guide.shortName} (${dirName})`;
266
+ const summary = ` Ops: ${ops.length} · ran ${ran} · failed ${failed} · skipped ${skipped}`;
267
+
268
+ if (failed > 0) {
269
+ ctx.ui.notify(
270
+ [
271
+ header,
272
+ summary,
273
+ ...report,
274
+ "",
275
+ `❌ NOT stamped — ${failed} op(s) failed. Fix and re-run /api verify.`,
276
+ ].join("\n"),
277
+ "warning",
278
+ );
279
+ return;
280
+ }
281
+ if (ran === 0) {
282
+ ctx.ui.notify(
283
+ [
284
+ header,
285
+ summary,
286
+ ...report,
287
+ "",
288
+ `⚠ NOT stamped — all ops skipped. Supply params via verify.json (${dirName}/verify.json), or verify manually via api-fetch.`,
289
+ ].join("\n"),
290
+ "warning",
291
+ );
292
+ return;
293
+ }
294
+
295
+ stampVerified(dirName);
296
+ ctx.ui.notify(
297
+ [
298
+ header,
299
+ summary,
300
+ ...report,
301
+ "",
302
+ `✅ All runnable ops passed — stamped verified: ${TODAY()}`,
303
+ ].join("\n"),
304
+ "info",
305
+ );
306
+ }
307
+
308
+ // ═══════════════════════════════════════════════════════════════════
309
+ // Helpers
310
+ // ═══════════════════════════════════════════════════════════════════
311
+
312
+ /**
313
+ * The params an op still needs to run: path `{token}`s (never defaultable —
314
+ * they're filled from the params map), `required: true` query params with no
315
+ * default, and an unsatisfied `requiresAnyOf` group. Anything the executor
316
+ * would throw on before making a request.
317
+ *
318
+ * A `requiresAnyOf` group contributes ONE group-level reason when no member
319
+ * is supplied; group members are governed by the group, not per-param
320
+ * required (the parser bans `required: true` on them), so they're skipped
321
+ * in the per-param loop.
322
+ */
323
+ function unsatisfiableParams(
324
+ op: Operation,
325
+ supplied: Record<string, unknown>,
326
+ ): string[] {
327
+ const missing: string[] = [];
328
+ for (const token of op.pathParams) {
329
+ if (supplied[token] === undefined) missing.push(token);
330
+ }
331
+ const group = op.requiresAnyOf;
332
+ const groupMember = new Set(group ?? []);
333
+ if (group && group.length > 0) {
334
+ const anySupplied = group.some((name) => supplied[name] !== undefined);
335
+ if (!anySupplied) missing.push(`one of: ${group.join(", ")}`);
336
+ }
337
+ for (const [key, spec] of Object.entries(op.params)) {
338
+ if (groupMember.has(key)) continue; // governed by the group
339
+ if (
340
+ spec.required &&
341
+ spec.default === undefined &&
342
+ supplied[key] === undefined
343
+ ) {
344
+ missing.push(key);
345
+ }
346
+ }
347
+ return missing;
348
+ }
349
+
350
+ /** Load the co-located verify.json sidecar, best-effort. */
351
+ function loadVerifyJson(
352
+ dirName: string,
353
+ ):
354
+ | { data: Record<string, Record<string, unknown>> }
355
+ | { error: string }
356
+ | null {
357
+ const p = join(getUserGuidesDir(), dirName, "verify.json");
358
+ if (!existsSync(p)) return null;
359
+ try {
360
+ const parsed: unknown = JSON.parse(readFileSync(p, "utf-8"));
361
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
362
+ return { data: parsed as Record<string, Record<string, unknown>> };
363
+ }
364
+ return { error: "expected a JSON object" };
365
+ } catch (err) {
366
+ return { error: err instanceof Error ? err.message : String(err) };
367
+ }
368
+ }
369
+
370
+ /** One report line for a successful op run. A transform warning is noted but
371
+ * non-blocking — the HTTP op succeeded, so the op counts as pass. */
372
+ function opLine(
373
+ outcome: Extract<ResolveOpResult, { ok: true }>,
374
+ op: Operation,
375
+ ): string {
376
+ if (outcome.via === "restGet") {
377
+ const r = outcome.result as RestGetResult;
378
+ const warn =
379
+ r.transformWarning === undefined
380
+ ? ""
381
+ : ` — transform warning: ${r.transformWarning}`;
382
+ return ` ✓ ${op.name} — ${op.path} (restGet)${warn}`;
383
+ }
384
+ const r = outcome.result as PaginateResult;
385
+ return ` ✓ ${op.name} — ${r.totalFetched} item(s) (paginate)`;
386
+ }
387
+
388
+ /**
389
+ * Stamp `verified: today` into the raw guide.md (frontmatter-isolated,
390
+ * line-level — comments + key order preserved), then invalidate the cache so
391
+ * the next api-guide / api-fetch sees the fresh date immediately.
392
+ */
393
+ function stampVerified(dirName: string): void {
394
+ const filepath = join(getUserGuidesDir(), dirName, "guide.md");
395
+ const raw = readFileSync(filepath, "utf-8");
396
+ const stamped = stampFrontmatterField(raw, "verified", TODAY());
397
+ writeFileSync(filepath, stamped, "utf-8");
398
+ invalidateCache();
399
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "REST API client for Pi. A YAML file per API covers endpoints and pagination; the agent calls through a fixed executor so an API encoded once is reusable forever, not re-derived each session. It can probe a live endpoint and write the YAML for you, and a TypeScript file alongside can add custom auth or reshape the request and response freely.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -21,6 +21,16 @@
21
21
  "publishConfig": {
22
22
  "access": "public"
23
23
  },
24
+ "exports": {
25
+ ".": "./index.ts",
26
+ "./core/helpers.js": "./core/helpers.ts",
27
+ "./core/parse-api-guide.js": "./core/parse-api-guide.ts",
28
+ "./core/guide-store.js": "./core/guide-store.ts",
29
+ "./core/local-helpers.js": "./core/local-helpers.ts",
30
+ "./core/api-guide-types.js": "./core/api-guide-types.ts",
31
+ "./core/transport.js": "./core/transport.ts",
32
+ "./core/auth.js": "./core/auth.ts"
33
+ },
24
34
  "files": [
25
35
  "index.ts",
26
36
  "LICENSE",
@@ -40,6 +50,10 @@
40
50
  "core/auth.ts",
41
51
  "core/portal-projection.ts",
42
52
  "core/response-spill.ts",
53
+ "core/resolve-op.ts",
54
+ "core/guide-picker.ts",
55
+ "core/verify-command.ts",
56
+ "core/delete-command.ts",
43
57
  "core/verify-ship-manifest.ts",
44
58
  "tools/index.ts",
45
59
  "tools/api-guide.ts",