{"repo_name": "container-use", "file_name": "/container-use/cmd/container-use/watch_windows.go", "inference_info": {"prefix_code": "//go:build windows\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org/x/term\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar watchCmd = &cobra.Command{\n\tUse: \"watch\",\n\tShort: \"Watch environment activity in real-time\",\n\tLong: `Continuously display environment activity as agents work.\nShows new commits and environment changes updated every second.\nPress Ctrl+C to stop watching.`,\n\tExample: `# Watch all environment activity\ncontainer-use watch\n\n# Monitor agents while they work\ncontainer-use watch`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\tif _, err := repository.Open(ctx, \".\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Enter alternate screen buffer and hide cursor\n\t\tfmt.Print(\"\\x1b[?1049h\\x1b[?25l\")\n\t\tdefer fmt.Print(\"\\x1b[?25h\\x1b[?1049l\") // restore screen + show cursor\n\n\t\tticker := time.NewTicker(time.Second)\n\t\tdefer ticker.Stop()\n\n\t\t// Run once immediately\n\t\tif err := runGitLogWindows(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tcase <-ticker.C:\n\t\t\t\tif err := runGitLogWindows(ctx); err != nil {\n\t\t\t\t\t// Don't exit on git errors, just display them and continue\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Warning: %v\\n\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n}\n\n// runGitLogWindows executes the git log command with output matching Unix watch format\n", "suffix_code": "\n\nfunc init() {\n\trootCmd.AddCommand(watchCmd)\n}\n", "middle_code": "func runGitLogWindows(ctx context.Context) error {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"\\x1b[H\\x1b[J\")\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"unknown\"\n\t}\n\ttimestamp := time.Now().Format(\"Mon Jan 2 15:04:05 2006\")\n\tgitCommand := \"git log --color=always --remotes=container-use --oneline --graph --decorate\"\n\theaderLine := fmt.Sprintf(\"Every 1.0s: %s\", gitCommand)\n\tterminalWidth := 80\n\tif width, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && width > 0 {\n\t\tterminalWidth = width\n\t}\n\trightPart := fmt.Sprintf(\"%s: %s\", hostname, timestamp)\n\tspacesNeeded := terminalWidth - len(headerLine) - len(rightPart)\n\tif spacesNeeded >= 1 {\n\t\tbuf.WriteString(headerLine + strings.Repeat(\" \", spacesNeeded) + rightPart + \"\\n\")\n\t} else {\n\t\tbuf.WriteString(headerLine + \" \" + rightPart + \"\\n\")\n\t}\n\tbuf.WriteString(\"\\n\") \n\tcmd := exec.CommandContext(ctx, \"git\", \"log\",\n\t\t\"--color=always\",\n\t\t\"--remotes=container-use\",\n\t\t\"--oneline\",\n\t\t\"--graph\",\n\t\t\"--decorate\")\n\tpr, pw, err := os.Pipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create pipe: %w\", err)\n\t}\n\tcmd.Stdout = pw\n\tcmd.Stderr = pw\n\tif err := cmd.Start(); err != nil {\n\t\tpw.Close()\n\t\tpr.Close()\n\t\treturn fmt.Errorf(\"failed to start git log: %w\", err)\n\t}\n\tpw.Close()\n\tscanner := bufio.NewScanner(pr)\n\tfor scanner.Scan() {\n\t\tbuf.WriteString(scanner.Text() + \"\\n\")\n\t}\n\tpr.Close()\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"git log failed: %w\", err)\n\t}\n\tos.Stdout.Write(buf.Bytes())\n\treturn nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/container-use/cmd/container-use/watch_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"time\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n\twatch \"github.com/tiborvass/go-watch\"\n)\n\nvar watchCmd = &cobra.Command{\n\tUse: \"watch\",\n\tShort: \"Watch environment activity in real-time\",\n\tLong: `Continuously display environment activity as agents work.\nShows new commits and environment changes updated every second.\nPress Ctrl+C to stop watching.`,\n\tExample: `# Watch all environment activity\ncontainer-use watch\n\n# Monitor agents while they work\ncontainer-use watch`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\tif _, err := repository.Open(ctx, \".\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tw := watch.Watcher{Interval: time.Second}\n\t\tw.Watch(app.Context(), \"git\", \"log\", \"--color=always\", \"--remotes=container-use\", \"--oneline\", \"--graph\", \"--decorate\")\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(watchCmd)\n}\n"], ["/container-use/repository/git.go", "package repository\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/mitchellh/go-homedir\"\n)\n\nconst (\n\tmaxFileSizeForTextCheck = 10 * 1024 * 1024 // 10MB\n)\n\nvar (\n\turlSchemeRegExp = regexp.MustCompile(`^[^:]+://`)\n\tscpLikeURLRegExp = regexp.MustCompile(`^(?:(?P[^@]+)@)?(?P[^:\\s]+):(?:(?P[0-9]{1,5})(?:\\/|:))?(?P[^\\\\].*\\/[^\\\\].*)$`)\n)\n\n// RunGitCommand executes a git command in the specified directory.\n// This is exported for use in tests and other packages that need direct git access.\nfunc RunGitCommand(ctx context.Context, dir string, args ...string) (out string, rerr error) {\n\tslog.Info(fmt.Sprintf(\"[%s] $ git %s\", dir, strings.Join(args, \" \")))\n\tdefer func() {\n\t\tslog.Info(fmt.Sprintf(\"[%s] $ git %s (DONE)\", dir, strings.Join(args, \" \")), \"err\", rerr)\n\t}()\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) {\n\t\t\treturn \"\", fmt.Errorf(\"git command failed (exit code %d): %w\\nOutput: %s\",\n\t\t\t\texitErr.ExitCode(), err, string(output))\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"git command failed: %w\", err)\n\t}\n\n\treturn string(output), nil\n}\n\n// RunInteractiveGitCommand executes a git command in the specified directory in interactive mode.\nfunc RunInteractiveGitCommand(ctx context.Context, dir string, w io.Writer, args ...string) (rerr error) {\n\tslog.Info(fmt.Sprintf(\"[%s] $ git %s\", dir, strings.Join(args, \" \")))\n\tdefer func() {\n\t\tslog.Info(fmt.Sprintf(\"[%s] $ git %s (DONE)\", dir, strings.Join(args, \" \")), \"err\", rerr)\n\t}()\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Dir = dir\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\n\treturn cmd.Run()\n}\n\nfunc getContainerUseRemote(ctx context.Context, repo string) (string, error) {\n\t// Check if we already have a container-use remote\n\tcuRemote, err := RunGitCommand(ctx, repo, \"remote\", \"get-url\", \"container-use\")\n\tif err != nil {\n\t\t// Check for exit code 2 which means the remote doesn't exist\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(cuRemote), nil\n}\n\nfunc (r *Repository) WorktreePath(id string) (string, error) {\n\treturn homedir.Expand(filepath.Join(r.getWorktreePath(), id))\n}\n\nfunc (r *Repository) deleteWorktree(id string) error {\n\tworktreePath, err := r.WorktreePath(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Deleting worktree at %s\\n\", worktreePath)\n\treturn os.RemoveAll(worktreePath)\n}\n\nfunc (r *Repository) deleteLocalRemoteBranch(id string) error {\n\tslog.Info(\"Pruning git worktrees\", \"repo\", r.forkRepoPath)\n\tif _, err := RunGitCommand(context.Background(), r.forkRepoPath, \"worktree\", \"prune\"); err != nil {\n\t\tslog.Error(\"Failed to prune git worktrees\", \"repo\", r.forkRepoPath, \"err\", err)\n\t\treturn err\n\t}\n\n\tslog.Info(\"Deleting local branch\", \"repo\", r.forkRepoPath, \"branch\", id)\n\tif _, err := RunGitCommand(context.Background(), r.forkRepoPath, \"branch\", \"-D\", id); err != nil {\n\t\tslog.Error(\"Failed to delete local branch\", \"repo\", r.forkRepoPath, \"branch\", id, \"err\", err)\n\t\treturn err\n\t}\n\n\tif _, err := RunGitCommand(context.Background(), r.userRepoPath, \"remote\", \"prune\", containerUseRemote); err != nil {\n\t\tslog.Error(\"Failed to fetch and prune container-use remote\", \"local-repo\", r.userRepoPath, \"err\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) initializeWorktree(ctx context.Context, id string) (string, error) {\n\tworktreePath, err := r.WorktreePath(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := os.Stat(worktreePath); err == nil {\n\t\treturn worktreePath, nil\n\t}\n\n\tslog.Info(\"Initializing worktree\", \"repository\", r.userRepoPath, \"container-id\", id)\n\n\tcurrentHead, err := RunGitCommand(ctx, r.userRepoPath, \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcurrentHead = strings.TrimSpace(currentHead)\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"push\", containerUseRemote, fmt.Sprintf(\"%s:refs/heads/%s\", currentHead, id))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = RunGitCommand(ctx, r.forkRepoPath, \"worktree\", \"add\", worktreePath, id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn worktreePath, nil\n}\n\n// createInitialCommit creates an empty commit with the environment creation message - this prevents multiple environments from overwriting the container-use-state on the parent commit\nfunc (r *Repository) createInitialCommit(ctx context.Context, worktreePath, id, title string) error {\n\tcommitMessage := fmt.Sprintf(\"Create environment %s: %s\", id, title)\n\t_, err := RunGitCommand(ctx, worktreePath, \"commit\", \"--allow-empty\", \"-m\", commitMessage)\n\treturn err\n}\n\nfunc (r *Repository) propagateToWorktree(ctx context.Context, env *environment.Environment, explanation string) (rerr error) {\n\tslog.Info(\"Propagating to worktree...\",\n\t\t\"environment.id\", env.ID,\n\t\t\"workdir\", env.State.Config.Workdir,\n\t\t\"id\", env.ID)\n\tdefer func() {\n\t\tslog.Info(\"Propagating to worktree... (DONE)\",\n\t\t\t\"environment.id\", env.ID,\n\t\t\t\"workdir\", env.State.Config.Workdir,\n\t\t\t\"id\", env.ID,\n\t\t\t\"err\", rerr)\n\t}()\n\n\tif err := r.exportEnvironment(ctx, env); err != nil {\n\t\treturn err\n\t}\n\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\tif err := r.commitWorktreeChanges(ctx, worktreePath, explanation); err != nil {\n\t\treturn fmt.Errorf(\"failed to commit worktree changes: %w\", err)\n\t}\n\n\tif err := r.saveState(ctx, env); err != nil {\n\t\treturn fmt.Errorf(\"failed to add notes: %w\", err)\n\t}\n\n\tslog.Info(\"Fetching container-use remote in source repository\")\n\tif _, err := RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, env.ID); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.propagateGitNotes(ctx, gitNotesStateRef); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) exportEnvironment(ctx context.Context, env *environment.Environment) error {\n\tworktreePointer := fmt.Sprintf(\"gitdir: %s\", filepath.Join(r.forkRepoPath, \"worktrees\", env.ID))\n\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\n\t_, err = env.Workdir().\n\t\tWithNewFile(\".git\", worktreePointer).\n\t\tExport(\n\t\t\tctx,\n\t\t\tworktreePath,\n\t\t\tdagger.DirectoryExportOpts{Wipe: true},\n\t\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\nfunc (r *Repository) propagateGitNotes(ctx context.Context, ref string) error {\n\tfullRef := fmt.Sprintf(\"refs/notes/%s\", ref)\n\tfetch := func() error {\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, fullRef+\":\"+fullRef)\n\t\treturn err\n\t}\n\n\tif err := fetch(); err != nil {\n\t\tif strings.Contains(err.Error(), \"[rejected]\") {\n\t\t\tif _, err := RunGitCommand(ctx, r.userRepoPath, \"update-ref\", \"-d\", fullRef); err == nil {\n\t\t\t\treturn fetch()\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) saveState(ctx context.Context, env *environment.Environment) error {\n\tstate, err := env.State.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\n\tf, err := os.CreateTemp(os.TempDir(), \".container-use-git-notes-*\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif _, err := f.Write(state); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesStateRef, \"add\", \"-f\", \"-F\", f.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) loadState(ctx context.Context, worktreePath string) ([]byte, error) {\n\tbuff, err := RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesStateRef, \"show\")\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"no note found\") {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn []byte(buff), nil\n}\n\nfunc (r *Repository) addGitNote(ctx context.Context, env *environment.Environment, note string) error {\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\t_, err = RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesLogRef, \"append\", \"-m\", note)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.propagateGitNotes(ctx, gitNotesLogRef)\n}\n\nfunc (r *Repository) currentUserBranch(ctx context.Context) (string, error) {\n\treturn RunGitCommand(ctx, r.userRepoPath, \"branch\", \"--show-current\")\n}\n\nfunc (r *Repository) mergeBase(ctx context.Context, env *environment.EnvironmentInfo) (string, error) {\n\tcurrentBranch, err := r.currentUserBranch(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcurrentBranch = strings.TrimSpace(currentBranch)\n\tif currentBranch == \"\" {\n\t\tcurrentBranch = \"HEAD\"\n\t}\n\tenvGitRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, env.ID)\n\tmergeBase, err := RunGitCommand(ctx, r.userRepoPath, \"merge-base\", currentBranch, envGitRef)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(mergeBase), nil\n}\n\nfunc (r *Repository) revisionRange(ctx context.Context, env *environment.EnvironmentInfo) (string, error) {\n\tmergeBase, err := r.mergeBase(ctx, env)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tenvGitRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, env.ID)\n\treturn fmt.Sprintf(\"%s..%s\", mergeBase, envGitRef), nil\n}\n\nfunc (r *Repository) commitWorktreeChanges(ctx context.Context, worktreePath, explanation string) error {\n\tstatus, err := RunGitCommand(ctx, worktreePath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.TrimSpace(status) == \"\" {\n\t\treturn nil\n\t}\n\n\tif err := r.addNonBinaryFiles(ctx, worktreePath); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = RunGitCommand(ctx, worktreePath, \"commit\", \"--allow-empty\", \"--allow-empty-message\", \"-m\", explanation)\n\treturn err\n}\n\n// AI slop below!\n// this is just to keep us moving fast because big git repos get hard to work with\n// and our demos like to download large dependencies.\nfunc (r *Repository) addNonBinaryFiles(ctx context.Context, worktreePath string) error {\n\tstatusOutput, err := RunGitCommand(ctx, worktreePath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor line := range strings.SplitSeq(strings.TrimSpace(statusOutput), \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif len(line) < 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\tindexStatus := line[0]\n\t\tworkTreeStatus := line[1]\n\t\tfileName := strings.TrimSpace(line[2:])\n\t\tif fileName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif r.shouldSkipFile(fileName) {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase indexStatus == '?' && workTreeStatus == '?':\n\t\t\t// ?? = untracked files or directories\n\t\t\tif strings.HasSuffix(fileName, \"/\") {\n\t\t\t\t// Untracked directory - traverse and add non-binary files\n\t\t\t\tdirName := strings.TrimSuffix(fileName, \"/\")\n\t\t\t\tif err := r.addFilesFromUntrackedDirectory(ctx, worktreePath, dirName); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else if !r.isBinaryFile(worktreePath, fileName) {\n\t\t\t\t// Untracked file - add if not binary\n\n\t\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase indexStatus == 'A':\n\t\t\t// A = already staged, skip\n\t\t\tcontinue\n\t\tcase indexStatus == 'D' || workTreeStatus == 'D':\n\t\t\t// D = deleted files (always stage deletion)\n\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\t// M, R, C and other statuses - add if not binary\n\t\t\tif !r.isBinaryFile(worktreePath, fileName) {\n\t\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) shouldSkipFile(fileName string) bool {\n\tskipExtensions := []string{\n\t\t\".tar\", \".tar.gz\", \".tgz\", \".tar.bz2\", \".tbz2\", \".tar.xz\", \".txz\",\n\t\t\".zip\", \".rar\", \".7z\", \".gz\", \".bz2\", \".xz\",\n\t\t\".exe\", \".bin\", \".dmg\", \".pkg\", \".msi\",\n\t\t\".jpg\", \".jpeg\", \".png\", \".gif\", \".bmp\", \".tiff\", \".svg\",\n\t\t\".mp3\", \".mp4\", \".avi\", \".mov\", \".wmv\", \".flv\", \".mkv\",\n\t\t\".pdf\", \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\",\n\t\t\".so\", \".dylib\", \".dll\", \".a\", \".lib\",\n\t}\n\n\tlowerName := strings.ToLower(fileName)\n\tfor _, ext := range skipExtensions {\n\t\tif strings.HasSuffix(lowerName, ext) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Use cross-platform path-aware directory patterns\n\tskipDirNames := []string{\n\t\t\"node_modules\", \".git\", \"__pycache__\", \"venv\", \".venv\", \"env\", \".env\",\n\t\t\"target\", \"build\", \"dist\", \".next\",\n\t}\n\n\tskipFilePatterns := []string{\n\t\t\".DS_Store\", \"*.tmp\", \"*.temp\", \"*.cache\", \"*.log\",\n\t}\n\n\t// Check if the path contains any of the skip directory names\n\tpathParts := strings.Split(filepath.ToSlash(lowerName), \"/\")\n\tfor _, part := range pathParts {\n\t\tfor _, skipDir := range skipDirNames {\n\t\t\tif part == strings.ToLower(skipDir) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check file patterns\n\tfor _, pattern := range skipFilePatterns {\n\t\tif strings.Contains(lowerName, strings.ToLower(pattern)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (r *Repository) IsDirty(ctx context.Context) (bool, string, error) {\n\tstatus, err := RunGitCommand(ctx, r.userRepoPath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\tif strings.TrimSpace(status) == \"\" {\n\t\treturn false, \"\", nil\n\t}\n\n\treturn true, status, nil\n}\n\nfunc (r *Repository) addFilesFromUntrackedDirectory(ctx context.Context, worktreePath, dirName string) error {\n\tdirPath := filepath.Join(worktreePath, dirName)\n\n\treturn filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(worktreePath, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\tif r.shouldSkipFile(relPath) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif r.shouldSkipFile(relPath) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !r.isBinaryFile(worktreePath, relPath) {\n\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", relPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (r *Repository) isBinaryFile(worktreePath, fileName string) bool {\n\tfullPath := filepath.Join(worktreePath, fileName)\n\n\tstat, err := os.Stat(fullPath)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\tif stat.IsDir() {\n\t\treturn false\n\t}\n\n\tif stat.Size() > maxFileSizeForTextCheck {\n\t\treturn true\n\t}\n\n\t// Empty files should be treated as text files so `touch .gitkeep` and friends work correctly\n\tif stat.Size() == 0 {\n\t\treturn false\n\t}\n\n\tfile, err := os.Open(fullPath)\n\tif err != nil {\n\t\tslog.Error(\"Error opening file\", \"err\", err)\n\t\treturn true\n\t}\n\tdefer file.Close()\n\n\tbuffer := make([]byte, 8000)\n\tn, err := file.Read(buffer)\n\tif err != nil && n == 0 {\n\t\treturn true\n\t}\n\n\tbuffer = buffer[:n]\n\treturn slices.Contains(buffer, 0)\n}\n\nfunc (r *Repository) normalizeForkPath(ctx context.Context, repo string) (string, error) {\n\t// Check if there's an origin remote\n\torigin, err := RunGitCommand(ctx, repo, \"remote\", \"get-url\", \"origin\")\n\tif err != nil {\n\t\t// If not -- this repository is a local one, we're going to use the filesystem path for the container-use repo\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {\n\t\t\t// Exit code 2 means the remote doesn't exist\n\t\t\t// Create a safe path component from the absolute repo path\n\t\t\tsafeRepoPath := createSafePathFromAbsolute(repo)\n\t\t\treturn homedir.Expand(filepath.Join(r.getRepoPath(), safeRepoPath))\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\t// Otherwise, let's use the normalized origin as path\n\tnormalizedOrigin, err := normalizeGitURL(strings.TrimSpace(origin))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn homedir.Expand(filepath.Join(r.getRepoPath(), normalizedOrigin))\n}\n\n// createSafePathFromAbsolute converts an absolute path to a safe relative path component\n// This handles Windows drive letters and special characters that can't be used in paths\nfunc createSafePathFromAbsolute(absPath string) string {\n\t// Convert to forward slashes for consistency\n\tnormalized := filepath.ToSlash(absPath)\n\n\t// Remove leading slash if present\n\tnormalized = strings.TrimPrefix(normalized, \"/\")\n\n\t// Replace colons (from Windows drive letters) with underscores\n\tnormalized = strings.ReplaceAll(normalized, \":\", \"_\")\n\n\t// Replace any remaining problematic characters\n\tnormalized = strings.ReplaceAll(normalized, \"<\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \">\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"|\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"?\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"*\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"\\\"\", \"_\")\n\n\treturn normalized\n}\n\nfunc normalizeGitURL(endpoint string) (string, error) {\n\tif e, ok := normalizeSCPLike(endpoint); ok {\n\t\treturn e, nil\n\t}\n\n\treturn normalizeURL(endpoint)\n}\n\nfunc normalizeURL(endpoint string) (string, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !u.IsAbs() {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"invalid endpoint: %s\", endpoint,\n\t\t)\n\t}\n\n\treturn fmt.Sprintf(\"%s%s\", u.Hostname(), strings.TrimSuffix(u.Path, \".git\")), nil\n}\n\nfunc normalizeSCPLike(endpoint string) (string, bool) {\n\tif matchesURLScheme(endpoint) || !matchesScpLike(endpoint) {\n\t\treturn \"\", false\n\t}\n\n\t_, host, _, path := findScpLikeComponents(endpoint)\n\n\treturn fmt.Sprintf(\"%s/%s\", host, strings.TrimSuffix(path, \".git\")), true\n}\n\n// matchesURLScheme returns true if the given string matches a URL-like\n// format scheme.\nfunc matchesURLScheme(url string) bool {\n\treturn urlSchemeRegExp.MatchString(url)\n}\n\n// matchesScpLike returns true if the given string matches an SCP-like\n// format scheme.\nfunc matchesScpLike(url string) bool {\n\treturn scpLikeURLRegExp.MatchString(url)\n}\n\n// findScpLikeComponents returns the user, host, port and path of the\n// given SCP-like URL.\nfunc findScpLikeComponents(url string) (user, host, port, path string) {\n\tm := scpLikeURLRegExp.FindStringSubmatch(url)\n\treturn m[1], m[2], m[3], m[4]\n}\n"], ["/container-use/environment/filesystem.go", "package environment\n\nimport (\n\t\"context\"\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"strings\"\n\n\tgodiffpatch \"github.com/sourcegraph/go-diff-patch\"\n)\n\nfunc (env *Environment) FileRead(ctx context.Context, targetFile string, shouldReadEntireFile bool, startLineOneIndexedInclusive int, endLineOneIndexedInclusive int) (string, error) {\n\tfile, err := env.container().File(targetFile).Contents(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif shouldReadEntireFile {\n\t\treturn file, err\n\t}\n\n\tlines := strings.Split(file, \"\\n\")\n\tstart := startLineOneIndexedInclusive - 1\n\tstart = max(start, 0)\n\tif start >= len(lines) {\n\t\tstart = len(lines) - 1\n\t}\n\tif start < 0 {\n\t\treturn \"\", fmt.Errorf(\"error reading file: start_line_one_indexed_inclusive (%d) cannot be less than 1\", startLineOneIndexedInclusive)\n\t}\n\tend := endLineOneIndexedInclusive\n\n\tif end >= len(lines) {\n\t\tend = len(lines) - 1\n\t}\n\tif end < start {\n\t\treturn \"\", fmt.Errorf(\"error reading file: end_line_one_indexed_inclusive (%d) must be greater than start_line_one_indexed_inclusive (%d)\", endLineOneIndexedInclusive, startLineOneIndexedInclusive)\n\t}\n\n\treturn strings.Join(lines[start:end], \"\\n\"), nil\n}\n\nfunc (env *Environment) FileWrite(ctx context.Context, explanation, targetFile, contents string) error {\n\terr := env.apply(ctx, env.container().WithNewFile(targetFile, contents))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file write, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Write %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileEdit(ctx context.Context, explanation, targetFile, search, replace, matchID string) error {\n\tcontents, err := env.container().File(targetFile).Contents(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Find all matches of the search text\n\tmatches := []int{}\n\tcursor := 0\n\tfor {\n\t\tindex := strings.Index(contents[cursor:], search)\n\t\tif index == -1 {\n\t\t\tbreak\n\t\t}\n\t\tactualIndex := cursor + index\n\t\tmatches = append(matches, actualIndex)\n\t\tcursor = actualIndex + 1\n\t}\n\n\tif len(matches) == 0 {\n\t\treturn fmt.Errorf(\"search text not found in file %s\", targetFile)\n\t}\n\n\t// If there are multiple matches and no matchID is provided, return an error with all matches\n\tif len(matches) > 1 && matchID == \"\" {\n\t\tvar matchDescriptions []string\n\t\tfor i, matchIndex := range matches {\n\t\t\t// Generate a unique ID for each match\n\t\t\tid := generateMatchID(targetFile, search, replace, i)\n\n\t\t\t// Get context around the match (3 lines before and after)\n\t\t\tcontext := getMatchContext(contents, matchIndex)\n\n\t\t\tmatchDescriptions = append(matchDescriptions, fmt.Sprintf(\"Match %d (ID: %s):\\n%s\", i+1, id, context))\n\t\t}\n\n\t\treturn fmt.Errorf(\"multiple matches found for search text in %s. Please specify which_match parameter with one of the following IDs:\\n\\n%s\",\n\t\t\ttargetFile, strings.Join(matchDescriptions, \"\\n\\n\"))\n\t}\n\n\t// Determine which match to replace\n\tvar targetMatchIndex int\n\tif len(matches) == 1 {\n\t\ttargetMatchIndex = matches[0]\n\t} else {\n\t\t// Find the match with the specified ID\n\t\tfound := false\n\t\tfor i, matchIndex := range matches {\n\t\t\tid := generateMatchID(targetFile, search, replace, i)\n\t\t\tif id == matchID {\n\t\t\t\ttargetMatchIndex = matchIndex\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"match ID %s not found\", matchID)\n\t\t}\n\t}\n\n\t// Replace the specific match\n\tnewContents := contents[:targetMatchIndex] + replace + contents[targetMatchIndex+len(search):]\n\n\t// Apply the changes using `Directory.withPatch` so we don't have to spit out\n\t// the entire contents\n\tpatch := godiffpatch.GeneratePatch(targetFile, contents, newContents)\n\tctr := env.container()\n\terr = env.apply(ctx, ctr.WithDirectory(\".\", ctr.Directory(\".\").WithPatch(patch)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file edit, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Edit %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileDelete(ctx context.Context, explanation, targetFile string) error {\n\terr := env.apply(ctx, env.container().WithoutFile(targetFile))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file delete, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Delete %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileList(ctx context.Context, path string) (string, error) {\n\tentries, err := env.container().Directory(path).Entries(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tout := &strings.Builder{}\n\tfor _, entry := range entries {\n\t\tfmt.Fprintf(out, \"%s\\n\", entry)\n\t}\n\treturn out.String(), nil\n}\n\n// generateMatchID creates a unique ID for a match based on file, search, replace, and index\nfunc generateMatchID(targetFile, search, replace string, index int) string {\n\tdata := fmt.Sprintf(\"%s:%s:%s:%d\", targetFile, search, replace, index)\n\thash := sha256.Sum256([]byte(data))\n\treturn fmt.Sprintf(\"%x\", hash)[:8] // Use first 8 characters of hash\n}\n\n// getMatchContext returns the context around a match (3 lines before and after)\nfunc getMatchContext(contents string, matchIndex int) string {\n\tlines := strings.Split(contents, \"\\n\")\n\n\t// Find which line contains the match\n\tcurrentPos := 0\n\tmatchLine := 0\n\tfor i, line := range lines {\n\t\tif currentPos+len(line) >= matchIndex {\n\t\t\tmatchLine = i\n\t\t\tbreak\n\t\t}\n\t\tcurrentPos += len(line) + 1 // +1 for newline\n\t}\n\n\t// Get context lines (3 before, match line, 3 after)\n\tstart := max(0, matchLine-3)\n\tend := min(len(lines), matchLine+4)\n\n\tcontextLines := make([]string, 0, end-start)\n\tfor i := start; i < end; i++ {\n\t\tprefix := \" \"\n\t\tif i == matchLine {\n\t\t\tprefix = \"> \" // Mark the line containing the match\n\t\t}\n\t\t// Include line numbers, which may help the model determine the right match\n\t\tprefix += fmt.Sprintf(\"%4d | \", i+1)\n\t\tcontextLines = append(contextLines, fmt.Sprintf(\"%s%s\", prefix, lines[i]))\n\t}\n\n\treturn strings.Join(contextLines, \"\\n\")\n}\n"], ["/container-use/environment/environment.go", "package environment\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"dagger.io/dagger\"\n)\n\n// EnvironmentInfo contains basic metadata about an environment\n// without requiring dagger operations\ntype EnvironmentInfo struct {\n\tState *State `json:\"state,omitempty\"`\n\n\tID string `json:\"id,omitempty\"`\n}\n\ntype Environment struct {\n\t*EnvironmentInfo\n\n\tdag *dagger.Client\n\n\tServices []*Service\n\tNotes Notes\n\n\tmu sync.RWMutex\n}\n\nfunc New(ctx context.Context, dag *dagger.Client, id, title string, config *EnvironmentConfig, initialSourceDir *dagger.Directory) (*Environment, error) {\n\tenv := &Environment{\n\t\tEnvironmentInfo: &EnvironmentInfo{\n\t\t\tID: id,\n\t\t\tState: &State{\n\t\t\t\tConfig: config,\n\t\t\t\tTitle: title,\n\t\t\t\tCreatedAt: time.Now(),\n\t\t\t\tUpdatedAt: time.Now(),\n\t\t\t},\n\t\t},\n\t\tdag: dag,\n\t}\n\n\tcontainer, err := env.buildBase(ctx, initialSourceDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tslog.Info(\"Creating environment\", \"id\", env.ID, \"workdir\", env.State.Config.Workdir)\n\n\tif err := env.apply(ctx, container); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\nfunc (env *Environment) Workdir() *dagger.Directory {\n\treturn env.container().Directory(env.State.Config.Workdir)\n}\n\nfunc (env *Environment) container() *dagger.Container {\n\tenv.mu.RLock()\n\tdefer env.mu.RUnlock()\n\n\treturn env.dag.LoadContainerFromID(dagger.ContainerID(env.State.Container))\n}\n\nfunc Load(ctx context.Context, dag *dagger.Client, id string, state []byte, worktree string) (*Environment, error) {\n\tenvInfo, err := LoadInfo(ctx, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv := &Environment{\n\t\tEnvironmentInfo: envInfo,\n\t\tdag: dag,\n\t\t// Services: ?\n\t}\n\n\treturn env, nil\n}\n\n// LoadInfo loads basic environment metadata without requiring dagger operations.\n// This is useful for operations that only need access to configuration and state\n// information without the overhead of initializing container operations.\nfunc LoadInfo(ctx context.Context, id string, state []byte, worktree string) (*EnvironmentInfo, error) {\n\tenvInfo := &EnvironmentInfo{\n\t\tID: id,\n\t\tState: &State{},\n\t}\n\n\tif err := envInfo.State.Unmarshal(state); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Backward compatibility: if there's no config in the state, load it from the worktree\n\tif envInfo.State.Config == nil {\n\t\tconfig := DefaultConfig()\n\t\tif err := config.Load(worktree); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenvInfo.State.Config = config\n\t}\n\n\treturn envInfo, nil\n}\n\nfunc (env *Environment) apply(ctx context.Context, newState *dagger.Container) error {\n\t// TODO(braa): is this sync redundant with newState.ID?\n\tif _, err := newState.Sync(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tcontainerID, err := newState.ID(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenv.mu.Lock()\n\tdefer env.mu.Unlock()\n\tenv.State.UpdatedAt = time.Now()\n\tenv.State.Container = string(containerID)\n\n\treturn nil\n}\n\nfunc containerWithEnvAndSecrets(dag *dagger.Client, container *dagger.Container, envs, secrets []string) (*dagger.Container, error) {\n\tfor _, env := range envs {\n\t\tk, v, found := strings.Cut(env, \"=\")\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid env variable: %s\", env)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid environment variable: %s\", env)\n\t\t}\n\t\tcontainer = container.WithEnvVariable(k, v)\n\t}\n\n\tfor _, secret := range secrets {\n\t\tk, v, found := strings.Cut(secret, \"=\")\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid secret: %s\", secret)\n\t\t}\n\t\tcontainer = container.WithSecretVariable(k, dag.Secret(v))\n\t}\n\n\treturn container, nil\n}\n\nfunc (env *Environment) buildBase(ctx context.Context, baseSourceDir *dagger.Directory) (*dagger.Container, error) {\n\tcontainer := env.dag.\n\t\tContainer().\n\t\tFrom(env.State.Config.BaseImage).\n\t\tWithWorkdir(env.State.Config.Workdir)\n\n\tcontainer, err := containerWithEnvAndSecrets(env.dag, container, env.State.Config.Env, env.State.Config.Secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunCommands := func(commands []string) error {\n\t\tfor _, command := range commands {\n\t\t\tvar err error\n\n\t\t\tcontainer = container.WithExec([]string{\"sh\", \"-c\", command})\n\n\t\t\texitCode, err := container.ExitCode(ctx)\n\t\t\tif err != nil {\n\t\t\t\tvar exitErr *dagger.ExecError\n\t\t\t\tif errors.As(err, &exitErr) {\n\t\t\t\t\tenv.Notes.AddCommand(command, exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t\t\t\treturn fmt.Errorf(\"exit code %d.\\nstdout: %s\\nstderr: %s\\n%w\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr, err)\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstdout, err := container.Stdout(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get stdout: %w\", err)\n\t\t\t}\n\n\t\t\tstderr, err := container.Stderr(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get stderr: %w\", err)\n\t\t\t}\n\n\t\t\tenv.Notes.AddCommand(command, exitCode, stdout, stderr)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// Run setup commands without the source directory for caching purposes\n\tif err := runCommands(env.State.Config.SetupCommands); err != nil {\n\t\treturn nil, fmt.Errorf(\"setup command failed: %w\", err)\n\t}\n\n\tenv.Services, err = env.startServices(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start services: %w\", err)\n\t}\n\tfor _, service := range env.Services {\n\t\tcontainer = container.WithServiceBinding(service.Config.Name, service.svc)\n\t}\n\n\tcontainer = container.WithDirectory(\".\", baseSourceDir)\n\n\t// Run the install commands after the source directory is set up\n\tif err := runCommands(env.State.Config.InstallCommands); err != nil {\n\t\treturn nil, fmt.Errorf(\"install command failed: %w\", err)\n\t}\n\n\treturn container, nil\n}\n\nfunc (env *Environment) UpdateConfig(ctx context.Context, newConfig *EnvironmentConfig) error {\n\tenv.State.Config = newConfig\n\n\t// Re-build the base image with the new config\n\tcontainer, err := env.buildBase(ctx, env.Workdir())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := env.apply(ctx, container); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (env *Environment) Run(ctx context.Context, command, shell string, useEntrypoint bool) (string, error) {\n\targs := []string{}\n\tif command != \"\" {\n\t\targs = []string{shell, \"-c\", command}\n\t}\n\tnewState := env.container().WithExec(args, dagger.ContainerWithExecOpts{\n\t\tUseEntrypoint: useEntrypoint,\n\t\tExpect: dagger.ReturnTypeAny, // Don't treat non-zero exit as error\n\t\tExperimentalPrivilegedNesting: true,\n\t})\n\n\texitCode, err := newState.ExitCode(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get exit code: %w\", err)\n\t}\n\n\tstdout, err := newState.Stdout(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get stdout: %w\", err)\n\t}\n\n\tstderr, err := newState.Stderr(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get stderr: %w\", err)\n\t}\n\n\t// Log the command execution with all details\n\tenv.Notes.AddCommand(command, exitCode, stdout, stderr)\n\n\t// Always apply the container state (preserving changes even on non-zero exit)\n\tif err := env.apply(ctx, newState); err != nil {\n\t\treturn stdout, fmt.Errorf(\"failed to apply container state: %w\", err)\n\t}\n\n\t// Return combined output (stdout + stderr if there was stderr)\n\tcombinedOutput := stdout\n\tif stderr != \"\" {\n\t\tif stdout != \"\" {\n\t\t\tcombinedOutput += \"\\n\"\n\t\t}\n\t\tcombinedOutput += \"stderr: \" + stderr\n\t}\n\treturn combinedOutput, nil\n}\n\nfunc (env *Environment) RunBackground(ctx context.Context, command, shell string, ports []int, useEntrypoint bool) (EndpointMappings, error) {\n\targs := []string{}\n\tif command != \"\" {\n\t\targs = []string{shell, \"-c\", command}\n\t}\n\tdisplayCommand := command + \" &\"\n\tserviceState := env.container()\n\n\t// Expose ports\n\tfor _, port := range ports {\n\t\tserviceState = serviceState.WithExposedPort(port, dagger.ContainerWithExposedPortOpts{\n\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\tDescription: fmt.Sprintf(\"Port %d\", port),\n\t\t})\n\t}\n\n\t// Start the service\n\tstartCtx, cancel := context.WithTimeout(ctx, serviceStartTimeout)\n\tdefer cancel()\n\tsvc, err := serviceState.AsService(dagger.ContainerAsServiceOpts{\n\t\tArgs: args,\n\t\tUseEntrypoint: useEntrypoint,\n\t}).Start(startCtx)\n\tif err != nil {\n\t\tvar exitErr *dagger.ExecError\n\t\tif errors.As(err, &exitErr) {\n\t\t\tenv.Notes.AddCommand(displayCommand, exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t\treturn nil, fmt.Errorf(\"command failed with exit code %d.\\nstdout: %s\\nstderr: %s\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t}\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\terr = fmt.Errorf(\"service failed to start within %s timeout\", serviceStartTimeout)\n\t\t\tenv.Notes.AddCommand(displayCommand, 137, \"\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tenv.Notes.AddCommand(displayCommand, 0, \"\", \"\")\n\n\tendpoints := EndpointMappings{}\n\tfor _, port := range ports {\n\t\tendpoint := &EndpointMapping{}\n\t\tendpoints[port] = endpoint\n\n\t\t// Expose port on the host\n\t\ttunnel, err := env.dag.Host().Tunnel(svc, dagger.HostTunnelOpts{\n\t\t\tPorts: []dagger.PortForward{\n\t\t\t\t{\n\t\t\t\t\tBackend: port,\n\t\t\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\t\t},\n\t\t\t},\n\t\t}).Start(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texternalEndpoint, err := tunnel.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpoint.HostExternal = externalEndpoint\n\n\t\tinternalEndpoint, err := svc.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tPort: port,\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpoint.EnvironmentInternal = internalEndpoint\n\t}\n\n\treturn endpoints, nil\n}\n\nfunc (env *Environment) Terminal(ctx context.Context) error {\n\tcontainer := env.container()\n\tvar cmd []string\n\tvar sourceRC string\n\tif shells, err := container.File(\"/etc/shells\").Contents(ctx); err == nil {\n\t\tfor shell := range strings.Lines(shells) {\n\t\t\tif shell[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshell = strings.TrimRight(shell, \"\\n\")\n\t\t\tif strings.HasSuffix(shell, \"/bash\") {\n\t\t\t\tsourceRC = fmt.Sprintf(\"[ -f ~/.bashrc ] && . ~/.bashrc; %q --version | head -4; \", shell)\n\t\t\t\tcmd = []string{shell, \"--rcfile\", \"/cu/rc.sh\", \"-i\"}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// Try to show the same pretty PS1 as for the default /bin/sh terminal in dagger\n\tcontainer = container.WithNewFile(\"/cu/rc.sh\", sourceRC+`export PS1=\"\\033[33mcu\\033[0m \\033[02m\\$(pwd | sed \\\"s|^\\$HOME|~|\\\")\\033[0m \\$ \"`+\"\\n\")\n\tif cmd == nil {\n\t\t// If bash not available, assume POSIX shell\n\t\tcontainer = container.WithEnvVariable(\"ENV\", \"/cu/rc.sh\")\n\t\tcmd = []string{\"sh\"}\n\t}\n\tif _, err := container.Terminal(dagger.ContainerTerminalOpts{\n\t\tExperimentalPrivilegedNesting: true,\n\t\tCmd: cmd,\n\t}).Sync(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (env *Environment) Checkpoint(ctx context.Context, target string) (string, error) {\n\treturn env.container().Publish(ctx, target)\n}\n"], ["/container-use/cmd/container-use/config.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/dagger/container-use/cmd/container-use/agent\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\n// Helper function for read-only config operations\nfunc withConfig(cmd *cobra.Command, fn func(*environment.EnvironmentConfig) error) error {\n\tctx := cmd.Context()\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t}\n\n\treturn fn(config)\n}\n\n// Helper function for config update operations\nfunc updateConfig(cmd *cobra.Command, fn func(*environment.EnvironmentConfig) error) error {\n\tctx := cmd.Context()\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t}\n\n\tif err := fn(config); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.Save(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to save configuration: %w\", err)\n\t}\n\n\treturn nil\n}\n\nvar configCmd = &cobra.Command{\n\tUse: \"config\",\n\tShort: \"Manage environment configuration\",\n\tLong: `Configure the development environment settings such as base image and setup commands.\nThese settings are stored in .container-use/environment.json and apply to all new environments.`,\n}\n\nfunc init() {\n\tconfigShowCmd.Flags().Bool(\"json\", false, \"Dump the configuration in JSON\")\n}\n\nvar configShowCmd = &cobra.Command{\n\tUse: \"show []\",\n\tShort: \"Show environment configuration\",\n\tLong: `Display environment configuration including base image and setup commands.\nWithout an environment argument, shows the default configuration used for new environments.\nWith an environment argument, shows the configuration for that specific environment.`,\n\tExample: `# Show the default environment configuration\ncontainer-use config show\n\n# Show the configuration for a specific environment\ncontainer-use config show my-env\n`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tvar config *environment.EnvironmentConfig\n\n\t\t// If no environment is specified, use the default configuration\n\t\tif len(args) == 0 {\n\t\t\tconfig = environment.DefaultConfig()\n\t\t\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tenvID := args[0]\n\t\t\tenv, err := repo.Info(ctx, envID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tconfig = env.State.Config\n\t\t}\n\n\t\tif ok, _ := cmd.Flags().GetBool(\"json\"); ok {\n\t\t\tenc := json.NewEncoder(os.Stdout)\n\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\treturn enc.Encode(config)\n\t\t}\n\n\t\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\t\tdefer tw.Flush()\n\n\t\tfmt.Fprintf(tw, \"Base Image:\\t%s\\n\", config.BaseImage)\n\t\tfmt.Fprintf(tw, \"Workdir:\\t%s\\n\", config.Workdir)\n\n\t\tif len(config.SetupCommands) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Setup Commands:\\t\\n\")\n\t\t\tfor i, cmd := range config.SetupCommands {\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s\\n\", i+1, cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Setup Commands:\\t(none)\\n\")\n\t\t}\n\n\t\tif len(config.InstallCommands) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Install Commands:\\t\\n\")\n\t\t\tfor i, cmd := range config.InstallCommands {\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s\\n\", i+1, cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Install Commands:\\t(none)\\n\")\n\t\t}\n\n\t\tenvKeys := config.Env.Keys()\n\t\tif len(envKeys) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Environment Variables:\\t\\n\")\n\t\t\tfor i, key := range envKeys {\n\t\t\t\tvalue := config.Env.Get(key)\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Environment Variables:\\t(none)\\n\")\n\t\t}\n\n\t\tsecretKeys := config.Secrets.Keys()\n\t\tif len(secretKeys) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Secrets:\\t\\n\")\n\t\t\tfor i, key := range secretKeys {\n\t\t\t\tvalue := config.Secrets.Get(key)\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Secrets:\\t(none)\\n\")\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nvar configImportCmd = &cobra.Command{\n\tUse: \"import \",\n\tShort: \"Import configuration from an environment\",\n\tLong: `Import configuration from an existing environment and set it as the default.\nThis copies the environment's base image, setup commands, environment variables,\nand secrets to be used as defaults for new environments.`,\n\tExample: `# Import configuration from an environment\ncontainer-use config import my-env\n\n# View the configuration before importing\ncontainer-use config show my-env\ncontainer-use config import my-env`,\n\tArgs: cobra.ExactArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tenvID := args[0]\n\t\tenv, err := repo.Info(ctx, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := env.State.Config.Save(repo.SourcePath()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to save configuration: %w\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Configuration imported from environment '%s'\\n\", envID)\n\t\treturn nil\n\t},\n}\n\n// Base image object commands\nvar configBaseImageCmd = &cobra.Command{\n\tUse: \"base-image\",\n\tShort: \"Manage base container image\",\n\tLong: `Manage the base container image for new environments.`,\n}\n\nvar configBaseImageSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set the base container image\",\n\tLong: `Set the base container image for new environments (e.g., python:3.11, node:18, ubuntu:22.04).`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tbaseImage := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.BaseImage = baseImage\n\t\t\tfmt.Printf(\"Base image set to: %s\\n\", baseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configBaseImageGetCmd = &cobra.Command{\n\tUse: \"get\",\n\tShort: \"Get the current base container image\",\n\tLong: `Display the current base container image.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfmt.Println(config.BaseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configBaseImageResetCmd = &cobra.Command{\n\tUse: \"reset\",\n\tShort: \"Reset base image to default\",\n\tLong: `Reset the base container image to the default (ubuntu:24.04).`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tdefaultConfig := environment.DefaultConfig()\n\t\t\tconfig.BaseImage = defaultConfig.BaseImage\n\t\t\tfmt.Printf(\"Base image reset to default: %s\\n\", defaultConfig.BaseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Setup command object commands\nvar configSetupCommandCmd = &cobra.Command{\n\tUse: \"setup-command\",\n\tShort: \"Manage setup commands\",\n\tLong: `Manage setup commands that are run when creating environments.`,\n}\n\nvar configSetupCommandAddCmd = &cobra.Command{\n\tUse: \"add \",\n\tShort: \"Add a setup command\",\n\tLong: `Add a command to be run when creating new environments (e.g., \"apt update && apt install -y python3\").`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.SetupCommands = append(config.SetupCommands, command)\n\t\t\tfmt.Printf(\"Setup command added: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandRemoveCmd = &cobra.Command{\n\tUse: \"remove \",\n\tShort: \"Remove a setup command\",\n\tLong: `Remove a setup command from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfound := false\n\t\t\tnewCommands := make([]string, 0, len(config.SetupCommands))\n\t\t\tfor _, existing := range config.SetupCommands {\n\t\t\t\tif existing != command {\n\t\t\t\t\tnewCommands = append(newCommands, existing)\n\t\t\t\t} else {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\treturn fmt.Errorf(\"setup command not found: %s\", command)\n\t\t\t}\n\n\t\t\tconfig.SetupCommands = newCommands\n\t\t\tfmt.Printf(\"Setup command removed: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all setup commands\",\n\tLong: `List all setup commands that will be run when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif len(config.SetupCommands) == 0 {\n\t\t\t\tfmt.Println(\"No setup commands configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, command := range config.SetupCommands {\n\t\t\t\tfmt.Printf(\"%d. %s\\n\", i+1, command)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all setup commands\",\n\tLong: `Remove all setup commands from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.SetupCommands = []string{}\n\t\t\tfmt.Println(\"All setup commands cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Install command object commands\nvar configInstallCommandCmd = &cobra.Command{\n\tUse: \"install-command\",\n\tShort: \"Manage install commands\",\n\tLong: `Manage install commands that are run after copying code to environments.`,\n}\n\nvar configInstallCommandAddCmd = &cobra.Command{\n\tUse: \"add \",\n\tShort: \"Add an install command\",\n\tLong: `Add a command to be run after copying code to new environments (e.g., \"go mod download\").`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.InstallCommands = append(config.InstallCommands, command)\n\t\t\tfmt.Printf(\"Install command added: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandRemoveCmd = &cobra.Command{\n\tUse: \"remove \",\n\tShort: \"Remove an install command\",\n\tLong: `Remove an install command from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfound := false\n\t\t\tnewCommands := make([]string, 0, len(config.InstallCommands))\n\t\t\tfor _, existing := range config.InstallCommands {\n\t\t\t\tif existing != command {\n\t\t\t\t\tnewCommands = append(newCommands, existing)\n\t\t\t\t} else {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\treturn fmt.Errorf(\"install command not found: %s\", command)\n\t\t\t}\n\n\t\t\tconfig.InstallCommands = newCommands\n\t\t\tfmt.Printf(\"Install command removed: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all install commands\",\n\tLong: `List all install commands that will be run after copying code to environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif len(config.InstallCommands) == 0 {\n\t\t\t\tfmt.Println(\"No install commands configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, command := range config.InstallCommands {\n\t\t\t\tfmt.Printf(\"%d. %s\\n\", i+1, command)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all install commands\",\n\tLong: `Remove all install commands from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.InstallCommands = []string{}\n\t\t\tfmt.Println(\"All install commands cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Environment variable object commands\nvar configEnvCmd = &cobra.Command{\n\tUse: \"env\",\n\tShort: \"Manage environment variables\",\n\tLong: `Manage environment variables that are set when creating environments.`,\n}\n\nvar configEnvSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set an environment variable\",\n\tLong: `Set an environment variable to be used when creating new environments (e.g., \"PATH\" \"/usr/local/bin:$PATH\").`,\n\tArgs: cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\tvalue := args[1]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Env.Set(key, value)\n\t\t\tfmt.Printf(\"Environment variable set: %s=%s\\n\", key, value)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvUnsetCmd = &cobra.Command{\n\tUse: \"unset \",\n\tShort: \"Unset an environment variable\",\n\tLong: `Unset an environment variable from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif !config.Env.Unset(key) {\n\t\t\t\treturn fmt.Errorf(\"environment variable not found: %s\", key)\n\t\t\t}\n\t\t\tfmt.Printf(\"Environment variable unset: %s\\n\", key)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all environment variables\",\n\tLong: `List all environment variables that will be set when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tkeys := config.Env.Keys()\n\t\t\tif len(keys) == 0 {\n\t\t\t\tfmt.Println(\"No environment variables configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, key := range keys {\n\t\t\t\tvalue := config.Env.Get(key)\n\t\t\t\tfmt.Printf(\"%d. %s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all environment variables\",\n\tLong: `Remove all environment variables from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Env.Clear()\n\t\t\tfmt.Println(\"All environment variables cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Secret object commands\nvar configSecretCmd = &cobra.Command{\n\tUse: \"secret\",\n\tShort: \"Manage secrets\",\n\tLong: `Manage secrets that are set when creating environments.`,\n}\n\nvar configSecretSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set a secret\",\n\tLong: `Set a secret to be used when creating new environments (e.g., \"API_KEY\" \"op://vault/item/field\").`,\n\tArgs: cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\tvalue := args[1]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Secrets.Set(key, value)\n\t\t\tfmt.Printf(\"Secret set: %s=%s\\n\", key, value)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretUnsetCmd = &cobra.Command{\n\tUse: \"unset \",\n\tShort: \"Unset a secret\",\n\tLong: `Unset a secret from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif !config.Secrets.Unset(key) {\n\t\t\t\treturn fmt.Errorf(\"secret not found: %s\", key)\n\t\t\t}\n\t\t\tfmt.Printf(\"Secret unset: %s\\n\", key)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all secrets\",\n\tLong: `List all secrets that will be set when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tkeys := config.Secrets.Keys()\n\t\t\tif len(keys) == 0 {\n\t\t\t\tfmt.Println(\"No secrets configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, key := range keys {\n\t\t\t\tvalue := config.Secrets.Get(key)\n\t\t\t\tfmt.Printf(\"%d. %s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all secrets\",\n\tLong: `Remove all secrets from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Secrets.Clear()\n\t\t\tfmt.Println(\"All secrets cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nfunc init() {\n\t// Add base-image commands\n\tconfigBaseImageCmd.AddCommand(configBaseImageSetCmd)\n\tconfigBaseImageCmd.AddCommand(configBaseImageGetCmd)\n\tconfigBaseImageCmd.AddCommand(configBaseImageResetCmd)\n\n\t// Add setup-command commands\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandAddCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandRemoveCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandListCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandClearCmd)\n\n\t// Add install-command commands\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandAddCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandRemoveCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandListCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandClearCmd)\n\n\t// Add env commands\n\tconfigEnvCmd.AddCommand(configEnvSetCmd)\n\tconfigEnvCmd.AddCommand(configEnvUnsetCmd)\n\tconfigEnvCmd.AddCommand(configEnvListCmd)\n\tconfigEnvCmd.AddCommand(configEnvClearCmd)\n\n\t// Add secret commands\n\tconfigSecretCmd.AddCommand(configSecretSetCmd)\n\tconfigSecretCmd.AddCommand(configSecretUnsetCmd)\n\tconfigSecretCmd.AddCommand(configSecretListCmd)\n\tconfigSecretCmd.AddCommand(configSecretClearCmd)\n\n\t// Add object commands to config\n\tconfigCmd.AddCommand(configBaseImageCmd)\n\tconfigCmd.AddCommand(configSetupCommandCmd)\n\tconfigCmd.AddCommand(configInstallCommandCmd)\n\tconfigCmd.AddCommand(configEnvCmd)\n\tconfigCmd.AddCommand(configSecretCmd)\n\tconfigCmd.AddCommand(configShowCmd)\n\tconfigCmd.AddCommand(configImportCmd)\n\n\t// Add agent command\n\tconfigCmd.AddCommand(agent.AgentCmd)\n\n\t// Add config command to root\n\trootCmd.AddCommand(configCmd)\n}\n"], ["/container-use/cmd/container-use/agent/configure.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/dagger/container-use/mcpserver\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype MCPServersConfig struct {\n\tMCPServers map[string]MCPServer `json:\"mcpServers\"`\n}\n\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tEnv map[string]string `json:\"env,omitempty\"`\n\tTimeout *int `json:\"timeout,omitempty\"`\n\tDisabled *bool `json:\"disabled,omitempty\"`\n\tAutoApprove []string `json:\"autoApprove,omitempty\"`\n\tAlwaysAllow []string `json:\"alwaysAllow,omitempty\"`\n\tWorkingDir *string `json:\"working_directory,omitempty\"`\n\tStartOnLaunch *bool `json:\"start_on_launch,omitempty\"`\n}\n\nconst ContainerUseBinary = \"container-use\"\n\nvar AgentCmd = &cobra.Command{\n\tUse: \"agent [agent]\",\n\tShort: \"Configure MCP server for different agents\",\n\tLong: `Setup the container-use MCP server according to the specified agent including Claude Code, Goose, Cursor, and others.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) == 0 {\n\t\t\treturn interactiveConfiguration()\n\t\t}\n\t\tagent, err := selectAgent(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn configureAgent(agent)\n\t},\n}\n\nfunc interactiveConfiguration() error {\n\tselectedAgent, err := RunAgentSelector()\n\tif err != nil {\n\t\t// If the user quits, it's not an error, just exit gracefully.\n\t\tif err.Error() == \"no agent selected\" {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"failed to select agent: %w\", err)\n\t}\n\n\tagent, err := selectAgent(selectedAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn configureAgent(agent)\n}\n\ntype ConfigurableAgent interface {\n\tname() string\n\tdescription() string\n\teditMcpConfig() error\n\teditRules() error\n\tisInstalled() bool\n}\n\n// Add agents here\nfunc selectAgent(agentKey string) (ConfigurableAgent, error) {\n\t// Check if agent is supported on current platform\n\tif runtime.GOOS == \"windows\" {\n\t\tswitch agentKey {\n\t\tcase \"codex\", \"amazonq\":\n\t\t\treturn nil, fmt.Errorf(\"agent '%s' is not supported on native Windows.\\nTo use this agent, please install and run container-use in Windows Subsystem for Linux (WSL)\", agentKey)\n\t\t}\n\t}\n\n\tswitch agentKey {\n\tcase \"claude\":\n\t\treturn &ConfigureClaude{}, nil\n\tcase \"goose\":\n\t\treturn &ConfigureGoose{}, nil\n\tcase \"cursor\":\n\t\treturn &ConfigureCursor{}, nil\n\tcase \"codex\":\n\t\treturn &ConfigureCodex{}, nil\n\tcase \"amazonq\":\n\t\treturn &ConfigureQ{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown agent: %s\", agentKey)\n}\n\nfunc configureAgent(agent ConfigurableAgent) error {\n\tfmt.Printf(\"Configuring %s...\\n\", agent.name())\n\n\t// Save MCP config\n\terr := agent.editMcpConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"✓ Configured %s MCP configuration\\n\", agent.name())\n\n\t// Save rules\n\terr = agent.editRules()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"✓ Saved %s container-use rules\\n\", agent.name())\n\n\tfmt.Printf(\"\\n%s configuration complete!\\n\", agent.name())\n\treturn nil\n}\n\n// Helper functions\nfunc saveRulesFile(rulesFile, content string) error {\n\tdir := filepath.Dir(rulesFile)\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t// Append to file if it exists, create if it doesn't TODO make it re-entrant with a marker\n\texisting, err := os.ReadFile(rulesFile)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to read existing rules: %w\", err)\n\t}\n\texistingStr := string(existing)\n\n\teditedRules, err := editRulesFile(existingStr, content)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(rulesFile, []byte(editedRules), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update rules: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc editRulesFile(existingRules, content string) (string, error) {\n\t// Look for section markers\n\tconst marker = \"\"\n\n\tif strings.Contains(existingRules, marker) {\n\t\t// Update existing section\n\t\tparts := strings.Split(existingRules, marker)\n\t\tif len(parts) != 3 {\n\t\t\treturn \"\", fmt.Errorf(\"malformed rules file - expected single section marked with %s\", marker)\n\t\t}\n\t\tnewContent := parts[0] + marker + \"\\n\" + content + \"\\n\" + marker + parts[2]\n\t\treturn newContent, nil\n\t} else {\n\t\t// Append new section\n\t\tnewContent := existingRules\n\t\tif len(newContent) > 0 && !strings.HasSuffix(newContent, \"\\n\") {\n\t\t\tnewContent += \"\\n\"\n\t\t}\n\t\tnewContent += \"\\n\" + marker + \"\\n\" + content + \"\\n\" + marker + \"\\n\"\n\t\treturn newContent, nil\n\t}\n}\n\nfunc tools(prefix string) []string {\n\ttools := []string{}\n\tfor _, t := range mcpserver.Tools() {\n\t\ttools = append(tools, fmt.Sprintf(\"%s%s\", prefix, t.Definition.Name))\n\t}\n\treturn tools\n}\n"], ["/container-use/cmd/container-use/agent/configure_ui.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Agent represents an agent configuration option\ntype Agent struct {\n\tKey string\n\tName string\n\tDescription string\n}\n\n// Available agents\nvar agents = []Agent{\n\t{\n\t\tKey: \"claude\",\n\t\tName: \"Claude Code\",\n\t\tDescription: \"Anthropic's Claude Code\",\n\t},\n\t{\n\t\tKey: \"goose\",\n\t\tName: \"Goose\",\n\t\tDescription: \"an open source, extensible AI agent that goes beyond code suggestions\",\n\t},\n\t{\n\t\tKey: \"cursor\",\n\t\tName: \"Cursor\",\n\t\tDescription: \"AI-powered code editor\",\n\t},\n\t{\n\t\tKey: \"codex\",\n\t\tName: \"OpenAI Codex\",\n\t\tDescription: \"OpenAI's lightweight coding agent that runs in your terminal (Linux/macOS/WSL)\",\n\t},\n\t{\n\t\tKey: \"amazonq\",\n\t\tName: \"Amazon Q Developer\",\n\t\tDescription: \"Amazon's agentic chat experience in your terminal (Linux/macOS/WSL)\",\n\t},\n}\n\n// getSupportedAgents returns agents that are supported on the current platform\nfunc getSupportedAgents() []Agent {\n\tif runtime.GOOS == \"windows\" {\n\t\t// Filter out Windows-incompatible agents\n\t\tvar supportedAgents []Agent\n\t\tfor _, agent := range agents {\n\t\t\tif agent.Key != \"codex\" && agent.Key != \"amazonq\" {\n\t\t\t\tsupportedAgents = append(supportedAgents, agent)\n\t\t\t}\n\t\t}\n\t\treturn supportedAgents\n\t}\n\treturn agents\n}\n\n// AgentSelectorModel represents the bubbletea model for agent selection\ntype AgentSelectorModel struct {\n\tcursor int\n\tselected string\n\tquit bool\n}\n\n// InitialModel creates the initial model for agent selection\nfunc InitialModel() AgentSelectorModel {\n\treturn AgentSelectorModel{}\n}\n\n// Init initializes the model\nfunc (m AgentSelectorModel) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update handles incoming messages and updates the model\nfunc (m AgentSelectorModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tsupportedAgents := getSupportedAgents()\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch msg.String() {\n\t\tcase \"ctrl+c\", \"q\", \"esc\":\n\t\t\tm.quit = true\n\t\t\treturn m, tea.Quit\n\t\tcase \"up\", \"k\":\n\t\t\tif m.cursor > 0 {\n\t\t\t\tm.cursor--\n\t\t\t}\n\t\tcase \"down\", \"j\":\n\t\t\tif m.cursor < len(supportedAgents)-1 {\n\t\t\t\tm.cursor++\n\t\t\t}\n\t\tcase \"enter\", \" \":\n\t\t\tm.selected = supportedAgents[m.cursor].Key\n\t\t\tm.quit = true\n\t\t\treturn m, tea.Quit\n\t\t}\n\tdefault:\n\t\treturn m, nil\n\t}\n\treturn m, nil\n}\n\n// View renders the interface\nfunc (m AgentSelectorModel) View() string {\n\tif m.quit {\n\t\treturn \"\"\n\t}\n\n\t// Styles\n\ttitleStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#FAFAFA\")).\n\t\tBackground(lipgloss.Color(\"#7D56F4\")).\n\t\tPadding(0, 1).\n\t\tMargin(1, 0).\n\t\tBold(true)\n\n\theaderStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#7D56F4\")).\n\t\tBold(true).\n\t\tMargin(1, 0, 0, 0)\n\n\tselectedStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#FAFAFA\")).\n\t\tBackground(lipgloss.Color(\"#F25D94\")).\n\t\tPadding(0, 1).\n\t\tBold(true)\n\n\tnormalStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#04B575\")).\n\t\tPadding(0, 1)\n\n\tdescriptionStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#626262\")).\n\t\tPadding(0, 1, 0, 3).\n\t\tItalic(true)\n\n\tfooterStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#626262\")).\n\t\tMargin(1, 0, 0, 0)\n\n\t// Build the view\n\tvar s strings.Builder\n\n\t// Title\n\ts.WriteString(titleStyle.Render(\"🛠️ Container Use Configuration\"))\n\ts.WriteString(\"\\n\")\n\n\t// Header\n\ts.WriteString(headerStyle.Render(\"Select an agent to configure:\"))\n\ts.WriteString(\"\\n\\n\")\n\n\t// Show WSL note for Windows users\n\tif runtime.GOOS == \"windows\" {\n\t\twslNoteStyle := lipgloss.NewStyle().\n\t\t\tForeground(lipgloss.Color(\"#FFA500\")).\n\t\t\tPadding(0, 1).\n\t\t\tItalic(true)\n\t\ts.WriteString(wslNoteStyle.Render(\"Note: OpenAI Codex and Amazon Q Developer are available in WSL\"))\n\t\ts.WriteString(\"\\n\\n\")\n\t}\n\n\t// Agent list TODO: filter or sort agents based on if they are installed (ConfigurableAgent.isInstalled())\n\tsupportedAgents := getSupportedAgents()\n\tfor i, agent := range supportedAgents {\n\t\tcursor := \" \" // not selected\n\t\tif m.cursor == i {\n\t\t\tcursor = \"▶ \" // selected\n\t\t}\n\n\t\tagentLine := fmt.Sprintf(\"%s%s\", cursor, agent.Name)\n\t\tif m.cursor == i {\n\t\t\ts.WriteString(selectedStyle.Render(agentLine))\n\t\t} else {\n\t\t\ts.WriteString(normalStyle.Render(agentLine))\n\t\t}\n\n\t\ts.WriteString(\"\\n\")\n\n\t\t// Show description for selected item\n\t\tif m.cursor == i {\n\t\t\ts.WriteString(descriptionStyle.Render(agent.Description))\n\t\t\ts.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\t// Footer\n\ts.WriteString(\"\\n\")\n\ts.WriteString(footerStyle.Render(\"Use ↑/↓ or j/k to navigate • Enter/Space to select • q/Ctrl+C/Esc to quit\"))\n\n\treturn s.String()\n}\n\n// RunAgentSelector runs the interactive agent selector and returns the selected agent key\nfunc RunAgentSelector() (string, error) {\n\tp := tea.NewProgram(InitialModel())\n\tfinalModel, err := p.Run()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error running agent selector: %w\", err)\n\t}\n\n\tm := finalModel.(AgentSelectorModel)\n\tif m.selected == \"\" {\n\t\treturn \"\", fmt.Errorf(\"no agent selected\")\n\t}\n\n\treturn m.selected, nil\n}\n"], ["/container-use/repository/repository.go", "package repository\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\tpetname \"github.com/dustinkirkland/golang-petname\"\n\t\"github.com/mitchellh/go-homedir\"\n)\n\nconst (\n\tcontainerUseRemote = \"container-use\"\n\tgitNotesLogRef = \"container-use\"\n\tgitNotesStateRef = \"container-use-state\"\n)\n\n// getDefaultConfigPath returns the default configuration path for the current OS\nfunc getDefaultConfigPath() string {\n\tif runtime.GOOS == \"windows\" {\n\t\t// On Windows, use APPDATA or LOCALAPPDATA\n\t\tif appData := os.Getenv(\"APPDATA\"); appData != \"\" {\n\t\t\treturn filepath.Join(appData, \"container-use\")\n\t\t}\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\treturn filepath.Join(localAppData, \"container-use\")\n\t\t}\n\t\t// Fallback to home directory\n\t\tif home, err := homedir.Dir(); err == nil {\n\t\t\treturn filepath.Join(home, \"AppData\", \"Roaming\", \"container-use\")\n\t\t}\n\t\treturn \"container-use\" // Last resort fallback\n\t}\n\t// On Unix-like systems (Linux, macOS, etc.)\n\tif home, err := homedir.Dir(); err == nil {\n\t\treturn filepath.Join(home, \".config\", \"container-use\")\n\t}\n\treturn \"~/.config/container-use\" // Fallback for compatibility\n}\n\nvar (\n\tcuGlobalConfigPath = getDefaultConfigPath()\n)\n\ntype Repository struct {\n\tuserRepoPath string\n\tforkRepoPath string\n\tbasePath string // defaults to OS-appropriate config path if empty\n}\n\n// getRepoPath returns the path for storing repository data\nfunc (r *Repository) getRepoPath() string {\n\treturn filepath.Join(r.basePath, \"repos\")\n}\n\n// getWorktreePath returns the path for storing worktrees\nfunc (r *Repository) getWorktreePath() string {\n\treturn filepath.Join(r.basePath, \"worktrees\")\n}\n\nfunc Open(ctx context.Context, repo string) (*Repository, error) {\n\treturn OpenWithBasePath(ctx, repo, cuGlobalConfigPath)\n}\n\n// OpenWithBasePath opens a repository with a custom base path for container-use data.\n// This is useful for tests that need isolated environments.\nfunc OpenWithBasePath(ctx context.Context, repo string, basePath string) (*Repository, error) {\n\t// Expand tilde in basePath for cross-platform compatibility\n\texpandedBasePath, err := homedir.Expand(basePath)\n\tif err != nil {\n\t\t// If expansion fails, use the original path\n\t\texpandedBasePath = basePath\n\t}\n\n\toutput, err := RunGitCommand(ctx, repo, \"rev-parse\", \"--show-toplevel\")\n\tif err != nil {\n\t\t// Check for exit code 128 which means not a git repository\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 128 {\n\t\t\treturn nil, errors.New(\"you must be in a git repository to use container-use\")\n\t\t}\n\t\treturn nil, err\n\t}\n\tuserRepoPath := strings.TrimSpace(output)\n\n\tforkRepoPath, err := getContainerUseRemote(ctx, userRepoPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Create a temporary repository to get the normalized fork path\n\t\ttempRepo := &Repository{basePath: expandedBasePath}\n\t\tforkRepoPath, err = tempRepo.normalizeForkPath(ctx, userRepoPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr := &Repository{\n\t\tuserRepoPath: userRepoPath,\n\t\tforkRepoPath: forkRepoPath,\n\t\tbasePath: expandedBasePath,\n\t}\n\n\tif err := r.ensureFork(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to fork the repository: %w\", err)\n\t}\n\tif err := r.ensureUserRemote(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to set container-use remote: %w\", err)\n\t}\n\n\treturn r, nil\n}\n\nfunc (r *Repository) ensureFork(ctx context.Context) error {\n\t// Make sure the fork repo path exists, otherwise create it\n\t_, err := os.Stat(r.forkRepoPath)\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tslog.Info(\"Initializing local remote\", \"user-repo\", r.userRepoPath, \"fork-repo\", r.forkRepoPath)\n\tif err := os.MkdirAll(r.forkRepoPath, 0755); err != nil {\n\t\treturn err\n\t}\n\t_, err = RunGitCommand(ctx, r.forkRepoPath, \"init\", \"--bare\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) ensureUserRemote(ctx context.Context) error {\n\tcurrentForkPath, err := getContainerUseRemote(ctx, r.userRepoPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn err\n\t\t}\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"remote\", \"add\", containerUseRemote, r.forkRepoPath)\n\t\treturn err\n\t}\n\n\tif currentForkPath != r.forkRepoPath {\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"remote\", \"set-url\", containerUseRemote, r.forkRepoPath)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) SourcePath() string {\n\treturn r.userRepoPath\n}\n\nfunc (r *Repository) exists(ctx context.Context, id string) error {\n\tif _, err := RunGitCommand(ctx, r.forkRepoPath, \"rev-parse\", \"--verify\", id); err != nil {\n\t\tif strings.Contains(err.Error(), \"Needed a single revision\") {\n\t\t\treturn fmt.Errorf(\"environment %q not found\", id)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Create creates a new environment with the given description and explanation.\n// Requires a dagger client for container operations during environment initialization.\nfunc (r *Repository) Create(ctx context.Context, dag *dagger.Client, description, explanation string) (*environment.Environment, error) {\n\tid := petname.Generate(2, \"-\")\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.createInitialCommit(ctx, worktree, id, description); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create initial commit: %w\", err)\n\t}\n\n\tworktreeHead, err := RunGitCommand(ctx, worktree, \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tworktreeHead = strings.TrimSpace(worktreeHead)\n\n\tbaseSourceDir, err := dag.\n\t\tHost().\n\t\tDirectory(r.forkRepoPath, dagger.HostDirectoryOpts{NoCache: true}). // bust cache for each Create call\n\t\tAsGit().\n\t\tRef(worktreeHead).\n\t\tTree(dagger.GitRefTreeOpts{DiscardGitDir: true}).\n\t\tSync(ctx) // don't bust cache when loading from state\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed loading initial source directory: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(r.userRepoPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := environment.New(ctx, dag, id, description, config, baseSourceDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.propagateToWorktree(ctx, env, explanation); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\n// Get retrieves a full Environment with dagger client embedded for container operations.\n// Use this when you need to perform container operations like running commands, terminals, etc.\n// For basic metadata access without container operations, use Info() instead.\nfunc (r *Repository) Get(ctx context.Context, dag *dagger.Client, id string) (*environment.Environment, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.loadState(ctx, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := environment.Load(ctx, dag, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\n// Info retrieves environment metadata without requiring dagger operations.\n// This is more efficient than Get() when you only need access to configuration,\n// state, and other metadata without performing container operations.\nfunc (r *Repository) Info(ctx context.Context, id string) (*environment.EnvironmentInfo, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.loadState(ctx, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvInfo, err := environment.LoadInfo(ctx, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn envInfo, nil\n}\n\n// List returns information about all environments in the repository.\n// Returns EnvironmentInfo slice avoiding dagger client initialization.\n// Use Get() on individual environments when you need full Environment with container operations.\nfunc (r *Repository) List(ctx context.Context) ([]*environment.EnvironmentInfo, error) {\n\tbranches, err := RunGitCommand(ctx, r.forkRepoPath, \"branch\", \"--format\", \"%(refname:short)\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvs := []*environment.EnvironmentInfo{}\n\tfor branch := range strings.SplitSeq(branches, \"\\n\") {\n\t\tbranch = strings.TrimSpace(branch)\n\n\t\t// FIXME(aluzzardi): This is a hack to make sure the branch is actually an environment.\n\t\t// There must be a better way to do this.\n\t\tworktree, err := r.WorktreePath(branch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstate, err := r.loadState(ctx, worktree)\n\t\tif err != nil || state == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tenvInfo, err := r.Info(ctx, branch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tenvs = append(envs, envInfo)\n\t}\n\n\t// Sort by most recently updated environments first\n\tsort.Slice(envs, func(i, j int) bool {\n\t\treturn envs[i].State.UpdatedAt.After(envs[j].State.UpdatedAt)\n\t})\n\n\treturn envs, nil\n}\n\n// ListDescendantEnvironments returns environments that are descendants of the given commit.\n// This filters environments to only those where the provided commit is an ancestor\n// of the environment's current HEAD. Environments are sorted by most recently updated first.\nfunc (r *Repository) ListDescendantEnvironments(ctx context.Context, ancestorCommit string) ([]*environment.EnvironmentInfo, error) {\n\tallEnvs, err := r.List(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar filteredEnvs []*environment.EnvironmentInfo\n\tfor _, env := range allEnvs {\n\t\tif r.isDescendantOfCommit(ctx, ancestorCommit, env.ID) {\n\t\t\tfilteredEnvs = append(filteredEnvs, env)\n\t\t}\n\t}\n\n\treturn filteredEnvs, nil\n}\n\n// isDescendantOfCommit checks if the environment is a descendant of the given commit\n// using git merge-base --is-ancestor which is the canonical way to check ancestry\nfunc (r *Repository) isDescendantOfCommit(ctx context.Context, ancestorCommit, envID string) bool {\n\tenvRef := fmt.Sprintf(\"container-use/%s\", envID)\n\n\t// Use git merge-base --is-ancestor to check if ancestorCommit is an ancestor of envRef\n\t// This returns exit code 0 if ancestorCommit is an ancestor of envRef\n\t_, err := RunGitCommand(ctx, r.userRepoPath, \"merge-base\", \"--is-ancestor\", ancestorCommit, envRef)\n\n\treturn err == nil\n}\n\n// Update saves the provided environment to the repository.\n// Writes configuration and source code changes to the worktree and history + state to git notes.\nfunc (r *Repository) Update(ctx context.Context, env *environment.Environment, explanation string) error {\n\tif err := r.propagateToWorktree(ctx, env, explanation); err != nil {\n\t\treturn err\n\t}\n\tif note := env.Notes.Pop(); note != \"\" {\n\t\treturn r.addGitNote(ctx, env, note)\n\t}\n\n\treturn nil\n}\n\n// Delete removes an environment from the repository.\nfunc (r *Repository) Delete(ctx context.Context, id string) error {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.deleteWorktree(id); err != nil {\n\t\treturn err\n\t}\n\tif err := r.deleteLocalRemoteBranch(id); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Checkout changes the user's current branch to that of the identified environment.\n// It attempts to get the most recent commit from the environment without discarding any user changes.\nfunc (r *Repository) Checkout(ctx context.Context, id, branch string) (string, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif branch == \"\" {\n\t\tbranch = \"cu-\" + id\n\t}\n\n\t// set up remote tracking branch if it's not already there\n\t_, err := RunGitCommand(ctx, r.userRepoPath, \"show-ref\", \"--verify\", \"--quiet\", fmt.Sprintf(\"refs/heads/%s\", branch))\n\tlocalBranchExists := err == nil\n\tif !localBranchExists {\n\t\t_, err = RunGitCommand(ctx, r.userRepoPath, \"branch\", \"--track\", branch, fmt.Sprintf(\"%s/%s\", containerUseRemote, id))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"checkout\", branch)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif localBranchExists {\n\t\tremoteRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, id)\n\n\t\tcounts, err := RunGitCommand(ctx, r.userRepoPath, \"rev-list\", \"--left-right\", \"--count\", fmt.Sprintf(\"HEAD...%s\", remoteRef))\n\t\tif err != nil {\n\t\t\treturn branch, err\n\t\t}\n\n\t\tparts := strings.Split(strings.TrimSpace(counts), \"\\t\")\n\t\tif len(parts) != 2 {\n\t\t\treturn branch, fmt.Errorf(\"unexpected git rev-list output: %s\", counts)\n\t\t}\n\t\taheadCount, behindCount := parts[0], parts[1]\n\n\t\tif behindCount != \"0\" && aheadCount == \"0\" {\n\t\t\t_, err = RunGitCommand(ctx, r.userRepoPath, \"merge\", \"--ff-only\", remoteRef)\n\t\t\tif err != nil {\n\t\t\t\treturn branch, err\n\t\t\t}\n\t\t} else if behindCount != \"0\" {\n\t\t\treturn branch, fmt.Errorf(\"switched to %s, but %s is %s ahead and container-use/ remote has %s additional commits\", branch, branch, aheadCount, behindCount)\n\t\t}\n\t}\n\n\treturn branch, err\n}\n\nfunc (r *Repository) Log(ctx context.Context, id string, patch bool, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogArgs := []string{\n\t\t\"log\",\n\t\tfmt.Sprintf(\"--notes=%s\", gitNotesLogRef),\n\t}\n\n\tif patch {\n\t\tlogArgs = append(logArgs, \"--patch\")\n\t} else {\n\t\tlogArgs = append(logArgs, \"--format=%C(yellow)%h%Creset %s %Cgreen(%cr)%Creset %+N\")\n\t}\n\n\trevisionRange, err := r.revisionRange(ctx, envInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogArgs = append(logArgs, revisionRange)\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, logArgs...)\n}\n\nfunc (r *Repository) Diff(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiffArgs := []string{\n\t\t\"diff\",\n\t}\n\n\trevisionRange, err := r.revisionRange(ctx, envInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiffArgs = append(diffArgs, revisionRange)\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, diffArgs...)\n}\n\nfunc (r *Repository) Merge(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, \"merge\", \"--no-ff\", \"--autostash\", \"-m\", \"Merge environment \"+envInfo.ID, \"--\", \"container-use/\"+envInfo.ID)\n}\n\nfunc (r *Repository) Apply(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, \"merge\", \"--autostash\", \"--squash\", \"--\", \"container-use/\"+envInfo.ID)\n}\n"], ["/container-use/cmd/container-use/delete.go", "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar deleteCmd = &cobra.Command{\n\tUse: \"delete [...]\",\n\tShort: \"Delete environments and start fresh\",\n\tLong: `Delete one or more environments and their associated resources.\nThis permanently removes the environment's branch and container state.\nUse this when starting over with a different approach.\n\nUse --all to delete all environments at once.`,\n\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\tall, _ := cmd.Flags().GetBool(\"all\")\n\t\tif all && len(args) > 0 {\n\t\t\treturn fmt.Errorf(\"cannot specify environment names when using --all flag\")\n\t\t}\n\t\tif !all && len(args) == 0 {\n\t\t\treturn fmt.Errorf(\"must specify at least one environment name or use --all flag\")\n\t\t}\n\t\treturn nil\n\t},\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Delete a single environment\ncontainer-use delete fancy-mallard\n\n# Delete multiple environments at once\ncontainer-use delete env1 env2 env3\n\n# Delete all environments\ncontainer-use delete --all`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\t\tall, _ := cmd.Flags().GetBool(\"all\")\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tvar envIDs []string\n\t\tif all {\n\t\t\t// Get all environment IDs\n\t\t\tenvs, err := repo.List(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to list environments: %w\", err)\n\t\t\t}\n\t\t\tif len(envs) == 0 {\n\t\t\t\tfmt.Println(\"No environments found to delete.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor _, env := range envs {\n\t\t\t\tenvIDs = append(envIDs, env.ID)\n\t\t\t}\n\t\t\tfmt.Printf(\"Deleting %d environment(s)...\\n\", len(envIDs))\n\t\t} else {\n\t\t\tenvIDs = args\n\t\t}\n\n\t\tfor _, envID := range envIDs {\n\t\t\tif err := repo.Delete(ctx, envID); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete environment '%s': %w\", envID, err)\n\t\t\t}\n\t\t\tfmt.Printf(\"Environment '%s' deleted successfully.\\n\", envID)\n\t\t}\n\n\t\tif all {\n\t\t\tfmt.Printf(\"Successfully deleted %d environment(s).\\n\", len(envIDs))\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(deleteCmd)\n\tdeleteCmd.Flags().Bool(\"all\", false, \"Delete all environments\")\n}\n"], ["/container-use/cmd/container-use/terminal.go", "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar terminalCmd = &cobra.Command{\n\tUse: \"terminal []\",\n\tShort: \"Get a shell inside an environment's container\",\n\tLong: `Open an interactive terminal in the exact container environment the agent used. Perfect for debugging, testing, or hands-on exploration.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Drop into environment's container\ncontainer-use terminal fancy-mallard\n\n# Debug agent's work interactively\ncontainer-use terminal backend-api\n\n# Auto-select environment\ncontainer-use terminal`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// FIXME(aluzzardi): This is a hack to make sure we're wrapped in `dagger run` since `Terminal()` only works with the CLI.\n\t\t// If not, it will auto-wrap this command in a `dagger run`.\n\t\tif _, ok := os.LookupEnv(\"DAGGER_SESSION_TOKEN\"); !ok {\n\t\t\tdaggerBin, err := exec.LookPath(\"dagger\")\n\t\t\tif err != nil {\n\t\t\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\t\t\treturn fmt.Errorf(\"dagger is not installed. Please install it from https://docs.dagger.io/install/\")\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"failed to look up dagger binary: %w\", err)\n\t\t\t}\n\t\t\treturn execDaggerRun(daggerBin, append([]string{\"dagger\", \"run\"}, os.Args...), os.Environ())\n\t\t}\n\n\t\tdag, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr))\n\t\tif err != nil {\n\t\t\tif isDockerDaemonError(err) {\n\t\t\t\thandleDockerDaemonError()\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to connect to dagger: %w\", err)\n\t\t}\n\t\tdefer dag.Close()\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenv, err := repo.Get(ctx, dag, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn env.Terminal(ctx)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(terminalCmd)\n}\n"], ["/container-use/cmd/container-use/list.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/dustin/go-humanize\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar listCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all environments\",\n\tLong: `Display all active environments with their IDs, titles, and timestamps.\nUse -q for environment IDs only, useful for scripting.`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tenvInfos, err := repo.List(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif quiet, _ := app.Flags().GetBool(\"quiet\"); quiet {\n\t\t\tfor _, envInfo := range envInfos {\n\t\t\t\tfmt.Println(envInfo.ID)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\t\tfmt.Fprintln(tw, \"ID\\tTITLE\\tCREATED\\tUPDATED\")\n\n\t\tdefer tw.Flush()\n\t\tfor _, envInfo := range envInfos {\n\t\t\tfmt.Fprintf(tw, \"%s\\t%s\\t%s\\t%s\\n\", envInfo.ID, truncate(app, envInfo.State.Title, 40), humanize.Time(envInfo.State.CreatedAt), humanize.Time(envInfo.State.UpdatedAt))\n\t\t}\n\t\treturn nil\n\t},\n}\n\nfunc truncate(app *cobra.Command, s string, max int) string {\n\tif noTrunc, _ := app.Flags().GetBool(\"no-trunc\"); noTrunc {\n\t\treturn s\n\t}\n\tif len(s) > max {\n\t\treturn s[:max] + \"…\"\n\t}\n\treturn s\n}\n\nfunc init() {\n\tlistCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Display only environment IDs\")\n\tlistCmd.Flags().BoolP(\"no-trunc\", \"\", false, \"Don't truncate output\")\n\trootCmd.AddCommand(listCmd)\n}\n"], ["/container-use/environment/integration/helpers.go", "package integration\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\ttestDaggerClient *dagger.Client\n\tdaggerOnce sync.Once\n\tdaggerErr error\n)\n\n// init sets up logging for tests\nfunc init() {\n\t// Only show warnings and errors in tests unless TEST_VERBOSE is set\n\tlevel := slog.LevelWarn\n\tif os.Getenv(\"TEST_VERBOSE\") != \"\" {\n\t\tlevel = slog.LevelInfo\n\t}\n\n\tslog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{\n\t\tLevel: level,\n\t})))\n}\n\n// WithRepository runs a test function with an isolated repository and UserActions\nfunc WithRepository(t *testing.T, name string, setup RepositorySetup, fn func(t *testing.T, repo *repository.Repository, user *UserActions)) {\n\t// Initialize Dagger (needed for environment operations)\n\tinitializeDaggerOnce(t)\n\n\tctx := context.Background()\n\n\t// Create isolated temp directories\n\trepoDir, err := os.MkdirTemp(\"\", \"cu-test-\"+name+\"-*\")\n\trequire.NoError(t, err, \"Failed to create repo dir\")\n\n\tconfigDir, err := os.MkdirTemp(\"\", \"cu-test-config-\"+name+\"-*\")\n\trequire.NoError(t, err, \"Failed to create config dir\")\n\n\t// Initialize git repo\n\tcmds := [][]string{\n\t\t{\"init\"},\n\t\t{\"config\", \"user.email\", \"test@example.com\"},\n\t\t{\"config\", \"user.name\", \"Test User\"},\n\t\t{\"config\", \"commit.gpgsign\", \"false\"},\n\t}\n\n\tfor _, cmd := range cmds {\n\t\t_, err := repository.RunGitCommand(ctx, repoDir, cmd...)\n\t\trequire.NoError(t, err, \"Failed to run git %v\", cmd)\n\t}\n\n\t// Run setup to populate repo\n\tif setup != nil {\n\t\tsetup(t, repoDir)\n\t}\n\n\t// Open repository with isolated base path\n\trepo, err := repository.OpenWithBasePath(ctx, repoDir, configDir)\n\trequire.NoError(t, err, \"Failed to open repository\")\n\n\t// Create UserActions with extended capabilities\n\tuser := NewUserActions(t, repo, testDaggerClient).WithDirectAccess(repoDir, configDir)\n\n\t// Cleanup\n\tt.Cleanup(func() {\n\t\t// Clean up any environments created during the test\n\t\tenvs, _ := repo.List(context.Background())\n\t\tfor _, env := range envs {\n\t\t\trepo.Delete(context.Background(), env.ID)\n\t\t}\n\n\t\t// Remove directories\n\t\tos.RemoveAll(repoDir)\n\t\tos.RemoveAll(configDir)\n\t})\n\n\t// Run the test function\n\tfn(t, repo, user)\n}\n\n// RepositorySetup is a function that prepares a test repository\ntype RepositorySetup func(t *testing.T, repoDir string)\n\n// Common repository setups\nvar (\n\tSetupPythonRepo = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"main.py\", \"def main():\\n print('Hello World')\\n\\nif __name__ == '__main__':\\n main()\\n\")\n\t\twriteFile(t, repoDir, \"requirements.txt\", \"requests==2.31.0\\nnumpy==1.24.0\\n\")\n\t\twriteFile(t, repoDir, \".gitignore\", \"__pycache__/\\n*.pyc\\n.env\\nvenv/\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Python project\")\n\t}\n\n\tSetupPythonRepoNoGitignore = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"main.py\", \"def main():\\n print('Hello World')\\n\\nif __name__ == '__main__':\\n main()\\n\")\n\t\twriteFile(t, repoDir, \"requirements.txt\", \"requests==2.31.0\\nnumpy==1.24.0\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Python project\")\n\t}\n\n\tSetupNodeRepo = func(t *testing.T, repoDir string) {\n\t\tpackageJSON := `{\n \"name\": \"test-project\",\n \"version\": \"1.0.0\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"node index.js\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"express\": \"^4.18.0\"\n }\n}`\n\t\twriteFile(t, repoDir, \"package.json\", packageJSON)\n\t\twriteFile(t, repoDir, \"index.js\", \"console.log('Hello from Node.js');\\n\")\n\t\twriteFile(t, repoDir, \".gitignore\", \"node_modules/\\n.env\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Node project\")\n\t}\n\n\tSetupEmptyRepo = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"README.md\", \"# Test Project\\n\")\n\t\tgitCommit(t, repoDir, \"Initial commit\")\n\t}\n)\n\n// Helper functions for repository setup\nfunc writeFile(t *testing.T, repoDir, path, content string) {\n\tfullPath := filepath.Join(repoDir, path)\n\tdir := filepath.Dir(fullPath)\n\terr := os.MkdirAll(dir, 0755)\n\trequire.NoError(t, err, \"Failed to create dir\")\n\terr = os.WriteFile(fullPath, []byte(content), 0644)\n\trequire.NoError(t, err, \"Failed to write file\")\n}\n\nfunc gitCommit(t *testing.T, repoDir, message string) {\n\tctx := context.Background()\n\t_, err := repository.RunGitCommand(ctx, repoDir, \"add\", \".\")\n\trequire.NoError(t, err, \"Failed to stage files\")\n\t_, err = repository.RunGitCommand(ctx, repoDir, \"commit\", \"-m\", message)\n\trequire.NoError(t, err, \"Failed to commit\")\n}\n\n// initializeDaggerOnce initializes Dagger client once for all tests\nfunc initializeDaggerOnce(t *testing.T) {\n\tdaggerOnce.Do(func() {\n\t\tif testDaggerClient != nil {\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.Background()\n\t\tclient, err := dagger.Connect(ctx)\n\t\tif err != nil {\n\t\t\tdaggerErr = err\n\t\t\treturn\n\t\t}\n\n\t\ttestDaggerClient = client\n\t})\n\n\tif daggerErr != nil {\n\t\tt.Skipf(\"Skipping test - Dagger not available: %v\", daggerErr)\n\t}\n}\n\n// UserActions provides test helpers that mirror MCP tool behavior exactly\n// These represent what a user would experience when using the MCP tools\ntype UserActions struct {\n\tt *testing.T\n\tctx context.Context\n\trepo *repository.Repository\n\tdag *dagger.Client\n\trepoDir string // Source directory (for direct manipulation)\n\tconfigDir string // Container-use config directory\n}\n\nfunc NewUserActions(t *testing.T, repo *repository.Repository, dag *dagger.Client) *UserActions {\n\treturn &UserActions{\n\t\tt: t,\n\t\tctx: context.Background(),\n\t\trepo: repo,\n\t\tdag: dag,\n\t}\n}\n\n// WithDirectAccess adds direct filesystem access for edge case testing\nfunc (u *UserActions) WithDirectAccess(repoDir, configDir string) *UserActions {\n\tu.repoDir = repoDir\n\tu.configDir = configDir\n\treturn u\n}\n\n// FileWrite mirrors environment_file_write MCP tool behavior\nfunc (u *UserActions) FileWrite(envID, targetFile, contents, explanation string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\terr = env.FileWrite(u.ctx, explanation, targetFile, contents)\n\trequire.NoError(u.t, err, \"FileWrite should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after FileWrite should succeed\")\n}\n\n// RunCommand mirrors environment_run_cmd MCP tool behavior\nfunc (u *UserActions) RunCommand(envID, command, explanation string) string {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\toutput, err := env.Run(u.ctx, command, \"/bin/sh\", false)\n\trequire.NoError(u.t, err, \"Run command should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after Run should succeed\")\n\n\treturn output\n}\n\n// CreateEnvironment mirrors environment_create MCP tool behavior\nfunc (u *UserActions) CreateEnvironment(title, explanation string) *environment.Environment {\n\tenv, err := u.repo.Create(u.ctx, u.dag, title, explanation)\n\trequire.NoError(u.t, err, \"Create environment should succeed\")\n\treturn env\n}\n\n// UpdateEnvironment mirrors environment_update MCP tool behavior\nfunc (u *UserActions) UpdateEnvironment(envID, title, explanation string, config *environment.EnvironmentConfig) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\tif title != \"\" {\n\t\tenv.State.Title = title\n\t}\n\n\terr = env.UpdateConfig(u.ctx, config)\n\trequire.NoError(u.t, err, \"UpdateConfig should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after UpdateConfig should succeed\")\n}\n\n// FileDelete mirrors environment_file_delete MCP tool behavior\nfunc (u *UserActions) FileDelete(envID, targetFile, explanation string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\terr = env.FileDelete(u.ctx, explanation, targetFile)\n\trequire.NoError(u.t, err, \"FileDelete should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after FileDelete should succeed\")\n}\n\n// FileRead mirrors environment_file_read MCP tool behavior (read-only, no update)\nfunc (u *UserActions) FileRead(envID, targetFile string) string {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\tcontent, err := env.FileRead(u.ctx, targetFile, true, 0, 0)\n\trequire.NoError(u.t, err, \"FileRead should succeed\")\n\treturn content\n}\n\n// FileReadExpectError is for testing expected failures\nfunc (u *UserActions) FileReadExpectError(envID, targetFile string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\t_, err = env.FileRead(u.ctx, targetFile, true, 0, 0)\n\tassert.Error(u.t, err, \"FileRead should fail for %s\", targetFile)\n}\n\n// GetEnvironment retrieves an environment by ID - mirrors how MCP tools work\n// Each MCP tool call starts fresh by getting the environment from the repository\nfunc (u *UserActions) GetEnvironment(envID string) *environment.Environment {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Should be able to get environment %s\", envID)\n\treturn env\n}\n\n// --- Direct manipulation methods for edge case testing ---\n\n// WriteSourceFile writes directly to the source repository\nfunc (u *UserActions) WriteSourceFile(path, content string) {\n\trequire.NotEmpty(u.t, u.repoDir, \"Need direct access for source file manipulation\")\n\tfullPath := filepath.Join(u.repoDir, path)\n\tdir := filepath.Dir(fullPath)\n\n\terr := os.MkdirAll(dir, 0755)\n\trequire.NoError(u.t, err, \"Failed to create dir\")\n\n\terr = os.WriteFile(fullPath, []byte(content), 0644)\n\trequire.NoError(u.t, err, \"Failed to write source file\")\n}\n\n// WorktreePath returns the worktree path for an environment, handling errors\nfunc (u *UserActions) WorktreePath(envID string) string {\n\tworktreePath, err := u.repo.WorktreePath(envID)\n\trequire.NoError(u.t, err, \"Failed to get worktree path for environment %s\", envID)\n\treturn worktreePath\n}\n\n// ReadWorktreeFile reads directly from an environment's worktree\nfunc (u *UserActions) ReadWorktreeFile(envID, path string) string {\n\tworktreePath := u.WorktreePath(envID)\n\tfullPath := filepath.Join(worktreePath, path)\n\tcontent, err := os.ReadFile(fullPath)\n\trequire.NoError(u.t, err, \"Failed to read worktree file\")\n\treturn string(content)\n}\n\n// CorruptWorktree simulates worktree corruption for recovery testing\nfunc (u *UserActions) CorruptWorktree(envID string) {\n\tworktreePath := u.WorktreePath(envID)\n\n\t// Remove .git directory to corrupt the worktree\n\tgitDir := filepath.Join(worktreePath, \".git\")\n\terr := os.RemoveAll(gitDir)\n\trequire.NoError(u.t, err, \"Failed to corrupt worktree\")\n}\n\n// GitCommand runs a git command in the source repository\nfunc (u *UserActions) GitCommand(args ...string) string {\n\trequire.NotEmpty(u.t, u.repoDir, \"Need direct access for git commands\")\n\toutput, err := repository.RunGitCommand(u.ctx, u.repoDir, args...)\n\trequire.NoError(u.t, err, \"Git command failed: %v\", args)\n\treturn output\n}\n"], ["/container-use/cmd/container-use/merge.go", "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tmergeDelete bool\n)\n\nvar mergeCmd = &cobra.Command{\n\tUse: \"merge []\",\n\tShort: \"Accept an environment's work into your branch\",\n\tLong: `Merge an environment's changes into your current git branch.\nThis makes the agent's work permanent in your repository.\nYour working directory will be automatically stashed and restored.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Accept agent's work into current branch\ncontainer-use merge backend-api\n\n# Merge and delete the environment after successful merge\ncontainer-use merge -d backend-api\ncontainer-use merge --delete backend-api\n\n# Auto-select environment\ncontainer-use merge`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := repo.Merge(ctx, envID, os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge environment: %w\", err)\n\t\t}\n\n\t\treturn deleteAfterMerge(ctx, repo, envID, mergeDelete, \"merged\")\n\t},\n}\n\nfunc deleteAfterMerge(ctx context.Context, repo *repository.Repository, env string, delete bool, verb string) error {\n\tif !delete {\n\t\tfmt.Printf(\"Environment '%s' %s successfully.\\n\", env, verb)\n\t\treturn nil\n\t}\n\tif err := repo.Delete(ctx, env); err != nil {\n\t\treturn fmt.Errorf(\"environment '%s' %s but delete failed: %w\", env, verb, err)\n\t}\n\tfmt.Printf(\"Environment '%s' %s and deleted successfully.\\n\", env, verb)\n\treturn nil\n}\n\nfunc init() {\n\tmergeCmd.Flags().BoolVarP(&mergeDelete, \"delete\", \"d\", false, \"Delete the environment after successful merge\")\n\n\trootCmd.AddCommand(mergeCmd)\n}\n"], ["/container-use/mcpserver/tools.go", "package mcpserver\n\nimport (\n\t\"context\"\n\t_ \"embed\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n\t\"github.com/mark3labs/mcp-go/server\"\n)\n\ntype daggerClientKey struct{}\n\nfunc openRepository(ctx context.Context, request mcp.CallToolRequest) (*repository.Repository, error) {\n\tsource, err := request.RequireString(\"environment_source\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trepo, err := repository.Open(ctx, source)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open repository: %w\", err)\n\t}\n\treturn repo, nil\n}\n\nfunc openEnvironment(ctx context.Context, request mcp.CallToolRequest) (*repository.Repository, *environment.Environment, error) {\n\trepo, err := openRepository(ctx, request)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tenvID, err := request.RequireString(\"environment_id\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdag, ok := ctx.Value(daggerClientKey{}).(*dagger.Client)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"dagger client not found in context\")\n\t}\n\tenv, err := repo.Get(ctx, dag, envID)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to get environment: %w\", err)\n\t}\n\treturn repo, env, nil\n}\n\ntype Tool struct {\n\tDefinition mcp.Tool\n\tHandler server.ToolHandlerFunc\n}\n\nfunc RunStdioServer(ctx context.Context, dag *dagger.Client) error {\n\ts := server.NewMCPServer(\n\t\t\"Dagger\",\n\t\t\"1.0.0\",\n\t\tserver.WithInstructions(rules.AgentRules),\n\t)\n\n\tfor _, t := range tools {\n\t\ts.AddTool(t.Definition, wrapToolWithClient(t, dag).Handler)\n\t}\n\n\tslog.Info(\"starting server\")\n\n\tstdioSrv := server.NewStdioServer(s)\n\tstdioSrv.SetErrorLogger(log.Default()) // this should re-use our `slog` handler\n\n\tctx, cancel := signal.NotifyContext(ctx, getNotifySignals()...)\n\tdefer cancel()\n\n\terr := stdioSrv.Listen(ctx, os.Stdin, os.Stdout)\n\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nvar tools = []*Tool{}\n\nfunc Tools() []*Tool {\n\treturn tools\n}\n\nfunc registerTool(tool ...*Tool) {\n\tfor _, t := range tool {\n\t\ttools = append(tools, wrapTool(t))\n\t}\n}\n\nfunc wrapTool(tool *Tool) *Tool {\n\treturn &Tool{\n\t\tDefinition: tool.Definition,\n\t\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t\tslog.Info(\"Tool called\", \"tool\", tool.Definition.Name)\n\t\t\tdefer func() {\n\t\t\t\tslog.Info(\"Tool finished\", \"tool\", tool.Definition.Name)\n\t\t\t}()\n\t\t\tresponse, err := tool.Handler(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\treturn mcp.NewToolResultError(err.Error()), nil\n\t\t\t}\n\t\t\treturn response, nil\n\t\t},\n\t}\n}\n\n// keeping this modular for now. we could move tool registration to RunStdioServer and collapse the 2 wrapTool functions.\nfunc wrapToolWithClient(tool *Tool, dag *dagger.Client) *Tool {\n\treturn &Tool{\n\t\tDefinition: tool.Definition,\n\t\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t\tctx = context.WithValue(ctx, daggerClientKey{}, dag)\n\t\t\treturn tool.Handler(ctx, request)\n\t\t},\n\t}\n}\n\nfunc init() {\n\tregisterTool(\n\t\tEnvironmentOpenTool,\n\t\tEnvironmentCreateTool,\n\t\tEnvironmentUpdateMetadataTool,\n\t\tEnvironmentConfigTool,\n\n\t\tEnvironmentRunCmdTool,\n\n\t\tEnvironmentFileReadTool,\n\t\tEnvironmentFileListTool,\n\t\tEnvironmentFileWriteTool,\n\t\tEnvironmentFileEditTool,\n\t\tEnvironmentFileDeleteTool,\n\n\t\tEnvironmentAddServiceTool,\n\n\t\tEnvironmentCheckpointTool,\n\t)\n}\n\ntype EnvironmentResponse struct {\n\tID string `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tConfig *environment.EnvironmentConfig `json:\"config\"`\n\tRemoteRef string `json:\"remote_ref\"`\n\tCheckoutCommand string `json:\"checkout_command_to_share_with_user\"`\n\tLogCommand string `json:\"log_command_to_share_with_user\"`\n\tDiffCommand string `json:\"diff_command_to_share_with_user\"`\n\tServices []*environment.Service `json:\"services,omitempty\"`\n}\n\nfunc environmentResponseFromEnvInfo(envInfo *environment.EnvironmentInfo) *EnvironmentResponse {\n\treturn &EnvironmentResponse{\n\t\tID: envInfo.ID,\n\t\tTitle: envInfo.State.Title,\n\t\tConfig: envInfo.State.Config,\n\t\tRemoteRef: fmt.Sprintf(\"container-use/%s\", envInfo.ID),\n\t\tCheckoutCommand: fmt.Sprintf(\"container-use checkout %s\", envInfo.ID),\n\t\tLogCommand: fmt.Sprintf(\"container-use log %s\", envInfo.ID),\n\t\tDiffCommand: fmt.Sprintf(\"container-use diff %s\", envInfo.ID),\n\t\tServices: nil, // EnvironmentInfo doesn't have \"active\" services, specifically useful for EndpointMappings\n\t}\n}\n\nfunc environmentResponseFromEnv(env *environment.Environment) *EnvironmentResponse {\n\tresp := environmentResponseFromEnvInfo(env.EnvironmentInfo)\n\tresp.Services = env.Services\n\treturn resp\n}\n\nfunc marshalEnvironment(env *environment.Environment) (string, error) {\n\tout, err := json.Marshal(environmentResponseFromEnv(env))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal response: %w\", err)\n\t}\n\treturn string(out), nil\n}\n\nfunc marshalEnvironmentInfo(envInfo *environment.EnvironmentInfo) (string, error) {\n\tout, err := json.Marshal(environmentResponseFromEnvInfo(envInfo))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal response: %w\", err)\n\t}\n\treturn string(out), nil\n}\n\nfunc EnvironmentToCallResult(env *environment.Environment) (*mcp.CallToolResult, error) {\n\tout, err := marshalEnvironment(env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mcp.NewToolResultText(out), nil\n}\n\nfunc EnvironmentInfoToCallResult(envInfo *environment.EnvironmentInfo) (*mcp.CallToolResult, error) {\n\tout, err := marshalEnvironmentInfo(envInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mcp.NewToolResultText(out), nil\n}\n\nvar EnvironmentOpenTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_open\",\n\t\t\"Opens an existing environment. Return format is same as environment_create.\",\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn EnvironmentToCallResult(env)\n\t},\n}\n\nvar EnvironmentCreateTool = &Tool{\n\tDefinition: newRepositoryTool(\n\t\t\"environment_create\",\n\t\t`Creates a new development environment.\nThe environment is the result of a the setups commands on top of the base image.\nEnvironment configuration is managed by the user via cu config commands.`,\n\t\tmcp.WithString(\"title\",\n\t\t\tmcp.Description(\"Short description of the work that is happening in this environment.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, err := openRepository(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttitle, err := request.RequireString(\"title\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdag, ok := ctx.Value(daggerClientKey{}).(*dagger.Client)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"dagger client not found in context\")\n\t\t}\n\n\t\tenv, err := repo.Create(ctx, dag, title, request.GetString(\"explanation\", \"\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create environment: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\n\t\tdirty, status, err := repo.IsDirty(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to check if environment is dirty: %w\", err)\n\t\t}\n\n\t\tif !dirty {\n\t\t\treturn mcp.NewToolResultText(out), nil\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(`%s\n\nCRITICAL: You MUST inform the user that the repository %s has uncommitted changes that are NOT included in this environment. The environment was created from the last committed state only.\n\nUncommitted changes detected:\n%s\n\nYou MUST tell the user: To include these changes in the environment, they need to commit them first using git commands outside the environment.`, out, request.GetString(\"environment_source\", \"\"), status)), nil\n\t},\n}\n\nvar EnvironmentUpdateMetadataTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_update_metadata\",\n\t\t\"Update environment metadata such as title. This updates the descriptive information about what work is being done in the environment.\",\n\t\tmcp.WithString(\"title\",\n\t\t\tmcp.Description(\"Updated title describing the work being done in this environment.\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Update title if provided\n\t\tif title := request.GetString(\"title\", \"\"); title != \"\" {\n\t\t\tenv.State.Title = title\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Environment metadata updated successfully.\\n%s\", out)), nil\n\t},\n}\n\nvar EnvironmentConfigTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_config\",\n\t\t\"Make environment config changes such as base image and setup commands.\"+\n\t\t\t\"If the environment is missing any tools or instructions, you MUST call this function to update the environment.\"+\n\t\t\t\"You MUST update the environment with any useful tools. You will be resumed with no other context than the information provided here\",\n\t\tmcp.WithObject(\"config\",\n\t\t\tmcp.Required(),\n\t\t\tmcp.Properties(map[string]any{\n\t\t\t\t\"base_image\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Base image for the environment\",\n\t\t\t\t},\n\t\t\t\t\"setup_commands\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Commands that should be executed on top of the base image to set up the environment. Similar to `RUN` instructions in Dockerfiles.\",\n\t\t\t\t\t\"items\": map[string]any{\"type\": \"string\"},\n\t\t\t\t},\n\t\t\t\t\"envs\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"The environment variables to set (e.g. `[\\\"FOO=bar\\\", \\\"BAZ=qux\\\"]`).\",\n\t\t\t\t\t\"items\": map[string]any{\"type\": \"string\"},\n\t\t\t\t},\n\t\t\t}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tupdatedConfig := env.State.Config.Copy()\n\n\t\tnewConfig, ok := request.GetArguments()[\"config\"].(map[string]any)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid config\")\n\t\t}\n\n\t\tif baseImage, ok := newConfig[\"base_image\"].(string); ok {\n\t\t\tupdatedConfig.BaseImage = baseImage\n\t\t}\n\n\t\tif setupCommands, ok := newConfig[\"setup_commands\"].([]any); ok {\n\t\t\tupdatedConfig.SetupCommands = make([]string, len(setupCommands))\n\t\t\tfor i, command := range setupCommands {\n\t\t\t\tupdatedConfig.SetupCommands[i] = command.(string)\n\t\t\t}\n\t\t}\n\n\t\tif envs, ok := newConfig[\"envs\"].([]any); ok {\n\t\t\tupdatedConfig.Env = make([]string, len(envs))\n\t\t\tfor i, env := range envs {\n\t\t\t\tupdatedConfig.Env[i] = env.(string)\n\t\t\t}\n\t\t}\n\n\t\tif err := env.UpdateConfig(ctx, updatedConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update repository: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\n\t\tmessage := fmt.Sprintf(`SUCCESS: Configuration successfully applied. Environment has been restarted, all previous commands have been lost.\nIMPORTANT: The configuration changes are LOCAL to this environment.\nTELL THE USER: To make these changes persistent, they will have to run \"cu config import %s\"\n\n%s\n`, env.ID, out)\n\n\t\treturn mcp.NewToolResultText(message), nil\n\t},\n}\n\nvar EnvironmentListTool = &Tool{\n\tDefinition: newRepositoryTool(\n\t\t\"environment_list\",\n\t\t\"List available environments\",\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, err := openRepository(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenvInfos, err := repo.List(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid source: %w\", err)\n\t\t}\n\n\t\t// Convert EnvironmentInfo slice to EnvironmentResponse slice\n\t\tresponses := make([]EnvironmentResponse, len(envInfos))\n\t\tfor i, envInfo := range envInfos {\n\t\t\tresponses[i] = *environmentResponseFromEnvInfo(envInfo)\n\t\t}\n\n\t\tout, err := json.Marshal(responses)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn mcp.NewToolResultText(string(out)), nil\n\t},\n}\n\nvar EnvironmentRunCmdTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_run_cmd\",\n\t\t\"Run a terminal command inside a NEW container within the environment.\",\n\t\tmcp.WithString(\"command\",\n\t\t\tmcp.Description(\"The terminal command to execute. If empty, the environment's default command is used.\"),\n\t\t),\n\t\tmcp.WithString(\"shell\",\n\t\t\tmcp.Description(\"The shell that will be interpreting this command (default: sh)\"),\n\t\t),\n\t\tmcp.WithBoolean(\"background\",\n\t\t\tmcp.Description(`Run the command in the background\nMust ALWAYS be set for long running command (e.g. http server).\nFailure to do so will result in the tool being stuck, awaiting for the command to finish.`,\n\t\t\t),\n\t\t),\n\t\tmcp.WithBoolean(\"use_entrypoint\",\n\t\t\tmcp.Description(\"Use the image entrypoint, if present, by prepending it to the args.\"),\n\t\t),\n\t\tmcp.WithArray(\"ports\",\n\t\t\tmcp.Description(\"Ports to expose. Only works with background environments. For each port, returns the environment_internal (for use inside environments) and host_external (for use by the user) addresses.\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"number\"}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcommand := request.GetString(\"command\", \"\")\n\t\tshell := request.GetString(\"shell\", \"sh\")\n\n\t\tupdateRepo := func() error {\n\t\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update repository: %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tbackground := request.GetBool(\"background\", false)\n\t\tif background {\n\t\t\tports := []int{}\n\t\t\tif portList, ok := request.GetArguments()[\"ports\"].([]any); ok {\n\t\t\t\tfor _, port := range portList {\n\t\t\t\t\tports = append(ports, int(port.(float64)))\n\t\t\t\t}\n\t\t\t}\n\t\t\tendpoints, runErr := env.RunBackground(ctx, command, shell, ports, request.GetBool(\"use_entrypoint\", false))\n\t\t\t// We want to update the repository even if the command failed.\n\t\t\tif err := updateRepo(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif runErr != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to run command: %w\", runErr)\n\t\t\t}\n\n\t\t\tout, err := json.Marshal(endpoints)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn mcp.NewToolResultText(fmt.Sprintf(`Command started in the background in NEW container. Endpoints are %s\n\nTo access from the user's machine: use host_external. To access from other commands in this environment: use environment_internal.\n\nAny changes to the container workdir (%s) WILL NOT be committed to container-use/%s\n\nBackground commands are unaffected by filesystem and any other kind of changes. You need to start a new command for changes to take effect.`,\n\t\t\t\tstring(out), env.State.Config.Workdir, env.ID)), nil\n\t\t}\n\n\t\tstdout, runErr := env.Run(ctx, command, shell, request.GetBool(\"use_entrypoint\", false))\n\t\t// We want to update the repository even if the command failed.\n\t\tif err := updateRepo(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif runErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to run command: %w\", runErr)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"%s\\n\\nAny changes to the container workdir (%s) have been committed and pushed to container-use/ remote\", stdout, env.State.Config.Workdir)), nil\n\t},\n}\n\nvar EnvironmentFileReadTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_read\",\n\t\t\"Read the contents of a file, specifying a line range or the entire file.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to read, absolute or relative to the workdir\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithBoolean(\"should_read_entire_file\",\n\t\t\tmcp.Description(\"Whether to read the entire file. Defaults to false.\"),\n\t\t),\n\t\tmcp.WithNumber(\"start_line_one_indexed_inclusive\",\n\t\t\tmcp.Description(\"The one-indexed line number to start reading from (inclusive).\"),\n\t\t),\n\t\tmcp.WithNumber(\"end_line_one_indexed_inclusive\",\n\t\t\tmcp.Description(\"The one-indexed line number to end reading at (inclusive).\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshouldReadEntireFile := request.GetBool(\"should_read_entire_file\", false)\n\t\tstartLineOneIndexedInclusive := request.GetInt(\"start_line_one_indexed_inclusive\", 0)\n\t\tendLineOneIndexedInclusive := request.GetInt(\"end_line_one_indexed_inclusive\", 0)\n\n\t\tfileContents, err := env.FileRead(ctx, targetFile, shouldReadEntireFile, startLineOneIndexedInclusive, endLineOneIndexedInclusive)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read file: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fileContents), nil\n\t},\n}\n\nvar EnvironmentFileListTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_list\",\n\t\t\"List the contents of a directory\",\n\t\tmcp.WithString(\"path\",\n\t\t\tmcp.Description(\"Path of the directory to list contents of, absolute or relative to the workdir\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpath, err := request.RequireString(\"path\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tout, err := env.FileList(ctx, path)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list directory: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(out), nil\n\t},\n}\n\nvar EnvironmentFileWriteTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_write\",\n\t\t\"Write the contents of a file.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to write, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"contents\",\n\t\t\tmcp.Description(\"Full text content of the file you want to write.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcontents, err := request.RequireString(\"contents\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileWrite(ctx, request.GetString(\"explanation\", \"\"), targetFile, contents); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to write file: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s written successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentFileEditTool = &Tool{\n\tDefinition: mcp.NewTool(\"environment_file_edit\",\n\t\tmcp.WithDescription(\"Find and replace text in a file.\"),\n\t\tmcp.WithString(\"explanation\",\n\t\t\tmcp.Description(\"One sentence explanation for why this file is being edited.\"),\n\t\t),\n\t\tmcp.WithString(\"environment_source\",\n\t\t\tmcp.Description(\"Absolute path to the source git repository for the environment.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"environment_id\",\n\t\t\tmcp.Description(\"The ID of the environment for this command. Must call `environment_create` first.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to write, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"search_text\",\n\t\t\tmcp.Description(\"The text to find and replace.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"replace_text\",\n\t\t\tmcp.Description(\"The text to insert.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"which_match\",\n\t\t\tmcp.Description(\"The ID of the match to replace, if there were multiple matches.\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"unable to open the environment\", err), nil\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsearch, err := request.RequireString(\"search_text\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treplace, err := request.RequireString(\"replace_text\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileEdit(ctx,\n\t\t\trequest.GetString(\"explanation\", \"\"),\n\t\t\ttargetFile,\n\t\t\tsearch,\n\t\t\treplace,\n\t\t\trequest.GetString(\"which_match\", \"\"),\n\t\t); err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"failed to write file\", err), nil\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"unable to update the environment\", err), nil\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s edited successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentFileDeleteTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_delete\",\n\t\t\"Deletes a file at the specified path.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to delete, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileDelete(ctx, request.GetString(\"explanation\", \"\"), targetFile); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update env: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s deleted successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentCheckpointTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_checkpoint\",\n\t\t\"Checkpoints an environment in its current state as a container.\",\n\t\tmcp.WithString(\"destination\",\n\t\t\tmcp.Description(\"Container image destination to checkpoint to (e.g. registry.com/user/image:tag\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdestination, err := request.RequireString(\"destination\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tendpoint, err := env.Checkpoint(ctx, destination)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to checkpoint environment: %w\", err)\n\t\t}\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Checkpoint pushed to %q. You MUST use the full content addressed (@sha256:...) reference in `docker` commands. The entrypoint is set to `sh`, keep that in mind when giving commands to the container.\", endpoint)), nil\n\t},\n}\n\nvar EnvironmentAddServiceTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_add_service\",\n\t\t\"Add a service to the environment (e.g. database, cache, etc.)\",\n\t\tmcp.WithString(\"name\",\n\t\t\tmcp.Description(\"The name of the service to start.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"image\",\n\t\t\tmcp.Description(\"The image of the service to start.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"command\",\n\t\t\tmcp.Description(\"The command to start the service. If not provided the image default command will be used.\"),\n\t\t),\n\t\tmcp.WithArray(\"ports\",\n\t\t\tmcp.Description(\"Ports to expose. For each port, returns the container_internal (for use by environments) and host_external (for use by the user) address.\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"number\"}),\n\t\t),\n\t\tmcp.WithArray(\"envs\",\n\t\t\tmcp.Description(\"The environment variables to set (e.g. `[\\\"FOO=bar\\\", \\\"BAZ=qux\\\"]`).\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"string\"}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserviceName, err := request.RequireString(\"name\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\timage, err := request.RequireString(\"image\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcommand := request.GetString(\"command\", \"\")\n\t\tports := []int{}\n\t\tif portList, ok := request.GetArguments()[\"ports\"].([]any); ok {\n\t\t\tfor _, port := range portList {\n\t\t\t\tports = append(ports, int(port.(float64)))\n\t\t\t}\n\t\t}\n\n\t\tenvs := request.GetStringSlice(\"envs\", []string{})\n\n\t\tservice, err := env.AddService(ctx, request.GetString(\"explanation\", \"\"), &environment.ServiceConfig{\n\t\t\tName: serviceName,\n\t\t\tImage: image,\n\t\t\tCommand: command,\n\t\t\tExposedPorts: ports,\n\t\t\tEnv: envs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add service: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update env: %w\", err)\n\t\t}\n\n\t\toutput, err := json.Marshal(service)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal service: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Service added and started successfully: %s\", string(output))), nil\n\t},\n}\n"], ["/container-use/cmd/container-use/apply.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tapplyDelete bool\n)\n\nvar applyCmd = &cobra.Command{\n\tUse: \"apply []\",\n\tShort: \"Apply an environment's work as staged changes to your branch\",\n\tLong: `Apply an environment's changes to your current git branch as staged modifications.\nUnlike 'merge' which preserves the original commit history, 'apply' stages all changes\nfor you to commit manually, discarding the original commit sequence. This lets you\nreview and customize the final commit before making the agent's work permanent.\nYour working directory will be automatically stashed and restored.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Apply agent's work as staged changes to current branch\ncu apply backend-api\n\n# Apply and delete the environment after successful application\ncu apply -d backend-api\ncu apply --delete backend-api\n\n# After applying, you can review and commit the changes\ngit status\ngit commit -m \"Add backend API implementation\"\n\n# Auto-select environment\ncu apply`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := repo.Apply(ctx, envID, os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply environment: %w\", err)\n\t\t}\n\n\t\treturn deleteAfterMerge(ctx, repo, envID, applyDelete, \"applied\")\n\t},\n}\n\nfunc init() {\n\tapplyCmd.Flags().BoolVarP(&applyDelete, \"delete\", \"d\", false, \"Delete the environment after successful application\")\n\n\trootCmd.AddCommand(applyCmd)\n}\n"], ["/container-use/cmd/container-use/main.go", "package main\n\nimport (\n\t\"context\"\n\t_ \"embed\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/fang\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\trootCmd = &cobra.Command{\n\t\tUse: \"container-use\",\n\t\tShort: \"Containerized environments for coding agents\",\n\t\tLong: `Container Use creates isolated development environments for AI agents.\nEach environment runs in its own container with dedicated git branches.`,\n\t}\n)\n\nfunc main() {\n\tctx := context.Background()\n\tsetupSignalHandling()\n\n\tif err := setupLogger(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to setup logger: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// FIXME(aluzzardi): `fang` misbehaves with the `stdio` command.\n\t// It hangs on Ctrl-C. Traced the hang back to `lipgloss.HasDarkBackground(os.Stdin, os.Stdout)`\n\t// I'm assuming it's not playing nice the mcpserver listening on stdio.\n\tif len(os.Args) > 1 && os.Args[1] == \"stdio\" {\n\t\tif err := rootCmd.ExecuteContext(ctx); err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n\n\tif err := fang.Execute(\n\t\tctx,\n\t\trootCmd,\n\t\tfang.WithVersion(version),\n\t\tfang.WithCommit(commit),\n\t\tfang.WithNotifySignal(getNotifySignals()...),\n\t); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc suggestEnvironments(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tctx := cmd.Context()\n\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn nil, cobra.ShellCompDirectiveError\n\t}\n\n\tenvs, err := repo.List(ctx)\n\tif err != nil {\n\t\treturn nil, cobra.ShellCompDirectiveError\n\t}\n\n\tids := []string{}\n\tfor _, e := range envs {\n\t\tids = append(ids, e.ID)\n\t}\n\treturn ids, cobra.ShellCompDirectiveKeepOrder\n}\n"], ["/container-use/cmd/container-use/checkout.go", "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar checkoutCmd = &cobra.Command{\n\tUse: \"checkout []\",\n\tShort: \"Switch to an environment's branch locally\",\n\tLong: `Bring an environment's work into your local git workspace.\nThis creates a local branch from the environment's state so you can\nexplore files in your IDE, make changes, or continue development.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Switch to environment's branch locally\ncontainer-use checkout fancy-mallard\n\n# Create custom branch name\ncontainer-use checkout fancy-mallard -b my-review-branch\n\n# Auto-select environment\ncontainer-use checkout`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbranchName, err := app.Flags().GetString(\"branch\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbranch, err := repo.Checkout(ctx, envID, branchName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"Switched to branch '%s'\\n\", branch)\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\tcheckoutCmd.Flags().StringP(\"branch\", \"b\", \"\", \"Local branch name to use\")\n\trootCmd.AddCommand(checkoutCmd)\n}\n"], ["/container-use/cmd/container-use/log.go", "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar logCmd = &cobra.Command{\n\tUse: \"log []\",\n\tShort: \"View what an agent did step-by-step\",\n\tLong: `Display the complete development history for an environment.\nShows all commits made by the agent plus command execution notes.\nUse -p to include code patches in the output.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# See what agent did\ncontainer-use log fancy-mallard\n\n# Include code changes\ncontainer-use log fancy-mallard -p\n\n# Auto-select environment\ncontainer-use log`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpatch, _ := app.Flags().GetBool(\"patch\")\n\n\t\treturn repo.Log(ctx, envID, patch, os.Stdout)\n\t},\n}\n\nfunc init() {\n\tlogCmd.Flags().BoolP(\"patch\", \"p\", false, \"Generate patch\")\n\trootCmd.AddCommand(logCmd)\n}\n"], ["/container-use/environment/config.go", "package environment\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tdefaultImage = \"ubuntu:24.04\"\n\talpineImage = \"alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c\"\n\tconfigDir = \".container-use\"\n\tenvironmentFile = \"environment.json\"\n)\n\nfunc DefaultConfig() *EnvironmentConfig {\n\treturn &EnvironmentConfig{\n\t\tBaseImage: defaultImage,\n\t\tWorkdir: \"/workdir\",\n\t}\n}\n\ntype EnvironmentConfig struct {\n\tWorkdir string `json:\"workdir,omitempty\"`\n\tBaseImage string `json:\"base_image,omitempty\"`\n\tSetupCommands []string `json:\"setup_commands,omitempty\"`\n\tInstallCommands []string `json:\"install_commands,omitempty\"`\n\tEnv KVList `json:\"env,omitempty\"`\n\tSecrets KVList `json:\"secrets,omitempty\"`\n\tServices ServiceConfigs `json:\"services,omitempty\"`\n}\n\ntype ServiceConfig struct {\n\tName string `json:\"name,omitempty\"`\n\tImage string `json:\"image,omitempty\"`\n\tCommand string `json:\"command,omitempty\"`\n\tExposedPorts []int `json:\"exposed_ports,omitempty\"`\n\tEnv []string `json:\"env,omitempty\"`\n}\n\ntype ServiceConfigs []*ServiceConfig\n\nfunc (sc ServiceConfigs) Get(name string) *ServiceConfig {\n\tfor _, cfg := range sc {\n\t\tif cfg.Name == name {\n\t\t\treturn cfg\n\t\t}\n\t}\n\treturn nil\n}\n\n// KVList represents a list of key-value pairs in the format KEY=VALUE\ntype KVList []string\n\n// parseKeyValue parses a key-value string in the format \"KEY=VALUE\"\nfunc (kv KVList) parseKeyValue(raw string) (key, value string) {\n\tk, v, _ := strings.Cut(raw, \"=\")\n\treturn k, v\n}\n\n// Set adds or updates a key-value pair\nfunc (kv *KVList) Set(key, value string) {\n\t// Remove existing key if it exists\n\tkv.Unset(key)\n\t// Add new key-value pair\n\t*kv = append(*kv, fmt.Sprintf(\"%s=%s\", key, value))\n}\n\n// Unset removes a key-value pair by key and returns true if the key was found\nfunc (kv *KVList) Unset(key string) bool {\n\tfound := false\n\tnewList := make([]string, 0, len(*kv))\n\tfor _, item := range *kv {\n\t\tif itemKey, _ := kv.parseKeyValue(item); itemKey != key {\n\t\t\tnewList = append(newList, item)\n\t\t} else {\n\t\t\tfound = true\n\t\t}\n\t}\n\t*kv = newList\n\treturn found\n}\n\n// Clear removes all key-value pairs\nfunc (kv *KVList) Clear() {\n\t*kv = []string{}\n}\n\n// Keys returns all keys in the list\nfunc (kv KVList) Keys() []string {\n\tkeys := make([]string, 0, len(kv))\n\tfor _, item := range kv {\n\t\tif key, _ := kv.parseKeyValue(item); key != \"\" {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\treturn keys\n}\n\n// Get returns the value for a given key, or empty string if not found\nfunc (kv KVList) Get(key string) string {\n\tfor _, item := range kv {\n\t\tif itemKey, value := kv.parseKeyValue(item); itemKey == key {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (config *EnvironmentConfig) Copy() *EnvironmentConfig {\n\tcopy := *config\n\tcopy.Services = make(ServiceConfigs, len(config.Services))\n\tfor i, svc := range config.Services {\n\t\tsvcCopy := *svc\n\t\tcopy.Services[i] = &svcCopy\n\t}\n\treturn ©\n}\n\nfunc (config *EnvironmentConfig) Save(baseDir string) error {\n\tconfigPath := filepath.Join(baseDir, configDir)\n\tif err := os.MkdirAll(configPath, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t// Use a custom encoder to prevent HTML escaping of characters like &, <, >\n\tvar buf bytes.Buffer\n\tencoder := json.NewEncoder(&buf)\n\tencoder.SetIndent(\"\", \" \")\n\tencoder.SetEscapeHTML(false) // This prevents & from being escaped as \\u0026\n\n\tif err := encoder.Encode(config); err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.WriteFile(filepath.Join(configPath, environmentFile), buf.Bytes(), 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (config *EnvironmentConfig) Load(baseDir string) error {\n\tconfigPath := filepath.Join(baseDir, configDir)\n\n\tdata, err := os.ReadFile(filepath.Join(configPath, environmentFile))\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tif err == nil {\n\t\tif err := json.Unmarshal(data, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"], ["/container-use/cmd/container-use/completion_override.go", "package main\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar commandName string\n\nfunc init() {\n\t// Override cobra's default completion command\n\tcompletionCmd := &cobra.Command{\n\t\tUse: \"completion [bash|zsh|fish|powershell]\",\n\t\tShort: \"Generate the autocompletion script for the specified shell\",\n\t\tLong: `Generate the autocompletion script for container-use for the specified shell.\nSee each sub-command's help for details on how to use the generated script.\n\nUse --command-name to generate completions for a different command name (e.g., 'cu').`,\n\t\tDisableFlagsInUseLine: true,\n\t\tValidArgs: []string{\"bash\", \"zsh\", \"fish\", \"powershell\"},\n\t\tArgs: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn generateCompletionForBinary(args[0])\n\t\t},\n\t}\n\n\tcompletionCmd.PersistentFlags().StringVar(&commandName, \"command-name\", \"container-use\", \"Command name to use in completions\")\n\n\t// Add help subcommands that show usage instructions\n\tfor _, shell := range []string{\"bash\", \"zsh\", \"fish\", \"powershell\"} {\n\t\tshell := shell // capture loop variable\n\t\thelpCmd := &cobra.Command{\n\t\t\tUse: shell,\n\t\t\tShort: \"Generate the autocompletion script for \" + shell,\n\t\t\tLong: generateHelpText(shell),\n\t\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t\treturn generateCompletionForBinary(shell)\n\t\t\t},\n\t\t}\n\t\tcompletionCmd.AddCommand(helpCmd)\n\t}\n\n\trootCmd.AddCommand(completionCmd)\n}\n\nfunc generateCompletionForBinary(shell string) error {\n\ttempRootCmd := &cobra.Command{\n\t\tUse: commandName,\n\t\tShort: rootCmd.Short,\n\t\tLong: rootCmd.Long,\n\t}\n\n\tfor _, subCmd := range rootCmd.Commands() {\n\t\tif subCmd.Name() != \"completion\" {\n\t\t\ttempRootCmd.AddCommand(subCmd)\n\t\t}\n\t}\n\n\tswitch shell {\n\tcase \"bash\":\n\t\treturn tempRootCmd.GenBashCompletion(os.Stdout)\n\tcase \"zsh\":\n\t\treturn tempRootCmd.GenZshCompletion(os.Stdout)\n\tcase \"fish\":\n\t\treturn tempRootCmd.GenFishCompletion(os.Stdout, true)\n\tcase \"powershell\":\n\t\treturn tempRootCmd.GenPowerShellCompletion(os.Stdout)\n\t}\n\treturn nil\n}\n\nfunc generateHelpText(shell string) string {\n\t// Generate help text dynamically based on the shell\n\t// This reduces duplication of the static help text\n\ttemplates := map[string]string{\n\t\t\"bash\": `Generate the autocompletion script for the bash shell.\n\nThis script depends on the 'bash-completion' package.\nIf it is not installed already, you can install it via your OS's package manager.\n\nTo load completions in your current shell session:\n\tsource <({{.command}} completion bash)\n\nTo load completions for every new session, save the output to your bash completion directory.\nCommon locations include:\n - Linux: /usr/local/etc/bash_completion.d/{{.command}}\n - macOS: $(brew --prefix)/etc/bash_completion.d/{{.command}}\n - Windows (Git Bash): /usr/share/bash-completion/completions/{{.command}}\n\nExample:\n\t{{.command}} completion bash > /path/to/bash_completion.d/{{.command}}`,\n\n\t\t\"zsh\": `Generate the autocompletion script for the zsh shell.\n\nIf shell completion is not already enabled in your environment,\nyou will need to enable it. You can execute the following once:\n\techo \"autoload -U compinit; compinit\" >> ~/.zshrc\n\nTo load completions in your current shell session:\n\tsource <({{.command}} completion zsh)\n\nTo load completions for every new session, save the output to your zsh completion directory.\nCommon locations include:\n - Linux: /usr/local/share/zsh/site-functions/_{{.command}}\n - macOS: $(brew --prefix)/share/zsh/site-functions/_{{.command}}\n - Custom: Any directory in your $fpath\n\nExample:\n\t{{.command}} completion zsh > /path/to/zsh/site-functions/_{{.command}}`,\n\n\t\t\"fish\": `Generate the autocompletion script for the fish shell.\n\nTo load completions in your current shell session:\n\t{{.command}} completion fish | source\n\nTo load completions for every new session, save the output to your fish completion directory.\nCommon locations include:\n - Linux/macOS: ~/.config/fish/completions/{{.command}}.fish\n - Windows: %APPDATA%\\fish\\completions\\{{.command}}.fish\n\nExample:\n\t{{.command}} completion fish > ~/.config/fish/completions/{{.command}}.fish`,\n\n\t\t\"powershell\": `Generate the autocompletion script for PowerShell.\n\nTo load completions in your current shell session:\n\t{{.command}} completion powershell | Out-String | Invoke-Expression\n\nTo load completions for every new session, add the output to your PowerShell profile.\nCommon profile locations include:\n - Windows: $PROFILE (usually %USERPROFILE%\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1)\n - Linux/macOS: ~/.config/powershell/Microsoft.PowerShell_profile.ps1\n\nExample:\n\t{{.command}} completion powershell >> $PROFILE\n\nNote: You may need to create the profile file if it doesn't exist.`,\n\t}\n\n\ttemplate := templates[shell]\n\treturn strings.ReplaceAll(template, \"{{.command}}\", commandName)\n}\n"], ["/container-use/cmd/container-use/env_selection.go", "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/huh\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n)\n\n// resolveEnvironmentID resolves the environment ID for commands that take env_id as the only positional argument.\n// If no args are provided, it filters environments to those where the local repo head is a parent of the environment's head,\n// then either auto-selects if there's only one match or prompts the user to select from multiple options.\nfunc resolveEnvironmentID(ctx context.Context, repo *repository.Repository, args []string) (string, error) {\n\tif len(args) == 1 {\n\t\treturn args[0], nil\n\t}\n\tif len(args) > 1 {\n\t\treturn \"\", errors.New(\"too many arguments\")\n\t}\n\n\t// Get current user repo head - this could easily go inside ListDescendantEnvironments, but keeping it outside simplifies testing\n\tcurrentHead, err := repository.RunGitCommand(ctx, repo.SourcePath(), \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get current HEAD: %w\", err)\n\t}\n\tcurrentHead = strings.TrimSpace(currentHead)\n\n\t// Get environments that are descendants of current HEAD\n\tfilteredEnvs, err := repo.ListDescendantEnvironments(ctx, currentHead)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to list descendant environments: %w\", err)\n\t}\n\n\tif len(filteredEnvs) == 0 {\n\t\treturn \"\", errors.New(\"no environments found that are descendants of the current HEAD\")\n\t}\n\n\t// If only one environment matches, use it\n\tif len(filteredEnvs) == 1 {\n\t\treturn filteredEnvs[0].ID, nil\n\t}\n\n\t// Multiple environments - prompt user to select\n\treturn promptForEnvironmentSelection(filteredEnvs)\n}\n\n// promptForEnvironmentSelection prompts the user to select from multiple environments\nfunc promptForEnvironmentSelection(envs []*environment.EnvironmentInfo) (string, error) {\n\tvar options []huh.Option[string]\n\n\tfor _, env := range envs {\n\t\ttitle := env.State.Title\n\t\tif title == \"\" {\n\t\t\ttitle = \"No description\"\n\t\t}\n\n\t\tlabel := fmt.Sprintf(\"%s - %s\", env.ID, title)\n\t\toptions = append(options, huh.NewOption(label, env.ID))\n\t}\n\n\tvar selectedID string\n\tprompt := huh.NewSelect[string]().\n\t\tTitle(\"Select an environment:\").\n\t\tOptions(options...).\n\t\tValue(&selectedID)\n\n\tif err := prompt.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn selectedID, nil\n}\n"], ["/container-use/environment/service.go", "package environment\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"dagger.io/dagger\"\n)\n\nvar (\n\tserviceStartTimeout = 30 * time.Second\n)\n\ntype Service struct {\n\tConfig *ServiceConfig `json:\"config\"`\n\tEndpoints EndpointMappings `json:\"endpoints\"`\n\n\tsvc *dagger.Service\n}\n\ntype EndpointMapping struct {\n\tEnvironmentInternal string `json:\"environment_internal\"`\n\tHostExternal string `json:\"host_external\"`\n}\n\ntype EndpointMappings map[int]*EndpointMapping\n\nfunc (env *Environment) startServices(ctx context.Context) ([]*Service, error) {\n\tservices := []*Service{}\n\tfor _, cfg := range env.State.Config.Services {\n\t\tservice, err := env.startService(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservices = append(services, service)\n\t}\n\treturn services, nil\n}\n\nfunc (env *Environment) startService(ctx context.Context, cfg *ServiceConfig) (*Service, error) {\n\tcontainer := env.dag.Container().From(cfg.Image)\n\tcontainer, err := containerWithEnvAndSecrets(env.dag, container, cfg.Env, env.State.Config.Secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.Command != \"\" {\n\t\tcontainer = container.WithExec([]string{\"sh\", \"-c\", cfg.Command})\n\t}\n\n\targs := []string{}\n\tif cfg.Command != \"\" {\n\t\targs = []string{\"sh\", \"-c\", cfg.Command}\n\t}\n\n\t// Expose ports\n\tfor _, port := range cfg.ExposedPorts {\n\t\tcontainer = container.WithExposedPort(port, dagger.ContainerWithExposedPortOpts{\n\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\tDescription: fmt.Sprintf(\"Port %d\", port),\n\t\t})\n\t}\n\n\t// Start the service\n\tstartCtx, cancel := context.WithTimeout(ctx, serviceStartTimeout)\n\tdefer cancel()\n\tsvc, err := container.AsService(dagger.ContainerAsServiceOpts{\n\t\tArgs: args,\n\t\tUseEntrypoint: true,\n\t}).Start(startCtx)\n\tif err != nil {\n\t\tvar exitErr *dagger.ExecError\n\t\tif errors.As(err, &exitErr) {\n\t\t\treturn nil, fmt.Errorf(\"command failed with exit code %d.\\nstdout: %s\\nstderr: %s\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t}\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\treturn nil, fmt.Errorf(\"service failed to start within %s timeout\", serviceStartTimeout)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tendpoints := EndpointMappings{}\n\tfor _, port := range cfg.ExposedPorts {\n\t\tendpoint := &EndpointMapping{\n\t\t\tEnvironmentInternal: fmt.Sprintf(\"tcp://%s:%d\", cfg.Name, port),\n\t\t}\n\t\tendpoints[port] = endpoint\n\n\t\t// Expose ports on the host\n\t\ttunnel, err := env.dag.Host().Tunnel(svc, dagger.HostTunnelOpts{\n\t\t\tPorts: []dagger.PortForward{\n\t\t\t\t{\n\t\t\t\t\tBackend: port,\n\t\t\t\t\tFrontend: 0,\n\t\t\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\t\t},\n\t\t\t},\n\t\t}).Start(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texternalEndpoint, err := tunnel.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get endpoint for service %s: %w\", cfg.Name, err)\n\t\t}\n\t\tendpoint.HostExternal = externalEndpoint\n\t}\n\n\treturn &Service{\n\t\tConfig: cfg,\n\t\tEndpoints: endpoints,\n\t\tsvc: svc,\n\t}, nil\n}\n\nfunc (env *Environment) AddService(ctx context.Context, explanation string, cfg *ServiceConfig) (*Service, error) {\n\tif env.State.Config.Services.Get(cfg.Name) != nil {\n\t\treturn nil, fmt.Errorf(\"service %s already exists\", cfg.Name)\n\t}\n\tsvc, err := env.startService(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv.State.Config.Services = append(env.State.Config.Services, cfg)\n\tenv.Services = append(env.Services, svc)\n\n\tstate := env.container().WithServiceBinding(cfg.Name, svc.svc)\n\tif err := env.apply(ctx, state); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv.Notes.Add(\"Add service %s\\n%s\\n\\n\", cfg.Name, explanation)\n\n\treturn svc, nil\n}\n"], ["/container-use/cmd/container-use/stdio.go", "package main\n\nimport (\n\t\"log/slog\"\n\t\"os\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/mcpserver\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar stdioCmd = &cobra.Command{\n\tUse: \"stdio\",\n\tShort: \"Start MCP server for agent integration\",\n\tLong: `Start the Model Context Protocol server that enables AI agents to create and manage containerized environments. This is typically used by agents like Claude Code, Cursor, or VSCode.`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\tslog.Info(\"connecting to dagger\")\n\n\t\tdag, err := dagger.Connect(ctx, dagger.WithLogOutput(logWriter))\n\t\tif err != nil {\n\t\t\tslog.Error(\"Error starting dagger\", \"error\", err)\n\n\t\t\tif isDockerDaemonError(err) {\n\t\t\t\thandleDockerDaemonError()\n\t\t\t}\n\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer dag.Close()\n\n\t\treturn mcpserver.RunStdioServer(ctx, dag)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(stdioCmd)\n}\n"], ["/container-use/cmd/container-use/logger.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nvar (\n\tlogWriter = io.Discard\n)\n\nfunc parseLogLevel(levelStr string) slog.Level {\n\tswitch levelStr {\n\tcase \"debug\", \"DEBUG\":\n\t\treturn slog.LevelDebug\n\tcase \"info\", \"INFO\":\n\t\treturn slog.LevelInfo\n\tcase \"warn\", \"WARN\", \"warning\", \"WARNING\":\n\t\treturn slog.LevelWarn\n\tcase \"error\", \"ERROR\":\n\t\treturn slog.LevelError\n\tdefault:\n\t\treturn slog.LevelInfo\n\t}\n}\n\nfunc setupLogger() error {\n\tvar writers []io.Writer\n\n\tlogFile := filepath.Join(os.TempDir(), \"container-use.debug.stderr.log\")\n\tif v, ok := os.LookupEnv(\"CONTAINER_USE_STDERR_FILE\"); ok {\n\t\tlogFile = v\n\t}\n\n\tfile, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open log file %s: %w\", logFile, err)\n\t}\n\twriters = append(writers, file)\n\n\tif len(writers) == 0 {\n\t\tfmt.Fprintf(os.Stderr, \"%s Logging disabled. Set CONTAINER_USE_STDERR_FILE and CONTAINER_USE_LOG_LEVEL environment variables\\n\", time.Now().Format(time.DateTime))\n\t}\n\n\tlogLevel := parseLogLevel(os.Getenv(\"CONTAINER_USE_LOG_LEVEL\"))\n\tlogWriter = io.MultiWriter(writers...)\n\thandler := slog.NewTextHandler(logWriter, &slog.HandlerOptions{\n\t\tLevel: logLevel,\n\t})\n\tslog.SetDefault(slog.New(handler))\n\n\treturn nil\n}\n"], ["/container-use/cmd/container-use/diff.go", "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar diffCmd = &cobra.Command{\n\tUse: \"diff []\",\n\tShort: \"Show what files an agent changed\",\n\tLong: `Display the code changes made by an agent in an environment.\nShows a git diff between the environment's state and your current branch.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# See what changes the agent made\ncontainer-use diff fancy-mallard\n\n# Quick assessment before merging\ncontainer-use diff backend-api\n\n# Auto-select environment\ncontainer-use diff`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn repo.Diff(ctx, envID, os.Stdout)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(diffCmd)\n}\n"], ["/container-use/cmd/container-use/agent/configure_codex.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mitchellh/go-homedir\"\n\t\"github.com/pelletier/go-toml/v2\"\n)\n\ntype ConfigureCodex struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureCodex() *ConfigureCodex {\n\treturn &ConfigureCodex{\n\t\tName: \"OpenAI Codex\",\n\t\tDescription: \"OpenAI's lightweight coding agent that runs in your terminal\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureCodex) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureCodex) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureCodex) editMcpConfig() error {\n\tconfigPath, err := homedir.Expand(filepath.Join(\"~\", \".codex\", \"config.toml\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config map[string]any\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := toml.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t} else {\n\t\tconfig = make(map[string]any)\n\t}\n\n\tdata, err := a.updateCodexConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureCodex) updateCodexConfig(config map[string]any) ([]byte, error) {\n\t// Get mcp_servers map\n\tvar mcpServers map[string]any\n\tif servers, ok := config[\"mcp_servers\"]; ok {\n\t\tmcpServers = servers.(map[string]any)\n\t} else {\n\t\tmcpServers = make(map[string]any)\n\t\tconfig[\"mcp_servers\"] = mcpServers\n\t}\n\n\t// Add container-use server\n\tmcpServers[\"container-use\"] = map[string]any{\n\t\t\"command\": ContainerUseBinary,\n\t\t\"args\": []any{\"stdio\"},\n\t\t\"auto_approve\": tools(\"\"),\n\t}\n\n\t// Write config back\n\tdata, err := toml.Marshal(&config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureCodex) editRules() error {\n\tagentsFile := \"AGENTS.md\"\n\treturn saveRulesFile(agentsFile, rules.AgentRules)\n}\n\nfunc (a *ConfigureCodex) isInstalled() bool {\n\t_, err := exec.LookPath(\"codex\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/agent/configure_claude.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureClaude struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureClaude() *ConfigureClaude {\n\treturn &ConfigureClaude{\n\t\tName: \"Claude Code\",\n\t\tDescription: \"Anthropic's Claude Code\",\n\t}\n}\n\ntype ClaudeSettingsLocal struct {\n\tPermissions *ClaudePermissions `json:\"permissions,omitempty\"`\n\tEnv map[string]string `json:\"env,omitempty\"`\n}\n\ntype ClaudePermissions struct {\n\tAllow []string `json:\"allow,omitempty\"`\n\tDeny []string `json:\"deny,omitempty\"`\n}\n\nfunc (c *ConfigureClaude) name() string {\n\treturn c.Name\n}\n\nfunc (c *ConfigureClaude) description() string {\n\treturn c.Description\n}\n\nfunc (c *ConfigureClaude) editMcpConfig() error {\n\t// Add MCP server\n\tcmd := exec.Command(\"claude\", \"mcp\", \"add\", \"container-use\", \"--\", ContainerUseBinary, \"stdio\")\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not automatically add MCP server: %w\", err)\n\t}\n\n\t// Configure auto approve settings\n\tconfigPath := filepath.Join(\".claude\", \"settings.local.json\")\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\tvar config ClaudeSettingsLocal\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := c.updateSettingsLocal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (c *ConfigureClaude) updateSettingsLocal(config ClaudeSettingsLocal) ([]byte, error) {\n\t// Initialize permissions map if nil\n\tif config.Permissions == nil {\n\t\tconfig.Permissions = &ClaudePermissions{Allow: []string{}}\n\t}\n\n\t// remove save non-container-use items from allow\n\tallows := []string{}\n\tfor _, tool := range config.Permissions.Allow {\n\t\tif !strings.HasPrefix(tool, \"mcp__container-use\") {\n\t\t\tallows = append(allows, tool)\n\t\t}\n\t}\n\n\t// Add container-use tools to allow\n\ttools := tools(\"mcp__container-use__\")\n\tallows = append(allows, tools...)\n\tconfig.Permissions.Allow = allows\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\nfunc (c *ConfigureClaude) editRules() error {\n\treturn saveRulesFile(\"CLAUDE.md\", rules.AgentRules)\n}\n\nfunc (c *ConfigureClaude) isInstalled() bool {\n\t_, err := exec.LookPath(\"claude\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/agent/configure_goose.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mitchellh/go-homedir\"\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype ConfigureGoose struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureGoose() *ConfigureGoose {\n\treturn &ConfigureGoose{\n\t\tName: \"Goose\",\n\t\tDescription: \"an open source, extensible AI agent that goes beyond code suggestions\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureGoose) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureGoose) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureGoose) editMcpConfig() error {\n\tvar configPath string\n\tvar err error\n\n\tif runtime.GOOS == \"windows\" {\n\t\t// Windows: %APPDATA%\\Block\\goose\\config\\config.yaml\n\t\t// Reference: https://block.github.io/goose/docs/guides/config-file\n\t\tappData := os.Getenv(\"APPDATA\")\n\t\tif appData == \"\" {\n\t\t\treturn fmt.Errorf(\"APPDATA environment variable not set\")\n\t\t}\n\t\tconfigPath = filepath.Join(appData, \"Block\", \"goose\", \"config\", \"config.yaml\")\n\t} else {\n\t\t// macOS/Linux: ~/.config/goose/config.yaml\n\t\tconfigPath, err = homedir.Expand(filepath.Join(\"~\", \".config\", \"goose\", \"config.yaml\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config map[string]any\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := yaml.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t} else {\n\t\tconfig = make(map[string]any)\n\t}\n\n\tdata, err := a.updateGooseConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.WriteFile(configPath, data, 0644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureGoose) updateGooseConfig(config map[string]any) ([]byte, error) {\n\t// Get extensions map\n\tvar extensions map[string]any\n\tif ext, ok := config[\"extensions\"]; ok {\n\t\textensions = ext.(map[string]any)\n\t} else {\n\t\textensions = make(map[string]any)\n\t\tconfig[\"extensions\"] = extensions\n\t}\n\n\t// Add container-use extension\n\textensions[\"container-use\"] = map[string]any{\n\t\t\"name\": \"container-use\",\n\t\t\"type\": \"stdio\",\n\t\t\"enabled\": true,\n\t\t\"cmd\": ContainerUseBinary,\n\t\t\"args\": []any{\"stdio\"},\n\t\t\"envs\": map[string]any{},\n\t}\n\n\t// Write config back\n\tdata, err := yaml.Marshal(&config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureGoose) editRules() error {\n\treturn saveRulesFile(\".goosehints\", rules.AgentRules)\n}\n\nfunc (a *ConfigureGoose) isInstalled() bool {\n\t_, err := exec.LookPath(\"goose\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/agent/configure_q.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureQ struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureQ() *ConfigureQ {\n\treturn &ConfigureQ{\n\t\tName: \"Amazon Q Developer\",\n\t\tDescription: \"Amazon's agentic chat experience in your terminal\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureQ) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureQ) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureQ) editMcpConfig() error {\n\tconfigPath := filepath.Join(\".amazonq\", \"mcp.json\")\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config MCPServersConfig\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := a.updateMcpConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureQ) updateMcpConfig(config MCPServersConfig) ([]byte, error) {\n\t// Initialize mcpServers map if nil\n\tif config.MCPServers == nil {\n\t\tconfig.MCPServers = make(map[string]MCPServer)\n\t}\n\n\t// Add container-use server\n\tconfig.MCPServers[\"container-use\"] = MCPServer{\n\t\tCommand: ContainerUseBinary,\n\t\tArgs: []string{\"stdio\"},\n\t\tEnv: map[string]string{},\n\t\tTimeout: &[]int{60000}[0],\n\t}\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureQ) editRules() error {\n\treturn saveRulesFile(\".amazonq/rules/container-use.md\", rules.AgentRules)\n}\n\nfunc (a *ConfigureQ) isInstalled() bool {\n\t_, err := exec.LookPath(\"q\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/docker_errors.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n// isDockerDaemonError checks if the error is related to Docker daemon connectivity\nfunc isDockerDaemonError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\terrStr := strings.ToLower(err.Error())\n\n\t// Linux: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\n\tif strings.Contains(errStr, \"cannot connect to the docker daemon\") {\n\t\treturn true\n\t}\n\n\t// Windows: error during connect: Get \"http://%2F%2F.%2Fpipe%2FdockerDesktopLinuxEngine/v1.51/containers/json\": open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified.\n\tif strings.Contains(errStr, \"error during connect\") && strings.Contains(errStr, \"pipe/dockerdesktoplinuxengine\") && strings.Contains(errStr, \"the system cannot find the file specified\") {\n\t\treturn true\n\t}\n\n\t// macOS: request returned 500 Internal Server Error for API route and version http://%2FUsers%2Fb1tank%2F.docker%2Frun%2Fdocker.sock/v1.50/containers/json, check if the server supports the requested API version\n\tif strings.Contains(errStr, \"request returned 500 internal server error\") && strings.Contains(errStr, \"docker.sock\") && strings.Contains(errStr, \"check if the server supports the requested api version\") {\n\t\treturn true\n\t}\n\n\t// Generic fallbacks\n\treturn strings.Contains(errStr, \"docker daemon\") ||\n\t\tstrings.Contains(errStr, \"docker.sock\")\n}\n\n// handleDockerDaemonError prints a helpful error message for Docker daemon issues\nfunc handleDockerDaemonError() {\n\tfmt.Fprintf(os.Stderr, \"\\nError: Docker daemon is not running.\\n\")\n\tfmt.Fprintf(os.Stderr, \"Please start Docker and try again.\\n\\n\")\n}\n"], ["/container-use/cmd/container-use/version.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime/debug\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tversion = \"dev\"\n\tcommit = \"unknown\"\n\tdate = \"unknown\"\n)\n\nfunc init() {\n\tif version == \"dev\" {\n\t\tif buildCommit, buildTime := getBuildInfoFromBinary(); buildCommit != \"unknown\" {\n\t\t\tcommit = buildCommit\n\t\t\tdate = buildTime\n\t\t}\n\t}\n}\n\nvar versionCmd = &cobra.Command{\n\tUse: \"version\",\n\tShort: \"Print version information\",\n\tLong: `Print the version, commit hash, and build date of the container-use binary.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfmt.Printf(\"container-use version %s\\n\", version)\n\t\tif commit != \"unknown\" {\n\t\t\tfmt.Printf(\"commit: %s\\n\", commit)\n\t\t}\n\t\tif date != \"unknown\" {\n\t\t\tfmt.Printf(\"built: %s\\n\", date)\n\t\t}\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(versionCmd)\n}\n\nfunc getBuildInfoFromBinary() (string, string) {\n\tbuildInfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn \"unknown\", \"unknown\"\n\t}\n\n\tvar revision, buildTime, modified string\n\n\tfor _, setting := range buildInfo.Settings {\n\t\tswitch setting.Key {\n\t\tcase \"vcs.revision\":\n\t\t\trevision = setting.Value\n\t\tcase \"vcs.time\":\n\t\t\tbuildTime = setting.Value\n\t\tcase \"vcs.modified\":\n\t\t\tmodified = setting.Value\n\t\t}\n\t}\n\n\t// Format commit hash (use short version)\n\tif len(revision) > 7 {\n\t\trevision = revision[:7]\n\t}\n\tif modified == \"true\" {\n\t\trevision += \"-dirty\"\n\t}\n\n\tif revision == \"\" {\n\t\trevision = \"unknown\"\n\t}\n\tif buildTime == \"\" {\n\t\tbuildTime = \"unknown\"\n\t}\n\n\treturn revision, buildTime\n}\n"], ["/container-use/cmd/container-use/inspect.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar inspectCmd = &cobra.Command{\n\tUse: \"inspect []\",\n\tShort: \"Inspect an environment\",\n\tLong: \"This is an internal command used by the CLI to inspect an environment. It is not meant to be used by users.\",\n\tArgs: cobra.MaximumNArgs(1),\n\tHidden: true,\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvInfo, err := repo.Info(ctx, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvInfo.State.Container = \"\"\n\t\tout, err := json.MarshalIndent(envInfo, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(string(out))\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(inspectCmd)\n}\n"], ["/container-use/cmd/container-use/agent/configure_cursor.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureCursor struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureCursor() *ConfigureCursor {\n\treturn &ConfigureCursor{\n\t\tName: \"Cursor\",\n\t\tDescription: \"AI-powered code editor\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureCursor) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureCursor) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureCursor) editMcpConfig() error {\n\tconfigPath := filepath.Join(\".cursor\", \"mcp.json\")\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config MCPServersConfig\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := a.updateMcpConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureCursor) updateMcpConfig(config MCPServersConfig) ([]byte, error) {\n\t// Initialize mcpServers map if nil\n\tif config.MCPServers == nil {\n\t\tconfig.MCPServers = make(map[string]MCPServer)\n\t}\n\n\t// Add container-use server\n\tconfig.MCPServers[\"container-use\"] = MCPServer{\n\t\tCommand: ContainerUseBinary,\n\t\tArgs: []string{\"stdio\"},\n\t}\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureCursor) editRules() error {\n\trulesFile := filepath.Join(\".cursor\", \"rules\", \"container-use.mdc\")\n\treturn saveRulesFile(rulesFile, rules.CursorRules)\n}\n\nfunc (a *ConfigureCursor) isInstalled() bool {\n\treturn true\n}\n"], ["/container-use/cmd/container-use/terminal_windows.go", "//go:build windows\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc execDaggerRun(daggerBin string, args []string, env []string) error {\n\tcmd := exec.Command(daggerBin, args...)\n\tcmd.Args = append([]string{\"dagger\", \"run\"}, os.Args...)\n\tcmd.Env = env\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"failed to execute dagger run: %w\", err)\n\t}\n\n\t// On Windows, we can't replace the current process, so we exit\n\tos.Exit(0)\n\treturn nil\n}\n"], ["/container-use/environment/state.go", "package environment\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype State struct {\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tUpdatedAt time.Time `json:\"updated_at,omitempty\"`\n\n\tConfig *EnvironmentConfig `json:\"config,omitempty\"`\n\tContainer string `json:\"container,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n}\n\nfunc (s *State) Marshal() ([]byte, error) {\n\treturn json.MarshalIndent(s, \"\", \" \")\n}\n\nfunc (s *State) Unmarshal(data []byte) error {\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\t// Try to migrate the legacy state\n\t\tlegacySt, err := migrateLegacyState(data)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load state: %w\", err)\n\t\t}\n\t\t*s = *legacySt\n\t}\n\treturn nil\n}\n\nfunc migrateLegacyState(state []byte) (*State, error) {\n\tvar history legacyState\n\tif err := json.Unmarshal(state, &history); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load state: %w\", err)\n\t}\n\tlatest := history.Latest()\n\tif latest == nil {\n\t\treturn nil, fmt.Errorf(\"no latest revision found\")\n\t}\n\n\treturn &State{\n\t\tContainer: latest.State,\n\t\tCreatedAt: latest.CreatedAt,\n\t\tUpdatedAt: latest.CreatedAt,\n\t}, nil\n}\n\ntype legacyState []*legacyRevision\n\nfunc (h legacyState) Latest() *legacyRevision {\n\tif len(h) == 0 {\n\t\treturn nil\n\t}\n\treturn h[len(h)-1]\n}\n\nfunc (h legacyState) LatestVersion() int {\n\tlatest := h.Latest()\n\tif latest == nil {\n\t\treturn 0\n\t}\n\treturn latest.Version\n}\n\nfunc (h legacyState) Get(version int) *legacyRevision {\n\tfor _, revision := range h {\n\t\tif revision.Version == version {\n\t\t\treturn revision\n\t\t}\n\t}\n\treturn nil\n}\n\ntype legacyRevision struct {\n\tVersion int `json:\"version\"`\n\tName string `json:\"name\"`\n\tExplanation string `json:\"explanation\"`\n\tOutput string `json:\"output,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n\tState string `json:\"state\"`\n}\n"], ["/container-use/environment/note.go", "package environment\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype Notes struct {\n\titems []string\n\tmu sync.Mutex\n}\n\nfunc (n *Notes) Add(format string, a ...any) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tn.items = append(n.items, fmt.Sprintf(format, a...))\n}\n\nfunc (n *Notes) AddCommand(command string, exitCode int, stdout, stderr string) {\n\tmsg := fmt.Sprintf(\"$ %s\", strings.TrimSpace(command))\n\tif exitCode != 0 {\n\t\tmsg += fmt.Sprintf(\"\\nexit %d\", exitCode)\n\t}\n\tif strings.TrimSpace(stdout) != \"\" {\n\t\tmsg += fmt.Sprintf(\"\\n%s\", stdout)\n\t}\n\tif strings.TrimSpace(stderr) != \"\" {\n\t\tmsg += fmt.Sprintf(\"\\nstderr: %s\", stderr)\n\t}\n\n\tn.Add(\"%s\", msg)\n}\n\nfunc (n *Notes) Clear() {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tn.items = []string{}\n}\n\nfunc (n *Notes) String() string {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\treturn strings.TrimSpace(strings.Join(n.items, \"\\n\"))\n}\n\nfunc (n *Notes) Pop() string {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tout := strings.TrimSpace(strings.Join(n.items, \"\\n\"))\n\tn.items = []string{}\n\n\treturn out\n}\n"], ["/container-use/cmd/container-use/signal_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nfunc setupSignalHandling() {\n\tsigusrCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigusrCh, syscall.SIGUSR1)\n\tgo handleSIGUSR(sigusrCh)\n}\n\nfunc handleSIGUSR(sigusrCh <-chan os.Signal) {\n\tfor sig := range sigusrCh {\n\t\tif sig == syscall.SIGUSR1 {\n\t\t\tdumpStacks()\n\t\t}\n\t}\n}\n\nfunc dumpStacks() {\n\tbuf := make([]byte, 1<<20) // 1MB buffer\n\tn := runtime.Stack(buf, true)\n\tio.MultiWriter(logWriter, os.Stderr).Write(buf[:n])\n}\n"], ["/container-use/mcpserver/args.go", "package mcpserver\n\nimport \"github.com/mark3labs/mcp-go/mcp\"\n\nvar (\n\texplainationArgument = mcp.WithString(\"explanation\",\n\t\tmcp.Description(\"One sentence explanation for why this directory is being listed.\"),\n\t)\n\tenvironmentSourceArgument = mcp.WithString(\"environment_source\",\n\t\tmcp.Description(\"Absolute path to the source git repository for the environment.\"),\n\t\tmcp.Required(),\n\t)\n\tenvironmentIDArgument = mcp.WithString(\"environment_id\",\n\t\tmcp.Description(\"The ID of the environment for this command. Must call `environment_create` first.\"),\n\t\tmcp.Required(),\n\t)\n)\n\nfunc newRepositoryTool(name string, description string, args ...mcp.ToolOption) mcp.Tool {\n\topts := []mcp.ToolOption{\n\t\tmcp.WithDescription(description),\n\t\texplainationArgument,\n\t\tenvironmentSourceArgument,\n\t}\n\topts = append(opts, args...)\n\n\treturn mcp.NewTool(name, opts...)\n}\n\nfunc newEnvironmentTool(name string, description string, args ...mcp.ToolOption) mcp.Tool {\n\topts := []mcp.ToolOption{\n\t\tmcp.WithDescription(description),\n\t\texplainationArgument,\n\t\tenvironmentSourceArgument,\n\t\tenvironmentIDArgument,\n\t}\n\topts = append(opts, args...)\n\n\treturn mcp.NewTool(name, opts...)\n}\n"], ["/container-use/mcpserver/signals_windows.go", "//go:build windows\n\npackage mcpserver\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Windows-compatible signals for MCP server\nfunc getNotifySignals() []os.Signal {\n\t// On Windows:\n\t// - os.Interrupt: Ctrl+C signal (can receive, cannot send to other processes)\n\t// - syscall.SIGTERM: Termination signal (can receive)\n\t// - os.Kill: Not a receivable signal, used only for Process.Kill()\n\treturn []os.Signal{os.Interrupt, syscall.SIGTERM}\n}\n"], ["/container-use/cmd/container-use/signals_windows.go", "//go:build windows\n\npackage main\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Windows-compatible signals for receiving\nfunc getNotifySignals() []os.Signal {\n\t// On Windows:\n\t// - os.Interrupt: Ctrl+C signal (can receive, cannot send to other processes)\n\t// - syscall.SIGTERM: Termination signal (can receive) (https://pkg.go.dev/os/signal#hdr-Windows)\n\t// - os.Kill: Not a receivable signal\n\treturn []os.Signal{os.Interrupt, syscall.SIGTERM}\n}\n"], ["/container-use/cmd/container-use/signal_windows.go", "//go:build windows\n\npackage main\n\n// On Windows, SIGUSR1 is not available, so we provide a no-op implementation\nfunc setupSignalHandling() {\n\t// No special signal handling on Windows\n}\n"], ["/container-use/cmd/container-use/signals_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Unix-compatible signals\nfunc getNotifySignals() []os.Signal {\n\treturn []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}\n}\n"], ["/container-use/mcpserver/signals_unix.go", "//go:build !windows\n\npackage mcpserver\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Unix-compatible signals for MCP server\nfunc getNotifySignals() []os.Signal {\n\treturn []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}\n}\n"], ["/container-use/cmd/container-use/terminal_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"syscall\"\n)\n\nfunc execDaggerRun(daggerBin string, args []string, env []string) error {\n\treturn syscall.Exec(daggerBin, args, env)\n}\n"], ["/container-use/rules/rules.go", "package rules\n\nimport _ \"embed\"\n\n//go:embed agent.md\nvar AgentRules string\n\n//go:embed cursor.mdc\nvar CursorRules string\n"]], "task_instance_info": {"created_time": "2025-08-20 20:54:16", "created_task_model": "DeepSeek-R1", "function_skeleton": "func runGitLogWindows (ctx context.Context) error {}", "code_description": "This code segment functions to: Generate formatted terminal output displaying version control history and system metadata while dynamically adapting to terminal dimensions and handling command execution pipelines."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc runGitLogWindows(ctx context.Context) error {\n\t// Use context with timeout to prevent hanging\n\tctx, cancel := context.WithTimeout(ctx, 5*time.Second)\n\tdefer cancel()\n\n\t// Build the git command with PowerShell for better ANSI support\n\tcmd := exec.CommandContext(ctx, \"powershell.exe\", \"-Command\", \n\t\t\"git log --color=always --oneline --decorate --graph --all -n 20\")\n\n\t// Capture command output\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"git log failed: %w\\n%s\", err, output)\n\t}\n\n\t// Clear screen and print formatted output\n\tfmt.Print(\"\\x1b[2J\\x1b[H\") // ANSI escape codes for clear screen and home position\n\tfmt.Println(strings.TrimSpace(string(output)))\n\t\n\treturn nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-54-32"}, "editdistance_info": {"edit_distance": 12.1281, "calculate_time": "2025-08-20 20:54:32", "true_code_clean": "func runGitLogWindows(ctx context.Context) error {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"\\x1b[H\\x1b[J\")\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"unknown\"\n\t}\n\ttimestamp := time.Now().Format(\"Mon Jan 2 15:04:05 2006\")\n\tgitCommand := \"git log --color=always --remotes=container-use --oneline --graph --decorate\"\n\theaderLine := fmt.Sprintf(\"Every 1.0s: %s\", gitCommand)\n\tterminalWidth := 80\n\tif width, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && width > 0 {\n\t\tterminalWidth = width\n\t}\n\trightPart := fmt.Sprintf(\"%s: %s\", hostname, timestamp)\n\tspacesNeeded := terminalWidth - len(headerLine) - len(rightPart)\n\tif spacesNeeded >= 1 {\n\t\tbuf.WriteString(headerLine + strings.Repeat(\" \", spacesNeeded) + rightPart + \"\\n\")\n\t} else {\n\t\tbuf.WriteString(headerLine + \" \" + rightPart + \"\\n\")\n\t}\n\tbuf.WriteString(\"\\n\") \n\tcmd := exec.CommandContext(ctx, \"git\", \"log\",\n\t\t\"--color=always\",\n\t\t\"--remotes=container-use\",\n\t\t\"--oneline\",\n\t\t\"--graph\",\n\t\t\"--decorate\")\n\tpr, pw, err := os.Pipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create pipe: %w\", err)\n\t}\n\tcmd.Stdout = pw\n\tcmd.Stderr = pw\n\tif err := cmd.Start(); err != nil {\n\t\tpw.Close()\n\t\tpr.Close()\n\t\treturn fmt.Errorf(\"failed to start git log: %w\", err)\n\t}\n\tpw.Close()\n\tscanner := bufio.NewScanner(pr)\n\tfor scanner.Scan() {\n\t\tbuf.WriteString(scanner.Text() + \"\\n\")\n\t}\n\tpr.Close()\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"git log failed: %w\", err)\n\t}\n\tos.Stdout.Write(buf.Bytes())\n\treturn nil\n}", "predict_code_clean": "func runGitLogWindows(ctx context.Context) error {\n\tctx, cancel := context.WithTimeout(ctx, 5*time.Second)\n\tdefer cancel()\n\tcmd := exec.CommandContext(ctx, \"powershell.exe\", \"-Command\", \n\t\t\"git log --color=always --oneline --decorate --graph --all -n 20\")\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"git log failed: %w\\n%s\", err, output)\n\t}\n\tfmt.Print(\"\\x1b[2J\\x1b[H\") \n\tfmt.Println(strings.TrimSpace(string(output)))\n\treturn nil\n}"}} {"repo_name": "container-use", "file_name": "/container-use/cmd/container-use/logger.go", "inference_info": {"prefix_code": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nvar (\n\tlogWriter = io.Discard\n)\n\nfunc parseLogLevel(levelStr string) slog.Level {\n\tswitch levelStr {\n\tcase \"debug\", \"DEBUG\":\n\t\treturn slog.LevelDebug\n\tcase \"info\", \"INFO\":\n\t\treturn slog.LevelInfo\n\tcase \"warn\", \"WARN\", \"warning\", \"WARNING\":\n\t\treturn slog.LevelWarn\n\tcase \"error\", \"ERROR\":\n\t\treturn slog.LevelError\n\tdefault:\n\t\treturn slog.LevelInfo\n\t}\n}\n\n", "suffix_code": "\n", "middle_code": "func setupLogger() error {\n\tvar writers []io.Writer\n\tlogFile := filepath.Join(os.TempDir(), \"container-use.debug.stderr.log\")\n\tif v, ok := os.LookupEnv(\"CONTAINER_USE_STDERR_FILE\"); ok {\n\t\tlogFile = v\n\t}\n\tfile, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open log file %s: %w\", logFile, err)\n\t}\n\twriters = append(writers, file)\n\tif len(writers) == 0 {\n\t\tfmt.Fprintf(os.Stderr, \"%s Logging disabled. Set CONTAINER_USE_STDERR_FILE and CONTAINER_USE_LOG_LEVEL environment variables\\n\", time.Now().Format(time.DateTime))\n\t}\n\tlogLevel := parseLogLevel(os.Getenv(\"CONTAINER_USE_LOG_LEVEL\"))\n\tlogWriter = io.MultiWriter(writers...)\n\thandler := slog.NewTextHandler(logWriter, &slog.HandlerOptions{\n\t\tLevel: logLevel,\n\t})\n\tslog.SetDefault(slog.New(handler))\n\treturn nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/container-use/environment/integration/helpers.go", "package integration\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\ttestDaggerClient *dagger.Client\n\tdaggerOnce sync.Once\n\tdaggerErr error\n)\n\n// init sets up logging for tests\nfunc init() {\n\t// Only show warnings and errors in tests unless TEST_VERBOSE is set\n\tlevel := slog.LevelWarn\n\tif os.Getenv(\"TEST_VERBOSE\") != \"\" {\n\t\tlevel = slog.LevelInfo\n\t}\n\n\tslog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{\n\t\tLevel: level,\n\t})))\n}\n\n// WithRepository runs a test function with an isolated repository and UserActions\nfunc WithRepository(t *testing.T, name string, setup RepositorySetup, fn func(t *testing.T, repo *repository.Repository, user *UserActions)) {\n\t// Initialize Dagger (needed for environment operations)\n\tinitializeDaggerOnce(t)\n\n\tctx := context.Background()\n\n\t// Create isolated temp directories\n\trepoDir, err := os.MkdirTemp(\"\", \"cu-test-\"+name+\"-*\")\n\trequire.NoError(t, err, \"Failed to create repo dir\")\n\n\tconfigDir, err := os.MkdirTemp(\"\", \"cu-test-config-\"+name+\"-*\")\n\trequire.NoError(t, err, \"Failed to create config dir\")\n\n\t// Initialize git repo\n\tcmds := [][]string{\n\t\t{\"init\"},\n\t\t{\"config\", \"user.email\", \"test@example.com\"},\n\t\t{\"config\", \"user.name\", \"Test User\"},\n\t\t{\"config\", \"commit.gpgsign\", \"false\"},\n\t}\n\n\tfor _, cmd := range cmds {\n\t\t_, err := repository.RunGitCommand(ctx, repoDir, cmd...)\n\t\trequire.NoError(t, err, \"Failed to run git %v\", cmd)\n\t}\n\n\t// Run setup to populate repo\n\tif setup != nil {\n\t\tsetup(t, repoDir)\n\t}\n\n\t// Open repository with isolated base path\n\trepo, err := repository.OpenWithBasePath(ctx, repoDir, configDir)\n\trequire.NoError(t, err, \"Failed to open repository\")\n\n\t// Create UserActions with extended capabilities\n\tuser := NewUserActions(t, repo, testDaggerClient).WithDirectAccess(repoDir, configDir)\n\n\t// Cleanup\n\tt.Cleanup(func() {\n\t\t// Clean up any environments created during the test\n\t\tenvs, _ := repo.List(context.Background())\n\t\tfor _, env := range envs {\n\t\t\trepo.Delete(context.Background(), env.ID)\n\t\t}\n\n\t\t// Remove directories\n\t\tos.RemoveAll(repoDir)\n\t\tos.RemoveAll(configDir)\n\t})\n\n\t// Run the test function\n\tfn(t, repo, user)\n}\n\n// RepositorySetup is a function that prepares a test repository\ntype RepositorySetup func(t *testing.T, repoDir string)\n\n// Common repository setups\nvar (\n\tSetupPythonRepo = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"main.py\", \"def main():\\n print('Hello World')\\n\\nif __name__ == '__main__':\\n main()\\n\")\n\t\twriteFile(t, repoDir, \"requirements.txt\", \"requests==2.31.0\\nnumpy==1.24.0\\n\")\n\t\twriteFile(t, repoDir, \".gitignore\", \"__pycache__/\\n*.pyc\\n.env\\nvenv/\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Python project\")\n\t}\n\n\tSetupPythonRepoNoGitignore = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"main.py\", \"def main():\\n print('Hello World')\\n\\nif __name__ == '__main__':\\n main()\\n\")\n\t\twriteFile(t, repoDir, \"requirements.txt\", \"requests==2.31.0\\nnumpy==1.24.0\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Python project\")\n\t}\n\n\tSetupNodeRepo = func(t *testing.T, repoDir string) {\n\t\tpackageJSON := `{\n \"name\": \"test-project\",\n \"version\": \"1.0.0\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"node index.js\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"express\": \"^4.18.0\"\n }\n}`\n\t\twriteFile(t, repoDir, \"package.json\", packageJSON)\n\t\twriteFile(t, repoDir, \"index.js\", \"console.log('Hello from Node.js');\\n\")\n\t\twriteFile(t, repoDir, \".gitignore\", \"node_modules/\\n.env\\n\")\n\t\tgitCommit(t, repoDir, \"Initial Node project\")\n\t}\n\n\tSetupEmptyRepo = func(t *testing.T, repoDir string) {\n\t\twriteFile(t, repoDir, \"README.md\", \"# Test Project\\n\")\n\t\tgitCommit(t, repoDir, \"Initial commit\")\n\t}\n)\n\n// Helper functions for repository setup\nfunc writeFile(t *testing.T, repoDir, path, content string) {\n\tfullPath := filepath.Join(repoDir, path)\n\tdir := filepath.Dir(fullPath)\n\terr := os.MkdirAll(dir, 0755)\n\trequire.NoError(t, err, \"Failed to create dir\")\n\terr = os.WriteFile(fullPath, []byte(content), 0644)\n\trequire.NoError(t, err, \"Failed to write file\")\n}\n\nfunc gitCommit(t *testing.T, repoDir, message string) {\n\tctx := context.Background()\n\t_, err := repository.RunGitCommand(ctx, repoDir, \"add\", \".\")\n\trequire.NoError(t, err, \"Failed to stage files\")\n\t_, err = repository.RunGitCommand(ctx, repoDir, \"commit\", \"-m\", message)\n\trequire.NoError(t, err, \"Failed to commit\")\n}\n\n// initializeDaggerOnce initializes Dagger client once for all tests\nfunc initializeDaggerOnce(t *testing.T) {\n\tdaggerOnce.Do(func() {\n\t\tif testDaggerClient != nil {\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.Background()\n\t\tclient, err := dagger.Connect(ctx)\n\t\tif err != nil {\n\t\t\tdaggerErr = err\n\t\t\treturn\n\t\t}\n\n\t\ttestDaggerClient = client\n\t})\n\n\tif daggerErr != nil {\n\t\tt.Skipf(\"Skipping test - Dagger not available: %v\", daggerErr)\n\t}\n}\n\n// UserActions provides test helpers that mirror MCP tool behavior exactly\n// These represent what a user would experience when using the MCP tools\ntype UserActions struct {\n\tt *testing.T\n\tctx context.Context\n\trepo *repository.Repository\n\tdag *dagger.Client\n\trepoDir string // Source directory (for direct manipulation)\n\tconfigDir string // Container-use config directory\n}\n\nfunc NewUserActions(t *testing.T, repo *repository.Repository, dag *dagger.Client) *UserActions {\n\treturn &UserActions{\n\t\tt: t,\n\t\tctx: context.Background(),\n\t\trepo: repo,\n\t\tdag: dag,\n\t}\n}\n\n// WithDirectAccess adds direct filesystem access for edge case testing\nfunc (u *UserActions) WithDirectAccess(repoDir, configDir string) *UserActions {\n\tu.repoDir = repoDir\n\tu.configDir = configDir\n\treturn u\n}\n\n// FileWrite mirrors environment_file_write MCP tool behavior\nfunc (u *UserActions) FileWrite(envID, targetFile, contents, explanation string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\terr = env.FileWrite(u.ctx, explanation, targetFile, contents)\n\trequire.NoError(u.t, err, \"FileWrite should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after FileWrite should succeed\")\n}\n\n// RunCommand mirrors environment_run_cmd MCP tool behavior\nfunc (u *UserActions) RunCommand(envID, command, explanation string) string {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\toutput, err := env.Run(u.ctx, command, \"/bin/sh\", false)\n\trequire.NoError(u.t, err, \"Run command should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after Run should succeed\")\n\n\treturn output\n}\n\n// CreateEnvironment mirrors environment_create MCP tool behavior\nfunc (u *UserActions) CreateEnvironment(title, explanation string) *environment.Environment {\n\tenv, err := u.repo.Create(u.ctx, u.dag, title, explanation)\n\trequire.NoError(u.t, err, \"Create environment should succeed\")\n\treturn env\n}\n\n// UpdateEnvironment mirrors environment_update MCP tool behavior\nfunc (u *UserActions) UpdateEnvironment(envID, title, explanation string, config *environment.EnvironmentConfig) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\tif title != \"\" {\n\t\tenv.State.Title = title\n\t}\n\n\terr = env.UpdateConfig(u.ctx, config)\n\trequire.NoError(u.t, err, \"UpdateConfig should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after UpdateConfig should succeed\")\n}\n\n// FileDelete mirrors environment_file_delete MCP tool behavior\nfunc (u *UserActions) FileDelete(envID, targetFile, explanation string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\terr = env.FileDelete(u.ctx, explanation, targetFile)\n\trequire.NoError(u.t, err, \"FileDelete should succeed\")\n\n\terr = u.repo.Update(u.ctx, env, explanation)\n\trequire.NoError(u.t, err, \"repo.Update after FileDelete should succeed\")\n}\n\n// FileRead mirrors environment_file_read MCP tool behavior (read-only, no update)\nfunc (u *UserActions) FileRead(envID, targetFile string) string {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\tcontent, err := env.FileRead(u.ctx, targetFile, true, 0, 0)\n\trequire.NoError(u.t, err, \"FileRead should succeed\")\n\treturn content\n}\n\n// FileReadExpectError is for testing expected failures\nfunc (u *UserActions) FileReadExpectError(envID, targetFile string) {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Failed to get environment %s\", envID)\n\n\t_, err = env.FileRead(u.ctx, targetFile, true, 0, 0)\n\tassert.Error(u.t, err, \"FileRead should fail for %s\", targetFile)\n}\n\n// GetEnvironment retrieves an environment by ID - mirrors how MCP tools work\n// Each MCP tool call starts fresh by getting the environment from the repository\nfunc (u *UserActions) GetEnvironment(envID string) *environment.Environment {\n\tenv, err := u.repo.Get(u.ctx, u.dag, envID)\n\trequire.NoError(u.t, err, \"Should be able to get environment %s\", envID)\n\treturn env\n}\n\n// --- Direct manipulation methods for edge case testing ---\n\n// WriteSourceFile writes directly to the source repository\nfunc (u *UserActions) WriteSourceFile(path, content string) {\n\trequire.NotEmpty(u.t, u.repoDir, \"Need direct access for source file manipulation\")\n\tfullPath := filepath.Join(u.repoDir, path)\n\tdir := filepath.Dir(fullPath)\n\n\terr := os.MkdirAll(dir, 0755)\n\trequire.NoError(u.t, err, \"Failed to create dir\")\n\n\terr = os.WriteFile(fullPath, []byte(content), 0644)\n\trequire.NoError(u.t, err, \"Failed to write source file\")\n}\n\n// WorktreePath returns the worktree path for an environment, handling errors\nfunc (u *UserActions) WorktreePath(envID string) string {\n\tworktreePath, err := u.repo.WorktreePath(envID)\n\trequire.NoError(u.t, err, \"Failed to get worktree path for environment %s\", envID)\n\treturn worktreePath\n}\n\n// ReadWorktreeFile reads directly from an environment's worktree\nfunc (u *UserActions) ReadWorktreeFile(envID, path string) string {\n\tworktreePath := u.WorktreePath(envID)\n\tfullPath := filepath.Join(worktreePath, path)\n\tcontent, err := os.ReadFile(fullPath)\n\trequire.NoError(u.t, err, \"Failed to read worktree file\")\n\treturn string(content)\n}\n\n// CorruptWorktree simulates worktree corruption for recovery testing\nfunc (u *UserActions) CorruptWorktree(envID string) {\n\tworktreePath := u.WorktreePath(envID)\n\n\t// Remove .git directory to corrupt the worktree\n\tgitDir := filepath.Join(worktreePath, \".git\")\n\terr := os.RemoveAll(gitDir)\n\trequire.NoError(u.t, err, \"Failed to corrupt worktree\")\n}\n\n// GitCommand runs a git command in the source repository\nfunc (u *UserActions) GitCommand(args ...string) string {\n\trequire.NotEmpty(u.t, u.repoDir, \"Need direct access for git commands\")\n\toutput, err := repository.RunGitCommand(u.ctx, u.repoDir, args...)\n\trequire.NoError(u.t, err, \"Git command failed: %v\", args)\n\treturn output\n}\n"], ["/container-use/cmd/container-use/watch_windows.go", "//go:build windows\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org/x/term\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar watchCmd = &cobra.Command{\n\tUse: \"watch\",\n\tShort: \"Watch environment activity in real-time\",\n\tLong: `Continuously display environment activity as agents work.\nShows new commits and environment changes updated every second.\nPress Ctrl+C to stop watching.`,\n\tExample: `# Watch all environment activity\ncontainer-use watch\n\n# Monitor agents while they work\ncontainer-use watch`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\tif _, err := repository.Open(ctx, \".\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Enter alternate screen buffer and hide cursor\n\t\tfmt.Print(\"\\x1b[?1049h\\x1b[?25l\")\n\t\tdefer fmt.Print(\"\\x1b[?25h\\x1b[?1049l\") // restore screen + show cursor\n\n\t\tticker := time.NewTicker(time.Second)\n\t\tdefer ticker.Stop()\n\n\t\t// Run once immediately\n\t\tif err := runGitLogWindows(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tcase <-ticker.C:\n\t\t\t\tif err := runGitLogWindows(ctx); err != nil {\n\t\t\t\t\t// Don't exit on git errors, just display them and continue\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Warning: %v\\n\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n}\n\n// runGitLogWindows executes the git log command with output matching Unix watch format\nfunc runGitLogWindows(ctx context.Context) error {\n\tvar buf bytes.Buffer\n\n\t// Clear screen and move cursor to home position\n\tbuf.WriteString(\"\\x1b[H\\x1b[J\")\n\n\t// Get hostname\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"unknown\"\n\t}\n\n\t// Format timestamp like Unix watch (Day Month DD HH:MM:SS YYYY)\n\ttimestamp := time.Now().Format(\"Mon Jan 2 15:04:05 2006\")\n\n\t// Create header that matches Unix watch format exactly\n\tgitCommand := \"git log --color=always --remotes=container-use --oneline --graph --decorate\"\n\theaderLine := fmt.Sprintf(\"Every 1.0s: %s\", gitCommand)\n\n\t// Get terminal width, fallback to 80 if unable to determine\n\tterminalWidth := 80\n\tif width, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && width > 0 {\n\t\tterminalWidth = width\n\t}\n\n\t// Calculate spaces needed to right-align the hostname and timestamp\n\trightPart := fmt.Sprintf(\"%s: %s\", hostname, timestamp)\n\tspacesNeeded := terminalWidth - len(headerLine) - len(rightPart)\n\n\t// Write the header line with responsive spacing\n\tif spacesNeeded >= 1 {\n\t\t// Enough space to fit on one line - right align\n\t\tbuf.WriteString(headerLine + strings.Repeat(\" \", spacesNeeded) + rightPart + \"\\n\")\n\t} else {\n\t\t// Not enough space - wrap to next line with minimum 1 space\n\t\tbuf.WriteString(headerLine + \" \" + rightPart + \"\\n\")\n\t}\n\tbuf.WriteString(\"\\n\") // Empty line after header to match Unix watch format\n\n\t// Run git log command with same arguments as Unix version\n\tcmd := exec.CommandContext(ctx, \"git\", \"log\",\n\t\t\"--color=always\",\n\t\t\"--remotes=container-use\",\n\t\t\"--oneline\",\n\t\t\"--graph\",\n\t\t\"--decorate\")\n\n\t// Create pipe to capture output\n\tpr, pw, err := os.Pipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create pipe: %w\", err)\n\t}\n\n\tcmd.Stdout = pw\n\tcmd.Stderr = pw\n\n\t// Start the command\n\tif err := cmd.Start(); err != nil {\n\t\tpw.Close()\n\t\tpr.Close()\n\t\treturn fmt.Errorf(\"failed to start git log: %w\", err)\n\t}\n\n\t// Close write end so we can read\n\tpw.Close()\n\n\t// Read all output into buffer\n\tscanner := bufio.NewScanner(pr)\n\tfor scanner.Scan() {\n\t\tbuf.WriteString(scanner.Text() + \"\\n\")\n\t}\n\n\tpr.Close()\n\n\t// Wait for command to complete\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"git log failed: %w\", err)\n\t}\n\n\t// Output everything at once for smooth rendering\n\tos.Stdout.Write(buf.Bytes())\n\n\treturn nil\n}\n\nfunc init() {\n\trootCmd.AddCommand(watchCmd)\n}\n"], ["/container-use/cmd/container-use/agent/configure.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/dagger/container-use/mcpserver\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype MCPServersConfig struct {\n\tMCPServers map[string]MCPServer `json:\"mcpServers\"`\n}\n\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tEnv map[string]string `json:\"env,omitempty\"`\n\tTimeout *int `json:\"timeout,omitempty\"`\n\tDisabled *bool `json:\"disabled,omitempty\"`\n\tAutoApprove []string `json:\"autoApprove,omitempty\"`\n\tAlwaysAllow []string `json:\"alwaysAllow,omitempty\"`\n\tWorkingDir *string `json:\"working_directory,omitempty\"`\n\tStartOnLaunch *bool `json:\"start_on_launch,omitempty\"`\n}\n\nconst ContainerUseBinary = \"container-use\"\n\nvar AgentCmd = &cobra.Command{\n\tUse: \"agent [agent]\",\n\tShort: \"Configure MCP server for different agents\",\n\tLong: `Setup the container-use MCP server according to the specified agent including Claude Code, Goose, Cursor, and others.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) == 0 {\n\t\t\treturn interactiveConfiguration()\n\t\t}\n\t\tagent, err := selectAgent(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn configureAgent(agent)\n\t},\n}\n\nfunc interactiveConfiguration() error {\n\tselectedAgent, err := RunAgentSelector()\n\tif err != nil {\n\t\t// If the user quits, it's not an error, just exit gracefully.\n\t\tif err.Error() == \"no agent selected\" {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"failed to select agent: %w\", err)\n\t}\n\n\tagent, err := selectAgent(selectedAgent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn configureAgent(agent)\n}\n\ntype ConfigurableAgent interface {\n\tname() string\n\tdescription() string\n\teditMcpConfig() error\n\teditRules() error\n\tisInstalled() bool\n}\n\n// Add agents here\nfunc selectAgent(agentKey string) (ConfigurableAgent, error) {\n\t// Check if agent is supported on current platform\n\tif runtime.GOOS == \"windows\" {\n\t\tswitch agentKey {\n\t\tcase \"codex\", \"amazonq\":\n\t\t\treturn nil, fmt.Errorf(\"agent '%s' is not supported on native Windows.\\nTo use this agent, please install and run container-use in Windows Subsystem for Linux (WSL)\", agentKey)\n\t\t}\n\t}\n\n\tswitch agentKey {\n\tcase \"claude\":\n\t\treturn &ConfigureClaude{}, nil\n\tcase \"goose\":\n\t\treturn &ConfigureGoose{}, nil\n\tcase \"cursor\":\n\t\treturn &ConfigureCursor{}, nil\n\tcase \"codex\":\n\t\treturn &ConfigureCodex{}, nil\n\tcase \"amazonq\":\n\t\treturn &ConfigureQ{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown agent: %s\", agentKey)\n}\n\nfunc configureAgent(agent ConfigurableAgent) error {\n\tfmt.Printf(\"Configuring %s...\\n\", agent.name())\n\n\t// Save MCP config\n\terr := agent.editMcpConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"✓ Configured %s MCP configuration\\n\", agent.name())\n\n\t// Save rules\n\terr = agent.editRules()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"✓ Saved %s container-use rules\\n\", agent.name())\n\n\tfmt.Printf(\"\\n%s configuration complete!\\n\", agent.name())\n\treturn nil\n}\n\n// Helper functions\nfunc saveRulesFile(rulesFile, content string) error {\n\tdir := filepath.Dir(rulesFile)\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t// Append to file if it exists, create if it doesn't TODO make it re-entrant with a marker\n\texisting, err := os.ReadFile(rulesFile)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to read existing rules: %w\", err)\n\t}\n\texistingStr := string(existing)\n\n\teditedRules, err := editRulesFile(existingStr, content)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(rulesFile, []byte(editedRules), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update rules: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc editRulesFile(existingRules, content string) (string, error) {\n\t// Look for section markers\n\tconst marker = \"\"\n\n\tif strings.Contains(existingRules, marker) {\n\t\t// Update existing section\n\t\tparts := strings.Split(existingRules, marker)\n\t\tif len(parts) != 3 {\n\t\t\treturn \"\", fmt.Errorf(\"malformed rules file - expected single section marked with %s\", marker)\n\t\t}\n\t\tnewContent := parts[0] + marker + \"\\n\" + content + \"\\n\" + marker + parts[2]\n\t\treturn newContent, nil\n\t} else {\n\t\t// Append new section\n\t\tnewContent := existingRules\n\t\tif len(newContent) > 0 && !strings.HasSuffix(newContent, \"\\n\") {\n\t\t\tnewContent += \"\\n\"\n\t\t}\n\t\tnewContent += \"\\n\" + marker + \"\\n\" + content + \"\\n\" + marker + \"\\n\"\n\t\treturn newContent, nil\n\t}\n}\n\nfunc tools(prefix string) []string {\n\ttools := []string{}\n\tfor _, t := range mcpserver.Tools() {\n\t\ttools = append(tools, fmt.Sprintf(\"%s%s\", prefix, t.Definition.Name))\n\t}\n\treturn tools\n}\n"], ["/container-use/mcpserver/tools.go", "package mcpserver\n\nimport (\n\t\"context\"\n\t_ \"embed\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n\t\"github.com/mark3labs/mcp-go/server\"\n)\n\ntype daggerClientKey struct{}\n\nfunc openRepository(ctx context.Context, request mcp.CallToolRequest) (*repository.Repository, error) {\n\tsource, err := request.RequireString(\"environment_source\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trepo, err := repository.Open(ctx, source)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open repository: %w\", err)\n\t}\n\treturn repo, nil\n}\n\nfunc openEnvironment(ctx context.Context, request mcp.CallToolRequest) (*repository.Repository, *environment.Environment, error) {\n\trepo, err := openRepository(ctx, request)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tenvID, err := request.RequireString(\"environment_id\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdag, ok := ctx.Value(daggerClientKey{}).(*dagger.Client)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"dagger client not found in context\")\n\t}\n\tenv, err := repo.Get(ctx, dag, envID)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to get environment: %w\", err)\n\t}\n\treturn repo, env, nil\n}\n\ntype Tool struct {\n\tDefinition mcp.Tool\n\tHandler server.ToolHandlerFunc\n}\n\nfunc RunStdioServer(ctx context.Context, dag *dagger.Client) error {\n\ts := server.NewMCPServer(\n\t\t\"Dagger\",\n\t\t\"1.0.0\",\n\t\tserver.WithInstructions(rules.AgentRules),\n\t)\n\n\tfor _, t := range tools {\n\t\ts.AddTool(t.Definition, wrapToolWithClient(t, dag).Handler)\n\t}\n\n\tslog.Info(\"starting server\")\n\n\tstdioSrv := server.NewStdioServer(s)\n\tstdioSrv.SetErrorLogger(log.Default()) // this should re-use our `slog` handler\n\n\tctx, cancel := signal.NotifyContext(ctx, getNotifySignals()...)\n\tdefer cancel()\n\n\terr := stdioSrv.Listen(ctx, os.Stdin, os.Stdout)\n\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nvar tools = []*Tool{}\n\nfunc Tools() []*Tool {\n\treturn tools\n}\n\nfunc registerTool(tool ...*Tool) {\n\tfor _, t := range tool {\n\t\ttools = append(tools, wrapTool(t))\n\t}\n}\n\nfunc wrapTool(tool *Tool) *Tool {\n\treturn &Tool{\n\t\tDefinition: tool.Definition,\n\t\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t\tslog.Info(\"Tool called\", \"tool\", tool.Definition.Name)\n\t\t\tdefer func() {\n\t\t\t\tslog.Info(\"Tool finished\", \"tool\", tool.Definition.Name)\n\t\t\t}()\n\t\t\tresponse, err := tool.Handler(ctx, request)\n\t\t\tif err != nil {\n\t\t\t\treturn mcp.NewToolResultError(err.Error()), nil\n\t\t\t}\n\t\t\treturn response, nil\n\t\t},\n\t}\n}\n\n// keeping this modular for now. we could move tool registration to RunStdioServer and collapse the 2 wrapTool functions.\nfunc wrapToolWithClient(tool *Tool, dag *dagger.Client) *Tool {\n\treturn &Tool{\n\t\tDefinition: tool.Definition,\n\t\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t\tctx = context.WithValue(ctx, daggerClientKey{}, dag)\n\t\t\treturn tool.Handler(ctx, request)\n\t\t},\n\t}\n}\n\nfunc init() {\n\tregisterTool(\n\t\tEnvironmentOpenTool,\n\t\tEnvironmentCreateTool,\n\t\tEnvironmentUpdateMetadataTool,\n\t\tEnvironmentConfigTool,\n\n\t\tEnvironmentRunCmdTool,\n\n\t\tEnvironmentFileReadTool,\n\t\tEnvironmentFileListTool,\n\t\tEnvironmentFileWriteTool,\n\t\tEnvironmentFileEditTool,\n\t\tEnvironmentFileDeleteTool,\n\n\t\tEnvironmentAddServiceTool,\n\n\t\tEnvironmentCheckpointTool,\n\t)\n}\n\ntype EnvironmentResponse struct {\n\tID string `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tConfig *environment.EnvironmentConfig `json:\"config\"`\n\tRemoteRef string `json:\"remote_ref\"`\n\tCheckoutCommand string `json:\"checkout_command_to_share_with_user\"`\n\tLogCommand string `json:\"log_command_to_share_with_user\"`\n\tDiffCommand string `json:\"diff_command_to_share_with_user\"`\n\tServices []*environment.Service `json:\"services,omitempty\"`\n}\n\nfunc environmentResponseFromEnvInfo(envInfo *environment.EnvironmentInfo) *EnvironmentResponse {\n\treturn &EnvironmentResponse{\n\t\tID: envInfo.ID,\n\t\tTitle: envInfo.State.Title,\n\t\tConfig: envInfo.State.Config,\n\t\tRemoteRef: fmt.Sprintf(\"container-use/%s\", envInfo.ID),\n\t\tCheckoutCommand: fmt.Sprintf(\"container-use checkout %s\", envInfo.ID),\n\t\tLogCommand: fmt.Sprintf(\"container-use log %s\", envInfo.ID),\n\t\tDiffCommand: fmt.Sprintf(\"container-use diff %s\", envInfo.ID),\n\t\tServices: nil, // EnvironmentInfo doesn't have \"active\" services, specifically useful for EndpointMappings\n\t}\n}\n\nfunc environmentResponseFromEnv(env *environment.Environment) *EnvironmentResponse {\n\tresp := environmentResponseFromEnvInfo(env.EnvironmentInfo)\n\tresp.Services = env.Services\n\treturn resp\n}\n\nfunc marshalEnvironment(env *environment.Environment) (string, error) {\n\tout, err := json.Marshal(environmentResponseFromEnv(env))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal response: %w\", err)\n\t}\n\treturn string(out), nil\n}\n\nfunc marshalEnvironmentInfo(envInfo *environment.EnvironmentInfo) (string, error) {\n\tout, err := json.Marshal(environmentResponseFromEnvInfo(envInfo))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal response: %w\", err)\n\t}\n\treturn string(out), nil\n}\n\nfunc EnvironmentToCallResult(env *environment.Environment) (*mcp.CallToolResult, error) {\n\tout, err := marshalEnvironment(env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mcp.NewToolResultText(out), nil\n}\n\nfunc EnvironmentInfoToCallResult(envInfo *environment.EnvironmentInfo) (*mcp.CallToolResult, error) {\n\tout, err := marshalEnvironmentInfo(envInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mcp.NewToolResultText(out), nil\n}\n\nvar EnvironmentOpenTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_open\",\n\t\t\"Opens an existing environment. Return format is same as environment_create.\",\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn EnvironmentToCallResult(env)\n\t},\n}\n\nvar EnvironmentCreateTool = &Tool{\n\tDefinition: newRepositoryTool(\n\t\t\"environment_create\",\n\t\t`Creates a new development environment.\nThe environment is the result of a the setups commands on top of the base image.\nEnvironment configuration is managed by the user via cu config commands.`,\n\t\tmcp.WithString(\"title\",\n\t\t\tmcp.Description(\"Short description of the work that is happening in this environment.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, err := openRepository(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttitle, err := request.RequireString(\"title\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdag, ok := ctx.Value(daggerClientKey{}).(*dagger.Client)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"dagger client not found in context\")\n\t\t}\n\n\t\tenv, err := repo.Create(ctx, dag, title, request.GetString(\"explanation\", \"\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create environment: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\n\t\tdirty, status, err := repo.IsDirty(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to check if environment is dirty: %w\", err)\n\t\t}\n\n\t\tif !dirty {\n\t\t\treturn mcp.NewToolResultText(out), nil\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(`%s\n\nCRITICAL: You MUST inform the user that the repository %s has uncommitted changes that are NOT included in this environment. The environment was created from the last committed state only.\n\nUncommitted changes detected:\n%s\n\nYou MUST tell the user: To include these changes in the environment, they need to commit them first using git commands outside the environment.`, out, request.GetString(\"environment_source\", \"\"), status)), nil\n\t},\n}\n\nvar EnvironmentUpdateMetadataTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_update_metadata\",\n\t\t\"Update environment metadata such as title. This updates the descriptive information about what work is being done in the environment.\",\n\t\tmcp.WithString(\"title\",\n\t\t\tmcp.Description(\"Updated title describing the work being done in this environment.\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Update title if provided\n\t\tif title := request.GetString(\"title\", \"\"); title != \"\" {\n\t\t\tenv.State.Title = title\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Environment metadata updated successfully.\\n%s\", out)), nil\n\t},\n}\n\nvar EnvironmentConfigTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_config\",\n\t\t\"Make environment config changes such as base image and setup commands.\"+\n\t\t\t\"If the environment is missing any tools or instructions, you MUST call this function to update the environment.\"+\n\t\t\t\"You MUST update the environment with any useful tools. You will be resumed with no other context than the information provided here\",\n\t\tmcp.WithObject(\"config\",\n\t\t\tmcp.Required(),\n\t\t\tmcp.Properties(map[string]any{\n\t\t\t\t\"base_image\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Base image for the environment\",\n\t\t\t\t},\n\t\t\t\t\"setup_commands\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Commands that should be executed on top of the base image to set up the environment. Similar to `RUN` instructions in Dockerfiles.\",\n\t\t\t\t\t\"items\": map[string]any{\"type\": \"string\"},\n\t\t\t\t},\n\t\t\t\t\"envs\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"The environment variables to set (e.g. `[\\\"FOO=bar\\\", \\\"BAZ=qux\\\"]`).\",\n\t\t\t\t\t\"items\": map[string]any{\"type\": \"string\"},\n\t\t\t\t},\n\t\t\t}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tupdatedConfig := env.State.Config.Copy()\n\n\t\tnewConfig, ok := request.GetArguments()[\"config\"].(map[string]any)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid config\")\n\t\t}\n\n\t\tif baseImage, ok := newConfig[\"base_image\"].(string); ok {\n\t\t\tupdatedConfig.BaseImage = baseImage\n\t\t}\n\n\t\tif setupCommands, ok := newConfig[\"setup_commands\"].([]any); ok {\n\t\t\tupdatedConfig.SetupCommands = make([]string, len(setupCommands))\n\t\t\tfor i, command := range setupCommands {\n\t\t\t\tupdatedConfig.SetupCommands[i] = command.(string)\n\t\t\t}\n\t\t}\n\n\t\tif envs, ok := newConfig[\"envs\"].([]any); ok {\n\t\t\tupdatedConfig.Env = make([]string, len(envs))\n\t\t\tfor i, env := range envs {\n\t\t\t\tupdatedConfig.Env[i] = env.(string)\n\t\t\t}\n\t\t}\n\n\t\tif err := env.UpdateConfig(ctx, updatedConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update repository: %w\", err)\n\t\t}\n\n\t\tout, err := marshalEnvironment(env)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal environment: %w\", err)\n\t\t}\n\n\t\tmessage := fmt.Sprintf(`SUCCESS: Configuration successfully applied. Environment has been restarted, all previous commands have been lost.\nIMPORTANT: The configuration changes are LOCAL to this environment.\nTELL THE USER: To make these changes persistent, they will have to run \"cu config import %s\"\n\n%s\n`, env.ID, out)\n\n\t\treturn mcp.NewToolResultText(message), nil\n\t},\n}\n\nvar EnvironmentListTool = &Tool{\n\tDefinition: newRepositoryTool(\n\t\t\"environment_list\",\n\t\t\"List available environments\",\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, err := openRepository(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenvInfos, err := repo.List(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid source: %w\", err)\n\t\t}\n\n\t\t// Convert EnvironmentInfo slice to EnvironmentResponse slice\n\t\tresponses := make([]EnvironmentResponse, len(envInfos))\n\t\tfor i, envInfo := range envInfos {\n\t\t\tresponses[i] = *environmentResponseFromEnvInfo(envInfo)\n\t\t}\n\n\t\tout, err := json.Marshal(responses)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn mcp.NewToolResultText(string(out)), nil\n\t},\n}\n\nvar EnvironmentRunCmdTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_run_cmd\",\n\t\t\"Run a terminal command inside a NEW container within the environment.\",\n\t\tmcp.WithString(\"command\",\n\t\t\tmcp.Description(\"The terminal command to execute. If empty, the environment's default command is used.\"),\n\t\t),\n\t\tmcp.WithString(\"shell\",\n\t\t\tmcp.Description(\"The shell that will be interpreting this command (default: sh)\"),\n\t\t),\n\t\tmcp.WithBoolean(\"background\",\n\t\t\tmcp.Description(`Run the command in the background\nMust ALWAYS be set for long running command (e.g. http server).\nFailure to do so will result in the tool being stuck, awaiting for the command to finish.`,\n\t\t\t),\n\t\t),\n\t\tmcp.WithBoolean(\"use_entrypoint\",\n\t\t\tmcp.Description(\"Use the image entrypoint, if present, by prepending it to the args.\"),\n\t\t),\n\t\tmcp.WithArray(\"ports\",\n\t\t\tmcp.Description(\"Ports to expose. Only works with background environments. For each port, returns the environment_internal (for use inside environments) and host_external (for use by the user) addresses.\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"number\"}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcommand := request.GetString(\"command\", \"\")\n\t\tshell := request.GetString(\"shell\", \"sh\")\n\n\t\tupdateRepo := func() error {\n\t\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update repository: %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tbackground := request.GetBool(\"background\", false)\n\t\tif background {\n\t\t\tports := []int{}\n\t\t\tif portList, ok := request.GetArguments()[\"ports\"].([]any); ok {\n\t\t\t\tfor _, port := range portList {\n\t\t\t\t\tports = append(ports, int(port.(float64)))\n\t\t\t\t}\n\t\t\t}\n\t\t\tendpoints, runErr := env.RunBackground(ctx, command, shell, ports, request.GetBool(\"use_entrypoint\", false))\n\t\t\t// We want to update the repository even if the command failed.\n\t\t\tif err := updateRepo(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif runErr != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to run command: %w\", runErr)\n\t\t\t}\n\n\t\t\tout, err := json.Marshal(endpoints)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn mcp.NewToolResultText(fmt.Sprintf(`Command started in the background in NEW container. Endpoints are %s\n\nTo access from the user's machine: use host_external. To access from other commands in this environment: use environment_internal.\n\nAny changes to the container workdir (%s) WILL NOT be committed to container-use/%s\n\nBackground commands are unaffected by filesystem and any other kind of changes. You need to start a new command for changes to take effect.`,\n\t\t\t\tstring(out), env.State.Config.Workdir, env.ID)), nil\n\t\t}\n\n\t\tstdout, runErr := env.Run(ctx, command, shell, request.GetBool(\"use_entrypoint\", false))\n\t\t// We want to update the repository even if the command failed.\n\t\tif err := updateRepo(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif runErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to run command: %w\", runErr)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"%s\\n\\nAny changes to the container workdir (%s) have been committed and pushed to container-use/ remote\", stdout, env.State.Config.Workdir)), nil\n\t},\n}\n\nvar EnvironmentFileReadTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_read\",\n\t\t\"Read the contents of a file, specifying a line range or the entire file.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to read, absolute or relative to the workdir\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithBoolean(\"should_read_entire_file\",\n\t\t\tmcp.Description(\"Whether to read the entire file. Defaults to false.\"),\n\t\t),\n\t\tmcp.WithNumber(\"start_line_one_indexed_inclusive\",\n\t\t\tmcp.Description(\"The one-indexed line number to start reading from (inclusive).\"),\n\t\t),\n\t\tmcp.WithNumber(\"end_line_one_indexed_inclusive\",\n\t\t\tmcp.Description(\"The one-indexed line number to end reading at (inclusive).\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshouldReadEntireFile := request.GetBool(\"should_read_entire_file\", false)\n\t\tstartLineOneIndexedInclusive := request.GetInt(\"start_line_one_indexed_inclusive\", 0)\n\t\tendLineOneIndexedInclusive := request.GetInt(\"end_line_one_indexed_inclusive\", 0)\n\n\t\tfileContents, err := env.FileRead(ctx, targetFile, shouldReadEntireFile, startLineOneIndexedInclusive, endLineOneIndexedInclusive)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read file: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fileContents), nil\n\t},\n}\n\nvar EnvironmentFileListTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_list\",\n\t\t\"List the contents of a directory\",\n\t\tmcp.WithString(\"path\",\n\t\t\tmcp.Description(\"Path of the directory to list contents of, absolute or relative to the workdir\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpath, err := request.RequireString(\"path\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tout, err := env.FileList(ctx, path)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list directory: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(out), nil\n\t},\n}\n\nvar EnvironmentFileWriteTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_write\",\n\t\t\"Write the contents of a file.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to write, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"contents\",\n\t\t\tmcp.Description(\"Full text content of the file you want to write.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcontents, err := request.RequireString(\"contents\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileWrite(ctx, request.GetString(\"explanation\", \"\"), targetFile, contents); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to write file: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to update the environment: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s written successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentFileEditTool = &Tool{\n\tDefinition: mcp.NewTool(\"environment_file_edit\",\n\t\tmcp.WithDescription(\"Find and replace text in a file.\"),\n\t\tmcp.WithString(\"explanation\",\n\t\t\tmcp.Description(\"One sentence explanation for why this file is being edited.\"),\n\t\t),\n\t\tmcp.WithString(\"environment_source\",\n\t\t\tmcp.Description(\"Absolute path to the source git repository for the environment.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"environment_id\",\n\t\t\tmcp.Description(\"The ID of the environment for this command. Must call `environment_create` first.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to write, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"search_text\",\n\t\t\tmcp.Description(\"The text to find and replace.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"replace_text\",\n\t\t\tmcp.Description(\"The text to insert.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"which_match\",\n\t\t\tmcp.Description(\"The ID of the match to replace, if there were multiple matches.\"),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"unable to open the environment\", err), nil\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsearch, err := request.RequireString(\"search_text\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treplace, err := request.RequireString(\"replace_text\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileEdit(ctx,\n\t\t\trequest.GetString(\"explanation\", \"\"),\n\t\t\ttargetFile,\n\t\t\tsearch,\n\t\t\treplace,\n\t\t\trequest.GetString(\"which_match\", \"\"),\n\t\t); err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"failed to write file\", err), nil\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn mcp.NewToolResultErrorFromErr(\"unable to update the environment\", err), nil\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s edited successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentFileDeleteTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_file_delete\",\n\t\t\"Deletes a file at the specified path.\",\n\t\tmcp.WithString(\"target_file\",\n\t\t\tmcp.Description(\"Path of the file to delete, absolute or relative to the workdir.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttargetFile, err := request.RequireString(\"target_file\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := env.FileDelete(ctx, request.GetString(\"explanation\", \"\"), targetFile); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update env: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"file %s deleted successfully and committed to container-use/ remote\", targetFile)), nil\n\t},\n}\n\nvar EnvironmentCheckpointTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_checkpoint\",\n\t\t\"Checkpoints an environment in its current state as a container.\",\n\t\tmcp.WithString(\"destination\",\n\t\t\tmcp.Description(\"Container image destination to checkpoint to (e.g. registry.com/user/image:tag\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\t_, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdestination, err := request.RequireString(\"destination\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tendpoint, err := env.Checkpoint(ctx, destination)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to checkpoint environment: %w\", err)\n\t\t}\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Checkpoint pushed to %q. You MUST use the full content addressed (@sha256:...) reference in `docker` commands. The entrypoint is set to `sh`, keep that in mind when giving commands to the container.\", endpoint)), nil\n\t},\n}\n\nvar EnvironmentAddServiceTool = &Tool{\n\tDefinition: newEnvironmentTool(\n\t\t\"environment_add_service\",\n\t\t\"Add a service to the environment (e.g. database, cache, etc.)\",\n\t\tmcp.WithString(\"name\",\n\t\t\tmcp.Description(\"The name of the service to start.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"image\",\n\t\t\tmcp.Description(\"The image of the service to start.\"),\n\t\t\tmcp.Required(),\n\t\t),\n\t\tmcp.WithString(\"command\",\n\t\t\tmcp.Description(\"The command to start the service. If not provided the image default command will be used.\"),\n\t\t),\n\t\tmcp.WithArray(\"ports\",\n\t\t\tmcp.Description(\"Ports to expose. For each port, returns the container_internal (for use by environments) and host_external (for use by the user) address.\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"number\"}),\n\t\t),\n\t\tmcp.WithArray(\"envs\",\n\t\t\tmcp.Description(\"The environment variables to set (e.g. `[\\\"FOO=bar\\\", \\\"BAZ=qux\\\"]`).\"),\n\t\t\tmcp.Items(map[string]any{\"type\": \"string\"}),\n\t\t),\n\t),\n\tHandler: func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {\n\t\trepo, env, err := openEnvironment(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserviceName, err := request.RequireString(\"name\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\timage, err := request.RequireString(\"image\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcommand := request.GetString(\"command\", \"\")\n\t\tports := []int{}\n\t\tif portList, ok := request.GetArguments()[\"ports\"].([]any); ok {\n\t\t\tfor _, port := range portList {\n\t\t\t\tports = append(ports, int(port.(float64)))\n\t\t\t}\n\t\t}\n\n\t\tenvs := request.GetStringSlice(\"envs\", []string{})\n\n\t\tservice, err := env.AddService(ctx, request.GetString(\"explanation\", \"\"), &environment.ServiceConfig{\n\t\t\tName: serviceName,\n\t\t\tImage: image,\n\t\t\tCommand: command,\n\t\t\tExposedPorts: ports,\n\t\t\tEnv: envs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add service: %w\", err)\n\t\t}\n\n\t\tif err := repo.Update(ctx, env, request.GetString(\"explanation\", \"\")); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update env: %w\", err)\n\t\t}\n\n\t\toutput, err := json.Marshal(service)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal service: %w\", err)\n\t\t}\n\n\t\treturn mcp.NewToolResultText(fmt.Sprintf(\"Service added and started successfully: %s\", string(output))), nil\n\t},\n}\n"], ["/container-use/repository/git.go", "package repository\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/mitchellh/go-homedir\"\n)\n\nconst (\n\tmaxFileSizeForTextCheck = 10 * 1024 * 1024 // 10MB\n)\n\nvar (\n\turlSchemeRegExp = regexp.MustCompile(`^[^:]+://`)\n\tscpLikeURLRegExp = regexp.MustCompile(`^(?:(?P[^@]+)@)?(?P[^:\\s]+):(?:(?P[0-9]{1,5})(?:\\/|:))?(?P[^\\\\].*\\/[^\\\\].*)$`)\n)\n\n// RunGitCommand executes a git command in the specified directory.\n// This is exported for use in tests and other packages that need direct git access.\nfunc RunGitCommand(ctx context.Context, dir string, args ...string) (out string, rerr error) {\n\tslog.Info(fmt.Sprintf(\"[%s] $ git %s\", dir, strings.Join(args, \" \")))\n\tdefer func() {\n\t\tslog.Info(fmt.Sprintf(\"[%s] $ git %s (DONE)\", dir, strings.Join(args, \" \")), \"err\", rerr)\n\t}()\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) {\n\t\t\treturn \"\", fmt.Errorf(\"git command failed (exit code %d): %w\\nOutput: %s\",\n\t\t\t\texitErr.ExitCode(), err, string(output))\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"git command failed: %w\", err)\n\t}\n\n\treturn string(output), nil\n}\n\n// RunInteractiveGitCommand executes a git command in the specified directory in interactive mode.\nfunc RunInteractiveGitCommand(ctx context.Context, dir string, w io.Writer, args ...string) (rerr error) {\n\tslog.Info(fmt.Sprintf(\"[%s] $ git %s\", dir, strings.Join(args, \" \")))\n\tdefer func() {\n\t\tslog.Info(fmt.Sprintf(\"[%s] $ git %s (DONE)\", dir, strings.Join(args, \" \")), \"err\", rerr)\n\t}()\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Dir = dir\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\n\treturn cmd.Run()\n}\n\nfunc getContainerUseRemote(ctx context.Context, repo string) (string, error) {\n\t// Check if we already have a container-use remote\n\tcuRemote, err := RunGitCommand(ctx, repo, \"remote\", \"get-url\", \"container-use\")\n\tif err != nil {\n\t\t// Check for exit code 2 which means the remote doesn't exist\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(cuRemote), nil\n}\n\nfunc (r *Repository) WorktreePath(id string) (string, error) {\n\treturn homedir.Expand(filepath.Join(r.getWorktreePath(), id))\n}\n\nfunc (r *Repository) deleteWorktree(id string) error {\n\tworktreePath, err := r.WorktreePath(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Deleting worktree at %s\\n\", worktreePath)\n\treturn os.RemoveAll(worktreePath)\n}\n\nfunc (r *Repository) deleteLocalRemoteBranch(id string) error {\n\tslog.Info(\"Pruning git worktrees\", \"repo\", r.forkRepoPath)\n\tif _, err := RunGitCommand(context.Background(), r.forkRepoPath, \"worktree\", \"prune\"); err != nil {\n\t\tslog.Error(\"Failed to prune git worktrees\", \"repo\", r.forkRepoPath, \"err\", err)\n\t\treturn err\n\t}\n\n\tslog.Info(\"Deleting local branch\", \"repo\", r.forkRepoPath, \"branch\", id)\n\tif _, err := RunGitCommand(context.Background(), r.forkRepoPath, \"branch\", \"-D\", id); err != nil {\n\t\tslog.Error(\"Failed to delete local branch\", \"repo\", r.forkRepoPath, \"branch\", id, \"err\", err)\n\t\treturn err\n\t}\n\n\tif _, err := RunGitCommand(context.Background(), r.userRepoPath, \"remote\", \"prune\", containerUseRemote); err != nil {\n\t\tslog.Error(\"Failed to fetch and prune container-use remote\", \"local-repo\", r.userRepoPath, \"err\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) initializeWorktree(ctx context.Context, id string) (string, error) {\n\tworktreePath, err := r.WorktreePath(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := os.Stat(worktreePath); err == nil {\n\t\treturn worktreePath, nil\n\t}\n\n\tslog.Info(\"Initializing worktree\", \"repository\", r.userRepoPath, \"container-id\", id)\n\n\tcurrentHead, err := RunGitCommand(ctx, r.userRepoPath, \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcurrentHead = strings.TrimSpace(currentHead)\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"push\", containerUseRemote, fmt.Sprintf(\"%s:refs/heads/%s\", currentHead, id))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = RunGitCommand(ctx, r.forkRepoPath, \"worktree\", \"add\", worktreePath, id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn worktreePath, nil\n}\n\n// createInitialCommit creates an empty commit with the environment creation message - this prevents multiple environments from overwriting the container-use-state on the parent commit\nfunc (r *Repository) createInitialCommit(ctx context.Context, worktreePath, id, title string) error {\n\tcommitMessage := fmt.Sprintf(\"Create environment %s: %s\", id, title)\n\t_, err := RunGitCommand(ctx, worktreePath, \"commit\", \"--allow-empty\", \"-m\", commitMessage)\n\treturn err\n}\n\nfunc (r *Repository) propagateToWorktree(ctx context.Context, env *environment.Environment, explanation string) (rerr error) {\n\tslog.Info(\"Propagating to worktree...\",\n\t\t\"environment.id\", env.ID,\n\t\t\"workdir\", env.State.Config.Workdir,\n\t\t\"id\", env.ID)\n\tdefer func() {\n\t\tslog.Info(\"Propagating to worktree... (DONE)\",\n\t\t\t\"environment.id\", env.ID,\n\t\t\t\"workdir\", env.State.Config.Workdir,\n\t\t\t\"id\", env.ID,\n\t\t\t\"err\", rerr)\n\t}()\n\n\tif err := r.exportEnvironment(ctx, env); err != nil {\n\t\treturn err\n\t}\n\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\tif err := r.commitWorktreeChanges(ctx, worktreePath, explanation); err != nil {\n\t\treturn fmt.Errorf(\"failed to commit worktree changes: %w\", err)\n\t}\n\n\tif err := r.saveState(ctx, env); err != nil {\n\t\treturn fmt.Errorf(\"failed to add notes: %w\", err)\n\t}\n\n\tslog.Info(\"Fetching container-use remote in source repository\")\n\tif _, err := RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, env.ID); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.propagateGitNotes(ctx, gitNotesStateRef); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) exportEnvironment(ctx context.Context, env *environment.Environment) error {\n\tworktreePointer := fmt.Sprintf(\"gitdir: %s\", filepath.Join(r.forkRepoPath, \"worktrees\", env.ID))\n\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\n\t_, err = env.Workdir().\n\t\tWithNewFile(\".git\", worktreePointer).\n\t\tExport(\n\t\t\tctx,\n\t\t\tworktreePath,\n\t\t\tdagger.DirectoryExportOpts{Wipe: true},\n\t\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\nfunc (r *Repository) propagateGitNotes(ctx context.Context, ref string) error {\n\tfullRef := fmt.Sprintf(\"refs/notes/%s\", ref)\n\tfetch := func() error {\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"fetch\", containerUseRemote, fullRef+\":\"+fullRef)\n\t\treturn err\n\t}\n\n\tif err := fetch(); err != nil {\n\t\tif strings.Contains(err.Error(), \"[rejected]\") {\n\t\t\tif _, err := RunGitCommand(ctx, r.userRepoPath, \"update-ref\", \"-d\", fullRef); err == nil {\n\t\t\t\treturn fetch()\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) saveState(ctx context.Context, env *environment.Environment) error {\n\tstate, err := env.State.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\n\tf, err := os.CreateTemp(os.TempDir(), \".container-use-git-notes-*\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif _, err := f.Write(state); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesStateRef, \"add\", \"-f\", \"-F\", f.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) loadState(ctx context.Context, worktreePath string) ([]byte, error) {\n\tbuff, err := RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesStateRef, \"show\")\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"no note found\") {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn []byte(buff), nil\n}\n\nfunc (r *Repository) addGitNote(ctx context.Context, env *environment.Environment, note string) error {\n\tworktreePath, err := r.WorktreePath(env.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get worktree path: %w\", err)\n\t}\n\t_, err = RunGitCommand(ctx, worktreePath, \"notes\", \"--ref\", gitNotesLogRef, \"append\", \"-m\", note)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.propagateGitNotes(ctx, gitNotesLogRef)\n}\n\nfunc (r *Repository) currentUserBranch(ctx context.Context) (string, error) {\n\treturn RunGitCommand(ctx, r.userRepoPath, \"branch\", \"--show-current\")\n}\n\nfunc (r *Repository) mergeBase(ctx context.Context, env *environment.EnvironmentInfo) (string, error) {\n\tcurrentBranch, err := r.currentUserBranch(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcurrentBranch = strings.TrimSpace(currentBranch)\n\tif currentBranch == \"\" {\n\t\tcurrentBranch = \"HEAD\"\n\t}\n\tenvGitRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, env.ID)\n\tmergeBase, err := RunGitCommand(ctx, r.userRepoPath, \"merge-base\", currentBranch, envGitRef)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(mergeBase), nil\n}\n\nfunc (r *Repository) revisionRange(ctx context.Context, env *environment.EnvironmentInfo) (string, error) {\n\tmergeBase, err := r.mergeBase(ctx, env)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tenvGitRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, env.ID)\n\treturn fmt.Sprintf(\"%s..%s\", mergeBase, envGitRef), nil\n}\n\nfunc (r *Repository) commitWorktreeChanges(ctx context.Context, worktreePath, explanation string) error {\n\tstatus, err := RunGitCommand(ctx, worktreePath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.TrimSpace(status) == \"\" {\n\t\treturn nil\n\t}\n\n\tif err := r.addNonBinaryFiles(ctx, worktreePath); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = RunGitCommand(ctx, worktreePath, \"commit\", \"--allow-empty\", \"--allow-empty-message\", \"-m\", explanation)\n\treturn err\n}\n\n// AI slop below!\n// this is just to keep us moving fast because big git repos get hard to work with\n// and our demos like to download large dependencies.\nfunc (r *Repository) addNonBinaryFiles(ctx context.Context, worktreePath string) error {\n\tstatusOutput, err := RunGitCommand(ctx, worktreePath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor line := range strings.SplitSeq(strings.TrimSpace(statusOutput), \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif len(line) < 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\tindexStatus := line[0]\n\t\tworkTreeStatus := line[1]\n\t\tfileName := strings.TrimSpace(line[2:])\n\t\tif fileName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif r.shouldSkipFile(fileName) {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase indexStatus == '?' && workTreeStatus == '?':\n\t\t\t// ?? = untracked files or directories\n\t\t\tif strings.HasSuffix(fileName, \"/\") {\n\t\t\t\t// Untracked directory - traverse and add non-binary files\n\t\t\t\tdirName := strings.TrimSuffix(fileName, \"/\")\n\t\t\t\tif err := r.addFilesFromUntrackedDirectory(ctx, worktreePath, dirName); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else if !r.isBinaryFile(worktreePath, fileName) {\n\t\t\t\t// Untracked file - add if not binary\n\n\t\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase indexStatus == 'A':\n\t\t\t// A = already staged, skip\n\t\t\tcontinue\n\t\tcase indexStatus == 'D' || workTreeStatus == 'D':\n\t\t\t// D = deleted files (always stage deletion)\n\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\t// M, R, C and other statuses - add if not binary\n\t\t\tif !r.isBinaryFile(worktreePath, fileName) {\n\t\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) shouldSkipFile(fileName string) bool {\n\tskipExtensions := []string{\n\t\t\".tar\", \".tar.gz\", \".tgz\", \".tar.bz2\", \".tbz2\", \".tar.xz\", \".txz\",\n\t\t\".zip\", \".rar\", \".7z\", \".gz\", \".bz2\", \".xz\",\n\t\t\".exe\", \".bin\", \".dmg\", \".pkg\", \".msi\",\n\t\t\".jpg\", \".jpeg\", \".png\", \".gif\", \".bmp\", \".tiff\", \".svg\",\n\t\t\".mp3\", \".mp4\", \".avi\", \".mov\", \".wmv\", \".flv\", \".mkv\",\n\t\t\".pdf\", \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\",\n\t\t\".so\", \".dylib\", \".dll\", \".a\", \".lib\",\n\t}\n\n\tlowerName := strings.ToLower(fileName)\n\tfor _, ext := range skipExtensions {\n\t\tif strings.HasSuffix(lowerName, ext) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Use cross-platform path-aware directory patterns\n\tskipDirNames := []string{\n\t\t\"node_modules\", \".git\", \"__pycache__\", \"venv\", \".venv\", \"env\", \".env\",\n\t\t\"target\", \"build\", \"dist\", \".next\",\n\t}\n\n\tskipFilePatterns := []string{\n\t\t\".DS_Store\", \"*.tmp\", \"*.temp\", \"*.cache\", \"*.log\",\n\t}\n\n\t// Check if the path contains any of the skip directory names\n\tpathParts := strings.Split(filepath.ToSlash(lowerName), \"/\")\n\tfor _, part := range pathParts {\n\t\tfor _, skipDir := range skipDirNames {\n\t\t\tif part == strings.ToLower(skipDir) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check file patterns\n\tfor _, pattern := range skipFilePatterns {\n\t\tif strings.Contains(lowerName, strings.ToLower(pattern)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (r *Repository) IsDirty(ctx context.Context) (bool, string, error) {\n\tstatus, err := RunGitCommand(ctx, r.userRepoPath, \"status\", \"--porcelain\")\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\tif strings.TrimSpace(status) == \"\" {\n\t\treturn false, \"\", nil\n\t}\n\n\treturn true, status, nil\n}\n\nfunc (r *Repository) addFilesFromUntrackedDirectory(ctx context.Context, worktreePath, dirName string) error {\n\tdirPath := filepath.Join(worktreePath, dirName)\n\n\treturn filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(worktreePath, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\tif r.shouldSkipFile(relPath) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif r.shouldSkipFile(relPath) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !r.isBinaryFile(worktreePath, relPath) {\n\t\t\t_, err = RunGitCommand(ctx, worktreePath, \"add\", relPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (r *Repository) isBinaryFile(worktreePath, fileName string) bool {\n\tfullPath := filepath.Join(worktreePath, fileName)\n\n\tstat, err := os.Stat(fullPath)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\tif stat.IsDir() {\n\t\treturn false\n\t}\n\n\tif stat.Size() > maxFileSizeForTextCheck {\n\t\treturn true\n\t}\n\n\t// Empty files should be treated as text files so `touch .gitkeep` and friends work correctly\n\tif stat.Size() == 0 {\n\t\treturn false\n\t}\n\n\tfile, err := os.Open(fullPath)\n\tif err != nil {\n\t\tslog.Error(\"Error opening file\", \"err\", err)\n\t\treturn true\n\t}\n\tdefer file.Close()\n\n\tbuffer := make([]byte, 8000)\n\tn, err := file.Read(buffer)\n\tif err != nil && n == 0 {\n\t\treturn true\n\t}\n\n\tbuffer = buffer[:n]\n\treturn slices.Contains(buffer, 0)\n}\n\nfunc (r *Repository) normalizeForkPath(ctx context.Context, repo string) (string, error) {\n\t// Check if there's an origin remote\n\torigin, err := RunGitCommand(ctx, repo, \"remote\", \"get-url\", \"origin\")\n\tif err != nil {\n\t\t// If not -- this repository is a local one, we're going to use the filesystem path for the container-use repo\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {\n\t\t\t// Exit code 2 means the remote doesn't exist\n\t\t\t// Create a safe path component from the absolute repo path\n\t\t\tsafeRepoPath := createSafePathFromAbsolute(repo)\n\t\t\treturn homedir.Expand(filepath.Join(r.getRepoPath(), safeRepoPath))\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\t// Otherwise, let's use the normalized origin as path\n\tnormalizedOrigin, err := normalizeGitURL(strings.TrimSpace(origin))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn homedir.Expand(filepath.Join(r.getRepoPath(), normalizedOrigin))\n}\n\n// createSafePathFromAbsolute converts an absolute path to a safe relative path component\n// This handles Windows drive letters and special characters that can't be used in paths\nfunc createSafePathFromAbsolute(absPath string) string {\n\t// Convert to forward slashes for consistency\n\tnormalized := filepath.ToSlash(absPath)\n\n\t// Remove leading slash if present\n\tnormalized = strings.TrimPrefix(normalized, \"/\")\n\n\t// Replace colons (from Windows drive letters) with underscores\n\tnormalized = strings.ReplaceAll(normalized, \":\", \"_\")\n\n\t// Replace any remaining problematic characters\n\tnormalized = strings.ReplaceAll(normalized, \"<\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \">\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"|\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"?\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"*\", \"_\")\n\tnormalized = strings.ReplaceAll(normalized, \"\\\"\", \"_\")\n\n\treturn normalized\n}\n\nfunc normalizeGitURL(endpoint string) (string, error) {\n\tif e, ok := normalizeSCPLike(endpoint); ok {\n\t\treturn e, nil\n\t}\n\n\treturn normalizeURL(endpoint)\n}\n\nfunc normalizeURL(endpoint string) (string, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !u.IsAbs() {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"invalid endpoint: %s\", endpoint,\n\t\t)\n\t}\n\n\treturn fmt.Sprintf(\"%s%s\", u.Hostname(), strings.TrimSuffix(u.Path, \".git\")), nil\n}\n\nfunc normalizeSCPLike(endpoint string) (string, bool) {\n\tif matchesURLScheme(endpoint) || !matchesScpLike(endpoint) {\n\t\treturn \"\", false\n\t}\n\n\t_, host, _, path := findScpLikeComponents(endpoint)\n\n\treturn fmt.Sprintf(\"%s/%s\", host, strings.TrimSuffix(path, \".git\")), true\n}\n\n// matchesURLScheme returns true if the given string matches a URL-like\n// format scheme.\nfunc matchesURLScheme(url string) bool {\n\treturn urlSchemeRegExp.MatchString(url)\n}\n\n// matchesScpLike returns true if the given string matches an SCP-like\n// format scheme.\nfunc matchesScpLike(url string) bool {\n\treturn scpLikeURLRegExp.MatchString(url)\n}\n\n// findScpLikeComponents returns the user, host, port and path of the\n// given SCP-like URL.\nfunc findScpLikeComponents(url string) (user, host, port, path string) {\n\tm := scpLikeURLRegExp.FindStringSubmatch(url)\n\treturn m[1], m[2], m[3], m[4]\n}\n"], ["/container-use/repository/repository.go", "package repository\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/environment\"\n\tpetname \"github.com/dustinkirkland/golang-petname\"\n\t\"github.com/mitchellh/go-homedir\"\n)\n\nconst (\n\tcontainerUseRemote = \"container-use\"\n\tgitNotesLogRef = \"container-use\"\n\tgitNotesStateRef = \"container-use-state\"\n)\n\n// getDefaultConfigPath returns the default configuration path for the current OS\nfunc getDefaultConfigPath() string {\n\tif runtime.GOOS == \"windows\" {\n\t\t// On Windows, use APPDATA or LOCALAPPDATA\n\t\tif appData := os.Getenv(\"APPDATA\"); appData != \"\" {\n\t\t\treturn filepath.Join(appData, \"container-use\")\n\t\t}\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\treturn filepath.Join(localAppData, \"container-use\")\n\t\t}\n\t\t// Fallback to home directory\n\t\tif home, err := homedir.Dir(); err == nil {\n\t\t\treturn filepath.Join(home, \"AppData\", \"Roaming\", \"container-use\")\n\t\t}\n\t\treturn \"container-use\" // Last resort fallback\n\t}\n\t// On Unix-like systems (Linux, macOS, etc.)\n\tif home, err := homedir.Dir(); err == nil {\n\t\treturn filepath.Join(home, \".config\", \"container-use\")\n\t}\n\treturn \"~/.config/container-use\" // Fallback for compatibility\n}\n\nvar (\n\tcuGlobalConfigPath = getDefaultConfigPath()\n)\n\ntype Repository struct {\n\tuserRepoPath string\n\tforkRepoPath string\n\tbasePath string // defaults to OS-appropriate config path if empty\n}\n\n// getRepoPath returns the path for storing repository data\nfunc (r *Repository) getRepoPath() string {\n\treturn filepath.Join(r.basePath, \"repos\")\n}\n\n// getWorktreePath returns the path for storing worktrees\nfunc (r *Repository) getWorktreePath() string {\n\treturn filepath.Join(r.basePath, \"worktrees\")\n}\n\nfunc Open(ctx context.Context, repo string) (*Repository, error) {\n\treturn OpenWithBasePath(ctx, repo, cuGlobalConfigPath)\n}\n\n// OpenWithBasePath opens a repository with a custom base path for container-use data.\n// This is useful for tests that need isolated environments.\nfunc OpenWithBasePath(ctx context.Context, repo string, basePath string) (*Repository, error) {\n\t// Expand tilde in basePath for cross-platform compatibility\n\texpandedBasePath, err := homedir.Expand(basePath)\n\tif err != nil {\n\t\t// If expansion fails, use the original path\n\t\texpandedBasePath = basePath\n\t}\n\n\toutput, err := RunGitCommand(ctx, repo, \"rev-parse\", \"--show-toplevel\")\n\tif err != nil {\n\t\t// Check for exit code 128 which means not a git repository\n\t\tvar exitErr *exec.ExitError\n\t\tif errors.As(err, &exitErr) && exitErr.ExitCode() == 128 {\n\t\t\treturn nil, errors.New(\"you must be in a git repository to use container-use\")\n\t\t}\n\t\treturn nil, err\n\t}\n\tuserRepoPath := strings.TrimSpace(output)\n\n\tforkRepoPath, err := getContainerUseRemote(ctx, userRepoPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Create a temporary repository to get the normalized fork path\n\t\ttempRepo := &Repository{basePath: expandedBasePath}\n\t\tforkRepoPath, err = tempRepo.normalizeForkPath(ctx, userRepoPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr := &Repository{\n\t\tuserRepoPath: userRepoPath,\n\t\tforkRepoPath: forkRepoPath,\n\t\tbasePath: expandedBasePath,\n\t}\n\n\tif err := r.ensureFork(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to fork the repository: %w\", err)\n\t}\n\tif err := r.ensureUserRemote(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to set container-use remote: %w\", err)\n\t}\n\n\treturn r, nil\n}\n\nfunc (r *Repository) ensureFork(ctx context.Context) error {\n\t// Make sure the fork repo path exists, otherwise create it\n\t_, err := os.Stat(r.forkRepoPath)\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tslog.Info(\"Initializing local remote\", \"user-repo\", r.userRepoPath, \"fork-repo\", r.forkRepoPath)\n\tif err := os.MkdirAll(r.forkRepoPath, 0755); err != nil {\n\t\treturn err\n\t}\n\t_, err = RunGitCommand(ctx, r.forkRepoPath, \"init\", \"--bare\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *Repository) ensureUserRemote(ctx context.Context) error {\n\tcurrentForkPath, err := getContainerUseRemote(ctx, r.userRepoPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn err\n\t\t}\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"remote\", \"add\", containerUseRemote, r.forkRepoPath)\n\t\treturn err\n\t}\n\n\tif currentForkPath != r.forkRepoPath {\n\t\t_, err := RunGitCommand(ctx, r.userRepoPath, \"remote\", \"set-url\", containerUseRemote, r.forkRepoPath)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *Repository) SourcePath() string {\n\treturn r.userRepoPath\n}\n\nfunc (r *Repository) exists(ctx context.Context, id string) error {\n\tif _, err := RunGitCommand(ctx, r.forkRepoPath, \"rev-parse\", \"--verify\", id); err != nil {\n\t\tif strings.Contains(err.Error(), \"Needed a single revision\") {\n\t\t\treturn fmt.Errorf(\"environment %q not found\", id)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Create creates a new environment with the given description and explanation.\n// Requires a dagger client for container operations during environment initialization.\nfunc (r *Repository) Create(ctx context.Context, dag *dagger.Client, description, explanation string) (*environment.Environment, error) {\n\tid := petname.Generate(2, \"-\")\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.createInitialCommit(ctx, worktree, id, description); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create initial commit: %w\", err)\n\t}\n\n\tworktreeHead, err := RunGitCommand(ctx, worktree, \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tworktreeHead = strings.TrimSpace(worktreeHead)\n\n\tbaseSourceDir, err := dag.\n\t\tHost().\n\t\tDirectory(r.forkRepoPath, dagger.HostDirectoryOpts{NoCache: true}). // bust cache for each Create call\n\t\tAsGit().\n\t\tRef(worktreeHead).\n\t\tTree(dagger.GitRefTreeOpts{DiscardGitDir: true}).\n\t\tSync(ctx) // don't bust cache when loading from state\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed loading initial source directory: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(r.userRepoPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := environment.New(ctx, dag, id, description, config, baseSourceDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.propagateToWorktree(ctx, env, explanation); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\n// Get retrieves a full Environment with dagger client embedded for container operations.\n// Use this when you need to perform container operations like running commands, terminals, etc.\n// For basic metadata access without container operations, use Info() instead.\nfunc (r *Repository) Get(ctx context.Context, dag *dagger.Client, id string) (*environment.Environment, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.loadState(ctx, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := environment.Load(ctx, dag, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\n// Info retrieves environment metadata without requiring dagger operations.\n// This is more efficient than Get() when you only need access to configuration,\n// state, and other metadata without performing container operations.\nfunc (r *Repository) Info(ctx context.Context, id string) (*environment.EnvironmentInfo, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tworktree, err := r.initializeWorktree(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.loadState(ctx, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvInfo, err := environment.LoadInfo(ctx, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn envInfo, nil\n}\n\n// List returns information about all environments in the repository.\n// Returns EnvironmentInfo slice avoiding dagger client initialization.\n// Use Get() on individual environments when you need full Environment with container operations.\nfunc (r *Repository) List(ctx context.Context) ([]*environment.EnvironmentInfo, error) {\n\tbranches, err := RunGitCommand(ctx, r.forkRepoPath, \"branch\", \"--format\", \"%(refname:short)\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvs := []*environment.EnvironmentInfo{}\n\tfor branch := range strings.SplitSeq(branches, \"\\n\") {\n\t\tbranch = strings.TrimSpace(branch)\n\n\t\t// FIXME(aluzzardi): This is a hack to make sure the branch is actually an environment.\n\t\t// There must be a better way to do this.\n\t\tworktree, err := r.WorktreePath(branch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstate, err := r.loadState(ctx, worktree)\n\t\tif err != nil || state == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tenvInfo, err := r.Info(ctx, branch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tenvs = append(envs, envInfo)\n\t}\n\n\t// Sort by most recently updated environments first\n\tsort.Slice(envs, func(i, j int) bool {\n\t\treturn envs[i].State.UpdatedAt.After(envs[j].State.UpdatedAt)\n\t})\n\n\treturn envs, nil\n}\n\n// ListDescendantEnvironments returns environments that are descendants of the given commit.\n// This filters environments to only those where the provided commit is an ancestor\n// of the environment's current HEAD. Environments are sorted by most recently updated first.\nfunc (r *Repository) ListDescendantEnvironments(ctx context.Context, ancestorCommit string) ([]*environment.EnvironmentInfo, error) {\n\tallEnvs, err := r.List(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar filteredEnvs []*environment.EnvironmentInfo\n\tfor _, env := range allEnvs {\n\t\tif r.isDescendantOfCommit(ctx, ancestorCommit, env.ID) {\n\t\t\tfilteredEnvs = append(filteredEnvs, env)\n\t\t}\n\t}\n\n\treturn filteredEnvs, nil\n}\n\n// isDescendantOfCommit checks if the environment is a descendant of the given commit\n// using git merge-base --is-ancestor which is the canonical way to check ancestry\nfunc (r *Repository) isDescendantOfCommit(ctx context.Context, ancestorCommit, envID string) bool {\n\tenvRef := fmt.Sprintf(\"container-use/%s\", envID)\n\n\t// Use git merge-base --is-ancestor to check if ancestorCommit is an ancestor of envRef\n\t// This returns exit code 0 if ancestorCommit is an ancestor of envRef\n\t_, err := RunGitCommand(ctx, r.userRepoPath, \"merge-base\", \"--is-ancestor\", ancestorCommit, envRef)\n\n\treturn err == nil\n}\n\n// Update saves the provided environment to the repository.\n// Writes configuration and source code changes to the worktree and history + state to git notes.\nfunc (r *Repository) Update(ctx context.Context, env *environment.Environment, explanation string) error {\n\tif err := r.propagateToWorktree(ctx, env, explanation); err != nil {\n\t\treturn err\n\t}\n\tif note := env.Notes.Pop(); note != \"\" {\n\t\treturn r.addGitNote(ctx, env, note)\n\t}\n\n\treturn nil\n}\n\n// Delete removes an environment from the repository.\nfunc (r *Repository) Delete(ctx context.Context, id string) error {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.deleteWorktree(id); err != nil {\n\t\treturn err\n\t}\n\tif err := r.deleteLocalRemoteBranch(id); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Checkout changes the user's current branch to that of the identified environment.\n// It attempts to get the most recent commit from the environment without discarding any user changes.\nfunc (r *Repository) Checkout(ctx context.Context, id, branch string) (string, error) {\n\tif err := r.exists(ctx, id); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif branch == \"\" {\n\t\tbranch = \"cu-\" + id\n\t}\n\n\t// set up remote tracking branch if it's not already there\n\t_, err := RunGitCommand(ctx, r.userRepoPath, \"show-ref\", \"--verify\", \"--quiet\", fmt.Sprintf(\"refs/heads/%s\", branch))\n\tlocalBranchExists := err == nil\n\tif !localBranchExists {\n\t\t_, err = RunGitCommand(ctx, r.userRepoPath, \"branch\", \"--track\", branch, fmt.Sprintf(\"%s/%s\", containerUseRemote, id))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t_, err = RunGitCommand(ctx, r.userRepoPath, \"checkout\", branch)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif localBranchExists {\n\t\tremoteRef := fmt.Sprintf(\"%s/%s\", containerUseRemote, id)\n\n\t\tcounts, err := RunGitCommand(ctx, r.userRepoPath, \"rev-list\", \"--left-right\", \"--count\", fmt.Sprintf(\"HEAD...%s\", remoteRef))\n\t\tif err != nil {\n\t\t\treturn branch, err\n\t\t}\n\n\t\tparts := strings.Split(strings.TrimSpace(counts), \"\\t\")\n\t\tif len(parts) != 2 {\n\t\t\treturn branch, fmt.Errorf(\"unexpected git rev-list output: %s\", counts)\n\t\t}\n\t\taheadCount, behindCount := parts[0], parts[1]\n\n\t\tif behindCount != \"0\" && aheadCount == \"0\" {\n\t\t\t_, err = RunGitCommand(ctx, r.userRepoPath, \"merge\", \"--ff-only\", remoteRef)\n\t\t\tif err != nil {\n\t\t\t\treturn branch, err\n\t\t\t}\n\t\t} else if behindCount != \"0\" {\n\t\t\treturn branch, fmt.Errorf(\"switched to %s, but %s is %s ahead and container-use/ remote has %s additional commits\", branch, branch, aheadCount, behindCount)\n\t\t}\n\t}\n\n\treturn branch, err\n}\n\nfunc (r *Repository) Log(ctx context.Context, id string, patch bool, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogArgs := []string{\n\t\t\"log\",\n\t\tfmt.Sprintf(\"--notes=%s\", gitNotesLogRef),\n\t}\n\n\tif patch {\n\t\tlogArgs = append(logArgs, \"--patch\")\n\t} else {\n\t\tlogArgs = append(logArgs, \"--format=%C(yellow)%h%Creset %s %Cgreen(%cr)%Creset %+N\")\n\t}\n\n\trevisionRange, err := r.revisionRange(ctx, envInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogArgs = append(logArgs, revisionRange)\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, logArgs...)\n}\n\nfunc (r *Repository) Diff(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiffArgs := []string{\n\t\t\"diff\",\n\t}\n\n\trevisionRange, err := r.revisionRange(ctx, envInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdiffArgs = append(diffArgs, revisionRange)\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, diffArgs...)\n}\n\nfunc (r *Repository) Merge(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, \"merge\", \"--no-ff\", \"--autostash\", \"-m\", \"Merge environment \"+envInfo.ID, \"--\", \"container-use/\"+envInfo.ID)\n}\n\nfunc (r *Repository) Apply(ctx context.Context, id string, w io.Writer) error {\n\tenvInfo, err := r.Info(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn RunInteractiveGitCommand(ctx, r.userRepoPath, w, \"merge\", \"--autostash\", \"--squash\", \"--\", \"container-use/\"+envInfo.ID)\n}\n"], ["/container-use/cmd/container-use/agent/configure_ui.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Agent represents an agent configuration option\ntype Agent struct {\n\tKey string\n\tName string\n\tDescription string\n}\n\n// Available agents\nvar agents = []Agent{\n\t{\n\t\tKey: \"claude\",\n\t\tName: \"Claude Code\",\n\t\tDescription: \"Anthropic's Claude Code\",\n\t},\n\t{\n\t\tKey: \"goose\",\n\t\tName: \"Goose\",\n\t\tDescription: \"an open source, extensible AI agent that goes beyond code suggestions\",\n\t},\n\t{\n\t\tKey: \"cursor\",\n\t\tName: \"Cursor\",\n\t\tDescription: \"AI-powered code editor\",\n\t},\n\t{\n\t\tKey: \"codex\",\n\t\tName: \"OpenAI Codex\",\n\t\tDescription: \"OpenAI's lightweight coding agent that runs in your terminal (Linux/macOS/WSL)\",\n\t},\n\t{\n\t\tKey: \"amazonq\",\n\t\tName: \"Amazon Q Developer\",\n\t\tDescription: \"Amazon's agentic chat experience in your terminal (Linux/macOS/WSL)\",\n\t},\n}\n\n// getSupportedAgents returns agents that are supported on the current platform\nfunc getSupportedAgents() []Agent {\n\tif runtime.GOOS == \"windows\" {\n\t\t// Filter out Windows-incompatible agents\n\t\tvar supportedAgents []Agent\n\t\tfor _, agent := range agents {\n\t\t\tif agent.Key != \"codex\" && agent.Key != \"amazonq\" {\n\t\t\t\tsupportedAgents = append(supportedAgents, agent)\n\t\t\t}\n\t\t}\n\t\treturn supportedAgents\n\t}\n\treturn agents\n}\n\n// AgentSelectorModel represents the bubbletea model for agent selection\ntype AgentSelectorModel struct {\n\tcursor int\n\tselected string\n\tquit bool\n}\n\n// InitialModel creates the initial model for agent selection\nfunc InitialModel() AgentSelectorModel {\n\treturn AgentSelectorModel{}\n}\n\n// Init initializes the model\nfunc (m AgentSelectorModel) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update handles incoming messages and updates the model\nfunc (m AgentSelectorModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tsupportedAgents := getSupportedAgents()\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch msg.String() {\n\t\tcase \"ctrl+c\", \"q\", \"esc\":\n\t\t\tm.quit = true\n\t\t\treturn m, tea.Quit\n\t\tcase \"up\", \"k\":\n\t\t\tif m.cursor > 0 {\n\t\t\t\tm.cursor--\n\t\t\t}\n\t\tcase \"down\", \"j\":\n\t\t\tif m.cursor < len(supportedAgents)-1 {\n\t\t\t\tm.cursor++\n\t\t\t}\n\t\tcase \"enter\", \" \":\n\t\t\tm.selected = supportedAgents[m.cursor].Key\n\t\t\tm.quit = true\n\t\t\treturn m, tea.Quit\n\t\t}\n\tdefault:\n\t\treturn m, nil\n\t}\n\treturn m, nil\n}\n\n// View renders the interface\nfunc (m AgentSelectorModel) View() string {\n\tif m.quit {\n\t\treturn \"\"\n\t}\n\n\t// Styles\n\ttitleStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#FAFAFA\")).\n\t\tBackground(lipgloss.Color(\"#7D56F4\")).\n\t\tPadding(0, 1).\n\t\tMargin(1, 0).\n\t\tBold(true)\n\n\theaderStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#7D56F4\")).\n\t\tBold(true).\n\t\tMargin(1, 0, 0, 0)\n\n\tselectedStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#FAFAFA\")).\n\t\tBackground(lipgloss.Color(\"#F25D94\")).\n\t\tPadding(0, 1).\n\t\tBold(true)\n\n\tnormalStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#04B575\")).\n\t\tPadding(0, 1)\n\n\tdescriptionStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#626262\")).\n\t\tPadding(0, 1, 0, 3).\n\t\tItalic(true)\n\n\tfooterStyle := lipgloss.NewStyle().\n\t\tForeground(lipgloss.Color(\"#626262\")).\n\t\tMargin(1, 0, 0, 0)\n\n\t// Build the view\n\tvar s strings.Builder\n\n\t// Title\n\ts.WriteString(titleStyle.Render(\"🛠️ Container Use Configuration\"))\n\ts.WriteString(\"\\n\")\n\n\t// Header\n\ts.WriteString(headerStyle.Render(\"Select an agent to configure:\"))\n\ts.WriteString(\"\\n\\n\")\n\n\t// Show WSL note for Windows users\n\tif runtime.GOOS == \"windows\" {\n\t\twslNoteStyle := lipgloss.NewStyle().\n\t\t\tForeground(lipgloss.Color(\"#FFA500\")).\n\t\t\tPadding(0, 1).\n\t\t\tItalic(true)\n\t\ts.WriteString(wslNoteStyle.Render(\"Note: OpenAI Codex and Amazon Q Developer are available in WSL\"))\n\t\ts.WriteString(\"\\n\\n\")\n\t}\n\n\t// Agent list TODO: filter or sort agents based on if they are installed (ConfigurableAgent.isInstalled())\n\tsupportedAgents := getSupportedAgents()\n\tfor i, agent := range supportedAgents {\n\t\tcursor := \" \" // not selected\n\t\tif m.cursor == i {\n\t\t\tcursor = \"▶ \" // selected\n\t\t}\n\n\t\tagentLine := fmt.Sprintf(\"%s%s\", cursor, agent.Name)\n\t\tif m.cursor == i {\n\t\t\ts.WriteString(selectedStyle.Render(agentLine))\n\t\t} else {\n\t\t\ts.WriteString(normalStyle.Render(agentLine))\n\t\t}\n\n\t\ts.WriteString(\"\\n\")\n\n\t\t// Show description for selected item\n\t\tif m.cursor == i {\n\t\t\ts.WriteString(descriptionStyle.Render(agent.Description))\n\t\t\ts.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\t// Footer\n\ts.WriteString(\"\\n\")\n\ts.WriteString(footerStyle.Render(\"Use ↑/↓ or j/k to navigate • Enter/Space to select • q/Ctrl+C/Esc to quit\"))\n\n\treturn s.String()\n}\n\n// RunAgentSelector runs the interactive agent selector and returns the selected agent key\nfunc RunAgentSelector() (string, error) {\n\tp := tea.NewProgram(InitialModel())\n\tfinalModel, err := p.Run()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error running agent selector: %w\", err)\n\t}\n\n\tm := finalModel.(AgentSelectorModel)\n\tif m.selected == \"\" {\n\t\treturn \"\", fmt.Errorf(\"no agent selected\")\n\t}\n\n\treturn m.selected, nil\n}\n"], ["/container-use/environment/config.go", "package environment\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tdefaultImage = \"ubuntu:24.04\"\n\talpineImage = \"alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c\"\n\tconfigDir = \".container-use\"\n\tenvironmentFile = \"environment.json\"\n)\n\nfunc DefaultConfig() *EnvironmentConfig {\n\treturn &EnvironmentConfig{\n\t\tBaseImage: defaultImage,\n\t\tWorkdir: \"/workdir\",\n\t}\n}\n\ntype EnvironmentConfig struct {\n\tWorkdir string `json:\"workdir,omitempty\"`\n\tBaseImage string `json:\"base_image,omitempty\"`\n\tSetupCommands []string `json:\"setup_commands,omitempty\"`\n\tInstallCommands []string `json:\"install_commands,omitempty\"`\n\tEnv KVList `json:\"env,omitempty\"`\n\tSecrets KVList `json:\"secrets,omitempty\"`\n\tServices ServiceConfigs `json:\"services,omitempty\"`\n}\n\ntype ServiceConfig struct {\n\tName string `json:\"name,omitempty\"`\n\tImage string `json:\"image,omitempty\"`\n\tCommand string `json:\"command,omitempty\"`\n\tExposedPorts []int `json:\"exposed_ports,omitempty\"`\n\tEnv []string `json:\"env,omitempty\"`\n}\n\ntype ServiceConfigs []*ServiceConfig\n\nfunc (sc ServiceConfigs) Get(name string) *ServiceConfig {\n\tfor _, cfg := range sc {\n\t\tif cfg.Name == name {\n\t\t\treturn cfg\n\t\t}\n\t}\n\treturn nil\n}\n\n// KVList represents a list of key-value pairs in the format KEY=VALUE\ntype KVList []string\n\n// parseKeyValue parses a key-value string in the format \"KEY=VALUE\"\nfunc (kv KVList) parseKeyValue(raw string) (key, value string) {\n\tk, v, _ := strings.Cut(raw, \"=\")\n\treturn k, v\n}\n\n// Set adds or updates a key-value pair\nfunc (kv *KVList) Set(key, value string) {\n\t// Remove existing key if it exists\n\tkv.Unset(key)\n\t// Add new key-value pair\n\t*kv = append(*kv, fmt.Sprintf(\"%s=%s\", key, value))\n}\n\n// Unset removes a key-value pair by key and returns true if the key was found\nfunc (kv *KVList) Unset(key string) bool {\n\tfound := false\n\tnewList := make([]string, 0, len(*kv))\n\tfor _, item := range *kv {\n\t\tif itemKey, _ := kv.parseKeyValue(item); itemKey != key {\n\t\t\tnewList = append(newList, item)\n\t\t} else {\n\t\t\tfound = true\n\t\t}\n\t}\n\t*kv = newList\n\treturn found\n}\n\n// Clear removes all key-value pairs\nfunc (kv *KVList) Clear() {\n\t*kv = []string{}\n}\n\n// Keys returns all keys in the list\nfunc (kv KVList) Keys() []string {\n\tkeys := make([]string, 0, len(kv))\n\tfor _, item := range kv {\n\t\tif key, _ := kv.parseKeyValue(item); key != \"\" {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\treturn keys\n}\n\n// Get returns the value for a given key, or empty string if not found\nfunc (kv KVList) Get(key string) string {\n\tfor _, item := range kv {\n\t\tif itemKey, value := kv.parseKeyValue(item); itemKey == key {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (config *EnvironmentConfig) Copy() *EnvironmentConfig {\n\tcopy := *config\n\tcopy.Services = make(ServiceConfigs, len(config.Services))\n\tfor i, svc := range config.Services {\n\t\tsvcCopy := *svc\n\t\tcopy.Services[i] = &svcCopy\n\t}\n\treturn ©\n}\n\nfunc (config *EnvironmentConfig) Save(baseDir string) error {\n\tconfigPath := filepath.Join(baseDir, configDir)\n\tif err := os.MkdirAll(configPath, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t// Use a custom encoder to prevent HTML escaping of characters like &, <, >\n\tvar buf bytes.Buffer\n\tencoder := json.NewEncoder(&buf)\n\tencoder.SetIndent(\"\", \" \")\n\tencoder.SetEscapeHTML(false) // This prevents & from being escaped as \\u0026\n\n\tif err := encoder.Encode(config); err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.WriteFile(filepath.Join(configPath, environmentFile), buf.Bytes(), 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (config *EnvironmentConfig) Load(baseDir string) error {\n\tconfigPath := filepath.Join(baseDir, configDir)\n\n\tdata, err := os.ReadFile(filepath.Join(configPath, environmentFile))\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tif err == nil {\n\t\tif err := json.Unmarshal(data, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"], ["/container-use/environment/environment.go", "package environment\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"dagger.io/dagger\"\n)\n\n// EnvironmentInfo contains basic metadata about an environment\n// without requiring dagger operations\ntype EnvironmentInfo struct {\n\tState *State `json:\"state,omitempty\"`\n\n\tID string `json:\"id,omitempty\"`\n}\n\ntype Environment struct {\n\t*EnvironmentInfo\n\n\tdag *dagger.Client\n\n\tServices []*Service\n\tNotes Notes\n\n\tmu sync.RWMutex\n}\n\nfunc New(ctx context.Context, dag *dagger.Client, id, title string, config *EnvironmentConfig, initialSourceDir *dagger.Directory) (*Environment, error) {\n\tenv := &Environment{\n\t\tEnvironmentInfo: &EnvironmentInfo{\n\t\t\tID: id,\n\t\t\tState: &State{\n\t\t\t\tConfig: config,\n\t\t\t\tTitle: title,\n\t\t\t\tCreatedAt: time.Now(),\n\t\t\t\tUpdatedAt: time.Now(),\n\t\t\t},\n\t\t},\n\t\tdag: dag,\n\t}\n\n\tcontainer, err := env.buildBase(ctx, initialSourceDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tslog.Info(\"Creating environment\", \"id\", env.ID, \"workdir\", env.State.Config.Workdir)\n\n\tif err := env.apply(ctx, container); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}\n\nfunc (env *Environment) Workdir() *dagger.Directory {\n\treturn env.container().Directory(env.State.Config.Workdir)\n}\n\nfunc (env *Environment) container() *dagger.Container {\n\tenv.mu.RLock()\n\tdefer env.mu.RUnlock()\n\n\treturn env.dag.LoadContainerFromID(dagger.ContainerID(env.State.Container))\n}\n\nfunc Load(ctx context.Context, dag *dagger.Client, id string, state []byte, worktree string) (*Environment, error) {\n\tenvInfo, err := LoadInfo(ctx, id, state, worktree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv := &Environment{\n\t\tEnvironmentInfo: envInfo,\n\t\tdag: dag,\n\t\t// Services: ?\n\t}\n\n\treturn env, nil\n}\n\n// LoadInfo loads basic environment metadata without requiring dagger operations.\n// This is useful for operations that only need access to configuration and state\n// information without the overhead of initializing container operations.\nfunc LoadInfo(ctx context.Context, id string, state []byte, worktree string) (*EnvironmentInfo, error) {\n\tenvInfo := &EnvironmentInfo{\n\t\tID: id,\n\t\tState: &State{},\n\t}\n\n\tif err := envInfo.State.Unmarshal(state); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Backward compatibility: if there's no config in the state, load it from the worktree\n\tif envInfo.State.Config == nil {\n\t\tconfig := DefaultConfig()\n\t\tif err := config.Load(worktree); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenvInfo.State.Config = config\n\t}\n\n\treturn envInfo, nil\n}\n\nfunc (env *Environment) apply(ctx context.Context, newState *dagger.Container) error {\n\t// TODO(braa): is this sync redundant with newState.ID?\n\tif _, err := newState.Sync(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tcontainerID, err := newState.ID(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenv.mu.Lock()\n\tdefer env.mu.Unlock()\n\tenv.State.UpdatedAt = time.Now()\n\tenv.State.Container = string(containerID)\n\n\treturn nil\n}\n\nfunc containerWithEnvAndSecrets(dag *dagger.Client, container *dagger.Container, envs, secrets []string) (*dagger.Container, error) {\n\tfor _, env := range envs {\n\t\tk, v, found := strings.Cut(env, \"=\")\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid env variable: %s\", env)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid environment variable: %s\", env)\n\t\t}\n\t\tcontainer = container.WithEnvVariable(k, v)\n\t}\n\n\tfor _, secret := range secrets {\n\t\tk, v, found := strings.Cut(secret, \"=\")\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"invalid secret: %s\", secret)\n\t\t}\n\t\tcontainer = container.WithSecretVariable(k, dag.Secret(v))\n\t}\n\n\treturn container, nil\n}\n\nfunc (env *Environment) buildBase(ctx context.Context, baseSourceDir *dagger.Directory) (*dagger.Container, error) {\n\tcontainer := env.dag.\n\t\tContainer().\n\t\tFrom(env.State.Config.BaseImage).\n\t\tWithWorkdir(env.State.Config.Workdir)\n\n\tcontainer, err := containerWithEnvAndSecrets(env.dag, container, env.State.Config.Env, env.State.Config.Secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunCommands := func(commands []string) error {\n\t\tfor _, command := range commands {\n\t\t\tvar err error\n\n\t\t\tcontainer = container.WithExec([]string{\"sh\", \"-c\", command})\n\n\t\t\texitCode, err := container.ExitCode(ctx)\n\t\t\tif err != nil {\n\t\t\t\tvar exitErr *dagger.ExecError\n\t\t\t\tif errors.As(err, &exitErr) {\n\t\t\t\t\tenv.Notes.AddCommand(command, exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t\t\t\treturn fmt.Errorf(\"exit code %d.\\nstdout: %s\\nstderr: %s\\n%w\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr, err)\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstdout, err := container.Stdout(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get stdout: %w\", err)\n\t\t\t}\n\n\t\t\tstderr, err := container.Stderr(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get stderr: %w\", err)\n\t\t\t}\n\n\t\t\tenv.Notes.AddCommand(command, exitCode, stdout, stderr)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// Run setup commands without the source directory for caching purposes\n\tif err := runCommands(env.State.Config.SetupCommands); err != nil {\n\t\treturn nil, fmt.Errorf(\"setup command failed: %w\", err)\n\t}\n\n\tenv.Services, err = env.startServices(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start services: %w\", err)\n\t}\n\tfor _, service := range env.Services {\n\t\tcontainer = container.WithServiceBinding(service.Config.Name, service.svc)\n\t}\n\n\tcontainer = container.WithDirectory(\".\", baseSourceDir)\n\n\t// Run the install commands after the source directory is set up\n\tif err := runCommands(env.State.Config.InstallCommands); err != nil {\n\t\treturn nil, fmt.Errorf(\"install command failed: %w\", err)\n\t}\n\n\treturn container, nil\n}\n\nfunc (env *Environment) UpdateConfig(ctx context.Context, newConfig *EnvironmentConfig) error {\n\tenv.State.Config = newConfig\n\n\t// Re-build the base image with the new config\n\tcontainer, err := env.buildBase(ctx, env.Workdir())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := env.apply(ctx, container); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (env *Environment) Run(ctx context.Context, command, shell string, useEntrypoint bool) (string, error) {\n\targs := []string{}\n\tif command != \"\" {\n\t\targs = []string{shell, \"-c\", command}\n\t}\n\tnewState := env.container().WithExec(args, dagger.ContainerWithExecOpts{\n\t\tUseEntrypoint: useEntrypoint,\n\t\tExpect: dagger.ReturnTypeAny, // Don't treat non-zero exit as error\n\t\tExperimentalPrivilegedNesting: true,\n\t})\n\n\texitCode, err := newState.ExitCode(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get exit code: %w\", err)\n\t}\n\n\tstdout, err := newState.Stdout(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get stdout: %w\", err)\n\t}\n\n\tstderr, err := newState.Stderr(ctx)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get stderr: %w\", err)\n\t}\n\n\t// Log the command execution with all details\n\tenv.Notes.AddCommand(command, exitCode, stdout, stderr)\n\n\t// Always apply the container state (preserving changes even on non-zero exit)\n\tif err := env.apply(ctx, newState); err != nil {\n\t\treturn stdout, fmt.Errorf(\"failed to apply container state: %w\", err)\n\t}\n\n\t// Return combined output (stdout + stderr if there was stderr)\n\tcombinedOutput := stdout\n\tif stderr != \"\" {\n\t\tif stdout != \"\" {\n\t\t\tcombinedOutput += \"\\n\"\n\t\t}\n\t\tcombinedOutput += \"stderr: \" + stderr\n\t}\n\treturn combinedOutput, nil\n}\n\nfunc (env *Environment) RunBackground(ctx context.Context, command, shell string, ports []int, useEntrypoint bool) (EndpointMappings, error) {\n\targs := []string{}\n\tif command != \"\" {\n\t\targs = []string{shell, \"-c\", command}\n\t}\n\tdisplayCommand := command + \" &\"\n\tserviceState := env.container()\n\n\t// Expose ports\n\tfor _, port := range ports {\n\t\tserviceState = serviceState.WithExposedPort(port, dagger.ContainerWithExposedPortOpts{\n\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\tDescription: fmt.Sprintf(\"Port %d\", port),\n\t\t})\n\t}\n\n\t// Start the service\n\tstartCtx, cancel := context.WithTimeout(ctx, serviceStartTimeout)\n\tdefer cancel()\n\tsvc, err := serviceState.AsService(dagger.ContainerAsServiceOpts{\n\t\tArgs: args,\n\t\tUseEntrypoint: useEntrypoint,\n\t}).Start(startCtx)\n\tif err != nil {\n\t\tvar exitErr *dagger.ExecError\n\t\tif errors.As(err, &exitErr) {\n\t\t\tenv.Notes.AddCommand(displayCommand, exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t\treturn nil, fmt.Errorf(\"command failed with exit code %d.\\nstdout: %s\\nstderr: %s\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t}\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\terr = fmt.Errorf(\"service failed to start within %s timeout\", serviceStartTimeout)\n\t\t\tenv.Notes.AddCommand(displayCommand, 137, \"\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tenv.Notes.AddCommand(displayCommand, 0, \"\", \"\")\n\n\tendpoints := EndpointMappings{}\n\tfor _, port := range ports {\n\t\tendpoint := &EndpointMapping{}\n\t\tendpoints[port] = endpoint\n\n\t\t// Expose port on the host\n\t\ttunnel, err := env.dag.Host().Tunnel(svc, dagger.HostTunnelOpts{\n\t\t\tPorts: []dagger.PortForward{\n\t\t\t\t{\n\t\t\t\t\tBackend: port,\n\t\t\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\t\t},\n\t\t\t},\n\t\t}).Start(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texternalEndpoint, err := tunnel.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpoint.HostExternal = externalEndpoint\n\n\t\tinternalEndpoint, err := svc.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tPort: port,\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpoint.EnvironmentInternal = internalEndpoint\n\t}\n\n\treturn endpoints, nil\n}\n\nfunc (env *Environment) Terminal(ctx context.Context) error {\n\tcontainer := env.container()\n\tvar cmd []string\n\tvar sourceRC string\n\tif shells, err := container.File(\"/etc/shells\").Contents(ctx); err == nil {\n\t\tfor shell := range strings.Lines(shells) {\n\t\t\tif shell[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshell = strings.TrimRight(shell, \"\\n\")\n\t\t\tif strings.HasSuffix(shell, \"/bash\") {\n\t\t\t\tsourceRC = fmt.Sprintf(\"[ -f ~/.bashrc ] && . ~/.bashrc; %q --version | head -4; \", shell)\n\t\t\t\tcmd = []string{shell, \"--rcfile\", \"/cu/rc.sh\", \"-i\"}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// Try to show the same pretty PS1 as for the default /bin/sh terminal in dagger\n\tcontainer = container.WithNewFile(\"/cu/rc.sh\", sourceRC+`export PS1=\"\\033[33mcu\\033[0m \\033[02m\\$(pwd | sed \\\"s|^\\$HOME|~|\\\")\\033[0m \\$ \"`+\"\\n\")\n\tif cmd == nil {\n\t\t// If bash not available, assume POSIX shell\n\t\tcontainer = container.WithEnvVariable(\"ENV\", \"/cu/rc.sh\")\n\t\tcmd = []string{\"sh\"}\n\t}\n\tif _, err := container.Terminal(dagger.ContainerTerminalOpts{\n\t\tExperimentalPrivilegedNesting: true,\n\t\tCmd: cmd,\n\t}).Sync(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (env *Environment) Checkpoint(ctx context.Context, target string) (string, error) {\n\treturn env.container().Publish(ctx, target)\n}\n"], ["/container-use/cmd/container-use/config.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/dagger/container-use/cmd/container-use/agent\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\n// Helper function for read-only config operations\nfunc withConfig(cmd *cobra.Command, fn func(*environment.EnvironmentConfig) error) error {\n\tctx := cmd.Context()\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t}\n\n\treturn fn(config)\n}\n\n// Helper function for config update operations\nfunc updateConfig(cmd *cobra.Command, fn func(*environment.EnvironmentConfig) error) error {\n\tctx := cmd.Context()\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t}\n\n\tconfig := environment.DefaultConfig()\n\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t}\n\n\tif err := fn(config); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.Save(repo.SourcePath()); err != nil {\n\t\treturn fmt.Errorf(\"failed to save configuration: %w\", err)\n\t}\n\n\treturn nil\n}\n\nvar configCmd = &cobra.Command{\n\tUse: \"config\",\n\tShort: \"Manage environment configuration\",\n\tLong: `Configure the development environment settings such as base image and setup commands.\nThese settings are stored in .container-use/environment.json and apply to all new environments.`,\n}\n\nfunc init() {\n\tconfigShowCmd.Flags().Bool(\"json\", false, \"Dump the configuration in JSON\")\n}\n\nvar configShowCmd = &cobra.Command{\n\tUse: \"show []\",\n\tShort: \"Show environment configuration\",\n\tLong: `Display environment configuration including base image and setup commands.\nWithout an environment argument, shows the default configuration used for new environments.\nWith an environment argument, shows the configuration for that specific environment.`,\n\tExample: `# Show the default environment configuration\ncontainer-use config show\n\n# Show the configuration for a specific environment\ncontainer-use config show my-env\n`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tvar config *environment.EnvironmentConfig\n\n\t\t// If no environment is specified, use the default configuration\n\t\tif len(args) == 0 {\n\t\t\tconfig = environment.DefaultConfig()\n\t\t\tif err := config.Load(repo.SourcePath()); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to load configuration: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tenvID := args[0]\n\t\t\tenv, err := repo.Info(ctx, envID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tconfig = env.State.Config\n\t\t}\n\n\t\tif ok, _ := cmd.Flags().GetBool(\"json\"); ok {\n\t\t\tenc := json.NewEncoder(os.Stdout)\n\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\treturn enc.Encode(config)\n\t\t}\n\n\t\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\t\tdefer tw.Flush()\n\n\t\tfmt.Fprintf(tw, \"Base Image:\\t%s\\n\", config.BaseImage)\n\t\tfmt.Fprintf(tw, \"Workdir:\\t%s\\n\", config.Workdir)\n\n\t\tif len(config.SetupCommands) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Setup Commands:\\t\\n\")\n\t\t\tfor i, cmd := range config.SetupCommands {\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s\\n\", i+1, cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Setup Commands:\\t(none)\\n\")\n\t\t}\n\n\t\tif len(config.InstallCommands) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Install Commands:\\t\\n\")\n\t\t\tfor i, cmd := range config.InstallCommands {\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s\\n\", i+1, cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Install Commands:\\t(none)\\n\")\n\t\t}\n\n\t\tenvKeys := config.Env.Keys()\n\t\tif len(envKeys) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Environment Variables:\\t\\n\")\n\t\t\tfor i, key := range envKeys {\n\t\t\t\tvalue := config.Env.Get(key)\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Environment Variables:\\t(none)\\n\")\n\t\t}\n\n\t\tsecretKeys := config.Secrets.Keys()\n\t\tif len(secretKeys) > 0 {\n\t\t\tfmt.Fprintf(tw, \"Secrets:\\t\\n\")\n\t\t\tfor i, key := range secretKeys {\n\t\t\t\tvalue := config.Secrets.Get(key)\n\t\t\t\tfmt.Fprintf(tw, \" %d.\\t%s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(tw, \"Secrets:\\t(none)\\n\")\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nvar configImportCmd = &cobra.Command{\n\tUse: \"import \",\n\tShort: \"Import configuration from an environment\",\n\tLong: `Import configuration from an existing environment and set it as the default.\nThis copies the environment's base image, setup commands, environment variables,\nand secrets to be used as defaults for new environments.`,\n\tExample: `# Import configuration from an environment\ncontainer-use config import my-env\n\n# View the configuration before importing\ncontainer-use config show my-env\ncontainer-use config import my-env`,\n\tArgs: cobra.ExactArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tenvID := args[0]\n\t\tenv, err := repo.Info(ctx, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := env.State.Config.Save(repo.SourcePath()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to save configuration: %w\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Configuration imported from environment '%s'\\n\", envID)\n\t\treturn nil\n\t},\n}\n\n// Base image object commands\nvar configBaseImageCmd = &cobra.Command{\n\tUse: \"base-image\",\n\tShort: \"Manage base container image\",\n\tLong: `Manage the base container image for new environments.`,\n}\n\nvar configBaseImageSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set the base container image\",\n\tLong: `Set the base container image for new environments (e.g., python:3.11, node:18, ubuntu:22.04).`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tbaseImage := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.BaseImage = baseImage\n\t\t\tfmt.Printf(\"Base image set to: %s\\n\", baseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configBaseImageGetCmd = &cobra.Command{\n\tUse: \"get\",\n\tShort: \"Get the current base container image\",\n\tLong: `Display the current base container image.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfmt.Println(config.BaseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configBaseImageResetCmd = &cobra.Command{\n\tUse: \"reset\",\n\tShort: \"Reset base image to default\",\n\tLong: `Reset the base container image to the default (ubuntu:24.04).`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tdefaultConfig := environment.DefaultConfig()\n\t\t\tconfig.BaseImage = defaultConfig.BaseImage\n\t\t\tfmt.Printf(\"Base image reset to default: %s\\n\", defaultConfig.BaseImage)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Setup command object commands\nvar configSetupCommandCmd = &cobra.Command{\n\tUse: \"setup-command\",\n\tShort: \"Manage setup commands\",\n\tLong: `Manage setup commands that are run when creating environments.`,\n}\n\nvar configSetupCommandAddCmd = &cobra.Command{\n\tUse: \"add \",\n\tShort: \"Add a setup command\",\n\tLong: `Add a command to be run when creating new environments (e.g., \"apt update && apt install -y python3\").`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.SetupCommands = append(config.SetupCommands, command)\n\t\t\tfmt.Printf(\"Setup command added: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandRemoveCmd = &cobra.Command{\n\tUse: \"remove \",\n\tShort: \"Remove a setup command\",\n\tLong: `Remove a setup command from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfound := false\n\t\t\tnewCommands := make([]string, 0, len(config.SetupCommands))\n\t\t\tfor _, existing := range config.SetupCommands {\n\t\t\t\tif existing != command {\n\t\t\t\t\tnewCommands = append(newCommands, existing)\n\t\t\t\t} else {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\treturn fmt.Errorf(\"setup command not found: %s\", command)\n\t\t\t}\n\n\t\t\tconfig.SetupCommands = newCommands\n\t\t\tfmt.Printf(\"Setup command removed: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all setup commands\",\n\tLong: `List all setup commands that will be run when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif len(config.SetupCommands) == 0 {\n\t\t\t\tfmt.Println(\"No setup commands configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, command := range config.SetupCommands {\n\t\t\t\tfmt.Printf(\"%d. %s\\n\", i+1, command)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSetupCommandClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all setup commands\",\n\tLong: `Remove all setup commands from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.SetupCommands = []string{}\n\t\t\tfmt.Println(\"All setup commands cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Install command object commands\nvar configInstallCommandCmd = &cobra.Command{\n\tUse: \"install-command\",\n\tShort: \"Manage install commands\",\n\tLong: `Manage install commands that are run after copying code to environments.`,\n}\n\nvar configInstallCommandAddCmd = &cobra.Command{\n\tUse: \"add \",\n\tShort: \"Add an install command\",\n\tLong: `Add a command to be run after copying code to new environments (e.g., \"go mod download\").`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.InstallCommands = append(config.InstallCommands, command)\n\t\t\tfmt.Printf(\"Install command added: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandRemoveCmd = &cobra.Command{\n\tUse: \"remove \",\n\tShort: \"Remove an install command\",\n\tLong: `Remove an install command from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcommand := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tfound := false\n\t\t\tnewCommands := make([]string, 0, len(config.InstallCommands))\n\t\t\tfor _, existing := range config.InstallCommands {\n\t\t\t\tif existing != command {\n\t\t\t\t\tnewCommands = append(newCommands, existing)\n\t\t\t\t} else {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\treturn fmt.Errorf(\"install command not found: %s\", command)\n\t\t\t}\n\n\t\t\tconfig.InstallCommands = newCommands\n\t\t\tfmt.Printf(\"Install command removed: %s\\n\", command)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all install commands\",\n\tLong: `List all install commands that will be run after copying code to environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif len(config.InstallCommands) == 0 {\n\t\t\t\tfmt.Println(\"No install commands configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, command := range config.InstallCommands {\n\t\t\t\tfmt.Printf(\"%d. %s\\n\", i+1, command)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configInstallCommandClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all install commands\",\n\tLong: `Remove all install commands from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.InstallCommands = []string{}\n\t\t\tfmt.Println(\"All install commands cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Environment variable object commands\nvar configEnvCmd = &cobra.Command{\n\tUse: \"env\",\n\tShort: \"Manage environment variables\",\n\tLong: `Manage environment variables that are set when creating environments.`,\n}\n\nvar configEnvSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set an environment variable\",\n\tLong: `Set an environment variable to be used when creating new environments (e.g., \"PATH\" \"/usr/local/bin:$PATH\").`,\n\tArgs: cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\tvalue := args[1]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Env.Set(key, value)\n\t\t\tfmt.Printf(\"Environment variable set: %s=%s\\n\", key, value)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvUnsetCmd = &cobra.Command{\n\tUse: \"unset \",\n\tShort: \"Unset an environment variable\",\n\tLong: `Unset an environment variable from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif !config.Env.Unset(key) {\n\t\t\t\treturn fmt.Errorf(\"environment variable not found: %s\", key)\n\t\t\t}\n\t\t\tfmt.Printf(\"Environment variable unset: %s\\n\", key)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all environment variables\",\n\tLong: `List all environment variables that will be set when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tkeys := config.Env.Keys()\n\t\t\tif len(keys) == 0 {\n\t\t\t\tfmt.Println(\"No environment variables configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, key := range keys {\n\t\t\t\tvalue := config.Env.Get(key)\n\t\t\t\tfmt.Printf(\"%d. %s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configEnvClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all environment variables\",\n\tLong: `Remove all environment variables from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Env.Clear()\n\t\t\tfmt.Println(\"All environment variables cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\n// Secret object commands\nvar configSecretCmd = &cobra.Command{\n\tUse: \"secret\",\n\tShort: \"Manage secrets\",\n\tLong: `Manage secrets that are set when creating environments.`,\n}\n\nvar configSecretSetCmd = &cobra.Command{\n\tUse: \"set \",\n\tShort: \"Set a secret\",\n\tLong: `Set a secret to be used when creating new environments (e.g., \"API_KEY\" \"op://vault/item/field\").`,\n\tArgs: cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\tvalue := args[1]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Secrets.Set(key, value)\n\t\t\tfmt.Printf(\"Secret set: %s=%s\\n\", key, value)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretUnsetCmd = &cobra.Command{\n\tUse: \"unset \",\n\tShort: \"Unset a secret\",\n\tLong: `Unset a secret from the environment configuration.`,\n\tArgs: cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tkey := args[0]\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tif !config.Secrets.Unset(key) {\n\t\t\t\treturn fmt.Errorf(\"secret not found: %s\", key)\n\t\t\t}\n\t\t\tfmt.Printf(\"Secret unset: %s\\n\", key)\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretListCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all secrets\",\n\tLong: `List all secrets that will be set when creating environments.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn withConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tkeys := config.Secrets.Keys()\n\t\t\tif len(keys) == 0 {\n\t\t\t\tfmt.Println(\"No secrets configured\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor i, key := range keys {\n\t\t\t\tvalue := config.Secrets.Get(key)\n\t\t\t\tfmt.Printf(\"%d. %s=%s\\n\", i+1, key, value)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nvar configSecretClearCmd = &cobra.Command{\n\tUse: \"clear\",\n\tShort: \"Clear all secrets\",\n\tLong: `Remove all secrets from the environment configuration.`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn updateConfig(cmd, func(config *environment.EnvironmentConfig) error {\n\t\t\tconfig.Secrets.Clear()\n\t\t\tfmt.Println(\"All secrets cleared\")\n\t\t\treturn nil\n\t\t})\n\t},\n}\n\nfunc init() {\n\t// Add base-image commands\n\tconfigBaseImageCmd.AddCommand(configBaseImageSetCmd)\n\tconfigBaseImageCmd.AddCommand(configBaseImageGetCmd)\n\tconfigBaseImageCmd.AddCommand(configBaseImageResetCmd)\n\n\t// Add setup-command commands\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandAddCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandRemoveCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandListCmd)\n\tconfigSetupCommandCmd.AddCommand(configSetupCommandClearCmd)\n\n\t// Add install-command commands\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandAddCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandRemoveCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandListCmd)\n\tconfigInstallCommandCmd.AddCommand(configInstallCommandClearCmd)\n\n\t// Add env commands\n\tconfigEnvCmd.AddCommand(configEnvSetCmd)\n\tconfigEnvCmd.AddCommand(configEnvUnsetCmd)\n\tconfigEnvCmd.AddCommand(configEnvListCmd)\n\tconfigEnvCmd.AddCommand(configEnvClearCmd)\n\n\t// Add secret commands\n\tconfigSecretCmd.AddCommand(configSecretSetCmd)\n\tconfigSecretCmd.AddCommand(configSecretUnsetCmd)\n\tconfigSecretCmd.AddCommand(configSecretListCmd)\n\tconfigSecretCmd.AddCommand(configSecretClearCmd)\n\n\t// Add object commands to config\n\tconfigCmd.AddCommand(configBaseImageCmd)\n\tconfigCmd.AddCommand(configSetupCommandCmd)\n\tconfigCmd.AddCommand(configInstallCommandCmd)\n\tconfigCmd.AddCommand(configEnvCmd)\n\tconfigCmd.AddCommand(configSecretCmd)\n\tconfigCmd.AddCommand(configShowCmd)\n\tconfigCmd.AddCommand(configImportCmd)\n\n\t// Add agent command\n\tconfigCmd.AddCommand(agent.AgentCmd)\n\n\t// Add config command to root\n\trootCmd.AddCommand(configCmd)\n}\n"], ["/container-use/environment/filesystem.go", "package environment\n\nimport (\n\t\"context\"\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"strings\"\n\n\tgodiffpatch \"github.com/sourcegraph/go-diff-patch\"\n)\n\nfunc (env *Environment) FileRead(ctx context.Context, targetFile string, shouldReadEntireFile bool, startLineOneIndexedInclusive int, endLineOneIndexedInclusive int) (string, error) {\n\tfile, err := env.container().File(targetFile).Contents(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif shouldReadEntireFile {\n\t\treturn file, err\n\t}\n\n\tlines := strings.Split(file, \"\\n\")\n\tstart := startLineOneIndexedInclusive - 1\n\tstart = max(start, 0)\n\tif start >= len(lines) {\n\t\tstart = len(lines) - 1\n\t}\n\tif start < 0 {\n\t\treturn \"\", fmt.Errorf(\"error reading file: start_line_one_indexed_inclusive (%d) cannot be less than 1\", startLineOneIndexedInclusive)\n\t}\n\tend := endLineOneIndexedInclusive\n\n\tif end >= len(lines) {\n\t\tend = len(lines) - 1\n\t}\n\tif end < start {\n\t\treturn \"\", fmt.Errorf(\"error reading file: end_line_one_indexed_inclusive (%d) must be greater than start_line_one_indexed_inclusive (%d)\", endLineOneIndexedInclusive, startLineOneIndexedInclusive)\n\t}\n\n\treturn strings.Join(lines[start:end], \"\\n\"), nil\n}\n\nfunc (env *Environment) FileWrite(ctx context.Context, explanation, targetFile, contents string) error {\n\terr := env.apply(ctx, env.container().WithNewFile(targetFile, contents))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file write, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Write %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileEdit(ctx context.Context, explanation, targetFile, search, replace, matchID string) error {\n\tcontents, err := env.container().File(targetFile).Contents(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Find all matches of the search text\n\tmatches := []int{}\n\tcursor := 0\n\tfor {\n\t\tindex := strings.Index(contents[cursor:], search)\n\t\tif index == -1 {\n\t\t\tbreak\n\t\t}\n\t\tactualIndex := cursor + index\n\t\tmatches = append(matches, actualIndex)\n\t\tcursor = actualIndex + 1\n\t}\n\n\tif len(matches) == 0 {\n\t\treturn fmt.Errorf(\"search text not found in file %s\", targetFile)\n\t}\n\n\t// If there are multiple matches and no matchID is provided, return an error with all matches\n\tif len(matches) > 1 && matchID == \"\" {\n\t\tvar matchDescriptions []string\n\t\tfor i, matchIndex := range matches {\n\t\t\t// Generate a unique ID for each match\n\t\t\tid := generateMatchID(targetFile, search, replace, i)\n\n\t\t\t// Get context around the match (3 lines before and after)\n\t\t\tcontext := getMatchContext(contents, matchIndex)\n\n\t\t\tmatchDescriptions = append(matchDescriptions, fmt.Sprintf(\"Match %d (ID: %s):\\n%s\", i+1, id, context))\n\t\t}\n\n\t\treturn fmt.Errorf(\"multiple matches found for search text in %s. Please specify which_match parameter with one of the following IDs:\\n\\n%s\",\n\t\t\ttargetFile, strings.Join(matchDescriptions, \"\\n\\n\"))\n\t}\n\n\t// Determine which match to replace\n\tvar targetMatchIndex int\n\tif len(matches) == 1 {\n\t\ttargetMatchIndex = matches[0]\n\t} else {\n\t\t// Find the match with the specified ID\n\t\tfound := false\n\t\tfor i, matchIndex := range matches {\n\t\t\tid := generateMatchID(targetFile, search, replace, i)\n\t\t\tif id == matchID {\n\t\t\t\ttargetMatchIndex = matchIndex\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"match ID %s not found\", matchID)\n\t\t}\n\t}\n\n\t// Replace the specific match\n\tnewContents := contents[:targetMatchIndex] + replace + contents[targetMatchIndex+len(search):]\n\n\t// Apply the changes using `Directory.withPatch` so we don't have to spit out\n\t// the entire contents\n\tpatch := godiffpatch.GeneratePatch(targetFile, contents, newContents)\n\tctr := env.container()\n\terr = env.apply(ctx, ctr.WithDirectory(\".\", ctr.Directory(\".\").WithPatch(patch)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file edit, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Edit %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileDelete(ctx context.Context, explanation, targetFile string) error {\n\terr := env.apply(ctx, env.container().WithoutFile(targetFile))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed applying file delete, skipping git propagation: %w\", err)\n\t}\n\tenv.Notes.Add(\"Delete %s\", targetFile)\n\treturn nil\n}\n\nfunc (env *Environment) FileList(ctx context.Context, path string) (string, error) {\n\tentries, err := env.container().Directory(path).Entries(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tout := &strings.Builder{}\n\tfor _, entry := range entries {\n\t\tfmt.Fprintf(out, \"%s\\n\", entry)\n\t}\n\treturn out.String(), nil\n}\n\n// generateMatchID creates a unique ID for a match based on file, search, replace, and index\nfunc generateMatchID(targetFile, search, replace string, index int) string {\n\tdata := fmt.Sprintf(\"%s:%s:%s:%d\", targetFile, search, replace, index)\n\thash := sha256.Sum256([]byte(data))\n\treturn fmt.Sprintf(\"%x\", hash)[:8] // Use first 8 characters of hash\n}\n\n// getMatchContext returns the context around a match (3 lines before and after)\nfunc getMatchContext(contents string, matchIndex int) string {\n\tlines := strings.Split(contents, \"\\n\")\n\n\t// Find which line contains the match\n\tcurrentPos := 0\n\tmatchLine := 0\n\tfor i, line := range lines {\n\t\tif currentPos+len(line) >= matchIndex {\n\t\t\tmatchLine = i\n\t\t\tbreak\n\t\t}\n\t\tcurrentPos += len(line) + 1 // +1 for newline\n\t}\n\n\t// Get context lines (3 before, match line, 3 after)\n\tstart := max(0, matchLine-3)\n\tend := min(len(lines), matchLine+4)\n\n\tcontextLines := make([]string, 0, end-start)\n\tfor i := start; i < end; i++ {\n\t\tprefix := \" \"\n\t\tif i == matchLine {\n\t\t\tprefix = \"> \" // Mark the line containing the match\n\t\t}\n\t\t// Include line numbers, which may help the model determine the right match\n\t\tprefix += fmt.Sprintf(\"%4d | \", i+1)\n\t\tcontextLines = append(contextLines, fmt.Sprintf(\"%s%s\", prefix, lines[i]))\n\t}\n\n\treturn strings.Join(contextLines, \"\\n\")\n}\n"], ["/container-use/cmd/container-use/list.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/dustin/go-humanize\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar listCmd = &cobra.Command{\n\tUse: \"list\",\n\tShort: \"List all environments\",\n\tLong: `Display all active environments with their IDs, titles, and timestamps.\nUse -q for environment IDs only, useful for scripting.`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tenvInfos, err := repo.List(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif quiet, _ := app.Flags().GetBool(\"quiet\"); quiet {\n\t\t\tfor _, envInfo := range envInfos {\n\t\t\t\tfmt.Println(envInfo.ID)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\t\tfmt.Fprintln(tw, \"ID\\tTITLE\\tCREATED\\tUPDATED\")\n\n\t\tdefer tw.Flush()\n\t\tfor _, envInfo := range envInfos {\n\t\t\tfmt.Fprintf(tw, \"%s\\t%s\\t%s\\t%s\\n\", envInfo.ID, truncate(app, envInfo.State.Title, 40), humanize.Time(envInfo.State.CreatedAt), humanize.Time(envInfo.State.UpdatedAt))\n\t\t}\n\t\treturn nil\n\t},\n}\n\nfunc truncate(app *cobra.Command, s string, max int) string {\n\tif noTrunc, _ := app.Flags().GetBool(\"no-trunc\"); noTrunc {\n\t\treturn s\n\t}\n\tif len(s) > max {\n\t\treturn s[:max] + \"…\"\n\t}\n\treturn s\n}\n\nfunc init() {\n\tlistCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Display only environment IDs\")\n\tlistCmd.Flags().BoolP(\"no-trunc\", \"\", false, \"Don't truncate output\")\n\trootCmd.AddCommand(listCmd)\n}\n"], ["/container-use/cmd/container-use/version.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"runtime/debug\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tversion = \"dev\"\n\tcommit = \"unknown\"\n\tdate = \"unknown\"\n)\n\nfunc init() {\n\tif version == \"dev\" {\n\t\tif buildCommit, buildTime := getBuildInfoFromBinary(); buildCommit != \"unknown\" {\n\t\t\tcommit = buildCommit\n\t\t\tdate = buildTime\n\t\t}\n\t}\n}\n\nvar versionCmd = &cobra.Command{\n\tUse: \"version\",\n\tShort: \"Print version information\",\n\tLong: `Print the version, commit hash, and build date of the container-use binary.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfmt.Printf(\"container-use version %s\\n\", version)\n\t\tif commit != \"unknown\" {\n\t\t\tfmt.Printf(\"commit: %s\\n\", commit)\n\t\t}\n\t\tif date != \"unknown\" {\n\t\t\tfmt.Printf(\"built: %s\\n\", date)\n\t\t}\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(versionCmd)\n}\n\nfunc getBuildInfoFromBinary() (string, string) {\n\tbuildInfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn \"unknown\", \"unknown\"\n\t}\n\n\tvar revision, buildTime, modified string\n\n\tfor _, setting := range buildInfo.Settings {\n\t\tswitch setting.Key {\n\t\tcase \"vcs.revision\":\n\t\t\trevision = setting.Value\n\t\tcase \"vcs.time\":\n\t\t\tbuildTime = setting.Value\n\t\tcase \"vcs.modified\":\n\t\t\tmodified = setting.Value\n\t\t}\n\t}\n\n\t// Format commit hash (use short version)\n\tif len(revision) > 7 {\n\t\trevision = revision[:7]\n\t}\n\tif modified == \"true\" {\n\t\trevision += \"-dirty\"\n\t}\n\n\tif revision == \"\" {\n\t\trevision = \"unknown\"\n\t}\n\tif buildTime == \"\" {\n\t\tbuildTime = \"unknown\"\n\t}\n\n\treturn revision, buildTime\n}\n"], ["/container-use/cmd/container-use/agent/configure_goose.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mitchellh/go-homedir\"\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype ConfigureGoose struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureGoose() *ConfigureGoose {\n\treturn &ConfigureGoose{\n\t\tName: \"Goose\",\n\t\tDescription: \"an open source, extensible AI agent that goes beyond code suggestions\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureGoose) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureGoose) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureGoose) editMcpConfig() error {\n\tvar configPath string\n\tvar err error\n\n\tif runtime.GOOS == \"windows\" {\n\t\t// Windows: %APPDATA%\\Block\\goose\\config\\config.yaml\n\t\t// Reference: https://block.github.io/goose/docs/guides/config-file\n\t\tappData := os.Getenv(\"APPDATA\")\n\t\tif appData == \"\" {\n\t\t\treturn fmt.Errorf(\"APPDATA environment variable not set\")\n\t\t}\n\t\tconfigPath = filepath.Join(appData, \"Block\", \"goose\", \"config\", \"config.yaml\")\n\t} else {\n\t\t// macOS/Linux: ~/.config/goose/config.yaml\n\t\tconfigPath, err = homedir.Expand(filepath.Join(\"~\", \".config\", \"goose\", \"config.yaml\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config map[string]any\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := yaml.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t} else {\n\t\tconfig = make(map[string]any)\n\t}\n\n\tdata, err := a.updateGooseConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.WriteFile(configPath, data, 0644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureGoose) updateGooseConfig(config map[string]any) ([]byte, error) {\n\t// Get extensions map\n\tvar extensions map[string]any\n\tif ext, ok := config[\"extensions\"]; ok {\n\t\textensions = ext.(map[string]any)\n\t} else {\n\t\textensions = make(map[string]any)\n\t\tconfig[\"extensions\"] = extensions\n\t}\n\n\t// Add container-use extension\n\textensions[\"container-use\"] = map[string]any{\n\t\t\"name\": \"container-use\",\n\t\t\"type\": \"stdio\",\n\t\t\"enabled\": true,\n\t\t\"cmd\": ContainerUseBinary,\n\t\t\"args\": []any{\"stdio\"},\n\t\t\"envs\": map[string]any{},\n\t}\n\n\t// Write config back\n\tdata, err := yaml.Marshal(&config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureGoose) editRules() error {\n\treturn saveRulesFile(\".goosehints\", rules.AgentRules)\n}\n\nfunc (a *ConfigureGoose) isInstalled() bool {\n\t_, err := exec.LookPath(\"goose\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/completion_override.go", "package main\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar commandName string\n\nfunc init() {\n\t// Override cobra's default completion command\n\tcompletionCmd := &cobra.Command{\n\t\tUse: \"completion [bash|zsh|fish|powershell]\",\n\t\tShort: \"Generate the autocompletion script for the specified shell\",\n\t\tLong: `Generate the autocompletion script for container-use for the specified shell.\nSee each sub-command's help for details on how to use the generated script.\n\nUse --command-name to generate completions for a different command name (e.g., 'cu').`,\n\t\tDisableFlagsInUseLine: true,\n\t\tValidArgs: []string{\"bash\", \"zsh\", \"fish\", \"powershell\"},\n\t\tArgs: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn generateCompletionForBinary(args[0])\n\t\t},\n\t}\n\n\tcompletionCmd.PersistentFlags().StringVar(&commandName, \"command-name\", \"container-use\", \"Command name to use in completions\")\n\n\t// Add help subcommands that show usage instructions\n\tfor _, shell := range []string{\"bash\", \"zsh\", \"fish\", \"powershell\"} {\n\t\tshell := shell // capture loop variable\n\t\thelpCmd := &cobra.Command{\n\t\t\tUse: shell,\n\t\t\tShort: \"Generate the autocompletion script for \" + shell,\n\t\t\tLong: generateHelpText(shell),\n\t\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t\treturn generateCompletionForBinary(shell)\n\t\t\t},\n\t\t}\n\t\tcompletionCmd.AddCommand(helpCmd)\n\t}\n\n\trootCmd.AddCommand(completionCmd)\n}\n\nfunc generateCompletionForBinary(shell string) error {\n\ttempRootCmd := &cobra.Command{\n\t\tUse: commandName,\n\t\tShort: rootCmd.Short,\n\t\tLong: rootCmd.Long,\n\t}\n\n\tfor _, subCmd := range rootCmd.Commands() {\n\t\tif subCmd.Name() != \"completion\" {\n\t\t\ttempRootCmd.AddCommand(subCmd)\n\t\t}\n\t}\n\n\tswitch shell {\n\tcase \"bash\":\n\t\treturn tempRootCmd.GenBashCompletion(os.Stdout)\n\tcase \"zsh\":\n\t\treturn tempRootCmd.GenZshCompletion(os.Stdout)\n\tcase \"fish\":\n\t\treturn tempRootCmd.GenFishCompletion(os.Stdout, true)\n\tcase \"powershell\":\n\t\treturn tempRootCmd.GenPowerShellCompletion(os.Stdout)\n\t}\n\treturn nil\n}\n\nfunc generateHelpText(shell string) string {\n\t// Generate help text dynamically based on the shell\n\t// This reduces duplication of the static help text\n\ttemplates := map[string]string{\n\t\t\"bash\": `Generate the autocompletion script for the bash shell.\n\nThis script depends on the 'bash-completion' package.\nIf it is not installed already, you can install it via your OS's package manager.\n\nTo load completions in your current shell session:\n\tsource <({{.command}} completion bash)\n\nTo load completions for every new session, save the output to your bash completion directory.\nCommon locations include:\n - Linux: /usr/local/etc/bash_completion.d/{{.command}}\n - macOS: $(brew --prefix)/etc/bash_completion.d/{{.command}}\n - Windows (Git Bash): /usr/share/bash-completion/completions/{{.command}}\n\nExample:\n\t{{.command}} completion bash > /path/to/bash_completion.d/{{.command}}`,\n\n\t\t\"zsh\": `Generate the autocompletion script for the zsh shell.\n\nIf shell completion is not already enabled in your environment,\nyou will need to enable it. You can execute the following once:\n\techo \"autoload -U compinit; compinit\" >> ~/.zshrc\n\nTo load completions in your current shell session:\n\tsource <({{.command}} completion zsh)\n\nTo load completions for every new session, save the output to your zsh completion directory.\nCommon locations include:\n - Linux: /usr/local/share/zsh/site-functions/_{{.command}}\n - macOS: $(brew --prefix)/share/zsh/site-functions/_{{.command}}\n - Custom: Any directory in your $fpath\n\nExample:\n\t{{.command}} completion zsh > /path/to/zsh/site-functions/_{{.command}}`,\n\n\t\t\"fish\": `Generate the autocompletion script for the fish shell.\n\nTo load completions in your current shell session:\n\t{{.command}} completion fish | source\n\nTo load completions for every new session, save the output to your fish completion directory.\nCommon locations include:\n - Linux/macOS: ~/.config/fish/completions/{{.command}}.fish\n - Windows: %APPDATA%\\fish\\completions\\{{.command}}.fish\n\nExample:\n\t{{.command}} completion fish > ~/.config/fish/completions/{{.command}}.fish`,\n\n\t\t\"powershell\": `Generate the autocompletion script for PowerShell.\n\nTo load completions in your current shell session:\n\t{{.command}} completion powershell | Out-String | Invoke-Expression\n\nTo load completions for every new session, add the output to your PowerShell profile.\nCommon profile locations include:\n - Windows: $PROFILE (usually %USERPROFILE%\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1)\n - Linux/macOS: ~/.config/powershell/Microsoft.PowerShell_profile.ps1\n\nExample:\n\t{{.command}} completion powershell >> $PROFILE\n\nNote: You may need to create the profile file if it doesn't exist.`,\n\t}\n\n\ttemplate := templates[shell]\n\treturn strings.ReplaceAll(template, \"{{.command}}\", commandName)\n}\n"], ["/container-use/cmd/container-use/log.go", "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar logCmd = &cobra.Command{\n\tUse: \"log []\",\n\tShort: \"View what an agent did step-by-step\",\n\tLong: `Display the complete development history for an environment.\nShows all commits made by the agent plus command execution notes.\nUse -p to include code patches in the output.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# See what agent did\ncontainer-use log fancy-mallard\n\n# Include code changes\ncontainer-use log fancy-mallard -p\n\n# Auto-select environment\ncontainer-use log`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpatch, _ := app.Flags().GetBool(\"patch\")\n\n\t\treturn repo.Log(ctx, envID, patch, os.Stdout)\n\t},\n}\n\nfunc init() {\n\tlogCmd.Flags().BoolP(\"patch\", \"p\", false, \"Generate patch\")\n\trootCmd.AddCommand(logCmd)\n}\n"], ["/container-use/cmd/container-use/stdio.go", "package main\n\nimport (\n\t\"log/slog\"\n\t\"os\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/mcpserver\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar stdioCmd = &cobra.Command{\n\tUse: \"stdio\",\n\tShort: \"Start MCP server for agent integration\",\n\tLong: `Start the Model Context Protocol server that enables AI agents to create and manage containerized environments. This is typically used by agents like Claude Code, Cursor, or VSCode.`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\tslog.Info(\"connecting to dagger\")\n\n\t\tdag, err := dagger.Connect(ctx, dagger.WithLogOutput(logWriter))\n\t\tif err != nil {\n\t\t\tslog.Error(\"Error starting dagger\", \"error\", err)\n\n\t\t\tif isDockerDaemonError(err) {\n\t\t\t\thandleDockerDaemonError()\n\t\t\t}\n\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer dag.Close()\n\n\t\treturn mcpserver.RunStdioServer(ctx, dag)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(stdioCmd)\n}\n"], ["/container-use/cmd/container-use/agent/configure_codex.go", "package agent\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n\t\"github.com/mitchellh/go-homedir\"\n\t\"github.com/pelletier/go-toml/v2\"\n)\n\ntype ConfigureCodex struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureCodex() *ConfigureCodex {\n\treturn &ConfigureCodex{\n\t\tName: \"OpenAI Codex\",\n\t\tDescription: \"OpenAI's lightweight coding agent that runs in your terminal\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureCodex) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureCodex) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureCodex) editMcpConfig() error {\n\tconfigPath, err := homedir.Expand(filepath.Join(\"~\", \".codex\", \"config.toml\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config map[string]any\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := toml.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t} else {\n\t\tconfig = make(map[string]any)\n\t}\n\n\tdata, err := a.updateCodexConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureCodex) updateCodexConfig(config map[string]any) ([]byte, error) {\n\t// Get mcp_servers map\n\tvar mcpServers map[string]any\n\tif servers, ok := config[\"mcp_servers\"]; ok {\n\t\tmcpServers = servers.(map[string]any)\n\t} else {\n\t\tmcpServers = make(map[string]any)\n\t\tconfig[\"mcp_servers\"] = mcpServers\n\t}\n\n\t// Add container-use server\n\tmcpServers[\"container-use\"] = map[string]any{\n\t\t\"command\": ContainerUseBinary,\n\t\t\"args\": []any{\"stdio\"},\n\t\t\"auto_approve\": tools(\"\"),\n\t}\n\n\t// Write config back\n\tdata, err := toml.Marshal(&config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureCodex) editRules() error {\n\tagentsFile := \"AGENTS.md\"\n\treturn saveRulesFile(agentsFile, rules.AgentRules)\n}\n\nfunc (a *ConfigureCodex) isInstalled() bool {\n\t_, err := exec.LookPath(\"codex\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/agent/configure_claude.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureClaude struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureClaude() *ConfigureClaude {\n\treturn &ConfigureClaude{\n\t\tName: \"Claude Code\",\n\t\tDescription: \"Anthropic's Claude Code\",\n\t}\n}\n\ntype ClaudeSettingsLocal struct {\n\tPermissions *ClaudePermissions `json:\"permissions,omitempty\"`\n\tEnv map[string]string `json:\"env,omitempty\"`\n}\n\ntype ClaudePermissions struct {\n\tAllow []string `json:\"allow,omitempty\"`\n\tDeny []string `json:\"deny,omitempty\"`\n}\n\nfunc (c *ConfigureClaude) name() string {\n\treturn c.Name\n}\n\nfunc (c *ConfigureClaude) description() string {\n\treturn c.Description\n}\n\nfunc (c *ConfigureClaude) editMcpConfig() error {\n\t// Add MCP server\n\tcmd := exec.Command(\"claude\", \"mcp\", \"add\", \"container-use\", \"--\", ContainerUseBinary, \"stdio\")\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not automatically add MCP server: %w\", err)\n\t}\n\n\t// Configure auto approve settings\n\tconfigPath := filepath.Join(\".claude\", \"settings.local.json\")\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\tvar config ClaudeSettingsLocal\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := c.updateSettingsLocal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (c *ConfigureClaude) updateSettingsLocal(config ClaudeSettingsLocal) ([]byte, error) {\n\t// Initialize permissions map if nil\n\tif config.Permissions == nil {\n\t\tconfig.Permissions = &ClaudePermissions{Allow: []string{}}\n\t}\n\n\t// remove save non-container-use items from allow\n\tallows := []string{}\n\tfor _, tool := range config.Permissions.Allow {\n\t\tif !strings.HasPrefix(tool, \"mcp__container-use\") {\n\t\t\tallows = append(allows, tool)\n\t\t}\n\t}\n\n\t// Add container-use tools to allow\n\ttools := tools(\"mcp__container-use__\")\n\tallows = append(allows, tools...)\n\tconfig.Permissions.Allow = allows\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\nfunc (c *ConfigureClaude) editRules() error {\n\treturn saveRulesFile(\"CLAUDE.md\", rules.AgentRules)\n}\n\nfunc (c *ConfigureClaude) isInstalled() bool {\n\t_, err := exec.LookPath(\"claude\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/agent/configure_cursor.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureCursor struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureCursor() *ConfigureCursor {\n\treturn &ConfigureCursor{\n\t\tName: \"Cursor\",\n\t\tDescription: \"AI-powered code editor\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureCursor) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureCursor) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureCursor) editMcpConfig() error {\n\tconfigPath := filepath.Join(\".cursor\", \"mcp.json\")\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config MCPServersConfig\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := a.updateMcpConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureCursor) updateMcpConfig(config MCPServersConfig) ([]byte, error) {\n\t// Initialize mcpServers map if nil\n\tif config.MCPServers == nil {\n\t\tconfig.MCPServers = make(map[string]MCPServer)\n\t}\n\n\t// Add container-use server\n\tconfig.MCPServers[\"container-use\"] = MCPServer{\n\t\tCommand: ContainerUseBinary,\n\t\tArgs: []string{\"stdio\"},\n\t}\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureCursor) editRules() error {\n\trulesFile := filepath.Join(\".cursor\", \"rules\", \"container-use.mdc\")\n\treturn saveRulesFile(rulesFile, rules.CursorRules)\n}\n\nfunc (a *ConfigureCursor) isInstalled() bool {\n\treturn true\n}\n"], ["/container-use/cmd/container-use/agent/configure_q.go", "package agent\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/dagger/container-use/rules\"\n)\n\ntype ConfigureQ struct {\n\tName string\n\tDescription string\n}\n\nfunc NewConfigureQ() *ConfigureQ {\n\treturn &ConfigureQ{\n\t\tName: \"Amazon Q Developer\",\n\t\tDescription: \"Amazon's agentic chat experience in your terminal\",\n\t}\n}\n\n// Return the agents full name\nfunc (a *ConfigureQ) name() string {\n\treturn a.Name\n}\n\n// Return a description of the agent\nfunc (a *ConfigureQ) description() string {\n\treturn a.Description\n}\n\n// Save the MCP config with container-use enabled\nfunc (a *ConfigureQ) editMcpConfig() error {\n\tconfigPath := filepath.Join(\".amazonq\", \"mcp.json\")\n\n\t// Create directory if it doesn't exist\n\tif err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create config directory: %w\", err)\n\t}\n\n\t// Read existing config or create new\n\tvar config MCPServersConfig\n\tif data, err := os.ReadFile(configPath); err == nil {\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse existing config: %w\", err)\n\t\t}\n\t}\n\n\tdata, err := a.updateMcpConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(configPath, data, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write config: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *ConfigureQ) updateMcpConfig(config MCPServersConfig) ([]byte, error) {\n\t// Initialize mcpServers map if nil\n\tif config.MCPServers == nil {\n\t\tconfig.MCPServers = make(map[string]MCPServer)\n\t}\n\n\t// Add container-use server\n\tconfig.MCPServers[\"container-use\"] = MCPServer{\n\t\tCommand: ContainerUseBinary,\n\t\tArgs: []string{\"stdio\"},\n\t\tEnv: map[string]string{},\n\t\tTimeout: &[]int{60000}[0],\n\t}\n\n\t// Write config back\n\tdata, err := json.MarshalIndent(config, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn data, nil\n}\n\n// Save the agent rules with the container-use prompt\nfunc (a *ConfigureQ) editRules() error {\n\treturn saveRulesFile(\".amazonq/rules/container-use.md\", rules.AgentRules)\n}\n\nfunc (a *ConfigureQ) isInstalled() bool {\n\t_, err := exec.LookPath(\"q\")\n\treturn err == nil\n}\n"], ["/container-use/cmd/container-use/main.go", "package main\n\nimport (\n\t\"context\"\n\t_ \"embed\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/fang\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\trootCmd = &cobra.Command{\n\t\tUse: \"container-use\",\n\t\tShort: \"Containerized environments for coding agents\",\n\t\tLong: `Container Use creates isolated development environments for AI agents.\nEach environment runs in its own container with dedicated git branches.`,\n\t}\n)\n\nfunc main() {\n\tctx := context.Background()\n\tsetupSignalHandling()\n\n\tif err := setupLogger(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to setup logger: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// FIXME(aluzzardi): `fang` misbehaves with the `stdio` command.\n\t// It hangs on Ctrl-C. Traced the hang back to `lipgloss.HasDarkBackground(os.Stdin, os.Stdout)`\n\t// I'm assuming it's not playing nice the mcpserver listening on stdio.\n\tif len(os.Args) > 1 && os.Args[1] == \"stdio\" {\n\t\tif err := rootCmd.ExecuteContext(ctx); err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n\n\tif err := fang.Execute(\n\t\tctx,\n\t\trootCmd,\n\t\tfang.WithVersion(version),\n\t\tfang.WithCommit(commit),\n\t\tfang.WithNotifySignal(getNotifySignals()...),\n\t); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc suggestEnvironments(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tctx := cmd.Context()\n\n\trepo, err := repository.Open(ctx, \".\")\n\tif err != nil {\n\t\treturn nil, cobra.ShellCompDirectiveError\n\t}\n\n\tenvs, err := repo.List(ctx)\n\tif err != nil {\n\t\treturn nil, cobra.ShellCompDirectiveError\n\t}\n\n\tids := []string{}\n\tfor _, e := range envs {\n\t\tids = append(ids, e.ID)\n\t}\n\treturn ids, cobra.ShellCompDirectiveKeepOrder\n}\n"], ["/container-use/cmd/container-use/docker_errors.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\n// isDockerDaemonError checks if the error is related to Docker daemon connectivity\nfunc isDockerDaemonError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\terrStr := strings.ToLower(err.Error())\n\n\t// Linux: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\n\tif strings.Contains(errStr, \"cannot connect to the docker daemon\") {\n\t\treturn true\n\t}\n\n\t// Windows: error during connect: Get \"http://%2F%2F.%2Fpipe%2FdockerDesktopLinuxEngine/v1.51/containers/json\": open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified.\n\tif strings.Contains(errStr, \"error during connect\") && strings.Contains(errStr, \"pipe/dockerdesktoplinuxengine\") && strings.Contains(errStr, \"the system cannot find the file specified\") {\n\t\treturn true\n\t}\n\n\t// macOS: request returned 500 Internal Server Error for API route and version http://%2FUsers%2Fb1tank%2F.docker%2Frun%2Fdocker.sock/v1.50/containers/json, check if the server supports the requested API version\n\tif strings.Contains(errStr, \"request returned 500 internal server error\") && strings.Contains(errStr, \"docker.sock\") && strings.Contains(errStr, \"check if the server supports the requested api version\") {\n\t\treturn true\n\t}\n\n\t// Generic fallbacks\n\treturn strings.Contains(errStr, \"docker daemon\") ||\n\t\tstrings.Contains(errStr, \"docker.sock\")\n}\n\n// handleDockerDaemonError prints a helpful error message for Docker daemon issues\nfunc handleDockerDaemonError() {\n\tfmt.Fprintf(os.Stderr, \"\\nError: Docker daemon is not running.\\n\")\n\tfmt.Fprintf(os.Stderr, \"Please start Docker and try again.\\n\\n\")\n}\n"], ["/container-use/cmd/container-use/terminal.go", "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"dagger.io/dagger\"\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar terminalCmd = &cobra.Command{\n\tUse: \"terminal []\",\n\tShort: \"Get a shell inside an environment's container\",\n\tLong: `Open an interactive terminal in the exact container environment the agent used. Perfect for debugging, testing, or hands-on exploration.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Drop into environment's container\ncontainer-use terminal fancy-mallard\n\n# Debug agent's work interactively\ncontainer-use terminal backend-api\n\n# Auto-select environment\ncontainer-use terminal`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// FIXME(aluzzardi): This is a hack to make sure we're wrapped in `dagger run` since `Terminal()` only works with the CLI.\n\t\t// If not, it will auto-wrap this command in a `dagger run`.\n\t\tif _, ok := os.LookupEnv(\"DAGGER_SESSION_TOKEN\"); !ok {\n\t\t\tdaggerBin, err := exec.LookPath(\"dagger\")\n\t\t\tif err != nil {\n\t\t\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\t\t\treturn fmt.Errorf(\"dagger is not installed. Please install it from https://docs.dagger.io/install/\")\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"failed to look up dagger binary: %w\", err)\n\t\t\t}\n\t\t\treturn execDaggerRun(daggerBin, append([]string{\"dagger\", \"run\"}, os.Args...), os.Environ())\n\t\t}\n\n\t\tdag, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr))\n\t\tif err != nil {\n\t\t\tif isDockerDaemonError(err) {\n\t\t\t\thandleDockerDaemonError()\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to connect to dagger: %w\", err)\n\t\t}\n\t\tdefer dag.Close()\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenv, err := repo.Get(ctx, dag, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn env.Terminal(ctx)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(terminalCmd)\n}\n"], ["/container-use/cmd/container-use/delete.go", "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar deleteCmd = &cobra.Command{\n\tUse: \"delete [...]\",\n\tShort: \"Delete environments and start fresh\",\n\tLong: `Delete one or more environments and their associated resources.\nThis permanently removes the environment's branch and container state.\nUse this when starting over with a different approach.\n\nUse --all to delete all environments at once.`,\n\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\tall, _ := cmd.Flags().GetBool(\"all\")\n\t\tif all && len(args) > 0 {\n\t\t\treturn fmt.Errorf(\"cannot specify environment names when using --all flag\")\n\t\t}\n\t\tif !all && len(args) == 0 {\n\t\t\treturn fmt.Errorf(\"must specify at least one environment name or use --all flag\")\n\t\t}\n\t\treturn nil\n\t},\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Delete a single environment\ncontainer-use delete fancy-mallard\n\n# Delete multiple environments at once\ncontainer-use delete env1 env2 env3\n\n# Delete all environments\ncontainer-use delete --all`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tctx := cmd.Context()\n\t\tall, _ := cmd.Flags().GetBool(\"all\")\n\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open repository: %w\", err)\n\t\t}\n\n\t\tvar envIDs []string\n\t\tif all {\n\t\t\t// Get all environment IDs\n\t\t\tenvs, err := repo.List(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to list environments: %w\", err)\n\t\t\t}\n\t\t\tif len(envs) == 0 {\n\t\t\t\tfmt.Println(\"No environments found to delete.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor _, env := range envs {\n\t\t\t\tenvIDs = append(envIDs, env.ID)\n\t\t\t}\n\t\t\tfmt.Printf(\"Deleting %d environment(s)...\\n\", len(envIDs))\n\t\t} else {\n\t\t\tenvIDs = args\n\t\t}\n\n\t\tfor _, envID := range envIDs {\n\t\t\tif err := repo.Delete(ctx, envID); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete environment '%s': %w\", envID, err)\n\t\t\t}\n\t\t\tfmt.Printf(\"Environment '%s' deleted successfully.\\n\", envID)\n\t\t}\n\n\t\tif all {\n\t\t\tfmt.Printf(\"Successfully deleted %d environment(s).\\n\", len(envIDs))\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(deleteCmd)\n\tdeleteCmd.Flags().Bool(\"all\", false, \"Delete all environments\")\n}\n"], ["/container-use/environment/service.go", "package environment\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"dagger.io/dagger\"\n)\n\nvar (\n\tserviceStartTimeout = 30 * time.Second\n)\n\ntype Service struct {\n\tConfig *ServiceConfig `json:\"config\"`\n\tEndpoints EndpointMappings `json:\"endpoints\"`\n\n\tsvc *dagger.Service\n}\n\ntype EndpointMapping struct {\n\tEnvironmentInternal string `json:\"environment_internal\"`\n\tHostExternal string `json:\"host_external\"`\n}\n\ntype EndpointMappings map[int]*EndpointMapping\n\nfunc (env *Environment) startServices(ctx context.Context) ([]*Service, error) {\n\tservices := []*Service{}\n\tfor _, cfg := range env.State.Config.Services {\n\t\tservice, err := env.startService(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservices = append(services, service)\n\t}\n\treturn services, nil\n}\n\nfunc (env *Environment) startService(ctx context.Context, cfg *ServiceConfig) (*Service, error) {\n\tcontainer := env.dag.Container().From(cfg.Image)\n\tcontainer, err := containerWithEnvAndSecrets(env.dag, container, cfg.Env, env.State.Config.Secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.Command != \"\" {\n\t\tcontainer = container.WithExec([]string{\"sh\", \"-c\", cfg.Command})\n\t}\n\n\targs := []string{}\n\tif cfg.Command != \"\" {\n\t\targs = []string{\"sh\", \"-c\", cfg.Command}\n\t}\n\n\t// Expose ports\n\tfor _, port := range cfg.ExposedPorts {\n\t\tcontainer = container.WithExposedPort(port, dagger.ContainerWithExposedPortOpts{\n\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\tDescription: fmt.Sprintf(\"Port %d\", port),\n\t\t})\n\t}\n\n\t// Start the service\n\tstartCtx, cancel := context.WithTimeout(ctx, serviceStartTimeout)\n\tdefer cancel()\n\tsvc, err := container.AsService(dagger.ContainerAsServiceOpts{\n\t\tArgs: args,\n\t\tUseEntrypoint: true,\n\t}).Start(startCtx)\n\tif err != nil {\n\t\tvar exitErr *dagger.ExecError\n\t\tif errors.As(err, &exitErr) {\n\t\t\treturn nil, fmt.Errorf(\"command failed with exit code %d.\\nstdout: %s\\nstderr: %s\", exitErr.ExitCode, exitErr.Stdout, exitErr.Stderr)\n\t\t}\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\treturn nil, fmt.Errorf(\"service failed to start within %s timeout\", serviceStartTimeout)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tendpoints := EndpointMappings{}\n\tfor _, port := range cfg.ExposedPorts {\n\t\tendpoint := &EndpointMapping{\n\t\t\tEnvironmentInternal: fmt.Sprintf(\"tcp://%s:%d\", cfg.Name, port),\n\t\t}\n\t\tendpoints[port] = endpoint\n\n\t\t// Expose ports on the host\n\t\ttunnel, err := env.dag.Host().Tunnel(svc, dagger.HostTunnelOpts{\n\t\t\tPorts: []dagger.PortForward{\n\t\t\t\t{\n\t\t\t\t\tBackend: port,\n\t\t\t\t\tFrontend: 0,\n\t\t\t\t\tProtocol: dagger.NetworkProtocolTcp,\n\t\t\t\t},\n\t\t\t},\n\t\t}).Start(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texternalEndpoint, err := tunnel.Endpoint(ctx, dagger.ServiceEndpointOpts{\n\t\t\tScheme: \"tcp\",\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get endpoint for service %s: %w\", cfg.Name, err)\n\t\t}\n\t\tendpoint.HostExternal = externalEndpoint\n\t}\n\n\treturn &Service{\n\t\tConfig: cfg,\n\t\tEndpoints: endpoints,\n\t\tsvc: svc,\n\t}, nil\n}\n\nfunc (env *Environment) AddService(ctx context.Context, explanation string, cfg *ServiceConfig) (*Service, error) {\n\tif env.State.Config.Services.Get(cfg.Name) != nil {\n\t\treturn nil, fmt.Errorf(\"service %s already exists\", cfg.Name)\n\t}\n\tsvc, err := env.startService(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv.State.Config.Services = append(env.State.Config.Services, cfg)\n\tenv.Services = append(env.Services, svc)\n\n\tstate := env.container().WithServiceBinding(cfg.Name, svc.svc)\n\tif err := env.apply(ctx, state); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv.Notes.Add(\"Add service %s\\n%s\\n\\n\", cfg.Name, explanation)\n\n\treturn svc, nil\n}\n"], ["/container-use/cmd/container-use/env_selection.go", "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/huh\"\n\t\"github.com/dagger/container-use/environment\"\n\t\"github.com/dagger/container-use/repository\"\n)\n\n// resolveEnvironmentID resolves the environment ID for commands that take env_id as the only positional argument.\n// If no args are provided, it filters environments to those where the local repo head is a parent of the environment's head,\n// then either auto-selects if there's only one match or prompts the user to select from multiple options.\nfunc resolveEnvironmentID(ctx context.Context, repo *repository.Repository, args []string) (string, error) {\n\tif len(args) == 1 {\n\t\treturn args[0], nil\n\t}\n\tif len(args) > 1 {\n\t\treturn \"\", errors.New(\"too many arguments\")\n\t}\n\n\t// Get current user repo head - this could easily go inside ListDescendantEnvironments, but keeping it outside simplifies testing\n\tcurrentHead, err := repository.RunGitCommand(ctx, repo.SourcePath(), \"rev-parse\", \"HEAD\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get current HEAD: %w\", err)\n\t}\n\tcurrentHead = strings.TrimSpace(currentHead)\n\n\t// Get environments that are descendants of current HEAD\n\tfilteredEnvs, err := repo.ListDescendantEnvironments(ctx, currentHead)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to list descendant environments: %w\", err)\n\t}\n\n\tif len(filteredEnvs) == 0 {\n\t\treturn \"\", errors.New(\"no environments found that are descendants of the current HEAD\")\n\t}\n\n\t// If only one environment matches, use it\n\tif len(filteredEnvs) == 1 {\n\t\treturn filteredEnvs[0].ID, nil\n\t}\n\n\t// Multiple environments - prompt user to select\n\treturn promptForEnvironmentSelection(filteredEnvs)\n}\n\n// promptForEnvironmentSelection prompts the user to select from multiple environments\nfunc promptForEnvironmentSelection(envs []*environment.EnvironmentInfo) (string, error) {\n\tvar options []huh.Option[string]\n\n\tfor _, env := range envs {\n\t\ttitle := env.State.Title\n\t\tif title == \"\" {\n\t\t\ttitle = \"No description\"\n\t\t}\n\n\t\tlabel := fmt.Sprintf(\"%s - %s\", env.ID, title)\n\t\toptions = append(options, huh.NewOption(label, env.ID))\n\t}\n\n\tvar selectedID string\n\tprompt := huh.NewSelect[string]().\n\t\tTitle(\"Select an environment:\").\n\t\tOptions(options...).\n\t\tValue(&selectedID)\n\n\tif err := prompt.Run(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn selectedID, nil\n}\n"], ["/container-use/cmd/container-use/watch_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"time\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n\twatch \"github.com/tiborvass/go-watch\"\n)\n\nvar watchCmd = &cobra.Command{\n\tUse: \"watch\",\n\tShort: \"Watch environment activity in real-time\",\n\tLong: `Continuously display environment activity as agents work.\nShows new commits and environment changes updated every second.\nPress Ctrl+C to stop watching.`,\n\tExample: `# Watch all environment activity\ncontainer-use watch\n\n# Monitor agents while they work\ncontainer-use watch`,\n\tRunE: func(app *cobra.Command, _ []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\tif _, err := repository.Open(ctx, \".\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tw := watch.Watcher{Interval: time.Second}\n\t\tw.Watch(app.Context(), \"git\", \"log\", \"--color=always\", \"--remotes=container-use\", \"--oneline\", \"--graph\", \"--decorate\")\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(watchCmd)\n}\n"], ["/container-use/cmd/container-use/signal_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nfunc setupSignalHandling() {\n\tsigusrCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigusrCh, syscall.SIGUSR1)\n\tgo handleSIGUSR(sigusrCh)\n}\n\nfunc handleSIGUSR(sigusrCh <-chan os.Signal) {\n\tfor sig := range sigusrCh {\n\t\tif sig == syscall.SIGUSR1 {\n\t\t\tdumpStacks()\n\t\t}\n\t}\n}\n\nfunc dumpStacks() {\n\tbuf := make([]byte, 1<<20) // 1MB buffer\n\tn := runtime.Stack(buf, true)\n\tio.MultiWriter(logWriter, os.Stderr).Write(buf[:n])\n}\n"], ["/container-use/environment/state.go", "package environment\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype State struct {\n\tCreatedAt time.Time `json:\"created_at,omitempty\"`\n\tUpdatedAt time.Time `json:\"updated_at,omitempty\"`\n\n\tConfig *EnvironmentConfig `json:\"config,omitempty\"`\n\tContainer string `json:\"container,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n}\n\nfunc (s *State) Marshal() ([]byte, error) {\n\treturn json.MarshalIndent(s, \"\", \" \")\n}\n\nfunc (s *State) Unmarshal(data []byte) error {\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\t// Try to migrate the legacy state\n\t\tlegacySt, err := migrateLegacyState(data)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load state: %w\", err)\n\t\t}\n\t\t*s = *legacySt\n\t}\n\treturn nil\n}\n\nfunc migrateLegacyState(state []byte) (*State, error) {\n\tvar history legacyState\n\tif err := json.Unmarshal(state, &history); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load state: %w\", err)\n\t}\n\tlatest := history.Latest()\n\tif latest == nil {\n\t\treturn nil, fmt.Errorf(\"no latest revision found\")\n\t}\n\n\treturn &State{\n\t\tContainer: latest.State,\n\t\tCreatedAt: latest.CreatedAt,\n\t\tUpdatedAt: latest.CreatedAt,\n\t}, nil\n}\n\ntype legacyState []*legacyRevision\n\nfunc (h legacyState) Latest() *legacyRevision {\n\tif len(h) == 0 {\n\t\treturn nil\n\t}\n\treturn h[len(h)-1]\n}\n\nfunc (h legacyState) LatestVersion() int {\n\tlatest := h.Latest()\n\tif latest == nil {\n\t\treturn 0\n\t}\n\treturn latest.Version\n}\n\nfunc (h legacyState) Get(version int) *legacyRevision {\n\tfor _, revision := range h {\n\t\tif revision.Version == version {\n\t\t\treturn revision\n\t\t}\n\t}\n\treturn nil\n}\n\ntype legacyRevision struct {\n\tVersion int `json:\"version\"`\n\tName string `json:\"name\"`\n\tExplanation string `json:\"explanation\"`\n\tOutput string `json:\"output,omitempty\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n\tState string `json:\"state\"`\n}\n"], ["/container-use/cmd/container-use/merge.go", "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tmergeDelete bool\n)\n\nvar mergeCmd = &cobra.Command{\n\tUse: \"merge []\",\n\tShort: \"Accept an environment's work into your branch\",\n\tLong: `Merge an environment's changes into your current git branch.\nThis makes the agent's work permanent in your repository.\nYour working directory will be automatically stashed and restored.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Accept agent's work into current branch\ncontainer-use merge backend-api\n\n# Merge and delete the environment after successful merge\ncontainer-use merge -d backend-api\ncontainer-use merge --delete backend-api\n\n# Auto-select environment\ncontainer-use merge`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := repo.Merge(ctx, envID, os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge environment: %w\", err)\n\t\t}\n\n\t\treturn deleteAfterMerge(ctx, repo, envID, mergeDelete, \"merged\")\n\t},\n}\n\nfunc deleteAfterMerge(ctx context.Context, repo *repository.Repository, env string, delete bool, verb string) error {\n\tif !delete {\n\t\tfmt.Printf(\"Environment '%s' %s successfully.\\n\", env, verb)\n\t\treturn nil\n\t}\n\tif err := repo.Delete(ctx, env); err != nil {\n\t\treturn fmt.Errorf(\"environment '%s' %s but delete failed: %w\", env, verb, err)\n\t}\n\tfmt.Printf(\"Environment '%s' %s and deleted successfully.\\n\", env, verb)\n\treturn nil\n}\n\nfunc init() {\n\tmergeCmd.Flags().BoolVarP(&mergeDelete, \"delete\", \"d\", false, \"Delete the environment after successful merge\")\n\n\trootCmd.AddCommand(mergeCmd)\n}\n"], ["/container-use/cmd/container-use/terminal_windows.go", "//go:build windows\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc execDaggerRun(daggerBin string, args []string, env []string) error {\n\tcmd := exec.Command(daggerBin, args...)\n\tcmd.Args = append([]string{\"dagger\", \"run\"}, os.Args...)\n\tcmd.Env = env\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"failed to execute dagger run: %w\", err)\n\t}\n\n\t// On Windows, we can't replace the current process, so we exit\n\tos.Exit(0)\n\treturn nil\n}\n"], ["/container-use/cmd/container-use/apply.go", "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tapplyDelete bool\n)\n\nvar applyCmd = &cobra.Command{\n\tUse: \"apply []\",\n\tShort: \"Apply an environment's work as staged changes to your branch\",\n\tLong: `Apply an environment's changes to your current git branch as staged modifications.\nUnlike 'merge' which preserves the original commit history, 'apply' stages all changes\nfor you to commit manually, discarding the original commit sequence. This lets you\nreview and customize the final commit before making the agent's work permanent.\nYour working directory will be automatically stashed and restored.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Apply agent's work as staged changes to current branch\ncu apply backend-api\n\n# Apply and delete the environment after successful application\ncu apply -d backend-api\ncu apply --delete backend-api\n\n# After applying, you can review and commit the changes\ngit status\ngit commit -m \"Add backend API implementation\"\n\n# Auto-select environment\ncu apply`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := repo.Apply(ctx, envID, os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply environment: %w\", err)\n\t\t}\n\n\t\treturn deleteAfterMerge(ctx, repo, envID, applyDelete, \"applied\")\n\t},\n}\n\nfunc init() {\n\tapplyCmd.Flags().BoolVarP(&applyDelete, \"delete\", \"d\", false, \"Delete the environment after successful application\")\n\n\trootCmd.AddCommand(applyCmd)\n}\n"], ["/container-use/cmd/container-use/checkout.go", "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar checkoutCmd = &cobra.Command{\n\tUse: \"checkout []\",\n\tShort: \"Switch to an environment's branch locally\",\n\tLong: `Bring an environment's work into your local git workspace.\nThis creates a local branch from the environment's state so you can\nexplore files in your IDE, make changes, or continue development.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# Switch to environment's branch locally\ncontainer-use checkout fancy-mallard\n\n# Create custom branch name\ncontainer-use checkout fancy-mallard -b my-review-branch\n\n# Auto-select environment\ncontainer-use checkout`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbranchName, err := app.Flags().GetString(\"branch\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbranch, err := repo.Checkout(ctx, envID, branchName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"Switched to branch '%s'\\n\", branch)\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\tcheckoutCmd.Flags().StringP(\"branch\", \"b\", \"\", \"Local branch name to use\")\n\trootCmd.AddCommand(checkoutCmd)\n}\n"], ["/container-use/cmd/container-use/inspect.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar inspectCmd = &cobra.Command{\n\tUse: \"inspect []\",\n\tShort: \"Inspect an environment\",\n\tLong: \"This is an internal command used by the CLI to inspect an environment. It is not meant to be used by users.\",\n\tArgs: cobra.MaximumNArgs(1),\n\tHidden: true,\n\tValidArgsFunction: suggestEnvironments,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvInfo, err := repo.Info(ctx, envID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvInfo.State.Container = \"\"\n\t\tout, err := json.MarshalIndent(envInfo, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(string(out))\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(inspectCmd)\n}\n"], ["/container-use/environment/note.go", "package environment\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype Notes struct {\n\titems []string\n\tmu sync.Mutex\n}\n\nfunc (n *Notes) Add(format string, a ...any) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tn.items = append(n.items, fmt.Sprintf(format, a...))\n}\n\nfunc (n *Notes) AddCommand(command string, exitCode int, stdout, stderr string) {\n\tmsg := fmt.Sprintf(\"$ %s\", strings.TrimSpace(command))\n\tif exitCode != 0 {\n\t\tmsg += fmt.Sprintf(\"\\nexit %d\", exitCode)\n\t}\n\tif strings.TrimSpace(stdout) != \"\" {\n\t\tmsg += fmt.Sprintf(\"\\n%s\", stdout)\n\t}\n\tif strings.TrimSpace(stderr) != \"\" {\n\t\tmsg += fmt.Sprintf(\"\\nstderr: %s\", stderr)\n\t}\n\n\tn.Add(\"%s\", msg)\n}\n\nfunc (n *Notes) Clear() {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tn.items = []string{}\n}\n\nfunc (n *Notes) String() string {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\treturn strings.TrimSpace(strings.Join(n.items, \"\\n\"))\n}\n\nfunc (n *Notes) Pop() string {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tout := strings.TrimSpace(strings.Join(n.items, \"\\n\"))\n\tn.items = []string{}\n\n\treturn out\n}\n"], ["/container-use/cmd/container-use/diff.go", "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/dagger/container-use/repository\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar diffCmd = &cobra.Command{\n\tUse: \"diff []\",\n\tShort: \"Show what files an agent changed\",\n\tLong: `Display the code changes made by an agent in an environment.\nShows a git diff between the environment's state and your current branch.\n\nIf no environment is specified, automatically selects from environments \nthat are descendants of the current HEAD.`,\n\tArgs: cobra.MaximumNArgs(1),\n\tValidArgsFunction: suggestEnvironments,\n\tExample: `# See what changes the agent made\ncontainer-use diff fancy-mallard\n\n# Quick assessment before merging\ncontainer-use diff backend-api\n\n# Auto-select environment\ncontainer-use diff`,\n\tRunE: func(app *cobra.Command, args []string) error {\n\t\tctx := app.Context()\n\n\t\t// Ensure we're in a git repository\n\t\trepo, err := repository.Open(ctx, \".\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenvID, err := resolveEnvironmentID(ctx, repo, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn repo.Diff(ctx, envID, os.Stdout)\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(diffCmd)\n}\n"], ["/container-use/mcpserver/args.go", "package mcpserver\n\nimport \"github.com/mark3labs/mcp-go/mcp\"\n\nvar (\n\texplainationArgument = mcp.WithString(\"explanation\",\n\t\tmcp.Description(\"One sentence explanation for why this directory is being listed.\"),\n\t)\n\tenvironmentSourceArgument = mcp.WithString(\"environment_source\",\n\t\tmcp.Description(\"Absolute path to the source git repository for the environment.\"),\n\t\tmcp.Required(),\n\t)\n\tenvironmentIDArgument = mcp.WithString(\"environment_id\",\n\t\tmcp.Description(\"The ID of the environment for this command. Must call `environment_create` first.\"),\n\t\tmcp.Required(),\n\t)\n)\n\nfunc newRepositoryTool(name string, description string, args ...mcp.ToolOption) mcp.Tool {\n\topts := []mcp.ToolOption{\n\t\tmcp.WithDescription(description),\n\t\texplainationArgument,\n\t\tenvironmentSourceArgument,\n\t}\n\topts = append(opts, args...)\n\n\treturn mcp.NewTool(name, opts...)\n}\n\nfunc newEnvironmentTool(name string, description string, args ...mcp.ToolOption) mcp.Tool {\n\topts := []mcp.ToolOption{\n\t\tmcp.WithDescription(description),\n\t\texplainationArgument,\n\t\tenvironmentSourceArgument,\n\t\tenvironmentIDArgument,\n\t}\n\topts = append(opts, args...)\n\n\treturn mcp.NewTool(name, opts...)\n}\n"], ["/container-use/cmd/container-use/signals_windows.go", "//go:build windows\n\npackage main\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Windows-compatible signals for receiving\nfunc getNotifySignals() []os.Signal {\n\t// On Windows:\n\t// - os.Interrupt: Ctrl+C signal (can receive, cannot send to other processes)\n\t// - syscall.SIGTERM: Termination signal (can receive) (https://pkg.go.dev/os/signal#hdr-Windows)\n\t// - os.Kill: Not a receivable signal\n\treturn []os.Signal{os.Interrupt, syscall.SIGTERM}\n}\n"], ["/container-use/mcpserver/signals_windows.go", "//go:build windows\n\npackage mcpserver\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Windows-compatible signals for MCP server\nfunc getNotifySignals() []os.Signal {\n\t// On Windows:\n\t// - os.Interrupt: Ctrl+C signal (can receive, cannot send to other processes)\n\t// - syscall.SIGTERM: Termination signal (can receive)\n\t// - os.Kill: Not a receivable signal, used only for Process.Kill()\n\treturn []os.Signal{os.Interrupt, syscall.SIGTERM}\n}\n"], ["/container-use/cmd/container-use/signals_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Unix-compatible signals\nfunc getNotifySignals() []os.Signal {\n\treturn []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}\n}\n"], ["/container-use/mcpserver/signals_unix.go", "//go:build !windows\n\npackage mcpserver\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n// getNotifySignals returns Unix-compatible signals for MCP server\nfunc getNotifySignals() []os.Signal {\n\treturn []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}\n}\n"], ["/container-use/cmd/container-use/terminal_unix.go", "//go:build !windows\n\npackage main\n\nimport (\n\t\"syscall\"\n)\n\nfunc execDaggerRun(daggerBin string, args []string, env []string) error {\n\treturn syscall.Exec(daggerBin, args, env)\n}\n"], ["/container-use/cmd/container-use/signal_windows.go", "//go:build windows\n\npackage main\n\n// On Windows, SIGUSR1 is not available, so we provide a no-op implementation\nfunc setupSignalHandling() {\n\t// No special signal handling on Windows\n}\n"], ["/container-use/rules/rules.go", "package rules\n\nimport _ \"embed\"\n\n//go:embed agent.md\nvar AgentRules string\n\n//go:embed cursor.mdc\nvar CursorRules string\n"]], "task_instance_info": {"created_time": "2025-08-20 20:54:16", "created_task_model": "DeepSeek-R1", "function_skeleton": "func setupLogger () error {}", "code_description": "This code segment functions to: Configure application logging by specifying output destinations based on environmental settings and establishing severity level controls through a multi-writer handler initialization."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc setupLogger() error {\n\tlogFile := os.Getenv(\"LOG_FILE\")\n\tif logFile != \"\" {\n\t\tdir := filepath.Dir(logFile)\n\t\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create log directory: %w\", err)\n\t\t}\n\n\t\tf, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\tlogWriter = f\n\t}\n\n\tlevel := parseLogLevel(os.Getenv(\"LOG_LEVEL\"))\n\tlogger := slog.New(slog.NewTextHandler(logWriter, &slog.HandlerOptions{\n\t\tLevel: level,\n\t}))\n\tslog.SetDefault(logger)\n\n\treturn nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-54-44"}, "editdistance_info": {"edit_distance": 34.2222, "calculate_time": "2025-08-20 20:54:44", "true_code_clean": "func setupLogger() error {\n\tvar writers []io.Writer\n\tlogFile := filepath.Join(os.TempDir(), \"container-use.debug.stderr.log\")\n\tif v, ok := os.LookupEnv(\"CONTAINER_USE_STDERR_FILE\"); ok {\n\t\tlogFile = v\n\t}\n\tfile, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open log file %s: %w\", logFile, err)\n\t}\n\twriters = append(writers, file)\n\tif len(writers) == 0 {\n\t\tfmt.Fprintf(os.Stderr, \"%s Logging disabled. Set CONTAINER_USE_STDERR_FILE and CONTAINER_USE_LOG_LEVEL environment variables\\n\", time.Now().Format(time.DateTime))\n\t}\n\tlogLevel := parseLogLevel(os.Getenv(\"CONTAINER_USE_LOG_LEVEL\"))\n\tlogWriter = io.MultiWriter(writers...)\n\thandler := slog.NewTextHandler(logWriter, &slog.HandlerOptions{\n\t\tLevel: logLevel,\n\t})\n\tslog.SetDefault(slog.New(handler))\n\treturn nil\n}", "predict_code_clean": "func setupLogger() error {\n\tlogFile := os.Getenv(\"LOG_FILE\")\n\tif logFile != \"\" {\n\t\tdir := filepath.Dir(logFile)\n\t\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create log directory: %w\", err)\n\t\t}\n\t\tf, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\tlogWriter = f\n\t}\n\tlevel := parseLogLevel(os.Getenv(\"LOG_LEVEL\"))\n\tlogger := slog.New(slog.NewTextHandler(logWriter, &slog.HandlerOptions{\n\t\tLevel: level,\n\t}))\n\tslog.SetDefault(logger)\n\treturn nil\n}"}}