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

orchestrationV2ThreadError.ts

137 lines5.1 KB

1import type {
2 OrchestrationV2ProviderFailure,
3 OrchestrationV2Run,
4 OrchestrationV2TurnItem,
5} from "@t3tools/contracts";
6import * as DateTime from "effect/DateTime";
7​
8export function latestRootProviderFailure(
9 run: OrchestrationV2Run | null,
10 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
11): OrchestrationV2ProviderFailure | null {
12 if (run?.status !== "failed") return null;
13 let latest: Extract<OrchestrationV2TurnItem, { type: "error" }> | null = null;
14 for (const item of turnItems) {
15 if (
16 item.type !== "error" ||
17 item.status !== "failed" ||
18 item.runId !== run.id ||
19 item.nodeId !== run.rootNodeId
20 )
21 continue;
22 if (
23 latest === null ||
24 DateTime.toEpochMillis(item.updatedAt) > DateTime.toEpochMillis(latest.updatedAt) ||
25 (DateTime.toEpochMillis(item.updatedAt) === DateTime.toEpochMillis(latest.updatedAt) &&
26 (item.ordinal > latest.ordinal || (item.ordinal === latest.ordinal && item.id > latest.id)))
27 ) {
28 latest = item;
29 }
30 }
31 return latest?.failure ?? null;
33​
34export function threadErrorSummary(
35 failure: OrchestrationV2ProviderFailure | null,
36 sessionError: string | null,
37) {
38 const currentFailure =
39 sessionError !== null && sessionError !== failure?.message ? null : failure;
40 return {
41 usageLimitResetAt:
42 currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,
43 lastError: sessionError ?? failure?.message ?? null,
44 lastErrorClass:
45 sessionError !== null && sessionError !== failure?.message ? null : (failure?.class ?? null),
46 };
48​
49export function latestExecutedRun(
50 runs: ReadonlyArray<OrchestrationV2Run>,
51): OrchestrationV2Run | null {
52 let latest: OrchestrationV2Run | null = null;
53 for (const run of runs) {
54 if (run.status === "queued") continue;
55 if (run.status === "cancelled" && run.startedAt === null) continue;
56 if (latest === null || runRanAfter(run, latest)) latest = run;
57 }
58 return latest;
60​
61/**
62 * Ordinals follow submission, but a run can start ahead of a held queue (a
63 * restart continuation, or a message sent while the queue is held), so a queued
64 * run resumed later can have a lower ordinal than one that already ended. An
65 * unfinished run is the latest.
66 */
67export function runRanAfter(
68 run: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
69 other: Pick<OrchestrationV2Run, "ordinal" | "completedAt">,
70): boolean {
71 const end = (candidate: typeof run) =>
72 !candidate.completedAt
73 ? Number.POSITIVE_INFINITY
74 : DateTime.toEpochMillis(candidate.completedAt);
75 return end(run) === end(other) ? run.ordinal > other.ordinal : end(run) > end(other);
77​
78export function usageLimitBlockedRun(
79 runs: ReadonlyArray<OrchestrationV2Run>,
80 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
81 sessionError: string | null,
82): OrchestrationV2Run | null {
83 const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));
84 const failure = latestRootProviderFailure(failed, turnItems);
85 if (failure?.class !== "usage_limit") return null;
86 const resetAt = failure.resetAt == null ? NaN : Date.parse(failure.resetAt);
87 // Before reset, a completed notification wake cannot supersede the limited work.
88 // After reset, success is authoritative even when the input was a notification.
89 const firstInputs = new Map<
90 NonNullable<OrchestrationV2TurnItem["nodeId"]>,
91 Extract<OrchestrationV2TurnItem, { type: "user_message" | "notification" }>
92 >();
93 for (const item of turnItems) {
94 if (item.nodeId === null || (item.type !== "user_message" && item.type !== "notification"))
95 continue;
96 const first = firstInputs.get(item.nodeId);
97 if (first === undefined || item.ordinal < first.ordinal) firstInputs.set(item.nodeId, item);
98 }
99 const executed = latestExecutedRun(
100 runs.filter(
101 (run) =>
102 run.status !== "completed" ||
103 run.completedAt === null ||
104 !(DateTime.toEpochMillis(run.completedAt) <= resetAt) ||
105 run.rootNodeId === null ||
106 firstInputs.get(run.rootNodeId)?.type !== "notification",
107 ),
108 );
109 if (executed?.status !== "failed") return null;
110 const summary = threadErrorSummary(latestRootProviderFailure(executed, turnItems), sessionError);
111 return summary.lastErrorClass === "usage_limit" ? executed : null;
113​
114/**
115 * That limited run, when newer runs were queued or cancelled before starting.
116 * Callers that treat the highest-ordinal run as the thread outcome would
117 * otherwise hide the limit.
118 */
119export function usageLimitRunPresentedAsLatest(
120 runs: ReadonlyArray<OrchestrationV2Run>,
121 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
122 sessionError: string | null,
123): OrchestrationV2Run | null {
124 const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);
125 return blocked !== null && runs.some((run) => run.ordinal > blocked.ordinal) ? blocked : null;
127​
128export function latestUnheldRun(
129 runs: ReadonlyArray<OrchestrationV2Run>,
130): OrchestrationV2Run | null {
131 let latest: OrchestrationV2Run | null = null;
132 for (const run of runs) {
133 if (run.status === "queued" && run.queueHeld === true) continue;
134 if (latest === null || run.ordinal > latest.ordinal) latest = run;
135 }
136 return latest;