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

SubagentProjection.ts

259 lines8.5 KB

1import type {
2 MessageId,
3 ModelSelection,
4 NodeId,
5 OrchestrationV2AppThread,
6 OrchestrationV2Actor,
7 OrchestrationV2ConversationMessage,
8 OrchestrationV2CreationSource,
9 OrchestrationV2ProviderRef,
10 OrchestrationV2Run,
11 OrchestrationV2ThreadProjection,
12 OrchestrationV2TurnItem,
13 ProviderInstanceId,
14 ProviderThreadId,
15 ProviderTurnId,
16 ThreadId,
17 TurnItemId,
18} from "@t3tools/contracts";
19import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
20import * as DateTime from "effect/DateTime";
21import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
22​
23function trimmed(value: string | null | undefined): string | undefined {
24 const result = value?.trim();
25 return result && result.length > 0 ? result : undefined;
27​
28export function subagentThreadTitle(input: {
29 readonly parentTitle: string;
30 readonly title?: string | null;
31 readonly prompt: string;
32 readonly ordinal: number;
33}): string {
34 const detail = trimmed(input.title) ?? trimmed(input.prompt);
35 if (detail === undefined) {
36 return `${input.parentTitle} subagent ${input.ordinal}`;
37 }
38 const clipped = detail.length > 72 ? `${detail.slice(0, 69)}...` : detail;
39 return clipped;
41​
42export function makeSubagentChildThread(input: {
43 readonly parentThread: OrchestrationV2AppThread;
44 readonly childThreadId: ThreadId;
45 readonly parentNodeId: NodeId;
46 readonly activeProviderThreadId: ProviderThreadId | null;
47 readonly providerInstanceId: ProviderInstanceId;
48 readonly modelSelection: ModelSelection;
49 readonly title: string;
50 readonly now: DateTime.Utc;
51 readonly createdBy: OrchestrationV2Actor;
52 readonly creationSource: OrchestrationV2CreationSource;
53}): OrchestrationV2AppThread {
54 return {
55 ...input.parentThread,
56 createdBy: input.createdBy,
57 creationSource: input.creationSource,
58 id: input.childThreadId,
59 title: input.title,
60 linkedPullRequest: null,
61 pullRequests: [],
62 historyOrigin: undefined,
63 providerInstanceId: input.providerInstanceId,
64 modelSelection: input.modelSelection,
65 activeProviderThreadId: input.activeProviderThreadId,
66 lineage: {
67 parentThreadId: input.parentThread.id,
68 relationshipToParent: "subagent",
69 rootThreadId: input.parentThread.lineage.rootThreadId,
70 },
71 forkedFrom: {
72 type: "node",
73 nodeId: input.parentNodeId,
74 },
75 createdAt: input.now,
76 updatedAt: input.now,
77 archivedAt: null,
78 settledOverride: null,
79 settledAt: null,
80 snoozedUntil: null,
81 snoozedAt: null,
82 lastVisitedAt: null,
83 deletedAt: null,
84 };
86​
87export function makeSubagentConversationArtifacts(input: {
88 readonly messageId: MessageId;
89 readonly senderThreadId?: ThreadId;
90 readonly turnItemId: TurnItemId;
91 readonly threadId: ThreadId;
92 readonly rootNodeId: NodeId;
93 readonly providerThreadId: ProviderThreadId | null;
94 readonly providerTurnId: ProviderTurnId | null;
95 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
96 readonly role: "user" | "assistant";
97 readonly text: string;
98 readonly ordinal: number;
99 readonly now: DateTime.Utc;
100}): {
101 readonly message: OrchestrationV2ConversationMessage;
102 readonly turnItem: OrchestrationV2TurnItem;
103} {
104 const message: OrchestrationV2ConversationMessage = {
105 createdBy: "agent",
106 creationSource: "provider",
107 id: input.messageId,
108 threadId: input.threadId,
109 runId: null,
110 nodeId: input.rootNodeId,
111 role: input.role,
112 ...(input.role === "user" && input.senderThreadId !== undefined
113 ? { senderThreadId: input.senderThreadId }
114 : {}),
115 text: input.text,
116 attachments: [],
117 streaming: false,
118 createdAt: input.now,
119 updatedAt: input.now,
120 };
121 const base = {
122 id: input.turnItemId,
123 threadId: input.threadId,
124 runId: null,
125 nodeId: input.rootNodeId,
126 providerThreadId: input.providerThreadId,
127 providerTurnId: input.providerTurnId,
128 nativeItemRef: input.nativeItemRef,
129 parentItemId: null,
130 ordinal: input.ordinal,
131 status: "completed" as const,
132 title: null,
133 startedAt: input.now,
134 completedAt: input.now,
135 updatedAt: input.now,
136 messageId: input.messageId,
137 text: input.text,
138 };
139 const turnItem: OrchestrationV2TurnItem =
140 input.role === "user"
141 ? {
142 ...base,
143 createdBy: "agent",
144 creationSource: "provider",
145 type: "user_message",
146 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
147 inputIntent: "turn_start",
148 attachments: [],
149 }
150 : {
151 ...base,
152 type: "assistant_message",
153 streaming: false,
154 };
155 return { message, turnItem };
157​
158export function subagentResultForRun(
159 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems">,
160 run: OrchestrationV2Run,
161): {
162 readonly text: string;
163 readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
164 readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
165} {
166 const message =
167 projection.messages
168 .filter(
169 (candidate) =>
170 candidate.runId === run.id &&
171 candidate.role === "assistant" &&
172 candidate.text.trim().length > 0,
173 )
174 .toSorted(
175 (left, right) =>
176 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
177 )[0] ?? null;
178 const turnItem =
179 projection.turnItems
180 .filter(
181 (
182 candidate,
183 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "assistant_message" }> =>
184 candidate.runId === run.id &&
185 candidate.type === "assistant_message" &&
186 candidate.text.trim().length > 0,
187 )
188 .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
189 const failure =
190 run.status === "failed"
191 ? projection.turnItems
192 .filter((item) => item.runId === run.id && item.type === "error")
193 .toSorted((left, right) => right.ordinal - left.ordinal)[0]
194 : undefined;
195 const text =
196 (failure?.type === "error" ? failure.failure.message : undefined) ??
197 message?.text ??
198 turnItem?.text ??
199 (run.status === "completed"
200 ? "Child task completed without an assistant result."
201 : `Child task ended with status ${run.status}.`);
202 return {
203 text,
204 messageId: failure === undefined ? (message?.id ?? turnItem?.messageId ?? null) : null,
205 turnItemId: failure?.id ?? turnItem?.id ?? null,
206 };
208​
209/** A finished turn can still own live children or queued completion follow-ups. */
210export function delegatedTaskProgress(projection: {
211 readonly runs: OrchestrationV2ThreadProjection["runs"];
212 readonly messages: ReadonlyArray<
213 Pick<OrchestrationV2ConversationMessage, "runId" | "notification">
214 >;
215 readonly subagents: ReadonlyArray<
216 Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">
217 >;
218 readonly providerThreads: ReadonlyArray<
219 Pick<OrchestrationV2ThreadProjection["providerThreads"][number], "pendingBackgroundTasks">
220 >;
221}) {
222 const terminal = (status: string) =>
223 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(status);
224 const monitorRuns = new Set(
225 projection.messages
226 .filter((message) => message.notification?.source.kind === "monitor")
227 .map((message) => message.runId),
228 );
229 const workRuns = projection.runs.filter(
230 (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back",
231 );
232 // A held queue waits for the user to resume it (after Stop, a restart, or a
233 // provider failure), so its runs are not work the task still owes.
234 const active = workRuns.some(
235 (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true),
236 );
237 const children =
238 projection.subagents.some(
239 (task) =>
240 isOrchestrationV2WorkActive(task.status) ||
241 // Publishing a child's result precedes scheduling its parent's wake.
242 // The parent still owes that follow-up even between those transactions.
243 task.completionDelivery?.state === "pending" ||
244 task.completionDelivery?.state === "claimed",
245 ) ||
246 projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
247 const resultRun = workRuns
248 .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1))
249 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0];
250 return {
251 state:
252 active || resultRun === undefined
253 ? ("working" as const)
254 : children
255 ? ("waiting_for_children" as const)
256 : ("result_available" as const),
257 resultRun,
258 };