pi-lean-host 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,20 +17,23 @@
17
17
  import { defineTool } from "@earendil-works/pi-coding-agent";
18
18
  import { Type } from "@earendil-works/pi-ai";
19
19
  import { Text } from "@earendil-works/pi-tui";
20
- import { restGet, paginate, HelperError } from "../core/helpers.js";
20
+ import {
21
+ HelperError,
22
+ type RestGetResult,
23
+ type PaginateResult,
24
+ } from "../core/helpers.js";
21
25
  import { findGuidesByDomain } from "../core/guide-store.js";
22
- import { callHelper, loadTransform } from "../core/local-helpers.js";
23
26
  import {
24
- resolveSecretHeaders,
25
- resolveSecretQueryParams,
26
- authStatusLine,
27
- canonicalStoreDomain,
28
- containsSecret,
29
- type SecretResolution,
30
- type QuerySecretResolution,
31
- } from "../core/auth.js";
27
+ resolveOpForExecution,
28
+ type ResolveOpOptions,
29
+ type ResolveOpResult,
30
+ } from "../core/resolve-op.js";
31
+ import { canonicalStoreDomain, containsSecret } from "../core/auth.js";
32
32
  import { provisionedDomainsSuffix } from "../core/secrets-store.js";
33
- import { formatGuideListings } from "../core/parse-api-guide.js";
33
+ import {
34
+ formatGuideListings,
35
+ staleSchemaLine,
36
+ } from "../core/parse-api-guide.js";
34
37
  import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
35
38
  import { appendFooter, contentText } from "./utils.js";
36
39
  import type { Operation, ApiGuide } from "../core/api-guide-types.js";
