feat(sandbox): add tenant skill install and remove service layer

Introduce the hidden skill-installer agent and TenantSkillService so a
sandbox config can install or remove skills into snapshot images under a
per-config lock, without yet exposing HTTP or UI entry points.

Co-authored-by: Cursor <cursoragent@cursor.com>
main
hailongzhao 2026-08-20 12:02:59 +08:00 committed by lyingbug
parent 3505a58c37
commit 67cdf26216
27 changed files with 5066 additions and 77 deletions

View File

@ -233,3 +233,39 @@ builtin_agents:
rerank_top_k: 10
rerank_threshold: 0.3
- id: "builtin-skill-installer"
avatar: "📦"
is_builtin: true
i18n:
default:
name: "Skill Installer"
description: "Internal agent that installs an uploaded skill and its dependencies into the sandbox image"
zh-CN:
name: "技能安装器"
description: "把上传的技能及其依赖装进沙盒镜像的内部智能体"
zh-TW:
name: "技能安裝器"
description: "把上傳的技能及其相依套件裝進沙盒鏡像的內部智能體"
ja-JP:
name: "スキルインストーラー"
description: "アップロードされたスキルとその依存関係をサンドボックスイメージにインストールする内部エージェント"
ko-KR:
name: "스킬 설치 도구"
description: "업로드된 스킬과 의존성을 샌드박스 이미지에 설치하는 내부 에이전트"
config:
agent_mode: "smart-reasoning"
agent_type: "custom"
system_prompt_id: "skill_installer"
temperature: 0.2
max_completion_tokens: 4096
max_iterations: 30
kb_selection_mode: "none"
retrieve_kb_only_when_mentioned: false
allowed_tools:
- "shell_exec"
web_search_enabled: false
web_search_max_results: 0
reflection_enabled: false
multi_turn_enabled: true
history_turns: 10

View File

