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

handlers.ts

330 lines11.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";
12import { formatThreadLink } from "@t3tools/shared/threadLinks";
13​
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});
79const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
80 handle: (params: P) => Effect.Effect<A, E, R>,
81) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
82​
83export const layer = McpToolAccess.toLayer(ThreadToolkit, {
84 run_scheduled_task_now: McpToolAccess.writesEnvironment((input) =>
85 Effect.gen(function* () {
86 const scheduler = yield* ScheduledTasks.ScheduledTaskService;
87 const { tasks } = yield* scheduler.list().pipe(Effect.mapError(unavailable));
88 if (!tasks.some((task) => task.id === input.taskId))
89 return yield* new OrchestratorMcpFailure({
90 code: "invalid_request",
91 message: "The scheduled task was not found.",
92 });
93 const { task, threadId } = yield* scheduler
94 .runNow({ id: input.taskId })
95 .pipe(Effect.mapError(unavailable));
96 return {
97 taskId: task.id,
98 threadId,
99 lastRunStatus: task.lastRunStatus,
100 runCount: task.runCount,
101 nextRunAt: task.nextRunAt,
102 };
103 }),
104 ),
105 t3_thread_search: McpToolAccess.reads((input) =>
106 Effect.gen(function* () {
107 const { caller } = yield* readCaller();
108 const threadSearch = yield* ThreadSearch.ThreadSearch;
109 const { matches } = yield* threadSearch
110 .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId })
111 .pipe(Effect.mapError(unavailable));
112 return {
113 matches: matches.map((match) => ({
114 ...match,
115 link: formatThreadLink(match.threadId, match.title),
116 })),
117 };
118 }),
119 ),
120 t3_thread_fork: writesThread((input) =>
121 Effect.gen(function* () {
122 const { threads, projection } = yield* readThread(input.threadId);
123 const commandId = yield* newCommandId();
124 const targetThreadId = ThreadId.make(`${commandId}:fork`);
125 const result = yield* threads
126 .dispatch({
127 type: "thread.fork",
128 commandId,
129 sourceThreadId: projection.thread.id,
130 targetThreadId,
131 sourcePoint: input.sourcePoint,
132 ...(input.title === undefined ? {} : { title: input.title }),
133 createdBy: "agent",
134 creationSource: "mcp",
135 })
136 .pipe(Effect.mapError(dispatchFailure));
137 return { sequence: result.sequence, targetThreadId };
138 }),
139 ),
140 t3_thread_merge_back: McpToolAccess.writesThreads(
141 (input) => [input.targetThreadId, input.sourceThreadId],
142 (input) =>
143 Effect.gen(function* () {
144 const context = yield* readThread(input.targetThreadId);
145 const source = yield* readThread(input.sourceThreadId);
146 const result = yield* context.threads
147 .dispatch({
148 type: "thread.merge_back",
149 commandId: yield* newCommandId(),
150 sourceThreadId: source.projection.thread.id,
151 targetThreadId: input.targetThreadId,
152 sourcePoint: input.sourcePoint,
153 createdBy: "agent",
154 creationSource: "mcp",
155 })
156 .pipe(Effect.mapError(dispatchFailure));
157 return { sequence: result.sequence, targetThreadId: input.targetThreadId };
158 }),
159 ),
160 t3_thread_transfers: McpToolAccess.reads((input) =>
161 Effect.gen(function* () {
162 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
163 return {
164 transfers: projection.contextTransfers.map(
165 ({ id, sourceThreadId, targetThreadId, status }) => ({
166 id,
167 sourceThreadId,
168 targetThreadId,
169 status,
170 }),
171 ),
172 };
173 }),
174 ),
175 t3_thread_configuration: McpToolAccess.reads((input) =>
176 Effect.gen(function* () {
177 const {
178 projection: { thread },
179 } = yield* readThread(input.threadId);
180 return {
181 threadId: thread.id,
182 modelSelection: thread.modelSelection,
183 runtimeMode: thread.runtimeMode,
184 interactionMode: thread.interactionMode,
185 };
186 }),
187 ),
188 t3_thread_configure: writesThread((input) =>
189 Effect.gen(function* () {
190 const {
191 threads,
192 projection: { thread },
193 } = yield* readThread(input.threadId);
194 const type = modelSelectionCommandType(thread.providerInstanceId, input.modelSelection);
195 const result = yield* threads
196 .dispatch({
197 type,
198 threadId: thread.id,
199 commandId: yield* newCommandId(),
200 modelSelection: input.modelSelection,
201 })
202 .pipe(Effect.mapError(dispatchFailure));
203 return { sequence: result.sequence };
204 }),
205 ),
206 t3_pending_request_list: McpToolAccess.reads((input) =>
207 Effect.gen(function* () {
208 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
209 return {
210 requestIds: projection.runtimeRequests
211 .filter((request) => request.kind === "user_input" && request.status === "pending")
212 .map((request) => request.id),
213 };
214 }),
215 ),
216 t3_pending_request_read: McpToolAccess.reads((input) =>
217 Effect.gen(function* () {
218 const { item } = yield* readQuestion(input);
219 return { requestId: input.requestId, questions: item.questions };
220 }),
221 ),
222 t3_pending_request_respond: writesThread((input) =>
223 Effect.gen(function* () {
224 const { threads, projection } = yield* readQuestion(input);
225 const result = yield* threads
226 .dispatch({
227 type: "runtime-request.respond",
228 threadId: projection.thread.id,
229 commandId: yield* newCommandId(),
230 requestId: input.requestId,
231 answers: input.answers,
232 })
233 .pipe(Effect.mapError(dispatchFailure));
234 return { sequence: result.sequence };
235 }),
236 ),
237 t3_queue_list: McpToolAccess.reads((input) =>
238 Effect.gen(function* () {
239 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
240 const runs = queuedRunsInDeliveryOrder(projection);
241 const cursor = input.cursor ?? 0;
242 const end = cursor + (input.limit ?? 20);
243 return {
244 items: runs.slice(cursor, end).flatMap((run) => {
245 const entry = queueEntry(projection, run.id, 1000);
246 return entry === undefined ? [] : [entry];
247 }),
248 nextCursor: end < runs.length ? end : null,
249 };
250 }),
251 ),
252 t3_queue_read: McpToolAccess.reads((input) =>
253 Effect.gen(function* () {
254 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
255 const entry = queueEntry(projection, input.queuedRunId, 16000);
256 return (
257 entry ??
258 (yield* new OrchestratorMcpFailure({
259 code: "invalid_request",
260 message: "The queued message was not found.",
261 }))
262 );
263 }),
264 ),
265 t3_queue_edit: writesThread((input) =>
266 dispatch(input.threadId, (common) => ({
267 ...common,
268 type: "queued-run.edit",
269 runId: input.queuedRunId,
270 text: input.text,
271 })),
272 ),
273 t3_queue_cancel: writesThread((input) =>
274 dispatch(input.threadId, (common) => ({
275 ...common,
276 type: "queued-run.cancel",
277 runId: input.queuedRunId,
278 })),
279 ),
280 t3_queue_reorder: writesThread((input) =>
281 dispatch(input.threadId, (common) => ({
282 ...common,
283 type: "queued-run.reorder",
284 runId: input.queuedRunId,
285 beforeRunId: input.beforeRunId,
286 })),
287 ),
288 t3_queue_promote_to_steer: writesThread((input) =>
289 dispatch(input.threadId, (common) => ({
290 ...common,
291 type: "queued-message.promote-to-steer",
292 queuedRunId: input.queuedRunId,
293 targetRunId: input.targetRunId,
294 })),
295 ),
296 t3_thread_organize: writesThread((input) =>
297 Effect.gen(function* () {
298 const { threads, projection, caller } = yield* readThread(input.threadId);
299 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
300 if (input.action === "settle") {
301 return yield* threads
302 .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
303 .pipe(Effect.mapError(dispatchFailure));
304 }
305 let command: OrchestrationV2Command;
306 switch (input.action) {
307 case "snooze":
308 if (input.snoozedUntil === undefined) {
309 return yield* new OrchestratorMcpFailure({
310 code: "invalid_request",
311 message: "snooze requires snoozedUntil.",
312 });
313 }
314 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
315 break;
316 case "unsnooze":
317 case "unsettle":
318 command = { ...common, type: `thread.${input.action}`, reason: "user" };
319 break;
320 case "mark_unread":
321 command = { ...common, type: "thread.mark-unread" };
322 break;
323 default:
324 command = { ...common, type: `thread.${input.action}` };
325 }
326 const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
327 return { sequence: result.sequence };
328 }),
329 ),
330});