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

agentAwareness.ts

215 lines6.8 KB

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 /** A card only the user can answer, rather than an approval. */
31 readonly waitsForInput?: boolean;
33​
34/**
35 * Turn items that can start or end a subagent's user-only wait: its secret or link card,
36 * or a user message that moves past a link card. Filters that drop subagent transcript
37 * updates must keep these, or the parent's "Input needed" never appears or never clears.
38 */
39export const turnItemCanChangeUserWait = (item: { readonly type: string }) =>
40 item.type === "secret_request" || item.type === "link_request" || item.type === "user_message";
41​
42/**
43 * Provider-native subagents ask on their parent. The coordinator answers child questions,
44 * but not a card only the user can answer, such as a secret.
45 */
46export function subagentAwaitsUser(
47 thread: Pick<
48 OrchestrationV2ThreadShell,
49 "activityRunStatus" | "creationSource" | "lineage" | "pendingRuntimeRequest"
50 >,
51): boolean {
52 const kind = thread.pendingRuntimeRequest?.kind;
53 return (
54 kind !== undefined &&
55 kind !== "auth_refresh" &&
56 (kind !== "user_input" || thread.pendingRuntimeRequest?.userOnly === true) &&
57 thread.lineage.relationshipToParent === "subagent" &&
58 !isProviderNativeSubagentThread(thread) &&
59 // The activity run stays set when a follow-up is queued behind a blocked run.
60 thread.activityRunStatus != null
61 );
63​
64export interface AgentAwarenessState {
65 readonly environmentId: EnvironmentId;
66 readonly threadId: ThreadId;
67 readonly projectTitle: string;
68 readonly threadTitle: string;
69 readonly phase: AgentAwarenessPhase;
70 readonly headline: string;
71 readonly detail?: string;
72 readonly modelTitle: string;
73 readonly updatedAt: string;
74 readonly deepLink: string;
76​
77function buildAgentAwarenessDeepLink(input: {
78 readonly environmentId: EnvironmentId;
79 readonly threadId: ThreadId;
80}): string {
81 return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;
83​
84export interface ProjectThreadAwarenessV2Input {
85 readonly environmentId: EnvironmentId;
86 readonly project: Pick<Project, "title">;
87 readonly thread: Pick<
88 OrchestrationV2ThreadShell,
89 | "activityRunStatus"
90 | "delegatedFrom"
91 | "id"
92 | "lineage"
93 | "latestRunBackgroundWake"
94 | "latestRunStopRequested"
95 | "modelSelection"
96 | "pendingBackgroundTasks"
97 | "pendingRuntimeRequest"
98 | "settledOverride"
99 | "status"
100 | "title"
101 | "updatedAt"
102 >;
103 /** What a live subagent below this thread is waiting on the user for. */
104 readonly pendingSubagentRequest?: SubagentRequestAwareness | null;
106​
107export function projectThreadAwarenessV2(
108 input: ProjectThreadAwarenessV2Input,
109): AgentAwarenessState | null {
110 const { environmentId, project, thread } = input;
111 if (!isListedThreadLineage(thread.lineage)) return null;
112 const subagentRequest = input.pendingSubagentRequest ?? null;
113 const phase = resolveThreadAwarenessPhaseV2(thread, subagentRequest);
114 if (phase === null) {
115 return null;
116 }
117 if (phase === "completed" && thread.latestRunStopRequested === true) return null;
118 // Like a local subagent's, a linked environment's task outcome reaches the user through its parent.
119 if (thread.delegatedFrom != null && (phase === "completed" || phase === "failed")) {
120 return null;
121 }
122 // Resolve the phase first so live or waiting work stays visible after settlement.
123 const runStatus = thread.activityRunStatus ?? thread.status;
124 if (
125 thread.settledOverride === "settled" &&
126 (phase === "completed" ||
127 phase === "failed" ||
128 (phase === "running" && runStatus === "completed")) &&
129 !backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
130 ) {
131 return null;
132 }
133 const detail =
134 phase === "completed"
135 ? "Review the completed task."
136 : phase === "failed"
137 ? "The agent run failed."
138 : undefined;
139 return {
140 environmentId,
141 threadId: thread.id,
142 projectTitle: project.title,
143 threadTitle: thread.title,
144 phase,
145 headline: headlineForPhase(phase),
146 ...(detail === undefined ? {} : { detail }),
147 modelTitle: thread.modelSelection.model,
148 // A child's request leaves the parent's own timestamp alone. Alerts are
149 // keyed by phase and time, so a second wait needs the child's time.
150 updatedAt: DateTime.formatIso(
151 subagentRequest === null
152 ? thread.updatedAt
153 : DateTime.max(thread.updatedAt, subagentRequest.updatedAt),
154 ),
155 deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),
156 };
158​
159function resolveThreadAwarenessPhaseV2(
160 thread: ProjectThreadAwarenessV2Input["thread"],
161 subagentRequest: SubagentRequestAwareness | null,
162): AgentAwarenessPhase | null {
163 if (thread.pendingRuntimeRequest?.kind === "user_input") return "waiting_for_input";
164 if (
165 thread.pendingRuntimeRequest !== null &&
166 thread.pendingRuntimeRequest.kind !== "auth_refresh"
167 ) {
168 return "waiting_for_approval";
169 }
170 // The parent can finish its own turn while a delegated child keeps working,
171 // so a child's request outranks the parent's run status.
172 if (subagentRequest !== null) {
173 return subagentRequest.waitsForInput === true ? "waiting_for_input" : "waiting_for_approval";
174 }
175 switch (thread.activityRunStatus ?? thread.status) {
176 case "preparing":
177 case "starting":
178 return "starting";
179 case "running":
180 case "waiting":
181 return "running";
182 case "completed":
183 return backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) ||
184 monitorHoldsWakeCompletion(thread)
185 ? "running"
186 : "completed";
187 case "failed":
188 return "failed";
189 case "idle":
190 case "queued":
191 case "interrupted":
192 case "cancelled":
193 case "rolled_back":
194 return null;
195 }
197​
198function headlineForPhase(phase: AgentAwarenessPhase): string {
199 switch (phase) {
200 case "starting":
201 return "Starting agent";
202 case "running":
203 return "Agent is working";
204 case "waiting_for_approval":
205 return "Approval needed";
206 case "waiting_for_input":
207 return "Waiting for input";
208 case "completed":
209 return "Agent finished";
210 case "failed":
211 return "Agent failed";
212 case "stale":
213 return "Update delayed";
214 }