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.
- package/README.md +113 -117
- package/core/api-guide-types.ts +39 -0
- package/core/api-toggle.ts +23 -1
- package/core/auth.ts +42 -5
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/guide-store.ts +0 -26
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +72 -24
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +491 -57
- package/core/path-template.ts +30 -1
- package/core/resolve-op.ts +222 -0
- 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/core/verify-command.ts +399 -0
- package/package.json +15 -1
- package/tools/api-fetch.ts +147 -233
- package/tools/api-guide.ts +35 -46
- package/tools/api-learn.ts +438 -125
- package/tools/api-probe.ts +501 -88
- package/tools/utils.ts +21 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/api delete <domain> [guide]` — remove a guide directory and invalidate
|
|
3
|
+
* the per-session guide-store cache (closing the ghost-guide cache bug that
|
|
4
|
+
* `bash rm` leaves behind).
|
|
5
|
+
*
|
|
6
|
+
* - `delete <domain>` — whole-domain delete (interactive confirm).
|
|
7
|
+
* - `delete <domain> <guide>` — delete one guide by shortName (no confirm).
|
|
8
|
+
* - `delete --help` — usage.
|
|
9
|
+
*
|
|
10
|
+
* Whole-domain delete mirrors `/api secrets --delete` (interactive confirm);
|
|
11
|
+
* single-guide delete mirrors `/api secrets --delete <domain> <name>` (no
|
|
12
|
+
* confirm). After the `rm -rf` of the directory, `invalidateCache()` so the
|
|
13
|
+
* next api-guide / api-fetch doesn't see a ghost guide — the load-bearing
|
|
14
|
+
* reason this beats `bash rm`.
|
|
15
|
+
*
|
|
16
|
+
* Always-available (runs in **on** mode), not learn-gated, and not refused by
|
|
17
|
+
* the focus-mode guard — it writes no toolset state (peer of secrets/verify).
|
|
18
|
+
*
|
|
19
|
+
* The agent has NO delete surface: api-learn's collision/malformed errors
|
|
20
|
+
* tell it to ask the human to run this command.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { existsSync, rmSync } from "node:fs";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
import {
|
|
27
|
+
findGuidesByDomain,
|
|
28
|
+
invalidateCache,
|
|
29
|
+
getUserGuidesDir,
|
|
30
|
+
} from "./guide-store.js";
|
|
31
|
+
import {
|
|
32
|
+
formatGuideListings,
|
|
33
|
+
selectGuideByShortName,
|
|
34
|
+
shortNameErrorText,
|
|
35
|
+
} from "./parse-api-guide.js";
|
|
36
|
+
import { pickGuide } from "./guide-picker.js";
|
|
37
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
38
|
+
|
|
39
|
+
/** Usage, surfaced by `--help`. */
|
|
40
|
+
function helpText(): string {
|
|
41
|
+
return [
|
|
42
|
+
"Usage: /api delete <domain> [guide]",
|
|
43
|
+
" /api delete <domain> delete the whole guide directory (interactive confirm)",
|
|
44
|
+
" /api delete <domain> <guide> delete one guide by shortName (no confirm)",
|
|
45
|
+
" /api delete --help this help",
|
|
46
|
+
"",
|
|
47
|
+
" Removes the directory and invalidates the per-session guide cache, so the",
|
|
48
|
+
" next api-guide / api-fetch no longer lists it (bash rm leaves a ghost).",
|
|
49
|
+
" The agent has no delete tool — this is a human-typed recovery gesture.",
|
|
50
|
+
].join("\n");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Handle the `delete` subcommand of `/api`.
|
|
55
|
+
*
|
|
56
|
+
* @param args The text after "delete" ("" / "<domain>" / "<domain> <guide>").
|
|
57
|
+
* @param ctx The extension command context
|
|
58
|
+
*/
|
|
59
|
+
export async function handleDeleteSubcommand(
|
|
60
|
+
args: string,
|
|
61
|
+
ctx: ExtensionCommandContext,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
64
|
+
|
|
65
|
+
if (parts.includes("--help") || parts.includes("help")) {
|
|
66
|
+
ctx.ui.notify(helpText(), "info");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const domain = parts[0];
|
|
71
|
+
const guideSelector = parts[1];
|
|
72
|
+
|
|
73
|
+
if (!domain) {
|
|
74
|
+
ctx.ui.notify(
|
|
75
|
+
"Usage: /api delete <domain> [guide] — see /api delete --help.",
|
|
76
|
+
"warning",
|
|
77
|
+
);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Path-traversal guard before any filesystem access — the literal-dir
|
|
82
|
+
// fallback below joins the domain into the guides dir.
|
|
83
|
+
try {
|
|
84
|
+
assertSafeDomain(domain);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
ctx.ui.notify(
|
|
87
|
+
err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
|
|
88
|
+
"warning",
|
|
89
|
+
);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const matches = findGuidesByDomain(domain);
|
|
94
|
+
|
|
95
|
+
if (matches.length === 0) {
|
|
96
|
+
// Literal-dir fallback: a malformed guide's `domains:` block is
|
|
97
|
+
// unreadable, so findGuidesByDomain can't address it — but the
|
|
98
|
+
// malformed catalog line shows its dirName. `/api delete <dirName>`
|
|
99
|
+
// recovers it. Whole-domain delete (confirm) since the guide can't be
|
|
100
|
+
// enumerated from it.
|
|
101
|
+
if (existsSync(join(getUserGuidesDir(), domain))) {
|
|
102
|
+
await deleteDir(ctx, domain, true);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
ctx.ui.notify(
|
|
106
|
+
`No API guide for '${domain}'. ` +
|
|
107
|
+
`Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author one.`,
|
|
108
|
+
"warning",
|
|
109
|
+
);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// guide selector present → resolve by shortName (1 or N guides), no confirm.
|
|
114
|
+
if (guideSelector) {
|
|
115
|
+
const sel = selectGuideByShortName(matches, guideSelector);
|
|
116
|
+
if (!sel.ok) {
|
|
117
|
+
ctx.ui.notify(
|
|
118
|
+
shortNameErrorText(
|
|
119
|
+
sel,
|
|
120
|
+
domain,
|
|
121
|
+
guideSelector,
|
|
122
|
+
`Call /api delete ${domain} to see the menu.`,
|
|
123
|
+
),
|
|
124
|
+
"warning",
|
|
125
|
+
);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
await deleteDir(ctx, sel.dirName, false);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (matches.length === 1) {
|
|
133
|
+
// Whole-domain delete — interactive confirm.
|
|
134
|
+
await deleteDir(ctx, matches[0]!.dirName, true);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// N guides, no selector → interactive pick (TUI) or the menu
|
|
139
|
+
// fallback (headless/RPC/print or cancelled), nothing removed.
|
|
140
|
+
const picked = await pickGuide(ctx, matches);
|
|
141
|
+
if (!picked) {
|
|
142
|
+
ctx.ui.notify(
|
|
143
|
+
[
|
|
144
|
+
`${matches.length} API guides for '${domain}':`,
|
|
145
|
+
formatGuideListings(matches),
|
|
146
|
+
`Call /api delete ${domain} <shortName> to delete one guide (no confirm).`,
|
|
147
|
+
].join("\n"),
|
|
148
|
+
"info",
|
|
149
|
+
);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
await deleteDir(ctx, picked.dirName, false);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Remove one guide directory and invalidate the cache. `confirm` is true for
|
|
157
|
+
* whole-domain deletes (interactive confirm, headless skips it — mirroring
|
|
158
|
+
* `/api secrets --delete`) and false for single-guide deletes.
|
|
159
|
+
*/
|
|
160
|
+
async function deleteDir(
|
|
161
|
+
ctx: ExtensionCommandContext,
|
|
162
|
+
dirName: string,
|
|
163
|
+
confirm: boolean,
|
|
164
|
+
): Promise<void> {
|
|
165
|
+
const dir = join(getUserGuidesDir(), dirName);
|
|
166
|
+
if (!existsSync(dir)) {
|
|
167
|
+
ctx.ui.notify(
|
|
168
|
+
`No guide directory '${dirName}' — nothing to delete.`,
|
|
169
|
+
"warning",
|
|
170
|
+
);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (confirm && ctx.hasUI) {
|
|
174
|
+
const ok = await ctx.ui.confirm(
|
|
175
|
+
`Delete the API guide directory '${dirName}'?`,
|
|
176
|
+
`This removes ${dir} and its contents (guide.md, helper.ts, verify.json).`,
|
|
177
|
+
);
|
|
178
|
+
if (!ok) {
|
|
179
|
+
ctx.ui.notify("Cancelled — nothing deleted.", "info");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
rmSync(dir, { recursive: true, force: true });
|
|
184
|
+
invalidateCache();
|
|
185
|
+
ctx.ui.notify(
|
|
186
|
+
`🗑 Deleted API guide '${dirName}'. ` +
|
|
187
|
+
`Cache invalidated — the next api-guide catalog will no longer list it.`,
|
|
188
|
+
"info",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interactive guide picker for the /api verify and /api delete commands.
|
|
3
|
+
*
|
|
4
|
+
* When a domain claims N guides and no `guide` selector is supplied, the
|
|
5
|
+
* commands show a `SelectList` (from @earendil-works/pi-tui, already a peer
|
|
6
|
+
* dep) with the shortName in the primary column and the guide description in
|
|
7
|
+
* a second column — the user picks with ↑↓/enter instead of retyping the
|
|
8
|
+
* command with a shortName. `value` is the dirName (unique, unlike shortName,
|
|
9
|
+
* which can be ambiguous across sibling guides).
|
|
10
|
+
*
|
|
11
|
+
* Terminal-only: `ctx.mode === "tui"` (custom components don't exist in
|
|
12
|
+
* RPC/print). In headless/RPC/print `pickGuide` returns undefined and the
|
|
13
|
+
* caller keeps today's text menu + retype fallback. A stale guide
|
|
14
|
+
* (`schemaVersion < current`) gets a `⚠` on its label so stale-guide
|
|
15
|
+
* detection survives the interactive path.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
import {
|
|
20
|
+
Container,
|
|
21
|
+
type SelectItem,
|
|
22
|
+
SelectList,
|
|
23
|
+
Text,
|
|
24
|
+
} from "@earendil-works/pi-tui";
|
|
25
|
+
import { GUIDE_SCHEMA_VERSION, type ApiGuide } from "./api-guide-types.js";
|
|
26
|
+
import { isStaleSchema } from "./parse-api-guide.js";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Build the picker rows: `value` = dirName (unique), `label` = shortName (with
|
|
30
|
+
* a `⚠` when stale), `description` = the guide description, falling back to an
|
|
31
|
+
* op-count summary when absent. Pure — tests exercise it without a TUI.
|
|
32
|
+
*/
|
|
33
|
+
export function buildGuidePickerItems(
|
|
34
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
35
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
36
|
+
): SelectItem[] {
|
|
37
|
+
return matches.map(({ guide, dirName }) => {
|
|
38
|
+
const desc =
|
|
39
|
+
guide.description ??
|
|
40
|
+
(guide.operations.length > 0
|
|
41
|
+
? `${guide.operations.length} op${guide.operations.length === 1 ? "" : "s"}`
|
|
42
|
+
: undefined);
|
|
43
|
+
const item: SelectItem = {
|
|
44
|
+
value: dirName,
|
|
45
|
+
label:
|
|
46
|
+
guide.shortName +
|
|
47
|
+
(isStaleSchema(guide.schemaVersion ?? 0, current) ? " ⚠" : ""),
|
|
48
|
+
};
|
|
49
|
+
if (desc !== undefined) item.description = desc;
|
|
50
|
+
return item;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Let the user pick one of a domain's guides interactively (TUI only).
|
|
56
|
+
* Returns the selected `{ guide, dirName }`, or undefined when the picker is
|
|
57
|
+
* unavailable (not TUI mode) or the user cancelled — the caller then renders
|
|
58
|
+
* its own text menu fallback.
|
|
59
|
+
*/
|
|
60
|
+
export async function pickGuide(
|
|
61
|
+
ctx: ExtensionCommandContext,
|
|
62
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
63
|
+
): Promise<{ guide: ApiGuide; dirName: string } | undefined> {
|
|
64
|
+
if (ctx.mode !== "tui") return undefined;
|
|
65
|
+
|
|
66
|
+
const items = buildGuidePickerItems(matches);
|
|
67
|
+
|
|
68
|
+
const picked = await ctx.ui.custom<string | undefined>(
|
|
69
|
+
(tui, theme, _kb, done) => {
|
|
70
|
+
const container = new Container();
|
|
71
|
+
container.addChild(
|
|
72
|
+
new Text(theme.fg("accent", theme.bold("Select API guide"))),
|
|
73
|
+
);
|
|
74
|
+
const list = new SelectList(items, Math.min(items.length, 10), {
|
|
75
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
76
|
+
selectedText: (text) => theme.fg("accent", text),
|
|
77
|
+
description: (text) => theme.fg("muted", text),
|
|
78
|
+
scrollInfo: (text) => theme.fg("dim", text),
|
|
79
|
+
noMatch: (text) => theme.fg("warning", text),
|
|
80
|
+
});
|
|
81
|
+
list.onSelect = (item) => done(item.value);
|
|
82
|
+
list.onCancel = () => done(undefined);
|
|
83
|
+
container.addChild(list);
|
|
84
|
+
container.addChild(
|
|
85
|
+
new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel")),
|
|
86
|
+
);
|
|
87
|
+
return {
|
|
88
|
+
render(width: number) {
|
|
89
|
+
return container.render(width);
|
|
90
|
+
},
|
|
91
|
+
invalidate() {
|
|
92
|
+
container.invalidate();
|
|
93
|
+
},
|
|
94
|
+
handleInput(data: string) {
|
|
95
|
+
list.handleInput(data);
|
|
96
|
+
tui.requestRender();
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
if (picked === undefined) return undefined;
|
|
103
|
+
return matches.find((m) => m.dirName === picked);
|
|
104
|
+
}
|
package/core/guide-store.ts
CHANGED
|
@@ -50,32 +50,6 @@ export function invalidateCache(): void {
|
|
|
50
50
|
_cache = null;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
/**
|
|
54
|
-
* Reject a `domain` that could escape the guides dir via path traversal.
|
|
55
|
-
*
|
|
56
|
-
* Domains are used in `join(guidesDir, domain, ...)` for helper lookups
|
|
57
|
-
* and guide writes. A user-typed `/api helpers ../../foo` or an agent
|
|
58
|
-
* `api-learn({domain: "../x"})` must not read or write outside the
|
|
59
|
-
* guides dir. Returns the domain if safe, throws otherwise.
|
|
60
|
-
*/
|
|
61
|
-
export function assertSafeDomain(domain: string): string {
|
|
62
|
-
// A safe domain is a single path segment: no separators, no NUL,
|
|
63
|
-
// and not "."/".." (self/parent). Anything else is a literal dir name.
|
|
64
|
-
if (
|
|
65
|
-
domain.length === 0 ||
|
|
66
|
-
domain.includes("/") ||
|
|
67
|
-
domain.includes("\\") ||
|
|
68
|
-
domain.includes("\0") ||
|
|
69
|
-
domain === "." ||
|
|
70
|
-
domain === ".."
|
|
71
|
-
) {
|
|
72
|
-
throw new Error(
|
|
73
|
-
`Invalid domain '${domain}': must be a single path segment with no '/', '\\', or '..'.`,
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
return domain;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
53
|
// ═══════════════════════════════════════════════════════════════════
|
|
80
54
|
// Internal load
|
|
81
55
|
// ═══════════════════════════════════════════════════════════════════
|
package/core/helpers-command.ts
CHANGED
|
@@ -55,7 +55,7 @@ export async function handleHelpersSubcommand(
|
|
|
55
55
|
lines.push(
|
|
56
56
|
"",
|
|
57
57
|
"Call /api helpers <domain> to view a helper's source.",
|
|
58
|
-
"Call api-learn({domain,
|
|
58
|
+
"Call api-learn({domain, recipeFile}) to author or update a guide (and its helper).",
|
|
59
59
|
);
|
|
60
60
|
|
|
61
61
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
@@ -78,9 +78,7 @@ export async function handleHelpersSubcommand(
|
|
|
78
78
|
if (source === null) {
|
|
79
79
|
const all = getAllHelpers();
|
|
80
80
|
const known =
|
|
81
|
-
all.length > 0
|
|
82
|
-
? ` Known helpers: ${all.join(", ")}.`
|
|
83
|
-
: " No helpers found.";
|
|
81
|
+
all.length > 0 ? ` Known helpers: ${all.join(", ")}.` : " No helpers found.";
|
|
84
82
|
ctx.ui.notify(
|
|
85
83
|
`No helper for '${domain}'.${known}\n\n` +
|
|
86
84
|
`Helpers live alongside guides at api-guides/${domain}/helper.ts.\n` +
|
package/core/helpers.ts
CHANGED
|
@@ -21,15 +21,12 @@ function expandAccept(accept: string): string {
|
|
|
21
21
|
|
|
22
22
|
import { XMLParser } from "fast-xml-parser";
|
|
23
23
|
import { ssrfGuard } from "./ssrf-guard.js";
|
|
24
|
+
import { scrubSecretValues } from "./auth.js";
|
|
24
25
|
import {
|
|
25
26
|
fetchUrl,
|
|
26
27
|
redactSecretParams,
|
|
27
28
|
type FetchOptions,
|
|
28
29
|
} from "./transport.js";
|
|
29
|
-
// Re-export for callers (api-probe.ts) that surface redacted URLs; the
|
|
30
|
-
// implementation now lives in transport.ts so the fetch layer can self-
|
|
31
|
-
// redact any URL it embeds in an error message.
|
|
32
|
-
export { redactSecretParams };
|
|
33
30
|
import { fillPathTemplate, joinUrl } from "./path-template.js";
|
|
34
31
|
import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
|
|
35
32
|
import type {
|
|
@@ -173,6 +170,26 @@ function buildQueryParams(
|
|
|
173
170
|
}
|
|
174
171
|
}
|
|
175
172
|
|
|
173
|
+
// At-least-one-of constraint: at least one group member must be supplied.
|
|
174
|
+
// Members can't be `required` or carry a `default` (parser-enforced), so
|
|
175
|
+
// this is the only guard the group needs — same fail-closed seam as the
|
|
176
|
+
// per-param `required` check above. Both api-fetch and /api verify route
|
|
177
|
+
// through here (resolveOpForExecution → restGet/paginate), so one guard
|
|
178
|
+
// covers both call sites.
|
|
179
|
+
if (operation.requiresAnyOf && operation.requiresAnyOf.length > 0) {
|
|
180
|
+
const satisfied = operation.requiresAnyOf.some(
|
|
181
|
+
(name) => params[name] !== undefined,
|
|
182
|
+
);
|
|
183
|
+
if (!satisfied) {
|
|
184
|
+
throw new HelperError(
|
|
185
|
+
"params.requiresAnyOf",
|
|
186
|
+
`Missing one of: ${operation.requiresAnyOf.join(", ")}`,
|
|
187
|
+
`at least one of: ${operation.requiresAnyOf.join(", ")}`,
|
|
188
|
+
"none supplied",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
176
193
|
// `passthrough`: forward caller-supplied params not declared in the
|
|
177
194
|
// recipe's `params` map onto the query string as-is. For APIs with an
|
|
178
195
|
// open param surface (Infogami /query.json flat form, CKAN, OAI-PMH)
|
|
@@ -222,7 +239,11 @@ export function normalizeDateParam(
|
|
|
222
239
|
/**
|
|
223
240
|
* Resolve a simple dot-delimited JSON path against an object.
|
|
224
241
|
* Supports `data.items`, `resultados[0].campo`, `$.items` prefix.
|
|
242
|
+
*
|
|
243
|
+
* Returns `unknown` by design — the value at an arbitrary JSON path has no
|
|
244
|
+
* named domain type until the caller knows the path they asked for.
|
|
225
245
|
*/
|
|
246
|
+
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
226
247
|
export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
227
248
|
// Normalise: strip leading $ or $., convert bracket notation.
|
|
228
249
|
const normalised = path
|
|
@@ -270,10 +291,14 @@ const xmlParser = new XMLParser({
|
|
|
270
291
|
* header charset wins). `parseResponse` itself does no decoding — the
|
|
271
292
|
* `charset` field is consumed by the transport, not here.
|
|
272
293
|
*
|
|
294
|
+
* Returns `unknown` by design — an arbitrary API response body has no named
|
|
295
|
+
* domain type; callers resolve JSON paths or run transforms against it.
|
|
296
|
+
*
|
|
273
297
|
* @param body The response body string (correctly decoded).
|
|
274
298
|
* @param shape The response shape (format dictates XML vs JSON parsing).
|
|
275
299
|
* @returns Parsed JSON value or XML-converted object.
|
|
276
300
|
*/
|
|
301
|
+
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
277
302
|
export function parseResponse(body: string, shape: ResponseShape): unknown {
|
|
278
303
|
if (shape.format === "text") {
|
|
279
304
|
// Raw passthrough — returned as-is, no trim (matches xml/json branches).
|
|
@@ -324,8 +349,7 @@ function buildUrl(
|
|
|
324
349
|
* This dispatch is a deliberate seam, not dead code: keeping the field +
|
|
325
350
|
* dispatch now makes the future keyed-auth build additive (a new `kind`
|
|
326
351
|
* behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
|
|
327
|
-
* `paginate` call site and the guide schema.
|
|
328
|
-
* `docs/design/api-secrets-roadmap.md` for the build-out plan.
|
|
352
|
+
* `paginate` call site and the guide schema.
|
|
329
353
|
*/
|
|
330
354
|
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
331
355
|
const kind = auth.kind;
|
|
@@ -354,7 +378,6 @@ function fetchWithOpts(
|
|
|
354
378
|
fallbackCharset?: string,
|
|
355
379
|
secretHeaderNames?: Set<string>,
|
|
356
380
|
hasQuerySecret?: boolean,
|
|
357
|
-
secretQueryParamNames?: Set<string>,
|
|
358
381
|
): ReturnType<typeof fetchUrl> {
|
|
359
382
|
const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
|
|
360
383
|
if (fresh !== undefined) opts.fresh = fresh;
|
|
@@ -362,7 +385,6 @@ function fetchWithOpts(
|
|
|
362
385
|
if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
|
|
363
386
|
if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
|
|
364
387
|
if (hasQuerySecret) opts.hasQuerySecret = true;
|
|
365
|
-
if (secretQueryParamNames) opts.secretQueryParamNames = secretQueryParamNames;
|
|
366
388
|
return fetchUrl(url, opts);
|
|
367
389
|
}
|
|
368
390
|
|
|
@@ -397,11 +419,7 @@ function checkResponseStatus(
|
|
|
397
419
|
// Output-channel audit: scrub known store-injected secret values from the
|
|
398
420
|
// error excerpt so a 401 body echoing an auth header can't leak the key
|
|
399
421
|
// into agent context.
|
|
400
|
-
|
|
401
|
-
for (const v of secretValues) {
|
|
402
|
-
if (v && v.length > 0) message = message.split(v).join("***");
|
|
403
|
-
}
|
|
404
|
-
}
|
|
422
|
+
message = scrubSecretValues(message, secretValues);
|
|
405
423
|
|
|
406
424
|
throw new HelperError(
|
|
407
425
|
"response",
|
|
@@ -498,7 +516,6 @@ export async function restGet(
|
|
|
498
516
|
shape.charset,
|
|
499
517
|
opts?.secretHeaderNames,
|
|
500
518
|
hasQuerySecret,
|
|
501
|
-
opts?.secretQueryParamNames,
|
|
502
519
|
);
|
|
503
520
|
|
|
504
521
|
// 7. Check HTTP status before attempting to parse the body.
|
|
@@ -627,14 +644,16 @@ export async function paginate(
|
|
|
627
644
|
|
|
628
645
|
// Seed offset/page params.
|
|
629
646
|
if (style === "offset-limit" || style === "page") {
|
|
630
|
-
// Caller value, else
|
|
631
|
-
//
|
|
647
|
+
// Caller value, else `pagination.base` (where this API's index
|
|
648
|
+
// starts), else the recipe's declared default for this page param,
|
|
649
|
+
// else the style's framework default: 0 for offset-limit (row
|
|
632
650
|
// offsets start at 0) and 1 for page (nearly all page-indexed APIs are
|
|
633
651
|
// 1-based; a rare 0-based page API overrides with
|
|
634
|
-
// `params: { page: { default: 0 } }`).
|
|
652
|
+
// `base: 0` or `params: { page: { default: 0 } }`).
|
|
635
653
|
const fallback = style === "page" ? 1 : 0;
|
|
636
654
|
const rawPage =
|
|
637
655
|
params[pagCfg.pageParam!] ??
|
|
656
|
+
pagCfg.base ??
|
|
638
657
|
operation.params[pagCfg.pageParam!]?.default ??
|
|
639
658
|
fallback;
|
|
640
659
|
page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
|
|
@@ -645,6 +664,23 @@ export async function paginate(
|
|
|
645
664
|
// Agent-supplied only (secret param names excluded, incl. passthrough).
|
|
646
665
|
const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
|
|
647
666
|
const effectiveParams = buildQueryParams(operation, params, secretParamNames);
|
|
667
|
+
|
|
668
|
+
// Resolve the effective page size once for the seeding styles — the
|
|
669
|
+
// caller's value, else the op's declared default (both already folded into
|
|
670
|
+
// effectiveParams), else pagCfg.pageSize, else 50. Used for the per-page
|
|
671
|
+
// pageSizeParam set AND the offset-limit advance, so a caller-supplied
|
|
672
|
+
// size is honored end-to-end (the row-offset increment must match the size
|
|
673
|
+
// the server honored, or pages overlap/skip).
|
|
674
|
+
let effectivePageSize: number | undefined;
|
|
675
|
+
if (style === "offset-limit" || style === "page") {
|
|
676
|
+
const rawSize =
|
|
677
|
+
pagCfg.pageSizeParam === undefined
|
|
678
|
+
? undefined
|
|
679
|
+
: (params[pagCfg.pageSizeParam] ?? effectiveParams[pagCfg.pageSizeParam]);
|
|
680
|
+
effectivePageSize =
|
|
681
|
+
rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
|
|
682
|
+
if (isNaN(effectivePageSize)) effectivePageSize = 50;
|
|
683
|
+
}
|
|
648
684
|
// Secret query params injected below the agent map on every page's fetch URL.
|
|
649
685
|
const secretParams = opts?.secretQueryParams ?? {};
|
|
650
686
|
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
@@ -659,8 +695,9 @@ export async function paginate(
|
|
|
659
695
|
|
|
660
696
|
if (style === "offset-limit" || style === "page") {
|
|
661
697
|
pageParams[pagCfg.pageParam!] = String(page ?? 0);
|
|
698
|
+
// effectivePageSize is always resolved (a number) in this branch.
|
|
662
699
|
if (pagCfg.pageSizeParam) {
|
|
663
|
-
pageParams[pagCfg.pageSizeParam] = String(
|
|
700
|
+
pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
|
|
664
701
|
}
|
|
665
702
|
} else if (style === "cursor" && cursor !== undefined) {
|
|
666
703
|
pageParams[pagCfg.cursorParam!] = cursor;
|
|
@@ -724,7 +761,6 @@ export async function paginate(
|
|
|
724
761
|
shape.charset,
|
|
725
762
|
opts?.secretHeaderNames,
|
|
726
763
|
hasQuerySecret,
|
|
727
|
-
opts?.secretQueryParamNames,
|
|
728
764
|
);
|
|
729
765
|
|
|
730
766
|
// Check HTTP status before attempting to parse. Secret values scrubbed
|
|
@@ -806,7 +842,13 @@ export async function paginate(
|
|
|
806
842
|
}
|
|
807
843
|
|
|
808
844
|
// Determine next page.
|
|
809
|
-
const advanced = advancePagination(
|
|
845
|
+
const advanced = advancePagination(
|
|
846
|
+
style,
|
|
847
|
+
pagCfg,
|
|
848
|
+
data,
|
|
849
|
+
page,
|
|
850
|
+
effectivePageSize,
|
|
851
|
+
);
|
|
810
852
|
|
|
811
853
|
if (!advanced) break;
|
|
812
854
|
|
|
@@ -846,13 +888,19 @@ function advancePagination(
|
|
|
846
888
|
cfg: NonNullable<Operation["pagination"]>,
|
|
847
889
|
data: unknown,
|
|
848
890
|
prevPage?: number,
|
|
891
|
+
effectivePageSize?: number,
|
|
849
892
|
): PaginationState | null {
|
|
850
893
|
if (style === "offset-limit") {
|
|
851
894
|
// Row-offset semantics: the API skips `offset` items, so the next page
|
|
852
|
-
// must advance by the page size
|
|
853
|
-
//
|
|
854
|
-
//
|
|
855
|
-
|
|
895
|
+
// must advance by the effective page size (caller value → op default →
|
|
896
|
+
// cfg.pageSize → 50) — the size actually sent — not by 1 (a +1 advance
|
|
897
|
+
// re-reads the same rows and overlaps pages) and not by a stale
|
|
898
|
+
// pageSize (overlaps/skips when the caller overrides the size). APIs
|
|
899
|
+
// whose param is a true page index use style: page, which keeps the +1
|
|
900
|
+
// advance.
|
|
901
|
+
return {
|
|
902
|
+
page: (prevPage ?? 0) + (effectivePageSize ?? cfg.pageSize ?? 50),
|
|
903
|
+
};
|
|
856
904
|
}
|
|
857
905
|
|
|
858
906
|
if (style === "page") {
|
package/core/local-helpers.ts
CHANGED
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
import { join } from "node:path";
|
|
29
29
|
import { pathToFileURL } from "node:url";
|
|
30
30
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
31
|
-
import { getUserGuidesDir
|
|
31
|
+
import { getUserGuidesDir } from "./guide-store.js";
|
|
32
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
32
33
|
|
|
33
34
|
// ═══════════════════════════════════════════════════════════════════
|
|
34
35
|
// Session-level state
|