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

IdleCompactionService.ts

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