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 readonly snapshot: Pick<NonNullable<ThreadPullRequestLink["snapshot"]>, "state"> | null;
117};
118
119type PendingBackgroundWorkProviderThread = Pick<
120 OrchestrationV2ProviderThread,
121 "id" | "pendingBackgroundTasks"
122> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };
123
124type PendingBackgroundWorkTurnItem = {
125 readonly id: OrchestrationV2TurnItem["id"] | string;
126 readonly type: OrchestrationV2TurnItem["type"];
127 readonly status: OrchestrationV2TurnItem["status"];
128 readonly title: string | null;
129 /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */
130 readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];
131 readonly runId?: OrchestrationV2Run["id"] | string | null;
132 readonly nativeItemRef?: {
133 readonly nativeId: string | null;
134 } | null;
135 readonly input?: unknown;
136 readonly monitor?: boolean | undefined;
137 readonly prompt?: string | undefined;
138 readonly childThreadId?: ThreadId | null;
139};
140
141function isLatestRunSettledForBackgroundWait(
142 latestRun: PendingBackgroundWorkRun | null | undefined,
143): boolean {
144 if (latestRun === undefined || latestRun === null) {
145 return false;
146 }
147 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
148}
149
150function isPersistentDynamicToolInput(input: unknown): boolean {
151 if (input === null || typeof input !== "object" || Array.isArray(input)) {
152 return false;
153 }
154 return Reflect.get(input, "persistent") === true;
155}
156
157function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
158 if (typeof item.title === "string" && item.title.trim().length > 0) {
159 return item.title.trim();
160 }
161 if (item.type === "command_execution" && typeof item.input === "string") {
162 const command = item.input.trim();
163 return command.length > 0 ? command : undefined;
164 }
165 if (item.type === "dynamic_tool") {
166 const toolName = Reflect.get(item, "toolName");
167 if (typeof toolName === "string" && toolName.trim().length > 0) {
168 return toolName.trim();
169 }
170 }
171 if (item.type === "subagent" && typeof item.prompt === "string") {
172 const prompt = item.prompt.trim();
173 return prompt.length > 0 ? prompt : undefined;
174 }
175 return undefined;
176}
177
178function pendingTaskFromTurnItem(
179 taskId: string,
180 item: PendingBackgroundWorkTurnItem,
181): PendingBackgroundWorkTask {
182 const description = descriptionFromTurnItem(item);
183 const named = { taskId, ...(description === undefined ? {} : { description }) };
184 switch (item.type) {
185 case "subagent":
186 return {
187 ...named,
188 kind: "subagent",
189 ...(item.owningProviderInstanceId === undefined
190 ? {}
191 : { providerInstanceId: item.owningProviderInstanceId }),
192 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
193 };
194 case "command_execution":
195 return { ...named, kind: item.monitor === true ? "monitor" : "command" };
196 default:
197 return { ...named, kind: "background_task" };
198 }
199}
200
201function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
202 const nativeId = item.nativeItemRef?.nativeId;
203 if (typeof nativeId === "string" && nativeId.length > 0) {
204 return nativeId;
205 }
206 return String(item.id);
207}
208
209/** Items Stop ends, without the pending list's settled-run gate. */
210export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
211 readonly turnItems: ReadonlyArray<Item>;
212 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
213}): ReadonlyArray<Item> {
214 const rolledBackRunIds = new Set(
215 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
216 );
217 return input.turnItems.filter(
218 (item) =>
219 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
220 isOrchestrationV2WorkActive(item.status) &&
221 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
222 (item.runId === undefined ||
223 item.runId === null ||
224 !rolledBackRunIds.has(String(item.runId))),
225 );
226}
227
228export function derivePendingBackgroundWork(input: {
229 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
230 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
231 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
232 readonly activeProviderThreadId?: string | null;
233 readonly hasActiveRun?: boolean;
234 /** Excludes rolled-back runs; optional only when the caller already filtered them, as SQL shell reads do. */
235 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
236 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
237}): ReadonlyArray<PendingBackgroundWorkTask> {
238 const hasActiveRun =
239 input.hasActiveRun ??
240 input.runs?.some(
241 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
242 ) ??
243 false;
244 if (hasActiveRun) {
245 return [];
246 }
247 if (input.latestRun == null) {
248 return pullRequestWatchTasks(input.pullRequests);
249 }
250 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
251 return [];
252 }
253
254 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
255
256 const providerThreads =
257 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
258 ? input.providerThreads
259 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
260
261 for (const providerThread of providerThreads) {
262 for (const task of providerThread.pendingBackgroundTasks ?? []) {
263 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
264 continue;
265 }
266 const { description: rawDescription, ...named } = task;
267 const description = rawDescription?.trim();
268 byTaskId.set(task.taskId, {
269 ...named,
270 ...(task.kind === "subagent"
271 ? { providerInstanceId: providerThread.providerInstanceId }
272 : {}),
273 ...(description === undefined || description.length === 0 ? {} : { description }),
274 });
275 }
276 }
277
278 for (const item of pendingBackgroundTurnItems(input)) {
279 const taskId = nativeTaskIdFromTurnItem(item);
280 if (byTaskId.has(taskId)) {
281 continue;
282 }
283
284 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
285 }
286
287 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
288
289 return Array.from(byTaskId.values());
290}
291
292function pullRequestWatchTasks(
293 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
294): Array<PendingBackgroundWorkTask> {
295 return (pullRequests ?? []).flatMap((link) =>
296 // The watch reactor ends a merged PR's watch without waking the agent, so it holds nothing.
297 link.watch === undefined ||
298 link.source === "stack-dismissed" ||
299 link.snapshot?.state === "merged"
300 ? []
301 : [
302 {
303 // Links store their normalized identity, and this id only has to be unique within the
304 // thread, so it reads those fields instead of parsing the URL.
305 taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
306 description: `Watching pull request #${link.number}`,
307 kind: "monitor" as const,
308 awaited: true as const,
309 },
310 ],
311 );
312}