Open History to see the last commit
1import type {
2 OrchestrationV2LimitRecovery,
3 OrchestrationV2ProviderFailure,
4 OrchestrationV2Run,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8
9type ErrorTurnItem = Extract<OrchestrationV2TurnItem, { type: "error" }>;
10/** Only error items are read, so callers may pass items stripped of other fields. */
11type FailureScanTurnItem =
12 | ErrorTurnItem
13 | { readonly type: Exclude<OrchestrationV2TurnItem["type"], "error"> };
14
15export function latestRootProviderFailure(
16 run: OrchestrationV2Run | null,
17 turnItems: ReadonlyArray<FailureScanTurnItem>,
18): OrchestrationV2ProviderFailure | null {
19 if (run?.status !== "failed") return null;
20 let latest: ErrorTurnItem | null = null;
21 for (const item of turnItems) {
22 if (
23 item.type !== "error" ||
24 item.status !== "failed" ||
25 item.runId !== run.id ||
26 item.nodeId !== run.rootNodeId
27 )
28 continue;
29 if (
30 latest === null ||
31 DateTime.toEpochMillis(item.updatedAt) > DateTime.toEpochMillis(latest.updatedAt) ||
32 (DateTime.toEpochMillis(item.updatedAt) === DateTime.toEpochMillis(latest.updatedAt) &&
33 (item.ordinal > latest.ordinal || (item.ordinal === latest.ordinal && item.id > latest.id)))
34 ) {
35 latest = item;
36 }
37 }
38 return latest?.failure ?? null;
39}
40
41export function threadErrorSummary(
42 failure: OrchestrationV2ProviderFailure | null,
43 sessionError: string | null,
44) {
45 const currentFailure =
46 sessionError !== null && sessionError !== failure?.message ? null : failure;
47 return {
48 usageLimitResetAt:
49 currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,
50 lastError: sessionError ?? failure?.message ?? null,
51 lastErrorClass: currentFailure?.class ?? null,
52 lastErrorCode: currentFailure?.code ?? null,
53 };
54}
55
56export function latestExecutedRun(
57 runs: ReadonlyArray<OrchestrationV2Run>,
58): OrchestrationV2Run | null {
59 let latest: OrchestrationV2Run | null = null;
60 for (const run of runs) {
61 if (run.status === "queued") continue;
62 if (run.status === "cancelled" && run.startedAt === null) continue;
63 if (latest === null || runRanAfter(run, latest)) latest = run;
64 }
65 return latest;
66}
67
68/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
69export function runRanAfter(
70 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
71 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
72): boolean {
73 const end = (candidate: typeof run) =>
74 !candidate.completedAt
75 ? Number.POSITIVE_INFINITY
76 : DateTime.toEpochMillis(candidate.completedAt);
77 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
78}
79
80export function usageLimitBlockedRun(
81 runs: ReadonlyArray<OrchestrationV2Run>,
82 turnItems: ReadonlyArray<FailureScanTurnItem>,
83 sessionError: string | null,
84): OrchestrationV2Run | null {
85 const executed = latestExecutedRun(runs);
86 if (executed?.status !== "failed") return null;
87 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
88 return summary.lastErrorClass === "usage_limit" ? executed : null;
89}
90
91const REFUSED_CONTINUATION_BACKOFF_MINUTES = [2, 5, 15] as const;
92
93/** A usage-limit failure's reset when it is after the run ended; null when not limited. */
94function laterUsageLimitReset(
95 run: OrchestrationV2Run,
96 turnItems: ReadonlyArray<FailureScanTurnItem>,
97): { readonly resetAt: string | null } | null {
98 const failure = latestRootProviderFailure(run, turnItems);
99 if (failure?.class !== "usage_limit") return null;
100 const endedMs = DateTime.toEpochMillis(run.completedAt ?? run.requestedAt);
101 return {
102 resetAt: failure.resetAt && Date.parse(failure.resetAt) > endedMs ? failure.resetAt : null,
103 };
104}
105
106/**
107 * When usage-limit recovery may resume `run`: the provider's reset when it is after the run
108 * ended. A continuation refused with no later reset retries after a backoff, giving up after
109 * the last step; any other limited run without a later reset has nothing to wait for.
110 */
111export function usageLimitRecoveryResetAt(
112 run: OrchestrationV2Run | null,
113 runs: ReadonlyArray<OrchestrationV2Run>,
114 turnItems: ReadonlyArray<FailureScanTurnItem>,
115): string | null {
116 const limit = run === null ? null : laterUsageLimitReset(run, turnItems);
117 if (run === null || limit === null) return null;
118 if (limit.resetAt !== null) return limit.resetAt;
119 let refusals = 0;
120 for (const current of usageLimitContinuationChain(run, runs)) {
121 if (current.usageLimitContinuationOfRunId === undefined) break;
122 const refused = laterUsageLimitReset(current, turnItems);
123 if (refused === null || refused.resetAt !== null) break;
124 refusals += 1;
125 }
126 return refusedContinuationRetryAt(run.completedAt ?? run.requestedAt, refusals);
127}
128
129/** When recovery retries a continuation refused `refusals` times in a row; null once it gives up. */
130export function refusedContinuationRetryAt(endedAt: DateTime.Utc, refusals: number): string | null {
131 const minutes = REFUSED_CONTINUATION_BACKOFF_MINUTES[refusals - 1];
132 return minutes === undefined ? null : DateTime.formatIso(DateTime.add(endedAt, { minutes }));
133}
134
135/**
136 * `run` and the runs its continuation chain retries, as far as the backoff can count, so a
137 * long or cyclic chain costs at most one more step than the backoff has.
138 */
139export function usageLimitContinuationChain(
140 run: OrchestrationV2Run,
141 runs: ReadonlyArray<OrchestrationV2Run>,
142): ReadonlyArray<OrchestrationV2Run> {
143 const chain = [run];
144 let current: OrchestrationV2Run | undefined = run;
145 while (
146 chain.length <= REFUSED_CONTINUATION_BACKOFF_MINUTES.length &&
147 current.usageLimitContinuationOfRunId !== undefined
148 ) {
149 const sourceRunId: string = current.usageLimitContinuationOfRunId;
150 current = runs.find((candidate) => candidate.id === sourceRunId);
151 if (current === undefined) break;
152 chain.push(current);
153 }
154 return chain;
155}
156
157/**
158 * The reset a usage-limit notice offers for `runId`, which stopped at `stoppedAtMs`: the
159 * provider's reset when it is later. Otherwise a recovery still armed for the run (auto-resume
160 * on, or its snooze still ahead) carries the server's retry time; else the provider's reset.
161 */
162export function usageLimitNoticeResetAt(input: {
163 readonly runId: string | null | undefined;
164 readonly resetAt: string | null | undefined;
165 readonly stoppedAtMs: number;
166 readonly recovery: OrchestrationV2LimitRecovery | null | undefined;
167 readonly snoozedUntilMs: number | null;
168 readonly nowMs: number;
169}): string | null {
170 const { runId, resetAt, stoppedAtMs, recovery, snoozedUntilMs, nowMs } = input;
171 if (resetAt != null && Date.parse(resetAt) > stoppedAtMs) return resetAt;
172 if (runId == null || recovery?.runId !== runId) return resetAt ?? null;
173 const retryMs = Date.parse(recovery.resetAt);
174 const armed =
175 recovery.autoResume ||
176 (recovery.snooze === true && snoozedUntilMs === retryMs && retryMs > nowMs);
177 return armed && retryMs > stoppedAtMs ? recovery.resetAt : (resetAt ?? null);
178}
179
180/** Retains a limited run's outcome when higher-ordinal runs never started. */
181export function usageLimitRunPresentedAsLatest(
182 runs: ReadonlyArray<OrchestrationV2Run>,
183 turnItems: ReadonlyArray<FailureScanTurnItem>,
184 sessionError: string | null,
185): OrchestrationV2Run | null {
186 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
187 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
188}
189
190export function latestUnheldRun(
191 runs: ReadonlyArray<OrchestrationV2Run>,
192): OrchestrationV2Run | null {
193 let latest: OrchestrationV2Run | null = null;
194 for (const run of runs) {
195 if (run.status === "queued" && run.queueHeld === true) continue;
196 if (latest === null || run.ordinal > latest.ordinal) latest = run;
197 }
198 return latest;
199}