The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { |
| 2 | OrchestrationV2PendingBackgroundTask, |
| 3 | OrchestrationV2ProviderThread, |
| 4 | OrchestrationV2Run, |
| 5 | OrchestrationV2ThreadShell, |
| 6 | OrchestrationV2TurnItem, |
| 7 | ThreadId, |
| 8 | ThreadPullRequestLink, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { isOrchestrationV2WorkActive } from "@t3tools/contracts"; |
| 11 | import * as Predicate from "effect/Predicate"; |
| 12 | |
| 13 | import { resolveT3McpToolId } from "./t3McpToolPresentation.ts"; |
| 14 | |
| 15 | const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([ |
| 16 | "command_execution", |
| 17 | "dynamic_tool", |
| 18 | "subagent", |
| 19 | ]); |
| 20 | |
| 21 | // Plans and text streams can stay open across tool calls without executing work. |
| 22 | const EXECUTION_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([ |
| 23 | ...BACKGROUND_TURN_ITEM_TYPES, |
| 24 | "file_change", |
| 25 | "file_search", |
| 26 | "web_search", |
| 27 | "compaction", |
| 28 | ]); |
| 29 | |
| 30 | const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([ |
| 31 | "cancelled", |
| 32 | "completed", |
| 33 | "failed", |
| 34 | "interrupted", |
| 35 | "rolled_back", |
| 36 | ]); |
| 37 | |
| 38 | // waiting is completed work awaiting checkpoints; exclude rolled_back entirely because provider threads are not run-tied. |
| 39 | const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([ |
| 40 | "cancelled", |
| 41 | "completed", |
| 42 | "failed", |
| 43 | "interrupted", |
| 44 | "waiting", |
| 45 | ]); |
| 46 | |
| 47 | void TERMINAL_RUN_STATUSES; |
| 48 | |
| 49 | export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask; |
| 50 | |
| 51 | export function turnItemUpdateCanEndBackgroundWork( |
| 52 | item: Pick<OrchestrationV2TurnItem, "type" | "status">, |
| 53 | ): boolean { |
| 54 | return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status); |
| 55 | } |
| 56 | |
| 57 | export function deriveBlockedOnThreadWait(input: { |
| 58 | readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null; |
| 59 | readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>; |
| 60 | }): boolean { |
| 61 | if (input.activeRun?.status !== "running") return false; |
| 62 | let hasWait = false; |
| 63 | for (const item of input.turnItems) { |
| 64 | if ( |
| 65 | item.runId !== input.activeRun.id || |
| 66 | !EXECUTION_TURN_ITEM_TYPES.has(item.type) || |
| 67 | (item.status !== "running" && item.status !== "waiting") || |
| 68 | // App-owned rows track the child, including the child a blocking delegate is waiting for. |
| 69 | (item.type === "subagent" && item.origin === "app_owned") |
| 70 | ) { |
| 71 | continue; |
| 72 | } |
| 73 | if (item.type !== "dynamic_tool") return false; |
| 74 | const tool = resolveT3McpToolId(item.toolName); |
| 75 | if ( |
| 76 | tool !== "t3_thread_wait" && |
| 77 | !( |
| 78 | tool === "delegate_task" && |
| 79 | Predicate.isObject(item.input) && |
| 80 | Reflect.get(item.input, "mode") === "wait" |
| 81 | ) |
| 82 | ) { |
| 83 | return false; |
| 84 | } |
| 85 | hasWait = true; |
| 86 | } |
| 87 | return hasWait; |
| 88 | } |
| 89 | |
| 90 | /** A provider instance's background subagent outlives its run and still calls tools. */ |
| 91 | export function hasPendingBackgroundSubagent( |
| 92 | tasks: ReadonlyArray<PendingBackgroundWorkTask> | undefined, |
| 93 | providerInstanceId: OrchestrationV2ProviderThread["providerInstanceId"] | undefined, |
| 94 | ): boolean { |
| 95 | return ( |
| 96 | tasks?.some( |
| 97 | (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId, |
| 98 | ) ?? false |
| 99 | ); |
| 100 | } |
| 101 | |
| 102 | export function backgroundWorkHoldsCompletion( |
| 103 | tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind" | "awaited">>, |
| 104 | ): boolean { |
| 105 | return tasks.some( |
| 106 | (task) => task.awaited === true || backgroundWorkKindHoldsCompletion(task.kind), |
| 107 | ); |
| 108 | } |
| 109 | |
| 110 | // Commands and monitors are as often a dev server or its watchdog as a wait, so they hold |
| 111 | // only when the agent marks them awaited. |
| 112 | function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean { |
| 113 | switch (kind) { |
| 114 | case "command": |
| 115 | case "monitor": |
| 116 | return false; |
| 117 | case "subagent": |
| 118 | case "background_task": |
| 119 | return true; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | const PULL_REQUEST_WATCH_TASK_ID = "pull-request-watch:"; |
| 124 | |
| 125 | export const isPullRequestWatchTask = (task: Pick<PendingBackgroundWorkTask, "taskId">) => |
| 126 | task.taskId.startsWith(PULL_REQUEST_WATCH_TASK_ID); |
| 127 | |
| 128 | /** |
| 129 | * A monitor wakes the agent once per line, so a progress wake run's completion waits for the |
| 130 | * monitor to end. A pull request watch wakes only on news and holds while its checks run. |
| 131 | */ |
| 132 | export function monitorHoldsWakeCompletion( |
| 133 | thread: Pick<OrchestrationV2ThreadShell, "latestRunBackgroundWake" | "pendingBackgroundTasks">, |
| 134 | ): boolean { |
| 135 | return ( |
| 136 | thread.latestRunBackgroundWake === true && |
| 137 | (thread.pendingBackgroundTasks ?? []).some( |
| 138 | (task) => task.kind === "monitor" && !isPullRequestWatchTask(task), |
| 139 | ) |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">; |
| 144 | |
| 145 | type PendingBackgroundWorkPullRequest = Pick< |
| 146 | ThreadPullRequestLink, |
| 147 | "host" | "repository" | "number" | "url" | "source" | "watch" |
| 148 | > & { |
| 149 | readonly snapshot: Pick<NonNullable<ThreadPullRequestLink["snapshot"]>, "state"> | null; |
| 150 | }; |
| 151 | |
| 152 | type PendingBackgroundWorkProviderThread = Pick< |
| 153 | OrchestrationV2ProviderThread, |
| 154 | "id" | "pendingBackgroundTasks" |
| 155 | > & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] }; |
| 156 | |
| 157 | type PendingBackgroundWorkTurnItem = { |
| 158 | readonly id: OrchestrationV2TurnItem["id"] | string; |
| 159 | readonly type: OrchestrationV2TurnItem["type"]; |
| 160 | readonly status: OrchestrationV2TurnItem["status"]; |
| 161 | readonly title: string | null; |
| 162 | /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */ |
| 163 | readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"]; |
| 164 | readonly runId?: OrchestrationV2Run["id"] | string | null; |
| 165 | readonly nativeItemRef?: { |
| 166 | readonly nativeId: string | null; |
| 167 | } | null; |
| 168 | readonly input?: unknown; |
| 169 | readonly monitor?: boolean | undefined; |
| 170 | readonly prompt?: string | undefined; |
| 171 | readonly childThreadId?: ThreadId | null; |
| 172 | }; |
| 173 | |
| 174 | function isLatestRunSettledForBackgroundWait( |
| 175 | latestRun: PendingBackgroundWorkRun | null | undefined, |
| 176 | ): boolean { |
| 177 | if (latestRun === undefined || latestRun === null) { |
| 178 | return false; |
| 179 | } |
| 180 | return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status); |
| 181 | } |
| 182 | |
| 183 | function isPersistentDynamicToolInput(input: unknown): boolean { |
| 184 | if (input === null || typeof input !== "object" || Array.isArray(input)) { |
| 185 | return false; |
| 186 | } |
| 187 | return Reflect.get(input, "persistent") === true; |
| 188 | } |
| 189 | |
| 190 | function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined { |
| 191 | if (typeof item.title === "string" && item.title.trim().length > 0) { |
| 192 | return item.title.trim(); |
| 193 | } |
| 194 | if (item.type === "command_execution" && typeof item.input === "string") { |
| 195 | const command = item.input.trim(); |
| 196 | return command.length > 0 ? command : undefined; |
| 197 | } |
| 198 | if (item.type === "dynamic_tool") { |
| 199 | const toolName = Reflect.get(item, "toolName"); |
| 200 | if (typeof toolName === "string" && toolName.trim().length > 0) { |
| 201 | return toolName.trim(); |
| 202 | } |
| 203 | } |
| 204 | if (item.type === "subagent" && typeof item.prompt === "string") { |
| 205 | const prompt = item.prompt.trim(); |
| 206 | return prompt.length > 0 ? prompt : undefined; |
| 207 | } |
| 208 | return undefined; |
| 209 | } |
| 210 | |
| 211 | function pendingTaskFromTurnItem( |
| 212 | taskId: string, |
| 213 | item: PendingBackgroundWorkTurnItem, |
| 214 | ): PendingBackgroundWorkTask { |
| 215 | const description = descriptionFromTurnItem(item); |
| 216 | const named = { taskId, ...(description === undefined ? {} : { description }) }; |
| 217 | switch (item.type) { |
| 218 | case "subagent": |
| 219 | return { |
| 220 | ...named, |
| 221 | kind: "subagent", |
| 222 | ...(item.owningProviderInstanceId === undefined |
| 223 | ? {} |
| 224 | : { providerInstanceId: item.owningProviderInstanceId }), |
| 225 | ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }), |
| 226 | }; |
| 227 | case "command_execution": |
| 228 | return { ...named, kind: item.monitor === true ? "monitor" : "command" }; |
| 229 | default: |
| 230 | return { ...named, kind: "background_task" }; |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string { |
| 235 | const nativeId = item.nativeItemRef?.nativeId; |
| 236 | if (typeof nativeId === "string" && nativeId.length > 0) { |
| 237 | return nativeId; |
| 238 | } |
| 239 | return String(item.id); |
| 240 | } |
| 241 | |
| 242 | /** Items Stop ends, without the pending list's settled-run gate. */ |
| 243 | export function pendingBackgroundTurnItems<Item extends PendingBackgroundWorkTurnItem>(input: { |
| 244 | readonly turnItems: ReadonlyArray<Item>; |
| 245 | readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>; |
| 246 | }): ReadonlyArray<Item> { |
| 247 | const rolledBackRunIds = new Set( |
| 248 | (input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)), |
| 249 | ); |
| 250 | return input.turnItems.filter( |
| 251 | (item) => |
| 252 | BACKGROUND_TURN_ITEM_TYPES.has(item.type) && |
| 253 | isOrchestrationV2WorkActive(item.status) && |
| 254 | !(item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) && |
| 255 | (item.runId === undefined || |
| 256 | item.runId === null || |
| 257 | !rolledBackRunIds.has(String(item.runId))), |
| 258 | ); |
| 259 | } |
| 260 | |
| 261 | export function derivePendingBackgroundWork(input: { |
| 262 | readonly latestRun: PendingBackgroundWorkRun | null | undefined; |
| 263 | readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>; |
| 264 | readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>; |
| 265 | readonly activeProviderThreadId?: string | null; |
| 266 | readonly hasActiveRun?: boolean; |
| 267 | /** Excludes rolled-back runs; optional only when the caller already filtered them, as SQL shell reads do. */ |
| 268 | readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>; |
| 269 | readonly pullRequests?: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined; |
| 270 | }): ReadonlyArray<PendingBackgroundWorkTask> { |
| 271 | const hasActiveRun = |
| 272 | input.hasActiveRun ?? |
| 273 | input.runs?.some( |
| 274 | (run) => run.status === "preparing" || run.status === "starting" || run.status === "running", |
| 275 | ) ?? |
| 276 | false; |
| 277 | if (hasActiveRun) { |
| 278 | return []; |
| 279 | } |
| 280 | if (input.latestRun == null) { |
| 281 | return pullRequestWatchTasks(input.pullRequests); |
| 282 | } |
| 283 | if (!isLatestRunSettledForBackgroundWait(input.latestRun)) { |
| 284 | return []; |
| 285 | } |
| 286 | |
| 287 | const byTaskId = new Map<string, PendingBackgroundWorkTask>(); |
| 288 | |
| 289 | const providerThreads = |
| 290 | input.activeProviderThreadId === undefined || input.activeProviderThreadId === null |
| 291 | ? input.providerThreads |
| 292 | : input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId); |
| 293 | |
| 294 | for (const providerThread of providerThreads) { |
| 295 | for (const task of providerThread.pendingBackgroundTasks ?? []) { |
| 296 | if (task.taskId.length === 0 || byTaskId.has(task.taskId)) { |
| 297 | continue; |
| 298 | } |
| 299 | const { description: rawDescription, ...named } = task; |
| 300 | const description = rawDescription?.trim(); |
| 301 | byTaskId.set(task.taskId, { |
| 302 | ...named, |
| 303 | ...(task.kind === "subagent" |
| 304 | ? { providerInstanceId: providerThread.providerInstanceId } |
| 305 | : {}), |
| 306 | ...(description === undefined || description.length === 0 ? {} : { description }), |
| 307 | }); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | for (const item of pendingBackgroundTurnItems(input)) { |
| 312 | const taskId = nativeTaskIdFromTurnItem(item); |
| 313 | if (byTaskId.has(taskId)) { |
| 314 | continue; |
| 315 | } |
| 316 | |
| 317 | byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item)); |
| 318 | } |
| 319 | |
| 320 | for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task); |
| 321 | |
| 322 | // Follow-up tasks can share a child thread; the pending list counts agents, not messages. |
| 323 | const childThreadIds = new Set<ThreadId>(); |
| 324 | return Array.from(byTaskId.values()).filter((task) => { |
| 325 | if (task.kind !== "subagent" || task.childThreadId == null) return true; |
| 326 | if (childThreadIds.has(task.childThreadId)) return false; |
| 327 | childThreadIds.add(task.childThreadId); |
| 328 | return true; |
| 329 | }); |
| 330 | } |
| 331 | |
| 332 | function pullRequestWatchTasks( |
| 333 | pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined, |
| 334 | ): Array<PendingBackgroundWorkTask> { |
| 335 | return (pullRequests ?? []).flatMap((link) => |
| 336 | link.watch === undefined || link.source === "stack-dismissed" |
| 337 | ? [] |
| 338 | : [ |
| 339 | { |
| 340 | // Links store their normalized identity, and this id only has to be unique within the |
| 341 | // thread, so it reads those fields instead of parsing the URL. |
| 342 | taskId: `${PULL_REQUEST_WATCH_TASK_ID}${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`, |
| 343 | description: `Watching pull request #${link.number}`, |
| 344 | kind: "monitor" as const, |
| 345 | // Once every check finished, a person moves the PR next: the watch stays on but holds |
| 346 | // nothing, unless the agent said it acts on the PR itself. A merged PR's watch holds |
| 347 | // until its read wakes the agent, so settling on merge waits. |
| 348 | ...(link.watch.checksPending === false && |
| 349 | link.watch.until !== "merged" && |
| 350 | link.snapshot?.state !== "merged" |
| 351 | ? {} |
| 352 | : { awaited: true as const }), |
| 353 | }, |
| 354 | ], |
| 355 | ); |
| 356 | } |