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.
@@ -5,9 +5,9 @@
5
5
  * commands to enable/disable API tools in the system prompt.
6
6
  *
7
7
  * Three states: on (api-guide + api-fetch), learn (on + api-learn + api-probe +
8
- * api-scaffold), off (all disabled).
8
+ * api-scaffold + api-store + oauth-mint), off (all disabled).
9
9
  *
10
- * Starts enabled (api-guide + api-fetch on, api-learn + api-probe + api-scaffold off), mirroring
10
+ * Starts enabled (api-guide + api-fetch on; api-learn + api-probe + api-scaffold + api-store + oauth-mint off), mirroring
11
11
  * portal's browser toggle. Both defaults are overridable via the
12
12
  * `toolsetDefaults` settings tier read by pi-tool-masking. The /api toggle
13
13
  * is an independent peer: it composes freely with /web (portal's toggle)
@@ -30,18 +30,19 @@ import {
30
30
  import type { ToolsetSpec } from "pi-tool-masking";
31
31
  import { handleHelpersSubcommand } from "./helpers-command.js";
32
32
  import { handleSecretsSubcommand } from "./secrets-command.js";
33
+ import { handleOauthSubcommand } from "./oauth-command.js";
33
34
  import { handleVerifySubcommand } from "./verify-command.js";
34
35
  import { handleDeleteSubcommand } from "./delete-command.js";
35
36
  import { loadAllGuides } from "./guide-store.js";
36
37
  import { getAllHelpers, getDisabledHelperDomains } from "./local-helpers.js";
38
+ import { resolveProvisionedParentDomain } from "./auth.js";
39
+ import { listNames } from "./secrets-store.js";
37
40
 
38
- // Focus-mode guard: refuse actuating subcommands while the library holds the
39
- // line — inclusion mode or allowlist focus (an upstream pi-tool-masking
40
- // consumer). Either way a sibling toggle must not write a focus-
41
- // indistinguishable {enabled} entry.
41
+ // Focus-mode guard: refuse actuating subcommands while allowlist focus holds
42
+ // (an upstream pi-tool-masking consumer). A sibling toggle must not write a
43
+ // focus-indistinguishable {enabled} entry.
42
44
  function isFocusHolding(): boolean {
43
- const mode = getDefaultResolutionMode();
44
- return mode === "inclusion" || mode === "allowlist";
45
+ return getDefaultResolutionMode() === "allowlist";
45
46
  }
46
47
 
47
48
  // ---- Toolset specs -----------------------------------------------
@@ -54,12 +55,26 @@ const HOST_API_SPEC: ToolsetSpec = {
54
55
 
55
56
  const HOST_API_LEARN_SPEC: ToolsetSpec = {
56
57
  id: "pi-lean-dimension.api-learn",
57
- names: new Set(["api-learn", "api-probe", "api-scaffold"]),
58
+ names: new Set([
59
+ "api-learn",
60
+ "api-probe",
61
+ "api-scaffold",
62
+ "api-store",
63
+ "oauth-mint",
64
+ ]),
58
65
  persistKey: "toolset-state:pi-lean-dimension.api-learn",
59
66
  defaultEnabled: false,
60
67
  requires: ["pi-lean-dimension.api"],
61
68
  };
62
69
 
70
+ /** The learn toolset's tool names, rendered for status/notify strings —
71
+ * derived from the spec so the enumeration can't rot when tools are added. */
72
+ function learnToolNames(): string {
73
+ return [...HOST_API_LEARN_SPEC.names]
74
+ .sort((a, b) => a.localeCompare(b))
75
+ .join(" + ");
76
+ }
77
+
63
78
  // ---- Status bar cached state (derived from library events) ------
64
79
 
65
80
  /** @internal Last known api-tools toggle state for status bar rendering. */
@@ -76,9 +91,9 @@ export function getApiToggleState(): boolean {
76
91
  }
77
92
 
78
93
  /**
79
- * Learn-mode gate for api-probe's `listSecrets` discovery. Returns the
80
- * cached learn state synced on session_start and toolset events. A hard
81
- * runtime gate (not just toolset masking) so a `listSecrets` call under
94
+ * Learn-mode gate for the authoring tools (api-probe, api-store). Returns
95
+ * the cached learn state synced on session_start and toolset events. A hard
96
+ * runtime gate (not just toolset masking) so a store-inspection call under
82
97
  * `/api on` is refused even if the tool is somehow reachable.
83
98
  */
84
99
  export function isApiLearnEnabled(): boolean {
@@ -137,6 +152,23 @@ function renderApiGlyph(
137
152
 
138
153
  // ---- /api status command ------------------------------------------
139
154
 
155
+ /** The /api subcommand menu — one source shared by `/api status` and the
156
+ * bare/unknown-subcommand renderer so the two can't drift. */
157
+ function apiCommandMenu(): string[] {
158
+ return [
159
+ ` /api on enable api-guide + api-fetch`,
160
+ ` /api learn enable all seven tools (adds ${learnToolNames()})`,
161
+ ` /api off disable all API tools`,
162
+ ` /api status detailed status (guides, helpers)`,
163
+ ` /api helpers list local helpers`,
164
+ ` /api secrets list/provision stored secrets (names only)`,
165
+ ` /api oauth provision/inspect/revoke OAuth2 tokens (client_credentials + auth-code/PKCE)`,
166
+ ` /api verify verify a guide's ops against its live API (stamps verified)`,
167
+ ` /api bootstrap agent-driven OAuth2 bootstrap (injects a research brief; enables learn)`,
168
+ ` /api delete delete a guide directory (human-typed recovery gesture)`,
169
+ ];
170
+ }
171
+
140
172
  function handleStatusSubcommand(
141
173
  apiOn: boolean,
142
174
  learnOn: boolean,
@@ -148,9 +180,7 @@ function handleStatusSubcommand(
148
180
  } else {
149
181
  state = "off";
150
182
  }
151
- const learnFlag = learnOn
152
- ? "✅ on (api-learn + api-probe + api-scaffold available)"
153
- : "❌ off";
183
+ const learnFlag = learnOn ? `✅ on (${learnToolNames()} available)` : "❌ off";
154
184
 
155
185
  const allGuides = loadAllGuides();
156
186
  const guideCount = Object.keys(allGuides.guides).length;
@@ -184,18 +214,181 @@ function handleStatusSubcommand(
184
214
  lines.push(` Run /api helpers to list them.`);
185
215
  }
186
216
 
217
+ lines.push(``, ...apiCommandMenu());
187
218
  lines.push(
188
219
  ``,
189
- ` /api on enable api-guide + api-fetch`,
190
- ` /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)`,
191
- ` /api off disable all API tools`,
192
- ` /api verify verify a guide's ops against its live API (stamps verified)`,
193
- ` /api delete delete a guide directory (human-typed recovery gesture)`,
220
+ ` Focus mode: /api on|off|learn are refused while focus holds;`,
221
+ ` /api bootstrap flips learn mode, so enabling it is blocked there too.`,
194
222
  );
195
223
 
196
224
  ctx.ui.notify(lines.join("\n"), "info");
197
225
  }
198
226
 
227
+ // ---- /api bootstrap: agent-driven OAuth2 bootstrap ------------------
228
+
229
+ const BOOTSTRAP_USAGE = [
230
+ "Usage: /api bootstrap oauth <domain> <spec>",
231
+ "",
232
+ " Hand OAuth2 bootstrap for <domain> to the agent: composes a research brief",
233
+ " from <spec> (a provider docs URL or file), injects it as a follow-up turn,",
234
+ " and exits — the agent researches the provider's OAuth2 shape, then calls the",
235
+ " oauth-mint tool, which walks the human through confirm → scopes → paste.",
236
+ "",
237
+ " Requires an interactive session (the mint prompts the human).",
238
+ " Enables learn mode when off (blocked by focus mode — exit focus first).",
239
+ "",
240
+ " Available modes: oauth",
241
+ ].join("\n");
242
+
243
+ /**
244
+ * The research brief injected via `pi.sendUserMessage(brief, {deliverAs:
245
+ * "followUp"})`, with {domain} / {spec} filled from the command args, plus
246
+ * the conditional provisioned-secrets sentence when the store has names for
247
+ * the domain. Inject-and-exit: the
248
+ * command's entire output is this one message.
249
+ */
250
+ export function composeBootstrapBrief(
251
+ domain: string,
252
+ spec: string,
253
+ provisionedSecrets?: string[],
254
+ ): string {
255
+ // Names only (audit rule, same as /api secrets) — lets the agent skip the
256
+ // failed oauth-mint precheck call when credentials are already provisioned.
257
+ const provisionedNote = provisionedSecrets?.length
258
+ ? `\nProvisioned secret names for this domain: ${provisionedSecrets.map((n) => `\`${n}\``).join(", ")} — use these store names (pick the ones matching the provider's client-id/secret semantics).`
259
+ : "";
260
+ return `**OAuth2 bootstrap for \`${domain}\` — research then mint.**
261
+
262
+ Your task: bootstrap OAuth2 access for the API at domain \`${domain}\`. The
263
+ user has pointed you at the provider's documentation as the starting source.
264
+ Learn mode is on — you'll need it to author the
265
+ guide afterwards.
266
+
267
+ **Step 1 — Research.** Read \`${spec}\` (a URL or file path; if it references
268
+ other pages or files, follow them as needed). From the docs, determine:
269
+
270
+ - the OAuth2 **grant type** this provider expects for a read-only CLI client
271
+ (\`client_credentials\` or \`authorization_code\`),
272
+ - the **token URL** (the endpoint that exchanges credentials/codes for
273
+ tokens),
274
+ - the **authorize URL** (authorization_code only),
275
+ - the **scopes** the provider defines and what each one grants — you'll
276
+ offer these to the user as a selectable list with short descriptions, so
277
+ research what each scope means, not just its name. Request the narrowest
278
+ set that covers read operations: prefer a read-only variant
279
+ (\`*:readonly\` or equivalent) when one exists, omit write-only scopes
280
+ entirely, and include a write-capable scope only when no read-only
281
+ variant grants the needed access — and say so in that scope's
282
+ description.
283
+
284
+ **Step 2 — Mint.** Call the \`oauth-mint\` tool with what you found: \`domain\`,
285
+ \`grant\`, \`tokenUrl\`, \`authorizeUrl\` (auth-code only), \`clientId\` and
286
+ optional \`clientSecret\` as **secrets-store names** (never literal values —
287
+ if the needed names aren't provisioned, the tool will tell you and the user
288
+ will provision via \`/api secrets ${domain} <name>\`), the optional
289
+ \`tokenEndpointAuthMethod\` (\`client_secret_post\` is the default; some
290
+ providers require \`client_secret_basic\` — research which), and \`scopes\` as
291
+ \`{name, description}\` pairs for the human to pick from.${provisionedNote}
292
+
293
+ **Boundaries.** Do not fetch or mint anything yourself — \`oauth-mint\`
294
+ performs the consent flow with the user. Do not author the guide yet; that
295
+ comes after a successful mint. If the user cancels a prompt, stop and ask them how to proceed — never
296
+ auto-re-prompt a human who just declined. If they already authorized before
297
+ cancelling, they can finish without re-consenting — ask the user to run
298
+ the two-call form the tool's cancel error printed:
299
+ \`/api oauth init ${domain} --grant <grant> --token-url <tokenUrl>
300
+ [--authorize-url <authorizeUrl>] --client-id <store name> --code
301
+ <redirect-url>\`. Before calling \`oauth-mint\`,
302
+ **verify that both the authorize URL and the token URL belong to
303
+ \`${domain}\`'s provider** — the token URL is where the client secret is sent,
304
+ so if the docs point either endpoint somewhere that doesn't match, stop and
305
+ ask the user rather than proceeding. (The tool also asks the human to
306
+ confirm the token URL before the exchange — that check is yours, this is a
307
+ second pair of eyes, not a substitute.)
308
+
309
+ When the mint succeeds, report the granted scopes and store domain to the
310
+ user.`;
311
+ }
312
+
313
+ /**
314
+ * `/api bootstrap oauth <domain> <spec>` — inject-and-exit (F1–F5, H1).
315
+ * hooks close over the toolsets created in initApiToggle.
316
+ */
317
+ async function handleBootstrapSubcommand(
318
+ args: string,
319
+ hooks: { learnEnabled: () => boolean; enableLearn: () => void },
320
+ pi: ExtensionAPI,
321
+ ctx: ExtensionCommandContext,
322
+ ): Promise<void> {
323
+ const parts = args.trim().split(/\s+/).filter(Boolean);
324
+ const mode = parts[0]?.toLowerCase();
325
+ if (!mode) {
326
+ ctx.ui.notify(
327
+ `Usage: /api bootstrap <mode> <args…>\n\n${BOOTSTRAP_USAGE}`,
328
+ "info",
329
+ );
330
+ return;
331
+ }
332
+ if (mode !== "oauth") {
333
+ ctx.ui.notify(
334
+ `Unknown bootstrap mode: "${mode}".\n\n${BOOTSTRAP_USAGE}`,
335
+ "warning",
336
+ );
337
+ return;
338
+ }
339
+ const domain = parts[1];
340
+ const spec = parts.slice(2).join(" ");
341
+ if (!domain || !spec) {
342
+ ctx.ui.notify(
343
+ `Usage: /api bootstrap oauth <domain> <spec> — both required, domain first.\n` +
344
+ ` <spec> is any provider docs URL or file for the agent to research.\n` +
345
+ ` Example: /api bootstrap oauth openstreetmap.org https://wiki.openstreetmap.org/wiki/OAuth`,
346
+ "warning",
347
+ );
348
+ return;
349
+ }
350
+
351
+ // H1 (command side): the downstream oauth-mint prompts all need ctx.hasUI,
352
+ // so injecting a brief into a headless session would dead-end at the
353
+ // first prompt.
354
+ if (!ctx.hasUI) {
355
+ ctx.ui.notify(
356
+ "/api bootstrap requires an interactive session — the downstream oauth-mint prompts need one. " +
357
+ "Use the headless flags instead: /api oauth init <domain> --grant … --token-url …",
358
+ "warning",
359
+ );
360
+ return;
361
+ }
362
+
363
+ // F5: auto-enable learn when off (same as the user running /api learn);
364
+ // loud fail if the focus-mode guard blocks the enable. Learn stays off.
365
+ if (!hooks.learnEnabled()) {
366
+ if (isFocusHolding()) {
367
+ ctx.ui.notify(
368
+ "Focus mode (allowlist) is active — bootstrap needs to enable learn mode, which can't be toggled while focus is holding the line. Exit focus there first.",
369
+ "warning",
370
+ );
371
+ return;
372
+ }
373
+ hooks.enableLearn();
374
+ // A mode flip the user didn't ask for must not be silent (inject-and-exit
375
+ // otherwise produces no output).
376
+ ctx.ui.notify(
377
+ "📖 Learn mode enabled (bootstrap needs api-learn to author the guide afterwards).",
378
+ "info",
379
+ );
380
+ }
381
+
382
+ const brief = composeBootstrapBrief(
383
+ domain,
384
+ spec,
385
+ // Parent-domain normalization shared with probe/oauth-mint store
386
+ // resolution — names only, never values.
387
+ listNames(resolveProvisionedParentDomain(domain)),
388
+ );
389
+ pi.sendUserMessage(brief, { deliverAs: "followUp" });
390
+ }
391
+
199
392
  // ---- Extension factory -------------------------------------------
200
393
 
201
394
  export default function initApiToggle(pi: ExtensionAPI): void {
@@ -221,24 +414,20 @@ export default function initApiToggle(pi: ExtensionAPI): void {
221
414
  pi.registerCommand("api", {
222
415
  description:
223
416
  "Enable/disable API tools. " +
224
- "Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help] | verify <domain> [guide] [--force] | delete <domain> [guide]",
417
+ "Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help] | verify <domain> [guide] [--force] | delete <domain> [guide] | oauth <domain> … | bootstrap oauth <domain> <spec>",
225
418
  handler: async (args: string, ctx: ExtensionCommandContext) => {
226
419
  const trimmed = args.trim();
227
420
  const parts = trimmed.split(/\s+/);
228
421
  const sub = parts[0]?.toLowerCase() ?? "";
229
422
  const rest = parts.slice(1).join(" ");
230
423
 
231
- // Focus-mode guard: refuse actuating subcommands while the library
232
- // holds the line — either inclusion mode or allowlist focus (an
233
- // upstream pi-tool-masking consumer). Either way a sibling toggle
234
- // must not write a focus-indistinguishable {enabled} entry.
424
+ // Focus-mode guard: refuse actuating subcommands while allowlist
425
+ // focus holds (an upstream pi-tool-masking consumer) — a sibling
426
+ // toggle must not write a focus-indistinguishable {enabled} entry.
235
427
  // Read-only subcommands (status/helpers/bare /api) stay unguarded.
236
428
  if (["on", "off", "learn"].includes(sub) && isFocusHolding()) {
237
- const inInclusion = getDefaultResolutionMode() === "inclusion";
238
429
  ctx.ui.notify(
239
- inInclusion
240
- ? "Another plugin has active inclusion mode — this toolset can't be toggled while inclusion is holding the line. Deactivate it there first."
241
- : "Focus mode (allowlist) is active — this toolset can't be toggled while focus is holding the line. Exit focus there first.",
430
+ "Focus mode (allowlist) is active — this toolset can't be toggled while focus is holding the line. Exit focus there first.",
242
431
  "warning",
243
432
  );
244
433
  return;
@@ -249,7 +438,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
249
438
  apiToolset.enable(pi);
250
439
  learnToolset.disable(pi);
251
440
  ctx.ui.notify(
252
- "📡 API tools enabled. /api learn to make api-learn + api-probe + api-scaffold available.",
441
+ `📡 API tools enabled. /api learn to make ${learnToolNames()} available.`,
253
442
  "info",
254
443
  );
255
444
  return;
@@ -264,7 +453,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
264
453
  case "learn": {
265
454
  learnToolset.enable(pi); // cascades api on via requires
266
455
  ctx.ui.notify(
267
- "📖 api-learn + api-probe + api-scaffold tools are now available. " +
456
+ `📖 ${learnToolNames()} tools are now available. ` +
268
457
  "Agent will discover shapes and save/update guides when asked.",
269
458
  "info",
270
459
  );
@@ -292,6 +481,13 @@ export default function initApiToggle(pi: ExtensionAPI): void {
292
481
  return;
293
482
  }
294
483
 
484
+ case "oauth": {
485
+ // Peer of secrets/verify/delete — writes the token store, not
486
+ // toolset state, so the focus-mode guard does not apply.
487
+ await handleOauthSubcommand(rest, ctx);
488
+ return;
489
+ }
490
+
295
491
  case "verify": {
296
492
  // Peer of status/helpers/secrets — verifies a guide's ops and
297
493
  // stamps verified: (writes guide.md, not toolset state), so the
@@ -308,6 +504,22 @@ export default function initApiToggle(pi: ExtensionAPI): void {
308
504
  return;
309
505
  }
310
506
 
507
+ case "bootstrap": {
508
+ // F4: explicit dispatch arm — no mode registry. Writes toolset
509
+ // state (learn flip) only when learn was off, so the focus-mode
510
+ // guard is enforced INSIDE the handler, scoped to the flip (F5).
511
+ await handleBootstrapSubcommand(
512
+ rest,
513
+ {
514
+ learnEnabled: () => learnToolset.isEnabled(pi),
515
+ enableLearn: () => learnToolset.enable(pi), // cascades api on via requires
516
+ },
517
+ pi,
518
+ ctx,
519
+ );
520
+ return;
521
+ }
522
+
311
523
  default: {
312
524
  const apiStatus = apiToolset.isEnabled(pi) ? "✅ on" : "❌ off";
313
525
  const learnStatus = learnToolset.isEnabled(pi) ? "✅ on" : "❌ off";
@@ -316,14 +528,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
316
528
  `📡 API tools: ${apiStatus}`,
317
529
  `📖 Learn mode: ${learnStatus}`,
318
530
  ``,
319
- ` /api on enable api-guide + api-fetch`,
320
- ` /api learn enable all five tools (adds api-learn + api-probe + api-scaffold)`,
321
- ` /api off disable all API tools`,
322
- ` /api status detailed status (guides, helpers)`,
323
- ` /api helpers list local helpers`,
324
- ` /api secrets list/provision stored secrets (names only)`,
325
- ` /api verify verify a guide's ops against its live API (stamps verified)`,
326
- ` /api delete delete a guide directory (human-typed recovery gesture)`,
531
+ ...apiCommandMenu(),
327
532
  ` /api show this status`,
328
533
  ];
329
534