repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(angel): on/off toggle, Doubt rename, advisor-uncertain banner

ba397120cf7fb92c69641b79795a6376470241e9

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Replace the `/angel <question>` + `/angel-policy` surface with a single
`/angel on|off` session toggle. Rename the low-confidence `Devil` field to
`Doubt` (widget badge `consider-devil` → `low confidence`). Inject a
`> ⚠ ADVISOR UNCERTAIN` banner (or `INSUFFICIENT CONTEXT`) at the top of
formatted advice when confidence is below threshold, so the receiving model
is told to verify assumptions and risks and prefer read-only operations
before acting on `Next:`.

Also bundled (per "commit all"):
- changelog: document the mode extension's memory-only-state restore-on-off
  / restore-on-shutdown behavior (the feature landed in 4870b53)
- add the `/wr` "wrap it up" prompt

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Changed files (4)

+79 / −78 text lines

Diff layout

CHANGELOG.md

Modified

+24 / −0 text lines

33## Unreleased
5- Rename angel low-confidence `Devil` field to `Doubt` and widget badge from
6 `consider-devil` to `low confidence`
7- Inject a `> ⚠ ADVISOR UNCERTAIN` banner at the top of formatted angel advice
8 when confidence < 50% (or `INSUFFICIENT CONTEXT` banner when the advisor
9 reports insufficient context) so the receiving model is explicitly told to
10 verify assumptions and risks and prefer read-only operations before acting
11 on `Next:`
12- Make `/mode off` a no-op with `no mode active` notify when no mode is active,
13 and otherwise restore baseline tools/model/thinking only for fields the active
14 mode overrode, skipping restore for fields the user manually changed since
15 switch and for fields whose baseline ref is stale, while keeping the
16 `<mode_kernel>` guard so the mode body and reminder are physically removed
17 from the system prompt after off
18- Restore mode baseline tools/model/thinking on `session_shutdown` so a mode
19 left active at session end does not leave the user's default model, thinking,
20 or tool filter polluted for the next session
21- Capture `getAllTools()` (name + `sourceInfo.source`) in the mode baseline so
22 `/mode off` and shutdown restore can union new pi builtin tools back into the
23 active tool set, while leaving post-switch extension tool registrations out
24 unless the user explicitly enabled them
25- Document that mode `model`/`thinking` overrides are not session-scoped in the
26 current SDK: `pi.setModel` and `pi.setThinkingLevel` rewrite the user's
27 default model and thinking in settings, and only the `mode` extension's
28 baseline capture and restore-on-off / restore-on-shutdown mitigates the bleed
529- Convert extension drivers, helper scripts, and skill scripts from Python to MJS,
630 remove the Python/ruff project setup, and rename the goal pexpect test task
731- Fix notes widget rendering so Pi displays it at column zero with width-aware

extensions/angel/README.md

Modified

+9 / −9 text lines

4040### Commands
42- `/angel <question>`:
43 manual advisor consult.
44 Requires UI and a non-empty question.
45 Opens full advice in editor.
46- `/angel-policy`:
47 show latest enforceable policy in editor, or print it without UI.
42- `/angel on|off`:
43 toggle Angel for the current session.
44 Argument hint `<on|off>` and tab completion for `on` / `off`.
45 Defaults to `settings.enabled !== false` on session start.
46 No persistence — resets each session.
47 Re-runs `syncAvailability` to show/hide the `angel` tool and status.
4949### Hooks
123123- Persists advice as `angel-advice` entries with packet summary metadata.
124124- Injects formatted advice into the agent loop after configured failed
125125 tool-result intervals.
126- Stores the latest enforceable policy for `/angel-policy`.
127126- Keeps semantic guidance in `advisoryOnly`; only dangerous-command detection is
128127 mechanical.
129- Tool render marks low-confidence advice as `consider-devil`; formatted advice
130 marks `Devil` as recommended when confidence is below 50%.
128- Tool render marks low-confidence advice as `low confidence`; formatted advice
129 prepends a `> ⚠ ADVISOR UNCERTAIN` banner and marks `Doubt` as recommended when
130 confidence is below 50%.
132132## Policy Gates

extensions/angel/index.ts

