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

models.ts

397 lines15.0 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 readonly lineage: OrchestrationV2ThreadShell["lineage"];
149 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
150 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
151 readonly latestRun: ThreadRunSummary | null;
152 readonly runtime: ThreadRuntimeSummary | null;
153 readonly blockedOnThreadWait?: boolean;
154 readonly latestUserMessageAt: string | null;
155 readonly latestUserAuthoredMessageAt?: string | null;
156 readonly hasPendingApprovals: boolean;
157 readonly hasPendingUserInput: boolean;
158 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
159 /** Guest messages waiting for the owner to send or dismiss. */
160 readonly pendingGuestMessageCount?: number;
161 readonly hasActionableProposedPlan: boolean;
162 readonly pendingBackgroundTasks: ReadonlyArray<
163 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
164 >;
165 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
166 readonly goal: OrchestrationV2ProviderGoal | null;
167 readonly itemCount: number;
168 readonly visibleItemCount: number;
169 readonly createdAt: string;
170 readonly updatedAt: string;
171 readonly archivedAt: string | null;
172 readonly settledOverride: "settled" | "active" | null;
173 readonly settledAt: string | null;
174 readonly unsettledAt: string | null;
175 readonly snoozedUntil: string | null;
176 readonly snoozedAt: string | null;
177 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
178 readonly pinnedAt: string | null;
179 readonly autoSettleDisabledAt?: string | null;
180 readonly pinOrderKey: string | null;
181 readonly activeOrderKey: string | null;
182 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
183 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
184 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
185 /**
186 * Server-tracked visited watermark. `undefined` means the environment's
187 * server predates visited tracking and clients should fall back to any
188 * local visited state they keep.
189 */
190 readonly lastVisitedAt?: string | null;
191 /** Server-tracked open history for search ranking. */
192 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
193 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
194 readonly deletedAt: string | null;
195 readonly source: OrchestrationV2ThreadShell;
197​
198function iso(value: DateTime.Utc): string {
199 return DateTime.formatIso(value);
201​
202function nullableIso(value: DateTime.Utc | null): string | null {
203 return value === null ? null : iso(value);
205​
206function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
207 return (
208 status === "completed" ||
209 status === "interrupted" ||
210 status === "failed" ||
211 status === "cancelled" ||
212 status === "rolled_back"
213 );
215​
216// Only work the agent waits on holds it: commands and monitors it left running
217// unmarked, such as a dev server, present the run's own status. The
218// server suppresses the roster while an interruptible activity run exists, so a
219// remaining roster is stronger than checkpoint-oriented waiting.
220function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
221 const parkAtIdle =
222 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
223 thread.status !== "failed";
224 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
225 return null;
226 }
227 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
228 return {
229 status,
230 activeRunId: thread.activeRunId,
231 activityStartedAt:
232 thread.activityRunStartedAt === undefined
233 ? undefined
234 : nullableIso(thread.activityRunStartedAt),
235 providerInstanceId: thread.providerInstanceId,
236 providerName: null,
237 lastError: thread.lastError ?? null,
238 lastErrorClass: thread.lastErrorClass ?? null,
239 lastErrorCode: thread.lastErrorCode ?? null,
240 usageLimitResetAt: thread.usageLimitResetAt ?? null,
241 updatedAt: iso(thread.updatedAt),
242 };
244​
245export function scopeProject(
246 environmentId: EnvironmentId,
247 project: OrchestrationProjectShell,
248): EnvironmentProject {
249 return { ...project, environmentId };
251​
252export type PendingSubagentRequest = "approval" | "user_input";
253​
254export function presentThreadShell(
255 environmentId: EnvironmentId,
256 thread: OrchestrationV2ThreadShell,
257 pendingSubagentRequest: PendingSubagentRequest | null = null,
258): EnvironmentThreadShell {
259 const updatedAt = iso(thread.updatedAt);
260 const latestRun =
261 thread.latestRunId === null
262 ? null
263 : ({
264 runId: thread.latestRunId,
265 status: thread.status === "idle" ? "completed" : thread.status,
266 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
267 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
268 completedAt:
269 thread.latestRunCompletedAt === undefined
270 ? thread.status === "idle" || terminalRunStatus(thread.status)
271 ? updatedAt
272 : null
273 : nullableIso(thread.latestRunCompletedAt),
274 assistantMessageId: null,
275 } satisfies ThreadRunSummary);
276 const runtime = shellRuntime(thread);
277 // Waiting runs have ended their provider turn and are only draining effects.
278 const runtimeIsWorking =
279 runtime?.status === "preparing" ||
280 runtime?.status === "starting" ||
281 runtime?.status === "running";
282 return {
283 environmentId,
284 id: thread.id,
285 projectId: thread.projectId,
286 title:
287 thread.lineage.relationshipToParent === "subagent"
288 ? formatSubagentDisplayTitle(thread.title)
289 : thread.title,
290 providerInstanceId: thread.providerInstanceId,
291 modelSelection: thread.modelSelection,
292 runtimeMode: thread.runtimeMode,
293 interactionMode: thread.interactionMode,
294 branch: thread.branch,
295 worktreePath: thread.worktreePath,
296 pullRequests: threadPullRequestsOf(thread),
297 linkedPullRequest: thread.linkedPullRequest ?? null,
298 branchPullRequest: thread.branchPullRequest ?? null,
299 lineage: thread.lineage,
300 forkedFrom: thread.forkedFrom,
301 activeProviderThreadId: thread.activeProviderThreadId,
302 latestRun,
303 runtime,
304 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
305 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
306 ...(thread.latestUserAuthoredMessageAt === undefined
307 ? {}
308 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
309 hasPendingApprovals:
310 thread.pendingRuntimeRequest !== null &&
311 thread.pendingRuntimeRequest.kind !== "user_input" &&
312 thread.pendingRuntimeRequest.kind !== "auth_refresh",
313 hasPendingUserInput:
314 thread.pendingRuntimeRequest?.kind === "user_input" &&
315 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
316 pendingSubagentRequest,
317 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
318 hasActionableProposedPlan: thread.hasActionableProposedPlan,
319 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
320 providerInstanceHistory: thread.providerInstanceHistory ?? [],
321 goal: thread.goal ?? null,
322 itemCount: thread.itemCount,
323 visibleItemCount: thread.visibleItemCount,
324 createdAt: iso(thread.createdAt),
325 updatedAt,
326 archivedAt: nullableIso(thread.archivedAt),
327 settledOverride: thread.settledOverride,
328 settledAt: nullableIso(thread.settledAt),
329 unsettledAt: nullableIso(thread.unsettledAt ?? null),
330 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
331 snoozedAt: nullableIso(thread.snoozedAt ?? null),
332 limitRecovery: thread.limitRecovery ?? null,
333 pinnedAt: nullableIso(thread.pinnedAt ?? null),
334 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
335 pinOrderKey: thread.pinOrderKey ?? null,
336 activeOrderKey: thread.activeOrderKey ?? null,
337 ...(thread.lastVisitedAt === undefined
338 ? {}
339 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
340 opens: thread.opens ?? null,
341 titleRegeneration:
342 thread.titleRegeneration == null
343 ? null
344 : {
345 requestId: thread.titleRegeneration.requestId,
346 startedAt: iso(thread.titleRegeneration.startedAt),
347 },
348 deletedAt: nullableIso(thread.deletedAt),
349 source: thread,
350 };
352​
353export function scopeThreadShell(
354 environmentId: EnvironmentId,
355 thread: OrchestrationV2ThreadShell,
356): EnvironmentThreadShell {
357 return presentThreadShell(environmentId, thread);
359​
360const THREAD_PROVIDER_STACK_LIMIT = 3;
361​
362export function resolveThreadProviderStack(
363 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
364): ReadonlyArray<ProviderInstanceId> {
365 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
366 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
367 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
369​
370/**
371 * Both shell and detail timers count from the activity-owning run's work
372 * start, never last activity. A wake keeps the start of the work it continues.
373 */
374export function resolveThreadWorkingStartedAt(input: {
375 readonly latestRun: Pick<
376 ThreadRunSummary,
377 "runId" | "startedAt" | "requestedAt" | "completedAt"
378 > | null;
379 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
380}): string | null {
381 const valid = (value: string | null | undefined) =>
382 value != null && Number.isFinite(Date.parse(value)) ? value : null;
383 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
384 const run = input.latestRun;
385 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
386 return valid(run.startedAt) ?? valid(run.requestedAt);
387 }
388 return null;
390​
391export function formatWorkingDurationLabel(elapsedMs: number): string {
392 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
393 if (seconds < 60) return `${seconds}s`;
394 const minutes = Math.floor(seconds / 60);
395 if (minutes < 60) return `${minutes}m`;
396 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;