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

subagentProjection.ts

423 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 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 /** 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 };
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 };
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.completionDelivery?.state === "pending" ||
254 task.completionDelivery?.state === "claimed",
255 ) ||
256 projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
257 const resultRun = workRuns
258 .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1))
259 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0];
260 return {
261 state:
262 active || resultRun === undefined
263 ? ("working" as const)
264 : children
265 ? ("waiting_for_children" as const)
266 : ("result_available" as const),
267 resultRun,
268 };
270​
271function writtenIds(
272 emitted: ReadonlyArray<OrchestrationV2DomainEvent>,
273 type: "subagent.updated" | "node.updated" | "turn-item.updated",
274): ReadonlySet<string> {
275 return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));
277​
278export const endOrphanedNativeSubagent = <E>(input: {
279 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
280 readonly subagentId: NodeId;
281 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
282 readonly completedAt?: DateTime.Utc;
283 readonly result?: string | null;
284 readonly now: DateTime.Utc;
285 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
286 readonly allocateEventId: () => Effect.Effect<EventId, E>;
287}) =>
288 Effect.gen(function* () {
289 const { now, status, subagentId, completedAt = now } = input;
290 const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);
291 if (subagent?.origin !== "provider_native") return [];
292 const node = input.projection.nodes.find((entry) => entry.id === subagentId);
293 const item = input.projection.turnItems.find(
294 (entry) => entry.type === "subagent" && entry.subagentId === subagentId,
295 );
296 const scope = {
297 threadId: subagent.threadId,
298 ...(subagent.runId === null ? {} : { runId: subagent.runId }),
299 nodeId: subagentId,
300 providerInstanceId: subagent.providerInstanceId,
301 occurredAt: now,
302 };
303 const events: Array<OrchestrationV2DomainEvent> = [];
304 if (
305 isOrchestrationV2WorkActive(subagent.status) &&
306 !writtenIds(input.emitted, "subagent.updated").has(subagentId)
307 ) {
308 events.push({
309 ...scope,
310 id: yield* input.allocateEventId(),
311 type: "subagent.updated",
312 driver: subagent.driver,
313 payload: {
314 ...subagent,
315 status,
316 completedAt,
317 updatedAt: now,
318 ...(input.result === undefined ? {} : { result: input.result }),
319 },
320 });
321 }
322 if (
323 node !== undefined &&
324 isOrchestrationV2WorkActive(node.status) &&
325 !writtenIds(input.emitted, "node.updated").has(subagentId)
326 ) {
327 events.push({
328 ...scope,
329 id: yield* input.allocateEventId(),
330 type: "node.updated",
331 payload: { ...node, status, completedAt },
332 });
333 }
334 if (
335 item !== undefined &&
336 isOrchestrationV2WorkActive(item.status) &&
337 !writtenIds(input.emitted, "turn-item.updated").has(item.id)
338 ) {
339 events.push({
340 ...scope,
341 id: yield* input.allocateEventId(),
342 type: "turn-item.updated",
343 payload: {
344 ...item,
345 status,
346 completedAt,
347 updatedAt: now,
348 ...(input.result === undefined ? {} : { result: input.result }),
349 },
350 });
351 }
352 return events;
353 });
354​
355export const endRunlessRootTurns = <E>(input: {
356 readonly threadId: ThreadId;
357 readonly providerInstanceId: ProviderInstanceId;
358 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "turnItems">;
359 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
360 readonly completedAt?: DateTime.Utc;
361 readonly now: DateTime.Utc;
362 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
363 readonly allocateEventId: () => Effect.Effect<EventId, E>;
364}) =>
365 Effect.gen(function* () {
366 const { now, status, completedAt = now } = input;
367 const endedNodeIds = writtenIds(input.emitted, "node.updated");
368 const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
369 const scope = {
370 threadId: input.threadId,
371 providerInstanceId: input.providerInstanceId,
372 occurredAt: now,
373 };
374 const events: Array<OrchestrationV2DomainEvent> = [];
375 for (const node of input.projection.nodes) {
376 if (
377 node.kind !== "root_turn" ||
378 node.runId !== null ||
379 !isOrchestrationV2WorkActive(node.status)
380 ) {
381 continue;
382 }
383 if (!endedNodeIds.has(node.id)) {
384 events.push({
385 ...scope,
386 id: yield* input.allocateEventId(),
387 type: "node.updated",
388 nodeId: node.id,
389 payload: { ...node, status, completedAt },
390 });
391 }
392 for (const item of input.projection.turnItems) {
393 if (
394 item.nodeId !== node.id ||
395 item.runId !== null ||
396 !isOrchestrationV2WorkActive(item.status) ||
397 endedItemIds.has(item.id)
398 ) {
399 continue;
400 }
401 events.push({
402 ...scope,
403 id: yield* input.allocateEventId(),
404 type: "turn-item.updated",
405 nodeId: node.id,
406 payload: {
407 ...item,
408 status:
409 status === "completed" &&
410 (item.type === "command_execution" || item.type === "dynamic_tool")
411 ? "failed"
412 : status,
413 completedAt,
414 updatedAt: now,
415 ...(item.type === "reasoning" || item.type === "assistant_message"
416 ? { streaming: false }
417 : {}),
418 },
419 });
420 }
421 }
422 return events;
423 });