From dd647fefad9948f5b8ecec41f5ccb27d79986534 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 2 Sep 2026 14:33:26 +0800 Subject: [PATCH] refactor(skills): introduce write_skill_file and edit_skill_file tools for skill directory management - Added write_skill_file and edit_skill_file tools to facilitate writing and editing files directly within the skill directory during installation. - Updated the agent service to register these tools exclusively for the built-in skill installer, ensuring they operate within the correct scope. - Enhanced error handling and validation to prevent unauthorized file access outside the designated skill directory. - Improved documentation and prompts to clarify usage and limitations of the new tools, emphasizing the importance of proving import resolutions by executing them. - Added tests to validate the functionality and security of the new file management tools. --- config/builtin_agents.yaml | 7 + .../prompt_templates/agent_system_prompt.yaml | 17 +- internal/agent/tools/definitions.go | 10 + internal/agent/tools/python_syntax.go | 9 +- internal/agent/tools/python_syntax_test.go | 7 +- internal/agent/tools/sandbox_edit.go | 2 +- internal/agent/tools/sandbox_write.go | 2 +- internal/agent/tools/shell_exec.go | 61 ++- internal/agent/tools/shell_exec_test.go | 74 +++- internal/agent/tools/skill_file.go | 413 ++++++++++++++++++ internal/agent/tools/skill_file_test.go | 195 +++++++++ .../agent/tools/tool_policy_coverage_test.go | 2 + internal/application/service/agent_service.go | 60 ++- .../agent_service_install_shell_test.go | 10 +- .../application/service/agent_service_test.go | 2 +- .../service/tenant_skill_install.go | 121 +++-- .../service/tenant_skill_install_test.go | 49 ++- .../service/tenant_skill_verify.go | 53 ++- .../service/tenant_skill_verify.py | 389 +---------------- .../tenant_skill_verify_python_test.go | 340 +++++--------- internal/modelcontext/tool_policy.go | 4 + internal/types/agent.go | 29 +- 22 files changed, 1146 insertions(+), 710 deletions(-) create mode 100644 internal/agent/tools/skill_file.go create mode 100644 internal/agent/tools/skill_file_test.go diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml index 9a9ea5a1..6716fba7 100644 --- a/config/builtin_agents.yaml +++ b/config/builtin_agents.yaml @@ -261,8 +261,15 @@ builtin_agents: max_iterations: 30 kb_selection_mode: "none" retrieve_kb_only_when_mentioned: false + # The install path unions these three in regardless of what is written + # here: an install that cannot write its own skill directory cannot + # record what it did. They are listed for accuracy, not as the source of + # truth. write_skill_file / edit_skill_file reach only the one skill + # being installed and are never offered to a tenant-editable agent. allowed_tools: - "shell_exec" + - "write_skill_file" + - "edit_skill_file" web_search_enabled: false web_search_max_results: 0 reflection_enabled: false diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index b9c8ed5d..786ad18d 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -516,9 +516,19 @@ templates: 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 ), including on-demand extras (see ). - 4. Reply with a short summary: what you installed, where it went. + 4. PROVE the imports resolve by running them (see ). Do not skip this: nothing else can check it. + 5. Reply with a short summary: what you installed, where it went, and anything you had to change in the skill's own files. + + You are the only party that can tell whether this skill's imports actually resolve. The server's check parses files without executing them, so it never finds out — it will not catch an import you left broken. + - For each script the skill offers, run the import the way the skill would: `/.venv/bin/python -c 'import x'`, or the script's own `--help` if it has one. + - A failure is usually one of two things. A missing distribution: install it. Or a module the skill SHIPS that Python cannot find — then the script needs its directory on `sys.path`. + - Prefer installing over editing. Editing a shipped source file is a last resort with a real cost: `read_skill` serves the uploaded archive while scripts run from this image, so a later session would read one version of that file and run another. If you must edit one with `edit_skill_file`, keep the change as small as possible and name the file in your summary so the user can fix the archive. + - Import names and distribution names differ often: PIL → pillow, yaml → pyyaml, docx → python-docx, pptx → python-pptx, cv2 → opencv-python-headless, bs4 → beautifulsoup4, sklearn → scikit-learn, fitz → pymupdf. + - Do not report success until every entry point imports cleanly. + + 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. @@ -537,8 +547,9 @@ templates: - * **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. + * **shell_exec:** for running commands. Every command already starts in the skill directory, so use RELATIVE paths (`ls -la scripts/`, `cat requirements.txt`, `uv venv --seed .venv`). Do NOT prefix `cd &&` onto your commands — you are already there, and it wastes a line on every call. Pass `work_dir` only to leave that directory, which an install rarely needs. + * **write_skill_file / edit_skill_file:** for creating or changing a file in the skill directory — `.weknora/requirements.json`, a wrapper script, a `sys.path` fix. Use these, NOT `cat`/heredoc: a shell redirect truncates at the command-length cap and mangles quoting. Paths may be relative to the skill directory. + * `write_sandbox_file` / `edit_sandbox_file` / `list_sandbox_files` / `read_sandbox_file` are not registered. They only reach `/workspace`, which is wiped before the snapshot, so they could not help here anyway. * If a command fails, read the error and adapt. diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.go index 71803ecf..d1c2436b 100644 --- a/internal/agent/tools/definitions.go +++ b/internal/agent/tools/definitions.go @@ -32,6 +32,16 @@ const ( ToolReadSandboxFile = "read_sandbox_file" ToolWriteSandboxFile = "write_sandbox_file" ToolEditSandboxFile = "edit_sandbox_file" + // ToolWriteSkillFile / ToolEditSkillFile write the skill tree under + // /opt/weknora/tenant/skills rather than /workspace, and exist only for + // the built-in skill installer. They are scoped to the one skill being + // installed; see internal/agent/tools/skill_file.go. + // + // Deliberately absent from AvailableToolDefinitions: these write the + // shared snapshot image, so they are granted by install mode alone and + // must not become selectable on a tenant-editable agent config. + ToolWriteSkillFile = "write_skill_file" + ToolEditSkillFile = "edit_skill_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 diff --git a/internal/agent/tools/python_syntax.go b/internal/agent/tools/python_syntax.go index ce82f9d8..5792c05f 100644 --- a/internal/agent/tools/python_syntax.go +++ b/internal/agent/tools/python_syntax.go @@ -28,7 +28,10 @@ var pythonKeywords = map[string]bool{ "while": true, "with": true, "yield": true, } -func pythonScriptSyntaxHint(filePath, src string) string { +// pythonScriptSyntaxHint reports the nested-quote failure, if any, in a file +// just written. editTool names the tool that can repair it: the same guidance +// serves /workspace writes and skill-tree writes, which have different editors. +func pythonScriptSyntaxHint(filePath, src, editTool string) string { switch strings.ToLower(path.Ext(filePath)) { case ".py": default: @@ -42,9 +45,9 @@ func pythonScriptSyntaxHint(filePath, src string) string { "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, "+ + "Fix it with %s: wrap that text in the other quote, "+ "or use 「」 / \\\" for the inner quotation. Do not execute the script until it parses.", - line, + line, editTool, ) } diff --git a/internal/agent/tools/python_syntax_test.go b/internal/agent/tools/python_syntax_test.go index 876d0bc6..eb8f71ab 100644 --- a/internal/agent/tools/python_syntax_test.go +++ b/internal/agent/tools/python_syntax_test.go @@ -49,8 +49,11 @@ func TestFirstBrokenPythonQuoteReportsUnclosed(t *testing.T) { 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)) + assert.Contains(t, pythonScriptSyntaxHint("/workspace/output/x.py", src, ToolEditSandboxFile), + ToolEditSandboxFile, "the hint must name the tool that can repair this file") + assert.Contains(t, pythonScriptSyntaxHint(testSkillDir+"/run.py", src, ToolEditSkillFile), + ToolEditSkillFile, "a skill-tree file is not repairable with edit_sandbox_file") + assert.Empty(t, pythonScriptSyntaxHint("/workspace/output/x.md", src, ToolEditSandboxFile)) } func TestPythonSyntaxErrorHint(t *testing.T) { diff --git a/internal/agent/tools/sandbox_edit.go b/internal/agent/tools/sandbox_edit.go index e7d34dd3..8944601f 100644 --- a/internal/agent/tools/sandbox_edit.go +++ b/internal/agent/tools/sandbox_edit.go @@ -229,7 +229,7 @@ func (t *EditSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) logger.Infof(ctx, "[Tool][EditSandboxFile] session=%s path=%s replacements=%d bytes=%d", sessionID, clean, replacements, len(content)) - if hint := pythonScriptSyntaxHint(clean, updated); hint != "" { + if hint := pythonScriptSyntaxHint(clean, updated, ToolEditSandboxFile); hint != "" { return &types.ToolResult{ Success: false, Error: hint, diff --git a/internal/agent/tools/sandbox_write.go b/internal/agent/tools/sandbox_write.go index 1de40aa6..d63165d6 100644 --- a/internal/agent/tools/sandbox_write.go +++ b/internal/agent/tools/sandbox_write.go @@ -180,7 +180,7 @@ func (t *WriteSandboxFileTool) Execute(ctx context.Context, args json.RawMessage logger.Infof(ctx, "[Tool][WriteSandboxFile] session=%s path=%s bytes=%d", sessionID, clean, len(content)) - if hint := pythonScriptSyntaxHint(clean, input.Content); hint != "" { + if hint := pythonScriptSyntaxHint(clean, input.Content, ToolEditSandboxFile); hint != "" { return &types.ToolResult{ Success: false, Error: hint, diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go index bba36e7b..e3562b5d 100644 --- a/internal/agent/tools/shell_exec.go +++ b/internal/agent/tools/shell_exec.go @@ -295,6 +295,13 @@ type ShellExecTool struct { // workDirRoots are the directories work_dir may point inside. Ordinary // sessions get /workspace only; install mode adds the skills image root. workDirRoots []string + // defaultWorkDir is where a call that omits work_dir lands. Empty means + // /workspace, which is right for an ordinary session and wrong for an + // install: an install works in one skill directory and is told not to + // touch /workspace at all (it is wiped before the snapshot). Leaving the + // default there made the model prefix `cd &&` onto command + // after command, since that is the spelling guaranteed to work. + defaultWorkDir string // defaultTimeout is applied when the caller omits timeout_sec. Ordinary // sessions keep the 120s default; install mode uses the 10-minute cap // because dependency installs routinely exceed two minutes. @@ -329,13 +336,24 @@ func NewShellExecTool(executor SandboxCommandExecutor, envResolver skills.SkillE // NewInstallShellExecTool constructs the install-mode variant: commands run as // 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 { +// +// skillDir becomes the default working directory, because every command an +// install runs belongs there. A validated directory is required for that: an +// empty or unrecognised one falls back to /workspace rather than guessing. +func NewInstallShellExecTool( + executor SandboxInstallCommandExecutor, skillDir string, +) *ShellExecTool { base := shellExecTool - base.description = installShellExecDescription() + defaultWorkDir, ok := sandbox.ValidatedImageSkillDir(skillDir) + if !ok { + defaultWorkDir = defaultShellExecWorkDir + } + base.description = installShellExecDescription(defaultWorkDir) return &ShellExecTool{ BaseTool: base, executor: installShellExecutor{inner: executor}, workDirRoots: []string{defaultShellExecWorkDir, sandbox.SkillsImageRoot}, + defaultWorkDir: defaultWorkDir, defaultTimeout: shellExecMaxTimeout, } } @@ -344,24 +362,32 @@ func NewInstallShellExecTool(executor SandboxInstallCommandExecutor) *ShellExecT // 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 { +func installShellExecDescription(defaultWorkDir string) string { return `Run a shell command as root inside the skill-install sandbox. +## Working Directory +- Every command already starts in ` + "`" + defaultWorkDir + "`" + `, the skill + you are installing. Use RELATIVE paths: ` + "`ls -la scripts/`" + `, + ` + "`cat requirements.txt`" + `, ` + "`uv venv --seed .venv`" + `. +- Do NOT prefix ` + "`cd " + defaultWorkDir + " && `" + ` onto your commands. + You are already there, and the prefix wastes a line on every call. +- Pass ` + "`work_dir`" + ` only to leave that directory, which an install + rarely needs. + ## 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. +- Run commands with this tool. Create or change files in the skill directory + with ` + "`write_skill_file`" + ` / ` + "`edit_skill_file`" + ` instead of + ` + "`cat`" + ` or a heredoc: a shell redirect truncates at the + command-length cap and mangles quoting. - Install Python extras into the skill's ` + "`.venv`" + `, Node extras into ` + "`node_modules`" + `. Prefer ` + "`uv pip install`" + ` / ` + "`python3 -m venv`" + `. +- ` + "`write_sandbox_file`" + ` / ` + "`read_sandbox_file`" + ` are not + available; they only reach ` + "`/workspace`" + `, which is wiped before the + snapshot. ## Parameters - ` + "`command`" + ` (required): the shell one-liner under ` + "`/bin/bash -l -c`" + `. -- ` + "`work_dir`" + ` (optional): defaults to ` + "`/workspace`" + `; the skill - directory is allowed. +- ` + "`work_dir`" + ` (optional): defaults to ` + "`" + defaultWorkDir + "`" + `. - ` + "`timeout_sec`" + ` (optional): defaults to 600 seconds. ## Returns @@ -437,7 +463,7 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ workDir := strings.TrimSpace(input.WorkDir) if workDir == "" { - workDir = defaultShellExecWorkDir + workDir = t.effectiveDefaultWorkDir() } cleanWorkDir := path.Clean(workDir) if !t.workDirAllowed(cleanWorkDir) { @@ -677,6 +703,15 @@ func (t *ShellExecTool) isInstallMode() bool { return false } +// effectiveDefaultWorkDir keeps a zero-value tool on the ordinary /workspace +// contract; only the install-mode constructor sets anything else. +func (t *ShellExecTool) effectiveDefaultWorkDir() string { + if strings.TrimSpace(t.defaultWorkDir) == "" { + return defaultShellExecWorkDir + } + return t.defaultWorkDir +} + // 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 { diff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.go index 0944a5af..94356fd9 100644 --- a/internal/agent/tools/shell_exec_test.go +++ b/internal/agent/tools/shell_exec_test.go @@ -72,6 +72,7 @@ func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) { type fakeInstallShellExecutor struct { timeout time.Duration + workDir string calls int } @@ -79,24 +80,81 @@ func (f *fakeInstallShellExecutor) ExecShellCommandWithOptions( _ context.Context, _ string, _ string, opts sandbox.ShellExecOptions, ) (*sandbox.ExecuteResult, error) { f.timeout = opts.Timeout + f.workDir = opts.WorkDir f.calls++ return &sandbox.ExecuteResult{ExitCode: 0}, nil } -func TestInstallShellExecDescriptionDoesNotPointAtWriteSandboxFile(t *testing.T) { - description := NewInstallShellExecTool(&fakeInstallShellExecutor{}).Description() +// installShellSkillDir is the directory an install owns, and the working +// directory its shell must default to. +const installShellSkillDir = sandbox.SkillsImageRoot + "/pdf-tools" - assert.Contains(t, description, "only tool") - assert.Contains(t, description, "requirements.json") - assert.Contains(t, description, sandbox.SkillsImageRoot) +func TestInstallShellExecDescriptionDoesNotPointAtWriteSandboxFile(t *testing.T) { + description := NewInstallShellExecTool(&fakeInstallShellExecutor{}, installShellSkillDir).Description() + + assert.Contains(t, description, ToolWriteSkillFile, + "the writer for this tree is write_skill_file, not a heredoc") + assert.Contains(t, description, installShellSkillDir) assert.NotContains(t, description, "Do NOT dump large files through") assert.NotContains(t, NewShellExecTool(&fakeShellExecutor{}, nil).Description(), "write_sandbox_file is not available") } +// The model reached for `cd && …` on command after command because +// the default landed it in /workspace — a directory an install is told not to +// touch, since it is wiped before the snapshot. Naming the skill directory as +// the default is what removes the prefix. +func TestInstallShellExecDefaultsToTheSkillDirectory(t *testing.T) { + inner := &fakeInstallShellExecutor{} + tool := NewInstallShellExecTool(inner, installShellSkillDir) + + result, err := tool.Execute(shellExecTestContext(), json.RawMessage( + `{"command":"ls -la scripts/"}`, + )) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, installShellSkillDir, inner.workDir) + assert.Equal(t, installShellSkillDir, result.Data["work_dir"], + "the transcript must show where the command actually ran") + + assert.Contains(t, tool.Description(), "Do NOT prefix", + "the default alone did not stop the model; it has to be told") +} + +// An explicit work_dir still wins: an install occasionally has to leave its own +// directory, and the allowed roots have not changed. +func TestInstallShellExecStillHonoursAnExplicitWorkDir(t *testing.T) { + inner := &fakeInstallShellExecutor{} + + result, err := NewInstallShellExecTool(inner, installShellSkillDir).Execute( + shellExecTestContext(), + json.RawMessage(`{"command":"ls","work_dir":"/workspace"}`), + ) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, "/workspace", inner.workDir) +} + +// A run that somehow carries no valid skill directory must not invent one, and +// must not send commands to a path outside the allowed roots. +func TestInstallShellExecFallsBackToWorkspaceWithoutAValidSkillDir(t *testing.T) { + for _, dir := range []string{"", sandbox.SkillsImageRoot, "/etc", "/opt/weknora/tenant/skills/a/b"} { + inner := &fakeInstallShellExecutor{} + + result, err := NewInstallShellExecTool(inner, dir).Execute( + shellExecTestContext(), json.RawMessage(`{"command":"ls"}`)) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, "/workspace", inner.workDir, "skillDir %q must not become a default", dir) + } +} + func TestInstallShellExecDefaultsToTheTenMinuteBudget(t *testing.T) { inner := &fakeInstallShellExecutor{} - tool := NewInstallShellExecTool(inner) + tool := NewInstallShellExecTool(inner, installShellSkillDir) result, err := tool.Execute(shellExecTestContext(), json.RawMessage( `{"command":"pip install -r requirements.txt"}`, @@ -357,7 +415,7 @@ func TestShellExecDoesNotCaptureWhenExecutorErrors(t *testing.T) { func TestInstallShellExecDoesNotCapture(t *testing.T) { recorder := &recordedCapture{} - tool := NewInstallShellExecTool(&fakeInstallShellExecutor{}).WithEnvCapture(recorder.capture) + tool := NewInstallShellExecTool(&fakeInstallShellExecutor{}, installShellSkillDir).WithEnvCapture(recorder.capture) result, err := tool.Execute(shellExecTestContext(), json.RawMessage( `{"command":"export USER_TOKEN=x; pip install x","skill_name":"pdf-tools"}`, @@ -454,7 +512,7 @@ func TestShellExecAllowsOverlayInstallThatMentionsTheSkillTree(t *testing.T) { func TestInstallShellExecStillPipsIntoTheSkillTree(t *testing.T) { inner := &fakeInstallShellExecutor{} - tool := NewInstallShellExecTool(inner) + tool := NewInstallShellExecTool(inner, installShellSkillDir) result, err := tool.Execute(shellExecTestContext(), json.RawMessage( `{"command":"pip install python-docx","work_dir":"/opt/weknora/tenant/skills/律师助手"}`, diff --git a/internal/agent/tools/skill_file.go b/internal/agent/tools/skill_file.go new file mode 100644 index 00000000..e375a00a --- /dev/null +++ b/internal/agent/tools/skill_file.go @@ -0,0 +1,413 @@ +// Package tools — write_skill_file / edit_skill_file. +// +// The installer agent's only writer used to be `shell_exec` with a heredoc. +// That caps every file at the shell's command-length limit and puts the +// content through two levels of quoting, so a requirements.json or a small +// patch script routinely arrived truncated or mangled. These two tools write +// the same bytes over the file API instead. +// +// They are separate from write_sandbox_file / edit_sandbox_file rather than a +// loosening of them. Those write /workspace, which is wiped before the +// snapshot; the skill tree lives under /opt/weknora/tenant/skills and is what +// the snapshot keeps. Sharing one tool would mean one path guard covering both +// a per-session scratch area and the shared image. +// +// Scope: one install writes one skill. The tool is constructed with that +// skill's directory and refuses everything outside it, so an installer cannot +// reach a neighbouring skill in the shared image even though its shell runs as +// root. The prompt asks for the same thing; this enforces it. +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" +) + +// SkillFileStore is the write surface these tools need. Production uses +// *sandbox.SessionBoundManager, whose WriteSessionFile already refuses any +// path outside the skills image root; the per-skill scope below narrows that +// to the one directory this install owns. +type SkillFileStore interface { + StatSessionFile(ctx context.Context, sessionID, filePath string) (*sandbox.RemoteStatEntry, error) + ReadSessionFile(ctx context.Context, sessionID, filePath string) ([]byte, error) + WriteSessionFile(ctx context.Context, sessionID, filePath string, content []byte) error +} + +var writeSkillFileTool = BaseTool{ + name: ToolWriteSkillFile, + description: `Create or overwrite a text file inside the skill directory being installed. + +## Usage +- This is the way to write a file into the skill tree. Do NOT use + ` + "`shell_exec`" + ` with ` + "`cat`" + `, a heredoc, or ` + "`python -c`" + `: + those hit a command-length cap and mangle quoting. +- Use it for ` + "`.weknora/requirements.json`" + `, a small wrapper script, or a + patch to a shipped file. +- ` + pythonQuoteGuidance + ` + +## When NOT to Use +- To change a few lines of an existing file, call ` + "`edit_skill_file`" + `. +- To write scratch files — the skill directory is snapshotted; keep it clean. +- Binary content. Have a script produce binary files instead. + +## Path Rules +- ` + "`path`" + ` MUST be absolute and inside this install's skill directory. + A relative path is resolved against that directory. +- Any path outside it is refused, including another skill's directory. + +## 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[WriteSkillFileInput](), +} + +// WriteSkillFileInput defines the input parameters for write_skill_file. +type WriteSkillFileInput struct { + Path string `json:"path" jsonschema:"Path of the file to write, inside the skill directory being installed. Absolute, or relative to that directory."` + 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."` +} + +// WriteSkillFileTool writes a text file into the skill directory under install. +type WriteSkillFileTool struct { + BaseTool + store SkillFileStore + skillDir string +} + +// NewWriteSkillFileTool constructs the tool. `store` MUST NOT be nil and +// `skillDir` MUST be the directory of the skill this install owns. +func NewWriteSkillFileTool(store SkillFileStore, skillDir string) *WriteSkillFileTool { + return &WriteSkillFileTool{ + BaseTool: writeSkillFileTool, + store: store, + skillDir: skillDir, + } +} + +// Execute writes the file after confirming it lands inside the skill directory. +func (t *WriteSkillFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { + logger.Infof(ctx, "[Tool][WriteSkillFile] Execute started") + + var input WriteSkillFileInput + 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.store == nil { + return &types.ToolResult{ + Success: false, + Error: "skill file writing is not available in this deployment", + }, nil + } + + sessionID := resolveSessionID(ctx) + if sessionID == "" { + return &types.ToolResult{ + Success: false, + Error: "no session ID in context; write_skill_file must run inside an agent turn", + }, nil + } + + clean, err := resolveSkillFilePath(t.skillDir, input.Path) + if err != nil { + return &types.ToolResult{Success: false, Error: err.Error()}, 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 file", + len(content), maxWriteSandboxBytes, + ), + }, nil + } + if isBinaryShellOutput(input.Content) { + return &types.ToolResult{ + Success: false, + Error: "binary content is not accepted; write a text file instead", + }, nil + } + + if err := t.store.WriteSessionFile(ctx, sessionID, clean, content); err != nil { + logger.Warnf(ctx, "[Tool][WriteSkillFile] 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][WriteSkillFile] session=%s path=%s bytes=%d", + sessionID, clean, len(content)) + + data := map[string]interface{}{ + "display_type": ToolWriteSkillFile, + "session_id": sessionID, + "path": clean, + "root": t.skillDir, + "name": path.Base(clean), + "size": len(content), + } + if hint := pythonScriptSyntaxHint(clean, input.Content, ToolEditSkillFile); hint != "" { + data["syntax_error"] = true + return &types.ToolResult{ + Success: false, + Error: hint, + Output: fmt.Sprintf("=== Wrote skill file with syntax problems: %s ===\n\n%s\n", clean, hint), + Data: data, + }, nil + } + return &types.ToolResult{ + Success: true, + Output: fmt.Sprintf("=== Wrote skill file: %s ===\n\nbytes=%d\n", clean, len(content)), + Data: data, + }, nil +} + +// Cleanup releases any resources. +func (t *WriteSkillFileTool) Cleanup(ctx context.Context) error { + return nil +} + +var editSkillFileTool = BaseTool{ + name: ToolEditSkillFile, + description: `Replace exact text in a file inside the skill directory being installed. + +## Usage +- Use this when only a few lines of an existing file need to change — a wrong + path, an import, 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. +- ` + pythonQuoteGuidance + ` + +## When NOT to Use +- Creating a new file — use ` + "`write_skill_file`" + `. +- Replacing most of the file — rewrite it with ` + "`write_skill_file`" + `. +- Binary files. + +## Path Rules +- ` + "`path`" + ` MUST be inside this install's skill directory. Absolute, or + relative to that directory. + +## 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.`, + schema: utils.GenerateSchema[EditSkillFileInput](), +} + +// EditSkillFileInput defines the input parameters for edit_skill_file. +type EditSkillFileInput struct { + Path string `json:"path" jsonschema:"Path of an existing text file inside the skill directory being installed. Absolute, or relative to that directory."` + 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."` +} + +// EditSkillFileTool applies an exact string replacement inside the skill tree. +type EditSkillFileTool struct { + BaseTool + store SkillFileStore + skillDir string +} + +// NewEditSkillFileTool constructs the tool. `store` MUST NOT be nil and +// `skillDir` MUST be the directory of the skill this install owns. +func NewEditSkillFileTool(store SkillFileStore, skillDir string) *EditSkillFileTool { + return &EditSkillFileTool{ + BaseTool: editSkillFileTool, + store: store, + skillDir: skillDir, + } +} + +// Execute reads the file, applies the replacement, and writes it back. +func (t *EditSkillFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { + logger.Infof(ctx, "[Tool][EditSkillFile] Execute started") + + var input EditSkillFileInput + 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.store == nil { + return &types.ToolResult{ + Success: false, + Error: "skill file editing is not available in this deployment", + }, nil + } + + sessionID := resolveSessionID(ctx) + if sessionID == "" { + return &types.ToolResult{ + Success: false, + Error: "no session ID in context; edit_skill_file must run inside an agent turn", + }, nil + } + + clean, err := resolveSkillFilePath(t.skillDir, input.Path) + if err != nil { + return &types.ToolResult{Success: false, Error: err.Error()}, nil + } + + stat, statErr := t.store.StatSessionFile(ctx, sessionID, clean) + if statErr != nil { + return &types.ToolResult{ + Success: false, + Error: fmt.Sprintf("failed to stat %s: %v", clean, statErr), + }, nil + } + if stat != nil && stat.Type == sandbox.RemoteEntryDir { + return &types.ToolResult{ + Success: false, + Error: fmt.Sprintf("%s is a directory; edit_skill_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). Rewrite a smaller file with write_skill_file", + stat.Size, maxWriteSandboxBytes, + ), + }, nil + } + + raw, err := t.store.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", + }, 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.store.WriteSessionFile(ctx, sessionID, clean, content); err != nil { + logger.Warnf(ctx, "[Tool][EditSkillFile] 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][EditSkillFile] session=%s path=%s replacements=%d bytes=%d", + sessionID, clean, replacements, len(content)) + + data := map[string]interface{}{ + "display_type": ToolEditSkillFile, + "session_id": sessionID, + "path": clean, + "root": t.skillDir, + "name": path.Base(clean), + "size": len(content), + "replacements": replacements, + } + if hint := pythonScriptSyntaxHint(clean, updated, ToolEditSkillFile); hint != "" { + data["syntax_error"] = true + return &types.ToolResult{ + Success: false, + Error: hint, + Output: fmt.Sprintf("=== Edited skill file with syntax problems: %s ===\n\n%s\n", clean, hint), + Data: data, + }, nil + } + return &types.ToolResult{ + Success: true, + Output: fmt.Sprintf("=== Edited skill file: %s ===\n\nreplacements=%d\nbytes=%d\n", + clean, replacements, len(content)), + Data: data, + }, nil +} + +// Cleanup releases any resources. +func (t *EditSkillFileTool) Cleanup(ctx context.Context) error { + return nil +} + +// resolveSkillFilePath turns a model-supplied path into an absolute path +// proven to sit inside skillDir. +// +// A relative path is resolved against skillDir, which is what the model +// reaches for after being told the directory once. Everything is then cleaned +// and re-checked against the prefix, so "..", a symlink-looking spelling or an +// absolute path into a neighbouring skill all fail here rather than reaching +// the image. The directory itself is refused: it is not a file. +func resolveSkillFilePath(skillDir, requested string) (string, error) { + dir := path.Clean(strings.TrimSpace(skillDir)) + if dir == "" || dir == "." || dir == "/" { + return "", fmt.Errorf("this tool is not bound to a skill directory") + } + trimmed := strings.TrimSpace(requested) + if trimmed == "" { + return "", fmt.Errorf("path is required; write a file inside %s", dir) + } + if strings.ContainsRune(trimmed, 0) { + return "", fmt.Errorf("path %q is not a valid file path", requested) + } + candidate := trimmed + if !path.IsAbs(candidate) { + candidate = path.Join(dir, candidate) + } + clean := path.Clean(candidate) + if clean == dir || !strings.HasPrefix(clean, dir+"/") { + return "", fmt.Errorf( + "path %q is outside this install's skill directory (%s); "+ + "an install may only write its own skill", + requested, dir, + ) + } + return clean, nil +} diff --git a/internal/agent/tools/skill_file_test.go b/internal/agent/tools/skill_file_test.go new file mode 100644 index 00000000..92c3574a --- /dev/null +++ b/internal/agent/tools/skill_file_test.go @@ -0,0 +1,195 @@ +package tools + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/sandbox" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testSkillDir = sandbox.SkillsImageRoot + "/pdf-tools" + +type fakeSkillFileStore struct { + existing map[string][]byte + stat *sandbox.RemoteStatEntry + statErr error + writeErr error + + writes []string + last []byte +} + +func (f *fakeSkillFileStore) StatSessionFile( + _ context.Context, _, filePath string, +) (*sandbox.RemoteStatEntry, error) { + if f.statErr != nil { + return nil, f.statErr + } + if f.stat != nil { + return f.stat, nil + } + if _, ok := f.existing[filePath]; !ok { + return nil, errors.New("no such file") + } + return &sandbox.RemoteStatEntry{Path: filePath, Type: sandbox.RemoteEntryFile}, nil +} + +func (f *fakeSkillFileStore) ReadSessionFile( + _ context.Context, _, filePath string, +) ([]byte, error) { + raw, ok := f.existing[filePath] + if !ok { + return nil, errors.New("no such file") + } + return append([]byte(nil), raw...), nil +} + +func (f *fakeSkillFileStore) WriteSessionFile( + _ context.Context, _, filePath string, content []byte, +) error { + if f.writeErr != nil { + return f.writeErr + } + f.writes = append(f.writes, filePath) + f.last = append([]byte(nil), content...) + if f.existing == nil { + f.existing = map[string][]byte{} + } + f.existing[filePath] = append([]byte(nil), content...) + return nil +} + +// The reason these tools exist: the installer's only writer was `cat` with a +// heredoc, so anything past the shell's command-length cap arrived truncated. +func TestWriteSkillFileWritesAFileTooLargeForAHeredoc(t *testing.T) { + content := strings.Repeat("# a line of a generated wrapper script\n", 500) + require.Greater(t, len(content), 8*1024) + store := &fakeSkillFileStore{} + + result, err := NewWriteSkillFileTool(store, testSkillDir).Execute( + sandboxFileTestContext(), + mustWriteSandboxArgs(testSkillDir+"/.weknora/requirements.json", content), + ) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, []string{testSkillDir + "/.weknora/requirements.json"}, store.writes) + assert.Equal(t, content, string(store.last)) + assert.NotContains(t, result.Output, content, "the model already has these bytes") +} + +// The model is told the skill directory once, then reaches for paths relative +// to it. Resolving them beats refusing a call that meant the right file. +func TestWriteSkillFileResolvesARelativePathAgainstTheSkillDirectory(t *testing.T) { + store := &fakeSkillFileStore{} + + result, err := NewWriteSkillFileTool(store, testSkillDir).Execute( + sandboxFileTestContext(), + mustWriteSandboxArgs(".weknora/requirements.json", `{"env":[]}`), + ) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, []string{testSkillDir + "/.weknora/requirements.json"}, store.writes) +} + +// One install writes one skill. The installer's shell runs as root in an image +// every session of the config inherits, so reaching a neighbouring skill has to +// fail in the tool rather than be discouraged by the prompt. +func TestSkillFileToolsRefuseEveryPathOutsideTheirOwnSkill(t *testing.T) { + for _, requested := range []string{ + sandbox.SkillsImageRoot + "/other-skill/SKILL.md", + sandbox.SkillsImageRoot + "/.manifest.json", + sandbox.SkillsImageRoot, + testSkillDir + "/../other-skill/run.py", + testSkillDir + "/./../.manifest.json", + "../other-skill/run.py", + "/etc/passwd", + "/workspace/output/run.py", + testSkillDir, + "", + } { + t.Run(requested, func(t *testing.T) { + store := &fakeSkillFileStore{} + + result, err := NewWriteSkillFileTool(store, testSkillDir).Execute( + sandboxFileTestContext(), mustWriteSandboxArgs(requested, "x = 1\n")) + + require.NoError(t, err) + require.False(t, result.Success, + "an install must not be able to write %q", requested) + assert.Empty(t, store.writes, "the refusal must happen before any write") + }) + } +} + +func TestEditSkillFileReplacesASnippetInPlace(t *testing.T) { + store := &fakeSkillFileStore{existing: map[string][]byte{ + testSkillDir + "/scripts/run.py": []byte("import sys\nLIB = '/wrong/path'\n"), + }} + + args, err := json.Marshal(map[string]any{ + "path": "scripts/run.py", + "old_string": "'/wrong/path'", + "new_string": "'" + testSkillDir + "/lib'", + }) + require.NoError(t, err) + + result, err := NewEditSkillFileTool(store, testSkillDir).Execute( + sandboxFileTestContext(), args) + + require.NoError(t, err) + require.True(t, result.Success, result.Error) + assert.Equal(t, 1, result.Data["replacements"]) + assert.Contains(t, string(store.last), testSkillDir+"/lib") +} + +// A nested-quote break is reported but the write still lands, so the next call +// can be an edit rather than a rewrite of the whole file. The hint has to name +// edit_skill_file: edit_sandbox_file cannot reach this tree. +func TestWriteSkillFileFlagsNestedPythonQuotesAndStillWrites(t *testing.T) { + store := &fakeSkillFileStore{} + + result, err := NewWriteSkillFileTool(store, testSkillDir).Execute( + sandboxFileTestContext(), + mustWriteSandboxArgs("scripts/run.py", + "title = \"这不是一个\"大干快上\"的夜晚\"\n")) + + require.NoError(t, err) + require.False(t, result.Success) + assert.Equal(t, true, result.Data["syntax_error"]) + assert.Contains(t, result.Error, ToolEditSkillFile) + assert.Len(t, store.writes, 1, "edit_skill_file needs the file to exist") +} + +// These write the shared snapshot image, so they are granted by install mode +// alone. A checkbox for them in the settings UI would turn "can edit an agent" +// into "can write the image every session of this config inherits", which is a +// different permission from "can upload a skill". +func TestSkillFileToolsAreNotSelectableOnATenantAgent(t *testing.T) { + for _, name := range []string{ToolWriteSkillFile, ToolEditSkillFile} { + require.NotContains(t, DefaultAllowedTools(), name) + for _, definition := range AvailableToolDefinitions() { + require.NotEqual(t, name, definition.Name, + "a tenant-editable agent must not be able to request %s", name) + } + } +} + +func TestSkillFileToolsRefuseToWriteWhenBoundToNoSkillDirectory(t *testing.T) { + for _, dir := range []string{"", "/", "."} { + store := &fakeSkillFileStore{} + + result, err := NewWriteSkillFileTool(store, dir).Execute( + sandboxFileTestContext(), mustWriteSandboxArgs("/etc/passwd", "x")) + + require.NoError(t, err) + require.False(t, result.Success, "skillDir %q must not authorise any write", dir) + assert.Empty(t, store.writes) + } +} diff --git a/internal/agent/tools/tool_policy_coverage_test.go b/internal/agent/tools/tool_policy_coverage_test.go index 546a97c0..f4a6932c 100644 --- a/internal/agent/tools/tool_policy_coverage_test.go +++ b/internal/agent/tools/tool_policy_coverage_test.go @@ -34,6 +34,8 @@ func TestEveryBuiltInToolDeclaresAModelHandlePolicy(t *testing.T) { ToolReadSandboxFile, ToolWriteSandboxFile, ToolEditSandboxFile, + ToolWriteSkillFile, + ToolEditSkillFile, ToolShellExec, ToolWikiReadPage, ToolWikiWritePage, diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index ce7f84fc..85d72b75 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -398,7 +398,9 @@ func (s *agentService) resolveKBAndDocInfos( // /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. +// Install mode gets write_skill_file / edit_skill_file instead, which write +// the image tree and are scoped to the one skill being installed — +// see registerSkillFileTools. func (s *agentService) registerSandboxFileTools( ctx context.Context, toolRegistry *tools.ToolRegistry, @@ -407,6 +409,7 @@ func (s *agentService) registerSandboxFileTools( ) { if config != nil && config.SkillInstallMode() { logger.Infof(ctx, "Skipping session file tools in skill install mode") + s.registerSkillFileTools(ctx, toolRegistry, sessionID, config) return } sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config) @@ -429,6 +432,55 @@ func (s *agentService) registerSandboxFileTools( } } +// registerSkillFileTools registers write_skill_file / edit_skill_file for the +// built-in skill installer, and for nothing else. +// +// The installer's shell already runs as root inside the skills image root, so +// these tools grant no reach it does not have. They exist because its only +// writer was `cat` with a heredoc: every file went through the shell's +// command-length cap and two levels of quoting, which truncated or mangled +// anything larger than a few lines. +// +// Two conditions gate registration, and both are checked here rather than +// trusted from the caller. SkillInstallMode is settable only through +// EnableSkillInstallMode, which refuses every agent but the built-in +// installer. The skill directory is re-validated against the image path rules, +// so a run that somehow carried a bad scope gets no writer at all instead of +// one pointed somewhere unintended. +func (s *agentService) registerSkillFileTools( + ctx context.Context, + toolRegistry *tools.ToolRegistry, + sessionID string, + config *types.AgentConfig, +) { + if config == nil || !config.SkillInstallMode() { + return + } + skillDir, ok := sandbox.ValidatedImageSkillDir(config.SkillInstallDir()) + if !ok { + logger.Warnf(ctx, "Install mode carries no valid skill directory (%q); "+ + "write_skill_file/edit_skill_file not registered", config.SkillInstallDir()) + return + } + sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config) + if err != nil { + logger.Warnf(ctx, "Failed to resolve sandbox for skill file tools: %v", err) + return + } + if sandboxMgr == nil { + return + } + store, ok := sandboxMgr.(tools.SkillFileStore) + if !ok { + logger.Infof(ctx, "Sandbox backend cannot write the skills image root; "+ + "write_skill_file/edit_skill_file not registered") + return + } + toolRegistry.RegisterTool(tools.NewWriteSkillFileTool(store, skillDir)) + toolRegistry.RegisterTool(tools.NewEditSkillFileTool(store, skillDir)) + logger.Infof(ctx, "Registered write_skill_file and edit_skill_file scoped to %s", skillDir) +} + // registerSandboxShellIfAllowed registers shell_exec when this run is // entitled to a sandbox shell: SkillsEnabled, or the built-in skill // installer. It does not require a ready skill to already exist, so a @@ -735,8 +787,10 @@ func (s *agentService) registerSandboxShellTool( ) { if config.SkillInstallMode() { if executor := sessionSandboxInstallShellExecutor(sandboxMgr); executor != nil { - toolRegistry.RegisterTool(tools.NewInstallShellExecTool(executor)) - logger.Infof(ctx, "Registered install-mode shell_exec tool") + skillDir := config.SkillInstallDir() + toolRegistry.RegisterTool(tools.NewInstallShellExecTool(executor, skillDir)) + logger.Infof(ctx, "Registered install-mode shell_exec tool (work_dir defaults to %s)", + skillDir) } else { logger.Warnf(ctx, "Sandbox backend does not advertise install-mode shell; skill install cannot run") } diff --git a/internal/application/service/agent_service_install_shell_test.go b/internal/application/service/agent_service_install_shell_test.go index ab963474..1b1c617c 100644 --- a/internal/application/service/agent_service_install_shell_test.go +++ b/internal/application/service/agent_service_install_shell_test.go @@ -38,7 +38,7 @@ func TestInstallerAgentGetsTheRootShellWithTheSkillsRoot(t *testing.T) { installShell: privileged, } config := &types.AgentConfig{} - config.EnableSkillInstallMode(types.BuiltinSkillInstallerID) + config.EnableSkillInstallMode(types.BuiltinSkillInstallerID, sandbox.SkillsImageRoot+"/pptx") registry := tools.NewToolRegistry() (&agentService{}).registerSandboxShellTool(context.Background(), registry, mgr, config) @@ -86,7 +86,7 @@ func TestOrdinaryAgentKeepsTheUnprivilegedShell(t *testing.T) { func TestInstallModeIsRefusedToEveryAgentButTheInstaller(t *testing.T) { config := &types.AgentConfig{} - config.EnableSkillInstallMode("some-tenant-agent") + config.EnableSkillInstallMode("some-tenant-agent", sandbox.SkillsImageRoot+"/pptx") require.False(t, config.SkillInstallMode()) } @@ -105,7 +105,7 @@ func TestInstallerAgentConfigTurnsOnInstallMode(t *testing.T) { config := installerAgentConfig(&types.CustomAgent{ ID: types.BuiltinSkillInstallerID, Config: types.CustomAgentConfig{AllowedTools: []string{tools.ToolShellExec}}, - }, "cfg-1") + }, "cfg-1", sandbox.SkillsImageRoot+"/pptx") require.True(t, config.SkillInstallMode()) require.Equal(t, "none", config.MCPSelectionMode, @@ -126,7 +126,7 @@ func TestInstallerAgentConfigKeepsMCPOffWhenThePlatformYAMLEnablesIt(t *testing. WebSearchEnabled: true, MemoryEnabled: &memoryOn, }, - }, "cfg-1") + }, "cfg-1", sandbox.SkillsImageRoot+"/pptx") require.Equal(t, "none", config.MCPSelectionMode) require.False(t, config.WebSearchEnabled) @@ -138,7 +138,7 @@ func TestInstallerAgentConfigLeavesInstallModeOffForAnotherAgent(t *testing.T) { config := installerAgentConfig(&types.CustomAgent{ ID: "agent-42", Config: types.CustomAgentConfig{AllowedTools: []string{tools.ToolShellExec}}, - }, "cfg-1") + }, "cfg-1", sandbox.SkillsImageRoot+"/pptx") require.False(t, config.SkillInstallMode()) } diff --git a/internal/application/service/agent_service_test.go b/internal/application/service/agent_service_test.go index cc2fd420..44df91b3 100644 --- a/internal/application/service/agent_service_test.go +++ b/internal/application/service/agent_service_test.go @@ -155,7 +155,7 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) { SkillsEnabled: false, AllowedTools: []string{tools.ToolShellExec}, } - config.EnableSkillInstallMode(types.BuiltinSkillInstallerID) + config.EnableSkillInstallMode(types.BuiltinSkillInstallerID, sandbox.SkillsImageRoot+"/pptx") engine, err := svc.CreateAgentEngine(ctx, config, chatModel, nil, nil, "sess-1", "msg-1") diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go index 3bc08bea..e3b5970c 100644 --- a/internal/application/service/tenant_skill_install.go +++ b/internal/application/service/tenant_skill_install.go @@ -731,7 +731,7 @@ type installerJob struct { func (s *TenantSkillService) installDependenciesAndVerify( ctx context.Context, job installerJob, ) (err error) { - run, err := s.openInstallerRun(ctx, job.tenantID, job.sess, job.transcript) + run, err := s.openInstallerRun(ctx, job.tenantID, job.sess, job.skillDir, job.transcript) if err != nil { job.transcript.Finish(context.WithoutCancel(ctx), err) return err @@ -805,7 +805,11 @@ type installerRun struct { // AgentQA swallows engine failures (it emits an error event and returns nil) // and we need a reliable signal before switching the image. func (s *TenantSkillService) openInstallerRun( - ctx context.Context, tenantID uint64, sess *types.Session, transcript *installTranscript, + ctx context.Context, + tenantID uint64, + sess *types.Session, + skillDir string, + transcript *installTranscript, ) (*installerRun, error) { if s.installerAgents == nil { return nil, errors.New("custom agent service is not configured") @@ -821,7 +825,8 @@ func (s *TenantSkillService) openInstallerRun( if err != nil { return nil, fmt.Errorf("load installer agent: %w", err) } - agentConfig := installerAgentConfig(installerAgentDefaults(ctx, tenantID), sess.SandboxConfigID) + agentConfig := installerAgentConfig( + installerAgentDefaults(ctx, tenantID), sess.SandboxConfigID, skillDir) chatModel, err := s.resolveInstallerModel(ctx, tenantID, record) if err != nil { @@ -904,12 +909,11 @@ func (s *TenantSkillService) reopenSkillDirForRepair( // buildRepairPrompt turns the gate's own findings into the next round's brief. // -// It carries no analysis of its own, deliberately. The reason a first round can -// fail on a working skill is that SKILL.md and the imports its files execute are -// two different descriptions of what the skill needs; a third description -// written here would reintroduce exactly that gap. The only thing added is the -// import-name-to-distribution mapping, which is a property of PyPI rather than -// of this skill. +// It carries no analysis of its own, deliberately: the gate is the only +// authority on what has to resolve in this image, and a second description +// written here could disagree with it. Every repairable finding names a +// distribution one of the skill's manifests declares and pip did not land, so +// the brief is short — install what the lines name, change nothing else. func buildRepairPrompt(skillDir string, gate *skillVerificationError) string { var findings strings.Builder for _, problem := range gate.Problems { @@ -921,20 +925,15 @@ func buildRepairPrompt(skillDir string, gate *skillVerificationError) string { The %s check reported: %s -Every line above is a dependency this image cannot resolve. The names were read -from the imports the skill's own files execute when they load, which is why some -of them appear nowhere in SKILL.md — install them anyway. +Every line above names a dependency one of this skill's own manifests declares +and that is not installed in this image. Install it. - Python packages go into %s/.venv (`+"`uv pip install`"+`, or %s/.venv/bin/python -m pip install). Node packages go under %s/node_modules. -- The name in each line is an IMPORT name; install the distribution that - provides it. Common cases where they differ: PIL -> pillow, yaml -> pyyaml, - docx -> python-docx, pptx -> python-pptx, cv2 -> opencv-python-headless, - bs4 -> beautifulsoup4, sklearn -> scikit-learn, fitz -> pymupdf. -- Do NOT edit, move or delete any of the skill's own files, and do NOT edit - SKILL.md or requirements.txt to make the check pass. The uploaded archive is - what read_skill serves, so a source edit here makes the installed skill differ - from what everyone else sees. +- Do NOT edit SKILL.md, requirements.txt, pyproject.toml or package.json to + make the check pass. Those files are what read_skill serves, so weakening a + declaration here makes the installed skill differ from what everyone else + sees — and the dependency would still be missing at run time. - If a package genuinely cannot be installed in this image, say so plainly in your summary rather than working around it. @@ -1738,14 +1737,19 @@ 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 (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. +- shell_exec already starts every command in %s. Use relative paths + (`+"`ls -la scripts/`"+`, `+"`uv venv --seed .venv`"+`) and do NOT prefix + `+"`cd &&`"+` onto them. +- To create or change a file in this tree use write_skill_file / + edit_skill_file, NOT a shell heredoc or `+"`cat`"+`: those truncate at the + command-length cap and mangle quoting. + write_sandbox_file only writes /workspace, which is wiped before the + snapshot, so it cannot help you here. - 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 needs AT RUN TIME. Decide from the SKILL.md text at the end of this message: declare what it documents as needed to run the skill. Ignore - anything only the installation itself needed. Run mkdir -p on the directory first, then write the declaration to %s as JSON of this exact shape: + anything only the installation itself needed. Write the declaration with write_skill_file to %s, as JSON of this exact shape: {"env":[{"name":"TAVILY_API_KEY","description":"what the skill uses it for","required":true}]} Each name must be UPPER_SNAKE_CASE and must appear literally somewhere in the skill's own files. Never write any value, placeholder or example credential: this file declares what is needed, and @@ -1768,11 +1772,24 @@ already in the venv. %s - If an installer script needs --yes / --all / every extra flag, pass them. %s -The server verifies the result itself before the image is kept, so report what -you did rather than whether it passed. Verification parses every script with -the interpreter that would run it, resolves the imports each one executes on -load, and checks every distribution named in requirements.txt is present in the -venv. It never runs the skill's code. +Before you finish, PROVE the skill's imports resolve. Do not reason about it — +run it. The server's own check cannot: it parses files without executing them, +so it never learns whether an import would have worked. You have the real +interpreter, so this is your job and yours only. +- For each script the skill offers, run the import the way the skill would: + `+"`%s/.venv/bin/python -c 'import x'`"+`, or the script's own + `+"`--help`"+` if it has one. +- A failure here is usually one of two things. A missing distribution: install + it. Or a module the skill ships that Python cannot find — then the script + needs the directory on sys.path, and you fix the script with edit_skill_file + rather than installing anything. +- Do not declare success until every entry point imports cleanly. + +The server then checks what it can before the image is kept, so report what you +did rather than whether it passed. It confirms every file parses with the +interpreter that would run it, and that every distribution named in +requirements.txt / pyproject.toml is installed in the venv. It never runs the +skill's code and never judges an import. Lazy imports and install_deps.py extras are invisible to that check — you still have to install them. @@ -1780,7 +1797,7 @@ SKILL.md: %s `, skillDir, formatToolchainSection(tools), skillDir, skillDir, skillDir, requirementsPath, skillDir, formatOnDemandInstallers(bundle), - formatFrontmatterRepairNote(bundle), skillMD) + formatFrontmatterRepairNote(bundle), skillDir, skillMD) } // formatOnDemandInstallers names bundle files that install extras at first @@ -1920,12 +1937,22 @@ func installerAgentDefaults(ctx context.Context, tenantID uint64) *types.CustomA // the shared sandbox image": that is a different permission from "can upload a // skill". The model is the one choice still taken from the stored record, in // resolveInstallerModel. -func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.AgentConfig { +// +// skillDir scopes the skill file tools to the one skill this install owns. The +// installer's shell already runs as root in the shared image, so the tools add +// no reach — they replace `cat` with a heredoc, whose command-length cap and +// double quoting truncated or mangled every file the agent tried to write. +func installerAgentConfig( + defaults *types.CustomAgent, configID, skillDir string, +) *types.AgentConfig { memoryOff := false thinkingOff := false + installTools := []string{ + tools.ToolShellExec, tools.ToolWriteSkillFile, tools.ToolEditSkillFile, + } cfg := &types.AgentConfig{ MaxIterations: 30, - AllowedTools: []string{tools.ToolShellExec}, + AllowedTools: append([]string(nil), installTools...), Temperature: 0.2, WebSearchEnabled: false, MCPSelectionMode: "none", @@ -1942,16 +1969,17 @@ func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.A // The installer's shell_exec must run as root inside the skills image // root; the prompt below asks for exactly that. The grant is keyed on the // built-in agent ID and refused for anything else. - cfg.EnableSkillInstallMode(defaults.ID) + cfg.EnableSkillInstallMode(defaults.ID, skillDir) custom := defaults.Config cfg.MaxIterations = custom.MaxIterations if cfg.MaxIterations == 0 { cfg.MaxIterations = 30 } - cfg.AllowedTools = append([]string(nil), custom.AllowedTools...) - if len(cfg.AllowedTools) == 0 { - cfg.AllowedTools = []string{tools.ToolShellExec} - } + // The install tools are unioned in rather than read off the registry entry. + // An install that cannot write its own skill directory cannot record what + // it did, and the platform YAML predates these tools — a deployment that + // has not re-synced it must not silently lose them. + cfg.AllowedTools = unionTools(custom.AllowedTools, installTools) cfg.Temperature = custom.Temperature cfg.SystemPrompt = custom.SystemPrompt cfg.UseCustomSystemPrompt = custom.SystemPrompt != "" @@ -1964,6 +1992,25 @@ func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.A return cfg } +// unionTools returns configured plus every name in required that it is missing, +// preserving the configured order so a deployment's own list still reads as it +// was written. +func unionTools(configured, required []string) []string { + seen := make(map[string]struct{}, len(configured)+len(required)) + out := make([]string, 0, len(configured)+len(required)) + for _, name := range append(append([]string(nil), configured...), required...) { + if name = strings.TrimSpace(name); name == "" { + continue + } + if _, ok := seen[name]; ok { + continue + } + seen[name] = struct{}{} + out = append(out, name) + } + return out +} + // resolveInstallerModel prefers the model the installer agent is configured // with. Whoever set that model chose it for this job; the workspace default is // only the fallback for a record that names no model or names one this diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index 0a03a38e..49b7cb2c 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -622,12 +622,46 @@ func TestBuildInstallPromptAsksForADeclarationWithoutValues(t *testing.T) { 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") + require.Contains(t, prompt, "write_skill_file", + "a heredoc truncates at the command-length cap; the file tools are the writer") + require.Contains(t, prompt, "write_sandbox_file only writes /workspace", + "the installer must be told why the workspace writer cannot help it") require.Contains(t, prompt, "- uv: /root/.local/bin/uv", "the prompt hands over absolute paths instead of a PATH gamble") } +// shell_exec used to default to /workspace, so the installer opened command +// after command with `cd &&` — the one spelling guaranteed to land +// somewhere useful. The default is now the skill directory, and the prompt has +// to say so, because a model that is not told keeps paying for the prefix. +func TestBuildInstallPromptSaysCommandsAlreadyStartInTheSkillDirectory(t *testing.T) { + fx := newInstallFixture(t) + + prompt := buildInstallPrompt(installSkillDir, fx.bundle, nil) + + require.Contains(t, prompt, "shell_exec already starts every command in "+installSkillDir) + require.Contains(t, prompt, "do NOT prefix") + require.Contains(t, prompt, "cd &&") +} + +// Import resolution is the agent's job because it is nobody else's: the server +// parses files without executing them, so it never learns whether an import +// would have worked. The prompt has to say so, or the one party holding a real +// interpreter reasons about imports instead of running them. +func TestBuildInstallPromptDemandsImportsBeProvenByRunningThem(t *testing.T) { + fx := newInstallFixture(t) + + prompt := buildInstallPrompt(installSkillDir, fx.bundle, nil) + + require.Contains(t, prompt, "PROVE the skill's imports resolve") + require.Contains(t, prompt, "Do not reason about it") + require.Contains(t, prompt, installSkillDir+"/.venv/bin/python -c 'import x'") + require.Contains(t, prompt, "never judges an import", + "the agent must not expect the server to catch an unresolved import") + require.Contains(t, prompt, "edit_skill_file", + "a shipped module Python cannot find is fixed in the script, not with pip") +} + func TestBuildInstallPromptNamesOnDemandInstallerInTheArchive(t *testing.T) { fx := newInstallFixture(t) fx.bundle.Files["scripts/install_deps.py"] = []byte("print(1)\n") @@ -1487,10 +1521,19 @@ func TestInstallSessionIgnoresATenantOverrideOfTheInstallerAgent(t *testing.T) { require.Equal(t, platform.Config.SystemPrompt, fx.engineConfig.SystemPrompt, "the prompt that drives a root shell is the platform's, not the tenant's") require.NotContains(t, fx.engineConfig.SystemPrompt, "/root/.ssh") - require.Equal(t, platform.Config.AllowedTools, fx.engineConfig.AllowedTools) + require.Subset(t, fx.engineConfig.AllowedTools, platform.Config.AllowedTools, + "the tool set is the platform's, plus what an install structurally needs") require.NotContains(t, fx.engineConfig.AllowedTools, tools.ToolWebSearch) + require.NotContains(t, fx.engineConfig.AllowedTools, tools.ToolReadSkill) + // Unioned in rather than read off the registry entry: an install that + // cannot write its own skill directory cannot record what it did, and a + // deployment whose platform YAML predates these tools must not lose them. + require.Contains(t, fx.engineConfig.AllowedTools, tools.ToolWriteSkillFile) + require.Contains(t, fx.engineConfig.AllowedTools, tools.ToolEditSkillFile) require.Equal(t, platform.Config.MaxIterations, fx.engineConfig.MaxIterations) require.True(t, fx.engineConfig.SkillInstallMode()) + require.Equal(t, installSkillDir, fx.engineConfig.SkillInstallDir(), + "the file tools must be scoped to this install's own skill directory") require.Equal(t, "model-agent", fx.engineModel.GetModelID(), "the model is the one choice the tenant record still makes") } diff --git a/internal/application/service/tenant_skill_verify.go b/internal/application/service/tenant_skill_verify.go index c7b8d003..2e417f8f 100644 --- a/internal/application/service/tenant_skill_verify.go +++ b/internal/application/service/tenant_skill_verify.go @@ -63,22 +63,24 @@ func (e *skillVerificationError) Error() string { // verifySkill is the server's own check, and the last gate before the image // pointer moves: a broken install must leave the previous snapshot serving. // -// It proves loadability, not behaviour, and not "every file can be used as -// python this_file.py". A skill ships scripts and library packages together; -// execute_skill_script names files, but those files are also imported by each -// other. The Python pass resolves each file's imports against the prefixes -// Python itself would use — the file's own directory and every ancestor up to -// the skill root — plus the venv. Guessing a single entry script, or treating -// every .py as an isolated __main__, both fail real skills. +// It checks only what a file can settle, never what a runtime decides. Every +// pass here is deterministic: the files the bundle named are present, the +// isolated dependency trees the installer was told to create exist, every +// source parses with the interpreter that would run it, and every distribution +// the manifests name is installed. +// +// Import resolution is deliberately absent. Whether `import helper` resolves +// depends on what a script does to sys.path before the import runs, which no +// static evaluator can enumerate — and every approximation of it refused +// skills that run perfectly. That proof belongs to the installer agent, which +// holds a root shell and the real interpreter and can simply run the import. +// See the header of tenant_skill_verify.py. // // Findings are graded rather than uniformly fatal. Refusing an install costs // the minutes of dependency work that already succeeded, so only evidence that -// the install itself is broken may do it: a file nothing the skill offers ever -// loads, or a requirement pip would have skipped, is returned as a note. -// -// Not executing is the point, not a limitation. The previous implementation -// ran one guessed script with --help; skills that do not parse arguments -// simply ran their whole main path inside the tree about to be snapshotted. +// the install itself is broken may do it: a finding in a file nothing the +// skill offers ever loads, or a requirement pip would have skipped, is +// returned as a note. func (s *TenantSkillService) verifySkill( ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle, ) ([]string, error) { @@ -88,7 +90,7 @@ func (s *TenantSkillService) verifySkill( if err := s.verifyDeclaredDependencies(ctx, mgr, sessionID, skillDir, bundle); err != nil { return nil, err } - return s.verifyScriptsLoad(ctx, mgr, sessionID, skillDir, bundle) + return s.verifyScriptsParse(ctx, mgr, sessionID, skillDir, bundle) } // verifySkillTree confirms the files the agent was given are still the files @@ -180,15 +182,20 @@ func (s *TenantSkillService) verifyDeclaredDependencies( return nil } -// verifyScriptsLoad runs one pass per language present in the bundle. Each -// pass covers every file of that language: syntax and imports are properties -// of the file, not of a guessed entry point. +// verifyScriptsParse runs one pass per language present in the bundle. Each +// pass covers every file of that language: parsing is a property of the file, +// not of a guessed entry point. // -// Only the Python pass takes the auxiliary split. Its findings depend on what -// the image carries, so a bundled tests/ directory can fail an install that -// works; `node --check` and `bash -n` only state whether a file parses, which -// no amount of installing changes either way. -func (s *TenantSkillService) verifyScriptsLoad( +// All three passes are parse-only — `ast.parse`, `node --check`, `bash -n`. +// None of them executes the skill's code and none of them decides whether an +// import resolves. The Python pass additionally checks the manifests against +// what pip actually landed, which is the one finding here another installer +// round can still fix. +// +// Only the Python pass takes the auxiliary split, because it is the only one +// whose findings depend on what the image carries: a bundled tests/ directory +// naming a package the venv does not have must not fail an install that works. +func (s *TenantSkillService) verifyScriptsParse( ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle, ) ([]string, error) { var notes []string @@ -282,7 +289,7 @@ func verificationProblems(stderr string) []string { return problems } -// skillPythonVerifyCommand pipes the verifier into the same interpreter a +// skillPythonVerifyCommand pipes the parser into the same interpreter a // runtime skill call would use, and names the files to check on the command // line. The list is explicit rather than a directory walk so the pass covers // exactly the uploaded sources — never .venv, node_modules or anything else diff --git a/internal/application/service/tenant_skill_verify.py b/internal/application/service/tenant_skill_verify.py index 7e95daed..aad856ec 100644 --- a/internal/application/service/tenant_skill_verify.py +++ b/internal/application/service/tenant_skill_verify.py @@ -1,32 +1,36 @@ -"""Verify that an installed skill's Python sources can be loaded in this image. +"""Verify that an installed skill's Python sources are well-formed in this image. Run inside the sandbox, by the interpreter a real skill call would use, as the ordinary execution user, after the tree has been given its final permissions: python3 -