pi-lean-host 0.0.1 → 0.1.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,578 @@
1
+ /**
2
+ * api-fetch tool definition.
3
+ *
4
+ * Executes an API operation from a registered guide:
5
+ * 1. Resolves all guides claiming `domain` and finds the one whose
6
+ * operation matches `operation` (op-name resolution across guides).
7
+ * 2. Calls the declared helper (`restGet` / `paginate`) via the matched
8
+ * guide's directory name (the helper-routing key).
9
+ * 3. Returns parsed items with a continuation handle if paginated.
10
+ *
11
+ * Self-correcting execute-fail: no guide for `domain` fails informingly,
12
+ * pointing at `api-guide({})` and `/api learn`.
13
+ *
14
+ * No ad-hoc bare-fetch mode — every request must follow a guide.
15
+ */
16
+
17
+ import { defineTool } from "@earendil-works/pi-coding-agent";
18
+ import { Type } from "@earendil-works/pi-ai";
19
+ import { Text } from "@earendil-works/pi-tui";
20
+ import { restGet, paginate, HelperError } from "../core/helpers.js";
21
+ import { findGuidesByDomain } from "../core/guide-store.js";
22
+ import { callHelper, loadTransform } from "../core/local-helpers.js";
23
+ import { formatGuideListings } from "../core/parse-api-guide.js";
24
+ import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
25
+ import { contentText, renderExpandedText } from "./utils.js";
26
+ import type { Operation, ApiGuide } from "../core/api-guide-types.js";
27
+
28
+ // ═══════════════════════════════════════════════════════════════════
29
+ // Test hook — bypasses the nextLink SSRF guard in `paginate`
30
+ // (127.0.0.1 / localhost are blocked in production). No-op for
31
+ // `restGet`, which no longer guards agent-supplied URLs.
32
+ // ═══════════════════════════════════════════════════════════════════
33
+
34
+ let _bypassUrlSafety = false;
35
+ export function __test__setBypassUrlSafety(v: boolean): void {
36
+ // Inert outside the test suite so the SSRF guard can't be flipped
37
+ // off in a production tarball.
38
+ if (process.env.NODE_ENV !== "test") return;
39
+ _bypassUrlSafety = v;
40
+ }
41
+
42
+ // ═══════════════════════════════════════════════════════════════════
43
+ // Tool definition
44
+ // ═══════════════════════════════════════════════════════════════════
45
+
46
+ export const apiFetchTool = defineTool({
47
+ name: "api-fetch",
48
+ label: "API Fetch",
49
+ description:
50
+ "Fetch structured data from a REST API using a recipe-based guide. " +
51
+ "Requires an API guide for the target domain. " +
52
+ "Call api-guide({domain}) to see available operations, or api-learn({domain, recipe}) to author a new guide.",
53
+
54
+ parameters: Type.Object({
55
+ domain: Type.String({
56
+ description:
57
+ "Domain registered in an API guide (e.g. 'boe.es'). Use api-guide to discover guides.",
58
+ }),
59
+ operation: Type.String({
60
+ description:
61
+ "Operation name from the guide (e.g. 'searchDiary'). Use api-guide({domain}) to list operations.",
62
+ }),
63
+ params: Type.Optional(
64
+ Type.Record(Type.String(), Type.Unknown(), {
65
+ description: "Path and query parameter values for the operation.",
66
+ }),
67
+ ),
68
+ gatherAll: Type.Optional(
69
+ Type.Boolean({
70
+ description:
71
+ "When true, paginate to gather all items up to the guide's gatherAllMax ceiling.",
72
+ }),
73
+ ),
74
+ }),
75
+
76
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
77
+ const sessionKey = ctx?.sessionManager?.getSessionId?.() ?? "api-default";
78
+ const { domain, operation } = params as {
79
+ domain: string;
80
+ operation: string;
81
+ params?: Record<string, unknown>;
82
+ gatherAll?: boolean;
83
+ };
84
+
85
+ // `gatherAll` may be passed at the tool's top level (the documented
86
+ // position) or nested inside `params` (the natural place, since `params`
87
+ // holds the operation arguments). Resolve both, preferring the top level,
88
+ // and strip `gatherAll` out of the forwarded params so it can't leak onto
89
+ // a `passthrough` query string or reach a domain helper. This must happen
90
+ // before `executeParams` is built below.
91
+ const rawParams = (params as Record<string, unknown>)["params"] as
92
+ | Record<string, unknown>
93
+ | undefined;
94
+ const gatherAll =
95
+ ((params as Record<string, unknown>)["gatherAll"] as
96
+ | boolean
97
+ | undefined) ?? (rawParams?.gatherAll as boolean | undefined);
98
+ const userParams = rawParams ? { ...rawParams } : undefined;
99
+ if (userParams && "gatherAll" in userParams) {
100
+ delete userParams.gatherAll;
101
+ }
102
+
103
+ // 1. Resolve guides by domain — a domain may be claimed by more than
104
+ // one guide (one domain, multiple APIs). Search every match for the
105
+ // named operation: exactly one hit executes (resolved via that guide's
106
+ // dirName, the helper-routing key); zero lists ops from all matches; an
107
+ // op name appearing in ≥2 guides is an ambiguous collision the authors
108
+ // must fix (re-author via api-learn to rename). dirName diverges from
109
+ // `domain` exactly in the multi-recipe case, so the helper is resolved
110
+ // by dirName, not the routing param.
111
+ const matches = findGuidesByDomain(domain);
112
+ if (matches.length === 0) {
113
+ return {
114
+ content: [
115
+ {
116
+ type: "text",
117
+ text:
118
+ `No API guide for '${domain}'. ` +
119
+ `Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author a new one.`,
120
+ },
121
+ ],
122
+ details: { error: "no_guide", domain },
123
+ };
124
+ }
125
+
126
+ const opMatches: { guide: ApiGuide; dirName: string; op: Operation }[] = [];
127
+ for (const { guide, dirName } of matches) {
128
+ const op = guide.operations.find((o) => o.name === operation);
129
+ if (op) opMatches.push({ guide, dirName, op });
130
+ }
131
+
132
+ if (opMatches.length === 0) {
133
+ const known = matches
134
+ .flatMap(({ guide }) => guide.operations.map((o) => o.name))
135
+ .join(", ");
136
+ return {
137
+ content: [
138
+ {
139
+ type: "text",
140
+ text: `No operation '${operation}' in guide(s) for '${domain}'. Available: ${known}. Call api-guide({domain: "${domain}"}) for details.`,
141
+ },
142
+ ],
143
+ details: { error: "no_operation", domain, operation },
144
+ };
145
+ }
146
+
147
+ if (opMatches.length > 1) {
148
+ return {
149
+ content: [
150
+ {
151
+ type: "text",
152
+ text: formatAmbiguousOperation(domain, operation, opMatches),
153
+ },
154
+ ],
155
+ details: { error: "ambiguous_operation", domain, operation },
156
+ };
157
+ }
158
+
159
+ const { guide, dirName: helperDirName, op } = opMatches[0]!;
160
+
161
+ // 2.5 Resolve local helper if the operation declares one.
162
+ // The helper is resolved by the matched guide's directory name
163
+ // (helperDirName), not by a helper name — one helper per guide lives
164
+ // at <guidesDir>/<dirName>/helper.ts. dirName may differ from the
165
+ // routing `domain` in the multi-recipe case.
166
+ let executeParams = userParams ?? {};
167
+ if (op.helper === true) {
168
+ const helperResult = await callHelper(
169
+ helperDirName,
170
+ op.name,
171
+ executeParams,
172
+ );
173
+ if (!helperResult.ok) {
174
+ return {
175
+ content: [
176
+ {
177
+ type: "text",
178
+ text: formatHelperDisabled(
179
+ helperResult.error,
180
+ helperDirName,
181
+ domain,
182
+ operation,
183
+ ),
184
+ },
185
+ ],
186
+ details: {
187
+ error: "helper_disabled",
188
+ domain,
189
+ operation,
190
+ },
191
+ };
192
+ }
193
+ executeParams = helperResult.params;
194
+ }
195
+
196
+ // 2.6 Resolve the post-response transform if the operation declares one.
197
+ // Loaded once before dispatch via `loadTransform(dirName)` (the helper
198
+ // is resolved by the matched guide's directory name, same as pre-call
199
+ // helpers). The executor hookpoint applies it and owns the try/catch —
200
+ // a throw never escapes. No disable map: a failed transform is retried
201
+ // on the next call.
202
+ const transformFn =
203
+ op.transform === true ? await loadTransform(helperDirName) : null;
204
+ if (op.transform === true && transformFn === null) {
205
+ console.warn(
206
+ `⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
207
+ );
208
+ }
209
+
210
+ // 3. Execute via the declared helper.
211
+ try {
212
+ const helperOpts = {
213
+ ...(_bypassUrlSafety ? { skipSsrfGuard: true } : {}),
214
+ };
215
+
216
+ if (op.via === "restGet") {
217
+ const result = await restGet(
218
+ guide.apiHost,
219
+ op,
220
+ executeParams,
221
+ guide,
222
+ undefined, // opts — restGet has no SSRF guard to bypass
223
+ transformFn ?? undefined,
224
+ helperDirName,
225
+ );
226
+ let text = formatResult(result.data, guide, op, sessionKey, result.url);
227
+ if (result.transformWarning !== undefined) {
228
+ text =
229
+ `⚠ Transform failed: ${result.transformWarning}. Returning raw response.\n` +
230
+ text;
231
+ }
232
+ if (gatherAll) {
233
+ text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
234
+ }
235
+ return {
236
+ content: [{ type: "text", text }],
237
+ details: {
238
+ domain,
239
+ operation,
240
+ shortName: guide.shortName,
241
+ via: "restGet",
242
+ request: { method: "GET", url: result.url, params: result.params },
243
+ headers: result.headers,
244
+ },
245
+ };
246
+ }
247
+
248
+ if (op.via === "paginate") {
249
+ const paginateOpts: Parameters<typeof paginate>[4] = {
250
+ ...helperOpts,
251
+ };
252
+ if (gatherAll !== undefined) paginateOpts.gatherAll = gatherAll;
253
+ const result = await paginate(
254
+ guide.apiHost,
255
+ op,
256
+ executeParams,
257
+ guide,
258
+ paginateOpts,
259
+ transformFn ?? undefined,
260
+ helperDirName,
261
+ );
262
+ const firstUrl = result.urls[0] ?? "";
263
+ const serverTotal = result.serverTotal;
264
+ const text =
265
+ result.items.length === 0 && !result.failedItems
266
+ ? [
267
+ `📦 0 item(s) fetched`,
268
+ formatRequestLine("GET", firstUrl),
269
+ ` pages fetched: ${result.pages}${result.ceilingHit ? " · ceiling: reached" : ""}`,
270
+ ...formatServerTotalLines(serverTotal, 0),
271
+ ].join("\n")
272
+ : formatPaginatedResult(
273
+ result.items,
274
+ result.totalFetched,
275
+ result.ceilingHit,
276
+ sessionKey,
277
+ firstUrl,
278
+ result.pages,
279
+ serverTotal,
280
+ result.failedItems,
281
+ );
282
+ return {
283
+ content: [{ type: "text", text }],
284
+ details: {
285
+ domain,
286
+ operation,
287
+ shortName: guide.shortName,
288
+ via: "paginate",
289
+ request: {
290
+ method: "GET",
291
+ url: firstUrl,
292
+ params: result.params,
293
+ pages: result.pages,
294
+ urls: result.urls,
295
+ },
296
+ totalFetched: result.totalFetched,
297
+ ...(serverTotal !== undefined ? { serverTotal } : {}),
298
+ ceilingHit: result.ceilingHit,
299
+ },
300
+ };
301
+ }
302
+
303
+ // TypeScript guard — all ExecutorVia values handled above.
304
+ return {
305
+ content: [
306
+ { type: "text", text: `Unhandled executor '${op.via as string}'.` },
307
+ ],
308
+ details: { error: "unhandled_via", via: op.via },
309
+ };
310
+ } catch (err) {
311
+ if (err instanceof HelperError) {
312
+ return {
313
+ content: [
314
+ {
315
+ type: "text",
316
+ text: formatHelperError(err, domain, operation),
317
+ },
318
+ ],
319
+ details: {
320
+ error: "helper_error",
321
+ field: err.field,
322
+ message: err.message,
323
+ },
324
+ };
325
+ }
326
+ return {
327
+ content: [
328
+ {
329
+ type: "text",
330
+ text:
331
+ `api-fetch failed for '${domain}' / '${operation}': ` +
332
+ `${err instanceof Error ? err.message : String(err)}`,
333
+ },
334
+ ],
335
+ details: { error: "unexpected", message: String(err) },
336
+ };
337
+ }
338
+ },
339
+
340
+ renderCall(args, theme, _context) {
341
+ const parts: string[] = [theme.fg("toolTitle", theme.bold("api-fetch "))];
342
+ parts.push(theme.fg("accent", `"${args.domain}"`));
343
+ if (args.operation) {
344
+ parts.push(theme.fg("dim", `› ${args.operation}`));
345
+ }
346
+ // Optional scalar param hint in collapsed view.
347
+ const rawParams = args.params;
348
+ if (rawParams && typeof rawParams === "object") {
349
+ const keys = Object.keys(rawParams);
350
+ if (keys.length > 0 && keys.length <= 3) {
351
+ const summary = keys
352
+ .filter((k) =>
353
+ ["string", "number", "boolean"].includes(typeof rawParams[k]),
354
+ )
355
+ .map((k) => `${k}: ${rawParams[k]}`)
356
+ .join(", ");
357
+ if (summary) parts.push(theme.fg("dim", `{${summary}}`));
358
+ }
359
+ }
360
+ return new Text(parts.join(" "), 0, 0);
361
+ },
362
+
363
+ renderResult(result, { expanded, isPartial }, theme, _context) {
364
+ if (isPartial) return new Text(theme.fg("warning", "Fetching…"), 0, 0);
365
+ const d = result.details as Record<string, unknown> | undefined;
366
+ if (d?.error)
367
+ return new Text(
368
+ theme.fg("error", `Fetch failed: ${contentText(result, "?")}`),
369
+ 0,
370
+ 0,
371
+ );
372
+
373
+ const shortName = (d?.shortName as string) || (d?.domain as string) || "?";
374
+ const operation = (d?.operation as string) || "?";
375
+ const reqUrl =
376
+ ((d?.request as Record<string, unknown>)?.url as string) || "";
377
+ const totalFetched = d?.totalFetched as number | undefined;
378
+
379
+ let text = theme.fg("accent", theme.bold(`📡 ${shortName}`));
380
+ text += ` — ${operation} · GET ${reqUrl}`;
381
+ if (totalFetched !== undefined) {
382
+ text += `\n📦 ${totalFetched} item(s) fetched`;
383
+ }
384
+
385
+ const content = contentText(result);
386
+ if (expanded) {
387
+ text += "\n";
388
+ text = renderExpandedText(text, theme, content, 1000);
389
+ } else {
390
+ text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
391
+ }
392
+ return new Text(text, 0, 0);
393
+ },
394
+ });
395
+
396
+ // ═══════════════════════════════════════════════════════════════════
397
+ // Formatting helpers
398
+ // ═══════════════════════════════════════════════════════════════════
399
+
400
+ const INLINE_LIMIT = 4000;
401
+
402
+ /**
403
+ * Format a request URL line for result transparency.
404
+ */
405
+ function formatRequestLine(method: string, url: string): string {
406
+ return `🔗 ${method} ${url}`;
407
+ }
408
+
409
+ /**
410
+ * Newline-aware cut position: break at the last newline before `limit`,
411
+ * falling back to a hard cut at `limit` if no newline in the second half.
412
+ */
413
+ function cutAtNewline(s: string, limit: number): number {
414
+ const cut = s.lastIndexOf("\n", limit);
415
+ return cut < limit / 2 ? limit : cut;
416
+ }
417
+
418
+ /**
419
+ * Truncate a pretty-printed JSON to INLINE_LIMIT (newline-aware, ending on "…"),
420
+ * and when truncation occurs spill the full body to disk and append the pointer.
421
+ */
422
+ function formatJsonSnippet(json: string, sessionKey: string): string {
423
+ const tooLarge = json.length > INLINE_LIMIT;
424
+ const cut = tooLarge ? cutAtNewline(json, INLINE_LIMIT) : json.length;
425
+ const snippet = tooLarge ? json.slice(0, cut) + "\n…" : json;
426
+ if (!tooLarge) return snippet;
427
+ const spill = spillResponse(json, sessionKey);
428
+ return snippet + "\n" + formatSpillNotice(spill, json.length);
429
+ }
430
+
431
+ function formatResult(
432
+ data: unknown,
433
+ guide: ApiGuide,
434
+ op: Operation,
435
+ sessionKey: string,
436
+ url?: string,
437
+ ): string {
438
+ const lines: string[] = [];
439
+ lines.push(`📡 ${guide.shortName} — ${op.name}`);
440
+ lines.push(` ${op.path}`);
441
+ if (url) lines.push(formatRequestLine("GET", url));
442
+ lines.push("");
443
+ lines.push(formatJsonSnippet(JSON.stringify(data, null, 2), sessionKey));
444
+ return lines.join("\n");
445
+ }
446
+
447
+ /**
448
+ * Footer for paginate results. When the guide declares `totalCountPath` and the
449
+ * server reported a total, stacks lines like `server total: N` / `remaining: …`.
450
+ * Returns [] when the server total is unknown (guides without a count path).
451
+ */
452
+ function formatServerTotalLines(
453
+ serverTotal: number | undefined,
454
+ totalFetched: number,
455
+ ): string[] {
456
+ if (serverTotal === undefined) return [];
457
+ const lines = [` server total: ${serverTotal}`];
458
+ if (serverTotal > totalFetched) {
459
+ lines.push(` remaining: ${serverTotal - totalFetched}`);
460
+ }
461
+ return lines;
462
+ }
463
+
464
+ function formatPaginatedResult(
465
+ items: unknown[],
466
+ totalFetched: number,
467
+ ceilingHit: boolean,
468
+ sessionKey: string,
469
+ firstUrl?: string,
470
+ pages?: number,
471
+ serverTotal?: number,
472
+ failedItems?: unknown[],
473
+ ): string {
474
+ const lines: string[] = [];
475
+ lines.push(`📦 ${totalFetched} item(s) fetched`);
476
+ if (firstUrl) lines.push(formatRequestLine("GET", firstUrl));
477
+ if (pages !== undefined && pages > 0) {
478
+ lines.push(
479
+ ` pages fetched: ${pages}${ceilingHit ? " · ceiling: reached" : ""}`,
480
+ );
481
+ }
482
+ lines.push(...formatServerTotalLines(serverTotal, totalFetched));
483
+ if (ceilingHit) {
484
+ lines.push(` ⚠ Ceiling reached — not all items were gathered.`);
485
+ } else if (totalFetched > 0) {
486
+ lines.push(
487
+ ` 💡 Pass gatherAll: true to fetch all pages (up to the guide's ceiling).`,
488
+ );
489
+ }
490
+ lines.push("");
491
+ lines.push(formatJsonSnippet(JSON.stringify(items, null, 2), sessionKey));
492
+ if (failedItems && failedItems.length > 0) {
493
+ lines.push("");
494
+ lines.push(
495
+ `⠂ ${failedItems.length} item(s) failed transform (raw, untransformed):`,
496
+ );
497
+ lines.push(
498
+ formatJsonSnippet(JSON.stringify(failedItems, null, 2), sessionKey),
499
+ );
500
+ }
501
+ return lines.join("\n");
502
+ }
503
+
504
+ /**
505
+ * Ambiguous-operation error: the op name appears in ≥2 guides for one
506
+ * domain. Shows the disambiguation listing, then points the agent at
507
+ * api-guide to read each recipe and api-learn to re-author with the op
508
+ * renamed. api-learn rewrites a whole recipe, not a single op — the
509
+ * message sets that expectation. No `guide:` selector is referenced on
510
+ * api-fetch (that param is deferred as YAGNI), so the message must not
511
+ * point at one.
512
+ */
513
+ function formatAmbiguousOperation(
514
+ domain: string,
515
+ operation: string,
516
+ opMatches: { guide: ApiGuide; dirName: string; op: Operation }[],
517
+ ): string {
518
+ const lines: string[] = [];
519
+ lines.push(
520
+ `Ambiguous operation '${operation}' for '${domain}' — found in ${opMatches.length} guides:`,
521
+ );
522
+ lines.push(formatGuideListings(opMatches));
523
+ const first = opMatches[0]!;
524
+ lines.push("");
525
+ lines.push(
526
+ `The operation '${operation}' appears in multiple guides for '${domain}'.`,
527
+ );
528
+ lines.push(
529
+ `Call api-guide({domain: "${domain}", guide: "${first.guide.shortName}"}) to read each guide's full recipe,`,
530
+ );
531
+ lines.push(
532
+ `then re-author one guide via api-learn({domain: "${first.dirName}", recipe: …}) with the colliding operation renamed so the names no longer clash.`,
533
+ );
534
+ lines.push(
535
+ `Note: api-learn rewrites a whole recipe, not a single operation.`,
536
+ );
537
+ return lines.join("\n");
538
+ }
539
+
540
+ function formatHelperDisabled(
541
+ message: string,
542
+ helperDirName: string,
543
+ domain: string,
544
+ operation: string,
545
+ ): string {
546
+ // dirName (not routing `domain`) is where the helper file lives —
547
+ // they diverge in the multi-recipe case; naming `domain` sends the
548
+ // user to the wrong file.
549
+ const lines: string[] = [
550
+ `⚠ api-fetch error for '${domain}' / '${operation}':`,
551
+ ` ${message}`,
552
+ ` Helper directory: ${helperDirName}`,
553
+ "",
554
+ "Call api-guide({domain: …}) to review the guide, or fix the helper file and restart the session.",
555
+ ];
556
+ return lines.join("\n");
557
+ }
558
+
559
+ function formatHelperError(
560
+ err: HelperError,
561
+ domain: string,
562
+ operation: string,
563
+ ): string {
564
+ const lines: string[] = [
565
+ `⚠ api-fetch error for '${domain}' / '${operation}':`,
566
+ ` ${err.message}`,
567
+ ` Field: ${err.field}`,
568
+ ];
569
+ if (err.expected) lines.push(` Expected: ${err.expected}`);
570
+ if (err.found) lines.push(` Found: ${err.found}`);
571
+ if (err.fix) lines.push(` Fix: ${err.fix}`);
572
+ if (err.url) lines.push(formatRequestLine("GET", err.url));
573
+ lines.push("");
574
+ lines.push(
575
+ `Call api-guide({domain: "${domain}"}) to review the guide, or api-learn({domain: "${domain}", recipe: …}) to fix it.`,
576
+ );
577
+ return lines.join("\n");
578
+ }