fix(agent): let file tools read staged inputs without hanging empty skill tools

list/read sandbox tools were advertised for skills-off agents so they could inspect /workspace/input, but they still refused anything outside /workspace/output. Register shell_exec independently of the skills manager so a skills-enabled sandbox with no ready skill gets a shell without empty read_skill / execute_skill_script tools.
main
wizardchen 2026-08-29 00:22:24 +08:00 committed by lyingbug
parent 252e97e7d6
commit 84a35993d2
7 changed files with 400 additions and 106 deletions

View File

@ -1,19 +1,21 @@
// Package tools — list_sandbox_files.
//
// Read-only tool that lets the LLM enumerate files under a session's
// sandbox artifact output directory. Without this tool, the LLM cannot
// see files produced by prior skill invocations in the same session and
// has to guess paths when chaining skills together.
// inspectable sandbox directories. Without this tool, the LLM cannot
// see files produced by prior skill invocations or staged chat
// attachments and has to guess paths when chaining work together.
//
// Design notes:
// - Session-scoped: the sandbox path is resolved from the tool exec
// context (`ToolExecContext.SessionID`). The LLM cannot pass an
// arbitrary session ID.
// - Directory guardrail: `path` must resolve underneath the session's
// artifact output dir (`$WEKNORA_SKILL_OUTPUT_DIR`, default
// `/workspace/output`). This keeps the tool aligned with the
// directory ArtifactCollector already drains so anything the LLM
// lists is guaranteed to also become a downloadable artifact.
// - Directory guardrail: `path` must resolve underneath one of the
// inspectable roots — the artifact output dir
// (`$WEKNORA_SKILL_OUTPUT_DIR`, default `/workspace/output`) or the
// session input dir (`/workspace/input`). Output stays aligned with
// ArtifactCollector; input is where chat attachments are staged.
// 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.
// - Graceful "no sandbox": if the session has never spawned a sandbox
@ -63,7 +65,7 @@ const (
var listSandboxFilesTool = BaseTool{
name: ToolListSandboxFiles,
description: `List files produced by prior skill executions in the current session's sandbox.
description: `List files in the current session's inspectable sandbox directories.
## Usage
- Call this tool BEFORE invoking a follow-up skill that consumes a file
@ -71,21 +73,25 @@ var listSandboxFilesTool = BaseTool{
guessing paths; with it you can see exactly what is available.
- Also useful to confirm a skill actually produced the files it claims to
have generated (e.g. before telling the user "your report is ready").
- Pass ` + "`/workspace/input`" + ` (or a path from the current
` + "`<sandbox_attachments>`" + ` block) to list staged chat attachments.
## When to Use
- The user asks a follow-up question that references a file from a prior
turn ("summarize the report you generated", "improve the chart").
- You are about to chain two skills where the second consumes an output
of the first.
- You want to inspect a user-uploaded attachment staged under
` + "`/workspace/input`" + `.
- You want to give the user a listing of everything the current session
has produced.
## Path Rules
- ` + "`path`" + ` is optional. When omitted, the tool lists the default artifact
output directory (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `).
- When provided, ` + "`path`" + ` MUST be underneath the artifact output directory.
Attempts to list arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `) are
rejected.
- When provided, ` + "`path`" + ` MUST sit under the artifact output directory or
the session input directory (` + "`/workspace/input`" + `). Attempts to list
arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `) are rejected.
- Listing is recursive: sub-directories are traversed automatically and
only files are returned in the flat listing.
@ -101,9 +107,9 @@ var listSandboxFilesTool = BaseTool{
// ListSandboxFilesInput defines the input parameters for list_sandbox_files.
type ListSandboxFilesInput struct {
// Path is the absolute path inside the sandbox to list. When empty
// the tool falls back to skills.ArtifactOutputDir(). Must be
// underneath the artifact output directory.
Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list. Defaults to the session's artifact output directory. Must be underneath that directory."`
// the tool falls back to skills.ArtifactOutputDir(). Must sit under
// the artifact output directory or /workspace/input.
Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list. Defaults to the session's artifact output directory. Must sit under that directory or /workspace/input."`
// MaxEntries caps the listing size to protect the LLM context.
// Zero uses defaultListSandboxMaxEntries.
MaxEntries int `json:"max_entries,omitempty" jsonschema:"Optional cap on the number of entries returned. Defaults to 200, hard-capped at 500. Use a smaller value when you only need to check whether a specific file exists."`
@ -157,24 +163,23 @@ func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessage
}
// Resolve target directory. When the caller omits path we scan the
// same directory ArtifactCollector drains, guaranteeing everything
// the LLM sees will also be downloadable.
rootDir := skills.ArtifactOutputDir()
// same directory ArtifactCollector drains. An explicit path may also
// sit under /workspace/input so staged chat attachments are listable.
targetDir := strings.TrimSpace(input.Path)
if targetDir == "" {
targetDir = rootDir
targetDir = skills.ArtifactOutputDir()
} else {
clean := path.Clean(targetDir)
if !isUnderRoot(clean, rootDir) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path %q is outside the artifact output directory %q; the LLM can only list files under the artifact output directory",
input.Path, rootDir,
),
}, nil
}
targetDir = clean
targetDir = path.Clean(targetDir)
}
rootDir, ok := matchingInspectableRoot(targetDir)
if !ok {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path %q is outside the inspectable sandbox directories (%s)",
input.Path, inspectableRootsDescription(),
),
}, nil
}
maxEntries := input.MaxEntries
@ -213,7 +218,7 @@ func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessage
var b strings.Builder
b.WriteString(fmt.Sprintf("=== Sandbox listing: %s ===\n\n", targetDir))
if len(entries) == 0 {
b.WriteString("No files found. Either no skill has produced output in this session yet, or the sandbox has been reaped.\n")
b.WriteString("No files found under this path. Either nothing has been written here yet, or the sandbox has been reaped.\n")
} else {
b.WriteString(fmt.Sprintf("Found %d file(s)", len(entries)))
if truncated {
@ -282,9 +287,33 @@ func resolveSessionID(ctx context.Context) string {
return ""
}
// sandboxInspectableRoots is the allowlist for list_sandbox_files and
// read_sandbox_file. Artifact output is where skills write downloadable
// files; session input is where chat attachments are staged. Anything
// else (including /workspace itself) stays unreachable so these tools
// cannot become a general-purpose filesystem reader.
func sandboxInspectableRoots() []string {
return []string{skills.ArtifactOutputDir(), sandbox.SessionInputRoot}
}
func inspectableRootsDescription() string {
return strings.Join(sandboxInspectableRoots(), ", ")
}
// matchingInspectableRoot returns the allowlisted root that contains
// clean, or ("", false) when the path sits outside every root.
func matchingInspectableRoot(clean string) (string, bool) {
for _, root := range sandboxInspectableRoots() {
if isUnderRoot(clean, root) {
return root, true
}
}
return "", false
}
// 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 artifact output directory: even if a rogue
// listing paths outside the inspectable directories: even if a rogue
// prompt asks for `/etc/passwd`, the tool refuses.
func isUnderRoot(clean, root string) bool {
if clean == root {

View File

@ -1,17 +1,17 @@
// Package tools — read_sandbox_file.
//
// Read-only tool that lets the LLM read the contents of a file the
// current session's sandbox has produced. Pairs with list_sandbox_files:
// the LLM lists first, then reads a specific path.
// Read-only tool that lets the LLM read a file under the session's
// inspectable sandbox directories. Pairs with list_sandbox_files: the
// LLM lists first, then reads a specific path.
//
// Design notes:
// - Session-scoped: path must belong to the current session's sandbox,
// enforced by delegating to SandboxFileSource.ReadSessionFile which
// itself takes the session ID from context.
// - Directory guardrail: path must sit underneath the artifact output
// directory. This makes the tool a companion to ArtifactCollector,
// not a general-purpose filesystem reader (skills that need to peek
// elsewhere should print via stdout).
// directory or /workspace/input. Output is a companion to
// ArtifactCollector; input is where chat attachments are staged.
// Skills that need to peek elsewhere should print via stdout.
// - Stat-first size cap: files over 64 KiB are never downloaded. The
// model receives metadata and uses shell_exec with sed/head/tail/grep/awk
// to inspect only the relevant text section.
@ -26,7 +26,6 @@ import (
"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"
@ -44,13 +43,15 @@ const (
var readSandboxFileTool = BaseTool{
name: ToolReadSandboxFile,
description: `Read the contents of a file the current session's sandbox has produced.
description: `Read the contents of a file in the current session's inspectable sandbox directories.
## Usage
- Use in tandem with ` + "`list_sandbox_files`" + `: first list to find the file,
then read to inspect its content.
- Handy when the user asks "what did that report say?" or you want to
quote a section of a skill-generated artifact.
- Also use this to inspect a staged chat attachment under
` + "`/workspace/input`" + ` when ` + "`shell_exec`" + ` is not available.
## When to Use
- After a skill claims it wrote something and you want to confirm the
@ -60,12 +61,16 @@ var readSandboxFileTool = BaseTool{
to pass.
- When the user asks you to summarise or edit a previously generated
artifact.
- When ` + "`<sandbox_attachments>`" + ` lists a user-uploaded file you need to
read without running a shell command.
## Path Rules
- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `.
- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `
or listed in the current ` + "`<sandbox_attachments>`" + ` block.
- ` + "`path`" + ` MUST sit underneath the session's artifact output directory
(` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `). Reads
outside that directory are rejected.
(` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `) or the
session input directory (` + "`/workspace/input`" + `). Reads outside those
directories are rejected.
## Size Handling
- Files larger than 64 KiB are NOT downloaded or returned.
@ -83,8 +88,8 @@ var readSandboxFileTool = BaseTool{
// ReadSandboxFileInput defines the input parameters for read_sandbox_file.
type ReadSandboxFileInput struct {
// Path is the absolute path inside the sandbox to read. Required.
// Must sit underneath the artifact output directory.
Path string `json:"path" jsonschema:"Absolute path inside the sandbox. Must sit under the session's artifact output directory (typically /workspace/output). Get valid paths from list_sandbox_files."`
// Must sit underneath the artifact output directory or /workspace/input.
Path string `json:"path" jsonschema:"Absolute path inside the sandbox. Must sit under the session's artifact output directory (typically /workspace/output) or /workspace/input. Get valid paths from list_sandbox_files or the current sandbox_attachments block."`
// MaxBytes is the largest file the tool may download. Zero uses 64 KiB;
// callers may lower but never raise the hard 64 KiB ceiling.
MaxBytes int64 `json:"max_bytes,omitempty" jsonschema:"Optional maximum file size to read. Defaults to 65536 bytes and is hard-capped at 65536. Larger files are not downloaded; use shell_exec with sed/head/tail/grep/awk."`
@ -143,17 +148,17 @@ func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage)
}, nil
}
// Enforce that the path sits underneath the artifact output dir.
// This mirrors list_sandbox_files' rule so the LLM sees a
// consistent "reachable surface".
rootDir := skills.ArtifactOutputDir()
// Enforce that the path sits underneath an inspectable root. This
// mirrors list_sandbox_files so the LLM sees a consistent reachable
// surface covering both skill output and staged attachments.
clean := path.Clean(trimmed)
if !isUnderRoot(clean, rootDir) {
rootDir, ok := matchingInspectableRoot(clean)
if !ok {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path %q is outside the artifact output directory %q; only files produced under that directory can be read",
input.Path, rootDir,
"path %q is outside the inspectable sandbox directories (%s)",
input.Path, inspectableRootsDescription(),
),
}, nil
}
@ -202,8 +207,8 @@ func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path is not a regular file: %s; only files produced under %s can be read",
clean, rootDir,
"path is not a regular file: %s; only files under %s can be read",
clean, inspectableRootsDescription(),
),
}, nil
}

View File

@ -20,9 +20,11 @@ type fakeSandboxFileSource struct {
entries []sandbox.RemoteDirEntry
statCalls int
readCalls int
listedDir string
}
func (f *fakeSandboxFileSource) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
func (f *fakeSandboxFileSource) ListSessionFiles(_ context.Context, _, dir string) ([]sandbox.RemoteDirEntry, error) {
f.listedDir = dir
return f.entries, nil
}
@ -153,3 +155,94 @@ func TestListSandboxFilesHardCapsEntries(t *testing.T) {
assert.Equal(t, true, result.Data["truncated"])
assert.Equal(t, maxListSandboxMaxEntries, strings.Count(result.Output, "\n- "))
}
func TestReadSandboxFileAllowsSessionInput(t *testing.T) {
content := []byte("uploaded report\n")
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{
Path: "/workspace/input/ab12cd/report.txt",
Type: sandbox.RemoteEntryFile,
Size: int64(len(content)),
},
data: content,
}
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/input/ab12cd/report.txt"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, 1, source.readCalls)
assert.Contains(t, result.Output, string(content))
assert.Equal(t, sandbox.SessionInputRoot, result.Data["root"])
}
func TestReadSandboxFileRefusesOutsideInspectableRoots(t *testing.T) {
source := &fakeSandboxFileSource{
data: []byte("must not be read"),
stat: &sandbox.RemoteStatEntry{Path: "/etc/passwd", Type: sandbox.RemoteEntryFile, Size: 4},
}
for _, path := range []string{"/etc/passwd", "/workspace/other/file.txt", "/workspace"} {
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"`+path+`"}`),
)
require.NoError(t, err, path)
require.False(t, result.Success, path)
assert.Contains(t, result.Error, "outside the inspectable sandbox directories", path)
}
assert.Zero(t, source.readCalls)
assert.Zero(t, source.statCalls)
}
func TestListSandboxFilesDefaultsToOutput(t *testing.T) {
source := &fakeSandboxFileSource{}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, sandboxInspectableRoots()[0], source.listedDir)
assert.Equal(t, sandboxInspectableRoots()[0], result.Data["path"])
}
func TestListSandboxFilesAllowsSessionInput(t *testing.T) {
source := &fakeSandboxFileSource{
entries: []sandbox.RemoteDirEntry{{
Name: "report.txt",
Path: "/workspace/input/ab12cd/report.txt",
Type: sandbox.RemoteEntryFile,
}},
}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/input"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, sandbox.SessionInputRoot, source.listedDir)
assert.Equal(t, sandbox.SessionInputRoot, result.Data["root"])
assert.Equal(t, 1, result.Data["count"])
}
func TestListSandboxFilesRefusesOutsideInspectableRoots(t *testing.T) {
source := &fakeSandboxFileSource{}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/etc"}`),
)
require.NoError(t, err)
require.False(t, result.Success)
assert.Contains(t, result.Error, "outside the inspectable sandbox directories")
assert.Empty(t, source.listedDir)
}

