feat(sandbox): install skills on the Docker backend

Docker already ran session sandboxes, but skill install required snapshots
that only Cube and E2B advertised. Commit local skill images, boot sessions
from them, and show the skills step for Docker configs.
main
wizardchen 2026-08-25 20:54:18 +08:00 committed by lyingbug
parent a753a15354
commit ee9cf749f8
19 changed files with 789 additions and 54 deletions

View File

@ -159,10 +159,14 @@ WeKnora 自己跑在容器里时,要把 **实际的** docker socket 挂进 app
## 快照
「空间级管理沙箱装 skill → commit 成快照 → 会话从快照起容器 → 增量出下一版」这套流程在 Docker 上
是原生形态(容器 → 镜像),[PoC](./poc/docker-sandbox) 已经验证:commit 一个 140 MB 镜像约
0.5–1.0 秒,从快照冷启一个容器约 0.2 秒,v1→v2 增量正常。两个要注意的约束:镜像层上限 127,
长期增量要定期压平;快照是本机资产,多机部署必须推到 registry。这部分按计划在单独分支实现。
「空间级管理沙箱装 skill → commit 成快照 → 会话从快照起容器 → 增量出下一版」这套流程已经接入:
`DockerRemoteClient` 实现 `RemoteSnapshotManager`,`docker commit` 打出带
`com.weknora.sandbox.skill-snapshot` 标签的本地镜像(命名空间 `weknora-skill/`),
会话启动时用该镜像覆盖配置里的基础 image。安装器用 root `shell_exec` 写
`/opt/weknora/tenant/skills`,与 Cube / E2B 同一条技能安装链路。
两个要注意的约束:镜像层上限 127,长期增量要定期压平;快照是本机资产,多机部署必须推到 registry。
压平和跨 daemon 分发还不在这条路径里。
## 测试

View File

