From 67cdf26216389c0d3f0bc367cf746850c5bdd1b9 Mon Sep 17 00:00:00 2001 From: hailongzhao Date: Thu, 20 Aug 2026 12:02:59 +0800 Subject: [PATCH] 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 --- config/builtin_agents.yaml | 36 + .../prompt_templates/agent_system_prompt.yaml | 59 + internal/agent/tools/shell_exec.go | 82 +- internal/agent/tools/shell_exec_test.go | 2 +- internal/application/service/agent_service.go | 100 +- .../agent_service_install_shell_test.go | 120 ++ .../service/agent_service_shell_test.go | 11 +- .../application/service/agent_service_test.go | 253 +++ .../service/session_attachment_staging.go | 11 + .../service/tenant_skill_bundle.go | 225 +++ .../service/tenant_skill_bundle_test.go | 309 ++++ .../service/tenant_skill_install.go | 1193 ++++++++++++++ .../service/tenant_skill_install_test.go | 1424 +++++++++++++++++ .../service/tenant_skill_progress.go | 69 + .../service/tenant_skill_remove.go | 436 +++++ .../service/tenant_skill_remove_test.go | 368 +++++ .../service/tenant_skill_service.go | 128 ++ .../service/tenant_skill_service_test.go | 48 + internal/container/container.go | 1 + internal/sandbox/capabilities.go | 34 + internal/sandbox/cube_remote_client.go | 34 +- internal/sandbox/session_manager.go | 96 +- internal/sandbox/shell_quote.go | 38 + internal/sandbox/shell_quote_test.go | 25 + internal/sandbox/skill_paths.go | 4 +- internal/types/agent.go | 24 + internal/types/custom_agent.go | 13 +- 27 files changed, 5066 insertions(+), 77 deletions(-) create mode 100644 internal/application/service/agent_service_install_shell_test.go create mode 100644 internal/application/service/tenant_skill_bundle.go create mode 100644 internal/application/service/tenant_skill_bundle_test.go create mode 100644 internal/application/service/tenant_skill_install.go create mode 100644 internal/application/service/tenant_skill_install_test.go create mode 100644 internal/application/service/tenant_skill_progress.go create mode 100644 internal/application/service/tenant_skill_remove.go create mode 100644 internal/application/service/tenant_skill_remove_test.go create mode 100644 internal/application/service/tenant_skill_service.go create mode 100644 internal/application/service/tenant_skill_service_test.go create mode 100644 internal/sandbox/shell_quote.go create mode 100644 internal/sandbox/shell_quote_test.go diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml index 22b0ce52..98887162 100644 --- a/config/builtin_agents.yaml +++ b/config/builtin_agents.yaml @@ -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 + diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index f46f72d3..68331c21 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -487,3 +487,62 @@ templates: User Language: {{language}} + + - 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: | + + 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. + + + + 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 + + + + 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 ). + 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. + + + + 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 `/.venv` and install into it. + With uv: `uv venv /.venv` then `uv pip install --python /.venv/bin/python -r /requirements.txt` + Without uv: `python3 -m venv /.venv` then `/.venv/bin/pip install -r /requirements.txt` + - Node: install into `/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. + + + + * **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. + + + + 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. + + + + User Language: {{language}} + diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go index 43bf0043..dfba8d7e 100644 --- a/internal/agent/tools/shell_exec.go +++ b/internal/agent/tools/shell_exec.go @@ -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 diff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.go index bdb74247..3dd69033 100644 --- a/internal/agent/tools/shell_exec_test.go +++ b/internal/agent/tools/shell_exec_test.go @@ -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) } diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index 90cf17bd..aa79df0b 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -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, diff --git a/internal/application/service/agent_service_install_shell_test.go b/internal/application/service/agent_service_install_shell_test.go new file mode 100644 index 00000000..5059d6df --- /dev/null +++ b/internal/application/service/agent_service_install_shell_test.go @@ -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()) +} diff --git a/internal/application/service/agent_service_shell_test.go b/internal/application/service/agent_service_shell_test.go index 5e09bf0d..74b22633 100644 --- a/internal/application/service/agent_service_shell_test.go +++ b/internal/application/service/agent_service_shell_test.go @@ -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) { diff --git a/internal/application/service/agent_service_test.go b/internal/application/service/agent_service_test.go index 52ed5085..00f299ed 100644 --- a/internal/application/service/agent_service_test.go +++ b/internal/application/service/agent_service_test.go @@ -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) diff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.go index 205fd8f4..26cb380c 100644 --- a/internal/application/service/session_attachment_staging.go +++ b/internal/application/service/session_attachment_staging.go @@ -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. diff --git a/internal/application/service/tenant_skill_bundle.go b/internal/application/service/tenant_skill_bundle.go new file mode 100644 index 00000000..1c40b520 --- /dev/null +++ b/internal/application/service/tenant_skill_bundle.go @@ -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 +} diff --git a/internal/application/service/tenant_skill_bundle_test.go b/internal/application/service/tenant_skill_bundle_test.go new file mode 100644 index 00000000..15278eca --- /dev/null +++ b/internal/application/service/tenant_skill_bundle_test.go @@ -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) + }) +} diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go new file mode 100644 index 00000000..e92202ce --- /dev/null +++ b/internal/application/service/tenant_skill_install.go @@ -0,0 +1,1193 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/Tencent/WeKnora/internal/agent/tools" + apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/models/chat" + "github.com/Tencent/WeKnora/internal/sandbox" + "github.com/Tencent/WeKnora/internal/types" +) + +const ( + installCommandTimeout = 10 * time.Minute + + // installCleanupTimeout bounds the compensating work that must outlive the + // install context: destroying the sandbox and writing the terminal row. + installCleanupTimeout = 30 * time.Second + + // The terminal "ready" write happens after the pointer has moved, so it is + // retried: the skill is already installed and serving, and the only thing + // still missing is the row that says so. + readySkillWriteAttempts = 3 + readySkillWriteDelay = 100 * time.Millisecond +) + +// InstallSkill validates an uploaded archive, records it, and kicks off the +// install in the background. It returns the skill ID so the caller can answer +// 202 and let the UI subscribe to progress. +func (s *TenantSkillService) InstallSkill( + ctx context.Context, tenantID uint64, configID string, archive []byte, +) (string, error) { + cfgEntity, err := s.configs.GetByID(ctx, tenantID, configID) + if err != nil { + return "", err + } + if cfgEntity == nil { + return "", apperrors.NewNotFoundError("sandbox config not found") + } + + bundle, err := ParseSkillBundle(archive) + if err != nil { + return "", err + } + + // Re-uploading a skill by the same name is an upgrade of that skill, not a + // second row: the unique (config, name) index would reject the insert, and + // the image directory is the name, so it stays put. + existing, err := s.skills.GetSkillByName(ctx, tenantID, configID, bundle.Name) + if err != nil { + return "", err + } + + skillID := uuid.NewString() + now := s.now() + if existing != nil { + skillID = existing.ID + existing.Version = bundle.Version + existing.Description = bundle.Description + existing.Instructions = bundle.Instructions + existing.BundleSHA256 = bundle.SHA256 + existing.Status = types.SkillStatusInstalling + existing.Error = "" + existing.InstallingSince = &now + if err := s.skills.UpdateSkill(ctx, existing); err != nil { + return "", err + } + } else { + if err := s.skills.CreateSkill(ctx, &types.TenantSkillEntity{ + ID: skillID, TenantID: tenantID, SandboxConfigID: configID, + Name: bundle.Name, Version: bundle.Version, + Description: bundle.Description, Instructions: bundle.Instructions, + BundleSHA256: bundle.SHA256, Enabled: true, + Status: types.SkillStatusInstalling, InstallingSince: &now, + }); err != nil { + return "", err + } + } + + // Store the archive before the long-running part: read_skill serves file + // contents from it, and a re-install after a crash needs it too. + if ref, err := s.saveBundle(ctx, tenantID, skillID, archive); err == nil { + _ = s.updateSkillFields(ctx, tenantID, configID, skillID, func(e *types.TenantSkillEntity) { + e.BundleRef = ref + }) + } else { + logger.Warnf(ctx, "[skill] store bundle for %s failed: %v", skillID, err) + } + + s.publishProgress(ctx, configID, skillID, SkillProgress{ + Percent: 10, Stage: "accepted", Status: types.SkillStatusInstalling, + }) + + // The install outlives the HTTP request, so it must not inherit its + // cancellation. It is not durable across a restart either - the stuck-run + // reaper (Task 17) is what closes that gap. + go func() { + bgCtx := context.WithoutCancel(ctx) + if err := s.withConfigLock(bgCtx, configID, func(lockCtx context.Context) error { + return s.runInstall(lockCtx, tenantID, configID, skillID, bundle) + }); err != nil { + logger.Errorf(bgCtx, "[skill] install %s failed: %v", skillID, err) + } + }() + + return skillID, nil +} + +func (s *TenantSkillService) runInstall( + ctx context.Context, tenantID uint64, configID, skillID string, bundle *SkillBundle, +) (err error) { + ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID) + ctx = types.WithSandboxTenantID(ctx, tenantID) + + // The name comes from SKILL.md and is already validated on parse, so a + // rejection here means the bundle was accepted by a looser rule than the + // one the image path enforces. Failing before any sandbox work keeps that + // disagreement cheap. + skillDir, err := sandbox.SkillDirFor(bundle.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 the two things that must still happen then are a provider + // call (destroy the sandbox, or it stays running and billed) and a DB write + // (mark the skill failed, or the row sits at "installing" with the cause + // only in a log line). + // + // Only cancellation is detached here; the deadline is NOT. An install runs + // for minutes โ€” a single agent command may take installCommandTimeout โ€” so + // a timeout started at this line would already be spent by the time any + // compensating work begins. Each consumer calls cleanupContext to start its + // own budget at the moment it needs one. + cleanupBase := context.WithoutCancel(ctx) + + // pointerSwitched marks the point of no return. Past it the skill is + // installed, snapshotted and serving every new session, so a later failure + // is a bookkeeping failure and must not be reported as a failed install. + pointerSwitched := false + defer func() { + if err == nil { + return + } + if pointerSwitched { + logger.Errorf(cleanupBase, + "[skill] %s is installed and serving but its bookkeeping is incomplete: %v", + skillID, err) + return + } + // The image pointer is deliberately untouched on failure: the previous + // snapshot keeps serving every session. + failCtx, cancelFail := s.cleanupContext(cleanupBase) + defer cancelFail() + s.failSkill(failCtx, 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) + } + if err := ensureUsableImage(cfgEntity); err != nil { + return err + } + + // 1. Install session + sandbox. ResolveEffectiveConfig has already turned + // the current snapshot into the template, so this sandbox boots from the + // existing image and this install stacks on top of it. + sess, mgr, err := s.startMaintenanceSession(ctx, tenantID, configID, "install") + if err != nil { + return err + } + // Only the sandbox is released. The session and its messages stay so the + // agent's install transcript can be read back when something goes wrong. + defer func() { + releaseCtx, cancelRelease := s.cleanupContext(cleanupBase) + defer cancelRelease() + s.releaseSandbox(releaseCtx, mgr, sess.ID) + }() + + s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 25, Stage: "sandbox_ready"}) + + // 2. Provision the target directory, then seed the source files + // server-side. The agent only installs dependencies; it never has to + // reconstruct the skill itself. + if err := s.resetSkillDir(ctx, mgr, sess.ID, skillDir); err != nil { + return err + } + if err := s.seedSkillFiles(ctx, mgr, sess.ID, skillDir, bundle); err != nil { + return err + } + s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 35, Stage: "seeded"}) + + // 3. Let the installer agent install dependencies. + if err := s.driveInstallerAgent(ctx, tenantID, sess, mgr, skillDir, bundle); err != nil { + return err + } + s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 80, Stage: "agent_done"}) + + // 4. Hand the tree to the execution user BEFORE verifying it. The agent + // created these files as root, and the smoke run below deliberately + // runs as the ordinary user: verifying first would test permissions + // that never reach the image, and a restrictive root umask would fail a + // perfectly good install because the .venv interpreter was unreadable. + if err := s.normalizeSkillPermissions(ctx, mgr, sess.ID, skillDir); err != nil { + return err + } + + // 5. Verify ourselves. "The agent said it worked" is a sentence, not + // evidence, and this is the last gate before the image is switched. + if err := s.verifySkill(ctx, mgr, sess.ID, skillDir, bundle); err != nil { + return err + } + if err := s.writeManifestEntry(ctx, mgr, sess.ID, skillID, bundle); err != nil { + return err + } + s.publishProgress(ctx, configID, skillID, SkillProgress{Percent: 90, Stage: "verified"}) + + // 6. Wipe the scratch state. It must happen BEFORE the snapshot, or the + // per-session workspace and every package cache land in the image. + if err := s.cleanImageScratch(ctx, mgr, sess.ID); err != nil { + return err + } + + // 7. Snapshot. This is the point of no return: everything above is + // confined to a sandbox we are about to destroy, everything below + // creates provider resources and moves the pointer. withConfigLock + // cancels this context when the lock's renewal fails, and a lost lock + // means another install may already be building on the same config, so + // stop here rather than race it. The ledger row is written before the + // snapshot: a snapshot with no ledger entry is a resource nobody knows + // exists. + if err := ctx.Err(); err != nil { + return fmt.Errorf("install lock lost before snapshot: %w", err) + } + // The generation comes from the config read at the top of this function, + // while switchImagePointer deliberately re-reads for everything else it + // writes. That asymmetry is sound because the two fields have different + // writers: SkillImage is written only by an install or a removal, and + // withConfigLock serialises every one of those per config, so no other + // writer can have advanced the generation while this run held the lock. + // The rest of the entity is written by the config service under its own + // cordon, which this lock says nothing about โ€” hence the re-read there. + generation := currentGeneration(cfgEntity) + 1 + installRowID := uuid.NewString() + if err := s.skills.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{ + ID: installRowID, TenantID: tenantID, SandboxConfigID: configID, SkillID: skillID, + ParentSnapshotID: currentSnapshotID(cfgEntity), Generation: generation, + Trigger: types.SkillSnapshotTriggerInstall, 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, installRowID, 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, installRowID, ref.ID) + return err + } + + // 8. Switch the pointer. One DB write; everything after this is cleanup. + if err := s.switchImagePointer(ctx, tenantID, configID, ref.ID, generation); err != nil { + s.abandonSnapshot(cleanupBase, tenantID, mgr, installRowID, ref.ID) + return err + } + pointerSwitched = true + s.markPreviousSnapshotsSuperseded(ctx, tenantID, configID, installRowID) + + // The terminal write is the one that must not be best-effort: the pointer + // already moved, so a row left at "installing" would be reaped as failed + // even though the skill is installed and serving. + readyCtx, cancelReady := s.cleanupContext(cleanupBase) + defer cancelReady() + if err := s.writeReadySkillState(readyCtx, tenantID, configID, skillID, ref.ID); err != nil { + return err + } + s.markConfigSandboxesStale(ctx, tenantID, configID) + s.publishProgress(ctx, configID, skillID, SkillProgress{ + Percent: 100, Stage: "done", Status: types.SkillStatusReady, + }) + return nil +} + +// ensureUsableImage refuses to grow the image when the stored snapshot is one +// the live credentials cannot resolve. +// +// Snapshots are private to a provider account, so a rotated credential turns +// the recorded pointer into an ID that no longer exists for us: the session +// layer notices via the fingerprint and boots the BASE TEMPLATE instead. A run +// that ignored that would do its work in a sandbox carrying none of the +// tenant's skills, snapshot that, and switch the pointer to it with a +// fingerprint that now matches - so it sticks, while every skill row still +// claims ready. Until then the old image is still recoverable by restoring the +// credential, which is why both flows stop here instead of committing the loss. +func ensureUsableImage(cfgEntity *types.TenantSandboxConfigEntity) error { + if cfgEntity == nil || cfgEntity.Config == nil { + return nil + } + image := cfgEntity.Config.SkillImage + if image == nil || strings.TrimSpace(image.SnapshotID) == "" { + return nil + } + // An empty fingerprint on either side is the same condition: the session + // layer keeps the base template for both. + live := skillOwnerFingerprint(cfgEntity.Config) + if live != "" && image.OwnerFingerprint == live { + return nil + } + return fmt.Errorf( + "skill image %s of sandbox config %s belongs to another provider account; "+ + "restore the credentials it was built with or rebuild the image", + image.SnapshotID, cfgEntity.ID, + ) +} + +// abandonSnapshot disposes of a snapshot that was created but never became +// reachable - either because the ledger could not be told its ID or because +// the pointer switch failed. Both leave a provider resource that is billed and +// that nothing can ever boot again, and this is the only snapshot delete +// either flow performs: an ordinary switch leaves the previous image reachable +// for the ledger. +// +// It runs on a detached context because a cancelled one is among the reasons +// the caller failed, and that is exactly when a leaked snapshot is most likely. +func (s *TenantSkillService) abandonSnapshot( + cleanupBase context.Context, tenantID uint64, mgr sandbox.Manager, rowID, snapshotID string, +) { + ctx, cancel := s.cleanupContext(cleanupBase) + defer cancel() + s.deleteSnapshotBestEffort(ctx, mgr, snapshotID) + _ = s.skills.MarkSnapshotState( + ctx, tenantID, rowID, types.SkillSnapshotStateDeleted, snapshotID) +} + +// cleanupContext bounds one piece of compensating work, starting the budget +// when that work starts. Anchoring it earlier would hand every consumer an +// already-expired deadline, because an install takes minutes to reach them. +func (s *TenantSkillService) cleanupContext( + base context.Context, +) (context.Context, context.CancelFunc) { + timeout := s.cleanupTimeout + if timeout <= 0 { + timeout = installCleanupTimeout + } + return context.WithTimeout(base, timeout) +} + +// resetSkillDir makes the target directory an empty, writable directory owned +// by the execution user. +// +// Emptying it is what makes a re-install an install of exactly the uploaded +// bundle: the sandbox boots from the inherited image, so a file that the +// previous version shipped and this one dropped would otherwise live on in +// every later snapshot while BundleSHA256 claims the tree equals the archive. +// +// Creating and chowning it is what makes the FIRST install work at all: +// seeding goes through the provider file API, which runs as the default exec +// user, and the skills root is not part of the base image. +func (s *TenantSkillService) resetSkillDir( + ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, +) error { + if err := guardSkillDir(skillDir); err != nil { + return err + } + root := sandbox.ShellQuote(sandbox.SkillsImageRoot) + dir := sandbox.ShellQuote(skillDir) + user := sandbox.DefaultSandboxExecUser + cmd := fmt.Sprintf( + "rm -rf %s && mkdir -p %s %s && chown %s:%s %s %s && chmod 755 %s %s", + dir, root, dir, user, user, root, dir, root, dir, + ) + if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil { + return fmt.Errorf("reset skill directory %s: %w", skillDir, err) + } + return nil +} + +// guardSkillDir refuses the one path no destructive skill command may target. +// SkillDirFor("") collapses to the skills root, so an empty skill name would +// turn any "rm -rf " into a wipe of every skill in the image. No caller +// can pass an empty name today; this is the invariant that keeps that true, +// because the failure is unrecoverable. +func guardSkillDir(skillDir string) error { + if path.Clean(skillDir) == path.Clean(sandbox.SkillsImageRoot) { + return fmt.Errorf("refusing to use the skills root %q as a skill directory", skillDir) + } + return nil +} + +// seedSkillFiles writes the archive contents into the image. Doing it +// server-side rather than asking the agent to unpack keeps the source of truth +// byte-identical to what was uploaded. Provisioning the directory is +// runInstall's step 2, not this function's job. +func (s *TenantSkillService) seedSkillFiles( + ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle, +) error { + store, err := installFileStore(mgr) + if err != nil { + return err + } + for rel, content := range bundle.Files { + target := path.Join(skillDir, rel) + if err := store.WriteSessionFile(ctx, sessionID, target, content); err != nil { + return fmt.Errorf("seed %s: %w", target, err) + } + } + return nil +} + +// driveInstallerAgent runs one installer conversation. It calls the engine +// directly instead of going through sessionService.AgentQA, because AgentQA +// swallows engine failures (it emits an error event and returns nil) and we +// need a reliable signal before switching the image. +func (s *TenantSkillService) driveInstallerAgent( + ctx context.Context, tenantID uint64, sess *types.Session, mgr sandbox.Manager, + skillDir string, bundle *SkillBundle, +) error { + if s.installerAgents == nil { + return errors.New("custom agent service is not configured") + } + // The record is tenant-writable: updateBuiltinAgent lets a tenant persist a + // Config for any built-in ID, this one included. It is therefore read for + // the model choice only. What the root shell is told to do comes from the + // platform's own registry entry. + record, err := s.installerAgents.GetAgentByID(ctx, types.BuiltinSkillInstallerID) + if err != nil { + return fmt.Errorf("load installer agent: %w", err) + } + agentConfig := installerAgentConfig(installerAgentDefaults(ctx, tenantID), sess.SandboxConfigID) + + chatModel, err := s.resolveInstallerModel(ctx, tenantID, record) + if err != nil { + return err + } + + bus := event.NewEventBus() + assistantMessageID := uuid.NewString() + engine, err := s.agents.CreateAgentEngine( + ctx, agentConfig, chatModel, nil, bus, sess.ID, assistantMessageID, + ) + if err != nil { + return fmt.Errorf("create installer engine: %w", err) + } + + prompt := buildInstallPrompt(skillDir, bundle, s.probeUv(ctx, mgr, sess.ID)) + state, err := engine.Execute(ctx, sess.ID, assistantMessageID, prompt, nil) + if err != nil { + return fmt.Errorf("installer agent failed: %w", err) + } + if state == nil || !state.IsComplete { + return errors.New("installer agent stopped without completing") + } + return nil +} + +// verifySkill is the server's own check. Both structure and smoke run are +// gates for the snapshot switch: a broken install must leave the old image live. +func (s *TenantSkillService) verifySkill( + ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle, +) error { + if _, err := s.execInstall(ctx, mgr, sessionID, + fmt.Sprintf("test -f %s", sandbox.ShellQuote(path.Join(skillDir, "SKILL.md")))); err != nil { + return fmt.Errorf("skill directory is incomplete after install: %w", err) + } + for rel := range bundle.Files { + if !strings.HasSuffix(rel, ".py") && !strings.HasSuffix(rel, ".js") && + !strings.HasSuffix(rel, ".mjs") && !strings.HasSuffix(rel, ".sh") { + continue + } + target := path.Join(skillDir, rel) + if _, err := s.execInstall(ctx, mgr, sessionID, + fmt.Sprintf("test -f %s", sandbox.ShellQuote(target))); err != nil { + return fmt.Errorf("script %s is missing after install: %w", rel, err) + } + } + if entry := primaryEntryScript(bundle); entry != "" { + res, err := s.execSmoke(ctx, mgr, sessionID, skillDir, path.Join(skillDir, entry)) + if err != nil { + return fmt.Errorf("smoke run %s: %w", entry, err) + } + if res.ExitCode != 0 { + return fmt.Errorf("smoke run %s failed (%s)", entry, describeExecFailure(res)) + } + } + return nil +} + +// normalizeSkillPermissions hands the skill tree to the execution user. +// Installs run as root, so without this the non-root user that actually runs +// skills could not read them โ€” which is also why it runs before verification: +// the smoke test has to exercise the permissions the snapshot will carry. +func (s *TenantSkillService) normalizeSkillPermissions( + ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, +) error { + cmds := []string{ + fmt.Sprintf("chmod -R 755 %s", sandbox.ShellQuote(skillDir)), + fmt.Sprintf("chown -R %s %s", sandbox.DefaultSandboxExecUser, sandbox.ShellQuote(skillDir)), + } + for _, cmd := range cmds { + if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil { + return fmt.Errorf("normalize skill permissions (%s): %w", cmd, err) + } + } + return nil +} + +// cleanImageScratch wipes the state that must not reach the snapshot: the +// per-session workspace and the package download caches. +func (s *TenantSkillService) cleanImageScratch( + ctx context.Context, mgr sandbox.Manager, sessionID string, +) error { + cmds := []string{ + "rm -rf /workspace/* /workspace/.[!.]* || true", + // Spelled out for both accounts on purpose: this runs as root, so "~" + // would only ever clear root's caches, while the agent's own installs + // populate the exec user's caches and those are what reach the image. + "rm -rf " + strings.Join(append( + packageCachePaths("/root"), + packageCachePaths(path.Join("/home", sandbox.DefaultSandboxExecUser))..., + ), " ") + " || true", + } + for _, cmd := range cmds { + if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil { + return fmt.Errorf("clean image scratch (%s): %w", cmd, err) + } + } + return nil +} + +// packageCachePaths lists the download caches the three package managers we +// support keep under a home directory. They are scratch by definition and +// would otherwise be snapshotted into every future session's image. +func packageCachePaths(home string) []string { + return []string{ + path.Join(home, ".cache", "pip"), + path.Join(home, ".cache", "uv"), + path.Join(home, ".npm"), + path.Join(home, ".local", "share", "pnpm", "store"), + } +} + +// describeExecFailure renders everything the executor knows about a failed +// command. Transport failures and timeouts arrive as ExitCode -1 with an empty +// Stderr and the cause in Error, so formatting Stderr alone leaves the admin +// with "command failed (exit -1): " and nothing else. +func describeExecFailure(res *sandbox.ExecuteResult) string { + if res == nil { + return "no result from the sandbox" + } + parts := []string{fmt.Sprintf("exit %d", res.ExitCode)} + if res.Killed { + parts = append(parts, "killed") + } + if cause := strings.TrimSpace(res.Error); cause != "" { + parts = append(parts, "error: "+cause) + } + if stderr := strings.TrimSpace(res.Stderr); stderr != "" { + parts = append(parts, "stderr: "+stderr) + } + return strings.Join(parts, "; ") +} + +// installExecutor resolves the one executor every command of an install runs +// through. It goes through the capability accessor rather than a bare type +// assertion so a manager that fell back to LocalSandbox reports no capability +// instead of running the install on the WeKnora host. +func installExecutor(mgr sandbox.Manager) (sandbox.SessionInstallShellExecutor, error) { + executor := sessionSandboxInstallShellExecutor(mgr) + if executor == nil { + return nil, errors.New("sandbox backend does not support install-mode shell") + } + return executor, nil +} + +// execInstall runs one command as root with the skills root allowed. +func (s *TenantSkillService) execInstall( + ctx context.Context, mgr sandbox.Manager, sessionID, command string, +) (*sandbox.ExecuteResult, error) { + executor, err := installExecutor(mgr) + if err != nil { + return nil, err + } + res, err := executor.ExecShellCommandWithOptions(ctx, sessionID, command, + sandbox.ShellExecOptions{AsRoot: true, AllowSkillsRoot: true, Timeout: installCommandTimeout}) + if err != nil { + return nil, err + } + if res.ExitCode != 0 { + return res, fmt.Errorf("command failed (%s)", describeExecFailure(res)) + } + return res, nil +} + +func (s *TenantSkillService) saveBundle( + ctx context.Context, tenantID uint64, skillID string, archive []byte, +) (string, error) { + if s.resolver == nil { + return "", errors.New("storage resolver is not configured") + } + fs, _, err := s.resolver.ResolveFileService(ctx, &types.Tenant{ID: tenantID}, "", "", "") + if err != nil { + return "", err + } + if fs == nil { + return "", errors.New("file service is not configured") + } + return fs.SaveBytes(ctx, archive, tenantID, fmt.Sprintf("tenant-skills/%s.zip", skillID), false) +} + +// updateSkillFields loads, mutates and writes back one skill row. It logs on +// failure for the progress-only call sites and returns the error for the one +// call site where the row is the record of a completed install. +func (s *TenantSkillService) updateSkillFields( + ctx context.Context, + tenantID uint64, + configID, skillID string, + mutate func(*types.TenantSkillEntity), +) error { + skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID) + if err != nil { + logger.Warnf(ctx, "[skill] load %s for update failed: %v", skillID, err) + return fmt.Errorf("load skill %s: %w", skillID, err) + } + if skill == nil { + return fmt.Errorf("skill %s not found", skillID) + } + mutate(skill) + if err := s.skills.UpdateSkill(ctx, skill); err != nil { + logger.Warnf(ctx, "[skill] update %s failed: %v", skillID, err) + return fmt.Errorf("update skill %s: %w", skillID, err) + } + return nil +} + +// writeReadySkillState records the finished install. It is retried because it +// runs after the pointer switch: the skill is installed, snapshotted and being +// served, so a transient write failure here is a bookkeeping gap, not a failed +// install, and re-running the whole install to fix a row would be absurd. +func (s *TenantSkillService) writeReadySkillState( + ctx context.Context, tenantID uint64, configID, skillID, snapshotID string, +) error { + if err := s.retrySkillBookkeeping(ctx, func() error { + return s.updateSkillFields(ctx, tenantID, configID, skillID, + func(e *types.TenantSkillEntity) { + e.Status = types.SkillStatusReady + e.Error = "" + e.InstalledSnapshotID = snapshotID + e.InstallingSince = nil + }) + }); err != nil { + return fmt.Errorf("skill %s is installed and serving but could not be marked ready: %w", + skillID, err) + } + return nil +} + +// retrySkillBookkeeping runs one terminal bookkeeping write past the point of +// no return, where the image already changed and only the row recording it is +// missing. Both callers are in that position, so both retry instead of +// reporting the whole run as failed. +func (s *TenantSkillService) retrySkillBookkeeping( + ctx context.Context, write func() error, +) error { + var lastErr error + for attempt := 1; attempt <= readySkillWriteAttempts; attempt++ { + if attempt > 1 { + select { + case <-time.After(readySkillWriteDelay): + case <-ctx.Done(): + return ctx.Err() + } + } + if lastErr = write(); lastErr == nil { + return nil + } + } + return lastErr +} + +func (s *TenantSkillService) failSkill( + ctx context.Context, tenantID uint64, configID, skillID string, cause error, +) { + _ = s.updateSkillFields(ctx, tenantID, configID, skillID, func(e *types.TenantSkillEntity) { + e.Status = types.SkillStatusFailed + e.Error = cause.Error() + e.InstallingSince = nil + }) + s.publishProgress(ctx, configID, skillID, SkillProgress{ + Percent: 100, Stage: "failed", Status: types.SkillStatusFailed, Log: cause.Error(), + }) +} + +// startMaintenanceSession opens the session one image operation runs in. The +// operation name is carried into the session because the transcript is kept +// deliberately, for troubleshooting: filing a removal's under "Skill install" +// would send whoever reads it looking at the wrong operation. +func (s *TenantSkillService) startMaintenanceSession( + ctx context.Context, tenantID uint64, configID, operation string, +) (*types.Session, sandbox.Manager, error) { + if s.sessions == nil { + return nil, nil, errors.New("session service is not configured") + } + sess, err := s.sessions.CreateSession(ctx, &types.Session{ + TenantID: tenantID, + Title: "Skill " + operation, + Description: "Tenant skill image maintenance", + SandboxConfigID: configID, + }) + if err != nil { + return nil, nil, fmt.Errorf("create %s session: %w", operation, err) + } + if sess == nil { + return nil, nil, fmt.Errorf("create %s session returned nil", operation) + } + if s.sandboxes == nil { + return nil, nil, errors.New("sandbox resolver is not configured") + } + mgr, err := s.sandboxes.Resolve(ctx, tenantID, configID) + if err != nil { + return nil, nil, fmt.Errorf("resolve sandbox config: %w", err) + } + if mgr == nil { + return nil, nil, errors.New("sandbox resolver returned nil manager") + } + return sess, mgr, nil +} + +func (s *TenantSkillService) releaseSandbox(ctx context.Context, mgr sandbox.Manager, sessionID string) { + destroyer, ok := mgr.(sandbox.SessionDestroyer) + if !ok { + return + } + if err := destroyer.DestroySession(ctx, sessionID); err != nil { + logger.Warnf(ctx, "[skill] destroy install sandbox for session %s failed: %v", sessionID, err) + } +} + +func (s *TenantSkillService) createSnapshot( + ctx context.Context, mgr sandbox.Manager, sessionID, name string, +) (sandbox.RemoteSnapshotRef, error) { + snapshots, ok := mgr.(sandbox.RemoteSnapshotManager) + if !ok { + return sandbox.RemoteSnapshotRef{}, errors.New("sandbox backend does not support snapshots") + } + ref, err := snapshots.CreateSnapshot(ctx, sessionID, name) + if err != nil { + return sandbox.RemoteSnapshotRef{}, fmt.Errorf("create snapshot: %w", err) + } + if strings.TrimSpace(ref.ID) == "" { + return sandbox.RemoteSnapshotRef{}, errors.New("create snapshot returned empty id") + } + return ref, nil +} + +func (s *TenantSkillService) deleteSnapshotBestEffort( + ctx context.Context, mgr sandbox.Manager, snapshotID string, +) { + snapshots, ok := mgr.(sandbox.RemoteSnapshotManager) + if !ok { + return + } + if err := snapshots.DeleteSnapshot(ctx, snapshotID); err != nil { + logger.Warnf(ctx, "[skill] delete orphan snapshot %s failed: %v", snapshotID, err) + } +} + +// switchImagePointer is the single DB write that makes the new snapshot the +// image every future session boots from. +// +// The config is re-read here rather than reused from the read at the top of +// runInstall, which happened minutes and one whole agent conversation ago. The +// repository Update overwrites name, description, sandbox type and the entire +// config blob, and config edits are serialised by the config service's cordon +// rather than by this task's lock โ€” so writing back the stale entity would +// silently revert an admin's credential rotation. It would also compute the +// fingerprint from the stale credentials, and a pointer whose fingerprint does +// not match the live ones is discarded at session start: the install would +// report success while every session kept booting the base template. +func (s *TenantSkillService) switchImagePointer( + ctx context.Context, + tenantID uint64, + configID string, + snapshotID 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 install", configID) + } + + fingerprint := skillOwnerFingerprint(cfgEntity.Config) + if strings.TrimSpace(fingerprint) == "" { + // An empty fingerprint is treated as "keep the base template" when a + // session resolves the image, so persisting one would mark the skill + // ready while no sandbox ever sees it. + return fmt.Errorf( + "sandbox config %s has no usable owner fingerprint for a skill image", configID, + ) + } + + // Only the SkillImage portion is touched; everything else in the entity is + // whatever the latest read says it is. + cfgEntity.Config.SkillImage = &types.SkillImageConfig{ + SnapshotID: snapshotID, + Generation: generation, + BuiltAt: s.now(), + BaseTemplateID: effectiveBaseTemplate(cfgEntity), + OwnerFingerprint: fingerprint, + } + cfgEntity.TenantID = tenantID + return s.configs.Update(ctx, cfgEntity) +} + +// effectiveBaseTemplate returns the template the image chain grew from. Once +// recorded it is never re-derived, because the config's own template field is +// overwritten with the snapshot ID whenever a session resolves the config. +func effectiveBaseTemplate(cfgEntity *types.TenantSandboxConfigEntity) string { + if cfgEntity == nil || cfgEntity.Config == nil { + return "" + } + if image := cfgEntity.Config.SkillImage; image != nil && + strings.TrimSpace(image.BaseTemplateID) != "" { + return image.BaseTemplateID + } + return currentBaseTemplate(cfgEntity.Config) +} + +func (s *TenantSkillService) markPreviousSnapshotsSuperseded( + ctx context.Context, tenantID uint64, configID, currentRowID string, +) { + rows, err := s.skills.ListSnapshotsByConfig(ctx, tenantID, configID) + if err != nil { + logger.Warnf(ctx, "[skill] list snapshots for supersede failed: %v", err) + return + } + for _, row := range rows { + if row == nil || row.ID == currentRowID || row.State != types.SkillSnapshotStateActive { + continue + } + if err := s.skills.MarkSnapshotState( + ctx, tenantID, row.ID, types.SkillSnapshotStateSuperseded, row.SnapshotID, + ); err != nil { + logger.Warnf(ctx, "[skill] mark snapshot %s superseded failed: %v", row.ID, err) + } + } +} + +func currentGeneration(cfgEntity *types.TenantSandboxConfigEntity) int { + if cfgEntity == nil || cfgEntity.Config == nil || cfgEntity.Config.SkillImage == nil { + return 0 + } + return cfgEntity.Config.SkillImage.Generation +} + +func currentSnapshotID(cfgEntity *types.TenantSandboxConfigEntity) string { + if cfgEntity == nil || cfgEntity.Config == nil || cfgEntity.Config.SkillImage == nil { + return "" + } + return cfgEntity.Config.SkillImage.SnapshotID +} + +func shortID(id string) string { + trimmed := strings.ReplaceAll(strings.TrimSpace(id), "-", "") + if len(trimmed) > 8 { + return trimmed[:8] + } + if trimmed == "" { + return "config" + } + return trimmed +} + +func buildInstallPrompt(skillDir string, bundle *SkillBundle, uvAvailable bool) string { + skillMD := "" + if bundle != nil { + skillMD = string(bundle.Files["SKILL.md"]) + } + return fmt.Sprintf(`Install this WeKnora skill into the sandbox image. + +Skill directory: %s +uv available: %t + +Hard requirements: +- Install dependencies for exactly this one skill. +- Python dependencies must go into %s/.venv. Do not install into system Python. +- Node dependencies must go under %s/node_modules. Do not install global packages unless no local alternative exists. +- Use shell_exec only. You may set work_dir to %s. +- When finished, report what you installed and any global/system packages you changed. + +SKILL.md: +%s +`, skillDir, uvAvailable, skillDir, skillDir, skillDir, skillMD) +} + +func primaryEntryScript(bundle *SkillBundle) string { + if bundle == nil { + return "" + } + preferred := []string{".py", ".js", ".mjs", ".sh"} + for _, suffix := range preferred { + for rel := range bundle.Files { + if strings.HasPrefix(rel, "scripts/") && strings.HasSuffix(rel, suffix) { + return rel + } + } + } + return "" +} + +func (s *TenantSkillService) probeUv(ctx context.Context, mgr sandbox.Manager, sessionID string) bool { + _, err := s.execInstall(ctx, mgr, sessionID, "uv --version") + return err == nil +} + +// installerAgentDefaults returns the platform's own definition of the installer +// agent. It is deliberately not the record GetAgentByID serves, which a tenant +// can overwrite. When the registry has not been loaded, an ID-only agent yields +// the hardcoded platform defaults below rather than improvised settings. +func installerAgentDefaults(ctx context.Context, tenantID uint64) *types.CustomAgent { + if defaults := types.GetBuiltinAgentWithContext( + ctx, types.BuiltinSkillInstallerID, tenantID, + ); defaults != nil { + return defaults + } + return &types.CustomAgent{ID: types.BuiltinSkillInstallerID} +} + +// installerAgentConfig builds the config the install session runs under. +// +// `defaults` must be the built-in registry entry, never the tenant-editable +// record. Everything that decides what the root shell is asked to do โ€” system +// prompt, tool whitelist, iteration budget โ€” is fixed by the platform here. +// A tenant can edit any built-in agent's stored Config, and "can edit an +// agent" must not become "can script a root shell whose output is baked into +// the shared sandbox image": that is a different permission from "can upload a +// skill". The model is the one choice still taken from the stored record, in +// resolveInstallerModel. +func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.AgentConfig { + cfg := &types.AgentConfig{ + MaxIterations: 30, + AllowedTools: []string{tools.ToolShellExec}, + Temperature: 0.2, + WebSearchEnabled: false, + SandboxConfigID: configID, + } + if defaults == nil { + return cfg + } + // The installer's shell_exec must run as root inside the skills image + // root; the prompt below asks for exactly that. The grant is keyed on the + // built-in agent ID and refused for anything else. + cfg.EnableSkillInstallMode(defaults.ID) + custom := defaults.Config + cfg.MaxIterations = custom.MaxIterations + if cfg.MaxIterations == 0 { + cfg.MaxIterations = 30 + } + cfg.AllowedTools = append([]string(nil), custom.AllowedTools...) + if len(cfg.AllowedTools) == 0 { + cfg.AllowedTools = []string{tools.ToolShellExec} + } + cfg.Temperature = custom.Temperature + cfg.SystemPrompt = custom.SystemPrompt + cfg.UseCustomSystemPrompt = custom.SystemPrompt != "" + cfg.WebSearchEnabled = custom.WebSearchEnabled + cfg.WebSearchMaxResults = custom.WebSearchMaxResults + cfg.MultiTurnEnabled = custom.MultiTurnEnabled + cfg.LLMCallTimeout = custom.LLMCallTimeout + return cfg +} + +// resolveInstallerModel prefers the model the installer agent is configured +// with. Whoever set that model chose it for this job; the workspace default is +// only the fallback for a record that names no model or names one this +// workspace can no longer resolve. +func (s *TenantSkillService) resolveInstallerModel( + ctx context.Context, tenantID uint64, agent *types.CustomAgent, +) (chat.Chat, error) { + if s.models == nil { + return nil, errors.New("model service is not configured") + } + if agent != nil { + if modelID := strings.TrimSpace(agent.Config.ModelID); modelID != "" { + model, err := s.models.GetChatModel(ctx, modelID) + if err == nil && model != nil { + return model, nil + } + logger.Warnf(ctx, + "[skill] installer agent model %s is unusable (%v); falling back to the workspace default", + modelID, err) + } + } + models, err := s.models.ListModels(ctx) + if err != nil { + return nil, fmt.Errorf("list models for installer: %w", err) + } + for _, model := range models { + if model != nil && model.Type == types.ModelTypeKnowledgeQA && + model.Status == types.ModelStatusActive && model.IsDefault { + return s.models.GetChatModel(ctx, model.ID) + } + } + for _, model := range models { + if model != nil && model.Type == types.ModelTypeKnowledgeQA && + model.Status == types.ModelStatusActive { + return s.models.GetChatModel(ctx, model.ID) + } + } + return nil, fmt.Errorf("workspace %d has no active chat model for skill installer", tenantID) +} + +func (s *TenantSkillService) execSmoke( + ctx context.Context, mgr sandbox.Manager, sessionID, skillDir, scriptPath string, +) (*sandbox.ExecuteResult, error) { + executor, err := installExecutor(mgr) + if err != nil { + return nil, err + } + // The interpreter argv must survive intact. For Python it is + // /bin/sh -c "