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

IdleCompactionService.ts

100 lines3.6 KB

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