@ -532,10 +532,9 @@ const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() =
steps.push({ key: 'template', title: t('settings.sandbox.stepTemplate') })
}
steps.push({ key: 'runtime', title: t('settings.sandbox.stepRuntime') })
// Skills are baked into the config's snapshot image, which only the remote
// backends have. Docker and local configs therefore end at runtime rather
// than showing a step that could never do anything.
if (isRemoteBackend.value) {
// Skills are baked into the config's snapshot image. Local configs end
// at runtime rather than showing a step that could never do anything.
if (isRemoteBackend.value || backend.value === 'docker') {
steps.push({ key: 'skills', title: t('settings.sandbox.stepSkills') })
}
return steps

View File

@ -391,7 +391,10 @@ const deleteHint = computed(() =>
)
const runtimeTemplateId = computed(() => {
const cfg = props.record?.config
return cfg?.cube?.template_id?.trim() || cfg?.e2b?.template_id?.trim() || ''
return cfg?.cube?.template_id?.trim()
|| cfg?.e2b?.template_id?.trim()
|| cfg?.docker?.image?.trim()
|| ''
})
const hasSkillSnapshot = computed(() => Boolean(skillImage.value?.snapshot_id?.trim()))

View File

@ -264,10 +264,10 @@ const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)
// Skills are baked into the remote snapshot image. Docker and local configs
// have no skills step, so their cards stay a connection summary.
// Skills are baked into the snapshot image. Local configs have no skills
// step, so their cards stay a connection summary.
function supportsSkills(record: SandboxConfigRecord) {
return record.sandbox_type === 'cube' || record.sandbox_type === 'e2b'
return record.sandbox_type === 'cube' || record.sandbox_type === 'e2b' || record.sandbox_type === 'docker'
}
function skillsOf(record: SandboxConfigRecord): ConfigSkill[] | undefined {
@ -314,6 +314,8 @@ const cardMenu = (record: SandboxConfigRecord): CardMenuOption[] => {
]
if (record.sandbox_type === 'cube' || record.sandbox_type === 'e2b') {
options.push({ content: t('settings.sandbox.viewSandboxes'), value: 'inventory' })
}
if (supportsSkills(record)) {
options.push({ content: t('settings.sandbox.manageSkills'), value: 'skills' })
}
options.push({ content: t('common.delete'), value: 'delete', theme: 'error' })
@ -377,7 +379,7 @@ function openSkills(record: SandboxConfigRecord) {
showEditor.value = true
}
// Cube/e2b cards now lead with installed skills, so a click lands on that
// Cube/E2B/Docker cards lead with installed skills, so a click lands on that
// step. Connection and runtime stay behind the card menu's edit action.
function openCard(record: SandboxConfigRecord) {
if (supportsSkills(record)) {

View File

@ -101,12 +101,29 @@ func TestEffectiveTenantSkillsInjectsNothingWhenTheFingerprintDisagrees(t *testi
func TestEffectiveTenantSkillsInjectsNothingWhenTheBackendCannotSnapshot(t *testing.T) {
fx := newEffectiveFixture(t)
fx.configs.entity.SandboxType = "docker"
fx.configs.entity.Config.SandboxType = "docker"
fx.configs.entity.SandboxType = "local"
fx.configs.entity.Config.SandboxType = "local"
require.Empty(t, fx.derive(context.Background()))
}
func TestEffectiveTenantSkillsInjectsReadySkillsOnDocker(t *testing.T) {
fx := newEffectiveFixture(t)
host := "unix:///var/run/docker.sock"
fx.configs.entity.SandboxType = "docker"
fx.configs.entity.Config.SandboxType = "docker"
fx.configs.entity.Config.E2B = nil
fx.configs.entity.Config.Docker = &types.DockerSandboxConfig{Image: "weknora/sandbox:base", Host: host}
fx.configs.entity.Config.SkillImage = &types.SkillImageConfig{
SnapshotID: "weknora-skill/weknora-sk-cfg1-g1",
Generation: 1,
OwnerFingerprint: sandbox.SkillImageFingerprint("docker", "", host),
}
require.ElementsMatch(t, []string{"ready-enabled", "second-ready"},
skillNames(fx.derive(context.Background())))
}
func TestEffectiveTenantSkillsInjectsNothingWithoutAnImage(t *testing.T) {
fx := newEffectiveFixture(t)
fx.configs.entity.Config.SkillImage = nil

View File

@ -1628,6 +1628,10 @@ func currentBaseTemplate(cfg *types.TenantSandboxConfig) string {
if cfg.E2B != nil {
return cfg.E2B.TemplateID
}
case sandbox.SandboxTypeDocker:
if cfg.Docker != nil {
return cfg.Docker.Image
}
}
return ""
}
@ -1646,20 +1650,7 @@ func isSkillNameConflict(err error) bool {
}
func skillOwnerFingerprint(cfg *types.TenantSandboxConfig) string {
if cfg == nil {
return ""
}
switch sandbox.SandboxType(cfg.SandboxType) {
case sandbox.SandboxTypeCube:
if cfg.Cube != nil {
return sandbox.SkillImageFingerprint("cube", cfg.Cube.APIKey, cfg.Cube.APIURL)
}
case sandbox.SandboxTypeE2B:
if cfg.E2B != nil {
return sandbox.SkillImageFingerprint("e2b", cfg.E2B.APIKey, cfg.E2B.APIURL)
}
}
return ""
return sandbox.SkillOwnerFingerprint(cfg)
}
// configSandboxInvalidator is the narrow capability marking bound sandboxes

View File

@ -69,6 +69,26 @@ func TestRunInstallHappyPathSwitchesPointerLast(t *testing.T) {
require.Equal(t, types.SkillStatusReady, skill.Status)
}
func TestRunInstallSucceedsOnDockerConfig(t *testing.T) {
fx := newInstallFixture(t)
fx.configRepo.entity.SandboxType = "docker"
fx.configRepo.entity.Config.SandboxType = "docker"
fx.configRepo.entity.Config.E2B = nil
fx.configRepo.entity.Config.Docker = &types.DockerSandboxConfig{
Image: "weknora/sandbox:base",
Host: "unix:///var/run/docker.sock",
}
fx.fingerprint = sandbox.SkillImageFingerprint("docker", "", "unix:///var/run/docker.sock")
err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
require.NoError(t, err)
require.Contains(t, fx.events, "create-snapshot")
require.Equal(t, "snap-1", fx.configRepo.saved.Config.SkillImage.SnapshotID)
require.Equal(t, "weknora/sandbox:base", fx.configRepo.saved.Config.SkillImage.BaseTemplateID)
require.Equal(t, fx.fingerprint, fx.configRepo.saved.Config.SkillImage.OwnerFingerprint)
}
// TestRunInstallIssuesExactlyTheseCommands pins the order, not just the set.
// Ownership and permissions are normalised BEFORE verification on purpose: the
// agent creates the tree as root, so a restrictive root umask would leave the
@ -715,10 +735,10 @@ func (s stubWorkspaceSandboxPolicy) WorkspaceScriptsDisabled(context.Context, ui
func TestSwitchImagePointerRefusesAnUnusableFingerprint(t *testing.T) {
fx := newInstallFixture(t)
// A config whose provider carries no credentials produces no fingerprint,
// A config whose provider cannot snapshot produces no fingerprint,
// and a pointer with an empty fingerprint is discarded at session start.
fx.configRepo.entity.SandboxType = "docker"
fx.configRepo.entity.Config.SandboxType = "docker"
fx.configRepo.entity.SandboxType = "local"
fx.configRepo.entity.Config.SandboxType = "local"
fx.configRepo.entity.Config.E2B = nil
err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)

View File

@ -68,6 +68,16 @@ type dockerEngineAPI interface {
) (client.ImageInspectResult, error)
ImagePull(ctx context.Context, refStr string, options client.ImagePullOptions) (client.ImagePullResponse, error)
ImageList(ctx context.Context, options client.ImageListOptions) (client.ImageListResult, error)
ImageRemove(
ctx context.Context, imageID string, options client.ImageRemoveOptions,
) (client.ImageRemoveResult, error)
// ContainerCommit is a long call (a large skill image can take well
// over the short RPC budget), so the timeout wrapper leaves it on the
// caller's context the way it does ImagePull.
ContainerCommit(
ctx context.Context, containerID string, options client.ContainerCommitOptions,
) (client.ContainerCommitResult, error)
}
var _ dockerEngineAPI = (*client.Client)(nil)

View File

@ -568,3 +568,119 @@ func runDockerScriptWithTimeout(
result.ExitCode, result.Killed, result.Stdout, result.Stderr, result.Error)
return result
}
func TestDockerSkillSnapshotIntegration(t *testing.T) {
cfg := dockerIntegrationConfig(t)
client, err := NewDockerRemoteClient(cfg)
if err != nil {
t.Fatalf("build docker client: %v", err)
}
probeCtx, cancelProbe := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelProbe()
if err := client.Health(probeCtx); err != nil {
t.Skipf("docker daemon unreachable: %v", err)
}
if !client.Capabilities().SupportsSnapshots {
t.Fatal("docker backend must advertise snapshot support")
}
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
5*time.Minute,
)
defer cancel()
builder, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.DockerImage,
Metadata: map[string]string{"weknora.test": "skill-snapshot"},
})
if err != nil {
t.Fatalf("Create builder: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.Delete(cleanupCtx, builder.ID())
})
skillDir := SkillsImageRoot + "/itest"
skillFile := skillDir + "/SKILL.md"
seed, err := client.Exec(ctx, builder, RemoteExecRequest{
Command: fmt.Sprintf(
"mkdir -p %s && echo skill-ok > %s && chown %s:%s %s %s",
skillDir, skillFile, DefaultSandboxExecUser, DefaultSandboxExecUser,
SkillsImageRoot, skillDir,
),
Shell: true,
User: "root",
Timeout: time.Minute,
})
if err != nil || seed == nil || seed.ExitCode != 0 {
t.Fatalf("seed skill tree: err=%v result=%#v", err, seed)
}
ref, err := client.CreateSnapshot(ctx, builder.ID(), "weknora-sk-itest-g1")
if err != nil {
t.Fatalf("CreateSnapshot: %v", err)
}
if ref.ID == "" {
t.Fatal("CreateSnapshot returned an empty id")
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.DeleteSnapshot(cleanupCtx, ref.ID)
})
if err := client.Delete(ctx, builder.ID()); err != nil {
t.Fatalf("Delete builder: %v", err)
}
booted, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: ref.ID,
Metadata: map[string]string{"weknora.test": "skill-snapshot-boot"},
})
if err != nil {
t.Fatalf("Create from snapshot: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
_ = client.Delete(cleanupCtx, booted.ID())
})
check, err := client.Exec(ctx, booted, RemoteExecRequest{
Command: "cat " + skillFile,
Shell: true,
User: DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
if err != nil || check == nil || check.ExitCode != 0 || !strings.Contains(check.Stdout, "skill-ok") {
t.Fatalf("snapshot did not carry the skill: err=%v result=%#v", err, check)
}
listed, err := client.ListSnapshots(ctx, "")
if err != nil {
t.Fatalf("ListSnapshots: %v", err)
}
found := false
for _, item := range listed {
if item.ID == ref.ID {
found = true
break
}
}
if !found {
t.Fatalf("ListSnapshots missing %s: %#v", ref.ID, listed)
}
templates, err := client.ListTemplates(ctx)
if err != nil {
t.Fatalf("ListTemplates: %v", err)
}
for _, item := range templates {
if dockerCanonicalSnapshotID(item.ID) == ref.ID {
t.Fatalf("skill snapshot %s leaked into the template catalog", ref.ID)
}
}
}

View File

@ -14,6 +14,7 @@
// Get/List → GET /containers/json?filters=label=…
// Delete → DELETE /containers/{id}?force=1
// Exec → POST /containers/{id}/exec → /exec/{id}/start (hijack)
// Snapshot → POST /commit (skill images under weknora-skill/)
//
// Every file operation — WriteFile, ReadFile, Stat, MakeDir, Remove, ListDir —
// is an exec running as the sandbox account, NOT a call to /archive. The
@ -225,7 +226,11 @@ func (c *DockerRemoteClient) Capabilities() RemoteSandboxCapabilities {
SupportsPauseResume: true,
SupportsTimeoutRefresh: false,
SupportsFilesystemEnumeration: true,
SupportsVolumes: false,
// docker commit produces a local image whose tag is a template ID,
// which is what skill install uses on Cube/E2B. The snapshot is
// filesystem-only (no memory) and lives on this daemon.
SupportsSnapshots: true,
SupportsVolumes: false,
}
}
@ -1041,6 +1046,12 @@ func (c *DockerRemoteClient) ensureImage(ctx context.Context, image string) erro
if _, err := c.api.ImageInspect(ctx, image); err == nil {
return nil
}
// Skill snapshots are daemon-local commits, not registry tags. Pulling
// one would hit Docker Hub for a name we minted and never pushed, and a
// miss here means "this daemon does not have the image", not "fetch it".
if dockerIsSkillSnapshotRef(image) {
return dockerInvalidRequest("Create", "skill snapshot image "+image+" is not on this daemon")
}
pullCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerImagePullBudget)
defer cancel()
body, err := c.api.ImagePull(pullCtx, image, client.ImagePullOptions{})
@ -1147,4 +1158,7 @@ func firstNonEmptyLine(output string) string {
return ""
}
var _ RemoteSandboxClient = (*DockerRemoteClient)(nil)
var (
_ RemoteSandboxClient = (*DockerRemoteClient)(nil)
_ RemoteSnapshotManager = (*DockerRemoteClient)(nil)
)

