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

orchestrationV2PendingBackgroundWork.ts

260 lines8.3 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>;
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 readonly runId?: OrchestrationV2Run["id"] | string | null;
86 readonly nativeItemRef?: {
87 readonly nativeId: string | null;
88 } | null;
89 readonly input?: unknown;
90 readonly prompt?: string | undefined;
91 readonly childThreadId?: ThreadId | null;
92};
93​
94function isLatestRunSettledForBackgroundWait(
95 latestRun: PendingBackgroundWorkRun | null | undefined,
96): boolean {
97 if (latestRun === undefined || latestRun === null) {
98 return false;
99 }
100 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
102​
103function isPersistentDynamicToolInput(input: unknown): boolean {
104 if (input === null || typeof input !== "object" || Array.isArray(input)) {
105 return false;
106 }
107 return Reflect.get(input, "persistent") === true;
109​
110function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
111 if (typeof item.title === "string" && item.title.trim().length > 0) {
112 return item.title.trim();
113 }
114 if (item.type === "command_execution" && typeof item.input === "string") {
115 const command = item.input.trim();
116 return command.length > 0 ? command : undefined;
117 }
118 if (item.type === "dynamic_tool") {
119 const toolName = Reflect.get(item, "toolName");
120 if (typeof toolName === "string" && toolName.trim().length > 0) {
121 return toolName.trim();
122 }
123 }
124 if (item.type === "subagent" && typeof item.prompt === "string") {
125 const prompt = item.prompt.trim();
126 return prompt.length > 0 ? prompt : undefined;
127 }
128 return undefined;
130​
131function pendingTaskFromTurnItem(
132 taskId: string,
133 item: PendingBackgroundWorkTurnItem,
134): PendingBackgroundWorkTask {
135 const description = descriptionFromTurnItem(item);
136 const named = { taskId, ...(description === undefined ? {} : { description }) };
137 switch (item.type) {
138 case "subagent":
139 return {
140 ...named,
141 kind: "subagent",
142 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
143 };
144 case "command_execution":
145 return { ...named, kind: "command" };
146 default:
147 return { ...named, kind: "background_task" };
148 }
150​
151function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
152 const nativeId = item.nativeItemRef?.nativeId;
153 if (typeof nativeId === "string" && nativeId.length > 0) {
154 return nativeId;
155 }
156 return String(item.id);
158​
159/**
160 * The turn items the pending-work list names, without its settled-run gate.
161 * Stop ends exactly these, so the list and Stop cannot disagree.
162 */
163export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: {
164 readonly turnItems: ReadonlyArray<Item>;
165 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
166}): ReadonlyArray<Item> {
167 const rolledBackRunIds = new Set(
168 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
169 );
170 return input.turnItems.filter(
171 (item) =>
172 BACKGROUND_TURN_ITEM_TYPES.has(item.type) &&
173 isOrchestrationV2WorkActive(item.status) &&
174 !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) &&
175 (item.runId === undefined ||
176 item.runId === null ||
177 !rolledBackRunIds.has(String(item.runId))),
178 );
180​
181export function derivePendingBackgroundWork(input: {
182 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
183 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
184 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
185 readonly activeProviderThreadId?: string | null;
186 readonly hasActiveRun?: boolean;
187 /**
188 * Run rows used to exclude items owned by rolled_back runs. Optional for
189 * callers that already filtered (SQL shell path); in-memory callers should
190 * pass projection runs so policy cannot drift.
191 */
192 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
193 readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined;
194}): ReadonlyArray<PendingBackgroundWorkTask> {
195 const hasActiveRun =
196 input.hasActiveRun ??
197 input.runs?.some(
198 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
199 ) ??
200 false;
201 if (hasActiveRun) {
202 return [];
203 }
204 if (input.latestRun == null) {
205 return pullRequestWatchTasks(input.pullRequests);
206 }
207 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
208 return [];
209 }
210​
211 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
212​
213 const providerThreads =
214 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
215 ? input.providerThreads
216 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
217​
218 for (const providerThread of providerThreads) {
219 for (const task of providerThread.pendingBackgroundTasks ?? []) {
220 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
221 continue;
222 }
223 const { description: rawDescription, ...named } = task;
224 const description = rawDescription?.trim();
225 byTaskId.set(task.taskId, {
226 ...named,
227 ...(description === undefined || description.length === 0 ? {} : { description }),
228 });
229 }
230 }
231​
232 for (const item of pendingBackgroundTurnItems(input)) {
233 const taskId = nativeTaskIdFromTurnItem(item);
234 if (byTaskId.has(taskId)) {
235 continue;
236 }
237​
238 byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item));
239 }
240​
241 for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task);
242​
243 return Array.from(byTaskId.values());
245​
246function pullRequestWatchTasks(
247 pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
248): Array<PendingBackgroundWorkTask> {
249 return (pullRequests ?? []).flatMap((link) =>
250 link.watch === undefined || link.source === "stack-dismissed"
251 ? []
252 : [
253 {
254 taskId: `pull-request-watch:${threadPullRequestKeyOf(link)}`,
255 description: `Watching pull request #${link.number}`,
256 kind: "monitor" as const,
257 },
258 ],
259 );