Open History to see the last commit
1import type {
2 EventId,
3 MessageId,
4 ModelSelection,
5 NodeId,
6 OrchestrationV2AppThread,
7 OrchestrationV2Actor,
8 OrchestrationV2ConversationMessage,
9 OrchestrationV2CreationSource,
10 OrchestrationV2DomainEvent,
11 OrchestrationV2ProviderRef,
12 OrchestrationV2Run,
13 OrchestrationV2ThreadProjection,
14 OrchestrationV2TurnItem,
15 ProviderInstanceId,
16 ProviderThreadId,
17 ProviderTurnId,
18 ThreadId,
19 TurnItemId,
20} from "@t3tools/contracts";
21import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
25
26function trimmed(value: string | null | undefined): string | undefined {
27 const result = value?.trim();
28 return result && result.length > 0 ? result : undefined;
29}
30
31export function subagentThreadTitle(input: {
32 readonly parentTitle: string;
33 readonly title?: string | null;
34 readonly prompt: string;
35 readonly ordinal: number;
36}): string {
37 const detail = trimmed(input.title) ?? trimmed(input.prompt);
38 if (detail === undefined) {
39 return `${input.parentTitle} subagent ${input.ordinal}`;
40 }
41 const clipped = detail.length > 72 ? `${detail.slice(0, 69)}...` : detail;
42 return clipped;
43}
44
45export function makeSubagentChildThread(input: {
46 readonly parentThread: OrchestrationV2AppThread;
47 readonly childThreadId: ThreadId;
48 readonly parentNodeId: NodeId;
49 readonly activeProviderThreadId: ProviderThreadId | null;
50 readonly providerInstanceId: ProviderInstanceId;
51 readonly modelSelection: ModelSelection;
52 readonly title: string;
53 readonly now: DateTime.Utc;
54 readonly createdBy: OrchestrationV2Actor;
55 readonly creationSource: OrchestrationV2CreationSource;
56}): OrchestrationV2AppThread {
57 return {
58 ...input.parentThread,
59 createdBy: input.createdBy,
60 creationSource: input.creationSource,
61 id: input.childThreadId,
62 title: input.title,
63 linkedPullRequest: null,
64 pullRequests: [],
65 historyOrigin: undefined,
66 providerInstanceId: input.providerInstanceId,
67 modelSelection: input.modelSelection,
68 activeProviderThreadId: input.activeProviderThreadId,
69 lineage: {
70 parentThreadId: input.parentThread.id,
71 relationshipToParent: "subagent",
72 rootThreadId: input.parentThread.lineage.rootThreadId,
73 },
74 forkedFrom: {
75 type: "node",
76 nodeId: input.parentNodeId,
77 },
78 createdAt: input.now,
79 updatedAt: input.now,
80 archivedAt: null,
81 settledOverride: null,
82 settledAt: null,
83 snoozedUntil: null,
84 snoozedAt: null,
85 lastVisitedAt: null,
86 deletedAt: null,
87 };
88}
89
90export function makeSubagentConversationArtifacts(input: {
91 readonly messageId: MessageId;
92 readonly senderThreadId?: ThreadId;
93 readonly turnItemId: TurnItemId;
94 readonly threadId: ThreadId;
95 readonly rootNodeId: NodeId;
96 readonly providerThreadId: ProviderThreadId | null;
97 readonly providerTurnId: ProviderTurnId | null;
98 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
99 readonly role: "user" | "assistant";
100 readonly text: string;
101 /** Whether a user message is the script a workflow run executes; unset for older callers. */
102 readonly workflowScript?: boolean;
103 readonly ordinal: number;
104 readonly now: DateTime.Utc;
105}): {
106 readonly message: OrchestrationV2ConversationMessage;
107 readonly turnItem: OrchestrationV2TurnItem;
108} {
109 const message: OrchestrationV2ConversationMessage = {
110 createdBy: "agent",
111 creationSource: "provider",
112 id: input.messageId,
113 threadId: input.threadId,
114 runId: null,
115 nodeId: input.rootNodeId,
116 role: input.role,
117 ...(input.role === "user" && input.senderThreadId !== undefined
118 ? { senderThreadId: input.senderThreadId }
119 : {}),
120 ...(input.role === "user" && input.workflowScript !== undefined
121 ? { workflowScript: input.workflowScript }
122 : {}),
123 text: input.text,
124 attachments: [],
125 streaming: false,
126 createdAt: input.now,
127 updatedAt: input.now,
128 };
129 const base = {
130 id: input.turnItemId,
131 threadId: input.threadId,
132 runId: null,
133 nodeId: input.rootNodeId,
134 providerThreadId: input.providerThreadId,
135 providerTurnId: input.providerTurnId,
136 nativeItemRef: input.nativeItemRef,
137 parentItemId: null,
138 ordinal: input.ordinal,
139 status: "completed" as const,
140 title: null,
141 startedAt: input.now,
142 completedAt: input.now,
143 updatedAt: input.now,
144 messageId: input.messageId,
145 text: input.text,
146 };
147 const turnItem: OrchestrationV2TurnItem =
148 input.role === "user"
149 ? {
150 ...base,
151 createdBy: "agent",
152 creationSource: "provider",
153 type: "user_message",
154 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
155 ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
156 inputIntent: "turn_start",
157 attachments: [],
158 }
159 : {
160 ...base,
161 type: "assistant_message",
162 streaming: false,
163 };
164 return { message, turnItem };
165}
166
167export function subagentResultForRun(
168 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems">,
169 run: OrchestrationV2Run,
170): {
171 readonly text: string;
172 readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
173 readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
174} {
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 messages = projection.messages.filter(
187 (candidate) =>
188 candidate.runId === run.id &&
189 candidate.role === "assistant" &&
190 candidate.text.trim().length > 0,
191 );
192 // Turn item order is authoritative: providers can finalize every message of a turn at once,
193 // so message timestamps can tie. They only order messages that have no turn item.
194 const message =
195 messages.find((candidate) => candidate.id === turnItem?.messageId) ??
196 messages.toSorted(
197 (left, right) =>
198 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
199 DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
200 )[0] ??
201 null;
202 const failure =
203 run.status === "failed"
204 ? projection.turnItems
205 .filter((item) => item.runId === run.id && item.type === "error")
206 .toSorted((left, right) => right.ordinal - left.ordinal)[0]
207 : undefined;
208 const text =
209 (failure?.type === "error" ? failure.failure.message : undefined) ??
210 message?.text ??
211 turnItem?.text ??
212 (run.status === "completed"
213 ? "Child task completed without an assistant result."
214 : `Child task ended with status ${run.status}.`);
215 return {
216 text,
217 messageId: failure === undefined ? (message?.id ?? turnItem?.messageId ?? null) : null,
218 turnItemId: failure?.id ?? turnItem?.id ?? null,
219 };
220}
221
222export function delegatedTaskProgress(projection: {
223 readonly runs: OrchestrationV2ThreadProjection["runs"];
224 readonly messages: ReadonlyArray<
225 Pick<OrchestrationV2ConversationMessage, "runId" | "notification">
226 >;
227 readonly subagents: ReadonlyArray<
228 Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">
229 >;
230 readonly providerThreads: ReadonlyArray<
231 Pick<OrchestrationV2ThreadProjection["providerThreads"][number], "pendingBackgroundTasks">
232 >;
233}) {
234 const terminal = (status: string) =>
235 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(status);
236 const monitorRuns = new Set(
237 projection.messages
238 .filter((message) => message.notification?.source.kind === "monitor")
239 .map((message) => message.runId),
240 );
241 const workRuns = projection.runs.filter(
242 (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back",
243 );
244 const active = workRuns.some(
245 (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true),
246 );
247 const children =
248 projection.subagents.some(
249 (task) =>
250 isOrchestrationV2WorkActive(task.status) ||
251 // Publishing a child's result precedes scheduling its parent's wake.
252 // The parent still owes that follow-up even between those transactions.
253 (task.status !== "idle" &&
254 (task.completionDelivery?.state === "pending" ||
255 task.completionDelivery?.state === "claimed")),
256 ) ||
257 projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
258 const resultRun = workRuns
259 .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1))
260 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0];
261 return {
262 state:
263 active || resultRun === undefined
264 ? ("working" as const)
265 : children
266 ? ("waiting_for_children" as const)
267 : ("result_available" as const),
268 resultRun,
269 };
270}
271
272function writtenIds(
273 emitted: ReadonlyArray<OrchestrationV2DomainEvent>,
274 type: "subagent.updated" | "node.updated" | "turn-item.updated",
275): ReadonlySet<string> {
276 return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));
277}
278
279export const endOrphanedNativeSubagent = Effect.fn("subagentProjection.endOrphanedNativeSubagent")(
280 function* <E>(input: {
281 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
282 readonly subagentId: NodeId;
283 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
284 readonly completedAt?: DateTime.Utc;
285 readonly result?: string | null;
286 readonly now: DateTime.Utc;
287 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
288 readonly allocateEventId: () => Effect.Effect<EventId, E>;
289 }) {
290 const { now, status, subagentId, completedAt = now } = input;
291 const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);
292 if (subagent?.origin !== "provider_native") return [];
293 const node = input.projection.nodes.find((entry) => entry.id === subagentId);
294 const item = input.projection.turnItems.find(
295 (entry) => entry.type === "subagent" && entry.subagentId === subagentId,
296 );
297 const scope = {
298 threadId: subagent.threadId,
299 ...(subagent.runId === null ? {} : { runId: subagent.runId }),
300 nodeId: subagentId,
301 providerInstanceId: subagent.providerInstanceId,
302 occurredAt: now,
303 };
304 const events: Array<OrchestrationV2DomainEvent> = [];
305 if (
306 isOrchestrationV2WorkActive(subagent.status) &&
307 !writtenIds(input.emitted, "subagent.updated").has(subagentId)
308 ) {
309 events.push({
310 ...scope,
311 id: yield* input.allocateEventId(),
312 type: "subagent.updated",
313 driver: subagent.driver,
314 payload: {
315 ...subagent,
316 status,
317 completedAt,
318 updatedAt: now,
319 ...(input.result === undefined ? {} : { result: input.result }),
320 },
321 });
322 }
323 if (
324 node !== undefined &&
325 isOrchestrationV2WorkActive(node.status) &&
326 !writtenIds(input.emitted, "node.updated").has(subagentId)
327 ) {
328 events.push({
329 ...scope,
330 id: yield* input.allocateEventId(),
331 type: "node.updated",
332 payload: { ...node, status, completedAt },
333 });
334 }
335 if (
336 item !== undefined &&
337 isOrchestrationV2WorkActive(item.status) &&
338 !writtenIds(input.emitted, "turn-item.updated").has(item.id)
339 ) {
340 events.push({
341 ...scope,
342 id: yield* input.allocateEventId(),
343 type: "turn-item.updated",
344 payload: {
345 ...item,
346 status,
347 completedAt,
348 updatedAt: now,
349 ...(input.result === undefined ? {} : { result: input.result }),
350 },
351 });
352 }
353 return events;
354 },
355);
356
357export const endRunlessRootTurns = Effect.fn("subagentProjection.endRunlessRootTurns")(function* <
358 E,
359>(input: {
360 readonly threadId: ThreadId;
361 readonly providerInstanceId: ProviderInstanceId;
362 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "turnItems">;
363 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
364 readonly completedAt?: DateTime.Utc;
365 readonly now: DateTime.Utc;
366 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
367 readonly allocateEventId: () => Effect.Effect<EventId, E>;
368}) {
369 const { now, status, completedAt = now } = input;
370 const endedNodeIds = writtenIds(input.emitted, "node.updated");
371 const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
372 const scope = {
373 threadId: input.threadId,
374 providerInstanceId: input.providerInstanceId,
375 occurredAt: now,
376 };
377 const events: Array<OrchestrationV2DomainEvent> = [];
378 for (const node of input.projection.nodes) {
379 if (
380 node.kind !== "root_turn" ||
381 node.runId !== null ||
382 !isOrchestrationV2WorkActive(node.status)
383 ) {
384 continue;
385 }
386 if (!endedNodeIds.has(node.id)) {
387 events.push({
388 ...scope,
389 id: yield* input.allocateEventId(),
390 type: "node.updated",
391 nodeId: node.id,
392 payload: { ...node, status, completedAt },
393 });
394 }
395 for (const item of input.projection.turnItems) {
396 if (
397 item.nodeId !== node.id ||
398 item.runId !== null ||
399 !isOrchestrationV2WorkActive(item.status) ||
400 endedItemIds.has(item.id)
401 ) {
402 continue;
403 }
404 events.push({
405 ...scope,
406 id: yield* input.allocateEventId(),
407 type: "turn-item.updated",
408 nodeId: node.id,
409 payload: {
410 ...item,
411 status:
412 status === "completed" &&
413 (item.type === "command_execution" || item.type === "dynamic_tool")
414 ? "failed"
415 : status,
416 completedAt,
417 updatedAt: now,
418 ...(item.type === "reasoning" || item.type === "assistant_message"
419 ? { streaming: false }
420 : {}),
421 },
422 });
423 }
424 }
425 return events;
426});