Open History to see the last commit
1import {
2 isListedThreadLineage,
3 type EnvironmentId,
4 isProviderNativeSubagentThread,
5 type OrchestrationV2ThreadShell,
6 type Project,
7 type RuntimeRequestId,
8 type ThreadId,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11
12import {
13 backgroundWorkHoldsCompletion,
14 monitorHoldsWakeCompletion,
15} from "./orchestrationV2PendingBackgroundWork.ts";
16
17export type AgentAwarenessPhase =
18 | "starting"
19 | "running"
20 | "waiting_for_approval"
21 | "waiting_for_input"
22 | "completed"
23 | "failed"
24 | "stale";
25
26export interface SubagentRequestAwareness {
27 readonly requestId: RuntimeRequestId;
28 /** The child's own update time, which moves whenever its request changes. */
29 readonly updatedAt: DateTime.Utc;
30}
31
32/** Provider-native subagents ask on their parent; the coordinator answers child questions. */
33export function subagentAwaitsApproval(
34 thread: Pick<
35 OrchestrationV2ThreadShell,
36 "activityRunStatus" | "creationSource" | "lineage" | "pendingRuntimeRequest"
37 >,
38): boolean {
39 const kind = thread.pendingRuntimeRequest?.kind;
40 return (
41 kind !== undefined &&
42 kind !== "auth_refresh" &&
43 kind !== "user_input" &&
44 thread.lineage.relationshipToParent === "subagent" &&
45 !isProviderNativeSubagentThread(thread) &&
46 // The activity run stays set when a follow-up is queued behind a blocked run.
47 thread.activityRunStatus != null
48 );
49}
50
51export interface AgentAwarenessState {
52 readonly environmentId: EnvironmentId;
53 readonly threadId: ThreadId;
54 readonly projectTitle: string;
55 readonly threadTitle: string;
56 readonly phase: AgentAwarenessPhase;
57 readonly headline: string;
58 readonly detail?: string;
59 readonly modelTitle: string;
60 readonly updatedAt: string;
61 readonly deepLink: string;
62}
63
64function buildAgentAwarenessDeepLink(input: {
65 readonly environmentId: EnvironmentId;
66 readonly threadId: ThreadId;
67}): string {
68 return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;
69}
70
71export interface ProjectThreadAwarenessV2Input {
72 readonly environmentId: EnvironmentId;
73 readonly project: Pick<Project, "title">;
74 readonly thread: Pick<
75 OrchestrationV2ThreadShell,
76 | "activityRunStatus"
77 | "id"
78 | "lineage"
79 | "latestRunBackgroundWake"
80 | "latestRunStopRequested"
81 | "modelSelection"
82 | "pendingBackgroundTasks"
83 | "pendingRuntimeRequest"
84 | "settledOverride"
85 | "status"
86 | "title"
87 | "updatedAt"
88 >;
89 /** The approval a live subagent below this thread is waiting on. */
90 readonly pendingSubagentRequest?: SubagentRequestAwareness | null;
91}
92
93export function projectThreadAwarenessV2(
94 input: ProjectThreadAwarenessV2Input,
95): AgentAwarenessState | null {
96 const { environmentId, project, thread } = input;
97 if (!isListedThreadLineage(thread.lineage)) return null;
98 const subagentRequest = input.pendingSubagentRequest ?? null;
99 const phase = resolveThreadAwarenessPhaseV2(thread, subagentRequest !== null);
100 if (phase === null) {
101 return null;
102 }
103 if (phase === "completed" && thread.latestRunStopRequested === true) return null;
104 // Resolve the phase first so live or waiting work stays visible after settlement.
105 const runStatus = thread.activityRunStatus ?? thread.status;
106 if (
107 thread.settledOverride === "settled" &&
108 (phase === "completed" ||
109 phase === "failed" ||
110 (phase === "running" && runStatus === "completed")) &&
111 !backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
112 ) {
113 return null;
114 }
115 const detail =
116 phase === "completed"
117 ? "Review the completed task."
118 : phase === "failed"
119 ? "The agent run failed."
120 : undefined;
121 return {
122 environmentId,
123 threadId: thread.id,
124 projectTitle: project.title,
125 threadTitle: thread.title,
126 phase,
127 headline: headlineForPhase(phase),
128 ...(detail === undefined ? {} : { detail }),
129 modelTitle: thread.modelSelection.model,
130 // A child's request leaves the parent's own timestamp alone. Alerts are
131 // keyed by phase and time, so a second wait needs the child's time.
132 updatedAt: DateTime.formatIso(
133 subagentRequest === null
134 ? thread.updatedAt
135 : DateTime.max(thread.updatedAt, subagentRequest.updatedAt),
136 ),
137 deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),
138 };
139}
140
141function resolveThreadAwarenessPhaseV2(
142 thread: ProjectThreadAwarenessV2Input["thread"],
143 childAwaitsApproval: boolean,
144): AgentAwarenessPhase | null {
145 if (thread.pendingRuntimeRequest?.kind === "user_input") return "waiting_for_input";
146 if (
147 thread.pendingRuntimeRequest !== null &&
148 thread.pendingRuntimeRequest.kind !== "auth_refresh"
149 ) {
150 return "waiting_for_approval";
151 }
152 // The parent can finish its own turn while a delegated child keeps working,
153 // so a child's request outranks the parent's run status.
154 if (childAwaitsApproval) return "waiting_for_approval";
155 switch (thread.activityRunStatus ?? thread.status) {
156 case "preparing":
157 case "starting":
158 return "starting";
159 case "running":
160 case "waiting":
161 return "running";
162 case "completed":
163 return backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) ||
164 monitorHoldsWakeCompletion(thread)
165 ? "running"
166 : "completed";
167 case "failed":
168 return "failed";
169 case "idle":
170 case "queued":
171 case "interrupted":
172 case "cancelled":
173 case "rolled_back":
174 return null;
175 }
176}
177
178function headlineForPhase(phase: AgentAwarenessPhase): string {
179 switch (phase) {
180 case "starting":
181 return "Starting agent";
182 case "running":
183 return "Agent is working";
184 case "waiting_for_approval":
185 return "Approval needed";
186 case "waiting_for_input":
187 return "Waiting for input";
188 case "completed":
189 return "Agent finished";
190 case "failed":
191 return "Agent failed";
192 case "stale":
193 return "Update delayed";
194 }
195}