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";
12import { topOfPinnedRunOrderKey } from "@t3tools/shared/pinOrderKey";
13
14import * as McpInvocationContext from "../../McpInvocationContext.ts";
15import * as McpToolAccess from "../../McpToolAccess.ts";
16import {
17 dispatchFailure,
18 newCommandId,
19 readCaller,
20 readThread,
21 unavailable,
22} from "../../threadAccess.ts";
23import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
24import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
25import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
26import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
27import { ThreadToolkit } from "./tools.ts";
28
29function queueEntry(
30 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">,
31 runId: RunId,
32 limit: number,
33) {
34 const run = projection.runs.find((run) => run.id === runId && run.status === "queued");
35 const message = projection.messages.find((message) => message.id === run?.userMessageId);
36 if (run === undefined || message === undefined) return undefined;
37 const characters = Array.from(message.text);
38 return {
39 queuedRunId: run.id,
40 text: characters.slice(0, limit).join(""),
41 truncated: characters.length > limit,
42 };
43}
44const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
45 threadId: ThreadId | undefined,
46 command: (common: { commandId: CommandId; threadId: ThreadId }) => OrchestrationV2Command,
47) {
48 const { threads, projection } = yield* readThread(threadId);
49 const result = yield* threads
50 .dispatch(command({ commandId: yield* newCommandId(), threadId: projection.thread.id }))
51 .pipe(Effect.mapError(dispatchFailure));
52 return { sequence: result.sequence };
53});
54
55/**
56 * Places an agent pin at the top of the Pinned section, as a client pin is placed.
57 * Without a key the sidebar sorts the pin below every keyed pin. Ordering is
58 * best effort: if the index cannot be read, the pin still lands, keyless.
59 */
60const topOfPinnedRunKey = Effect.fn("mcp.topOfPinnedRunKey")(function* (
61 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "listActiveShellIndex">,
62) {
63 const index = yield* threads.listActiveShellIndex().pipe(Effect.orElseSucceed(() => null));
64 if (index === null) return undefined;
65 const pinnedKeys = index.flatMap((entry) => (entry.pinnedAt == null ? [] : [entry.pinOrderKey]));
66 return topOfPinnedRunOrderKey(pinnedKeys) ?? undefined;
67});
68
69const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: {
70 threadId?: ThreadId | undefined;
71 requestId: RuntimeRequestId;
72}) {
73 const context = yield* readThread(input.threadId, ["runtimeRequests", "turnItems"]);
74 const request = context.projection.runtimeRequests.find(
75 (request) => request.id === input.requestId && request.kind === "user_input",
76 );
77 const item = context.projection.turnItems.find(
78 (item) => item.type === "user_input_request" && item.requestId === input.requestId,
79 );
80 if (request === undefined || item?.type !== "user_input_request")
81 return yield* new OrchestratorMcpFailure({
82 code: "invalid_request",
83 message: "The pending user-input request was not found.",
84 });
85 if (request.status !== "pending")
86 return yield* new OrchestratorMcpFailure({
87 code: "invalid_request",
88 message:
89 request.status === "resolved"
90 ? "The user-input request was already answered."
91 : `The user-input request is no longer pending (${request.status}).`,
92 });
93 return { ...context, request, item };
94});
95/** A field the chosen action needs. `null` counts as given, as in `beforeRunId: null`. */
96const required = <A>(value: A | undefined, name: string) =>
97 value === undefined
98 ? Effect.fail(
99 new OrchestratorMcpFailure({
100 code: "invalid_request",
101 message: `This action needs \`${name}\`.`,
102 }),
103 )
104 : Effect.succeed(value);
105const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
106 handle: (params: P) => Effect.Effect<A, E, R>,
107) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
108
109export const layer = McpToolAccess.toLayer(ThreadToolkit, {
110 run_scheduled_task_now: McpToolAccess.writesEnvironment((input) =>
111 Effect.gen(function* () {
112 const scheduler = yield* ScheduledTasks.ScheduledTaskService;
113 const { tasks } = yield* scheduler.list().pipe(Effect.mapError(unavailable));
114 if (!tasks.some((task) => task.id === input.taskId))
115 return yield* new OrchestratorMcpFailure({
116 code: "invalid_request",
117 message: "The scheduled task was not found.",
118 });
119 const { task, threadId } = yield* scheduler
120 .runNow({ id: input.taskId })
121 .pipe(
122 Effect.mapError(
123 (error) =>
124 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
125 ),
126 );
127 const scope = yield* McpInvocationContext.McpInvocationContext;
128 return {
129 taskId: task.id,
130 threadId,
131 ...(threadId === null
132 ? {}
133 : {
134 link: McpInvocationContext.threadLinkFor(scope, threadId),
135 }),
136 lastRunStatus: task.lastRunStatus,
137 lastRunError: task.lastRunError,
138 runCount: task.runCount,
139 nextRunAt: task.nextRunAt,
140 };
141 }),
142 ),
143 t3_thread_search: McpToolAccess.reads((input) =>
144 Effect.gen(function* () {
145 const { caller } = yield* readCaller();
146 const scope = yield* McpInvocationContext.McpInvocationContext;
147 const threadSearch = yield* ThreadSearch.ThreadSearch;
148 const { matches } = yield* threadSearch
149 .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId })
150 .pipe(Effect.mapError(unavailable));
151 return {
152 currentThreadId: scope.thread?.threadId ?? null,
153 matches: matches.map((match) => ({
154 ...match,
155 link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title),
156 })),
157 };
158 }),
159 ),
160 t3_thread_transfer: McpToolAccess.either(
161 (input) => input.action === "status",
162 McpToolAccess.reads((input) =>
163 Effect.gen(function* () {
164 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
165 return {
166 transfers: projection.contextTransfers.map(
167 ({ id, sourceThreadId, targetThreadId, status }) => ({
168 id,
169 sourceThreadId,
170 targetThreadId,
171 status,
172 }),
173 ),
174 };
175 }),
176 ),
177 McpToolAccess.writesThreads(
178 (input) => [input.threadId, input.targetThreadId],
179 (input) =>
180 Effect.gen(function* () {
181 const sourcePoint = input.sourcePoint ?? { type: "latest_stable" as const };
182 const { threads, projection } = yield* readThread(input.threadId);
183 const commandId = yield* newCommandId();
184 if (input.action === "merge_back") {
185 const targetThreadId = yield* required(input.targetThreadId, "targetThreadId");
186 yield* readThread(targetThreadId);
187 const result = yield* threads
188 .dispatch({
189 type: "thread.merge_back",
190 commandId,
191 sourceThreadId: projection.thread.id,
192 targetThreadId,
193 sourcePoint,
194 createdBy: "agent",
195 creationSource: "mcp",
196 })
197 .pipe(Effect.mapError(dispatchFailure));
198 return { sequence: result.sequence, targetThreadId };
199 }
200 const targetThreadId = ThreadId.make(`${commandId}:fork`);
201 const result = yield* threads
202 .dispatch({
203 type: "thread.fork",
204 commandId,
205 sourceThreadId: projection.thread.id,
206 targetThreadId,
207 sourcePoint,
208 ...(input.title === undefined ? {} : { title: input.title }),
209 createdBy: "agent",
210 creationSource: "mcp",
211 })
212 .pipe(Effect.mapError(dispatchFailure));
213 return { sequence: result.sequence, targetThreadId };
214 }),
215 ),
216 ),
217 t3_thread_configure: McpToolAccess.either(
218 (input) => input.modelSelection === undefined,
219 McpToolAccess.reads((input) =>
220 Effect.gen(function* () {
221 const {
222 projection: { thread },
223 } = yield* readThread(input.threadId);
224 return {
225 threadId: thread.id,
226 modelSelection: thread.modelSelection,
227 runtimeMode: thread.runtimeMode,
228 interactionMode: thread.interactionMode,
229 };
230 }),
231 ),
232 writesThread((input) =>
233 Effect.gen(function* () {
234 const modelSelection = yield* required(input.modelSelection, "modelSelection");
235 const {
236 threads,
237 projection: { thread },
238 } = yield* readThread(input.threadId);
239 const type = modelSelectionCommandType(thread.providerInstanceId, modelSelection);
240 const result = yield* threads
241 .dispatch({ type, threadId: thread.id, commandId: yield* newCommandId(), modelSelection })
242 .pipe(Effect.mapError(dispatchFailure));
243 return { sequence: result.sequence };
244 }),
245 ),
246 ),
247 t3_pending_request: McpToolAccess.either(
248 (input) => input.action !== "respond",
249 McpToolAccess.reads((input) =>
250 Effect.gen(function* () {
251 if (input.action === "list") {
252 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
253 return {
254 requestIds: projection.runtimeRequests
255 .filter((request) => request.kind === "user_input" && request.status === "pending")
256 .map((request) => request.id),
257 };
258 }
259 const requestId = yield* required(input.requestId, "requestId");
260 const { item } = yield* readQuestion({ threadId: input.threadId, requestId });
261 return { requestId, questions: item.questions };
262 }),
263 ),
264 writesThread((input) =>
265 Effect.gen(function* () {
266 const requestId = yield* required(input.requestId, "requestId");
267 const answers = yield* required(input.answers, "answers");
268 const { threads, projection } = yield* readQuestion({
269 threadId: input.threadId,
270 requestId,
271 });
272 const result = yield* threads
273 .dispatch({
274 type: "runtime-request.respond",
275 threadId: projection.thread.id,
276 commandId: yield* newCommandId(),
277 requestId,
278 answers,
279 })
280 .pipe(Effect.mapError(dispatchFailure));
281 return { sequence: result.sequence };
282 }),
283 ),
284 ),
285 t3_queue: McpToolAccess.either(
286 (input) => input.action === "list" || input.action === "read",
287 McpToolAccess.reads((input) =>
288 Effect.gen(function* () {
289 const { threads, projection: queued } = yield* readThread(input.threadId, ["runs"], {
290 runStatuses: ["queued"],
291 });
292 const messages = yield* threads
293 .getMessagesById(
294 queued.thread.id,
295 queued.runs.map((run) => run.userMessageId),
296 )
297 .pipe(Effect.mapError(unavailable));
298 const projection = { runs: queued.runs, messages: [...messages.values()] };
299 if (input.action === "list") {
300 const runs = queuedRunsInDeliveryOrder(projection);
301 const cursor = input.cursor ?? 0;
302 const end = cursor + (input.limit ?? 20);
303 return {
304 items: runs.slice(cursor, end).flatMap((run) => {
305 const entry = queueEntry(projection, run.id, 1000);
306 return entry === undefined ? [] : [entry];
307 }),
308 nextCursor: end < runs.length ? end : null,
309 };
310 }
311 const queuedRunId = yield* required(input.queuedRunId, "queuedRunId");
312 return (
313 queueEntry(projection, queuedRunId, 16000) ??
314 (yield* new OrchestratorMcpFailure({
315 code: "invalid_request",
316 message: "The queued message was not found.",
317 }))
318 );
319 }),
320 ),
321 writesThread((input) =>
322 Effect.gen(function* () {
323 const runId = yield* required(input.queuedRunId, "queuedRunId");
324 switch (input.action) {
325 case "edit": {
326 const text = yield* required(input.text, "text");
327 return yield* dispatch(input.threadId, (common) => ({
328 ...common,
329 type: "queued-run.edit",
330 runId,
331 text,
332 }));
333 }
334 case "reorder": {
335 const beforeRunId = yield* required(input.beforeRunId, "beforeRunId");
336 return yield* dispatch(input.threadId, (common) => ({
337 ...common,
338 type: "queued-run.reorder",
339 runId,
340 beforeRunId,
341 }));
342 }
343 case "promote_to_steer": {
344 const targetRunId = yield* required(input.targetRunId, "targetRunId");
345 return yield* dispatch(input.threadId, (common) => ({
346 ...common,
347 type: "queued-message.promote-to-steer",
348 queuedRunId: runId,
349 targetRunId,
350 }));
351 }
352 default:
353 return yield* dispatch(input.threadId, (common) => ({
354 ...common,
355 type: "queued-run.cancel",
356 runId,
357 }));
358 }
359 }),
360 ),
361 ),
362 t3_thread_organize: writesThread((input) =>
363 Effect.gen(function* () {
364 const { threads, projection, caller } = yield* readThread(input.threadId);
365 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
366 if (input.action === "settle") {
367 return yield* threads
368 .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
369 .pipe(Effect.mapError(dispatchFailure));
370 }
371 let command: OrchestrationV2Command;
372 switch (input.action) {
373 case "snooze":
374 if (input.snoozedUntil === undefined) {
375 return yield* new OrchestratorMcpFailure({
376 code: "invalid_request",
377 message: "snooze requires snoozedUntil.",
378 });
379 }
380 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
381 break;
382 case "unsnooze":
383 case "unsettle":
384 command = { ...common, type: `thread.${input.action}`, reason: "user" };
385 break;
386 case "mark_unread":
387 command = { ...common, type: "thread.mark-unread" };
388 break;
389 case "pin": {
390 // Always send a key, as the client does: the reducer ignores it for a
391 // thread that is already pinned, and a projection read before this
392 // command can be stale if an unpin commits in between.
393 const orderKey = yield* topOfPinnedRunKey(threads);
394 command = { ...common, type: "thread.pin", ...(orderKey ? { orderKey } : {}) };
395 break;
396 }
397 default:
398 command = { ...common, type: `thread.${input.action}` };
399 }
400 const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
401 return { sequence: result.sequence };
402 }),
403 ),
404});