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

handlers.ts

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