Open History to see the last commit
1import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3
4import type { ThreadRunSummary, ThreadRuntimeSummary } from "./models.ts";
5
6const ACTIVE_RUN_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
7
8export function deriveLatestThreadRun(
9 projection: OrchestrationV2ThreadProjection,
10): ThreadRunSummary | null {
11 const run = projection.runs.reduce<(typeof projection.runs)[number] | null>(
12 (latest, candidate) =>
13 latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,
14 null,
15 );
16 if (run === null) return null;
17 return {
18 runId: run.id,
19 status: run.status,
20 requestedAt: DateTime.formatIso(run.requestedAt),
21 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
22 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
23 assistantMessageId:
24 projection.messages.findLast(
25 (message) => message.runId === run.id && message.role === "assistant",
26 )?.id ?? null,
27 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
28 };
29}
30
31export function deriveThreadRuntime(
32 projection: OrchestrationV2ThreadProjection,
33): ThreadRuntimeSummary | null {
34 const latestRun = deriveLatestThreadRun(projection);
35 const providerSession = projection.providerSessions.findLast(
36 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
37 );
38 if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
39 const activeRunId =
40 projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status))?.id ?? null;
41 return {
42 status: latestRun?.status ?? "idle",
43 activeRunId,
44 providerInstanceId: projection.thread.providerInstanceId,
45 providerName: providerSession?.driver ?? null,
46 lastError: providerSession?.lastError ?? null,
47 updatedAt: DateTime.formatIso(projection.updatedAt),
48 };
49}