@@ -59,7 +62,7 @@ export const apiFetchTool = defineTool({
59
62
  description:
60
63
  "Fetch structured data from a REST API using a recipe-based guide. " +
61
64
  "Requires an API guide for the target domain. " +
62
- "Call api-guide({domain}) to see available operations, or api-learn({domain, recipe}) to author a new guide.",
65
+ "Call api-guide({domain}) to see available operations, or api-learn({domain, recipeFile}) to author a new guide.",
63
66
 
64
67
  parameters: Type.Object({
65
68
  domain: Type.String({
@@ -167,224 +170,19 @@ export const apiFetchTool = defineTool({
167
170
 
168
171
  const { guide, dirName: helperDirName, op } = opMatches[0]!;
169
172
 
170
- // 2.5.5 The canonical secret-store key: `guide.domains[0]` (the plain
171
- // browsable domain). Independent of the routing `domain` the agent
172
- // passed — auth resolution, the fail-closed error, and the footer all
173
- // key the store on this canonical value, not on `domain`.
173
+ // The canonical secret-store key: `guide.domains[0]` (the plain
174
+ // browsable domain), used for the fail-closed error below.
174
175
  const storeDomain = canonicalStoreDomain(guide);
175
176
 
176
- // 2.5 Resolve local helper if the operation declares one.
177
- // The helper is resolved by the matched guide's directory name
178
- // (helperDirName), not by a helper name — one helper per guide lives
179
- // at <guidesDir>/<dirName>/helper.ts. dirName may differ from the
180
- // routing `domain` in the multi-recipe case.
181
- let executeParams = userParams ?? {};
182
- if (op.helper === true) {
183
- const helperResult = await callHelper(helperDirName, op.name, executeParams);
184
- if (!helperResult.ok) {
185
- return {
186
- content: [
187
- {
188
- type: "text",
189
- text: formatHelperDisabled(
190
- helperResult.error,
191
- helperDirName,
192
- domain,
193
- operation,
194
- ),
195
- },
196
- ],
197
- details: {
198
- error: "helper_disabled",
199
- domain,
200
- operation,
201
- },
202
- };
203
- }
204
- executeParams = helperResult.params;
205
- }
206
-
207
- // 2.6 Resolve the post-response transform if the operation declares one.
208
- // Loaded once before dispatch via `loadTransform(dirName)` (the helper
209
- // is resolved by the matched guide's directory name, same as pre-call
210
- // helpers). The executor hookpoint applies it and owns the try/catch —
211
- // a throw never escapes. No disable map: a failed transform is retried
212
- // on the next call.
213
- const transformFn =
214
- op.transform === true ? await loadTransform(helperDirName) : null;
215
- if (op.transform === true && transformFn === null) {
216
- console.warn(
217
- `⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
218
- );
219
- }
220
-
221
- // 2.7 Authentication (kind: static-key): resolve store-injected secret
222
- // headers AND query params up front so a missing required secret
223
- // fails closed BEFORE any request is made. Values never leave this
224
- // scope — only header/param and secret NAMES ever surface to the agent.
225
- let headerRes: SecretResolution | undefined;
226
- let queryRes: QuerySecretResolution | undefined;
227
- if (guide.auth.kind === "static-key") {
228
- headerRes = resolveSecretHeaders(guide.auth, storeDomain);
229
- queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
230
- const missingRequired = [
231
- ...(headerRes.absentRequired ?? []),
232
- ...(queryRes.absentRequired ?? []),
233
- ];
234
- if (missingRequired.length > 0) {
235
- const text =
236
- `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
237
- `${missingRequired.join(", ")}.\n` +
238
- `Run /api secrets ${storeDomain} to provision it, then retry this call.` +
239
- provisionedDomainsSuffix(storeDomain);
240
- return {
241
- content: [{ type: "text", text }],
242
- details: {
243
- error: "auth_required_not_provisioned",
244
- domain,
245
- operation,
246
- missing: missingRequired,
247
- },
248
- };
249
- }
250
- }
251
- const headerValues = headerRes
252
- ? [...Object.values(headerRes.headers), ...headerRes.rawHeaderValues]
253
- : [];
254
- const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
255
- const authOpts: {
256
- authHeaders?: Record<string, string>;
257
- secretHeaderNames?: Set<string>;
258
- secretValues?: string[];
259
- secretQueryParams?: Record<string, string>;
260
- secretQueryParamNames?: Set<string>;
261
- } =
262
- headerRes || queryRes
263
- ? {
264
- ...(headerRes
265
- ? {
266
- authHeaders: headerRes.headers,
267
- secretHeaderNames: new Set(
268
- Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
269
- ),
270
- }
271
- : {}),
272
- ...(queryRes
273
- ? {
274
- secretQueryParams: queryRes.queryParams,
275
- secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
276
- }
277
- : {}),
278
- secretValues: [...headerValues, ...queryValues],
279
- }
280
- : {};
281
- const authFooter = authStatusLine(guide.auth, storeDomain);
282
-
283
- // 3. Execute via the declared helper.
177
+ // Shared resolution + dispatch (callHelper + loadTransform + auth
178
+ // resolution + executor) — see core/resolve-op.ts. api-fetch and
179
+ // /api verify both route through it so the sequence can't drift.
180
+ let outcome: ResolveOpResult;
284
181
  try {
285
- const helperOpts = {
286
- ...(_bypassUrlSafety ? { skipSsrfGuard: true } : {}),
287
- };
288
-
289
- if (op.via === "restGet") {
290
- const result = await restGet(
291
- guide.apiHost,
292
- op,
293
- executeParams,
294
- guide,
295
- authOpts, // opts — restGet has no SSRF bypass; auth headers injected here
296
- transformFn ?? undefined,
297
- helperDirName,
298
- );
299
- let text = formatResult(result.data, guide, op, sessionKey, result.url);
300
- if (result.transformWarning !== undefined) {
301
- text =
302
- `⚠ Transform failed: ${result.transformWarning}. Returning raw response.\n` +
303
- text;
304
- }
305
- if (gatherAll) {
306
- text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
307
- }
308
- if (authFooter) text += `\n${authFooter}`;
309
- return {
310
- content: [{ type: "text", text }],
311
- details: {
312
- domain,
313
- operation,
314
- shortName: guide.shortName,
315
- via: "restGet",
316
- request: { method: "GET", url: result.url, params: result.params },
317
- // Output-channel audit: drop response headers that echo a known
318
- // secret value (an auth-bearing server must not leak the key).
319
- headers: scrubSecretHeaders(result.headers, authOpts.secretValues),
320
- },
321
- };
322
- }
323
-
324
- if (op.via === "paginate") {
325
- const paginateOpts: Parameters<typeof paginate>[4] = {
326
- ...helperOpts,
327
- ...authOpts,
328
- };
329
- if (gatherAll !== undefined) paginateOpts.gatherAll = gatherAll;
330
- const result = await paginate(
331
- guide.apiHost,
332
- op,
333
- executeParams,
334
- guide,
335
- paginateOpts,
336
- transformFn ?? undefined,
337
- helperDirName,
338
- );
339
- const firstUrl = result.urls[0] ?? "";
340
- const serverTotal = result.serverTotal;
341
- let text =
342
- result.items.length === 0 && !result.failedItems
343
- ? [
344
- `📦 0 item(s) fetched`,
345
- formatRequestLine("GET", firstUrl),
346
- ` pages fetched: ${result.pages}${result.ceilingHit ? " · ceiling: reached" : ""}`,
347
- ...formatServerTotalLines(serverTotal, 0),
348
- ].join("\n")
349
- : formatPaginatedResult(
350
- result.items,
351
- result.totalFetched,
352
- result.ceilingHit,
353
- sessionKey,
354
- firstUrl,
355
- result.pages,
356
- serverTotal,
357
- result.failedItems,
358
- );
359
- if (authFooter) text += `\n${authFooter}`;
360
- return {
361
- content: [{ type: "text", text }],
362
- details: {
363
- domain,
364
- operation,
365
- shortName: guide.shortName,
366
- via: "paginate",
367
- request: {
368
- method: "GET",
369
- url: firstUrl,
370
- params: result.params,
371
- pages: result.pages,
372
- urls: result.urls,
373
- },
374
- totalFetched: result.totalFetched,
375
- ...(serverTotal === undefined ? {} : { serverTotal }),
376
- ceilingHit: result.ceilingHit,
377
- },
378
- };
379
- }
380
-
381
- // TypeScript guard — all ExecutorVia values handled above.
382
- return {
383
- content: [
384
- { type: "text", text: `Unhandled executor '${op.via as string}'.` },
385
- ],
386
- details: { error: "unhandled_via", via: op.via },
387
- };
182
+ const execOpts: ResolveOpOptions = { skipSsrfGuard: _bypassUrlSafety };
183
+ if (userParams) execOpts.userParams = userParams;
184
+ if (gatherAll !== undefined) execOpts.gatherAll = gatherAll;
185
+ outcome = await resolveOpForExecution(guide, op, helperDirName, execOpts);
388
186
  } catch (err) {
389
187
  if (err instanceof HelperError) {
390
188
  return {
@@ -413,6 +211,128 @@ export const apiFetchTool = defineTool({
413
211
  details: { error: "unexpected", message: String(err) },
414
212
  };
415
213
  }
214
+
215
+ // Non-run outcomes: a session-disabled helper or a fail-closed missing
216
+ // `requires` secret. Both return before any request is made.
217
+ if (!outcome.ok) {
218
+ if (outcome.reason === "helper_disabled") {
219
+ return {
220
+ content: [
221
+ {
222
+ type: "text",
223
+ text: formatHelperDisabled(
224
+ outcome.message,
225
+ helperDirName,
226
+ domain,
227
+ operation,
228
+ ),
229
+ },
230
+ ],
231
+ details: {
232
+ error: "helper_disabled",
233
+ domain,
234
+ operation,
235
+ },
236
+ };
237
+ }
238
+ const text =
239
+ `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
240
+ `${outcome.missing.join(", ")}.\n` +
241
+ `Run /api secrets ${storeDomain} to provision it, then retry this call.` +
242
+ provisionedDomainsSuffix(storeDomain);
243
+ return {
244
+ content: [{ type: "text", text }],
245
+ details: {
246
+ error: "auth_required_not_provisioned",
247
+ domain,
248
+ operation,
249
+ missing: outcome.missing,
250
+ },
251
+ };
252
+ }
253
+
254
+ const { via, result, authFooter } = outcome;
255
+
256
+ if (via === "restGet") {
257
+ const r = result as RestGetResult;
258
+ let text = formatResult(r.data, guide, op, sessionKey, r.url);
259
+ if (r.transformWarning !== undefined) {
260
+ text =
261
+ `⚠ Transform failed: ${r.transformWarning}. Returning raw response.\n` +
262
+ text;
263
+ }
264
+ if (gatherAll) {
265
+ text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
266
+ }
267
+ if (authFooter) text += `\n${authFooter}`;
268
+ const staleNote = staleSchemaLine(guide);
269
+ if (staleNote) text += `\n${staleNote}`;
270
+ return {
271
+ content: [{ type: "text", text }],
272
+ details: {
273
+ domain,
274
+ operation,
275
+ shortName: guide.shortName,
276
+ via: "restGet",
277
+ request: { method: "GET", url: r.url, params: r.params },
278
+ // Output-channel audit: drop response headers that echo a known
279
+ // secret value (an auth-bearing server must not leak the key).
280
+ headers: scrubSecretHeaders(r.headers, outcome.authOpts.secretValues),
281
+ },
282
+ };
283
+ }
284
+
285
+ if (via === "paginate") {
286
+ const r = result as PaginateResult;
287
+ const firstUrl = r.urls[0] ?? "";
288
+ const serverTotal = r.serverTotal;
289
+ let text =
290
+ r.items.length === 0 && !r.failedItems
291
+ ? [
292
+ `📦 0 item(s) fetched`,
293
+ formatRequestLine("GET", firstUrl),
294
+ ` pages fetched: ${r.pages}${r.ceilingHit ? " · ceiling: reached" : ""}`,
295
+ ...formatServerTotalLines(serverTotal, 0),
296
+ ].join("\n")
297
+ : formatPaginatedResult(
298
+ r.items,
299
+ r.totalFetched,
300
+ r.ceilingHit,
301
+ sessionKey,
302
+ firstUrl,
303
+ r.pages,
304
+ serverTotal,
305
+ r.failedItems,
306
+ );
307
+ if (authFooter) text += `\n${authFooter}`;
308
+ const staleNote = staleSchemaLine(guide);
309
+ if (staleNote) text += `\n${staleNote}`;
310
+ return {
311
+ content: [{ type: "text", text }],
312
+ details: {
313
+ domain,
314
+ operation,
315
+ shortName: guide.shortName,
316
+ via: "paginate",
317
+ request: {
318
+ method: "GET",
319
+ url: firstUrl,
320
+ params: r.params,
321
+ pages: r.pages,
322
+ urls: r.urls,
323
+ },
324
+ totalFetched: r.totalFetched,
325
+ ...(serverTotal === undefined ? {} : { serverTotal }),
326
+ ceilingHit: r.ceilingHit,
327
+ },
328
+ };
329
+ }
330
+
331
+ // TypeScript guard — all ExecutorVia values handled above.
332
+ return {
333
+ content: [{ type: "text", text: `Unhandled executor '${via as string}'.` }],
334
+ details: { error: "unhandled_via", via },
335
+ };
416
336
  },
417
337
 
418
338
  renderCall(args, theme, _context) {
@@ -599,7 +519,7 @@ function formatAmbiguousOperation(
599
519
  `Call api-guide({domain: "${domain}", guide: "${first.guide.shortName}"}) to read each guide's full recipe,`,
600
520
  );
601
521
  lines.push(
602
- `then re-author one guide via api-learn({domain: "${first.dirName}", recipe: …}) with the colliding operation renamed so the names no longer clash.`,
522
+ `then re-author one guide via api-learn({domain: "${first.dirName}", recipeFile: …}) with the colliding operation renamed so the names no longer clash.`,
603
523
  );
604
524
  lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
605
525
  return lines.join("\n");
@@ -659,7 +579,7 @@ function formatHelperError(
659
579
  if (err.url) lines.push(formatRequestLine("GET", err.url));
660
580
  lines.push("");
661
581
  lines.push(
662
- `Call api-guide({domain: "${domain}"}) to review the guide, or api-learn({domain: "${domain}", recipe: …}) to fix it.`,
582
+ `Call api-guide({domain: "${domain}"}) to review the guide, or api-learn({domain: "${domain}", recipeFile: …}) to fix it.`,
663
583
  );
664
584
  return lines.join("\n");
665
585
  }
@@ -19,7 +19,13 @@ import {
19
19
  findGuidesByDomain,
20
20
  getCatalogText,
21
21
  } from "../core/guide-store.js";
22
- import { formatGuideListings, TODAY } from "../core/parse-api-guide.js";
22
+ import {
23
+ formatGuideListings,
24
+ selectGuideByShortName,
25
+ shortNameErrorText,
26
+ TODAY,
27
+ staleSchemaLine,
28
+ } from "../core/parse-api-guide.js";
23
29
  import { authStatusLine, canonicalStoreDomain } from "../core/auth.js";
24
30
  import type { ApiGuide } from "../core/api-guide-types.js";
25
31
 
@@ -71,7 +77,7 @@ export const apiGuideTool = defineTool({
71
77
  text:
72
78
  `No API guide for '${domain}'.` +
73
79
  (known.length > 0 ? ` Known guides: ${known.join(", ")}.` : "") +
74
- "\n\nCall api-guide with no params to list all guides, or api-learn({domain, recipe}) to author one.",
80
+ "\n\nCall api-guide with no params to list all guides, or api-learn({domain, recipeFile}) to author one.",
75
81
  },
76
82
  ],
77
83
  details: {},
@@ -82,51 +88,32 @@ export const apiGuideTool = defineTool({
82
88
  // No substring fallback — exact match is sufficient for v1 and avoids
83
89
  // the unambiguous-or-error branch the substring path forces.
84
90
  if (guideSelector) {
85
- const lc = guideSelector.toLowerCase();
86
- const selected = matches.filter(
87
- (m) => m.guide.shortName.toLowerCase() === lc,
88
- );
89
- if (selected.length === 0) {
90
- const valid = matches.map((m) => m.guide.shortName).join(", ");
91
+ const sel = selectGuideByShortName(matches, guideSelector);
92
+ if (!sel.ok) {
91
93
  return {
92
94
  content: [
93
95
  {
94
96
  type: "text",
95
- text:
96
- `No guide named '${guideSelector}' for '${domain}'. ` +
97
- `Available guides: ${valid}. ` +
97
+ text: shortNameErrorText(
98
+ sel,
99
+ domain,
100
+ guideSelector,
98
101
  `Call api-guide({domain: "${domain}"}) to see the menu.`,
102
+ ),
99
103
  },
100
104
  ],
101
- details: {
102
- error: "no_guide_by_shortname",
103
- domain,
104
- guide: guideSelector,
105
- },
106
- };
107
- }
108
- if (selected.length > 1) {
109
- const dirs = selected.map((s) => s.dirName).join(", ");
110
- return {
111
- content: [
112
- {
113
- type: "text",
114
- text:
115
- `Ambiguous guide '${guideSelector}' for '${domain}' — ` +
116
- `${selected.length} guides share shortName '${guideSelector}' ` +
117
- `(directories: ${dirs}). Rename one guide's shortName to ` +
118
- `disambiguate. Call api-guide({domain: "${domain}"}) to see the menu.`,
119
- },
120
- ],
121
- details: {
122
- error: "ambiguous_shortname",
123
- domain,
124
- guide: guideSelector,
125
- directories: selected.map((s) => s.dirName),
126
- },
105
+ details:
106
+ sel.reason === "no_match"
107
+ ? { error: "no_guide_by_shortname", domain, guide: guideSelector }
108
+ : {
109
+ error: "ambiguous_shortname",
110
+ domain,
111
+ guide: guideSelector,
112
+ directories: sel.directories,
113
+ },
127
114
  };
128
115
  }
129
- return renderGuideDetail(selected[0]!.guide, domain);
116
+ return renderGuideDetail(sel.guide, domain);
130
117
  }
131
118
 
132
119
  if (matches.length === 1) {
@@ -189,6 +176,8 @@ function renderGuideDetail(
189
176
  lines.push(` Domains: ${guide.domains?.join(", ") ?? "—"}`);
190
177
  lines.push(` Host: ${guide.apiHost}`);
191
178
  lines.push(` Verified: ${guide.verified} · Updated: ${guide.updated}`);
179
+ const stale = staleSchemaLine(guide);
180
+ if (stale) lines.push(stale);
192
181
  if (guide.docs) lines.push(` Docs: ${guide.docs}`);
193
182
  lines.push(` Auth: ${guide.auth.kind}`);
194
183
  // Auth status footer — shared with api-fetch. Metadata only (names,
@@ -230,6 +219,12 @@ function renderGuideDetail(
230
219
  return parts.join(" ");
231
220
  });
232
221
  lines.push(` params: ${rendered.join(", ")}`);
222
+ // At-least-one-of group — a single line naming the interchangeable
223
+ // params. Members are NOT rendered as `required` (parser bans
224
+ // required: true on them), so no suppression logic is needed.
225
+ if (op.requiresAnyOf && op.requiresAnyOf.length > 0) {
226
+ lines.push(` requires any of: ${op.requiresAnyOf.join(", ")}`);
227
+ }
233
228
  // Per-param hints (format, semantics) — these are the model's
234
229
  // primary guidance for shaping values, so they get their own lines.
235
230
  for (const [k, spec] of qParams) {