1
/**2
* Shared utilities for compaction and branch summarization.3
*/5
import type { AgentMessage } from "@earendil-works/pi-agent-core";6
import { contentText, type Message } from "@earendil-works/pi-ai";8
// ============================================================================9
// File Operation Tracking10
// ============================================================================12
export interface FileOperations {13
read: Set<string>;14
written: Set<string>;15
edited: Set<string>;16
}18
export function createFileOps(): FileOperations {19
return {20
read: new Set(),21
written: new Set(),22
edited: new Set(),23
};24
}26
/**27
* Extract file operations from tool calls in an assistant message, or from the nested calls28
* recorded on a tool result.29
*/30
export function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {31
if (message.role === "toolResult") {32
// Calls made from codemode scripts are recorded on the script's result.33
for (const call of message.nestedCalls?.calls ?? []) addFileOp(call.name, call.arguments, fileOps);34
return;35
}36
if (message.role !== "assistant") return;37
if (!("content" in message) || !Array.isArray(message.content)) return;39
for (const block of message.content) {40
if (typeof block !== "object" || block === null) continue;41
if (!("type" in block) || block.type !== "toolCall") continue;42
if (!("arguments" in block) || !("name" in block)) continue;43
addFileOp(block.name, block.arguments as Record<string, unknown> | undefined, fileOps);44
}45
}47
function addFileOp(toolName: string, args: Record<string, unknown> | undefined, fileOps: FileOperations): void {48
const path = typeof args?.path === "string" ? args.path : undefined;49
if (!path) return;50
switch (toolName) {51
case "read":52
fileOps.read.add(path);53
break;54
case "write":55
fileOps.written.add(path);56
break;57
case "edit":58
fileOps.edited.add(path);59
break;60
}61
}63
/**64
* Compute final file lists from file operations.65
* Returns readFiles (files only read, not modified) and modifiedFiles.66
*/67
export function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {68
const modified = new Set([...fileOps.edited, ...fileOps.written]);69
const readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();70
const modifiedFiles = [...modified].sort();71
return { readFiles: readOnly, modifiedFiles };72
}74
/**75
* Format file operations as XML tags for summary.76
*/77
export function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {78
const sections: string[] = [];79
if (readFiles.length > 0) {80
sections.push(`<read-files>\n${readFiles.join("\n")}\n</read-files>`);81
}82
if (modifiedFiles.length > 0) {83
sections.push(`<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`);84
}85
if (sections.length === 0) return "";86
return `\n\n${sections.join("\n\n")}`;87
}89
// ============================================================================90
// Message Serialization91
// ============================================================================93
/** Maximum characters for a tool result in serialized summaries. */94
const TOOL_RESULT_MAX_CHARS = 2000;96
/**97
* Truncate text to a maximum character length for summarization.98
* Keeps the beginning and appends a truncation marker.99
*/100
function truncateForSummary(text: string, maxChars: number): string {101
if (text.length <= maxChars) return text;102
const truncatedChars = text.length - maxChars;103
return `${text.slice(0, maxChars)}\n\n[... ${truncatedChars} more characters truncated]`;104
}106
/**107
* Serialize LLM messages to text for summarization.108
* This prevents the model from treating it as a conversation to continue.109
* Call convertToLlm() first to handle custom message types.110
*111
* Tool results are truncated to keep the summarization request within112
* reasonable token budgets. Full content is not needed for summarization.113
*114
* Thinking is omitted. Providers return summaries of the real reasoning, and115
* replayed thinking is often not part of the model's live context: for example,116
* a block that does not match its request is dropped. Including it can make the117
* summarization request larger than the context it summarizes. Visible text,118
* tool calls, and tool results record what happened.119
*/120
export function serializeConversation(messages: Message[]): string {121
const parts: string[] = [];123
for (const msg of messages) {124
if (msg.role === "user") {125
const content = contentText(msg.content, "");126
if (content) parts.push(`[User]: ${content}`);127
} else if (msg.role === "assistant") {128
const toolCalls: string[] = [];130
for (const block of msg.content) {131
if (block.type === "toolCall") {132
const args = block.arguments as Record<string, unknown>;133
const argsStr = Object.entries(args)134
.map(([k, v]) => `${k}=${JSON.stringify(v)}`)135
.join(", ");136
toolCalls.push(`${block.name}(${argsStr})`);137
}138
}140
if (msg.content.some((block) => block.type === "text")) {141
parts.push(`[Assistant]: ${contentText(msg.content)}`);142
}143
if (toolCalls.length > 0) {144
parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);145
}146
} else if (msg.role === "toolResult") {147
const content = contentText(msg.content, "");148
if (content) {149
parts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);150
}151
}152
}154
return parts.join("\n\n");155
}157
// ============================================================================158
// Summarization System Prompt159
// ============================================================================161
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.163
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;