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.
@@ -72,8 +72,10 @@ function helpText(): string {
72
72
  " /api verify --help this help",
73
73
  "",
74
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`,
75
+ " are skipped, not failed. Scaffold a starter sidecar with api-scaffold({domain, verify: true})",
76
+ ' (writes to /tmp, with "__FILL_ME__" sentinels for every blocking param), then save via',
77
+ " api-learn({domain, dir}) — the sidecar lives at:",
78
+ ` ~/.pi/agent/pi-lean-host/api-guides/<dirName>/verify.json`,
77
79
  ` { "<opName>": { "<param>": "<value>" } }`,
78
80
  "",
79
81
  " Not free: N live HTTP requests against the target API (GET only — no mutation).",
@@ -213,53 +215,82 @@ export async function handleVerifySubcommand(
213
215
  let skipped = 0;
214
216
 
215
217
  for (const op of ops) {
216
- const supplied = verifyJson[op.name] ?? {};
217
- const missing = unsatisfiableParams(op, supplied);
218
+ // Strip `"__FILL_ME__"` sentinels (from verify.json / api-scaffold) so
219
+ // they never count as supplied params or serialize into the query string.
220
+ const rawSupplied = verifyJson[op.name] ?? {};
221
+ const supplied: Record<string, unknown> = {};
222
+ for (const [k, v] of Object.entries(rawSupplied)) {
223
+ if (v !== "__FILL_ME__") supplied[k] = v;
224
+ }
225
+ const missing = renderForReport(unsatisfiable(op, supplied));
218
226
  if (missing.length > 0) {
219
227
  skipped++;
220
228
  report.push(
221
- ` ⏭ ${op.name} — skipped: requires agent-supplied params (${missing.join(", ")}) — verify manually via api-fetch`,
229
+ ` ⏭ ${op.name} — skipped: requires agent-supplied params (${missing.join(", ")}) — scaffold via api-scaffold({domain, verify: true}), or verify manually via api-fetch`,
222
230
  );
223
231
  continue;
224
232
  }
225
233
 
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
234
+ // Fan-out: a requiresAnyOf group with >1 supplied member is verified
235
+ // once per member, isolating that member (non-group params carried on
236
+ // every run). Mutually-exclusive peers (id ⊻ symbol) never ride the
237
+ // same request; inclusive-OR filters get per-peer coverage. ≤1 supplied
238
+ // member → today's single run. Sentinels are already stripped above, so
239
+ // a partially-filled file still runs just the real values.
240
+ const group = op.requiresAnyOf ?? [];
241
+ const suppliedMembers = group.filter((m) => supplied[m] !== undefined);
242
+ const runs =
243
+ suppliedMembers.length > 1
244
+ ? suppliedMembers.map((m) => {
245
+ const params = { ...supplied };
246
+ for (const peer of group) {
247
+ if (peer !== m) delete params[peer];
248
+ }
249
+ return { params, tag: m };
250
+ })
251
+ : [{ params: supplied, tag: undefined }];
252
+
253
+ for (const run of runs) {
254
+ let outcome: ResolveOpResult;
255
+ try {
256
+ outcome = await resolveOpForExecution(guide, op, dirName, {
257
+ userParams: run.params,
258
+ });
259
+ } catch (err) {
260
+ failed++;
261
+ const msg =
262
+ err instanceof HelperError
237
263
  ? err.message
238
- : String(err);
239
- report.push(` ✗ ${op.name} — ${msg}`);
240
- continue;
241
- }
264
+ : err instanceof Error
265
+ ? err.message
266
+ : String(err);
267
+ report.push(` ✗ ${opTag(op.name, run.tag)} — ${msg}`);
268
+ continue;
269
+ }
242
270
 
243
- if (!outcome.ok) {
244
- if (outcome.reason === "helper_disabled") {
245
- // Session-persistent condition — unverifiable this session, not broken.
246
- skipped++;
271
+ if (!outcome.ok) {
272
+ if (outcome.reason === "helper_disabled") {
273
+ // Session-persistent condition — unverifiable this session, not broken.
274
+ skipped++;
275
+ report.push(
276
+ ` ⏭ ${opTag(op.name, run.tag)} — skipped: local helper disabled this session (${outcome.message})`,
277
+ );
278
+ // Disabled helpers are session-persistent and deterministic — the
279
+ // remaining fan-out runs would skip identically, so stop here.
280
+ break;
281
+ }
282
+ // auth_required_not_provisioned — unreachable after the precheck
283
+ // (auth is per-guide constant); defensive.
284
+ failed++;
247
285
  report.push(
248
- ` ⏭ ${op.name} — skipped: local helper disabled this session (${outcome.message})`,
286
+ ` ✗ ${opTag(op.name, run.tag)} — requires secret not provisioned: ${outcome.missing.join(", ")}`,
249
287
  );
250
288
  continue;
251
289
  }
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
290
 
261
- ran++;
262
- report.push(opLine(outcome, op));
291
+ ran++;
292
+ report.push(opLine(outcome, op, run.tag));
293
+ }
263
294
  }
264
295
 
265
296
  const header = `📡 Verify: ${guide.shortName} (${dirName})`;
@@ -285,7 +316,7 @@ export async function handleVerifySubcommand(
285
316
  summary,
286
317
  ...report,
287
318
  "",
288
- `⚠ NOT stamped — all ops skipped. Supply params via verify.json (${dirName}/verify.json), or verify manually via api-fetch.`,
319
+ `⚠ NOT stamped — all ops skipped. Scaffold a verify.json via api-scaffold({domain: "${domain}", verify: true}), or supply params via ${dirName}/verify.json, or verify manually via api-fetch.`,
289
320
  ].join("\n"),
290
321
  "warning",
291
322
  );
@@ -310,29 +341,36 @@ export async function handleVerifySubcommand(
310
341
  // ═══════════════════════════════════════════════════════════════════
311
342
 
312
343
  /**
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.
344
+ * Why an op can't run yet: a path `{token}` (never defaultable — filled from
345
+ * the params map), a `required: true` query param with no default, or an
346
+ * unsatisfied `requiresAnyOf` group. Anything the executor would throw on
347
+ * before making a request.
317
348
  *
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.
349
+ * A `requiresAnyOf` group contributes ONE group-level entry when no member is
350
+ * supplied; group members are governed by the group, not per-param required
351
+ * (the parser bans `required: true` on them), so they're skipped in the
352
+ * per-param loop.
322
353
  */
323
- function unsatisfiableParams(
354
+ export type Unsatisfiable =
355
+ | { kind: "path"; param: string }
356
+ | { kind: "group"; members: string[] }
357
+ | { kind: "query"; param: string };
358
+
359
+ /** The params an op still needs to run, as structured entries. */
360
+ export function unsatisfiable(
324
361
  op: Operation,
325
362
  supplied: Record<string, unknown>,
326
- ): string[] {
327
- const missing: string[] = [];
363
+ ): Unsatisfiable[] {
364
+ const missing: Unsatisfiable[] = [];
328
365
  for (const token of op.pathParams) {
329
- if (supplied[token] === undefined) missing.push(token);
366
+ if (supplied[token] === undefined)
367
+ missing.push({ kind: "path", param: token });
330
368
  }
331
369
  const group = op.requiresAnyOf;
332
370
  const groupMember = new Set(group ?? []);
333
371
  if (group && group.length > 0) {
334
372
  const anySupplied = group.some((name) => supplied[name] !== undefined);
335
- if (!anySupplied) missing.push(`one of: ${group.join(", ")}`);
373
+ if (!anySupplied) missing.push({ kind: "group", members: group });
336
374
  }
337
375
  for (const [key, spec] of Object.entries(op.params)) {
338
376
  if (groupMember.has(key)) continue; // governed by the group
@@ -341,14 +379,40 @@ function unsatisfiableParams(
341
379
  spec.default === undefined &&
342
380
  supplied[key] === undefined
343
381
  ) {
344
- missing.push(key);
382
+ missing.push({ kind: "query", param: key });
345
383
  }
346
384
  }
347
385
  return missing;
348
386
  }
349
387
 
388
+ /** Render unsatisfiable entries exactly as the verify report shows them. */
389
+ function renderForReport(items: Unsatisfiable[]): string[] {
390
+ return items.map((item) => {
391
+ switch (item.kind) {
392
+ case "group":
393
+ return `one of: ${item.members.join(", ")}`;
394
+ case "path":
395
+ case "query":
396
+ return item.param;
397
+ }
398
+ });
399
+ }
400
+
401
+ /** Render unsatisfiable entries as one sentinel key per param. */
402
+ export function renderForSentinels(items: Unsatisfiable[]): string[] {
403
+ return items.flatMap((item) => {
404
+ switch (item.kind) {
405
+ case "group":
406
+ return item.members;
407
+ case "path":
408
+ case "query":
409
+ return [item.param];
410
+ }
411
+ });
412
+ }
413
+
350
414
  /** Load the co-located verify.json sidecar, best-effort. */
351
- function loadVerifyJson(
415
+ export function loadVerifyJson(
352
416
  dirName: string,
353
417
  ):
354
418
  | { data: Record<string, Record<string, unknown>> }
@@ -367,22 +431,29 @@ function loadVerifyJson(
367
431
  }
368
432
  }
369
433
 
434
+ /** `name (member)` when a fan-out run is tagged, else `name`. */
435
+ function opTag(name: string, tag?: string): string {
436
+ return tag === undefined ? name : `${name} (${tag})`;
437
+ }
438
+
370
439
  /** One report line for a successful op run. A transform warning is noted but
371
440
  * non-blocking — the HTTP op succeeded, so the op counts as pass. */
372
441
  function opLine(
373
442
  outcome: Extract<ResolveOpResult, { ok: true }>,
374
443
  op: Operation,
444
+ tag?: string,
375
445
  ): string {
446
+ const name = opTag(op.name, tag);
376
447
  if (outcome.via === "restGet") {
377
448
  const r = outcome.result as RestGetResult;
378
449
  const warn =
379
450
  r.transformWarning === undefined
380
451
  ? ""
381
452
  : ` — transform warning: ${r.transformWarning}`;
382
- return ` ✓ ${op.name} — ${op.path} (restGet)${warn}`;
453
+ return ` ✓ ${name} — ${op.path} (restGet)${warn}`;
383
454
  }
384
455
  const r = outcome.result as PaginateResult;
385
- return ` ✓ ${op.name} — ${r.totalFetched} item(s) (paginate)`;
456
+ return ` ✓ ${name} — ${r.totalFetched} item(s) (paginate)`;
386
457
  }
387
458
 
388
459
  /**
package/index.ts CHANGED
@@ -5,9 +5,11 @@ import {
5
5
  apiFetchTool,
6
6
  apiLearnTool,
7
7
  apiProbeTool,
8
+ apiScaffoldTool,
8
9
  } from "./tools/index.js";
9
10
  import initApiToggle from "./core/api-toggle.js";
10
11
  import { registerPortalProjection } from "./core/portal-projection.js";
12
+ import { invalidateCache, loadAllGuides } from "./core/guide-store.js";
11
13
  import { cleanupAllSpill } from "./core/response-spill.js";
12
14
  import { resetToggleModuleState } from "./core/api-toggle.js";
13
15
  import { resetDisabledHelpers } from "./core/local-helpers.js";
@@ -24,6 +26,7 @@ export default function (pi: ExtensionAPI): void {
24
26
  pi.registerTool(apiFetchTool);
25
27
  pi.registerTool(apiLearnTool);
26
28
  pi.registerTool(apiProbeTool);
29
+ pi.registerTool(apiScaffoldTool);
27
30
 
28
31
  // ── Register /api command and session hooks ─────────────────
29
32
  initApiToggle(pi);
@@ -33,8 +36,20 @@ export default function (pi: ExtensionAPI): void {
33
36
  // Runtime feature-detect — no static portal import.
34
37
  registerPortalProjection();
35
38
  // session_start ensures registration even if host loads before portal.
36
- pi.on("session_start", async () => {
39
+ pi.on("session_start", async (_event, ctx) => {
37
40
  registerPortalProjection();
41
+ // Clear the guide-store cache so a folder rename made between sessions
42
+ // (the divergence check's "mv then /reload" migration) is picked up —
43
+ // regardless of whether pi re-evaluates the module or re-calls the entry
44
+ // function with persisted module-level state (the /resume path).
45
+ invalidateCache();
46
+ // Trigger a fresh scan with the UI notify channel so the migration
47
+ // banner + per-guide warnings render through the Text component (wraps
48
+ // long lines, honors newlines) instead of raw console.warn (truncates
49
+ // + merges with the status bar). No-op on a warm cache; every later
50
+ // command/tool call hits the cached scan, so this is the single
51
+ // load-time warning point.
52
+ loadAllGuides(ctx.ui.notify);
38
53
  });
39
54
 
40
55
  // ── Response spill cleanup ─────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.3.1",
3
+ "version": "0.4.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",
@@ -35,6 +35,7 @@
35
35
  "index.ts",
36
36
  "LICENSE",
37
37
  "core/ssrf-guard.ts",
38
+ "core/status-hint.ts",
38
39
  "core/guide-loader.ts",
39
40
  "core/api-guide-types.ts",
40
41
  "core/parse-api-guide.ts",
@@ -59,6 +60,7 @@
59
60
  "tools/api-guide.ts",
60
61
  "tools/api-fetch.ts",
61
62
  "tools/api-learn.ts",
63
+ "tools/api-scaffold.ts",
62
64
  "tools/api-probe.ts",
63
65
  "tools/utils.ts",
64
66
  "README.md"
@@ -62,7 +62,8 @@ export const apiFetchTool = defineTool({
62
62
  description:
63
63
  "Fetch structured data from a REST API using a recipe-based guide. " +
64
64
  "Requires an API guide for the target domain. " +
65
- "Call api-guide({domain}) to see available operations, or api-learn({domain, recipeFile}) to author a new guide.",
65
+ "Call api-guide({domain}) to see available operations, or api-learn({domain, dir}) to author a new guide.\n\n" +
66
+ "Authoring: pass params per call to test an op (verify.json feeds /api verify, not api-fetch).",
66
67
 
67
68
  parameters: Type.Object({
68
69
  domain: Type.String({
@@ -519,7 +520,7 @@ function formatAmbiguousOperation(
519
520
  `Call api-guide({domain: "${domain}", guide: "${first.guide.shortName}"}) to read each guide's full recipe,`,
520
521
  );
