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, run inputs and the run of other items are read, so callers may pass stripped items. */
10type FailureScanTurnItem =
11 | ErrorTurnItem
12 | {
13 readonly type: Exclude<OrchestrationV2TurnItem["type"], "error">;
14 readonly runId?: OrchestrationV2TurnItem["runId"];
15 readonly nodeId?: OrchestrationV2TurnItem["nodeId"];
16 readonly ordinal?: number;
17 };
18
19export function latestRootProviderFailure(
20 run: OrchestrationV2Run | null,
21 turnItems: ReadonlyArray<FailureScanTurnItem>,
22): OrchestrationV2ProviderFailure | null {
23 if (run?.status !== "failed") return null;
24 let latest: ErrorTurnItem | null = null;
25 for (const item of turnItems) {
26 if (
27 item.type !== "error" ||
28 item.status !== "failed" ||
29 item.runId !== run.id ||
30 item.nodeId !== run.rootNodeId
31 )
32 continue;
33 if (
34 latest === null ||
35 DateTime.toEpochMillis(item.updatedAt) > DateTime.toEpochMillis(latest.updatedAt) ||
36 (DateTime.toEpochMillis(item.updatedAt) === DateTime.toEpochMillis(latest.updatedAt) &&
37 (item.ordinal > latest.ordinal || (item.ordinal === latest.ordinal && item.id > latest.id)))
38 ) {
39 latest = item;
40 }
41 }
42 return latest?.failure ?? null;
43}
44
45export function threadErrorSummary(
46 failure: OrchestrationV2ProviderFailure | null,
47 sessionError: string | null,
48) {
49 const currentFailure =
50 sessionError !== null && sessionError !== failure?.message ? null : failure;
51 return {
52 usageLimitResetAt:
53 currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,
54 lastError: sessionError ?? failure?.message ?? null,
55 lastErrorClass: currentFailure?.class ?? null,
56 lastErrorCode: currentFailure?.code ?? null,
57 };
58}
59
60export function latestExecutedRun(
61 runs: ReadonlyArray<OrchestrationV2Run>,
62): OrchestrationV2Run | null {
63 let latest: OrchestrationV2Run | null = null;
64 for (const run of runs) {
65 if (run.status === "queued") continue;
66 if (run.status === "cancelled" && run.startedAt === null) continue;
67 if (latest === null || runRanAfter(run, latest)) latest = run;
68 }
69 return latest;
70}
71
72/**
73 * Work started now would run in the project checkout, not the worktree the thread asked for. A
74 * failed or interrupted setup leaves the request standing until a worktree exists or later work
75 * has run past it.
76 */
77export function orchestrationV2WorktreePending(
78 worktreePath: string | null,
79 runs: ReadonlyArray<OrchestrationV2Run>,
80): boolean {
81 const latest = latestExecutedRun(runs);
82 return (
83 worktreePath === null &&
84 (latest?.status === "preparing" ||
85 latest?.status === "failed" ||
86 latest?.status === "interrupted") &&
87 latest.workspacePreparation?.type === "worktree"
88 );
89}
90
91/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
92export function runRanAfter(
93 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
94 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
95): boolean {
96 const end = (candidate: typeof run) =>
97 !candidate.completedAt
98 ? Number.POSITIVE_INFINITY
99 : DateTime.toEpochMillis(candidate.completedAt);
100 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
101}
102
103/**
104 * Subagents that die on a usage limit start notification runs that finish before the reset
105 * with no work to show. These candidates ran on the limited provider after its latest failure
106 * and before the reset; continuations and other providers' runs are never wakes.
107 */
108export function usageLimitWakeCandidates(
109 runs: ReadonlyArray<OrchestrationV2Run>,
110 turnItems: ReadonlyArray<FailureScanTurnItem>,
111): ReadonlyArray<OrchestrationV2Run> {
112 const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));
113 const failure = latestRootProviderFailure(failed, turnItems);
114 if (failed === null || failure?.class !== "usage_limit" || failure.resetAt == null) return [];
115 const resetMs = Date.parse(failure.resetAt);
116 if (!Number.isFinite(resetMs)) return [];
117 return runs.filter(
118 (run) =>
119 run.status === "completed" &&
120 run.completedAt !== null &&
121 run.rootNodeId !== null &&
122 run.providerInstanceId === failed.providerInstanceId &&
123 DateTime.toEpochMillis(run.completedAt) <= resetMs &&
124 runRanAfter(run, failed) &&
125 run.manualContinuationOfRunId === undefined &&
126 run.usageLimitContinuationOfRunId === undefined &&
127 run.restartContinuationOfRunId === undefined,
128 );
129}
130
131/** Inputs, and the interrupt signal Stop leaves on the latest run, are not work. */
132export const NO_WORK_ITEM_TYPES: ReadonlySet<OrchestrationV2TurnItem["type"]> = new Set([
133 "user_message",
134 "notification",
135 "run_interrupt_request",
136]);
137
138/** The wake candidates a notification started; only those without any other item are wakes. */
139export function notificationStartedWakeCandidates(
140 runs: ReadonlyArray<OrchestrationV2Run>,
141 turnItems: ReadonlyArray<FailureScanTurnItem>,
142): ReadonlyArray<OrchestrationV2Run> {
143 const candidates = usageLimitWakeCandidates(runs, turnItems);
144 if (candidates.length === 0) return candidates;
145 const firstInputs = new Map<string, { readonly type: string; readonly ordinal: number }>();
146 for (const item of turnItems) {
147 if (item.nodeId == null || item.ordinal == null) continue;
148 if (item.type !== "user_message" && item.type !== "notification") continue;
149 const first = firstInputs.get(item.nodeId);
150 if (first === undefined || item.ordinal < first.ordinal) {
151 firstInputs.set(item.nodeId, { type: item.type, ordinal: item.ordinal });
152 }
153 }
154 return candidates.filter(
155 (run) => run.rootNodeId !== null && firstInputs.get(run.rootNodeId)?.type === "notification",
156 );
157}
158
159/**
160 * Drops notification-started candidates that hold no work item, so they cannot replace the
161 * limited run. Callers must pass every item
162 * of notificationStartedWakeCandidates; other runs need only user_message, notification, error.
163 */
164function runsWithoutLimitedWakes(
165 runs: ReadonlyArray<OrchestrationV2Run>,
166 turnItems: ReadonlyArray<FailureScanTurnItem>,
167): ReadonlyArray<OrchestrationV2Run> {
168 const started = notificationStartedWakeCandidates(runs, turnItems);
169 if (started.length === 0) return runs;
170 const worked = new Set<string>();
171 for (const item of turnItems) {
172 if (item.runId != null && !NO_WORK_ITEM_TYPES.has(item.type)) worked.add(item.runId);
173 }
174 const wakes = new Set(started.filter((run) => !worked.has(run.id)));
175 return wakes.size === 0 ? runs : runs.filter((run) => !wakes.has(run));
176}
177
178/** The latest executed run, not counting notification wakes that did no work before a reset. */
179export function latestRunIgnoringLimitedWakes(
180 runs: ReadonlyArray<OrchestrationV2Run>,
181 turnItems: ReadonlyArray<FailureScanTurnItem>,
182): OrchestrationV2Run | null {
183 return latestExecutedRun(runsWithoutLimitedWakes(runs, turnItems));
184}
185
186export function usageLimitBlockedRun(
187 runs: ReadonlyArray<OrchestrationV2Run>,
188 turnItems: ReadonlyArray<FailureScanTurnItem>,
189 sessionError: string | null,
190): OrchestrationV2Run | null {
191 const executed = latestRunIgnoringLimitedWakes(runs, turnItems);
192 if (executed?.status !== "failed") return null;
193 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
194 return summary.lastErrorClass === "usage_limit" ? executed : null;
195}
196
197/** Retains a limited run's outcome when higher-ordinal runs never started. */
198export function usageLimitRunPresentedAsLatest(
199 runs: ReadonlyArray<OrchestrationV2Run>,
200 turnItems: ReadonlyArray<FailureScanTurnItem>,
201 sessionError: string | null,
202): OrchestrationV2Run | null {
203 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
204 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
205}
206
207export function latestUnheldRun(
208 runs: ReadonlyArray<OrchestrationV2Run>,
209): OrchestrationV2Run | null {
210 let latest: OrchestrationV2Run | null = null;
211 for (const run of runs) {
212 if (run.status === "queued" && run.queueHeld === true) continue;
213 if (outlivedBeforeStart(run, runs)) continue;
214 if (latest === null || run.ordinal > latest.ordinal) latest = run;
215 }
216 return latest;
217}
218
219// Steering a queued message cancels its run before it starts and hands the message to the
220// earlier run, which outlives the cancellation; that earlier run then presents as latest.
221function outlivedBeforeStart(
222 run: OrchestrationV2Run,
223 runs: ReadonlyArray<OrchestrationV2Run>,
224): boolean {
225 if (run.status !== "cancelled" || run.startedAt !== null || !run.completedAt) return false;
226 const cancelledAt = DateTime.toEpochMillis(run.completedAt);
227 return runs.some(
228 (earlier) =>
229 earlier.ordinal < run.ordinal &&
230 earlier.status !== "queued" &&
231 (!earlier.completedAt || DateTime.toEpochMillis(earlier.completedAt) >= cancelledAt),
232 );
233}