pi-lean-host 0.0.1 → 0.1.1

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