🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(bot): explain fail-fast sandbox dispatch errors in IM replies (#21973)
Lobehub Coder485e02539a03
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.tsindex 8a1b23b2af6..a368d3a96be 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts@@ -2,7 +2,11 @@ import { ModelEmptyError, ModelRefusalError } from '@lobechat/model-runtime';import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { formatErrorForState, readErrorBudgetContext } from './formatErrorForState';+import {+ formatErrorForState,+ readDispatchErrorContext,+ readErrorBudgetContext,+} from './formatErrorForState';describe('formatErrorForState', () => {it('classifies an already-wrapped error using its nested provider message', () => {@@ -506,3 +510,46 @@ describe('readErrorBudgetContext', () => {).toBeUndefined();});});++describe('readDispatchErrorContext', () => {+ const sandboxFailure = (dispatch: Record<string, unknown> = {}) =>+ formatErrorForState({+ body: {+ detail: 'CLAUDE_CODE_OAUTH_TOKEN 未设置。请先在凭证管理中添加该凭证后再运行 claude-code。',+ dispatch: { agentType: 'claude-code', stage: 'sandbox_spawn', ...dispatch },+ },+ message: 'Hetero sandbox spawn failed',+ type: ChatErrorType.ServerAgentRuntimeError,+ });++ it('projects only the allowlisted dispatch fields', () => {+ const context = readDispatchErrorContext(+ sandboxFailure({+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ workspaceId: 'ws-internal',+ }),+ );++ expect(context).toEqual({+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ });+ expect(JSON.stringify(context)).not.toContain('凭证管理');+ });++ it('drops a credential that is not an environment-variable name', () => {+ expect(+ readDispatchErrorContext(sandboxFailure({ missingCredential: 'sk-ant-oat01-AbC_dEf' })),+ ).toEqual({ agentType: 'claude-code', stage: 'sandbox_spawn' });+ });++ it('ignores errors without an allowlisted dispatch context', () => {+ expect(readDispatchErrorContext(undefined)).toBeUndefined();+ expect(readDispatchErrorContext(formatErrorForState(new Error('boom')))).toBeUndefined();+ expect(readDispatchErrorContext(sandboxFailure({ stage: 'other' }))).toBeUndefined();+ expect(readDispatchErrorContext(sandboxFailure({ agentType: 'openclaw' }))).toBeUndefined();+ });+});diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.tsindex b11ab5e283f..ce58ac4076f 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts@@ -1,6 +1,11 @@+import { isLocalHeterogeneousType } from '@lobechat/heterogeneous-agents';import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';-import type { ChatErrorBudgetContext, ChatMessageError } from '@lobechat/types';+import type {+ ChatErrorBudgetContext,+ ChatErrorDispatchContext,+ ChatMessageError,+} from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import { formatPgError, pgErrorType, unwrapPgError } from './pgError';@@ -60,3 +65,29 @@ export const readErrorBudgetContext = (return Object.values(context).some((value) => value !== undefined) ? context : undefined;};++/** Credential names are environment-variable shaped; anything else is dropped. */+const CREDENTIAL_NAME = /^[A-Z][\dA-Z]*(?:_[\dA-Z]+)+$/;++/**+ * Read the fail-fast dispatch context a hetero dispatch attached to its error+ * (`body.dispatch`) out of an already-normalized error, field by field, so+ * only allowlisted values reach hook consumers and IM replies.+ */+export const readDispatchErrorContext = (+ error: ChatMessageError | undefined,+): ChatErrorDispatchContext | undefined => {+ const dispatch = isRecord(error?.body) ? error.body.dispatch : undefined;+ if (!isRecord(dispatch) || dispatch.stage !== 'sandbox_spawn') return undefined;+ if (typeof dispatch.agentType !== 'string' || !isLocalHeterogeneousType(dispatch.agentType))+ return undefined;++ const { missingCredential } = dispatch;+ return {+ agentType: dispatch.agentType,+ ...(dispatch.deviceAccessDenied === true && { deviceAccessDenied: true }),+ ...(typeof missingCredential === 'string' &&+ CREDENTIAL_NAME.test(missingCredential) && { missingCredential }),+ stage: 'sandbox_spawn',+ };+};diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.tsindex b93d592fdec..b47077e8556 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.lifecycleEvent.test.ts@@ -398,6 +398,34 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {});});+ it('carries the allowlisted cause of a failed sandbox dispatch', () => {+ const { event } = callBuild(+ {+ error: {+ body: {+ dispatch: {+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ },+ },+ message: 'Hetero sandbox spawn failed',+ type: 'ServerAgentRuntimeError',+ },+ origin: { agentId: 'agent-1', userId: 'user-1' },+ },+ 'error',+ );++ expect(event.errorDispatch).toEqual({+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ });+ });+it('populates errorType + attribution from the normalized error on the error path', () => {// Regression: the event previously carried only errorDetail/errorMessage, so// bot reply renderers never saw the stable code/attribution and always felldiff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.tsindex ae45bbb868a..06fefa9ad3a 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts@@ -6,6 +6,7 @@ import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/erimport {formatErrorForState,+ readDispatchErrorContext,readErrorBudgetContext,} from '@/server/modules/AgentRuntime/formatErrorForState';@@ -107,6 +108,7 @@ export function buildLifecycleEvent(errorBudget: readErrorBudgetContext(formattedError),errorHeterogeneous: readHeterogeneousErrorContext(formattedError),errorDetail: state?.error,+ errorDispatch: readDispatchErrorContext(formattedError),errorMessage: extractErrorMessage(state?.error) || String(state?.error || ''),errorType: formattedError?.type === undefined ? undefined : String(formattedError.type),finalState: state,diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex fdf56746935..07348855af9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -2437,7 +2437,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>expect(errorBubbleUpdates()[0][1]).toEqual(expect.objectContaining({error: expect.objectContaining({- body: { detail: 'Gateway Timeout' },+ body: expect.objectContaining({ detail: 'Gateway Timeout' }),message: 'Hetero sandbox spawn failed',}),}),diff --git a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.test.ts b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.test.tsnew file mode 100644index 00000000000..c273b29b62a--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.test.ts@@ -0,0 +1,84 @@+import { ChatErrorType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { finalizeHeteroDispatchError } from './finalizeHeteroDispatchError';++const mocks = vi.hoisted(() => ({+ completeOperation: vi.fn(),+ publishAgentRuntimeEnd: vi.fn(),+}));++vi.mock('@/server/services/agentRuntime/CompletionLifecycle', () => ({+ CompletionLifecycle: class {+ completeOperation = mocks.completeOperation;+ },+}));++vi.mock('@/server/services/agentRuntime/hooks', () => ({+ hookDispatcher: { canDeliver: vi.fn(() => true), getSerializedHooks: vi.fn(() => []) },+}));++vi.mock('@/server/modules/AgentRuntime/factory', () => ({+ createStreamEventManager: () => ({ publishAgentRuntimeEnd: mocks.publishAgentRuntimeEnd }),+}));++const createDeps = () => ({+ db: {} as any,+ messageModel: { update: vi.fn().mockResolvedValue(undefined) } as any,+ topicModel: { settleRunningOperation: vi.fn().mockResolvedValue(undefined) } as any,+ userId: 'user-1',+});++const baseParams = {+ assistantMessageId: 'asst-1',+ detail: 'CLAUDE_CODE_OAUTH_TOKEN 未设置。请先在凭证管理中添加该凭证后再运行 claude-code。',+ message: 'Hetero sandbox spawn failed',+ operationId: 'op-1',+ topicId: 'topic-1',+};++describe('finalizeHeteroDispatchError', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.completeOperation.mockResolvedValue(undefined);+ });++ /**+ * The completion hooks (IM bot reply) only see the lifecycle error, not the+ * message row. Before T-1195 that error dropped the body, so the bot could+ * only render a bare Operation ID for a sandbox that was missing a credential.+ */+ it('hands the dispatch cause to the completion hooks', async () => {+ const deps = createDeps();+ const dispatch = {+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ } as const;+ const error = { message: baseParams.message, type: ChatErrorType.ServerAgentRuntimeError };++ await finalizeHeteroDispatchError(deps, { ...baseParams, dispatch });++ expect(deps.messageModel.update).toHaveBeenCalledWith('asst-1', {+ content: '',+ error: { ...error, body: { detail: baseParams.detail, dispatch } },+ });+ // The free-form detail stays on the message row; hooks get only the+ // allowlisted cause.+ expect(mocks.completeOperation).toHaveBeenCalledWith(+ expect.objectContaining({ error: { ...error, body: { dispatch } } }),+ 'error',+ { skipErrorMessageWrite: true },+ );+ });++ it('keeps the lifecycle error unchanged for other dispatch failures', async () => {+ await finalizeHeteroDispatchError(createDeps(), baseParams);++ expect(mocks.completeOperation.mock.calls[0][0].error).toEqual({+ message: baseParams.message,+ type: ChatErrorType.ServerAgentRuntimeError,+ });+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.tsindex 852caa2f285..657e3e5afd4 100644--- a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts+++ b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts@@ -1,5 +1,9 @@import type { LobeChatDatabase } from '@lobechat/database';-import type { DeviceUnavailableErrorData, ErrorType } from '@lobechat/types';+import type {+ ChatErrorDispatchContext,+ DeviceUnavailableErrorData,+ ErrorType,+} from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';import debug from 'debug';@@ -52,6 +56,12 @@ export const finalizeHeteroDispatchError = async (agentId?: string;assistantMessageId: string;detail: string;+ /**+ * Allowlisted cause of the dispatch failure. Unlike `detail`, it also rides+ * on the lifecycle error, so completion hooks (the IM bot reply) can name+ * the cause without receiving the free-form text.+ */+ dispatch?: ChatErrorDispatchContext;/** The device this dispatch was routed to, when it was a device dispatch. */deviceRoute?: DeviceDispatchRoute;errorData?: DeviceUnavailableErrorData;@@ -71,6 +81,7 @@ export const finalizeHeteroDispatchError = async (assistantMessageId,detail,deviceRoute,+ dispatch,errorData,errorType = ChatErrorType.ServerAgentRuntimeError,message,@@ -82,7 +93,11 @@ export const finalizeHeteroDispatchError = async (// end event below re-reads a message that already carries the error.await deps.messageModel.update(assistantMessageId, {content: '',- error: { body: { detail, ...errorData }, message, type: errorType },+ error: {+ body: { detail, ...errorData, ...(dispatch && { dispatch }) },+ message,+ type: errorType,+ },});// 1b. Finalize the run through CompletionLifecycle's single entry — the SAME@@ -101,7 +116,12 @@ export const finalizeHeteroDispatchError = async ({agentId,assistantMessageId,- error: { message, type: errorType, ...(deviceRoute && { deviceRoute }) },+ error: {+ message,+ type: errorType,+ ...(deviceRoute && { deviceRoute }),+ ...(dispatch && { body: { dispatch } }),+ },operationId,serializedHooks: hookDispatcher.getSerializedHooks(operationId),topicId,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.tsindex f83955ab08d..4eb1a0a7e5f 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts@@ -758,4 +758,81 @@ describe('dispatchHeteroAgent — cloud sandbox', () => {expect(mocks.signUserJWT).toHaveBeenCalledWith('user-1', '4h');expect(result).toMatchObject({ success: true, token: undefined });});++ describe('spawn failure', () => {+ const marketService = { market: { creds: { list: vi.fn().mockResolvedValue({ data: [] }) } } };+ const credentialMissing =+ 'CLAUDE_CODE_OAUTH_TOKEN 未设置。请先在凭证管理中添加该凭证后再运行 claude-code。';+ const spawnFailure = async (ctx: ExecRunContext, detail = credentialMissing) => {+ mocks.spawnHeteroSandbox.mockRejectedValueOnce(new Error(detail));+ const { deps } = createDeps({ getMarketService: vi.fn().mockResolvedValue(marketService) });+ await dispatchHeteroAgent(deps, ctx, createInput('claude-code'));+ await vi.waitFor(() => expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalled());+ return mocks.finalizeHeteroDispatchError.mock.calls.at(-1)![1];+ };++ /**+ * A sender without device access on a device-bound agent is degraded to the+ * sandbox. When the sandbox then fails, the reply must say why the run was+ * there at all — otherwise "the sandbox is missing a credential" reads as+ * nonsense to someone who expected the owner's device.+ */+ it('marks a sandbox run that replaced a denied device', async () => {+ const params = await spawnFailure(+ createCtx(+ {+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ },+ { canUseDevice: false, deviceAccessReason: 'bot-external-sender' },+ ),+ );++ expect(params).toMatchObject({+ detail: credentialMissing,+ dispatch: {+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ },+ message: 'Hetero sandbox spawn failed',+ });+ });++ const sandboxAgent = () =>+ createCtx(+ { executionTarget: 'sandbox', heterogeneousProvider: { type: 'claude-code' } },+ { canUseDevice: false },+ );++ it('reads the credential from English wording too', async () => {+ const params = await spawnFailure(+ sandboxAgent(),+ 'CLAUDE_CODE_OAUTH_TOKEN is not set. Add it under Credentials and retry.',+ );++ expect(params.dispatch.missingCredential).toBe('CLAUDE_CODE_OAUTH_TOKEN');+ });++ it('does not blame device access for an agent that targets the sandbox', async () => {+ const params = await spawnFailure(sandboxAgent());++ expect(params.dispatch).toEqual({+ agentType: 'claude-code',+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ });+ });++ it.each([+ 'E2B_API_KEY is not set; sandbox credential configuration is incomplete',+ 'Gateway Timeout',+ ])('names no credential for a failure that is not about one (%s)', async (detail) => {+ const params = await spawnFailure(sandboxAgent(), detail);++ expect(params.dispatch).toEqual({ agentType: 'claude-code', stage: 'sandbox_spawn' });+ });+ });});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex 2a4ff3adc51..8e5ebdfedf2 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -186,18 +186,25 @@ export const dispatchHeteroAgent = async (// Resolve CLI-device routing before persisting the marker. Cancellation// must address the same device even though local CLI agents use a different// dispatch transport from notify-based platform agents.+ const cliPlanParams = {+ agencyConfig: agentConfig.agencyConfig,+ clientExecutionAvailable: false,+ isHetero: true,+ requestedDeviceId,+ sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),+ trigger: requestTrigger,+ };const deviceHeteroPlan = !isRemoteHetero- ? resolveExecutionPlan({- agencyConfig: agentConfig.agencyConfig,- canUseDevice,- isHetero: true,- clientExecutionAvailable: false,- requestedDeviceId,- sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),- trigger: requestTrigger,- })+ ? resolveExecutionPlan({ ...cliPlanParams, canUseDevice }): undefined;const cliDeviceId = deviceHeteroPlan?.kind === 'device' ? deviceHeteroPlan.deviceId : undefined;+ // Whether the sandbox is a fallback for a sender denied the agent's device:+ // with access the same request would have routed to a device. Lets a failed+ // sandbox run tell the sender why it ran there instead.+ const deviceAccessDenied =+ deviceHeteroPlan?.kind === 'sandbox' &&+ !canUseDevice &&+ resolveExecutionPlan({ ...cliPlanParams, canUseDevice: true }).kind === 'device';const cliDeviceWorkspaceId = cliDeviceId? await deps.resolveDeviceWorkspaceId(cliDeviceId): undefined;@@ -408,7 +415,7 @@ export const dispatchHeteroAgent = async (heterogeneousProvider,prepared,})- : await spawnInCloudSandbox(deps, run, { heteroType, prepared });+ : await spawnInCloudSandbox(deps, run, { deviceAccessDenied, heteroType, prepared });if (failure) return failure;}diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.tsindex 8525ff825a8..66ac3b55754 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts@@ -2,6 +2,7 @@ import type { ExecAgentResult } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';+import { CLAUDE_CODE_TOKEN_CRED_KEY } from '@/helpers/claudeCodeTokenCred';import { signUserJWT } from '@/libs/trpc/utils/internalJwt';import { spawnHeteroSandbox } from '@/server/services/heterogeneousAgent/sandboxRunner';@@ -88,6 +89,27 @@ const hasHeteroRunStarted = async (}};+/**+ * Vault credentials the cloud sandbox injects for each agent. Only these can be+ * named as missing: a sandbox provider may report its own variables the same+ * way (`E2B_API_KEY is not set`), and those are not the user's to add.+ */+const SANDBOX_AGENT_CREDENTIALS: Partial<Record<string, readonly string[]>> = {+ 'claude-code': [CLAUDE_CODE_TOKEN_CRED_KEY],+};++const MISSING_CREDENTIAL =+ /\b([A-Z][\dA-Z]*(?:_[\dA-Z]+)+)\s*(?:未设置|未配置|is not set|is not configured)/;++/**+ * Name the agent credential the sandbox rejected the run for, e.g.+ * `CLAUDE_CODE_OAUTH_TOKEN 未设置。请先在凭证管理中添加该凭证…`.+ */+const readMissingCredential = (heteroType: string, detail: string): string | undefined => {+ const name = MISSING_CREDENTIAL.exec(detail)?.[1];+ return name && SANDBOX_AGENT_CREDENTIALS[heteroType]?.includes(name) ? name : undefined;+};+/*** Spawn a local CLI hetero agent in the cloud sandbox. The spawn is* fire-and-forget; its failure is settled in the background unless the run@@ -99,9 +121,14 @@ const hasHeteroRunStarted = async (export const spawnInCloudSandbox = async (deps: HeteroDispatchDeps,run: HeteroRun,- params: { heteroType: HeteroDispatchInput['heteroType']; prepared: PreparedHeteroRun },+ params: {+ /** The sender may not use the agent's device, which is why this run landed here. */+ deviceAccessDenied?: boolean;+ heteroType: HeteroDispatchInput['heteroType'];+ prepared: PreparedHeteroRun;+ },): Promise<ExecAgentResult | undefined> => {- const { heteroType, prepared } = params;+ const { deviceAccessDenied, heteroType, prepared } = params;const { heteroExecArgs, heteroParams, sandbox } = prepared;const { agentId: resolvedAgentId, assistantMessageId, operationId, topicId } = run;@@ -158,10 +185,18 @@ export const spawnInCloudSandbox = async (// ran — see `hasHeteroRunStarted`.if (await hasHeteroRunStarted(deps, { operationId, topicId })) return;+ const detail = err instanceof Error ? err.message : String(err);+ const missingCredential = readMissingCredential(heteroType, detail);await finalizeHeteroDispatchError(deps, {agentId: resolvedAgentId,assistantMessageId,- detail: err instanceof Error ? err.message : String(err),+ detail,+ dispatch: {+ agentType: heteroType,+ ...(deviceAccessDenied && { deviceAccessDenied }),+ ...(missingCredential && { missingCredential }),+ stage: 'sandbox_spawn',+ },message: 'Hetero sandbox spawn failed',operationId,topicId,diff --git a/apps/server/src/services/bot/AgentBridgeService/localMode.ts b/apps/server/src/services/bot/AgentBridgeService/localMode.tsindex 5ec85bd2aea..492da536ee9 100644--- a/apps/server/src/services/bot/AgentBridgeService/localMode.ts+++ b/apps/server/src/services/bot/AgentBridgeService/localMode.ts@@ -257,6 +257,7 @@ export async function executeWithHooksLocalMode(event.errorAttribution,event.errorBudget,event.errorHeterogeneous,+ event.errorDispatch,);// Wrap in `{ markdown }` so the Chat SDK adapter sets the// platform's markdown parse_mode (e.g. Telegram `Markdown`,diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.tsindex b55e9c9aebc..35ae8433c46 100644--- a/apps/server/src/services/bot/BotCallbackService.ts+++ b/apps/server/src/services/bot/BotCallbackService.ts@@ -4,6 +4,7 @@ import type {BotNoReplyResult,BotWakeKind,ChatErrorBudgetContext,+ ChatErrorDispatchContext,ChatErrorHeterogeneousContext,} from '@lobechat/types';import debug from 'debug';@@ -108,6 +109,7 @@ export interface BotCallbackBody {* Forwarded verbatim from the agent lifecycle event.*/errorBudget?: ChatErrorBudgetContext;+ errorDispatch?: ChatErrorDispatchContext;errorHeterogeneous?: ChatErrorHeterogeneousContext;errorMessage?: string;errorType?: string;@@ -605,6 +607,7 @@ export class BotCallbackService {lastAssistantContent,errorAttribution,errorBudget,+ errorDispatch,errorHeterogeneous,errorMessage,errorType,@@ -627,6 +630,7 @@ export class BotCallbackService {errorAttribution,errorBudget,errorHeterogeneous,+ errorDispatch,);const errorText = client.formatMarkdown?.(errorBody) ?? errorBody;if (deliveredChunkCount < 1) {diff --git a/apps/server/src/services/bot/__tests__/renderDispatchError.test.ts b/apps/server/src/services/bot/__tests__/renderDispatchError.test.tsnew file mode 100644index 00000000000..7c03f5cfdf7--- /dev/null+++ b/apps/server/src/services/bot/__tests__/renderDispatchError.test.ts@@ -0,0 +1,88 @@+import type { ChatErrorDispatchContext } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { renderAgentError } from '../replyTemplate';++const OPERATION_ID = 'op_xxx';++const render = (dispatch: ChatErrorDispatchContext | undefined, lng?: 'en-US' | 'zh-CN') =>+ renderAgentError(+ 'ServerAgentRuntimeError',+ 'Hetero sandbox spawn failed',+ OPERATION_ID,+ lng,+ undefined,+ undefined,+ undefined,+ dispatch,+ );++describe('fail-fast dispatch IM errors', () => {+ /**+ * ROOT CAUSE (T-1195): a sandbox spawn failure reached the bot as a bare+ * `ServerAgentRuntimeError` with no attribution, so the reply fell to the+ * legacy tier — "Agent Execution Failed" plus an Operation ID — while the+ * actual cause (a missing CLAUDE_CODE_OAUTH_TOKEN) sat only on the message row.+ */+ it('explains a device-access fallback into a sandbox without the credential', () => {+ const reply = render(+ {+ agentType: 'claude-code',+ deviceAccessDenied: true,+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ },+ 'zh-CN',+ );++ expect(reply).toBe(+ [+ '**Claude Code 未能在云端沙箱启动**',+ '你没有这台设备的操作权限,已转到云端沙箱运行,但沙箱缺少 `CLAUDE_CODE_OAUTH_TOKEN` 凭证。请让 Bot 所有者在频道的「设备权限」中为你授权,或在「设置 → 凭证管理」中添加 `CLAUDE_CODE_OAUTH_TOKEN`。',+ `Operation ID: \`${OPERATION_ID}\``,+ ].join('\n'),+ );+ expect(reply).not.toContain('Agent Execution Failed');+ });++ it('keeps the Operation ID as the last line, after the cause', () => {+ const lines = render({+ agentType: 'claude-code',+ missingCredential: 'CLAUDE_CODE_OAUTH_TOKEN',+ stage: 'sandbox_spawn',+ }).split('\n');++ expect(lines).toEqual([+ '**Claude Code could not start in the cloud sandbox**',+ 'The cloud sandbox is missing the `CLAUDE_CODE_OAUTH_TOKEN` credential. Ask the bot owner to add `CLAUDE_CODE_OAUTH_TOKEN` under Settings → Credentials, then try again.',+ `Operation ID: \`${OPERATION_ID}\``,+ ]);+ });++ it.each([+ ['en-US', true, "You don't have access to this bot's device"],+ ['zh-CN', true, '你没有这台设备的操作权限'],+ ['en-US', false, 'The cloud sandbox failed to start.'],+ ['zh-CN', false, '云端沙箱启动失败。'],+ ] as const)(+ 'names the sandbox failure when no credential is known (%s, denied=%s)',+ (lng, deviceAccessDenied, expected) => {+ const reply = render(+ {+ agentType: 'codex',+ ...(deviceAccessDenied && { deviceAccessDenied }),+ stage: 'sandbox_spawn',+ },+ lng,+ );++ expect(reply).toContain('Codex');+ expect(reply).toContain(expected);+ expect(reply).not.toContain('Hetero sandbox spawn failed');+ },+ );++ it('falls back to the legacy reply without a dispatch context', () => {+ expect(render(undefined)).toBe(`**Agent Execution Failed**\nOperation ID: \`${OPERATION_ID}\``);+ });+});diff --git a/apps/server/src/services/bot/renderDispatchError.ts b/apps/server/src/services/bot/renderDispatchError.tsnew file mode 100644index 00000000000..fbf736e3d6e--- /dev/null+++ b/apps/server/src/services/bot/renderDispatchError.ts@@ -0,0 +1,61 @@+import { getHeterogeneousTypeLabel } from '@lobechat/heterogeneous-agents';+import type { ChatErrorDispatchContext } from '@lobechat/types';++import type { BotReplyLocale } from './platforms/const';++interface DispatchCopy {+ credential: (name: string) => string;+ deniedCredential: (name: string) => string;+ deniedFailed: string;+ failed: string;+ title: (agent: string) => string;+}++const COPY: Partial<Record<BotReplyLocale, DispatchCopy>> = {+ 'en-US': {+ credential: (name) =>+ `The cloud sandbox is missing the \`${name}\` credential. Ask the bot owner to add \`${name}\` under Settings → Credentials, then try again.`,+ deniedCredential: (name) =>+ `You don't have access to this bot's device, so the run moved to the cloud sandbox — which is missing the \`${name}\` credential. Ask the bot owner to grant you Device access in the channel settings, or to add \`${name}\` under Settings → Credentials.`,+ deniedFailed:+ "You don't have access to this bot's device, so the run moved to the cloud sandbox, which failed to start. Ask the bot owner to grant you Device access in the channel settings, or try again later.",+ failed:+ 'The cloud sandbox failed to start. Try again; if it keeps happening, share the Operation ID below with the bot owner.',+ title: (agent) => `**${agent} could not start in the cloud sandbox**`,+ },+ 'zh-CN': {+ credential: (name) =>+ `云端沙箱缺少 \`${name}\` 凭证。请让 Bot 所有者在「设置 → 凭证管理」中添加 \`${name}\` 后重试。`,+ deniedCredential: (name) =>+ `你没有这台设备的操作权限,已转到云端沙箱运行,但沙箱缺少 \`${name}\` 凭证。请让 Bot 所有者在频道的「设备权限」中为你授权,或在「设置 → 凭证管理」中添加 \`${name}\`。`,+ deniedFailed:+ '你没有这台设备的操作权限,已转到云端沙箱运行,但沙箱启动失败。请让 Bot 所有者在频道的「设备权限」中为你授权,或稍后重试。',+ failed: '云端沙箱启动失败。请稍后重试;如果持续出现,请把下方 Operation ID 提供给 Bot 所有者。',+ title: (agent) => `**${agent} 未能在云端沙箱启动**`,+ },+};++/**+ * Render a run that failed before its agent started as one line of cause and+ * one of next step. Built only from the allowlisted dispatch context — the raw+ * dispatch detail never reaches the channel.+ */+export const renderDispatchError = (+ context: ChatErrorDispatchContext | undefined,+ lng: BotReplyLocale = 'en-US',+): string | undefined => {+ if (context?.stage !== 'sandbox_spawn') return;+ const copy = COPY[lng] ?? COPY['en-US']!;+ const agent = getHeterogeneousTypeLabel(context.agentType) ?? 'Agent';+ const { deviceAccessDenied, missingCredential } = context;++ const cause = missingCredential+ ? deviceAccessDenied+ ? copy.deniedCredential(missingCredential)+ : copy.credential(missingCredential)+ : deviceAccessDenied+ ? copy.deniedFailed+ : copy.failed;++ return `${copy.title(agent)}\n${cause}`;+};diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex 05ab4e69429..abca5eb5de5 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -3,7 +3,11 @@ import {getErrorCodeSpec,normalizeChatMessageError,} from '@lobechat/model-runtime/errors';-import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';+import type {+ ChatErrorBudgetContext,+ ChatErrorDispatchContext,+ ChatErrorHeterogeneousContext,+} from '@lobechat/types';import type { StepPresentationData } from '../agentRuntime/types';import { getExtremeAck } from './ackPhrases';@@ -13,6 +17,7 @@ import { getExtremeAck } from './ackPhrases';// Telegram Guest outbound path import this template for localized copy.import { type BotReplyLocale } from './platforms/const';import { formatDuration } from './platforms/utils';+import { renderDispatchError } from './renderDispatchError';import { renderHeterogeneousError } from './renderHeterogeneousError';// Use raw Unicode emoji instead of Chat SDK emoji placeholders,@@ -728,6 +733,9 @@ const isCommandConnectionClosedError = (* learns who owns the failure and whether to retry.* 3. **Legacy** — when neither is known, the opaque `Operation ID` template.*+ * Allowlisted external-agent (`heterogeneous`) and fail-fast dispatch+ * (`dispatch`) contexts take precedence over all three tiers.+ ** The Operation ID is appended as a footer to every tier (not the whole* message) so it stays traceable in logs without being the only thing the* user sees.@@ -740,10 +748,15 @@ export function renderAgentError(attribution?: string,budget?: ChatErrorBudgetContext,heterogeneous?: ChatErrorHeterogeneousContext,+ dispatch?: ChatErrorDispatchContext,): string {const strings = getSystemStrings(lng);const heteroReply = renderHeterogeneousError(heterogeneous);if (heteroReply) return appendOperationId(heteroReply, operationId);+ // A run that failed before its agent started: name the cause (missing+ // sandbox credential, device-access fallback) instead of the bare legacy tier.+ const dispatchReply = renderDispatchError(dispatch, lng);+ if (dispatchReply) return appendOperationId(dispatchReply, operationId);const normalized = normalizeChatMessageError({message: errorMessage,diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.tsindex c577db2840e..77dc2825c3a 100644--- a/packages/agent-runtime/src/types/hooks.ts+++ b/packages/agent-runtime/src/types/hooks.ts@@ -1,5 +1,6 @@import type {ChatErrorBudgetContext,+ ChatErrorDispatchContext,ChatErrorHeterogeneousContext,ExecutionPlan,ToolExecutor,@@ -88,6 +89,12 @@ export interface AgentHookEvent {errorBudget?: ChatErrorBudgetContext;// ContenterrorDetail?: string;+ /**+ * Allowlisted cause of a run that failed before its agent started (e.g. the+ * cloud sandbox is missing a credential), so consumers can say what went+ * wrong without forwarding the free-form dispatch detail.+ */+ errorDispatch?: ChatErrorDispatchContext;errorHeterogeneous?: ChatErrorHeterogeneousContext;errorMessage?: string;diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.tsindex 9f31e91d4e0..b00321c9384 100644--- a/packages/types/src/message/common/base.ts+++ b/packages/types/src/message/common/base.ts@@ -42,6 +42,20 @@ export interface ChatErrorBudgetContext {shortfallCredits?: number;}+/**+ * Safe context for a run that failed before its agent started (fail-fast+ * dispatch), for completion hooks and IM replies. Only allowlisted fields:+ * the free-form dispatch detail stays on the message row.+ */+export interface ChatErrorDispatchContext {+ agentType: string;+ /** The sender may not use the agent's device, so the run fell back to the cloud sandbox. */+ deviceAccessDenied?: boolean;+ /** Environment-variable name of a credential the sandbox reported missing — never its value. */+ missingCredential?: string;+ stage: 'sandbox_spawn';+}+/** Safe external-agent error context for completion hooks and IM replies. */export interface ChatErrorHeterogeneousContext {agentType: string;