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

orchestrationV2ManualContinuation.ts

41 lines1.7 KB

1import {
2 isDeliveredProviderTurn,
3 type OrchestrationV2Run,
4 type OrchestrationV2ThreadProjection,
5} from "@t3tools/contracts";
6​
7export function unsentManualContinuationSource(
8 run: Pick<OrchestrationV2Run, "manualContinuationOfRunId"> | undefined,
9 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">,
10) {
11 let sourceId = run?.manualContinuationOfRunId;
12 if (sourceId === undefined) return undefined;
13 const runs = new Map(projection.runs.map((source) => [source.id, source]));
14 const acceptedAttempts = new Set(
15 projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId),
16 );
17 const latestAttempt = (
18 runId: OrchestrationV2Run["id"],
19 matches: (attempt: (typeof projection.attempts)[number]) => boolean,
20 ) =>
21 Math.max(
22 0,
23 ...projection.attempts
24 .filter((attempt) => attempt.runId === runId && matches(attempt))
25 .map((attempt) => attempt.attemptOrdinal),
26 );
27 const visited = new Set<OrchestrationV2Run["id"]>();
28 while (sourceId !== undefined && !visited.has(sourceId)) {
29 visited.add(sourceId);
30 const source = runs.get(sourceId);
31 if (source === undefined) return undefined;
32 const accepted = latestAttempt(sourceId, (attempt) => acceptedAttempts.has(attempt.id));
33 // An accepted attempt delivered everything before it; only a later steering restart's message is unsent.
34 const restarted = latestAttempt(sourceId, (attempt) => attempt.reason === "steering_restart");
35 if (restarted > accepted) return source;
36 if (accepted > 0) return undefined;
37 if (source.manualContinuationOfRunId === undefined) return source;
38 sourceId = source.manualContinuationOfRunId;
39 }
40 return undefined;