Open History to see the last commit
1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderThread,
4 OrchestrationV2Run,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
8
9const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
10 "command_execution",
11 "dynamic_tool",
12 "subagent",
13]);
14
15/**
16 * True terminal run statuses (includes `rolled_back`). Retained as the
17 * canonical terminal set for this module; do not widen or reuse it as the
18 * background-wait gate — that gate intentionally excludes `rolled_back`.
19 */
20const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
21 "cancelled",
22 "completed",
23 "failed",
24 "interrupted",
25 "rolled_back",
26]);
27
28/**
29 * Run statuses that allow a pending-background roster to surface.
30 * Includes `waiting`: a successful turn persists as waiting until checkpoint
31 * capture flips it to completed, and waiting is only set from completed.
32 * Excludes `rolled_back`: the provider-thread roster is not run-tied, so a
33 * rolled-back latest run must fail the gate entirely (not only item filter).
34 * Built explicitly rather than spreading or deleting from TERMINAL_RUN_STATUSES.
35 */
36const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
37 "cancelled",
38 "completed",
39 "failed",
40 "interrupted",
41 "waiting",
42]);
43
44// Keep TERMINAL_RUN_STATUSES referenced so the true-terminal set stays defined
45// next to the background-wait subset (rolled_back is terminal, not wait-settled).
46void TERMINAL_RUN_STATUSES;
47
48export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
49
50type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
51
52type PendingBackgroundWorkProviderThread = Pick<
53 OrchestrationV2ProviderThread,
54 "id" | "pendingBackgroundTasks"
55>;
56
57type PendingBackgroundWorkTurnItem = {
58 readonly id: OrchestrationV2TurnItem["id"] | string;
59 readonly type: OrchestrationV2TurnItem["type"];
60 readonly status: OrchestrationV2TurnItem["status"];
61 readonly title: string | null;
62 /** When present and the run is rolled_back, the item is abandoned, not pending. */
63 readonly runId?: OrchestrationV2Run["id"] | string | null;
64 readonly nativeItemRef?: {
65 readonly nativeId: string | null;
66 } | null;
67 readonly input?: unknown;
68 readonly prompt?: string | undefined;
69};
70
71function isLatestRunSettledForBackgroundWait(
72 latestRun: PendingBackgroundWorkRun | null | undefined,
73): boolean {
74 if (latestRun === undefined || latestRun === null) {
75 return false;
76 }
77 return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
78}
79
80function isPersistentDynamicToolInput(input: unknown): boolean {
81 if (input === null || typeof input !== "object" || Array.isArray(input)) {
82 return false;
83 }
84 return Reflect.get(input, "persistent") === true;
85}
86
87function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
88 if (typeof item.title === "string" && item.title.trim().length > 0) {
89 return item.title.trim();
90 }
91 if (item.type === "command_execution" && typeof item.input === "string") {
92 const command = item.input.trim();
93 return command.length > 0 ? command : undefined;
94 }
95 if (item.type === "dynamic_tool") {
96 const toolName = Reflect.get(item, "toolName");
97 if (typeof toolName === "string" && toolName.trim().length > 0) {
98 return toolName.trim();
99 }
100 }
101 if (item.type === "subagent" && typeof item.prompt === "string") {
102 const prompt = item.prompt.trim();
103 return prompt.length > 0 ? prompt : undefined;
104 }
105 return undefined;
106}
107
108function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
109 const nativeId = item.nativeItemRef?.nativeId;
110 if (typeof nativeId === "string" && nativeId.length > 0) {
111 return nativeId;
112 }
113 return String(item.id);
114}
115
116/**
117 * Derive one normalized pending-background-work list for post-settlement UI.
118 *
119 * Sources:
120 * - Provider-thread roster (Claude SDK background tasks)
121 * - Active command_execution / dynamic_tool / subagent turn items
122 *
123 * Gated on latest root run settlement. Dedupes by native task ID. Excludes
124 * the roster while any interruptible foreground run remains active. Excludes
125 * Grok persistent monitors (`dynamic_tool` input with `persistent: true`).
126 * Excludes turn items whose run resolves to `rolled_back` (abandoned work);
127 * items with a null or absent run id stay eligible (matches SQL shell path).
128 * Does not consult subagent entities (those double-count turn items).
129 */
130export function derivePendingBackgroundWork(input: {
131 readonly latestRun: PendingBackgroundWorkRun | null | undefined;
132 readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
133 readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
134 readonly activeProviderThreadId?: string | null;
135 readonly hasActiveRun?: boolean;
136 /**
137 * Run rows used to exclude items owned by rolled_back runs. Optional for
138 * callers that already filtered (SQL shell path); in-memory callers should
139 * pass projection runs so policy cannot drift.
140 */
141 readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
142}): ReadonlyArray<PendingBackgroundWorkTask> {
143 const hasActiveRun =
144 input.hasActiveRun ??
145 input.runs?.some(
146 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
147 ) ??
148 false;
149 if (hasActiveRun) {
150 return [];
151 }
152 if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
153 return [];
154 }
155
156 const byTaskId = new Map<string, PendingBackgroundWorkTask>();
157 const rolledBackRunIds = new Set(
158 (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
159 );
160
161 const providerThreads =
162 input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
163 ? input.providerThreads
164 : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
165
166 for (const providerThread of providerThreads) {
167 for (const task of providerThread.pendingBackgroundTasks ?? []) {
168 if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
169 continue;
170 }
171 const description = task.description?.trim();
172 byTaskId.set(task.taskId, {
173 taskId: task.taskId,
174 ...(description === undefined || description.length === 0 ? {} : { description }),
175 ...(task.taskType === undefined ? {} : { taskType: task.taskType }),
176 });
177 }
178 }
179
180 for (const item of input.turnItems) {
181 if (!BACKGROUND_TURN_ITEM_TYPES.has(item.type)) {
182 continue;
183 }
184 if (!isOrchestrationV2WorkActive(item.status)) {
185 continue;
186 }
187 if (item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) {
188 continue;
189 }
190 // Null/absent run id stays eligible; only known rolled_back runs drop.
191 const itemRunId = item.runId;
192 if (itemRunId !== undefined && itemRunId !== null && rolledBackRunIds.has(String(itemRunId))) {
193 continue;
194 }
195
196 const taskId = nativeTaskIdFromTurnItem(item);
197 if (byTaskId.has(taskId)) {
198 continue;
199 }
200
201 const description = descriptionFromTurnItem(item);
202 byTaskId.set(taskId, {
203 taskId,
204 ...(description === undefined ? {} : { description }),
205 taskType: item.type,
206 });
207 }
208
209 return Array.from(byTaskId.values());
210}
211
212export function formatPendingBackgroundWorkLabel(
213 tasks: ReadonlyArray<PendingBackgroundWorkTask>,
214): string | null {
215 if (tasks.length === 0) {
216 return null;
217 }
218 const firstDescription = tasks[0]?.description?.trim();
219 if (tasks.length === 1) {
220 return firstDescription && firstDescription.length > 0
221 ? `Waiting on background task: ${firstDescription}`
222 : "Waiting on a background task";
223 }
224 if (firstDescription && firstDescription.length > 0) {
225 return `Waiting on ${tasks.length} background tasks: ${firstDescription}, …`;
226 }
227 return `Waiting on ${tasks.length} background tasks`;
228}