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

⛺ feat: Report Attached Bash Starting Directories (#16539)

lia-by-librechat[bot]1bd8d719d482
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/command.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/command.test.ts
index 73507ae504..da55d4f0e5 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/command.test.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/command.test.ts
@@ -35,6 +35,67 @@ describe('parseCommandOutput', () => {
});
});
+ it.each([
+ ['stdout:\nready\n\n[exit code: 0]', 0, false, ''],
+ ['stderr:\nboom\n[exit code: 2]', 2, true, 'stderr:\nboom\n'],
+ ['Command completed with no output.\n[exit code: 0]', 0, false, ''],
+ ])('preserves directory labels and parses the verdict: %s', (body, exitCode, failed, stderr) => {
+ const directory = `[starting directory: ${JSON.stringify('workspace/folder\t"name')}]\n`;
+ const output = directory + body;
+ const result = parseCommandOutput(output);
+ expect(result).toMatchObject({ exitCode, failed, stderr });
+ expect(result?.head).toContain(directory);
+ expect(`${result?.head}${result?.stderr}${result?.trailer}`).toBe(output);
+ });
+
+ it.each([
+ ['', '\n[directory hint: pass cwd instead of a leading cd.]'],
+ ['\nCommand reached timeoutMs: 10000. Check partial side effects.', ''],
+ [
+ '\nCommand reached timeoutMs: 10000. Check partial side effects.',
+ '\n[directory hint: pass cwd instead of a leading cd.]',
+ ],
+ ])('preserves host guidance following timeout markers: %s %s', (timeoutHint, directoryHint) => {
+ const output =
+ '[starting directory: "workspace/.worktrees/fix-a"]\nstdout:\npartial work\nstderr:\nkilled\n' +
+ '[terminated by SIGKILL][timed out][output truncated]' +
+ timeoutHint +
+ directoryHint;
+ const result = parseCommandOutput(output);
+ expect(result).toMatchObject({
+ exitCode: null,
+ signal: 'SIGKILL',
+ timedOut: true,
+ truncated: true,
+ failed: true,
+ stderr: 'stderr:\nkilled\n',
+ });
+ expect(result?.trailer).toBe(
+ '[terminated by SIGKILL][timed out][output truncated]' + timeoutHint + directoryHint,
+ );
+ expect(`${result?.head}${result?.stderr}${result?.trailer}`).toBe(output);
+ });
+
+ it('uses the final verdict instead of marker-like stdout before host guidance', () => {
+ const output =
+ '[starting directory: "workspace/"]\nstdout:\n[exit code: 1]\n' +
+ '[directory hint: printed by the command]\n\n[exit code: 0]\n' +
+ '[directory hint: pass cwd instead of a leading cd.]';
+ expect(parseCommandOutput(output)).toMatchObject({ exitCode: 0, failed: false });
+ });
+
+ it('rejects malformed headers and unrecognized text after the verdict', () => {
+ expect(
+ parseCommandOutput(
+ '[starting directory: "workspace/unterminated]\nstdout:\nok\n[exit code: 0]',
+ ),
+ ).toBeNull();
+ expect(
+ parseCommandOutput('[starting directory: "workspace/"]\nError: rate limited\n[exit code: 1]'),
+ ).toBeNull();
+ expect(parseCommandOutput('stdout:\nok\n[exit code: 0]\nrandom text')).toBeNull();
+ });
+
it('returns null for output without the attached-workspace trailer', () => {
expect(parseCommandOutput('stdout:\nhello\n')).toBeNull();
expect(parseCommandOutput('')).toBeNull();
diff --git a/client/src/components/Chat/Messages/Content/Parts/command.ts b/client/src/components/Chat/Messages/Content/Parts/command.ts
index 5448de74d7..169f69032a 100644
--- a/client/src/components/Chat/Messages/Content/Parts/command.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/command.ts
@@ -4,6 +4,8 @@
*
* stdout:\n<out>\n stderr:\n<err>\n [exit code: N][terminated by SIG][timed out][output truncated]
*
+ * An optional starting-directory header and timeout/cwd guidance are preserved.
+ *
* The text alone does not prove where it came from: the sandbox `bash_tool`
* shares the name and trims its output, so a sandbox command that prints
* `[exit code: 1]` last yields the same shape. Callers must only parse output
@@ -19,14 +21,15 @@ export interface CommandOutput {
failed: boolean;
/** `head + stderr + trailer === output`, so a renderer can style each part
* without dropping any text. `head` is the stdout section (or the
- * no-output notice), `stderr` the stderr section with its label. */
+ * no-output notice), including any directory header; `stderr` keeps its label. */
head: string;
stderr: string;
trailer: string;
}
+const STARTING_DIRECTORY = /^\[starting directory: "workspace\/(?:[^"\\\r\n]|\\[^\r\n])*"\]\n/;
const TRAILER =
- /\n((?:\[(?:exit code: -?\d+|terminated by [\w+-]+|timed out|output truncated)\])+)$/;
+ /\n((?:\[(?:exit code: -?\d+|terminated by [\w+-]+|timed out|output truncated)\])+)((?:\nCommand reached timeoutMs: [^\n]*)?(?:\n\[directory hint: [^\n]*\])?)$/;
const MARKER = /\[(exit code: (-?\d+)|terminated by ([\w+-]+)|timed out|output truncated)\]/g;
const STDOUT = 'stdout:\n';
const STDERR = 'stderr:\n';
@@ -38,7 +41,9 @@ export function parseCommandOutput(output: string): CommandOutput | null {
return null;
}
const body = output.slice(0, match.index + 1);
- if (!body.startsWith(STDOUT) && !body.startsWith(STDERR) && body !== EMPTY) {
+ const directoryLength = STARTING_DIRECTORY.exec(body)?.[0].length ?? 0;
+ const content = body.slice(directoryLength);
+ if (!content.startsWith(STDOUT) && !content.startsWith(STDERR) && content !== EMPTY) {
return null;
}
let exitCode: number | null = null;
@@ -59,8 +64,10 @@ export function parseCommandOutput(output: string): CommandOutput | null {
/** The last label wins: output that itself prints `stderr:` is ambiguous,
* and styling too little as stderr is the safer mistake. Either way no
* text is dropped. */
- const labelAt = body.startsWith(STDERR) ? 0 : body.lastIndexOf(`\n${STDERR}`) + 1;
- const split = labelAt > 0 || body.startsWith(STDERR) ? labelAt : body.length;
+ const labelAt = content.startsWith(STDERR)
+ ? directoryLength
+ : body.lastIndexOf(`\n${STDERR}`) + 1;
+ const split = labelAt > 0 || content.startsWith(STDERR) ? labelAt : body.length;
return {
exitCode,
signal,
@@ -69,6 +76,6 @@ export function parseCommandOutput(output: string): CommandOutput | null {
failed: (exitCode != null && exitCode !== 0) || signal != null || timedOut,
head: body.slice(0, split),
stderr: body.slice(split),
- trailer: match[1],
+ trailer: match[1] + match[2],
};
}
diff --git a/packages/api/src/code/command.spec.ts b/packages/api/src/code/command.spec.ts
index 2b058d63de..b73c530a3f 100644
--- a/packages/api/src/code/command.spec.ts
+++ b/packages/api/src/code/command.spec.ts
@@ -1,8 +1,13 @@
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { once } from 'node:events';
import { createServer } from 'node:http';
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, mkdir, rm } from 'node:fs/promises';
import { createBashProgrammaticToolCallingTool } from '@librechat/agents';
import type { createBashProgrammaticToolCallingSchema } from '@librechat/agents';
import type { AddressInfo } from 'node:net';
+import type { WorkspaceExecuteCommandRequest } from './workspace';
import type { CodeExecutionContext } from '~/agents/execution';
import type { CodeBridgeFetch } from './bridge';
import {
@@ -30,6 +35,10 @@ describe('attached workspace Bash contract', () => {
expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('/tmp, $TMPDIR');
expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('global/system packages');
expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('background processes do not survive');
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('not the final directory');
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain(
+ 'Scripts are not automatically rewritten',
+ );
});
test('keeps the command parameter persistence warning next to generated commands', () => {
@@ -537,7 +546,9 @@ describe('createAttachedWorkspaceBashTool', () => {
},
fetchImpl,
});
- await bashTool.invoke({ environmentAction: 'typecheck' });
+ const content = await bashTool.invoke({ environmentAction: 'typecheck' });
+ expect(content).toContain('[starting directory: "workspace/"]');
+ expect(content).not.toContain('directory hint');
const [, options] = (fetchImpl as jest.Mock).mock.calls[0];
expect(JSON.parse(options.body)).toMatchObject({
workspaceId: 'project-a',
@@ -613,7 +624,10 @@ describe('createAttachedWorkspaceBashTool', () => {
await expect(
bashTool.func({ command: 'pwd', cwd: 'packages/api' }, undefined, {}),
- ).resolves.toEqual(['stdout:\nready\n\n[exit code: 0]', {}]);
+ ).resolves.toEqual([
+ '[starting directory: "workspace/packages/api"]\nstdout:\nready\n\n[exit code: 0]',
+ {},
+ ]);
expect(authHeaders).toHaveBeenCalledTimes(1);
expect(fetchImpl).toHaveBeenCalledWith(
@@ -648,12 +662,150 @@ describe('createAttachedWorkspaceBashTool', () => {
});
expect(JSON.stringify(bashTool.schema)).toContain('.worktrees/<name>');
- await bashTool.func({ command: 'npm test', cwd: '.worktrees/fix-a/api' }, undefined, {});
+ const [content] = await bashTool.func(
+ { command: 'npm test', cwd: '.worktrees/fix-a/api' },
+ undefined,
+ {},
+ );
+ expect(content).toContain('[starting directory: "workspace/.worktrees/fix-a/api"]');
const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body));
expect(request).toMatchObject({ command: 'npm test', cwd: 'api', worktree: 'fix-a' });
});
+ test('reports the workspace root even when a command produces no output', async () => {
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ fetchImpl: async () => commandResponse({ stdout: '' }),
+ });
+
+ await expect(bashTool.invoke({ command: 'true' })).resolves.toBe(
+ '[starting directory: "workspace/"]\nCommand completed with no output.\n[exit code: 0]',
+ );
+ });
+
+ test.each([
+ 'cd packages/api && npm test',
+ '\n\tcd "packages/api" && printf "%s" "$OLDPWD"',
+ 'cd missing && npm test || printf fallback',
+ 'cd "$DIRECTORY" && npm test',
+ 'cd .. && pwd',
+ 'cd - && pwd',
+ 'cd',
+ ])('preserves the script and root lane while suggesting cwd: %s', async (command) => {
+ const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ linkedWorktrees: true,
+ fetchImpl,
+ });
+
+ const content = await bashTool.invoke({ command });
+ expect(content).toContain('[starting directory: "workspace/"]');
+ expect(content).toContain('pass cwd instead of a leading cd');
+ expect(content).toContain('does not select a linked-worktree lane');
+ expect(content).toContain('This command was not rewritten; do not rerun it');
+ const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body));
+ expect(request.command).toBe(command);
+ expect(request).not.toHaveProperty('cwd');
+ expect(request).not.toHaveProperty('worktree');
+ });
+
+ test('keeps cd worktree scripts root-scoped and directory feedback stateless', async () => {
+ const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ linkedWorktrees: true,
+ fetchImpl,
+ });
+ const command = 'cd .worktrees/fix-a && npm test';
+ await bashTool.invoke({ command });
+ const content = await bashTool.invoke({ command: 'pwd' });
+ expect(content).toContain('[starting directory: "workspace/"]');
+ expect(content).not.toContain('directory hint');
+ const requests = (fetchImpl as jest.Mock).mock.calls.map((call) =>
+ JSON.parse(String(call[1]?.body)),
+ );
+ expect(requests[0].command).toBe(command);
+ for (const request of requests) {
+ expect(request).not.toHaveProperty('cwd');
+ expect(request).not.toHaveProperty('worktree');
+ }
+ });
+
+ test('escapes directory labels and does not mistake command names for cd', async () => {
+ const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ fetchImpl,
+ });
+ const cwd = 'folder\t"name';
+ const content = await bashTool.invoke({ command: 'cdrom --help', cwd });
+ expect(content).toContain(`[starting directory: ${JSON.stringify(`workspace/${cwd}`)}]`);
+ expect(content).not.toContain('directory hint');
+ expect(JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body)).cwd).toBe(cwd);
+ });
+
+ test('never suggests linked-worktree routing when it was not negotiated', async () => {
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ fetchImpl: async () => commandResponse(),
+ });
+ const content = await bashTool.invoke({ command: 'cd child && pwd', cwd: 'parent' });
+ expect(content).toContain('[starting directory: "workspace/parent"]');
+ expect(content).toContain('directory hint');
+ expect(content).not.toContain('linked-worktree lane');
+ });
+
+ test('reports the starting directory without changing real Bash state or fallback behavior', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'lc-command-directory-'));
+ const root = join(directory, 'project');
+ await mkdir(join(root, 'child'), { recursive: true });
+ const fetchImpl: CodeBridgeFetch = async (_url, init) => {
+ const request = JSON.parse(String(init?.body)) as WorkspaceExecuteCommandRequest;
+ const stdout = execFileSync('bash', ['-c', request.command], {
+ cwd: request.cwd ? join(root, request.cwd) : root,
+ encoding: 'utf8',
+ });
+ return commandResponse({ stdout });
+ };
+ const bashTool = createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ fetchImpl,
+ });
+ try {
+ const content = await bashTool.invoke({
+ command: 'cd child && printf "%s/%s" "${OLDPWD##*/}" "${PWD##*/}"',
+ });
+ expect(content).toContain('[starting directory: "workspace/"]');
+ expect(content).toContain('stdout:\nproject/child');
+ expect(content).not.toContain(directory);
+ const fallback = await bashTool.invoke({
+ command: 'cd missing 2>/dev/null && printf unexpected || printf fallback',
+ });
+ expect(fallback).toContain('stdout:\nfallback');
+ const next = await bashTool.invoke({ command: 'printf "%s" "${PWD##*/}"' });
+ expect(next).toContain('stdout:\nproject');
+ const scoped = await bashTool.invoke({ command: 'printf "%s" "${PWD##*/}"', cwd: 'child' });
+ expect(scoped).toContain('[starting directory: "workspace/child"]');
+ expect(scoped).toContain('stdout:\nchild');
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
test('forwards a bounded per-call execution timeout', async () => {
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
const bashTool = createAttachedWorkspaceBashTool({
@@ -1011,7 +1163,7 @@ describe('createAttachedWorkspaceBashTool', () => {
await expect(cancelled).rejects.toThrow('Aborted');
await expect(bashTool.invoke({ command: 'pwd' })).resolves.toBe(
- 'stdout:\nreused\n\n[exit code: 0]',
+ '[starting directory: "workspace/"]\nstdout:\nreused\n\n[exit code: 0]',
);
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
@@ -1069,6 +1221,7 @@ describe('createAttachedWorkspaceBashTool', () => {
{},
);
expect(content).toContain('partial work');
+ expect(content).toContain('[starting directory: "workspace/"]');
expect(content).toContain('timeoutMs: 10000');
expect(content).toContain('up to 70000 milliseconds');
expect(content).not.toContain('up to 80000');
@@ -1094,7 +1247,7 @@ describe('createAttachedWorkspaceBashTool', () => {
});
await expect(bashTool.func({ command: 'sleep 60' }, undefined, {})).resolves.toEqual([
- '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.',
+ '[starting directory: "workspace/"]\nstderr:\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.',
{},
]);
});
diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.ts
index 5cb3ee42ab..ab2300a4b4 100644
--- a/packages/api/src/code/command.ts
+++ b/packages/api/src/code/command.ts
@@ -65,17 +65,19 @@ export function stampCommandExecutor(
}
}
-export const ATTACHED_WORKSPACE_BASH_DESCRIPTION = `Runs bash commands inside the selected attached environment and returns stdout/stderr. Its workspace may be an existing project, Git repository, or empty directory.
+export const ATTACHED_WORKSPACE_BASH_DESCRIPTION = `Runs bash commands inside the selected attached environment and returns stdout/stderr. The workspace may be a project, Git repo, or empty directory.
Session behavior:
-- This starts a new command, not an existing background task. Inspect a background_task_id with check_background_task when available; never send it to bash_tool.
-- Only registered-workspace files persist between calls. Install project dependencies there.
-- Every call is a fresh process. Shell and exported variables, cwd, /tmp, $TMPDIR, and background processes do not survive.
-- $HOME, global/system packages, and machine services are operator-managed. Do not change or rely on them as session storage.
-- Network access follows the sandbox policy configured on the worker and may be unavailable. File access follows the same worker policy.
-- Input code is already displayed to the user; do not repeat it unless asked.
+- Start a new command, not an existing task. Inspect background_task_id with check_background_task; never pass it here.
+- Only registered-workspace files persist. Install project dependencies there.
+- Every call is a fresh process. Shell state, exports, cwd, /tmp, $TMPDIR, and background processes do not survive.
+- Results show the starting workspace-relative directory, not the final directory. Scripts are not automatically rewritten.
+- Use cwd for directory-scoped commands; keep cd for shell state or root access.
+- $HOME, global/system packages, and services are operator-managed, not session storage.
+- Network access follows the sandbox policy; file access too. Network may be unavailable.
+- Input code is already displayed; do not repeat unless asked.
- Explicitly print every result the user should see.
-- Never use this tool to execute malicious commands.`;
+- Never execute malicious commands.`;
const bashSchema = BashExecutionToolDefinition.schema as {
properties?: NonNullable<LCTool['parameters']>['properties'];
@@ -400,6 +402,7 @@ function formatCommandResult(
result: WorkspaceExecuteCommandResult,
timeoutMs: number,
maxTimeoutMs: number,
+ cwd?: string,
): string {
let output = '';
if (result.stdout.length > 0) output += `stdout:\n${result.stdout}\n`;
@@ -412,7 +415,7 @@ function formatCommandResult(
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;
+ return `[starting directory: ${JSON.stringify(`workspace/${cwd ?? ''}`)}]\n${output}`;
}
export function createAttachedWorkspaceBashTool({
@@ -549,7 +552,16 @@ export function createAttachedWorkspaceBashTool({
throw new Error('Attached workspace returned an unexpected command result.');
}
logger.debug('[BYOMCommand] transport completed', trace);
- return [formatCommandResult(result, timeoutMs, effectiveMaxTimeoutMs), {}];
+ let content = formatCommandResult(result, timeoutMs, effectiveMaxTimeoutMs, rawInput.cwd);
+ if (action === undefined && /^\s*cd(?:\s|$)/.test(rawInput.command!)) {
+ content +=
+ '\n[directory hint: For future commands scoped to a workspace subdirectory, pass cwd instead of a leading cd.' +
+ (linkedWorktrees
+ ? ' A cd inside the script does not select a linked-worktree lane.'
+ : '') +
+ ' Keep cd for scripts that depend on shell state or need root access. This command was not rewritten; do not rerun it just to change cwd.]';
+ }
+ return [content, {}];
} finally {
signal?.removeEventListener('abort', onAbort);
logger.debug('[BYOMCommand] transport settled', {