pi-lean-host 0.2.1 → 0.3.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 +66 -89
- package/core/api-guide-types.ts +9 -0
- package/core/api-toggle.ts +23 -1
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +28 -0
- package/core/parse-api-guide.ts +373 -23
- package/core/resolve-op.ts +222 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +399 -0
- package/package.json +5 -1
- package/tools/api-fetch.ts +148 -228
- package/tools/api-guide.ts +32 -37
- package/tools/api-learn.ts +431 -115
- package/tools/api-probe.ts +266 -45
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.
|
|
23
|
+
> ⚠️ **Early release (0.3.0).** 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.
|
|
27
|
+
> `pi-lean-dimension` 0.5.0. Guides authored against 0.3.x may need revision
|
|
28
28
|
> as the schema firms up.
|
|
29
29
|
|
|
30
30
|
---
|
|
@@ -67,7 +67,8 @@ From a fresh install you have no guides yet, so the workflow is:
|
|
|
67
67
|
1. **`/api learn`** — enable the authoring tools (`api-learn` + `api-probe`).
|
|
68
68
|
2. **`api-probe({apiHost, path})`** — discover the shape of a not-yet-guided
|
|
69
69
|
endpoint; it drafts a YAML operation block to paste into a recipe.
|
|
70
|
-
3. **`api-learn({domain,
|
|
70
|
+
3. **`api-learn({domain, recipeFile})`** — validate the staged draft and write
|
|
71
|
+
the guide to
|
|
71
72
|
`~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
|
|
72
73
|
4. **`api-fetch({domain, operation})`** — execute and verify.
|
|
73
74
|
|
|
@@ -153,6 +154,8 @@ touches the other's tools.
|
|
|
153
154
|
| `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
|
|
154
155
|
| `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
|
|
155
156
|
| `/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)). |
|
|
158
|
+
| `/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. |
|
|
156
159
|
|
|
157
160
|
### Why a peer toggle?
|
|
158
161
|
|
|
@@ -235,22 +238,33 @@ one) — turning a failed execute into a discovery moment in one round-trip.
|
|
|
235
238
|
### 3. `api-learn` — Author / Update a Guide (local write)
|
|
236
239
|
|
|
237
240
|
```text
|
|
238
|
-
api-learn →
|
|
239
|
-
api-learn domain="
|
|
241
|
+
api-learn → field reference + pointer to the starter template
|
|
242
|
+
api-learn domain="arxiv.org" new=true → stages a fresh placeholder template to /tmp/pi-lean-host/arxiv.org/guide.md
|
|
243
|
+
api-learn domain="arxiv.org" → fetches an existing guide's raw recipe into the staged file
|
|
244
|
+
api-learn domain="arxiv.org" recipeFile="/tmp/pi-lean-host/arxiv.org/guide.md" → validates + writes the guide to disk
|
|
240
245
|
```
|
|
241
246
|
|
|
242
|
-
- No parameters → a
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
247
|
+
- No parameters → a concise field reference plus a pointer to
|
|
248
|
+
`{domain, new: true}` for a domain-specific starter template.
|
|
249
|
+
- `{domain, new: true}` → a fresh starter template with `domains: [<domain>]`
|
|
250
|
+
**staged to `/tmp/pi-lean-host/<domain>/guide.md`**. Only `domains` is real;
|
|
251
|
+
the other fields are `<placeholder>` values that **fail closed**, so a
|
|
252
|
+
pasted template cannot save until you fill it in.
|
|
253
|
+
- `{domain}` (no `recipeFile`) → fetch the current raw recipe of an existing
|
|
254
|
+
guide into the staged file (surfaces `dirName` to prevent sibling-clobber
|
|
255
|
+
in multi-recipe domains); a disambiguation menu if several guides claim the
|
|
256
|
+
domain.
|
|
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`, overwriting any
|
|
260
|
+
existing guide for that domain. On a structural error it names the field,
|
|
261
|
+
the expected shape, and what was found — the file on disk is left untouched
|
|
262
|
+
(no half-written guide). Requires `/api learn`.
|
|
263
|
+
|
|
264
|
+
The working copy is staged at `/tmp/pi-lean-host/<domain>/guide.md` (`/tmp`
|
|
265
|
+
self-cleans, so drafts don't accumulate) — fetch/template calls write the
|
|
266
|
+
draft there and you edit that file between saves; saving reads it and
|
|
267
|
+
publishes to the guides dir. No session-held state, no `/api save`.
|
|
254
268
|
|
|
255
269
|
### 4. `api-probe` — Discover an Endpoint's Shape (network read, exploratory)
|
|
256
270
|
|
|
@@ -269,6 +283,13 @@ fetched (disable with `walkVersions=false`). A stale version that still
|
|
|
269
283
|
returns 200 is not detected as old — read the provider's docs to supply the
|
|
270
284
|
newest version up front.
|
|
271
285
|
|
|
286
|
+
Pass `scaffold: true` to emit a **full recipe skeleton** (frontmatter +
|
|
287
|
+
`auth:` translated from the inline auth block + a draft op block) instead of
|
|
288
|
+
just the op block — opt-in, and auto-degrades by guide count (0 guides →
|
|
289
|
+
skeleton, 1/N → op block + a merge note). The scaffolded `schemaVersion`
|
|
290
|
+
matches what `api-learn` stamps on save, so the guide is detection-ready the
|
|
291
|
+
moment it's saved.
|
|
292
|
+
|
|
272
293
|
`api-probe` only **suggests** — it never writes the guide. The operation must
|
|
273
294
|
still be traceable to your plan source (the API docs or a working curl
|
|
274
295
|
example); this tool surfaces evidence, not authority. Requires `/api learn`.
|
|
@@ -283,68 +304,20 @@ agent (advisory). `api-fetch` reads the recipe slice and executes against it;
|
|
|
283
304
|
`api-guide` reads the detail slice for introspection. **The prose is
|
|
284
305
|
advisory, the frontmatter is authoritative.**
|
|
285
306
|
|
|
286
|
-
###
|
|
287
|
-
|
|
288
|
-
```yaml
|
|
289
|
-
---
|
|
290
|
-
kind: api
|
|
291
|
-
domains: [boe.es, www.boe.es]
|
|
292
|
-
icon: ⚖️
|
|
293
|
-
shortName: BOE
|
|
294
|
-
updated: 2026-07-17
|
|
295
|
-
# organization: boe.es # optional — org identity across guides
|
|
296
|
-
# description: BOE open-data API. # optional — ≤200 chars, one line; aids disambiguation
|
|
297
|
-
apiHost: https://apidatos.boe.es/v1
|
|
298
|
-
verified: 2026-07-17
|
|
299
|
-
gatherAllMax: 500
|
|
307
|
+
### File shape
|
|
300
308
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
style: offset-limit
|
|
306
|
-
pageParam: page
|
|
307
|
-
pageSizeParam: limit
|
|
308
|
-
pageSize: 50
|
|
309
|
-
itemsPath: data
|
|
310
|
-
# totalCountPath: meta.totalCount # optional, any style → server total in the footer
|
|
311
|
-
|
|
312
|
-
responseShape:
|
|
313
|
-
format: json
|
|
314
|
-
charset: utf-8
|
|
315
|
-
|
|
316
|
-
operations:
|
|
317
|
-
- name: searchDiary
|
|
318
|
-
via: restGet
|
|
319
|
-
path: /diario/{date}
|
|
320
|
-
accept: json
|
|
321
|
-
params:
|
|
322
|
-
limit:
|
|
323
|
-
default: 50
|
|
324
|
-
helper: true # run this domain's local helper.ts for this op
|
|
325
|
-
parse:
|
|
326
|
-
format: xml
|
|
327
|
-
charset: iso-8859-1
|
|
328
|
-
|
|
329
|
-
- name: listConsolidada
|
|
330
|
-
via: paginate
|
|
331
|
-
path: /legislacion-consolidada
|
|
332
|
-
accept: json
|
|
333
|
-
pagination:
|
|
334
|
-
style: cursor
|
|
335
|
-
cursorParam: cursor
|
|
336
|
-
cursorPath: pagination.nextCursor
|
|
337
|
-
itemsPath: results
|
|
338
|
-
gatherAllMax: 1000 # op-level ceiling override
|
|
339
|
-
---
|
|
340
|
-
# BOE Legislación Consolidada — structured API access
|
|
309
|
+
A `guide.md` opens with a `---`-delimited YAML frontmatter block and
|
|
310
|
+
closes it with a second `---`; the prose body follows. An operation can
|
|
311
|
+
override the guide-level `pagination` / `responseShape` with its own block
|
|
312
|
+
in the frontmatter.
|
|
341
313
|
|
|
342
|
-
|
|
343
|
-
`
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
314
|
+
The fastest way to a first guide is to let the tools draft it:
|
|
315
|
+
`api-learn({domain, new: true})` returns a fail-closed starter template,
|
|
316
|
+
and `api-probe({scaffold: true})` emits a full skeleton from a live
|
|
317
|
+
endpoint — fill the placeholders, then save with `api-learn`. For
|
|
318
|
+
**complete worked recipes** (real endpoints, `verified:` provenance,
|
|
319
|
+
auth-in-place, helper examples), see the [Caritas](#bundled-reference-recipes)
|
|
320
|
+
recipe library and copy a domain folder that matches your target.
|
|
348
321
|
|
|
349
322
|
### Field reference
|
|
350
323
|
|
|
@@ -357,7 +330,8 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
|
|
|
357
330
|
| `organization` | guide | — | optional org identity (registrable domain); catalog grouping + disambiguation. Recipe-slice only |
|
|
358
331
|
| `description` | guide | — | optional one-line summary (≤200 chars); primary disambiguation signal for multi-guide domains |
|
|
359
332
|
| `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
|
|
360
|
-
| `verified` | guide | creation date | drift signal — **defaulted, not enforced
|
|
333
|
+
| `verified` | guide | creation date | drift signal — **defaulted, not enforced**; stamped on success by `/api verify` |
|
|
334
|
+
| `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** |
|
|
361
335
|
| `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
|
|
362
336
|
| `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
|
|
363
337
|
| `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 |
|
|
@@ -379,6 +353,7 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
|
|
|
379
353
|
| `operations[].dateParams` | op | — | optional `{param: format}` → normalizes ISO dates to `iso8601` \| `yyyymmdd` \| `yyyy-mm-dd` (query params only) |
|
|
380
354
|
| `operations[].helper` | op | `false` | `true` runs this domain's local helper for the op |
|
|
381
355
|
| `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) |
|
|
356
|
+
| `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) |
|
|
382
357
|
| `operations[].passthrough` | op | `false` | `true` forwards undeclared caller params onto the query string (for open-param APIs) |
|
|
383
358
|
| `operations[].parse` | op | inherits `responseShape` | op-level override of format/charset |
|
|
384
359
|
| `operations[].pagination` | op | inherits top-level | op-level override of pagination |
|
|
@@ -411,7 +386,10 @@ loader enforces:
|
|
|
411
386
|
- The `verified` frontmatter date records when a guide was last verified
|
|
412
387
|
against the live API (defaulted to creation date, **never enforced**). It's
|
|
413
388
|
rendered in the guide-detail footer alongside the current date — the agent
|
|
414
|
-
reads both and judges.
|
|
389
|
+
reads both and judges. `/api verify <domain>` runs every runnable op
|
|
390
|
+
against the live API and stamps `verified` on success (strict: any
|
|
391
|
+
runnable-op failure → no stamp; skipped ops named in the report; `--force`
|
|
392
|
+
is human-typed only, no agent tool surface).
|
|
415
393
|
- The **live HTTP response is the actual drift signal.** A 401 on a no-auth
|
|
416
394
|
guide, a 404 on a pinned path, a changed response shape — the agent reads
|
|
417
395
|
those directly. The `verified` date is predictive; the response is actual.
|
|
@@ -538,7 +516,7 @@ Agents mangle encodings constantly; `parseResponse` fixes it once. Declared
|
|
|
538
516
|
per-guide (top-level `responseShape`) and overridable per-op (`parse:`):
|
|
539
517
|
|
|
540
518
|
- `format: json | xml | text` — XML is converted to JSON via `fast-xml-parser`; `text` is raw passthrough.
|
|
541
|
-
- `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
|
|
519
|
+
- `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.
|
|
542
520
|
- `accept` (request-side, on each operation) is declared **independently**
|
|
543
521
|
from `responseShape.format` (response-side) — they usually match but an API
|
|
544
522
|
may return XML regardless of `Accept`, so they're separate fields.
|
|
@@ -686,12 +664,10 @@ the recipe frontmatter**, not in settings. Credentials are **not** stored in
|
|
|
686
664
|
|
|
687
665
|
## Co-Installing with `pi-lean-portal`
|
|
688
666
|
|
|
689
|
-
> **Planned for a future release.** Portal integration is
|
|
690
|
-
>
|
|
691
|
-
>
|
|
692
|
-
>
|
|
693
|
-
> Host-side projection code is present but inert until portal ships the
|
|
694
|
-
> receiving global (`__piLeanPortalRegisterGuideProvider`).
|
|
667
|
+
> **Planned for a future release.** Portal integration is not yet shipped:
|
|
668
|
+
> the projection and navigate-footer surfacing described below are what that
|
|
669
|
+
> release delivers. Host-side projection code is present but inert until
|
|
670
|
+
> portal ships the receiving global (`__piLeanPortalRegisterGuideProvider`).
|
|
695
671
|
|
|
696
672
|
Portal is fully optional. When co-installed, host registers a **projection**
|
|
697
673
|
of its user-authored `ApiGuide`s with portal's guide-source registry at load
|
|
@@ -846,9 +822,10 @@ never the value, so it's safe anywhere it renders.
|
|
|
846
822
|
`api-probe` accepts an inline `auth` block (injection fields only) plus a
|
|
847
823
|
`domain` selector, so you can prove a keyed shape before writing the guide —
|
|
848
824
|
a store miss reports the name and fetches unauthenticated (authoring is
|
|
849
|
-
human-in-the-loop, not fail-closed).
|
|
850
|
-
|
|
851
|
-
|
|
825
|
+
human-in-the-loop, not fail-closed). A learn-gated `listSecrets: true` mode
|
|
826
|
+
lists provisioned secret names (names only) to close the authoring bootstrap
|
|
827
|
+
gap; a bare `listSecrets` call (no `domain`, no `apiHost`) lists
|
|
828
|
+
provisioned-but-guideless store domains first.
|
|
852
829
|
|
|
853
830
|
## Security & Scope
|
|
854
831
|
|
package/core/api-guide-types.ts
CHANGED
|
@@ -174,6 +174,15 @@ export interface Operation {
|
|
|
174
174
|
* the model via api-guide only.
|
|
175
175
|
*/
|
|
176
176
|
pathParamDocs?: Record<string, string>;
|
|
177
|
+
/**
|
|
178
|
+
* At-least-one-of constraint: at least one of these param names must be
|
|
179
|
+
* supplied. Members may not be `required: true` nor carry a `default`
|
|
180
|
+
* (both parser-enforced) — they are mutually exclusive peers, so a
|
|
181
|
+
* default would fire alongside a caller-supplied sibling and a
|
|
182
|
+
* `required` flag would defeat the group. One group per op (v1); a
|
|
183
|
+
* multi-group `requiresAnyOfGroups` upgrade is purely additive.
|
|
184
|
+
*/
|
|
185
|
+
requiresAnyOf?: string[];
|
|
177
186
|
/**
|
|
178
187
|
* Whether this operation uses the domain's local helper (coarse, pre-call).
|
|
179
188
|
* A `true` value means call `<guidesDir>/<domain>/helper.ts` for this op.
|
package/core/api-toggle.ts
CHANGED
|
@@ -30,6 +30,8 @@ import {
|
|
|
30
30
|
import type { ToolsetSpec } from "pi-tool-masking";
|
|
31
31
|
import { handleHelpersSubcommand } from "./helpers-command.js";
|
|
32
32
|
import { handleSecretsSubcommand } from "./secrets-command.js";
|
|
33
|
+
import { handleVerifySubcommand } from "./verify-command.js";
|
|
34
|
+
import { handleDeleteSubcommand } from "./delete-command.js";
|
|
33
35
|
import { loadAllGuides } from "./guide-store.js";
|
|
34
36
|
import { getAllHelpers, getDisabledHelperDomains } from "./local-helpers.js";
|
|
35
37
|
|
|
@@ -187,6 +189,8 @@ function handleStatusSubcommand(
|
|
|
187
189
|
` /api on enable api-guide + api-fetch`,
|
|
188
190
|
` /api learn enable all four tools (adds api-learn + api-probe)`,
|
|
189
191
|
` /api off disable all API tools`,
|
|
192
|
+
` /api verify verify a guide's ops against its live API (stamps verified)`,
|
|
193
|
+
` /api delete delete a guide directory (human-typed recovery gesture)`,
|
|
190
194
|
);
|
|
191
195
|
|
|
192
196
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
@@ -217,7 +221,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
217
221
|
pi.registerCommand("api", {
|
|
218
222
|
description:
|
|
219
223
|
"Enable/disable API tools. " +
|
|
220
|
-
"Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help]",
|
|
224
|
+
"Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help] | verify <domain> [guide] [--force] | delete <domain> [guide]",
|
|
221
225
|
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
222
226
|
const trimmed = args.trim();
|
|
223
227
|
const parts = trimmed.split(/\s+/);
|
|
@@ -288,6 +292,22 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
288
292
|
return;
|
|
289
293
|
}
|
|
290
294
|
|
|
295
|
+
case "verify": {
|
|
296
|
+
// Peer of status/helpers/secrets — verifies a guide's ops and
|
|
297
|
+
// stamps verified: (writes guide.md, not toolset state), so the
|
|
298
|
+
// focus-mode guard does not apply.
|
|
299
|
+
await handleVerifySubcommand(rest, ctx);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
case "delete": {
|
|
304
|
+
// Peer of status/helpers/secrets/verify — removes a guide
|
|
305
|
+
// directory and invalidates the cache (writes guide.md, not
|
|
306
|
+
// toolset state), so the focus-mode guard does not apply.
|
|
307
|
+
await handleDeleteSubcommand(rest, ctx);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
|
|
291
311
|
default: {
|
|
292
312
|
const apiStatus = apiToolset.isEnabled(pi) ? "✅ on" : "❌ off";
|
|
293
313
|
const learnStatus = learnToolset.isEnabled(pi) ? "✅ on" : "❌ off";
|
|
@@ -302,6 +322,8 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
302
322
|
` /api status detailed status (guides, helpers)`,
|
|
303
323
|
` /api helpers list local helpers`,
|
|
304
324
|
` /api secrets list/provision stored secrets (names only)`,
|
|
325
|
+
` /api verify verify a guide's ops against its live API (stamps verified)`,
|
|
326
|
+
` /api delete delete a guide directory (human-typed recovery gesture)`,
|
|
305
327
|
` /api show this status`,
|
|
306
328
|
];
|
|
307
329
|
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/api delete <domain> [guide]` — remove a guide directory and invalidate
|
|
3
|
+
* the per-session guide-store cache (closing the ghost-guide cache bug that
|
|
4
|
+
* `bash rm` leaves behind).
|
|
5
|
+
*
|
|
6
|
+
* - `delete <domain>` — whole-domain delete (interactive confirm).
|
|
7
|
+
* - `delete <domain> <guide>` — delete one guide by shortName (no confirm).
|
|
8
|
+
* - `delete --help` — usage.
|
|
9
|
+
*
|
|
10
|
+
* Whole-domain delete mirrors `/api secrets --delete` (interactive confirm);
|
|
11
|
+
* single-guide delete mirrors `/api secrets --delete <domain> <name>` (no
|
|
12
|
+
* confirm). After the `rm -rf` of the directory, `invalidateCache()` so the
|
|
13
|
+
* next api-guide / api-fetch doesn't see a ghost guide — the load-bearing
|
|
14
|
+
* reason this beats `bash rm`.
|
|
15
|
+
*
|
|
16
|
+
* Always-available (runs in **on** mode), not learn-gated, and not refused by
|
|
17
|
+
* the focus-mode guard — it writes no toolset state (peer of secrets/verify).
|
|
18
|
+
*
|
|
19
|
+
* The agent has NO delete surface: api-learn's collision/malformed errors
|
|
20
|
+
* tell it to ask the human to run this command.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { existsSync, rmSync } from "node:fs";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
import {
|
|
27
|
+
findGuidesByDomain,
|
|
28
|
+
invalidateCache,
|
|
29
|
+
getUserGuidesDir,
|
|
30
|
+
} from "./guide-store.js";
|
|
31
|
+
import {
|
|
32
|
+
formatGuideListings,
|
|
33
|
+
selectGuideByShortName,
|
|
34
|
+
shortNameErrorText,
|
|
35
|
+
} from "./parse-api-guide.js";
|
|
36
|
+
import { pickGuide } from "./guide-picker.js";
|
|
37
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
38
|
+
|
|
39
|
+
/** Usage, surfaced by `--help`. */
|
|
40
|
+
function helpText(): string {
|
|
41
|
+
return [
|
|
42
|
+
"Usage: /api delete <domain> [guide]",
|
|
43
|
+
" /api delete <domain> delete the whole guide directory (interactive confirm)",
|
|
44
|
+
" /api delete <domain> <guide> delete one guide by shortName (no confirm)",
|
|
45
|
+
" /api delete --help this help",
|
|
46
|
+
"",
|
|
47
|
+
" Removes the directory and invalidates the per-session guide cache, so the",
|
|
48
|
+
" next api-guide / api-fetch no longer lists it (bash rm leaves a ghost).",
|
|
49
|
+
" The agent has no delete tool — this is a human-typed recovery gesture.",
|
|
50
|
+
].join("\n");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Handle the `delete` subcommand of `/api`.
|
|
55
|
+
*
|
|
56
|
+
* @param args The text after "delete" ("" / "<domain>" / "<domain> <guide>").
|
|
57
|
+
* @param ctx The extension command context
|
|
58
|
+
*/
|
|
59
|
+
export async function handleDeleteSubcommand(
|
|
60
|
+
args: string,
|
|
61
|
+
ctx: ExtensionCommandContext,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
64
|
+
|
|
65
|
+
if (parts.includes("--help") || parts.includes("help")) {
|
|
66
|
+
ctx.ui.notify(helpText(), "info");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const domain = parts[0];
|
|
71
|
+
const guideSelector = parts[1];
|
|
72
|
+
|
|
73
|
+
if (!domain) {
|
|
74
|
+
ctx.ui.notify(
|
|
75
|
+
"Usage: /api delete <domain> [guide] — see /api delete --help.",
|
|
76
|
+
"warning",
|
|
77
|
+
);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Path-traversal guard before any filesystem access — the literal-dir
|
|
82
|
+
// fallback below joins the domain into the guides dir.
|
|
83
|
+
try {
|
|
84
|
+
assertSafeDomain(domain);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
ctx.ui.notify(
|
|
87
|
+
err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
|
|
88
|
+
"warning",
|
|
89
|
+
);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const matches = findGuidesByDomain(domain);
|
|
94
|
+
|
|
95
|
+
if (matches.length === 0) {
|
|
96
|
+
// Literal-dir fallback: a malformed guide's `domains:` block is
|
|
97
|
+
// unreadable, so findGuidesByDomain can't address it — but the
|
|
98
|
+
// malformed catalog line shows its dirName. `/api delete <dirName>`
|
|
99
|
+
// recovers it. Whole-domain delete (confirm) since the guide can't be
|
|
100
|
+
// enumerated from it.
|
|
101
|
+
if (existsSync(join(getUserGuidesDir(), domain))) {
|
|
102
|
+
await deleteDir(ctx, domain, true);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
ctx.ui.notify(
|
|
106
|
+
`No API guide for '${domain}'. ` +
|
|
107
|
+
`Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author one.`,
|
|
108
|
+
"warning",
|
|
109
|
+
);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// guide selector present → resolve by shortName (1 or N guides), no confirm.
|
|
114
|
+
if (guideSelector) {
|
|
115
|
+
const sel = selectGuideByShortName(matches, guideSelector);
|
|
116
|
+
if (!sel.ok) {
|
|
117
|
+
ctx.ui.notify(
|
|
118
|
+
shortNameErrorText(
|
|
119
|
+
sel,
|
|
120
|
+
domain,
|
|
121
|
+
guideSelector,
|
|
122
|
+
`Call /api delete ${domain} to see the menu.`,
|
|
123
|
+
),
|
|
124
|
+
"warning",
|
|
125
|
+
);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
await deleteDir(ctx, sel.dirName, false);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (matches.length === 1) {
|
|
133
|
+
// Whole-domain delete — interactive confirm.
|
|
134
|
+
await deleteDir(ctx, matches[0]!.dirName, true);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// N guides, no selector → interactive pick (TUI) or the menu
|
|
139
|
+
// fallback (headless/RPC/print or cancelled), nothing removed.
|
|
140
|
+
const picked = await pickGuide(ctx, matches);
|
|
141
|
+
if (!picked) {
|
|
142
|
+
ctx.ui.notify(
|
|
143
|
+
[
|
|
144
|
+
`${matches.length} API guides for '${domain}':`,
|
|
145
|
+
formatGuideListings(matches),
|
|
146
|
+
`Call /api delete ${domain} <shortName> to delete one guide (no confirm).`,
|
|
147
|
+
].join("\n"),
|
|
148
|
+
"info",
|
|
149
|
+
);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
await deleteDir(ctx, picked.dirName, false);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Remove one guide directory and invalidate the cache. `confirm` is true for
|
|
157
|
+
* whole-domain deletes (interactive confirm, headless skips it — mirroring
|
|
158
|
+
* `/api secrets --delete`) and false for single-guide deletes.
|
|
159
|
+
*/
|
|
160
|
+
async function deleteDir(
|
|
161
|
+
ctx: ExtensionCommandContext,
|
|
162
|
+
dirName: string,
|
|
163
|
+
confirm: boolean,
|
|
164
|
+
): Promise<void> {
|
|
165
|
+
const dir = join(getUserGuidesDir(), dirName);
|
|
166
|
+
if (!existsSync(dir)) {
|
|
167
|
+
ctx.ui.notify(
|
|
168
|
+
`No guide directory '${dirName}' — nothing to delete.`,
|
|
169
|
+
"warning",
|
|
170
|
+
);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (confirm && ctx.hasUI) {
|
|
174
|
+
const ok = await ctx.ui.confirm(
|
|
175
|
+
`Delete the API guide directory '${dirName}'?`,
|
|
176
|
+
`This removes ${dir} and its contents (guide.md, helper.ts, verify.json).`,
|
|
177
|
+
);
|
|
178
|
+
if (!ok) {
|
|
179
|
+
ctx.ui.notify("Cancelled — nothing deleted.", "info");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
rmSync(dir, { recursive: true, force: true });
|
|
184
|
+
invalidateCache();
|
|
185
|
+
ctx.ui.notify(
|
|
186
|
+
`🗑 Deleted API guide '${dirName}'. ` +
|
|
187
|
+
`Cache invalidated — the next api-guide catalog will no longer list it.`,
|
|
188
|
+
"info",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interactive guide picker for the /api verify and /api delete commands.
|
|
3
|
+
*
|
|
4
|
+
* When a domain claims N guides and no `guide` selector is supplied, the
|
|
5
|
+
* commands show a `SelectList` (from @earendil-works/pi-tui, already a peer
|
|
6
|
+
* dep) with the shortName in the primary column and the guide description in
|
|
7
|
+
* a second column — the user picks with ↑↓/enter instead of retyping the
|
|
8
|
+
* command with a shortName. `value` is the dirName (unique, unlike shortName,
|
|
9
|
+
* which can be ambiguous across sibling guides).
|
|
10
|
+
*
|
|
11
|
+
* Terminal-only: `ctx.mode === "tui"` (custom components don't exist in
|
|
12
|
+
* RPC/print). In headless/RPC/print `pickGuide` returns undefined and the
|
|
13
|
+
* caller keeps today's text menu + retype fallback. A stale guide
|
|
14
|
+
* (`schemaVersion < current`) gets a `⚠` on its label so stale-guide
|
|
15
|
+
* detection survives the interactive path.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
import {
|
|
20
|
+
Container,
|
|
21
|
+
type SelectItem,
|
|
22
|
+
SelectList,
|
|
23
|
+
Text,
|
|
24
|
+
} from "@earendil-works/pi-tui";
|
|
25
|
+
import { GUIDE_SCHEMA_VERSION, type ApiGuide } from "./api-guide-types.js";
|
|
26
|
+
import { isStaleSchema } from "./parse-api-guide.js";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Build the picker rows: `value` = dirName (unique), `label` = shortName (with
|
|
30
|
+
* a `⚠` when stale), `description` = the guide description, falling back to an
|
|
31
|
+
* op-count summary when absent. Pure — tests exercise it without a TUI.
|
|
32
|
+
*/
|
|
33
|
+
export function buildGuidePickerItems(
|
|
34
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
35
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
36
|
+
): SelectItem[] {
|
|
37
|
+
return matches.map(({ guide, dirName }) => {
|
|
38
|
+
const desc =
|
|
39
|
+
guide.description ??
|
|
40
|
+
(guide.operations.length > 0
|
|
41
|
+
? `${guide.operations.length} op${guide.operations.length === 1 ? "" : "s"}`
|
|
42
|
+
: undefined);
|
|
43
|
+
const item: SelectItem = {
|
|
44
|
+
value: dirName,
|
|
45
|
+
label:
|
|
46
|
+
guide.shortName +
|
|
47
|
+
(isStaleSchema(guide.schemaVersion ?? 0, current) ? " ⚠" : ""),
|
|
48
|
+
};
|
|
49
|
+
if (desc !== undefined) item.description = desc;
|
|
50
|
+
return item;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Let the user pick one of a domain's guides interactively (TUI only).
|
|
56
|
+
* Returns the selected `{ guide, dirName }`, or undefined when the picker is
|
|
57
|
+
* unavailable (not TUI mode) or the user cancelled — the caller then renders
|
|
58
|
+
* its own text menu fallback.
|
|
59
|
+
*/
|
|
60
|
+
export async function pickGuide(
|
|
61
|
+
ctx: ExtensionCommandContext,
|
|
62
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
63
|
+
): Promise<{ guide: ApiGuide; dirName: string } | undefined> {
|
|
64
|
+
if (ctx.mode !== "tui") return undefined;
|
|
65
|
+
|
|
66
|
+
const items = buildGuidePickerItems(matches);
|
|
67
|
+
|
|
68
|
+
const picked = await ctx.ui.custom<string | undefined>(
|
|
69
|
+
(tui, theme, _kb, done) => {
|
|
70
|
+
const container = new Container();
|
|
71
|
+
container.addChild(
|
|
72
|
+
new Text(theme.fg("accent", theme.bold("Select API guide"))),
|
|
73
|
+
);
|
|
74
|
+
const list = new SelectList(items, Math.min(items.length, 10), {
|
|
75
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
76
|
+
selectedText: (text) => theme.fg("accent", text),
|
|
77
|
+
description: (text) => theme.fg("muted", text),
|
|
78
|
+
scrollInfo: (text) => theme.fg("dim", text),
|
|
79
|
+
noMatch: (text) => theme.fg("warning", text),
|
|
80
|
+
});
|
|
81
|
+
list.onSelect = (item) => done(item.value);
|
|
82
|
+
list.onCancel = () => done(undefined);
|
|
83
|
+
container.addChild(list);
|
|
84
|
+
container.addChild(
|
|
85
|
+
new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel")),
|
|
86
|
+
);
|
|
87
|
+
return {
|
|
88
|
+
render(width: number) {
|
|
89
|
+
return container.render(width);
|
|
90
|
+
},
|
|
91
|
+
invalidate() {
|
|
92
|
+
container.invalidate();
|
|
93
|
+
},
|
|
94
|
+
handleInput(data: string) {
|
|
95
|
+
list.handleInput(data);
|
|
96
|
+
tui.requestRender();
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
if (picked === undefined) return undefined;
|
|
103
|
+
return matches.find((m) => m.dirName === picked);
|
|
104
|
+
}
|
package/core/helpers-command.ts
CHANGED
|
@@ -55,7 +55,7 @@ export async function handleHelpersSubcommand(
|
|
|
55
55
|
lines.push(
|
|
56
56
|
"",
|
|
57
57
|
"Call /api helpers <domain> to view a helper's source.",
|
|
58
|
-
"Call api-learn({domain,
|
|
58
|
+
"Call api-learn({domain, recipeFile}) to author or update a guide (and its helper).",
|
|
59
59
|
);
|
|
60
60
|
|
|
61
61
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
@@ -78,9 +78,7 @@ export async function handleHelpersSubcommand(
|
|
|
78
78
|
if (source === null) {
|
|
79
79
|
const all = getAllHelpers();
|
|
80
80
|
const known =
|
|
81
|
-
all.length > 0
|
|
82
|
-
? ` Known helpers: ${all.join(", ")}.`
|
|
83
|
-
: " No helpers found.";
|
|
81
|
+
all.length > 0 ? ` Known helpers: ${all.join(", ")}.` : " No helpers found.";
|
|
84
82
|
ctx.ui.notify(
|
|
85
83
|
`No helper for '${domain}'.${known}\n\n` +
|
|
86
84
|
`Helpers live alongside guides at api-guides/${domain}/helper.ts.\n` +
|