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/** Only error items are read, so callers may pass items stripped of other fields. */
10type FailureScanTurnItem =
11 | ErrorTurnItem
12 | { readonly type: Exclude<OrchestrationV2TurnItem["type"], "error"> };
13
14export function latestRootProviderFailure(
15 run: OrchestrationV2Run | null,
16 turnItems: ReadonlyArray<FailureScanTurnItem>,
17): OrchestrationV2ProviderFailure | null {
18 return latestRootProviderFailureItem(run, turnItems)?.failure ?? null;
19}
20
21export function latestRootProviderFailureItem(
22 run: OrchestrationV2Run | null,
23 turnItems: ReadonlyArray<FailureScanTurnItem>,
24): ErrorTurnItem | null {
25 if (run?.status !== "failed") return null;
26 let latest: ErrorTurnItem | null = null;
27 for (const item of turnItems) {
28 if (
29 item.type !== "error" ||
30 item.status !== "failed" ||
31 item.runId !== run.id ||
32 item.nodeId !== run.rootNodeId
33 )
34 continue;
35 if (
36 latest === null ||
37 DateTime.toEpochMillis(item.updatedAt) > DateTime.toEpochMillis(latest.updatedAt) ||
38 (DateTime.toEpochMillis(item.updatedAt) === DateTime.toEpochMillis(latest.updatedAt) &&
39 (item.ordinal > latest.ordinal || (item.ordinal === latest.ordinal && item.id > latest.id)))
40 ) {
41 latest = item;
42 }
43 }
44 return latest;
45}
46
47export function threadErrorSummary(
48 failure: OrchestrationV2ProviderFailure | null,
49 sessionError: string | null,
50) {
51 const currentFailure =
52 sessionError !== null && sessionError !== failure?.message ? null : failure;
53 return {
54 usageLimitResetAt:
55 currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,
56 lastError: sessionError ?? failure?.message ?? null,
57 lastErrorClass: currentFailure?.class ?? null,
58 lastErrorCode: currentFailure?.code ?? null,
59 };
60}
61
62export function latestExecutedRun(
63 runs: ReadonlyArray<OrchestrationV2Run>,
64): OrchestrationV2Run | null {
65 let latest: OrchestrationV2Run | null = null;
66 for (const run of runs) {
67 if (run.status === "queued") continue;
68 if (run.status === "cancelled" && run.startedAt === null) continue;
69 if (latest === null || runRanAfter(run, latest)) latest = run;
70 }
71 return latest;
72}
73
74/**
75 * Work started now would run in the project checkout, not the worktree the thread asked for. A
76 * failed or interrupted setup leaves the request standing until a worktree exists or later work
77 * has run past it.
78 */
79export function orchestrationV2WorktreePending(
80 worktreePath: string | null,
81 runs: ReadonlyArray<OrchestrationV2Run>,
82): boolean {
83 const latest = latestExecutedRun(runs);
84 return (
85 worktreePath === null &&
86 (latest?.status === "preparing" ||
87 latest?.status === "failed" ||
88 latest?.status === "interrupted") &&
89 latest.workspacePreparation?.type === "worktree"
90 );
91}
92
93/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
94export function runRanAfter(
95 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
96 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
97): boolean {
98 const end = (candidate: typeof run) =>
99 !candidate.completedAt
100 ? Number.POSITIVE_INFINITY
101 : DateTime.toEpochMillis(candidate.completedAt);
102 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
103}
104
105export function usageLimitBlockedRun(
106 runs: ReadonlyArray<OrchestrationV2Run>,
107 turnItems: ReadonlyArray<FailureScanTurnItem>,
108 sessionError: string | null,
109): OrchestrationV2Run | null {
110 const executed = latestExecutedRun(runs);
111 if (executed?.status !== "failed") return null;
112 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
113 return summary.lastErrorClass === "usage_limit" ? executed : null;
114}
115
116/** Retains a limited run's outcome when higher-ordinal runs never started. */
117export function usageLimitRunPresentedAsLatest(
118 runs: ReadonlyArray<OrchestrationV2Run>,
119 turnItems: ReadonlyArray<FailureScanTurnItem>,
120 sessionError: string | null,
121): OrchestrationV2Run | null {
122 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
123 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
124}
125
126export function latestUnheldRun(
127 runs: ReadonlyArray<OrchestrationV2Run>,
128): OrchestrationV2Run | null {
129 let latest: OrchestrationV2Run | null = null;
130 for (const run of runs) {
131 if (run.status === "queued" && run.queueHeld === true) continue;
132 if (outlivedBeforeStart(run, runs)) continue;
133 if (latest === null || run.ordinal > latest.ordinal) latest = run;
134 }
135 return latest;
136}
137
138// Steering a queued message cancels its run before it starts and hands the message to the
139// earlier run, which outlives the cancellation; that earlier run then presents as latest.
140function outlivedBeforeStart(
141 run: OrchestrationV2Run,
142 runs: ReadonlyArray<OrchestrationV2Run>,
143): boolean {
144 if (run.status !== "cancelled" || run.startedAt !== null || !run.completedAt) return false;
145 const cancelledAt = DateTime.toEpochMillis(run.completedAt);
146 return runs.some(
147 (earlier) =>
148 earlier.ordinal < run.ordinal &&
149 earlier.status !== "queued" &&
150 (!earlier.completedAt || DateTime.toEpochMillis(earlier.completedAt) >= cancelledAt),
151 );
152}