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

orchestrationV2PendingBackgroundWork.ts

313 lines10.4 KB

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/**
38 * Includes `waiting`: a successful turn persists as waiting until checkpoint capture flips it to
39 * completed, and waiting is only set from completed. Excludes `rolled_back`: the provider-thread
40 * roster is not run-tied, so a rolled-back latest run must fail the gate entirely (not only item
41 * filter).
42 */
43const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
44 "cancelled",
45 "completed",
46 "failed",
47 "interrupted",
48 "waiting",
49]);
50​
51void TERMINAL_RUN_STATUSES;
52​
53export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
54​
55export function turnItemUpdateCanEndBackgroundWork(
56 item: Pick<OrchestrationV2TurnItem, "type" | "status">,
57): boolean {
58 return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
60​
61export function deriveBlockedOnThreadWait(input: {
62 readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null;
63 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
64}): boolean {
65 if (input.activeRun?.status !== "running") return false;
66 let hasWait = false;
67 for (const item of input.turnItems) {
68 if (
69 item.runId !== input.activeRun.id ||
70 !EXECUTION_TURN_ITEM_TYPES.has(item.type) ||
71 (item.status !== "running" && item.status !== "waiting") ||
72 // App-owned rows track the child, including the child a blocking delegate is waiting for.
73 (item.type === "subagent" && item.origin === "app_owned")
74 ) {
75 continue;
76 }
77 if (item.type !== "dynamic_tool") return false;
78 const tool = resolveT3McpToolId(item.toolName);
79 if (
80 tool !== "t3_thread_wait" &&
81 !(
82 tool === "delegate_task" &&
83 Predicate.isObject(item.input) &&
84 Reflect.get(item.input, "mode") === "wait"
85 )
86 ) {
87 return false;
88 }
89 hasWait = true;
90 }
91 return hasWait;
93​
94export function backgroundWorkHoldsCompletion(
95 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
96): boolean {
97 return tasks.some((task) => backgroundWorkKindHoldsCompletion(task.kind));
99​
100function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
101 switch (kind) {
102 case "command":
103 return false;
104 case "subagent":
105 case "monitor":
106 case "background_task":
107 return true;
108 }
110​
111type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
112​
113type PendingBackgroundWorkPullRequest = Pick<
114 ThreadPullRequestLink,
115 "host" | "repository" | "number" | "url" | "source" | "watch"
116>;
117​
118type PendingBackgroundWorkProviderThread = Pick<
119 OrchestrationV2ProviderThread,
120 "id" | "pendingBackgroundTasks"
121> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };
122​
123type PendingBackgroundWorkTurnItem = {
124 readonly id: OrchestrationV2TurnItem["id"] | string;
125 readonly type: OrchestrationV2TurnItem["type"];
126 readonly status: OrchestrationV2TurnItem["status"];
127 readonly title: string | null;
128 /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */
129 readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];
130 readonly runId?: OrchestrationV2Run["id"] | string | null;
131 readonly nativeItemRef?: {
132 readonly nativeId: string | null;
133 } | null;
134 readonly input?: unknown;
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);
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;
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;
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: "command" };
194 default:
195 return { ...named, kind: "background_task" };
196 }
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);
206​
207/**
208 * The turn items the pending-work list names, without its settled-run gate.
209 * Stop ends exactly these, so the list and Stop cannot disagree.
210 */
211export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
212 readonly turnItems: ReadonlyArray<Item>;
213 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
214}): ReadonlyArray<Item> {
215 const rolledBackRunIds = new Set(
216 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
217 );
218 return input.turnItems.filter(
219 (item) =>
220 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
221 isOrchestrationV2WorkActive(item.status) &&
222 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
223 (item.runId === undefined ||
224 item.runId === null ||
225 !rolledBackRunIds.has(String(item.runId))),
226 );
228​
229export function derivePendingBackgroundWork(input: {
230 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
231 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
232 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
233 readonly activeProviderThreadId?: string | null;
234 readonly hasActiveRun?: boolean;
235 /**
236 * Run rows used to exclude items owned by rolled_back runs. Optional for
237 * callers that already filtered (SQL shell path); in-memory callers should
238 * pass projection runs so policy cannot drift.
239 */
240 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
241 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
242}): ReadonlyArray<PendingBackgroundWorkTask> {
243 const hasActiveRun =
244 input.hasActiveRun ??
245 input.runs?.some(
246 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
247 ) ??
248 false;
249 if (hasActiveRun) {
250 return [];
251 }
252 if (input.latestRun == null) {
253 return pullRequestWatchTasks(input.pullRequests);
254 }
255 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
256 return [];
257 }
258​
259 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
260​
261 const providerThreads =
262 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
263 ? input.providerThreads
264 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
265​
266 for (const providerThread of providerThreads) {
267 for (const task of providerThread.pendingBackgroundTasks ?? []) {
268 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
269 continue;
270 }
271 const { description: rawDescription, ...named } = task;
272 const description = rawDescription?.trim();
273 byTaskId.set(task.taskId, {
274 ...named,
275 ...(task.kind === "subagent"
276 ? { providerInstanceId: providerThread.providerInstanceId }
277 : {}),
278 ...(description === undefined || description.length === 0 ? {} : { description }),
279 });
280 }
281 }
282​
283 for (const item of pendingBackgroundTurnItems(input)) {
284 const taskId = nativeTaskIdFromTurnItem(item);
285 if (byTaskId.has(taskId)) {
286 continue;
287 }
288​
289 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
290 }
291​
292 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
293​
294 return Array.from(byTaskId.values());
296​
297function pullRequestWatchTasks(
298 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
299): Array<PendingBackgroundWorkTask> {
300 return (pullRequests ?? []).flatMap((link) =>
301 link.watch === undefined || link.source === "stack-dismissed"
302 ? []
303 : [
304 {
305 // Links store their normalized identity, and this id only has to be unique within the
306 // thread, so it reads those fields instead of parsing the URL.
307 taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
308 description: `Watching pull request #${link.number}`,
309 kind: "monitor" as const,
310 },
311 ],
312 );