From caecb4e13517742cffb0a238ae127f35cc3e023c Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Thu, 26 Nov 2026 10:48:09 +0000 Subject: [PATCH] agent/compaction: Compact idle agents before the cache expires An idle agent's next prompt resends its whole context uncached once the provider's prompt cache expires. Compact large idle contexts shortly before that, following Claude Code's own idle compaction: at 90% of a one-hour cache lifetime, from 200,000 tokens of context, and not when the sweep is more than a minute late. Providers opt in by reporting their cache through `getPromptCacheState()`. Claude reads the lifetime from each request's `cache_creation` usage. The daemon runs `/compact` as its own turn without recording a prompt, and restores the agent's attention afterwards so it neither notifies nor changes unread state. `agents.idleCompaction` in `config.json` turns it off or sets the context threshold. Co-Authored-By: Claude Opus 5.5 --- .../diff-subscription/refresh-metrics.json | 7 + docs/agent-lifecycle.md | 8 ++ docs/jujutsu-fork.md | 4 +- .../src/server/agent/agent-manager.test.ts | 98 +++++++++++++ .../server/src/server/agent/agent-manager.ts | 73 +++++++++- .../src/server/agent/agent-sdk-types.ts | 14 ++ .../idle-compaction/idle-compaction.test.ts | 107 ++++++++++++++ .../src/server/agent/idle-compaction/index.ts | 135 ++++++++++++++++++ .../src/server/agent/provider-registry.ts | 1 + .../agent/providers/claude/agent.test.ts | 46 ++++++ .../server/agent/providers/claude/agent.ts | 39 +++++ packages/server/src/server/bootstrap.ts | 17 +++ packages/server/src/server/config.ts | 7 + .../server/src/server/persisted-config.ts | 11 ++ .../public/schemas/paseo.config.v1.json | 21 +++ public-docs/configuration.md | 25 ++++ 16 files changed, 611 insertions(+), 2 deletions(-) create mode 100644 .artifacts/diff-subscription/refresh-metrics.json create mode 100644 packages/server/src/server/agent/idle-compaction/idle-compaction.test.ts create mode 100644 packages/server/src/server/agent/idle-compaction/index.ts diff --git a/.artifacts/diff-subscription/refresh-metrics.json b/.artifacts/diff-subscription/refresh-metrics.json new file mode 100644 index 000000000..0deb2210a --- /dev/null +++ b/.artifacts/diff-subscription/refresh-metrics.json @@ -0,0 +1,7 @@ +{ + "files": 252, + "coldMs": 2076.0937139999996, + "oneFileRefreshMs": 345.29472799999985, + "changedBodies": 1, + "highlightCalls": 1 +} \ No newline at end of file diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 1520635c9..e6803fccb 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -53,6 +53,14 @@ host config to disable automatic collection. The host setting applies immediatel apply on reload. Disabling invalidates pending safety checks and close admission. A close already started finishes. Re-enabling keeps the existing idle timestamps. +Idle compaction runs `/compact` on an idle agent shortly before its provider's prompt cache +expires (`packages/server/src/server/agent/idle-compaction/`). Providers opt in with +`getPromptCacheState()`, which reports the time of the latest request and the cache lifetime; +Claude reads the lifetime from each request's `cache_creation` usage. The same daemon baseline as +collection must allow it, and agents with a pending wakeup or message delivery are skipped. The +compaction turn records no prompt and restores the attention the agent had before it. See +`agents.idleCompaction` in [configuration](../public-docs/configuration.md#idle-compaction). + Foreground runs, permissions and responses, queued deliveries, lifecycle operations, and working managed or native descendants prevent collection. Outstanding local or remote finish subscriptions also protect their caller, including registration, recovery and notification dispatch acknowledgment. diff --git a/docs/jujutsu-fork.md b/docs/jujutsu-fork.md index b219397c1..12453e95e 100644 --- a/docs/jujutsu-fork.md +++ b/docs/jujutsu-fork.md @@ -95,7 +95,9 @@ Retention refs accumulate, as they do for Git worktrees. The local series has a standalone fix for the detached-HEAD base picker, followed by the Jujutsu daemon and protocol support, the CLI commands, the app controls -and the documentation. The daemon commit keeps creation, diff semantics and +and the documentation. A last, independent commit adds idle compaction before +the prompt cache expires; see +[configuration](../public-docs/configuration.md#idle-compaction). The daemon commit keeps creation, diff semantics and archive safety together because they share the same checkout and persistence code. The app and CLI both call that interface. diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 81a8ecedc..c7ae1fda2 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -16501,3 +16501,101 @@ test("a wrapped refresh passes a Windows script provider command to the wrapper expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error"); await manager.closeAgent(created.id); }); + +class PromptCacheTestSession extends TestAgentSession { + readonly prompts: AgentPromptInput[] = []; + + getPromptCacheState() { + return { lastRequestAt: 1_000, ttlMs: 60 * 60 * 1000 }; + } + + async startTurn(prompt?: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt !== undefined) this.prompts.push(prompt); + return super.startTurn(); + } +} + +class PromptCacheTestClient extends TestAgentClient { + readonly sessions: PromptCacheTestSession[] = []; + + async createSession(config: AgentSessionConfig): Promise { + const session = new PromptCacheTestSession(config); + this.sessions.push(session); + return session; + } +} + +test.each([ + ["unread", true], + ["read", false], +])( + "an idle compaction sends /compact without a prompt and keeps the agent %s", + async (_case, unread) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-idle-compaction-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new PromptCacheTestClient(); + const attentionReasons: string[] = []; + const manager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + onAgentAttention: ({ reason }) => attentionReasons.push(reason), + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + await manager.runAgent(agent.id, "hello"); + if (!unread) await manager.clearAgentAttention(agent.id); + const attentionBefore = manager.getAgent(agent.id)?.attention; + expect(attentionBefore?.requiresAttention).toBe(unread); + + const [candidate] = manager.getIdleCompactionCandidates(); + expect(candidate).toMatchObject({ + agentId: agent.id, + cache: { lastRequestAt: 1_000, ttlMs: 60 * 60 * 1000 }, + }); + const idle = waitForAgentLifecycle(manager, agent.id, "idle"); + await expect(candidate?.compact()).resolves.toBe(true); + await idle; + + expect(client.sessions[0]?.prompts).toEqual(["hello", "/compact"]); + expect(manager.getAgent(agent.id)?.attention).toEqual(attentionBefore); + expect(attentionReasons).toEqual(["finished"]); + const timeline = manager.getTimeline(agent.id); + expect(timeline.filter((item) => item.type === "user_message")).toEqual([]); + expect(timeline).toContainEqual({ + type: "notification", + level: "info", + message: "Compacting while idle, before the prompt cache expires", + }); + } finally { + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test("a running agent is not an idle compaction candidate", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-idle-compaction-busy-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new PromptCacheTestClient() }, + registry: storage, + logger, + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + expect(manager.getIdleCompactionCandidates()).toHaveLength(1); + + const run = manager.runAgent(agent.id, "hello"); + expect(manager.getIdleCompactionCandidates()).toEqual([]); + await run; + expect(manager.getIdleCompactionCandidates()).toHaveLength(1); + } finally { + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index ac262bffb..90e2f4a34 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -6,6 +6,7 @@ import type { import { LaunchWrapUnsupportedError, ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; +import type { IdleCompactionCandidate } from "./idle-compaction/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; import { AgentTurnChangedError } from "./agent-prompt.js"; import { @@ -956,6 +957,8 @@ export class AgentManager { { readonly openedAt: number } >(); private readonly collectingRuntimes = new Set(); + /** Agents running a daemon-started compaction, with the attention they had before it. */ + private readonly idleCompactions = new Map(); private readonly lifecycleMutationTails = new Map>(); private readonly pendingCancellations = new Map>(); private readonly agentStreamCoalescer: AgentStreamCoalescer; @@ -2365,6 +2368,63 @@ export class AgentManager { return candidates; } + /** Idle agents whose provider reports a prompt cache and can compact before it expires. */ + getIdleCompactionCandidates(): IdleCompactionCandidate[] { + const candidates: IdleCompactionCandidate[] = []; + for (const agent of this.agents.values()) { + if (!this.canStartIdleCompaction(agent)) continue; + const cache = agent.session.getPromptCacheState?.(); + if (!cache) continue; + + candidates.push({ + agentId: agent.id, + provider: agent.provider, + cache, + contextTokens: agent.lastUsage?.contextWindowUsedTokens, + compact: async () => this.startIdleCompaction(agent), + }); + } + return candidates; + } + + private canStartIdleCompaction(agent: LiveManagedAgent): boolean { + return ( + this.agents.get(agent.id) === agent && + !this.historySessions.has(agent.session) && + !this.collectingRuntimes.has(agent.id) && + !agent.session.hasPendingWakeup?.() && + this.runtimeHasNoPendingWork(agent) + ); + } + + // Runs `/compact` as a turn of its own. No prompt is recorded, and the agent keeps the + // attention it had, so a finished compaction neither notifies nor marks the agent unread. + private async startIdleCompaction(agent: LiveManagedAgent): Promise { + if (!this.canStartIdleCompaction(agent)) return false; + + const attention = agent.attention; + const events = this.streamAgent(agent.id, "/compact"); + this.idleCompactions.set(agent.id, attention); + void (async () => { + try { + for await (const _event of events) { + // The manager records and broadcasts the turn's events itself. + } + } catch (error) { + this.logger.warn({ err: error, agentId: agent.id }, "idle_compaction_turn_failed"); + } finally { + this.idleCompactions.delete(agent.id); + } + })(); + + await this.appendTimelineItem(agent.id, { + type: "notification", + level: "info", + message: "Compacting while idle, before the prompt cache expires", + }); + return true; + } + private runtimeHasNoPendingWork(agent: LiveManagedAgent): boolean { return ( agent.lifecycle === "idle" && @@ -6081,7 +6141,11 @@ export class AgentManager { ) return; this.touchUpdatedAt(agent); - if (item.type === "user_message") agent.lastUserMessageAt = new Date(); + if (item.type === "user_message") { + agent.lastUserMessageAt = new Date(); + // A prompt sent during an idle compaction continues that turn, so its result notifies. + this.idleCompactions.delete(agent.id); + } this.recordAndDispatchTimelineItem(agent.id, item, agent.provider, options?.turnId, options); } @@ -6232,11 +6296,18 @@ export class AgentManager { } if (previousStatus !== "error" && currentStatus === "error") { + this.idleCompactions.delete(agent.id); this.raiseErrorAttention(agent); return; } const finished = previousStatus === "running" && currentStatus === "idle"; + const idleCompactionAttention = this.idleCompactions.get(agent.id); + if (finished && idleCompactionAttention) { + this.idleCompactions.delete(agent.id); + agent.attention = idleCompactionAttention; + return; + } if (agent.attention.requiresAttention) { // The unread finish stays the same; the notifier knows whether the user was told about it. if (finished && agent.attention.attentionReason === "finished") { diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 244c7faf3..81f3e79f4 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -229,6 +229,14 @@ export interface SteerActiveTurnOptions extends AgentSteerOptions { expectedTurnId: string; } +/** The provider's prompt cache for the main conversation, as of its latest model request. */ +export interface AgentPromptCacheState { + /** When the latest request was sent (epoch milliseconds). Each request renews the cache. */ + lastRequestAt: number; + /** How long the cache lives after a request. */ + ttlMs: number; +} + export interface AgentUsage { inputTokens?: number; cachedInputTokens?: number; @@ -779,6 +787,12 @@ export interface AgentSession { * background task that reports back when it ends. Recurring triggers do not count. */ hasPendingWakeup?(): boolean; + /** + * The prompt cache of the main conversation, or null while it is unknown. Sessions that + * implement this compact their context when sent `/compact` as a prompt, which lets the daemon + * compact an idle session before its cache expires. + */ + getPromptCacheState?(): AgentPromptCacheState | null; /** Release live runtime resources without archiving or deleting the durable native session. */ close(): Promise; listCommands?(): Promise; diff --git a/packages/server/src/server/agent/idle-compaction/idle-compaction.test.ts b/packages/server/src/server/agent/idle-compaction/idle-compaction.test.ts new file mode 100644 index 000000000..15316eb0a --- /dev/null +++ b/packages/server/src/server/agent/idle-compaction/idle-compaction.test.ts @@ -0,0 +1,107 @@ +import { expect, onTestFinished, test } from "vitest"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { + createIdleCompaction, + resolveIdleCompactionConfig, + type IdleCompactionCandidate, +} from "./index.js"; + +const HOUR = 60 * 60 * 1000; +const FIRE_AT = 0.9 * HOUR; + +class Agent { + lastRequestAt = 0; + ttlMs = HOUR; + contextTokens: number | undefined = 250_000; + idle = true; + compactions = 0; + + candidate(): IdleCompactionCandidate { + return { + agentId: "agent", + provider: "claude", + cache: { lastRequestAt: this.lastRequestAt, ttlMs: this.ttlMs }, + contextTokens: this.contextTokens, + compact: async () => { + this.compactions++; + return true; + }, + }; + } +} + +function scenario(enabled = true) { + const agent = new Agent(); + let time = 0; + const compaction = createIdleCompaction({ + enabled, + minContextTokens: 200_000, + candidates: () => (agent.idle ? [agent.candidate()] : []), + logger: createTestLogger(), + now: () => time, + schedule: () => () => {}, + }); + onTestFinished(() => compaction.close()); + return { + agent, + sweepAt: (at: number) => { + time = at; + return compaction.sweep(); + }, + }; +} + +test("compacts once at 90% of a one-hour cache lifetime", async () => { + const s = scenario(); + expect(await s.sweepAt(FIRE_AT - 1)).toEqual([]); + expect(await s.sweepAt(FIRE_AT)).toEqual(["agent"]); + expect(await s.sweepAt(FIRE_AT + 15_000)).toEqual([]); + expect(s.agent.compactions).toBe(1); +}); + +test("a newer request moves the compaction", async () => { + const s = scenario(); + s.agent.lastRequestAt = 10 * 60 * 1000; + expect(await s.sweepAt(FIRE_AT)).toEqual([]); + expect(await s.sweepAt(s.agent.lastRequestAt + FIRE_AT)).toEqual(["agent"]); +}); + +test.each([ + ["the cache lives five minutes", (agent: Agent) => (agent.ttlMs = 5 * 60 * 1000)], + ["the context is small", (agent: Agent) => (agent.contextTokens = 199_999)], + ["the context size is unknown", (agent: Agent) => (agent.contextTokens = undefined)], +])("leaves the agent alone when %s", async (_case, change) => { + const s = scenario(); + change(s.agent); + expect(await s.sweepAt(HOUR - 1)).toEqual([]); + expect(s.agent.compactions).toBe(0); +}); + +test("a sweep more than a minute late leaves the cache to expire", async () => { + const s = scenario(); + expect(await s.sweepAt(FIRE_AT + 60_001)).toEqual([]); + expect(await s.sweepAt(FIRE_AT + 60_002)).toEqual([]); + expect(s.agent.compactions).toBe(0); +}); + +test("an agent that is busy at the fire time is judged again when it is idle", async () => { + const s = scenario(); + s.agent.idle = false; + expect(await s.sweepAt(FIRE_AT)).toEqual([]); + s.agent.idle = true; + expect(await s.sweepAt(FIRE_AT + 15_000)).toEqual(["agent"]); +}); + +test("does nothing when disabled", async () => { + const s = scenario(false); + expect(await s.sweepAt(FIRE_AT)).toEqual([]); + expect(s.agent.compactions).toBe(0); +}); + +test.each([ + [undefined, { enabled: true, minContextTokens: 200_000 }], + [false, { enabled: false, minContextTokens: 200_000 }], + [{ minContextTokens: 100_000 }, { enabled: true, minContextTokens: 100_000 }], +])("resolves the config.json setting %j", (persisted, expected) => { + expect(resolveIdleCompactionConfig(persisted)).toEqual(expected); +}); diff --git a/packages/server/src/server/agent/idle-compaction/index.ts b/packages/server/src/server/agent/idle-compaction/index.ts new file mode 100644 index 000000000..0e6375c19 --- /dev/null +++ b/packages/server/src/server/agent/idle-compaction/index.ts @@ -0,0 +1,135 @@ +import type { Logger } from "pino"; +import type { AgentPromptCacheState } from "../agent-sdk-types.js"; + +/** An idle agent whose provider reports its prompt cache. */ +export interface IdleCompactionCandidate { + readonly agentId: string; + readonly provider: string; + readonly cache: AgentPromptCacheState; + readonly contextTokens: number | undefined; + /** Starts `/compact` if the agent is still idle. Resolves false when it did not start. */ + compact(): Promise; +} + +export interface IdleCompactionConfig { + enabled: boolean; + /** Smaller contexts are cheap to send again uncached, so they are left alone. */ + minContextTokens: number; +} + +// The rules follow Claude Code's own idle compaction: only a one-hour cache is worth keeping, +// compaction starts at 90% of its lifetime, and a sweep that runs too late leaves it, since the +// cache may already be gone and compacting would then resend the whole context uncached. +export const IDLE_COMPACTION_DEFAULT_MIN_CONTEXT_TOKENS = 200_000; +const MIN_CACHE_TTL_MS = 60 * 60 * 1000; +const FIRE_AT_FRACTION = 0.9; +const MAX_LATE_MS = 60_000; +const SWEEP_INTERVAL_MS = 15_000; + +/** `agents.idleCompaction` in `config.json`: a switch, or the settings themselves. */ +export function resolveIdleCompactionConfig( + persisted: boolean | { enabled?: boolean; minContextTokens?: number } | undefined, +): IdleCompactionConfig { + const settings = typeof persisted === "boolean" ? { enabled: persisted } : (persisted ?? {}); + return { + enabled: settings.enabled ?? true, + minContextTokens: settings.minContextTokens ?? IDLE_COMPACTION_DEFAULT_MIN_CONTEXT_TOKENS, + }; +} + +interface Options extends IdleCompactionConfig { + candidates(): readonly IdleCompactionCandidate[]; + logger: Pick; + now?: () => number; + schedule?: (tick: () => void, intervalMs: number) => () => void; +} + +function scheduleInterval(tick: () => void, intervalMs: number): () => void { + const timer = setInterval(tick, intervalMs); + timer.unref?.(); + return () => clearInterval(timer); +} + +function skipReason( + candidate: IdleCompactionCandidate, + lateMs: number, + minContextTokens: number, +): string | null { + if (candidate.cache.ttlMs < MIN_CACHE_TTL_MS) return "short_ttl"; + if (lateMs > MAX_LATE_MS) return "lapsed"; + if ((candidate.contextTokens ?? 0) < minContextTokens) return "small"; + return null; +} + +/** Compacts idle agents shortly before their prompt cache expires. */ +export function createIdleCompaction(options: Options) { + const now = options.now ?? Date.now; + const logger = options.logger; + // The request each agent's cache was last judged for, so an idle period compacts at most once. + const judged = new Map(); + let sweeping: Promise | null = null; + + async function sweepOnce(): Promise { + const candidates = options.candidates(); + const present = new Set(candidates.map((candidate) => candidate.agentId)); + for (const agentId of judged.keys()) { + if (!present.has(agentId)) judged.delete(agentId); + } + + const compacted: string[] = []; + for (const candidate of candidates) { + const { agentId, cache } = candidate; + if (judged.get(agentId) === cache.lastRequestAt) continue; + + const fireAt = cache.lastRequestAt + cache.ttlMs * FIRE_AT_FRACTION; + const current = now(); + if (cache.ttlMs >= MIN_CACHE_TTL_MS && current < fireAt) continue; + judged.set(agentId, cache.lastRequestAt); + + const skip = skipReason(candidate, current - fireAt, options.minContextTokens); + if (skip) { + logger.debug( + { agentId, provider: candidate.provider, reason: skip }, + "idle_compaction_skipped", + ); + continue; + } + + try { + if (await candidate.compact()) { + compacted.push(agentId); + logger.info( + { agentId, provider: candidate.provider, contextTokens: candidate.contextTokens }, + "idle_compaction_started", + ); + } + } catch (error) { + logger.warn( + { err: error, agentId, provider: candidate.provider }, + "idle_compaction_failed", + ); + } + } + return compacted; + } + + function sweep(): Promise { + if (!options.enabled) return Promise.resolve([]); + sweeping ??= sweepOnce().finally(() => { + sweeping = null; + }); + return sweeping; + } + + const stop = options.enabled + ? (options.schedule ?? scheduleInterval)(() => void sweep(), SWEEP_INTERVAL_MS) + : () => {}; + + return { + sweep, + async close(): Promise { + stop(); + await sweeping; + }, + }; +} diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 82946a14f..756d05aa1 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -496,6 +496,7 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession close: () => inner.close(), canStopRuntime: inner.canStopRuntime?.bind(inner), hasPendingWakeup: inner.hasPendingWakeup?.bind(inner), + getPromptCacheState: inner.getPromptCacheState?.bind(inner), listCommands: inner.listCommands?.bind(inner), setModel: inner.setModel?.bind(inner), setThinkingOption: inner.setThinkingOption?.bind(inner), diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index dfa763f85..fd6500998 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -4063,6 +4063,52 @@ describe("ClaudeAgentSession context window usage", () => { } }); + test.each([ + [ + "a one-hour write", + { ephemeral_1h_input_tokens: 20, ephemeral_5m_input_tokens: 0 }, + 3_600_000, + ], + [ + "a five-minute write", + { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 20 }, + 300_000, + ], + ])( + "message_start records the prompt cache lifetime of %s", + async (_case, cacheCreation, ttlMs) => { + const usage = { + input_tokens: 100, + cache_creation_input_tokens: 20, + cache_read_input_tokens: 30, + cache_creation: cacheCreation, + }; + const readOnly = { ...usage, cache_creation_input_tokens: 0, cache_creation: {} }; + const session = await createSessionForTurns([ + [createInitMessage(), createMessageStartEvent(usage), createSuccessResult()], + [createInitMessage(), createMessageStartEvent(readOnly), createSuccessResult()], + ]); + + try { + expect(session.getPromptCacheState?.()).toBeNull(); + const before = Date.now(); + await collectStreamEvents(session); + expect(session.getPromptCacheState?.()).toEqual({ + lastRequestAt: expect.any(Number), + ttlMs, + }); + const first = session.getPromptCacheState?.()?.lastRequestAt ?? 0; + expect(first).toBeGreaterThanOrEqual(before); + + await collectStreamEvents(session); + expect(session.getPromptCacheState?.()?.ttlMs).toBe(ttlMs); + expect(session.getPromptCacheState?.()?.lastRequestAt).toBeGreaterThanOrEqual(first); + } finally { + await session.close(); + } + }, + ); + test("selected Claude models seed active context window usage with max tokens", async () => { const session = await createSessionForTurns( [[createInitMessage(), createMessageStartEvent(), createSuccessResult()]], diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index f5e31fc12..a6d878ae8 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -151,6 +151,7 @@ import { type SteerResult, type AgentStreamEvent, type AgentTimelineItem, + type AgentPromptCacheState, type AgentUsage, type AgentRuntimeInfo, type AgentClientInstallation, @@ -2208,6 +2209,28 @@ function readStreamRequestInputUsage( }; } +const PROMPT_CACHE_TTL_1H_MS = 60 * 60 * 1000; +const PROMPT_CACHE_TTL_5M_MS = 5 * 60 * 1000; + +/** + * The cache lifetime a request wrote, from `message_start.usage.cache_creation`. A request that + * only read the cache writes nothing and keeps the lifetime of the prefix it read. + */ +function readPromptCacheWriteTtlMs(event: Record): number | undefined { + const usage = toObjectRecord(toObjectRecord(event.message)?.usage); + const cacheCreation = usage ? toObjectRecord(usage.cache_creation) : undefined; + if (!cacheCreation) { + return undefined; + } + if ((readUsageCount(cacheCreation, "ephemeral_1h_input_tokens") ?? 0) > 0) { + return PROMPT_CACHE_TTL_1H_MS; + } + if ((readUsageCount(cacheCreation, "ephemeral_5m_input_tokens") ?? 0) > 0) { + return PROMPT_CACHE_TTL_5M_MS; + } + return undefined; +} + /** * The input counters on `message_delta.usage` are cumulative whole-request totals and are * optional. Mirror the Anthropic SDK's MessageStream: a counter present on the delta replaces @@ -2567,6 +2590,7 @@ class ClaudeAgentSession implements AgentSession { private readonly resultMeter = new ClaudeResultMeter(); private compacting = false; private compactionMarkerOpen = false; + private promptCache: AgentPromptCacheState | null = null; private queryPumpPromise: Promise | null = null; private queryRestartNeeded = false; /** True from the moment a query's launch options are copied until the query exists. */ @@ -3329,6 +3353,20 @@ class ClaudeAgentSession implements AgentSession { return this.persistence; } + getPromptCacheState(): AgentPromptCacheState | null { + return this.promptCache; + } + + // Main-thread stream events arrive only live, so `message_start` marks when a request was sent. + private observePromptCacheRequest(event: unknown): void { + const streamEvent = toObjectRecord(event); + if (!streamEvent || readTrimmedString(streamEvent.type) !== "message_start") { + return; + } + const ttlMs = readPromptCacheWriteTtlMs(streamEvent) ?? this.promptCache?.ttlMs; + this.promptCache = ttlMs === undefined ? null : { lastRequestAt: Date.now(), ttlMs }; + } + hasPendingWakeup(): boolean { // A delivered task notification opens its turn only with the next init. return this.notificationTurnId !== null || this.runtimeSafety.hasPendingWakeup(); @@ -5399,6 +5437,7 @@ class ClaudeAgentSession implements AgentSession { events: AgentStreamEvent[], options: { suppressAssistantText?: boolean; suppressReasoning?: boolean } | undefined, ): Promise { + this.observePromptCacheRequest(message.event); const usageUpdatedEvent = this.contextUsage.buildStreamUsageEvent(message.event); if (usageUpdatedEvent) { events.push(usageUpdatedEvent); diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 3007c7ae2..223ee17b3 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -3,6 +3,11 @@ import { createRestartRecovery } from "./agent/restart-recovery/index.js"; import { sendPromptToAgent, unarchiveAgentState } from "./agent/agent-prompt.js"; import { createChangeRequestWatches } from "./agent/change-request-watches/index.js"; import { createIdleRuntimeCleanup } from "./agent/idle-runtime-cleanup/index.js"; +import { + createIdleCompaction, + resolveIdleCompactionConfig, + type IdleCompactionConfig, +} from "./agent/idle-compaction/index.js"; import { createFinishSubscriptions, createFinishObservation, @@ -429,6 +434,7 @@ export interface PaseoDaemonConfig { downloadTokenTtlMs?: number; agentProviderSettings?: AgentProviderRuntimeSettingsMap; idleRuntimeCleanup?: boolean; + idleCompaction?: IdleCompactionConfig; resumeOnStartup?: boolean; resumePrompt?: string; providerCatalogRefreshTimeoutMs?: number; @@ -1566,6 +1572,16 @@ export async function createPaseoDaemon( idleRuntimeCleanup, ); + const idleCompaction = createIdleCompaction({ + ...(config.idleCompaction ?? resolveIdleCompactionConfig(undefined)), + // A message about to be delivered starts a turn of its own. + candidates: () => + agentManager + .getIdleCompactionCandidates() + .filter((candidate) => !(wsServer?.agentMessages.hasPending(candidate.agentId) ?? false)), + logger, + }); + const createAgentToolHostDependencies = ( runtime: PaseoToolRuntimeContext, ): PaseoToolHostDependencies => ({ @@ -2048,6 +2064,7 @@ export async function createPaseoDaemon( scriptHealthMonitor.stop(); unsubscribeIdleRuntimeCleanup(); await idleRuntimeCleanup.close(); + await idleCompaction.close(); // Freeze both ingress and registration before taking the agent closure snapshot. wsServer?.prepareForShutdown(); await changeRequestWatches.close(); diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index b5736e6a3..3337670a9 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -13,6 +13,7 @@ import { LogLevelSchema, type PersistedConfig, } from "./persisted-config.js"; +import { resolveIdleCompactionConfig } from "./agent/idle-compaction/index.js"; import type { AgentProvider } from "./agent/agent-sdk-types.js"; import type { AgentProviderRuntimeSettingsMap, @@ -597,6 +598,7 @@ export type ResolvedDaemonSettings = Pick< | "relayRequireProtectedSecurity" | "appBaseUrl" | "idleRuntimeCleanup" + | "idleCompaction" | "resumeOnStartup" | "resumePrompt" | "providerCatalogRefreshTimeoutMs" @@ -686,6 +688,7 @@ export function resolveReloadableConfig( relayEnabled: relay.enabled, relayRequireProtectedSecurity: relay.requireProtectedSecurity, idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true, + idleCompaction: resolveIdleCompaction(persisted.agents), ...resolveRestartRecoveryConfig(persisted.agents), providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs, metadataGeneration: persisted.agents?.metadataGeneration, @@ -838,6 +841,10 @@ function resolveSpeechOverrideControlledPaths( return paths; } +function resolveIdleCompaction(agents: PersistedConfig["agents"]) { + return resolveIdleCompactionConfig(agents?.idleCompaction); +} + function resolveRestartRecoveryConfig(agents: PersistedConfig["agents"]) { return { resumeOnStartup: agents?.resumeOnStartup ?? false, diff --git a/packages/server/src/server/persisted-config.ts b/packages/server/src/server/persisted-config.ts index 5181194b1..eea1f2f14 100644 --- a/packages/server/src/server/persisted-config.ts +++ b/packages/server/src/server/persisted-config.ts @@ -370,6 +370,17 @@ export const PersistedConfigSchema = z .object({ providers: z.preprocess(normalizeAgentProviders, ProviderOverridesSchema).optional(), idleRuntimeCleanup: z.boolean().optional(), + idleCompaction: z + .union([ + z.boolean(), + z + .object({ + enabled: z.boolean().optional(), + minContextTokens: z.number().int().nonnegative().optional(), + }) + .strict(), + ]) + .optional(), resumeOnStartup: z.boolean().optional(), resumePrompt: z.string().optional(), catalogRefreshTimeoutMs: z.number().int().positive().max(2_147_483_647).optional(), diff --git a/packages/website/public/schemas/paseo.config.v1.json b/packages/website/public/schemas/paseo.config.v1.json index 8ead79103..a9a9fe0fc 100644 --- a/packages/website/public/schemas/paseo.config.v1.json +++ b/packages/website/public/schemas/paseo.config.v1.json @@ -528,6 +528,27 @@ "idleRuntimeCleanup": { "type": "boolean" }, + "idleCompaction": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "minContextTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "additionalProperties": false + } + ] + }, "resumeOnStartup": { "type": "boolean" }, diff --git a/public-docs/configuration.md b/public-docs/configuration.md index 14a36520e..5ad553509 100644 --- a/public-docs/configuration.md +++ b/public-docs/configuration.md @@ -113,6 +113,31 @@ period. Active work, descendants and pending finish notifications prevent cleanu also retain runtimes with running ACP terminals, including silent ones; exited terminals do not prevent cleanup. This check does not inspect processes launched internally by the provider. +## Idle compaction + +An agent's next prompt is cheap and fast while the provider still holds its conversation in a +prompt cache. Claude keeps that cache for an hour after each request. When an idle Claude agent +has a large context, Paseo compacts it shortly before the cache expires, so the next prompt +sends a short summary instead of the whole conversation uncached. This follows Claude Code's own +idle compaction: + +- It starts at 90% of a one-hour cache lifetime and is skipped for five-minute caches. +- It needs at least 200,000 tokens of context. +- It is skipped when the daemon misses that moment by more than a minute, since the cache may + already be gone. +- It runs `/compact` as a turn of its own. The chat shows a note and the compaction; no prompt is + added, and the agent keeps its read or unread state without a notification. + +A prompt sent while it runs is handled as during a manual `/compact`. Turn it off, or change the +context threshold, +in `config.json`; changes apply when the daemon restarts: + +```json +{ "agents": { "idleCompaction": { "enabled": true, "minContextTokens": 100000 } } } +``` + +`"idleCompaction": false` turns it off. + ## Worktrees New worktrees are created under `$PASEO_HOME/worktrees` by default. To place new worktrees somewhere else, set `worktrees.root`: