@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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