pi-lean-host 0.3.1 → 0.5.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.
@@ -20,65 +20,217 @@ import type { Guide } from "./guide-loader.js";
20
20
  export const GATHER_ALL_MAX_FALLBACK = 1000;
21
21
 
22
22
  /**
23
- * The schema version of the guide recipe format. Metadata-only attribution:
24
- * it is surfaced on the parsed guide but NEVER gates/warns/alters parse
25
- * (see __tests__/schema-version.test.ts). Absent frontmatter defaults to the
26
- * semantic 0. Bumped to 1 at lockstep (a label change, not a break).
23
+ * The schema version of the guide recipe format. Enforced by the hard gate:
24
+ * a guide whose schemaVersion is stale (< current) fails to parse and routes
25
+ * to malformed (see __tests__/schema-version.test.ts). Absent frontmatter
26
+ * defaults to the semantic 0, so an unversioned guide is treated as pre-v1
27
+ * and refused. Bumped to 1 at the v1 auth-type reshape (0.5.0) — a breaking
28
+ * TS-type + YAML-shape change to `AuthConfig`, not a parse-behavior break.
27
29
  */
28
- export const GUIDE_SCHEMA_VERSION = 0 as const;
30
+ export const GUIDE_SCHEMA_VERSION = 1 as const;
29
31
 
30
- /** Auth strategies recognized by the schema (the seam). v1 realizes `none` and `static-key`; `oauth2` is rejected at parse. */
32
+ /** Auth strategies recognized by the schema (the seam). v1 realizes `none`, `static-key`, and `oauth2`. */
31
33
  export const KNOWN_AUTH_KINDS: ReadonlySet<string> = new Set([
32
34
  "none",
33
35
  "static-key",
34
36
  "oauth2",
35
37
  ]);
36
38
 
37
- // ═══════════════════════════════════════════════════════════════════
38
- // Auth
39
- // ═══════════════════════════════════════════════════════════════════
40
-
41
39
  export type AuthKind = "none" | "static-key" | "oauth2";
42
40
 
