From 9f311b810dd62b4123621e3fde1bf8aae119b92c Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 9 Sep 2026 09:22:33 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=94=20feat:=20Expose=20Bounded=20Attac?= =?UTF-8?q?hed=20Bash=20Timeouts=20(#15776)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ๐Ÿ•ฐ๏ธ feat: Add BYOM Bash Execution Timeouts * ๐Ÿ”ง fix: Type Bash Timeout Bounds * ๐Ÿ”’ fix: Bound BYOM Bash timeouts by policy * ๐Ÿงช test: Propagate BYOM timeout policy fixture --- api/server/services/ToolService.js | 4 + .../services/__tests__/ToolService.spec.js | 2 + librechat.example.yaml | 4 + .../src/agents/__tests__/initialize.test.ts | 14 ++- packages/api/src/agents/initialize.ts | 9 ++ packages/api/src/agents/skills.ts | 4 + packages/api/src/agents/tools.spec.ts | 20 ++++ packages/api/src/agents/tools.ts | 17 +++- packages/api/src/code/command.spec.ts | 84 +++++++++++++++++ packages/api/src/code/command.ts | 92 ++++++++++++++++--- packages/api/src/code/config.spec.ts | 6 ++ packages/api/src/code/workspace.ts | 11 ++- packages/data-provider/src/config.spec.ts | 25 +++++ packages/data-provider/src/config.ts | 18 ++++ 14 files changed, 289 insertions(+), 21 deletions(-) diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js index 34b762e997..35253aa595 100644 --- a/api/server/services/ToolService.js +++ b/api/server/services/ToolService.js @@ -47,6 +47,7 @@ const { isFatalAgentInitializationError, codeExecutionAuthHeaders, createAttachedWorkspaceBashTool, + resolveAttachedWorkspaceCommandTimeoutMax, createGitIdentityProgrammaticBashTool, resolveCodeExecutionContext, resolveCodeExecutionWorkspaceContext, @@ -2234,6 +2235,9 @@ async function loadToolsForExecution({ baseUrl: codeExecutionContext.baseUrl, workspaceId: codeExecutionContext.codeWorkspace.workspaceId, gitIdentity: agent?.git_identity, + maxTimeoutMs: resolveAttachedWorkspaceCommandTimeoutMax( + codeExecutionContext.codeEnvironmentConfigSchema, + ), }) : createBashExecutionTool({ authHeaders, diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js index 5235a65441..21d5540790 100644 --- a/api/server/services/__tests__/ToolService.spec.js +++ b/api/server/services/__tests__/ToolService.spec.js @@ -2750,6 +2750,7 @@ describe('ToolService - Action Capability Gating', () => { environmentType: 'attached', environmentId: 'personal-machine', bridgeWorkerId: 'worker-abc', + codeEnvironmentConfigSchema: { limits: { maxCommandTimeoutMs: 120000 } }, }); const toolRegistry = new Map([ [AgentConstants.BASH_TOOL, { name: AgentConstants.BASH_TOOL }], @@ -2775,6 +2776,7 @@ describe('ToolService - Action Capability Gating', () => { baseUrl: 'http://attached-code.test/v1', workspaceId: 'project-a', gitIdentity: { name: 'LibreChat Agent', email: 'agent@example.com' }, + maxTimeoutMs: 120000, }); expect(mockResolveCodeExecutionWorkspaceContext).toHaveBeenCalledWith( expect.objectContaining({ requestedSelections: req.body.codeWorkspaces }), diff --git a/librechat.example.yaml b/librechat.example.yaml index b502457ac0..d91e8e2176 100644 --- a/librechat.example.yaml +++ b/librechat.example.yaml @@ -630,6 +630,10 @@ endpoints: # owner: deployment # # Optionally expose only these bounded preferences to environment owners. # configSchema: + # limits: + # # Maximum Bash execution budget the model may request per call. + # # Omit to preserve the historical 30-second limit. Hard cap: 300000. + # maxCommandTimeoutMs: 120000 # permissions: # fileWrite: # allowed: [allow, ask, deny] diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts index 1feffdf41b..1ca43f52aa 100644 --- a/packages/api/src/agents/__tests__/initialize.test.ts +++ b/packages/api/src/agents/__tests__/initialize.test.ts @@ -2520,6 +2520,9 @@ describe('initializeAgent โ€” execute_code capability expansion', () => { baseURL: 'https://code.example.com/v1', owner: 'deployment', workerId: 'worker-a', + configSchema: { + limits: { maxCommandTimeoutMs: 120_000 }, + }, }, ], }, @@ -2543,10 +2546,13 @@ describe('initializeAgent โ€” execute_code capability expansion', () => { environmentId: 'personal-vm', environmentType: 'attached', bridgeWorkerId: 'worker-a', + codeEnvironmentConfigSchema: { + limits: { maxCommandTimeoutMs: 120_000 }, + }, codeWorkspace: { environmentId: 'personal-vm', workspaceId: 'project-a', - operations: ['read_file', 'list_files'], + operations: ['read_file', 'list_files', 'execute_command'], }, }; if (protectedEdit) codeExecutionContext.codeWorkspace!.operations.push('edit_file'); @@ -2576,9 +2582,15 @@ describe('initializeAgent โ€” execute_code capability expansion', () => { expect(result.codeExecutionContext).toBe(codeExecutionContext); expect(result.toolDefinitions?.map(({ name }) => name).sort()).toEqual([ + 'bash_tool', 'list_workspace_files', 'read_file', ]); + const bashTool = result.toolDefinitions?.find(({ name }) => name === 'bash_tool'); + expect( + (bashTool?.parameters as { properties?: { timeoutMs?: { maximum?: number } } })?.properties + ?.timeoutMs?.maximum, + ).toBe(120_000); }, ); diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts index 5254a6b88f..5b2dd0f0ac 100644 --- a/packages/api/src/agents/initialize.ts +++ b/packages/api/src/agents/initialize.ts @@ -103,6 +103,7 @@ import { import { extractAgentContent, extractSkillContent } from '../protection/adapters/submissions'; import { createConfiguredContentInspector, inspectContent } from '../protection/runtime'; import { assertAgentAttachmentLimits, isModelBoundAttachmentFile } from './attachments'; +import { resolveAttachedWorkspaceCommandTimeoutMax } from '~/code/command'; import { assertModelBoundContent } from '../middleware/modelBoundContent'; import { registerMemoryTools, memoryToolUsageGuard } from './memory'; import { applyIntentLabels, sanitizeIntentLabels } from './intent'; @@ -1670,6 +1671,12 @@ export async function initializeAgent( trustedCodeExecutionContext.environmentType === 'attached' ? new Set(trustedCodeExecutionContext.codeWorkspace?.operations ?? []) : undefined; + const attachedWorkspaceCommandTimeoutMaxMs = + trustedCodeExecutionContext.environmentType === 'attached' + ? resolveAttachedWorkspaceCommandTimeoutMax( + trustedCodeExecutionContext.codeEnvironmentConfigSchema, + ) + : undefined; if ( attachedWorkspaceOperations && !attachedWorkspaceOperations.has('preview_edit') && @@ -1805,6 +1812,7 @@ export async function initializeAgent( statefulSessions: effectiveStatefulSessions, workspaceTools: attachedWorkspaceTools, workspaceOperations: attachedWorkspaceOperations, + workspaceCommandTimeoutMaxMs: attachedWorkspaceCommandTimeoutMaxMs, }); toolDefinitions = codeExecResult.toolDefinitions; recordCapabilityToolNames(AgentCapabilities.execute_code, codeExecResult.toolNames); @@ -1855,6 +1863,7 @@ export async function initializeAgent( enableToolOutputReferences: effectiveCodeEnvAvailable, workspaceTools: attachedWorkspaceTools, workspaceOperations: attachedWorkspaceOperations, + workspaceCommandTimeoutMaxMs: attachedWorkspaceCommandTimeoutMaxMs, }); toolDefinitions = skillReadResult.toolDefinitions; recordCapabilityToolNames(AgentCapabilities.skills, skillReadResult.toolNames); diff --git a/packages/api/src/agents/skills.ts b/packages/api/src/agents/skills.ts index 970d836e01..9c7367f609 100644 --- a/packages/api/src/agents/skills.ts +++ b/packages/api/src/agents/skills.ts @@ -434,6 +434,8 @@ export interface InjectSkillCatalogParams { workspaceTools?: boolean; /** Live operation ceiling for the selected attached workspace. */ workspaceOperations?: ReadonlySet; + /** Deployment ceiling advertised on attached Bash tool definitions. */ + workspaceCommandTimeoutMaxMs?: number; /** Current user ID โ€” used to determine skill ownership for active-state resolution. */ userId?: string; /** Per-user skill overrides: `{ [skillId]: boolean }`. Missing entries use the default. */ @@ -662,6 +664,7 @@ export async function injectSkillCatalog( statefulSessions, workspaceTools, workspaceOperations, + workspaceCommandTimeoutMaxMs, userId, skillStates, defaultActiveOnShare = false, @@ -821,6 +824,7 @@ export async function injectSkillCatalog( statefulSessions: statefulSessions === true, workspaceTools: workspaceTools === true, workspaceOperations, + workspaceCommandTimeoutMaxMs, }); workingDefs = codeExecResult.toolDefinitions; diff --git a/packages/api/src/agents/tools.spec.ts b/packages/api/src/agents/tools.spec.ts index 8afd0a524a..a49d61aaac 100644 --- a/packages/api/src/agents/tools.spec.ts +++ b/packages/api/src/agents/tools.spec.ts @@ -520,6 +520,7 @@ describe('registerCodeExecutionTools', () => { command: { type: 'string' }, args: { type: 'array' }, cwd: { type: 'string', maxLength: 4096 }, + timeoutMs: { type: 'integer', minimum: 1, maximum: 30000 }, }, required: ['command'], }); @@ -550,6 +551,25 @@ describe('registerCodeExecutionTools', () => { expect(filePathDescription(listWorkspaceFiles)).toContain('canonical relative'); }); + it('advertises the configured attached-command timeout ceiling', () => { + const result = registerCodeExecutionTools({ + toolRegistry: makeRegistry(), + toolDefinitions: [], + includeBash: true, + workspaceTools: true, + workspaceOperations: new Set(['execute_command'] as const), + workspaceCommandTimeoutMaxMs: 120_000, + }); + + expect( + result.toolDefinitions.find((definition) => definition.name === 'bash_tool'), + ).toMatchObject({ + parameters: { + properties: { timeoutMs: { minimum: 1, maximum: 120_000 } }, + }, + }); + }); + it('registers only operations advertised by the selected workspace', () => { const result = registerCodeExecutionTools({ toolRegistry: makeRegistry(), diff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.ts index ce8af5002f..5b23429b5a 100644 --- a/packages/api/src/agents/tools.ts +++ b/packages/api/src/agents/tools.ts @@ -15,7 +15,7 @@ import type { AgentToolOptions, CodeWorkspaceOperation, GraphEdge } from 'librec import type { LCTool, LCToolRegistry } from '@librechat/agents'; import type { ReachableAgent } from './traversal'; import { - ATTACHED_WORKSPACE_BASH_SCHEMA, + buildAttachedWorkspaceBashSchema, buildAttachedWorkspaceBashDescription, } from '~/code/command'; import { toolkitExpansion } from '~/tools/toolkits/mapping'; @@ -379,6 +379,8 @@ export interface RegisterCodeExecutionToolsParams { workspaceTools?: boolean; /** Live operation ceiling for the selected workspace. Omitted for managed runtimes. */ workspaceOperations?: ReadonlySet; + /** Deployment ceiling advertised on attached Bash tool definitions. */ + workspaceCommandTimeoutMaxMs?: number; /** * When `true`, the registered `bash_tool` description includes the * LLM-facing `{{toolturn}}` reference syntax guide so the @@ -888,6 +890,7 @@ function createBashToolDef( enableToolOutputReferences: boolean, statefulSessions = false, workspaceTools = false, + workspaceCommandTimeoutMaxMs?: number, ): LCTool { /* Passed as a variable (not an inline literal) so the extra * `statefulSessions` key stays assignable against pinned SDK versions @@ -900,7 +903,7 @@ function createBashToolDef( ? buildAttachedWorkspaceBashDescription(enableToolOutputReferences) : buildBashExecutionToolDescription(descriptionOpts), parameters: (workspaceTools - ? ATTACHED_WORKSPACE_BASH_SCHEMA + ? buildAttachedWorkspaceBashSchema(workspaceCommandTimeoutMaxMs) : BashExecutionToolDefinition.schema) as unknown as LCTool['parameters'], }) as LCTool; } @@ -912,6 +915,7 @@ function buildBashToolDef(opts: { enableToolOutputReferences: boolean; statefulSessions?: boolean; workspaceTools?: boolean; + workspaceCommandTimeoutMaxMs?: number; }): LCTool { /* Stateful defs are built on demand: the stateless pair covers the * default path, and per-run construction is negligible next to init. */ @@ -920,6 +924,7 @@ function buildBashToolDef(opts: { opts.enableToolOutputReferences, opts.statefulSessions === true, opts.workspaceTools === true, + opts.workspaceCommandTimeoutMaxMs, ); } return opts.enableToolOutputReferences @@ -951,6 +956,7 @@ export function registerCodeExecutionTools( includeSkillFileInstructions = true, workspaceTools = false, workspaceOperations, + workspaceCommandTimeoutMaxMs, enableToolOutputReferences = false, statefulSessions = false, } = params; @@ -965,7 +971,12 @@ export function registerCodeExecutionTools( } if (includeBash && supportsWorkspaceOperation('execute_command')) { candidates.push( - buildBashToolDef({ enableToolOutputReferences, statefulSessions, workspaceTools }), + buildBashToolDef({ + enableToolOutputReferences, + statefulSessions, + workspaceTools, + workspaceCommandTimeoutMaxMs, + }), ); } if (workspaceTools && supportsWorkspaceOperation('search_text')) { diff --git a/packages/api/src/code/command.spec.ts b/packages/api/src/code/command.spec.ts index db57adaa40..fcf5420116 100644 --- a/packages/api/src/code/command.spec.ts +++ b/packages/api/src/code/command.spec.ts @@ -4,8 +4,10 @@ import type { AddressInfo } from 'node:net'; import type { CodeBridgeFetch } from './bridge'; import { ATTACHED_WORKSPACE_BASH_SCHEMA, + buildAttachedWorkspaceBashSchema, createAttachedWorkspaceBashTool, createGitIdentityProgrammaticBashTool, + resolveAttachedWorkspaceCommandTimeoutMax, } from './command'; describe('programmatic Bash Git identity', () => { @@ -98,10 +100,92 @@ describe('createAttachedWorkspaceBashTool', () => { workspaceId: 'project-a', command: 'pwd', cwd: 'packages/api', + timeoutMs: 30_000, maxOutputBytes: 256 * 1024, }); }); + test('forwards a bounded per-call execution timeout', async () => { + const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); + const bashTool = createAttachedWorkspaceBashTool({ + baseUrl: 'https://code.example.com/v1', + authHeaders: () => ({}), + workspaceId: 'project-a', + maxTimeoutMs: 300_000, + fetchImpl, + }); + + await bashTool.invoke({ command: 'npm test', timeoutMs: 300_000 }); + + const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body)); + expect(request).toMatchObject({ command: 'npm test', timeoutMs: 300_000 }); + }); + + test('preserves the historical 30-second ceiling unless an administrator raises it', async () => { + const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); + const bashTool = createAttachedWorkspaceBashTool({ + baseUrl: 'https://code.example.com/v1', + authHeaders: () => ({}), + workspaceId: 'project-a', + fetchImpl, + }); + + await expect( + bashTool.func({ command: 'npm test', timeoutMs: 30_001 }, undefined, {}), + ).rejects.toThrow('deployment limit of 30000 milliseconds'); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + test('resolves and advertises an administrator-configured timeout ceiling', () => { + const maxTimeoutMs = resolveAttachedWorkspaceCommandTimeoutMax({ + limits: { maxCommandTimeoutMs: 120_000 }, + }); + const schema = buildAttachedWorkspaceBashSchema(maxTimeoutMs); + + expect(maxTimeoutMs).toBe(120_000); + expect(schema).toMatchObject({ + properties: { timeoutMs: { type: 'integer', minimum: 1, maximum: 120_000 } }, + }); + expect(resolveAttachedWorkspaceCommandTimeoutMax()).toBe(30_000); + }); + + test('lowers the omitted timeout when the deployment ceiling is below 30 seconds', async () => { + const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); + const bashTool = createAttachedWorkspaceBashTool({ + baseUrl: 'https://code.example.com/v1', + authHeaders: () => ({}), + workspaceId: 'project-a', + maxTimeoutMs: 5_000, + fetchImpl, + }); + + await bashTool.invoke({ command: 'npm test' }); + + const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body)); + expect(request).toMatchObject({ timeoutMs: 5_000 }); + expect(buildAttachedWorkspaceBashSchema(5_000)).toMatchObject({ + properties: { + timeoutMs: expect.objectContaining({ + maximum: 5_000, + description: expect.stringContaining('Defaults to 5000'), + }), + }, + }); + }); + + test.each([0, 300_001, 1.5])('rejects an invalid execution timeout of %p', async (timeoutMs) => { + const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); + const bashTool = createAttachedWorkspaceBashTool({ + baseUrl: 'https://code.example.com/v1', + authHeaders: () => ({}), + workspaceId: 'project-a', + fetchImpl, + }); + + await expect(bashTool.invoke({ command: 'npm test', timeoutMs })).rejects.toThrow(); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + test('validates and invokes commands through the LangChain tool runtime', async () => { const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); const bashTool = createAttachedWorkspaceBashTool({ diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.ts index ecb16e3e1e..20b3122e11 100644 --- a/packages/api/src/code/command.ts +++ b/packages/api/src/code/command.ts @@ -4,12 +4,16 @@ import { BashToolOutputReferencesGuide, createBashProgrammaticToolCallingTool, } from '@librechat/agents'; +import type { AgentGitIdentity, CodeEnvironmentUserConfigSchema } from 'librechat-data-provider'; import type { DynamicStructuredTool } from '@librechat/agents/langchain/tools'; -import type { AgentGitIdentity } from 'librechat-data-provider'; import type { LCTool } from '@librechat/agents'; import type { WorkspaceExecuteCommandResult } from './workspace'; import type { CodeBridgeFetch } from './bridge'; -import { executeWorkspaceTool } from './workspace'; +import { + executeWorkspaceTool, + WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, + WORKSPACE_COMMAND_MAX_TIMEOUT_MS, +} from './workspace'; const DEFAULT_OUTPUT_BYTES = 256 * 1024; @@ -48,20 +52,64 @@ const attachedWorkingDirectorySchema: BoundedWorkingDirectorySchema = { 'Optional working directory relative to the selected workspace root, such as "packages/api". Absolute paths and parent traversal are rejected.', }; +/** Numeric bounds are valid JSON Schema, but the SDK's schema type omits them. */ +interface BoundedTimeoutSchema { + type: 'integer'; + minimum: number; + maximum: number; + description: string; +} + +function buildAttachedTimeoutSchema(maxTimeoutMs: number): BoundedTimeoutSchema { + const defaultTimeoutMs = Math.min(WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, maxTimeoutMs); + return { + type: 'integer', + minimum: 1, + maximum: maxTimeoutMs, + description: `Optional execution timeout in milliseconds, from 1 through ${maxTimeoutMs}. Defaults to ${defaultTimeoutMs}. Waiting for an available worker does not consume this execution budget.`, + }; +} + +function normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs: number): number { + if (!Number.isSafeInteger(maxTimeoutMs) || maxTimeoutMs < 1) { + return WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS; + } + return Math.min(WORKSPACE_COMMAND_MAX_TIMEOUT_MS, maxTimeoutMs); +} + +export function resolveAttachedWorkspaceCommandTimeoutMax( + configSchema?: CodeEnvironmentUserConfigSchema, +): number { + const configured = configSchema?.limits?.maxCommandTimeoutMs; + return configured == null + ? WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS + : normalizeAttachedWorkspaceCommandTimeoutMax(configured); +} + +export function buildAttachedWorkspaceBashSchema( + maxTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, +): NonNullable { + const effectiveMaxTimeoutMs = normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs); + return { + type: 'object', + properties: { + ...bashSchema.properties, + command: attachedCommandSchema, + cwd: attachedWorkingDirectorySchema, + timeoutMs: buildAttachedTimeoutSchema(effectiveMaxTimeoutMs), + }, + required: ['command'], + }; +} + /** * This definition is shared with agent metadata. LangChain's JSON Schema * dereferencer annotates schemas during validation, so each tool receives an * isolated mutable clone instead of mutating this shared definition. */ -export const ATTACHED_WORKSPACE_BASH_SCHEMA: NonNullable = Object.freeze({ - type: 'object', - properties: { - ...bashSchema.properties, - command: attachedCommandSchema, - cwd: attachedWorkingDirectorySchema, - }, - required: ['command'], -}); +export const ATTACHED_WORKSPACE_BASH_SCHEMA: NonNullable = Object.freeze( + buildAttachedWorkspaceBashSchema(), +); export function buildAttachedWorkspaceBashDescription(enableToolOutputReferences: boolean): string { return enableToolOutputReferences @@ -130,23 +178,40 @@ export function createAttachedWorkspaceBashTool({ authHeaders, workspaceId, gitIdentity, + maxTimeoutMs = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, fetchImpl, }: { baseUrl: string; authHeaders: () => Promise> | Record; workspaceId: string; gitIdentity?: AgentGitIdentity | null; + /** Deployment ceiling already intersected with the protocol hard cap. */ + maxTimeoutMs?: number; fetchImpl?: CodeBridgeFetch; }): DynamicStructuredTool { + const effectiveMaxTimeoutMs = normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs); return tool( async ( - rawInput: { command: string; args?: string[]; cwd?: string; intent?: string }, + rawInput: { + command: string; + args?: string[]; + cwd?: string; + timeoutMs?: number; + intent?: string; + }, config, ): Promise<[string, Record]> => { + if (rawInput.timeoutMs != null && rawInput.timeoutMs > effectiveMaxTimeoutMs) { + throw new Error( + `Command timeout exceeds the deployment limit of ${effectiveMaxTimeoutMs} milliseconds.`, + ); + } const command = commandWithGitIdentity( commandWithArguments(rawInput.command, rawInput.args), gitIdentity, ); + const timeoutMs = + rawInput.timeoutMs ?? Math.min(WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, effectiveMaxTimeoutMs); const result = await executeWorkspaceTool({ baseURL: baseUrl, authHeaders: await authHeaders(), @@ -156,6 +221,7 @@ export function createAttachedWorkspaceBashTool({ workspaceId, command, ...(rawInput.cwd ? { cwd: rawInput.cwd } : {}), + timeoutMs, maxOutputBytes: DEFAULT_OUTPUT_BYTES, }, signal: config?.signal, @@ -169,7 +235,7 @@ export function createAttachedWorkspaceBashTool({ { name: BashExecutionToolDefinition.name, description: ATTACHED_WORKSPACE_BASH_DESCRIPTION, - schema: structuredClone(ATTACHED_WORKSPACE_BASH_SCHEMA), + schema: structuredClone(buildAttachedWorkspaceBashSchema(effectiveMaxTimeoutMs)), responseFormat: 'content_and_artifact', }, ) as unknown as DynamicStructuredTool; diff --git a/packages/api/src/code/config.spec.ts b/packages/api/src/code/config.spec.ts index 784c33ad39..b3f3a31042 100644 --- a/packages/api/src/code/config.spec.ts +++ b/packages/api/src/code/config.spec.ts @@ -134,6 +134,9 @@ describe('mergeAccessibleCodeEnvironments', () => { permissions: { commandExecution: { allowed: ['ask', 'deny'], default: 'ask' }, }, + limits: { + maxCommandTimeoutMs: 120_000, + }, }, }, ], @@ -172,6 +175,9 @@ describe('mergeAccessibleCodeEnvironments', () => { permissions: { commandExecution: { allowed: ['ask', 'deny'], default: 'ask' }, }, + limits: { + maxCommandTimeoutMs: 120_000, + }, }, settings: { permissions: { commandExecution: 'deny' } }, }); diff --git a/packages/api/src/code/workspace.ts b/packages/api/src/code/workspace.ts index cedc624b66..900dd6d211 100644 --- a/packages/api/src/code/workspace.ts +++ b/packages/api/src/code/workspace.ts @@ -11,8 +11,9 @@ const MAX_LIST_RESULTS = 500; export const WORKSPACE_WRITE_MAX_BYTES: number = 1024 * 1024; export const WORKSPACE_EDIT_MAX_COUNT: number = 100; const MAX_COMMAND_BYTES = 32 * 1024; -const DEFAULT_COMMAND_TIMEOUT_MS = 30_000; -const MAX_COMMAND_TIMEOUT_MS = 5 * 60_000; +/** Keep aligned with data-provider's deployment schema defaults and hard cap. */ +export const WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS: number = 30_000; +export const WORKSPACE_COMMAND_MAX_TIMEOUT_MS: number = 5 * 60_000; const DEFAULT_COMMAND_OUTPUT_BYTES = 256 * 1024; const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024; const MAX_COMMAND_SIGNAL_LENGTH = 32; @@ -467,7 +468,8 @@ function isValidRequest(request: WorkspaceToolRequest): boolean { request.command.trim().length > 0 && !request.command.includes('\0') && (request.cwd == null || isSafePath(request.cwd)) && - (request.timeoutMs == null || isPositiveInteger(request.timeoutMs, MAX_COMMAND_TIMEOUT_MS)) && + (request.timeoutMs == null || + isPositiveInteger(request.timeoutMs, WORKSPACE_COMMAND_MAX_TIMEOUT_MS)) && (request.maxOutputBytes == null || isPositiveInteger(request.maxOutputBytes, MAX_COMMAND_OUTPUT_BYTES)) ); @@ -658,7 +660,8 @@ function isValidResult( function getWorkspaceToolTimeoutMs(request: WorkspaceToolRequest): number { const executionBudgetMs = request.operation === 'execute_command' - ? (request.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS) + WORKSPACE_COMMAND_SETTLEMENT_GRACE_MS + ? (request.timeoutMs ?? WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS) + + WORKSPACE_COMMAND_SETTLEMENT_GRACE_MS : WORKSPACE_TOOL_TIMEOUT_MS; return WORKSPACE_QUEUE_TIMEOUT_MS + executionBudgetMs + WORKSPACE_COMMAND_TRANSPORT_GRACE_MS; } diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts index 5d3b1ae098..72dafeb6c3 100644 --- a/packages/data-provider/src/config.spec.ts +++ b/packages/data-provider/src/config.spec.ts @@ -237,6 +237,7 @@ describe('attached code environment user config schema', () => { fileWrite: { allowed: ['allow', 'ask', 'deny'], default: 'ask' }, commandExecution: { allowed: ['ask', 'deny'], default: 'ask' }, }, + limits: { maxCommandTimeoutMs: 120000 }, }, }, ], @@ -251,6 +252,30 @@ describe('attached code environment user config schema', () => { expect(result.success).toBe(true); }); + it('rejects an attached command timeout above the protocol hard cap', () => { + const result = configSchema.safeParse({ + version: '1.0', + endpoints: { + agents: { + statefulCodeSessions: { + allowedEnvironments: ['user'], + environments: [ + { + id: 'personal-vm', + name: 'Personal VM', + type: 'attached', + baseURL: 'https://code.example.com/v1', + configSchema: { limits: { maxCommandTimeoutMs: 300001 } }, + }, + ], + }, + }, + }, + }); + + expect(result.success).toBe(false); + }); + it('rejects a permission default the administrator did not expose', () => { const result = configSchema.safeParse({ version: '1.0', diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index d4f1c84fbe..acfa2561e4 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -1116,6 +1116,11 @@ const codeEnvironmentPermissionFieldSchema = z } }); +/** Existing attached commands used a fixed 30-second execution budget. */ +export const CODE_ENVIRONMENT_COMMAND_TIMEOUT_DEFAULT_MS = 30_000; +/** Protocol-level ceiling; deployments may only lower this value. */ +export const CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS = 5 * 60_000; + /** * Typed user-tunable surface for one attached code environment. Omitted fields * remain fixed at LibreChat's safe baseline. Isolation, networking, mounts, @@ -1130,6 +1135,19 @@ export const codeEnvironmentUserConfigSchema = z }) .strict() .optional(), + limits: z + .object({ + /** Maximum timeout a Bash invocation may request. Omission preserves + * the historical 30-second command budget. */ + maxCommandTimeoutMs: z + .number() + .int() + .min(1) + .max(CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS) + .optional(), + }) + .strict() + .optional(), }) .strict();