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

models.ts

325 lines12.1 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 latestUserMessageAt: string | null;
107 readonly latestUserAuthoredMessageAt?: string | null;
108 readonly hasPendingApprovals: boolean;
109 readonly hasPendingUserInput: boolean;
110 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
111 readonly hasActionableProposedPlan: boolean;
112 readonly pendingBackgroundTasks: ReadonlyArray<
113 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
114 >;
115 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
116 readonly goal: OrchestrationV2ProviderGoal | null;
117 readonly itemCount: number;
118 readonly visibleItemCount: number;
119 readonly createdAt: string;
120 readonly updatedAt: string;
121 readonly archivedAt: string | null;
122 readonly settledOverride: "settled" | "active" | null;
123 readonly settledAt: string | null;
124 readonly unsettledAt: string | null;
125 readonly snoozedUntil: string | null;
126 readonly snoozedAt: string | null;
127 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
128 readonly pinnedAt: string | null;
129 readonly autoSettleDisabledAt?: string | null;
130 readonly pinOrderKey: string | null;
131 readonly activeOrderKey: string | null;
132 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
133 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
134 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
135 /**
136 * Server-tracked visited watermark. `undefined` means the environment's
137 * server predates visited tracking and clients should fall back to any
138 * local visited state they keep.
139 */
140 readonly lastVisitedAt?: string | null;
141 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
142 readonly deletedAt: string | null;
143 readonly source: OrchestrationV2ThreadShell;
145​
146function iso(value: DateTime.Utc): string {
147 return DateTime.formatIso(value);
149​
150function nullableIso(value: DateTime.Utc | null): string | null {
151 return value === null ? null : iso(value);
153​
154function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
155 return (
156 status === "completed" ||
157 status === "interrupted" ||
158 status === "failed" ||
159 status === "cancelled" ||
160 status === "rolled_back"
161 );
163​
164// Only work that wakes the agent holds it: commands it left running, such as a
165// dev server, present the run's own status (#14872). The server suppresses the
166// roster while an interruptible activity run exists, so a remaining roster is
167// stronger than checkpoint-oriented waiting.
168function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
169 const parkAtIdle =
170 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
171 thread.status !== "failed";
172 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
173 return null;
174 }
175 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
176 return {
177 status,
178 activeRunId: thread.activeRunId,
179 activityStartedAt:
180 thread.activityRunStartedAt === undefined
181 ? undefined
182 : nullableIso(thread.activityRunStartedAt),
183 providerInstanceId: thread.providerInstanceId,
184 providerName: null,
185 lastError: thread.lastError ?? null,
186 lastErrorClass: thread.lastErrorClass ?? null,
187 usageLimitResetAt: thread.usageLimitResetAt ?? null,
188 updatedAt: iso(thread.updatedAt),
189 };
191​
192export function scopeProject(
193 environmentId: EnvironmentId,
194 project: OrchestrationProjectShell,
195): EnvironmentProject {
196 return { ...project, environmentId };
198​
199export type PendingSubagentRequest = "approval" | "user_input";
200​
201export function presentThreadShell(
202 environmentId: EnvironmentId,
203 thread: OrchestrationV2ThreadShell,
204 pendingSubagentRequest: PendingSubagentRequest | null = null,
205): EnvironmentThreadShell {
206 const updatedAt = iso(thread.updatedAt);
207 const latestRun =
208 thread.latestRunId === null
209 ? null
210 : ({
211 runId: thread.latestRunId,
212 status: thread.status === "idle" ? "completed" : thread.status,
213 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
214 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
215 completedAt:
216 thread.latestRunCompletedAt === undefined
217 ? thread.status === "idle" || terminalRunStatus(thread.status)
218 ? updatedAt
219 : null
220 : nullableIso(thread.latestRunCompletedAt),
221 assistantMessageId: null,
222 } satisfies ThreadRunSummary);
223 return {
224 environmentId,
225 id: thread.id,
226 projectId: thread.projectId,
227 title:
228 thread.lineage.relationshipToParent === "subagent"
229 ? formatSubagentDisplayTitle(thread.title)
230 : thread.title,
231 providerInstanceId: thread.providerInstanceId,
232 modelSelection: thread.modelSelection,
233 runtimeMode: thread.runtimeMode,
234 interactionMode: thread.interactionMode,
235 branch: thread.branch,
236 worktreePath: thread.worktreePath,
237 pullRequests: threadPullRequestsOf(thread),
238 linkedPullRequest: thread.linkedPullRequest ?? null,
239 branchPullRequest: thread.branchPullRequest ?? null,
240 lineage: thread.lineage,
241 forkedFrom: thread.forkedFrom,
242 activeProviderThreadId: thread.activeProviderThreadId,
243 latestRun,
244 runtime: shellRuntime(thread),
245 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
246 ...(thread.latestUserAuthoredMessageAt === undefined
247 ? {}
248 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
249 hasPendingApprovals:
250 thread.pendingRuntimeRequest !== null &&
251 thread.pendingRuntimeRequest.kind !== "user_input" &&
252 thread.pendingRuntimeRequest.kind !== "auth_refresh",
253 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
254 pendingSubagentRequest,
255 hasActionableProposedPlan: thread.hasActionableProposedPlan,
256 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
257 providerInstanceHistory: thread.providerInstanceHistory ?? [],
258 goal: thread.goal ?? null,
259 itemCount: thread.itemCount,
260 visibleItemCount: thread.visibleItemCount,
261 createdAt: iso(thread.createdAt),
262 updatedAt,
263 archivedAt: nullableIso(thread.archivedAt),
264 settledOverride: thread.settledOverride,
265 settledAt: nullableIso(thread.settledAt),
266 unsettledAt: nullableIso(thread.unsettledAt ?? null),
267 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
268 snoozedAt: nullableIso(thread.snoozedAt ?? null),
269 limitRecovery: thread.limitRecovery ?? null,
270 pinnedAt: nullableIso(thread.pinnedAt ?? null),
271 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
272 pinOrderKey: thread.pinOrderKey ?? null,
273 activeOrderKey: thread.activeOrderKey ?? null,
274 ...(thread.lastVisitedAt === undefined
275 ? {}
276 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
277 titleRegeneration:
278 thread.titleRegeneration == null
279 ? null
280 : {
281 requestId: thread.titleRegeneration.requestId,
282 startedAt: iso(thread.titleRegeneration.startedAt),
283 },
284 deletedAt: nullableIso(thread.deletedAt),
285 source: thread,
286 };
288​
289export function scopeThreadShell(
290 environmentId: EnvironmentId,
291 thread: OrchestrationV2ThreadShell,
292): EnvironmentThreadShell {
293 return presentThreadShell(environmentId, thread);
295​
296const THREAD_PROVIDER_STACK_LIMIT = 3;
297​
298export function resolveThreadProviderStack(
299 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
300): ReadonlyArray<ProviderInstanceId> {
301 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
302 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
303 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
305​
306/**
307 * Both shell and detail timers count from the activity-owning run's work
308 * start, never last activity. A wake keeps the start of the work it continues.
309 */
310export function resolveThreadWorkingStartedAt(input: {
311 readonly latestRun: Pick<
312 ThreadRunSummary,
313 "runId" | "startedAt" | "requestedAt" | "completedAt"
314 > | null;
315 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
316}): string | null {
317 const valid = (value: string | null | undefined) =>
318 value != null && Number.isFinite(Date.parse(value)) ? value : null;
319 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
320 const run = input.latestRun;
321 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
322 return valid(run.startedAt) ?? valid(run.requestedAt);
323 }
324 return null;