Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent): bound tool error messages so a huge tool output can't kill the operation (#19496)

Arvin Xu85c6a7f1d3c2
diff --git a/apps/server/src/services/queue/__tests__/QueueService.test.ts b/apps/server/src/services/queue/__tests__/QueueService.test.ts
index fd4c026b9b2..4ac21e48e0d 100644
--- a/apps/server/src/services/queue/__tests__/QueueService.test.ts
+++ b/apps/server/src/services/queue/__tests__/QueueService.test.ts
@@ -248,6 +248,77 @@ describe('QueueService', () => {
expect(qstashMocks.publishJSON.mock.calls[0][0]).toMatchObject({ delay: 2 });
});
+ it('clamps an oversized body instead of letting the publish blow the QStash quota', async () => {
+ qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });
+
+ const { QStashQueueServiceImpl } = await import('../impls/qstash');
+ const impl = new QStashQueueServiceImpl({ qstashToken: 'test-qstash-token' });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // A tool that failed with ~12 MB of command output β€” the shape that used
+ // to 500 the publish and take the whole operation down with it.
+ const runawayOutput = 'x'.repeat(12 * 1024 * 1024);
+
+ await impl.scheduleMessage({
+ context: {
+ payload: { toolsResult: [{ content: runawayOutput }] },
+ phase: 'llm_result',
+ } as any,
+ delay: 0,
+ endpoint: 'https://example.com/api/agent/run',
+ operationId: 'op-oversized',
+ priority: 'normal',
+ stepIndex: 7,
+ });
+
+ const request = qstashMocks.publishJSON.mock.calls[0][0];
+ const clamped = request.body.context.payload.toolsResult[0].content;
+ expect(clamped.length).toBeLessThan(runawayOutput.length);
+ expect(clamped).toContain('characters omitted so the step could be scheduled');
+ expect(Buffer.byteLength(JSON.stringify(request.body), 'utf8')).toBeLessThan(9 * 1024 * 1024);
+ // Shape is preserved so the worker still reads the step it expects.
+ expect(request.body).toMatchObject({ operationId: 'op-oversized', stepIndex: 7 });
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('agent.queue.oversized_message_clamped'),
+ );
+
+ warn.mockRestore();
+ });
+
+ /**
+ * Fragmented oversize: the MCP contract keeps every raw content block in
+ * `state`, so a body can pass the quota through hundreds of mid-sized
+ * strings that a single generous clamp pass would leave untouched.
+ */
+ it('tightens the clamp until a fragmented oversized body actually fits', async () => {
+ qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });
+
+ const { QStashQueueServiceImpl } = await import('../impls/qstash');
+ const impl = new QStashQueueServiceImpl({ qstashToken: 'test-qstash-token' });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const blocks = Array.from({ length: 525 }, () => ({ text: 'y'.repeat(20_000) }));
+
+ await impl.scheduleMessage({
+ context: { payload: { state: { content: blocks } }, phase: 'llm_result' } as any,
+ delay: 0,
+ endpoint: 'https://example.com/api/agent/run',
+ operationId: 'op-fragmented',
+ priority: 'normal',
+ stepIndex: 3,
+ });
+
+ const request = qstashMocks.publishJSON.mock.calls[0][0];
+ expect(Buffer.byteLength(JSON.stringify(request.body), 'utf8')).toBeLessThan(9 * 1024 * 1024);
+ expect(request.body.context.payload.state.content).toHaveLength(525);
+ expect(request.body.context.payload.state.content[0].text).toContain(
+ 'characters omitted so the step could be scheduled',
+ );
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"stringKeep":4000'));
+
+ warn.mockRestore();
+ });
+
it('encodes logical deduplication keys as stable QStash-safe opaque IDs', async () => {
qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });
diff --git a/apps/server/src/services/queue/impls/qstash.ts b/apps/server/src/services/queue/impls/qstash.ts
index a2524eac12c..53c55ff557c 100644
--- a/apps/server/src/services/queue/impls/qstash.ts
+++ b/apps/server/src/services/queue/impls/qstash.ts
@@ -29,6 +29,57 @@ const toQStashDelaySeconds = (delayMs: number): number | undefined => {
return Math.max(1, Math.round(delayMs / 1000));
};
+/**
+ * QStash rejects any single message above 10 MiB (`quota maxMessageSize
+ * exceeded`) with a 500, so an oversized body used to fail the publish, throw
+ * out of `executeStep` and kill the whole operation at a step boundary. The
+ * budget leaves headroom for the envelope QStash adds around the body.
+ */
+const QSTASH_MAX_BODY_BYTES = 10 * 1024 * 1024;
+const QSTASH_BODY_BUDGET_BYTES = 9 * 1024 * 1024;
+
+/**
+ * How much a single string may keep, tried in order until the WHOLE body
+ * measures under budget. One pass at a generous limit is not enough: a body
+ * can also be oversized through fragmentation β€” the MCP contract keeps every
+ * raw content block in `state`, so hundreds of blocks each shorter than the
+ * limit survive an untouched pass and still add up past the quota. Each rung
+ * re-clamps the original body, so the notices never nest.
+ */
+const OVERSIZED_STRING_KEEP_LADDER = [25_000, 4000, 512, 0];
+
+const byteLength = (value: unknown): number =>
+ Buffer.byteLength(JSON.stringify(value) ?? '', 'utf8');
+
+/**
+ * Shrink a too-large message body by clamping every string past `keep`,
+ * depth-first. Strings are the only thing that can run away here β€” tool
+ * results and error messages carrying raw command output β€” so clamping them
+ * recovers the body while keeping its shape intact for the worker that
+ * receives it.
+ */
+const clampOversizedStrings = (value: unknown, keep: number): unknown => {
+ if (typeof value === 'string') {
+ if (value.length <= keep) return value;
+ const omitted = value.length - keep;
+
+ return `${value.slice(0, keep)}\n\n[Truncated: ${omitted.toLocaleString()} characters omitted so the step could be scheduled. Original length: ${value.length.toLocaleString()} characters]`;
+ }
+
+ if (Array.isArray(value)) return value.map((entry) => clampOversizedStrings(entry, keep));
+
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
+ key,
+ clampOversizedStrings(entry, keep),
+ ]),
+ );
+ }
+
+ return value;
+};
+
/**
* QStash queue service implementation
*/
@@ -82,7 +133,7 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {
retries,
url: endpoint,
};
- const response = await qstashClient.publishJSON(request);
+ const response = await qstashClient.publishJSON(this.fitBodyToQuota(request, operationId));
log(
`[${operationId}] Scheduled step %d to %s with %dms delay (messageId: %s)`,
@@ -99,6 +150,46 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {
}
}
+ /**
+ * Keep a step schedulable when its body outgrew the QStash message quota:
+ * clamp its strings rather than let the publish 500 and take the whole
+ * operation down. The step still runs β€” it just sees a truncated copy of
+ * whatever ran away. Clamping tightens until the body MEASURES under budget,
+ * so a body that is oversized through many mid-sized strings is handled too,
+ * not only one runaway blob.
+ */
+ private fitBodyToQuota<T extends { body: unknown }>(request: T, operationId: string): T {
+ const size = byteLength(request.body);
+ if (size <= QSTASH_BODY_BUDGET_BYTES) return request;
+
+ for (const keep of OVERSIZED_STRING_KEEP_LADDER) {
+ const body = clampOversizedStrings(request.body, keep);
+ const clampedBytes = byteLength(body);
+ if (clampedBytes > QSTASH_BODY_BUDGET_BYTES) continue;
+
+ console.warn(
+ JSON.stringify({
+ bytes: size,
+ clampedBytes,
+ event: 'agent.queue.oversized_message_clamped',
+ limitBytes: QSTASH_MAX_BODY_BYTES,
+ operationId,
+ stringKeep: keep,
+ }),
+ );
+
+ return { ...request, body };
+ }
+
+ // Unreachable through strings β€” the last rung drops every string to a
+ // notice. Getting here means the body is huge in its non-string structure,
+ // which no truncation can fix; fail with something diagnosable instead of
+ // an opaque `quota maxMessageSize exceeded` 500 from the provider.
+ throw new Error(
+ `QStash message for operation ${operationId} is ${size} bytes and cannot be reduced under the ${QSTASH_MAX_BODY_BYTES} byte quota`,
+ );
+ }
+
async scheduleBatchMessages(messages: QueueMessage[]): Promise<string[]> {
try {
// Use Promise.all for concurrent execution
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index c8d9266528b..c6766c56ade 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -83,6 +83,44 @@ describe('ToolExecutionService', () => {
expect(result.content).toContain('Content truncated');
});
+ /**
+ * @example A sandbox `rm -rf` against a read-only FS fails with one line per
+ * file β€” ~29 MB of stderr. The error envelope must not carry it: it rides the
+ * step's nextContext into the QStash publish body, whose 10 MB message quota
+ * would fail the publish and kill the whole operation.
+ */
+ it('clamps the error message of a tool that failed with a huge output', async () => {
+ const runawayOutput = `Command failed with exit code 1\n\nStderr:\n${'rm: cannot remove\n'.repeat(200_000)}`;
+ const builtinToolsExecutor = {
+ execute: vi.fn().mockResolvedValue({
+ content: runawayOutput,
+ success: false,
+ }),
+ };
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: builtinToolsExecutor as any,
+ mcpService: {} as any,
+ });
+
+ const result = await service.executeTool(
+ {
+ apiName: 'runCommand',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ },
+ { skipResultTruncation: true, toolManifestMap: {} },
+ );
+
+ const message = (result.error as { message: string }).message;
+ expect(message.length).toBeLessThan(5000);
+ expect(message).toContain('Command failed with exit code 1');
+ expect(message).toContain('Content truncated');
+ // The archival opt-out covers the LLM-facing content, never the error.
+ expect(result.content).toBe(runawayOutput);
+ });
+
/** @example A missing remote device remains machine-readable to the calling agent runtime. */
it('preserves structured unavailable-device data in the normalized error envelope', async () => {
const builtinToolsExecutor = {
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index cb366061804..1e6c9270a40 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -40,16 +40,33 @@ interface ToolExecutionServiceDeps {
mcpService: MCPService;
}
+/**
+ * Hard bound on the `error.message` of a failed tool call. The (already
+ * truncated) `content` is what the LLM reads; the error is metadata, so it
+ * never needs the full payload β€” and an unbounded one is dangerous: a tool
+ * that fails with megabytes of output (e.g. `rm -rf` on a read-only sandbox
+ * FS, one `cannot remove` line per file) rides the step's `nextContext` into
+ * the QStash publish body and blows the provider's 10 MB message quota, which
+ * fails the whole operation at the step boundary instead of just that one tool
+ * call. Deliberately NOT subject to `skipResultTruncation` β€” that opt-out is
+ * about the LLM context budget, this is a transport safety bound.
+ */
+const TOOL_ERROR_MESSAGE_MAX_LENGTH = 4000;
+
+const clampErrorMessage = (message: string | undefined): string | undefined =>
+ message === undefined ? undefined : truncateToolResult(message, TOOL_ERROR_MESSAGE_MAX_LENGTH);
+
const normalizeExecutionError = (error: unknown, fallbackMessage: string) => {
const normalized = classifyToolError(error || fallbackMessage);
- const message = fallbackMessage || normalized.message;
+ // Classification reads the raw error above; only the carried copy is clamped.
+ const message = clampErrorMessage(fallbackMessage || normalized.message);
if (error && typeof error === 'object') {
if (error instanceof Error) {
return {
code: normalized.code,
kind: normalized.kind,
- message: error.message || message,
+ message: clampErrorMessage(error.message) || message,
name: error.name,
};
}
@@ -60,12 +77,12 @@ const normalizeExecutionError = (error: unknown, fallbackMessage: string) => {
...plainError,
code: (plainError.code as string | undefined) || normalized.code,
kind: normalized.kind,
- message: (plainError.message as string | undefined) || message,
+ message: clampErrorMessage(plainError.message as string | undefined) || message,
};
}
if (typeof error === 'string') {
- return { code: normalized.code, kind: normalized.kind, message: error };
+ return { code: normalized.code, kind: normalized.kind, message: clampErrorMessage(error) };
}
return { code: normalized.code, kind: normalized.kind, message };