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";
13import { threadPullRequestKeyOf } from "./threadPullRequests.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/**
39 * Includes `waiting`: a successful turn persists as waiting until checkpoint capture flips it to
40 * completed, and waiting is only set from completed. Excludes `rolled_back`: the provider-thread
41 * roster is not run-tied, so a rolled-back latest run must fail the gate entirely (not only item
42 * filter).
43 */
44const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
45 "cancelled",
46 "completed",
47 "failed",
48 "interrupted",
49 "waiting",
50]);
51
52void TERMINAL_RUN_STATUSES;
53
54export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
55
56export function turnItemUpdateCanEndBackgroundWork(
57 item: Pick<OrchestrationV2TurnItem, "type" | "status">,
58): boolean {
59 return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
60}
61
62export function deriveBlockedOnThreadWait(input: {
63 readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null;
64 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
65}): boolean {
66 if (input.activeRun?.status !== "running") return false;
67 let hasWait = false;
68 for (const item of input.turnItems) {
69 if (
70 item.runId !== input.activeRun.id ||
71 !EXECUTION_TURN_ITEM_TYPES.has(item.type) ||
72 (item.status !== "running" && item.status !== "waiting") ||
73 // App-owned rows track the child, including the child a blocking delegate is waiting for.
74 (item.type === "subagent" && item.origin === "app_owned")
75 ) {
76 continue;
77 }
78 if (item.type !== "dynamic_tool") return false;
79 const tool = resolveT3McpToolId(item.toolName);
80 if (
81 tool !== "t3_thread_wait" &&
82 !(
83 tool === "delegate_task" &&
84 Predicate.isObject(item.input) &&
85 Reflect.get(item.input, "mode") === "wait"
86 )
87 ) {
88 return false;
89 }
90 hasWait = true;
91 }
92 return hasWait;
93}
94
95export function backgroundWorkHoldsCompletion(
96 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
97): boolean {
98 return tasks.some((task) => backgroundWorkKindHoldsCompletion(task.kind));
99}
100
101function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
102 switch (kind) {
103 case "command":
104 return false;
105 case "subagent":
106 case "monitor":
107 case "background_task":
108 return true;
109 }
110}
111
112type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
113
114type PendingBackgroundWorkPullRequest = Pick<
115 ThreadPullRequestLink,
116 "host" | "repository" | "number" | "url" | "source" | "watch"
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 prompt?: string | undefined;
137 readonly childThreadId?: ThreadId | null;
138};
139
140function isLatestRunSettledForBackgroundWait(
141 latestRun: PendingBackgroundWorkRun | null | undefined,
142): boolean {
143 if (latestRun === undefined || latestRun === null) {
144 return false;
145 }
146 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
147}
148
149function isPersistentDynamicToolInput(input: unknown): boolean {
150 if (input === null || typeof input !== "object" || Array.isArray(input)) {
151 return false;
152 }
153 return Reflect.get(input, "persistent") === true;
154}
155
156function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
157 if (typeof item.title === "string" && item.title.trim().length > 0) {
158 return item.title.trim();
159 }
160 if (item.type === "command_execution" && typeof item.input === "string") {
161 const command = item.input.trim();
162 return command.length > 0 ? command : undefined;
163 }
164 if (item.type === "dynamic_tool") {
165 const toolName = Reflect.get(item, "toolName");
166 if (typeof toolName === "string" && toolName.trim().length > 0) {
167 return toolName.trim();
168 }
169 }
170 if (item.type === "subagent" && typeof item.prompt === "string") {
171 const prompt = item.prompt.trim();
172 return prompt.length > 0 ? prompt : undefined;
173 }
174 return undefined;
175}
176
177function pendingTaskFromTurnItem(
178 taskId: string,
179 item: PendingBackgroundWorkTurnItem,
180): PendingBackgroundWorkTask {
181 const description = descriptionFromTurnItem(item);
182 const named = { taskId, ...(description === undefined ? {} : { description }) };
183 switch (item.type) {
184 case "subagent":
185 return {
186 ...named,
187 kind: "subagent",
188 ...(item.owningProviderInstanceId === undefined
189 ? {}
190 : { providerInstanceId: item.owningProviderInstanceId }),
191 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
192 };
193 case "command_execution":
194 return { ...named, kind: "command" };
195 default:
196 return { ...named, kind: "background_task" };
197 }
198}
199
200function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
201 const nativeId = item.nativeItemRef?.nativeId;
202 if (typeof nativeId === "string" && nativeId.length > 0) {
203 return nativeId;
204 }
205 return String(item.id);
206}
207
208/**
209 * The turn items the pending-work list names, without its settled-run gate.
210 * Stop ends exactly these, so the list and Stop cannot disagree.
211 */
212export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
213 readonly turnItems: ReadonlyArray<Item>;
214 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
215}): ReadonlyArray<Item> {
216 const rolledBackRunIds = new Set(
217 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
218 );
219 return input.turnItems.filter(
220 (item) =>
221 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
222 isOrchestrationV2WorkActive(item.status) &&
223 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
224 (item.runId === undefined ||
225 item.runId === null ||
226 !rolledBackRunIds.has(String(item.runId))),
227 );
228}
229
230export function derivePendingBackgroundWork(input: {
231 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
232 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
233 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
234 readonly activeProviderThreadId?: string | null;
235 readonly hasActiveRun?: boolean;
236 /**
237 * Run rows used to exclude items owned by rolled_back runs. Optional for
238 * callers that already filtered (SQL shell path); in-memory callers should
239 * pass projection runs so policy cannot drift.
240 */
241 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
242 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
243}): ReadonlyArray<PendingBackgroundWorkTask> {
244 const hasActiveRun =
245 input.hasActiveRun ??
246 input.runs?.some(
247 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
248 ) ??
249 false;
250 if (hasActiveRun) {
251 return [];
252 }
253 if (input.latestRun == null) {
254 return pullRequestWatchTasks(input.pullRequests);
255 }
256 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
257 return [];
258 }
259
260 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
261
262 const providerThreads =
263 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
264 ? input.providerThreads
265 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
266
267 for (const providerThread of providerThreads) {
268 for (const task of providerThread.pendingBackgroundTasks ?? []) {
269 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
270 continue;
271 }
272 const { description: rawDescription, ...named } = task;
273 const description = rawDescription?.trim();
274 byTaskId.set(task.taskId, {
275 ...named,
276 ...(task.kind === "subagent"
277 ? { providerInstanceId: providerThread.providerInstanceId }
278 : {}),
279 ...(description === undefined || description.length === 0 ? {} : { description }),
280 });
281 }
282 }
283
284 for (const item of pendingBackgroundTurnItems(input)) {
285 const taskId = nativeTaskIdFromTurnItem(item);
286 if (byTaskId.has(taskId)) {
287 continue;
288 }
289
290 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
291 }
292
293 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
294
295 return Array.from(byTaskId.values());
296}
297
298function pullRequestWatchTasks(
299 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
300): Array<PendingBackgroundWorkTask> {
301 return (pullRequests ?? []).flatMap((link) =>
302 link.watch === undefined || link.source === "stack-dismissed"
303 ? []
304 : [
305 {
306 taskId: `pull-request-watch:${threadPullRequestKeyOf(link)}`,
307 description: `Watching pull request #${link.number}`,
308 kind: "monitor" as const,
309 },
310 ],
311 );
312}