Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

orchestrationV2ThreadError.ts

153 lines5.4 KB

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;
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;
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 };
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;
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.startedAt === null &&
90 latest.workspacePreparation?.type === "worktree"
91 );
93​
94/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
95export function runRanAfter(
96 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
97 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
98): boolean {
99 const end = (candidate: typeof run) =>
100 !candidate.completedAt
101 ? Number.POSITIVE_INFINITY
102 : DateTime.toEpochMillis(candidate.completedAt);
103 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
105​
106export function usageLimitBlockedRun(
107 runs: ReadonlyArray<OrchestrationV2Run>,
108 turnItems: ReadonlyArray<FailureScanTurnItem>,
109 sessionError: string | null,
110): OrchestrationV2Run | null {
111 const executed = latestExecutedRun(runs);
112 if (executed?.status !== "failed") return null;
113 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
114 return summary.lastErrorClass === "usage_limit" ? executed : null;
116​
117/** Retains a limited run's outcome when higher-ordinal runs never started. */
118export function usageLimitRunPresentedAsLatest(
119 runs: ReadonlyArray<OrchestrationV2Run>,
120 turnItems: ReadonlyArray<FailureScanTurnItem>,
121 sessionError: string | null,
122): OrchestrationV2Run | null {
123 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
124 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
126​
127export function latestUnheldRun(
128 runs: ReadonlyArray<OrchestrationV2Run>,
129): OrchestrationV2Run | null {
130 let latest: OrchestrationV2Run | null = null;
131 for (const run of runs) {
132 if (run.status === "queued" && run.queueHeld === true) continue;
133 if (outlivedBeforeStart(run, runs)) continue;
134 if (latest === null || run.ordinal > latest.ordinal) latest = run;
135 }
136 return latest;
138​
139// Steering a queued message cancels its run before it starts and hands the message to the
140// earlier run, which outlives the cancellation; that earlier run then presents as latest.
141function outlivedBeforeStart(
142 run: OrchestrationV2Run,
143 runs: ReadonlyArray<OrchestrationV2Run>,
144): boolean {
145 if (run.status !== "cancelled" || run.startedAt !== null || !run.completedAt) return false;
146 const cancelledAt = DateTime.toEpochMillis(run.completedAt);
147 return runs.some(
148 (earlier) =>
149 earlier.ordinal < run.ordinal &&
150 earlier.status !== "queued" &&
151 (!earlier.completedAt || DateTime.toEpochMillis(earlier.completedAt) >= cancelledAt),
152 );