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 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.`,
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 // Runs for every domain event; most events return before any work is needed.
62 const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = Effect.fnUntraced(
63 function* (event) {
64 if (event.type === "run.updated") {
65 if (!["completed", "failed", "waiting"].includes(event.payload.status)) return;
66 const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]);
67 if (parent.thread.archivedAt !== null || parent.thread.deletedAt !== null) return;
68 for (const task of parent.subagents) {
69 if (
70 task.origin !== "app_owned" ||
71 task.runId !== event.payload.id ||
72 task.completionWake !== "settled_only" ||
73 task.completionDelivery?.state === "disposed" ||
74 task.childThreadId === null ||
75 ["completed", "failed", "cancelled", "interrupted"].includes(task.status)
76 ) {
77 continue;
78 }
79 const child = yield* projections.getThreadRecords(task.childThreadId, [
80 "runtimeRequests",
81 ]);
82 for (const request of child.runtimeRequests) {
83 if (
84 request.kind !== "user_input" ||
85 request.status !== "pending" ||
86 request.responseCapability.type !== "live"
87 ) {
88 continue;
89 }
90 yield* wakeParent(task, request).pipe(
91 Effect.catchCause((cause) =>
92 Effect.logWarning("catching up a delegated task question failed", {
93 taskId: task.id,
94 requestId: request.id,
95 cause,
96 }),
97 ),
98 );
99 }
100 }
101 return;
102 }
103 if (event.type !== "runtime-request.updated" || event.payload.kind !== "user_input") {
104 return;
105 }
106 const child = yield* projections.getThread(event.threadId);
107 const parentThreadId = child.lineage.parentThreadId;
108 if (parentThreadId === null) return;
109 const request = yield* projections.getRuntimeRequest(event.threadId, event.payload.id);
110 const key = `${parentThreadId}:${event.payload.id}`;
111 const messageId = MessageId.make(`message:delegated-task-question:${key}`);
112 if (event.payload.status !== "pending" || request?.status !== "pending") {
113 const parent = yield* projections.getThreadRecords(parentThreadId, ["runs"]);
114 const queued = parent.runs.find(
115 (run) => run.status === "queued" && run.userMessageId === messageId,
116 );
117 if (queued !== undefined) {
118 yield* engine.dispatch({
119 type: "queued-run.cancel",
120 commandId: CommandId.make(`server:delegated-task-question-cancel:${key}`),
121 threadId: parentThreadId,
122 runId: queued.id,
123 });
124 }
125 return;
126 }
127 const parent = yield* projections.getThreadRecords(parentThreadId, ["subagents", "runs"]);
128 const { runs } = yield* projections.getThreadRecords(child.id, ["runs"]);
129 const run =
130 runs.find((run) => run.id === event.runId) ??
131 runs.toSorted((a, b) => b.ordinal - a.ordinal)[0];
132 const taskId =
133 run?.delegatedTaskId ??
134 (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined);
135 const task = parent.subagents.find(
136 (candidate) => candidate.origin === "app_owned" && candidate.id === taskId,
137 );
138 if (
139 task === undefined ||
140 parent.thread.archivedAt !== null ||
141 parent.thread.deletedAt !== null
142 ) {
143 return;
144 }
145 // A blocking delegate_task wait delivers the question itself.
146 if (
147 task.completionWake === "settled_only" &&
148 event.payload.responseCapability.type === "live" &&
149 parent.runs.some(
150 (run) =>
151 run.id === task.runId &&
152 (run.status === "preparing" || run.status === "starting" || run.status === "running"),
153 )
154 ) {
155 return;
156 }
157 yield* wakeParent(task, request);
158 },
159 (effect, event) =>
160 effect.pipe(
161 Effect.catchCause((cause) =>
162 Effect.logWarning("waking the parent of a delegated task question failed", {
163 threadId: event.threadId,
164 cause,
165 }),
166 ),
167 ),
168 );
169
170 const start: DelegatedTaskQuestionReactor["Service"]["start"] = () =>
171 forkParked(
172 Stream.runForEach(engine.streamDomainEvents, handle).pipe(
173 Effect.catchCause((cause) =>
174 Effect.logWarning("delegated task question event stream failed", { cause }),
175 ),
176 ),
177 );
178
179 return { start, handle } satisfies DelegatedTaskQuestionReactor["Service"];
180});
181
182export const layer = Layer.effect(DelegatedTaskQuestionReactor, make);