pi-lean-host 0.4.0 → 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.
@@ -37,16 +37,17 @@ import {
37
37
  rmSync,
38
38
  writeFileSync,
39
39
  } from "node:fs";
40
- import { tmpdir } from "node:os";
41
- import { basename, join, sep } from "node:path";
40
+ import { basename, join } from "node:path";
42
41
  import { pathToFileURL } from "node:url";
43
42
  import {
44
43
  parseApiGuide,
45
44
  stampFrontmatterField,
45
+ } from "../core/parse-api-guide.js";
46
+ import {
46
47
  formatGuideListings,
47
48
  selectGuideByShortName,
48
49
  shortNameErrorText,
49
- } from "../core/parse-api-guide.js";
50
+ } from "../core/guide-catalog.js";
50
51
  import {
51
52
  GUIDE_SCHEMA_VERSION,
52
53
  type ApiGuide,
@@ -58,31 +59,10 @@ import {
58
59
  findGuidesByDomain,
59
60
  } from "../core/guide-store.js";
60
61
  import { assertSafeDomain, slug } from "../core/path-template.js";
62
+ import { stagingDirFor, isUnderStagingRoot } from "../core/staging.js";
61
63
 
62
- // ═══════════════════════════════════════════════════════════════════
63
- // Staged working copy (/tmp) — the draft the agent edits between saves
64
- // ═══════════════════════════════════════════════════════════════════
65
-
66
- let _stagingRoot = join(tmpdir(), "pi-lean-host");
67
-
68
- /** Test override — mirrors `setUserGuidesDir` so tests keep drafts out of
69
- * the real /tmp root. */
70
- export function setStagingRoot(dir: string): void {
71
- _stagingRoot = dir;
72
- }
73
-
74
- /** Deterministic staged dir: `<root>/<key>/`. The key is the requested
75
- * `domain` for templates (placeholder shortName) and `slug(shortName)` for
76
- * fetched recipes (which is the on-disk dirName). */
77
- function stagingDirFor(key: string): string {
78
- return join(_stagingRoot, key);
79
- }
80
-
81
- /** True when `p` is a staged dir under the staging root (the root itself
82
- * excluded — save must never try to rename the whole root). */
83
- function isUnderStagingRoot(p: string): boolean {
84
- return p !== _stagingRoot && p.startsWith(`${_stagingRoot}${sep}`);
85
- }
64
+ // Staged working copy (/tmp) — the draft the agent edits between saves.
65
+ // Root + helpers live in core/staging.js (shared with api-scaffold).
86
66
 
87
67
  /** Write the working copy (template or fetched raw recipe) to the staged
88
68
  * dir. Returns the staged *dir* path (multi-file — siblings write to the
@@ -113,14 +93,25 @@ const SIBLING_NAMES = [
113
93
  const DESCRIPTION_MAX = 200;
114
94
 
115
95
  /** Commented static-key auth block — the issue-#5 auth-wiring teaching,
116
- * API-agnostic, kept after the worked example retired. */
96
+ * API-agnostic, kept after the worked example retired. Nested SecretRef
97
+ * shape (v1): each ref is self-contained (secret + optional prefix/optional). */
117
98
  const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in the secrets store (/api secrets), never in the recipe:
118
99
  # kind: static-key
119
- # requires: [<secret-name>]
120
100
  # secretRefs:
121
- # Authorization: <secret-name> # header name → secret name (must match the name provisioned via /api secrets)
122
- # headerPrefixes:
123
- # Authorization: "Bearer "`;
101
+ # Authorization: # header name
102
+ # secret: <secret-name> # store name (must match /api secrets)
103
+ # prefix: "Bearer " # optional — prepended at fetch time
104
+ # optional: false # optional refs don't fail closed when absent`;
105
+
106
+ /** Commented oauth2 authorization_code block — mirrors the manual's worked
107
+ * example so the fresh template teaches the interactive-grant shape without
108
+ * the agent having to grep a sibling guide for the field names. */
109
+ const OAUTH2_AC_BLOCK = ` # OAuth2 API? Use kind: oauth2 — credentials are store names (/api secrets), minting via /api oauth <domain>:
110
+ # grant: authorization_code # or client_credentials (server-to-server: adds clientSecret, drops authorizeUrl)
111
+ # tokenUrl: https://…/oauth/token
112
+ # authorizeUrl: https://…/oauth/authorize # REQUIRED for authorization_code
113
+ # clientId: { secret: client_id }
114
+ # scopes: [read]`;
124
115
 
125
116
  /** Placeholder starter template — only `domains:` is real (the requested
126
117
  * domain). Every other field is a placeholder the agent fills (op blocks
@@ -131,6 +122,7 @@ function placeholderSkeleton(domain: string): string {
131
122
  return `---
132
123
  kind: api
133
124
  domains: [${domain}]
125
+ schemaVersion: ${GUIDE_SCHEMA_VERSION}
134
126
  organization: <org> # optional — org identity across guides (registrable domain)
135
127
  description: <one-line summary> # optional — one-line summary; aids disambiguation
136
128
  icon: <emoji>
@@ -143,6 +135,7 @@ gatherAllMax: 1000 # omitted → 1000
143
135
  auth:
144
136
  kind: none
145
137
  ${STATIC_KEY_BLOCK}
138
+ ${OAUTH2_AC_BLOCK}
146
139
 
147
140
  pagination:
148
141
  style: offset-limit
@@ -150,6 +143,14 @@ pagination:
150
143
  pageSizeParam: limit
151
144
  pageSize: 50
152
145
  itemsPath: results
146
+ # Path fields are dot-delimited. If the API's key itself contains a dot
147
+ # (OData's '@odata.nextLink' / '@iot.count' family), quote it as an atomic
148
+ # key or the dot splits the path and pagination silently misses:
149
+ # nextLinkPath: "['@odata.nextLink']" # single or double quotes
150
+ # For a cursor walk whose continuation value is an item field (derived-id
151
+ # cursor), declare the sort params on the op too — the executor serializes
152
+ # ONLY declared params, and an undeclared sort lets the API default apply,
153
+ # turning the walk into a moving feed that re-reads rows.
153
154
 
154
155
  responseShape:
155
156
  format: json
@@ -166,6 +167,8 @@ responseShape:
166
167
  # params:
167
168
  # id:
168
169
  # description: <what id selects>
170
+ # # listStyle: comma # array values serialize as comma | repeat | bracket — omit for single-valued
171
+ # # unknown params keys are a parse error (typo tripwire)
169
172
  ---
170
173
 
171
174
  # Optional agent-instruction prose goes AFTER the closing --- and is surfaced
@@ -176,15 +179,43 @@ responseShape:
176
179
 
177
180
  /** Save-summary auth line — names the header→secret mapping (names only,
178
181
  * never values: values live in the store). e.g.
179
- * `static-key · Authorization ← secret apiKey (Bearer )`. */
182
+ * `static-key · Authorization ← secret apiKey (Bearer )` or
183
+ * `oauth2 · grant client_credentials · clientId ← secret client_id`. */
180
184
  function authSummary(auth: AuthConfig): string {
181
185
  const parts: string[] = [];
182
- for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
183
- const prefix = auth.headerPrefixes?.[header];
184
- parts.push(`${header} ← secret ${secretName}${prefix ? ` (${prefix})` : ""}`);
185
- }
186
- for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
187
- parts.push(`?${param} ← secret ${secretName}`);
186
+ switch (auth.kind) {
187
+ case "static-key":
188
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
189
+ parts.push(
190
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
191
+ );
192
+ }
193
+ for (const [param, ref] of Object.entries(auth.secretQueryRefs ?? {})) {
194
+ parts.push(`?${param} ← secret ${ref.secret}`);
195
+ }
196
+ for (const [token, ref] of Object.entries(auth.secretPathRefs ?? {})) {
197
+ parts.push(`{${token}} ← secret ${ref.secret}`);
198
+ }
199
+ break;
200
+ case "oauth2":
201
+ parts.push(
202
+ `grant ${auth.grant} · clientId ← secret ${auth.clientId.secret}` +
203
+ (auth.clientSecret
204
+ ? ` · clientSecret ← secret ${auth.clientSecret.secret}`
205
+ : ""),
206
+ );
207
+ for (const [header, ref] of Object.entries(auth.secretRefs ?? {})) {
208
+ parts.push(
209
+ `${header} ← secret ${ref.secret}${ref.prefix ? ` (${ref.prefix})` : ""}`,
210
+ );
211
+ }
212
+ break;
213
+ case "none":
214
+ break;
215
+ default: {
216
+ const _exhaustive: never = auth;
217
+ throw new Error(`Unhandled auth kind: ${_exhaustive}`);
218
+ }
188
219
  }
