Open History to see the last commit
1import {
2 CommandId,
3 isProviderAvailable,
4 MessageId,
5 type ModelSelection,
6 NodeId,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ThreadShell,
10 type OrchestrationV2TurnItem,
11 OrchestratorMcpFailure,
12 type OrchestratorMcpCapabilitiesResult,
13 type OrchestratorMcpCreateThreadsInput,
14 type OrchestratorMcpCreateThreadsResult,
15 type OrchestratorMcpCreatedThread,
16 type OrchestratorMcpDelegateTaskInput,
17 type OrchestratorMcpDelegateTaskResult,
18 type OrchestratorMcpInteractionMode,
19 type OrchestratorMcpDeleteScheduledTaskInput,
20 type OrchestratorMcpDeleteScheduledTaskResult,
21 type OrchestratorMcpListScheduledTasksResult,
22 type OrchestratorMcpRuntimeMode,
23 type OrchestratorMcpScheduledTask,
24 type OrchestratorMcpScheduleTaskInput,
25 type OrchestratorMcpScheduleTaskResult,
26 type OrchestratorMcpTarget,
27 type OrchestratorMcpTaskCancelInput,
28 type OrchestratorMcpTaskCancelResult,
29 type OrchestratorMcpUpdateScheduledTaskInput,
30 type OrchestratorMcpThreadDetail,
31 type OrchestratorMcpThreadInterruptInput,
32 type OrchestratorMcpThreadInterruptResult,
33 type OrchestratorMcpThreadListInput,
34 type OrchestratorMcpThreadListItem,
35 type OrchestratorMcpThreadListResult,
36 type OrchestratorMcpThreadReadInput,
37 type OrchestratorMcpThreadReadResult,
38 type OrchestratorMcpThreadRun,
39 type OrchestratorMcpThreadSendInput,
40 type OrchestratorMcpThreadSendResult,
41 type OrchestratorMcpThreadTimelineItem,
42 type OrchestratorMcpThreadWaitInput,
43 type OrchestratorMcpThreadWaitResult,
44 type ProviderInteractionMode,
45 ProviderInstanceId,
46 type RuntimeMode,
47 type ScheduledTask,
48 type ScheduledTaskUpsertInput,
49 type ServerProvider,
50 ThreadId,
51} from "@t3tools/contracts";
52import * as Context from "effect/Context";
53import * as Crypto from "effect/Crypto";
54import * as DateTime from "effect/DateTime";
55import * as Duration from "effect/Duration";
56import * as Effect from "effect/Effect";
57import * as Layer from "effect/Layer";
58import * as Option from "effect/Option";
59import * as Schema from "effect/Schema";
60
61import { isBuiltInProviderAdapterDriverV2 } from "../orchestration-v2/builtInProviderAdapterDrivers.ts";
62import { subagentResultForRun } from "../orchestration-v2/SubagentProjection.ts";
63import {
64 isActiveRun,
65 latestActiveRun,
66 latestRun,
67 ThreadManagementError,
68 ThreadManagementService,
69} from "../orchestration-v2/ThreadManagementService.ts";
70import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
71import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
72import type { McpInvocationScope } from "./McpInvocationContext.ts";
73
74const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
75const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
76const TASK_POLL_INTERVAL_MS = 50;
77const DEFAULT_THREAD_LIST_LIMIT = 50;
78const DEFAULT_THREAD_READ_LIMIT = 50;
79const DEFAULT_THREAD_RUN_LIMIT = 10;
80const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
81
82interface ResolvedTarget {
83 readonly modelSelection: ModelSelection;
84}
85
86type TerminalTaskStatus = Extract<
87 OrchestratorMcpDelegateTaskResult["status"],
88 "completed" | "failed" | "cancelled" | "interrupted"
89>;
90
91export interface OrchestratorMcpServiceShape {
92 readonly capabilities: (
93 scope: McpInvocationScope,
94 ) => Effect.Effect<OrchestratorMcpCapabilitiesResult, OrchestratorMcpFailure>;
95 readonly delegateTask: (
96 scope: McpInvocationScope,
97 input: OrchestratorMcpDelegateTaskInput,
98 ) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
99 readonly taskStatus: (
100 scope: McpInvocationScope,
101 taskId: NodeId,
102 ) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
103 readonly cancelTask: (
104 scope: McpInvocationScope,
105 input: OrchestratorMcpTaskCancelInput,
106 ) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
107 readonly createThreads: (
108 scope: McpInvocationScope,
109 input: OrchestratorMcpCreateThreadsInput,
110 ) => Effect.Effect<OrchestratorMcpCreateThreadsResult, OrchestratorMcpFailure>;
111 readonly scheduleTask: (
112 scope: McpInvocationScope,
113 input: OrchestratorMcpScheduleTaskInput,
114 ) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
115 readonly listScheduledTasks: (
116 scope: McpInvocationScope,
117 ) => Effect.Effect<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
118 readonly updateScheduledTask: (
119 scope: McpInvocationScope,
120 input: OrchestratorMcpUpdateScheduledTaskInput,
121 ) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
122 readonly deleteScheduledTask: (
123 scope: McpInvocationScope,
124 input: OrchestratorMcpDeleteScheduledTaskInput,
125 ) => Effect.Effect<OrchestratorMcpDeleteScheduledTaskResult, OrchestratorMcpFailure>;
126 readonly listThreads: (
127 scope: McpInvocationScope,
128 input: OrchestratorMcpThreadListInput,
129 ) => Effect.Effect<OrchestratorMcpThreadListResult, OrchestratorMcpFailure>;
130 readonly readThread: (
131 scope: McpInvocationScope,
132 input: OrchestratorMcpThreadReadInput,
133 ) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
134 readonly sendToThread: (
135 scope: McpInvocationScope,
136 input: OrchestratorMcpThreadSendInput,
137 ) => Effect.Effect<OrchestratorMcpThreadSendResult, OrchestratorMcpFailure>;
138 readonly waitForThread: (
139 scope: McpInvocationScope,
140 input: OrchestratorMcpThreadWaitInput,
141 ) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
142 readonly interruptThread: (
143 scope: McpInvocationScope,
144 input: OrchestratorMcpThreadInterruptInput,
145 ) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
146}
147
148export class OrchestratorMcpService extends Context.Service<
149 OrchestratorMcpService,
150 OrchestratorMcpServiceShape
151>()("t3/mcp/OrchestratorMcpService") {}
152
153const isThreadManagementError = Schema.is(ThreadManagementError);
154
155function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
156 return new OrchestratorMcpFailure({ code, message });
157}
158
159function errorMessage(error: unknown): string {
160 return error instanceof Error ? error.message : String(error);
161}
162
163/**
164 * Workspace strategy for a scheduled task created/updated over MCP: bound runs
165 * post into the existing thread (the strategy is unused, keep root); unbound
166 * runs launch a fresh worktree per run.
167 */
168function scheduledTaskWorkspaceStrategy(
169 boundToThread: boolean,
170): ScheduledTask["workspaceStrategy"] {
171 return boundToThread
172 ? { type: "root" }
173 : { type: "worktree", baseRef: "main", startFromOrigin: true };
174}
175
176function scheduledTaskSummary(task: ScheduledTask): OrchestratorMcpScheduledTask {
177 return {
178 scheduledTaskId: task.id,
179 title: task.title,
180 prompt: task.prompt,
181 enabled: task.enabled,
182 projectId: task.projectId,
183 boundThreadId: task.threadId,
184 schedule: task.schedule,
185 nextRunAt: task.nextRunAt,
186 lastRunStatus: task.lastRunStatus,
187 };
188}
189
190function providerConstraints(
191 provider: ServerProvider | undefined,
192 supportsOrchestrationV2: boolean,
193): ReadonlyArray<string> {
194 const constraints: Array<string> = [];
195 if (!supportsOrchestrationV2) {
196 constraints.push("No V2 provider adapter is registered.");
197 }
198 if (provider === undefined) return constraints;
199 if (!provider.enabled) constraints.push("Provider instance is disabled.");
200 if (!provider.installed) constraints.push("Provider executable is not installed.");
201 if (!isProviderAvailable(provider)) {
202 constraints.push(provider.unavailableReason ?? "Provider driver is unavailable.");
203 }
204 if (provider.status === "error" || provider.status === "disabled") {
205 constraints.push(provider.message ?? `Provider status is ${provider.status}.`);
206 }
207 if (provider.auth.status === "unauthenticated") {
208 constraints.push("Provider is not authenticated.");
209 }
210 return constraints;
211}
212
213function taskStatusForRun(
214 run: OrchestrationV2Run | undefined,
215): OrchestratorMcpDelegateTaskResult["status"] {
216 switch (run?.status) {
217 case "queued":
218 return "queued";
219 case "waiting":
220 return "waiting";
221 case "completed":
222 return "completed";
223 case "failed":
224 return "failed";
225 case "cancelled":
226 case "rolled_back":
227 return "cancelled";
228 case "interrupted":
229 return "interrupted";
230 case "preparing":
231 case "starting":
232 case "running":
233 case undefined:
234 return "running";
235 }
236}
237
238function isTerminalTaskStatus(
239 status: OrchestratorMcpDelegateTaskResult["status"],
240): status is TerminalTaskStatus {
241 return (
242 status === "completed" ||
243 status === "failed" ||
244 status === "cancelled" ||
245 status === "interrupted"
246 );
247}
248
249function runtimeModeRank(mode: RuntimeMode): number {
250 switch (mode) {
251 case "approval-required":
252 return 0;
253 case "auto-accept-edits":
254 return 1;
255 case "full-access":
256 return 2;
257 }
258}
259
260function interactionModeRank(mode: ProviderInteractionMode): number {
261 return mode === "plan" ? 0 : 1;
262}
263
264function resolveRuntimeMode(
265 parentMode: RuntimeMode,
266 requested: OrchestratorMcpRuntimeMode | undefined,
267): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {
268 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
269 return runtimeModeRank(resolved) > runtimeModeRank(parentMode)
270 ? Effect.fail(
271 failure(
272 "runtime_mode_escalation_denied",
273 `Child runtime mode ${resolved} is broader than parent mode ${parentMode}.`,
274 ),
275 )
276 : Effect.succeed(resolved);
277}
278
279function resolveInteractionMode(
280 parentMode: ProviderInteractionMode,
281 requested: OrchestratorMcpInteractionMode | undefined,
282): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {
283 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
284 return interactionModeRank(resolved) > interactionModeRank(parentMode)
285 ? Effect.fail(
286 failure(
287 "interaction_mode_escalation_denied",
288 `Child interaction mode ${resolved} is broader than parent mode ${parentMode}.`,
289 ),
290 )
291 : Effect.succeed(resolved);
292}
293
294function stablePart(value: string): string {
295 return encodeURIComponent(value);
296}
297
298function stableCommandId(input: {
299 readonly scope: McpInvocationScope;
300 readonly requestKey: string;
301 readonly operation: string;
302 readonly index?: number;
303}): CommandId {
304 return CommandId.make(
305 [
306 "command",
307 "mcp",
308 stablePart(input.scope.providerSessionId),
309 stablePart(input.operation),
310 stablePart(input.requestKey),
311 ...(input.index === undefined ? [] : [String(input.index)]),
312 ].join(":"),
313 );
314}
315
316function stableThreadId(input: {
317 readonly scope: McpInvocationScope;
318 readonly requestKey: string;
319 readonly index: number;
320}): ThreadId {
321 return ThreadId.make(
322 [
323 "thread",
324 "mcp",
325 stablePart(input.scope.providerSessionId),
326 stablePart(input.requestKey),
327 String(input.index),
328 ].join(":"),
329 );
330}
331
332function stableMessageId(input: {
333 readonly scope: McpInvocationScope;
334 readonly requestKey: string;
335 readonly index: number;
336}): MessageId {
337 return MessageId.make(
338 [
339 "message",
340 "mcp",
341 stablePart(input.scope.providerSessionId),
342 stablePart(input.requestKey),
343 String(input.index),
344 ].join(":"),
345 );
346}
347
348function stableOperationMessageId(input: {
349 readonly scope: McpInvocationScope;
350 readonly requestKey: string;
351 readonly operation: string;
352}): MessageId {
353 return MessageId.make(
354 [
355 "message",
356 "mcp",
357 stablePart(input.scope.providerSessionId),
358 stablePart(input.operation),
359 stablePart(input.requestKey),
360 ].join(":"),
361 );
362}
363
364function threadTitle(input: {
365 readonly parentTitle: string;
366 readonly prompt: string | undefined;
367 readonly title: string | undefined;
368 readonly index: number;
369}): string {
370 const detail = input.title?.trim() || input.prompt?.trim();
371 if (!detail) return `${input.parentTitle} thread ${input.index + 1}`;
372 return detail.length > 80 ? `${detail.slice(0, 77)}...` : detail;
373}
374
375function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string {
376 return input.role === undefined || input.role === "general"
377 ? input.task
378 : `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`;
379}
380
381function listItemFromShell(shell: OrchestrationV2ThreadShell): OrchestratorMcpThreadListItem {
382 return {
383 threadId: shell.id,
384 title: shell.title,
385 createdBy: shell.createdBy,
386 creationSource: shell.creationSource,
387 status: shell.status,
388 latestRunId: shell.latestRunId,
389 providerInstanceId: shell.modelSelection.instanceId,
390 model: shell.modelSelection.model,
391 runtimeMode: shell.runtimeMode,
392 interactionMode: shell.interactionMode,
393 parentThreadId: shell.lineage.parentThreadId,
394 relationshipToParent: shell.lineage.relationshipToParent,
395 itemCount: shell.visibleItemCount,
396 createdAt: DateTime.formatIso(shell.createdAt),
397 updatedAt: DateTime.formatIso(shell.updatedAt),
398 };
399}
400
401function threadDetail(projection: OrchestrationV2ThreadProjection): OrchestratorMcpThreadDetail {
402 const latest = latestRun(projection);
403 const active = latestActiveRun(projection);
404 return {
405 threadId: projection.thread.id,
406 projectId: projection.thread.projectId,
407 title: projection.thread.title,
408 createdBy: projection.thread.createdBy,
409 creationSource: projection.thread.creationSource,
410 status: latest?.status ?? "idle",
411 latestRunId: latest?.id ?? null,
412 activeRunId: active?.id ?? null,
413 providerInstanceId: projection.thread.modelSelection.instanceId,
414 model: projection.thread.modelSelection.model,
415 runtimeMode: projection.thread.runtimeMode,
416 interactionMode: projection.thread.interactionMode,
417 branch: projection.thread.branch,
418 worktreePath: projection.thread.worktreePath,
419 parentThreadId: projection.thread.lineage.parentThreadId,
420 relationshipToParent: projection.thread.lineage.relationshipToParent,
421 runCount: projection.runs.length,
422 itemCount: projection.visibleTurnItems.length,
423 pendingRequestCount: projection.runtimeRequests.filter(
424 (request) => request.status === "pending",
425 ).length,
426 archived: projection.thread.archivedAt !== null,
427 createdAt: DateTime.formatIso(projection.thread.createdAt),
428 updatedAt: DateTime.formatIso(projection.updatedAt),
429 };
430}
431
432function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun {
433 return {
434 runId: run.id,
435 ordinal: run.ordinal,
436 status: run.status,
437 providerInstanceId: run.modelSelection.instanceId,
438 model: run.modelSelection.model,
439 requestedAt: DateTime.formatIso(run.requestedAt),
440 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
441 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
442 };
443}
444
445function jsonText(value: unknown): string {
446 try {
447 return JSON.stringify(value, null, 2);
448 } catch {
449 return String(value);
450 }
451}
452
453function turnItemText(item: OrchestrationV2TurnItem): string | null {
454 switch (item.type) {
455 case "user_message":
456 case "assistant_message":
457 case "reasoning":
458 return item.text;
459 case "proposed_plan":
460 return item.markdown;
461 case "todo_list":
462 return [item.explanation, ...item.steps.map((step) => `[${step.status}] ${step.text}`)]
463 .filter((line): line is string => line !== undefined)
464 .join("\n");
465 case "user_input_request":
466 return jsonText(item.questions);
467 case "file_change":
468 return [
469 item.fileName,
470 item.additions === undefined && item.deletions === undefined
471 ? undefined
472 : `+${item.additions ?? 0} -${item.deletions ?? 0}`,
473 item.diffStr ?? item.newStr,
474 ]
475 .filter((line): line is string => line !== undefined)
476 .join("\n");
477 case "command_execution":
478 return [`$ ${item.input}`, item.output]
479 .filter((line): line is string => line !== undefined)
480 .join("\n");
481 case "file_search":
482 return jsonText({ pattern: item.pattern, results: item.results });
483 case "web_search":
484 return jsonText({ patterns: item.patterns, results: item.results });
485 case "approval_request":
486 return item.prompt ?? item.requestKind;
487 case "checkpoint":
488 return jsonText(item.files);
489 case "run_interrupt_request":
490 case "run_interrupt_result":
491 return item.message;
492 case "error":
493 return item.failure.message;
494 case "compaction":
495 return item.summary ?? null;
496 case "handoff":
497 return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`;
498 case "fork":
499 return `Forked to thread ${item.targetThreadId}.`;
500 case "thread_created":
501 return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
502 case "subagent":
503 return item.result ?? item.progress ?? item.prompt;
504 case "dynamic_tool":
505 return jsonText({ toolName: item.toolName, input: item.input, output: item.output });
506 }
507}
508
509function timelineItem(input: {
510 readonly row: OrchestrationV2ThreadProjection["visibleTurnItems"][number];
511 readonly maxChars: number;
512 readonly projection: OrchestrationV2ThreadProjection;
513}): OrchestratorMcpThreadTimelineItem {
514 const text = turnItemText(input.row.item);
515 const textTruncated = text !== null && text.length > input.maxChars;
516 const messageId =
517 input.row.item.type === "user_message" || input.row.item.type === "assistant_message"
518 ? input.row.item.messageId
519 : null;
520 const message =
521 messageId === null
522 ? undefined
523 : input.projection.messages.find((candidate) => candidate.id === messageId);
524 return {
525 position: input.row.position,
526 visibility: input.row.visibility,
527 sourceThreadId: input.row.sourceThreadId,
528 itemId: input.row.sourceItemId,
529 runId: input.row.item.runId,
530 messageId,
531 createdBy: message?.createdBy ?? null,
532 creationSource: message?.creationSource ?? null,
533 type: input.row.item.type,
534 status: input.row.item.status,
535 title: input.row.item.title,
536 text: textTruncated ? `${text.slice(0, input.maxChars)}\n…[truncated]` : text,
537 textTruncated,
538 updatedAt: DateTime.formatIso(input.row.item.updatedAt),
539 };
540}
541
542const make = Effect.gen(function* () {
543 const crypto = yield* Crypto.Crypto;
544 const threadManagement = yield* ThreadManagementService;
545 const providerRegistry = yield* ProviderRegistry;
546 const scheduledTasks = yield* ScheduledTaskService;
547
548 const requireCapability = (scope: McpInvocationScope) =>
549 scope.capabilities.has("orchestration")
550 ? Effect.void
551 : Effect.fail(
552 failure(
553 "capability_denied",
554 "This MCP credential does not grant orchestration capabilities.",
555 ),
556 );
557
558 const loadProjection = (threadId: ThreadId) =>
559 threadManagement
560 .getThreadProjection(threadId)
561 .pipe(
562 Effect.mapError((error) =>
563 failure(
564 "orchestration_error",
565 `Unable to read thread ${threadId}: ${errorMessage(error)}`,
566 ),
567 ),
568 );
569
570 const loadProjectThread = (
571 projectId: OrchestrationV2ThreadProjection["thread"]["projectId"],
572 threadId: ThreadId,
573 ): Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorMcpFailure> =>
574 threadManagement
575 .getProjectThread({ projectId, threadId })
576 .pipe(
577 Effect.mapError(() =>
578 failure("thread_not_found", `Thread ${threadId} was not found in the calling project.`),
579 ),
580 );
581
582 const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) =>
583 Effect.gen(function* () {
584 yield* requireCapability(scope);
585 const parent = yield* loadProjection(scope.threadId);
586 const target =
587 threadId === scope.threadId
588 ? parent
589 : yield* loadProjectThread(parent.thread.projectId, threadId);
590 return { parent, target } as const;
591 });
592
593 const loadProviders = providerRegistry.getProviders;
594
595 const resolveTarget = (input: {
596 readonly parent: OrchestrationV2ThreadProjection;
597 readonly target: OrchestratorMcpTarget | undefined;
598 readonly providers: ReadonlyArray<ServerProvider>;
599 }): Effect.Effect<ResolvedTarget, OrchestratorMcpFailure> =>
600 Effect.gen(function* () {
601 const requestedInstanceId = input.target?.providerInstanceId;
602 const requestedDriver = input.target?.driverKind;
603 let instanceId = requestedInstanceId;
604
605 if (instanceId === undefined && requestedDriver !== undefined) {
606 const candidates = input.providers.filter(
607 (provider) =>
608 provider.driver === requestedDriver &&
609 isBuiltInProviderAdapterDriverV2(provider.driver),
610 );
611 if (candidates.length === 0) {
612 return yield* failure(
613 "provider_unavailable",
614 `No V2 provider adapter is registered for driver ${requestedDriver}.`,
615 );
616 }
617 const inheritedCandidate = candidates.find(
618 (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
619 );
620 const availableCandidate = candidates.find((candidate) => {
621 return (
622 providerConstraints(candidate, isBuiltInProviderAdapterDriverV2(candidate.driver))
623 .length === 0
624 );
625 });
626 instanceId = inheritedCandidate?.instanceId ?? availableCandidate?.instanceId;
627 }
628 instanceId ??= input.parent.thread.modelSelection.instanceId;
629
630 const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);
631 if (provider === undefined) {
632 return yield* failure(
633 "provider_unavailable",
634 `Provider instance ${instanceId} is not registered.`,
635 );
636 }
637 if (requestedDriver !== undefined && provider.driver !== requestedDriver) {
638 return yield* failure(
639 "invalid_request",
640 `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
641 );
642 }
643 const constraints = providerConstraints(
644 provider,
645 isBuiltInProviderAdapterDriverV2(provider.driver),
646 );
647 if (constraints.length > 0) {
648 return yield* failure(
649 "provider_unavailable",
650 `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,
651 );
652 }
653
654 const inheritedSelection = input.parent.thread.modelSelection;
655 const requestedModel = input.target?.model;
656 const model =
657 requestedModel ??
658 (instanceId === inheritedSelection.instanceId
659 ? inheritedSelection.model
660 : provider?.models[0]?.slug);
661 if (model === undefined) {
662 return yield* failure(
663 "model_unavailable",
664 `Provider ${instanceId} has no model available for inheritance.`,
665 );
666 }
667 if (
668 requestedModel !== undefined &&
669 provider !== undefined &&
670 provider.models.length > 0 &&
671 !provider.models.some((candidate) => candidate.slug === requestedModel)
672 ) {
673 return yield* failure(
674 "model_unavailable",
675 `Model ${requestedModel} is not advertised by provider ${instanceId}.`,
676 );
677 }
678
679 return {
680 modelSelection:
681 instanceId === inheritedSelection.instanceId && model === inheritedSelection.model
682 ? inheritedSelection
683 : { instanceId, model },
684 };
685 });
686
687 const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>
688 clientRequestId === undefined
689 ? crypto.randomUUIDv4.pipe(Effect.orDie)
690 : Effect.succeed(clientRequestId);
691
692 const readTask = (
693 scope: McpInvocationScope,
694 taskId: NodeId,
695 waitTimedOut = false,
696 ): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>
697 Effect.gen(function* () {
698 yield* requireCapability(scope);
699 const parentProjection = yield* loadProjection(scope.threadId);
700 const task = parentProjection.subagents.find(
701 (candidate) =>
702 candidate.id === taskId &&
703 candidate.origin === "app_owned" &&
704 candidate.threadId === scope.threadId,
705 );
706 if (task === undefined || task.childThreadId === null) {
707 return yield* failure(
708 "task_not_found",
709 `Delegated task ${taskId} does not belong to thread ${scope.threadId}.`,
710 );
711 }
712 const childProjection = yield* loadProjection(task.childThreadId);
713 const childRun = childProjection.runs[0];
714 const status = taskStatusForRun(childRun);
715 const derivedResult =
716 task.result !== null
717 ? task.result
718 : childRun !== undefined && isTerminalTaskStatus(status)
719 ? subagentResultForRun(childProjection, childRun).text
720 : null;
721 const resultTransfer =
722 parentProjection.contextTransfers.find(
723 (transfer) =>
724 transfer.type === "subagent_result" &&
725 transfer.sourceThreadId === task.childThreadId &&
726 transfer.targetThreadId === scope.threadId,
727 ) ?? null;
728 return {
729 taskId: task.id,
730 childThreadId: task.childThreadId,
731 childRunId: childRun?.id ?? null,
732 childNodeId: task.id,
733 status,
734 providerInstanceId: ProviderInstanceId.make(task.driver),
735 model: task.model,
736 summary: derivedResult,
737 resultContextTransferId: resultTransfer?.id ?? null,
738 waitTimedOut,
739 };
740 });
741
742 const waitForTask = (scope: McpInvocationScope, taskId: NodeId, timeoutMs: number) =>
743 Effect.gen(function* () {
744 while (true) {
745 const result = yield* readTask(scope, taskId);
746 if (isTerminalTaskStatus(result.status)) return result;
747 yield* Effect.sleep(Duration.millis(TASK_POLL_INTERVAL_MS));
748 }
749 }).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)));
750
751 // Load a single scheduled task and enforce that it belongs to the calling
752 // thread's project, so agents can only read/mutate tasks in their own scope.
753 const loadScopedScheduledTask = (
754 projectId: ScheduledTask["projectId"],
755 scheduledTaskId: ScheduledTask["id"],
756 ): Effect.Effect<ScheduledTask, OrchestratorMcpFailure> =>
757 Effect.gen(function* () {
758 const { tasks } = yield* scheduledTasks
759 .list()
760 .pipe(
761 Effect.mapError((error) =>
762 failure("orchestration_error", `Could not load scheduled task: ${error.message}`),
763 ),
764 );
765 const task = tasks.find((candidate) => candidate.id === scheduledTaskId);
766 if (task === undefined || task.projectId !== projectId) {
767 return yield* failure(
768 "task_not_found",
769 `Scheduled task ${scheduledTaskId} was not found in the calling project.`,
770 );
771 }
772 return task;
773 });
774
775 return OrchestratorMcpService.of({
776 scheduleTask: (scope, input) =>
777 Effect.gen(function* () {
778 yield* requireCapability(scope);
779 const parent = yield* loadProjection(scope.threadId);
780 const bindToCurrentThread = input.bindToCurrentThread ?? true;
781 const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";
782 const title =
783 input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");
784 const upsertInput: ScheduledTaskUpsertInput = {
785 title,
786 prompt: input.prompt,
787 enabled: input.enabled ?? true,
788 schedule: input.schedule,
789 projectId: parent.thread.projectId,
790 threadId: bindToCurrentThread ? scope.threadId : null,
791 workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),
792 modelSelection: parent.thread.modelSelection,
793 runtimeMode: parent.thread.runtimeMode,
794 interactionMode: parent.thread.interactionMode,
795 createdBy: "agent",
796 creationSource: "mcp",
797 // Scope the idempotency key by provider session so two callers
798 // reusing the same clientRequestId cannot collide on one task row.
799 ...(input.clientRequestId === undefined
800 ? {}
801 : {
802 commandId: stableCommandId({
803 scope,
804 requestKey: input.clientRequestId,
805 operation: "schedule-task",
806 }),
807 }),
808 };
809 const { task } = yield* scheduledTasks
810 .upsert(upsertInput)
811 .pipe(
812 Effect.mapError((error) =>
813 failure("orchestration_error", `Could not schedule task: ${error.message}`),
814 ),
815 );
816 return scheduledTaskSummary(task);
817 }),
818 listScheduledTasks: (scope) =>
819 Effect.gen(function* () {
820 yield* requireCapability(scope);
821 const parent = yield* loadProjection(scope.threadId);
822 const { tasks } = yield* scheduledTasks
823 .list()
824 .pipe(
825 Effect.mapError((error) =>
826 failure("orchestration_error", `Could not list scheduled tasks: ${error.message}`),
827 ),
828 );
829 // Only expose tasks belonging to the calling thread's project.
830 return {
831 tasks: tasks
832 .filter((task) => task.projectId === parent.thread.projectId)
833 .map(scheduledTaskSummary),
834 };
835 }),
836 updateScheduledTask: (scope, input) =>
837 Effect.gen(function* () {
838 yield* requireCapability(scope);
839 const parent = yield* loadProjection(scope.threadId);
840 const existing = yield* loadScopedScheduledTask(
841 parent.thread.projectId,
842 input.scheduledTaskId,
843 );
844 const threadId =
845 input.bindToCurrentThread === undefined
846 ? existing.threadId
847 : input.bindToCurrentThread
848 ? scope.threadId
849 : null;
850 // Rebinding changes where runs execute, so the workspace strategy must
851 // follow: unbinding a root-strategy task would otherwise run loose
852 // prompts in the shared project checkout.
853 const workspaceStrategy =
854 input.bindToCurrentThread === undefined
855 ? existing.workspaceStrategy
856 : scheduledTaskWorkspaceStrategy(input.bindToCurrentThread);
857 const upsertInput: ScheduledTaskUpsertInput = {
858 id: existing.id,
859 title: input.title ?? existing.title,
860 prompt: input.prompt ?? existing.prompt,
861 enabled: input.enabled ?? existing.enabled,
862 schedule: input.schedule ?? existing.schedule,
863 projectId: existing.projectId,
864 threadId,
865 workspaceStrategy,
866 modelSelection: existing.modelSelection,
867 runtimeMode: existing.runtimeMode,
868 interactionMode: existing.interactionMode,
869 createdBy: existing.createdBy,
870 creationSource: existing.creationSource,
871 };
872 const { task } = yield* scheduledTasks
873 .upsert(upsertInput)
874 .pipe(
875 Effect.mapError((error) =>
876 failure("orchestration_error", `Could not update scheduled task: ${error.message}`),
877 ),
878 );
879 return scheduledTaskSummary(task);
880 }),
881 deleteScheduledTask: (scope, input) =>
882 Effect.gen(function* () {
883 yield* requireCapability(scope);
884 const parent = yield* loadProjection(scope.threadId);
885 const existing = yield* loadScopedScheduledTask(
886 parent.thread.projectId,
887 input.scheduledTaskId,
888 );
889 yield* scheduledTasks
890 .delete({ id: existing.id })
891 .pipe(
892 Effect.mapError((error) =>
893 failure("orchestration_error", `Could not delete scheduled task: ${error.message}`),
894 ),
895 );
896 return { scheduledTaskId: existing.id, deleted: true };
897 }),
898 capabilities: (scope) =>
899 Effect.gen(function* () {
900 yield* requireCapability(scope);
901 const parent = yield* loadProjection(scope.threadId);
902 const providers = yield* loadProviders;
903 return {
904 parentThreadId: scope.threadId,
905 inheritedProviderInstanceId: parent.thread.modelSelection.instanceId,
906 inheritedModel: parent.thread.modelSelection.model,
907 runtimeMode: parent.thread.runtimeMode,
908 interactionMode: parent.thread.interactionMode,
909 providers: providers.map((provider) => {
910 const constraints = providerConstraints(
911 provider,
912 isBuiltInProviderAdapterDriverV2(provider.driver),
913 );
914 return {
915 providerInstanceId: provider.instanceId,
916 driverKind: provider.driver,
917 displayName: provider?.displayName ?? null,
918 models:
919 provider?.models.map((model) => ({
920 id: model.slug,
921 label: model.name ?? null,
922 })) ?? [],
923 canRunChildTask: constraints.length === 0,
924 canRunCrossProviderChildTask: constraints.length === 0,
925 constraints: [...constraints],
926 };
927 }),
928 features: {
929 appOwnedSubagents: true,
930 asyncPolling: true,
931 cancellation: true,
932 batchThreadCreation: true,
933 threadManagement: true,
934 incrementalThreadRead: true,
935 scheduledTasks: true,
936 maxBatchThreads: 20,
937 },
938 };
939 }),
940 delegateTask: (scope, input) =>
941 Effect.gen(function* () {
942 yield* requireCapability(scope);
943 const parent = yield* loadProjection(scope.threadId);
944 const parentRun = parent.runs
945 .filter(isActiveRun)
946 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
947 if (
948 parentRun === undefined ||
949 parentRun.rootNodeId === null ||
950 parentRun.providerInstanceId !== scope.providerInstanceId
951 ) {
952 return yield* failure(
953 "parent_not_active",
954 "Delegated tasks require an active run owned by this MCP provider session.",
955 );
956 }
957 const providers = yield* loadProviders;
958 const target = yield* resolveTarget({
959 parent,
960 target: input.target,
961 providers,
962 });
963 const runtimeMode = yield* resolveRuntimeMode(parent.thread.runtimeMode, input.runtimeMode);
964 const interactionMode = yield* resolveInteractionMode(
965 parent.thread.interactionMode,
966 input.interactionMode,
967 );
968 const key = yield* requestKey(input.clientRequestId);
969 const commandId = stableCommandId({
970 scope,
971 requestKey: key,
972 operation: "delegate-task",
973 });
974 const result = yield* threadManagement
975 .dispatch({
976 type: "delegated_task.request",
977 createdBy: "agent",
978 creationSource: "mcp",
979 commandId,
980 parentThreadId: scope.threadId,
981 parentRunId: parentRun.id,
982 parentNodeId: parentRun.rootNodeId,
983 task: taskPrompt(input),
984 ...(input.title === undefined ? {} : { title: input.title }),
985 modelSelection: target.modelSelection,
986 runtimeMode,
987 interactionMode,
988 })
989 .pipe(
990 Effect.mapError((error) =>
991 failure(
992 "orchestration_error",
993 `Unable to create delegated task: ${errorMessage(error)}`,
994 ),
995 ),
996 );
997 const taskEvent = result.storedEvents.find(
998 (stored) =>
999 stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",
1000 );
1001 if (taskEvent?.event.type !== "subagent.updated") {
1002 return yield* failure(
1003 "orchestration_error",
1004 "Delegated task command did not produce a task projection.",
1005 );
1006 }
1007
1008 if (input.mode !== "wait") {
1009 return yield* readTask(scope, taskEvent.event.payload.id);
1010 }
1011 const timeoutMs = Math.min(
1012 MAX_WAIT_TIMEOUT_MS,
1013 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
1014 );
1015 const waited = yield* waitForTask(scope, taskEvent.event.payload.id, timeoutMs);
1016 return Option.isSome(waited)
1017 ? waited.value
1018 : yield* readTask(scope, taskEvent.event.payload.id, true);
1019 }),
1020 taskStatus: (scope, taskId) => readTask(scope, taskId),
1021 cancelTask: (scope, input) =>
1022 Effect.gen(function* () {
1023 const current = yield* readTask(scope, input.taskId);
1024 if (isTerminalTaskStatus(current.status)) {
1025 return {
1026 taskId: input.taskId,
1027 status: current.status,
1028 } satisfies OrchestratorMcpTaskCancelResult;
1029 }
1030 const child = yield* loadProjection(current.childThreadId);
1031 const activeRun = child.runs.find(isActiveRun);
1032 if (activeRun === undefined) {
1033 return yield* failure(
1034 "task_not_cancellable",
1035 `Delegated task ${input.taskId} has no interruptible child run.`,
1036 );
1037 }
1038 const key = yield* requestKey(input.clientRequestId);
1039 yield* threadManagement
1040 .dispatch({
1041 type: "run.interrupt",
1042 commandId: stableCommandId({
1043 scope,
1044 requestKey: key,
1045 operation: "cancel-task",
1046 }),
1047 threadId: current.childThreadId,
1048 runId: activeRun.id,
1049 ...(input.reason === undefined ? {} : { reason: input.reason }),
1050 })
1051 .pipe(
1052 Effect.mapError((error) =>
1053 failure(
1054 "task_not_cancellable",
1055 `Unable to interrupt delegated task ${input.taskId}: ${errorMessage(error)}`,
1056 ),
1057 ),
1058 );
1059 return {
1060 taskId: input.taskId,
1061 status: "cancel_requested",
1062 };
1063 }),
1064 createThreads: (scope, input) =>
1065 Effect.gen(function* () {
1066 yield* requireCapability(scope);
1067 const parent = yield* loadProjection(scope.threadId);
1068 const parentRun = latestActiveRun(parent);
1069 if (
1070 parentRun === undefined ||
1071 parentRun.rootNodeId === null ||
1072 parentRun.providerInstanceId !== scope.providerInstanceId
1073 ) {
1074 return yield* failure(
1075 "parent_not_active",
1076 "Thread creation requires an active run owned by this MCP provider session.",
1077 );
1078 }
1079 const parentNodeId = parentRun.rootNodeId;
1080 const providers = yield* loadProviders;
1081 const key = yield* requestKey(input.clientRequestId);
1082 const created = yield* Effect.forEach(
1083 input.threads,
1084 (request, index) =>
1085 Effect.gen(function* () {
1086 const target = yield* resolveTarget({
1087 parent,
1088 target: request.target,
1089 providers,
1090 });
1091 const runtimeMode = yield* resolveRuntimeMode(
1092 parent.thread.runtimeMode,
1093 request.runtimeMode,
1094 );
1095 const interactionMode = yield* resolveInteractionMode(
1096 parent.thread.interactionMode,
1097 request.interactionMode,
1098 );
1099 const threadId = stableThreadId({
1100 scope,
1101 requestKey: key,
1102 index,
1103 });
1104 const title = threadTitle({
1105 parentTitle: parent.thread.title,
1106 prompt: request.prompt,
1107 title: request.title,
1108 index,
1109 });
1110 yield* threadManagement
1111 .dispatch({
1112 type: "thread.create",
1113 createdBy: "agent",
1114 creationSource: "mcp",
1115 commandId: stableCommandId({
1116 scope,
1117 requestKey: key,
1118 operation: "create-thread",
1119 index,
1120 }),
1121 threadId,
1122 projectId: parent.thread.projectId,
1123 title,
1124 modelSelection: target.modelSelection,
1125 runtimeMode,
1126 interactionMode,
1127 branch: parent.thread.branch,
1128 worktreePath: parent.thread.worktreePath,
1129 })
1130 .pipe(
1131 Effect.mapError((error) =>
1132 failure(
1133 "orchestration_error",
1134 `Unable to create thread ${index + 1}: ${errorMessage(error)}`,
1135 ),
1136 ),
1137 );
1138 if (request.prompt !== undefined) {
1139 yield* threadManagement
1140 .dispatch({
1141 type: "message.dispatch",
1142 createdBy: "agent",
1143 creationSource: "mcp",
1144 commandId: stableCommandId({
1145 scope,
1146 requestKey: key,
1147 operation: "dispatch-thread",
1148 index,
1149 }),
1150 threadId,
1151 messageId: stableMessageId({
1152 scope,
1153 requestKey: key,
1154 index,
1155 }),
1156 text: request.prompt,
1157 attachments: [],
1158 modelSelection: target.modelSelection,
1159 dispatchMode: { type: "start_immediately" },
1160 })
1161 .pipe(
1162 Effect.mapError((error) =>
1163 failure(
1164 "orchestration_error",
1165 `Unable to start thread ${index + 1}: ${errorMessage(error)}`,
1166 ),
1167 ),
1168 );
1169 }
1170 const projection = yield* loadProjection(threadId);
1171 const run = projection.runs.at(-1);
1172 yield* threadManagement
1173 .dispatch({
1174 type: "thread.created.record",
1175 commandId: stableCommandId({
1176 scope,
1177 requestKey: key,
1178 operation: "record-created-thread",
1179 index,
1180 }),
1181 parentThreadId: scope.threadId,
1182 parentRunId: parentRun.id,
1183 parentNodeId,
1184 targetThreadId: threadId,
1185 targetRunId: run?.id ?? null,
1186 })
1187 .pipe(
1188 Effect.mapError((error) =>
1189 failure(
1190 "orchestration_error",
1191 `Unable to record thread ${index + 1} in the parent timeline: ${errorMessage(error)}`,
1192 ),
1193 ),
1194 );
1195 return {
1196 threadId,
1197 runId: run?.id ?? null,
1198 status: run?.status ?? "idle",
1199 title: projection.thread.title,
1200 createdBy: projection.thread.createdBy,
1201 creationSource: projection.thread.creationSource,
1202 providerInstanceId: target.modelSelection.instanceId,
1203 model: target.modelSelection.model,
1204 } satisfies OrchestratorMcpCreatedThread;
1205 }),
1206 { concurrency: 1 },
1207 );
1208 return { threads: created };
1209 }),
1210 listThreads: (scope, input) =>
1211 Effect.gen(function* () {
1212 yield* requireCapability(scope);
1213 const parent = yield* loadProjection(scope.threadId);
1214 const projectThreads = yield* threadManagement
1215 .listProjectThreads({
1216 projectId: parent.thread.projectId,
1217 includeSubagents: input.includeSubagents !== false,
1218 })
1219 .pipe(
1220 Effect.mapError((error) =>
1221 failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),
1222 ),
1223 );
1224 const statuses = input.statuses === undefined ? null : new Set(input.statuses);
1225 const titleContains = input.titleContains?.toLocaleLowerCase();
1226 const filtered = projectThreads
1227 .filter((thread) => statuses === null || statuses.has(thread.status))
1228 .filter(
1229 (thread) =>
1230 titleContains === undefined ||
1231 thread.title.toLocaleLowerCase().includes(titleContains),
1232 );
1233 const cursor = input.cursor ?? 0;
1234 const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;
1235 const page = filtered.slice(cursor, cursor + limit);
1236 const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;
1237 return {
1238 projectId: parent.thread.projectId,
1239 currentThreadId: scope.threadId,
1240 threads: page.map(listItemFromShell),
1241 nextCursor,
1242 total: filtered.length,
1243 } satisfies OrchestratorMcpThreadListResult;
1244 }),
1245 readThread: (scope, input) =>
1246 Effect.gen(function* () {
1247 const { target } = yield* loadScopedThread(scope, input.threadId);
1248 const view = input.view ?? "messages";
1249 const afterPosition = input.afterPosition ?? -1;
1250 const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
1251 const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
1252 const matching = target.visibleTurnItems
1253 .filter((row) => row.position > afterPosition)
1254 .filter(
1255 (row) =>
1256 view === "activity" ||
1257 row.item.type === "user_message" ||
1258 row.item.type === "assistant_message" ||
1259 row.item.type === "proposed_plan",
1260 );
1261 const page = matching.slice(0, limit);
1262 return {
1263 thread: threadDetail(target),
1264 recentRuns: target.runs
1265 .toSorted((left, right) => right.ordinal - left.ordinal)
1266 .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
1267 .map(threadRun),
1268 items: page.map((row) => timelineItem({ row, maxChars, projection: target })),
1269 nextPosition: page.at(-1)?.position ?? null,
1270 hasMore: page.length < matching.length,
1271 } satisfies OrchestratorMcpThreadReadResult;
1272 }),
1273 sendToThread: (scope, input) =>
1274 Effect.gen(function* () {
1275 const { parent, target } = yield* loadScopedThread(scope, input.threadId);
1276 yield* resolveRuntimeMode(parent.thread.runtimeMode, target.thread.runtimeMode);
1277 yield* resolveInteractionMode(parent.thread.interactionMode, target.thread.interactionMode);
1278
1279 const mode = input.mode ?? "auto";
1280 const key = yield* requestKey(input.clientRequestId);
1281 const messageId = stableOperationMessageId({
1282 scope,
1283 requestKey: key,
1284 operation: "thread-send",
1285 });
1286 const result = yield* threadManagement
1287 .sendToThread({
1288 projectId: parent.thread.projectId,
1289 commandId: stableCommandId({
1290 scope,
1291 requestKey: key,
1292 operation: "thread-send",
1293 }),
1294 threadId: input.threadId,
1295 messageId,
1296 text: input.message,
1297 attachments: [],
1298 mode,
1299 createdBy: "agent",
1300 creationSource: "mcp",
1301 })
1302 .pipe(
1303 Effect.mapError((error) =>
1304 failure(
1305 "thread_not_sendable",
1306 `Unable to send to thread ${input.threadId}: ${errorMessage(error)}`,
1307 ),
1308 ),
1309 );
1310 return {
1311 threadId: input.threadId,
1312 messageId,
1313 runId: result.run.id,
1314 status: result.run.status,
1315 delivery: result.delivery,
1316 } satisfies OrchestratorMcpThreadSendResult;
1317 }),
1318 waitForThread: (scope, input) =>
1319 Effect.gen(function* () {
1320 const { parent } = yield* loadScopedThread(scope, input.threadId);
1321 const result = yield* threadManagement
1322 .waitForThread({
1323 projectId: parent.thread.projectId,
1324 threadId: input.threadId,
1325 ...(input.runId === undefined ? {} : { runId: input.runId }),
1326 timeoutMs: Math.min(
1327 MAX_WAIT_TIMEOUT_MS,
1328 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
1329 ),
1330 })
1331 .pipe(
1332 Effect.mapError((error) =>
1333 failure(
1334 error.code === "run_not_found" ? "run_not_found" : "orchestration_error",
1335 error.message,
1336 ),
1337 ),
1338 );
1339 return {
1340 threadId: input.threadId,
1341 runId: result.run?.id ?? null,
1342 status: result.run?.status ?? "idle",
1343 timedOut: result.timedOut,
1344 } satisfies OrchestratorMcpThreadWaitResult;
1345 }),
1346 interruptThread: (scope, input) =>
1347 Effect.gen(function* () {
1348 const { parent } = yield* loadScopedThread(scope, input.threadId);
1349 const key = yield* requestKey(input.clientRequestId);
1350 const result = yield* threadManagement
1351 .interruptThread({
1352 projectId: parent.thread.projectId,
1353 commandId: stableCommandId({
1354 scope,
1355 requestKey: key,
1356 operation: "thread-interrupt",
1357 }),
1358 threadId: input.threadId,
1359 ...(input.runId === undefined ? {} : { runId: input.runId }),
1360 ...(input.reason === undefined ? {} : { reason: input.reason }),
1361 })
1362 .pipe(
1363 Effect.mapError((error) =>
1364 failure(
1365 isThreadManagementError(error) && error.code === "run_not_found"
1366 ? "run_not_found"
1367 : "thread_not_interruptible",
1368 isThreadManagementError(error)
1369 ? error.message
1370 : `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,
1371 ),
1372 ),
1373 );
1374 if (result.type === "no_active_run") {
1375 return {
1376 threadId: input.threadId,
1377 runId: null,
1378 status: "no_active_run",
1379 } satisfies OrchestratorMcpThreadInterruptResult;
1380 }
1381 return {
1382 threadId: input.threadId,
1383 runId: result.run.id,
1384 status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",
1385 } satisfies OrchestratorMcpThreadInterruptResult;
1386 }),
1387 });
1388});
1389
1390export const layer: Layer.Layer<
1391 OrchestratorMcpService,
1392 never,
1393 Crypto.Crypto | ThreadManagementService | ProviderRegistry | ScheduledTaskService
1394> = Layer.effect(OrchestratorMcpService, make);