Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2RuntimeRequest,
6 type OrchestrationV2Subagent,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import type * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13
14import { reportLabel } from "@t3tools/provider-core/server/notification";
15
16import { forkParked } from "../serverActivation.ts";
17import * as Orchestrator from "./Orchestrator.ts";
18import * as ProjectionStore from "./ProjectionStore.ts";
19
20export class DelegatedTaskQuestionReactor extends Context.Service<
21 DelegatedTaskQuestionReactor,
22 {
23 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
24 readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect<void>;
25 }
26>()("t3/orchestration-v2/DelegatedTaskQuestionReactor") {}
27
28const make = Effect.gen(function* () {
29 const engine = yield* Orchestrator.OrchestratorV2;
30 const projections = yield* ProjectionStore.ProjectionStoreV2;
31
32 const wakeParent = Effect.fnUntraced(function* (
33 task: OrchestrationV2Subagent,
34 request: OrchestrationV2RuntimeRequest,
35 ) {
36 if (task.childThreadId === null) return;
37 const key = `${task.threadId}:${request.id}`;
38 const label = reportLabel(task.title?.trim() || task.prompt);
39 const situation =
40 request.responseCapability.type === "message"
41 ? `Delegated task ${task.id} asked a question and is still working.`
42 : `Delegated task ${task.id} is blocked on a question and cannot continue until it is answered.`;
43 yield* engine.dispatch({
44 type: "message.dispatch",
45 commandId: CommandId.make(`server:delegated-task-question:${key}`),
46 threadId: task.threadId,
47 messageId: MessageId.make(`message:delegated-task-question:${key}`),
48 text: `${situation} Read it with t3_pending_request_read using threadId ${task.childThreadId} and requestId ${request.id}. Answer it with t3_pending_request_respond when the answer follows from the task or the user's instructions; otherwise ask the user, then answer it. If it is no longer pending, it was answered or dismissed.`,
49 notification: {
50 source: { kind: "delegated_task", taskIds: [task.id], childThreadId: task.childThreadId },
51 outcome: "updated",
52 summary: `Delegated task${label === undefined ? "" : ` "${label}"`} has a question`,
53 },
54 attachments: [],
55 dispatchMode: { type: "queue_after_active" },
56 createdBy: "agent",
57 creationSource: "server",
58 });
59 });
60
61 const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = (event) =>
62 Effect.gen(function* () {
63 if (event.type === "run.updated") {
64 if (!["completed", "failed", "waiting"].includes(event.payload.status)) return;
65 const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]);
66 if (parent.thread.archivedAt !== null || parent.thread.deletedAt !== null) return;
67 for (const task of parent.subagents) {
68 if (
69 task.origin !== "app_owned" ||
70 task.runId !== event.payload.id ||
71 task.completionWake !== "settled_only" ||
72 task.completionDelivery?.state === "disposed" ||
73 task.childThreadId === null ||
74 ["completed", "failed", "cancelled", "interrupted"].includes(task.status)
75 ) {
76 continue;
77 }
78 const child = yield* projections.getThreadRecords(task.childThreadId, [
79 "runtimeRequests",
80 ]);
81 for (const request of child.runtimeRequests) {
82 if (
83 request.kind !== "user_input" ||
84 request.status !== "pending" ||
85 request.responseCapability.type !== "live"
86 ) {
87 continue;
88 }
89 yield* wakeParent(task, request).pipe(
90 Effect.catchCause((cause) =>
91 Effect.logWarning("catching up a delegated task question failed", {
92 taskId: task.id,
93 requestId: request.id,
94 cause,
95 }),
96 ),
97 );
98 }
99 }
100 return;
101 }
102 if (event.type !== "runtime-request.updated" || event.payload.kind !== "user_input") {
103 return;
104 }
105 const child = yield* projections.getThread(event.threadId);
106 const parentThreadId = child.lineage.parentThreadId;
107 if (parentThreadId === null) return;
108 const request = yield* projections.getRuntimeRequest(event.threadId, event.payload.id);
109 const key = `${parentThreadId}:${event.payload.id}`;
110 const messageId = MessageId.make(`message:delegated-task-question:${key}`);
111 if (event.payload.status !== "pending" || request?.status !== "pending") {
112 const parent = yield* projections.getThreadRecords(parentThreadId, ["runs"]);
113 const queued = parent.runs.find(
114 (run) => run.status === "queued" && run.userMessageId === messageId,
115 );
116 if (queued !== undefined) {
117 yield* engine.dispatch({
118 type: "queued-run.cancel",
119 commandId: CommandId.make(`server:delegated-task-question-cancel:${key}`),
120 threadId: parentThreadId,
121 runId: queued.id,
122 });
123 }
124 return;
125 }
126 const parent = yield* projections.getThreadRecords(parentThreadId, ["subagents", "runs"]);
127 const { runs } = yield* projections.getThreadRecords(child.id, ["runs"]);
128 const run =
129 runs.find((run) => run.id === event.runId) ??
130 runs.toSorted((a, b) => b.ordinal - a.ordinal)[0];
131 const taskId =
132 run?.delegatedTaskId ??
133 (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined);
134 const task = parent.subagents.find(
135 (candidate) => candidate.origin === "app_owned" && candidate.id === taskId,
136 );
137 if (
138 task === undefined ||
139 parent.thread.archivedAt !== null ||
140 parent.thread.deletedAt !== null
141 ) {
142 return;
143 }
144 // A blocking delegate_task wait delivers the question itself.
145 if (
146 task.completionWake === "settled_only" &&
147 event.payload.responseCapability.type === "live" &&
148 parent.runs.some(
149 (run) =>
150 run.id === task.runId &&
151 (run.status === "preparing" || run.status === "starting" || run.status === "running"),
152 )
153 ) {
154 return;
155 }
156 yield* wakeParent(task, request);
157 }).pipe(
158 Effect.catchCause((cause) =>
159 Effect.logWarning("waking the parent of a delegated task question failed", {
160 threadId: event.threadId,
161 cause,
162 }),
163 ),
164 );
165
166 const start: DelegatedTaskQuestionReactor["Service"]["start"] = () =>
167 forkParked(
168 Stream.runForEach(engine.streamDomainEvents, handle).pipe(
169 Effect.catchCause((cause) =>
170 Effect.logWarning("delegated task question event stream failed", { cause }),
171 ),
172 ),
173 );
174
175 return { start, handle } satisfies DelegatedTaskQuestionReactor["Service"];
176});
177
178export const layer = Layer.effect(DelegatedTaskQuestionReactor, make);