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

handlers.ts

369 lines13.6 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 matches: matches.map((match) => ({
136 ...match,
137 link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title),
138 })),
139 };
140 }),
141 ),
142 t3_thread_transfer: McpToolAccess.either(
143 (input) => input.action === "status",
144 McpToolAccess.reads((input) =>
145 Effect.gen(function* () {
146 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
147 return {
148 transfers: projection.contextTransfers.map(
149 ({ id, sourceThreadId, targetThreadId, status }) => ({
150 id,
151 sourceThreadId,
152 targetThreadId,
153 status,
154 }),
155 ),
156 };
157 }),
158 ),
159 McpToolAccess.writesThreads(
160 (input) => [input.threadId, input.targetThreadId],
161 (input) =>
162 Effect.gen(function* () {
163 const sourcePoint = input.sourcePoint ?? { type: "latest_stable" as const };
164 const { threads, projection } = yield* readThread(input.threadId);
165 const commandId = yield* newCommandId();
166 if (input.action === "merge_back") {
167 const targetThreadId = yield* required(input.targetThreadId, "targetThreadId");
168 yield* readThread(targetThreadId);
169 const result = yield* threads
170 .dispatch({
171 type: "thread.merge_back",
172 commandId,
173 sourceThreadId: projection.thread.id,
174 targetThreadId,
175 sourcePoint,
176 createdBy: "agent",
177 creationSource: "mcp",
178 })
179 .pipe(Effect.mapError(dispatchFailure));
180 return { sequence: result.sequence, targetThreadId };
181 }
182 const targetThreadId = ThreadId.make(`${commandId}:fork`);
183 const result = yield* threads
184 .dispatch({
185 type: "thread.fork",
186 commandId,
187 sourceThreadId: projection.thread.id,
188 targetThreadId,
189 sourcePoint,
190 ...(input.title === undefined ? {} : { title: input.title }),
191 createdBy: "agent",
192 creationSource: "mcp",
193 })
194 .pipe(Effect.mapError(dispatchFailure));
195 return { sequence: result.sequence, targetThreadId };
196 }),
197 ),
198 ),
199 t3_thread_configure: McpToolAccess.either(
200 (input) => input.modelSelection === undefined,
201 McpToolAccess.reads((input) =>
202 Effect.gen(function* () {
203 const {
204 projection: { thread },
205 } = yield* readThread(input.threadId);
206 return {
207 threadId: thread.id,
208 modelSelection: thread.modelSelection,
209 runtimeMode: thread.runtimeMode,
210 interactionMode: thread.interactionMode,
211 };
212 }),
213 ),
214 writesThread((input) =>
215 Effect.gen(function* () {
216 const modelSelection = yield* required(input.modelSelection, "modelSelection");
217 const {
218 threads,
219 projection: { thread },
220 } = yield* readThread(input.threadId);
221 const type = modelSelectionCommandType(thread.providerInstanceId, modelSelection);
222 const result = yield* threads
223 .dispatch({ type, threadId: thread.id, commandId: yield* newCommandId(), modelSelection })
224 .pipe(Effect.mapError(dispatchFailure));
225 return { sequence: result.sequence };
226 }),
227 ),
228 ),
229 t3_pending_request: McpToolAccess.either(
230 (input) => input.action !== "respond",
231 McpToolAccess.reads((input) =>
232 Effect.gen(function* () {
233 if (input.action === "list") {
234 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
235 return {
236 requestIds: projection.runtimeRequests
237 .filter((request) => request.kind === "user_input" && request.status === "pending")
238 .map((request) => request.id),
239 };
240 }
241 const requestId = yield* required(input.requestId, "requestId");
242 const { item } = yield* readQuestion({ threadId: input.threadId, requestId });
243 return { requestId, questions: item.questions };
244 }),
245 ),
246 writesThread((input) =>
247 Effect.gen(function* () {
248 const requestId = yield* required(input.requestId, "requestId");
249 const answers = yield* required(input.answers, "answers");
250 const { threads, projection } = yield* readQuestion({
251 threadId: input.threadId,
252 requestId,
253 });
254 const result = yield* threads
255 .dispatch({
256 type: "runtime-request.respond",
257 threadId: projection.thread.id,
258 commandId: yield* newCommandId(),
259 requestId,
260 answers,
261 })
262 .pipe(Effect.mapError(dispatchFailure));
263 return { sequence: result.sequence };
264 }),
265 ),
266 ),
267 t3_queue: McpToolAccess.either(
268 (input) => input.action === "list" || input.action === "read",
269 McpToolAccess.reads((input) =>
270 Effect.gen(function* () {
271 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
272 if (input.action === "list") {
273 const runs = queuedRunsInDeliveryOrder(projection);
274 const cursor = input.cursor ?? 0;
275 const end = cursor + (input.limit ?? 20);
276 return {
277 items: runs.slice(cursor, end).flatMap((run) => {
278 const entry = queueEntry(projection, run.id, 1000);
279 return entry === undefined ? [] : [entry];
280 }),
281 nextCursor: end < runs.length ? end : null,
282 };
283 }
284 const queuedRunId = yield* required(input.queuedRunId, "queuedRunId");
285 return (
286 queueEntry(projection, queuedRunId, 16000) ??
287 (yield* new OrchestratorMcpFailure({
288 code: "invalid_request",
289 message: "The queued message was not found.",
290 }))
291 );
292 }),
293 ),
294 writesThread((input) =>
295 Effect.gen(function* () {
296 const runId = yield* required(input.queuedRunId, "queuedRunId");
297 switch (input.action) {
298 case "edit": {
299 const text = yield* required(input.text, "text");
300 return yield* dispatch(input.threadId, (common) => ({
301 ...common,
302 type: "queued-run.edit",
303 runId,
304 text,
305 }));
306 }
307 case "reorder": {
308 const beforeRunId = yield* required(input.beforeRunId, "beforeRunId");
309 return yield* dispatch(input.threadId, (common) => ({
310 ...common,
311 type: "queued-run.reorder",
312 runId,
313 beforeRunId,
314 }));
315 }
316 case "promote_to_steer": {
317 const targetRunId = yield* required(input.targetRunId, "targetRunId");
318 return yield* dispatch(input.threadId, (common) => ({
319 ...common,
320 type: "queued-message.promote-to-steer",
321 queuedRunId: runId,
322 targetRunId,
323 }));
324 }
325 default:
326 return yield* dispatch(input.threadId, (common) => ({
327 ...common,
328 type: "queued-run.cancel",
329 runId,
330 }));
331 }
332 }),
333 ),
334 ),
335 t3_thread_organize: writesThread((input) =>
336 Effect.gen(function* () {
337 const { threads, projection, caller } = yield* readThread(input.threadId);
338 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
339 if (input.action === "settle") {
340 return yield* threads
341 .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
342 .pipe(Effect.mapError(dispatchFailure));
343 }
344 let command: OrchestrationV2Command;
345 switch (input.action) {
346 case "snooze":
347 if (input.snoozedUntil === undefined) {
348 return yield* new OrchestratorMcpFailure({
349 code: "invalid_request",
350 message: "snooze requires snoozedUntil.",
351 });
352 }
353 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
354 break;
355 case "unsnooze":
356 case "unsettle":
357 command = { ...common, type: `thread.${input.action}`, reason: "user" };
358 break;
359 case "mark_unread":
360 command = { ...common, type: "thread.mark-unread" };
361 break;
362 default:
363 command = { ...common, type: `thread.${input.action}` };
364 }
365 const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
366 return { sequence: result.sequence };
367 }),
368 ),
369});