Open History to see the last commit
1import {
2 CommandId,
3 IDLE_COMPACTION_TEXT,
4 MessageId,
5 resolveIdleCompaction,
6 resolveProjectProviderInstanceEnabled,
7 type RunId,
8 type ThreadId,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FiberMap from "effect/FiberMap";
14import * as Stream from "effect/Stream";
15
16import { forkParked } from "../serverActivation.ts";
17import * as ServerSettings from "../serverSettings.ts";
18import { idleCompactionWindow } from "./IdleCompaction.ts";
19import * as Orchestrator from "./Orchestrator.ts";
20import * as ProjectionStore from "./ProjectionStore.ts";
21
22/**
23 * Beta: when a run completes on a Claude instance set to compact before the
24 * cache expires, waits until shortly before its prompt cache expires and sends
25 * `/compact` as a visible T3 Code turn. Timers live in
26 * memory, so a server restart skips compactions that were still waiting.
27 */
28export const make = Effect.gen(function* () {
29 const orchestrator = yield* Orchestrator.OrchestratorV2;
30 const projections = yield* ProjectionStore.ProjectionStoreV2;
31 const settings = yield* ServerSettings.ServerSettingsService;
32
33 const compactWhenDue = Effect.fn("IdleCompactionService.compactWhenDue")(
34 function* (threadId: ThreadId, completedRunId: RunId) {
35 let runId = completedRunId;
36 // Loops after the wait or a retarget: the thread may have moved on.
37 while (true) {
38 const current = yield* settings.getSettings;
39 const thread = yield* projections.getThread(threadId);
40 const claudeInstance = Object.hasOwn(current.providerInstances, thread.providerInstanceId)
41 ? current.providerInstances[thread.providerInstanceId]?.driver === "claudeAgent"
42 : thread.providerInstanceId === "claudeAgent";
43 if (
44 !claudeInstance ||
45 resolveIdleCompaction(current, thread.providerInstanceId) !== "beforeCacheExpires" ||
46 !resolveProjectProviderInstanceEnabled(
47 current,
48 thread.projectId,
49 thread.providerInstanceId,
50 )
51 )
52 return;
53 const records = yield* projections.getThreadRecords(
54 threadId,
55 [
56 "runs",
57 "messages",
58 "providerThreads",
59 "providerTurns",
60 "runtimeRequests",
61 "turnItems",
62 "contextTransfers",
63 ],
64 { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] },
65 );
66 if (
67 resolveIdleCompaction(current, records.thread.providerInstanceId) !==
68 "beforeCacheExpires" ||
69 !resolveProjectProviderInstanceEnabled(
70 current,
71 records.thread.projectId,
72 records.thread.providerInstanceId,
73 )
74 )
75 return;
76 const latestRun = records.runs.reduce<(typeof records.runs)[number] | undefined>(
77 (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest),
78 undefined,
79 );
80 // A late update for an earlier run replaced the latest run's timer, so take it over.
81 if (latestRun?.status === "completed" && latestRun.id !== runId) {
82 runId = latestRun.id;
83 continue;
84 }
85 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
86 const window = idleCompactionWindow(records, nowMs);
87 if (window?.runId !== runId) return;
88 if (nowMs < window.startMs) {
89 yield* Effect.sleep(Duration.millis(window.startMs - nowMs));
90 continue;
91 }
92 yield* orchestrator.dispatch({
93 type: "message.dispatch",
94 // One compaction per completed run, even across duplicate events.
95 commandId: CommandId.make(`server:idle-compact:${threadId}:${runId}`),
96 messageId: MessageId.make(`idle-compact:${threadId}:${runId}`),
97 threadId,
98 text: IDLE_COMPACTION_TEXT,
99 attachments: [],
100 createdBy: "agent",
101 creationSource: "server",
102 idleCompaction: "beforeCacheExpires",
103 dispatchMode: { type: "start_immediately" },
104 });
105 return;
106 }
107 },
108 (effect, threadId) =>
109 effect.pipe(
110 Effect.catch((cause) => Effect.logWarning("idle compaction skipped", { threadId, cause })),
111 ),
112 );
113
114 const start = Effect.fn("IdleCompactionService.start")(function* () {
115 // Keyed by thread: a newer completed run replaces the waiting timer.
116 const timers = yield* FiberMap.make<ThreadId>();
117 yield* forkParked(
118 Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
119 event.type === "run.updated" && event.payload.status === "completed"
120 ? FiberMap.run(timers, event.threadId, compactWhenDue(event.threadId, event.payload.id))
121 : Effect.void,
122 ),
123 );
124 });
125 return { start };
126});