🥽 feat: Configure Attached Defaults and Honor Skill Read Ranges (#16540)

* feat: configure attached command and read defaults

* fix: separate programmatic timeout defaults from ceilings

* fix: retain attached programmatic schema instructions

* fix: honor explicit skill and sandbox read ranges

* fix: remove duplicate command imports after rebase

* fix: retrieve complete sandbox text before paging

---------

Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
lia-by-librechat[bot] 2026-10-01 19:57:08 -04:00 • committed by GitHub
parent 92432e95d5
commit 59b772f132
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 1751 additions and 135 deletions

View file

@ -1,14 +1,19 @@
import { once } from 'node:events';
import { createServer } from 'node:http';
import { createBashProgrammaticToolCallingTool } from '@librechat/agents';
import type { createBashProgrammaticToolCallingSchema } from '@librechat/agents';
import type { AddressInfo } from 'node:net';
import type { CodeExecutionContext } from '~/agents/execution';
import type { CodeBridgeFetch } from './bridge';
import {
ATTACHED_WORKSPACE_BASH_DESCRIPTION,
ATTACHED_WORKSPACE_BASH_SCHEMA,
buildAttachedWorkspaceBashSchema,
createAttachedWorkspaceBashTool,
createContextProgrammaticBashTool,
createGitIdentityProgrammaticBashTool,
resolveAttachedWorkspaceCommandTimeoutMax,
resolveAttachedWorkspaceCommandTimeoutDefault,
resolveAttachedWorkspaceProgrammaticTimeout,
resolveAttachedWorkspaceQueueWaitMs,
resolveAttachedWorkspaceRequestTimeoutMs,
@ -129,6 +134,243 @@ describe('programmatic Bash Git identity', () => {
}
});
test.each([false, true])(
'preserves the complete attached SDK schema with configured defaults and identity=%s',
(withIdentity) => {
const context: CodeExecutionContext = {
baseUrl: 'http://127.0.0.1:9999/v1',
codeSessionKey: 'execute_code:stateful:attached',
executionProfile: 'stateful',
environmentType: 'attached',
statefulSessions: true,
codeWorkspace: {
environmentId: 'machine',
workspaceId: 'project-a',
workspaceInstanceId: 'a'.repeat(64),
operations: ['execute_command'],
maxCommandTimeoutMs: 80_000,
},
codeEnvironmentConfigSchema: {
limits: { defaultCommandTimeoutMs: 60_000, maxCommandTimeoutMs: 80_000 },
},
};
const baseline = createBashProgrammaticToolCallingTool({
baseUrl: context.baseUrl,
authHeaders: () => ({}),
executionProfile: context.executionProfile,
workspaceId: context.codeWorkspace?.workspaceId,
workspaceInstanceId: context.codeWorkspace?.workspaceInstanceId,
runTimeoutMs: 80_000,
});
const originalSchema = structuredClone(baseline.schema) as ReturnType<
typeof createBashProgrammaticToolCallingSchema
>;
const configured = createContextProgrammaticBashTool(
() => ({}),
context,
withIdentity ? { name: 'Lia', email: 'lia@example.com' } : undefined,
);
const schema = configured.schema as ReturnType<
typeof createBashProgrammaticToolCallingSchema
>;
expect(schema.properties.code).toEqual(originalSchema.properties.code);
expect(schema.properties.code.description).toContain('ATTACHED WORKSPACE EXECUTION');
expect(schema.properties.code.description).toContain('${LIBRECHAT_CODE_DATA_DIR:-/mnt/data}');
expect(schema).toEqual({
...originalSchema,
properties: {
...originalSchema.properties,
timeout: {
...originalSchema.properties.timeout,
default: 60_000,
description: expect.stringContaining('when timeout is omitted'),
},
},
});
expect(configured.description).toBe(baseline.description);
expect(configured.schema).not.toBe(baseline.schema);
expect(baseline.schema).toEqual(originalSchema);
expect(
createContextProgrammaticBashTool(() => ({}), {
...context,
codeEnvironmentConfigSchema: { limits: { maxCommandTimeoutMs: 80_000 } },
}).schema,
).toEqual(originalSchema);
},
);
test('uses the foreground default only when the real SDK programmatic call omits timeout', async () => {
const received: { timeout: number; code: string }[] = [];
const server = createServer(async (req, res) => {
let body = '';
for await (const chunk of req) body += chunk;
received.push(JSON.parse(body));
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'completed', stdout: 'done', stderr: '', files: [] }));
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address() as AddressInfo;
try {
const bashTool = createContextProgrammaticBashTool(
() => ({}),
{
baseUrl: `http://127.0.0.1:${port}/v1`,
codeSessionKey: 'execute_code:stateful:attached',
executionProfile: 'stateful',
environmentType: 'attached',
statefulSessions: true,
codeWorkspace: {
environmentId: 'machine',
workspaceId: 'project-a',
operations: ['execute_command'],
maxCommandTimeoutMs: 80_000,
},
codeEnvironmentConfigSchema: {
limits: { defaultCommandTimeoutMs: 60_000, maxCommandTimeoutMs: 80_000 },
},
},
{ name: 'Lia', email: 'lia@example.com' },
);
const invocationConfig = {
tags: [],
toolCall: { name: 'run_tools_with_bash', args: {}, toolDefs: [] },
};
for (const timeout of [undefined, 75_000, 10_000, 90_000]) {
await bashTool.invoke(
{ code: 'printf done', tool_manifest: [], ...(timeout == null ? {} : { timeout }) },
invocationConfig,
);
}
expect(received.map(({ timeout }) => timeout)).toEqual([60_000, 75_000, 10_000, 80_000]);
expect(received.every(({ code }) => code.includes("GIT_AUTHOR_NAME='Lia'"))).toBe(true);
expect(bashTool.schema).toMatchObject({
properties: {
timeout: {
default: 60_000,
description: expect.stringContaining('Default: 60000 milliseconds'),
},
},
});
expect(bashTool.schema).toMatchObject({
properties: {
timeout: { description: expect.stringContaining('Configured cap: 80000 milliseconds') },
},
});
} finally {
server.close();
await once(server, 'close');
}
});
test.each([
[60_000, 80_000, 50_000, undefined, 50_000, 50_000],
[60_000, 80_000, 80_000, 65_000, 45_000, 45_000],
[120_000, 80_000, 80_000, undefined, 80_000, 75_000],
[1, 80_000, 80_000, undefined, 1_000, 75_000],
[undefined, 80_000, 80_000, undefined, 80_000, 75_000],
[undefined, undefined, 90_000, undefined, 30_000, 30_000],
])(
'keeps real SDK defaults and explicit calls within admin/worker/HTTP ceilings (%s, %s, %s, %s)',
async (
defaultCommandTimeoutMs,
maxCommandTimeoutMs,
upstreamMaxTimeoutMs,
maxRequestTimeoutMs,
expectedDefault,
expectedExplicit,
) => {
const received: { timeout: number }[] = [];
const server = createServer(async (req, res) => {
let body = '';
for await (const chunk of req) body += chunk;
received.push(JSON.parse(body));
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'completed', stdout: 'done', stderr: '', files: [] }));
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address() as AddressInfo;
try {
const bashTool = createContextProgrammaticBashTool(() => ({}), {
baseUrl: `http://127.0.0.1:${port}/v1`,
codeSessionKey: 'execute_code:stateful:attached',
executionProfile: 'stateful',
environmentType: 'attached',
statefulSessions: true,
codeWorkspace: {
environmentId: 'machine',
workspaceId: 'project-a',
operations: ['execute_command'],
maxCommandTimeoutMs: upstreamMaxTimeoutMs,
},
codeEnvironmentConfigSchema: {
limits: { defaultCommandTimeoutMs, maxCommandTimeoutMs, maxRequestTimeoutMs },
},
});
const config = { tags: [], toolCall: { toolDefs: [] } };
await bashTool.func({ code: 'printf done', tool_manifest: [] }, undefined, config);
await bashTool.func(
{ code: 'printf done', tool_manifest: [], timeout: 75_000 },
undefined,
config,
);
expect(received.map(({ timeout }) => timeout)).toEqual([expectedDefault, expectedExplicit]);
expect(bashTool.schema).toMatchObject({
properties: { timeout: { default: expectedDefault } },
});
} finally {
server.close();
await once(server, 'close');
}
},
);
test('refuses a newly configured programmatic ceiling below the SDK floor instead of raising it', () => {
expect(() =>
createContextProgrammaticBashTool(() => ({}), {
baseUrl: 'http://127.0.0.1:9999/v1',
codeSessionKey: 'execute_code:stateful:attached',
executionProfile: 'stateful',
environmentType: 'attached',
statefulSessions: true,
codeEnvironmentConfigSchema: {
limits: { defaultCommandTimeoutMs: 1, maxCommandTimeoutMs: 500 },
},
}),
).toThrow('requires a timeout ceiling of at least 1000 milliseconds');
});
test('resolves the programmatic ceiling independently of the foreground default', () => {
expect(
resolveAttachedWorkspaceProgrammaticTimeout(
{ limits: { defaultCommandTimeoutMs: 60_000, maxCommandTimeoutMs: 80_000 } },
70_000,
),
).toBe(70_000);
expect(
resolveAttachedWorkspaceProgrammaticTimeout(
{ limits: { defaultCommandTimeoutMs: 60_000, maxCommandTimeoutMs: 80_000 } },
50_000,
),
).toBe(50_000);
expect(
resolveAttachedWorkspaceProgrammaticTimeout({ limits: { defaultCommandTimeoutMs: 60_000 } }),
).toBe(30_000);
expect(
resolveAttachedWorkspaceProgrammaticTimeout(
{
limits: {
defaultCommandTimeoutMs: 60_000,
maxCommandTimeoutMs: 80_000,
maxRequestTimeoutMs: 65_000,
},
},
80_000,
),
).toBe(45_000);
});
test('preserves the foreground timeout while bounding an explicit admin override', () => {
expect(resolveAttachedWorkspaceProgrammaticTimeout(undefined, 90_000)).toBe(30_000);
expect(
@ -164,6 +406,85 @@ function commandResponse(overrides: Record<string, unknown> = {}): Response {
}
describe('createAttachedWorkspaceBashTool', () => {
test.each([
[60_000, 80_000, undefined, 60_000],
[120_000, 80_000, undefined, 80_000],
[60_000, 80_000, 65_000, 45_000],
[60_000, 5_000, undefined, 5_000],
[1, 80_000, undefined, 1],
])(
'bounds foreground default %i by ceiling %i and HTTP budget %s',
async (defaultTimeoutMs, maxTimeoutMs, maxRequestTimeoutMs, expected) => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1',
authHeaders: () => ({}),
workspaceId: 'project-a',
defaultTimeoutMs,
maxTimeoutMs,
maxRequestTimeoutMs,
fetchImpl,
});
await bashTool.invoke({ command: 'npm test' });
expect(JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body))).toMatchObject({
timeoutMs: expected,
});
expect(bashTool.schema).toMatchObject({
properties: {
timeoutMs: {
description: expect.stringContaining(`Defaults to ${expected} for foreground calls`),
},
},
});
},
);
test('keeps explicit and background timeouts independent of the foreground default', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1',
authHeaders: () => ({}),
workspaceId: 'project-a',
defaultTimeoutMs: 60_000,
maxTimeoutMs: 80_000,
fetchImpl,
});
await bashTool.invoke({ command: 'npm test', timeoutMs: 10_000 });
await bashTool.invoke(
{ command: 'npm test' },
{ configurable: { [BACKGROUND_TOOL_INVOCATION_CONFIG_KEY]: true } },
);
await bashTool.invoke(
{ command: 'npm test', timeoutMs: 20_000 },
{ configurable: { [BACKGROUND_TOOL_INVOCATION_CONFIG_KEY]: true } },
);
expect(
(fetchImpl as jest.Mock).mock.calls.map(
([, init]) => JSON.parse(String(init?.body)).timeoutMs,
),
).toEqual([10_000, 80_000, 20_000]);
});
test.each([0, -1, 1.5, NaN, Infinity])(
'falls back safely for invalid foreground default %s',
(defaultTimeoutMs) => {
expect(resolveAttachedWorkspaceCommandTimeoutDefault(defaultTimeoutMs, 80_000)).toBe(30_000);
},
);
test('does not raise the command ceiling when only a foreground default is configured', () => {
const maxTimeoutMs = resolveAttachedWorkspaceCommandTimeoutMax({
limits: { defaultCommandTimeoutMs: 60_000 },
});
expect(maxTimeoutMs).toBe(30_000);
expect(resolveAttachedWorkspaceCommandTimeoutDefault(60_000, maxTimeoutMs)).toBe(30_000);
const upstreamMax = resolveAttachedWorkspaceCommandTimeoutMax(
{ limits: { defaultCommandTimeoutMs: 60_000 } },
50_000,
);
expect(resolveAttachedWorkspaceCommandTimeoutDefault(60_000, upstreamMax)).toBe(50_000);
});
test('honors a zero Code API rate-limit retry budget', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(
async () => new Response(JSON.stringify({ error: 'rate_limited' }), { status: 429 }),
@ -729,6 +1050,31 @@ describe('createAttachedWorkspaceBashTool', () => {
expect(request.command).not.toContain('git config');
});
test('reports the requested timeout and effective retry ceiling after HTTP-budget clamping', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () =>
commandResponse({ exitCode: null, timedOut: true, stdout: 'partial work', stderr: '' }),
);
const bashTool = createAttachedWorkspaceBashTool({
baseUrl: 'https://code.example.com/v1',
authHeaders: () => ({}),
workspaceId: 'project-a',
defaultTimeoutMs: 60_000,
maxTimeoutMs: 80_000,
maxRequestTimeoutMs: 90_000,
fetchImpl,
});
const [content] = await bashTool.func(
{ command: 'npm test', timeoutMs: 10_000 },
undefined,
{},
);
expect(content).toContain('partial work');
expect(content).toContain('timeoutMs: 10000');
expect(content).toContain('up to 70000 milliseconds');
expect(content).not.toContain('up to 80000');
expect(content).toContain('partial side effects');
});
test('reports termination, timeouts, and truncation without hiding stderr', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () =>
commandResponse({
@ -748,7 +1094,7 @@ describe('createAttachedWorkspaceBashTool', () => {
});
await expect(bashTool.func({ command: 'sleep 60' }, undefined, {})).resolves.toEqual([
'stderr:\ndeadline reached\n[terminated by SIGKILL][timed out][output truncated]',
'stderr:\ndeadline reached\n[terminated by SIGKILL][timed out][output truncated]\nCommand reached timeoutMs: 30000. Before retrying, check for partial side effects. Set timeoutMs explicitly up to 30000 milliseconds, or use run_in_background: true if available. Background execution uses the same timeout ceiling.',
{},
]);
});

View file

@ -11,6 +11,7 @@ import type {
CodeEnvironmentUserConfigSchema,
CodeWorkspaceDescriptor,
} from 'librechat-data-provider';
import type { createBashProgrammaticToolCallingSchema } from '@librechat/agents';
import type { DynamicStructuredTool } from '@librechat/agents/langchain/tools';
import type { LCTool } from '@librechat/agents';
import type { WorkspaceExecuteCommandResult } from './workspace';
@ -108,8 +109,14 @@ interface BoundedTimeoutSchema {
description: string;
}
function buildAttachedTimeoutSchema(maxTimeoutMs: number): BoundedTimeoutSchema {
const defaultTimeoutMs = Math.min(WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, maxTimeoutMs);
function buildAttachedTimeoutSchema(
maxTimeoutMs: number,
foregroundTimeoutMs: number,
): BoundedTimeoutSchema {
const defaultTimeoutMs = resolveAttachedWorkspaceCommandTimeoutDefault(
foregroundTimeoutMs,
maxTimeoutMs,
);
return {
type: 'integer',
minimum: 1,
@ -125,6 +132,17 @@ function normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs: number): numb
return Math.min(WORKSPACE_COMMAND_MAX_TIMEOUT_MS, maxTimeoutMs);
}
/** Foreground defaults never raise the negotiated execution ceiling. */
export function resolveAttachedWorkspaceCommandTimeoutDefault(
defaultTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
maxTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
): number {
return Math.min(
normalizeAttachedWorkspaceCommandTimeoutMax(defaultTimeoutMs),
normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs),
);
}
export function resolveAttachedWorkspaceCommandTimeoutMax(
configSchema?: CodeEnvironmentUserConfigSchema,
upstreamMaxTimeoutMs?: number,
@ -161,13 +179,18 @@ function fitCommandTimeoutMaxToBudget(
/**
* Programmatic calls do not currently carry the detached-invocation marker.
* Preserve their historical foreground default while still enforcing both an
* explicit administrator override and the live upstream ceiling.
* The SDK's runTimeoutMs is a ceiling, not an omission-only default. When the
* environment configures a foreground default, resolve its ceiling separately;
* otherwise retain the legacy maxCommandTimeoutMs behavior on this SDK route.
*/
export function resolveAttachedWorkspaceProgrammaticTimeout(
configSchema?: CodeEnvironmentUserConfigSchema,
upstreamMaxTimeoutMs?: number,
): number {
const defaultTimeoutMs = configSchema?.limits?.defaultCommandTimeoutMs;
if (defaultTimeoutMs != null) {
return resolveAttachedWorkspaceCommandTimeoutMax(configSchema, upstreamMaxTimeoutMs);
}
const configured = configSchema?.limits?.maxCommandTimeoutMs;
const requested =
configured == null
@ -219,6 +242,7 @@ export function buildAttachedWorkspaceBashSchema(
maxTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
environment?: CodeWorkspaceDescriptor['environment'],
linkedWorktrees = false,
defaultTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
): NonNullable<LCTool['parameters']> {
const effectiveMaxTimeoutMs = normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs);
return {
@ -230,7 +254,7 @@ export function buildAttachedWorkspaceBashSchema(
linkedWorktrees === true
? linkedWorktreeWorkingDirectorySchema
: attachedWorkingDirectorySchema,
timeoutMs: buildAttachedTimeoutSchema(effectiveMaxTimeoutMs),
timeoutMs: buildAttachedTimeoutSchema(effectiveMaxTimeoutMs, defaultTimeoutMs),
...(environment?.actions.length
? {
environmentAction: {
@ -326,7 +350,35 @@ export function createContextProgrammaticBashTool(
}
: {}),
};
return createGitIdentityProgrammaticBashTool(options, attached ? identity : undefined);
const bashTool = createGitIdentityProgrammaticBashTool(options, attached ? identity : undefined);
const configuredDefault = attached
? context.codeEnvironmentConfigSchema?.limits?.defaultCommandTimeoutMs
: undefined;
if (configuredDefault == null) return bashTool;
const maxTimeoutMs = options.runTimeoutMs ?? WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS;
const schema = structuredClone(bashTool.schema) as ReturnType<
typeof createBashProgrammaticToolCallingSchema
>;
const minimumTimeoutMs = schema.properties.timeout.minimum;
if (maxTimeoutMs < minimumTimeoutMs) {
throw new Error(
`Attached programmatic execution requires a timeout ceiling of at least ${minimumTimeoutMs} milliseconds. Use bash_tool for shorter command budgets.`,
);
}
const defaultTimeoutMs = Math.max(
minimumTimeoutMs,
resolveAttachedWorkspaceCommandTimeoutDefault(configuredDefault, maxTimeoutMs),
);
schema.properties.timeout.default = defaultTimeoutMs;
schema.properties.timeout.description = `Maximum wall-clock time in milliseconds for one sandbox run or replay iteration, not the total multi-round-trip task budget. Default: ${defaultTimeoutMs} milliseconds when timeout is omitted. Accepted values above the configured cap are clamped before execution. Configured cap: ${maxTimeoutMs} milliseconds.`;
bashTool.schema = schema;
const execute = bashTool.func.bind(bashTool);
bashTool.func = (input, ...args) => {
const params = input as { timeout?: number };
return execute({ ...params, timeout: params.timeout ?? defaultTimeoutMs }, ...args);
};
return bashTool;
}
/** Apply authorship before the SDK prepares the script and its replay requests. */
@ -344,7 +396,11 @@ export function createGitIdentityProgrammaticBashTool(
return bashTool;
}
function formatCommandResult(result: WorkspaceExecuteCommandResult): string {
function formatCommandResult(
result: WorkspaceExecuteCommandResult,
timeoutMs: number,
maxTimeoutMs: number,
): string {
let output = '';
if (result.stdout.length > 0) output += `stdout:\n${result.stdout}\n`;
if (result.stderr.length > 0) output += `stderr:\n${result.stderr}\n`;
@ -353,6 +409,9 @@ function formatCommandResult(result: WorkspaceExecuteCommandResult): string {
if (result.signal != null) output += `[terminated by ${result.signal}]`;
if (result.timedOut) output += '[timed out]';
if (result.truncated) output += '[output truncated]';
if (result.timedOut) {
output += `\nCommand reached timeoutMs: ${timeoutMs}. Before retrying, check for partial side effects. Set timeoutMs explicitly up to ${maxTimeoutMs} milliseconds, or use run_in_background: true if available. Background execution uses the same timeout ceiling.`;
}
return output;
}
@ -364,6 +423,7 @@ export function createAttachedWorkspaceBashTool({
environment,
gitIdentity,
maxTimeoutMs = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
defaultTimeoutMs = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
maxQueueWaitMs,
codeApiMaxRetryWaitMs,
maxRequestTimeoutMs,
@ -381,6 +441,8 @@ export function createAttachedWorkspaceBashTool({
gitIdentity?: AgentGitIdentity | null;
/** Effective admin/upstream ceiling already intersected with the protocol hard cap. */
maxTimeoutMs?: number;
/** Foreground timeout when omitted by the model; bounded by the effective ceiling. */
defaultTimeoutMs?: number;
/** Retry horizon across typed queue expirations, not an admission budget. */
maxQueueWaitMs?: number;
codeApiMaxRetryWaitMs?: number;
@ -395,8 +457,17 @@ export function createAttachedWorkspaceBashTool({
maxRequestTimeoutMs,
minCommandAdmissionMs,
);
const effectiveDefaultTimeoutMs = resolveAttachedWorkspaceCommandTimeoutDefault(
defaultTimeoutMs,
effectiveMaxTimeoutMs,
);
const schema = structuredClone(
buildAttachedWorkspaceBashSchema(effectiveMaxTimeoutMs, environment, linkedWorktrees),
buildAttachedWorkspaceBashSchema(
effectiveMaxTimeoutMs,
environment,
linkedWorktrees,
effectiveDefaultTimeoutMs,
),
);
const actions = environment?.actions ?? [];
const bashTool = tool(
@ -437,7 +508,7 @@ export function createAttachedWorkspaceBashTool({
rawInput.timeoutMs ??
(config?.configurable?.[BACKGROUND_TOOL_INVOCATION_CONFIG_KEY] === true
? effectiveMaxTimeoutMs
: Math.min(WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS, effectiveMaxTimeoutMs));
: effectiveDefaultTimeoutMs);
const signal = config?.signal;
const trace = {
runId: config?.metadata?.run_id,
@ -478,7 +549,7 @@ export function createAttachedWorkspaceBashTool({
throw new Error('Attached workspace returned an unexpected command result.');
}
logger.debug('[BYOMCommand] transport completed', trace);
return [formatCommandResult(result), {}];
return [formatCommandResult(result, timeoutMs, effectiveMaxTimeoutMs), {}];
} finally {
signal?.removeEventListener('abort', onAbort);
logger.debug('[BYOMCommand] transport settled', {

View file

@ -1,6 +1,28 @@
import type { WorkspaceToolRequest } from './workspace';
import type { CodeBridgeFetch } from './bridge';
import { executeWorkspaceTool, WorkspaceToolHttpError } from './workspace';
import {
executeWorkspaceTool,
WorkspaceToolHttpError,
resolveAttachedWorkspaceReadFileLines,
} from './workspace';
describe('attached read window defaults', () => {
test('preserves the legacy read window unless configured', () => {
expect(resolveAttachedWorkspaceReadFileLines()).toBe(200);
expect(resolveAttachedWorkspaceReadFileLines({ limits: {} })).toBe(200);
expect(resolveAttachedWorkspaceReadFileLines({ limits: { defaultReadFileLines: 500 } })).toBe(
500,
);
expect(resolveAttachedWorkspaceReadFileLines({ limits: { defaultReadFileLines: 1 } })).toBe(1);
});
test.each([0, -1, 1.5, 501, NaN, Infinity])(
'falls back safely for an invalid read window %s',
(defaultReadFileLines) => {
expect(resolveAttachedWorkspaceReadFileLines({ limits: { defaultReadFileLines } })).toBe(200);
},
);
});
describe('workspace admission feedback', () => {
test('forwards a valid conversation workspace instance unchanged', async () => {

View file

@ -1,9 +1,13 @@
import {
CODE_ENVIRONMENT_ADMISSION_MAX_MS,
CODE_ENVIRONMENT_COMMAND_TIMEOUT_DEFAULT_MS,
CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES,
CODE_ENVIRONMENT_READ_FILE_HARD_MAX_LINES,
CODE_ENVIRONMENT_COMMAND_ADMISSION_DEFAULT_MS,
CODE_ENVIRONMENT_QUEUE_WAIT_DEFAULT_MS,
CODE_ENVIRONMENT_REQUEST_TIMEOUT_HARD_MAX_MS,
} from 'librechat-data-provider';
import type { CodeEnvironmentUserConfigSchema } from 'librechat-data-provider';
import type { WorkspaceEditMatch, WorkspaceEditMatching } from './edits';
import type { CodeBridgeFetch } from './bridge';
import { CODE_API_RATE_LIMIT_WAIT_DEFAULT_MS } from './limits';
@ -13,7 +17,7 @@ const WORKSPACE_TOOL_TIMEOUT_MS = 30_000;
const MAX_PATH_LENGTH = 4096;
const MAX_QUERY_LENGTH = 4096;
const MAX_READ_BYTES = 1024 * 1024;
const MAX_READ_LINES = 500;
const MAX_READ_LINES = CODE_ENVIRONMENT_READ_FILE_HARD_MAX_LINES;
const MAX_SEARCH_RESULTS = 200;
const MAX_SEARCH_TEXT_LENGTH = 2000;
const MAX_LIST_RESULTS = 500;
@ -21,7 +25,8 @@ export const WORKSPACE_WRITE_MAX_BYTES: number = 1024 * 1024;
export const WORKSPACE_EDIT_MAX_COUNT: number = 100;
const MAX_COMMAND_BYTES = 32 * 1024;
/** 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_DEFAULT_TIMEOUT_MS: number =
CODE_ENVIRONMENT_COMMAND_TIMEOUT_DEFAULT_MS;
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;
@ -1071,6 +1076,19 @@ export function fromLinkedWorktreeResult(
}
}
/** Resolves a bounded read window without changing the protocol-v1 byte or line ceilings. */
export function resolveAttachedWorkspaceReadFileLines(
configSchema?: CodeEnvironmentUserConfigSchema,
): number {
const configured = configSchema?.limits?.defaultReadFileLines;
return configured != null &&
Number.isSafeInteger(configured) &&
configured >= 1 &&
configured <= MAX_READ_LINES
? configured
: CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES;
}
export async function executeWorkspaceTool({
baseURL,
authHeaders,