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