Open History to see the last commit
1import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import * as DateTime from "effect/DateTime";
4
5import {
6 threadRuntimeIsActive,
7 type ThreadRunSummary,
8 type ThreadRuntimeSummary,
9} from "./models.ts";
10
11const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
12const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
13
14function latestMatchingRun(
15 projection: OrchestrationV2ThreadProjection,
16 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
17): OrchestrationV2ThreadProjection["runs"][number] | null {
18 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
19 (latest, candidate) =>
20 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
21 ? candidate
22 : latest,
23 null,
24 );
25}
26
27function summarizeThreadRun(
28 projection: OrchestrationV2ThreadProjection,
29 run: OrchestrationV2ThreadProjection["runs"][number],
30): ThreadRunSummary {
31 return {
32 runId: run.id,
33 status: run.status,
34 requestedAt: DateTime.formatIso(run.requestedAt),
35 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
36 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
37 assistantMessageId:
38 projection.messages.findLast(
39 (message) => message.runId === run.id && message.role === "assistant",
40 )?.id ?? null,
41 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
42 };
43}
44
45export function deriveLatestThreadRun(
46 projection: OrchestrationV2ThreadProjection,
47): ThreadRunSummary | null {
48 const run = latestMatchingRun(projection, () => true);
49 return run === null ? null : summarizeThreadRun(projection, run);
50}
51
52/**
53 * Returns the run that owns live provider work, falling back to the newest run
54 * once the thread is idle. A newer queued run must not make an older executing
55 * run look settled in clients that render per-run activity.
56 */
57export function deriveThreadActivityRun(
58 projection: OrchestrationV2ThreadProjection,
59): ThreadRunSummary | null {
60 const run =
61 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
62 latestMatchingRun(projection, () => true);
63 return run === null ? null : summarizeThreadRun(projection, run);
64}
65
66export function deriveThreadRuntime(
67 projection: OrchestrationV2ThreadProjection,
68): ThreadRuntimeSummary | null {
69 const latestRun = deriveLatestThreadRun(projection);
70 const latestRunProjection = latestMatchingRun(projection, () => true);
71 const activityRun = deriveThreadActivityRun(projection);
72 const providerSession = projection.providerSessions.findLast(
73 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
74 );
75 if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
76 const activeRunId =
77 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
78 const hasPendingBackgroundTasks =
79 derivePendingBackgroundWork({
80 latestRun: latestRunProjection,
81 providerThreads: projection.providerThreads,
82 turnItems: projection.turnItems,
83 activeProviderThreadId: projection.thread.activeProviderThreadId,
84 runs: projection.runs,
85 }).length > 0;
86 return {
87 status: hasPendingBackgroundTasks ? "idle" : (activityRun?.status ?? "idle"),
88 activeRunId,
89 providerInstanceId: projection.thread.providerInstanceId,
90 providerName: providerSession?.driver ?? null,
91 lastError: providerSession?.lastError ?? null,
92 updatedAt: DateTime.formatIso(projection.updatedAt),
93 };
94}
95
96export function threadRuntimeHasInterruptibleRun(
97 runtime: ThreadRuntimeSummary | null | undefined,
98): boolean {
99 return (
100 threadRuntimeIsActive(runtime) &&
101 runtime?.activeRunId !== null &&
102 runtime?.activeRunId !== undefined
103 );
104}