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