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.
- package/README.md +62 -89
- package/core/api-guide-types.ts +9 -0
- package/core/api-toggle.ts +23 -1
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +28 -0
- package/core/parse-api-guide.ts +451 -24
- package/core/resolve-op.ts +222 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +399 -0
- package/package.json +5 -1
- package/tools/api-fetch.ts +149 -229
- package/tools/api-guide.ts +33 -38
- package/tools/api-learn.ts +432 -131
- package/tools/api-probe.ts +146 -36
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* resolveOpForExecution — the shared guide-resolution → helper-call →
|
|
3
|
+
* transform-load → auth-resolution → executor-dispatch sequence used by both
|
|
4
|
+
* `api-fetch` (single op) and `/api verify` (a loop over every op). One
|
|
5
|
+
* implementation, two real call sites — a duplicated copy would drift and
|
|
6
|
+
* ship a known second bug, so the sequence lives here.
|
|
7
|
+
*
|
|
8
|
+
* The caller owns everything around it: guide/op resolution (api-fetch by
|
|
9
|
+
* op name across guides, verify by declared order), result formatting, and
|
|
10
|
+
* error/skip rendering. This module only turns a (guide, op) into a
|
|
11
|
+
* successful executor result or a structured non-run outcome.
|
|
12
|
+
*
|
|
13
|
+
* Throws `HelperError` / transport errors up to the caller (both call sites
|
|
14
|
+
* catch); returns a non-`ok` result only for the two conditions that are
|
|
15
|
+
* *not* run failures: a session-disabled local helper (skip, not fail) and
|
|
16
|
+
* a fail-closed missing `requires` secret (short-circuit before dispatch).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
restGet,
|
|
21
|
+
paginate,
|
|
22
|
+
type RestGetResult,
|
|
23
|
+
type PaginateResult,
|
|
24
|
+
} from "./helpers.js";
|
|
25
|
+
import { callHelper, loadTransform } from "./local-helpers.js";
|
|
26
|
+
import {
|
|
27
|
+
resolveSecretHeaders,
|
|
28
|
+
resolveSecretQueryParams,
|
|
29
|
+
authStatusLine,
|
|
30
|
+
canonicalStoreDomain,
|
|
31
|
+
type SecretResolution,
|
|
32
|
+
type QuerySecretResolution,
|
|
33
|
+
} from "./auth.js";
|
|
34
|
+
import type { ApiGuide, ExecutorVia, Operation } from "./api-guide-types.js";
|
|
35
|
+
|
|
36
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
37
|
+
// Types
|
|
38
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
39
|
+
|
|
40
|
+
export interface ResolveOpOptions {
|
|
41
|
+
/** User-supplied params (pre-helper) — the role `userParams` plays in api-fetch. */
|
|
42
|
+
userParams?: Record<string, unknown>;
|
|
43
|
+
/** paginate: gather all items up to the guide's ceiling. */
|
|
44
|
+
gatherAll?: boolean;
|
|
45
|
+
/** paginate: bypass the nextLink SSRF guard (test hook only). */
|
|
46
|
+
skipSsrfGuard?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Store-injected auth opts, forwarded to the executor and reused by the
|
|
50
|
+
* caller for the output-channel audit (secret scrub). */
|
|
51
|
+
interface AuthOpts {
|
|
52
|
+
authHeaders?: Record<string, string>;
|
|
53
|
+
secretHeaderNames?: Set<string>;
|
|
54
|
+
secretValues?: string[];
|
|
55
|
+
secretQueryParams?: Record<string, string>;
|
|
56
|
+
secretQueryParamNames?: Set<string>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type ResolveOpResult =
|
|
60
|
+
| {
|
|
61
|
+
ok: true;
|
|
62
|
+
via: ExecutorVia;
|
|
63
|
+
result: RestGetResult | PaginateResult;
|
|
64
|
+
/** Metadata-only auth footer (names only) — undefined for no-auth guides. */
|
|
65
|
+
authFooter?: string;
|
|
66
|
+
/** Resolved auth opts — for the caller's output-channel audit. */
|
|
67
|
+
authOpts: AuthOpts;
|
|
68
|
+
}
|
|
69
|
+
| {
|
|
70
|
+
ok: false;
|
|
71
|
+
reason: "helper_disabled";
|
|
72
|
+
/** Human-readable reason (the callHelper error message). */
|
|
73
|
+
message: string;
|
|
74
|
+
}
|
|
75
|
+
| {
|
|
76
|
+
ok: false;
|
|
77
|
+
reason: "auth_required_not_provisioned";
|
|
78
|
+
/** The secret names a `requires` block wants but the store lacks. */
|
|
79
|
+
missing: string[];
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
83
|
+
// resolveOpForExecution
|
|
84
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Resolve and execute one operation against its guide.
|
|
88
|
+
*
|
|
89
|
+
* @param guide The matched ApiGuide.
|
|
90
|
+
* @param op The operation to execute.
|
|
91
|
+
* @param helperDirName The guide's directory name — the helper-routing key
|
|
92
|
+
* for `callHelper` / `loadTransform` (diverges from the
|
|
93
|
+
* routing `domain` in the multi-recipe case).
|
|
94
|
+
* @param opts Execution options (user params, gatherAll, …).
|
|
95
|
+
*/
|
|
96
|
+
export async function resolveOpForExecution(
|
|
97
|
+
guide: ApiGuide,
|
|
98
|
+
op: Operation,
|
|
99
|
+
helperDirName: string,
|
|
100
|
+
opts?: ResolveOpOptions,
|
|
101
|
+
): Promise<ResolveOpResult> {
|
|
102
|
+
// The canonical secret-store key: `guide.domains[0]` (the plain browsable
|
|
103
|
+
// domain), independent of the routing `domain` the caller was given.
|
|
104
|
+
const storeDomain = canonicalStoreDomain(guide);
|
|
105
|
+
const userParams = opts?.userParams ?? {};
|
|
106
|
+
|
|
107
|
+
// 1. Pre-call helper (op.helper === true). A session-disabled helper is a
|
|
108
|
+
// skip, not a failure — the op is unverifiable this session, not broken.
|
|
109
|
+
let executeParams = userParams;
|
|
110
|
+
if (op.helper === true) {
|
|
111
|
+
const helperResult = await callHelper(helperDirName, op.name, executeParams);
|
|
112
|
+
if (!helperResult.ok) {
|
|
113
|
+
return { ok: false, reason: "helper_disabled", message: helperResult.error };
|
|
114
|
+
}
|
|
115
|
+
executeParams = helperResult.params;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 2. Post-response transform (op.transform === true). Loaded once before
|
|
119
|
+
// dispatch; the executor owns the invocation + its try/catch (a throw
|
|
120
|
+
// never escapes — it surfaces as a non-blocking transformWarning).
|
|
121
|
+
const transformFn =
|
|
122
|
+
op.transform === true ? await loadTransform(helperDirName) : null;
|
|
123
|
+
if (op.transform === true && transformFn === null) {
|
|
124
|
+
console.warn(
|
|
125
|
+
`⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 3. Auth resolution (kind: static-key) — resolve store-injected headers
|
|
130
|
+
// AND query params up front so a missing required secret fails closed
|
|
131
|
+
// BEFORE any request. Values never leave this scope — only header/param
|
|
132
|
+
// and secret NAMES ever surface to the caller.
|
|
133
|
+
let headerRes: SecretResolution | undefined;
|
|
134
|
+
let queryRes: QuerySecretResolution | undefined;
|
|
135
|
+
if (guide.auth.kind === "static-key") {
|
|
136
|
+
headerRes = resolveSecretHeaders(guide.auth, storeDomain);
|
|
137
|
+
queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
|
|
138
|
+
const missingRequired = [
|
|
139
|
+
...(headerRes.absentRequired ?? []),
|
|
140
|
+
...(queryRes.absentRequired ?? []),
|
|
141
|
+
];
|
|
142
|
+
if (missingRequired.length > 0) {
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
reason: "auth_required_not_provisioned",
|
|
146
|
+
missing: missingRequired,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const headerValues = headerRes
|
|
151
|
+
? [...Object.values(headerRes.headers), ...headerRes.rawHeaderValues]
|
|
152
|
+
: [];
|
|
153
|
+
const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
|
|
154
|
+
const authOpts: AuthOpts =
|
|
155
|
+
headerRes || queryRes
|
|
156
|
+
? {
|
|
157
|
+
...(headerRes
|
|
158
|
+
? {
|
|
159
|
+
authHeaders: headerRes.headers,
|
|
160
|
+
secretHeaderNames: new Set(
|
|
161
|
+
Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
|
|
162
|
+
),
|
|
163
|
+
}
|
|
164
|
+
: {}),
|
|
165
|
+
...(queryRes
|
|
166
|
+
? {
|
|
167
|
+
secretQueryParams: queryRes.queryParams,
|
|
168
|
+
secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
|
|
169
|
+
}
|
|
170
|
+
: {}),
|
|
171
|
+
secretValues: [...headerValues, ...queryValues],
|
|
172
|
+
}
|
|
173
|
+
: {};
|
|
174
|
+
const authFooter = authStatusLine(guide.auth, storeDomain);
|
|
175
|
+
|
|
176
|
+
// 4. Execute via the declared executor.
|
|
177
|
+
if (op.via === "restGet") {
|
|
178
|
+
const result = await restGet(
|
|
179
|
+
guide.apiHost,
|
|
180
|
+
op,
|
|
181
|
+
executeParams,
|
|
182
|
+
guide,
|
|
183
|
+
authOpts,
|
|
184
|
+
transformFn ?? undefined,
|
|
185
|
+
helperDirName,
|
|
186
|
+
);
|
|
187
|
+
return {
|
|
188
|
+
ok: true,
|
|
189
|
+
via: "restGet",
|
|
190
|
+
result,
|
|
191
|
+
...(authFooter ? { authFooter } : {}),
|
|
192
|
+
authOpts,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (op.via === "paginate") {
|
|
197
|
+
const paginateOpts: Parameters<typeof paginate>[4] = {
|
|
198
|
+
...authOpts,
|
|
199
|
+
...(opts?.skipSsrfGuard ? { skipSsrfGuard: true } : {}),
|
|
200
|
+
...(opts?.gatherAll === undefined ? {} : { gatherAll: opts.gatherAll }),
|
|
201
|
+
};
|
|
202
|
+
const result = await paginate(
|
|
203
|
+
guide.apiHost,
|
|
204
|
+
op,
|
|
205
|
+
executeParams,
|
|
206
|
+
guide,
|
|
207
|
+
paginateOpts,
|
|
208
|
+
transformFn ?? undefined,
|
|
209
|
+
helperDirName,
|
|
210
|
+
);
|
|
211
|
+
return {
|
|
212
|
+
ok: true,
|
|
213
|
+
via: "paginate",
|
|
214
|
+
result,
|
|
215
|
+
...(authFooter ? { authFooter } : {}),
|
|
216
|
+
authOpts,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// TypeScript guard — all ExecutorVia values handled above.
|
|
221
|
+
throw new Error(`Unhandled executor '${op.via as string}'.`);
|
|
222
|
+
}
|
package/core/transport.ts
CHANGED
|
@@ -433,7 +433,7 @@ export async function fetchUrl(
|
|
|
433
433
|
const reqHeaders: Record<string, string> = { ...opts?.headers };
|
|
434
434
|
if (!reqHeaders["user-agent"]) {
|
|
435
435
|
reqHeaders["user-agent"] =
|
|
436
|
-
"pi-lean-host/0.
|
|
436
|
+
"pi-lean-host/0.3.1 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
437
437
|
}
|
|
438
438
|
|
|
439
439
|
if (!opts?.fresh && !hasAuth) {
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/api verify <domain> [guide] [--force]` — verify every runnable operation
|
|
3
|
+
* of a guide against its live API, stamping `verified: today` only when all
|
|
4
|
+
* runnable ops pass.
|
|
5
|
+
*
|
|
6
|
+
* - `verify <domain>` — fetch every op; stamp on all-runnable-pass.
|
|
7
|
+
* - `verify <domain> <guide>` — pick a guide by shortName (N-guide domains).
|
|
8
|
+
* - `verify <domain> --force` — stamp today WITHOUT running any ops
|
|
9
|
+
* (human-typed "human-attested good" escape valve).
|
|
10
|
+
* - `verify --help` — usage + cost note.
|
|
11
|
+
*
|
|
12
|
+
* Strict threshold: any runnable-op failure (partial or all-fail) → no stamp.
|
|
13
|
+
* Skipped ops are NOT failures and don't block the stamp, but are named in
|
|
14
|
+
* the report. Two skip categories: unsatisfiable params (a path `{token}` or
|
|
15
|
+
* required query param with no default, and no verify.json value) and a
|
|
16
|
+
* session-disabled local helper. A post-response transform failure is
|
|
17
|
+
* non-blocking (the HTTP op succeeded — the executor carries it as a
|
|
18
|
+
* `transformWarning`).
|
|
19
|
+
*
|
|
20
|
+
* Opt-in params sidecar: a co-located
|
|
21
|
+
* `~/.pi/agent/pi-lean-host/api-guides/<dirName>/verify.json`,
|
|
22
|
+
* shape `{ "<opName>": { "<param>": "<value>" } }`, supplies the params map
|
|
23
|
+
* verbatim to the executor (pre-helper inputs for `helper: true` ops). It is
|
|
24
|
+
* the only way an op with unsatisfiable params can run.
|
|
25
|
+
*
|
|
26
|
+
* Always-available (runs in **on** mode, not just learn) and not refused by
|
|
27
|
+
* the focus-mode guard — it writes no toolset state (peer of `secrets`).
|
|
28
|
+
* Runs the executor/auth/transport directly, so it works even when the
|
|
29
|
+
* api-fetch / api-guide tools are masked off.
|
|
30
|
+
*
|
|
31
|
+
* Not free: N live HTTP requests against the target API (GET only — no
|
|
32
|
+
* mutation side-effects, but real quota/rate-limit cost). Reuses the
|
|
33
|
+
* transport's existing 429 retry at the default maxRetries.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
37
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
38
|
+
import { join } from "node:path";
|
|
39
|
+
import {
|
|
40
|
+
findGuidesByDomain,
|
|
41
|
+
invalidateCache,
|
|
42
|
+
getUserGuidesDir,
|
|
43
|
+
} from "./guide-store.js";
|
|
44
|
+
import {
|
|
45
|
+
formatGuideListings,
|
|
46
|
+
selectGuideByShortName,
|
|
47
|
+
shortNameErrorText,
|
|
48
|
+
stampFrontmatterField,
|
|
49
|
+
TODAY,
|
|
50
|
+
} from "./parse-api-guide.js";
|
|
51
|
+
import { pickGuide } from "./guide-picker.js";
|
|
52
|
+
import {
|
|
53
|
+
resolveSecretHeaders,
|
|
54
|
+
resolveSecretQueryParams,
|
|
55
|
+
canonicalStoreDomain,
|
|
56
|
+
} from "./auth.js";
|
|
57
|
+
import { resolveOpForExecution, type ResolveOpResult } from "./resolve-op.js";
|
|
58
|
+
import {
|
|
59
|
+
HelperError,
|
|
60
|
+
type RestGetResult,
|
|
61
|
+
type PaginateResult,
|
|
62
|
+
} from "./helpers.js";
|
|
63
|
+
import type { ApiGuide, Operation } from "./api-guide-types.js";
|
|
64
|
+
|
|
65
|
+
/** Usage + cost note, surfaced by `--help`. */
|
|
66
|
+
function helpText(): string {
|
|
67
|
+
return [
|
|
68
|
+
"Usage: /api verify <domain> [guide] [--force]",
|
|
69
|
+
" /api verify <domain> fetch every runnable op; stamp verified: today on all-pass",
|
|
70
|
+
" /api verify <domain> <guide> pick a guide by shortName when a domain claims several",
|
|
71
|
+
" /api verify <domain> --force stamp verified: today WITHOUT running any ops (human-attested)",
|
|
72
|
+
" /api verify --help this help",
|
|
73
|
+
"",
|
|
74
|
+
" Ops with unsatisfiable params (a path {token} or required query param with no default)",
|
|
75
|
+
" are skipped, not failed. Supply them via a co-located verify.json:",
|
|
76
|
+
` ~/.pi/agent/pi-lean-host/api-guides/<domain>/verify.json`,
|
|
77
|
+
` { "<opName>": { "<param>": "<value>" } }`,
|
|
78
|
+
"",
|
|
79
|
+
" Not free: N live HTTP requests against the target API (GET only — no mutation).",
|
|
80
|
+
" Reuses the transport's 429 retry at the default maxRetries.",
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Handle the `verify` subcommand of `/api`.
|
|
86
|
+
*
|
|
87
|
+
* @param args The text after "verify" ("" / "<domain>" / "<domain> <guide>").
|
|
88
|
+
* @param ctx The extension command context
|
|
89
|
+
*/
|
|
90
|
+
export async function handleVerifySubcommand(
|
|
91
|
+
args: string,
|
|
92
|
+
ctx: ExtensionCommandContext,
|
|
93
|
+
): Promise<void> {
|
|
94
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
95
|
+
|
|
96
|
+
if (parts.includes("--help") || parts.includes("help")) {
|
|
97
|
+
ctx.ui.notify(helpText(), "info");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const force = parts.includes("--force");
|
|
102
|
+
const tokens = parts.filter((p) => p !== "--force");
|
|
103
|
+
const domain = tokens[0];
|
|
104
|
+
const guideSelector = tokens[1];
|
|
105
|
+
|
|
106
|
+
if (!domain) {
|
|
107
|
+
ctx.ui.notify(
|
|
108
|
+
"Usage: /api verify <domain> [guide] [--force] — see /api verify --help.",
|
|
109
|
+
"warning",
|
|
110
|
+
);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Resolve the guide by domain (disambiguation for N-guide domains).
|
|
115
|
+
const matches = findGuidesByDomain(domain);
|
|
116
|
+
if (matches.length === 0) {
|
|
117
|
+
ctx.ui.notify(
|
|
118
|
+
`No API guide for '${domain}'. ` +
|
|
119
|
+
`Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author one.`,
|
|
120
|
+
"warning",
|
|
121
|
+
);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let selected: { guide: ApiGuide; dirName: string };
|
|
126
|
+
if (matches.length === 1) {
|
|
127
|
+
selected = matches[0]!;
|
|
128
|
+
} else if (guideSelector) {
|
|
129
|
+
const sel = selectGuideByShortName(matches, guideSelector);
|
|
130
|
+
if (!sel.ok) {
|
|
131
|
+
ctx.ui.notify(
|
|
132
|
+
shortNameErrorText(
|
|
133
|
+
sel,
|
|
134
|
+
domain,
|
|
135
|
+
guideSelector,
|
|
136
|
+
`Call /api verify ${domain} to see the menu.`,
|
|
137
|
+
),
|
|
138
|
+
"warning",
|
|
139
|
+
);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
selected = sel;
|
|
143
|
+
} else {
|
|
144
|
+
// N guides, no selector → interactive pick (TUI) or the menu
|
|
145
|
+
// fallback (headless/RPC/print or cancelled), nothing run yet.
|
|
146
|
+
const picked = await pickGuide(ctx, matches);
|
|
147
|
+
if (!picked) {
|
|
148
|
+
ctx.ui.notify(
|
|
149
|
+
[
|
|
150
|
+
`${matches.length} API guides for '${domain}':`,
|
|
151
|
+
formatGuideListings(matches),
|
|
152
|
+
`Call /api verify ${domain} <shortName> to pick one.`,
|
|
153
|
+
].join("\n"),
|
|
154
|
+
"info",
|
|
155
|
+
);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
selected = picked;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const { guide, dirName } = selected;
|
|
162
|
+
const storeDomain = canonicalStoreDomain(guide);
|
|
163
|
+
|
|
164
|
+
// --force: human-attested stamp, no HTTP at all.
|
|
165
|
+
if (force) {
|
|
166
|
+
stampVerified(dirName);
|
|
167
|
+
ctx.ui.notify(
|
|
168
|
+
`📡 Verify --force: ${guide.shortName} (${dirName})\n` +
|
|
169
|
+
` Stamped verified: ${TODAY()} without running any ops — human-attested good.\n` +
|
|
170
|
+
` Note: this reflects attestation, not a run confirmation.`,
|
|
171
|
+
"info",
|
|
172
|
+
);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Auth precheck (fail-fast): resolve the same secrets api-fetch does. If
|
|
177
|
+
// any `requires` secret is unprovisioned, short-circuit with ONE message —
|
|
178
|
+
// do not run N ops that all fail identically.
|
|
179
|
+
if (guide.auth.kind === "static-key") {
|
|
180
|
+
const headerRes = resolveSecretHeaders(guide.auth, storeDomain);
|
|
181
|
+
const queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
|
|
182
|
+
const missingRequired = [
|
|
183
|
+
...headerRes.absentRequired,
|
|
184
|
+
...queryRes.absentRequired,
|
|
185
|
+
];
|
|
186
|
+
if (missingRequired.length > 0) {
|
|
187
|
+
ctx.ui.notify(
|
|
188
|
+
`🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
|
|
189
|
+
`${missingRequired.join(", ")}.\n` +
|
|
190
|
+
`Run /api secrets ${storeDomain} to provision it, then re-run /api verify.`,
|
|
191
|
+
"warning",
|
|
192
|
+
);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Best-effort verify.json sidecar: file-miss → no sidecar (today's skip
|
|
198
|
+
// behavior); malformed → parse error caught at load, not a runtime crash.
|
|
199
|
+
const sidecar = loadVerifyJson(dirName);
|
|
200
|
+
if (sidecar && "error" in sidecar) {
|
|
201
|
+
ctx.ui.notify(
|
|
202
|
+
`⚠ verify.json for '${dirName}' is malformed — ignoring it (${sidecar.error}).`,
|
|
203
|
+
"warning",
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
const verifyJson = sidecar && "data" in sidecar ? sidecar.data : {};
|
|
207
|
+
|
|
208
|
+
// ── Fetch loop ──────────────────────────────────────────────
|
|
209
|
+
const ops = guide.operations;
|
|
210
|
+
const report: string[] = [];
|
|
211
|
+
let ran = 0;
|
|
212
|
+
let failed = 0;
|
|
213
|
+
let skipped = 0;
|
|
214
|
+
|
|
215
|
+
for (const op of ops) {
|
|
216
|
+
const supplied = verifyJson[op.name] ?? {};
|
|
217
|
+
const missing = unsatisfiableParams(op, supplied);
|
|
218
|
+
if (missing.length > 0) {
|
|
219
|
+
skipped++;
|
|
220
|
+
report.push(
|
|
221
|
+
` ⏭ ${op.name} — skipped: requires agent-supplied params (${missing.join(", ")}) — verify manually via api-fetch`,
|
|
222
|
+
);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
let outcome: ResolveOpResult;
|
|
227
|
+
try {
|
|
228
|
+
outcome = await resolveOpForExecution(guide, op, dirName, {
|
|
229
|
+
userParams: supplied,
|
|
230
|
+
});
|
|
231
|
+
} catch (err) {
|
|
232
|
+
failed++;
|
|
233
|
+
const msg =
|
|
234
|
+
err instanceof HelperError
|
|
235
|
+
? err.message
|
|
236
|
+
: err instanceof Error
|
|
237
|
+
? err.message
|
|
238
|
+
: String(err);
|
|
239
|
+
report.push(` ✗ ${op.name} — ${msg}`);
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!outcome.ok) {
|
|
244
|
+
if (outcome.reason === "helper_disabled") {
|
|
245
|
+
// Session-persistent condition — unverifiable this session, not broken.
|
|
246
|
+
skipped++;
|
|
247
|
+
report.push(
|
|
248
|
+
` ⏭ ${op.name} — skipped: local helper disabled this session (${outcome.message})`,
|
|
249
|
+
);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
// auth_required_not_provisioned — unreachable after the precheck
|
|
253
|
+
// (auth is per-guide constant); defensive.
|
|
254
|
+
failed++;
|
|
255
|
+
report.push(
|
|
256
|
+
` ✗ ${op.name} — requires secret not provisioned: ${outcome.missing.join(", ")}`,
|
|
257
|
+
);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
ran++;
|
|
262
|
+
report.push(opLine(outcome, op));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const header = `📡 Verify: ${guide.shortName} (${dirName})`;
|
|
266
|
+
const summary = ` Ops: ${ops.length} · ran ${ran} · failed ${failed} · skipped ${skipped}`;
|
|
267
|
+
|
|
268
|
+
if (failed > 0) {
|
|
269
|
+
ctx.ui.notify(
|
|
270
|
+
[
|
|
271
|
+
header,
|
|
272
|
+
summary,
|
|
273
|
+
...report,
|
|
274
|
+
"",
|
|
275
|
+
`❌ NOT stamped — ${failed} op(s) failed. Fix and re-run /api verify.`,
|
|
276
|
+
].join("\n"),
|
|
277
|
+
"warning",
|
|
278
|
+
);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (ran === 0) {
|
|
282
|
+
ctx.ui.notify(
|
|
283
|
+
[
|
|
284
|
+
header,
|
|
285
|
+
summary,
|
|
286
|
+
...report,
|
|
287
|
+
"",
|
|
288
|
+
`⚠ NOT stamped — all ops skipped. Supply params via verify.json (${dirName}/verify.json), or verify manually via api-fetch.`,
|
|
289
|
+
].join("\n"),
|
|
290
|
+
"warning",
|
|
291
|
+
);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
stampVerified(dirName);
|
|
296
|
+
ctx.ui.notify(
|
|
297
|
+
[
|
|
298
|
+
header,
|
|
299
|
+
summary,
|
|
300
|
+
...report,
|
|
301
|
+
"",
|
|
302
|
+
`✅ All runnable ops passed — stamped verified: ${TODAY()}`,
|
|
303
|
+
].join("\n"),
|
|
304
|
+
"info",
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
309
|
+
// Helpers
|
|
310
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The params an op still needs to run: path `{token}`s (never defaultable —
|
|
314
|
+
* they're filled from the params map), `required: true` query params with no
|
|
315
|
+
* default, and an unsatisfied `requiresAnyOf` group. Anything the executor
|
|
316
|
+
* would throw on before making a request.
|
|
317
|
+
*
|
|
318
|
+
* A `requiresAnyOf` group contributes ONE group-level reason when no member
|
|
319
|
+
* is supplied; group members are governed by the group, not per-param
|
|
320
|
+
* required (the parser bans `required: true` on them), so they're skipped
|
|
321
|
+
* in the per-param loop.
|
|
322
|
+
*/
|
|
323
|
+
function unsatisfiableParams(
|
|
324
|
+
op: Operation,
|
|
325
|
+
supplied: Record<string, unknown>,
|
|
326
|
+
): string[] {
|
|
327
|
+
const missing: string[] = [];
|
|
328
|
+
for (const token of op.pathParams) {
|
|
329
|
+
if (supplied[token] === undefined) missing.push(token);
|
|
330
|
+
}
|
|
331
|
+
const group = op.requiresAnyOf;
|
|
332
|
+
const groupMember = new Set(group ?? []);
|
|
333
|
+
if (group && group.length > 0) {
|
|
334
|
+
const anySupplied = group.some((name) => supplied[name] !== undefined);
|
|
335
|
+
if (!anySupplied) missing.push(`one of: ${group.join(", ")}`);
|
|
336
|
+
}
|
|
337
|
+
for (const [key, spec] of Object.entries(op.params)) {
|
|
338
|
+
if (groupMember.has(key)) continue; // governed by the group
|
|
339
|
+
if (
|
|
340
|
+
spec.required &&
|
|
341
|
+
spec.default === undefined &&
|
|
342
|
+
supplied[key] === undefined
|
|
343
|
+
) {
|
|
344
|
+
missing.push(key);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return missing;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Load the co-located verify.json sidecar, best-effort. */
|
|
351
|
+
function loadVerifyJson(
|
|
352
|
+
dirName: string,
|
|
353
|
+
):
|
|
354
|
+
| { data: Record<string, Record<string, unknown>> }
|
|
355
|
+
| { error: string }
|
|
356
|
+
| null {
|
|
357
|
+
const p = join(getUserGuidesDir(), dirName, "verify.json");
|
|
358
|
+
if (!existsSync(p)) return null;
|
|
359
|
+
try {
|
|
360
|
+
const parsed: unknown = JSON.parse(readFileSync(p, "utf-8"));
|
|
361
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
362
|
+
return { data: parsed as Record<string, Record<string, unknown>> };
|
|
363
|
+
}
|
|
364
|
+
return { error: "expected a JSON object" };
|
|
365
|
+
} catch (err) {
|
|
366
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** One report line for a successful op run. A transform warning is noted but
|
|
371
|
+
* non-blocking — the HTTP op succeeded, so the op counts as pass. */
|
|
372
|
+
function opLine(
|
|
373
|
+
outcome: Extract<ResolveOpResult, { ok: true }>,
|
|
374
|
+
op: Operation,
|
|
375
|
+
): string {
|
|
376
|
+
if (outcome.via === "restGet") {
|
|
377
|
+
const r = outcome.result as RestGetResult;
|
|
378
|
+
const warn =
|
|
379
|
+
r.transformWarning === undefined
|
|
380
|
+
? ""
|
|
381
|
+
: ` — transform warning: ${r.transformWarning}`;
|
|
382
|
+
return ` ✓ ${op.name} — ${op.path} (restGet)${warn}`;
|
|
383
|
+
}
|
|
384
|
+
const r = outcome.result as PaginateResult;
|
|
385
|
+
return ` ✓ ${op.name} — ${r.totalFetched} item(s) (paginate)`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Stamp `verified: today` into the raw guide.md (frontmatter-isolated,
|
|
390
|
+
* line-level — comments + key order preserved), then invalidate the cache so
|
|
391
|
+
* the next api-guide / api-fetch sees the fresh date immediately.
|
|
392
|
+
*/
|
|
393
|
+
function stampVerified(dirName: string): void {
|
|
394
|
+
const filepath = join(getUserGuidesDir(), dirName, "guide.md");
|
|
395
|
+
const raw = readFileSync(filepath, "utf-8");
|
|
396
|
+
const stamped = stampFrontmatterField(raw, "verified", TODAY());
|
|
397
|
+
writeFileSync(filepath, stamped, "utf-8");
|
|
398
|
+
invalidateCache();
|
|
399
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-lean-host",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|
|
@@ -50,6 +50,10 @@
|
|
|
50
50
|
"core/auth.ts",
|
|
51
51
|
"core/portal-projection.ts",
|
|
52
52
|
"core/response-spill.ts",
|
|
53
|
+
"core/resolve-op.ts",
|
|
54
|
+
"core/guide-picker.ts",
|
|
55
|
+
"core/verify-command.ts",
|
|
56
|
+
"core/delete-command.ts",
|
|
53
57
|
"core/verify-ship-manifest.ts",
|
|
54
58
|
"tools/index.ts",
|
|
55
59
|
"tools/api-guide.ts",
|