pi-lean-host 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,20 +17,25 @@
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
- type SecretResolution,
29
- type QuerySecretResolution,
30
- } from "../core/auth.js";
31
- import { formatGuideListings } from "../core/parse-api-guide.js";
27
+ resolveOpForExecution,
28
+ type ResolveOpOptions,
29
+ type ResolveOpResult,
30
+ } from "../core/resolve-op.js";
31
+ import { canonicalStoreDomain, containsSecret } from "../core/auth.js";
32
+ import { provisionedDomainsSuffix } from "../core/secrets-store.js";
33
+ import {
34
+ formatGuideListings,
35
+ staleSchemaLine,
36
+ } from "../core/parse-api-guide.js";
32
37
  import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
33
- import { contentText, renderExpandedText } from "./utils.js";
38
+ import { appendFooter, contentText } from "./utils.js";
34
39
  import type { Operation, ApiGuide } from "../core/api-guide-types.js";
35
40
 
36
41
  // ═══════════════════════════════════════════════════════════════════
@@ -165,253 +170,169 @@ export const apiFetchTool = defineTool({
165
170
 
166
171
  const { guide, dirName: helperDirName, op } = opMatches[0]!;
167
172
 
168
- // 2.5.5 The canonical secret-store key: `guide.domains[0]` (the plain
169
- // browsable domain). Independent of the routing `domain` the agent
170
- // passed — auth resolution, the fail-closed error, and the footer all
171
- // 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.
172
175
  const storeDomain = canonicalStoreDomain(guide);
173
176
 
174
- // 2.5 Resolve local helper if the operation declares one.
175
- // The helper is resolved by the matched guide's directory name
176
- // (helperDirName), not by a helper name — one helper per guide lives
177
- // at <guidesDir>/<dirName>/helper.ts. dirName may differ from the
178
- // routing `domain` in the multi-recipe case.
179
- let executeParams = userParams ?? {};
180
- if (op.helper === true) {
181
- const helperResult = await callHelper(helperDirName, op.name, executeParams);
182
- if (!helperResult.ok) {
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;
181
+ try {
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);
186
+ } catch (err) {
187
+ if (err instanceof HelperError) {
183
188
  return {
184
189
  content: [
185
190
  {
186
191
  type: "text",
187
- text: formatHelperDisabled(
188
- helperResult.error,
189
- helperDirName,
190
- domain,
191
- operation,
192
- ),
192
+ text: formatHelperError(err, domain, operation),
193
193
  },
194
194
  ],
195
195
  details: {
196
- error: "helper_disabled",
197
- domain,
198
- operation,
196
+ error: "helper_error",
197
+ field: err.field,
198
+ message: err.message,
199
199
  },
200
200
  };
201
201
  }
202
- executeParams = helperResult.params;
203
- }
204
-
205
- // 2.6 Resolve the post-response transform if the operation declares one.
206
- // Loaded once before dispatch via `loadTransform(dirName)` (the helper
207
- // is resolved by the matched guide's directory name, same as pre-call
208
- // helpers). The executor hookpoint applies it and owns the try/catch —
209
- // a throw never escapes. No disable map: a failed transform is retried
210
- // on the next call.
211
- const transformFn =
212
- op.transform === true ? await loadTransform(helperDirName) : null;
213
- if (op.transform === true && transformFn === null) {
214
- console.warn(
215
- `⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
216
- );
202
+ return {
203
+ content: [
204
+ {
205
+ type: "text",
206
+ text:
207
+ `api-fetch failed for '${domain}' / '${operation}': ` +
208
+ `${err instanceof Error ? err.message : String(err)}`,
209
+ },
210
+ ],
211
+ details: { error: "unexpected", message: String(err) },
212
+ };
217
213
  }
218
214
 
219
- // 2.7 Authentication (kind: static-key): resolve store-injected secret
220
- // headers AND query params up front so a missing required secret
221
- // fails closed BEFORE any request is made. Values never leave this
222
- // scope — only header/param and secret NAMES ever surface to the agent.
223
- let headerRes: SecretResolution | undefined;
224
- let queryRes: QuerySecretResolution | undefined;
225
- if (guide.auth.kind === "static-key") {
226
- headerRes = resolveSecretHeaders(guide.auth, storeDomain);
227
- queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
228
- const missingRequired = [
229
- ...(headerRes.absentRequired ?? []),
230
- ...(queryRes.absentRequired ?? []),
231
- ];
232
- if (missingRequired.length > 0) {
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") {
233
219
  return {
234
220
  content: [
235
221
  {
236
222
  type: "text",
237
- text:
238
- `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
239
- `${missingRequired.join(", ")}.\n` +
240
- `Run /api secrets ${storeDomain} to provision it, then retry this call.`,
223
+ text: formatHelperDisabled(
224
+ outcome.message,
225
+ helperDirName,
226
+ domain,
227
+ operation,
228
+ ),
241
229
  },
242
230
  ],
243
231
  details: {
244
- error: "auth_required_not_provisioned",
232
+ error: "helper_disabled",
245
233
  domain,
246
234
  operation,
247
- missing: missingRequired,
248
235
  },
249
236
  };
250
237
  }
251
- }
252
- const headerValues = headerRes ? Object.values(headerRes.headers) : [];
253
- const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
254
- const authOpts: {
255
- authHeaders?: Record<string, string>;
256
- secretHeaderNames?: Set<string>;
257
- secretValues?: string[];
258
- secretQueryParams?: Record<string, string>;
259
- secretQueryParamNames?: Set<string>;
260
- } =
261
- headerRes || queryRes
262
- ? {
263
- ...(headerRes
264
- ? {
265
- authHeaders: headerRes.headers,
266
- secretHeaderNames: new Set(
267
- Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
268
- ),
269
- }
270
- : {}),
271
- ...(queryRes
272
- ? {
273
- secretQueryParams: queryRes.queryParams,
274
- secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
275
- }
276
- : {}),
277
- secretValues: [...headerValues, ...queryValues],
278
- }
279
- : {};
280
- const authFooter = authStatusLine(guide.auth, storeDomain);
281
-
282
- // 3. Execute via the declared helper.
283
- try {
284
- const helperOpts = {
285
- ...(_bypassUrlSafety ? { skipSsrfGuard: true } : {}),
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
+ },
286
251
  };
