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.
@@ -0,0 +1,420 @@
1
+ /**
2
+ * api-scaffold tool definition.
3
+ *
4
+ * Learn-gated bootstrap tool for a guide's sibling artifacts. Reads the
5
+ * saved guide from the guides dir and writes starter `helper.ts` and/or
6
+ * `verify.json` into `/tmp/pi-lean-host/<slug(shortName)>/` staging — never
7
+ * the guides dir. The agent saves via `api-learn({domain, dir})`.
8
+ *
9
+ * - `{domain, helper: true}` → commented-out helper stub (default +
10
+ * `transform` exports) with doc comments. Self-documenting.
11
+ * - `{domain, verify: true}` → `verify.json` with `"__FILL_ME__"` sentinels
12
+ * for every unsatisfiable param (path `{token}`, required-no-default
13
+ * query, each `requiresAnyOf` member). Existing guides-dir `verify.json`
14
+ * real values are additive-merged; new sentinels added for newly-
15
+ * unsatisfiable params.
16
+ * - `{domain, verify: true, helper: true}` → both files, same staged dir.
17
+ *
18
+ * Refuses to overwrite an existing staged sibling (delete from /tmp +
19
+ * re-call for a fresh scaffold). At least one of `verify`/`helper` must be
20
+ * true. `dirName` is always derived (slug(shortName)) and surfaced.
21
+ *
22
+ * Guide resolution mirrors api-learn's fetch-recipe exactly
23
+ * (`findGuidesByDomain` + `selectGuideByShortName`, disambiguation menu for
24
+ * N-guide domains with no selector).
25
+ */
26
+
27
+ import { defineTool } from "@earendil-works/pi-coding-agent";
28
+ import { Type } from "@earendil-works/pi-ai";
29
+ import { Text } from "@earendil-works/pi-tui";
30
+ import { appendFooter, contentText } from "./utils.js";
31
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
32
+ import { tmpdir } from "node:os";
33
+ import { join } from "node:path";
34
+ import {
35
+ formatGuideListings,
36
+ selectGuideByShortName,
37
+ shortNameErrorText,
38
+ } from "../core/parse-api-guide.js";
39
+ import type { ApiGuide } from "../core/api-guide-types.js";
40
+ import { findGuidesByDomain, getUserGuidesDir } from "../core/guide-store.js";
41
+ import { assertSafeDomain, slug } from "../core/path-template.js";
42
+ import {
43
+ unsatisfiable,
44
+ renderForSentinels,
45
+ loadVerifyJson,
46
+ } from "../core/verify-command.js";
47
+
48
+ // ═══════════════════════════════════════════════════════════════════
49
+ // Staged working copy (/tmp) — same root api-learn writes to
50
+ // ═══════════════════════════════════════════════════════════════════
51
+
52
+ let _stagingRoot = join(tmpdir(), "pi-lean-host");
53
+
54
+ /** Test override — keeps scaffolds out of the real /tmp root (mirrors
55
+ * api-learn's `setStagingRoot`). */
56
+ export function setStagingRoot(dir: string): void {
57
+ _stagingRoot = dir;
58
+ }
59
+
60
+ // ═══════════════════════════════════════════════════════════════════
61
+ // Authoring manual + templates
62
+ // ═══════════════════════════════════════════════════════════════════
63
+
64
+ /** Compact authoring manual, prepended to every scaffold result. */
65
+ const SCAFFOLD_MANUAL = [
66
+ "# verify.json authoring manual",
67
+ "",
68
+ '1. "__FILL_ME__" means "replace with a real value." The sentinel is treated as unsupplied; the op skips until you replace it.',
69
+ "2. For requiresAnyOf groups, fill one or more members — /api verify tests each supplied member independently, so mutually-exclusive peers (e.g. id XOR symbol) never conflict. Sentinels left as __FILL_ME__ are ignored.",
70
+ "3. Source the values. Don't invent them — use api-fetch or api-probe to discover a real {token} value, or read the guide's param descriptions for format hints.",
71
+ "",
72
+ "Save the guide FIRST, then scaffold: api-scaffold reads the SAVED guide, so the staged sibling matches what the loader will see. Re-scaffold = delete the staged file from /tmp + re-call (no merge).",
73
+ ].join("\n");
74
+
75
+ /** Starter helper.ts — both exports commented out, self-documenting. */
76
+ function helperStub(domain: string): string {
77
+ return `/**
78
+ * Helper for ${domain}.
79
+ * One helper per domain is the v1 contract.
80
+ *
81
+ * Uncomment the export(s) you need and fill in the logic.
82
+ */
83
+
84
+ // Pre-call param transform — receives agent-supplied params, returns the
85
+ // params the executor uses for URL templating / query assembly.
86
+ // export default function(
87
+ // params: Record<string, unknown>,
88
+ // _ctx: { operation: string; domain: string },
89
+ // ): Record<string, unknown> {
90
+ // return params;
91
+ // }
92
+
93
+ // Post-response transform — reshapes the parsed response body.
94
+ // export function transform(
95
+ // data: unknown,
96
+ // _ctx: { operation: string; domain: string },
97
+ // ): unknown {
98
+ // return data;
99
+ // }
100
+ `;
101
+ }
102
+
103
+ // ═══════════════════════════════════════════════════════════════════
104
+ // verify.json sentinel computation
105
+ // ═══════════════════════════════════════════════════════════════════
106
+
107
+ /**
108
+ * Additive-merge the sentinel scaffold into an existing guides-dir
109
+ * verify.json: real values preserved, `"__FILL_ME__"` added only for
110
+ * unsatisfiable params not yet present. Purely additive — no pruning.
111
+ */
112
+ function mergeVerifySentinels(
113
+ guide: ApiGuide,
114
+ existing: Record<string, Record<string, unknown>>,
115
+ ): Record<string, Record<string, unknown>> {
116
+ const merged: Record<string, Record<string, unknown>> = {};
117
+ for (const [opName, params] of Object.entries(existing)) {
118
+ merged[opName] = { ...params };
119
+ }
120
+ for (const op of guide.operations) {
121
+ const sentinels = renderForSentinels(unsatisfiable(op, {}));
122
+ if (sentinels.length === 0) continue; // runnable op → no entry
123
+ const entry = merged[op.name] ?? {};
124
+ for (const p of sentinels) {
125
+ if (entry[p] === undefined) entry[p] = "__FILL_ME__";
126
+ }
127
+ merged[op.name] = entry;
128
+ }
129
+ return merged;
130
+ }
131
+
132
+ // ═══════════════════════════════════════════════════════════════════
133
+ // Tool definition
134
+ // ═══════════════════════════════════════════════════════════════════
135
+
136
+ export const apiScaffoldTool = defineTool({
137
+ name: "api-scaffold",
138
+ label: "API Scaffold",
139
+ description:
140
+ "Bootstrap sibling artifacts (helper.ts / verify.json) for an API guide, staged to /tmp — never the guides dir. " +
141
+ "Call with {domain, verify: true} and/or {domain, helper: true}. " +
142
+ "Then save via api-learn({domain, dir: '<staged dir>'}).",
143
+
144
+ parameters: Type.Object({
145
+ domain: Type.String({
146
+ description:
147
+ "Routing domain (e.g. 'example.com'). Resolves the guide exactly like api-learn fetch-recipe.",
148
+ }),
149
+ guide: Type.Optional(
150
+ Type.String({
151
+ description:
152
+ "When a domain claims multiple guides, select one by shortName (shown in the disambiguation menu).",
153
+ }),
154
+ ),
155
+ verify: Type.Optional(
156
+ Type.Boolean({
157
+ description:
158
+ 'true → scaffold a starter verify.json with "__FILL_ME__" sentinels for every unsatisfiable param.',
159
+ }),
160
+ ),
161
+ helper: Type.Optional(
162
+ Type.Boolean({
163
+ description:
164
+ "true → scaffold a commented-out helper.ts stub (default + transform exports).",
165
+ }),
166
+ ),
167
+ }),
168
+
169
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
170
+ const {
171
+ domain,
172
+ guide: guideSelector,
173
+ verify,
174
+ helper,
175
+ } = params as {
176
+ domain: string;
177
+ guide?: string;
178
+ verify?: boolean;
179
+ helper?: boolean;
180
+ };
181
+
182
+ // ── At least one artifact requested ────────────────────
183
+ if (!verify && !helper) {
184
+ return {
185
+ content: [
186
+ {
187
+ type: "text",
188
+ text:
189
+ `⚠ Nothing to scaffold — at least one of verify: true or helper: true is required.\n` +
190
+ ` verify: true → starter verify.json (sentinels for unsatisfiable params)\n` +
191
+ ` helper: true → commented-out helper.ts stub`,
192
+ },
193
+ ],
194
+ details: { error: "nothing_to_scaffold", domain },
195
+ };
196
+ }
197
+
198
+ // ── Validate domain (path-traversal guard) ─────────────
199
+ try {
200
+ assertSafeDomain(domain);
201
+ } catch (err) {
202
+ return {
203
+ content: [
204
+ {
205
+ type: "text",
206
+ text: err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
207
+ },
208
+ ],
209
+ details: { error: "invalid_domain", domain },
210
+ };
211
+ }
212
+
213
+ // ── Guide resolution (mirrors api-learn fetch-recipe) ──
214
+ const matches = findGuidesByDomain(domain);
215
+ if (matches.length === 0) {
216
+ // State-aware guidance: if a staged template already exists for this
217
+ // domain (api-learn {domain, new:true} stages by domain), the user is
218
+ // mid-authoring — tell them to save it first. Otherwise keep the
219
+ // browse + author-one-first guidance.
220
+ const stagedDraftDir = join(_stagingRoot, domain);
221
+ const hasStagedDraft = existsSync(join(stagedDraftDir, "guide.md"));
222
+ return {
223
+ content: [
224
+ {
225
+ type: "text",
226
+ text: hasStagedDraft
227
+ ? `No SAVED API guide for '${domain}' — scaffold reads the saved guide, not a staged draft.\n` +
228
+ ` You have a staged template at ${stagedDraftDir}/guide.md — save it first via\n` +
229
+ ` api-learn({domain: "${domain}", dir: "${stagedDraftDir}"}), then re-call api-scaffold.`
230
+ : `No API guide for '${domain}'. ` +
231
+ `Call api-guide({}) to list available guides, or author one first via api-learn({domain: "${domain}", new: true}) — ` +
232
+ `scaffold reads the SAVED guide.`,
233
+ },
234
+ ],
235
+ details: { error: "no_guide", domain, stagedDraft: hasStagedDraft },
236
+ };
237
+ }
238
+
239
+ let selected: { guide: ApiGuide; dirName: string };
240
+ if (matches.length === 1) {
241
+ selected = matches[0]!;
242
+ } else if (guideSelector) {
243
+ const sel = selectGuideByShortName(matches, guideSelector);
244
+ if (!sel.ok) {
245
+ return {
246
+ content: [
247
+ {
248
+ type: "text",
249
+ text: shortNameErrorText(
250
+ sel,
251
+ domain,
252
+ guideSelector,
253
+ `Call api-scaffold({domain: "${domain}", verify: true}) to see the menu.`,
254
+ ),
255
+ },
256
+ ],
257
+ details:
258
+ sel.reason === "no_match"
259
+ ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
260
+ : {
261
+ error: "ambiguous_shortname",
262
+ domain,
263
+ guide: guideSelector,
264
+ directories: sel.directories,
265
+ },
266
+ };
267
+ }
268
+ selected = sel;
269
+ } else {
270
+ // N guides, no selector → disambiguation menu (mirrors api-learn).
271
+ return {
272
+ content: [
273
+ {
274
+ type: "text",
275
+ text: [
276
+ `${matches.length} API guides for '${domain}':`,
277
+ formatGuideListings(matches),
278
+ `Call api-scaffold({domain: "${domain}", guide: "${matches[0]!.guide.shortName}", verify: true}) to scaffold one.`,
279
+ ].join("\n"),
280
+ },
281
+ ],
282
+ details: { mode: "menu", domain, disambiguation: matches.length },
283
+ };
284
+ }
285
+
286
+ const { guide, dirName } = selected;
287
+ const stagedDir = join(_stagingRoot, slug(guide.shortName));
288
+
289
+ // ── Refuse-to-overwrite (before any write) ────────────
290
+ if (helper && existsSync(join(stagedDir, "helper.ts"))) {
291
+ return {
292
+ content: [
293
+ {
294
+ type: "text",
295
+ text:
296
+ `⚠ Refusing to scaffold — ${join(stagedDir, "helper.ts")} already exists.\n` +
297
+ ` api-scaffold never overwrites a staged sibling. Delete the file from /tmp first, then re-call for a fresh scaffold.`,
298
+ },
299
+ ],
300
+ details: { error: "refuse_overwrite", domain, dirName, file: "helper.ts" },
301
+ };
302
+ }
303
+ if (verify && existsSync(join(stagedDir, "verify.json"))) {
304
+ return {
305
+ content: [
306
+ {
307
+ type: "text",
308
+ text:
309
+ `⚠ Refusing to scaffold — ${join(stagedDir, "verify.json")} already exists.\n` +
310
+ ` api-scaffold never overwrites a staged sibling. Delete the file from /tmp first, then re-call for a fresh scaffold.`,
311
+ },
312
+ ],
313
+ details: {
314
+ error: "refuse_overwrite",
315
+ domain,
316
+ dirName,
317
+ file: "verify.json",
318
+ },
319
+ };
320
+ }
321
+
322
+ // ── verify: load existing guides-dir sidecar for the merge ──
323
+ let existingVerify: Record<string, Record<string, unknown>> = {};
324
+ if (verify) {
325
+ const sidecar = loadVerifyJson(dirName);
326
+ if (sidecar && "error" in sidecar) {
327
+ return {
328
+ content: [
329
+ {
330
+ type: "text",
331
+ text:
332
+ `⚠ verify.json for '${dirName}' is malformed — cannot merge (${sidecar.error}).\n` +
333
+ ` Fix or delete ${join(getUserGuidesDir(), dirName, "verify.json")}, then re-call. Guides dir untouched.`,
334
+ },
335
+ ],
336
+ details: { error: "malformed_verify_json", domain, dirName },
337
+ };
338
+ }
339
+ if (sidecar && "data" in sidecar) existingVerify = sidecar.data;
340
+ }
341
+
342
+ mkdirSync(stagedDir, { recursive: true });
343
+
344
+ const written: string[] = [];
345
+ let helperPath: string | undefined;
346
+ let verifyPath: string | undefined;
347
+
348
+ if (helper) {
349
+ helperPath = join(stagedDir, "helper.ts");
350
+ writeFileSync(helperPath, helperStub(domain), "utf-8");
351
+ written.push(helperPath);
352
+ }
353
+ if (verify) {
354
+ verifyPath = join(stagedDir, "verify.json");
355
+ const merged = mergeVerifySentinels(guide, existingVerify);
356
+ writeFileSync(verifyPath, `${JSON.stringify(merged, null, 2)}\n`, "utf-8");
357
+ written.push(verifyPath);
358
+ }
359
+
360
+ let mode: string;
361
+ if (helper && verify) mode = "both";
362
+ else if (helper) mode = "helper";
363
+ else mode = "verify";
364
+
365
+ return {
366
+ content: [
367
+ {
368
+ type: "text",
369
+ text:
370
+ SCAFFOLD_MANUAL +
371
+ "\n\n" +
372
+ `🛠 Scaffolded '${guide.shortName}' (${dirName}) into ${stagedDir}\n` +
373
+ written.map((p) => ` ${p}`).join("\n") +
374
+ `\n Then save via api-learn({domain: "${domain}", dir: "${stagedDir}"}).`,
375
+ },
376
+ ],
377
+ details: {
378
+ mode,
379
+ domain,
380
+ dirName,
381
+ guide: guide.shortName,
382
+ stagedDir,
383
+ ...(helperPath === undefined ? {} : { helperPath }),
384
+ ...(verifyPath === undefined ? {} : { verifyPath }),
385
+ },
386
+ };
387
+ },
388
+
389
+ renderCall(args, theme, _context) {
390
+ const parts: string[] = [theme.fg("toolTitle", theme.bold("api-scaffold "))];
391
+ parts.push(theme.fg("accent", `"${args.domain}"`));
392
+ if (args.verify && args.helper) parts.push(theme.fg("dim", "🛠"));
393
+ else if (args.verify) parts.push(theme.fg("dim", "🔑"));
394
+ else if (args.helper) parts.push(theme.fg("dim", "🧩"));
395
+ return new Text(parts.join(" "), 0, 0);
396
+ },
397
+
398
+ renderResult(result, { expanded, isPartial }, theme, _context) {
399
+ if (isPartial) return new Text(theme.fg("warning", "Scaffolding…"), 0, 0);
400
+ const d = result.details as Record<string, unknown> | undefined;
401
+ if (d?.error) {
402
+ return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
403
+ }
404
+ const mode = d?.mode as string | undefined;
405
+ const domain = d?.domain as string | undefined;
406
+ const dirName = d?.dirName as string | undefined;
407
+ const stagedDir = d?.stagedDir as string | undefined;
408
+ const disambig = d?.disambiguation as number | undefined;
409
+
410
+ let text: string;
411
+ if (mode === "menu" && domain) {
412
+ text = theme.fg("dim", theme.bold("📖 menu"));
413
+ text += ` — ${disambig ?? "?"} guides for ${domain}`;
414
+ } else {
415
+ text = theme.fg("accent", theme.bold(`🛠 ${dirName ?? "?"}`));
416
+ text += ` — ${mode ?? "scaffold"} → ${stagedDir ?? "?"}`;
417
+ }
418
+ return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);
419
+ },
420
+ });
package/tools/index.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
- * Tool definitions barrel — exports all 4 tool definitions for registration.
2
+ * Tool definitions barrel — exports all 5 tool definitions for registration.
3
3
  */
4
4
  export { apiGuideTool } from "./api-guide.js";
5
5
  export { apiFetchTool } from "./api-fetch.js";
6
6
  export { apiLearnTool } from "./api-learn.js";
7
7
  export { apiProbeTool } from "./api-probe.js";
8
+ export { apiScaffoldTool } from "./api-scaffold.js";