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

🛎️ fix: Route Background Tool Handoffs (#15990)

Danny Avila182cce56b7ed
diff --git a/packages/api/src/agents/background.spec.ts b/packages/api/src/agents/background.spec.ts
index fa1303f465..c34d8d6826 100644
--- a/packages/api/src/agents/background.spec.ts
+++ b/packages/api/src/agents/background.spec.ts
@@ -26,6 +26,7 @@ import {
CHECK_BACKGROUND_TASK_NAME,
RUN_IN_BACKGROUND_ARG,
} from './background';
+import { parseBackgroundHandle } from '../../../../client/src/components/Chat/Messages/Content/Parts/handle';
import { SUBAGENT_COMPLETION_DELIVERY, SUBAGENT_WAKEUP_GUIDANCE } from './subagentDelivery';
import { SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
import { TOOL_SELECTION_WILDCARD } from './selection';
@@ -128,6 +129,23 @@ describe('isBackgroundRequested / stripRunInBackgroundArg', () => {
});
describe('injectRunInBackgroundParam', () => {
+ it('preserves required command fields across injection and inherited-definition cleanup', () => {
+ const definition = {
+ name: 'bash_tool',
+ description: 'Starts a command',
+ parameters: {
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ },
+ } as LCTool;
+ const injected = injectRunInBackgroundParam(definition);
+ expect(injected.parameters?.required).toEqual(['command']);
+ expect(injected.name).toBe('bash_tool');
+ const [restored] = stripBackgroundFromToolDefinitions([injected], ['bash_tool']);
+ expect(restored.parameters?.required).toEqual(['command']);
+ expect(restored.parameters?.properties).toEqual(definition.parameters?.properties);
+ });
it('adds a run_in_background boolean without mutating a frozen def', () => {
const def = Object.freeze(mcpDef('search_mcp_docs'));
const injected = injectRunInBackgroundParam(def);
@@ -3195,6 +3213,16 @@ describe('stripBackgroundFromToolRegistry', () => {
});
describe('buildBackgroundHandleContent', () => {
+ it.each([{}, { completionWakeup: true }, { liveArtifactPollRequired: true }])(
+ 'keeps the server handle compatible with the client parser: %j',
+ (options) => {
+ const content = buildBackgroundHandleContent(
+ { id: '2a6b05c3-327d-43f4-8196-73a6c8d88706', toolName: 'bash_tool', status: 'running' },
+ options,
+ );
+ expect(parseBackgroundHandle(content)).toEqual(JSON.parse(content));
+ },
+ );
it('produces a running handle carrying the id and poll instruction', () => {
const registry = new BackgroundTaskRegistryClass();
const created = registry.create({
@@ -3210,6 +3238,11 @@ describe('buildBackgroundHandleContent', () => {
expect(parsed.background_task_id).toBe(created.task.id);
expect(parsed.status).toBe('running');
expect(parsed.message).toContain(CHECK_BACKGROUND_TASK_NAME);
+ expect(Object.keys(parsed).sort()).toEqual(['background_task_id', 'message', 'status', 'tool']);
+ expect(JSON.parse(parsed.message.split('Status request: ')[1])).toEqual({
+ name: CHECK_BACKGROUND_TASK_NAME,
+ arguments: { background_task_id: created.task.id },
+ });
});
it('requires polling when the tool can return a process-local live artifact', () => {
diff --git a/packages/api/src/agents/background.ts b/packages/api/src/agents/background.ts
index de752c68a0..70e2429e0a 100644
--- a/packages/api/src/agents/background.ts
+++ b/packages/api/src/agents/background.ts
@@ -1787,7 +1787,7 @@ export function buildBackgroundHandleContent(
background_task_id: task.id,
tool: task.toolName,
status: task.status,
- message,
+ message: `${message} The tool field identifies the originating tool, not the polling tool. Status request: ${JSON.stringify({ name: CHECK_BACKGROUND_TASK_NAME, arguments: { background_task_id: task.id } })}`,
});
}
diff --git a/packages/api/src/agents/handlers.background.spec.ts b/packages/api/src/agents/handlers.background.spec.ts
index c1f972df15..dc41cb8464 100644
--- a/packages/api/src/agents/handlers.background.spec.ts
+++ b/packages/api/src/agents/handlers.background.spec.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { logger } from '@librechat/data-schemas';
+import { tool as structuredTool } from '@librechat/agents/langchain/tools';
import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';
import type { FiltersConfig } from 'librechat-data-provider';
import type { ToolExecuteOptions } from './handlers';
@@ -90,6 +91,54 @@ const runBatch = async (
};
describe('createToolExecuteHandler — background tool calls', () => {
+ it('hands off an explicit polling call and preserves validation feedback in its result', async () => {
+ const execute = jest.fn(async () => 'executed');
+ const bash = structuredTool(execute, {
+ name: 'build_project',
+ description: 'Starts commands',
+ schema: {
+ type: 'object',
+ required: ['command'],
+ properties: { command: { type: 'string' } },
+ },
+ });
+ const handler = createToolExecuteHandler({ loadTools: async () => ({ loadedTools: [bash] }) });
+ const configurable = buildConfig(['build_project']);
+ const [dispatch] = await runBatch(handler, {
+ toolCalls: [
+ {
+ id: 'invalid-background-bash',
+ name: 'build_project',
+ args: { background_task_id: 'secret-task', run_in_background: true },
+ },
+ ],
+ agentId: 'agent_parent_1',
+ configurable,
+ metadata: { thread_id: 'exec_convo', run_id: 'invalid-background-run' },
+ });
+ const handle = JSON.parse(dispatch.content);
+ const statusCheck = JSON.parse(handle.message.split('Status request: ')[1]);
+ expect(statusCheck).toEqual({
+ name: CHECK_BACKGROUND_TASK_NAME,
+ arguments: { background_task_id: handle.background_task_id },
+ });
+ await flushMicrotasks();
+ const [poll] = await runBatch(handler, {
+ toolCalls: [
+ {
+ id: 'poll-invalid-background-bash',
+ name: statusCheck.name,
+ args: statusCheck.arguments,
+ },
+ ],
+ agentId: 'agent_parent_1',
+ configurable,
+ metadata: { thread_id: 'exec_convo', run_id: 'invalid-background-run' },
+ });
+ expect(execute).not.toHaveBeenCalled();
+ expect(poll.content).toContain('Missing required fields: command');
+ expect(poll.content).not.toContain('secret-task');
+ });
it('pre-registers an ordinary completion before invoke and persists its terminal receipt', async () => {
const events: string[] = [];
const retire = jest.fn(async () => true);
diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.ts
index c65b82c91e..daa6eebabf 100644
--- a/packages/api/src/agents/handlers.spec.ts
+++ b/packages/api/src/agents/handlers.spec.ts
@@ -8,6 +8,7 @@ import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { Constants } from '@librechat/agents';
import { logger } from '@librechat/data-schemas';
+import { tool } from '@librechat/agents/langchain/tools';
import type {
ToolExecuteBatchRequest,
ToolExecuteResult,
@@ -1777,6 +1778,41 @@ describe('createToolExecuteHandler', () => {
);
});
+ it('returns actionable schema feedback and distinct log identity for a misrouted poll', async () => {
+ const execute = jest.fn(async () => 'executed');
+ const bash = tool(execute, {
+ name: 'bash_tool',
+ description: 'Starts a command',
+ schema: {
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ },
+ });
+ const errorSpy = jest.spyOn(logger, 'error').mockReturnValue(logger);
+ const [result] = await invokeHandler(
+ createToolExecuteHandler({
+ loadTools: async () => ({ loadedTools: [bash] }),
+ }),
+ [{ id: 'misrouted-poll', name: 'bash_tool', args: { background_task_id: 'private-task' } }],
+ );
+ expect(execute).not.toHaveBeenCalled();
+ expect(result.errorMessage).toContain('Missing required fields: command');
+ expect(errorSpy).toHaveBeenCalledWith(
+ '[ON_TOOL_EXECUTE] Tool bash_tool error',
+ expect.objectContaining({
+ toolName: 'bash_tool',
+ toolCallId: 'misrouted-poll',
+ errorName: 'Error',
+ errorMessage: result.errorMessage,
+ }),
+ );
+ const logged = JSON.stringify(errorSpy.mock.calls);
+ expect(logged).not.toContain('"message":');
+ expect(logged).not.toContain('"name":');
+ expect(logged).not.toContain('private-task');
+ });
+
it('truncates oversized tool errors in the result and log context', async () => {
const oversizedMessage = `tool failed: ${'x'.repeat(15_000)}`;
const thrown = new Error(oversizedMessage);
@@ -1851,7 +1887,7 @@ describe('createToolExecuteHandler', () => {
expect(errorSpy).toHaveBeenCalledWith(
'[ON_TOOL_EXECUTE] Tool bad_to_string_tool error',
expect.objectContaining({
- name: 'object',
+ errorName: 'object',
messageTruncated: false,
}),
);
@@ -1888,7 +1924,7 @@ describe('createToolExecuteHandler', () => {
expect(errorSpy).toHaveBeenCalledWith(
'[ON_TOOL_EXECUTE] Tool plain_object_tool error',
expect.objectContaining({
- message: 'plain object timeout',
+ errorMessage: 'plain object timeout',
messageTruncated: false,
}),
);
@@ -5908,7 +5944,7 @@ describe('createToolExecuteHandler', () => {
expect(errorSpy).toHaveBeenCalledWith(
'[ON_TOOL_EXECUTE] Tool list_workspace_files error',
expect.objectContaining({
- name: 'WorkspaceToolHttpError',
+ errorName: 'WorkspaceToolHttpError',
upstreamStatus: status,
upstreamBody: body,
upstreamBodyTruncated: false,
diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.ts
index e3f518d788..4c4a836781 100644
--- a/packages/api/src/agents/handlers.ts
+++ b/packages/api/src/agents/handlers.ts
@@ -117,6 +117,7 @@ import {
import { buildSkillPrimeMessage, isSkillFilePath, SKILL_FILE_PREFIX } from './skills';
import { resolveCallerCapabilityProjectionSnapshot } from './callerCapabilities';
import { mergeCodeFilesIntoContext } from './codeFilesSession';
+import { toolValidationFeedback } from './validationFeedback';
import { createSkillContentDigest } from './compatibility';
import { isMissingSandboxPathError } from '~/files/code';
import { resolveDownloadPath } from '~/storage/path';
@@ -817,18 +818,21 @@ function getThrownValueMessage(error: unknown): string {
return stringifyThrownValue(error);
}
-function getSafeToolError(error: unknown): {
+function getSafeToolError(
+ error: unknown,
+ feedback?: string,
+): {
message: string;
logContext: Record<string, unknown>;
} {
- const rawMessage = getThrownValueMessage(error);
+ const rawMessage = feedback ?? getThrownValueMessage(error);
const message = truncateMiddle(rawMessage, MAX_TOOL_ERROR_MESSAGE_CHARS);
- const stack = error instanceof Error && error.stack ? error.stack : undefined;
+ const stack = !feedback && error instanceof Error && error.stack ? error.stack : undefined;
return {
message,
logContext: {
- name: error instanceof Error ? error.name : typeof error,
+ errorName: error instanceof Error ? error.name : typeof error,
...(error instanceof WorkspaceToolHttpError
? {
upstreamStatus: error.upstreamStatus,
@@ -836,7 +840,7 @@ function getSafeToolError(error: unknown): {
upstreamBodyTruncated: error.upstreamBodyTruncated,
}
: {}),
- message,
+ errorMessage: message,
messageLength: rawMessage.length,
messageTruncated: message.length !== rawMessage.length,
stack: stack ? truncateMiddle(stack, MAX_TOOL_ERROR_STACK_CHARS) : undefined,
@@ -6192,7 +6196,16 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
toolError instanceof ContentFilterError
? modelBoundContentFilterErrorMessage(toolError.body)
: null;
- const { message } = getSafeToolError(toolError);
+ const { message, logContext } = getSafeToolError(
+ toolError,
+ toolValidationFeedback(
+ toolError,
+ tc.name,
+ tool.schema,
+ normalizedArgs,
+ backgroundControlEnabled,
+ ),
+ );
const errorOutput = policyError ?? message;
const filteredError =
policyError == null
@@ -6205,6 +6218,14 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
})
: null;
const neutralizedError = filteredError?.errorMessage ?? errorOutput;
+ if (policyError == null && filteredError == null) {
+ logger.debug('[background] Tool failed', {
+ ...logContext,
+ toolName: tc.name,
+ toolCallId: tc.id,
+ backgroundTaskId: task.id,
+ });
+ }
const deliveredError = toBackgroundToolFailure(tc.name, neutralizedError);
const registryError = isCodeCall ? deliveredError : neutralizedError;
/** Only an owner-authorized request is cancellation evidence.
@@ -6650,13 +6671,15 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
});
if (filteredError != null) {
logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {
- name: logContext.name,
+ errorName: logContext.errorName,
contentFiltered: true,
});
return filteredError;
}
const context = {
...logContext,
+ toolName: tc.name,
+ toolCallId: tc.id,
toolCallArgsShape: getValueShape(tc.args),
};
if (runSignal?.aborted === true && isAbortError(toolError)) {
@@ -6794,6 +6817,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
return missingToolResult;
}
+ let normalizedArgs: unknown = tc.args;
try {
const toolCallConfig = buildToolCallConfig(tc, mergedConfigurable);
@@ -6914,7 +6938,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
(hasRunInBackgroundArg(tc.args) && !toolDeclaresRunInBackgroundParam(tool))
? stripRunInBackgroundArg(tc.args)
: tc.args;
- const normalizedArgs = normalizeToolInvokeArgs(
+ normalizedArgs = normalizeToolInvokeArgs(
stripIntentForInvoke(foregroundArgs, tool),
tool,
);
@@ -7034,7 +7058,16 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
});
return errorResult(tc, modelBoundContentFilterErrorMessage(toolError.body));
}
- const { message, logContext } = getSafeToolError(toolError);
+ const { message, logContext } = getSafeToolError(
+ toolError,
+ toolValidationFeedback(
+ toolError,
+ tc.name,
+ tool.schema,
+ normalizedArgs,
+ backgroundControlEnabled,
+ ),
+ );
/** A user Stop rejects every in-flight call at once. That is
* the abort working, not a fault, so it is logged at debug.
* An aborted run says the turn is over, not that THIS
@@ -7062,13 +7095,15 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand
});
if (filteredError != null) {
logToolFailure({
- name: logContext.name,
+ errorName: logContext.errorName,
contentFiltered: true,
});
return filteredError;
}
logToolFailure({
...logContext,
+ toolName: tc.name,
+ toolCallId: tc.id,
toolCallArgsShape: getValueShape(tc.args),
toolInputSchemaKind: getToolInputSchemaKind(tool),
});
diff --git a/packages/api/src/agents/validationFeedback.spec.ts b/packages/api/src/agents/validationFeedback.spec.ts
new file mode 100644
index 0000000000..8cc3b82cd5
--- /dev/null
+++ b/packages/api/src/agents/validationFeedback.spec.ts
@@ -0,0 +1,55 @@
+import { tool } from '@librechat/agents/langchain/tools';
+import { toolValidationFeedback } from './validationFeedback';
+
+describe('toolValidationFeedback', () => {
+ it('explains a misrouted poll without invoking Bash or disclosing values', async () => {
+ const execute = jest.fn(async () => 'executed');
+ const bash = tool(execute, {
+ name: 'bash_tool',
+ description: 'Runs commands',
+ schema: {
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ },
+ });
+ const input = { background_task_id: 'private-task-id', intent: 'private-intent' };
+ const error = await bash.invoke(input).catch((failure: Error) => failure);
+ const feedback = toolValidationFeedback(error, bash.name, bash.schema, input, true);
+ expect(execute).not.toHaveBeenCalled();
+ expect(feedback).toContain('Missing required fields: command');
+ expect(feedback).toContain('call check_background_task');
+ expect(feedback).not.toContain('private-');
+ expect(toolValidationFeedback(error, bash.name, bash.schema, input)).not.toContain(
+ 'check_background_task',
+ );
+ });
+
+ it('does not rewrite execution failures that happen to use the parser message', () => {
+ expect(
+ toolValidationFeedback(
+ new Error('Received tool input did not match expected schema'),
+ 'bash_tool',
+ ),
+ ).toBeUndefined();
+ });
+
+ it('reports primitive type mismatches using schema metadata only', async () => {
+ const execute = jest.fn(async () => 'executed');
+ const bash = tool(execute, {
+ name: 'bash_tool',
+ description: 'Runs commands',
+ schema: {
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ },
+ });
+ const input = { command: { secret: 'never-echo' } };
+ const error = await bash.invoke(input).catch((failure: Error) => failure);
+ const feedback = toolValidationFeedback(error, bash.name, bash.schema, input);
+ expect(feedback).toContain('command (expected string)');
+ expect(feedback).not.toContain('never-echo');
+ expect(execute).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/agents/validationFeedback.ts b/packages/api/src/agents/validationFeedback.ts
new file mode 100644
index 0000000000..db1d570f06
--- /dev/null
+++ b/packages/api/src/agents/validationFeedback.ts
@@ -0,0 +1,72 @@
+import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';
+
+const MAX_FIELDS = 8;
+const safeName = (name: string): string => name.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 80);
+
+/** Read only schema-owned field names; parser messages/output can contain input secrets. */
+export function toolValidationFeedback(
+ error: unknown,
+ toolName: string,
+ schema?: StructuredToolInterface['schema'],
+ input?: unknown,
+ canCheckBackground = false,
+): string | undefined {
+ if (
+ !(error instanceof Error) ||
+ error.constructor.name !== 'ToolInputParsingException' ||
+ !error.message.startsWith('Received tool input did not match expected schema')
+ ) {
+ return undefined;
+ }
+ const fields: string[] = [];
+ if (schema != null && typeof schema === 'object' && 'required' in schema) {
+ const required = schema.required;
+ if (Array.isArray(required)) {
+ for (const field of required.slice(0, MAX_FIELDS)) {
+ if (
+ typeof field === 'string' &&
+ (input == null ||
+ typeof input !== 'object' ||
+ !Object.prototype.hasOwnProperty.call(input, field))
+ ) {
+ fields.push(safeName(field));
+ }
+ }
+ }
+ }
+ const missing = fields.length ? ` Missing required fields: ${fields.join(', ')}.` : '';
+ const invalid: string[] = [];
+ if (
+ schema != null &&
+ typeof schema === 'object' &&
+ 'properties' in schema &&
+ schema.properties != null &&
+ typeof schema.properties === 'object' &&
+ input != null &&
+ typeof input === 'object'
+ ) {
+ for (const [field, property] of Object.entries(schema.properties).slice(0, MAX_FIELDS)) {
+ if (
+ !Object.prototype.hasOwnProperty.call(input, field) ||
+ property == null ||
+ typeof property !== 'object' ||
+ !('type' in property)
+ )
+ continue;
+ const type = property.type;
+ const value = Object.getOwnPropertyDescriptor(input, field)?.value;
+ if ((type === 'string' || type === 'boolean' || type === 'number') && typeof value !== type) {
+ invalid.push(`${safeName(field)} (expected ${type})`);
+ }
+ }
+ }
+ const invalidTypes = invalid.length ? ` Invalid field types: ${invalid.join(', ')}.` : '';
+ const polling =
+ canCheckBackground &&
+ input != null &&
+ typeof input === 'object' &&
+ Object.prototype.hasOwnProperty.call(input, 'background_task_id')
+ ? ' To inspect an existing background task, call check_background_task with background_task_id.'
+ : '';
+ return `Tool "${safeName(toolName)}" input failed schema validation.${missing}${invalidTypes} Use this tool's declared arguments.${polling}`;
+}
diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.ts
index c436fb6809..e32da5a295 100644
--- a/packages/api/src/code/command.ts
+++ b/packages/api/src/code/command.ts
@@ -26,6 +26,7 @@ const DEFAULT_OUTPUT_BYTES = 256 * 1024;
export const ATTACHED_WORKSPACE_BASH_DESCRIPTION = `Runs bash commands inside the selected attached environment and returns stdout/stderr. The workspace may be an existing project, a Git repository, or an empty directory; Git is not required.
Session behavior:
+- This tool starts a new command. It does not inspect an existing background task. Use check_background_task with background_task_id when that tool is available to inspect an existing task; do not send a task ID to bash_tool.
- Files in the registered workspace persist between calls.
- Each call runs in a fresh sandboxed process; shell variables, the working directory, temporary files, and background processes do not survive the call.
- Network access follows the sandbox policy configured on the worker and may be unavailable.