pi-lean-host 0.2.0 → 0.2.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.
- package/README.md +50 -31
- package/core/api-guide-types.ts +30 -0
- package/core/auth.ts +42 -5
- package/core/guide-store.ts +0 -26
- package/core/helpers.ts +44 -24
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +138 -54
- package/core/path-template.ts +30 -1
- package/core/secrets-command.ts +25 -2
- package/core/secrets-store.ts +11 -1
- package/core/ssrf-guard.ts +5 -0
- package/core/transport.ts +2 -16
- package/package.json +11 -1
- package/tools/api-fetch.ts +14 -20
- package/tools/api-guide.ts +3 -9
- package/tools/api-learn.ts +16 -19
- package/tools/api-probe.ts +254 -62
- package/tools/utils.ts +21 -0
package/core/parse-api-guide.ts
CHANGED
|
@@ -250,6 +250,18 @@ function validatePagination(
|
|
|
250
250
|
}
|
|
251
251
|
cfg.pageSize = ps;
|
|
252
252
|
}
|
|
253
|
+
const base = p["base"];
|
|
254
|
+
if (base !== undefined) {
|
|
255
|
+
if (typeof base !== "number" || !Number.isInteger(base)) {
|
|
256
|
+
return fail(
|
|
257
|
+
file,
|
|
258
|
+
`${fieldPrefix}.base`,
|
|
259
|
+
"a finite integer (the seed value for the page param)",
|
|
260
|
+
describeFound(base),
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
cfg.base = base;
|
|
264
|
+
}
|
|
253
265
|
} else if (style === "nextLink") {
|
|
254
266
|
const nlp = p["nextLinkPath"];
|
|
255
267
|
if (typeof nlp !== "string" || nlp === "") {
|
|
@@ -382,6 +394,43 @@ function validateResponseShape(
|
|
|
382
394
|
// Auth
|
|
383
395
|
// ═══════════════════════════════════════════════════════════════════
|
|
384
396
|
|
|
397
|
+
/**
|
|
398
|
+
* Validate a `Record<string, string>` auth sub-field (headers, secretRefs,
|
|
399
|
+
* secretQueryRefs, headerPrefixes). Returns the parsed record, or a ParseError
|
|
400
|
+
* when `raw` is absent/null/non-object/an array, or a value fails `valueOk`
|
|
401
|
+
* (default: any string; `headerPrefixes` passes a non-empty check).
|
|
402
|
+
*/
|
|
403
|
+
function parseStringRecord(
|
|
404
|
+
raw: unknown,
|
|
405
|
+
file: string | undefined,
|
|
406
|
+
fm: string,
|
|
407
|
+
field: string,
|
|
408
|
+
expect: string,
|
|
409
|
+
valueOk: (v: unknown) => boolean = (v) => typeof v === "string",
|
|
410
|
+
): Record<string, string> | ParseApiGuideResult {
|
|
411
|
+
if (
|
|
412
|
+
raw === null ||
|
|
413
|
+
typeof raw !== "object" ||
|
|
414
|
+
Array.isArray(raw) ||
|
|
415
|
+
Object.values(raw).some((v) => !valueOk(v))
|
|
416
|
+
) {
|
|
417
|
+
return fail(file, field, expect, describeFound(raw), {
|
|
418
|
+
snippet: snippetFor(fm, "auth"),
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
return raw as Record<string, string>;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** `true` when a `parseStringRecord` / validator result is a ParseError. */
|
|
425
|
+
function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
|
|
426
|
+
return (
|
|
427
|
+
typeof v === "object" &&
|
|
428
|
+
v !== null &&
|
|
429
|
+
"ok" in v &&
|
|
430
|
+
(v as { ok: unknown }).ok === false
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
|
|
385
434
|
function validateAuth(
|
|
386
435
|
raw: unknown,
|
|
387
436
|
file: string | undefined,
|
|
@@ -424,66 +473,46 @@ function validateAuth(
|
|
|
424
473
|
}
|
|
425
474
|
// Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
|
|
426
475
|
let headers: Record<string, string> | undefined;
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
)
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
"auth.headers",
|
|
438
|
-
"a YAML mapping of string → string",
|
|
439
|
-
describeFound(headersRaw),
|
|
440
|
-
);
|
|
441
|
-
}
|
|
442
|
-
headers = headersRaw as Record<string, string>;
|
|
476
|
+
if (a["headers"] !== undefined) {
|
|
477
|
+
const hr = parseStringRecord(
|
|
478
|
+
a["headers"],
|
|
479
|
+
file,
|
|
480
|
+
fm,
|
|
481
|
+
"auth.headers",
|
|
482
|
+
"a YAML mapping of string → string",
|
|
483
|
+
);
|
|
484
|
+
if (isParseErr(hr)) return hr;
|
|
485
|
+
headers = hr;
|
|
443
486
|
}
|
|
444
487
|
|
|
445
488
|
// static-key reference fields (secretRefs/requires/optional).
|
|
446
489
|
let secretRefs: Record<string, string> | undefined;
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
)
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
"auth.secretRefs",
|
|
458
|
-
"a YAML mapping of header name → secret name",
|
|
459
|
-
describeFound(refsRaw),
|
|
460
|
-
{ snippet: snippetFor(fm, "auth") },
|
|
461
|
-
);
|
|
462
|
-
}
|
|
463
|
-
secretRefs = refsRaw as Record<string, string>;
|
|
490
|
+
if (a["secretRefs"] !== undefined) {
|
|
491
|
+
const sr = parseStringRecord(
|
|
492
|
+
a["secretRefs"],
|
|
493
|
+
file,
|
|
494
|
+
fm,
|
|
495
|
+
"auth.secretRefs",
|
|
496
|
+
"a YAML mapping of header name → secret name",
|
|
497
|
+
);
|
|
498
|
+
if (isParseErr(sr)) return sr;
|
|
499
|
+
secretRefs = sr;
|
|
464
500
|
}
|
|
465
501
|
|
|
466
502
|
// Query-param secrets: maps query param name → secret store name.
|
|
467
503
|
// Same shape + consistency rules as secretRefs; the collision-with-op-`params`
|
|
468
504
|
// rule is enforced in parseApiGuide (auth is parsed before operations).
|
|
469
505
|
let secretQueryRefs: Record<string, string> | undefined;
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
)
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
"auth.secretQueryRefs",
|
|
481
|
-
"a YAML mapping of query param name → secret name",
|
|
482
|
-
describeFound(sqrRaw),
|
|
483
|
-
{ snippet: snippetFor(fm, "auth") },
|
|
484
|
-
);
|
|
485
|
-
}
|
|
486
|
-
secretQueryRefs = sqrRaw as Record<string, string>;
|
|
506
|
+
if (a["secretQueryRefs"] !== undefined) {
|
|
507
|
+
const qr = parseStringRecord(
|
|
508
|
+
a["secretQueryRefs"],
|
|
509
|
+
file,
|
|
510
|
+
fm,
|
|
511
|
+
"auth.secretQueryRefs",
|
|
512
|
+
"a YAML mapping of query param name → secret name",
|
|
513
|
+
);
|
|
514
|
+
if (isParseErr(qr)) return qr;
|
|
515
|
+
secretQueryRefs = qr;
|
|
487
516
|
}
|
|
488
517
|
|
|
489
518
|
let requires: string[] | undefined;
|
|
@@ -524,10 +553,28 @@ function validateAuth(
|
|
|
524
553
|
optional = optRaw as string[];
|
|
525
554
|
}
|
|
526
555
|
|
|
556
|
+
// static-key header prefixes: header name → non-empty prefix string
|
|
557
|
+
// prepended to the resolved secret value. Same mapping shape as secretRefs;
|
|
558
|
+
// every key must also be a secretRefs header (a prefix for a non-secret
|
|
559
|
+
// header is a mistake).
|
|
560
|
+
let headerPrefixes: Record<string, string> | undefined;
|
|
561
|
+
if (a["headerPrefixes"] !== undefined) {
|
|
562
|
+
const hp = parseStringRecord(
|
|
563
|
+
a["headerPrefixes"],
|
|
564
|
+
file,
|
|
565
|
+
fm,
|
|
566
|
+
"auth.headerPrefixes",
|
|
567
|
+
"a YAML mapping of header name → non-empty prefix string",
|
|
568
|
+
(v) => typeof v === "string" && v.length > 0,
|
|
569
|
+
);
|
|
570
|
+
if (isParseErr(hp)) return hp;
|
|
571
|
+
headerPrefixes = hp;
|
|
572
|
+
}
|
|
573
|
+
|
|
527
574
|
// Fail-closed consistency rules.
|
|
528
575
|
if (
|
|
529
576
|
kindRaw === "none" &&
|
|
530
|
-
(secretRefs || secretQueryRefs || requires || optional)
|
|
577
|
+
(secretRefs || secretQueryRefs || requires || optional || headerPrefixes)
|
|
531
578
|
) {
|
|
532
579
|
return fail(
|
|
533
580
|
file,
|
|
@@ -605,10 +652,30 @@ function validateAuth(
|
|
|
605
652
|
const r4 = checkDeclared(optional ?? [], "auth.optional");
|
|
606
653
|
if (r4) return r4;
|
|
607
654
|
}
|
|
655
|
+
// Every headerPrefixes key must target a secret-injected header; a prefix
|
|
656
|
+
// for a header that isn't in secretRefs is a mistake. Checked outside the
|
|
657
|
+
// secretRefs/requires/optional block so a headerPrefixes-only guide fails
|
|
658
|
+
// too (the prefix would otherwise be dead at fetch time silently).
|
|
659
|
+
if (headerPrefixes) {
|
|
660
|
+
for (const headerName of Object.keys(headerPrefixes)) {
|
|
661
|
+
if (!secretRefs || !(headerName in secretRefs)) {
|
|
662
|
+
return fail(
|
|
663
|
+
file,
|
|
664
|
+
`auth.headerPrefixes.${headerName}`,
|
|
665
|
+
"a header name present in auth.secretRefs",
|
|
666
|
+
`"${headerName}" is not a secret-injected header`,
|
|
667
|
+
{
|
|
668
|
+
fix: `Add "${headerName}" to auth.secretRefs (or remove the prefix).`,
|
|
669
|
+
},
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
608
674
|
|
|
609
675
|
const result: AuthConfig = { kind: kindRaw as AuthKind };
|
|
610
676
|
if (headers !== undefined) result.headers = headers;
|
|
611
677
|
if (secretRefs !== undefined) result.secretRefs = secretRefs;
|
|
678
|
+
if (headerPrefixes !== undefined) result.headerPrefixes = headerPrefixes;
|
|
612
679
|
if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
|
|
613
680
|
if (requires !== undefined) result.requires = requires;
|
|
614
681
|
if (optional !== undefined) result.optional = optional;
|
|
@@ -1102,6 +1169,24 @@ export function parseApiGuide(
|
|
|
1102
1169
|
description = descriptionRaw;
|
|
1103
1170
|
}
|
|
1104
1171
|
|
|
1172
|
+
// schemaVersion — metadata-only attribution (design: "schemaVersion is
|
|
1173
|
+
// attribution, not enforcement"). Read from frontmatter, surfaced on the
|
|
1174
|
+
// parsed guide when present, left `undefined` when absent. Never gates,
|
|
1175
|
+
// warns, or alters parse. A malformed (non-integer/negative) value is
|
|
1176
|
+
// tolerated and ignored — it must never reject a guide.
|
|
1177
|
+
let schemaVersion: number | undefined;
|
|
1178
|
+
const schemaVersionRaw = m["schemaVersion"];
|
|
1179
|
+
if (schemaVersionRaw !== undefined) {
|
|
1180
|
+
if (
|
|
1181
|
+
typeof schemaVersionRaw === "number" &&
|
|
1182
|
+
Number.isInteger(schemaVersionRaw) &&
|
|
1183
|
+
schemaVersionRaw >= 0
|
|
1184
|
+
) {
|
|
1185
|
+
schemaVersion = schemaVersionRaw;
|
|
1186
|
+
}
|
|
1187
|
+
// else: tolerated + ignored — metadata stays silent on malformed input.
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1105
1190
|
let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
|
|
1106
1191
|
const gatherAllMaxRaw = m["gatherAllMax"];
|
|
1107
1192
|
if (gatherAllMaxRaw !== undefined) {
|
|
@@ -1206,6 +1291,7 @@ export function parseApiGuide(
|
|
|
1206
1291
|
...(docs ? { docs } : {}),
|
|
1207
1292
|
...(organization ? { organization } : {}),
|
|
1208
1293
|
...(description ? { description } : {}),
|
|
1294
|
+
...(schemaVersion === undefined ? {} : { schemaVersion }),
|
|
1209
1295
|
gatherAllMax,
|
|
1210
1296
|
auth,
|
|
1211
1297
|
responseShape,
|
|
@@ -1316,9 +1402,7 @@ function formatOpSummary(ops: { name: string }[]): string {
|
|
|
1316
1402
|
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
1317
1403
|
* guides render consistently with those that have a one-line summary.
|
|
1318
1404
|
*/
|
|
1319
|
-
export function formatGuideListings(
|
|
1320
|
-
entries: { guide: ApiGuide; dirName: string }[],
|
|
1321
|
-
): string {
|
|
1405
|
+
export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
1322
1406
|
const lines: string[] = [];
|
|
1323
1407
|
for (const { guide } of entries) {
|
|
1324
1408
|
lines.push(
|
package/core/path-template.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* - `extractPathTokens` — pull `{token}` names out of a templated path.
|
|
9
9
|
* - `fillPathTemplate` — substitute `{token}` placeholders from params.
|
|
10
10
|
* - `joinUrl` — join a base host + path + query string into a full URL.
|
|
11
|
+
* - `assertSafeDomain` — reject a domain that could escape the guides dir.
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
14
|
/** Extract `{token}` names from a templated path, in order, deduplicated. */
|
|
@@ -46,5 +47,33 @@ export function joinUrl(baseHost: string, path: string, query: string): string {
|
|
|
46
47
|
const base = baseHost.endsWith("/") ? baseHost : `${baseHost}/`;
|
|
47
48
|
const rel = path.startsWith("/") ? path.slice(1) : path;
|
|
48
49
|
const url = new URL(rel, base).toString();
|
|
49
|
-
|
|
50
|
+
if (!query) return url;
|
|
51
|
+
const sep = url.includes("?") ? "&" : "?";
|
|
52
|
+
return `${url}${sep}${query}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Reject a `domain` that could escape the guides dir via path traversal.
|
|
57
|
+
*
|
|
58
|
+
* Domains are used in `join(guidesDir, domain, ...)` for helper lookups
|
|
59
|
+
* and guide writes. A user-typed `/api helpers ../../foo` or an agent
|
|
60
|
+
* `api-learn({domain: "../x"})` must not read or write outside the
|
|
61
|
+
* guides dir. Returns the domain if safe, throws otherwise.
|
|
62
|
+
*/
|
|
63
|
+
export function assertSafeDomain(domain: string): string {
|
|
64
|
+
// A safe domain is a single path segment: no separators, no NUL,
|
|
65
|
+
// and not "."/".." (self/parent). Anything else is a literal dir name.
|
|
66
|
+
if (
|
|
67
|
+
domain.length === 0 ||
|
|
68
|
+
domain.includes("/") ||
|
|
69
|
+
domain.includes("\\") ||
|
|
70
|
+
domain.includes("\0") ||
|
|
71
|
+
domain === "." ||
|
|
72
|
+
domain === ".."
|
|
73
|
+
) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid domain '${domain}': must be a single path segment with no '/', '\\', or '..'.`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return domain;
|
|
50
79
|
}
|
package/core/secrets-command.ts
CHANGED
|
@@ -147,6 +147,26 @@ function declaredSecretNames(domain: string): string[] {
|
|
|
147
147
|
return [...names].sort((a, b) => a.localeCompare(b));
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
/**
|
|
151
|
+
* The guide-declared header prefix for a secret name, or undefined. When a
|
|
152
|
+
* guide maps a secret to a prefixed header, the store must hold the raw
|
|
153
|
+
* credential (the guide adds the prefix at fetch time) — surface that in the
|
|
154
|
+
* provisioning prompt so the user pastes the raw token, not the prefixed form.
|
|
155
|
+
*/
|
|
156
|
+
function declaredPrefixHint(domain: string, name: string): string | undefined {
|
|
157
|
+
for (const { guide } of findGuidesByDomain(domain)) {
|
|
158
|
+
if (guide.auth.kind !== "static-key") continue;
|
|
159
|
+
for (const [headerName, secretName] of Object.entries(
|
|
160
|
+
guide.auth.secretRefs ?? {},
|
|
161
|
+
)) {
|
|
162
|
+
if (secretName === name && guide.auth.headerPrefixes?.[headerName]) {
|
|
163
|
+
return guide.auth.headerPrefixes[headerName];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
150
170
|
// ── Assisted entry: /api secrets <domain> ──────────────────────────
|
|
151
171
|
|
|
152
172
|
async function assistedEntry(
|
|
@@ -213,9 +233,12 @@ async function promptAndStore(
|
|
|
213
233
|
domain: string,
|
|
214
234
|
name: string,
|
|
215
235
|
): Promise<void> {
|
|
236
|
+
const prefix = declaredPrefixHint(domain, name);
|
|
216
237
|
const value = await ctx.ui.input(
|
|
217
|
-
|
|
218
|
-
|
|
238
|
+
prefix
|
|
239
|
+
? `Value for '${domain}'.${name} (raw token — the guide adds \`${prefix}\`)`
|
|
240
|
+
: `Value for '${domain}'.${name}`,
|
|
241
|
+
prefix ? "paste the raw token" : "paste the secret value",
|
|
219
242
|
);
|
|
220
243
|
if (value === undefined) return; // cancelled
|
|
221
244
|
const trimmed = value.trim();
|
package/core/secrets-store.ts
CHANGED
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
rmSync,
|
|
27
27
|
writeFileSync,
|
|
28
28
|
} from "node:fs";
|
|
29
|
-
import { assertSafeDomain } from "./
|
|
29
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
30
30
|
|
|
31
31
|
/** A secret store: read/write/delete one name, list domain/name indexes. */
|
|
32
32
|
export interface SecretStore {
|
|
@@ -168,3 +168,13 @@ export function listDomains(): string[] {
|
|
|
168
168
|
export function listNames(domain: string): string[] {
|
|
169
169
|
return _store.listNames(domain);
|
|
170
170
|
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Suffix naming the *other* provisioned domains (names only) for a store-miss
|
|
174
|
+
* note — " — provisioned domains: a, b" — or "" when none. Lets a miss tell
|
|
175
|
+
* the authoring agent where the key actually lives without an `ls`.
|
|
176
|
+
*/
|
|
177
|
+
export function provisionedDomainsSuffix(domain: string): string {
|
|
178
|
+
const others = listDomains().filter((d) => d !== domain);
|
|
179
|
+
return others.length > 0 ? ` — provisioned domains: ${others.join(", ")}` : "";
|
|
180
|
+
}
|
package/core/ssrf-guard.ts
CHANGED
|
@@ -29,6 +29,11 @@ const INTERNAL_IP_REGEX =
|
|
|
29
29
|
|
|
30
30
|
// ─── Guard ───────────────────────────────────────────────────────────
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* `reason` is hostname-only by design — never embed the full URL here:
|
|
34
|
+
* query secrets live in URLs, and transport surfaces `reason` verbatim
|
|
35
|
+
* (SsrfBlockedError, transport.ts).
|
|
36
|
+
*/
|
|
32
37
|
export function ssrfGuard(
|
|
33
38
|
rawUrl: string,
|
|
34
39
|
): { ok: true } | { ok: false; reason: string } {
|
package/core/transport.ts
CHANGED
|
@@ -65,13 +65,6 @@ export interface FetchOptions {
|
|
|
65
65
|
* private (never cached / served from cache) and redirects are guarded.
|
|
66
66
|
*/
|
|
67
67
|
hasQuerySecret?: boolean;
|
|
68
|
-
/**
|
|
69
|
-
* Names of store-injected query-param secrets in the request URL. Used by
|
|
70
|
-
* `fetchUrl` to redact the URL in any error message it surfaces, so a raw
|
|
71
|
-
* query secret can never leak into agent context via a transport error
|
|
72
|
-
* (output-channel audit).
|
|
73
|
-
*/
|
|
74
|
-
secretQueryParamNames?: Set<string>;
|
|
75
68
|
/** Charset to decode the body with when the response's Content-Type
|
|
76
69
|
* header omits one. Honors a guide's `responseShape.charset` for APIs
|
|
77
70
|
* that serve e.g. ISO-8859-1 bytes without a charset parameter. An
|
|
@@ -440,7 +433,7 @@ export async function fetchUrl(
|
|
|
440
433
|
const reqHeaders: Record<string, string> = { ...opts?.headers };
|
|
441
434
|
if (!reqHeaders["user-agent"]) {
|
|
442
435
|
reqHeaders["user-agent"] =
|
|
443
|
-
"pi-lean-host/0.2.
|
|
436
|
+
"pi-lean-host/0.2.1 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
444
437
|
}
|
|
445
438
|
|
|
446
439
|
if (!opts?.fresh && !hasAuth) {
|
|
@@ -452,7 +445,7 @@ export async function fetchUrl(
|
|
|
452
445
|
|
|
453
446
|
const startTime = Date.now();
|
|
454
447
|
|
|
455
|
-
for (let attempt = 0;
|
|
448
|
+
for (let attempt = 0; ; attempt++) {
|
|
456
449
|
const remaining = timeout - (Date.now() - startTime);
|
|
457
450
|
if (remaining <= 0) throw new Error("Request timeout");
|
|
458
451
|
|
|
@@ -543,11 +536,4 @@ export async function fetchUrl(
|
|
|
543
536
|
throw e;
|
|
544
537
|
}
|
|
545
538
|
}
|
|
546
|
-
|
|
547
|
-
// Output-channel audit: never embed the raw request URL in a surfaced
|
|
548
|
-
// message. If a query secret is in play, redact it so the fallthrough
|
|
549
|
-
// (or any future reachable variant) can't leak the key.
|
|
550
|
-
throw new Error(
|
|
551
|
-
`Failed to fetch ${redactSecretParams(url, opts?.secretQueryParamNames)} after ${maxRetries + 1} attempts`,
|
|
552
|
-
);
|
|
553
539
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-lean-host",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "REST API client for Pi. A YAML file per API covers endpoints and pagination; the agent calls through a fixed executor so an API encoded once is reusable forever, not re-derived each session. It can probe a live endpoint and write the YAML for you, and a TypeScript file alongside can add custom auth or reshape the request and response freely.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -21,6 +21,16 @@
|
|
|
21
21
|
"publishConfig": {
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./index.ts",
|
|
26
|
+
"./core/helpers.js": "./core/helpers.ts",
|
|
27
|
+
"./core/parse-api-guide.js": "./core/parse-api-guide.ts",
|
|
28
|
+
"./core/guide-store.js": "./core/guide-store.ts",
|
|
29
|
+
"./core/local-helpers.js": "./core/local-helpers.ts",
|
|
30
|
+
"./core/api-guide-types.js": "./core/api-guide-types.ts",
|
|
31
|
+
"./core/transport.js": "./core/transport.ts",
|
|
32
|
+
"./core/auth.js": "./core/auth.ts"
|
|
33
|
+
},
|
|
24
34
|
"files": [
|
|
25
35
|
"index.ts",
|
|
26
36
|
"LICENSE",
|
package/tools/api-fetch.ts
CHANGED
|
@@ -25,12 +25,14 @@ import {
|
|
|
25
25
|
resolveSecretQueryParams,
|
|
26
26
|
authStatusLine,
|
|
27
27
|
canonicalStoreDomain,
|
|
28
|
+
containsSecret,
|
|
28
29
|
type SecretResolution,
|
|
29
30
|
type QuerySecretResolution,
|
|
30
31
|
} from "../core/auth.js";
|
|
32
|
+
import { provisionedDomainsSuffix } from "../core/secrets-store.js";
|
|
31
33
|
import { formatGuideListings } from "../core/parse-api-guide.js";
|
|
32
34
|
import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
|
|
33
|
-
import {
|
|
35
|
+
import { appendFooter, contentText } from "./utils.js";
|
|
34
36
|
import type { Operation, ApiGuide } from "../core/api-guide-types.js";
|
|
35
37
|
|
|
36
38
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -230,16 +232,13 @@ export const apiFetchTool = defineTool({
|
|
|
230
232
|
...(queryRes.absentRequired ?? []),
|
|
231
233
|
];
|
|
232
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);
|
|
233
240
|
return {
|
|
234
|
-
content: [
|
|
235
|
-
{
|
|
236
|
-
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.`,
|
|
241
|
-
},
|
|
242
|
-
],
|
|
241
|
+
content: [{ type: "text", text }],
|
|
243
242
|
details: {
|
|
244
243
|
error: "auth_required_not_provisioned",
|
|
245
244
|
domain,
|
|
@@ -249,7 +248,9 @@ export const apiFetchTool = defineTool({
|
|
|
249
248
|
};
|
|
250
249
|
}
|
|
251
250
|
}
|
|
252
|
-
const headerValues = headerRes
|
|
251
|
+
const headerValues = headerRes
|
|
252
|
+
? [...Object.values(headerRes.headers), ...headerRes.rawHeaderValues]
|
|
253
|
+
: [];
|
|
253
254
|
const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
|
|
254
255
|
const authOpts: {
|
|
255
256
|
authHeaders?: Record<string, string>;
|
|
@@ -458,14 +459,7 @@ export const apiFetchTool = defineTool({
|
|
|
458
459
|
text += `\n📦 ${totalFetched} item(s) fetched`;
|
|
459
460
|
}
|
|
460
461
|
|
|
461
|
-
|
|
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);
|
|
462
|
+
return new Text(appendFooter(text, expanded, result, theme, 1000), 0, 0);
|
|
469
463
|
},
|
|
470
464
|
});
|
|
471
465
|
|
|
@@ -643,7 +637,7 @@ function scrubSecretHeaders(
|
|
|
643
637
|
if (!secretValues || secretValues.length === 0) return headers;
|
|
644
638
|
const out: Record<string, string> = {};
|
|
645
639
|
for (const [k, v] of Object.entries(headers)) {
|
|
646
|
-
if (
|
|
640
|
+
if (containsSecret(v, secretValues)) continue;
|
|
647
641
|
out[k] = v;
|
|
648
642
|
}
|
|
649
643
|
return out;
|
package/tools/api-guide.ts
CHANGED
|
@@ -13,7 +13,7 @@ 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 {
|
|
16
|
+
import { appendFooter, contentText } from "./utils.js";
|
|
17
17
|
import {
|
|
18
18
|
loadAllGuides,
|
|
19
19
|
findGuidesByDomain,
|
|
@@ -171,14 +171,7 @@ export const apiGuideTool = defineTool({
|
|
|
171
171
|
text += ` — ${guideCount} guides`;
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
|
|
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);
|
|
174
|
+
return new Text(appendFooter(text, expanded, result, theme, 800), 0, 0);
|
|
182
175
|
},
|
|
183
176
|
});
|
|
184
177
|
|
|
@@ -252,6 +245,7 @@ function renderGuideDetail(
|
|
|
252
245
|
if (pagCfg.pageParam) bits.push(pagCfg.pageParam);
|
|
253
246
|
if (pagCfg.pageSizeParam)
|
|
254
247
|
bits.push(`${pagCfg.pageSizeParam}=${pagCfg.pageSize ?? 50}`);
|
|
248
|
+
if (pagCfg.base !== undefined) bits.push(`base=${pagCfg.base}`);
|
|
255
249
|
lines.push(` pagination: ${bits.join(" ")}`);
|
|
256
250
|
}
|
|
257
251
|
}
|
package/tools/api-learn.ts
CHANGED
|
@@ -15,16 +15,16 @@
|
|
|
15
15
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { Type } from "@earendil-works/pi-ai";
|
|
17
17
|
import { Text } from "@earendil-works/pi-tui";
|
|
18
|
-
import {
|
|
18
|
+
import { appendFooter, contentText } from "./utils.js";
|
|
19
19
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
20
20
|
import { join } from "node:path";
|
|
21
21
|
import { parseApiGuide } from "../core/parse-api-guide.js";
|
|
22
22
|
import {
|
|
23
23
|
invalidateCache,
|
|
24
24
|
getUserGuidesDir,
|
|
25
|
-
assertSafeDomain,
|
|
26
25
|
findGuidesByDomain,
|
|
27
26
|
} from "../core/guide-store.js";
|
|
27
|
+
import { assertSafeDomain } from "../core/path-template.js";
|
|
28
28
|
|
|
29
29
|
// ═══════════════════════════════════════════════════════════════════
|
|
30
30
|
// Worked example
|
|
@@ -101,8 +101,7 @@ export const apiLearnTool = defineTool({
|
|
|
101
101
|
description:
|
|
102
102
|
"Save or update an API guide for a domain. " +
|
|
103
103
|
"The recipe is written in YAML frontmatter format. " +
|
|
104
|
-
"Call with no params to see the worked example recipe and field reference.
|
|
105
|
-
"Requires /api learn to be active.",
|
|
104
|
+
"Call with no params to see the worked example recipe and field reference.",
|
|
106
105
|
|
|
107
106
|
parameters: Type.Object({
|
|
108
107
|
domain: Type.Optional(
|
|
@@ -146,6 +145,7 @@ export const apiLearnTool = defineTool({
|
|
|
146
145
|
` \`operations[].path\` — path starting with /`,
|
|
147
146
|
"",
|
|
148
147
|
"## Key defaults",
|
|
148
|
+
` \`apiHost\` — base URL. \`path\` is always resolved relative to it — \`joinUrl\` strips a leading \`/\`, so \`/items\` + \`apiHost: https://host/v3\` → \`https://host/v3/items\`. Keep the version in \`apiHost\` (worked-example style) or leave it bare with the version in each \`path\` — pick one per guide; both at once doubles the segment (\`/v3/v3/items\` → 404)`,
|
|
149
149
|
` \`auth\` — omitted → kind: none`,
|
|
150
150
|
` \`verified\` — omitted → today's date`,
|
|
151
151
|
` \`docs\` — optional API documentation URL (http/https); omitted → no docs line`,
|
|
@@ -165,6 +165,13 @@ export const apiLearnTool = defineTool({
|
|
|
165
165
|
` \`passthrough\` — true → forward undeclared caller params onto the query string`,
|
|
166
166
|
` \`parse\` — op-level responseShape override (format/charset) for this operation`,
|
|
167
167
|
"",
|
|
168
|
+
"## Executor semantics",
|
|
169
|
+
" Pagination:",
|
|
170
|
+
` \`pagination.base\` seeds the page param for offset-limit/page styles (caller value wins, then \`base\`, then the param \`default\`); use \`base: 1\` for 1-based offset APIs`,
|
|
171
|
+
` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
|
|
172
|
+
" Auth:",
|
|
173
|
+
` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store.`,
|
|
174
|
+
"",
|
|
168
175
|
"Call api-learn({domain: '...', recipe: '...'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
|
|
169
176
|
].join("\n");
|
|
170
177
|
return {
|
|
@@ -181,10 +188,7 @@ export const apiLearnTool = defineTool({
|
|
|
181
188
|
content: [
|
|
182
189
|
{
|
|
183
190
|
type: "text",
|
|
184
|
-
text:
|
|
185
|
-
err instanceof Error
|
|
186
|
-
? err.message
|
|
187
|
-
: `Invalid domain '${domain}'.`,
|
|
191
|
+
text: err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
|
|
188
192
|
},
|
|
189
193
|
],
|
|
190
194
|
details: { error: "invalid_domain", domain },
|
|
@@ -280,8 +284,7 @@ export const apiLearnTool = defineTool({
|
|
|
280
284
|
const opCount = parsed.guide.operations.length;
|
|
281
285
|
const opNames = parsed.guide.operations.map((o) => o.name).join(", ");
|
|
282
286
|
|
|
283
|
-
const warningBlock =
|
|
284
|
-
warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
|
|
287
|
+
const warningBlock = warnings.length > 0 ? warnings.join("\n") + "\n\n" : "";
|
|
285
288
|
|
|
286
289
|
return {
|
|
287
290
|
content: [
|
|
@@ -295,7 +298,8 @@ export const apiLearnTool = defineTool({
|
|
|
295
298
|
` Verified: ${parsed.guide.verified}\n` +
|
|
296
299
|
`\n` +
|
|
297
300
|
warningBlock +
|
|
298
|
-
`Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify
|
|
301
|
+
`Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
|
|
302
|
+
`\n⚠ Direct edits to guide.md are ignored until the next api-learn save (per-session cache). Re-run api-learn to apply changes.`,
|
|
299
303
|
},
|
|
300
304
|
],
|
|
301
305
|
details: {
|
|
@@ -336,13 +340,6 @@ export const apiLearnTool = defineTool({
|
|
|
336
340
|
text = theme.fg("dim", "📝 Worked example");
|
|
337
341
|
}
|
|
338
342
|
|
|
339
|
-
|
|
340
|
-
if (expanded) {
|
|
341
|
-
text += "\n";
|
|
342
|
-
text = renderExpandedText(text, theme, content, 600);
|
|
343
|
-
} else {
|
|
344
|
-
text += `\n${theme.fg("muted", `${content.length} chars (expand)`)}`;
|
|
345
|
-
}
|
|
346
|
-
return new Text(text, 0, 0);
|
|
343
|
+
return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);
|
|
347
344
|
},
|
|
348
345
|
});
|