import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
CommandId,
ContextTransferId,
EnvironmentId,
GitCommandError,
MessageId,
NodeId,
ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
type OrchestratorMcpCapabilitiesResult,
OrchestratorMcpTarget,
type OrchestrationV2ThreadShell,
type ScheduledTask,
type ScheduledTaskUpsertInput,
ScheduledTaskId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderThreadId,
ProviderTurnId,
RunId,
ThreadId,
type OrchestrationV2ServerCommand,
type OrchestrationV2StoredEvent,
type OrchestrationV2ThreadProjection,
type ServerProvider,
} from "@t3tools/contracts";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import {
DispatchModeLimit,
type DispatchModeRefusal,
} from "../orchestration-v2/DispatchModeLimit.ts";
import {
OrchestratorProjectionError,
OrchestratorThreadAboveModeLimitError,
} from "../orchestration-v2/Orchestrator.ts";
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import { buildUnavailableProviderSnapshot } from "../provider/unavailableProviderSnapshot.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import { resolveRuntimeMode } from "./delegatedTaskModes.ts";
import type { ProjectionRecordFilter } from "../orchestration-v2/ProjectionStore.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget);
const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
);
describe("OrchestratorMcpService", () => {
it.effect("retries terminal acknowledgement with a fresh command id", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-ack-parent");
const childThreadId = ThreadId.make("thread:mcp-ack-child");
const childRunId = RunId.make("run:mcp-ack-child");
const taskId = NodeId.make("node:mcp-ack-task");
const resultTransferId = ContextTransferId.make("transfer:mcp-ack-result");
const acknowledgementCommandIds = yield* Ref.make<ReadonlyArray<string>>([]);
const acknowledgementAttempts = yield* Ref.make(0);
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
contextTransfers: [
{
id: resultTransferId,
type: "subagent_result",
sourceThreadId: childThreadId,
targetThreadId: parentThreadId,
sourcePoint: { runId: childRunId },
},
],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
result: "terminal result",
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [
{
id: childRunId,
ordinal: 1,
status: "completed",
startedAt: DateTime.makeUnsafe("2026-10-03T10:00:00Z"),
completedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"),
},
{
id: RunId.make("run:mcp-ack-continuation"),
ordinal: 2,
status: "failed",
startedAt: DateTime.makeUnsafe("2026-10-03T10:02:00Z"),
completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"),
},
],
contextTransfers: [],
messages: [
{
id: MessageId.make("message:mcp-ack-result"),
runId: childRunId,
role: "assistant",
text: "terminal result",
createdAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"),
updatedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"),
},
],
turnItems: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
} as unknown as OrchestrationV2ThreadProjection;
let hasNestedWork = true;
let settleAfterTaskRead = false;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.sync(() => {
if (threadId !== parentThreadId) {
return hasNestedWork
? {
...childProjection,
subagents: [
{ ...parentProjection.subagents[0]!, status: "running" as const },
],
}
: childProjection;
}
const snapshot = hasNestedWork
? {
...parentProjection,
contextTransfers: [],
subagents: parentProjection.subagents.map((task) => ({
...task,
result: null,
status: "running" as const,
})),
}
: parentProjection;
if (settleAfterTaskRead) {
settleAfterTaskRead = false;
hasNestedWork = false;
}
return snapshot;
}),
delegatedTaskResultPending: () => Effect.succeed(false),
dispatch: (command) =>
Ref.update(acknowledgementCommandIds, (commandIds) => [
...commandIds,
String(command.commandId),
]).pipe(
Effect.andThen(Ref.updateAndGet(acknowledgementAttempts, (count) => count + 1)),
Effect.flatMap((attempt) =>
attempt === 1
? Effect.fail(new Error("simulated acknowledgement failure") as never)
: Effect.succeed({} as never),
),
),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-ack"),
requestNamespace: "provider-session:mcp-ack",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-ack",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const pending = yield* service.taskStatus(scope, taskId);
assert.equal(pending.status, "running");
assert.equal(pending.workState, "waiting_for_children");
assert.isNull(pending.summary);
assert.isNull(pending.resultContextTransferId);
assert.equal(yield* Ref.get(acknowledgementAttempts), 0);
hasNestedWork = false;
const error = yield* service.taskStatus(scope, taskId).pipe(Effect.flip);
assert.equal(error.code, "orchestration_error");
// Completion lands after task selection, before the remaining parent/child reads.
hasNestedWork = true;
settleAfterTaskRead = true;
const result = yield* service.taskStatus(scope, taskId);
assert.equal(result.status, "completed");
assert.equal(result.summary, "terminal result");
assert.equal(result.latestTerminalRunId, childRunId);
assert.equal(result.latestTerminalStatus, "completed");
assert.equal(result.resultContextTransferId, resultTransferId);
const commandIds = yield* Ref.get(acknowledgementCommandIds);
assert.equal(commandIds.length, 2);
assert.notEqual(commandIds[0], commandIds[1]);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("reports a restart-cut child as working until its continuation settles", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-restart-parent");
const childThreadId = ThreadId.make("thread:mcp-restart-child");
const taskId = NodeId.make("node:mcp-restart-task");
const dispatched = yield* Ref.make(0);
let awaitsRestart = true;
let readFails = true;
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
status: "running",
result: null,
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [
{
id: RunId.make("run:mcp-restart-child"),
ordinal: 1,
status: "cancelled",
delegatedTaskId: taskId,
},
{ id: RunId.make("run:mcp-restart-later"), ordinal: 2, status: "running" },
],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
turnItems: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
delegatedTaskResultPending: () =>
readFails
? Effect.fail(new OrchestratorProjectionError({ threadId: childThreadId }))
: Effect.succeed(awaitsRestart),
dispatch: () => Ref.update(dispatched, (count) => count + 1).pipe(Effect.as({} as never)),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-restart"),
requestNamespace: "provider-session:mcp-restart",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-restart",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const failed = yield* service.taskStatus(scope, taskId).pipe(Effect.flip);
assert.equal(failed.code, "orchestration_error");
assert.equal(yield* Ref.get(dispatched), 0);
readFails = false;
const held = yield* service.taskStatus(scope, taskId);
assert.equal(held.status, "running");
assert.equal(held.workState, "working");
assert.isNull(held.summary);
assert.equal(yield* Ref.get(dispatched), 0);
awaitsRestart = false;
const settled = yield* service.taskStatus(scope, taskId);
assert.equal(settled.status, "cancelled");
assert.equal(yield* Ref.get(dispatched), 1);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("tells the parent to end its turn only while its task still runs", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-next-parent");
const childThreadId = ThreadId.make("thread:mcp-next-child");
const taskId = NodeId.make("node:mcp-next-task");
let finished = false;
let pendingRequest = false;
const parentProjection = () =>
({
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
status: finished ? "completed" : "running",
result: finished ? "done" : null,
completionDelivery: { state: "pending" },
},
],
}) as unknown as OrchestrationV2ThreadProjection;
const childRun = () => ({
id: RunId.make("run:mcp-next-child"),
ordinal: 1,
status: finished ? ("completed" as const) : ("running" as const),
delegatedTaskId: taskId,
});
const childProjection = () =>
({
thread: { id: childThreadId, title: "Child task" },
runs: [childRun()],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: pendingRequest ? [{ status: "pending" }] : [],
nodes: [],
turnItems: [],
}) as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection() : childProjection()),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
getProjectThreadRecords: () => Effect.succeed(childProjection()),
waitForThread: () =>
Effect.succeed({
threadId: childThreadId,
run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number],
timedOut: !finished,
}),
dispatch: () => Effect.succeed({} as never),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-next"),
requestNamespace: "provider-session:mcp-next",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-next",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const running = yield* service.taskStatus(scope, taskId);
assert.equal(running.status, "running");
assert.equal(running.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT);
const waiting = yield* service.waitForThread(scope, { threadId: childThreadId });
assert.isTrue(waiting.timedOut);
assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT);
// A child waiting on a question or approval needs an answer, not a wake.
pendingRequest = true;
const asking = yield* service.waitForThread(scope, { threadId: childThreadId });
assert.isTrue(asking.timedOut);
assert.notProperty(asking, "next");
pendingRequest = false;
finished = true;
const completed = yield* service.taskStatus(scope, taskId);
assert.equal(completed.status, "completed");
assert.notProperty(completed, "next");
const waited = yield* service.waitForThread(scope, { threadId: childThreadId });
assert.equal(waited.status, "completed");
assert.notProperty(waited, "next");
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("does not dispose delivery when a nonterminal task has no active child run", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-cancel-parent");
const childThreadId = ThreadId.make("thread:mcp-cancel-child");
const taskId = NodeId.make("node:mcp-cancel-task");
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
result: null,
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
listAppOwnedChildThreadIds: () => Effect.succeed([]),
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.as({} as never),
),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-cancel"),
requestNamespace: "provider-session:mcp-cancel",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-cancel",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const error = yield* service
.cancelTask(scope, { taskId, clientRequestId: "cancel-unstarted-task" })
.pipe(Effect.flip);
assert.equal(error.code, "task_not_cancellable");
assert.deepEqual(yield* Ref.get(dispatched), []);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect.each(["no runs", "a finished run"] as const)(
"cancels an orphaned follow-up through its parent when the child has %s",
(childState) =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-orphan-parent");
const childThreadId = ThreadId.make("thread:mcp-orphan-child");
const taskId = NodeId.make("node:mcp-orphan-task");
const parentRunId = RunId.make("run:mcp-orphan-parent");
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationV2ServerCommand>>([]);
const status = yield* Ref.make("running");
const parentProjection = (taskStatus: string) =>
({
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
runId: parentRunId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
status: taskStatus,
result: null,
completionDelivery: { state: "pending" },
},
],
}) as unknown as OrchestrationV2ThreadProjection;
// A finished run whose binding to the follow-up was lost.
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs:
childState === "no runs"
? []
: [{ id: RunId.make("run:mcp-orphan-child"), ordinal: 1, status: "completed" }],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
turnItems: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
threadId === parentThreadId
? Effect.map(Ref.get(status), parentProjection)
: Effect.succeed(childProjection),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
listAppOwnedChildThreadIds: () => Effect.succeed([]),
delegatedTaskResultPending: () => Effect.succeed(false),
stopDelegatedTasks: () => Effect.void,
// The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.andThen(
command.type === "subagent.stop" ? Ref.set(status, "cancelled") : Effect.void,
),
Effect.as({} as never),
),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-orphan"),
requestNamespace: "provider-session:mcp-orphan",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-orphan",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const result = yield* service.cancelTask(scope, {
taskId,
clientRequestId: "cancel-orphan-task",
});
assert.deepEqual(result, { taskId, status: "cancelled" });
const commands = yield* Ref.get(dispatched);
// A child whose run finished can still run another turn's work, so it is stopped too.
assert.deepEqual(
commands.flatMap((command) =>
command.type === "thread.stop" ? [command.threadId] : [],
),
childState === "a finished run" ? [childThreadId] : [],
);
const stop = commands.find((command) => command.type === "subagent.stop");
if (stop?.type !== "subagent.stop") return;
assert.deepEqual(
{ threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId },
{ threadId: parentThreadId, runId: parentRunId, subagentId: taskId },
);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("does not dispose delivery when the child stop fails", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent");
const childThreadId = ThreadId.make("thread:mcp-cancel-failed-child");
const childRunId = RunId.make("run:mcp-cancel-failed-child");
const taskId = NodeId.make("node:mcp-cancel-failed-task");
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
result: null,
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [{ id: childRunId, status: "running" }],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
listAppOwnedChildThreadIds: () => Effect.succeed([]),
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)),
),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-cancel-failed"),
requestNamespace: "provider-session:mcp-cancel-failed",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-cancel-failed",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const error = yield* service
.cancelTask(scope, { taskId, clientRequestId: "cancel-failed-task" })
.pipe(Effect.flip);
assert.equal(error.code, "task_not_cancellable");
assert.deepEqual(
(yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type),
["thread.stop"],
);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("returns cancel requested when post-stop disposal fails", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent");
const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-child");
const childRunId = RunId.make("run:mcp-cancel-dispose-failed-child");
const taskId = NodeId.make("node:mcp-cancel-dispose-failed-task");
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
result: null,
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [{ id: childRunId, status: "running" }],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
listAppOwnedChildThreadIds: () => Effect.succeed([]),
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.andThen(
command.type === "delegated_task.completion-delivery.dispose"
? Effect.fail(new Error("simulated disposal failure") as never)
: Effect.succeed({} as never),
),
),
stopDelegatedTasks: () => Effect.void,
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-failed"),
requestNamespace: "provider-session:mcp-cancel-dispose-failed",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-cancel-dispose-failed",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const result = yield* service.cancelTask(scope, {
taskId,
clientRequestId: "cancel-dispose-failed-task",
});
assert.equal(result.status, "cancel_requested");
assert.deepEqual(
(yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type),
["thread.stop", "delegated_task.completion-delivery.dispose"],
);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
it.effect("refuses to cancel a task whose child now runs above the parent's modes", () =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent");
const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-child");
const childRunId = RunId.make("run:mcp-cancel-dispose-failed-child");
const taskId = NodeId.make("node:mcp-cancel-dispose-failed-task");
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
const parentProjection = {
thread: { id: parentThreadId, runtimeMode: "approval-required", interactionMode: "plan" },
runs: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
origin: "app_owned",
childThreadId,
driver: "codex",
model: "gpt-5.6-terra",
result: null,
completionDelivery: { state: "pending" },
},
],
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [{ id: childRunId, status: "running" }],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
} as unknown as OrchestrationV2ThreadProjection;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId) =>
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
listAppOwnedChildThreadIds: () => Effect.succeed([]),
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.andThen(
command.type === "delegated_task.completion-delivery.dispose"
? Effect.fail(new Error("simulated disposal failure") as never)
: Effect.succeed({} as never),
),
),
stopDelegatedTasks: () => Effect.void,
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-failed"),
requestNamespace: "provider-session:mcp-cancel-dispose-failed",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-cancel-dispose-failed",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const error = yield* service
.cancelTask(scope, { taskId, clientRequestId: "cancel-above-modes" })
.pipe(Effect.flip);
assert.equal(error.code, "runtime_mode_escalation_denied");
assert.deepEqual(yield* Ref.get(dispatched), []);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
const cancelOverRaisedGrandchild = (child: {
readonly deleted: boolean;
readonly raisedDuringStop?: boolean;
}) =>
Effect.gen(function* () {
const parentThreadId = ThreadId.make("thread:mcp-cancel-grandchild-parent");
const childThreadId = ThreadId.make("thread:mcp-cancel-grandchild-child");
const grandchildThreadId = ThreadId.make("thread:mcp-cancel-grandchild-grandchild");
const taskId = NodeId.make("node:mcp-cancel-grandchild-task");
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
const stoppedBelow = yield* Ref.make(false);
const subagentReads = yield* Ref.make<ReadonlyArray<ProjectionRecordFilter | undefined>>([]);
const appOwnedTask = (
id: string,
threadId: ThreadId,
childId: ThreadId,
settled?: "settled",
) => ({
id: NodeId.make(id),
threadId,
origin: "app_owned",
childThreadId: childId,
driver: "codex",
model: "gpt-5.6-terra",
status: settled === undefined ? "running" : "completed",
result: settled === undefined ? null : "Done.",
completionDelivery: { state: settled === undefined ? "pending" : "delivered" },
});
// Older tasks the parent and child dispatched and that have long settled.
const settledThreadId = ThreadId.make("thread:mcp-cancel-grandchild-settled");
const projections = new Map([
[
parentThreadId,
{
thread: {
id: parentThreadId,
runtimeMode: "approval-required",
interactionMode: "default",
},
runs: [],
contextTransfers: [],
subagents: [
appOwnedTask(
"node:mcp-cancel-grandchild-old",
parentThreadId,
settledThreadId,
"settled",
),
appOwnedTask(taskId, parentThreadId, childThreadId),
],
},
],
[
childThreadId,
{
thread: { id: childThreadId, title: "Child" },
runs: [{ id: RunId.make("run:mcp-cancel-grandchild-child"), status: "running" }],
contextTransfers: [],
messages: [],
subagents: [
appOwnedTask(
"node:mcp-cancel-grandchild-done",
childThreadId,
settledThreadId,
"settled",
),
appOwnedTask("node:mcp-cancel-grandchild-below", childThreadId, grandchildThreadId),
],
providerThreads: [],
runtimeRequests: [],
},
],
[
settledThreadId,
{
thread: { id: settledThreadId },
runs: [],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
},
],
[
grandchildThreadId,
{
thread: { id: grandchildThreadId },
runs: [],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
},
],
]) as unknown as ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (threadId, fields, filter) =>
((fields as ReadonlyArray<string>).includes("subagents")
? Ref.update(subagentReads, (reads) => [...reads, filter])
: Effect.void
).pipe(Effect.as(projections.get(threadId)!)),
listAppOwnedChildThreadIds: (threadId) =>
Effect.succeed(
projections
.get(threadId)!
.subagents.flatMap((task) =>
task.origin === "app_owned" && task.childThreadId !== null
? [task.childThreadId]
: [],
),
),
getThreadShell: (threadId) =>
Effect.succeed(
threadId === grandchildThreadId && child.raisedDuringStop !== true
? liveThreadShell(threadId)
: threadId === childThreadId && child.deleted
? null
: liveThreadShell(threadId, { runtimeMode: "approval-required" }),
),
dispatch: (command) =>
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
Effect.as({} as never),
),
stopDelegatedTasks: () =>
Effect.gen(function* () {
const limit = yield* DispatchModeLimit;
if (child.raisedDuringStop === true && limit?.refused !== undefined) {
const refusal: DispatchModeRefusal = {
threadId: grandchildThreadId,
mode: "runtime",
runtimeMode: "full-access",
interactionMode: "default",
};
yield* Ref.set(limit.refused, refusal);
return yield* new OrchestratorThreadAboveModeLimitError({
commandId: CommandId.make("stop-grandchild"),
threadId: grandchildThreadId,
mode: "runtime",
runtimeMode: "full-access",
interactionMode: "default",
});
}
yield* Ref.set(stoppedBelow, true);
}),
}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-cancel-grandchild"),
requestNamespace: "provider-session:mcp-cancel-grandchild",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-cancel-grandchild",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
return yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const error = yield* service
.cancelTask(scope, { taskId, clientRequestId: "cancel-grandchild-above-modes" })
.pipe(Effect.flip);
// No read decodes every task a thread has dispatched.
for (const filter of yield* Ref.get(subagentReads)) {
assert.isTrue(
filter?.subagentIds !== undefined || filter?.omitSettledSubagents !== undefined,
);
}
return {
code: error.code,
dispatched: yield* Ref.get(dispatched),
stoppedBelow: yield* Ref.get(stoppedBelow),
};
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
});
it.effect("refuses to cancel a task when a task under it now runs above the parent's modes", () =>
Effect.gen(function* () {
assert.deepEqual(yield* cancelOverRaisedGrandchild({ deleted: false }), {
code: "runtime_mode_escalation_denied",
dispatched: [],
stoppedBelow: false,
});
}),
);
it.effect("reports a task under the child that its user raises while it is being stopped", () =>
Effect.gen(function* () {
const outcome = yield* cancelOverRaisedGrandchild({ deleted: false, raisedDuringStop: true });
assert.equal(outcome.code, "runtime_mode_escalation_denied");
assert.isFalse(outcome.stoppedBelow);
}),
);
it.effect("checks the tasks under a deleted child before cancelling it", () =>
Effect.gen(function* () {
assert.deepEqual(yield* cancelOverRaisedGrandchild({ deleted: true }), {
code: "runtime_mode_escalation_denied",
dispatched: [],
stoppedBelow: false,
});
}),
);
});
describe("OrchestratorMcpService provider resolution", () => {
const parentThreadId = ThreadId.make("thread:mcp-providers-parent");
const childThreadId = ThreadId.make("thread:mcp-providers-child");
const parentRunId = RunId.make("run:mcp-providers-parent");
const parentNodeId = NodeId.make("node:mcp-providers-root");
const taskId = NodeId.make("node:mcp-providers-task");
const projectId = ProjectId.make("project:mcp-providers");
const codexInstanceId = ProviderInstanceId.make("codex");
const antigravityInstanceId = ProviderInstanceId.make("antigravity");
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:mcp-providers"),
requestNamespace: "provider-session:mcp-providers",
thread: {
threadId: parentThreadId,
providerSessionId: "provider-session:mcp-providers",
providerInstanceId: codexInstanceId,
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
const providerSnapshot = (input: {
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
readonly model?: string;
readonly enabled?: boolean;
}): ServerProvider => ({
instanceId: input.instanceId,
driver: input.driver,
enabled: input.enabled ?? true,
installed: input.enabled !== false,
version: input.enabled === false ? null : "test",
status: input.enabled === false ? "disabled" : "ready",
auth: { status: input.enabled === false ? "unknown" : "authenticated" },
...(input.enabled === false ? { message: "Provider is disabled in T3 Code settings." } : {}),
checkedAt: "2026-09-13T00:00:00.000Z",
models:
input.model === undefined
? []
: [{ slug: input.model, name: input.model, isCustom: false, capabilities: null }],
slashCommands: [],
skills: [],
});
const providerRegistryLayer = (providers: ReadonlyArray<ServerProvider>) =>
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.succeed(providers),
refreshInstance: () => Effect.succeed(providers),
});
const adapterRegistryLayer = (instanceIds: ReadonlyArray<ProviderInstanceId>) =>
Layer.succeed(
ProviderAdapterRegistry.ProviderAdapterRegistryV2,
ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
list: () => Effect.succeed(instanceIds),
get: (instanceId) =>
instanceIds.includes(instanceId)
? Effect.succeed({
instanceId,
} as unknown as ProviderAdapter.ProviderAdapterV2["Service"])
: Effect.fail(
new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
),
}),
);
const parentProjection = (
subagents: ReadonlyArray<unknown>,
modelSelection: {
readonly instanceId: ProviderInstanceId;
readonly model: string;
readonly options?: ReadonlyArray<{ readonly id: string; readonly value: unknown }>;
} = { instanceId: codexInstanceId, model: "gpt-5.4" },
): OrchestrationV2ThreadProjection =>
({
thread: {
id: parentThreadId,
projectId,
title: "MCP parent",
createdBy: "user",
creationSource: "web",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
},
runs: [
{
id: parentRunId,
ordinal: 1,
status: "running",
rootNodeId: parentNodeId,
providerInstanceId: codexInstanceId,
modelSelection,
},
],
contextTransfers: [],
subagents,
}) as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: { id: childThreadId, title: "Child" },
runs: [],
contextTransfers: [],
messages: [],
subagents: [],
providerThreads: [],
runtimeRequests: [],
turnItems: [],
} as unknown as OrchestrationV2ThreadProjection;
it.effect.each([
"parent completion",
"nested child completion",
"child run completion",
"child question",
"child approval",
] as const)("a task wait still returns on %s", (wake) =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
const subscribed = yield* Deferred.make<void>();
const nestedId = NodeId.make("node:mcp-wait-nested");
const childRunId = RunId.make("run:mcp-wait-child");
const childRootId = NodeId.make("node:mcp-wait-child-root");
const eventThreadId = wake === "parent completion" ? parentThreadId : childThreadId;
const eventType =
wake === "child run completion"
? "run.updated"
: wake === "child question" || wake === "child approval"
? "runtime-request.updated"
: "subagent.updated";
const terminal = wake.endsWith("completion");
let ready = false;
const task = () => ({
id: taskId,
threadId: parentThreadId,
runId: parentRunId,
parentNodeId,
origin: "app_owned",
providerInstanceId: codexInstanceId,
driver: "codex",
childThreadId,
model: "gpt-5.4",
status: ready && terminal ? "completed" : "running",
result: ready && wake === "parent completion" ? "done" : null,
});
const child = () =>
({
...childProjection,
runs: [
{
id: childRunId,
ordinal: 1,
status:
wake === "nested child completion" || (ready && terminal) ? "completed" : "running",
startedAt: DateTime.makeUnsafe(0),
completedAt: ready && terminal ? DateTime.makeUnsafe(1) : null,
},
],
subagents:
wake === "nested child completion"
? [{ id: nestedId, status: ready ? "completed" : "running" }]
: [],
nodes: [{ id: childRootId, runId: childRunId }],
runtimeRequests:
ready && !terminal
? [
{
id: "request:mcp-wait-answer",
nodeId: childRootId,
kind: wake === "child question" ? "user_input" : "command",
status: "pending",
responseCapability: { type: "live" },
createdAt: DateTime.makeUnsafe(0),
},
]
: [],
}) as unknown as OrchestrationV2ThreadProjection;
const dependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
hasReceipt: () => Effect.succeed(false),
assertProviderInstanceEnabled: () => Effect.void,
isProviderInstanceEnabledForProject: () => Effect.succeed(true),
getThreadRecords: (threadId) =>
Effect.sync(() => (threadId === parentThreadId ? parentProjection([task()]) : child())),
getThreadEventSequence: () => Effect.succeed(0),
delegatedTaskResultPending: () => Effect.succeed(false),
streamStoredEventsFrom: (input) =>
input?.threadId === eventThreadId && input.eventType === eventType
? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
Stream.drain,
Stream.concat(Stream.fromQueue(events)),
)
: Stream.never,
dispatch: () =>
Effect.succeed({
sequence: 1,
storedEvents: [{ event: { type: "subagent.updated", payload: task() } }],
} as never),
}),
ServerSettings.layerTest(),
providerRegistryLayer([
providerSnapshot({
instanceId: codexInstanceId,
driver: ProviderDriverKind.make("codex"),
model: "gpt-5.4",
}),
]),
adapterRegistryLayer([codexInstanceId]),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const waiting = yield* service
.delegateTask(scope, { task: "Review the change.", mode: "wait" })
.pipe(Effect.forkChild);
yield* Deferred.await(subscribed);
ready = true;
if (wake === "parent completion") {
yield* Queue.offer(events, {
sequence: 2,
event: {
type: "subagent.updated",
threadId: parentThreadId,
payload: { ...task(), id: nestedId },
},
} as unknown as OrchestrationV2StoredEvent);
}
yield* Queue.offer(events, {
sequence: 3,
event: {
type: eventType,
threadId: eventThreadId,
payload: { id: wake === "parent completion" ? taskId : nestedId },
},
} as unknown as OrchestrationV2StoredEvent);
const result = yield* Fiber.join(waiting);
assert.isFalse(result.waitTimedOut);
if (terminal) {
assert.equal(result.status, "completed");
if (wake === "parent completion") assert.equal(result.summary, "done");
} else {
assert.equal(result.status, "running");
if (wake === "child question") assert.isTrue(result.hasPendingQuestion);
else {
assert.deepEqual(result.pendingApproval, {
requestId: "request:mcp-wait-answer",
kind: "command",
runId: childRunId,
});
}
}
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies))));
}),
);
it.effect(
"advertises orchestration capability from registered adapters rather than a driver allowlist",
() =>
Effect.gen(function* () {
const disabledAntigravityInstanceId = ProviderInstanceId.make("antigravity-alt");
const disabledWithoutAdapterInstanceId = ProviderInstanceId.make("codex-without-adapter");
const projectDisabledInstanceId = ProviderInstanceId.make("codex-project-off");
const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly");
const forkShadow = yield* buildUnavailableProviderSnapshot({
driverKind: "forkOnly",
instanceId: forkOnlyInstanceId,
reason: "Driver 'forkOnly' is not registered in this build.",
checkedAt: "2026-09-13T00:00:00.000Z",
});
let providers: ReadonlyArray<ServerProvider> = [
providerSnapshot({
instanceId: codexInstanceId,
driver: ProviderDriverKind.make("codex"),
model: "gpt-5.4",
}),
providerSnapshot({
instanceId: ProviderInstanceId.make("claudeAgent"),
driver: ProviderDriverKind.make("claudeAgent"),
model: "claude-sonnet-4-6",
}),
providerSnapshot({
instanceId: ProviderInstanceId.make("pi"),
driver: ProviderDriverKind.make("pi"),
model: "pi-model",
}),
providerSnapshot({
instanceId: ProviderInstanceId.make("acpRegistry"),
driver: ProviderDriverKind.make("acpRegistry"),
model: "acp-model",
}),
providerSnapshot({
instanceId: antigravityInstanceId,
driver: ProviderDriverKind.make("antigravity"),
model: "ant-model",
}),
providerSnapshot({
instanceId: disabledAntigravityInstanceId,
driver: ProviderDriverKind.make("antigravity"),
model: "ant-model",
enabled: false,
}),
providerSnapshot({
instanceId: disabledWithoutAdapterInstanceId,
driver: ProviderDriverKind.make("codex"),
model: "gpt-5.4",
enabled: false,
}),
providerSnapshot({
instanceId: projectDisabledInstanceId,
driver: ProviderDriverKind.make("codex"),
model: "gpt-5.4",
}),
forkShadow,
];
const layerDependencies = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: () => Effect.succeed(parentProjection([])),
}),
ServerSettings.layerTest({
providerInstances: {
[ProviderInstanceId.make("pi")]: {
driver: ProviderDriverKind.make("pi"),
enabled: true,
},
[ProviderInstanceId.make("acpRegistry")]: {
driver: ProviderDriverKind.make("acpRegistry"),
enabled: true,
},
[antigravityInstanceId]: {
driver: ProviderDriverKind.make("antigravity"),
enabled: true,
},
[projectDisabledInstanceId]: { driver: ProviderDriverKind.make("codex") },
},
projectSettingsOverrides: {
[projectId]: {
providerInstances: { [projectDisabledInstanceId]: { enabled: false } },
},
},
}),
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.sync(() => providers),
}),
adapterRegistryLayer([
codexInstanceId,
projectDisabledInstanceId,
ProviderInstanceId.make("claudeAgent"),
ProviderInstanceId.make("pi"),
ProviderInstanceId.make("acpRegistry"),
antigravityInstanceId,
disabledAntigravityInstanceId,
]),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
);
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
const capabilities = yield* service.capabilities(scope);
const byId = new Map(
capabilities.providers.map((provider) => [provider.providerInstanceId, provider]),
);
for (const provider of providers) {
assert.deepEqual(
byId.get(provider.instanceId)?.models.map((model) => model.id),
provider.models.map((model) => model.slug),
);
}
providers = providers.map((provider) => ({
...provider,
models: [
...provider.models,
{
slug: `${provider.driver}/custom-model-after-refresh`,
name: "Custom model",
isCustom: true,
capabilities: null,
},
],
}));
const refreshed = yield* service.capabilities(scope);
for (const provider of providers) {
assert.deepEqual(
refreshed.providers
.find((entry) => entry.providerInstanceId === provider.instanceId)
?.models.map((model) => model.id),
provider.models.map((model) => model.slug),
);
}
for (const instanceId of [
codexInstanceId,
ProviderInstanceId.make("claudeAgent"),
ProviderInstanceId.make("pi"),
ProviderInstanceId.make("acpRegistry"),
antigravityInstanceId,
]) {
const entry = byId.get(instanceId);
assert.isDefined(entry);
assert.isTrue(
entry!.canRunChildTask,
`expected ${instanceId} to advertise canRunChildTask`,
);
assert.isTrue(entry!.canRunCrossProviderChildTask);
assert.deepEqual(entry!.constraints, []);
}
const disabled = byId.get(disabledAntigravityInstanceId);
assert.isDefined(disabled);
assert.isFalse(disabled!.canRunChildTask);
assert.isFalse(disabled!.canRunCrossProviderChildTask);
assert.deepEqual(disabled!.constraints, ["Provider instance is disabled."]);
const projectDisabled = byId.get(projectDisabledInstanceId);
assert.isDefined(projectDisabled);
assert.isFalse(projectDisabled!.canRunChildTask);
assert.deepEqual(projectDisabled!.constraints, ["Provider instance is disabled."]);
const disabledWithoutAdapter = byId.get(disabledWithoutAdapterInstanceId);
assert.isDefined(disabledWithoutAdapter);
assert.isFalse(disabledWithoutAdapter!.canRunChildTask);
assert.isFalse(disabledWithoutAdapter!.canRunCrossProviderChildTask);
assert.deepEqual(disabledWithoutAdapter!.constraints, [
"No V2 provider adapter is registered.",
"Provider instance is disabled.",
]);
const fork = byId.get(forkOnlyInstanceId);
assert.isDefined(fork);
assert.isFalse(fork!.canRunChildTask);
assert.isFalse(fork!.canRunCrossProviderChildTask);
assert.deepEqual(fork!.constraints, [
"No V2 provider adapter is registered.",
"Driver 'forkOnly' is not registered in this build.",
"Provider instance is disabled.",
]);
}).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
}),
);
describe("listed models", () => {
const opencodeInstanceId = ProviderInstanceId.make("opencode");
const model = (slug: string, extra: Partial<ServerProvider["models"][number]> = {}) => ({
slug,
name: slug,
isCustom: false,
capabilities: null,
...extra,
});
const opencodeSlugs = Array.from(
{ length: 12 },
(_, index) => `oc/m${String(index + 1).padStart(2, "0")}`,
);
const catalog: ReadonlyArray<ServerProvider> = [
{