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

📝 docs: Describe Attached-Workspace Lanes, Sandbox Scratch, and Skill Files in Tool Descriptions (#16702)

Danny Avila76fcf0a6eb84
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index caad0c81dd..048cd0c4ea 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -2367,6 +2367,7 @@ async function loadToolsForExecution({
workspaceId: codeExecutionContext.codeWorkspace.workspaceId,
workspaceInstanceId: codeExecutionContext.codeWorkspace.workspaceInstanceId,
linkedWorktrees: codeExecutionContext.codeWorkspace.linkedWorktrees,
+ nativeSandbox: codeExecutionContext.codeWorkspace.nativeSandbox,
environment: codeExecutionContext.codeWorkspace.environment,
gitIdentity: agent?.git_identity,
maxTimeoutMs: resolveAttachedWorkspaceCommandTimeoutMax(
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index 238c297b9f..5516ce25f5 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -3103,6 +3103,56 @@ describe('ToolService - Action Capability Gating', () => {
expect(result.loadedTools).toContainEqual({ name: AgentConstants.BASH_TOOL });
});
+ it('passes negotiated lane and native sandbox capabilities to the attached bash tool', async () => {
+ const capabilities = [
+ AgentCapabilities.tools,
+ AgentCapabilities.execute_code,
+ AgentCapabilities.stateful_code_sessions,
+ ];
+ const req = createMockReq(capabilities);
+ req.body = {
+ codeWorkspaces: [{ environmentId: 'personal-machine', workspaceId: 'project-a' }],
+ };
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+ mockResolveCodeExecutionContext.mockReturnValueOnce({
+ baseUrl: 'http://attached-code.test/v1',
+ codeSessionKey: 'execute_code:stateful:attached',
+ executionProfile: 'stateful',
+ statefulSessions: true,
+ environmentType: 'attached',
+ environmentId: 'personal-machine',
+ bridgeWorkerId: 'worker-abc',
+ });
+ mockResolveCodeExecutionWorkspaceContext.mockImplementationOnce(async ({ context }) => ({
+ ...context,
+ codeWorkspace: {
+ environmentId: 'personal-machine',
+ workspaceId: 'project-a',
+ operations: attachedWorkspaceOperations,
+ linkedWorktrees: true,
+ nativeSandbox: true,
+ },
+ }));
+
+ 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: new Map([[AgentConstants.BASH_TOOL, { name: AgentConstants.BASH_TOOL }]]),
+ actionsEnabled: false,
+ });
+
+ expect(mockCreateAttachedWorkspaceBashTool).toHaveBeenLastCalledWith(
+ expect.objectContaining({ linkedWorktrees: true, nativeSandbox: true }),
+ );
+ });
+
it('resolves stateful routing when handle_skill is the only requested tool', async () => {
const capabilities = [
AgentCapabilities.tools,
diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.ts
index cd234175c2..e6ffa19508 100644
--- a/packages/api/src/agents/execution.ts
+++ b/packages/api/src/agents/execution.ts
@@ -62,6 +62,8 @@ export interface CodeExecutionContext {
workspaceInstanceId?: string;
/** The worker schedules each `.worktrees/<name>` of this root as its own lane. */
linkedWorktrees?: boolean;
+ /** The worker advertises the native SRT sandbox: read-only filesystem outside the workspace and `$TMPDIR`. */
+ nativeSandbox?: boolean;
/** Live Code API execution ceiling. Omitted by older deployments. */
maxCommandTimeoutMs?: number;
/** Edit features the worker negotiated with the Code API. Omitted by older workers. */
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 1ab746e634..2088e588b2 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -2289,6 +2289,7 @@ export async function initializeAgent(
workspaceReadFileDefaultLines: attachedWorkspaceReadFileDefaultLines,
workspaceEnvironment: trustedCodeExecutionContext.codeWorkspace?.environment,
workspaceLinkedWorktrees: trustedCodeExecutionContext.codeWorkspace?.linkedWorktrees,
+ workspaceNativeSandbox: trustedCodeExecutionContext.codeWorkspace?.nativeSandbox,
});
toolDefinitions = codeExecResult.toolDefinitions;
recordCapabilityToolNames(AgentCapabilities.execute_code, codeExecResult.toolNames);
@@ -2539,6 +2540,7 @@ export async function initializeAgent(
workspaceReadFileDefaultLines: attachedWorkspaceReadFileDefaultLines,
workspaceEnvironment: trustedCodeExecutionContext.codeWorkspace?.environment,
workspaceLinkedWorktrees: trustedCodeExecutionContext.codeWorkspace?.linkedWorktrees,
+ workspaceNativeSandbox: trustedCodeExecutionContext.codeWorkspace?.nativeSandbox,
skillStates: params.skillStates,
defaultActiveOnShare: params.defaultActiveOnShare,
maxCatalogSkills: getMaxCatalogSkills(runtime),
diff --git a/packages/api/src/agents/skills.ts b/packages/api/src/agents/skills.ts
index 6b3842af42..a31b17c537 100644
--- a/packages/api/src/agents/skills.ts
+++ b/packages/api/src/agents/skills.ts
@@ -445,6 +445,8 @@ export interface InjectSkillCatalogParams {
workspaceEnvironment?: CodeWorkspaceDescriptor['environment'];
/** The worker runs `.worktrees/<name>` in its own lane; advertise `cwd` routing to the model. */
workspaceLinkedWorktrees?: boolean;
+ /** The worker advertises its native SRT sandbox; describe the read-only filesystem to the model. */
+ workspaceNativeSandbox?: boolean;
/** 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. */
@@ -684,6 +686,7 @@ export async function injectSkillCatalog(
workspaceReadFileDefaultLines,
workspaceEnvironment,
workspaceLinkedWorktrees,
+ workspaceNativeSandbox,
userId,
skillStates,
defaultActiveOnShare = false,
@@ -873,6 +876,7 @@ export async function injectSkillCatalog(
workspaceReadFileDefaultLines,
workspaceEnvironment,
workspaceLinkedWorktrees,
+ workspaceNativeSandbox,
});
workingDefs = codeExecResult.toolDefinitions;
diff --git a/packages/api/src/agents/tools.spec.ts b/packages/api/src/agents/tools.spec.ts
index 685e6ad8ac..ea52462ed3 100644
--- a/packages/api/src/agents/tools.spec.ts
+++ b/packages/api/src/agents/tools.spec.ts
@@ -93,6 +93,9 @@ import {
/** Portable ceiling for OpenAI-compatible tool description validators. */
const TOOL_DESCRIPTION_ADVISORY_MAX_LENGTH = 1024;
+const ATTACHED_SKILL_FILE_SENTENCE =
+ 'Skill files are not on the attached machine, so bash_tool cannot run them by path; to run a skill script there, read it and write it into the workspace first.';
+
function filePathDescription(tool?: LCTool): string {
const parameters = tool?.parameters as
| { properties?: { path?: { description?: string } } }
@@ -722,8 +725,93 @@ describe('registerCodeExecutionTools', () => {
};
expect(cwdDescription(true)).toContain('.worktrees/<name>');
+ expect(cwdDescription(true)).toContain('Any other call, with or without cwd, is checkout-wide');
expect(cwdDescription(false)).not.toContain('.worktrees');
+ expect(cwdDescription(false)).not.toContain('checkout-wide');
+ for (const lanes of [true, false]) {
+ expect(cwdDescription(lanes)).toContain('The command starts there; do not also cd into it.');
+ }
+ });
+
+ it('describes the read-only native sandbox filesystem only when the worker advertises it', () => {
+ const bashDescription = (workspaceNativeSandbox?: boolean): string | undefined =>
+ registerCodeExecutionTools({
+ toolRegistry: undefined,
+ toolDefinitions: [],
+ includeBash: true,
+ workspaceTools: true,
+ workspaceOperations: new Set(['execute_command']),
+ workspaceNativeSandbox,
+ }).toolDefinitions.find((def) => def.name === 'bash_tool')?.description;
+
+ const scratch =
+ '/ and /tmp are read-only; write scratch files to $TMPDIR or the workspace. Programs that hardcode /tmp fail.';
+ expect(bashDescription(true)).toContain(scratch);
+ expect(bashDescription(false)).not.toContain(scratch);
+ expect(bashDescription()).not.toContain(scratch);
+ expect(bashDescription(false)).toContain(
+ 'temp files, and background processes are not durable',
+ );
});
+
+ it.each([
+ {
+ operations: ['read_file', 'execute_command'],
+ includeBash: true,
+ lines: undefined,
+ warns: true,
+ },
+ { operations: ['read_file', 'execute_command'], includeBash: true, lines: 50, warns: true },
+ { operations: ['execute_command'], includeBash: true, lines: undefined, warns: true },
+ {
+ operations: ['read_file', 'execute_command'],
+ includeBash: false,
+ lines: undefined,
+ warns: false,
+ },
+ { operations: ['read_file'], includeBash: true, lines: undefined, warns: false },
+ { operations: ['read_file'], includeBash: true, lines: 50, warns: false },
+ { operations: ['list_files', 'write_file'], includeBash: true, lines: undefined, warns: false },
+ ] as const)(
+ 'names bash_tool in the skill-file warning only when it is registered: %j',
+ ({ operations, includeBash, lines, warns }) => {
+ const result = registerCodeExecutionTools({
+ toolRegistry: undefined,
+ toolDefinitions: [],
+ includeBash,
+ includeSkillFileInstructions: true,
+ workspaceTools: true,
+ workspaceOperations: new Set(operations),
+ workspaceReadFileDefaultLines: lines,
+ });
+ const names = result.toolDefinitions.map((def) => def.name);
+ const readFile = result.toolDefinitions.find((def) => def.name === 'read_file');
+
+ expect(names.includes('bash_tool')).toBe(warns);
+ expect(readFile?.description).toContain('skills/{skillName}/...');
+ expect(readFile?.description?.includes(ATTACHED_SKILL_FILE_SENTENCE)).toBe(warns);
+ },
+ );
+
+ it.each([
+ { includeSkillFileInstructions: false, workspaceTools: true },
+ { includeSkillFileInstructions: true, workspaceTools: false },
+ ])(
+ 'omits the skill-file warning outside attached skill runs: %j',
+ ({ includeSkillFileInstructions, workspaceTools }) => {
+ const readFile = registerCodeExecutionTools({
+ toolRegistry: undefined,
+ toolDefinitions: [],
+ includeBash: true,
+ includeSkillFileInstructions,
+ workspaceTools,
+ workspaceOperations: new Set(['read_file', 'execute_command']),
+ }).toolDefinitions.find((def) => def.name === 'read_file');
+
+ expect(readFile?.description).not.toContain('Skill files are not on');
+ },
+ );
+
const makeRegistry = (): LCToolRegistry => new Map() as unknown as LCToolRegistry;
describe('fresh run (no pre-existing defs or registry entries)', () => {
@@ -853,7 +941,7 @@ describe('registerCodeExecutionTools', () => {
});
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).toContain('Network and file access follow the sandbox policy');
expect(bashTool?.description).not.toContain('/mnt/data');
expect(bashTool?.parameters).toMatchObject({
properties: {
@@ -1090,11 +1178,23 @@ describe('registerCodeExecutionTools', () => {
workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS),
});
+ const attachedNativeSandboxWithoutRefs = registerCodeExecutionTools({
+ toolRegistry: makeRegistry(),
+ toolDefinitions: [],
+ includeBash: true,
+ includeSkillFileInstructions: false,
+ enableToolOutputReferences: false,
+ workspaceTools: true,
+ workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS),
+ workspaceNativeSandbox: true,
+ });
+
expect(
maxToolDescriptionLength([
...skillAwareWithRefs.toolDefinitions,
...codeOnlyWithoutRefs.toolDefinitions,
...attachedWithoutRefs.toolDefinitions,
+ ...attachedNativeSandboxWithoutRefs.toolDefinitions,
]),
).toBeLessThanOrEqual(TOOL_DESCRIPTION_ADVISORY_MAX_LENGTH);
});
diff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.ts
index 66f7319fcc..dd1120d687 100644
--- a/packages/api/src/agents/tools.ts
+++ b/packages/api/src/agents/tools.ts
@@ -446,6 +446,8 @@ export interface RegisterCodeExecutionToolsParams {
workspaceEnvironment?: CodeWorkspaceDescriptor['environment'];
/** The worker runs `.worktrees/<name>` in its own lane; advertise `cwd` routing to the model. */
workspaceLinkedWorktrees?: boolean;
+ /** The worker advertises its native SRT sandbox; describe the read-only filesystem to the model. */
+ workspaceNativeSandbox?: boolean;
/**
* When `true`, the registered `bash_tool` description includes the
* LLM-facing `{{tool<idx>turn<turn>}}` reference syntax guide so the
@@ -543,6 +545,10 @@ ${READ_FILE_RANGE_INSTRUCTIONS}`;
const ATTACHED_WORKSPACE_READ_FILE_INSTRUCTIONS = `For an attached environment, read registered files as "workspace/{relativePath}". Use a canonical relative path without empty, ".", or ".." segments; the worker's host path stays private. Only the registered workspace persists for attached commands. Project dependencies stored there persist, while $HOME and global/system packages are operator-managed. Use start_line and max_lines for bounded pagination.`;
+/** Skill files live in LibreChat storage; attached commands only see the registered workspace. */
+const ATTACHED_WORKSPACE_SKILL_FILE_INSTRUCTIONS =
+ 'Skill files are not on the attached machine, so bash_tool cannot run them by path; to run a skill script there, read it and write it into the workspace first.';
+
const CODE_READ_FILE_PARAMETERS: LCTool['parameters'] = Object.freeze({
...SKILL_READ_FILE_PARAMETERS,
type: 'object',
@@ -587,17 +593,26 @@ const CODE_READ_FILE_DEF: LCTool = Object.freeze({
responseFormat: ReadFileToolDefinition.responseFormat,
}) as LCTool;
+/**
+ * `attachedCommands` is true only when the attached `bash_tool` is registered
+ * beside this definition: the skill-file warning names it.
+ */
function createAttachedWorkspaceReadFileDef(
includeSkillFileInstructions: boolean,
defaultReadFileLines: number = CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES,
+ attachedCommands = false,
): LCTool {
const baseDescription = includeSkillFileInstructions
? SKILL_READ_FILE_DESCRIPTION
: CODE_READ_FILE_DESCRIPTION;
+ const attachedInstructions =
+ includeSkillFileInstructions && attachedCommands
+ ? `${ATTACHED_WORKSPACE_READ_FILE_INSTRUCTIONS} ${ATTACHED_WORKSPACE_SKILL_FILE_INSTRUCTIONS}`
+ : ATTACHED_WORKSPACE_READ_FILE_INSTRUCTIONS;
return Object.freeze({
name: ReadFileToolDefinition.name,
toolType: 'builtin',
- description: `${baseDescription}\n\n${ATTACHED_WORKSPACE_READ_FILE_INSTRUCTIONS}`,
+ description: `${baseDescription}\n\n${attachedInstructions}`,
parameters:
defaultReadFileLines === CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES
? ATTACHED_WORKSPACE_READ_FILE_PARAMETERS
@@ -617,6 +632,17 @@ function createAttachedWorkspaceReadFileDef(
const ATTACHED_CODE_READ_FILE_DEF = createAttachedWorkspaceReadFileDef(false);
const ATTACHED_SKILL_READ_FILE_DEF = createAttachedWorkspaceReadFileDef(true);
+const ATTACHED_SKILL_COMMAND_READ_FILE_DEF = createAttachedWorkspaceReadFileDef(
+ true,
+ CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES,
+ true,
+);
+
+/** Skill-only `read_file` beside the attached `bash_tool` when the worker does not offer `read_file`. */
+const ATTACHED_SKILL_ONLY_READ_FILE_DEF: LCTool = Object.freeze({
+ ...READ_FILE_DEF,
+ description: `${SKILL_READ_FILE_DESCRIPTION}\n\n${ATTACHED_WORKSPACE_SKILL_FILE_INSTRUCTIONS}`,
+}) as LCTool;
/**
* The SDK constraint the authoring variant rewrites. Left alone it tells the
@@ -1020,14 +1046,20 @@ function buildReadFileDef(
includeSkillFileInstructions: boolean,
workspaceTools: boolean,
defaultReadFileLines: number = CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES,
+ attachedCommands = false,
): LCTool {
if (workspaceTools) {
if (defaultReadFileLines !== CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES) {
- return createAttachedWorkspaceReadFileDef(includeSkillFileInstructions, defaultReadFileLines);
+ return createAttachedWorkspaceReadFileDef(
+ includeSkillFileInstructions,
+ defaultReadFileLines,
+ attachedCommands,
+ );
}
- return includeSkillFileInstructions
- ? ATTACHED_SKILL_READ_FILE_DEF
- : ATTACHED_CODE_READ_FILE_DEF;
+ if (!includeSkillFileInstructions) {
+ return ATTACHED_CODE_READ_FILE_DEF;
+ }
+ return attachedCommands ? ATTACHED_SKILL_COMMAND_READ_FILE_DEF : ATTACHED_SKILL_READ_FILE_DEF;
}
return includeSkillFileInstructions ? READ_FILE_DEF : CODE_READ_FILE_DEF;
}
@@ -1109,6 +1141,7 @@ function createBashToolDef(
workspaceEnvironment?: CodeWorkspaceDescriptor['environment'],
workspaceLinkedWorktrees = false,
workspaceCommandTimeoutDefaultMs?: number,
+ workspaceNativeSandbox = false,
): LCTool {
/* Passed as a variable (not an inline literal) so the extra
* `statefulSessions` key stays assignable against pinned SDK versions
@@ -1118,7 +1151,11 @@ function createBashToolDef(
name: BashExecutionToolDefinition.name,
toolType: 'builtin',
description: workspaceTools
- ? buildAttachedWorkspaceBashDescription(enableToolOutputReferences, workspaceEnvironment)
+ ? buildAttachedWorkspaceBashDescription(
+ enableToolOutputReferences,
+ workspaceEnvironment,
+ workspaceNativeSandbox,
+ )
: buildBashExecutionToolDescription(descriptionOpts),
parameters: (workspaceTools
? buildAttachedWorkspaceBashSchema(
@@ -1143,6 +1180,7 @@ function buildBashToolDef(opts: {
workspaceEnvironment?: CodeWorkspaceDescriptor['environment'];
/** The worker runs `.worktrees/<name>` in its own lane; advertise `cwd` routing to the model. */
workspaceLinkedWorktrees?: boolean;
+ workspaceNativeSandbox?: boolean;
}): LCTool {
/* Stateful defs are built on demand: the stateless pair covers the
* default path, and per-run construction is negligible next to init. */
@@ -1155,6 +1193,7 @@ function buildBashToolDef(opts: {
opts.workspaceEnvironment,
opts.workspaceLinkedWorktrees === true,
opts.workspaceCommandTimeoutDefaultMs,
+ opts.workspaceNativeSandbox === true,
);
}
return opts.enableToolOutputReferences
@@ -1191,6 +1230,7 @@ export function registerCodeExecutionTools(
workspaceReadFileDefaultLines,
workspaceEnvironment,
workspaceLinkedWorktrees,
+ workspaceNativeSandbox,
enableToolOutputReferences = false,
statefulSessions = false,
} = params;
@@ -1198,14 +1238,21 @@ export function registerCodeExecutionTools(
const supportsWorkspaceOperation = (operation: CodeWorkspaceOperation): boolean =>
!workspaceTools || workspaceOperations?.has(operation) === true;
const candidates: LCTool[] = [];
+ const bashAvailable = includeBash && supportsWorkspaceOperation('execute_command');
+ const attachedCommands = workspaceTools && bashAvailable;
if (!workspaceTools || supportsWorkspaceOperation('read_file')) {
candidates.push(
- buildReadFileDef(includeSkillFileInstructions, workspaceTools, workspaceReadFileDefaultLines),
+ buildReadFileDef(
+ includeSkillFileInstructions,
+ workspaceTools,
+ workspaceReadFileDefaultLines,
+ attachedCommands,
+ ),
);
} else if (includeSkillFileInstructions) {
- candidates.push(buildReadFileDef(true, false));
+ candidates.push(attachedCommands ? ATTACHED_SKILL_ONLY_READ_FILE_DEF : READ_FILE_DEF);
}
- if (includeBash && supportsWorkspaceOperation('execute_command')) {
+ if (bashAvailable) {
candidates.push(
buildBashToolDef({
enableToolOutputReferences,
@@ -1215,6 +1262,7 @@ export function registerCodeExecutionTools(
workspaceCommandTimeoutDefaultMs,
workspaceEnvironment,
workspaceLinkedWorktrees,
+ workspaceNativeSandbox,
}),
);
}
diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.ts
index f3571df107..fa10ef0379 100644
--- a/packages/api/src/code/capabilities.spec.ts
+++ b/packages/api/src/code/capabilities.spec.ts
@@ -3,6 +3,7 @@ import type { AppConfig } from '@librechat/data-schemas';
import type { CodeExecutionContext, CodeEnvironmentConfig } from '~/agents/execution';
import {
CodeWorkspaceSelectionError,
+ isNativeSandboxProfile,
resolveCodeExecutionWorkspaceContext,
supportsProgrammaticCodeExecution,
} from './capabilities';
@@ -430,6 +431,32 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
]);
});
+ it.each([
+ { sandboxProfile: 'anthropic-srt', nativeSandbox: true },
+ { sandboxProfile: 'anthropic-srt:trusted-vm', nativeSandbox: true },
+ { sandboxProfile: 'anthropic-srt-custom', nativeSandbox: undefined },
+ { sandboxProfile: 'native-srt', nativeSandbox: undefined },
+ { sandboxProfile: 'oci-docker', nativeSandbox: undefined },
+ ])(
+ 'marks the native sandbox only for its advertised profile: $sandboxProfile',
+ async ({ sandboxProfile, nativeSandbox }) => {
+ const response = workspaceStatus([{ id: 'docs' }]);
+ const body = await response.json();
+ body.capabilities.sandboxProfile = sandboxProfile;
+ jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify(body)));
+
+ const resolved = await resolveCodeExecutionWorkspaceContext({
+ context,
+ requestedSelections: [{ environmentId: 'personal', workspaceId: 'docs' }],
+ environments,
+ getAppConfig,
+ });
+
+ expect(resolved.codeWorkspace?.nativeSandbox).toBe(nativeSandbox);
+ expect(isNativeSandboxProfile(sandboxProfile)).toBe(nativeSandbox === true);
+ },
+ );
+
it('carries validated project metadata from the selected workspace', async () => {
const environment = {
fingerprint: 'a'.repeat(64),
diff --git a/packages/api/src/code/capabilities.ts b/packages/api/src/code/capabilities.ts
index f1cd9e6916..f6d128bf7a 100644
--- a/packages/api/src/code/capabilities.ts
+++ b/packages/api/src/code/capabilities.ts
@@ -22,6 +22,20 @@ export type CodeCapabilityConfigLoader = ReturnType<typeof createAppConfigServic
const pollWorkerStatus = createCodeBridgeStatusPoller();
+/** The worker's default label for native SRT workspace commands, optionally `:<command-policy-preset>`. */
+const NATIVE_SANDBOX_PROFILE = 'anthropic-srt';
+
+/**
+ * Whether the worker reports the native SRT command sandbox, whose filesystem is
+ * read-only outside the workspace and a private `$TMPDIR`. A custom operator
+ * label is not recognized, so its description omits the claim.
+ */
+export function isNativeSandboxProfile(profile: string | undefined): boolean {
+ return (
+ profile === NATIVE_SANDBOX_PROFILE || profile?.startsWith(`${NATIVE_SANDBOX_PROFILE}:`) === true
+ );
+}
+
function canonicalWorkspaceSelections(
selections: CodeWorkspaceSelection[],
): CodeWorkspaceSelection[] {
@@ -169,6 +183,7 @@ export async function resolveCodeExecutionWorkspaceContext({
!usesIsolation
? { linkedWorktrees: true }
: {}),
+ ...(isNativeSandboxProfile(status.sandboxProfile) ? { nativeSandbox: true } : {}),
...(status.maxCommandTimeoutMs == null
? {}
: { maxCommandTimeoutMs: status.maxCommandTimeoutMs }),
diff --git a/packages/api/src/code/command.spec.ts b/packages/api/src/code/command.spec.ts
index b73c530a3f..39c1caacb3 100644
--- a/packages/api/src/code/command.spec.ts
+++ b/packages/api/src/code/command.spec.ts
@@ -11,8 +11,10 @@ import type { WorkspaceExecuteCommandRequest } from './workspace';
import type { CodeExecutionContext } from '~/agents/execution';
import type { CodeBridgeFetch } from './bridge';
import {
+ ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION,
ATTACHED_WORKSPACE_BASH_DESCRIPTION,
ATTACHED_WORKSPACE_BASH_SCHEMA,
+ buildAttachedWorkspaceBashDescription,
buildAttachedWorkspaceBashSchema,
createAttachedWorkspaceBashTool,
createContextProgrammaticBashTool,
@@ -30,14 +32,66 @@ describe('attached workspace Bash contract', () => {
expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain(
'Only registered-workspace files persist',
);
- expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('Install project dependencies there');
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('install project dependencies there');
expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('$HOME');
- 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',
+ 'temp files, and background processes are not durable',
+ );
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('global/system packages');
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('not the final one');
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).toContain('scripts are not rewritten');
+ });
+
+ test('describes the read-only native sandbox filesystem only when the worker advertises it', () => {
+ const scratch =
+ '/ and /tmp are read-only; write scratch files to $TMPDIR or the workspace. Programs that hardcode /tmp fail.';
+ expect(ATTACHED_WORKSPACE_BASH_DESCRIPTION).not.toContain('read-only');
+ expect(ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION).toContain(scratch);
+ expect(ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION.replace(`- ${scratch}\n`, '')).toBe(
+ ATTACHED_WORKSPACE_BASH_DESCRIPTION,
+ );
+ expect(buildAttachedWorkspaceBashDescription(false)).toBe(ATTACHED_WORKSPACE_BASH_DESCRIPTION);
+ expect(
+ buildAttachedWorkspaceBashDescription(true, undefined, true).startsWith(
+ `${ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION}\n\n`,
+ ),
+ ).toBe(true);
+ const tool = (nativeSandbox?: boolean): string =>
+ createAttachedWorkspaceBashTool({
+ baseUrl: 'https://code.example.com/v1',
+ authHeaders: () => ({}),
+ workspaceId: 'project-a',
+ nativeSandbox,
+ }).description;
+ expect(tool(true)).toBe(ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION);
+ expect(tool(false)).toBe(ATTACHED_WORKSPACE_BASH_DESCRIPTION);
+ expect(tool()).toBe(ATTACHED_WORKSPACE_BASH_DESCRIPTION);
+ });
+
+ test('states that commands start in cwd so the model does not also cd into it', () => {
+ const { properties } = buildAttachedWorkspaceBashSchema();
+ expect(properties?.command?.description).toContain(
+ 'It starts in cwd, or in the workspace root when cwd is omitted.',
+ );
+ expect(properties?.cwd?.description).toContain(
+ 'The command starts there; do not also cd into it.',
+ );
+ expect(properties?.cwd?.description).not.toContain('checkout-wide');
+ expect(properties?.cwd?.description).not.toContain('.worktrees');
+ });
+
+ test('describes checkout-wide root calls only in linked-worktree lane mode', () => {
+ const laneCwd = buildAttachedWorkspaceBashSchema(undefined, undefined, true).properties?.cwd
+ ?.description;
+ expect(laneCwd).toContain('The command starts there; do not also cd into it.');
+ expect(laneCwd).toContain(
+ 'Pass a linked worktree directory here (e.g. ".worktrees/fix-auth") rather than cd into it: different worktrees run in parallel.',
+ );
+ expect(laneCwd).toContain(
+ 'Any other call, with or without cwd, is checkout-wide: it waits for all running worktree calls and blocks new ones until it finishes, as do file tools on paths outside .worktrees/<name>.',
+ );
+ expect(laneCwd).toContain(
+ 'Reserve checkout-wide calls for creating, pruning or removing worktrees, batching any git fetch they need into the same call.',
);
});
@@ -707,7 +761,9 @@ describe('createAttachedWorkspaceBashTool', () => {
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(
+ 'does not select a linked-worktree lane, so this call ran checkout-wide.',
+ );
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);
diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.ts
index ab2300a4b4..cdf53ee132 100644
--- a/packages/api/src/code/command.ts
+++ b/packages/api/src/code/command.ts
@@ -65,20 +65,31 @@ export function stampCommandExecutor(
}
}
-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.
+const ATTACHED_WORKSPACE_BASH_INTRO = `Runs bash in the selected attached environment and returns stdout/stderr. The workspace may be a project, Git repo, or empty directory.
Session behavior:
-- 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.
+- Never pass background_task_id here; inspect it with check_background_task.
+- Only registered-workspace files persist; install project dependencies there. $HOME, global/system packages, and services are operator-managed.
+- Each call is a fresh process; shell state, exports, cwd, temp files, and background processes are not durable.`;
+
+/** Native SRT workers make the host filesystem read-only outside the workspace and a private `$TMPDIR`. */
+const ATTACHED_WORKSPACE_NATIVE_SANDBOX_SCRATCH =
+ '- / and /tmp are read-only; write scratch files to $TMPDIR or the workspace. Programs that hardcode /tmp fail.';
+
+const ATTACHED_WORKSPACE_BASH_RULES = `- Results show the starting directory, not the final one; scripts are not 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.
+- Network and file access follow the sandbox policy; network may be unavailable.
- Input code is already displayed; do not repeat unless asked.
- Explicitly print every result the user should see.
- Never execute malicious commands.`;
+export const ATTACHED_WORKSPACE_BASH_DESCRIPTION: string = `${ATTACHED_WORKSPACE_BASH_INTRO}
+${ATTACHED_WORKSPACE_BASH_RULES}`;
+
+export const ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION: string = `${ATTACHED_WORKSPACE_BASH_INTRO}
+${ATTACHED_WORKSPACE_NATIVE_SANDBOX_SCRATCH}
+${ATTACHED_WORKSPACE_BASH_RULES}`;
+
const bashSchema = BashExecutionToolDefinition.schema as {
properties?: NonNullable<LCTool['parameters']>['properties'];
};
@@ -86,7 +97,7 @@ const attachedCommandSchema: NonNullable<LCTool['parameters']> = {
...bashSchema.properties?.command,
type: 'string',
description:
- 'The bash command or script to execute from the attached workspace root. Only files written inside the workspace persist between calls. Each call starts a fresh process; $HOME, temporary files, shell state, global installs, and background processes are not durable.',
+ 'The bash command or script to execute. It starts in cwd, or in the workspace root when cwd is omitted. Only files written inside the workspace persist between calls. Each call starts a fresh process; $HOME, temporary files, shell state, global installs, and background processes are not durable.',
};
/** `maxLength` is valid JSON Schema, but the SDK's schema type omits it. */
@@ -100,7 +111,7 @@ const attachedWorkingDirectorySchema: BoundedWorkingDirectorySchema = {
type: 'string',
maxLength: 4096,
description:
- 'Optional working directory relative to the selected workspace root, such as "packages/api". Absolute paths and parent traversal are rejected.',
+ 'Optional working directory relative to the selected workspace root, such as "packages/api". The command starts there; do not also cd into it. Absolute paths and parent traversal are rejected.',
};
/** Numeric bounds are valid JSON Schema, but the SDK's schema type omits them. */
@@ -235,9 +246,14 @@ export function resolveAttachedWorkspaceRequestTimeoutMs(
return configured;
}
+/**
+ * Code API schedules each `.worktrees/<name>` as its own lane beneath the
+ * checkout. Every request that is not routed into a lane is checkout-wide: it
+ * waits for the running lanes and, while queued, holds back newer ones.
+ */
const linkedWorktreeWorkingDirectorySchema: BoundedWorkingDirectorySchema = {
...attachedWorkingDirectorySchema,
- description: `${attachedWorkingDirectorySchema.description} To work in a linked worktree, pass its directory here (for example ".worktrees/fix-auth") instead of running cd inside the command: commands in different .worktrees/<name> directories then run in parallel, while a cd from the workspace root waits for all of them.`,
+ description: `${attachedWorkingDirectorySchema.description} Pass a linked worktree directory here (e.g. ".worktrees/fix-auth") rather than cd into it: different worktrees run in parallel. Any other call, with or without cwd, is checkout-wide: it waits for all running worktree calls and blocks new ones until it finishes, as do file tools on paths outside .worktrees/<name>. Reserve checkout-wide calls for creating, pruning or removing worktrees, batching any git fetch they need into the same call.`,
};
export function buildAttachedWorkspaceBashSchema(
@@ -284,10 +300,14 @@ export const ATTACHED_WORKSPACE_BASH_SCHEMA: NonNullable<LCTool['parameters']> =
export function buildAttachedWorkspaceBashDescription(
enableToolOutputReferences: boolean,
environment?: CodeWorkspaceDescriptor['environment'],
+ nativeSandbox = false,
): string {
- const description = enableToolOutputReferences
- ? `${ATTACHED_WORKSPACE_BASH_DESCRIPTION}\n\n${BashToolOutputReferencesGuide}`
+ const base = nativeSandbox
+ ? ATTACHED_WORKSPACE_NATIVE_SANDBOX_BASH_DESCRIPTION
: ATTACHED_WORKSPACE_BASH_DESCRIPTION;
+ const description = enableToolOutputReferences
+ ? `${base}\n\n${BashToolOutputReferencesGuide}`
+ : base;
return (
description +
(environment
@@ -432,6 +452,7 @@ export function createAttachedWorkspaceBashTool({
maxRequestTimeoutMs,
minCommandAdmissionMs,
linkedWorktrees = false,
+ nativeSandbox = false,
fetchImpl,
}: {
baseUrl: string;
@@ -440,6 +461,8 @@ export function createAttachedWorkspaceBashTool({
workspaceInstanceId?: string;
/** The worker runs each `.worktrees/<name>` in its own lane; a matching `cwd` is routed there. */
linkedWorktrees?: boolean;
+ /** The worker advertises its native SRT sandbox profile; describe its read-only filesystem. */
+ nativeSandbox?: boolean;
environment?: CodeWorkspaceDescriptor['environment'];
gitIdentity?: AgentGitIdentity | null;
/** Effective admin/upstream ceiling already intersected with the protocol hard cap. */
@@ -557,7 +580,7 @@ export function createAttachedWorkspaceBashTool({
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.'
+ ? ' A cd inside the script does not select a linked-worktree lane, so this call ran checkout-wide.'
: '') +
' 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.]';
}
@@ -572,7 +595,7 @@ export function createAttachedWorkspaceBashTool({
},
{
name: BashExecutionToolDefinition.name,
- description: buildAttachedWorkspaceBashDescription(false, environment),
+ description: buildAttachedWorkspaceBashDescription(false, environment, nativeSandbox),
schema,
responseFormat: 'content_and_artifact',
},