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

models.ts

405 lines15.4 KB

1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { threadPullRequestsOf } from "../threadPullRequests.ts";
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​
37type ProjectionTurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
38type StreamedProjectionTurnItem = Extract<
39 ProjectionTurnItem,
40 { readonly type: "assistant_message" | "reasoning" }
41>;
42​
43/** A turn item without the fields that move while it streams. */
44export type ThreadStructureTurnItem =
45 | Exclude<ProjectionTurnItem, StreamedProjectionTurnItem>
46 | Omit<Extract<ProjectionTurnItem, { readonly type: "assistant_message" }>, "text" | "updatedAt">
47 | Omit<Extract<ProjectionTurnItem, { readonly type: "reasoning" }>, "text" | "updatedAt">;
48​
49export type ThreadStructureVisibleTurnItem = Omit<
50 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
51 "item"
52> & {
53 readonly item: ThreadStructureTurnItem;
54};
55​
56/**
57 * A thread projection without the fields that move while a reply streams, so a
58 * reader of the quiet thread cannot depend on them and go stale. A full
59 * projection is assignable to it.
60 */
61export type ThreadStructureThread = Omit<
62 OrchestrationV2ThreadProjection["thread"],
63 "updatedAt" | "lastVisitedAt"
64>;
65​
66export type ThreadStructure = Omit<
67 OrchestrationV2ThreadProjection,
68 "thread" | "turnItems" | "visibleTurnItems" | "updatedAt"
69> & {
70 readonly thread: ThreadStructureThread;
71 readonly turnItems: ReadonlyArray<ThreadStructureTurnItem>;
72 readonly visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>;
73};
74​
75export interface EnvironmentThreadStructure {
76 readonly environmentId: EnvironmentId;
77 readonly projection: ThreadStructure;
79​
80export interface ThreadRunSummary {
81 readonly runId: RunId;
82 readonly status: OrchestrationV2RunStatus;
83 readonly requestedAt: string | null;
84 readonly startedAt: string | null;
85 readonly completedAt: string | null;
86 readonly assistantMessageId: MessageId | null;
87 /**
88 * The run is still open, but its provider turn already ended, so nothing is
89 * generating while the server settles it.
90 */
91 readonly turnEnded?: boolean;
92 readonly sourcePlanRef?: {
93 readonly threadId: ThreadId;
94 readonly planId: PlanId;
95 };
97​
98export interface ThreadRuntimeSummary {
99 readonly status: OrchestrationV2RunStatus | "idle";
100 readonly activeRunId: RunId | null;
101 readonly activityStartedAt?: string | null | undefined;
102 readonly providerInstanceId: ProviderInstanceId;
103 readonly providerName: string | null;
104 readonly lastError: string | null;
105 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
106 readonly lastErrorCode?: string | null;
107 readonly usageLimitResetAt?: string | null;
108 readonly updatedAt: string;
110​
111/** The runtime summary a thread's structure determines; see ThreadStructure. */
112export type ThreadStructureRuntime = Omit<ThreadRuntimeSummary, "updatedAt">;
113​
114export function threadRuntimeIsActive(runtime: ThreadStructureRuntime | null | undefined): boolean {
115 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
117​
118export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
119 if (runtime?.status === "queued") return runtime.activeRunId === null;
120 return (
121 runtime?.status !== "preparing" &&
122 runtime?.status !== "starting" &&
123 runtime?.status !== "running"
124 );
126​
127function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
128 return (
129 status === "preparing" ||
130 status === "queued" ||
131 status === "starting" ||
132 status === "running" ||
133 status === "waiting"
134 );
136​
137export interface EnvironmentThreadShell {
138 readonly environmentId: EnvironmentId;
139 readonly id: ThreadId;
140 readonly projectId: ProjectId;
141 readonly title: string;
142 readonly providerInstanceId: ProviderInstanceId;
143 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
144 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
145 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
146 readonly branch: string | null;
147 readonly worktreePath: string | null;
148 /** Presentation flag: lives in the right panel, out of the sidebar. */
149 readonly sideChat: boolean;
150 readonly lineage: OrchestrationV2ThreadShell["lineage"];
151 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
152 readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;
153 /** The thread in a linked environment that delegated this one, if one did. */
154 readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null;
155 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
156 readonly latestRun: ThreadRunSummary | null;
157 readonly runtime: ThreadRuntimeSummary | null;
158 readonly blockedOnThreadWait?: boolean;
159 readonly latestUserMessageAt: string | null;
160 readonly latestUserAuthoredMessageAt?: string | null;
161 readonly hasPendingApprovals: boolean;
162 readonly hasPendingUserInput: boolean;
163 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
164 /** Guest messages waiting for the owner to send or dismiss. */
165 readonly pendingGuestMessageCount?: number;
166 readonly hasActionableProposedPlan: boolean;
167 readonly pendingBackgroundTasks: ReadonlyArray<
168 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
169 >;
170 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
171 readonly goal: OrchestrationV2ProviderGoal | null;
172 readonly itemCount: number;
173 readonly visibleItemCount: number;
174 readonly createdAt: string;
175 readonly updatedAt: string;
176 readonly archivedAt: string | null;
177 readonly settledOverride: "settled" | "active" | null;
178 readonly settledAt: string | null;
179 readonly unsettledAt: string | null;
180 readonly snoozedUntil: string | null;
181 readonly snoozedAt: string | null;
182 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
183 readonly pinnedAt: string | null;
184 readonly autoSettleDisabledAt?: string | null;
185 readonly pinOrderKey: string | null;
186 readonly activeOrderKey: string | null;
187 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
188 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
189 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
190 /**
191 * Server-tracked visited watermark. `undefined` means the environment's
192 * server predates visited tracking and clients should fall back to any
193 * local visited state they keep.
194 */
195 readonly lastVisitedAt?: string | null;
196 /** Server-tracked open history for search ranking. */
197 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
198 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
199 readonly deletedAt: string | null;
200 readonly source: OrchestrationV2ThreadShell;
202​
203function iso(value: DateTime.Utc): string {
204 return DateTime.formatIso(value);
206​
207function nullableIso(value: DateTime.Utc | null): string | null {
208 return value === null ? null : iso(value);
210​
211function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
212 return (
213 status === "completed" ||
214 status === "interrupted" ||
215 status === "failed" ||
216 status === "cancelled" ||
217 status === "rolled_back"
218 );
220​
221// Only work the agent waits on holds it: commands and monitors it left running
222// unmarked, such as a dev server, present the run's own status. The
223// server suppresses the roster while an interruptible activity run exists, so a
224// remaining roster is stronger than checkpoint-oriented waiting.
225function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
226 const parkAtIdle =
227 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
228 thread.status !== "failed";
229 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
230 return null;
231 }
232 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
233 return {
234 status,
235 activeRunId: thread.activeRunId,
236 activityStartedAt:
237 thread.activityRunStartedAt === undefined
238 ? undefined
239 : nullableIso(thread.activityRunStartedAt),
240 providerInstanceId: thread.providerInstanceId,
241 providerName: null,
242 lastError: thread.lastError ?? null,
243 lastErrorClass: thread.lastErrorClass ?? null,
244 lastErrorCode: thread.lastErrorCode ?? null,
245 usageLimitResetAt: thread.usageLimitResetAt ?? null,
246 updatedAt: iso(thread.updatedAt),
247 };
249​
250export function scopeProject(
251 environmentId: EnvironmentId,
252 project: OrchestrationProjectShell,
253): EnvironmentProject {
254 return { ...project, environmentId };
256​
257export type PendingSubagentRequest = "approval" | "user_input";
258​
259export function presentThreadShell(
260 environmentId: EnvironmentId,
261 thread: OrchestrationV2ThreadShell,
262 pendingSubagentRequest: PendingSubagentRequest | null = null,
263): EnvironmentThreadShell {
264 const updatedAt = iso(thread.updatedAt);
265 const latestRun =
266 thread.latestRunId === null
267 ? null
268 : ({
269 runId: thread.latestRunId,
270 status: thread.status === "idle" ? "completed" : thread.status,
271 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
272 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
273 completedAt:
274 thread.latestRunCompletedAt === undefined
275 ? thread.status === "idle" || terminalRunStatus(thread.status)
276 ? updatedAt
277 : null
278 : nullableIso(thread.latestRunCompletedAt),
279 assistantMessageId: null,
280 } satisfies ThreadRunSummary);
281 const runtime = shellRuntime(thread);
282 // Waiting runs have ended their provider turn and are only draining effects.
283 const runtimeIsWorking =
284 runtime?.status === "preparing" ||
285 runtime?.status === "starting" ||
286 runtime?.status === "running";
287 return {
288 environmentId,
289 id: thread.id,
290 projectId: thread.projectId,
291 title:
292 thread.lineage.relationshipToParent === "subagent"
293 ? formatSubagentDisplayTitle(thread.title)
294 : thread.title,
295 providerInstanceId: thread.providerInstanceId,
296 modelSelection: thread.modelSelection,
297 runtimeMode: thread.runtimeMode,
298 interactionMode: thread.interactionMode,
299 branch: thread.branch,
300 worktreePath: thread.worktreePath,
301 pullRequests: threadPullRequestsOf(thread),
302 linkedPullRequest: thread.linkedPullRequest ?? null,
303 branchPullRequest: thread.branchPullRequest ?? null,
304 sideChat: thread.sideChat === true,
305 lineage: thread.lineage,
306 forkedFrom: thread.forkedFrom,
307 linkOrigin: thread.linkOrigin ?? null,
308 delegatedFrom: thread.delegatedFrom ?? null,
309 activeProviderThreadId: thread.activeProviderThreadId,
310 latestRun,
311 runtime,
312 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
313 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
314 ...(thread.latestUserAuthoredMessageAt === undefined
315 ? {}
316 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
317 hasPendingApprovals:
318 thread.pendingRuntimeRequest !== null &&
319 thread.pendingRuntimeRequest.kind !== "user_input" &&
320 thread.pendingRuntimeRequest.kind !== "auth_refresh",
321 hasPendingUserInput:
322 thread.pendingRuntimeRequest?.kind === "user_input" &&
323 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
324 pendingSubagentRequest,
325 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
326 hasActionableProposedPlan: thread.hasActionableProposedPlan,
327 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
328 providerInstanceHistory: thread.providerInstanceHistory ?? [],
329 goal: thread.goal ?? null,
330 itemCount: thread.itemCount,
331 visibleItemCount: thread.visibleItemCount,
332 createdAt: iso(thread.createdAt),
333 updatedAt,
334 archivedAt: nullableIso(thread.archivedAt),
335 settledOverride: thread.settledOverride,
336 settledAt: nullableIso(thread.settledAt),
337 unsettledAt: nullableIso(thread.unsettledAt ?? null),
338 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
339 snoozedAt: nullableIso(thread.snoozedAt ?? null),
340 limitRecovery: thread.limitRecovery ?? null,
341 pinnedAt: nullableIso(thread.pinnedAt ?? null),
342 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
343 pinOrderKey: thread.pinOrderKey ?? null,
344 activeOrderKey: thread.activeOrderKey ?? null,
345 ...(thread.lastVisitedAt === undefined
346 ? {}
347 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
348 opens: thread.opens ?? null,
349 titleRegeneration:
350 thread.titleRegeneration == null
351 ? null
352 : {
353 requestId: thread.titleRegeneration.requestId,
354 startedAt: iso(thread.titleRegeneration.startedAt),
355 },
356 deletedAt: nullableIso(thread.deletedAt),
357 source: thread,
358 };
360​
361export function scopeThreadShell(
362 environmentId: EnvironmentId,
363 thread: OrchestrationV2ThreadShell,
364): EnvironmentThreadShell {
365 return presentThreadShell(environmentId, thread);
367​
368const THREAD_PROVIDER_STACK_LIMIT = 3;
369​
370export function resolveThreadProviderStack(
371 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
372): ReadonlyArray<ProviderInstanceId> {
373 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
374 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
375 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
377​
378/**
379 * Both shell and detail timers count from the activity-owning run's work
380 * start, never last activity. A wake keeps the start of the work it continues.
381 */
382export function resolveThreadWorkingStartedAt(input: {
383 readonly latestRun: Pick<
384 ThreadRunSummary,
385 "runId" | "startedAt" | "requestedAt" | "completedAt"
386 > | null;
387 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
388}): string | null {
389 const valid = (value: string | null | undefined) =>
390 value != null && Number.isFinite(Date.parse(value)) ? value : null;
391 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
392 const run = input.latestRun;
393 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
394 return valid(run.startedAt) ?? valid(run.requestedAt);
395 }
396 return null;
398​
399export function formatWorkingDurationLabel(elapsedMs: number): string {
400 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
401 if (seconds < 60) return `${seconds}s`;
402 const minutes = Math.floor(seconds / 60);
403 if (minutes < 60) return `${minutes}m`;
404 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;