View File

@ -65,6 +65,12 @@ type fakeDockerEngine struct {
images []image.Summary
imagePresent map[string]bool
pulled []string
committed []client.ContainerCommitOptions
commitID string
commitErr error
removedImages []string
removeImageErr error
}
func newFakeDockerEngine() *fakeDockerEngine {
@ -76,6 +82,8 @@ func newFakeDockerEngine() *fakeDockerEngine {
}
}
var _ dockerEngineAPI = (*fakeDockerEngine)(nil)
func (f *fakeDockerEngine) Ping(context.Context, client.PingOptions) (client.PingResult, error) {
return client.PingResult{APIVersion: "1.55"}, f.pingErr
}
@ -242,6 +250,75 @@ func (f *fakeDockerEngine) ImageList(
return client.ImageListResult{Items: f.images}, nil
}
func (f *fakeDockerEngine) ImageRemove(
_ context.Context, imageID string, _ client.ImageRemoveOptions,
) (client.ImageRemoveResult, error) {
f.removedImages = append(f.removedImages, imageID)
if f.removeImageErr != nil {
return client.ImageRemoveResult{}, f.removeImageErr
}
canonical := dockerCanonicalSnapshotID(imageID)
found := f.imagePresent[imageID] || f.imagePresent[canonical]
kept := make([]image.Summary, 0, len(f.images))
for _, item := range f.images {
match := item.ID == imageID || item.ID == canonical
for _, tag := range item.RepoTags {
if tag == imageID || dockerCanonicalSnapshotID(tag) == canonical {
match = true
break
}
}
if match {
found = true
continue
}
kept = append(kept, item)
}
if !found {
return client.ImageRemoveResult{}, cerrdefs.ErrNotFound.WithMessage("no such image")
}
f.images = kept
delete(f.imagePresent, imageID)
delete(f.imagePresent, canonical)
return client.ImageRemoveResult{}, nil
}
func (f *fakeDockerEngine) ContainerCommit(
_ context.Context, _ string, options client.ContainerCommitOptions,
) (client.ContainerCommitResult, error) {
f.committed = append(f.committed, options)
if f.commitErr != nil {
return client.ContainerCommitResult{}, f.commitErr
}
id := f.commitID
if id == "" {
id = "sha256:snapshot-1"
}
labels := map[string]string{}
for _, change := range options.Changes {
change = strings.TrimSpace(change)
if !strings.HasPrefix(strings.ToUpper(change), "LABEL ") {
continue
}
rest := strings.TrimSpace(change[len("LABEL "):])
key, value, ok := strings.Cut(rest, "=")
if !ok {
continue
}
labels[strings.TrimSpace(key)] = strings.Trim(strings.TrimSpace(value), `"`)
}
ref := strings.TrimSpace(options.Reference)
var tags []string
if ref != "" {
tags = []string{ref + ":latest"}
f.imagePresent[ref] = true
f.imagePresent[ref+":latest"] = true
}
f.imagePresent[id] = true
f.images = append(f.images, image.Summary{ID: id, RepoTags: tags, Labels: labels})
return client.ContainerCommitResult{ID: id}, nil
}
// fakePullResponse satisfies the pull-response contract without a registry.
type fakePullResponse struct{ io.ReadCloser }
@ -853,6 +930,8 @@ func TestDockerClientCapabilities(t *testing.T) {
require.True(t, caps.SupportsFilesystemEnumeration)
require.False(t, caps.SupportsTimeoutRefresh,
"the daemon has no TTL to refresh; reclamation is WeKnora's own sweep")
require.True(t, caps.SupportsSnapshots,
"docker commit is the skill-image snapshot; without this flag install is refused")
require.False(t, caps.SupportsVolumes)
}

