pi-lean-host 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,338 @@
1
+ /**
2
+ * oauth-mint tool definition.
3
+ *
4
+ * The human-in-the-loop mint of the agent-driven OAuth2 bootstrap. The agent
5
+ * supplies all researched parameters (grant, tokenUrl, authorizeUrl, scopes as
6
+ * {name, description} pairs, client credentials as STORE NAMES); the tool
7
+ * does only what the agent cannot: fail-closed validation, store-name
8
+ * precheck, the token-URL confirm prompt (the human is the trust root for the
9
+ * secret-bearing destination) with the redirect-URI edit folded in as a
10
+ * third action (auth-code select: Confirm / Change redirect URI / Esc), the
11
+ * scopes checklist picker, the paste prompt
12
+ * (the redirect URL never enters the transcript), and the mint/stamp via the
13
+ * existing `mintAuthCodeToken` / `resolveAccessToken` machinery.
14
+ *
15
+ * Prompt order is deliberate (cheapest-to-cancel first): confirm/select →
16
+ * picker → paste. A cancel at the confirm/select, redirect-URI input, or
17
+ * picker never discards a completed browser
18
+ * authorization. Any cancel throws with the two-call `init … --code`
19
+ * escape-hatch hint (plain `/api oauth <domain> --code` cannot complete
20
+ * guide-less; bootstrap is guide-less by definition).
21
+ *
22
+ * Learn-gated: rides the existing `pi-lean-dimension.api-learn` ToolsetSpec —
23
+ * no new spec, no runtime re-gate (masking is the gate).
24
+ */
25
+
26
+ import { defineTool } from "@earendil-works/pi-coding-agent";
27
+ import { Type } from "@earendil-works/pi-ai";
28
+ import { Text } from "@earendil-works/pi-tui";
29
+ import {
30
+ buildSyntheticOAuth2Auth,
31
+ credentialNameGap,
32
+ grantedScopes,
33
+ mintFreshClientCredentials,
34
+ resolveProvisionedParentDomain,
35
+ slotOverwriteWarning,
36
+ OAuthTokenMissingError,
37
+ } from "../core/auth.js";
38
+ import type { SyntheticOAuth2Fields } from "../core/auth.js";
39
+ import { initFlagsFromFields } from "../core/oauth-command.js";
40
+ import {
41
+ confirmTokenUrl,
42
+ mintAuthCodeToken,
43
+ REDIRECT_URI,
44
+ } from "../core/oauth-flow.js";
45
+ import { readToken } from "../core/oauth-store.js";
46
+ import { pickChecklist } from "../core/select-picker.js";
47
+ import { appendFooter } from "./utils.js";
48
+
49
+ /** The exact two-call completion command for the escape-hatch hint. */
50
+ export function escapeHatchCommand(
51
+ domain: string,
52
+ fields: SyntheticOAuth2Fields,
53
+ ): string {
54
+ const flags = initFlagsFromFields(fields);
55
+ return `/api oauth init ${domain} ${flags.join(" ")} --code <redirect-url-or-code>`;
56
+ }
57
+
58
+ function cancelledError(domain: string, fields: SyntheticOAuth2Fields): Error {
59
+ return new Error(
60
+ `OAuth2 mint cancelled — nothing was provisioned. ` +
61
+ `Stop and ask the user how to proceed (a re-call starts a FRESH authorization). ` +
62
+ `If they already authorized in their browser, they can finish without re-consenting via: ` +
63
+ escapeHatchCommand(domain, fields),
64
+ );
65
+ }
66
+
67
+ export const oauthMintTool = defineTool({
68
+ name: "oauth-mint",
69
+ label: "OAuth Mint",
70
+ description:
71
+ "Mint an OAuth2 token for a domain and stamp the token store — call AFTER you have researched " +
72
+ "the provider's OAuth2 shape; this tool performs no discovery. Prompts the human to confirm " +
73
+ "the token endpoint, select scopes, and paste the redirect URL; returns granted scopes + store domain.",
74
+
75
+ promptGuidelines: [
76
+ "The agent researches the provider's OAuth2 shape; this tool does no discovery — supply grant, tokenUrl, authorizeUrl, scopes, and credentials from your research.",
77
+ "Never for static-key / API-key providers — use api-probe's inline auth or /api secrets instead.",
78
+ "clientId / clientSecret are secrets-store NAMES, never literal values.",
79
+ "If the user cancels a prompt, STOP and ask how to proceed — never auto-re-call. A re-call starts a fresh authorization; the cancel error prints the /api oauth init … --code two-call form to finish without re-consenting.",
80
+ ],
81
+
82
+ parameters: Type.Object({
83
+ domain: Type.String({
84
+ description:
85
+ "Token-store domain (e.g. 'openstreetmap.org'). Normalized against provisioned secrets; the token stamps there.",
86
+ }),
87
+ grant: Type.Union(
88
+ [Type.Literal("client_credentials"), Type.Literal("authorization_code")],
89
+ {
90
+ description:
91
+ "OAuth2 grant. authorization_code = interactive paste dance (PKCE).",
92
+ },
93
+ ),
94
+ tokenUrl: Type.String({
95
+ description:
96
+ "The provider's token endpoint (exchanges credentials/codes for tokens).",
97
+ }),
98
+ clientId: Type.String({
99
+ description:
100
+ "client-id STORE NAME from the secrets store — never a literal value.",
101
+ }),
102
+ clientSecret: Type.Optional(
103
+ Type.String({
104
+ description:
105
+ "client-secret STORE NAME; required for client_credentials, omit for PKCE public clients.",
106
+ }),
107
+ ),
108
+ authorizeUrl: Type.Optional(
109
+ Type.String({
110
+ description: "Authorization endpoint (authorization_code only).",
111
+ }),
112
+ ),
113
+ scopes: Type.Optional(
114
+ Type.Array(
115
+ Type.Object({
116
+ name: Type.String({
117
+ description: "Scope name as the provider defines it.",
118
+ }),
119
+ description: Type.Optional(
120
+ Type.String({
121
+ description:
122
+ "One line on what granting it allows — shown in the picker.",
123
+ }),
124
+ ),
125
+ }),
126
+ {
127
+ description:
128
+ "Scopes to offer the human as a ✓/○ checklist (research what each means).",
129
+ },
130
+ ),
131
+ ),
132
+ tokenEndpointAuthMethod: Type.Optional(
133
+ Type.Union(
134
+ [
135
+ Type.Literal("client_secret_basic"),
136
+ Type.Literal("client_secret_post"),
137
+ Type.Literal("none"),
138
+ ],
139
+ {
140
+ description:
141
+ "How the client authenticates at the token endpoint (default client_secret_post).",
142
+ },
143
+ ),
144
+ ),
145
+ redirectUri: Type.Optional(
146
+ Type.String({
147
+ description:
148
+ "Redirect URI registered in the user's OAuth app (authorization_code only; default http://127.0.0.1/callback). Some providers constrain the spelling (Twitch: https or localhost; OSM: unencrypted must be 127.0.0.1) — supply the user's registered URI when it differs from the default. Proposed in the combined endpoint-confirm dialog; the human can change it inline there.",
149
+ }),
150
+ ),
151
+ }),
152
+
153
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
154
+ const p = params as {
155
+ domain: string;
156
+ grant: "client_credentials" | "authorization_code";
157
+ tokenUrl: string;
158
+ clientId: string;
159
+ clientSecret?: string;
160
+ authorizeUrl?: string;
161
+ scopes?: { name: string; description?: string }[];
162
+ tokenEndpointAuthMethod?:
163
+ | "client_secret_basic"
164
+ | "client_secret_post"
165
+ | "none";
166
+ redirectUri?: string;
167
+ };
168
+
169
+ // H1 — one guard at the top; no degraded half-flow.
170
+ if (!ctx.hasUI) {
171
+ throw new Error(
172
+ "oauth-mint requires an interactive session — use the `/api oauth init <domain> --grant … --token-url …` flags instead, or run pi interactively.",
173
+ );
174
+ }
175
+
176
+ // Fail-closed validation of ALL params before any prompt (throws on any
177
+ // invalid combination — the return value is rebuilt after scope picking).
178
+ const fields: SyntheticOAuth2Fields = {
179
+ grant: p.grant,
180
+ tokenUrl: p.tokenUrl,
181
+ clientId: p.clientId,
182
+ ...(p.clientSecret === undefined ? {} : { clientSecret: p.clientSecret }),
183
+ ...(p.authorizeUrl === undefined ? {} : { authorizeUrl: p.authorizeUrl }),
184
+ ...(p.scopes === undefined ? {} : { scopes: p.scopes.map((s) => s.name) }),
185
+ ...(p.tokenEndpointAuthMethod === undefined
186
+ ? {}
187
+ : { tokenEndpointAuthMethod: p.tokenEndpointAuthMethod }),
188
+ };
189
+ buildSyntheticOAuth2Auth(fields);
190
+
191
+ // Token-store keying: same longest-provisioned-parent normalization the
192
+ // init wizard and probe use (matched against the SECRETS store).
193
+ const storeDomain = resolveProvisionedParentDomain(p.domain);
194
+
195
+ // Store-name precheck BEFORE any prompt.
196
+ const gap = credentialNameGap(
197
+ storeDomain,
198
+ fields.clientId,
199
+ fields.clientSecret,
200
+ );
201
+ if (gap !== null) throw new Error(gap);
202
+
203
+ // Token-URL confirm — the FIRST prompt, both grants, before any
204
+ // exchange: tokenUrl is the one agent-supplied parameter that receives
205
+ // secret values, and the agent's research source is untrusted.
206
+ //
207
+ // Redirect URI — human-editable override of the RFC 8252 loopback
208
+ // default (auth-code only). The human owns their OAuth app
209
+ // registration, so while the agent proposes a value, the human can
210
+ // correct it inline before consenting — it decides where the provider
211
+ // sends the auth code (same trust class as the token endpoint).
212
+ // Auth-code folds both into ONE select: "Confirm" accepts endpoint +
213
+ // redirect URI as proposed (the common case — no extra dialog);
214
+ // "Change redirect URI" drops to an input, then loops back so the
215
+ // updated value is visible before consenting. Esc/undefined cancels.
216
+ let redirectUri = p.redirectUri ?? REDIRECT_URI;
217
+ if (p.grant === "authorization_code") {
218
+ for (;;) {
219
+ const choice = await ctx.ui.select(
220
+ `Confirm the token endpoint for '${storeDomain}' — exchange credentials at ${p.tokenUrl} (client: '${p.clientId}'; the client secret is sent to this URL). Redirect URI: ${redirectUri}`,
221
+ ["Confirm", "Change redirect URI"],
222
+ );
223
+ if (choice === undefined) throw cancelledError(p.domain, fields);
224
+ if (choice === "Confirm") break;
225
+ const entered = await ctx.ui.input(
226
+ `Redirect URI for '${storeDomain}' — where the provider sends the auth code (must match your app registration). Proposed: ${redirectUri}`,
227
+ `Enter to keep ${redirectUri}, or type an override`,
228
+ );
229
+ if (entered === undefined) throw cancelledError(p.domain, fields);
230
+ if (entered !== "") redirectUri = entered;
231
+ }
232
+ } else if (!(await confirmTokenUrl(ctx, storeDomain, p.tokenUrl, p.clientId)))
233
+ throw cancelledError(p.domain, fields);
234
+
235
+ // Scopes checklist — the human's affirmative grant. No scopes → skip.
236
+ let pickedScopes: string[] | undefined;
237
+ if (p.scopes !== undefined && p.scopes.length > 0) {
238
+ const picked = await pickChecklist(
239
+ ctx,
240
+ `Scopes to grant for '${storeDomain}'`,
241
+ p.scopes.map((s) => ({
242
+ value: s.name,
243
+ label: s.name,
244
+ ...(s.description === undefined ? {} : { description: s.description }),
245
+ })),
246
+ );
247
+ if (picked === undefined) throw cancelledError(p.domain, fields);
248
+ pickedScopes = picked;
249
+ }
250
+
251
+ const finalFields: SyntheticOAuth2Fields = {
252
+ ...fields,
253
+ ...(pickedScopes === undefined ? {} : { scopes: pickedScopes }),
254
+ };
255
+ const finalSynthetic = buildSyntheticOAuth2Auth(finalFields);
256
+
257
+ try {
258
+ if (finalSynthetic.grant === "client_credentials") {
259
+ // Mint-time overwrite warning (shared mitigation — see
260
+ // slotOverwriteWarning): mintFreshClientCredentials is ui-free,
261
+ // so the caller renders it. The auth-code arm warns inside
262
+ // mintAuthCodeToken instead — do not double-warn here.
263
+ const overwrite = slotOverwriteWarning(finalSynthetic, storeDomain);
264
+ if (overwrite) ctx.ui.notify(overwrite, "warning");
265
+ // Bootstrap wants a fresh mint, not a cached token (mirrors the
266
+ // init wizard / --refresh path). Slot-scoped delete inside the
267
+ // shared helper: a bare domain delete would leave a stale
268
+ // prior-grant/prior-issuer slot surviving the re-mint — the exact
269
+ // clobber the slot keying fixes.
270
+ await mintFreshClientCredentials(finalSynthetic, storeDomain);
271
+ } else {
272
+ // Prints the authorize URL + paste prompt (retry loop inside);
273
+ // cancel lands in the OAuthTokenMissingError handler below.
274
+ await mintAuthCodeToken(finalSynthetic, storeDomain, ctx, { redirectUri });
275
+ }
276
+ } catch (err) {
277
+ if (err instanceof OAuthTokenMissingError)
278
+ throw cancelledError(p.domain, fields);
279
+ throw err;
280
+ }
281
+
282
+ // Report what the provider actually echoed, not what was requested —
283
+ // a provider may grant a subset. Absent scope → requested scopes with
284
+ // an "(assumed)" marker (RFC 6749 §5.1, same convention as api-store).
285
+ const minted = readToken(
286
+ storeDomain,
287
+ finalSynthetic.grant,
288
+ finalSynthetic.tokenUrl,
289
+ );
290
+ const requested = pickedScopes ?? [];
291
+ const { scopes: scopeList, assumed } = grantedScopes(
292
+ minted?.scope,
293
+ requested,
294
+ );
295
+ let scopeLine: string;
296
+ if (!assumed && scopeList.length > 0) {
297
+ scopeLine = ` Granted scopes: ${scopeList.join(", ")}.`;
298
+ } else if (requested.length > 0) {
299
+ scopeLine = ` Requested scopes (assumed granted): ${requested.join(", ")}.`;
300
+ } else {
301
+ scopeLine = " No scopes requested.";
302
+ }
303
+ const details: Record<string, unknown> = {
304
+ mode: "minted",
305
+ domain: storeDomain,
306
+ grant: finalSynthetic.grant,
307
+ };
308
+ if (scopeList.length > 0) details.scopes = scopeList;
309
+ return {
310
+ content: [
311
+ {
312
+ type: "text",
313
+ text:
314
+ `🔑 OAuth2 token minted for '${storeDomain}' (grant ${finalSynthetic.grant}).${scopeLine}\n` +
315
+ `Report the granted scopes and store domain to the user.`,
316
+ },
317
+ ],
318
+ details,
319
+ };
320
+ },
321
+
322
+ renderCall(args, theme, _context) {
323
+ const parts = [theme.fg("toolTitle", theme.bold("oauth-mint "))];
324
+ const a = args as { domain?: string; grant?: string };
325
+ parts.push(theme.fg("accent", `"${a.domain ?? "?"}"`));
326
+ if (a.grant) parts.push(theme.fg("dim", a.grant));
327
+ return new Text(parts.join(" "), 0, 0);
328
+ },
329
+
330
+ renderResult(result, { expanded }, theme, _context) {
331
+ const d = result.details as Record<string, unknown> | undefined;
332
+ const grant = d?.grant as string | undefined;
333
+ const text =
334
+ theme.fg("accent", theme.bold("🔑 minted")) +
335
+ theme.fg("dim", ` — ${d?.domain ?? "?"} (${grant ?? "?"})`);
336
+ return new Text(appendFooter(text, expanded, result, theme, 400), 0, 0);
337
+ },
338
+ });
package/tools/utils.ts CHANGED
@@ -19,7 +19,7 @@ export function contentText(
19
19
  * Append a dim-styled content preview to an in-progress result string,
20
20
  * with a "more chars" suffix when the content exceeds the given limit.
21
21
  */
22
- export function renderExpandedText(
22
+ function renderExpandedText(
23
23
  text: string,
24
24
  theme: { fg: (c: ThemeColor, t: string) => string },
25
25
  content: string,
@@ -1,118 +0,0 @@
1
- /**
2
- * Ship-manifest verification helper (vendored from pi-lean-portal).
3
- *
4
- * Walks a package directory for production `.ts` files and compares them to
5
- * the `files` array in `package.json`. Used by `ship-manifest.test.ts` to
6
- * prove the published npm tarball contains every module the package imports
7
- * at runtime — with a negative assertion that `api-guides/` and helper .ts
8
- * files are absent (GitHub-only recipes).
9
- *
10
- * Vendored (not imported from portal) so the host-only boundary stays intact.
11
- */
12
-
13
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
14
- import { dirname, relative, resolve } from "node:path";
15
- import { fileURLToPath } from "node:url";
16
-
17
- const DEFAULT_SKIP_DIRS = ["node_modules", "docs", "__tests__"];
18
- const SKIP_FILES = new Set<string>(["test-fixtures.ts"]);
19
- /** Entries that won't exist on disk at rest but are valid (generated at pack time). */
20
- const SKIP_STALE = new Set(["LICENSE"]);
21
-
22
- export interface ShipManifestResult {
23
- declared: readonly string[];
24
- onDisk: readonly string[];
25
- missing: readonly string[];
26
- stale: readonly string[];
27
- }
28
-
29
- export function verifyShipManifest(
30
- packageDirOrUrl: string,
31
- opts?: { skipDirs?: readonly string[] },
32
- ): ShipManifestResult {
33
- const packageDir = packageDirOrUrl.startsWith("file:")
34
- ? dirname(fileURLToPath(packageDirOrUrl))
35
- : packageDirOrUrl;
36
- const skipDirs = new Set([...DEFAULT_SKIP_DIRS, ...(opts?.skipDirs ?? [])]);
37
- let pkgRaw: string;
38
- try {
39
- pkgRaw = readFileSync(resolve(packageDir, "package.json"), "utf8");
40
- } catch (err) {
41
- throw new Error(
42
- `verifyShipManifest: could not read package.json under "${packageDir}": ${
43
- err instanceof Error ? err.message : String(err)
44
- }`,
45
- );
46
- }
47
- let pkg: { files?: string[] };
48
- try {
49
- pkg = JSON.parse(pkgRaw) as { files?: string[] };
50
- } catch (err) {
51
- throw new Error(
52
- `verifyShipManifest: invalid package.json under "${packageDir}": ${
53
- err instanceof Error ? err.message : String(err)
54
- }`,
55
- );
56
- }
57
- const declared = pkg.files ?? [];
58
- const exactFiles = new Set<string>();
59
- const dirPrefixes: string[] = [];
60
- for (const entry of declared) {
61
- if (entry.startsWith("!")) continue;
62
- if (entry.endsWith("/")) dirPrefixes.push(entry);
63
- else if (isDirOnDisk(packageDir, entry)) dirPrefixes.push(`${entry}/`);
64
- else exactFiles.add(entry);
65
- }
66
-
67
- const onDisk = walkProductionTs(packageDir, packageDir, skipDirs);
68
- const missing = onDisk.filter((f) => !isCovered(f, exactFiles, dirPrefixes));
69
- const stale = declared.filter(
70
- (entry) =>
71
- !entry.startsWith("!") &&
72
- !SKIP_STALE.has(entry) &&
73
- !existsSync(resolve(packageDir, entry)),
74
- );
75
-
76
- return { declared, onDisk, missing, stale };
77
- }
78
-
79
- function isDirOnDisk(packageDir: string, entry: string): boolean {
80
- try {
81
- return statSync(resolve(packageDir, entry)).isDirectory();
82
- } catch {
83
- return false;
84
- }
85
- }
86
-
87
- function isCovered(
88
- file: string,
89
- exactFiles: Set<string>,
90
- dirPrefixes: readonly string[],
91
- ): boolean {
92
- if (exactFiles.has(file)) return true;
93
- for (const prefix of dirPrefixes) {
94
- if (file.startsWith(prefix)) return true;
95
- }
96
- return false;
97
- }
98
-
99
- function walkProductionTs(
100
- root: string,
101
- dir: string,
102
- skipDirs: Set<string>,
103
- ): string[] {
104
- const out: string[] = [];
105
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
106
- if (entry.name.startsWith(".")) continue;
107
- if (entry.isDirectory() && skipDirs.has(entry.name)) continue;
108
- const abs = resolve(dir, entry.name);
109
- if (entry.isDirectory()) {
110
- out.push(...walkProductionTs(root, abs, skipDirs));
111
- continue;
112
- }
113
- if (!entry.isFile() || !entry.name.endsWith(".ts")) continue;
114
- if (entry.name.endsWith(".test.ts") || SKIP_FILES.has(entry.name)) continue;
115
- out.push(relative(root, abs));
116
- }
117
- return out;
118
- }
package/tools/index.ts DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * Tool definitions barrel — exports all 5 tool definitions for registration.
3
- */
4
- export { apiGuideTool } from "./api-guide.js";
5
- export { apiFetchTool } from "./api-fetch.js";
6
- export { apiLearnTool } from "./api-learn.js";
7
- export { apiProbeTool } from "./api-probe.js";
8
- export { apiScaffoldTool } from "./api-scaffold.js";