Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(agent): write workspace scripts and run them with installed skills
wizardchen21244d451a4a
diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yamlindex 015087dec..494234366 100644--- a/config/builtin_agents.yaml+++ b/config/builtin_agents.yaml@@ -70,7 +70,7 @@ builtin_agents:agent_type: "rag-qa"system_prompt: ""temperature: 0.7- max_completion_tokens: 2048+ max_completion_tokens: 32768max_iterations: 50kb_selection_mode: "all"retrieve_kb_only_when_mentioned: false@@ -118,7 +118,7 @@ builtin_agents:agent_type: "data-analysis"system_prompt_id: "data_analyst"temperature: 0.3- max_completion_tokens: 4096+ max_completion_tokens: 32768max_iterations: 30kb_selection_mode: "all"retrieve_kb_only_when_mentioned: false@@ -163,7 +163,7 @@ builtin_agents:agent_type: "wiki-qa"system_prompt_id: "wiki_researcher"temperature: 0.7- max_completion_tokens: 4096+ max_completion_tokens: 32768max_iterations: 30kb_selection_mode: "all"retrieve_kb_only_when_mentioned: false@@ -207,7 +207,7 @@ builtin_agents:agent_type: "custom"system_prompt_id: "wiki_fixer"temperature: 0.7- max_completion_tokens: 4096+ max_completion_tokens: 32768max_iterations: 30kb_selection_mode: "selected"retrieve_kb_only_when_mentioned: false@@ -257,7 +257,7 @@ builtin_agents:agent_type: "custom"system_prompt_id: "skill_installer"temperature: 0.2- max_completion_tokens: 4096+ max_completion_tokens: 32768max_iterations: 30kb_selection_mode: "none"retrieve_kb_only_when_mentioned: falsediff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yamlindex dc7af4ad9..6bdf87f1e 100644--- a/config/prompt_templates/agent_system_prompt.yaml+++ b/config/prompt_templates/agent_system_prompt.yaml@@ -514,15 +514,22 @@ templates:<workflow>1. Read the SKILL.md text in the user message and work out what has to be installed. Dependencies are often described in prose rather than a requirements file — read carefully.2. Inspect the skill directory with `ls -la` before installing, so you know which of requirements.txt / pyproject.toml / package.json actually exist.- 3. Install dependencies INTO THE SKILL DIRECTORY (see <isolation>).+ 3. Install dependencies INTO THE SKILL DIRECTORY (see <isolation>), including on-demand extras (see <on_demand_dependencies>).4. Verify by actually running the skill's entry point (for example `--help`). Do not declare success until a real command exits 0.5. Reply with a short summary: what you installed, where it went, and what you ran to verify.</workflow>+ <on_demand_dependencies>+ Many skills defer optional packages (python-docx, python-pptx, …) to a first-use script such as `scripts/install_deps.py --word`. That pattern does not work after this install: the skill tree is snapshotted read-only and `uv venv` often has no pip, so a later chat cannot `pip install` into the venv.+ - Install every extra NOW. Read SKILL.md, requirements extras, pyproject optional-dependencies, and any `install_deps.py` / whitelist of locked packages.+ - Run those installer scripts here with non-interactive flags covering every extra (`--yes`, `--all`, `--word --ppt`, …), or `uv pip install` the packages they name.+ - Do not leave "pip install when the user asks for Word" for session time.+ </on_demand_dependencies>+<isolation>This is the most important part. Every skill on this image shares one root filesystem, so anything you install globally is inherited by every other skill forever.- Python: create the skill's OWN virtual environment at `<skill-dir>/.venv` and install into it.- With uv: `uv venv <skill-dir>/.venv` then `uv pip install --python <skill-dir>/.venv/bin/python -r <skill-dir>/requirements.txt`+ With uv: `uv venv --seed <skill-dir>/.venv` then `uv pip install --python <skill-dir>/.venv/bin/python -r <skill-dir>/requirements.txt`Without uv: `python3 -m venv <skill-dir>/.venv` then `<skill-dir>/.venv/bin/pip install -r <skill-dir>/requirements.txt`- Node: install into `<skill-dir>/node_modules`, e.g. `pnpm install` with work_dir set to the skill directory.- Never `pip install` into the system Python. Never `pnpm add -g` / `npm i -g` unless there is no alternative.@@ -530,7 +537,8 @@ templates:</isolation><tool_guidelines>- * **shell_exec:** your only tool. You may set `work_dir` to the skill directory (it is allowed for this session) and then use relative paths, or leave `work_dir` unset and use absolute paths. Both work.+ * **shell_exec:** your only tool. `write_sandbox_file` / `edit_sandbox_file` / `list_sandbox_files` / `read_sandbox_file` are not registered. You may set `work_dir` to the skill directory (it is allowed for this session) and then use relative paths, or leave `work_dir` unset and use absolute paths. Both work.+ * Write `.weknora/requirements.json` with a short `mkdir -p .weknora && cat > .weknora/requirements.json <<'EOF'` redirect. Do not call `write_sandbox_file` — it only accepts `/workspace`, which is wiped before the snapshot.* Prefer one command per call so a failure is easy to attribute.* If a command fails, read the error and adapt — do not repeat the identical command.</tool_guidelines>diff --git a/docker/Dockerfile.sandbox b/docker/Dockerfile.sandboxindex 3150780e4..0c08898b2 100644--- a/docker/Dockerfile.sandbox+++ b/docker/Dockerfile.sandbox@@ -33,13 +33,15 @@ RUN ln -s /usr/local/bin/uv /usr/local/bin/uvxRUN npm install -g pnpm# Install minimal CLI tools (bash/grep/sed/coreutils/findutils already in slim-# image). curl is not optional: the sandbox connectivity check probes egress-# with it, and skills that fetch a URL expect it to be there. The compression-# tools are here because skill bundles and their assets arrive archived.+# image). `file` is not in slim; models reach for it after a script-type error.+# curl is not optional: the sandbox connectivity check probes egress with it,+# and skills that fetch a URL expect it to be there. The compression tools are+# here because skill bundles and their assets arrive archived.RUN apt-get update && apt-get install -y --no-install-recommends \jq \curl \ca-certificates \+ file \zip \unzip \bzip2 \diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.tsindex 09cc126f6..95a61b4ca 100644--- a/frontend/src/api/agent/index.ts+++ b/frontend/src/api/agent/index.ts@@ -44,7 +44,7 @@ export interface CustomAgentConfig {model_id?: string;rerank_model_id?: string; // ReRank 模型 IDtemperature?: number;- max_completion_tokens?: number; // 最大生成token数(普通模式)+ max_completion_tokens?: number; // 最大生成 token 数;智能推理 ReAct 轮次会抬到至少 32768,避免工具 JSON 被网关默认 4096 截断thinking?: boolean; // 是否启用思考模式(支持扩展思考的模型)citation_enabled?: boolean; // 是否在最终回答中输出知识库/网页来源引用(默认开启)diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.tsindex 3a6bf168a..3cd7cf3bd 100644--- a/frontend/src/i18n/embed.ts+++ b/frontend/src/i18n/embed.ts@@ -337,6 +337,8 @@ const messages = {"executeSkillScript": "执行技能脚本","listSandboxFiles": "列出沙箱文件","readSandboxFile": "读取沙箱文件",+ "writeSandboxFile": "写入沙箱文件",+ "editSandboxFile": "编辑沙箱文件","shellExec": "执行沙箱命令","dataAnalysis": "数据分析","dataSchema": "数据结构",@@ -350,7 +352,10 @@ const messages = {"sandboxFiles": {"found": "找到 {count} 个文件","empty": "暂无文件",- "truncated": "列表已截断"+ "truncated": "列表已截断",+ "wrote": "已写入",+ "edited": "已编辑",+ "replacements": "替换 {count} 处"},"shellExec": {"workDir": "目录",@@ -858,6 +863,8 @@ const messages = {"executeSkillScript": "Execute Skill Script","listSandboxFiles": "List sandbox files","readSandboxFile": "Read sandbox file",+ "writeSandboxFile": "Write sandbox file",+ "editSandboxFile": "Edit sandbox file","shellExec": "Run sandbox command","dataAnalysis": "Data Analysis","dataSchema": "Data Schema",@@ -871,7 +878,10 @@ const messages = {"sandboxFiles": {"found": "Found {count} file(s)","empty": "No files",- "truncated": "List truncated"+ "truncated": "List truncated",+ "wrote": "Wrote",+ "edited": "Edited",+ "replacements": "Replaced {count}"},"shellExec": {"workDir": "Directory",diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex cfc2b751a..caedfe4c1 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -5332,6 +5332,8 @@ export default {executeSkillScript: 'Execute Skill Script',listSandboxFiles: 'List sandbox files',readSandboxFile: 'Read sandbox file',+ writeSandboxFile: 'Write sandbox file',+ editSandboxFile: 'Edit sandbox file',shellExec: 'Run sandbox command',dataAnalysis: 'Data Analysis',dataSchema: 'Data Schema',@@ -5345,7 +5347,10 @@ export default {sandboxFiles: {found: 'Found {count} file(s)',empty: 'No files',- truncated: 'List truncated'+ truncated: 'List truncated',+ wrote: 'Wrote',+ edited: 'Edited',+ replacements: 'Replaced {count}'},shellExec: {workDir: 'Directory',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex b94ecab31..5cd901cb1 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -1310,6 +1310,8 @@ export default {executeSkillScript: '스킬 스크립트 실행',listSandboxFiles: '샌드박스 파일 목록',readSandboxFile: '샌드박스 파일 읽기',+ writeSandboxFile: '샌드박스 파일 쓰기',+ editSandboxFile: '샌드박스 파일 편집',shellExec: '샌드박스 명령 실행',dataAnalysis: '데이터 분석',dataSchema: '데이터 구조',@@ -1323,7 +1325,10 @@ export default {sandboxFiles: {found: '파일 {count}개 발견',empty: '파일 없음',- truncated: '목록이 잘림'+ truncated: '목록이 잘림',+ wrote: '씀',+ edited: '편집함',+ replacements: '{count}곳 치환'},shellExec: {workDir: '디렉터리',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 8866bbff4..b94e68de7 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -1310,6 +1310,8 @@ export default {executeSkillScript: 'Выполнение скрипта навыка',listSandboxFiles: 'Список файлов песочницы',readSandboxFile: 'Чтение файла песочницы',+ writeSandboxFile: 'Запись файла песочницы',+ editSandboxFile: 'Правка файла песочницы',shellExec: 'Выполнение команды в песочнице',dataAnalysis: 'Анализ данных',dataSchema: 'Структура данных',@@ -1323,7 +1325,10 @@ export default {sandboxFiles: {found: 'Найдено файлов: {count}',empty: 'Нет файлов',- truncated: 'Список обрезан'+ truncated: 'Список обрезан',+ wrote: 'Записано',+ edited: 'Изменено',+ replacements: 'Замен: {count}'},shellExec: {workDir: 'Каталог',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex f77a819ab..01bbc5926 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -1312,6 +1312,8 @@ export default {executeSkillScript: '执行技能脚本',listSandboxFiles: '列出沙箱文件',readSandboxFile: '读取沙箱文件',+ writeSandboxFile: '写入沙箱文件',+ editSandboxFile: '编辑沙箱文件',shellExec: '执行沙箱命令',dataAnalysis: '数据分析',dataSchema: '数据结构',@@ -1325,7 +1327,10 @@ export default {sandboxFiles: {found: '找到 {count} 个文件',empty: '暂无文件',- truncated: '列表已截断'+ truncated: '列表已截断',+ wrote: '已写入',+ edited: '已编辑',+ replacements: '替换 {count} 处'},shellExec: {workDir: '目录',diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.tsindex 74316d965..f1cdc455f 100644--- a/frontend/src/types/tool-results.ts+++ b/frontend/src/types/tool-results.ts@@ -28,6 +28,8 @@ export type DisplayType =| 'wiki_delete_page'| 'shell_exec'| 'list_sandbox_files'+ | 'write_sandbox_file'+ | 'edit_sandbox_file'| 'read_skill';// Search result item@@ -357,6 +359,16 @@ export interface ListSandboxFilesData {truncated?: boolean;}+export interface WriteSandboxFileData {+ display_type?: 'write_sandbox_file' | 'edit_sandbox_file';+ session_id?: string;+ path?: string;+ root?: string;+ name?: string;+ size?: number;+ replacements?: number;+}+export interface ReadSkillData {display_type?: 'read_skill';skill_name?: string;diff --git a/frontend/src/utils/agent-tool-icons.ts b/frontend/src/utils/agent-tool-icons.tsindex 7fee1e20e..260b52d18 100644--- a/frontend/src/utils/agent-tool-icons.ts+++ b/frontend/src/utils/agent-tool-icons.ts@@ -48,6 +48,9 @@ export function getAgentToolIconName(if (toolName === 'read_sandbox_file' || toolName === 'read_skill') {return 'file'}+ if (toolName === 'write_sandbox_file' || toolName === 'edit_sandbox_file') {+ return 'edit'+ }if (toolName === 'execute_skill_script') {return 'code'}diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs b/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjsindex aeb0c5cd4..ddb85de20 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs+++ b/frontend/src/views/chat/components/AgentStreamDisplay.style.test.mjs@@ -61,6 +61,8 @@ test('tool rows use line icon names instead of legacy asset masks', () => {assert.match(source, /wiki_read_source_doc: 'agentStream\.tools\.wikiReadSourceDoc'/)assert.match(source, /list_sandbox_files: 'agentStream\.tools\.listSandboxFiles'/)assert.match(source, /read_sandbox_file: 'agentStream\.tools\.readSandboxFile'/)+ assert.match(source, /write_sandbox_file: 'agentStream\.tools\.writeSandboxFile'/)+ assert.match(source, /edit_sandbox_file: 'agentStream\.tools\.editSandboxFile'/)assert.match(source, /getReadSkillTarget/)assert.match(source, /tool_name === 'list_sandbox_files'/)assert.match(source, /toolName === 'get_document_content' \|\| toolName === 'wiki_read_source_doc'/)diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex 18cd03811..79f7f7266 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -640,6 +640,8 @@ const TOOL_NAME_KEYS: Record<string, string> = {execute_skill_script: 'agentStream.tools.executeSkillScript',list_sandbox_files: 'agentStream.tools.listSandboxFiles',read_sandbox_file: 'agentStream.tools.readSandboxFile',+ write_sandbox_file: 'agentStream.tools.writeSandboxFile',+ edit_sandbox_file: 'agentStream.tools.editSandboxFile',shell_exec: 'agentStream.tools.shellExec',data_analysis: 'agentStream.tools.dataAnalysis',data_schema: 'agentStream.tools.dataSchema',@@ -1086,6 +1088,12 @@ const resolveToolDisplayType = (event: any): DisplayType | undefined => {if (event?.tool_name === 'list_sandbox_files' && event?.success !== false) {return 'list_sandbox_files'}+ if (event?.tool_name === 'write_sandbox_file' && event?.success !== false) {+ return 'write_sandbox_file'+ }+ if (event?.tool_name === 'edit_sandbox_file' && event?.success !== false) {+ return 'edit_sandbox_file'+ }if (event?.tool_name === 'read_skill' && event?.success !== false) {return 'read_skill'}@@ -2701,7 +2709,7 @@ const getToolTitle = (event: any): string => {const name = getLocalizedToolName(event.tool_name);return `${formatToolTitleWithDetail(name, getEventSkillName(event))}...`;}- if (event.tool_name === 'list_sandbox_files' || event.tool_name === 'read_sandbox_file') {+ if (event.tool_name === 'list_sandbox_files' || event.tool_name === 'read_sandbox_file' || event.tool_name === 'write_sandbox_file' || event.tool_name === 'edit_sandbox_file') {const name = getLocalizedToolName(event.tool_name);return `${formatToolTitleWithDetail(name, getSandboxToolPath(event))}...`;}@@ -2807,7 +2815,7 @@ const getToolTitle = (event: any): string => {return formatToolTitleWithDetail(getToolDescription(event), getReadSkillTarget(event));}- if (toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file') {+ if (toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file' || toolName === 'write_sandbox_file' || toolName === 'edit_sandbox_file') {return formatToolTitleWithDetail(getToolDescription(event), getSandboxToolPath(event));}@@ -2862,7 +2870,7 @@ const getToolDescription = (event: any): string => {const name = getLocalizedToolName(event.tool_name);return `${formatToolTitleWithDetail(name, getEventSkillName(event))}...`;}- if (event.tool_name === 'list_sandbox_files' || event.tool_name === 'read_sandbox_file') {+ if (event.tool_name === 'list_sandbox_files' || event.tool_name === 'read_sandbox_file' || event.tool_name === 'write_sandbox_file' || event.tool_name === 'edit_sandbox_file') {const name = getLocalizedToolName(event.tool_name);return `${formatToolTitleWithDetail(name, getSandboxToolPath(event))}...`;}@@ -2899,7 +2907,7 @@ 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' || toolName === 'execute_skill_script' || toolName === 'read_skill' || toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file') {+ } else if (toolName === 'shell_exec' || toolName === 'execute_skill_script' || toolName === 'read_skill' || toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file' || toolName === 'write_sandbox_file' || toolName === 'edit_sandbox_file') {const localizedName = getLocalizedToolName(toolName);return success ? localizedName : t('agentStream.toolStatus.calledFailed', { name: localizedName });} else {diff --git a/frontend/src/views/chat/components/ToolResultRenderer.vue b/frontend/src/views/chat/components/ToolResultRenderer.vueindex 8f7b0e2ae..142abf9b0 100644--- a/frontend/src/views/chat/components/ToolResultRenderer.vue+++ b/frontend/src/views/chat/components/ToolResultRenderer.vue@@ -58,6 +58,11 @@:data="toolData as ListSandboxFilesData"/>+ <WriteSandboxFileResult+ v-else-if="displayType === 'write_sandbox_file' || displayType === 'edit_sandbox_file'"+ :data="toolData as WriteSandboxFileData"+ />+<ReadSkillResultv-else-if="displayType === 'read_skill'":data="toolData as ReadSkillData"@@ -95,6 +100,7 @@ import type {WikiEditData,ShellExecData,ListSandboxFilesData,+ WriteSandboxFileData,ReadSkillData} from '@/types/tool-results';@@ -114,6 +120,7 @@ import KnowledgeChunksList from './tool-results/KnowledgeChunksList.vue';import WikiEditResult from './tool-results/WikiEditResult.vue';import ShellExecResult from './tool-results/ShellExecResult.vue';import SandboxFilesResult from './tool-results/SandboxFilesResult.vue';+import WriteSandboxFileResult from './tool-results/WriteSandboxFileResult.vue';import ReadSkillResult from './tool-results/ReadSkillResult.vue';interface Props {diff --git a/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue b/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vuenew file mode 100644index 000000000..c0cbc4e02--- /dev/null+++ b/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue@@ -0,0 +1,62 @@+<template>+ <div class="sandbox-files-result">+ <ResultRow+ :index="1"+ :title="title"+ :meta="meta"+ :popup-key="path"+ :show-popup="false"+ />+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { formatFileSize } from '@/utils/files'+import type { WriteSandboxFileData } from '@/types/tool-results'+import ResultRow from './ResultRow.vue'++const props = defineProps<{+ data: WriteSandboxFileData | Record<string, unknown>+}>()++const { t } = useI18n()++const record = computed(() => (props.data || {}) as Record<string, unknown>)++const path = computed(() => String(record.value.path || ''))++const title = computed(() => {+ const name = String(record.value.name || '').trim()+ if (name) return name+ const parts = path.value.split('/').filter(Boolean)+ const isEdit = record.value.display_type === 'edit_sandbox_file'+ return parts[parts.length - 1] || path.value || t(isEdit ? 'agentStream.sandboxFiles.edited' : 'agentStream.sandboxFiles.wrote')+})++const meta = computed(() => {+ const size = record.value.size+ const replacements = record.value.replacements+ const isEdit = record.value.display_type === 'edit_sandbox_file' || typeof replacements === 'number'+ const parts = [t(isEdit ? 'agentStream.sandboxFiles.edited' : 'agentStream.sandboxFiles.wrote')]+ if (isEdit && typeof replacements === 'number' && Number.isFinite(replacements)) {+ parts.push(t('agentStream.sandboxFiles.replacements', { count: replacements }))+ }+ if (typeof size === 'number' && Number.isFinite(size) && size >= 0) {+ parts.push(size === 0 ? '0 B' : formatFileSize(size))+ }+ if (path.value) parts.push(path.value)+ return parts.join(' · ')+})+</script>++<style lang="less" scoped>+@import './tool-results.less';++.sandbox-files-result {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+</style>diff --git a/internal/agent/act.go b/internal/agent/act.goindex 765a70a82..0072ff1f0 100644--- a/internal/agent/act.go+++ b/internal/agent/act.go@@ -6,6 +6,7 @@ import ("errors""fmt""sort"+ "strings""sync""time"@@ -180,6 +181,8 @@ var toolDisplayNames = map[string]string{agenttools.ToolReadSkill: "读取技能",agenttools.ToolListSandboxFiles: "列出沙箱文件",agenttools.ToolReadSandboxFile: "读取沙箱文件",+ agenttools.ToolWriteSandboxFile: "写入沙箱文件",+ agenttools.ToolEditSandboxFile: "编辑沙箱文件",agenttools.ToolShellExec: "执行沙箱命令",}@@ -235,6 +238,32 @@ func (e *AgentEngine) executeToolCalls(for i, tc := range response.ToolCalls {e.executeSingleToolCall(ctx, tc, i, step, iteration, round, sessionID, assistantMessageID)}+ annotateLengthTruncatedToolErrors(response.FinishReason, step.ToolCalls)+}++// truncatedOutputHint explains a failed tool call that the provider cut off at+// the completion-token cap. It stays tool-neutral: any tool can be the one that+// got truncated, and naming another tool's fields would send the model chasing+// arguments the failing call does not have.+const truncatedOutputHint = "\n\nThe previous model output was cut off at the completion-token limit " ++ "(finish_reason=length), so these arguments are incomplete rather than wrong. " ++ "Retry with a complete JSON object and a smaller payload."++// annotateLengthTruncatedToolErrors appends that explanation to every failed+// result in the round. Results carry a pointer, so mutating through the slice+// reaches the caller's tool calls.+func annotateLengthTruncatedToolErrors(finishReason string, toolCalls []types.ToolCall) {+ if !isLengthFinishReason(finishReason) {+ return+ }+ for i := range toolCalls {+ result := toolCalls[i].Result+ if result == nil || result.Success ||+ strings.Contains(result.Error, "finish_reason=length") {+ continue+ }+ result.Error += truncatedOutputHint+ }}// executeToolCallsParallel runs all tool calls concurrently using errgroup,@@ -263,6 +292,7 @@ func (e *AgentEngine) executeToolCallsParallel(}_ = g.Wait()+ annotateLengthTruncatedToolErrors(response.FinishReason, results)// Append results and emit events in original orderfor _, toolCall := range results {@@ -377,7 +407,9 @@ func (e *AgentEngine) runToolCall(Success: false,Error: fmt.Sprintf("Failed to parse tool arguments: %v", err,- ) + "\n\n[Analyze the error above and try a different approach.]",+ ) + "\n\nIf the JSON looks cut off, the previous round likely hit the output token cap. " ++ "Retry with complete JSON (required fields first) and a smaller payload.\n\n" ++ "[Analyze the error above and try a different approach.]",},}}diff --git a/internal/agent/const.go b/internal/agent/const.goindex b865131c2..47311da3c 100644--- a/internal/agent/const.go+++ b/internal/agent/const.go@@ -5,6 +5,7 @@ import ("strings""time"+ "github.com/Tencent/WeKnora/internal/types""github.com/google/uuid")@@ -83,6 +84,17 @@ func (e *AgentEngine) getLLMCallTimeout() time.Duration {return defaultLLMCallTimeout}+// getCompletionTokenBudget is the max_tokens / max_completion_tokens sent on+// each ReAct LLM round. Leaving it unset lets providers default to 4096 and+// truncate write_sandbox_file (and similar) tool-call JSON.+func (e *AgentEngine) getCompletionTokenBudget() int {+ configured := 0+ if e.config != nil {+ configured = e.config.MaxCompletionTokens+ }+ return types.AgentRoundMaxCompletionTokens(configured)+}+// generateEventID generates a unique event ID with type suffix for better traceabilityfunc generateEventID(suffix string) string {return fmt.Sprintf("%s-%s", uuid.New().String()[:8], suffix)diff --git a/internal/agent/engine_test.go b/internal/agent/engine_test.goindex 20869d034..e2fd0bf57 100644--- a/internal/agent/engine_test.go+++ b/internal/agent/engine_test.go@@ -42,13 +42,14 @@ type mockChat struct {mu sync.Mutexresponses []mockResponsecalls [][]chat.Message+ opts []*chat.ChatOptionscallCount int}func (m *mockChat) ChatStream(_ context.Context,messages []chat.Message,- _ *chat.ChatOptions,+ opts *chat.ChatOptions,) (<-chan types.StreamResponse, error) {m.mu.Lock()defer m.mu.Unlock()@@ -57,6 +58,7 @@ func (m *mockChat) ChatStream(}resp := m.responses[m.callCount]m.calls = append(m.calls, append([]chat.Message(nil), messages...))+ m.opts = append(m.opts, opts)m.callCount++ch := make(chan types.StreamResponse, len(resp.chunks))@@ -244,6 +246,12 @@ func withCitationsEnabled(enabled bool) testEngineOption {}}+func withMaxCompletionTokens(n int) testEngineOption {+ return func(cfg *types.AgentConfig) {+ cfg.MaxCompletionTokens = n+ }+}+func TestBuildSystemPromptUsesInternalCitationSetting(t *testing.T) {model := &mockChat{}enabledEngine := newTestEngine(t, model)@@ -411,6 +419,53 @@ func TestStreamThinkingToEventBus_PropagatesFinishReason(t *testing.T) {}}+func TestStreamThinkingToEventBus_SetsCompletionTokenBudget(t *testing.T) {+ t.Run("honors an explicit 4096 budget", func(t *testing.T) {+ mock := &mockChat{+ responses: []mockResponse{+ {chunks: []types.StreamResponse{{Content: "ok", Done: true, FinishReason: "stop"}}},+ },+ }+ engine := newTestEngine(t, mock, withMaxCompletionTokens(4096))+ _, err := engine.streamThinkingToEventBus(context.Background(),+ []chat.Message{{Role: "user", Content: "test"}}, nil, 0, "sess-1")+ require.NoError(t, err)+ require.Len(t, mock.opts, 1)+ assert.Equal(t, 4096, mock.opts[0].MaxTokens)+ assert.Equal(t, 4096, mock.opts[0].MaxCompletionTokens)+ })++ t.Run("defaults when unset", func(t *testing.T) {+ mock := &mockChat{+ responses: []mockResponse{+ {chunks: []types.StreamResponse{{Content: "ok", Done: true, FinishReason: "stop"}}},+ },+ }+ engine := newTestEngine(t, mock)+ _, err := engine.streamThinkingToEventBus(context.Background(),+ []chat.Message{{Role: "user", Content: "test"}}, nil, 0, "sess-1")+ require.NoError(t, err)+ require.Len(t, mock.opts, 1)+ assert.Equal(t, types.DefaultAgentMaxCompletionTokens, mock.opts[0].MaxTokens)+ assert.Equal(t, types.DefaultAgentMaxCompletionTokens, mock.opts[0].MaxCompletionTokens)+ })++ t.Run("preserves explicit higher budget", func(t *testing.T) {+ mock := &mockChat{+ responses: []mockResponse{+ {chunks: []types.StreamResponse{{Content: "ok", Done: true, FinishReason: "stop"}}},+ },+ }+ engine := newTestEngine(t, mock, withMaxCompletionTokens(64000))+ _, err := engine.streamThinkingToEventBus(context.Background(),+ []chat.Message{{Role: "user", Content: "test"}}, nil, 0, "sess-1")+ require.NoError(t, err)+ require.Len(t, mock.opts, 1)+ assert.Equal(t, 64000, mock.opts[0].MaxTokens)+ assert.Equal(t, 64000, mock.opts[0].MaxCompletionTokens)+ })+}+// TestStreamThinkingToEventBus_RoutesReasoningAndAnswerSeparately is the// regression guard for the "answer first shows under Thinking, then jumps to// the answer area" UX bug. A natural-stop response that carries reasoning indiff --git a/internal/agent/finalize.go b/internal/agent/finalize.goindex d33d70b1a..498e55194 100644--- a/internal/agent/finalize.go+++ b/internal/agent/finalize.go@@ -97,10 +97,15 @@ Now generate the final answer:`, query, imageRequirement)logger.Debugf(ctx, "[Agent][FinalAnswer] AnswerID: %s", answerID)answerDoneEmitted := false+ budget := e.getCompletionTokenBudget()llmResult, err := e.streamLLMToEventBus(ctx,messages,- &chat.ChatOptions{Temperature: e.config.Temperature}, // Thinking disabled for final answer synthesis+ &chat.ChatOptions{+ Temperature: e.config.Temperature,+ MaxTokens: budget,+ MaxCompletionTokens: budget,+ }, // Thinking disabled for final answer synthesisfunc(chunk *types.StreamResponse, fullContent string) {// Defensive filter: only emit answer content, skip thinking chunksif chunk.ResponseType == types.ResponseTypeThinking {diff --git a/internal/agent/observe.go b/internal/agent/observe.goindex da829f121..289406174 100644--- a/internal/agent/observe.go+++ b/internal/agent/observe.go@@ -200,6 +200,18 @@ func isNaturalStopFinishReason(reason string) bool {}}+// isLengthFinishReason reports whether the provider stopped because the+// completion-token cap was hit. Truncated tool-call JSON then fails+// validation (missing path, unexpected end of JSON, etc.).+func isLengthFinishReason(reason string) bool {+ switch strings.ToLower(strings.TrimSpace(reason)) {+ case "length", "max_tokens", "max_output_tokens":+ return true+ default:+ return false+ }+}+// analyzeResponse inspects the LLM response for stop conditions:// - natural finish reason with no tool calls → agent is done (natural stop)// - finish_reason == "content_filter" with no tool calls → agent is done (content filtered)diff --git a/internal/agent/observe_test.go b/internal/agent/observe_test.goindex 405e64f79..e92035803 100644--- a/internal/agent/observe_test.go+++ b/internal/agent/observe_test.go@@ -390,3 +390,36 @@ func TestBuildMustUseBlock_SanitizesNamesIntoSingleLine(t *testing.T) {// The injected newline must be neutralized so it cannot forge a new line.assert.NotContains(t, block, "evil\nMust call")}++func TestIsLengthFinishReason(t *testing.T) {+ assert.True(t, isLengthFinishReason("length"))+ assert.True(t, isLengthFinishReason("max_tokens"))+ assert.True(t, isLengthFinishReason("MAX_OUTPUT_TOKENS"))+ assert.False(t, isLengthFinishReason("stop"))+ assert.False(t, isLengthFinishReason("tool_calls"))+}++func TestAnnotateLengthTruncatedToolErrors(t *testing.T) {+ step := &types.AgentStep{+ ToolCalls: []types.ToolCall{+ {Name: "write_sandbox_file", Result: &types.ToolResult{Success: false, Error: "required parameter 'path' is missing"}},+ {Name: "ok", Result: &types.ToolResult{Success: true, Output: "wrote"}},+ },+ }+ annotateLengthTruncatedToolErrors("length", step.ToolCalls)+ assert.Contains(t, step.ToolCalls[0].Result.Error, "finish_reason=length")+ assert.Contains(t, step.ToolCalls[0].Result.Error, "smaller payload")+ assert.NotContains(t, step.ToolCalls[0].Result.Error, "`path`")+ assert.Equal(t, "wrote", step.ToolCalls[1].Result.Output)++ annotateLengthTruncatedToolErrors("length", step.ToolCalls)+ assert.Equal(t, 1, strings.Count(step.ToolCalls[0].Result.Error, "finish_reason=length"))++ okStep := &types.AgentStep{+ ToolCalls: []types.ToolCall{+ {Result: &types.ToolResult{Success: false, Error: "nope"}},+ },+ }+ annotateLengthTruncatedToolErrors("stop", okStep.ToolCalls)+ assert.Equal(t, "nope", okStep.ToolCalls[0].Result.Error)+}diff --git a/internal/agent/prompts.go b/internal/agent/prompts.goindex 72f173ee9..80d158d35 100644--- a/internal/agent/prompts.go+++ b/internal/agent/prompts.go@@ -254,21 +254,30 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata, shellExecEnabl}builder.WriteString("#### Tool Reference\n\n")- builder.WriteString("- `read_skill(skill_name)`: Load full skill instructions (MUST call before using a skill)\n")- builder.WriteString("- `execute_skill_script(skill_name, script_path, args, input)`: Run utility scripts bundled with a skill\n")+ builder.WriteString("- `read_skill(skill_name)`: Load SKILL.md **and** list the skill's files. This is how you discover scripts — do not `list_sandbox_files` or `ls` `/opt/weknora/tenant/skills/...`\n")+ builder.WriteString("- `read_skill(skill_name, file_path)`: Read one file inside the skill (`file_path` is relative, e.g. `scripts/generate_ppt.py`)\n")+ builder.WriteString("- `execute_skill_script(skill_name, script_path, args, input)`: Run a skill script with that skill's interpreter and packages\n")+ builder.WriteString(" - `script_path`: relative inside the skill (`scripts/foo.py`), or an absolute `/workspace/...` file from `write_sandbox_file` / `edit_sandbox_file` (not `/workspace/input`)\n")builder.WriteString(" - `input`: Pass data directly via stdin (use this when you have data in memory, e.g. JSON string)\n")builder.WriteString(" - `args`: Command-line arguments; pass absolute `/workspace/input/...` paths from `<sandbox_attachments>` for user-uploaded files\n")builder.WriteString(" - Treat `/workspace/input` as read-only and write generated files only to `$WEKNORA_SKILL_OUTPUT_DIR`\n")builder.WriteString(sandboxArtifactReferenceGuidance())builder.WriteString(" - Each skill keeps its dependencies to itself (virtualenv or node_modules); ")builder.WriteString("this tool already runs scripts the right way. A bare `python3 -c` / `node -e` ")- builder.WriteString("sees none of them, so never conclude from that that a skill cannot run, and ")- builder.WriteString("never reinstall a skill's dependencies — they would live in this session only\n")+ builder.WriteString("sees none of them, so never conclude from that that a skill cannot run. ")+ builder.WriteString("The skill tree is frozen after install — do not run install_deps.py, ")+ builder.WriteString("chown, ensurepip, or pip into `/opt/weknora/tenant/skills`. ")+ builder.WriteString("On-demand extras: `python3 -m pip install --target /workspace/.skill-packages/<skill> <package>`, ")+ builder.WriteString("then execute_skill_script; or ask the user to reinstall the skill so extras are baked in\n")if shellExecEnabled {builder.WriteString("- `shell_exec(command, work_dir, timeout_sec, max_output_bytes, max_stderr_bytes, env)`: Freely execute shell commands and explore the current session's isolated Cube sandbox\n")builder.WriteString(" - User-uploaded files are restored under `/workspace/input` and listed in `<sandbox_attachments>`\n")- builder.WriteString(" - Use `find` and `file` to discover files and types; use `cat`, `head`, `tail`, and `sed` to inspect text; use `grep` and `awk` to search and process content\n")+ builder.WriteString(" - Use `find` and `ls` to discover files; use `cat`, `head`, `tail`, and `sed` to inspect text; use `grep` and `awk` to search and process content; use `file` for an unknown type\n")+ builder.WriteString(" - Do not `ls` / `find` / `cat` / `file` a skill under `/opt/weknora/tenant/skills` to discover scripts. `read_skill(skill_name)` already lists them; that tree also contains `.venv` / `node_modules`\n")builder.WriteString(" - Use shell pipelines, redirects, scripts, package managers, compilers, and other installed commands whenever they are the most direct way to complete the task\n")+ builder.WriteString(" - Do not inspect skill-generated office files with `python3 -c` (system Python has no python-docx/pptx). Write a short script with `write_sandbox_file` and run it with `execute_skill_script`; do not paste the same code into `.venv/bin/python -c`\n")+ builder.WriteString(" - To change a few lines of a file you already wrote, call `edit_sandbox_file` instead of rewriting the whole file\n")+ builder.WriteString(" - Python strings: never nest ASCII `\"` inside `\"...\"` (or `'` inside `'...'`). Use the other quote, and 「」 for Chinese quotation\n")builder.WriteString(" - Increase `max_output_bytes` up to 65536 per stream for large text output, or use `sed`/`head`/`tail` for targeted sections\n")builder.WriteString(" - Binary output is suppressed; write binary results under `/workspace/output` so ArtifactCollector attaches them for download\n")builder.WriteString(" - Session state persists across later `shell_exec` and `execute_skill_script` calls\n")diff --git a/internal/agent/prompts_shell_test.go b/internal/agent/prompts_shell_test.goindex 39b45df6d..8a1fb6823 100644--- a/internal/agent/prompts_shell_test.go+++ b/internal/agent/prompts_shell_test.go@@ -13,11 +13,23 @@ func TestFormatSkillsMetadataIncludesShellGuidanceOnlyWhenEnabled(t *testing.T)enabled := formatSkillsMetadata(metadata, true)require.Contains(t, enabled, "shell_exec")- for _, command := range []string{"find", "file", "cat", "head", "tail", "sed", "grep", "awk"} {+ for _, command := range []string{"find", "ls", "cat", "head", "tail", "sed", "grep", "awk"} {assert.Contains(t, enabled, command)}assert.Contains(t, enabled, "Freely execute shell commands")assert.Contains(t, enabled, "Binary output is suppressed")+ assert.Contains(t, enabled, "use `file` for an unknown type")+ assert.NotContains(t, enabled, "do not `apt-get install file`")+ assert.Contains(t, enabled, "write_sandbox_file")+ assert.Contains(t, enabled, "edit_sandbox_file")+ assert.Contains(t, enabled, "python3 -c")+ assert.Contains(t, enabled, "execute_skill_script")+ assert.Contains(t, enabled, "/workspace/...")+ assert.Contains(t, enabled, "do not `list_sandbox_files`")+ assert.Contains(t, enabled, "read_skill(skill_name, file_path)")+ assert.Contains(t, enabled, ".skill-packages")+ assert.Contains(t, enabled, "install_deps.py")+ assert.Contains(t, enabled, "never nest ASCII")disabled := formatSkillsMetadata(metadata, false)assert.NotContains(t, disabled, "shell_exec")diff --git a/internal/agent/skills/env_resolver.go b/internal/agent/skills/env_resolver.goindex 9782e9162..41a20ee0e 100644--- a/internal/agent/skills/env_resolver.go+++ b/internal/agent/skills/env_resolver.go@@ -4,6 +4,8 @@ import ("context""fmt""strings"++ "github.com/Tencent/WeKnora/internal/sandbox")// SkillEnvResolver produces the environment one execution gets. It is separate@@ -47,8 +49,9 @@ func (e *MissingSkillEnvError) Error() string {)}-// applyResolvedEnv overlays resolved onto env WITHOUT displacing anything env-// already carries.+// ApplyResolvedEnv overlays resolved onto env WITHOUT displacing anything env+// already carries. It is exported because shell_exec applies the same overlay+// for its optional skill_name parameter and must not diverge from it.//// This is the second layer of reserved-name protection. Task 2's write-time// blacklist is the first, but a value written before that blacklist existed@@ -56,7 +59,7 @@ func (e *MissingSkillEnvError) Error() string {// WEKNORA_SKILL_OUTPUT_DIR would silently redirect the turn's artifacts to a// directory nobody drains. Skipping existing keys makes that impossible// regardless of what is stored.-func applyResolvedEnv(env, resolved map[string]string) {+func ApplyResolvedEnv(env, resolved map[string]string) {for name, value := range resolved {if _, taken := env[name]; taken {continue@@ -64,3 +67,26 @@ func applyResolvedEnv(env, resolved map[string]string) {env[name] = value}}++// applySessionPackagePath prepends the per-session extra-packages directory+// so a frozen skill venv can still see `pip install --target` extras without+// mutating the snapshot. Missing directories are ignored by the interpreters.+func applySessionPackagePath(env map[string]string, skillName string) {+ if env == nil {+ return+ }+ dir := sandbox.SessionSkillPackageDir(skillName)+ if dir == "" {+ return+ }+ prependPathEnv(env, pythonPathEnvVar, dir)+ prependPathEnv(env, nodePathEnvVar, dir)+}++func prependPathEnv(env map[string]string, key, dir string) {+ if existing := strings.TrimSpace(env[key]); existing != "" {+ env[key] = dir + ":" + existing+ return+ }+ env[key] = dir+}diff --git a/internal/agent/skills/env_resolver_test.go b/internal/agent/skills/env_resolver_test.goindex e837cb5c7..b749ae02a 100644--- a/internal/agent/skills/env_resolver_test.go+++ b/internal/agent/skills/env_resolver_test.go@@ -5,6 +5,7 @@ import ("errors""testing"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/stretchr/testify/require")@@ -17,7 +18,7 @@ func TestApplyResolvedEnvAddsNewKeysAndKeepsExistingOnes(t *testing.T) {artifactHistoryEnvVar: "/workspace/output",}- applyResolvedEnv(env, map[string]string{+ ApplyResolvedEnv(env, map[string]string{"TAVILY_API_KEY": "user-key",artifactOutputEnvVar: "/tmp/hijacked",artifactHistoryEnvVar: "/tmp/hijacked",@@ -28,12 +29,14 @@ func TestApplyResolvedEnvAddsNewKeysAndKeepsExistingOnes(t *testing.T) {require.Equal(t, "/workspace/output", env[artifactHistoryEnvVar])}-func TestApplyResolvedEnvToleratesNilResolved(t *testing.T) {- env := map[string]string{artifactOutputEnvVar: "/workspace/output"}+func TestApplySessionPackagePathPrependsPythonAndNodePath(t *testing.T) {+ env := map[string]string{pythonPathEnvVar: "/already"}- applyResolvedEnv(env, nil)+ applySessionPackagePath(env, "律师助手")- require.Equal(t, map[string]string{artifactOutputEnvVar: "/workspace/output"}, env)+ dir := sandbox.SessionSkillPackageDir("律师助手")+ require.Equal(t, dir+":/already", env[pythonPathEnvVar])+ require.Equal(t, dir, env[nodePathEnvVar])}// The message is read by the agent and relayed verbatim to a person, so it hasdiff --git a/internal/agent/skills/manager.go b/internal/agent/skills/manager.goindex c7eabaaa7..b88187e59 100644--- a/internal/agent/skills/manager.go+++ b/internal/agent/skills/manager.go@@ -38,6 +38,12 @@ const artifactHistoryEnvVar = "WEKNORA_SKILL_HISTORY_ROOT"// install-time verification pass exports the same name.const skillDirEnvVar = "WEKNORA_SKILL_DIR"+// pythonPathEnvVar / nodePathEnvVar carry the per-session extra-packages+// overlay (see sandbox.SessionSkillPackageDir). They are injected rather than+// left for the skill to declare so a stored PYTHONPATH cannot displace them.+const pythonPathEnvVar = "PYTHONPATH"+const nodePathEnvVar = "NODE_PATH"+// InjectedSandboxEnvVars is every name ExecuteScript writes into the sandbox// environment. The skill-env declaration blacklist must reject these so a// stored value cannot redirect artifacts, the skill directory, or the session@@ -48,6 +54,8 @@ func InjectedSandboxEnvVars() []string {sessionInputEnvVar,artifactHistoryEnvVar,skillDirEnvVar,+ pythonPathEnvVar,+ nodePathEnvVar,}}@@ -355,6 +363,7 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strinartifactOutputEnvVar: outputDir,artifactHistoryEnvVar: ArtifactOutputDir(),}+ applySessionPackagePath(env, skillName)// SessionFileStore advertises the "sandbox provides per-session file// storage" capability. When present we can safely expose the input// staging directory and pre-materialise the output directory; when@@ -375,7 +384,7 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin// linger where the next person could read them with `env`.//// The resolver runs after the artifact keys above are seeded, so- // applyResolvedEnv's skip-existing rule protects WEKNORA_SKILL_OUTPUT_DIR+ // ApplyResolvedEnv's skip-existing rule protects WEKNORA_SKILL_OUTPUT_DIR// and WEKNORA_SKILL_HISTORY_ROOT (always) plus WEKNORA_SESSION_INPUT_DIR// (when a session file store exists). skillDirEnvVar is set later inside// buildSkillExecuteConfig by an unconditional write. The write-time@@ -390,7 +399,7 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strinif len(missing) > 0 {return nil, &MissingSkillEnvError{SkillName: skillName, Names: missing}}- applyResolvedEnv(env, resolved)+ ApplyResolvedEnv(env, resolved)}config, err := buildSkillExecuteConfig(@@ -406,11 +415,12 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin// buildSkillExecuteConfig turns one skill script into an execution request.//-// The two sources diverge here and nowhere else. A skill installed into the-// image is run in place: there is no host-side copy to upload, and the-// executor pins WorkDir to the session workspace and runs it as the ordinary-// sandbox user. A preloaded skill keeps its existing behaviour exactly --// uploaded from the host, executed with the skill directory as WorkDir.+// Three cases:+// - A session /workspace file (from write_sandbox_file): run in place with+// the installed skill's interpreter. Preloaded skills cannot do this.+// - An installed image skill: run the relative path in place; no host upload.+// - A preloaded skill: upload from the host and run with the skill directory+// as WorkDir.func buildSkillExecuteConfig(source SkillSource,skillName, scriptPath, basePath string,@@ -419,6 +429,10 @@ func buildSkillExecuteConfig(env map[string]string,sessionID string,) (*sandbox.ExecuteConfig, error) {+ if workspace, ok := sandbox.RunnableWorkspaceScript(scriptPath); ok {+ return workspaceSkillExecuteConfig(source, skillName, workspace, basePath, args, stdin, env, sessionID)+ }+image, installed := source.(imageSkillSource)if !installed {// Load the script file to verify it exists and is a script@@ -463,6 +477,41 @@ func buildSkillExecuteConfig(}, nil}+// workspaceSkillExecuteConfig runs a session-written /workspace file with the+// installed skill's interpreter. Preloaded (host-uploaded) skills have no+// in-sandbox venv to attach, so those calls are rejected with a shell_exec hint.+func workspaceSkillExecuteConfig(+ source SkillSource,+ skillName, workspacePath, basePath string,+ args []string,+ stdin string,+ env map[string]string,+ sessionID string,+) (*sandbox.ExecuteConfig, error) {+ if !IsScript(workspacePath) {+ return nil, fmt.Errorf("file is not an executable script: %s", workspacePath)+ }+ if _, installed := source.(imageSkillSource); !installed {+ return nil, fmt.Errorf(+ "script_path %q is a session workspace file; this skill is not installed in the sandbox image, so execute_skill_script cannot attach its environment. Run it with shell_exec, or pass a skill-relative path such as scripts/foo.py",+ workspacePath,+ )+ }+ skillDir, ok := sandbox.ValidatedImageSkillDir(basePath)+ if !ok {+ return nil, fmt.Errorf("cannot run workspace script %q for skill %q: no installed skill directory", workspacePath, skillName)+ }+ env[skillDirEnvVar] = skillDir+ return &sandbox.ExecuteConfig{+ RemoteScriptPath: workspacePath,+ SkillDir: skillDir,+ Args: args,+ Stdin: stdin,+ Env: env,+ SessionID: sessionID,+ }, nil+}+// sessionFileStoreFromManager returns the sandbox manager's effective// session filesystem capability, or nil when the backend cannot expose one.// Isolated in a helper so callers stay free of provider-specific branches.diff --git a/internal/agent/skills/skill.go b/internal/agent/skills/skill.goindex e8dcb9025..550dd8463 100644--- a/internal/agent/skills/skill.go+++ b/internal/agent/skills/skill.go@@ -9,8 +9,7 @@ import ("path/filepath""regexp""strings"-- "gopkg.in/yaml.v3"+ "unicode/utf8")// Skill validation constants following Claude's specification@@ -23,8 +22,13 @@ const (// Reserved words that cannot be used in skill namesvar reservedWords = []string{"anthropic", "claude"}-// namePattern validates skill names: unicode letters, numbers only-var namePattern = regexp.MustCompile(`^[\p{L}\p{N}-]+$`)+// namePattern is the install identity: a single path segment of letters+// (any script), digits, hyphens, and underscores. Display titles such as+// "Word / DOCX" are not this; those are rewritten via slug / slugify+// before Validate. Slashes stay out so the name cannot walk SkillsImageRoot.+var namePattern = regexp.MustCompile(`^[\p{L}\p{N}_-]+$`)++var skillNameSepRE = regexp.MustCompile(`[^\p{L}\p{N}]+`)// xmlTagPattern detects XML tags in contentvar xmlTagPattern = regexp.MustCompile(`<[^>]+>`)@@ -38,6 +42,10 @@ type Skill struct {// Metadata (Level 1) - always loadedName string `yaml:"name"`Description string `yaml:"description"`+ // Slug is an optional filesystem-safe id. ClawHub / SkillHub often put a+ // display title in name ("Word / DOCX") and the install id in slug+ // ("word-docx"). When name is not a valid install identity, slug wins.+ Slug string `yaml:"slug,omitempty"`// Filesystem informationBasePath string // Absolute path to the skill directory@@ -46,6 +54,12 @@ type Skill struct {// Instructions (Level 2) - loaded on demandInstructions string // The main body of SKILL.md (after frontmatter)Loaded bool // Whether Level 2 instructions have been loaded++ // FrontmatterRepaired is true when the YAML between the --- markers had+ // to be repaired (keys nested under a scalar, or an unquoted colon)+ // before it would parse. The original SKILL.md is unchanged; callers+ // that install the archive should tell the user so they can fix it.+ FrontmatterRepaired bool}// SkillMetadata represents the minimal metadata for system prompt injection (Level 1)@@ -70,11 +84,11 @@ func (s *Skill) Validate() error {if s.Name == "" {return errors.New("skill name is required")}- if len(s.Name) > MaxNameLength {- return fmt.Errorf("skill name exceeds maximum length of %d characters", MaxNameLength)+ if n := utf8.RuneCountInString(s.Name); n > MaxNameLength {+ return fmt.Errorf("skill name is %d characters; maximum is %d", n, MaxNameLength)}if !namePattern.MatchString(s.Name) {- return errors.New("skill name must contain only lowercase letters, numbers, and hyphens")+ return errors.New("skill name must contain only letters, numbers, hyphens, and underscores")}for _, reserved := range reservedWords {if strings.Contains(s.Name, reserved) {@@ -89,8 +103,8 @@ func (s *Skill) Validate() error {if s.Description == "" {return errors.New("skill description is required")}- if len(s.Description) > MaxDescriptionLength {- return fmt.Errorf("skill description exceeds maximum length of %d characters", MaxDescriptionLength)+ if n := utf8.RuneCountInString(s.Description); n > MaxDescriptionLength {+ return fmt.Errorf("skill description is %d characters; maximum is %d", n, MaxDescriptionLength)}if xmlTagPattern.MatchString(s.Description) {return errors.New("skill description cannot contain XML tags")@@ -99,6 +113,40 @@ func (s *Skill) Validate() error {return nil}+// applyInstallName picks the directory / tool identity. Third-party SKILL.md+// files often put a display title in name ("Word / DOCX") and a kebab-case+// id in slug ("word-docx"). A title that is already a valid identity is+// left alone so Chinese names such as 律师助手 stay as-is.+func (s *Skill) applyInstallName() error {+ if s == nil {+ return errors.New("skill name is required")+ }+ if installableSkillName(s.Name) {+ s.Name = strings.TrimSpace(s.Name)+ return nil+ }+ if installableSkillName(s.Slug) {+ s.Name = strings.TrimSpace(s.Slug)+ return nil+ }+ if derived := slugifySkillName(s.Name); installableSkillName(derived) {+ s.Name = derived+ return nil+ }+ return errors.New("skill name must contain only letters, numbers, hyphens, and underscores (or set slug)")+}++func installableSkillName(name string) bool {+ name = strings.TrimSpace(name)+ return name != "" && namePattern.MatchString(name)+}++func slugifySkillName(name string) string {+ s := strings.ToLower(strings.TrimSpace(name))+ s = skillNameSepRE.ReplaceAllString(s, "-")+ return strings.Trim(s, "-_")+}+// ToMetadata converts a Skill to its lightweight metadata representationfunc (s *Skill) ToMetadata() *SkillMetadata {return &SkillMetadata{@@ -156,9 +204,14 @@ func ParseSkillFile(content string) (*Skill, error) {// Parse YAML frontmatterfrontmatter := strings.Join(frontmatterLines, "\n")- if err := yaml.Unmarshal([]byte(frontmatter), skill); err != nil {+ repaired, err := UnmarshalSkillFrontmatter(frontmatter, skill)+ if err != nil {return nil, fmt.Errorf("failed to parse YAML frontmatter: %w", err)}+ skill.FrontmatterRepaired = repaired+ if err := skill.applyInstallName(); err != nil {+ return nil, err+ }// Set body instructionsskill.Instructions = strings.TrimSpace(strings.Join(bodyLines, "\n"))@@ -182,6 +235,23 @@ func ParseSkillMetadata(content string) (*SkillMetadata, error) {return skill.ToMetadata(), nil}+// IsOnDemandInstallerPath reports whether path is a first-use dependency+// installer (scripts/install_deps.py and friends). Skills ship these to defer+// optional packages to chat time, which cannot work once the skill tree is+// snapshotted read-only. The installer agent's prompt ("install these extras+// now") and the runtime hint ("skip this installer") key off the same list.+func IsOnDemandInstallerPath(scriptPath string) bool {+ base := strings.ToLower(filepath.Base(strings.TrimSpace(scriptPath)))+ switch {+ case strings.Contains(base, "install_dep"):+ return true+ case base == "setup_deps.py", base == "bootstrap_deps.py":+ return true+ default:+ return false+ }+}+// IsScript checks if a file path represents an executable scriptfunc IsScript(path string) bool {ext := strings.ToLower(filepath.Ext(path))@@ -190,6 +260,8 @@ func IsScript(path string) bool {".sh": true,".bash": true,".js": true,+ ".mjs": true,+ ".cjs": true,".ts": true,".rb": true,".pl": true,@@ -206,6 +278,8 @@ func GetScriptLanguage(path string) string {".sh": "bash",".bash": "bash",".js": "node",+ ".mjs": "node",+ ".cjs": "node",".ts": "ts-node",".rb": "ruby",".pl": "perl",diff --git a/internal/agent/skills/skill_frontmatter.go b/internal/agent/skills/skill_frontmatter.gonew file mode 100644index 000000000..1f3819b41--- /dev/null+++ b/internal/agent/skills/skill_frontmatter.go@@ -0,0 +1,203 @@+package skills++import (+ "fmt"+ "reflect"+ "regexp"+ "strings"+ "unicode"++ "gopkg.in/yaml.v3"+)++// UnmarshalSkillFrontmatter decodes the YAML between SKILL.md's --- markers.+//+// Third-party skills (ClawHub / SkillHub) often indent `version` / `description`+// under `name:` as if it were a nested mapping, or leave a colon unquoted in+// a scalar. Strict YAML rejects both with "mapping values are not allowed in+// this context". When the first parse fails, those two conservative repairs+// are retried so those archives still install; valid frontmatter is unchanged.+//+// The decode always lands on a temporary value and is copied into dest only+// on success, so a failed candidate cannot leave dest half-written.+// repaired is true when a repair candidate was what succeeded.+func UnmarshalSkillFrontmatter(frontmatter string, dest any) (repaired bool, err error) {+ firstErr := unmarshalFrontmatterCopy(frontmatter, dest)+ if firstErr == nil {+ return false, nil+ }+ for _, candidate := range frontmatterRepairCandidates(frontmatter) {+ if candidate == frontmatter {+ continue+ }+ if unmarshalFrontmatterCopy(candidate, dest) == nil {+ return true, nil+ }+ }+ return false, firstErr+}++func unmarshalFrontmatterCopy(src string, dest any) error {+ rv := reflect.ValueOf(dest)+ if rv.Kind() != reflect.Ptr || rv.IsNil() {+ return fmt.Errorf("frontmatter dest must be a non-nil pointer")+ }+ tmp := reflect.New(rv.Elem().Type())+ if err := yaml.Unmarshal([]byte(src), tmp.Interface()); err != nil {+ return err+ }+ rv.Elem().Set(tmp.Elem())+ return nil+}++func frontmatterRepairCandidates(frontmatter string) []string {+ outdented := repairAccidentalNestedFrontmatter(frontmatter)+ quoted := quoteColonInUnquotedScalars(frontmatter)+ both := quoteColonInUnquotedScalars(outdented)+ return []string{outdented, quoted, both}+}++// repairAccidentalNestedFrontmatter outdents keys that were nested under a+// plain scalar, e.g.+//+// name: 命理大师+// version: 1.2.6+// description: |+//+// A real nested mapping (`compatibility:` with no value on the same line) is+// left alone because it is valid YAML and does not need this pass.+func repairAccidentalNestedFrontmatter(src string) string {+ lines := strings.Split(src, "\n")+ out := make([]string, 0, len(lines))+ for i := 0; i < len(lines); {+ line := lines[i]+ out = append(out, line)+ i+++ if !isPlainScalarMapping(strings.TrimSpace(line)) {+ continue+ }+ indent := leadingWS(line)+ if i >= len(lines) {+ break+ }+ next := lines[i]+ for i < len(lines) && strings.TrimSpace(lines[i]) == "" {+ out = append(out, lines[i])+ i+++ if i < len(lines) {+ next = lines[i]+ }+ }+ if i >= len(lines) {+ break+ }+ nextIndent := leadingWS(next)+ if nextIndent <= indent || !looksLikeYAMLKey(strings.TrimSpace(next)) {+ continue+ }+ extra := nextIndent - indent+ for i < len(lines) {+ cur := lines[i]+ if strings.TrimSpace(cur) == "" {+ out = append(out, cur)+ i+++ continue+ }+ curIndent := leadingWS(cur)+ if curIndent < nextIndent {+ break+ }+ out = append(out, stripLeadingWS(cur, extra))+ i+++ }+ }+ return strings.Join(out, "\n")+}++var unquotedColonScalarRE = regexp.MustCompile(+ `^(\s*(?:name|description)\s*:\s*)([^"'|>{\[\s#].*:.+)$`,+)++// quoteColonInUnquotedScalars wraps name/description values that contain a+// colon so `description: Foo: bar` is not parsed as a nested mapping.+func quoteColonInUnquotedScalars(src string) string {+ lines := strings.Split(src, "\n")+ for i, line := range lines {+ m := unquotedColonScalarRE.FindStringSubmatch(line)+ if len(m) != 3 {+ continue+ }+ value := strings.TrimSpace(m[2])+ if strings.HasPrefix(value, `"`) || strings.HasPrefix(value, "'") {+ continue+ }+ escaped := strings.ReplaceAll(value, `\`, `\\`)+ escaped = strings.ReplaceAll(escaped, `"`, `\"`)+ lines[i] = m[1] + `"` + escaped + `"`+ }+ return strings.Join(lines, "\n")+}++func isPlainScalarMapping(trimmed string) bool {+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {+ return false+ }+ key, value, ok := strings.Cut(trimmed, ":")+ if !ok || strings.TrimSpace(key) == "" {+ return false+ }+ value = strings.TrimSpace(value)+ if value == "" {+ return false+ }+ if strings.HasPrefix(value, "#") {+ return false+ }+ if value == "|" || value == ">" ||+ strings.HasPrefix(value, "|") || strings.HasPrefix(value, ">") ||+ strings.HasPrefix(value, "{") || strings.HasPrefix(value, "[") {+ return false+ }+ return true+}++func looksLikeYAMLKey(trimmed string) bool {+ if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, "-") {+ return false+ }+ key, _, ok := strings.Cut(trimmed, ":")+ if !ok {+ return false+ }+ key = strings.TrimSpace(key)+ if key == "" {+ return false+ }+ if strings.HasPrefix(key, `"`) || strings.HasPrefix(key, "'") {+ return true+ }+ for i, r := range key {+ if i == 0 && !unicode.IsLetter(r) && r != '_' {+ return false+ }+ if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' && r != '-' && r != '.' {+ return false+ }+ }+ return true+}++func leadingWS(s string) int {+ return len(s) - len(strings.TrimLeft(s, " \t"))+}++func stripLeadingWS(s string, n int) string {+ if n <= 0 {+ return s+ }+ i := 0+ for i < len(s) && i < n && (s[i] == ' ' || s[i] == '\t') {+ i+++ }+ return s[i:]+}diff --git a/internal/agent/skills/skill_frontmatter_test.go b/internal/agent/skills/skill_frontmatter_test.gonew file mode 100644index 000000000..495d54714--- /dev/null+++ b/internal/agent/skills/skill_frontmatter_test.go@@ -0,0 +1,131 @@+package skills++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestParseSkillFileRepairsKeysNestedUnderName(t *testing.T) {+ content := `---+name: 命理大师+ version: 1.2.6+ description: |+ 全体系命理大师 — 八字四柱。+ 仅作文化参考。+metadata:+ displayName: "命理大师"+ version: 1.2.0+---+# Body+`+ skill, err := ParseSkillFile(content)+ require.NoError(t, err)+ require.True(t, skill.FrontmatterRepaired)+ require.Equal(t, "命理大师", skill.Name)+ require.Contains(t, skill.Description, "全体系命理大师")+ require.Contains(t, skill.Instructions, "# Body")+}++func TestParseSkillFileQuotesUnquotedColonInDescription(t *testing.T) {+ content := `---+name: university-applications+description: Apply to universities: resume, essays, and interviews+---+Body+`+ skill, err := ParseSkillFile(content)+ require.NoError(t, err)+ require.True(t, skill.FrontmatterRepaired)+ require.Equal(t, "university-applications", skill.Name)+ require.Equal(t, "Apply to universities: resume, essays, and interviews", skill.Description)+}++func TestRepairAccidentalNestedFrontmatterLeavesValidNestedMapping(t *testing.T) {+ src := strings.TrimSpace(`+compatibility:+ python: "3.11"+name: pdf-tools+description: Extract text+`)+ require.Equal(t, src, repairAccidentalNestedFrontmatter(src))++ var skill Skill+ repaired, err := UnmarshalSkillFrontmatter(src, &skill)+ require.NoError(t, err)+ require.False(t, repaired)+ require.Equal(t, "pdf-tools", skill.Name)+}++func TestUnmarshalSkillFrontmatterStillRejectsBrokenYAML(t *testing.T) {+ var skill Skill+ _, err := UnmarshalSkillFrontmatter(":\n - oops", &skill)+ require.Error(t, err)+ require.Empty(t, skill.Name)+}++func TestUnmarshalSkillFrontmatterDoesNotPolluteDestOnFailedRepair(t *testing.T) {+ type dest struct {+ Name string `yaml:"name"`+ Description string `yaml:"description"`+ Tags []string `yaml:"tags"`+ }+ // tags would decode, but the nested name/description plus broken+ // metadata list is still invalid after the two repairs. dest must+ // stay zero — not a mix of a partial first attempt and a later one.+ fm := "tags:\n - a\n - b\nname: alpha\n version: 9.9.9\n description: |\n hello\nmetadata:\n openclaw:\n install:\n - kind: node\n package: iztro\n"+ var d dest+ repaired, err := UnmarshalSkillFrontmatter(fm, &d)+ require.Error(t, err)+ require.False(t, repaired)+ require.Empty(t, d.Name)+ require.Empty(t, d.Tags)+}++func TestParseSkillFileUsesSlugWhenNameIsADisplayTitle(t *testing.T) {+ content := `---+name: Word / DOCX+slug: word-docx+description: Create and edit Microsoft Word documents.+---+Body+`+ skill, err := ParseSkillFile(content)+ require.NoError(t, err)+ require.Equal(t, "word-docx", skill.Name)+}++func TestParseSkillFileSlugifiesDisplayTitleWithoutSlug(t *testing.T) {+ content := `---+name: Word / DOCX+description: Create and edit Microsoft Word documents.+---+Body+`+ skill, err := ParseSkillFile(content)+ require.NoError(t, err)+ require.Equal(t, "word-docx", skill.Name)+}++func TestParseSkillFileKeepsUnicodeName(t *testing.T) {+ content := `---+name: 律师助手+description: 法律文书助手+---+Body+`+ skill, err := ParseSkillFile(content)+ require.NoError(t, err)+ require.Equal(t, "律师助手", skill.Name)+}++func TestParseSkillFileRejectsSkillHubFrontmatterWithBrokenExtraYAML(t *testing.T) {+ content, err := os.ReadFile(filepath.Join("testdata", "skillhub_nested_name.md"))+ require.NoError(t, err)++ _, err = ParseSkillFile(string(content))+ require.Error(t, err, "nest repair is not enough when extra keys (metadata.openclaw.install) are still invalid YAML")+}diff --git a/internal/agent/skills/skills_test.go b/internal/agent/skills/skills_test.goindex 4e0fe0f9a..cb2a4cf2c 100644--- a/internal/agent/skills/skills_test.go+++ b/internal/agent/skills/skills_test.go@@ -4,6 +4,7 @@ import ("context""os""path/filepath"+ "strings""testing")@@ -41,6 +42,9 @@ Use this skill when testing.if !skill.Loaded {t.Error("Expected Loaded to be true after parsing")}+ if skill.FrontmatterRepaired {+ t.Error("valid frontmatter should not be marked repaired")+ }t.Logf("Parsed skill: name=%s, description=%s, instructions_len=%d",skill.Name, skill.Description, len(skill.Instructions))@@ -72,7 +76,19 @@ func TestSkillValidation(t *testing.T) {skillName: "My Skill",description: "A skill",wantErr: true,- errContains: "lowercase letters",+ errContains: "letters, numbers, hyphens, and underscores",+ },+ {+ name: "underscore is allowed",+ skillName: "word_docx",+ description: "A skill",+ wantErr: false,+ },+ {+ name: "unicode letters are allowed",+ skillName: "律师助手",+ description: "A skill",+ wantErr: false,},{name: "reserved word in name",@@ -93,7 +109,27 @@ func TestSkillValidation(t *testing.T) {skillName: "this-is-a-very-long-skill-name-that-exceeds-the-maximum-allowed-length-of-64-characters",description: "A skill",wantErr: true,- errContains: "exceeds maximum length",+ errContains: "maximum is 64",+ },+ {+ name: "description at 1024 CJK runes is allowed even though it is over 1024 bytes",+ skillName: "my-skill",+ description: strings.Repeat("描", 1024),+ wantErr: false,+ },+ {+ name: "description over 1024 CJK runes is rejected",+ skillName: "my-skill",+ description: strings.Repeat("描", 1025),+ wantErr: true,+ errContains: "maximum is 1024",+ },+ {+ name: "description over 1024 ASCII runes is rejected",+ skillName: "my-skill",+ description: strings.Repeat("a", 1025),+ wantErr: true,+ errContains: "maximum is 1024",},}@@ -376,6 +412,8 @@ func TestIsScript(t *testing.T) {{"script.sh", true},{"script.bash", true},{"script.js", true},+ {"script.mjs", true},+ {"script.cjs", true},{"script.ts", true},{"script.rb", true},{"README.md", false},@@ -390,3 +428,19 @@ func TestIsScript(t *testing.T) {}}}++func TestIsOnDemandInstallerPath(t *testing.T) {+ for _, path := range []string{+ "scripts/install_deps.py",+ "scripts/install_dep.sh",+ "setup_deps.py",+ "bootstrap_deps.py",+ } {+ if !IsOnDemandInstallerPath(path) {+ t.Errorf("IsOnDemandInstallerPath(%s) = false, want true", path)+ }+ }+ if IsOnDemandInstallerPath("scripts/generate_ppt.py") {+ t.Error("a real skill script must not look like an on-demand installer")+ }+}diff --git a/internal/agent/skills/tenant_source_test.go b/internal/agent/skills/tenant_source_test.goindex a672ddfb4..05dc426ea 100644--- a/internal/agent/skills/tenant_source_test.go+++ b/internal/agent/skills/tenant_source_test.go@@ -246,6 +246,58 @@ func TestManagerRunsATenantSkillFromTheImageWithoutUploading(t *testing.T) {require.Equal(t, sandbox.SkillsImageRoot+"/pdf",sandboxMgr.config.Env["WEKNORA_SKILL_DIR"])require.Equal(t, "/workspace/output", sandboxMgr.config.Env[artifactOutputEnvVar])+ require.Equal(t, sandbox.SessionSkillPackageDir("pdf"),+ sandboxMgr.config.Env["PYTHONPATH"])+ require.Equal(t, sandbox.SessionSkillPackageDir("pdf"),+ sandboxMgr.config.Env["NODE_PATH"])+}++func TestManagerRunsAWorkspaceScriptWithInstalledSkillInterpreter(t *testing.T) {+ sandboxMgr := &recordingSandboxManager{}+ mgr := NewManager(&ManagerConfig{SkillDirs: nil, Enabled: true}, sandboxMgr)+ mgr.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{{+ ID: "sk-1", Name: "ppt-generator", Status: types.SkillStatusReady, Enabled: true,+ }}, nil))+ require.NoError(t, mgr.Initialize(context.Background()))++ _, err := mgr.ExecuteScript(+ types.WithSessionID(context.Background(), "sess-1"),+ "ppt-generator", "/workspace/output/generate_rencui_ppt.py", []string{"--theme", "doraemon"}, "",+ )++ require.NoError(t, err)+ require.NotNil(t, sandboxMgr.config)+ require.Equal(t, "/workspace/output/generate_rencui_ppt.py", sandboxMgr.config.RemoteScriptPath)+ require.Equal(t, sandbox.SkillsImageRoot+"/ppt-generator", sandboxMgr.config.SkillDir)+ require.Empty(t, sandboxMgr.config.Script)+ require.Equal(t, []string{"--theme", "doraemon"}, sandboxMgr.config.Args)+ require.Equal(t, sandbox.SkillsImageRoot+"/ppt-generator",+ sandboxMgr.config.Env["WEKNORA_SKILL_DIR"])+}++func TestManagerRejectsWorkspaceScriptForPreloadedSkill(t *testing.T) {+ dir := preloadedSkillDir(t, "pdf", "preloaded description")+ sandboxMgr := &recordingSandboxManager{}+ mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr)+ require.NoError(t, mgr.Initialize(context.Background()))++ _, err := mgr.ExecuteScript(context.Background(), "pdf", "/workspace/output/custom.py", nil, "")+ require.Error(t, err)+ require.Contains(t, err.Error(), "shell_exec")+ require.Zero(t, sandboxMgr.calls)+}++func TestManagerRejectsWorkspaceInputAsSkillScript(t *testing.T) {+ sandboxMgr := &recordingSandboxManager{}+ mgr := NewManager(&ManagerConfig{SkillDirs: nil, Enabled: true}, sandboxMgr)+ mgr.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{{+ ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,+ }}, nil))+ require.NoError(t, mgr.Initialize(context.Background()))++ _, err := mgr.ExecuteScript(context.Background(), "pdf", "/workspace/input/upload.py", nil, "")+ require.Error(t, err)+ require.Zero(t, sandboxMgr.calls)}// The in-sandbox directory is what read_skill shows the model so it can namediff --git a/internal/agent/skills/testdata/skillhub_nested_name.md b/internal/agent/skills/testdata/skillhub_nested_name.mdnew file mode 100644index 000000000..cbffce5db--- /dev/null+++ b/internal/agent/skills/testdata/skillhub_nested_name.md@@ -0,0 +1,86 @@+---+name: 命理大师+ version: 1.2.6+ description: |+ 全体系命理大师 — 八字四柱、紫微斗数、奇门遁甲、六爻、梅花易数、塔罗、星盘、+ 数字命理、九宫飞星风水、掌纹面相、起名命名、穿衣搭配、合婚择吉一站式解读。仅作文化参考,不替代医疗、法律、心理、财务、婚姻、命名等+ 专业建议;遇重大决策请咨询专业人士。+ 【数据与隐私提示】本 skill 会在本地文件系统保存用户主动提交的出生年月日时、地点、+ 姓名、可选的家庭成员信息、交互主题记录(用于追踪偏好,默认关闭),以及推送任务日志。+ 所有数据均不上传,仅在本地 data/ 目录留存;用户可随时通过 profile.js 查看、编辑或删除。+ 每日推送为 opt-in,默认关闭。+metadata:+ displayName: "命理大师"+ author:+ - "腾讯高级研发-enoyao"+ - "腾讯高级产品运营-rekyhe"+ version: 1.2.0+ keywords: 八字, 紫微斗数, 奇门遁甲, 六爻, 梅花易数, 塔罗, 星盘, 九宫飞星, 掌纹, 手相, 面相, 起名, 命名, 取名, 穿衣, 搭配, 颜色, 五行色, 开运色, 今日运势, 每日运程, 合婚, 择吉, 生命灵数, 风水, 算命, BaZi, ZiWei, QiMen, Tarot, feng shui, I Ching, numerology, daily horoscope, palmistry, physiognomy, naming, dressing+ # 触发关键词收紧:1.1.8 移除「算命 / 占卜 / 命理 / 数字命理 / fortune telling / astrology」等过宽泛词,+ # 避免在用户未明确要求占卜的对话中误激活本 skill;仅在明确出现具体体系名称或具体主题时才被触发。+ openclaw:+ emoji: "☯️"+ skillKey: "university-applications"+ runtime:+ node: ">=18"+ python3: true+ install:+ - kind: node+ package: iztro+ env: [] # 本 skill 不再读取任何环境变量;曾经的 OPENCLAW_KNOWLEDGE_DIR 已被移除以避免 file-system enumeration。+ security:+ network:+ default: none+ optional:+ - feature: "liuyao HTML LLM divination (user-initiated, in-browser, OFF by default)"+ allowed-endpoints:+ - "https://api.openai.com"+ - "https://api.anthropic.com"+ - "https://api.deepseek.com"+ custom-endpoint: "only after explicit in-UI consent dialog; HTTPS-only, no IP/localhost auto-trust"+ data-sent: "only the hexagram and the user's typed question; no profile, no env vars, no file paths"+ credential: "user-provided LLM API key, entered at runtime, stored in browser localStorage only"+ - feature: "liuyao HTML Google Fonts (commented out by default)"+ endpoint: "https://fonts.googleapis.com"+ data-sent: "none beyond standard font request"+ credential: none+ credentials:+ bundled: none+ required: none+ user-optional:+ - "LLM API key for liuyao/index.html divination feature (scope it to a separate limited key, never reused)"+ push-mechanism: openclaw-ipc+ push-optin: true+ push-default-state: disabled+ data-retention:+ location: "local filesystem under data/profiles/ and data/push-log.json"+ remote-upload: none+ user-controls:+ - "view: node scripts/profile.js show <userId>"+ - "list: node scripts/profile.js list"+ - "edit: node scripts/profile.js save <userId> <field> <value>"+ - "delete: node scripts/profile.js delete <userId>"+ - "disable push: node scripts/push-toggle.js off <userId>"+ notes: |+ All bundled scripts perform local computation only — no fetch, axios,+ https.request, curl, wget, or any outbound network calls from the Node/Python+ side. Push delivery is handled entirely by the OpenClaw runtime via stdout/IPC+ protocol, and is OPT-IN (disabled until the user runs push-toggle.js on).+ The 'channels' field in user profiles (e.g. telegram) is a routing hint for+ the OpenClaw runtime, not a direct API integration. This skill does not hold+ or require any third-party API tokens (Telegram Bot Token, SMTP credentials,+ webhook URLs, etc.). The local-only release helper script is excluded+ from the published bundle via .clawhubignore and is not part of the+ installed skill surface.+ EXCEPTION — OPTIONAL LLM NETWORK USE: the browser-only file liuyao/index.html+ exposes an optional "LLM divination" button. If and only if the user clicks+ it and fills in their own API key + endpoint, the browser (not the skill+ process) will POST the hexagram and question to that user-configured endpoint.+ No key is bundled, hardcoded, or transmitted anywhere else. Users are advised+ to supply a scoped/limited API key rather than a primary account key.+ User profile data (birth details, optional family members, interaction log)+ is stored only on the local filesystem and can be viewed, edited, or deleted+ at any time via scripts/profile.js (see data-retention.user-controls above).+---++# bodydiff --git a/internal/agent/think.go b/internal/agent/think.goindex d22d7f3db..91004c0f0 100644--- a/internal/agent/think.go+++ b/internal/agent/think.go@@ -165,15 +165,18 @@ func (e *AgentEngine) streamThinkingToEventBus(iteration int,sessionID string,) (*types.ChatResponse, error) {- logger.Debugf(ctx, "[Agent][Thinking] Iteration-%d: temp=%.2f, tools=%d, thinking=%v",- iteration+1, e.config.Temperature, len(tools), e.config.Thinking)+ budget := e.getCompletionTokenBudget()+ logger.Debugf(ctx, "[Agent][Thinking] Iteration-%d: temp=%.2f, tools=%d, thinking=%v, max_tokens=%d",+ iteration+1, e.config.Temperature, len(tools), e.config.Thinking, budget)parallelToolCalls := trueopts := &chat.ChatOptions{- Temperature: e.config.Temperature,- Tools: tools,- Thinking: e.config.Thinking,- ParallelToolCalls: ¶llelToolCalls,+ Temperature: e.config.Temperature,+ MaxTokens: budget,+ MaxCompletionTokens: budget,+ Tools: tools,+ Thinking: e.config.Thinking,+ ParallelToolCalls: ¶llelToolCalls,}pendingToolCalls := make(map[string]bool)diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.goindex 997684cae..71803ecfe 100644--- a/internal/agent/tools/definitions.go+++ b/internal/agent/tools/definitions.go@@ -23,13 +23,15 @@ const (// Skills-related tools (only available when skills are enabled)ToolExecuteSkillScript = "execute_skill_script"ToolReadSkill = "read_skill"- // Sandbox filesystem inspection (read-only; only available when the- // sandbox backend supports per-session file listing — currently the- // Cube SessionBoundManager). Lets the LLM discover and inspect files- // produced by prior skill executions in the same session so chained- // skills stop guessing paths.+ // Sandbox filesystem tools (only available when the sandbox backend+ // supports per-session files — Cube, E2B, Docker). list/read inspect+ // output and staged attachments; write creates text files so generated+ // scripts do not have to travel through a shell_exec heredoc; edit+ // patches an existing file without regenerating it.ToolListSandboxFiles = "list_sandbox_files"ToolReadSandboxFile = "read_sandbox_file"+ ToolWriteSandboxFile = "write_sandbox_file"+ ToolEditSandboxFile = "edit_sandbox_file"// ToolShellExec lets the LLM execute ad-hoc shell commands inside the// current session's sandbox (dependency installs, environment probing).// Registered only when the resolved backend advertises the session shell@@ -78,6 +80,8 @@ func AvailableToolDefinitions() []AvailableTool {{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},{Name: ToolListSandboxFiles, Label: "列出沙箱文件", Description: "列出当前会话沙箱产出目录下的文件"},{Name: ToolReadSandboxFile, Label: "读取沙箱文件", Description: "读取当前会话沙箱中已生成的文件内容"},+ {Name: ToolWriteSandboxFile, Label: "写入沙箱文件", Description: "向当前会话沙箱写入文本文件(脚本、报告等)"},+ {Name: ToolEditSandboxFile, Label: "编辑沙箱文件", Description: "精确替换当前会话沙箱中已有文本文件的片段"},{Name: ToolShellExec, Label: "执行沙箱命令", Description: "在当前会话沙箱中执行 shell 命令(如安装依赖、检查环境)"},{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},diff --git a/internal/agent/tools/persist.go b/internal/agent/tools/persist.goindex 347d8c421..eaf14d284 100644--- a/internal/agent/tools/persist.go+++ b/internal/agent/tools/persist.go@@ -16,16 +16,20 @@ var persistStripFields = map[string][]string{// persistStripFieldsByTool drops binary / duplicate blobs. stdout/stderr stay// (compacted separately) so a history reload can still render the card.var persistStripFieldsByTool = map[string][]string{- ToolShellExec: {"content", "content_base64"},- ToolReadSandboxFile: {"content", "content_base64"},+ ToolShellExec: {"content", "content_base64"},+ ToolReadSandboxFile: {"content", "content_base64"},+ ToolWriteSandboxFile: {"content", "content_base64"},+ ToolEditSandboxFile: {"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"},+ ToolShellExec: {"content", "content_base64"},+ ToolReadSandboxFile: {"content", "content_base64"},+ ToolWriteSandboxFile: {"content", "content_base64"},+ ToolEditSandboxFile: {"content", "content_base64"},}const historicalSandboxOutputChars = 4 * 1024@@ -324,6 +328,19 @@ func compactToolSummary(success bool, errMsg string, data map[string]interface{}return rebuilt}return compactShellExecHeadline(data)+ case "write_sandbox_file":+ path := stringField(data, "path")+ size := intField(data, "size")+ if path != "" {+ return fmt.Sprintf("Wrote %s (%d bytes)", path, size)+ }+ case "edit_sandbox_file":+ path := stringField(data, "path")+ size := intField(data, "size")+ n := intField(data, "replacements")+ if path != "" {+ return fmt.Sprintf("Edited %s (%d replacement(s), %d bytes)", path, n, size)+ }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.goindex 53831a854..09f699644 100644--- a/internal/agent/tools/persist_test.go+++ b/internal/agent/tools/persist_test.go@@ -284,3 +284,34 @@ func TestSanitizeAgentStepsForStorage_skillScriptKeepsStreamsOnFailure(t *testint.Fatalf("persisted stdout should remain for the UI card, got %#v", result.Data["stdout"])}}++func TestCompactToolOutputForHistory_writeSandboxFileKeepsPath(t *testing.T) {+ history := CompactToolOutputForHistory(ToolWriteSandboxFile, &types.ToolResult{+ Success: true,+ Output: "=== Wrote sandbox file: /workspace/output/generate_ppt.py ===\n",+ Data: map[string]interface{}{+ "display_type": ToolWriteSandboxFile,+ "path": "/workspace/output/generate_ppt.py",+ "size": 12345,+ },+ })+ if history != "Wrote /workspace/output/generate_ppt.py (12345 bytes)" {+ t.Fatalf("history should keep path and size, got %q", history)+ }+}++func TestCompactToolOutputForHistory_editSandboxFileKeepsPath(t *testing.T) {+ history := CompactToolOutputForHistory(ToolEditSandboxFile, &types.ToolResult{+ Success: true,+ Output: "=== Edited sandbox file: /workspace/output/generate_ppt.py ===\n",+ Data: map[string]interface{}{+ "display_type": ToolEditSandboxFile,+ "path": "/workspace/output/generate_ppt.py",+ "size": 12345,+ "replacements": 1,+ },+ })+ if history != "Edited /workspace/output/generate_ppt.py (1 replacement(s), 12345 bytes)" {+ t.Fatalf("history should keep path, replacements, and size, got %q", history)+ }+}diff --git a/internal/agent/tools/python_syntax.go b/internal/agent/tools/python_syntax.gonew file mode 100644index 000000000..ce82f9d8a--- /dev/null+++ b/internal/agent/tools/python_syntax.go@@ -0,0 +1,238 @@+package tools++import (+ "fmt"+ "path"+ "strings"+ "unicode"+ "unicode/utf8"+)++// pythonQuoteGuidance is the short rule for generated Python. The common+// failure is ASCII quotation marks inside a same-kind string literal+// (`"这不是一个"大干快上"..."`), which Python treats as the end of the+// string. Caught at write/edit time so the model does not burn a round on+// execute_skill_script + py_compile.+const pythonQuoteGuidance = "Python strings: never put ASCII `\"` inside `\"...\"` " ++ "(or `'` inside `'...'`). Use the other quote for the literal, and 「」 " ++ "for Chinese quotation."++var pythonKeywords = map[string]bool{+ "False": true, "None": true, "True": true,+ "and": true, "as": true, "assert": true, "async": true, "await": true,+ "break": true, "class": true, "continue": true, "def": true, "del": true,+ "elif": true, "else": true, "except": true, "finally": true, "for": true,+ "from": true, "global": true, "if": true, "import": true, "in": true,+ "is": true, "lambda": true, "match": true, "nonlocal": true, "not": true,+ "or": true, "pass": true, "raise": true, "return": true, "try": true,+ "while": true, "with": true, "yield": true,+}++func pythonScriptSyntaxHint(filePath, src string) string {+ switch strings.ToLower(path.Ext(filePath)) {+ case ".py":+ default:+ return ""+ }+ line, ok := firstBrokenPythonQuote(src)+ if !ok {+ return ""+ }+ return fmt.Sprintf(+ "Python syntax looks broken around line %d: an ASCII quote inside a "++ "string of the same kind closed the literal early "++ "(e.g. (\"这不是一个\"大干快上\"...\")). The file was written. "++ "Fix it with edit_sandbox_file: wrap that text in the other quote, "++ "or use 「」 / \\\" for the inner quotation. Do not execute the script until it parses.",+ line,+ )+}++func pythonSyntaxErrorHint(stderr string) string {+ if !strings.Contains(stderr, "SyntaxError") {+ return ""+ }+ return "Hint: this is almost always an ASCII quote inside a same-kind Python string " ++ `(e.g. "这不是一个"大干快上"..."). ` ++ "edit_sandbox_file: wrap the text in the other quote, or replace inner quotes with 「」 / \\\"."+}++// firstBrokenPythonQuote reports the line of the first string literal that+// is immediately followed by a non-keyword identifier — the parse error+// `"这不是一个"大干快上` produces. `"hello" if x` is left alone.+func firstBrokenPythonQuote(src string) (int, bool) {+ line := 1+ for i := 0; i < len(src); {+ switch src[i] {+ case '\n':+ line+++ i+++ continue+ case '#':+ if end := strings.IndexByte(src[i:], '\n'); end < 0 {+ return 0, false+ } else {+ i += end+ }+ continue+ }+ start, quote, triple, fstring, ok := pythonStringStart(src, i)+ if !ok {+ i+++ continue+ }+ end, endLine, unclosed := scanPythonString(src, start, quote, triple, fstring, line)+ if unclosed {+ return line, true+ }+ if !fstring {+ j := end+ for j < len(src) && (src[j] == ' ' || src[j] == '\t' || src[j] == '\r') {+ j+++ }+ if ident, isKw := peekPythonIdent(src, j); ident != "" && !isKw {+ return endLine, true+ }+ }+ i = end+ line = endLine+ }+ return 0, false+}++func pythonStringStart(src string, i int) (contentStart int, quote byte, triple, fstring, ok bool) {+ j := i+ for n := 0; n < 2 && j < len(src) && isPythonStringPrefixByte(src[j]); n++ {+ j+++ }+ if j >= len(src) || (src[j] != '"' && src[j] != '\'') {+ return 0, 0, false, false, false+ }+ if j > i {+ if !validPythonStringPrefix(src[i:j]) {+ return 0, 0, false, false, false+ }+ if i > 0 && isPythonIdentContinueByte(src[i-1]) {+ return 0, 0, false, false, false+ }+ }+ quote = src[j]+ fstring = strings.ContainsAny(src[i:j], "fF")+ if j+2 < len(src) && src[j+1] == quote && src[j+2] == quote {+ return j + 3, quote, true, fstring, true+ }+ return j + 1, quote, false, fstring, true+}++func isPythonStringPrefixByte(b byte) bool {+ switch b {+ case 'r', 'R', 'u', 'U', 'b', 'B', 'f', 'F':+ return true+ default:+ return false+ }+}++func isPythonIdentContinueByte(b byte) bool {+ return b == '_' ||+ (b >= '0' && b <= '9') ||+ (b >= 'A' && b <= 'Z') ||+ (b >= 'a' && b <= 'z')+}++func validPythonStringPrefix(p string) bool {+ switch strings.ToLower(p) {+ case "r", "u", "b", "f", "fr", "rf", "br", "rb":+ return true+ default:+ return false+ }+}++func scanPythonString(src string, i int, quote byte, triple, fstring bool, line int) (end, endLine int, unclosed bool) {+ endLine = line+ brace := 0+ for i < len(src) {+ c := src[i]+ if c == '\\' && i+1 < len(src) {+ if src[i+1] == '\n' {+ endLine+++ }+ i += 2+ continue+ }+ if fstring && brace == 0 && c == '{' {+ if i+1 < len(src) && src[i+1] == '{' {+ i += 2+ continue+ }+ brace+++ i+++ continue+ }+ if fstring && brace == 0 && c == '}' {+ if i+1 < len(src) && src[i+1] == '}' {+ i += 2+ continue+ }+ }+ if fstring && brace > 0 && c == '}' {+ brace--+ i+++ continue+ }+ if fstring && brace > 0 && (c == '"' || c == '\'') {+ nested := i + 1+ tripleNest := i+2 < len(src) && src[i+1] == c && src[i+2] == c+ if tripleNest {+ nested = i + 3+ }+ var unclosedNest bool+ i, endLine, unclosedNest = scanPythonString(src, nested, c, tripleNest, false, endLine)+ if unclosedNest {+ return i, endLine, true+ }+ continue+ }+ if c == '\n' {+ if !triple && brace == 0 {+ return i, endLine, true+ }+ endLine+++ i+++ continue+ }+ if brace == 0 && c == quote {+ if triple {+ if i+2 < len(src) && src[i+1] == quote && src[i+2] == quote {+ return i + 3, endLine, false+ }+ i+++ continue+ }+ return i + 1, endLine, false+ }+ i+++ }+ return i, endLine, true+}++func peekPythonIdent(src string, i int) (string, bool) {+ if i >= len(src) {+ return "", false+ }+ r, size := utf8.DecodeRuneInString(src[i:])+ if !unicode.IsLetter(r) && r != '_' {+ return "", false+ }+ j := i + size+ for j < len(src) {+ r, size = utf8.DecodeRuneInString(src[j:])+ if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' {+ break+ }+ j += size+ }+ ident := src[i:j]+ return ident, pythonKeywords[ident]+}diff --git a/internal/agent/tools/python_syntax_test.go b/internal/agent/tools/python_syntax_test.gonew file mode 100644index 000000000..876d0bc66--- /dev/null+++ b/internal/agent/tools/python_syntax_test.go@@ -0,0 +1,59 @@+package tools++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestFirstBrokenPythonQuoteCatchesNestedASCIIQuotes(t *testing.T) {+ src := "slides = [\n" ++ " (\"这不是一个\"大干快上\"的夜晚,而是一个适合整理、沉淀、\", False),\n" ++ "]\n"+ line, ok := firstBrokenPythonQuote(src)+ require.True(t, ok)+ assert.Equal(t, 2, line)+}++func TestFirstBrokenPythonQuoteAllowsKeywordAfterString(t *testing.T) {+ _, ok := firstBrokenPythonQuote(`x = "hello" if cond else "bye"`)+ assert.False(t, ok)+}++func TestFirstBrokenPythonQuoteAllowsImplicitConcat(t *testing.T) {+ _, ok := firstBrokenPythonQuote("x = \"hello\" \"world\"\n")+ assert.False(t, ok)+}++func TestFirstBrokenPythonQuoteAllowsSingleQuotedChinese(t *testing.T) {+ _, ok := firstBrokenPythonQuote("x = '这不是一个\"大干快上\"的夜晚'\n")+ assert.False(t, ok)+}++func TestFirstBrokenPythonQuoteAllowsCornerQuotes(t *testing.T) {+ _, ok := firstBrokenPythonQuote("x = \"这不是一个「大干快上」的夜晚\"\n")+ assert.False(t, ok)+}++func TestFirstBrokenPythonQuoteAllowsFString(t *testing.T) {+ _, ok := firstBrokenPythonQuote("x = f\"hello {name}\"\n")+ assert.False(t, ok)+}++func TestFirstBrokenPythonQuoteReportsUnclosed(t *testing.T) {+ line, ok := firstBrokenPythonQuote("x = \"hello\n")+ require.True(t, ok)+ assert.Equal(t, 1, line)+}++func TestPythonScriptSyntaxHintOnlyForPy(t *testing.T) {+ src := "(\"这不是一个\"大干快上\"的夜晚\")\n"+ assert.NotEmpty(t, pythonScriptSyntaxHint("/workspace/output/x.py", src))+ assert.Empty(t, pythonScriptSyntaxHint("/workspace/output/x.md", src))+}++func TestPythonSyntaxErrorHint(t *testing.T) {+ assert.Empty(t, pythonSyntaxErrorHint("ModuleNotFoundError: docx"))+ assert.Contains(t, pythonSyntaxErrorHint("SyntaxError: invalid syntax"), "edit_sandbox_file")+}diff --git a/internal/agent/tools/registry.go b/internal/agent/tools/registry.goindex c6a41fa79..f78612693 100644--- a/internal/agent/tools/registry.go+++ b/internal/agent/tools/registry.go@@ -137,7 +137,14 @@ func (r *ToolRegistry) ExecuteTool(// Validate parameters against the tool's JSON Schema before execution.// This catches invalid arguments early, avoiding a wasted tool execution + LLM round.if validationErrs := ValidateParams(args, tool.Parameters()); len(validationErrs) > 0 {- errMsg := FormatValidationErrors(validationErrs) + toolErrorHint+ errMsg := FormatValidationErrors(validationErrs)+ if name == ToolWriteSandboxFile {+ errMsg += writeSandboxMissingFieldHint+ }+ if name == ToolEditSandboxFile {+ errMsg += editSandboxMissingFieldHint+ }+ errMsg += toolErrorHintcommon.PipelineWarn(ctx, "AgentTool", "validation_failed", map[string]interface{}{"tool": name,"errors": errMsg,diff --git a/internal/agent/tools/sandbox_edit.go b/internal/agent/tools/sandbox_edit.gonew file mode 100644index 000000000..e7d34dd3c--- /dev/null+++ b/internal/agent/tools/sandbox_edit.go@@ -0,0 +1,297 @@+// Package tools — edit_sandbox_file.+//+// Surgical text replacement for a file already in the session sandbox.+// write_sandbox_file is the right first step for a new script; this tool+// exists so a one-line path fix (or similar) does not force the model to+// regenerate the whole file — that burns tokens and often truncates.+//+// Design notes:+// - Same writable roots as write_sandbox_file: /workspace except+// /workspace/input.+// - Default is a unique match (Cursor-style). replace_all=true replaces+// every occurrence. 0 matches or an ambiguous match without replace_all+// fail without writing.+// - Result is path + replacement count + size; contents are not echoed.+package tools++import (+ "context"+ "encoding/json"+ "fmt"+ "path"+ "strings"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/utils"+)++// editSandboxMissingFieldHint is appended when schema validation fails+// (typically a truncated call that omitted path or old_string).+const editSandboxMissingFieldHint = "\nIf the previous call was truncated, retry with a complete JSON object: " ++ "put `path` first, then `old_string` and `new_string`. Do not send the whole file — this tool replaces a snippet."++// SandboxFileEditor reads then writes a session workspace file. Production+// uses *sandbox.SessionBoundManager via SessionFileStore.+type SandboxFileEditor interface {+ StatSessionFile(ctx context.Context, sessionID, filePath string) (*sandbox.RemoteStatEntry, error)+ ReadSessionFile(ctx context.Context, sessionID, filePath string) ([]byte, error)+ WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error+}++var editSandboxFileTool = BaseTool{+ name: ToolEditSandboxFile,+ description: `Replace exact text in an existing sandbox file without rewriting the whole file.++## Usage+- Use this after ` + "`write_sandbox_file`" + ` (or a previous edit) when only a+ few lines need to change — a wrong output path, a typo, a constant.+- ` + "`old_string`" + ` must match the file exactly, including whitespace and+ quotes. Include a few surrounding lines so the match is unique.+- Default: the snippet must occur exactly once. Set ` + "`replace_all=true`" + `+ only when you intentionally want every occurrence changed.+- Do NOT call ` + "`write_sandbox_file`" + ` with the full file to fix one line.+- ` + pythonQuoteGuidance + `++## When to Use+- A script failed because one path, import, or constant is wrong.+- Renaming a variable or output filename that appears once (or everywhere+ with ` + "`replace_all`" + `).+- Deleting a short block by setting ` + "`new_string`" + ` to empty.++## When NOT to Use+- Creating a new file — use ` + "`write_sandbox_file`" + `.+- Replacing most of the file — rewrite with ` + "`write_sandbox_file`" + `.+- Editing under ` + "`/workspace/input`" + ` (attachments are read-only).+- Binary files.++## Path Rules+- ` + "`path`" + ` MUST be an absolute path under ` + "`/workspace`" + `, not under+ ` + "`/workspace/input`" + `, and not ` + "`/workspace`" + ` or ` + "`/workspace/output`" + `+ themselves.++## Size Handling+- The file (and the result) must stay within 262144 bytes.++## Returns+- The path, how many replacements were made, and the new byte count.+ File contents are not echoed back.`,+ schema: utils.GenerateSchema[EditSandboxFileInput](),+}++// EditSandboxFileInput defines the input parameters for edit_sandbox_file.+type EditSandboxFileInput struct {+ Path string `json:"path" jsonschema:"Absolute sandbox path of an existing text file under /workspace (not /workspace/input)."`+ OldString string `json:"old_string" jsonschema:"Exact text to find. Include enough surrounding lines so the match is unique unless replace_all is true."`+ NewString string `json:"new_string" jsonschema:"Replacement text. Use an empty string to delete the matched text."`+ ReplaceAll bool `json:"replace_all,omitempty" jsonschema:"If true, replace every occurrence. If false (default), old_string must match exactly once."`+}++// EditSandboxFileTool applies an exact string replacement to a sandbox file.+type EditSandboxFileTool struct {+ BaseTool+ editor SandboxFileEditor+}++// NewEditSandboxFileTool constructs the tool. `editor` MUST NOT be nil.+func NewEditSandboxFileTool(editor SandboxFileEditor) *EditSandboxFileTool {+ return &EditSandboxFileTool{+ BaseTool: editSandboxFileTool,+ editor: editor,+ }+}++// Execute reads the file, applies the replacement, and writes it back.+func (t *EditSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {+ logger.Infof(ctx, "[Tool][EditSandboxFile] Execute started")++ var input EditSandboxFileInput+ if err := json.Unmarshal(args, &input); err != nil {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("Failed to parse args: %v", err),+ }, nil+ }++ if t.editor == nil {+ return &types.ToolResult{+ Success: false,+ Error: "sandbox file editing is not available in this deployment",+ }, nil+ }++ trimmed := strings.TrimSpace(input.Path)+ if trimmed == "" {+ return &types.ToolResult{+ Success: false,+ Error: "path is required; edit a file under /workspace (not /workspace/input)",+ }, nil+ }++ sessionID := resolveSessionID(ctx)+ if sessionID == "" {+ return &types.ToolResult{+ Success: false,+ Error: "no session ID in context; edit_sandbox_file must run inside an agent turn",+ }, nil+ }++ clean := path.Clean(trimmed)+ rootDir, ok := matchingWritableRoot(clean)+ if !ok {+ return &types.ToolResult{+ Success: false,+ Error: workspaceWriteScopeError(input.Path),+ }, nil+ }++ stat, err := t.editor.StatSessionFile(ctx, sessionID, clean)+ if err != nil {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("failed to stat %s: %v", clean, err),+ }, nil+ }+ if stat != nil && stat.Type == sandbox.RemoteEntryDir {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("%s is a directory; edit_sandbox_file only edits files", clean),+ }, nil+ }+ if stat != nil && stat.Size > int64(maxWriteSandboxBytes) {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf(+ "file too large to edit (%d bytes; max %d). Split the work or rewrite a smaller file with write_sandbox_file",+ stat.Size, maxWriteSandboxBytes,+ ),+ }, nil+ }++ raw, err := t.editor.ReadSessionFile(ctx, sessionID, clean)+ if err != nil {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("failed to read %s: %v", clean, err),+ }, nil+ }+ if len(raw) > maxWriteSandboxBytes {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf(+ "file too large to edit (%d bytes; max %d)",+ len(raw), maxWriteSandboxBytes,+ ),+ }, nil+ }+ if isBinaryShellOutput(string(raw)) {+ return &types.ToolResult{+ Success: false,+ Error: "binary files cannot be edited; write a text script and have it produce binary artifacts under /workspace/output",+ }, nil+ }++ updated, replacements, err := applySandboxEdit(string(raw), input.OldString, input.NewString, input.ReplaceAll)+ if err != nil {+ return &types.ToolResult{+ Success: false,+ Error: err.Error(),+ }, nil+ }++ content := []byte(updated)+ if len(content) > maxWriteSandboxBytes {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf(+ "result too large (%d bytes; max %d). Shrink new_string or split the file",+ len(content), maxWriteSandboxBytes,+ ),+ }, nil+ }+ if isBinaryShellOutput(updated) {+ return &types.ToolResult{+ Success: false,+ Error: "replacement would introduce binary content, which is not accepted",+ }, nil+ }++ if err := t.editor.WriteSessionWorkspaceFile(ctx, sessionID, clean, content); err != nil {+ logger.Warnf(ctx, "[Tool][EditSandboxFile] write failed: session=%s path=%s err=%v",+ sessionID, clean, err)+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("failed to write %s: %v", clean, err),+ }, nil+ }++ logger.Infof(ctx, "[Tool][EditSandboxFile] session=%s path=%s replacements=%d bytes=%d",+ sessionID, clean, replacements, len(content))++ if hint := pythonScriptSyntaxHint(clean, updated); hint != "" {+ return &types.ToolResult{+ Success: false,+ Error: hint,+ Output: fmt.Sprintf("=== Edited sandbox file with syntax problems: %s ===\n\n%s\n", clean, hint),+ Data: map[string]interface{}{+ "display_type": ToolEditSandboxFile,+ "session_id": sessionID,+ "path": clean,+ "root": rootDir,+ "name": path.Base(clean),+ "size": len(content),+ "replacements": replacements,+ "syntax_error": true,+ },+ }, nil+ }++ output := fmt.Sprintf(+ "=== Edited sandbox file: %s ===\n\nreplacements=%d\nbytes=%d\n",+ clean, replacements, len(content),+ )+ return &types.ToolResult{+ Success: true,+ Output: output,+ Data: map[string]interface{}{+ "display_type": ToolEditSandboxFile,+ "session_id": sessionID,+ "path": clean,+ "root": rootDir,+ "name": path.Base(clean),+ "size": len(content),+ "replacements": replacements,+ },+ }, nil+}++// Cleanup releases any resources.+func (t *EditSandboxFileTool) Cleanup(ctx context.Context) error {+ return nil+}++// applySandboxEdit performs an exact string replacement. replaceAll=false+// requires a unique match.+func applySandboxEdit(content, oldString, newString string, replaceAll bool) (string, int, error) {+ if oldString == "" {+ return "", 0, fmt.Errorf("old_string is required; copy the exact text to change, including whitespace")+ }+ if oldString == newString {+ return "", 0, fmt.Errorf("old_string and new_string are identical; no change would be made")+ }+ n := strings.Count(content, oldString)+ if n == 0 {+ return "", 0, fmt.Errorf("old_string was not found in the file. Copy the exact text (including whitespace) from the file")+ }+ if n > 1 && !replaceAll {+ return "", 0, fmt.Errorf(+ "old_string matched %d times. Include more surrounding context so it is unique, or set replace_all=true",+ n,+ )+ }+ if replaceAll {+ return strings.ReplaceAll(content, oldString, newString), n, nil+ }+ return strings.Replace(content, oldString, newString, 1), 1, nil+}diff --git a/internal/agent/tools/sandbox_edit_test.go b/internal/agent/tools/sandbox_edit_test.gonew file mode 100644index 000000000..dfcbbef62--- /dev/null+++ b/internal/agent/tools/sandbox_edit_test.go@@ -0,0 +1,245 @@+package tools++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type fakeSandboxFileEditor struct {+ files map[string][]byte+ statErr error+ readErr error+ writeErr error+ writes int+}++func (f *fakeSandboxFileEditor) StatSessionFile(_ context.Context, _, filePath string) (*sandbox.RemoteStatEntry, error) {+ if f.statErr != nil {+ return nil, f.statErr+ }+ data, ok := f.files[filePath]+ if !ok {+ return nil, fmt.Errorf("no such file: %s", filePath)+ }+ return &sandbox.RemoteStatEntry{+ Path: filePath,+ Type: sandbox.RemoteEntryFile,+ Size: int64(len(data)),+ }, nil+}++func (f *fakeSandboxFileEditor) ReadSessionFile(_ context.Context, _, filePath string) ([]byte, error) {+ if f.readErr != nil {+ return nil, f.readErr+ }+ data, ok := f.files[filePath]+ if !ok {+ return nil, fmt.Errorf("no such file: %s", filePath)+ }+ return append([]byte(nil), data...), nil+}++func (f *fakeSandboxFileEditor) WriteSessionWorkspaceFile(_ context.Context, _, filePath string, content []byte) error {+ if f.writeErr != nil {+ return f.writeErr+ }+ f.writes+++ if f.files == nil {+ f.files = map[string][]byte{}+ }+ f.files[filePath] = append([]byte(nil), content...)+ return nil+}++func TestApplySandboxEditUniqueAndReplaceAll(t *testing.T) {+ content := "a = '/home/user/Desktop/deck.pptx'\nprint(a)\n"++ updated, n, err := applySandboxEdit(+ content,+ "/home/user/Desktop/deck.pptx",+ "/workspace/output/deck.pptx",+ false,+ )+ require.NoError(t, err)+ assert.Equal(t, 1, n)+ assert.Contains(t, updated, "/workspace/output/deck.pptx")+ assert.NotContains(t, updated, "/home/user/Desktop")++ _, _, err = applySandboxEdit("xx xx xx", "xx", "yy", false)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "3 times")++ all, n, err := applySandboxEdit("xx xx xx", "xx", "yy", true)+ require.NoError(t, err)+ assert.Equal(t, 3, n)+ assert.Equal(t, "yy yy yy", all)++ _, _, err = applySandboxEdit(content, "missing", "x", false)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "not found")++ _, _, err = applySandboxEdit(content, "print(a)", "print(a)", false)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "identical")++ _, _, err = applySandboxEdit(content, "", "x", false)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "old_string is required")+}++func TestEditSandboxFileReplacesUniqueSnippet(t *testing.T) {+ path := "/workspace/output/generate_wifi_ppt.py"+ original := "from pptx import Presentation\n" ++ "out = '/home/user/Desktop/Windows_Server_2008_WiFi连接指南.pptx'\n" ++ "prs.save(out)\n"+ editor := &fakeSandboxFileEditor{files: map[string][]byte{path: []byte(original)}}++ result, err := NewEditSandboxFileTool(editor).Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs(path,+ "/home/user/Desktop/Windows_Server_2008_WiFi连接指南.pptx",+ "/workspace/output/Windows_Server_2008_WiFi连接指南.pptx",+ false,+ ),+ )++ require.NoError(t, err)+ require.True(t, result.Success, result.Error)+ assert.Equal(t, 1, editor.writes)+ assert.Equal(t, 1, result.Data["replacements"])+ assert.Equal(t, path, result.Data["path"])+ assert.Contains(t, string(editor.files[path]), "/workspace/output/Windows_Server_2008_WiFi连接指南.pptx")+ assert.NotContains(t, string(editor.files[path]), "/home/user/Desktop")+ assert.NotContains(t, result.Output, original)+ _, hasContent := result.Data["content"]+ assert.False(t, hasContent)+}++func TestEditSandboxFileFlagsNestedPythonQuotes(t *testing.T) {+ path := "/workspace/output/generate_fortune_ppt.py"+ original := "slides = [(\"placeholder\", False)]\n"+ editor := &fakeSandboxFileEditor{files: map[string][]byte{path: []byte(original)}}++ result, err := NewEditSandboxFileTool(editor).Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs(path, "placeholder", "这不是一个\"大干快上\"的夜晚", false),+ )++ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Equal(t, 1, editor.writes)+ assert.Contains(t, result.Error, "edit_sandbox_file")+ assert.Equal(t, true, result.Data["syntax_error"])+}++func TestEditSandboxFileReplaceAllAndAmbiguous(t *testing.T) {+ path := "/workspace/scratch.py"+ original := "print('todo')\nprint('todo')\n"+ editor := &fakeSandboxFileEditor{files: map[string][]byte{path: []byte(original)}}+ tool := NewEditSandboxFileTool(editor)++ ambiguous, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs(path, "todo", "done", false),+ )+ require.NoError(t, err)+ require.False(t, ambiguous.Success)+ assert.Contains(t, ambiguous.Error, "2 times")+ assert.Zero(t, editor.writes)++ all, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs(path, "todo", "done", true),+ )+ require.NoError(t, err)+ require.True(t, all.Success, all.Error)+ assert.Equal(t, 2, all.Data["replacements"])+ assert.Equal(t, "print('done')\nprint('done')\n", string(editor.files[path]))+}++func TestEditSandboxFileRefusesInputAndMissing(t *testing.T) {+ editor := &fakeSandboxFileEditor{files: map[string][]byte{+ "/workspace/input/secret.txt": []byte("nope"),+ }}+ tool := NewEditSandboxFileTool(editor)++ input, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs("/workspace/input/secret.txt", "nope", "ok", false),+ )+ require.NoError(t, err)+ require.False(t, input.Success)+ assert.Contains(t, input.Error, "outside that scope")+ assert.Zero(t, editor.writes)++ missing, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs("/workspace/output/missing.py", "a", "b", false),+ )+ require.NoError(t, err)+ require.False(t, missing.Success)+ assert.Contains(t, missing.Error, "failed to stat")+}++func TestEditSandboxFileRefusesBinaryAndOversize(t *testing.T) {+ tool := NewEditSandboxFileTool(&fakeSandboxFileEditor{files: map[string][]byte{+ "/workspace/output/x.bin": []byte("pre\x00post"),+ "/workspace/output/big.py": []byte(strings.Repeat("a", maxWriteSandboxBytes+1)),+ }})++ binary, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs("/workspace/output/x.bin", "pre", "POST", false),+ )+ require.NoError(t, err)+ require.False(t, binary.Success)+ assert.Contains(t, binary.Error, "binary")++ oversize, err := tool.Execute(+ sandboxFileTestContext(),+ mustEditSandboxArgs("/workspace/output/big.py", "a", "b", true),+ )+ require.NoError(t, err)+ require.False(t, oversize.Success)+ assert.Contains(t, oversize.Error, "too large")+}++func TestEditSandboxFileRegistryHintsWhenPathMissing(t *testing.T) {+ registry := NewToolRegistry()+ registry.RegisterTool(NewEditSandboxFileTool(&fakeSandboxFileEditor{+ files: map[string][]byte{"/workspace/a.py": []byte("x")},+ }))++ result, err := registry.ExecuteTool(+ sandboxFileTestContext(),+ ToolEditSandboxFile,+ json.RawMessage(`{"old_string":"x","new_string":"y"}`),+ )+ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Contains(t, result.Error, "path")+ assert.Contains(t, result.Error, "put `path` first")+}++func mustEditSandboxArgs(path, oldString, newString string, replaceAll bool) json.RawMessage {+ payload := map[string]any{+ "path": path,+ "old_string": oldString,+ "new_string": newString,+ }+ if replaceAll {+ payload["replace_all"] = true+ }+ raw, err := json.Marshal(payload)+ if err != nil {+ panic(err)+ }+ return raw+}diff --git a/internal/agent/tools/sandbox_ls.go b/internal/agent/tools/sandbox_ls.goindex 1864df9a7..38e73bd2a 100644--- a/internal/agent/tools/sandbox_ls.go+++ b/internal/agent/tools/sandbox_ls.go@@ -17,7 +17,7 @@// Omitting `path` still lists output so a listing does not dump// every attachment into context.// - Read-only: this tool never creates, modifies or deletes anything-// inside the sandbox. Writes still go through skill scripts.+// inside the sandbox. Model-authored files go through write_sandbox_file.// - Graceful "no sandbox": if the session has never spawned a sandbox// yet (chat-only turn, or sandbox was reaped), the tool returns an// empty listing with a helpful message rather than an error, so the@@ -86,12 +86,19 @@ var listSandboxFilesTool = BaseTool{- You want to give the user a listing of everything the current sessionhas produced.+## When NOT to Use+- Do NOT list skill install directories (` + "`/opt/weknora/tenant/skills/...`" + `).+ Call ` + "`read_skill(skill_name=...)`" + ` instead: that returns SKILL.md and+ the skill's file list (scripts, docs). Those trees also contain+ ` + "`.venv`" + ` / ` + "`node_modules`" + `.+- Do not list ` + "`/workspace`" + ` itself, ` + "`/etc`" + `, or other system paths.+## Path Rules- ` + "`path`" + ` is optional. When omitted, the tool lists the default artifactoutput directory (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `).- When provided, ` + "`path`" + ` MUST sit under the artifact output directory orthe session input directory (` + "`/workspace/input`" + `). Attempts to list- arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `) are rejected.+ arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `, skill image dirs) are rejected.- Listing is recursive: sub-directories are traversed automatically andonly files are returned in the flat listing.@@ -175,10 +182,7 @@ func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessageif !ok {return &types.ToolResult{Success: false,- Error: fmt.Sprintf(- "path %q is outside the inspectable sandbox directories (%s)",- input.Path, inspectableRootsDescription(),- ),+ Error: inspectablePathError(input.Path),}, nil}@@ -300,6 +304,50 @@ func inspectableRootsDescription() string {return strings.Join(sandboxInspectableRoots(), ", ")}+// inspectablePathError explains a refused list/read path. Skill image+// paths are the common miss: the model sees /opt/weknora/tenant/skills/<name>+// in read_skill's environment section and retries with this tool or ls.+func inspectablePathError(requested string) string {+ base := fmt.Sprintf(+ "this tool only lists/reads session artifacts and attachments under %s. path %q is outside that scope",+ inspectableRootsDescription(), requested,+ )+ clean := path.Clean(strings.TrimSpace(requested))+ name, inImage := sandbox.SkillNameFromImagePath(clean)+ if !inImage {+ return base + ". Those tools only see session artifacts and attachments. Skill files: read_skill(skill_name=..., file_path=...)."+ }+ if name == "" {+ return base + fmt.Sprintf(+ ". That path is the skill install root. Call read_skill(skill_name=...) for a listed skill instead of listing %s.",+ sandbox.SkillsImageRoot,+ )+ }+ hint := fmt.Sprintf(+ ". That path belongs to skill %q. Call read_skill(skill_name=%q) to load SKILL.md and list files",+ name, name,+ )+ if rel := relativeSkillFileFromImagePath(clean, name); rel != "" {+ hint += fmt.Sprintf(", or read_skill(skill_name=%q, file_path=%q) to read it", name, rel)+ }+ return base + hint + fmt.Sprintf(+ ". Do not ls %s (it includes .venv / node_modules).",+ sandbox.SkillsImageRoot,+ )+}++func relativeSkillFileFromImagePath(clean, skillName string) string {+ dir, err := sandbox.SkillDirFor(skillName)+ if err != nil || clean == dir {+ return ""+ }+ prefix := dir + "/"+ if strings.HasPrefix(clean, prefix) {+ return strings.TrimPrefix(clean, prefix)+ }+ return ""+}+// matchingInspectableRoot returns the allowlisted root that contains// clean, or ("", false) when the path sits outside every root.func matchingInspectableRoot(clean string) (string, bool) {@@ -312,9 +360,9 @@ func matchingInspectableRoot(clean string) (string, bool) {}// isUnderRoot reports whether clean sits at or underneath root. Both-// arguments must already be cleaned. This guardrail keeps the LLM from-// listing paths outside the inspectable directories: even if a rogue-// prompt asks for `/etc/passwd`, the tool refuses.+// arguments must already be cleaned. The list/read tools use this as a+// scope check so they stay on artifacts and attachments; it is not a+// privilege boundary (shell_exec can already reach the same files).func isUnderRoot(clean, root string) bool {if clean == root {return truediff --git a/internal/agent/tools/sandbox_read.go b/internal/agent/tools/sandbox_read.goindex 94f2fd252..06f7e9aa1 100644--- a/internal/agent/tools/sandbox_read.go+++ b/internal/agent/tools/sandbox_read.go@@ -64,6 +64,10 @@ var readSandboxFileTool = BaseTool{- When ` + "`<sandbox_attachments>`" + ` lists a user-uploaded file you need toread without running a shell command.+## When NOT to Use+- Skill files under ` + "`/opt/weknora/tenant/skills`" + `. Use ` + "`read_skill`" + `+ with ` + "`skill_name`" + ` / ` + "`file_path`" + `.+## Path Rules- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `or listed in the current ` + "`<sandbox_attachments>`" + ` block.@@ -156,10 +160,7 @@ func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage)if !ok {return &types.ToolResult{Success: false,- Error: fmt.Sprintf(- "path %q is outside the inspectable sandbox directories (%s)",- input.Path, inspectableRootsDescription(),- ),+ Error: inspectablePathError(input.Path),}, nil}diff --git a/internal/agent/tools/sandbox_read_test.go b/internal/agent/tools/sandbox_read_test.goindex 5bc505558..c77dd34b3 100644--- a/internal/agent/tools/sandbox_read_test.go+++ b/internal/agent/tools/sandbox_read_test.go@@ -192,7 +192,7 @@ func TestReadSandboxFileRefusesOutsideInspectableRoots(t *testing.T) {)require.NoError(t, err, path)require.False(t, result.Success, path)- assert.Contains(t, result.Error, "outside the inspectable sandbox directories", path)+ assert.Contains(t, result.Error, "outside that scope", path)}assert.Zero(t, source.readCalls)assert.Zero(t, source.statCalls)@@ -243,6 +243,35 @@ func TestListSandboxFilesRefusesOutsideInspectableRoots(t *testing.T) {require.NoError(t, err)require.False(t, result.Success)- assert.Contains(t, result.Error, "outside the inspectable sandbox directories")+ assert.Contains(t, result.Error, "outside that scope")assert.Empty(t, source.listedDir)}++func TestListSandboxFilesRedirectsSkillImagePaths(t *testing.T) {+ source := &fakeSandboxFileSource{}+ result, err := NewListSandboxFilesTool(source).Execute(+ sandboxFileTestContext(),+ json.RawMessage(`{"path":"/opt/weknora/tenant/skills/ppt-generator"}`),+ )+ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Contains(t, result.Error, "outside that scope")+ assert.Contains(t, result.Error, `read_skill(skill_name="ppt-generator")`)+ assert.Contains(t, result.Error, "Do not ls")+ assert.Empty(t, source.listedDir)+}++func TestReadSandboxFileRedirectsSkillImagePaths(t *testing.T) {+ source := &fakeSandboxFileSource{+ data: []byte("must not be read"),+ stat: &sandbox.RemoteStatEntry{Path: "/opt/weknora/tenant/skills/ppt-generator/scripts/generate_ppt.py", Type: sandbox.RemoteEntryFile, Size: 4},+ }+ result, err := NewReadSandboxFileTool(source).Execute(+ sandboxFileTestContext(),+ json.RawMessage(`{"path":"/opt/weknora/tenant/skills/ppt-generator/scripts/generate_ppt.py"}`),+ )+ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Contains(t, result.Error, `file_path="scripts/generate_ppt.py"`)+ assert.Zero(t, source.readCalls)+}diff --git a/internal/agent/tools/sandbox_write.go b/internal/agent/tools/sandbox_write.gonew file mode 100644index 000000000..1de40aa60--- /dev/null+++ b/internal/agent/tools/sandbox_write.go@@ -0,0 +1,253 @@+// Package tools — write_sandbox_file.+//+// Lets the LLM write a text file into the current session's sandbox without+// stuffing the bytes through a shell_exec heredoc. shell_exec keeps an 8 KiB+// command cap; generated scripts (PPT builders, reports) routinely exceed it.+//+// Design notes:+// - Session-scoped: the sandbox is resolved from ToolExecContext.SessionID.+// - Path guardrail: writes sit under /workspace and never under+// /workspace/input (staged attachments stay read-only). Prefer+// /workspace/output for files the user should download.+// - Content stays out of ToolResult.Data/Output: the model already has the+// bytes it just sent. The result is path + size so the next call can+// shell_exec the file.+package tools++import (+ "context"+ "encoding/json"+ "fmt"+ "path"+ "strings"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/utils"+)++const maxWriteSandboxBytes = 256 * 1024++// writeSandboxMissingFieldHint is appended when schema validation fails+// (typically a truncated call that only sent `content`).+const writeSandboxMissingFieldHint = "\nIf the previous call was truncated, retry with a complete JSON object: " ++ "put `path` first (e.g. /workspace/output/script.py), then `content`. Split large files."++// SandboxFileSink is the write-side counterpart of SandboxFileSource.+// Production uses *sandbox.SessionBoundManager via SessionFileStore.+type SandboxFileSink interface {+ WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error+}++var writeSandboxFileTool = BaseTool{+ name: ToolWriteSandboxFile,+ description: `Write a text file into the current session's sandbox.++## Usage+- This is the way to create or overwrite a script, report, or other text+ file. Do NOT dump large files through ` + "`shell_exec`" + ` with ` + "`cat`" + `,+ heredocs, or ` + "`python -c`" + ` — those hit a small command-length cap.+- After writing a script that needs a skill's packages, run it with+ ` + "`execute_skill_script(skill_name=..., script_path=<this path>)`" + `+ so the skill's virtualenv is used. Independent scripts: ` + "`shell_exec`" + `,+ e.g. ` + "`python3 /workspace/output/generate_ppt.py`" + `.+- Put user-facing artifacts (pptx, pdf, png, html) under+ ` + "`/workspace/output`" + ` so they can be collected for download. Scratch+ scripts may live anywhere under ` + "`/workspace`" + ` except+ ` + "`/workspace/input`" + `.+- JSON arguments MUST include both ` + "`path`" + ` and ` + "`content`" + `.+ Emit ` + "`path`" + ` first. If a write would be huge, split it across+ multiple files instead of one giant ` + "`content`" + ` string.+- ` + pythonQuoteGuidance + `++## When to Use+- Generating a Python/JS/HTML file the sandbox will execute next.+- Saving a long report or config that does not fit in a shell command.+- Overwriting a file you previously wrote in this session.++## When NOT to Use+- To change a few lines of a file you already wrote, call+ ` + "`edit_sandbox_file`" + ` instead of sending the whole file again.+- Do not write under ` + "`/workspace/input`" + `: that tree is reserved for+ user-uploaded attachments and is read-only.+- Do not write binary bytes. Have a script produce binary artifacts under+ ` + "`/workspace/output`" + `.++## Path Rules+- ` + "`path`" + ` MUST be an absolute path under ` + "`/workspace`" + `.+- ` + "`/workspace`" + `, ` + "`/workspace/output`" + `, and ` + "`/workspace/input`" + `+ themselves are directories and cannot be used as the file path.++## Size Handling+- Content is capped at 262144 bytes per call.++## Returns+- The absolute path and byte count. File contents are not echoed back.`,+ schema: utils.GenerateSchema[WriteSandboxFileInput](),+}++// WriteSandboxFileInput defines the input parameters for write_sandbox_file.+type WriteSandboxFileInput struct {+ Path string `json:"path" jsonschema:"Absolute sandbox path to write. Must sit under /workspace and must not sit under /workspace/input. Prefer /workspace/output for downloadable artifacts."`+ Content string `json:"content" jsonschema:"Full text contents of the file. Overwrites any existing file at path. Maximum 262144 bytes. Do not send binary bytes."`+}++// WriteSandboxFileTool writes a text file into the session sandbox.+type WriteSandboxFileTool struct {+ BaseTool+ sink SandboxFileSink+}++// NewWriteSandboxFileTool constructs the tool. `sink` MUST NOT be nil.+func NewWriteSandboxFileTool(sink SandboxFileSink) *WriteSandboxFileTool {+ return &WriteSandboxFileTool{+ BaseTool: writeSandboxFileTool,+ sink: sink,+ }+}++// Execute writes the requested file into the current session's sandbox.+func (t *WriteSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {+ logger.Infof(ctx, "[Tool][WriteSandboxFile] Execute started")++ var input WriteSandboxFileInput+ if err := json.Unmarshal(args, &input); err != nil {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("Failed to parse args: %v", err),+ }, nil+ }++ if t.sink == nil {+ return &types.ToolResult{+ Success: false,+ Error: "sandbox file writing is not available in this deployment",+ }, nil+ }++ trimmed := strings.TrimSpace(input.Path)+ if trimmed == "" {+ return &types.ToolResult{+ Success: false,+ Error: "path is required; write under /workspace/output for artifacts or /workspace for scratch scripts",+ }, nil+ }++ sessionID := resolveSessionID(ctx)+ if sessionID == "" {+ return &types.ToolResult{+ Success: false,+ Error: "no session ID in context; write_sandbox_file must run inside an agent turn",+ }, nil+ }++ clean := path.Clean(trimmed)+ rootDir, ok := matchingWritableRoot(clean)+ if !ok {+ return &types.ToolResult{+ Success: false,+ Error: workspaceWriteScopeError(input.Path),+ }, nil+ }++ content := []byte(input.Content)+ if len(content) > maxWriteSandboxBytes {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf(+ "content too large (%d bytes; max %d). Split the work across files or shrink the script",+ len(content), maxWriteSandboxBytes,+ ),+ }, nil+ }+ if isBinaryShellOutput(string(content)) {+ return &types.ToolResult{+ Success: false,+ Error: "binary content is not accepted; write a text script and have it produce binary files under /workspace/output",+ }, nil+ }++ if err := t.sink.WriteSessionWorkspaceFile(ctx, sessionID, clean, content); err != nil {+ logger.Warnf(ctx, "[Tool][WriteSandboxFile] write failed: session=%s path=%s err=%v",+ sessionID, clean, err)+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("failed to write %s: %v", clean, err),+ }, nil+ }++ logger.Infof(ctx, "[Tool][WriteSandboxFile] session=%s path=%s bytes=%d",+ sessionID, clean, len(content))++ if hint := pythonScriptSyntaxHint(clean, input.Content); hint != "" {+ return &types.ToolResult{+ Success: false,+ Error: hint,+ Output: fmt.Sprintf("=== Wrote sandbox file with syntax problems: %s ===\n\n%s\n", clean, hint),+ Data: map[string]interface{}{+ "display_type": ToolWriteSandboxFile,+ "session_id": sessionID,+ "path": clean,+ "root": rootDir,+ "name": path.Base(clean),+ "size": len(content),+ "syntax_error": true,+ },+ }, nil+ }++ output := fmt.Sprintf(+ "=== Wrote sandbox file: %s ===\n\nbytes=%d\n\n"++ "If this script needs a skill's packages, run it with\n"++ "execute_skill_script(skill_name=<skill>, script_path=%s)\n"++ "so the skill's virtualenv is used. Independent scripts:\n"++ "shell_exec python3 %s\n\n"++ "User-facing artifacts should land under %s.\n",+ clean, len(content), clean, clean, sandbox.SessionOutputRoot,+ )+ return &types.ToolResult{+ Success: true,+ Output: output,+ Data: map[string]interface{}{+ "display_type": ToolWriteSandboxFile,+ "session_id": sessionID,+ "path": clean,+ "root": rootDir,+ "name": path.Base(clean),+ "size": len(content),+ },+ }, nil+}++// Cleanup releases any resources.+func (t *WriteSandboxFileTool) Cleanup(ctx context.Context) error {+ return nil+}++// workspaceWriteScopeError explains a refused write/edit path. This is a+// tool-scope convention (attachments stay out of these tools; scripts go+// under /workspace), not a privilege check — shell_exec can already write+// the same session sandbox.+func workspaceWriteScopeError(requested string) string {+ return fmt.Sprintf(+ "this tool only writes files under %s (not under %s, and not the directory roots themselves). path %q is outside that scope; use shell_exec for other locations",+ sandbox.SessionWorkspaceRoot, sandbox.SessionInputRoot, requested,+ )+}++// matchingWritableRoot returns the workspace root that contains clean, or+// ("", false) when the path is outside /workspace, is /workspace itself, or+// sits under the read-only attachment tree.+func matchingWritableRoot(clean string) (string, bool) {+ if !isUnderRoot(clean, sandbox.SessionWorkspaceRoot) ||+ clean == sandbox.SessionWorkspaceRoot ||+ clean == sandbox.SessionOutputRoot ||+ isUnderRoot(clean, sandbox.SessionInputRoot) {+ return "", false+ }+ if isUnderRoot(clean, sandbox.SessionOutputRoot) {+ return sandbox.SessionOutputRoot, true+ }+ return sandbox.SessionWorkspaceRoot, true+}diff --git a/internal/agent/tools/sandbox_write_test.go b/internal/agent/tools/sandbox_write_test.gonew file mode 100644index 000000000..7119e5ad6--- /dev/null+++ b/internal/agent/tools/sandbox_write_test.go@@ -0,0 +1,150 @@+package tools++import (+ "context"+ "encoding/json"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type fakeSandboxFileSink struct {+ path string+ content []byte+ err error+ calls int+}++func (f *fakeSandboxFileSink) WriteSessionWorkspaceFile(_ context.Context, _, filePath string, content []byte) error {+ f.calls+++ f.path = filePath+ f.content = append([]byte(nil), content...)+ return f.err+}++func TestWriteSandboxFileWritesTextUnderOutput(t *testing.T) {+ script := "from pptx import Presentation\n" + strings.Repeat("# slide content for a long deck\n", 400)+ require.Greater(t, len(script), 8*1024)++ sink := &fakeSandboxFileSink{}+ result, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/output/generate_ppt.py", script),+ )++ require.NoError(t, err)+ require.True(t, result.Success, result.Error)+ assert.Equal(t, 1, sink.calls)+ assert.Equal(t, "/workspace/output/generate_ppt.py", sink.path)+ assert.Equal(t, script, string(sink.content))+ assert.Equal(t, "/workspace/output/generate_ppt.py", result.Data["path"])+ assert.Equal(t, len(script), result.Data["size"])+ assert.NotContains(t, result.Output, script)+ assert.Contains(t, result.Output, "execute_skill_script")+ assert.Contains(t, result.Output, "/workspace/output/generate_ppt.py")+ _, hasContent := result.Data["content"]+ assert.False(t, hasContent)+}++func TestWriteSandboxFileFlagsNestedPythonQuotes(t *testing.T) {+ script := "slides = [(\"这不是一个\"大干快上\"的夜晚\", False)]\n"+ sink := &fakeSandboxFileSink{}+ result, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/output/generate_fortune_ppt.py", script),+ )++ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Equal(t, 1, sink.calls, "the file is still written so edit_sandbox_file can fix it")+ assert.Contains(t, result.Error, "line 1")+ assert.Contains(t, result.Error, "edit_sandbox_file")+ assert.Equal(t, true, result.Data["syntax_error"])+}++func TestWriteSandboxFileAllowsWorkspaceScratch(t *testing.T) {+ sink := &fakeSandboxFileSink{}+ result, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/scratch.py", "print(1)\n"),+ )++ require.NoError(t, err)+ require.True(t, result.Success, result.Error)+ assert.Equal(t, sandbox.SessionWorkspaceRoot, result.Data["root"])+ assert.Equal(t, "/workspace/scratch.py", sink.path)+}++func TestWriteSandboxFileRefusesSessionInput(t *testing.T) {+ sink := &fakeSandboxFileSink{}+ result, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/input/secret.txt", "nope"),+ )++ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Zero(t, sink.calls)+ assert.Contains(t, result.Error, "outside that scope")+ assert.Contains(t, result.Error, sandbox.SessionWorkspaceRoot)+}++func TestWriteSandboxFileRefusesDirectoryPaths(t *testing.T) {+ sink := &fakeSandboxFileSink{}+ for _, p := range []string{"/workspace", "/workspace/output", "/workspace/input"} {+ result, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs(p, "nope"),+ )+ require.NoError(t, err, p)+ require.False(t, result.Success, p)+ }+ assert.Zero(t, sink.calls)+}++func TestWriteSandboxFileRefusesBinaryAndOversize(t *testing.T) {+ sink := &fakeSandboxFileSink{}++ binary, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/output/x.bin", "pre\x00post"),+ )+ require.NoError(t, err)+ require.False(t, binary.Success)+ assert.Contains(t, binary.Error, "binary")++ oversize, err := NewWriteSandboxFileTool(sink).Execute(+ sandboxFileTestContext(),+ mustWriteSandboxArgs("/workspace/output/big.py", strings.Repeat("a", maxWriteSandboxBytes+1)),+ )+ require.NoError(t, err)+ require.False(t, oversize.Success)+ assert.Contains(t, oversize.Error, "too large")+ assert.Zero(t, sink.calls)+}++func TestWriteSandboxFileRegistryHintsWhenPathMissing(t *testing.T) {+ registry := NewToolRegistry()+ registry.RegisterTool(NewWriteSandboxFileTool(&fakeSandboxFileSink{}))++ result, err := registry.ExecuteTool(+ sandboxFileTestContext(),+ ToolWriteSandboxFile,+ json.RawMessage(`{"content":"print(1)\n"}`),+ )+ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Contains(t, result.Error, "path")+ assert.Contains(t, result.Error, "put `path` first")+}++func mustWriteSandboxArgs(path, content string) json.RawMessage {+ raw, err := json.Marshal(map[string]string{"path": path, "content": content})+ if err != nil {+ panic(err)+ }+ return raw+}diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.goindex bbcb99553..bba36e7bf 100644--- a/internal/agent/tools/shell_exec.go+++ b/internal/agent/tools/shell_exec.go@@ -77,7 +77,8 @@ const (// pin the session's sandbox for hours.shellExecMaxTimeout = 10 * time.Minute// shellExecMaxCommandBytes rejects excessively long command strings.- // Real skill setup scripts fit comfortably under 8 KiB.+ // Real skill setup one-liners fit comfortably under 8 KiB. Generated+ // scripts belong in write_sandbox_file, not inlined in the command.shellExecMaxCommandBytes = 8 * 1024// max_output_bytes controls stdout only. Stderr uses a smaller independent// budget so verbose failures cannot consume the entire tool result.@@ -130,15 +131,19 @@ var shellExecTool = BaseTool{## Usage- Use freely to explore and operate inside the sandbox: inspect files, searchcontent, transform data, run programs, manage dependencies, install system packages and verify outputs.-- If a 'command not found' error occurs, attempt to resolve it by running ` + "`apt-get update && apt-get install -y <package>`" + `, or use any other appropriate method to install the missing command.+- Prefer tools that already ship: ` + "`find`" + ` / ` + "`ls`" + ` to discover files;+ ` + "`cat`" + ` / ` + "`head`" + ` / ` + "`tail`" + ` / ` + "`sed`" + ` to inspect text;+ ` + "`grep`" + ` / ` + "`awk`" + ` to search; ` + "`file`" + ` for an unknown type.+ Do not ` + "`apt-get install`" + ` inspection utilities (` + "`tree`" + `, editors)+ after a 127 — those packages vanish with the session.- User-uploaded files listed in ` + "`<sandbox_attachments>`" + ` are restored under` + "`/workspace/input`" + `. Treat them as read-only inputs; write generated filesunder ` + "`/workspace/output`" + `.-- Prefer standard Unix tools for filesystem work: ` + "`find`" + ` / ` + "`file`" + ` to discover- files and types; ` + "`cat`" + ` / ` + "`head`" + ` / ` + "`tail`" + ` / ` + "`sed`" + ` to inspect- text; ` + "`grep`" + ` / ` + "`awk`" + ` to search and process it.-- Install skill dependencies (` + "`pip install ...`" + `, ` + "`apt-get update && apt-get install -y ...`" + `,- ` + "`npm i ...`" + `) before calling ` + "`execute_skill_script`" + ` when required.+- Install extra Python packages into the session overlay+ (` + "`python3 -m pip install --target /workspace/.skill-packages/<skill> ...`" + `),+ never into ` + "`/opt/weknora/tenant/skills`" + `. The skill venv is frozen after+ install. ` + "`apt-get`" + ` is only for a system library this task actually needs,+ not to recover from probing with a missing inspection command.## When to Use- Whenever executing a command is the most direct way to complete the task.@@ -148,16 +153,36 @@ var shellExecTool = BaseTool{## When NOT to Use- DO NOT judge a skill's dependencies with a bare ` + "`python3 -c`" + ` or- ` + "`node -e`" + `: each skill keeps its dependencies in its own virtualenv or- node_modules, which neither of those resolves from here. ` + "`read_skill`" + `- reports the skill's directory and how to reach its environment; reinstalling- the packages here only fills a sandbox that is discarded with the session.+ ` + "`node -e`" + `, and do NOT inspect a skill-generated docx/pptx/xlsx that way+ either: system ` + "`python3`" + ` has none of the skill's packages (` + "`docx`" + `,+ ` + "`pptx`" + `, pandas, …). Do not ` + "`pip install`" + ` them here, and do not+ paste the same program into ` + "`.venv/bin/python -c`" + `. Write the script+ with ` + "`write_sandbox_file`" + ` and run it with+ ` + "`execute_skill_script(skill_name=..., script_path=/workspace/output/... )`" + `.+ ` + "`read_skill`" + ` names the skill and how to reach its environment.+- DO NOT ` + "`chown`" + ` / ` + "`chmod`" + ` / ` + "`ensurepip`" + ` / ` + "`pip install`" + ` a skill+ under ` + "`/opt/weknora/tenant/skills`" + `. That tree is read-only after install+ and ` + "`uv venv`" + ` often has no pip. On-demand extras go to+ ` + "`python3 -m pip install --target /workspace/.skill-packages/<skill> <package>`" + `+ (system python3), then ` + "`execute_skill_script`" + `. Or ask the user to+ reinstall the skill so extras are baked in.- DO NOT try to background processes (` + "`&`" + ` at the end, ` + "`nohup`" + `). Sandboxexecution is synchronous.+- DO NOT write large files with ` + "`cat`" + `, heredocs, or ` + "`python -c`" + `. Use+ ` + "`write_sandbox_file`" + ` for the file, then run it from here. To change a+ few lines of an existing file, use ` + "`edit_sandbox_file`" + ` instead of+ rewriting it.+- DO NOT ` + "`ls`" + ` / ` + "`find`" + ` / ` + "`cat`" + ` / ` + "`file`" + ` a skill under+ ` + "`/opt/weknora/tenant/skills`" + ` to discover or read its scripts.+ ` + "`read_skill(skill_name)`" + ` already lists them; that tree also contains+ ` + "`.venv`" + ` / ` + "`node_modules`" + `. A ` + "`.cjs`" + ` / ` + "`.js`" + ` / ` + "`.py`" + `+ path is already a script — call ` + "`execute_skill_script`" + `.## Parameters- ` + "`command`" + ` (required): the shell one-liner to run under ` + "`/bin/bash -l -c`" + `.- Supports pipes, redirects, ` + "`&&`" + ` / ` + "`||`" + ` chaining.+ Supports pipes, redirects, ` + "`&&`" + ` / ` + "`||`" + ` chaining. Keep this short;+ large scripts go through ` + "`write_sandbox_file`" + `; small edits go through+ ` + "`edit_sandbox_file`" + `.- ` + "`work_dir`" + ` (optional): working directory, defaults to ` + "`/workspace`" + `.Created on demand if it doesn't exist.- ` + "`timeout_sec`" + ` (optional): per-call timeout in seconds. Defaults to 120,@@ -305,14 +330,45 @@ func NewShellExecTool(executor SandboxCommandExecutor, envResolver skills.SkillE// root and may work inside the skills image root. It is registered only for// the built-in skill installer agent (see AgentConfig.SkillInstallMode).func NewInstallShellExecTool(executor SandboxInstallCommandExecutor) *ShellExecTool {+ base := shellExecTool+ base.description = installShellExecDescription()return &ShellExecTool{- BaseTool: shellExecTool,+ BaseTool: base,executor: installShellExecutor{inner: executor},workDirRoots: []string{defaultShellExecWorkDir, sandbox.SkillsImageRoot},defaultTimeout: shellExecMaxTimeout,}}+// installShellExecDescription replaces the session-agent "use write_sandbox_file"+// guidance. That tool is not registered in install mode, and the files this+// agent must write sit under the skills image root, which write_sandbox_file+// cannot accept.+func installShellExecDescription() string {+ return `Run a shell command as root inside the skill-install sandbox.++## Usage+- This is your only tool. write_sandbox_file / edit_sandbox_file /+ list_sandbox_files / read_sandbox_file are not available.+- work_dir may be the skill directory under ` + "`/opt/weknora/tenant/skills`" + `.+- Write small files (including ` + "`.weknora/requirements.json`" + `) with a+ short redirect: ` + "`mkdir -p .weknora && cat > .weknora/requirements.json <<'EOF'`" + `.+ Do not try write_sandbox_file — it only accepts ` + "`/workspace`" + `, which+ is wiped before the snapshot.+- Install Python extras into the skill's ` + "`.venv`" + `, Node extras into+ ` + "`node_modules`" + `. Prefer ` + "`uv pip install`" + ` / ` + "`python3 -m venv`" + `.++## Parameters+- ` + "`command`" + ` (required): the shell one-liner under ` + "`/bin/bash -l -c`" + `.+- ` + "`work_dir`" + ` (optional): defaults to ` + "`/workspace`" + `; the skill+ directory is allowed.+- ` + "`timeout_sec`" + ` (optional): defaults to 600 seconds.++## Returns+- ` + "`exit_code`" + `, ` + "`stdout`" + `, ` + "`stderr`" + `. Non-zero is not a+ tool error — read stderr and adapt.`+}+// WithEnvCapture attaches an optional capture hook. A nil hook is a no-op so// callers can pass the wiring result through without a nil check.func (t *ShellExecTool) WithEnvCapture(capture SkillEnvCapture) *ShellExecTool {@@ -357,7 +413,10 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typif len(command) > shellExecMaxCommandBytes {return &types.ToolResult{Success: false,- Error: fmt.Sprintf("command too long (%d bytes; max %d)", len(command), shellExecMaxCommandBytes),+ Error: fmt.Sprintf(+ "command too long (%d bytes; max %d). Put the file in write_sandbox_file, then run it with shell_exec",+ len(command), shellExecMaxCommandBytes,+ ),}, nil}if reason := checkShellExecBlacklist(command); reason != "" {@@ -368,7 +427,6 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typError: fmt.Sprintf("command rejected by shell_exec safety guard: %s", reason),}, nil}-sessionID := resolveSessionID(ctx)if sessionID == "" {return &types.ToolResult{@@ -439,7 +497,9 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typif len(resolved) > 0 && env == nil {env = make(map[string]string)}- overlayResolvedEnv(env, resolved)+ // Model-supplied env wins over resolved values, matching the+ // execute_skill_script contract.+ skills.ApplyResolvedEnv(env, resolved)// A name that already resolved is one the workspace or this caller has// filled in. Capture must not touch it: otherwise a hallucinated// `export KEY=test` would overwrite a working stored credential.@@ -503,6 +563,10 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typb.WriteString(errorText)b.WriteString("\n")}+ if hint := shellExecRecoveryHint(res.ExitCode, command, stderr); hint != "" {+ b.WriteString(hint)+ b.WriteString("\n")+ }visibleOutput := b.String()visibleOutput, totalTruncated := truncateShellStream(visibleOutput, maxShellExecVisibleBytes)truncated = truncated || errorTruncated || totalTruncated@@ -613,20 +677,6 @@ func (t *ShellExecTool) isInstallMode() bool {return false}-// overlayResolvedEnv merges resolved skill-scoped variables into env WITHOUT-// displacing any key env already carries. Model-supplied values (via the env-// parameter) therefore take precedence over resolved ones, matching the-// existing execute_skill_script contract. It mirrors skills.applyResolvedEnv,-// duplicated here to avoid exporting that helper from the skills package.-func overlayResolvedEnv(env, resolved map[string]string) {- for name, value := range resolved {- if _, taken := env[name]; taken {- continue- }- env[name] = value- }-}-// allowedWorkDirRoots defaults to /workspace so a zero-value tool (or one// built before install mode existed) keeps the ordinary contract.func (t *ShellExecTool) allowedWorkDirRoots() []string {@@ -645,6 +695,128 @@ func (t *ShellExecTool) workDirAllowed(cleanWorkDir string) bool {return false}+func shellExecRecoveryHint(exitCode int, command, stderr string) string {+ var parts []string+ if h := shellCommandNotFoundHint(exitCode, command, stderr); h != "" {+ parts = append(parts, h)+ }+ if isFrozenSkillVenvFailure(stderr) {+ parts = append(parts, "Hint: "+frozenSkillTreeGuidance(skillNameFromShellCommand(command)))+ return strings.Join(parts, "\n")+ }+ if h := shellMissingModuleHint(command, stderr); h != "" {+ parts = append(parts, h)+ } else if h := shellInlineEvalHint(command); h != "" {+ parts = append(parts, h)+ }+ return strings.Join(parts, "\n")+}++func shellMissingModuleHint(command, stderr string) string {+ if !isMissingInterpreterModule(stderr) {+ return ""+ }+ skill := skillNameFromShellCommand(command)+ skillArg := "skill_name=<the skill that owns those packages>"+ if skill != "" {+ skillArg = fmt.Sprintf("skill_name=%q", skill)+ }+ return "Hint: system python3 / node do not see skill packages (docx, pptx, pandas, …). " ++ "Do not pip install them into this session, and do not paste the same program into " ++ "`.venv/bin/python -c`. Write it with write_sandbox_file, then " ++ "execute_skill_script(" + skillArg + ", script_path=/workspace/output/inspect.py)."+}++func isMissingInterpreterModule(stderr string) bool {+ if isFrozenSkillVenvFailure(stderr) {+ return false+ }+ return strings.Contains(stderr, "ModuleNotFoundError") ||+ strings.Contains(stderr, "No module named") ||+ strings.Contains(stderr, "Cannot find module") ||+ strings.Contains(stderr, "MODULE_NOT_FOUND")+}++func shellInlineEvalHint(command string) string {+ if !isInlineInterpreterProgram(command) {+ return ""+ }+ skill := skillNameFromShellCommand(command)+ skillArg := "skill_name=..."+ if skill != "" {+ skillArg = fmt.Sprintf("skill_name=%q", skill)+ }+ return "Hint: do not pass a multi-line program through python -c / node -e " ++ "(including a skill venv). Write it with write_sandbox_file, then " ++ "execute_skill_script(" + skillArg + ", script_path=/workspace/output/inspect.py)."+}++func isInlineInterpreterProgram(command string) bool {+ if !hasInlineEvalFlag(command) {+ return false+ }+ return len(command) >= 280 || strings.Count(command, "\n") >= 2+}++func hasInlineEvalFlag(command string) bool {+ lower := strings.ToLower(command)+ pythonEval := strings.Contains(lower, "python") && strings.Contains(lower, " -c")+ nodeEval := strings.Contains(lower, "node") &&+ (strings.Contains(lower, " -e") || strings.Contains(lower, " --eval"))+ return pythonEval || nodeEval+}++func skillNameFromShellCommand(command string) string {+ idx := strings.Index(command, sandbox.SkillsImageRoot+"/")+ if idx < 0 {+ return ""+ }+ rest := command[idx:]+ if end := strings.IndexAny(rest, " \t\"'"); end > 0 {+ rest = rest[:end]+ }+ name, inImage := sandbox.SkillNameFromImagePath(rest)+ if !inImage {+ return ""+ }+ return name+}++// shellCommandNotFoundHint steers the model off apt-get install tree/editors+// after a 127. Those packages are not in the slim image (`file` is), and a+// session install is thrown away.+func shellCommandNotFoundHint(exitCode int, command, stderr string) string {+ if exitCode != 127 && !strings.Contains(strings.ToLower(stderr), "command not found") {+ return ""+ }+ missing := inferredMissingCommand(command, stderr)+ switch missing {+ case "tree", "less", "more", "nano", "vim", "vi":+ return "Hint: `" + missing + "` is not in the default sandbox image. Use find/ls, head, sed, and `file`. Skill scripts: `read_skill` / `execute_skill_script`. Do not apt-get install inspection tools — session packages are discarded."+ default:+ return "Hint: that command is not installed. Prefer find, ls, head, tail, cat, sed, grep, awk, file. apt-get install only for a package this task actually needs — session installs are discarded."+ }+}++func inferredMissingCommand(command, stderr string) string {+ lower := strings.ToLower(stderr)+ const marker = ": command not found"+ if i := strings.Index(lower, marker); i > 0 {+ head := strings.TrimSpace(stderr[:i])+ if j := strings.LastIndexAny(head, ": \t"); j >= 0 {+ head = strings.TrimSpace(head[j+1:])+ }+ if head != "" {+ return path.Base(head)+ }+ }+ fields := strings.Fields(command)+ if len(fields) == 0 {+ return ""+ }+ return path.Base(fields[0])+}+func resolveShellOutputLimit(requested int) int {if requested <= 0 {return defaultShellExecOutputBytesdiff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.goindex 24b4da009..0944a5af4 100644--- a/internal/agent/tools/shell_exec_test.go+++ b/internal/agent/tools/shell_exec_test.go@@ -17,6 +17,7 @@ type fakeShellExecutor struct {result *sandbox.ExecuteResulterr errortimeout time.Duration+ calls int}func (f *fakeShellExecutor) ExecShellCommand(@@ -28,6 +29,7 @@ func (f *fakeShellExecutor) ExecShellCommand(_ map[string]string,) (*sandbox.ExecuteResult, error) {f.timeout = timeout+ f.calls++if f.err != nil {return nil, f.err}@@ -70,15 +72,28 @@ func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) {type fakeInstallShellExecutor struct {timeout time.Duration+ calls int}func (f *fakeInstallShellExecutor) ExecShellCommandWithOptions(_ context.Context, _ string, _ string, opts sandbox.ShellExecOptions,) (*sandbox.ExecuteResult, error) {f.timeout = opts.Timeout+ f.calls++return &sandbox.ExecuteResult{ExitCode: 0}, nil}+func TestInstallShellExecDescriptionDoesNotPointAtWriteSandboxFile(t *testing.T) {+ description := NewInstallShellExecTool(&fakeInstallShellExecutor{}).Description()++ assert.Contains(t, description, "only tool")+ assert.Contains(t, description, "requirements.json")+ assert.Contains(t, description, sandbox.SkillsImageRoot)+ assert.NotContains(t, description, "Do NOT dump large files through")+ assert.NotContains(t, NewShellExecTool(&fakeShellExecutor{}, nil).Description(),+ "write_sandbox_file is not available")+}+func TestInstallShellExecDefaultsToTheTenMinuteBudget(t *testing.T) {inner := &fakeInstallShellExecutor{}tool := NewInstallShellExecTool(inner)@@ -146,11 +161,19 @@ func TestShellExecSuppressesBinaryStreams(t *testing.T) {func TestShellExecDescriptionSupportsGeneralExploration(t *testing.T) {description := NewShellExecTool(&fakeShellExecutor{}, nil).Description()- for _, command := range []string{"find", "file", "sed", "head", "tail", "cat", "grep", "awk"} {+ for _, command := range []string{"find", "ls", "cat", "head", "tail", "sed", "grep", "awk"} {assert.Contains(t, description, command)}assert.Contains(t, description, "Use freely to explore")assert.Contains(t, description, "Binary output is never returned")+ assert.Contains(t, description, "write_sandbox_file")+ assert.Contains(t, description, "edit_sandbox_file")+ assert.Contains(t, description, "/opt/weknora/tenant/skills")+ assert.Contains(t, description, "python3 -c")+ assert.Contains(t, description, "execute_skill_script")+ assert.Contains(t, description, ".skill-packages")+ assert.Contains(t, description, "Do not `apt-get install` inspection utilities")+ assert.NotContains(t, description, "If a 'command not found' error occurs, attempt to resolve it")}func TestShellExecBoundsStdoutStderrErrorAndTotal(t *testing.T) {@@ -344,3 +367,115 @@ func TestInstallShellExecDoesNotCapture(t *testing.T) {require.True(t, result.Success)require.Zero(t, recorder.calls)}++func TestShellExecOversizeCommandPointsAtWriteSandboxFile(t *testing.T) {+ command := strings.Repeat("a", shellExecMaxCommandBytes+1)+ raw, err := json.Marshal(map[string]string{"command": command})+ require.NoError(t, err)++ result, err := NewShellExecTool(&fakeShellExecutor{}, nil).Execute(+ shellExecTestContext(), raw,+ )++ require.NoError(t, err)+ require.False(t, result.Success)+ assert.Contains(t, result.Error, "command too long")+ assert.Contains(t, result.Error, "write_sandbox_file")+}++func TestShellExecHintsWhenTreeCommandIsMissing(t *testing.T) {+ tool := NewShellExecTool(&fakeShellExecutor{result: &sandbox.ExecuteResult{+ ExitCode: 127,+ Stderr: "/bin/bash: line 1: tree: command not found\n",+ }}, nil)++ result, err := tool.Execute(+ shellExecTestContext(),+ json.RawMessage(`{"command":"tree -L 2 /workspace/output"}`),+ )+ require.NoError(t, err)+ require.True(t, result.Success)+ assert.Equal(t, 127, result.Data["exit_code"])+ assert.Contains(t, result.Output, "not in the default sandbox image")+ assert.Contains(t, result.Output, "Use find/ls")+ assert.Contains(t, result.Output, "Do not apt-get install")+}++func TestInferredMissingCommandFromBashStderr(t *testing.T) {+ assert.Equal(t, "file", inferredMissingCommand(+ "file /tmp/x",+ "/bin/bash: line 1: file: command not found\n",+ ))+ assert.Equal(t, "tree", inferredMissingCommand("tree -L 2", "tree: command not found"))+}++func TestShellExecHintsWhenSystemPythonMissesASkillModule(t *testing.T) {+ script := `cd /workspace/output && python3 -c "+from docx import Document+doc = Document('brief.docx')+print(len(doc.paragraphs))+"`+ tool := NewShellExecTool(&fakeShellExecutor{result: &sandbox.ExecuteResult{+ ExitCode: 1,+ Stderr: "ModuleNotFoundError: No module named 'docx'\n",+ }}, nil)++ raw, err := json.Marshal(map[string]string{"command": script})+ require.NoError(t, err)+ result, err := tool.Execute(shellExecTestContext(), raw)+ require.NoError(t, err)+ require.True(t, result.Success)+ assert.Contains(t, result.Output, "Do not pip install")+ assert.Contains(t, result.Output, "write_sandbox_file")+ assert.Contains(t, result.Output, "execute_skill_script")+ assert.Contains(t, result.Output, ".venv/bin/python -c")+}++func TestSkillNameFromShellCommandExtractsImageSkill(t *testing.T) {+ assert.Equal(t, "meeting-and-brief", skillNameFromShellCommand(+ `/opt/weknora/tenant/skills/meeting-and-brief/.venv/bin/python -c "print(1)"`,+ ))+ assert.Empty(t, skillNameFromShellCommand(`python3 -c "print(1)"`))+}++func TestShellExecAllowsOverlayInstallThatMentionsTheSkillTree(t *testing.T) {+ // Previously an up-front command blacklist rejected this recovery path+ // because the line contained both `pip install` and the skills root.+ executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{ExitCode: 0}}+ tool := NewShellExecTool(executor, nil)++ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(+ `{"command":"python3 -m pip install --target /workspace/.skill-packages/foo -r /opt/weknora/tenant/skills/foo/requirements.txt"}`,+ ))+ require.NoError(t, err)+ require.True(t, result.Success, result.Error)+ assert.Equal(t, 1, executor.calls)+}++func TestInstallShellExecStillPipsIntoTheSkillTree(t *testing.T) {+ inner := &fakeInstallShellExecutor{}+ tool := NewInstallShellExecTool(inner)++ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(+ `{"command":"pip install python-docx","work_dir":"/opt/weknora/tenant/skills/律师助手"}`,+ ))+ require.NoError(t, err)+ require.True(t, result.Success, result.Error)+ require.Equal(t, 1, inner.calls)+}++func TestShellExecHintsWhenVenvHasNoPip(t *testing.T) {+ tool := NewShellExecTool(&fakeShellExecutor{result: &sandbox.ExecuteResult{+ ExitCode: 1,+ Stderr: "/opt/weknora/tenant/skills/律师助手/.venv/bin/python: No module named pip\n",+ }}, nil)++ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(+ `{"command":"/opt/weknora/tenant/skills/律师助手/.venv/bin/python /opt/weknora/tenant/skills/律师助手/scripts/install_deps.py --word --yes"}`,+ ))+ require.NoError(t, err)+ require.True(t, result.Success)+ assert.Contains(t, result.Output, "frozen")+ assert.Contains(t, result.Output, "/workspace/.skill-packages/律师助手")+ assert.NotContains(t, result.Output, "write_sandbox_file")+}diff --git a/internal/agent/tools/skill_execute.go b/internal/agent/tools/skill_execute.goindex aedb5e75d..24e5fcfd5 100644--- a/internal/agent/tools/skill_execute.go+++ b/internal/agent/tools/skill_execute.go@@ -4,10 +4,12 @@ import ("context""encoding/json""fmt"+ "path""strings""github.com/Tencent/WeKnora/internal/agent/skills""github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/types""github.com/Tencent/WeKnora/internal/utils")@@ -16,12 +18,16 @@ import (var executeSkillScriptTool = BaseTool{name: ToolExecuteSkillScript,- description: `Execute a script from a skill in a sandboxed environment.+ description: `Execute a script with a skill's own interpreter and dependencies.## Usage-- Use this tool to run utility scripts bundled with a skill-- Scripts are executed in an isolated sandbox for security-- Only scripts from loaded skills can be executed+- ` + "`script_path`" + ` is either:+ - a path **inside the skill** (` + "`scripts/analyze.py`" + `), or+ - an absolute session file you just wrote with ` + "`write_sandbox_file`" + `+ (` + "`/workspace/output/generate_ppt.py`" + `). That file still runs with+ this skill's virtualenv / node_modules.+- Do NOT pass ` + "`/workspace/input`" + ` paths as ` + "`script_path`" + `+ (attachments are inputs via ` + "`args`" + `).- User-uploaded files are listed in the current ` + "`<sandbox_attachments>`" + `block. Pass their absolute ` + "`/workspace/input/...`" + ` paths through` + "`args`" + ` when a script accepts an input file.@@ -32,16 +38,28 @@ var executeSkillScriptTool = BaseTool{node_modules from the script's location. A failed import under a bare` + "`python3 -c`" + ` or ` + "`node -e`" + ` says nothing about whether thistool can run the script.+- The skill tree is frozen after install. Do not run ` + "`install_deps.py`" + `+ (or ` + "`python -m pip`" + ` / ` + "`ensurepip`" + ` inside the skill ` + "`.venv`" + `) to+ fetch extras at chat time. If a package is missing, install it into+ ` + "`/workspace/.skill-packages/<skill_name>`" + ` with system ` + "`python3 -m pip install --target`" + `+ and call this tool again — PYTHONPATH already includes that directory.## When to Use- When a skill's instructions reference a utility script (e.g., "Run scripts/analyze_form.py")+- After ` + "`write_sandbox_file`" + ` / ` + "`edit_sandbox_file`" + ` customizes a skill+ script and you still need that skill's packages (python-pptx, pandas, …)- When automation or data processing is needed as part of skill workflow- For deterministic operations where script execution is more reliable than generating code+## When NOT to Use+- Do not use this for a standalone ` + "`/workspace`" + ` script that does not need a+ skill's packages — call ` + "`shell_exec`" + ` instead.+## Security- Scripts run in a sandboxed environment with limited permissions- Network access is disabled by default-- File access is restricted to the skill directory+- Bundled scripts stay inside the skill directory; session files must sit+ under ` + "`/workspace`" + ` and not under ` + "`/workspace/input`" + `## Returns- Script stdout and stderr output@@ -52,7 +70,7 @@ var executeSkillScriptTool = BaseTool{// ExecuteSkillScriptInput defines the input parameters for the execute_skill_script tooltype ExecuteSkillScriptInput struct {SkillName string `json:"skill_name" jsonschema:"Name of the skill containing the script"`- ScriptPath string `json:"script_path" jsonschema:"Relative path to the script within the skill directory (e.g. scripts/analyze.py)"`+ ScriptPath string `json:"script_path" jsonschema:"Relative path inside the skill (e.g. scripts/analyze.py), or an absolute /workspace/... file written with write_sandbox_file. Do not pass /workspace/input paths."`Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments. For file flags, pass an absolute path from the current <sandbox_attachments> block (/workspace/input/...). For in-memory data, use input instead."`Input string `json:"input,omitempty" jsonschema:"Optional input data to pass to the script via stdin. Use this when you have data in memory (e.g. JSON string) that the script should process. This is equivalent to piping data: echo 'data' | python script.py"`}@@ -140,6 +158,23 @@ func (t *ExecuteSkillScriptTool) Execute(ctx context.Context, args json.RawMessa}, nil}+ if _, ok := sandbox.RunnableWorkspaceScript(input.ScriptPath); !ok {+ rel, err := skillRelativeFilePath(input.SkillName, input.ScriptPath)+ if err != nil {+ return &types.ToolResult{+ Success: false,+ Error: err.Error(),+ }, nil+ }+ if rel == "" {+ return &types.ToolResult{+ Success: false,+ Error: "script_path is the skill directory; pass a relative script such as scripts/generate_ppt.py",+ }, nil+ }+ input.ScriptPath = rel+ }+// Check if skill manager is availableif t.skillManager == nil || !t.skillManager.IsEnabled() {return &types.ToolResult{@@ -202,6 +237,19 @@ func (t *ExecuteSkillScriptTool) Execute(ctx context.Context, args json.RawMessabuilder.WriteString("\n")}+ if hint := skillOnDemandInstallHint(input.SkillName, input.ScriptPath, result.Stdout, result.Stderr); hint != "" {+ builder.WriteString(hint)+ builder.WriteString("\n")+ } else if !result.IsSuccess() {+ if hint := pythonSyntaxErrorHint(result.Stderr); hint != "" {+ builder.WriteString(hint)+ builder.WriteString("\n")+ } else if hint := skillMissingPackageHint(input.SkillName, result.Stderr); hint != "" {+ builder.WriteString(hint)+ builder.WriteString("\n")+ }+ }+// Determine success based on exit codesuccess := result.IsSuccess()@@ -238,11 +286,14 @@ func (t *ExecuteSkillScriptTool) Execute(ctx context.Context, args json.RawMessafunc skillScriptCommand(input ExecuteSkillScriptInput) string {parts := make([]string, 0, 1+len(input.Args))+ script := strings.TrimSpace(input.ScriptPath)switch {- case input.SkillName != "" && input.ScriptPath != "":- parts = append(parts, input.SkillName+"/"+input.ScriptPath)- case input.ScriptPath != "":- parts = append(parts, input.ScriptPath)+ case strings.HasPrefix(path.Clean(script), "/workspace/"):+ parts = append(parts, script)+ case input.SkillName != "" && script != "":+ parts = append(parts, input.SkillName+"/"+script)+ case script != "":+ parts = append(parts, script)}parts = append(parts, input.Args...)return strings.Join(parts, " ")diff --git a/internal/agent/tools/skill_execute_test.go b/internal/agent/tools/skill_execute_test.gonew file mode 100644index 000000000..2b38fa13b--- /dev/null+++ b/internal/agent/tools/skill_execute_test.go@@ -0,0 +1,35 @@+package tools++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestSkillScriptCommandDoesNotJoinWorkspacePaths(t *testing.T) {+ got := skillScriptCommand(ExecuteSkillScriptInput{+ SkillName: "ppt-generator",+ ScriptPath: "/workspace/output/generate_rencui_ppt.py",+ Args: []string{"--flag"},+ })+ require.Equal(t, "/workspace/output/generate_rencui_ppt.py --flag", got)+ assert.NotContains(t, got, "ppt-generator/")+}++func TestSkillScriptCommandKeepsRelativeSkillPaths(t *testing.T) {+ got := skillScriptCommand(ExecuteSkillScriptInput{+ SkillName: "pdf",+ ScriptPath: "scripts/extract.py",+ })+ require.Equal(t, "pdf/scripts/extract.py", got)+}++func TestExecuteSkillScriptDescriptionAcceptsWorkspacePaths(t *testing.T) {+ assert.Contains(t, executeSkillScriptTool.Description(), "write_sandbox_file")+ assert.Contains(t, executeSkillScriptTool.Description(), "edit_sandbox_file")+ assert.Contains(t, executeSkillScriptTool.Description(), "/workspace/output")+ assert.Contains(t, executeSkillScriptTool.Description(), "/workspace/input")+ assert.Contains(t, executeSkillScriptTool.Description(), "install_deps.py")+ assert.Contains(t, executeSkillScriptTool.Description(), ".skill-packages")+}diff --git a/internal/agent/tools/skill_read.go b/internal/agent/tools/skill_read.goindex 37bd20d63..b80a0879f 100644--- a/internal/agent/tools/skill_read.go+++ b/internal/agent/tools/skill_read.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "path""strings""github.com/Tencent/WeKnora/internal/agent/skills"@@ -20,17 +21,25 @@ var readSkillTool = BaseTool{description: `Read skill content on demand to learn specialized capabilities.## Usage-- Use this tool when a user request matches an available skill's description-- Provide the skill_name to load the skill's full instructions (SKILL.md content)-- Optionally provide file_path to read additional files within the skill directory+- Call ` + "`read_skill(skill_name=...)`" + ` with no ` + "`file_path`" + ` to load+ SKILL.md **and** the skill's file list (scripts, docs, references).+ That listing is how you discover ` + "`scripts/generate_ppt.py`" + ` and similar.+- Then call ` + "`read_skill(skill_name=..., file_path=\"scripts/...\")`" + ` to+ read one file. ` + "`file_path`" + ` is relative inside the skill, not an+ absolute ` + "`/opt/weknora/tenant/skills/...`" + ` path.+- Do NOT use ` + "`list_sandbox_files`" + `, ` + "`read_sandbox_file`" + `, or+ ` + "`ls`" + ` on the skill install directory. Those tools only see+ ` + "`/workspace/output`" + ` and ` + "`/workspace/input`" + `; the skill tree also+ contains ` + "`.venv`" + ` / ` + "`node_modules`" + `.## When to Use- When the system prompt shows an available skill that matches the user's request- Before performing tasks that match a skill's description-- To read additional documentation or reference files within a skill+- To list or read documentation, templates, or scripts shipped with a skill## Returns-- Skill instructions and guidance for completing the task+- Skill instructions, the available file list, and (for installed skills)+ how to reach that skill's interpreter- File content if file_path is specified`,schema: utils.GenerateSchema[ReadSkillInput](),}@@ -38,7 +47,7 @@ var readSkillTool = BaseTool{// ReadSkillInput defines the input parameters for the read_skill tooltype ReadSkillInput struct {SkillName string `json:"skill_name" jsonschema:"Name of the skill to read"`- FilePath string `json:"file_path,omitempty" jsonschema:"Optional relative path to a specific file within the skill directory"`+ FilePath string `json:"file_path,omitempty" jsonschema:"Optional relative path inside the skill (e.g. scripts/generate_ppt.py). Omit to load SKILL.md and list files. Do not pass /opt/weknora/tenant/skills/... or /workspace paths."`}// ReadSkillTool allows the agent to read skill content on demand@@ -89,6 +98,23 @@ func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (*typvar resultData = make(map[string]interface{})if input.FilePath != "" {+ rel, err := skillRelativeFilePath(input.SkillName, input.FilePath)+ if err != nil {+ return &types.ToolResult{+ Success: false,+ Error: err.Error(),+ }, nil+ }+ input.FilePath = rel+ if input.FilePath == "" {+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf(+ "file_path is the skill directory; omit file_path and call read_skill(skill_name=%q) to list files",+ input.SkillName,+ ),+ }, nil+ }// Read a specific file from the skill directorycontent, err := t.skillManager.ReadSkillFile(ctx, input.SkillName, input.FilePath)if err != nil {@@ -132,7 +158,7 @@ func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (*typ// Add available files sectionif len(files) > 1 { // More than just SKILL.mdbuilder.WriteString("\n\n## Available Files\n\n")- builder.WriteString("The following files are available in this skill directory. Use `read_skill` with `file_path` to read them:\n\n")+ builder.WriteString("The following files are available in this skill directory. Use `read_skill` with `file_path` to read them (relative paths, e.g. scripts/foo.py). Do not list the skill directory with `list_sandbox_files` or `ls`:\n\n")for _, file := range files {if file != skills.SkillFileName { // Don't list SKILL.md againif skills.IsScript(file) {@@ -189,15 +215,64 @@ func skillEnvironmentSection(skillDir string) string {- This skill is installed at `+"`%s`"+` inside the sandbox, and itsdependencies live there with it, not in the sandbox's system interpreters.-- `+"`execute_skill_script`"+` already runs its scripts the right way. Prefer- it over invoking them yourself.+- `+"`execute_skill_script`"+` already runs its scripts the right way, including+ `+"`/workspace/...`"+` files you wrote that still need this skill's packages. Prefer+ it over invoking them yourself with a bare interpreter.+- Do NOT paste a program into `+"`python3 -c`"+` or into `+"`%s -c`"+`.+ Write it with `+"`write_sandbox_file`"+`, then+ `+"`execute_skill_script(skill_name=..., script_path=/workspace/output/....py)`"+`.+- Do NOT list or read that directory with `+"`list_sandbox_files`"+` /+ `+"`read_sandbox_file`"+` / `+"`ls`"+`: those tools only see `+"`/workspace/output`"+`+ and `+"`/workspace/input`"+`, and the skill tree includes `+"`.venv`"+` /+ `+"`node_modules`"+`. Call `+"`read_skill`"+` without `+"`file_path`"+` to list+ files, or with `+"`file_path`"+` to read one.- Do NOT decide from a system interpreter whether this skill can run, and do- NOT reinstall its dependencies with `+"`pip install`"+` / `+"`npm install`"+`:- those packages land in this session only and are lost with it.-- To inspect the environment yourself from `+"`shell_exec`"+`: for Python, run- `+"`%s`"+` instead of `+"`python3`"+`; for Node, run from `+"`%s`"+` as the- working directory so its `+"`node_modules`"+` resolves.-`, skillDir, sandbox.SkillVenvPython(skillDir), skillDir)+ NOT reinstall its dependencies with `+"`pip install`"+` / `+"`npm install`"+`+ into `+"`%s`"+` (that tree is frozen; `+"`uv venv`"+` often has no pip):+ `+"`chown`"+` / `+"`ensurepip`"+` / `+"`pip install`"+` there is rejected.+ On-demand extras (`+"`install_deps.py --word`"+`, python-docx, …) go to+ `+"`python3 -m pip install --target %s <package>`"+`, then+ `+"`execute_skill_script`"+` (PYTHONPATH already includes that directory).+ Or ask the user to reinstall the skill so extras are baked into the image.+`, skillDir, sandbox.SkillVenvPython(skillDir), skillDir, sandbox.SessionSkillPackageDir(path.Base(skillDir)))+}++// skillRelativeFilePath maps a model-supplied path onto a relative path+// inside skillName. Absolute /opt/weknora/tenant/skills/<name>/... paths and+// a redundant "<name>/..." prefix are accepted so a copied ls line still+// works. Workspace paths are rejected here; they belong to other tools.+func skillRelativeFilePath(skillName, filePath string) (string, error) {+ trimmed := strings.TrimSpace(filePath)+ if trimmed == "" {+ return "", nil+ }+ clean := path.Clean(trimmed)+ if path.IsAbs(trimmed) {+ dir, err := sandbox.SkillDirFor(skillName)+ if err == nil {+ if clean == dir {+ return "", nil+ }+ if strings.HasPrefix(clean, dir+"/") {+ return strings.TrimPrefix(clean, dir+"/"), nil+ }+ }+ if other, inImage := sandbox.SkillNameFromImagePath(clean); inImage && other != "" && other != skillName {+ return "", fmt.Errorf(+ "file_path belongs to skill %q; call read_skill(skill_name=%q, file_path=...)",+ other, other,+ )+ }+ return "", fmt.Errorf(+ "file_path must be relative inside the skill (e.g. scripts/generate_ppt.py), not %s",+ filePath,+ )+ }+ prefix := skillName + "/"+ if strings.HasPrefix(clean, prefix) {+ return strings.TrimPrefix(clean, prefix), nil+ }+ return clean, nil}// Cleanup releases any resources (implements Tool interface if needed)diff --git a/internal/agent/tools/skill_read_environment_test.go b/internal/agent/tools/skill_read_environment_test.goindex 4c0918f45..7c6e70961 100644--- a/internal/agent/tools/skill_read_environment_test.go+++ b/internal/agent/tools/skill_read_environment_test.go@@ -26,6 +26,13 @@ func TestSkillEnvironmentSectionNamesTheWayIntoBothEnvironments(t *testing.T) {require.Contains(t, section, dir)require.Contains(t, section, sandbox.SkillVenvPython(dir))require.Contains(t, section, "node_modules")+ require.Contains(t, section, "list_sandbox_files")+ require.Contains(t, section, "read_skill")+ require.Contains(t, section, "write_sandbox_file")+ require.Contains(t, section, "python3 -c")require.Contains(t, strings.ToLower(section), "pip install")require.Contains(t, strings.ToLower(section), "npm install")+ require.Contains(t, section, sandbox.SessionSkillPackageDir("smart-charts"))+ require.Contains(t, section, "install_deps.py")+ require.Contains(t, section, "frozen")}diff --git a/internal/agent/tools/skill_read_path_test.go b/internal/agent/tools/skill_read_path_test.gonew file mode 100644index 000000000..cabf91b0b--- /dev/null+++ b/internal/agent/tools/skill_read_path_test.go@@ -0,0 +1,38 @@+package tools++import (+ "testing"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestSkillRelativeFilePathNormalizesCopiedImagePaths(t *testing.T) {+ rel, err := skillRelativeFilePath("ppt-generator", "scripts/generate_ppt.py")+ require.NoError(t, err)+ assert.Equal(t, "scripts/generate_ppt.py", rel)++ rel, err = skillRelativeFilePath("ppt-generator", "ppt-generator/scripts/generate_ppt.py")+ require.NoError(t, err)+ assert.Equal(t, "scripts/generate_ppt.py", rel)++ rel, err = skillRelativeFilePath(+ "ppt-generator",+ sandbox.SkillsImageRoot+"/ppt-generator/scripts/generate_ppt.py",+ )+ require.NoError(t, err)+ assert.Equal(t, "scripts/generate_ppt.py", rel)++ rel, err = skillRelativeFilePath("ppt-generator", sandbox.SkillsImageRoot+"/ppt-generator")+ require.NoError(t, err)+ assert.Empty(t, rel)++ _, err = skillRelativeFilePath("ppt-generator", sandbox.SkillsImageRoot+"/other/scripts/x.py")+ require.Error(t, err)+ assert.Contains(t, err.Error(), `skill "other"`)++ _, err = skillRelativeFilePath("ppt-generator", "/workspace/output/x.py")+ require.Error(t, err)+ assert.Contains(t, err.Error(), "relative")+}diff --git a/internal/agent/tools/skill_runtime_guard.go b/internal/agent/tools/skill_runtime_guard.gonew file mode 100644index 000000000..2709c4989--- /dev/null+++ b/internal/agent/tools/skill_runtime_guard.go@@ -0,0 +1,78 @@+package tools++import (+ "strconv"+ "strings"++ "github.com/Tencent/WeKnora/internal/agent/skills"+ "github.com/Tencent/WeKnora/internal/sandbox"+)++// Session skill trees are snapshotted read-only (root-owned, mode 555). uv+// venv often has no pip. Skills that lazily pip-install extras on first use+// cannot write that venv; session agents must use the /workspace overlay+// instead of chown / ensurepip / pip into /opt/weknora/tenant/skills.+//+// That rule is enforced by the filesystem, not by inspecting commands: the+// kernel already refuses the write. What the model needs is a readable reason+// for the EROFS / EPERM / "No module named pip" it gets back, which is what+// the hints below attach after the fact. An up-front command blacklist was+// tried and removed: matching `pip install` next to the skills root also+// rejected the recovery command this guidance recommends (installing into the+// overlay with `-r <skill>/requirements.txt`), while any indirection through a+// shell variable walked straight past it.++func frozenSkillTreeGuidance(skillName string) string {+ pkgDir := sandbox.SessionSkillPackageDir(skillName)+ skillArg := "skill_name=<skill>"+ if skillName != "" {+ skillArg = "skill_name=" + strconv.Quote(skillName)+ }+ return "the skill tree under " + sandbox.SkillsImageRoot ++ " is frozen after install (read-only, root-owned; uv venv often has no pip). " ++ "Do not chown, chmod, ensurepip, or pip/npm install into it. " ++ "On-demand extras (python-docx, python-pptx, …) go in the session overlay: " ++ "`python3 -m pip install --target " + pkgDir + " <package>` " ++ "(system python3, not the skill venv), then execute_skill_script(" + skillArg + "). " ++ "Or ask the user to reinstall the skill so extras are baked into the image."+}++func isFrozenSkillVenvFailure(stderr string) bool {+ if stderr == "" {+ return false+ }+ lower := strings.ToLower(stderr)+ if strings.Contains(stderr, "No module named pip") ||+ strings.Contains(stderr, "No module named 'pip'") {+ return true+ }+ if strings.Contains(lower, "read-only file system") ||+ strings.Contains(lower, "erofs") ||+ strings.Contains(lower, "read-only filesystem") {+ return true+ }+ return strings.Contains(lower, "permission denied") && strings.Contains(lower, ".venv")+}++func skillOnDemandInstallHint(skillName, scriptPath, stdout, stderr string) string {+ installer := skills.IsOnDemandInstallerPath(scriptPath)+ failedInstaller := installer &&+ (isFrozenSkillVenvFailure(stderr) || strings.Contains(strings.ToLower(stdout+stderr), "安装失败") ||+ strings.Contains(strings.ToLower(stdout+stderr), "install failed"))+ if !failedInstaller && !isFrozenSkillVenvFailure(stderr) {+ return ""+ }+ msg := "Hint: " + frozenSkillTreeGuidance(skillName)+ if installer {+ msg += " Skip this installer and run the skill's real script."+ }+ return msg+}++func skillMissingPackageHint(skillName, stderr string) string {+ if !isMissingInterpreterModule(stderr) {+ return ""+ }+ return "Hint: this skill's frozen venv does not have that package. " ++ frozenSkillTreeGuidance(skillName)+}diff --git a/internal/agent/tools/skill_runtime_guard_test.go b/internal/agent/tools/skill_runtime_guard_test.gonew file mode 100644index 000000000..473cca761--- /dev/null+++ b/internal/agent/tools/skill_runtime_guard_test.go@@ -0,0 +1,39 @@+package tools++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestSkillOnDemandInstallHintSkipInstallerOnFrozenVenv(t *testing.T) {+ t.Parallel()++ hint := skillOnDemandInstallHint(+ "律师助手",+ "scripts/install_deps.py",+ "word 依赖: python-docx==1.1.2\nX word 安装失败 (exit 1)\n",+ "/opt/weknora/tenant/skills/律师助手/.venv/bin/python: No module named pip\n",+ )+ require.NotEmpty(t, hint)+ assert.Contains(t, hint, "/workspace/.skill-packages/律师助手")+ assert.Contains(t, hint, "python3 -m pip install --target")+ assert.Contains(t, hint, "Skip this installer")+}++func TestSkillMissingPackageHint(t *testing.T) {+ t.Parallel()++ hint := skillMissingPackageHint("律师助手", "ModuleNotFoundError: No module named 'docx'\n")+ require.NotEmpty(t, hint)+ assert.Contains(t, hint, "frozen venv")+ assert.Contains(t, hint, "/workspace/.skill-packages/律师助手")+}++func TestIsMissingInterpreterModuleIgnoresMissingPip(t *testing.T) {+ t.Parallel()++ assert.False(t, isMissingInterpreterModule("No module named pip"))+ assert.True(t, isMissingInterpreterModule("ModuleNotFoundError: No module named 'docx'\n"))+}diff --git a/internal/agent/tools/tool_policy_coverage_test.go b/internal/agent/tools/tool_policy_coverage_test.goindex cfc6d6a9d..546a97c00 100644--- a/internal/agent/tools/tool_policy_coverage_test.go+++ b/internal/agent/tools/tool_policy_coverage_test.go@@ -30,6 +30,11 @@ func TestEveryBuiltInToolDeclaresAModelHandlePolicy(t *testing.T) {ToolWebFetch,ToolExecuteSkillScript,ToolReadSkill,+ ToolListSandboxFiles,+ ToolReadSandboxFile,+ ToolWriteSandboxFile,+ ToolEditSandboxFile,+ ToolShellExec,ToolWikiReadPage,ToolWikiWritePage,ToolWikiReplaceText,diff --git a/internal/application/service/agent_memory_config_test.go b/internal/application/service/agent_memory_config_test.goindex b2fd00fc4..2cc5cf7fa 100644--- a/internal/application/service/agent_memory_config_test.go+++ b/internal/application/service/agent_memory_config_test.go@@ -45,4 +45,25 @@ func TestAgentConfigCarriesTheMemoryPreference(t *testing.T) {}}+func TestAgentConfigCarriesMaxCompletionTokens(t *testing.T) {+ svc := &sessionService{+ cfg: &config.Config{},+ webSearchProviderRepo: &sharedAgentWebSearchRepo{},+ }+ req := &types.QARequest{+ Session: &types.Session{ID: "session-1", TenantID: 1},+ CustomAgent: &types.CustomAgent{+ TenantID: 1,+ Config: types.CustomAgentConfig{+ MaxIterations: 5,+ MaxCompletionTokens: 64000,+ },+ },+ }++ agentConfig, err := svc.buildAgentConfig(t.Context(), req, &types.Tenant{ID: 1}, 1)+ require.NoError(t, err)+ require.Equal(t, 64000, agentConfig.MaxCompletionTokens)+}+func boolPtr(v bool) *bool { return &v }diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 2689dc4c4..d05209c2f 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -200,7 +200,7 @@ func (s *agentService) CreateAgentEngine(}s.registerMCPTools(ctx, toolRegistry, config, eventBus, sessionID, assistantMessageID)- // File inspection tools are a pure sandbox capability independent of the+ // File tools are a pure sandbox capability independent of the// skill switch: register them whenever the workspace sandbox supports a// session filesystem, even when skills are disabled.s.registerSandboxFileTools(ctx, toolRegistry, sessionID, config)@@ -381,27 +381,33 @@ func (s *agentService) resolveKBAndDocInfos(return kbInfos, selectedDocs}-// registerSandboxFileTools registers list_sandbox_files / read_sandbox_file.+// registerSandboxFileTools registers list_sandbox_files / read_sandbox_file /+// write_sandbox_file / edit_sandbox_file.//-// These expose per-session filesystem inspection and are a pure sandbox+// These expose per-session filesystem access and are a pure sandbox// capability, not a skill capability. They therefore do NOT follow// SkillsEnabled: an agent with skills disabled must still be able to read-// staged attachments out of /workspace/input. The tools themselves allow-// that directory (and /workspace/output). Registration only requires a-// non-disabled sandbox whose manager advertises a SessionFileStore. The-// skill installer agent also receives them (its remote sandbox advertises a-// file store), which is harmless — a root shell can already list and read the-// same tree.+// staged attachments out of /workspace/input, and to write generated files+// under /workspace. The tools themselves allow those directories (input is+// read-only). Registration only requires a non-disabled sandbox whose+// manager advertises a SessionFileStore.//-// It resolves the sandbox independently of initializeSkillsManager so the-// file tools are available even when skills are disabled and the skills-// manager is never built.+// The skill installer is the exception: write_sandbox_file only accepts+// /workspace, the installer must write .weknora/requirements.json under+// /opt/weknora/tenant/skills, and its prompt forbids touching /workspace+// (that tree is wiped before the snapshot). Offering the file tools made+// the first write of every install fail, then fall back to a shell heredoc.+// Install mode uses shell_exec alone.func (s *agentService) registerSandboxFileTools(ctx context.Context,toolRegistry *tools.ToolRegistry,sessionID string,config *types.AgentConfig,) {+ if config != nil && config.SkillInstallMode() {+ logger.Infof(ctx, "Skipping session file tools in skill install mode")+ return+ }sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config)if err != nil {logger.Warnf(ctx, "Failed to resolve sandbox for file tools: %v", err)@@ -413,10 +419,12 @@ func (s *agentService) registerSandboxFileTools(if store := sessionSandboxFileStore(sandboxMgr); store != nil {toolRegistry.RegisterTool(tools.NewListSandboxFilesTool(store))toolRegistry.RegisterTool(tools.NewReadSandboxFileTool(store))- logger.Infof(ctx, "Registered list_sandbox_files and read_sandbox_file tools")+ toolRegistry.RegisterTool(tools.NewWriteSandboxFileTool(store))+ toolRegistry.RegisterTool(tools.NewEditSandboxFileTool(store))+ logger.Infof(ctx, "Registered list_sandbox_files, read_sandbox_file, write_sandbox_file, and edit_sandbox_file tools")} else {logger.Infof(ctx, "Sandbox backend does not advertise session filesystem capability; "+- "list_sandbox_files/read_sandbox_file not registered")+ "list_sandbox_files/read_sandbox_file/write_sandbox_file/edit_sandbox_file not registered")}}@@ -986,7 +994,8 @@ func (s *agentService) registerTools(toolToRegister = tools.NewWikiDeletePageTool(s.wikiPageService, wikiKBIDs, wikiRoutes)case tools.ToolShellExec, tools.ToolReadSkill, tools.ToolExecuteSkillScript,- tools.ToolListSandboxFiles, tools.ToolReadSandboxFile:+ tools.ToolListSandboxFiles, tools.ToolReadSandboxFile, tools.ToolWriteSandboxFile,+ tools.ToolEditSandboxFile:// Bound to the resolved sandbox manager in registerSandboxFileTools// / registerSandboxShellIfAllowed / initializeSkillsManager.// Listing them here would warn "Unknown tool: shell_exec" on everydiff --git a/internal/application/service/agent_service_test.go b/internal/application/service/agent_service_test.goindex 0cee811c4..cc2fd420d 100644--- a/internal/application/service/agent_service_test.go+++ b/internal/application/service/agent_service_test.go@@ -88,6 +88,9 @@ func (stubSessionFileStore) ReadSessionFile(context.Context, string, string) ([]func (stubSessionFileStore) WriteSessionInputFile(context.Context, string, string, []byte) error {return nil}+func (stubSessionFileStore) WriteSessionWorkspaceFile(context.Context, string, string, []byte) error {+ return nil+}func (stubSessionFileStore) RemoveSessionInputPath(context.Context, string, string) error { return nil }func (s *fakeAgentKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID(@@ -125,10 +128,10 @@ func toolOffered(names []string, name string) bool {// TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode pins the skill// gate on the skill installer alone for shell_exec. shell_exec follows-// SkillsEnabled (it can execute skill scripts), while list_sandbox_files and-// read_sandbox_file are pure filesystem capabilities that follow the sandbox-// backend's SessionFileStore capability instead — so they are offered even-// when skills are disabled and to the installer agent.+// SkillsEnabled (or install mode). list/read/write/edit sandbox file tools+// follow SessionFileStore for ordinary agents, including when skills are+// disabled, but are withheld from the installer: those tools only accept+// /workspace, and the installer must write the skill tree via shell_exec.func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))@@ -140,8 +143,8 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {typ: sandbox.SandboxTypeCube,shell: &stubShellExecutor{},// The manager advertises a session file store, the way- // every real remote backend does. File tools are a pure- // sandbox capability, so the installer receives them too.+ // every real remote backend does. The installer still+ // must not receive those tools: they only write /workspace.files: stubSessionFileStore{},installShell: &stubInstallShellExecutor{},},@@ -162,9 +165,11 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))- require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles),- "file inspection is a sandbox capability, not a skill, so the installer keeps it")- require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles),+ "session file tools only accept /workspace; the installer must write the skill tree via shell_exec")+ require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolWriteSandboxFile))+ require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolEditSandboxFile))require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())})@@ -194,6 +199,8 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {"shell_exec follows SkillsEnabled; an agent with skills off gets no shell")require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolWriteSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolEditSandboxFile))require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())})@@ -221,6 +228,8 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolWriteSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolEditSandboxFile))require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())@@ -250,6 +259,8 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolWriteSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolEditSandboxFile))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))require.NotNil(t, engine.(*agent.AgentEngine).GetSkillsManager())@@ -373,6 +384,8 @@ func TestCreateAgentEngineShellFollowsSkillsEnabledWithoutInstalledSkills(t *tesrequire.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolWriteSandboxFile))+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolEditSandboxFile))require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())}diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.goindex 7ff76dcd1..fb09f4c89 100644--- a/internal/application/service/session_agent_qa.go+++ b/internal/application/service/session_agent_qa.go@@ -293,6 +293,7 @@ func (s *sessionService) buildAgentConfig(CitationEnabled: customAgent.Config.CitationEnabled,RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,LLMCallTimeout: customAgent.Config.LLMCallTimeout,+ MaxCompletionTokens: customAgent.Config.MaxCompletionTokens,RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory,SharedAgentReadOnly: req.SharedAgentReadOnly,}diff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.goindex cc19fd5c6..2fb1e21c6 100644--- a/internal/application/service/session_attachment_staging.go+++ b/internal/application/service/session_attachment_staging.go@@ -272,7 +272,7 @@ func buildSandboxAttachmentsPrompt(attachments []stagedSessionAttachment) stringescapeAttachmentXML(attachment.Path),)}- b.WriteString(" <instruction>Use these absolute paths as read-only inputs. Inspect them with read_sandbox_file or list_sandbox_files, or pass them to shell commands or skill script arguments when those tools are available. Write generated files only under $WEKNORA_SKILL_OUTPUT_DIR.</instruction>\n")+ b.WriteString(" <instruction>Use these absolute paths as read-only inputs. Inspect them with read_sandbox_file or list_sandbox_files, or pass them to shell commands or skill script arguments when those tools are available. Create generated files with write_sandbox_file; patch existing ones with edit_sandbox_file; put downloadable artifacts under $WEKNORA_SKILL_OUTPUT_DIR.</instruction>\n")b.WriteString("</sandbox_attachments>")return b.String()}diff --git a/internal/application/service/session_attachment_staging_test.go b/internal/application/service/session_attachment_staging_test.goindex 74c20ea4a..18706b761 100644--- a/internal/application/service/session_attachment_staging_test.go+++ b/internal/application/service/session_attachment_staging_test.go@@ -98,6 +98,9 @@ func (m *stagingSandboxManager) WriteSessionInputFile(_ context.Context, _ strinm.writes = append(m.writes, filePath)return nil}+func (m *stagingSandboxManager) WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error {+ return m.WriteSessionInputFile(ctx, sessionID, filePath, content)+}func (m *stagingSandboxManager) RemoveSessionInputPath(_ context.Context, _ string, targetPath string) error {for filePath := range m.files {if filePath == targetPath || strings.HasPrefix(filePath, targetPath+"/") {@@ -181,6 +184,8 @@ func TestBuildSandboxAttachmentsPromptEscapesMetadata(t *testing.T) {assert.Contains(t, prompt, `path="/workspace/input/hash/a.txt"`)assert.Contains(t, prompt, "read-only inputs")assert.Contains(t, prompt, "read_sandbox_file")+ assert.Contains(t, prompt, "write_sandbox_file")+ assert.Contains(t, prompt, "edit_sandbox_file")}func TestStageSessionAttachmentsResolvesURLFromTemporaryDocument(t *testing.T) {diff --git a/internal/application/service/tenant_skill_bundle.go b/internal/application/service/tenant_skill_bundle.goindex bfe9a36cd..65911e807 100644--- a/internal/application/service/tenant_skill_bundle.go+++ b/internal/application/service/tenant_skill_bundle.go@@ -15,7 +15,6 @@ import ("unicode""github.com/Tencent/WeKnora/internal/agent/skills"- "gopkg.in/yaml.v3")// ErrSkillBundleInvalid marks every rejection of an uploaded archive, so the@@ -42,6 +41,10 @@ type SkillBundle struct {SHA256 string// Files maps skill-root-relative paths to contents, SKILL.md included.Files map[string][]byte+ // FrontmatterRepaired is true when SKILL.md YAML had to be repaired+ // before it would parse. The original file is unchanged; the install+ // prompt tells the agent to mention this so the user can fix it.+ FrontmatterRepaired bool}// SkillBundleParseOptions relaxes the uploaded-zip rules for archives pulled@@ -272,12 +275,13 @@ func skillBundleFromFiles(archive []byte, files map[string][]byte) (*SkillBundle}return &SkillBundle{- Name: skill.Name,- Version: version,- Description: skill.Description,- Instructions: skill.Instructions,- SHA256: skillArchiveSHA256(archive),- Files: files,+ Name: skill.Name,+ Version: version,+ Description: skill.Description,+ Instructions: skill.Instructions,+ SHA256: skillArchiveSHA256(archive),+ Files: files,+ FrontmatterRepaired: skill.FrontmatterRepaired,}, nil}@@ -376,7 +380,7 @@ func parseSkillBundleVersion(manifest string) (string, error) {Version string `yaml:"version"`}frontmatter := strings.Join(lines[frontmatterStart+1:frontmatterEnd], "\n")- if err := yaml.Unmarshal([]byte(frontmatter), &metadata); err != nil {+ if _, err := skills.UnmarshalSkillFrontmatter(frontmatter, &metadata); err != nil {return "", err}return metadata.Version, nildiff --git a/internal/application/service/tenant_skill_bundle_test.go b/internal/application/service/tenant_skill_bundle_test.goindex 27ac13f4b..ed5aeefbe 100644--- a/internal/application/service/tenant_skill_bundle_test.go+++ b/internal/application/service/tenant_skill_bundle_test.go@@ -194,6 +194,69 @@ Use scripts/extract.py to pull text out of a PDF.require.Equal(t, "1.2.3", bundle.Version)})+ t.Run("uses slug when name is a display title", func(t *testing.T) {+ data := zipBundle(t, map[string]string{+ "SKILL.md": `---+name: Word / DOCX+slug: word-docx+version: 1.0.2+description: Create and edit Microsoft Word documents.+---+Use this skill for .docx files.+`,+ })++ bundle, err := ParseSkillBundle(data)++ require.NoError(t, err)+ require.Equal(t, "word-docx", bundle.Name)+ require.Equal(t, "1.0.2", bundle.Version)+ })++ t.Run("repairs version and description nested under name", func(t *testing.T) {+ data := zipBundle(t, map[string]string{+ "SKILL.md": `---+name: 命理大师+ version: 1.2.6+ description: |+ 全体系命理大师。+---+Use the scripts in this skill.+`,+ })++ bundle, err := ParseSkillBundle(data)++ require.NoError(t, err)+ require.True(t, bundle.FrontmatterRepaired)+ require.Equal(t, "命理大师", bundle.Name)+ require.Equal(t, "1.2.6", bundle.Version)+ require.Contains(t, bundle.Description, "全体系命理大师")+ })++ t.Run("rejects a SkillHub archive whose extra YAML is still invalid after repair", func(t *testing.T) {+ data := zipBundle(t, map[string]string{+ "SKILL.md": `---+name: 命理大师+ version: 1.2.6+ description: |+ 全体系命理大师。+metadata:+ openclaw:+ install:+ - kind: node+ package: iztro+---+Use the scripts in this skill.+`,+ })++ _, err := ParseSkillBundle(data)++ require.Error(t, err)+ require.ErrorIs(t, err, ErrSkillBundleInvalid)+ })+t.Run("tolerates a single top-level directory", func(t *testing.T) {data := zipBundle(t, map[string]string{"pdf-tools/SKILL.md": validSkillMD,diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.goindex 90438d993..0d0bcfb03 100644--- a/internal/application/service/tenant_skill_install.go+++ b/internal/application/service/tenant_skill_install.go@@ -16,6 +16,7 @@ import ("github.com/google/uuid""gorm.io/gorm"+ "github.com/Tencent/WeKnora/internal/agent/skills""github.com/Tencent/WeKnora/internal/agent/tools"apperrors "github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/event"@@ -1487,7 +1488,9 @@ Hard requirements:- Install dependencies for exactly this one skill.- Python dependencies must go into %s/.venv. Do not install into system Python.- Node dependencies must go under %s/node_modules. Do not install global packages unless no local alternative exists.-- Use shell_exec only. You may set work_dir to %s.+- Use shell_exec only (write_sandbox_file is not available and cannot write+ this tree). You may set work_dir to %s. Write .weknora/requirements.json+ with a short shell redirect after mkdir -p.- Each command has a 10-minute budget; you do not need to set timeout_sec.- When finished, report what you installed and any global/system packages you changed.- Declare the environment variables this skill reads AT RUN TIME. Read its scripts to decide;@@ -1503,16 +1506,70 @@ Hard requirements:WEKNORA_SESSION_INPUT_DIR: the sandbox injects those. Other WEKNORA_* names the skill reads(WEKNORA_API_KEY, WEKNORA_BASE_URL, WEKNORA_HOST, WEKNORA_TOKEN, WEKNORA_KB_ID) MUST be declared.+On-demand / optional extras MUST be installed now. After you finish, this+tree is made read-only and session agents cannot pip/npm into it (uv venv also+has no pip). Skills that ship scripts/install_deps.py or say "pip install when+the user needs Word/PPT" will fail at chat time unless those packages are+already in the venv.+- Create the venv with pip present: `+"`uv venv --seed %s/.venv`"+` (or `+"`python3 -m venv`"+`).+- Install requirements.txt / pyproject.toml with `+"`uv pip install`"+`.+- Read SKILL.md and any on-demand installer for extra packages (python-docx,+ python-pptx, …) and `+"`uv pip install`"+` every extra, not only the default set.+%s+- If an installer script needs --yes / --all / every extra flag, pass them.+%sThe server verifies the result itself before the image is kept, so report whatyou did rather than whether it passed. Verification parses every script withthe interpreter that would run it, resolves the imports each one executes onload, and checks every distribution named in requirements.txt is present in thevenv. It never runs the skill's code, so nothing is expected to answer --help.+Lazy imports and install_deps.py extras are invisible to that check — you still+have to install them.SKILL.md:%s`, skillDir, uvAvailable, skillDir, skillDir, skillDir,- requirementsPath, skillMD)+ requirementsPath, skillDir, formatOnDemandInstallers(bundle),+ formatFrontmatterRepairNote(bundle), skillMD)+}++// formatOnDemandInstallers names bundle files that install extras at first+// use, so the installer agent does not have to discover them by grepping.+func formatOnDemandInstallers(bundle *SkillBundle) string {+ names := bundleOnDemandInstallers(bundle)+ if len(names) == 0 {+ return "- Look for scripts named install_deps.py (or similar) even if they are not listed here."+ }+ quoted := make([]string, len(names))+ for i, name := range names {+ quoted[i] = "`" + name + "`"+ }+ return "- This archive ships on-demand installer(s): " + strings.Join(quoted, ", ") ++ ". Run each one now with non-interactive flags covering every extra."+}++func bundleOnDemandInstallers(bundle *SkillBundle) []string {+ if bundle == nil {+ return nil+ }+ var names []string+ for rel := range bundle.Files {+ if skills.IsOnDemandInstallerPath(rel) {+ names = append(names, rel)+ }+ }+ sort.Strings(names)+ return names+}++func formatFrontmatterRepairNote(bundle *SkillBundle) string {+ if bundle == nil || !bundle.FrontmatterRepaired {+ return ""+ }+ return "\nThe SKILL.md YAML frontmatter was automatically repaired " ++ "(keys nested under name, or an unquoted colon). Extra or still-broken " ++ "keys were not reconstructed. Mention this in your summary so the user " ++ "can fix the file.\n"}func (s *TenantSkillService) probeUv(ctx context.Context, mgr sandbox.Manager, sessionID string) bool {diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.goindex 342e803cf..62b33b7e0 100644--- a/internal/application/service/tenant_skill_install_test.go+++ b/internal/application/service/tenant_skill_install_test.go@@ -453,6 +453,31 @@ func TestBuildInstallPromptAsksForADeclarationWithoutValues(t *testing.T) {"a value the model invents would be stored as the workspace credential")require.Contains(t, prompt, "WEKNORA_API_KEY","the installer must be told credential names are declarable, or it writes {\"env\":[]}")+ require.Contains(t, prompt, "On-demand / optional extras MUST be installed now")+ require.Contains(t, prompt, "uv venv --seed")+ require.Contains(t, prompt, "install_deps.py")+ require.Contains(t, prompt, "write_sandbox_file is not available")+ require.Contains(t, prompt, "short shell redirect")+}++func TestBuildInstallPromptNamesOnDemandInstallerInTheArchive(t *testing.T) {+ fx := newInstallFixture(t)+ fx.bundle.Files["scripts/install_deps.py"] = []byte("print(1)\n")++ prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)++ require.Contains(t, prompt, "This archive ships on-demand installer(s)")+ require.Contains(t, prompt, "scripts/install_deps.py")+}++func TestBuildInstallPromptMentionsRepairedFrontmatter(t *testing.T) {+ fx := newInstallFixture(t)+ fx.bundle.FrontmatterRepaired = true++ prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)++ require.Contains(t, prompt, "YAML frontmatter was automatically repaired")+ require.Contains(t, prompt, "Mention this in your summary")}func TestInstallSkillRepoNormalizesStoredUserEnvPrincipal(t *testing.T) {@@ -2412,6 +2437,12 @@ func (m *installSandboxManager) WriteSessionInputFile(return m.WriteSessionFile(context.Background(), "", filePath, content)}+func (m *installSandboxManager) WriteSessionWorkspaceFile(+ ctx context.Context, sessionID, filePath string, content []byte,+) error {+ return m.WriteSessionFile(ctx, sessionID, filePath, content)+}+func (m *installSandboxManager) WriteSessionFile(_ context.Context, _ string, filePath string, content []byte,) error {diff --git a/internal/application/service/tenant_skill_verify.go b/internal/application/service/tenant_skill_verify.goindex f05595bbc..89df23ef0 100644--- a/internal/application/service/tenant_skill_verify.go+++ b/internal/application/service/tenant_skill_verify.go@@ -104,7 +104,7 @@ func (s *TenantSkillService) verifyScriptsLoad(return err}}- if scripts := sortedScriptPaths(bundle, ".js", ".mjs"); len(scripts) > 0 {+ if scripts := sortedScriptPaths(bundle, ".js", ".mjs", ".cjs"); len(scripts) > 0 {if err := s.execVerify(ctx, mgr, sessionID, skillDir, "node",skillNodeVerifyCommand(skillDir, scripts, nodeDependencyNames(bundle))); err != nil {return err@@ -206,7 +206,7 @@ func forEachScript(skillDir string, scripts []string, check string) string {// allScriptExtensions is every suffix the runtime knows how to execute, which// is what makes a bundle file a script the model can name.-var allScriptExtensions = []string{".py", ".js", ".mjs", ".sh"}+var allScriptExtensions = []string{".py", ".js", ".mjs", ".cjs", ".sh"}// sortedScriptPaths returns the bundle's files with any of the given suffixes,// in a stable order so the emitted command is deterministic.diff --git a/internal/im/tool_display.go b/internal/im/tool_display.goindex 778bbf072..992293f48 100644--- a/internal/im/tool_display.go+++ b/internal/im/tool_display.go@@ -49,6 +49,10 @@ var imToolNameLabels = map[string]string{"query_knowledge_graph": "知识图谱查询","read_skill": "读取技能","execute_skill_script": "执行技能脚本",+ "list_sandbox_files": "列出沙箱文件",+ "read_sandbox_file": "读取沙箱文件",+ "write_sandbox_file": "写入沙箱文件",+ "edit_sandbox_file": "编辑沙箱文件","shell_exec": "执行沙箱命令","data_analysis": "数据分析","data_schema": "数据结构",diff --git a/internal/modelcontext/tool_policy.go b/internal/modelcontext/tool_policy.goindex 556b9197a..3577eb09a 100644--- a/internal/modelcontext/tool_policy.go+++ b/internal/modelcontext/tool_policy.go@@ -156,6 +156,8 @@ var toolHandlePolicies = map[string]toolHandlePolicy{"shell_exec": {},"list_sandbox_files": {},"read_sandbox_file": {},+ "write_sandbox_file": {},+ "edit_sandbox_file": {},}// HasToolPolicy reports whether a tool has an explicit model-handle policy.diff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.goindex 00a80e21d..4067fcae4 100644--- a/internal/sandbox/capabilities.go+++ b/internal/sandbox/capabilities.go@@ -60,6 +60,12 @@ type SessionFileStore interface {// session's remote sandbox, provisioning the sandbox on first call.WriteSessionInputFile(ctx context.Context, sessionID, filePath string, content []byte) error+ // WriteSessionWorkspaceFile writes a model-authored file under+ // /workspace. /workspace/input stays read-only (attachments); everything+ // else under /workspace is accepted so generated scripts do not have to+ // travel through shell_exec heredocs.+ WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error+// RemoveSessionInputPath deletes a staged attachment. No-op when the// session has no live sandbox.RemoveSessionInputPath(ctx context.Context, sessionID, targetPath string) errordiff --git a/internal/sandbox/remote_sandbox.go b/internal/sandbox/remote_sandbox.goindex c7ca61914..e5257b369 100644--- a/internal/sandbox/remote_sandbox.go+++ b/internal/sandbox/remote_sandbox.go@@ -112,17 +112,16 @@ func (s *RemoteSandbox) ExecuteOnHandle(return nil, ErrInvalidScript}- // Skills installed into the image are already on disk; uploading them again- // would both waste a round trip and shadow the venv layout next to them.+ // Scripts already on disk skip upload so the skill venv layout is not+ // shadowed. Image paths derive the skill directory; workspace paths+ // require an explicit SkillDir so arbitrary files cannot inherit a+ // skill interpreter by accident.if remote := strings.TrimSpace(cfg.RemoteScriptPath); remote != "" {- skillDir, ok := SkillDirForImageScript(remote)+ skillDir, ok := InterpreterSkillDir(remote, cfg.SkillDir)if !ok {- // RemoteScriptPath is only trusted for installed image skills; rejecting- // other paths avoids silently executing arbitrary sandbox files with- // image-skill defaults when callers pass an unvalidated path.return nil, ErrInvalidScript}- command, baseArgs := SkillInterpreterCommand(skillDir, remote)+ command, baseArgs := SkillInterpreterCommand(skillDir, path.Clean(remote))request := RemoteExecRequest{Command: command,Args: append(baseArgs, cfg.Args...),@@ -240,7 +239,7 @@ func getInterpreter(scriptName string) string {return "python3"case ".sh", ".bash":return "bash"- case ".js":+ case ".js", ".mjs", ".cjs":return "node"case ".rb":return "ruby"diff --git a/internal/sandbox/remote_sandbox_test.go b/internal/sandbox/remote_sandbox_test.goindex 29ec2ee64..fbb1eb978 100644--- a/internal/sandbox/remote_sandbox_test.go+++ b/internal/sandbox/remote_sandbox_test.go@@ -74,3 +74,60 @@ func TestExecuteOnHandleRejectsRemoteScriptOutsideSkillRoot(t *testing.T) {require.Empty(t, writes)require.Empty(t, execs)}++func TestExecuteOnHandleRunsWorkspaceScriptWithExplicitSkillDir(t *testing.T) {+ ctx := context.Background()+ client := newFakeRemoteClient(SandboxTypeCube)+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})+ require.NoError(t, err)++ skillDir := mustSkillDir(t, "ppt-generator")+ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{+ RemoteScriptPath: "/workspace/output/generate_rencui_ppt.py",+ SkillDir: skillDir,+ Args: []string{"--flag"},+ })++ require.NoError(t, err)+ client.mu.Lock()+ writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)+ execs := append([]RemoteExecRequest(nil), client.execRequests...)+ client.mu.Unlock()+ require.Empty(t, writes, "a session workspace script must not be uploaded")+ require.Len(t, execs, 1)+ require.Equal(t, SessionWorkspaceRoot, execs[0].WorkDir)+ require.Contains(t, execs[0].Args[1], skillDir+"/.venv/bin/python")+ require.Contains(t, execs[0].Args[1], "/workspace/output/generate_rencui_ppt.py")+ require.Contains(t, execs[0].Args[len(execs[0].Args)-1], "--flag")+}++func TestExecuteOnHandleRejectsWorkspaceScriptWithoutSkillDir(t *testing.T) {+ ctx := context.Background()+ client := newFakeRemoteClient(SandboxTypeCube)+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})+ require.NoError(t, err)++ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{+ RemoteScriptPath: "/workspace/output/generate_ppt.py",+ })+ require.ErrorIs(t, err, ErrInvalidScript)+}++func TestExecuteOnHandleRejectsWorkspaceInputEvenWithSkillDir(t *testing.T) {+ ctx := context.Background()+ client := newFakeRemoteClient(SandboxTypeCube)+ sb := NewRemoteSandbox(client, RemoteCreateRequest{})+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})+ require.NoError(t, err)++ _, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{+ RemoteScriptPath: "/workspace/input/upload.py",+ SkillDir: mustSkillDir(t, "pdf"),+ })+ require.ErrorIs(t, err, ErrInvalidScript)+ client.mu.Lock()+ require.Empty(t, client.execRequests)+ client.mu.Unlock()+}diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex 6f69881d7..7a33bd982 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -184,12 +184,18 @@ type ExecuteConfig struct {SessionID string// RemoteScriptPath is an absolute path to a script that already exists- // inside the sandbox image (installed skills). When set, the executor- // skips the upload step and runs it in place. Only paths under a valid- // skill directory in SkillsImageRoot are accepted; script-content- // validation is skipped because the file is already on the image, so- // callers must have vetted the bundle at install time.+ // inside the sandbox. When set, the executor skips the upload step and+ // runs it in place. Accepted locations:+ // - an installed skill file under SkillsImageRoot (bundle vetted at install)+ // - a session-writable file under /workspace, not under /workspace/input,+ // which also requires SkillDir so the skill's interpreter is usedRemoteScriptPath string++ // SkillDir is the installed skill directory whose venv/node_modules+ // should run RemoteScriptPath. Required when RemoteScriptPath sits under+ // /workspace. Image-skill paths derive the directory from the script and+ // ignore this field.+ SkillDir string}// ExecuteResult contains the result of script executiondiff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.goindex ac2377d07..9c8215662 100644--- a/internal/sandbox/session_manager.go+++ b/internal/sandbox/session_manager.go@@ -513,6 +513,36 @@ func (m *SessionBoundManager) WriteSessionInputFile(return nil}+// WriteSessionWorkspaceFile writes a model-authored file into the session's+// remote sandbox, provisioning the sandbox on first call. Paths must sit+// under /workspace and must not land in /workspace/input.+func (m *SessionBoundManager) WriteSessionWorkspaceFile(+ ctx context.Context, sessionID, filePath string, content []byte,+) error {+ if err := m.requireRemoteBackend(); err != nil {+ return err+ }+ if strings.TrimSpace(sessionID) == "" {+ return errors.New("sandbox: session ID required for workspace write")+ }+ clean, err := cleanSessionWorkspaceWritePath(filePath)+ if err != nil {+ return err+ }+ handle, err := m.resolveSession(ctx, sessionID)+ if err != nil {+ return err+ }+ m.ensureSessionWorkspaceDirs(ctx, handle, SessionOutputRoot)+ if err := ignoreExistingDir(m.client.MakeDir(ctx, handle, path.Dir(clean))); err != nil {+ return fmt.Errorf("sandbox: create workspace directory: %w", err)+ }+ if err := m.client.WriteFile(ctx, handle, clean, content); err != nil {+ return fmt.Errorf("sandbox: write session file %s: %w", clean, err)+ }+ return nil+}+// RemoveSessionInputPath deletes a staged attachment. It is a no-op when the// session has no live sandbox and never provisions one.func (m *SessionBoundManager) RemoveSessionInputPath(@@ -970,6 +1000,26 @@ func cleanSessionInputPath(filePath string) (string, error) {)}+// cleanSessionWorkspaceWritePath keeps model-authored writes inside the+// session workspace and out of the attachment tree. Validation is lexical+// (path.Clean plus prefix checks), matching cleanSessionWorkDir.+func cleanSessionWorkspaceWritePath(filePath string) (string, error) {+ clean := path.Clean(strings.TrimSpace(filePath))+ if !path.IsAbs(clean) || clean == "." || clean == "/" {+ return "", fmt.Errorf("sandbox: workspace write path %q must be an absolute file path", filePath)+ }+ if clean == SessionWorkspaceRoot || clean == SessionOutputRoot || clean == SessionInputRoot {+ return "", fmt.Errorf("sandbox: workspace write path %q is a directory, not a file", filePath)+ }+ if !strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {+ return "", fmt.Errorf("sandbox: workspace write path %q is outside %s", filePath, SessionWorkspaceRoot)+ }+ if strings.HasPrefix(clean, SessionInputRoot+"/") {+ return "", fmt.Errorf("sandbox: session input %s is read-only", SessionInputRoot)+ }+ return clean, nil+}+// cleanSessionWorkDir keeps shell_exec inside directories we are willing to let// an agent work in. Ordinary sessions get /workspace only.//diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.goindex 0ed893431..26da57f45 100644--- a/internal/sandbox/session_manager_test.go+++ b/internal/sandbox/session_manager_test.go@@ -330,6 +330,55 @@ func TestSessionBoundManagerEndSessionTurnIgnoresCancel(t *testing.T) {require.False(t, active)}+func TestCleanSessionWorkspaceWritePathAcceptsWorkspaceAndRefusesInput(t *testing.T) {+ got, err := cleanSessionWorkspaceWritePath("/workspace/output/generate_ppt.py")+ require.NoError(t, err)+ require.Equal(t, "/workspace/output/generate_ppt.py", got)++ got, err = cleanSessionWorkspaceWritePath("/workspace/scratch/gen.py")+ require.NoError(t, err)+ require.Equal(t, "/workspace/scratch/gen.py", got)++ _, err = cleanSessionWorkspaceWritePath("/workspace/input/report.txt")+ require.Error(t, err)+ _, err = cleanSessionWorkspaceWritePath("/workspace/output")+ require.Error(t, err)+ _, err = cleanSessionWorkspaceWritePath("/etc/passwd")+ require.Error(t, err)+ _, err = cleanSessionWorkspaceWritePath("relative.py")+ require.Error(t, err)+}++func TestWriteSessionWorkspaceFileWritesUnderOutput(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))+ mgr, client := newSessionManagerExecTestHarness(t)++ require.NoError(t, mgr.WriteSessionWorkspaceFile(+ ctx, "sess-1", "/workspace/output/generate_ppt.py", []byte("print(1)\n"),+ ))++ client.mu.Lock()+ writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)+ client.mu.Unlock()+ require.Len(t, writes, 1)+ require.Equal(t, "/workspace/output/generate_ppt.py", writes[0].path)+ require.Equal(t, []byte("print(1)\n"), writes[0].content)+}++func TestWriteSessionWorkspaceFileRefusesSessionInput(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))+ mgr, client := newSessionManagerExecTestHarness(t)++ err := mgr.WriteSessionWorkspaceFile(+ ctx, "sess-1", "/workspace/input/secret.txt", []byte("nope"),+ )+ require.Error(t, err)+ client.mu.Lock()+ n := len(client.writeFiles)+ client.mu.Unlock()+ require.Zero(t, n)+}+func TestWriteSessionFileSucceedsWhenInstallDirectoryAlreadyExists(t *testing.T) {ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))mgr, client := newSessionManagerExecTestHarness(t)diff --git a/internal/sandbox/skill_paths.go b/internal/sandbox/skill_paths.goindex 837a6ebf4..fa7c8f00d 100644--- a/internal/sandbox/skill_paths.go+++ b/internal/sandbox/skill_paths.go@@ -66,23 +66,98 @@ func SkillRequirementsPath(skillName string) string {return path.Join(dir, ".weknora", "requirements.json")}+// RunnableWorkspaceScript reports whether scriptPath is a session-writable+// file under /workspace that may be executed with an installed skill's+// interpreter. /workspace/input is reserved for attachments and is excluded;+// so are the workspace directory roots themselves.+func RunnableWorkspaceScript(scriptPath string) (string, bool) {+ clean := path.Clean(strings.TrimSpace(scriptPath))+ if clean == SessionWorkspaceRoot || clean == SessionOutputRoot || clean == SessionInputRoot {+ return "", false+ }+ if !strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {+ return "", false+ }+ if strings.HasPrefix(clean, SessionInputRoot+"/") {+ return "", false+ }+ return clean, true+}++// ValidatedImageSkillDir reports whether skillDir is exactly one installed+// skill directory under SkillsImageRoot (for example /opt/weknora/tenant/skills/pdf).+func ValidatedImageSkillDir(skillDir string) (string, bool) {+ clean := path.Clean(strings.TrimSpace(skillDir))+ expected, err := SkillDirFor(path.Base(clean))+ if err != nil || expected != clean {+ return "", false+ }+ return clean, true+}++// InterpreterSkillDir chooses the skill directory whose venv/node_modules+// should run remote. Image-skill scripts always win from the path so a+// mismatched SkillDir cannot redirect them. Workspace scripts require an+// explicit, validated SkillDir.+func InterpreterSkillDir(remotePath, skillDir string) (string, bool) {+ if dir, ok := SkillDirForImageScript(remotePath); ok {+ return dir, true+ }+ if _, ok := RunnableWorkspaceScript(remotePath); !ok {+ return "", false+ }+ return ValidatedImageSkillDir(skillDir)+}++// SkillNameFromImagePath reports whether p sits at or under SkillsImageRoot.+// The skills root itself returns ("", true). A skill directory or a file+// inside one returns (skillName, true). Paths outside the image return+// ("", false).+func SkillNameFromImagePath(p string) (name string, inImage bool) {+ clean := path.Clean(strings.TrimSpace(p))+ root := path.Clean(SkillsImageRoot)+ if clean == root {+ return "", true+ }+ prefix := root + "/"+ if !strings.HasPrefix(clean, prefix) {+ return "", false+ }+ name = strings.SplitN(strings.TrimPrefix(clean, prefix), "/", 2)[0]+ if !IsValidSkillName(name) {+ return "", false+ }+ return name, true+}+// SkillDirForImageScript returns the owning skill directory for an image script.// It anchors on SkillsImageRoot so nested script layouts still use the venv that// was installed beside the skill, not a shallower scripts directory.func SkillDirForImageScript(scriptPath string) (string, bool) {- cleanRoot := path.Clean(SkillsImageRoot)- cleanScript := path.Clean(scriptPath)- prefix := cleanRoot + "/"- if !strings.HasPrefix(cleanScript, prefix) {+ name, inImage := SkillNameFromImagePath(scriptPath)+ if !inImage || name == "" {return "", false}-- rest := strings.TrimPrefix(cleanScript, prefix)- parts := strings.SplitN(rest, "/", 2)- if len(parts) != 2 || parts[0] == "" || !IsValidSkillName(parts[0]) {+ clean := path.Clean(strings.TrimSpace(scriptPath))+ dir, err := SkillDirFor(name)+ if err != nil || clean == dir {return "", false}- return path.Join(cleanRoot, parts[0]), true+ return dir, true+}++// SessionSkillPackageDir is the per-session extra-packages overlay for one+// skill. The image venv is frozen after install (root-owned, mode 555, and+// often created with `uv venv` so it has no pip). Skills that lazily+// `pip install` on first use cannot write there; packages installed with+// `python3 -m pip install --target` this directory are visible to+// execute_skill_script via PYTHONPATH / NODE_PATH. The directory is under+// /workspace so it dies with the session and never mutates the snapshot.+func SessionSkillPackageDir(skillName string) string {+ if !IsValidSkillName(skillName) {+ return path.Join(SessionWorkspaceRoot, ".skill-packages")+ }+ return path.Join(SessionWorkspaceRoot, ".skill-packages", skillName)}// SkillVenvPython is where a skill's own Python interpreter lives when the@@ -111,7 +186,7 @@ func SkillInterpreterCommand(skillDir, scriptPath string) (string, []string) {`if [ -x %s ]; then exec %s %s "$@"; else exec python3 %s "$@"; fi`,ShellQuote(venvPython), ShellQuote(venvPython), script, script,), skillShellArgv0}- case ".js", ".mjs":+ case ".js", ".mjs", ".cjs":return "node", []string{scriptPath}case ".sh":return "/bin/sh", []string{scriptPath}diff --git a/internal/sandbox/skill_paths_test.go b/internal/sandbox/skill_paths_test.goindex c4f92f15d..97ae6a4b5 100644--- a/internal/sandbox/skill_paths_test.go+++ b/internal/sandbox/skill_paths_test.go@@ -15,6 +15,11 @@ func TestSkillDirFor(t *testing.T) {require.Equal(t, "/opt/weknora/tenant/skills/sk-1", dir)}+func TestSessionSkillPackageDir(t *testing.T) {+ require.Equal(t, "/workspace/.skill-packages/律师助手", SessionSkillPackageDir("律师助手"))+ require.Equal(t, "/workspace/.skill-packages", SessionSkillPackageDir("../escape"))+}+func TestSkillDirForRejectsPathEscape(t *testing.T) {for _, name := range []string{"", ".", "..", "../x", "foo/bar", `foo\bar`, "foo/../bar"} {_, err := SkillDirFor(name)@@ -22,6 +27,26 @@ func TestSkillDirForRejectsPathEscape(t *testing.T) {}}+func TestSkillNameFromImagePath(t *testing.T) {+ name, ok := SkillNameFromImagePath(SkillsImageRoot)+ require.True(t, ok)+ require.Empty(t, name)++ name, ok = SkillNameFromImagePath(SkillsImageRoot + "/ppt-generator")+ require.True(t, ok)+ require.Equal(t, "ppt-generator", name)++ name, ok = SkillNameFromImagePath(SkillsImageRoot + "/ppt-generator/scripts/generate_ppt.py")+ require.True(t, ok)+ require.Equal(t, "ppt-generator", name)++ _, ok = SkillNameFromImagePath("/workspace/output/x.py")+ require.False(t, ok)++ _, ok = SkillNameFromImagePath("/etc/passwd")+ require.False(t, ok)+}+func TestSkillDirForImageScript(t *testing.T) {t.Run("flat script path resolves to skill directory", func(t *testing.T) {skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/sk-1/run.py")@@ -41,6 +66,12 @@ func TestSkillDirForImageScript(t *testing.T) {require.Empty(t, skillDir)})+ t.Run("skill directory itself is not an image script", func(t *testing.T) {+ skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/sk-1")+ require.False(t, ok)+ require.Empty(t, skillDir)+ })+t.Run("dot-dot after clean that leaves the skills root is rejected", func(t *testing.T) {skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/../workspace/run.py")require.False(t, ok)@@ -48,6 +79,66 @@ func TestSkillDirForImageScript(t *testing.T) {})}+func TestRunnableWorkspaceScript(t *testing.T) {+ okPath, ok := RunnableWorkspaceScript("/workspace/output/generate_ppt.py")+ require.True(t, ok)+ require.Equal(t, "/workspace/output/generate_ppt.py", okPath)++ scratch, ok := RunnableWorkspaceScript("/workspace/scratch.py")+ require.True(t, ok)+ require.Equal(t, "/workspace/scratch.py", scratch)++ for _, p := range []string{+ "/workspace",+ "/workspace/output",+ "/workspace/input",+ "/workspace/input/upload.py",+ "/opt/weknora/tenant/skills/pdf/scripts/run.py",+ "/etc/passwd",+ "",+ } {+ _, ok := RunnableWorkspaceScript(p)+ require.False(t, ok, "path %q must not be a runnable workspace script", p)+ }+}++func TestValidatedImageSkillDir(t *testing.T) {+ dir, ok := ValidatedImageSkillDir(SkillsImageRoot + "/pdf")+ require.True(t, ok)+ require.Equal(t, SkillsImageRoot+"/pdf", dir)++ for _, p := range []string{+ SkillsImageRoot,+ SkillsImageRoot + "/pdf/scripts",+ "/workspace/output",+ "/opt/weknora/tenant/skills/../skills/pdf/x",+ "",+ } {+ _, ok := ValidatedImageSkillDir(p)+ require.False(t, ok, "dir %q must not validate as an image skill directory", p)+ }+}++func TestInterpreterSkillDir(t *testing.T) {+ imageDir, ok := InterpreterSkillDir(SkillsImageRoot+"/pdf/scripts/run.py", SkillsImageRoot+"/other")+ require.True(t, ok)+ require.Equal(t, SkillsImageRoot+"/pdf", imageDir,+ "an image script must derive SkillDir from the path, not the caller field")++ workspaceDir, ok := InterpreterSkillDir("/workspace/output/foo.py", SkillsImageRoot+"/pdf")+ require.True(t, ok)+ require.Equal(t, SkillsImageRoot+"/pdf", workspaceDir)++ _, ok = InterpreterSkillDir("/workspace/output/foo.py", "")+ require.False(t, ok, "workspace scripts require an explicit skill directory")++ _, ok = InterpreterSkillDir("/workspace/input/x.py", SkillsImageRoot+"/pdf")+ require.False(t, ok)++ _, ok = InterpreterSkillDir("/etc/passwd", SkillsImageRoot+"/pdf")+ require.False(t, ok)+}+func TestSkillInterpreterCommand(t *testing.T) {dir := mustSkillDir(t, "sk-1")@@ -63,9 +154,11 @@ func TestSkillInterpreterCommand(t *testing.T) {})t.Run("javascript uses node", func(t *testing.T) {- cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.js")- require.Equal(t, "node", cmd)- require.Equal(t, []string{dir + "/scripts/run.js"}, args)+ for _, name := range []string{"run.js", "run.mjs", "run.cjs"} {+ cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/"+name)+ require.Equal(t, "node", cmd, name)+ require.Equal(t, []string{dir + "/scripts/" + name}, args, name)+ }})t.Run("shell scripts run with sh", func(t *testing.T) {diff --git a/internal/types/agent.go b/internal/types/agent.goindex 9dbfa28fb..9f4f4f331 100644--- a/internal/types/agent.go+++ b/internal/types/agent.go@@ -11,6 +11,24 @@ import (// DefaultMaxContextTokens is the default context window budget for agent conversations (200k).const DefaultMaxContextTokens = 200000+// DefaultAgentMaxCompletionTokens is the per-round completion budget for+// ReAct / tool-calling agents. When MaxTokens is omitted, OpenAI-compatible+// providers (and many Chinese gateways) default to 4096 — large tool-call JSON+// such as write_sandbox_file is then truncated mid-stream (finish_reason=length),+// which surfaces as missing required arguments. 32768 matches wiki ingest (#2604).+const DefaultAgentMaxCompletionTokens = 32768++// AgentRoundMaxCompletionTokens returns the completion-token budget for one+// ReAct LLM round. Zero (unset) uses DefaultAgentMaxCompletionTokens. An+// explicit configured value is honored as-is so a user who capped a small+// local model at 4096 is not silently sent 32768.+func AgentRoundMaxCompletionTokens(configured int) int {+ if configured <= 0 {+ return DefaultAgentMaxCompletionTokens+ }+ return configured+}+// AgentConfig represents the full agent configuration (used at tenant level and runtime)// This includes all configuration parameters for agent executiontype AgentConfig struct {@@ -71,6 +89,10 @@ type AgentConfig struct {// LLM call timeout in seconds (default: 120). Controls the maximum time for a single LLM call.LLMCallTimeout int `json:"llm_call_timeout,omitempty"`+ // Maximum completion tokens for each ReAct LLM round. Zero means+ // DefaultAgentMaxCompletionTokens. Explicit values are sent as-is.+ MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`+// Maximum character length for tool output (default: 16000).// Outputs exceeding this limit are truncated with head + tail preservation.MaxToolOutputChars int `json:"max_tool_output_chars,omitempty"`diff --git a/internal/types/agent_test.go b/internal/types/agent_test.goindex 383e9511b..ceb338f9a 100644--- a/internal/types/agent_test.go+++ b/internal/types/agent_test.go@@ -75,3 +75,18 @@ func TestUseCustomSystemPromptFlag(t *testing.T) {t.Errorf("expected 'custom prompt', got %q", got)}}++func TestAgentRoundMaxCompletionTokens(t *testing.T) {+ if got := AgentRoundMaxCompletionTokens(0); got != DefaultAgentMaxCompletionTokens {+ t.Fatalf("zero configured = %d, want %d", got, DefaultAgentMaxCompletionTokens)+ }+ if got := AgentRoundMaxCompletionTokens(2048); got != 2048 {+ t.Fatalf("explicit 2048 = %d, want 2048", got)+ }+ if got := AgentRoundMaxCompletionTokens(4096); got != 4096 {+ t.Fatalf("explicit 4096 = %d, want 4096", got)+ }+ if got := AgentRoundMaxCompletionTokens(64000); got != 64000 {+ t.Fatalf("explicit high value = %d, want 64000", got)+ }+}diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.goindex fe7c50a7d..9929e771d 100644--- a/internal/types/custom_agent.go+++ b/internal/types/custom_agent.go@@ -123,7 +123,9 @@ type CustomAgentConfig struct {RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"`// Temperature for LLM (0-1)Temperature float64 `yaml:"temperature" json:"temperature"`- // Maximum completion tokens (only for normal mode)+ // Maximum completion tokens. Quick-answer uses this for the RAG answer.+ // Smart-reasoning ReAct rounds send this value as-is (zero becomes+ // DefaultAgentMaxCompletionTokens at call time).MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"`// Whether to enable thinking mode (for models that support extended thinking)Thinking *bool `yaml:"thinking" json:"thinking"`@@ -524,7 +526,11 @@ func (a *CustomAgent) EnsureDefaults() {a.Config.FallbackStrategy = "model"}if a.Config.MaxCompletionTokens == 0 {- a.Config.MaxCompletionTokens = 2048+ if a.Config.AgentMode == AgentModeSmartReasoning {+ a.Config.MaxCompletionTokens = DefaultAgentMaxCompletionTokens+ } else {+ a.Config.MaxCompletionTokens = 2048+ }}// Agent mode should always enable multi-turn conversationif a.Config.AgentMode == AgentModeSmartReasoning {diff --git a/internal/types/custom_agent_test.go b/internal/types/custom_agent_test.goindex 83e667734..363f389eb 100644--- a/internal/types/custom_agent_test.go+++ b/internal/types/custom_agent_test.go@@ -40,6 +40,31 @@ func TestEnsureDefaults_ThinkingPreservesTrue(t *testing.T) {}}+func TestEnsureDefaults_MaxCompletionTokensByMode(t *testing.T) {+ qa := &CustomAgent{Config: CustomAgentConfig{AgentMode: AgentModeQuickAnswer}}+ qa.EnsureDefaults()+ if qa.Config.MaxCompletionTokens != 2048 {+ t.Fatalf("quick-answer default MaxCompletionTokens = %d, want 2048", qa.Config.MaxCompletionTokens)+ }++ sr := &CustomAgent{Config: CustomAgentConfig{AgentMode: AgentModeSmartReasoning}}+ sr.EnsureDefaults()+ if sr.Config.MaxCompletionTokens != DefaultAgentMaxCompletionTokens {+ t.Fatalf("smart-reasoning default MaxCompletionTokens = %d, want %d",+ sr.Config.MaxCompletionTokens, DefaultAgentMaxCompletionTokens)+ }++ explicit := &CustomAgent{Config: CustomAgentConfig{+ AgentMode: AgentModeSmartReasoning,+ MaxCompletionTokens: 64000,+ }}+ explicit.EnsureDefaults()+ if explicit.Config.MaxCompletionTokens != 64000 {+ t.Fatalf("EnsureDefaults must preserve explicit MaxCompletionTokens, got %d",+ explicit.Config.MaxCompletionTokens)+ }+}+func TestEnsureDefaults_CitationsDefaultEnabledAndPreserveFalse(t *testing.T) {legacy := &CustomAgent{Config: CustomAgentConfig{}}legacy.EnsureDefaults()