252
+ }
287
253
 
288
- if (op.via === "restGet") {
289
- const result = await restGet(
290
- guide.apiHost,
291
- op,
292
- executeParams,
293
- guide,
294
- authOpts, // opts — restGet has no SSRF bypass; auth headers injected here
295
- transformFn ?? undefined,
296
- helperDirName,
297
- );
298
- let text = formatResult(result.data, guide, op, sessionKey, result.url);
299
- if (result.transformWarning !== undefined) {
300
- text =
301
- `⚠ Transform failed: ${result.transformWarning}. Returning raw response.\n` +
302
- text;
303
- }
304
- if (gatherAll) {
305
- text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
306
- }
307
- if (authFooter) text += `\n${authFooter}`;
308
- return {
309
- content: [{ type: "text", text }],
310
- details: {
311
- domain,
312
- operation,
313
- shortName: guide.shortName,
314
- via: "restGet",
315
- request: { method: "GET", url: result.url, params: result.params },
316
- // Output-channel audit: drop response headers that echo a known
317
- // secret value (an auth-bearing server must not leak the key).
318
- headers: scrubSecretHeaders(result.headers, authOpts.secretValues),
319
- },
320
- };
321
- }
254
+ const { via, result, authFooter } = outcome;
322
255
 
323
- if (op.via === "paginate") {
324
- const paginateOpts: Parameters<typeof paginate>[4] = {
325
- ...helperOpts,
326
- ...authOpts,
327
- };
328
- if (gatherAll !== undefined) paginateOpts.gatherAll = gatherAll;
329
- const result = await paginate(
330
- guide.apiHost,
331
- op,
332
- executeParams,
333
- guide,
334
- paginateOpts,
335
- transformFn ?? undefined,
336
- helperDirName,
337
- );
338
- const firstUrl = result.urls[0] ?? "";
339
- const serverTotal = result.serverTotal;
340
- let text =
341
- result.items.length === 0 && !result.failedItems
342
- ? [
343
- `📦 0 item(s) fetched`,
344
- formatRequestLine("GET", firstUrl),
345
- ` pages fetched: ${result.pages}${result.ceilingHit ? " · ceiling: reached" : ""}`,
346
- ...formatServerTotalLines(serverTotal, 0),
347
- ].join("\n")
348
- : formatPaginatedResult(
349
- result.items,
350
- result.totalFetched,
351
- result.ceilingHit,
352
- sessionKey,
353
- firstUrl,
354
- result.pages,
355
- serverTotal,
356
- result.failedItems,
357
- );
358
- if (authFooter) text += `\n${authFooter}`;
359
- return {
360
- content: [{ type: "text", text }],
361
- details: {
362
- domain,
363
- operation,
364
- shortName: guide.shortName,
365
- via: "paginate",
366
- request: {
367
- method: "GET",
368
- url: firstUrl,
369
- params: result.params,
370
- pages: result.pages,
371
- urls: result.urls,
372
- },
373
- totalFetched: result.totalFetched,
374
- ...(serverTotal === undefined ? {} : { serverTotal }),
375
- ceilingHit: result.ceilingHit,
376
- },
377
- };
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;
378
263
  }
