import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { getLogger } from "./log.js"; /** * pi before 1.2 starts the run for `pi.sendMessage(…, { triggerTurn: true })` * without before_agent_start, so pi-pi never gets to set that run's system * prompt: its first request reuses whatever prompt the last run left behind, * and every request after a tool batch sends pi's own base prompt. Worker * updates and hidden continuations start runs that way. For such a run, the * prompt pi sends is swapped for the one pi-pi built for the last run it did * see start. pi 1.2 and later fire before_agent_start for these runs too, and * then nothing here applies. */ export class SystemPromptGuard { private base: string | undefined; private rendered: string | undefined; private starting = false; private unprompted = false; /** before_agent_start ran for the run about to start: pi-pi built `rendered` for it from pi's `base`, unless it is a one-off. */ prompted(base: unknown, rendered?: string): void { if (typeof base === "string") this.base = base; if (rendered !== undefined) this.rendered = rendered; this.starting = true; } runStarted(): void { this.unprompted = !this.starting; this.starting = false; } runEnded(): void { this.unprompted = false; } /** The payload with pi's prompt put back to pi-pi's; undefined when nothing needs changing. */ rewrite(payload: unknown, current: string | undefined): unknown { if (!this.unprompted || !this.rendered) return undefined; const rendered = this.rendered; const stale = new Set([this.base, current].filter((text): text is string => typeof text === "string" && text.length > 0 && text !== rendered)); if (stale.size === 0) return undefined; // pi rebuilds its base when the tools or resources change, which keeps its opening. const opening = this.base && this.base.length >= OPENING ? this.base.slice(0, OPENING) : undefined; const isStale = (text: string) => text !== rendered && (stale.has(text) || (opening !== undefined && text.startsWith(opening))); let replaced = 0; // Copies only what leads to a replaced string; everything else stays shared. const walk = (value: unknown): unknown => { if (typeof value === "string") { if (!isStale(value)) return value; replaced++; return rendered; } if (Array.isArray(value)) { const next = value.map(walk); return next.some((item, i) => item !== value[i]) ? next : value; } if (isPlain(value)) { const entries = Object.entries(value); const next = entries.map(([key, inner]) => [key, walk(inner)] as const); return next.some(([, inner], i) => inner !== entries[i]![1]) ? Object.fromEntries(next) : value; } return value; }; // Only where providers put the system prompt: conversation content that quotes it stays as it is. const next = inSystemPositions(payload, walk); if (replaced === 0) return undefined; getLogger().debug({ s: "system-prompt", replaced }, "restored pi-pi's system prompt in a run started without before_agent_start"); return next; } } /** How much of pi's base prompt identifies a rebuilt one. */ const OPENING = 200; const isPlain = (value: unknown): value is Record => !!value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype; /** * Applies `fix` to the places pi-ai's providers send the system prompt: * Anthropic's and Bedrock's `system`, the Responses and Codex `instructions`, * Google's `systemInstruction` (also under `config`), pi's own gateway's * `context.systemPrompt`, and a system or developer message in `messages` or `input`. */ function inSystemPositions(payload: unknown, fix: (value: unknown) => unknown): unknown { if (!isPlain(payload)) return payload; let next: Record = payload; const set = (key: string, value: unknown) => { if (value === next[key]) return; if (next === payload) next = { ...payload }; next[key] = value; }; for (const key of ["system", "instructions", "systemInstruction"]) if (key in payload) set(key, fix(payload[key])); for (const [key, field] of [["config", "systemInstruction"], ["context", "systemPrompt"]] as const) { const inner = payload[key]; if (!isPlain(inner) || !(field in inner)) continue; const value = fix(inner[field]); if (value !== inner[field]) set(key, { ...inner, [field]: value }); } for (const key of ["messages", "input"]) { const list = payload[key]; if (!Array.isArray(list)) continue; const fixed = list.map((item) => (isPlain(item) && (item.role === "system" || item.role === "developer") ? fix(item) : item)); if (fixed.some((item, i) => item !== list[i])) set(key, fixed); } return next; } export function registerSystemPromptGuard(pi: ExtensionAPI, guard: SystemPromptGuard): void { pi.on("agent_start", async () => guard.runStarted()); pi.on("agent_end", async () => guard.runEnded()); pi.on("before_provider_request", async (event: any, ctx: any) => guard.rewrite(event?.payload, safely(() => ctx?.getSystemPrompt?.()))); } function safely(read: () => T): T | undefined { try { return read(); } catch { return undefined; } }