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.
- package/README.md +201 -513
- package/core/api-guide-types.ts +263 -46
- package/core/api-toggle.ts +245 -40
- package/core/auth.ts +996 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +21 -6
- package/core/helpers-command.ts +6 -5
- package/core/helpers.ts +551 -148
- package/core/local-helpers.ts +17 -2
- package/core/oauth-command.ts +911 -0
- package/core/oauth-flow.ts +376 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1153 -542
- package/core/path-template.ts +147 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/status-hint.ts +61 -0
- package/core/transport.ts +321 -34
- package/core/verify-command.ts +215 -116
- package/docs/migration-v1.md +56 -0
- package/index.ts +24 -7
- package/package.json +18 -6
- package/tools/api-fetch.ts +49 -21
- package/tools/api-guide.ts +21 -12
- package/tools/api-learn.ts +515 -126
- package/tools/api-probe.ts +473 -323
- package/tools/api-scaffold.ts +413 -0
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +1 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -7
package/tools/api-probe.ts
CHANGED
|
@@ -18,23 +18,43 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
21
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { confirmTokenUrl } from "../core/oauth-flow.js";
|
|
21
23
|
import { Type } from "@earendil-works/pi-ai";
|
|
22
24
|
import { Text } from "@earendil-works/pi-tui";
|
|
23
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
fetchUrl,
|
|
27
|
+
redactSecretParams,
|
|
28
|
+
redactSecretPathValues,
|
|
29
|
+
} from "../core/transport.js";
|
|
30
|
+
import { splitPathSecretParams } from "../core/helpers.js";
|
|
24
31
|
import {
|
|
25
32
|
extractPathTokens,
|
|
26
33
|
fillPathTemplate,
|
|
27
34
|
joinUrl,
|
|
28
35
|
} from "../core/path-template.js";
|
|
29
36
|
import {
|
|
37
|
+
assertNoBearerCollision,
|
|
38
|
+
buildSyntheticOAuth2Auth,
|
|
39
|
+
hostnameOf,
|
|
40
|
+
isTokenExpired,
|
|
41
|
+
pathScrubValues,
|
|
42
|
+
resolveAccessToken,
|
|
43
|
+
resolveProvisionedParentDomain,
|
|
30
44
|
resolveSecretHeaders,
|
|
45
|
+
resolveSecretPathParams,
|
|
31
46
|
resolveSecretQueryParams,
|
|
32
47
|
scrubSecretValues,
|
|
33
48
|
} from "../core/auth.js";
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
49
|
+
import { readToken } from "../core/oauth-store.js";
|
|
50
|
+
import { provisionedDomainsSuffix } from "../core/secrets-store.js";
|
|
51
|
+
import { serverMessage, isPlanGated } from "../core/status-hint.js";
|
|
37
52
|
import { appendFooter, contentText } from "./utils.js";
|
|
53
|
+
import type {
|
|
54
|
+
SecretRef,
|
|
55
|
+
StaticKeyAuth,
|
|
56
|
+
OAuth2Grant,
|
|
57
|
+
} from "../core/api-guide-types.js";
|
|
38
58
|
|
|
39
59
|
// ═══════════════════════════════════════════════════════════════════
|
|
40
60
|
// Types
|
|
@@ -86,12 +106,56 @@ export interface ProbeOptions {
|
|
|
86
106
|
/** Maps header name → secret name, same direction as the guide schema. */
|
|
87
107
|
secretRefs?: Record<string, string>;
|
|
88
108
|
secretQueryRefs?: Record<string, string>;
|
|
109
|
+
/**
|
|
110
|
+
* Maps path token → secret name (Telegram-class token-in-path APIs:
|
|
111
|
+
* `/bot{token}/getMe`). Store value fills `{token}` below the agent
|
|
112
|
+
* params map; any agent-supplied value for the name is dropped, and the
|
|
113
|
+
* token is redacted from every surfaced URL.
|
|
114
|
+
*/
|
|
115
|
+
secretPathRefs?: Record<string, string>;
|
|
89
116
|
/**
|
|
90
117
|
* Header name → prefix prepended to the resolved secret value (e.g.
|
|
91
118
|
* `Authorization: "Bearer "`). The store holds the raw token; the prefix
|
|
92
119
|
* is API knowledge. Keys must be present in `secretRefs`.
|
|
93
120
|
*/
|
|
94
121
|
headerPrefixes?: Record<string, string>;
|
|
122
|
+
/**
|
|
123
|
+
* Read the OAuth2 access token from the token store (the domain the
|
|
124
|
+
* probe resolved) and inject `Authorization: Bearer <token>` — values
|
|
125
|
+
* never enter the transcript. Bearer-header only (ponytail: query
|
|
126
|
+
* paramStyle waits for a recipe that needs it). No/expired token →
|
|
127
|
+
* the note nudges `/api oauth <domain>` and the probe proceeds
|
|
128
|
+
* unauthenticated (probe misses are never fail-closed). With mint
|
|
129
|
+
* fields below, the miss mints instead of nudging. Requires `grant` +
|
|
130
|
+
* `tokenUrl` (the slot key) — omitting either is a validation error.
|
|
131
|
+
*/
|
|
132
|
+
useTokenStore?: boolean;
|
|
133
|
+
/**
|
|
134
|
+
* The token slot to read: slots are keyed `(domain, grant, tokenUrl)`,
|
|
135
|
+
* so a store read needs the same grant + token endpoint facts the mint
|
|
136
|
+
* arm already carries. Required with useTokenStore — a call without
|
|
137
|
+
* them is a loud validation error, not a silent store miss.
|
|
138
|
+
*/
|
|
139
|
+
grant?: OAuth2Grant;
|
|
140
|
+
/**
|
|
141
|
+
* Mint-on-demand (client-credentials authoring bootstrap): when the
|
|
142
|
+
* token store has no usable token, the probe POSTs `tokenUrl` once
|
|
143
|
+
* (client-credentials grant), stamps the token store, and injects the
|
|
144
|
+
* fresh Bearer. `clientId`/`clientSecret` are secrets-store NAMES —
|
|
145
|
+
* values resolve from the store, never the transcript. Implies
|
|
146
|
+
* useTokenStore. auth-code cannot be inlined (needs the interactive
|
|
147
|
+
* paste dance) — save a draft guide and use `/api oauth` for that.
|
|
148
|
+
* `tokenUrl` is load-bearing beyond minting: it keys the token-store
|
|
149
|
+
* slot read (with `grant`).
|
|
150
|
+
*/
|
|
151
|
+
tokenUrl?: string;
|
|
152
|
+
clientId?: string;
|
|
153
|
+
clientSecret?: string;
|
|
154
|
+
scopes?: string[];
|
|
155
|
+
tokenEndpointAuthMethod?:
|
|
156
|
+
| "client_secret_basic"
|
|
157
|
+
| "client_secret_post"
|
|
158
|
+
| "none";
|
|
95
159
|
};
|
|
96
160
|
/** Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain). */
|
|
97
161
|
domain?: string;
|
|
@@ -219,11 +283,51 @@ interface ProbeAuthCtx {
|
|
|
219
283
|
queryParams: Record<string, string>;
|
|
220
284
|
secretHeaderNames: Set<string>;
|
|
221
285
|
secretQueryParamNames: Set<string>;
|
|
286
|
+
/** path token → store-filled raw value (empty when no path refs / store miss). */
|
|
287
|
+
pathSecretParams: Record<string, string>;
|
|
288
|
+
/** path token → store secret NAME (for draft emission — never a value). */
|
|
289
|
+
pathSecretNames: Record<string, string>;
|
|
222
290
|
secretValues: string[];
|
|
223
291
|
missingNames: string[];
|
|
224
292
|
/** headerPrefixes declared but no secretRefs to apply them to — the
|
|
225
293
|
* prefixes would be silently dropped. Surfaced as a note, not an error. */
|
|
226
294
|
misconfiguredPrefixes: boolean;
|
|
295
|
+
/** useTokenStore declared but no usable token (absent or expired) — the
|
|
296
|
+
* nudge text, composed into the 401/403 note. Empty when fine/unused. */
|
|
297
|
+
tokenNote: string;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Convert the probe's flat inline `auth` block (tool param — injection
|
|
302
|
+
* fields only) into a nested `StaticKeyAuth` for the shared resolvers.
|
|
303
|
+
* `headerPrefixes` fold inline onto each ref's `prefix`.
|
|
304
|
+
*/
|
|
305
|
+
function flatToStaticKeyAuth(
|
|
306
|
+
auth: NonNullable<ProbeOptions["auth"]>,
|
|
307
|
+
): StaticKeyAuth {
|
|
308
|
+
const secretRefs: Record<string, SecretRef> = {};
|
|
309
|
+
for (const [header, secretName] of Object.entries(auth.secretRefs ?? {})) {
|
|
310
|
+
secretRefs[header] = {
|
|
311
|
+
secret: secretName,
|
|
312
|
+
...(auth.headerPrefixes?.[header] === undefined
|
|
313
|
+
? {}
|
|
314
|
+
: { prefix: auth.headerPrefixes[header] }),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const secretQueryRefs: Record<string, SecretRef> = {};
|
|
318
|
+
for (const [param, secretName] of Object.entries(auth.secretQueryRefs ?? {})) {
|
|
319
|
+
secretQueryRefs[param] = { secret: secretName };
|
|
320
|
+
}
|
|
321
|
+
const secretPathRefs: Record<string, SecretRef> = {};
|
|
322
|
+
for (const [token, secretName] of Object.entries(auth.secretPathRefs ?? {})) {
|
|
323
|
+
secretPathRefs[token] = { secret: secretName };
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
kind: "static-key",
|
|
327
|
+
...(Object.keys(secretRefs).length > 0 ? { secretRefs } : {}),
|
|
328
|
+
...(Object.keys(secretQueryRefs).length > 0 ? { secretQueryRefs } : {}),
|
|
329
|
+
...(Object.keys(secretPathRefs).length > 0 ? { secretPathRefs } : {}),
|
|
330
|
+
};
|
|
227
331
|
}
|
|
228
332
|
|
|
229
333
|
/**
|
|
@@ -233,10 +337,11 @@ interface ProbeAuthCtx {
|
|
|
233
337
|
* omitted. `requires`/`optional` are absent from the probe's injection-only
|
|
234
338
|
* block, so every miss lands in the report list.
|
|
235
339
|
*/
|
|
236
|
-
function resolveProbeAuth(
|
|
340
|
+
async function resolveProbeAuth(
|
|
237
341
|
auth: NonNullable<ProbeOptions["auth"]> | undefined,
|
|
238
342
|
domain: string,
|
|
239
|
-
|
|
343
|
+
ctx?: ExtensionContext,
|
|
344
|
+
): Promise<ProbeAuthCtx> {
|
|
240
345
|
// Computed before the hasRefs check so the flag survives both paths: a
|
|
241
346
|
// headerPrefixes-only block (hasRefs false → early return) and a
|
|
242
347
|
// secretQueryRefs block with prefixes but no secretRefs (hasRefs true →
|
|
@@ -250,54 +355,166 @@ function resolveProbeAuth(
|
|
|
250
355
|
const hasRefs =
|
|
251
356
|
!!auth &&
|
|
252
357
|
(Object.keys(auth.secretRefs ?? {}).length > 0 ||
|
|
253
|
-
Object.keys(auth.secretQueryRefs ?? {}).length > 0
|
|
254
|
-
|
|
358
|
+
Object.keys(auth.secretQueryRefs ?? {}).length > 0 ||
|
|
359
|
+
Object.keys(auth.secretPathRefs ?? {}).length > 0);
|
|
360
|
+
const useTokenStore = !!auth?.useTokenStore;
|
|
361
|
+
// Inline mint fields imply the token path even without useTokenStore.
|
|
362
|
+
const hasMintFields = !!auth?.tokenUrl && !!auth?.clientId;
|
|
363
|
+
// tokenUrl is load-bearing for both arms (mint destination AND store slot
|
|
364
|
+
// key), so mint fields + any non-cc grant is an ambiguous mix — refuse
|
|
365
|
+
// loudly instead of silently minting a client_credentials token that
|
|
366
|
+
// overwrites the intent (and stamps a cc slot nobody asked for).
|
|
367
|
+
if (hasMintFields && auth?.grant && auth.grant !== "client_credentials") {
|
|
368
|
+
return {
|
|
369
|
+
hasAuthBlock: true,
|
|
370
|
+
headers: {},
|
|
371
|
+
queryParams: {},
|
|
372
|
+
secretHeaderNames: new Set(),
|
|
373
|
+
secretQueryParamNames: new Set(),
|
|
374
|
+
pathSecretParams: {},
|
|
375
|
+
pathSecretNames: {},
|
|
376
|
+
secretValues: [],
|
|
377
|
+
missingNames: [],
|
|
378
|
+
misconfiguredPrefixes,
|
|
379
|
+
tokenNote:
|
|
380
|
+
`mint fields (tokenUrl + clientId) are client_credentials-only; ` +
|
|
381
|
+
`drop auth.grant ("${auth.grant}") or omit the mint fields and set ` +
|
|
382
|
+
`auth.useTokenStore to read the existing ${auth.grant} slot`,
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (!hasRefs && !useTokenStore && !hasMintFields) {
|
|
255
386
|
return {
|
|
256
387
|
hasAuthBlock: false,
|
|
257
388
|
headers: {},
|
|
258
389
|
queryParams: {},
|
|
259
390
|
secretHeaderNames: new Set(),
|
|
260
391
|
secretQueryParamNames: new Set(),
|
|
392
|
+
pathSecretParams: {},
|
|
393
|
+
pathSecretNames: {},
|
|
261
394
|
secretValues: [],
|
|
262
395
|
missingNames: [],
|
|
263
396
|
misconfiguredPrefixes,
|
|
397
|
+
tokenNote: "",
|
|
264
398
|
};
|
|
265
399
|
}
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
)
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
)
|
|
400
|
+
const staticKeyAuth = flatToStaticKeyAuth(auth!);
|
|
401
|
+
const headerRes = resolveSecretHeaders(staticKeyAuth, domain);
|
|
402
|
+
const queryRes = resolveSecretQueryParams(staticKeyAuth, domain);
|
|
403
|
+
const pathRes = resolveSecretPathParams(staticKeyAuth, domain);
|
|
404
|
+
// OAuth2 token injection: the token rides the same ctx as secret headers
|
|
405
|
+
// (scrub + redirect-strip cover it). Bearer-header only (ponytail: query
|
|
406
|
+
// paramStyle injection waits for a recipe that needs it). Two modes:
|
|
407
|
+
// store-read-only (useTokenStore, nudge /api oauth on miss) and
|
|
408
|
+
// mint-on-demand (inline tokenUrl + clientId — authoring bootstrap).
|
|
409
|
+
let tokenNote = "";
|
|
410
|
+
const tokenHeader: Record<string, string> = {};
|
|
411
|
+
// Raw (unprefixed) token value for the body scrub — a 401 body can echo
|
|
412
|
+
// the bare credential, not just the `Bearer <token>` header form.
|
|
413
|
+
let rawTokenValue = "";
|
|
414
|
+
if (hasMintFields) {
|
|
415
|
+
// Build a synthetic oauth2 auth and hand it straight to
|
|
416
|
+
// resolveAccessToken so the cache → refresh → mint → stamp machinery is
|
|
417
|
+
// reused wholesale (incl. the per-domain refresh lock). Failures never
|
|
418
|
+
// fail-closed — validation throws included, since
|
|
419
|
+
// buildSyntheticOAuth2Auth runs inside the same try/catch — the message
|
|
420
|
+
// rides the note and the probe proceeds unauthenticated.
|
|
421
|
+
// Interactive sessions re-gate the secret-bearing destination on the
|
|
422
|
+
// human (same trust root as oauth-mint). Headless has no gate — the
|
|
423
|
+
// agent-has-bash posture covers it; documented in AGENTS.md. Decline
|
|
424
|
+
// skips only the mint: tokenHeader stays empty and the shared return
|
|
425
|
+
// below reports the unauthenticated probe + any secret misses.
|
|
426
|
+
if (ctx?.hasUI) {
|
|
427
|
+
const ok = await confirmTokenUrl(
|
|
428
|
+
ctx,
|
|
429
|
+
domain,
|
|
430
|
+
auth!.tokenUrl!,
|
|
431
|
+
auth!.clientId!,
|
|
432
|
+
);
|
|
433
|
+
if (!ok)
|
|
434
|
+
tokenNote = `token-URL confirm declined for "${domain}"; probe proceeding unauthenticated`;
|
|
435
|
+
}
|
|
436
|
+
// Decline skips only the mint (tokenHeader stays empty) — the note and
|
|
437
|
+
// unauthenticated probe are reported by the shared return below.
|
|
438
|
+
if (tokenNote === "") {
|
|
439
|
+
try {
|
|
440
|
+
const oauthAuth = buildSyntheticOAuth2Auth({
|
|
441
|
+
grant: "client_credentials",
|
|
442
|
+
tokenUrl: auth!.tokenUrl!,
|
|
443
|
+
clientId: auth!.clientId!,
|
|
444
|
+
...(auth!.clientSecret ? { clientSecret: auth!.clientSecret } : {}),
|
|
445
|
+
...(auth!.scopes?.length ? { scopes: auth!.scopes } : {}),
|
|
446
|
+
...(auth!.tokenEndpointAuthMethod
|
|
447
|
+
? { tokenEndpointAuthMethod: auth!.tokenEndpointAuthMethod }
|
|
448
|
+
: {}),
|
|
449
|
+
});
|
|
450
|
+
const result = await resolveAccessToken(oauthAuth, domain);
|
|
451
|
+
const bearer = result.authHeaders?.authorization;
|
|
452
|
+
if (bearer) {
|
|
453
|
+
tokenHeader["authorization"] = bearer;
|
|
454
|
+
rawTokenValue = result.secretValues[0] ?? "";
|
|
455
|
+
} else tokenNote = "oauth2 mint succeeded but produced no bearer header";
|
|
456
|
+
} catch (e) {
|
|
457
|
+
tokenNote = e instanceof Error ? e.message : "oauth2 mint failed";
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
} else if (useTokenStore) {
|
|
461
|
+
// Slot-keyed store read: the slot derives from (grant, tokenUrl) — the
|
|
462
|
+
// same facts the mint arm carries. Without them the read would target a
|
|
463
|
+
// slot that never exists; that misconfiguration is a LOUD validation
|
|
464
|
+
// error (the caller's try/catch surfaces it), not a misleading
|
|
465
|
+
// "run /api oauth" note on an unauthenticated fetch.
|
|
466
|
+
if (!auth?.grant || !auth?.tokenUrl) {
|
|
467
|
+
throw new Error(
|
|
468
|
+
"auth.useTokenStore requires auth.grant (client_credentials | authorization_code) " +
|
|
469
|
+
"and auth.tokenUrl — token slots are keyed by (domain, grant, token endpoint).",
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const token = readToken(domain, auth.grant, auth.tokenUrl);
|
|
473
|
+
if (!token) {
|
|
474
|
+
tokenNote = `no cached token for "${domain}"; run /api oauth ${domain} to mint one`;
|
|
475
|
+
} else if (isTokenExpired(token)) {
|
|
476
|
+
tokenNote = `token for "${domain}" is expired; run /api oauth ${domain} --refresh`;
|
|
477
|
+
} else {
|
|
478
|
+
tokenHeader["authorization"] = `Bearer ${token.accessToken}`;
|
|
479
|
+
rawTokenValue = token.accessToken;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (Object.keys(tokenHeader).length > 0) {
|
|
483
|
+
assertNoBearerCollision(
|
|
484
|
+
headerRes.headers,
|
|
485
|
+
"the probe auth block's secretRefs",
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
const headers = { ...headerRes.headers, ...tokenHeader };
|
|
281
489
|
return {
|
|
282
490
|
hasAuthBlock: true,
|
|
283
|
-
headers
|
|
491
|
+
headers,
|
|
284
492
|
queryParams: queryRes.queryParams,
|
|
285
|
-
secretHeaderNames: new Set(
|
|
286
|
-
Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
|
|
287
|
-
),
|
|
493
|
+
secretHeaderNames: new Set(Object.keys(headers).map((h) => h.toLowerCase())),
|
|
288
494
|
secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
|
|
495
|
+
pathSecretParams: pathRes.values,
|
|
496
|
+
pathSecretNames: Object.fromEntries(
|
|
497
|
+
Object.entries(staticKeyAuth.secretPathRefs ?? {}).map(([t, r]) => [
|
|
498
|
+
t,
|
|
499
|
+
r.secret,
|
|
500
|
+
]),
|
|
501
|
+
),
|
|
289
502
|
secretValues: [
|
|
290
|
-
...Object.values(
|
|
503
|
+
...Object.values(headers),
|
|
291
504
|
...headerRes.rawHeaderValues,
|
|
292
505
|
...Object.values(queryRes.queryParams),
|
|
506
|
+
...pathScrubValues(pathRes.values),
|
|
507
|
+
...(rawTokenValue ? [rawTokenValue] : []),
|
|
293
508
|
],
|
|
294
509
|
missingNames: [
|
|
295
510
|
...headerRes.absentRequired,
|
|
296
511
|
...headerRes.absentOptional,
|
|
297
512
|
...queryRes.absentRequired,
|
|
298
513
|
...queryRes.absentOptional,
|
|
514
|
+
...pathRes.missing,
|
|
299
515
|
],
|
|
300
516
|
misconfiguredPrefixes,
|
|
517
|
+
tokenNote,
|
|
301
518
|
};
|
|
302
519
|
}
|
|
303
520
|
|
|
@@ -308,76 +525,24 @@ function resolveProbeAuth(
|
|
|
308
525
|
const MISCONFIGURED_PREFIXES_NOTE =
|
|
309
526
|
"headerPrefixes ignored: no secretRefs to apply them to; put the secret name in auth.secretRefs";
|
|
310
527
|
|
|
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
|
-
|
|
346
528
|
/** First missing secret name as a one-line note (names only, never values).
|
|
347
529
|
* Prescriptive: names the other provisioned domains and tells the author to
|
|
348
530
|
* pass `domain:` — the probe's domain is inferred from apiHost, so a miss is
|
|
349
531
|
* usually a domain-mismatch, not a missing secret. */
|
|
350
532
|
function missNote(authCtx: ProbeAuthCtx, domain: string): string {
|
|
351
533
|
if (authCtx.missingNames.length === 0) return "";
|
|
352
|
-
const
|
|
353
|
-
const tail =
|
|
354
|
-
others.length > 0
|
|
355
|
-
? ` — provisioned domains: ${others.join(", ")}; pass domain: <one> to use its secret`
|
|
356
|
-
: "";
|
|
534
|
+
const suffix = provisionedDomainsSuffix(domain);
|
|
535
|
+
const tail = suffix ? `${suffix}; pass domain: <one> to use its secret` : "";
|
|
357
536
|
return `secret "${authCtx.missingNames[0]}" not found in store for domain "${domain}"${tail}`;
|
|
358
537
|
}
|
|
359
538
|
|
|
360
|
-
/**
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (domains.includes(hostname)) return hostname;
|
|
368
|
-
const parent = domains
|
|
369
|
-
.filter((d) => hostname.endsWith(`.${d}`))
|
|
370
|
-
.sort((a, b) => b.length - a.length)[0];
|
|
371
|
-
return parent ?? hostname;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
/** Hostname of an apiHost URL (falls back to the raw string). */
|
|
375
|
-
function hostnameOf(apiHost: string): string {
|
|
376
|
-
try {
|
|
377
|
-
return new URL(apiHost).hostname;
|
|
378
|
-
} catch {
|
|
379
|
-
return apiHost;
|
|
380
|
-
}
|
|
539
|
+
/** missNote + the token-store note, joined — the one miss renderer used at
|
|
540
|
+
* every note site, so a useTokenStore nudge rides along wherever a secret
|
|
541
|
+
* miss would. */
|
|
542
|
+
function authMissNote(authCtx: ProbeAuthCtx, domain: string): string {
|
|
543
|
+
return [missNote(authCtx, domain), authCtx.tokenNote]
|
|
544
|
+
.filter(Boolean)
|
|
545
|
+
.join(" — ");
|
|
381
546
|
}
|
|
382
547
|
|
|
383
548
|
/** Trailing path of an apiHost URL (e.g. `/v3`), or `""` when empty/root.
|
|
@@ -396,11 +561,13 @@ export async function probe(
|
|
|
396
561
|
path: string,
|
|
397
562
|
params: Record<string, unknown> = {},
|
|
398
563
|
opts: ProbeOptions = {},
|
|
564
|
+
ctx?: ExtensionContext,
|
|
399
565
|
): Promise<ProbeResult> {
|
|
400
566
|
const accept = opts.accept ?? "application/json";
|
|
401
567
|
const walkVersions = opts.walkVersions ?? true;
|
|
402
|
-
const domain =
|
|
403
|
-
|
|
568
|
+
const domain =
|
|
569
|
+
opts.domain ?? resolveProvisionedParentDomain(hostnameOf(apiHost));
|
|
570
|
+
const authCtx = await resolveProbeAuth(opts.auth, domain, ctx);
|
|
404
571
|
|
|
405
572
|
// Base case only carries the apiHost version prefix; a walk-hit draft
|
|
406
573
|
// embeds its walked version in the prefix passed to fetchOne.
|
|
@@ -454,7 +621,7 @@ async function walkBackward(
|
|
|
454
621
|
},
|
|
455
622
|
start: number,
|
|
456
623
|
): Promise<ProbeResult | null> {
|
|
457
|
-
const miss =
|
|
624
|
+
const miss = authMissNote(ctx.authCtx, ctx.domain);
|
|
458
625
|
const floor = Math.max(start - MAX_VERSION_WALK, 1);
|
|
459
626
|
for (let k = start - 1; k >= floor; k--) {
|
|
460
627
|
const tried = await fetchOne(
|
|
@@ -471,7 +638,7 @@ async function walkBackward(
|
|
|
471
638
|
// draft carries /v${k} while the body came from elsewhere — flag
|
|
472
639
|
// it so the agent checks finalUrl instead of trusting the prefix.
|
|
473
640
|
const redirected = tried.finalUrl !== tried.url;
|
|
474
|
-
tried.note = `${miss ? miss
|
|
641
|
+
tried.note = `${miss ? `${miss} — ` : ""}404 on /v${start}${ctx.path}; version walk → /v${k}${redirected ? " — verify finalUrl (redirect target)" : ""}`;
|
|
475
642
|
return tried;
|
|
476
643
|
}
|
|
477
644
|
}
|
|
@@ -492,8 +659,8 @@ function withVersion(apiHost: string, k: number): string {
|
|
|
492
659
|
|
|
493
660
|
/** The gate-excluded 404 note (bare / non-integer / subdomain version hosts). */
|
|
494
661
|
function walkSkipNote(authCtx: ProbeAuthCtx, domain: string): string {
|
|
495
|
-
const miss =
|
|
496
|
-
return `${miss ? miss
|
|
662
|
+
const miss = authMissNote(authCtx, domain);
|
|
663
|
+
return `${miss ? `${miss} — ` : ""}404 — no version walk (apiHost has no /vN prefix)`;
|
|
497
664
|
}
|
|
498
665
|
|
|
499
666
|
async function fetchOne(
|
|
@@ -505,10 +672,26 @@ async function fetchOne(
|
|
|
505
672
|
domain: string,
|
|
506
673
|
prefix = "",
|
|
507
674
|
): Promise<ProbeResult> {
|
|
508
|
-
//
|
|
509
|
-
//
|
|
510
|
-
|
|
511
|
-
|
|
675
|
+
// Secret-owned path tokens: the path fill sees the merged map (store
|
|
676
|
+
// wins; agent-supplied values for secret-owned tokens dropped), while the
|
|
677
|
+
// query builder gets a deletion-only copy — a probe whose path lacks the
|
|
678
|
+
// token must not leak the plaintext into the query string.
|
|
679
|
+
const pathSecrets = authCtx.pathSecretParams;
|
|
680
|
+
const pathValues = Object.values(pathSecrets);
|
|
681
|
+
const { fillParams, queryParamsForBuild } = splitPathSecretParams(
|
|
682
|
+
params,
|
|
683
|
+
pathSecrets,
|
|
684
|
+
);
|
|
685
|
+
const rawUrl = buildUrl(apiHost, path, fillParams, {
|
|
686
|
+
...queryParamsForBuild,
|
|
687
|
+
...authCtx.queryParams,
|
|
688
|
+
});
|
|
689
|
+
const redactUrl = (u: string) =>
|
|
690
|
+
redactSecretPathValues(
|
|
691
|
+
redactSecretParams(u, authCtx.secretQueryParamNames),
|
|
692
|
+
pathValues,
|
|
693
|
+
);
|
|
694
|
+
const url = redactUrl(rawUrl);
|
|
512
695
|
const hasQuerySecret = Object.keys(authCtx.queryParams).length > 0;
|
|
513
696
|
const res = await fetchUrl(rawUrl, {
|
|
514
697
|
headers: { accept, ...authCtx.headers },
|
|
@@ -516,25 +699,33 @@ async function fetchOne(
|
|
|
516
699
|
...(authCtx.hasAuthBlock
|
|
517
700
|
? {
|
|
518
701
|
hasQuerySecret,
|
|
702
|
+
hasPathSecret: pathValues.length > 0,
|
|
519
703
|
secretHeaderNames: authCtx.secretHeaderNames,
|
|
704
|
+
secretQueryParamNames: authCtx.secretQueryParamNames,
|
|
705
|
+
...(pathValues.length > 0
|
|
706
|
+
? {
|
|
707
|
+
// Redaction closure (not raw values): keeps the
|
|
708
|
+
// transport's option surface value-agnostic; used
|
|
709
|
+
// on cross-domain redirect hops.
|
|
710
|
+
redactPathSecret: (u: string) => redactSecretPathValues(u, pathValues),
|
|
711
|
+
}
|
|
712
|
+
: {}),
|
|
520
713
|
}
|
|
521
714
|
: {}),
|
|
522
715
|
});
|
|
523
716
|
// Probe-local body scrub: the probe bypasses checkResponseStatus, so
|
|
524
|
-
// scrub known secret values from the
|
|
525
|
-
// echoing the key must not leak it into agent context.
|
|
526
|
-
|
|
527
|
-
const
|
|
528
|
-
|
|
529
|
-
authCtx.secretQueryParamNames,
|
|
530
|
-
);
|
|
717
|
+
// scrub known secret values from the full body directly — a 401 body
|
|
718
|
+
// echoing the key must not leak it into agent context. Scrub before
|
|
719
|
+
// slicing so a secret straddling the cut can't leave a partial prefix.
|
|
720
|
+
const raw = scrubSecretValues(res.body, authCtx.secretValues).slice(0, 800);
|
|
721
|
+
const finalUrl = redactUrl(res.finalUrl ?? rawUrl);
|
|
531
722
|
|
|
532
723
|
if (res.status >= 400) {
|
|
533
724
|
// 401 or 403 — both mean the request was rejected on auth grounds
|
|
534
725
|
// (gated endpoint, or bad/missing credentials), distinct from other
|
|
535
726
|
// 4xx/5xx statuses. The name is deliberate: it covers 403 too.
|
|
536
727
|
const isAuthError = res.status === 401 || res.status === 403;
|
|
537
|
-
const miss =
|
|
728
|
+
const miss = authMissNote(authCtx, domain);
|
|
538
729
|
let note: string;
|
|
539
730
|
if (!authCtx.hasAuthBlock) {
|
|
540
731
|
// No auth injected — a 401/403 means the endpoint is gated and the
|
|
@@ -551,12 +742,23 @@ async function fetchOne(
|
|
|
551
742
|
// forbidden — "verify header name" is a 401 signal, not a 403 one.
|
|
552
743
|
// Surface the server's own reason (from the scrubbed `raw`, never
|
|
553
744
|
// `res.body`) when we can parse it; fall back to the bare status.
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
745
|
+
// When the reason reads as plan-gating, say so — it's the key's
|
|
746
|
+
// plan, not the recipe.
|
|
747
|
+
if (res.status === 403) {
|
|
748
|
+
const msg = serverMessage(raw);
|
|
749
|
+
if (msg) {
|
|
750
|
+
const suffix = isPlanGated(raw)
|
|
751
|
+
? "plan/subscription limitation on the key, not the recipe"
|
|
752
|
+
: "auth configured correctly; not a header/secret problem";
|
|
753
|
+
note = `${res.status} — ${msg} (${suffix})`;
|
|
754
|
+
} else {
|
|
755
|
+
note = `${res.status}`;
|
|
756
|
+
}
|
|
757
|
+
} else if (res.status === 401) {
|
|
758
|
+
note = `${res.status} — auth injected but rejected; verify header name and secret value`;
|
|
759
|
+
} else {
|
|
760
|
+
note = `${res.status}`;
|
|
761
|
+
}
|
|
560
762
|
}
|
|
561
763
|
if (authCtx.misconfiguredPrefixes) {
|
|
562
764
|
note += ` — ${MISCONFIGURED_PREFIXES_NOTE}`;
|
|
@@ -591,8 +793,14 @@ async function fetchOne(
|
|
|
591
793
|
}
|
|
592
794
|
|
|
593
795
|
const shape = summarize(data);
|
|
594
|
-
const miss =
|
|
595
|
-
const draft = emitDraft(
|
|
796
|
+
const miss = authMissNote(authCtx, domain);
|
|
797
|
+
const draft = emitDraft(
|
|
798
|
+
path,
|
|
799
|
+
queryParamsForBuild,
|
|
800
|
+
shape,
|
|
801
|
+
prefix,
|
|
802
|
+
authCtx.pathSecretNames,
|
|
803
|
+
);
|
|
596
804
|
let note: string | undefined = miss;
|
|
597
805
|
if (authCtx.misconfiguredPrefixes) {
|
|
598
806
|
note = [note, MISCONFIGURED_PREFIXES_NOTE].filter(Boolean).join(" — ");
|
|
@@ -614,25 +822,38 @@ const RESERVED_PARAM_NAMES = new Set(["domain", "apiHost", "path", "auth"]);
|
|
|
614
822
|
function buildUrl(
|
|
615
823
|
apiHost: string,
|
|
616
824
|
path: string,
|
|
617
|
-
|
|
825
|
+
fillParams: Record<string, unknown>,
|
|
826
|
+
queryParams: Record<string, unknown>,
|
|
618
827
|
): string {
|
|
619
|
-
for (const key of Object.keys(
|
|
828
|
+
for (const key of Object.keys(fillParams).concat(Object.keys(queryParams))) {
|
|
620
829
|
if (RESERVED_PARAM_NAMES.has(key)) {
|
|
621
830
|
throw new Error(
|
|
622
831
|
`"${key}" is a top-level param, not a query param — move it out of params`,
|
|
623
832
|
);
|
|
624
833
|
}
|
|
625
834
|
}
|
|
626
|
-
// Substitute {token} →
|
|
835
|
+
// Substitute {token} → fillParams[token] BEFORE building the URL, so a
|
|
627
836
|
// templated path fetches real values instead of literal %7Bowner%7D.
|
|
628
837
|
// Missing tokens stay literal ({token}) — fine for probing an unfilled path.
|
|
629
838
|
const pathTokens = new Set(extractPathTokens(path));
|
|
630
|
-
const substituted = fillPathTemplate(path,
|
|
839
|
+
const substituted = fillPathTemplate(path, fillParams);
|
|
631
840
|
const qs = new URLSearchParams(
|
|
632
841
|
Object.fromEntries(
|
|
633
|
-
Object.entries(
|
|
842
|
+
Object.entries(queryParams)
|
|
634
843
|
.filter(([k, v]) => v !== undefined && !pathTokens.has(k))
|
|
635
|
-
.map(([k, v]) =>
|
|
844
|
+
.map(([k, v]) => {
|
|
845
|
+
// Probe has no guide schema to declare listStyle against, so
|
|
846
|
+
// non-scalar values are a loud error — never the silent
|
|
847
|
+
// String(v) wire form (String(["a","b"]) → "a,b" is
|
|
848
|
+
// accidentally comma-correct but misdescribes repeat/bracket
|
|
849
|
+
// APIs; [object Object] is wrong everywhere).
|
|
850
|
+
if (Array.isArray(v) || (typeof v === "object" && v !== null)) {
|
|
851
|
+
throw new Error(
|
|
852
|
+
`Param "${k}" is ${Array.isArray(v) ? "an array" : "an object"} — api-probe sends scalar params only: pre-join list values as a string, or JSON.stringify DSL params`,
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
return [k, String(v)] as [string, string];
|
|
856
|
+
}),
|
|
636
857
|
),
|
|
637
858
|
).toString();
|
|
638
859
|
return joinUrl(apiHost, substituted, qs);
|
|
@@ -647,19 +868,20 @@ export function emitDraft(
|
|
|
647
868
|
params: Record<string, unknown>,
|
|
648
869
|
shape: ShapeSummary,
|
|
649
870
|
prefix = "",
|
|
871
|
+
pathSecretRefs?: Record<string, string>,
|
|
650
872
|
): string {
|
|
651
873
|
// Idempotent: only prepend when the path doesn't already carry the prefix,
|
|
652
874
|
// so `apiHost: .../v3` + `path: /v3/items` doesn't become `/v3/v3/items`.
|
|
653
|
-
|
|
654
|
-
const name = suggestName(
|
|
655
|
-
const pathTokens = extractPathTokens(
|
|
875
|
+
const fullPath = prefix && !path.startsWith(prefix) ? prefix + path : path;
|
|
876
|
+
const name = suggestName(fullPath);
|
|
877
|
+
const pathTokens = extractPathTokens(fullPath);
|
|
656
878
|
const queryParamKeys = Object.keys(params).filter(
|
|
657
879
|
(k) => !pathTokens.includes(k),
|
|
658
880
|
);
|
|
659
881
|
const lines: string[] = [
|
|
660
882
|
` - name: ${name}`,
|
|
661
883
|
` via: ${shape.suggestedVia}`,
|
|
662
|
-
` path: ${
|
|
884
|
+
` path: ${fullPath}`,
|
|
663
885
|
` accept: json`,
|
|
664
886
|
];
|
|
665
887
|
|
|
@@ -695,6 +917,21 @@ export function emitDraft(
|
|
|
695
917
|
" # array response with no pagination markers — if the API documents paging, prefer paginate:",
|
|
696
918
|
" # offset-limit advances the page param by pageSize each page (use base: 1 for 1-based `start` APIs like CMC); page increments the page param by 1.",
|
|
697
919
|
);
|
|
920
|
+
if (shape.topLevel === "array") {
|
|
921
|
+
// Bare top-level array — the author would have to hand-convert, and
|
|
922
|
+
// `itemsPath` is parser-required on paginate ops but invisible here.
|
|
923
|
+
// Emit the ready-to-uncomment block so the conversion can't drop it.
|
|
924
|
+
lines.push(
|
|
925
|
+
" # bare top-level array — the paginate equivalent (itemsPath is REQUIRED on paginate ops):",
|
|
926
|
+
" # via: paginate",
|
|
927
|
+
" # pagination:",
|
|
928
|
+
" # style: offset-limit",
|
|
929
|
+
` # itemsPath: ${shape.suggestedItemsPath}`,
|
|
930
|
+
" # pageParam: offset",
|
|
931
|
+
" # pageSizeParam: limit",
|
|
932
|
+
" # pageSize: 30",
|
|
933
|
+
);
|
|
934
|
+
}
|
|
698
935
|
}
|
|
699
936
|
if (queryParamKeys.length > 0) {
|
|
700
937
|
lines.push(" params:");
|
|
@@ -708,6 +945,28 @@ export function emitDraft(
|
|
|
708
945
|
` # representative id: ${shape.representativeId.field}=${shape.representativeId.value}`,
|
|
709
946
|
);
|
|
710
947
|
}
|
|
948
|
+
// Path-secret tokens are store-filled (the agent must never hand-bake the
|
|
949
|
+
// token into the path — that's the transcript leak this surface closes),
|
|
950
|
+
// so the draft carries the guide-level auth block that backs them. Auth is
|
|
951
|
+
// frontmatter, not per-op — emitted commented, pasted above `operations:`.
|
|
952
|
+
// Only tokens the emitted path actually uses: a name in no op's path is
|
|
953
|
+
// rejected at parse (declared-but-unused), so emitting one would hand the
|
|
954
|
+
// author a guide that can't parse.
|
|
955
|
+
const pathRefEntries = Object.entries(pathSecretRefs ?? {}).filter(([t]) =>
|
|
956
|
+
pathTokens.includes(t),
|
|
957
|
+
);
|
|
958
|
+
if (pathRefEntries.length > 0) {
|
|
959
|
+
lines.push(
|
|
960
|
+
"# guide-level auth (paste into the frontmatter, above operations:) — the token fills from the secrets store, never params:",
|
|
961
|
+
"# auth:",
|
|
962
|
+
"# kind: static-key",
|
|
963
|
+
"# secretPathRefs:",
|
|
964
|
+
);
|
|
965
|
+
for (const [token, secret] of pathRefEntries) {
|
|
966
|
+
lines.push(`# ${token}:`);
|
|
967
|
+
lines.push(`# secret: ${secret}`);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
711
970
|
return lines.join("\n");
|
|
712
971
|
}
|
|
713
972
|
|
|
@@ -734,9 +993,9 @@ export const apiProbeTool = defineTool({
|
|
|
734
993
|
"It only suggests — it never writes the guide, and the operation must still be " +
|
|
735
994
|
"traceable to your plan source. Pre-guide: pass apiHost + path. After a guide " +
|
|
736
995
|
"exists, use api-guide({domain}) to get apiHost, or api-fetch to execute. " +
|
|
737
|
-
"Before the first auth-gated probe,
|
|
738
|
-
"
|
|
739
|
-
"
|
|
996
|
+
"Before the first auth-gated probe, use api-store (learn mode) to check what " +
|
|
997
|
+
"credentials exist for the domain — pass that domain up front so a store-miss " +
|
|
998
|
+
"round-trip is avoided. " +
|
|
740
999
|
"Before authoring a new guide, read the provider's docs index (llms.txt, " +
|
|
741
1000
|
"openapi.json at the API root, or the docs page) to learn the current API " +
|
|
742
1001
|
"version — then probe that version explicitly. Do not default the version from " +
|
|
@@ -745,23 +1004,19 @@ export const apiProbeTool = defineTool({
|
|
|
745
1004
|
"but cannot detect a stale-but-working one. ",
|
|
746
1005
|
|
|
747
1006
|
parameters: Type.Object({
|
|
748
|
-
apiHost: Type.
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
description:
|
|
762
|
-
"Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
|
|
763
|
-
}),
|
|
764
|
-
),
|
|
1007
|
+
apiHost: Type.String({
|
|
1008
|
+
description:
|
|
1009
|
+
"Base URL including the API's current version prefix, e.g. " +
|
|
1010
|
+
"'https://api.example.com/v3'. Find the latest version before probing: " +
|
|
1011
|
+
"check the API's docs page, openapi.json/swagger.json at the API root, " +
|
|
1012
|
+
"or llms.txt. Supply the newest version you can verify — if it 404s, the " +
|
|
1013
|
+
"probe walks backward (v3→v2→v1) to recover. Do not default to /v1 from " +
|
|
1014
|
+
"memory; a stale version that still returns 200 is not detected as old.",
|
|
1015
|
+
}),
|
|
1016
|
+
path: Type.String({
|
|
1017
|
+
description:
|
|
1018
|
+
"Templated path, e.g. '/repos/{owner}/{repo}/branches'. {token} placeholders are filled from params.",
|
|
1019
|
+
}),
|
|
765
1020
|
params: Type.Optional(
|
|
766
1021
|
Type.Record(Type.String(), Type.Unknown(), {
|
|
767
1022
|
description:
|
|
@@ -779,11 +1034,67 @@ export const apiProbeTool = defineTool({
|
|
|
779
1034
|
{
|
|
780
1035
|
secretRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
781
1036
|
secretQueryRefs: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
1037
|
+
secretPathRefs: Type.Optional(
|
|
1038
|
+
Type.Record(Type.String(), Type.String(), {
|
|
1039
|
+
description:
|
|
1040
|
+
"Path token → secret name for token-in-path APIs (e.g. {token: 'bot_token'} for /bot{token}/getMe). The store value fills {token}; agent-supplied values for the name are dropped and the token is redacted from surfaced URLs.",
|
|
1041
|
+
}),
|
|
1042
|
+
),
|
|
782
1043
|
headerPrefixes: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
1044
|
+
useTokenStore: Type.Optional(
|
|
1045
|
+
Type.Boolean({
|
|
1046
|
+
description:
|
|
1047
|
+
"Inject the OAuth2 access token from the token store as 'Authorization: Bearer <token>' (mint it first via /api oauth <domain>). Requires auth.grant + auth.tokenUrl (the token-slot key). Values never enter the transcript; absent/expired token → the note nudges /api oauth and the probe proceeds unauthenticated.",
|
|
1048
|
+
}),
|
|
1049
|
+
),
|
|
1050
|
+
grant: Type.Optional(
|
|
1051
|
+
Type.Union(
|
|
1052
|
+
[Type.Literal("client_credentials"), Type.Literal("authorization_code")],
|
|
1053
|
+
{
|
|
1054
|
+
description:
|
|
1055
|
+
"The token slot's grant — token slots are keyed (domain, grant, tokenUrl). Required with useTokenStore; the mint arm always uses client_credentials.",
|
|
1056
|
+
},
|
|
1057
|
+
),
|
|
1058
|
+
),
|
|
1059
|
+
tokenUrl: Type.Optional(
|
|
1060
|
+
Type.String({
|
|
1061
|
+
description:
|
|
1062
|
+
"Token endpoint URL — load-bearing beyond minting: it keys the token-store slot read (with grant). When the token store has no usable token and mint fields are present, the probe POSTs client-credentials once, stamps the store, and injects the fresh Bearer.",
|
|
1063
|
+
}),
|
|
1064
|
+
),
|
|
1065
|
+
clientId: Type.Optional(
|
|
1066
|
+
Type.String({
|
|
1067
|
+
description:
|
|
1068
|
+
"Mint-on-demand: secrets-store NAME of the client id (value resolves from the store, never the transcript). Requires tokenUrl.",
|
|
1069
|
+
}),
|
|
1070
|
+
),
|
|
1071
|
+
clientSecret: Type.Optional(
|
|
1072
|
+
Type.String({
|
|
1073
|
+
description: "Mint-on-demand: secrets-store NAME of the client secret.",
|
|
1074
|
+
}),
|
|
1075
|
+
),
|
|
1076
|
+
scopes: Type.Optional(
|
|
1077
|
+
Type.Array(Type.String(), {
|
|
1078
|
+
description: "Mint-on-demand: scopes for the token request.",
|
|
1079
|
+
}),
|
|
1080
|
+
),
|
|
1081
|
+
tokenEndpointAuthMethod: Type.Optional(
|
|
1082
|
+
Type.Union(
|
|
1083
|
+
[
|
|
1084
|
+
Type.Literal("client_secret_basic"),
|
|
1085
|
+
Type.Literal("client_secret_post"),
|
|
1086
|
+
Type.Literal("none"),
|
|
1087
|
+
],
|
|
1088
|
+
{
|
|
1089
|
+
description:
|
|
1090
|
+
"Mint-on-demand: token-endpoint auth method (default client_secret_post).",
|
|
1091
|
+
},
|
|
1092
|
+
),
|
|
1093
|
+
),
|
|
783
1094
|
},
|
|
784
1095
|
{
|
|
785
1096
|
description:
|
|
786
|
-
"Store-backed auth injection for probing auth-gated endpoints (authoring loop). Accepts
|
|
1097
|
+
"Store-backed auth injection for probing auth-gated endpoints (authoring loop). Accepts secretRefs, secretQueryRefs, secretPathRefs (token-in-path APIs), headerPrefixes, useTokenStore (+ grant + tokenUrl, the token-slot key), and client-credentials mint-on-demand fields (tokenUrl + clientId [+ clientSecret, scopes, tokenEndpointAuthMethod]) for bootstrapping a guide-less authoring loop. Values resolve from the secrets/token stores and never enter the transcript; a store miss fetches unauthenticated and reports the miss in the note.",
|
|
787
1098
|
// Tight: unknown keys (e.g. a stray `domain`) are rejected before execute runs.
|
|
788
1099
|
// The description above names the allowed fields explicitly — keep it in
|
|
789
1100
|
// sync when adding/renaming a field here, or the prose lies to agents.
|
|
@@ -797,102 +1108,33 @@ export const apiProbeTool = defineTool({
|
|
|
797
1108
|
"Domain for secrets-store lookups; defaults to apiHost's hostname (or its provisioned parent domain).",
|
|
798
1109
|
}),
|
|
799
1110
|
),
|
|
800
|
-
listSecrets: Type.Optional(
|
|
801
|
-
Type.Boolean({
|
|
802
|
-
description:
|
|
803
|
-
"Names only, never values. Two modes: with no domain/apiHost, lists " +
|
|
804
|
-
"provisioned-but-guideless store domains (authoring-bootstrap view — " +
|
|
805
|
-
"call this empty first to see what's provisioned); with a domain (or " +
|
|
806
|
-
"apiHost), lists provisioned secret names for that domain, with " +
|
|
807
|
-
"declared-vs-stored gaps when a guide exists.",
|
|
808
|
-
}),
|
|
809
|
-
),
|
|
810
1111
|
}),
|
|
811
1112
|
|
|
812
|
-
async execute(_toolCallId, params, _signal, _onUpdate,
|
|
813
|
-
const { apiHost, path, walkVersions, auth, domain
|
|
814
|
-
apiHost
|
|
815
|
-
path
|
|
1113
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1114
|
+
const { apiHost, path, walkVersions, auth, domain } = params as {
|
|
1115
|
+
apiHost: string;
|
|
1116
|
+
path: string;
|
|
816
1117
|
params?: Record<string, unknown>;
|
|
817
1118
|
walkVersions?: boolean;
|
|
818
|
-
auth?:
|
|
819
|
-
secretRefs?: Record<string, string>;
|
|
820
|
-
secretQueryRefs?: Record<string, string>;
|
|
821
|
-
headerPrefixes?: Record<string, string>;
|
|
822
|
-
};
|
|
1119
|
+
auth?: ProbeOptions["auth"];
|
|
823
1120
|
domain?: string;
|
|
824
|
-
listSecrets?: boolean;
|
|
825
1121
|
};
|
|
826
1122
|
const userParams = (params as Record<string, unknown>)["params"] as
|
|
827
1123
|
| Record<string, unknown>
|
|
828
1124
|
| undefined;
|
|
829
1125
|
|
|
830
|
-
// Learn-gated secrets discovery — short-circuits the fetch entirely.
|
|
831
|
-
// The agent's only programmatic path to the secrets store; /api secrets is
|
|
832
|
-
// user-typed only. Names only, never values.
|
|
833
|
-
if (listSecrets === true) {
|
|
834
|
-
if (!isApiLearnEnabled()) {
|
|
835
|
-
return {
|
|
836
|
-
content: [
|
|
837
|
-
{
|
|
838
|
-
type: "text",
|
|
839
|
-
text:
|
|
840
|
-
"api-probe: listSecrets: true is learn mode only — run /api learn first.",
|
|
841
|
-
},
|
|
842
|
-
],
|
|
843
|
-
details: { error: "learn_mode_only" },
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
// Bare call (no domain, no apiHost): orphan list only. apiHost present:
|
|
847
|
-
// orphan list first, then the per-domain view. domain present: unchanged.
|
|
848
|
-
const unscoped = domain ? undefined : unscopedStoreDomains();
|
|
849
|
-
const blocks: string[] = [];
|
|
850
|
-
if (unscoped !== undefined) blocks.push(formatUnscopedDomains(unscoped));
|
|
851
|
-
const target =
|
|
852
|
-
domain ??
|
|
853
|
-
(apiHost ? resolveProbeStoreDomain(hostnameOf(apiHost)) : undefined);
|
|
854
|
-
if (target !== undefined) {
|
|
855
|
-
const secrets = listDomainSecrets(target);
|
|
856
|
-
blocks.push(formatSecretsResult(secrets));
|
|
857
|
-
// apiHost/domain present means a real probe was suppressed by
|
|
858
|
-
// listSecrets: true — say so, or the author silently loses the probe.
|
|
859
|
-
blocks.push(
|
|
860
|
-
"probe suppressed because listSecrets: true — drop listSecrets to probe.",
|
|
861
|
-
);
|
|
862
|
-
return {
|
|
863
|
-
content: [{ type: "text", text: blocks.join("\n\n") }],
|
|
864
|
-
details: unscoped === undefined ? { secrets } : { secrets, unscoped },
|
|
865
|
-
};
|
|
866
|
-
}
|
|
867
|
-
return {
|
|
868
|
-
content: [{ type: "text", text: blocks.join("\n\n") }],
|
|
869
|
-
details: { unscoped: unscoped! },
|
|
870
|
-
};
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
// apiHost/path are optional in the schema so the bare listSecrets call is
|
|
874
|
-
// legal; every real probe needs both. The schema no longer enforces it,
|
|
875
|
-
// so guard here before falling through to probe(). (The listSecrets:true
|
|
876
|
-
// branch always returns above, so this guard only sees non-listSecrets.)
|
|
877
|
-
if (!apiHost || !path) {
|
|
878
|
-
return {
|
|
879
|
-
content: [
|
|
880
|
-
{
|
|
881
|
-
type: "text",
|
|
882
|
-
text:
|
|
883
|
-
"api-probe: apiHost and path are required unless listSecrets: true.",
|
|
884
|
-
},
|
|
885
|
-
],
|
|
886
|
-
details: { error: "missing_apiHost_or_path" },
|
|
887
|
-
};
|
|
888
|
-
}
|
|
889
|
-
|
|
890
1126
|
try {
|
|
891
|
-
const result = await probe(
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
1127
|
+
const result = await probe(
|
|
1128
|
+
apiHost,
|
|
1129
|
+
path,
|
|
1130
|
+
userParams ?? {},
|
|
1131
|
+
{
|
|
1132
|
+
...(walkVersions === undefined ? {} : { walkVersions }),
|
|
1133
|
+
...(auth ? { auth } : {}),
|
|
1134
|
+
...(domain ? { domain } : {}),
|
|
1135
|
+
},
|
|
1136
|
+
ctx,
|
|
1137
|
+
);
|
|
896
1138
|
return {
|
|
897
1139
|
content: [{ type: "text", text: formatProbeResult(result) }],
|
|
898
1140
|
details: {
|
|
@@ -934,42 +1176,6 @@ export const apiProbeTool = defineTool({
|
|
|
934
1176
|
if (d?.error) {
|
|
935
1177
|
return new Text(theme.fg("error", `⚠ ${contentText(result, "?")}`), 0, 0);
|
|
936
1178
|
}
|
|
937
|
-
// Secrets first: the domain-scoped view is the primary output and is present
|
|
938
|
-
// for both the per-domain and combined (apiHost-no-domain) shapes. Only the
|
|
939
|
-
// bare call (no domain/apiHost) carries unscoped alone.
|
|
940
|
-
const secrets = d?.secrets as
|
|
941
|
-
| { domain: string; provisioned: string[] }
|
|
942
|
-
| undefined;
|
|
943
|
-
if (secrets) {
|
|
944
|
-
const text = theme.fg("accent", theme.bold("🔑 api-probe"));
|
|
945
|
-
return new Text(
|
|
946
|
-
appendFooter(
|
|
947
|
-
text +
|
|
948
|
-
` — secrets for ${secrets.domain} · ${secrets.provisioned.length} provisioned`,
|
|
949
|
-
expanded,
|
|
950
|
-
result,
|
|
951
|
-
theme,
|
|
952
|
-
1000,
|
|
953
|
-
),
|
|
954
|
-
0,
|
|
955
|
-
0,
|
|
956
|
-
);
|
|
957
|
-
}
|
|
958
|
-
const unscoped = d?.unscoped as string[] | undefined;
|
|
959
|
-
if (unscoped) {
|
|
960
|
-
const text = theme.fg("accent", theme.bold("🔑 api-probe"));
|
|
961
|
-
return new Text(
|
|
962
|
-
appendFooter(
|
|
963
|
-
text + ` — ${unscoped.length} unscoped domains`,
|
|
964
|
-
expanded,
|
|
965
|
-
result,
|
|
966
|
-
theme,
|
|
967
|
-
1000,
|
|
968
|
-
),
|
|
969
|
-
0,
|
|
970
|
-
0,
|
|
971
|
-
);
|
|
972
|
-
}
|
|
973
1179
|
const status = d?.status as number | undefined;
|
|
974
1180
|
const shape = d?.shape as ShapeSummary | null | undefined;
|
|
975
1181
|
|
|
@@ -1027,59 +1233,3 @@ export function formatProbeResult(r: ProbeResult): string {
|
|
|
1027
1233
|
lines.push(` ${DOCS_NUDGE.join("\n ")}`);
|
|
1028
1234
|
return lines.join("\n");
|
|
1029
1235
|
}
|
|
1030
|
-
|
|
1031
|
-
/** Store domains that are provisioned but not scoped to any guide.
|
|
1032
|
-
* Authoring-loop diagnostic: surfaces bootstrap + migration-orphan
|
|
1033
|
-
* secrets. Names only. */
|
|
1034
|
-
function unscopedStoreDomains(): string[] {
|
|
1035
|
-
return listDomains().filter((d) => findGuidesByDomain(d).length === 0);
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
function formatUnscopedDomains(domains: string[]): string {
|
|
1039
|
-
const lines: string[] = ["🗂 unscoped store domains (provisioned, no guide)"];
|
|
1040
|
-
lines.push(` ${domains.length > 0 ? domains.join(", ") : "(none)"}`);
|
|
1041
|
-
lines.push(" (names only — values never leave the store)");
|
|
1042
|
-
return lines.join("\n");
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
/** List mode: provisioned secret names for a domain (names only). */
|
|
1046
|
-
function listDomainSecrets(domain: string): {
|
|
1047
|
-
domain: string;
|
|
1048
|
-
provisioned: string[];
|
|
1049
|
-
declared?: string[];
|
|
1050
|
-
} {
|
|
1051
|
-
const provisioned = listNames(domain);
|
|
1052
|
-
const matches = findGuidesByDomain(domain);
|
|
1053
|
-
if (matches.length === 0) return { domain, provisioned };
|
|
1054
|
-
const declaredSet = new Set<string>();
|
|
1055
|
-
for (const { guide } of matches) {
|
|
1056
|
-
for (const n of [
|
|
1057
|
-
...(guide.auth.requires ?? []),
|
|
1058
|
-
...(guide.auth.optional ?? []),
|
|
1059
|
-
]) {
|
|
1060
|
-
declaredSet.add(n);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
const declared = [...declaredSet].sort();
|
|
1064
|
-
return { domain, provisioned, declared };
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
function formatSecretsResult(s: {
|
|
1068
|
-
domain: string;
|
|
1069
|
-
provisioned: string[];
|
|
1070
|
-
declared?: string[];
|
|
1071
|
-
}): string {
|
|
1072
|
-
const lines: string[] = [`🔑 secrets for ${s.domain}`];
|
|
1073
|
-
lines.push(
|
|
1074
|
-
` provisioned: ${s.provisioned.length > 0 ? s.provisioned.join(", ") : "(none)"}`,
|
|
1075
|
-
);
|
|
1076
|
-
if (s.declared !== undefined) {
|
|
1077
|
-
lines.push(
|
|
1078
|
-
` declared: ${s.declared.length > 0 ? s.declared.join(", ") : "(none)"}`,
|
|
1079
|
-
);
|
|
1080
|
-
const gaps = s.declared.filter((d) => !s.provisioned.includes(d));
|
|
1081
|
-
if (gaps.length > 0) lines.push(` gaps: ${gaps.join(", ")}`);
|
|
1082
|
-
}
|
|
1083
|
-
lines.push(" (names only — values never leave the store)");
|
|
1084
|
-
return lines.join("\n");
|
|
1085
|
-
}
|