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