diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 3115d776ba4d8..09d2499a0ec0b 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -36,6 +36,7 @@ import { assertLiveCaller, assertTargetWithinLimits, type Caller, + limitsForOwnChild, loadCaller, readCaller, unavailable, @@ -204,25 +205,38 @@ export const writesWithCapability = (handle: (params: P) => Effect.E export const writesThreads = ( threads: (params: P) => ReadonlyArray, handle: (params: P) => Effect.Effect, + /** `ownChildren` lets a thread reach a child it delegated that runs above its runtime mode. */ + options?: { readonly ownChildren?: "at-their-runtime-mode" }, ) => declare( (params: P) => Effect.gen(function* () { const caller = yield* writingCaller; + let dispatchLimits = caller.limits; for (const threadId of threads(params)) { if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue; const target = yield* caller.threads .getThreadShell(threadId) .pipe(Effect.mapError(unavailable)); if (target !== null && target.deletedAt === null) { - yield* assertTargetWithinLimits(caller.limits, target); + const limits = + options?.ownChildren === undefined + ? caller.limits + : yield* limitsForOwnChild( + caller.threads, + caller.caller?.id, + caller.limits, + target, + ); + yield* assertTargetWithinLimits(limits, target); + if (limits !== caller.limits) dispatchLimits = limits; yield* assertSameLink(caller, target); } } // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors. const refused = yield* Ref.make(undefined); return yield* handle(params).pipe( - Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }), + Effect.provideService(DispatchModeLimit, { ...dispatchLimits, refused }), Effect.catch((error) => Effect.flatMap(Ref.get(refused), (refusal) => Effect.fail( diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index f387f481e24a6..706f6e8f6b599 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -5,6 +5,7 @@ import type { import { CommandId, type EnvironmentId, + isRuntimeModeAbove, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -187,6 +188,29 @@ export const assertTargetWithinLimits = ( ), ); +/** + * A thread acts on a child it delegated at the runtime mode that child already has, so it can + * move the child to another account and resume it after its own mode was lowered. + */ +export const limitsForOwnChild = Effect.fn("mcp.limitsForOwnChild")(function* ( + threads: Pick, + callerThreadId: ThreadId | undefined, + limits: CallerLimits, + target: Pick, +) { + if ( + callerThreadId === undefined || + !isRuntimeModeAbove(target.runtimeMode, limits.runtimeMode) || + target.lineage.parentThreadId !== callerThreadId || + target.lineage.relationshipToParent !== "subagent" + ) + return limits; + const delegated = yield* threads + .listAppOwnedChildThreadIds(callerThreadId) + .pipe(Effect.mapError(unavailable)); + return delegated.includes(target.id) ? { ...limits, runtimeMode: target.runtimeMode } : limits; +}); + /** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */ export const isLiveCallerShell = ( shell: Pick< @@ -275,7 +299,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* < : unavailable(), ), ); - return { ...context, projection }; + return { ...context, shell, projection }; }); export const newCommandId = Effect.fn("mcp.newCommandId")(function* () { diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index bdd48dda82817..f6fa527658abc 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -44,6 +44,7 @@ import { import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; import * as ServerConfig from "../../config.ts"; +import { DispatchModeLimit } from "../../orchestration-v2/DispatchModeLimit.ts"; import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; @@ -1331,6 +1332,88 @@ it.effect( ), ); +it.effect.each([ + ["default", "idle", true, "provider.switch full-access/default"], + ["default", "usage-limited", true, "message.dispatch run:limited full-access/default"], + ["default", "idle", false, "runtime_mode_escalation_denied"], + ["plan", "idle", true, "interaction_mode_escalation_denied"], +] as const)( + "t3_thread_configure from an Auto/%s parent moving its %s Full-access child (delegated: %s) gives %s", + ([interactionMode, childState, delegated, expected]) => { + const childId = ThreadId.make("mcp-core-own-child"); + const parent = McpToolAccessTestkit.liveThreadShell(threadId, { + runtimeMode: "auto", + interactionMode, + }); + const child = { + ...McpToolAccessTestkit.liveThreadShell(childId), + ...(childState === "usage-limited" + ? { + status: "failed" as const, + activeRunId: null, + latestRunId: RunId.make("run:limited"), + lastErrorClass: "usage_limit" as const, + } + : {}), + lineage: { + rootThreadId: threadId, + parentThreadId: threadId, + relationshipToParent: "subagent" as const, + }, + }; + let dispatched: string | undefined; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const result = yield* server + .callTool({ + name: "t3_thread_configure", + arguments: { + threadId: childId, + modelSelection: { instanceId: "codex-b", model: "gpt-5" }, + }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(declaredFailure(result)?.code ?? dispatched).toBe(expected); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(id === childId ? child : parent), + getProjectThreadRecords: () => + Effect.succeed(McpToolAccessTestkit.idleThreadProjection(child) as never), + listAppOwnedChildThreadIds: () => Effect.succeed(delegated ? [childId] : []), + // Records the command and the limit the orchestrator rechecks it against under its lock. + dispatch: (command) => + DispatchModeLimit.pipe( + Effect.map((limit) => { + const resumes = + command.type === "message.dispatch" ? command.manualContinuationOfRunId : ""; + dispatched = [ + command.type, + resumes, + `${limit?.runtimeMode}/${limit?.interactionMode}`, + ] + .filter(Boolean) + .join(" "); + return { sequence: 1, storedEvents: [] }; + }), + ), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(NodeCrypto.layer), + ), + ), + ); + }, +); + it.effect("discovers workflow stop targets and requires orchestration capability", () => { const threadId = ThreadId.make("workflow-parent"); const shell = McpToolAccessTestkit.liveThreadShell(threadId); diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 190cbe3eac2b1..cc99411f08ffb 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -1,5 +1,6 @@ import { type CommandId, + MessageId, type RuntimeRequestId, ThreadId, type OrchestrationV2ThreadProjection, @@ -106,6 +107,12 @@ const required = (value: A | undefined, name: string) => const writesThread =

( handle: (params: P) => Effect.Effect, ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle); +const writesOwnChildThread =

( + handle: (params: P) => Effect.Effect, +) => + McpToolAccess.writesThreads((params: P) => [params.threadId], handle, { + ownChildren: "at-their-runtime-mode", + }); export const layer = McpToolAccess.toLayer(ThreadToolkit, { run_scheduled_task_now: McpToolAccess.writesEnvironment((input) => @@ -230,16 +237,41 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { }; }), ), - writesThread((input) => + writesOwnChildThread((input) => Effect.gen(function* () { const modelSelection = yield* required(input.modelSelection, "modelSelection"); - const { - threads, - projection: { thread }, - } = yield* readThread(input.threadId); - const type = modelSelectionCommandType(thread.providerInstanceId, modelSelection); + const { threads, shell } = yield* readThread(input.threadId); + const commandId = yield* newCommandId(); + // A thread a usage limit stopped resumes on the instance it moves to, as the clients' Resume does. + const limitedRunId = + shell.status === "failed" && + shell.lastErrorClass === "usage_limit" && + modelSelection.instanceId !== shell.providerInstanceId + ? shell.latestRunId + : null; const result = yield* threads - .dispatch({ type, threadId: thread.id, commandId: yield* newCommandId(), modelSelection }) + .dispatch( + limitedRunId === null + ? { + type: modelSelectionCommandType(shell.providerInstanceId, modelSelection), + threadId: shell.id, + commandId, + modelSelection, + } + : { + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId, + threadId: shell.id, + messageId: MessageId.make(commandId), + text: "Continue where you left off.", + attachments: [], + modelSelection, + manualContinuationOfRunId: limitedRunId, + dispatchMode: { type: "start_immediately" }, + }, + ) .pipe(Effect.mapError(dispatchFailure)); return { sequence: result.sequence }; }),