fix(agents): skip compaction API call when session has no real messages

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
This commit is contained in:
SidQin-cyber
2026-03-06 00:40:23 +08:00
committed by Josh Lehman
parent 60a6d11116
commit e1c5b2c6a8

View File

@@ -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),