pi-lean-host 0.3.1 → 0.5.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,13 +20,6 @@
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
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.3.x may need revision
28
- > as the schema firms up.
29
-
30
23
  ---
31
24
 
32
25
  ## Table of Contents
@@ -34,20 +27,14 @@
34
27
  1. [Quick Start](#quick-start)
35
28
  2. [The Big Idea: Recipes, Not a Runtime](#the-big-idea-recipes-not-a-runtime)
36
29
  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. [Authentication & Secrets](#authentication--secrets)
49
- 16. [Tips & Best Practices](#tips--best-practices)
50
- 17. [Security & Scope](#security--scope)
30
+ 4. [All 7 Tools](#all-7-tools)
31
+ 5. [Authoring Your First Guide](#authoring-your-first-guide)
32
+ 6. [Reference Recipes (caritas)](#reference-recipes-caritas)
33
+ 7. [Configuration (`settings.json`)](#configuration-settingsjson)
34
+ 8. [Co-Installing with `pi-lean-portal`](#co-installing-with-pi-lean-portal)
35
+ 9. [Tips & Best Practices](#tips--best-practices)
36
+ 10. [Authentication & Secrets](#authentication--secrets)
37
+ 11. [Security & Scope](#security--scope)
51
38
 
52
39
  ---
53
40
 
@@ -60,30 +47,18 @@ pi install npm:pi-lean-host
60
47
  No browser binaries, no server, no setup wizard. The host tools are **enabled
61
48
  by default** — you'll see:
62
49
 
63
- > 📡 API tools enabled. /api learn to make api-learn + api-probe available.
64
-
65
- From a fresh install you have no guides yet, so the workflow is:
66
-
67
- 1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe`).
68
- 2. **`api-probe({apiHost, path})`** — discover the shape of a not-yet-guided
69
- endpoint; it drafts a YAML operation block to paste into a recipe.
70
- 3. **`api-learn({domain, recipeFile})`** — validate the staged draft and write
71
- the guide to
72
- `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
73
- 4. **`api-fetch({domain, operation})`** — execute and verify.
50
+ > 📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold + api-store + oauth-mint available.
74
51
 
75
- Or skip the authoring and **copy a bundled reference recipe** (see
76
- [Bundled Reference Recipes](#bundled-reference-recipes)) into
77
- `~/.pi/agent/pi-lean-host/api-guides/<domain>/` — it loads immediately.
52
+ From a fresh install you have no guides yet, so the next step is to get one:
78
53
 
79
- > **Host-only is a first-class install.** `pi-lean-host` declares
80
- > `pi-lean-portal` as an *optional* peer dependency and has zero static
81
- > imports from it. The core loop — authoring via docs/example, on-demand
82
- > discovery, guided execution — runs with no browser package installed.
83
- > Co-installing portal is planned to unlock two additive features
84
- > (navigate-footer surfacing and probe-authoring via `web-fetch`) in a
85
- > **future release**. Host-side projection code is present but inert
86
- > until portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
54
+ - **Author one** — see [Authoring Your First Guide](#authoring-your-first-guide)
55
+ for the end-to-end workflow, including auth-gated APIs. The complete
56
+ authoring manual (field reference, pagination styles, helper contracts)
57
+ lives in [docs/authoring.md](docs/authoring.md).
58
+ - **Or copy a reference recipe** (see
59
+ [Reference Recipes (caritas)](#reference-recipes-caritas)) into
60
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` — it loads
61
+ immediately.
87
62
 
88
63
  ---
89
64
 
@@ -100,12 +75,13 @@ This kills two whole classes of recurring mistakes before they exist:
100
75
 
101
76
  - **Agents getting the same API wrong every session.** The reason they do is
102
77
  *they are the ones writing the calls.* Move call construction into a
103
- reviewed tool + fixed helpers, and the agent never touches the auth
104
- header, never hand-rolls pagination, never picks the wrong `Accept`.
105
- - **Arbitrary eval / egress safety.** Executable TS in a guide is a sandbox
106
- problem. Declarative recipes executed by a fixed tool are not — and because
107
- bundled recipes are inert, the only code that ever runs is code you
108
- explicitly placed in your own directory.
78
+ reviewed tool + fixed helpers, and those mistakes disappear at the source.
79
+ - **Arbitrary eval / egress safety (default path).** Declarative recipes
80
+ run no agent-authored code, and bundled recipes are inert. The exception is
81
+ local helpers: in `/api learn` the agent can write `helper.ts` to your
82
+ guides directory. These run in-process with the agent's privileges. Since
83
+ the agent already has shell access, this isn't a privilege escalation,
84
+ but it introduces persistent code.
109
85
 
110
86
  ### Why not just a skill?
111
87
 
@@ -127,45 +103,29 @@ demand. A skill is pure text with no in-process eval, whereas a loaded
127
103
  | Tier | Where it lives | Who writes it | Ships in tarball? | Trust |
128
104
  |------|----------------|---------------|-------------------|-------|
129
105
  | 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 |
131
- | Bundled recipes | `caritas` repo (`api-guides/<domain>/`) | maintainers | no (reference) | **inert — never auto-executed** |
106
+ | Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
107
+ | Bundled recipes | `caritas` repo (`api-guides/<slug(shortName)>/`) | maintainers | no (see [Reference Recipes](#reference-recipes-caritas)) | **inert: never auto-executed** |
132
108
 
133
109
  Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
134
- (computed signatures, strange date transforms, custom auth). Bundled recipes
135
- are inert reference material in the [`caritas`](https://github.com/coreyryanhanson/caritas)
136
- repo — the loader never reads `api-guides/` from the package. You adopt one by
137
- copying the whole domain folder into your own directory; only then does it
138
- load and execute.
110
+ (computed signatures, strange date transforms, custom auth).
139
111
 
140
112
  ---
141
113
 
142
114
  ## `/api` Command — API Toggle
143
115
 
144
- `/api` is an **independent peer** of `/web`, not a child. They compose
145
- freely: each owns its own tool set and its own status-bar slot, and neither
146
- touches the other's tools.
147
-
148
116
  | Command | Effect |
149
117
  |---------|--------|
150
118
  | `/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. |
119
+ | `/api learn` | **API access + authoring** — adds `api-learn` + `api-probe` + `api-scaffold` + `api-store` + `oauth-mint` on top of `on`. The agent never authors guides unprompted — it must be in learn mode. |
152
120
  | `/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
121
  | `/api` | Show current state and available sub-commands. |
154
- | `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
122
+ | `/api status` | Detailed runtime status — toggle state, active guide count, domain list, and helper health (disabled helpers surface with a `⚠`). |
155
123
  | `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
156
124
  | `/api secrets [<domain> [<name>]]` | Manage stored API secrets — list, provision, delete (see [Authentication & Secrets](#authentication--secrets)). |
157
- | `/api verify <domain> [guide] [--force]` | Run every runnable op against the live API and stamp `verified` on success — strict: any runnable-op failure → no stamp; skipped ops named in the report (see [Recipe drift](#recipe-drift)). |
125
+ | `/api verify <domain> [guide] [--force]` | Run every runnable op against the live API and stamp `verified` on success — strict: any runnable-op failure → no stamp; skipped ops named in the report (see [Recipe drift](docs/authoring.md#recipe-drift)). |
158
126
  | `/api delete <domain> [guide]` | Remove a guide directory and invalidate the guide-store cache — a human-typed recovery gesture (no agent tool surface); interactive confirm for a whole-domain delete. |
159
-
160
- ### Why a peer toggle?
161
-
162
- The concrete win is **api-only mode**: `/api on` + `/web off` turns off every
163
- `browser-*` tool while keeping structured API access live. That's the workflow
164
- that pays for the machinery — batch structured-data pulls against a known API
165
- (paginating a JSON endpoint to exhaustion, querying a documented read API
166
- across many dates) where the browser tools are pure context noise you want
167
- gone, but API access must stay on. A `/web`-child toggle cannot give you
168
- that — `/web off` would kill both together.
127
+ | `/api oauth <domain> …` | OAuth2 token management — `init` / mint / `--status` / `--refresh` / `--revoke` / `--code <code>` per token slot (human-typed; the agent's mint path is `oauth-mint`). `init` runs an interactive wizard (or headless flags — see `--help` for `--redirect-uri`, which must match the provider app registration) and finishes a paste-based auth-code flow via `/api oauth init <domain> … --code <code>`. |
128
+ | `/api bootstrap oauth <domain> <spec>` | Agent-driven OAuth2 bootstrap — validates args, auto-enables learn when off, injects a research brief into the session, and exits; the agent then researches the provider and calls `oauth-mint` (the human is the trust root for the secret-bearing endpoint). Refused headless. |
169
129
 
170
130
  ### Persistence
171
131
 
@@ -174,7 +134,7 @@ library (`persistKey: toolset-state:pi-lean-dimension.api`), surviving
174
134
  `/reload`, `/resume`, `/fork`, and `/tree` navigation. A fresh conversation
175
135
  starts from the `toolsetDefaults` block in merged Pi settings (see
176
136
  [Configuration](#configuration-settingsjson)), falling back to the packaged
177
- default (`on` for `api`, `off` for `api-learn`).
137
+ defaults.
178
138
 
179
139
  The status bar shows an `api` glyph (independent of the `browser`/`search`
180
140
  slots). It reads `● api` when `/api` is on (colored to reflect learn state)
@@ -182,13 +142,11 @@ and `○ api` when off.
182
142
 
183
143
  ---
184
144
 
185
- ## All 4 Tools
186
-
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`.
145
+ ## All 7 Tools
189
146
 
190
- The four tools split cleanly by side-effect boundary — one each for **local
191
- read**, **network read**, **local write**, and **network read (exploratory)**:
147
+ `pi-lean-host` registers 7 tools. `api-guide` and `api-fetch` are available
148
+ under `/api on`; `api-learn`, `api-probe`, `api-scaffold`, `api-store`, and
149
+ `oauth-mint` are added under `/api learn`.
192
150
 
193
151
  ### 1. `api-guide` — Inspect the Guide Store (local read)
194
152
 
@@ -222,11 +180,16 @@ api-fetch domain="wikipedia.org" operation="searchPages" params={srsearch:"clima
222
180
  - `gatherAll` (optional) — `true` paginates to gather all items up to the
223
181
  guide's `gatherAllMax` ceiling (default `1000`, overridable per-guide and
224
182
  per-op).
183
+ - `fresh` (optional) — `true` bypasses the response cache and forces a full
184
+ network fetch.
225
185
 
226
186
  `api-fetch` resolves every guide claiming `domain`, finds the named
227
- `operation` across them, and executes it against the matching guide (helper
228
- routed by directory name, not the routing `domain`). The agent never sees a
229
- URL, never sees a header, never sees the auth scheme. Output is an inline
187
+ `operation` across them, and executes it against the matching guide.
188
+ Exactly one hit executes; zero hits lists the ops from all matching guides
189
+ (a multi-guide domain — each guide in its own directory — so you can pick);
190
+ an op name appearing in ≥2 guides is an ambiguous collision the guide
191
+ authors must fix (re-author via `api-learn` to rename). The agent never sees an
192
+ unredacted URL, never sees a header value, never sees the auth scheme. Output is an inline
230
193
  preview (~4000 chars) with larger responses spilled to a temp file under
231
194
  `/tmp/pi-lean-host/` (overridable via `PI_HOST_TEMP_DIR`) — `read` it with
232
195
  offset/limit for specific sections.
@@ -239,326 +202,159 @@ one) — turning a failed execute into a discovery moment in one round-trip.
239
202
 
240
203
  ```text
241
204
  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
205
+ api-learn domain="arxiv.org" → fetches an existing guide's raw recipe + siblings into the staged dir
206
+ api-learn domain="arxiv.org" dir="/tmp/pi-lean-host/arxiv.org" → validates + mirror-saves the staged dir to disk
244
207
  ```
245
208
 
246
- - `{domain, new: true}` → a fresh starter template with `domains: [<domain>]`
247
- **staged to `/tmp/pi-lean-host/<domain>/guide.md`**. Only `domains` is real;
248
- the other fields are `<placeholder>` values that **fail closed**, so a
249
- 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.
254
- - Every staged pull (template or fetched recipe) is prepended with the
255
- authoring manual — the field reference + defaults + semantics the author
256
- 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
260
- 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`.
266
-
267
- The working copy is staged at `/tmp/pi-lean-host/<domain>/guide.md` (`/tmp`
268
- 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`.
209
+ The working copy is staged under `/tmp/pi-lean-host/` (`/tmp`
210
+ self-cleans, so drafts don't accumulate; `<domain>/` for starter
211
+ templates (`new: true`), `<slug(shortName)>/` for fetched recipes) —
212
+ a fresh fail-closed starter
213
+ template, an existing guide's raw recipe + siblings for
214
+ direct editing, or a validated mirror-save of the staged dir into
215
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/`. Every staged pull
216
+ is prepended with the authoring manual.
217
+ Full staging, deletion-gate, and slug-collision semantics:
218
+ [docs/authoring.md](docs/authoring.md#the-authoring-tools-in-detail).
271
219
 
272
220
  ### 4. `api-probe` — Discover an Endpoint's Shape (network read, exploratory)
273
221
 
274
- ```text
275
- api-probe apiHost="https://api.github.com" path="/repos/{owner}/{repo}/branches" params={owner:"torvalds", repo:"linux"}
276
- ```
222
+ Agent-driven shape discovery for the authoring loop. Fetches a not-yet-guided
223
+ endpoint over the real transport (same UA, charset, retry, and ETag handling
224
+ as `api-fetch` — the sanctioned way to reach even WAF'd hosts), summarizes the
225
+ JSON shape, and emits a **draft YAML operation block** to paste into a recipe.
226
+ It only **suggests** — it never writes the guide, and a draft still needs
227
+ confirming against the provider's docs (probe surfaces evidence, not
228
+ authority).
277
229
 
278
- Shape-discovery for the authoring loop. Fetches a templated path over the
279
- real transport (same UA, charset, 429-retry, ETag cache as `api-fetch` — the
280
- sanctioned way to reach even WAF'd hosts), summarizes the JSON shape, suggests
281
- `via` / `itemsPath` / pagination style, echoes a representative record id, and
282
- emits a **draft YAML operation block** to paste straight into a recipe. On 404
283
- it walks the `apiHost` version backward (e.g. `/v3` → `/v2` → `/v1`) to recover
284
- an over-claimed version; a draft carries the version prefix that was actually
285
- fetched (disable with `walkVersions=false`). A stale version that still
286
- returns 200 is not detected as old — read the provider's docs to supply the
287
- newest version up front.
288
-
289
- `api-probe` only **suggests** — it never writes the guide. The operation must
290
- still be traceable to your plan source (the API docs or a working curl
291
- example); this tool surfaces evidence, not authority. Requires `/api learn`.
230
+ ### 5. `api-scaffold` — Bootstrap `verify.json` / `helper.ts` (local write)
292
231
 
293
- ---
294
-
295
- ## Guide Recipes (the `recipe` block)
296
-
297
- A guide is one markdown file: YAML frontmatter carries the structured recipe
298
- (the executable contract), and a prose body carries orientation for the
299
- agent (advisory). `api-fetch` reads the recipe slice and executes against it;
300
- `api-guide` reads the detail slice for introspection. **The prose is
301
- advisory, the frontmatter is authoritative.**
302
-
303
- ### File shape
304
-
305
- A `guide.md` opens with a `---`-delimited YAML frontmatter block and
306
- closes it with a second `---`; the prose body follows. An operation can
307
- override the guide-level `pagination` / `responseShape` with its own block
308
- in the frontmatter.
309
-
310
- The fastest way to a first guide is to let the tools draft it:
311
- `api-learn({domain, new: true})` returns a fail-closed starter template,
312
- `api-probe` drafts real op blocks from a live endpoint — fill the
313
- placeholders, then save with `api-learn`. For
314
- **complete worked recipes** (real endpoints, `verified:` provenance,
315
- auth-in-place, helper examples), see the [Caritas](#bundled-reference-recipes)
316
- recipe library and copy a domain folder that matches your target.
317
-
318
- ### Field reference
319
-
320
- | Field | Level | Default | Purpose |
321
- |---|---|---|---|
322
- | `kind` | guide | `"api"` | the guide type; defaults to `"api"` and is omittable. Values like `"web"` are rejected for API guides. |
323
- | `domains` | guide | — | discovery keys (plural bare aliases) |
324
- | `icon` / `shortName` / `updated` | guide | `📖` / filename / today | presentation slice (portal + `api-guide`) |
325
- | `apiHost` | guide | — | execution root: scheme + host + base path; the version prefix lives here |
326
- | `organization` | guide | — | optional org identity (registrable domain); catalog grouping + disambiguation. Recipe-slice only |
327
- | `description` | guide | — | optional one-line summary (≤200 chars); primary disambiguation signal for multi-guide domains |
328
- | `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
329
- | `verified` | guide | creation date | drift signal — **defaulted, not enforced**; stamped on success by `/api verify` |
330
- | `schemaVersion` | guide | `0` (floor) | breaking-change detection — stamped on save by `api-learn`; a stale guide (`< current`) gets a non-blocking `⚠` warning in `api-guide`/`api-fetch`, **never a gate** |
331
- | `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
332
- | `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
333
- | `auth.headers` | guide | — | literal extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) — **literal values only**, never the path for real credentials |
334
- | `auth.secretRefs` | guide | — | `Record<headerName, secretName>` — store-backed header injection (`static-key`) |
335
- | `auth.headerPrefixes` | guide | — | `Record<headerName, prefix>` — prefix prepended to a secretRefs header value, e.g. `Authorization: "Bearer "` (store holds the raw credential) |
336
- | `auth.secretQueryRefs` | guide | — | `Record<paramName, secretName>` — store-backed query-param injection (`static-key`) |
337
- | `auth.requires` | guide | — | secret names the guide hard-requires; absent → `api-fetch` fails closed before the request |
338
- | `auth.optional` | guide | — | secret names used if present, skipped if absent (e.g. GitHub rate-limit token) |
339
- | `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
340
- | `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
341
- | `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
342
- | `responseShape.format` | guide / op | `json` | `json` \| `xml` \| `text` → drives `parseResponse` (`text` is raw passthrough) |
343
- | `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 |
344
- | `operations[].name` | op | — | the `operation` arg `api-fetch` takes |
345
- | `operations[].via` | op | — | executor: `restGet` \| `paginate` |
346
- | `operations[].path` | op | — | relative path; `{token}` = inferred path param (no re-declaration) |
347
- | `operations[].accept` | op | `json` | `json` \| `xml` \| `<any media-type string>` — request-side `Accept` header (distinct from `responseShape.format`) |
348
- | `operations[].params` | op | `{}` | query params; `{ required?, default?, description? }` per key |
349
- | `operations[].dateParams` | op | — | optional `{param: format}` → normalizes ISO dates to `iso8601` \| `yyyymmdd` \| `yyyy-mm-dd` (query params only) |
350
- | `operations[].helper` | op | `false` | `true` runs this domain's local helper for the op |
351
- | `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) |
352
- | `operations[].requiresAnyOf` | op | — | `[param, ...]` — at least one of these params must be supplied (single group per op, v1; members are plain optional params — not `required: true`, not `default`-bearing: both rejected at parse) |
353
- | `operations[].passthrough` | op | `false` | `true` forwards undeclared caller params onto the query string (for open-param APIs) |
354
- | `operations[].parse` | op | inherits `responseShape` | op-level override of format/charset |
355
- | `operations[].pagination` | op | inherits top-level | op-level override of pagination |
356
-
357
- ### Built-in helpers (the fixed executor set)
358
-
359
- Three helpers, for v1. The agent never calls these directly — `api-fetch`
360
- routes each operation through the one its `via` names:
361
-
362
- - **`restGet`** — path templating, query params, Accept negotiation
363
- (JSON/XML), and auth injection for `auth.kind: static-key` guides
364
- (store-backed `secretRefs` / `secretQueryRefs`). See [Authentication &
365
- Secrets](#authentication--secrets).
366
- - **`paginate`** — wraps a list operation. The guide declares the style; the
367
- helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
368
- stop or continue, plus a `gatherAll` flag for the "just get me everything"
369
- case with a hard ceiling.
370
- - **`parseResponse`** — XML→JSON, declared per-endpoint (charset decoding happens in the transport).
371
- Agents mangle encodings constantly; fix it once here.
372
-
373
- `restPost`/mutations are **not** in scope for v1 — the target APIs are
374
- overwhelmingly GET-read.
375
-
376
- ### Recipe drift
377
-
378
- A prose guide degrades gracefully; a declarative recipe with a wrong endpoint
379
- fails **hard**. v1 treats drift as a signal the agent reads, not a gate the
380
- loader enforces:
381
-
382
- - The `verified` frontmatter date records when a guide was last verified
383
- against the live API (defaulted to creation date, **never enforced**). It's
384
- rendered in the guide-detail footer alongside the current date — the agent
385
- reads both and judges. `/api verify <domain>` runs every runnable op
386
- against the live API and stamps `verified` on success (strict: any
387
- runnable-op failure → no stamp; skipped ops named in the report; `--force`
388
- is human-typed only, no agent tool surface).
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)
232
+ ```text
233
+ api-scaffold domain="arxiv.org" verify=true → writes a starter verify.json with "__FILL_ME__" sentinels to /tmp/pi-lean-host/<slug(shortName)>/verify.json
234
+ api-scaffold domain="arxiv.org" helper=true → writes a commented-out helper.ts stub to /tmp/pi-lean-host/<slug(shortName)>/helper.ts
403
235
  ```
404
236
 
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 recipe library (caritas) pressure-tested:
489
-
490
- | Style | What it sends | Key fields |
491
- |-------|---------------|------------|
492
- | `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `base`, `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` |
237
+ Bootstrap tool for the two artifacts the authoring loop needs but that
238
+ `api-learn` can't draft from the recipe alone: a `verify.json` with
239
+ `"__FILL_ME__"` sentinels for every op with unsatisfiable params (sentinels
240
+ skip until you replace them; existing real values merge additively) and a
241
+ commented-out `helper.ts` stub. Both staged to `/tmp` — never the guides
242
+ dir, never overwriting an existing staged sibling. Save the guide **first**,
243
+ then scaffold.
498
244
 
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.
245
+ ### 6. `api-store` — Inspect Both Credential Stores (local read, learn-gated)
503
246
 
504
- `pagination` and `responseShape` are top-level defaults; an individual
505
- operation overrides them with its own block.
506
-
507
- ---
247
+ ```text
248
+ api-store → orphan view: unscoped secret domains + token domains with no guide
249
+ api-store domain="api.github.com" → combined secrets + tokens report for the domain
250
+ ```
508
251
 
509
- ## Response Shapes (`parseResponse`)
252
+ Read-only inspection of **both credential stores in one call** — the
253
+ agent-facing view of `/api secrets` + `/api oauth --status`. The authoring
254
+ question is never "show me tokens" in isolation; it is what credentials exist
255
+ for a domain, what's declared vs provisioned vs minted, what's expired, and
256
+ what needs minting next.
257
+
258
+ - Bare call → the authoring-bootstrap (orphan) view: unscoped secret domains
259
+ and token domains with no guide. Token domains resolve through the same
260
+ store-domain seam minting uses, so an `api.`-subdomain token maps to its
261
+ parent's guides instead of false-positive as guideless.
262
+ - With `domain` (or `apiHost`, resolved the same way) → the combined
263
+ per-domain report: provisioned/declared/gap secret names, token slots
264
+ (issuer, granted scope, expiry, refreshable), and **declared-slot gaps** —
265
+ "guide declares client_credentials via `tokenUrl`: no token minted" — the
266
+ pointer to `oauth-mint` that replaces a trial-and-error 401.
267
+
268
+ Metadata only: `accessToken`/`refreshToken` are dropped at the collection
269
+ boundary and secret values never enter the tool — they can't appear in the
270
+ rendered text **or** the structured `details`. When a token's granted scope
271
+ wasn't echoed by the provider, the requested scopes render with an
272
+ "(assumed)" marker (RFC 6749 §5.1). Mint via `oauth-mint`; refresh/revoke
273
+ stay human-typed (`/api oauth`).
274
+
275
+ ### 7. `oauth-mint` — Human-in-the-Loop OAuth2 Mint (network write, consented)
510
276
 
511
- Agents mangle encodings constantly; `parseResponse` fixes it once. Declared
512
- per-guide (top-level `responseShape`) and overridable per-op (`parse:`):
277
+ ```text
278
+ oauth-mint domain="github.com" grant="authorization_code" tokenUrl="https://github.com/login/oauth/access_token" ... → prompts the human, then mints + stamps the token store
279
+ ```
513
280
 
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 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.
281
+ The learn-gated mint half of the agent-driven OAuth2 bootstrap. The agent
282
+ supplies researched params (grant, token/authorize URLs, scopes, client
283
+ credentials as **store NAMES**); the tool validates fail-closed, prechecks
284
+ the store names, then prompts the human — token-URL confirm (the human is
285
+ the trust root for the secret-bearing endpoint), a ✓/○ scopes checklist,
286
+ and a paste prompt for the redirect URL (which never enters the
287
+ transcript). Any cancel prints the two-call `/api oauth init <domain> …
288
+ --code` escape-hatch hint.
519
289
 
520
290
  ---
521
291
 
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.
292
+ ## Authoring Your First Guide
293
+
294
+ The simplest case — a public API with no auth — end to end:
295
+
296
+ 1. **`/api learn`** — enable the authoring tools.
297
+ 2. **Ask your agent to author a guide** — point it at the API's
298
+ documentation (a saved spec document or an online docs URL) and say
299
+ which endpoints you want. The agent stages a starter template
300
+ (`api-learn({domain, new: true})`), fills in the recipe — `apiHost`,
301
+ one operation to start, no pagination needed for a single flat
302
+ endpoint — and confirms every op block against the spec you supplied.
303
+ For an endpoint that isn't documented, the agent calls `api-probe` on
304
+ the live URL to draft the YAML op block for your review.
305
+ 3. **Review and save** — the agent validates the draft and saves it to
306
+ `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/guide.md`
307
+ (via `api-learn({domain, dir: …})`).
308
+ 4. **Use it** — from now on, just ask your agent for data from that API
309
+ in plain language; it calls `api-fetch`, which discovers the guide by
310
+ domain and handles URL construction, auth, and pagination. Then run
311
+ `/api verify <your-domain>` to check every op against the live API — a
312
+ passing run stamps `verified` on the guide.
313
+
314
+ Auth-gated API? Two additions, both handled before the guide will fetch
315
+ successfully:
316
+
317
+ - **Static key** — you provision the value once via `/api secrets <domain>`;
318
+ the guide declares it by name with `auth.kind: static-key`. See
319
+ [Authentication & Secrets](#authentication--secrets).
320
+ - **OAuth2** — `/api bootstrap oauth <domain> <spec>` injects a research
321
+ brief and the agent drives `oauth-mint`; you confirm the token URL, tick
322
+ the scopes, and paste the redirect URL back. See the `/api bootstrap` row
323
+ in the [command table](#api-command--api-toggle).
324
+
325
+ The complete field reference, pagination styles, and helper contracts live
326
+ in [docs/authoring.md](docs/authoring.md).
540
327
 
541
328
  ---
542
329
 
543
- ## Bundled Reference Recipes
330
+ ## Reference Recipes (caritas)
544
331
 
545
332
  The comprehensive recipe library lives in the
546
333
  [**caritas**](https://github.com/coreyryanhanson/caritas) repo — real,
547
334
  verified recipes spanning the no-auth **and keyed** axes, each with a
548
335
  per-recipe `verified:`-date provenance and the perpetual drift disclaimer.
549
336
  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.
337
+ into your own `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/`
338
+ directory.
339
+
340
+ Host itself ships only a **synthetic axis-guide set** under `api-guides/` —
341
+ minimal coverage fixtures (no `verified:` date, no live endpoints) that keep
342
+ every guide-driven framework axis exercised via mocked transport. They are
343
+ framework fixtures for host's own tests, not recipes for you to copy
344
+ (membership pinned by `__tests__/axis-coverage.test.ts`).
551
345
 
552
346
  The domains caritas covers (a discoverability index, may drift from the live
553
347
  repo):
554
348
 
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
349
+ ```text
350
+ arxiv federal-register mastodon twitch-user
351
+ boletin-oficial-del-estado frost-server-sensorthings musicbrainz usgs-earthquake
352
+ coingecko gbif open-food-facts wayback-availability
353
+ data-gov github open-library wayback-cdx-server
354
+ datos-gob-es gitlab pubmed-e-utilities wikidata
355
+ deutsche-nationalbibliothek inaturalist stripe wikimedia-action
356
+ ecb-data-portal internet-archive telegram-bot-api wikipedia-rest
357
+ etherscan library-of-congress twitch world-bank-indicators
562
358
  ```
563
359
 
564
360
  Several are **keyed** (`auth.kind: static-key`), the spread that exercises
@@ -573,53 +369,12 @@ cp -r /tmp/caritas/api-guides/* ~/.pi/agent/pi-lean-host/api-guides/
573
369
  ```
574
370
 
575
371
  To grab a single domain instead of all of them, copy just its folder
576
- (e.g. `.../api-guides/en.wikipedia.org`).
577
-
578
- Only then does it load and execute. A recipe may carry
579
- `operation.helper: true` plus an accompanying `helper.ts` in its domain
580
- subdir as a worked example — but it stays inert until you copy the folder.
581
- See caritas's `CONTRIBUTING.md` for authoring a recipe.
582
-
583
- ### What host ships instead
584
-
585
- Host itself ships only a **synthetic axis-guide set** under `api-guides/` —
586
- minimal coverage fixtures (no `verified:` date, no live endpoints) that keep
587
- every guide-driven framework axis exercised via mocked transport. They are
588
- framework fixtures for host's own tests, not recipes for you to copy. The
589
- membership is pinned by `__tests__/axis-coverage.test.ts` (which encodes the
590
- axis-set audit matrix).
591
-
592
- ---
593
-
594
- ## `/api status` — Detailed Runtime Status
595
-
596
- ```text
597
- /api status
598
- ```
599
-
600
- ```text
601
- 📡 API status
602
- State: on
603
- Learn: ❌ off
604
-
605
- Guides: 2 active
606
- Domains: en.wikipedia.org, boe.es, www.boe.es
607
- Helpers: 1 present
608
- ⚠ Disabled: boe.es
609
- Run /api helpers to list them.
610
-
611
- /api on enable api-guide + api-fetch
612
- /api learn enable all four tools (adds api-learn + api-probe)
613
- /api off disable all API tools
614
- ```
372
+ (e.g. `.../api-guides/wikipedia-rest`).
615
373
 
616
- Covers toggle state, active guide count, the domain list, and helper health
617
- (disabled helpers surface with a `⚠`). When `pi-lean-portal` and
618
- `pi-lean-search` are also installed, the status bar shows three independent
619
- glyphs: `● idle` (browser), `● searxng` (search), and `● api` (host — when
620
- `/api` is on).
621
-
622
- ---
374
+ A recipe may carry `operation.helper: true` plus an accompanying `helper.ts`
375
+ in its domain subdir as a worked example. See caritas's `CONTRIBUTING.md`
376
+ for contributing a recipe to the library; for authoring one for yourself,
377
+ see [docs/authoring.md](docs/authoring.md).
623
378
 
624
379
  ## Configuration (`settings.json`)
625
380
 
@@ -642,13 +397,13 @@ the toolset's packaged default:
642
397
  ```
643
398
 
644
399
  - Keys are the toolsets' `persistKey` values.
400
+ - Pins do not apply in spawned subagent children (see pi-tool-masking
401
+ 1.3.0's `piToolMasking.childPolicy` for the opt-out).
645
402
  - Omit a key to use the packaged default (`api` defaults `true`; `api-learn`
646
403
  defaults `false`).
647
404
  - The `api-learn` toolset `requires` `api`, so enabling learn cascades api on;
648
405
  disabling api cascades learn off.
649
406
 
650
- ### No other settings keys
651
-
652
407
  There is no `host.*` settings block. The transport layer (per-domain undici
653
408
  `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
654
409
  caching) is configured internally; `apiHost` and operation paths live **in
@@ -660,11 +415,6 @@ the recipe frontmatter**, not in settings. Credentials are **not** stored in
660
415
 
661
416
  ## Co-Installing with `pi-lean-portal`
662
417
 
663
- > **Planned for a future release.** Portal integration is not yet shipped:
664
- > the projection and navigate-footer surfacing described below are what that
665
- > release delivers. Host-side projection code is present but inert until
666
- > portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
667
-
668
418
  Portal is fully optional. When co-installed, host registers a **projection**
669
419
  of its user-authored `ApiGuide`s with portal's guide-source registry at load
670
420
  time — recipe fields stripped, presentation fields kept — so they **surface
@@ -697,30 +447,13 @@ enhancement for co-installs, not a host-only requirement. The on-demand path
697
447
  |-----------------|-----------------|--------------------------|
698
448
  | An API you've guided | Discovering shape before authoring a guide | A one-off unguided fetch against a known URL |
699
449
  | Repeated/paginated pulls | Drafting an op block from a live endpoint | Reading docs to author a recipe |
700
- | You want auth/pagination handled for you | You're in `/api learn` | Host-only with an undocumented API (last resort) |
701
450
 
702
451
  `api-fetch` is the guided path — the guide is the product. It has no
703
452
  ad-hoc bare-fetch mode on purpose: that would recreate the exact mistakes
704
- (hand-rolled auth, no pagination) the tool exists to prevent. The escape
453
+ the tool exists to prevent. The escape
705
454
  hatches are `api-learn` (write a guide, then execute through it) and
706
455
  `web-fetch` (portal) for a one-off.
707
456
 
708
- ### Authoring discipline
709
-
710
- - Keep the prose body concise — it orients the agent; the frontmatter is the
711
- executable contract.
712
- - Cite the source for every operation (docs URL or working example). `api-probe`
713
- surfaces evidence, not authority — confirm the shape against the docs.
714
- - Fill `verified:` when you verify; it's defaulted to today, not enforced.
715
- - Use `description:` when a domain has multiple guides — it's the primary
716
- disambiguation signal.
717
-
718
- ### `gatherAll` ceilings
719
-
720
- A misconfigured `gatherAll` against a 100k-item paginator is a self-DoS. Set
721
- `gatherAllMax` per-guide (or per-op) to the endpoint's real ceiling when you
722
- know it. The global fallback (`1000`) bounds undeclared guides.
723
-
724
457
  ---
725
458
 
726
459
  ## Authentication & Secrets
@@ -736,10 +469,7 @@ injects it in code.
736
469
  The secrets store is **plaintext JSON at rest** — mode `0600`, no encryption.
737
470
  That matches pi's own posture for its credentials (an API key in
738
471
  `settings.json` or the env). The threat this guards against is not another
739
- process reading the file; it's accidental **transcript exfiltration**. You
740
- provision a value once via `/api secrets`, it's written transcript-safely to
741
- the store, and `api-fetch` injects it in code — the agent sees the name, not
742
- the value.
472
+ process reading the file; it's accidental **transcript exfiltration**.
743
473
 
744
474
  That containment is plugin discipline, not a vault. `read`/`cat` on the
745
475
  store file is one tool-call from the agent, which runs with your privileges,
@@ -751,41 +481,16 @@ plugin is GET-only, so a read-only key is always enough for what it does.
751
481
 
752
482
  ### Guide-side: declare the name, never the value
753
483
 
754
- In `guide.md`, set `auth.kind: static-key` and point at store secrets by name.
755
- The value never lives in the guide (a real key committed there would be one
756
- `cat` from the agent's context).
757
-
758
- ```yaml
759
- auth:
760
- kind: static-key
761
- secretRefs:
762
- x-cg-demo-api-key: api_key # headerName: secretName
763
- requires: [api_key] # absent → api-fetch fails closed
764
- # secretQueryRefs: { apikey: api_key } # query-param injection (?key=)
765
- # optional: [api_key] # used if present, skipped if absent
766
- # headerPrefixes: # headerName → prefix for scheme-style headers
767
- # Authorization: "Bearer " # (GitHub/GitLab) — the store holds the
768
- # # RAW token; the guide adds the prefix
769
- ```
484
+ In `guide.md`, set `auth.kind: static-key` and point at store secrets by name
485
+ — the value never lives in the guide (a real key committed there would be one
486
+ `cat` from the agent's context). The full guide-side YAML (`secretRefs` /
487
+ `secretQueryRefs` / `secretPathRefs`, `prefix`, `optional`, and the
488
+ parser-enforced invariants) is documented in
489
+ [docs/authoring.md](docs/authoring.md#static-key-auth-in-the-guide).
770
490
 
771
- - **`auth.secretRefs`** — `Record<headerName, secretName>`: inject the store
772
- value into that request header.
773
- - **`auth.headerPrefixes`** — `Record<headerName, prefix>`: prepend a scheme
774
- prefix to the resolved value for that header (e.g. `Authorization: "Bearer "`).
775
- The store holds the **raw credential**; the guide declares how it is
776
- presented. Absent = verbatim value. Every key must also be a `secretRefs`
777
- header (parser-enforced).
778
- - **`auth.secretQueryRefs`** — `Record<paramName, secretName>`: inject the
779
- store value as that query param.
780
- - **`auth.requires`** — names the guide **hard-requires**. If one is absent
781
- from the store, `api-fetch` **fails closed before the request** — no silent
782
- unauthenticated fetch that could return partial data the agent mistakes for
783
- complete.
784
- - **`auth.optional`** — names usable-if-present. Absent → `api-fetch` proceeds
785
- unauthenticated (e.g. GitHub: 60 req/hr unauth, 5000 with a token); present
786
- → injected like a required secret.
787
- - **`auth.headers`** stays **literal-only** (demo keys, committed rate-limit
788
- tokens) — it is not the path for real credentials.
491
+ Migrating a guide from the old flat shape (`requires`/`optional` rosters,
492
+ `headerPrefixes` map, bare-string refs)? See
493
+ [docs/migration-v1.md](docs/migration-v1.md).
789
494
 
790
495
  ### Provisioning
791
496
 
@@ -800,28 +505,18 @@ auth:
800
505
  Provisioning is interactive (`ctx.ui` dialogs — the value is captured
801
506
  **transcript-safely** and written straight to the store, never returned). On
802
507
  headless hosts there is no dialog, so `/api secrets` prints the direct
803
- file-write instructions instead — write the `0600` file yourself before pi
804
- starts (a one-line `install -m 600` + `cat >` step).
805
-
806
- Secrets persist at `~/.pi/agent/pi-lean-host/secrets/<domain>.json` (mode
807
- `0600`). **Only names are ever listed** — values never leave the store.
508
+ file-write instructions instead — write a `{ "<name>": "<value>" }` JSON
509
+ mapping into the `0600` `<domain>.json` file yourself before pi starts. Secrets persist at
510
+ `~/.pi/agent/pi-lean-host/secrets/<domain>.json` (mode `0600`).
808
511
 
809
512
  ### The status footer
810
513
 
811
- Every `api-guide` / `api-fetch` result on an auth-bearing guide (`secretRefs`
812
- or `secretQueryRefs`) ends with a `🔑 auth:` line — `ok`, `requires <name>
813
- — not provisioned`, or an optional state — showing name and presence only,
814
- never the value, so it's safe anywhere it renders.
815
-
816
- ### Authoring keyed guides
817
-
818
- `api-probe` accepts an inline `auth` block (injection fields only) plus a
819
- `domain` selector, so you can prove a keyed shape before writing the guide —
820
- a store miss reports the name and fetches unauthenticated (authoring is
821
- human-in-the-loop, not fail-closed). A learn-gated `listSecrets: true` mode
822
- lists provisioned secret names (names only) to close the authoring bootstrap
823
- gap; a bare `listSecrets` call (no `domain`, no `apiHost`) lists
824
- provisioned-but-guideless store domains first.
514
+ Every `api-guide` / `api-fetch` result on an auth-bearing guide (static-key
515
+ `secretRefs`/`secretQueryRefs`/`secretPathRefs`, or an `oauth2` token slot)
516
+ ends with a
517
+ `🔑 auth:` line — `ok`, `requires <name> — not provisioned`, or an optional
518
+ state — showing name and presence only, never the value, so it's safe
519
+ anywhere it renders.
825
520
 
826
521
  ## Security & Scope
827
522
 
@@ -850,15 +545,10 @@ channel stays closed.
850
545
  - **GET-read only.** No mutation helper. Add one only when a real *retrieval*
851
546
  guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
852
547
  gate.
853
- - **Static-key auth only.** `auth.kind: static-key` is realized (store-backed
854
- header/query-param secrets, `requires`/`optional`); `oauth2` and cookie-login
855
- stay deferred. Values live in the `0600` secrets store, never in a guide —
856
- see [Authentication & Secrets](#authentication--secrets).
857
- - **Bundled recipes are inert.** Nothing the package ships executes until you
858
- place it in `~/.pi/agent/pi-lean-host/` and opt in.
859
- - **No inferred-link discovery.** Declared links only in v1; inference is v2.
860
- - **No guide suppression.** Both guide kinds surface by domain match when
861
- their toggle is on; host-first is a preference, not suppression.
548
+ - **GET-read auth surface.** `auth.kind: static-key` (store-backed
549
+ header/query-param secrets) and `auth.kind: oauth2` (`client_credentials`
550
+ - paste-based `authorization_code`) are realized; cookie-login stays
551
+ deferred. See [Authentication & Secrets](#authentication--secrets).
862
552
 
863
553
  ### Mission
864
554
 
@@ -874,8 +564,6 @@ machine; the package does not aim to make that easy.
874
564
 
875
565
  > `pi-lean-host` is part of the
876
566
  > [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
877
- > web-tools suite. For the security model behind the secrets store (the
878
- > two-threat model and the output-channel audit), see
879
- > [Authentication & Secrets](#authentication--secrets).
567
+ > web-tools suite.
880
568
  >
881
569
  > License: AGPL-3.0-only