View File

@ -135,4 +135,18 @@ func (a *dockerRPCTimeoutAPI) ImageList(
return a.inner.ImageList(rpcCtx, options)
}
func (a *dockerRPCTimeoutAPI) ImageRemove(
ctx context.Context, imageID string, options client.ImageRemoveOptions,
) (client.ImageRemoveResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ImageRemove(rpcCtx, imageID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerCommit(
ctx context.Context, containerID string, options client.ContainerCommitOptions,
) (client.ContainerCommitResult, error) {
return a.inner.ContainerCommit(ctx, containerID, options)
}
var _ dockerEngineAPI = (*dockerRPCTimeoutAPI)(nil)

View File

@ -0,0 +1,192 @@
package sandbox
import (
"context"
"strings"
"unicode"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/client"
)
const (
// dockerSkillSnapshotRepo is the local image namespace every skill
// snapshot is committed into. It is not a registry path: these tags are
// never pulled, and ListTemplates hides anything under it so an admin
// cannot pick a baked skill image as the config's base template.
dockerSkillSnapshotRepo = "weknora-skill"
dockerSkillSnapshotLabel = "com.weknora.sandbox.skill-snapshot"
dockerSkillSnapshotSourceLabel = "com.weknora.sandbox.skill-snapshot-source"
)
// CreateSnapshot commits the container's filesystem into a tagged local image.
//
// The Engine pauses the container for the duration of the commit unless we
// opt out (we do not): that is the same "provider pauses while snapshotting"
// contract Cube and E2B honour. The resulting tag is a template ID — Create
// accepts it as RemoteCreateRequest.TemplateID — so the skill install path
// needs no Docker-specific branch past this adapter.
func (c *DockerRemoteClient) CreateSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
id := strings.TrimSpace(sandboxID)
if id == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest("CreateSnapshot", "sandbox ID is required")
}
reference, err := dockerSkillSnapshotReference(name, id)
if err != nil {
return RemoteSnapshotRef{}, err
}
committed, err := c.api.ContainerCommit(ctx, id, client.ContainerCommitOptions{
Reference: reference,
Comment: "weknora skill snapshot",
Changes: []string{
"LABEL " + dockerSkillSnapshotLabel + "=true",
"LABEL " + dockerSkillSnapshotSourceLabel + "=" + id,
},
})
if err != nil {
return RemoteSnapshotRef{}, dockerError("CreateSnapshot", err)
}
if strings.TrimSpace(committed.ID) == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest(
"CreateSnapshot", "provider returned an empty snapshot ID")
}
return RemoteSnapshotRef{
ID: dockerCanonicalSnapshotID(reference),
Names: []string{dockerCanonicalSnapshotID(reference)},
}, nil
}
// DeleteSnapshot removes a committed skill image. A missing image is success:
// the reaper and the install-compensation path both retry deletes.
func (c *DockerRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
id := strings.TrimSpace(snapshotID)
if id == "" {
return dockerInvalidRequest("DeleteSnapshot", "snapshot ID is required")
}
_, err := c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{Force: true})
if err != nil {
normalized := dockerError("DeleteSnapshot", err)
if IsRemoteNotFound(normalized) {
return nil
}
return normalized
}
return nil
}
// ListSnapshots returns skill-snapshot images on this daemon. An empty
// sandboxID lists every skill snapshot; a non-empty one keeps those committed
// from that container.
func (c *DockerRemoteClient) ListSnapshots(
ctx context.Context, sandboxID string,
) ([]RemoteSnapshotRef, error) {
filters := client.Filters{}.Add("label", dockerSkillSnapshotLabel+"=true")
if src := strings.TrimSpace(sandboxID); src != "" {
filters = filters.Add("label", dockerSkillSnapshotSourceLabel+"="+src)
}
listed, err := c.api.ImageList(ctx, client.ImageListOptions{All: true, Filters: filters})
if err != nil {
return nil, dockerError("ListSnapshots", err)
}
wantSource := strings.TrimSpace(sandboxID)
out := make([]RemoteSnapshotRef, 0, len(listed.Items))
for _, item := range listed.Items {
if !dockerImageIsSkillSnapshot(item) {
continue
}
if wantSource != "" && item.Labels[dockerSkillSnapshotSourceLabel] != wantSource {
continue
}
out = append(out, dockerSnapshotRef(item))
}
return out, nil
}
func dockerImageIsSkillSnapshot(item image.Summary) bool {
if item.Labels[dockerSkillSnapshotLabel] == "true" {
return true
}
for _, tag := range item.RepoTags {
if dockerIsSkillSnapshotRef(tag) {
return true
}
}
return false
}
func dockerIsSkillSnapshotRef(ref string) bool {
trimmed := strings.TrimSpace(ref)
prefix := dockerSkillSnapshotRepo + "/"
if strings.HasPrefix(trimmed, prefix) {
return true
}
// ImageList sometimes returns the docker.io/ prefix. The tag we mint
// never has a registry, so this is only a listing alias.
return strings.HasPrefix(trimmed, "docker.io/"+prefix)
}
func dockerSnapshotRef(item image.Summary) RemoteSnapshotRef {
names := make([]string, 0, len(item.RepoTags))
id := strings.TrimSpace(item.ID)
for _, tag := range item.RepoTags {
if tag == "" || tag == "<none>:<none>" {
continue
}
canonical := dockerCanonicalSnapshotID(tag)
names = append(names, canonical)
if dockerIsSkillSnapshotRef(canonical) && (id == "" || !dockerIsSkillSnapshotRef(id)) {
id = canonical
}
}
if id == "" && len(names) > 0 {
id = names[0]
}
return RemoteSnapshotRef{ID: id, Names: names}
}
func dockerCanonicalSnapshotID(ref string) string {
trimmed := strings.TrimPrefix(strings.TrimSpace(ref), "docker.io/")
return strings.TrimSuffix(trimmed, ":latest")
}
func dockerSkillSnapshotReference(name, sandboxID string) (string, error) {
base := dockerSanitizeImageName(name)
if base == "" {
base = dockerSanitizeImageName(sandboxID)
}
if base == "" {
return "", dockerInvalidRequest("CreateSnapshot", "snapshot name is required")
}
return dockerSkillSnapshotRepo + "/" + base, nil
}
// dockerSanitizeImageName maps an install-generated snapshot name onto a
// single Docker path component: lowercase [a-z0-9] with interior - separators.
func dockerSanitizeImageName(raw string) string {
var b strings.Builder
lastSep := true
for _, r := range strings.ToLower(strings.TrimSpace(raw)) {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
b.WriteRune(r)
lastSep = false
case r == '.' || r == '_' || r == '-':
if lastSep || b.Len() == 0 {
continue
}
b.WriteByte('-')
lastSep = true
}
}
out := strings.Trim(b.String(), "-")
const maxName = 80
if len(out) > maxName {
out = strings.Trim(out[:maxName], "-")
}
return out
}

