pi-lean-host 0.2.0 → 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 +113 -117
- package/core/api-guide-types.ts +39 -0
- package/core/api-toggle.ts +23 -1
- package/core/auth.ts +42 -5
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/guide-store.ts +0 -26
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +72 -24
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +491 -57
- package/core/path-template.ts +30 -1
- package/core/resolve-op.ts +222 -0
- package/core/secrets-command.ts +25 -2
- package/core/secrets-store.ts +11 -1
- package/core/ssrf-guard.ts +5 -0
- package/core/transport.ts +2 -16
- package/core/verify-command.ts +399 -0
- package/package.json +15 -1
- package/tools/api-fetch.ts +147 -233
- package/tools/api-guide.ts +35 -46
- package/tools/api-learn.ts +438 -125
- package/tools/api-probe.ts +501 -88
- package/tools/utils.ts +21 -0
package/tools/api-learn.ts
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* api-learn tool definition.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* -
|
|
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,84 +20,313 @@
|
|
|
12
20
|
* Mirrors portal's `web-learn`.
|
|
13
21
|
*/
|
|
14
22
|
|
|
15
|
-
import {
|
|
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
|
-
import {
|
|
19
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
29
|
+
import { appendFooter, contentText } from "./utils.js";
|
|
30
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
31
|
+
import { tmpdir } from "node:os";
|
|
20
32
|
import { join } from "node:path";
|
|
21
|
-
import {
|
|
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,
|
|
25
|
-
assertSafeDomain,
|
|
26
48
|
findGuidesByDomain,
|
|
27
49
|
} from "../core/guide-store.js";
|
|
50
|
+
import { assertSafeDomain } from "../core/path-template.js";
|
|
28
51
|
|
|
29
52
|
// ═══════════════════════════════════════════════════════════════════
|
|
30
|
-
//
|
|
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
|
-
|
|
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: [
|
|
40
|
-
organization:
|
|
41
|
-
description:
|
|
42
|
-
icon:
|
|
43
|
-
shortName:
|
|
44
|
-
updated
|
|
45
|
-
apiHost:
|
|
46
|
-
|
|
47
|
-
|
|
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:
|
|
123
|
+
itemsPath: results
|
|
59
124
|
|
|
60
125
|
responseShape:
|
|
61
126
|
format: json
|
|
62
127
|
charset: utf-8
|
|
63
128
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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,77 +336,61 @@ export const apiLearnTool = defineTool({
|
|
|
99
336
|
name: "api-learn",
|
|
100
337
|
label: "API Learn",
|
|
101
338
|
description:
|
|
102
|
-
"
|
|
103
|
-
"
|
|
104
|
-
"Call with
|
|
105
|
-
"
|
|
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.",
|
|
106
344
|
|
|
107
345
|
parameters: Type.Object({
|
|
108
346
|
domain: Type.Optional(
|
|
109
347
|
Type.String({
|
|
110
348
|
description:
|
|
111
|
-
"
|
|
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.",
|
|
112
351
|
}),
|
|
113
352
|
),
|
|
114
|
-
|
|
353
|
+
recipeFile: Type.Optional(
|
|
115
354
|
Type.String({
|
|
116
355
|
description:
|
|
117
|
-
"
|
|
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.",
|
|
118
372
|
}),
|
|
119
373
|
),
|
|
120
374
|
}),
|
|
121
375
|
|
|
122
376
|
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
123
|
-
const {
|
|
377
|
+
const {
|
|
378
|
+
domain,
|
|
379
|
+
recipeFile,
|
|
380
|
+
guide: guideSelector,
|
|
381
|
+
new: isNew,
|
|
382
|
+
} = params as {
|
|
124
383
|
domain?: string;
|
|
125
|
-
|
|
384
|
+
recipeFile?: string;
|
|
385
|
+
guide?: string;
|
|
386
|
+
new?: boolean;
|
|
126
387
|
};
|
|
127
388
|
|
|
128
|
-
// ── No domain →
|
|
389
|
+
// ── No domain → authoring manual ─────────────────────────
|
|
129
390
|
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
391
|
return {
|
|
171
|
-
content: [{ type: "text", text }],
|
|
172
|
-
details: {},
|
|
392
|
+
content: [{ type: "text", text: AUTHORING_MANUAL }],
|
|
393
|
+
details: { mode: "manual" },
|
|
173
394
|
};
|
|
174
395
|
}
|
|
175
396
|
|
|
@@ -181,26 +402,86 @@ export const apiLearnTool = defineTool({
|
|
|
181
402
|
content: [
|
|
182
403
|
{
|
|
183
404
|
type: "text",
|
|
184
|
-
text:
|
|
185
|
-
err instanceof Error
|
|
186
|
-
? err.message
|
|
187
|
-
: `Invalid domain '${domain}'.`,
|
|
405
|
+
text: err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
|
|
188
406
|
},
|
|
189
407
|
],
|
|
190
408
|
details: { error: "invalid_domain", domain },
|
|
191
409
|
};
|
|
192
410
|
}
|
|
193
411
|
|
|
194
|
-
// ──
|
|
195
|
-
if (
|
|
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 {
|
|
196
474
|
return {
|
|
197
475
|
content: [
|
|
198
476
|
{
|
|
199
477
|
type: "text",
|
|
200
|
-
text:
|
|
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.`,
|
|
201
482
|
},
|
|
202
483
|
],
|
|
203
|
-
details: { error: "
|
|
484
|
+
details: { error: "recipe_file_unreadable", domain, recipeFile },
|
|
204
485
|
};
|
|
205
486
|
}
|
|
206
487
|
|
|
@@ -214,7 +495,13 @@ export const apiLearnTool = defineTool({
|
|
|
214
495
|
` Found: ${err.found}`,
|
|
215
496
|
];
|
|
216
497
|
if (err.fix) lines.push(` Fix: ${err.fix}`);
|
|
498
|
+
const section = manualSectionFor(err.field);
|
|
217
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
|
+
);
|
|
218
505
|
lines.push("Fix the recipe and call api-learn again.");
|
|
219
506
|
return {
|
|
220
507
|
content: [{ type: "text", text: lines.join("\n") }],
|
|
@@ -250,8 +537,14 @@ export const apiLearnTool = defineTool({
|
|
|
250
537
|
// so the routing-vs-identity distinction is explicit.
|
|
251
538
|
const warnings: string[] = [];
|
|
252
539
|
const collidingDomains: string[] = [];
|
|
540
|
+
const collidingDirs: string[] = [];
|
|
253
541
|
for (const d of parsed.guide.domains ?? []) {
|
|
254
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
|
+
}
|
|
255
548
|
if (existing.some((m) => m.dirName !== domain)) {
|
|
256
549
|
collidingDomains.push(d);
|
|
257
550
|
}
|
|
@@ -266,6 +559,9 @@ export const apiLearnTool = defineTool({
|
|
|
266
559
|
` \`description:\` is absent — adding one is recommended when several guides share a domain (it's the primary disambiguation signal).`,
|
|
267
560
|
);
|
|
268
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
|
+
);
|
|
269
565
|
}
|
|
270
566
|
|
|
271
567
|
// ── Write guide ──────────────────────────────────────────
|
|
@@ -274,14 +570,22 @@ export const apiLearnTool = defineTool({
|
|
|
274
570
|
mkdirSync(domainDir, { recursive: true });
|
|
275
571
|
const filepath = join(domainDir, "guide.md");
|
|
276
572
|
|
|
277
|
-
|
|
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");
|
|
278
583
|
invalidateCache(); // next api-fetch / api-guide read picks it up
|
|
279
584
|
|
|
280
585
|
const opCount = parsed.guide.operations.length;
|
|
281
586
|
const opNames = parsed.guide.operations.map((o) => o.name).join(", ");
|
|
282
587
|
|
|
283
|
-
const warningBlock =
|
|
284
|
-
warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
|
|
588
|
+
const warningBlock = warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
|
|
285
589
|
|
|
286
590
|
return {
|
|
287
591
|
content: [
|
|
@@ -291,14 +595,17 @@ export const apiLearnTool = defineTool({
|
|
|
291
595
|
`📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${domain}/guide.md\n` +
|
|
292
596
|
` Domain: ${domain}\n` +
|
|
293
597
|
` Operations: ${opCount} — ${opNames}\n` +
|
|
294
|
-
`
|
|
598
|
+
` ${authSummary(parsed.guide.auth)}\n` +
|
|
295
599
|
` Verified: ${parsed.guide.verified}\n` +
|
|
600
|
+
` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
|
|
296
601
|
`\n` +
|
|
297
602
|
warningBlock +
|
|
298
|
-
`Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify
|
|
603
|
+
`Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
|
|
604
|
+
`\n⚠ Direct edits to guide.md are ignored until the next api-learn save (per-session cache). Re-run api-learn to apply changes.`,
|
|
299
605
|
},
|
|
300
606
|
],
|
|
301
607
|
details: {
|
|
608
|
+
mode: "saved",
|
|
302
609
|
filePath: filepath,
|
|
303
610
|
domain,
|
|
304
611
|
operations: opCount,
|
|
@@ -311,9 +618,11 @@ export const apiLearnTool = defineTool({
|
|
|
311
618
|
const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
|
|
312
619
|
if (args.domain) {
|
|
313
620
|
parts.push(theme.fg("accent", `"${args.domain}"`));
|
|
314
|
-
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", "📖"));
|
|
315
624
|
} else {
|
|
316
|
-
parts.push(theme.fg("dim", "(
|
|
625
|
+
parts.push(theme.fg("dim", "(manual)"));
|
|
317
626
|
}
|
|
318
627
|
return new Text(parts.join(" "), 0, 0);
|
|
319
628
|
},
|
|
@@ -325,24 +634,28 @@ export const apiLearnTool = defineTool({
|
|
|
325
634
|
return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
|
|
326
635
|
}
|
|
327
636
|
|
|
637
|
+
const mode = d?.mode as string | undefined;
|
|
328
638
|
const domain = d?.domain as string | undefined;
|
|
329
639
|
const opCount = d?.operations as number | undefined;
|
|
640
|
+
const dirName = d?.dirName as string | undefined;
|
|
641
|
+
const disambig = d?.disambiguation as number | undefined;
|
|
330
642
|
|
|
331
643
|
let text: string;
|
|
332
|
-
if (
|
|
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) {
|
|
333
653
|
text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
|
|
334
654
|
text += ` — ${opCount} ops`;
|
|
335
655
|
} else {
|
|
336
|
-
text = theme.fg("dim", "📝
|
|
656
|
+
text = theme.fg("dim", "📝 Authoring manual");
|
|
337
657
|
}
|
|
338
658
|
|
|
339
|
-
|
|
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);
|
|
659
|
+
return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);
|
|
347
660
|
},
|
|
348
661
|
});
|