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.
package/README.md CHANGED
@@ -20,7 +20,17 @@
20
20
  > SearXNG search, install
21
21
  > [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
22
22
 
23
- > ⚠️ **Early release (0.3.1).** The API tools here work today, but this is a
23
+ > ⚠️ **Breaking change in 0.4.0 — guide folders are now keyed by `shortName`.**
24
+ > Each guide must live in a folder named `slug(shortName)` — its `shortName`
25
+ > lowercased, with non-alphanumeric runs replaced by `-` (e.g. `shortName:
26
+ > BOE` → folder `boe`). Guides still sitting in a `<domain>/` folder from 0.3.x
27
+ > are flagged **malformed** and won't load until you rename the folder to
28
+ > `slug(shortName)` and `/reload` — the startup warnings give the exact `mv`
29
+ > command. Hand the warnings to the agent; it will fix them for you.
30
+
31
+ <!-- TODO(0.5.0): remove this temporary breaking-change note once the 0.4.0 migration is settled. -->
32
+
33
+ > ⚠️ **Early release (0.4.0).** The API tools here work today, but this is a
24
34
  > development preview. The recipe schema, tool surfaces, and guide format are
25
35
  > still settling as we test more APIs to finalize the shape — **future
26
36
  > compatibility is not guaranteed** until the package reaches lockstep with
@@ -34,7 +44,7 @@
34
44
  1. [Quick Start](#quick-start)
35
45
  2. [The Big Idea: Recipes, Not a Runtime](#the-big-idea-recipes-not-a-runtime)
36
46
  3. [`/api` Command — API Toggle](#api-command--api-toggle)
37
- 4. [All 4 Tools](#all-4-tools)
47
+ 4. [All 5 Tools](#all-5-tools)
38
48
  5. [Guide Recipes (the `recipe` block)](#guide-recipes-the-recipe-block)
39
49
  6. [Authoring a Guide](#authoring-a-guide)
40
50
  7. [Local User Helpers](#local-user-helpers)
@@ -60,21 +70,24 @@ pi install npm:pi-lean-host
60
70
  No browser binaries, no server, no setup wizard. The host tools are **enabled
61
71
  by default** — you'll see:
62
72
 
63
- > 📡 API tools enabled. /api learn to make api-learn + api-probe available.
73
+ > 📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold available.
64
74
 
65
75
  From a fresh install you have no guides yet, so the workflow is:
66
76
 
67
- 1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe`).
77
+ 1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe` +
78
+ `api-scaffold`).
68
79
  2. **`api-probe({apiHost, path})`** — discover the shape of a not-yet-guided
69
80
  endpoint; it drafts a YAML operation block to paste into a recipe.
70
- 3. **`api-learn({domain, recipeFile})`** — validate the staged draft and write
81
+ 3. **`api-learn({domain, dir})`** — validate the staged draft(s) and write
71
82
  the guide to
72
- `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
83
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/guide.md`.
73
84
  4. **`api-fetch({domain, operation})`** — execute and verify.
74
85
 
75
86
  Or skip the authoring and **copy a bundled reference recipe** (see
76
87
  [Bundled Reference Recipes](#bundled-reference-recipes)) into
77
- `~/.pi/agent/pi-lean-host/api-guides/<domain>/` — it loads immediately.
88
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` — it loads
89
+ immediately. The folder name must match `slug(shortName)` (see the
90
+ 0.4.0 breaking-change note above).
78
91
 
79
92
  > **Host-only is a first-class install.** `pi-lean-host` declares
80
93
  > `pi-lean-portal` as an *optional* peer dependency and has zero static
@@ -127,7 +140,7 @@ demand. A skill is pure text with no in-process eval, whereas a loaded
127
140
  | Tier | Where it lives | Who writes it | Ships in tarball? | Trust |
128
141
  |------|----------------|---------------|-------------------|-------|
129
142
  | Built-in helpers | package source (`core/`) | maintainers | yes | reviewed |
130
- | Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
143
+ | Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
131
144
  | Bundled recipes | `caritas` repo (`api-guides/<domain>/`) | maintainers | no (reference) | **inert — never auto-executed** |
132
145
 
133
146
  Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
@@ -148,7 +161,7 @@ touches the other's tools.
148
161
  | Command | Effect |
149
162
  |---------|--------|
150
163
  | `/api on` | **API access** — `api-guide` + `api-fetch` available. Authoring tools hidden. (Default for new sessions.) |
151
- | `/api learn` | **API access + authoring** — adds `api-learn` + `api-probe` on top of `on`. The agent never authors guides unprompted — it must be in learn mode. |
164
+ | `/api learn` | **API access + authoring** — adds `api-learn` + `api-probe` + `api-scaffold` on top of `on`. The agent never authors guides unprompted — it must be in learn mode. |
152
165
  | `/api off` | **All API tools hidden** — removes `api-*` from the agent's context to save tokens on sessions that aren't doing API work. |
153
166
  | `/api` | Show current state and available sub-commands. |
154
167
  | `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
@@ -182,13 +195,15 @@ and `○ api` when off.
182
195
 
183
196
  ---
184
197
 
185
- ## All 4 Tools
198
+ ## All 5 Tools
186
199
 
187
- `pi-lean-host` registers 4 tools. `api-guide` and `api-fetch` are available
188
- under `/api on`; `api-learn` and `api-probe` are added under `/api learn`.
200
+ `pi-lean-host` registers 5 tools. `api-guide` and `api-fetch` are available
201
+ under `/api on`; `api-learn`, `api-probe`, and `api-scaffold` are added under
202
+ `/api learn`.
189
203
 
190
- The four tools split cleanly by side-effect boundary — one each for **local
191
- read**, **network read**, **local write**, and **network read (exploratory)**:
204
+ The five tools split cleanly by side-effect boundary — one each for **local
205
+ read**, **network read**, **local write**, **network read (exploratory)**, and
206
+ **local write (bootstrap)**:
192
207
 
193
208
  ### 1. `api-guide` — Inspect the Guide Store (local read)
194
209
 
@@ -239,35 +254,41 @@ one) — turning a failed execute into a discovery moment in one round-trip.
239
254
 
240
255
  ```text
241
256
  api-learn domain="arxiv.org" new=true → stages a fresh placeholder template to /tmp/pi-lean-host/arxiv.org/guide.md
242
- api-learn domain="arxiv.org" → fetches an existing guide's raw recipe into the staged file
243
- api-learn domain="arxiv.org" recipeFile="/tmp/pi-lean-host/arxiv.org/guide.md" → validates + writes the guide to disk
257
+ api-learn domain="arxiv.org" → fetches an existing guide's raw recipe + siblings into the staged dir
258
+ api-learn domain="arxiv.org" dir="/tmp/pi-lean-host/arxiv.org" → validates + mirror-saves the staged dir to disk
244
259
  ```
245
260
 
246
261
  - `{domain, new: true}` → a fresh starter template with `domains: [<domain>]`
247
262
  **staged to `/tmp/pi-lean-host/<domain>/guide.md`**. Only `domains` is real;
248
263
  the other fields are `<placeholder>` values that **fail closed**, so a
249
264
  pasted template cannot save until you fill it in.
250
- - `{domain}` (no `recipeFile`) → fetch the current raw recipe of an existing
251
- guide into the staged file (surfaces `dirName` to prevent sibling-clobber
252
- in multi-recipe domains); a disambiguation menu if several guides claim the
253
- domain.
265
+ - `{domain}` (no `dir`) → fetch the current raw recipe of an existing guide
266
+ **and its present siblings** (`helper.ts`, `verify.json`) into the staged
267
+ dir (surfacing the guide's `dirName` so you know which folder it lives in);
268
+ a disambiguation menu if several guides claim the domain.
254
269
  - Every staged pull (template or fetched recipe) is prepended with the
255
270
  authoring manual — the field reference + defaults + semantics the author
256
271
  needs at the moment of authoring.
257
- - `{domain, recipeFile}` → reads the staged draft, validates it **before**
258
- touching disk, then writes to
259
- `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`. A fail-closed
272
+ - `{domain, dir}` → reads every staged file, validates the guide **before**
273
+ touching disk, then **mirror-saves** the staged dir to
274
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` — the folder is
275
+ derived from the guide's own `shortName`, not the `domain` arg, so a
276
+ re-save naturally lands back in the same folder. Present staged files
277
+ overwrite their guides-dir counterparts; a sibling present in the guides dir
278
+ but absent from the staged dir would be deleted, so save **refuses and
279
+ names the doomed files** until you re-call with `confirmDeletions: true`
280
+ (that flag is discovered only via the refusal message). A fail-closed
260
281
  guard refuses to overwrite an existing `guide.md` whose `shortName`
261
- differs from the incoming guide (prevents clobbering a sibling in a
262
- multi-recipe domain); a same-`shortName` save is a legitimate update.
263
- On a structural error it names the field, the expected shape, and what
264
- was found — the file on disk is left untouched (no half-written guide).
265
- Requires `/api learn`.
282
+ differs from the incoming guide — a slug collision (two shortNames that
283
+ slug to the same folder, e.g. `cmc_full` / `cmc-full`); a same-`shortName`
284
+ save is a legitimate update. On a structural error it names the field, the
285
+ expected shape, and what was found — the file on disk is left untouched (no
286
+ half-written guide). Requires `/api learn`.
266
287
 
267
- The working copy is staged at `/tmp/pi-lean-host/<domain>/guide.md` (`/tmp`
288
+ The working copy is staged at `/tmp/pi-lean-host/<domain>/` (`/tmp`
268
289
  self-cleans, so drafts don't accumulate) — fetch/template calls write the
269
- draft there and you edit that file between saves; saving reads it and
270
- publishes to the guides dir. No session-held state, no `/api save`.
290
+ draft there and you edit that file between saves; saving reads the staged dir
291
+ and publishes to the guides dir. No session-held state, no `/api save`.
271
292
 
272
293
  ### 4. `api-probe` — Discover an Endpoint's Shape (network read, exploratory)
273
294
 
@@ -290,6 +311,33 @@ newest version up front.
290
311
  still be traceable to your plan source (the API docs or a working curl
291
312
  example); this tool surfaces evidence, not authority. Requires `/api learn`.
292
313
 
314
+ ### 5. `api-scaffold` — Bootstrap `verify.json` / `helper.ts` (local write)
315
+
316
+ ```text
317
+ api-scaffold domain="arxiv.org" verify=true → writes a starter verify.json with "__FILL_ME__" sentinels to /tmp/pi-lean-host/arxiv.org/verify.json
318
+ api-scaffold domain="arxiv.org" helper=true → writes a commented-out helper.ts stub to /tmp/pi-lean-host/arxiv.org/helper.ts
319
+ ```
320
+
321
+ Bootstrap tool for the two artifacts the authoring loop needs but that
322
+ `api-learn` can't draft from the recipe alone:
323
+
324
+ - `{domain, verify: true}` → for every op with unsatisfiable params (path
325
+ `{token}`, required query with no default, `requiresAnyOf` group), writes
326
+ `{ "<opName>": { "<param>": "__FILL_ME__" } }` to the staged
327
+ `/tmp/pi-lean-host/<slug(shortName)>/verify.json`. `"__FILL_ME__"` is a
328
+ sentinel: treated as unsupplied, so the op skips until you replace it. If a
329
+ `verify.json` exists in the guides dir, its real values are **additively
330
+ merged** (preserved; sentinels added only for newly-unsatisfiable params).
331
+ - `{domain, helper: true}` → writes a commented-out `helper.ts` stub (both
332
+ `default` and `transform` exports, with doc comments) to the same staged
333
+ dir.
334
+ - At least one of `verify`/`helper` must be `true`. The tool **never
335
+ overwrites** an existing staged sibling — delete it from `/tmp` first, then
336
+ re-call. Staging is keyed by `slug(shortName)` (same pattern as
337
+ `api-learn`), so a scaffolded `verify.json`/`helper.ts` lands in the same
338
+ dir `api-learn` saves from. Save the guide **first**, then scaffold —
339
+ `api-scaffold` reads the saved guide. Requires `/api learn`.
340
+
293
341
  ---
294
342
 
295
343
  ## Guide Recipes (the `recipe` block)
@@ -438,7 +486,7 @@ For sites that need a computed signature, a strange date transform, or a
438
486
  custom auth flow a declarative recipe can't express — one local user helper
439
487
  per guide:
440
488
 
441
- - **Location:** `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts`
489
+ - **Location:** `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/helper.ts`
442
490
  (alongside the guide's `guide.md`).
443
491
  - **Authoring gate:** `/api learn` (the explicit opt-in, mirroring `/web
444
492
  learn`). **Execution gate:** `/api on` only — a persisted helper runs on
@@ -478,7 +526,7 @@ mitigations:
478
526
  mitigation is user ownership and review, not a sandbox.
479
527
 
480
528
  View helpers with `/api helpers` (list) or `/api helpers <domain>` (source).
481
- Authoring is via `api-learn` in learn mode, or hand-editing the file.
529
+ Authoring: scaffold a starter `helper.ts` stub via `api-scaffold({domain, helper: true})` (writes to the staged `/tmp` dir — never the guides dir), uncomment the export you need, then save via `api-learn({domain, dir})`. Edit a staged helper the same way; avoid hand-editing the file in the guides dir directly.
482
530
 
483
531
  ---
484
532
 
@@ -522,7 +570,8 @@ per-guide (top-level `responseShape`) and overridable per-op (`parse:`):
522
570
  ## Multi-Recipe Domains
523
571
 
524
572
  A domain may claim **multiple guides** — each in its own directory (e.g.
525
- `archive.org` + `archive.org-wayback`). `buildDomainMap` is multi-valued
573
+ `internet-archive` + `wayback-availability`, both claiming the `archive.org`
574
+ domain). `buildDomainMap` is multi-valued
526
575
  (`Record<string, string[]>`):
527
576
 
528
577
  - `api-guide({domain})` shows a **disambiguation menu** and accepts a `guide`
@@ -547,18 +596,20 @@ The comprehensive recipe library lives in the
547
596
  verified recipes spanning the no-auth **and keyed** axes, each with a
548
597
  per-recipe `verified:`-date provenance and the perpetual drift disclaimer.
549
598
  They are inert reference material: nothing executes until you copy a recipe
550
- into your own `~/.pi/agent/pi-lean-host/api-guides/<domain>/` directory.
599
+ into your own `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/`
600
+ directory — the folder name must match `slug(shortName)` or it routes to
601
+ **malformed** (see the 0.4.0 breaking-change note above).
551
602
 
552
603
  The domains caritas covers (a discoverability index, may drift from the live
553
604
  repo):
554
605
 
555
- ```
556
- api.gbif.org api.github.com archive.org archive.org-wayback
557
- arxiv.org boe.es coingecko.com data-api.ecb.europa.eu
558
- datos.gob.es earthquake.usgs.gov en.wikipedia.org en.wikipedia.org-action
559
- etherscan.io eutils.ncbi.nlm.nih.gov gitlab.com loc.gov
560
- musicbrainz.org openlibrary.org resources.data.gov services.dnb.de
561
- web.archive.org www.federalregister.gov www.wikidata.org
606
+ ```text
607
+ arxiv ecb-data-portal internet-archive wayback-availability
608
+ boletin-oficial-del-estado etherscan library-of-congress wayback-cdx-server
609
+ coingecko federal-register musicbrainz wikidata
610
+ data-gov gbif open-library wikimedia-action
611
+ datos-gob-es github pubmed-e-utilities wikipedia-rest
612
+ deutsche-nationalbibliothek gitlab usgs-earthquake
562
613
  ```
563
614
 
564
615
  Several are **keyed** (`auth.kind: static-key`), the spread that exercises
@@ -609,7 +660,7 @@ axis-set audit matrix).
609
660
  Run /api helpers to list them.
610
661
 
611
662
  /api on enable api-guide + api-fetch
612
- /api learn enable all four tools (adds api-learn + api-probe)
663
+ /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)
613
664
  /api off disable all API tools
614
665
  ```
615
666
 
@@ -300,5 +300,19 @@ export interface LoadedApiGuides {
300
300
  malformed: MalformedGuide[];
301
301
  }
302
302
 
303
+ /**
304
+ * Warning channel for load-time diagnostics — `ctx.ui.notify` when the
305
+ * caller has a UI context, else `console.warn`. The loader defaults to
306
+ * `console.warn` so pure call sites (and tests) stay unchanged; the
307
+ * `session_start` handler passes `ctx.ui.notify` so the migration banner
308
+ * and per-guide warnings render through the Text component (wraps long
309
+ * lines, honors newlines) instead of raw stderr (truncates + merges with
310
+ * the status bar).
311
+ */
312
+ export type NotifyFn = (
313
+ message: string,
314
+ type?: "info" | "warning" | "error",
315
+ ) => void;
316
+
303
317
  // `Guide` (the projection-slice base type) is imported above and extended by
304
318
  // `ApiGuide`; consumers import it directly from ./guide-loader.js when needed.
@@ -4,10 +4,10 @@
4
4
  * Provides /api on, /api off, /api learn, /api status, and /api helpers
5
5
  * commands to enable/disable API tools in the system prompt.
6
6
  *
7
- * Three states: on (api-guide + api-fetch), learn (on + api-learn + api-probe),
8
- * off (all three disabled).
7
+ * Three states: on (api-guide + api-fetch), learn (on + api-learn + api-probe +
8
+ * api-scaffold), off (all disabled).
9
9
  *
10
- * Starts enabled (api-guide + api-fetch on, api-learn + api-probe off), mirroring
10
+ * Starts enabled (api-guide + api-fetch on, api-learn + api-probe + api-scaffold off), mirroring
11
11
  * portal's browser toggle. Both defaults are overridable via the
12
12
  * `toolsetDefaults` settings tier read by pi-tool-masking. The /api toggle
13
13
  * is an independent peer: it composes freely with /web (portal's toggle)
@@ -54,7 +54,7 @@ const HOST_API_SPEC: ToolsetSpec = {
54
54
 
55
55
  const HOST_API_LEARN_SPEC: ToolsetSpec = {
56
56
  id: "pi-lean-dimension.api-learn",
57
- names: new Set(["api-learn", "api-probe"]),
57
+ names: new Set(["api-learn", "api-probe", "api-scaffold"]),
58
58
  persistKey: "toolset-state:pi-lean-dimension.api-learn",
59
59
  defaultEnabled: false,
60
60
  requires: ["pi-lean-dimension.api"],
@@ -149,7 +149,7 @@ function handleStatusSubcommand(
149
149
  state = "off";
150
150
  }
151
151
  const learnFlag = learnOn
152
- ? "✅ on (api-learn + api-probe available)"
152
+ ? "✅ on (api-learn + api-probe + api-scaffold available)"
153
153
  : "❌ off";
154
154
 
155
155
  const allGuides = loadAllGuides();
@@ -187,7 +187,7 @@ function handleStatusSubcommand(
187
187
  lines.push(
188
188
  ``,
189
189
  ` /api on enable api-guide + api-fetch`,
190
- ` /api learn enable all four tools (adds api-learn + api-probe)`,
190
+ ` /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)`,
191
191
  ` /api off disable all API tools`,
192
192
  ` /api verify verify a guide's ops against its live API (stamps verified)`,
193
193
  ` /api delete delete a guide directory (human-typed recovery gesture)`,
@@ -249,7 +249,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
249
249
  apiToolset.enable(pi);
250
250
  learnToolset.disable(pi);
251
251
  ctx.ui.notify(
252
- "📡 API tools enabled. /api learn to make api-learn + api-probe available.",
252
+ "📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold available.",
253
253
  "info",
254
254
  );
255
255
  return;
@@ -264,7 +264,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
264
264
  case "learn": {
265
265
  learnToolset.enable(pi); // cascades api on via requires
266
266
  ctx.ui.notify(
267
- "📖 api-learn + api-probe tools are now available. " +
267
+ "📖 api-learn + api-probe + api-scaffold tools are now available. " +
268
268
  "Agent will discover shapes and save/update guides when asked.",
269
269
  "info",
270
270
  );
@@ -317,7 +317,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
317
317
  `📖 Learn mode: ${learnStatus}`,
318
318
  ``,
319
319
  ` /api on enable api-guide + api-fetch`,
320
- ` /api learn enable all four tools (adds api-learn + api-probe)`,
320
+ ` /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)`,
321
321
  ` /api off disable all API tools`,
322
322
  ` /api status detailed status (guides, helpers)`,
323
323
  ` /api helpers list local helpers`,
@@ -13,7 +13,7 @@ import {
13
13
  formatApiGuideCatalog,
14
14
  } from "./parse-api-guide.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 (migration banner + 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 user = loadApiGuidesFromDir(_userGuidesDir);
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(
@@ -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/<domain>/helper.ts.\n\n` +
39
- "Author a helper via api-learn in learn mode, or hand-edit a <domain>/helper.ts file.",
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, recipeFile}) to author or update a guide (and its helper).",
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/${domain}/helper.ts.\n` +
85
- "Author via api-learn in learn mode.",
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;
package/core/helpers.ts CHANGED
@@ -22,6 +22,7 @@ function expandAccept(accept: string): string {
22
22
  import { XMLParser } from "fast-xml-parser";
23
23
  import { ssrfGuard } from "./ssrf-guard.js";
24
24
  import { scrubSecretValues } from "./auth.js";
25
+ import { serverMessage, isPlanGated } from "./status-hint.js";
25
26
  import {
26
27
  fetchUrl,
27
28
  redactSecretParams,
@@ -408,18 +409,33 @@ function checkResponseStatus(
408
409
  ): void {
409
410
  if (result.status < 400) return;
410
411
 
412
+ // Output-channel audit: scrub known store-injected secret values from the
413
+ // error excerpt so a 401 body echoing an auth header can't leak the key
414
+ // into agent context.
415
+ const scrubbed = scrubSecretValues(result.body, secretValues);
411
416
  // Cap the raw body to avoid flooding the error output.
412
- let message = result.body.slice(0, 500);
417
+ let message = scrubbed.slice(0, 500);
413
418
  // Try to extract <text> from BOE-style XML error bodies.
414
- const textMatch = result.body.match(/<text>([\s\S]*?)<\/text>/i);
419
+ const textMatch = scrubbed.match(/<text>([\s\S]*?)<\/text>/i);
415
420
  if (textMatch) {
416
421
  message = textMatch[1]!.trim();
417
422
  }
418
423
 
419
- // Output-channel audit: scrub known store-injected secret values from the
420
- // error excerpt so a 401 body echoing an auth header can't leak the key
421
- // into agent context.
422
- message = scrubSecretValues(message, secretValues);
424
+ // 403 + structured JSON: surface the server's own reason and flag
425
+ // plan-gating so a "plan doesn't support this endpoint" reads as a
426
+ // key/subscription limitation, not a recipe bug. Same classifier as
427
+ // api-probe — one implementation, two call sites. Parses the scrubbed
428
+ // body (full, for the best chance the JSON is intact), never the raw one.
429
+ // Unlike probe, fetch has no auth context, so it only adds the
430
+ // plan-gating hint — no "auth configured correctly" claim.
431
+ if (result.status === 403) {
432
+ const reason = serverMessage(scrubbed);
433
+ if (reason) {
434
+ message = isPlanGated(scrubbed)
435
+ ? `${reason} (plan/subscription limitation on the key, not the recipe)`
436
+ : reason;
437
+ }
438
+ }
423
439
 
424
440
  throw new HelperError(
425
441
  "response",
@@ -2,7 +2,7 @@
2
2
  * Local user helpers — `import()`-loaded transform modules.
3
3
  *
4
4
  * User-authored TypeScript helpers live alongside their guide in a per-domain
5
- * subdirectory: `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts`.
5
+ * subdirectory: `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/helper.ts`.
6
6
  * They are loaded on demand via dynamic `import()` when an API guide's
7
7
  * operation sets `helper: true`. A load failure (syntax error, missing
8
8
  * dep, top-level throw) or execution throw disables the helper for the
@@ -28,7 +28,7 @@
28
28
  import { join } from "node:path";
29
29
  import { pathToFileURL } from "node:url";
30
30
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
31
- import { getUserGuidesDir } from "./guide-store.js";
31
+ import { getUserGuidesDir, loadAllGuides } from "./guide-store.js";
32
32
  import { assertSafeDomain } from "./path-template.js";
33
33
 
34
34
  // ═══════════════════════════════════════════════════════════════════
@@ -93,10 +93,17 @@ export type CallHelperResult =
93
93
 
94
94
  /**
95
95
  * List all persisted helper domains (domain subdirs with a helper.ts).
96
+ *
97
+ * Only helpers whose folder holds a LOADED (non-malformed) guide are surfaced
98
+ * — a malformed guide's helper is dead (it can never be routed to at fetch
99
+ * time), so listing it is misleading. A helper in a folder with no guide at
100
+ * all is equally dead and hidden. The enumeration intersects the raw
101
+ * filesystem scan with the loader's active-guide set.
96
102
  */
97
103
  export function getAllHelpers(): string[] {
98
104
  const guidesDir = getUserGuidesDir();
99
105
  if (!existsSync(guidesDir)) return [];
106
+ const loadedDirs = new Set(Object.keys(loadAllGuides().guides));
100
107
  const result: string[] = [];
101
108
  for (const entry of readdirSync(guidesDir)) {
102
109
  const entryPath = join(guidesDir, entry);
@@ -105,6 +112,7 @@ export function getAllHelpers(): string[] {
105
112
  } catch {
106
113
  continue;
107
114
  }
115
+ if (!loadedDirs.has(entry)) continue;
108
116
  // Check for helper.ts (or .mjs / .js fallback for tests)
109
117
  for (const ext of [".ts", ".mjs", ".js"] as const) {
110
118
  if (existsSync(join(entryPath, `helper${ext}`))) {