pi-lean-host 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,320 @@
1
+ /**
2
+ * api-guide tool definition.
3
+ *
4
+ * Mirrors portal's `web-guide`:
5
+ * - No params → catalog of all guides (collapsed by `organization:`, healthy + ⚠ malformed).
6
+ * - `{domain}` → one match: detailed guide; multiple matches: disambiguation menu.
7
+ * - `{domain, guide}` → detailed guide selected by shortName (exact, case-insensitive).
8
+ */
9
+
10
+ import {
11
+ defineTool,
12
+ type AgentToolResult,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import { Type } from "@earendil-works/pi-ai";
15
+ import { Text } from "@earendil-works/pi-tui";
16
+ import { contentText, renderExpandedText } from "./utils.js";
17
+ import {
18
+ loadAllGuides,
19
+ findGuidesByDomain,
20
+ getCatalogText,
21
+ } from "../core/guide-store.js";
22
+ import { formatGuideListings, TODAY } from "../core/parse-api-guide.js";
23
+ import type { ApiGuide } from "../core/api-guide-types.js";
24
+
25
+ export const apiGuideTool = defineTool({
26
+ name: "api-guide",
27
+ label: "API Guide",
28
+ description:
29
+ "Get navigation guidance for a REST API. " +
30
+ "Call with a domain (e.g. 'boe.es') for a guide's detailed operation list, " +
31
+ "or with no parameter to list all available API guides.",
32
+
33
+ parameters: Type.Object({
34
+ domain: Type.Optional(
35
+ Type.String({
36
+ description:
37
+ "Domain to look up (e.g. 'boe.es'). Omit to list all API guides.",
38
+ }),
39
+ ),
40
+ guide: Type.Optional(
41
+ Type.String({
42
+ description:
43
+ "When multiple guides exist for a domain, select one by shortName " +
44
+ "(shown in the disambiguation menu). Omit to list all matches.",
45
+ }),
46
+ ),
47
+ }),
48
+
49
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
50
+ const { domain, guide: guideSelector } = params as {
51
+ domain?: string;
52
+ guide?: string;
53
+ };
54
+
55
+ if (!domain) {
56
+ const guideCount = Object.keys(loadAllGuides().guides).length;
57
+ return {
58
+ content: [{ type: "text", text: getCatalogText() }],
59
+ details: { guideCount },
60
+ };
61
+ }
62
+
63
+ const matches = findGuidesByDomain(domain);
64
+ if (matches.length === 0) {
65
+ const known = Object.keys(loadAllGuides().guides);
66
+ return {
67
+ content: [
68
+ {
69
+ type: "text",
70
+ text:
71
+ `No API guide for '${domain}'.` +
72
+ (known.length > 0 ? ` Known guides: ${known.join(", ")}.` : "") +
73
+ "\n\nCall api-guide with no params to list all guides, or api-learn({domain, recipe}) to author one.",
74
+ },
75
+ ],
76
+ details: {},
77
+ };
78
+ }
79
+
80
+ // `guide` selector: resolve by shortName exact, case-insensitive.
81
+ // No substring fallback — exact match is sufficient for v1 and avoids
82
+ // the unambiguous-or-error branch the substring path forces.
83
+ if (guideSelector) {
84
+ const lc = guideSelector.toLowerCase();
85
+ const selected = matches.filter(
86
+ (m) => m.guide.shortName.toLowerCase() === lc,
87
+ );
88
+ if (selected.length === 0) {
89
+ const valid = matches.map((m) => m.guide.shortName).join(", ");
90
+ return {
91
+ content: [
92
+ {
93
+ type: "text",
94
+ text:
95
+ `No guide named '${guideSelector}' for '${domain}'. ` +
96
+ `Available guides: ${valid}. ` +
97
+ `Call api-guide({domain: "${domain}"}) to see the menu.`,
98
+ },
99
+ ],
100
+ details: {
101
+ error: "no_guide_by_shortname",
102
+ domain,
103
+ guide: guideSelector,
104
+ },
105
+ };
106
+ }
107
+ if (selected.length > 1) {
108
+ const dirs = selected.map((s) => s.dirName).join(", ");
109
+ return {
110
+ content: [
111
+ {
112
+ type: "text",
113
+ text:
114
+ `Ambiguous guide '${guideSelector}' for '${domain}' — ` +
115
+ `${selected.length} guides share shortName '${guideSelector}' ` +
116
+ `(directories: ${dirs}). Rename one guide's shortName to ` +
117
+ `disambiguate. Call api-guide({domain: "${domain}"}) to see the menu.`,
118
+ },
119
+ ],
120
+ details: {
121
+ error: "ambiguous_shortname",
122
+ domain,
123
+ guide: guideSelector,
124
+ directories: selected.map((s) => s.dirName),
125
+ },
126
+ };
127
+ }
128
+ return renderGuideDetail(selected[0]!.guide, domain);
129
+ }
130
+
131
+ if (matches.length === 1) {
132
+ return renderGuideDetail(matches[0]!.guide, domain);
133
+ }
134
+
135
+ // Multiple guides for one domain → disambiguation menu.
136
+ return renderDisambiguationMenu(domain, matches);
137
+ },
138
+
139
+ renderCall(args, theme, _context) {
140
+ const parts: string[] = [theme.fg("toolTitle", theme.bold("api-guide "))];
141
+ if (args.domain) {
142
+ parts.push(theme.fg("accent", `"${args.domain}"`));
143
+ if (args.guide) parts.push(theme.fg("dim", `› ${args.guide}`));
144
+ } else {
145
+ parts.push(theme.fg("dim", "(catalog)"));
146
+ }
147
+ return new Text(parts.join(" "), 0, 0);
148
+ },
149
+
150
+ renderResult(result, { expanded, isPartial }, theme, _context) {
151
+ if (isPartial) return new Text(theme.fg("warning", "Loading…"), 0, 0);
152
+ const d = result.details as Record<string, unknown> | undefined;
153
+
154
+ const guideName = d?.guide as string | undefined;
155
+ const opCount = d?.operations as number | undefined;
156
+ const guideCount = d?.guideCount as number | undefined;
157
+ const disambig = d?.disambiguation as number | undefined;
158
+
159
+ let text: string;
160
+ if (disambig !== undefined) {
161
+ text = theme.fg("dim", theme.bold("📖 menu"));
162
+ text += ` — ${disambig} guides for ${d?.domain ?? "?"}`;
163
+ } else if (guideName && opCount !== undefined) {
164
+ text = theme.fg("accent", theme.bold(`📖 ${guideName}`));
165
+ text += ` — ${opCount} operations`;
166
+ } else if (guideCount !== undefined) {
167
+ text = theme.fg("dim", theme.bold("📖 catalog"));
168
+ text += ` — ${guideCount} guides`;
169
+ } else {
170
+ text = theme.fg("dim", "📖 No guide");
171
+ }
172
+
173
+ const content = contentText(result);
174
+ if (expanded) {
175
+ text += "\n";
176
+ text = renderExpandedText(text, theme, content, 800);
177
+ } else {
178
+ text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
179
+ }
180
+ return new Text(text, 0, 0);
181
+ },
182
+ });
183
+
184
+ // ════════════════════════════════════════════════════════════════════
185
+ // Detail + disambiguation renderers
186
+ // ════════════════════════════════════════════════════════════════════
187
+
188
+ /** Detailed operation list for a single resolved guide (today's render). */
189
+ function renderGuideDetail(
190
+ guide: ApiGuide,
191
+ domain: string,
192
+ ): AgentToolResult<unknown> {
193
+ const lines: string[] = [];
194
+ lines.push(`${guide.icon} ${guide.shortName} — API guide`);
195
+ lines.push(` Domains: ${guide.domains?.join(", ") ?? "—"}`);
196
+ lines.push(` Host: ${guide.apiHost}`);
197
+ lines.push(` Verified: ${guide.verified} · Updated: ${guide.updated}`);
198
+ if (guide.docs) lines.push(` Docs: ${guide.docs}`);
199
+ lines.push(` Auth: ${guide.auth.kind}`);
200
+ lines.push(
201
+ ` Response: ${guide.responseShape.format} (${guide.responseShape.charset})`,
202
+ );
203
+ if (guide.pagination) {
204
+ lines.push(` Pagination: ${guide.pagination.style}`);
205
+ lines.push(` Items path: ${guide.pagination.itemsPath}`);
206
+ }
207
+ lines.push("");
208
+ lines.push("Operations:");
209
+ for (const op of guide.operations) {
210
+ lines.push(` ${op.name}`);
211
+ lines.push(` via: ${op.via}`);
212
+ lines.push(` path: ${op.path}`);
213
+ // Path-param docs — `{token}` semantics (format, example values).
214
+ // Declared as `params.<token>.description`; shown next to the path
215
+ // line since the token lives in the path, not the query string.
216
+ if (op.pathParamDocs && Object.keys(op.pathParamDocs).length > 0) {
217
+ for (const [token, desc] of Object.entries(op.pathParamDocs)) {
218
+ lines.push(` {${token}}: ${desc.replace(/\s+/g, " ").trim()}`);
219
+ }
220
+ }
221
+ const pathParamSet = new Set(op.pathParams);
222
+ const qParams = Object.entries(op.params).filter(
223
+ ([k]) => !pathParamSet.has(k),
224
+ );
225
+ if (qParams.length > 0) {
226
+ const rendered = qParams.map(([k, spec]) => {
227
+ const parts = [k];
228
+ if (spec.required) parts.push("required");
229
+ if (spec.default !== undefined)
230
+ parts.push(`default ${JSON.stringify(spec.default)}`);
231
+ return parts.join(" ");
232
+ });
233
+ lines.push(` params: ${rendered.join(", ")}`);
234
+ // Per-param hints (format, semantics) — these are the model's
235
+ // primary guidance for shaping values, so they get their own lines.
236
+ for (const [k, spec] of qParams) {
237
+ if (spec.description) {
238
+ lines.push(
239
+ ` ${k}: ${spec.description.replace(/\s+/g, " ").trim()}`,
240
+ );
241
+ }
242
+ }
243
+ }
244
+ if (op.via === "paginate") {
245
+ const pagCfg = op.pagination ?? guide.pagination;
246
+ if (pagCfg) {
247
+ const bits: string[] = [pagCfg.style];
248
+ if (pagCfg.pageParam) bits.push(pagCfg.pageParam);
249
+ if (pagCfg.pageSizeParam)
250
+ bits.push(`${pagCfg.pageSizeParam}=${pagCfg.pageSize ?? 50}`);
251
+ lines.push(` pagination: ${bits.join(" ")}`);
252
+ }
253
+ }
254
+ }
255
+ lines.push("");
256
+ lines.push(
257
+ `Call api-fetch({domain: "${domain}", operation: "<name>", params: {...}}) to execute.`,
258
+ );
259
+
260
+ // Surface the guide's prose (date formats, query semantics, field
261
+ // lists, etc.) — this is the author's documentation and otherwise
262
+ // never reaches the model via api-guide. Capped at the same inline
263
+ // budget api-fetch uses (INLINE_LIMIT) so a typical guide fits whole;
264
+ // longer prose spills with a pointer rather than flooding context.
265
+ if (guide.content) {
266
+ const PROSE_LIMIT = 4000;
267
+ const prose = guide.content.trim();
268
+ lines.push("");
269
+ lines.push("— Guide notes —");
270
+ if (prose.length <= PROSE_LIMIT) {
271
+ lines.push(prose);
272
+ } else {
273
+ lines.push(prose.slice(0, PROSE_LIMIT));
274
+ lines.push(`… (${prose.length - PROSE_LIMIT} more chars omitted)`);
275
+ }
276
+ }
277
+
278
+ const currentDate = TODAY();
279
+ lines.push(
280
+ `\n_Guide updated: ${guide.updated} · Current date: ${currentDate} · Source: ${guide.source}_`,
281
+ );
282
+
283
+ return {
284
+ content: [{ type: "text", text: lines.join("\n") }],
285
+ details: {
286
+ guide: guide.shortName,
287
+ domains: guide.domains,
288
+ apiHost: guide.apiHost,
289
+ operations: guide.operations.length,
290
+ },
291
+ };
292
+ }
293
+
294
+ /**
295
+ * Disambiguation menu for a domain claimed by more than one guide. Lists
296
+ * each guide's shortName (+ description when present) and a truncated op-name
297
+ * summary; the org header shows only when all matches share one organization.
298
+ */
299
+ function renderDisambiguationMenu(
300
+ domain: string,
301
+ matches: { guide: ApiGuide; dirName: string }[],
302
+ ): AgentToolResult<unknown> {
303
+ const orgs = new Set(
304
+ matches.map((m) => m.guide.organization).filter((o): o is string => !!o),
305
+ );
306
+ const orgName = [...orgs][0];
307
+ const orgPart =
308
+ orgs.size === 1 && orgName ? ` (organization: ${orgName})` : "";
309
+ const lines: string[] = [];
310
+ lines.push(`${matches.length} API guides for '${domain}'${orgPart}:`);
311
+ lines.push(formatGuideListings(matches));
312
+ const example = matches[0]!.guide.shortName;
313
+ lines.push(
314
+ `Call api-guide({domain: "${domain}", guide: "${example}"}) for details.`,
315
+ );
316
+ return {
317
+ content: [{ type: "text", text: lines.join("\n") }],
318
+ details: { domain, disambiguation: matches.length },
319
+ };
320
+ }
@@ -0,0 +1,348 @@
1
+ /**
2
+ * api-learn tool definition.
3
+ *
4
+ * Validates and writes an API guide recipe.
5
+ * - `{domain, recipe}` → validates via `parseApiGuide()`, writes to
6
+ * `~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`.
7
+ * - No `domain` → returns the worked-example recipe for authoring.
8
+ *
9
+ * No half-write on validation error (validate first, write only on success).
10
+ * Defaults are filled by the validator before writing.
11
+ *
12
+ * Mirrors portal's `web-learn`.
13
+ */
14
+
15
+ import { defineTool } from "@earendil-works/pi-coding-agent";
16
+ import { Type } from "@earendil-works/pi-ai";
17
+ import { Text } from "@earendil-works/pi-tui";
18
+ import { contentText, renderExpandedText } from "./utils.js";
19
+ import { mkdirSync, writeFileSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ import { parseApiGuide } from "../core/parse-api-guide.js";
22
+ import {
23
+ invalidateCache,
24
+ getUserGuidesDir,
25
+ assertSafeDomain,
26
+ findGuidesByDomain,
27
+ } from "../core/guide-store.js";
28
+
29
+ // ═══════════════════════════════════════════════════════════════════
30
+ // Worked example
31
+ // ═══════════════════════════════════════════════════════════════════
32
+
33
+ /** Max length for `description:` enforced on the write path (strict-on-write,
34
+ * lenient-on-read — the loader accepts any length). One-liner, not prose. */
35
+ const DESCRIPTION_MAX = 200;
36
+
37
+ const WORKED_EXAMPLE = `---
38
+ 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
49
+
50
+ auth:
51
+ kind: none
52
+
53
+ pagination:
54
+ style: offset-limit
55
+ pageParam: page
56
+ pageSizeParam: limit
57
+ pageSize: 50
58
+ itemsPath: data
59
+
60
+ responseShape:
61
+ format: json
62
+ charset: utf-8
63
+
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
91
+ ---
92
+ `;
93
+
94
+ // ═══════════════════════════════════════════════════════════════════
95
+ // Tool definition
96
+ // ═══════════════════════════════════════════════════════════════════
97
+
98
+ export const apiLearnTool = defineTool({
99
+ name: "api-learn",
100
+ label: "API Learn",
101
+ 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. " +
105
+ "Requires /api learn to be active.",
106
+
107
+ parameters: Type.Object({
108
+ domain: Type.Optional(
109
+ Type.String({
110
+ description:
111
+ "Primary domain (e.g. 'boe.es'). Used as the filename. Omit to see the worked example.",
112
+ }),
113
+ ),
114
+ recipe: Type.Optional(
115
+ Type.String({
116
+ description:
117
+ "Full recipe string including YAML frontmatter (---\\n...\\n---) and optional prose body. Required when domain is provided.",
118
+ }),
119
+ ),
120
+ }),
121
+
122
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
123
+ const { domain, recipe } = params as {
124
+ domain?: string;
125
+ recipe?: string;
126
+ };
127
+
128
+ // ── No domain → return worked example ────────────────────
129
+ if (!domain) {
130
+ const text = [
131
+ "# Example recipe — copy, edit, and call api-learn({domain: '...', recipe: '...'})",
132
+ "",
133
+ "💡 For a not-yet-guided API, discover its shape first with api-probe({apiHost, path, params}) ",
134
+ " — it drafts a YAML operation block to paste straight into the recipe below.",
135
+ "",
136
+ "```yaml",
137
+ WORKED_EXAMPLE,
138
+ "```",
139
+ "",
140
+ "## Required fields",
141
+ ` \`domains\` — list of domain names this guide applies to`,
142
+ ` \`apiHost\` — base URL including version prefix`,
143
+ ` \`operations\` — at least one operation mapping`,
144
+ ` \`operations[].name\` — unique operation name`,
145
+ ` \`operations[].via\` — "restGet" or "paginate"`,
146
+ ` \`operations[].path\` — path starting with /`,
147
+ "",
148
+ "## Key defaults",
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
+ "Call api-learn({domain: '...', recipe: '...'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
169
+ ].join("\n");
170
+ return {
171
+ content: [{ type: "text", text }],
172
+ details: {},
173
+ };
174
+ }
175
+
176
+ // ── Validate domain (path-traversal guard) ─────────────
177
+ try {
178
+ assertSafeDomain(domain);
179
+ } catch (err) {
180
+ return {
181
+ content: [
182
+ {
183
+ type: "text",
184
+ text:
185
+ err instanceof Error
186
+ ? err.message
187
+ : `Invalid domain '${domain}'.`,
188
+ },
189
+ ],
190
+ details: { error: "invalid_domain", domain },
191
+ };
192
+ }
193
+
194
+ // ── Validate recipe ──────────────────────────────────────
195
+ if (!recipe || !recipe.trim()) {
196
+ return {
197
+ content: [
198
+ {
199
+ type: "text",
200
+ text: `Recipe is required when domain is provided. Call api-learn() with no params to see the worked example.`,
201
+ },
202
+ ],
203
+ details: { error: "missing_recipe" },
204
+ };
205
+ }
206
+
207
+ const parsed = parseApiGuide(recipe, { filename: domain });
208
+ if (!parsed.ok) {
209
+ const err = parsed.error;
210
+ const lines: string[] = [
211
+ `⚠ Validation error — guide was NOT saved.`,
212
+ ` Field: ${err.field}`,
213
+ ` Expected: ${err.expected}`,
214
+ ` Found: ${err.found}`,
215
+ ];
216
+ if (err.fix) lines.push(` Fix: ${err.fix}`);
217
+ lines.push("");
218
+ lines.push("Fix the recipe and call api-learn again.");
219
+ return {
220
+ content: [{ type: "text", text: lines.join("\n") }],
221
+ details: { error: "validation_error", field: err.field },
222
+ };
223
+ }
224
+
225
+ // ── Post-parse authoring policy (strict-on-write) ───────
226
+ // `description:` length cap. The parser validates structure only
227
+ // (non-empty, single line); conciseness is an api-learn policy so the
228
+ // one-parser invariant stays intact. Reject before writing.
229
+ const desc = parsed.guide.description;
230
+ if (desc !== undefined && desc.length > DESCRIPTION_MAX) {
231
+ return {
232
+ content: [
233
+ {
234
+ type: "text",
235
+ text:
236
+ `⚠ description: is too long — guide was NOT saved.\n` +
237
+ ` Length: ${desc.length} chars (max ${DESCRIPTION_MAX}).\n` +
238
+ ` Keep description to one line; put longer prose in the guide body (after ---).`,
239
+ },
240
+ ],
241
+ details: { error: "description_too_long", length: desc.length },
242
+ };
243
+ }
244
+
245
+ // Collision detection — another guide (different directory) already
246
+ // claims one of this guide's `domains:` keys. Valid (that's the whole
247
+ // point of multi-recipe), but warn so the author knows they're in
248
+ // disambiguation territory. Updating the same directory is NOT a
249
+ // collision. Names both the directory and the colliding `domains:` key
250
+ // so the routing-vs-identity distinction is explicit.
251
+ const warnings: string[] = [];
252
+ const collidingDomains: string[] = [];
253
+ for (const d of parsed.guide.domains ?? []) {
254
+ const existing = findGuidesByDomain(d);
255
+ if (existing.some((m) => m.dirName !== domain)) {
256
+ collidingDomains.push(d);
257
+ }
258
+ }
259
+ if (collidingDomains.length > 0) {
260
+ const keys = collidingDomains.join(", ");
261
+ warnings.push(
262
+ `⚠ Multi-recipe: writing to directory \`${domain}\`, but \`domains:\` declares [${keys}] which another guide already claims — disambiguation menu applies. Give each guide a distinct \`shortName\`.`,
263
+ );
264
+ if (desc === undefined) {
265
+ warnings.push(
266
+ ` \`description:\` is absent — adding one is recommended when several guides share a domain (it's the primary disambiguation signal).`,
267
+ );
268
+ }
269
+ }
270
+
271
+ // ── Write guide ──────────────────────────────────────────
272
+ const guidesDir = getUserGuidesDir();
273
+ const domainDir = join(guidesDir, domain);
274
+ mkdirSync(domainDir, { recursive: true });
275
+ const filepath = join(domainDir, "guide.md");
276
+
277
+ writeFileSync(filepath, recipe, "utf-8");
278
+ invalidateCache(); // next api-fetch / api-guide read picks it up
279
+
280
+ const opCount = parsed.guide.operations.length;
281
+ const opNames = parsed.guide.operations.map((o) => o.name).join(", ");
282
+
283
+ const warningBlock =
284
+ warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
285
+
286
+ return {
287
+ content: [
288
+ {
289
+ type: "text",
290
+ text:
291
+ `📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
292
+ ` Domain: ${domain}\n` +
293
+ ` Operations: ${opCount} — ${opNames}\n` +
294
+ ` Auth: ${parsed.guide.auth.kind}\n` +
295
+ ` Verified: ${parsed.guide.verified}\n` +
296
+ `\n` +
297
+ warningBlock +
298
+ `Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.`,
299
+ },
300
+ ],
301
+ details: {
302
+ filePath: filepath,
303
+ domain,
304
+ operations: opCount,
305
+ verified: parsed.guide.verified,
306
+ },
307
+ };
308
+ },
309
+
310
+ renderCall(args, theme, _context) {
311
+ const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
312
+ if (args.domain) {
313
+ parts.push(theme.fg("accent", `"${args.domain}"`));
314
+ parts.push(theme.fg("dim", "📝"));
315
+ } else {
316
+ parts.push(theme.fg("dim", "(example)"));
317
+ }
318
+ return new Text(parts.join(" "), 0, 0);
319
+ },
320
+
321
+ renderResult(result, { expanded, isPartial }, theme, _context) {
322
+ if (isPartial) return new Text(theme.fg("warning", "Saving…"), 0, 0);
323
+ const d = result.details as Record<string, unknown> | undefined;
324
+ if (d?.error) {
325
+ return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
326
+ }
327
+
328
+ const domain = d?.domain as string | undefined;
329
+ const opCount = d?.operations as number | undefined;
330
+
331
+ let text: string;
332
+ if (domain && opCount !== undefined) {
333
+ text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
334
+ text += ` — ${opCount} ops`;
335
+ } else {
336
+ text = theme.fg("dim", "📝 Worked example");
337
+ }
338
+
339
+ const content = contentText(result);
340
+ if (expanded) {
341
+ text += "\n";
342
+ text = renderExpandedText(text, theme, content, 600);
343
+ } else {
344
+ text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
345
+ }
346
+ return new Text(text, 0, 0);
347
+ },
348
+ });