返回源码地图

packages/coding-agent/src/core/compaction/utils.ts

v1.3.0 · 71023aec1546 · 07:106–165,serializeConversation省略thinking及有界工具结果;非完整审计导出

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * Shared utilities for compaction and branch summarization.
3 */
4
5import type { AgentMessage } from "@earendil-works/pi-agent-core";
6import { contentText, type Message } from "@earendil-works/pi-ai";
7
8// ============================================================================
9// File Operation Tracking
10// ============================================================================
11
12export interface FileOperations {
13 read: Set<string>;
14 written: Set<string>;
15 edited: Set<string>;
16}
17
18export function createFileOps(): FileOperations {
19 return {
20 read: new Set(),
21 written: new Set(),
22 edited: new Set(),
23 };
24}
25
26/**
27 * Extract file operations from tool calls in an assistant message, or from the nested calls
28 * recorded on a tool result.
29 */
30export 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;
38
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}
46
47function 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}
62
63/**
64 * Compute final file lists from file operations.
65 * Returns readFiles (files only read, not modified) and modifiedFiles.
66 */
67export 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}
73
74/**
75 * Format file operations as XML tags for summary.
76 */
77export 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}
88
89// ============================================================================
90// Message Serialization
91// ============================================================================
92
93/** Maximum characters for a tool result in serialized summaries. */
94const TOOL_RESULT_MAX_CHARS = 2000;
95
96/**
97 * Truncate text to a maximum character length for summarization.
98 * Keeps the beginning and appends a truncation marker.
99 */
100function 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}
105
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 within
112 * reasonable token budgets. Full content is not needed for summarization.
113 *
114 * Thinking is omitted. Providers return summaries of the real reasoning, and
115 * 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 the
117 * summarization request larger than the context it summarizes. Visible text,
118 * tool calls, and tool results record what happened.
119 */
120export function serializeConversation(messages: Message[]): string {
121 const parts: string[] = [];
122
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[] = [];
129
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 }
139
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 }
153
154 return parts.join("\n\n");
155}
156
157// ============================================================================
158// Summarization System Prompt
159// ============================================================================
160
161export 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.
162
163Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;