Add orchestration MCP toolkit

- Register orchestration tools on the MCP HTTP server
- Grant orchestration capability to MCP sessions
- Add service and integration coverage for delegated tasks and thread creation
This commit is contained in:
Julius Marminge committed 2026-08-14 11:22:51 +02:00
1 parent 3596d26659
commit b38863bbd2
26 files changed
+3209 -706

No files matched your search

+12 -1
View File
@@ -11,8 +11,11 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstab
import packageJson from "../../package.json" with { type: "json" };
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
import { OrchestratorToolkitHandlersLive } from "./toolkits/orchestrator/handlers.ts";
import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
import {
PreviewSnapshotToolkitHandlersLive,
PreviewStandardToolkitHandlersLive,
@@ -216,6 +219,11 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive,
);
export const OrchestratorToolkitRegistrationLive = McpServer.toolkit(OrchestratorToolkit).pipe(
Layer.provide(OrchestratorToolkitHandlersLive),
Layer.provide(OrchestratorMcpService.layer),
);
const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
@@ -223,4 +231,7 @@ const McpTransportLive = McpServer.layerHttp({
protocols: [McpProtocol.v2025_06_18],
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = Layer.mergeAll(
PreviewToolkitRegistrationLive,
OrchestratorToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive), Layer.provide(PreviewAutomationBroker.layer));
+1 -1
View File
@@ -7,7 +7,7 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
export type McpCapability = "preview";
export type McpCapability = "preview" | "orchestration";
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
@@ -46,6 +46,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
const resolved = yield* registry.resolve(token);
expect(resolved?.threadId).toBe(threadId);
expect(resolved?.capabilities).toEqual(new Set(["preview", "orchestration"]));
yield* registry.revokeThread(threadId);
expect(yield* registry.resolve(token)).toBeUndefined();
+1 -1
View File
@@ -128,7 +128,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
threadId: ThreadId.make(request.threadId),
providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview"]),
capabilities: new Set(["preview", "orchestration"]),
issuedAt,
};
yield* SynchronizedRef.update(state, ({ records }) => {
@@ -0,0 +1,725 @@
import {
CommandId,
isProviderAvailable,
MessageId,
type ModelSelection,
NodeId,
type OrchestrationV2Run,
type OrchestrationV2ThreadProjection,
OrchestratorMcpFailure,
type OrchestratorMcpCapabilitiesResult,
type OrchestratorMcpCreateThreadsInput,
type OrchestratorMcpCreateThreadsResult,
type OrchestratorMcpCreatedThread,
type OrchestratorMcpDelegateTaskInput,
type OrchestratorMcpDelegateTaskResult,
type OrchestratorMcpInteractionMode,
type OrchestratorMcpRuntimeMode,
type OrchestratorMcpTarget,
type OrchestratorMcpTaskCancelInput,
type OrchestratorMcpTaskCancelResult,
type ProviderInteractionMode,
ProviderInstanceId,
type RuntimeMode,
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { isBuiltInProviderAdapterDriverV2 } from "../orchestration-v2/builtInProviderAdapterDrivers.ts";
import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
import { subagentResultForRun } from "../orchestration-v2/SubagentProjection.ts";
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
const TASK_POLL_INTERVAL_MS = 50;
interface ResolvedTarget {
readonly modelSelection: ModelSelection;
}
type TerminalTaskStatus = Extract<
OrchestratorMcpDelegateTaskResult["status"],
"completed" | "failed" | "cancelled" | "interrupted"
>;
export interface OrchestratorMcpServiceShape {
readonly capabilities: (
scope: McpInvocationScope,
) => 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>;
}
export class OrchestratorMcpService extends Context.Service<
OrchestratorMcpService,
OrchestratorMcpServiceShape
>()("t3/mcp/OrchestratorMcpService") {}
function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
return new OrchestratorMcpFailure({ code, message });
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
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 (!provider.enabled) constraints.push("Provider instance is disabled.");
if (!provider.installed) constraints.push("Provider executable is not installed.");
if (!isProviderAvailable(provider)) {
constraints.push(provider.unavailableReason ?? "Provider driver is unavailable.");
}
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;
}
function isActiveRun(run: OrchestrationV2Run): boolean {
return run.status === "starting" || run.status === "running" || run.status === "waiting";
}
function taskStatusForRun(
run: OrchestrationV2Run | undefined,
): OrchestratorMcpDelegateTaskResult["status"] {
switch (run?.status) {
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 "starting":
case "running":
case undefined:
return "running";
}
}
function isTerminalTaskStatus(
status: OrchestratorMcpDelegateTaskResult["status"],
): status is TerminalTaskStatus {
return (
status === "completed" ||
status === "failed" ||
status === "cancelled" ||
status === "interrupted"
);
}
function runtimeModeRank(mode: RuntimeMode): number {
switch (mode) {
case "approval-required":
return 0;
case "auto-accept-edits":
return 1;
case "full-access":
return 2;
}
}
function interactionModeRank(mode: ProviderInteractionMode): number {
return mode === "plan" ? 0 : 1;
}
function resolveRuntimeMode(
parentMode: RuntimeMode,
requested: OrchestratorMcpRuntimeMode | undefined,
): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {
const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
return runtimeModeRank(resolved) > runtimeModeRank(parentMode)
? Effect.fail(
failure(
"runtime_mode_escalation_denied",
`Child runtime mode ${resolved} is broader than parent mode ${parentMode}.`,
),
)
: Effect.succeed(resolved);
}
function resolveInteractionMode(
parentMode: ProviderInteractionMode,
requested: OrchestratorMcpInteractionMode | undefined,
): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {
const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
return interactionModeRank(resolved) > interactionModeRank(parentMode)
? Effect.fail(
failure(
"interaction_mode_escalation_denied",
`Child interaction mode ${resolved} is broader than parent mode ${parentMode}.`,
),
)
: Effect.succeed(resolved);
}
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.providerSessionId),
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.providerSessionId),
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.providerSessionId),
stablePart(input.requestKey),
String(input.index),
].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}`;
return detail.length > 80 ? `${detail.slice(0, 77)}...` : detail;
}
function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string {
return input.role === undefined || input.role === "general"
? input.task
: `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`;
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrator = yield* OrchestratorV2;
const providerRegistry = yield* ProviderRegistry;
const requireCapability = (scope: McpInvocationScope) =>
scope.capabilities.has("orchestration")
? Effect.void
: Effect.fail(
failure(
"capability_denied",
"This MCP credential does not grant orchestration capabilities.",
),
);
const loadProjection = (threadId: ThreadId) =>
orchestrator
.getThreadProjection(threadId)
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to read thread ${threadId}: ${errorMessage(error)}`,
),
),
);
const loadProviders = providerRegistry.getProviders;
const resolveTarget = (input: {
readonly parent: OrchestrationV2ThreadProjection;
readonly target: OrchestratorMcpTarget | undefined;
readonly providers: ReadonlyArray<ServerProvider>;
}): Effect.Effect<ResolvedTarget, OrchestratorMcpFailure> =>
Effect.gen(function* () {
const requestedInstanceId = input.target?.providerInstanceId;
const requestedDriver = input.target?.driverKind;
let instanceId = requestedInstanceId;
if (instanceId === undefined && requestedDriver !== undefined) {
const candidates = input.providers.filter(
(provider) =>
provider.driver === requestedDriver &&
isBuiltInProviderAdapterDriverV2(provider.driver),
);
if (candidates.length === 0) {
return yield* failure(
"provider_unavailable",
`No V2 provider adapter is registered for driver ${requestedDriver}.`,
);
}
const inheritedCandidate = candidates.find(
(candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
);
const availableCandidate = candidates.find((candidate) => {
return (
providerConstraints(candidate, isBuiltInProviderAdapterDriverV2(candidate.driver))
.length === 0
);
});
instanceId = inheritedCandidate?.instanceId ?? availableCandidate?.instanceId;
}
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,
isBuiltInProviderAdapterDriverV2(provider.driver),
);
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 !== 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}.`,
);
}
return {
modelSelection:
instanceId === inheritedSelection.instanceId && model === inheritedSelection.model
? inheritedSelection
: { instanceId, model },
};
});
const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>
clientRequestId === undefined
? crypto.randomUUIDv4.pipe(Effect.orDie)
: Effect.succeed(clientRequestId);
const readTask = (
scope: McpInvocationScope,
taskId: NodeId,
waitTimedOut = false,
): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>
Effect.gen(function* () {
yield* requireCapability(scope);
const parentProjection = yield* loadProjection(scope.threadId);
const task = parentProjection.subagents.find(
(candidate) =>
candidate.id === taskId &&
candidate.origin === "app_owned" &&
candidate.threadId === scope.threadId,
);
if (task === undefined || task.childThreadId === null) {
return yield* failure(
"task_not_found",
`Delegated task ${taskId} does not belong to thread ${scope.threadId}.`,
);
}
const childProjection = yield* loadProjection(task.childThreadId);
const childRun = childProjection.runs[0];
const status = taskStatusForRun(childRun);
const derivedResult =
task.result !== null
? task.result
: childRun !== undefined && isTerminalTaskStatus(status)
? subagentResultForRun(childProjection, childRun).text
: null;
const resultTransfer =
parentProjection.contextTransfers.find(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === task.childThreadId &&
transfer.targetThreadId === scope.threadId,
) ?? null;
return {
taskId: task.id,
childThreadId: task.childThreadId,
childRunId: childRun?.id ?? null,
childNodeId: task.id,
status,
providerInstanceId: ProviderInstanceId.make(task.provider),
model: task.model,
summary: derivedResult,
resultContextTransferId: resultTransfer?.id ?? null,
waitTimedOut,
};
});
const waitForTask = (scope: McpInvocationScope, taskId: NodeId, timeoutMs: number) =>
Effect.gen(function* () {
while (true) {
const result = yield* readTask(scope, taskId);
if (isTerminalTaskStatus(result.status)) return result;
yield* Effect.sleep(Duration.millis(TASK_POLL_INTERVAL_MS));
}
}).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)));
return OrchestratorMcpService.of({
capabilities: (scope) =>
Effect.gen(function* () {
yield* requireCapability(scope);
const parent = yield* loadProjection(scope.threadId);
const providers = yield* loadProviders;
return {
parentThreadId: scope.threadId,
inheritedProviderInstanceId: parent.thread.modelSelection.instanceId,
inheritedModel: parent.thread.modelSelection.model,
runtimeMode: parent.thread.runtimeMode,
interactionMode: parent.thread.interactionMode,
providers: providers.map((provider) => {
const constraints = providerConstraints(
provider,
isBuiltInProviderAdapterDriverV2(provider.driver),
);
return {
providerInstanceId: provider.instanceId,
driverKind: provider.driver,
displayName: provider?.displayName ?? null,
models:
provider?.models.map((model) => ({
id: model.slug,
label: model.name ?? null,
})) ?? [],
canRunChildTask: constraints.length === 0,
canRunCrossProviderChildTask: constraints.length === 0,
constraints: [...constraints],
};
}),
features: {
appOwnedSubagents: true,
asyncPolling: true,
cancellation: true,
batchThreadCreation: true,
maxBatchThreads: 20,
},
};
}),
delegateTask: (scope, input) =>
Effect.gen(function* () {
yield* requireCapability(scope);
const parent = yield* loadProjection(scope.threadId);
const parentRun = parent.runs
.filter(isActiveRun)
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
if (
parentRun === undefined ||
parentRun.rootNodeId === null ||
parentRun.provider !== scope.providerInstanceId
) {
return yield* failure(
"parent_not_active",
"Delegated tasks require an active run owned by this MCP provider session.",
);
}
const providers = yield* loadProviders;
const target = yield* resolveTarget({
parent,
target: input.target,
providers,
});
const runtimeMode = yield* resolveRuntimeMode(parent.thread.runtimeMode, input.runtimeMode);
const interactionMode = yield* resolveInteractionMode(
parent.thread.interactionMode,
input.interactionMode,
);
const key = yield* requestKey(input.clientRequestId);
const commandId = stableCommandId({
scope,
requestKey: key,
operation: "delegate-task",
});
const result = yield* orchestrator
.dispatch({
type: "delegated_task.request",
commandId,
parentThreadId: scope.threadId,
parentRunId: parentRun.id,
parentNodeId: parentRun.rootNodeId,
task: taskPrompt(input),
...(input.title === undefined ? {} : { title: input.title }),
modelSelection: target.modelSelection,
runtimeMode,
interactionMode,
})
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to create delegated task: ${errorMessage(error)}`,
),
),
);
const taskEvent = result.storedEvents.find(
(stored) =>
stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",
);
if (taskEvent?.event.type !== "subagent.updated") {
return yield* failure(
"orchestration_error",
"Delegated task command did not produce a task projection.",
);
}
if (input.mode !== "wait") {
return yield* readTask(scope, taskEvent.event.payload.id);
}
const timeoutMs = Math.min(
MAX_WAIT_TIMEOUT_MS,
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
);
const waited = yield* waitForTask(scope, taskEvent.event.payload.id, timeoutMs);
return Option.isSome(waited)
? waited.value
: yield* readTask(scope, taskEvent.event.payload.id, true);
}),
taskStatus: (scope, taskId) => readTask(scope, taskId),
cancelTask: (scope, input) =>
Effect.gen(function* () {
const current = yield* readTask(scope, input.taskId);
if (isTerminalTaskStatus(current.status)) {
return {
taskId: input.taskId,
status: current.status,
} satisfies OrchestratorMcpTaskCancelResult;
}
const child = yield* loadProjection(current.childThreadId);
const activeRun = child.runs.find(isActiveRun);
if (activeRun === undefined) {
return yield* failure(
"task_not_cancellable",
`Delegated task ${input.taskId} has no interruptible child run.`,
);
}
const key = yield* requestKey(input.clientRequestId);
yield* orchestrator
.dispatch({
type: "run.interrupt",
commandId: stableCommandId({
scope,
requestKey: key,
operation: "cancel-task",
}),
threadId: current.childThreadId,
runId: activeRun.id,
...(input.reason === undefined ? {} : { reason: input.reason }),
})
.pipe(
Effect.mapError((error) =>
failure(
"task_not_cancellable",
`Unable to interrupt delegated task ${input.taskId}: ${errorMessage(error)}`,
),
),
);
return {
taskId: input.taskId,
status: "cancel_requested",
};
}),
createThreads: (scope, input) =>
Effect.gen(function* () {
yield* requireCapability(scope);
const parent = yield* loadProjection(scope.threadId);
const providers = yield* loadProviders;
const key = yield* requestKey(input.clientRequestId);
const created = yield* Effect.forEach(
input.threads,
(request, index) =>
Effect.gen(function* () {
const target = yield* resolveTarget({
parent,
target: request.target,
providers,
});
const runtimeMode = yield* resolveRuntimeMode(
parent.thread.runtimeMode,
request.runtimeMode,
);
const interactionMode = yield* resolveInteractionMode(
parent.thread.interactionMode,
request.interactionMode,
);
const threadId = stableThreadId({
scope,
requestKey: key,
index,
});
const title = threadTitle({
parentTitle: parent.thread.title,
prompt: request.prompt,
title: request.title,
index,
});
yield* orchestrator
.dispatch({
type: "thread.create",
commandId: stableCommandId({
scope,
requestKey: key,
operation: "create-thread",
index,
}),
threadId,
projectId: parent.thread.projectId,
title,
modelSelection: target.modelSelection,
runtimeMode,
interactionMode,
branch: parent.thread.branch,
worktreePath: parent.thread.worktreePath,
})
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to create thread ${index + 1}: ${errorMessage(error)}`,
),
),
);
if (request.prompt !== undefined) {
yield* orchestrator
.dispatch({
type: "message.dispatch",
commandId: stableCommandId({
scope,
requestKey: key,
operation: "dispatch-thread",
index,
}),
threadId,
messageId: stableMessageId({
scope,
requestKey: key,
index,
}),
text: request.prompt,
attachments: [],
modelSelection: target.modelSelection,
dispatchMode: { type: "start_immediately" },
})
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to start thread ${index + 1}: ${errorMessage(error)}`,
),
),
);
}
const projection = yield* loadProjection(threadId);
const run = projection.runs.at(-1);
return {
threadId,
runId: run?.id ?? null,
status: run?.status ?? "idle",
title: projection.thread.title,
providerInstanceId: target.modelSelection.instanceId,
model: target.modelSelection.model,
} satisfies OrchestratorMcpCreatedThread;
}),
{ concurrency: 1 },
);
return { threads: created };
}),
});
});
export const layer: Layer.Layer<
OrchestratorMcpService,
never,
Crypto.Crypto | OrchestratorV2 | ProviderRegistry
> = Layer.effect(OrchestratorMcpService, make);
@@ -0,0 +1,686 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import {
CommandId,
EnvironmentId,
MessageId,
type ModelSelection,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ThreadProjection,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskResult,
OrchestratorMcpTaskCancelResult,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
type ProviderKind,
ProviderThreadId,
ProviderTurnId,
type ServerProvider,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
import { OrchestratorV2, type OrchestratorV2Shape } from "../orchestration-v2/Orchestrator.ts";
import {
type ProviderAdapterV2Event,
ProviderAdapterProtocolError,
type ProviderAdapterV2Shape,
type ProviderAdapterV2TurnInput,
} from "../orchestration-v2/ProviderAdapter.ts";
import { makeLayer as makeProviderAdapterRegistryLayer } from "../orchestration-v2/ProviderAdapterRegistry.ts";
import { checkpointWorkspace } from "../orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
import { makeOrchestratorV2ReplayLayerWithRegistry } from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
const parentThreadId = ThreadId.make("thread:mcp-orchestrator-parent");
const projectId = ProjectId.make("project:mcp-orchestrator");
const codexInstanceId = ProviderInstanceId.make("codex");
const claudeInstanceId = ProviderInstanceId.make("claudeAgent");
const codexModel = "gpt-5.4";
const claudeModel = "claude-sonnet-4-6";
const parentPrompt = "Keep this parent turn active while orchestration tools are tested.";
const delegatedPrompt = "Inspect the delegated API boundary and return the result.";
const delegatedResult = "Delegated API boundary inspected.";
const cancellationPrompt = "Remain active until the parent cancels this delegated task.";
const createdThreadPrompt = "Complete the newly created ordinary thread.";
const decodeCreateThreadsResult = Schema.decodeUnknownEffect(OrchestratorMcpCreateThreadsResult);
const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult);
const decodeTaskCancelResult = Schema.decodeUnknownEffect(OrchestratorMcpTaskCancelResult);
const codexSelection = {
instanceId: codexInstanceId,
model: codexModel,
} satisfies ModelSelection;
const claudeSelection = {
instanceId: claudeInstanceId,
model: claudeModel,
} satisfies ModelSelection;
interface CapturedTurn {
readonly instanceId: ProviderInstanceId;
readonly threadId: ThreadId;
readonly text: string;
}
function unsupported(provider: ProviderKind, detail: string) {
return Effect.fail(new ProviderAdapterProtocolError({ provider, detail }));
}
function makeProviderSnapshot(input: {
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
readonly model: string;
}): ServerProvider {
return {
instanceId: input.instanceId,
driver: input.driver,
enabled: true,
installed: true,
version: "test",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-06-17T00:00:00.000Z",
models: [
{
slug: input.model,
name: input.model,
isCustom: false,
capabilities: null,
},
],
slashCommands: [],
skills: [],
};
}
function makeDeterministicAdapter(input: {
readonly instanceId: ProviderInstanceId;
readonly provider: ProviderKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
readonly shouldComplete: (turn: ProviderAdapterV2TurnInput) => boolean;
readonly response: (turn: ProviderAdapterV2TurnInput) => string;
}): ProviderAdapterV2Shape {
return {
instanceId: input.instanceId,
provider: input.provider,
getCapabilities: () => Effect.succeed(input.capabilities),
openSession: (sessionInput) =>
Effect.gen(function* () {
const events = yield* PubSub.unbounded<ProviderAdapterV2Event>();
const now = yield* DateTime.now;
const providerSession: OrchestrationV2ProviderSession = {
id: sessionInput.providerSessionId,
provider: input.provider,
status: "ready",
cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
model: sessionInput.modelSelection.model,
capabilities: input.capabilities,
createdAt: now,
updatedAt: now,
lastError: null,
};
const publish = (providerEvents: ReadonlyArray<ProviderAdapterV2Event>) =>
Effect.forEach(providerEvents, (event) => PubSub.publish(events, event), {
discard: true,
});
return {
instanceId: input.instanceId,
provider: input.provider,
providerSessionId: sessionInput.providerSessionId,
providerSession,
rawEvents: Stream.empty,
events: Stream.fromPubSub(events),
ensureThread: (threadInput) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const nativeThreadId = `${input.provider}:${threadInput.threadId}`;
return {
id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
provider: input.provider,
providerSessionId: sessionInput.providerSessionId,
appThreadId: threadInput.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: input.provider,
nativeId: nativeThreadId,
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: null,
createdAt,
updatedAt: createdAt,
} satisfies OrchestrationV2ProviderThread;
}),
resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
startTurn: (turnInput) =>
Effect.gen(function* () {
yield* Ref.update(input.capturedTurns, (turns) => [
...turns,
{
instanceId: input.instanceId,
threadId: turnInput.threadId,
text: turnInput.message.text,
},
]);
const eventTime = yield* DateTime.now;
const providerTurnId = ProviderTurnId.make(
`provider-turn:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}`,
);
yield* publish([
{
type: "provider_turn.updated",
provider: input.provider,
providerTurn: {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: {
provider: input.provider,
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
strength: "strong",
},
ordinal: turnInput.providerTurnOrdinal,
status: "running",
startedAt: eventTime,
completedAt: null,
},
},
]);
if (!input.shouldComplete(turnInput)) {
return;
}
const response = input.response(turnInput);
yield* publish([
{
type: "provider_turn.updated",
provider: input.provider,
providerTurn: {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: {
provider: input.provider,
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
strength: "strong",
},
ordinal: turnInput.providerTurnOrdinal,
status: "completed",
startedAt: eventTime,
completedAt: eventTime,
},
},
{
type: "turn_item.updated",
provider: input.provider,
turnItem: {
id: TurnItemId.make(
`turn-item:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
),
threadId: turnInput.threadId,
runId: turnInput.runId,
nodeId: turnInput.rootNodeId,
providerThreadId: turnInput.providerThread.id,
providerTurnId,
nativeItemRef: null,
parentItemId: null,
ordinal: turnInput.runOrdinal * 100 + 1,
status: "completed",
title: null,
startedAt: eventTime,
completedAt: eventTime,
updatedAt: eventTime,
type: "assistant_message",
messageId: MessageId.make(
`message:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
),
text: response,
streaming: false,
},
},
{
type: "turn.terminal",
provider: input.provider,
providerTurnId,
status: "completed",
},
]);
}),
steerTurn: () => Effect.void,
interruptTurn: ({ providerTurnId }) =>
PubSub.publish(events, {
type: "turn.terminal",
provider: input.provider,
providerTurnId,
status: "interrupted",
}).pipe(Effect.asVoid),
respondToRuntimeRequest: () => Effect.void,
readThreadSnapshot: () =>
unsupported(input.provider, "readThreadSnapshot is unused in this test"),
rollbackThread: () =>
unsupported(input.provider, "rollbackThread is unused in this test"),
forkThread: () => unsupported(input.provider, "forkThread is unused in this test"),
};
}),
};
}
function waitForProjection(
orchestrator: OrchestratorV2Shape,
threadId: ThreadId,
predicate: (projection: OrchestrationV2ThreadProjection) => boolean,
) {
return Effect.gen(function* () {
for (let attempt = 0; attempt < 1_000; attempt += 1) {
const projection = yield* orchestrator.getThreadProjection(threadId);
if (predicate(projection)) {
return projection;
}
yield* Effect.sleep("5 millis");
}
return yield* Effect.die(
new Error(`Timed out waiting for orchestration projection ${threadId}.`),
);
});
}
const client = McpSchema.McpServerClient.of({
clientId: 1,
initializePayload: {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "orchestrator-mcp-test", version: "1.0.0" },
},
getClient: Effect.die("unused"),
});
describe("orchestrator MCP toolkit", () => {
it.live(
"delegates cross-provider tasks, polls and cancels children, and creates ordinary threads",
() =>
Effect.scoped(
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace("orchestrator-mcp-toolkit");
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const registryLayer = makeProviderAdapterRegistryLayer([
makeDeterministicAdapter({
instanceId: codexInstanceId,
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
capturedTurns,
shouldComplete: (turn) =>
turn.threadId !== parentThreadId && turn.message.text !== cancellationPrompt,
response: (turn) => `Codex completed: ${turn.message.text}`,
}),
makeDeterministicAdapter({
instanceId: claudeInstanceId,
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
capturedTurns,
shouldComplete: () => true,
response: (turn) =>
turn.message.text === delegatedPrompt
? delegatedResult
: `Claude completed: ${turn.message.text}`,
}),
]);
const orchestratorLayer = makeOrchestratorV2ReplayLayerWithRegistry(
{
name: "orchestrator-mcp-toolkit",
runtimePolicyOverride: {
cwd,
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: { type: "fullAccess" },
networkAccess: false,
},
},
},
registryLayer,
);
const providerRegistryLayer = makeProviderRegistryLayer([
makeProviderSnapshot({
instanceId: codexInstanceId,
driver: ProviderDriverKind.make("codex"),
model: codexModel,
}),
makeProviderSnapshot({
instanceId: claudeInstanceId,
driver: ProviderDriverKind.make("claudeAgent"),
model: claudeModel,
}),
makeProviderSnapshot({
instanceId: ProviderInstanceId.make("opencode"),
driver: ProviderDriverKind.make("opencode"),
model: "opencode/test",
}),
]);
const testLayer = McpHttpServer.OrchestratorToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(orchestratorLayer),
Layer.provide(providerRegistryLayer),
Layer.provide(NodeServices.layer),
);
yield* Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const server = yield* McpServer.McpServer;
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make("command:mcp-parent:create"),
threadId: parentThreadId,
projectId,
title: "MCP parent",
modelSelection: codexSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: cwd,
});
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make("command:mcp-parent:start"),
threadId: parentThreadId,
messageId: MessageId.make("message:mcp-parent:start"),
text: parentPrompt,
attachments: [],
modelSelection: codexSelection,
dispatchMode: { type: "start_immediately" },
});
const parent = yield* waitForProjection(
orchestrator,
parentThreadId,
(projection) =>
projection.runs.some((run) =>
["starting", "running", "waiting"].includes(run.status),
) && projection.providerTurns.some((turn) => turn.status === "running"),
);
const parentRun = parent.runs[0];
expect(parentRun?.status).toBe("running");
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-orchestrator"),
threadId: parentThreadId,
providerSessionId: "mcp-provider-session-parent",
providerInstanceId: codexInstanceId,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};
const invoke = (name: string, args: Record<string, unknown>) =>
server
.callTool({ name, arguments: args })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
const capabilitiesTool = server.tools.find(
({ tool }) => tool.name === "orchestrator_capabilities",
);
expect(capabilitiesTool?.tool.annotations?.readOnlyHint).toBe(true);
expect(capabilitiesTool?.tool.annotations?.idempotentHint).toBe(true);
const delegateTool = server.tools.find(({ tool }) => tool.name === "delegate_task");
expect(delegateTool?.tool.annotations?.destructiveHint).toBe(true);
expect(delegateTool?.tool.annotations?.openWorldHint).toBe(true);
const createThreadsTool = server.tools.find(
({ tool }) => tool.name === "create_threads",
);
expect(createThreadsTool?.tool.annotations?.destructiveHint).toBe(true);
const capabilities = yield* invoke("orchestrator_capabilities", {});
expect(capabilities.isError).toBe(false);
expect(capabilities.structuredContent).toMatchObject({
inheritedProviderInstanceId: codexInstanceId,
inheritedModel: codexModel,
features: {
appOwnedSubagents: true,
asyncPolling: true,
cancellation: true,
batchThreadCreation: true,
},
providers: expect.arrayContaining([
expect.objectContaining({
providerInstanceId: claudeInstanceId,
canRunCrossProviderChildTask: true,
}),
expect.objectContaining({
providerInstanceId: "opencode",
canRunChildTask: false,
}),
]),
});
const delegatedCall = yield* invoke("delegate_task", {
task: delegatedPrompt,
target: {
providerInstanceId: claudeInstanceId,
model: claudeModel,
},
mode: "wait",
timeoutMs: 10_000,
clientRequestId: "delegate-claude-1",
});
expect(delegatedCall.isError).toBe(false);
const delegated = yield* decodeDelegateTaskResult(delegatedCall.structuredContent).pipe(
Effect.orDie,
);
expect(delegated.status).toBe("completed");
expect(delegated.summary).toBe(delegatedResult);
expect(delegated.providerInstanceId).toBe(claudeInstanceId);
const completedParent = yield* waitForProjection(
orchestrator,
parentThreadId,
(projection) =>
projection.subagents.some(
(task) =>
task.id === delegated.taskId &&
task.status === "completed" &&
task.result === delegatedResult,
) &&
projection.contextTransfers.some(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === delegated.childThreadId,
),
);
const completedTask = completedParent.subagents.find(
(task) => task.id === delegated.taskId,
);
expect(completedTask).toMatchObject({
origin: "app_owned",
createdBy: "agent",
childThreadId: delegated.childThreadId,
status: "completed",
result: delegatedResult,
});
const child = yield* orchestrator.getThreadProjection(delegated.childThreadId);
expect(child.thread.lineage).toEqual({
parentThreadId,
relationshipToParent: "subagent",
rootThreadId: parentThreadId,
});
expect(child.thread.modelSelection).toEqual(claudeSelection);
expect(
child.messages
.filter((message) => message.role === "user")
.map((message) => message.text),
).toEqual([delegatedPrompt]);
expect(
child.contextTransfers.some(
(transfer) =>
transfer.type === "subagent_spawn" && transfer.sourceThreadId === parentThreadId,
),
).toBe(true);
const capturedAfterDelegate = yield* Ref.get(capturedTurns);
expect(
capturedAfterDelegate.filter((turn) => turn.threadId === delegated.childThreadId),
).toEqual([
{
instanceId: claudeInstanceId,
threadId: delegated.childThreadId,
text: delegatedPrompt,
},
]);
expect(
capturedAfterDelegate.some(
(turn) =>
turn.threadId === delegated.childThreadId && turn.text.includes(parentPrompt),
),
).toBe(false);
const delegatedStatusCall = yield* invoke("task_status", {
taskId: delegated.taskId,
});
const delegatedStatus = yield* decodeDelegateTaskResult(
delegatedStatusCall.structuredContent,
).pipe(Effect.orDie);
expect(delegatedStatus.status).toBe("completed");
expect(delegatedStatus.resultContextTransferId).not.toBeNull();
const repeatedDelegatedCall = yield* invoke("delegate_task", {
task: delegatedPrompt,
target: {
providerInstanceId: claudeInstanceId,
model: claudeModel,
},
mode: "async",
clientRequestId: "delegate-claude-1",
});
const repeatedDelegated = yield* decodeDelegateTaskResult(
repeatedDelegatedCall.structuredContent,
).pipe(Effect.orDie);
expect(repeatedDelegated.taskId).toBe(delegated.taskId);
expect(
(yield* orchestrator.getThreadProjection(parentThreadId)).subagents.filter(
(task) => task.id === delegated.taskId,
),
).toHaveLength(1);
const cancellableCall = yield* invoke("delegate_task", {
task: cancellationPrompt,
target: {
providerInstanceId: codexInstanceId,
model: codexModel,
},
mode: "async",
clientRequestId: "delegate-cancel-1",
});
const cancellable = yield* decodeDelegateTaskResult(
cancellableCall.structuredContent,
).pipe(Effect.orDie);
expect(cancellable.status).toBe("running");
yield* waitForProjection(orchestrator, cancellable.childThreadId, (projection) =>
projection.providerTurns.some((turn) => turn.status === "running"),
);
const cancelCall = yield* invoke("task_cancel", {
taskId: cancellable.taskId,
reason: "Parent no longer needs this work.",
clientRequestId: "cancel-1",
});
const cancelResult = yield* decodeTaskCancelResult(cancelCall.structuredContent).pipe(
Effect.orDie,
);
expect(cancelResult.status).toBe("cancel_requested");
yield* waitForProjection(orchestrator, cancellable.childThreadId, (projection) =>
projection.runs.some((run) => run.status === "interrupted"),
);
const cancelledStatusCall = yield* invoke("task_status", {
taskId: cancellable.taskId,
});
const cancelledStatus = yield* decodeDelegateTaskResult(
cancelledStatusCall.structuredContent,
).pipe(Effect.orDie);
expect(cancelledStatus.status).toBe("interrupted");
const createInput = {
clientRequestId: "create-thread-batch-1",
threads: [
{
title: "Inherited empty thread",
},
{
title: "Claude ordinary thread",
prompt: createdThreadPrompt,
target: {
driverKind: "claudeAgent",
},
},
],
};
const createCall = yield* invoke("create_threads", createInput);
expect(createCall.isError).toBe(false);
const created = yield* decodeCreateThreadsResult(createCall.structuredContent).pipe(
Effect.orDie,
);
expect(created.threads).toHaveLength(2);
const emptyThread = created.threads[0]!;
const promptedThread = created.threads[1]!;
expect(emptyThread).toMatchObject({
status: "idle",
providerInstanceId: codexInstanceId,
model: codexModel,
});
expect(promptedThread).toMatchObject({
providerInstanceId: claudeInstanceId,
model: claudeModel,
});
const emptyProjection = yield* orchestrator.getThreadProjection(emptyThread.threadId);
expect(emptyProjection.thread.lineage).toEqual({
parentThreadId: null,
relationshipToParent: null,
rootThreadId: emptyThread.threadId,
});
expect(emptyProjection.thread.forkedFrom).toBeNull();
expect(emptyProjection.runs).toEqual([]);
const promptedProjection = yield* waitForProjection(
orchestrator,
promptedThread.threadId,
(projection) => projection.runs.some((run) => run.status === "completed"),
);
expect(promptedProjection.thread.lineage.parentThreadId).toBeNull();
expect(
promptedProjection.messages
.filter((message) => message.role === "user")
.map((message) => message.text),
).toEqual([createdThreadPrompt]);
const repeatedCreateCall = yield* invoke("create_threads", createInput);
const repeatedCreated = yield* decodeCreateThreadsResult(
repeatedCreateCall.structuredContent,
).pipe(Effect.orDie);
expect(repeatedCreated.threads.map((thread) => thread.threadId)).toEqual(
created.threads.map((thread) => thread.threadId),
);
}).pipe(Effect.provide(testLayer));
}),
),
);
});
@@ -0,0 +1,40 @@
import { OrchestratorToolkit } from "./tools.ts";
import * as Effect from "effect/Effect";
import { McpInvocationContext } from "../../McpInvocationContext.ts";
import { OrchestratorMcpService } from "../../OrchestratorMcpService.ts";
const handlers = {
orchestrator_capabilities: () =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.capabilities(scope);
}),
delegate_task: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.delegateTask(scope, input);
}),
task_status: ({ taskId }) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.taskStatus(scope, taskId);
}),
task_cancel: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.cancelTask(scope, input);
}),
create_threads: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.createThreads(scope, input);
}),
} satisfies Parameters<typeof OrchestratorToolkit.toLayer>[0];
export const OrchestratorToolkitHandlersLive = OrchestratorToolkit.toLayer(handlers);
@@ -0,0 +1,90 @@
import {
OrchestratorMcpCapabilitiesResult,
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskInput,
OrchestratorMcpDelegateTaskResult,
OrchestratorMcpFailure,
OrchestratorMcpTaskCancelInput,
OrchestratorMcpTaskCancelResult,
OrchestratorMcpTaskStatusInput,
} from "@t3tools/contracts";
import { Tool, Toolkit } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { OrchestratorMcpService } from "../../OrchestratorMcpService.ts";
const dependencies = [McpInvocationContext.McpInvocationContext, OrchestratorMcpService];
export const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
description:
"List the V2 provider instances, models, inherited runtime settings, and app-owned orchestration features available to this T3 thread.",
success: OrchestratorMcpCapabilitiesResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Get orchestration capabilities")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const DelegateTaskTool = Tool.make("delegate_task", {
description:
"Create a T3-owned child agent thread and run it with only the supplied task prompt, without copying parent conversation history. Provider, model, runtime mode, and interaction mode inherit from the parent unless overridden. Prefer mode='async' and poll task_status for long work; mode='wait' blocks until completion or timeout.",
parameters: OrchestratorMcpDelegateTaskInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Delegate a child task")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const TaskStatusTool = Tool.make("task_status", {
description:
"Read the latest durable state and final summary for a T3-owned delegated task created by this parent thread.",
parameters: OrchestratorMcpTaskStatusInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Get delegated task status")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const TaskCancelTool = Tool.make("task_cancel", {
description:
"Request interruption of an active T3-owned delegated task. Completed tasks are returned unchanged.",
parameters: OrchestratorMcpTaskCancelInput,
success: OrchestratorMcpTaskCancelResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Cancel delegated task")
.annotate(Tool.Destructive, true);
export const CreateThreadsTool = Tool.make("create_threads", {
description:
"Create one or more ordinary top-level T3 V2 threads. Each entry may have its own prompt, title, provider instance or driver, model, runtime mode, and interaction mode. Omitted provider/model/settings inherit from the calling thread; entries without prompts create empty threads.",
parameters: OrchestratorMcpCreateThreadsInput,
success: OrchestratorMcpCreateThreadsResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Create T3 threads")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilitiesTool,
DelegateTaskTool,
TaskStatusTool,
TaskCancelTool,
CreateThreadsTool,
);
@@ -1,5 +1,6 @@
import {
ClaudeSettings,
EnvironmentId,
MessageId,
NodeId,
ProjectId,
@@ -16,6 +17,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
import {
@@ -24,10 +26,12 @@ import {
CLAUDE_PROVIDER,
CLAUDE_READ_ONLY_ALLOWED_TOOLS,
ClaudeProviderCapabilitiesV2,
claudeMcpQueryOverrides,
claudeRuntimeQueryPolicyForRuntimePolicy,
loggedClaudeQueryOptions,
makeClaudeAdapterV2,
makeClaudeAgentSdkProtocolLogger,
makeClaudeQueryOptions,
type ClaudeAgentSdkQueryOptions,
type ClaudeAgentSdkQueryOpenInput,
} from "./ClaudeAdapterV2.ts";
@@ -124,6 +128,53 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
});
describe("ClaudeAdapterV2 native protocol logging", () => {
it("injects thread-scoped MCP configuration without logging the credential", () => {
const threadId = ThreadId.make("thread-claude-mcp");
McpProviderSession.setMcpProviderSession({
environmentId: EnvironmentId.make("environment-claude-mcp"),
threadId,
providerSessionId: "mcp-session-claude",
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader: "Bearer secret-claude-token",
});
try {
const overrides = claudeMcpQueryOverrides({
threadId,
allowedTools: ["Read"],
});
assert.deepEqual(overrides, {
allowedTools: ["Read", "mcp__t3-code__*"],
mcpServers: {
"t3-code": {
type: "http",
url: "http://127.0.0.1:43123/mcp",
headers: {
Authorization: "Bearer secret-claude-token",
},
},
},
});
const options = makeClaudeQueryOptions({
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
nativeThreadId: "native-thread-claude-mcp",
resume: false,
cwd: "/workspace",
...overrides,
});
const logged = loggedClaudeQueryOptions(options);
assert.equal(logged.hasMcpServers, true);
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
} finally {
McpProviderSession.clearMcpProviderSession(threadId);
}
});
it.effect("writes Claude Agent SDK protocol frames to the native provider log", () =>
Effect.gen(function* () {
const writes: Array<{
@@ -58,6 +58,7 @@ import {
makeEventNdjsonLogger,
} from "../../provider/Layers/EventNdjsonLogger.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
import {
ProviderAdapterEnsureThreadError,
@@ -140,7 +141,7 @@ export const ClaudeProviderCapabilitiesV2 = {
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: false,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
},
approvals: {
@@ -320,6 +321,7 @@ export interface ClaudeAgentSdkLoggedQueryOptions {
readonly allowDangerouslySkipPermissions?: true;
readonly hasCanUseTool?: true;
readonly hasEnvironment?: true;
readonly hasMcpServers?: true;
}
export type ClaudeAgentSdkProtocolLogEvent =
@@ -411,6 +413,7 @@ export function loggedClaudeQueryOptions(
: {}),
...(options.canUseTool === undefined ? {} : { hasCanUseTool: true }),
...(options.env === undefined ? {} : { hasEnvironment: true }),
...(options.mcpServers === undefined ? {} : { hasMcpServers: true }),
};
}
@@ -607,6 +610,7 @@ export function makeClaudeQueryOptions(input: {
readonly settings?: ClaudeSettings;
readonly sdkSettings?: string | ClaudeSdkSettings;
readonly environment?: NodeJS.ProcessEnv;
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
readonly tools?: ClaudeAgentSdkQueryTools;
readonly allowedTools?: ReadonlyArray<string>;
readonly disallowedTools?: ReadonlyArray<string>;
@@ -637,11 +641,37 @@ export function makeClaudeQueryOptions(input: {
? { pathToClaudeCodeExecutable: input.settings.binaryPath }
: {}),
...(input.environment === undefined ? {} : { env: input.environment }),
...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),
...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
};
return input.cwd === null ? options : { ...options, cwd: input.cwd };
}
export function claudeMcpQueryOverrides(input: {
readonly threadId: ThreadId;
readonly allowedTools?: ReadonlyArray<string>;
}): {
readonly allowedTools?: ReadonlyArray<string>;
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
} {
const session = McpProviderSession.readMcpProviderSession(input.threadId);
if (session === undefined) {
return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
}
return {
allowedTools: Array.from(new Set([...(input.allowedTools ?? []), "mcp__t3-code__*"])),
mcpServers: {
"t3-code": {
type: "http",
url: session.endpoint,
headers: {
Authorization: session.authorizationHeader,
},
},
},
};
}
function providerSession(input: {
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly cwd: string | null;
@@ -2688,6 +2718,12 @@ export function makeClaudeAdapterV2(
nativeThreadId: string,
) {
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
const mcpOverrides = claudeMcpQueryOverrides({
threadId: turnInput.threadId,
...(queryPolicy.allowedTools === undefined
? {}
: { allowedTools: queryPolicy.allowedTools }),
});
const queryPolicyKey = claudeRuntimeQueryPolicyKey(queryPolicy);
const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread);
const existing = yield* Ref.get(queryContext);
@@ -2729,9 +2765,7 @@ export function makeClaudeAdapterV2(
settings: adapterOptions.settings,
environment: adapterOptions.environment,
tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS,
...(queryPolicy.allowedTools === undefined
? {}
: { allowedTools: queryPolicy.allowedTools }),
...mcpOverrides,
permissionMode: queryPolicy.permissionMode,
...(queryPolicy.allowDangerouslySkipPermissions === undefined
? {}
@@ -1,8 +1,10 @@
import {
CheckpointId,
EnvironmentId,
NodeId,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
@@ -16,14 +18,97 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { ChildProcess } from "effect/unstable/process";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
import {
buildCodexTurnStartParams,
codexAppServerMcpLaunchConfig,
makeCodexAppServerProtocolLogger,
makeCodexAppServerSpawnCommand,
projectCodexDynamicToolItem,
resolveCodexRollbackTurnCount,
} from "./CodexAdapterV2.ts";
describe("CodexAdapterV2 runtime policy", () => {
it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
Effect.gen(function* () {
const build = (runtimeMode: "approval-required" | "auto-accept-edits" | "full-access") =>
buildCodexTurnStartParams({
nativeThreadId: `native-${runtimeMode}`,
codexInput: [{ type: "text", text: "test" }],
runtimePolicy: {
runtimeMode,
interactionMode: "default",
cwd: null,
},
model: "gpt-5.4",
});
const approvalRequired = yield* build("approval-required");
const autoAcceptEdits = yield* build("auto-accept-edits");
const fullAccess = yield* build("full-access");
assert.equal(approvalRequired.approvalPolicy, "untrusted");
assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly");
assert.equal(autoAcceptEdits.approvalPolicy, "on-request");
assert.equal(autoAcceptEdits.sandboxPolicy?.type, "workspaceWrite");
assert.equal(fullAccess.approvalPolicy, "never");
assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess");
}),
);
it.effect("preserves explicit Codex turn policy overrides", () =>
Effect.gen(function* () {
const params = yield* buildCodexTurnStartParams({
nativeThreadId: "native-override",
codexInput: [{ type: "text", text: "test" }],
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: null,
approvalPolicy: "on-request",
sandboxPolicy: {
type: "readOnly",
},
},
model: "gpt-5.4",
});
assert.equal(params.approvalPolicy, "on-request");
assert.equal(params.sandboxPolicy?.type, "readOnly");
}),
);
});
describe("CodexAdapterV2 process spawning", () => {
it("injects the thread-scoped MCP endpoint and bearer token", () => {
const threadId = ThreadId.make("thread-codex-mcp");
McpProviderSession.setMcpProviderSession({
environmentId: EnvironmentId.make("environment-codex-mcp"),
threadId,
providerSessionId: "mcp-session-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader: "Bearer secret-codex-token",
});
try {
assert.deepEqual(codexAppServerMcpLaunchConfig(threadId), {
args: [
"-c",
"mcp_servers.t3-code.url=http://127.0.0.1:43123/mcp",
"-c",
'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"',
],
environment: {
T3_MCP_BEARER_TOKEN: "secret-codex-token",
},
});
} finally {
McpProviderSession.clearMcpProviderSession(threadId);
}
});
it.effect("resolves Windows command shims through the shared spawn policy", () =>
Effect.gen(function* () {
const command = yield* makeCodexAppServerSpawnCommand({
@@ -79,6 +164,58 @@ describe("CodexAdapterV2 process spawning", () => {
);
});
describe("CodexAdapterV2 dynamic tool projection", () => {
it("preserves MCP arguments and prefers structured output", () => {
const projection = projectCodexDynamicToolItem({
type: "mcpToolCall",
id: "call-create-threads",
server: "t3-code",
tool: "create_threads",
status: "completed",
arguments: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
result: {
content: [{ type: "text", text: '{"threads":[{"threadId":"thread:mcp:fixture:0"}]}' }],
structuredContent: {
threads: [{ threadId: "thread:mcp:fixture:0" }],
},
},
});
assert.deepEqual(projection, {
toolName: "t3-code.create_threads",
input: {
threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
},
output: {
threads: [{ threadId: "thread:mcp:fixture:0" }],
},
status: "completed",
});
});
it("preserves namespaced dynamic tool output", () => {
const projection = projectCodexDynamicToolItem({
type: "dynamicToolCall",
id: "call-dynamic",
namespace: "workspace",
tool: "inspect",
status: "failed",
arguments: { path: "package.json" },
contentItems: [{ type: "inputText", text: "inspection failed" }],
success: false,
});
assert.deepEqual(projection, {
toolName: "workspace.inspect",
input: { path: "package.json" },
output: [{ type: "inputText", text: "inspection failed" }],
status: "failed",
});
});
});
describe("CodexAdapterV2 native protocol logging", () => {
it.effect("writes app-server protocol frames to the native provider log", () =>
Effect.gen(function* () {
@@ -18,6 +18,8 @@ import type {
ProviderApprovalDecision,
ProviderRequestKind,
ProviderTurnId,
ProviderInstanceId,
RuntimeMode,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
@@ -44,7 +46,12 @@ import {
type EventNdjsonLogger,
makeEventNdjsonLogger,
} from "../../provider/Layers/EventNdjsonLogger.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
} from "../ProviderAdapterDriver.ts";
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
import {
ProviderAdapterEnsureThreadError,
@@ -262,6 +269,57 @@ function codexItemStatus(status: "inProgress" | "completed" | "failed" | "declin
}
}
export interface CodexDynamicToolProjection {
readonly toolName: string;
readonly input: unknown;
readonly output?: unknown;
readonly status: OrchestrationV2TurnItem["status"];
}
function codexMcpToolOutput(
item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,
): unknown | undefined {
const resultOutput =
item.result === null || item.result === undefined
? undefined
: item.result.structuredContent !== null && item.result.structuredContent !== undefined
? item.result.structuredContent
: item.result.content;
if (item.error === null || item.error === undefined) {
return resultOutput;
}
return resultOutput === undefined
? { error: item.error.message }
: { error: item.error.message, result: resultOutput };
}
function codexDynamicToolOutput(
item: Extract<CodexDynamicToolItem, { readonly type: "dynamicToolCall" }>,
): unknown | undefined {
if (item.contentItems !== null && item.contentItems !== undefined) {
return item.contentItems;
}
return item.success === false ? { success: false } : undefined;
}
export function projectCodexDynamicToolItem(
item: CodexDynamicToolItem,
): CodexDynamicToolProjection {
const output =
item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item);
const toolName =
item.type === "mcpToolCall"
? `${item.server}.${item.tool}`
: [trimText(item.namespace), item.tool].filter(Boolean).join(".");
const projection: CodexDynamicToolProjection = {
toolName,
input: item.arguments,
status: codexItemStatus(item.status).turnItem,
};
return output === undefined ? projection : { ...projection, output };
}
function codexNativeItemRef(nativeItemId: string) {
return {
provider: CODEX_PROVIDER,
@@ -402,20 +460,50 @@ const CodexTurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.
type CodexTurnStartParamsWithCollaborationMode =
typeof CodexTurnStartParamsWithCollaborationMode.Type;
function buildTurnStartParams(input: {
function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): {
readonly approvalPolicy: CodexSchema.V2TurnStartParams__AskForApproval;
readonly sandboxPolicy: CodexSchema.V2TurnStartParams__SandboxPolicy;
} {
switch (runtimeMode) {
case "approval-required":
return {
approvalPolicy: "untrusted",
sandboxPolicy: {
type: "readOnly",
},
};
case "auto-accept-edits":
return {
approvalPolicy: "on-request",
sandboxPolicy: {
type: "workspaceWrite",
},
};
case "full-access":
return {
approvalPolicy: "never",
sandboxPolicy: {
type: "dangerFullAccess",
},
};
}
}
export function buildCodexTurnStartParams(input: {
readonly nativeThreadId: string;
readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
readonly model: string;
}) {
return Effect.gen(function* () {
const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
const approvalPolicy =
input.runtimePolicy.approvalPolicy === undefined
? undefined
? runtimeModeDefaults.approvalPolicy
: yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);
const sandboxPolicy =
input.runtimePolicy.sandboxPolicy === undefined
? undefined
? runtimeModeDefaults.sandboxPolicy
: yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);
const effort =
input.runtimePolicy.reasoningEffort === undefined
@@ -652,6 +740,12 @@ type CodexWebSearchItem = {
| null;
};
export type CodexDynamicToolItem = Extract<
| CodexSchema.V2ItemStartedNotification__ThreadItem
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ readonly type: "mcpToolCall" | "dynamicToolCall" }
>;
export interface CodexAppServerClientFactoryShape {
readonly open: (input: {
readonly threadId: ThreadId;
@@ -669,6 +763,26 @@ export class CodexAppServerClientFactory extends Context.Service<
CodexAppServerClientFactoryShape
>()("t3/orchestration-v2/Adapters/CodexAdapterV2/CodexAppServerClientFactory") {}
export function codexAppServerMcpLaunchConfig(threadId: ThreadId): {
readonly args: ReadonlyArray<string>;
readonly environment: NodeJS.ProcessEnv;
} | null {
const session = McpProviderSession.readMcpProviderSession(threadId);
return session === undefined
? null
: {
args: [
"-c",
`mcp_servers.t3-code.url=${session.endpoint}`,
"-c",
'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"',
],
environment: {
T3_MCP_BEARER_TOKEN: session.authorizationHeader.replace(/^Bearer\s+/, ""),
},
};
}
export const makeCodexAppServerSpawnCommand = Effect.fn(
"CodexAdapterV2.makeCodexAppServerSpawnCommand",
)(function* (input: {
@@ -706,13 +820,22 @@ export const makeCodexAppServerClientFactoryCommandLayer = (
open: (input) =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const mcp = codexAppServerMcpLaunchConfig(input.threadId);
const command = yield* makeCodexAppServerSpawnCommand({
command: options.command,
args: options.args ?? [],
args: [...(options.args ?? []), ...(mcp?.args ?? [])],
...((input.runtimePolicy.cwd ?? options.cwd) === undefined
? {}
: { cwd: input.runtimePolicy.cwd ?? options.cwd }),
...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),
...(options.env === undefined && mcp === null
? {}
: {
env: {
...options.env,
...mcp?.environment,
},
extendEnv: true,
}),
});
const handle = yield* spawner.spawn(command).pipe(
Effect.provideService(Scope.Scope, scope),
@@ -777,13 +900,15 @@ export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer<
open: (input) =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const mcp = codexAppServerMcpLaunchConfig(input.threadId);
const environment = {
...input.environment,
...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),
...mcp?.environment,
};
const command = yield* makeCodexAppServerSpawnCommand({
command: input.settings.binaryPath || "codex",
args: ["app-server"],
args: ["app-server", ...(mcp?.args ?? [])],
...(input.runtimePolicy.cwd === null ? {} : { cwd: input.runtimePolicy.cwd }),
env: environment,
});
@@ -2448,6 +2573,64 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return { node, turnItem };
});
const buildDynamicToolArtifacts = (
context: ActiveCodexTurnContext,
item: CodexDynamicToolItem,
) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
const status = codexItemStatus(item.status);
const completedAt = status.completed ? updatedAt : null;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const ordinal = yield* resolveItemOrdinal(context, item.id);
const projection = projectCodexDynamicToolItem(item);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
status: status.node,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
parentItemId: null,
ordinal,
status: projection.status,
title: null,
startedAt: context.startedAt,
completedAt,
updatedAt,
type: "dynamic_tool",
toolName: projection.toolName,
input: projection.input,
...(projection.output === undefined ? {} : { output: projection.output }),
};
return { node, turnItem };
});
const buildProposedPlanArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
@@ -2895,6 +3078,21 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "mcpToolCall" || payload.item.type === "dynamicToolCall") {
const artifacts = yield* buildDynamicToolArtifacts(context, payload.item);
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type !== "webSearch") {
return;
}
@@ -2945,6 +3143,21 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "mcpToolCall" || payload.item.type === "dynamicToolCall") {
const artifacts = yield* buildDynamicToolArtifacts(context, payload.item);
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type === "fileChange") {
const artifacts = yield* buildFileChangeArtifacts(context, payload.item);
if (artifacts === null) {
@@ -3602,86 +3815,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(turnInput.providerThread);
if (payload.item.type === "fileChange") {
const artifacts = yield* buildFileChangeArtifacts(context, payload.item);
if (artifacts === null) {
return;
}
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type === "webSearch") {
const artifacts = yield* buildWebSearchArtifacts({
context,
item: payload.item,
completed: true,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type === "plan") {
const deltas = yield* Ref.get(planDeltas);
const markdown =
payload.item.text.length > 0
? payload.item.text
: (deltas.get(payload.item.id) ?? "");
const artifacts = yield* buildProposedPlanArtifacts({
context,
nativeItemId: payload.item.id,
status: "completed",
markdown,
completed: true,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "plan.updated",
provider: CODEX_PROVIDER,
plan: artifacts.plan,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type !== "agentMessage") {
return;
}
const deltas = yield* Ref.get(agentMessageDeltas);
const text =
payload.item.text.length > 0
? payload.item.text
: (deltas.get(payload.item.id) ?? "");
const artifacts = yield* buildAgentMessageArtifacts(context, {
...payload.item,
text,
const codexInput = yield* toCodexInput(turnInput);
const turnStartParams = yield* buildCodexTurnStartParams({
nativeThreadId: threadId,
codexInput,
runtimePolicy: turnInput.runtimePolicy,
model: turnInput.modelSelection.model,
});
yield* emitProviderEvent({
type: "node.updated",
@@ -126,6 +126,10 @@ export interface IdAllocatorV2AllocateShape {
}
export interface IdAllocatorV2DeriveShape {
readonly delegatedTaskNode: (input: { readonly commandId: CommandId }) => NodeId;
readonly delegatedTaskThread: (input: { readonly commandId: CommandId }) => ThreadId;
readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId;
readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId;
readonly threadFromProviderThread: (input: {
readonly provider: ProviderKind;
readonly nativeThreadId: string;
@@ -338,6 +342,13 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
})(input),
},
derive: {
delegatedTaskNode: (input) => NodeId.make(joinId("node", "delegated-task", input.commandId)),
delegatedTaskThread: (input) =>
ThreadId.make(joinId("thread", "delegated-task", input.commandId)),
delegatedTaskMessage: (input) =>
MessageId.make(joinId("message", "delegated-task", input.commandId)),
delegatedTaskTurnItem: (input) =>
TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)),
threadFromProviderThread: (input) =>
ThreadId.make(
joinId("thread", "provider", input.provider, "native-thread", input.nativeThreadId),
@@ -18,6 +18,7 @@ import {
type OrchestrationV2RunAttempt,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2StoredEvent,
type OrchestrationV2Subagent,
type OrchestrationV2ThreadProjection,
type OrchestrationV2TurnItem,
ThreadId,
@@ -47,6 +48,11 @@ import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
import {
makeSubagentChildThread,
subagentResultForRun,
subagentThreadTitle,
} from "./SubagentProjection.ts";
export class OrchestratorDispatchError extends Schema.TaggedErrorClass<OrchestratorDispatchError>()(
"OrchestratorDispatchError",
@@ -158,6 +164,8 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "checkpoint.rollback":
case "provider.switch":
return command.threadId;
case "delegated_task.request":
return command.parentThreadId;
case "thread.fork":
case "thread.merge_back":
return command.targetThreadId;
@@ -190,6 +198,25 @@ function isBlockingRun(run: OrchestrationV2Run): boolean {
return run.status === "starting" || run.status === "running" || run.status === "waiting";
}
function delegatedTaskTerminalStatus(
status: OrchestrationV2Run["status"],
): OrchestrationV2Subagent["status"] | null {
switch (status) {
case "completed":
case "failed":
case "cancelled":
case "interrupted":
return status;
case "rolled_back":
return "cancelled";
case "queued":
case "starting":
case "running":
case "waiting":
return null;
}
}
function nextQueuedRun(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2Run | undefined {
@@ -2604,6 +2631,246 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
});
const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")(
function* (
command: Extract<OrchestrationV2Command, { readonly type: "delegated_task.request" }>,
events: Ref.Ref<Array<OrchestrationV2StoredEvent>>,
) {
const parentProjection = yield* projectionStore
.getThreadProjection(command.parentThreadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestratorProjectionError({
threadId: command.parentThreadId,
cause,
}),
),
);
const parentRun = parentProjection.runs.find(
(candidate) => candidate.id === command.parentRunId,
);
if (parentRun === undefined || !isBlockingRun(parentRun)) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Parent run ${command.parentRunId} is not active.`,
});
}
const parentNode = parentProjection.nodes.find(
(candidate) => candidate.id === command.parentNodeId,
);
if (
parentNode === undefined ||
parentNode.runId !== parentRun.id ||
parentRun.rootNodeId === null
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Parent node ${command.parentNodeId} is not part of active run ${parentRun.id}.`,
});
}
const now = command.createdAt ?? (yield* DateTime.now);
const taskNodeId = idAllocator.derive.delegatedTaskNode({
commandId: command.commandId,
});
const childThreadId = idAllocator.derive.delegatedTaskThread({
commandId: command.commandId,
});
const childMessageId = idAllocator.derive.delegatedTaskMessage({
commandId: command.commandId,
});
const taskTurnItemId = idAllocator.derive.delegatedTaskTurnItem({
commandId: command.commandId,
});
const taskTitle = subagentThreadTitle({
parentTitle: parentProjection.thread.title,
prompt: command.task,
...(command.title === undefined ? {} : { title: command.title }),
ordinal: parentProjection.subagents.length + 1,
});
const childThread: OrchestrationV2AppThread = {
...makeSubagentChildThread({
parentThread: parentProjection.thread,
childThreadId,
parentNodeId: taskNodeId,
activeProviderThreadId: null,
providerInstanceId: command.modelSelection.instanceId,
modelSelection: command.modelSelection,
title: taskTitle,
now,
}),
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
};
const task: OrchestrationV2Subagent = {
id: taskNodeId,
threadId: command.parentThreadId,
runId: parentRun.id,
parentNodeId: command.parentNodeId,
origin: "app_owned",
createdBy: "agent",
provider: command.modelSelection.instanceId,
providerThreadId: null,
childThreadId,
nativeTaskRef: null,
prompt: command.task,
title: command.title ?? null,
model: command.modelSelection.model,
status: "running",
result: null,
startedAt: now,
completedAt: null,
updatedAt: now,
};
const taskNode: OrchestrationV2ExecutionNode = {
id: taskNodeId,
threadId: command.parentThreadId,
runId: parentRun.id,
parentNodeId: command.parentNodeId,
rootNodeId: parentRun.rootNodeId,
kind: "subagent",
status: "running",
countsForRun: false,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: now,
completedAt: null,
};
const parentProviderTurn = providerTurnForRun(parentProjection, parentRun);
const taskTurnItem: OrchestrationV2TurnItem = {
id: taskTurnItemId,
threadId: command.parentThreadId,
runId: parentRun.id,
nodeId: taskNodeId,
providerThreadId: parentRun.providerThreadId,
providerTurnId: parentProviderTurn?.id ?? null,
nativeItemRef: null,
parentItemId: null,
ordinal: nextTurnItemOrdinal(parentProjection),
status: "running",
title: command.title ?? taskTitle,
startedAt: now,
completedAt: null,
updatedAt: now,
type: "subagent",
subagentId: taskNodeId,
origin: "app_owned",
provider: command.modelSelection.instanceId,
childThreadId,
prompt: command.task,
result: null,
};
const emitEvent = emit(events, command);
yield* emitEvent({
type: "thread.created",
threadId: childThreadId,
provider: command.modelSelection.instanceId,
occurredAt: now,
payload: childThread,
});
yield* emitEvent({
type: "node.updated",
threadId: command.parentThreadId,
runId: parentRun.id,
nodeId: taskNodeId,
provider: command.modelSelection.instanceId,
occurredAt: now,
payload: taskNode,
});
yield* emitEvent({
type: "subagent.updated",
threadId: command.parentThreadId,
runId: parentRun.id,
nodeId: taskNodeId,
provider: command.modelSelection.instanceId,
occurredAt: now,
payload: task,
});
yield* emitEvent({
type: "turn-item.updated",
threadId: command.parentThreadId,
runId: parentRun.id,
nodeId: taskNodeId,
provider: command.modelSelection.instanceId,
occurredAt: now,
payload: taskTurnItem,
});
const childMessageCommand = {
type: "message.dispatch",
commandId: command.commandId,
threadId: childThreadId,
messageId: childMessageId,
text: command.task,
attachments: [],
modelSelection: command.modelSelection,
dispatchMode: { type: "start_immediately" },
} satisfies Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>;
yield* dispatchMessage(childMessageCommand, events);
const childProjection = yield* projectionStore.getThreadProjection(childThreadId).pipe(
Effect.mapError(
(cause) =>
new OrchestratorProjectionError({
threadId: childThreadId,
cause,
}),
),
);
const childRun = childProjection.runs[0];
if (childRun === undefined) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Delegated child thread ${childThreadId} did not create a run.`,
});
}
const spawnTransferId = yield* mapDispatchError(command)(
idAllocator.allocate.contextTransfer({
sourceThreadId: command.parentThreadId,
targetThreadId: childThreadId,
type: "subagent_spawn",
}),
);
const spawnTransfer: OrchestrationV2ContextTransfer = {
id: spawnTransferId,
type: "subagent_spawn",
sourceThreadId: command.parentThreadId,
targetThreadId: childThreadId,
sourcePoint: {
...contextSourcePointForRun(parentProjection, parentRun),
turnItemId: taskTurnItemId,
},
basePoint: null,
sourceProvider: parentRun.provider,
targetProvider: command.modelSelection.instanceId,
targetRunId: childRun.id,
status: "consumed",
resolution: null,
createdBy: "agent",
error: null,
createdAt: now,
updatedAt: now,
consumedAt: now,
};
yield* emitEvent({
type: "context-transfer.created",
threadId: childThreadId,
runId: childRun.id,
provider: command.modelSelection.instanceId,
occurredAt: now,
payload: spawnTransfer,
});
},
);
const dispatchRuntimeRequestRespond = (
command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
events: Ref.Ref<Array<OrchestrationV2StoredEvent>>,
@@ -3048,7 +3315,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
completedAt: now,
updatedAt: now,
type: "run_interrupt_request",
message: "Interrupt requested",
message: command.reason ?? "Interrupt requested",
};
yield* emitEvent({
type: "turn-item.updated",
@@ -3334,6 +3601,208 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
});
const finalizeAppOwnedSubagent = (childThreadId: ThreadId) =>
Effect.gen(function* () {
const childProjection = yield* projectionStore.getThreadProjection(childThreadId);
const forkedFrom = childProjection.thread.forkedFrom;
if (
childProjection.thread.lineage.relationshipToParent !== "subagent" ||
childProjection.thread.lineage.parentThreadId === null ||
forkedFrom?.type !== "node"
) {
return;
}
const childRun = childProjection.runs[0];
if (childRun === undefined) {
return;
}
const terminalStatus = delegatedTaskTerminalStatus(childRun.status);
if (terminalStatus === null) {
return;
}
const parentThreadId = childProjection.thread.lineage.parentThreadId;
const parentProjection = yield* projectionStore.getThreadProjection(parentThreadId);
const task = parentProjection.subagents.find(
(candidate) =>
candidate.id === forkedFrom.nodeId &&
candidate.origin === "app_owned" &&
candidate.childThreadId === childThreadId,
);
if (task === undefined) {
return;
}
const existingResultTransfer = parentProjection.contextTransfers.find(
(transfer) =>
transfer.type === "subagent_result" &&
transfer.sourceThreadId === childThreadId &&
transfer.targetThreadId === parentThreadId,
);
if (existingResultTransfer !== undefined) {
return;
}
const now = yield* DateTime.now;
const result = subagentResultForRun(childProjection, childRun);
const parentRun =
task.runId === null
? undefined
: parentProjection.runs.find((candidate) => candidate.id === task.runId);
const parentNode = parentProjection.nodes.find((candidate) => candidate.id === task.id);
const parentTurnItem = parentProjection.turnItems.find(
(candidate) => candidate.type === "subagent" && candidate.subagentId === task.id,
);
const updatedTask: OrchestrationV2Subagent = {
...task,
providerThreadId: childRun.providerThreadId,
status: terminalStatus,
result: result.text,
completedAt: now,
updatedAt: now,
};
const resultTransferId = yield* idAllocator.allocate.contextTransfer({
sourceThreadId: childThreadId,
targetThreadId: parentThreadId,
type: "subagent_result",
});
const childProviderThread =
childRun.providerThreadId === null
? undefined
: childProjection.providerThreads.find(
(candidate) => candidate.id === childRun.providerThreadId,
);
const parentProviderThread =
parentRun?.providerThreadId === null || parentRun?.providerThreadId === undefined
? undefined
: parentProjection.providerThreads.find(
(candidate) => candidate.id === parentRun.providerThreadId,
);
const resultHandoff: OrchestrationV2ContextHandoff | null =
parentRun === undefined ||
childProviderThread === undefined ||
parentProviderThread === undefined
? null
: {
id: yield* idAllocator.allocate.contextHandoff({
threadId: parentThreadId,
fromProvider: childRun.provider,
toProvider: parentRun.provider,
}),
transferId: resultTransferId,
threadId: parentThreadId,
targetRunId: parentRun.id,
fromProviderThreadIds: [childProviderThread.id],
toProviderThreadId: parentProviderThread.id,
coveredRunOrdinals: {
from: childRun.ordinal,
to: childRun.ordinal,
},
strategy: "manual_context",
status: "ready",
summaryMessageId: result.messageId,
summaryText: result.text,
createdByProvider: childRun.provider,
createdAt: now,
updatedAt: now,
};
const resultTransfer: OrchestrationV2ContextTransfer = {
id: resultTransferId,
type: "subagent_result",
sourceThreadId: childThreadId,
targetThreadId: parentThreadId,
sourcePoint: {
...contextSourcePointForRun(childProjection, childRun),
...(result.turnItemId === null ? {} : { turnItemId: result.turnItemId }),
},
basePoint: null,
sourceProvider: childRun.provider,
targetProvider: parentRun?.provider ?? parentProjection.thread.defaultProvider,
targetRunId: parentRun?.id ?? null,
status: "consumed",
resolution:
resultHandoff === null
? null
: {
strategy: "portable_context",
contextHandoffId: resultHandoff.id,
},
createdBy: "system",
error: null,
createdAt: now,
updatedAt: now,
consumedAt: now,
};
yield* writeSystemEvents([
{
type: "subagent.updated",
threadId: parentThreadId,
...(task.runId === null ? {} : { runId: task.runId }),
nodeId: task.id,
provider: task.provider,
occurredAt: now,
payload: updatedTask,
},
...(parentNode === undefined
? []
: [
{
type: "node.updated" as const,
threadId: parentThreadId,
...(parentNode.runId === null ? {} : { runId: parentNode.runId }),
nodeId: parentNode.id,
provider: task.provider,
occurredAt: now,
payload: {
...parentNode,
status: terminalStatus,
providerThreadId: childRun.providerThreadId,
completedAt: now,
},
},
]),
...(parentTurnItem === undefined
? []
: [
{
type: "turn-item.updated" as const,
threadId: parentThreadId,
...(parentTurnItem.runId === null ? {} : { runId: parentTurnItem.runId }),
...(parentTurnItem.nodeId === null ? {} : { nodeId: parentTurnItem.nodeId }),
provider: task.provider,
occurredAt: now,
payload: {
...parentTurnItem,
status: terminalStatus,
result: result.text,
completedAt: now,
updatedAt: now,
},
},
]),
...(resultHandoff === null
? []
: [
{
type: "context-handoff.updated" as const,
threadId: parentThreadId,
...(parentRun === undefined ? {} : { runId: parentRun.id }),
provider: childRun.provider,
occurredAt: now,
payload: resultHandoff,
},
]),
{
type: "context-transfer.created",
threadId: parentThreadId,
...(parentRun === undefined ? {} : { runId: parentRun.id }),
provider: childRun.provider,
occurredAt: now,
payload: resultTransfer,
},
]);
});
const dispatchUnsupported = (command: OrchestrationV2Command) =>
Effect.fail(
new OrchestratorDispatchError({
@@ -3380,6 +3849,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "thread.merge_back":
yield* dispatchThreadMergeBack(command, events);
break;
case "delegated_task.request":
yield* dispatchDelegatedTaskRequest(command, events);
break;
default:
return yield* dispatchUnsupported(command);
}
@@ -3486,7 +3958,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
Stream.runForEach((stored) =>
dispatchSemaphore
.withPermit(startNextQueuedRun(stored.event.threadId))
.withPermit(
finalizeAppOwnedSubagent(stored.event.threadId).pipe(
Effect.andThen(startNextQueuedRun(stored.event.threadId)),
),
)
.pipe(Effect.catchCause(() => Effect.void)),
),
Effect.forkDetach,
@@ -1,5 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
EnvironmentId,
type ModelSelection,
type OrchestrationV2AppThread,
type OrchestrationV2DomainEvent,
@@ -7,7 +9,7 @@ import {
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type ProviderSessionId,
type ThreadId,
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -17,7 +19,11 @@ import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { HttpServer } from "effect/unstable/http";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as McpProviderSession from "../mcp/McpProviderSession.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
@@ -181,6 +187,9 @@ function makeProviderAdapter(
state: Ref.Ref<TestProviderRuntimeState>,
options: {
readonly failEventStream?: boolean;
readonly mcpConfigs?: Ref.Ref<
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
>;
} = {},
): ProviderAdapterV2Shape {
return {
@@ -188,6 +197,12 @@ function makeProviderAdapter(
getCapabilities: () => Effect.succeed(CodexCapabilities),
openSession: (input) =>
Effect.gen(function* () {
if (options.mcpConfigs !== undefined) {
yield* Ref.update(options.mcpConfigs, (configs) => [
...configs,
McpProviderSession.readMcpProviderSession(input.threadId),
]);
}
const now = yield* DateTime.now;
const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
const session = makeProviderSession({
@@ -242,9 +257,15 @@ function makeTestLayer(input: {
readonly state: Ref.Ref<TestProviderRuntimeState>;
readonly idleTimeoutMs: number;
readonly failEventStream?: boolean;
readonly mcpConfigs?: Ref.Ref<
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
>;
}) {
const registryLayer = makeProviderAdapterRegistryLayer(
makeProviderAdapter(input.state, { failEventStream: input.failEventStream ?? false }),
makeProviderAdapter(input.state, {
failEventStream: input.failEventStream ?? false,
...(input.mcpConfigs === undefined ? {} : { mcpConfigs: input.mcpConfigs }),
}),
);
return Layer.mergeAll(
TestStoresLayer,
@@ -258,6 +279,22 @@ function makeTestLayer(input: {
);
}
const fakeHttpServer = HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const fakeEnvironment = ServerEnvironment.of({
getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-provider-session-manager")),
getDescriptor: Effect.die("unused"),
});
const TestMcpRegistryLayer = McpSessionRegistry.layer.pipe(
Layer.provide(Layer.succeed(HttpServer.HttpServer, fakeHttpServer)),
Layer.provide(Layer.succeed(ServerEnvironment, fakeEnvironment)),
Layer.provide(NodeServices.layer),
);
function makePendingRuntimeRequestEvents(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly threadId: ThreadId;
@@ -366,6 +403,64 @@ function makePendingRuntimeRequestEvents(input: {
});
}
it.effect(
"ProviderSessionManagerV2 issues MCP credentials before opening and revokes them on close",
() =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
const mcpConfigs = yield* Ref.make<
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
>([]);
const effect = Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const manager = yield* ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-mcp");
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
threadId,
});
yield* eventSink.write({
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
});
yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
const captured = (yield* Ref.get(mcpConfigs))[0];
assert.isDefined(captured);
assert.equal(captured?.threadId, threadId);
assert.equal(captured?.providerInstanceId, modelSelection.instanceId);
assert.equal(captured?.endpoint, "http://127.0.0.1:43123/mcp");
const token = captured?.authorizationHeader.replace(/^Bearer\s+/, "");
assert.isDefined(token);
const resolved = yield* registry.resolve(token!);
assert.equal(resolved?.threadId, threadId);
assert.deepEqual(resolved?.capabilities, new Set(["preview", "orchestration"]));
yield* manager.close(providerSessionId);
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* registry.resolve(token!));
});
yield* effect.pipe(
Effect.provide(
makeTestLayer({
state,
idleTimeoutMs: 1_000,
mcpConfigs,
}).pipe(Layer.provideMerge(TestMcpRegistryLayer)),
),
);
}),
);
it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all sessions", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -22,6 +22,8 @@ import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as McpProviderSession from "../mcp/McpProviderSession.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { IdAllocatorV2 } from "./IdAllocator.ts";
import {
@@ -202,6 +204,21 @@ export const layerWithOptions = (
const layerScope = yield* Effect.scope;
const sessions = yield* Ref.make(new Map<string, LiveSessionEntry>());
const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
McpSessionRegistry.issueActiveMcpCredential({
threadId,
providerInstanceId,
}).pipe(
Effect.tap((credential) =>
credential === undefined
? Effect.void
: Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)),
),
);
const clearMcpSession = (threadId: ThreadId) =>
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
);
const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore);
@@ -373,6 +390,7 @@ export const layerWithOptions = (
entry: entry.value,
reason: input.reason,
});
yield* Effect.forEach(entry.value.attachedThreadIds, clearMcpSession, { discard: true });
if (Exit.isFailure(closeExit)) {
return yield* Effect.failCause(closeExit.cause);
}
@@ -656,6 +674,7 @@ export const layerWithOptions = (
}),
),
);
yield* prepareMcpSession(input.threadId, input.modelSelection.instanceId);
const sessionScope = yield* Scope.make();
const runtime = yield* adapter
.openSession({
@@ -669,7 +688,12 @@ export const layerWithOptions = (
})
.pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.tapError(() => Scope.close(sessionScope, Exit.void).pipe(Effect.ignore)),
Effect.tapError(() =>
Scope.close(sessionScope, Exit.void).pipe(
Effect.ignore,
Effect.andThen(clearMcpSession(input.threadId)),
),
),
Effect.mapError(
(cause) =>
new ProviderSessionOpenError({
@@ -5,6 +5,8 @@ import type {
OrchestrationV2AppThread,
OrchestrationV2ConversationMessage,
OrchestrationV2ProviderRef,
OrchestrationV2Run,
OrchestrationV2ThreadProjection,
OrchestrationV2TurnItem,
ProviderInstanceId,
ProviderThreadId,
@@ -12,7 +14,7 @@ import type {
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import type * as DateTime from "effect/DateTime";
import * as DateTime from "effect/DateTime";
function trimmed(value: string | null | undefined): string | undefined {
const result = value?.trim();
@@ -127,3 +129,47 @@ export function makeSubagentConversationArtifacts(input: {
};
return { message, turnItem };
}
export function subagentResultForRun(
projection: OrchestrationV2ThreadProjection,
run: OrchestrationV2Run,
): {
readonly text: string;
readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
} {
const message =
projection.messages
.filter(
(candidate) =>
candidate.runId === run.id &&
candidate.role === "assistant" &&
candidate.text.trim().length > 0,
)
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
const turnItem =
projection.turnItems
.filter(
(
candidate,
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "assistant_message" }> =>
candidate.runId === run.id &&
candidate.type === "assistant_message" &&
candidate.text.trim().length > 0,
)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const text =
message?.text ??
turnItem?.text ??
(run.status === "completed"
? "Child task completed without an assistant result."
: `Child task ended with status ${run.status}.`);
return {
text,
messageId: message?.id ?? turnItem?.messageId ?? null,
turnItemId: turnItem?.id ?? null,
};
}
@@ -0,0 +1,21 @@
import type { ProviderDriverKind } from "@t3tools/contracts";
import {
ClaudeAdapterV2Driver,
type ClaudeAdapterV2DriverEnv,
} from "./Adapters/ClaudeAdapterV2.ts";
import { CodexAdapterV2Driver, type CodexAdapterV2DriverEnv } from "./Adapters/CodexAdapterV2.ts";
import type { AnyProviderAdapterDriver } from "./ProviderAdapterDriver.ts";
export type BuiltInProviderAdapterDriversV2Env = ClaudeAdapterV2DriverEnv | CodexAdapterV2DriverEnv;
export const BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2: ReadonlyArray<
AnyProviderAdapterDriver<BuiltInProviderAdapterDriversV2Env>
> = [CodexAdapterV2Driver, ClaudeAdapterV2Driver];
export const BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2: ReadonlySet<ProviderDriverKind> = new Set(
BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2.map((driver) => driver.driverKind),
);
export const isBuiltInProviderAdapterDriverV2 = (driver: ProviderDriverKind): boolean =>
BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2.has(driver);
@@ -100,6 +100,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "checkpoint.rollback":
case "provider.switch":
return [command.threadId];
case "delegated_task.request":
return [command.parentThreadId];
case "thread.fork":
case "thread.merge_back":
return [command.sourceThreadId, command.targetThreadId];
+3 -1
View File
@@ -1508,7 +1508,9 @@ const makeWsRpcLayer = (
"orchestration_v2.thread_id":
command.type === "thread.fork" || command.type === "thread.merge_back"
? command.targetThreadId
: command.threadId,
: command.type === "delegated_task.request"
? command.parentThreadId
: command.threadId,
...(command.type === "thread.fork" || command.type === "thread.merge_back"
? { "orchestration_v2.source_thread_id": command.sourceThreadId }
: {}),
+221 -604
View File
@@ -2,293 +2,116 @@
## Purpose
T3 should ship an app-owned MCP server that lets provider agents ask the V2
orchestrator for orchestration work. The first tool family is delegated work:
a parent provider turn can request another provider/model/agent to run a task
as a child execution node, then receive a durable result back.
T3 exposes V2 orchestration through its app-owned MCP endpoint. A provider
agent can use this endpoint to:
This is not a subagent-only design. The MCP server is the provider-neutral
bridge for future model-controlled orchestration actions. Subagents are just
the first action because MCP is the most common extension point across the
current provider harnesses.
- create an app-owned sub-agent on any supported provider instance;
- wait for or poll the sub-agent's durable result;
- cancel an active delegated task; and
- create one or more ordinary top-level T3 threads.
## External Provider Wiring
These are T3 orchestration operations, not provider-native sub-agent APIs.
Delegated tasks always create a T3 child thread and run. The child receives
only the supplied task prompt, plus an optional role instruction supplied in
the same tool call. Parent conversation history is not copied into the child.
### Codex
## Transport And Authentication
Codex supports MCP through Codex configuration. Official docs say MCP servers
are stored in `config.toml`, normally `~/.codex/config.toml`, and can also be
project-scoped through `.codex/config.toml` for trusted projects. Stdio servers
use `[mcp_servers.<server-name>]` with `command`, `args`, `env`, `env_vars`,
`cwd`, timeout, enabled, required, and tool allow/deny options.
Local fit:
- Current Codex sessions start `codex app-server` with `CODEX_HOME` supplied
by `CodexSessionRuntimeOptions.homePath`.
- The generated app-server protocol already includes
`config/mcpServer/reload`, `mcpServerStatus/list`,
`mcpServer/resource/read`, `mcpServer/tool/call`, OAuth completion, and MCP
startup status notifications.
- Current `CodexHomeLayout` can create shadow homes, but it currently symlinks
`config.toml` from the shared home. V2 should add an app-managed MCP config
projection instead of mutating arbitrary user TOML blindly.
Recommended projection:
```toml
[mcp_servers.t3_orchestrator]
command = "/path/to/t3"
args = ["mcp", "orchestrator", "--transport", "stdio"]
env = {
T3_ORCH_MCP_TOKEN = "<short-lived capability token>",
T3_ORCH_MCP_ENDPOINT = "http://127.0.0.1:<port>",
T3_ORCH_MCP_CONTEXT = "<signed parent context id>"
}
enabled = true
required = false
tool_timeout_sec = 600
enabled_tools = [
"orchestrator_capabilities",
"delegate_task",
"task_status",
"task_cancel"
]
```
Implementation note: prefer a structured TOML merge into an app-managed
session home. If we must touch a user-visible `config.toml`, own only the
`mcp_servers.t3_orchestrator` table, preserve all other tables, and call
`config/mcpServer/reload` after updating a running app-server.
### Claude Agent SDK
Claude Agent SDK exposes MCP directly in `query` options. Official docs show
`mcpServers` entries in the SDK options and require `allowedTools` for Claude
to use those tools without broad permission bypass. Tool names are granted as
`mcp__<serverName>__<toolName>` or with a server wildcard.
Local fit:
- `ClaudeAdapter` already builds a `ClaudeQueryOptions` object in
`startSession`.
- Add `mcpServers.t3_orchestrator` and `allowedTools:
["mcp__t3_orchestrator__*"]` there.
- This is per Claude query/session startup. There is no hot reload path in our
current Claude adapter, so changing the MCP projection should restart or
recreate the Claude query runtime.
Recommended projection:
```ts
const queryOptions: ClaudeQueryOptions = {
...existing,
mcpServers: {
...existing.mcpServers,
t3_orchestrator: {
command: t3BinaryPath,
args: ["mcp", "orchestrator", "--transport", "stdio"],
env: buildOrchestratorMcpEnv(parentContext),
},
},
allowedTools: [...existingAllowedTools, "mcp__t3_orchestrator__*"],
};
```
### OpenCode
OpenCode supports local and remote MCP servers under the `mcp` config object.
Local servers use `type: "local"`, `command: string[]`, optional
`environment`, `enabled`, and timeout. Remote servers use `type: "remote"`,
`url`, headers, OAuth, and timeout. OpenCode tools are managed by glob-like
tool names, and MCP tools are prefixed by server name.
Local fit:
- Our local OpenCode server path spawns `opencode serve` and currently sets
`OPENCODE_CONFIG_CONTENT` to `JSON.stringify({})`.
- When T3 owns the OpenCode server process, V2 can merge the orchestrator MCP
config into that generated config content before process start.
- When `serverUrl` points at an external OpenCode server, T3 does not own the
server config. Treat automatic MCP injection as unsupported unless OpenCode
exposes a runtime config API we intentionally adopt.
Recommended projection for owned servers:
```ts
const opencodeConfig = {
...existingGeneratedConfig,
mcp: {
...existingGeneratedConfig.mcp,
t3_orchestrator: {
type: "local",
command: [t3BinaryPath, "mcp", "orchestrator", "--transport", "stdio"],
environment: buildOrchestratorMcpEnv(parentContext),
enabled: true,
timeout: 600_000,
},
},
tools: {
...existingGeneratedConfig.tools,
"t3_orchestrator_*": true,
},
};
```
### Cursor SDK
Cursor's TypeScript SDK exposes Cursor agents as durable `Agent` objects and
per-prompt `Run` objects. It also exposes MCP through SDK options instead of
requiring us to mutate Cursor editor configuration. Local agents can receive
inline `mcpServers` at `Agent.create` time and at `agent.send` time. Cloud
agents can also receive inline MCP configuration, but stdio servers run inside
the cloud VM; use a reachable remote MCP transport for cloud agents rather
than a local T3 binary path.
Local fit:
- The V2 Cursor adapter should model a Cursor SDK `Agent` as the provider
thread and a Cursor SDK `Run` as the provider turn.
- `Agent.resume(agentId, options)` can reattach to durable Cursor state, but
inline MCP configuration is not persisted across resume. The adapter must
rebuild and pass the current orchestrator MCP projection on resume and on
each run that should expose T3 orchestration tools.
- `Run.stream()`, `Run.wait()`, and `Run.cancel()` map cleanly to V2 streaming,
terminal turn state, and interrupt semantics.
- Cursor SDK stream messages include normalized message types such as
assistant text, reasoning, tool calls, status, task, and request. Tool
argument/result payloads should be treated as provider diagnostics until
replay fixtures prove stable shapes for the V2 normalizer.
- Send-time inline `mcpServers` replaces the create-time inline server set for
that run. When using send-time injection, always pass the full desired MCP
server set, not only the delta.
Recommended projection for local SDK agents:
```ts
const agent = await Agent.create({
local: { cwd },
model,
mcpServers: {
t3_orchestrator: {
command: t3BinaryPath,
args: ["mcp", "orchestrator", "--transport", "stdio"],
env: buildOrchestratorMcpEnv(parentContext),
},
},
});
const run = await agent.send(prompt, {
model,
mcpServers: {
t3_orchestrator: {
command: t3BinaryPath,
args: ["mcp", "orchestrator", "--transport", "stdio"],
env: buildOrchestratorMcpEnv(parentContext),
},
},
});
```
Recommended V2 posture:
- Prefer the Cursor SDK for the V2 adapter foundation. It gives V2 first-class
provider-thread resumption, run lifecycle, streaming, cancellation, model
selection, and MCP injection primitives.
- Do not silently write project/global Cursor config from a provider session.
Project config mutation is user-visible and should be an explicit user
setting or setup step.
## V2 Capability Additions
Extend provider capabilities instead of branching on provider kind:
```ts
type ToolCapabilities = {
exposesToolItemIds: boolean;
emitsToolStarted: boolean;
emitsToolCompleted: boolean;
emitsToolOutput: boolean;
supportsMcpTools: boolean;
supportsDynamicToolCallbacks: boolean;
mcpInjection:
| { type: "none" }
| { type: "sdk_options"; reload: "per_run" | "restart_required" }
| { type: "config_file"; reload: "hot_reload" | "restart_required" }
| { type: "process_env_config"; reload: "restart_required" }
| { type: "external_config_only" };
};
type SubagentCapabilities = {
supportsSubagents: boolean;
exposesSubagentThreadIds: boolean;
emitsSubagentLifecycle: boolean;
canWaitForSubagents: boolean;
canCloseSubagents: boolean;
canForkSubagentThread: boolean;
supportsCrossProviderDelegationViaMcp: boolean;
};
```
Expected initial values:
The orchestration tools share the existing authenticated HTTP MCP endpoint:
```text
codex mcpInjection=config_file/hot_reload, native subagents=yes
claudeAgent mcpInjection=sdk_options/restart_required
openCode mcpInjection=process_env_config/restart_required for owned servers
cursor mcpInjection=sdk_options/per_run for SDK, external_config_only for legacy ACP
http://127.0.0.1:<server-port>/mcp
```
## MCP Server Shape
The provider-visible server key is `t3-code`. The endpoint registers both the
preview toolkit and the orchestration toolkit.
The server should be named `t3_orchestrator` and should expose a small stable
tool surface. Tool names should stay generic because this server will outgrow
subagents.
Before `ProviderSessionManager` opens a new V2 provider session, it asks
`McpSessionRegistry` for a credential scoped to:
Use Effect's MCP server module as the implementation baseline:
- the T3 environment;
- the parent T3 thread;
- the concrete provider instance; and
- the provider session.
The credential grants `preview` and `orchestration` capabilities. Credentials
expire after a maximum lifetime, expire when idle, and are revoked when the
provider session is released. The raw token is not persisted in orchestration
state.
The MCP HTTP server resolves the bearer token and supplies the resulting
`McpInvocationScope` to tool handlers. Orchestration handlers additionally
check the `orchestration` capability before reading or mutating state.
## Provider Injection
### Codex V2
Codex app-server receives the remote MCP server through command-line config
overrides:
```text
-c mcp_servers.t3-code.url=http://127.0.0.1:<port>/mcp
-c mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"
```
The provider-session token is placed in `T3_MCP_BEARER_TOKEN`. Both the
production Codex launcher and the injectable test launcher use the same
projection helper.
### Claude Agent SDK V2
Claude receives an HTTP MCP server in its query options:
```ts
import { NodeRuntime, NodeStdio } from "@effect/platform-node";
import { Context, Effect, Layer, Logger, Schema } from "effect";
import { McpServer, Tool, Toolkit } from "effect/unstable/ai";
{
mcpServers: {
"t3-code": {
type: "http",
url: "http://127.0.0.1:<port>/mcp",
headers: {
Authorization: "Bearer <provider-session-token>",
},
},
},
allowedTools: [
// existing allowed tools
"mcp__t3-code__*",
],
}
```
The relevant primitives are:
The adapter logs only whether MCP configuration exists; it does not log the
server headers or token.
- `Tool.make` for typed MCP tool definitions.
- `Toolkit.make` and `Toolkit.toLayer` for tool handler registration.
- `McpServer.toolkit` for registering the toolkit with the MCP registry.
- `McpServer.layerStdio` for the provider-spawned stdio server.
- `McpServer.layerHttp` if we later need HTTP transport for internal tests or
non-stdio clients.
### Initial Provider Support
### Tools
The initial V2 provider adapters are Codex and Claude Agent SDK. Capability
discovery still reports other registered provider instances, but marks them
unavailable for orchestration when no V2 adapter exists. This keeps provider
selection model-visible without allowing a request that cannot run.
`orchestrator_capabilities`
## Tool Surface
Returns the providers, provider instances, models, runtime modes, and
delegation features currently available to the parent context.
The server exposes five orchestration tools.
```ts
type OrchestratorCapabilitiesResult = {
providers: Array<{
providerInstanceId: string;
driverKind: string;
displayName?: string;
models: Array<{ id: string; label?: string }>;
canRunChildTask: boolean;
canRunSameProviderNativeSubagent: boolean;
canRunCrossProviderChildTask: boolean;
constraints: string[];
}>;
};
```
### `orchestrator_capabilities`
`delegate_task`
Returns:
Requests a child execution task. The orchestrator decides whether this becomes
a same-provider native subagent, a child app thread/run on another provider, or
a rejected request with a model-visible error.
- the inherited provider instance and model;
- the parent runtime and interaction modes;
- registered provider instances and advertised models;
- whether each provider can run a child task; and
- feature flags for polling, cancellation, and batch thread creation.
Unavailable providers include model-visible constraints such as missing V2
adapter support, disabled state, missing executable, or missing authentication.
### `delegate_task`
Creates a T3-owned child thread and immediately dispatches the supplied task
prompt.
```ts
type DelegateTaskInput = {
@@ -298,384 +121,178 @@ type DelegateTaskInput = {
driverKind?: string;
model?: string;
};
title?: string;
role?: "implementation" | "research" | "review" | "design" | "test" | "general";
mode?: "async" | "wait";
timeoutMs?: number;
clientRequestId?: string;
context?: {
summary?: string;
files?: string[];
sourcePoint?: {
threadId?: string;
runId?: string;
nodeId?: string;
checkpointId?: string;
};
};
runtimeMode?: "inherit" | "read_only" | "workspace_write" | "full_access";
runtimeMode?: "inherit" | "approval-required" | "auto-accept-edits" | "full-access";
interactionMode?: "inherit" | "plan" | "default";
};
```
Provider, model, runtime mode, and interaction mode inherit from the parent
when omitted. Selecting a different provider without a model uses that
provider's first advertised model.
Delegation requires an active parent run owned by the MCP credential's
provider session. The request becomes the V2 command
`delegated_task.request`.
`mode: "async"` returns the current durable state immediately.
`mode: "wait"` polls the same durable state until it becomes terminal or the
timeout expires. A wait timeout does not cancel the child; the result sets
`waitTimedOut: true`, and the caller can continue with `task_status`.
```ts
type DelegateTaskResult = {
taskId: string;
childThreadId?: string;
childRunId?: string;
childThreadId: string;
childRunId: string | null;
childNodeId: string;
status: "queued" | "running" | "completed" | "failed" | "cancelled" | "rejected";
status: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "interrupted";
providerInstanceId: string;
model?: string;
summary?: string;
failure?: {
code: string;
message: string;
};
resultContextTransferId?: string;
model: string | null;
summary: string | null;
resultContextTransferId: string | null;
waitTimedOut: boolean;
};
```
`task_status`
### `task_status`
Returns the latest durable state for a delegated task, including final summary,
artifact refs, child thread/run/node ids, failure reason, and whether the
parent can wait longer.
Reads a delegated task from the parent thread's durable projection. A task ID
from another parent thread is rejected. Terminal results include the child
summary and the durable `subagent_result` context transfer ID when available.
`task_cancel`
### `task_cancel`
Cancels a delegated task through the V2 command layer. This should target app
ids and let the adapter translate to native interruption.
Interrupts the active child run through the normal V2 `run.interrupt` command.
It is idempotent for terminal tasks and accepts an optional cancellation
reason.
Future tools can use the same server:
### `create_threads`
- `context_read` for bounded, orchestrator-curated context resources.
- `handoff_request` for agent-initiated provider switching.
- `checkpoint_create` for explicit child scopes.
- `plan_review_request` for app-owned plan review flows.
Creates between one and twenty ordinary top-level T3 threads:
### MCP Tool Result Rules
MCP clients call tools with `tools/call` and arguments. Effect's
`McpServer.toolkit` registers Effect `Tool` definitions as MCP tools, emits
JSON schemas from Effect Schema, and returns both model-visible text content
and `structuredContent` from encoded tool results. Handler failures are mapped
to MCP tool errors, while protocol failures stay JSON-RPC errors.
For expected orchestration denials, prefer typed tool failures or explicit
rejected statuses over defects. That keeps "provider unavailable", "permission
denied", and "runtime mode escalation denied" as model-actionable outcomes
instead of transport-level failures.
For long-running work, prefer:
```text
delegate_task(mode="async")
-> returns taskId immediately
task_status(taskId)
-> model polls when it needs result
```ts
type CreateThreadsInput = {
threads: Array<{
prompt?: string;
title?: string;
target?: {
providerInstanceId?: string;
driverKind?: string;
model?: string;
};
runtimeMode?: "inherit" | "approval-required" | "auto-accept-edits" | "full-access";
interactionMode?: "inherit" | "plan" | "default";
}>;
clientRequestId?: string;
};
```
`delegate_task(mode="wait")` may block until completion or timeout, but it
still creates the same durable child node and returns the same ids.
Each entry independently resolves provider, model, and modes. The new threads
inherit the parent's project, branch, and worktree path, but they have no
sub-agent lineage. Entries with a prompt immediately dispatch a run; entries
without a prompt remain idle.
## Orchestrator Integration
## Delegated Task Lifecycle
The MCP server must not call provider adapters directly. It should be another
command ingress into V2 orchestration.
The MCP server is a command ingress into V2. It does not call provider adapters
directly.
```text
provider model
-> MCP tools/call delegate_task
-> T3 MCP server validates token and input
-> V2 command: delegated_task.request
-> durable event: DelegatedTaskRequested
-> execution graph: child ExecutionNode(parentNodeId=caller node)
-> ContextTransfer(type=subagent_spawn, createdBy=agent)
-> provider effect request starts/resumes selected child provider
-> child provider events normalize into graph
-> ContextTransfer(type=subagent_result) materializes result
-> MCP result / task_status returns durable child state
-> authenticated OrchestratorMcpService
-> V2 delegated_task.request command
-> child thread + child run
-> parent app_owned subagent projection
-> parent/child execution nodes
-> consumed subagent_spawn context transfer
-> normal provider effect and runtime ingestion
-> child run reaches a terminal state
-> parent subagent/node/turn item finalized
-> consumed subagent_result context transfer
-> wait result or later task_status result
```
Important boundaries:
The child thread has lineage relationship `subagent` and points back to the
parent node. The parent gets an `app_owned` sub-agent projection and a
sub-agent turn item so the existing debug UI can render progress.
- Authentication is through a short-lived capability token scoped to the
parent session/thread/run/node and delivered through MCP server env.
- Authorization is app-owned. The tool input can ask for a provider, model,
files, and runtime mode; policy decides what is allowed.
- Runtime mode can only stay the same or narrow without explicit user
approval. A parent in read-only mode cannot create a full-access child.
- Child tasks use app ids. Native provider ids are refs and are scoped through
normal V2 identity bindings.
- `clientRequestId` makes MCP retries idempotent within the parent MCP session.
- The parent tool call item should be linked to the child `ExecutionNode` so
the UI can show progress under the parent turn.
- The child result should flow back through `ContextTransfer`, not hidden prompt
concatenation.
Terminal provider events trigger finalization. The event stream first replays
persisted events and then follows live events, so finalization also runs after
a server restart. An existing `subagent_result` transfer makes finalization
idempotent.
## Pseudo-Code
The result summary prefers the latest assistant content from the child run and
falls back to a terminal-status message when no assistant text exists.
Typed tool declarations:
## Policy And Idempotency
Assume the `*Schema` constants mirror the TypeScript shapes above.
- A child runtime mode may stay equal to or become narrower than the parent
mode. It may not escalate privileges.
- A child interaction mode may stay equal to or narrow from `default` to
`plan`. It may not escalate from `plan` to `default`.
- Provider instances must be enabled, installed, available, authenticated, and
backed by a V2 adapter.
- A requested model must be advertised by the selected provider when the
provider publishes a model list.
- `clientRequestId` derives stable command, thread, and message IDs within the
provider session. Retrying the same call returns the same durable work.
- Calls without `clientRequestId` receive a generated request key and create
new work.
```ts
const DelegationFailure = Schema.Struct({
code: Schema.Literals([
"provider_unavailable",
"model_unavailable",
"permission_denied",
"runtime_mode_escalation_denied",
"timeout",
"internal_error",
]),
message: Schema.String,
});
Expected denials use the typed `OrchestratorMcpFailure` result:
const OrchestratorCapabilities = Tool.make("orchestrator_capabilities", {
description: "List providers and models available for delegated work.",
success: OrchestratorCapabilitiesResultSchema,
}).annotate(Tool.Readonly, true);
const DelegateTask = Tool.make("delegate_task", {
description: "Request a child orchestration task from T3.",
parameters: DelegateTaskInputSchema,
success: DelegateTaskResultSchema,
failure: DelegationFailure,
failureMode: "return",
}).annotate(Tool.Idempotent, true);
const TaskStatus = Tool.make("task_status", {
description: "Read the latest durable state for a delegated task.",
parameters: Schema.Struct({
taskId: Schema.String,
}),
success: DelegateTaskResultSchema,
}).annotate(Tool.Readonly, true);
const TaskCancel = Tool.make("task_cancel", {
description: "Cancel a delegated task.",
parameters: Schema.Struct({
taskId: Schema.String,
reason: Schema.optionalKey(Schema.String),
}),
success: Schema.Struct({
taskId: Schema.String,
status: Schema.Literal("cancel_requested"),
}),
failure: DelegationFailure,
failureMode: "return",
}).annotate(Tool.Idempotent, true);
const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilities,
DelegateTask,
TaskStatus,
TaskCancel,
);
```text
capability_denied
parent_not_active
provider_unavailable
model_unavailable
runtime_mode_escalation_denied
interaction_mode_escalation_denied
task_not_found
task_not_cancellable
invalid_request
orchestration_error
```
Provider projection contract:
## Code Ownership
```ts
type OrchestratorMcpProjection = {
serverName: "t3_orchestrator";
command: string;
args: string[];
env: Record<string, string>;
allowedToolNames: string[];
};
- Shared schemas: `packages/contracts/src/orchestratorMcp.ts`
- MCP service: `apps/server/src/mcp/OrchestratorMcpService.ts`
- Tool definitions and handlers:
`apps/server/src/mcp/toolkits/orchestrator/`
- HTTP registration and authentication:
`apps/server/src/mcp/McpHttpServer.ts`
- Credential lifecycle: `apps/server/src/mcp/McpSessionRegistry.ts`
- Provider injection:
`apps/server/src/orchestration-v2/ProviderSessionManager.ts` and V2 adapters
- Durable delegated-task command and finalization:
`apps/server/src/orchestration-v2/Orchestrator.ts`
type ProviderMcpProjector = {
support: ToolCapabilities["mcpInjection"];
buildProjection(input: {
parentThreadId: string;
parentRunId?: string;
parentNodeId?: string;
providerInstanceId: string;
cwd: string;
}): OrchestratorMcpProjection;
};
```
## Verification
MCP server entrypoint using Effect layers:
The integration test uses the real MCP toolkit registration, V2 orchestrator,
SQL persistence, event ingestion, projections, and checkpoints. Only the
external provider adapters are deterministic test implementations.
```ts
class OrchestratorMcpAuth extends Context.Service<OrchestratorMcpAuth, OrchestratorMcpAuthShape>()(
"t3/orchestrator-mcp/Auth",
) {}
Coverage includes:
const OrchestratorMcpHandlers = OrchestratorToolkit.toLayer({
orchestrator_capabilities: () =>
Effect.gen(function* () {
const auth = yield* OrchestratorMcpAuth;
const orchestration = yield* OrchestrationV2;
return yield* orchestration.readDelegationCapabilities(auth.scope);
}),
- capability discovery;
- cross-provider delegated completion;
- prompt-only child context;
- parent and child lineage projections;
- spawn and result context transfers;
- async status polling;
- cancellation;
- batch ordinary-thread creation;
- inheritance and per-thread provider overrides; and
- idempotent retries.
delegate_task: (input) =>
Effect.gen(function* () {
const auth = yield* OrchestratorMcpAuth;
const orchestration = yield* OrchestrationV2;
const commandId = stableCommandId(auth.mcpSessionId, input.clientRequestId);
const receipt = yield* orchestration.dispatch({
type: "delegated_task.request",
commandId,
causation: {
source: "mcp",
providerInstanceId: auth.providerInstanceId,
parentThreadId: auth.parentThreadId,
parentRunId: auth.parentRunId,
parentNodeId: auth.parentNodeId,
},
input,
});
if (input.mode !== "wait") {
return toDelegateTaskResult(receipt);
}
const finalState = yield* orchestration.waitForDelegatedTask(
receipt.taskId,
input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
);
return toDelegateTaskResult(finalState);
}),
task_status: ({ taskId }) =>
Effect.gen(function* () {
const auth = yield* OrchestratorMcpAuth;
const orchestration = yield* OrchestrationV2;
return yield* orchestration.readDelegatedTask(auth.scope, taskId);
}),
task_cancel: ({ taskId, reason }) =>
Effect.gen(function* () {
const auth = yield* OrchestratorMcpAuth;
const orchestration = yield* OrchestrationV2;
return yield* orchestration.cancelDelegatedTask(auth.scope, {
taskId,
reason,
});
}),
});
const ServerLayer = McpServer.toolkit(OrchestratorToolkit).pipe(
Layer.provide(OrchestratorMcpHandlers),
Layer.provide(OrchestrationMcpServicesLive),
Layer.provide(
McpServer.layerStdio({
name: "t3_orchestrator",
version: APP_VERSION,
}),
),
Layer.provide(NodeStdio.layer),
Layer.provide(Layer.succeed(Logger.LogToStderr)(true)),
);
Layer.launch(ServerLayer).pipe(NodeRuntime.runMain);
```
The handler layer should translate expected orchestration denials into typed
tool failures or explicit rejected statuses. Defects, malformed inputs, and
protocol problems can remain Effect failures so `McpServer.toolkit` maps them
to MCP tool errors.
Provider hooks:
```ts
function applyCodexProjection(home: CodexHome, projection: OrchestratorMcpProjection) {
mergeTomlTable(home.configToml, "mcp_servers.t3_orchestrator", {
command: projection.command,
args: projection.args,
env: projection.env,
enabled_tools: projection.allowedToolNames,
enabled: true,
required: false,
});
codexRpc.request("config/mcpServer/reload");
}
function applyClaudeProjection(options: ClaudeQueryOptions, projection: OrchestratorMcpProjection) {
options.mcpServers = {
...options.mcpServers,
[projection.serverName]: {
command: projection.command,
args: projection.args,
env: projection.env,
},
};
options.allowedTools = [...(options.allowedTools ?? []), `mcp__${projection.serverName}__*`];
}
function buildOpenCodeConfig(projection: OrchestratorMcpProjection) {
return {
mcp: {
[projection.serverName]: {
type: "local",
command: [projection.command, ...projection.args],
environment: projection.env,
enabled: true,
},
},
tools: {
[`${projection.serverName}_*`]: true,
},
};
}
function applyCursorSdkProjection<T extends { mcpServers?: Record<string, unknown> }>(
options: T,
projection: OrchestratorMcpProjection,
): T {
return {
...options,
mcpServers: {
...(options.mcpServers ?? {}),
[projection.serverName]: {
command: projection.command,
args: projection.args,
env: projection.env,
},
},
};
}
```
## Testing Plan
- Unit test provider projection builders for Codex TOML, Claude query options,
OpenCode JSON config, and Cursor SDK create/send options.
- Cursor SDK replay tests should assert that the adapter re-supplies the
orchestrator MCP projection after `Agent.resume` and on each `agent.send`
that exposes orchestration tools.
- Unit test MCP schemas and error mapping: expected denials return typed tool
outcomes, handler failures become MCP tool errors, and protocol errors stay
JSON-RPC errors.
- Replay-backed integration test: a synthetic parent MCP `delegate_task` call
creates `DelegatedTaskRequested`, a child execution node, a child provider
effect, child runtime events, and a result context transfer.
- Failure tests: provider unavailable, missing model, runtime mode escalation,
duplicate `clientRequestId`, child timeout, child cancellation, and parent
session restart.
- Provider-specific tests should mock only external harness/process layers,
not orchestration business logic.
## Sources Checked
- OpenAI Codex MCP configuration:
https://developers.openai.com/codex/mcp
- OpenAI Codex app-server lifecycle and MCP app-server methods observed in
generated local protocol:
https://developers.openai.com/codex/app-server
- Claude Agent SDK MCP options and `allowedTools`:
https://code.claude.com/docs/en/agent-sdk/mcp
- OpenCode MCP configuration:
https://opencode.ai/docs/mcp-servers
- Cursor TypeScript SDK agents, runs, resume, MCP, and cloud behavior:
https://cursor.com/docs/sdk/typescript
- Cursor CLI MCP behavior for legacy ACP fallback and external configuration:
https://cursor.com/docs/cli/mcp
- Cursor CLI ACP behavior for legacy adapter context:
https://cursor.com/docs/cli/acp
- Effect MCP server module:
https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/ai/McpServer.ts
- MCP tool call and result schema:
https://modelcontextprotocol.io/specification/2025-06-18/schema
Provider adapter tests separately verify Codex and Claude MCP injection, and
the provider-session manager test verifies that credentials exist before an
adapter opens and are revoked when it closes.
+1
View File
@@ -21,6 +21,7 @@ export * from "./sourceControl.ts";
export * from "./pullRequest.ts";
export * from "./orchestration.ts";
export * from "./orchestrationV2.ts";
export * from "./orchestratorMcp.ts";
export * from "./editor.ts";
export * from "./project.ts";
export * from "./filesystem.ts";
+28 -1
View File
@@ -29,6 +29,7 @@ import {
} from "./orchestrationV2.ts";
const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
const decodeOrchestrationV2Command = Schema.decodeUnknownSync(OrchestrationV2Command);
describe("orchestration V2 contracts", () => {
it("decodes nested checkpoint scopes without making child scopes advance app run count", () => {
@@ -86,7 +87,7 @@ describe("orchestration V2 contracts", () => {
});
it("decodes command and domain event shapes for command-to-projection tests", () => {
const command = Schema.decodeUnknownSync(OrchestrationV2Command)({
const command = decodeOrchestrationV2Command({
type: "message.dispatch",
commandId: "command-1",
threadId: "thread-1",
@@ -128,6 +129,32 @@ describe("orchestration V2 contracts", () => {
expect(event.payload.id).toBe(RunId.make("run-1"));
});
it("decodes app-owned delegated task commands", () => {
const command = decodeOrchestrationV2Command({
type: "delegated_task.request",
commandId: "command-delegate-1",
parentThreadId: "thread-parent-1",
parentRunId: "run-parent-1",
parentNodeId: "node-parent-1",
task: "Inspect the API boundary.",
title: "API inspection",
modelSelection: {
instanceId: "claudeAgent",
model: "claude-sonnet-4-6",
},
runtimeMode: "approval-required",
interactionMode: "plan",
});
expect(command.type).toBe("delegated_task.request");
if (command.type !== "delegated_task.request") {
throw new Error("expected delegated_task.request");
}
expect(command.parentThreadId).toBe(ThreadId.make("thread-parent-1"));
expect(command.parentRunId).toBe(RunId.make("run-parent-1"));
expect(command.parentNodeId).toBe(NodeId.make("node-parent-1"));
});
it("decodes provider-neutral replay transcripts", () => {
const transcript = Schema.decodeUnknownSync(ProviderReplayTranscript)({
provider: "codex",
+14
View File
@@ -1463,6 +1463,7 @@ export const OrchestrationV2Command = Schema.Union([
commandId: CommandId,
threadId: ThreadId,
runId: RunId,
reason: Schema.optional(Schema.String),
}),
Schema.Struct({
type: Schema.Literal("queued-message.promote-to-steer"),
@@ -1510,6 +1511,19 @@ export const OrchestrationV2Command = Schema.Union([
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
createdAt: Schema.optional(Schema.DateTimeUtc),
}),
Schema.Struct({
type: Schema.Literal("delegated_task.request"),
commandId: CommandId,
parentThreadId: ThreadId,
parentRunId: RunId,
parentNodeId: NodeId,
task: TrimmedNonEmptyString,
title: Schema.optional(TrimmedNonEmptyString),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
createdAt: Schema.optional(Schema.DateTimeUtc),
}),
Schema.Struct({
type: Schema.Literal("provider.switch"),
commandId: CommandId,
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import * as Schema from "effect/Schema";
import {
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpDelegateTaskInput,
OrchestratorMcpDelegateTaskResult,
} from "./orchestratorMcp.ts";
const decodeCreateThreadsInput = Schema.decodeUnknownSync(OrchestratorMcpCreateThreadsInput);
const decodeDelegateTaskInput = Schema.decodeUnknownSync(OrchestratorMcpDelegateTaskInput);
const decodeDelegateTaskResult = Schema.decodeUnknownSync(OrchestratorMcpDelegateTaskResult);
describe("orchestrator MCP contracts", () => {
it("decodes cross-provider delegated task requests and durable results", () => {
const request = decodeDelegateTaskInput({
task: "Inspect the workspace and report the result.",
target: {
providerInstanceId: "claudeAgent",
model: "claude-sonnet-4-6",
},
mode: "wait",
timeoutMs: 5_000,
clientRequestId: "delegate-1",
runtimeMode: "inherit",
interactionMode: "inherit",
});
const result = decodeDelegateTaskResult({
taskId: "node-task-1",
childThreadId: "thread-child-1",
childRunId: "run-child-1",
childNodeId: "node-task-1",
status: "completed",
providerInstanceId: "claudeAgent",
model: "claude-sonnet-4-6",
summary: "Workspace inspected.",
resultContextTransferId: "context-transfer-result-1",
waitTimedOut: false,
});
expect(request.target?.providerInstanceId).toBe("claudeAgent");
expect(result.status).toBe("completed");
expect(result.summary).toBe("Workspace inspected.");
});
it("decodes mixed prompted and empty thread batches", () => {
const request = decodeCreateThreadsInput({
clientRequestId: "threads-1",
threads: [
{ title: "Inherited empty thread" },
{
prompt: "Review the API.",
target: { driverKind: "claudeAgent" },
runtimeMode: "approval-required",
},
],
});
expect(request.threads).toHaveLength(2);
expect(request.threads[0]?.prompt).toBeUndefined();
expect(request.threads[1]?.target?.driverKind).toBe("claudeAgent");
});
});
+190
View File
@@ -0,0 +1,190 @@
import * as Schema from "effect/Schema";
import {
ContextTransferId,
NodeId,
RunId,
ThreadId,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
import { ProviderInteractionMode, RuntimeMode } from "./orchestration.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000));
const OrchestratorMcpTitle = TrimmedNonEmptyString.check(Schema.isMaxLength(512));
const OrchestratorMcpClientRequestId = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
export const OrchestratorMcpTarget = Schema.Struct({
providerInstanceId: Schema.optional(ProviderInstanceId),
driverKind: Schema.optional(ProviderDriverKind),
model: Schema.optional(TrimmedNonEmptyString),
});
export type OrchestratorMcpTarget = typeof OrchestratorMcpTarget.Type;
export const OrchestratorMcpRuntimeMode = Schema.Union([Schema.Literal("inherit"), RuntimeMode]);
export type OrchestratorMcpRuntimeMode = typeof OrchestratorMcpRuntimeMode.Type;
export const OrchestratorMcpInteractionMode = Schema.Union([
Schema.Literal("inherit"),
ProviderInteractionMode,
]);
export type OrchestratorMcpInteractionMode = typeof OrchestratorMcpInteractionMode.Type;
export const OrchestratorMcpTaskRole = Schema.Literals([
"implementation",
"research",
"review",
"design",
"test",
"general",
]);
export type OrchestratorMcpTaskRole = typeof OrchestratorMcpTaskRole.Type;
export const OrchestratorMcpDelegatedTaskStatus = Schema.Literals([
"queued",
"running",
"waiting",
"completed",
"failed",
"cancelled",
"interrupted",
]);
export type OrchestratorMcpDelegatedTaskStatus = typeof OrchestratorMcpDelegatedTaskStatus.Type;
export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
task: OrchestratorMcpPrompt,
target: Schema.optional(OrchestratorMcpTarget),
title: Schema.optional(OrchestratorMcpTitle),
role: Schema.optional(OrchestratorMcpTaskRole),
mode: Schema.optional(Schema.Literals(["async", "wait"])),
timeoutMs: Schema.optional(Schema.Number),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
runtimeMode: Schema.optional(OrchestratorMcpRuntimeMode),
interactionMode: Schema.optional(OrchestratorMcpInteractionMode),
});
export type OrchestratorMcpDelegateTaskInput = typeof OrchestratorMcpDelegateTaskInput.Type;
export const OrchestratorMcpDelegateTaskResult = Schema.Struct({
taskId: NodeId,
childThreadId: ThreadId,
childRunId: Schema.NullOr(RunId),
childNodeId: NodeId,
status: OrchestratorMcpDelegatedTaskStatus,
providerInstanceId: ProviderInstanceId,
model: Schema.NullOr(Schema.String),
summary: Schema.NullOr(Schema.String),
resultContextTransferId: Schema.NullOr(ContextTransferId),
waitTimedOut: Schema.Boolean,
});
export type OrchestratorMcpDelegateTaskResult = typeof OrchestratorMcpDelegateTaskResult.Type;
export const OrchestratorMcpTaskStatusInput = Schema.Struct({
taskId: NodeId,
});
export type OrchestratorMcpTaskStatusInput = typeof OrchestratorMcpTaskStatusInput.Type;
export const OrchestratorMcpTaskCancelInput = Schema.Struct({
taskId: NodeId,
reason: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
});
export type OrchestratorMcpTaskCancelInput = typeof OrchestratorMcpTaskCancelInput.Type;
export const OrchestratorMcpTaskCancelResult = Schema.Struct({
taskId: NodeId,
status: Schema.Literals(["cancel_requested", "completed", "failed", "cancelled", "interrupted"]),
});
export type OrchestratorMcpTaskCancelResult = typeof OrchestratorMcpTaskCancelResult.Type;
export const OrchestratorMcpCreateThreadRequest = Schema.Struct({
prompt: Schema.optional(OrchestratorMcpPrompt),
title: Schema.optional(OrchestratorMcpTitle),
target: Schema.optional(OrchestratorMcpTarget),
runtimeMode: Schema.optional(OrchestratorMcpRuntimeMode),
interactionMode: Schema.optional(OrchestratorMcpInteractionMode),
});
export type OrchestratorMcpCreateThreadRequest = typeof OrchestratorMcpCreateThreadRequest.Type;
export const OrchestratorMcpCreateThreadsInput = Schema.Struct({
threads: Schema.Array(OrchestratorMcpCreateThreadRequest).check(
Schema.isMinLength(1),
Schema.isMaxLength(20),
),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
});
export type OrchestratorMcpCreateThreadsInput = typeof OrchestratorMcpCreateThreadsInput.Type;
export const OrchestratorMcpCreatedThreadStatus = Schema.Union([
Schema.Literal("idle"),
Schema.Literal("starting"),
OrchestratorMcpDelegatedTaskStatus,
Schema.Literal("rolled_back"),
]);
export type OrchestratorMcpCreatedThreadStatus = typeof OrchestratorMcpCreatedThreadStatus.Type;
export const OrchestratorMcpCreatedThread = Schema.Struct({
threadId: ThreadId,
runId: Schema.NullOr(RunId),
status: OrchestratorMcpCreatedThreadStatus,
title: Schema.String,
providerInstanceId: ProviderInstanceId,
model: Schema.String,
});
export type OrchestratorMcpCreatedThread = typeof OrchestratorMcpCreatedThread.Type;
export const OrchestratorMcpCreateThreadsResult = Schema.Struct({
threads: Schema.Array(OrchestratorMcpCreatedThread),
});
export type OrchestratorMcpCreateThreadsResult = typeof OrchestratorMcpCreateThreadsResult.Type;
export const OrchestratorMcpProviderCapability = Schema.Struct({
providerInstanceId: ProviderInstanceId,
driverKind: ProviderDriverKind,
displayName: Schema.NullOr(Schema.String),
models: Schema.Array(
Schema.Struct({
id: Schema.String,
label: Schema.NullOr(Schema.String),
}),
),
canRunChildTask: Schema.Boolean,
canRunCrossProviderChildTask: Schema.Boolean,
constraints: Schema.Array(Schema.String),
});
export type OrchestratorMcpProviderCapability = typeof OrchestratorMcpProviderCapability.Type;
export const OrchestratorMcpCapabilitiesResult = Schema.Struct({
parentThreadId: ThreadId,
inheritedProviderInstanceId: ProviderInstanceId,
inheritedModel: Schema.String,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
providers: Schema.Array(OrchestratorMcpProviderCapability),
features: Schema.Struct({
appOwnedSubagents: Schema.Boolean,
asyncPolling: Schema.Boolean,
cancellation: Schema.Boolean,
batchThreadCreation: Schema.Boolean,
maxBatchThreads: Schema.Number,
}),
});
export type OrchestratorMcpCapabilitiesResult = typeof OrchestratorMcpCapabilitiesResult.Type;
export class OrchestratorMcpFailure extends Schema.TaggedErrorClass<OrchestratorMcpFailure>()(
"OrchestratorMcpFailure",
{
code: Schema.Literals([
"capability_denied",
"parent_not_active",
"provider_unavailable",
"model_unavailable",
"runtime_mode_escalation_denied",
"interaction_mode_escalation_denied",
"task_not_found",
"task_not_cancellable",
"invalid_request",
"orchestration_error",
]),
message: Schema.String,
},
) {}