/** * Angel — structured advisor + execution guardrail. * * Builds a max-context packet, asks a paired advisor model for JSON advice, * injects advice after error batches, and gates dangerous shell commands once. * * Config (settings.json): * { "angel": { "pairs": [{ "executor": "a", "advisor": "b" }], ... } } * * Tools: angel(question?, context?) * Commands: /angel on|off */ import * as fs from "node:fs/promises"; import * as path from "node:path"; import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai"; import type { ExtensionAPI, ExtensionContext, SessionEntry, } from "@earendil-works/pi-coding-agent"; import { convertToLlm, SettingsManager, serializeConversation, } from "@earendil-works/pi-coding-agent"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; // ── constants ────────────────────────────────────────────────────────── const SYSTEM_PROMPT = `You are Angel: generic advisor for a coding agent. Use the whole packet: request, system prompt, conversation, files, errors, context usage, missing/truncated notes, extra context. Return only valid JSON: { "summary": "short conclusion", "nextAction": "single concrete next step", "risks": ["specific risk"], "assumptions": ["assumption or missing context"], "validationChecklist": ["specific check/test/inspection"], "enforceablePolicy": ["mechanically-checkable dangerous-command constraint"], "advisoryOnly": ["semantic/non-checkable guidance"], "confidence": 0.0, "insufficientContext": false } Rules: terse; specific; conditional if useful; 1-3 items/array; confidence <0.5 when context is weak.`; const CONFIDENCE_THRESHOLD = 0.5; const DEFAULT_MAX_CALLS = 4; const DEFAULT_AUTO_ON_ERRORS = 1; const MAX_FILE_CHARS = 30_000; const MAX_FILES = 50; const MAX_MESSAGES = 200; const MAX_ERRORS_EXTRACTED = 9; const MAX_SYSTEM_PROMPT_CHARS = 60_000; const FILE_TOOLS = new Set(["read", "edit", "write"]); const DANGEROUS_BASH = /(\bsudo\b|\brm\s+-(?:[^\s]*r[^\s]*f|[^\s]*f[^\s]*r)\b|\bgit\s+push\b|\b(?:npm|pnpm|bun)\s+publish\b|\bchmod\s+-R\b|\bchown\s+-R\b|\bdd\s+(?:if=|of=)|\bmkfs(?:\.\w+)?\b|\bcurl\b[^|]*\|\s*(?:sh|bash)\b|\bwget\b[^|]*\|\s*(?:sh|bash)\b|:\s*\(\)\s*\{)/i; // Magic numbers const USER_REQUEST_MAX = 4000; const ERROR_CONTENT_MAX = 1000; const FALLBACK_SUMMARY_MAX = 500; const FALLBACK_ADVISORY_MAX = 1200; // ── types ────────────────────────────────────────────────────────────── interface Settings { pairs?: { executor: string; advisor: string }[]; maxCallsPerTask?: number; enabled?: boolean; autoOnErrors?: number; policyGate?: "off" | "block"; } interface Advice { summary: string; nextAction: string; risks: string[]; assumptions: string[]; validationChecklist: string[]; enforceablePolicy: string[]; advisoryOnly: string[]; confidence: number; insufficientContext: boolean; } interface ContextPacket { version: 1; cwd: string; trigger: "manual" | "tool" | "auto_error" | "dangerous_command"; question?: string; userRequest?: string; systemPrompt: string; contextUsage?: { tokens: number | null; contextWindow: number; percent: number | null; }; recentConversation: string; touchedFiles: { path: string; content: string; truncated: boolean; missing?: boolean; }[]; recentToolErrors: string[]; missingSources: string[]; truncation: { maxFiles: number; maxFileChars: number; maxMessages: number; maxSystemPromptChars: number; }; extraContext?: string; } type AnyModel = Model; interface Binding { executor: AnyModel; advisor: AnyModel; } interface AngelResult { advice: Advice; raw: string; tokens: number; advisorKey: string; executorKey: string; packet: ContextPacket; } // ── helpers ──────────────────────────────────────────────────────────── function modelKey(m: AnyModel): string { return `${m.provider}/${m.id}`; } function modelMatches(spec: string, m: AnyModel): boolean { return spec === m.id || spec === modelKey(m); } interface ContentPart { type: string; text?: string; } function textFromContent(content: unknown): string { if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; return content .map((p): string => { if (typeof p !== "object" || p === null) return ""; const part = p as ContentPart; return part.text ?? ""; }) .filter(Boolean) .join("\n"); } function bulletList(items: string[]): string { return items.length > 0 ? items.map((i) => `- ${i}`).join("\n") : "- none"; } // ── settings ─────────────────────────────────────────────────────────── function isPlainObject(v: unknown): v is Record { return v !== null && typeof v === "object" && !Array.isArray(v); } function loadSettings(cwd = process.cwd(), agentDir?: string): Settings { const manager = SettingsManager.create(cwd, agentDir); const global = manager.getGlobalSettings() as Record; const project = manager.getProjectSettings() as Record; return { ...(isPlainObject(global.angel) ? global.angel : {}), ...(isPlainObject(project.angel) ? project.angel : {}), }; } // ── model resolution ─────────────────────────────────────────────────── function resolveBinding( ctx: ExtensionContext, s: Settings, executor = ctx.model, ): Binding | null { if (!executor) return null; for (const pair of s.pairs ?? []) { if (!modelMatches(pair.executor, executor)) continue; const [prov, id] = pair.advisor.includes("/") ? pair.advisor.split("/", 2) : [executor.provider, pair.advisor]; if (!prov || !id) return null; const advisor = ctx.modelRegistry.find(prov, id) ?? null; if (!advisor) return null; return { executor, advisor }; } return null; } // ── context packet ───────────────────────────────────────────────────── function lastUserRequest(entries: SessionEntry[]): string | undefined { for (let i = entries.length - 1; i >= 0; i--) { const e = entries[i]; if (e.type === "message" && e.message.role === "user") { const t = textFromContent(e.message.content).trim(); if (t) return t.slice(0, USER_REQUEST_MAX); } } return undefined; } interface ToolResultMessage { isError?: boolean; details?: { error?: unknown }; toolName?: string; } function extractToolErrors( entries: SessionEntry[], max = MAX_ERRORS_EXTRACTED, ): string[] { const errors: string[] = []; for (let i = entries.length - 1; i >= 0 && errors.length < max; i--) { const e = entries[i]; if (e.type !== "message" || e.message.role !== "toolResult") continue; const msg = e.message as ToolResultMessage; const hasError = msg.isError || msg.details?.error !== undefined; if (!hasError) continue; errors.push( `${msg.toolName ?? "tool"}: ${textFromContent(e.message.content).trim().slice(0, ERROR_CONTENT_MAX)}`, ); } return errors; } async function buildPacket( ctx: ExtensionContext, trigger: ContextPacket["trigger"], question?: string, extraContext?: string, ): Promise { const branch = ctx.sessionManager.getBranch(); const missingSources: string[] = []; // collect file paths touched by read/edit/write calls const filePaths = new Set(); for (const e of branch) { if ( e.type !== "message" || e.message.role !== "assistant" || !Array.isArray(e.message.content) ) continue; for (const block of e.message.content) { const b = block as { type?: string; name?: string; arguments?: { path?: string; file_path?: string }; }; if (b.type !== "toolCall" || !b.name || !FILE_TOOLS.has(b.name)) continue; const fp = b.arguments?.path ?? b.arguments?.file_path; if (typeof fp === "string" && fp.trim()) { filePaths.add(path.resolve(ctx.cwd, fp.trim())); } } } // read touched files const touchedFiles: ContextPacket["touchedFiles"] = []; for (const fp of [...filePaths].slice(0, MAX_FILES)) { try { const raw = await fs.readFile(fp, "utf-8"); const truncated = raw.length > MAX_FILE_CHARS; touchedFiles.push({ path: path.relative(ctx.cwd, fp), content: truncated ? raw.slice(0, MAX_FILE_CHARS) : raw, truncated, }); } catch { touchedFiles.push({ path: path.relative(ctx.cwd, fp), content: "", truncated: false, missing: true, }); } } if (filePaths.size > MAX_FILES) missingSources.push( `Only included ${MAX_FILES}/${filePaths.size} touched files.`, ); // recent conversation const msgs = branch .filter( (e): e is SessionEntry & { type: "message" } => e.type === "message", ) .map((e) => e.message); const recent = msgs.slice(-MAX_MESSAGES); if (msgs.length > MAX_MESSAGES) missingSources.push( `Conversation truncated to last ${MAX_MESSAGES}/${msgs.length} messages.`, ); const rawSystemPrompt = ctx.getSystemPrompt(); const systemPrompt = rawSystemPrompt.length > MAX_SYSTEM_PROMPT_CHARS ? rawSystemPrompt.slice(0, MAX_SYSTEM_PROMPT_CHARS) : rawSystemPrompt; if (rawSystemPrompt.length > MAX_SYSTEM_PROMPT_CHARS) { missingSources.push( `System prompt truncated to ${MAX_SYSTEM_PROMPT_CHARS}/${rawSystemPrompt.length} chars.`, ); } return { version: 1, cwd: ctx.cwd, trigger, question, userRequest: lastUserRequest(branch), systemPrompt, contextUsage: ctx.getContextUsage(), recentConversation: serializeConversation(convertToLlm(recent)), touchedFiles, recentToolErrors: extractToolErrors(branch), missingSources, truncation: { maxFiles: MAX_FILES, maxFileChars: MAX_FILE_CHARS, maxMessages: MAX_MESSAGES, maxSystemPromptChars: MAX_SYSTEM_PROMPT_CHARS, }, extraContext, }; } // ── advice parsing ───────────────────────────────────────────────────── function parseAdvice(raw: string): Advice { // Strip markdown code fences (```json ... ```) const FENCE_OPEN = /^\s*`{3}(?:json)?\s*\n?/i; const FENCE_CLOSE = /\n?`{3}\s*$/; const stripped = raw.replace(FENCE_OPEN, "").replace(FENCE_CLOSE, "").trim(); const first = stripped.indexOf("{"); if (first !== -1) { try { const p = JSON.parse(stripped.slice(first)) as Partial; const strArr = (v: unknown): string[] => Array.isArray(v) ? v.map(String) : []; return { summary: String(p.summary ?? "No summary returned."), nextAction: String( p.nextAction ?? "Decide next step from available context.", ), risks: strArr(p.risks), assumptions: strArr(p.assumptions), validationChecklist: strArr(p.validationChecklist), enforceablePolicy: strArr(p.enforceablePolicy), advisoryOnly: strArr(p.advisoryOnly), confidence: typeof p.confidence === "number" ? Math.max(0, Math.min(1, p.confidence)) : 0.5, insufficientContext: Boolean(p.insufficientContext), }; } catch { /* fall through */ } } return { summary: raw.slice(0, FALLBACK_SUMMARY_MAX) || "Angel returned unstructured advice.", nextAction: "Review unstructured advice manually.", risks: [], assumptions: ["Advisor response was not valid JSON."], validationChecklist: [], enforceablePolicy: [], advisoryOnly: [raw.slice(0, FALLBACK_ADVISORY_MAX)], confidence: 0.3, insufficientContext: true, }; } // ── formatting ───────────────────────────────────────────────────────── function formatAdvice(r: AngelResult): string { const { advice: a, advisorKey, executorKey, tokens, packet } = r; const lowConfidence = a.confidence < CONFIDENCE_THRESHOLD; const warning = lowConfidence ? `\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` : a.insufficientContext ? "\n> ⚠ **INSUFFICIENT CONTEXT**. Ask the human for clarification before acting on `Next:`.\n" : ""; const lines = [ "## Angel\n", warning, `**Summary:** ${a.summary}`, `**Next:** ${a.nextAction}`, `**Confidence:** ${Math.round(a.confidence * 100)}%${a.insufficientContext ? " · insufficient context" : ""}`, `**Doubt:** ${lowConfidence ? "⚠ recommended" : "not needed"}\n`, "### Risks", bulletList(a.risks), "### Assumptions", bulletList([...a.assumptions, ...packet.missingSources]), "### Validation", bulletList(a.validationChecklist), "### Policy", bulletList(a.enforceablePolicy), "### Advisory", bulletList(a.advisoryOnly), `\n---\n*executor:${executorKey} · advisor:${advisorKey} · ${tokens} tokens · trigger:${packet.trigger} · files:${packet.touchedFiles.length}*`, ]; return lines.join("\n"); } // ── LLM call ─────────────────────────────────────────────────────────── interface BashArgs { command?: string; } function bashCommand(input: unknown): string { if (typeof input !== "object" || input === null) return ""; const args = input as BashArgs; return (args.command ?? "").trim(); } function isDangerousCommand(toolName: string, input: unknown): boolean { return toolName === "bash" && DANGEROUS_BASH.test(bashCommand(input)); } async function consult( binding: Binding, packet: ContextPacket, auth: { apiKey?: string; headers?: ProviderHeaders }, signal?: AbortSignal, ): Promise { const { complete } = await import("@earendil-works/pi-ai/compat"); const res = await complete( binding.advisor, { systemPrompt: SYSTEM_PROMPT, messages: [ { role: "user", content: [{ type: "text", text: JSON.stringify(packet, null, 2) }], timestamp: Date.now(), }, ], }, { apiKey: auth.apiKey, headers: auth.headers, signal, cacheRetention: "none", }, ); const raw = res.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n"); return { advice: parseAdvice(raw), raw, tokens: (res.usage?.input ?? 0) + (res.usage?.output ?? 0), executorKey: modelKey(binding.executor), advisorKey: modelKey(binding.advisor), packet, }; } // ── extension entry ──────────────────────────────────────────────────── export default function (pi: ExtensionAPI) { const settings = loadSettings(); const maxCalls = settings.maxCallsPerTask ?? DEFAULT_MAX_CALLS; const autoOnErrors = settings.autoOnErrors ?? DEFAULT_AUTO_ON_ERRORS; const policyGate = settings.policyGate ?? "block"; let callCount = 0; let toolErrorCount = 0; let gatedDangerousCommands = new Set(); let sessionEnabled = settings.enabled !== false; const isEnabled = (): boolean => sessionEnabled && settings.enabled !== false; // ── availability ── function syncAvailability(ctx: ExtensionContext, executor = ctx.model) { const binding = executor && isEnabled() ? resolveBinding(ctx, settings, executor) : null; const available = binding !== null; const tools = pi.getActiveTools(); const has = tools.includes("angel"); if (available && !has) pi.setActiveTools([...tools, "angel"]); else if (!available && has) pi.setActiveTools(tools.filter((t) => t !== "angel")); if (ctx.hasUI) ctx.ui.setStatus( "angel", binding ? `👼 Angel → ${binding.advisor.id}` : undefined, ); } // ── core consult ── async function getAuth(ctx: ExtensionContext, model: AnyModel) { const a = await ctx.modelRegistry.getApiKeyAndHeaders(model); return a.ok ? { apiKey: a.apiKey, headers: a.headers } : null; } async function runAngel( ctx: ExtensionContext, trigger: ContextPacket["trigger"], question?: string, extraContext?: string, signal?: AbortSignal, ): Promise { if (!isEnabled()) throw new Error("Angel is disabled"); if (callCount >= maxCalls) throw new Error(`Max Angel calls (${maxCalls}) reached`); const binding = resolveBinding(ctx, settings); if (!binding) throw new Error( `Angel unavailable for ${ctx.model ? modelKey(ctx.model) : "no model"}`, ); const auth = await getAuth(ctx, binding.advisor); if (!auth) throw new Error(`Auth unavailable for ${binding.advisor.provider}`); callCount++; const packet = await buildPacket(ctx, trigger, question, extraContext); const result = await consult(binding, packet, auth, signal); pi.appendEntry("angel-advice", { timestamp: Date.now(), executor: result.executorKey, advisor: result.advisorKey, trigger, question, advice: result.advice, packetSummary: { cwd: packet.cwd, files: packet.touchedFiles.map((f) => ({ path: f.path, truncated: f.truncated, missing: f.missing, })), missingSources: packet.missingSources, }, }); return result; } // ── events ── pi.on("session_start", (_event, ctx) => { callCount = 0; toolErrorCount = 0; gatedDangerousCommands = new Set(); sessionEnabled = settings.enabled !== false; syncAvailability(ctx); }); pi.on("model_select", (event, ctx) => syncAvailability(ctx, event.model)); // Dangerous bash gate: block once, inject smarts, allow exact retry. pi.on("tool_call", async (event, ctx) => { if (!isEnabled() || policyGate === "off") return; if (!isDangerousCommand(event.toolName, event.input)) return; const binding = resolveBinding(ctx, settings); if (!binding || callCount >= maxCalls) return; const auth = await getAuth(ctx, binding.advisor); if (!auth) return; const command = bashCommand(event.input); if (!command || gatedDangerousCommands.has(command)) return; gatedDangerousCommands.add(command); let reason = `Angel dangerous-command gate: blocked once before running:\n${command}\n\n`; try { const result = await runAngel( ctx, "dangerous_command", "Review this dangerous shell command before execution.", `Pending tool call:\n${event.toolName} ${JSON.stringify(event.input, null, 2)}`, ctx.signal, ); reason += formatAdvice(result); } catch (err) { reason += `Angel unavailable: ${err instanceof Error ? err.message : String(err)}`; } return { block: true, reason: `${reason}\n\nIf still correct, retry the same command. Angel will not block that exact command again this session.`, }; }); // Auto-consult on every Nth tool error; inject advice into the agent loop. pi.on("tool_result", async (event, ctx) => { if (!isEnabled() || autoOnErrors <= 0 || event.toolName === "angel") return; if (!event.isError) return; toolErrorCount++; if (toolErrorCount % autoOnErrors !== 0) return; try { const result = await runAngel( ctx, "auto_error", `Tool error #${toolErrorCount}. Advise next step.`, `Latest failed tool:\n${event.toolName} ${JSON.stringify(event.input, null, 2)}\n\nResult:\n${textFromContent(event.content).slice(0, ERROR_CONTENT_MAX)}`, ctx.signal, ); pi.sendMessage( { customType: "angel-advice", content: formatAdvice(result), display: true, details: { advice: result.advice, tokensUsed: result.tokens, advisor: result.advisorKey, executor: result.executorKey, call: callCount, maxCalls, }, }, { deliverAs: "steer" }, ); } catch { /* non-critical */ } }); // ── tool ── pi.registerTool({ name: "angel", label: "Angel", description: "On-demand advisor for configured executor/advisor model pairs. Normally auto-injected after error batches and dangerous-command gates.", promptSnippet: "On-demand advisor with risks, validation checklist, and dangerous-command policy", promptGuidelines: [ "Do not call angel for generic review or vague value checks.", "Call angel only when explicitly asked or when blocked by Angel's dangerous-command gate.", "When Angel advice is injected, use nextAction/validation as steering, not as a permission wall.", ], parameters: Type.Object({ question: Type.Optional( Type.String({ description: "Specific advisor focus or review question", }), ), context: Type.Optional( Type.String({ description: "Extra context not visible in session state", }), ), }), renderCall(args, theme) { const q = args.question as string | undefined; const label = q ? `? "${q.slice(0, 30)}${q.length > 30 ? "..." : ""}"` : "structured review"; return new Text( theme.fg("toolTitle", theme.bold("angel ")) + theme.fg("dim", label), 0, 0, ); }, renderResult(result, { expanded }, theme) { const d = result.details as | { advice?: Advice; tokensUsed?: number; advisor?: string; executor?: string; call?: number; maxCalls?: number; } | undefined; const a = d?.advice; if (!a) { const t = result.content[0]; return new Text(t?.type === "text" ? t.text : "", 0, 0); } let out = theme.fg("success", "👼 angel "); out += theme.fg("muted", `${Math.round(a.confidence * 100)}%`); if (a.insufficientContext) out += theme.fg("warning", " insufficient-context"); if (a.confidence < CONFIDENCE_THRESHOLD) out += theme.fg("warning", " low confidence"); out += `\n${theme.fg("toolTitle", "Next: ")}${a.nextAction}`; if (a.enforceablePolicy.length > 0) out += `\n${theme.fg("warning", `${a.enforceablePolicy.length} policy gate(s) active`)}`; if (expanded) { if (a.risks.length) { out += `\n\n${theme.fg("toolTitle", "Risks")}`; for (const r of a.risks) out += `\n ${theme.fg("dim", `• ${r}`)}`; } if (a.validationChecklist.length) { out += `\n${theme.fg("toolTitle", "Validation")}`; for (const c of a.validationChecklist) out += `\n ${theme.fg("dim", `• ${c}`)}`; } if (a.assumptions.length) { out += `\n${theme.fg("toolTitle", "Assumptions")}`; for (const c of a.assumptions) out += `\n ${theme.fg("dim", `• ${c}`)}`; } if (a.enforceablePolicy.length) { out += `\n${theme.fg("toolTitle", "Policy")}`; for (const p of a.enforceablePolicy) out += `\n ${theme.fg("warning", `• ${p}`)}`; } if (a.advisoryOnly.length) { out += `\n${theme.fg("toolTitle", "Advisory")}`; for (const c of a.advisoryOnly) out += `\n ${theme.fg("dim", `• ${c}`)}`; } } return new Text(out, 0, 0); }, execute: async (_id, params, signal, onUpdate, ctx) => { onUpdate?.({ content: [{ type: "text", text: "👼 Building context packet..." }], details: { call: callCount + 1, maxCalls }, }); const result = await runAngel( ctx, "tool", params.question, params.context, signal, ); const output = formatAdvice(result); const details = { advice: result.advice, tokensUsed: result.tokens, advisor: result.advisorKey, executor: result.executorKey, call: callCount, maxCalls, }; return { content: [{ type: "text", text: output }], details }; }, }); // ── commands ── pi.registerCommand("angel", { description: "Enable/disable Angel for this session", getArgumentCompletions: (prefix): AutocompleteItem[] | null => { const items: AutocompleteItem[] = [ { value: "on", label: "on" }, { value: "off", label: "off" }, ]; const filtered = items.filter((i) => i.value.startsWith(prefix.toLowerCase()), ); return filtered.length > 0 ? filtered : null; }, handler: async (args, ctx) => { const arg = args.trim().toLowerCase(); if (arg !== "on" && arg !== "off") { if (ctx.hasUI) ctx.ui.notify("Usage: /angel on|off", "error"); return; } sessionEnabled = arg === "on"; syncAvailability(ctx); if (ctx.hasUI) ctx.ui.notify( `Angel ${sessionEnabled ? "enabled" : "disabled"}`, "info", ); }, }); } export const __test = { loadSettings };