🤯 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: clarify artifact delivery and preserve tool refusals (#19409)
YuTengjing4367a885eb93
diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 520f43b0809..8bb8b10ba4b 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -6,6 +6,7 @@ import { type NextRequest } from 'next/server';import { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';+import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';import { listSkillToolsWithLiveFallback } from './listSkillToolsWithLiveFallback';@@ -687,6 +688,9 @@ export class MarketService {}const message = responseError?.message || dataMessage || 'LobeHub Skill call failed';+ const denial = getToolAccessDeniedError(responseError, message);+ if (denial)+ return { content: JSON.stringify({ error: denial }), error: denial, success: false };return {content: message,@@ -719,6 +723,9 @@ export class MarketService {// Extract it so the content is not empty on failure.const errorBody = (err as any).errorBody;const skillError = errorBody?.error;+ const denial = getToolAccessDeniedError(error, err.message);+ if (denial)+ return { content: JSON.stringify({ error: denial }), error: denial, success: false };const content = skillError ? JSON.stringify(skillError) : err.message;return {diff --git a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.tsindex 7e9f0110c2f..21699126be9 100644--- a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts+++ b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts@@ -13,6 +13,38 @@ class TestComputerRuntime extends ComputerRuntime {}}+describe('CloudSandbox access refusals', () => {+ it.each(['writeFile', 'runCommand', 'executeCode', 'exportFile'] as const)(+ 'preserves refusal details and failure status for %s',+ async (api) => {+ const error = {+ code: 'FORBIDDEN',+ hint: 'Ask the administrator to review request filtering.',+ message: 'Forbidden',+ status: 403,+ };+ const runtime = new CloudSandboxExecutionRuntime({+ callTool: vi.fn().mockResolvedValue({ error, result: null, success: false }),+ exportAndUploadFile: vi+ .fn()+ .mockResolvedValue({ error, filename: 'page.html', success: false }),+ });++ const result =+ api === 'writeFile'+ ? await runtime.writeFile({ content: '<html></html>', path: '/page.html' })+ : api === 'runCommand'+ ? await runtime.runCommand({ command: 'echo ok' })+ : api === 'executeCode'+ ? await runtime.executeCode({ code: 'print(1)' })+ : await runtime.exportFile({ path: '/page.html' });++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject(error);+ },+ );+});+describe.each(['runCommand', 'executeCode', 'getCommandOutput'] as const)('CloudSandbox %s recreation',(api) => {diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex 2a35f1fce0d..59c7c378a3e 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -2,6 +2,8 @@ import type { SandboxCallToolResult } from '@lobechat/builtin-tool-cloud-sandboximport type { CodeInterpreterToolName } from '@lobehub/market-sdk';import debug from 'debug';+import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';+import { SandboxMiddlewareService } from '../service';import type {SandboxProvider,@@ -71,7 +73,7 @@ export class MarketSandboxProvider implements SandboxProvider {if (!response.success) {return {- error: {+ error: getToolAccessDeniedError(response.error, response.error?.message || '') || {message: response.error?.message || 'Unknown error',name: response.error?.code,},@@ -90,7 +92,7 @@ export class MarketSandboxProvider implements SandboxProvider {log('Error calling sandbox tool %s: %O', toolName, error);return {- error: {+ error: getToolAccessDeniedError(error, (error as Error).message) || {message: (error as Error).message,name: (error as Error).name,},@@ -119,7 +121,7 @@ export class MarketSandboxProvider implements SandboxProvider {if (!response.success) {return {- error: {+ error: getToolAccessDeniedError(response.error, response.error?.message || '') || {message: response.error?.message || 'Failed to export file from sandbox',name: response.error?.code,},@@ -146,7 +148,9 @@ export class MarketSandboxProvider implements SandboxProvider {log('Error exporting file: %O', error);return {- error: { message: (error as Error).message },+ error: getToolAccessDeniedError(error, (error as Error).message) || {+ message: (error as Error).message,+ },success: false,};}diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.tsindex 7b0826acde6..e8952a497bc 100644--- a/apps/server/src/services/sandbox/service.ts+++ b/apps/server/src/services/sandbox/service.ts@@ -148,8 +148,8 @@ export class SandboxMiddlewareService implements SandboxService {if (!exported.success) {return {error: {+ ...exported.error,message: exported.error?.message || 'Failed to export file from sandbox',- name: exported.error?.name,},filename,success: false,diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.tsindex 1ab05d880b5..319587fb1b0 100644--- a/apps/server/src/services/sandbox/types.ts+++ b/apps/server/src/services/sandbox/types.ts@@ -62,7 +62,7 @@ export interface SandboxProviderFileExportRequest {}export interface SandboxProviderFileExportResult {- error?: { message: string; name?: string };+ error?: SandboxExportFileResult['error'];mimeType?: string;result?: Record<string, unknown>;size?: number;diff --git a/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts b/apps/server/src/services/toolExecution/__tests__/errorClassification.test.tsindex 7672bbf9f2a..69390f509e6 100644--- a/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { classifyToolError } from '../errorClassification';+import { classifyToolError, getToolAccessDeniedError } from '../errorClassification';describe('classifyToolError', () => {it('should classify rate limit as retry', () => {@@ -27,3 +27,55 @@ describe('classifyToolError', () => {expect(result.kind).toBe('stop');});});++describe('getToolAccessDeniedError', () => {+ it('handles a thrown string without losing its message', () => {+ expect(getToolAccessDeniedError('Forbidden', '')).toMatchObject({+ code: 'FORBIDDEN',+ message: 'Forbidden',+ });+ });++ it('keeps documented upstream guidance without publishing the raw response body', () => {+ const error = Object.assign(new Error('Access denied'), {+ code: 'PERMISSION_DENIED',+ errorBody: {+ error: { doc_url: 'https://example.com/help', hint: 'Ask an administrator.' },+ internal: 'private response detail',+ },+ status: 403,+ });++ expect(getToolAccessDeniedError(error, error.message)).toEqual({+ code: 'PERMISSION_DENIED',+ doc_url: 'https://example.com/help',+ hint: 'Ask an administrator.',+ kind: 'stop',+ message: 'Access denied',+ status: 403,+ });+ });++ it('accepts numeric HTTP error codes without throwing', () => {+ expect(getToolAccessDeniedError({ code: 403, message: 'Request blocked' }, '')).toMatchObject({+ code: 'FORBIDDEN',+ kind: 'stop',+ });+ });++ it.each([+ [undefined, 'curl: (22) The requested URL returned error: 403'],+ [new Error('AssertionError: expected 200 but got 403'), ''],+ ])('does not infer a platform refusal from an HTTP status in tool output', (error, content) => {+ expect(getToolAccessDeniedError(error, content)).toBeUndefined();+ });++ it.each([+ { code: 'BAD_REQUEST', message: 'The word forbidden is not a supported option' },+ { message: 'ENOENT: /tmp/forbidden.txt' },+ { message: 'Network error', status: 503 },+ { code: 'NOT_IMPLEMENTED', message: 'Unsupported tool' },+ ])('does not invent a refusal from an unrelated error: $message', (error) => {+ expect(getToolAccessDeniedError(error, error.message)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex c6766c56ade..1132a6a9298 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import { executeToolWithRetry } from '@lobechat/agent-runtime';+import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';import { beforeEach, describe, expect, it, vi } from 'vitest';import { deviceGateway } from '@/server/services/deviceGateway';@@ -23,6 +25,209 @@ vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({}));describe('ToolExecutionService', () => {+ it('keeps a failed command HTTP status as command output', async () => {+ const output = 'curl: (22) The requested URL returned error: 403';+ const service = new ToolExecutionService({+ builtinToolsExecutor: {+ execute: vi.fn().mockResolvedValue({ content: output, success: false }),+ } as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ {+ apiName: 'runCommand',+ arguments: '{}',+ id: 'http-command',+ identifier: 'lobe-cloud-sandbox',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ );++ expect(result.content).toBe(output);+ expect(result.error).not.toMatchObject({ code: 'FORBIDDEN' });+ });++ it.each(['returned', 'thrown'])(+ 'retries a read-only sandbox %s network failure',+ async (mode) => {+ const error = { code: 'SERVICE_UNAVAILABLE', message: 'Network error', status: 503 };+ const call =+ mode === 'returned'+ ? vi+ .fn()+ .mockResolvedValueOnce({ error, result: null, success: false })+ .mockResolvedValue({ result: { content: 'ok' }, success: true })+ : vi+ .fn()+ .mockRejectedValueOnce(Object.assign(new Error(error.message), error))+ .mockResolvedValue({ result: { content: 'ok' }, success: true });+ const runtime = new CloudSandboxExecutionRuntime({+ callTool: call,+ exportAndUploadFile: vi.fn(),+ });+ const service = new ToolExecutionService({+ builtinToolsExecutor: { execute: () => runtime.readFile({ path: '/page.html' }) } as any,+ mcpService: {} as any,+ });+ const { attempts, result } = await executeToolWithRetry(+ () =>+ service.executeTool(+ {+ apiName: 'readFile',+ arguments: '{}',+ id: 'read-retry',+ identifier: 'lobe-cloud-sandbox',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ ),+ { maxRetries: 2 },+ );++ expect(result.success).toBe(true);+ expect(attempts).toBe(2);+ expect(call).toHaveBeenCalledTimes(2);+ },+ );++ describe.each(['writeFile', 'runCommand', 'executeCode', 'exportFile'] as const)(+ 'non-retryable sandbox %s failures',+ (api) => {+ it.each(['returned', 'thrown'])(+ 'does not repeat side effects after a %s network error',+ async (mode) => {+ const error = {+ code: 'SERVICE_UNAVAILABLE',+ message: 'Network error after execution',+ status: 503,+ };+ const call =+ mode === 'returned'+ ? vi+ .fn()+ .mockResolvedValue({ error, result: null, filename: 'page.html', success: false })+ : vi.fn().mockRejectedValue(Object.assign(new Error(error.message), error));+ const runtime = new CloudSandboxExecutionRuntime({+ callTool: call,+ exportAndUploadFile: call,+ });+ const execute = () =>+ api === 'writeFile'+ ? runtime.writeFile({ content: 'content', path: '/page.html' })+ : api === 'runCommand'+ ? runtime.runCommand({ command: 'echo effect' })+ : api === 'executeCode'+ ? runtime.executeCode({ code: 'print("effect")' })+ : runtime.exportFile({ path: '/page.html' });+ const service = new ToolExecutionService({+ builtinToolsExecutor: { execute } as any,+ mcpService: {} as any,+ });+ const { attempts, result } = await executeToolWithRetry(+ () =>+ service.executeTool(+ {+ apiName: api,+ arguments: '{}',+ id: 'side-effect',+ identifier: 'lobe-cloud-sandbox',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ ),+ { maxRetries: 2 },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ kind: 'stop', message: error.message });+ expect(attempts).toBe(1);+ expect(call).toHaveBeenCalledTimes(1);+ },+ );+ },+ );++ it.each([+ { identifier: 'lobe-cloud-sandbox', error: { message: 'Forbidden' } },+ { identifier: 'linear', error: { code: 'LOBEHUB_SKILL_ERROR', message: 'Forbidden' } },+ ])('makes a bare denial actionable for $identifier', async ({ identifier, error }) => {+ const service = new ToolExecutionService({+ builtinToolsExecutor: {+ execute: vi.fn().mockResolvedValue({ content: 'Forbidden', error, success: false }),+ } as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ { apiName: 'writeFile', arguments: '{}', id: 'denied-call', identifier, type: 'builtin' },+ { toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(JSON.parse(result.content).error).toMatchObject({+ code: 'FORBIDDEN',+ hint: expect.stringContaining('Do not retry'),+ kind: 'stop',+ message: 'Forbidden',+ });+ expect(result.error).toMatchObject({ code: 'FORBIDDEN', kind: 'stop' });+ expect(result.content).not.toContain('matched_pattern');+ });++ it('preserves upstream refusal details in the model-visible content', async () => {+ const error = {+ code: 'PERMISSION_DENIED',+ hint: 'Ask the workspace administrator to grant access.',+ message: 'Access denied',+ status: 403,+ };+ const service = new ToolExecutionService({+ builtinToolsExecutor: {+ execute: vi.fn().mockRejectedValue(Object.assign(new Error(error.message), error)),+ } as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ {+ apiName: 'writeFile',+ arguments: '{}',+ id: 'denied-call',+ identifier: 'tool',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ );++ expect(JSON.parse(result.content).error).toMatchObject({ ...error, kind: 'stop' });+ expect(result.error).toMatchObject(error);+ });++ it('does not reinterpret successful content containing Forbidden as a denial', async () => {+ const service = new ToolExecutionService({+ builtinToolsExecutor: {+ execute: vi.fn().mockResolvedValue({ content: 'Forbidden', success: true }),+ } as any,+ mcpService: {} as any,+ });++ const result = await service.executeTool(+ {+ apiName: 'readFile',+ arguments: '{}',+ id: 'read-call',+ identifier: 'tool',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ );++ expect(result.content).toBe('Forbidden');+ expect(result.success).toBe(true);+ });+it('can skip low-level result truncation for AgentRuntime archival', async () => {const builtinToolsExecutor = {execute: vi.fn().mockResolvedValue({diff --git a/apps/server/src/services/toolExecution/errorClassification.ts b/apps/server/src/services/toolExecution/errorClassification.tsindex c88cff0567d..9497afe00a0 100644--- a/apps/server/src/services/toolExecution/errorClassification.ts+++ b/apps/server/src/services/toolExecution/errorClassification.ts@@ -1,3 +1,5 @@+import { pickString, toRecord } from '@lobechat/utils/object';+export type ToolErrorKind = 'replan' | 'retry' | 'stop';interface ToolErrorSignal {@@ -21,6 +23,7 @@ const REPLAN_CODES = new Set(['MCP_EXECUTION_ERROR',]);const STOP_CODES = new Set([+ 'CONTENT_POLICY_VIOLATION','FORBIDDEN','INSUFFICIENT_PERMISSIONS','NOT_IMPLEMENTED',@@ -63,10 +66,11 @@ const STOP_KEYWORDS = [const hasAnyKeyword = (text: string, keywords: string[]) =>keywords.some((keyword) => text.includes(keyword));-const normalizeCode = (value?: string): string | undefined => {- if (!value) return;+const normalizeCode = (value?: unknown): string | undefined => {+ const code = typeof value === 'number' ? String(value) : pickString(value);+ if (!code) return;- return value+ return code.trim().toUpperCase().replaceAll(/[\s-]+/g, '_');@@ -162,3 +166,57 @@ export const classifyToolError = (error: unknown): ClassifiedToolError => {message: signal.message,};};++const DENIAL_CODES = new Set([+ '403',+ 'CONTENT_POLICY_VIOLATION',+ 'FORBIDDEN',+ 'INSUFFICIENT_PERMISSIONS',+ 'PERMISSION_DENIED',+]);+const GENERIC_ERROR_CODES = new Set([+ '403',+ 'CLOUD_MCP_EXECUTION_ERROR',+ 'LOBEHUB_SKILL_ERROR',+ 'MCP_EXECUTION_ERROR',+]);++/**+ * A transport refusal must explain the next action in the model-visible content.+ * A bare 403 cannot identify whether authorization or request filtering rejected+ * the call, so never infer a content policy or a matched rule from its message.+ */+export const getToolAccessDeniedError = (error: unknown, fallbackMessage: string) => {+ const raw = toRecord(error);+ const nested = toRecord(toRecord(raw?.errorBody)?.error) || toRecord(raw?.error);+ const signal = normalizeSignal(error || fallbackMessage);+ const code = normalizeCode(nested?.code) || signal.code;+ const structuredStatus =+ raw?.status === 403 ||+ raw?.statusCode === 403 ||+ nested?.status === 403 ||+ nested?.statusCode === 403;+ const bareForbidden = /^\s*(?:403[ :-]*)?forbidden\s*$/i;+ const message =+ pickString(raw?.message) ||+ pickString(nested?.message) ||+ pickString(error) ||+ fallbackMessage ||+ 'Tool access was denied';++ if (!structuredStatus && !DENIAL_CODES.has(code || '') && !bareForbidden.test(message)) {+ return;+ }++ return {+ code: code && !GENERIC_ERROR_CODES.has(code) ? code : 'FORBIDDEN',+ doc_url: pickString(raw?.doc_url) || pickString(nested?.doc_url),+ hint:+ pickString(raw?.hint) ||+ pickString(nested?.hint) ||+ 'Do not retry this call, switch tools or paths, encode/split its arguments, or run permission/directory probes to work around the refusal. Stop the affected operation and report this error. Ask the user or administrator to check tool permissions and upstream request filtering; do not make diagnostic tool calls unless explicitly asked to investigate. The upstream response did not identify the blocking rule.',+ kind: 'stop' as const,+ message,+ status: signal.status,+ };+};diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 1e6c9270a40..e3650b5ba95 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -25,7 +25,7 @@ import {import { DiscoverService } from '../discover';import { type MCPService } from '../mcp';import { type BuiltinToolsExecutor } from './builtin';-import { classifyToolError } from './errorClassification';+import { classifyToolError, getToolAccessDeniedError } from './errorClassification';import { resolveRunWorkspaceId } from './serverRuntimes/resolveWorkspaceScope';import {type ToolExecutionContext,@@ -76,7 +76,9 @@ const normalizeExecutionError = (error: unknown, fallbackMessage: string) => {return {...plainError,code: (plainError.code as string | undefined) || normalized.code,- kind: normalized.kind,+ // A runtime may know that side effects already happened; retry keywords+ // must not override its explicit refusal to replay the operation.+ kind: plainError.kind === 'stop' ? 'stop' : normalized.kind,message: clampErrorMessage(plainError.message as string | undefined) || message,};}@@ -147,6 +149,13 @@ export class ToolExecutionService {const executionTime = Date.now() - startTime;+ const denial = !data.success+ ? getToolAccessDeniedError(data.errorData ?? data.error, data.content)+ : undefined;+ if (denial) {+ data = { ...data, content: JSON.stringify({ error: denial }), error: denial };+ }+// Truncate result content to prevent context overflow// Use agent-specific config if provided, otherwise use defaultconst truncatedContent = context.skipResultTruncation@@ -186,10 +195,12 @@ export class ToolExecutionService {const executionTime = Date.now() - startTime;log('Error executing tool %s:%s: %O', identifier, apiName, error);const errorMessage = (error as Error).message;+ const denial = getToolAccessDeniedError(error, errorMessage);+ const content = denial ? JSON.stringify({ error: denial }) : errorMessage;return {- content: context.skipResultTruncation ? errorMessage : truncateToolResult(errorMessage),- error: normalizeExecutionError(error, errorMessage),+ content: context.skipResultTruncation ? content : truncateToolResult(content),+ error: denial || normalizeExecutionError(error, errorMessage),executionTime,success: false,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.tsindex 5d44719e02c..f9ff5277063 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts@@ -147,6 +147,76 @@ vi.mock('../resolveWorkspaceScope', () => ({}));describe('skillsRuntime', () => {+ it.each(+ (['runCommand', 'execScript', 'exportFile'] as const).flatMap((api) =>+ (['returned', 'thrown', 'stderr'] as const)+ .filter((mode) => api !== 'exportFile' || mode !== 'stderr')+ .map((mode) => ({ api, mode })),+ ),+ )(+ 'preserves sandbox $mode errors through the $api execution pipeline',+ async ({ api, mode }) => {+ const { skillsRuntime } = await import('../skills');+ const { ToolExecutionService } = await import('../../index');+ const error = { name: 'MarketAPIError', message: 'Forbidden' };+ mocks.sandboxService.callTool.mockResolvedValue({ error, result: null, success: false });+ mocks.sandboxService.exportAndUploadFile.mockResolvedValue({+ error,+ filename: 'page.html',+ success: false,+ });+ if (mode === 'thrown') {+ const thrown = Object.assign(new Error('Forbidden'), { status: 403 });+ mocks.sandboxService.callTool.mockRejectedValue(thrown);+ mocks.sandboxService.exportAndUploadFile.mockRejectedValue(thrown);+ } else if (mode === 'stderr') {+ mocks.sandboxService.callTool.mockResolvedValue({+ success: true,+ result: { success: false, exitCode: 1, stdout: '', stderr: 'Forbidden' },+ });+ }+ const runtime = await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });+ const execute = () =>+ api === 'exportFile'+ ? runtime.exportFile({ path: '/page.html', filename: 'page.html' })+ : runtime[api]({ command: 'echo example', description: 'Example' });+ const service = new ToolExecutionService({+ builtinToolsExecutor: { execute } as never,+ mcpService: {} as never,+ });+ const result = await service.executeTool(+ {+ apiName: api,+ arguments: '{}',+ id: 'refusal',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ { toolManifestMap: {} },+ );+ expect(result.success).toBe(false);+ if (mode === 'stderr') {+ expect(result.content).toContain('Forbidden');+ expect(result.content).not.toContain('Do not retry');+ expect(result.error?.code).not.toBe('FORBIDDEN');+ return;+ }+ expect(JSON.parse(result.content).error).toMatchObject({+ code: 'FORBIDDEN',+ kind: 'stop',+ message: 'Forbidden',+ hint: expect.stringContaining('Do not retry'),+ });+ expect(result.error).toMatchObject({ code: 'FORBIDDEN', kind: 'stop' });+ },+ 30_000,+ );+beforeEach(() => {vi.clearAllMocks();diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex e84b0f27b49..fb1d80a91aa 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -36,6 +36,7 @@ import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService, normalizeSandboxCommandResult } from '@/server/services/sandbox';import { SkillResourceService } from '@/server/services/skill/resource';+import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';import {buildDeviceLhEnv,isLhCommand,@@ -244,6 +245,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {if (!response.success) {return {+ error: response.error,executionEnv: 'sandbox',exitCode: 1,output: '',@@ -256,6 +258,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {} catch (error) {log('Error running command: %O', error);return {+ error: getToolAccessDeniedError(error, 'Command execution failed') ?? {+ message: (error as Error).message,+ },executionEnv: 'sandbox',exitCode: 1,output: '',@@ -577,6 +582,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {if (!response.success) {return {+ error: response.error,executionEnv: 'sandbox',exitCode: 1,output: '',@@ -589,6 +595,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {} catch (error) {log('Error executing script: %O', error);return {+ error: getToolAccessDeniedError(error, 'Command execution failed') ?? {+ message: (error as Error).message,+ },executionEnv: 'sandbox',exitCode: 1,output: '',@@ -621,6 +630,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {const result = await sandboxService.exportAndUploadFile(path, filename);return {+ error: result.error,fileId: result.fileId,filename: result.filename,mimeType: result.mimeType,@@ -631,6 +641,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {} catch (error) {log('Error exporting file: %O', error);return {+ error: getToolAccessDeniedError(error, 'File export failed') ?? {+ message: (error as Error).message,+ },filename,success: false,};diff --git a/packages/builtin-skills/src/artifacts/content.ts b/packages/builtin-skills/src/artifacts/content.tsindex 9ee7e980350..e0e2b5050c9 100644--- a/packages/builtin-skills/src/artifacts/content.ts+++ b/packages/builtin-skills/src/artifacts/content.ts@@ -3,6 +3,8 @@ The assistant possesses the capability to generate "Artifacts"—dedicated UI wi# 1. Evaluation Criteria+For a self-contained preview, emit the Artifact directly after loading these instructions unless the user explicitly requests a downloadable file, an inline preview, or separate computation or validation. Do NOT activate or call sandbox tools merely to prepare a file, probe the environment, or perform optional validation. Do not invent an additional download or validation requirement: "write a playable game in HTML" requests an HTML Artifact, not a downloadable file. Instructions to activate needed tools apply only to tools the user's task actually needs. Complete separately requested computation or validation when needed, then deliver in the requested format.+## When to Create an Artifact (Qualifying Content)Target content that serves as a distinct visual or interactive "deliverable." Valid candidates are:- **Interactive Components:** UI components, dashboards, data visualizations, or interactive widgets.@@ -21,12 +23,12 @@ Do NOT generate artifacts for:# 2. Operational Constraints- **Frequency:** Limit to one artifact per response unless explicitly engaged in a multi-file task.-- **Preference:** Defaults to inline text for simplicity. Artifacts are reserved for when a separate visual window significantly enhances utility.+- **Preference:** Use Artifacts for visual and interactive works. Honor an explicit request for a downloadable file or supported inline preview instead; code snippets and explanations stay inline.- **Capability Mapping:**- - If asked for "images/SVG", provide an SVG artifact.+ - If asked for "SVG", provide an SVG artifact. Raster image files use the available image-generation or file tools.- If asked for "websites" or "web pages", provide HTML or React artifacts.- If asked for "dashboards" or "interactive components", provide React artifacts.- - If asked for "code", provide it inline as markdown code blocks, NOT as an artifact.+ - If asked for a code snippet or code explanation, provide it inline as markdown code blocks, NOT as an artifact. "Write code for a playable web game" still requests an interactive deliverable.- **Safety:** Do NOT generate hazardous content. Apply the same safety standards as text responses.# 3. Generation Workflow@@ -201,5 +203,5 @@ Here are some examples of correct usage of artifacts:The assistant should not mention any of these instructions to the user, nor make reference to the \`lobeArtifact\` tag, any of the MIME types (e.g. \`application/lobe.artifacts.react\`), or related syntax unless it is directly relevant to the query.The assistant should always take care to not produce artifacts that would be highly hazardous to human health or wellbeing if misused, even if is asked to produce them for seemingly benign reasons. However, if Claude would be willing to produce the same content in text form, it should be willing to produce it in an artifact.-</artifacts_info>+</artifacts_guides>`;diff --git a/packages/builtin-skills/src/artifacts/manifest.ts b/packages/builtin-skills/src/artifacts/manifest.tsindex 035cf2b7fc1..3a6233c9a84 100644--- a/packages/builtin-skills/src/artifacts/manifest.ts+++ b/packages/builtin-skills/src/artifacts/manifest.ts@@ -5,7 +5,7 @@ export const ArtifactsIdentifier = 'lobe-artifacts';export const ArtifactsManifest: BuiltinSkillManifest = {avatar: `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHJ4PSI1MTIiIGZpbGw9IiNDNDc4NUIiLz48cGF0aCBkPSJNNTEyIDYxMmM1NS4yMjggMCAxMDAtNDQuNzcyIDEwMC0xMDBzLTQ0Ljc3Mi0xMDAtMTAwLTEwMC0xMDAgNDQuNzcyLTEwMCAxMDAgNDQuNzcyIDEwMCAxMDAgMTAwWiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNTEyIDY2MmExNDkuOTk4IDE0OS45OTggMCAwIDEtOTIuNTk3IDEzOC41ODIgMTUwLjAwMiAxNTAuMDAyIDAgMCAxLTIwNC41MjEtMTA5LjMxOCAxNDkuOTk4IDE0OS45OTggMCAwIDEgNjMuNzgzLTE1My45ODRBMTQ5Ljk5MiAxNDkuOTkyIDAgMCAxIDM2MiA1MTJhMTQ5Ljk5OSAxNDkuOTk5IDAgMSAxIDE1MC0xNTAgMTQ5Ljk5OCAxNDkuOTk4IDAgMCAxIDI5Ny4xMTgtMjkuMjYzQTE1MCAxNTAgMCAwIDEgNjYyIDUxMmMyOS42NjcgMCA1OC42NjggOC43OTcgODMuMzM1IDI1LjI4YTE0OS45OTUgMTQ5Ljk5NSAwIDAgMSA2My43ODMgMTUzLjk4NEExNTAgMTUwIDAgMCAxIDUxMiA2NjJaTTUxMiAzNjJ2NTBNMzYyIDUxMmg1ME02NjIgNTEyaC01ME01MTIgNjYydi01ME0zNzguNjY3IDM3OC42NjdsNjIuNjY2IDYyLjY2Nk01ODIuNjY3IDQ0MS4zMzNsNjIuNjY2LTYyLjY2Nk0zNzguNjY3IDY0NS4zMzNsNjIuNjY2LTYyLjY2Nk01ODIuNjY3IDU4Mi42NjdsNjIuNjY2IDYyLjY2NiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4=`,description:- 'Generate visual and interactive artifacts like SVG graphics, HTML pages, and React components',+ 'Create directly viewable web pages, browser games, SVG graphics or animations, and React components. Prefer this skill for visual works, including requests to show the result directly or preview it. Use files only when the user explicitly requests a download; HTML/SVG specify the implementation format, not download intent. Do not add a downloadable file or sandbox preparation to a self-contained preview request. Use inline preview only when the user explicitly asks to display inside the chat message or code block, or rejects a separate Artifact panel; respond with a complete HTML code block (wrap SVG inside it) without activation. Answer code snippets and explanations directly without loading this skill.',identifier: ArtifactsIdentifier,name: 'artifacts',source: 'builtin',diff --git a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.tsindex 9f21250027e..9be6e373f70 100644--- a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts@@ -59,11 +59,18 @@ export class CloudSandboxExecutionRuntime extends ComputerRuntime {if (!result.success) {return {content: formatSandboxRecreation(- result.error?.message || JSON.stringify(result.error),+ result.error?.message || 'Failed to execute code in sandbox',result.sessionExpiredAndRecreated,),+ // Execution may have completed before its response failed. Preserve+ // diagnostics without automatically replaying arbitrary code.+ error: {+ ...result.error,+ kind: 'stop',+ message: result.error?.message || 'Failed to execute code in sandbox',+ },state,- success: true,+ success: false,};}@@ -109,8 +116,14 @@ export class CloudSandboxExecutionRuntime extends ComputerRuntime {filename,success: false,}),+ // Upload or registration may already have succeeded before the error.+ error: {+ ...result.error,+ kind: 'stop',+ message: result.error?.message || 'Failed to export file from sandbox',+ },state,- success: true,+ success: false,};}diff --git a/packages/builtin-tool-cloud-sandbox/src/manifest.ts b/packages/builtin-tool-cloud-sandbox/src/manifest.tsindex b9891fc9aa4..5178886b358 100644--- a/packages/builtin-tool-cloud-sandbox/src/manifest.ts+++ b/packages/builtin-tool-cloud-sandbox/src/manifest.ts@@ -308,7 +308,8 @@ export const CloudSandboxManifest: BuiltinToolManifest = {identifier: CloudSandboxIdentifier,meta: {avatar: '💻',- description: 'Execute code, run commands, and manage files in a secure cloud environment',+ description:+ 'Run code for computation or validation, process files, and create downloadable files (HTML/SVG file export requires an explicit download request). For self-contained web pages, games, or SVG previews, use the artifacts skill when available; do not activate this tool to generate their code or add unrequested file preparation or validation. Answer code snippets and explanations directly without activation.',readme:'Execute Python, JavaScript, and TypeScript code in an isolated cloud environment. Run shell commands, manage files, search content with regex, and export results securely.',title: 'Cloud Sandbox',diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.tsindex f2da055c319..6d794cbfd74 100644--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts@@ -110,34 +110,35 @@ You have access to the following tools for interacting with the cloud sandbox:<workflow>+Use these tools only for actual execution or file operations. Having the sandbox activated does not require using it: self-contained previews and code explanations need no environment probe or placeholder call.1. Understand the user's request regarding code execution or file operations.2. Select the appropriate tool(s) for the task.3. Execute operations in the sandbox environment.4. Present results clearly, noting that files exist in the cloud sandbox.-5. **Export files by default** - see export_policy below for when to export vs skip.+5. **Export finalized file deliverables** according to export_policy. Execution or validation alone does not require a downloadable file.</workflow><export_policy>-**CRITICAL: Default Export Behavior**+**CRITICAL: Export Requested File Deliverables**-**Core Principle: Export by Default**-When code execution produces any output files (documents, images, data, etc.), you SHOULD automatically export them using \`exportFile\` unless the user explicitly indicates they don't need the file.+**Core Principle: Export Final Files Requested by the User**+When the user requests a file deliverable or download, export the finalized file using \`exportFile\`. Creating files for testing or preview preparation does not itself require export.-**When to Export (DEFAULT - most cases):**-- User asks to "create/make/generate/write/build" something+**When to Export:**+- User asks to create a downloadable file- User asks to "export/download/save" something- User asks to "convert/transform" files- User asks to "process/analyze" data and expects output files-- User asks to "draw/plot/visualize" something (export the chart/image)+- User asks for a static chart/image file (prefer Artifacts for supported interactive visualizations)- User provides data and expects a result file-- Any task that produces a meaningful output file the user would want-**Trigger Phrases that REQUIRE export:**-- English: "create", "make", "generate", "export", "download", "save", "convert", "help me [verb] a [file]", "I need/want a [file]"-- Chinese: "创建", "生成", "制作", "导出", "下载", "保存", "转换", "帮我做/写/画", "我要/需要一个"+**Interpret intent, not isolated keywords:**+- Words such as "create", "write", "visualize", "创建", or "帮我写" do not by themselves require export.+- Naming a format such as HTML or SVG does not by itself request a downloadable file.-**When NOT to Export (exceptions only):**+**When NOT to Export:**+- The deliverable is an Artifact preview or inline code snippet- User explicitly says "just run it" / "帮我跑一下" / "run this" / "execute only"- User says "don't export" / "不用导出" / "just check" / "只是看看"- User only asks to "read", "view", "check", or "debug" without expecting output files@@ -147,7 +148,7 @@ When code execution produces any output files (documents, images, data, etc.), y**Execution Pattern:**1. Execute the requested operation-2. If output files are produced → **call exportFile immediately**+2. When the requested file deliverable is finalized → **call exportFile**3. Present download links prominently in the response4. Confirm what was created and exported@@ -174,7 +175,7 @@ When code execution produces any output files (documents, images, data, etc.), y- For running shell commands: Use 'runCommand' to execute shell commands like \`pip install package\` or complex shell operations.- For background tasks: Set background: true in runCommand, then use getCommandOutput to check progress.- For searching files: Use 'searchFiles' for filename search, 'grepContent' for content search, 'globFiles' for pattern matching.-- For exporting files: Use 'exportFile' with the file path to generate a download URL for the user. **Export by default when any output files are produced - only skip when user explicitly asks to just run/check something.**+- For exporting files: Use 'exportFile' with the file path to generate a download URL for the user. **Export finalized file deliverables, not intermediate files or Artifact previews.**</tool_usage_guidelines>@@ -228,6 +229,7 @@ When generating PDFs with Chinese text, you MUST:<security_considerations>+- HTML and JavaScript are supported file content. A Forbidden response alone does not establish that either language is prohibited; it may originate from permissions or an upstream request filter. On FORBIDDEN or kind: stop, stop the affected sandbox workflow. Do NOT run permission or directory probes, switch tools or paths, or encode/split content to work around the refusal. Report the structured error and seek user or administrator resolution; do not diagnose the refusal with additional sandbox calls unless explicitly asked to investigate it.- This sandbox is isolated from the user's local system for security- Confirm with the user before performing destructive operations- Be cautious with shell commands that have significant side effectsdiff --git a/packages/builtin-tool-cloud-sandbox/src/types/service.ts b/packages/builtin-tool-cloud-sandbox/src/types/service.tsindex e45f1077aaa..6a2409f0387 100644--- a/packages/builtin-tool-cloud-sandbox/src/types/service.ts+++ b/packages/builtin-tool-cloud-sandbox/src/types/service.ts@@ -1,10 +1,12 @@+import type { ServiceResult } from '@lobechat/tool-runtime';+// ==================== Sandbox Service Interface ====================/*** Result of calling a sandbox tool*/export interface SandboxCallToolResult {- error?: { message: string; name?: string };+ error?: ServiceResult['error'];result: any;sessionExpiredAndRecreated?: boolean;success: boolean;@@ -14,7 +16,7 @@ export interface SandboxCallToolResult {* Result of exporting and uploading a file from sandbox*/export interface SandboxExportFileResult {- error?: { message: string; name?: string };+ error?: ServiceResult['error'];fileId?: string;filename: string;mimeType?: string;diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.tsindex 59836837cf6..1f712e8d254 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts@@ -34,6 +34,8 @@ export interface SkillImportServiceResult {}export interface ExportFileResult {+ /** Preserve upstream failures for the outer tool error classifier. */+ error?: unknown;fileId?: string;filename: string;mimeType?: string;@@ -254,6 +256,7 @@ export class SkillsExecutionRuntime {if (!result.success) {return {content: `Failed to export file: ${filename}`,+ error: result.error,success: false,};}@@ -530,6 +533,7 @@ export class SkillsExecutionRuntime {return {content: formatSandboxRecreation(content, result.sessionExpiredAndRecreated),+ error: result.error,state: {command,...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.tsindex 021e7f86731..87a08498891 100644--- a/packages/builtin-tool-skills/src/types.ts+++ b/packages/builtin-tool-skills/src/types.ts@@ -70,6 +70,8 @@ export interface RunCommandOptions {}export interface CommandResult {+ /** Upstream execution errors are distinct from a command's ordinary stderr. */+ error?: unknown;/*** Where the command actually ran. Flows into the tool call's plugin state so* execution-target degradation is observable in the product UI.diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.tsindex c19d711fd3d..e7225a69595 100644--- a/packages/tool-runtime/src/ComputerRuntime.ts+++ b/packages/tool-runtime/src/ComputerRuntime.ts@@ -70,7 +70,7 @@ export abstract class ComputerRuntime {const result = await this.callService('listLocalFiles', args);if (!result.success) {- return this.errorOutput(result, { files: [], totalCount: 0 });+ return this.errorOutput(result, { files: [], totalCount: 0 }, true);}const files = result.result?.files || [];@@ -91,7 +91,7 @@ export abstract class ComputerRuntime {return { content, state, success: true };} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}@@ -100,12 +100,16 @@ export abstract class ComputerRuntime {const result = await this.callService('readLocalFile', args);if (!result.success) {- return this.errorOutput(result, {- content: '',- endLine: args.endLine,- path: args.path,- startLine: args.startLine,- });+ return this.errorOutput(+ result,+ {+ content: '',+ endLine: args.endLine,+ path: args.path,+ startLine: args.startLine,+ },+ true,+ );}const r = result.result || {};@@ -163,7 +167,7 @@ export abstract class ComputerRuntime {return { content, state, success: true };} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}@@ -223,7 +227,7 @@ export abstract class ComputerRuntime {const result = await this.callService('searchLocalFiles', args);if (!result.success) {- return this.errorOutput(result, { results: [], totalCount: 0 });+ return this.errorOutput(result, { results: [], totalCount: 0 }, true);}const rawResults = result.result?.results || result.result;@@ -239,7 +243,7 @@ export abstract class ComputerRuntime {return { content, state, success: true };} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}@@ -389,11 +393,15 @@ export abstract class ComputerRuntime {: {};if (!result.success) {- const output = this.errorOutput(result, {- ...sessionState,- error: result.error?.message,- success: false,- });+ const output = this.errorOutput(+ result,+ {+ ...sessionState,+ error: result.error?.message,+ success: false,+ },+ true,+ );return {...output,content: formatSandboxRecreation(output.content, result.sessionExpiredAndRecreated),@@ -433,7 +441,7 @@ export abstract class ComputerRuntime {success: true,};} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}@@ -477,11 +485,15 @@ export abstract class ComputerRuntime {const result = await this.callService('grepContent', args);if (!result.success) {- return this.errorOutput(result, {- matches: [],- pattern: args.pattern,- totalMatches: 0,- });+ return this.errorOutput(+ result,+ {+ matches: [],+ pattern: args.pattern,+ totalMatches: 0,+ },+ true,+ );}const r = result.result || {};@@ -498,7 +510,7 @@ export abstract class ComputerRuntime {return { content, state, success: true };} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}@@ -514,11 +526,15 @@ export abstract class ComputerRuntime {});if (!result.success) {- return this.errorOutput(result, {- files: [],- pattern: args.pattern,- totalCount: 0,- });+ return this.errorOutput(+ result,+ {+ files: [],+ pattern: args.pattern,+ totalCount: 0,+ },+ true,+ );}const files = result.result?.files || [];@@ -534,18 +550,38 @@ export abstract class ComputerRuntime {return { content, state, success: true };} catch (error) {- return this.handleError(error);+ return this.handleError(error, true);}}// ==================== Helpers ====================- protected handleError(error: unknown): BuiltinServerRuntimeOutput {+ protected handleError(error: unknown, retrySafe = false): BuiltinServerRuntimeOutput {+ const diagnostics =+ error && typeof error === 'object' ? (error as ServiceResult['error']) : undefined;const errorMessage = error instanceof Error ? error.message : String(error);- return { content: errorMessage, error, success: false };+ // Side-effecting operations may complete before a transport error. Reads+ // can use the normal error classifier to retry a transient failure.+ return {+ content: errorMessage,+ error: {+ code: diagnostics?.code,+ doc_url: diagnostics?.doc_url,+ hint: diagnostics?.hint,+ kind: retrySafe ? undefined : 'stop',+ message: errorMessage,+ name: diagnostics?.name,+ status: diagnostics?.status,+ },+ success: false,+ };}- private errorOutput(result: ServiceResult, state: any): BuiltinServerRuntimeOutput {+ private errorOutput(+ result: ServiceResult,+ state: any,+ retrySafe = false,+ ): BuiltinServerRuntimeOutput {// Defensive fallback: when a service reports success: false without an// error object, JSON.stringify(undefined) returns the value `undefined`// (not the string "undefined"), which collapsed downstream into an empty@@ -582,16 +618,18 @@ export abstract class ComputerRuntime {// unset a failed edit had neither a diff nor an error to draw and// rendered as an empty card.//- // What the model sees is unchanged: `ToolMessageReorder` prefers a- // non-empty `content` over `pluginError.message`, and `content` still- // carries the same text.- //- // Deliberately a fresh `{ message }` rather than forwarding- // `result.error`: `executeToolWithRetry` escalates on- // `error.kind === 'retry'`, and these failures were never retried while- // they claimed success. Flipping the flag should not quietly enrol them- // in the retry loop.- error: { message: errorText },+ // Preserve service diagnostics for the common tool-result formatter.+ // Only read-only callers may use its retry classification; a service's+ // `kind: 'retry'` must not replay an operation with possible side effects.+ error: {+ code: result.error?.code,+ doc_url: result.error?.doc_url,+ hint: result.error?.hint,+ kind: retrySafe ? undefined : 'stop',+ message: errorText,+ name: result.error?.name,+ status: result.error?.status,+ },state,success: false,};diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.tsindex 25f62f52ff4..6a32ec9cd9a 100644--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts@@ -76,7 +76,7 @@ describe('LocalSystemExecutionRuntime.editFile', () => {});expect(output.success).toBe(false);- expect((output.error as { kind?: string }).kind).toBeUndefined();+ expect((output.error as { kind?: string }).kind).toBe('stop');});it('returns a formatted success result on a successful edit', async () => {diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.tsindex 7dbb0c46a9f..3d2ab525a05 100644--- a/packages/tool-runtime/src/types.ts+++ b/packages/tool-runtime/src/types.ts@@ -3,7 +3,14 @@* Each ComputerRuntime subclass maps its raw service response into this shape.*/export interface ServiceResult {- error?: { message: string; name?: string };+ error?: {+ code?: string;+ doc_url?: string;+ hint?: string;+ message: string;+ name?: string;+ status?: number;+ };result: any;/** The execution workspace was recreated before this call. */sessionExpiredAndRecreated?: boolean;