chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+323
View File
@@ -0,0 +1,323 @@
package adapter
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"academy/internal/localsandbox"
"academy/internal/logger"
"academy/internal/sandbox"
)
// Adapter presents the local sandbox through the session-scoped capability
// interfaces the agent already consumes. It *is* the session shell, file
// store, and layout provider — not a wrapper around a second remote path.
//
// File operations do NOT go through the OS sandbox: Academy itself is trusted
// and already holds the user's privileges, so putting it inside Seatbelt would
// only stop it reading its own database. They are bounded by PathGuard, which
// is derived from the same Policy the backend compiles.
//
// Adapter deliberately does NOT implement DestroySession: a host workspace is
// a real directory the user picked, often shared with other sessions, so
// tearing it down on chat delete has no safe meaning.
type Adapter struct {
svc *localsandbox.Service
}
// New wraps a localsandbox Service as the session-scoped Manager the agent uses.
func New(svc *localsandbox.Service) *Adapter { return &Adapter{svc: svc} }
// LocalSandboxService exposes the wrapped service for desktop composition
// (local shell jobs). Not part of the remote-facing capability interfaces.
func (a *Adapter) LocalSandboxService() *localsandbox.Service {
if a == nil {
return nil
}
return a.svc
}
// maxListSessionFiles stops WalkDir once the listing is as large as the
// list_sandbox_files tool will ever keep (500). The tool also truncates,
// but that is after the whole tree is already in memory.
const maxListSessionFiles = 500
var (
_ sandbox.Manager = (*Adapter)(nil)
_ sandbox.SessionCapabilityProvider = (*Adapter)(nil)
_ sandbox.SessionWorkspaceLayoutProvider = (*Adapter)(nil)
_ sandbox.SessionShellExecutor = (*Adapter)(nil)
_ sandbox.SessionFileStore = (*Adapter)(nil)
)
// GetType reports SandboxTypeHost.
func (a *Adapter) GetType() sandbox.SandboxType { return sandbox.SandboxTypeHost }
// GetSandbox is unused: host has no remote instance to expose.
func (a *Adapter) GetSandbox() sandbox.Sandbox { return nil }
// VersionsWorkspace is false on host: the workspace is the user's real
// directory and must not be auto-committed, even if this adapter is injected
// as the process-wide checkpoint runner.
func (a *Adapter) VersionsWorkspace(context.Context, string) bool { return false }
// Cleanup is a no-op; host holds no process-wide resources to tear down.
func (a *Adapter) Cleanup(context.Context) error { return nil }
// Execute is the legacy script entry point. The local sandbox exposes shell
// execution only, so callers must use ExecShellCommand.
func (a *Adapter) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
return nil, fmt.Errorf("localsandbox: script execution is not supported; use shell_exec")
}
// SessionShellExecutor returns the adapter when a service is wired.
func (a *Adapter) SessionShellExecutor() sandbox.SessionShellExecutor {
if a.svc == nil {
return nil
}
return a
}
// SessionFileStore returns the adapter when a service is wired.
func (a *Adapter) SessionFileStore() sandbox.SessionFileStore {
if a.svc == nil {
return nil
}
return a
}
// SessionWorkspaceLayout describes this session's host workspace. Tools bind
// the session ID before Description() so the model sees the real Root instead
// of the remote /workspace contract.
func (a *Adapter) SessionWorkspaceLayout(
ctx context.Context, sessionID string,
) (sandbox.WorkspaceLayout, error) {
if a == nil || a.svc == nil {
return sandbox.WorkspaceLayout{}, fmt.Errorf("localsandbox: session workspace is unavailable")
}
_, ws, err := a.svc.GuardForSession(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] layout session=%s: %v", sessionID, err)
return sandbox.WorkspaceLayout{}, err
}
layout := LayoutFor(ws)
logger.Debugf(ctx, "[LocalSandbox] layout session=%s root=%s", sessionID, layout.Root)
return layout, nil
}
// ExecShellCommand runs command under the OS sandbox for this session.
func (a *Adapter) ExecShellCommand(
ctx context.Context,
sessionID, command, workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error) {
res, err := a.svc.Run(ctx, localsandbox.RunRequest{
SessionID: sessionID,
Command: command,
WorkDir: workDir,
Timeout: timeout,
Env: env,
})
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] exec session=%s work_dir=%q: %v", sessionID, workDir, err)
return nil, err
}
return executeResult(ctx, sessionID, res), nil
}
func executeResult(ctx context.Context, sessionID string, res *localsandbox.RunResult) *sandbox.ExecuteResult {
out := &sandbox.ExecuteResult{
Stdout: res.Stdout,
Stderr: res.Stderr,
ExitCode: res.Exit.Code,
Duration: res.Exit.Duration,
Killed: res.Exit.Killed,
}
if res.Denial.IsDenied() {
// A denial is a normal, reportable outcome: the model must see why the
// command failed so it can choose a path inside the workspace.
logger.Warnf(ctx, "[LocalSandbox] exec denied session=%s reason=%d path=%q",
sessionID, res.Denial.Reason, res.Denial.Path)
out.Stderr += "\n[sandbox] denied by workspace policy"
}
return out
}
func (a *Adapter) guard(
ctx context.Context, sessionID string,
) (*localsandbox.PathGuard, localsandbox.Workspace, error) {
return a.svc.GuardForSession(ctx, sessionID)
}
// EnsureSessionDir creates dir inside the session workspace when the policy allows it.
func (a *Adapter) EnsureSessionDir(ctx context.Context, sessionID, dir string) error {
guard, ws, err := a.guard(ctx, sessionID)
if err != nil {
return err
}
unlock := a.svc.LockRoot(ws.Root)
defer unlock()
target := absoluteIn(ws.Root, dir)
if err := guard.MkdirAll(target, 0o755); err != nil {
if errors.Is(err, localsandbox.ErrPathDenied) {
logger.Warnf(ctx, "[LocalSandbox] mkdir denied session=%s path=%q: %v", sessionID, dir, err)
} else {
logger.Errorf(ctx, "[LocalSandbox] mkdir session=%s path=%s: %v", sessionID, target, err)
}
return err
}
logger.Debugf(ctx, "[LocalSandbox] mkdir session=%s path=%s", sessionID, target)
return nil
}
// ListSessionFiles walks dir under the session workspace, truncated at maxListSessionFiles.
func (a *Adapter) ListSessionFiles(
ctx context.Context, sessionID, dir string,
) ([]sandbox.RemoteDirEntry, error) {
guard, ws, err := a.guard(ctx, sessionID)
if err != nil {
return nil, err
}
resolved, err := guard.CheckRead(absoluteIn(ws.Root, dir))
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] list denied session=%s path=%q: %v", sessionID, dir, err)
return nil, err
}
logger.Debugf(ctx, "[LocalSandbox] list session=%s path=%s", sessionID, resolved)
var out []sandbox.RemoteDirEntry
err = filepath.WalkDir(resolved, func(p string, d os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() {
return nil
}
if len(out) >= maxListSessionFiles {
return filepath.SkipAll
}
info, err := d.Info()
if err != nil {
return err
}
out = append(out, sandbox.RemoteDirEntry{
Name: d.Name(),
Path: p,
Type: sandbox.RemoteEntryFile,
Size: info.Size(),
ModTime: info.ModTime(),
})
return nil
})
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] list session=%s path=%s: %v", sessionID, resolved, err)
return nil, err
}
logger.Debugf(ctx, "[LocalSandbox] listed session=%s path=%s entries=%d", sessionID, resolved, len(out))
return out, nil
}
// StatSessionFile returns metadata for p when the policy allows reading it.
func (a *Adapter) StatSessionFile(
ctx context.Context, sessionID, p string,
) (*sandbox.RemoteStatEntry, error) {
guard, ws, err := a.guard(ctx, sessionID)
if err != nil {
return nil, err
}
target := absoluteIn(ws.Root, p)
info, err := guard.Lstat(target)
if err != nil {
if errors.Is(err, localsandbox.ErrPathDenied) {
logger.Warnf(ctx, "[LocalSandbox] stat denied session=%s path=%q: %v", sessionID, p, err)
}
return nil, err
}
entryType := sandbox.RemoteEntryFile
if info.IsDir() {
entryType = sandbox.RemoteEntryDir
}
return &sandbox.RemoteStatEntry{
Path: target, Type: entryType, Size: info.Size(), ModTime: info.ModTime(),
}, nil
}
// ReadSessionFile returns the contents of p when the policy allows reading it.
func (a *Adapter) ReadSessionFile(ctx context.Context, sessionID, p string) ([]byte, error) {
guard, ws, err := a.guard(ctx, sessionID)
if err != nil {
return nil, err
}
target := absoluteIn(ws.Root, p)
data, err := guard.ReadFile(target)
if err != nil {
if errors.Is(err, localsandbox.ErrPathDenied) {
logger.Warnf(ctx, "[LocalSandbox] read denied session=%s path=%q: %v", sessionID, p, err)
}
return nil, err
}
logger.Debugf(ctx, "[LocalSandbox] read session=%s path=%s", sessionID, target)
return data, nil
}
// WriteSessionWorkspaceFile writes content to p when the policy allows it.
func (a *Adapter) WriteSessionWorkspaceFile(
ctx context.Context, sessionID, p string, content []byte,
) error {
guard, ws, err := a.guard(ctx, sessionID)
if err != nil {
return err
}
unlock := a.svc.LockRoot(ws.Root)
defer unlock()
target := absoluteIn(ws.Root, p)
if err := guard.WriteFile(target, content, 0o644); err != nil {
if errors.Is(err, localsandbox.ErrPathDenied) {
logger.Warnf(ctx, "[LocalSandbox] write denied session=%s path=%q: %v", sessionID, p, err)
} else {
logger.Errorf(ctx, "[LocalSandbox] write session=%s path=%s: %v", sessionID, target, err)
}
return err
}
logger.Infof(ctx, "[LocalSandbox] wrote session=%s path=%s bytes=%d", sessionID, target, len(content))
return nil
}
// WriteSessionWorkspaceFiles writes each file in turn, stopping at the first error.
func (a *Adapter) WriteSessionWorkspaceFiles(
ctx context.Context, sessionID string, files []sandbox.SessionWorkspaceFile,
) error {
for _, f := range files {
if err := a.WriteSessionWorkspaceFile(ctx, sessionID, f.Path, f.Content); err != nil {
return err
}
}
return nil
}
// WriteSessionInputFile is a no-op error on host: the work directory is the
// user's own folder, and attachments are not copied into it.
func (a *Adapter) WriteSessionInputFile(
context.Context, string, string, []byte,
) error {
return errNoHostAttachmentDir
}
// RemoveSessionInputPath is unused on host: there is no attachment directory to clean.
func (a *Adapter) RemoveSessionInputPath(context.Context, string, string) error {
return errNoHostAttachmentDir
}
var errNoHostAttachmentDir = fmt.Errorf("localsandbox: this workspace has no attachment directory")
func absoluteIn(root, p string) string {
if filepath.IsAbs(p) {
return filepath.Clean(p)
}
return filepath.Join(root, p)
}
@@ -0,0 +1,294 @@
package adapter
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/localsandbox"
"academy/internal/sandbox"
)
func TestAdapterSatisfiesCapabilityInterfaces(t *testing.T) {
var a any = New(nil)
_, ok := a.(sandbox.Manager)
require.True(t, ok)
provider, ok := a.(sandbox.SessionCapabilityProvider)
require.True(t, ok)
require.NotNil(t, provider)
}
func TestAdapterReportsHostType(t *testing.T) {
require.Equal(t, sandbox.SandboxTypeHost, New(nil).GetType())
}
func TestAdapterDoesNotVersionWorkspace(t *testing.T) {
require.False(t, New(nil).VersionsWorkspace(context.Background(), "s1"))
}
// Capabilities the local sandbox genuinely lacks must be absent rather than
// stubbed: a fake PTY is worse than none.
func TestAdapterDoesNotAdvertiseTerminalOrDesktop(t *testing.T) {
var a any = New(nil)
_, hasTerminal := a.(sandbox.SessionTerminalProvider)
require.False(t, hasTerminal)
_, hasDesktop := a.(sandbox.SessionDesktopProvider)
require.False(t, hasDesktop)
}
func TestAdapterDoesNotImplementSessionDestroyer(t *testing.T) {
var a any = New(nil)
_, ok := a.(sandbox.SessionDestroyer)
require.False(t, ok)
}
// Deleting a chat session must never delete the user's files. The host adapter
// therefore must not implement SessionDestroyer: destroyBoundSandbox resolves
// the host manager for unpinned sessions and would call it.
func TestHostAdapterIsNotASessionDestroyer(t *testing.T) {
var a any = New(nil)
_, isDestroyer := a.(interface {
DestroySession(context.Context, string) error
})
require.False(t, isDestroyer,
"a host workspace is the user's own directory; deleting a session must not delete it")
}
func TestAdapterDoesNotImplementTurnHolderOrInteractiveManagers(t *testing.T) {
var a any = New(nil)
_, hasTurn := a.(sandbox.SessionTurnHolder)
require.False(t, hasTurn)
_, hasTerminal := a.(sandbox.SessionTerminalManager)
require.False(t, hasTerminal)
_, hasDesktop := a.(sandbox.SessionDesktopManager)
require.False(t, hasDesktop)
}
func TestLayoutForProjectWorkspace(t *testing.T) {
ws := localsandbox.Workspace{
Kind: localsandbox.WorkspaceProject,
Root: "/Users/dev/My Project",
}
l := LayoutFor(ws)
require.Equal(t, sandbox.WorkspaceOriginHost, l.Origin)
require.Equal(t, ws.Root, l.Root)
require.Equal(t, []string{ws.Root}, l.WriteRoots)
require.Equal(t, []string{ws.Root}, l.ReadRoots)
require.Empty(t, l.InputDir)
require.Empty(t, l.OutputDir)
}
func TestLayoutForReadRootsAreTheWorkspace(t *testing.T) {
l := LayoutFor(localsandbox.Workspace{Root: "/Users/dev/proj"})
require.Equal(t, []string{"/Users/dev/proj"}, l.ReadRoots)
}
func TestLayoutForHintIsTheWorkspaceRoot(t *testing.T) {
l := LayoutFor(localsandbox.Workspace{Root: "/Users/dev/My Project"})
require.Equal(t, l.Root, l.Hint)
}
// A session workspace keeps output inside the tree, so Root alone is writable.
func TestLayoutForSessionWorkspaceHasNoInputOrOutput(t *testing.T) {
l := LayoutFor(localsandbox.Workspace{
Kind: localsandbox.WorkspaceSession,
Root: "/Users/dev/Documents/Academy/s1",
})
require.Equal(t, []string{"/Users/dev/Documents/Academy/s1"}, l.WriteRoots)
require.Empty(t, l.InputDir)
require.Empty(t, l.OutputDir)
}
func TestAdapterProvidesWorkspaceLayout(t *testing.T) {
var a any = New(nil)
_, ok := a.(sandbox.SessionWorkspaceLayoutProvider)
require.True(t, ok)
}
func TestAdapterIsTheSessionShellAndFileStore(t *testing.T) {
a := New(testService(t, &stubBackend{exit: localsandbox.ExitStatus{Code: 0}}))
require.Equal(t, a, a.SessionShellExecutor())
require.Equal(t, a, a.SessionFileStore())
}
func TestAdapterNilServiceAdvertisesNoShellOrFiles(t *testing.T) {
a := New(nil)
require.Nil(t, a.SessionShellExecutor())
require.Nil(t, a.SessionFileStore())
}
// Description() used to look up the layout with sessionID="". Host adapters
// still refuse that so unbound tools fall back to remote copy instead of
// stuffing an absolute home path into Hint.
func TestAdapterSessionWorkspaceLayoutRejectsEmptySessionID(t *testing.T) {
a := New(testService(t, &stubBackend{}))
layout, err := a.SessionWorkspaceLayout(context.Background(), "")
require.Error(t, err)
require.Empty(t, layout.Root)
require.NotContains(t, layout.Hint, "/Users")
}
func TestAdapterSessionWorkspaceLayoutErrorsWithoutService(t *testing.T) {
_, err := New(nil).SessionWorkspaceLayout(context.Background(), "")
require.Error(t, err)
}
func TestAdapterSessionWorkspaceLayoutMapsResolvedWorkspace(t *testing.T) {
a := New(testService(t, &stubBackend{}))
layout, err := a.SessionWorkspaceLayout(context.Background(), "s1")
require.NoError(t, err)
require.NotEmpty(t, layout.Root)
require.Equal(t, []string{layout.Root}, layout.WriteRoots)
require.Equal(t, layout.Root, layout.ReadRoots[len(layout.ReadRoots)-1])
require.Equal(t, layout.Hint, LayoutFor(localsandbox.Workspace{Root: layout.Root}).Hint)
require.Equal(t, layout.Root, layout.Hint)
}
func TestAdapterWritesAndReadsWorkspaceFile(t *testing.T) {
a := New(testService(t, &stubBackend{}))
ctx := context.Background()
require.NoError(t, a.WriteSessionWorkspaceFile(ctx, "s1", "notes.md", []byte("hello")))
got, err := a.ReadSessionFile(ctx, "s1", "notes.md")
require.NoError(t, err)
require.Equal(t, []byte("hello"), got)
err = a.WriteSessionWorkspaceFile(ctx, "s1", "/etc/passwd", []byte("nope"))
require.ErrorIs(t, err, localsandbox.ErrPathDenied)
}
func TestAdapterWriteSessionInputFileIsDisabled(t *testing.T) {
a := New(testService(t, &stubBackend{}))
err := a.WriteSessionInputFile(context.Background(), "s1", "report.pdf", []byte("escape"))
require.ErrorIs(t, err, errNoHostAttachmentDir)
}
func TestAdapterSessionWorkspaceHasNoAttachmentDir(t *testing.T) {
a := New(testService(t, &stubBackend{}))
ctx := context.Background()
layout, err := a.SessionWorkspaceLayout(ctx, "s1")
require.NoError(t, err)
require.Empty(t, layout.InputDir)
require.Empty(t, layout.OutputDir)
dest := filepath.Join(layout.Root, "stolen.pdf")
err = a.WriteSessionInputFile(ctx, "s1", dest, []byte("nope"))
require.ErrorIs(t, err, errNoHostAttachmentDir)
_, statErr := os.Stat(dest)
require.Error(t, statErr)
}
func TestAdapterExecShellCommandMapsResult(t *testing.T) {
backend := &stubBackend{
stdout: "hello\n",
exit: localsandbox.ExitStatus{Code: 0, Duration: 12 * time.Millisecond},
}
a := New(testService(t, backend))
res, err := a.ExecShellCommand(context.Background(), "s1", "echo hello", "", 0, nil)
require.NoError(t, err)
require.Equal(t, "hello\n", res.Stdout)
require.Equal(t, 0, res.ExitCode)
require.Equal(t, 12*time.Millisecond, res.Duration)
require.False(t, res.Killed)
}
func TestAdapterExecShellCommandAnnotatesDenial(t *testing.T) {
backend := &stubBackend{
stderr: "touch: /etc/x: Operation not permitted",
exit: localsandbox.ExitStatus{Code: 1},
}
a := New(testService(t, backend))
res, err := a.ExecShellCommand(context.Background(), "s1", "touch /etc/x", "", 0, nil)
require.NoError(t, err)
require.Equal(t, 1, res.ExitCode)
require.Contains(t, res.Stderr, "[sandbox] denied by workspace policy")
}
func TestAdapterListSessionFilesStopsWalkingAtCap(t *testing.T) {
a := New(testService(t, &stubBackend{}))
ctx := context.Background()
layout, err := a.SessionWorkspaceLayout(ctx, "s1")
require.NoError(t, err)
bulk := filepath.Join(layout.Root, "bulk")
require.NoError(t, os.MkdirAll(bulk, 0o755))
for i := 0; i < maxListSessionFiles+40; i++ {
require.NoError(t, os.WriteFile(filepath.Join(bulk, fmt.Sprintf("f%04d.txt", i)), []byte("x"), 0o644))
}
entries, err := a.ListSessionFiles(ctx, "s1", ".")
require.NoError(t, err)
require.Equal(t, maxListSessionFiles, len(entries))
}
type stubProjects struct{}
func (stubProjects) ProjectDirForSession(context.Context, string) (string, bool, error) {
return "", false, nil
}
func testService(t *testing.T, backend localsandbox.Backend) *localsandbox.Service {
t.Helper()
base := t.TempDir()
home := filepath.Join(base, "home")
appData := filepath.Join(home, "App Support", "Academy Lite")
require.NoError(t, os.MkdirAll(home, 0o755))
resolver := localsandbox.NewWorkspaceResolver(localsandbox.DirLayout{
SessionRoot: filepath.Join(home, "Documents", "Academy"),
}, stubProjects{})
return localsandbox.NewService(backend, resolver, localsandbox.NewPolicyBuilder(home, appData), nil)
}
type stubBackend struct {
stdout string
stderr string
exit localsandbox.ExitStatus
available error
}
func (s *stubBackend) Name() string { return "stub" }
func (s *stubBackend) Available() error { return s.available }
func (s *stubBackend) EnsureReady(context.Context) error { return nil }
func (s *stubBackend) TearDown(context.Context) error { return nil }
type stubPrepared struct{ fp string }
func (p stubPrepared) Fingerprint() string { return p.fp }
func (p stubPrepared) Close() error { return nil }
func (s *stubBackend) Prepare(_ context.Context, p localsandbox.Policy) (localsandbox.Prepared, error) {
return stubPrepared{fp: p.Fingerprint()}, nil
}
func (s *stubBackend) Spawn(
_ context.Context, _ localsandbox.Prepared, _ localsandbox.Command,
) (localsandbox.Process, error) {
return &stubProcess{
stdout: io.NopCloser(bytes.NewBufferString(s.stdout)),
stderr: io.NopCloser(bytes.NewBufferString(s.stderr)),
exit: s.exit,
}, nil
}
type stubProcess struct {
stdout io.ReadCloser
stderr io.ReadCloser
exit localsandbox.ExitStatus
}
func (p *stubProcess) Stdout() io.Reader { return p.stdout }
func (p *stubProcess) Stderr() io.Reader { return p.stderr }
func (p *stubProcess) Kill() error { return nil }
func (p *stubProcess) PID() int { return 1 }
func (p *stubProcess) Wait(context.Context) (localsandbox.ExitStatus, error) {
return p.exit, nil
}
+190
View File
@@ -0,0 +1,190 @@
package adapter
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"sync"
"academy/internal/localsandbox"
"academy/internal/logger"
"academy/internal/sandbox"
)
// InstallRunner is the slice of localsandbox.Service an install needs.
type InstallRunner interface {
RunWithPolicy(
ctx context.Context, policy localsandbox.Policy, req localsandbox.RunRequest,
) (*localsandbox.RunResult, error)
}
// InstallPolicies builds the install-only policy for one version directory.
type InstallPolicies interface {
BuildInstall(dir string) (localsandbox.Policy, error)
}
// InstallManager is the sandbox the built-in skill installer agent talks to on
// Lite. Each maintenance session is bound to one version directory; an
// unbound session has no scope and every call fails.
//
// It deliberately does not implement SessionCapabilityProvider: chat agents
// must never resolve to a shell whose network is open.
type InstallManager struct {
runner InstallRunner
policies InstallPolicies
mu sync.Mutex
scopes map[string]string
}
var (
_ sandbox.Manager = (*InstallManager)(nil)
_ sandbox.SessionInstallCapabilityProvider = (*InstallManager)(nil)
_ sandbox.SessionInstallShellExecutor = (*InstallManager)(nil)
_ sandbox.SessionFileReader = (*InstallManager)(nil)
)
var errNoInstallScope = errors.New("localsandbox: this session is not a skill install")
// NewInstallManager wires the install sandbox.
func NewInstallManager(runner InstallRunner, policies InstallPolicies) *InstallManager {
return &InstallManager{runner: runner, policies: policies, scopes: map[string]string{}}
}
// Bind scopes sessionID to dir until release is called.
func (m *InstallManager) Bind(sessionID, dir string) func() {
m.mu.Lock()
m.scopes[sessionID] = filepath.Clean(dir)
m.mu.Unlock()
return func() {
m.mu.Lock()
delete(m.scopes, sessionID)
m.mu.Unlock()
}
}
func (m *InstallManager) scope(sessionID string) (string, localsandbox.Policy, error) {
m.mu.Lock()
dir, ok := m.scopes[sessionID]
m.mu.Unlock()
if !ok {
return "", localsandbox.Policy{}, errNoInstallScope
}
policy, err := m.policies.BuildInstall(dir)
if err != nil {
return "", localsandbox.Policy{}, err
}
return dir, policy, nil
}
// GetType reports host so logs and type switches read naturally.
func (m *InstallManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeHost }
// GetSandbox is unused: there is no remote instance.
func (m *InstallManager) GetSandbox() sandbox.Sandbox { return nil }
// Cleanup holds nothing process-wide.
func (m *InstallManager) Cleanup(context.Context) error { return nil }
// Execute is the legacy script entry point, which installs never use.
func (m *InstallManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
return nil, fmt.Errorf("localsandbox: script execution is not supported; use shell_exec")
}
// SessionInstallShellExecutor exposes the install shell.
func (m *InstallManager) SessionInstallShellExecutor() sandbox.SessionInstallShellExecutor { return m }
// ExecShellCommandWithOptions runs one installer command in the bound
// version directory. AsRoot and AllowSkillsRoot have no meaning here: the
// command runs as the desktop user and may write only that directory.
func (m *InstallManager) ExecShellCommandWithOptions(
ctx context.Context, sessionID, command string, opts sandbox.ShellExecOptions,
) (*sandbox.ExecuteResult, error) {
dir, policy, err := m.scope(sessionID)
if err != nil {
return nil, err
}
workDir := strings.TrimSpace(opts.WorkDir)
if workDir == sandbox.SessionWorkspaceRoot {
workDir = ""
}
res, err := m.runner.RunWithPolicy(ctx, policy, localsandbox.RunRequest{
SessionID: sessionID,
Command: command,
WorkDir: workDir,
Timeout: opts.Timeout,
Env: installEnv(dir, opts.Env),
})
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] install exec session=%s dir=%s: %v", sessionID, dir, err)
return nil, err
}
return executeResult(ctx, sessionID, res), nil
}
// installEnv points package caches inside dir: the default cache locations
// under the home directory are not writable to the install policy.
func installEnv(dir string, extra map[string]string) map[string]string {
cache := filepath.Join(dir, ".academy", "cache")
env := make(map[string]string, len(extra)+4)
for k, v := range extra {
env[k] = v
}
env["UV_CACHE_DIR"] = filepath.Join(cache, "uv")
env["PIP_CACHE_DIR"] = filepath.Join(cache, "pip")
env["npm_config_cache"] = filepath.Join(cache, "npm")
env["ACADEMY_SKILL_DIR"] = dir
return env
}
func (m *InstallManager) guard(sessionID string) (*localsandbox.PathGuard, string, error) {
dir, policy, err := m.scope(sessionID)
if err != nil {
return nil, "", err
}
return localsandbox.NewPathGuard(policy), dir, nil
}
// StatSessionFile returns metadata for p inside the version directory.
func (m *InstallManager) StatSessionFile(
_ context.Context, sessionID, p string,
) (*sandbox.RemoteStatEntry, error) {
guard, dir, err := m.guard(sessionID)
if err != nil {
return nil, err
}
target := absoluteIn(dir, p)
info, err := guard.Lstat(target)
if err != nil {
return nil, err
}
entryType := sandbox.RemoteEntryFile
if info.IsDir() {
entryType = sandbox.RemoteEntryDir
}
return &sandbox.RemoteStatEntry{Path: target, Type: entryType, Size: info.Size(), ModTime: info.ModTime()}, nil
}
// ReadSessionFile reads p inside the version directory.
func (m *InstallManager) ReadSessionFile(_ context.Context, sessionID, p string) ([]byte, error) {
guard, dir, err := m.guard(sessionID)
if err != nil {
return nil, err
}
return guard.ReadFile(absoluteIn(dir, p))
}
// WriteSessionFile writes p inside the version directory, creating parents.
func (m *InstallManager) WriteSessionFile(_ context.Context, sessionID, p string, content []byte) error {
guard, dir, err := m.guard(sessionID)
if err != nil {
return err
}
target := absoluteIn(dir, p)
if err := guard.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
return guard.WriteFile(target, content, 0o644)
}
@@ -0,0 +1,96 @@
package adapter
import (
"context"
"os"
"path/filepath"
"testing"
"academy/internal/localsandbox"
"academy/internal/sandbox"
"github.com/stretchr/testify/require"
)
type recordingInstallRunner struct {
policy localsandbox.Policy
req localsandbox.RunRequest
}
func (r *recordingInstallRunner) RunWithPolicy(
_ context.Context, p localsandbox.Policy, req localsandbox.RunRequest,
) (*localsandbox.RunResult, error) {
r.policy, r.req = p, req
return &localsandbox.RunResult{Stdout: "ok"}, nil
}
type dirInstallPolicies struct{}
func (dirInstallPolicies) BuildInstall(dir string) (localsandbox.Policy, error) {
return localsandbox.Policy{
Cwd: dir,
WritableRoots: []localsandbox.WritableRoot{{Path: dir}},
Network: localsandbox.NetworkUnrestricted,
}, nil
}
func installFixture(t *testing.T) (*InstallManager, *recordingInstallRunner, string) {
t.Helper()
dir := filepath.Join(t.TempDir(), "skills", ".versions", "pdf-1")
require.NoError(t, os.MkdirAll(dir, 0o755))
runner := &recordingInstallRunner{}
return NewInstallManager(runner, dirInstallPolicies{}), runner, dir
}
func TestInstallManagerRefusesUnboundSession(t *testing.T) {
m, _, _ := installFixture(t)
_, err := m.ExecShellCommandWithOptions(context.Background(), "s1", "ls", sandbox.ShellExecOptions{})
require.Error(t, err)
_, err = m.ReadSessionFile(context.Background(), "s1", "SKILL.md")
require.Error(t, err)
}
func TestInstallManagerRunsInBoundVersionDir(t *testing.T) {
m, runner, dir := installFixture(t)
release := m.Bind("s1", dir)
res, err := m.ExecShellCommandWithOptions(context.Background(), "s1", "uv venv --seed .venv",
sandbox.ShellExecOptions{WorkDir: sandbox.SessionWorkspaceRoot, AsRoot: true, Env: map[string]string{"X": "1"}})
require.NoError(t, err)
require.Equal(t, "ok", res.Stdout)
require.Equal(t, dir, runner.policy.Cwd)
require.Empty(t, runner.req.WorkDir, "/workspace means the version dir on host")
require.Equal(t, filepath.Join(dir, ".academy", "cache", "uv"), runner.req.Env["UV_CACHE_DIR"])
require.Equal(t, filepath.Join(dir, ".academy", "cache", "pip"), runner.req.Env["PIP_CACHE_DIR"])
require.Equal(t, filepath.Join(dir, ".academy", "cache", "npm"), runner.req.Env["npm_config_cache"])
require.Equal(t, dir, runner.req.Env["ACADEMY_SKILL_DIR"])
require.Equal(t, "1", runner.req.Env["X"])
release()
_, err = m.ExecShellCommandWithOptions(context.Background(), "s1", "ls", sandbox.ShellExecOptions{})
require.Error(t, err)
}
func TestInstallManagerFilesStayInsideVersionDir(t *testing.T) {
m, _, dir := installFixture(t)
defer m.Bind("s1", dir)()
ctx := context.Background()
require.NoError(t, m.WriteSessionFile(ctx, "s1", "scripts/run.py", []byte("print(1)")))
got, err := m.ReadSessionFile(ctx, "s1", filepath.Join(dir, "scripts", "run.py"))
require.NoError(t, err)
require.Equal(t, "print(1)", string(got))
st, err := m.StatSessionFile(ctx, "s1", "scripts/run.py")
require.NoError(t, err)
require.Equal(t, int64(len("print(1)")), st.Size)
err = m.WriteSessionFile(ctx, "s1", filepath.Join(filepath.Dir(dir), "other-1", "x"), []byte("x"))
require.ErrorIs(t, err, localsandbox.ErrPathDenied)
}
func TestInstallManagerIsNotAChatBackend(t *testing.T) {
var m any = NewInstallManager(&recordingInstallRunner{}, dirInstallPolicies{})
_, isChat := m.(sandbox.SessionCapabilityProvider)
require.False(t, isChat, "the installer must never serve chat shell or file tools")
_, isDestroyer := m.(sandbox.SessionDestroyer)
require.False(t, isDestroyer)
require.Equal(t, sandbox.SandboxTypeHost, m.(sandbox.Manager).GetType())
}
+26
View File
@@ -0,0 +1,26 @@
// Package adapter connects the local sandbox to the agent's existing
// capability interfaces. It is the only package allowed to depend on both
// internal/localsandbox and internal/sandbox; neither of those depends on
// the other.
package adapter
import (
"academy/internal/localsandbox"
"academy/internal/sandbox"
)
// LayoutFor maps a resolved workspace onto the layout the agent tools consume.
//
// The tools enforce this as a convention (what the model is told, and what the
// scope errors say). The real enforcement for host file operations is
// PathGuard inside the adapter's SessionFileStore, so a mistake here cannot
// widen actual access.
func LayoutFor(ws localsandbox.Workspace) sandbox.WorkspaceLayout {
return sandbox.WorkspaceLayout{
Origin: sandbox.WorkspaceOriginHost,
Root: ws.Root,
WriteRoots: []string{ws.Root},
ReadRoots: []string{ws.Root},
Hint: ws.Root,
}
}