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

models.ts

335 lines12.6 KB

1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
3import type {
4 ThreadLinkedPullRequest,
5 EnvironmentId,
6 MessageId,
7 OrchestrationProjectShell,
8 OrchestrationV2ProviderGoal,
9 OrchestrationV2RunStatus,
10 OrchestrationV2ProviderFailureClass,
11 OrchestrationV2ThreadProjection,
12 OrchestrationV2ThreadShell,
13 PlanId,
14 ProjectId,
15 ProviderInstanceId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20​
21import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
22​
23export interface EnvironmentProject extends OrchestrationProjectShell {
24 readonly environmentId: EnvironmentId;
25 readonly isScratch?: true;
27​
28/**
29 * The projection stays nested so the server projection and all structurally
30 * shared collections retain their identities.
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 /**
45 * The run is still open, but its provider turn already ended, so nothing is
46 * generating while the server settles it.
47 */
48 readonly turnEnded?: boolean;
49 readonly sourcePlanRef?: {
50 readonly threadId: ThreadId;
51 readonly planId: PlanId;
52 };
54​
55export interface ThreadRuntimeSummary {
56 readonly status: OrchestrationV2RunStatus | "idle";
57 readonly activeRunId: RunId | null;
58 readonly activityStartedAt?: string | null | undefined;
59 readonly providerInstanceId: ProviderInstanceId;
60 readonly providerName: string | null;
61 readonly lastError: string | null;
62 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
63 readonly usageLimitResetAt?: string | null;
64 readonly updatedAt: string;
66​
67export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
68 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
70​
71export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
72 if (runtime?.status === "queued") return runtime.activeRunId === null;
73 return (
74 runtime?.status !== "preparing" &&
75 runtime?.status !== "starting" &&
76 runtime?.status !== "running"
77 );
79​
80function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
81 return (
82 status === "preparing" ||
83 status === "queued" ||
84 status === "starting" ||
85 status === "running" ||
86 status === "waiting"
87 );
89​
90export interface EnvironmentThreadShell {
91 readonly environmentId: EnvironmentId;
92 readonly id: ThreadId;
93 readonly projectId: ProjectId;
94 readonly title: string;
95 readonly providerInstanceId: ProviderInstanceId;
96 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
97 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
98 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
99 readonly branch: string | null;
100 readonly worktreePath: string | null;
101 readonly lineage: OrchestrationV2ThreadShell["lineage"];
102 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
103 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
104 readonly latestRun: ThreadRunSummary | null;
105 readonly runtime: ThreadRuntimeSummary | null;
106 readonly blockedOnThreadWait?: boolean;
107 readonly latestUserMessageAt: string | null;
108 readonly latestUserAuthoredMessageAt?: string | null;
109 readonly hasPendingApprovals: boolean;
110 readonly hasPendingUserInput: boolean;
111 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
112 readonly hasActionableProposedPlan: boolean;
113 readonly pendingBackgroundTasks: ReadonlyArray<
114 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
115 >;
116 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
117 readonly goal: OrchestrationV2ProviderGoal | null;
118 readonly itemCount: number;
119 readonly visibleItemCount: number;
120 readonly createdAt: string;
121 readonly updatedAt: string;
122 readonly archivedAt: string | null;
123 readonly settledOverride: "settled" | "active" | null;
124 readonly settledAt: string | null;
125 readonly unsettledAt: string | null;
126 readonly snoozedUntil: string | null;
127 readonly snoozedAt: string | null;
128 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
129 readonly pinnedAt: string | null;
130 readonly autoSettleDisabledAt?: string | null;
131 readonly pinOrderKey: string | null;
132 readonly activeOrderKey: string | null;
133 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
134 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
135 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
136 /**
137 * Server-tracked visited watermark. `undefined` means the environment's
138 * server predates visited tracking and clients should fall back to any
139 * local visited state they keep.
140 */
141 readonly lastVisitedAt?: string | null;
142 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
143 readonly deletedAt: string | null;
144 readonly source: OrchestrationV2ThreadShell;
146​
147function iso(value: DateTime.Utc): string {
148 return DateTime.formatIso(value);
150​
151function nullableIso(value: DateTime.Utc | null): string | null {
152 return value === null ? null : iso(value);
154​
155function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
156 return (
157 status === "completed" ||
158 status === "interrupted" ||
159 status === "failed" ||
160 status === "cancelled" ||
161 status === "rolled_back"
162 );
164​
165// Only work that wakes the agent holds it: commands it left running, such as a
166// dev server, present the run's own status (#14872). The server suppresses the
167// roster while an interruptible activity run exists, so a remaining roster is
168// stronger than checkpoint-oriented waiting.
169function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
170 const parkAtIdle =
171 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
172 thread.status !== "failed";
173 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
174 return null;
175 }
176 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
177 return {
178 status,
179 activeRunId: thread.activeRunId,
180 activityStartedAt:
181 thread.activityRunStartedAt === undefined
182 ? undefined
183 : nullableIso(thread.activityRunStartedAt),
184 providerInstanceId: thread.providerInstanceId,
185 providerName: null,
186 lastError: thread.lastError ?? null,
187 lastErrorClass: thread.lastErrorClass ?? null,
188 usageLimitResetAt: thread.usageLimitResetAt ?? null,
189 updatedAt: iso(thread.updatedAt),
190 };
192​
193export function scopeProject(
194 environmentId: EnvironmentId,
195 project: OrchestrationProjectShell,
196): EnvironmentProject {
197 return { ...project, environmentId };
199​
200export type PendingSubagentRequest = "approval" | "user_input";
201​
202export function presentThreadShell(
203 environmentId: EnvironmentId,
204 thread: OrchestrationV2ThreadShell,
205 pendingSubagentRequest: PendingSubagentRequest | null = null,
206): EnvironmentThreadShell {
207 const updatedAt = iso(thread.updatedAt);
208 const latestRun =
209 thread.latestRunId === null
210 ? null
211 : ({
212 runId: thread.latestRunId,
213 status: thread.status === "idle" ? "completed" : thread.status,
214 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
215 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
216 completedAt:
217 thread.latestRunCompletedAt === undefined
218 ? thread.status === "idle" || terminalRunStatus(thread.status)
219 ? updatedAt
220 : null
221 : nullableIso(thread.latestRunCompletedAt),
222 assistantMessageId: null,
223 } satisfies ThreadRunSummary);
224 const runtime = shellRuntime(thread);
225 // Waiting runs have ended their provider turn and are only draining effects.
226 const runtimeIsWorking =
227 runtime?.status === "preparing" ||
228 runtime?.status === "starting" ||
229 runtime?.status === "running";
230 return {
231 environmentId,
232 id: thread.id,
233 projectId: thread.projectId,
234 title:
235 thread.lineage.relationshipToParent === "subagent"
236 ? formatSubagentDisplayTitle(thread.title)
237 : thread.title,
238 providerInstanceId: thread.providerInstanceId,
239 modelSelection: thread.modelSelection,
240 runtimeMode: thread.runtimeMode,
241 interactionMode: thread.interactionMode,
242 branch: thread.branch,
243 worktreePath: thread.worktreePath,
244 pullRequests: threadPullRequestsOf(thread),
245 linkedPullRequest: thread.linkedPullRequest ?? null,
246 branchPullRequest: thread.branchPullRequest ?? null,
247 lineage: thread.lineage,
248 forkedFrom: thread.forkedFrom,
249 activeProviderThreadId: thread.activeProviderThreadId,
250 latestRun,
251 runtime,
252 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
253 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
254 ...(thread.latestUserAuthoredMessageAt === undefined
255 ? {}
256 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
257 hasPendingApprovals:
258 thread.pendingRuntimeRequest !== null &&
259 thread.pendingRuntimeRequest.kind !== "user_input" &&
260 thread.pendingRuntimeRequest.kind !== "auth_refresh",
261 hasPendingUserInput:
262 thread.pendingRuntimeRequest?.kind === "user_input" &&
263 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
264 pendingSubagentRequest,
265 hasActionableProposedPlan: thread.hasActionableProposedPlan,
266 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
267 providerInstanceHistory: thread.providerInstanceHistory ?? [],
268 goal: thread.goal ?? null,
269 itemCount: thread.itemCount,
270 visibleItemCount: thread.visibleItemCount,
271 createdAt: iso(thread.createdAt),
272 updatedAt,
273 archivedAt: nullableIso(thread.archivedAt),
274 settledOverride: thread.settledOverride,
275 settledAt: nullableIso(thread.settledAt),
276 unsettledAt: nullableIso(thread.unsettledAt ?? null),
277 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
278 snoozedAt: nullableIso(thread.snoozedAt ?? null),
279 limitRecovery: thread.limitRecovery ?? null,
280 pinnedAt: nullableIso(thread.pinnedAt ?? null),
281 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
282 pinOrderKey: thread.pinOrderKey ?? null,
283 activeOrderKey: thread.activeOrderKey ?? null,
284 ...(thread.lastVisitedAt === undefined
285 ? {}
286 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
287 titleRegeneration:
288 thread.titleRegeneration == null
289 ? null
290 : {
291 requestId: thread.titleRegeneration.requestId,
292 startedAt: iso(thread.titleRegeneration.startedAt),
293 },
294 deletedAt: nullableIso(thread.deletedAt),
295 source: thread,
296 };
298​
299export function scopeThreadShell(
300 environmentId: EnvironmentId,
301 thread: OrchestrationV2ThreadShell,
302): EnvironmentThreadShell {
303 return presentThreadShell(environmentId, thread);
305​
306const THREAD_PROVIDER_STACK_LIMIT = 3;
307​
308export function resolveThreadProviderStack(
309 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
310): ReadonlyArray<ProviderInstanceId> {
311 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
312 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
313 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
315​
316/**
317 * Both shell and detail timers count from the activity-owning run's work
318 * start, never last activity. A wake keeps the start of the work it continues.
319 */
320export function resolveThreadWorkingStartedAt(input: {
321 readonly latestRun: Pick<
322 ThreadRunSummary,
323 "runId" | "startedAt" | "requestedAt" | "completedAt"
324 > | null;
325 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
326}): string | null {
327 const valid = (value: string | null | undefined) =>
328 value != null && Number.isFinite(Date.parse(value)) ? value : null;
329 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
330 const run = input.latestRun;
331 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
332 return valid(run.startedAt) ?? valid(run.requestedAt);
333 }
334 return null;