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