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