pi-lean-host 0.3.0 → 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 +13 -17
- package/core/parse-api-guide.ts +80 -3
- package/core/transport.ts +1 -1
- package/package.json +1 -1
- package/tools/api-fetch.ts +1 -1
- package/tools/api-guide.ts +1 -1
- package/tools/api-learn.ts +66 -81
- package/tools/api-probe.ts +67 -178
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
> SearXNG search, install
|
|
21
21
|
> [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
|
|
22
22
|
|
|
23
|
-
> ⚠️ **Early release (0.3.
|
|
23
|
+
> ⚠️ **Early release (0.3.1).** The API tools here work today, but this is a
|
|
24
24
|
> development preview. The recipe schema, tool surfaces, and guide format are
|
|
25
25
|
> still settling as we test more APIs to finalize the shape — **future
|
|
26
26
|
> compatibility is not guaranteed** until the package reaches lockstep with
|
|
@@ -238,14 +238,11 @@ one) — turning a failed execute into a discovery moment in one round-trip.
|
|
|
238
238
|
### 3. `api-learn` — Author / Update a Guide (local write)
|
|
239
239
|
|
|
240
240
|
```text
|
|
241
|
-
api-learn → field reference + pointer to the starter template
|
|
242
241
|
api-learn domain="arxiv.org" new=true → stages a fresh placeholder template to /tmp/pi-lean-host/arxiv.org/guide.md
|
|
243
242
|
api-learn domain="arxiv.org" → fetches an existing guide's raw recipe into the staged file
|
|
244
243
|
api-learn domain="arxiv.org" recipeFile="/tmp/pi-lean-host/arxiv.org/guide.md" → validates + writes the guide to disk
|
|
245
244
|
```
|
|
246
245
|
|
|
247
|
-
- No parameters → a concise field reference plus a pointer to
|
|
248
|
-
`{domain, new: true}` for a domain-specific starter template.
|
|
249
246
|
- `{domain, new: true}` → a fresh starter template with `domains: [<domain>]`
|
|
250
247
|
**staged to `/tmp/pi-lean-host/<domain>/guide.md`**. Only `domains` is real;
|
|
251
248
|
the other fields are `<placeholder>` values that **fail closed**, so a
|
|
@@ -254,12 +251,18 @@ api-learn domain="arxiv.org" recipeFile="/tmp/pi-lean-host/arxiv.org/guide.md"
|
|
|
254
251
|
guide into the staged file (surfaces `dirName` to prevent sibling-clobber
|
|
255
252
|
in multi-recipe domains); a disambiguation menu if several guides claim the
|
|
256
253
|
domain.
|
|
254
|
+
- Every staged pull (template or fetched recipe) is prepended with the
|
|
255
|
+
authoring manual — the field reference + defaults + semantics the author
|
|
256
|
+
needs at the moment of authoring.
|
|
257
257
|
- `{domain, recipeFile}` → reads the staged draft, validates it **before**
|
|
258
258
|
touching disk, then writes to
|
|
259
|
-
`~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
259
|
+
`~/.pi/agent/pi-lean-host/api-guides/<domain>/guide.md`. A fail-closed
|
|
260
|
+
guard refuses to overwrite an existing `guide.md` whose `shortName`
|
|
261
|
+
differs from the incoming guide (prevents clobbering a sibling in a
|
|
262
|
+
multi-recipe domain); a same-`shortName` save is a legitimate update.
|
|
263
|
+
On a structural error it names the field, the expected shape, and what
|
|
264
|
+
was found — the file on disk is left untouched (no half-written guide).
|
|
265
|
+
Requires `/api learn`.
|
|
263
266
|
|
|
264
267
|
The working copy is staged at `/tmp/pi-lean-host/<domain>/guide.md` (`/tmp`
|
|
265
268
|
self-cleans, so drafts don't accumulate) — fetch/template calls write the
|
|
@@ -283,13 +286,6 @@ fetched (disable with `walkVersions=false`). A stale version that still
|
|
|
283
286
|
returns 200 is not detected as old — read the provider's docs to supply the
|
|
284
287
|
newest version up front.
|
|
285
288
|
|
|
286
|
-
Pass `scaffold: true` to emit a **full recipe skeleton** (frontmatter +
|
|
287
|
-
`auth:` translated from the inline auth block + a draft op block) instead of
|
|
288
|
-
just the op block — opt-in, and auto-degrades by guide count (0 guides →
|
|
289
|
-
skeleton, 1/N → op block + a merge note). The scaffolded `schemaVersion`
|
|
290
|
-
matches what `api-learn` stamps on save, so the guide is detection-ready the
|
|
291
|
-
moment it's saved.
|
|
292
|
-
|
|
293
289
|
`api-probe` only **suggests** — it never writes the guide. The operation must
|
|
294
290
|
still be traceable to your plan source (the API docs or a working curl
|
|
295
291
|
example); this tool surfaces evidence, not authority. Requires `/api learn`.
|
|
@@ -313,8 +309,8 @@ in the frontmatter.
|
|
|
313
309
|
|
|
314
310
|
The fastest way to a first guide is to let the tools draft it:
|
|
315
311
|
`api-learn({domain, new: true})` returns a fail-closed starter template,
|
|
316
|
-
|
|
317
|
-
|
|
312
|
+
`api-probe` drafts real op blocks from a live endpoint — fill the
|
|
313
|
+
placeholders, then save with `api-learn`. For
|
|
318
314
|
**complete worked recipes** (real endpoints, `verified:` provenance,
|
|
319
315
|
auth-in-place, helper examples), see the [Caritas](#bundled-reference-recipes)
|
|
320
316
|
recipe library and copy a domain folder that matches your target.
|
package/core/parse-api-guide.ts
CHANGED
|
@@ -98,7 +98,7 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
|
98
98
|
"tokenBag",
|
|
99
99
|
]);
|
|
100
100
|
|
|
101
|
-
// Strict auth schema
|
|
101
|
+
// Strict auth schema: the only keys validateAuth reads. Any other key
|
|
102
102
|
// under `auth` is rejected at parse — the parser used to silently drop
|
|
103
103
|
// unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
|
|
104
104
|
// guide the executor then silently couldn't honor.
|
|
@@ -165,6 +165,58 @@ function snippetFor(frontmatter: string, key: string): string | undefined {
|
|
|
165
165
|
return out.join("\n");
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
169
|
+
// Reserved-char plain-scalar pre-scan
|
|
170
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Chars that make a plain scalar invalid as a value — yaml's
|
|
174
|
+
* "Plain value cannot start with reserved character" error class. Backtick is
|
|
175
|
+
* the observed footgun (markdown-style `` `field` `` refs pasted into
|
|
176
|
+
* descriptions); `%`/`@`/`,` are the same error class and never legitimate at
|
|
177
|
+
* the start of a value. `|`/`>` (block scalars), `[`/`{` (flow), quotes, and
|
|
178
|
+
* `#` (comments) are all legitimate starts and deliberately NOT flagged.
|
|
179
|
+
*/
|
|
180
|
+
const RESERVED_PLAIN_START = new Set(["`", "%", "@", ","]);
|
|
181
|
+
|
|
182
|
+
interface ReservedPlainHit {
|
|
183
|
+
line: number;
|
|
184
|
+
col: number;
|
|
185
|
+
char: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Best-effort one-pass scan for `key: <value>` lines whose plain-scalar value
|
|
190
|
+
* starts with a reserved YAML character. yamlParse throws on the FIRST such
|
|
191
|
+
* value and stops, so a multi-backtick frontmatter needs one save/validate
|
|
192
|
+
* cycle per offender — this lists them all at once. Line/column are reported
|
|
193
|
+
* relative to the frontmatter block (matching yamlParse) and count from the
|
|
194
|
+
* raw line, indentation included. Advisory: only fires on the reserved-char
|
|
195
|
+
* class, which the parser would reject anyway.
|
|
196
|
+
*/
|
|
197
|
+
function scanReservedPlainStarts(fm: string): ReservedPlainHit[] {
|
|
198
|
+
const hits: ReservedPlainHit[] = [];
|
|
199
|
+
const lines = fm.split("\n");
|
|
200
|
+
for (let i = 0; i < lines.length; i++) {
|
|
201
|
+
const raw = lines[i] ?? "";
|
|
202
|
+
const line = raw.trimStart();
|
|
203
|
+
// Skip blank, comment, and list-item lines (op headers like
|
|
204
|
+
// `- name: …` — the backtick footgun lives in `description:`-style
|
|
205
|
+
// value lines, which are never `- `-prefixed).
|
|
206
|
+
if (line === "" || line.startsWith("#") || line.startsWith("- ")) continue;
|
|
207
|
+
const m = /^[^:#]+: /.exec(line);
|
|
208
|
+
if (!m) continue;
|
|
209
|
+
const ch = line[m[0].length];
|
|
210
|
+
if (ch === undefined || !RESERVED_PLAIN_START.has(ch)) continue;
|
|
211
|
+
hits.push({
|
|
212
|
+
line: i + 1,
|
|
213
|
+
col: raw.length - line.length + m[0].length + 1,
|
|
214
|
+
char: ch,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
return hits;
|
|
218
|
+
}
|
|
219
|
+
|
|
168
220
|
// ═══════════════════════════════════════════════════════════════════
|
|
169
221
|
// Field validators
|
|
170
222
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -590,7 +642,7 @@ function validateAuth(
|
|
|
590
642
|
fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
|
|
591
643
|
});
|
|
592
644
|
}
|
|
593
|
-
// Strict auth schema — reject unknown keys
|
|
645
|
+
// Strict auth schema — reject unknown keys. The parser used to
|
|
594
646
|
// silently drop unknown keys (a wrong-but-plausible shape like
|
|
595
647
|
// `name`/`secret` saved a guide the executor then silently couldn't
|
|
596
648
|
// honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
|
|
@@ -1285,6 +1337,29 @@ export function parseApiGuide(
|
|
|
1285
1337
|
);
|
|
1286
1338
|
}
|
|
1287
1339
|
|
|
1340
|
+
// One-pass reserved-char pre-scan: yamlParse throws on the FIRST
|
|
1341
|
+
// backtick-leading plain scalar and stops, so a multi-offender
|
|
1342
|
+
// frontmatter costs one save/validate cycle per line. Scan first and
|
|
1343
|
+
// list them all at once. Advisory only — it fires solely on the
|
|
1344
|
+
// "Plain value cannot start with reserved character" class, which
|
|
1345
|
+
// yamlParse would reject anyway — the parser stays the source of truth.
|
|
1346
|
+
const reservedHits = scanReservedPlainStarts(fm);
|
|
1347
|
+
if (reservedHits.length > 0) {
|
|
1348
|
+
const where = reservedHits
|
|
1349
|
+
.map((h) => `line ${h.line}, column ${h.col}: ${h.char}`)
|
|
1350
|
+
.join(" ; ");
|
|
1351
|
+
return fail(
|
|
1352
|
+
file,
|
|
1353
|
+
"frontmatter",
|
|
1354
|
+
"valid YAML",
|
|
1355
|
+
`plain scalar value(s) start with a reserved YAML character — ${where}`,
|
|
1356
|
+
{
|
|
1357
|
+
snippet: fm,
|
|
1358
|
+
fix: 'Quote the value (description: "`the id`") or remove the leading backtick — a plain scalar cannot start with a reserved YAML character.',
|
|
1359
|
+
},
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1288
1363
|
let meta: unknown;
|
|
1289
1364
|
try {
|
|
1290
1365
|
meta = yamlParse(fm);
|
|
@@ -1819,7 +1894,9 @@ export function formatApiGuideCatalog(
|
|
|
1819
1894
|
);
|
|
1820
1895
|
}
|
|
1821
1896
|
if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
|
|
1822
|
-
lines.push(
|
|
1897
|
+
lines.push(
|
|
1898
|
+
" (no guides — call api-learn({domain, recipeFile}) to author one)",
|
|
1899
|
+
);
|
|
1823
1900
|
}
|
|
1824
1901
|
lines.push("");
|
|
1825
1902
|
lines.push(
|
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.3.
|
|
436
|
+
"pi-lean-host/0.3.1 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
437
437
|
}
|
|
438
438
|
|
|
439
439
|
if (!opts?.fresh && !hasAuth) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-lean-host",
|
|
3
|
-
"version": "0.3.
|
|
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",
|
package/tools/api-fetch.ts
CHANGED
|
@@ -62,7 +62,7 @@ export const apiFetchTool = defineTool({
|
|
|
62
62
|
description:
|
|
63
63
|
"Fetch structured data from a REST API using a recipe-based guide. " +
|
|
64
64
|
"Requires an API guide for the target domain. " +
|
|
65
|
-
"Call api-guide({domain}) to see available operations, or api-learn({domain,
|
|
65
|
+
"Call api-guide({domain}) to see available operations, or api-learn({domain, recipeFile}) to author a new guide.",
|
|
66
66
|
|
|
67
67
|
parameters: Type.Object({
|
|
68
68
|
domain: Type.String({
|
package/tools/api-guide.ts
CHANGED
|
@@ -77,7 +77,7 @@ export const apiGuideTool = defineTool({
|
|
|
77
77
|
text:
|
|
78
78
|
`No API guide for '${domain}'.` +
|
|
79
79
|
(known.length > 0 ? ` Known guides: ${known.join(", ")}.` : "") +
|
|
80
|
-
"\n\nCall api-guide with no params to list all guides, or api-learn({domain,
|
|
80
|
+
"\n\nCall api-guide with no params to list all guides, or api-learn({domain, recipeFile}) to author one.",
|
|
81
81
|
},
|
|
82
82
|
],
|
|
83
83
|
details: {},
|
package/tools/api-learn.ts
CHANGED
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
* api-learn tool definition.
|
|
3
3
|
*
|
|
4
4
|
* Authoring entry points:
|
|
5
|
-
* - No params → authoring manual (field reference + defaults + semantics)
|
|
6
|
-
* with a pointer to `{domain, new: true}` for a domain-specific starter.
|
|
7
5
|
* - `{domain, new: true}` → fresh template with `domains: [<domain>]`
|
|
8
6
|
* pre-filled (regardless of existing guides).
|
|
9
7
|
* - `{domain}` (no recipeFile) → fetch the current raw recipe of an existing
|
|
@@ -27,7 +25,7 @@ import {
|
|
|
27
25
|
import { Type } from "@earendil-works/pi-ai";
|
|
28
26
|
import { Text } from "@earendil-works/pi-tui";
|
|
29
27
|
import { appendFooter, contentText } from "./utils.js";
|
|
30
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
31
29
|
import { tmpdir } from "node:os";
|
|
32
30
|
import { join } from "node:path";
|
|
33
31
|
import {
|
|
@@ -95,7 +93,7 @@ const STATIC_KEY_BLOCK = ` # Keyed API? Use kind: static-key — values live in
|
|
|
95
93
|
|
|
96
94
|
/** Placeholder starter template — only `domains:` is real (the requested
|
|
97
95
|
* domain). Every other field is a placeholder the agent fills (op blocks
|
|
98
|
-
* sourced from api-probe({
|
|
96
|
+
* sourced from api-probe({apiHost, path})). Fails closed: an unsaved,
|
|
99
97
|
* as-is template is rejected by the parser because `apiHost: <base url>`
|
|
100
98
|
* is not a valid URL — no wrong-API guide can be saved silently. */
|
|
101
99
|
function placeholderSkeleton(domain: string): string {
|
|
@@ -127,8 +125,7 @@ responseShape:
|
|
|
127
125
|
charset: utf-8
|
|
128
126
|
|
|
129
127
|
# Add one operation per endpoint here — source the block from
|
|
130
|
-
# api-probe({apiHost, path
|
|
131
|
-
# values):
|
|
128
|
+
# api-probe({apiHost, path}) (it drafts real ops with real values):
|
|
132
129
|
# operations:
|
|
133
130
|
# - name: <op>
|
|
134
131
|
# via: restGet
|
|
@@ -169,15 +166,15 @@ function authSummary(auth: AuthConfig): string {
|
|
|
169
166
|
// Authoring manual + templates
|
|
170
167
|
// ═══════════════════════════════════════════════════════════════════
|
|
171
168
|
|
|
172
|
-
/**
|
|
173
|
-
*
|
|
174
|
-
* the
|
|
169
|
+
/** The field reference + defaults + semantics manual. Travels with the
|
|
170
|
+
* pull-to-/tmp action — prepended to every staged draft (template or
|
|
171
|
+
* fetched recipe) so the author sees it at the moment of authoring. */
|
|
175
172
|
const AUTHORING_MANUAL = [
|
|
176
173
|
"# API guide authoring manual",
|
|
177
174
|
"",
|
|
178
175
|
"💡 Start a new guide: call api-learn({domain: '<domain>', new: true}) — it returns a ",
|
|
179
176
|
" template with `domains` pre-filled. Discover the API's shape first with ",
|
|
180
|
-
" api-probe({apiHost, path
|
|
177
|
+
" api-probe({apiHost, path}) — it drafts a YAML operation block ",
|
|
181
178
|
" to paste into the template.",
|
|
182
179
|
"",
|
|
183
180
|
"## Required fields",
|
|
@@ -233,37 +230,6 @@ const AUTHORING_MANUAL = [
|
|
|
233
230
|
"Call api-learn({domain: '<domain>', recipeFile: '<staged file path>'}) to save the guide, then api-fetch({domain, operation: '...'}) to verify.",
|
|
234
231
|
].join("\n");
|
|
235
232
|
|
|
236
|
-
/** Manual section that governs a failing parser field — the validation-error
|
|
237
|
-
* closing line routes the author to the manual (gap 2). Ordered rules, first
|
|
238
|
-
* match wins; undefined → generic manual pointer. Names must match the
|
|
239
|
-
* `##` headings in AUTHORING_MANUAL above. */
|
|
240
|
-
const MANUAL_SECTION_RULES: ReadonlyArray<[RegExp, string]> = [
|
|
241
|
-
[/^auth(\.|$)/, "Auth"],
|
|
242
|
-
[/^operations(\[\d+\])?\.params(\.|$)/, "Optional fields (operation-level)"],
|
|
243
|
-
[/^operations(\[\d+\])?\.(via|name|path)$/, "Required fields"],
|
|
244
|
-
[
|
|
245
|
-
/^operations(\[\d+\])?\.(dateParams|helper|transform|passthrough|parse|requiresAnyOf)(\.|$)/,
|
|
246
|
-
"Optional fields (operation-level)",
|
|
247
|
-
],
|
|
248
|
-
[/^operations(\[\d+\])?\.pagination(\.|$)/, "Executor semantics"],
|
|
249
|
-
[/^pagination(\.|$)/, "Executor semantics"],
|
|
250
|
-
[/^operations(\[\d+\])?\.(accept|gatherAllMax)(\.|$)/, "Key defaults"],
|
|
251
|
-
[/^responseShape(\.|$)/, "Key defaults"],
|
|
252
|
-
[
|
|
253
|
-
/^(organization|description)$/,
|
|
254
|
-
"Optional fields (multi-recipe disambiguation)",
|
|
255
|
-
],
|
|
256
|
-
[/^(domains|apiHost|kind|operations)$/, "Required fields"],
|
|
257
|
-
[/^(verified|docs|gatherAllMax)$/, "Key defaults"],
|
|
258
|
-
];
|
|
259
|
-
|
|
260
|
-
function manualSectionFor(field: string): string | undefined {
|
|
261
|
-
for (const [re, section] of MANUAL_SECTION_RULES) {
|
|
262
|
-
if (re.test(field)) return section;
|
|
263
|
-
}
|
|
264
|
-
return undefined;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
233
|
/** Template path — write the placeholder skeleton to the staging path and
|
|
268
234
|
* surface the file path (the agent edits the file, not an inline copy).
|
|
269
235
|
* Fail-closed: the as-is template cannot save (placeholder `apiHost`
|
|
@@ -271,9 +237,12 @@ function manualSectionFor(field: string): string | undefined {
|
|
|
271
237
|
function stageTemplate(domain: string): string {
|
|
272
238
|
const path = writeStagedDraft(domain, placeholderSkeleton(domain));
|
|
273
239
|
return (
|
|
240
|
+
AUTHORING_MANUAL +
|
|
241
|
+
"\n\n" +
|
|
274
242
|
`📝 Template for '${domain}' written to ${path}\n` +
|
|
275
243
|
` Edit the file (or append ops via bash), then call ` +
|
|
276
|
-
`api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save
|
|
244
|
+
`api-learn({domain: "${domain}", recipeFile: "${path}"}) to validate and save.\n` +
|
|
245
|
+
` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`
|
|
277
246
|
);
|
|
278
247
|
}
|
|
279
248
|
|
|
@@ -297,12 +266,15 @@ function stageFetchedRecipe(
|
|
|
297
266
|
{
|
|
298
267
|
type: "text",
|
|
299
268
|
text:
|
|
269
|
+
AUTHORING_MANUAL +
|
|
270
|
+
"\n\n" +
|
|
300
271
|
`📖 Current recipe for '${domain}' — guide '${guide.shortName}'\n` +
|
|
301
272
|
` Directory: ${dirName}\n` +
|
|
302
273
|
` Staged draft: ${path}\n` +
|
|
303
274
|
` To edit: edit the staged file with the edit tool or bash, then call ` +
|
|
304
275
|
`api-learn({domain: "${dirName}", recipeFile: "${path}"}) — pass the ` +
|
|
305
|
-
`directory name as \`domain\` on re-save so a sibling guide is not clobbered
|
|
276
|
+
`directory name as \`domain\` on re-save so a sibling guide is not clobbered.\n` +
|
|
277
|
+
` Re-fetching or re-templating this domain replaces the staged draft — save first to keep edits.`,
|
|
306
278
|
},
|
|
307
279
|
],
|
|
308
280
|
details: { mode: "fetch", domain, dirName, guide: guide.shortName },
|
|
@@ -337,19 +309,16 @@ export const apiLearnTool = defineTool({
|
|
|
337
309
|
label: "API Learn",
|
|
338
310
|
description:
|
|
339
311
|
"Author an API guide for a domain. " +
|
|
340
|
-
"Call with no params for the authoring manual (field reference + defaults + semantics). " +
|
|
341
312
|
"Call with {domain, new: true} for a fresh domain-specific template. " +
|
|
342
313
|
"Call with {domain} and no recipeFile to fetch an existing guide's current raw recipe. " +
|
|
343
314
|
"Call with {domain, recipeFile} to validate and save.",
|
|
344
315
|
|
|
345
316
|
parameters: Type.Object({
|
|
346
|
-
domain: Type.
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
}),
|
|
352
|
-
),
|
|
317
|
+
domain: Type.String({
|
|
318
|
+
description:
|
|
319
|
+
"Domain (e.g. 'example.com'). With `recipeFile` it's the save directory; " +
|
|
320
|
+
"with no recipeFile it's the routing domain for fetch-recipe lookup.",
|
|
321
|
+
}),
|
|
353
322
|
recipeFile: Type.Optional(
|
|
354
323
|
Type.String({
|
|
355
324
|
description:
|
|
@@ -380,20 +349,12 @@ export const apiLearnTool = defineTool({
|
|
|
380
349
|
guide: guideSelector,
|
|
381
350
|
new: isNew,
|
|
382
351
|
} = params as {
|
|
383
|
-
domain
|
|
352
|
+
domain: string;
|
|
384
353
|
recipeFile?: string;
|
|
385
354
|
guide?: string;
|
|
386
355
|
new?: boolean;
|
|
387
356
|
};
|
|
388
357
|
|
|
389
|
-
// ── No domain → authoring manual ─────────────────────────
|
|
390
|
-
if (!domain) {
|
|
391
|
-
return {
|
|
392
|
-
content: [{ type: "text", text: AUTHORING_MANUAL }],
|
|
393
|
-
details: { mode: "manual" },
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
|
|
397
358
|
// ── Validate domain (path-traversal guard) ─────────────
|
|
398
359
|
try {
|
|
399
360
|
assertSafeDomain(domain);
|
|
@@ -495,13 +456,6 @@ export const apiLearnTool = defineTool({
|
|
|
495
456
|
` Found: ${err.found}`,
|
|
496
457
|
];
|
|
497
458
|
if (err.fix) lines.push(` Fix: ${err.fix}`);
|
|
498
|
-
const section = manualSectionFor(err.field);
|
|
499
|
-
lines.push("");
|
|
500
|
-
lines.push(
|
|
501
|
-
section
|
|
502
|
-
? `See the \`${section}\` section of the authoring manual — call api-learn() with no params.`
|
|
503
|
-
: `Call api-learn() with no params for the authoring manual.`,
|
|
504
|
-
);
|
|
505
459
|
lines.push("Fix the recipe and call api-learn again.");
|
|
506
460
|
return {
|
|
507
461
|
content: [{ type: "text", text: lines.join("\n") }],
|
|
@@ -564,11 +518,48 @@ export const apiLearnTool = defineTool({
|
|
|
564
518
|
);
|
|
565
519
|
}
|
|
566
520
|
|
|
567
|
-
// ──
|
|
521
|
+
// ── Fail-closed overwrite guard ─────────────────────────
|
|
522
|
+
// A guide.md already in the target directory is that directory's
|
|
523
|
+
// identity anchor. If its shortName differs from the incoming
|
|
524
|
+
// guide's, this save would silently replace a sibling guide (the
|
|
525
|
+
// multi-recipe clobber bug). Refuse and teach the directory
|
|
526
|
+
// convention instead. Same shortName = legitimate update, proceeds.
|
|
568
527
|
const guidesDir = getUserGuidesDir();
|
|
569
528
|
const domainDir = join(guidesDir, domain);
|
|
570
|
-
mkdirSync(domainDir, { recursive: true });
|
|
571
529
|
const filepath = join(domainDir, "guide.md");
|
|
530
|
+
if (existsSync(filepath)) {
|
|
531
|
+
const existing = parseApiGuide(readFileSync(filepath, "utf-8"), {
|
|
532
|
+
filename: domain,
|
|
533
|
+
});
|
|
534
|
+
const existingShort = existing.ok ? existing.guide.shortName : undefined;
|
|
535
|
+
if (existingShort !== parsed.guide.shortName) {
|
|
536
|
+
return {
|
|
537
|
+
content: [
|
|
538
|
+
{
|
|
539
|
+
type: "text",
|
|
540
|
+
text:
|
|
541
|
+
`⚠ Refusing to overwrite — guide was NOT saved.\n` +
|
|
542
|
+
` Directory '${domain}' already holds guide '${existingShort ?? "?"}' (guide.md); ` +
|
|
543
|
+
`the incoming guide is '${parsed.guide.shortName}'.` +
|
|
544
|
+
(existing.ok
|
|
545
|
+
? `\n To save a SECOND guide for the same routing domain, use a distinct directory:\n` +
|
|
546
|
+
` api-learn({domain: "${domain}-${parsed.guide.shortName}", recipeFile: "${recipeFile}"})\n` +
|
|
547
|
+
` Keep \`domains: [${parsed.guide.domains?.join(", ")}]\` in the recipe for routing.`
|
|
548
|
+
: `\n The existing guide.md is malformed (won't parse). If you intend to replace it, ask the user to run /api delete ${domain} first.`),
|
|
549
|
+
},
|
|
550
|
+
],
|
|
551
|
+
details: {
|
|
552
|
+
error: "overwrite_refused",
|
|
553
|
+
domain,
|
|
554
|
+
existing: existingShort ?? null,
|
|
555
|
+
incoming: parsed.guide.shortName,
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
mkdirSync(domainDir, { recursive: true });
|
|
561
|
+
|
|
562
|
+
// ── Write guide ──────────────────────────────────────────
|
|
572
563
|
|
|
573
564
|
// Stamp schemaVersion on save — each guide records the schema vintage
|
|
574
565
|
// it was authored against (the per-guide vintage that stale detection
|
|
@@ -601,7 +592,7 @@ export const apiLearnTool = defineTool({
|
|
|
601
592
|
`\n` +
|
|
602
593
|
warningBlock +
|
|
603
594
|
`Call api-fetch({domain: "${domain}", operation: "${parsed.guide.operations[0]!.name}"}) to verify.` +
|
|
604
|
-
`\n⚠
|
|
595
|
+
`\n⚠ Edit the staged /tmp file, not the saved guide.md — direct edits to guide.md are overwritten on save and invisible to api-fetch until then.`,
|
|
605
596
|
},
|
|
606
597
|
],
|
|
607
598
|
details: {
|
|
@@ -616,14 +607,10 @@ export const apiLearnTool = defineTool({
|
|
|
616
607
|
|
|
617
608
|
renderCall(args, theme, _context) {
|
|
618
609
|
const parts: string[] = [theme.fg("toolTitle", theme.bold("api-learn "))];
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
else parts.push(theme.fg("dim", "📖"));
|
|
624
|
-
} else {
|
|
625
|
-
parts.push(theme.fg("dim", "(manual)"));
|
|
626
|
-
}
|
|
610
|
+
parts.push(theme.fg("accent", `"${args.domain}"`));
|
|
611
|
+
if (args.new) parts.push(theme.fg("dim", "✨new"));
|
|
612
|
+
else if (args.recipeFile) parts.push(theme.fg("dim", "📝"));
|
|
613
|
+
else parts.push(theme.fg("dim", "📖"));
|
|
627
614
|
return new Text(parts.join(" "), 0, 0);
|
|
628
615
|
},
|
|
629
616
|
|
|
@@ -649,11 +636,9 @@ export const apiLearnTool = defineTool({
|
|
|
649
636
|
} else if (mode === "menu" && domain) {
|
|
650
637
|
text = theme.fg("dim", theme.bold("📖 menu"));
|
|
651
638
|
text += ` — ${disambig ?? "?"} guides for ${domain}`;
|
|
652
|
-
} else
|
|
639
|
+
} else {
|
|
653
640
|
text = theme.fg("accent", theme.bold(`📝 Saved guide for ${domain}`));
|
|
654
641
|
text += ` — ${opCount} ops`;
|
|
655
|
-
} else {
|
|
656
|
-
text = theme.fg("dim", "📝 Authoring manual");
|
|
657
642
|
}
|
|
658
643
|
|
|
659
644
|
return new Text(appendFooter(text, expanded, result, theme, 600), 0, 0);
|
package/tools/api-probe.ts
CHANGED
|
@@ -33,7 +33,6 @@ import {
|
|
|
33
33
|
} from "../core/auth.js";
|
|
34
34
|
import { listDomains, listNames } from "../core/secrets-store.js";
|
|
35
35
|
import { findGuidesByDomain } from "../core/guide-store.js";
|
|
36
|
-
import { GUIDE_SCHEMA_VERSION } from "../core/api-guide-types.js";
|
|
37
36
|
import { isApiLearnEnabled } from "../core/api-toggle.js";
|
|
38
37
|
import { appendFooter, contentText } from "./utils.js";
|
|
39
38
|
|
|
@@ -71,9 +70,6 @@ export interface ProbeResult {
|
|
|
71
70
|
raw: string;
|
|
72
71
|
/** Human note (auth-required, 404, version-prefix hit, non-JSON, …). */
|
|
73
72
|
note?: string;
|
|
74
|
-
/** True when the caller didn't pass scaffold: true and no guide claims the
|
|
75
|
-
* domain yet — the authoring loop should surface the skeleton option. */
|
|
76
|
-
scaffoldNudge?: boolean;
|
|
77
73
|
}
|
|
78
74
|
|
|
79
75
|
export interface ProbeOptions {
|
|
@@ -99,13 +95,6 @@ export interface ProbeOptions {
|
|
|
99
95
|
};
|
|
100
96
|
/** Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain). */
|
|
101
97
|
domain?: string;
|
|
102
|
-
/**
|
|
103
|
-
* Emit a full recipe skeleton (frontmatter + auth + operations) when no
|
|
104
|
-
* guide exists for the domain; auto-degrades to a single op block + merge
|
|
105
|
-
* note when one or more guides already claim the domain. Opt-in —
|
|
106
|
-
* without it the output is today's op-block-only draft.
|
|
107
|
-
*/
|
|
108
|
-
scaffold?: boolean;
|
|
109
98
|
}
|
|
110
99
|
|
|
111
100
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -319,6 +308,41 @@ function resolveProbeAuth(
|
|
|
319
308
|
const MISCONFIGURED_PREFIXES_NOTE =
|
|
320
309
|
"headerPrefixes ignored: no secretRefs to apply them to; put the secret name in auth.secretRefs";
|
|
321
310
|
|
|
311
|
+
/** Extracts the server's own human-readable reason from a 403 body — the
|
|
312
|
+
* note says what the API actually means instead of a synthesized
|
|
313
|
+
* classification. A 403 is "authenticated but forbidden", not a
|
|
314
|
+
* header/secret problem, so surfacing the server's words beats both the
|
|
315
|
+
* bare status and a "verify header" false signal. Returns undefined when
|
|
316
|
+
* the body isn't JSON or carries no message field; the caller falls back
|
|
317
|
+
* to the bare status.
|
|
318
|
+
* ponytail: secret-scrub invariant — this MUST parse the scrubbed `raw`
|
|
319
|
+
* slice, never the raw `res.body`, or a key echoed in the body would leak
|
|
320
|
+
* into agent context. */
|
|
321
|
+
function serverMessage(raw: string): string | undefined {
|
|
322
|
+
let data: unknown;
|
|
323
|
+
try {
|
|
324
|
+
data = JSON.parse(raw);
|
|
325
|
+
} catch {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
if (!isObj(data)) return undefined;
|
|
329
|
+
const d = data as Record<string, unknown>;
|
|
330
|
+
const status = isObj(d["status"])
|
|
331
|
+
? (d["status"] as Record<string, unknown>)
|
|
332
|
+
: undefined;
|
|
333
|
+
const candidates: unknown[] = [
|
|
334
|
+
d["message"],
|
|
335
|
+
d["error"],
|
|
336
|
+
d["error_message"],
|
|
337
|
+
d["detail"],
|
|
338
|
+
status?.["error_message"],
|
|
339
|
+
];
|
|
340
|
+
const msg = candidates.find(
|
|
341
|
+
(c) => typeof c === "string" && c.trim().length > 0,
|
|
342
|
+
);
|
|
343
|
+
return typeof msg === "string" ? msg.trim().slice(0, 200) : undefined;
|
|
344
|
+
}
|
|
345
|
+
|
|
322
346
|
/** First missing secret name as a one-line note (names only, never values).
|
|
323
347
|
* Prescriptive: names the other provisioned domains and tells the author to
|
|
324
348
|
* pass `domain:` — the probe's domain is inferred from apiHost, so a miss is
|
|
@@ -388,7 +412,6 @@ export async function probe(
|
|
|
388
412
|
authCtx,
|
|
389
413
|
domain,
|
|
390
414
|
versionPrefixOf(apiHost),
|
|
391
|
-
opts,
|
|
392
415
|
);
|
|
393
416
|
if (base.status !== 404 || !walkVersions || /^\/v\d+\//.test(path)) {
|
|
394
417
|
return base;
|
|
@@ -403,7 +426,7 @@ export async function probe(
|
|
|
403
426
|
return base;
|
|
404
427
|
}
|
|
405
428
|
const hit = await walkBackward(
|
|
406
|
-
{ apiHost, path, params, accept, authCtx, domain
|
|
429
|
+
{ apiHost, path, params, accept, authCtx, domain },
|
|
407
430
|
Number(stated),
|
|
408
431
|
);
|
|
409
432
|
return hit ?? base;
|
|
@@ -428,7 +451,6 @@ async function walkBackward(
|
|
|
428
451
|
accept: string;
|
|
429
452
|
authCtx: ProbeAuthCtx;
|
|
430
453
|
domain: string;
|
|
431
|
-
opts: ProbeOptions;
|
|
432
454
|
},
|
|
433
455
|
start: number,
|
|
434
456
|
): Promise<ProbeResult | null> {
|
|
@@ -443,7 +465,6 @@ async function walkBackward(
|
|
|
443
465
|
ctx.authCtx,
|
|
444
466
|
ctx.domain,
|
|
445
467
|
`/v${k}`,
|
|
446
|
-
ctx.opts,
|
|
447
468
|
);
|
|
448
469
|
if (tried.status !== 404) {
|
|
449
470
|
// A walk hit may itself have redirected (e.g. /v2 301→ /v3); the
|
|
@@ -483,7 +504,6 @@ async function fetchOne(
|
|
|
483
504
|
authCtx: ProbeAuthCtx,
|
|
484
505
|
domain: string,
|
|
485
506
|
prefix = "",
|
|
486
|
-
opts: ProbeOptions = {},
|
|
487
507
|
): Promise<ProbeResult> {
|
|
488
508
|
// Inject secret query params below the agent-supplied params map, then
|
|
489
509
|
// redact the surfaced URL so the real key never reaches the transcript.
|
|
@@ -510,25 +530,33 @@ async function fetchOne(
|
|
|
510
530
|
);
|
|
511
531
|
|
|
512
532
|
if (res.status >= 400) {
|
|
513
|
-
|
|
533
|
+
// 401 or 403 — both mean the request was rejected on auth grounds
|
|
534
|
+
// (gated endpoint, or bad/missing credentials), distinct from other
|
|
535
|
+
// 4xx/5xx statuses. The name is deliberate: it covers 403 too.
|
|
536
|
+
const isAuthError = res.status === 401 || res.status === 403;
|
|
514
537
|
const miss = missNote(authCtx, domain);
|
|
515
538
|
let note: string;
|
|
516
539
|
if (!authCtx.hasAuthBlock) {
|
|
517
540
|
// No auth injected — a 401/403 means the endpoint is gated and the
|
|
518
541
|
// probe sent nothing. Pre-guide authoring tool: no guide in scope,
|
|
519
542
|
// so no stale "(guide is auth:none)" wording.
|
|
520
|
-
note =
|
|
543
|
+
note = isAuthError
|
|
521
544
|
? `${res.status} — endpoint requires auth; configure auth injection (auth.secretRefs)`
|
|
522
545
|
: `${res.status}`;
|
|
523
546
|
} else if (miss) {
|
|
524
547
|
// Auth injected but a required secret was missing — the miss names it.
|
|
525
|
-
note = `${res.status}${
|
|
548
|
+
note = `${res.status}${isAuthError ? " — auth rejected;" : ""} ${miss}`;
|
|
526
549
|
} else {
|
|
527
|
-
// Auth injected, nothing missing
|
|
528
|
-
//
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
550
|
+
// Auth injected, nothing missing. A 403 means authenticated but
|
|
551
|
+
// forbidden — "verify header name" is a 401 signal, not a 403 one.
|
|
552
|
+
// Surface the server's own reason (from the scrubbed `raw`, never
|
|
553
|
+
// `res.body`) when we can parse it; fall back to the bare status.
|
|
554
|
+
const msg = res.status === 403 ? serverMessage(raw) : undefined;
|
|
555
|
+
note = msg
|
|
556
|
+
? `${res.status} — ${msg} (auth configured correctly; not a header/secret problem)`
|
|
557
|
+
: res.status === 401
|
|
558
|
+
? `${res.status} — auth injected but rejected; verify header name and secret value`
|
|
559
|
+
: `${res.status}`;
|
|
532
560
|
}
|
|
533
561
|
if (authCtx.misconfiguredPrefixes) {
|
|
534
562
|
note += ` — ${MISCONFIGURED_PREFIXES_NOTE}`;
|
|
@@ -564,21 +592,11 @@ async function fetchOne(
|
|
|
564
592
|
|
|
565
593
|
const shape = summarize(data);
|
|
566
594
|
const miss = missNote(authCtx, domain);
|
|
567
|
-
|
|
595
|
+
const draft = emitDraft(path, params, shape, prefix);
|
|
568
596
|
let note: string | undefined = miss;
|
|
569
|
-
if (opts.scaffold && draft) {
|
|
570
|
-
const sc = emitScaffold({ apiHost, domain, draft, auth: opts.auth });
|
|
571
|
-
draft = sc.draft;
|
|
572
|
-
if (sc.note) note = [note, sc.note].filter(Boolean).join(" — ");
|
|
573
|
-
}
|
|
574
597
|
if (authCtx.misconfiguredPrefixes) {
|
|
575
598
|
note = [note, MISCONFIGURED_PREFIXES_NOTE].filter(Boolean).join(" — ");
|
|
576
599
|
}
|
|
577
|
-
// Targeted scaffold nudge: only when the caller didn't pass
|
|
578
|
-
// scaffold: true AND no guide claims the domain yet — authors who already
|
|
579
|
-
// used the skeleton (or who have a guide) see no noise.
|
|
580
|
-
const scaffoldNudge =
|
|
581
|
-
opts.scaffold !== true && findGuidesByDomain(domain).length === 0;
|
|
582
600
|
return {
|
|
583
601
|
url,
|
|
584
602
|
finalUrl,
|
|
@@ -588,7 +606,6 @@ async function fetchOne(
|
|
|
588
606
|
draft,
|
|
589
607
|
raw,
|
|
590
608
|
...(note ? { note } : {}),
|
|
591
|
-
...(scaffoldNudge ? { scaffoldNudge } : {}),
|
|
592
609
|
};
|
|
593
610
|
}
|
|
594
611
|
|
|
@@ -703,113 +720,6 @@ function suggestName(path: string): string {
|
|
|
703
720
|
.replace(/[^a-zA-Z0-9]/g, "");
|
|
704
721
|
}
|
|
705
722
|
|
|
706
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
707
|
-
// Scaffold emission — full skeleton vs op-block + merge note
|
|
708
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
709
|
-
|
|
710
|
-
/**
|
|
711
|
-
* Translate the probe's auth-injection params into a `kind: static-key` auth
|
|
712
|
-
* block (probe auth shape matches the guide schema).
|
|
713
|
-
* `requires` = the union of secret names referenced by the refs. Returns
|
|
714
|
-
* undefined when no injection refs are declared (auth: none default).
|
|
715
|
-
*/
|
|
716
|
-
function emitAuthBlock(
|
|
717
|
-
auth: NonNullable<ProbeOptions["auth"]> | undefined,
|
|
718
|
-
): string | undefined {
|
|
719
|
-
const refs = auth?.secretRefs ?? {};
|
|
720
|
-
const queryRefs = auth?.secretQueryRefs ?? {};
|
|
721
|
-
const prefixes = auth?.headerPrefixes ?? {};
|
|
722
|
-
const names = [
|
|
723
|
-
...new Set([...Object.values(refs), ...Object.values(queryRefs)]),
|
|
724
|
-
];
|
|
725
|
-
if (names.length === 0) return undefined;
|
|
726
|
-
const lines = [
|
|
727
|
-
"auth:",
|
|
728
|
-
" kind: static-key",
|
|
729
|
-
` requires: [${names.join(", ")}]`,
|
|
730
|
-
];
|
|
731
|
-
if (Object.keys(refs).length > 0) {
|
|
732
|
-
lines.push(" secretRefs:");
|
|
733
|
-
for (const [header, secret] of Object.entries(refs))
|
|
734
|
-
lines.push(` ${header}: ${secret}`);
|
|
735
|
-
}
|
|
736
|
-
if (Object.keys(queryRefs).length > 0) {
|
|
737
|
-
lines.push(" secretQueryRefs:");
|
|
738
|
-
for (const [param, secret] of Object.entries(queryRefs))
|
|
739
|
-
lines.push(` ${param}: ${secret}`);
|
|
740
|
-
}
|
|
741
|
-
if (Object.keys(prefixes).length > 0) {
|
|
742
|
-
lines.push(" headerPrefixes:");
|
|
743
|
-
for (const [header, prefix] of Object.entries(prefixes))
|
|
744
|
-
lines.push(` ${header}: "${prefix}"`);
|
|
745
|
-
}
|
|
746
|
-
return lines.join("\n");
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
/**
|
|
750
|
-
* Full recipe skeleton (bootstrap): frontmatter + auth + the probe's op
|
|
751
|
-
* block. `schemaVersion` literal matches what api-learn stamps on save, so a
|
|
752
|
-
* scaffolded guide is detection-ready the moment it's saved. Pagination stays
|
|
753
|
-
* op-level only (a single probe justifies one op's pagination, never a
|
|
754
|
-
* top-level default).
|
|
755
|
-
*/
|
|
756
|
-
function emitScaffoldSkeleton(opts: {
|
|
757
|
-
apiHost: string;
|
|
758
|
-
domain: string;
|
|
759
|
-
draft: string;
|
|
760
|
-
auth: ProbeOptions["auth"];
|
|
761
|
-
}): string {
|
|
762
|
-
const lines = [
|
|
763
|
-
"---",
|
|
764
|
-
"kind: api",
|
|
765
|
-
`domains: [${opts.domain}]`,
|
|
766
|
-
`apiHost: ${opts.apiHost}`,
|
|
767
|
-
"responseShape:",
|
|
768
|
-
" format: json",
|
|
769
|
-
"gatherAllMax: 1000",
|
|
770
|
-
`schemaVersion: ${GUIDE_SCHEMA_VERSION}`,
|
|
771
|
-
];
|
|
772
|
-
const authBlock = emitAuthBlock(opts.auth);
|
|
773
|
-
if (authBlock) lines.push("", authBlock);
|
|
774
|
-
// Op-level hint for the new constraint field — commented so a fresh
|
|
775
|
-
// scaffold surfaces the mechanism (mirrors placeholderSkeleton).
|
|
776
|
-
lines.push(
|
|
777
|
-
"",
|
|
778
|
-
"# requiresAnyOf: [id, slug, code] # at least one of these params must be supplied",
|
|
779
|
-
"operations:",
|
|
780
|
-
opts.draft,
|
|
781
|
-
"---",
|
|
782
|
-
"",
|
|
783
|
-
);
|
|
784
|
-
return lines.join("\n");
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
/**
|
|
788
|
-
* Scaffold decision, driven by findGuidesByDomain(domain): 0 guides →
|
|
789
|
-
* full skeleton (bootstrap); 1 guide → op block + merge note naming the one
|
|
790
|
-
* dirName; N guides → op block + merge note listing every candidate dirName
|
|
791
|
-
* (the merge-target choice defers to api-learn's selector). Returns the
|
|
792
|
-
* paste-able draft + an optional human merge note.
|
|
793
|
-
*/
|
|
794
|
-
function emitScaffold(opts: {
|
|
795
|
-
apiHost: string;
|
|
796
|
-
domain: string;
|
|
797
|
-
draft: string;
|
|
798
|
-
auth: ProbeOptions["auth"];
|
|
799
|
-
}): { draft: string; note?: string } {
|
|
800
|
-
const matches = findGuidesByDomain(opts.domain);
|
|
801
|
-
if (matches.length === 0) {
|
|
802
|
-
return { draft: emitScaffoldSkeleton(opts) };
|
|
803
|
-
}
|
|
804
|
-
const dirs = matches.map((m) => m.dirName);
|
|
805
|
-
const note =
|
|
806
|
-
matches.length === 1
|
|
807
|
-
? `scaffold: guide already exists — merge into \`${dirs[0]}\``
|
|
808
|
-
: `scaffold: ${matches.length} guides already exist — merge into one of: ${dirs.join(", ")}`;
|
|
809
|
-
return { draft: opts.draft, note };
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
813
723
|
// Tool definition
|
|
814
724
|
// ═══════════════════════════════════════════════════════════════════
|
|
815
725
|
|
|
@@ -832,10 +742,7 @@ export const apiProbeTool = defineTool({
|
|
|
832
742
|
"version — then probe that version explicitly. Do not default the version from " +
|
|
833
743
|
"memory: a stale version that still returns 200 is not detected as old (the " +
|
|
834
744
|
"backward walk only fires on 404). The probe recovers an over-claimed version " +
|
|
835
|
-
"but cannot detect a stale-but-working one. "
|
|
836
|
-
"Pass scaffold: true to emit a full recipe skeleton (frontmatter + auth + " +
|
|
837
|
-
"operations) when no guide exists for the domain; it auto-degrades to a single " +
|
|
838
|
-
"op block + merge note when one or more guides already claim the domain.",
|
|
745
|
+
"but cannot detect a stale-but-working one. ",
|
|
839
746
|
|
|
840
747
|
parameters: Type.Object({
|
|
841
748
|
apiHost: Type.Optional(
|
|
@@ -867,14 +774,6 @@ export const apiProbeTool = defineTool({
|
|
|
867
774
|
"On 404, walk the apiHost version backward (vN→v1) to find the highest live version. Default true.",
|
|
868
775
|
}),
|
|
869
776
|
),
|
|
870
|
-
scaffold: Type.Optional(
|
|
871
|
-
Type.Boolean({
|
|
872
|
-
description:
|
|
873
|
-
"Emit a full recipe skeleton (frontmatter + auth + operations) when no guide exists for the domain; " +
|
|
874
|
-
"auto-degrades to a single op block + merge note when one or more guides already claim the domain. " +
|
|
875
|
-
"Opt-in — without it the output is today's op-block-only draft.",
|
|
876
|
-
}),
|
|
877
|
-
),
|
|
878
777
|
auth: Type.Optional(
|
|
879
778
|
Type.Object(
|
|
880
779
|
{
|
|
@@ -911,21 +810,19 @@ export const apiProbeTool = defineTool({
|
|
|
911
810
|
}),
|
|
912
811
|
|
|
913
812
|
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
914
|
-
const { apiHost, path, walkVersions, auth, domain, listSecrets
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
headerPrefixes?: Record<string, string>;
|
|
924
|
-
};
|
|
925
|
-
domain?: string;
|
|
926
|
-
listSecrets?: boolean;
|
|
927
|
-
scaffold?: boolean;
|
|
813
|
+
const { apiHost, path, walkVersions, auth, domain, listSecrets } = params as {
|
|
814
|
+
apiHost?: string;
|
|
815
|
+
path?: string;
|
|
816
|
+
params?: Record<string, unknown>;
|
|
817
|
+
walkVersions?: boolean;
|
|
818
|
+
auth?: {
|
|
819
|
+
secretRefs?: Record<string, string>;
|
|
820
|
+
secretQueryRefs?: Record<string, string>;
|
|
821
|
+
headerPrefixes?: Record<string, string>;
|
|
928
822
|
};
|
|
823
|
+
domain?: string;
|
|
824
|
+
listSecrets?: boolean;
|
|
825
|
+
};
|
|
929
826
|
const userParams = (params as Record<string, unknown>)["params"] as
|
|
930
827
|
| Record<string, unknown>
|
|
931
828
|
| undefined;
|
|
@@ -995,7 +892,6 @@ export const apiProbeTool = defineTool({
|
|
|
995
892
|
...(walkVersions === undefined ? {} : { walkVersions }),
|
|
996
893
|
...(auth ? { auth } : {}),
|
|
997
894
|
...(domain ? { domain } : {}),
|
|
998
|
-
...(scaffold === undefined ? {} : { scaffold }),
|
|
999
895
|
});
|
|
1000
896
|
return {
|
|
1001
897
|
content: [{ type: "text", text: formatProbeResult(result) }],
|
|
@@ -1029,7 +925,6 @@ export const apiProbeTool = defineTool({
|
|
|
1029
925
|
const parts: string[] = [theme.fg("toolTitle", theme.bold("api-probe "))];
|
|
1030
926
|
if (args.apiHost) parts.push(theme.fg("accent", `"${args.apiHost}"`));
|
|
1031
927
|
if (args.path) parts.push(theme.fg("dim", `› ${args.path}`));
|
|
1032
|
-
if (args.scaffold) parts.push(theme.fg("dim", "· scaffold"));
|
|
1033
928
|
return new Text(parts.join(" "), 0, 0);
|
|
1034
929
|
},
|
|
1035
930
|
|
|
@@ -1129,13 +1024,7 @@ export function formatProbeResult(r: ProbeResult): string {
|
|
|
1129
1024
|
lines.push(r.raw);
|
|
1130
1025
|
}
|
|
1131
1026
|
lines.push("");
|
|
1132
|
-
|
|
1133
|
-
if (r.scaffoldNudge) {
|
|
1134
|
-
footer.push(
|
|
1135
|
-
"No guide for this domain yet — pass scaffold: true to emit a full recipe skeleton.",
|
|
1136
|
-
);
|
|
1137
|
-
}
|
|
1138
|
-
lines.push(` ${footer.join("\n ")}`);
|
|
1027
|
+
lines.push(` ${DOCS_NUDGE.join("\n ")}`);
|
|
1139
1028
|
return lines.join("\n");
|
|
1140
1029
|
}
|
|
1141
1030
|
|