-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_container.go
More file actions
781 lines (652 loc) · 23.4 KB
/
backend_container.go
File metadata and controls
781 lines (652 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
package sbox
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"go.uber.org/zap"
)
// DockerSocketEnvVar is the environment variable to override the Docker socket path
const DockerSocketEnvVar = "SBOX_DOCKER_SOCKET"
// ContainerBackend implements the Backend interface using standard Docker containers
type ContainerBackend struct {
config *Config
}
// NewContainerBackend creates a new container backend instance
func NewContainerBackend(config *Config) *ContainerBackend {
return &ContainerBackend{config: config}
}
// Name returns the backend type name
func (b *ContainerBackend) Name() BackendType {
return BackendContainer
}
// volumeName generates a unique volume name for persisting agent config folder
func (b *ContainerBackend) volumeName(workspaceDir string, agent AgentType) string {
absPath, _ := filepath.Abs(workspaceDir)
hash := sha256.Sum256([]byte(absPath))
agentName := string(agent)
if agentName == "" {
agentName = string(DefaultAgent)
}
return "sbox-" + agentName + "-" + hex.EncodeToString(hash[:])[:12]
}
// containerName generates the container name for a workspace
func (b *ContainerBackend) containerName(workspaceDir string, agent AgentType) (string, error) {
return GenerateSandboxName(workspaceDir, agent)
}
// Run starts or attaches to a container for the given workspace
func (b *ContainerBackend) Run(opts BackendOptions) error {
absPath, err := filepath.Abs(opts.WorkspaceDir)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
// Resolve agent type first (needed for container name)
agentType := AgentType(opts.ProjectConfig.Agent)
if agentType == "" {
agentType = DefaultAgent
}
containerName, err := b.containerName(absPath, agentType)
if err != nil {
return fmt.Errorf("failed to generate container name: %w", err)
}
// Merge project profiles with command-line profiles
allProfiles := mergeProfiles(opts.ProjectConfig.Profiles, opts.Profiles)
zlog.Info("preparing to run Docker container",
zap.String("name", containerName),
zap.String("workspace", absPath),
zap.Strings("profiles", allProfiles))
// Prepare .sbox directory with plugins, agents, and env vars
var sboxFileEnvs []string
if opts.SboxFile != nil && opts.SboxFile.Config != nil {
sboxFileEnvs = opts.SboxFile.Config.Envs
}
if err := PrepareSboxDirectory(absPath, opts.Config, opts.Config.Envs, opts.ProjectConfig.Envs, sboxFileEnvs, BackendContainer, agentType, opts); err != nil {
return fmt.Errorf("failed to prepare .sbox directory: %w", err)
}
// Check if container exists
existing, err := b.Find(absPath)
if err != nil {
zlog.Debug("failed to check for existing container", zap.Error(err))
}
if existing != nil {
// Check if the container's TTY mode matches what we need.
// A container created for prompt/loop mode (no TTY) cannot be reused
// for interactive mode (needs TTY), and vice versa. If there's a
// mismatch, remove the old container and create a new one.
needsTTY := opts.Prompt == ""
hasTTY := b.containerHasTTY(existing.ID)
if needsTTY != hasTTY {
zlog.Info("container TTY mode mismatch, recreating",
zap.Bool("needs_tty", needsTTY),
zap.Bool("has_tty", hasTTY))
DefaultUI.Status("Recreating container '%s' (TTY mode changed)", containerName)
// Stop if running, then remove
if existing.Status == "running" {
stopCmd := exec.Command("docker", "stop", existing.ID)
_ = stopCmd.Run()
}
rmCmd := exec.Command("docker", "rm", "-v", existing.ID)
_ = rmCmd.Run()
// Fall through to create a new container below
} else {
// Container exists with matching TTY mode - reuse it
if existing.Status == "running" {
DefaultUI.Status("Attaching to running container '%s'", containerName)
return b.attachContainer(containerName, opts)
}
// Container exists but not running - start it
DefaultUI.Status("Starting existing container '%s'", containerName)
return b.startContainer(containerName, opts)
}
}
// Container doesn't exist - create and run it
// Build custom template
builder := NewTemplateBuilder(opts.Config, allProfiles, agentType)
templateImage, err := builder.Build(opts.ForceRebuild)
if err != nil {
return fmt.Errorf("failed to build custom template: %w", err)
}
DefaultUI.Status("Creating container '%s'", containerName)
zlog.Info("container does not exist, creating",
zap.String("name", containerName),
zap.String("workspace", absPath),
zap.String("template", templateImage))
// Ensure volume exists for agent config persistence
volumeName := b.volumeName(absPath, agentType)
if err := b.ensureVolume(volumeName); err != nil {
return fmt.Errorf("failed to create persistence volume: %w", err)
}
// Build docker run command
args := b.buildRunArgs(containerName, absPath, templateImage, volumeName, agentType, opts)
zlog.Debug("executing docker command",
zap.String("cmd", "docker"),
zap.Strings("args", args))
DefaultUI.Status("Starting container '%s'", containerName)
cmd := exec.Command("docker", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker run failed: %w", err)
}
zlog.Info("Docker container exited successfully")
return nil
}
// buildRunArgs constructs the docker run command arguments
func (b *ContainerBackend) buildRunArgs(containerName, workspaceDir, image, volumeName string, agentType AgentType, opts BackendOptions) []string {
var args []string
if opts.Prompt != "" {
// Non-interactive mode (prompt/loop): no TTY allocation.
// A TTY would mangle the stream-json output that the entrypoint parses.
args = []string{"run", "--name", containerName}
} else {
args = []string{"run", "-it", "--name", containerName}
}
// Mount workspace directory
args = append(args, "-v", fmt.Sprintf("%s:%s", workspaceDir, workspaceDir))
// If workspace is a git linked worktree, also mount the main repo root so git
// can follow the absolute gitdir path stored in the worktree's .git file.
if mainRepoRoot, ok := detectGitWorktree(workspaceDir); ok {
args = append(args, "-v", fmt.Sprintf("%s:%s", mainRepoRoot, mainRepoRoot))
zlog.Info("workspace is a git worktree, mounting main repo root",
zap.String("main_repo_root", mainRepoRoot))
}
// Mount persistence volume for agent config folder
spec := GetAgentSpec(agentType)
configDir := spec.ConfigDirName()
args = append(args, "-v", fmt.Sprintf("%s:/home/agent/%s", volumeName, configDir))
// Set working directory
args = append(args, "-w", workspaceDir)
// Set workspace env var (used by entrypoint)
args = append(args, "-e", fmt.Sprintf("WORKSPACE_DIR=%s", workspaceDir))
// Mount SSH directory if it exists (read-only)
homeDir, err := os.UserHomeDir()
if err == nil {
sshPath := filepath.Join(homeDir, ".ssh")
if _, err := os.Stat(sshPath); err == nil {
args = append(args, "-v", fmt.Sprintf("%s:/home/agent/.ssh:ro", sshPath))
}
}
// Mount Docker socket if requested
if opts.MountDockerSocket {
socketPath := getDockerSocketPath()
if socketPath != "" {
args = append(args, "-v", fmt.Sprintf("%s:/var/run/docker.sock", socketPath))
zlog.Debug("mounting docker socket", zap.String("host_path", socketPath))
} else {
zlog.Warn("docker socket requested but no socket found")
}
}
// Shadow excluded dirs with anonymous volumes to prevent host file-descriptor
// exhaustion on macOS from large build output trees (e.g. target/, node_modules/).
for _, dir := range opts.ProjectConfig.ExcludeDirs {
var containerPath string
if filepath.IsAbs(dir) {
containerPath = dir
} else {
containerPath = filepath.Join(workspaceDir, dir)
}
args = append(args, "-v", containerPath)
}
// Mount additional volumes from project config
for _, vol := range opts.ProjectConfig.Volumes {
hostPath, containerPath, readOnly, err := ParseVolumeSpec(vol)
if err != nil {
zlog.Warn("invalid volume specification, skipping", zap.String("spec", vol), zap.Error(err))
continue
}
// Check if host path exists
if _, err := os.Stat(hostPath); err != nil {
zlog.Warn("volume host path not found, skipping",
zap.String("host_path", hostPath),
zap.String("container_path", containerPath),
zap.Error(err))
continue
}
mountSpec := fmt.Sprintf("%s:%s", hostPath, containerPath)
if readOnly {
mountSpec += ":ro"
}
args = append(args, "-v", mountSpec)
}
// Add the image
args = append(args, image)
return args
}
// ensureVolume creates a Docker volume if it doesn't exist
func (b *ContainerBackend) ensureVolume(volumeName string) error {
// Check if volume exists
cmd := exec.Command("docker", "volume", "inspect", volumeName)
if err := cmd.Run(); err == nil {
// Volume already exists
zlog.Debug("volume already exists", zap.String("volume", volumeName))
return nil
}
// Create volume
zlog.Info("creating persistence volume", zap.String("volume", volumeName))
cmd = exec.Command("docker", "volume", "create", volumeName)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker volume create failed: %w (stderr: %s)", err, stderr.String())
}
return nil
}
// attachContainer attaches to a running container
func (b *ContainerBackend) attachContainer(containerName string, opts BackendOptions) error {
args := []string{"attach"}
if opts.Prompt != "" {
// Non-interactive mode: don't attach stdin (no --sig-proxy=false needed,
// we still want signals forwarded)
args = append(args, "--no-stdin")
}
args = append(args, containerName)
cmd := exec.Command("docker", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker attach failed: %w", err)
}
return nil
}
// startContainer starts a stopped container
func (b *ContainerBackend) startContainer(containerName string, opts BackendOptions) error {
args := []string{"start"}
if opts.Prompt != "" {
// Non-interactive mode: attach stdout/stderr but no interactive TTY
args = append(args, "-a")
} else {
// Interactive mode: attach + interactive
args = append(args, "-ai")
}
args = append(args, containerName)
cmd := exec.Command("docker", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker start failed: %w", err)
}
return nil
}
// Shell opens a shell in the running container
func (b *ContainerBackend) Shell(workspaceDir string) error {
// Check if we're already inside a container
if IsInsideSandbox() {
return fmt.Errorf("you are already inside a container\nUse 'bash' to open a new shell, or exit and run 'sbox shell' from the host")
}
absPath, err := filepath.Abs(workspaceDir)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
info, err := b.FindRunning(absPath)
if err != nil {
return fmt.Errorf("failed to find running container: %w", err)
}
if info == nil {
return fmt.Errorf("no container is running for workspace: %s\nStart a container first with: sbox run", absPath)
}
zlog.Info("connecting to container shell",
zap.String("container_id", info.ID),
zap.String("container_name", info.Name),
zap.String("workspace", absPath))
cmd := exec.Command("docker", "exec", "-it", info.ID, "bash")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker exec failed: %w", err)
}
return nil
}
// Stop stops the container, optionally removing it
func (b *ContainerBackend) Stop(workspaceDir string, remove bool) (*ContainerInfo, error) {
absPath, err := filepath.Abs(workspaceDir)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
info, err := b.FindRunning(absPath)
if err != nil {
return nil, fmt.Errorf("failed to find running container: %w", err)
}
// If no running container but remove is requested, look for stopped container
if info == nil && remove {
info, err = b.Find(absPath)
if err != nil {
return nil, fmt.Errorf("failed to find container: %w", err)
}
if info != nil {
zlog.Debug("found stopped container to remove",
zap.String("container_id", info.ID),
zap.String("status", info.Status))
}
}
if info == nil {
zlog.Debug("no container to stop or remove", zap.String("workspace", absPath))
return nil, nil
}
var stderr bytes.Buffer
// Only stop if the container is running
if info.Status == "running" {
zlog.Info("stopping container",
zap.String("container_id", info.ID),
zap.String("container_name", info.Name),
zap.String("workspace", absPath))
// Stop the container
stopCmd := exec.Command("docker", "stop", info.ID)
stopCmd.Stderr = &stderr
if err := stopCmd.Run(); err != nil {
return nil, fmt.Errorf("docker stop failed: %w (stderr: %s)", err, stderr.String())
}
zlog.Info("container stopped",
zap.String("container_id", info.ID),
zap.String("container_name", info.Name))
} else {
zlog.Debug("container already stopped",
zap.String("container_id", info.ID),
zap.String("status", info.Status))
}
// Remove the container if requested
if remove {
zlog.Info("removing container",
zap.String("container_id", info.ID),
zap.String("container_name", info.Name))
rmCmd := exec.Command("docker", "rm", "-v", info.ID)
rmCmd.Stderr = &stderr
if err := rmCmd.Run(); err != nil {
return nil, fmt.Errorf("docker rm failed: %w (stderr: %s)", err, stderr.String())
}
zlog.Info("container removed",
zap.String("container_id", info.ID),
zap.String("container_name", info.Name))
}
return info, nil
}
// Find returns container info for the given workspace (any state)
func (b *ContainerBackend) Find(workspaceDir string) (*ContainerInfo, error) {
absPath, err := filepath.Abs(workspaceDir)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
// Load project config to get the agent type
projectConfig, _, err := GetProjectConfig(absPath)
if err != nil {
return nil, fmt.Errorf("failed to load project config: %w", err)
}
agentType := AgentType(projectConfig.Agent)
if agentType == "" {
agentType = DefaultAgent
}
containerName, err := b.containerName(absPath, agentType)
if err != nil {
return nil, err
}
// Use docker ps -a to find the container by name
cmd := exec.Command("docker", "ps", "-a", "--filter", fmt.Sprintf("name=^%s$", containerName), "--format", "{{json .}}")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
zlog.Debug("docker ps command failed",
zap.Error(err),
zap.String("stderr", stderr.String()))
return nil, nil // Container likely doesn't exist
}
output := strings.TrimSpace(stdout.String())
if output == "" {
return nil, nil // No container found
}
// Parse the JSON output
var containerData struct {
ID string `json:"ID"`
Names string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
}
if err := json.Unmarshal([]byte(output), &containerData); err != nil {
return nil, fmt.Errorf("failed to parse docker ps output: %w", err)
}
return &ContainerInfo{
ID: containerData.ID,
Name: containerData.Names,
Status: containerData.State,
Image: containerData.Image,
Workspace: absPath,
Backend: BackendContainer,
}, nil
}
// FindRunning returns container info only if running
func (b *ContainerBackend) FindRunning(workspaceDir string) (*ContainerInfo, error) {
info, err := b.Find(workspaceDir)
if err != nil {
return nil, err
}
if info == nil {
return nil, nil
}
// Only return if the container is running
if info.Status != "running" {
zlog.Debug("container found but not running",
zap.String("container_id", info.ID),
zap.String("status", info.Status))
return nil, nil
}
return info, nil
}
// List returns all containers managed by this backend
func (b *ContainerBackend) List() ([]ContainerInfo, error) {
// List all containers with the sbox- prefix (covers both claude and opencode)
cmd := exec.Command("docker", "ps", "-a", "--filter", "name=^sbox-", "--format", "{{json .}}")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
zlog.Debug("docker ps command failed",
zap.Error(err),
zap.String("stderr", stderr.String()))
return nil, fmt.Errorf("docker ps failed: %w", err)
}
var infos []ContainerInfo
lines := strings.Split(strings.TrimSpace(stdout.String()), "\n")
for _, line := range lines {
if line == "" {
continue
}
var containerData struct {
ID string `json:"ID"`
Names string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
}
if err := json.Unmarshal([]byte(line), &containerData); err != nil {
zlog.Debug("failed to parse container data", zap.String("line", line), zap.Error(err))
continue
}
// Try to extract workspace from container mounts
workspace := b.getContainerWorkspace(containerData.ID)
infos = append(infos, ContainerInfo{
ID: containerData.ID,
Name: containerData.Names,
Status: containerData.State,
Image: containerData.Image,
Workspace: workspace,
Backend: BackendContainer,
})
}
return infos, nil
}
// containerHasTTY checks if a container was created with TTY enabled.
func (b *ContainerBackend) containerHasTTY(containerID string) bool {
cmd := exec.Command("docker", "inspect", containerID, "--format", "{{.Config.Tty}}")
var stdout bytes.Buffer
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return false
}
return strings.TrimSpace(stdout.String()) == "true"
}
// getContainerWorkspace inspects a container to find its workspace mount
func (b *ContainerBackend) getContainerWorkspace(containerID string) string {
cmd := exec.Command("docker", "inspect", containerID, "--format", "{{range .Mounts}}{{if eq .Type \"bind\"}}{{.Source}}:{{.Destination}}\n{{end}}{{end}}")
var stdout bytes.Buffer
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return ""
}
// Look for a bind mount where source == destination (workspace pattern)
lines := strings.Split(strings.TrimSpace(stdout.String()), "\n")
for _, line := range lines {
parts := strings.Split(line, ":")
if len(parts) == 2 && parts[0] == parts[1] && strings.HasPrefix(parts[0], "/") {
return parts[0]
}
}
return ""
}
// Remove removes a container by ID
func (b *ContainerBackend) Remove(containerID string) error {
zlog.Info("removing docker container",
zap.String("container_id", containerID))
// First try to stop if running
stopCmd := exec.Command("docker", "stop", containerID)
_ = stopCmd.Run() // Ignore error - container might not be running
// Remove the container and its anonymous volumes (e.g. exclude_dirs shadows)
cmd := exec.Command("docker", "rm", "-v", containerID)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker rm failed: %w (stderr: %s)", err, stderr.String())
}
zlog.Info("docker container removed",
zap.String("container_id", containerID))
return nil
}
// RemoveVolume removes the persistence volume for a workspace
func (b *ContainerBackend) RemoveVolume(workspaceDir string, agentType AgentType) error {
volumeName := b.volumeName(workspaceDir, agentType)
zlog.Info("removing persistence volume", zap.String("volume", volumeName))
cmd := exec.Command("docker", "volume", "rm", volumeName)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("docker volume rm failed: %w (stderr: %s)", err, stderr.String())
}
return nil
}
// Cleanup removes all backend-specific resources for a workspace
func (b *ContainerBackend) Cleanup(workspaceDir string) error {
absPath, err := filepath.Abs(workspaceDir)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
// Load project config to determine agent type
projectConfig, _, err := GetProjectConfig(absPath)
if err != nil {
zlog.Warn("failed to load project config for cleanup", zap.Error(err))
// Continue with default agent
projectConfig = &ProjectConfig{}
}
agentType := AgentType(projectConfig.Agent)
if agentType == "" {
agentType = DefaultAgent
}
// Remove .sbox directory
sboxDir := filepath.Join(absPath, ".sbox")
if err := os.RemoveAll(sboxDir); err != nil {
zlog.Warn("failed to remove .sbox directory", zap.String("path", sboxDir), zap.Error(err))
// Continue to remove volume
} else {
zlog.Info(".sbox directory removed", zap.String("path", sboxDir))
}
// Remove persistence volume
if err := b.RemoveVolume(workspaceDir, agentType); err != nil {
zlog.Warn("failed to remove persistence volume", zap.Error(err))
// Non-fatal - volume might not exist
}
return nil
}
// SaveCache is a no-op for container backend - uses named volumes for persistence
func (b *ContainerBackend) SaveCache(workspaceDir string, agentType AgentType) error {
// Container backend uses named volumes that automatically persist across container restarts
zlog.Debug("container backend uses volumes, no cache save needed")
return nil
}
// detectGitWorktree checks if workspaceDir is a git linked worktree.
// A linked worktree has a .git file (not directory) pointing to the actual gitdir.
// Returns the main repository root and true when detected, otherwise empty string and false.
func detectGitWorktree(workspaceDir string) (string, bool) {
gitPath := filepath.Join(workspaceDir, ".git")
info, err := os.Stat(gitPath)
if err != nil || info.IsDir() {
return "", false
}
content, err := os.ReadFile(gitPath)
if err != nil {
return "", false
}
gitdir, ok := strings.CutPrefix(strings.TrimSpace(string(content)), "gitdir: ")
if !ok {
return "", false
}
if !filepath.IsAbs(gitdir) {
gitdir = filepath.Join(workspaceDir, gitdir)
}
gitdir = filepath.Clean(gitdir)
// The commondir file inside the gitdir points to the main .git directory.
commondirBytes, err := os.ReadFile(filepath.Join(gitdir, "commondir"))
if err != nil {
// Fallback: gitdir is typically .git/worktrees/<name> — go 3 levels up.
return filepath.Dir(filepath.Dir(filepath.Dir(gitdir))), true
}
commondir := strings.TrimSpace(string(commondirBytes))
if !filepath.IsAbs(commondir) {
commondir = filepath.Join(gitdir, commondir)
}
// commondir is the main .git directory; its parent is the main repo root.
return filepath.Dir(filepath.Clean(commondir)), true
}
// getDockerSocketPath returns the Docker socket path to mount.
// Priority:
// 1. SBOX_DOCKER_SOCKET environment variable (explicit override)
// 2. Platform-specific default paths
func getDockerSocketPath() string {
// Check for explicit override
if envPath := os.Getenv(DockerSocketEnvVar); envPath != "" {
if _, err := os.Stat(envPath); err == nil {
return envPath
}
zlog.Warn("SBOX_DOCKER_SOCKET path does not exist", zap.String("path", envPath))
}
// Platform-specific defaults
var candidates []string
switch runtime.GOOS {
case "darwin":
// macOS: Docker Desktop uses different locations
homeDir, _ := os.UserHomeDir()
if homeDir != "" {
candidates = append(candidates, filepath.Join(homeDir, ".docker", "run", "docker.sock"))
}
candidates = append(candidates, "/var/run/docker.sock")
case "linux":
candidates = []string{"/var/run/docker.sock"}
default:
// Fallback for other platforms
candidates = []string{"/var/run/docker.sock"}
}
// Return first existing socket
for _, path := range candidates {
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}