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

handlers.ts

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