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

orchestrationV2PendingBackgroundWork.ts

268 lines8.9 KB

1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderThread,
4 OrchestrationV2Run,
5 OrchestrationV2TurnItem,
6 ThreadId,
7 ThreadPullRequestLink,
8} from "@t3tools/contracts";
9import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
10​
11import { threadPullRequestKeyOf } from "./threadPullRequests.ts";
12​
13const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
14 "command_execution",
15 "dynamic_tool",
16 "subagent",
17]);
18​
19const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
20 "cancelled",
21 "completed",
22 "failed",
23 "interrupted",
24 "rolled_back",
25]);
26​
27/**
28 * Includes `waiting`: a successful turn persists as waiting until checkpoint capture flips it to
29 * completed, and waiting is only set from completed. Excludes `rolled_back`: the provider-thread
30 * roster is not run-tied, so a rolled-back latest run must fail the gate entirely (not only item
31 * filter).
32 */
33const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
34 "cancelled",
35 "completed",
36 "failed",
37 "interrupted",
38 "waiting",
39]);
40​
41void TERMINAL_RUN_STATUSES;
42​
43export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
44​
45export function turnItemUpdateCanEndBackgroundWork(
46 item: Pick<OrchestrationV2TurnItem, "type" | "status">,
47): boolean {
48 return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
50​
51export function backgroundWorkHoldsCompletion(
52 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
53): boolean {
54 return tasks.some((task) => backgroundWorkKindHoldsCompletion(task.kind));
56​
57function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
58 switch (kind) {
59 case "command":
60 return false;
61 case "subagent":
62 case "monitor":
63 case "background_task":
64 return true;
65 }
67​
68type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
69​
70type PendingBackgroundWorkPullRequest = Pick<
71 ThreadPullRequestLink,
72 "host" | "repository" | "number" | "url" | "source" | "watch"
73>;
74​
75type PendingBackgroundWorkProviderThread = Pick<
76 OrchestrationV2ProviderThread,
77 "id" | "pendingBackgroundTasks"
78> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };
79​
80type PendingBackgroundWorkTurnItem = {
81 readonly id: OrchestrationV2TurnItem["id"] | string;
82 readonly type: OrchestrationV2TurnItem["type"];
83 readonly status: OrchestrationV2TurnItem["status"];
84 readonly title: string | null;
85 /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */
86 readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];
87 readonly runId?: OrchestrationV2Run["id"] | string | null;
88 readonly nativeItemRef?: {
89 readonly nativeId: string | null;
90 } | null;
91 readonly input?: unknown;
92 readonly prompt?: string | undefined;
93 readonly childThreadId?: ThreadId | null;
94};
95​
96function isLatestRunSettledForBackgroundWait(
97 latestRun: PendingBackgroundWorkRun | null | undefined,
98): boolean {
99 if (latestRun === undefined || latestRun === null) {
100 return false;
101 }
102 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
104​
105function isPersistentDynamicToolInput(input: unknown): boolean {
106 if (input === null || typeof input !== "object" || Array.isArray(input)) {
107 return false;
108 }
109 return Reflect.get(input, "persistent") === true;
111​
112function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
113 if (typeof item.title === "string" && item.title.trim().length > 0) {
114 return item.title.trim();
115 }
116 if (item.type === "command_execution" && typeof item.input === "string") {
117 const command = item.input.trim();
118 return command.length > 0 ? command : undefined;
119 }
120 if (item.type === "dynamic_tool") {
121 const toolName = Reflect.get(item, "toolName");
122 if (typeof toolName === "string" && toolName.trim().length > 0) {
123 return toolName.trim();
124 }
125 }
126 if (item.type === "subagent" && typeof item.prompt === "string") {
127 const prompt = item.prompt.trim();
128 return prompt.length > 0 ? prompt : undefined;
129 }
130 return undefined;
132​
133function pendingTaskFromTurnItem(
134 taskId: string,
135 item: PendingBackgroundWorkTurnItem,
136): PendingBackgroundWorkTask {
137 const description = descriptionFromTurnItem(item);
138 const named = { taskId, ...(description === undefined ? {} : { description }) };
139 switch (item.type) {
140 case "subagent":
141 return {
142 ...named,
143 kind: "subagent",
144 ...(item.owningProviderInstanceId === undefined
145 ? {}
146 : { providerInstanceId: item.owningProviderInstanceId }),
147 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
148 };
149 case "command_execution":
150 return { ...named, kind: "command" };
151 default:
152 return { ...named, kind: "background_task" };
153 }
155​
156function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
157 const nativeId = item.nativeItemRef?.nativeId;
158 if (typeof nativeId === "string" && nativeId.length > 0) {
159 return nativeId;
160 }
161 return String(item.id);
163​
164/**
165 * The turn items the pending-work list names, without its settled-run gate.
166 * Stop ends exactly these, so the list and Stop cannot disagree.
167 */
168export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
169 readonly turnItems: ReadonlyArray<Item>;
170 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
171}): ReadonlyArray<Item> {
172 const rolledBackRunIds = new Set(
173 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
174 );
175 return input.turnItems.filter(
176 (item) =>
177 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
178 isOrchestrationV2WorkActive(item.status) &&
179 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
180 (item.runId === undefined ||
181 item.runId === null ||
182 !rolledBackRunIds.has(String(item.runId))),
183 );
185​
186export function derivePendingBackgroundWork(input: {
187 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
188 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
189 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
190 readonly activeProviderThreadId?: string | null;
191 readonly hasActiveRun?: boolean;
192 /**
193 * Run rows used to exclude items owned by rolled_back runs. Optional for
194 * callers that already filtered (SQL shell path); in-memory callers should
195 * pass projection runs so policy cannot drift.
196 */
197 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
198 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
199}): ReadonlyArray<PendingBackgroundWorkTask> {
200 const hasActiveRun =
201 input.hasActiveRun ??
202 input.runs?.some(
203 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
204 ) ??
205 false;
206 if (hasActiveRun) {
207 return [];
208 }
209 if (input.latestRun == null) {
210 return pullRequestWatchTasks(input.pullRequests);
211 }
212 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
213 return [];
214 }
215​
216 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
217​
218 const providerThreads =
219 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
220 ? input.providerThreads
221 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
222​
223 for (const providerThread of providerThreads) {
224 for (const task of providerThread.pendingBackgroundTasks ?? []) {
225 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
226 continue;
227 }
228 const { description: rawDescription, ...named } = task;
229 const description = rawDescription?.trim();
230 byTaskId.set(task.taskId, {
231 ...named,
232 ...(task.kind === "subagent"
233 ? { providerInstanceId: providerThread.providerInstanceId }
234 : {}),
235 ...(description === undefined || description.length === 0 ? {} : { description }),
236 });
237 }
238 }
239​
240 for (const item of pendingBackgroundTurnItems(input)) {
241 const taskId = nativeTaskIdFromTurnItem(item);
242 if (byTaskId.has(taskId)) {
243 continue;
244 }
245​
246 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
247 }
248​
249 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
250​
251 return Array.from(byTaskId.values());
253​
254function pullRequestWatchTasks(
255 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
256): Array<PendingBackgroundWorkTask> {
257 return (pullRequests ?? []).flatMap((link) =>
258 link.watch === undefined || link.source === "stack-dismissed"
259 ? []
260 : [
261 {
262 taskId: `pull-request-watch:${threadPullRequestKeyOf(link)}`,
263 description: `Watching pull request #${link.number}`,
264 kind: "monitor" as const,
265 },
266 ],
267 );