Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ librechat.yaml
librechat.yml

# Environment
.npmrc
.env*
my.secrets
!**/.env.example
Expand Down
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
allow-remote=root
2 changes: 1 addition & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
"@librechat/agents": "^3.8.2",
"@librechat/agents": "^3.8.3",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
Expand Down
3 changes: 3 additions & 0 deletions api/server/controllers/agents/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const {
isHITLEnabled,
resolveToolApprovalPolicy,
buildToolApprovalHooks,
buildToolApprovalExecutionConfig,
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
buildAttachedCodeEnvironmentAdmissionHooks,
Expand Down Expand Up @@ -4452,6 +4453,7 @@ class AgentClient extends BaseClient {
runName: 'AgentRun',
configurable: {
thread_id: this.conversationId,
...buildToolApprovalExecutionConfig(this.responseMessageId, this.jobCreatedAt),
// LangGraph owns `checkpoint_ns` and resets it to '' at every root
// invocation. The saver maps this private immutable generation key
// into its physical namespace while tools keep the conversation id.
Expand Down Expand Up @@ -5243,6 +5245,7 @@ class AgentClient extends BaseClient {
runName: 'AgentRun',
configurable: {
thread_id: this.conversationId,
...buildToolApprovalExecutionConfig(this.responseMessageId, this.jobCreatedAt),
checkpoint_ns: '',
[LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: this.checkpointNamespace,
[LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY]:
Expand Down
22 changes: 20 additions & 2 deletions api/server/services/ToolService.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
buildWebSearchContext,
buildImageToolContext,
buildToolClassification,
supportsProgrammaticCodeExecution,
getMissingCustomUserVars,
buildWebSearchDynamicContext,
getCodeApiAuthHeaders,
Expand Down Expand Up @@ -90,6 +91,7 @@ const {
domainParser,
} = require('./ActionService');
const {
getAppConfig,
getEndpointsConfig,
getMCPServerTools,
getCachedTools,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1738,6 +1746,8 @@ async function loadAgentTools({
deferredToolsEnabled,
programmaticToolsEnabled,
codeExecutionEnabled,
codeEnvironments: appConfig?.endpoints?.agents?.statefulCodeSessions?.environments,
getAppConfig,
authHeaders: () =>
codeExecutionAuthHeaders(
(bridgeWorkerId) => getCodeApiAuthHeaders(req, bridgeWorkerId),
Expand Down Expand Up @@ -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 {
/**
Expand Down Expand Up @@ -2218,7 +2236,7 @@ async function loadToolsForExecution({
]);

let ptcOrchestratedToolNames = [];
if (isPTC && toolRegistry) {
if (canLoadPTC) {
ptcOrchestratedToolNames = Array.from(toolRegistry.values())
.filter(
(toolDef) =>
Expand Down
124 changes: 124 additions & 0 deletions api/server/services/__tests__/ToolService.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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),
}));
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading