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