189
220
  return parts.length === 0
190
221
  ? `Auth: ${auth.kind}`
@@ -195,6 +226,31 @@ function authSummary(auth: AuthConfig): string {
195
226
  // Authoring manual + templates
196
227
  // ═══════════════════════════════════════════════════════════════════
197
228
 
229
+ /** Worked oauth2 examples shown in the authoring manual — exported so the
230
+ * parse test proves they parse as-is (the teaching can't rot silently).
231
+ * Field semantics mirror validateOAuth2Auth's grant invariants. */
232
+ export const OAUTH2_CC_EXAMPLE = ` # client_credentials — server-to-server, no browser:
233
+ auth:
234
+ kind: oauth2
235
+ grant: client_credentials
236
+ tokenUrl: https://api.example.com/oauth/token
237
+ clientId: { secret: client_id }
238
+ clientSecret: { secret: client_secret } # parser-required for this grant
239
+ # scopes: [read]
240
+ # secretRefs: # extra headers beside the Bearer token
241
+ # Client-Id:
242
+ # secret: client_id`;
243
+
244
+ export const OAUTH2_AC_EXAMPLE = ` # authorization_code — interactive; human consents in their browser and pastes the redirect (/api oauth):
245
+ auth:
246
+ kind: oauth2
247
+ grant: authorization_code
248
+ tokenUrl: https://api.example.com/oauth/token
249
+ authorizeUrl: https://example.com/oauth/authorize # REQUIRED for this grant; rejected for client_credentials
250
+ clientId: { secret: client_id }
251
+ # clientSecret: { secret: client_secret } # confidential clients only; PKCE public clients omit it
252
+ scopes: [read]`;
253
+
198
254
  /** The field reference + defaults + semantics manual. Travels with the
199
255
  * pull-to-/tmp action — prepended to every staged draft (template or
200
256
  * fetched recipe) so the author sees it at the moment of authoring. */
@@ -211,7 +267,7 @@ const AUTHORING_MANUAL = [
211
267
  ` \`apiHost\` — base URL. Version in apiHost XOR in each path — never both (see Key defaults)`,
212
268
  ` \`operations\` — a LIST of operation mappings — at least one entry`,
213
269
  ` \`operations[].name\` — unique operation name`,
214
- ` \`operations[].via\` — "restGet" or "paginate"`,
270
+ ` \`operations[].via\` — "restGet" or "paginate" — both issue GETs; the plugin is read-only by design (writes have no schema representation)`,
215
271
  ` \`operations[].path\` — path starting with /`,
216
272
  "",
217
273
  "## Key defaults",
@@ -231,25 +287,41 @@ const AUTHORING_MANUAL = [
231
287
  ` \`dateParams\` — normalize date QUERY params before sending: map name → iso8601 | yyyymmdd | yyyy-mm-dd (path tokens are documented via params.<token>.description; core dateParams does not reach path tokens)`,
232
288
  ` \`helper\` — true → call this domain's local helper.ts for this op`,
233
289
  ` \`transform\` — true → run the helper.ts \`transform\` export on the parsed response`,
290
+ ` \`errorPath\` — JSON path to a present-only-on-error envelope element in a 200 body (e.g. \`OAI-PMH.error\`); anything other than \`undefined\` there (including null/""/0/false) fails the call as an error — declare a path that exists ONLY on error (Flickr \`message\`, World Bank \`0.message\`); root paths (\`$\`, \`.\`), malformed paths, and ops whose effective format is \`text\` are parse errors`,
234
291
  ` \`params.<token>.description\` — docs-only description for a {token} path param (format, e.g. 'yyyy-mm-dd'); never sent as a query param, shown in api-guide`,
235
292
  ` \`params.<name>.required\` — true → query param must be supplied (verify skips the op if missing; api-fetch errors before the request)`,
236
- ` \`params.<name>.default\` — value (any YAML scalar: string, number, boolean) used when the caller omits the param (verify runs the op with it; a \`required\`+\`default\` op is always verifiable without a verify.json sidecar)`,
293
+ ` \`params.<name>.default\` — value (any YAML scalar: string, number, boolean) used when the caller omits the param (verify runs the op with it; a \`required\`+\`default\` op is always verifiable without a verify.json sidecar; an array default additionally requires \`listStyle\` and must be non-empty)`,
294
+ ` \`params.<name>.listStyle\` — comma | repeat | bracket — how an array value serializes on the query string (comma → id=a,b; repeat → id=a&id=b; bracket → id[]=a); scalars ignore the field`,
237
295
  ` \`requiresAnyOf\` — [param, ...] — at least one of these params must be supplied (one group per op). Use it when the API identifies a resource by exactly one of several interchangeable params and rejects them together (id XOR symbol XOR slug — the "exclusive peers" 400). Members may not be \`required: true\` NOR carry a \`default\` (both parser-enforced) — a default would always fire alongside a caller-supplied sibling and cause the conflict. Use \`required: true\` for a single-param constraint; \`requiresAnyOf\` is for two or more interchangeable params`,
238
296
  ` \`passthrough\` — true → forward undeclared caller params onto the query string`,
239
297
  ` \`parse\` — op-level responseShape override (format/charset) for this operation`,
240
298
  "",
241
299
  "## Auth",
242
300
  ` \`kind: static-key\` — keyed-header auth mode (values live in the secrets store, never in the recipe):`,
243
- ` \`requires\` = fail-closed if unprovisioned; \`optional\` = proceeds unauthenticated if absent. Both are names only — values live in the secrets store, and each name must match exactly the one passed to /api secrets. Each \`requires\` / \`optional\` name must also appear as a secretRefs/secretQueryRefs value (parser-enforced).`,
301
+ ` \`kind: oauth2\` — OAuth2 (client_credentials / authorization_code); token minting via /api oauth <domain>. ALL oauth2 credentials are store names, never literals — a shippable guide must not bake in one app's registration:`,
302
+ ` \`clientId\` — { secret: <store name> } — the client id's secrets-store name (e.g. clientId: { secret: client_id })`,
303
+ ` \`clientSecret\` — { secret: <store name> } — parser-required for client_credentials; absent for authorization_code (PKCE public clients)`,
304
+ ` \`secretRefs\` — { <request header>: { secret: <store name>, prefix?, optional? } } — headers merged alongside the Bearer token (e.g. Twitch's Client-Id)`,
305
+ ` \`scopes\` — optional static scope list (e.g. scopes: [read])`,
306
+ ` \`tokenEndpointAuthMethod\` — client_secret_post (default) | client_secret_basic | none — how the client authenticates at the token endpoint; none = PKCE public client (no clientSecret)`,
307
+ ` \`paramStyle\` — bearer-header (default) | query (sends ?access_token=…)`,
308
+ ` \`revokeUrl\` — optional revocation endpoint`,
309
+ "",
310
+ " Worked examples — copy one and edit; store names must match /api secrets <domain>:",
311
+ OAUTH2_CC_EXAMPLE,
312
+ "",
313
+ OAUTH2_AC_EXAMPLE,
314
+ "",
244
315
  " static-key (keyed APIs):",
245
- ` \`secretRefs\` — { <header name>: <secret name> } ← header → secret direction`,
246
- ` \`headerPrefixes\` — { <header>: "Bearer " } ← scheme prefix; store holds the raw token`,
247
- ` \`requires\` — [<secret-name>] ← fail-closed if unprovisioned (literal name, must match the store)`,
316
+ ` \`secretRefs\` — { <header name>: { secret: <store name>, prefix?, optional? } } ← self-contained ref`,
317
+ ` \`secretQueryRefs\` — { <query param>: { secret: <store name>, optional? } } ← query-param injection`,
318
+ ` \`secretPathRefs\` — { <path token>: { secret: <store name> } } ← path-token injection (/bot{token}/getMe); required-only: no prefix/optional`,
319
+ ` \`optional: true\` on a ref → proceeds unauthenticated if absent; default (required) → fail-closed. Values live in the secrets store; the store name must match /api secrets exactly.`,
248
320
  "",
249
321
  "## Executor semantics",
250
322
  " Pagination:",
251
323
  ` \`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`,
252
- ` The page-size param is a real knob: caller value → op param \`default\` → \`pagination.pageSize\` → 50`,
324
+ ` Page-size resolution (offset-limit/page): caller value → op param \`default\` → \`pagination.pageSize\` → 50. Cursor: caller value → op param \`default\` → \`pagination.pageSize\` → omit (server default applies)`,
253
325
  "",
254
326
  "## Guide prose (agent instructions)",
255
327
  " After the closing `---`, optional plaintext guidance for the reading agent —",
@@ -523,7 +595,17 @@ export const apiLearnTool = defineTool({
523
595
  };
524
596
  }
525
597
 
526
- const parsed = parseApiGuide(recipe, { filename: domain });
598
+ // Stamp schemaVersion before validation: under the schemaVersion hard
599
+ // gate a recipe without a current stamp would fail validation before
600
+ // the stamp could land. Line-level frontmatter edit (comments + key
601
+ // order preserved); the write below persists the stamped text only on
602
+ // validation success.
603
+ const stamped = stampFrontmatterField(
604
+ recipe,
605
+ "schemaVersion",
606
+ String(GUIDE_SCHEMA_VERSION),
607
+ );
608
+ const parsed = parseApiGuide(stamped, { filename: domain });
527
609
  if (!parsed.ok) {
528
610
  const err = parsed.error;
529
611
  const lines: string[] = [
@@ -598,7 +680,7 @@ export const apiLearnTool = defineTool({
598
680
  if (divergent && existsSync(join(canonicalStaged, "guide.md"))) {
599
681
  const existing = parseApiGuide(
600
682
  readFileSync(join(canonicalStaged, "guide.md"), "utf-8"),
601
- { filename: slugged },
683
+ { file: join(canonicalStaged, "guide.md"), filename: slugged },
602
684
  );
603
685
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
604
686
  if (existingShort !== parsed.guide.shortName) {
@@ -673,6 +755,7 @@ export const apiLearnTool = defineTool({
673
755
  const filepath = join(domainDir, "guide.md");
674
756
  if (existsSync(filepath)) {
675
757
  const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
758
+ file: filepath,
676
759
  filename: slugged,
677
760
  });
678
761
  const existingShort = existing.ok ? existing.guide.shortName : undefined;
@@ -847,15 +930,6 @@ export const apiLearnTool = defineTool({
847
930
 
848
931
  // ── Write guide + mirror siblings ───────────────────────
849
932
 
850
- // Stamp schemaVersion on save — each guide records the schema vintage
851
- // it was authored against (the per-guide vintage that stale detection
852
- // compares against). Line-level frontmatter edit; comments + key order
853
- // preserved (no YAML round-trip).
854
- const stamped = stampFrontmatterField(
855
- recipe,
856
- "schemaVersion",
857
- String(GUIDE_SCHEMA_VERSION),
858
- );
859
933
  writeFileSync(filepath, stamped, "utf-8");
860
934
 
861
935
  // Mirror the staged dir: present siblings overwrite the guides-dir