379
-
380
- // TypeScript guard — all ExecutorVia values handled above.
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}`;
381
270
  return {
382
- content: [
383
- { type: "text", text: `Unhandled executor '${op.via as string}'.` },
384
- ],
385
- details: { error: "unhandled_via", via: op.via },
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
+ },
386
282
  };
387
- } catch (err) {
388
- if (err instanceof HelperError) {
389
- return {
390
- content: [
391
- {
392
- type: "text",
393
- text: formatHelperError(err, domain, operation),
394
- },
395
- ],
396
- details: {
397
- error: "helper_error",
398
- field: err.field,
399
- message: err.message,
400
- },
401
- };
402
- }
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}`;
403
310
  return {
404
- content: [
405
- {
406
- type: "text",
407
- text:
408
- `api-fetch failed for '${domain}' / '${operation}': ` +
409
- `${err instanceof Error ? err.message : String(err)}`,
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,
410
323
  },
411
- ],
412
- details: { error: "unexpected", message: String(err) },
324
+ totalFetched: r.totalFetched,
325
+ ...(serverTotal === undefined ? {} : { serverTotal }),
326
+ ceilingHit: r.ceilingHit,
327
+ },
413
328
  };
414
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
+ };
415
336
  },
416
337
 
417
338
  renderCall(args, theme, _context) {
@@ -458,14 +379,7 @@ export const apiFetchTool = defineTool({
458
379
  text += `\n📦 ${totalFetched} item(s) fetched`;
459
380
  }
460
381
 
461
- const content = contentText(result);
462
- if (expanded) {
463
- text += "\n";
464
- text = renderExpandedText(text, theme, content, 1000);
465
- } else {
466
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
467
- }
468
- return new Text(text, 0, 0);
382
+ return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
469
383
  },
470
384
  });
471
385
 
@@ -605,7 +519,7 @@ function formatAmbiguousOperation(
605
519
  `Call api-guide({domain: "${domain}", guide: "${first.guide.shortName}"}) to read each guide's full recipe,`,
606
520
  );
607
521
  lines.push(
608
- `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.`,
609
523
  );
610
524
  lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
611
525
  return lines.join("\n");
@@ -643,7 +557,7 @@ function scrubSecretHeaders(
643
557
  if (!secretValues || secretValues.length === 0) return headers;
644
558
  const out: Record<string, string> = {};
645
559
  for (const [k, v] of Object.entries(headers)) {
646
- if (secretValues.some((s) => s && v.includes(s))) continue;
560
+ if (containsSecret(v, secretValues)) continue;
647
561
  out[k] = v;
648
562
  }
649
563
  return out;
@@ -665,7 +579,7 @@ function formatHelperError(
665
579
  if (err.url) lines.push(formatRequestLine("GET", err.url));
666
580
  lines.push("");
667
581
  lines.push(
668
- `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.`,
669
583
  );
670
584
  return lines.join("\n");
671
585
  }
@@ -13,13 +13,19 @@ import {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
  import { Type } from "@earendil-works/pi-ai";
15
15
  import { Text } from "@earendil-works/pi-tui";
16
- import { contentText, renderExpandedText } from "./utils.js";
16
+ import { appendFooter, contentText } from "./utils.js";
17
17
  import {
18
18
  loadAllGuides,
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
 
@@ -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) {
@@ -171,14 +158,7 @@ export const apiGuideTool = defineTool({
171
158
  text += ` — ${guideCount} guides`;
172
159
  }
173
160
 
174
- const content = contentText(result);
175
- if (expanded) {
176
- text += "\n";
177
- text = renderExpandedText(text, theme, content, 800);
178
- } else {
179
- text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
180
- }
181
- return new Text(text, 0, 0);
161
+ return new Text(appendFooter(text, expanded, result, theme, 800), 0, 0);
182
162
  },
183
163
  });
184
164
 
@@ -196,6 +176,8 @@ function renderGuideDetail(
196
176
  lines.push(` Domains: ${guide.domains?.join(", ") ?? "—"}`);
197
177
  lines.push(` Host: ${guide.apiHost}`);
198
178
  lines.push(` Verified: ${guide.verified} · Updated: ${guide.updated}`);
179
+ const stale = staleSchemaLine(guide);
180
+ if (stale) lines.push(stale);
199
181
  if (guide.docs) lines.push(` Docs: ${guide.docs}`);
200
182
  lines.push(` Auth: ${guide.auth.kind}`);
201
183
  // Auth status footer — shared with api-fetch. Metadata only (names,
@@ -237,6 +219,12 @@ function renderGuideDetail(
237
219
  return parts.join(" ");
238
220
  });
239
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
+ }
240
228
  // Per-param hints (format, semantics) — these are the model's
241
229
  // primary guidance for shaping values, so they get their own lines.
242
230
  for (const [k, spec] of qParams) {
@@ -252,6 +240,7 @@ function renderGuideDetail(
252
240
  if (pagCfg.pageParam) bits.push(pagCfg.pageParam);
253
241
  if (pagCfg.pageSizeParam)
254
242
  bits.push(`${pagCfg.pageSizeParam}=${pagCfg.pageSize ?? 50}`);
243
+ if (pagCfg.base !== undefined) bits.push(`base=${pagCfg.base}`);
255
244
  lines.push(` pagination: ${bits.join(" ")}`);
256
245
  }
257
246
  }