pi-lean-host 0.4.0 → 0.6.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.
@@ -13,20 +13,20 @@ import {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
  import { Type } from "@earendil-works/pi-ai";
15
15
  import { Text } from "@earendil-works/pi-tui";
16
- import { appendFooter, contentText } from "./utils.js";
16
+ import {
17
+ appendFooter,
18
+ disambiguationMenuResult,
19
+ shortNameErrorResult,
20
+ } from "./utils.js";
17
21
  import {
18
22
  loadAllGuides,
19
23
  findGuidesByDomain,
20
24
  getCatalogText,
21
25
  } from "../core/guide-store.js";
22
- import {
23
- formatGuideListings,
24
- selectGuideByShortName,
25
- shortNameErrorText,
26
- TODAY,
27
- staleSchemaLine,
28
- } from "../core/parse-api-guide.js";
26
+ import { TODAY } from "../core/parse-api-guide.js";
27
+ import { selectGuideByShortName } from "../core/guide-catalog.js";
29
28
  import { authStatusLine, canonicalStoreDomain } from "../core/auth.js";
29
+ import { INLINE_LIMIT } from "../core/response-spill.js";
30
30
  import type { ApiGuide } from "../core/api-guide-types.js";
31
31
 
32
32
  export const apiGuideTool = defineTool({
@@ -90,28 +90,12 @@ export const apiGuideTool = defineTool({
90
90
  if (guideSelector) {
91
91
  const sel = selectGuideByShortName(matches, guideSelector);
92
92
  if (!sel.ok) {
93
- return {
94
- content: [
95
- {
96
- type: "text",
97
- text: shortNameErrorText(
98
- sel,
99
- domain,
100
- guideSelector,
101
- `Call api-guide({domain: "${domain}"}) to see the menu.`,
102
- ),
103
- },
104
- ],
105
- details:
106
- sel.reason === "no_match"
107
- ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
108
- : {
109
- error: "ambiguous_shortname",
110
- domain,
111
- guide: guideSelector,
112
- directories: sel.directories,
113
- },
114
- };
93
+ return shortNameErrorResult(
94
+ sel,
95
+ domain,
96
+ guideSelector,
97
+ `Call api-guide({domain: "${domain}"}) to see the menu.`,
98
+ );
115
99
  }
116
100
  return renderGuideDetail(sel.guide, domain);
117
101
  }
@@ -121,7 +105,12 @@ export const apiGuideTool = defineTool({
121
105
  }
122
106
 
123
107
  // Multiple guides for one domain → disambiguation menu.
124
- return renderDisambiguationMenu(domain, matches);
108
+ return disambiguationMenuResult(
109
+ domain,
110
+ matches,
111
+ (shortName) =>
112
+ `Call api-guide({domain: "${domain}", guide: "${shortName}"}) for details.`,
113
+ );
125
114
  },
126
115
 
127
116
  renderCall(args, theme, _context) {
@@ -176,8 +165,6 @@ function renderGuideDetail(
176
165
  lines.push(` Domains: ${guide.domains?.join(", ") ?? "—"}`);
177
166
  lines.push(` Host: ${guide.apiHost}`);
178
167
  lines.push(` Verified: ${guide.verified} · Updated: ${guide.updated}`);
179
- const stale = staleSchemaLine(guide);
180
- if (stale) lines.push(stale);
181
168
  if (guide.docs) lines.push(` Docs: ${guide.docs}`);
182
169
  lines.push(` Auth: ${guide.auth.kind}`);
183
170
  // Auth status footer — shared with api-fetch. Metadata only (names,
@@ -216,6 +203,7 @@ function renderGuideDetail(
216
203
  if (spec.required) parts.push("required");
217
204
  if (spec.default !== undefined)
218
205
  parts.push(`default ${JSON.stringify(spec.default)}`);
206
+ if (spec.listStyle) parts.push(`(listStyle: ${spec.listStyle})`);
219
207
  return parts.join(" ");
220
208
  });
221
209
  lines.push(` params: ${rendered.join(", ")}`);
@@ -238,8 +226,19 @@ function renderGuideDetail(
238
226
  if (pagCfg) {
239
227
  const bits: string[] = [pagCfg.style];
240
228
  if (pagCfg.pageParam) bits.push(pagCfg.pageParam);
241
- if (pagCfg.pageSizeParam)
242
- bits.push(`${pagCfg.pageSizeParam}=${pagCfg.pageSize ?? 50}`);
229
+ if (pagCfg.pageSizeParam) {
230
+ // offset-limit/page: the executor fabricates 50 when nothing
231
+ // resolves (and advances row offsets by it) — rendering the
232
+ // fallback is honest there. Cursor's terminal fallback is
233
+ // omit (server default applies) — only render a size that
234
+ // will actually be sent.
235
+ const renderedSize =
236
+ pagCfg.style === "cursor" && pagCfg.pageSize === undefined
237
+ ? undefined
238
+ : String(pagCfg.pageSize ?? 50);
239
+ if (renderedSize !== undefined)
240
+ bits.push(`${pagCfg.pageSizeParam}=${renderedSize}`);
241
+ }
243
242
  if (pagCfg.base !== undefined) bits.push(`base=${pagCfg.base}`);
244
243
  lines.push(` pagination: ${bits.join(" ")}`);
245
244
  }
@@ -256,15 +255,14 @@ function renderGuideDetail(
256
255
  // budget api-fetch uses (INLINE_LIMIT) so a typical guide fits whole;
257
256
  // longer prose spills with a pointer rather than flooding context.
258
257
  if (guide.content) {
259
- const PROSE_LIMIT = 4000;
260
258
  const prose = guide.content.trim();
261
259
  lines.push("");
262
260
  lines.push("— Guide notes —");
263
- if (prose.length <= PROSE_LIMIT) {
261
+ if (prose.length <= INLINE_LIMIT) {
264
262
  lines.push(prose);
265
263
  } else {
266
- lines.push(prose.slice(0, PROSE_LIMIT));
267
- lines.push(`… (${prose.length - PROSE_LIMIT} more chars omitted)`);
264
+ lines.push(prose.slice(0, INLINE_LIMIT));
265
+ lines.push(`… (${prose.length - INLINE_LIMIT} more chars omitted)`);
268
266
  }
269
267
  }
270
268
 
@@ -283,31 +281,3 @@ function renderGuideDetail(
283
281
  },
284
282
  };
285
283
  }
286
-
287
- /**
288
- * Disambiguation menu for a domain claimed by more than one guide. Lists
289
- * each guide's shortName (+ description when present) and a truncated op-name
290
- * summary; the org header shows only when all matches share one organization.
291
- */
292
- function renderDisambiguationMenu(
293
- domain: string,
294
- matches: { guide: ApiGuide; dirName: string }[],
295
- ): AgentToolResult<unknown> {
296
- const orgs = new Set(
297
- matches.map((m) => m.guide.organization).filter((o): o is string => !!o),
298
- );
299
- const orgName = [...orgs][0];
300
- const orgPart =
301
- orgs.size === 1 && orgName ? ` (organization: ${orgName})` : "";
302
- const lines: string[] = [];
303
- lines.push(`${matches.length} API guides for '${domain}'${orgPart}:`);
304
- lines.push(formatGuideListings(matches));
305
- const example = matches[0]!.guide.shortName;
306
- lines.push(
307
- `Call api-guide({domain: "${domain}", guide: "${example}"}) for details.`,
308
- );
309
- return {
310
- content: [{ type: "text", text: lines.join("\n") }],
311
- details: { domain, disambiguation: matches.length },
312
- };
313
- }
@@ -27,7 +27,12 @@ import {
27
27
  } from "@earendil-works/pi-coding-agent";
28
28
  import { Type } from "@earendil-works/pi-ai";
29
29
  import { Text } from "@earendil-works/pi-tui";
30
- import { appendFooter, contentText } from "./utils.js";
30
+ import {
31
+ appendFooter,
32
+ contentText,
33
+ disambiguationMenuResult,
34
+ shortNameErrorResult,
35
+ } from "./utils.js";
31
36
  import {
32
37
  existsSync,
33
38
  mkdirSync,
@@ -37,16 +42,13 @@ import {
37
42
  rmSync,
38
43
  writeFileSync,
39
44
  } from "node:fs";
40
- import { tmpdir } from "node:os";
41
- import { basename, join, sep } from "node:path";
45
+ import { basename, join } from "node:path";
42
46
  import { pathToFileURL } from "node:url";
43
47
  import {
44
48
  parseApiGuide,
45
49
  stampFrontmatterField,
46
- formatGuideListings,
47
- selectGuideByShortName,
48
- shortNameErrorText,
49
50
  } from "../core/parse-api-guide.js";
51
+ import { selectGuideByShortName } from "../core/guide-catalog.js";
50
52
  import {
51
53
  GUIDE_SCHEMA_VERSION,
52
54
  type ApiGuide,
@@ -58,31 +60,10 @@ import {
58
60
  findGuidesByDomain,
59
61
  } from "../core/guide-store.js";
60
62
  import { assertSafeDomain, slug } from "../core/path-template.js";
63
+ import { stagingDirFor, isUnderStagingRoot } from "../core/staging.js";
61
64
 
62
- // ═══════════════════════════════════════════════════════════════════
63
- // Staged working copy (/tmp) — the draft the agent edits between saves
64
- // ═══════════════════════════════════════════════════════════════════
65
-
66
- let _stagingRoot = join(tmpdir(), "pi-lean-host");
67
-
68
- /** Test override — mirrors `setUserGuidesDir` so tests keep drafts out of
69
- * the real /tmp root. */
70
- export function setStagingRoot(dir: string): void {
71
- _stagingRoot = dir;
72
- }
73
-
74
- /** Deterministic staged dir: `<root>/<key>/`. The key is the requested
75
- * `domain` for templates (placeholder shortName) and `slug(shortName)` for
76
- * fetched recipes (which is the on-disk dirName). */
77
- function stagingDirFor(key: string): string {
78
- return join(_stagingRoot, key);
79
- }
80
-
81
- /** True when `p` is a staged dir under the staging root (the root itself
82
- * excluded — save must never try to rename the whole root). */
83
- function isUnderStagingRoot(p: string): boolean {
84
- return p !== _stagingRoot && p.startsWith(`${_stagingRoot}${sep}`);
85
- }
65
+ // Staged working copy (/tmp) — the draft the agent edits between saves.
66
+ // Root + helpers live in core/staging.js (shared with api-scaffold).
86
67
 
87
68
  /** Write the working copy (template or fetched raw recipe) to the staged
88
69
  * dir. Returns the staged *dir* path (multi-file — siblings write to the
@@ -113,14 +94,25 @@ const SIBLING_NAMES = [
113
94
  const DESCRIPTION_MAX = 200;
114
95
 
115
96
  /** Commented static-key auth block — the issue-#5 auth-wiring teaching,
116
- * API-agnostic, kept after the worked example retired. */
97
+ * API-agnostic, kept after the worked example retired. Nested SecretRef
98
+ * shape (v1): each ref is self-contained (secret + optional prefix/optional). */
117
99
  const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in the secrets store (/api secrets), never in the recipe:
118
100
  # kind: static-key
119
- # requires: [<secret-name>]
120
101
  # secretRefs:
121
- # Authorization: <secret-name> # header name → secret name (must match the name provisioned via /api secrets)
122
- # headerPrefixes:
123
- # Authorization: "Bearer "`;
102
+ # Authorization: # header name
103
+ # secret: <secret-name> # store name (must match /api secrets)
104
+ # prefix: "Bearer " # optional — prepended at fetch time
105
+ # optional: false # optional refs don't fail closed when absent`;
106
+
107
+ /** Commented oauth2 authorization_code block — mirrors the manual's worked
108
+ * example so the fresh template teaches the interactive-grant shape without
109
+ * the agent having to grep a sibling guide for the field names. */
110
+ const OAUTH2_AC_BLOCK = ` # OAuth2 API? Use kind: oauth2 — credentials are store names (/api secrets), minting via /api oauth <domain>:
111
+ # grant: authorization_code # or client_credentials (server-to-server: adds clientSecret, drops authorizeUrl)
112
+ # tokenUrl: https://…/oauth/token
113
+ # authorizeUrl: https://…/oauth/authorize # REQUIRED for authorization_code
114
+ # clientId: { secret: client_id }
115
+ # scopes: [read]`;
124
116
 
125
117
  /** Placeholder starter template — only `domains:` is real (the requested
126
118
  * domain). Every other field is a placeholder the agent fills (op blocks
@@ -131,6 +123,7 @@ function placeholderSkeleton(domain: string): string {
131
123
  return `---
132
124
  kind: api
133
125
  domains: [${domain}]
126
+ schemaVersion: ${GUIDE_SCHEMA_VERSION}
134
127
  organization: <org> # optional — org identity across guides (registrable domain)
135
128
  description: <one-line summary> # optional — one-line summary; aids disambiguation
136
129
  icon: <emoji>
@@ -143,6 +136,7 @@ gatherAllMax: 1000 # omitted → 1000
143
136
  auth:
144
137
  kind: none
145
138
  ${STATIC_KEY_BLOCK}
139
+ ${OAUTH2_AC_BLOCK}
146
140
 
147
141
  pagination:
148
142
  style: offset-limit
@@ -150,6 +144,14 @@ pagination:
150
144
  pageSizeParam: limit
151
145
  pageSize: 50
152
146
  itemsPath: results
147
+ # Path fields are dot-delimited. If the API's key itself contains a dot
148
+ # (OData's '@odata.nextLink' / '@iot.count' family), quote it as an atomic
149
+ # key or the dot splits the path and pagination silently misses:
150
+ # nextLinkPath: "['@odata.nextLink']" # single or double quotes
151
+ # For a cursor walk whose continuation value is an item field (derived-id
152
+ # cursor), declare the sort params on the op too — the executor serializes
153
+ # ONLY declared params, and an undeclared sort lets the API default apply,
154
+ # turning the walk into a moving feed that re-reads rows.
153
155
 
154
156
  responseShape:
155
157
  format: json
@@ -166,6 +168,8 @@ responseShape:
166
168
  # params:
167
169
  # id:
168
170
  # description: <what id selects>
171
+ # # listStyle: comma # array values serialize as comma | repeat | bracket — omit for single-valued
172
+ # # unknown params keys are a parse error (typo tripwire)
169
173
  ---
170
174
 
171
175
  # Optional agent-instruction prose goes AFTER the closing --- and is surfaced
@@ -176,15 +180,43 @@ responseShape:
176
180
 
177
181
  /** Save-summary auth line — names the header→secret mapping (names only,
178
182
  * never values: values live in the store). e.g.
179
- * `static-key · Authorization ← secret apiKey (Bearer )`. */
183
+ * `static-key · Authorization ← secret apiKey (Bearer )` or
184
+ * `oauth2 · grant client_credentials · clientId ← secret client_id`. */
180
185
  function authSummary(auth: AuthConfig): string {
181
186
  const parts: string[] = [];
182
- for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
183
- const prefix = auth.headerPrefixes?.[header];
184
- parts.push(`${header} ← secret ${secretName}${prefix ? ` (${prefix})` : ""}`);
185
- }
186
- for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
187
- parts.push(`?${param} ← secret ${secretName}`);
187
+ switch (auth.kind) {
188
+ case "static-key":
189
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
190
+ parts.push(
191
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
192
+ );
193
+ }
194
+ for (const [param, ref] of Object.entries(auth.secretQueryRefs ?? {})) {
195
+ parts.push(`?${param} ← secret ${ref.secret}`);
196
+ }
197
+ for (const [token, ref] of Object.entries(auth.secretPathRefs ?? {})) {
198
+ parts.push(`{${token}} ← secret ${ref.secret}`);
199
+ }
200
+ break;
201
+ case "oauth2":
202
+ parts.push(
203
+ `grant ${auth.grant} · clientId ← secret ${auth.clientId.secret}` +
204
+ (auth.clientSecret
205
+ ? ` · clientSecret ← secret ${auth.clientSecret.secret}`
206
+ : ""),
207
+ );
208
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
209
+ parts.push(
210
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
211
+ );
212
+ }
213
+ break;
214
+ case "none":
215
+ break;
216
+ default: {
217
+ const _exhaustive: never = auth;
218
+ throw new Error(`Unhandled auth kind: ${_exhaustive}`);
219
+ }
188
220
  }
189
221
  return parts.length === 0
190
222
  ? `Auth: ${auth.kind}`
@@ -195,6 +227,31 @@ function authSummary(auth: AuthConfig): string {
195
227
  // Authoring manual + templates
196
228
  // ═══════════════════════════════════════════════════════════════════
197
229
 
230
+ /** Worked oauth2 examples shown in the authoring manual — exported so the
231
+ * parse test proves they parse as-is (the teaching can't rot silently).
232
+ * Field semantics mirror validateOAuth2Auth's grant invariants. */
233
+ export const OAUTH2_CC_EXAMPLE = ` # client_credentials — server-to-server, no browser:
234
+ auth:
235
+ kind: oauth2
236
+ grant: client_credentials
237
+ tokenUrl: https://api.example.com/oauth/token
238
+ clientId: { secret: client_id }
239
+ clientSecret: { secret: client_secret } # parser-required for this grant
240
+ # scopes: [read]
241
+ # secretRefs: # extra headers beside the Bearer token
242
+ # Client-Id:
243
+ # secret: client_id`;
244
+
245
+ export const OAUTH2_AC_EXAMPLE = ` # authorization_code — interactive; human consents in their browser and pastes the redirect (/api oauth):
246
+ auth:
247
+ kind: oauth2
248
+ grant: authorization_code
249
+ tokenUrl: https://api.example.com/oauth/token
250
+ authorizeUrl: https://example.com/oauth/authorize # REQUIRED for this grant; rejected for client_credentials
251
+ clientId: { secret: client_id }
252
+ # clientSecret: { secret: client_secret } # confidential clients only; PKCE public clients omit it
253
+ scopes: [read]`;
254
+
198
255
  /** The field reference + defaults + semantics manual. Travels with the
199
256
  * pull-to-/tmp action — prepended to every staged draft (template or
200
257
  * fetched recipe) so the author sees it at the moment of authoring. */
@@ -211,7 +268,7 @@ const AUTHORING_MANUAL = [
211
268
  ` \`apiHost\` — base URL. Version in apiHost XOR in each path — never both (see Key defaults)`,
212
269
  ` \`operations\` — a LIST of operation mappings — at least one entry`,
213
270
  ` \`operations[].name\` — unique operation name`,
214
- ` \`operations[].via\` — "restGet" or "paginate"`,
271
+ ` \`operations[].via\` — "restGet" or "paginate" — both issue GETs; the plugin is read-only by design (writes have no schema representation)`,
215
272
  ` \`operations[].path\` — path starting with /`,
216
273
  "",
217
274
  "## Key defaults",
@@ -231,25 +288,41 @@ const AUTHORING_MANUAL = [
231
288
  ` \`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)`,
232
289
  ` \`helper\` — true → call this domain's local helper.ts for this op`,
233
290
  ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
291
+ ` \`errorPath\` — JSON path to a present-only-on-error envelope element in a 200 body (e.g. \`OAI-PMH.error\`); anything other than \`undefined\` there (including null/""/0/false) fails the call as an error — declare a path that exists ONLY on error (Flickr \`message\`, World Bank \`0.message\`); root paths (\`$\`, \`.\`), malformed paths, and ops whose effective format is \`text\` are parse errors`,
234
292
  ` \`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`,
235
293
  ` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
236
- ` \`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)`,
294
+ ` \`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; an array default additionally requires \`listStyle\` and must be non-empty)`,
295
+ ` \`params.<name>.listStyle\` — comma | repeat | bracket — how an array value serializes on the query string (comma → id=a,b; repeat → id=a&id=b; bracket → id[]=a); scalars ignore the field`,
237
296
  ` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Use it when the API identifies a resource by exactly one of several interchangeable params and rejects them together (id XOR symbol XOR slug — the "exclusive peers" 400). Members may not be \`required: true\` NOR carry a \`default\` (both parser-enforced) — a default would always fire alongside a caller-supplied sibling and cause the conflict. Use \`required: true\` for a single-param constraint; \`requiresAnyOf\` is for two or more interchangeable params`,
238
297
  ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
239
298
  ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
240
299
  "",
241
300
  "## Auth",
242
301
  ` \`kind: static-key\` — keyed-header auth mode (values live in the secrets store, never in the recipe):`,
243
- ` \`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).`,
302
+ ` \`kind: oauth2\` — OAuth2 (client_credentials / authorization_code); token minting via /api oauth <domain>. ALL oauth2 credentials are store names, never literals — a shippable guide must not bake in one app's registration:`,
303
+ ` \`clientId\` — { secret: <store name> } — the client id's secrets-store name (e.g. clientId: { secret: client_id })`,
304
+ ` \`clientSecret\` — { secret: <store name> } — parser-required for client_credentials; absent for authorization_code (PKCE public clients)`,
305
+ ` \`secretRefs\` — { <request header>: { secret: <store name>, prefix?, optional? } } — headers merged alongside the Bearer token (e.g. Twitch's Client-Id)`,
306
+ ` \`scopes\` — optional static scope list (e.g. scopes: [read])`,
307
+ ` \`tokenEndpointAuthMethod\` — client_secret_post (default) | client_secret_basic | none — how the client authenticates at the token endpoint; none = PKCE public client (no clientSecret)`,
308
+ ` \`paramStyle\` — bearer-header (default) | query (sends ?access_token=…)`,
309
+ ` \`revokeUrl\` — optional revocation endpoint`,
310
+ "",
311
+ " Worked examples — copy one and edit; store names must match /api secrets <domain>:",
312
+ OAUTH2_CC_EXAMPLE,
313
+ "",
314
+ OAUTH2_AC_EXAMPLE,
315
+ "",
244
316
  " static-key (keyed APIs):",
245
- ` \`secretRefs\` — { <header name>: <secret name> } ← header → secret direction`,
246
- ` \`headerPrefixes\` — { <header>: "Bearer " } ← scheme prefix; store holds the raw token`,
247
- ` \`requires\` — [<secret-name>] ← fail-closed if unprovisioned (literal name, must match the store)`,
317
+ ` \`secretRefs\` — { <header name>: { secret: <store name>, prefix?, optional? } } ← self-contained ref`,
318
+ ` \`secretQueryRefs\` — { <query param>: { secret: <store name>, optional? } } ← query-param injection`,
319
+ ` \`secretPathRefs\` — { <path token>: { secret: <store name> } } ← path-token injection (/bot{token}/getMe); required-only: no prefix/optional`,
320
+ ` \`optional: true\` on a ref → proceeds unauthenticated if absent; default (required) → fail-closed. Values live in the secrets store; the store name must match /api secrets exactly.`,
248
321
  "",
249
322
  "## Executor semantics",
250
323
  " Pagination:",
251
324
  ` \`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`,
252
- ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
325
+ ` Page-size resolution (offset-limit/page): caller value → op param \`default\` → \`pagination.pageSize\` → 50. Cursor: caller value → op param \`default\` → \`pagination.pageSize\` → omit (server default applies)`,
253
326
  "",
254
327
  "## Guide prose (agent instructions)",
255
328
  " After the closing `---`, optional plaintext guidance for the reading agent —",
@@ -343,25 +416,6 @@ function stageFetchedRecipe(
343
416
  };
344
417
  }
345
418
 
346
- /** Disambiguation menu for the N-guide fetch-recipe case (mirrors
347
- * api-guide's menu). */
348
- function renderFetchMenu(
349
- domain: string,
350
- matches: { guide: ApiGuide; dirName: string }[],
351
- ): AgentToolResult<unknown> {
352
- const lines: string[] = [];
353
- lines.push(`${matches.length} API guides for '${domain}':`);
354
- lines.push(formatGuideListings(matches));
355
- const example = matches[0]!.guide.shortName;
356
- lines.push(
357
- `Call api-learn({domain: "${domain}", guide: "${example}"}) to fetch one guide's recipe.`,
358
- );
359
- return {
360
- content: [{ type: "text", text: lines.join("\n") }],
361
- details: { mode: "menu", domain, disambiguation: matches.length },
362
- };
363
- }
364
-
365
419
  // ═══════════════════════════════════════════════════════════════════
366
420
  // Tool definition
367
421
  // ═══════════════════════════════════════════════════════════════════
@@ -469,34 +523,23 @@ export const apiLearnTool = defineTool({
469
523
  const { guide, dirName } = matches[0]!;
470
524
  return stageFetchedRecipe(domain, guide, dirName);
471
525
  }
472
- // N guides → disambiguation by shortName (mirrors api-guide).
526
+ // N guides → disambiguation by shortName (shared menu helper).
473
527
  if (!guideSelector) {
474
- return renderFetchMenu(domain, matches);
528
+ return disambiguationMenuResult(
529
+ domain,
530
+ matches,
531
+ (shortName) =>
532
+ `Call api-learn({domain: "${domain}", guide: "${shortName}"}) to fetch one guide's recipe.`,
533
+ );
475
534
  }
476
535
  const sel = selectGuideByShortName(matches, guideSelector);
477
536
  if (!sel.ok) {
478
- return {
479
- content: [
480
- {
481
- type: "text",
482
- text: shortNameErrorText(
483
- sel,
484
- domain,
485
- guideSelector,
486
- `Call api-learn({domain: "${domain}"}) to see the menu.`,
487
- ),
488
- },
489
- ],
490
- details:
491
- sel.reason === "no_match"
492
- ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
493
- : {
494
- error: "ambiguous_shortname",
495
- domain,
496
- guide: guideSelector,
497
- directories: sel.directories,
498
- },
499
- };
537
+ return shortNameErrorResult(
538
+ sel,
539
+ domain,
540
+ guideSelector,
541
+ `Call api-learn({domain: "${domain}"}) to see the menu.`,
542
+ );
500
543
  }
501
544
  return stageFetchedRecipe(domain, sel.guide, sel.dirName);
502
545
  }
@@ -523,7 +566,17 @@ export const apiLearnTool = defineTool({
523
566
  };
524
567
  }
525
568
 
526
- const parsed = parseApiGuide(recipe, { filename: domain });
569
+ // Stamp schemaVersion before validation: under the schemaVersion hard
570
+ // gate a recipe without a current stamp would fail validation before
571
+ // the stamp could land. Line-level frontmatter edit (comments + key
572
+ // order preserved); the write below persists the stamped text only on
573
+ // validation success.
574
+ const stamped = stampFrontmatterField(
575
+ recipe,
576
+ "schemaVersion",
577
+ String(GUIDE_SCHEMA_VERSION),
578
+ );
579
+ const parsed = parseApiGuide(stamped, { filename: domain });
527
580
  if (!parsed.ok) {
528
581
  const err = parsed.error;
529
582
  const lines: string[] = [
@@ -598,7 +651,7 @@ export const apiLearnTool = defineTool({
598
651
  if (divergent && existsSync(join(canonicalStaged, "guide.md"))) {
599
652
  const existing = parseApiGuide(
600
653
  readFileSync(join(canonicalStaged, "guide.md"), "utf-8"),
601
- { filename: slugged },
654
+ { file: join(canonicalStaged, "guide.md"), filename: slugged },
602
655
  );
603
656
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
604
657
  if (existingShort !== parsed.guide.shortName) {
@@ -673,6 +726,7 @@ export const apiLearnTool = defineTool({
673
726
  const filepath = join(domainDir, "guide.md");
674
727
  if (existsSync(filepath)) {
675
728
  const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
729
+ file: filepath,
676
730
  filename: slugged,
677
731
  });
678
732
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
@@ -847,15 +901,6 @@ export const apiLearnTool = defineTool({
847
901
 
848
902
  // ── Write guide + mirror siblings ───────────────────────
849
903
 
850
- // Stamp schemaVersion on save — each guide records the schema vintage
851
- // it was authored against (the per-guide vintage that stale detection
852
- // compares against). Line-level frontmatter edit; comments + key order
853
- // preserved (no YAML round-trip).
854
- const stamped = stampFrontmatterField(
855
- recipe,
856
- "schemaVersion",
857
- String(GUIDE_SCHEMA_VERSION),
858
- );
859
904
  writeFileSync(filepath, stamped, "utf-8");
860
905
 
861
906
  // Mirror the staged dir: present siblings overwrite the guides-dir