From e1c5b2c6a8c05cb6406493f5f99083a48fc5de04 Mon Sep 17 00:00:00 2001 From: SidQin-cyber Date: Fri, 6 Mar 2026 00:40:23 +0800 Subject: [PATCH] fix(agents): skip compaction API call when session has no real messages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With compaction.mode: "safeguard", the compaction timer fires every ~30 minutes on all active sessions including idle cron sessions. The safeguard extension correctly cancels compaction when there are no real conversation messages, but the cancellation happens inside the Pi SDK's session_before_compact event — after the SDK has already initiated an LLM API call. This wastes ~33k prompt tokens per idle session per cycle (~48 unnecessary calls/day). Add a local pre-check in compactEmbeddedPiSessionDirect that bails out before calling session.compact() when no user/assistant/toolResult messages exist. This avoids the API round-trip entirely. Closes #34935 Made-with: Cursor --- src/agents/pi-embedded-runner/compact.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/agents/pi-embedded-runner/compact.ts b/src/agents/pi-embedded-runner/compact.ts index 2fc622c842b..83b98f532d4 100644 --- a/src/agents/pi-embedded-runner/compact.ts +++ b/src/agents/pi-embedded-runner/compact.ts @@ -132,6 +132,10 @@ type CompactionMessageMetrics = { contributors: Array<{ role: string; chars: number; tool?: string }>; }; +function hasRealConversationContent(msg: AgentMessage): boolean { + return msg.role === "user" || msg.role === "assistant" || msg.role === "toolResult"; +} + function createCompactionDiagId(): string { return `cmp-${Date.now().toString(36)}-${generateSecureToken(4)}`; } @@ -663,6 +667,17 @@ export async function compactEmbeddedPiSessionDirect( ); } + if (!session.messages.some(hasRealConversationContent)) { + log.info( + `[compaction] skipping — no real conversation messages (sessionKey=${params.sessionKey ?? params.sessionId})`, + ); + return { + ok: true, + compacted: false, + reason: "no real conversation messages", + }; + } + const compactStartedAt = Date.now(); const result = await compactWithSafetyTimeout(() => session.compact(params.customInstructions),