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

models.ts

336 lines13.2 KB

1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
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;
26​
27/**
28 * A pristine V2 thread projection paired with the environment that produced it.
29 *
30 * The projection stays nested so the server projection and all structurally
31 * shared collections retain their identities. Rich consumers read V2 state
32 * directly instead of a second presentation-shaped thread graph.
33 */
34export interface EnvironmentThread {
35 readonly environmentId: EnvironmentId;
36 readonly projection: OrchestrationV2ThreadProjection;
38​
39export interface ThreadRunSummary {
40 readonly runId: RunId;
41 readonly status: OrchestrationV2RunStatus;
42 readonly requestedAt: string | null;
43 readonly startedAt: string | null;
44 readonly completedAt: string | null;
45 readonly assistantMessageId: MessageId | null;
46 readonly sourcePlanRef?: {
47 readonly threadId: ThreadId;
48 readonly planId: PlanId;
49 };
51​
52export interface ThreadRuntimeSummary {
53 readonly status: OrchestrationV2RunStatus | "idle";
54 readonly activeRunId: RunId | null;
55 readonly activityStartedAt?: string | null | undefined;
56 readonly providerInstanceId: ProviderInstanceId;
57 readonly providerName: string | null;
58 readonly lastError: string | null;
59 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
60 readonly usageLimitResetAt?: string | null;
61 readonly updatedAt: string;
63​
64export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
65 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
67​
68/** Archiving may discard queued work, but it must not detach a provider that
69 * is preparing, starting, or running a turn. */
70export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
71 if (runtime?.status === "queued") return runtime.activeRunId === null;
72 return (
73 runtime?.status !== "preparing" &&
74 runtime?.status !== "starting" &&
75 runtime?.status !== "running"
76 );
78​
79function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
80 return (
81 status === "preparing" ||
82 status === "queued" ||
83 status === "starting" ||
84 status === "running" ||
85 status === "waiting"
86 );
88​
89export interface EnvironmentThreadShell {
90 readonly environmentId: EnvironmentId;
91 readonly id: ThreadId;
92 readonly projectId: ProjectId;
93 readonly title: string;
94 readonly providerInstanceId: ProviderInstanceId;
95 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
96 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
97 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
98 readonly branch: string | null;
99 readonly worktreePath: string | null;
100 readonly lineage: OrchestrationV2ThreadShell["lineage"];
101 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
102 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
103 readonly latestRun: ThreadRunSummary | null;
104 readonly runtime: ThreadRuntimeSummary | null;
105 readonly latestUserMessageAt: string | null;
106 /** The last message the user wrote. `undefined` means the server predates it. */
107 readonly latestUserAuthoredMessageAt?: string | null;
108 readonly hasPendingApprovals: boolean;
109 readonly hasPendingUserInput: boolean;
110 readonly hasActionableProposedPlan: boolean;
111 readonly pendingBackgroundTasks: ReadonlyArray<
112 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
113 >;
114 /** Provider instances that have owned the root conversation, oldest first. */
115 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
116 /** Native `/goal` on the active provider thread. */
117 readonly goal: OrchestrationV2ProviderGoal | null;
118 readonly itemCount: number;
119 readonly visibleItemCount: number;
120 readonly createdAt: string;
121 readonly updatedAt: string;
122 readonly archivedAt: string | null;
123 readonly settledOverride: "settled" | "active" | null;
124 readonly settledAt: string | null;
125 readonly unsettledAt: string | null;
126 readonly snoozedUntil: string | null;
127 readonly snoozedAt: string | null;
128 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
129 readonly pinnedAt: string | null;
130 readonly autoSettleDisabledAt?: string | null;
131 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
132 readonly pinOrderKey: string | null;
133 /** Slot in the user-arranged active order; null for keyless active threads. */
134 readonly activeOrderKey: string | null;
135 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
136 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
137 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
138 /**
139 * Server-tracked visited watermark. `undefined` means the environment's
140 * server predates visited tracking and clients should fall back to any
141 * local visited state they keep.
142 */
143 readonly lastVisitedAt?: string | null;
144 /** Pending title regeneration marker; null when no request is in flight. */
145 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
146 readonly deletedAt: string | null;
147 readonly source: OrchestrationV2ThreadShell;
149​
150function iso(value: DateTime.Utc): string {
151 return DateTime.formatIso(value);
153​
154function nullableIso(value: DateTime.Utc | null): string | null {
155 return value === null ? null : iso(value);
157​
158function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
159 return (
160 status === "completed" ||
161 status === "interrupted" ||
162 status === "failed" ||
163 status === "cancelled" ||
164 status === "rolled_back"
165 );
167​
168// Park runtime at idle when the post-settlement background roster holds the
169// run's completion, so #4415 waiting-presentation Waiting (session.idle) can
170// consume CTM runtime. Only work that wakes the agent holds it: commands it
171// left running, such as a dev server, present the run's own status (#14872).
172// The server suppresses the roster while an interruptible activity run exists,
173// so a remaining roster is stronger than checkpoint-oriented waiting.
174// latestRun keeps the latest run's status for history presentation.
175// A failed latest run outranks the roster, so the failure stays visible.
176function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
177 const parkAtIdle =
178 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
179 thread.status !== "failed";
180 // A pull request watch can hold a thread that never ran.
181 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
182 return null;
183 }
184 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
185 return {
186 status,
187 activeRunId: thread.activeRunId,
188 activityStartedAt:
189 thread.activityRunStartedAt === undefined
190 ? undefined
191 : nullableIso(thread.activityRunStartedAt),
192 providerInstanceId: thread.providerInstanceId,
193 providerName: null,
194 lastError: thread.lastError ?? null,
195 lastErrorClass: thread.lastErrorClass ?? null,
196 usageLimitResetAt: thread.usageLimitResetAt ?? null,
197 updatedAt: iso(thread.updatedAt),
198 };
200​
201export function scopeProject(
202 environmentId: EnvironmentId,
203 project: OrchestrationProjectShell,
204): EnvironmentProject {
205 return { ...project, environmentId };
207​
208export function presentThreadShell(
209 environmentId: EnvironmentId,
210 thread: OrchestrationV2ThreadShell,
211): EnvironmentThreadShell {
212 const updatedAt = iso(thread.updatedAt);
213 const latestRun =
214 thread.latestRunId === null
215 ? null
216 : ({
217 runId: thread.latestRunId,
218 status: thread.status === "idle" ? "completed" : thread.status,
219 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
220 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
221 completedAt:
222 thread.latestRunCompletedAt === undefined
223 ? thread.status === "idle" || terminalRunStatus(thread.status)
224 ? updatedAt
225 : null
226 : nullableIso(thread.latestRunCompletedAt),
227 assistantMessageId: null,
228 } satisfies ThreadRunSummary);
229 return {
230 environmentId,
231 id: thread.id,
232 projectId: thread.projectId,
233 title:
234 thread.lineage.relationshipToParent === "subagent"
235 ? formatSubagentDisplayTitle(thread.title)
236 : thread.title,
237 providerInstanceId: thread.providerInstanceId,
238 modelSelection: thread.modelSelection,
239 runtimeMode: thread.runtimeMode,
240 interactionMode: thread.interactionMode,
241 branch: thread.branch,
242 worktreePath: thread.worktreePath,
243 pullRequests: threadPullRequestsOf(thread),
244 linkedPullRequest: thread.linkedPullRequest ?? null,
245 branchPullRequest: thread.branchPullRequest ?? null,
246 lineage: thread.lineage,
247 forkedFrom: thread.forkedFrom,
248 activeProviderThreadId: thread.activeProviderThreadId,
249 latestRun,
250 runtime: shellRuntime(thread),
251 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
252 ...(thread.latestUserAuthoredMessageAt === undefined
253 ? {}
254 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
255 hasPendingApprovals:
256 thread.pendingRuntimeRequest !== null &&
257 thread.pendingRuntimeRequest.kind !== "user_input" &&
258 thread.pendingRuntimeRequest.kind !== "auth_refresh",
259 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
260 hasActionableProposedPlan: thread.hasActionableProposedPlan,
261 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
262 providerInstanceHistory: thread.providerInstanceHistory ?? [],
263 goal: thread.goal ?? null,
264 itemCount: thread.itemCount,
265 visibleItemCount: thread.visibleItemCount,
266 createdAt: iso(thread.createdAt),
267 updatedAt,
268 archivedAt: nullableIso(thread.archivedAt),
269 settledOverride: thread.settledOverride,
270 settledAt: nullableIso(thread.settledAt),
271 unsettledAt: nullableIso(thread.unsettledAt ?? null),
272 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
273 snoozedAt: nullableIso(thread.snoozedAt ?? null),
274 limitRecovery: thread.limitRecovery ?? null,
275 pinnedAt: nullableIso(thread.pinnedAt ?? null),
276 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
277 pinOrderKey: thread.pinOrderKey ?? null,
278 activeOrderKey: thread.activeOrderKey ?? null,
279 ...(thread.lastVisitedAt === undefined
280 ? {}
281 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
282 titleRegeneration:
283 thread.titleRegeneration == null
284 ? null
285 : {
286 requestId: thread.titleRegeneration.requestId,
287 startedAt: iso(thread.titleRegeneration.startedAt),
288 },
289 deletedAt: nullableIso(thread.deletedAt),
290 source: thread,
291 };
293​
294export function scopeThreadShell(
295 environmentId: EnvironmentId,
296 thread: OrchestrationV2ThreadShell,
297): EnvironmentThreadShell {
298 return presentThreadShell(environmentId, thread);
300​
301const THREAD_PROVIDER_STACK_LIMIT = 3;
302​
303/**
304 * Provider instances to draw in a thread row's trailing stack, back to front:
305 * the current one is always last, earlier owners precede it oldest first.
306 * Newest history wins when the thread has been handed off more times than fit.
307 */
308export function resolveThreadProviderStack(
309 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
310): ReadonlyArray<ProviderInstanceId> {
311 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
312 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
313 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
315​
316/**
317 * Both shell and detail timers count from the activity-owning run's work
318 * start, never last activity. A wake keeps the start of the work it continues.
319 */
320export function resolveThreadWorkingStartedAt(input: {
321 readonly latestRun: Pick<
322 ThreadRunSummary,
323 "runId" | "startedAt" | "requestedAt" | "completedAt"
324 > | null;
325 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
326}): string | null {
327 const valid = (value: string | null | undefined) =>
328 value != null && Number.isFinite(Date.parse(value)) ? value : null;
329 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
330 // Older servers can supply a timestamp only if the newest run owns the work.
331 const run = input.latestRun;
332 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
333 return valid(run.startedAt) ?? valid(run.requestedAt);
334 }
335 return null;