pi-lean-host 0.3.0 → 0.4.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 +101 -54
- package/core/api-guide-types.ts +14 -0
- package/core/api-toggle.ts +9 -9
- package/core/guide-store.ts +20 -5
- package/core/helpers-command.ts +6 -5
- package/core/helpers.ts +22 -6
- package/core/local-helpers.ts +10 -2
- package/core/parse-api-guide.ts +241 -84
- package/core/path-template.ts +46 -0
- package/core/status-hint.ts +61 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +124 -53
- package/index.ts +16 -1
- package/package.json +3 -1
- package/tools/api-fetch.ts +4 -3
- package/tools/api-guide.ts +1 -1
- package/tools/api-learn.ts +447 -147
- package/tools/api-probe.ts +44 -178
- package/tools/api-scaffold.ts +420 -0
- package/tools/index.ts +2 -1
package/tools/api-learn.ts
CHANGED
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
* api-learn tool definition.
|
|
3
3
|
*
|
|
4
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
5
|
* - `{domain, new: true}` → fresh template with `domains: [<domain>]`
|
|
8
6
|
* pre-filled (regardless of existing guides).
|
|
9
|
-
* - `{domain}` (no
|
|
7
|
+
* - `{domain}` (no dir) → fetch the current raw recipe of an existing
|
|
10
8
|
* guide (0 guides → template; 1 guide → raw recipe + dirName surfaced;
|
|
11
9
|
* N guides → disambiguation menu by shortName), staged to
|
|
12
|
-
* `/tmp/pi-lean-host/<
|
|
13
|
-
* - `{domain,
|
|
10
|
+
* `/tmp/pi-lean-host/<slug(shortName)>/` (guide.md + present siblings).
|
|
11
|
+
* - `{domain, dir}` → reads the staged directory (guide.md required,
|
|
12
|
+
* helper.ts / verify.json siblings mirrored), validates via
|
|
14
13
|
* `parseApiGuide()`, writes to
|
|
15
|
-
* `~/.pi/agent/pi-lean-host/api-guides/<
|
|
14
|
+
* `~/.pi/agent/pi-lean-host/api-guides/<slug(shortName)>/` —
|
|
15
|
+
* the write target is a function of the guide's own `shortName`, never
|
|
16
|
+
* the `domain` arg (the arg is cosmetic on the save branch).
|
|
16
17
|
*
|
|
17
18
|
* No half-write on validation error (validate first, write only on success).
|
|
18
19
|
* Defaults are filled by the validator before writing.
|
|
@@ -27,9 +28,18 @@ import {
|
|
|
27
28
|
import { Type } from "@earendil-works/pi-ai";
|
|
28
29
|
import { Text } from "@earendil-works/pi-tui";
|
|
29
30
|
import { appendFooter, contentText } from "./utils.js";
|
|
30
|
-
import {
|
|
31
|
+
import {
|
|
32
|
+
existsSync,
|
|
33
|
+
mkdirSync,
|
|
34
|
+
readFileSync,
|
|
35
|
+
readdirSync,
|
|
36
|
+
renameSync,
|
|
37
|
+
rmSync,
|
|
38
|
+
writeFileSync,
|
|
39
|
+
} from "node:fs";
|
|
31
40
|
import { tmpdir } from "node:os";
|
|
32
|
-
import { join } from "node:path";
|
|
41
|
+
import { basename, join, sep } from "node:path";
|
|
42
|
+
import { pathToFileURL } from "node:url";
|
|
33
43
|
import {
|
|
34
44
|
parseApiGuide,
|
|
35
45
|
stampFrontmatterField,
|
|
@@ -47,7 +57,7 @@ import {
|
|
|
47
57
|
getUserGuidesDir,
|
|
48
58
|
findGuidesByDomain,
|
|
49
59
|
} from "../core/guide-store.js";
|
|
50
|
-
import { assertSafeDomain } from "../core/path-template.js";
|
|
60
|
+
import { assertSafeDomain, slug } from "../core/path-template.js";
|
|
51
61
|
|
|
52
62
|
// ═══════════════════════════════════════════════════════════════════
|
|
53
63
|
// Staged working copy (/tmp) — the draft the agent edits between saves
|
|
@@ -61,20 +71,39 @@ export function setStagingRoot(dir: string): void {
|
|
|
61
71
|
_stagingRoot = dir;
|
|
62
72
|
}
|
|
63
73
|
|
|
64
|
-
/** Deterministic
|
|
65
|
-
|
|
66
|
-
|
|
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}`);
|
|
67
85
|
}
|
|
68
86
|
|
|
69
|
-
/** Write the working copy (template or fetched raw recipe) to the
|
|
70
|
-
*
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
87
|
+
/** Write the working copy (template or fetched raw recipe) to the staged
|
|
88
|
+
* dir. Returns the staged *dir* path (multi-file — siblings write to the
|
|
89
|
+
* same dir). */
|
|
90
|
+
function writeStagedDraft(key: string, raw: string): string {
|
|
91
|
+
const dir = stagingDirFor(key);
|
|
92
|
+
mkdirSync(dir, { recursive: true });
|
|
93
|
+
writeFileSync(join(dir, "guide.md"), raw, "utf-8");
|
|
94
|
+
return dir;
|
|
76
95
|
}
|
|
77
96
|
|
|
97
|
+
/** Sibling artifact names mirrored between the staged dir and the guides
|
|
98
|
+
* dir on save (guide.md is always written). The helper extension set mirrors
|
|
99
|
+
* core/local-helpers.ts's `findHelperFile` resolution (.ts → .mjs → .js). */
|
|
100
|
+
const SIBLING_NAMES = [
|
|
101
|
+
"helper.ts",
|
|
102
|
+
"helper.mjs",
|
|
103
|
+
"helper.js",
|
|
104
|
+
"verify.json",
|
|
105
|
+
] as const;
|
|
106
|
+
|
|
78
107
|
// ═══════════════════════════════════════════════════════════════════
|
|
79
108
|
// Placeholder skeleton (retired worked example)
|
|
80
109
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -95,7 +124,7 @@ const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in
|
|
|
95
124
|
|
|
96
125
|
/** Placeholder starter template — only `domains:` is real (the requested
|
|
97
126
|
* domain). Every other field is a placeholder the agent fills (op blocks
|
|
98
|
-
* sourced from api-probe({
|
|
127
|
+
* sourced from api-probe({apiHost, path})). Fails closed: an unsaved,
|
|
99
128
|
* as-is template is rejected by the parser because `apiHost: <base url>`
|
|
100
129
|
* is not a valid URL — no wrong-API guide can be saved silently. */
|
|
101
130
|
function placeholderSkeleton(domain: string): string {
|
|
@@ -127,8 +156,7 @@ responseShape:
|
|
|
127
156
|
charset: utf-8
|
|
128
157
|
|
|
129
158
|
# Add one operation per endpoint here — source the block from
|
|
130
|
-
# api-probe({apiHost, path
|
|
131
|
-
# values):
|
|
159
|
+
# api-probe({apiHost, path}) (it drafts real ops with real values):
|
|
132
160
|
# operations:
|
|
133
161
|
# - name: <op>
|
|
134
162
|
# via: restGet
|
|
@@ -153,9 +181,7 @@ function authSummary(auth: AuthConfig): string {
|
|
|
153
181
|
const parts: string[] = [];
|
|
154
182
|
for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
|
|
155
183
|
const prefix = auth.headerPrefixes?.[header];
|
|
156
|
-
parts.push(
|
|
157
|
-
`${header} ← secret ${secretName}${prefix === undefined ? "" : ` (${prefix})`}`,
|
|
158
|
-
);
|
|
184
|
+
parts.push(`${header} ← secret ${secretName}${prefix ? ` (${prefix})` : ""}`);
|
|
159
185
|
}
|
|
160
186
|
for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
|
|
161
187
|
parts.push(`?${param} ← secret ${secretName}`);
|
|
@@ -169,15 +195,15 @@ function authSummary(auth: AuthConfig): string {
|
|
|
169
195
|
// Authoring manual + templates
|
|
170
196
|
// ═══════════════════════════════════════════════════════════════════
|
|
171
197
|
|
|
172
|
-
/**
|
|
173
|
-
*
|
|
174
|
-
* the
|
|
198
|
+
/** The field reference + defaults + semantics manual. Travels with the
|
|
199
|
+
* pull-to-/tmp action — prepended to every staged draft (template or
|
|
200
|
+
* fetched recipe) so the author sees it at the moment of authoring. */
|
|
175
201
|
const AUTHORING_MANUAL = [
|
|
176
202
|
"# API guide authoring manual",
|
|
177
203
|
"",
|
|
178
204
|
"💡 Start a new guide: call api-learn({domain: '<domain>', new: true}) — it returns a ",
|
|
179
205
|
" template with `domains` pre-filled. Discover the API's shape first with ",
|
|
180
|
-
" api-probe({apiHost, path
|
|
206
|
+
" api-probe({apiHost, path}) — it drafts a YAML operation block ",
|
|
181
207
|
" to paste into the template.",
|
|
182
208
|
"",
|
|
183
209
|
"## Required fields",
|
|
@@ -208,7 +234,7 @@ const AUTHORING_MANUAL = [
|
|
|
208
234
|
` \`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
235
|
` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
|
|
210
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)`,
|
|
211
|
-
` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Members may not be \`required: true\`
|
|
237
|
+
` \`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`,
|
|
212
238
|
` \`passthrough\` — true → forward undeclared caller params onto the query string`,
|
|
213
239
|
` \`parse\` — op-level responseShape override (format/charset) for this operation`,
|
|
214
240
|
"",
|
|
@@ -230,82 +256,90 @@ const AUTHORING_MANUAL = [
|
|
|
230
256
|
" date formats, auth caveats, field semantics, endpoint quirks. Surfaced by",
|
|
231
257
|
" api-guide as 'Guide notes'.",
|
|
232
258
|
"",
|
|
233
|
-
"
|
|
259
|
+
"## Saving (mirror-save)",
|
|
260
|
+
" Save reads every staged file (guide.md + helper.ts + verify.json when present) and",
|
|
261
|
+
" mirrors it into the guides dir. A sibling present in the guides dir but absent from",
|
|
262
|
+
" the staged /tmp dir would be DELETED — save refuses and names it; re-call with",
|
|
263
|
+
" confirmDeletions: true to proceed (that flag is discovered only via the refusal message,",
|
|
264
|
+
" never the tool description). A guide declaring helper: true / transform: true must",
|
|
265
|
+
" have a loadable staged helper.ts.",
|
|
266
|
+
"",
|
|
267
|
+
"Call api-learn({domain: '<domain>', dir: '<staged dir>'}) to save the guide, then test each op via api-fetch({domain, operation, params: <your verify.json values>}) — pass the values yourself; verify.json feeds /api verify (the user's batch stamp), not api-fetch.",
|
|
234
268
|
].join("\n");
|
|
235
269
|
|
|
236
|
-
/**
|
|
237
|
-
*
|
|
238
|
-
*
|
|
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).
|
|
270
|
+
/** Template path — write the placeholder skeleton to the staging dir and
|
|
271
|
+
* surface the guide.md path + staged dir (the agent edits the file, not an
|
|
272
|
+
* inline copy).
|
|
269
273
|
* Fail-closed: the as-is template cannot save (placeholder `apiHost`
|
|
270
274
|
* is rejected by requireHttpUrl). */
|
|
271
275
|
function stageTemplate(domain: string): string {
|
|
272
|
-
const
|
|
276
|
+
const dir = writeStagedDraft(domain, placeholderSkeleton(domain));
|
|
273
277
|
return (
|
|
274
|
-
|
|
278
|
+
AUTHORING_MANUAL +
|
|
279
|
+
"\n\n" +
|
|
280
|
+
`📝 Template for '${domain}' written to ${join(dir, "guide.md")}\n` +
|
|
275
281
|
` Edit the file (or append ops via bash), then call ` +
|
|
276
|
-
`api-learn({domain: "${domain}",
|
|
282
|
+
`api-learn({domain: "${domain}", dir: "${dir}"}) to validate and save.\n` +
|
|
283
|
+
` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`
|
|
277
284
|
);
|
|
278
285
|
}
|
|
279
286
|
|
|
280
|
-
/** Fetch-recipe response — the saved guide's raw recipe
|
|
281
|
-
* staging
|
|
282
|
-
* keys on the
|
|
283
|
-
*
|
|
284
|
-
*
|
|
287
|
+
/** Fetch-recipe response — the saved guide's raw recipe (and present
|
|
288
|
+
* siblings) staged to the staging dir, with the dir path + resolved dirName
|
|
289
|
+
* surfaced. Staging keys on `slug(shortName)` (the on-disk dirName in steady
|
|
290
|
+
* state), and the re-save self-keys off the draft's own shortName — no
|
|
291
|
+
* "pass the directory name as domain" guidance (that arg is cosmetic on
|
|
292
|
+
* save). The inline YAML block is dropped: the staged files are the source
|
|
293
|
+
* of truth the agent edits. */
|
|
285
294
|
function stageFetchedRecipe(
|
|
286
295
|
domain: string,
|
|
287
296
|
guide: ApiGuide,
|
|
288
297
|
dirName: string,
|
|
289
298
|
): AgentToolResult<unknown> {
|
|
290
|
-
const
|
|
291
|
-
|
|
299
|
+
const sourceDir = join(getUserGuidesDir(), dirName);
|
|
300
|
+
const stagedKey = slug(guide.shortName);
|
|
301
|
+
const stagedDir = stagingDirFor(stagedKey);
|
|
302
|
+
mkdirSync(stagedDir, { recursive: true });
|
|
303
|
+
// guide.md always; helper.ts / verify.json when present.
|
|
304
|
+
writeFileSync(
|
|
305
|
+
join(stagedDir, "guide.md"),
|
|
306
|
+
readFileSync(join(sourceDir, "guide.md"), "utf-8"),
|
|
292
307
|
"utf-8",
|
|
293
308
|
);
|
|
294
|
-
const
|
|
309
|
+
const stagedSiblings: string[] = [];
|
|
310
|
+
for (const name of SIBLING_NAMES) {
|
|
311
|
+
const src = join(sourceDir, name);
|
|
312
|
+
if (existsSync(src)) {
|
|
313
|
+
writeFileSync(join(stagedDir, name), readFileSync(src, "utf-8"), "utf-8");
|
|
314
|
+
stagedSiblings.push(name);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
295
317
|
return {
|
|
296
318
|
content: [
|
|
297
319
|
{
|
|
298
320
|
type: "text",
|
|
299
321
|
text:
|
|
322
|
+
AUTHORING_MANUAL +
|
|
323
|
+
"\n\n" +
|
|
300
324
|
`📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
|
|
301
325
|
` Directory: ${dirName}\n` +
|
|
302
|
-
` Staged
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
326
|
+
` Staged dir: ${stagedDir}\n` +
|
|
327
|
+
(stagedSiblings.length > 0
|
|
328
|
+
? ` Siblings staged: ${stagedSiblings.join(", ")}\n`
|
|
329
|
+
: "") +
|
|
330
|
+
` To edit: edit the staged files with the edit tool or bash, then call ` +
|
|
331
|
+
`api-learn({domain: "${domain}", dir: "${stagedDir}"}) — the guide ` +
|
|
332
|
+
`saves to its own \`${stagedKey}\` folder (self-keyed by shortName).\n` +
|
|
333
|
+
` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`,
|
|
306
334
|
},
|
|
307
335
|
],
|
|
308
|
-
details: {
|
|
336
|
+
details: {
|
|
337
|
+
mode: "fetch",
|
|
338
|
+
domain,
|
|
339
|
+
dirName,
|
|
340
|
+
guide: guide.shortName,
|
|
341
|
+
stagedDir,
|
|
342
|
+
},
|
|
309
343
|
};
|
|
310
344
|
}
|
|
311
345
|
|
|
@@ -337,31 +371,36 @@ export const apiLearnTool = defineTool({
|
|
|
337
371
|
label: "API Learn",
|
|
338
372
|
description:
|
|
339
373
|
"Author an API guide for a domain. " +
|
|
340
|
-
"Call with no params for the authoring manual (field reference + defaults + semantics). " +
|
|
341
374
|
"Call with {domain, new: true} for a fresh domain-specific template. " +
|
|
342
|
-
"Call with {domain} and no
|
|
343
|
-
"Call with {domain,
|
|
375
|
+
"Call with {domain} and no dir to fetch an existing guide's current raw recipe (and its sibling files). " +
|
|
376
|
+
"Call with {domain, dir} to validate and save.\n\n" +
|
|
377
|
+
"Authoring order (follow this to avoid the common mis-ordering):\n" +
|
|
378
|
+
"1. (optional) api-probe({apiHost, path, params}) — discover a not-yet-guided endpoint's shape and draft an op block from the docs/example.\n" +
|
|
379
|
+
"2. api-learn({domain, new: true}) — get a fresh template, fill the recipe, then api-learn({domain, dir}) to save it.\n" +
|
|
380
|
+
"3. ONLY after the guide is saved: api-scaffold({domain, verify: true | helper: true}) — scaffold reads the SAVED guide, so scaffold-before-save fails. Fill the staged verify.json / helper.ts, then api-learn({domain, dir}) to save the siblings.\n" +
|
|
381
|
+
"4. Test each op: api-fetch({domain, operation, params: <your verify.json values>}) — verify.json feeds /api verify, not api-fetch, so pass the values yourself. Fix via api-learn({domain}) → edit staged → api-learn({domain, dir}). /api verify is the user's batch attestation stamp (runs every op + stamps verified:).\n" +
|
|
382
|
+
"Staged drafts live in /tmp/pi-lean-host/<slug(shortName)>/; the save target is self-keyed by the guide's shortName, never the domain arg.",
|
|
344
383
|
|
|
345
384
|
parameters: Type.Object({
|
|
346
|
-
domain: Type.
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
recipeFile: Type.Optional(
|
|
385
|
+
domain: Type.String({
|
|
386
|
+
description:
|
|
387
|
+
"Domain (e.g. 'example.com'). With no dir it's the routing domain " +
|
|
388
|
+
"for fetch-recipe lookup; with `dir` it's display/error context only — " +
|
|
389
|
+
"the guide saves to its own slug(shortName) folder.",
|
|
390
|
+
}),
|
|
391
|
+
dir: Type.Optional(
|
|
354
392
|
Type.String({
|
|
355
393
|
description:
|
|
356
|
-
"Path to the staged
|
|
357
|
-
"
|
|
394
|
+
"Path to the staged directory (written by a prior api-learn fetch/template or api-scaffold call to /tmp/pi-lean-host/<slug(shortName)>/). " +
|
|
395
|
+
"guide.md is read, validated, and saved; present helper.ts / verify.json siblings are mirrored. " +
|
|
396
|
+
"Omit to fetch the current raw recipe of an existing guide (or get a template when none exists).",
|
|
358
397
|
}),
|
|
359
398
|
),
|
|
360
399
|
guide: Type.Optional(
|
|
361
400
|
Type.String({
|
|
362
401
|
description:
|
|
363
402
|
"When a domain claims multiple guides, select one by shortName (shown in the disambiguation menu). " +
|
|
364
|
-
"Only used with the fetch-recipe path (no
|
|
403
|
+
"Only used with the fetch-recipe path (no dir).",
|
|
365
404
|
}),
|
|
366
405
|
),
|
|
367
406
|
new: Type.Optional(
|
|
@@ -371,29 +410,26 @@ export const apiLearnTool = defineTool({
|
|
|
371
410
|
"Does not touch any existing guide.",
|
|
372
411
|
}),
|
|
373
412
|
),
|
|
413
|
+
// Undescribed by design — the only discovery path is the deletion-safety
|
|
414
|
+
// gate's refusal message.
|
|
415
|
+
confirmDeletions: Type.Optional(Type.Boolean()),
|
|
374
416
|
}),
|
|
375
417
|
|
|
376
418
|
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
377
419
|
const {
|
|
378
420
|
domain,
|
|
379
|
-
|
|
421
|
+
dir,
|
|
380
422
|
guide: guideSelector,
|
|
381
423
|
new: isNew,
|
|
424
|
+
confirmDeletions,
|
|
382
425
|
} = params as {
|
|
383
|
-
domain
|
|
384
|
-
|
|
426
|
+
domain: string;
|
|
427
|
+
dir?: string;
|
|
385
428
|
guide?: string;
|
|
386
429
|
new?: boolean;
|
|
430
|
+
confirmDeletions?: boolean;
|
|
387
431
|
};
|
|
388
432
|
|
|
389
|
-
// ── No domain → authoring manual ─────────────────────────
|
|
390
|
-
if (!domain) {
|
|
391
|
-
return {
|
|
392
|
-
content: [{ type: "text", text: AUTHORING_MANUAL }],
|
|
393
|
-
details: { mode: "manual" },
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
|
|
397
433
|
// ── Validate domain (path-traversal guard) ─────────────
|
|
398
434
|
try {
|
|
399
435
|
assertSafeDomain(domain);
|
|
@@ -417,10 +453,11 @@ export const apiLearnTool = defineTool({
|
|
|
417
453
|
};
|
|
418
454
|
}
|
|
419
455
|
|
|
420
|
-
// ── No
|
|
421
|
-
// 0 guides → template staged; 1 guide → raw recipe staged +
|
|
422
|
-
// surfaced; N guides → disambiguation menu (guide selector
|
|
423
|
-
|
|
456
|
+
// ── No dir → fetch-recipe ──────────────────────────────
|
|
457
|
+
// 0 guides → template staged; 1 guide → raw recipe + siblings staged +
|
|
458
|
+
// dirName surfaced; N guides → disambiguation menu (guide selector
|
|
459
|
+
// resolves it).
|
|
460
|
+
if (!dir || !dir.trim()) {
|
|
424
461
|
const matches = findGuidesByDomain(domain);
|
|
425
462
|
if (matches.length === 0) {
|
|
426
463
|
return {
|
|
@@ -464,24 +501,25 @@ export const apiLearnTool = defineTool({
|
|
|
464
501
|
return stageFetchedRecipe(domain, sel.guide, sel.dirName);
|
|
465
502
|
}
|
|
466
503
|
|
|
467
|
-
// ── Save from a staged
|
|
468
|
-
// Read the
|
|
469
|
-
// path. A missing/unreadable
|
|
504
|
+
// ── Save from a staged directory ────────────────────────
|
|
505
|
+
// Read guide.md (required) from the staged dir, then run the identical
|
|
506
|
+
// validate → stamp → write path. A missing/unreadable dir is a clear
|
|
507
|
+
// error; guides dir untouched.
|
|
470
508
|
let recipe: string;
|
|
471
509
|
try {
|
|
472
|
-
recipe = readFileSync(
|
|
510
|
+
recipe = readFileSync(join(dir, "guide.md"), "utf-8");
|
|
473
511
|
} catch {
|
|
474
512
|
return {
|
|
475
513
|
content: [
|
|
476
514
|
{
|
|
477
515
|
type: "text",
|
|
478
516
|
text:
|
|
479
|
-
`⚠ Could not read
|
|
517
|
+
`⚠ Could not read staged guide from '${join(dir, "guide.md")}' — guide was NOT saved.\n` +
|
|
480
518
|
` Fetch the current recipe first via api-learn({domain: "${domain}"}) ` +
|
|
481
|
-
`(or a template with {domain, new: true}), then edit the staged
|
|
519
|
+
`(or a template with {domain, new: true}), then edit the staged files and save with dir.`,
|
|
482
520
|
},
|
|
483
521
|
],
|
|
484
|
-
details: { error: "
|
|
522
|
+
details: { error: "staged_dir_unreadable", domain, dir },
|
|
485
523
|
};
|
|
486
524
|
}
|
|
487
525
|
|
|
@@ -495,13 +533,6 @@ export const apiLearnTool = defineTool({
|
|
|
495
533
|
` Found: ${err.found}`,
|
|
496
534
|
];
|
|
497
535
|
if (err.fix) lines.push(` Fix: ${err.fix}`);
|
|
498
|
-
const section = manualSectionFor(err.field);
|
|
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
|
-
);
|
|
505
536
|
lines.push("Fix the recipe and call api-learn again.");
|
|
506
537
|
return {
|
|
507
538
|
content: [{ type: "text", text: lines.join("\n") }],
|
|
@@ -529,30 +560,97 @@ export const apiLearnTool = defineTool({
|
|
|
529
560
|
};
|
|
530
561
|
}
|
|
531
562
|
|
|
563
|
+
// Save target — a function of the guide's own `shortName`, never the
|
|
564
|
+
// `domain` arg. Two guides with different shortNames physically cannot
|
|
565
|
+
// share a directory. An empty/all-symbol shortName throws here (the
|
|
566
|
+
// slug flattens to empty) — refuse with a prescriptive error before
|
|
567
|
+
// any write.
|
|
568
|
+
let slugged: string;
|
|
569
|
+
try {
|
|
570
|
+
slugged = slug(parsed.guide.shortName);
|
|
571
|
+
} catch (err) {
|
|
572
|
+
return {
|
|
573
|
+
content: [
|
|
574
|
+
{
|
|
575
|
+
type: "text",
|
|
576
|
+
text:
|
|
577
|
+
`⚠ Invalid shortName — guide was NOT saved.\n` +
|
|
578
|
+
` ${err instanceof Error ? err.message : `shortName '${parsed.guide.shortName}' does not slug to a directory name.`}\n` +
|
|
579
|
+
` Set a valid shortName (lowercase letters, digits, and '-') in the recipe and save again.`,
|
|
580
|
+
},
|
|
581
|
+
],
|
|
582
|
+
details: { error: "invalid_shortname", domain },
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// ── Staged-dir collision guard (drift guard, part 1) ──
|
|
587
|
+
// The template stages by `domain` (shortName is still a placeholder at
|
|
588
|
+
// that point), but every later stage (fetch-recipe, scaffold) keys by
|
|
589
|
+
// `slug(shortName)`. When the draft's staged dir basename doesn't match
|
|
590
|
+
// its slug, the save re-stages it to the canonical slug dir (part 2).
|
|
591
|
+
// Before that, refuse if the canonical dir already holds a guide.md
|
|
592
|
+
// with a DIFFERENT shortName — a divergent save would clobber another
|
|
593
|
+
// guide's staged recipe (e.g. a shortName copied from another guide).
|
|
594
|
+
// Same shortName = legitimate update of this guide's own draft; no
|
|
595
|
+
// guide.md = only scaffold siblings, safe to re-stage beside them.
|
|
596
|
+
const canonicalStaged = stagingDirFor(slugged);
|
|
597
|
+
const divergent = basename(dir) !== slugged && isUnderStagingRoot(dir);
|
|
598
|
+
if (divergent && existsSync(join(canonicalStaged, "guide.md"))) {
|
|
599
|
+
const existing = parseApiGuide(
|
|
600
|
+
readFileSync(join(canonicalStaged, "guide.md"), "utf-8"),
|
|
601
|
+
{ filename: slugged },
|
|
602
|
+
);
|
|
603
|
+
const existingShort = existing.ok ? existing.guide.shortName : undefined;
|
|
604
|
+
if (existingShort !== parsed.guide.shortName) {
|
|
605
|
+
return {
|
|
606
|
+
content: [
|
|
607
|
+
{
|
|
608
|
+
type: "text",
|
|
609
|
+
text:
|
|
610
|
+
`⚠ Save refused — '${canonicalStaged}/guide.md' already holds ${existing.ok ? `a different guide ('${existing.guide.shortName}')` : "an unparseable guide"} — not the incoming '${parsed.guide.shortName}'.\n` +
|
|
611
|
+
` Your draft is staged at '${dir}', but its shortName slugs to '${canonicalStaged}', which already holds staged files${existing.ok ? " for another guide" : ""}.\n` +
|
|
612
|
+
` Resolve the collision, then save again:\n` +
|
|
613
|
+
` - If this is a new guide, change \`shortName\` so it slugs to a distinct directory.\n` +
|
|
614
|
+
` - If you're re-authoring this guide, delete the staged files in '${canonicalStaged}' (or move your draft there), then save.\n` +
|
|
615
|
+
` Guides dir untouched.`,
|
|
616
|
+
},
|
|
617
|
+
],
|
|
618
|
+
details: {
|
|
619
|
+
error: "staged_dir_collision",
|
|
620
|
+
domain,
|
|
621
|
+
dir,
|
|
622
|
+
canonicalStaged,
|
|
623
|
+
existing: existingShort ?? null,
|
|
624
|
+
incoming: parsed.guide.shortName,
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
532
630
|
// Collision detection — another guide (different directory) already
|
|
533
631
|
// claims one of this guide's `domains:` keys. Valid (that's the whole
|
|
534
632
|
// point of multi-recipe), but warn so the author knows they're in
|
|
535
|
-
// disambiguation territory. Updating the same directory
|
|
536
|
-
// collision. Names both the directory and the colliding `domains:`
|
|
537
|
-
// so the routing-vs-identity distinction is explicit.
|
|
633
|
+
// disambiguation territory. Updating the same directory (same slug) is
|
|
634
|
+
// NOT a collision. Names both the directory and the colliding `domains:`
|
|
635
|
+
// key so the routing-vs-identity distinction is explicit.
|
|
538
636
|
const warnings: string[] = [];
|
|
539
637
|
const collidingDomains: string[] = [];
|
|
540
638
|
const collidingDirs: string[] = [];
|
|
541
639
|
for (const d of parsed.guide.domains ?? []) {
|
|
542
640
|
const existing = findGuidesByDomain(d);
|
|
543
641
|
for (const m of existing) {
|
|
544
|
-
if (m.dirName !==
|
|
642
|
+
if (m.dirName !== slugged && !collidingDirs.includes(m.dirName)) {
|
|
545
643
|
collidingDirs.push(m.dirName);
|
|
546
644
|
}
|
|
547
645
|
}
|
|
548
|
-
if (existing.some((m) => m.dirName !==
|
|
646
|
+
if (existing.some((m) => m.dirName !== slugged)) {
|
|
549
647
|
collidingDomains.push(d);
|
|
550
648
|
}
|
|
551
649
|
}
|
|
552
650
|
if (collidingDomains.length > 0) {
|
|
553
651
|
const keys = collidingDomains.join(", ");
|
|
554
652
|
warnings.push(
|
|
555
|
-
`⚠ Multi-recipe: writing to directory \`${
|
|
653
|
+
`⚠ Multi-recipe: writing to directory \`${slugged}\`, but \`domains:\` declares [${keys}] which another guide already claims — disambiguation menu applies. Give each guide a distinct \`shortName\`.`,
|
|
556
654
|
);
|
|
557
655
|
if (desc === undefined) {
|
|
558
656
|
warnings.push(
|
|
@@ -564,11 +662,190 @@ export const apiLearnTool = defineTool({
|
|
|
564
662
|
);
|
|
565
663
|
}
|
|
566
664
|
|
|
567
|
-
// ──
|
|
665
|
+
// ── Fail-closed overwrite guard ─────────────────────────
|
|
666
|
+
// A guide.md already in the target directory is that directory's
|
|
667
|
+
// identity anchor. Since the write target is slug(shortName), a
|
|
668
|
+
// pre-existing guide.md there with a DIFFERENT shortName is reachable
|
|
669
|
+
// only via a slug collision — refuse and teach the rename-shortName
|
|
670
|
+
// convention. Same shortName = legitimate update, proceeds.
|
|
568
671
|
const guidesDir = getUserGuidesDir();
|
|
569
|
-
const domainDir = join(guidesDir,
|
|
570
|
-
mkdirSync(domainDir, { recursive: true });
|
|
672
|
+
const domainDir = join(guidesDir, slugged);
|
|
571
673
|
const filepath = join(domainDir, "guide.md");
|
|
674
|
+
if (existsSync(filepath)) {
|
|
675
|
+
const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
|
|
676
|
+
filename: slugged,
|
|
677
|
+
});
|
|
678
|
+
const existingShort = existing.ok ? existing.guide.shortName : undefined;
|
|
679
|
+
if (existingShort !== parsed.guide.shortName) {
|
|
680
|
+
return {
|
|
681
|
+
content: [
|
|
682
|
+
{
|
|
683
|
+
type: "text",
|
|
684
|
+
text:
|
|
685
|
+
`⚠ Refusing to overwrite — guide was NOT saved.\n` +
|
|
686
|
+
` Directory '${slugged}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
|
|
687
|
+
`the incoming guide is '${parsed.guide.shortName}'.` +
|
|
688
|
+
(existing.ok
|
|
689
|
+
? `\n Both shortNames slug to the same directory ('${slugged}') — a slug collision. Rename the incoming guide's \`shortName\` so it slugs to a distinct directory.`
|
|
690
|
+
: `\n The existing guide.md is malformed (won't parse). If you intend to replace it, ask the user to run /api delete ${slugged} first.`),
|
|
691
|
+
},
|
|
692
|
+
],
|
|
693
|
+
details: {
|
|
694
|
+
error: "overwrite_refused",
|
|
695
|
+
domain,
|
|
696
|
+
existing: existingShort ?? null,
|
|
697
|
+
incoming: parsed.guide.shortName,
|
|
698
|
+
},
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
// ── Deletion-safety gate ────────────────────────────────
|
|
703
|
+
// Mirror-save can wipe a sibling silently (accidental /tmp cleanup, or
|
|
704
|
+
// the same-shortName new:true case). Compute the deletion set — siblings
|
|
705
|
+
// in the guides dir absent from the staged dir — and refuse unless the
|
|
706
|
+
// agent confirms. `confirmDeletions` is undescribed by design; the
|
|
707
|
+
// refusal message is its only discovery path.
|
|
708
|
+
const stagedSiblingNames = SIBLING_NAMES.filter((n) =>
|
|
709
|
+
existsSync(join(dir, n)),
|
|
710
|
+
);
|
|
711
|
+
const doomed = SIBLING_NAMES.filter(
|
|
712
|
+
(n) => existsSync(join(domainDir, n)) && !stagedSiblingNames.includes(n),
|
|
713
|
+
);
|
|
714
|
+
if (doomed.length > 0 && !confirmDeletions) {
|
|
715
|
+
return {
|
|
716
|
+
content: [
|
|
717
|
+
{
|
|
718
|
+
type: "text",
|
|
719
|
+
text:
|
|
720
|
+
`⚠ Save refused — these sibling files exist in the guides dir but are absent from your staged /tmp dir and would be deleted: ${doomed.join(", ")}.\n` +
|
|
721
|
+
` Re-call with confirmDeletions: true to delete them, or restore them in /tmp first.`,
|
|
722
|
+
},
|
|
723
|
+
],
|
|
724
|
+
details: { error: "deletion_refused", domain, doomed },
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ── Guide↔helper validation at save time ───────────────
|
|
729
|
+
// A guide that declares helper/transform usage must have a loadable
|
|
730
|
+
// staged helper with the declared exports. Self-contained — does not
|
|
731
|
+
// touch core/local-helpers.ts (no loadHelper/loadTransform, no
|
|
732
|
+
// disabledHelpers side effects).
|
|
733
|
+
const ops = parsed.guide.operations;
|
|
734
|
+
const needsHelper = ops.some(
|
|
735
|
+
(o) => o.helper === true || o.transform === true,
|
|
736
|
+
);
|
|
737
|
+
if (needsHelper) {
|
|
738
|
+
const stagedHelper = SIBLING_NAMES.find(
|
|
739
|
+
(n) => n.startsWith("helper.") && existsSync(join(dir, n)),
|
|
740
|
+
);
|
|
741
|
+
if (!stagedHelper) {
|
|
742
|
+
return {
|
|
743
|
+
content: [
|
|
744
|
+
{
|
|
745
|
+
type: "text",
|
|
746
|
+
text:
|
|
747
|
+
`⚠ Save refused — the guide declares helper usage (helper: true / transform: true) but no helper.ts is in the staged dir.\n` +
|
|
748
|
+
` Scaffold one via api-scaffold({domain: "${domain}", helper: true}), or remove the helper: true / transform: true declarations from the guide.`,
|
|
749
|
+
},
|
|
750
|
+
],
|
|
751
|
+
details: { error: "helper_declared_missing_staged", domain },
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
try {
|
|
755
|
+
const mod = await import(pathToFileURL(join(dir, stagedHelper)).href);
|
|
756
|
+
if (
|
|
757
|
+
ops.some((o) => o.helper === true) &&
|
|
758
|
+
typeof mod.default !== "function"
|
|
759
|
+
) {
|
|
760
|
+
return {
|
|
761
|
+
content: [
|
|
762
|
+
{
|
|
763
|
+
type: "text",
|
|
764
|
+
text:
|
|
765
|
+
`⚠ Save refused — staged ${stagedHelper} has no default export, but an op declares helper: true.\n` +
|
|
766
|
+
` Uncomment the default export in the staged helper, or drop the helper: true declarations.`,
|
|
767
|
+
},
|
|
768
|
+
],
|
|
769
|
+
details: { error: "helper_missing_default_export", domain },
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
if (
|
|
773
|
+
ops.some((o) => o.transform === true) &&
|
|
774
|
+
typeof mod.transform !== "function"
|
|
775
|
+
) {
|
|
776
|
+
return {
|
|
777
|
+
content: [
|
|
778
|
+
{
|
|
779
|
+
type: "text",
|
|
780
|
+
text:
|
|
781
|
+
`⚠ Save refused — staged ${stagedHelper} has no transform export, but an op declares transform: true.\n` +
|
|
782
|
+
` Uncomment the transform export in the staged helper, or drop the transform: true declarations.`,
|
|
783
|
+
},
|
|
784
|
+
],
|
|
785
|
+
details: { error: "helper_missing_transform_export", domain },
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
} catch {
|
|
789
|
+
return {
|
|
790
|
+
content: [
|
|
791
|
+
{
|
|
792
|
+
type: "text",
|
|
793
|
+
text:
|
|
794
|
+
`⚠ Save refused — staged ${stagedHelper} failed to load (syntax error, broken import, or top-level throw).\n` +
|
|
795
|
+
` Fix the staged helper, or remove the helper: true / transform: true declarations from the guide.`,
|
|
796
|
+
},
|
|
797
|
+
],
|
|
798
|
+
details: { error: "helper_load_failed", domain },
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// ── Self-correct the staged root (drift guard, part 2) ──
|
|
804
|
+
// Move the draft to the canonical slug dir and read from there for the
|
|
805
|
+
// rest of save. Runs after all gates pass, so a refused save never
|
|
806
|
+
// mutates /tmp. When the canonical dir already exists it holds the
|
|
807
|
+
// same guide's draft (or only scaffold siblings) — the collision guard
|
|
808
|
+
// above refused a different guide — so merge per-file; otherwise do an
|
|
809
|
+
// atomic whole-dir rename.
|
|
810
|
+
let reStagedNote: string | undefined;
|
|
811
|
+
// `writeDir` is the staged dir the write reads from — reassigned to the
|
|
812
|
+
// canonical slug dir when the passed dir diverges (see above). `dir`
|
|
813
|
+
// stays const so its earlier narrowing survives the closure captures.
|
|
814
|
+
let writeDir = dir;
|
|
815
|
+
if (divergent) {
|
|
816
|
+
const oldName = basename(writeDir);
|
|
817
|
+
try {
|
|
818
|
+
if (existsSync(canonicalStaged)) {
|
|
819
|
+
for (const name of readdirSync(writeDir)) {
|
|
820
|
+
renameSync(join(writeDir, name), join(canonicalStaged, name));
|
|
821
|
+
}
|
|
822
|
+
rmSync(writeDir, { recursive: true, force: true });
|
|
823
|
+
} else {
|
|
824
|
+
renameSync(writeDir, canonicalStaged);
|
|
825
|
+
}
|
|
826
|
+
} catch (err) {
|
|
827
|
+
return {
|
|
828
|
+
content: [
|
|
829
|
+
{
|
|
830
|
+
type: "text",
|
|
831
|
+
text:
|
|
832
|
+
`⚠ Could not re-stage the draft from '${writeDir}' to '${canonicalStaged}' — guide was NOT saved.\n` +
|
|
833
|
+
` ${err instanceof Error ? err.message : String(err)}\n` +
|
|
834
|
+
` Move the staged files manually (or re-fetch via api-learn({domain: "${domain}"})), then save again.`,
|
|
835
|
+
},
|
|
836
|
+
],
|
|
837
|
+
details: { error: "restage_failed", domain, dir, canonicalStaged },
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
writeDir = canonicalStaged;
|
|
841
|
+
reStagedNote =
|
|
842
|
+
`Re-staged /${oldName} → ${writeDir} (slug of shortName) — ` +
|
|
843
|
+
`the staged draft moved here; edit these files from now on.`;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
mkdirSync(domainDir, { recursive: true });
|
|
847
|
+
|
|
848
|
+
// ── Write guide + mirror siblings ───────────────────────
|
|
572
849
|
|
|
573
850
|
// Stamp schemaVersion on save — each guide records the schema vintage
|
|
574
851
|
// it was authored against (the per-guide vintage that stale detection
|
|
@@ -580,6 +857,25 @@ export const apiLearnTool = defineTool({
|
|
|
580
857
|
String(GUIDE_SCHEMA_VERSION),
|
|
581
858
|
);
|
|
582
859
|
writeFileSync(filepath, stamped, "utf-8");
|
|
860
|
+
|
|
861
|
+
// Mirror the staged dir: present siblings overwrite the guides-dir
|
|
862
|
+
// counterpart; confirmed-absent siblings are removed.
|
|
863
|
+
const writtenSiblings: string[] = [];
|
|
864
|
+
for (const name of stagedSiblingNames) {
|
|
865
|
+
writeFileSync(
|
|
866
|
+
join(domainDir, name),
|
|
867
|
+
readFileSync(join(writeDir, name), "utf-8"),
|
|
868
|
+
"utf-8",
|
|
869
|
+
);
|
|
870
|
+
writtenSiblings.push(name);
|
|
871
|
+
}
|
|
872
|
+
const deletedSiblings: string[] = [];
|
|
873
|
+
if (confirmDeletions) {
|
|
874
|
+
for (const name of doomed) {
|
|
875
|
+
rmSync(join(domainDir, name), { force: true });
|
|
876
|
+
deletedSiblings.push(name);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
583
879
|
invalidateCache(); // next api-fetch / api-guide read picks it up
|
|
584
880
|
|
|
585
881
|
const opCount = parsed.guide.operations.length;
|
|
@@ -592,16 +888,23 @@ export const apiLearnTool = defineTool({
|
|
|
592
888
|
{
|
|
593
889
|
type: "text",
|
|
594
890
|
text:
|
|
595
|
-
`📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${
|
|
596
|
-
`
|
|
891
|
+
`📖 Guide saved to ~/.pi/agent/pi-lean-host/api-guides/${slugged}/guide.md\n` +
|
|
892
|
+
` Directory: ${slugged}\n` +
|
|
597
893
|
` Operations: ${opCount} — ${opNames}\n` +
|
|
598
894
|
` ${authSummary(parsed.guide.auth)}\n` +
|
|
599
895
|
` Verified: ${parsed.guide.verified}\n` +
|
|
600
896
|
` Schema version: ${GUIDE_SCHEMA_VERSION}\n` +
|
|
897
|
+
(writtenSiblings.length > 0
|
|
898
|
+
? ` Written: ${writtenSiblings.join(", ")}\n`
|
|
899
|
+
: "") +
|
|
900
|
+
(deletedSiblings.length > 0
|
|
901
|
+
? ` Deleted: ${deletedSiblings.join(", ")}\n`
|
|
902
|
+
: "") +
|
|
903
|
+
(reStagedNote ? ` ${reStagedNote}\n` : "") +
|
|
601
904
|
`\n` +
|
|
602
905
|
warningBlock +
|
|
603
|
-
`
|
|
604
|
-
`\n⚠
|
|
906
|
+
`Test each op via api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}", params: <your verify.json values>}) — pass the values yourself (verify.json feeds /api verify, not api-fetch). /api verify is the user's batch stamp.` +
|
|
907
|
+
`\n⚠ Edit the staged /tmp files, not the saved guide.md — direct edits to guide.md are overwritten on save and invisible to api-fetch until then.`,
|
|
605
908
|
},
|
|
606
909
|
],
|
|
607
910
|
details: {
|
|
@@ -610,20 +913,19 @@ export const apiLearnTool = defineTool({
|
|
|
610
913
|
domain,
|
|
611
914
|
operations: opCount,
|
|
612
915
|
verified: parsed.guide.verified,
|
|
916
|
+
...(reStagedNote ? { reStaged: true } : {}),
|
|
917
|
+
...(writtenSiblings.length > 0 ? { written: writtenSiblings } : {}),
|
|
918
|
+
...(deletedSiblings.length > 0 ? { deleted: deletedSiblings } : {}),
|
|
613
919
|
},
|
|
614
920
|
};
|
|
615
921
|
},
|
|
616
922
|
|
|
617
923
|
renderCall(args, theme, _context) {
|
|
618
924
|
const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
else parts.push(theme.fg("dim", "📖"));
|
|
624
|
-
} else {
|
|
625
|
-
parts.push(theme.fg("dim", "(manual)"));
|
|
626
|
-
}
|
|
925
|
+
parts.push(theme.fg("accent", `"${args.domain}"`));
|
|
926
|
+
if (args.new) parts.push(theme.fg("dim", "✨new"));
|
|
927
|
+
else if (args.dir) parts.push(theme.fg("dim", "📝"));
|
|
928
|
+
else parts.push(theme.fg("dim", "📖"));
|
|
627
929
|
return new Text(parts.join(" "), 0, 0);
|
|
628
930
|
},
|
|
629
931
|
|
|
@@ -649,11 +951,9 @@ export const apiLearnTool = defineTool({
|
|
|
649
951
|
} else if (mode === "menu" && domain) {
|
|
650
952
|
text = theme.fg("dim", theme.bold("📖 menu"));
|
|
651
953
|
text += ` — ${disambig ?? "?"} guides for ${domain}`;
|
|
652
|
-
} else
|
|
954
|
+
} else {
|
|
653
955
|
text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
|
|
654
956
|
text += ` — ${opCount} ops`;
|
|
655
|
-
} else {
|
|
656
|
-
text = theme.fg("dim", "📝 Authoring manual");
|
|
657
957
|
}
|
|
658
958
|
|
|
659
959
|
return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);
|