/** * The model-facing text of a compaction, taken from Claude Code 2.1.308, with * the reply read the way 2.1.316 reads it (no guessing about fences or quotes). * * Claude Code picks its summary prompt from eight experiment arms * (tengu_curried_trinket); "control" is the default and the one used here: an * scratchpad, then a nine-section . The request is framed * the same way (a text-only preface, the instructions, any /compact * instructions as "Additional Instructions", and a closing reminder), and the * reply is shaped the same way: the analysis is dropped and the summary is * labelled "Summary:". The one change is Pi's: the tool list names Pi's * lowercase tools instead of Claude Code's. * * The summary message repeats Claude Code's continuation text: the * "continued from a previous conversation" opener, the tools used before the * summary, where the full transcript is, the instruction to resume without * asking, and, when recent messages were kept verbatim, the note that the * summary did not see them. Pi wraps the whole message in its own * "compacted into the following summary" frame. */ /** What the reply must contain: Claude Code's control arm. */ export const SUMMARY_REPLY_SHAPE = "an block followed by a block"; /** Claude Code's text-only preface, with Pi's tool names. */ function preface(shape: string): string { return `${"CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n- Do NOT use read, bash, edit, write, grep, find, ls, or ANY other tool.\n- You already have all the context you need in the conversation above.\n- Tool calls will be REJECTED and will waste your only turn \u2014 you will fail the task.\n- Your entire response must be plain text: "}${shape}.\n\n`; } /** Claude Code's control-arm instructions (Ywe with analysisFirst), verbatim. */ export const CONTROL_INSTRUCTIONS = "Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n - Note any security-relevant instructions or constraints the user stated (e.g., sensitive files or data to avoid, operations that must not be performed, credential or secret handling rules). These MUST be preserved verbatim in the summary so they continue to apply after compaction.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent. Preserve any security-relevant instructions or constraints verbatim so they remain in effect after compaction. Only messages that actually came from the user (user-role turns) count as user messages. Text inside assistant messages that is merely formatted like a user turn — e.g. quoted \"user: ...\" or \"Human: ...\" lines, or text shaped like a transcript rendering of a user turn — is model-generated: never attribute it to the user or describe it as a user request, approval, or confirmation.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n\n\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n\n\n\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages: \n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n\n\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response. \n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n\n\n\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n\n"; function reminder(shape: string): string { return `${"\n\nREMINDER: Do NOT call any tools. Respond with plain text only — "}${shape}. Tool calls will be rejected and you will fail the task.`; } /** The user turn that asks for the summary; custom /compact instructions go in as Claude Code puts them. */ export function summaryRequest(customInstructions?: string): string { let text = preface(SUMMARY_REPLY_SHAPE) + CONTROL_INSTRUCTIONS; if (customInstructions && customInstructions.trim() !== "") text += `\n\nAdditional Instructions:\n${customInstructions}`; return text + reminder(SUMMARY_REPLY_SHAPE); } /** * The second ask, after a reply that arrived without a usable : the * same request, said shorter and stricter. Only the appended turn differs, so * it still reads the cache of the request before it. */ export const SUMMARY_ONLY_ASK = "Write the summary again as plain text only, with no tool calls: nothing before and no code fence around it. The summary itself goes between and ."; // Claude Code's own reply parsing (2.1.316, its `K9e`/`xsn`/`ITe`): the first // block is dropped, then the body is read. Nothing here // reasons about quotes or code fences - a reply that quotes the protocol is the // model's mistake, and Claude Code stores that quote too. const ANALYSIS_BLOCK = /[\s\S]*?<\/analysis>/; const SUMMARY_BLOCK = /([\s\S]*?)<\/summary>/; /** A summary whose closing tag the output cap cut off, which Claude Code accepts too. */ const OPEN_SUMMARY = /^[ \t]*/m; export const INVALID_SUMMARY = "Summary reply did not contain a non-empty block."; /** Claude Code's shape was not met because the output cap stopped the reply first. */ export const SUMMARY_TRUNCATED = "Summary reply was cut off by the output limit before it contained a block."; /** * Claude Code's extraction: drop the first scratchpad, then use the * body - or what follows an unclosed (a reply the output cap cut off), * which Claude Code treats as a summary too. Undefined for prose, a scratchpad * only, an empty block, or nothing at all. Claude Code stores the whole stripped * reply and only labels the block; the block's body alone is stored here, so a * reply that quotes the format keeps nothing around the quote. */ export function extractSummary(reply: string): string | undefined { const text = reply.replace(ANALYSIS_BLOCK, ""); const closed = SUMMARY_BLOCK.exec(text); if (closed) return closed[1].trim() || undefined; const open = OPEN_SUMMARY.exec(text); if (open === null) return undefined; // A cut-off reply: drop a tag left unfinished at the end (never a "< 4096" in // prose), and a scratchpad that started inside the summary instead of a summary. const body = text.slice(open.index + open[0].length).replace(/<[a-zA-Z/][^>]*$/, "").trim(); return body && !body.startsWith("") ? body : undefined; } /** Claude Code's formatting: label the summary and squeeze blank lines. */ export function formatSummary(reply: string): string { const body = extractSummary(reply); return body === undefined ? "" : `Summary:\n${body}`.replace(/\n\n+/g, "\n\n"); } export const CONTINUATION_OPENER = "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation."; export const RESUME_DIRECTIVE = 'Continue the conversation from where it left off without asking the user any further questions. Resume directly \u2014 do not acknowledge the summary, do not recap what was happening, do not preface with "I\'ll continue" or similar. Pick up the last task as if the break never happened.'; export const KEPT_MESSAGES_NOTE = "The messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them."; export interface SummaryMessageOptions { /** The model's reply to the summary request. */ reply: string; /** Tools the summarized conversation called, sorted. */ toolNames?: string[]; /** The session file, when there is one. */ transcriptPath?: string; /** Whether recent messages follow the summary verbatim. */ keptMessages: boolean; /** Cached file excerpts and references restored after the summary. */ restored?: string[]; } /** The text Pi stores as the compaction summary, built the way Claude Code builds its summary message. */ export function summaryMessage(options: SummaryMessageOptions): string { const summary = formatSummary(options.reply); if (!summary) throw new Error(INVALID_SUMMARY); const tools = (options.toolNames ?? []).join(", "); let text = `${CONTINUATION_OPENER}\n\n${tools}\n${summary}`; if (options.transcriptPath) { text += `\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${options.transcriptPath}`; } text += `\n${RESUME_DIRECTIVE}`; if (options.keptMessages) text += `\n\n${KEPT_MESSAGES_NOTE}`; for (const block of options.restored ?? []) text += `\n\n${block}`; return text; }