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.
@@ -1,10 +1,18 @@
1
1
  /**
2
2
  * api-learn tool definition.
3
3
  *
4
- * Validates and writes an API guide recipe.
5
- * - `{domain, recipe}` → validates via `parseApiGuide()`, writes to
4
+ * Authoring entry points:
5
+ * - No params → authoring manual (field reference + defaults + semantics)
6
+ * with a pointer to `{domain, new: true}` for a domain-specific starter.
7
+ * - `{domain, new: true}` → fresh template with `domains: [<domain>]`
8
+ * pre-filled (regardless of existing guides).
9
+ * - `{domain}` (no recipeFile) → fetch the current raw recipe of an existing
10
+ * guide (0 guides → template; 1 guide → raw recipe + dirName surfaced;
11
+ * N guides → disambiguation menu by shortName), staged to
12
+ * `/tmp/pi-lean-host/<domain>/guide.md`.
13
+ * - `{domain, recipeFile}` → reads the staged draft, validates via
14
+ * `parseApiGuide()`, writes to
6
15
  * `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
7
- * - No `domain` → returns the worked-example recipe for authoring.
8
16
  *
9
17
  * No half-write on validation error (validate first, write only on success).
10
18
  * Defaults are filled by the validator before writing.
@@ -12,13 +20,28 @@
12
20
  * Mirrors portal's `web-learn`.
13
21
  */
14
22
 
15
- import { defineTool } from "@earendil-works/pi-coding-agent";
23
+ import {
24
+ defineTool,
25
+ type AgentToolResult,
26
+ } from "@earendil-works/pi-coding-agent";
16
27
  import { Type } from "@earendil-works/pi-ai";
17
28
  import { Text } from "@earendil-works/pi-tui";
18
29
  import { appendFooter, contentText } from "./utils.js";
19
- import { mkdirSync, writeFileSync } from "node:fs";
30
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
31
+ import { tmpdir } from "node:os";
20
32
  import { join } from "node:path";
