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