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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
⛓️ fix: Bind Programmatic Bash to Selected Workspaces (#15992)
Danny Avila4d08bcf20301
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 3afc2ba13e..e2d7c4e172 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -5,7 +5,6 @@ const {createToolSearch,createBashExecutionTool,Constants: AgentConstants,- createBashProgrammaticToolCallingTool,} = require('@librechat/agents');const {sendEvent,@@ -50,7 +49,7 @@ const {codeExecutionAuthHeaders,createAttachedWorkspaceBashTool,resolveAttachedWorkspaceCommandTimeoutMax,- createGitIdentityProgrammaticBashTool,+ createContextProgrammaticBashTool,resolveCodeExecutionContext,resolveCodeExecutionWorkspaceContext,resolveRunFileCodeExecutionContext,@@ -1798,6 +1797,7 @@ async function loadAgentTools({agentId: agent.id,provider: agent.provider,agentToolOptions: agent.tool_options,+ gitIdentity: agent.git_identity,deferredToolsEnabled,programmaticToolsEnabled,codeExecutionEnabled,@@ -2233,20 +2233,15 @@ async function loadToolsForExecution({* library so PTC calls share the same managed auth context.*/for (const name of ptcToolNames) {- const ptcOptions = {- authHeaders: () =>+ const ptcTool = createContextProgrammaticBashTool(+ () =>codeExecutionAuthHeaders((bridgeWorkerId) => getCodeApiAuthHeaders(req, bridgeWorkerId),codeExecutionContext,),- baseUrl: codeExecutionContext.baseUrl,- executionProfile: codeExecutionContext.executionProfile,- runtimeSessionHint: codeExecutionContext.runtimeSessionHint,- };- const ptcTool =- codeExecutionContext.environmentType === 'attached'- ? createGitIdentityProgrammaticBashTool(ptcOptions, agent?.git_identity)- : createBashProgrammaticToolCallingTool(ptcOptions);+ codeExecutionContext,+ agent?.git_identity,+ );ptcTool.name = name;allLoadedTools.push(ptcTool);}diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex 280e7d7572..05641b3a67 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -3307,8 +3307,8 @@ describe('ToolService - Action Capability Gating', () => {(tool) => tool.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING,),).toBe(supported);- expect(mockGetAppConfig).not.toHaveBeenCalled();- expect(fetchSpy).not.toHaveBeenCalled();+ expect(mockGetAppConfig).toHaveBeenCalledTimes(1);+ expect(fetchSpy).toHaveBeenCalledTimes(1);} finally {fetchSpy.mockRestore();delete process.env.TEST_PTC_DEPLOYMENT_TOKEN;diff --git a/client/src/data-provider/__tests__/pinnedConversations.test.tsx b/client/src/data-provider/__tests__/pinnedConversations.test.tsxindex 4e9292f7fd..95ca4a5bb4 100644--- a/client/src/data-provider/__tests__/pinnedConversations.test.tsx+++ b/client/src/data-provider/__tests__/pinnedConversations.test.tsx@@ -605,6 +605,37 @@ describe('bookmark mutations invalidate the pinned cache', () => {});describe('unpinning a pin that is not on a loaded chats page', () => {+ it('does not let an older list refresh restore a successfully removed pin', async () => {+ const queryClient = createQueryClient();+ const queryKey = [QueryKeys.allConversations];+ const stalePage = { pages: [listResponse([pinnedConvo])], pageParams: [undefined] };+ queryClient.setQueryData(queryKey, stalePage);+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));+ let finishRefresh!: (data: typeof stalePage) => void;+ const refresh = queryClient+ .fetchQuery(+ queryKey,+ () =>+ new Promise<typeof stalePage>((resolve) => {+ finishRefresh = resolve;+ }),+ )+ .catch(() => undefined);+ pinConversation.mockResolvedValue({ ...pinnedConvo, pinned: false });+ const { result } = renderHook(() => usePinConversationMutation(), {+ wrapper: createWrapper(queryClient),+ });+ await act(async () => {+ await result.current.mutateAsync({ conversationId: pinnedConversationId, pinned: false });+ finishRefresh(stalePage);+ await refresh;+ });+ expect(+ queryClient.getQueryData<typeof stalePage>(queryKey)?.pages[0].conversations[0].pinned,+ ).toBe(false);+ queryClient.clear();+ });+it('inserts the unpinned conversation at the top of the chats list', async () => {const unpinned = { ...pinnedConvo, pinned: false } as TConversation;pinConversation.mockResolvedValue(unpinned);diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.tsindex 7be5f45b7f..5c914b5e7a 100644--- a/client/src/data-provider/mutations.ts+++ b/client/src/data-provider/mutations.ts@@ -227,7 +227,14 @@ export const usePinConversationMutation = ([MutationKeys.convoPin],(payload: t.TPinConversationRequest) => dataService.pinConversation(payload),{- onSuccess: (data, vars, context) => {+ onSuccess: async (data, vars, context) => {+ /** A project drop can start a list refresh before its following unpin.+ * Cancel that older snapshot before publishing the authoritative pin result. */+ await Promise.all([+ queryClient.cancelQueries([QueryKeys.allConversations]),+ queryClient.cancelQueries([QueryKeys.archivedConversations]),+ queryClient.cancelQueries([QueryKeys.pinnedConversations]),+ ]);/** `isShared` is derived per list request and is absent from this response, so* read it off the cached pin before the update drops that row: the reinsert* below has no existing chats row to carry the badge over from. */diff --git a/packages/api/src/agents/hitl/byom.spec.ts b/packages/api/src/agents/hitl/byom.spec.tsindex 123d85ca8a..45bf807a40 100644--- a/packages/api/src/agents/hitl/byom.spec.ts+++ b/packages/api/src/agents/hitl/byom.spec.ts@@ -164,16 +164,19 @@ describe('markNativeCodeToolApprovalRequests', () => {});describe('createAttachedCodeEnvironmentPolicyHook', () => {- test('asks before a shell action in an attached environment', async () => {- const hook = createAttachedCodeEnvironmentPolicyHook(new Set(['attached-agent']));+ test.each(['bash_tool', 'run_tools_with_bash'])(+ 'asks before a shell action in an attached environment: %s',+ async (toolName) => {+ const hook = createAttachedCodeEnvironmentPolicyHook(new Set(['attached-agent']));- await expect(- hook({ toolName: 'bash_tool', executingAgentId: 'attached-agent' } as never, signal),- ).resolves.toEqual({- decision: 'ask',- reason: 'bash_tool can modify your attached code environment',- });- });+ await expect(+ hook({ toolName, executingAgentId: 'attached-agent' } as never, signal),+ ).resolves.toEqual({+ decision: 'ask',+ reason: `${toolName} can modify your attached code environment`,+ });+ },+ );test('allows the baseline policy to auto-approve read-only coding actions', async () => {const hook = createAttachedCodeEnvironmentPolicyHook(new Set(['attached-agent']));diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.tsindex 36e1494c92..db1af81812 100644--- a/packages/api/src/code/bridge.spec.ts+++ b/packages/api/src/code/bridge.spec.ts@@ -5,6 +5,42 @@ import {} from './bridge';describe('getCodeBridgeWorkerStatus', () => {+ test.each([+ [['bash'], ['bash']],+ [['bash', 'python'], ['bash']],+ [['python'], undefined],+ [['bash', 123], undefined],+ ])(+ 'preserves recognized programmatic capability from %j',+ async (programmaticLanguages, expected) => {+ const status = await getCodeBridgeWorkerStatus({+ baseURL: 'https://code.example.com/v1',+ token: 'token',+ workerId: 'personal-vm',+ fetchImpl: jest.fn().mockResolvedValue(+ Response.json({+ protocolVersion: 1,+ workerId: 'personal-vm',+ online: true,+ ready: true,+ leaseExpiresInMs: 45_000,+ capabilities: {+ statefulWorkspace: false,+ runtimes: [],+ sandboxProfile: 'native-srt',+ workspaceTools: {+ protocolVersion: 1,+ operations: ['execute_command'],+ workspaces: [{ id: 'project-a' }],+ programmaticLanguages,+ },+ },+ }),+ ),+ });+ expect(status.programmaticLanguages).toEqual(expected);+ },+ );test('accepts the maximum declared environment metadata population', async () => {const workspaces = Array.from({ length: 32 }, (_, index) => ({id: `root-${index}`,diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.tsindex 6b5dd940d2..2dac938a88 100644--- a/packages/api/src/code/bridge.ts+++ b/packages/api/src/code/bridge.ts@@ -36,6 +36,7 @@ export type CodeBridgeWorkerStatus = {runtimes?: string[];operations?: CodeWorkspaceOperation[];workspaces?: CodeWorkspaceDescriptor[];+ programmaticLanguages?: ['bash'];};export type CodeBridgeFetch = (@@ -166,6 +167,7 @@ function validWorkspaceCapabilities(value: unknown): value is {protocolVersion: 1;operations: CodeWorkspaceOperation[];workspaces: CodeWorkspaceDescriptor[];+ programmaticLanguages?: unknown;} {if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;const capabilities = value as Record<string, unknown>;@@ -322,7 +324,10 @@ export async function getCodeBridgeWorkerStatus({if (status.online) {workerStatus = status.ready ? 'ready' : 'starting';}- let workspaceStatus: Pick<CodeBridgeWorkerStatus, 'operations' | 'workspaces'> = {};+ let workspaceStatus: Pick<+ CodeBridgeWorkerStatus,+ 'operations' | 'workspaces' | 'programmaticLanguages'+ > = {};if (validWorkspaceCapabilities(capabilities?.workspaceTools)) {workspaceStatus = {operations: [...capabilities.workspaceTools.operations],@@ -331,6 +336,15 @@ export async function getCodeBridgeWorkerStatus({...(workspace.operations ? { operations: [...workspace.operations] } : {}),})),};+ if (+ Array.isArray(capabilities.workspaceTools.programmaticLanguages) &&+ capabilities.workspaceTools.programmaticLanguages.every(+ (language) => typeof language === 'string',+ ) &&+ capabilities.workspaceTools.programmaticLanguages.includes('bash')+ ) {+ workspaceStatus.programmaticLanguages = ['bash'];+ }} else if (validLegacyWorkspaceCapabilities(capabilities?.workspaceTools)) {workspaceStatus = { operations: [...capabilities.workspaceTools.operations] };}diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.tsindex f9c3056d1a..a473389ca2 100644--- a/packages/api/src/code/capabilities.spec.ts+++ b/packages/api/src/code/capabilities.spec.ts@@ -172,6 +172,74 @@ describe('supportsProgrammaticCodeExecution', () => {expect(fetchSpy).not.toHaveBeenCalled();});+ it.each([+ {+ languages: ['bash'],+ operation: 'execute_command',+ workspaceId: 'project-a',+ supported: true,+ },+ {+ languages: undefined,+ operation: 'execute_command',+ workspaceId: 'project-a',+ supported: false,+ },+ {+ languages: ['python'],+ operation: 'execute_command',+ workspaceId: 'project-a',+ supported: false,+ },+ { languages: ['bash'], operation: 'read_file', workspaceId: 'project-a', supported: false },+ { languages: ['bash'], operation: 'execute_command', workspaceId: 'removed', supported: false },+ ])(+ 'gates selected project PTC using the live capability: %j',+ async ({ languages, operation, workspaceId, supported }) => {+ process.env.TEST_CODE_CAPABILITY_TOKEN = JSON.stringify({+ languages,+ operation,+ workspaceId,+ });+ jest.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(+ JSON.stringify({+ protocolVersion: 1,+ workerId: 'worker',+ online: true,+ ready: true,+ leaseExpiresInMs: 45000,+ capabilities: {+ statefulWorkspace: false,+ sandboxProfile: 'anthropic-srt',+ runtimes: [],+ workspaceTools: {+ protocolVersion: 1,+ operations: ['execute_command', 'read_file'],+ programmaticLanguages: languages,+ workspaces: [{ id: 'project-a', operations: [operation] }],+ },+ },+ }),+ ),+ );+ expect(+ await supportsProgrammaticCodeExecution(+ {+ ...context,+ codeWorkspace: {+ environmentId: 'personal',+ workspaceId,+ operations: ['execute_command', 'read_file'],+ },+ },+ environments,+ getAppConfig,+ ),+ ).toBe(supported);+ },+ );+it('does not send credentials to a different execution route', async () => {process.env.TEST_CODE_CAPABILITY_TOKEN = 'route-token';const fetchSpy = jestdiff --git a/packages/api/src/code/capabilities.ts b/packages/api/src/code/capabilities.tsindex 74a7e40469..64aba8ccbf 100644--- a/packages/api/src/code/capabilities.ts+++ b/packages/api/src/code/capabilities.ts@@ -183,19 +183,27 @@ export async function resolveCodeExecutionWorkspaceContext({};}-/** Attached workers must confirm both a stateful workspace and the Bash runtime. */+/** Require explicit capability support for the selected execution route. */export async function supportsProgrammaticCodeExecution(context?: CodeExecutionContext,environments?: readonly CodeEnvironmentConfig[],getAppConfig?: CodeCapabilityConfigLoader,): Promise<boolean> {if (context?.environmentType !== 'attached') return true;- /** Programmatic Bash uses Code API's generic exec endpoint, which has no- * workspace identifier. A fully resolved attached context therefore cannot- * use it until that protocol can preserve the selected-root boundary. */- if (context.codeWorkspace != null) return false;try {const status = await readAuthorizedAttachedWorkerStatus(context, environments, getAppConfig);+ if (context.codeWorkspace != null) {+ const selected = context.codeWorkspace;+ const workspace = status.workspaces?.find(({ id }) => id === selected.workspaceId);+ return (+ status.status === 'ready' &&+ selected.environmentId === context.environmentId &&+ selected.operations.includes('execute_command') &&+ workspace != null &&+ (workspace.operations ?? status.operations)?.includes('execute_command') === true &&+ status.programmaticLanguages?.includes('bash') === true+ );+ }return (status.status === 'ready' &&status.statefulWorkspace === true &&diff --git a/packages/api/src/code/command.spec.ts b/packages/api/src/code/command.spec.tsindex ff542a05c8..f936ddbf59 100644--- a/packages/api/src/code/command.spec.ts+++ b/packages/api/src/code/command.spec.ts@@ -46,6 +46,47 @@ describe('programmatic Bash Git identity', () => {await once(server, 'close');}});++ test('pins a selected project on the real SDK no-tools route', async () => {+ const received: { url?: string; workspace?: string | string[]; code: string }[] = [];+ const server = createServer(async (req, res) => {+ let body = '';+ for await (const chunk of req) body += chunk;+ received.push({+ url: req.url,+ workspace: req.headers['x-librechat-code-workspace-id'],+ code: JSON.parse(body).code,+ });+ 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 = createGitIdentityProgrammaticBashTool(+ {+ baseUrl: `http://127.0.0.1:${port}/v1`,+ workspaceId: 'project-a',+ authHeaders: () => ({}),+ },+ { name: 'Lia', email: '[email protected]' },+ );+ const invocationConfig = { tags: [], toolCall: { toolDefs: [] } };+ await bashTool.func(+ { code: 'printf done', tool_manifest: [], workspaceId: 'forged-project' },+ undefined,+ invocationConfig,+ );+ expect(received).toHaveLength(1);+ expect(received[0]).toMatchObject({ url: '/v1/exec/programmatic', workspace: 'project-a' });+ expect(received[0].code).toContain("GIT_AUTHOR_NAME='Lia'");+ expect(bashTool.description).toContain('selected persistent workspace');+ } finally {+ server.close();+ await once(server, 'close');+ }+ });});function commandResponse(overrides: Record<string, unknown> = {}): Response {diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.tsindex cd9f6875bf..c436fb6809 100644--- a/packages/api/src/code/command.ts+++ b/packages/api/src/code/command.ts@@ -13,6 +13,7 @@ import type {import type { DynamicStructuredTool } from '@librechat/agents/langchain/tools';import type { LCTool } from '@librechat/agents';import type { WorkspaceExecuteCommandResult } from './workspace';+import type { CodeExecutionContext } from '~/agents/execution';import type { CodeBridgeFetch } from './bridge';import {executeWorkspaceTool,@@ -171,6 +172,34 @@ function commandWithGitIdentity(return `export GIT_AUTHOR_NAME=${quoteShellArgument(name)} GIT_AUTHOR_EMAIL=${quoteShellArgument(email)} GIT_COMMITTER_NAME=${quoteShellArgument(name)} GIT_COMMITTER_EMAIL=${quoteShellArgument(email)}; ${command}`;}+/** Apply authorship before the SDK prepares the script and its replay requests. */+export function createContextProgrammaticBashTool(+ authHeaders: NonNullable<+ Parameters<typeof createBashProgrammaticToolCallingTool>[0]+ >['authHeaders'],+ context?: CodeExecutionContext,+ identity?: AgentGitIdentity | null,+): DynamicStructuredTool {+ const attached = context?.environmentType === 'attached';+ return createGitIdentityProgrammaticBashTool(+ {+ authHeaders,+ baseUrl: context?.baseUrl,+ executionProfile: context?.executionProfile,+ runtimeSessionHint: context?.runtimeSessionHint,+ ...(attached+ ? {+ workspaceId: context.codeWorkspace?.workspaceId,+ runTimeoutMs: resolveAttachedWorkspaceCommandTimeoutMax(+ context.codeEnvironmentConfigSchema,+ ),+ }+ : {}),+ },+ attached ? identity : undefined,+ );+}+/** Apply authorship before the SDK prepares the script and its replay requests. */export function createGitIdentityProgrammaticBashTool(options: Parameters<typeof createBashProgrammaticToolCallingTool>[0],diff --git a/packages/api/src/tools/classification.spec.ts b/packages/api/src/tools/classification.spec.tsindex c7740db824..517e7d360e 100644--- a/packages/api/src/tools/classification.spec.ts+++ b/packages/api/src/tools/classification.spec.ts@@ -543,14 +543,39 @@ describe('classification.ts', () => {it.each([false, true].flatMap((definitionsOnly) => [- { definitionsOnly, statefulWorkspace: false, runtimes: ['bash'], supported: false },- { definitionsOnly, statefulWorkspace: true, runtimes: ['py'], supported: false },- { definitionsOnly, statefulWorkspace: true, runtimes: ['bash'], supported: false },+ {+ definitionsOnly,+ statefulWorkspace: false,+ runtimes: ['bash'],+ supported: false,+ selected: false,+ },+ {+ definitionsOnly,+ statefulWorkspace: true,+ runtimes: ['py'],+ supported: false,+ selected: false,+ },+ {+ definitionsOnly,+ statefulWorkspace: true,+ runtimes: ['bash'],+ supported: false,+ selected: false,+ },+ {+ definitionsOnly,+ statefulWorkspace: false,+ runtimes: [],+ supported: true,+ selected: true,+ },]),)('gates attached PTC: definitionsOnly=$definitionsOnly stateful=$statefulWorkspace runtimes=$runtimes',- async ({ definitionsOnly, statefulWorkspace, runtimes, supported }) => {- const workerId = `worker-${definitionsOnly}-${statefulWorkspace}-${runtimes[0]}`;+ async ({ definitionsOnly, statefulWorkspace, runtimes, supported, selected }) => {+ const workerId = `worker-${definitionsOnly}-${statefulWorkspace}-${runtimes[0]}-${selected}`;process.env.TEST_CODE_CAPABILITY_TOKEN = 'capability-test-token';const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(@@ -564,6 +589,16 @@ describe('classification.ts', () => {statefulWorkspace,sandboxProfile: 'native-srt',runtimes,+ ...(selected+ ? {+ workspaceTools: {+ protocolVersion: 1,+ operations: ['execute_command'],+ programmaticLanguages: ['bash'],+ workspaces: [{ id: 'project-a', operations: ['execute_command'] }],+ },+ }+ : {}),},}),),@@ -602,6 +637,15 @@ describe('classification.ts', () => {environmentType: 'attached',environmentId: 'attached',bridgeWorkerId: workerId,+ ...(selected+ ? {+ codeWorkspace: {+ environmentId: 'attached',+ workspaceId: 'project-a',+ operations: ['execute_command' as const],+ },+ }+ : {}),},codeEnvironments,getAppConfig: jest.fn().mockResolvedValue({@@ -620,7 +664,13 @@ describe('classification.ts', () => {'direct','code_execution',]);- expect(fetchSpy).not.toHaveBeenCalled();+ if (selected) {+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ expect(+ result.toolDefinitions.find((tool) => tool.name === 'run_tools_with_bash')+ ?.description,+ ).toContain('selected persistent workspace');+ } else expect(fetchSpy).not.toHaveBeenCalled();} finally {fetchSpy.mockRestore();delete process.env.TEST_CODE_CAPABILITY_TOKEN;diff --git a/packages/api/src/tools/classification.ts b/packages/api/src/tools/classification.tsindex 1123e1e5b3..2c84a193e5 100644--- a/packages/api/src/tools/classification.ts+++ b/packages/api/src/tools/classification.ts@@ -12,7 +12,6 @@ import {createToolSearch,ToolSearchToolDefinition,BashProgrammaticToolCallingDefinition,- createBashProgrammaticToolCallingTool,} from '@librechat/agents';import type {LCToolRegistry,@@ -21,10 +20,11 @@ import type {GenericTool,LCTool,} from '@librechat/agents';-import type { AgentToolOptions } from 'librechat-data-provider';+import type { AgentGitIdentity, AgentToolOptions } from 'librechat-data-provider';import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';import type { CodeCapabilityConfigLoader } from '~/code/capabilities';import { supportsProgrammaticCodeExecution } from '~/code/capabilities';+import { createContextProgrammaticBashTool } from '~/code/command';import { sanitizeGeminiSchema } from '~/mcp/zod';export type { LCTool, LCToolRegistry, AllowedCaller, JsonSchemaType };@@ -268,13 +268,14 @@ export interface BuildToolClassificationParams {agentId?: string;/** Per-tool configuration from the agent */agentToolOptions?: AgentToolOptions;+ gitIdentity?: AgentGitIdentity | null;/** Whether the deferred_tools capability is enabled (from agent config) */deferredToolsEnabled?: boolean;/** Whether the programmatic_tools capability is enabled (from agent config) */programmaticToolsEnabled?: boolean;/** Whether code execution is enabled and requested by this agent */codeExecutionEnabled?: boolean;- /** When true, skip creating tool instances (for event-driven mode) */+ /** When true, return definitions without executable tools (event-driven mode). */definitionsOnly?: boolean;/** Agent provider — Gemini/Vertex rejects union types, so injected tool schemas get sanitized */provider?: Providers | string;@@ -389,7 +390,8 @@ export async function buildToolClassification(programmaticToolsEnabled &&codeExecutionEnabled &&agentHasProgrammaticTools(toolRegistry) &&- codeExecutionContext?.environmentType !== 'attached' &&+ (codeExecutionContext?.environmentType !== 'attached' ||+ codeExecutionContext.codeWorkspace != null) &&(await supportsProgrammaticCodeExecution(codeExecutionContext, codeEnvironments, getAppConfig));const hasDeferredTools = deferredToolsEnabled && agentHasDeferredTools(toolRegistry);@@ -459,43 +461,19 @@ export async function buildToolClassification(return { toolRegistry, toolDefinitions, additionalTools, hasDeferredTools, mcpToolAliases };}- /** In definitions-only mode, add PTC definition without creating the tool instance */- if (definitionsOnly) {- toolDefinitions.push({- name: BashProgrammaticToolCallingDefinition.name,- description: BashProgrammaticToolCallingDefinition.description,- parameters: BashProgrammaticToolCallingDefinition.schema as unknown as LCTool['parameters'],- });- toolRegistry.set(BashProgrammaticToolCallingDefinition.name, {- name: BashProgrammaticToolCallingDefinition.name,- allowed_callers: ['direct'],- });- logger.debug(- `[buildToolClassification] PTC definition added for agent ${agentId} (definitions only)`,- );- return { toolRegistry, toolDefinitions, additionalTools, hasDeferredTools, mcpToolAliases };- }-try {- const profileParams = codeExecutionContext- ? {- baseUrl: codeExecutionContext.baseUrl,- executionProfile: codeExecutionContext.executionProfile,- runtimeSessionHint: codeExecutionContext.runtimeSessionHint,- }- : {};- const ptcTool = createBashProgrammaticToolCallingTool({+ const ptcTool = createContextProgrammaticBashTool(authHeaders,- ...profileParams,- } as Parameters<typeof createBashProgrammaticToolCallingTool>[0] &- typeof profileParams & { authHeaders?: BuildToolClassificationParams['authHeaders'] });- additionalTools.push(ptcTool);+ codeExecutionContext,+ params.gitIdentity,+ );+ if (!definitionsOnly) additionalTools.push(ptcTool);/** Add PTC definition for event-driven mode */toolDefinitions.push({name: BashProgrammaticToolCallingDefinition.name,- description: BashProgrammaticToolCallingDefinition.description,- parameters: BashProgrammaticToolCallingDefinition.schema as unknown as LCTool['parameters'],+ description: ptcTool.description,+ parameters: ptcTool.schema as LCTool['parameters'],});toolRegistry.set(BashProgrammaticToolCallingDefinition.name, {name: BashProgrammaticToolCallingDefinition.name,