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