Open History to see the last commit
1import { CommandId, MessageId, ThreadId } from "@t3tools/contracts";
2import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Schedule from "effect/Schedule";
11import type * as Scope from "effect/Scope";
12
13import { forkParked } from "../serverActivation.ts";
14import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
15import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
16
17/** Sweep cadence: how often armed threads are checked for resume readiness. */
18const USAGE_LIMIT_RESUME_SWEEP_INTERVAL = "1 minute";
19
20/** Prompt used for the automatic resume turn (matches server-update continuation). */
21const USAGE_LIMIT_RESUME_PROMPT = "Continue where you left off.";
22
23export class UsageLimitResumeReactor extends Context.Service<
24 UsageLimitResumeReactor,
25 {
26 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
27 readonly drain: Effect.Effect<void>;
28 }
29>()("t3/orchestration/UsageLimitResumeReactor") {}
30
31/** @public Service construction is part of the canonical Effect module API. */
32export const make = Effect.gen(function* () {
33 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
34 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
35 const crypto = yield* Crypto.Crypto;
36
37 const sweep = Effect.fn("UsageLimitResumeReactor.sweep")(function* () {
38 const snapshot = yield* snapshots.getShellSnapshot();
39 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
40 const dueThreads = snapshot.threads.filter(
41 (thread) =>
42 thread.usageLimitResumeAt !== null &&
43 thread.usageLimitResumeAt !== undefined &&
44 thread.session?.status !== "running" &&
45 thread.session?.status !== "starting" &&
46 DateTime.make(thread.usageLimitResumeAt).pipe(
47 Option.match({
48 onNone: () => false,
49 onSome: (resumeAt) => DateTime.toEpochMillis(resumeAt) <= nowMs,
50 }),
51 ),
52 );
53
54 yield* Effect.forEach(
55 dueThreads,
56 Effect.fn("UsageLimitResumeReactor.resumeThread")(function* (thread) {
57 // Re-read the arm: a cancel (or a user turn, which disarms in the
58 // decider) may land between the sweep's snapshot and this dispatch,
59 // and an armed-then-cancelled thread must not receive an
60 // unsolicited continuation.
61 const current = yield* snapshots.getThreadShellById(thread.id);
62 if (
63 Option.isNone(current) ||
64 current.value.usageLimitResumeAt === null ||
65 current.value.usageLimitResumeAt === undefined ||
66 current.value.usageLimitResumeAt !== thread.usageLimitResumeAt
67 ) {
68 return;
69 }
70 // The turn.start itself disarms the resume in the decider; if the
71 // provider rejects the turn again the failure re-arms a fresh window.
72 yield* engine
73 .dispatch({
74 type: "thread.turn.start",
75 commandId: CommandId.make(
76 `server:usage-limit-resume:${thread.id}:${yield* crypto.randomUUIDv4}`,
77 ),
78 threadId: ThreadId.make(thread.id),
79 message: {
80 messageId: MessageId.make(yield* crypto.randomUUIDv4),
81 role: "user",
82 text: USAGE_LIMIT_RESUME_PROMPT,
83 attachments: [],
84 },
85 runtimeMode: thread.runtimeMode,
86 interactionMode: thread.interactionMode,
87 createdAt: DateTime.formatIso(yield* DateTime.now),
88 })
89 .pipe(
90 Effect.catchCause((cause) =>
91 Cause.hasInterruptsOnly(cause)
92 ? Effect.failCause(cause)
93 : Effect.logWarning("usage-limit resume failed for thread", {
94 threadId: thread.id,
95 cause: Cause.pretty(cause),
96 }),
97 ),
98 );
99 }),
100 { concurrency: 1, discard: true },
101 );
102 });
103
104 const runSweep = sweep().pipe(
105 Effect.catchCause((cause) =>
106 Cause.hasInterruptsOnly(cause)
107 ? Effect.failCause(cause)
108 : Effect.logWarning("usage-limit resume sweep failed", {
109 cause: Cause.pretty(cause),
110 }),
111 ),
112 );
113 const worker = yield* makeDrainableWorker(() => runSweep);
114
115 const start: UsageLimitResumeReactor["Service"]["start"] = Effect.fn(
116 "UsageLimitResumeReactor.start",
117 )(function* () {
118 yield* forkParked(
119 Effect.gen(function* () {
120 yield* worker.enqueue(undefined);
121 yield* worker.drain;
122 }).pipe(Effect.repeat(Schedule.spaced(USAGE_LIMIT_RESUME_SWEEP_INTERVAL)), Effect.asVoid),
123 );
124 });
125
126 return { start, drain: worker.drain } satisfies UsageLimitResumeReactor["Service"];
127});
128
129export const layer = Layer.effect(UsageLimitResumeReactor, make);