@ -487,3 +487,62 @@ templates:
<system_status>
User Language: {{language}}
</system_status>
- id: "skill_installer"
name: "Skill Installer System Prompt"
description: "System prompt for installing an uploaded skill and its dependencies into the sandbox image"
i18n:
zh-CN:
name: "技能安装系统提示词"
description: "用于把上传的技能及其依赖装进沙盒镜像的系统提示词"
en-US:
name: "Skill Installer System Prompt"
description: "System prompt for installing an uploaded skill and its dependencies into the sandbox image"
mode: "smart-reasoning"
content: |
<role>
You are the WeKnora Skill Installer. You install ONE skill and its dependencies into a sandbox image, using shell commands. The image will be snapshotted afterwards and reused by every future session of this sandbox config.
</role>
<inputs>
The user message gives you:
- the skill directory (absolute path, already seeded with the skill's source files)
- the full text of that skill's SKILL.md
- whether `uv` is available in this image
</inputs>
<workflow>
1. Read the SKILL.md text in the user message and work out what has to be installed. Dependencies are often described in prose rather than a requirements file — read carefully.
2. Inspect the skill directory with `ls -la` before installing, so you know which of requirements.txt / pyproject.toml / package.json actually exist.
3. Install dependencies INTO THE SKILL DIRECTORY (see <isolation>).
4. Verify by actually running the skill's entry point (for example `--help`). Do not declare success until a real command exits 0.
5. Reply with a short summary: what you installed, where it went, and what you ran to verify.
</workflow>
<isolation>
This is the most important part. Every skill on this image shares one root filesystem, so anything you install globally is inherited by every other skill forever.
- Python: create the skill's OWN virtual environment at `<skill-dir>/.venv` and install into it.
With uv: `uv venv <skill-dir>/.venv` then `uv pip install --python <skill-dir>/.venv/bin/python -r <skill-dir>/requirements.txt`
Without uv: `python3 -m venv <skill-dir>/.venv` then `<skill-dir>/.venv/bin/pip install -r <skill-dir>/requirements.txt`
- Node: install into `<skill-dir>/node_modules`, e.g. `pnpm install` with work_dir set to the skill directory.
- Never `pip install` into the system Python. Never `pnpm add -g` / `npm i -g` unless there is no alternative.
- `apt-get install` IS allowed for genuine system libraries (e.g. libgl1) that cannot live in the skill directory. If you use it, say so explicitly in your final summary.
</isolation>
<tool_guidelines>
* **shell_exec:** your only tool. You may set `work_dir` to the skill directory (it is allowed for this session) and then use relative paths, or leave `work_dir` unset and use absolute paths. Both work.
* Prefer one command per call so a failure is easy to attribute.
* If a command fails, read the error and adapt — do not repeat the identical command.
</tool_guidelines>
<constraints>
1. Only write inside the skill directory, apart from deliberate system packages via apt-get.
2. Do not modify or delete other skills' directories.
3. Do not touch /workspace: it is wiped before the snapshot is taken.
4. Do not attempt to snapshot, restart or shut down the sandbox — the server does that after you finish.
5. Your last message must be the summary described in step 5, with no further tool calls.
</constraints>
<system_status>
User Language: {{language}}
</system_status>

View File

@ -207,10 +207,52 @@ type ShellExecInput struct {
Env map[string]string `json:"env,omitempty" jsonschema:"Optional extra environment variables, e.g. {\"PIP_INDEX_URL\":\"https://mirrors.example.com/pypi/simple\"}."`
}
// SandboxInstallCommandExecutor is the privileged counterpart of
// SandboxCommandExecutor, satisfied by *sandbox.SessionBoundManager via
// sandbox.SessionInstallShellExecutor. It exists as its own named type so the
// install privilege can only be handed over deliberately: nothing that merely
// implements ExecShellCommand can be mistaken for it.
type SandboxInstallCommandExecutor interface {
ExecShellCommandWithOptions(
ctx context.Context,
sessionID string,
command string,
opts sandbox.ShellExecOptions,
) (*sandbox.ExecuteResult, error)
}
// installShellExecutor adapts the privileged executor to the plain executor
// contract the tool speaks, stamping every call as root with the skills image
// root writable. The install agent's whole job is to install dependencies into
// that image, which the default user cannot write.
type installShellExecutor struct {
inner SandboxInstallCommandExecutor
}
func (e installShellExecutor) ExecShellCommand(
ctx context.Context,
sessionID string,
command string,
workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error) {
return e.inner.ExecShellCommandWithOptions(ctx, sessionID, command, sandbox.ShellExecOptions{
WorkDir: workDir,
Timeout: timeout,
Env: env,
AllowSkillsRoot: true,
AsRoot: true,
})
}
// ShellExecTool executes shell commands inside the session's sandbox.
type ShellExecTool struct {
BaseTool
executor SandboxCommandExecutor
// workDirRoots are the directories work_dir may point inside. Ordinary
// sessions get /workspace only; install mode adds the skills image root.
workDirRoots []string
}
// NewShellExecTool constructs the tool. `executor` MUST NOT be nil:
@ -218,8 +260,20 @@ type ShellExecTool struct {
// does not support ad-hoc shell execution (i.e. is not Cube).
func NewShellExecTool(executor SandboxCommandExecutor) *ShellExecTool {
return &ShellExecTool{
BaseTool: shellExecTool,
executor: executor,
BaseTool: shellExecTool,
executor: executor,
workDirRoots: []string{defaultShellExecWorkDir},
}
}
// 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 {
return &ShellExecTool{
BaseTool: shellExecTool,
executor: installShellExecutor{inner: executor},
workDirRoots: []string{defaultShellExecWorkDir, sandbox.SkillsImageRoot},
}
}
@ -282,12 +336,12 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
workDir = defaultShellExecWorkDir
}
cleanWorkDir := path.Clean(workDir)
if !isUnderRoot(cleanWorkDir, defaultShellExecWorkDir) {
if !t.workDirAllowed(cleanWorkDir) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"work_dir %q is outside the sandbox workspace %q",
input.WorkDir, defaultShellExecWorkDir,
"work_dir %q is outside the allowed sandbox roots %s",
input.WorkDir, strings.Join(t.allowedWorkDirRoots(), ", "),
),
}, nil
}
@ -408,6 +462,24 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
}, nil
}
// 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 {
if len(t.workDirRoots) == 0 {
return []string{defaultShellExecWorkDir}
}
return t.workDirRoots
}
func (t *ShellExecTool) workDirAllowed(cleanWorkDir string) bool {
for _, root := range t.allowedWorkDirRoots() {
if isUnderRoot(cleanWorkDir, root) {
return true
}
}
return false
}
func resolveShellOutputLimit(requested int) int {
if requested <= 0 {
return defaultShellExecOutputBytes

View File

@ -51,7 +51,7 @@ func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
require.NoError(t, err)
require.False(t, result.Success)
require.Contains(t, result.Error, "outside the sandbox workspace")
require.Contains(t, result.Error, `work_dir "/etc" is outside the allowed sandbox roots /workspace`)
assert.Equal(t, time.Duration(0), executor.timeout)
}

View File

@ -235,12 +235,20 @@ func (s *agentService) CreateAgentEngine(
}
}
// Initialize skills manager if skills are enabled
if config.SkillsEnabled && len(config.SkillDirs) > 0 {
skillsEnabledWithDirs := config.SkillsEnabled && len(config.SkillDirs) > 0
// Initialize the skills/sandbox manager when skills are configured, or for
// the skill installer, which keeps skills off yet needs the sandbox shell.
// The second disjunct is deliberately NOT "the config lists a sandbox
// tool": shell_exec is a user-selectable entry in the tool picker, so that
// rule would hand a live sandbox shell to every stored agent record that
// already lists it. Install mode is settable only through
// EnableSkillInstallMode, so only the built-in installer passes here and
// every other agent keeps exactly its previous behaviour.
if skillsEnabledWithDirs || config.SkillInstallMode() {
skillsManager, err := s.initializeSkillsManager(ctx, sessionID, config, toolRegistry)
if err != nil {
logger.Warnf(ctx, "Failed to initialize skills manager: %v", err)
} else if skillsManager != nil {
} else if skillsEnabledWithDirs && skillsManager != nil {
engine.SetSkillsManager(skillsManager)
logger.Infof(ctx, "Skills manager initialized with %d skills",
len(skillsManager.GetAllMetadata()))
@ -397,15 +405,19 @@ func (s *agentService) initializeSkillsManager(
return nil, fmt.Errorf("failed to initialize skills: %w", err)
}
// Register skills tools
readSkillTool := tools.NewReadSkillTool(skillsManager)
toolRegistry.RegisterTool(readSkillTool)
logger.Infof(ctx, "Registered read_skill tool")
// 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.
if config.SkillsEnabled {
toolRegistry.RegisterTool(tools.NewReadSkillTool(skillsManager))
logger.Infof(ctx, "Registered read_skill tool")
}
if sandboxMgr.GetType() != sandbox.SandboxTypeDisabled {
executeSkillTool := tools.NewExecuteSkillScriptTool(skillsManager)
toolRegistry.RegisterTool(executeSkillTool)
logger.Infof(ctx, "Registered execute_skill_script tool")
if config.SkillsEnabled {
toolRegistry.RegisterTool(tools.NewExecuteSkillScriptTool(skillsManager))
logger.Infof(ctx, "Registered execute_skill_script tool")
}
// list_sandbox_files / read_sandbox_file expose per-session
// filesystem inspection. Registration is gated on the sandbox
@ -413,29 +425,65 @@ func (s *agentService) initializeSkillsManager(
// that fell back to a stateless local sandbox return nil so we
// never surface tenant-isolated tools that would run on the
// WeKnora host.
if store := sessionSandboxFileStore(sandboxMgr); store != nil {
toolRegistry.RegisterTool(tools.NewListSandboxFilesTool(store))
toolRegistry.RegisterTool(tools.NewReadSandboxFileTool(store))
logger.Infof(ctx, "Registered list_sandbox_files and read_sandbox_file tools")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise session filesystem capability; list_sandbox_files/read_sandbox_file not registered")
//
// They follow SkillsEnabled for the same reason the skill tools do:
// the installer agent is here only for the shell it needs to install
// dependencies, and its prompt tells it to use shell_exec alone. A
// root shell can already read and list anything these two could, so
// offering them adds nothing but tool surface and iteration budget.
if config.SkillsEnabled {
if store := sessionSandboxFileStore(sandboxMgr); store != nil {
toolRegistry.RegisterTool(tools.NewListSandboxFilesTool(store))
toolRegistry.RegisterTool(tools.NewReadSandboxFileTool(store))
logger.Infof(ctx, "Registered list_sandbox_files and read_sandbox_file tools")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise session filesystem capability; list_sandbox_files/read_sandbox_file not registered")
}
}
// shell_exec is a remote-only capability. SessionCapabilityProvider
// yields nil for stateless backends and for a SessionBoundManager
// that fell back to LocalSandbox, so the same check works for
// every provider (Cube, E2B, future backends).
if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {
toolRegistry.RegisterTool(tools.NewShellExecTool(executor))
logger.Infof(ctx, "Registered shell_exec tool")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise remote shell capability; shell_exec not registered")
}
registerSandboxShellTool(ctx, toolRegistry, sandboxMgr, config)
}
return skillsManager, nil
}
// registerSandboxShellTool registers the one shell_exec variant this run is
// entitled to.
//
// shell_exec is a remote-only capability: the capability accessors yield nil
// for stateless backends and for a SessionBoundManager that fell back to
// LocalSandbox, so the same check works for every provider.
//
// The skill installer agent gets the install-mode variant, which runs as root
// and may work inside the skills image root — it exists to install
// dependencies into the image, which the ordinary contract forbids on both
// counts. Every other agent keeps the non-root, /workspace-only executor.
// AgentConfig.SkillInstallMode is settable only through
// EnableSkillInstallMode, which refuses every agent but the built-in
// installer, so no tenant agent can reach this branch.
func registerSandboxShellTool(
ctx context.Context,
toolRegistry *tools.ToolRegistry,
sandboxMgr sandbox.Manager,
config *types.AgentConfig,
) {
if config.SkillInstallMode() {
if executor := sessionSandboxInstallShellExecutor(sandboxMgr); executor != nil {
toolRegistry.RegisterTool(tools.NewInstallShellExecTool(executor))
logger.Infof(ctx, "Registered install-mode shell_exec tool")
} else {
logger.Warnf(ctx, "Sandbox backend does not advertise install-mode shell capability; skill install cannot run")
}
return
}
if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {
toolRegistry.RegisterTool(tools.NewShellExecTool(executor))
logger.Infof(ctx, "Registered shell_exec tool")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise remote shell capability; shell_exec not registered")
}
}
// registerTools registers tools based on the agent configuration
func (s *agentService) registerTools(
ctx context.Context,

View File

@ -0,0 +1,120 @@
package service
import (
"context"
"encoding/json"
"testing"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// stubInstallShellExecutor records the options the privileged executor is
// asked for, so a test can prove the difference between the two shell_exec
// wirings rather than merely that one was registered.
type stubInstallShellExecutor struct {
calls []sandbox.ShellExecOptions
}
func (s *stubInstallShellExecutor) ExecShellCommandWithOptions(
_ context.Context, _ string, _ string, opts sandbox.ShellExecOptions,
) (*sandbox.ExecuteResult, error) {
s.calls = append(s.calls, opts)
return &sandbox.ExecuteResult{ExitCode: 0}, nil
}
func installShellToolContext() context.Context {
return tools.WithToolExecContext(context.Background(), &tools.ToolExecContext{SessionID: "sess-1"})
}
func TestInstallerAgentGetsTheRootShellWithTheSkillsRoot(t *testing.T) {
privileged := &stubInstallShellExecutor{}
ordinary := &stubShellExecutor{}
mgr := &capableManager{
typ: sandbox.SandboxTypeE2B,
shell: ordinary,
installShell: privileged,
}
config := &types.AgentConfig{}
config.EnableSkillInstallMode(types.BuiltinSkillInstallerID)
registry := tools.NewToolRegistry()
registerSandboxShellTool(context.Background(), registry, mgr, config)
result, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"pip install -r requirements.txt","work_dir":"`+
sandbox.SkillsImageRoot+`/sk-1"}`))
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.False(t, ordinary.called,
"the installer must not fall through to the unprivileged executor")
require.Len(t, privileged.calls, 1)
require.True(t, privileged.calls[0].AsRoot)
require.True(t, privileged.calls[0].AllowSkillsRoot)
require.Equal(t, sandbox.SkillsImageRoot+"/sk-1", privileged.calls[0].WorkDir)
}
func TestOrdinaryAgentKeepsTheUnprivilegedShell(t *testing.T) {
privileged := &stubInstallShellExecutor{}
ordinary := &stubShellExecutor{}
mgr := &capableManager{
typ: sandbox.SandboxTypeE2B,
shell: ordinary,
installShell: privileged,
}
registry := tools.NewToolRegistry()
registerSandboxShellTool(context.Background(), registry, mgr, &types.AgentConfig{})
rejected, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"pip install x","work_dir":"`+sandbox.SkillsImageRoot+`/sk-1"}`))
require.NoError(t, err)
require.False(t, rejected.Success, "an ordinary agent has no business under /opt")
accepted, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"ls"}`))
require.NoError(t, err)
require.True(t, accepted.Success)
require.True(t, ordinary.called)
require.Empty(t, privileged.calls,
"nothing an ordinary agent can ask for may reach the root executor")
}
func TestInstallModeIsRefusedToEveryAgentButTheInstaller(t *testing.T) {
config := &types.AgentConfig{}
config.EnableSkillInstallMode("some-tenant-agent")
require.False(t, config.SkillInstallMode())
}
func TestInstallModeSurvivesNoJSONRoundTrip(t *testing.T) {
// The flag must be unreachable from stored agent records and API payloads:
// both arrive as JSON.
var config types.AgentConfig
require.NoError(t, json.Unmarshal(
[]byte(`{"skill_install_mode":true,"SkillInstallMode":true}`), &config))
require.False(t, config.SkillInstallMode())
}
func TestInstallerAgentConfigTurnsOnInstallMode(t *testing.T) {
config := installerAgentConfig(&types.CustomAgent{
ID: types.BuiltinSkillInstallerID,
Config: types.CustomAgentConfig{AllowedTools: []string{tools.ToolShellExec}},
}, "cfg-1")
require.True(t, config.SkillInstallMode())
}
func TestInstallerAgentConfigLeavesInstallModeOffForAnotherAgent(t *testing.T) {
config := installerAgentConfig(&types.CustomAgent{
ID: "agent-42",
Config: types.CustomAgentConfig{AllowedTools: []string{tools.ToolShellExec}},
}, "cfg-1")
require.False(t, config.SkillInstallMode())
}

View File

@ -14,9 +14,14 @@ import (
// It mirrors the real SessionCapabilityProvider contract SessionBoundManager
// implements, without pulling in the full manager wiring.
type capableManager struct {
typ sandbox.SandboxType
shell sandbox.SessionShellExecutor
files sandbox.SessionFileStore
typ sandbox.SandboxType
shell sandbox.SessionShellExecutor
files sandbox.SessionFileStore
installShell sandbox.SessionInstallShellExecutor
}
func (m *capableManager) SessionInstallShellExecutor() sandbox.SessionInstallShellExecutor {
return m.installShell
}
func (m *capableManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {

View File

@ -3,9 +3,14 @@ package service
import (
"context"
"errors"
"path/filepath"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
@ -31,6 +36,53 @@ type fakeAgentKnowledgeService struct {
lastTenant uint64
}
type fakeAgentChatModel struct {
lastToolNames []string
}
func (*fakeAgentChatModel) Chat(context.Context, []chat.Message, *chat.ChatOptions) (*types.ChatResponse, error) {
return &types.ChatResponse{}, nil
}
func (m *fakeAgentChatModel) ChatStream(_ context.Context, _ []chat.Message, opts *chat.ChatOptions) (<-chan types.StreamResponse, error) {
m.lastToolNames = nil
if opts != nil {
for _, tool := range opts.Tools {
m.lastToolNames = append(m.lastToolNames, tool.Function.Name)
}
}
ch := make(chan types.StreamResponse, 1)
ch <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "ok",
Done: true,
FinishReason: "stop",
}
close(ch)
return ch, nil
}
func (*fakeAgentChatModel) GetModelName() string { return "fake-chat" }
func (*fakeAgentChatModel) GetModelID() string { return "fake-chat-id" }
type stubSessionFileStore struct{}
func (stubSessionFileStore) EnsureSessionDir(context.Context, string, string) error { return nil }
func (stubSessionFileStore) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
return nil, nil
}
func (stubSessionFileStore) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
return nil, nil
}
func (stubSessionFileStore) ReadSessionFile(context.Context, string, string) ([]byte, error) {
return nil, nil
}
func (stubSessionFileStore) WriteSessionInputFile(context.Context, string, string, []byte) error {
return nil
}
func (stubSessionFileStore) RemoveSessionInputPath(context.Context, string, string) error { return nil }
func (s *fakeAgentKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context,
_ string,
@ -50,6 +102,207 @@ func (s *fakeAgentKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID(
return types.NewPageResult(int64(len(filtered)), page, filtered), nil
}
func toolRegistered(registry *tools.ToolRegistry, name string) bool {
_, err := registry.GetTool(name)
return err == nil
}
func toolOffered(names []string, name string) bool {
for _, got := range names {
if got == name {
return true
}
}
return false
}
// TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode pins the gate on
// the skill installer alone. shell_exec is a user-selectable entry in the tool
// picker, so gating on AllowedTools would hand a live sandbox shell (plus
// list_sandbox_files and read_sandbox_file) to every existing agent record
// that already lists it, on deploy, with nobody touching those agents.
func TestCreateAgentEngineOpensSandboxToolsOnlyForInstallMode(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
t.Run("install-mode config gets shell_exec without skill tools", func(t *testing.T) {
chatModel := &fakeAgentChatModel{}
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{
typ: sandbox.SandboxTypeCube,
shell: &stubShellExecutor{},
// The manager advertises a session file store, the way
// every real remote backend does: withholding
// list_sandbox_files/read_sandbox_file from install mode
// must be a decision, not an accident of the fake.
files: stubSessionFileStore{},
installShell: &stubInstallShellExecutor{},
},
},
}
config := &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: false,
AllowedTools: []string{tools.ToolShellExec},
}
config.EnableSkillInstallMode(types.BuiltinSkillInstallerID)
engine, err := svc.CreateAgentEngine(ctx, config, chatModel, nil, nil, "sess-1", "msg-1")
require.NoError(t, err)
_, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
require.NoError(t, err)
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles),
"the installer is here for the shell; a root shell already reads any file")
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))
require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())
})
t.Run("an ordinary agent that lists shell_exec still gets no sandbox tools", func(t *testing.T) {
chatModel := &fakeAgentChatModel{}
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{
typ: sandbox.SandboxTypeCube,
shell: &stubShellExecutor{},
files: stubSessionFileStore{},
installShell: &stubInstallShellExecutor{},
},
},
}
engine, err := svc.CreateAgentEngine(ctx, &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: false,
AllowedTools: []string{tools.ToolShellExec, tools.ToolThinking},
}, chatModel, nil, nil, "sess-1", "msg-1")
require.NoError(t, err)
_, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
require.NoError(t, err)
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec),
"an agent with skills off could never obtain a sandbox shell before this work")
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))
require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())
})
t.Run("skills disabled without skills or install mode gets no sandbox or skill tools", func(t *testing.T) {
chatModel := &fakeAgentChatModel{}
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{
typ: sandbox.SandboxTypeCube,
shell: &stubShellExecutor{},
files: stubSessionFileStore{},
},
},
}
engine, err := svc.CreateAgentEngine(ctx, &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: false,
AllowedTools: []string{tools.ToolThinking},
}, chatModel, nil, nil, "sess-1", "msg-1")
require.NoError(t, err)
_, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
require.NoError(t, err)
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))
require.False(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))
require.Nil(t, engine.(*agent.AgentEngine).GetSkillsManager())
})
t.Run("skills enabled with skill dirs keeps existing behavior", func(t *testing.T) {
chatModel := &fakeAgentChatModel{}
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{
typ: sandbox.SandboxTypeCube,
shell: &stubShellExecutor{},
files: stubSessionFileStore{},
},
},
}
engine, err := svc.CreateAgentEngine(ctx, &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: true,
SkillDirs: []string{t.TempDir()},
}, chatModel, nil, nil, "sess-1", "msg-1")
require.NoError(t, err)
_, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
require.NoError(t, err)
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolShellExec))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolListSandboxFiles))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSandboxFile))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolReadSkill))
require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolExecuteSkillScript))
require.NotNil(t, engine.(*agent.AgentEngine).GetSkillsManager())
})
}
func TestSkillToolsFollowSkillsEnabled(t *testing.T) {
t.Run("skills disabled: no skill tools, shell_exec still available", func(t *testing.T) {
registry := tools.NewToolRegistry()
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{typ: sandbox.SandboxTypeCube, shell: &stubShellExecutor{}},
},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
_, err := svc.initializeSkillsManager(ctx, "sess-1", &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: false,
AllowedTools: []string{tools.ToolShellExec},
}, registry)
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")
})
t.Run("skills enabled: existing behaviour is unchanged", func(t *testing.T) {
registry := tools.NewToolRegistry()
svc := &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{typ: sandbox.SandboxTypeCube, shell: &stubShellExecutor{}},
},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
_, err := svc.initializeSkillsManager(ctx, "sess-1", &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: true,
SkillDirs: []string{t.TempDir()},
}, registry)
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))
})
}
func TestSkillInstallerIsHiddenFromThePicker(t *testing.T) {
require.NoError(t, types.LoadBuiltinAgentsConfig(filepath.Join("..", "..", "..", "config")))
require.True(t, types.IsBuiltinAgentID(types.BuiltinSkillInstallerID),
"the server must still be able to resolve it by ID")
require.NotContains(t, types.GetBuiltinAgentIDs(), types.BuiltinSkillInstallerID,
"it must not clutter the tenant's agent picker")
}
func TestGetKnowledgeBaseInfos_SharedKnowledgeBaseUsesSourceTenant(t *testing.T) {
const (
receiverTenantID = uint64(7)

View File

@ -42,6 +42,17 @@ func sessionSandboxShellExecutor(mgr sandbox.Manager) sandbox.SessionShellExecut
return provider.SessionShellExecutor()
}
// sessionSandboxInstallShellExecutor is the install-mode counterpart of
// sessionSandboxShellExecutor. It is a separate accessor on a separate
// interface so a caller cannot obtain the privileged executor by accident.
func sessionSandboxInstallShellExecutor(mgr sandbox.Manager) sandbox.SessionInstallShellExecutor {
provider, ok := mgr.(sandbox.SessionInstallCapabilityProvider)
if !ok || provider == nil {
return nil
}
return provider.SessionInstallShellExecutor()
}
// sessionAttachmentStager is the agentService surface the QA pipeline needs to
// stage attachments. Declared as a named interface so the runtime type
// assertion in session_agent_qa.go has one definition to drift against.

View File

@ -0,0 +1,225 @@
package service
import (
"archive/zip"
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"unicode"
"github.com/Tencent/WeKnora/internal/agent/skills"
"gopkg.in/yaml.v3"
)
// ErrSkillBundleInvalid marks every rejection of an uploaded archive, so the
// handler can map the whole class to 400 without matching on message text.
var ErrSkillBundleInvalid = errors.New("skill bundle is invalid")
// The skill bundle limits bound decompression so a zip bomb cannot exhaust
// memory before we ever reach the sandbox.
const (
maxSkillBundleFiles = 2000
maxSkillBundleFileBytes = 32 << 20 // 32 MiB per entry
maxSkillBundleTotalBytes = 256 << 20 // 256 MiB across the archive
)
// SkillBundle is a validated, in-memory skill archive.
type SkillBundle struct {
Name string
Version string
Description string
Instructions string
// SHA256 is over the uploaded bytes, so re-uploading the same archive is
// recognisable in the UI and in the ledger.
SHA256 string
// Files maps skill-root-relative paths to contents, SKILL.md included.
Files map[string][]byte
}
// ParseSkillBundle validates an uploaded zip and extracts everything the
// install flow needs. It accepts both a flat archive and one wrapped in a
// single top-level directory, because both are what people actually upload.
func ParseSkillBundle(archive []byte) (*SkillBundle, error) {
reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))
if err != nil {
return nil, fmt.Errorf("%w: not a readable zip archive: %v", ErrSkillBundleInvalid, err)
}
if len(reader.File) > maxSkillBundleFiles {
return nil, fmt.Errorf("%w: archive holds more than %d files",
ErrSkillBundleInvalid, maxSkillBundleFiles)
}
raw := make(map[string][]byte, len(reader.File))
var totalBytes int64
for _, entry := range reader.File {
if entry.FileInfo().IsDir() {
continue
}
if entry.FileInfo().Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("%w: entry %q is a symlink", ErrSkillBundleInvalid, entry.Name)
}
name := path.Clean(entry.Name)
if name == "." || strings.HasPrefix(name, "..") ||
path.IsAbs(name) || strings.Contains(name, "../") {
return nil, fmt.Errorf("%w: entry %q escapes the archive root",
ErrSkillBundleInvalid, entry.Name)
}
if err := validateSkillEntryName(name); err != nil {
return nil, err
}
if entry.FileInfo().Size() > maxSkillBundleFileBytes {
return nil, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name)
}
entryBytes := entry.FileInfo().Size()
if totalBytes+entryBytes > maxSkillBundleTotalBytes {
return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid)
}
totalBytes += entryBytes
rc, err := entry.Open()
if err != nil {
return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err)
}
content, err := io.ReadAll(io.LimitReader(rc, maxSkillBundleFileBytes+1))
_ = rc.Close()
if err != nil {
return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err)
}
if len(content) > maxSkillBundleFileBytes {
return nil, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name)
}
if int64(len(content)) > entryBytes {
actualExcess := int64(len(content)) - entryBytes
if totalBytes+actualExcess > maxSkillBundleTotalBytes {
return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid)
}
totalBytes += actualExcess
}
raw[name] = content
}
files, err := stripSkillRootPrefix(raw)
if err != nil {
return nil, err
}
manifest, ok := files["SKILL.md"]
if !ok {
return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
}
skill, err := skills.ParseSkillFile(string(manifest))
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrSkillBundleInvalid, err)
}
version, err := parseSkillBundleVersion(string(manifest))
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrSkillBundleInvalid, err)
}
sum := sha256.Sum256(archive)
return &SkillBundle{
Name: skill.Name,
Version: version,
Description: skill.Description,
Instructions: skill.Instructions,
SHA256: hex.EncodeToString(sum[:]),
Files: files,
}, nil
}
// validateSkillEntryName bans control characters and nothing else.
//
// Shell safety is not this function's job: every interpolation of a bundle
// path goes through sandbox.ShellQuote, which makes any name inert. What
// quoting cannot fix is a name that rewrites the lines it is printed into —
// the entry names also reach log lines, error messages and the image
// manifest, and a newline or an escape sequence there forges a second record.
// So control characters (NUL included) are refused and ordinary punctuation is
// not: real bundles vendor node_modules/@scope/pkg and wheels named
// numpy-1.26.4+cpu.whl, and a charset that rejected '@' or '+' broke them for
// no security gain. Traversal and symlinks are checked separately by the
// caller.
func validateSkillEntryName(name string) error {
for _, r := range name {
if unicode.IsControl(r) || r == 0 {
return fmt.Errorf("%w: entry %q holds unsupported character %q",
ErrSkillBundleInvalid, name, r)
}
}
return nil
}
func parseSkillBundleVersion(manifest string) (string, error) {
lines := strings.Split(manifest, "\n")
frontmatterStart := -1
for i, line := range lines {
if strings.TrimSpace(line) == "---" {
frontmatterStart = i
break
}
if strings.TrimSpace(line) != "" {
break
}
}
if frontmatterStart < 0 {
return "", nil
}
frontmatterEnd := -1
for i := frontmatterStart + 1; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == "---" {
frontmatterEnd = i
break
}
}
if frontmatterEnd < 0 {
return "", nil
}
var metadata struct {
Version string `yaml:"version"`
}
if err := yaml.Unmarshal([]byte(strings.Join(lines[frontmatterStart+1:frontmatterEnd], "\n")), &metadata); err != nil {
return "", err
}
return metadata.Version, nil
}
// stripSkillRootPrefix re-roots the archive at the directory holding SKILL.md.
func stripSkillRootPrefix(raw map[string][]byte) (map[string][]byte, error) {
if _, ok := raw["SKILL.md"]; ok {
return raw, nil
}
var prefix string
for name := range raw {
if path.Base(name) != "SKILL.md" {
continue
}
dir := path.Dir(name)
if dir == "." || strings.Contains(dir, "/") {
// Either already handled above, or nested deeper than one level:
// we refuse to guess which of several directories is the skill.
continue
}
if prefix != "" && prefix != dir {
return nil, fmt.Errorf("%w: archive holds more than one skill", ErrSkillBundleInvalid)
}
prefix = dir
}
if prefix == "" {
return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
}
out := make(map[string][]byte, len(raw))
for name, content := range raw {
if !strings.HasPrefix(name, prefix+"/") {
continue
}
out[strings.TrimPrefix(name, prefix+"/")] = content
}
return out, nil
}