View File

@ -0,0 +1,116 @@
package sandbox
import (
"context"
"testing"
"github.com/moby/moby/api/types/image"
"github.com/stretchr/testify/require"
)
func TestDockerCreateSnapshotTagsASkillImage(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ref, err := docker.CreateSnapshot(context.Background(), "container-1", "weknora-sk-cfg1-g1")
require.NoError(t, err)
require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", ref.ID)
require.Len(t, engine.committed, 1)
require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", engine.committed[0].Reference)
require.False(t, engine.committed[0].NoPause,
"the Engine must pause the container for the duration of the commit")
require.Contains(t, engine.committed[0].Changes, "LABEL "+dockerSkillSnapshotLabel+"=true")
require.Contains(t, engine.committed[0].Changes,
"LABEL "+dockerSkillSnapshotSourceLabel+"=container-1")
}
func TestDockerCreateSnapshotRejectsEmptySandboxID(t *testing.T) {
_, err := newTestDockerClient(t, newFakeDockerEngine()).
CreateSnapshot(context.Background(), " ", "n")
require.True(t, IsRemoteInvalidRequest(err))
}
func TestDockerDeleteSnapshotTreatsMissingAsSuccess(t *testing.T) {
err := newTestDockerClient(t, newFakeDockerEngine()).
DeleteSnapshot(context.Background(), "weknora-skill/missing")
require.NoError(t, err)
}
func TestDockerDeleteSnapshotRejectsEmptySnapshotID(t *testing.T) {
err := newTestDockerClient(t, newFakeDockerEngine()).
DeleteSnapshot(context.Background(), " ")
require.True(t, IsRemoteInvalidRequest(err))
}
func TestDockerSnapshotRoundTripAndListFilter(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ctx := context.Background()
first, err := docker.CreateSnapshot(ctx, "container-a", "weknora-sk-a-g1")
require.NoError(t, err)
second, err := docker.CreateSnapshot(ctx, "container-a", "weknora-sk-a-g2")
require.NoError(t, err)
_, err = docker.CreateSnapshot(ctx, "container-b", "weknora-sk-b-g1")
require.NoError(t, err)
all, err := docker.ListSnapshots(ctx, "")
require.NoError(t, err)
require.Len(t, all, 3)
fromA, err := docker.ListSnapshots(ctx, "container-a")
require.NoError(t, err)
require.Len(t, fromA, 2)
ids := map[string]struct{}{fromA[0].ID: {}, fromA[1].ID: {}}
require.Contains(t, ids, first.ID)
require.Contains(t, ids, second.ID)
require.NoError(t, docker.DeleteSnapshot(ctx, first.ID))
require.NoError(t, docker.DeleteSnapshot(ctx, first.ID), "deleting twice must stay idempotent")
fromA, err = docker.ListSnapshots(ctx, "container-a")
require.NoError(t, err)
require.Len(t, fromA, 1)
require.Equal(t, second.ID, fromA[0].ID)
}
func TestDockerListTemplatesHidesSkillSnapshots(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:base",
RepoTags: []string{"weknora/sandbox:test"},
Labels: map[string]string{dockerTemplateLabel: "true"},
},
{
ID: "sha256:snap",
RepoTags: []string{"weknora-skill/weknora-sk-cfg1-g1:latest"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
}
docker := newTestDockerClient(t, engine)
templates, err := docker.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "weknora/sandbox:test", templates[0].ID)
}
func TestDockerCreateDoesNotPullAMissingSkillSnapshot(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
_, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: "weknora-skill/weknora-sk-cfg1-g1",
})
require.True(t, IsRemoteInvalidRequest(err), err)
require.Empty(t, engine.pulled,
"a local commit must not be fetched from a registry")
}
func TestDockerSanitizeImageName(t *testing.T) {
require.Equal(t, "weknora-sk-cfg1-g1", dockerSanitizeImageName("weknora-sk-cfg1-g1"))
require.Equal(t, "abc-def", dockerSanitizeImageName("ABC_DEF"))
require.Equal(t, "snap", dockerSanitizeImageName("--snap--"))
require.Empty(t, dockerSanitizeImageName("***"))
}

