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

subagentProjection.ts

426 lines14.0 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 // A guest link belongs to the thread it was made for.
86 guestShare: null,
87 lastVisitedAt: null,
88 deletedAt: null,
89 };
91​
92export function makeSubagentConversationArtifacts(input: {
93 readonly messageId: MessageId;
94 readonly senderThreadId?: ThreadId;
95 readonly turnItemId: TurnItemId;
96 readonly threadId: ThreadId;
97 readonly rootNodeId: NodeId;
98 readonly providerThreadId: ProviderThreadId | null;
99 readonly providerTurnId: ProviderTurnId | null;
100 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
101 readonly role: "user" | "assistant";
102 readonly text: string;
103 readonly workflowScript?: boolean;
104 readonly ordinal: number;
105 readonly now: DateTime.Utc;
106}): {
107 readonly message: OrchestrationV2ConversationMessage;
108 readonly turnItem: OrchestrationV2TurnItem;
109} {
110 const message: OrchestrationV2ConversationMessage = {
111 createdBy: "agent",
112 creationSource: "provider",
113 id: input.messageId,
114 threadId: input.threadId,
115 runId: null,
116 nodeId: input.rootNodeId,
117 role: input.role,
118 ...(input.role === "user" && input.senderThreadId !== undefined
119 ? { senderThreadId: input.senderThreadId }
120 : {}),
121 ...(input.role === "user" && input.workflowScript !== undefined
122 ? { workflowScript: input.workflowScript }
123 : {}),
124 text: input.text,
125 attachments: [],
126 streaming: false,
127 createdAt: input.now,
128 updatedAt: input.now,
129 };
130 const base = {
131 id: input.turnItemId,
132 threadId: input.threadId,
133 runId: null,
134 nodeId: input.rootNodeId,
135 providerThreadId: input.providerThreadId,
136 providerTurnId: input.providerTurnId,
137 nativeItemRef: input.nativeItemRef,
138 parentItemId: null,
139 ordinal: input.ordinal,
140 status: "completed" as const,
141 title: null,
142 startedAt: input.now,
143 completedAt: input.now,
144 updatedAt: input.now,
145 messageId: input.messageId,
146 text: input.text,
147 };
148 const turnItem: OrchestrationV2TurnItem =
149 input.role === "user"
150 ? {
151 ...base,
152 createdBy: "agent",
153 creationSource: "provider",
154 type: "user_message",
155 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
156 ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
157 inputIntent: "turn_start",
158 attachments: [],
159 }
160 : {
161 ...base,
162 type: "assistant_message",
163 streaming: false,
164 };
165 return { message, turnItem };
167​
168export function subagentResultForRun(
169 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems">,
170 run: OrchestrationV2Run,
171): {
172 readonly text: string;
173 readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
174 readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
175} {
176 const turnItem =
177 projection.turnItems
178 .filter(
179 (
180 candidate,
181 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "assistant_message" }> =>
182 candidate.runId === run.id &&
183 candidate.type === "assistant_message" &&
184 candidate.text.trim().length > 0,
185 )
186 .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
187 const messages = projection.messages.filter(
188 (candidate) =>
189 candidate.runId === run.id &&
190 candidate.role === "assistant" &&
191 candidate.text.trim().length > 0,
192 );
193 // Prefer turn item order; providers can finalize messages with identical timestamps.
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 };
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 };
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] : [])));
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});