diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.ts index a0162bf9..6edd8bd6 100644 --- a/frontend/src/i18n/embed.ts +++ b/frontend/src/i18n/embed.ts @@ -335,10 +335,21 @@ const messages = { "queryKnowledgeGraph": "知识图谱查询", "readSkill": "读取技能", "executeSkillScript": "执行技能脚本", + "shellExec": "执行沙箱命令", "dataAnalysis": "数据分析", "dataSchema": "数据结构", "databaseQuery": "数据库查询" }, + "shellExec": { + "workDir": "目录", + "exitCode": "退出码", + "stdout": "标准输出", + "stderr": "标准错误", + "emptyOutput": "无输出", + "truncated": "输出已截断", + "killed": "已超时终止", + "binarySuppressed": "二进制输出已省略,请将文件写入产物目录后下载" + }, "summary": { "searchKb": "检索知识库 {count} 次", "thinking": "思考 {count} 次", @@ -432,7 +443,8 @@ const messages = { "queryUnderstanding": "正在理解问题...", "queryUnderstandDone": "已完成问题理解", "called": "调用 {name}", - "calledFailed": "调用 {name} 失败" + "calledFailed": "调用 {name} 失败", + "shellExecRunning": "正在执行沙箱命令..." }, "copy": { "emptyContent": "当前回答为空,无法复制", @@ -832,10 +844,21 @@ const messages = { "queryKnowledgeGraph": "Knowledge Graph Query", "readSkill": "Read Skill", "executeSkillScript": "Execute Skill Script", + "shellExec": "Run sandbox command", "dataAnalysis": "Data Analysis", "dataSchema": "Data Schema", "databaseQuery": "Database Query" }, + "shellExec": { + "workDir": "Directory", + "exitCode": "Exit code", + "stdout": "Stdout", + "stderr": "Stderr", + "emptyOutput": "No output", + "truncated": "Output truncated", + "killed": "Timed out", + "binarySuppressed": "Binary output omitted. Write files to the artifact directory to download them." + }, "summary": { "searchKb": "Searched knowledge base {count} time(s)", "thinking": "Thought {count} time(s)", @@ -929,7 +952,8 @@ const messages = { "queryUnderstanding": "Understanding query...", "queryUnderstandDone": "Query understood", "called": "Called {name}", - "calledFailed": "Failed to call {name}" + "calledFailed": "Failed to call {name}", + "shellExecRunning": "Running sandbox command..." }, "copy": { "emptyContent": "Current response is empty, cannot copy", diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index ee9f0d82..9a28be51 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -5156,10 +5156,21 @@ export default { queryKnowledgeGraph: 'Knowledge Graph Query', readSkill: 'Read Skill', executeSkillScript: 'Execute Skill Script', + shellExec: 'Run sandbox command', dataAnalysis: 'Data Analysis', dataSchema: 'Data Schema', databaseQuery: 'Database Query' }, + shellExec: { + workDir: 'Directory', + exitCode: 'Exit code', + stdout: 'Stdout', + stderr: 'Stderr', + emptyOutput: 'No output', + truncated: 'Output truncated', + killed: 'Timed out', + binarySuppressed: 'Binary output omitted. Write files to the artifact directory to download them.' + }, citation: { notFound: 'Content not found', loadFailed: 'Failed to load', @@ -5236,7 +5247,8 @@ export default { queryUnderstanding: 'Understanding query...', queryUnderstandDone: 'Query understood', called: 'Called {name}', - calledFailed: 'Failed to call {name}' + calledFailed: 'Failed to call {name}', + shellExecRunning: 'Running sandbox command...' }, copy: { emptyContent: 'Current response is empty, cannot copy', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 79f1b60f..94ba10d0 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1236,7 +1236,8 @@ export default { queryUnderstanding: '질문 이해 중...', queryUnderstandDone: '질문 이해 완료', called: '{name} 호출 완료', - calledFailed: '{name} 호출 실패' + calledFailed: '{name} 호출 실패', + shellExecRunning: '샌드박스 명령 실행 중...' }, ragPipeline: { searching: '지식베이스 검색 중...', @@ -1307,10 +1308,21 @@ export default { queryKnowledgeGraph: '지식 그래프 조회', readSkill: '스킬 읽기', executeSkillScript: '스킬 스크립트 실행', + shellExec: '샌드박스 명령 실행', dataAnalysis: '데이터 분석', dataSchema: '데이터 구조', databaseQuery: '데이터베이스 조회' }, + shellExec: { + workDir: '디렉터리', + exitCode: '종료 코드', + stdout: '표준 출력', + stderr: '표준 에러', + emptyOutput: '출력 없음', + truncated: '출력이 잘림', + killed: '시간 초과로 종료됨', + binarySuppressed: '바이너리 출력은 생략되었습니다. 파일은 산출물 디렉터리에 저장한 뒤 다운로드하세요.' + }, mcpOAuth: { waiting: '인증 대기 · {target}', waitingStatus: '인증 대기', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index c8741b21..39709d8f 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1236,7 +1236,8 @@ export default { queryUnderstanding: 'Анализ запроса...', queryUnderstandDone: 'Запрос понят', called: 'Вызван {name}', - calledFailed: 'Ошибка вызова {name}' + calledFailed: 'Ошибка вызова {name}', + shellExecRunning: 'Выполнение команды в песочнице...' }, ragPipeline: { searching: 'Поиск в базе знаний...', @@ -1307,10 +1308,21 @@ export default { queryKnowledgeGraph: 'Запрос графа знаний', readSkill: 'Чтение навыка', executeSkillScript: 'Выполнение скрипта навыка', + shellExec: 'Выполнение команды в песочнице', dataAnalysis: 'Анализ данных', dataSchema: 'Структура данных', databaseQuery: 'Запрос к базе данных' }, + shellExec: { + workDir: 'Каталог', + exitCode: 'Код выхода', + stdout: 'Stdout', + stderr: 'Stderr', + emptyOutput: 'Нет вывода', + truncated: 'Вывод обрезан', + killed: 'Прервано по таймауту', + binarySuppressed: 'Двоичный вывод опущен. Сохраните файлы в каталог артефактов и скачайте их.' + }, mcpOAuth: { waiting: 'Ожидание авторизации · {target}', waitingStatus: 'Ожидание авторизации', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index dc6024d8..59fc7fb0 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1238,7 +1238,8 @@ export default { queryUnderstanding: '正在理解问题...', queryUnderstandDone: '已完成问题理解', called: '调用 {name}', - calledFailed: '调用 {name} 失败' + calledFailed: '调用 {name} 失败', + shellExecRunning: '正在执行沙箱命令...' }, ragPipeline: { searching: '正在检索知识库...', @@ -1309,10 +1310,21 @@ export default { queryKnowledgeGraph: '知识图谱查询', readSkill: '读取技能', executeSkillScript: '执行技能脚本', + shellExec: '执行沙箱命令', dataAnalysis: '数据分析', dataSchema: '数据结构', databaseQuery: '数据库查询' }, + shellExec: { + workDir: '目录', + exitCode: '退出码', + stdout: '标准输出', + stderr: '标准错误', + emptyOutput: '无输出', + truncated: '输出已截断', + killed: '已超时终止', + binarySuppressed: '二进制输出已省略,请将文件写入产物目录后下载' + }, mcpOAuth: { waiting: '等待授权 · {target}', waitingStatus: '等待授权', diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.ts index 1614e1dd..7e58db6a 100644 --- a/frontend/src/types/tool-results.ts +++ b/frontend/src/types/tool-results.ts @@ -25,7 +25,8 @@ export type DisplayType = | 'wiki_write_page' | 'wiki_replace_text' | 'wiki_rename_page' - | 'wiki_delete_page'; + | 'wiki_delete_page' + | 'shell_exec'; // Search result item export interface SearchResultItem { @@ -321,6 +322,22 @@ export interface WikiDeletePageData { affected_pages?: string[]; } +export interface ShellExecData { + display_type: 'shell_exec'; + command?: string; + work_dir?: string; + exit_code?: number; + duration_ms?: number; + killed?: boolean; + truncated?: boolean; + stdout?: string; + stderr?: string; + stdout_binary?: boolean; + stderr_binary?: boolean; + stdout_truncated?: boolean; + stderr_truncated?: boolean; +} + // Union type for all wiki edit data export type WikiEditData = WikiWritePageData | WikiReplaceTextData | WikiRenamePageData | WikiDeletePageData; @@ -342,7 +359,8 @@ export type ToolResultData = | WikiWritePageData | WikiReplaceTextData | WikiRenamePageData - | WikiDeletePageData; + | WikiDeletePageData + | ShellExecData; // Action data (from index.vue) export interface ActionData { diff --git a/frontend/src/utils/agent-tool-display.test.mjs b/frontend/src/utils/agent-tool-display.test.mjs index 7e072c42..5ded83b9 100644 --- a/frontend/src/utils/agent-tool-display.test.mjs +++ b/frontend/src/utils/agent-tool-display.test.mjs @@ -26,6 +26,10 @@ test('getAgentToolIconName maps rag pipeline tools', () => { assert.equal(getAgentToolIconName('knowledge_search'), 'data-search') }) +test('getAgentToolIconName maps sandbox shell tools to the terminal icon', () => { + assert.equal(getAgentToolIconName('shell_exec'), 'terminal') +}) + test('getAgentToolIconName maps Wiki tools to semantic search and reading icons', () => { assert.equal(getAgentToolIconName('wiki_search'), 'search') assert.equal(getAgentToolIconName('wiki_read_page'), 'file-search') diff --git a/frontend/src/utils/agent-tool-icons.ts b/frontend/src/utils/agent-tool-icons.ts index d7760183..a7203e53 100644 --- a/frontend/src/utils/agent-tool-icons.ts +++ b/frontend/src/utils/agent-tool-icons.ts @@ -39,5 +39,11 @@ export function getAgentToolIconName( if (toolName.startsWith('mcp_')) { return 'terminal' } + if (toolName === 'shell_exec' || toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file') { + return 'terminal' + } + if (toolName === 'execute_skill_script') { + return 'code' + } return 'file-paste' } diff --git a/frontend/src/utils/shellExecResult.test.ts b/frontend/src/utils/shellExecResult.test.ts new file mode 100644 index 00000000..58062959 --- /dev/null +++ b/frontend/src/utils/shellExecResult.test.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { buildShellExecView, previewShellCommand } from './shellExecResult.ts' + +test('buildShellExecView prefers structured streams over markdown output', () => { + const view = buildShellExecView( + { command: 'ls', work_dir: '/workspace', exit_code: 0, stdout: 'a.txt\n', stderr: '' }, + { command: 'ignored' }, + '## Stdout\n\n```\nold\n```\n', + ) + assert.equal(view.command, 'ls') + assert.equal(view.workDir, '/workspace') + assert.equal(view.exitCode, 0) + assert.equal(view.stdout, 'a.txt\n') +}) + +test('buildShellExecView parses legacy markdown output when streams were stripped', () => { + const view = buildShellExecView( + { command: 'cat README.md', exit_code: 0 }, + null, + [ + '=== Shell Exec (session=abc) ===', + '', + '**Command**: `cat README.md`', + '**Work Dir**: /workspace', + '**Exit Code**: 0', + '', + '## Stdout', + '', + '```', + '# title', + '```', + '', + '## Stderr', + '', + '```', + 'warn', + '```', + '', + ].join('\n'), + ) + assert.equal(view.command, 'cat README.md') + assert.equal(view.stdout, '# title') + assert.equal(view.stderr, 'warn') +}) + +test('previewShellCommand collapses whitespace and truncates', () => { + assert.equal(previewShellCommand('ls -la'), 'ls -la') + assert.equal(previewShellCommand('abcdefghij', 8), 'abcdefg…') +}) diff --git a/frontend/src/utils/shellExecResult.ts b/frontend/src/utils/shellExecResult.ts new file mode 100644 index 00000000..07393730 --- /dev/null +++ b/frontend/src/utils/shellExecResult.ts @@ -0,0 +1,114 @@ +/** + * Helpers for rendering shell_exec tool cards. + * Live results carry stdout/stderr on tool_data; older turns only have the + * markdown Output blob that used to be shown as "raw output". + */ + +export type ShellExecView = { + command: string + workDir: string + exitCode: number | null + durationMs: number | null + killed: boolean + truncated: boolean + stdoutBinary: boolean + stderrBinary: boolean + stdout: string + stderr: string +} + +function asRecord(value: unknown): Record { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value as Record + } + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value) + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as Record + } + } catch { + return {} + } + } + return {} +} + +function asString(value: unknown): string { + return typeof value === 'string' ? value : value == null ? '' : String(value) +} + +function asNumber(value: unknown): number | null { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim()) { + const n = Number(value) + return Number.isFinite(n) ? n : null + } + return null +} + +function asBool(value: unknown): boolean { + return value === true || value === 'true' +} + +function extractFencedSection(output: string, heading: string): string { + const headingMatch = output.match(new RegExp(`##\\s+${heading}\\b[\\s\\S]*?\`\`\``, 'i')) + if (!headingMatch) return '' + const afterOpenFence = output.slice(output.indexOf(headingMatch[0]) + headingMatch[0].length) + const start = afterOpenFence.startsWith('\n') ? 1 : 0 + const end = afterOpenFence.indexOf('```', start) + const body = end >= 0 ? afterOpenFence.slice(start, end) : afterOpenFence.slice(start) + return body.replace(/^\n/, '').replace(/\n$/, '') +} + +function stripLegacyShellHeader(output: string): string { + return output + .replace(/^=== Shell Exec[\s\S]*?\n\n/, '') + .replace(/\*\*Command\*\*:[\s\S]*?(?:\n(?!\*\*)|$)/, '') + .replace(/\*\*Work Dir\*\*:.*\n/, '') + .replace(/\*\*Exit Code\*\*:.*\n/, '') + .replace(/\*\*Duration\*\*:.*\n/, '') + .replace(/\*\*Killed\*\*:.*\n/, '') + .replace(/\*\*Truncated\*\*:.*\n/, '') + .replace(/\*\*Binary Output Suppressed\*\*:.*\n/, '') + .trim() +} + +export function buildShellExecView( + data: Record | null | undefined, + args: unknown, + output?: string, +): ShellExecView { + const record = data || {} + const argumentsRecord = asRecord(args) + const rawOutput = asString(output) + const stdoutFromData = asString(record.stdout) + const stderrFromData = asString(record.stderr) + const parsedStdout = stdoutFromData ? '' : extractFencedSection(rawOutput, 'Stdout') + const parsedStderr = stderrFromData ? '' : extractFencedSection(rawOutput, 'Stderr') + + let stdout = stdoutFromData || parsedStdout + let stderr = stderrFromData || parsedStderr + if (!stdout && !stderr && rawOutput) { + stdout = stripLegacyShellHeader(rawOutput) + } + + return { + command: asString(record.command) || asString(argumentsRecord.command), + workDir: asString(record.work_dir) || asString(argumentsRecord.work_dir), + exitCode: asNumber(record.exit_code), + durationMs: asNumber(record.duration_ms), + killed: asBool(record.killed), + truncated: asBool(record.truncated) || asBool(record.stdout_truncated) || asBool(record.stderr_truncated), + stdoutBinary: asBool(record.stdout_binary), + stderrBinary: asBool(record.stderr_binary), + stdout, + stderr, + } +} + +export function previewShellCommand(command: string, max = 72): string { + const trimmed = command.replace(/\s+/g, ' ').trim() + if (trimmed.length <= max) return trimmed + return `${trimmed.slice(0, max - 1)}…` +} diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 913a8bbd..2724a6fc 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -178,10 +178,10 @@
-
-
- +
@@ -440,8 +440,8 @@
-
- +
@@ -559,6 +559,7 @@ import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess'; import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer'; import { getAgentToolIconName } from '@/utils/agent-tool-icons'; import { getQueryText, getWikiPageText } from '@/utils/agent-tool-display'; +import { previewShellCommand } from '@/utils/shellExecResult'; import { parseWikiToolReferences } from '@/utils/wikiToolReferences'; import { buildManualMarkdown, @@ -624,6 +625,7 @@ const TOOL_NAME_KEYS: Record = { query_knowledge_graph: 'agentStream.tools.queryKnowledgeGraph', read_skill: 'agentStream.tools.readSkill', execute_skill_script: 'agentStream.tools.executeSkillScript', + shell_exec: 'agentStream.tools.shellExec', data_analysis: 'agentStream.tools.dataAnalysis', data_schema: 'agentStream.tools.dataSchema', database_query: 'agentStream.tools.databaseQuery', @@ -1043,6 +1045,12 @@ const formatToolResultContent = (value: unknown): string => { const isMcpTool = (toolName?: string | null): boolean => String(toolName || '').startsWith('mcp_'); +const resolveToolDisplayType = (event: any): string | undefined => { + if (event?.display_type) return event.display_type + if (event?.tool_name === 'shell_exec') return 'shell_exec' + return undefined +}; + const WIKI_EDIT_TOOL_NAMES = new Set([ 'wiki_write_page', 'wiki_replace_text', @@ -2605,6 +2613,9 @@ const getToolTitle = (event: any): string => { if (event.tool_name === 'wiki_search' || event.tool_name === 'wiki_read_page') { return `${getLocalizedToolName(event.tool_name)}...`; } + if (event.tool_name === 'shell_exec') { + return t('agentStream.toolStatus.shellExecRunning'); + } const localizedName = getLocalizedToolName(event.tool_name); return t('agentStream.toolStatus.calling', { name: localizedName }); } @@ -2700,6 +2711,14 @@ const getToolTitle = (event: any): string => { return pageLabel ? `${baseTitle}:「${sanitizeForDisplay(pageLabel)}」` : baseTitle; } + if (toolName === 'shell_exec') { + const command = previewShellCommand( + String(event.tool_data?.command || event.arguments?.command || ''), + ) + const baseTitle = getToolDescription(event) + return command ? `${baseTitle}:${command}` : baseTitle + } + // Use tool summary if available const summary = getToolSummary(event); return summary || getToolDescription(event); @@ -2717,6 +2736,9 @@ const getToolDescription = (event: any): string => { if (event.tool_name === 'query_understand') { return t('agentStream.toolStatus.queryUnderstanding'); } + if (event.tool_name === 'shell_exec') { + return t('agentStream.toolStatus.shellExecRunning'); + } const localizedName = getLocalizedToolName(event.tool_name); return t('agentStream.toolStatus.calling', { name: localizedName }); } @@ -2747,6 +2769,9 @@ const getToolDescription = (event: any): string => { return success ? t('agentStream.toolStatus.attachmentParsingDone') : t('agentStream.toolStatus.attachmentParsingFailed'); } else if (toolName === 'query_understand') { return success ? t('agentStream.toolStatus.queryUnderstandDone') : t('agentStream.toolStatus.calledFailed', { name: getLocalizedToolName(toolName) }); + } else if (toolName === 'shell_exec') { + const localizedName = getLocalizedToolName(toolName); + return success ? localizedName : t('agentStream.toolStatus.calledFailed', { name: localizedName }); } else { const localizedName = getLocalizedToolName(toolName); return success ? t('agentStream.toolStatus.called', { name: localizedName }) : t('agentStream.toolStatus.calledFailed', { name: localizedName }); diff --git a/frontend/src/views/chat/components/ToolResultRenderer.vue b/frontend/src/views/chat/components/ToolResultRenderer.vue index 3c64818c..da08bb6e 100644 --- a/frontend/src/views/chat/components/ToolResultRenderer.vue +++ b/frontend/src/views/chat/components/ToolResultRenderer.vue @@ -46,6 +46,13 @@ v-else-if="displayType === 'wiki_write_page' || displayType === 'wiki_replace_text' || displayType === 'wiki_rename_page' || displayType === 'wiki_delete_page'" :data="toolData as WikiEditData" /> + +
@@ -75,7 +82,8 @@ import type { WebFetchResultsData, GrepResultsData, KnowledgeChunksListData, - WikiEditData + WikiEditData, + ShellExecData } from '@/types/tool-results'; import SearchResults from './tool-results/SearchResults.vue'; @@ -92,6 +100,7 @@ import WebFetchResults from './tool-results/WebFetchResults.vue'; import GrepResults from './tool-results/GrepResults.vue'; import KnowledgeChunksList from './tool-results/KnowledgeChunksList.vue'; import WikiEditResult from './tool-results/WikiEditResult.vue'; +import ShellExecResult from './tool-results/ShellExecResult.vue'; interface Props { displayType?: DisplayType; diff --git a/frontend/src/views/chat/components/tool-results/ShellExecResult.vue b/frontend/src/views/chat/components/tool-results/ShellExecResult.vue new file mode 100644 index 00000000..a70afe4d --- /dev/null +++ b/frontend/src/views/chat/components/tool-results/ShellExecResult.vue @@ -0,0 +1,177 @@ + + + + + diff --git a/internal/agent/tools/persist.go b/internal/agent/tools/persist.go index 5a6aec4f..c78a60c1 100644 --- a/internal/agent/tools/persist.go +++ b/internal/agent/tools/persist.go @@ -18,6 +18,14 @@ var persistStripFieldsByTool = map[string][]string{ ToolReadSandboxFile: {"stdout", "stderr", "content", "content_base64"}, } +// clientStripFieldsByTool is the lighter omit list for live SSE. The UI +// needs stdout/stderr to render a terminal card; those streams are already +// capped by the tool. Persist still uses persistStripFieldsByTool. +var clientStripFieldsByTool = map[string][]string{ + ToolShellExec: {"content", "content_base64"}, + ToolReadSandboxFile: {"content", "content_base64"}, +} + const historicalSandboxOutputChars = 4 * 1024 // ShouldOmitRawToolOutput reports whether the raw XML/text Output should be @@ -33,6 +41,18 @@ func ShouldOmitRawToolOutput(_ string, data map[string]interface{}) bool { // SanitizeToolDataForPersist returns a copy of tool Data safe for DB / SSE replay. func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) map[string]interface{} { + return sanitizeToolData(data, persistStripFieldsByTool[toolName]) +} + +func sanitizeToolDataForClient(toolName string, data map[string]interface{}) map[string]interface{} { + omit := clientStripFieldsByTool[toolName] + if omit == nil { + omit = persistStripFieldsByTool[toolName] + } + return sanitizeToolData(data, omit) +} + +func sanitizeToolData(data map[string]interface{}, extraOmit []string) map[string]interface{} { if data == nil { return nil } @@ -44,7 +64,7 @@ func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) ma for _, key := range persistStripFields[displayType] { delete(out, key) } - for _, key := range persistStripFieldsByTool[toolName] { + for _, key := range extraOmit { delete(out, key) } return out @@ -57,7 +77,7 @@ func SanitizeToolResultForClient(toolName string, result *types.ToolResult) map[ return meta } if result.Data != nil { - for k, v := range SanitizeToolDataForPersist(toolName, result.Data) { + for k, v := range sanitizeToolDataForClient(toolName, result.Data) { meta[k] = v } } @@ -185,6 +205,16 @@ func compactToolSummary(success bool, errMsg string, data map[string]interface{} if count > 0 { return fmt.Sprintf("Semantic search returned %d result(s) (details omitted from history)", count) } + case "shell_exec": + exit := intField(data, "exit_code") + cmd := stringField(data, "command") + if cmd != "" { + if len(cmd) > 80 { + cmd = cmd[:80] + "..." + } + return fmt.Sprintf("shell_exec exit=%d command=%s (output omitted from history)", exit, cmd) + } + return fmt.Sprintf("shell_exec exit=%d (output omitted from history)", exit) case "attachment_parsing": parsed := intField(data, "parsed_count") skipped := intField(data, "skipped_count") diff --git a/internal/agent/tools/persist_test.go b/internal/agent/tools/persist_test.go index f16ebf00..cb43d2ae 100644 --- a/internal/agent/tools/persist_test.go +++ b/internal/agent/tools/persist_test.go @@ -127,3 +127,29 @@ func TestSandboxToolPersistenceStripsDuplicatePayloadsAndCompactsHistory(t *test assert(len(CompactToolOutputForHistory(ToolShellExec, steps[0].ToolCalls[0].Result)) <= historicalSandboxOutputChars, "historical replay must independently cap legacy raw output") } + +func TestSanitizeToolResultForClientKeepsShellStreams(t *testing.T) { + meta := SanitizeToolResultForClient(ToolShellExec, &types.ToolResult{ + Success: true, + Output: "=== Shell Exec ===\n**Command**: `ls`\n", + Data: map[string]interface{}{ + "display_type": "shell_exec", + "command": "ls", + "exit_code": 0, + "stdout": "README.md\n", + "stderr": "", + }, + }) + if _, ok := meta["output"]; ok { + t.Fatal("structured shell_exec should omit the markdown Output from client metadata") + } + if meta["stdout"] != "README.md\n" { + t.Fatalf("live UI needs stdout, got %#v", meta["stdout"]) + } + if meta["command"] != "ls" { + t.Fatalf("command should remain, got %#v", meta["command"]) + } + if meta["display_type"] != "shell_exec" { + t.Fatalf("display_type should remain, got %#v", meta["display_type"]) + } +} diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go index c24ddb32..80fe95c4 100644 --- a/internal/agent/tools/shell_exec.go +++ b/internal/agent/tools/shell_exec.go @@ -431,6 +431,7 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ // only mark Success=false when a wire-level problem prevented the command // from running at all (already handled above via err != nil). resultData := map[string]interface{}{ + "display_type": "shell_exec", "session_id": sessionID, "command": command, "work_dir": workDir, diff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.go index dc4fd8a8..9dc7a51d 100644 --- a/internal/agent/tools/shell_exec_test.go +++ b/internal/agent/tools/shell_exec_test.go @@ -111,6 +111,7 @@ func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) { assert.Contains(t, result.Output, content) assert.NotContains(t, result.Output, "output truncated") assert.Equal(t, 32768, result.Data["max_output_bytes"]) + assert.Equal(t, "shell_exec", result.Data["display_type"]) } func TestShellExecOutputLimitIsHardCapped(t *testing.T) {