View File

@ -0,0 +1,309 @@
package service
import (
"archive/zip"
"bytes"
"compress/flate"
"fmt"
"hash/crc32"
"io"
"os"
"testing"
"github.com/stretchr/testify/require"
)
func zipBundle(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
w := zip.NewWriter(&buf)
for name, content := range files {
f, err := w.Create(name)
require.NoError(t, err)
_, err = f.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, w.Close())
return buf.Bytes()
}
func zipBundleWithSymlink(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
w := zip.NewWriter(&buf)
f, err := w.Create("SKILL.md")
require.NoError(t, err)
_, err = f.Write([]byte(validSkillMD))
require.NoError(t, err)
header := &zip.FileHeader{Name: "scripts/link"}
header.SetMode(0o777 | os.ModeSymlink)
link, err := w.CreateHeader(header)
require.NoError(t, err)
_, err = link.Write([]byte("/etc/passwd"))
require.NoError(t, err)
require.NoError(t, w.Close())
return buf.Bytes()
}
func zipBundleWithNFiles(t *testing.T, count int) []byte {
t.Helper()
var buf bytes.Buffer
w := zip.NewWriter(&buf)
f, err := w.Create("SKILL.md")
require.NoError(t, err)
_, err = f.Write([]byte(validSkillMD))
require.NoError(t, err)
for i := range count {
f, err := w.Create(fmt.Sprintf("scripts/%04d.txt", i))
require.NoError(t, err)
_, err = f.Write([]byte("x"))
require.NoError(t, err)
}
require.NoError(t, w.Close())
return buf.Bytes()
}
func zipBundleWithDeclaredSize(t *testing.T, name string, size uint64) []byte {
t.Helper()
var buf bytes.Buffer
w := zip.NewWriter(&buf)
header := &zip.FileHeader{
Name: name,
Method: zip.Store,
UncompressedSize64: size,
CompressedSize64: 0,
CRC32: 0,
}
_, err := w.CreateRaw(header)
require.NoError(t, err)
f, err := w.Create("SKILL.md")
require.NoError(t, err)
_, err = f.Write([]byte(validSkillMD))
require.NoError(t, err)
require.NoError(t, w.Close())
return buf.Bytes()
}
type repeatedByteReader byte
func (r repeatedByteReader) Read(p []byte) (int, error) {
for i := range p {
p[i] = byte(r)
}
return len(p), nil
}
func deflatedRepeatedBytes(t *testing.T, size int64) ([]byte, uint32) {
t.Helper()
var compressed bytes.Buffer
checksum := crc32.NewIEEE()
zw, err := flate.NewWriter(&compressed, flate.BestSpeed)
require.NoError(t, err)
_, err = io.Copy(io.MultiWriter(zw, checksum), io.LimitReader(repeatedByteReader('x'), size))
require.NoError(t, err)
require.NoError(t, zw.Close())
return compressed.Bytes(), checksum.Sum32()
}
func zipBundleExceedingDeclaredTotal(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
w := zip.NewWriter(&buf)
payload, checksum := deflatedRepeatedBytes(t, int64(maxSkillBundleFileBytes))
for i := 0; i < maxSkillBundleTotalBytes/maxSkillBundleFileBytes+1; i++ {
header := &zip.FileHeader{
Name: fmt.Sprintf("scripts/chunk-%d.bin", i),
Method: zip.Deflate,
UncompressedSize64: uint64(maxSkillBundleFileBytes),
CompressedSize64: uint64(len(payload)),
CRC32: checksum,
}
f, err := w.CreateRaw(header)
require.NoError(t, err)
_, err = f.Write(payload)
require.NoError(t, err)
}
f, err := w.Create("SKILL.md")
require.NoError(t, err)
_, err = f.Write([]byte(validSkillMD))
require.NoError(t, err)
require.NoError(t, w.Close())
return buf.Bytes()
}
const validSkillMD = `---
name: pdf-tools
description: Extract text from PDF files
---
Use scripts/extract.py to pull text out of a PDF.
`
func TestParseSkillBundle(t *testing.T) {
t.Run("rejects malformed zip input", func(t *testing.T) {
_, err := ParseSkillBundle([]byte("not a zip"))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, "not a readable zip archive")
})
t.Run("reads frontmatter, body and files", func(t *testing.T) {
data := zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"scripts/extract.py": "print('hi')\n",
"requirements.txt": "pypdf==4.0.0\n",
})
bundle, err := ParseSkillBundle(data)
require.NoError(t, err)
require.Equal(t, "pdf-tools", bundle.Name)
require.Equal(t, "Extract text from PDF files", bundle.Description)
require.Contains(t, bundle.Instructions, "scripts/extract.py")
require.Len(t, bundle.SHA256, 64)
require.Contains(t, bundle.Files, "scripts/extract.py")
})
t.Run("reads version frontmatter", func(t *testing.T) {
data := zipBundle(t, map[string]string{
"SKILL.md": `---
name: pdf-tools
version: 1.2.3
description: Extract text from PDF files
---
Use scripts/extract.py to pull text out of a PDF.
`,
})
bundle, err := ParseSkillBundle(data)
require.NoError(t, err)
require.Equal(t, "1.2.3", bundle.Version)
})
t.Run("tolerates a single top-level directory", func(t *testing.T) {
data := zipBundle(t, map[string]string{
"pdf-tools/SKILL.md": validSkillMD,
"pdf-tools/scripts/extract.py": "print('hi')\n",
})
bundle, err := ParseSkillBundle(data)
require.NoError(t, err)
require.Equal(t, "pdf-tools", bundle.Name)
require.Contains(t, bundle.Files, "scripts/extract.py",
"paths must be relative to the skill root, not to the archive root")
})
t.Run("rejects an archive without SKILL.md", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundle(t, map[string]string{"a.txt": "x"}))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
})
t.Run("rejects too many entries", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundleWithNFiles(t, maxSkillBundleFiles))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, "archive holds more than")
})
t.Run("rejects per-entry oversize", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundleWithDeclaredSize(
t, "scripts/large.bin", uint64(maxSkillBundleFileBytes+1),
))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, `entry "scripts/large.bin" is too large`)
})
t.Run("rejects aggregate decompressed oversize", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundleExceedingDeclaredTotal(t))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, "archive is too large")
})
t.Run("rejects path traversal", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"../escape.py": "x",
}))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
})
t.Run("rejects absolute paths", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"/tmp/x": "x",
}))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
})
t.Run("rejects symlinks", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundleWithSymlink(t))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
})
t.Run("rejects control characters in entry names", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"scripts/a\nb.py": "x",
}))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, "unsupported character")
})
t.Run("rejects NUL in entry names", func(t *testing.T) {
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"scripts/a\x00b.py": "x",
}))
require.ErrorIs(t, err, ErrSkillBundleInvalid)
require.ErrorContains(t, err, "unsupported character")
})
t.Run("accepts the punctuation vendored dependencies actually use", func(t *testing.T) {
bundle, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"node_modules/@scope/pkg/index.js": "x",
"wheels/numpy-1.26.4+cpu.whl": "x",
"scripts/x$(id).py": "x",
}))
require.NoError(t, err,
"sandbox.ShellQuote makes any name inert, so refusing @ or + only broke real bundles")
require.Contains(t, bundle.Files, "node_modules/@scope/pkg/index.js")
require.Contains(t, bundle.Files, "wheels/numpy-1.26.4+cpu.whl")
require.Contains(t, bundle.Files, "scripts/x$(id).py")
})
t.Run("accepts non-ASCII entry names", func(t *testing.T) {
bundle, err := ParseSkillBundle(zipBundle(t, map[string]string{
"SKILL.md": validSkillMD,
"references/参考 手册.md": "x",
}))
require.NoError(t, err)
require.Contains(t, bundle.Files, "references/参考 手册.md",
"real skills ship documents named in the operator's own language")
})
t.Run("same bytes hash the same", func(t *testing.T) {
data := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
a, err := ParseSkillBundle(data)
require.NoError(t, err)
b, err := ParseSkillBundle(data)
require.NoError(t, err)
require.Equal(t, a.SHA256, b.SHA256)
})
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,69 @@
package service
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// skillProgressTTL keeps a finished run's last value around long enough for a
// late SSE subscriber to render it, then lets it expire.
const skillProgressTTL = 30 * time.Minute
// SkillProgress is the transient install/remove progress. It is deliberately
// NOT persisted: the durable state is tenant_skills.status, and a percentage
// that outlives the job that produced it is worse than no percentage.
type SkillProgress struct {
Percent int `json:"percent"`
Stage string `json:"stage"`
Log string `json:"log,omitempty"`
Status string `json:"status,omitempty"`
}
func skillProgressKey(configID, skillID string) string {
return fmt.Sprintf("weknora-skill-install:%s:%s", configID, skillID)
}
// publishProgress stores the latest value and broadcasts it. Without Redis both
// are no-ops and the UI falls back to the DB status alone; the install itself
// keeps working, which is the point.
func (s *TenantSkillService) publishProgress(
ctx context.Context, configID, skillID string, p SkillProgress,
) {
if s.redis == nil {
return
}
payload, err := json.Marshal(p)
if err != nil {
return
}
key := skillProgressKey(configID, skillID)
if err := s.redis.Set(ctx, key, payload, skillProgressTTL).Err(); err != nil {
logger.Warnf(ctx, "[skill] store progress %s failed: %v", key, err)
}
if err := s.redis.Publish(ctx, key, payload).Err(); err != nil {
logger.Warnf(ctx, "[skill] publish progress %s failed: %v", key, err)
}
}
// LastProgress returns the last known value so a fresh SSE connection can paint
// immediately instead of waiting for the next tick.
func (s *TenantSkillService) LastProgress(
ctx context.Context, configID, skillID string,
) (SkillProgress, bool) {
if s.redis == nil {
return SkillProgress{}, false
}
raw, err := s.redis.Get(ctx, skillProgressKey(configID, skillID)).Bytes()
if err != nil {
return SkillProgress{}, false
}
var p SkillProgress
if err := json.Unmarshal(raw, &p); err != nil {
return SkillProgress{}, false
}
return p, true
}

