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

models.ts

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