Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧬 fix: Default Subagents to Their Parent's Code Machine and Workspace (#16756)
Danny Avilac23fbc8f7725
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.jsindex 25a2ef800d..3aa48850fe 100644--- a/api/app/clients/tools/util/handleTools.js+++ b/api/app/clients/tools/util/handleTools.js@@ -394,6 +394,7 @@ const loadTools = async ({conversation: options.req?.resolvedConversation,request: options.req?.body,}),+ inheritedEnvironments: options.req?.codeWorkspaceInheritance,environments:options.req?.config?.endpoints?.agents?.statefulCodeSessions?.environments,userId: user,diff --git a/api/server/routes/config.js b/api/server/routes/config.jsindex f8633443b9..fd0adb57ae 100644--- a/api/server/routes/config.js+++ b/api/server/routes/config.js@@ -20,6 +20,7 @@ const {buildPreLoginInterface,resolveMaxPasskeysPerUser,resolveCodeEnvironmentMoveCapabilities,+ resolveCodeWorkspaceInheritanceCapability,resolveCodeEnvironmentTransitionVersion,loadConversationListLimits,} = require('@librechat/api');@@ -342,6 +343,7 @@ router.get('/', async function (req, res) {appConfig?.mcpAppSandbox?.operationLimits,),...codeEnvironmentMoveCapabilities,+ ...resolveCodeWorkspaceInheritanceCapability(process.env.CODE_ENVIRONMENT_DECISION_VERSION),...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),...(cloudFront ? { cloudFront } : {}),...(rum ? { rum } : {}),diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 01269a99b9..b4a4e03d73 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -24,11 +24,15 @@ const {buildAgentContextAttachmentsByAgentId,collectCodeExecutionProfileRoutes,getLazySubagentConfigId,+ createViewableSubagentLoader,resolveCodeExecutionContext,resolveCodeExecutionWorkspaceSelections,optsOutOfAttachedCodeEnvironment,isImplicitStatefulCodeRouteAvailable,resolveCodeExecutionWorkspaceContext,+ resolveSubagentCodeWorkspaceInheritance,+ resolveSubagentCodeAvailability,+ guardUnavailableSubagent,createStatefulCodeEnvironmentPolicyError,buildSubagentThreadTaskConfig,backgroundCompletionWakeupsEnabled,@@ -1161,33 +1165,38 @@ const initializeClientWithProvider = async ({) {throw createStatefulCodeEnvironmentPolicyError(statefulCodeEnvironment);}- const baseCodeExecutionContext = lazyCodeEnvAvailable- ? resolveCodeExecutionContext({- statefulSessions: statefulCodeSessions,- environment: statefulCodeEnvironment,- environmentId: agent.code_environment_id,- environmentIds: agent.code_environment_ids,- allowEnvironmentSelection:- appConfig.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,- workspaceSelections: resolveCodeExecutionWorkspaceSelections({- conversation: admittedConversation,- request: runtimeRequestBody,+ const codeAvailability = await resolveSubagentCodeAvailability({+ agentId: agent.id,+ codeEnvAvailable: lazyCodeEnvAvailable,+ statefulCodeSessions,+ resolveContext: async () => {+ if (!lazyCodeEnvAvailable) return undefined;+ return resolveCodeExecutionWorkspaceContext({+ context: resolveCodeExecutionContext({+ statefulSessions: statefulCodeSessions,+ environment: statefulCodeEnvironment,+ environmentId: agent.code_environment_id,+ environmentIds: agent.code_environment_ids,+ allowEnvironmentSelection:+ appConfig.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({+ conversation: admittedConversation,+ request: runtimeRequestBody,+ }),+ inheritedEnvironments: req.codeWorkspaceInheritance,+ environments: configuredCodeEnvironments,+ userId,+ agentId: agent.id,+ conversationId,}),- environments: configuredCodeEnvironments,- userId,- agentId: agent.id,- conversationId,- })- : undefined;- const codeExecutionContext = baseCodeExecutionContext- ? await resolveCodeExecutionWorkspaceContext({- context: baseCodeExecutionContext,requestedSelections: runtimeRequestBody?.codeWorkspaces,persistedSelections: admittedConversation?.codeWorkspaces,environments: configuredCodeEnvironments,getAppConfig,- })- : undefined;+ });+ },+ });+ const { codeExecutionContext } = codeAvailability;const {alwaysApplySkillPrimes,historicalToolNames,@@ -1212,10 +1221,8 @@ const initializeClientWithProvider = async ({memoryAvailable === true && agent.tools?.includes(Tools.memory) === true,subagents: agent.subagents,configId: getLazySubagentConfigId(agent),- codeEnvAvailable: lazyCodeEnvAvailable,- statefulCodeSessions,+ ...codeAvailability,statefulCodeEnvironment,- codeExecutionContext,codeSessionKey: codeExecutionContext?.codeSessionKey,includeReasoningHistory: getIncludeReasoningHistory(agent),alwaysApplySkillPrimes,@@ -1232,6 +1239,11 @@ const initializeClientWithProvider = async ({);};+ const loadViewableSubagent = createViewableSubagentLoader({+ getAgent: (agentId) => db.getAgentWithVersionCount({ id: agentId }),+ canView: (agent, agentId) => hasSubagentViewAccess(agent, agentId),+ });+const loadSubagentMetadata = async (agentId) => {if (skippedAgentIds.has(agentId)) return null;const cached = lazyMetadataByAgentId.get(agentId);@@ -1239,8 +1251,8 @@ const initializeClientWithProvider = async ({let loading = lazyMetadataLoadsByAgentId.get(agentId);if (!loading) {loading = resolveLazyMetadata(async () => {- const agent = await db.getAgentWithVersionCount({ id: agentId });- if (!agent || !(await hasSubagentViewAccess(agent, agentId))) {+ const agent = await loadViewableSubagent(agentId);+ if (!agent) {skippedAgentIds.add(agentId);return null;}@@ -1504,18 +1516,22 @@ const initializeClientWithProvider = async ({lazySubagentConfigs: lazyChildren,subagentAgentConfigs: eagerChildren,subagentGraphMemberMetadata,- resolve: async (context) =>- initializeLazySubagent({- agentId: metadata.id,- configId: metadata.configId,- context,- lazyChildren,- }).then(async (config) => {+ ...guardUnavailableSubagent({+ description: metadata.description,+ codeWorkspaceUnavailable: metadata.codeWorkspaceUnavailable,+ resolve: async (context) => {+ const config = await initializeLazySubagent({+ agentId: metadata.id,+ configId: metadata.configId,+ context,+ lazyChildren,+ });config.subagentAgentConfigs = eagerChildren;graphMemberConfigsById.set(config.id, config);await resolveGraphSubagentsFor(config, context.signal);return config;- }),+ },+ }),},metadata,);@@ -1539,6 +1555,21 @@ const initializeClientWithProvider = async ({};const rootSubagentConfigs = [primaryConfig, ...agentConfigs.values()];+ const statefulCodeSessionsConfig =+ appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions;+ req.codeWorkspaceInheritance = subagentsAvailableForRun+ ? await resolveSubagentCodeWorkspaceInheritance({+ selections: resolveCodeExecutionWorkspaceSelections({+ conversation: admittedConversation,+ request: runtimeRequestBody,+ }),+ roots: rootSubagentConfigs.filter((config) => config?.id),+ loadSubagent: (agentId) => resolveLazyMetadata(() => loadViewableSubagent(agentId)),+ environments: statefulCodeSessionsConfig?.environments,+ allowEnvironmentSelection: statefulCodeSessionsConfig?.allowEnvironmentSelection,+ codeExecutionAvailable: codeEnvAvailable === true && statefulSessionsAvailable === true,+ })+ : undefined;await resolveSubagentTrees(rootSubagentConfigs);const graphMemberConfigsById = new Map(diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 777188ba10..cccc074f27 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -2404,10 +2404,22 @@ describe('initializeClient — subagent loading', () => {const defaultsWithoutAttached =source === 'other-owner' || (source === 'resolved-null' && !movesEnabled);if ((!registered && !defaultsWithoutAttached) || source === 'inaccessible-choice') {- await expect(initialization).rejects.toMatchObject({- code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,- });- expect(agentClientArgs).toBeUndefined();+ /** The parent's turn proceeds; the subagent is advertised as unable to run instead. */+ await initialization;+ const descriptor = agentClientArgs.agent.lazySubagentConfigs[0];+ const reason = source === 'inaccessible-choice' ? 'invalid' : 'missing';+ expect(descriptor).toEqual(+ expect.objectContaining({+ codeEnvAvailable: false,+ statefulCodeSessions: false,+ codeExecutionContext: undefined,+ description: expect.stringContaining('Unavailable in this conversation'),+ }),+ );+ await expect(+ descriptor.resolve({ signal: new AbortController().signal }),+ ).rejects.toMatchObject({ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason });+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);return;}await initialization;@@ -2471,6 +2483,199 @@ describe('initializeClient — subagent loading', () => {},);+ describe('subagent machine inheritance', () => {+ const SKYNET = 'code-skynet';+ const LIA_RAG = 'code-lia-rag';+ const bridgeEnvironment = (id) => ({+ id,+ name: id,+ type: 'attached',+ owner: 'deployment',+ pairing: { workerId: `${id}-worker`, tokenEnv: 'TEST_INHERIT_WORKSPACE_TOKEN' },+ baseURL: 'https://bridge.example.com/v1/',+ });+ /** Both machines are registered; each advertises the checkout it holds on demo. */+ const mockWorkerStatus = () =>+ jest.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {+ const workerId = decodeURIComponent(String(url).match(/workers\/([^/]+)\/status/)[1]);+ return new Response(+ JSON.stringify({+ protocolVersion: 1,+ workerId,+ online: true,+ ready: true,+ leaseExpiresInMs: 45000,+ capabilities: {+ statefulWorkspace: true,+ sandboxProfile: 'native-srt',+ runtimes: ['bash'],+ workspaceTools: {+ protocolVersion: 1,+ operations: ['read_file'],+ workspaces: [{ id: workerId.startsWith(SKYNET) ? 'code-api' : 'agents' }],+ },+ },+ }),+ );+ });++ const setup = async ({ reviewer = {}, environments = [SKYNET, LIA_RAG] } = {}) => {+ const subAgent = await createAgent({+ id: SUBAGENT_ID,+ name: 'PR Reviewer',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools: ['execute_code'],+ stateful_code_sessions: true,+ stateful_code_environment: 'user',+ code_environment_id: SKYNET,+ code_environment_ids: [LIA_RAG],+ code_workspace_id: '',+ ...reviewer,+ });+ await grantView(subAgent);+ mockInitializeAgent.mockResolvedValue({+ ...makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ statefulCodeSessions: true,+ codeExecutionContext: { environmentId: LIA_RAG, environmentType: 'attached' },+ });+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions');+ req.config.endpoints.agents.statefulCodeSessions = {+ allowedEnvironments: ['user'],+ environments: environments.map(bridgeEnvironment),+ };+ /** An older client: Lia owns her machine, the reviewer is named nowhere. */+ req.body.codeEnvironmentMode = 'attached';+ req.body.codeWorkspaces = [+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: [PRIMARY_ID] },+ ...(environments.includes(SKYNET)+ ? [{ environmentId: SKYNET, workspaceId: 'code-api' }]+ : []),+ ];+ mockGetAppConfig.mockResolvedValue(req.config);+ process.env.TEST_INHERIT_WORKSPACE_TOKEN = 'test-token';+ return req;+ };++ afterEach(() => {+ delete process.env.TEST_INHERIT_WORKSPACE_TOKEN;+ });++ it("routes the reviewer to its parent's machine and workspace, not its own default", async () => {+ const req = await setup();+ const fetchSpy = mockWorkerStatus();+ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ } finally {+ fetchSpy.mockRestore();+ }++ expect(req.codeWorkspaceInheritance).toEqual(new Map([[SUBAGENT_ID, LIA_RAG]]));+ expect(req.body.codeWorkspaces).toEqual([+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: [PRIMARY_ID] },+ { environmentId: SKYNET, workspaceId: 'code-api' },+ ]);+ expect(agentClientArgs.agent.lazySubagentConfigs[0].codeExecutionContext).toEqual(+ expect.objectContaining({+ environmentId: LIA_RAG,+ codeWorkspace: expect.objectContaining({ environmentId: LIA_RAG, workspaceId: 'agents' }),+ }),+ );++ mockInitializeAgent.mockImplementationOnce(async (params) => {+ expect(params.req.codeWorkspaceInheritance).toBe(req.codeWorkspaceInheritance);+ return makeSubagentConfig(SUBAGENT_ID);+ });+ await agentClientArgs.agent.lazySubagentConfigs[0].resolve({+ signal: new AbortController().signal,+ });+ });++ it('keeps a reviewer that may not use the parent machine on its own default', async () => {+ const req = await setup({ reviewer: { code_environment_ids: [] } });+ const fetchSpy = mockWorkerStatus();+ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ } finally {+ fetchSpy.mockRestore();+ }++ expect(req.codeWorkspaceInheritance.size).toBe(0);+ expect(agentClientArgs.agent.lazySubagentConfigs[0].codeExecutionContext).toEqual(+ expect.objectContaining({+ environmentId: SKYNET,+ codeWorkspace: expect.objectContaining({ workspaceId: 'code-api' }),+ }),+ );+ });++ it("never inherits a machine outside the principal's environments", async () => {+ const req = await setup({ environments: [SKYNET] });+ req.body.codeWorkspaces = [{ environmentId: SKYNET, workspaceId: 'code-api' }];+ mockInitializeAgent.mockResolvedValue({+ ...makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ statefulCodeSessions: true,+ codeExecutionContext: { environmentId: LIA_RAG, environmentType: 'attached' },+ });+ const fetchSpy = mockWorkerStatus();+ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ } finally {+ fetchSpy.mockRestore();+ }++ expect(req.codeWorkspaceInheritance.size).toBe(0);+ expect(agentClientArgs.agent.lazySubagentConfigs[0].codeExecutionContext.environmentId).toBe(+ SKYNET,+ );+ });++ it("keeps the parent's turn when a reviewer has no selection it may use", async () => {+ const req = await setup({ reviewer: { code_environment_ids: [] } });+ req.body.codeWorkspaces = [req.body.codeWorkspaces[0]];+ const fetchSpy = mockWorkerStatus();+ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ } finally {+ fetchSpy.mockRestore();+ }++ const descriptor = agentClientArgs.agent.lazySubagentConfigs[0];+ expect(descriptor.codeExecutionContext).toBeUndefined();+ expect(descriptor.description).toContain('Unavailable in this conversation');+ await expect(+ descriptor.resolve({ signal: new AbortController().signal }),+ ).rejects.toMatchObject({ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason: 'required' });+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ });+ });+it('omits a descriptor when its metadata lookup fails without aborting the primary run', async () => {const primaryConfig = makePrimaryConfig({subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 8b74236819..2a28d1ebd0 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -895,6 +895,7 @@ async function loadToolDefinitionsWrapper({conversation: req.resolvedConversation,request: runtimeRequestBody,}),+ inheritedEnvironments: req.codeWorkspaceInheritance,environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,userId: req.user.id,agentId: agent.id,@@ -1828,6 +1829,7 @@ async function loadAgentTools({conversation: req.resolvedConversation,request: runtimeRequestBody,}),+ inheritedEnvironments: req.codeWorkspaceInheritance,environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,userId: req.user.id,agentId: agent.id,@@ -2267,6 +2269,7 @@ async function loadToolsForExecution({conversation: req.resolvedConversation,request: runtimeRequestBody,}),+ inheritedEnvironments: req.codeWorkspaceInheritance,environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,userId: req.user.id,agentId: agent?.id,diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsxindex 8dad7c3b52..5c324ee3d2 100644--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx@@ -124,6 +124,13 @@ describe('useCodeWorkspace', () => {return config;}+ function enableInheritance() {+ mockStartupConfig.mockReturnValue({+ ...mockStartupConfig(),+ codeWorkspaceInheritanceVersion: 1,+ });+ }+it('names the reviewer whose separate machine still needs a workspace', () => {enableChoices();mockAgentPermissions().agent.name = 'Lia';@@ -251,6 +258,168 @@ describe('useCodeWorkspace', () => {expect(result.current.resolveSubmission(choices)?.codeWorkspaces).toEqual(choices);});+ it("routes a reviewer with Lia's chosen machine when an older client sealed only her", () => {+ enableChoices();+ enableInheritance();+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };+ mockAgentsMap.mockReturnValue({+ reviewer: {+ id: 'reviewer',+ name: 'PR Reviewer',+ stateful_code_sessions: true,+ tools: [Tools.execute_code],+ code_environment_id: 'personal-vm',+ code_environment_ids: ['runtime-vm'],+ },+ });+ mockStatus.mockImplementation((ids: string[]) =>+ ids.map((id) => ({+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },+ })),+ );+ const sealedChoice = [+ { environmentId: 'runtime-vm', workspaceId: 'project-a', agentIds: ['agent_primary'] },+ ];+ const { result } = renderHook(() =>+ useCodeWorkspace({+ ...conversation(sealedChoice),+ conversationId: 'saved',+ codeEnvironmentMode: 'attached',+ }),+ );+ expect(result.current.canSubmit).toBe(true);+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([+ 'runtime-vm',+ ]);+ expect(result.current.environments[0].requiredBy).toEqual(+ expect.arrayContaining([{ id: 'reviewer', name: 'PR Reviewer' }]),+ );+ expect(result.current.resolveSubmission(sealedChoice)?.codeWorkspaces).toEqual(sealedChoice);+ });++ it("echoes the reviewer's former selection after it follows Lia, without gating on it", () => {+ enableChoices();+ mockStartupConfig.mockReturnValue({+ codeEnvironmentDecisionVersion: 1,+ codeEnvironmentMoveVersion: 1,+ codeEnvironmentTransitionVersion: 2,+ codeWorkspaceInheritanceVersion: 1,+ });+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };+ mockAgentsMap.mockReturnValue({+ reviewer: {+ id: 'reviewer',+ name: 'PR Reviewer',+ stateful_code_sessions: true,+ tools: [Tools.execute_code],+ code_environment_id: 'personal-vm',+ code_environment_ids: ['runtime-vm'],+ },+ });+ mockStatus.mockImplementation((ids: string[]) =>+ ids.map((id) => ({+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },+ })),+ );+ /** The demo incident's sealed decision: the reviewer's Code API checkout plus Lia's machine. */+ const incident = [+ { environmentId: 'personal-vm', workspaceId: 'project-a' },+ { environmentId: 'runtime-vm', workspaceId: 'project-a', agentIds: ['agent_primary'] },+ ];+ const { result } = renderHook(() =>+ useCodeWorkspace({+ ...conversation(incident),+ conversationId: 'saved',+ codeEnvironmentMode: 'attached',+ }),+ );+ expect(result.current.canSubmit).toBe(true);+ expect(result.current.transition?.kind).not.toBe('move');+ /** Nothing runs on the former machine, so its readiness is never polled or required. */+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([+ 'runtime-vm',+ ]);+ expect(mockStatus).toHaveBeenLastCalledWith(['runtime-vm'], true, expect.anything());+ expect(+ result.current.environments.find(({ environment }) => environment.id === 'runtime-vm')+ ?.requiredBy,+ ).toEqual(expect.arrayContaining([{ id: 'reviewer', name: 'PR Reviewer' }]));+ expect(result.current.resolveSubmission(incident)?.codeWorkspaces).toEqual(incident);+ });++ it("lets a new chat's reviewer follow Lia before any workspace is picked", () => {+ enableChoices();+ enableInheritance();+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };+ mockAgentsMap.mockReturnValue({+ reviewer: {+ id: 'reviewer',+ name: 'PR Reviewer',+ stateful_code_sessions: true,+ tools: [Tools.execute_code],+ code_environment_id: 'runtime-vm',+ code_environment_ids: ['personal-vm'],+ },+ });+ const { result } = renderHook(() => useCodeWorkspace(conversation()));+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([+ 'personal-vm',+ ]);+ expect(result.current.canSubmit).toBe(true);+ expect(result.current.resolveSubmission()?.codeWorkspaces).toEqual([+ { environmentId: 'personal-vm', workspaceId: 'project-a' },+ ]);+ });++ it("still asks for the reviewer's own machine when the API predates inheritance", () => {+ enableChoices();+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };+ mockAgentsMap.mockReturnValue({+ reviewer: {+ id: 'reviewer',+ stateful_code_sessions: true,+ tools: [Tools.execute_code],+ code_environment_id: 'runtime-vm',+ code_environment_ids: ['personal-vm'],+ },+ });+ const { result } = renderHook(() => useCodeWorkspace(conversation()));+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([+ 'personal-vm',+ 'runtime-vm',+ ]);+ });++ it("keeps a reviewer that may not use Lia's machine on its own default", () => {+ enableChoices();+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };+ mockAgentsMap.mockReturnValue({+ reviewer: {+ id: 'reviewer',+ name: 'PR Reviewer',+ stateful_code_sessions: true,+ tools: [Tools.execute_code],+ code_environment_id: 'personal-vm',+ },+ });+ mockStatus.mockImplementation((ids: string[]) =>+ ids.map((id) => ({+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'one' }, { id: 'two' }] },+ })),+ );+ const { result } = renderHook(() =>+ useCodeWorkspace(+ conversation([+ { environmentId: 'runtime-vm', workspaceId: 'one', agentIds: ['agent_primary'] },+ ]),+ ),+ );+ expect(result.current.canSubmit).toBe(false);+ expect(+ result.current.environments.find(({ environment }) => environment.id === 'personal-vm'),+ ).toMatchObject({ state: 'choose', requiredBy: [{ id: 'reviewer', name: 'PR Reviewer' }] });+ });+it('offers an explicit saved-chat recovery target when the selected default disappears', () => {const config = enableChoices();config.statefulCodeSessions.environments = config.statefulCodeSessions.environments.filter(diff --git a/client/src/hooks/Agents/useCodeApprovalMode.ts b/client/src/hooks/Agents/useCodeApprovalMode.tsindex d94b0417a9..336dba54db 100644--- a/client/src/hooks/Agents/useCodeApprovalMode.ts+++ b/client/src/hooks/Agents/useCodeApprovalMode.ts@@ -6,6 +6,7 @@ import {getAllowedCodeApprovalModes,CODE_APPROVAL_MODES,resolveCodeEnvironmentSelection,+ resolveCodeWorkspaceInheritance,} from 'librechat-data-provider';import type {Agent,@@ -13,6 +14,7 @@ import type {TConfig,TPublicCodeEnvironment,CodeWorkspaceSelection,+ CodeWorkspaceRoutingAgent,} from 'librechat-data-provider';import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';import { useCodeApprovalModePreference } from './codeApprovalPreference';@@ -45,6 +47,8 @@ export default function useCodeApprovalMode(]),[addedAgent, agentsMap, primaryAgent, conversation?.agent_id, addedConversation?.agent_id],);+ /** Approval modes intersect every machine an agent could run on, including a subagent's own+ * default it may no longer use once it follows its parent: offering fewer modes is safe. */const codeEnvironments = useMemo(() =>reachable.agents@@ -155,6 +159,7 @@ export function findExecutionEnvironment(environments?: TPublicCodeEnvironment[],allowEnvironmentSelection?: boolean,selections?: CodeWorkspaceSelection[],+ inheritedEnvironmentId?: string,): TPublicCodeEnvironment | undefined {const defaultEnvironment = agent.code_environment_id? environments?.find((candidate) => candidate.id === agent.code_environment_id)@@ -166,7 +171,13 @@ export function findExecutionEnvironment(environmentId: agent.code_environment_id ?? defaultEnvironment?.id,environmentIds: agent.code_environment_ids,allowSelection,- selections,+ /** A draft's machine for its parent is selected on submission, before the reader picks it. */+ selections:+ inheritedEnvironmentId != null &&+ !selections?.some(({ environmentId }) => environmentId === inheritedEnvironmentId)+ ? [...(selections ?? []), { environmentId: inheritedEnvironmentId, workspaceId: 'draft' }]+ : selections,+ inheritedEnvironmentId,});if (!selection.valid) return undefined;const resolved = selection.environmentId@@ -182,9 +193,16 @@ export function findCodeWorkspaceDiscoveryEnvironment(environments?: TPublicCodeEnvironment[],allowEnvironmentSelection?: boolean,selections?: CodeWorkspaceSelection[],+ inheritedEnvironmentId?: string,): TPublicCodeEnvironment | undefined {return (- findExecutionEnvironment(agent, environments, allowEnvironmentSelection, selections) ??+ findExecutionEnvironment(+ agent,+ environments,+ allowEnvironmentSelection,+ selections,+ inheritedEnvironmentId,+ ) ??findExecutionEnvironment(agent, environments) ??environments?.find(({ id, type }) =>@@ -231,3 +249,105 @@ export function collectReachableAgents(}return { agents, complete };}++function getLinkedAgentIds(agent: Agent): string[] {+ const edgeIds = agent.edges?.flatMap((edge) => [+ ...(Array.isArray(edge.from) ? edge.from : [edge.from]),+ ...(Array.isArray(edge.to) ? edge.to : [edge.to]),+ ]);+ return [...(agent.agent_ids ?? []), ...(edgeIds ?? [])];+}++function toCodeWorkspaceRoutingAgent(+ agent: Agent,+ environments: TPublicCodeEnvironment[] | undefined,+ allowEnvironmentSelection: boolean | undefined,+): CodeWorkspaceRoutingAgent {+ return {+ id: agent.id,+ routesCode:+ agent.stateful_code_sessions === true && agent.tools?.includes(Tools.execute_code) === true,+ environmentId:+ agent.code_environment_id ?? environments?.find(({ default: isDefault }) => isDefault)?.id,+ environmentIds: agent.code_environment_ids,+ allowSelection:+ getCodeEnvironmentChoiceIds(agent, environments, allowEnvironmentSelection) != null,+ subagentIds:+ agent.subagents?.enabled === true+ ? [+ ...(agent.subagents.agent_ids ?? []),+ ...(agent.subagents.graphs ?? []).flatMap((graph) => graph.agent_ids ?? []),+ ].filter((id) => id.length > 0 && id !== agent.id)+ : undefined,+ };+}++/**+ * Mirrors the server's subagent machine inheritance for the composer. Conversation agents and+ * the agents they hand off to are roots; explicit subagents follow their parent's machine when+ * `resolveCodeWorkspaceInheritance` allows it, so the composer neither asks for a workspace a+ * subagent will not use nor rejects a graph the server will route.+ */+export function resolveReachableCodeWorkspaceInheritance(+ roots: Array<Agent | undefined>,+ agentsMap: TAgentsMap | undefined,+ environments: TPublicCodeEnvironment[] | undefined,+ allowEnvironmentSelection: boolean | undefined,+ selections: CodeWorkspaceSelection[] | undefined,+ /** The chat has not decided yet, so the submission will also select each root's machine. */+ draft = false,+): Map<string, string> {+ if (!draft && !selections?.length) return new Map();+ const lookup = (id: string): Agent | undefined =>+ roots.find((root) => root?.id === id) ?? agentsMap?.[id];+ const agents = new Map<string, CodeWorkspaceRoutingAgent>();+ const rootIds: string[] = [];+ const pendingRoots = roots.filter((agent): agent is Agent => agent != null);+ while (pendingRoots.length > 0) {+ const agent = pendingRoots.shift() as Agent;+ if (agents.has(agent.id)) continue;+ agents.set(+ agent.id,+ toCodeWorkspaceRoutingAgent(agent, environments, allowEnvironmentSelection),+ );+ rootIds.push(agent.id);+ for (const id of getLinkedAgentIds(agent)) {+ const linked = agents.has(id) ? undefined : lookup(id);+ if (linked != null) pendingRoots.push(linked);+ }+ }+ const pending = rootIds.flatMap((id) => agents.get(id)?.subagentIds ?? []);+ while (pending.length > 0) {+ const id = pending.shift() as string;+ const agent = agents.has(id) ? undefined : lookup(id);+ if (agent == null) continue;+ const node = toCodeWorkspaceRoutingAgent(agent, environments, allowEnvironmentSelection);+ agents.set(id, node);+ pending.push(...(node.subagentIds ?? []));+ }+ /** A sendable draft selects a workspace on every machine a root runs on, so a subagent can follow+ * its parent there before the reader picks one; requiring its own default would ask for a+ * workspace the submitted decision never uses. */+ const prospective = draft+ ? rootIds.reduce<CodeWorkspaceSelection[]>((planned, id) => {+ const root = lookup(id);+ const environment =+ root != null && agents.get(id)?.routesCode === true+ ? findExecutionEnvironment(root, environments, allowEnvironmentSelection, selections)+ : undefined;+ return environment?.type === 'attached' &&+ !planned.some(({ environmentId }) => environmentId === environment.id)+ ? [...planned, { environmentId: environment.id, workspaceId: 'draft' }]+ : planned;+ }, selections ?? [])+ : selections;+ return resolveCodeWorkspaceInheritance({+ selections: prospective,+ rootIds,+ agents,+ isAttachedEnvironment: (id) =>+ environments?.some(+ (environment) => environment.id === id && environment.type === 'attached',+ ) === true,+ });+}diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.tsindex 6bb848d4ab..f6f8d2f45e 100644--- a/client/src/hooks/Agents/useCodeWorkspace.ts+++ b/client/src/hooks/Agents/useCodeWorkspace.ts@@ -13,10 +13,12 @@ import {CODE_ENVIRONMENT_MOVE_VERSION,CODE_ENVIRONMENT_TRANSITION_VERSION,CODE_WORKSPACE_RECOVERY_VERSION,+ CODE_WORKSPACE_INHERITANCE_VERSION,PermissionTypes,Permissions,} from 'librechat-data-provider';import type {+ Agent,CodeEnvironmentMode,CodeWorkspaceDescriptor,CodeWorkspaceSelection,@@ -26,18 +28,19 @@ import type {TPublicCodeEnvironment,} from 'librechat-data-provider';import type { CodeEnvironmentReconciliation } from '~/store/codeEnvironmentReconciliation';-import {- useCodeEnvironmentStatusQueries,- useGetStartupConfig,- useIsReplacingConversationCodeEnvironment,- useConversationCodeEnvironmentRecovery,-} from '~/data-provider';import {collectReachableAgents,findExecutionEnvironment,getCodeEnvironmentChoiceIds,findCodeWorkspaceDiscoveryEnvironment,+ resolveReachableCodeWorkspaceInheritance,} from './useCodeApprovalMode';+import {+ useCodeEnvironmentStatusQueries,+ useGetStartupConfig,+ useIsReplacingConversationCodeEnvironment,+ useConversationCodeEnvironmentRecovery,+} from '~/data-provider';import { useWorkspacePreferences } from './workspacePreferences';import useAgentToolPermissions from './useAgentToolPermissions';import useHasAccess from '~/hooks/Roles/useHasAccess';@@ -187,6 +190,10 @@ export default function useCodeWorkspace(const supportsWorkspaceRecovery =supportsEnvironmentMoves &&startupConfig?.codeWorkspaceRecoveryVersion === CODE_WORKSPACE_RECOVERY_VERSION;+ /** An API that predates inheritance still routes each subagent to its own machine, so only an+ * advertising one lets the composer drop that machine's workspace. */+ const supportsWorkspaceInheritance =+ startupConfig?.codeWorkspaceInheritanceVersion === CODE_WORKSPACE_INHERITANCE_VERSION;const preferences = useWorkspacePreferences(conversation?.agent_id);const { agentsConfig, endpointsConfig } = useGetAgentsConfig();const canRunCode = useHasAccess({@@ -211,11 +218,69 @@ export default function useCodeWorkspace(]),[addedAgent, agentsMap, primaryAgent, conversation?.agent_id, addedConversation?.agent_id],);+ const storedSelections = conversation?.codeWorkspaces;+ const isNewChat =+ conversation != null &&+ (conversation.conversationId == null || conversation.conversationId === 'new');+ /** Only a recorded decision is sealed. A saved chat whose turns never involved a code-capable+ * agent stores none, so switching one to a coding agent still gets to choose; treating it as+ * sealed leaves the composer showing a decision its owner never made, with no workspace to+ * select and no way to submit.+ *+ * Until the deployment advertises the decision protocol, a replica that still reads a+ * field-less row as a sealed `without_attached` may serve the next turn and reject an attached+ * choice as `locked`, so the legacy lock stays for the whole rollout window. Nothing is lost by+ * waiting: the composer only reports that unmade decision once the same flag is on. */+ const holdsDecision =+ conversation?.codeEnvironmentMode != null || (storedSelections?.length ?? 0) > 0;+ const locked =+ conversation != null && !isNewChat && (holdsDecision || !supportsEnvironmentDecisions);+ /** A new chat and a saved chat that never decided are both still choosing, so agent defaults, a+ * remembered selection, and a sole workspace apply to each. */+ const undecided = conversation != null && !locked;const workspaceMetadata = useMemo(() => {const unique = new Map<string, TPublicCodeEnvironment>();const defaults = new Map<string, Set<string>>();const preferenceAgentIds = new Map<string, Set<string>>();const requiredBy = new Map<string, Array<{ id: string; name?: string | null }>>();+ const inheritance = supportsWorkspaceInheritance+ ? resolveReachableCodeWorkspaceInheritance(+ [primaryAgent, addedAgent],+ agentsMap,+ statefulCodeSessions?.environments,+ statefulCodeSessions?.allowEnvironmentSelection,+ conversation?.codeWorkspaces,+ undecided,+ )+ : new Map<string, string>();+ /** A decision may still select the machine an inheriting subagent ran on before it followed+ * its parent. No agent runs there now, so that selection is echoed as sealed but neither+ * required, nor checked for readiness, nor read as a foreign choice that needs a move. */+ const formerEnvironmentIds = new Set<string>();+ const retainInheritedFromSelection = (agent: Agent) => {+ if (!inheritance.has(agent.id)) return;+ const own = resolveCodeEnvironmentSelection({+ agentId: agent.id,+ environmentId:+ agent.code_environment_id ??+ statefulCodeSessions?.environments?.find(({ default: isDefault }) => isDefault)?.id,+ environmentIds: agent.code_environment_ids,+ allowSelection:+ getCodeEnvironmentChoiceIds(+ agent,+ statefulCodeSessions?.environments,+ statefulCodeSessions?.allowEnvironmentSelection,+ ) != null,+ selections: conversation?.codeWorkspaces,+ });+ const ownId = own.valid ? own.environmentId : undefined;+ if (+ ownId &&+ conversation?.codeWorkspaces?.some(({ environmentId }) => environmentId === ownId)+ ) {+ formerEnvironmentIds.add(ownId);+ }+ };let complete = true;for (const agent of reachable.agents) {if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {@@ -226,12 +291,14 @@ export default function useCodeWorkspace(statefulCodeSessions?.environments,statefulCodeSessions?.allowEnvironmentSelection,conversation?.codeWorkspaces,+ inheritance.get(agent.id),);/** Discovery must remain available while a graph draft is partial or its sealed* route needs recovery. Only final submission resolves the entire graph strictly. */if (environment == null && agent.code_environment_id) {complete = false;}+ retainInheritedFromSelection(agent);if (environment?.type !== 'attached') continue;unique.set(environment.id, environment);const owners = requiredBy.get(environment.id) ?? [];@@ -259,6 +326,7 @@ export default function useCodeWorkspace(statefulCodeSessions?.environments,statefulCodeSessions?.allowEnvironmentSelection,conversation?.codeWorkspaces,+ inheritance.get(agent.id),);if (environment?.type !== 'attached') continue;const owners = preferenceAgentIds.get(environment.id) ?? new Set<string>();@@ -271,6 +339,7 @@ export default function useCodeWorkspace(defaults,preferenceAgentIds,requiredBy,+ formerEnvironmentIds: new Set([...formerEnvironmentIds].filter((id) => !unique.has(id))),environments: [...unique.values()].sort((a, b) => a.id.localeCompare(b.id)),};}, [@@ -283,6 +352,8 @@ export default function useCodeWorkspace(reachable.agents,statefulCodeSessions?.environments,statefulCodeSessions?.allowEnvironmentSelection,+ supportsWorkspaceInheritance,+ undecided,]);const isAgentsConversation =(conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents;@@ -306,33 +377,15 @@ export default function useCodeWorkspace(// Poll progress is not workspace state; keep unchanged refreshes off the send path.{ notifyOnChangeProps: ['data', 'isLoading', 'isError'] },);- const storedSelections = conversation?.codeWorkspaces;const attachedEnvironmentIds = useMemo(() => new Set(attachedEnvironments.map(({ id }) => id)),[attachedEnvironments],);+ const { formerEnvironmentIds } = workspaceMetadata;const hasForeignStoredSelection = storedSelections?.some(- ({ environmentId }) => !attachedEnvironmentIds.has(environmentId),+ ({ environmentId }) =>+ !attachedEnvironmentIds.has(environmentId) && !formerEnvironmentIds.has(environmentId),);- const isNewChat =- conversation != null &&- (conversation.conversationId == null || conversation.conversationId === 'new');- /** Only a recorded decision is sealed. A saved chat whose turns never involved a code-capable- * agent stores none, so switching one to a coding agent still gets to choose; treating it as- * sealed leaves the composer showing a decision its owner never made, with no workspace to- * select and no way to submit.- *- * Until the deployment advertises the decision protocol, a replica that still reads a- * field-less row as a sealed `without_attached` may serve the next turn and reject an attached- * choice as `locked`, so the legacy lock stays for the whole rollout window. Nothing is lost by- * waiting: the composer only reports that unmade decision once the same flag is on. */- const holdsDecision =- conversation?.codeEnvironmentMode != null || (storedSelections?.length ?? 0) > 0;- const locked =- conversation != null && !isNewChat && (holdsDecision || !supportsEnvironmentDecisions);- /** A new chat and a saved chat that never decided are both still choosing, so agent defaults, a- * remembered selection, and a sole workspace apply to each. */- const undecided = conversation != null && !locked;const machineChoiceOwners =required &&supportsEnvironmentDecisions &&@@ -443,10 +496,16 @@ export default function useCodeWorkspace(}/** Never silently discard a machine the user picked. A sealed choice needs a transition;* a draft choice not used by the graph must be corrected before it can execute elsewhere. */- if (selections?.some(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))) {+ if (+ selections?.some(+ ({ environmentId }) =>+ !attachedEnvironmentIds.has(environmentId) && !formerEnvironmentIds.has(environmentId),+ )+ ) {return undefined;}- const resolved: CodeWorkspaceSelection[] = [];+ const resolved: CodeWorkspaceSelection[] =+ selections?.filter(({ environmentId }) => formerEnvironmentIds.has(environmentId)) ?? [];for (const result of environmentResults) {const requested = selections?.find(({ environmentId }) => environmentId === result.environment.id,@@ -480,6 +539,16 @@ export default function useCodeWorkspace(}return undefined;}+ const inheritance =+ supportsWorkspaceInheritance && statefulCodeSessions?.allowEnvironmentSelection === true+ ? resolveReachableCodeWorkspaceInheritance(+ [primaryAgent, addedAgent],+ agentsMap,+ statefulCodeSessions.environments,+ true,+ resolved,+ )+ : undefined;if (statefulCodeSessions?.allowEnvironmentSelection === true &&reachable.agents.some(@@ -495,6 +564,7 @@ export default function useCodeWorkspace(environmentIds: agent.code_environment_ids,allowSelection: true,selections: resolved,+ inheritedEnvironmentId: inheritance?.get(agent.id),}).valid,))@@ -502,12 +572,17 @@ export default function useCodeWorkspace(return resolved.sort((a, b) => a.environmentId.localeCompare(b.environmentId));},[+ addedAgent,+ agentsMap,attachedEnvironmentIds,environmentResults,+ formerEnvironmentIds,+ primaryAgent,required,selectionMetadataComplete,reachable.agents,statefulCodeSessions,+ supportsWorkspaceInheritance,],);diff --git a/packages/api/src/agents/execution.spec.ts b/packages/api/src/agents/execution.spec.tsindex e090585bf3..a935f6060d 100644--- a/packages/api/src/agents/execution.spec.ts+++ b/packages/api/src/agents/execution.spec.ts@@ -223,6 +223,61 @@ describe('resolveCodeExecutionContext', () => {resolveCodeExecutionContext({ ...params, environments: [environments[1]] }).environmentId,).toBe('runtime-vm');});++ describe('subagent inheritance', () => {+ const choices = [+ { environmentId: 'application-vm', workspaceId: 'code-api' },+ { environmentId: 'runtime-vm', workspaceId: 'agents', agentIds: ['lia'] },+ ];+ const inheritedEnvironments = new Map([['reviewer', 'runtime-vm']]);+ const reviewer = { ...params, agentId: 'reviewer', workspaceSelections: choices };++ it("shares the parent's machine and conversation workspace instance", () => {+ const parent = resolveCodeExecutionContext({ ...params, workspaceSelections: choices });+ const child = resolveCodeExecutionContext({ ...reviewer, inheritedEnvironments });+ expect(resolveCodeExecutionContext(reviewer).environmentId).toBe('application-vm');+ expect(child.environmentId).toBe('runtime-vm');+ expect(child.conversationWorkspaceInstanceId).toBe(parent.conversationWorkspaceInstanceId);+ expect(child.executionRouteKey).toBe(parent.executionRouteKey);+ });++ it('looks the inheritance up under the saved agent ID', () => {+ expect(+ resolveCodeExecutionContext({+ ...reviewer,+ agentId: 'reviewer____1',+ inheritedEnvironments,+ }).environmentId,+ ).toBe('runtime-vm');+ });++ it('ignores an inherited machine the principal can no longer use', () => {+ expect(+ resolveCodeExecutionContext({+ ...reviewer,+ environments: [environments[0]],+ inheritedEnvironments,+ }).environmentId,+ ).toBe('application-vm');+ });++ it('never lets inheritance override an explicit owner or widen the allowlist', () => {+ expect(+ resolveCodeExecutionContext({+ ...reviewer,+ workspaceSelections: [{ ...choices[0], agentIds: ['reviewer'] }, choices[1]],+ inheritedEnvironments,+ }).environmentId,+ ).toBe('application-vm');+ expect(+ resolveCodeExecutionContext({+ ...reviewer,+ environmentIds: undefined,+ inheritedEnvironments,+ }).environmentId,+ ).toBe('application-vm');+ });+ });});const originalStatefulUrl = process.env.LIBRECHAT_CODE_BASEURL_STATEFUL;diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.tsindex e6ffa19508..1567eacf93 100644--- a/packages/api/src/agents/execution.ts+++ b/packages/api/src/agents/execution.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto';import { logger } from '@librechat/data-schemas';import { Constants, getCodeBaseURL } from '@librechat/agents';-import { resolveCodeEnvironmentSelection } from 'librechat-data-provider';+import { stripAgentIdSuffix, resolveCodeEnvironmentSelection } from 'librechat-data-provider';import type {Agents,CodeWorkspaceOperation,@@ -347,6 +347,42 @@ function resolveConfiguredEnvironment(params: {return executableEnvironments?.find((environment) => environment.default === true);}+/** Machine an agent runs on without a conversation choice, and whether a choice applies to it. */+export function resolveAgentCodeEnvironmentRouting(params: {+ environmentId?: string | null;+ environmentIds?: readonly string[];+ environments?: readonly CodeEnvironmentConfig[];+ /** Deployment ceiling (on unless `false` or the decision protocol is off). */+ allowEnvironmentSelection?: boolean;+}): { defaultEnvironment?: CodeEnvironmentConfig; allowSelection: boolean } {+ const defaultEnvironment = params.environments?.find(+ (candidate) =>+ isExecutableEnvironment(candidate) &&+ (params.environmentId ? candidate.id === params.environmentId : candidate.default === true),+ );+ const allowSelection =+ isCodeEnvironmentSelectionEnabled(params.allowEnvironmentSelection) &&+ (params.environmentIds?.length ?? 0) > 0 &&+ (defaultEnvironment?.type === 'attached' ||+ (defaultEnvironment == null && Boolean(params.environmentId)));+ return { defaultEnvironment, allowSelection };+}++/** Whether the principal-scoped environment list admits running on this attached machine. */+export function isExecutableAttachedEnvironment(+ environmentId: string,+ environments?: readonly CodeEnvironmentConfig[],+): boolean {+ return (+ environments?.some(+ (candidate) =>+ candidate.id === environmentId &&+ candidate.type === 'attached' &&+ isExecutableEnvironment(candidate),+ ) === true+ );+}+export function resolveCodeExecutionContext(params: {statefulSessions: boolean;environment?: StatefulCodeEnvironment | string | null;@@ -360,6 +396,9 @@ export function resolveCodeExecutionContext(params: {allowEnvironmentSelection?: boolean;environmentIds?: readonly string[];workspaceSelections?: unknown;+ /** Request-scoped subagent inheritance, keyed by saved agent ID. An inherited machine the+ * principal can no longer use is ignored, leaving the agent on its own route. */+ inheritedEnvironments?: ReadonlyMap<string, string>;}): CodeExecutionContext {if (!params.statefulSessions) {return {@@ -371,22 +410,22 @@ export function resolveCodeExecutionContext(params: {}const environment = normalizeStatefulCodeEnvironment(params.environment);- const defaultEnvironment = params.environments?.find(- (candidate) =>- isExecutableEnvironment(candidate) &&- (params.environmentId ? candidate.id === params.environmentId : candidate.default === true),- );- const allowSelection =- isCodeEnvironmentSelectionEnabled(params.allowEnvironmentSelection) &&- (params.environmentIds?.length ?? 0) > 0 &&- (defaultEnvironment?.type === 'attached' ||- (defaultEnvironment == null && Boolean(params.environmentId)));+ const { defaultEnvironment, allowSelection } = resolveAgentCodeEnvironmentRouting(params);+ const inheritedEnvironmentId =+ params.agentId == null+ ? undefined+ : params.inheritedEnvironments?.get(stripAgentIdSuffix(params.agentId));const selection = resolveCodeEnvironmentSelection({agentId: params.agentId,environmentId: params.environmentId ?? defaultEnvironment?.id,environmentIds: params.environmentIds,allowSelection,selections: params.workspaceSelections,+ inheritedEnvironmentId:+ inheritedEnvironmentId != null &&+ isExecutableAttachedEnvironment(inheritedEnvironmentId, params.environments)+ ? inheritedEnvironmentId+ : undefined,});if (!selection.valid) throw new CodeWorkspaceSelectionError('invalid');if (diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 0e2be4a4be..9d648632b4 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -1657,6 +1657,7 @@ export async function initializeAgent(conversation: runtime.resolvedConversation,request: requestBody,}),+ inheritedEnvironments: runtime.codeWorkspaceInheritance,environments: configuredCodeEnvironments,userId: requestFileOwnerId,agentId: agent.id,diff --git a/packages/api/src/agents/lazySubagents.spec.ts b/packages/api/src/agents/lazySubagents.spec.tsindex a21aad6981..5e30e1f7e6 100644--- a/packages/api/src/agents/lazySubagents.spec.ts+++ b/packages/api/src/agents/lazySubagents.spec.ts@@ -1,5 +1,13 @@+import { ErrorTypes } from 'librechat-data-provider';import { SkillsScope } from 'librechat-data-provider';-import { getLazySubagentConfigId } from './lazySubagents';+import type { CodeExecutionContext } from './execution';+import {+ guardUnavailableSubagent,+ getLazySubagentConfigId,+ createViewableSubagentLoader,+ resolveSubagentCodeAvailability,+} from './lazySubagents';+import { CodeWorkspaceSelectionError } from '~/code/errors';const agent = {id: 'child-agent',@@ -121,3 +129,101 @@ describe('getLazySubagentConfigId', () => {);});});++describe('createViewableSubagentLoader', () => {+ it('reads and checks VIEW once per subagent, and hides what the principal cannot view', async () => {+ const getAgent = jest.fn(async (id: string) => (id === 'missing' ? null : { id }));+ const canView = jest.fn(async (candidate: { id: string }) => candidate.id !== 'hidden');+ const load = createViewableSubagentLoader({ getAgent, canView });++ await expect(Promise.all([load('child'), load('child')])).resolves.toEqual([+ { id: 'child' },+ { id: 'child' },+ ]);+ await expect(load('hidden')).resolves.toBeNull();+ await expect(load('missing')).resolves.toBeNull();+ expect(getAgent).toHaveBeenCalledTimes(3);+ expect(canView).toHaveBeenCalledTimes(2);+ });++ it('shares a failed read with every caller', async () => {+ const getAgent = jest.fn(async () => {+ throw new Error('transient read');+ });+ const load = createViewableSubagentLoader({ getAgent, canView: async () => true });+ await expect(load('child')).rejects.toThrow('transient read');+ await expect(load('child')).rejects.toThrow('transient read');+ expect(getAgent).toHaveBeenCalledTimes(1);+ });+});++describe('subagent code availability', () => {+ const context = { environmentId: 'vm', environmentType: 'attached' } as CodeExecutionContext;++ it('keeps the resolved route when the workspace is usable', async () => {+ await expect(+ resolveSubagentCodeAvailability({+ agentId: 'child',+ codeEnvAvailable: true,+ statefulCodeSessions: true,+ resolveContext: async () => context,+ }),+ ).resolves.toEqual({+ codeEnvAvailable: true,+ statefulCodeSessions: true,+ codeExecutionContext: context,+ });+ });++ it('reports a missing workspace instead of throwing, and turns code off', async () => {+ await expect(+ resolveSubagentCodeAvailability({+ agentId: 'child',+ codeEnvAvailable: true,+ statefulCodeSessions: true,+ resolveContext: async () => {+ throw new CodeWorkspaceSelectionError('required');+ },+ }),+ ).resolves.toEqual({+ codeEnvAvailable: false,+ statefulCodeSessions: false,+ codeWorkspaceUnavailable: 'required',+ });+ });++ it.each([new CodeWorkspaceSelectionError('locked'), new Error('not configured')])(+ 'propagates %s',+ async (error) => {+ await expect(+ resolveSubagentCodeAvailability({+ agentId: 'child',+ codeEnvAvailable: true,+ statefulCodeSessions: true,+ resolveContext: async () => {+ throw error;+ },+ }),+ ).rejects.toBe(error);+ },+ );++ it('lists an unavailable subagent with the reason and never resolves it', async () => {+ const resolve = jest.fn(async () => 'config');+ const guarded = guardUnavailableSubagent({+ description: 'Reviews PRs.',+ codeWorkspaceUnavailable: 'missing',+ resolve,+ });+ expect(guarded.description).toContain('Unavailable in this conversation');+ await expect(guarded.resolve({})).rejects.toMatchObject({+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'missing',+ });+ expect(resolve).not.toHaveBeenCalled();+ expect(guardUnavailableSubagent({ description: 'Reviews PRs.', resolve })).toEqual({+ description: 'Reviews PRs.',+ resolve,+ });+ });+});diff --git a/packages/api/src/agents/lazySubagents.ts b/packages/api/src/agents/lazySubagents.tsindex ff1f2e356f..9b70e13666 100644--- a/packages/api/src/agents/lazySubagents.ts+++ b/packages/api/src/agents/lazySubagents.ts@@ -1,5 +1,12 @@import { createHash } from 'crypto';-import type { Agent } from 'librechat-data-provider';+import { logger } from '@librechat/data-schemas';+import type { Agent, CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';+import type { CodeExecutionContext } from './execution';+import {+ CodeWorkspaceSelectionError,+ describeCodeWorkspaceUnavailableSubagent,+ getSubagentCodeWorkspaceUnavailableReason,+} from '~/code/errors';type VersionedAgent = Pick<Agent,@@ -160,3 +167,91 @@ export function getLazySubagentConfigId(agent: VersionedAgent): string {.digest('hex');return `${agent.id}:${version}:${fingerprint}`;}++/**+ * Memoizes one read and one VIEW check per subagent for the life of a request, so machine+ * inheritance, lazy descriptors and graph members share them. A missing or unviewable agent+ * resolves to `null`; a failed read rejects for every caller, which each handles as before.+ */+export function createViewableSubagentLoader<TAgent>({+ getAgent,+ canView,+}: {+ getAgent: (agentId: string) => Promise<TAgent | null | undefined>;+ canView: (agent: TAgent, agentId: string) => Promise<boolean>;+}): (agentId: string) => Promise<TAgent | null> {+ const loads = new Map<string, Promise<TAgent | null>>();+ return (agentId) => {+ let loading = loads.get(agentId);+ if (loading == null) {+ loading = getAgent(agentId).then(async (agent) =>+ agent != null && (await canView(agent, agentId)) ? agent : null,+ );+ loads.set(agentId, loading);+ }+ return loading;+ };+}++export interface SubagentCodeAvailability {+ codeEnvAvailable: boolean;+ statefulCodeSessions: boolean;+ codeExecutionContext?: CodeExecutionContext;+ /** Set when the subagent's machine has no usable workspace in this conversation. */+ codeWorkspaceUnavailable?: Exclude<CodeWorkspaceSelectionErrorReason, 'locked'>;+}++/**+ * Resolves a lazy subagent's code route for its descriptor. A subagent whose machine has no usable+ * workspace is reported unavailable, with code off, instead of failing its parent's turn; a locked+ * decision and every other error still propagate.+ */+export async function resolveSubagentCodeAvailability({+ agentId,+ codeEnvAvailable,+ statefulCodeSessions,+ resolveContext,+}: {+ agentId: string;+ codeEnvAvailable: boolean;+ statefulCodeSessions: boolean;+ resolveContext: () => Promise<CodeExecutionContext | undefined>;+}): Promise<SubagentCodeAvailability> {+ try {+ return { codeEnvAvailable, statefulCodeSessions, codeExecutionContext: await resolveContext() };+ } catch (error) {+ const codeWorkspaceUnavailable = getSubagentCodeWorkspaceUnavailableReason(error);+ if (!codeWorkspaceUnavailable) {+ throw error;+ }+ logger.warn('[resolveSubagentCodeAvailability] Subagent advertised without a code workspace', {+ agentId,+ reason: codeWorkspaceUnavailable,+ });+ return { codeEnvAvailable: false, statefulCodeSessions: false, codeWorkspaceUnavailable };+ }+}++/**+ * Keeps an unavailable subagent listed so its parent learns why, while its resolver rejects with+ * the same `CODE_WORKSPACE_UNAVAILABLE` error so it can never run.+ */+export function guardUnavailableSubagent<TContext, TConfig>({+ description,+ codeWorkspaceUnavailable,+ resolve,+}: {+ description?: string;+ codeWorkspaceUnavailable?: CodeWorkspaceSelectionErrorReason;+ resolve: (context: TContext) => Promise<TConfig>;+}): { description?: string; resolve: (context: TContext) => Promise<TConfig> } {+ if (!codeWorkspaceUnavailable) {+ return { description, resolve };+ }+ return {+ description: describeCodeWorkspaceUnavailableSubagent(description, codeWorkspaceUnavailable),+ resolve: async () => {+ throw new CodeWorkspaceSelectionError(codeWorkspaceUnavailable);+ },+ };+}diff --git a/packages/api/src/agents/runtime.ts b/packages/api/src/agents/runtime.tsindex 358e7947de..73a461cc38 100644--- a/packages/api/src/agents/runtime.ts+++ b/packages/api/src/agents/runtime.ts@@ -28,6 +28,8 @@ export interface AgentExecutionContext {chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;/** Shares in-flight hydration across concurrently initialized graph agents. */chatProjectFilesPromise?: Promise<TFile[]>;+ /** Subagents that run on their parent's machine this turn, keyed by saved agent ID. */+ codeWorkspaceInheritance?: ReadonlyMap<string, string>;}/** Creates the transport-free context at the existing HTTP adapter seam. */@@ -43,6 +45,7 @@ export function createAgentExecutionContext({chatProjectFiles,chatProjectContextResourcesPromise,chatProjectFilesPromise,+ codeWorkspaceInheritance,}: {user?: IUser;appConfig?: AppConfig;@@ -55,6 +58,7 @@ export function createAgentExecutionContext({chatProjectFiles?: TFile[];chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;chatProjectFilesPromise?: Promise<TFile[]>;+ codeWorkspaceInheritance?: ReadonlyMap<string, string>;}): AgentExecutionContext {const context: AgentExecutionContext = {user,@@ -68,6 +72,7 @@ export function createAgentExecutionContext({: {}),...(chatProjectFiles !== undefined ? { chatProjectFiles } : {}),...(chatProjectFilesPromise !== undefined ? { chatProjectFilesPromise } : {}),+ ...(codeWorkspaceInheritance !== undefined ? { codeWorkspaceInheritance } : {}),};if (hasResolvedConversation) {context.resolvedConversation = resolvedConversation ?? null;@@ -94,5 +99,6 @@ export function createRequestAgentExecutionContext(chatProjectFiles: req.chatProjectFiles,chatProjectContextResourcesPromise: req.chatProjectContextResourcesPromise,chatProjectFilesPromise: req.chatProjectFilesPromise,+ codeWorkspaceInheritance: req.codeWorkspaceInheritance,});}diff --git a/packages/api/src/code/config.ts b/packages/api/src/code/config.tsindex 8e293d2760..356995689a 100644--- a/packages/api/src/code/config.ts+++ b/packages/api/src/code/config.ts@@ -3,6 +3,7 @@ import {CODE_ENVIRONMENT_MOVE_VERSION,CODE_ENVIRONMENT_TRANSITION_VERSION,CODE_WORKSPACE_RECOVERY_VERSION,+ CODE_WORKSPACE_INHERITANCE_VERSION,EModelEndpoint,} from 'librechat-data-provider';import type { TStartupConfig } from 'librechat-data-provider';@@ -70,6 +71,15 @@ export function resolveCodeEnvironmentMoveCapabilities(};}+/** Subagent machine inheritance rides on the decision protocol that records the selections. */+export function resolveCodeWorkspaceInheritanceCapability(+ configuredDecisionVersion?: string,+): Pick<TStartupConfig, 'codeWorkspaceInheritanceVersion'> {+ return resolveCodeEnvironmentDecisionVersion(configuredDecisionVersion) == null+ ? {}+ : { codeWorkspaceInheritanceVersion: CODE_WORKSPACE_INHERITANCE_VERSION };+}+/** Enables the implicit managed route only after the versioned rollout is complete. */export function isImplicitStatefulCodeRouteAvailable(configuredVersion?: string,diff --git a/packages/api/src/code/errors.spec.ts b/packages/api/src/code/errors.spec.tsindex 2efac324f5..d59568427b 100644--- a/packages/api/src/code/errors.spec.ts+++ b/packages/api/src/code/errors.spec.ts@@ -1,6 +1,9 @@import { ErrorTypes } from 'librechat-data-provider';import {+ CodeWorkspaceSelectionError,getCodeWorkspaceSelectionErrorDetails,+ describeCodeWorkspaceUnavailableSubagent,+ getSubagentCodeWorkspaceUnavailableReason,shouldPersistCodeWorkspaceInitializationError,} from './errors';@@ -63,3 +66,36 @@ describe('shouldPersistCodeWorkspaceInitializationError', () => {).toBe(false);});});++describe('subagent workspace unavailability', () => {+ it.each(['required', 'invalid', 'worker_unavailable', 'unsupported', 'missing'] as const)(+ 'confines %s to the subagent',+ (reason) => {+ expect(+ getSubagentCodeWorkspaceUnavailableReason(new CodeWorkspaceSelectionError(reason)),+ ).toBe(reason);+ },+ );++ it('keeps a locked decision and unrelated errors fatal', () => {+ expect(+ getSubagentCodeWorkspaceUnavailableReason(new CodeWorkspaceSelectionError('locked')),+ ).toBeUndefined();+ expect(getSubagentCodeWorkspaceUnavailableReason(new Error('boom'))).toBeUndefined();+ expect(+ getSubagentCodeWorkspaceUnavailableReason({+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason: 'missing',+ }),+ ).toBeUndefined();+ });++ it('tells the parent why the subagent cannot run', () => {+ expect(describeCodeWorkspaceUnavailableSubagent('Reviews PRs.', 'required')).toBe(+ 'Reviews PRs.\n\nUnavailable in this conversation: Choose an attached workspace before using this agent.',+ );+ expect(describeCodeWorkspaceUnavailableSubagent(undefined, 'missing')).toMatch(+ /^Unavailable in this conversation: The selected workspace is no longer registered/,+ );+ });+});diff --git a/packages/api/src/code/errors.ts b/packages/api/src/code/errors.tsindex db30c013ca..6902605b20 100644--- a/packages/api/src/code/errors.ts+++ b/packages/api/src/code/errors.ts@@ -75,3 +75,25 @@ export function shouldPersistCodeWorkspaceInitializationError({!hasValidatedDecision);}++/**+ * Why a subagent cannot run on its machine in this conversation, when that need not fail the+ * parent's turn. A `locked` decision concerns the whole conversation, so it stays fatal.+ */+export function getSubagentCodeWorkspaceUnavailableReason(+ error: unknown,+): Exclude<CodeWorkspaceSelectionErrorReason, 'locked'> | undefined {+ if (!(error instanceof CodeWorkspaceSelectionError) || error.reason === 'locked') {+ return undefined;+ }+ return error.reason;+}++/** Tells the parent model up front that this subagent cannot run, and why. */+export function describeCodeWorkspaceUnavailableSubagent(+ description: string | undefined,+ reason: CodeWorkspaceSelectionErrorReason,+): string {+ const notice = `Unavailable in this conversation: ${codeWorkspaceSelectionErrorMessage(reason)}`;+ return description ? `${description}\n\n${notice}` : notice;+}diff --git a/packages/api/src/code/index.ts b/packages/api/src/code/index.tsindex 6bf116a5a1..45ac13a95f 100644--- a/packages/api/src/code/index.ts+++ b/packages/api/src/code/index.ts@@ -7,5 +7,6 @@ export * from './workspace';export * from './command';export * from './capabilities';export * from './decision';+export * from './inheritance';export * from './errors';export * from './instructions';diff --git a/packages/api/src/code/inheritance.spec.ts b/packages/api/src/code/inheritance.spec.tsnew file mode 100644index 0000000000..08b35163c4--- /dev/null+++ b/packages/api/src/code/inheritance.spec.ts@@ -0,0 +1,428 @@+import mongoose from 'mongoose';+import { Tools } from 'librechat-data-provider';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { agentSchema, createMethods } from '@librechat/data-schemas';+import type { CodeWorkspaceSelection } from 'librechat-data-provider';+import type { IAgent } from '@librechat/data-schemas';+import type { CodeWorkspaceInheritanceRoot, SubagentCodeRoutingAgent } from './inheritance';+import type { CodeEnvironmentConfig } from '~/agents/execution';+import { resolveSubagentCodeWorkspaceInheritance } from './inheritance';+import { resolveCodeExecutionContext } from '~/agents/execution';++const SKYNET = 'code-yuwoQAAPhY1WMaDD6oIk';+const LIA_RAG = 'code-LTc54AG4yNobYdXzQg7g';+const LIA = 'agent_ZwXQuP527oibHg8S2qNV3';+const REVIEWER = 'agent_lOztazCW3rucC9f9K8kS7';++const environments: CodeEnvironmentConfig[] = [SKYNET, LIA_RAG].map((id) => ({+ id,+ name: id,+ type: 'attached',+ owner: 'deployment',+ baseURL: `https://${id}.example.com/v1`,+ workerId: `worker-${id}`,+}));++/** Lia and the PR Reviewer share these saved code settings on demo. */+const demoCodeSettings = {+ tools: [Tools.execute_code],+ stateful_code_sessions: true,+ stateful_code_environment: 'user' as const,+ code_environment_id: SKYNET,+ code_environment_ids: [LIA_RAG],+ code_workspace_id: '',+};++/** What an older client seals after the user picks Lia's machine: only Lia owns it. */+const incident: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api' },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: [LIA] },+];++describe('resolveSubagentCodeWorkspaceInheritance', () => {+ let mongoServer: MongoMemoryServer;+ let methods: ReturnType<typeof createMethods>;+ const author = new mongoose.Types.ObjectId();+ const hidden = new Set<string>();++ const toRouting = (doc: IAgent): SubagentCodeRoutingAgent => ({+ id: doc.id,+ tools: doc.tools,+ stateful_code_sessions: doc.stateful_code_sessions,+ code_environment_id: doc.code_environment_id,+ code_environment_ids: doc.code_environment_ids,+ subagents: doc.subagents,+ });++ const loadSubagent = jest.fn(async (agentId: string) => {+ if (hidden.has(agentId)) return null;+ const doc = await methods.getAgentWithVersionCount({ id: agentId });+ return doc == null ? null : toRouting(doc);+ });++ async function seed(+ id: string,+ overrides: Partial<Omit<IAgent, 'id'>> = {},+ ): Promise<SubagentCodeRoutingAgent> {+ return toRouting(+ await methods.createAgent({+ id,+ name: id,+ provider: 'openai',+ model: 'gpt-4.1',+ author,+ ...demoCodeSettings,+ ...overrides,+ }),+ );+ }++ function root(+ agent: SubagentCodeRoutingAgent,+ environmentId = LIA_RAG,+ ): CodeWorkspaceInheritanceRoot {+ return {+ id: agent.id,+ subagents: agent.subagents,+ statefulCodeSessions: true,+ codeExecutionContext: { environmentId, environmentType: 'attached' },+ };+ }++ function routeOf(+ agent: SubagentCodeRoutingAgent,+ selections: CodeWorkspaceSelection[],+ inheritedEnvironments?: ReadonlyMap<string, string>,+ ): string | undefined {+ return resolveCodeExecutionContext({+ statefulSessions: true,+ environmentId: agent.code_environment_id,+ environmentIds: agent.code_environment_ids,+ environments,+ allowEnvironmentSelection: true,+ workspaceSelections: selections,+ inheritedEnvironments,+ userId: 'user-1',+ agentId: agent.id,+ conversationId: 'chat-1',+ }).environmentId;+ }++ beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ if (!mongoose.models.Agent) mongoose.model('Agent', agentSchema);+ await mongoose.connect(mongoServer.getUri());+ methods = createMethods(mongoose);+ }, 20000);++ afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+ });++ beforeEach(async () => {+ await mongoose.models.Agent.deleteMany({});+ hidden.clear();+ loadSubagent.mockClear();+ });++ it("reproduces the PR Reviewer incident and routes the reviewer to Lia's workspace", async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ const reviewer = await seed(REVIEWER);+ expect(routeOf(reviewer, incident)).toBe(SKYNET);++ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });++ expect(inheritance).toEqual(new Map([[REVIEWER, LIA_RAG]]));+ expect(routeOf(reviewer, incident, inheritance)).toBe(LIA_RAG);+ expect(loadSubagent).toHaveBeenCalledTimes(1);+ });++ it('derives the same routes on every replay without touching the sealed decision', async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ await seed(REVIEWER);+ const sealed = structuredClone(incident);+ const resolve = () =>+ resolveSubagentCodeWorkspaceInheritance({+ selections: sealed,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(await resolve()).toEqual(await resolve());+ expect(sealed).toEqual(incident);+ });++ it("keeps a child on its own default when it may not use the parent's machine", async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ const reviewer = await seed(REVIEWER, { code_environment_ids: [] });+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.size).toBe(0);+ expect(routeOf(reviewer, incident, inheritance)).toBe(SKYNET);+ });++ it('keeps per-chat choice off when the deployment ceiling disables it', async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ await seed(REVIEWER);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: false,+ codeExecutionAvailable: true,+ });+ expect(inheritance.size).toBe(0);+ });++ it("does not inherit a machine outside the principal's environment ACL", async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ await seed(REVIEWER);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments: environments.filter(({ id }) => id !== LIA_RAG),+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.size).toBe(0);+ });++ it('lets an explicit assignment for the child win', async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ const reviewer = await seed(REVIEWER);+ const explicit = [{ ...incident[0], agentIds: [REVIEWER] }, incident[1]];+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: explicit,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.size).toBe(0);+ expect(routeOf(reviewer, explicit, inheritance)).toBe(SKYNET);+ });++ it('never walks through a subagent the principal cannot view', async () => {+ const middle = 'agent_hidden_planner';+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [middle] } });+ await seed(middle, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ await seed(REVIEWER);+ hidden.add(middle);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.size).toBe(0);+ expect(loadSubagent).not.toHaveBeenCalledWith(REVIEWER);+ });++ it('follows nested subagents and ignores disabled subagent lists', async () => {+ const verifier = 'agent_finding_verifier';+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ await seed(REVIEWER, { subagents: { enabled: true, agent_ids: [verifier] } });+ await seed(verifier);+ const nested = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(nested).toEqual(+ new Map([+ [REVIEWER, LIA_RAG],+ [verifier, LIA_RAG],+ ]),+ );++ const disabled = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [{ ...root(lia), subagents: { enabled: false, agent_ids: [REVIEWER] } }],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(disabled.size).toBe(0);+ });++ it('routes the members of a spawned subagent graph with their parent', async () => {+ const verifier = 'agent_finding_verifier';+ const lia = await seed(LIA, {+ subagents: {+ enabled: true,+ graphs: [+ {+ type: 'review-team',+ name: 'Review team',+ description: 'Reviews and verifies findings',+ agent_ids: [REVIEWER, verifier],+ edges: [],+ entry_agent_id: REVIEWER,+ result_agent_id: verifier,+ },+ ],+ },+ });+ await seed(REVIEWER);+ await seed(verifier);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance).toEqual(+ new Map([+ [REVIEWER, LIA_RAG],+ [verifier, LIA_RAG],+ ]),+ );+ });++ it('counts only admitted subagents toward the node limit', async () => {+ const verifier = 'agent_finding_verifier';+ const stale = Array.from({ length: 49 }, (_, index) => `agent_deleted_${index}`);+ const lia = await seed(LIA, {+ subagents: { enabled: true, agent_ids: [...stale, REVIEWER] },+ });+ await seed(REVIEWER, { subagents: { enabled: true, agent_ids: [verifier] } });+ await seed(verifier);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.get(verifier)).toBe(LIA_RAG);+ });++ it('never re-routes a saved agent that is also a parallel root', async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ const reviewer = await seed(REVIEWER);+ const inheritance = await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [root(lia), root({ ...reviewer, id: `${REVIEWER}____1` }, SKYNET)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(inheritance.has(REVIEWER)).toBe(false);+ expect(loadSubagent).not.toHaveBeenCalled();+ });++ it('reads nothing past the node limit', async () => {+ const children = Array.from({ length: 50 }, (_, index) => `agent_child_${index}`);+ const load = jest.fn(+ async (agentId: string): Promise<SubagentCodeRoutingAgent> => ({+ id: agentId,+ ...demoCodeSettings,+ subagents: { enabled: true, agent_ids: [`${agentId}_leaf`] },+ }),+ );+ await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [+ {+ id: LIA,+ subagents: { enabled: true, agent_ids: children },+ statefulCodeSessions: true,+ codeExecutionContext: { environmentId: LIA_RAG, environmentType: 'attached' },+ },+ ],+ loadSubagent: load,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(load).toHaveBeenCalledTimes(50);+ });++ it('keeps loading missing subagents in parallel batches near the node limit', async () => {+ const admittedIds = Array.from({ length: 49 }, (_, index) => `agent_child_${index}`);+ const missing = Array.from({ length: 40 }, (_, index) => `agent_missing_${index}`);+ let inFlight = 0;+ let peak = 0;+ const load = jest.fn(async (agentId: string): Promise<SubagentCodeRoutingAgent | null> => {+ inFlight++;+ peak = Math.max(peak, inFlight);+ await new Promise((resolve) => setImmediate(resolve));+ inFlight--;+ if (agentId.startsWith('agent_missing_')) return null;+ return {+ id: agentId,+ ...demoCodeSettings,+ subagents: agentId === admittedIds[0] ? { enabled: true, agent_ids: missing } : undefined,+ };+ });+ await resolveSubagentCodeWorkspaceInheritance({+ selections: incident,+ roots: [+ {+ id: LIA,+ subagents: { enabled: true, agent_ids: admittedIds },+ statefulCodeSessions: true,+ codeExecutionContext: { environmentId: LIA_RAG, environmentType: 'attached' },+ },+ ],+ loadSubagent: load,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable: true,+ });+ expect(load).toHaveBeenCalledTimes(admittedIds.length + missing.length);+ expect(peak).toBeGreaterThan(1);+ });++ it('reads nothing when the run cannot use stateful code or holds no selection', async () => {+ const lia = await seed(LIA, { subagents: { enabled: true, agent_ids: [REVIEWER] } });+ for (const [selections, codeExecutionAvailable] of [+ [incident, false],+ [[], true],+ [undefined, true],+ ] as const) {+ expect(+ (+ await resolveSubagentCodeWorkspaceInheritance({+ selections,+ roots: [root(lia)],+ loadSubagent,+ environments,+ allowEnvironmentSelection: true,+ codeExecutionAvailable,+ })+ ).size,+ ).toBe(0);+ }+ expect(loadSubagent).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/code/inheritance.ts b/packages/api/src/code/inheritance.tsnew file mode 100644index 0000000000..5ebac6af53--- /dev/null+++ b/packages/api/src/code/inheritance.ts@@ -0,0 +1,167 @@+import {+ Tools,+ MAX_SUBAGENT_DEPTH,+ MAX_SUBAGENT_GRAPH_NODES,+ stripAgentIdSuffix,+ isCodeWorkspaceSelections,+ resolveCodeWorkspaceInheritance,+} from 'librechat-data-provider';+import type { Agent, CodeWorkspaceRoutingAgent } from 'librechat-data-provider';+import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';+import {+ isExecutableAttachedEnvironment,+ resolveAgentCodeEnvironmentRouting,+} from '~/agents/execution';++type SpawnConfig = Pick<NonNullable<Agent['subagents']>, 'enabled' | 'agent_ids'> & {+ graphs?: ReadonlyArray<+ Pick<NonNullable<NonNullable<Agent['subagents']>['graphs']>[number], 'agent_ids'>+ >;+};++/** Near the node limit, missing or unviewable IDs still load in parallel; the injected loader+ * bounds actual concurrency, and at most this many reads land past the limit. */+const MIN_LOAD_BATCH = 8;++/** The saved fields of a subagent that decide where it runs code. */+export type SubagentCodeRoutingAgent = Pick<+ Agent,+ 'id' | 'tools' | 'stateful_code_sessions' | 'code_environment_id' | 'code_environment_ids'+> & { subagents?: SpawnConfig | null };++/** An initialized root of the run, whose machine is already resolved. */+export type CodeWorkspaceInheritanceRoot = Pick<SubagentCodeRoutingAgent, 'id' | 'subagents'> & {+ statefulCodeSessions?: boolean;+ codeExecutionContext?: Pick<CodeExecutionContext, 'environmentId' | 'environmentType'>;+};++/** Saved agents this agent may spawn: explicit subagents and the members of its subagent graphs.+ * Self-spawns already share their parent's route. */+export function getSpawnableSubagentIds(+ agent: Pick<SubagentCodeRoutingAgent, 'id' | 'subagents'>,+): string[] {+ const subagents = agent.subagents;+ if (subagents?.enabled !== true) {+ return [];+ }+ const ids = [+ ...(Array.isArray(subagents.agent_ids) ? subagents.agent_ids : []),+ ...(subagents.graphs ?? []).flatMap((graph) =>+ Array.isArray(graph?.agent_ids) ? graph.agent_ids : [],+ ),+ ];+ return [+ ...new Set(+ ids.filter((id): id is string => typeof id === 'string' && id.length > 0 && id !== agent.id),+ ),+ ];+}++/** Keyed by saved ID: a parallel root's runtime ID (`id____1`) must still mark that agent a root. */+function toRootRoutingAgent(root: CodeWorkspaceInheritanceRoot): CodeWorkspaceRoutingAgent {+ const context = root.codeExecutionContext;+ return {+ id: stripAgentIdSuffix(root.id),+ routesCode: root.statefulCodeSessions === true,+ allowSelection: false,+ subagentIds: getSpawnableSubagentIds(root),+ resolvedEnvironmentId:+ context?.environmentType === 'attached' ? (context.environmentId ?? null) : null,+ };+}++function toSubagentRoutingAgent(+ agent: SubagentCodeRoutingAgent,+ environments: readonly CodeEnvironmentConfig[] | undefined,+ allowEnvironmentSelection: boolean | undefined,+): CodeWorkspaceRoutingAgent {+ const { defaultEnvironment, allowSelection } = resolveAgentCodeEnvironmentRouting({+ environmentId: agent.code_environment_id,+ environmentIds: agent.code_environment_ids,+ environments,+ allowEnvironmentSelection,+ });+ return {+ id: agent.id,+ routesCode:+ agent.stateful_code_sessions === true && agent.tools?.includes(Tools.execute_code) === true,+ environmentId: agent.code_environment_id ?? defaultEnvironment?.id,+ environmentIds: agent.code_environment_ids,+ allowSelection,+ subagentIds: getSpawnableSubagentIds(agent),+ };+}++/**+ * Derives, once per request, which subagents run on their parent's attached machine. Each+ * routing site passes the result to `resolveCodeExecutionContext`, so lazy descriptors, child+ * initialization and execution-time tool loads agree on one route per subagent.+ *+ * `loadSubagent` must return only agents the principal may view, and should share its results+ * with the run's own subagent loading. It stays within the subagent depth limit and stops once+ * more agents are admitted than the node limit allows; graph construction reports either.+ */+export async function resolveSubagentCodeWorkspaceInheritance({+ selections,+ roots,+ loadSubagent,+ environments,+ allowEnvironmentSelection,+ codeExecutionAvailable,+}: {+ selections: unknown;+ roots: readonly CodeWorkspaceInheritanceRoot[];+ loadSubagent: (agentId: string) => Promise<SubagentCodeRoutingAgent | null | undefined>;+ environments?: readonly CodeEnvironmentConfig[];+ allowEnvironmentSelection?: boolean;+ /** The run may use stateful code at all: capability, role grant and deployment switches. */+ codeExecutionAvailable: boolean;+}): Promise<Map<string, string>> {+ if (!codeExecutionAvailable || !isCodeWorkspaceSelections(selections) || !selections.length) {+ return new Map();+ }+ const agents = new Map<string, CodeWorkspaceRoutingAgent>();+ for (const root of roots) {+ const node = toRootRoutingAgent(root);+ if (!agents.has(node.id)) agents.set(node.id, node);+ }+ const rootIds = [...agents.keys()];+ let frontier = [...agents.values()].flatMap(({ subagentIds }) => subagentIds ?? []);+ const attempted = new Set<string>();+ /** Like graph construction, only admitted agents count toward the node limit, and reading stops+ * once it is reached: graph construction rejects a graph that admits more. */+ let admitted = 0;+ for (let depth = 1; depth <= MAX_SUBAGENT_DEPTH && frontier.length > 0; depth++) {+ const ids = [...new Set(frontier)].filter((id) => !agents.has(id) && !attempted.has(id));+ frontier = [];+ for (let start = 0; start < ids.length && admitted < MAX_SUBAGENT_GRAPH_NODES; ) {+ const batch = ids.slice(+ start,+ start + Math.max(MAX_SUBAGENT_GRAPH_NODES - admitted, MIN_LOAD_BATCH),+ );+ start += batch.length;+ batch.forEach((id) => attempted.add(id));+ const loaded = await Promise.all(batch.map((id) => loadSubagent(id).catch(() => null)));+ for (let index = 0; index < batch.length; index++) {+ const agent = loaded[index];+ if (agent == null) continue;+ admitted++;+ const node = toSubagentRoutingAgent(+ { ...agent, id: batch[index] },+ environments,+ allowEnvironmentSelection,+ );+ agents.set(node.id, node);+ frontier.push(...(node.subagentIds ?? []));+ }+ }+ if (admitted >= MAX_SUBAGENT_GRAPH_NODES) break;+ }+ return resolveCodeWorkspaceInheritance({+ selections,+ rootIds,+ agents,+ isAttachedEnvironment: (environmentId) =>+ isExecutableAttachedEnvironment(environmentId, environments),+ });+}diff --git a/packages/api/src/types/http.ts b/packages/api/src/types/http.tsindex 8f9d1682ee..ac1d6c7613 100644--- a/packages/api/src/types/http.ts+++ b/packages/api/src/types/http.ts@@ -55,6 +55,9 @@ export type ServerRequest = Request<unknown, unknown, RequestBody> & {chatProjectFilesPromise?: Promise<TFile[]>;/** Internal opt-in marker for conversation graph agent initialization. */chatProjectContextEnabled?: boolean;+ /** Subagents that run on their parent's attached machine this turn, keyed by saved agent ID.+ * Derived per request from the sealed decision and never persisted. */+ codeWorkspaceInheritance?: ReadonlyMap<string, string>;authStrategy?: string;/** Trusted snapshot used to keep a request-scoped override out of saved conversation defaults. */reasoningOverrideBase?: {diff --git a/packages/data-provider/src/code/inheritance.spec.ts b/packages/data-provider/src/code/inheritance.spec.tsnew file mode 100644index 0000000000..b782775f23--- /dev/null+++ b/packages/data-provider/src/code/inheritance.spec.ts@@ -0,0 +1,427 @@+import type { CodeWorkspaceRoutingAgent, CodeWorkspaceSelection } from './workspace';+import { resolveCodeEnvironmentSelection, resolveCodeWorkspaceInheritance } from './workspace';+import { appendAgentIdSuffix } from '../agents/identity';++const SKYNET = 'code-skynet';+const LIA_RAG = 'code-lia-rag';+const SPARE = 'code-spare';+const attached = new Set([SKYNET, LIA_RAG, SPARE]);+const isAttachedEnvironment = (id: string): boolean => attached.has(id);++function agent(+ id: string,+ overrides: Partial<CodeWorkspaceRoutingAgent> = {},+): CodeWorkspaceRoutingAgent {+ return {+ id,+ routesCode: true,+ environmentId: SKYNET,+ environmentIds: [LIA_RAG],+ allowSelection: true,+ ...overrides,+ };+}++function graph(...agents: CodeWorkspaceRoutingAgent[]): Map<string, CodeWorkspaceRoutingAgent> {+ return new Map(agents.map((entry) => [entry.id, entry]));+}++function route(+ entry: CodeWorkspaceRoutingAgent,+ selections: CodeWorkspaceSelection[],+ inheritance: ReadonlyMap<string, string>,+): ReturnType<typeof resolveCodeEnvironmentSelection> {+ return resolveCodeEnvironmentSelection({+ agentId: entry.id,+ environmentId: entry.environmentId,+ environmentIds: entry.environmentIds,+ allowSelection: entry.allowSelection,+ selections,+ inheritedEnvironmentId: inheritance.get(entry.id),+ });+}++describe('subagent machine inheritance', () => {+ const lia = agent('lia', { subagentIds: ['reviewer'] });+ const reviewer = agent('reviewer');+ /** The demo incident: Lia moved to her RAG machine, the reviewer stayed on Code API's checkout. */+ const incident: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api' },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ ];++ it("routes the reviewer to Lia's machine instead of its own default", () => {+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(new Map([['reviewer', LIA_RAG]]));+ expect(route(reviewer, incident, new Map())).toEqual({ valid: true, environmentId: SKYNET });+ expect(route(reviewer, incident, inheritance)).toEqual({+ valid: true,+ environmentId: LIA_RAG,+ });+ expect(route(lia, incident, inheritance)).toEqual({ valid: true, environmentId: LIA_RAG });+ });++ it('routes a child with no selection of its own instead of rejecting it', () => {+ const selections = [{ environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] }];+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment,+ });+ expect(route(reviewer, selections, new Map())).toEqual({ valid: false });+ expect(route(reviewer, selections, inheritance)).toEqual({+ valid: true,+ environmentId: LIA_RAG,+ });+ });++ it('matches the stable owner key for a parallel runtime agent ID', () => {+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment,+ });+ expect(+ resolveCodeEnvironmentSelection({+ agentId: appendAgentIdSuffix('reviewer', 1),+ environmentId: SKYNET,+ environmentIds: [LIA_RAG],+ allowSelection: true,+ selections: incident,+ inheritedEnvironmentId: inheritance.get('reviewer'),+ }),+ ).toEqual({ valid: true, environmentId: LIA_RAG });+ });++ it("keeps a child on its own default when the parent's machine is not on its allowlist", () => {+ const narrow = agent('reviewer', { environmentIds: [SPARE] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(lia, narrow),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ expect(route(narrow, incident, inheritance)).toEqual({ valid: true, environmentId: SKYNET });+ });++ it('never applies an allowlist where per-chat machine choice does not apply', () => {+ const fixed = agent('reviewer', { allowSelection: false });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(lia, fixed),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ expect(+ resolveCodeEnvironmentSelection({+ agentId: 'reviewer',+ environmentId: SKYNET,+ environmentIds: [LIA_RAG],+ allowSelection: false,+ selections: incident,+ inheritedEnvironmentId: LIA_RAG,+ }),+ ).toEqual({ valid: true, environmentId: SKYNET });+ });++ it('lets an explicit assignment for the child win over its parent', () => {+ const selections: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api', agentIds: ['reviewer'] },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ ];+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ expect(+ resolveCodeEnvironmentSelection({+ agentId: 'reviewer',+ environmentId: SKYNET,+ environmentIds: [LIA_RAG],+ allowSelection: true,+ selections,+ inheritedEnvironmentId: LIA_RAG,+ }),+ ).toEqual({ valid: true, environmentId: SKYNET });+ });++ it('does not inherit a machine the principal cannot use', () => {+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment: (id) => id !== LIA_RAG,+ });+ expect(inheritance.size).toBe(0);+ });++ it('does not inherit a machine the conversation never selected', () => {+ const parent = agent('lia', { subagentIds: ['reviewer'], resolvedEnvironmentId: LIA_RAG });+ const selections = [{ environmentId: SKYNET, workspaceId: 'code-api' }];+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(parent, reviewer),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ expect(+ resolveCodeEnvironmentSelection({+ agentId: 'reviewer',+ environmentId: SKYNET,+ environmentIds: [LIA_RAG],+ allowSelection: true,+ selections,+ inheritedEnvironmentId: LIA_RAG,+ }),+ ).toEqual({ valid: true, environmentId: SKYNET });+ });++ it('leaves the single legacy selection routing unchanged', () => {+ const selections = [{ environmentId: LIA_RAG, workspaceId: 'agents' }];+ const parent = agent('lia', {+ environmentId: LIA_RAG,+ environmentIds: [],+ subagentIds: ['a', 'b'],+ });+ const allowed = agent('a');+ const disallowed = agent('b', { environmentIds: [SPARE] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(parent, allowed, disallowed),+ isAttachedEnvironment,+ });+ for (const entry of [parent, allowed, disallowed]) {+ expect(route(entry, selections, inheritance)).toEqual(route(entry, selections, new Map()));+ }+ expect(route(allowed, selections, inheritance)).toEqual({+ valid: true,+ environmentId: LIA_RAG,+ });+ expect(route(disallowed, selections, inheritance)).toEqual({ valid: false });+ });++ it('passes a machine through a subagent that does not run code', () => {+ const planner = agent('planner', { routesCode: false, subagentIds: ['coder'] });+ const parent = agent('lia', { subagentIds: ['planner'] });+ const coder = agent('coder');+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, planner, coder),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(new Map([['coder', LIA_RAG]]));+ });++ it('follows a chain of inherited routes', () => {+ const parent = agent('lia', { subagentIds: ['reviewer'] });+ const middle = agent('reviewer', { subagentIds: ['verifier'] });+ const leaf = agent('verifier');+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, middle, leaf),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(+ new Map([+ ['reviewer', LIA_RAG],+ ['verifier', LIA_RAG],+ ]),+ );+ });++ it('keeps a subagent on its own route when its parents disagree', () => {+ const selections: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api' },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ { environmentId: SPARE, workspaceId: 'spare', agentIds: ['other'] },+ ];+ const left = agent('lia', { subagentIds: ['shared'] });+ const right = agent('other', { environmentIds: [SPARE], subagentIds: ['shared'] });+ const shared = agent('shared', { environmentIds: [LIA_RAG, SPARE] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia', 'other'],+ agents: graph(left, right, shared),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ });++ it('keeps its own route when a deeper spawning path runs on another machine', () => {+ const selections: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api' },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ { environmentId: SPARE, workspaceId: 'spare', agentIds: ['other'] },+ ];+ const direct = agent('lia', { subagentIds: ['shared'] });+ const other = agent('other', { environmentIds: [SPARE], subagentIds: ['planner'] });+ const planner = agent('planner', { routesCode: false, subagentIds: ['shared'] });+ const shared = agent('shared', { environmentIds: [LIA_RAG, SPARE] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia', 'other'],+ agents: graph(direct, other, planner, shared),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ });++ it('inherits when every spawning path, at any depth, runs on the same machine', () => {+ const parent = agent('lia', { subagentIds: ['shared', 'planner'] });+ const planner = agent('planner', { routesCode: false, subagentIds: ['shared'] });+ const shared = agent('shared');+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, planner, shared),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(new Map([['shared', LIA_RAG]]));+ });++ it('ignores a spawn back-edge the run prunes, as the descriptor tree does', () => {+ const parent = agent('lia', { subagentIds: ['left'] });+ const left = agent('left', { subagentIds: ['right'] });+ const right = agent('right', { subagentIds: ['left'] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, left, right),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(+ new Map([+ ['left', LIA_RAG],+ ['right', LIA_RAG],+ ]),+ );+ });++ it("routes subagents that spawn each other with their outside parent's machine", () => {+ const parent = agent('lia', { subagentIds: ['left', 'right'] });+ const left = agent('left', { subagentIds: ['right'] });+ const right = agent('right', { subagentIds: ['left'] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, left, right),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(+ new Map([+ ['left', LIA_RAG],+ ['right', LIA_RAG],+ ]),+ );+ });++ it('settles independent mutually spawning groups separately', () => {+ const selections: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api' },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ { environmentId: SPARE, workspaceId: 'spare', agentIds: ['other'] },+ ];+ const lia = agent('lia', { subagentIds: ['a1', 'a2'] });+ const other = agent('other', { environmentIds: [SPARE], subagentIds: ['b1', 'b2'] });+ const pair = (id: string, peer: string) =>+ agent(id, { environmentIds: [LIA_RAG, SPARE], subagentIds: [peer] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia', 'other'],+ agents: graph(+ lia,+ other,+ pair('a1', 'a2'),+ pair('a2', 'a1'),+ pair('b1', 'b2'),+ pair('b2', 'b1'),+ ),+ isAttachedEnvironment,+ });+ expect(inheritance).toEqual(+ new Map([+ ['a1', LIA_RAG],+ ['a2', LIA_RAG],+ ['b1', SPARE],+ ['b2', SPARE],+ ]),+ );+ });++ it('keeps a mutually spawning group on its own routes when one member is assigned elsewhere', () => {+ const selections: CodeWorkspaceSelection[] = [+ { environmentId: SKYNET, workspaceId: 'code-api', agentIds: ['right'] },+ { environmentId: LIA_RAG, workspaceId: 'agents', agentIds: ['lia'] },+ ];+ const parent = agent('lia', { subagentIds: ['left', 'right'] });+ const left = agent('left', { subagentIds: ['right'] });+ const right = agent('right', { subagentIds: ['left'] });+ const inheritance = resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(parent, left, right),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ });++ it('never re-routes a root, even when another root lists it as a subagent', () => {+ const parent = agent('lia', { subagentIds: ['peer'] });+ const peer = agent('peer');+ const inheritance = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia', 'peer'],+ agents: graph(parent, peer),+ isAttachedEnvironment,+ });+ expect(inheritance.size).toBe(0);+ });++ it('derives the same routes regardless of traversal order', () => {+ const parent = agent('lia', { subagentIds: ['reviewer', 'verifier'] });+ const second = agent('verifier', { environmentIds: [SPARE] });+ const forward = resolveCodeWorkspaceInheritance({+ selections: incident,+ rootIds: ['lia'],+ agents: graph(parent, reviewer, second),+ isAttachedEnvironment,+ });+ const reversed = resolveCodeWorkspaceInheritance({+ selections: [...incident].reverse(),+ rootIds: ['lia'],+ agents: graph(second, reviewer, agent('lia', { subagentIds: ['verifier', 'reviewer'] })),+ isAttachedEnvironment,+ });+ expect(Array.from(forward).sort()).toEqual(Array.from(reversed).sort());+ expect(forward).toEqual(new Map([['reviewer', LIA_RAG]]));+ });++ it('ignores an empty or invalid decision', () => {+ for (const selections of [undefined, [], [{ environmentId: '' }]]) {+ expect(+ resolveCodeWorkspaceInheritance({+ selections,+ rootIds: ['lia'],+ agents: graph(lia, reviewer),+ isAttachedEnvironment,+ }).size,+ ).toBe(0);+ }+ });+});diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.tsindex c18de19550..417ed87c30 100644--- a/packages/data-provider/src/code/workspace.ts+++ b/packages/data-provider/src/code/workspace.ts@@ -39,6 +39,11 @@ export const CODE_ENVIRONMENT_MOVE_VERSION = 1 as const;export const CODE_ENVIRONMENT_TRANSITION_VERSION = 2 as const;/** Additive capability for replacing a missing workspace without disabling moves in V1 clients. */export const CODE_WORKSPACE_RECOVERY_VERSION = 1 as const;+/**+ * API/client protocol for subagents that follow their parent's machine. A composer mirrors the+ * routing only when this is advertised, so it never omits a workspace an older API still needs.+ */+export const CODE_WORKSPACE_INHERITANCE_VERSION = 1 as const;export const CODE_WORKSPACE_OPERATIONS = ['read_file','search_text',@@ -238,20 +243,42 @@ export function canonicalizeCodeWorkspaceSelections(.sort((left, right) => left.environmentId.localeCompare(right.environmentId));}+/** Whether an agent may run on `candidate`: its own default, or a machine its author allowlisted+ * where per-chat machine choice applies to it. */+function isAllowedCodeEnvironment(+ candidate: string,+ environmentId: string | null | undefined,+ environmentIds: readonly string[] | undefined,+ allowSelection: boolean | undefined,+): boolean {+ return (+ candidate === environmentId ||+ (allowSelection === true && environmentIds?.includes(candidate) === true)+ );+}+/** Resolves an agent's default or its chat-owned machine choice. Callers still authorize the- * resolved ID against their principal-scoped environment list and verify live capabilities. */+ * resolved ID against their principal-scoped environment list and verify live capabilities.+ *+ * Precedence: an explicit owner of a selection, then the machine inherited from the parent that+ * spawned this subagent (see `resolveCodeWorkspaceInheritance`), then the agent's own default,+ * then a single legacy selection. Inheritance is a separate input rather than an added owner: an+ * owner on a legacy selection would stop it serving as every other agent's fallback. */export function resolveCodeEnvironmentSelection({environmentId,environmentIds,agentId,allowSelection,selections,+ inheritedEnvironmentId,}: {environmentId?: string | null;environmentIds?: readonly string[];agentId?: string | null;allowSelection?: boolean;selections?: unknown;+ /** The parent's machine; applies only when the conversation selected it and this agent may use it. */+ inheritedEnvironmentId?: string | null;}): { valid: true; environmentId?: string | null } | { valid: false } {if (selections == null) return { valid: true, environmentId };if (!isCodeWorkspaceSelections(selections)) return { valid: false };@@ -269,6 +296,18 @@ export function resolveCodeEnvironmentSelection({? { valid: true, environmentId: owned.environmentId }: { valid: false };}+ if (+ inheritedEnvironmentId != null &&+ isAllowedCodeEnvironment(+ inheritedEnvironmentId,+ environmentId,+ environmentIds,+ allowSelection,+ ) &&+ selections.some((selection) => selection.environmentId === inheritedEnvironmentId)+ ) {+ return { valid: true, environmentId: inheritedEnvironmentId };+ }if (!allowSelection) return { valid: true, environmentId };const allowed = new Set(environmentIds ?? []);if (environmentId) allowed.add(environmentId);@@ -281,3 +320,245 @@ export function resolveCodeEnvironmentSelection({if (legacy.length !== 1) return { valid: false };return { valid: true, environmentId: legacy[0].environmentId };}++/** One agent of a run's graph, reduced to the fields machine routing reads. */+export interface CodeWorkspaceRoutingAgent {+ /** Saved agent ID, the key conversation ownership is recorded under. */+ id: string;+ /** Runs code on a stateful machine. An agent that does not passes its parent's machine on. */+ routesCode: boolean;+ /** Effective default machine: the agent's own, or the deployment default. */+ environmentId?: string | null;+ environmentIds?: readonly string[];+ /** Both the deployment ceiling and this agent's allowlist admit a per-chat machine choice. */+ allowSelection: boolean;+ /** Subagents this agent may spawn: explicit subagents and the members of its subagent graphs. */+ subagentIds?: readonly string[];+ /** Machine already resolved for this agent, such as an initialized root; `null` for none. */+ resolvedEnvironmentId?: string | null;+}++/**+ * Subagents default to the attached machine, and so the workspace, their parent runs on. A+ * subagent inherits only when every one of these holds:+ * - no selection names it as an explicit owner, so a choice made for it still wins;+ * - the parent's machine is its own default or on its author's allowlist where per-chat choice+ * applies to it;+ * - `isAttachedEnvironment` admits that machine, which callers scope to the principal;+ * - the conversation's decision already selected a workspace on that machine.+ *+ * Inheritance is derived from the sealed decision and the agents' current configuration, the same+ * inputs every other route reads, so the same decision and graph always route the same way. A run+ * resolves one route per saved agent, so a subagent considers every agent that can spawn it, at any+ * depth: it inherits only when they all run on the same machine, and otherwise keeps its own route.+ * A subagent that does not run code passes its parent's machine on to its own subagents. Subagents+ * that spawn each other follow the machine of every parent outside that group only when it routes+ * each of them there.+ *+ * @returns Saved agent ID to inherited environment ID, for subagents whose route changes.+ */+export function resolveCodeWorkspaceInheritance({+ selections,+ rootIds,+ agents,+ isAttachedEnvironment,+}: {+ selections: unknown;+ rootIds: readonly string[];+ agents: ReadonlyMap<string, CodeWorkspaceRoutingAgent>;+ isAttachedEnvironment: (environmentId: string) => boolean;+}): Map<string, string> {+ const inherited = new Map<string, string>();+ if (!isCodeWorkspaceSelections(selections) || selections.length === 0) return inherited;+ const selected = new Set(selections.map(({ environmentId }) => environmentId));+ const owned = new Set(selections.flatMap(({ agentIds }) => agentIds ?? []));+ const routes = new Map<string, string | undefined>();++ const routeOf = (+ agent: CodeWorkspaceRoutingAgent,+ parentRoute: string | undefined,+ ): string | undefined => {+ if (!agent.routesCode) return parentRoute;+ const resolved =+ agent.resolvedEnvironmentId !== undefined+ ? agent.resolvedEnvironmentId+ : resolveRoutedEnvironmentId(agent, selections, inherited.get(agent.id));+ return resolved != null && isAttachedEnvironment(resolved) ? resolved : undefined;+ };+ const inherits = (agent: CodeWorkspaceRoutingAgent, candidate: string): boolean =>+ agent.routesCode &&+ agent.resolvedEnvironmentId === undefined &&+ candidate !== agent.environmentId &&+ !owned.has(agent.id) &&+ selected.has(candidate) &&+ isAllowedCodeEnvironment(+ candidate,+ agent.environmentId,+ agent.environmentIds,+ agent.allowSelection,+ ) &&+ isAttachedEnvironment(candidate);++ const roots = new Set(rootIds.filter((id) => agents.has(id)));+ const parents = collectSpawningParents(roots, agents);+ roots.forEach((id) =>+ routes.set(id, routeOf(agents.get(id) as CodeWorkspaceRoutingAgent, undefined)),+ );+ const resolve = (id: string, candidate: string | undefined): void => {+ const agent = agents.get(id) as CodeWorkspaceRoutingAgent;+ if (candidate != null && inherits(agent, candidate)) {+ inherited.set(id, candidate);+ }+ routes.set(id, routeOf(agent, candidate));+ };++ /** A group follows the single machine every outside parent runs on when that routes each member+ * there too; otherwise its members keep their own routes. */+ const resolveGroup = (members: string[]): void => {+ const group = new Set(members);+ const outside = new Set<string | undefined>();+ for (const id of members) {+ parents.get(id)?.forEach((parentId) => {+ if (!group.has(parentId)) outside.add(routes.get(parentId));+ });+ }+ const candidate = outside.size === 1 ? Array.from(outside)[0] : undefined;+ members.forEach((id) => resolve(id, candidate));+ if (candidate != null && members.some((id) => routes.get(id) !== candidate)) {+ members.forEach((id) => {+ inherited.delete(id);+ resolve(id, undefined);+ });+ }+ };++ let pending = Array.from(parents.keys());+ while (pending.length > 0) {+ const ready = pending.filter((id) =>+ Array.from(parents.get(id) ?? []).every((parentId) => routes.has(parentId)),+ );+ if (ready.length > 0) {+ for (const id of ready) {+ const candidates = new Set(+ Array.from(parents.get(id) ?? []).map((parentId) => routes.get(parentId)),+ );+ resolve(id, candidates.size === 1 ? Array.from(candidates)[0] : undefined);+ }+ } else {+ /** Every remaining agent waits on another, so some of them spawn each other. Each group of+ * mutually spawning agents whose outside parents are all resolved settles on its own. */+ const groups = findSettledSpawnGroups(pending, parents, routes);+ for (const members of groups.length > 0 ? groups : [pending]) {+ resolveGroup(members);+ }+ }+ pending = pending.filter((id) => !routes.has(id));+ }+ return inherited;+}++/**+ * Every agent that can spawn each subagent reachable from the roots. A run never spawns an agent+ * beneath itself, so `parent → child` counts only when some spawn path reaches the parent without+ * passing through the child.+ */+function collectSpawningParents(+ roots: ReadonlySet<string>,+ agents: ReadonlyMap<string, CodeWorkspaceRoutingAgent>,+): Map<string, Set<string>> {+ const parents = new Map<string, Set<string>>();+ const reachable = reachableFrom(roots, agents);+ reachable.forEach((parentId) => {+ for (const childId of agents.get(parentId)?.subagentIds ?? []) {+ if (roots.has(childId) || !agents.has(childId)) continue;+ if (!reachableFrom(roots, agents, childId).has(parentId)) continue;+ const childParents = parents.get(childId) ?? new Set<string>();+ childParents.add(parentId);+ parents.set(childId, childParents);+ }+ });+ return parents;+}++function reachableFrom(+ roots: ReadonlySet<string>,+ agents: ReadonlyMap<string, CodeWorkspaceRoutingAgent>,+ avoid?: string,+): Set<string> {+ const visited = new Set<string>(roots);+ const queue = Array.from(roots);+ for (let index = 0; index < queue.length; index++) {+ for (const childId of agents.get(queue[index])?.subagentIds ?? []) {+ if (childId === avoid || visited.has(childId) || !agents.has(childId)) continue;+ visited.add(childId);+ queue.push(childId);+ }+ }+ return visited;+}++/**+ * Groups of agents that spawn each other (strongly connected among the waiting agents) whose every+ * parent outside the group already has a route.+ */+function findSettledSpawnGroups(+ pending: readonly string[],+ parents: ReadonlyMap<string, ReadonlySet<string>>,+ routes: ReadonlyMap<string, string | undefined>,+): string[][] {+ const waiting = new Set(pending);+ const ancestors = new Map(pending.map((id) => [id, waitingAncestors(id, waiting, parents)]));+ const grouped = new Set<string>();+ const groups: string[][] = [];+ for (const id of pending) {+ if (grouped.has(id)) continue;+ const members = pending.filter(+ (other) =>+ other === id ||+ (ancestors.get(id)?.has(other) === true && ancestors.get(other)?.has(id) === true),+ );+ members.forEach((member) => grouped.add(member));+ const group = new Set(members);+ const settled = members.every((member) =>+ Array.from(parents.get(member) ?? []).every(+ (parentId) => group.has(parentId) || routes.has(parentId),+ ),+ );+ if (settled && (members.length > 1 || ancestors.get(id)?.has(id) === true)) {+ groups.push(members);+ }+ }+ return groups;+}++function waitingAncestors(+ id: string,+ waiting: ReadonlySet<string>,+ parents: ReadonlyMap<string, ReadonlySet<string>>,+): Set<string> {+ const seen = new Set<string>();+ const stack = Array.from(parents.get(id) ?? []);+ while (stack.length > 0) {+ const current = stack.pop() as string;+ if (!waiting.has(current) || seen.has(current)) continue;+ seen.add(current);+ stack.push(...Array.from(parents.get(current) ?? []));+ }+ return seen;+}++function resolveRoutedEnvironmentId(+ agent: CodeWorkspaceRoutingAgent,+ selections: CodeWorkspaceSelection[],+ inheritedEnvironmentId: string | undefined,+): string | null | undefined {+ const resolution = resolveCodeEnvironmentSelection({+ agentId: agent.id,+ environmentId: agent.environmentId,+ environmentIds: agent.environmentIds,+ allowSelection: agent.allowSelection,+ selections,+ inheritedEnvironmentId,+ });+ return resolution.valid ? resolution.environmentId : undefined;+}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 2388bcafb2..deb03f07ee 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -53,6 +53,7 @@ import {CODE_ENVIRONMENT_MOVE_VERSION,CODE_ENVIRONMENT_TRANSITION_VERSION,CODE_WORKSPACE_RECOVERY_VERSION,+ CODE_WORKSPACE_INHERITANCE_VERSION,MAX_AGENT_CODE_ENVIRONMENT_CHOICES,} from './code/workspace';import { ComponentTypes, SettingTypes, OptionTypes } from './generate';@@ -3067,6 +3068,9 @@ export type TStartupConfig = {/** Additive recovery support. Clients require this and the move capability before replacing* a missing workspace. Keeping it separate preserves exact-version checks in older clients. */codeWorkspaceRecoveryVersion?: typeof CODE_WORKSPACE_RECOVERY_VERSION;+ /** Subagents follow their parent's attached machine. Clients mirror that routing only when this+ * is advertised. */+ codeWorkspaceInheritanceVersion?: typeof CODE_WORKSPACE_INHERITANCE_VERSION;interface?: TInterfaceConfig;turnstile?: TTurnstileConfig;balance?: TBalanceConfig;