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