-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentrypoint.go
More file actions
2263 lines (1916 loc) · 78.1 KB
/
entrypoint.go
File metadata and controls
2263 lines (1916 loc) · 78.1 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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sbox
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"os"
"context"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"slices"
"sort"
"strings"
"syscall"
"time"
"github.com/kaptinlin/jsonmerge"
cli "github.com/streamingfast/cli"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
// entrypointLogFile is the path for entrypoint debug logging
const entrypointLogFile = "/tmp/sbox-entrypoint.log"
// elog is the entrypoint file logger (initialized by initEntrypointLog)
var elog *slog.Logger
// initEntrypointLog initializes the file logger for entrypoint debugging.
// Logs are appended to /tmp/sbox-entrypoint.log
func initEntrypointLog() func() {
f, err := os.OpenFile(entrypointLogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
// Can't log to file, use a no-op logger
elog = slog.New(slog.NewTextHandler(io.Discard, nil))
return func() {}
}
// Write separator for new run (extra blank line before makes consecutive runs easy to spot)
fmt.Fprintf(f, "\n\n========== sbox entrypoint new run at %s ==========\n", time.Now().Format(time.RFC3339))
elog = slog.New(slog.NewTextHandler(f, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
return func() { f.Close() }
}
// logEnvironment logs relevant environment variables for debugging
func logEnvironment() {
env := os.Environ()
sort.Strings(env)
// Log interesting env vars
interesting := []string{
"HOME", "USER", "PWD", "SHELL",
"WORKSPACE_DIR",
"CLAUDE", "CLAUDECODE", "IS_SANDBOX",
"PATH",
}
elog.Info("environment snapshot")
for _, key := range interesting {
if val := os.Getenv(key); val != "" {
elog.Debug("env", "key", key, "value", val)
}
}
// Log all env vars at trace level (as debug with prefix)
elog.Debug("full environment", "count", len(env))
for _, e := range env {
elog.Debug("env.full", "entry", e)
}
}
// EntrypointConfigVersion is the current version of the entrypoint config format.
// Increment this when making breaking changes to the config structure.
const EntrypointConfigVersion = 1
// EntrypointConfig is the configuration file exchanged between `sbox run` (host)
// and `sbox entrypoint` (container). It's written to .sbox/entrypoint.yaml.
type EntrypointConfig struct {
// Version is the config format version for compatibility checking
Version int `yaml:"version"`
// Plugins to install in the sandbox
Plugins []EntrypointPlugin `yaml:"plugins,omitempty"`
// Agents to install in the sandbox
Agents []EntrypointAgent `yaml:"agents,omitempty"`
// Agent specifies which AI agent to run ("claude" or "opencode")
Agent string `yaml:"agent,omitempty"`
// Prompt is an optional prompt to pass to the agent via -p flag.
// When set, the agent runs non-interactively with this prompt.
// Used by `sbox loop` to pass the loop prompt to the agent.
Prompt string `yaml:"prompt,omitempty"`
// Loop mode fields — when LoopMode is true, the entrypoint runs the agent
// in a loop until the goal is confirmed complete.
LoopMode bool `yaml:"loop_mode,omitempty"`
MaxIterations int `yaml:"max_iterations,omitempty"`
LoopConfirmations int `yaml:"loop_confirmations,omitempty"`
// OpenCode contains settings specific to the OpenCode agent.
OpenCode *OpenCodeSettings `yaml:"opencode,omitempty"`
// Developer contains developer-oriented settings for debugging and development
Developer *DeveloperSettings `yaml:"developer,omitempty"`
}
// OpenCodeSettings contains entrypoint settings specific to the OpenCode agent.
type OpenCodeSettings struct {
// LoadClaudeSkills enables converting installed Claude Code plugin SKILL.md files
// into OpenCode rules at startup.
LoadClaudeSkills bool `yaml:"load_claude_skills,omitempty"`
}
// DeveloperSettings contains developer-oriented settings for debugging and development.
type DeveloperSettings struct {
// StartupDelay delays agent startup inside the sandbox.
// If not set (nil), no delay. If 0, infinite delay (wait forever).
// Otherwise, waits for the specified duration before starting the agent.
StartupDelay *Duration `yaml:"startup_delay,omitempty"`
}
// EntrypointPlugin describes a plugin to be installed in the sandbox
type EntrypointPlugin struct {
// Name is the plugin identifier (e.g., "test-plugin@official")
Name string `yaml:"name"`
// Path is the relative path within .sbox/ where the plugin files are stored
// e.g., "plugins/official/test-plugin/abc123"
Path string `yaml:"path"`
// Version is the plugin version string
Version string `yaml:"version,omitempty"`
// PackageVersion is the package/commit hash
PackageVersion string `yaml:"package_version,omitempty"`
}
// EntrypointAgent describes an agent to be installed in the sandbox
type EntrypointAgent struct {
// Name is the agent name (filename without .json extension)
Name string `yaml:"name"`
// Path is the relative path within .sbox/ where the agent file is stored
// e.g., "agents/my-agent.json"
Path string `yaml:"path"`
}
// WriteEntrypointConfig writes the entrypoint configuration to .sbox/entrypoint.yaml
func WriteEntrypointConfig(workspaceDir string, config *EntrypointConfig) error {
config.Version = EntrypointConfigVersion
sboxDir := filepath.Join(workspaceDir, ".sbox")
if err := os.MkdirAll(sboxDir, 0755); err != nil {
return fmt.Errorf("failed to create .sbox directory: %w", err)
}
configPath := filepath.Join(sboxDir, "entrypoint.yaml")
data, err := yaml.Marshal(config)
if err != nil {
return fmt.Errorf("failed to marshal entrypoint config: %w", err)
}
if err := os.WriteFile(configPath, data, 0644); err != nil {
return fmt.Errorf("failed to write entrypoint config: %w", err)
}
return nil
}
// ReadEntrypointConfig reads the entrypoint configuration from .sbox/entrypoint.yaml
// Returns an error if the config version is incompatible.
func ReadEntrypointConfig(workspaceDir string) (*EntrypointConfig, error) {
configPath := filepath.Join(workspaceDir, ".sbox", "entrypoint.yaml")
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read entrypoint config: %w", err)
}
var config EntrypointConfig
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse entrypoint config: %w", err)
}
if config.Version == 0 {
return nil, fmt.Errorf("entrypoint config missing version field")
}
if config.Version > EntrypointConfigVersion {
return nil, fmt.Errorf("entrypoint config version %d is newer than supported version %d; please update sbox", config.Version, EntrypointConfigVersion)
}
// Future: handle migration from older versions if needed
// For now, we only support the current version
return &config, nil
}
// WriteEntrypointEnv writes resolved environment variables to .sbox/env
// Each line is in the format KEY=value (already resolved, no passthrough)
func WriteEntrypointEnv(workspaceDir string, envs []string) error {
sboxDir := filepath.Join(workspaceDir, ".sbox")
if err := os.MkdirAll(sboxDir, 0755); err != nil {
return fmt.Errorf("failed to create .sbox directory: %w", err)
}
envPath := filepath.Join(sboxDir, "env")
// Build content with resolved values
var content string
for _, env := range envs {
content += env + "\n"
}
if err := os.WriteFile(envPath, []byte(content), 0644); err != nil {
return fmt.Errorf("failed to write env file: %w", err)
}
return nil
}
// ReadEntrypointEnv reads environment variables from .sbox/env
// Returns a slice of KEY=value strings
func ReadEntrypointEnv(workspaceDir string) ([]string, error) {
envPath := filepath.Join(workspaceDir, ".sbox", "env")
data, err := os.ReadFile(envPath)
if err != nil {
if os.IsNotExist(err) {
return nil, nil // No env file is OK
}
return nil, fmt.Errorf("failed to read env file: %w", err)
}
var envs []string
for _, line := range splitLines(string(data)) {
line = trimSpace(line)
if line != "" && !hasPrefix(line, "#") {
envs = append(envs, line)
}
}
return envs, nil
}
// Helper functions to avoid importing strings package for simple operations
func splitLines(s string) []string {
var lines []string
start := 0
for i := 0; i < len(s); i++ {
if s[i] == '\n' {
lines = append(lines, s[start:i])
start = i + 1
}
}
if start < len(s) {
lines = append(lines, s[start:])
}
return lines
}
func trimSpace(s string) string {
start := 0
end := len(s)
for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\r') {
start++
}
for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\r') {
end--
}
return s[start:end]
}
func hasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
}
// SandboxPersistentEnvFile is the path to the persistent environment file in the sandbox.
// We use /etc/profile.d/ rather than /etc/sandbox-persistent.sh because:
// - /etc/sandbox-persistent.sh is managed by the Docker sandbox infrastructure (CLAUDE_ENV_FILE)
// and may have permissions that prevent the agent user from writing to it
// - /etc/profile.d/*.sh files are sourced by login shells (bash -l) which is the recommended
// invocation pattern in the sandbox CLAUDE.md
const SandboxPersistentEnvFile = "/etc/profile.d/sbox-env.sh"
// ReadWorkspacePath returns the workspace directory.
// Docker sandbox sets PWD and WORKSPACE_DIR to the workspace path.
// Returns empty string if workspace cannot be determined.
func ReadWorkspacePath() string {
// WORKSPACE_DIR is explicitly set by docker sandbox
if dir := os.Getenv("WORKSPACE_DIR"); dir != "" {
return dir
}
// Fallback to PWD
if dir := os.Getenv("PWD"); dir != "" {
return dir
}
// Last resort: get current working directory
if dir, err := os.Getwd(); err == nil {
return dir
}
return ""
}
// DefaultSandboxClaudeHome is the default Claude home directory inside the sandbox.
// Docker sandbox may mount the host's .claude at the host path instead.
// Use FindClaudeHome() to locate the actual directory.
const DefaultSandboxClaudeHome = "/home/agent/.claude"
// FindClaudeHome locates Claude's config directory inside the sandbox.
// Docker sandbox mounts the host's .claude at the host path (e.g., /Users/username/.claude).
// We search common locations to find where it actually is.
func FindAgentHome(agentType AgentType) string {
spec := GetAgentSpec(agentType)
configDirName := spec.ConfigDirName()
// Check environment variable first (for backwards compatibility with CLAUDE_CONFIG_DIR)
envVar := strings.ToUpper(spec.BinaryName()) + "_CONFIG_DIR"
if dir := os.Getenv(envVar); dir != "" {
if _, err := os.Stat(dir); err == nil {
return dir
}
}
// Check default location
defaultHome := filepath.Join("/home/agent", configDirName)
if _, err := os.Stat(defaultHome); err == nil {
return defaultHome
}
// Search /Users (macOS host mounts)
entries, _ := os.ReadDir("/Users")
for _, e := range entries {
if e.IsDir() {
agentDir := filepath.Join("/Users", e.Name(), configDirName)
if _, err := os.Stat(agentDir); err == nil {
return agentDir
}
}
}
// Search /home (Linux host mounts)
entries, _ = os.ReadDir("/home")
for _, e := range entries {
if e.IsDir() && e.Name() != "agent" { // Skip agent, already checked
agentDir := filepath.Join("/home", e.Name(), configDirName)
if _, err := os.Stat(agentDir); err == nil {
return agentDir
}
}
}
// Fallback to default
return defaultHome
}
// SboxEntrypointMarkerFile is written when sbox entrypoint runs successfully.
// Claude can check this file to verify the entrypoint ran.
const SboxEntrypointMarkerFile = "/tmp/sbox-entrypoint-ran"
// ClaudeCacheDir is the subdirectory in .sbox/ where we cache the .claude folder
// for persistence across sandbox recreations.
const ClaudeCacheDir = "claude-cache"
// OpenCodeCacheDir is the subdirectory in .sbox/ where we cache the .config/opencode folder
// for persistence across sandbox recreations.
const OpenCodeCacheDir = "opencode-cache"
// OpenCodeShareCacheDir is the subdirectory in .sbox/ where we cache the .local/share/opencode folder
// for persistence across sandbox recreations.
const OpenCodeShareCacheDir = "opencode-share-cache"
// RunEntrypoint executes the entrypoint logic inside the sandbox.
// It reads the configuration from .sbox/, sets up plugins/agents/env,
// then execs claude with the provided arguments.
func RunEntrypoint(args []string) error {
// Initialize file logger (note: log file won't be closed since we exec)
_ = initEntrypointLog()
elog.Info("=== RunEntrypoint starting ===", "version", cli.GetDisplayVersion(Version), "args", args)
logEnvironment()
zlog.Info("running sbox entrypoint")
// Read workspace path from env var set by wrapper
workspaceDir := ReadWorkspacePath()
elog.Info("workspace lookup", "WORKSPACE_DIR", os.Getenv("WORKSPACE_DIR"), "PWD", os.Getenv("PWD"), "result", workspaceDir)
if workspaceDir == "" {
// No workspace found, just exec default agent directly
elog.Warn("workspace directory not found, exec default agent directly")
zlog.Info("workspace directory not found, starting default agent directly")
return execAgent(DefaultAgent, args, nil)
}
elog.Info("found workspace directory", "path", workspaceDir)
zlog.Info("found workspace directory", zap.String("path", workspaceDir))
// Check for dev override binary. If .sbox/sbox-dev exists, exec it
// to continue the entrypoint with a newer version of sbox. This enables
// fast iteration without rebuilding the Docker image.
if err := maybeExecDevBinary(workspaceDir, args); err != nil {
// maybeExecDevBinary only returns on error (exec replaces the process on success)
return err
}
// Check .sbox directory contents
sboxDir := filepath.Join(workspaceDir, ".sbox")
if entries, err := os.ReadDir(sboxDir); err == nil {
var files []string
for _, e := range entries {
files = append(files, e.Name())
}
elog.Info(".sbox directory contents", "path", sboxDir, "files", files)
} else {
elog.Warn(".sbox directory not readable", "path", sboxDir, "error", err)
}
// Read entrypoint config
configPath := filepath.Join(sboxDir, "entrypoint.yaml")
elog.Info("reading entrypoint config", "path", configPath)
config, err := ReadEntrypointConfig(workspaceDir)
if err != nil {
// If no config, just exec default agent directly (backwards compatibility)
if errors.Is(err, os.ErrNotExist) {
elog.Warn("no entrypoint config found, exec default agent directly", "path", configPath)
zlog.Info("no entrypoint config found, starting default agent directly")
return execAgent(DefaultAgent, args, nil)
}
elog.Error("failed to read entrypoint config", "error", err)
return fmt.Errorf("failed to read entrypoint config: %w", err)
}
// Default to claude if no agent specified
agentType := config.Agent
if agentType == "" {
agentType = string(AgentClaude)
}
elog.Info("loaded entrypoint config",
"version", config.Version,
"plugins", len(config.Plugins),
"agents", len(config.Agents),
"agent", agentType)
zlog.Info("loaded entrypoint config",
zap.Int("version", config.Version),
zap.Int("plugins", len(config.Plugins)),
zap.Int("agents", len(config.Agents)),
zap.String("agent", agentType))
// Disable the agent's built-in auto-updater so it doesn't overwrite our shim
// wrapper. We handle updates ourselves via a background updater that correctly
// re-shims after each update.
spec := GetAgentSpec(AgentType(agentType))
if envVars := spec.DisableAutoUpdateEnv(); envVars != nil {
for k, v := range envVars {
os.Setenv(k, v)
elog.Info("set auto-update disable env var", "key", k, "value", v)
}
}
// Log plugin details
for i, p := range config.Plugins {
elog.Debug("plugin", "index", i, "name", p.Name, "path", p.Path)
}
// Log agent details
for i, a := range config.Agents {
elog.Debug("agent", "index", i, "name", a.Name, "path", a.Path)
}
// Find agent home
agent := AgentType(agentType)
agentHome := FindAgentHome(agent)
elog.Info("agent home directory", "path", agentHome, "agent", agentType)
// Restore agent cache if present (for persistence across recreations)
elog.Info("checking for agent cache to restore")
if err := restoreAgentCache(workspaceDir, agent, agentHome); err != nil {
elog.Warn("failed to restore agent cache", "error", err)
// Non-fatal - continue anyway
}
// Setup CLAUDE.md/AGENTS.md (copy from .sbox to agent home)
elog.Info("setting up CLAUDE.md/AGENTS.md")
if err := setupRules(workspaceDir, agent); err != nil {
elog.Error("failed to setup rules file", "error", err)
// Non-fatal - continue anyway
}
// Setup plugins
elog.Info("setting up plugins", "count", len(config.Plugins))
if err := setupPlugins(workspaceDir, config.Plugins); err != nil {
elog.Error("failed to setup plugins", "error", err)
return fmt.Errorf("failed to setup plugins: %w", err)
}
// Setup agents
elog.Info("setting up agents", "count", len(config.Agents))
if err := setupAgents(workspaceDir, agent, config.Agents); err != nil {
elog.Error("failed to setup agents", "error", err)
return fmt.Errorf("failed to setup agents: %w", err)
}
// Setup Claude settings files — merge with existing sandbox config so that
// sandbox-side changes (e.g. model selection, theme) are preserved while
// host-side updates (e.g. MCP servers) are applied.
if agent == AgentClaude {
claudeSettingsSrc := filepath.Join(workspaceDir, ".sbox", "claude-settings.json")
if _, err := os.Stat(claudeSettingsSrc); err == nil {
claudeSettingsDst := filepath.Join(agentHome, "settings.json")
elog.Info("merging claude settings.json into agent home", "src", claudeSettingsSrc, "dst", claudeSettingsDst)
if err := mergeConfigFile(claudeSettingsSrc, claudeSettingsDst); err != nil {
elog.Warn("failed to merge claude settings.json", "error", err)
zlog.Warn("failed to merge claude settings.json into agent home", zap.Error(err))
// Non-fatal - continue anyway
} else {
elog.Info("successfully merged claude settings.json")
zlog.Info("merged claude settings.json into agent home", zap.String("dst", claudeSettingsDst))
}
// Always enforce bypass-permissions mode after merge — the sandbox must
// run without permission prompts regardless of what the cached or host
// config had.
for key, val := range map[string]any{
"defaultMode": "bypassPermissions",
"bypassPermissionsModeAccepted": true,
"skipDangerousModePermissionPrompt": true,
} {
if err := enforceJSONField(claudeSettingsDst, key, val); err != nil {
elog.Warn("failed to enforce field in settings.json", "key", key, "error", err)
}
}
} else {
elog.Debug("claude-settings.json not found in .sbox, skipping", "path", claudeSettingsSrc)
zlog.Debug("claude-settings.json not found in .sbox, skipping", zap.String("path", claudeSettingsSrc))
}
claudeSettingsLocalSrc := filepath.Join(workspaceDir, ".sbox", "claude-settings.local.json")
if _, err := os.Stat(claudeSettingsLocalSrc); err == nil {
claudeSettingsLocalDst := filepath.Join(agentHome, "settings.local.json")
elog.Info("merging claude settings.local.json into agent home", "src", claudeSettingsLocalSrc, "dst", claudeSettingsLocalDst)
if err := mergeConfigFile(claudeSettingsLocalSrc, claudeSettingsLocalDst); err != nil {
elog.Warn("failed to merge claude settings.local.json", "error", err)
zlog.Warn("failed to merge claude settings.local.json into agent home", zap.Error(err))
// Non-fatal - continue anyway
} else {
elog.Info("successfully merged claude settings.local.json")
zlog.Info("merged claude settings.local.json into agent home", zap.String("dst", claudeSettingsLocalDst))
}
} else {
elog.Debug("claude-settings.local.json not found in .sbox, skipping", "path", claudeSettingsLocalSrc)
zlog.Debug("claude-settings.local.json not found in .sbox, skipping", zap.String("path", claudeSettingsLocalSrc))
}
}
// Setup OpenCode config and auth files
if agent == AgentOpenCode {
// Setup opencode.json (config file) — merge with existing sandbox config
// so that sandbox-side changes (e.g. model selection) are preserved while
// host-side updates (e.g. permissions) are applied.
opencodeConfigSrc := filepath.Join(workspaceDir, ".sbox", "opencode.json")
if _, err := os.Stat(opencodeConfigSrc); err == nil {
opencodeConfigDst := filepath.Join(agentHome, "opencode.json")
elog.Info("merging opencode.json into agent home", "src", opencodeConfigSrc, "dst", opencodeConfigDst)
if err := mergeConfigFile(opencodeConfigSrc, opencodeConfigDst); err != nil {
elog.Warn("failed to merge opencode.json", "error", err)
zlog.Warn("failed to merge opencode.json into agent home", zap.Error(err))
// Non-fatal - continue anyway
} else {
elog.Info("successfully merged opencode.json")
zlog.Info("merged opencode.json into agent home", zap.String("dst", opencodeConfigDst))
}
// Always enforce full permissions after merge — the sandbox must run
// with all permissions allowed regardless of what the cached or host
// config had.
if err := enforceJSONField(opencodeConfigDst, "permission", map[string]any{"*": "allow"}); err != nil {
elog.Warn("failed to enforce permissions in opencode.json", "error", err)
}
} else {
elog.Debug("opencode.json not found in .sbox, skipping", "path", opencodeConfigSrc)
zlog.Debug("opencode.json not found in .sbox, skipping", zap.String("path", opencodeConfigSrc))
}
// Setup tui.json (TUI config file) — merge with existing sandbox config
opencodeTUIConfigSrc := filepath.Join(workspaceDir, ".sbox", "tui.json")
if _, err := os.Stat(opencodeTUIConfigSrc); err == nil {
opencodeTUIConfigDst := filepath.Join(agentHome, "tui.json")
elog.Info("merging tui.json into agent home", "src", opencodeTUIConfigSrc, "dst", opencodeTUIConfigDst)
if err := mergeConfigFile(opencodeTUIConfigSrc, opencodeTUIConfigDst); err != nil {
elog.Warn("failed to merge tui.json", "error", err)
zlog.Warn("failed to merge tui.json into agent home", zap.Error(err))
// Non-fatal - continue anyway
} else {
elog.Info("successfully merged tui.json")
zlog.Info("merged tui.json into agent home", zap.String("dst", opencodeTUIConfigDst))
}
} else {
elog.Debug("tui.json not found in .sbox, skipping", "path", opencodeTUIConfigSrc)
zlog.Debug("tui.json not found in .sbox, skipping", zap.String("path", opencodeTUIConfigSrc))
}
// Setup auth.json (authentication file)
opencodeAuthSrc := filepath.Join(workspaceDir, ".sbox", "opencode-auth.json")
if _, err := os.Stat(opencodeAuthSrc); err == nil {
// OpenCode auth goes in XDG data directory: ~/.local/share/opencode/auth.json
authDir := filepath.Join("/home/agent", ".local", "share", "opencode")
if err := os.MkdirAll(authDir, 0755); err != nil {
elog.Warn("failed to create auth directory", "dir", authDir, "error", err)
zlog.Warn("failed to create opencode auth directory", zap.String("dir", authDir), zap.Error(err))
} else {
opencodeAuthDst := filepath.Join(authDir, "auth.json")
elog.Info("copying opencode auth.json to data directory", "src", opencodeAuthSrc, "dst", opencodeAuthDst)
if err := copyFile(opencodeAuthSrc, opencodeAuthDst); err != nil {
elog.Warn("failed to copy opencode auth.json", "error", err)
zlog.Warn("failed to copy opencode auth.json", zap.Error(err))
// Non-fatal - continue anyway
} else {
elog.Info("successfully copied opencode auth.json")
zlog.Info("copied opencode auth.json to data directory", zap.String("dst", opencodeAuthDst))
}
}
} else {
elog.Debug("opencode auth.json not found in .sbox, skipping", "path", opencodeAuthSrc)
zlog.Debug("opencode auth.json not found in .sbox, skipping", zap.String("path", opencodeAuthSrc))
}
// Restore share cache AFTER individual file setup so cached state from a previous
// session takes precedence over the initially seeded files (e.g. auth.json).
if err := restoreOpenCodeShareCache(workspaceDir); err != nil {
elog.Warn("failed to restore opencode share cache", "error", err)
// Non-fatal - continue anyway
}
// Convert Claude Code plugin SKILL.md files to OpenCode rules (opt-in).
// Done after cache restore so generated rules always overwrite any stale cached versions.
if config.OpenCode != nil && config.OpenCode.LoadClaudeSkills {
if err := setupOpencodeSkills(workspaceDir, agentHome); err != nil {
elog.Warn("failed to setup opencode skills from claude plugins", "error", err)
// Non-fatal - continue anyway
}
}
}
// Load environment variables
elog.Info("loading environment variables")
if err := loadEntrypointEnv(workspaceDir); err != nil {
elog.Error("failed to load environment", "error", err)
return fmt.Errorf("failed to load environment: %w", err)
}
// Collect plugin directories for --plugin-dir flags
var pluginDirs []string
for _, plugin := range config.Plugins {
// Plugin path is relative to .sbox/, e.g. "plugins/claude-plugins-official/code-simplifier/1.0.0"
pluginDir := filepath.Join(workspaceDir, ".sbox", plugin.Path)
if _, err := os.Stat(pluginDir); err == nil {
pluginDirs = append(pluginDirs, pluginDir)
elog.Info("adding plugin directory", "name", plugin.Name, "path", pluginDir)
} else {
elog.Warn("plugin directory not found", "name", plugin.Name, "path", pluginDir)
}
}
elog.Info("=== setup complete, exec agent ===", "agent", agentType, "pluginDirs", pluginDirs)
// Apply startup delay if configured (developer setting)
if config.Developer != nil && config.Developer.StartupDelay != nil {
delay := config.Developer.StartupDelay.Duration
if delay == 0 {
elog.Info("startup delay set to 0, waiting forever (use Ctrl+C to cancel)")
fmt.Println("[sbox] startup-delay is 0, waiting forever without starting agent (Ctrl+C to cancel)")
select {} // Block forever
} else {
elog.Info("applying startup delay", "duration", delay)
fmt.Printf("[sbox] startup-delay: waiting %s before starting agent...\n", delay)
time.Sleep(delay)
elog.Info("startup delay complete, proceeding")
}
}
// Loop mode: run the agent repeatedly until the goal is confirmed complete.
// The entrypoint handles all iterations internally so the sandbox stays warm.
if config.LoopMode && config.Prompt != "" {
elog.Info("entering loop mode", "prompt_length", len(config.Prompt), "max_iterations", config.MaxIterations)
return runLoop(config, AgentType(agentType), args, pluginDirs, workspaceDir)
}
// Single prompt mode (non-loop): run agent once with stream transformer.
if config.Prompt != "" {
elog.Info("adding prompt from entrypoint config", "prompt_length", len(config.Prompt))
// Agent-specific flags for prompt mode, then positional prompt last
args = append(spec.PromptArgs(), args...)
args = append(args, config.Prompt)
return runAgentWithStreamTransformer(AgentType(agentType), args, pluginDirs)
}
// For OpenCode, if no args provided, pass the workspace directory
// OpenCode expects: opencode [project]
agentTypeEnum := AgentType(agentType)
if agentTypeEnum == AgentOpenCode && len(args) == 0 {
args = []string{workspaceDir}
elog.Info("adding workspace path as first arg for OpenCode", "workspace", workspaceDir)
}
// Run the agent as a child process with signal forwarding and background updates
return runAgent(agentTypeEnum, args, pluginDirs, workspaceDir)
}
// setupRules copies .sbox/CLAUDE.md to agent home/CLAUDE.md or AGENTS.md
// depending on the agent type (Claude uses CLAUDE.md, OpenCode uses AGENTS.md)
func setupRules(workspaceDir string, agentType AgentType) error {
srcPath := filepath.Join(workspaceDir, ".sbox", "CLAUDE.md")
// Check if source exists
if _, err := os.Stat(srcPath); os.IsNotExist(err) {
zlog.Debug("no rules file in .sbox, skipping")
return nil
}
agentHome := FindAgentHome(agentType)
// Determine destination filename based on agent type
// Claude uses CLAUDE.md for backward compatibility
// OpenCode uses AGENTS.md as the standard name
var dstFilename string
if agentType == AgentOpenCode {
dstFilename = "AGENTS.md"
} else {
dstFilename = "CLAUDE.md"
}
dstPath := filepath.Join(agentHome, dstFilename)
// Ensure agent home exists
if err := os.MkdirAll(agentHome, 0755); err != nil {
return fmt.Errorf("failed to create agent home: %w", err)
}
if err := copyFile(srcPath, dstPath); err != nil {
return fmt.Errorf("failed to copy %s: %w", dstFilename, err)
}
zlog.Info("installed agent instructions file",
zap.String("agent", string(agentType)),
zap.String("filename", dstFilename),
zap.String("src", srcPath),
zap.String("dst", dstPath))
return nil
}
// setupPlugins is now a no-op - plugins are loaded via --plugin-dir flag
// The plugin directories in .sbox/plugins/ are passed directly to claude
func setupPlugins(workspaceDir string, plugins []EntrypointPlugin) error {
// Nothing to do - plugins are loaded via --plugin-dir from .sbox/plugins/
zlog.Debug("plugins will be loaded via --plugin-dir", zap.Int("count", len(plugins)))
return nil
}
// setupAgents copies agents from .sbox/agents/ to agent home/agents/
func setupAgents(workspaceDir string, agentType AgentType, agents []EntrypointAgent) error {
if len(agents) == 0 {
zlog.Debug("no agents to setup")
return nil
}
agentHome := FindAgentHome(agentType)
zlog.Info("using agent home directory for agents", zap.String("path", agentHome), zap.String("agent", string(agentType)))
// Ensure agent home exists with proper permissions
if err := os.MkdirAll(agentHome, 0755); err != nil {
return fmt.Errorf("failed to create agent home directory: %w", err)
}
agentsDir := filepath.Join(agentHome, "agents")
if err := os.MkdirAll(agentsDir, 0755); err != nil {
return fmt.Errorf("failed to create agents directory: %w", err)
}
for _, agent := range agents {
srcPath := filepath.Join(workspaceDir, ".sbox", agent.Path)
// Use the original filename from Path to preserve extension (.md or .json)
dstPath := filepath.Join(agentsDir, filepath.Base(agent.Path))
zlog.Debug("copying agent",
zap.String("name", agent.Name),
zap.String("src", srcPath),
zap.String("dst", dstPath))
if err := copyFile(srcPath, dstPath); err != nil {
zlog.Warn("failed to copy agent, skipping",
zap.String("name", agent.Name),
zap.Error(err))
continue
}
zlog.Info("agent installed",
zap.String("name", agent.Name),
zap.String("path", dstPath))
}
return nil
}
// setupOpencodeSkills converts Claude Code plugin SKILL.md files into OpenCode rules files.
// OpenCode rules are always-on markdown files in ~/.config/opencode/rules/ that are included
// in the system prompt automatically, bridging Claude Code's on-demand skill concept to OpenCode.
//
// For each installed plugin, skill files at .sbox/plugins/<publisher>/<plugin>/<ver>/skills/<skill>/SKILL.md
// are stripped of their YAML frontmatter and written to <agentHome>/rules/<plugin>-<skill>.md.
// !command interpolation in the skill body is left as-is for the agent to handle.
func setupOpencodeSkills(workspaceDir string, agentHome string) error {
pluginsDir := filepath.Join(workspaceDir, ".sbox", "claude-plugins")
rulesDir := filepath.Join(agentHome, "rules")
if err := os.MkdirAll(rulesDir, 0755); err != nil {
return fmt.Errorf("failed to create opencode rules directory: %w", err)
}
// Pattern: <publisher>/<plugin-name>/<version>/skills/<skill-name>/SKILL.md
pattern := filepath.Join(pluginsDir, "*", "*", "*", "skills", "*", "SKILL.md")
matches, err := filepath.Glob(pattern)
if err != nil {
return fmt.Errorf("failed to glob skill files: %w", err)
}
count := 0
for _, skillPath := range matches {
rel, err := filepath.Rel(pluginsDir, skillPath)
if err != nil {
continue
}
// parts: [publisher, plugin-name, version, "skills", skill-name, "SKILL.md"]
parts := strings.SplitN(rel, string(filepath.Separator), 7)
if len(parts) < 6 {
continue
}
pluginName := parts[1]
skillName := parts[4]
content, err := os.ReadFile(skillPath)
if err != nil {
zlog.Warn("failed to read skill file, skipping", zap.String("path", skillPath), zap.Error(err))
continue
}
ruleFileName := pluginName + "-" + skillName + ".md"
rulePath := filepath.Join(rulesDir, ruleFileName)
if err := os.WriteFile(rulePath, []byte(stripFrontmatter(string(content))), 0644); err != nil {
zlog.Warn("failed to write opencode rule file, skipping", zap.String("path", rulePath), zap.Error(err))
continue
}
count++
elog.Info("converted skill to opencode rule", "plugin", pluginName, "skill", skillName, "rule", ruleFileName)
}
elog.Info("setup opencode skills as rules", "count", count, "rules_dir", rulesDir)
return nil
}
// stripFrontmatter removes YAML frontmatter (the leading ---...--- block) from markdown content.
// Returns the content unchanged if no frontmatter is present.
func stripFrontmatter(content string) string {
if !strings.HasPrefix(content, "---") {
return content
}
rest := content[3:]
if strings.HasPrefix(rest, "\n") {
rest = rest[1:]
}
end := strings.Index(rest, "\n---")
if end < 0 {
return content
}
body := rest[end+4:]
if strings.HasPrefix(body, "\n") {
body = body[1:]
}
return body
}
// SboxDevBinaryEnvVar is set when running via the dev override binary to prevent
// infinite recursion (the dev binary would find itself and try to exec again).
const SboxDevBinaryEnvVar = "SBOX_DEV_ENTRYPOINT"
// maybeExecDevBinary checks for .sbox/sbox-dev and execs it if present.
// Returns nil if no dev binary is found (caller should continue normally).
// On successful exec, this function never returns (process is replaced).
// Returns an error only if the binary exists but cannot be executed.
func maybeExecDevBinary(workspaceDir string, args []string) error {
// Don't recurse: if we ARE the dev binary, skip this check
if os.Getenv(SboxDevBinaryEnvVar) == "1" {
elog.Info("running as dev binary, skipping dev override check")
return nil
}
devBinaryPath := filepath.Join(workspaceDir, ".sbox", "sbox-dev")
if _, err := os.Stat(devBinaryPath); err != nil {
return nil // No dev binary, continue normally
}
elog.Info("found dev override binary, exec'ing it", "path", devBinaryPath)
zlog.Info("found sbox-dev override binary, replacing entrypoint",
zap.String("path", devBinaryPath))
fmt.Fprintf(os.Stderr, "sbox: using dev override binary at %s\n", devBinaryPath)
// Build argv: sbox-dev entrypoint [args...]
argv := append([]string{"sbox-dev", "entrypoint"}, args...)
// Set env var to prevent the dev binary from recursing
env := os.Environ()
env = append(env, SboxDevBinaryEnvVar+"=1")
err := syscall.Exec(devBinaryPath, argv, env)
// syscall.Exec only returns on error
if errors.Is(err, syscall.ENOEXEC) {
return fmt.Errorf(
"sbox-dev binary at %s has wrong architecture (exec format error); "+
"rebuild it for the sandbox platform (linux/%s) with: "+
"GOOS=linux GOARCH=%s go build -o .sbox/sbox-dev ./cmd/sbox",
devBinaryPath, runtime.GOARCH, runtime.GOARCH,
)
}
return fmt.Errorf("failed to exec dev binary %s: %w", devBinaryPath, err)
}
// loadEntrypointEnv reads .sbox/env and sets env vars in the current process.
// It also attempts to write exports to the persistent env file for login shells.
func loadEntrypointEnv(workspaceDir string) error {
envs, err := ReadEntrypointEnv(workspaceDir)
if err != nil {
return err
}
if len(envs) == 0 {
zlog.Debug("no environment variables to load")
return nil
}
// Parse all env vars first and set them in the current process.
// This ensures they're available to the exec'd claude process regardless
// of whether we can write the persistent file.
type envEntry struct {
key, value string
}
var entries []envEntry
for _, env := range envs {
idx := strings.Index(env, "=")
if idx < 0 {
continue // Skip invalid entries
}
key := env[:idx]
value := env[idx+1:]
os.Setenv(key, value)
entries = append(entries, envEntry{key, value})
zlog.Debug("loaded environment variable", zap.String("key", key))
}
// Write to persistent env file so vars are available in login shells (bash -l).
// This is non-fatal: if we can't write the file, env vars are still set in
// the current process and will be inherited by claude via syscall.Exec.
f, err := os.OpenFile(SandboxPersistentEnvFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
zlog.Warn("could not open persistent env file, env vars will only be available via process environment",
zap.String("path", SandboxPersistentEnvFile),
zap.Error(err))
} else {
defer f.Close()
if _, err := f.WriteString("\n# sbox entrypoint environment variables\n"); err != nil {
zlog.Warn("failed to write to persistent env file", zap.Error(err))
} else {
for _, e := range entries {
exportLine := fmt.Sprintf("export %s=%q\n", e.key, e.value)
if _, err := f.WriteString(exportLine); err != nil {
zlog.Warn("failed to write env var to persistent file",
zap.String("key", e.key), zap.Error(err))
break
}
}
}
}