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

handlers.ts

379 lines14.0 KB

1import {
2 type CommandId,
3 type RuntimeRequestId,
4 ThreadId,
5 type OrchestrationV2ThreadProjection,
6 type RunId,
7 OrchestratorMcpFailure,
8 type OrchestrationV2Command,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import { modelSelectionCommandType } from "@t3tools/shared/model";
12​
13import * as McpInvocationContext from "../../McpInvocationContext.ts";
14import * as McpToolAccess from "../../McpToolAccess.ts";
15import {
16 dispatchFailure,
17 newCommandId,
18 readCaller,
19 readThread,
20 unavailable,
21} from "../../threadAccess.ts";
22import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
23import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
24import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
25import { ThreadToolkit } from "./tools.ts";
26​
27function queueEntry(
28 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">,
29 runId: RunId,
30 limit: number,
31) {
32 const run = projection.runs.find((run) => run.id === runId && run.status === "queued");
33 const message = projection.messages.find((message) => message.id === run?.userMessageId);
34 if (run === undefined || message === undefined) return undefined;
35 const characters = Array.from(message.text);
36 return {
37 queuedRunId: run.id,
38 text: characters.slice(0, limit).join(""),
39 truncated: characters.length > limit,
40 };
42const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
43 threadId: ThreadId | undefined,
44 command: (common: { commandId: CommandId; threadId: ThreadId }) => OrchestrationV2Command,
45) {
46 const { threads, projection } = yield* readThread(threadId);
47 const result = yield* threads
48 .dispatch(command({ commandId: yield* newCommandId(), threadId: projection.thread.id }))
49 .pipe(Effect.mapError(dispatchFailure));
50 return { sequence: result.sequence };
51});
52​
53const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: {
54 threadId?: ThreadId | undefined;
55 requestId: RuntimeRequestId;
56}) {
57 const context = yield* readThread(input.threadId, ["runtimeRequests", "turnItems"]);
58 const request = context.projection.runtimeRequests.find(
59 (request) => request.id === input.requestId && request.kind === "user_input",
60 );
61 const item = context.projection.turnItems.find(
62 (item) => item.type === "user_input_request" && item.requestId === input.requestId,
63 );
64 if (request === undefined || item?.type !== "user_input_request")
65 return yield* new OrchestratorMcpFailure({
66 code: "invalid_request",
67 message: "The pending user-input request was not found.",
68 });
69 if (request.status !== "pending")
70 return yield* new OrchestratorMcpFailure({
71 code: "invalid_request",
72 message:
73 request.status === "resolved"
74 ? "The user-input request was already answered."
75 : `The user-input request is no longer pending (${request.status}).`,
76 });
77 return { ...context, request, item };
78});
79/** A field the chosen action needs. `null` counts as given, as in `beforeRunId: null`. */
80const required = <A>(value: A | undefined, name: string) =>
81 value === undefined
82 ? Effect.fail(
83 new OrchestratorMcpFailure({
84 code: "invalid_request",
85 message: `This action needs \`${name}\`.`,
86 }),
87 )
88 : Effect.succeed(value);
89const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
90 handle: (params: P) => Effect.Effect<A, E, R>,
91) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
92​
93export const layer = McpToolAccess.toLayer(ThreadToolkit, {
94 run_scheduled_task_now: McpToolAccess.writesEnvironment((input) =>
95 Effect.gen(function* () {
96 const scheduler = yield* ScheduledTasks.ScheduledTaskService;
97 const { tasks } = yield* scheduler.list().pipe(Effect.mapError(unavailable));
98 if (!tasks.some((task) => task.id === input.taskId))
99 return yield* new OrchestratorMcpFailure({
100 code: "invalid_request",
101 message: "The scheduled task was not found.",
102 });
103 const { task, threadId } = yield* scheduler
104 .runNow({ id: input.taskId })
105 .pipe(
106 Effect.mapError(
107 (error) =>
108 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
109 ),
110 );
111 const scope = yield* McpInvocationContext.McpInvocationContext;
112 return {
113 taskId: task.id,
114 threadId,
115 ...(threadId === null
116 ? {}
117 : {
118 link: McpInvocationContext.threadLinkFor(scope, threadId),
119 }),
120 lastRunStatus: task.lastRunStatus,
121 runCount: task.runCount,
122 nextRunAt: task.nextRunAt,
123 };
124 }),
125 ),
126 t3_thread_search: McpToolAccess.reads((input) =>
127 Effect.gen(function* () {
128 const { caller } = yield* readCaller();
129 const scope = yield* McpInvocationContext.McpInvocationContext;
130 const threadSearch = yield* ThreadSearch.ThreadSearch;
131 const { matches } = yield* threadSearch
132 .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId })
133 .pipe(Effect.mapError(unavailable));
134 return {
135 currentThreadId: scope.thread?.threadId ?? null,
136 matches: matches.map((match) => ({
137 ...match,
138 link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title),
139 })),
140 };
141 }),
142 ),
143 t3_thread_transfer: McpToolAccess.either(
144 (input) => input.action === "status",
145 McpToolAccess.reads((input) =>
146 Effect.gen(function* () {
147 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
148 return {
149 transfers: projection.contextTransfers.map(
150 ({ id, sourceThreadId, targetThreadId, status }) => ({
151 id,
152 sourceThreadId,
153 targetThreadId,
154 status,
155 }),
156 ),
157 };
158 }),
159 ),
160 McpToolAccess.writesThreads(
161 (input) => [input.threadId, input.targetThreadId],
162 (input) =>
163 Effect.gen(function* () {
164 const sourcePoint = input.sourcePoint ?? { type: "latest_stable" as const };
165 const { threads, projection } = yield* readThread(input.threadId);
166 const commandId = yield* newCommandId();
167 if (input.action === "merge_back") {
168 const targetThreadId = yield* required(input.targetThreadId, "targetThreadId");
169 yield* readThread(targetThreadId);
170 const result = yield* threads
171 .dispatch({
172 type: "thread.merge_back",
173 commandId,
174 sourceThreadId: projection.thread.id,
175 targetThreadId,
176 sourcePoint,
177 createdBy: "agent",
178 creationSource: "mcp",
179 })
180 .pipe(Effect.mapError(dispatchFailure));
181 return { sequence: result.sequence, targetThreadId };
182 }
183 const targetThreadId = ThreadId.make(`${commandId}:fork`);
184 const result = yield* threads
185 .dispatch({
186 type: "thread.fork",
187 commandId,
188 sourceThreadId: projection.thread.id,
189 targetThreadId,
190 sourcePoint,
191 ...(input.title === undefined ? {} : { title: input.title }),
192 createdBy: "agent",
193 creationSource: "mcp",
194 })
195 .pipe(Effect.mapError(dispatchFailure));
196 return { sequence: result.sequence, targetThreadId };
197 }),
198 ),
199 ),
200 t3_thread_configure: McpToolAccess.either(
201 (input) => input.modelSelection === undefined,
202 McpToolAccess.reads((input) =>
203 Effect.gen(function* () {
204 const {
205 projection: { thread },
206 } = yield* readThread(input.threadId);
207 return {
208 threadId: thread.id,
209 modelSelection: thread.modelSelection,
210 runtimeMode: thread.runtimeMode,
211 interactionMode: thread.interactionMode,
212 };
213 }),
214 ),
215 writesThread((input) =>
216 Effect.gen(function* () {
217 const modelSelection = yield* required(input.modelSelection, "modelSelection");
218 const {
219 threads,
220 projection: { thread },
221 } = yield* readThread(input.threadId);
222 const type = modelSelectionCommandType(thread.providerInstanceId, modelSelection);
223 const result = yield* threads
224 .dispatch({ type, threadId: thread.id, commandId: yield* newCommandId(), modelSelection })
225 .pipe(Effect.mapError(dispatchFailure));
226 return { sequence: result.sequence };
227 }),
228 ),
229 ),
230 t3_pending_request: McpToolAccess.either(
231 (input) => input.action !== "respond",
232 McpToolAccess.reads((input) =>
233 Effect.gen(function* () {
234 if (input.action === "list") {
235 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
236 return {
237 requestIds: projection.runtimeRequests
238 .filter((request) => request.kind === "user_input" && request.status === "pending")
239 .map((request) => request.id),
240 };
241 }
242 const requestId = yield* required(input.requestId, "requestId");
243 const { item } = yield* readQuestion({ threadId: input.threadId, requestId });
244 return { requestId, questions: item.questions };
245 }),
246 ),
247 writesThread((input) =>
248 Effect.gen(function* () {
249 const requestId = yield* required(input.requestId, "requestId");
250 const answers = yield* required(input.answers, "answers");
251 const { threads, projection } = yield* readQuestion({
252 threadId: input.threadId,
253 requestId,
254 });
255 const result = yield* threads
256 .dispatch({
257 type: "runtime-request.respond",
258 threadId: projection.thread.id,
259 commandId: yield* newCommandId(),
260 requestId,
261 answers,
262 })
263 .pipe(Effect.mapError(dispatchFailure));
264 return { sequence: result.sequence };
265 }),
266 ),
267 ),
268 t3_queue: McpToolAccess.either(
269 (input) => input.action === "list" || input.action === "read",
270 McpToolAccess.reads((input) =>
271 Effect.gen(function* () {
272 const { threads, projection: queued } = yield* readThread(input.threadId, ["runs"], {
273 runStatuses: ["queued"],
274 });
275 const messages = yield* threads
276 .getMessagesById(
277 queued.thread.id,
278 queued.runs.map((run) => run.userMessageId),
279 )
280 .pipe(Effect.mapError(unavailable));
281 const projection = { runs: queued.runs, messages: [...messages.values()] };
282 if (input.action === "list") {
283 const runs = queuedRunsInDeliveryOrder(projection);
284 const cursor = input.cursor ?? 0;
285 const end = cursor + (input.limit ?? 20);
286 return {
287 items: runs.slice(cursor, end).flatMap((run) => {
288 const entry = queueEntry(projection, run.id, 1000);
289 return entry === undefined ? [] : [entry];
290 }),
291 nextCursor: end < runs.length ? end : null,
292 };
293 }
294 const queuedRunId = yield* required(input.queuedRunId, "queuedRunId");
295 return (
296 queueEntry(projection, queuedRunId, 16000) ??
297 (yield* new OrchestratorMcpFailure({
298 code: "invalid_request",
299 message: "The queued message was not found.",
300 }))
301 );
302 }),
303 ),
304 writesThread((input) =>
305 Effect.gen(function* () {
306 const runId = yield* required(input.queuedRunId, "queuedRunId");
307 switch (input.action) {
308 case "edit": {
309 const text = yield* required(input.text, "text");
310 return yield* dispatch(input.threadId, (common) => ({
311 ...common,
312 type: "queued-run.edit",
313 runId,
314 text,
315 }));
316 }
317 case "reorder": {
318 const beforeRunId = yield* required(input.beforeRunId, "beforeRunId");
319 return yield* dispatch(input.threadId, (common) => ({
320 ...common,
321 type: "queued-run.reorder",
322 runId,
323 beforeRunId,
324 }));
325 }
326 case "promote_to_steer": {
327 const targetRunId = yield* required(input.targetRunId, "targetRunId");
328 return yield* dispatch(input.threadId, (common) => ({
329 ...common,
330 type: "queued-message.promote-to-steer",
331 queuedRunId: runId,
332 targetRunId,
333 }));
334 }
335 default:
336 return yield* dispatch(input.threadId, (common) => ({
337 ...common,
338 type: "queued-run.cancel",
339 runId,
340 }));
341 }
342 }),
343 ),
344 ),
345 t3_thread_organize: writesThread((input) =>
346 Effect.gen(function* () {
347 const { threads, projection, caller } = yield* readThread(input.threadId);
348 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
349 if (input.action === "settle") {
350 return yield* threads
351 .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
352 .pipe(Effect.mapError(dispatchFailure));
353 }
354 let command: OrchestrationV2Command;
355 switch (input.action) {
356 case "snooze":
357 if (input.snoozedUntil === undefined) {
358 return yield* new OrchestratorMcpFailure({
359 code: "invalid_request",
360 message: "snooze requires snoozedUntil.",
361 });
362 }
363 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
364 break;
365 case "unsnooze":
366 case "unsettle":
367 command = { ...common, type: `thread.${input.action}`, reason: "user" };
368 break;
369 case "mark_unread":
370 command = { ...common, type: "thread.mark-unread" };
371 break;
372 default:
373 command = { ...common, type: `thread.${input.action}` };
374 }
375 const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
376 return { sequence: result.sequence };
377 }),
378 ),
379});