View File

@ -5,12 +5,14 @@
// answer is images on the daemon: an image is a pre-baked filesystem a sandbox
// starts from, which is exactly what a Cube or E2B template is.
//
// Two differences from the MicroVM backends shape this file:
// Three differences from the MicroVM backends shape this file:
//
// - A daemon holds every image its host ever pulled, most of which have
// nothing to do with sandboxes. Listing all of them would bury the one the
// admin needs, so the catalog only reports images that are recognisably
// sandbox templates.
// - Skill snapshots live in the same image store (weknora-skill/…), so they
// are subtracted the way Cube hides snap- IDs from GET /templates.
// - Making the standard template exist means pulling, which can take minutes
// on a cold host. The pull therefore runs in the background and the
// template reports "building" until it lands, mirroring how the other
@ -56,12 +58,19 @@ func (c *DockerRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplat
configured := strings.TrimSpace(c.settings.Image)
configuredPresent := false
for _, image := range listed.Items {
snapshot := dockerImageIsSkillSnapshot(image)
for _, tag := range image.RepoTags {
if tag == "" || tag == "<none>:<none>" {
continue
}
// Skill snapshots are images, so they would otherwise appear in
// the "pick a base template" list the way Cube's snap- IDs used
// to. Hide them unless this config's stored image is that tag.
if snapshot && tag != configured {
continue
}
standard := isStandardTemplateImage(tag)
if !standard && image.Labels[dockerTemplateLabel] != "true" && tag != configured {
if !standard && !snapshot && image.Labels[dockerTemplateLabel] != "true" && tag != configured {
continue
}
if tag == configured {

View File

@ -2,7 +2,7 @@
//
// This file introduces the RemoteSandboxClient interface and the neutral
// data-transfer types that SessionBoundManager depends on. Concrete backends
// (Cube, E2B) each provide an implementation
// (Cube, E2B, Docker) each provide an implementation
// in a separate adapter file.
//
// The interface is deliberately minimal: it covers only the operations
@ -338,7 +338,7 @@ type RemoteSandboxCapabilities struct {
// SupportsSnapshots reports whether the provider can snapshot a running
// sandbox into a reusable image. Snapshot IDs double as template IDs on
// both Cube and E2B, which is what makes skill images work.
// Cube, E2B, and Docker, which is what makes skill images work.
SupportsSnapshots bool
// SupportsVolumes is true when the provider can mount a named volume into
@ -424,8 +424,8 @@ func cloneMetadata(source map[string]string) map[string]string {
}
// RemoteSnapshotRef identifies one provider-side snapshot. ID can be passed
// straight back as RemoteCreateRequest.TemplateID: both Cube and E2B store
// snapshots as templates.
// straight back as RemoteCreateRequest.TemplateID: Cube and E2B store
// snapshots as templates, and Docker stores them as local image tags.
type RemoteSnapshotRef struct {
ID string
Names []string
@ -448,7 +448,7 @@ type RemoteSnapshotManager interface {
}
// SnapshotManagerFrom narrows a client to its snapshot capability. It returns
// false for providers that cannot snapshot (docker/local), so callers can fall
// false for providers that cannot snapshot (local), so callers can fall
// back to the base template instead of failing.
//
// Both signals must agree: the type assertion finds the methods, and

View File

@ -28,8 +28,8 @@ func SkillImageFingerprint(provider, apiKey, apiURL string) string {
// already answers, from the same inputs: a skill announced to the model while
// sessions keep booting the base template is a skill that cannot be invoked,
// and one hidden while the image carries it is an install nobody can use. It is
// false for backends that cannot snapshot at all, which is what "the base
// template is kept" means for them.
// false for backends that cannot snapshot at all (local/disabled), which is
// what "the base template is kept" means for them.
func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool {
if tenantCfg == nil {
return false
@ -42,11 +42,11 @@ func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool {
// ResolveEffectiveConfig falls back to the GLOBAL type when that field is
// empty - so in principle a config with no stored type could boot as e2b
// here and be judged "no image" there. The two agree today only because
// the install flow's skillOwnerFingerprint also returns "" for an empty
// SandboxType, and an empty OwnerFingerprint forces the override to "":
// such a config can never hold a usable image in the first place. That
// agreement is accidental. Keep the fingerprint guard, or make this switch
// take the global fallback too.
// SkillOwnerFingerprint also returns "" for an empty SandboxType, and an
// empty OwnerFingerprint forces the override to "": such a config can
// never hold a usable image in the first place. That agreement is
// accidental. Keep the fingerprint guard, or make this switch take the
// global fallback too.
switch SandboxType(tenantCfg.SandboxType) {
case SandboxTypeCube:
if tenantCfg.Cube == nil {
@ -62,10 +62,63 @@ func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool {
return skillImageTemplateOverride(
tenantCfg.SkillImage, "e2b", tenantCfg.E2B.APIKey, tenantCfg.E2B.APIURL,
) != ""
case SandboxTypeDocker:
if tenantCfg.Docker == nil {
return false
}
host, tls := dockerSkillOwnerIdentity(tenantCfg.Docker)
return skillImageTemplateOverride(
tenantCfg.SkillImage, "docker", tls, host,
) != ""
}
return false
}
// SkillOwnerFingerprint is the provider-account identity stamped onto a
// skill snapshot. The install path refuses to record a snapshot when this is
// empty: a pointer with no owner is discarded at session start.
func SkillOwnerFingerprint(tenantCfg *types.TenantSandboxConfig) string {
if tenantCfg == nil {
return ""
}
switch SandboxType(tenantCfg.SandboxType) {
case SandboxTypeCube:
if tenantCfg.Cube != nil {
return SkillImageFingerprint("cube", tenantCfg.Cube.APIKey, tenantCfg.Cube.APIURL)
}
case SandboxTypeE2B:
if tenantCfg.E2B != nil {
return SkillImageFingerprint("e2b", tenantCfg.E2B.APIKey, tenantCfg.E2B.APIURL)
}
case SandboxTypeDocker:
return dockerSkillOwnerFingerprint(tenantCfg.Docker)
}
return ""
}
// dockerSkillOwnerIdentity is the daemon this config will actually dial.
// A blank host follows the local docker CLI, which is also how
// ResolveEffectiveConfig fills DockerHost, so the fingerprint computed here
// matches the override computed there.
func dockerSkillOwnerIdentity(docker *types.DockerSandboxConfig) (host, tls string) {
if docker == nil {
return "", ""
}
host = strings.TrimSpace(docker.Host)
if host == "" {
host = DetectLocalDockerHost()
}
return host, strings.TrimSpace(docker.TLSCertPath)
}
func dockerSkillOwnerFingerprint(docker *types.DockerSandboxConfig) string {
if docker == nil {
return ""
}
host, tls := dockerSkillOwnerIdentity(docker)
return SkillImageFingerprint("docker", tls, host)
}
// skillImageTemplateOverride returns the snapshot ID that should replace the
// base template, or "" when the base template must be kept.
func skillImageTemplateOverride(

View File

@ -120,10 +120,10 @@ func ResolveEffectiveConfig(
case SandboxTypeDocker:
applyDockerRuntimeDefaults(&effective)
}
// A skill snapshot is just a template ID on both providers, so overriding
// the template field here is the entire session-side change. Everything
// downstream keeps reading CubeTemplate / E2BTemplate and needs no knowledge
// of skills.
// A skill snapshot is a template ID (Cube/E2B) or an image tag (Docker),
// so overriding that field here is the entire session-side change.
// Everything downstream keeps reading CubeTemplate / E2BTemplate /
// DockerImage and needs no knowledge of skills.
switch effective.Type {
case SandboxTypeCube:
if snapshot := skillImageTemplateOverride(
@ -137,6 +137,12 @@ func ResolveEffectiveConfig(
); snapshot != "" {
effective.E2BTemplate = snapshot
}
case SandboxTypeDocker:
if snapshot := skillImageTemplateOverride(
tenantCfg.SkillImage, "docker", effective.DockerTLSCertPath, effective.DockerHost,
); snapshot != "" {
effective.DockerImage = snapshot
}
}
// Deliberately after the runtime defaults: TTLs and HTTP timeouts have
// built-in fallbacks, endpoints and credentials do not.

View File

@ -368,6 +368,81 @@ func TestResolveEffectiveConfigUsesSkillSnapshotAsE2BTemplate(t *testing.T) {
})
}
func TestResolveEffectiveConfigUsesSkillSnapshotAsDockerImage(t *testing.T) {
global := DefaultConfig()
base := &types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{
Image: "weknora/sandbox:base",
Host: "unix:///var/run/docker.sock",
},
}
fp := SkillImageFingerprint("docker", "", "unix:///var/run/docker.sock")
t.Run("usable snapshot overrides the base image", func(t *testing.T) {
cfg := *base
cfg.Docker = &types.DockerSandboxConfig{
Image: "weknora/sandbox:base", Host: "unix:///var/run/docker.sock",
}
cfg.SkillImage = &types.SkillImageConfig{
SnapshotID: "weknora-skill/weknora-sk-cfg1-g1", OwnerFingerprint: fp,
}
eff, err := ResolveEffectiveConfig(&cfg, global)
require.NoError(t, err)
require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", eff.DockerImage)
})
t.Run("fingerprint mismatch falls back to the base image", func(t *testing.T) {
cfg := *base
cfg.Docker = &types.DockerSandboxConfig{
Image: "weknora/sandbox:base", Host: "unix:///var/run/docker.sock",
}
cfg.SkillImage = &types.SkillImageConfig{
SnapshotID: "weknora-skill/weknora-sk-cfg1-g1", OwnerFingerprint: "another-daemon",
}
eff, err := ResolveEffectiveConfig(&cfg, global)
require.NoError(t, err)
require.Equal(t, "weknora/sandbox:base", eff.DockerImage,
"a snapshot from another daemon is invisible; the session must still boot")
})
t.Run("blank host fingerprints as the resolved daemon", func(t *testing.T) {
t.Setenv("DOCKER_HOST", "unix:///tmp/weknora-skill-docker.sock")
cfg := &types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{Image: "weknora/sandbox:base"},
SkillImage: &types.SkillImageConfig{
SnapshotID: "weknora-skill/weknora-sk-cfg1-g1",
OwnerFingerprint: SkillImageFingerprint("docker", "", DetectLocalDockerHost()),
},
}
eff, err := ResolveEffectiveConfig(cfg, global)
require.NoError(t, err)
require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", eff.DockerImage)
require.True(t, SkillImageActive(cfg))
})
}
func TestSkillOwnerFingerprintForDocker(t *testing.T) {
require.Empty(t, SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "docker"}),
"a docker type with no daemon block cannot own a snapshot")
require.Empty(t, SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "local"}))
got := SkillOwnerFingerprint(&types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{
Image: "img", Host: "unix:///var/run/docker.sock", TLSCertPath: "/certs",
},
})
require.Equal(t, SkillImageFingerprint("docker", "/certs", "unix:///var/run/docker.sock"), got)
}
// SkillImageActive is what the agent side asks before telling a model about an
// installed skill, so it must agree with the template ResolveEffectiveConfig
// actually boots. Any disagreement means either skills that are announced and
@ -421,14 +496,29 @@ func TestSkillImageActiveAgreesWithTheResolvedTemplate(t *testing.T) {
},
"backend that cannot snapshot": {
config: &types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{Image: "img"},
SandboxType: "local",
SkillImage: &types.SkillImageConfig{
SnapshotID: "snap-1", OwnerFingerprint: fp,
},
},
want: false,
},
"docker snapshot owned by the live daemon": {
config: &types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{
Image: "weknora/sandbox:base",
Host: "unix:///var/run/docker.sock",
},
SkillImage: &types.SkillImageConfig{
SnapshotID: "weknora-skill/weknora-sk-cfg1-g1",
OwnerFingerprint: SkillImageFingerprint(
"docker", "", "unix:///var/run/docker.sock",
),
},
},
want: true,
},
}
for name, tc := range cases {