pi-lean-host 0.4.0 → 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,23 +20,6 @@
20
20
  > SearXNG search, install
21
21
  > [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
22
22
 
23
- > ⚠️ **Breaking change in 0.4.0 — guide folders are now keyed by `shortName`.**
24
- > Each guide must live in a folder named `slug(shortName)` — its `shortName`
25
- > lowercased, with non-alphanumeric runs replaced by `-` (e.g. `shortName:
26
- > BOE` → folder `boe`). Guides still sitting in a `<domain>/` folder from 0.3.x
27
- > are flagged **malformed** and won't load until you rename the folder to
28
- > `slug(shortName)` and `/reload` — the startup warnings give the exact `mv`
29
- > command. Hand the warnings to the agent; it will fix them for you.
30
-
31
- <!-- TODO(0.5.0): remove this temporary breaking-change note once the 0.4.0 migration is settled. -->
32
-
33
- > ⚠️ **Early release (0.4.0).** The API tools here work today, but this is a
34
- > development preview. The recipe schema, tool surfaces, and guide format are
35
- > still settling as we test more APIs to finalize the shape — **future
36
- > compatibility is not guaranteed** until the package reaches lockstep with
37
- > `pi-lean-dimension` 0.5.0. Guides authored against 0.3.x may need revision
38
- > as the schema firms up.
39
-
40
23
  ---
41
24
 
42
25
  ## Table of Contents
@@ -44,20 +27,14 @@
44
27
  1. [Quick Start](#quick-start)
45
28
  2. [The Big Idea: Recipes, Not a Runtime](#the-big-idea-recipes-not-a-runtime)
46
29
  3. [`/api` Command — API Toggle](#api-command--api-toggle)
47
- 4. [All 5 Tools](#all-5-tools)
48
- 5. [Guide Recipes (the `recipe` block)](#guide-recipes-the-recipe-block)
49
- 6. [Authoring a Guide](#authoring-a-guide)
50
- 7. [Local User Helpers](#local-user-helpers)
51
- 8. [Pagination Styles](#pagination-styles)
52
- 9. [Response Shapes (`parseResponse`)](#response-shapes-parseresponse)
53
- 10. [Multi-Recipe Domains](#multi-recipe-domains)
54
- 11. [Bundled Reference Recipes](#bundled-reference-recipes)
55
- 12. [`/api status` — Detailed Runtime Status](#api-status--detailed-runtime-status)
56
- 13. [Configuration (`settings.json`)](#configuration-settingsjson)
57
- 14. [Co-Installing with `pi-lean-portal`](#co-installing-with-pi-lean-portal)
58
- 15. [Authentication & Secrets](#authentication--secrets)
59
- 16. [Tips & Best Practices](#tips--best-practices)
60
- 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)
61
38
 
62
39
  ---
63
40
 
@@ -70,33 +47,18 @@ pi install npm:pi-lean-host
70
47
  No browser binaries, no server, no setup wizard. The host tools are **enabled
71
48
  by default** — you'll see:
72
49
 
73
- > 📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold available.
74
-
75
- From a fresh install you have no guides yet, so the workflow is:
76
-
77
- 1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe` +
78
- `api-scaffold`).
79
- 2. **`api-probe({apiHost, path})`** — discover the shape of a not-yet-guided
80
- endpoint; it drafts a YAML operation block to paste into a recipe.
81
- 3. **`api-learn({domain, dir})`** — validate the staged draft(s) and write
82
- the guide to
83
- `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/guide.md`.
84
- 4. **`api-fetch({domain, operation})`** — execute and verify.
85
-
86
- Or skip the authoring and **copy a bundled reference recipe** (see
87
- [Bundled Reference Recipes](#bundled-reference-recipes)) into
88
- `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` — it loads
89
- immediately. The folder name must match `slug(shortName)` (see the
90
- 0.4.0 breaking-change note above).
91
-
92
- > **Host-only is a first-class install.** `pi-lean-host` declares
93
- > `pi-lean-portal` as an *optional* peer dependency and has zero static
94
- > imports from it. The core loop — authoring via docs/example, on-demand
95
- > discovery, guided execution — runs with no browser package installed.
96
- > Co-installing portal is planned to unlock two additive features
97
- > (navigate-footer surfacing and probe-authoring via `web-fetch`) in a
98
- > **future release**. Host-side projection code is present but inert
99
- > until portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
50
+ > 📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold + api-store + oauth-mint available.
51
+
52
+ From a fresh install you have no guides yet, so the next step is to get one:
53
+
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.
100
62
 
101
63
  ---
102
64
 
@@ -113,12 +75,13 @@ This kills two whole classes of recurring mistakes before they exist:
113
75
 
114
76
  - **Agents getting the same API wrong every session.** The reason they do is
115
77
  *they are the ones writing the calls.* Move call construction into a
116
- reviewed tool + fixed helpers, and the agent never touches the auth
117
- header, never hand-rolls pagination, never picks the wrong `Accept`.
118
- - **Arbitrary eval / egress safety.** Executable TS in a guide is a sandbox
119
- problem. Declarative recipes executed by a fixed tool are not — and because
120
- bundled recipes are inert, the only code that ever runs is code you
121
- 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.
122
85
 
123
86
  ### Why not just a skill?
124
87
 
@@ -141,44 +104,28 @@ demand. A skill is pure text with no in-process eval, whereas a loaded
141
104
  |------|----------------|---------------|-------------------|-------|
142
105
  | Built-in helpers | package source (`core/`) | maintainers | yes | reviewed |
143
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 |
144
- | Bundled recipes | `caritas` repo (`api-guides/<domain>/`) | maintainers | no (reference) | **inert — never auto-executed** |
107
+ | Bundled recipes | `caritas` repo (`api-guides/<slug(shortName)>/`) | maintainers | no (see [Reference Recipes](#reference-recipes-caritas)) | **inert: never auto-executed** |
145
108
 
146
109
  Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
147
- (computed signatures, strange date transforms, custom auth). Bundled recipes
148
- are inert reference material in the [`caritas`](https://github.com/coreyryanhanson/caritas)
149
- repo — the loader never reads `api-guides/` from the package. You adopt one by
150
- copying the whole domain folder into your own directory; only then does it
151
- load and execute.
110
+ (computed signatures, strange date transforms, custom auth).
152
111
 
153
112
  ---
154
113
 
155
114
  ## `/api` Command — API Toggle
156
115
 
157
- `/api` is an **independent peer** of `/web`, not a child. They compose
158
- freely: each owns its own tool set and its own status-bar slot, and neither
159
- touches the other's tools.
160
-
161
116
  | Command | Effect |
162
117
  |---------|--------|
163
118
  | `/api on` | **API access** — `api-guide` + `api-fetch` available. Authoring tools hidden. (Default for new sessions.) |
164
- | `/api learn` | **API access + authoring** — adds `api-learn` + `api-probe` + `api-scaffold` on top of `on`. The agent never authors guides unprompted — it must be in learn mode. |
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. |
165
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. |
166
121
  | `/api` | Show current state and available sub-commands. |
167
- | `/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 `⚠`). |
168
123
  | `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
169
124
  | `/api secrets [<domain> [<name>]]` | Manage stored API secrets — list, provision, delete (see [Authentication & Secrets](#authentication--secrets)). |
170
- | `/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)). |
171
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. |
172
-
173
- ### Why a peer toggle?
174
-
175
- The concrete win is **api-only mode**: `/api on` + `/web off` turns off every
176
- `browser-*` tool while keeping structured API access live. That's the workflow
177
- that pays for the machinery — batch structured-data pulls against a known API
178
- (paginating a JSON endpoint to exhaustion, querying a documented read API
179
- across many dates) where the browser tools are pure context noise you want
180
- gone, but API access must stay on. A `/web`-child toggle cannot give you
181
- 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. |
182
129
 
183
130
  ### Persistence
184
131
 
@@ -187,7 +134,7 @@ library (`persistKey: toolset-state:pi-lean-dimension.api`), surviving
187
134
  `/reload`, `/resume`, `/fork`, and `/tree` navigation. A fresh conversation
188
135
  starts from the `toolsetDefaults` block in merged Pi settings (see
189
136
  [Configuration](#configuration-settingsjson)), falling back to the packaged
190
- default (`on` for `api`, `off` for `api-learn`).
137
+ defaults.
191
138
 
192
139
  The status bar shows an `api` glyph (independent of the `browser`/`search`
193
140
  slots). It reads `● api` when `/api` is on (colored to reflect learn state)
@@ -195,15 +142,11 @@ and `○ api` when off.
195
142
 
196
143
  ---
197
144
 
198
- ## All 5 Tools
199
-
200
- `pi-lean-host` registers 5 tools. `api-guide` and `api-fetch` are available
201
- under `/api on`; `api-learn`, `api-probe`, and `api-scaffold` are added under
202
- `/api learn`.
145
+ ## All 7 Tools
203
146
 
204
- The five tools split cleanly by side-effect boundary — one each for **local
205
- read**, **network read**, **local write**, **network read (exploratory)**, and
206
- **local write (bootstrap)**:
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`.
207
150
 
208
151
  ### 1. `api-guide` — Inspect the Guide Store (local read)
209
152
 
@@ -237,11 +180,16 @@ api-fetch domain="wikipedia.org" operation="searchPages" params={srsearch:"clima
237
180
  - `gatherAll` (optional) — `true` paginates to gather all items up to the
238
181
  guide's `gatherAllMax` ceiling (default `1000`, overridable per-guide and
239
182
  per-op).
183
+ - `fresh` (optional) — `true` bypasses the response cache and forces a full
184
+ network fetch.
240
185
 
241
186
  `api-fetch` resolves every guide claiming `domain`, finds the named
242
- `operation` across them, and executes it against the matching guide (helper
243
- routed by directory name, not the routing `domain`). The agent never sees a
244
- 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
245
193
  preview (~4000 chars) with larger responses spilled to a temp file under
246
194
  `/tmp/pi-lean-host/` (overridable via `PI_HOST_TEMP_DIR`) — `read` it with
247
195
  offset/limit for specific sections.
@@ -258,338 +206,128 @@ api-learn domain="arxiv.org" → fetches an existing guide's
258
206
  api-learn domain="arxiv.org" dir="/tmp/pi-lean-host/arxiv.org" → validates + mirror-saves the staged dir to disk
259
207
  ```
260
208
 
261
- - `{domain, new: true}` → a fresh starter template with `domains: [<domain>]`
262
- **staged to `/tmp/pi-lean-host/<domain>/guide.md`**. Only `domains` is real;
263
- the other fields are `<placeholder>` values that **fail closed**, so a
264
- pasted template cannot save until you fill it in.
265
- - `{domain}` (no `dir`) → fetch the current raw recipe of an existing guide
266
- **and its present siblings** (`helper.ts`, `verify.json`) into the staged
267
- dir (surfacing the guide's `dirName` so you know which folder it lives in);
268
- a disambiguation menu if several guides claim the domain.
269
- - Every staged pull (template or fetched recipe) is prepended with the
270
- authoring manual — the field reference + defaults + semantics the author
271
- needs at the moment of authoring.
272
- - `{domain, dir}` → reads every staged file, validates the guide **before**
273
- touching disk, then **mirror-saves** the staged dir to
274
- `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` — the folder is
275
- derived from the guide's own `shortName`, not the `domain` arg, so a
276
- re-save naturally lands back in the same folder. Present staged files
277
- overwrite their guides-dir counterparts; a sibling present in the guides dir
278
- but absent from the staged dir would be deleted, so save **refuses and
279
- names the doomed files** until you re-call with `confirmDeletions: true`
280
- (that flag is discovered only via the refusal message). A fail-closed
281
- guard refuses to overwrite an existing `guide.md` whose `shortName`
282
- differs from the incoming guide — a slug collision (two shortNames that
283
- slug to the same folder, e.g. `cmc_full` / `cmc-full`); a same-`shortName`
284
- save is a legitimate update. On a structural error it names the field, the
285
- expected shape, and what was found — the file on disk is left untouched (no
286
- half-written guide). Requires `/api learn`.
287
-
288
- The working copy is staged at `/tmp/pi-lean-host/<domain>/` (`/tmp`
289
- self-cleans, so drafts don't accumulate) — fetch/template calls write the
290
- draft there and you edit that file between saves; saving reads the staged dir
291
- and publishes to the guides dir. No session-held state, no `/api save`.
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).
292
219
 
293
220
  ### 4. `api-probe` — Discover an Endpoint's Shape (network read, exploratory)
294
221
 
295
- ```text
296
- api-probe apiHost="https://api.github.com" path="/repos/{owner}/{repo}/branches" params={owner:"torvalds", repo:"linux"}
297
- ```
298
-
299
- Shape-discovery for the authoring loop. Fetches a templated path over the
300
- real transport (same UA, charset, 429-retry, ETag cache as `api-fetch` — the
301
- sanctioned way to reach even WAF'd hosts), summarizes the JSON shape, suggests
302
- `via` / `itemsPath` / pagination style, echoes a representative record id, and
303
- emits a **draft YAML operation block** to paste straight into a recipe. On 404
304
- it walks the `apiHost` version backward (e.g. `/v3` → `/v2` → `/v1`) to recover
305
- an over-claimed version; a draft carries the version prefix that was actually
306
- fetched (disable with `walkVersions=false`). A stale version that still
307
- returns 200 is not detected as old — read the provider's docs to supply the
308
- newest version up front.
309
-
310
- `api-probe` only **suggests** — it never writes the guide. The operation must
311
- still be traceable to your plan source (the API docs or a working curl
312
- example); this tool surfaces evidence, not authority. Requires `/api learn`.
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).
313
229
 
314
230
  ### 5. `api-scaffold` — Bootstrap `verify.json` / `helper.ts` (local write)
315
231
 
316
232
  ```text
317
- api-scaffold domain="arxiv.org" verify=true → writes a starter verify.json with "__FILL_ME__" sentinels to /tmp/pi-lean-host/arxiv.org/verify.json
318
- api-scaffold domain="arxiv.org" helper=true → writes a commented-out helper.ts stub to /tmp/pi-lean-host/arxiv.org/helper.ts
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
319
235
  ```
320
236
 
321
237
  Bootstrap tool for the two artifacts the authoring loop needs but that
322
- `api-learn` can't draft from the recipe alone:
323
-
324
- - `{domain, verify: true}` → for every op with unsatisfiable params (path
325
- `{token}`, required query with no default, `requiresAnyOf` group), writes
326
- `{ "<opName>": { "<param>": "__FILL_ME__" } }` to the staged
327
- `/tmp/pi-lean-host/<slug(shortName)>/verify.json`. `"__FILL_ME__"` is a
328
- sentinel: treated as unsupplied, so the op skips until you replace it. If a
329
- `verify.json` exists in the guides dir, its real values are **additively
330
- merged** (preserved; sentinels added only for newly-unsatisfiable params).
331
- - `{domain, helper: true}` → writes a commented-out `helper.ts` stub (both
332
- `default` and `transform` exports, with doc comments) to the same staged
333
- dir.
334
- - At least one of `verify`/`helper` must be `true`. The tool **never
335
- overwrites** an existing staged sibling — delete it from `/tmp` first, then
336
- re-call. Staging is keyed by `slug(shortName)` (same pattern as
337
- `api-learn`), so a scaffolded `verify.json`/`helper.ts` lands in the same
338
- dir `api-learn` saves from. Save the guide **first**, then scaffold —
339
- `api-scaffold` reads the saved guide. Requires `/api learn`.
340
-
341
- ---
342
-
343
- ## Guide Recipes (the `recipe` block)
344
-
345
- A guide is one markdown file: YAML frontmatter carries the structured recipe
346
- (the executable contract), and a prose body carries orientation for the
347
- agent (advisory). `api-fetch` reads the recipe slice and executes against it;
348
- `api-guide` reads the detail slice for introspection. **The prose is
349
- advisory, the frontmatter is authoritative.**
350
-
351
- ### File shape
352
-
353
- A `guide.md` opens with a `---`-delimited YAML frontmatter block and
354
- closes it with a second `---`; the prose body follows. An operation can
355
- override the guide-level `pagination` / `responseShape` with its own block
356
- in the frontmatter.
357
-
358
- The fastest way to a first guide is to let the tools draft it:
359
- `api-learn({domain, new: true})` returns a fail-closed starter template,
360
- `api-probe` drafts real op blocks from a live endpoint — fill the
361
- placeholders, then save with `api-learn`. For
362
- **complete worked recipes** (real endpoints, `verified:` provenance,
363
- auth-in-place, helper examples), see the [Caritas](#bundled-reference-recipes)
364
- recipe library and copy a domain folder that matches your target.
365
-
366
- ### Field reference
367
-
368
- | Field | Level | Default | Purpose |
369
- |---|---|---|---|
370
- | `kind` | guide | `"api"` | the guide type; defaults to `"api"` and is omittable. Values like `"web"` are rejected for API guides. |
371
- | `domains` | guide | — | discovery keys (plural bare aliases) |
372
- | `icon` / `shortName` / `updated` | guide | `📖` / filename / today | presentation slice (portal + `api-guide`) |
373
- | `apiHost` | guide | — | execution root: scheme + host + base path; the version prefix lives here |
374
- | `organization` | guide | — | optional org identity (registrable domain); catalog grouping + disambiguation. Recipe-slice only |
375
- | `description` | guide | — | optional one-line summary (≤200 chars); primary disambiguation signal for multi-guide domains |
376
- | `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
377
- | `verified` | guide | creation date | drift signal — **defaulted, not enforced**; stamped on success by `/api verify` |
378
- | `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** |
379
- | `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
380
- | `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
381
- | `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 |
382
- | `auth.secretRefs` | guide | — | `Record<headerName, secretName>` — store-backed header injection (`static-key`) |
383
- | `auth.headerPrefixes` | guide | — | `Record<headerName, prefix>` — prefix prepended to a secretRefs header value, e.g. `Authorization: "Bearer "` (store holds the raw credential) |
384
- | `auth.secretQueryRefs` | guide | — | `Record<paramName, secretName>` — store-backed query-param injection (`static-key`) |
385
- | `auth.requires` | guide | — | secret names the guide hard-requires; absent → `api-fetch` fails closed before the request |
386
- | `auth.optional` | guide | — | secret names used if present, skipped if absent (e.g. GitHub rate-limit token) |
387
- | `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
388
- | `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
389
- | `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
390
- | `responseShape.format` | guide / op | `json` | `json` \| `xml` \| `text` → drives `parseResponse` (`text` is raw passthrough) |
391
- | `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 |
392
- | `operations[].name` | op | — | the `operation` arg `api-fetch` takes |
393
- | `operations[].via` | op | — | executor: `restGet` \| `paginate` |
394
- | `operations[].path` | op | — | relative path; `{token}` = inferred path param (no re-declaration) |
395
- | `operations[].accept` | op | `json` | `json` \| `xml` \| `<any media-type string>` — request-side `Accept` header (distinct from `responseShape.format`) |
396
- | `operations[].params` | op | `{}` | query params; `{ required?, default?, description? }` per key |
397
- | `operations[].dateParams` | op | — | optional `{param: format}` → normalizes ISO dates to `iso8601` \| `yyyymmdd` \| `yyyy-mm-dd` (query params only) |
398
- | `operations[].helper` | op | `false` | `true` runs this domain's local helper for the op |
399
- | `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) |
400
- | `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) |
401
- | `operations[].passthrough` | op | `false` | `true` forwards undeclared caller params onto the query string (for open-param APIs) |
402
- | `operations[].parse` | op | inherits `responseShape` | op-level override of format/charset |
403
- | `operations[].pagination` | op | inherits top-level | op-level override of pagination |
404
-
405
- ### Built-in helpers (the fixed executor set)
406
-
407
- Three helpers, for v1. The agent never calls these directly — `api-fetch`
408
- routes each operation through the one its `via` names:
409
-
410
- - **`restGet`** — path templating, query params, Accept negotiation
411
- (JSON/XML), and auth injection for `auth.kind: static-key` guides
412
- (store-backed `secretRefs` / `secretQueryRefs`). See [Authentication &
413
- Secrets](#authentication--secrets).
414
- - **`paginate`** — wraps a list operation. The guide declares the style; the
415
- helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
416
- stop or continue, plus a `gatherAll` flag for the "just get me everything"
417
- case with a hard ceiling.
418
- - **`parseResponse`** — XML→JSON, declared per-endpoint (charset decoding happens in the transport).
419
- Agents mangle encodings constantly; fix it once here.
420
-
421
- `restPost`/mutations are **not** in scope for v1 — the target APIs are
422
- overwhelmingly GET-read.
423
-
424
- ### Recipe drift
425
-
426
- A prose guide degrades gracefully; a declarative recipe with a wrong endpoint
427
- fails **hard**. v1 treats drift as a signal the agent reads, not a gate the
428
- loader enforces:
429
-
430
- - The `verified` frontmatter date records when a guide was last verified
431
- against the live API (defaulted to creation date, **never enforced**). It's
432
- rendered in the guide-detail footer alongside the current date — the agent
433
- reads both and judges. `/api verify <domain>` runs every runnable op
434
- against the live API and stamps `verified` on success (strict: any
435
- runnable-op failure → no stamp; skipped ops named in the report; `--force`
436
- is human-typed only, no agent tool surface).
437
- - The **live HTTP response is the actual drift signal.** A 401 on a no-auth
438
- guide, a 404 on a pinned path, a changed response shape — the agent reads
439
- those directly. The `verified` date is predictive; the response is actual.
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.
440
244
 
441
- ---
442
-
443
- ## Authoring a Guide
245
+ ### 6. `api-store` — Inspect Both Credential Stores (local read, learn-gated)
444
246
 
445
- The authoring model is **spec-first, probe-second**: read the contract and
446
- encode it, then verify the encoding. The trial-and-error lives at the
447
- *verification* step, not the discovery step. The loop is:
448
-
449
- ```
450
- api-learn (write) → api-fetch (verify) → api-learn (fix) → api-fetch (verify)
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
451
250
  ```
452
251
 
453
- exactly like the browser's `web-learn → browser-navigate → web-learn` loop,
454
- just at the recipe layer. `api-learn`'s return message nudges this
455
- ("guide saved; call `api-fetch(...)` to verify"). A guide on disk that has
456
- been successfully executed against *is* verified.
457
-
458
- ### Authoring paths, prioritized
459
-
460
- 1. **Documentation-driven (primary, works host-only).** Read the API's docs
461
- — via `web-fetch` (portal) or pasted/filepath (host-only) — encode them as
462
- a recipe via `api-learn`, verify with `api-fetch`. The docs *are* the
463
- affordance; this is the natural default.
464
- 2. **Example-generalization (works host-only).** Paste a working curl command
465
- or code sample; the agent generalizes from the one example to a recipe.
466
- A single working call teaches the base URL, the Accept header, the
467
- response shape.
468
- 3. **Probe-and-verify (needs portal, last resort).** Use `api-probe` (or
469
- portal's `web-fetch`) to hit endpoints, read responses, build a candidate
470
- recipe. Possible, but reading the docs is cheaper than probing.
471
- 4. **OpenAPI/Swagger import (deferred).** A spec→recipe transformer is
472
- mechanical when a machine-readable spec exists; build it when a second
473
- guide with a spec arrives.
474
-
475
- **Known limitation — api-only is a known-domains mode.** If your request
476
- doesn't name a domain and no guide in the catalog matches, the agent can't
477
- discover a brand-new API from scratch in api-only mode. That requires web
478
- tools (to search/browse and find the API) or you supplying the domain. It's
479
- an inherent trade-off of a clean api-only context, not a design flaw.
480
-
481
- ---
482
-
483
- ## Local User Helpers
484
-
485
- For sites that need a computed signature, a strange date transform, or a
486
- custom auth flow a declarative recipe can't express — one local user helper
487
- per guide:
488
-
489
- - **Location:** `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/helper.ts`
490
- (alongside the guide's `guide.md`).
491
- - **Authoring gate:** `/api learn` (the explicit opt-in, mirroring `/web
492
- learn`). **Execution gate:** `/api on` only — a persisted helper runs on
493
- later sessions whenever a guide references it, even outside learn mode.
494
- - **Pre-call contract:** `(params, ctx) => params | Promise<params>` — a
495
- transform that receives the resolved param map (path + query merged,
496
- defaults filled) and returns the final map the executor templates and sends.
497
- - **Post-response transform (gated):** an optional `transform(data, ctx)`
498
- *named export* from the same `helper.ts`, run when an op declares
499
- `transform: true`. Graceful by contract — a throw is caught per-call and
500
- the agent gets the raw untransformed data with a warning, never a disabled
501
- op. Cannot inspect response headers.
502
-
503
- ### Safety model
504
-
505
- Local helpers run **in-process** via `import()` with the agent's privileges —
506
- no process boundary. This is a deliberately new isolation profile in the
507
- codebase: stealth backends run as out-of-process Python subprocesses (a crash
508
- is caught; pi keeps running), whereas local helpers load in-process. The
509
- mitigations:
510
-
511
- - A load/call guard wraps both `import()` and each call in `try/catch`. Any
512
- in-frame throw (syntax error, missing dep, throw during execution) rejects
513
- the promise — it does **not** crash pi. On failure the helper is marked
514
- disabled for the session and surfaced via `/api status` (and the status-bar
515
- glyph). pi keeps running; only that one helper is dead until you fix it and
516
- reload.
517
- - The one case the guard **cannot** catch is a helper that registers a
518
- *background* callback (`setTimeout`, `setInterval`, `process.on(...)`) and
519
- throws from it later — that escapes the call frame as an
520
- `uncaughtException` and can take pi down. **The helper-author rule:
521
- synchronous-pure or fully awaited, no background work.** That covers every
522
- realistic v1 helper (format a query string, sign a header, compute a date).
523
- If a real keyed guide ever needs background work, isolation (worker thread
524
- or subprocess) gets revisited then.
525
- - A persisted helper can make arbitrary network calls on later sessions. The
526
- mitigation is user ownership and review, not a sandbox.
527
-
528
- View helpers with `/api helpers` (list) or `/api helpers <domain>` (source).
529
- Authoring: scaffold a starter `helper.ts` stub via `api-scaffold({domain, helper: true})` (writes to the staged `/tmp` dir — never the guides dir), uncomment the export you need, then save via `api-learn({domain, dir})`. Edit a staged helper the same way; avoid hand-editing the file in the guides dir directly.
530
-
531
- ---
532
-
533
- ## Pagination Styles
534
-
535
- `paginate` follows the style declared in the recipe. Six styles cover the
536
- patterns the recipe library (caritas) pressure-tested:
537
-
538
- | Style | What it sends | Key fields |
539
- |-------|---------------|------------|
540
- | `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `base`, `itemsPath` |
541
- | `page` | 1-based page number + page size | same fields as `offset-limit` (semantic difference only) |
542
- | `nextLink` | follows a URL from the response body | `nextLinkPath`, `itemsPath` — the **only** SSRF-guarded path (see [Security](#security--scope)) |
543
- | `cursor` | echoes an opaque cursor query param | `cursorParam`, `cursorPath`, `itemsPath` |
544
- | `resumptionToken` | OAI-PMH opaque single-token cursor | `tokenParam`, `tokenPath`, `itemsPath` |
545
- | `tokenBag` | Wikimedia-style multi-key continuation dict | `continuationParams[]`, `itemsPath` |
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)
546
276
 
547
- `totalCountPath` is optional on any style — a JSON path to the server's
548
- reported total, surfaced as `serverTotal` in the `paginate` result and as
549
- `server total: N` / `remaining: …` in the `api-fetch` footer. Omit it when
550
- the API exposes no total.
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
+ ```
551
280
 
552
- `pagination` and `responseShape` are top-level defaults; an individual
553
- operation overrides them with its own block.
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.
554
289
 
555
290
  ---
556
291
 
557
- ## Response Shapes (`parseResponse`)
558
-
559
- Agents mangle encodings constantly; `parseResponse` fixes it once. Declared
560
- per-guide (top-level `responseShape`) and overridable per-op (`parse:`):
561
-
562
- - `format: json | xml | text` — XML is converted to JSON via `fast-xml-parser`; `text` is raw passthrough.
563
- - `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.
564
- - `accept` (request-side, on each operation) is declared **independently**
565
- from `responseShape.format` (response-side) — they usually match but an API
566
- may return XML regardless of `Accept`, so they're separate fields.
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).
567
327
 
568
328
  ---
569
329
 
570
- ## Multi-Recipe Domains
571
-
572
- A domain may claim **multiple guides** — each in its own directory (e.g.
573
- `internet-archive` + `wayback-availability`, both claiming the `archive.org`
574
- domain). `buildDomainMap` is multi-valued
575
- (`Record<string, string[]>`):
576
-
577
- - `api-guide({domain})` shows a **disambiguation menu** and accepts a `guide`
578
- selector (resolved by `shortName`).
579
- - `api-fetch({domain, operation})` resolves the operation **by name across
580
- all matching guides** — exactly one hit executes (helper routed by the
581
- guide's directory name, not the routing `domain`); zero lists ops from all
582
- matches; an op name appearing in ≥2 guides is an ambiguous collision the
583
- authors must fix (re-author via `api-learn` to rename).
584
-
585
- Optional `organization:` (catalog grouping) and `description:` (≤200 chars,
586
- the primary disambiguation signal) fields help the catalog and menu stay
587
- legible when several guides share a domain. `api-learn` warns on collision so
588
- you know you're in disambiguation territory.
589
-
590
- ---
591
-
592
- ## Bundled Reference Recipes
330
+ ## Reference Recipes (caritas)
593
331
 
594
332
  The comprehensive recipe library lives in the
595
333
  [**caritas**](https://github.com/coreyryanhanson/caritas) repo — real,
@@ -597,19 +335,26 @@ verified recipes spanning the no-auth **and keyed** axes, each with a
597
335
  per-recipe `verified:`-date provenance and the perpetual drift disclaimer.
598
336
  They are inert reference material: nothing executes until you copy a recipe
599
337
  into your own `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/`
600
- directory — the folder name must match `slug(shortName)` or it routes to
601
- **malformed** (see the 0.4.0 breaking-change note above).
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`).
602
345
 
603
346
  The domains caritas covers (a discoverability index, may drift from the live
604
347
  repo):
605
348
 
606
349
  ```text
607
- arxiv ecb-data-portal internet-archive wayback-availability
608
- boletin-oficial-del-estado etherscan library-of-congress wayback-cdx-server
609
- coingecko federal-register musicbrainz wikidata
610
- data-gov gbif open-library wikimedia-action
611
- datos-gob-es github pubmed-e-utilities wikipedia-rest
612
- deutsche-nationalbibliothek gitlab usgs-earthquake
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
613
358
  ```
614
359
 
615
360
  Several are **keyed** (`auth.kind: static-key`), the spread that exercises
@@ -624,53 +369,12 @@ cp -r /tmp/caritas/api-guides/* ~/.pi/agent/pi-lean-host/api-guides/
624
369
  ```
625
370
 
626
371
  To grab a single domain instead of all of them, copy just its folder
627
- (e.g. `.../api-guides/en.wikipedia.org`).
628
-
629
- Only then does it load and execute. A recipe may carry
630
- `operation.helper: true` plus an accompanying `helper.ts` in its domain
631
- subdir as a worked example — but it stays inert until you copy the folder.
632
- See caritas's `CONTRIBUTING.md` for authoring a recipe.
372
+ (e.g. `.../api-guides/wikipedia-rest`).
633
373
 
634
- ### What host ships instead
635
-
636
- Host itself ships only a **synthetic axis-guide set** under `api-guides/` —
637
- minimal coverage fixtures (no `verified:` date, no live endpoints) that keep
638
- every guide-driven framework axis exercised via mocked transport. They are
639
- framework fixtures for host's own tests, not recipes for you to copy. The
640
- membership is pinned by `__tests__/axis-coverage.test.ts` (which encodes the
641
- axis-set audit matrix).
642
-
643
- ---
644
-
645
- ## `/api status` — Detailed Runtime Status
646
-
647
- ```text
648
- /api status
649
- ```
650
-
651
- ```text
652
- 📡 API status
653
- State: on
654
- Learn: ❌ off
655
-
656
- Guides: 2 active
657
- Domains: en.wikipedia.org, boe.es, www.boe.es
658
- Helpers: 1 present
659
- ⚠ Disabled: boe.es
660
- Run /api helpers to list them.
661
-
662
- /api on enable api-guide + api-fetch
663
- /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)
664
- /api off disable all API tools
665
- ```
666
-
667
- Covers toggle state, active guide count, the domain list, and helper health
668
- (disabled helpers surface with a `⚠`). When `pi-lean-portal` and
669
- `pi-lean-search` are also installed, the status bar shows three independent
670
- glyphs: `● idle` (browser), `● searxng` (search), and `● api` (host — when
671
- `/api` is on).
672
-
673
- ---
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).
674
378
 
675
379
  ## Configuration (`settings.json`)
676
380
 
@@ -693,13 +397,13 @@ the toolset's packaged default:
693
397
  ```
694
398
 
695
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).
696
402
  - Omit a key to use the packaged default (`api` defaults `true`; `api-learn`
697
403
  defaults `false`).
698
404
  - The `api-learn` toolset `requires` `api`, so enabling learn cascades api on;
699
405
  disabling api cascades learn off.
700
406
 
701
- ### No other settings keys
702
-
703
407
  There is no `host.*` settings block. The transport layer (per-domain undici
704
408
  `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
705
409
  caching) is configured internally; `apiHost` and operation paths live **in
@@ -711,11 +415,6 @@ the recipe frontmatter**, not in settings. Credentials are **not** stored in
711
415
 
712
416
  ## Co-Installing with `pi-lean-portal`
713
417
 
714
- > **Planned for a future release.** Portal integration is not yet shipped:
715
- > the projection and navigate-footer surfacing described below are what that
716
- > release delivers. Host-side projection code is present but inert until
717
- > portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
718
-
719
418
  Portal is fully optional. When co-installed, host registers a **projection**
720
419
  of its user-authored `ApiGuide`s with portal's guide-source registry at load
721
420
  time — recipe fields stripped, presentation fields kept — so they **surface
@@ -748,30 +447,13 @@ enhancement for co-installs, not a host-only requirement. The on-demand path
748
447
  |-----------------|-----------------|--------------------------|
749
448
  | An API you've guided | Discovering shape before authoring a guide | A one-off unguided fetch against a known URL |
750
449
  | Repeated/paginated pulls | Drafting an op block from a live endpoint | Reading docs to author a recipe |
751
- | You want auth/pagination handled for you | You're in `/api learn` | Host-only with an undocumented API (last resort) |
752
450
 
753
451
  `api-fetch` is the guided path — the guide is the product. It has no
754
452
  ad-hoc bare-fetch mode on purpose: that would recreate the exact mistakes
755
- (hand-rolled auth, no pagination) the tool exists to prevent. The escape
453
+ the tool exists to prevent. The escape
756
454
  hatches are `api-learn` (write a guide, then execute through it) and
757
455
  `web-fetch` (portal) for a one-off.
758
456
 
759
- ### Authoring discipline
760
-
761
- - Keep the prose body concise — it orients the agent; the frontmatter is the
762
- executable contract.
763
- - Cite the source for every operation (docs URL or working example). `api-probe`
764
- surfaces evidence, not authority — confirm the shape against the docs.
765
- - Fill `verified:` when you verify; it's defaulted to today, not enforced.
766
- - Use `description:` when a domain has multiple guides — it's the primary
767
- disambiguation signal.
768
-
769
- ### `gatherAll` ceilings
770
-
771
- A misconfigured `gatherAll` against a 100k-item paginator is a self-DoS. Set
772
- `gatherAllMax` per-guide (or per-op) to the endpoint's real ceiling when you
773
- know it. The global fallback (`1000`) bounds undeclared guides.
774
-
775
457
  ---
776
458
 
777
459
  ## Authentication & Secrets
@@ -787,10 +469,7 @@ injects it in code.
787
469
  The secrets store is **plaintext JSON at rest** — mode `0600`, no encryption.
788
470
  That matches pi's own posture for its credentials (an API key in
789
471
  `settings.json` or the env). The threat this guards against is not another
790
- process reading the file; it's accidental **transcript exfiltration**. You
791
- provision a value once via `/api secrets`, it's written transcript-safely to
792
- the store, and `api-fetch` injects it in code — the agent sees the name, not
793
- the value.
472
+ process reading the file; it's accidental **transcript exfiltration**.
794
473
 
795
474
  That containment is plugin discipline, not a vault. `read`/`cat` on the
796
475
  store file is one tool-call from the agent, which runs with your privileges,
@@ -802,41 +481,16 @@ plugin is GET-only, so a read-only key is always enough for what it does.
802
481
 
803
482
  ### Guide-side: declare the name, never the value
804
483
 
805
- In `guide.md`, set `auth.kind: static-key` and point at store secrets by name.
806
- The value never lives in the guide (a real key committed there would be one
807
- `cat` from the agent's context).
808
-
809
- ```yaml
810
- auth:
811
- kind: static-key
812
- secretRefs:
813
- x-cg-demo-api-key: api_key # headerName: secretName
814
- requires: [api_key] # absent → api-fetch fails closed
815
- # secretQueryRefs: { apikey: api_key } # query-param injection (?key=)
816
- # optional: [api_key] # used if present, skipped if absent
817
- # headerPrefixes: # headerName → prefix for scheme-style headers
818
- # Authorization: "Bearer " # (GitHub/GitLab) — the store holds the
819
- # # RAW token; the guide adds the prefix
820
- ```
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).
821
490
 
822
- - **`auth.secretRefs`** — `Record<headerName, secretName>`: inject the store
823
- value into that request header.
824
- - **`auth.headerPrefixes`** — `Record<headerName, prefix>`: prepend a scheme
825
- prefix to the resolved value for that header (e.g. `Authorization: "Bearer "`).
826
- The store holds the **raw credential**; the guide declares how it is
827
- presented. Absent = verbatim value. Every key must also be a `secretRefs`
828
- header (parser-enforced).
829
- - **`auth.secretQueryRefs`** — `Record<paramName, secretName>`: inject the
830
- store value as that query param.
831
- - **`auth.requires`** — names the guide **hard-requires**. If one is absent
832
- from the store, `api-fetch` **fails closed before the request** — no silent
833
- unauthenticated fetch that could return partial data the agent mistakes for
834
- complete.
835
- - **`auth.optional`** — names usable-if-present. Absent → `api-fetch` proceeds
836
- unauthenticated (e.g. GitHub: 60 req/hr unauth, 5000 with a token); present
837
- → injected like a required secret.
838
- - **`auth.headers`** stays **literal-only** (demo keys, committed rate-limit
839
- 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).
840
494
 
841
495
  ### Provisioning
842
496
 
@@ -851,28 +505,18 @@ auth:
851
505
  Provisioning is interactive (`ctx.ui` dialogs — the value is captured
852
506
  **transcript-safely** and written straight to the store, never returned). On
853
507
  headless hosts there is no dialog, so `/api secrets` prints the direct
854
- file-write instructions instead — write the `0600` file yourself before pi
855
- starts (a one-line `install -m 600` + `cat >` step).
856
-
857
- Secrets persist at `~/.pi/agent/pi-lean-host/secrets/<domain>.json` (mode
858
- `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`).
859
511
 
860
512
  ### The status footer
861
513
 
862
- Every `api-guide` / `api-fetch` result on an auth-bearing guide (`secretRefs`
863
- or `secretQueryRefs`) ends with a `🔑 auth:` line — `ok`, `requires <name>
864
- — not provisioned`, or an optional state — showing name and presence only,
865
- never the value, so it's safe anywhere it renders.
866
-
867
- ### Authoring keyed guides
868
-
869
- `api-probe` accepts an inline `auth` block (injection fields only) plus a
870
- `domain` selector, so you can prove a keyed shape before writing the guide —
871
- a store miss reports the name and fetches unauthenticated (authoring is
872
- human-in-the-loop, not fail-closed). A learn-gated `listSecrets: true` mode
873
- lists provisioned secret names (names only) to close the authoring bootstrap
874
- gap; a bare `listSecrets` call (no `domain`, no `apiHost`) lists
875
- 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.
876
520
 
877
521
  ## Security & Scope
878
522
 
@@ -901,15 +545,10 @@ channel stays closed.
901
545
  - **GET-read only.** No mutation helper. Add one only when a real *retrieval*
902
546
  guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
903
547
  gate.
904
- - **Static-key auth only.** `auth.kind: static-key` is realized (store-backed
905
- header/query-param secrets, `requires`/`optional`); `oauth2` and cookie-login
906
- stay deferred. Values live in the `0600` secrets store, never in a guide —
907
- see [Authentication & Secrets](#authentication--secrets).
908
- - **Bundled recipes are inert.** Nothing the package ships executes until you
909
- place it in `~/.pi/agent/pi-lean-host/` and opt in.
910
- - **No inferred-link discovery.** Declared links only in v1; inference is v2.
911
- - **No guide suppression.** Both guide kinds surface by domain match when
912
- 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).
913
552
 
914
553
  ### Mission
915
554
 
@@ -925,8 +564,6 @@ machine; the package does not aim to make that easy.
925
564
 
926
565
  > `pi-lean-host` is part of the
927
566
  > [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
928
- > web-tools suite. For the security model behind the secrets store (the
929
- > two-threat model and the output-channel audit), see
930
- > [Authentication & Secrets](#authentication--secrets).
567
+ > web-tools suite.
931
568
  >
932
569
  > License: AGPL-3.0-only