pi-lean-host 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,11 +20,11 @@
20
20
  > SearXNG search, install
21
21
  > [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
22
22
 
23
- > ⚠️ **Early release (0.1.1).** The API tools here work today, but this is a
23
+ > ⚠️ **Early release (0.2.1).** The API tools here work today, but this is a
24
24
  > development preview. The recipe schema, tool surfaces, and guide format are
25
25
  > still settling as we test more APIs to finalize the shape — **future
26
26
  > compatibility is not guaranteed** until the package reaches lockstep with
27
- > `pi-lean-dimension` 0.5.0. Guides authored against 0.1.x may need revision
27
+ > `pi-lean-dimension` 0.5.0. Guides authored against 0.2.x may need revision
28
28
  > as the schema firms up.
29
29
 
30
30
  ---
@@ -45,8 +45,9 @@
45
45
  12. [`/api status` — Detailed Runtime Status](#api-status--detailed-runtime-status)
46
46
  13. [Configuration (`settings.json`)](#configuration-settingsjson)
47
47
  14. [Co-Installing with `pi-lean-portal`](#co-installing-with-pi-lean-portal)
48
- 15. [Tips & Best Practices](#tips--best-practices)
49
- 16. [Security & Scope](#security--scope)
48
+ 15. [Authentication & Secrets](#authentication--secrets)
49
+ 16. [Tips & Best Practices](#tips--best-practices)
50
+ 17. [Security & Scope](#security--scope)
50
51
 
51
52
  ---
52
53
 
@@ -126,13 +127,14 @@ demand. A skill is pure text with no in-process eval, whereas a loaded
126
127
  |------|----------------|---------------|-------------------|-------|
127
128
  | Built-in helpers | package source (`core/`) | maintainers | yes | reviewed |
128
129
  | Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
129
- | Bundled recipes | `api-guides/<domain>/` in the repo (GitHub) | maintainers | no (reference) | **inert — never auto-executed** |
130
+ | Bundled recipes | `caritas` repo (`api-guides/<domain>/`) | maintainers | no (reference) | **inert — never auto-executed** |
130
131
 
131
132
  Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
132
133
  (computed signatures, strange date transforms, custom auth). Bundled recipes
133
- are inert reference material on GitHub — the loader never reads `api-guides/`
134
- from the package. You adopt one by copying the whole domain folder into your
135
- own directory; only then does it load and execute.
134
+ are inert reference material in the [`caritas`](https://github.com/coreyryanhanson/caritas)
135
+ repo — the loader never reads `api-guides/` from the package. You adopt one by
136
+ copying the whole domain folder into your own directory; only then does it
137
+ load and execute.
136
138
 
137
139
  ---
138
140
 
@@ -150,6 +152,7 @@ touches the other's tools.
150
152
  | `/api` | Show current state and available sub-commands. |
151
153
  | `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
152
154
  | `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
155
+ | `/api secrets [<domain> [<name>]]` | Manage stored API secrets — list, provision, delete (see [Authentication & Secrets](#authentication--secrets)). |
153
156
 
154
157
  ### Why a peer toggle?
155
158
 
@@ -188,8 +191,8 @@ read**, **network read**, **local write**, and **network read (exploratory)**:
188
191
 
189
192
  ```text
190
193
  api-guide → list all available API guides (catalog)
191
- api-guide domain="en.wikipedia.org" → disambiguation menu (two guides claim the domain)
192
- api-guide domain="en.wikipedia.org" guide="Wikipedia REST" → selected guide
194
+ api-guide domain="wikipedia.org" → disambiguation menu (two guides claim the domain)
195
+ api-guide domain="wikipedia.org" guide="Wikipedia REST" → selected guide
193
196
  ```
194
197
 
195
198
  - No parameters → the full catalog (collapsed by `organization:`).
@@ -204,13 +207,13 @@ broken field instead of re-authoring from scratch.
204
207
  ### 2. `api-fetch` — Execute a Guided Operation (network read)
205
208
 
206
209
  ```text
207
- api-fetch domain="en.wikipedia.org" operation="getPageSummary" params={title:"Albert_Einstein"}
208
- api-fetch domain="en.wikipedia.org" operation="searchPages" params={srsearch:"climate"} gatherAll=true
210
+ api-fetch domain="wikipedia.org" operation="getPageSummary" params={title:"Albert_Einstein"}
211
+ api-fetch domain="wikipedia.org" operation="searchPages" params={srsearch:"climate"} gatherAll=true
209
212
  ```
210
213
 
211
214
  **Parameters:**
212
215
 
213
- - `domain` — a domain registered in a guide (e.g. `"en.wikipedia.org"`).
216
+ - `domain` — a domain registered in a guide (e.g. `"wikipedia.org"`).
214
217
  - `operation` — an operation name from the guide (e.g. `"getPageSummary"`).
215
218
  - `params` (optional) — path and query parameter values for the operation.
216
219
  - `gatherAll` (optional) — `true` paginates to gather all items up to the
@@ -260,7 +263,11 @@ real transport (same UA, charset, 429-retry, ETag cache as `api-fetch` — the
260
263
  sanctioned way to reach even WAF'd hosts), summarizes the JSON shape, suggests
261
264
  `via` / `itemsPath` / pagination style, echoes a representative record id, and
262
265
  emits a **draft YAML operation block** to paste straight into a recipe. On 404
263
- it auto-tries `/v1` and `/v2` prefixes (disable with `tryPrefixes=false`).
266
+ it walks the `apiHost` version backward (e.g. `/v3` → `/v2` → `/v1`) to recover
267
+ an over-claimed version; a draft carries the version prefix that was actually
268
+ fetched (disable with `walkVersions=false`). A stale version that still
269
+ returns 200 is not detected as old — read the provider's docs to supply the
270
+ newest version up front.
264
271
 
265
272
  `api-probe` only **suggests** — it never writes the guide. The operation must
266
273
  still be traceable to your plan source (the API docs or a working curl
@@ -352,8 +359,13 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
352
359
  | `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
353
360
  | `verified` | guide | creation date | drift signal — **defaulted, not enforced** |
354
361
  | `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
355
- | `auth.kind` | guide | `none` | strategy seam — **v1 realizes only `none`** (others error) |
356
- | `auth.headers` | guide | — | optional extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) |
362
+ | `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
363
+ | `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 |
364
+ | `auth.secretRefs` | guide | — | `Record<headerName, secretName>` — store-backed header injection (`static-key`) |
365
+ | `auth.headerPrefixes` | guide | — | `Record<headerName, prefix>` — prefix prepended to a secretRefs header value, e.g. `Authorization: "Bearer "` (store holds the raw credential) |
366
+ | `auth.secretQueryRefs` | guide | — | `Record<paramName, secretName>` — store-backed query-param injection (`static-key`) |
367
+ | `auth.requires` | guide | — | secret names the guide hard-requires; absent → `api-fetch` fails closed before the request |
368
+ | `auth.optional` | guide | — | secret names used if present, skipped if absent (e.g. GitHub rate-limit token) |
357
369
  | `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
358
370
  | `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
359
371
  | `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
@@ -377,10 +389,9 @@ Three helpers, for v1. The agent never calls these directly — `api-fetch`
377
389
  routes each operation through the one its `via` names:
378
390
 
379
391
  - **`restGet`** — path templating, query params, Accept negotiation
380
- (JSON/XML), and auth injection *when a guide declares a strategy*. v1 ships
381
- only `auth.kind: none`, so no v1 guide declares a strategy — the dispatch
382
- exists as a seam, but the injection path is cold code until a keyed guide
383
- lands.
392
+ (JSON/XML), and auth injection for `auth.kind: static-key` guides
393
+ (store-backed `secretRefs` / `secretQueryRefs`). See [Authentication &
394
+ Secrets](#authentication--secrets).
384
395
  - **`paginate`** — wraps a list operation. The guide declares the style; the
385
396
  helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
386
397
  stop or continue, plus a `gatherAll` flag for the "just get me everything"
@@ -500,11 +511,11 @@ Authoring is via `api-learn` in learn mode, or hand-editing the file.
500
511
  ## Pagination Styles
501
512
 
502
513
  `paginate` follows the style declared in the recipe. Six styles cover the
503
- patterns the bundled 19-recipe spread pressure-tested:
514
+ patterns the recipe library (caritas) pressure-tested:
504
515
 
505
516
  | Style | What it sends | Key fields |
506
517
  |-------|---------------|------------|
507
- | `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `itemsPath` |
518
+ | `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `base`, `itemsPath` |
508
519
  | `page` | 1-based page number + page size | same fields as `offset-limit` (semantic difference only) |
509
520
  | `nextLink` | follows a URL from the response body | `nextLinkPath`, `itemsPath` — the **only** SSRF-guarded path (see [Security](#security--scope)) |
510
521
  | `cursor` | echoes an opaque cursor query param | `cursorParam`, `cursorPath`, `itemsPath` |
@@ -557,27 +568,34 @@ you know you're in disambiguation territory.
557
568
 
558
569
  ## Bundled Reference Recipes
559
570
 
560
- The repo ships **21 reference recipes** under `api-guides/` (GitHub only —
561
- **not in the npm tarball, never auto-loaded**). They are inert worked
562
- examples spanning the no-auth axes the helper set was validated against:
571
+ The comprehensive recipe library lives in the
572
+ [**caritas**](https://github.com/coreyryanhanson/caritas) repo — real,
573
+ verified recipes spanning the no-auth **and keyed** axes, each with a
574
+ per-recipe `verified:`-date provenance and the perpetual drift disclaimer.
575
+ They are inert reference material: nothing executes until you copy a recipe
576
+ into your own `~/.pi/agent/pi-lean-host/api-guides/<domain>/` directory.
577
+
578
+ The domains caritas covers (a discoverability index, may drift from the live
579
+ repo):
563
580
 
564
581
  ```
565
582
  api.gbif.org api.github.com archive.org archive.org-wayback
566
- arxiv.org boe.es data-api.ecb.europa.eu datos.gob.es
567
- earthquake.usgs.gov en.wikipedia.org en.wikipedia.org-action eutils.ncbi.nlm.nih.gov
568
- gitlab.com loc.gov musicbrainz.org openlibrary.org
569
- resources.data.gov services.dnb.de web.archive.org www.federalregister.gov
570
- www.wikidata.org
583
+ arxiv.org boe.es coingecko.com data-api.ecb.europa.eu
584
+ datos.gob.es earthquake.usgs.gov en.wikipedia.org en.wikipedia.org-action
585
+ etherscan.io eutils.ncbi.nlm.nih.gov gitlab.com loc.gov
586
+ musicbrainz.org openlibrary.org resources.data.gov services.dnb.de
587
+ web.archive.org www.federalregister.gov www.wikidata.org
571
588
  ```
572
589
 
573
- To use them, copy the guides into your own directory from a shallow clone of
574
- the feature branch ([browse the folder on GitHub](https://github.com/coreyryanhanson/pi-lean-dimension/tree/feat/pi-lean-host-package/packages/pi-lean-host/api-guides)):
590
+ Several are **keyed** (`auth.kind: static-key`), the spread that exercises
591
+ header-vs-query refs and the required/optional split (see [Authentication &
592
+ Secrets](#authentication--secrets)).
593
+
594
+ To use them, copy the guides into your own directory from a clone of caritas:
575
595
 
576
596
  ```bash
577
- git clone --depth 1 --branch feat/pi-lean-host-package \
578
- https://github.com/coreyryanhanson/pi-lean-dimension.git /tmp/pi-lean-dimension
579
- cp -r /tmp/pi-lean-dimension/packages/pi-lean-host/api-guides/* \
580
- ~/.pi/agent/pi-lean-host/api-guides/
597
+ git clone https://github.com/coreyryanhanson/caritas.git /tmp/caritas
598
+ cp -r /tmp/caritas/api-guides/* ~/.pi/agent/pi-lean-host/api-guides/
581
599
  ```
582
600
 
583
601
  To grab a single domain instead of all of them, copy just its folder
@@ -586,11 +604,16 @@ To grab a single domain instead of all of them, copy just its folder
586
604
  Only then does it load and execute. A recipe may carry
587
605
  `operation.helper: true` plus an accompanying `helper.ts` in its domain
588
606
  subdir as a worked example — but it stays inert until you copy the folder.
589
- See [`api-guides/CONTRIBUTING.md`](./api-guides/CONTRIBUTING.md) for authoring
590
- a bundled recipe, and
591
- [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md)
592
- for the per-recipe quirk breakdown and the built-in vs local-helper
593
- classification.
607
+ See caritas's `CONTRIBUTING.md` for authoring a recipe.
608
+
609
+ ### What host ships instead
610
+
611
+ Host itself ships only a **synthetic axis-guide set** under `api-guides/` —
612
+ minimal coverage fixtures (no `verified:` date, no live endpoints) that keep
613
+ every guide-driven framework axis exercised via mocked transport. They are
614
+ framework fixtures for host's own tests, not recipes for you to copy. The
615
+ membership is pinned by `__tests__/axis-coverage.test.ts` (which encodes the
616
+ axis-set audit matrix).
594
617
 
595
618
  ---
596
619
 
@@ -652,11 +675,12 @@ the toolset's packaged default:
652
675
 
653
676
  ### No other settings keys
654
677
 
655
- There is no `host.*` settings block in v1. The transport layer (per-domain
656
- undici `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
657
- caching) is configured internally; auth has no keyed strategy yet, so there
658
- are no secrets or endpoints to configure. `apiHost` and operation paths live
659
- **in the recipe frontmatter**, not in settings.
678
+ There is no `host.*` settings block. The transport layer (per-domain undici
679
+ `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
680
+ caching) is configured internally; `apiHost` and operation paths live **in
681
+ the recipe frontmatter**, not in settings. Credentials are **not** stored in
682
+ `settings.json` — they live in the per-domain secrets store, provisioned via
683
+ `/api secrets` (see [Authentication & Secrets](#authentication--secrets)).
660
684
 
661
685
  ---
662
686
 
@@ -727,6 +751,105 @@ know it. The global fallback (`1000`) bounds undeclared guides.
727
751
 
728
752
  ---
729
753
 
754
+ ## Authentication & Secrets
755
+
756
+ Many read APIs authenticate with a static key (`X-Api-Key`, `Authorization:
757
+ Bearer`, or a `?key=` query param). pi-lean-host supports these end-to-end
758
+ without the credential ever appearing in the agent's context — a guide
759
+ **declares the secret by name**, you provision the value once, and `api-fetch`
760
+ injects it in code.
761
+
762
+ ### A candid note on storage and threat model
763
+
764
+ The secrets store is **plaintext JSON at rest** — mode `0600`, no encryption.
765
+ That matches pi's own posture for its credentials (an API key in
766
+ `settings.json` or the env). The threat this guards against is not another
767
+ process reading the file; it's accidental **transcript exfiltration**. You
768
+ provision a value once via `/api secrets`, it's written transcript-safely to
769
+ the store, and `api-fetch` injects it in code — the agent sees the name, not
770
+ the value.
771
+
772
+ That containment is plugin discipline, not a vault. `read`/`cat` on the
773
+ store file is one tool-call from the agent, which runs with your privileges,
774
+ so nothing here is a hard guarantee. **That's why the real rule is: store
775
+ read-only keys.** Scope every credential to the smallest read surface it needs
776
+ (e.g. a GitHub fine-grained token with read-only `contents`). A leaked read
777
+ key is a data-exposure incident; a leaked write key is a takeover — and the
778
+ plugin is GET-only, so a read-only key is always enough for what it does.
779
+
780
+ ### Guide-side: declare the name, never the value
781
+
782
+ In `guide.md`, set `auth.kind: static-key` and point at store secrets by name.
783
+ The value never lives in the guide (a real key committed there would be one
784
+ `cat` from the agent's context).
785
+
786
+ ```yaml
787
+ auth:
788
+ kind: static-key
789
+ secretRefs:
790
+ x-cg-demo-api-key: api_key # headerName: secretName
791
+ requires: [api_key] # absent → api-fetch fails closed
792
+ # secretQueryRefs: { apikey: api_key } # query-param injection (?key=)
793
+ # optional: [api_key] # used if present, skipped if absent
794
+ # headerPrefixes: # headerName → prefix for scheme-style headers
795
+ # Authorization: "Bearer " # (GitHub/GitLab) — the store holds the
796
+ # # RAW token; the guide adds the prefix
797
+ ```
798
+
799
+ - **`auth.secretRefs`** — `Record<headerName, secretName>`: inject the store
800
+ value into that request header.
801
+ - **`auth.headerPrefixes`** — `Record<headerName, prefix>`: prepend a scheme
802
+ prefix to the resolved value for that header (e.g. `Authorization: "Bearer "`).
803
+ The store holds the **raw credential**; the guide declares how it is
804
+ presented. Absent = verbatim value. Every key must also be a `secretRefs`
805
+ header (parser-enforced).
806
+ - **`auth.secretQueryRefs`** — `Record<paramName, secretName>`: inject the
807
+ store value as that query param.
808
+ - **`auth.requires`** — names the guide **hard-requires**. If one is absent
809
+ from the store, `api-fetch` **fails closed before the request** — no silent
810
+ unauthenticated fetch that could return partial data the agent mistakes for
811
+ complete.
812
+ - **`auth.optional`** — names usable-if-present. Absent → `api-fetch` proceeds
813
+ unauthenticated (e.g. GitHub: 60 req/hr unauth, 5000 with a token); present
814
+ → injected like a required secret.
815
+ - **`auth.headers`** stays **literal-only** (demo keys, committed rate-limit
816
+ tokens) — it is not the path for real credentials.
817
+
818
+ ### Provisioning
819
+
820
+ ```text
821
+ /api secrets list stored domains + secret names (names only)
822
+ /api secrets <domain> view + provision for a guide (prompts the declared names)
823
+ /api secrets <domain> <name> set a single secret (manual escape valve)
824
+ /api secrets <domain> --delete delete all secrets for a domain (confirm)
825
+ /api secrets <domain> <name> --delete delete a single secret
826
+ ```
827
+
828
+ Provisioning is interactive (`ctx.ui` dialogs — the value is captured
829
+ **transcript-safely** and written straight to the store, never returned). On
830
+ headless hosts there is no dialog, so `/api secrets` prints the direct
831
+ file-write instructions instead — write the `0600` file yourself before pi
832
+ starts (a one-line `install -m 600` + `cat >` step).
833
+
834
+ Secrets persist at `~/.pi/agent/pi-lean-host/secrets/<domain>.json` (mode
835
+ `0600`). **Only names are ever listed** — values never leave the store.
836
+
837
+ ### The status footer
838
+
839
+ Every `api-guide` / `api-fetch` result on an auth-bearing guide (`secretRefs`
840
+ or `secretQueryRefs`) ends with a `🔑 auth:` line — `ok`, `requires <name>
841
+ — not provisioned`, or an optional state — showing name and presence only,
842
+ never the value, so it's safe anywhere it renders.
843
+
844
+ ### Authoring keyed guides
845
+
846
+ `api-probe` accepts an inline `auth` block (injection fields only) plus a
847
+ `domain` selector, so you can prove a keyed shape before writing the guide —
848
+ a store miss reports the name and fetches unauthenticated (authoring is
849
+ human-in-the-loop, not fail-closed). One of the keyed recipes in caritas is a
850
+ better starting template than `boe.es` for your first keyed guide — see
851
+ caritas's `CONTRIBUTING.md`.
852
+
730
853
  ## Security & Scope
731
854
 
732
855
  ### SSRF guard (server-supplied URLs only)
@@ -743,22 +866,21 @@ Agent-supplied URLs are **not** guarded. `restGet` assembles a URL from
743
866
  The agent runs on your own machine with your own privileges and has `bash`,
744
867
  `read`, and `write` over the filesystem; blocking `http://169.254.169.254/`
745
868
  on `restGet` while `curl` is one tool-call away is a sieve with one hole
746
- patched. The guard becomes load-bearing the moment keyed auth ships (a
747
- server-supplied `nextUrl` to an internal host would leak the attached
748
- `Authorization` header) — it is in place now so that channel is closed before
749
- the credential-bearing path arrives.
869
+ patched. With keyed auth shipped, the guard is now **load-bearing**: a server-supplied
870
+ `nextUrl` to an internal host would leak the attached `Authorization` header,
871
+ and any keyed `restGet`/`paginate` that redirects is forced through the
872
+ guarded loop — with injected secrets stripped on a cross-domain hop — so the
873
+ channel stays closed.
750
874
 
751
875
  ### v1 scope (what it is not)
752
876
 
753
877
  - **GET-read only.** No mutation helper. Add one only when a real *retrieval*
754
878
  guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
755
- gate — and that gate's foundation is a scoped secrets schema, deferred past
756
- v1.
757
- - **`auth.kind: none` only.** The `auth.kind` field + dispatch is a seam for
758
- future `static-key` / `oauth2` strategies; only `none` is realized. No
759
- secrets store ships in v1 — no OS-native store, no file fallback, no
760
- `requires`/`scopes` resolution, no secret-entry UX. The seam is what keeps
761
- that future build additive rather than a retrofit.
879
+ gate.
880
+ - **Static-key auth only.** `auth.kind: static-key` is realized (store-backed
881
+ header/query-param secrets, `requires`/`optional`); `oauth2` and cookie-login
882
+ stay deferred. Values live in the `0600` secrets store, never in a guide —
883
+ see [Authentication & Secrets](#authentication--secrets).
762
884
  - **Bundled recipes are inert.** Nothing the package ships executes until you
763
885
  place it in `~/.pi/agent/pi-lean-host/` and opt in.
764
886
  - **No inferred-link discovery.** Declared links only in v1; inference is v2.
@@ -779,10 +901,8 @@ machine; the package does not aim to make that easy.
779
901
 
780
902
  > `pi-lean-host` is part of the
781
903
  > [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
782
- > web-tools suite. For the deferred secrets-store track (the two-threat
783
- > model and the first-keyed-guide build checklist), see
784
- > [`docs/design/api-secrets-roadmap.md`](docs/design/api-secrets-roadmap.md).
785
- > For the helper escape-valve policy and the 19-recipe spread, see
786
- > [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md).
904
+ > web-tools suite. For the security model behind the secrets store (the
905
+ > two-threat model and the output-channel audit), see
906
+ > [Authentication & Secrets](#authentication--secrets).
787
907
  >
788
908
  > License: AGPL-3.0-only
@@ -19,7 +19,15 @@ import type { Guide } from "./guide-loader.js";
19
19
  */
20
20
  export const GATHER_ALL_MAX_FALLBACK = 1000;
21
21
 
22
- /** Auth strategies recognized by the schema (the seam). v1 realizes only `none`. */
22
+ /**
23
+ * The schema version of the guide recipe format. Metadata-only attribution:
24
+ * it is surfaced on the parsed guide but NEVER gates/warns/alters parse
25
+ * (see __tests__/schema-version.test.ts). Absent frontmatter defaults to the
26
+ * semantic 0. Bumped to 1 at lockstep (a label change, not a break).
27
+ */
28
+ export const GUIDE_SCHEMA_VERSION = 0 as const;
29
+
30
+ /** Auth strategies recognized by the schema (the seam). v1 realizes `none` and `static-key`; `oauth2` is rejected at parse. */
23
31
  export const KNOWN_AUTH_KINDS: ReadonlySet<string> = new Set([
24
32
  "none",
25
33
  "static-key",
@@ -36,6 +44,35 @@ export interface AuthConfig {
36
44
  kind: AuthKind;
37
45
  /** Extra headers merged into every request (e.g. `X-Api-Key: DEMO_KEY`). */
38
46
  headers?: Record<string, string>;
47
+ /**
48
+ * static-key only: maps request header name → secret store name. Values
49
+ * are injected at fetch time from the secrets store; the value never
50
+ * enters agent context. Every referenced name must also appear in
51
+ * `requires` or `optional` (parser-enforced).
52
+ */
53
+ secretRefs?: Record<string, string>;
54
+ /**
55
+ * static-key only: maps request header name → prefix string prepended to
56
+ * the stored secret value before it is sent. The store holds the raw
57
+ * credential; the guide declares how it is presented (e.g.
58
+ * `Authorization: "Bearer "`). Absent = verbatim value. Every key must
59
+ * also appear in `secretRefs` (parser-enforced).
60
+ */
61
+ headerPrefixes?: Record<string, string>;
62
+ /**
63
+ * static-key only: maps query param name → secret store name.
64
+ * Values are injected below the agent-supplied params map at fetch time
65
+ * (never into it) and redacted from every surfaced URL. A param name
66
+ * colliding with any operation's `params` map is a parse error — the
67
+ * agent must not be able to supply a secretly-injected param. Every
68
+ * referenced name must also appear in `requires` or `optional`
69
+ * (parser-enforced, same rule as `secretRefs`).
70
+ */
71
+ secretQueryRefs?: Record<string, string>;
72
+ /** static-key: secret names whose absence fails the request closed before it is sent. */
73
+ requires?: string[];
74
+ /** static-key: secret names that add value when present but are not required. */
75
+ optional?: string[];
39
76
  }
40
77
 
41
78
  // ═══════════════════════════════════════════════════════════════════
@@ -60,6 +97,14 @@ export interface PaginationConfig {
60
97
  pageSizeParam?: string;
61
98
  /** offset-limit / page: requested page size. */
62
99
  pageSize?: number;
100
+ /**
101
+ * offset-limit / page: the seed value for the page param — where this
102
+ * API's index starts (e.g. `base: 1` for 1-based offset APIs). Used only
103
+ * as the pagination seed; the seed precedence is caller value → `base` →
104
+ * the param `default` → the style fallback (0 for offset-limit, 1 for
105
+ * page). Accepted but never read by the non-seeding styles.
106
+ */
107
+ base?: number;
63
108
  /** nextLink: JSON path to the next-page URL. */
64
109
  nextLinkPath?: string;
65
110
  /** cursor: the cursor query param name. */
@@ -169,6 +214,12 @@ export interface Operation {
169
214
  */
170
215
  export interface ApiGuide extends Guide {
171
216
  kind: "api";
217
+ /**
218
+ * Recipe schema version (attribution, not enforcement — see
219
+ * GUIDE_SCHEMA_VERSION). Parsed from frontmatter `schemaVersion:`; absent
220
+ * stays `undefined` (semantic default 0). Never gates/warns/alters parse.
221
+ */
222
+ schemaVersion?: number;
172
223
  /** Execution root: scheme + host + base path; version prefix lives here. */
173
224
  apiHost: string;
174
225
  /** Drift signal; defaulted not enforced. */
@@ -29,6 +29,7 @@ import {
29
29
  } from "pi-tool-masking";
30
30
  import type { ToolsetSpec } from "pi-tool-masking";
31
31
  import { handleHelpersSubcommand } from "./helpers-command.js";
32
+ import { handleSecretsSubcommand } from "./secrets-command.js";
32
33
  import { loadAllGuides } from "./guide-store.js";
33
34
  import { getAllHelpers, getDisabledHelperDomains } from "./local-helpers.js";
34
35
 
@@ -72,6 +73,16 @@ export function getApiToggleState(): boolean {
72
73
  return _lastToggleState;
73
74
  }
74
75
 
76
+ /**
77
+ * Learn-mode gate for api-probe's `listSecrets` discovery. Returns the
78
+ * cached learn state synced on session_start and toolset events. A hard
79
+ * runtime gate (not just toolset masking) so a `listSecrets` call under
80
+ * `/api on` is refused even if the tool is somehow reachable.
81
+ */
82
+ export function isApiLearnEnabled(): boolean {
83
+ return _lastLearnState;
84
+ }
85
+
75
86
  /** @internal Test-only read access to live learn state. */
76
87
  export function _getApiLearnStateForTest(): boolean {
77
88
  return _lastLearnState;
@@ -206,7 +217,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
206
217
  pi.registerCommand("api", {
207
218
  description:
208
219
  "Enable/disable API tools. " +
209
- "Usage: /api on | off | learn | status | helpers [domain]",
220
+ "Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help]",
210
221
  handler: async (args: string, ctx: ExtensionCommandContext) => {
211
222
  const trimmed = args.trim();
212
223
  const parts = trimmed.split(/\s+/);
@@ -270,6 +281,13 @@ export default function initApiToggle(pi: ExtensionAPI): void {
270
281
  return;
271
282
  }
272
283
 
284
+ case "secrets": {
285
+ // Peer of status/helpers/bare — read/write to the secrets store,
286
+ // not a toolset actuation, so the focus-mode guard does not apply.
287
+ await handleSecretsSubcommand(rest, ctx);
288
+ return;
289
+ }
290
+
273
291
  default: {
274
292
  const apiStatus = apiToolset.isEnabled(pi) ? "✅ on" : "❌ off";
275
293
  const learnStatus = learnToolset.isEnabled(pi) ? "✅ on" : "❌ off";
@@ -283,6 +301,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
283
301
  ` /api off disable all API tools`,
284
302
  ` /api status detailed status (guides, helpers)`,
285
303
  ` /api helpers list local helpers`,
304
+ ` /api secrets list/provision stored secrets (names only)`,
286
305
  ` /api show this status`,
287
306
  ];
288
307