43
- export interface AuthConfig {
44
- kind: AuthKind;
41
+ /**
42
+ * A single secret reference — self-contained. Availability is a property of
43
+ * THIS ref (default: required, fail-closed when absent), not a separate
44
+ * roster. `prefix` folds the old top-level `headerPrefixes` inline. Shared by
45
+ * `StaticKeyAuth` and `OAuth2Auth` with the SAME semantics (map key = request
46
+ * header name).
47
+ */
48
+ export interface SecretRef {
49
+ /** Store name (provisioned via /api secrets <domain>). */
50
+ secret: string;
51
+ /** Prefix prepended to the stored value at resolution time (e.g. "Bearer "). */
52
+ prefix?: string;
53
+ /** Default false — absent → fail-closed before the request. */
54
+ optional?: boolean;
55
+ }
56
+
57
+ export interface NoneAuth {
58
+ kind: "none";
59
+ /** Extra headers merged into every request (e.g. `X-Api-Key: DEMO_KEY`). */
60
+ headers?: Record<string, string>;
61
+ }
62
+
63
+ export interface StaticKeyAuth {
64
+ kind: "static-key";
45
65
  /** Extra headers merged into every request (e.g. `X-Api-Key: DEMO_KEY`). */
46
66
  headers?: Record<string, string>;
47
67
  /**
48
- * static-key only: maps request header name → secret store name. Values
49
- * are injected at fetch time from the secrets store; the value never
50
- * enters agent context. Every referenced name must also appear in
51
- * `requires` or `optional` (parser-enforced).
68
+ * Maps request header name → secret ref. Values are injected at fetch
69
+ * time from the secrets store; the value never enters agent context.
70
+ */
71
+ secretRefs?: Record<string, SecretRef>;
72
+ /**
73
+ * Maps query param name → secret ref. Values are injected below the
74
+ * agent-supplied params map at fetch time (never into it) and redacted
75
+ * from every surfaced URL. A param name colliding with any operation's
76
+ * `params` map is a parse error — the agent must not be able to supply a
77
+ * secretly-injected param.
78
+ */
79
+ secretQueryRefs?: Record<string, SecretRef>;
80
+ /**
81
+ * Maps path-token name → secret ref, for APIs that key every method
82
+ * through the URL path (Telegram-class: `/bot<token>/getUpdates`). Values
83
+ * fill `{name}` in every operation's path from the secrets store, below
84
+ * the agent params map, and are redacted from every surfaced URL.
85
+ * Required-only (parse rejects `optional` — an absent path token fails
86
+ * closed before the request) and never prefixed (path injection is the
87
+ * raw value). Parse rejects names the agent could supply or that no op
88
+ * path uses.
89
+ */
90
+ secretPathRefs?: Record<string, SecretRef>;
91
+ }
92
+
93
+ export const OAUTH2_GRANTS = [
94
+ "client_credentials",
95
+ "authorization_code",
96
+ ] as const;
97
+ export type OAuth2Grant = (typeof OAUTH2_GRANTS)[number];
98
+ /** Boundary decoder: input is unvalidated (guide YAML / CLI flag). */
99
+ export function isOAuth2Grant(v: unknown): v is OAuth2Grant {
100
+ return (OAUTH2_GRANTS as readonly unknown[]).includes(v);
101
+ }
102
+ export type OAuth2ParamStyle = "bearer-header" | "query";
103
+ export const OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS = [
104
+ "client_secret_basic",
105
+ "client_secret_post",
106
+ "none",
107
+ ] as const;
108
+ export type OAuth2TokenEndpointAuthMethod =
109
+ (typeof OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS)[number];
110
+ export function isOAuth2TokenEndpointAuthMethod(
111
+ v: unknown,
112
+ ): v is OAuth2TokenEndpointAuthMethod {
113
+ return (OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS as readonly unknown[]).includes(v);
114
+ }
115
+
116
+ /** Why a set of OAuth2 grant fields violates the grant invariants. */
117
+ export interface OAuth2GrantIssue {
118
+ code:
119
+ | "noneWithSecret"
120
+ | "ccRequiresSecret"
121
+ | "ccRejectsAuthorizeUrl"
122
+ | "acRequiresAuthorizeUrl";
123
+ }
124
+
125
+ /**
126
+ * The single statement of the OAuth2 grant-semantics invariants — shared by
127
+ * the guide parser (`validateOAuth2Auth`) and the synthetic-auth builder
128
+ * (`buildSyntheticOAuth2Auth`) so a new grant or invariant edit lands in one
129
+ * place. Enum membership and URL/ref shape stay caller-side (each has its
130
+ * own richer error style); this encodes only the cross-field grant rules.
131
+ * Returns the first violation (precedence: noneWithSecret, then grant rules).
132
+ */
133
+ export function oauth2GrantIssue(fields: {
134
+ grant: OAuth2Grant;
135
+ hasClientSecret: boolean;
136
+ authorizeUrl?: string | undefined;
137
+ tokenEndpointAuthMethod?: OAuth2TokenEndpointAuthMethod | undefined;
138
+ }): OAuth2GrantIssue | null {
139
+ const { grant, hasClientSecret, authorizeUrl, tokenEndpointAuthMethod } =
140
+ fields;
141
+ // tokenEndpointAuthMethod: none sends no client credentials (PKCE public
142
+ // clients) — a declared clientSecret alongside it is a contradiction.
143
+ if (tokenEndpointAuthMethod === "none" && hasClientSecret) {
144
+ return { code: "noneWithSecret" };
145
+ }
146
+ if (grant === "client_credentials") {
147
+ if (!hasClientSecret) return { code: "ccRequiresSecret" };
148
+ if (authorizeUrl !== undefined) return { code: "ccRejectsAuthorizeUrl" };
149
+ } else if (authorizeUrl === undefined) {
150
+ return { code: "acRequiresAuthorizeUrl" };
151
+ }
152
+ return null;
153
+ }
154
+
155
+ export interface OAuth2Auth {
156
+ kind: "oauth2";
157
+ grant: OAuth2Grant;
158
+ /** Token endpoint (POST — the only non-GET host makes, auth plumbing). */
159
+ tokenUrl: string;
160
+ /**
161
+ * Client auth at the token endpoint is exactly two named scalars plus a
162
+ * placement method (`tokenEndpointAuthMethod`) — never an open-ended form
163
+ * map. Client authentication happens at the token endpoint; request-header
164
+ * decoration is uniformly `secretRefs` (same semantics as static-key).
165
+ * Store-resolved values appear ONLY as `SecretRef.secret` — a shippable
166
+ * recipe bakes in no per-user credentials (each user registers their own
167
+ * app → own quota, provisioned via /api secrets <domain>).
52
168
  */
53
- secretRefs?: Record<string, string>;
169
+ clientId: SecretRef;
54
170
  /**
55
- * static-key only: maps request header name → prefix string prepended to
56
- * the stored secret value before it is sent. The store holds the raw
57
- * credential; the guide declares how it is presented (e.g.
58
- * `Authorization: "Bearer "`). Absent = verbatim value. Every key must
59
- * also appear in `secretRefs` (parser-enforced).
171
+ * Parser-required for `client_credentials`; absent for `authorization_code`
172
+ * (PKCE public clients have no secret) — enforced in `validateOAuth2Auth`.
60
173
  */
61
- headerPrefixes?: Record<string, string>;
174
+ clientSecret?: SecretRef;
62
175
  /**
63
- * static-key only: maps query param name → secret store name.
64
- * Values are injected below the agent-supplied params map at fetch time
65
- * (never into it) and redacted from every surfaced URL. A param name
66
- * colliding with any operation's `params` map is a parse error — the
67
- * agent must not be able to supply a secretly-injected param. Every
68
- * referenced name must also appear in `requires` or `optional`
69
- * (parser-enforced, same rule as `secretRefs`).
176
+ * Request header name → ref — SAME semantics as static-key (merged
177
+ * alongside the Bearer token, stripped on cross-domain redirect hops,
178
+ * scrubbed from output). E.g. Twitch's `Client-Id`. Values resolve from
179
+ * the secrets store — per-user, never shipped in the guide.
70
180
  */
71
- secretQueryRefs?: Record<string, string>;
72
- /** static-key: secret names whose absence fails the request closed before it is sent. */
73
- requires?: string[];
74
- /** static-key: secret names that add value when present but are not required. */
75
- optional?: string[];
181
+ secretRefs?: Record<string, SecretRef>;
182
+ /** Static scope list declared in the guide — no runtime picker. */
183
+ scopes?: string[];
184
+ /** Default bearer-header. `query` sends `?access_token=…` (RFC 6750 §2.3). */
185
+ paramStyle?: OAuth2ParamStyle;
186
+ /** How the client authenticates at the token endpoint. Default client_secret_post. */
187
+ tokenEndpointAuthMethod?: OAuth2TokenEndpointAuthMethod;
188
+ /** auth-code only (parser-enforced present iff grant === "authorization_code"). */
189
+ authorizeUrl?: string;
190
+ /** Optional revocation endpoint. */
191
+ revokeUrl?: string;
76
192
  }
77
193
 
194
+ export type AuthConfig = NoneAuth | StaticKeyAuth | OAuth2Auth;
195
+
196
+ // Reserved seam — request-derived credentials (HMAC / SigV4 / digest).
197
+ // Binance SIGNED GETs, AWS SigV4, RFC 7616 digest, and OAuth 1.0 (e.g. the
198
+ // HathiTrust Data API's HMAC-SHA1-signed read GETs) all require a credential
199
+ // COMPUTED FROM a secret plus request context — provably inexpressible with
200
+ // `SecretRef`, which is verbatim-plus-prefix only. When a real recipe
201
+ // targets one, it lands as a new auth `kind` (or a `derive`-family field on
202
+ // `SecretRef`) and will require auth resolution to see method + final URL;
203
+ // `resolve-op.ts` step 3 must not assume auth is URL-independent, and must
204
+ // not entrench the auth-before-URL ordering further. New enum values are
205
+ // non-events under the bump rule, so waiting is free — do not build this
206
+ // speculatively.
207
+
208
+ // Reserved seam — OAuth2 slot key (`tokenKey?: string` on OAuth2Auth, NOT in
209
+ // the schema). The slot key is (storeDomain, grant, tokenUrl); scopes and
210
+ // clientId are deliberately excluded because same-issuer tokens are shared by
211
+ // design. The accepted consequence: sibling guides on one domain with the
212
+ // same grant + tokenUrl but different scopes/clientId collapse into one slot
213
+ // (first mint wins; refresh never re-sends scopes). Trigger to add it: a bug
214
+ // report of the form "wrong scope / sibling guide gets the other guide's
215
+ // token" on one domain + same grant. The fix is then `tokenKey` (slot becomes
216
+ // `<grant>__<hash>__<tokenKey>`) — additive, non-breaking, tokens re-mint on
217
+ // first use. Do not re-litigate the slot-key design; see AGENTS.md.
218
+
78
219
  // ═══════════════════════════════════════════════════════════════════
79
220
  // Pagination
80
221
  // ═══════════════════════════════════════════════════════════════════
81
222
 
223
+ // Reserved seam — Link-header pagination (GitHub/GitLab/Shopify: the next
224
+ // page rides the `Link: <…>; rel="next"` response header; the body never
225
+ // contains it). When it lands, the shape is: `PaginationStyle +=
226
+ // "linkHeader"` plus a sibling field `linkRel?: string` (default "next"),
227
+ // the resolved URL followed through the existing nextLink SSRF-guard path
228
+ // (the URL is server-supplied from a header — equally attacker-controllable
229
+ // — so the guard MUST key off the new style). Totals-in-header, if wanted,
230
+ // is a separate additive `totalCountHeader?: string`. Never overload
231
+ // `nextLinkPath` with magic values like "header:Link" — re-meaning an
232
+ // existing field is a schema break.
233
+
82
234
  export type PaginationStyle =
83
235
  | "offset-limit"
84
236
  | "nextLink"
@@ -93,9 +245,9 @@ export interface PaginationConfig {
93
245
  itemsPath: string;
94
246
  /** offset-limit: the row-offset param name; page: the page-number param name. */
95
247
  pageParam?: string;
96
- /** offset-limit / page: the page-size param name. */
248
+ /** offset-limit / page / cursor: the page-size param name (cursor: optional). */
97
249
  pageSizeParam?: string;
98
- /** offset-limit / page: requested page size. */
250
+ /** offset-limit / page: requested page size; cursor: optional terminal fallback — omitted if nothing resolves. */
99
251
  pageSize?: number;
100
252
  /**
101
253
  * offset-limit / page: the seed value for the page param — where this
@@ -118,11 +270,22 @@ export interface PaginationConfig {
118
270
  /**
119
271
  * Style-agnostic JSON path to the server's reported total count, surfaced
120
272
  * as `serverTotal` in PaginateResult / the api-fetch footer. Guides whose
121
- * APIs expose a total opt in; guides that don't simply omit it. The count
122
- * is read from the first page only. Supersedes the old resumptionToken-only
273
+ * APIs expose a total opt in; guides that don't simply omit it. The first
274
+ * page that resolves a number wins — earlier pages that miss don't lock it
275
+ * unset, later pages can still supply it. Supersedes the old resumptionToken-only
123
276
  * `completeListSizePath` (removed pre-release, not aliased).
124
277
  */
125
278
  totalCountPath?: string;
279
+ /**
280
+ * Style-agnostic JSON path to a boolean/numeric "more pages" flag.
281
+ * Resolved per page after
282
+ * items are collected: a RESOLVED falsy value (`false`/`0`/`""`/`null`)
283
+ * stops the walk cleanly; `undefined` (field absent, or the path missed)
284
+ * never stops — pre-existing exhaustion semantics apply. Plain truthiness,
285
+ * no string coercion: `"false"` advances (documented contract). Absent →
286
+ * semantics identical to a guide without the field.
287
+ */
288
+ hasMorePath?: string;
126
289
  /** tokenBag: response keys read from each page and merged into the next request's query params. */
127
290
  continuationParams?: string[];
128
291
  }
@@ -147,11 +310,28 @@ export interface ResponseShape {
147
310
  export type ExecutorVia = "restGet" | "paginate";
148
311
  export type AcceptType = string;
149
312
 
313
+ /** Multi-value query-param serialization styles (`listStyle`). */
314
+ export const LIST_STYLES = ["comma", "repeat", "bracket"] as const;
315
+ export type ListStyle = (typeof LIST_STYLES)[number];
316
+ /** Boundary decoder: input is unvalidated (guide YAML). */
317
+ export function isListStyle(v: unknown): v is ListStyle {
318
+ return (LIST_STYLES as readonly unknown[]).includes(v);
319
+ }
320
+
150
321
  export interface QueryParamSpec {
151
322
  required?: boolean;
152
323
  default?: unknown;
153
324
  /** Human-readable hint surfaced to the model via api-guide (format, semantics). */
154
325
  description?: string;
326
+ /**
327
+ * Multi-value serialization style. Absent = single-valued (today's
328
+ * behavior; an array value is a runtime error). `comma` joins the array
329
+ * with `,` (one pair), `repeat` fans out one pair per element under the
330
+ * declared name, `bracket` fans out with the wire key dressed `+ "[]"`
331
+ * (`id[]=a&id[]=b`). Scalar values ignore it entirely. Parser-validated;
332
+ * the runtime serializer enforces the same rules.
333
+ */
334
+ listStyle?: ListStyle;
155
335
  }
156
336
 
157
337
  export type DateParamFormat = "iso8601" | "yyyymmdd" | "yyyy-mm-dd";
@@ -177,10 +357,15 @@ export interface Operation {
177
357
  /**
178
358
  * At-least-one-of constraint: at least one of these param names must be
179
359
  * supplied. Members may not be `required: true` nor carry a `default`
180
- * (both parser-enforced) — they are mutually exclusive peers, so a
181
- * default would fire alongside a caller-supplied sibling and a
182
- * `required` flag would defeat the group. One group per op (v1); a
183
- * multi-group `requiresAnyOfGroups` upgrade is purely additive.
360
+ * (both parser-enforced) — a default would fire alongside a
361
+ * caller-supplied sibling and a `required` flag would defeat the group.
362
+ * Semantics are at-least-one-of with all supplied members sent — members
363
+ * may combine freely (Twitch `/helix/users` accepts `id` AND `login`
364
+ * together); they are NOT mutually exclusive. One group per op (v1); a
365
+ * multi-group upgrade lands only as a new sibling key
366
+ * (`requiresAnyOfGroups?: string[][]`, AND semantics over groups, each
367
+ * group at-least-one-of) — never as a union on this field, which would
368
+ * re-mean it.
184
369
  */
185
370
  requiresAnyOf?: string[];
186
371
  /**
@@ -192,10 +377,27 @@ export interface Operation {
192
377
  * Whether this operation post-processes the parsed response with the
193
378
  * domain's local helper `transform` export (post-response). A `true`
194
379
  * value means call `<guidesDir>/<domain>/helper.ts`'s named `transform`.
380
+ *
381
+ * Frozen contract: on `via: paginate` the transform is PER-ITEM, by
382
+ * documented contract in both executors and the escape-valve doc. A
383
+ * whole-envelope transform (e.g. an OpenAlex `{meta, results}` page) must
384
+ * land as a NEW field (`transformPage?: boolean`) — never by changing
385
+ * what `transform` receives on paginate ops, which would be a
386
+ * behavior-level re-meaning no published guide could take back cheaply.
195
387
  */
196
388
  transform?: boolean;
197
389
  /** Op-level responseShape override. */
198
390
  parse?: ResponseShape;
391
+ /**
392
+ * JSON path to a present-only-on-error envelope element inside a 200 body.
393
+ * After `parseResponse`, a resolution that is anything other than
394
+ * `undefined` fails the call with a structured HelperError — presence is
395
+ * the signal (`!== undefined`, not truthiness: `null`/`""`/`0`/`false`
396
+ * all count as present). Declared-absent is the API's not-an-error signal.
397
+ * Parse-time guards: non-empty string, tokenizeable, non-empty
398
+ * tokenization, and an effective response shape that is not `text`.
399
+ */
400
+ errorPath?: string;
199
401
  /** Op-level pagination override (for `via: paginate`). */
200
402
  pagination?: PaginationConfig;
201
403
  /** Param names → target date format. Applied in buildQueryParams before serialization. */
@@ -224,9 +426,10 @@ export interface Operation {
224
426
  export interface ApiGuide extends Guide {
225
427
  kind: "api";
226
428
  /**
227
- * Recipe schema version (attribution, not enforcement — see
228
- * GUIDE_SCHEMA_VERSION). Parsed from frontmatter `schemaVersion:`; absent
229
- * stays `undefined` (semantic default 0). Never gates/warns/alters parse.
429
+ * Recipe schema version (enforced by the hard gate — see
430
+ * GUIDE_SCHEMA_VERSION). Parsed from frontmatter `schemaVersion:`; an
431
+ * absent/malformed value parses as the floor 0, which the gate refuses
432
+ * as stale.
230
433
  */
231
434
  schemaVersion?: number;
232
435
  /** Execution root: scheme + host + base path; version prefix lives here. */
@@ -300,5 +503,19 @@ export interface LoadedApiGuides {
300
503
  malformed: MalformedGuide[];
301
504
  }
302
505
 
506
+ /**
507
+ * Warning channel for load-time diagnostics — `ctx.ui.notify` when the
508
+ * caller has a UI context, else `console.warn`. The loader defaults to
509
+ * `console.warn` so pure call sites (and tests) stay unchanged; the
510
+ * `session_start` handler passes `ctx.ui.notify` so the schema-gate banner
511
+ * and per-guide warnings render through the Text component (wraps long
512
+ * lines, honors newlines) instead of raw stderr (truncates + merges with
513
+ * the status bar).
514
+ */
515
+ export type NotifyFn = (
516
+ message: string,
517
+ type?: "info" | "warning" | "error",
518
+ ) => void;
519
+
303
520
  // `Guide` (the projection-slice base type) is imported above and extended by
304
521
  // `ApiGuide`; consumers import it directly from ./guide-loader.js when needed.