View File

@ -0,0 +1,436 @@
package service
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/google/uuid"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// RemoveSkill deletes a skill from the image. It is not a DB-only operation:
// the files really do leave the image, via a new snapshot taken after the
// directory is gone. Removal therefore shares the install's per-config lock —
// both grow a new snapshot from the current one, and interleaving them would
// discard whichever wrote the pointer first.
func (s *TenantSkillService) RemoveSkill(
ctx context.Context, tenantID uint64, configID, skillID string,
) error {
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
return err
}
if skill == nil {
return apperrors.NewNotFoundError("skill not found")
}
now := s.now()
skill.Status = types.SkillStatusRemoving
skill.Error = ""
skill.InstallingSince = &now
if err := s.skills.UpdateSkill(ctx, skill); err != nil {
return err
}
s.publishProgress(ctx, configID, skillID, SkillProgress{
Percent: 5, Stage: "accepted", Status: types.SkillStatusRemoving,
})
// Like the install, the removal outlives the HTTP request and must not
// inherit its cancellation. It is not durable across a restart either;
// that is the stuck-run reaper's job (Task 17).
go func() {
bgCtx := context.WithoutCancel(ctx)
if err := s.withConfigLock(bgCtx, configID, func(lockCtx context.Context) error {
return s.runRemove(lockCtx, tenantID, configID, skillID)
}); err != nil {
logger.Errorf(bgCtx, "[skill] remove %s failed: %v", skillID, err)
}
}()
return nil
}
func (s *TenantSkillService) runRemove(
ctx context.Context, tenantID uint64, configID, skillID string,
) (err error) {
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
ctx = types.WithSandboxTenantID(ctx, tenantID)
// An empty id never names a row; refusing here keeps the later GetSkill
// from being the only thing standing between us and a no-op that looks
// like success.
if strings.TrimSpace(skillID) == "" {
return fmt.Errorf("skill id is required")
}
// RemoveSkill validates the skill outside this lock, so two submissions
// queue two runs. The second has nothing to remove, and doing it anyway
// would boot a sandbox, wipe a directory that is not there and spend a
// snapshot plus a generation bump to produce an identical image.
existing, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
return fmt.Errorf("load skill %s: %w", skillID, err)
}
if existing == nil {
return nil
}
// The image directory is the skill name, and SkillDirFor is what refuses a
// name that would escape the skills root. Resolved before any sandbox work
// so a bad name costs nothing; the guard at the rm itself is what keeps
// that an invariant rather than a convention.
skillDir, err := sandbox.SkillDirFor(existing.Name)
if err != nil {
return err
}
// Cleanup runs on a context that cannot be cancelled by whatever it is
// compensating for: withConfigLock cancels ctx the moment lock renewal
// fails, and both the sandbox destroy (a provider call) and the terminal
// row write (a DB call) still have to happen then. Only cancellation is
// detached here — each consumer calls cleanupContext so its budget starts
// when its work does, because a removal can run for minutes.
cleanupBase := context.WithoutCancel(ctx)
// imageChanged marks the point of no return. Past it the skill is gone
// from the image every new session boots, so restoring the row to ready
// would advertise files that no longer exist.
imageChanged := false
defer func() {
if err == nil {
return
}
if imageChanged {
logger.Errorf(cleanupBase,
"[skill] %s is gone from the image but its bookkeeping is incomplete: %v",
skillID, err)
return
}
// A half-removed skill is worse than a kept one: the image still has
// it, so put the row back the way the operator can retry from.
restoreCtx, cancelRestore := s.cleanupContext(cleanupBase)
defer cancelRestore()
s.restoreSkillAfterFailedRemoval(restoreCtx, tenantID, configID, skillID, err)
}()
cfgEntity, err := s.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return fmt.Errorf("load sandbox config %s: %w", configID, err)
}
if cfgEntity == nil {
return fmt.Errorf("sandbox config %s not found", configID)
}
// A skill that never made it into any image needs no sandbox at all.
if currentSnapshotID(cfgEntity) == "" {
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
}
// Shared with the install: a snapshot the live credentials cannot resolve
// must not be built on, and here that matters most - the removal would
// wipe a directory the booted image never had and then move the pointer
// past an image the old credentials still make recoverable.
if err := ensureUsableImage(cfgEntity); err != nil {
return err
}
// Everything below either creates provider resources or moves the image
// pointer, and the fallback moves it without taking a snapshot first. A
// cancelled context means the lock's renewal failed and another run may
// already be building on this config, so stop rather than race it.
if err := ctx.Err(); err != nil {
return fmt.Errorf("remove lock lost before the image changes: %w", err)
}
remaining, err := s.countRemainingSkills(ctx, tenantID, configID, skillID)
if err != nil {
return err
}
if remaining == 0 {
// Nothing would be left to carry, and the base template carries no
// skills by construction, so pointing back at it removes the files as
// surely as a wipe would. Checked before the sandbox is started: the
// snapshot that work produced would be discarded unread.
if err := s.clearImagePointer(
ctx, tenantID, configID, currentGeneration(cfgEntity)+1,
); err != nil {
return err
}
imageChanged = true
// No new ledger row exists to keep active: nothing points at a
// snapshot any more.
s.markPreviousSnapshotsSuperseded(ctx, tenantID, configID, "")
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
}
// ResolveEffectiveConfig has already turned the current snapshot into the
// template, so this sandbox boots from the image the skill is in.
sess, mgr, err := s.startMaintenanceSession(ctx, tenantID, configID, "remove")
if err != nil {
return err
}
// Only the sandbox is released; the session and its messages stay, the
// same way an install keeps its transcript.
defer func() {
releaseCtx, cancelRelease := s.cleanupContext(cleanupBase)
defer cancelRelease()
s.releaseSandbox(releaseCtx, mgr, sess.ID)
}()
s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 30, Stage: "sandbox_ready"})
if err := s.removeSkillDirectory(ctx, mgr, sess.ID, skillDir); err != nil {
return err
}
if err := s.removeManifestEntry(ctx, mgr, sess.ID, skillID); err != nil {
return err
}
// Same reason as the install: the per-session workspace and the package
// caches must not reach the snapshot.
if err := s.cleanImageScratch(ctx, mgr, sess.ID); err != nil {
return err
}
s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 60, Stage: "removed"})
// Checked again: everything above is confined to a sandbox we are about
// to destroy, and the wipe itself takes minutes, so the lock may have been
// lost since the check before the fallback branch.
if err := ctx.Err(); err != nil {
return fmt.Errorf("remove lock lost before snapshot: %w", err)
}
// The generation comes from the config read at the top of this function
// while switchImagePointer re-reads for everything else, for the same
// reason it does in an install: SkillImage is written only by an install
// or a removal and this lock serialises both, whereas the rest of the
// entity is written by the config service under its own cordon.
generation := currentGeneration(cfgEntity) + 1
// The ledger row is written before the snapshot: a snapshot with no ledger
// entry is a provider resource nobody knows exists.
removeRowID := uuid.NewString()
if err := s.skills.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{
ID: removeRowID, TenantID: tenantID, SandboxConfigID: configID, SkillID: skillID,
ParentSnapshotID: currentSnapshotID(cfgEntity), Generation: generation,
Trigger: types.SkillSnapshotTriggerRemove, State: types.SkillSnapshotStateBuilding,
}); err != nil {
return err
}
snapshotName := fmt.Sprintf("weknora-sk-%s-g%d", shortID(configID), generation)
ref, err := s.createSnapshot(ctx, mgr, sess.ID, snapshotName)
if err != nil {
return err
}
if err := s.skills.MarkSnapshotState(
ctx, tenantID, removeRowID, types.SkillSnapshotStateActive, ref.ID,
); err != nil {
// The snapshot's ID exists nowhere but this function's locals now, so
// it is as unreachable as one nothing points at.
s.abandonSnapshot(cleanupBase, tenantID, mgr, removeRowID, ref.ID)
return err
}
if err := s.switchImagePointer(ctx, tenantID, configID, ref.ID, generation); err != nil {
s.abandonSnapshot(cleanupBase, tenantID, mgr, removeRowID, ref.ID)
return err
}
imageChanged = true
s.markPreviousSnapshotsSuperseded(ctx, tenantID, configID, removeRowID)
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
}
// removeSkillDirectory wipes one skill's tree from the image. The per-skill
// environment discipline is what makes a single rm enough: the venv,
// node_modules and any local bin live under that tree, so they go with it.
//
// It reclaims only what lives under that tree. Anything the installer agent
// put elsewhere - an apt package, a globally linked npm binary - stays behind,
// because there is no record of what a given install changed outside its own
// directory and guessing would mean uninstalling a system library another
// skill now depends on. The cost is bounded image growth, which the rebuild
// flow can reclaim from the base template; the alternative risks breaking
// skills that still work.
func (s *TenantSkillService) removeSkillDirectory(
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string,
) error {
if err := guardSkillDir(skillDir); err != nil {
return err
}
if _, err := s.execInstall(
ctx, mgr, sessionID, "rm -rf "+sandbox.ShellQuote(skillDir),
); err != nil {
return fmt.Errorf("remove skill directory %s: %w", skillDir, err)
}
return nil
}
// removeManifestEntry drops the skill from the image's manifest.
//
// A manifest that cannot be read or parsed is not a reason to fail the
// removal: it is a troubleshooting aid, never the source of truth for
// execution, and rewriting it from an empty value would erase the entries of
// every other skill in the image.
func (s *TenantSkillService) removeManifestEntry(
ctx context.Context, mgr sandbox.Manager, sessionID, skillID string,
) error {
reader, ok := mgr.(sandbox.SessionFileReader)
if !ok {
return nil
}
raw, err := reader.ReadSessionFile(ctx, sessionID, sandbox.SkillsManifestPath)
if err != nil {
logger.Warnf(ctx, "[skill] read image manifest failed: %v", err)
return nil
}
var manifest skillImageManifest
if err := json.Unmarshal(raw, &manifest); err != nil {
logger.Warnf(ctx, "[skill] image manifest is unreadable: %v", err)
return nil
}
kept := make([]skillImageManifestEntry, 0, len(manifest.Skills))
for _, entry := range manifest.Skills {
if entry.ID != skillID {
kept = append(kept, entry)
}
}
if len(kept) == len(manifest.Skills) {
return nil
}
manifest.Skills = kept
store, err := installFileStore(mgr)
if err != nil {
return err
}
payload, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return err
}
payload = append(payload, '\n')
return store.WriteSessionFile(ctx, sessionID, sandbox.SkillsManifestPath, payload)
}
// countRemainingSkills counts what the image would still have to carry.
//
// Every row counts, not just the ready ones: a row left failed by a re-install
// still has the previously installed version's files in the image, and
// dropping back to the base template would silently take those away too.
func (s *TenantSkillService) countRemainingSkills(
ctx context.Context, tenantID uint64, configID, removedSkillID string,
) (int, error) {
skills, err := s.skills.ListSkillsByConfig(ctx, tenantID, configID)
if err != nil {
return 0, fmt.Errorf("list skills of config %s: %w", configID, err)
}
remaining := 0
for _, skill := range skills {
if skill != nil && skill.ID != removedSkillID {
remaining++
}
}
return remaining, nil
}
// clearImagePointer points the config back at its base template. It re-reads
// the config for the same reason switchImagePointer does: the entity read at
// the top of the run is minutes old, and writing it back would revert whatever
// the config service persisted in the meantime.
func (s *TenantSkillService) clearImagePointer(
ctx context.Context, tenantID uint64, configID string, generation int,
) error {
cfgEntity, err := s.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return fmt.Errorf("re-read sandbox config %s: %w", configID, err)
}
if cfgEntity == nil || cfgEntity.Config == nil {
return fmt.Errorf("sandbox config %s disappeared during the removal", configID)
}
// The metadata is kept and the generation still advances: an empty
// SnapshotID already means "boot the base template", and the rest is what
// tells an operator which generation emptied the image.
cfgEntity.Config.SkillImage = &types.SkillImageConfig{
Generation: generation,
BuiltAt: s.now(),
BaseTemplateID: effectiveBaseTemplate(cfgEntity),
OwnerFingerprint: skillOwnerFingerprint(cfgEntity.Config),
}
cfgEntity.TenantID = tenantID
return s.configs.Update(ctx, cfgEntity)
}
// finishRemoval drops the DB row and the stored archive, then invalidates
// bound sandboxes. It runs only once the image no longer contains the skill,
// which is also why the delete is retried rather than reported as a failed
// removal: the files are gone and re-running the whole flow to fix a row would
// be absurd.
func (s *TenantSkillService) finishRemoval(
cleanupBase context.Context, tenantID uint64, configID, skillID string,
) error {
ctx, cancel := s.cleanupContext(cleanupBase)
defer cancel()
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
return err
}
// The row goes first. A surviving row whose BundleRef names a deleted
// object is a broken record - read_skill would serve nothing - whereas an
// archive whose row is gone is only unreferenced bytes.
if err := s.retrySkillBookkeeping(ctx, func() error {
return s.skills.DeleteSkill(ctx, tenantID, configID, skillID)
}); err != nil {
return fmt.Errorf("skill %s no longer exists in the image but its row remains: %w",
skillID, err)
}
if skill != nil && skill.BundleRef != "" {
s.deleteBundleBestEffort(ctx, tenantID, skill.BundleRef)
}
s.markConfigSandboxesStale(ctx, tenantID, configID)
s.publishProgress(ctx, configID, skillID, SkillProgress{
Percent: 100, Stage: "done", Status: "removed",
})
return nil
}
// restoreSkillAfterFailedRemoval puts back the row a failed removal borrowed.
func (s *TenantSkillService) restoreSkillAfterFailedRemoval(
ctx context.Context, tenantID uint64, configID, skillID string, cause error,
) {
status := types.SkillStatusFailed
_ = s.updateSkillFields(ctx, tenantID, configID, skillID,
func(e *types.TenantSkillEntity) {
// A skill that reached an image is still in it, so it goes back to
// ready and the operator can retry. One that never did has nothing
// to be ready for, and calling it ready would point the agent at
// files no image carries.
if e.InstalledSnapshotID != "" {
status = types.SkillStatusReady
}
e.Status = status
e.Error = cause.Error()
e.InstallingSince = nil
})
s.publishProgress(ctx, configID, skillID, SkillProgress{
Percent: 100, Stage: "failed", Status: status, Log: cause.Error(),
})
}
func (s *TenantSkillService) deleteBundleBestEffort(
ctx context.Context, tenantID uint64, bundleRef string,
) {
if s.resolver == nil {
return
}
fs, _, err := s.resolver.ResolveFileService(ctx, &types.Tenant{ID: tenantID}, "", "", "")
if err != nil || fs == nil {
logger.Warnf(ctx, "[skill] resolve file service to delete bundle %s failed: %v",
bundleRef, err)
return
}
if err := fs.DeleteFile(ctx, bundleRef); err != nil {
logger.Warnf(ctx, "[skill] delete bundle %s failed: %v", bundleRef, err)
}
}

