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

IdleCompactionService.ts

116 lines4.3 KB

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, runId: RunId) {
35 // Loops once after the wait: the thread may have moved on.
36 while (true) {
37 const current = yield* settings.getSettings;
38 const thread = yield* projections.getThread(threadId);
39 const claudeInstance = Object.hasOwn(current.providerInstances, thread.providerInstanceId)
40 ? current.providerInstances[thread.providerInstanceId]?.driver === "claudeAgent"
41 : thread.providerInstanceId === "claudeAgent";
42 if (
43 !claudeInstance ||
44 resolveIdleCompaction(current, thread.providerInstanceId) !== "beforeCacheExpires" ||
45 !resolveProjectProviderInstanceEnabled(
46 current,
47 thread.projectId,
48 thread.providerInstanceId,
49 )
50 )
51 return;
52 const records = yield* projections.getThreadRecords(
53 threadId,
54 [
55 "runs",
56 "messages",
57 "providerThreads",
58 "providerTurns",
59 "runtimeRequests",
60 "turnItems",
61 "contextTransfers",
62 ],
63 { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] },
64 );
65 if (
66 resolveIdleCompaction(current, records.thread.providerInstanceId) !==
67 "beforeCacheExpires" ||
68 !resolveProjectProviderInstanceEnabled(
69 current,
70 records.thread.projectId,
71 records.thread.providerInstanceId,
72 )
73 )
74 return;
75 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
76 const window = idleCompactionWindow(records, nowMs);
77 if (window?.runId !== runId) return;
78 if (nowMs < window.startMs) {
79 yield* Effect.sleep(Duration.millis(window.startMs - nowMs));
80 continue;
81 }
82 yield* orchestrator.dispatch({
83 type: "message.dispatch",
84 // One compaction per completed run, even across duplicate events.
85 commandId: CommandId.make(`server:idle-compact:${threadId}:${runId}`),
86 messageId: MessageId.make(`idle-compact:${threadId}:${runId}`),
87 threadId,
88 text: IDLE_COMPACTION_TEXT,
89 attachments: [],
90 createdBy: "agent",
91 creationSource: "server",
92 idleCompaction: "beforeCacheExpires",
93 dispatchMode: { type: "start_immediately" },
94 });
95 return;
96 }
97 },
98 (effect, threadId) =>
99 effect.pipe(
100 Effect.catch((cause) => Effect.logWarning("idle compaction skipped", { threadId, cause })),
101 ),
102 );
103​
104 const start = Effect.fn("IdleCompactionService.start")(function* () {
105 // Keyed by thread: a newer completed run replaces the waiting timer.
106 const timers = yield* FiberMap.make<ThreadId>();
107 yield* forkParked(
108 Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
109 event.type === "run.updated" && event.payload.status === "completed"
110 ? FiberMap.run(timers, event.threadId, compactWhenDue(event.threadId, event.payload.id))
111 : Effect.void,
112 ),
113 );
114 });
115 return { start };
116});