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

orchestrationV2PendingBackgroundWork.ts

323 lines11.0 KB

1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderThread,
4 OrchestrationV2Run,
5 OrchestrationV2ThreadShell,
6 OrchestrationV2TurnItem,
7 ThreadId,
8 ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
11import * as Predicate from "effect/Predicate";
12​
13import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
14​
15const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
16 "command_execution",
17 "dynamic_tool",
18 "subagent",
19]);
20​
21// Plans and text streams can stay open across tool calls without executing work.
22const EXECUTION_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
23 ...BACKGROUND_TURN_ITEM_TYPES,
24 "file_change",
25 "file_search",
26 "web_search",
27 "compaction",
28]);
29​
30const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
31 "cancelled",
32 "completed",
33 "failed",
34 "interrupted",
35 "rolled_back",
36]);
37​
38// waiting is completed work awaiting checkpoints; exclude rolled_back entirely because provider threads are not run-tied.
39const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
40 "cancelled",
41 "completed",
42 "failed",
43 "interrupted",
44 "waiting",
45]);
46​
47void TERMINAL_RUN_STATUSES;
48​
49export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
50​
51export function turnItemUpdateCanEndBackgroundWork(
52 item: Pick<OrchestrationV2TurnItem, "type" | "status">,
53): boolean {
54 return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
56​
57export function deriveBlockedOnThreadWait(input: {
58 readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null;
59 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
60}): boolean {
61 if (input.activeRun?.status !== "running") return false;
62 let hasWait = false;
63 for (const item of input.turnItems) {
64 if (
65 item.runId !== input.activeRun.id ||
66 !EXECUTION_TURN_ITEM_TYPES.has(item.type) ||
67 (item.status !== "running" && item.status !== "waiting") ||
68 // App-owned rows track the child, including the child a blocking delegate is waiting for.
69 (item.type === "subagent" && item.origin === "app_owned")
70 ) {
71 continue;
72 }
73 if (item.type !== "dynamic_tool") return false;
74 const tool = resolveT3McpToolId(item.toolName);
75 if (
76 tool !== "t3_thread_wait" &&
77 !(
78 tool === "delegate_task" &&
79 Predicate.isObject(item.input) &&
80 Reflect.get(item.input, "mode") === "wait"
81 )
82 ) {
83 return false;
84 }
85 hasWait = true;
86 }
87 return hasWait;
89​
90export function backgroundWorkHoldsCompletion(
91 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind" | "awaited">>,
92): boolean {
93 return tasks.some(
94 (task) => task.awaited === true || backgroundWorkKindHoldsCompletion(task.kind),
95 );
97​
98// Commands and monitors are as often a dev server or its watchdog as a wait, so they hold
99// only when the agent marks them awaited.
100function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
101 switch (kind) {
102 case "command":
103 case "monitor":
104 return false;
105 case "subagent":
106 case "background_task":
107 return true;
108 }
110​
111/** A monitor wakes the agent once per line, so a progress wake run's completion waits for the monitor to end. */
112export function monitorHoldsWakeCompletion(
113 thread: Pick<OrchestrationV2ThreadShell, "latestRunBackgroundWake" | "pendingBackgroundTasks">,
114): boolean {
115 return (
116 thread.latestRunBackgroundWake === true &&
117 (thread.pendingBackgroundTasks ?? []).some((task) => task.kind === "monitor")
118 );
120​
121type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
122​
123type PendingBackgroundWorkPullRequest = Pick<
124 ThreadPullRequestLink,
125 "host" | "repository" | "number" | "url" | "source" | "watch"
126> & {
127 readonly snapshot: Pick<NonNullable<ThreadPullRequestLink["snapshot"]>, "state"> | null;
128};
129​
130type PendingBackgroundWorkProviderThread = Pick<
131 OrchestrationV2ProviderThread,
132 "id" | "pendingBackgroundTasks"
133> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };
134​
135type PendingBackgroundWorkTurnItem = {
136 readonly id: OrchestrationV2TurnItem["id"] | string;
137 readonly type: OrchestrationV2TurnItem["type"];
138 readonly status: OrchestrationV2TurnItem["status"];
139 readonly title: string | null;
140 /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */
141 readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];
142 readonly runId?: OrchestrationV2Run["id"] | string | null;
143 readonly nativeItemRef?: {
144 readonly nativeId: string | null;
145 } | null;
146 readonly input?: unknown;
147 readonly monitor?: boolean | undefined;
148 readonly prompt?: string | undefined;
149 readonly childThreadId?: ThreadId | null;
150};
151​
152function isLatestRunSettledForBackgroundWait(
153 latestRun: PendingBackgroundWorkRun | null | undefined,
154): boolean {
155 if (latestRun === undefined || latestRun === null) {
156 return false;
157 }
158 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
160​
161function isPersistentDynamicToolInput(input: unknown): boolean {
162 if (input === null || typeof input !== "object" || Array.isArray(input)) {
163 return false;
164 }
165 return Reflect.get(input, "persistent") === true;
167​
168function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
169 if (typeof item.title === "string" && item.title.trim().length > 0) {
170 return item.title.trim();
171 }
172 if (item.type === "command_execution" && typeof item.input === "string") {
173 const command = item.input.trim();
174 return command.length > 0 ? command : undefined;
175 }
176 if (item.type === "dynamic_tool") {
177 const toolName = Reflect.get(item, "toolName");
178 if (typeof toolName === "string" && toolName.trim().length > 0) {
179 return toolName.trim();
180 }
181 }
182 if (item.type === "subagent" && typeof item.prompt === "string") {
183 const prompt = item.prompt.trim();
184 return prompt.length > 0 ? prompt : undefined;
185 }
186 return undefined;
188​
189function pendingTaskFromTurnItem(
190 taskId: string,
191 item: PendingBackgroundWorkTurnItem,
192): PendingBackgroundWorkTask {
193 const description = descriptionFromTurnItem(item);
194 const named = { taskId, ...(description === undefined ? {} : { description }) };
195 switch (item.type) {
196 case "subagent":
197 return {
198 ...named,
199 kind: "subagent",
200 ...(item.owningProviderInstanceId === undefined
201 ? {}
202 : { providerInstanceId: item.owningProviderInstanceId }),
203 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
204 };
205 case "command_execution":
206 return { ...named, kind: item.monitor === true ? "monitor" : "command" };
207 default:
208 return { ...named, kind: "background_task" };
209 }
211​
212function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
213 const nativeId = item.nativeItemRef?.nativeId;
214 if (typeof nativeId === "string" && nativeId.length > 0) {
215 return nativeId;
216 }
217 return String(item.id);
219​
220/** Items Stop ends, without the pending list's settled-run gate. */
221export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
222 readonly turnItems: ReadonlyArray<Item>;
223 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
224}): ReadonlyArray<Item> {
225 const rolledBackRunIds = new Set(
226 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
227 );
228 return input.turnItems.filter(
229 (item) =>
230 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
231 isOrchestrationV2WorkActive(item.status) &&
232 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
233 (item.runId === undefined ||
234 item.runId === null ||
235 !rolledBackRunIds.has(String(item.runId))),
236 );
238​
239export function derivePendingBackgroundWork(input: {
240 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
241 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
242 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
243 readonly activeProviderThreadId?: string | null;
244 readonly hasActiveRun?: boolean;
245 /** Excludes rolled-back runs; optional only when the caller already filtered them, as SQL shell reads do. */
246 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
247 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
248}): ReadonlyArray<PendingBackgroundWorkTask> {
249 const hasActiveRun =
250 input.hasActiveRun ??
251 input.runs?.some(
252 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
253 ) ??
254 false;
255 if (hasActiveRun) {
256 return [];
257 }
258 if (input.latestRun == null) {
259 return pullRequestWatchTasks(input.pullRequests);
260 }
261 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
262 return [];
263 }
264​
265 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
266​
267 const providerThreads =
268 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
269 ? input.providerThreads
270 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
271​
272 for (const providerThread of providerThreads) {
273 for (const task of providerThread.pendingBackgroundTasks ?? []) {
274 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
275 continue;
276 }
277 const { description: rawDescription, ...named } = task;
278 const description = rawDescription?.trim();
279 byTaskId.set(task.taskId, {
280 ...named,
281 ...(task.kind === "subagent"
282 ? { providerInstanceId: providerThread.providerInstanceId }
283 : {}),
284 ...(description === undefined || description.length === 0 ? {} : { description }),
285 });
286 }
287 }
288​
289 for (const item of pendingBackgroundTurnItems(input)) {
290 const taskId = nativeTaskIdFromTurnItem(item);
291 if (byTaskId.has(taskId)) {
292 continue;
293 }
294​
295 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
296 }
297​
298 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
299​
300 return Array.from(byTaskId.values());
302​
303function pullRequestWatchTasks(
304 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
305): Array<PendingBackgroundWorkTask> {
306 return (pullRequests ?? []).flatMap((link) =>
307 // The watch reactor ends a merged PR's watch without waking the agent, so it holds nothing.
308 link.watch === undefined ||
309 link.source === "stack-dismissed" ||
310 link.snapshot?.state === "merged"
311 ? []
312 : [
313 {
314 // Links store their normalized identity, and this id only has to be unique within the
315 // thread, so it reads those fields instead of parsing the URL.
316 taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
317 description: `Watching pull request #${link.number}`,
318 kind: "monitor" as const,
319 awaited: true as const,
320 },
321 ],
322 );