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

SubagentProjection.ts

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