Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IdleCompaction.ts

103 lines4.1 KB

1import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction";
3import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
4import * as DateTime from "effect/DateTime";
5​
6// Claude Code's idleCompaction defaults to 200K and won't go below 100K. Below
7// that a cold re-read is cheap, so compacting mostly loses context for little
8// saving.
9const MIN_CONTEXT_TOKENS = COMPACTION_SUGGESTION_MIN_TOKENS;
10// Start this long before the cache expires: enough for the session to resume
11// and send the compaction while the cache is still warm.
12const LEAD_MS = 2 * 60_000;
13​
14export type IdleCompactionRecords = Pick<
15 OrchestrationV2ThreadProjection,
16 | "thread"
17 | "runs"
18 | "messages"
19 | "providerThreads"
20 | "providerTurns"
21 | "runtimeRequests"
22 | "turnItems"
23 | "contextTransfers"
24>;
25​
26/**
27 * When an idle Claude thread should compact, or null when it should not. The
28 * window ends when the prompt cache of Claude's last request expires (1h on
29 * subscriptions, 5m on API keys); compacting after that pays a full uncached
30 * read.
31 */
32export function idleCompactionWindow(
33 {
34 thread,
35 runs,
36 messages,
37 providerThreads,
38 providerTurns,
39 runtimeRequests,
40 turnItems,
41 contextTransfers,
42 }: IdleCompactionRecords,
43 nowMs: number,
44): {
45 readonly runId: (typeof runs)[number]["id"];
46 readonly startMs: number;
47 readonly endMs: number;
48} | null {
49 if (thread.deletedAt !== null || thread.archivedAt !== null) return null;
50 if (thread.settledAt !== null || thread.settledOverride === "settled") return null;
51 if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)
52 return null;
53 if (!isListedThreadLineage(thread.lineage)) return null;
54 const latestRun = runs.reduce<(typeof runs)[number] | null>(
55 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
56 null,
57 );
58 if (latestRun?.status !== "completed" || latestRun.completedAt === null) return null;
59 const message = messages.find((candidate) => candidate.id === latestRun.userMessageId);
60 // Never compact a compaction, so one idle spell compacts at most once.
61 if (message === undefined || message.text.trim().toLowerCase() === "/compact") return null;
62 if (
63 runtimeRequests.some((request) => request.status === "pending") ||
64 // A pending merge-back belongs to the user's next message.
65 contextTransfers.some(
66 (transfer) =>
67 transfer.type === "merge_back" &&
68 transfer.targetThreadId === thread.id &&
69 transfer.status === "pending",
70 ) ||
71 // Background work reports into the next turn; compaction would swallow it.
72 derivePendingBackgroundWork({
73 latestRun,
74 runs,
75 providerThreads,
76 turnItems,
77 activeProviderThreadId: thread.activeProviderThreadId,
78 }).length > 0
79 )
80 return null;
81 const providerThread = providerThreads.find(
82 (candidate) => candidate.id === thread.activeProviderThreadId,
83 );
84 // The thread's current selection receives the /compact, so it must still be this Claude session.
85 if (
86 providerThread?.driver !== "claudeAgent" ||
87 providerThread.id !== latestRun.providerThreadId ||
88 providerThread.providerInstanceId !== thread.providerInstanceId ||
89 latestRun.providerInstanceId !== thread.providerInstanceId
90 )
91 return null;
92 const usages = providerTurns
93 .filter((turn) => turn.providerThreadId === providerThread.id && turn.tokenUsage !== undefined)
94 .map((turn) => turn.tokenUsage!)
95 .toSorted((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt));
96 if ((usages[0]?.usedTokens ?? 0) < MIN_CONTEXT_TOKENS) return null;
97 // A request served fully from cache creates no cache entry and reports no
98 // TTL, but it still refreshes the cache. Treat it as unknown and skip.
99 const expiresAt = usages[0]?.promptCacheExpiresAt;
100 const endMs = expiresAt === undefined ? Number.NaN : Date.parse(expiresAt);
101 if (!Number.isFinite(endMs) || nowMs >= endMs) return null;
102 return { runId: latestRun.id, startMs: endMs - LEAD_MS, endMs };