Open History to see the last commit
1import type {
2 OrchestrationV2ProviderFailure,
3 OrchestrationV2Run,
4 OrchestrationV2TurnItem,
5} from "@t3tools/contracts";
6import * as DateTime from "effect/DateTime";
7
8type ErrorTurnItem = Extract<OrchestrationV2TurnItem, { type: "error" }>;
9/** Error items and the first input of each run are read, so callers may pass items stripped of other fields. */
10type FailureScanTurnItem =
11 | ErrorTurnItem
12 | {
13 readonly type: Exclude<OrchestrationV2TurnItem["type"], "error">;
14 readonly nodeId?: OrchestrationV2TurnItem["nodeId"];
15 readonly ordinal?: number;
16 };
17
18export function latestRootProviderFailure(
19 run: OrchestrationV2Run | null,
20 turnItems: ReadonlyArray<FailureScanTurnItem>,
21): OrchestrationV2ProviderFailure | null {
22 if (run?.status !== "failed") return null;
23 let latest: ErrorTurnItem | null = null;
24 for (const item of turnItems) {
25 if (
26 item.type !== "error" ||
27 item.status !== "failed" ||
28 item.runId !== run.id ||
29 item.nodeId !== run.rootNodeId
30 )
31 continue;
32 if (
33 latest === null ||
34 DateTime.toEpochMillis(item.updatedAt) > DateTime.toEpochMillis(latest.updatedAt) ||
35 (DateTime.toEpochMillis(item.updatedAt) === DateTime.toEpochMillis(latest.updatedAt) &&
36 (item.ordinal > latest.ordinal || (item.ordinal === latest.ordinal && item.id > latest.id)))
37 ) {
38 latest = item;
39 }
40 }
41 return latest?.failure ?? null;
42}
43
44export function threadErrorSummary(
45 failure: OrchestrationV2ProviderFailure | null,
46 sessionError: string | null,
47) {
48 const currentFailure =
49 sessionError !== null && sessionError !== failure?.message ? null : failure;
50 return {
51 usageLimitResetAt:
52 currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,
53 lastError: sessionError ?? failure?.message ?? null,
54 lastErrorClass: currentFailure?.class ?? null,
55 lastErrorCode: currentFailure?.code ?? null,
56 };
57}
58
59export function latestExecutedRun(
60 runs: ReadonlyArray<OrchestrationV2Run>,
61): OrchestrationV2Run | null {
62 let latest: OrchestrationV2Run | null = null;
63 for (const run of runs) {
64 if (run.status === "queued") continue;
65 if (run.status === "cancelled" && run.startedAt === null) continue;
66 if (latest === null || runRanAfter(run, latest)) latest = run;
67 }
68 return latest;
69}
70
71/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
72export function runRanAfter(
73 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
74 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
75): boolean {
76 const end = (candidate: typeof run) =>
77 !candidate.completedAt
78 ? Number.POSITIVE_INFINITY
79 : DateTime.toEpochMillis(candidate.completedAt);
80 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
81}
82
83/**
84 * Background subagents that die on a usage limit each start a root run from a notification.
85 * Those runs finish within milliseconds, before the limit resets, and have no work to show.
86 * They must not replace the limited run, or the thread is never armed or resumed.
87 * Items of types other than user_message, notification and error may be omitted.
88 */
89function runsWithoutLimitedWakes(
90 runs: ReadonlyArray<OrchestrationV2Run>,
91 turnItems: ReadonlyArray<FailureScanTurnItem>,
92): ReadonlyArray<OrchestrationV2Run> {
93 const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));
94 const failure = latestRootProviderFailure(failed, turnItems);
95 if (failure?.class !== "usage_limit" || failure.resetAt == null) return runs;
96 const resetMs = Date.parse(failure.resetAt);
97 if (!Number.isFinite(resetMs)) return runs;
98 const firstInputs = new Map<string, { readonly type: string; readonly ordinal: number }>();
99 for (const item of turnItems) {
100 if (item.nodeId == null || item.ordinal == null) continue;
101 if (item.type !== "user_message" && item.type !== "notification") continue;
102 const first = firstInputs.get(item.nodeId);
103 if (first === undefined || item.ordinal < first.ordinal) {
104 firstInputs.set(item.nodeId, { type: item.type, ordinal: item.ordinal });
105 }
106 }
107 return runs.filter(
108 (run) =>
109 run.status !== "completed" ||
110 run.completedAt === null ||
111 DateTime.toEpochMillis(run.completedAt) > resetMs ||
112 run.rootNodeId === null ||
113 firstInputs.get(run.rootNodeId)?.type !== "notification",
114 );
115}
116
117export function usageLimitBlockedRun(
118 runs: ReadonlyArray<OrchestrationV2Run>,
119 turnItems: ReadonlyArray<FailureScanTurnItem>,
120 sessionError: string | null,
121): OrchestrationV2Run | null {
122 const executed = latestExecutedRun(runsWithoutLimitedWakes(runs, turnItems));
123 if (executed?.status !== "failed") return null;
124 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
125 return summary.lastErrorClass === "usage_limit" ? executed : null;
126}
127
128/** Retains a limited run's outcome when higher-ordinal runs never started. */
129export function usageLimitRunPresentedAsLatest(
130 runs: ReadonlyArray<OrchestrationV2Run>,
131 turnItems: ReadonlyArray<FailureScanTurnItem>,
132 sessionError: string | null,
133): OrchestrationV2Run | null {
134 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
135 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
136}
137
138export function latestUnheldRun(
139 runs: ReadonlyArray<OrchestrationV2Run>,
140): OrchestrationV2Run | null {
141 let latest: OrchestrationV2Run | null = null;
142 for (const run of runs) {
143 if (run.status === "queued" && run.queueHeld === true) continue;
144 if (latest === null || run.ordinal > latest.ordinal) latest = run;
145 }
146 return latest;
147}