import type { ContextEvent } from "@earendil-works/pi-coding-agent"; type AgentMessage = ContextEvent["messages"][number]; const WEB_TOOL_NAMES = new Set(["web_search", "web_fetch", "web_fetch_read"]); function stringField(value: unknown, key: string): string | undefined { if (!value || typeof value !== "object") return undefined; const field = (value as Record)[key]; return typeof field === "string" && field ? field : undefined; } function clearedReceipt(toolName: string, details: unknown): string { const artifactId = stringField(details, "searchId") ?? stringField(details, "fetchId") ?? stringField(details, "artifactId"); const reportPath = stringField(details, "reportPath"); if (toolName === "web_search") { if (reportPath) { return `[Previous web search content cleared from active context. report_path=${reportPath}; use read(path, offset, limit) if needed.]`; } return artifactId ? `[Previous web search content cleared from active context. search_id=${artifactId}; report path unavailable.]` : "[Previous web search content cleared from active context.]"; } return artifactId ? `[Previous fetched web content cleared from active context. fetch_id=${artifactId}; use web_fetch_read if needed.]` : "[Previous fetched web content cleared from active context.]"; } /** Replaces prior-user-turn web payloads while preserving every tool-call/result pair. */ export function pruneHistoricalWebResults(messages: AgentMessage[]): AgentMessage[] { let latestUserIndex = -1; for (let index = messages.length - 1; index >= 0; index -= 1) { if (messages[index]?.role === "user") { latestUserIndex = index; break; } } if (latestUserIndex < 0) return messages; return messages.map((message, index) => { if ( index >= latestUserIndex || message.role !== "toolResult" || message.isError || !WEB_TOOL_NAMES.has(message.toolName) ) { return message; } return { ...message, content: [{ type: "text", text: clearedReceipt(message.toolName, message.details) }], }; }); }