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

models.ts

313 lines12.1 KB

1import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
2import type {
3 ThreadLinkedPullRequest,
4 EnvironmentId,
5 MessageId,
6 OrchestrationProjectShell,
7 OrchestrationV2RunStatus,
8 OrchestrationV2ProviderFailureClass,
9 OrchestrationV2ThreadProjection,
10 OrchestrationV2ThreadShell,
11 PlanId,
12 ProjectId,
13 ProviderInstanceId,
14 RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18​
19import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
20​
21export interface EnvironmentProject extends OrchestrationProjectShell {
22 readonly environmentId: EnvironmentId;
24​
25/**
26 * A pristine V2 thread projection paired with the environment that produced it.
27 *
28 * The projection stays nested so the server projection and all structurally
29 * shared collections retain their identities. Rich consumers read V2 state
30 * directly instead of a second presentation-shaped thread graph.
31 */
32export interface EnvironmentThread {
33 readonly environmentId: EnvironmentId;
34 readonly projection: OrchestrationV2ThreadProjection;
36​
37export interface ThreadRunSummary {
38 readonly runId: RunId;
39 readonly status: OrchestrationV2RunStatus;
40 readonly requestedAt: string | null;
41 readonly startedAt: string | null;
42 readonly completedAt: string | null;
43 readonly assistantMessageId: MessageId | null;
44 readonly sourcePlanRef?: {
45 readonly threadId: ThreadId;
46 readonly planId: PlanId;
47 };
49​
50export interface ThreadRuntimeSummary {
51 readonly status: OrchestrationV2RunStatus | "idle";
52 readonly activeRunId: RunId | null;
53 readonly activityStartedAt?: string | null | undefined;
54 readonly providerInstanceId: ProviderInstanceId;
55 readonly providerName: string | null;
56 readonly lastError: string | null;
57 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
58 readonly usageLimitResetAt?: string | null;
59 readonly updatedAt: string;
61​
62export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
63 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
65​
66/** Archiving may discard queued work, but it must not detach a provider that
67 * is preparing, starting, or running a turn. */
68export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
69 if (runtime?.status === "queued") return runtime.activeRunId === null;
70 return (
71 runtime?.status !== "preparing" &&
72 runtime?.status !== "starting" &&
73 runtime?.status !== "running"
74 );
76​
77function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
78 return (
79 status === "preparing" ||
80 status === "queued" ||
81 status === "starting" ||
82 status === "running" ||
83 status === "waiting"
84 );
86​
87export interface EnvironmentThreadShell {
88 readonly environmentId: EnvironmentId;
89 readonly id: ThreadId;
90 readonly projectId: ProjectId;
91 readonly title: string;
92 readonly providerInstanceId: ProviderInstanceId;
93 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
94 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
95 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
96 readonly branch: string | null;
97 readonly worktreePath: string | null;
98 readonly lineage: OrchestrationV2ThreadShell["lineage"];
99 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
100 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
101 readonly latestRun: ThreadRunSummary | null;
102 readonly runtime: ThreadRuntimeSummary | null;
103 readonly latestUserMessageAt: string | null;
104 readonly hasPendingApprovals: boolean;
105 readonly hasPendingUserInput: boolean;
106 readonly hasActionableProposedPlan: boolean;
107 readonly pendingBackgroundTasks: ReadonlyArray<
108 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
109 >;
110 /** Provider instances that have owned the root conversation, oldest first. */
111 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
112 readonly itemCount: number;
113 readonly visibleItemCount: number;
114 readonly createdAt: string;
115 readonly updatedAt: string;
116 readonly archivedAt: string | null;
117 readonly settledOverride: "settled" | "active" | null;
118 readonly settledAt: string | null;
119 readonly unsettledAt: string | null;
120 readonly snoozedUntil: string | null;
121 readonly snoozedAt: string | null;
122 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
123 readonly pinnedAt: string | null;
124 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
125 readonly pinOrderKey: string | null;
126 /** Slot in the user-arranged active order; null for keyless active threads. */
127 readonly activeOrderKey: string | null;
128 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
129 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
130 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
131 /**
132 * Server-tracked visited watermark. `undefined` means the environment's
133 * server predates visited tracking and clients should fall back to any
134 * local visited state they keep.
135 */
136 readonly lastVisitedAt?: string | null;
137 /** Pending title regeneration marker; null when no request is in flight. */
138 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
139 readonly deletedAt: string | null;
140 readonly source: OrchestrationV2ThreadShell;
142​
143function iso(value: DateTime.Utc): string {
144 return DateTime.formatIso(value);
146​
147function nullableIso(value: DateTime.Utc | null): string | null {
148 return value === null ? null : iso(value);
150​
151function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
152 return (
153 status === "completed" ||
154 status === "interrupted" ||
155 status === "failed" ||
156 status === "cancelled" ||
157 status === "rolled_back"
158 );
160​
161// Park runtime at idle when the post-settlement background roster is nonempty
162// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
163// The server suppresses the roster while an interruptible activity run exists,
164// so a remaining roster is stronger than checkpoint-oriented waiting.
165// latestRun keeps the latest run's status for history presentation.
166function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
167 if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
168 const hasPendingBackgroundTasks = (thread.pendingBackgroundTasks?.length ?? 0) > 0;
169 const status = hasPendingBackgroundTasks ? "idle" : (thread.activityRunStatus ?? thread.status);
170 return {
171 status,
172 activeRunId: thread.activeRunId,
173 activityStartedAt:
174 thread.activityRunStartedAt === undefined
175 ? undefined
176 : nullableIso(thread.activityRunStartedAt),
177 providerInstanceId: thread.providerInstanceId,
178 providerName: null,
179 lastError: thread.lastError ?? null,
180 lastErrorClass: thread.lastErrorClass ?? null,
181 usageLimitResetAt: thread.usageLimitResetAt ?? null,
182 updatedAt: iso(thread.updatedAt),
183 };
185​
186export function scopeProject(
187 environmentId: EnvironmentId,
188 project: OrchestrationProjectShell,
189): EnvironmentProject {
190 return { ...project, environmentId };
192​
193export function presentThreadShell(
194 environmentId: EnvironmentId,
195 thread: OrchestrationV2ThreadShell,
196): EnvironmentThreadShell {
197 const updatedAt = iso(thread.updatedAt);
198 const latestRun =
199 thread.latestRunId === null
200 ? null
201 : ({
202 runId: thread.latestRunId,
203 status: thread.status === "idle" ? "completed" : thread.status,
204 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
205 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
206 completedAt:
207 thread.latestRunCompletedAt === undefined
208 ? thread.status === "idle" || terminalRunStatus(thread.status)
209 ? updatedAt
210 : null
211 : nullableIso(thread.latestRunCompletedAt),
212 assistantMessageId: null,
213 } satisfies ThreadRunSummary);
214 return {
215 environmentId,
216 id: thread.id,
217 projectId: thread.projectId,
218 title:
219 thread.lineage.relationshipToParent === "subagent"
220 ? formatSubagentDisplayTitle(thread.title)
221 : thread.title,
222 providerInstanceId: thread.providerInstanceId,
223 modelSelection: thread.modelSelection,
224 runtimeMode: thread.runtimeMode,
225 interactionMode: thread.interactionMode,
226 branch: thread.branch,
227 worktreePath: thread.worktreePath,
228 pullRequests: threadPullRequestsOf(thread),
229 linkedPullRequest: thread.linkedPullRequest ?? null,
230 branchPullRequest: thread.branchPullRequest ?? null,
231 lineage: thread.lineage,
232 forkedFrom: thread.forkedFrom,
233 activeProviderThreadId: thread.activeProviderThreadId,
234 latestRun,
235 runtime: shellRuntime(thread),
236 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
237 hasPendingApprovals:
238 thread.pendingRuntimeRequest !== null &&
239 thread.pendingRuntimeRequest.kind !== "user_input" &&
240 thread.pendingRuntimeRequest.kind !== "auth_refresh",
241 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
242 hasActionableProposedPlan: thread.hasActionableProposedPlan,
243 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
244 providerInstanceHistory: thread.providerInstanceHistory ?? [],
245 itemCount: thread.itemCount,
246 visibleItemCount: thread.visibleItemCount,
247 createdAt: iso(thread.createdAt),
248 updatedAt,
249 archivedAt: nullableIso(thread.archivedAt),
250 settledOverride: thread.settledOverride,
251 settledAt: nullableIso(thread.settledAt),
252 unsettledAt: nullableIso(thread.unsettledAt ?? null),
253 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
254 snoozedAt: nullableIso(thread.snoozedAt ?? null),
255 limitRecovery: thread.limitRecovery ?? null,
256 pinnedAt: nullableIso(thread.pinnedAt ?? null),
257 pinOrderKey: thread.pinOrderKey ?? null,
258 activeOrderKey: thread.activeOrderKey ?? null,
259 ...(thread.lastVisitedAt === undefined
260 ? {}
261 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
262 titleRegeneration:
263 thread.titleRegeneration == null
264 ? null
265 : {
266 requestId: thread.titleRegeneration.requestId,
267 startedAt: iso(thread.titleRegeneration.startedAt),
268 },
269 deletedAt: nullableIso(thread.deletedAt),
270 source: thread,
271 };
273​
274export function scopeThreadShell(
275 environmentId: EnvironmentId,
276 thread: OrchestrationV2ThreadShell,
277): EnvironmentThreadShell {
278 return presentThreadShell(environmentId, thread);
280​
281const THREAD_PROVIDER_STACK_LIMIT = 3;
282​
283/**
284 * Provider instances to draw in a thread row's trailing stack, back to front:
285 * the current one is always last, earlier owners precede it oldest first.
286 * Newest history wins when the thread has been handed off more times than fit.
287 */
288export function resolveThreadProviderStack(
289 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
290): ReadonlyArray<ProviderInstanceId> {
291 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
292 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
293 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
295​
296/** Both shell and detail timers use the activity-owning run, never last activity. */
297export function resolveThreadWorkingStartedAt(input: {
298 readonly latestRun: Pick<
299 ThreadRunSummary,
300 "runId" | "startedAt" | "requestedAt" | "completedAt"
301 > | null;
302 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
303}): string | null {
304 const valid = (value: string | null | undefined) =>
305 value != null && Number.isFinite(Date.parse(value)) ? value : null;
306 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
307 // Older servers can supply a timestamp only if the newest run owns the work.
308 const run = input.latestRun;
309 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
310 return valid(run.startedAt) ?? valid(run.requestedAt);
311 }
312 return null;