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

IdleCompactionService.ts

97 lines3.5 KB

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