magic-compact
Lossless context compression plugin for Claude Code & OpenCode.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/aerovato--magic-compact)HTML
<a href="/listings/aerovato--magic-compact"><img src="/api/listings/aerovato--magic-compact/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Magic Compact works flawlessly on Claude Code, but OpenCode will have more features + first class support as OpenCode exposes more functionality to plugins.
Claude Code
Install from this repository's first-party plugin marketplace:
/plugin marketplace add aerovato/magic-compact /plugin install claude-magic-compact@magic-compact
After installation, run `/reload-plugins` if Claude Code is already open.
OpenCode
Install from the CLI:
rm -rf ~/.cache/opencode/packages/magic-compact* opencode plugin magic-compact --global # If you are encountering "No versions available": NPM_CONFIG_MIN_RELEASE_AGE=0 opencode plugin magic-compact --global
This installs the package and adds it to your global OpenCode config.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 23 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "magic-compact",
- "description": "First-party Magic Compact plugins.",
- "owner": {
- "name": "kevinMEH"
- },
- "plugins": [
- {
- "name": "claude-magic-compact",
- "source": {
- "source": "npm",
- "package": "claude-magic-compact",
- "version": "1.4.0"
- },
- "description": "Lossless context compression for Claude Code.",
- "homepage": "https://github.com/aerovato/magic-compact#readme",
- "repository": "https://github.com/aerovato/magic-compact",
- "author": {
- "name": "kevinMEH"
- }
- }
- ]
- }
README.md · README · 195 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- # Magic Compact
- English | [中文](./README.zh-CN.md)
- > [!IMPORTANT]
- > Magic Compact development has been paused in favor of [Operator Memory](https://github.com/aerovato/operator-memory), its successor. Magic Compact focuses on context compression; Operator already provides durable memory and documentation, and will gain context-management features over time. Install and follow Operator for future development; a Claude Code plugin will be added soon. Magic Compact remains fully functional.
- Lossless context compression for OpenCode and Claude Code.
- <p align="center">
- <img src=".github/assets/preview.png" alt="Magic Compact Preview" />
- </p>
- > ##### Built with [Operator Memory](https://github.com/aerovato/operator-memory)
- ## Why
- OpenCode and Claude Code's built-in compaction replaces an entire conversation with one summary blob. The user messages, the assistant's reasoning, tool calls, design decisions, and workflow are all flattened into a generic template (Goal, Progress, Key Decisions...). The agent wakes up with amnesia, forced to reconstruct its working state from an abstraction that captured a fraction of what mattered.
- Magic Compact takes a different approach: preserve the conversation skeleton, condense each old assistant turn into its own summary, prune bulky tool I/O, and keep everything retrievable. The agent retains its memory of what it did, why, and what comes next.
- ## How
- Instead of collapsing an entire session into a single generic summary, Magic Compact replaces old assistant turns with high-fidelity summaries while leaving user messages and tool calls in place.
- The assistant's thought process, decisions, and actions remain in context along with all your commands while unnecessary bloat is stripped away. Long tool calls are aggressively pruned but can be retrieved via a custom `read_omitted_content` tool.
- <p align="center">
- <img src=".github/assets/visualization.png" alt="Compaction Comparison" />
- </p>
- ## Features
- - Lossless context compression — Fully preserve working memory instead of flattening history into one recap.
- - Zero compaction overhead — Compaction happens once on your command rather than during the agentic loop. Maximum token savings, minimal cache invalidations.
- - Preserved user messages — Exact requirements and guidance remain visible to the agent, verbatim.
- - Smart tool call pruning — Bulky completed tool I/O is replaced with omission notices, with original content cached and retrievable on demand via `read_omitted_content`.
- - Recompactable — Run `/magic-compact` again later to compact new turns while preserving prior summaries.
- - Trim without summarizing — OpenCode can prune historical tool I/O with `/magic-trim` while preserving assistant responses.
- ## Installation
- Magic Compact works flawlessly on Claude Code, but OpenCode will have more features + first class support as OpenCode exposes more functionality to plugins.
- ### Claude Code
- Install from this repository's first-party plugin marketplace:
- ```shell
- /plugin marketplace add aerovato/magic-compact
- /plugin install claude-magic-compact@magic-compact
- ```
- After installation, run `/reload-plugins` if Claude Code is already open.
- ### OpenCode
- Install from the CLI:
- ```bash
- rm -rf ~/.cache/opencode/packages/magic-compact*
- opencode plugin magic-compact --global
- # If you are encountering "No versions available":
- NPM_CONFIG_MIN_RELEASE_AGE=0 opencode plugin magic-compact --global
- ```
- This installs the package and adds it to your global OpenCode config.
- ## Usage
- ### `/magic-compact`
- To compact, run `/magic-compact [N]` with an optional argument indicating how many turns to preserve.
- - `N` is the number of recent assistant turns to preserve as-is. Default: `0` (summarize everything).
- - A backup session is created before the current conversation is compacted. If compaction fails, you will return to the backup.
- Examples:
- - `/magic-compact` — summarize all old assistant turns.
- - `/magic-compact 3` — keep the 3 most recent assistant turns, summarize the rest.
- ### `/magic-trim` (OpenCode Exclusive) (Experimental)
- Run `/magic-trim [N]` to apply the same tool I/O pruning rules without summarizing or deleting ordinary user and assistant content.
- - `N` preserves tool I/O in the most recent assistant turns. Default: `0` (trim all eligible turns).
- - Trimming does not call an LLM or create a compaction boundary.
- - A backup session is created before trimming.
- - Token reductions are included in `/magic-stats`.
- Examples:
- - `/magic-trim` — trim eligible tool I/O throughout the session.
- - `/magic-trim 3` — preserve tool I/O in the 3 most recent assistant turns.
- ### `/magic-stats` (OpenCode Exclusive)
- Run `/magic-stats` to show cumulative token savings for the current conversation: tokens pruned, cached tokens saved, estimated money saved, among other statistics.
- ### The Omitted Content Tool
- Magic Compact registers a `read_omitted_content` tool that the agent can call to retrieve any tool input or output that was pruned during compaction or trimming.
- Each omission notice in the conversation includes a Content ID (e.g. `omitted-001`). The agent uses that ID to fetch the original content when it needs stale information that cannot be reproduced via a new tool call.
- ### Claude Code
- Claude Code does not expose as much capability to plugins vs OpenCode. Therefore, certain differences are present when using Magic Compact for Claude Code:
- - Magic Compact will create a compacted destintaion sesion instead of compacting in place.
- - Claude Code does not allow us to modify the current session's message transcript
- - After compaction, Claude Code will tell you to run `/resume <new-session-id>` to enter the compacted session
- - Simply copy and paste that command and run it
- - `/magic-stats` is not implemented for Claude Code
- ## Pruning Rules
- During `/magic-compact`, pruning applies only to summarized turns. On OpenCode, `/magic-trim [N]` applies only the tool I/O rules to turns outside the preserved tail.
- Kept:
- - User messages (verbatim)
- - Per-turn summaries
- - Tool calls (structure preserved)
- - Selected high-value synthetic messages (shell wrappers, background task results, working-directory change reminders)
- Removed or condensed:
- - Assistant reasoning, text, and step markers — replaced by the per-turn summary
- - Most synthetic/injected messages (file expansions, plan reminders, prior compaction notices, etc.)
- - Bulky completed tool I/O — replaced with an omission notice pointing to the cache
- ### Tool I/O Rules
- Completed tool outputs over 128 words or 1024 characters are omitted by default. A few tools have special handling.
- #### OpenCode
- - `read` — output always omitted (stale file contents are reloadable)
- - `write` / `edit` / `apply_patch` — large file content omitted
- - `bash` — commands over 1024 characters are truncated
- - `task` — output omitted above a higher threshold (512 words / 4096 characters)
- - `question` — input and output preserved
- - `todowrite` / `skill` — output discarded without caching (redundant or reloadable)
- #### Claude Code
- - `Read` / `NotebookEdit` — output always omitted (file text, notebook JSON, images, PDFs are reloadable)
- - `Bash.command` — commands over 512 characters truncated; full command cached with an omission ID
- - `Agent` / `TaskOutput` — output omitted above a higher threshold (512 words / 4096 characters)
- - `AskUserQuestion` — input and output preserved (captures explicit user decisions)
- - `Skill` — output discarded without caching (reloadable by re-invoking the skill)
- Pending, running, and errored tool calls are always preserved as-is.
- Completed tool calls processed by pruning are marked so later trim and compaction operations do not trim them again.
- ## Vs DCP Plugin (OpenCode)
- OpenCode-DCP is a runtime context management system that rewrites messages when requested by the model. Magic Compact takes a different approach.
- Magic Compact Offers:
- - Simplicity — One command, zero configuration.
- - Lossless quality — Turn-by-turn flow stays intact. All user commands are preserved. All past tool calls are preserved.
- - Maximum token savings — The entire conversation is summarized with one request. Long tool calls are aggressively pruned.
- - No cache churn — Compaction happens once and is cache friendly, whereas DCP may invalidate entire conversations multiple times within one request.
- - Zero assistant overhead — No prompt injections asking the assistant to compact. Your assistant stay focused on its task.
- If you want model-driven compaction with increased cache invalidations and token burn, consider using DCP instead.
- ## Vs Magic Context (OpenCode)
- Magic Context is a much broader runtime context-management system: it runs background historian and dreamer processes, maintains project memory, and injects recalled memories and history back into the prompt on an ongoing basis. That makes it powerful, but also much heavier in tokens and cache churn.
- Magic Compact Offers:
- - Efficiency — One explicit compaction command, no background summarization loop, no always-on memory RAG, and no recurring prompt injections.
- - Lower token burn — Context reduction happens once on demand instead of continuously consuming tokens across every turn.
- - Fewer cache invalidations — The session is rewritten once, then stays stable, instead of repeatedly re-rendering volatile background state.
- - Lossless conversation shape — User messages stay verbatim, tool structure is preserved, and summarized assistant turns remain retrievable.
- - Focused compaction — The plugin does one job: compress the conversation without turning the runtime into a memory subsystem.
- If you want a lightweight, user-driven compaction tool with minimal ongoing overhead, Magic Compact is the better fit. If you want a full long-term memory system with background maintenance, Magic Context is the heavier alternative.
- ## Development
- See [`.operator-shared/operator.md`](./.operator-shared/operator.md) for setup and maintenance commands.
- ## Built with Operator
- This repository is maintained with [Operator Memory](https://github.com/aerovato/operator-memory) — durable, agent-maintained documentation that lets AI agents work on the project with full context across sessions. The published brain lives in [`.operator-shared/`](.operator-shared/).
packages/claude-code-plugin/src/compact.ts · Bundled script · 576 lines · 1 finding marked
- import { randomUUID } from "node:crypto";
- import { unlink } from "node:fs/promises";
- import { loadOmissionCache, saveOmissionCache } from "./omission";
- import { pruneTranscriptRow } from "./prune";
- import {
- buildAssistantTurns,
- copyTranscriptToNewSession,
- isRecord,
- readActiveTranscriptRows,
- readPreservedMetadataEntries,
- type Turn,
- type TranscriptRow,
- writeTranscriptEntries,
- } from "./transcript";
- type Plan = {
- prefixTurns: Turn[];
- summarizedTurns: Turn[];
- preservedTurns: Turn[];
- baseRow: TranscriptRow;
- };
- const POST_COMPACTION_NOTICE = `<post-compaction-notice>
- A compaction operation has just been applied to all messages above. You may have to reread certain files to regain context. Certain historical tool input/output may have been omitted due to length. If the exact I/O of the tool call needs to be retrieved and functionality cannot be replicated via a new tool call, call the read_omitted_content tool with the appropriate Content ID to reread the tool I/O content.
- </post-compaction-notice>`;
- const SYNTHETIC_MODEL = "<synthetic>";
- export async function compactTranscript(
- sourceTranscriptPath: string,
- destinationTranscriptPath: string,
- sessionId: string,
- keepTurns: number,
- ): Promise<boolean> {
- const rows = await readActiveTranscriptRows(sourceTranscriptPath);
- const plan = createPlan(rows, keepTurns);
- if (plan.summarizedTurns.length === 0) {
- return false;
- }
- const summaries = await generateSummaries(
- sourceTranscriptPath,
- plan.summarizedTurns,
- plan.preservedTurns[0] ?? null,
- latestAssistantModel(rows),
- );
- const compactedRows = await buildCompactedRows(plan, summaries, sessionId);
- const metadataEntries = await readPreservedMetadataEntries(
- sourceTranscriptPath,
- plan.baseRow.sessionId,
- sessionId,
- );
- await writeTranscriptEntries(destinationTranscriptPath, [
- ...metadataEntries,
- ...compactedRows,
- ]);
- return true;
- }
- function createPlan(rows: TranscriptRow[], keepTurns: number): Plan {
- const baseRow = rows.find(
- row => row.type === "user" || row.type === "assistant",
- );
- if (!baseRow) {
- throw new Error(
- "Transcript does not contain compactable conversation rows.",
- );
- }
- const turns = buildAssistantTurns(rows);
- const compactionStartIndex =
- turns.findLastIndex(turn => turn.rows.some(isMagicCompactSummaryRow)) + 1;
- const compactionEndIndex =
- keepTurns <= 0
- ? turns.length
- : Math.max(compactionStartIndex, turns.length - keepTurns);
- return {
- prefixTurns: turns.slice(0, compactionStartIndex),
- summarizedTurns: turns.slice(compactionStartIndex, compactionEndIndex),
- preservedTurns: turns.slice(compactionEndIndex),
- baseRow,
- };
- }
- async function generateSummaries(
- transcriptPath: string,
- turns: Turn[],
- nextTurn: Turn | null,
- model: string | null,
- ): Promise<string[]> {
- const analysis = await copyTranscriptToNewSession(transcriptPath);
- const prompt = buildCompactionPrompt(turns, nextTurn);
- const args = [
- "claude",
- "-p",
- "--resume",
- analysis.transcriptPath,
- "--settings",
- JSON.stringify({ disableAllHooks: true }),
- ];
- if (model !== null) {
- args.push("--model", model);
- }
- args.push(prompt);
- try {
- const summaryProcess = Bun.spawn(args, {
- stdout: "pipe",
- stderr: "pipe",
- });
- const [stdout, stderr, exitCode] = await Promise.all([
- new Response(summaryProcess.stdout).text(),
- new Response(summaryProcess.stderr).text(),
- summaryProcess.exited,
- ]);
- if (exitCode !== 0) {
- throw new Error(`Summary generation failed: ${stderr.trim()}`);
- }
- return parseSummaries(stdout, turns.length);
- } finally {
- await unlink(analysis.transcriptPath).catch(() => undefined);
- }
- }
- function latestAssistantModel(rows: TranscriptRow[]): string | null {
- for (const row of rows.toReversed()) {
- if (row.type !== "assistant" || !isRecord(row.message)) {
- continue;
- }
- const model = row.message["model"];
- if (
- typeof model === "string"
- && model !== ""
- && model !== SYNTHETIC_MODEL
- ) {
- return model;
- }
- }
- return null;
- }
- async function buildCompactedRows(
- plan: Plan,
- summaries: string[],
- sessionId: string,
- ): Promise<TranscriptRow[]> {
- const rows: TranscriptRow[] = [];
- const copiedUuids = new Map<string, string>();
- const completedToolUseIds = collectCompletedToolUseIds(plan.summarizedTurns);
- const toolNamesById = collectToolNamesById(plan.summarizedTurns);
- const omissionCache = await loadOmissionCache(sessionId);
- const timestamp = new Date().toISOString();
- const lastOriginalRow = sourceTurns(plan)
- .flatMap(turn => turn.rows)
- .at(-1);
- if (!lastOriginalRow) {
- throw new Error("Compaction plan has no source rows.");
- }
- const boundaryUuid = randomUUID();
- rows.push({
- ...copySessionFields(plan.baseRow, sessionId, timestamp),
- type: "user",
- uuid: boundaryUuid,
- parentUuid: null,
- isMeta: true,
- message: {
- id: `msg_${randomUUID()}`,
- role: "user",
- content: POST_COMPACTION_NOTICE,
- },
- logicalParentUuid: lastOriginalRow.uuid,
- magicCompact: {
- boundary: true,
- },
- });
- let parentUuid: string | null = boundaryUuid;
- for (const turn of plan.prefixTurns) {
- parentUuid = copyTurnRows(
- turn,
- rows,
- copiedUuids,
- sessionId,
- timestamp,
- parentUuid,
- );
- }
- for (const [index, turn] of plan.summarizedTurns.entries()) {
- for (const row of turn.userRows) {
- const copied = copyRow(row, sessionId, timestamp, parentUuid);
- copiedUuids.set(row.uuid, copied.uuid);
- rows.push(copied);
- parentUuid = copied.uuid;
- }
- const firstAssistant = turn.rows.find(row => row.type === "assistant");
- if (!firstAssistant) {
- throw new Error("Turn missing assistant row for summary shape.");
- }
- const summary = summaries[index];
- if (summary === undefined) {
- throw new Error("Missing summary for compacted turn.");
- }
- const copied = createAssistantSummaryRow(
- firstAssistant,
- sessionId,
- timestamp,
- parentUuid,
- summary,
- );
- copiedUuids.set(firstAssistant.uuid, copied.uuid);
- rows.push(copied);
- parentUuid = copied.uuid;
- for (const row of turn.rows) {
- if (turn.userRows.includes(row) || !isToolRow(row)) {
- continue;
- }
- const copiedToolRow = copyRow(
- row,
- sessionId,
- timestamp,
- row.parentUuid
- ? (copiedUuids.get(row.parentUuid) ?? parentUuid)
- : parentUuid,
- );
- keepOnlyToolBlocks(copiedToolRow);
- pruneTranscriptRow(copiedToolRow, {
- cache: omissionCache,
- sessionId,
- completedToolUseIds,
- toolNamesById,
- });
- copiedUuids.set(row.uuid, copiedToolRow.uuid);
- rows.push(copiedToolRow);
- parentUuid = copiedToolRow.uuid;
- }
- }
- for (const turn of plan.preservedTurns) {
- parentUuid = copyTurnRows(
- turn,
- rows,
- copiedUuids,
- sessionId,
- timestamp,
- parentUuid,
- );
- }
- await saveOmissionCache(sessionId, omissionCache);
- return rows;
- }
- function copyTurnRows(
- turn: Turn,
- rows: TranscriptRow[],
- copiedUuids: Map<string, string>,
- sessionId: string,
- timestamp: string,
- initialParentUuid: string | null,
- ): string | null {
- let parentUuid = initialParentUuid;
- for (const row of turn.rows) {
- const copied = copyRow(
- row,
- sessionId,
- timestamp,
- row.parentUuid
- ? (copiedUuids.get(row.parentUuid) ?? parentUuid)
- : parentUuid,
- );
- copiedUuids.set(row.uuid, copied.uuid);
- rows.push(copied);
- parentUuid = copied.uuid;
- }
- return parentUuid;
- }
- function copyRow(
- row: TranscriptRow,
- sessionId: string,
- timestamp: string,
- parentUuid: string | null,
- ): TranscriptRow {
- const copied = structuredClone(row) as TranscriptRow;
- copied.uuid = randomUUID();
- copied.parentUuid = parentUuid;
- copied.sessionId = sessionId;
- copied.timestamp = timestamp;
- return copied;
- }
- function collectCompletedToolUseIds(turns: Turn[]): Set<string> {
- const ids = new Set<string>();
- for (const turn of turns) {
- for (const row of turn.rows) {
- if (!isRecord(row.message)) {
- continue;
- }
- const content = row.message["content"];
- if (!Array.isArray(content)) {
- continue;
- }
- for (const block of content) {
- if (
- isRecord(block)
- && block["type"] === "tool_result"
- && block["is_error"] !== true
- && typeof block["tool_use_id"] === "string"
- ) {
- ids.add(block["tool_use_id"]);
- }
- }
- }
- }
- return ids;
- }
- function collectToolNamesById(turns: Turn[]): Map<string, string> {
- const names = new Map<string, string>();
- for (const turn of turns) {
- for (const row of turn.rows) {
- if (!isRecord(row.message)) {
- continue;
- }
- const content = row.message["content"];
- if (!Array.isArray(content)) {
- continue;
- }
- for (const block of content) {
- if (
- isRecord(block)
- && block["type"] === "tool_use"
- && typeof block["id"] === "string"
- && typeof block["name"] === "string"
- ) {
- names.set(block["id"], block["name"]);
- }
- }
- }
- }
- return names;
- }
- function isToolRow(row: TranscriptRow): boolean {
- if (!isRecord(row.message)) {
- return false;
- }
- const content = row.message["content"];
- return (
- Array.isArray(content)
- && content.some(
- block =>
- isRecord(block)
- && (block["type"] === "tool_use" || block["type"] === "tool_result"),
- )
- );
- }
- function keepOnlyToolBlocks(row: TranscriptRow): void {
- if (!isRecord(row.message)) {
- return;
- }
- const content = row.message["content"];
- if (!Array.isArray(content)) {
- return;
- }
- row.message["content"] = content.filter(
- block =>
- isRecord(block)
- && (block["type"] === "tool_use" || block["type"] === "tool_result"),
- );
- }
- function isMagicCompactSummaryRow(row: TranscriptRow): boolean {
- const magicCompact = row["magicCompact"];
- return isRecord(magicCompact) && magicCompact["summary"] === true;
- }
- function sourceTurns(plan: Plan): Turn[] {
- return [...plan.prefixTurns, ...plan.summarizedTurns, ...plan.preservedTurns];
- }
- function createAssistantSummaryRow(
- source: TranscriptRow,
- sessionId: string,
- timestamp: string,
- parentUuid: string | null,
- summary: string,
- ): TranscriptRow {
- const copied = structuredClone(source) as TranscriptRow;
- copied.uuid = randomUUID();
- copied.parentUuid = parentUuid;
- copied.sessionId = sessionId;
- copied.timestamp = timestamp;
- copied.message = {
- ...source.message,
- id: `msg_${randomUUID()}`,
- role: "assistant",
- content: [{ type: "text", text: summary }],
- stop_reason: "end_turn",
- stop_sequence: null,
- };
- copied["magicCompact"] = { summary: true };
- return copied;
- }
- function copySessionFields(
- row: TranscriptRow,
- sessionId: string,
- timestamp: string,
- ): TranscriptRow {
- const copied = structuredClone(row) as TranscriptRow;
- copied.sessionId = sessionId;
- copied.timestamp = timestamp;
- copied.isSidechain = false;
- delete copied.message;
- return copied;
- }
- function buildCompactionPrompt(turns: Turn[], nextTurn: Turn | null): string {
- return `<system>
- Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
- Line 434 on GitHub
- # Attention: Conversation Compaction Required
- The current conversation is reaching the maximum allowed conversation size. In order to continue, earlier unsummarized parts of the conversation must be summarized.
- ## Next Task
- In order to continue, a subset of earlier non-compacted **assistant turns** of this conversation must be summarized. An assistant turn encompasses all messages (including tool calls and results) sent by an assistant between one user request and the next user request.
- Next task: Summarize the conversation by **outputting exactly the XML structure shown below** but with all assistant turns summarized. Replace all placeholder text with your summary of the turn. **Your response should start with the <summary> tag and end with the closing </summary> tag.**
- ${buildXmlTemplate(turns, nextTurn)}
- ## Output Guidelines:
- - **Output the truncated text within the <user> </user> tags exactly** according to the XML template above
- - User prompts are intentionally truncated to only parts of the first line for brevity.
- - Therefore, only output PARTS OF THE FIRST LINE. DO NOT OUTPUT the entire user prompt.
- - Output your summary for assistant turns within the <assistant> </assistant> tags
- - You are **only responsible** for summarizing the specific assistant turns specified within the XML structure
- - Do not summarize any other assistant turns not specified in the XML template above.
- - Do not think. Do not call any tools. Output the summary ONLY.
- - **Follow the template.** Your response should start with the <summary> tag and end with the closing </summary> tag.
- ## Summarization Guidelines:
- - Summarize everything between one user message and the next
- - Keep your summaries short and direct
- - Try to keep your summaries under 250 words whenever possible
- - You may go over 250 words to preserve summary quality if the assistant turn was genuinely long
- - In your summary, include:
- - Relevant decisions and thought process, including specific plans if any was presented
- - Very brief bullet point summary of your workflow
- - Errors or bugs encountered + fixes, if any
- - Final results and summarized output to the user + next steps
- - All tool calls are preserved and automatically included with your summary
- - Therefore, you **do not need to restate details about what tools you used or with what arguments**
- - However, you include analysis of motivations for tool calls or specific findings from tool call results
- - E.g. for file reads: What files contains what, what files are junk
- - Do not mention this summarization process; your summaries should naturally replace the assistant's turn within the flow of the conversation
- </system>`;
- }
- function buildXmlTemplate(turns: Turn[], nextTurn: Turn | null): string {
- const parts: string[] = [];
- parts.push("<summary>");
- parts.push(
- ...turns.map(turn =>
- `
- <user>
- ${getUserPromptText(turn)}
- </user>
- <assistant>
- [**Replace: Your summary of the assistant turn**]
- </assistant>
- `.trim(),
- ),
- );
- if (nextTurn) {
- parts.push(
- `
- <user>
- ${getUserPromptText(nextTurn)}
- </user>
- [**Do not add an <assistant> summary for the final <user> above; it marks where summarization stops and the template ends here.**]
- `.trim(),
- );
- }
- parts.push("</summary>");
- return parts.join("\n");
- }
- function getUserPromptText(turn: Turn): string {
- const text = turn.userRows
- .map(row => getUserText(row))
- .filter(Boolean)
- .join("\n");
- const firstLine = text.trim().split("\n")[0]?.trim() ?? "";
- return firstLine.length <= 300
- ? `${firstLine}\n...`
- : `${firstLine.slice(0, 300).trim()}...`;
- }
- function parseSummaries(responseText: string, expectedCount: number): string[] {
- const start = responseText.indexOf("<summary>");
- const end = responseText.lastIndexOf("</summary>");
- if (start === -1 || end === -1 || end < start) {
- throw new Error(
- "Summary response did not include a complete <summary> block.",
- );
- }
- const summary = responseText.slice(start, end + "</summary>".length);
- // Models regularly append one unrequested summary for the trailing
- // next-turn <user> anchor. Pairing each echoed <user> with its following
- // <assistant> and taking the first expectedCount pairs ignores that extra
- // block while still failing loudly on a true miss.
- const segments = [
- ...summary.matchAll(/<(user|assistant)>([\s\S]*?)<\/\1>/g),
- ].map(match => ({ tag: match[1]!, text: match[2]!.trim() }));
- const matches: string[] = [];
- for (
- let index = 0;
- index < segments.length && matches.length < expectedCount;
- index++
- ) {
- const current = segments[index]!;
- const next = segments[index + 1];
- if (current.tag === "user" && next?.tag === "assistant") {
- matches.push(next.text);
- index++;
- }
- }
- if (matches.length !== expectedCount) {
- throw new Error(
- `Expected ${expectedCount} summaries, received ${matches.length} user/assistant pairs.`,
- );
- }
- return matches;
- }
- function getUserText(row: TranscriptRow): string {
- if (!isRecord(row.message)) {
- return "";
- }
- const content = row.message["content"];
- if (typeof content === "string") {
- return content;
- }
- if (!Array.isArray(content)) {
- return "";
- }
- return content
- .map(block =>
- isRecord(block) && typeof block["text"] === "string" ? block["text"] : "",
- )
- .filter(Boolean)
- .join("\n");
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.