View File

@ -0,0 +1,368 @@
package service
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// The removal command is asserted verbatim for the same reason the install
// commands are: it runs as root with the skills root writable.
const removeSkillDirCommand = "rm -rf " + installSkillDir
func TestRunRemoveProducesANewSnapshotWithoutTheSkillDir(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
// A second skill is what keeps the image worth carrying. With sk-1 the
// only one installed, the flow falls back to the base template instead
// and spends no snapshot at all (the test below).
fx.seedInstalledSkill("sk-2", "snap-old", 2)
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Contains(t, fx.commands, removeSkillDirCommand)
require.Equal(t, "snap-1", fx.configRepo.saved.Config.SkillImage.SnapshotID)
require.Equal(t, 3, fx.configRepo.saved.Config.SkillImage.Generation)
require.NotContains(t, fx.deletedSnapshots, "snap-old",
"the ledger records the old snapshot ID, so it must stay resolvable")
require.Equal(t, []string{"sess-1"}, fx.destroyedSandboxes,
"the maintenance sandbox is released, and only that one")
require.Equal(t, []string{"CreateSession"}, fx.sessionCalls,
"the maintenance session is kept for troubleshooting")
require.Equal(t, []string{"Skill remove"}, fx.sessionTitles,
"the transcript is kept to troubleshoot this operation, so it must name it")
require.Equal(t, []string{"file://sk-1.zip"}, fx.deletedBundles,
"the archive outlives nothing: its only readers are the removed row and read_skill")
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Nil(t, skill, "the DB row goes away only after the image no longer has the skill")
// The other half of "never delete, mark superseded": the delete-side
// assertion above says snap-old survives on the provider, this says the
// ledger stops calling it current instead of losing track of it.
rows := listSnapshotRows(t, fx)
require.Len(t, rows, 3, "the two seeded rows are kept and the removal adds its own")
for _, row := range rows {
switch row.SnapshotID {
case "snap-old":
require.Equal(t, types.SkillSnapshotStateSuperseded, row.State,
"a snapshot nothing points at any more is superseded, never deleted")
case "snap-1":
require.Equal(t, types.SkillSnapshotStateActive, row.State)
require.Equal(t, types.SkillSnapshotTriggerRemove, row.Trigger,
"the ledger has to say which operation produced this image")
default:
t.Fatalf("unexpected ledger row for snapshot %q", row.SnapshotID)
}
}
}
func listSnapshotRows(
t *testing.T, fx *installFixture,
) []*types.TenantSkillSnapshotEntity {
t.Helper()
rows, err := fx.skillRepo.ListSnapshotsByConfig(context.Background(), 7, "cfg-1")
require.NoError(t, err)
return rows
}
func TestRunRemoveDropsTheSkillFromTheImageManifest(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
var manifest skillImageManifest
require.NoError(t, json.Unmarshal(
fx.sandboxMgr.writeContents[sandbox.SkillsManifestPath], &manifest))
require.Len(t, manifest.Skills, 1,
"the manifest is what an operator reads to see what the image claims to carry")
require.Equal(t, "sk-2", manifest.Skills[0].ID)
}
func TestRunRemoveFallsBackToBaseTemplateWhenNoSkillsRemain(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID,
"an image with no skills left is just the base template; do not spend a snapshot on it")
require.Equal(t, []string{"switch-pointer"}, fx.events,
"clearing the pointer is the whole job: no sandbox is started, so none is billed")
require.Empty(t, fx.commands)
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Nil(t, skill)
// Nothing points at snap-old any more, so no ledger row may still call
// itself active - and the snapshot itself is still not deleted.
rows := listSnapshotRows(t, fx)
require.Len(t, rows, 1, "no snapshot was taken, so no row was added")
require.Equal(t, types.SkillSnapshotStateSuperseded, rows[0].State)
require.Equal(t, "snap-old", rows[0].SnapshotID)
require.Empty(t, fx.deletedSnapshots)
}
// A snapshot that the live credentials cannot resolve is not a snapshot this
// run may build on: the sandbox would boot the BASE TEMPLATE, the removal would
// wipe a directory that is not there, and the pointer would move past an image
// that is still recoverable by restoring the credentials.
func TestRunRemoveRefusesAnImageThatBelongsToAnotherProviderAccount(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.configRepo.entity.Config.E2B.APIKey = "key-2"
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err)
require.ErrorContains(t, err, "provider account")
require.Empty(t, fx.events, "no sandbox may be started on the wrong image")
require.Empty(t, fx.commands)
require.Nil(t, fx.configRepo.saved,
"moving the pointer here would commit a loss that restoring the credentials still undoes")
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NotNil(t, skill)
require.Equal(t, types.SkillStatusReady, skill.Status,
"every other skill in that image is still ready, and so is this one")
}
// The lock check has to sit above every write, not just above the snapshot:
// the fallback moves the image pointer without taking one.
func TestRunRemoveStopsBeforeClearingThePointerWhenTheLockIsLost(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fx.cancelDuringConfigRead = cancel
err := fx.svc.runRemove(ctx, 7, "cfg-1", "sk-1")
require.Error(t, err)
require.ErrorContains(t, err, "lock lost",
"the run must stop on the lost lock itself, not on whatever write happens to fail next")
require.Nil(t, fx.configRepo.saved,
"another run may already be building on this config; do not move its pointer")
}
// RemoveSkill validates the skill outside the lock, so two submissions queue
// two runs. The second one has nothing left to do and must not spend a sandbox,
// a snapshot and a generation bump proving it.
func TestRunRemoveDoesNothingWhenTheSkillIsAlreadyGone(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
require.NoError(t, fx.skillRepo.DeleteSkill(context.Background(), 7, "cfg-1", "sk-1"))
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
require.Empty(t, fx.events, "no session, no sandbox, no snapshot")
require.Empty(t, fx.commands)
require.Nil(t, fx.configRepo.saved)
}
// The snapshot exists before the ledger can be told about it, so a failure in
// between leaves its ID nowhere but a local variable. That is the same orphan
// the failed pointer switch produces and it gets the same treatment.
func TestRunRemoveDeletesTheSnapshotWhenTheLedgerCannotRecordIt(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.skillRepo.markStateFails = func(state string) bool {
return state == types.SkillSnapshotStateActive
}
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err)
require.Contains(t, fx.deletedSnapshots, "snap-1",
"a snapshot no row names is unreachable and billed; it must not be leaked")
require.Nil(t, fx.configRepo.saved)
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NotNil(t, skill)
require.Equal(t, types.SkillStatusReady, skill.Status)
}
// The orphan cleanup must survive the cancellation that produced the orphan:
// the switch fails because the context died, and the delete is a provider call
// on that same context.
func TestRunRemoveDeletesTheOrphanSnapshotAfterTheLockIsLost(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fx.cancelDuringSnapshot = cancel
err := fx.svc.runRemove(ctx, 7, "cfg-1", "sk-1")
require.Error(t, err)
require.Nil(t, fx.configRepo.saved, "the pointer switch runs on the dead context and fails")
require.Contains(t, fx.deletedSnapshots, "snap-1",
"cleaning up on the context that just died leaves a billed snapshot nobody can reach")
require.Equal(t, []string{"sess-1"}, fx.destroyedSandboxes)
}
// The archive is deleted only once the row that names it is gone. The other
// order leaves a row pointing at an object that no longer exists.
func TestRunRemoveKeepsTheBundleWhenTheRowCannotBeDeleted(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.skillRepo.deleteSkillErr = errUpdateBoom
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err)
require.Equal(t, 3, fx.skillRepo.deleteSkillAttempts,
"the image already lost the skill, so the row delete is retried, not reported as failed")
require.Empty(t, fx.deletedBundles,
"a surviving row must keep pointing at an archive that still exists")
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NotNil(t, skill)
}
func TestRunRemoveKeepsTheSkillWhenTheImageStepFails(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.rmExitCode = 1
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err)
require.Nil(t, fx.configRepo.saved)
require.NotContains(t, fx.events, "create-snapshot")
require.Equal(t, []string{"sess-1"}, fx.destroyedSandboxes)
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NotNil(t, skill, "a failed removal must leave the skill usable, not half-deleted")
require.Equal(t, types.SkillStatusReady, skill.Status)
require.NotEmpty(t, skill.Error, "the admin's only diagnostic is this row")
}
// A skill that never reached any image has nothing to restore to, so a failed
// removal must not advertise it as ready.
func TestRunRemoveLeavesANeverInstalledSkillFailed(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",
func(e *types.TenantSkillEntity) {
e.InstalledSnapshotID = ""
e.Status = types.SkillStatusRemoving
}))
fx.rmExitCode = 1
require.Error(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.Equal(t, types.SkillStatusFailed, skill.Status,
"calling a skill ready when no image ever carried it sends the agent at missing files")
}
func TestRunRemoveRefusesAnEmptySkillID(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "")
require.Error(t, err)
require.ErrorContains(t, err, "skill id is required")
require.Empty(t, fx.commands, "the command must not be issued at all")
require.Nil(t, fx.configRepo.saved)
}
func TestRunRemoveRefusesASkillNameThatCollapsesToTheSkillsRoot(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",
func(e *types.TenantSkillEntity) { e.Name = "" }))
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err,
"an empty skill name collapses to the skills root, and rm -rf there destroys every skill")
require.Empty(t, fx.commands, "the command must not be issued at all")
require.Nil(t, fx.configRepo.saved)
}
func TestRunRemoveStopsWhenTheLockIsLost(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
ctx, cancel := context.WithCancel(context.Background())
// withConfigLock cancels the run's context the moment lock renewal fails,
// which happens while the run is under way rather than before it starts.
fx.cancelDuringRemove = cancel
defer cancel()
err := fx.svc.runRemove(ctx, 7, "cfg-1", "sk-1")
require.Error(t, err)
require.NotContains(t, fx.events, "create-snapshot",
"losing the lock means another run may already be writing; do not snapshot")
require.Nil(t, fx.configRepo.saved)
require.Equal(t, []string{"sess-1"}, fx.destroyedSandboxes,
"a sandbox left running on the provider is billed until its TTL expires")
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Equal(t, types.SkillStatusReady, skill.Status,
"a row stuck at removing blocks the next attempt and tells the admin nothing")
}
// The compensating work must get a budget that starts when it starts. Every
// fixture removal finishes in microseconds, so a budget anchored at runRemove's
// entry looks fine here and expires on a real (minutes-long) removal.
func TestRunRemoveCleanupSurvivesARemovalLongerThanTheCleanupBudget(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.svc.cleanupTimeout = 50 * time.Millisecond
fx.removeDelay = 200 * time.Millisecond
start := time.Now()
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Greater(t, time.Since(start), fx.svc.cleanupTimeout,
"the removal must outlast the cleanup budget for this test to mean anything")
require.NoError(t, err)
require.Equal(t, []string{"sess-1"}, fx.destroyedSandboxes)
skill, getErr := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, getErr)
require.Nil(t, skill, "the row must still be dropped after the image lost the skill")
}
func TestRunRemoveDeletesTheSnapshotWhenSwitchFails(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 2)
fx.seedInstalledSkill("sk-2", "snap-old", 2)
fx.configRepo.updateErr = errUpdateBoom
err := fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1")
require.Error(t, err)
require.Contains(t, fx.deletedSnapshots, "snap-1",
"a snapshot nobody points at is an orphan; it must be cleaned up here")
require.NotContains(t, fx.deletedSnapshots, "snap-old",
"the previous image keeps serving and the ledger still names it")
skill, _ := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NotNil(t, skill)
require.Equal(t, types.SkillStatusReady, skill.Status)
}