Modified

+39 / −69 text lines

88 * { "angel": { "pairs": [{ "executor": "a", "advisor": "b" }], ... } }
99 *
1010 * Tools: angel(question?, context?)
11 * Commands: /angel <question>, /angel-policy
11 * Commands: /angel on|off
1212 */
1414import { existsSync, readFileSync } from "node:fs";
2525 getAgentDir,
2626 serializeConversation,
2727} from "@earendil-works/pi-coding-agent";
28import type { AutocompleteItem } from "@earendil-works/pi-tui";
2829import { Text } from "@earendil-works/pi-tui";
2930import { Type } from "typebox";
418419function formatAdvice(r: AngelResult): string {
419420 const { advice: a, advisorKey, executorKey, tokens, packet } = r;
421 const lowConfidence = a.confidence < CONFIDENCE_THRESHOLD;
422 const warning = lowConfidence
423 ? `\n> ⚠ **ADVISOR UNCERTAIN** (${Math.round(a.confidence * 100)}% confidence). Verify assumptions and risks before acting on \`Next:\`. Prefer read-only operations.${a.insufficientContext ? " Context is also insufficient — ask the human." : ""}\n`
424 : a.insufficientContext
425 ? "\n> ⚠ **INSUFFICIENT CONTEXT**. Ask the human for clarification before acting on `Next:`.\n"
426 : "";
420427 const lines = [
421428 "## Angel\n",
429 warning,
422430 `**Summary:** ${a.summary}`,
423431 `**Next:** ${a.nextAction}`,
424432 `**Confidence:** ${Math.round(a.confidence * 100)}%${a.insufficientContext ? " · insufficient context" : ""}`,
425 `**Devil:** ${a.confidence < CONFIDENCE_THRESHOLD ? "⚠ recommended" : "not needed"}\n`,
433 `**Doubt:** ${lowConfidence ? "⚠ recommended" : "not needed"}\n`,
426434 "### Risks",
427435 bulletList(a.risks),
428436 "### Assumptions",
504512 let callCount = 0;
505513 let toolErrorCount = 0;
506 let latestAdvice: Advice | null = null;
507514 let gatedDangerousCommands = new Set<string>();
515 let sessionEnabled = settings.enabled !== false;
517 const isEnabled = (): boolean => sessionEnabled && settings.enabled !== false;
509519 // ── availability ──
511521 function syncAvailability(ctx: ExtensionContext, executor = ctx.model) {
512522 const binding =
513 executor && settings.enabled !== false
514 ? resolveBinding(ctx, settings, executor)
515 : null;
523 executor && isEnabled() ? resolveBinding(ctx, settings, executor) : null;
516524 const available = binding !== null;
517525 const tools = pi.getActiveTools();
518526 const has = tools.includes("angel");
540548 extraContext?: string,
541549 signal?: AbortSignal,
542550 ): Promise<AngelResult> {
543 if (settings.enabled === false) throw new Error("Angel is disabled");
551 if (!isEnabled()) throw new Error("Angel is disabled");
544552 if (callCount >= maxCalls)
545553 throw new Error(`Max Angel calls (${maxCalls}) reached`);
557565 const packet = await buildPacket(ctx, trigger, question, extraContext);
558566 const result = await consult(binding, packet, auth, signal);
560 latestAdvice = result.advice;
562568 pi.appendEntry("angel-advice", {
563569 timestamp: Date.now(),
564570 executor: result.executorKey,
585591 pi.on("session_start", (_event, ctx) => {
586592 callCount = 0;
587593 toolErrorCount = 0;
588 latestAdvice = null;
589594 gatedDangerousCommands = new Set<string>();
595 sessionEnabled = settings.enabled !== false;
591 for (const e of ctx.sessionManager.getBranch()) {
592 if (e.type === "custom" && e.customType === "angel-advice") {
593 const d = (e.data as { advice?: Advice } | undefined)?.advice;
594 if (d) latestAdvice = d;
595 } else if (
596 e.type === "message" &&
597 e.message.role === "custom" &&
598 e.message.customType === "angel-advice"
599 ) {
600 const d = (e.message.details as { advice?: Advice } | undefined)
601 ?.advice;
602 if (d) latestAdvice = d;
603 }
604 }
605597 syncAvailability(ctx);
606598 });
610602 // Dangerous bash gate: block once, inject smarts, allow exact retry.
611603 pi.on("tool_call", async (event, ctx) => {
612 if (settings.enabled === false || policyGate === "off") return;
604 if (!isEnabled() || policyGate === "off") return;
613605 if (!isDangerousCommand(event.toolName, event.input)) return;
615607 const binding = resolveBinding(ctx, settings);
644636 // Auto-consult on every Nth tool error; inject advice into the agent loop.
645637 pi.on("tool_result", async (event, ctx) => {
646 if (
647 settings.enabled === false ||
648 autoOnErrors <= 0 ||
649 event.toolName === "angel"
650 )
651 return;
638 if (!isEnabled() || autoOnErrors <= 0 || event.toolName === "angel") return;
652639 if (!event.isError) return;
653640 toolErrorCount++;
654641 if (toolErrorCount % autoOnErrors !== 0) return;
740727 if (a.insufficientContext)
741728 out += theme.fg("warning", " insufficient-context");
742729 if (a.confidence < CONFIDENCE_THRESHOLD)
743 out += theme.fg("warning", " consider-devil");
730 out += theme.fg("warning", " low confidence");
744731 out += `\n${theme.fg("toolTitle", "Next: ")}${a.nextAction}`;
745732 if (a.enforceablePolicy.length > 0)
746733 out += `\n${theme.fg("warning", `${a.enforceablePolicy.length} policy gate(s) active`)}`;
802789 // ── commands ──
804791 pi.registerCommand("angel", {
805 description: "Consult Angel structured advisor",
792 description: "Enable/disable Angel for this session",
793 argumentHint: "<on|off>",
794 getArgumentCompletions: (prefix): AutocompleteItem[] | null => {
795 const items: AutocompleteItem[] = [
796 { value: "on", label: "on" },
797 { value: "off", label: "off" },
798 ];
799 const filtered = items.filter((i) =>
800 i.value.startsWith(prefix.toLowerCase()),
801 );
802 return filtered.length > 0 ? filtered : null;
803 },
806804 handler: async (args, ctx) => {
807 if (!ctx.hasUI) return;
808 const question = args.trim();
809 if (!question) {
810 ctx.ui.notify("Usage: /angel <question>", "error");
805 const arg = args.trim().toLowerCase();
806 if (arg !== "on" && arg !== "off") {
807 if (ctx.hasUI) ctx.ui.notify("Usage: /angel on|off", "error");
811808 return;
812809 }
814 try {
815 const result = await runAngel(
816 ctx,
817 "manual",
818 question,
819 undefined,
820 ctx.signal,
821 );
822 const edited = await ctx.ui.editor("Angel", formatAdvice(result));
823 if (edited !== undefined) ctx.ui.setEditorText(edited);
824 } catch (err) {
810 sessionEnabled = arg === "on";
811 syncAvailability(ctx);
812 if (ctx.hasUI)
825813 ctx.ui.notify(
826 `Angel failed: ${err instanceof Error ? err.message : err}`,
827 "error",
814 `Angel ${sessionEnabled ? "enabled" : "disabled"}`,
815 "info",
828816 );
829 }
830 },
831 });
833 pi.registerCommand("angel-policy", {
834 description: "Show latest Angel enforceable policy",
835 handler: async (_args, ctx) => {
836 const policy = latestAdvice?.enforceablePolicy ?? [];
837 const text =
838 policy.length > 0
839 ? policy.map((p) => `- ${p}`).join("\n")
840 : "No Angel policy active.";
841 if (ctx.hasUI) {
842 const edited = await ctx.ui.editor("Angel Policy", text);
843 if (edited !== undefined) ctx.ui.setEditorText(edited);
844 } else {
845 console.log(text);
846 }
847817 },
848818 });

prompts/wr.md

Added
new file mode 100644

+7 / −0 text lines

1---
2description: Wrap it up
3argument-hint: "[instructions]"
4---
5
6good, wrap it up and implement what we decided step by step, end to end. tdd, brutal.
7$ARGUMENTS