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

models.ts

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