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

handlers.ts

370 lines13.7 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 { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
273 if (input.action === "list") {
274 const runs = queuedRunsInDeliveryOrder(projection);
275 const cursor = input.cursor ?? 0;
276 const end = cursor + (input.limit ?? 20);
277 return {
278 items: runs.slice(cursor, end).flatMap((run) => {
279 const entry = queueEntry(projection, run.id, 1000);
280 return entry === undefined ? [] : [entry];
281 }),
282 nextCursor: end < runs.length ? end : null,
283 };
284 }
285 const queuedRunId = yield* required(input.queuedRunId, "queuedRunId");
286 return (
287 queueEntry(projection, queuedRunId, 16000) ??
288 (yield* new OrchestratorMcpFailure({
289 code: "invalid_request",
290 message: "The queued message was not found.",
291 }))
292 );
293 }),
294 ),
295 writesThread((input) =>
296 Effect.gen(function* () {
297 const runId = yield* required(input.queuedRunId, "queuedRunId");
298 switch (input.action) {
299 case "edit": {
300 const text = yield* required(input.text, "text");
301 return yield* dispatch(input.threadId, (common) => ({
302 ...common,
303 type: "queued-run.edit",
304 runId,
305 text,
306 }));
307 }
308 case "reorder": {
309 const beforeRunId = yield* required(input.beforeRunId, "beforeRunId");
310 return yield* dispatch(input.threadId, (common) => ({
311 ...common,
312 type: "queued-run.reorder",
313 runId,
314 beforeRunId,
315 }));
316 }
317 case "promote_to_steer": {
318 const targetRunId = yield* required(input.targetRunId, "targetRunId");
319 return yield* dispatch(input.threadId, (common) => ({
320 ...common,
321 type: "queued-message.promote-to-steer",
322 queuedRunId: runId,
323 targetRunId,
324 }));
325 }
326 default:
327 return yield* dispatch(input.threadId, (common) => ({
328 ...common,
329 type: "queued-run.cancel",
330 runId,
331 }));
332 }
333 }),
334 ),
335 ),
336 t3_thread_organize: writesThread((input) =>
337 Effect.gen(function* () {
338 const { threads, projection, caller } = yield* readThread(input.threadId);
339 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
340 if (input.action === "settle") {
341 return yield* threads
342 .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
343 .pipe(Effect.mapError(dispatchFailure));
344 }
345 let command: OrchestrationV2Command;
346 switch (input.action) {
347 case "snooze":
348 if (input.snoozedUntil === undefined) {
349 return yield* new OrchestratorMcpFailure({
350 code: "invalid_request",
351 message: "snooze requires snoozedUntil.",
352 });
353 }
354 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
355 break;
356 case "unsnooze":
357 case "unsettle":
358 command = { ...common, type: `thread.${input.action}`, reason: "user" };
359 break;
360 case "mark_unread":
361 command = { ...common, type: "thread.mark-unread" };
362 break;
363 default:
364 command = { ...common, type: `thread.${input.action}` };
365 }
366 const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
367 return { sequence: result.sequence };
368 }),
369 ),
370});