Open History to see the last commit
1import { CommandId, MessageId, type OrchestrationV2Command } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Stream from "effect/Stream";
6import type { OrchestrationV2DomainEvent } from "@t3tools/contracts";
7import * as DueHint from "../scheduling/DueHint.ts";
8import * as Scheduler from "../scheduling/Scheduler.ts";
9import { forkParked } from "../serverActivation.ts";
10import * as ServerSettings from "../serverSettings.ts";
11import * as ProjectionStore from "./ProjectionStore.ts";
12import * as Orchestrator from "./Orchestrator.ts";
13import * as ThreadManagement from "./ThreadManagementService.ts";
14import { routineSpan } from "@t3tools/shared/observability";
15
16export const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000;
17
18export function limitRecoveryCommand(
19 thread: ProjectionStore.ProjectionLimitRecoveryCandidate,
20 autoResume: boolean,
21 nowMs: number,
22 snooze = false,
23): OrchestrationV2Command | null {
24 if (
25 thread.status !== "failed" ||
26 thread.lastErrorClass !== "usage_limit" ||
27 !thread.latestRunId ||
28 !thread.usageLimitResetAt ||
29 thread.archivedAt !== null ||
30 thread.settledOverride === "settled" ||
31 thread.pendingRuntimeRequest !== null
32 )
33 return null;
34 const resetMs = Date.parse(thread.usageLimitResetAt);
35 // An already-expired window reported with a fresh failure cannot start a retry loop.
36 if (
37 !Number.isFinite(resetMs) ||
38 resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt)
39 )
40 return null;
41 const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`;
42 const recovery = thread.limitRecovery;
43 if (recovery?.runId !== thread.latestRunId || recovery.resetAt !== thread.usageLimitResetAt) {
44 if (nowMs - resetMs > MAX_OVERDUE_ARM_MS) return null;
45 if (!autoResume && (!snooze || resetMs <= nowMs)) return null;
46 return {
47 type: "thread.metadata.update",
48 commandId: CommandId.make(`limit-arm:${identity}`),
49 threadId: thread.id,
50 limitRecovery: {
51 runId: thread.latestRunId,
52 resetAt: thread.usageLimitResetAt,
53 autoResume,
54 snooze: snooze && resetMs > nowMs,
55 },
56 };
57 }
58 if (
59 !recovery.autoResume ||
60 resetMs > nowMs ||
61 (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)
62 )
63 return null;
64 const deliveryIdentity = `${identity}:${recovery.requestId ?? "legacy"}`;
65 return {
66 type: "message.dispatch",
67 commandId: CommandId.make(`limit-resume:${deliveryIdentity}`),
68 messageId: MessageId.make(`limit-resume:${deliveryIdentity}`),
69 threadId: thread.id,
70 usageLimitContinuationOfRunId: thread.latestRunId,
71 ...(recovery.requestId === undefined
72 ? {}
73 : { usageLimitRecoveryRequestId: recovery.requestId }),
74 text: "Continue where you left off.",
75 attachments: [],
76 dispatchMode: { type: "start_immediately" },
77 createdBy: "agent",
78 creationSource: "server",
79 };
80}
81
82// Events that can make a thread a candidate or change its command; streaming items cannot.
83const affectsLimitRecovery = (event: OrchestrationV2DomainEvent) =>
84 event.type.startsWith("thread.") ||
85 event.type === "run.created" ||
86 event.type === "run.updated" ||
87 event.type === "runtime-request.updated" ||
88 event.type.startsWith("provider-session.") ||
89 (event.type === "turn-item.updated" && event.payload.type === "error");
90
91const makeSweep = Effect.gen(function* () {
92 const projections = yield* ProjectionStore.ProjectionStoreV2;
93 const threads = yield* ThreadManagement.ThreadManagementService;
94 const orchestrator = yield* Orchestrator.OrchestratorV2;
95 const settings = yield* ServerSettings.ServerSettingsService;
96 const due = DueHint.make();
97 yield* forkParked(
98 Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
99 affectsLimitRecovery(event) ? due.invalidate : Effect.void,
100 ),
101 );
102 yield* forkParked(Stream.runForEach(settings.streamChanges, () => due.invalidate));
103 return Effect.fn("UsageLimitRecoveryWorker.sweep", { attributes: routineSpan })(function* () {
104 const now = yield* DateTime.now;
105 const nowMs = DateTime.toEpochMillis(now);
106 if (yield* due.isIdle(nowMs)) return;
107 const readVersion = yield* due.version;
108 const preferences = yield* settings.getSettings;
109 const candidates = yield* projections.getLimitRecoveryCandidates({
110 now,
111 autoResume: preferences.autoResumeLimitedThreads,
112 snooze: preferences.snoozeLimitedThreads,
113 });
114 let acted = false;
115 for (const thread of candidates) {
116 const command = limitRecoveryCommand(
117 thread,
118 preferences.autoResumeLimitedThreads,
119 nowMs,
120 preferences.snoozeLimitedThreads,
121 );
122 if (command === null) continue;
123 acted = true;
124 yield* Effect.gen(function* () {
125 if (command.type === "thread.metadata.update" && command.limitRecovery != null) {
126 yield* orchestrator.autoArmLimitRecovery({
127 commandId: command.commandId,
128 threadId: command.threadId,
129 limitRecovery: command.limitRecovery,
130 });
131 } else {
132 yield* threads.dispatch(command);
133 }
134 }).pipe(
135 Effect.catchCause((cause) =>
136 Effect.logWarning("orchestration-v2.limit-recovery.dispatch-failed", {
137 threadId: thread.id,
138 cause,
139 }),
140 ),
141 );
142 }
143 // A sweep that acted, or failed to, re-checks on the next tick.
144 if (acted) return;
145 const wakeAt = yield* projections.getLimitRecoveryWakeAt(now);
146 yield* due.record(readVersion, wakeAt ?? Infinity, nowMs);
147 });
148});
149
150export const layer = Layer.effectDiscard(
151 Effect.gen(function* () {
152 const sweep = yield* makeSweep;
153 const scheduler = yield* Scheduler.Scheduler;
154 yield* scheduler.register("usage-limit-recovery", sweep());
155 }),
156);