import {
CommandId,
type RunId,
isProviderAvailable,
MessageId,
type ModelSelection,
NodeId,
ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
TurnItemId,
type OrchestrationV2Run,
type OrchestrationV2Subagent,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadShell,
type OrchestrationV2ThreadLaunchWorkspaceStrategy,
type OrchestrationV2TurnItem,
OrchestratorMcpFailure,
type OrchestratorMcpCapabilitiesInput,
type OrchestratorMcpCapabilitiesResult,
type OrchestratorMcpModelOption,
type OrchestratorMcpCreateThreadsInput,
type OrchestratorMcpCreateThreadsResult,
type OrchestratorMcpCreatedThread,
type OrchestratorMcpDelegateTaskInput,
type OrchestratorMcpDelegateTaskResult,
type OrchestratorMcpDeleteScheduledTaskInput,
type OrchestratorMcpRequestSecretInput,
type OrchestratorMcpRequestSecretResult,
type OrchestratorMcpDeleteScheduledTaskResult,
type OrchestratorMcpListScheduledTasksResult,
type OrchestratorMcpScheduledTask,
type OrchestratorMcpScheduleTaskInput,
type OrchestratorMcpScheduleTaskResult,
type OrchestratorMcpTarget,
type OrchestratorMcpTaskCancelInput,
type OrchestratorMcpTaskCancelResult,
type OrchestratorMcpUpdateScheduledTaskInput,
type OrchestratorMcpListScheduledTasksInput,
type ProjectId,
type OrchestratorMcpThreadDetail,
type OrchestratorMcpThreadPullRequest,
type OrchestratorMcpThreadInterruptInput,
type OrchestratorMcpThreadInterruptResult,
type OrchestratorMcpThreadListInput,
type OrchestratorMcpThreadListItem,
type OrchestratorMcpThreadListResult,
type OrchestratorMcpThreadReadInput,
type OrchestratorMcpThreadReadResult,
type OrchestratorMcpThreadRun,
type OrchestratorMcpThreadSendInput,
type OrchestratorMcpThreadSendResult,
type OrchestratorMcpThreadTimelineItem,
type OrchestratorMcpThreadWaitInput,
type OrchestratorMcpThreadWaitResult,
type ProviderInteractionMode,
type ProviderOptionDescriptor,
type ProviderOptionSelection,
ProviderRequestKind,
type RuntimeMode,
type ScheduledTask,
type ScheduledTaskUpsertInput,
scheduledTaskThreadMode,
type ServerProvider,
type ServerProviderModel,
ThreadId,
isOrchestrationV2WorkActive,
resolveProjectProviderInstanceEnabled,
SECRET_REQUEST_UNSAVED_NOTE,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import {
normalizeThreadPullRequestKey,
visibleThreadPullRequests,
} from "../sourceControl/threadPullRequests.ts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
import {
subagentResultForRun,
delegatedTaskProgress,
} from "@t3tools/provider-core/server/subagentProjection";
import {
DispatchModeLimit,
type DispatchModeRefusal,
} from "../orchestration-v2/DispatchModeLimit.ts";
import type {
ProjectionRecordField,
ProjectionRecordFilter,
} from "../orchestration-v2/ProjectionStore.ts";
import { runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts";
import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import {
clientModeCeiling,
type McpInvocationScope,
type McpThreadInvocationScope,
requireThreadScope,
threadLinkFor,
} from "./McpInvocationContext.ts";
import * as Metrics from "../observability/Metrics.ts";
import {
interactionModeRank,
resolveInteractionMode,
resolveRuntimeMode,
runtimeModeRank,
taskPrompt,
} from "./delegatedTaskModes.ts";
import { isLiveCallerShell, threadNotFound } from "./threadAccess.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
const TASK_WAKE_EVENTS = [
{ thread: "parent", eventType: "subagent.updated" },
{ thread: "child", eventType: "run.updated" },
{ thread: "child", eventType: "subagent.updated" },
{ thread: "child", eventType: "provider-thread.updated" },
{ thread: "child", eventType: "runtime-request.updated" },
] as const;
const SECRET_REQUEST_POLL_INTERVAL_MS = 500;
const DEFAULT_THREAD_LIST_LIMIT = 50;
const DEFAULT_THREAD_READ_LIMIT = 50;
const DEFAULT_THREAD_RUN_LIMIT = 10;
const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
interface ResolvedTarget {
readonly modelSelection: ModelSelection;
readonly supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined;
}
type TerminalTaskStatus = Extract<
OrchestratorMcpDelegateTaskResult["status"],
"completed" | "failed" | "cancelled" | "interrupted"
>;
export interface OrchestratorMcpServiceShape {
readonly capabilities: (
scope: McpInvocationScope,
input?: OrchestratorMcpCapabilitiesInput,
) => Effect.Effect<OrchestratorMcpCapabilitiesResult, OrchestratorMcpFailure>;
readonly delegateTask: (
scope: McpInvocationScope,
input: OrchestratorMcpDelegateTaskInput,
) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
readonly taskStatus: (
scope: McpInvocationScope,
taskId: NodeId,
) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
readonly cancelTask: (
scope: McpInvocationScope,
input: OrchestratorMcpTaskCancelInput,
) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
readonly createThreads: (
scope: McpInvocationScope,
input: OrchestratorMcpCreateThreadsInput,
) => Effect.Effect<OrchestratorMcpCreateThreadsResult, OrchestratorMcpFailure>;
readonly scheduleTask: (
scope: McpInvocationScope,
input: OrchestratorMcpScheduleTaskInput,
) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
readonly listScheduledTasks: (
scope: McpInvocationScope,
input: OrchestratorMcpListScheduledTasksInput,
) => Effect.Effect<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
readonly updateScheduledTask: (
scope: McpInvocationScope,
input: OrchestratorMcpUpdateScheduledTaskInput,
) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
readonly deleteScheduledTask: (
scope: McpInvocationScope,
input: OrchestratorMcpDeleteScheduledTaskInput,
) => Effect.Effect<OrchestratorMcpDeleteScheduledTaskResult, OrchestratorMcpFailure>;
/** Only status reaches the agent, never this value. */
readonly requestSecret: (
scope: McpInvocationScope,
input: OrchestratorMcpRequestSecretInput,
) => Effect.Effect<OrchestratorMcpRequestSecretResult, OrchestratorMcpFailure>;
readonly listThreads: (
scope: McpInvocationScope,
input: OrchestratorMcpThreadListInput,
) => Effect.Effect<OrchestratorMcpThreadListResult, OrchestratorMcpFailure>;
readonly readThread: (
scope: McpInvocationScope,
input: OrchestratorMcpThreadReadInput,
) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
readonly sendToThread: (
scope: McpInvocationScope,
input: OrchestratorMcpThreadSendInput,
) => Effect.Effect<OrchestratorMcpThreadSendResult, OrchestratorMcpFailure>;
readonly waitForThread: (
scope: McpInvocationScope,
input: OrchestratorMcpThreadWaitInput,
) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
readonly interruptThread: (
scope: McpInvocationScope,
input: OrchestratorMcpThreadInterruptInput,
) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
}
export class OrchestratorMcpService extends Context.Service<
OrchestratorMcpService,
OrchestratorMcpServiceShape
>()("t3/mcp/OrchestratorMcpService") {}
const isThreadManagementError = Schema.is(ThreadManagementService.ThreadManagementError);
function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
return new OrchestratorMcpFailure({ code, message });
}
function threadManagementFailure(error: unknown): OrchestratorMcpFailure {
if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error));
switch (error._tag) {
case "ThreadManagementThreadNotFoundError":
return failure("thread_not_found", error.message);
case "ThreadManagementRunNotFoundError":
return failure("run_not_found", error.message);
case "ThreadManagementThreadArchivedError":
case "ThreadManagementNoSteerableRunError":
return failure("thread_not_sendable", error.message);
case "ThreadManagementThreadNotInterruptibleError":
return failure("thread_not_interruptible", error.message);
case "ThreadManagementProjectionLoadError":
case "ThreadManagementProjectThreadsListError":
case "ThreadManagementDurableRunProjectionError":
return failure("orchestration_error", error.message);
case "ThreadManagementProviderInstanceDisabledError":
return failure("invalid_request", error.message);
}
}
// Without a reason, a Stop reads as the user's (see RunExecutionService.USER_STOP_REASON).
function agentStopReason(reason: string | undefined): string {
return reason === undefined ? "Stopped by an agent" : `Stopped by an agent: ${reason}`;
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): OrchestratorMcpScheduledTask {
return {
scheduledTaskId: task.id,
title: task.title,
prompt: task.prompt,
enabled: task.enabled,
projectId: task.projectId,
boundThreadId: task.threadId,
freshSession: scheduledTaskThreadMode(task) === "fresh_session",
schedule: task.schedule,
nextRunAt: task.nextRunAt,
lastRunStatus: task.lastRunStatus,
...(task.webhook?.url == null || !mayRun || task.blockedByPolicy !== undefined
? {}
: { webhookUrl: task.webhook.url }),
...(task.webhook === undefined
? {}
: { webhookSignature: task.webhook.hasSecret ? "set" : "none" }),
...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
};
}
/**
* Large catalogs (OpenCode, Cursor, Pi) can list hundreds of models, so agents
* get a short list by default and search for the rest. These providers have
* small official catalogs, so all their current models are listed.
*/
const FULL_CATALOG_DRIVERS: ReadonlySet<string> = new Set(["codex", "claudeAgent", "muse", "grok"]);
const LISTED_MODEL_LIMIT = 8;
/**
* Lists visible models, keeping pinned models and limiting large catalogs by default.
* Whole provider words select the provider; partial words filter models when any match.
*/
function listCapabilityModels(input: {
readonly provider: ServerProvider;
readonly preferences:
| { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
| undefined;
readonly isPinned: (model: ServerProviderModel) => boolean;
readonly searchTerms: ReadonlyArray<string>;
}) {
const rank = new Map(input.preferences?.modelOrder.map((slug, index) => [slug, index]));
const visible = input.provider.models
.filter((model) => model.isCustom || !input.preferences?.hiddenModels.includes(model.slug))
.toSorted((a, b) => (rank.get(a.slug) ?? rank.size) - (rank.get(b.slug) ?? rank.size));
const { instanceId, driver, displayName } = input.provider;
const providerText = `${instanceId} ${driver} ${displayName ?? ""}`.toLowerCase();
// Whole ids like "codex-work" and their parts both name the provider.
const providerWords = new Set([
...providerText.split(/\s+/),
...providerText.split(/[^\p{L}\p{N}]+/u),
]);
const modelText = (model: ServerProviderModel) =>
`${model.slug} ${model.name} ${model.subProvider ?? ""}`.toLowerCase();
// Part of a provider word ("agent" in "claudeAgent") names the provider unless a model matches it.
const modelTerms = input.searchTerms.filter(
(term) =>
!providerWords.has(term) &&
(!providerText.includes(term) || visible.some((model) => modelText(model).includes(term))),
);
if (modelTerms.length > 0) {
const matches = visible.filter((model) => {
const text = modelText(model);
return modelTerms.every((term) => text.includes(term));
});
const listed = matches.slice(0, LISTED_MODEL_LIMIT);
return { listed, omitted: matches.length - listed.length };
}
const current = visible.filter((model) => !model.isLegacy);
const shown = new Set(
FULL_CATALOG_DRIVERS.has(input.provider.driver)
? current
: current.slice(0, LISTED_MODEL_LIMIT),
);
const listed = visible.filter((model) => input.isPinned(model) || shown.has(model));
return { listed, omitted: visible.length - listed.length };
}
/** Option ids and allowed values are all a delegating agent needs; labels are UI copy. */
function capabilityModelOption(descriptor: ProviderOptionDescriptor): OrchestratorMcpModelOption {
const defaultValue = getProviderOptionCurrentValue(descriptor);
return {
id: descriptor.id,
values:
descriptor.type === "boolean" ? [false, true] : descriptor.options.map((choice) => choice.id),
...(defaultValue === undefined ? {} : { default: defaultValue }),
};
}
function providerConstraints(
provider: ServerProvider | undefined,
supportsOrchestrationV2: boolean,
): ReadonlyArray<string> {
const constraints: Array<string> = [];
if (!supportsOrchestrationV2) {
constraints.push("No V2 provider adapter is registered.");
}
if (provider === undefined) return constraints;
if (!isProviderAvailable(provider)) {
constraints.push(provider.unavailableReason ?? "Provider driver is unavailable.");
}
if (!provider.enabled) {
constraints.push("Provider instance is disabled.");
// Disabled snapshots contain placeholders for installation, health, and auth.
return constraints;
}
if (!provider.installed) constraints.push("Provider executable is not installed.");
if (provider.status === "error" || provider.status === "disabled") {
constraints.push(provider.message ?? `Provider status is ${provider.status}.`);
}
if (provider.auth.status === "unauthenticated") {
constraints.push("Provider is not authenticated.");
}
return constraints;
}
/** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */
function knownOptions(
options: ReadonlyArray<ProviderOptionSelection> | undefined,
descriptors: ReadonlyArray<ProviderOptionDescriptor> | undefined,
): ReadonlyArray<ProviderOptionSelection> | undefined {
if (options === undefined || descriptors === undefined) return options;
return options.filter((option) => descriptors.some((descriptor) => descriptor.id === option.id));
}
/** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */
function invalidOptionSelections(
selections: ReadonlyArray<ProviderOptionSelection>,
descriptors: ReadonlyArray<ProviderOptionDescriptor> | undefined,
): ReadonlyArray<string> {
const problems: Array<string> = [];
const seen = new Set<string>();
for (const selection of selections) {
if (seen.has(selection.id)) {
problems.push(`Option ${selection.id} was specified more than once.`);
continue;
}
seen.add(selection.id);
if (descriptors === undefined) continue;
const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
if (descriptor === undefined) {
const known = descriptors.map((candidate) => candidate.id).join(", ");
problems.push(`Unknown option ${selection.id}; supported options: ${known || "none"}.`);
continue;
}
if (descriptor.type === "boolean" && typeof selection.value !== "boolean") {
problems.push(`Option ${selection.id} expects a boolean value.`);
continue;
}
if (
descriptor.type === "select" &&
!descriptor.options.some((choice) => choice.id === selection.value)
) {
const choices = descriptor.options.map((choice) => choice.id).join(", ");
problems.push(`Option ${selection.id} must be one of: ${choices}.`);
}
}
return problems;
}
function taskStatusForRun(
run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork"> | undefined,
): OrchestratorMcpDelegateTaskResult["status"] {
switch (run === undefined ? undefined : runOutcome(run)) {
case "queued":
return "queued";
case "waiting":
return "waiting";
case "completed":
return "completed";
case "failed":
return "failed";
case "cancelled":
case "rolled_back":
return "cancelled";
case "interrupted":
return "interrupted";
case "preparing":
case "starting":
case "running":
case undefined:
return "running";
}
}
function delegatedTaskRun(
childProjection: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
task: OrchestrationV2Subagent,
): OrchestrationV2Run | undefined {
const taskRun = childProjection.runs.find((run) => run.delegatedTaskId === task.id);
if (taskRun !== undefined) return taskRun;
const spawnTransfer = childProjection.contextTransfers.find(
(transfer) =>
transfer.type === "subagent_spawn" &&
transfer.sourceThreadId === task.threadId &&
transfer.targetThreadId === task.childThreadId,
);
if (spawnTransfer === undefined) {
return childProjection.runs[0];
}
return spawnTransfer.targetRunId === null
? undefined
: childProjection.runs.find((run) => run.id === spawnTransfer.targetRunId);
}
function hasPendingChildRuns(
childProjection: Pick<OrchestrationV2ThreadProjection, "runs">,
delegatedRun: OrchestrationV2Run | undefined,
): boolean {
return childProjection.runs.some(
(run) =>
!ThreadManagementService.isTerminalRunStatus(run.status) &&
!(run.status === "queued" && run.queueHeld === true) &&
(delegatedRun === undefined || run.ordinal > delegatedRun.ordinal),
);
}
function isTerminalTaskStatus(
status: OrchestratorMcpDelegateTaskResult["status"],
): status is TerminalTaskStatus {
return (
status === "completed" ||
status === "failed" ||
status === "cancelled" ||
status === "interrupted"
);
}
function endsTaskWait(result: OrchestratorMcpDelegateTaskResult): boolean {
return (
result.hasPendingQuestion ||
result.pendingApproval !== null ||
isTerminalTaskStatus(result.status)
);
}
const isApprovalRequestKind = Schema.is(ProviderRequestKind);
function pendingTaskApproval(
child: Pick<OrchestrationV2ThreadProjection, "runs" | "nodes" | "runtimeRequests">,
taskId: NodeId,
originalRun: OrchestrationV2Run | undefined,
) {
const taskRunIds = new Set(
child.runs
.filter(
(run) =>
!ThreadManagementService.isTerminalRunStatus(run.status) &&
(run.delegatedTaskId === taskId ||
// Legacy tasks own only their original run, not later turns in the child thread.
(run.delegatedTaskId === undefined && run.id === originalRun?.id)),
)
.map((run) => run.id),
);
let approval: OrchestratorMcpDelegateTaskResult["pendingApproval"] = null;
let oldestCreatedAt = Infinity;
for (const request of child.runtimeRequests) {
if (
request.status !== "pending" ||
request.responseCapability.type !== "live" ||
!isApprovalRequestKind(request.kind)
) {
continue;
}
const runId = child.nodes.find((node) => node.id === request.nodeId)?.runId;
if (runId === undefined || runId === null || !taskRunIds.has(runId)) continue;
const createdAt = DateTime.toEpochMillis(request.createdAt);
if (createdAt < oldestCreatedAt) {
oldestCreatedAt = createdAt;
approval = { requestId: request.id, kind: request.kind, runId };
}
}
return approval;
}
/** Every task `directAppOwnedChildTasks` can return, so callers load only those. */
function directChildTaskIds(
target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
returnedRunIds: ReadonlySet<RunId | null>,
): ReadonlyArray<NodeId> {
const ids = new Set<NodeId>();
if (target.thread.forkedFrom?.type === "node") ids.add(target.thread.forkedFrom.nodeId);
for (const run of target.runs) {
if (returnedRunIds.has(run.id) && run.delegatedTaskId !== undefined) {
ids.add(run.delegatedTaskId);
}
}
return [...ids];
}
function directAppOwnedChildTasks(
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,
target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
returnedRunIds: ReadonlySet<RunId | null>,
): ReadonlyArray<OrchestrationV2Subagent> {
if (
target.thread.lineage.parentThreadId !== parent.thread.id ||
target.thread.lineage.relationshipToParent !== "subagent"
) {
return [];
}
const original = parent.subagents.find(
(task) =>
task.origin === "app_owned" &&
task.threadId === parent.thread.id &&
task.id ===
(target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined) &&
task.childThreadId === target.thread.id,
);
const taskIds = new Set(
target.runs
.filter((run) => returnedRunIds.has(run.id))
.map((run) => run.delegatedTaskId ?? original?.id),
);
return parent.subagents.filter(
(task) =>
taskIds.has(task.id) &&
task.origin === "app_owned" &&
task.childThreadId === target.thread.id,
);
}
function taskResultTransfer(
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers">,
child: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
task: OrchestrationV2Subagent,
) {
const originalRun = delegatedTaskRun(child, task);
const resultRunIds = new Set(
child.runs
.filter(
(run) =>
run.delegatedTaskId === task.id ||
(originalRun?.delegatedTaskId === undefined && run.delegatedTaskId === undefined),
)
.map((run) => run.id),
);
if (originalRun !== undefined) resultRunIds.add(originalRun.id);
return parent.contextTransfers.find(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === task.childThreadId &&
transfer.targetThreadId === parent.thread.id &&
((transfer.sourcePoint.runId !== undefined && resultRunIds.has(transfer.sourcePoint.runId)) ||
(transfer.sourcePoint.runId === undefined && originalRun?.delegatedTaskId === undefined)),
);
}
function pageIncludesTerminalTaskResult(input: {
readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers">;
readonly page: ReadonlyArray<OrchestrationV2ThreadProjection["visibleTurnItems"][number]>;
readonly task: OrchestrationV2Subagent;
readonly target: Pick<
OrchestrationV2ThreadProjection,
"thread" | "runs" | "contextTransfers" | "messages" | "turnItems"
>;
readonly maxChars: number;
}): boolean {
const transfer = taskResultTransfer(input.parent, input.target, input.task);
if (transfer === undefined) return false;
const run =
transfer.sourcePoint.runId === undefined
? delegatedTaskRun(input.target, input.task)
: input.target.runs.find((run) => run.id === transfer.sourcePoint.runId);
if (run === undefined || !isTerminalTaskStatus(taskStatusForRun(run))) return false;
const result = subagentResultForRun(input.target, run);
if (result.messageId === null && result.turnItemId === null) return false;
return input.page.some((row) => {
if (row.sourceThreadId !== input.target.thread.id) return false;
const matchesResult =
(result.turnItemId !== null && row.sourceItemId === result.turnItemId) ||
(result.messageId !== null &&
row.item.type === "assistant_message" &&
row.item.messageId === result.messageId);
if (!matchesResult) return false;
const text = turnItemText(row.item);
return text !== null && text.length <= textPageEnd(text, 0, input.maxChars);
});
}
function latestTerminalResultRun(
projection: Pick<OrchestrationV2ThreadProjection, "messages" | "runs">,
delegatedRun: OrchestrationV2Run | undefined,
): OrchestrationV2Run | undefined {
const monitorRunIds = new Set(
projection.messages
.filter((message) => message.notification?.source.kind === "monitor")
.map((message) => message.runId),
);
return projection.runs
.filter(
(run) =>
ThreadManagementService.isTerminalRunStatus(run.status) &&
!monitorRunIds.has(run.id) &&
run.status !== "rolled_back" &&
(run.id === delegatedRun?.id || run.startedAt !== null),
)
.reduce<OrchestrationV2Run | undefined>(
(latest, run) => (latest === undefined || runRanAfter(run, latest) ? run : latest),
undefined,
);
}
function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is OrchestrationV2Run {
return (
run !== undefined && run.status !== "rolled_back" && isTerminalTaskStatus(taskStatusForRun(run))
);
}
function stablePart(value: string): string {
return encodeURIComponent(value);
}
function stableCommandId(input: {
readonly scope: McpInvocationScope;
readonly requestKey: string;
readonly operation: string;
readonly index?: number;
}): CommandId {
return CommandId.make(
[
"command",
"mcp",
stablePart(input.scope.requestNamespace),
stablePart(input.operation),
stablePart(input.requestKey),
...(input.index === undefined ? [] : [String(input.index)]),
].join(":"),
);
}
function stableThreadId(input: {
readonly scope: McpInvocationScope;
readonly requestKey: string;
readonly index: number;
}): ThreadId {
return ThreadId.make(
[
"thread",
"mcp",
stablePart(input.scope.requestNamespace),
stablePart(input.requestKey),
String(input.index),
].join(":"),
);
}
function stableMessageId(input: {
readonly scope: McpInvocationScope;
readonly requestKey: string;
readonly index: number;
}): MessageId {
return MessageId.make(
[
"message",
"mcp",
stablePart(input.scope.requestNamespace),
stablePart(input.requestKey),
String(input.index),
].join(":"),
);
}
function stableOperationMessageId(input: {
readonly scope: McpInvocationScope;
readonly requestKey: string;
readonly operation: string;
}): MessageId {
return MessageId.make(
[
"message",
"mcp",
stablePart(input.scope.requestNamespace),
stablePart(input.operation),
stablePart(input.requestKey),
].join(":"),
);
}
function threadTitle(input: {
readonly parentTitle: string;
readonly prompt: string | undefined;
readonly title: string | undefined;
readonly index: number;
}): string {
const detail = input.title?.trim() || input.prompt?.trim();
if (!detail) return `${input.parentTitle} thread ${input.index + 1}`;
if (detail.length <= 80) return detail;
let end = 77;
const previous = detail.charCodeAt(end - 1);
const next = detail.charCodeAt(end);
if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
end -= 1;
}
return `${detail.slice(0, end)}...`;
}
function threadSettlement(
thread: Pick<OrchestrationV2ThreadShell, "settledOverride" | "settledAt">,
): Pick<OrchestratorMcpThreadListItem, "settled" | "settledAt"> {
const settled = thread.settledOverride === "settled";
return {
settled,
settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null,
};
}
function threadSnooze(
thread: Parameters<typeof isSnoozed>[0],
nowMs: number,
): Pick<OrchestratorMcpThreadListItem, "snoozed" | "snoozedUntil"> {
const snoozed = isSnoozed(thread, nowMs);
return {
snoozed,
snoozedUntil:
snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null,
};
}
function threadPullRequests(
links: OrchestrationV2ThreadShell["pullRequests"],
): OrchestratorMcpThreadPullRequest[] {
return visibleThreadPullRequests(links ?? []).map((link) => ({
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
url: link.url,
source: link.source,
state: link.snapshot?.state ?? null,
}));
}
function listItemFromShell(
scope: McpInvocationScope,
shell: OrchestrationV2ThreadShell,
nowMs: number,
): OrchestratorMcpThreadListItem {
return {
threadId: shell.id,
projectId: shell.projectId,
title: shell.title,
link: threadLinkFor(scope, shell.id),
createdBy: shell.createdBy,
creationSource: shell.creationSource,
status: shell.activityRunStatus ?? shell.status,
latestRunId: shell.latestRunId,
providerInstanceId: shell.modelSelection.instanceId,
model: shell.modelSelection.model,
runtimeMode: shell.runtimeMode,
interactionMode: shell.interactionMode,
linkedPullRequest: shell.linkedPullRequest ?? null,
pullRequests: threadPullRequests(shell.pullRequests),
...threadSettlement(shell),
...threadSnooze(shell, nowMs),
parentThreadId: shell.lineage.parentThreadId,
relationshipToParent: shell.lineage.relationshipToParent,
itemCount: shell.visibleItemCount,
createdAt: DateTime.formatIso(shell.createdAt),
updatedAt: DateTime.formatIso(shell.updatedAt),
};
}
function threadDetail(
scope: McpInvocationScope,
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,
itemCount: number,
shell: OrchestrationV2ThreadShell,
nowMs: number,
): OrchestratorMcpThreadDetail {
const latest = ThreadManagementService.latestRun(projection);
const active = ThreadManagementService.latestActiveRun(projection);
return {
threadId: projection.thread.id,
projectId: projection.thread.projectId,
title: projection.thread.title,
link: threadLinkFor(scope, projection.thread.id),
createdBy: projection.thread.createdBy,
creationSource: projection.thread.creationSource,
status: active?.status ?? latest?.status ?? "idle",
latestRunId: latest?.id ?? null,
activeRunId: active?.id ?? null,
providerInstanceId: projection.thread.modelSelection.instanceId,
model: projection.thread.modelSelection.model,
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
linkedPullRequest: projection.thread.linkedPullRequest ?? null,
pullRequests: threadPullRequests(projection.thread.pullRequests),
titleRegeneration:
projection.thread.titleRegeneration === undefined ||
projection.thread.titleRegeneration === null
? null
: {
requestId: projection.thread.titleRegeneration.requestId,
startedAt: DateTime.formatIso(projection.thread.titleRegeneration.startedAt),
},
branch: projection.thread.branch,
worktreePath: projection.thread.worktreePath,
parentThreadId: projection.thread.lineage.parentThreadId,
relationshipToParent: projection.thread.lineage.relationshipToParent,
runCount: projection.runs.length,
itemCount,
pendingRequestCount: projection.runtimeRequests.filter(
(request) => request.status === "pending",
).length,
archived: projection.thread.archivedAt !== null,
...threadSettlement(projection.thread),
...threadSnooze(shell, nowMs),
createdAt: DateTime.formatIso(projection.thread.createdAt),
updatedAt: DateTime.formatIso(projection.thread.updatedAt),
};
}
function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun {
return {
runId: run.id,
ordinal: run.ordinal,
status: run.status,
providerInstanceId: run.modelSelection.instanceId,
model: run.modelSelection.model,
requestedAt: DateTime.formatIso(run.requestedAt),
startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
};
}
function jsonText(value: unknown): string {
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
function turnItemText(item: OrchestrationV2TurnItem): string | null {
switch (item.type) {
case "notification":
return [item.summary, item.detail].filter((part) => part !== undefined).join("\n");
case "user_message":
case "assistant_message":
case "reasoning":
return item.text;
case "proposed_plan":
return item.markdown;
case "todo_list":
return [item.explanation, ...item.steps.map((step) => `[${step.status}] ${step.text}`)]
.filter((line): line is string => line !== undefined)
.join("\n");
case "user_input_request":
return jsonText(item.questions);
case "file_change":
return [
item.fileName,
item.additions === undefined && item.deletions === undefined
? undefined
: `+${item.additions ?? 0} -${item.deletions ?? 0}`,
item.diffStr ?? item.newStr,
]
.filter((line): line is string => line !== undefined)
.join("\n");
case "command_execution":
return [`$ ${item.input}`, item.output]
.filter((line): line is string => line !== undefined)
.join("\n");
case "file_search":
return jsonText({ pattern: item.pattern, results: item.results });
case "web_search":
return jsonText({ patterns: item.patterns, results: item.results });
case "approval_request":
return [item.prompt ?? item.requestKind, item.reason]
.filter((line): line is string => line !== undefined)
.join("\n");
case "checkpoint":
return jsonText(item.files);
case "run_interrupt_request":
case "run_interrupt_result":
case "system_notice":
return item.message;
case "error":
return item.failure.message;
case "compaction":
return item.summary ?? null;
case "handoff":
return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`;
case "fork":
return `Forked to thread ${item.targetThreadId}.`;
case "thread_created":
return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
case "secret_request":
return `Asked the user for ${item.label}: ${item.secretStatus}.`;
case "link_request":
return item.linkStatus === "linked"
? `Linked ${item.linkedLabel ?? item.label ?? item.url ?? "an environment"} (${item.linkedAccess}).`
: `Asked the user to link ${item.label ?? item.url ?? "an environment"}: ${item.linkStatus}.`;
case "subagent":
return item.result ?? item.progress ?? item.prompt;
case "dynamic_tool":
return jsonText({ toolName: item.toolName, input: item.input, output: item.output });
}
}
/** A cut inside a surrogate pair would leave half an emoji on each page. */
function textPageEnd(text: string | null, offset: number, maxChars: number): number {
const end = offset + maxChars;
if (text === null || end >= text.length) return end;
const last = text.charCodeAt(end - 1);
if (last < 0xd800 || last > 0xdbff) return end;
return end - 1 > offset ? end - 1 : end + 1;
}
function timelineItem(input: {
readonly row: OrchestrationV2ThreadProjection["visibleTurnItems"][number];
readonly maxChars: number;
readonly textOffset?: number;
readonly messagesByThreadId: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection["messages"]>;
}): OrchestratorMcpThreadTimelineItem {
const text = turnItemText(input.row.item);
const offset = input.textOffset ?? 0;
const end = textPageEnd(text, offset, input.maxChars);
const textTruncated = text !== null && text.length > end;
const messageId =
input.row.item.type === "user_message" || input.row.item.type === "assistant_message"
? input.row.item.messageId
: null;
const message =
messageId === null
? undefined
: input.messagesByThreadId
.get(input.row.sourceThreadId)
?.find((candidate) => candidate.id === messageId);
return {
position: input.row.position,
visibility: input.row.visibility,
sourceThreadId: input.row.sourceThreadId,
itemId: input.row.sourceItemId,
...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}),
runId: input.row.item.runId,
messageId,
createdBy: message?.createdBy ?? null,
creationSource: message?.creationSource ?? null,
...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }),
type: input.row.item.type,
status: input.row.item.status,
title: input.row.item.title,
text: text === null ? null : text.slice(offset, end),
textTruncated,
nextTextOffset: textTruncated ? end : null,
updatedAt: DateTime.formatIso(input.row.item.updatedAt),
};
}
const make = Effect.gen(function* () {
const random = yield* SecureRandom.SecureRandom;
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerAdapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
const projects = yield* ProjectService.ProjectService;
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
const gitDriver = yield* GitVcsDriver.GitVcsDriver;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const remoteDelegation = yield* RemoteDelegation.RemoteDelegation;
const requireProject = (projectId: ProjectId) =>
projects.getById(projectId).pipe(
Effect.mapError((error) =>
failure("orchestration_error", `Unable to read project ${projectId}: ${error.message}`),
),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(failure("invalid_request", `Project ${projectId} was not found.`)),
onSome: Effect.succeed,
}),
),
);
const projectDefaultModelSelection = (
project: Effect.Success<ReturnType<typeof requireProject>>,
) =>
project.defaultModelSelection === null
? Effect.fail(
failure(
"invalid_request",
`Project ${project.id} has no default model, so this caller cannot pick one for it.`,
),
)
: Effect.succeed(project.defaultModelSelection);
const secretRequests = yield* SecretRequests.SecretRequests;
const requireCapability = (scope: McpInvocationScope) =>
scope.capabilities.has("orchestration")
? Effect.void
: Effect.fail(
failure(
"capability_denied",
"This MCP credential does not grant orchestration capabilities.",
),
);
const loadThreadRecords = <K extends ProjectionRecordField>(
threadId: ThreadId,
fields: ReadonlyArray<K>,
filter?: ProjectionRecordFilter,
) =>
threadManagement
.getThreadRecords(threadId, fields, filter)
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to read thread ${threadId}: ${errorMessage(error)}`,
),
),
);
const loadProjection = (threadId: ThreadId, includeUserMessages = true) =>
loadThreadRecords(
threadId,
[
"runs",
"messages",
"providerThreads",
"providerTurns",
"runtimeRequests",
"contextTransfers",
"turnItems",
],
{ turnItemTypes: [], messageRoles: includeUserMessages ? ["user"] : [] },
);
// A dispatcher thread holds thousands of tasks, each with its full prompt; read only the ones named.
const loadTasks = (threadId: ThreadId, taskIds: ReadonlyArray<NodeId>) =>
threadManagement.getThreadRecords(threadId, ["subagents"], { subagentIds: taskIds }).pipe(
Effect.map(({ subagents }) => subagents),
Effect.mapError((error) =>
failure("orchestration_error", `Unable to read thread ${threadId}: ${errorMessage(error)}`),
),
);
// Task waits read on every wake of a parent that may hold thousands of
// tasks, so they read only the task they watch and what its status needs.
const loadTaskParent = (threadId: ThreadId) =>
threadManagement
.getThreadRecords(threadId, ["runs", "contextTransfers"])
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to read thread ${threadId}: ${errorMessage(error)}`,
),
),
);
const loadProjectThread = (
projectId: OrchestrationV2ThreadProjection["thread"]["projectId"],
threadId: ThreadId,
) =>
threadManagement
.getProjectThreadRecords(
{ projectId, threadId },
[
"runs",
"messages",
"subagents",
"providerThreads",
"providerTurns",
"runtimeRequests",
"contextTransfers",
"turnItems",
],
{ turnItemTypes: [], messageRoles: ["user"] },
)
.pipe(Effect.mapError(threadManagementFailure));
const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* (
scope: McpInvocationScope,
) {
yield* requireCapability(scope);
if (scope.thread === undefined) {
return {
parent: undefined,
limits: clientModeCeiling(scope.client),
} as const;
}
// No loadCaller consumer reads the caller's own prompts.
const parent = yield* loadProjection(scope.thread.threadId, false);
return {
parent,
limits: {
runtimeMode: parent.thread.runtimeMode,
interactionMode: parent.thread.interactionMode,
},
} as const;
});
const loadThreadCaller = Effect.fn("OrchestratorMcpService.loadThreadCaller")(function* (
scope: McpInvocationScope,
operation: string,
) {
yield* requireCapability(scope);
const threadScope = yield* requireThreadScope(scope, operation);
const parent = yield* loadProjection(threadScope.thread.threadId);
return { scope: threadScope, parent } as const;
});
const resolveProjectTarget = (
parent: Pick<OrchestrationV2ThreadProjection, "thread"> | undefined,
projectId: ProjectId | undefined,
) =>
projectId !== undefined
? Effect.succeed(projectId)
: parent !== undefined
? Effect.succeed(parent.thread.projectId)
: Effect.fail(
failure(
"target_required",
"Pass projectId: this MCP client is not running inside a T3 thread.",
),
);
const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* (
threadId: ThreadId,
includeHistory = true,
) {
const shell = yield* threadManagement
.getThreadShell(threadId)
.pipe(Effect.mapError(threadManagementFailure));
if (shell === null || shell.deletedAt !== null) {
return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`);
}
// Native wait owns its history reads; keep legacy import and project validation here.
return yield* includeHistory
? loadProjectThread(shell.projectId, threadId)
: threadManagement
.getProjectThreadRecords({ projectId: shell.projectId, threadId }, [])
.pipe(Effect.mapError(threadManagementFailure));
});
const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* (
scope: McpInvocationScope,
threadId: ThreadId,
includeHistory = true,
) {
const caller = yield* loadCaller(scope);
const target =
caller.parent !== undefined && threadId === caller.parent.thread.id
? caller.parent
: yield* loadTargetThread(threadId, includeHistory);
return { ...caller, target } as const;
});
/** Cross-thread writes require a live caller run; stale session credentials cannot authorize them. */
const assertLiveCallerForOtherThread = (
scope: McpInvocationScope,
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined,
target: Pick<OrchestrationV2ThreadProjection, "thread">,
) =>
parent === undefined || target.thread.id === parent.thread.id
? Effect.void
: assertLiveCaller(scope, parent);
const assertLiveCallerForOtherProject = (
scope: McpInvocationScope,
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined,
projectId: ProjectId,
) =>
parent === undefined || projectId === parent.thread.projectId
? Effect.void
: assertLiveCaller(scope, parent);
const assertLiveCaller = (
scope: McpInvocationScope,
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
) => {
const notActive = failure(
"parent_not_active",
"The calling provider no longer owns an active thread run.",
);
const activeRun = ThreadManagementService.latestActiveRun(parent);
if (parent.thread.archivedAt === null && activeRun === undefined) {
// Decide from this one fresh snapshot: a run may have started since `parent` was read.
return threadManagement.getThreadShell(parent.thread.id).pipe(
Effect.mapError(threadManagementFailure),
Effect.flatMap((shell) =>
isLiveCallerShell(shell, scope.thread?.providerInstanceId)
? Effect.void
: Effect.fail(notActive),
),
);
}
return parent.thread.archivedAt !== null ||
activeRun === undefined ||
activeRun.providerInstanceId !== scope.thread?.providerInstanceId
? Effect.fail(notActive)
: Effect.void;
};
const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (
scope: McpInvocationScope,
threadId: ThreadId,
) {
const { parent } = yield* loadCaller(scope);
const shell = yield* threadManagement
.getThreadShell(threadId)
.pipe(Effect.mapError(threadManagementFailure));
if (shell === null || shell.deletedAt !== null) {
return yield* threadNotFound(
threadManagement,
threadId,
`Thread ${threadId} is no longer available.`,
);
}
const input = { projectId: shell.projectId, threadId };
// Transfers are needed only to acknowledge a caller's child-task result.
const records =
parent === undefined
? threadManagement
.getProjectThreadRecords(input, ["runs", "runtimeRequests"])
.pipe(Effect.map((target) => ({ ...target, contextTransfers: [] })))
: threadManagement.getProjectThreadRecords(input, [
"runs",
"runtimeRequests",
"contextTransfers",
]);
const target = yield* records.pipe(Effect.mapError(threadManagementFailure));
return { parent, target, shell } as const;
});
const loadProviders = providerRegistry.getProviders;
const loadOrchestrationCapableInstanceIds = () =>
providerAdapters.list().pipe(Effect.map((instanceIds) => new Set(instanceIds)));
/** Background agents miss foreground-only health probes; re-probe once before refusing. */
const assertTargetEnabledForProject = (
parent: Pick<OrchestrationV2ThreadProjection, "thread">,
commandId: CommandId,
target: ResolvedTarget,
) =>
threadManagement
.assertProviderInstanceEnabled({
projectId: parent.thread.projectId,
commandId,
instanceId: target.modelSelection.instanceId,
})
.pipe(Effect.mapError(threadManagementFailure));
const resolveTargetRechecking = (input: Parameters<typeof resolveTarget>[0]) => {
const instanceId =
input.target?.providerInstanceId ??
(input.target?.driverKind === undefined
? input.parent.thread.modelSelection.instanceId
: undefined);
const resolved = resolveTarget(input);
if (instanceId === undefined) return resolved;
return resolved.pipe(
Effect.catchIf(
(error) => error.code === "provider_unavailable",
() =>
providerRegistry
.refreshInstance(instanceId)
.pipe(Effect.flatMap((providers) => resolveTarget({ ...input, providers }))),
),
);
};
const resolveTarget = Effect.fn("OrchestratorMcpService.resolveTarget")(function* (input: {
readonly parent: Pick<OrchestrationV2ThreadProjection, "thread">;
readonly target: OrchestratorMcpTarget | undefined;
readonly providers: ReadonlyArray<ServerProvider>;
/** Receipt replays bypass current settings because they start no work. Dispatch must reuse the checked command ID. */
readonly skipProjectEnablementFilter?: boolean;
}): Effect.fn.Return<ResolvedTarget, OrchestratorMcpFailure> {
const requestedInstanceId = input.target?.providerInstanceId;
const requestedDriver = input.target?.driverKind;
const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
let instanceId = requestedInstanceId;
if (instanceId === undefined && requestedDriver !== undefined) {
const candidates = input.providers.filter(
(provider) =>
provider.driver === requestedDriver &&
orchestrationCapableInstanceIds.has(provider.instanceId),
);
if (candidates.length === 0) {
return yield* failure(
"provider_unavailable",
`No V2 provider adapter is registered for driver ${requestedDriver}.`,
);
}
const healthyCandidates = candidates.filter(
(candidate) => providerConstraints(candidate, true).length === 0,
);
const inheritedCandidate = healthyCandidates.find(
(candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
);
const orderedCandidates = [
...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),
...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),
];
for (const candidate of orderedCandidates) {
const enabledForProject =
input.skipProjectEnablementFilter === true ||
(yield* threadManagement.isProviderInstanceEnabledForProject({
projectId: input.parent.thread.projectId,
instanceId: candidate.instanceId,
}));
if (enabledForProject) {
instanceId = candidate.instanceId;
break;
}
}
if (instanceId === undefined) {
return yield* failure(
"provider_unavailable",
healthyCandidates.length === 0
? `No available V2 provider instance for driver ${requestedDriver}.`
: `No instance of driver ${requestedDriver} is enabled for this project.`,
);
}
}
instanceId ??= input.parent.thread.modelSelection.instanceId;
const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);
if (provider === undefined) {
return yield* failure(
"provider_unavailable",
`Provider instance ${instanceId} is not registered.`,
);
}
if (requestedDriver !== undefined && provider.driver !== requestedDriver) {
return yield* failure(
"invalid_request",
`Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
);
}
const constraints = providerConstraints(
provider,
orchestrationCapableInstanceIds.has(provider.instanceId),
);
if (constraints.length > 0) {
return yield* failure(
"provider_unavailable",
`Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,
);
}
const inheritedSelection = input.parent.thread.modelSelection;
const requestedModel = input.target?.model;
const model =
requestedModel ??
(instanceId === inheritedSelection.instanceId
? inheritedSelection.model
: provider.models[0]?.slug);
if (model === undefined) {
return yield* failure(
"model_unavailable",
`Provider ${instanceId} has no model available for inheritance.`,
);
}
if (
requestedModel !== undefined &&
provider.models.length > 0 &&
!provider.models.some((candidate) => candidate.slug === requestedModel)
) {
return yield* failure(
"model_unavailable",
`Model ${requestedModel} is not advertised by provider ${instanceId}.`,
);
}
const descriptors = provider.models.find((candidate) => candidate.slug === model)?.capabilities
?.optionDescriptors;
const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options);
if (requestedOptions !== undefined) {
const invalid = invalidOptionSelections(requestedOptions, descriptors);
if (invalid.length > 0) {
return yield* failure(
"invalid_request",
`Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,
);
}
}
const inheritsOptions =
instanceId === inheritedSelection.instanceId && model === inheritedSelection.model;
let options = inheritsOptions
? knownOptions(
withLegacyUltracodeEffort(descriptors, inheritedSelection.options),
descriptors,
)
: undefined;
if (requestedOptions !== undefined) {
const selections = new Map(
(requestedOptions.length === 0 ? [] : (options ?? [])).map((selection) => [
selection.id,
selection,
]),
);
for (const selection of requestedOptions) {
selections.set(selection.id, selection);
}
options = [...selections.values()];
}
return {
modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },
supportedRuntimeModes: provider.supportedRuntimeModes,
};
});
const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>
clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId);
const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* (
scope: McpThreadInvocationScope,
taskId: NodeId,
waitTimedOut = false,
acknowledgeTerminal = false,
acknowledgementOperation = "task-status-acknowledge",
): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
yield* requireCapability(scope);
const task = (yield* loadTasks(scope.thread.threadId, [taskId])).find(
(candidate) =>
candidate.id === taskId &&
candidate.origin === "app_owned" &&
candidate.threadId === scope.thread.threadId,
);
if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) {
return yield* failure(
"task_not_found",
`Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,
);
}
if (task.childThreadId === null) {
return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal);
}
const parentProjection = yield* loadTaskParent(scope.thread.threadId);
const childControls = yield* threadManagement
.getThreadRecords(
task.childThreadId,
[
"runs",
"messages",
"contextTransfers",
"subagents",
"providerThreads",
"runtimeRequests",
"nodes",
],
// Progress reads only active or undelivered tasks under the child.
{ messageRoles: ["user"], omitSettledLeafNodes: true, omitSettledSubagents: true },
)
.pipe(Effect.mapError(threadManagementFailure));
const childRun = delegatedTaskRun(childControls, task);
const terminalRun = latestTerminalResultRun(childControls, childRun);
const progress = delegatedTaskProgress(childControls);
const taskResultRun =
childRun?.delegatedTaskId === task.id
? childControls.runs
.filter((run) => run.delegatedTaskId === task.id)
.toSorted((a, b) => b.ordinal - a.ordinal)[0]
: progress.resultRun;
const taskWorkState =
childRun?.delegatedTaskId === task.id
? isTerminalTaskStatus(taskStatusForRun(taskResultRun))
? "result_available"
: "working"
: progress.state;
const resultRunIds = [
...new Set(
[taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
),
];
const resultRecords = yield* threadManagement
.getThreadRecords(task.childThreadId, ["messages", "turnItems"], {
messageRoles: ["assistant"],
messageRunIds: resultRunIds,
turnItemRunIds: resultRunIds,
turnItemTypes: ["assistant_message", "error"],
})
.pipe(Effect.mapError(threadManagementFailure));
const childProjection = {
...childControls,
messages: [...childControls.messages, ...resultRecords.messages],
turnItems: resultRecords.turnItems,
};
const heldForRestart =
task.result === null &&
taskWorkState === "result_available" &&
(yield* threadManagement
.delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)
.pipe(Effect.mapError(threadManagementFailure)));
const workState =
task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
const status =
task.result !== null
? taskStatusForRun(
task.status === "completed" ||
task.status === "failed" ||
task.status === "cancelled" ||
task.status === "interrupted"
? { status: task.status }
: childRun,
)
: workState === "result_available"
? taskStatusForRun(taskResultRun ?? childRun)
: taskStatusForRun(taskResultRun ?? childRun) === "queued"
? "queued"
: "running";
const derivedResult =
task.result !== null
? task.result
: taskResultRun !== undefined && isTerminalTaskStatus(status)
? subagentResultForRun(childProjection, taskResultRun).text
: null;
const resultTransfers = parentProjection.contextTransfers.filter(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === task.childThreadId &&
transfer.targetThreadId === scope.thread.threadId,
);
const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>
!canExposeTaskRunResult(run)
? null
: (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??
(run.id === childRun?.id
? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
: undefined) ??
null);
const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
? terminalRun.id === childRun?.id
? derivedResult
: subagentResultForRun(childProjection, terminalRun).text
: null;
const resultContextTransferId = resultTransfer?.id ?? null;
const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;
const modelSelection = childRun?.modelSelection ??
childControls.thread.modelSelection ?? {
instanceId: task.providerInstanceId,
model: task.model,
};
const result = {
taskId: task.id,
childThreadId: task.childThreadId,
link: formatThreadLink({
environmentId: scope.environmentId,
threadId: task.childThreadId,
}),
childRunId: childRun?.id ?? null,
childNodeId: task.id,
status,
workState,
hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
providerInstanceId: modelSelection.instanceId,
model: modelSelection.model,
options: modelSelection.options ?? [],
summary: derivedResult,
resultContextTransferId,
latestTerminalRunId: terminalRun?.id ?? null,
latestTerminalStatus:
terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,
latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary,
latestTerminalResultContextTransferId:
latestTerminalResultContextTransferId === resultContextTransferId
? null
: latestTerminalResultContextTransferId,
hasPendingQuestion:
!isTerminalTaskStatus(status) &&
childControls.runtimeRequests.some(
(request) =>
request.kind === "user_input" &&
request.status === "pending" &&
request.responseCapability.type === "live",
),
pendingApproval:
isTerminalTaskStatus(status) || task.completionDelivery?.state === "disposed"
? null
: pendingTaskApproval(childControls, task.id, childRun),
waitTimedOut,
} satisfies OrchestratorMcpDelegateTaskResult;
const response: OrchestratorMcpDelegateTaskResult =
endsTaskWait(result) || task.completionDelivery?.state === "disposed"
? result
: { ...result, next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT };
if (
acknowledgeTerminal &&
isTerminalTaskStatus(status) &&
task.completionDelivery?.state !== "acknowledged" &&
task.completionDelivery?.state !== "disposed"
) {
const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
const acknowledgementRequestKey = yield* requestKey(undefined);
yield* threadManagement
.dispatch({
type: "delegated_task.completion-delivery.acknowledge",
commandId: stableCommandId({
scope,
requestKey: acknowledgementRequestKey,
operation: acknowledgementOperation,
}),
parentThreadId: scope.thread.threadId,
taskId,
observedByRunId:
observingRun?.providerInstanceId === scope.thread.providerInstanceId
? observingRun.id
: null,
})
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,
),
),
);
}
return response;
});
/** `mode=wait` on a task already recorded, as `delegateTask` does for its own. */
const awaitTask = Effect.fn("OrchestratorMcpService.awaitTask")(function* (
scope: McpThreadInvocationScope,
taskId: NodeId,
requestedTimeoutMs: number | undefined,
): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
const timeoutMs = Math.min(
MAX_WAIT_TIMEOUT_MS,
Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
);
const waited = yield* waitForTask(scope, taskId, timeoutMs);
if (Option.isSome(waited)) return waited.value;
// As for a local task: once the blocking wait ends, a later result wakes the parent.
yield* threadManagement
.dispatch({
type: "delegated_task.wake-policy",
commandId: stableCommandId({
scope,
requestKey: taskId,
operation: "delegate-task-wake-policy",
}),
parentThreadId: scope.thread.threadId,
taskId,
completionWake: "always",
})
.pipe(Effect.ignoreCause({ log: true }));
return yield* readTask(scope, taskId, true, true);
});
/**
* A task that runs in a linked environment, answered from its row here:
* the follower records its result once its thread there ends.
*/
const readRemoteTask = Effect.fn("OrchestratorMcpService.readRemoteTask")(function* (
scope: McpThreadInvocationScope,
task: OrchestrationV2Subagent,
waitTimedOut: boolean,
acknowledgeTerminal: boolean,
): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
const status: OrchestratorMcpDelegateTaskResult["status"] =
task.result === null
? "running"
: task.status === "completed" ||
task.status === "failed" ||