From 6c57ff4163c9f2047c1d826e449e7300e766a82c Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:59:21 -0700 Subject: [PATCH] refactor(server): compose managed provider policy outside the adapters The MCP session now carries one composed orchestration policy (instruction sections, model roles, native-subagent switch). Codex and Claude only translate it. The managed role comes from IssueEligibility, the propose_issue_change handler moves to RepositoryOrchestrationMcp, and ManagedIssueDelegation takes its thread loader once. The tool description now points at the issue panel instead of the Issues page. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/issues/IssueEligibility.ts | 11 +++ apps/server/src/mcp/ManagedIssueDelegation.ts | 10 +-- .../mcp/OrchestratorMcpService.fork.test.ts | 73 ++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 66 +++----------- .../src/mcp/RepositoryOrchestrationMcp.ts | 23 +++++ .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../Adapters/ClaudeAdapterV2.ts | 24 +++-- .../Adapters/CodexAdapterV2.fork.test.ts | 3 +- .../Adapters/CodexAdapterV2.ts | 16 ++-- .../ProviderSessionManager.fork.test.ts | 50 +++++++++++ .../ProviderSessionManager.ts | 56 ++++++------ .../CodexDeveloperInstructions.fork.test.ts | 4 +- .../provider/CodexDeveloperInstructions.ts | 11 +-- .../provider/ManagedIssueDelegation.test.ts | 87 +++++++++++-------- .../provider-core/src/server/mcpSession.ts | 32 +++---- .../orchestrationInstructions.fork.test.ts | 10 ++- .../src/server/orchestrationInstructions.ts | 26 ++++-- 17 files changed, 320 insertions(+), 184 deletions(-) diff --git a/apps/server/src/issues/IssueEligibility.ts b/apps/server/src/issues/IssueEligibility.ts index fec623ad37445..7318402c15229 100644 --- a/apps/server/src/issues/IssueEligibility.ts +++ b/apps/server/src/issues/IssueEligibility.ts @@ -8,6 +8,7 @@ import { type ProviderDriverKind, type ThreadLinkedIssue, } from "@t3tools/contracts"; +import type { ManagedIssueRole } from "@t3tools/provider-core/server/mcpSession"; export const isReadOnlyIssueRole = (role: string | undefined) => { const resolved = role === undefined ? undefined : resolveThreadRole(role); @@ -36,6 +37,16 @@ export const requiresManagedIssueAdmission = ( parent.linkedIssue !== undefined || root.repositoryOrchestration !== undefined); +/** Linked issue workers and the repository root get managed orchestration instructions. */ +export const managedIssueRole = ( + thread: Pick, +): ManagedIssueRole | undefined => + thread.linkedIssue !== undefined + ? "worker" + : thread.repositoryOrchestration !== undefined + ? "root" + : undefined; + /** Codex and Claude drivers; IssueEligibility.test.ts ties these names to the real drivers. */ export const supportsManagedIssueWork = (driver: ProviderDriverKind) => driver === "codex" || driver === "claudeAgent"; diff --git a/apps/server/src/mcp/ManagedIssueDelegation.ts b/apps/server/src/mcp/ManagedIssueDelegation.ts index bb0f3a12b6fdb..4f5447b835913 100644 --- a/apps/server/src/mcp/ManagedIssueDelegation.ts +++ b/apps/server/src/mcp/ManagedIssueDelegation.ts @@ -18,7 +18,9 @@ import { requiresManagedIssueAdmission, } from "../issues/IssueEligibility.ts"; -export const makeManagedIssueDelegation = Effect.gen(function* () { +export const makeManagedIssueDelegation = Effect.fn("ManagedIssueDelegation.make")(function* ( + loadThread: (id: ThreadId) => Effect.Effect, +) { const issueWork = yield* Effect.serviceOption(IssueWorkService.IssueWorkService); const issueLinks = yield* Effect.serviceOption(IssueLinks.IssueLinks); const issueService = yield* Effect.serviceOption(IssueService.IssueService); @@ -29,13 +31,12 @@ export const makeManagedIssueDelegation = Effect.gen(function* () { const resolveIssue = Effect.fnUntraced(function* ( input: OrchestratorMcpDelegateTaskInput, parent: { readonly thread: OrchestrationV2AppThread }, - loadRoot: (id: ThreadId) => Effect.Effect, ) { const unmanaged = isUnmanagedIssueRole(input.role); const root = unmanaged || parent.thread.lineage.rootThreadId === parent.thread.id ? parent.thread - : yield* loadRoot(parent.thread.lineage.rootThreadId); + : yield* loadThread(parent.thread.lineage.rootThreadId); const managed = requiresManagedIssueAdmission(input.role, parent.thread, root); if (unmanaged && input.issue !== undefined && Option.isNone(issueLinks)) return yield* failure("orchestration_error", "Issue linking is unavailable on this server."); @@ -118,12 +119,11 @@ export const makeManagedIssueDelegation = Effect.gen(function* () { taskResult: OrchestratorMcpDelegateTaskResult, parent: OrchestrationV2AppThread, taskCommand: Extract, - loadRoot: (id: ThreadId) => Effect.Effect, ) { if (taskResult.status !== "queued" || Option.isNone(issueWork)) return taskResult; const root = parent.repositoryOrchestration === undefined - ? yield* loadRoot(parent.lineage.rootThreadId) + ? yield* loadThread(parent.lineage.rootThreadId) : parent; const config = root?.repositoryOrchestration; if (config === undefined) return taskResult; diff --git a/apps/server/src/mcp/OrchestratorMcpService.fork.test.ts b/apps/server/src/mcp/OrchestratorMcpService.fork.test.ts index e06bcf0061ec5..c2866d4c74e84 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.fork.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.fork.test.ts @@ -9,6 +9,7 @@ import { CommandId, DEFAULT_SERVER_SETTINGS, EnvironmentId, + IssueWorkError, NodeId, OrchestratorMcpTarget, ProjectId, @@ -34,6 +35,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as IssueChangeService from "../issues/IssueChangeService.ts"; import * as IssueWorkService from "../issues/IssueWorkService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; @@ -1718,4 +1720,75 @@ describe("OrchestratorMcpService provider resolution", () => { assert.equal(restored.code, "runtime_mode_escalation_denied"); }), ); + + it.effect("refuses issue proposals from an outside client and a retired root's subtree", () => + Effect.gen(function* () { + const retiredThreadId = ThreadId.make("thread:retired-worker"); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + 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(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(IssueWorkService.IssueWorkService)({ + assertCurrentCaller: (threadId) => + threadId === retiredThreadId + ? Effect.fail( + new IssueWorkError({ code: "retired-root", message: "Root retired." }), + ) + : Effect.void, + }), + Layer.mock(IssueChangeService.IssueChangeService)({ + propose: () => Effect.die("A refused caller reached the issue proposal."), + }), + ), + ), + ), + ), + ); + const input = { + host: "github.com", + repository: "acme/app", + clientRequestId: "proposal", + operation: { type: "state", number: 13, state: "closed" }, + } as const; + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:proposal"), + requestNamespace: "client:proposal", + thread: undefined, + client: { sessionId: "proposal", label: "Claude Code", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const outside = yield* mcp.proposeIssueChange(scope, input).pipe(Effect.flip); + const retired = yield* mcp + .proposeIssueChange( + { + ...scope, + client: undefined, + thread: { + threadId: retiredThreadId, + providerSessionId: "retired-session", + providerInstanceId: codexInstanceId, + }, + }, + input, + ) + .pipe(Effect.flip); + assert.deepEqual( + [outside.code, outside.message], + ["invalid_request", "Issue proposals require a managed thread."], + ); + assert.deepEqual([retired.code, retired.message], ["invalid_request", "Root retired."]); + }), + ); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 28c072b934092..1d5e3feaa9407 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -192,10 +192,6 @@ type TerminalTaskStatus = Extract< >; export interface OrchestratorMcpServiceShape extends RepositoryMcpMethods { - readonly proposeIssueChange: ( - scope: McpInvocationScope, - input: import("@t3tools/contracts").IssueChangeProposeInput, - ) => Effect.Effect; readonly capabilities: ( scope: McpInvocationScope, input?: OrchestratorMcpCapabilitiesInput, @@ -1266,7 +1262,12 @@ const make = Effect.gen(function* () { const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const gitDriver = yield* GitVcsDriver.GitVcsDriver; const serverSettings = yield* ServerSettings.ServerSettingsService; - const managedIssueDelegation = yield* makeManagedIssueDelegation; + const loadThreadRow = (threadId: ThreadId) => + threadManagement.getThreadRecords(threadId, []).pipe( + Effect.map((records) => records.thread), + Effect.mapError(threadManagementFailure), + ); + const managedIssueDelegation = yield* makeManagedIssueDelegation(loadThreadRow); const issueWork = yield* Effect.serviceOption(IssueWorkService.IssueWorkService); const issueChanges = yield* Effect.serviceOption(IssueChangeService.IssueChangeService); const remoteDelegation = yield* Effect.serviceOption(RemoteDelegation.RemoteDelegation); @@ -1518,12 +1519,7 @@ const make = Effect.gen(function* () { const loadProviders = providerRegistry.getProviders; const loadUsageSprint = (thread: OrchestrationV2ThreadProjection["thread"]) => - lineageUsageSprint(thread, (threadId) => - threadManagement.getThreadRecords(threadId, []).pipe( - Effect.map((records) => records.thread), - Effect.mapError(threadManagementFailure), - ), - ); + lineageUsageSprint(thread, loadThreadRow); const loadOrchestrationCapableInstanceIds = () => providerAdapters.list().pipe(Effect.map((instanceIds) => new Set(instanceIds))); @@ -2286,27 +2282,14 @@ const make = Effect.gen(function* () { const repositoryMcp = makeRepositoryMcpMethods({ issueWork, + issueChanges, + requireCapability, loadCaller: (scope) => loadCaller(scope, ["runs"]), loadThreadCaller, }); const { assertCurrentRepositoryCaller } = repositoryMcp; return OrchestratorMcpService.of({ - proposeIssueChange: Effect.fn("OrchestratorMcpService.proposeIssueChange")( - function* (scope, input) { - yield* requireCapability(scope); - if (scope.thread === undefined || Option.isNone(issueChanges)) - return yield* failure("invalid_request", "Issue proposals require a managed thread."); - // A retired root's subtree may finish its work but not plan new issue changes. - if (Option.isSome(issueWork)) - yield* issueWork.value - .assertCurrentCaller(scope.thread.threadId) - .pipe(Effect.mapError((error) => failure("invalid_request", error.message))); - return yield* issueChanges.value - .propose(scope.thread.threadId, input) - .pipe(Effect.mapError((error) => failure("invalid_request", error.message))); - }, - ), ...repositoryMcp.methods, scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) { yield* assertCurrentRepositoryCaller(scope); @@ -2759,10 +2742,7 @@ const make = Effect.gen(function* () { if (input.target !== undefined && environmentId !== undefined) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope, "delegate_task"); - const caller = yield* threadManagement.getThreadRecords(scope.thread.threadId, []).pipe( - Effect.map((records) => records.thread), - Effect.mapError(threadManagementFailure), - ); + const caller = yield* loadThreadRow(scope.thread.threadId); // The sprint cannot stop a child that runs on another environment. const sprint = yield* loadUsageSprint(caller); if (sprint !== undefined) @@ -2782,10 +2762,7 @@ const make = Effect.gen(function* () { : readTask(scope, taskId, false, true); } const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); - if (Option.isSome(issueWork)) - yield* issueWork.value - .assertCurrentCaller(parent.thread.id) - .pipe(Effect.mapError((error) => failure("invalid_request", error.message))); + yield* assertCurrentRepositoryCaller(scope); if ( input.target?.projectId !== undefined && input.target.projectId !== parent.thread.projectId @@ -2808,15 +2785,7 @@ const make = Effect.gen(function* () { "Delegated tasks require an active run owned by this MCP provider session.", ); } - const { unmanaged, linkedIssue } = yield* managedIssueDelegation.resolveIssue( - input, - parent, - (id) => - threadManagement.getThreadRecords(id, []).pipe( - Effect.map((records) => records.thread), - Effect.mapError(threadManagementFailure), - ), - ); + const { unmanaged, linkedIssue } = yield* managedIssueDelegation.resolveIssue(input, parent); const providers = yield* loadProviders; const key = yield* requestKey(input.clientRequestId); const commandId = stableCommandId({ @@ -2971,16 +2940,7 @@ const make = Effect.gen(function* () { ? awaitTask(scope, taskId, key, input.timeoutMs) : readTask(scope, taskId, false, true), ); - return yield* managedIssueDelegation.withQueueNote( - taskResult, - parent.thread, - taskCommand, - (id) => - threadManagement.getThreadRecords(id, []).pipe( - Effect.map((records) => records.thread), - Effect.mapError(threadManagementFailure), - ), - ); + return yield* managedIssueDelegation.withQueueNote(taskResult, parent.thread, taskCommand); }), taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) { const scope = yield* requireThreadScope(callerScope, "task_status"); diff --git a/apps/server/src/mcp/RepositoryOrchestrationMcp.ts b/apps/server/src/mcp/RepositoryOrchestrationMcp.ts index b2e3494663922..ada741b84de58 100644 --- a/apps/server/src/mcp/RepositoryOrchestrationMcp.ts +++ b/apps/server/src/mcp/RepositoryOrchestrationMcp.ts @@ -6,10 +6,15 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import type * as IssueChangeService from "../issues/IssueChangeService.ts"; import type * as IssueWorkService from "../issues/IssueWorkService.ts"; import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts"; import { resolveRuntimeMode, resolveInteractionMode } from "./delegatedTaskModes.ts"; export interface RepositoryMcpMethods { + readonly proposeIssueChange: ( + scope: McpInvocationScope, + input: import("@t3tools/contracts").IssueChangeProposeInput, + ) => Effect.Effect; readonly requestRepositoryHandoff: ( scope: McpInvocationScope, input: import("@t3tools/contracts").RepositoryHandoffRequestInput, @@ -62,6 +67,10 @@ export interface RepositoryMcpMethods { interface RepositoryMcpHooks { readonly issueWork: Option.Option; + readonly issueChanges: Option.Option; + readonly requireCapability: ( + scope: McpInvocationScope, + ) => Effect.Effect; readonly loadCaller: (scope: McpInvocationScope) => Effect.Effect< { readonly limits: { @@ -85,6 +94,8 @@ interface RepositoryMcpHooks { export function makeRepositoryMcpMethods({ issueWork, + issueChanges, + requireCapability, loadCaller, loadThreadCaller, }: RepositoryMcpHooks) { @@ -109,6 +120,18 @@ export function makeRepositoryMcpMethods({ }); const methods: RepositoryMcpMethods = { + proposeIssueChange: Effect.fn("OrchestratorMcpService.proposeIssueChange")( + function* (scope, input) { + yield* requireCapability(scope); + if (scope.thread === undefined || Option.isNone(issueChanges)) + return yield* failure("invalid_request", "Issue proposals require a managed thread."); + // A retired root's subtree may finish its work but not plan new issue changes. + yield* assertCurrentRepositoryCaller(scope); + return yield* issueChanges.value + .propose(scope.thread.threadId, input) + .pipe(Effect.mapError((error) => failure("invalid_request", error.message))); + }, + ), requestRepositoryHandoff: Effect.fn("OrchestratorMcpService.requestRepositoryHandoff")( function* (scope, input) { const caller = yield* loadThreadCaller(scope, "request_repository_handoff"); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 0f4f3dc309118..ba7ed521fb93f 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -95,7 +95,7 @@ const threadMetadataDependencies = [ ]; const ProposeIssueChangeTool = Tool.make("propose_issue_change", { description: - "Propose an exact issue change from a repository-managed thread. Create needs title, body and milestoneNumber (null for none); split needs number and issues with those fields. Other operations need number and their action, state, body, milestoneNumber, childNumber or blockerNumber. Use a stable clientRequestId on retries. Create/split and milestone moves execute automatically. Body edits, close/reopen, standalone parent changes, and blocked_by add/remove also execute automatically, unless the requesting thread is in approval-required mode; then they wait for the user's approval on the Issues page. The returned change includes the exact preview, decision and result. Agents cannot approve changes. A conflict needs a new proposal and preview. Labels and assignees are outside this tool's scope.", + "Propose an exact issue change from a repository-managed thread. Create needs title, body and milestoneNumber (null for none); split needs number and issues with those fields. Other operations need number and their action, state, body, milestoneNumber, childNumber or blockerNumber. Use a stable clientRequestId on retries. Create/split and milestone moves execute automatically. Body edits, close/reopen, standalone parent changes, and blocked_by add/remove also execute automatically, unless the requesting thread is in approval-required mode; then they wait for the user's approval in the issue panel. The returned change includes the exact preview, decision and result. Agents cannot approve changes. A conflict needs a new proposal and preview. Labels and assignees are outside this tool's scope.", parameters: IssueChangeProposeInput, success: IssueChange, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f8e80380c2bcb..dbddf65c5757b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -124,7 +124,6 @@ import { type OrchestrationV2WorkflowRunHandles, type OrchestrationV2TurnItem, type OrchestrationV2WebSearchResult, - type OrchestratorMcpModelRole, type ProviderApprovalDecision, type ProviderApprovalFullAccessOverride, type ProviderApprovalOption, @@ -219,7 +218,7 @@ import { type ClaudeScopedLimitNames, } from "../../provider/claudeUsageLimits.ts"; import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot"; -import { t3OrchestrationInstructions } from "@t3tools/provider-core/server/orchestrationInstructions"; +import { t3OrchestrationText } from "@t3tools/provider-core/server/orchestrationInstructions"; import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH } from "@t3tools/provider-core/server/orchestrationInstructions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import { @@ -2183,8 +2182,7 @@ export function makeClaudeQueryOptions(input: { readonly sdkSettings?: string | ClaudeSdkSettings; readonly environment?: NodeJS.ProcessEnv; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; - readonly modelRoles?: ReadonlyArray; - readonly managedIssue?: McpProviderSession.ManagedIssueRole; + readonly orchestration?: McpProviderSession.McpOrchestrationPolicy; /** The thread's T3 MCP session holds the `device` capability. */ readonly deviceToolsAvailable?: boolean; readonly tools?: ClaudeAgentSdkQueryTools; @@ -2340,7 +2338,7 @@ export function makeClaudeQueryOptions(input: { buildRuntimeInstructions({ harness: "Claude Code" }) + (input.mcpServers === undefined ? "" - : t3OrchestrationInstructions(input.modelRoles, input.managedIssue) + + : t3OrchestrationText(input.orchestration) + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS + CLAUDE_SEND_TO_USER_INSTRUCTIONS + (deviceInstructions @@ -2491,7 +2489,7 @@ export function claudeMcpQueryOverrides(input: { }): { readonly allowedTools?: ReadonlyArray; readonly disallowedTools?: ReadonlyArray; - readonly managedIssue?: McpProviderSession.ManagedIssueRole; + readonly orchestration?: McpProviderSession.McpOrchestrationPolicy; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; } { const session = input.mcpSession; @@ -2503,8 +2501,8 @@ export function claudeMcpQueryOverrides(input: { : [CLAUDE_T3_MCP_TOOL_WILDCARD]; return { allowedTools: Array.from(new Set([...(input.allowedTools ?? []), ...mcpAllowedTools])), - ...(session.managedIssue === undefined ? {} : { managedIssue: session.managedIssue }), - ...(session.managedIssue === "worker" + ...(session.orchestration === undefined ? {} : { orchestration: session.orchestration }), + ...(session.orchestration?.nativeSubagents === false ? { disallowedTools: ["Agent", "Task", "TeamCreate"] } : {}), mcpServers: { @@ -3561,7 +3559,7 @@ export function claudeEffectiveQueryPolicyKey( mcpOverrides: { readonly allowedTools?: ReadonlyArray; readonly disallowedTools?: ReadonlyArray; - readonly managedIssue?: McpProviderSession.ManagedIssueRole; + readonly orchestration?: McpProviderSession.McpOrchestrationPolicy; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; }, ): string { @@ -3574,7 +3572,8 @@ export function claudeEffectiveQueryPolicyKey( }), mcpServers: mcpOverrides.mcpServers, disallowedTools: mcpOverrides.disallowedTools, - managedIssue: mcpOverrides.managedIssue, + // The system prompt is fixed for a live query; model roles alone do not restart it. + orchestration: mcpOverrides.orchestration?.sections, }); } @@ -13162,10 +13161,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ...(mcpOverrides.disallowedTools === undefined ? {} : { disallowedTools: mcpOverrides.disallowedTools }), - ...(mcpOverrides.managedIssue === undefined + ...(mcpOverrides.orchestration === undefined ? {} - : { managedIssue: mcpOverrides.managedIssue }), - modelRoles: (yield* mcpSessions.read(turnInput.threadId))?.modelRoles ?? [], + : { orchestration: mcpOverrides.orchestration }), deviceToolsAvailable: mcpSession?.capabilities?.has("device") === true, permissionMode: queryPolicy.permissionMode, ...(queryPolicy.allowDangerouslySkipPermissions === undefined diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.fork.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.fork.test.ts index 94133728a1dcd..3841b32f0235a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.fork.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.fork.test.ts @@ -38,6 +38,7 @@ import { TestClock } from "effect/testing"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { t3OrchestrationPolicy } from "@t3tools/provider-core/server/orchestrationInstructions"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; @@ -256,7 +257,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { endpoint: "http://127.0.0.1:43123/mcp", authorizationHeader: "Bearer test-token", browserToolsAvailable: false, - managedIssue: role, + orchestration: t3OrchestrationPolicy(role, ""), }); const requests: Array = []; const entries = codexReplayPreamble({ diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 7428204e9e6d9..1d2fe9f25fe3e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -64,7 +64,6 @@ import type { OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, ModelSelection, - OrchestratorMcpModelRole, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderFailure, @@ -842,8 +841,7 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur readonly hasT3Mcp?: boolean; readonly browserToolsAvailable?: boolean; readonly deviceToolsAvailable?: boolean; - readonly modelRoles?: ReadonlyArray; - readonly managedIssue?: McpProviderSession.ManagedIssueRole; + readonly orchestration?: McpProviderSession.McpOrchestrationPolicy; /** ChatGPT token sharing does not accept service tiers. */ readonly omitServiceTier?: boolean; readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"]; @@ -893,8 +891,7 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur browser: input.browserToolsAvailable ?? true, device: input.deviceToolsAvailable ?? false, }, - input.modelRoles, - input.managedIssue, + input.orchestration, ) : undefined; const additionalContext = @@ -1573,7 +1570,7 @@ function codexThreadRuntimeParams(input: { ...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }), config: { ...CODEX_THREAD_CONFIG, - ...(mcpSession?.managedIssue === "worker" + ...(mcpSession?.orchestration?.nativeSubagents === false ? { "features.multi_agent": false, "features.multi_agent_v2": false } : {}), // One app-server serves many threads, so the id goes in per-thread shell config, not its env. @@ -7817,12 +7814,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( hasT3Mcp: mcpSession !== undefined, browserToolsAvailable: mcpSession?.browserToolsAvailable ?? true, deviceToolsAvailable: mcpSession?.capabilities?.has("device") ?? false, - ...(mcpSession?.managedIssue === undefined + ...(mcpSession?.orchestration === undefined ? {} - : { managedIssue: mcpSession.managedIssue }), - ...(mcpSession?.modelRoles === undefined - ? {} - : { modelRoles: mcpSession.modelRoles }), + : { orchestration: mcpSession.orchestration }), omitServiceTier: adapterOptions.resolveRuntime !== undefined, ...(turnInput.appContext === undefined ? {} : { appContext: turnInput.appContext }), ...(configuredReasoningSummary === undefined ? {} : { configuredReasoningSummary }), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.fork.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.fork.test.ts index da67a60e44ba0..d5096d9388cda 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.fork.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.fork.test.ts @@ -1564,6 +1564,56 @@ it.effect.each([0, 1] as const)( }), ); +it.effect.each(["worker", "ordinary"] as const)( + "ProviderSessionManagerV2 gives a %s thread's MCP session its orchestration policy", + (kind) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const mcpConfigs = yield* Ref.make< + ReadonlyArray + >([]); + yield* Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const allocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make(`thread-orchestration-policy-${kind}`); + const providerSessionId = yield* allocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const created = yield* makeThreadCreatedEvent({ + idAllocator: allocator, + threadId, + now: yield* DateTime.now, + }); + const linkedIssue = { + host: "github.com", + repository: "acme/app", + repositoryId: "repo", + id: "13", + nodeId: "I_13", + number: 13, + title: "Managed", + url: "https://github.com/acme/app/issues/13", + }; + yield* sink.write({ + events: [ + kind === "worker" + ? { ...created, payload: { ...created.payload, linkedIssue } } + : created, + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + const orchestration = (yield* Ref.get(mcpConfigs)).at(-1)?.orchestration; + assert.equal(orchestration?.nativeSubagents, kind !== "worker"); + assert.equal( + orchestration?.sections[0]?.startsWith("Keep issues current"), + kind === "worker", + ); + }).pipe(Effect.provide(layerTest({ state, mcpConfigs }))); + }), +); + it.effect("ProviderSessionManagerV2 unloads only old finished native children once", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 0d555965fa68e..43272c562e44f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -56,6 +56,11 @@ import * as ServerSettings from "../serverSettings.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import { modelRoleStatuses } from "../mcp/delegateTaskTarget.ts"; import { lineageUsageSprint } from "../issues/usageSprint.ts"; +import { managedIssueRole } from "../issues/IssueEligibility.ts"; +import { + t3ModelRolesInstructions, + t3OrchestrationPolicy, +} from "@t3tools/provider-core/server/orchestrationInstructions"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as EventSink from "./EventSink.ts"; import * as CommandOutputHub from "./CommandOutputHub.ts"; @@ -570,31 +575,32 @@ export const layerWithOptions = ( function* (threadId: ThreadId) { if ((yield* mcpSessions.read(threadId)) === undefined) return; const thread = yield* projectionStore.getThread(threadId); - const managedIssue = - thread.linkedIssue !== undefined - ? "worker" - : thread.repositoryOrchestration !== undefined - ? "root" - : undefined; - const withIssue = yield* mcpSessions.read(threadId); - if (withIssue !== undefined) yield* mcpSessions.set({ ...withIssue, managedIssue }); - if (Option.isNone(serverSettings)) return; - const settings = yield* serverSettings.value.getSettings; - const providers = Option.isSome(providerRegistry) - ? yield* providerRegistry.value.getProviders - : []; - const capableInstanceIds = new Set(yield* registry.list()); - const now = yield* Clock.currentTimeMillis; - const modelRoles = modelRoleStatuses( - settings.modelRoles, - providers, - capableInstanceIds, - now, - settings.workerProvider, - yield* lineageUsageSprint(thread, projectionStore.getThread), - ); - const withRoles = yield* mcpSessions.read(threadId); - if (withRoles !== undefined) yield* mcpSessions.set({ ...withRoles, modelRoles }); + const modelRoles = yield* Effect.gen(function* () { + if (Option.isNone(serverSettings)) return ""; + const settings = yield* serverSettings.value.getSettings; + const providers = Option.isSome(providerRegistry) + ? yield* providerRegistry.value.getProviders + : []; + return t3ModelRolesInstructions( + modelRoleStatuses( + settings.modelRoles, + providers, + new Set(yield* registry.list()), + yield* Clock.currentTimeMillis, + settings.workerProvider, + yield* lineageUsageSprint(thread, projectionStore.getThread), + ), + ); + }).pipe(Effect.option); + const session = yield* mcpSessions.read(threadId); + if (session === undefined) return; + yield* mcpSessions.set({ + ...session, + orchestration: t3OrchestrationPolicy( + managedIssueRole(thread), + Option.getOrElse(modelRoles, () => session.orchestration?.modelRoles ?? ""), + ), + }); }, (effect) => effect.pipe(Effect.ignore), ); diff --git a/apps/server/src/provider/CodexDeveloperInstructions.fork.test.ts b/apps/server/src/provider/CodexDeveloperInstructions.fork.test.ts index 30984cdc0383f..5e80854c62132 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.fork.test.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.fork.test.ts @@ -1,5 +1,6 @@ import * as NodeAssert from "node:assert/strict"; +import { t3OrchestrationPolicy } from "@t3tools/provider-core/server/orchestrationInstructions"; import { describe, it } from "vite-plus/test"; import { @@ -15,8 +16,7 @@ describe("buildCodexAdditionalContext", () => { const context = buildCodexAdditionalContext( { model: "gpt-5.3-codex", reasoningEffort: "high" }, false, - [], - role, + t3OrchestrationPolicy(role, ""), ); const first = context.t3_code_orchestration_01?.value ?? ""; const orchestration = Object.entries(context) diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 8b6d05e1657fc..afbf6161a8478 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -1,12 +1,10 @@ -import type { OrchestratorMcpModelRole } from "@t3tools/contracts"; import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema"; -import type { ManagedIssueRole } from "@t3tools/provider-core/server/mcpSession"; +import type { McpOrchestrationPolicy } from "@t3tools/provider-core/server/mcpSession"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import { T3_CODE_BROWSER_TOOL_INSTRUCTIONS, t3OrchestrationSections, - t3ModelRolesInstructions, T3_CODE_DEVICE_TOOL_INSTRUCTIONS, } from "@t3tools/provider-core/server/orchestrationInstructions"; @@ -44,12 +42,11 @@ export interface CodexRuntimeInfo { export function buildCodexAdditionalContext( runtime: CodexRuntimeInfo, toolsAvailable: boolean | T3CodeToolAvailability = true, - modelRoles: ReadonlyArray = [], - managedIssue?: ManagedIssueRole, + orchestration?: McpOrchestrationPolicy, ): Record { const tools = toolInstructions(toolsAvailable); - const roles = t3ModelRolesInstructions(modelRoles).trim(); - const orchestrationSections = t3OrchestrationSections(managedIssue); + const roles = orchestration?.modelRoles.trim(); + const orchestrationSections = orchestration?.sections ?? t3OrchestrationSections(); // Split values to fit per-entry caps; number keys because Codex emits them in key order. return { ...Object.fromEntries( diff --git a/apps/server/src/provider/ManagedIssueDelegation.test.ts b/apps/server/src/provider/ManagedIssueDelegation.test.ts index fcb0428da598f..cd781e676ecfa 100644 --- a/apps/server/src/provider/ManagedIssueDelegation.test.ts +++ b/apps/server/src/provider/ManagedIssueDelegation.test.ts @@ -1,5 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { t3OrchestrationPolicy } from "@t3tools/provider-core/server/orchestrationInstructions"; import { claudeEffectiveQueryPolicyKey, @@ -8,32 +9,30 @@ import { makeClaudeQueryOptions, } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +const session = { + environmentId: EnvironmentId.make("managed-environment"), + threadId: ThreadId.make("managed-claude"), + providerSessionId: "managed-session", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer test-token", + browserToolsAvailable: false, +}; +const policy = claudeRuntimeQueryPolicyForRuntimePolicy({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); +const overrides = (orchestration?: ReturnType) => + claudeMcpQueryOverrides({ + mcpSession: orchestration === undefined ? session : { ...session, orchestration }, + readOnlySandbox: false, + }); + describe("repository-managed Claude delegation", () => { it("removes Claude spawning tools in bypass mode and changes the live-query reuse key", () => { - const threadId = ThreadId.make("managed-claude"); - const session = { - environmentId: EnvironmentId.make("managed-environment"), - threadId, - providerSessionId: "managed-session", - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer test-token", - browserToolsAvailable: false, - }; - const ordinary = claudeMcpQueryOverrides({ mcpSession: session, readOnlySandbox: false }); - const managed = claudeMcpQueryOverrides({ - mcpSession: { ...session, managedIssue: "worker" }, - readOnlySandbox: false, - }); - const policy = claudeRuntimeQueryPolicyForRuntimePolicy({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - }); - assert.notEqual( - claudeEffectiveQueryPolicyKey(policy, ordinary), - claudeEffectiveQueryPolicyKey(policy, managed), - ); + const ordinary = overrides(); + const managed = overrides(t3OrchestrationPolicy("worker", "")); const options = makeClaudeQueryOptions({ modelSelection: { instanceId: session.providerInstanceId, model: "claude-sonnet-5-5" }, nativeThreadId: "managed-native-claude", @@ -46,23 +45,35 @@ describe("repository-managed Claude delegation", () => { assert.deepEqual(options.disallowedTools, ["Agent", "Task", "TeamCreate"]); assert.include(options.allowedTools ?? [], "mcp__t3-code__*"); assert.isUndefined(ordinary.disallowedTools); + const append = + typeof options.systemPrompt === "object" && "append" in options.systemPrompt + ? options.systemPrompt.append + : ""; + // The managed block is its own paragraph after the runtime block. + assert.include(append, "\n\nKeep issues current"); + assert.include(append, "Native subagent tools are disabled"); + }); + + it("restarts a live query on a role change but not on a model-roles refresh", () => { + const keys = [ + overrides(), + overrides(t3OrchestrationPolicy(undefined, "")), + overrides(t3OrchestrationPolicy("root", "")), + overrides(t3OrchestrationPolicy("worker", "")), + ].map((mcpOverrides) => claudeEffectiveQueryPolicyKey(policy, mcpOverrides)); + assert.equal(new Set(keys.slice(1)).size, 3); + assert.equal( + claudeEffectiveQueryPolicyKey( + policy, + overrides(t3OrchestrationPolicy("worker", "\n\n### Model roles\n- Sprinter\n")), + ), + keys[3], + ); }); it("keeps native subagents for the repository root's own work", () => { - const root = claudeMcpQueryOverrides({ - mcpSession: { - environmentId: EnvironmentId.make("managed-environment"), - threadId: ThreadId.make("repository-root"), - providerSessionId: "root-session", - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer test-token", - browserToolsAvailable: false, - managedIssue: "root", - }, - readOnlySandbox: false, - }); + const root = overrides(t3OrchestrationPolicy("root", "")); assert.isUndefined(root.disallowedTools); - assert.equal(root.managedIssue, "root"); + assert.isTrue(root.orchestration?.nativeSubagents); }); }); diff --git a/packages/provider-core/src/server/mcpSession.ts b/packages/provider-core/src/server/mcpSession.ts index e82b9af7abcac..dc165150d4cbd 100644 --- a/packages/provider-core/src/server/mcpSession.ts +++ b/packages/provider-core/src/server/mcpSession.ts @@ -1,12 +1,17 @@ -import type { - EnvironmentId, - OrchestratorMcpModelRole, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; +import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import type * as Effect from "effect/Effect"; export type ManagedIssueRole = "root" | "worker"; -import type * as Effect from "effect/Effect"; + +/** Composed outside the adapters by `t3OrchestrationPolicy`; adapters only translate it. */ +export interface McpOrchestrationPolicy { + /** Instruction sections in order, each within Codex's per-entry context cap. */ + readonly sections: ReadonlyArray; + /** The user's model roles block, refreshed before each turn; empty when there are none. */ + readonly modelRoles: string; + /** False for issue workers, which must delegate through T3. */ + readonly nativeSubagents: boolean; +} /** * Sent by MCP clients that cannot defer tools themselves. The T3 MCP server then * lists only a core set plus `tool_search`, which lists the rest on demand. @@ -24,17 +29,8 @@ export interface McpProviderSessionConfig { readonly browserToolsAvailable: boolean; readonly capabilities?: ReadonlySet; readonly agentDeviceEnvironment?: Readonly>; - /** - * The user's model roles with their current availability, refreshed when - * the session is prepared and before each turn. Adapters render them into - * the orchestration instructions. - */ - readonly modelRoles?: ReadonlyArray; - /** - * Issue workers must delegate through T3. The repository root keeps native - * subagents for its own work between orchestration runs. - */ - readonly managedIssue?: ManagedIssueRole | undefined; + /** Refreshed when the session is prepared and before each turn. */ + readonly orchestration?: McpOrchestrationPolicy; /** True while a delegated task this thread started will wake it with its result. */ readonly hasPendingWake?: Effect.Effect; } diff --git a/packages/provider-core/src/server/orchestrationInstructions.fork.test.ts b/packages/provider-core/src/server/orchestrationInstructions.fork.test.ts index 6af02627bea17..3070aacd21dad 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.fork.test.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.fork.test.ts @@ -17,7 +17,8 @@ import { MAX_MODEL_ROLES_INSTRUCTIONS_LENGTH, T3_CODE_ORCHESTRATION_INSTRUCTIONS, t3ModelRolesInstructions, - t3OrchestrationInstructions, + t3OrchestrationPolicy, + t3OrchestrationText, } from "./orchestrationInstructions.ts"; const decodeModelRoles = Schema.decodeUnknownSync(ModelRoles); @@ -87,8 +88,11 @@ describe("T3 orchestration provider instructions", () => { DEFAULT_MODEL_ROLES.length, ); assert.isAtMost(text.length, MAX_MODEL_ROLES_INSTRUCTIONS_LENGTH); - assert.equal(t3OrchestrationInstructions(roles), T3_CODE_ORCHESTRATION_INSTRUCTIONS + text); - assert.equal(t3OrchestrationInstructions([]), T3_CODE_ORCHESTRATION_INSTRUCTIONS); + assert.equal( + t3OrchestrationText(t3OrchestrationPolicy(undefined, text)), + T3_CODE_ORCHESTRATION_INSTRUCTIONS + text, + ); + assert.equal(t3OrchestrationText(undefined), T3_CODE_ORCHESTRATION_INSTRUCTIONS); }); it("keeps an available alternative when an earlier choice is unavailable", () => { diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 6e437d3fe2f49..630822a2fa07f 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -1,6 +1,6 @@ import type { OrchestratorMcpModelRole, ProviderInteractionMode } from "@t3tools/contracts"; -import type { ManagedIssueRole } from "./mcpSession.ts"; +import type { ManagedIssueRole, McpOrchestrationPolicy } from "./mcpSession.ts"; // Codex truncates entries over 4,000 bytes; keep each section self-contained and below that limit. const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = [ @@ -98,12 +98,24 @@ export function t3ModelRolesInstructions(roles: ReadonlyArray = [], - managedIssue?: ManagedIssueRole, -): string { - return `${t3OrchestrationBaseInstructions(managedIssue)}${t3ModelRolesInstructions(roles)}`; +/** The one place a managed role decides a session's instructions and native subagents. */ +export function t3OrchestrationPolicy( + managedIssue: ManagedIssueRole | undefined, + modelRoles: string, +): McpOrchestrationPolicy { + return { + sections: t3OrchestrationSections(managedIssue), + modelRoles, + // The repository root keeps native subagents for its own work between orchestration runs. + nativeSubagents: managedIssue !== "worker", + }; +} + +/** Orchestration instructions as one block, followed by the user's model roles. */ +export function t3OrchestrationText(policy: McpOrchestrationPolicy | undefined): string { + return policy === undefined + ? T3_CODE_ORCHESTRATION_INSTRUCTIONS + : `\n\n${policy.sections.join("\n\n")}\n${policy.modelRoles}`; } /** Managed issue work has one durable delegation path, including same-provider children. */