21
- import { parseApiGuide } from "../core/parse-api-guide.js";
33
+ import {
34
+ parseApiGuide,
35
+ stampFrontmatterField,
36
+ formatGuideListings,
37
+ selectGuideByShortName,
38
+ shortNameErrorText,
39
+ } from "../core/parse-api-guide.js";
40
+ import {
41
+ GUIDE_SCHEMA_VERSION,
42
+ type ApiGuide,
43
+ type AuthConfig,
44
+ } from "../core/api-guide-types.js";
22
45
  import {
23
46
  invalidateCache,
24
47
  getUserGuidesDir,
@@ -27,69 +50,283 @@ import {
27
50
  import { assertSafeDomain } from "../core/path-template.js";
28
51
 
29
52
  // ═══════════════════════════════════════════════════════════════════
30
- // Worked example
53
+ // Staged working copy (/tmp) — the draft the agent edits between saves
54
+ // ═══════════════════════════════════════════════════════════════════
55
+
56
+ let _stagingRoot = join(tmpdir(), "pi-lean-host");
57
+
58
+ /** Test override — mirrors `setUserGuidesDir` so tests keep drafts out of
59
+ * the real /tmp root. */
60
+ export function setStagingRoot(dir: string): void {
61
+ _stagingRoot = dir;
62
+ }
63
+
64
+ /** Deterministic draft path: `<root>/<domain>/guide.md`. */
65
+ function stagingPathFor(domain: string): string {
66
+ return join(_stagingRoot, domain, "guide.md");
67
+ }
68
+
69
+ /** Write the working copy (template or fetched raw recipe) to the staging
70
+ * path. Returns the path. */
71
+ function writeStagedDraft(domain: string, raw: string): string {
72
+ const path = stagingPathFor(domain);
73
+ mkdirSync(join(_stagingRoot, domain), { recursive: true });
74
+ writeFileSync(path, raw, "utf-8");
75
+ return path;
76
+ }
77
+
78
+ // ═══════════════════════════════════════════════════════════════════
79
+ // Placeholder skeleton (retired worked example)
31
80
  // ═══════════════════════════════════════════════════════════════════
32
81
 
33
82
  /** Max length for `description:` enforced on the write path (strict-on-write,
34
83
  * lenient-on-read — the loader accepts any length). One-liner, not prose. */
35
84
  const DESCRIPTION_MAX = 200;
36
85
 
37
- const WORKED_EXAMPLE = `---
86
+ /** Commented static-key auth block — the issue-#5 auth-wiring teaching,
87
+ * API-agnostic, kept after the worked example retired. */
88
+ const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in the secrets store (/api secrets), never in the recipe:
89
+ # kind: static-key
90
+ # requires: [<secret-name>]
91
+ # secretRefs:
92
+ # Authorization: <secret-name> # header name → secret name (must match the name provisioned via /api secrets)
93
+ # headerPrefixes:
94
+ # Authorization: "Bearer "`;
95
+
96
+ /** Placeholder starter template — only `domains:` is real (the requested
97
+ * domain). Every other field is a placeholder the agent fills (op blocks
98
+ * sourced from api-probe({scaffold: true})). Fails closed: an unsaved,
99
+ * as-is template is rejected by the parser because `apiHost: <base url>`
100
+ * is not a valid URL — no wrong-API guide can be saved silently. */
101
+ function placeholderSkeleton(domain: string): string {
102
+ return `---
38
103
  kind: api
39
- domains: [boe.es, www.boe.es]
40
- organization: boe.es # optional — org identity across guides (registrable domain)
41
- description: Spanish official gazette legislation API. # optional — one-line summary; aids disambiguation
42
- icon: ⚖️
43
- shortName: BOE
44
- updated: 2026-07-15
45
- apiHost: https://apidatos.boe.es/v1
46
- verified: 2026-07-15
47
- docs: https://www.boe.es/datosabiertos/api/api.php
48
- gatherAllMax: 500
104
+ domains: [${domain}]
105
+ organization: <org> # optional — org identity across guides (registrable domain)
106
+ description: <one-line summary> # optional — one-line summary; aids disambiguation
107
+ icon: <emoji>
108
+ shortName: <short>
109
+ # updated / verified are stamped by the tool when omitted (defaults to today)
110
+ apiHost: <base url> # REQUIRED — base URL. Version in apiHost XOR in each path — never both (/v3/v3/items → 404)
111
+ # docs: <api docs url> # optional — API documentation URL
112
+ gatherAllMax: 1000 # omitted → 1000
49
113
 
50
114
  auth:
51
115
  kind: none
116
+ ${STATIC_KEY_BLOCK}
52
117
 
53
118
  pagination:
54
119
  style: offset-limit
55
120
  pageParam: page
56
121
  pageSizeParam: limit
57
122
  pageSize: 50
58
- itemsPath: data
123
+ itemsPath: results
59
124
 
60
125
  responseShape:
61
126
  format: json
62
127
  charset: utf-8
63
128
 
64
- operations:
65
- - name: searchDiary
66
- via: restGet
67
- path: /diario/{date}
68
- accept: json
69
- dateParams: # normalize a date QUERY param before sending (path tokens aren't reached by dateParams)
70
- since: yyyy-mm-dd
71
- params:
72
- date: # docs-only — describes the {date} path token; never a query param
73
- description: Diary date in yyyy-mm-dd form (e.g. 2026-07-15).
74
- since:
75
- description: Lower-bound publication date; ISO YYYY-MM-DD auto-converted to yyyy-mm-dd.
76
- limit:
77
- default: 50
78
- parse:
79
- format: xml
80
- charset: iso-8859-1
81
-
82
- - name: listConsolidada
83
- via: paginate
84
- path: /legislacion-consolidada
85
- accept: json
86
- pagination:
87
- style: cursor
88
- cursorParam: cursor
89
- cursorPath: pagination.nextCursor
90
- itemsPath: results
129
+ # Add one operation per endpoint here — source the block from
130
+ # api-probe({apiHost, path, scaffold: true}) (it drafts real ops with real
131
+ # values):
132
+ # operations:
133
+ # - name: <op>
134
+ # via: restGet
135
+ # path: /<path>
136
+ # accept: json
137
+ # # requiresAnyOf: [id, slug, code] # at least one of these params must be supplied
138
+ # params:
139
+ # id:
140
+ # description: <what id selects>
91
141
  ---
142
+
143
+ # Optional agent-instruction prose goes AFTER the closing --- and is surfaced
144
+ # to the reading agent (as "Guide notes" via api-guide): date formats, auth
145
+ # caveats, field semantics, endpoint quirks. Delete this note before saving.
92
146
  `;
147
+ }
148
+
149
+ /** Save-summary auth line — names the header→secret mapping (names only,
150
+ * never values: values live in the store). e.g.
151
+ * `static-key · Authorization ← secret apiKey (Bearer )`. */
152
+ function authSummary(auth: AuthConfig): string {
153
+ const parts: string[] = [];
154
+ for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
155
+ const prefix = auth.headerPrefixes?.[header];
156
+ parts.push(
157
+ `${header} ← secret ${secretName}${prefix === undefined ? "" : ` (${prefix})`}`,
158
+ );
159
+ }
160
+ for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
161
+ parts.push(`?${param} ← secret ${secretName}`);
162
+ }
163
+ return parts.length === 0
164
+ ? `Auth: ${auth.kind}`
165
+ : `Auth: ${auth.kind} · ${parts.join(", ")}`;
166
+ }
167
+
168
+ // ═══════════════════════════════════════════════════════════════════
169
+ // Authoring manual + templates
170
+ // ═══════════════════════════════════════════════════════════════════
171
+
172
+ /** Bare `api-learn()` output — the field reference + defaults + semantics
173
+ * manual. No recipe body (superseded by `{domain, new: true}`); points at
174
+ * the template entry point. */
175
+ const AUTHORING_MANUAL = [
176
+ "# API guide authoring manual",
177
+ "",
178
+ "💡 Start a new guide: call api-learn({domain: '<domain>', new: true}) — it returns a ",
179
+ " template with `domains` pre-filled. Discover the API's shape first with ",
180
+ " api-probe({apiHost, path, scaffold: true}) — it drafts a YAML operation block ",
181
+ " to paste into the template.",
182
+ "",
183
+ "## Required fields",
184
+ ` \`domains\` — list of domain names this guide applies to`,
185
+ ` \`apiHost\` — base URL. Version in apiHost XOR in each path — never both (see Key defaults)`,
186
+ ` \`operations\` — a LIST of operation mappings — at least one entry`,
187
+ ` \`operations[].name\` — unique operation name`,
188
+ ` \`operations[].via\` — "restGet" or "paginate"`,
189
+ ` \`operations[].path\` — path starting with /`,
190
+ "",
191
+ "## Key defaults",
192
+ ` \`apiHost\` — base URL. \`path\` is always resolved relative to it — \`joinUrl\` strips a leading \`/\`, so \`/items\` + \`apiHost: https://host/v3\` → \`https://host/v3/items\`. Keep the version in \`apiHost\` (e.g. \`https://api.example.com/v3\`) or leave it bare with the version in each \`path\` — pick one per guide; both at once doubles the segment (\`/v3/v3/items\` → 404)`,
193
+ ` \`auth\` — omitted → kind: none`,
194
+ ` \`verified\` — omitted → today's date`,
195
+ ` \`docs\` — optional API documentation URL (http/https); omitted → no docs line`,
196
+ ` \`gatherAllMax\` — omitted → 1000`,
197
+ ` \`responseShape\` — omitted → json/utf-8`,
198
+ ` \`operation.accept\` — omitted → json`,
199
+ "",
200
+ "## Optional fields (multi-recipe disambiguation)",
201
+ ` \`organization\` — org identity across guides (use the org's registrable domain, e.g. archive.org)`,
202
+ ` \`description\` — one-line API summary (≤${DESCRIPTION_MAX} chars); the primary signal when several guides share a domain`,
203
+ "",
204
+ "## Optional fields (operation-level)",
205
+ ` \`dateParams\` — normalize date QUERY params before sending: map name → iso8601 | yyyymmdd | yyyy-mm-dd (path tokens are documented via params.<token>.description; core dateParams does not reach path tokens)`,
206
+ ` \`helper\` — true → call this domain's local helper.ts for this op`,
207
+ ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
208
+ ` \`params.<token>.description\` — docs-only description for a {token} path param (format, e.g. 'yyyy-mm-dd'); never sent as a query param, shown in api-guide`,
209
+ ` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
210
+ ` \`params.<name>.default\` — value (any YAML scalar: string, number, boolean) used when the caller omits the param (verify runs the op with it; a \`required\`+\`default\` op is always verifiable without a verify.json sidecar)`,
211
+ ` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Members may not be \`required: true\` — a group member is a plain optional param (verify it via a verify.json sidecar value). Use \`required: true\` for a single-param constraint; \`requiresAnyOf\` is for two or more interchangeable params`,
212
+ ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
213
+ ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
214
+ "",
215
+ "## Auth",
216
+ ` \`kind: static-key\` — keyed-header auth mode (values live in the secrets store, never in the recipe):`,
217
+ ` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store, and each name must match exactly the one passed to /api secrets. Each \`requires\` / \`optional\` name must also appear as a secretRefs/secretQueryRefs value (parser-enforced).`,
218
+ " static-key (keyed APIs):",
219
+ ` \`secretRefs\` — { <header name>: <secret name> } ← header → secret direction`,
220
+ ` \`headerPrefixes\` — { <header>: "Bearer " } ← scheme prefix; store holds the raw token`,
221
+ ` \`requires\` — [<secret-name>] ← fail-closed if unprovisioned (literal name, must match the store)`,
222
+ "",
223
+ "## Executor semantics",
224
+ " Pagination:",
225
+ ` \`pagination.base\` seeds the page param for offset-limit/page styles (caller value wins, then \`base\`, then the param \`default\`); use \`base: 1\` for 1-based offset APIs`,
226
+ ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
227
+ "",
228
+ "## Guide prose (agent instructions)",
229
+ " After the closing `---`, optional plaintext guidance for the reading agent —",
230
+ " date formats, auth caveats, field semantics, endpoint quirks. Surfaced by",
231
+ " api-guide as 'Guide notes'.",
232
+ "",
233
+ "Call api-learn({domain: '<domain>', recipeFile: '<staged file path>'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
234
+ ].join("\n");
235
+
236
+ /** Manual section that governs a failing parser field — the validation-error
237
+ * closing line routes the author to the manual (gap 2). Ordered rules, first
238
+ * match wins; undefined → generic manual pointer. Names must match the
239
+ * `##` headings in AUTHORING_MANUAL above. */
240
+ const MANUAL_SECTION_RULES: ReadonlyArray<[RegExp, string]> = [
241
+ [/^auth(\.|$)/, "Auth"],
242
+ [/^operations(\[\d+\])?\.params(\.|$)/, "Optional fields (operation-level)"],
243
+ [/^operations(\[\d+\])?\.(via|name|path)$/, "Required fields"],
244
+ [
245
+ /^operations(\[\d+\])?\.(dateParams|helper|transform|passthrough|parse|requiresAnyOf)(\.|$)/,
246
+ "Optional fields (operation-level)",
247
+ ],
248
+ [/^operations(\[\d+\])?\.pagination(\.|$)/, "Executor semantics"],
249
+ [/^pagination(\.|$)/, "Executor semantics"],
250
+ [/^operations(\[\d+\])?\.(accept|gatherAllMax)(\.|$)/, "Key defaults"],
251
+ [/^responseShape(\.|$)/, "Key defaults"],
252
+ [
253
+ /^(organization|description)$/,
254
+ "Optional fields (multi-recipe disambiguation)",
255
+ ],
256
+ [/^(domains|apiHost|kind|operations)$/, "Required fields"],
257
+ [/^(verified|docs|gatherAllMax)$/, "Key defaults"],
258
+ ];
259
+
260
+ function manualSectionFor(field: string): string | undefined {
261
+ for (const [re, section] of MANUAL_SECTION_RULES) {
262
+ if (re.test(field)) return section;
263
+ }
264
+ return undefined;
265
+ }
266
+
267
+ /** Template path — write the placeholder skeleton to the staging path and
268
+ * surface the file path (the agent edits the file, not an inline copy).
269
+ * Fail-closed: the as-is template cannot save (placeholder `apiHost`
270
+ * is rejected by requireHttpUrl). */
271
+ function stageTemplate(domain: string): string {
272
+ const path = writeStagedDraft(domain, placeholderSkeleton(domain));
273
+ return (
274
+ `📝 Template for '${domain}' written to ${path}\n` +
275
+ ` Edit the file (or append ops via bash), then call ` +
276
+ `api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save.`
277
+ );
278
+ }
279
+
280
+ /** Fetch-recipe response — the saved guide's raw recipe staged to the
281
+ * staging path, with the file path + resolved dirName surfaced so re-save
282
+ * keys on the directory, not the routing domain (sibling-clobber
283
+ * mitigation). The inline YAML block is dropped: the staged file is the
284
+ * source of truth the agent edits. */
285
+ function stageFetchedRecipe(
286
+ domain: string,
287
+ guide: ApiGuide,
288
+ dirName: string,
289
+ ): AgentToolResult<unknown> {
290
+ const raw = readFileSync(
291
+ join(getUserGuidesDir(), dirName, "guide.md"),
292
+ "utf-8",
293
+ );
294
+ const path = writeStagedDraft(domain, raw);
295
+ return {
296
+ content: [
297
+ {
298
+ type: "text",
299
+ text:
300
+ `📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
301
+ ` Directory: ${dirName}\n` +
302
+ ` Staged draft: ${path}\n` +
303
+ ` To edit: edit the staged file with the edit tool or bash, then call ` +
304
+ `api-learn({domain: "${dirName}", recipeFile: "${path}"}) — pass the ` +
305
+ `directory name as \`domain\` on re-save so a sibling guide is not clobbered.`,
306
+ },
307
+ ],
308
+ details: { mode: "fetch", domain, dirName, guide: guide.shortName },
309
+ };
310
+ }
311
+
312
+ /** Disambiguation menu for the N-guide fetch-recipe case (mirrors
313
+ * api-guide's menu). */
314
+ function renderFetchMenu(
315
+ domain: string,
316
+ matches: { guide: ApiGuide; dirName: string }[],
317
+ ): AgentToolResult<unknown> {
318
+ const lines: string[] = [];
319
+ lines.push(`${matches.length} API guides for '${domain}':`);
320
+ lines.push(formatGuideListings(matches));
321
+ const example = matches[0]!.guide.shortName;
322
+ lines.push(
323
+ `Call api-learn({domain: "${domain}", guide: "${example}"}) to fetch one guide's recipe.`,
324
+ );
325
+ return {
326
+ content: [{ type: "text", text: lines.join("\n") }],
327
+ details: { mode: "menu", domain, disambiguation: matches.length },
328
+ };
329
+ }
93
330
 
