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