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

subagentProjection.ts

450 lines14.7 KB

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;
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;
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 pinnedAt: null,
86 pinOrderKey: null,
87 autoSettleDisabledAt: null,
88 // A guest link belongs to the thread it was made for.
89 guestShare: null,
90 lastVisitedAt: null,
91 deletedAt: null,
92 };
94​
95export function makeSubagentConversationArtifacts(input: {
96 readonly messageId: MessageId;
97 readonly senderThreadId?: ThreadId;
98 readonly turnItemId: TurnItemId;
99 readonly threadId: ThreadId;
100 readonly rootNodeId: NodeId;
101 readonly providerThreadId: ProviderThreadId | null;
102 readonly providerTurnId: ProviderTurnId | null;
103 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
104 readonly role: "user" | "assistant";
105 readonly text: string;
106 readonly workflowScript?: boolean;
107 readonly ordinal: number;
108 readonly now: DateTime.Utc;
109}): {
110 readonly message: OrchestrationV2ConversationMessage;
111 readonly turnItem: OrchestrationV2TurnItem;
112} {
113 const message: OrchestrationV2ConversationMessage = {
114 createdBy: "agent",
115 creationSource: "provider",
116 id: input.messageId,
117 threadId: input.threadId,
118 runId: null,
119 nodeId: input.rootNodeId,
120 role: input.role,
121 ...(input.role === "user" && input.senderThreadId !== undefined
122 ? { senderThreadId: input.senderThreadId }
123 : {}),
124 ...(input.role === "user" && input.workflowScript !== undefined
125 ? { workflowScript: input.workflowScript }
126 : {}),
127 text: input.text,
128 attachments: [],
129 streaming: false,
130 createdAt: input.now,
131 updatedAt: input.now,
132 };
133 const base = {
134 id: input.turnItemId,
135 threadId: input.threadId,
136 runId: null,
137 nodeId: input.rootNodeId,
138 providerThreadId: input.providerThreadId,
139 providerTurnId: input.providerTurnId,
140 nativeItemRef: input.nativeItemRef,
141 parentItemId: null,
142 ordinal: input.ordinal,
143 status: "completed" as const,
144 title: null,
145 startedAt: input.now,
146 completedAt: input.now,
147 updatedAt: input.now,
148 messageId: input.messageId,
149 text: input.text,
150 };
151 const turnItem: OrchestrationV2TurnItem =
152 input.role === "user"
153 ? {
154 ...base,
155 createdBy: "agent",
156 creationSource: "provider",
157 type: "user_message",
158 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
159 ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
160 inputIntent: "turn_start",
161 attachments: [],
162 }
163 : {
164 ...base,
165 type: "assistant_message",
166 streaming: false,
167 };
168 return { message, turnItem };
170​
171export function subagentResultForRun(
172 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems">,
173 run: OrchestrationV2Run,
174): {
175 readonly text: string;
176 readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
177 readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
178} {
179 const turnItem =
180 projection.turnItems
181 .filter(
182 (
183 candidate,
184 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "assistant_message" }> =>
185 candidate.runId === run.id &&
186 candidate.type === "assistant_message" &&
187 candidate.text.trim().length > 0,
188 )
189 .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
190 const messages = projection.messages.filter(
191 (candidate) =>
192 candidate.runId === run.id &&
193 candidate.role === "assistant" &&
194 candidate.text.trim().length > 0,
195 );
196 // Prefer turn item order; providers can finalize messages with identical timestamps.
197 const message =
198 messages.find((candidate) => candidate.id === turnItem?.messageId) ??
199 messages.toSorted(
200 (left, right) =>
201 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
202 DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
203 )[0] ??
204 null;
205 const failure =
206 run.status === "failed"
207 ? projection.turnItems
208 .filter((item) => item.runId === run.id && item.type === "error")
209 .toSorted((left, right) => right.ordinal - left.ordinal)[0]
210 : undefined;
211 const text =
212 (failure?.type === "error" ? failure.failure.message : undefined) ??
213 message?.text ??
214 turnItem?.text ??
215 (run.status === "completed"
216 ? "Child task completed without an assistant result."
217 : `Child task ended with status ${run.status}.`);
218 return {
219 text,
220 messageId: failure === undefined ? (message?.id ?? turnItem?.messageId ?? null) : null,
221 turnItemId: failure?.id ?? turnItem?.id ?? null,
222 };
224​
225export function delegatedTaskProgress(projection: {
226 readonly runs: OrchestrationV2ThreadProjection["runs"];
227 readonly messages: ReadonlyArray<
228 Pick<OrchestrationV2ConversationMessage, "runId" | "notification">
229 >;
230 readonly subagents: ReadonlyArray<
231 Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">
232 >;
233 readonly providerThreads: ReadonlyArray<
234 Pick<OrchestrationV2ThreadProjection["providerThreads"][number], "pendingBackgroundTasks">
235 >;
236}) {
237 const terminal = (status: string) =>
238 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(status);
239 const monitorRuns = new Set(
240 projection.messages
241 .filter((message) => message.notification?.source.kind === "monitor")
242 .map((message) => message.runId),
243 );
244 const workRuns = projection.runs.filter(
245 (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back",
246 );
247 const active = workRuns.some(
248 (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true),
249 );
250 const children =
251 projection.subagents.some(
252 (task) =>
253 isOrchestrationV2WorkActive(task.status) ||
254 // Publishing a child's result precedes scheduling its parent's wake.
255 // The parent still owes that follow-up even between those transactions.
256 (task.status !== "idle" &&
257 (task.completionDelivery?.state === "pending" ||
258 task.completionDelivery?.state === "claimed")),
259 ) ||
260 projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
261 const resultRun = workRuns
262 .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1))
263 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0];
264 return {
265 state:
266 active || resultRun === undefined
267 ? ("working" as const)
268 : children
269 ? ("waiting_for_children" as const)
270 : ("result_available" as const),
271 resultRun,
272 };
274​
275function writtenIds(
276 emitted: ReadonlyArray<OrchestrationV2DomainEvent>,
277 type: "subagent.updated" | "node.updated" | "turn-item.updated" | "provider-turn.updated",
278): ReadonlySet<string> {
279 return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));
281​
282export const endOrphanedNativeSubagent = Effect.fn("subagentProjection.endOrphanedNativeSubagent")(
283 function* <E>(input: {
284 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
285 readonly subagentId: NodeId;
286 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
287 readonly completedAt?: DateTime.Utc;
288 readonly result?: string | null;
289 readonly now: DateTime.Utc;
290 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
291 readonly allocateEventId: () => Effect.Effect<EventId, E>;
292 }) {
293 const { now, status, subagentId, completedAt = now } = input;
294 const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);
295 if (subagent?.origin !== "provider_native") return [];
296 const node = input.projection.nodes.find((entry) => entry.id === subagentId);
297 const item = input.projection.turnItems.find(
298 (entry) => entry.type === "subagent" && entry.subagentId === subagentId,
299 );
300 const scope = {
301 threadId: subagent.threadId,
302 ...(subagent.runId === null ? {} : { runId: subagent.runId }),
303 nodeId: subagentId,
304 providerInstanceId: subagent.providerInstanceId,
305 occurredAt: now,
306 };
307 const events: Array<OrchestrationV2DomainEvent> = [];
308 if (
309 isOrchestrationV2WorkActive(subagent.status) &&
310 !writtenIds(input.emitted, "subagent.updated").has(subagentId)
311 ) {
312 events.push({
313 ...scope,
314 id: yield* input.allocateEventId(),
315 type: "subagent.updated",
316 driver: subagent.driver,
317 payload: {
318 ...subagent,
319 status,
320 completedAt,
321 updatedAt: now,
322 ...(input.result === undefined ? {} : { result: input.result }),
323 },
324 });
325 }
326 if (
327 node !== undefined &&
328 isOrchestrationV2WorkActive(node.status) &&
329 !writtenIds(input.emitted, "node.updated").has(subagentId)
330 ) {
331 events.push({
332 ...scope,
333 id: yield* input.allocateEventId(),
334 type: "node.updated",
335 payload: { ...node, status, completedAt },
336 });
337 }
338 if (
339 item !== undefined &&
340 isOrchestrationV2WorkActive(item.status) &&
341 !writtenIds(input.emitted, "turn-item.updated").has(item.id)
342 ) {
343 events.push({
344 ...scope,
345 id: yield* input.allocateEventId(),
346 type: "turn-item.updated",
347 payload: {
348 ...item,
349 status,
350 completedAt,
351 updatedAt: now,
352 ...(input.result === undefined ? {} : { result: input.result }),
353 },
354 });
355 }
356 return events;
357 },
358);
359​
360export const endRunlessRootTurns = Effect.fn("subagentProjection.endRunlessRootTurns")(function* <
361 E,
362>(input: {
363 readonly threadId: ThreadId;
364 readonly providerInstanceId: ProviderInstanceId;
365 readonly projection: Pick<
366 OrchestrationV2ThreadProjection,
367 "nodes" | "providerTurns" | "turnItems"
368 >;
369 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
370 readonly completedAt?: DateTime.Utc;
371 readonly now: DateTime.Utc;
372 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
373 readonly allocateEventId: () => Effect.Effect<EventId, E>;
374}) {
375 const { now, status, completedAt = now } = input;
376 const endedNodeIds = writtenIds(input.emitted, "node.updated");
377 const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
378 const endedProviderTurnIds = writtenIds(input.emitted, "provider-turn.updated");
379 const scope = {
380 threadId: input.threadId,
381 providerInstanceId: input.providerInstanceId,
382 occurredAt: now,
383 };
384 const events: Array<OrchestrationV2DomainEvent> = [];
385 for (const node of input.projection.nodes) {
386 if (
387 node.kind !== "root_turn" ||
388 node.runId !== null ||
389 !isOrchestrationV2WorkActive(node.status)
390 ) {
391 continue;
392 }
393 if (!endedNodeIds.has(node.id)) {
394 events.push({
395 ...scope,
396 id: yield* input.allocateEventId(),
397 type: "node.updated",
398 nodeId: node.id,
399 payload: { ...node, status, completedAt },
400 });
401 }
402 for (const item of input.projection.turnItems) {
403 if (
404 item.nodeId !== node.id ||
405 item.runId !== null ||
406 !isOrchestrationV2WorkActive(item.status) ||
407 endedItemIds.has(item.id)
408 ) {
409 continue;
410 }
411 events.push({
412 ...scope,
413 id: yield* input.allocateEventId(),
414 type: "turn-item.updated",
415 nodeId: node.id,
416 payload: {
417 ...item,
418 status:
419 status === "completed" &&
420 (item.type === "command_execution" || item.type === "dynamic_tool")
421 ? "failed"
422 : status,
423 completedAt,
424 updatedAt: now,
425 ...(item.type === "reasoning" || item.type === "assistant_message"
426 ? { streaming: false }
427 : {}),
428 },
429 });
430 }
431 for (const providerTurn of input.projection.providerTurns) {
432 if (
433 providerTurn.nodeId !== node.id ||
434 providerTurn.runAttemptId !== null ||
435 !isOrchestrationV2WorkActive(providerTurn.status) ||
436 endedProviderTurnIds.has(providerTurn.id)
437 ) {
438 continue;
439 }
440 events.push({
441 ...scope,
442 id: yield* input.allocateEventId(),
443 type: "provider-turn.updated",
444 nodeId: node.id,
445 payload: { ...providerTurn, status, completedAt },
446 });
447 }
448 }
449 return events;
450});