Skip to content

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

🪫 fix: Gate Programmatic Bash on Stateful Worker Capabilities (#15726)

Danny Avila968950a4bdb3
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index ac67315212..e7b121da11 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -18,6 +18,7 @@ const {
buildWebSearchContext,
buildImageToolContext,
buildToolClassification,
+ supportsProgrammaticCodeExecution,
getMissingCustomUserVars,
buildWebSearchDynamicContext,
getCodeApiAuthHeaders,
@@ -90,6 +91,7 @@ const {
domainParser,
} = require('./ActionService');
const {
+ getAppConfig,
getEndpointsConfig,
getMCPServerTools,
getCachedTools,
@@ -1288,6 +1290,9 @@ async function loadToolDefinitionsWrapper({
deferredToolsEnabled,
programmaticToolsEnabled,
codeExecutionEnabled,
+ codeExecutionContext: resolvedCodeExecutionContext,
+ codeEnvironments: appConfig?.endpoints?.agents?.statefulCodeSessions?.environments,
+ getAppConfig,
provider: agent.provider,
mcpServerNames,
rawServerNames: mcpRawServerNames,
@@ -1378,6 +1383,9 @@ async function loadToolDefinitionsWrapper({
deferredToolsEnabled,
programmaticToolsEnabled,
codeExecutionEnabled,
+ codeExecutionContext: resolvedCodeExecutionContext,
+ codeEnvironments: appConfig?.endpoints?.agents?.statefulCodeSessions?.environments,
+ getAppConfig,
provider: agent.provider,
mcpServerNames,
rawServerNames: mcpRawServerNames,
@@ -1738,6 +1746,8 @@ async function loadAgentTools({
deferredToolsEnabled,
programmaticToolsEnabled,
codeExecutionEnabled,
+ codeEnvironments: appConfig?.endpoints?.agents?.statefulCodeSessions?.environments,
+ getAppConfig,
authHeaders: () =>
codeExecutionAuthHeaders(
(bridgeWorkerId) => getCodeApiAuthHeaders(req, bridgeWorkerId),
@@ -2133,7 +2143,15 @@ async function loadToolsForExecution({
configurable.toolRegistry = toolRegistry;
}
- if (isPTC && toolRegistry) {
+ const canLoadPTC =
+ isPTC &&
+ toolRegistry != null &&
+ (await supportsProgrammaticCodeExecution(
+ codeExecutionContext,
+ req.config?.endpoints?.agents?.statefulCodeSessions?.environments,
+ getAppConfig,
+ ));
+ if (canLoadPTC) {
configurable.toolRegistry = toolRegistry;
try {
/**
@@ -2218,7 +2236,7 @@ async function loadToolsForExecution({
]);
let ptcOrchestratedToolNames = [];
- if (isPTC && toolRegistry) {
+ if (canLoadPTC) {
ptcOrchestratedToolNames = Array.from(toolRegistry.values())
.filter(
(toolDef) =>
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index 0d1a7d1eb7..fede6125f5 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -16,6 +16,7 @@ const {
} = require('librechat-data-provider');
const mockGetEndpointsConfig = jest.fn();
+const mockGetAppConfig = jest.fn();
const mockGetMCPServerTools = jest.fn();
const mockGetCachedTools = jest.fn();
const mockSendEvent = jest.fn();
@@ -59,6 +60,7 @@ const mockPrimeSearchFiles = jest.fn().mockResolvedValue({});
const mockPrimeCodeFiles = jest.fn().mockResolvedValue({});
jest.mock('~/server/services/Config', () => ({
getEndpointsConfig: (...args) => mockGetEndpointsConfig(...args),
+ getAppConfig: (...args) => mockGetAppConfig(...args),
getMCPServerTools: (...args) => mockGetMCPServerTools(...args),
getCachedTools: (...args) => mockGetCachedTools(...args),
}));
@@ -3013,6 +3015,128 @@ describe('ToolService - Action Capability Gating', () => {
);
});
+ it('does not lazily load PTC for an attached worker without confirmed stateful support', async () => {
+ const capabilities = [
+ AgentCapabilities.tools,
+ AgentCapabilities.programmatic_tools,
+ AgentCapabilities.execute_code,
+ AgentCapabilities.stateful_code_sessions,
+ ];
+ const req = createMockReq(capabilities);
+ req.config.endpoints.agents.statefulCodeSessions = {
+ environments: [
+ {
+ id: 'personal',
+ name: 'Personal',
+ type: 'attached',
+ owner: 'deployment',
+ baseURL: 'https://attached.example',
+ workerId: 'worker',
+ },
+ ],
+ };
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+ mockResolveCodeExecutionContext.mockImplementationOnce(
+ jest.requireActual('@librechat/api').resolveCodeExecutionContext,
+ );
+ const result = await loadToolsForExecution({
+ req,
+ res: {},
+ agent: {
+ id: 'agent_ptc',
+ tools: [Tools.execute_code],
+ stateful_code_sessions: true,
+ code_environment_id: 'personal',
+ },
+ toolNames: [Constants.BASH_PROGRAMMATIC_TOOL_CALLING],
+ toolRegistry: new Map(),
+ actionsEnabled: false,
+ });
+ expect(result.loadedTools.map((tool) => tool.name)).not.toContain(
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
+ );
+ });
+
+ it.each([
+ { statefulWorkspace: false, runtimes: ['bash'], supported: false },
+ { statefulWorkspace: true, runtimes: ['py'], supported: false },
+ { statefulWorkspace: true, runtimes: ['bash'], supported: true },
+ ])(
+ 'loads attached PTC using deployment credentials: stateful=$statefulWorkspace runtimes=$runtimes',
+ async ({ statefulWorkspace, runtimes, supported }) => {
+ const capabilities = [
+ AgentCapabilities.tools,
+ AgentCapabilities.programmatic_tools,
+ AgentCapabilities.execute_code,
+ AgentCapabilities.stateful_code_sessions,
+ ];
+ const req = createMockReq(capabilities);
+ const environment = {
+ id: 'personal',
+ name: 'Personal',
+ type: 'attached',
+ owner: 'deployment',
+ baseURL: 'https://attached.example',
+ workerId: `worker-${statefulWorkspace}-${runtimes[0]}`,
+ pairing: {
+ workerId: `worker-${statefulWorkspace}-${runtimes[0]}`,
+ tokenEnv: 'TEST_PTC_DEPLOYMENT_TOKEN',
+ },
+ };
+ req.config.endpoints.agents.statefulCodeSessions = { environments: [environment] };
+ mockGetAppConfig.mockResolvedValueOnce({
+ endpoints: { agents: { statefulCodeSessions: { environments: [environment] } } },
+ });
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+ mockResolveCodeExecutionContext.mockImplementationOnce(
+ jest.requireActual('@librechat/api').resolveCodeExecutionContext,
+ );
+ process.env.TEST_PTC_DEPLOYMENT_TOKEN = `deployment-token-${statefulWorkspace}`;
+ const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: environment.workerId,
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: { statefulWorkspace, sandboxProfile: 'native-srt', runtimes },
+ }),
+ ),
+ );
+ try {
+ const result = await loadToolsForExecution({
+ req,
+ res: {},
+ agent: {
+ id: 'agent_ptc',
+ tools: [Tools.execute_code],
+ stateful_code_sessions: true,
+ code_environment_id: 'personal',
+ },
+ toolNames: [Constants.BASH_PROGRAMMATIC_TOOL_CALLING],
+ toolRegistry: new Map(),
+ actionsEnabled: false,
+ });
+ expect(
+ result.loadedTools.some(
+ (tool) => tool.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
+ ),
+ ).toBe(supported);
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(fetchSpy).toHaveBeenCalledWith(
+ `https://attached.example/bridge/workers/${environment.workerId}/status`,
+ expect.objectContaining({
+ headers: { Authorization: `Bearer deployment-token-${statefulWorkspace}` },
+ }),
+ );
+ } finally {
+ fetchSpy.mockRestore();
+ delete process.env.TEST_PTC_DEPLOYMENT_TOKEN;
+ }
+ },
+ );
+
it('does not load PTC when programmatic tools capability is disabled', async () => {
const capabilities = [AgentCapabilities.tools, AgentCapabilities.execute_code];
const req = createMockReq(capabilities);
diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.ts
index 478ba5e5e2..989d0c3003 100644
--- a/packages/api/src/agents/execution.ts
+++ b/packages/api/src/agents/execution.ts
@@ -15,7 +15,10 @@ export const CODE_API_BRIDGE_WORKER_HEADER = 'X-LibreChat-Code-Worker-ID';
export type CodeExecutionProfile = 'default' | 'stateful';
export type CodeEnvironmentConfig = NonNullable<
NonNullable<TAgentsEndpoint['statefulCodeSessions']>['environments']
->[number];
+>[number] & {
+ /** Server-resolved control plane for a principal-owned attached environment. */
+ controlPlaneId?: string;
+};
export interface CodeExecutionContext {
baseUrl: string;
diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.ts
index b1e4b62543..0db156062d 100644
--- a/packages/api/src/code/bridge.spec.ts
+++ b/packages/api/src/code/bridge.spec.ts
@@ -35,6 +35,7 @@ describe('getCodeBridgeWorkerStatus', () => {
}),
).resolves.toEqual({
status: 'ready',
+ statefulWorkspace: true,
leaseExpiresInMs: 45_000,
sandboxProfile: 'native-srt',
runtimes: ['bash'],
diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.ts
index 8f5f8b713e..7d4aea1022 100644
--- a/packages/api/src/code/bridge.ts
+++ b/packages/api/src/code/bridge.ts
@@ -23,6 +23,7 @@ export type CodeBridgePairing = {
export type CodeBridgeWorkerStatus = {
status: 'offline' | 'starting' | 'ready';
leaseExpiresInMs?: number;
+ statefulWorkspace?: boolean;
sandboxProfile?: string;
runtimes?: string[];
operations?: string[];
@@ -199,6 +200,7 @@ export async function getCodeBridgeWorkerStatus({
ready?: unknown;
leaseExpiresInMs?: unknown;
capabilities?: {
+ statefulWorkspace?: unknown;
sandboxProfile?: unknown;
runtimes?: unknown;
workspaceTools?: { operations?: unknown };
@@ -228,7 +230,9 @@ export async function getCodeBridgeWorkerStatus({
!validLease ||
!validCapabilities ||
!validRuntimes ||
- !validOperations
+ !validOperations ||
+ (capabilities?.statefulWorkspace != null &&
+ typeof capabilities.statefulWorkspace !== 'boolean')
) {
throw new CodeBridgeStatusError('invalid');
}
@@ -238,6 +242,9 @@ export async function getCodeBridgeWorkerStatus({
}
return {
status: workerStatus,
+ ...(typeof capabilities?.statefulWorkspace === 'boolean'
+ ? { statefulWorkspace: capabilities.statefulWorkspace }
+ : {}),
...(typeof status.leaseExpiresInMs !== 'number'
? {}
: { leaseExpiresInMs: status.leaseExpiresInMs }),
diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.ts
new file mode 100644
index 0000000000..ffb6ded5f9
--- /dev/null
+++ b/packages/api/src/code/capabilities.spec.ts
@@ -0,0 +1,247 @@
+import type { AppConfig } from '@librechat/data-schemas';
+import type { CodeExecutionContext, CodeEnvironmentConfig } from '~/agents/execution';
+import { supportsProgrammaticCodeExecution } from './capabilities';
+
+const context: CodeExecutionContext = {
+ baseUrl: 'https://bridge.example',
+ codeSessionKey: 'session',
+ executionProfile: 'stateful',
+ statefulSessions: true,
+ environmentId: 'personal',
+ environmentType: 'attached',
+ bridgeWorkerId: 'worker',
+};
+const environments: CodeEnvironmentConfig[] = [
+ {
+ id: 'personal',
+ name: 'Personal',
+ type: 'attached',
+ owner: 'principal',
+ baseURL: context.baseUrl,
+ workerId: 'worker',
+ controlPlaneId: 'control-plane',
+ },
+ {
+ id: 'control-plane',
+ name: 'Control plane',
+ type: 'attached',
+ owner: 'deployment',
+ baseURL: context.baseUrl,
+ pairing: { allowPrincipalWorkers: true, tokenEnv: 'TEST_CODE_CAPABILITY_TOKEN' },
+ },
+];
+
+const deploymentConfig = {
+ endpoints: { agents: { statefulCodeSessions: { environments: [environments[1]] } } },
+} as AppConfig;
+const getAppConfig = jest.fn(async () => deploymentConfig);
+
+describe('supportsProgrammaticCodeExecution', () => {
+ beforeEach(() => {
+ getAppConfig.mockClear();
+ });
+
+ afterEach(() => {
+ delete process.env.TEST_CODE_CAPABILITY_TOKEN;
+ delete process.env.TEST_PRIVATE_CAPABILITY_SECRET;
+ });
+
+ it.each([false, true, undefined])('requires explicit support: %s', async (statefulWorkspace) => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = `token-${statefulWorkspace}`;
+ const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: 'worker',
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: { statefulWorkspace, sandboxProfile: 'native-srt', runtimes: ['bash'] },
+ }),
+ ),
+ );
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(
+ statefulWorkspace === true,
+ );
+ expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'https://bridge.example/bridge/workers/worker/status',
+ expect.objectContaining({ headers: { Authorization: `Bearer token-${statefulWorkspace}` } }),
+ );
+ });
+
+ it.each([
+ { runtimes: [], supported: false },
+ { runtimes: ['py'], supported: false },
+ { runtimes: undefined, supported: false },
+ { runtimes: ['py', 'bash'], supported: true },
+ ])('requires advertised Bash support: $runtimes', async ({ runtimes, supported }) => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = `runtimes-${JSON.stringify(runtimes)}`;
+ jest.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: 'worker',
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: { statefulWorkspace: true, sandboxProfile: 'native-srt', runtimes },
+ }),
+ ),
+ );
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(
+ supported,
+ );
+ });
+
+ it('refreshes worker capabilities after the cached status expires', async () => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = 'capability-transition-token';
+ const startedAt = Date.now();
+ const now = jest.spyOn(Date, 'now').mockReturnValue(startedAt);
+ const status = (runtimes: string[]) =>
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: 'worker',
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: { statefulWorkspace: true, sandboxProfile: 'native-srt', runtimes },
+ }),
+ );
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(status(['bash']))
+ .mockResolvedValueOnce(status(['py']));
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(true);
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(true);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ now.mockReturnValue(startedAt + 2_001);
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(
+ false,
+ );
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('disables PTC when discovery fails', async () => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = 'failed-token';
+ jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'));
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(
+ false,
+ );
+ });
+
+ it('does not poll managed environments or environments without status credentials', async () => {
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected status request'));
+ expect(
+ await supportsProgrammaticCodeExecution({ ...context, environmentType: 'managed' }),
+ ).toBe(true);
+ expect(await supportsProgrammaticCodeExecution()).toBe(true);
+ expect(await supportsProgrammaticCodeExecution(context, environments, getAppConfig)).toBe(
+ false,
+ );
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('does not send credentials to a different execution route', async () => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = 'route-token';
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected status request'));
+ expect(
+ await supportsProgrammaticCodeExecution(
+ { ...context, baseUrl: 'https://different.example' },
+ environments,
+ getAppConfig,
+ ),
+ ).toBe(false);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+ it('rejects a deployment environment override that redirects a process secret', async () => {
+ process.env.TEST_PRIVATE_CAPABILITY_SECRET = 'must-not-leave-the-process';
+ const override: CodeEnvironmentConfig = {
+ ...environments[1],
+ baseURL: 'https://attacker.example',
+ pairing: {
+ workerId: 'worker',
+ allowPrincipalWorkers: false,
+ tokenEnv: 'TEST_PRIVATE_CAPABILITY_SECRET',
+ },
+ };
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected status request'));
+ expect(
+ await supportsProgrammaticCodeExecution(
+ {
+ ...context,
+ environmentId: override.id,
+ baseUrl: override.baseURL,
+ },
+ [override],
+ getAppConfig,
+ ),
+ ).toBe(false);
+ expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('uses only deployment credentials even if the effective control plane names another secret', async () => {
+ process.env.TEST_CODE_CAPABILITY_TOKEN = 'deployment-only-token';
+ process.env.TEST_PRIVATE_CAPABILITY_SECRET = 'must-not-leave-the-process';
+ const override: CodeEnvironmentConfig = {
+ ...environments[1],
+ baseURL: 'https://attacker.example',
+ pairing: { allowPrincipalWorkers: true, tokenEnv: 'TEST_PRIVATE_CAPABILITY_SECRET' },
+ };
+ const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: 'worker',
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: {
+ statefulWorkspace: true,
+ sandboxProfile: 'native-srt',
+ runtimes: ['bash'],
+ },
+ }),
+ ),
+ );
+ expect(
+ await supportsProgrammaticCodeExecution(context, [environments[0], override], getAppConfig),
+ ).toBe(true);
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'https://bridge.example/bridge/workers/worker/status',
+ expect.objectContaining({ headers: { Authorization: 'Bearer deployment-only-token' } }),
+ );
+ expect(JSON.stringify(fetchSpy.mock.calls)).not.toContain('must-not-leave-the-process');
+ });
+
+ it('requires the control plane in effective config before reading deployment config', async () => {
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected status request'));
+ expect(await supportsProgrammaticCodeExecution(context, [environments[0]], getAppConfig)).toBe(
+ false,
+ );
+ expect(getAppConfig).not.toHaveBeenCalled();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when deployment configuration cannot be loaded', async () => {
+ const fetchSpy = jest
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected status request'));
+ expect(
+ await supportsProgrammaticCodeExecution(context, environments, async () => {
+ throw new Error('unavailable');
+ }),
+ ).toBe(false);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/code/capabilities.ts b/packages/api/src/code/capabilities.ts
new file mode 100644
index 0000000000..8221140bff
--- /dev/null
+++ b/packages/api/src/code/capabilities.ts
@@ -0,0 +1,59 @@
+import { logger } from '@librechat/data-schemas';
+import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';
+import type { createAppConfigService } from '~/app/service';
+import { createCodeBridgeStatusPoller, readCodeBridgeSecret } from './bridge';
+
+export type CodeCapabilityConfigLoader = ReturnType<typeof createAppConfigService>['getAppConfig'];
+
+const pollWorkerStatus = createCodeBridgeStatusPoller();
+
+/** Attached workers must confirm both a stateful workspace and the Bash runtime. */
+export async function supportsProgrammaticCodeExecution(
+ context?: CodeExecutionContext,
+ environments?: readonly CodeEnvironmentConfig[],
+ getAppConfig?: CodeCapabilityConfigLoader,
+): Promise<boolean> {
+ if (context?.environmentType !== 'attached') return true;
+ if (!context.bridgeWorkerId) return false;
+ const selected = environments?.find((environment) => environment.id === context.environmentId);
+ const controlPlaneId = selected?.controlPlaneId ?? selected?.id;
+ const effectiveControlPlane = environments?.find(
+ (environment) =>
+ environment.id === controlPlaneId &&
+ environment.type === 'attached' &&
+ environment.owner === 'deployment',
+ );
+ if (!effectiveControlPlane || !getAppConfig) return false;
+ try {
+ const deploymentConfig = await getAppConfig({ baseOnly: true });
+ const controlPlane =
+ deploymentConfig.endpoints?.agents?.statefulCodeSessions?.environments?.find(
+ (environment) =>
+ environment.id === controlPlaneId &&
+ environment.type === 'attached' &&
+ environment.owner === 'deployment',
+ );
+ if (
+ !controlPlane ||
+ controlPlane.baseURL.replace(/\/+$/, '') !== context.baseUrl.replace(/\/+$/, '')
+ ) {
+ return false;
+ }
+ const tokenEnv = controlPlane.pairing?.tokenEnv;
+ const token = tokenEnv == null ? undefined : readCodeBridgeSecret(tokenEnv)?.trim();
+ if (!token) return false;
+ const status = await pollWorkerStatus({
+ baseURL: controlPlane.baseURL,
+ workerId: context.bridgeWorkerId,
+ token,
+ });
+ return (
+ status.status === 'ready' &&
+ status.statefulWorkspace === true &&
+ status.runtimes?.includes('bash') === true
+ );
+ } catch {
+ logger.warn('[codeCapabilities] Worker capabilities unavailable; programmatic Bash disabled');
+ return false;
+ }
+}
diff --git a/packages/api/src/code/config.spec.ts b/packages/api/src/code/config.spec.ts
index 0936af2aab..784c33ad39 100644
--- a/packages/api/src/code/config.spec.ts
+++ b/packages/api/src/code/config.spec.ts
@@ -401,6 +401,9 @@ describe('mergeAccessibleCodeEnvironments', () => {
});
const environments = result.endpoints?.agents?.statefulCodeSessions?.environments;
+ expect(environments?.find((environment) => environment.id === 'personal-vm')).toEqual(
+ expect.objectContaining({ controlPlaneId: 'self-service', baseURL: pairingOnly.baseURL }),
+ );
expect(environments?.find((environment) => environment.id === 'self-service')?.default).toBe(
false,
);
diff --git a/packages/api/src/code/config.ts b/packages/api/src/code/config.ts
index d91d1a521d..aa7e8414cd 100644
--- a/packages/api/src/code/config.ts
+++ b/packages/api/src/code/config.ts
@@ -112,6 +112,7 @@ export async function mergeAccessibleCodeEnvironments({
return [
{
...environment,
+ controlPlaneId,
baseURL: controlPlane.baseURL,
configSchema: effectiveControlPlanes.get(controlPlaneId)?.configSchema,
},
diff --git a/packages/api/src/code/index.ts b/packages/api/src/code/index.ts
index 9c42b2e3b2..c45f48eb77 100644
--- a/packages/api/src/code/index.ts
+++ b/packages/api/src/code/index.ts
@@ -5,3 +5,4 @@ export * from './bridge';
export * from './lifecycle';
export * from './workspace';
export * from './command';
+export * from './capabilities';
diff --git a/packages/api/src/tools/classification.spec.ts b/packages/api/src/tools/classification.spec.ts
index 642bbc1e4a..f2aa5d9414 100644
--- a/packages/api/src/tools/classification.spec.ts
+++ b/packages/api/src/tools/classification.spec.ts
@@ -1,6 +1,7 @@
import { Providers } from '@librechat/agents';
import type { AgentToolOptions } from 'librechat-data-provider';
import type { GenericTool } from '@librechat/agents';
+import type { CodeEnvironmentConfig } from '~/agents/execution';
import type { LCToolRegistry } from './classification';
import {
buildToolRegistryFromAgentOptions,
@@ -540,6 +541,93 @@ describe('classification.ts', () => {
expect(result.additionalTools.length).toBe(0);
});
+ it.each(
+ [false, true].flatMap((definitionsOnly) => [
+ { definitionsOnly, statefulWorkspace: false, runtimes: ['bash'], supported: false },
+ { definitionsOnly, statefulWorkspace: true, runtimes: ['py'], supported: false },
+ { definitionsOnly, statefulWorkspace: true, runtimes: ['bash'], supported: true },
+ ]),
+ )(
+ 'gates attached PTC: definitionsOnly=$definitionsOnly stateful=$statefulWorkspace runtimes=$runtimes',
+ async ({ definitionsOnly, statefulWorkspace, runtimes, supported }) => {
+ const workerId = `worker-${definitionsOnly}-${statefulWorkspace}-${runtimes[0]}`;
+ process.env.TEST_CODE_CAPABILITY_TOKEN = 'capability-test-token';
+ const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: workerId,
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: {
+ statefulWorkspace,
+ sandboxProfile: 'native-srt',
+ runtimes,
+ },
+ }),
+ ),
+ );
+ const codeEnvironments: CodeEnvironmentConfig[] = [
+ {
+ id: 'attached',
+ name: 'Attached',
+ type: 'attached',
+ owner: 'deployment',
+ baseURL: 'https://code.example',
+ pairing: {
+ workerId: workerId,
+ allowPrincipalWorkers: false,
+ tokenEnv: 'TEST_CODE_CAPABILITY_TOKEN',
+ },
+ },
+ ];
+ try {
+ const result = await buildToolClassification({
+ loadedTools: [createMCPTool('tool1')],
+ userId: 'user1',
+ agentId: 'agent1',
+ agentToolOptions: {
+ tool1: { allowed_callers: ['direct', 'code_execution'], defer_loading: true },
+ },
+ programmaticToolsEnabled: true,
+ codeExecutionEnabled: true,
+ deferredToolsEnabled: true,
+ definitionsOnly,
+ codeExecutionContext: {
+ baseUrl: 'https://code.example',
+ codeSessionKey: 'session',
+ executionProfile: 'stateful',
+ statefulSessions: true,
+ environmentType: 'attached',
+ environmentId: 'attached',
+ bridgeWorkerId: workerId,
+ },
+ codeEnvironments,
+ getAppConfig: jest.fn().mockResolvedValue({
+ endpoints: { agents: { statefulCodeSessions: { environments: codeEnvironments } } },
+ }),
+ });
+ expect(result.toolDefinitions.some((d) => d.name === 'run_tools_with_bash')).toBe(
+ supported,
+ );
+ expect(result.toolRegistry?.has('run_tools_with_bash')).toBe(supported);
+ expect(result.additionalTools.some((tool) => tool.name === 'run_tools_with_bash')).toBe(
+ supported && !definitionsOnly,
+ );
+ expect(result.hasDeferredTools).toBe(true);
+ expect(result.toolRegistry?.get('tool1')?.allowed_callers).toEqual([
+ 'direct',
+ 'code_execution',
+ ]);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ fetchSpy.mockRestore();
+ delete process.env.TEST_CODE_CAPABILITY_TOKEN;
+ }
+ },
+ );
+
it('should create bash PTC tool when capabilities allow programmatic tools', async () => {
const loadedTools: GenericTool[] = [createMCPTool('tool1')];
diff --git a/packages/api/src/tools/classification.ts b/packages/api/src/tools/classification.ts
index be83fa08ef..c99190d2f6 100644
--- a/packages/api/src/tools/classification.ts
+++ b/packages/api/src/tools/classification.ts
@@ -22,7 +22,9 @@ import type {
LCTool,
} from '@librechat/agents';
import type { AgentToolOptions } from 'librechat-data-provider';
-import type { CodeExecutionContext } from '~/agents/execution';
+import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';
+import type { CodeCapabilityConfigLoader } from '~/code/capabilities';
+import { supportsProgrammaticCodeExecution } from '~/code/capabilities';
import { sanitizeGeminiSchema } from '~/mcp/zod';
export type { LCTool, LCToolRegistry, AllowedCaller, JsonSchemaType };
@@ -280,6 +282,8 @@ export interface BuildToolClassificationParams {
authHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
/** Trusted Code API route selected for the executing agent. */
codeExecutionContext?: CodeExecutionContext;
+ codeEnvironments?: readonly CodeEnvironmentConfig[];
+ getAppConfig?: CodeCapabilityConfigLoader;
}
/** Result from building tool classification */
@@ -351,6 +355,8 @@ export async function buildToolClassification(
codeExecutionEnabled = false,
authHeaders,
codeExecutionContext,
+ codeEnvironments,
+ getAppConfig,
} = params;
const isGoogle = provider === Providers.GOOGLE || provider === Providers.VERTEXAI;
const additionalTools: GenericTool[] = [];
@@ -380,7 +386,10 @@ export async function buildToolClassification(
* Only enable tool search if the agent has deferred tools AND the capability is enabled.
*/
const hasProgrammaticTools =
- programmaticToolsEnabled && codeExecutionEnabled && agentHasProgrammaticTools(toolRegistry);
+ programmaticToolsEnabled &&
+ codeExecutionEnabled &&
+ agentHasProgrammaticTools(toolRegistry) &&
+ (await supportsProgrammaticCodeExecution(codeExecutionContext, codeEnvironments, getAppConfig));
const hasDeferredTools = deferredToolsEnabled && agentHasDeferredTools(toolRegistry);
/** Clear defer_loading if capability disabled */
diff --git a/packages/api/src/tools/definitions.spec.ts b/packages/api/src/tools/definitions.spec.ts
index 809e1ba9b5..89d71b5de8 100644
--- a/packages/api/src/tools/definitions.spec.ts
+++ b/packages/api/src/tools/definitions.spec.ts
@@ -407,6 +407,37 @@ describe('definitions.ts', () => {
expect(result.toolRegistry.has('run_tools_with_bash')).toBe(false);
});
+ it('passes the selected attached environment into definitions-only classification', async () => {
+ mockGetOrFetchMCPServerTools.mockResolvedValueOnce(serverTools);
+ const result = await loadToolDefinitions(
+ {
+ userId: 'user-123',
+ agentId: 'agent-123',
+ tools: [mcpToolName],
+ toolOptions: { [mcpToolName]: { allowed_callers: ['code_execution'] } },
+ programmaticToolsEnabled: true,
+ codeExecutionEnabled: true,
+ codeExecutionContext: {
+ baseUrl: 'https://code.example',
+ codeSessionKey: 'session',
+ executionProfile: 'stateful',
+ statefulSessions: true,
+ environmentType: 'attached',
+ environmentId: 'attached',
+ bridgeWorkerId: 'worker',
+ },
+ },
+ {
+ getOrFetchMCPServerTools: mockGetOrFetchMCPServerTools,
+ isBuiltInTool: mockIsBuiltInTool,
+ },
+ );
+ expect(
+ result.toolDefinitions.some((definition) => definition.name === 'run_tools_with_bash'),
+ ).toBe(false);
+ expect(result.toolRegistry.has('run_tools_with_bash')).toBe(false);
+ });
+
it('adds Bash PTC definitions when code and programmatic capabilities are enabled', async () => {
mockGetOrFetchMCPServerTools.mockResolvedValueOnce(serverTools);
diff --git a/packages/api/src/tools/definitions.ts b/packages/api/src/tools/definitions.ts
index ea0cf9844d..eb4b01064d 100644
--- a/packages/api/src/tools/definitions.ts
+++ b/packages/api/src/tools/definitions.ts
@@ -16,6 +16,8 @@ import {
} from 'librechat-data-provider';
import type { LCToolRegistry, JsonSchemaType, LCTool, GenericTool } from '@librechat/agents';
import type { AgentToolOptions } from 'librechat-data-provider';
+import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';
+import type { CodeCapabilityConfigLoader } from '~/code/capabilities';
import type { MCPToolAlias, ToolDefinition } from './classification';
import { resolveJsonSchemaRefs, normalizeJsonSchema, sanitizeGeminiSchema } from '~/mcp/zod';
import { buildToolClassification } from './classification';
@@ -49,6 +51,9 @@ export interface LoadToolDefinitionsParams {
programmaticToolsEnabled?: boolean;
/** Whether code execution is enabled and requested by this agent */
codeExecutionEnabled?: boolean;
+ codeExecutionContext?: CodeExecutionContext;
+ codeEnvironments?: readonly CodeEnvironmentConfig[];
+ getAppConfig?: CodeCapabilityConfigLoader;
/** Agent provider — Gemini/Vertex tool schemas get union-flattened for compatibility */
provider?: Providers;
/** Configured server names, used to resolve the tool-key boundary exactly */
@@ -127,6 +132,9 @@ export async function loadToolDefinitions(
deferredToolsEnabled = false,
programmaticToolsEnabled = false,
codeExecutionEnabled = false,
+ codeExecutionContext,
+ codeEnvironments,
+ getAppConfig,
provider,
mcpServerNames,
rawServerNames,
@@ -363,6 +371,9 @@ export async function loadToolDefinitions(
deferredToolsEnabled,
programmaticToolsEnabled,
codeExecutionEnabled,
+ codeExecutionContext,
+ codeEnvironments,
+ getAppConfig,
definitionsOnly: true,
agentToolOptions: toolOptions,
});