package console import ( "context" "encoding/json" "errors" "fmt" "io" "io/fs" "maps" "os" "os/exec" "path/filepath" "slices" "strings" "tangled.org/guid.foo/simmer/inject" "tangled.org/guid.foo/simmer/mcptoken" "tangled.org/guid.foo/simmer/plugin" ) // McpConfigPath is the file of the McpServers' OAuth applications, // which SIMMER_MCP_CONFIG names in the server's container. func McpConfigPath(home string) string { return filepath.Join(home, ".config", "simmer", "mcp.json") } // statePath lists the McpServers that the last setup wrote into // ~/.claude.json, so the next one removes those the spec dropped and // never touches a server that the person added. func statePath(home string) string { return filepath.Join(home, ".config", "simmer", "console.json") } type state struct { McpServers []string `json:"mcpServers"` } // Setup is `simmer console setup`, which runs once per pod start, after // the template's init containers set up the forge's credentials. It // clones each missing repository, clones each plugin afresh, registers // the McpServers, and answers Remote Control's first-run questions. // Each clone that fails is logged to log and skipped, so one missing // credential does not keep the Console from starting. func Setup(ctx context.Context, c Config, log io.Writer) error { if err := os.MkdirAll(c.Directory, 0o755); err != nil { return err } for _, r := range c.Repositories { if err := clone(ctx, r.URL, filepath.Join(c.Directory, r.Path)); err != nil { fmt.Fprintf(log, "left %s out: %v\n", r.Path, err) } } if err := clonePlugins(ctx, c, log); err != nil { return err } if err := os.MkdirAll(filepath.Dir(statePath(c.Home)), 0o700); err != nil { return err } if err := mcptoken.WriteConfig(McpConfigPath(c.Home), c.McpServers); err != nil { return err } return writeClaudeConfig(c) } // clone clones a repository into dir, unless dir holds one already: a // checkout can hold work in progress, so setup never pulls or resets. func clone(ctx context.Context, url, dir string) error { if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil { return nil } if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { return err } out, err := exec.CommandContext(ctx, "git", "clone", "--quiet", url, dir).CombinedOutput() if err != nil { return fmt.Errorf("git clone %s: %w: %s", url, err, strings.TrimSpace(string(out))) } return nil } // clonePlugins replaces the plugins' directory with a fresh clone of // each plugin. Claude Code's sessions in a Console never update a // plugin, so a clone that each start makes is the only way a change to // a plugin reaches the Console. A plugin that fails to clone has no // directory, which each session reports as a plugin error. func clonePlugins(ctx context.Context, c Config, log io.Writer) error { dirs, err := c.PluginDirs() if err != nil { return err } if err := os.RemoveAll(PluginsDir(c.Home)); err != nil { return err } for i, repository := range c.Plugins { if err := plugin.Clone(ctx, repository, dirs[i]); err != nil { fmt.Fprintf(log, "left the plugin %s out: %v\n", repository, err) } } return nil } // writeClaudeConfig edits ~/.claude.json and keeps every key it does not // own, because Claude Code keeps its own state in the same file. func writeClaudeConfig(c Config) error { path := filepath.Join(c.Home, ".claude.json") config, err := readObject(path) if err != nil { return err } previous, err := readState(c.Home) if err != nil { return err } servers := object(config, "mcpServers") for _, name := range previous.McpServers { delete(servers, name) } for name, spec := range c.McpServers { entry := map[string]any{"type": "http", "url": spec.URL} if spec.OAuth != nil { entry["headersHelper"] = inject.Binary + " mcp-token" } servers[name] = entry } // Unanswered, these questions are drawn on the terminal's alternate // screen, where no log records them, and the server never reaches // claude.ai. config["remoteDialogSeen"] = true project := object(object(config, "projects"), c.Directory) project["hasTrustDialogAccepted"] = true project["disabledMcpServers"] = append([]string{}, c.DisabledConnectors...) if err := writeJSON(path, config); err != nil { return err } return writeJSON(statePath(c.Home), state{McpServers: slices.Sorted(maps.Keys(c.McpServers))}) } func readObject(path string) (map[string]any, error) { data, err := os.ReadFile(path) if errors.Is(err, fs.ErrNotExist) { return map[string]any{}, nil } if err != nil { return nil, err } out := map[string]any{} if err := json.Unmarshal(data, &out); err != nil { return nil, fmt.Errorf("reading %s: %w", path, err) } return out, nil } func readState(home string) (state, error) { var s state data, err := os.ReadFile(statePath(home)) if errors.Is(err, fs.ErrNotExist) { return s, nil } if err != nil { return s, err } return s, json.Unmarshal(data, &s) } // object answers the object at a key, and puts an empty one there when // it is missing or not an object. func object(o map[string]any, key string) map[string]any { inner, ok := o[key].(map[string]any) if !ok { inner = map[string]any{} o[key] = inner } return inner } // writeJSON replaces a file in one rename, so a server that starts // while setup writes never reads half a file. func writeJSON(path string, value any) error { data, err := json.MarshalIndent(value, "", " ") if err != nil { return err } next := path + ".next" if err := os.WriteFile(next, data, 0o600); err != nil { return err } return os.Rename(next, path) }