94
331
  // ═══════════════════════════════════════════════════════════════════
95
332
  // Tool definition
@@ -99,84 +336,61 @@ export const apiLearnTool = defineTool({
99
336
  name: "api-learn",
100
337
  label: "API Learn",
101
338
  description:
102
- "Save or update an API guide for a domain. " +
103
- "The recipe is written in YAML frontmatter format. " +
104
- "Call with no params to see the worked example recipe and field reference.",
339
+ "Author an API guide for a domain. " +
340
+ "Call with no params for the authoring manual (field reference + defaults + semantics). " +
341
+ "Call with {domain, new: true} for a fresh domain-specific template. " +
342
+ "Call with {domain} and no recipeFile to fetch an existing guide's current raw recipe. " +
343
+ "Call with {domain, recipeFile} to validate and save.",
105
344
 
106
345
  parameters: Type.Object({
107
346
  domain: Type.Optional(
108
347
  Type.String({
109
348
  description:
110
- "Primary domain (e.g. 'boe.es'). Used as the filename. Omit to see the worked example.",
349
+ "Domain (e.g. 'example.com'). With `recipeFile` it's the save directory; " +
350
+ "with no recipeFile it's the routing domain for fetch-recipe lookup.",
111
351
  }),
112
352
  ),
113
- recipe: Type.Optional(
353
+ recipeFile: Type.Optional(
114
354
  Type.String({
115
355
  description:
116
- "Full recipe string including YAML frontmatter (---\\n...\\n---) and optional prose body. Required when domain is provided.",
356
+ "Path to the staged draft guide file (written by a prior api-learn fetch/template call to /tmp/pi-lean-host/<domain>/guide.md). " +
357
+ "Read, validated, and saved. Omit to fetch the current raw recipe of an existing guide (or get a template when none exists).",
358
+ }),
359
+ ),
360
+ guide: Type.Optional(
361
+ Type.String({
362
+ description:
363
+ "When a domain claims multiple guides, select one by shortName (shown in the disambiguation menu). " +
364
+ "Only used with the fetch-recipe path (no recipeFile).",
365
+ }),
366
+ ),
367
+ new: Type.Optional(
368
+ Type.Boolean({
369
+ description:
370
+ "true → return a fresh domain-specific template (domains pre-filled) regardless of existing guides. " +
371
+ "Does not touch any existing guide.",
117
372
  }),
118
373
  ),
119
374
  }),
120
375
 
121
376
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
122
- const { domain, recipe } = params as {
377
+ const {
378
+ domain,
379
+ recipeFile,
380
+ guide: guideSelector,
381
+ new: isNew,
382
+ } = params as {
123
383
  domain?: string;
124
- recipe?: string;
384
+ recipeFile?: string;
385
+ guide?: string;
386
+ new?: boolean;
125
387
  };
126
388
 
127
- // ── No domain → return worked example ────────────────────
389
+ // ── No domain → authoring manual ─────────────────────────
128
390
  if (!domain) {
129
- const text = [
130
- "# Example recipe — copy, edit, and call api-learn({domain: '...', recipe: '...'})",
131
- "",
132
- "💡 For a not-yet-guided API, discover its shape first with api-probe({apiHost, path, params}) ",
133
- " — it drafts a YAML operation block to paste straight into the recipe below.",
134
- "",
135
- "```yaml",
136
- WORKED_EXAMPLE,
137
- "```",
138
- "",
139
- "## Required fields",
140
- ` \`domains\` — list of domain names this guide applies to`,
141
- ` \`apiHost\` — base URL including version prefix`,
142
- ` \`operations\` — at least one operation mapping`,
143
- ` \`operations[].name\` — unique operation name`,
144
- ` \`operations[].via\` — "restGet" or "paginate"`,
145
- ` \`operations[].path\` — path starting with /`,
146
- "",
147
- "## Key defaults",
148
- ` \`apiHost\` — base URL. \`path\` is always resolved relative to it — \`joinUrl\` strips a leading \`/\`, so \`/items\` + \`apiHost: https://host/v3\` → \`https://host/v3/items\`. Keep the version in \`apiHost\` (worked-example style) or leave it bare with the version in each \`path\` — pick one per guide; both at once doubles the segment (\`/v3/v3/items\` → 404)`,
149
- ` \`auth\` — omitted → kind: none`,
150
- ` \`verified\` — omitted → today's date`,
151
- ` \`docs\` — optional API documentation URL (http/https); omitted → no docs line`,
152
- ` \`gatherAllMax\` — omitted → 1000`,
153
- ` \`responseShape\` — omitted → json/utf-8`,
154
- ` \`operation.accept\` — omitted → json`,
155
- "",
156
- "## Optional fields (multi-recipe disambiguation)",
157
- ` \`organization\` — org identity across guides (use the org's registrable domain, e.g. archive.org)`,
158
- ` \`description\` — one-line API summary (≤${DESCRIPTION_MAX} chars); the primary signal when several guides share a domain`,
159
- "",
160
- "## Optional fields (operation-level)",
161
- ` \`dateParams\` — normalize date QUERY params before sending: map name → iso8601 | yyyymmdd | yyyy-mm-dd (path tokens are documented via params.<token>.description; core dateParams does not reach path tokens)`,
162
- ` \`helper\` — true → call this domain's local helper.ts for this op`,
163
- ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
164
- ` \`params.<token>.description\` — docs-only description for a {token} path param (format, e.g. 'yyyy-mm-dd'); never sent as a query param, shown in api-guide`,
165
- ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
166
- ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
167
- "",
168
- "## Executor semantics",
169
- " Pagination:",
170
- ` \`pagination.base\` seeds the page param for offset-limit/page styles (caller value wins, then \`base\`, then the param \`default\`); use \`base: 1\` for 1-based offset APIs`,
171
- ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
172
- " Auth:",
173
- ` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store.`,
174
- "",
175
- "Call api-learn({domain: '...', recipe: '...'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
176
- ].join("\n");
177
391
  return {
178
- content: [{ type: "text", text }],
179
- details: {},
392
+ content: [{ type: "text", text: AUTHORING_MANUAL }],
393
+ details: { mode: "manual" },
180
394
  };
181
395
  }
182
396
 
@@ -195,16 +409,79 @@ export const apiLearnTool = defineTool({
195
409
  };
196
410
  }
197
411
 
198
- // ── Validate recipe ──────────────────────────────────────
199
- if (!recipe || !recipe.trim()) {
412
+ // ── new: true → fresh template regardless of existing guides ──
413
+ if (isNew) {
414
+ return {
415
+ content: [{ type: "text", text: stageTemplate(domain) }],
416
+ details: { mode: "template", domain },
417
+ };
418
+ }
419
+
420
+ // ── No recipeFile → fetch-recipe ─────────────────────────
421
+ // 0 guides → template staged; 1 guide → raw recipe staged + dirName
422
+ // surfaced; N guides → disambiguation menu (guide selector resolves it).
423
+ if (!recipeFile || !recipeFile.trim()) {
424
+ const matches = findGuidesByDomain(domain);
425
+ if (matches.length === 0) {
426
+ return {
427
+ content: [{ type: "text", text: stageTemplate(domain) }],
428
+ details: { mode: "template", domain },
429
+ };
430
+ }
431
+ if (matches.length === 1) {
432
+ const { guide, dirName } = matches[0]!;
433
+ return stageFetchedRecipe(domain, guide, dirName);
434
+ }
435
+ // N guides → disambiguation by shortName (mirrors api-guide).
436
+ if (!guideSelector) {
437
+ return renderFetchMenu(domain, matches);
438
+ }
439
+ const sel = selectGuideByShortName(matches, guideSelector);
440
+ if (!sel.ok) {
441
+ return {
442
+ content: [
443
+ {
444
+ type: "text",
445
+ text: shortNameErrorText(
446
+ sel,
447
+ domain,
448
+ guideSelector,
449
+ `Call api-learn({domain: "${domain}"}) to see the menu.`,
450
+ ),
451
+ },
452
+ ],
453
+ details:
454
+ sel.reason === "no_match"
455
+ ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
456
+ : {
457
+ error: "ambiguous_shortname",
458
+ domain,
459
+ guide: guideSelector,
460
+ directories: sel.directories,
461
+ },
462
+ };
463
+ }
464
+ return stageFetchedRecipe(domain, sel.guide, sel.dirName);
465
+ }
466
+
467
+ // ── Save from a staged file ─────────────────────────────
468
+ // Read the draft, then run the identical validate → stamp → write
469
+ // path. A missing/unreadable file is a clear error; guide.md untouched.
470
+ let recipe: string;
471
+ try {
472
+ recipe = readFileSync(recipeFile, "utf-8");
473
+ } catch {
200
474
  return {
201
475
  content: [
202
476
  {
203
477
  type: "text",
204
- text: `Recipe is required when domain is provided. Call api-learn() with no params to see the worked example.`,
478
+ text:
479
+ `⚠ Could not read recipe file '${recipeFile}' — guide was NOT saved.\n` +
480
+ ` Fetch the current recipe first via api-learn({domain: "${domain}"}) ` +
481
+ `(or a template with {domain, new: true}), then edit the staged file and save with recipeFile.`,
205
482
  },
206
483
  ],
207
- details: { error: "missing_recipe" },
484
+ details: { error: "recipe_file_unreadable", domain, recipeFile },
208
485
  };
209
486
  }
210
487
 
@@ -218,7 +495,13 @@ export const apiLearnTool = defineTool({
218
495
  ` Found: ${err.found}`,
219
496
  ];
220
497
  if (err.fix) lines.push(` Fix: ${err.fix}`);
498
+ const section = manualSectionFor(err.field);
221
499
  lines.push("");
500
+ lines.push(
501
+ section
502
+ ? `See the \`${section}\` section of the authoring manual — call api-learn() with no params.`
503
+ : `Call api-learn() with no params for the authoring manual.`,
504
+ );
222
505
  lines.push("Fix the recipe and call api-learn again.");
223
506
  return {
224
507
  content: [{ type: "text", text: lines.join("\n") }],
@@ -254,8 +537,14 @@ export const apiLearnTool = defineTool({
254
537
  // so the routing-vs-identity distinction is explicit.
255
538
  const warnings: string[] = [];
256
539
  const collidingDomains: string[] = [];
540
+ const collidingDirs: string[] = [];
257
541
  for (const d of parsed.guide.domains ?? []) {
258
542
  const existing = findGuidesByDomain(d);
543
+ for (const m of existing) {
544
+ if (m.dirName !== domain && !collidingDirs.includes(m.dirName)) {
545
+ collidingDirs.push(m.dirName);
546
+ }
547
+ }
259
548
  if (existing.some((m) => m.dirName !== domain)) {
260
549
  collidingDomains.push(d);
261
550
  }
@@ -270,6 +559,9 @@ export const apiLearnTool = defineTool({
270
559
  ` \`description:\` is absent — adding one is recommended when several guides share a domain (it's the primary disambiguation signal).`,
271
560
  );
272
561
  }
562
+ warnings.push(
563
+ ` If an existing guide is wrong, ask the user to run /api delete ${collidingDirs.join(" ")} to remove it (the agent has no delete tool).`,
564
+ );
273
565
  }
274
566
 
275
567
  // ── Write guide ──────────────────────────────────────────
@@ -278,7 +570,16 @@ export const apiLearnTool = defineTool({
278
570
  mkdirSync(domainDir, { recursive: true });
279
571
  const filepath = join(domainDir, "guide.md");
280
572
 
281
- writeFileSync(filepath, recipe, "utf-8");
573
+ // Stamp schemaVersion on save — each guide records the schema vintage
574
+ // it was authored against (the per-guide vintage that stale detection
575
+ // compares against). Line-level frontmatter edit; comments + key order
576
+ // preserved (no YAML round-trip).
577
+ const stamped = stampFrontmatterField(
578
+ recipe,
579
+ "schemaVersion",
580
+ String(GUIDE_SCHEMA_VERSION),
581
+ );
582
+ writeFileSync(filepath, stamped, "utf-8");
282
583
  invalidateCache(); // next api-fetch / api-guide read picks it up
283
584
 
284
585
  const opCount = parsed.guide.operations.length;
@@ -294,8 +595,9 @@ export const apiLearnTool = defineTool({
294
595
  `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
295
596
  ` Domain: ${domain}\n` +
296
597
  ` Operations: ${opCount} — ${opNames}\n` +
297
- ` Auth: ${parsed.guide.auth.kind}\n` +
598
+ ` ${authSummary(parsed.guide.auth)}\n` +
298
599
  ` Verified: ${parsed.guide.verified}\n` +
600
+ ` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
299
601
  `\n` +
300
602
  warningBlock +
301
603
  `Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
@@ -303,6 +605,7 @@ export const apiLearnTool = defineTool({
303
605
  },
304
606
  ],
305
607
  details: {
608
+ mode: "saved",
306
609
  filePath: filepath,
307
610
  domain,
308
611
  operations: opCount,
@@ -315,9 +618,11 @@ export const apiLearnTool = defineTool({
315
618
  const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
316
619
  if (args.domain) {
317
620
  parts.push(theme.fg("accent", `"${args.domain}"`));
318
- parts.push(theme.fg("dim", "📝"));
621
+ if (args.new) parts.push(theme.fg("dim", "✨new"));
622
+ else if (args.recipeFile) parts.push(theme.fg("dim", "📝"));
623
+ else parts.push(theme.fg("dim", "📖"));
319
624
  } else {
320
- parts.push(theme.fg("dim", "(example)"));
625
+ parts.push(theme.fg("dim", "(manual)"));
321
626
  }
322
627
  return new Text(parts.join(" "), 0, 0);
323
628
  },
@@ -329,15 +634,26 @@ export const apiLearnTool = defineTool({
329
634
  return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
330
635
  }
331
636
 
637
+ const mode = d?.mode as string | undefined;
332
638
  const domain = d?.domain as string | undefined;
333
639
  const opCount = d?.operations as number | undefined;
640
+ const dirName = d?.dirName as string | undefined;
641
+ const disambig = d?.disambiguation as number | undefined;
334
642
 
335
643
  let text: string;
336
- if (domain && opCount !== undefined) {
644
+ if (mode === "fetch" && dirName) {
645
+ text = theme.fg("accent", theme.bold(`📖 ${dirName}`));
646
+ text += " — fetched recipe";
647
+ } else if (mode === "template" && domain) {
648
+ text = theme.fg("accent", theme.bold(`📝 Template for ${domain}`));
649
+ } else if (mode === "menu" && domain) {
650
+ text = theme.fg("dim", theme.bold("📖 menu"));
651
+ text += ` — ${disambig ?? "?"} guides for ${domain}`;
652
+ } else if (domain && opCount !== undefined) {
337
653
  text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
338
654
  text += ` — ${opCount} ops`;
339
655
  } else {
340
- text = theme.fg("dim", "📝 Worked example");
656
+ text = theme.fg("dim", "📝 Authoring manual");
341
657
  }
342
658
 
343
659
  return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);