View File

@ -204,6 +204,10 @@ func (s *agentService) CreateAgentEngine(
// skill switch: register them whenever the workspace sandbox supports a
// session filesystem, even when skills are disabled.
s.registerSandboxFileTools(ctx, toolRegistry, sessionID, config)
// shell_exec follows SkillsEnabled (or install mode), not the presence
// of a ready skill. Register it independently of the skills manager so a
// fresh or still-installing sandbox still has a shell.
s.registerSandboxShellIfAllowed(ctx, toolRegistry, sessionID, config)
// 3. Resolve knowledge base and selected document metadata
kbInfos, selectedDocs := s.resolveKBAndDocInfos(ctx, config)
@ -246,24 +250,22 @@ func (s *agentService) CreateAgentEngine(
// TenantSkills is the sandbox image. SkillDirs is the host
// skills/preloaded tree and is no longer filled on the QA path; it
// remains so tests (and any caller that still points at a host
// directory) can construct a manager. Install mode initializes for
// the shell without hanging a skills manager on the engine.
// directory) can construct a manager.
//
// The shell entry point follows SkillsEnabled rather than requiring a
// ready skill to already exist: shell_exec can execute skill scripts, so
// it belongs under the workspace's explicit skill switch. A sandbox whose
// skills are still installing — or that simply has none yet — must still
// hand the model a shell when skills are enabled, otherwise an agent
// pointed at a fresh sandbox has no way to inspect its environment.
// offerSkills (below) still gates the skills manager that feeds the model
// the installed-skill list; it does not gate the shell.
// The shell is registered above by registerSandboxShellIfAllowed and
// follows SkillsEnabled rather than requiring a ready skill to already
// exist. offerSkills only gates the skills manager that feeds the model
// the installed-skill list (and the read_skill / execute_skill_script
// tools that need it). A sandbox whose skills are still installing —
// or that simply has none yet — therefore gets a shell without an
// empty skills manager or skill tools that cannot succeed.
offerSkills := config.SkillsEnabled &&
(len(config.SkillDirs) > 0 || len(config.TenantSkills) > 0)
if config.SkillsEnabled || config.SkillInstallMode() {
if offerSkills {
skillsManager, err := s.initializeSkillsManager(ctx, sessionID, config, toolRegistry)
if err != nil {
logger.Warnf(ctx, "Failed to initialize skills manager: %v", err)
} else if offerSkills && skillsManager != nil {
} else if skillsManager != nil {
engine.SetSkillsManager(skillsManager)
logger.Infof(ctx, "Skills manager initialized with %d skills",
len(skillsManager.GetAllMetadata()))
@ -384,7 +386,8 @@ func (s *agentService) resolveKBAndDocInfos(
// These expose per-session filesystem inspection 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. Registration only requires a
// 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
@ -399,19 +402,12 @@ func (s *agentService) registerSandboxFileTools(
sessionID string,
config *types.AgentConfig,
) {
if s == nil {
return
}
tenantID, _ := types.TenantIDFromContext(ctx)
sandboxMgr, _, err := resolveSandboxForExecution(
ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,
tenantID, sessionID, config.SandboxConfigID, s.sandboxPolicy,
)
sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for file tools: %v", err)
return
}
if sandboxMgr == nil || sandboxMgr.GetType() == sandbox.SandboxTypeDisabled {
if sandboxMgr == nil {
return
}
if store := sessionSandboxFileStore(sandboxMgr); store != nil {
@ -424,6 +420,60 @@ func (s *agentService) registerSandboxFileTools(
}
}
// 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
// fresh sandbox still has a way to inspect its environment.
func (s *agentService) registerSandboxShellIfAllowed(
ctx context.Context,
toolRegistry *tools.ToolRegistry,
sessionID string,
config *types.AgentConfig,
) {
if config == nil || (!config.SkillsEnabled && !config.SkillInstallMode()) {
return
}
sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for shell_exec: %v", err)
return
}
if sandboxMgr == nil {
return
}
s.registerSandboxShellTool(ctx, toolRegistry, sandboxMgr, config)
}
// resolveWorkspaceSandbox returns the session's remote sandbox manager, or
// nil when the workspace is disabled / unresolved. Callers that only need
// a capability (file store, shell) use this so they do not have to stand
// up a skills manager.
func (s *agentService) resolveWorkspaceSandbox(
ctx context.Context,
sessionID string,
config *types.AgentConfig,
) (sandbox.Manager, error) {
if s == nil {
return nil, nil
}
configID := ""
if config != nil {
configID = config.SandboxConfigID
}
tenantID, _ := types.TenantIDFromContext(ctx)
sandboxMgr, _, err := resolveSandboxForExecution(
ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,
tenantID, sessionID, configID, s.sandboxPolicy,
)
if err != nil {
return nil, err
}
if sandboxMgr == nil || sandboxMgr.GetType() == sandbox.SandboxTypeDisabled {
return nil, nil
}
return sandboxMgr, nil
}
// initializeSkillsManager creates and initializes the skills manager.
//
// The sandbox manager is resolved per workspace: backends differ in
@ -472,26 +522,17 @@ func (s *agentService) initializeSkillsManager(
}
// Skill tools follow SkillsEnabled, not merely sandbox availability: the
// skill installer agent must have shell_exec WITHOUT
// execute_skill_script, since it is the thing installing skills.
// skill installer agent must have shell_exec WITHOUT execute_skill_script,
// since it is the thing installing skills. shell_exec itself is registered
// by registerSandboxShellIfAllowed, not here.
if config.SkillsEnabled {
toolRegistry.RegisterTool(tools.NewReadSkillTool(skillsManager))
logger.Infof(ctx, "Registered read_skill tool")
}
if sandboxMgr.GetType() != sandbox.SandboxTypeDisabled {
if config.SkillsEnabled {
toolRegistry.RegisterTool(tools.NewExecuteSkillScriptTool(skillsManager))
logger.Infof(ctx, "Registered execute_skill_script tool")
}
// shell_exec follows SkillsEnabled (it can execute skill scripts) and
// is registered by registerSandboxShellTool below. list_sandbox_files
// and read_sandbox_file are pure filesystem capabilities and are
// registered separately in registerSandboxFileTools, independent of
// SkillsEnabled.
s.registerSandboxShellTool(ctx, toolRegistry, sandboxMgr, config)
if sandboxMgr.GetType() != sandbox.SandboxTypeDisabled && config.SkillsEnabled {
toolRegistry.RegisterTool(tools.NewExecuteSkillScriptTool(skillsManager))
logger.Infof(ctx, "Registered execute_skill_script tool")
}
return skillsManager, nil
@ -946,10 +987,10 @@ func (s *agentService) registerTools(
case tools.ToolShellExec, tools.ToolReadSkill, tools.ToolExecuteSkillScript,
tools.ToolListSandboxFiles, tools.ToolReadSandboxFile:
// Bound to the resolved sandbox manager in initializeSkillsManager
// / registerSandboxShellTool. Listing them here would warn
// "Unknown tool: shell_exec" on every skill install, then register
// the real tool a few lines later.
// Bound to the resolved sandbox manager in registerSandboxFileTools
// / registerSandboxShellIfAllowed / initializeSkillsManager.
// Listing them here would warn "Unknown tool: shell_exec" on every
// skill install, then register the real tool a few lines later.
continue
default:

View File

@ -293,7 +293,7 @@ func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {
}
func TestSkillToolsFollowSkillsEnabled(t *testing.T) {
t.Run("skills disabled: no skill tools, shell_exec still available", func(t *testing.T) {
t.Run("skills disabled: initializeSkillsManager registers no skill tools or shell", func(t *testing.T) {
registry := tools.NewToolRegistry()
svc := &agentService{
sandboxResolver: stubSandboxResolver{
@ -311,11 +311,11 @@ func TestSkillToolsFollowSkillsEnabled(t *testing.T) {
require.NoError(t, err)
require.False(t, toolRegistered(registry, tools.ToolReadSkill))
require.False(t, toolRegistered(registry, tools.ToolExecuteSkillScript))
require.True(t, toolRegistered(registry, tools.ToolShellExec),
"the installer agent needs shell_exec without any skill tooling")
require.False(t, toolRegistered(registry, tools.ToolShellExec),
"shell_exec is registered by registerSandboxShellIfAllowed, not initializeSkillsManager")
})
t.Run("skills enabled: existing behaviour is unchanged", func(t *testing.T) {
t.Run("skills enabled: skill tools without shell", func(t *testing.T) {
registry := tools.NewToolRegistry()
svc := &agentService{
sandboxResolver: stubSandboxResolver{
@ -333,7 +333,8 @@ func TestSkillToolsFollowSkillsEnabled(t *testing.T) {
require.NoError(t, err)
require.True(t, toolRegistered(registry, tools.ToolReadSkill))
require.True(t, toolRegistered(registry, tools.ToolExecuteSkillScript))
require.True(t, toolRegistered(registry, tools.ToolShellExec))
require.False(t, toolRegistered(registry, tools.ToolShellExec),
"shell_exec is registered separately from the skills manager")
})
}
@ -367,6 +368,12 @@ func TestCreateAgentEngineShellFollowsSkillsEnabledWithoutInstalledSkills(t *tes
require.NoError(t, err)
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec),
"an agent with skills enabled must have shell_exec even when no ready skill exists yet")
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill),
"an empty sandbox must not be offered skill tools that cannot succeed")
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))
require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())
}
// Whether an installed skill is invocable is decided when the AgentConfig is

View File

@ -272,7 +272,7 @@ func buildSandboxAttachmentsPrompt(attachments []stagedSessionAttachment) string
escapeAttachmentXML(attachment.Path),
)
}
b.WriteString(" <instruction>Use these absolute paths as read-only inputs for shell commands or skill script arguments. 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. Write generated files only under $WEKNORA_SKILL_OUTPUT_DIR.</instruction>\n")
b.WriteString("</sandbox_attachments>")
return b.String()
}

View File

@ -180,13 +180,11 @@ func TestBuildSandboxAttachmentsPromptEscapesMetadata(t *testing.T) {
assert.Contains(t, prompt, `name="a&lt;&amp;&gt;.txt"`)
assert.Contains(t, prompt, `path="/workspace/input/hash/a.txt"`)
assert.Contains(t, prompt, "read-only inputs")
assert.Contains(t, prompt, "read_sandbox_file")
}
func TestStageSessionAttachmentsResolvesURLFromTemporaryDocument(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.TemporaryDocument{}))
db := stagingTempDocDB(t)
docID := "doc-1"
resourceRef := "local://tenant/attachment-1"
require.NoError(t, db.Create(&types.TemporaryDocument{
@ -241,3 +239,124 @@ func TestStageSessionAttachmentsResolvesURLFromTemporaryDocument(t *testing.T) {
assert.Equal(t, []string{remotePath}, manager.writes)
assert.Equal(t, 1, fileService.getCalls[resourceRef])
}
func TestStageSessionAttachmentsSkipsMissingTemporaryDocument(t *testing.T) {
db := stagingTempDocDB(t)
manager := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
fileService := &stagingFileService{files: map[string][]byte{}}
service := &agentService{
db: db,
sandboxMgr: manager,
fileService: fileService,
sandboxResolver: stubSandboxResolver{mgr: manager},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
staged, err := service.stageSessionAttachments(
ctx,
"session-1",
"cfg-remote",
7,
types.MessageAttachments{{
ID: "missing-doc", FileName: "gone.pdf", FileType: ".pdf", FileSize: 7,
}},
)
require.NoError(t, err)
assert.Empty(t, staged)
assert.Empty(t, manager.writes)
}
func TestStageSessionAttachmentsIgnoresWrongTenant(t *testing.T) {
db := stagingTempDocDB(t)
resourceRef := "local://tenant/attachment-1"
require.NoError(t, db.Create(&types.TemporaryDocument{
ID: "doc-1",
TenantID: 7,
SessionID: "session-1",
ResourceRef: resourceRef,
FileName: "report.pdf",
FileType: ".pdf",
FileSize: 7,
Status: types.TemporaryDocumentStatusReady,
ExpiresAt: time.Now().Add(time.Hour),
}).Error)
manager := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
fileService := &stagingFileService{
files: map[string][]byte{resourceRef: []byte("content")},
}
service := &agentService{
db: db,
sandboxMgr: manager,
fileService: fileService,
sandboxResolver: stubSandboxResolver{mgr: manager},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(99))
staged, err := service.stageSessionAttachments(
ctx,
"session-1",
"cfg-remote",
99, // session tenant must not see another tenant's temporary document
types.MessageAttachments{{
ID: "doc-1", FileName: "report.pdf", FileType: ".pdf", FileSize: 7,
}},
)
require.NoError(t, err)
assert.Empty(t, staged)
assert.Empty(t, manager.writes)
assert.Empty(t, fileService.getCalls)
}
func TestStageSessionAttachmentsKeepsExistingURLWithoutLookup(t *testing.T) {
db := stagingTempDocDB(t)
attachment := types.MessageAttachment{
ID: "doc-1",
URL: "local://tenant/already-present",
FileName: "notes.txt",
FileType: ".txt",
FileSize: 4,
}
require.NoError(t, db.Create(&types.TemporaryDocument{
ID: "doc-1",
TenantID: 7,
SessionID: "session-1",
ResourceRef: "local://tenant/must-not-be-used",
FileName: "notes.txt",
FileType: ".txt",
FileSize: 4,
Status: types.TemporaryDocumentStatusReady,
ExpiresAt: time.Now().Add(time.Hour),
}).Error)
manager := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
fileService := &stagingFileService{
files: map[string][]byte{attachment.URL: []byte("keep")},
}
service := &agentService{
db: db,
sandboxMgr: manager,
fileService: fileService,
sandboxResolver: stubSandboxResolver{mgr: manager},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
staged, err := service.stageSessionAttachments(
ctx, "session-1", "cfg-remote", 7, types.MessageAttachments{attachment},
)
require.NoError(t, err)
require.Len(t, staged, 1)
assert.Equal(t, 1, fileService.getCalls[attachment.URL])
assert.Zero(t, fileService.getCalls["local://tenant/must-not-be-used"])
}
func stagingTempDocDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.TemporaryDocument{}))
return db
}