View File

@ -0,0 +1,128 @@
package service
import (
"context"
"fmt"
"sync"
"time"
"github.com/redis/go-redis/v9"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/common/redislock"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// skillImageLockLease bounds how long one install/remove may hold the config
// lock without renewing. Installs run for minutes, so the lease is renewed by
// redislock rather than being set long.
const (
skillImageLockLease = 30 * time.Second
skillImageLockRenew = 10 * time.Second
skillInstallStuckTTL = 60 * time.Minute
)
// TenantSkillService owns the skill image lifecycle for sandbox configs.
type TenantSkillService struct {
skills repository.TenantSkillRepository
configs repository.TenantSandboxConfigRepository
resolver interfaces.StorageBackendResolver
sandboxes sandbox.TenantSandboxResolver
agents interfaces.AgentService
// installerAgents reads the stored installer record. It is a separate
// dependency from agents because GetAgentByID lives on the custom agent
// service, not on interfaces.AgentService.
installerAgents installerAgentSource
sessions interfaces.SessionService
models interfaces.ModelService
redis *redis.Client
now func() time.Time
// cleanupTimeout bounds one piece of compensating work. Injectable so a
// test can let an install outlast it, which every real install does.
cleanupTimeout time.Duration
// localLocks serialises installs when Redis is absent. It only guards this
// process; multi-replica deployments require Redis for cross-process safety.
localLocks *keyedMutex
}
func NewTenantSkillService(
skillsRepo repository.TenantSkillRepository,
configsRepo repository.TenantSandboxConfigRepository,
resolver interfaces.StorageBackendResolver,
sandboxes sandbox.TenantSandboxResolver,
agents interfaces.AgentService,
customAgents interfaces.CustomAgentService,
sessions interfaces.SessionService,
models interfaces.ModelService,
redisClient *redis.Client,
) *TenantSkillService {
return &TenantSkillService{
skills: skillsRepo,
configs: configsRepo,
resolver: resolver,
sandboxes: sandboxes,
agents: agents,
installerAgents: customAgents,
sessions: sessions,
models: models,
redis: redisClient,
now: time.Now,
cleanupTimeout: installCleanupTimeout,
localLocks: newKeyedMutex(),
}
}
// withConfigLock serialises every mutation of one config's skill image.
//
// This is not defensive locking: a new snapshot is the OLD snapshot plus this
// run's changes, and the config holds exactly one pointer. Two concurrent
// installs would each snapshot a base that lacks the other's work, and whoever
// wrote the pointer last would silently discard the other install.
func (s *TenantSkillService) withConfigLock(
ctx context.Context, configID string, fn func(context.Context) error,
) error {
if s.redis == nil {
release, err := s.localLocks.lock(ctx, configID)
if err != nil {
return err
}
defer release()
return fn(ctx)
}
key := fmt.Sprintf("weknora-skill-image-lock:%s", configID)
return redislock.WithRenewableLock(
ctx, s.redis, key, skillImageLockLease, skillImageLockRenew, fn,
)
}
// keyedMutex is the no-Redis fallback for withConfigLock.
type keyedMutex struct {
mu sync.Mutex
m map[string]chan struct{}
}
func newKeyedMutex() *keyedMutex { return &keyedMutex{m: map[string]chan struct{}{}} }
func (k *keyedMutex) lock(ctx context.Context, key string) (func(), error) {
if err := ctx.Err(); err != nil {
return nil, err
}
k.mu.Lock()
entry, ok := k.m[key]
if !ok {
entry = make(chan struct{}, 1)
k.m[key] = entry
}
k.mu.Unlock()
select {
case entry <- struct{}{}:
return func() { <-entry }, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}

View File

@ -0,0 +1,48 @@
package service
import (
"context"
"errors"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestTenantSkillServiceWithConfigLockLocalRespectsCanceledContext(t *testing.T) {
svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil)
entered := make(chan struct{})
releaseHolder := make(chan struct{})
holderDone := make(chan error, 1)
go func() {
holderDone <- svc.withConfigLock(context.Background(), "config-1", func(context.Context) error {
close(entered)
<-releaseHolder
return nil
})
}()
<-entered
ctx, cancel := context.WithCancel(context.Background())
cancel()
waiterDone := make(chan error, 1)
go func() {
waiterDone <- svc.withConfigLock(ctx, "config-1", func(context.Context) error {
return errors.New("canceled waiter entered lock")
})
}()
select {
case err := <-waiterDone:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(100 * time.Millisecond):
close(releaseHolder)
require.Fail(t, "canceled lock waiter did not return while another holder still held the local lock")
}
close(releaseHolder)
require.NoError(t, <-holderDone)
}

View File

@ -296,6 +296,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering session service...")
must(container.Provide(service.NewSessionService))
must(container.Provide(service.NewTenantSkillService))
// ArtifactCollector drains skill-generated files from the sandbox on
// each agent turn (see spec at

View File

@ -80,3 +80,37 @@ type SessionCapabilityProvider interface {
SessionShellExecutor() SessionShellExecutor
SessionFileStore() SessionFileStore
}
// SessionInstallShellExecutor runs install/maintenance shell commands, which
// need root and the skills image root. It is a separate interface from
// SessionShellExecutor so the privilege is something a caller must ask for by
// name: ordinary chat sessions keep the non-root, /workspace-only contract.
type SessionInstallShellExecutor interface {
ExecShellCommandWithOptions(
ctx context.Context,
sessionID string,
command string,
opts ShellExecOptions,
) (*ExecuteResult, error)
}
// SessionFileReader reads one file out of a session's sandbox. It is the
// single-method slice of SessionFileStore that callers which only ever read
// need, so a manager offering just this much is enough for them.
type SessionFileReader interface {
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
}
// SessionDestroyer releases the remote sandbox bound to a session, leaving the
// session record itself alone. Like RemoteSnapshotManager it is an optional
// capability: stateless backends have nothing to release.
type SessionDestroyer interface {
DestroySession(ctx context.Context, sessionID string) error
}
// SessionInstallCapabilityProvider is implemented by managers that can run
// install-mode shell commands. Like the other accessors it returns nil when
// the current runtime cannot honour the capability.
type SessionInstallCapabilityProvider interface {
SessionInstallShellExecutor() SessionInstallShellExecutor
}

View File

@ -836,9 +836,9 @@ func parseProxyURL(raw string) (host string, port int, scheme string, ok bool) {
// resolve `python3` (or similar) against $PATH inside the sandbox image.
func buildShellLine(cmd string, args []string) string {
parts := make([]string, 0, len(args)+1)
parts = append(parts, shellQuote(cmd))
parts = append(parts, ShellQuote(cmd))
for _, a := range args {
parts = append(parts, shellQuote(a))
parts = append(parts, ShellQuote(a))
}
return strings.Join(parts, " ")
}
@ -855,36 +855,6 @@ func wrapWithStdin(line, stdin string) string {
return "cat <<'" + delim + "' | " + line + "\n" + safe + "\n" + delim
}
// shellQuote wraps s in single quotes, escaping any embedded quotes. Suitable
// for building a /bin/bash -c line where every argv element should be treated
// as literal text.
func shellQuote(s string) string {
if s == "" {
return "''"
}
// Only bare tokens (alnum, dash, underscore, slash, dot, comma, colon,
// equals, plus) can be passed unquoted; everything else gets single
// quotes.
if isShellSafe(s) {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
func isShellSafe(s string) bool {
for _, r := range s {
switch {
case r >= 'a' && r <= 'z':
case r >= 'A' && r <= 'Z':
case r >= '0' && r <= '9':
case r == '-' || r == '_' || r == '/' || r == '.' || r == ',' ||
r == ':' || r == '=' || r == '+':
default:
return false
}
}
return true
}
func normalizeCubeState(state string) RemoteSandboxState {
switch strings.ToLower(strings.TrimSpace(state)) {
case "running", "available":

View File

@ -389,6 +389,54 @@ func (m *SessionBoundManager) DestroySession(ctx context.Context, sessionID stri
return m.lifecycle.Destroy(ctx, key)
}
// CreateSnapshot forwards provider snapshot creation for the live sandbox bound
// to sessionID. Session execution never uses this optional capability; it is
// reserved for skill image maintenance.
func (m *SessionBoundManager) CreateSnapshot(
ctx context.Context, sessionID string, name string,
) (RemoteSnapshotRef, error) {
if err := m.requireRemoteBackend(); err != nil {
return RemoteSnapshotRef{}, err
}
snapshots, ok := SnapshotManagerFrom(m.client)
if !ok || !m.client.Capabilities().SupportsSnapshots {
return RemoteSnapshotRef{}, errors.New("sandbox: remote provider does not support snapshots")
}
handle, err := m.resolveSession(ctx, sessionID)
if err != nil {
return RemoteSnapshotRef{}, err
}
return snapshots.CreateSnapshot(ctx, handle.ID(), name)
}
// DeleteSnapshot forwards provider snapshot deletion. It is used only to clean
// up a just-created orphan when the DB pointer switch fails.
func (m *SessionBoundManager) DeleteSnapshot(ctx context.Context, snapshotID string) error {
if err := m.requireRemoteBackend(); err != nil {
return err
}
snapshots, ok := SnapshotManagerFrom(m.client)
if !ok || !m.client.Capabilities().SupportsSnapshots {
return errors.New("sandbox: remote provider does not support snapshots")
}
return snapshots.DeleteSnapshot(ctx, snapshotID)
}
// ListSnapshots forwards provider snapshot listing for audit and later cleanup
// tasks.
func (m *SessionBoundManager) ListSnapshots(
ctx context.Context, sandboxID string,
) ([]RemoteSnapshotRef, error) {
if err := m.requireRemoteBackend(); err != nil {
return nil, err
}
snapshots, ok := SnapshotManagerFrom(m.client)
if !ok || !m.client.Capabilities().SupportsSnapshots {
return nil, errors.New("sandbox: remote provider does not support snapshots")
}
return snapshots.ListSnapshots(ctx, sandboxID)
}
// EnsureSessionDir creates dir inside the session's live sandbox when one is
// bound. It is a no-op when the session has no live binding; the skill
// framework will materialise the directory during the next Execute call.
@ -512,6 +560,36 @@ func (m *SessionBoundManager) ReadSessionFile(
return m.client.ReadFile(ctx, handle, filePath)
}
// WriteSessionFile writes an install/maintenance file into the session's live
// sandbox. It is deliberately narrower than a general remote write: only the
// tenant skills image root is accepted, because ordinary attachments must keep
// using WriteSessionInputFile and its /workspace/input guard.
func (m *SessionBoundManager) WriteSessionFile(
ctx context.Context, sessionID, filePath string, content []byte,
) error {
if err := m.requireRemoteBackend(); err != nil {
return err
}
if strings.TrimSpace(sessionID) == "" {
return errors.New("sandbox: session ID required for file staging")
}
clean := path.Clean(strings.TrimSpace(filePath))
if clean != SkillsImageRoot && !strings.HasPrefix(clean, SkillsImageRoot+"/") {
return fmt.Errorf("sandbox: install file path %q is outside %s", filePath, SkillsImageRoot)
}
handle, err := m.resolveSession(ctx, sessionID)
if err != nil {
return err
}
if err := m.client.MakeDir(ctx, handle, path.Dir(clean)); err != nil {
return fmt.Errorf("sandbox: create install directory: %w", err)
}
if err := m.client.WriteFile(ctx, handle, clean, content); err != nil {
return fmt.Errorf("sandbox: write install file %s: %w", clean, err)
}
return nil
}
// ShellExecOptions carries per-call shell execution knobs. The install-only
// flags are explicit so skill image maintenance can write under /opt without
// loosening work_dir or user privileges for ordinary chat sessions.
@ -630,6 +708,16 @@ func (m *SessionBoundManager) SessionShellExecutor() SessionShellExecutor {
return m
}
// SessionInstallShellExecutor advertises the privileged install-mode shell.
// Same nil contract as SessionShellExecutor: after Local fallback engages the
// capability disappears, so an install can never run on the host machine.
func (m *SessionBoundManager) SessionInstallShellExecutor() SessionInstallShellExecutor {
if m == nil || m.remoteDisabled() {
return nil
}
return m
}
// SessionFileStore advertises the session-scoped filesystem capability while
// a real remote backend is active and the provider implements the enumeration
// operations (ListDir / Stat / MakeDir / Remove).
@ -953,9 +1041,11 @@ func effectiveHTTPTimeout(provider RemoteProvider, cfg *Config) time.Duration {
}
var (
_ SessionCapabilityProvider = (*SessionBoundManager)(nil)
_ SessionShellExecutor = (*SessionBoundManager)(nil)
_ SessionFileStore = (*SessionBoundManager)(nil)
_ SessionCapabilityProvider = (*SessionBoundManager)(nil)
_ SessionShellExecutor = (*SessionBoundManager)(nil)
_ SessionFileStore = (*SessionBoundManager)(nil)
_ SessionInstallCapabilityProvider = (*SessionBoundManager)(nil)
_ SessionInstallShellExecutor = (*SessionBoundManager)(nil)
)
// PermissiveSessionExistenceChecker accepts every session. It is safe in

View File

@ -0,0 +1,38 @@
package sandbox
import "strings"
// ShellQuote renders s as one literal word for /bin/sh.
//
// Single quotes are the only construct that keeps every metacharacter inert:
// inside double quotes `$`, backtick and `\` still expand, so a path chosen by
// an uploaded archive would execute as a command. The embedded-quote escape is
// the usual '\” dance. Non-ASCII bytes are passed through unchanged, so a CJK
// file name still names the same file inside the sandbox.
func ShellQuote(s string) string {
if s == "" {
return "''"
}
// Only bare tokens (alnum, dash, underscore, slash, dot, comma, colon,
// equals, plus) can be passed unquoted; everything else gets single
// quotes.
if isShellSafe(s) {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
func isShellSafe(s string) bool {
for _, r := range s {
switch {
case r >= 'a' && r <= 'z':
case r >= 'A' && r <= 'Z':
case r >= '0' && r <= '9':
case r == '-' || r == '_' || r == '/' || r == '.' || r == ',' ||
r == ':' || r == '=' || r == '+':
default:
return false
}
}
return true
}

View File

@ -0,0 +1,25 @@
package sandbox
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestShellQuoteNeutralisesShellMetacharacters(t *testing.T) {
quoted := ShellQuote("/opt/weknora/tenant/skills/sk-1/scripts/x$(id).py")
require.Equal(t, `'/opt/weknora/tenant/skills/sk-1/scripts/x$(id).py'`, quoted,
"single quotes are the only form that keeps $ and backticks inert in sh")
}
func TestShellQuoteEscapesEmbeddedSingleQuote(t *testing.T) {
require.Equal(t, `'a'\''b'`, ShellQuote("a'b"))
}
func TestShellQuoteKeepsNonASCIILiteral(t *testing.T) {
quoted := ShellQuote("/opt/skills/sk-1/脚本.py")
require.Equal(t, `'/opt/skills/sk-1/脚本.py'`, quoted,
"a CJK path must reach the shell as itself, not as a \\u escape")
}

View File

@ -81,10 +81,10 @@ func SkillInterpreterCommand(skillDir, scriptPath string) (string, []string) {
switch strings.ToLower(path.Ext(scriptPath)) {
case ".py":
venvPython := path.Join(skillDir, ".venv", "bin", "python")
script := shellQuote(scriptPath)
script := ShellQuote(scriptPath)
return "/bin/sh", []string{"-c", fmt.Sprintf(
`if [ -x %s ]; then exec %s %s "$@"; else exec python3 %s "$@"; fi`,
shellQuote(venvPython), shellQuote(venvPython), script, script,
ShellQuote(venvPython), ShellQuote(venvPython), script, script,
), skillShellArgv0}
case ".js", ".mjs":
return "node", []string{scriptPath}

View File

@ -78,6 +78,30 @@ type AgentConfig struct {
// Whether to execute independent tool calls in parallel (default: false).
// When enabled and the LLM returns multiple tool calls, they run concurrently via errgroup.
ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
// skillInstallMode routes this run's shell_exec to the privileged
// install-mode executor (root, skills image root writable). It is
// unexported on purpose: JSON cannot reach it, so no stored agent record
// and no API payload can request the privilege, and no other package can
// assign it. EnableSkillInstallMode is the only way in and it refuses
// every agent except the built-in skill installer.
skillInstallMode bool
}
// EnableSkillInstallMode grants install-mode shell execution to the built-in
// skill installer agent and to nothing else. The agent ID is checked here
// rather than at the call site so there is exactly one place to audit.
func (c *AgentConfig) EnableSkillInstallMode(agentID string) {
if c == nil || agentID != BuiltinSkillInstallerID {
return
}
c.skillInstallMode = true
}
// SkillInstallMode reports whether this run may use the privileged
// install-mode shell.
func (c *AgentConfig) SkillInstallMode() bool {
return c != nil && c.skillInstallMode
}
// CitationsEnabled preserves citation output for legacy runtime configs that

View File

@ -28,6 +28,8 @@ const (
BuiltinWikiResearcherID = "builtin-wiki-researcher"
// BuiltinWikiFixerID is the ID for the built-in wiki fixer agent
BuiltinWikiFixerID = "builtin-wiki-fixer"
// BuiltinSkillInstallerID is the ID for the built-in skill installer agent
BuiltinSkillInstallerID = "builtin-skill-installer"
)
// AgentMode constants for agent running mode
@ -565,11 +567,12 @@ var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{}
// builtinAgentIDsOrdered defines the fixed display order of built-in agents
// that are exposed in the user-facing agent list (ListAgents).
//
// NOTE: BuiltinWikiFixerID is intentionally excluded here. The wiki fixer is
// an internal agent invoked programmatically from the Wiki editor
// (see frontend WikiBrowser.vue) and should not clutter the tenant's agent
// picker. It remains fully usable via GetAgentByID because the YAML entry
// still registers it in BuiltinAgentRegistry.
// NOTE: BuiltinWikiFixerID and BuiltinSkillInstallerID are intentionally
// excluded here. Both are internal agents invoked programmatically — the wiki
// fixer from the Wiki editor, the skill installer from the sandbox-config skill
// upload flow — and should not clutter the tenant's agent picker. They remain
// fully usable via GetAgentByID because the YAML entries still register them in
// BuiltinAgentRegistry.
var builtinAgentIDsOrdered = []string{
BuiltinQuickAnswerID,
BuiltinSmartReasoningID,