Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2RuntimeRequest,
6 type OrchestrationV2Subagent,
7 ProviderRequestKind,
8 type RuntimeRequestId,
9 type ThreadId,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Schema from "effect/Schema";
15import type * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17
18import { reportLabel } from "@t3tools/provider-core/server/notification";
19
20import { forkParked } from "../serverActivation.ts";
21import * as Orchestrator from "./Orchestrator.ts";
22import * as ProjectionStore from "./ProjectionStore.ts";
23
24const isApprovalKind = Schema.is(ProviderRequestKind);
25const notifiesParent = (kind: OrchestrationV2RuntimeRequest["kind"]) =>
26 kind === "user_input" || isApprovalKind(kind);
27
28export class DelegatedTaskQuestionReactor extends Context.Service<
29 DelegatedTaskQuestionReactor,
30 {
31 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
32 readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect<void>;
33 }
34>()("t3/orchestration-v2/DelegatedTaskQuestionReactor") {}
35
36const make = Effect.gen(function* () {
37 const engine = yield* Orchestrator.OrchestratorV2;
38 const projections = yield* ProjectionStore.ProjectionStoreV2;
39
40 const wakeParent = Effect.fnUntraced(function* (
41 task: OrchestrationV2Subagent,
42 request: OrchestrationV2RuntimeRequest,
43 ) {
44 if (task.childThreadId === null) return;
45 const key = `${task.threadId}:${request.id}`;
46 const label = reportLabel(task.title?.trim() || task.prompt);
47 const quotedLabel = label === undefined ? "" : ` "${label}"`;
48 // An approval notice is advisory: the parent agent cannot approve on the user's behalf.
49 const approval = isApprovalKind(request.kind);
50 const situation =
51 request.responseCapability.type === "message"
52 ? `Delegated task ${task.id} asked a question and is still working.`
53 : `Delegated task ${task.id} is blocked on a question and cannot continue until it is answered.`;
54 yield* engine.dispatch({
55 type: "message.dispatch",
56 commandId: CommandId.make(`server:delegated-task-question:${key}`),
57 threadId: task.threadId,
58 messageId: MessageId.make(`message:delegated-task-question:${key}`),
59 text: approval
60 ? `Delegated task ${task.id} is blocked on a ${request.kind} approval (requestId ${request.id}, threadId ${task.childThreadId}) and cannot continue until the user approves or declines it in the app. You cannot approve it. Tell the user it is waiting, or stop the task with task_cancel and relaunch it if it should not need this approval. If it is no longer pending, it was resolved.`
61 : `${situation} Read it with t3_pending_request action read, threadId ${task.childThreadId}, and requestId ${request.id}. Answer it with action 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.`,
62 notification: {
63 source: { kind: "delegated_task", taskIds: [task.id], childThreadId: task.childThreadId },
64 outcome: "updated",
65 summary: `Delegated task${quotedLabel} ${approval ? "needs approval" : "has a question"}`,
66 },
67 attachments: [],
68 dispatchMode: { type: "queue_after_active" },
69 createdBy: "agent",
70 creationSource: "server",
71 });
72 });
73
74 const cancelQueuedWakes = Effect.fnUntraced(function* (
75 parentThreadId: ThreadId,
76 requestIds: ReadonlyArray<RuntimeRequestId>,
77 ) {
78 const parent = yield* projections.getThreadRecords(parentThreadId, ["runs"]);
79 for (const requestId of requestIds) {
80 const key = `${parentThreadId}:${requestId}`;
81 const messageId = MessageId.make(`message:delegated-task-question:${key}`);
82 const queued = parent.runs.find(
83 (run) => run.status === "queued" && run.userMessageId === messageId,
84 );
85 if (queued === undefined) continue;
86 yield* engine
87 .dispatch({
88 type: "queued-run.cancel",
89 commandId: CommandId.make(`server:delegated-task-question-cancel:${key}`),
90 threadId: parentThreadId,
91 runId: queued.id,
92 })
93 .pipe(
94 Effect.catchCause((cause) =>
95 Effect.logWarning("cancelling a delegated task question wake failed", {
96 threadId: parentThreadId,
97 requestId,
98 cause,
99 }),
100 ),
101 );
102 }
103 });
104
105 // Runs for every domain event; most events return before any work is needed.
106 const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = Effect.fnUntraced(
107 function* (event) {
108 if (event.type === "run.updated") {
109 if (!["completed", "failed", "waiting"].includes(event.payload.status)) return;
110 const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]);
111 if (parent.thread.archivedAt !== null || parent.thread.deletedAt !== null) return;
112 for (const task of parent.subagents) {
113 if (
114 task.origin !== "app_owned" ||
115 task.runId !== event.payload.id ||
116 task.completionWake !== "settled_only" ||
117 task.completionDelivery?.state === "disposed" ||
118 task.childThreadId === null ||
119 ["completed", "failed", "cancelled", "interrupted"].includes(task.status)
120 ) {
121 continue;
122 }
123 const child = yield* projections.getThreadRecords(task.childThreadId, [
124 "runtimeRequests",
125 ]);
126 for (const request of child.runtimeRequests) {
127 if (
128 !notifiesParent(request.kind) ||
129 request.status !== "pending" ||
130 request.responseCapability.type !== "live"
131 ) {
132 continue;
133 }
134 yield* wakeParent(task, request).pipe(
135 Effect.catchCause((cause) =>
136 Effect.logWarning("catching up a delegated task question failed", {
137 taskId: task.id,
138 requestId: request.id,
139 cause,
140 }),
141 ),
142 );
143 }
144 }
145 return;
146 }
147 if (event.type === "subagent.updated") {
148 const task = event.payload;
149 if (
150 task.origin !== "app_owned" ||
151 task.childThreadId === null ||
152 !["completed", "failed", "cancelled", "interrupted"].includes(task.status)
153 ) {
154 return;
155 }
156 // A settled task can no longer use an answer to its still-pending requests.
157 const { runtimeRequests } = yield* projections.getThreadRecords(task.childThreadId, [
158 "runtimeRequests",
159 ]);
160 const requests = runtimeRequests.filter((request) => notifiesParent(request.kind));
161 if (requests.length === 0) return;
162 const child = yield* projections.getThreadRecords(task.childThreadId, ["runs", "nodes"]);
163 const taskRunIds = new Set(
164 child.runs
165 .filter(
166 (run) =>
167 run.delegatedTaskId === task.id ||
168 (run.delegatedTaskId === undefined &&
169 child.thread.forkedFrom?.type === "node" &&
170 child.thread.forkedFrom.nodeId === task.id),
171 )
172 .map((run) => run.id),
173 );
174 const taskNodeIds = new Set(
175 child.nodes
176 .filter((node) => node.runId !== null && taskRunIds.has(node.runId))
177 .map((node) => node.id),
178 );
179 yield* cancelQueuedWakes(
180 task.threadId,
181 requests
182 .filter((request) => taskNodeIds.has(request.nodeId))
183 .map((request) => request.id),
184 );
185 return;
186 }
187 if (event.type !== "runtime-request.updated" || !notifiesParent(event.payload.kind)) {
188 return;
189 }
190 // Only a live approval can still be approved, so only it is worth a notice.
191 if (
192 isApprovalKind(event.payload.kind) &&
193 event.payload.status === "pending" &&
194 event.payload.responseCapability.type !== "live"
195 ) {
196 return;
197 }
198 const child = yield* projections.getThread(event.threadId);
199 const parentThreadId = child.lineage.parentThreadId;
200 if (parentThreadId === null) return;
201 const request = yield* projections.getRuntimeRequest(event.threadId, event.payload.id);
202 if (event.payload.status !== "pending" || request?.status !== "pending") {
203 yield* cancelQueuedWakes(parentThreadId, [event.payload.id]);
204 return;
205 }
206 const parent = yield* projections.getThreadRecords(parentThreadId, ["subagents", "runs"]);
207 const { runs } = yield* projections.getThreadRecords(child.id, ["runs"]);
208 const run =
209 runs.find((run) => run.id === event.runId) ??
210 runs.toSorted((a, b) => b.ordinal - a.ordinal)[0];
211 const taskId =
212 run?.delegatedTaskId ??
213 (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined);
214 const task = parent.subagents.find(
215 (candidate) => candidate.origin === "app_owned" && candidate.id === taskId,
216 );
217 if (
218 task === undefined ||
219 parent.thread.archivedAt !== null ||
220 parent.thread.deletedAt !== null
221 ) {
222 return;
223 }
224 // A blocking delegate_task wait delivers the request itself.
225 if (
226 task.completionWake === "settled_only" &&
227 event.payload.responseCapability.type === "live" &&
228 parent.runs.some(
229 (run) =>
230 run.id === task.runId &&
231 (run.status === "preparing" || run.status === "starting" || run.status === "running"),
232 )
233 ) {
234 return;
235 }
236 yield* wakeParent(task, request);
237 },
238 (effect, event) =>
239 effect.pipe(
240 Effect.catchCause((cause) =>
241 Effect.logWarning("waking the parent of a delegated task question failed", {
242 threadId: event.threadId,
243 cause,
244 }),
245 ),
246 ),
247 );
248
249 const start: DelegatedTaskQuestionReactor["Service"]["start"] = () =>
250 forkParked(
251 Stream.runForEach(engine.streamDomainEvents, handle).pipe(
252 Effect.catchCause((cause) =>
253 Effect.logWarning("delegated task question event stream failed", { cause }),
254 ),
255 ),
256 );
257
258 return { start, handle } satisfies DelegatedTaskQuestionReactor["Service"];
259});
260
261export const layer = Layer.effect(DelegatedTaskQuestionReactor, make);