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

models.ts

319 lines12.4 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 readonly autoSettleDisabledAt?: string | null;
125 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
126 readonly pinOrderKey: string | null;
127 /** Slot in the user-arranged active order; null for keyless active threads. */
128 readonly activeOrderKey: string | null;
129 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
130 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
131 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
132 /**
133 * Server-tracked visited watermark. `undefined` means the environment's
134 * server predates visited tracking and clients should fall back to any
135 * local visited state they keep.
136 */
137 readonly lastVisitedAt?: string | null;
138 /** Pending title regeneration marker; null when no request is in flight. */
139 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
140 readonly deletedAt: string | null;
141 readonly source: OrchestrationV2ThreadShell;
143​
144function iso(value: DateTime.Utc): string {
145 return DateTime.formatIso(value);
147​
148function nullableIso(value: DateTime.Utc | null): string | null {
149 return value === null ? null : iso(value);
151​
152function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
153 return (
154 status === "completed" ||
155 status === "interrupted" ||
156 status === "failed" ||
157 status === "cancelled" ||
158 status === "rolled_back"
159 );
161​
162// Park runtime at idle when the post-settlement background roster is nonempty
163// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
164// The server suppresses the roster while an interruptible activity run exists,
165// so a remaining roster is stronger than checkpoint-oriented waiting.
166// latestRun keeps the latest run's status for history presentation.
167// A failed latest run outranks the roster, so the failure stays visible.
168function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
169 if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
170 const parkAtIdle = (thread.pendingBackgroundTasks?.length ?? 0) > 0 && thread.status !== "failed";
171 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
172 return {
173 status,
174 activeRunId: thread.activeRunId,
175 activityStartedAt:
176 thread.activityRunStartedAt === undefined
177 ? undefined
178 : nullableIso(thread.activityRunStartedAt),
179 providerInstanceId: thread.providerInstanceId,
180 providerName: null,
181 lastError: thread.lastError ?? null,
182 lastErrorClass: thread.lastErrorClass ?? null,
183 usageLimitResetAt: thread.usageLimitResetAt ?? null,
184 updatedAt: iso(thread.updatedAt),
185 };
187​
188export function scopeProject(
189 environmentId: EnvironmentId,
190 project: OrchestrationProjectShell,
191): EnvironmentProject {
192 return { ...project, environmentId };
194​
195export function presentThreadShell(
196 environmentId: EnvironmentId,
197 thread: OrchestrationV2ThreadShell,
198): EnvironmentThreadShell {
199 const updatedAt = iso(thread.updatedAt);
200 const latestRun =
201 thread.latestRunId === null
202 ? null
203 : ({
204 runId: thread.latestRunId,
205 status: thread.status === "idle" ? "completed" : thread.status,
206 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
207 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
208 completedAt:
209 thread.latestRunCompletedAt === undefined
210 ? thread.status === "idle" || terminalRunStatus(thread.status)
211 ? updatedAt
212 : null
213 : nullableIso(thread.latestRunCompletedAt),
214 assistantMessageId: null,
215 } satisfies ThreadRunSummary);
216 return {
217 environmentId,
218 id: thread.id,
219 projectId: thread.projectId,
220 title:
221 thread.lineage.relationshipToParent === "subagent"
222 ? formatSubagentDisplayTitle(thread.title)
223 : thread.title,
224 providerInstanceId: thread.providerInstanceId,
225 modelSelection: thread.modelSelection,
226 runtimeMode: thread.runtimeMode,
227 interactionMode: thread.interactionMode,
228 branch: thread.branch,
229 worktreePath: thread.worktreePath,
230 pullRequests: threadPullRequestsOf(thread),
231 linkedPullRequest: thread.linkedPullRequest ?? null,
232 branchPullRequest: thread.branchPullRequest ?? null,
233 lineage: thread.lineage,
234 forkedFrom: thread.forkedFrom,
235 activeProviderThreadId: thread.activeProviderThreadId,
236 latestRun,
237 runtime: shellRuntime(thread),
238 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
239 hasPendingApprovals:
240 thread.pendingRuntimeRequest !== null &&
241 thread.pendingRuntimeRequest.kind !== "user_input" &&
242 thread.pendingRuntimeRequest.kind !== "auth_refresh",
243 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
244 hasActionableProposedPlan: thread.hasActionableProposedPlan,
245 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
246 providerInstanceHistory: thread.providerInstanceHistory ?? [],
247 itemCount: thread.itemCount,
248 visibleItemCount: thread.visibleItemCount,
249 createdAt: iso(thread.createdAt),
250 updatedAt,
251 archivedAt: nullableIso(thread.archivedAt),
252 settledOverride: thread.settledOverride,
253 settledAt: nullableIso(thread.settledAt),
254 unsettledAt: nullableIso(thread.unsettledAt ?? null),
255 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
256 snoozedAt: nullableIso(thread.snoozedAt ?? null),
257 limitRecovery: thread.limitRecovery ?? null,
258 pinnedAt: nullableIso(thread.pinnedAt ?? null),
259 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
260 pinOrderKey: thread.pinOrderKey ?? null,
261 activeOrderKey: thread.activeOrderKey ?? null,
262 ...(thread.lastVisitedAt === undefined
263 ? {}
264 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
265 titleRegeneration:
266 thread.titleRegeneration == null
267 ? null
268 : {
269 requestId: thread.titleRegeneration.requestId,
270 startedAt: iso(thread.titleRegeneration.startedAt),
271 },
272 deletedAt: nullableIso(thread.deletedAt),
273 source: thread,
274 };
276​
277export function scopeThreadShell(
278 environmentId: EnvironmentId,
279 thread: OrchestrationV2ThreadShell,
280): EnvironmentThreadShell {
281 return presentThreadShell(environmentId, thread);
283​
284const THREAD_PROVIDER_STACK_LIMIT = 3;
285​
286/**
287 * Provider instances to draw in a thread row's trailing stack, back to front:
288 * the current one is always last, earlier owners precede it oldest first.
289 * Newest history wins when the thread has been handed off more times than fit.
290 */
291export function resolveThreadProviderStack(
292 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
293): ReadonlyArray<ProviderInstanceId> {
294 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
295 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
296 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
298​
299/**
300 * Both shell and detail timers count from the activity-owning run's work
301 * start, never last activity. A wake keeps the start of the work it continues.
302 */
303export function resolveThreadWorkingStartedAt(input: {
304 readonly latestRun: Pick<
305 ThreadRunSummary,
306 "runId" | "startedAt" | "requestedAt" | "completedAt"
307 > | null;
308 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
309}): string | null {
310 const valid = (value: string | null | undefined) =>
311 value != null && Number.isFinite(Date.parse(value)) ? value : null;
312 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
313 // Older servers can supply a timestamp only if the newest run owns the work.
314 const run = input.latestRun;
315 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
316 return valid(run.startedAt) ?? valid(run.requestedAt);
317 }
318 return null;