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

subagentProjection.ts

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