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

models.ts

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