Something went wrong. Try again.
A Kubernetes operator that runs Claude Code sessions on long-horizon work
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192package console
import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "path" "strings"
appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types"
"tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/inject" "tangled.org/guid.foo/simmer/podtemplate")
// The names in a Console's pod. The deployment's template mounts the// home volume by its name.const ( HomeVolume = "home" SetupContainer = "console-setup" // HashAnnotation holds the hash of the pod that the operator built // for a Deployment, so a pass writes the Deployment only when the // pod it would build is a different one. A Deployment that the API // server read back holds defaults the operator never wrote, so the // two cannot be compared field by field. HashAnnotation = v1alpha1.Group + "/console-hash")
// DefaultHomeSize is the CRD's default, for a Console that the API// server did not default, as in a test.const DefaultHomeSize = "64Gi"
// ServiceAccount names a Console's ServiceAccount.func ServiceAccount(name string) string { return "console-" + name }
// HomeVolumeClaim names a Console's home volume.func HomeVolumeClaim(name string) string { return "home-" + name }
func labels(c *v1alpha1.Console) map[string]string { return map[string]string{v1alpha1.LabelConsole: c.Metadata.Name}}
func ownedBy(c *v1alpha1.Console) []metav1.OwnerReference { controller := true return []metav1.OwnerReference{{ APIVersion: v1alpha1.APIVersion, Kind: v1alpha1.ConsoleKind.Name, Name: c.Metadata.Name, UID: types.UID(c.Metadata.UID), Controller: &controller, }}}
// Home builds a Console's home volume. It has no owner, so deleting the// Console keeps the person's login, memory, and checkouts.func Home(c *v1alpha1.Console) (*cluster.PersistentVolumeClaim, error) { size := c.Spec.Home.Size if size == "" { size = DefaultHomeSize } quantity, err := resource.ParseQuantity(size) if err != nil { return nil, fmt.Errorf("the home's size %q: %w", size, err) } claim := &cluster.PersistentVolumeClaim{PersistentVolumeClaim: corev1.PersistentVolumeClaim{ TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "PersistentVolumeClaim"}, ObjectMeta: metav1.ObjectMeta{Name: HomeVolumeClaim(c.Metadata.Name), Namespace: c.Metadata.Namespace, Labels: labels(c)}, Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: quantity}}, }, }} if class := c.Spec.Home.StorageClassName; class != "" { claim.Spec.StorageClassName = &class } return claim, nil}
// Deployment builds the Deployment of a Console. servers are the specs// of the McpServers it names.func Deployment(s inject.Settings, c *v1alpha1.Console, servers map[string]v1alpha1.McpServerSpec) (*cluster.Deployment, error) { config := ConfigOf(c, servers) image := c.Spec.Image if image == "" { image = s.SessionImage } bin := corev1.VolumeMount{Name: inject.BinVolume, MountPath: path.Dir(inject.Binary), ReadOnly: true} home := corev1.VolumeMount{Name: HomeVolume, MountPath: config.Home} env := []corev1.EnvVar{ {Name: ConfigEnv, Value: config.Encode()}, {Name: "SIMMER_MCP_CONFIG", Value: McpConfigPath(config.Home)}, } plugins, err := config.PluginDirs() if err != nil { return nil, err } // Remote Control takes no --plugin-dir, and each session it spawns // inherits the server's environment, so every session loads the // plugins from their clones. if len(plugins) > 0 { env = append(env, corev1.EnvVar{Name: "CLAUDE_CODE_PLUGIN_DIRS", Value: strings.Join(plugins, ":")}) } server := corev1.Container{ Name: ContainerName, Image: image, Command: []string{inject.Binary, "console", "serve"}, Env: env, VolumeMounts: []corev1.VolumeMount{bin, home}, // The probe reads files and calls nothing, so it runs often: a // login that lands shows in the Console's LoggedIn within a // period. ReadinessProbe: &corev1.Probe{ ProbeHandler: corev1.ProbeHandler{Exec: &corev1.ExecAction{Command: []string{inject.Binary, "console", "logged-in"}}}, PeriodSeconds: 30, TimeoutSeconds: int32(statusTimeout.Seconds()), FailureThreshold: 1, }, } spec := corev1.PodSpec{ ServiceAccountName: ServiceAccount(c.Metadata.Name), // Remote Control names the environment and its sessions after // the machine's hostname. Hostname: c.Metadata.Name, InitContainers: []corev1.Container{{ Name: inject.InitContainer, Image: s.OperatorImage, Args: []string{"install", "/inject/simmer"}, VolumeMounts: []corev1.VolumeMount{{Name: inject.BinVolume, MountPath: "/inject"}}, }}, Containers: []corev1.Container{server}, Volumes: []corev1.Volume{ {Name: inject.BinVolume, VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{}}}, {Name: HomeVolume, VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: HomeVolumeClaim(c.Metadata.Name), }}}, }, } pod, err := podtemplate.Merge(corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: labels(c)}, Spec: spec}, c.Spec.Template, ContainerName) if err != nil { return nil, err } pod.Labels[v1alpha1.LabelConsole] = c.Metadata.Name // Setup runs last, after the template's init containers set up the // forge's credentials that its clones use. It runs in the image of // the server, with the server's environment, so it sees what the // template gave the server. for _, merged := range pod.Spec.Containers { if merged.Name == ContainerName { pod.Spec.InitContainers = append(pod.Spec.InitContainers, corev1.Container{ Name: SetupContainer, Image: merged.Image, Command: []string{inject.Binary, "console", "setup"}, Env: merged.Env, EnvFrom: merged.EnvFrom, VolumeMounts: merged.VolumeMounts, SecurityContext: merged.SecurityContext, }) } }
hash, err := hashOf(pod) if err != nil { return nil, err } one := int32(1) history := int32(2) return &cluster.Deployment{Deployment: appsv1.Deployment{ TypeMeta: metav1.TypeMeta{APIVersion: "apps/v1", Kind: "Deployment"}, ObjectMeta: metav1.ObjectMeta{ Name: c.Metadata.Name, Namespace: c.Metadata.Namespace, Labels: labels(c), Annotations: map[string]string{HashAnnotation: hash}, OwnerReferences: ownedBy(c), }, Spec: appsv1.DeploymentSpec{ Replicas: &one, RevisionHistoryLimit: &history, Selector: &metav1.LabelSelector{MatchLabels: labels(c)}, // The home volume is ReadWriteOnce, and a rolling update // starts the new pod before the old one lets go of it. Strategy: appsv1.DeploymentStrategy{Type: appsv1.RecreateDeploymentStrategyType}, Template: pod, }, }}, nil}
func hashOf(pod corev1.PodTemplateSpec) (string, error) { data, err := json.Marshal(pod) if err != nil { return "", err } sum := sha256.Sum256(data) return hex.EncodeToString(sum[:8]), nil}