521
522
  lines.push(
522
- `then re-author one guide via api-learn({domain: "${first.dirName}", recipeFile: …}) with the colliding operation renamed so the names no longer clash.`,
523
+ `then re-author one guide via api-learn({dir: …}) with the colliding operation renamed so the names no longer clash.`,
523
524
  );
524
525
  lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
525
526
  return lines.join("\n");
@@ -579,7 +580,7 @@ function formatHelperError(
579
580
  if (err.url) lines.push(formatRequestLine("GET", err.url));
580
581
  lines.push("");
581
582
  lines.push(
582
- `Call api-guide({domain: "${domain}"}) to review the guide, or api-learn({domain: "${domain}", recipeFile: …}) to fix it.`,
583
+ `Call api-guide({domain: "${domain}"}) to review the guide, or api-learn({domain: "${domain}", dir: …}) to fix it.`,
583
584
  );
584
585
  return lines.join("\n");
585
586
  }
@@ -77,7 +77,7 @@ export const apiGuideTool = defineTool({
77
77
  text:
78
78
  `No API guide for '${domain}'.` +
79
79
  (known.length > 0 ? ` Known guides: ${known.join(", ")}.` : "") +
80
- "\n\nCall api-guide with no params to list all guides, or api-learn({domain, recipeFile}) to author one.",
80
+ "\n\nCall api-guide with no params to list all guides, or api-learn({domain, dir}) to author one.",
81
81
  },
82
82
  ],
83
83
  details: {},