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
24 changes: 16 additions & 8 deletions api/server/services/ToolService.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const {
AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE,
isFatalAgentInitializationError,
codeExecutionAuthHeaders,
createAttachedWorkspaceBashTool,
resolveCodeExecutionContext,
resolveCallerCapabilityProjectionSnapshot,
LIST_WORKSPACE_FILES_TOOL_NAME,
Expand Down Expand Up @@ -2122,14 +2123,21 @@ async function loadToolsForExecution({
}
if (isBashTool) {
try {
const bashTool = createBashExecutionTool({
authHeaders: () =>
codeExecutionAuthHeaders(
(bridgeWorkerId) => getCodeApiAuthHeaders(req, bridgeWorkerId),
codeExecutionContext,
),
...codeExecutionContext,
});
const authHeaders = () =>
codeExecutionAuthHeaders(
(bridgeWorkerId) => getCodeApiAuthHeaders(req, bridgeWorkerId),
codeExecutionContext,
);
const bashTool =
codeExecutionContext.environmentType === 'attached'
? createAttachedWorkspaceBashTool({
authHeaders,
baseUrl: codeExecutionContext.baseUrl,
})
: createBashExecutionTool({
authHeaders,
...codeExecutionContext,
});
allLoadedTools.push(bashTool);
} catch (error) {
logger.error(
Expand Down
43 changes: 43 additions & 0 deletions api/server/services/__tests__/ToolService.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const mockGetMCPServerTools = jest.fn();
const mockGetCachedTools = jest.fn();
const mockSendEvent = jest.fn();
const mockEmitChunk = jest.fn();
const mockCreateAttachedWorkspaceBashTool = jest.fn(() => ({ name: AgentConstants.BASH_TOOL }));
const mockResolveCodeExecutionContext = jest.fn(
({ statefulSessions, environment, userId, agentId, conversationId }) => {
if (!statefulSessions) {
Expand Down Expand Up @@ -80,6 +81,7 @@ jest.mock('@librechat/api', () => ({
emitChunk: (...args) => mockEmitChunk(...args),
},
resolveCodeExecutionContext: (...args) => mockResolveCodeExecutionContext(...args),
createAttachedWorkspaceBashTool: (...args) => mockCreateAttachedWorkspaceBashTool(...args),
}));

const mockLoadToolsUtil = jest.fn();
Expand Down Expand Up @@ -2631,6 +2633,47 @@ describe('ToolService - Action Capability Gating', () => {
}
});

it('loads bash execution through the attached worker transport', async () => {
const capabilities = [
AgentCapabilities.tools,
AgentCapabilities.execute_code,
AgentCapabilities.stateful_code_sessions,
];
const req = createMockReq(capabilities);
mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
mockResolveCodeExecutionContext.mockReturnValueOnce({
baseUrl: 'http://attached-code.test/v1',
codeSessionKey: 'execute_code:stateful:attached',
executionProfile: 'stateful',
statefulSessions: true,
environmentType: 'attached',
bridgeWorkerId: 'worker-abc',
});
const toolRegistry = new Map([
[AgentConstants.BASH_TOOL, { name: AgentConstants.BASH_TOOL }],
]);

const result = await loadToolsForExecution({
req,
res: {},
agent: {
id: 'attached-agent',
tools: [Tools.execute_code],
stateful_code_sessions: true,
stateful_code_environment: 'agent-user',
},
toolNames: [AgentConstants.BASH_TOOL],
toolRegistry,
actionsEnabled: false,
});

expect(mockCreateAttachedWorkspaceBashTool).toHaveBeenCalledWith({
authHeaders: expect.any(Function),
baseUrl: 'http://attached-code.test/v1',
});
expect(result.loadedTools).toContainEqual({ name: AgentConstants.BASH_TOOL });
});

it('resolves stateful routing when handle_skill is the only requested tool', async () => {
const capabilities = [
AgentCapabilities.tools,
Expand Down
22 changes: 21 additions & 1 deletion packages/api/src/agents/tools.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,16 @@ jest.mock('@librechat/agents', () => ({
BashExecutionToolDefinition: {
name: 'bash_tool',
description: 'bash',
schema: { type: 'object', properties: {} },
schema: {
type: 'object',
properties: {
command: { type: 'string' },
args: { type: 'array', items: { type: 'string' } },
},
required: ['command'],
},
},
BashToolOutputReferencesGuide: '{{tool<idx>turn<turn>}}',
/**
* Deterministic stub mirroring the SDK's `buildBashExecutionToolDescription`:
* appends an LLM-facing reference-syntax marker only when
Expand Down Expand Up @@ -486,6 +494,7 @@ describe('registerCodeExecutionTools', () => {
});

const readFile = result.toolDefinitions.find((definition) => definition.name === 'read_file');
const bashTool = result.toolDefinitions.find((definition) => definition.name === 'bash_tool');
const searchWorkspace = result.toolDefinitions.find(
(definition) => definition.name === 'search_workspace',
);
Expand All @@ -500,6 +509,17 @@ describe('registerCodeExecutionTools', () => {
max_lines: { type: 'integer', maximum: 500 },
},
});
expect(bashTool?.description).toContain('selected attached environment');
expect(bashTool?.description).toContain('empty directory');
expect(bashTool?.description).toContain('Network access follows the sandbox policy');
expect(bashTool?.description).not.toContain('/mnt/data');
expect(bashTool?.parameters).toMatchObject({
properties: {
command: { type: 'string' },
args: { type: 'array' },
},
required: ['command'],
});
expect(searchWorkspace).toMatchObject({
name: 'search_workspace',
parameters: {
Expand Down
32 changes: 26 additions & 6 deletions packages/api/src/agents/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import {
import type { AgentToolOptions, GraphEdge } from 'librechat-data-provider';
import type { LCTool, LCToolRegistry } from '@librechat/agents';
import type { ReachableAgent } from './traversal';
import {
ATTACHED_WORKSPACE_BASH_SCHEMA,
buildAttachedWorkspaceBashDescription,
} from '~/code/command';
import { toolkitExpansion } from '~/tools/toolkits/mapping';
import { normalizeAgentToolKeys } from '~/mcp/utils';
import { collectReachableAgents } from './traversal';
Expand Down Expand Up @@ -765,15 +769,23 @@ export function isFileAuthoringToolDefinition(def: LCTool | undefined): boolean
* intent of the original constant while keeping the per-agent gate
* behavior introduced for tool-output references.
*/
function createBashToolDef(enableToolOutputReferences: boolean, statefulSessions = false): LCTool {
function createBashToolDef(
enableToolOutputReferences: boolean,
statefulSessions = false,
workspaceTools = false,
): LCTool {
/* Passed as a variable (not an inline literal) so the extra
* `statefulSessions` key stays assignable against pinned SDK versions
* whose builder predates it (ignored at runtime there). */
const descriptionOpts = { enableToolOutputReferences, statefulSessions };
return Object.freeze({
name: BashExecutionToolDefinition.name,
description: buildBashExecutionToolDescription(descriptionOpts),
parameters: BashExecutionToolDefinition.schema as unknown as LCTool['parameters'],
description: workspaceTools
? buildAttachedWorkspaceBashDescription(enableToolOutputReferences)
: buildBashExecutionToolDescription(descriptionOpts),
parameters: (workspaceTools
? ATTACHED_WORKSPACE_BASH_SCHEMA
: BashExecutionToolDefinition.schema) as unknown as LCTool['parameters'],
}) as LCTool;
}

Expand All @@ -783,11 +795,16 @@ const BASH_TOOL_DEF_WITHOUT_OUTPUT_REFS = createBashToolDef(false);
function buildBashToolDef(opts: {
enableToolOutputReferences: boolean;
statefulSessions?: boolean;
workspaceTools?: boolean;
}): LCTool {
/* Stateful defs are built on demand: the stateless pair covers the
* default path, and per-run construction is negligible next to init. */
if (opts.statefulSessions === true) {
return createBashToolDef(opts.enableToolOutputReferences, true);
if (opts.statefulSessions === true || opts.workspaceTools === true) {
return createBashToolDef(
opts.enableToolOutputReferences,
opts.statefulSessions === true,
opts.workspaceTools === true,
);
}
return opts.enableToolOutputReferences
? BASH_TOOL_DEF_WITH_OUTPUT_REFS
Expand Down Expand Up @@ -823,7 +840,10 @@ export function registerCodeExecutionTools(

const readFileDef = buildReadFileDef(includeSkillFileInstructions, workspaceTools);
const codeTools: LCTool[] = includeBash
? [readFileDef, buildBashToolDef({ enableToolOutputReferences, statefulSessions })]
? [
readFileDef,
buildBashToolDef({ enableToolOutputReferences, statefulSessions, workspaceTools }),
]
: [readFileDef];
const candidates = workspaceTools
? [...codeTools, SEARCH_WORKSPACE_TOOL_DEF, LIST_WORKSPACE_FILES_TOOL_DEF]
Expand Down
95 changes: 95 additions & 0 deletions packages/api/src/code/command.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type { CodeBridgeFetch } from './bridge';
import { createAttachedWorkspaceBashTool } from './command';

function commandResponse(overrides: Record<string, unknown> = {}): Response {
return new Response(
JSON.stringify({
protocolVersion: 1,
operation: 'execute_command',
workspaceId: 'primary',
exitCode: 0,
stdout: 'ready\n',
stderr: '',
truncated: false,
timedOut: false,
...overrides,
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
);
}

describe('createAttachedWorkspaceBashTool', () => {
test('executes in the attached default workspace with per-user bridge authentication', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
const authHeaders = jest.fn().mockResolvedValue({
Authorization: 'Bearer jwt',
'X-LibreChat-Code-Worker-ID': 'user-worker',
});
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1/',
authHeaders,
fetchImpl,
});

await expect(bashTool.func({ command: 'pwd' }, undefined, {})).resolves.toEqual([
'stdout:\nready\n\n[exit code: 0]',
{},
]);

expect(authHeaders).toHaveBeenCalledTimes(1);
expect(fetchImpl).toHaveBeenCalledWith(
'https://code.example.com/v1/workspace-tools/execute',
expect.objectContaining({
headers: expect.objectContaining({
Authorization: 'Bearer jwt',
'X-LibreChat-Code-Worker-ID': 'user-worker',
}),
}),
);
const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body));
expect(request).toEqual({
protocolVersion: 1,
operation: 'execute_command',
workspaceId: 'primary',
command: 'pwd',
maxOutputBytes: 256 * 1024,
});
});

test('preserves legacy positional args without interpolating shell metacharacters', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1',
authHeaders: () => ({}),
fetchImpl,
});

await bashTool.func({ command: 'printf "%s" "$1"', args: ["a'b; echo unsafe"] }, undefined, {});

const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body));
expect(request.command).toBe(`bash -c 'printf "%s" "$1"' -- 'a'"'"'b; echo unsafe'`);
});

test('reports termination, timeouts, and truncation without hiding stderr', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () =>
commandResponse({
exitCode: null,
signal: 'SIGKILL',
stdout: '',
stderr: 'deadline reached',
truncated: true,
timedOut: true,
}),
);
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1',
authHeaders: () => ({}),
fetchImpl,
});

await expect(bashTool.func({ command: 'sleep 60' }, undefined, {})).resolves.toEqual([
'stderr:\ndeadline reached\n[terminated by SIGKILL][timed out][output truncated]',
{},
]);
});
});
Loading
Loading