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