pi-lean-host 0.0.1 → 0.1.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
@@ -1,41 +1,772 @@
1
- # pi-lean-host
1
+ # pi-lean-host User Guide
2
2
 
3
- > Placeholder for future pi-lean-portal browser benchmarking suite.
3
+ > **pi-lean-host** gives the Pi coding agent declarative access to REST APIs —
4
+ > recipe-based guides that encode an API's endpoints, auth, pagination, and
5
+ > response shape once, then execute through a small set of managed tools. The
6
+ > agent never hand-rolls auth headers, never picks the wrong `Accept`, never
7
+ > re-derives pagination from scratch each session. A `/api` toggle (peer to
8
+ > `/web`) hides the tools from context on sessions that aren't doing API work,
9
+ > and `/api on` + `/web off` gives a pure **api-only** context with zero
10
+ > `browser-*` noise for batch structured-data pulls.
11
+ >
12
+ > Some sites are hostile to scrape but expose a clean, documented API.
13
+ > `pi-lean-host` is the structured-data answer to that gap — author the API
14
+ > once, reuse it forever.
15
+ >
16
+ > Part of the [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
17
+ > web-tools suite. Host-only installs are valid — **`pi-lean-portal` is an
18
+ > optional peer dependency**. For interactive browsing, install
19
+ > [`pi-lean-portal`](https://www.npmjs.com/package/pi-lean-portal); for
20
+ > SearXNG search, install
21
+ > [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
4
22
 
5
- **pi-lean-host** is the evaluation harness for
6
- [pi-lean-portal](https://github.com/coreyryanhanson/pi-lean-dimension/tree/main/packages/pi-lean-portal)
7
- `BrowserPlugin` backends against [BrowserGym](https://github.com/ServiceNow/BrowserGym)
8
- task suites (MiniWoB, WebArena, WorkArena, etc.).
23
+ > ⚠️ **Early release (0.1.0).** The API tools here work today, but this is a
24
+ > development preview. The recipe schema, tool surfaces, and guide format are
25
+ > still settling as we test more APIs to finalize the shape — **future
26
+ > compatibility is not guaranteed** until the package reaches lockstep with
27
+ > `pi-lean-dimension` 0.5.0. Guides authored against 0.1.0 may need revision
28
+ > as the schema firms up.
9
29
 
10
- This package is **research tooling** — it consumes `pi-lean-portal`'s
11
- `BrowserPlugin` interface and runs behavioral evaluation tests (MiniWoB,
12
- WebArena, custom task packages) against any plugin implementation.
30
+ ---
13
31
 
14
- ## Status
32
+ ## Table of Contents
15
33
 
16
- 🚧 **Placeholder** — the §1.0 CDP endpoint spike has completed successfully
17
- (see [`docs/cdp-endpoint-spike.md`](docs/cdp-endpoint-spike.md)), proving that
18
- two Playwright clients can share one Chromium instance via CDP attach with
19
- no `@e`-ref contamination. Full implementation follows the
20
- [BrowserGym migration plan](../../browsergym-migration-plan.md).
34
+ 1. [Quick Start](#quick-start)
35
+ 2. [The Big Idea: Recipes, Not a Runtime](#the-big-idea-recipes-not-a-runtime)
36
+ 3. [`/api` Command — API Toggle](#api-command--api-toggle)
37
+ 4. [All 4 Tools](#all-4-tools)
38
+ 5. [Guide Recipes (the `recipe` block)](#guide-recipes-the-recipe-block)
39
+ 6. [Authoring a Guide](#authoring-a-guide)
40
+ 7. [Local User Helpers](#local-user-helpers)
41
+ 8. [Pagination Styles](#pagination-styles)
42
+ 9. [Response Shapes (`parseResponse`)](#response-shapes-parseresponse)
43
+ 10. [Multi-Recipe Domains](#multi-recipe-domains)
44
+ 11. [Bundled Reference Recipes](#bundled-reference-recipes)
45
+ 12. [`/api status` — Detailed Runtime Status](#api-status--detailed-runtime-status)
46
+ 13. [Configuration (`settings.json`)](#configuration-settingsjson)
47
+ 14. [Co-Installing with `pi-lean-portal`](#co-installing-with-pi-lean-portal)
48
+ 15. [Tips & Best Practices](#tips--best-practices)
49
+ 16. [Security & Scope](#security--scope)
21
50
 
22
- ## Planned contents
51
+ ---
23
52
 
24
- - `adapter/browsergym-bridge.py` — Python JSON-RPC adapter for BrowserGym
25
- task setup/validate
26
- - `adapter/browsergym-adapter.ts` — TypeScript wrapper, CDP attach, task
27
- lifecycle
28
- - `solvers/` — Trivial solvers for MiniWoB parity validation
29
- - `suites/` — Test files that run BrowserGym tasks against BrowserPlugin
30
- backends
31
- - `scripts/setup-venv` — Dedicated BrowserGym virtual environment
32
- - `scripts/setup-miniwob` — MiniWoB++ HTML content checkout
53
+ ## Quick Start
33
54
 
34
- ## npm namespace
55
+ ```bash
56
+ pi install npm:pi-lean-host
57
+ ```
35
58
 
36
- `pi-lean-host` is published to npm as a **placeholder** (`0.0.1`) to
37
- reserve the name. Real content ships under later versions.
59
+ No browser binaries, no server, no setup wizard. The host tools are **enabled
60
+ by default** — you'll see:
38
61
 
39
- ## License
62
+ > 📡 API tools enabled. /api learn to make api-learn + api-probe available.
40
63
 
41
- AGPL-3.0-only
64
+ From a fresh install you have no guides yet, so the workflow is:
65
+
66
+ 1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe`).
67
+ 2. **`api-probe({apiHost, path})`** — discover the shape of a not-yet-guided
68
+ endpoint; it drafts a YAML operation block to paste into a recipe.
69
+ 3. **`api-learn({domain, recipe})`** — write the guide to
70
+ `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
71
+ 4. **`api-fetch({domain, operation})`** — execute and verify.
72
+
73
+ Or skip the authoring and **copy a bundled reference recipe** (see
74
+ [Bundled Reference Recipes](#bundled-reference-recipes)) into
75
+ `~/.pi/agent/pi-lean-host/api-guides/<domain>/` — it loads immediately.
76
+
77
+ > **Host-only is a first-class install.** `pi-lean-host` declares
78
+ > `pi-lean-portal` as an *optional* peer dependency and has zero static
79
+ > imports from it. The core loop — authoring via docs/example, on-demand
80
+ > discovery, guided execution — runs with no browser package installed.
81
+ > Co-installing portal is planned to unlock two additive features
82
+ > (navigate-footer surfacing and probe-authoring via `web-fetch`) in a
83
+ > **future release**. Host-side projection code is present but inert
84
+ > until portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
85
+
86
+ ---
87
+
88
+ ## The Big Idea: Recipes, Not a Runtime
89
+
90
+ The single most important discipline: **only files you place in
91
+ `~/.pi/agent/pi-lean-host/` execute.** An API guide is a markdown file with
92
+ YAML frontmatter declaring endpoints, auth, pagination, and response shape.
93
+ A managed tool (`api-fetch`) executes the declared operation through a small
94
+ fixed set of built-in helpers. The agent never writes TypeScript against the
95
+ API — it authors (or copies) a recipe, and the tool does the call.
96
+
97
+ This kills two whole classes of recurring mistakes before they exist:
98
+
99
+ - **Agents getting the same API wrong every session.** The reason they do is
100
+ *they are the ones writing the calls.* Move call construction into a
101
+ reviewed tool + fixed helpers, and the agent never touches the auth
102
+ header, never hand-rolls pagination, never picks the wrong `Accept`.
103
+ - **Arbitrary eval / egress safety.** Executable TS in a guide is a sandbox
104
+ problem. Declarative recipes executed by a fixed tool are not — and because
105
+ bundled recipes are inert, the only code that ever runs is code you
106
+ explicitly placed in your own directory.
107
+
108
+ ### Three tiers of code, separated by trust
109
+
110
+ | Tier | Where it lives | Who writes it | Ships in tarball? | Trust |
111
+ |------|----------------|---------------|-------------------|-------|
112
+ | Built-in helpers | package source (`core/`) | maintainers | yes | reviewed |
113
+ | Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
114
+ | Bundled recipes | `api-guides/<domain>/` in the repo (GitHub) | maintainers | no (reference) | **inert — never auto-executed** |
115
+
116
+ Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
117
+ (computed signatures, strange date transforms, custom auth). Bundled recipes
118
+ are inert reference material on GitHub — the loader never reads `api-guides/`
119
+ from the package. You adopt one by copying the whole domain folder into your
120
+ own directory; only then does it load and execute.
121
+
122
+ ---
123
+
124
+ ## `/api` Command — API Toggle
125
+
126
+ `/api` is an **independent peer** of `/web`, not a child. They compose
127
+ freely: each owns its own tool set and its own status-bar slot, and neither
128
+ touches the other's tools.
129
+
130
+ | Command | Effect |
131
+ |---------|--------|
132
+ | `/api on` | **API access** — `api-guide` + `api-fetch` available. Authoring tools hidden. (Default for new sessions.) |
133
+ | `/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. |
134
+ | `/api off` | **All API tools hidden** — removes `api-*` from the agent's context to save tokens on sessions that aren't doing API work. |
135
+ | `/api` | Show current state and available sub-commands. |
136
+ | `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
137
+ | `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
138
+
139
+ ### Why a peer toggle?
140
+
141
+ The concrete win is **api-only mode**: `/api on` + `/web off` turns off every
142
+ `browser-*` tool while keeping structured API access live. That's the workflow
143
+ that pays for the machinery — batch structured-data pulls against a known API
144
+ (paginating a JSON endpoint to exhaustion, querying a documented read API
145
+ across many dates) where the browser tools are pure context noise you want
146
+ gone, but API access must stay on. A `/web`-child toggle cannot give you
147
+ that — `/web off` would kill both together.
148
+
149
+ ### Persistence
150
+
151
+ Toggle state persists via the [`pi-tool-masking`](https://github.com/coreyryanhanson/pi-tool-masking/)
152
+ library (`persistKey: toolset-state:pi-lean-dimension.api`), surviving
153
+ `/reload`, `/resume`, `/fork`, and `/tree` navigation. A fresh conversation
154
+ starts from the `toolsetDefaults` block in merged Pi settings (see
155
+ [Configuration](#configuration-settingsjson)), falling back to the packaged
156
+ default (`on` for `api`, `off` for `api-learn`).
157
+
158
+ The status bar shows an `api` glyph (independent of the `browser`/`search`
159
+ slots). It reads `● api` when `/api` is on (colored to reflect learn state)
160
+ and `○ api` when off.
161
+
162
+ ---
163
+
164
+ ## All 4 Tools
165
+
166
+ `pi-lean-host` registers 4 tools. `api-guide` and `api-fetch` are available
167
+ under `/api on`; `api-learn` and `api-probe` are added under `/api learn`.
168
+
169
+ The four tools split cleanly by side-effect boundary — one each for **local
170
+ read**, **network read**, **local write**, and **network read (exploratory)**:
171
+
172
+ ### 1. `api-guide` — Inspect the Guide Store (local read)
173
+
174
+ ```text
175
+ api-guide → list all available API guides (catalog)
176
+ api-guide domain="en.wikipedia.org" → disambiguation menu (two guides claim the domain)
177
+ api-guide domain="en.wikipedia.org" guide="Wikipedia REST" → selected guide
178
+ ```
179
+
180
+ - No parameters → the full catalog (collapsed by `organization:`).
181
+ - `{domain}` → the guide's detailed operation list, or a disambiguation menu
182
+ when more than one guide claims the domain.
183
+ - `{domain, guide}` → the selected guide, resolved by `shortName`.
184
+
185
+ When a guide is malformed on disk it shows with a `⚠ malformed` badge and the
186
+ error inline rather than silently disappearing — so you can fix the one
187
+ broken field instead of re-authoring from scratch.
188
+
189
+ ### 2. `api-fetch` — Execute a Guided Operation (network read)
190
+
191
+ ```text
192
+ api-fetch domain="en.wikipedia.org" operation="getPageSummary" params={title:"Albert_Einstein"}
193
+ api-fetch domain="en.wikipedia.org" operation="searchPages" params={srsearch:"climate"} gatherAll=true
194
+ ```
195
+
196
+ **Parameters:**
197
+
198
+ - `domain` — a domain registered in a guide (e.g. `"en.wikipedia.org"`).
199
+ - `operation` — an operation name from the guide (e.g. `"getPageSummary"`).
200
+ - `params` (optional) — path and query parameter values for the operation.
201
+ - `gatherAll` (optional) — `true` paginates to gather all items up to the
202
+ guide's `gatherAllMax` ceiling (default `1000`, overridable per-guide and
203
+ per-op).
204
+
205
+ `api-fetch` resolves every guide claiming `domain`, finds the named
206
+ `operation` across them, and executes it against the matching guide (helper
207
+ routed by directory name, not the routing `domain`). The agent never sees a
208
+ URL, never sees a header, never sees the auth scheme. Output is an inline
209
+ preview (~4000 chars) with larger responses spilled to a temp file under
210
+ `/tmp/pi-lean-host/` (overridable via `PI_HOST_TEMP_DIR`) — `read` it with
211
+ offset/limit for specific sections.
212
+
213
+ When no guide exists for the domain, the call **fails informatively** and
214
+ points at `api-guide({})` (to list guided domains) and `api-learn` (to author
215
+ one) — turning a failed execute into a discovery moment in one round-trip.
216
+
217
+ ### 3. `api-learn` — Author / Update a Guide (local write)
218
+
219
+ ```text
220
+ api-learn → worked example recipe + field reference
221
+ api-learn domain="boe.es" recipe="---\nkind: api\n…" → writes the guide to disk
222
+ ```
223
+
224
+ - No parameters → a complete worked-example recipe (the BOE shape, exercising
225
+ the core fields) plus a concise field reference. Read once at
226
+ authoring time, never carried on executing turns.
227
+ - `{domain, recipe}` → validates the recipe string **before** touching disk,
228
+ then writes to `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`,
229
+ overwriting any existing guide for that domain. On a structural error it
230
+ names the field, the expected shape, and what was found — the file on disk
231
+ is left untouched (no half-written guide). Requires `/api learn`.
232
+
233
+ There is no draft store, no `/api save`, no session-held state — the file on
234
+ disk *is* the working state, exactly like `web-learn`. If the recipe is wrong,
235
+ call `api-learn` again to overwrite.
236
+
237
+ ### 4. `api-probe` — Discover an Endpoint's Shape (network read, exploratory)
238
+
239
+ ```text
240
+ api-probe apiHost="https://api.github.com" path="/repos/{owner}/{repo}/branches" params={owner:"torvalds", repo:"linux"}
241
+ ```
242
+
243
+ Shape-discovery for the authoring loop. Fetches a templated path over the
244
+ real transport (same UA, charset, 429-retry, ETag cache as `api-fetch` — the
245
+ sanctioned way to reach even WAF'd hosts), summarizes the JSON shape, suggests
246
+ `via` / `itemsPath` / pagination style, echoes a representative record id, and
247
+ emits a **draft YAML operation block** to paste straight into a recipe. On 404
248
+ it auto-tries `/v1` and `/v2` prefixes (disable with `tryPrefixes=false`).
249
+
250
+ `api-probe` only **suggests** — it never writes the guide. The operation must
251
+ still be traceable to your plan source (the API docs or a working curl
252
+ example); this tool surfaces evidence, not authority. Requires `/api learn`.
253
+
254
+ ---
255
+
256
+ ## Guide Recipes (the `recipe` block)
257
+
258
+ A guide is one markdown file: YAML frontmatter carries the structured recipe
259
+ (the executable contract), and a prose body carries orientation for the
260
+ agent (advisory). `api-fetch` reads the recipe slice and executes against it;
261
+ `api-guide` reads the detail slice for introspection. **The prose is
262
+ advisory, the frontmatter is authoritative.**
263
+
264
+ ### A complete example (the BOE shape)
265
+
266
+ ```yaml
267
+ ---
268
+ kind: api
269
+ domains: [boe.es, www.boe.es]
270
+ icon: ⚖️
271
+ shortName: BOE
272
+ updated: 2026-07-17
273
+ # organization: boe.es # optional — org identity across guides
274
+ # description: BOE open-data API. # optional — ≤200 chars, one line; aids disambiguation
275
+ apiHost: https://apidatos.boe.es/v1
276
+ verified: 2026-07-17
277
+ gatherAllMax: 500
278
+
279
+ auth:
280
+ kind: none
281
+
282
+ pagination:
283
+ style: offset-limit
284
+ pageParam: page
285
+ pageSizeParam: limit
286
+ pageSize: 50
287
+ itemsPath: data
288
+ # totalCountPath: meta.totalCount # optional, any style → server total in the footer
289
+
290
+ responseShape:
291
+ format: json
292
+ charset: utf-8
293
+
294
+ operations:
295
+ - name: searchDiary
296
+ via: restGet
297
+ path: /diario/{date}
298
+ accept: json
299
+ params:
300
+ limit:
301
+ default: 50
302
+ helper: true # run this domain's local helper.ts for this op
303
+ parse:
304
+ format: xml
305
+ charset: iso-8859-1
306
+
307
+ - name: listConsolidada
308
+ via: paginate
309
+ path: /legislacion-consolidada
310
+ accept: json
311
+ pagination:
312
+ style: cursor
313
+ cursorParam: cursor
314
+ cursorPath: pagination.nextCursor
315
+ itemsPath: results
316
+ gatherAllMax: 1000 # op-level ceiling override
317
+ ---
318
+ # BOE Legislación Consolidada — structured API access
319
+
320
+ Use `api-fetch` with `searchDiary` to pull a day's dispatch (pass `date` as
321
+ `YYYYMMDD`). Use `listConsolidada` with `gatherAll: true` to walk consolidated
322
+ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
323
+ `date` param; it lives at
324
+ `~/.pi/agent/pi-lean-host/api-guides/boe.es/helper.ts`.
325
+ ```
326
+
327
+ ### Field reference
328
+
329
+ | Field | Level | Default | Purpose |
330
+ |---|---|---|---|
331
+ | `kind` | guide | `"api"` | the guide type; defaults to `"api"` and is omittable. Values like `"web"` are rejected for API guides. |
332
+ | `domains` | guide | — | discovery keys (plural bare aliases) |
333
+ | `icon` / `shortName` / `updated` | guide | `📖` / filename / today | presentation slice (portal + `api-guide`) |
334
+ | `apiHost` | guide | — | execution root: scheme + host + base path; the version prefix lives here |
335
+ | `organization` | guide | — | optional org identity (registrable domain); catalog grouping + disambiguation. Recipe-slice only |
336
+ | `description` | guide | — | optional one-line summary (≤200 chars); primary disambiguation signal for multi-guide domains |
337
+ | `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
338
+ | `verified` | guide | creation date | drift signal — **defaulted, not enforced** |
339
+ | `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
340
+ | `auth.kind` | guide | `none` | strategy seam — **v1 realizes only `none`** (others error) |
341
+ | `auth.headers` | guide | — | optional extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) |
342
+ | `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
343
+ | `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
344
+ | `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
345
+ | `responseShape.format` | guide / op | `json` | `json` \| `xml` \| `text` → drives `parseResponse` (`text` is raw passthrough) |
346
+ | `responseShape.charset` | guide / op | `utf-8` | `utf-8` or any IANA charset name (e.g. `iso-8859-1`); used as a fallback when the response's Content-Type header omits a charset — an explicit header charset wins |
347
+ | `operations[].name` | op | — | the `operation` arg `api-fetch` takes |
348
+ | `operations[].via` | op | — | executor: `restGet` \| `paginate` |
349
+ | `operations[].path` | op | — | relative path; `{token}` = inferred path param (no re-declaration) |
350
+ | `operations[].accept` | op | `json` | `json` \| `xml` \| `<any media-type string>` — request-side `Accept` header (distinct from `responseShape.format`) |
351
+ | `operations[].params` | op | `{}` | query params; `{ required?, default?, description? }` per key |
352
+ | `operations[].dateParams` | op | — | optional `{param: format}` → normalizes ISO dates to `iso8601` \| `yyyymmdd` \| `yyyy-mm-dd` (query params only) |
353
+ | `operations[].helper` | op | `false` | `true` runs this domain's local helper for the op |
354
+ | `operations[].transform` | op | `false` | `true` runs the helper's `transform` export on the parsed response (graceful — a throw returns raw data, never disables the op) |
355
+ | `operations[].passthrough` | op | `false` | `true` forwards undeclared caller params onto the query string (for open-param APIs) |
356
+ | `operations[].parse` | op | inherits `responseShape` | op-level override of format/charset |
357
+ | `operations[].pagination` | op | inherits top-level | op-level override of pagination |
358
+
359
+ ### Built-in helpers (the fixed executor set)
360
+
361
+ Three helpers, for v1. The agent never calls these directly — `api-fetch`
362
+ routes each operation through the one its `via` names:
363
+
364
+ - **`restGet`** — path templating, query params, Accept negotiation
365
+ (JSON/XML), and auth injection *when a guide declares a strategy*. v1 ships
366
+ only `auth.kind: none`, so no v1 guide declares a strategy — the dispatch
367
+ exists as a seam, but the injection path is cold code until a keyed guide
368
+ lands.
369
+ - **`paginate`** — wraps a list operation. The guide declares the style; the
370
+ helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
371
+ stop or continue, plus a `gatherAll` flag for the "just get me everything"
372
+ case with a hard ceiling.
373
+ - **`parseResponse`** — XML→JSON, declared per-endpoint (charset decoding happens in the transport).
374
+ Agents mangle encodings constantly; fix it once here.
375
+
376
+ `restPost`/mutations are **not** in scope for v1 — the target APIs are
377
+ overwhelmingly GET-read.
378
+
379
+ ### Recipe drift
380
+
381
+ A prose guide degrades gracefully; a declarative recipe with a wrong endpoint
382
+ fails **hard**. v1 treats drift as a signal the agent reads, not a gate the
383
+ loader enforces:
384
+
385
+ - The `verified` frontmatter date records when a guide was last verified
386
+ against the live API (defaulted to creation date, **never enforced**). It's
387
+ rendered in the guide-detail footer alongside the current date — the agent
388
+ reads both and judges.
389
+ - The **live HTTP response is the actual drift signal.** A 401 on a no-auth
390
+ guide, a 404 on a pinned path, a changed response shape — the agent reads
391
+ those directly. The `verified` date is predictive; the response is actual.
392
+
393
+ ---
394
+
395
+ ## Authoring a Guide
396
+
397
+ The authoring model is **spec-first, probe-second**: read the contract and
398
+ encode it, then verify the encoding. The trial-and-error lives at the
399
+ *verification* step, not the discovery step. The loop is:
400
+
401
+ ```
402
+ api-learn (write) → api-fetch (verify) → api-learn (fix) → api-fetch (verify)
403
+ ```
404
+
405
+ exactly like the browser's `web-learn → browser-navigate → web-learn` loop,
406
+ just at the recipe layer. `api-learn`'s return message nudges this
407
+ ("guide saved; call `api-fetch(...)` to verify"). A guide on disk that has
408
+ been successfully executed against *is* verified.
409
+
410
+ ### Authoring paths, prioritized
411
+
412
+ 1. **Documentation-driven (primary, works host-only).** Read the API's docs
413
+ — via `web-fetch` (portal) or pasted/filepath (host-only) — encode them as
414
+ a recipe via `api-learn`, verify with `api-fetch`. The docs *are* the
415
+ affordance; this is the natural default.
416
+ 2. **Example-generalization (works host-only).** Paste a working curl command
417
+ or code sample; the agent generalizes from the one example to a recipe.
418
+ A single working call teaches the base URL, the Accept header, the
419
+ response shape.
420
+ 3. **Probe-and-verify (needs portal, last resort).** Use `api-probe` (or
421
+ portal's `web-fetch`) to hit endpoints, read responses, build a candidate
422
+ recipe. Possible, but reading the docs is cheaper than probing.
423
+ 4. **OpenAPI/Swagger import (deferred).** A spec→recipe transformer is
424
+ mechanical when a machine-readable spec exists; build it when a second
425
+ guide with a spec arrives.
426
+
427
+ **Known limitation — api-only is a known-domains mode.** If your request
428
+ doesn't name a domain and no guide in the catalog matches, the agent can't
429
+ discover a brand-new API from scratch in api-only mode. That requires web
430
+ tools (to search/browse and find the API) or you supplying the domain. It's
431
+ an inherent trade-off of a clean api-only context, not a design flaw.
432
+
433
+ ---
434
+
435
+ ## Local User Helpers
436
+
437
+ For sites that need a computed signature, a strange date transform, or a
438
+ custom auth flow a declarative recipe can't express — one local user helper
439
+ per guide:
440
+
441
+ - **Location:** `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts`
442
+ (alongside the guide's `guide.md`).
443
+ - **Authoring gate:** `/api learn` (the explicit opt-in, mirroring `/web
444
+ learn`). **Execution gate:** `/api on` only — a persisted helper runs on
445
+ later sessions whenever a guide references it, even outside learn mode.
446
+ - **Pre-call contract:** `(params, ctx) => params | Promise<params>` — a
447
+ transform that receives the resolved param map (path + query merged,
448
+ defaults filled) and returns the final map the executor templates and sends.
449
+ - **Post-response transform (gated):** an optional `transform(data, ctx)`
450
+ *named export* from the same `helper.ts`, run when an op declares
451
+ `transform: true`. Graceful by contract — a throw is caught per-call and
452
+ the agent gets the raw untransformed data with a warning, never a disabled
453
+ op. Cannot inspect response headers.
454
+
455
+ ### Safety model
456
+
457
+ Local helpers run **in-process** via `import()` with the agent's privileges —
458
+ no process boundary. This is a deliberately new isolation profile in the
459
+ codebase: stealth backends run as out-of-process Python subprocesses (a crash
460
+ is caught; pi keeps running), whereas local helpers load in-process. The
461
+ mitigations:
462
+
463
+ - A load/call guard wraps both `import()` and each call in `try/catch`. Any
464
+ in-frame throw (syntax error, missing dep, throw during execution) rejects
465
+ the promise — it does **not** crash pi. On failure the helper is marked
466
+ disabled for the session and surfaced via `/api status` (and the status-bar
467
+ glyph). pi keeps running; only that one helper is dead until you fix it and
468
+ reload.
469
+ - The one case the guard **cannot** catch is a helper that registers a
470
+ *background* callback (`setTimeout`, `setInterval`, `process.on(...)`) and
471
+ throws from it later — that escapes the call frame as an
472
+ `uncaughtException` and can take pi down. **The helper-author rule:
473
+ synchronous-pure or fully awaited, no background work.** That covers every
474
+ realistic v1 helper (format a query string, sign a header, compute a date).
475
+ If a real keyed guide ever needs background work, isolation (worker thread
476
+ or subprocess) gets revisited then.
477
+ - A persisted helper can make arbitrary network calls on later sessions. The
478
+ mitigation is user ownership and review, not a sandbox.
479
+
480
+ 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.
482
+
483
+ ---
484
+
485
+ ## Pagination Styles
486
+
487
+ `paginate` follows the style declared in the recipe. Six styles cover the
488
+ patterns the bundled 17-recipe spread pressure-tested:
489
+
490
+ | Style | What it sends | Key fields |
491
+ |-------|---------------|------------|
492
+ | `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `itemsPath` |
493
+ | `page` | 1-based page number + page size | same fields as `offset-limit` (semantic difference only) |
494
+ | `nextLink` | follows a URL from the response body | `nextLinkPath`, `itemsPath` — the **only** SSRF-guarded path (see [Security](#security--scope)) |
495
+ | `cursor` | echoes an opaque cursor query param | `cursorParam`, `cursorPath`, `itemsPath` |
496
+ | `resumptionToken` | OAI-PMH opaque single-token cursor | `tokenParam`, `tokenPath`, `itemsPath` |
497
+ | `tokenBag` | Wikimedia-style multi-key continuation dict | `continuationParams[]`, `itemsPath` |
498
+
499
+ `totalCountPath` is optional on any style — a JSON path to the server's
500
+ reported total, surfaced as `serverTotal` in the `paginate` result and as
501
+ `server total: N` / `remaining: …` in the `api-fetch` footer. Omit it when
502
+ the API exposes no total.
503
+
504
+ `pagination` and `responseShape` are top-level defaults; an individual
505
+ operation overrides them with its own block.
506
+
507
+ ---
508
+
509
+ ## Response Shapes (`parseResponse`)
510
+
511
+ Agents mangle encodings constantly; `parseResponse` fixes it once. Declared
512
+ per-guide (top-level `responseShape`) and overridable per-op (`parse:`):
513
+
514
+ - `format: json | xml | text` — XML is converted to JSON via `fast-xml-parser`; `text` is raw passthrough.
515
+ - `charset: utf-8 | <IANA name>` — the transport decodes using the response's Content-Type charset, falling back to this value when the header omits one (essential for Latin-1 / ISO-8859-1 APIs like BOE that serve bytes without a charset parameter). An explicit header charset always wins.
516
+ - `accept` (request-side, on each operation) is declared **independently**
517
+ from `responseShape.format` (response-side) — they usually match but an API
518
+ may return XML regardless of `Accept`, so they're separate fields.
519
+
520
+ ---
521
+
522
+ ## Multi-Recipe Domains
523
+
524
+ A domain may claim **multiple guides** — each in its own directory (e.g.
525
+ `archive.org` + `archive.org-wayback`). `buildDomainMap` is multi-valued
526
+ (`Record<string, string[]>`):
527
+
528
+ - `api-guide({domain})` shows a **disambiguation menu** and accepts a `guide`
529
+ selector (resolved by `shortName`).
530
+ - `api-fetch({domain, operation})` resolves the operation **by name across
531
+ all matching guides** — exactly one hit executes (helper routed by the
532
+ guide's directory name, not the routing `domain`); zero lists ops from all
533
+ matches; an op name appearing in ≥2 guides is an ambiguous collision the
534
+ authors must fix (re-author via `api-learn` to rename).
535
+
536
+ Optional `organization:` (catalog grouping) and `description:` (≤200 chars,
537
+ the primary disambiguation signal) fields help the catalog and menu stay
538
+ legible when several guides share a domain. `api-learn` warns on collision so
539
+ you know you're in disambiguation territory.
540
+
541
+ ---
542
+
543
+ ## Bundled Reference Recipes
544
+
545
+ The repo ships **17 reference recipes** under `api-guides/` (GitHub only —
546
+ **not in the npm tarball, never auto-loaded**). They are inert worked
547
+ examples spanning the no-auth axes the helper set was validated against:
548
+
549
+ ```
550
+ api.gbif.org api.github.com archive.org archive.org-wayback
551
+ boe.es datos.gob.es earthquake.usgs.gov en.wikipedia.org
552
+ en.wikipedia.org-action loc.gov musicbrainz.org openlibrary.org
553
+ resources.data.gov services.dnb.de web.archive.org www.federalregister.gov
554
+ www.wikidata.org
555
+ ```
556
+
557
+ To use them, copy the guides into your own directory from a shallow clone of
558
+ the feature branch ([browse the folder on GitHub](https://github.com/coreyryanhanson/pi-lean-dimension/tree/feat/pi-lean-host-package/packages/pi-lean-host/api-guides)):
559
+
560
+ ```bash
561
+ git clone --depth 1 --branch feat/pi-lean-host-package \
562
+ https://github.com/coreyryanhanson/pi-lean-dimension.git /tmp/pi-lean-dimension
563
+ cp -r /tmp/pi-lean-dimension/packages/pi-lean-host/api-guides/* \
564
+ ~/.pi/agent/pi-lean-host/api-guides/
565
+ ```
566
+
567
+ To grab a single domain instead of all of them, copy just its folder
568
+ (e.g. `.../api-guides/en.wikipedia.org`).
569
+
570
+ Only then does it load and execute. A recipe may carry
571
+ `operation.helper: true` plus an accompanying `helper.ts` in its domain
572
+ subdir as a worked example — but it stays inert until you copy the folder.
573
+ See [`api-guides/CONTRIBUTING.md`](./api-guides/CONTRIBUTING.md) for authoring
574
+ a bundled recipe, and
575
+ [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md)
576
+ for the per-recipe quirk breakdown and the built-in vs local-helper
577
+ classification.
578
+
579
+ ---
580
+
581
+ ## `/api status` — Detailed Runtime Status
582
+
583
+ ```text
584
+ /api status
585
+ ```
586
+
587
+ ```text
588
+ 📡 API status
589
+ State: on
590
+ Learn: ❌ off
591
+
592
+ Guides: 2 active
593
+ Domains: en.wikipedia.org, boe.es, www.boe.es
594
+ Helpers: 1 present
595
+ ⚠ Disabled: boe.es
596
+ Run /api helpers to list them.
597
+
598
+ /api on enable api-guide + api-fetch
599
+ /api learn enable all four tools (adds api-learn + api-probe)
600
+ /api off disable all API tools
601
+ ```
602
+
603
+ Covers toggle state, active guide count, the domain list, and helper health
604
+ (disabled helpers surface with a `⚠`). When `pi-lean-portal` and
605
+ `pi-lean-search` are also installed, the status bar shows three independent
606
+ glyphs: `● idle` (browser), `● searxng` (search), and `● api` (host — when
607
+ `/api` is on).
608
+
609
+ ---
610
+
611
+ ## Configuration (`settings.json`)
612
+
613
+ Host settings are read from `~/.pi/agent/settings.json` (global) and
614
+ `.pi/settings.json` (project-local, overrides global).
615
+
616
+ ### `toolsetDefaults` (toolset on/off defaults)
617
+
618
+ Whether the API tools are enabled on fresh conversations. Read by the
619
+ `pi-tool-masking` library at restore time, between the chat-branch tier and
620
+ the toolset's packaged default:
621
+
622
+ ```jsonc
623
+ {
624
+ "toolsetDefaults": {
625
+ "toolset-state:pi-lean-dimension.api": { "enabled": true },
626
+ "toolset-state:pi-lean-dimension.api-learn": { "enabled": false }
627
+ }
628
+ }
629
+ ```
630
+
631
+ - Keys are the toolsets' `persistKey` values.
632
+ - Omit a key to use the packaged default (`api` defaults `true`; `api-learn`
633
+ defaults `false`).
634
+ - The `api-learn` toolset `requires` `api`, so enabling learn cascades api on;
635
+ disabling api cascades learn off.
636
+
637
+ ### No other settings keys
638
+
639
+ There is no `host.*` settings block in v1. The transport layer (per-domain
640
+ undici `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
641
+ caching) is configured internally; auth has no keyed strategy yet, so there
642
+ are no secrets or endpoints to configure. `apiHost` and operation paths live
643
+ **in the recipe frontmatter**, not in settings.
644
+
645
+ ---
646
+
647
+ ## Co-Installing with `pi-lean-portal`
648
+
649
+ > **Planned for a future release.** Portal integration is
650
+ > being developed on the `pi-lean-host-integration` branch (0.5.0-track
651
+ > code, continuously rebased onto this package branch). The projection and
652
+ > navigate-footer surfacing described below are what that track delivers.
653
+ > Host-side projection code is present but inert until portal ships the
654
+ > receiving global (`__piLeanPortalRegisterGuideProvider`).
655
+
656
+ Portal is fully optional. When co-installed, host registers a **projection**
657
+ of its user-authored `ApiGuide`s with portal's guide-source registry at load
658
+ time — recipe fields stripped, presentation fields kept — so they **surface
659
+ in the navigate footer** in browse mode (`/web on` + `/api on`), the same
660
+ reactive mechanism web guides use. Host→portal opt-in; portal never imports
661
+ host.
662
+
663
+ - **Host-first ordering.** When both a host guide and a web guide match a
664
+ domain, the host guide surfaces first (API access is cheaper, more
665
+ reliable, lower-context than browsing). Both still surface; you choose.
666
+ Host guides surface only when `/api` is on; web guides only when `/web`
667
+ is on. No suppression — partial-coverage APIs keep their web guide for the
668
+ gaps the API doesn't cover.
669
+ - **The projection carries one extra field**, `kind: "web" | "api"` (default
670
+ `"web"`), which portal consumes only for ordering and the footer `reason`
671
+ string. No recipe-structured data (`apiHost`, `operations`, `pagination`,
672
+ `auth`) ever crosses the boundary.
673
+
674
+ Host-only installs don't register and lose nothing — reactive surfacing is an
675
+ enhancement for co-installs, not a host-only requirement. The on-demand path
676
+ (`api-guide({domain})`) is fully functional without it.
677
+
678
+ ---
679
+
680
+ ## Tips & Best Practices
681
+
682
+ ### `api-fetch` vs `web-fetch` vs `api-probe`
683
+
684
+ | Use `api-fetch` | Use `api-probe` | Use `web-fetch` (portal) |
685
+ |-----------------|-----------------|--------------------------|
686
+ | An API you've guided | Discovering shape before authoring a guide | A one-off unguided fetch against a known URL |
687
+ | Repeated/paginated pulls | Drafting an op block from a live endpoint | Reading docs to author a recipe |
688
+ | You want auth/pagination handled for you | You're in `/api learn` | Host-only with an undocumented API (last resort) |
689
+
690
+ `api-fetch` is the guided path — the guide is the product. It has no
691
+ ad-hoc bare-fetch mode on purpose: that would recreate the exact mistakes
692
+ (hand-rolled auth, no pagination) the tool exists to prevent. The escape
693
+ hatches are `api-learn` (write a guide, then execute through it) and
694
+ `web-fetch` (portal) for a one-off.
695
+
696
+ ### Authoring discipline
697
+
698
+ - Keep the prose body concise — it orients the agent; the frontmatter is the
699
+ executable contract.
700
+ - Cite the source for every operation (docs URL or working example). `api-probe`
701
+ surfaces evidence, not authority — confirm the shape against the docs.
702
+ - Fill `verified:` when you verify; it's defaulted to today, not enforced.
703
+ - Use `description:` when a domain has multiple guides — it's the primary
704
+ disambiguation signal.
705
+
706
+ ### `gatherAll` ceilings
707
+
708
+ A misconfigured `gatherAll` against a 100k-item paginator is a self-DoS. Set
709
+ `gatherAllMax` per-guide (or per-op) to the endpoint's real ceiling when you
710
+ know it. The global fallback (`1000`) bounds undeclared guides.
711
+
712
+ ---
713
+
714
+ ## Security & Scope
715
+
716
+ ### SSRF guard (server-supplied URLs only)
717
+
718
+ Host guards only the one URL path that earns it: `paginate`'s `nextLink`
719
+ style, where the next URL comes from the **remote API's response body** — a
720
+ URL neither you nor the agent chose. `ssrfGuard()` (a minimal `core/ssrf-guard.ts`,
721
+ no deps, no portal import) blocks loopback, private RFC1918 ranges, and cloud
722
+ metadata endpoints (`169.254.169.254`, `metadata.google.internal`,
723
+ `100.100.100.200`) on that server-supplied `nextUrl` before it is followed.
724
+
725
+ Agent-supplied URLs are **not** guarded. `restGet` assembles a URL from
726
+ `apiHost` + `operation.path` + query params — all agent- or user-directed.
727
+ The agent runs on your own machine with your own privileges and has `bash`,
728
+ `read`, and `write` over the filesystem; blocking `http://169.254.169.254/`
729
+ on `restGet` while `curl` is one tool-call away is a sieve with one hole
730
+ patched. The guard becomes load-bearing the moment keyed auth ships (a
731
+ server-supplied `nextUrl` to an internal host would leak the attached
732
+ `Authorization` header) — it is in place now so that channel is closed before
733
+ the credential-bearing path arrives.
734
+
735
+ ### v1 scope (what it is not)
736
+
737
+ - **GET-read only.** No mutation helper. Add one only when a real *retrieval*
738
+ guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
739
+ gate — and that gate's foundation is a scoped secrets schema, deferred past
740
+ v1.
741
+ - **`auth.kind: none` only.** The `auth.kind` field + dispatch is a seam for
742
+ future `static-key` / `oauth2` strategies; only `none` is realized. No
743
+ secrets store ships in v1 — no OS-native store, no file fallback, no
744
+ `requires`/`scopes` resolution, no secret-entry UX. The seam is what keeps
745
+ that future build additive rather than a retrofit.
746
+ - **Bundled recipes are inert.** Nothing the package ships executes until you
747
+ place it in `~/.pi/agent/pi-lean-host/` and opt in.
748
+ - **No inferred-link discovery.** Declared links only in v1; inference is v2.
749
+ - **No guide suppression.** Both guide kinds surface by domain match when
750
+ their toggle is on; host-first is a preference, not suppression.
751
+
752
+ ### Mission
753
+
754
+ `pi-lean-host` is a navigation and information-retrieval aide. It exists to
755
+ help an agent obtain information from structured APIs with as little friction
756
+ as possible — not to author content or automate online actions. Features
757
+ whose primary value is creating, mutating, or bot-automating will not be
758
+ added, even when technically feasible, unless they serve retrieval. The
759
+ local-helper escape hatch means a capable user *can* build bots on their own
760
+ machine; the package does not aim to make that easy.
761
+
762
+ ---
763
+
764
+ > `pi-lean-host` is part of the
765
+ > [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
766
+ > web-tools suite. For the deferred secrets-store track (the two-threat
767
+ > model and the first-keyed-guide build checklist), see
768
+ > [`docs/design/api-secrets-roadmap.md`](docs/design/api-secrets-roadmap.md).
769
+ > For the helper escape-valve policy and the 17-recipe spread, see
770
+ > [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md).
771
+ >
772
+ > License: AGPL-3.0-only