From fcf5bcbcdbbbed4d63a394506b500fffcd76436c Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 12:40:39 -0800 Subject: [PATCH 1/8] docs(rfc): propose Kubernetes resources for sandboxes, templates, and providers (RFC 0030) Signed-off-by: Jim Bugwadia --- .../README.md | 514 ++++++++++++++++++ 1 file changed, 514 insertions(+) create mode 100644 rfc/0030-kubernetes-sandbox-resources/README.md diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md new file mode 100644 index 0000000000..3cd8c4bb12 --- /dev/null +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -0,0 +1,514 @@ +--- +authors: + - "@JimBugwadia" +state: draft +links: + - https://github.com/ai-openshell/openshell/issues/6073 + - https://github.com/ai-openshell/openshell/issues/5062 + - https://github.com/ai-openshell/openshell/issues/1719 + - https://github.com/ai-openshell/openshell/issues/5847 + - https://github.com/ai-openshell/openshell/issues/3362 +--- + +# RFC 0030 - Kubernetes Resources for Sandboxes, Templates, and Providers + + + +## Summary + +This RFC adds an optional Kubernetes controller and three custom resources in +`openshell.ai/v1alpha1`: `OpenShellSandbox`, `OpenShellSandboxTemplate`, and +`OpenShellProvider`. You declare long-lived agents in Git, deliver them with +Argo CD or Flux, govern them with Kubernetes RBAC and admission policy, and +wait for them with `kubectl wait`. The controller is an ordinary client of the +gateway's public gRPC API, the same API that the CLI and SDKs use. It never +creates compute resources itself. + +Each Kubernetes namespace that opts in maps to one gateway workspace. A new +gateway setting, `workspace_managers`, makes such a workspace +Kubernetes-managed: only the controller can create or change its sandboxes, +templates, and providers. Everyone else can still read them, connect to +sandboxes, and run commands in them. Workspaces without an entry, and gateways +without the controller, work as they do today. + +## Motivation + +Teams that run agents on Kubernetes already deliver everything else from Git. +Argo CD and Flux can install the OpenShell gateway with its Helm chart, but not +the agents that run inside OpenShell sandboxes. Today you create sandboxes, +templates, and providers only through the gateway, with the CLI, an SDK, or +gRPC. To deploy an agent from Git, teams write scripts that call the CLI from +CI. + +Those scripts lose what Kubernetes gives every other workload: + +- **Access control.** Permissions live in the gateway, not in namespace RBAC, + so platform teams manage two access models. +- **Drift detection and self-heal.** A CLI call runs once. Nothing notices + when the gateway's state stops matching Git. +- **Health.** `kubectl wait` and GitOps health checks can't see a sandbox. +- **Policy and audit.** Admission policy engines such as Kyverno, Gatekeeper, + and ValidatingAdmissionPolicy don't run, and Kubernetes audit logs don't + record changes. + +The Kubernetes compute driver creates `agents.x-k8s.io/Sandbox` objects, but +they describe pods and the driver owns them. They don't carry policy, +providers, or templates, so they can't serve as the declared intent. + +https://github.com/ai-openshell/openshell/issues/5062 proposed serving +sandboxes from an aggregated API server in the gateway. Reviewers preferred +custom resources and a controller that calls the gateway API, because a +controller supports more than one gateway in a cluster, needs no change to how +the gateway stores data, and works with `kubectl wait`, admission policy, and +GitOps health checks. This RFC describes that design. It needs an RFC because +it adds a public Kubernetes API, a new gateway authorization model for +workspaces, and a component that operators install and run. + +## Non-goals + +- **Installing or upgrading the gateway.** + https://github.com/ai-openshell/openshell/issues/5847 proposes an operator for + that. The controller works with a gateway installed by the Helm chart, the + operator, or any other way. +- **Sandboxes created on demand.** Sandboxes created for each user, session, + or conversation stay on the gateway API. They never become Kubernetes + resources, so etcd grows with the number of declared agents, not with + traffic. +- **Mirroring gateway objects into Kubernetes.** Sandboxes created through the + gateway API in other workspaces don't get resources. +- **Mixed managers in one workspace.** A workspace is either + Kubernetes-managed or gateway-managed in this RFC. +- **Native declarative apply in the CLI and SDKs.** `openshell apply -f`, with + gateway-owned recovery, is possible follow-up work. This RFC keeps recovery in + the controller. +- **Rollout strategies.** This RFC adds no canaries, session migration, or + zero-downtime replacement. Delivery tooling owns those. +- **A policy resource, shared templates across namespaces, and sandbox sets.** + They can follow without changing the fields defined here. + +## Proposal + +### Architecture + +The controller watches the three resources in every namespace that opts in, +and applies each one to the namespace's gateway workspace. Kubernetes stores +the declared intent and the controller's recovery journal. The gateway +database remains the record of each object's configuration and state. + +```mermaid +graph LR + Git --> GitOps[Argo CD or Flux] + GitOps --> API[Kubernetes API server] + API -->|watch| Ctrl[OpenShell controller] + Ctrl -->|status| API + Ctrl -->|gRPC, own identity| GW[Gateway] + CLI[CLI and SDKs] -->|gRPC| GW + GW --> DB[(Gateway database)] + GW --> Drivers[Compute drivers] +``` + +- **The controller is optional.** The gateway doesn't depend on it, and a + gateway outside Kubernetes works unchanged. +- **It uses only the public API.** The controller calls the same gRPC methods + as the CLI. It has no access to the gateway database or the compute driver. +- **It has its own identity.** It authenticates with its own client + certificate, separate from every user's, so the gateway can tell its calls + apart. +- **It runs separately from the gateway.** It's a Rust Deployment with + Lease-based leader election, packaged as a standalone Helm chart rather than + a sub-chart of the gateway chart. It can run in the gateway's cluster or in + another one, and you upgrade it on its own schedule. Sharing Rust code lets + it validate policy with the gateway's own parser. + +### Resources + +All three resources are namespaced, in API group `openshell.ai`, version +`v1alpha1`. + +| Resource | Short name | Gateway object | +|---|---|---| +| `OpenShellSandbox` | `ossbx` | A sandbox. | +| `OpenShellSandboxTemplate` | `ossbxt` | A template family. Each spec change publishes a new revision. | +| `OpenShellProvider` | `osprov` | A provider. Credentials come from Kubernetes Secrets in the same namespace. | + +```yaml +apiVersion: openshell.ai/v1alpha1 +kind: OpenShellSandboxTemplate +metadata: + name: support-agent + namespace: agents +spec: + image: registry.example.com/support-agent@sha256:9f2c... + resources: + cpu: "2" + memory: 4Gi +--- +apiVersion: openshell.ai/v1alpha1 +kind: OpenShellProvider +metadata: + name: nvidia + namespace: agents +spec: + type: nvidia + credentials: + - name: NVIDIA_API_KEY + secretKeyRef: + name: nvidia-credentials + key: api-key +--- +apiVersion: openshell.ai/v1alpha1 +kind: OpenShellSandbox +metadata: + name: support-agent + namespace: agents +spec: + templateRef: + name: support-agent + providers: [nvidia] + command: ["/app/agent", "--serve"] + restartPolicy: Always + stopped: false +``` + +**`OpenShellSandbox`** takes the existing sandbox inputs: a `templateRef` or +an inline `workload`, but not both; `providers`; `command`; `restartPolicy`; +`serviceExposures`; and an inline `policy`. It adds `stopped`. + +- **Mutable fields** are `providers`, `policy`, and `stopped`. The controller + attaches and detaches providers, applies the policy, and stops or starts the + sandbox. The gateway sandbox keeps its ID. +- **Immutable fields** are `templateRef`, `workload`, `command`, + `restartPolicy`, and `serviceExposures`, because they take effect when the + sandbox starts. A CEL transition rule in the CRD rejects changes to them, so + `kubectl apply` fails instead of the sandbox silently keeping its old + settings. To run a different workload, create a new resource. + +**`OpenShellSandboxTemplate`** carries the image and workload settings, so Git +holds the reviewed workload content, not only its name. Gateway templates +can't change in place, so the controller publishes each spec change as a new +revision, named `-r`. New sandboxes use the current revision, and +existing sandboxes keep the revision they started with. +`status.currentRevision` records the latest. A `templateRef` can also name a +gateway template that has no resource. + +**`OpenShellProvider`** declares a provider with references to Kubernetes +Secrets, for both credentials and per-provider refresh material. The resource +never holds a value. Its `type` can't change. + +### Namespaces and workspaces + +A namespace opts in with a label whose value names its gateway workspace: + +```shell +kubectl label namespace agents openshell.ai/workspace=agents +``` + +- **One controller serves every labeled namespace.** It watches namespaces + that carry the label, so a newly labeled namespace takes effect within + seconds. An optional extra label selector lets several controllers, one per + gateway, share a cluster. +- **Each workspace maps to one namespace.** If two namespaces carry the same + value, the namespace created first keeps the workspace, and resources in the + other report `WorkspaceConflict`. Kubernetes names are unique only within a + namespace, so two namespaces sharing a workspace could overwrite each + other's gateway objects. +- **The controller creates missing workspaces.** If the gateway lists the + controller's identity in `workspace_provisioners`, the controller becomes + the new workspace's manager. Onboarding a team then needs a label, not a + gateway configuration change or restart. +- **An admission policy enforces opt-in.** The chart ships a + ValidatingAdmissionPolicy that rejects OpenShell resources in namespaces + without a valid label. +- **Labeling a namespace is a privileged action.** The label decides which + workspace a namespace's resources reach. Clusters where tenants can label + their own namespaces should restrict who can set `openshell.ai/workspace`. + +### Workspace managers + +Two gateway settings decide who can change a workspace's objects: + +```toml +[openshell.gateway] +# Identities that become the manager of each workspace they create. +workspace_provisioners = ["mtls:openshell-k8s-controller"] + +[openshell.gateway.workspace_managers] +# Per workspace, the identities allowed to change its sandboxes, templates, +# and providers. +agents = ["mtls:openshell-k8s-controller"] +``` + +In a managed workspace, only its managers can create, delete, stop, start, +suspend, resume, or update sandboxes; attach or detach providers; expose +services; approve or edit policy drafts; create or delete templates; and +create, update, or delete providers. Other authorized callers can still list +and inspect these objects, read logs, and run commands with `sandbox exec`. +Operators, and users with the configured admin role, keep an emergency stop +and delete. The controller then reports the sandbox as missing and doesn't +recreate it. + +- **The gateway enforces it by authenticated identity**, not by client type, + on every interface. +- **The setting is a list of identities, not a mode.** Several controllers, + for example one per cluster, can manage one workspace, and mixed managers + can follow later without a data migration. +- **A provisioned workspace records its manager** in the + `internal.openshell.ai/workspace-managers` annotation when the controller + creates it. A `workspace_managers` entry takes precedence. + `openshell workspace get` shows the effective managers, from a new + `managers` field on `Workspace`. +- **A workspace without an entry is gateway-managed** and works as it does + today. +- **Roles still apply.** The controller needs the workspace admin role to + manage templates and providers. + +The policy advisor's draft approvals change a running sandbox's policy, so the +manager check blocks them in a Kubernetes-managed workspace. To approve a rule +for a declared sandbox, add it to the sandbox's policy in Git. + +### Reconciliation, status, and deletion + +The controller records its progress in each resource's status so that a crash, +restart, or leader change never duplicates or loses work. + +```mermaid +sequenceDiagram + participant K as Kubernetes + participant C as Controller + participant G as Gateway + C->>K: Add finalizer + C->>K: Record create attempt and request ID in status.journal + C->>G: CreateSandbox (request ID) + G-->>C: Sandbox ID + C->>K: Record sandbox ID, Ready=True + Note over K,C: Resource deleted + C->>G: DeleteSandbox (expected sandbox ID) + G-->>C: Accepted + C->>G: Confirm the sandbox is gone + C->>K: Remove finalizer +``` + +- **Finalizers come first.** The controller adds its finalizer before any + gateway call, and removes it only after the gateway reports the object gone, + not when it accepts the delete. This also covers deleting the whole + namespace. +- **Requests are replayed, not repeated.** The controller records each + attempt in `status.journal` before sending it, and sends the same request ID + after a lost response or restart. +- **Deletes are pinned.** A new optional `expected_sandbox_id` on + `DeleteSandboxRequest` makes the gateway delete the sandbox only if its ID + matches. The controller never deletes a sandbox that replaced the one it + created. +- **Status describes the declaration.** Each resource has a `Ready` + condition, `observedGeneration`, `phase`, and `reason`. A sandbox also + reports `sandboxId`, `templateRevision`, and an informational + `gatewayPhase`. A provisioned sandbox stays `Ready` while it's stopped, + suspended, or completed, so sleeping and waking never changes GitOps health. + Error and unknown phases block. +- **Failures are visible.** Resources report reasons such as + `TemplateNotFound`, `PolicyInvalid`, `SecretNotFound`, `SecretsForbidden`, + `WorkspaceConflict`, `WorkspaceUnavailable`, `NamespaceNotEnabled`, and + `CreateRejected`, and the controller's `/readyz` endpoint reports problems + that an administrator must fix. +- **Status stays current without load.** While a sandbox starts or stops, the + controller follows the gateway's `WatchSandbox` stream, so `gatewayPhase` + updates within seconds. It checks settled sandboxes every 2 minutes, writes + status only when it changes, and reconciles at most 16 resources at a time. + A flag turns `gatewayPhase` off for zero status writes from sleep and wake. + +### Secrets + +Kubernetes Secrets are the source of truth for credential values, typically +synced from a secret manager by the External Secrets Operator. + +1. You store or rotate a value in a Secret in the team's namespace. +2. The controller reads it, for each `OpenShellProvider` that references it. +3. The controller sends it over the authenticated gateway connection when it + creates or updates the provider. The gateway stores its copy with its + configured credential driver: the database, Kubernetes Secrets, or Vault. +4. The sandbox gets a placeholder. The sandbox proxy adds the real value only + to requests that its policy allows, so the agent never sees it. + +- **Access is granted per namespace.** The chart ships a ClusterRole for + reading Secrets with no ClusterRoleBinding. An administrator grants it in + each namespace with a RoleBinding, either through the chart's + `secretsNamespaces` value or with their own tooling. Labeling a namespace + never grants Secret access by itself. A namespace whose providers reference + no Secrets needs no RoleBinding. +- **Rotation reaches the gateway within seconds.** The controller watches + Secret metadata in namespaces whose providers reference Secrets, and + re-applies only the providers that reference a changed Secret. Provider + status records each Secret's resource version, never its value. +- **Values never leave their path.** Status, events, and errors don't include + values, and the controller never calls `RevealSecret`. +- **The controller's access to OpenShell resources is cluster-wide.** + Deleting a namespace deletes its RoleBindings in no particular order, so a + namespaced grant could disappear before the controller removed its + finalizers, and the namespace would never finish deleting. The cluster-wide + grant covers only `openshell.ai` resources and watching namespaces. Deleting + resources needs no Secrets. + +Shared refresh material, such as one OAuth client secret used by many +providers, belongs in workspace secrets from +[RFC 0024](../0024-workspace-secrets/README.md). A resource for them can +follow once that RFC lands. + +### Packaging and operations + +The controller ships as a container image and a Helm chart that installs the +CRDs (kept on uninstall), the controller's RBAC, optional ClusterRoles for +platform engineers and developers, the admission policy, and a Deployment with +leader election, a readiness probe, and credential reload. The controller +reloads rotated gateway credentials without a restart. + +```shell +helm install openshell-controller deploy/helm/openshell-k8s-controller \ + --namespace openshell-controller --create-namespace \ + --set gateway.url=https://openshell.openshell.svc:8080 \ + --set gateway.tls.secretName=openshell-controller-tls \ + --set "secretsNamespaces={agents}" +kubectl label namespace agents openshell.ai/workspace=agents +kubectl apply -f support-agent.yaml +kubectl wait ossbx/support-agent -n agents --for=condition=Ready +openshell sandbox exec --workspace agents --name support-agent -- echo hello +``` + +## Implementation plan + +The gateway changes and the controller are opt-in, so they can land +incrementally without changing behavior for existing users. A working +implementation, with tests and docs, is on +[`feat/6073-k8s-sandbox-crd/JimBugwadia`](https://github.com/JimBugwadia/OpenShell/tree/feat/6073-k8s-sandbox-crd/JimBugwadia). + +1. **Gateway.** Add `workspace_managers` and `workspace_provisioners`, the + `managers` field on `Workspace`, and `expected_sandbox_id` on + `DeleteSandboxRequest`. Enforce managers for sandboxes, templates, and + providers. Document the settings in the gateway configuration reference and + mark them experimental. Test that only managers can change a managed + workspace and that unmanaged workspaces are unaffected. +2. **Controller crate.** Add `crates/openshell-k8s-controller` with the three + resources, the recovery journal, namespace opt-in, Secret handling, status + streams, leader election, and credential reload. Unit-test reconciliation + against a mock gateway, including lost responses, restarts, rejected + immutable edits, and deletion. +3. **Packaging.** Add the controller image, the + `deploy/helm/openshell-k8s-controller` chart, and Helm tests for install, + leader failover, credential rotation, namespace opt-in, and readiness. +4. **Docs.** Add a Kubernetes sandbox resources page, image requirements, a + walkthrough under `examples/`, the chart README, and rows in the + `debug-openshell-cluster` skill. +5. **End-to-end validation.** Run the whole stack in a kind cluster with a + NetworkPolicy-enforcing network plugin, such as Cilium. Confirm that the + sandbox's workload pod can't open connections directly, that deleting a + namespace finishes and removes its gateway objects, and that Argo CD + reports sync, health, self-heal, and prune correctly. + +The API starts at `v1alpha1`, so field changes before `v1beta1` don't need +conversion webhooks. Graduating to `v1beta1` needs a load test that confirms +the etcd and gateway projections under [Risks](#risks). + +## Risks + +- **Two copies of intent.** Kubernetes stores the declaration and the gateway + stores the applied state. In a managed workspace only the controller writes, + so each object has one writer, and status reports the revision that the + gateway accepted. An administrator's emergency stop or delete still makes + the two differ; the controller reports the difference instead of undoing it. +- **Deletion depends on the controller.** Finalizers block deletion until the + controller removes the gateway object, so a controller outage stalls + namespace deletion. A rejected or never-submitted create releases its + finalizer without a gateway call, and the runbook documents manual recovery. + Removing a finalizer by hand leaves the gateway object behind. +- **The namespace label grants a workspace.** Anyone who can label namespaces + chooses which workspace their resources reach. Mitigations are the + one-namespace-per-workspace rule, the namespace selector, and admission + control on namespace labels. Secret access needs a separate RoleBinding. +- **etcd and gateway load.** The prototype stores about 2.8 KB per sandbox + resource, makes 7 Kubernetes writes from creation to `Ready`, and none while + `Ready`. 10,000 declared sandboxes would use about 28 MB of etcd and cause + about 83 gateway checks a second when settled. Each sandbox on the + Kubernetes driver already stores a Pod and an `agents.x-k8s.io/Sandbox` + object, so declarations are a small share. On-demand sandboxes stay off + Kubernetes. A load test must confirm these numbers. +- **Validation errors appear late.** Errors that only the gateway can detect, + such as an invalid policy, appear as conditions rather than `kubectl apply` + failures. The CRD schema and CEL rules catch structural errors at admission. +- **A new component to support.** The project takes on a controller, a chart, + and a Kubernetes API with compatibility obligations once it leaves alpha. + +## Alternatives + +### An aggregated API server in the gateway + +Proposed in https://github.com/ai-openshell/openshell/issues/5062. It stores +nothing in etcd and has one source of truth. But a cluster can register only +one server for each API group and version, so it can't serve several gateways. +If the gateway is down, discovery and namespace deletion stall, and watch, +server-side apply, and admission need custom work. An aggregated server +remains a good fit for a later read-only runtime view that shows live state +with no etcd writes, not for declared intent. + +### The driver's `agents.x-k8s.io/Sandbox` objects + +The Kubernetes driver already creates these objects. They describe pods, +the driver owns them, and they exist only on the Kubernetes driver. They can't +carry policy, providers, or templates, and editing them would bypass the +gateway. + +### Running the CLI from CI, or doing nothing + +Teams can keep calling the CLI from pipelines. This needs no new code, but it +gives no drift detection, self-heal, health, or admission policy, and keeps +access control in the gateway instead of namespace RBAC. + +### Native declarative apply in the gateway first + +`openshell apply -f`, with the gateway owning recovery, would serve users +outside Kubernetes too. It needs new durable intent and revision tracking in +the gateway database. Current demand is Kubernetes GitOps, so this RFC keeps +recovery in the controller. If native apply arrives, the gateway can take over +recovery from the controller instead of both owning it, without changing the +resources. + +## Prior art + +- **Kubernetes operators and controllers**, such as cert-manager and Crossplane + providers, declare external resources as custom resources and reconcile them + through the external system's API, with finalizers that guard cleanup. This + RFC follows the same pattern, including status conditions that GitOps tools + already understand. +- **metrics-server** serves `PodMetrics` through API aggregation next to Pods + that etcd stores. It's the model for a later read-only runtime view, and + shows why intent and live state are better split across two APIs. +- **Argo CD and Flux health checks** read `Ready` conditions and + `observedGeneration`. Designing status around them makes sync, health, + self-heal, and prune work without custom health scripts. +- **[RFC 0024](../0024-workspace-secrets/README.md)** introduces workspace + secrets for shared refresh material. This RFC leaves shared refresh material + to it. + +## Open questions + +- Should the controller authenticate with its Kubernetes ServiceAccount + instead of a client certificate? The gateway would verify the token with the + TokenReview API and accept identities such as + `k8s:system:serviceaccount:openshell-controller:openshell-k8s-controller` in + `workspace_managers`. This works only when the gateway runs in the same + cluster. +- Should mixed managers within one workspace follow, letting a session service + and the controller share a workspace? Which use cases justify the + per-operation ownership rules that it needs? +- When should policy get its own resource, and should teams share policies + across namespaces the way they would share templates? +- Should template references across namespaces follow, so platform teams can + publish shared templates from a namespace they control? Only templates from + listed namespaces would be allowed to set placement. +- Which signal, beyond the `Ready` condition, should gate successful delivery + in Argo CD and Flux? `Ready` describes the declaration, and a running + process isn't proof that the agent works. +- Should a sandbox set with a replica count follow for interchangeable + workers, and how would a new template revision reach existing members? From 4c511f4a3b0c2d27af849d5d6b0b1c071bddfc41 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 15:37:01 -0800 Subject: [PATCH 2/8] docs(rfc): explain the controller's gateway identity Signed-off-by: Jim Bugwadia --- rfc/0030-kubernetes-sandbox-resources/README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index 3cd8c4bb12..611f05e423 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -115,9 +115,11 @@ graph LR gateway outside Kubernetes works unchanged. - **It uses only the public API.** The controller calls the same gRPC methods as the CLI. It has no access to the gateway database or the compute driver. -- **It has its own identity.** It authenticates with its own client - certificate, separate from every user's, so the gateway can tell its calls - apart. +- **It has its own identity.** It authenticates to the gateway with its own + mTLS client certificate, `CN=openshell-k8s-controller`, separate from every + user's, so the gateway can tell its calls apart. Its Kubernetes + ServiceAccount is used only for the Kubernetes API; the gateway doesn't see + it. - **It runs separately from the gateway.** It's a Rust Deployment with Lease-based leader election, packaged as a standalone Helm chart rather than a sub-chart of the gateway chart. It can run in the gateway's cluster or in @@ -242,6 +244,14 @@ workspace_provisioners = ["mtls:openshell-k8s-controller"] agents = ["mtls:openshell-k8s-controller"] ``` +Each identity is written as `:`, the form the gateway's +authentication already produces. The subject is the client certificate CN for +`mtls`, and the token's `sub` claim for `oidc`. So +`mtls:openshell-k8s-controller` means "a caller that presented a client +certificate, issued by the gateway's CA, with `CN=openshell-k8s-controller`". +It isn't a Kubernetes ServiceAccount; see [Open questions](#open-questions) +for that option. + In a managed workspace, only its managers can create, delete, stop, start, suspend, resume, or update sandboxes; attach or detach providers; expose services; approve or edit policy drafts; create or delete templates; and From bd4aac1d1179c06052e8af25833aee05e7f207f5 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 16:01:18 -0800 Subject: [PATCH 3/8] docs(rfc): add delivery signals and warm-pool revision rules Signed-off-by: Jim Bugwadia --- .../README.md | 119 +++++++++++++++--- 1 file changed, 102 insertions(+), 17 deletions(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index 611f05e423..d9a8f4b5f3 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -8,6 +8,7 @@ links: - https://github.com/ai-openshell/openshell/issues/1719 - https://github.com/ai-openshell/openshell/issues/5847 - https://github.com/ai-openshell/openshell/issues/3362 + - https://github.com/ai-openshell/openshell/pull/5518 --- # RFC 0030 - Kubernetes Resources for Sandboxes, Templates, and Providers @@ -21,8 +22,13 @@ RFC number from that issue. ## Summary This RFC adds an optional Kubernetes controller and three custom resources in -`openshell.ai/v1alpha1`: `OpenShellSandbox`, `OpenShellSandboxTemplate`, and -`OpenShellProvider`. You declare long-lived agents in Git, deliver them with +the API group `openshell.ai/v1alpha1`: + +- `OpenShellSandbox` +- `OpenShellSandboxTemplate` +- `OpenShellProvider` + +You declare long-lived agents in Git, deliver them with Argo CD or Flux, govern them with Kubernetes RBAC and admission policy, and wait for them with `kubectl wait`. The controller is an ordinary client of the gateway's public gRPC API, the same API that the CLI and SDKs use. It never @@ -59,7 +65,7 @@ The Kubernetes compute driver creates `agents.x-k8s.io/Sandbox` objects, but they describe pods and the driver owns them. They don't carry policy, providers, or templates, so they can't serve as the declared intent. -https://github.com/ai-openshell/openshell/issues/5062 proposed serving + proposed serving sandboxes from an aggregated API server in the gateway. Reviewers preferred custom resources and a controller that calls the gateway API, because a controller supports more than one gateway in a cluster, needs no change to how @@ -71,7 +77,7 @@ workspaces, and a component that operators install and run. ## Non-goals - **Installing or upgrading the gateway.** - https://github.com/ai-openshell/openshell/issues/5847 proposes an operator for + proposes an operator for that. The controller works with a gateway installed by the Helm chart, the operator, or any other way. - **Sandboxes created on demand.** Sandboxes created for each user, session, @@ -197,6 +203,24 @@ existing sandboxes keep the revision they started with. `status.currentRevision` records the latest. A `templateRef` can also name a gateway template that has no resource. +Templates don't expose warm pools in `v1alpha1`. The gateway derives a warm +pool from a template's startup tuning, `ready_within` and `max_burst` +(), and a pool serves only +the template it came from. Without tuning, the gateway keeps no spare +runtimes, so the controller's revisions cost nothing. A later `spec.startup` +field with `readyWithin` and `maxBurst` must keep pools from following old +revisions: + +- **Only the current revision carries startup tuning.** When the controller + publishes a new revision, it removes the tuning from the previous one, and + the gateway drains that pool's unclaimed runtimes. Sandboxes that still run + an old revision are unaffected. +- **The controller deletes superseded revisions that no sandbox uses**, so + revision history doesn't grow without bound. +- **A new revision starts cold.** Its pool fills after it's published, so + frequent template changes reduce the benefit of warm pools. Status reports + the revision, so a rollout can wait for the new pool. + **`OpenShellProvider`** declares a provider with references to Kubernetes Secrets, for both credentials and per-provider refresh material. The resource never holds a value. Its `type` can't change. @@ -252,10 +276,10 @@ certificate, issued by the gateway's CA, with `CN=openshell-k8s-controller`". It isn't a Kubernetes ServiceAccount; see [Open questions](#open-questions) for that option. -In a managed workspace, only its managers can create, delete, stop, start, -suspend, resume, or update sandboxes; attach or detach providers; expose -services; approve or edit policy drafts; create or delete templates; and -create, update, or delete providers. Other authorized callers can still list +In a managed workspace, only its managers can `create`, `delete`, `stop`, `start`, +`suspend`, `resume`, or `update` sandboxes; `attach` or `detach` providers; expose +services; `approve` or `edit` policy drafts; `create` or `delete` templates; and +`create`, `update`, or `delete` providers. Other authorized callers can still list and inspect these objects, read logs, and run commands with `sandbox exec`. Operators, and users with the configured admin role, keep an emergency stop and delete. The controller then reports the sandbox as missing and doesn't @@ -313,12 +337,13 @@ sequenceDiagram `DeleteSandboxRequest` makes the gateway delete the sandbox only if its ID matches. The controller never deletes a sandbox that replaced the one it created. -- **Status describes the declaration.** Each resource has a `Ready` +- **`Ready` describes the declaration.** Each resource has a `Ready` condition, `observedGeneration`, `phase`, and `reason`. A sandbox also reports `sandboxId`, `templateRevision`, and an informational `gatewayPhase`. A provisioned sandbox stays `Ready` while it's stopped, suspended, or completed, so sleeping and waking never changes GitOps health. - Error and unknown phases block. + Error and unknown phases block. Whether the agent works is a separate + condition, `Available`; see [Delivery signals](#delivery-signals). - **Failures are visible.** Resources report reasons such as `TemplateNotFound`, `PolicyInvalid`, `SecretNotFound`, `SecretsForbidden`, `WorkspaceConflict`, `WorkspaceUnavailable`, `NamespaceNotEnabled`, and @@ -330,6 +355,55 @@ sequenceDiagram status only when it changes, and reconciles at most 16 resources at a time. A flag turns `gatewayPhase` off for zero status writes from sleep and wake. +### Delivery signals + +`Ready` means the gateway accepted the declared spec. It doesn't prove that +the agent works: a process can start, crash, and restart, or run with a policy +the gateway rejected. Argo CD and Flux need a signal that a delivery +succeeded, the way a Deployment separates `Available` from rollout progress. + +Each `OpenShellSandbox` gets a second condition, `Available`, and GitOps health +checks gate on it instead of `Ready`. The controller computes it from the +gateway's `WatchSandbox` stream, which it already follows, so it adds no +gateway calls and no polling for each sandbox. The design has three layers. + +1. **Stability, from signals the gateway reports today.** `Available` becomes + `True` when the sandbox is `READY`, `current_policy_version` matches the + policy the controller applied, every attached provider reports ready, and + `restart_count` doesn't increase for `spec.minReadySeconds`, 30 seconds by + default. A restart, a rejected policy, or a provider that isn't ready sets + it to `False` with a reason such as `CrashLooping`, `PolicyNotLoaded`, or + `ProviderNotReady`. The controller keeps one timer for each sandbox inside + its window and none after. +2. **An agent readiness probe.** A template can declare a probe, an `exec` + command or an HTTP request to a port in the sandbox, with a period and a + failure threshold. The supervisor runs it inside the sandbox, where it + already runs processes and controls the network, and reports only changes + over its existing gateway session. The gateway records the result as a + sandbox condition, `AgentReady`, and the controller includes it in + `Available`. This is the only layer that tests the agent rather than its + process, and the agent's owner decides what working means. Because the + probe runs at the edge and only changes travel, the cost doesn't grow with + the probe rate. +3. **Rollout status on the template.** `OpenShellSandboxTemplate` status + reports, for its current revision, how many sandboxes run it and how many + are `Available`, so a GitOps tool can gate a template change on the + sandboxes that use it. A check that needs a real request, such as a test + prompt, belongs in a delivery hook that runs once per application, for + example an Argo CD PostSync Job or a Flux post-deployment test that calls + `openshell sandbox exec`. + +A stopped or suspended sandbox reports `Available=True` with reason `Stopped` +or `Suspended`, and a completed sandbox reports reason `Completed`, so sleep +and wake don't change application health. The health checks read `Available` +only when `observedGeneration` matches the resource's generation. In Argo CD, +that's a Lua health check; in Flux 2.5 and later, a CEL expression in +`healthCheckExprs`. + +Layers 1 and 3 are controller changes and belong in the first release. +Layer 2 needs a template field, a supervisor change, and a gateway condition, +so it follows as its own change. + ### Secrets Kubernetes Secrets are the source of truth for credential values, typically @@ -402,7 +476,8 @@ implementation, with tests and docs, is on workspace and that unmanaged workspaces are unaffected. 2. **Controller crate.** Add `crates/openshell-k8s-controller` with the three resources, the recovery journal, namespace opt-in, Secret handling, status - streams, leader election, and credential reload. Unit-test reconciliation + streams, the `Available` condition and template rollout status, leader + election, and credential reload. Unit-test reconciliation against a mock gateway, including lost responses, restarts, rejected immutable edits, and deletion. 3. **Packaging.** Add the controller image, the @@ -417,6 +492,11 @@ implementation, with tests and docs, is on namespace finishes and removes its gateway objects, and that Argo CD reports sync, health, self-heal, and prune correctly. +Two follow-ups extend the resources after the first release: the agent +readiness probe from [Delivery signals](#delivery-signals), and template +startup tuning for warm pools, with the revision rules in +[Resources](#resources). + The API starts at `v1alpha1`, so field changes before `v1beta1` don't need conversion webhooks. Graduating to `v1beta1` needs a load test that confirms the etcd and gateway projections under [Risks](#risks). @@ -454,7 +534,7 @@ the etcd and gateway projections under [Risks](#risks). ### An aggregated API server in the gateway -Proposed in https://github.com/ai-openshell/openshell/issues/5062. It stores +Proposed in . It stores nothing in etcd and has one source of truth. But a cluster can register only one server for each API group and version, so it can't serve several gateways. If the gateway is down, discovery and namespace deletion stall, and watch, @@ -494,9 +574,14 @@ resources. - **metrics-server** serves `PodMetrics` through API aggregation next to Pods that etcd stores. It's the model for a later read-only runtime view, and shows why intent and live state are better split across two APIs. -- **Argo CD and Flux health checks** read `Ready` conditions and +- **Argo CD and Flux health checks** read conditions and `observedGeneration`. Designing status around them makes sync, health, - self-heal, and prune work without custom health scripts. + self-heal, and prune work with a short health check. +- **Deployment's `Available` condition and `minReadySeconds`** separate a + rollout that's progressing from one whose Pods stayed ready long enough to + count. `Available` on a sandbox follows the same split, and the readiness + probe follows Pod readiness probes, run next to the workload instead of by a + central poller. - **[RFC 0024](../0024-workspace-secrets/README.md)** introduces workspace secrets for shared refresh material. This RFC leaves shared refresh material to it. @@ -517,8 +602,8 @@ resources. - Should template references across namespaces follow, so platform teams can publish shared templates from a namespace they control? Only templates from listed namespaces would be allowed to set placement. -- Which signal, beyond the `Ready` condition, should gate successful delivery - in Argo CD and Flux? `Ready` describes the declaration, and a running - process isn't proof that the agent works. +- For the agent readiness probe, are `exec` and HTTP enough, or do agents need + a probe that sends a test request through a provider? Should a probe failure + restart the sandbox, the way a liveness probe would, or only report it? - Should a sandbox set with a replica count follow for interchangeable workers, and how would a new template revision reach existing members? From ed4d03d02c62e16d402eb3532551e36ff008e62d Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 16:15:16 -0800 Subject: [PATCH 4/8] docs(rfc): rename to sandbox availability and defer the readiness probe Signed-off-by: Jim Bugwadia --- .../README.md | 98 ++++++++----------- 1 file changed, 42 insertions(+), 56 deletions(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index d9a8f4b5f3..30d4083411 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -343,7 +343,7 @@ sequenceDiagram `gatewayPhase`. A provisioned sandbox stays `Ready` while it's stopped, suspended, or completed, so sleeping and waking never changes GitOps health. Error and unknown phases block. Whether the agent works is a separate - condition, `Available`; see [Delivery signals](#delivery-signals). + condition, `Available`; see [Sandbox availability](#sandbox-availability). - **Failures are visible.** Resources report reasons such as `TemplateNotFound`, `PolicyInvalid`, `SecretNotFound`, `SecretsForbidden`, `WorkspaceConflict`, `WorkspaceUnavailable`, `NamespaceNotEnabled`, and @@ -355,54 +355,43 @@ sequenceDiagram status only when it changes, and reconciles at most 16 resources at a time. A flag turns `gatewayPhase` off for zero status writes from sleep and wake. -### Delivery signals - -`Ready` means the gateway accepted the declared spec. It doesn't prove that -the agent works: a process can start, crash, and restart, or run with a policy -the gateway rejected. Argo CD and Flux need a signal that a delivery -succeeded, the way a Deployment separates `Available` from rollout progress. - -Each `OpenShellSandbox` gets a second condition, `Available`, and GitOps health -checks gate on it instead of `Ready`. The controller computes it from the -gateway's `WatchSandbox` stream, which it already follows, so it adds no -gateway calls and no polling for each sandbox. The design has three layers. - -1. **Stability, from signals the gateway reports today.** `Available` becomes - `True` when the sandbox is `READY`, `current_policy_version` matches the - policy the controller applied, every attached provider reports ready, and - `restart_count` doesn't increase for `spec.minReadySeconds`, 30 seconds by - default. A restart, a rejected policy, or a provider that isn't ready sets - it to `False` with a reason such as `CrashLooping`, `PolicyNotLoaded`, or - `ProviderNotReady`. The controller keeps one timer for each sandbox inside - its window and none after. -2. **An agent readiness probe.** A template can declare a probe, an `exec` - command or an HTTP request to a port in the sandbox, with a period and a - failure threshold. The supervisor runs it inside the sandbox, where it - already runs processes and controls the network, and reports only changes - over its existing gateway session. The gateway records the result as a - sandbox condition, `AgentReady`, and the controller includes it in - `Available`. This is the only layer that tests the agent rather than its - process, and the agent's owner decides what working means. Because the - probe runs at the edge and only changes travel, the cost doesn't grow with - the probe rate. -3. **Rollout status on the template.** `OpenShellSandboxTemplate` status - reports, for its current revision, how many sandboxes run it and how many - are `Available`, so a GitOps tool can gate a template change on the - sandboxes that use it. A check that needs a real request, such as a test - prompt, belongs in a delivery hook that runs once per application, for - example an Argo CD PostSync Job or a Flux post-deployment test that calls - `openshell sandbox exec`. - +### Sandbox availability + +`Ready` means the gateway accepted the declared spec. It doesn't show that the +agent stays up: a process can start, crash, and restart, or run without the +policy or credentials it needs. Each `OpenShellSandbox` therefore has a second +condition, `Available`, the way a Deployment separates `Available` from +rollout progress. GitOps health checks read `Available` instead of `Ready`. + +The controller computes `Available` from the gateway's `WatchSandbox` stream, +which it already follows, so it adds no gateway calls and no polling for each +sandbox. `Available` is `True` when all of these hold: + +- The sandbox is `READY`. +- `current_policy_version` matches the policy the controller applied. +- Every attached provider reports ready. +- Every endpoint in `endpoint_statuses`, which the gateway checks passively + for tool servers such as MCP over HTTP, last succeeded. +- `restart_count` hasn't increased for `spec.minReadySeconds`, 30 seconds by + default. + +Otherwise it's `False` with a reason such as `CrashLooping`, +`PolicyNotLoaded`, `ProviderNotReady`, or `EndpointUnreachable`. The +controller keeps one timer for each sandbox inside its window and none after. A stopped or suspended sandbox reports `Available=True` with reason `Stopped` or `Suspended`, and a completed sandbox reports reason `Completed`, so sleep -and wake don't change application health. The health checks read `Available` -only when `observedGeneration` matches the resource's generation. In Argo CD, -that's a Lua health check; in Flux 2.5 and later, a CEL expression in -`healthCheckExprs`. +and wake don't change application health. + +`OpenShellSandboxTemplate` status reports, for its current revision, how many +sandboxes run it and how many are `Available`, so a GitOps tool can gate a +template change on the sandboxes that use it. -Layers 1 and 3 are controller changes and belong in the first release. -Layer 2 needs a template field, a supervisor change, and a gateway condition, -so it follows as its own change. +Health checks read `Available` only when `observedGeneration` matches the +resource's generation. In Argo CD, that's a Lua health check; in Flux 2.5 and +later, a CEL expression in `healthCheckExprs`. A check that needs a real +request, such as a test prompt, belongs in a hook that runs once per +application, for example an Argo CD PostSync Job or a Flux post-deployment +test that calls `openshell sandbox exec`. ### Secrets @@ -492,10 +481,8 @@ implementation, with tests and docs, is on namespace finishes and removes its gateway objects, and that Argo CD reports sync, health, self-heal, and prune correctly. -Two follow-ups extend the resources after the first release: the agent -readiness probe from [Delivery signals](#delivery-signals), and template -startup tuning for warm pools, with the revision rules in -[Resources](#resources). +Template startup tuning for warm pools follows the first release, with the +revision rules in [Resources](#resources). The API starts at `v1alpha1`, so field changes before `v1beta1` don't need conversion webhooks. Graduating to `v1beta1` needs a load test that confirms @@ -579,9 +566,7 @@ resources. self-heal, and prune work with a short health check. - **Deployment's `Available` condition and `minReadySeconds`** separate a rollout that's progressing from one whose Pods stayed ready long enough to - count. `Available` on a sandbox follows the same split, and the readiness - probe follows Pod readiness probes, run next to the workload instead of by a - central poller. + count. `Available` on a sandbox follows the same split. - **[RFC 0024](../0024-workspace-secrets/README.md)** introduces workspace secrets for shared refresh material. This RFC leaves shared refresh material to it. @@ -602,8 +587,9 @@ resources. - Should template references across namespaces follow, so platform teams can publish shared templates from a namespace they control? Only templates from listed namespaces would be allowed to set placement. -- For the agent readiness probe, are `exec` and HTTP enough, or do agents need - a probe that sends a test request through a provider? Should a probe failure - restart the sandbox, the way a liveness probe would, or only report it? +- Do agents need a readiness probe that the supervisor runs inside the + sandbox, beyond stability, endpoint status, and delivery hooks? It would + test the agent rather than its process, but needs a template field, + supervisor support, and a gateway condition. - Should a sandbox set with a replica count follow for interchangeable workers, and how would a new template revision reach existing members? From 3a0947022f4a993a150a21c3e0a774e9d53b52a6 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 16:21:05 -0800 Subject: [PATCH 5/8] docs(rfc): add the runtime view as a deferred follow-up Signed-off-by: Jim Bugwadia --- .../README.md | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index 30d4083411..1c8e2e291f 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -481,8 +481,35 @@ implementation, with tests and docs, is on namespace finishes and removes its gateway objects, and that Argo CD reports sync, health, self-heal, and prune correctly. -Template startup tuning for warm pools follows the first release, with the -revision rules in [Resources](#resources). +Potential follow-ups after the first release: + +- **Warm pools.** Template startup tuning, with the revision rules in + [Resources](#resources). +- **A read-only runtime view.** A `SandboxRuntime` resource in its own API + group, such as `runtime.openshell.ai`, served by an aggregated API server + that reads live state from the gateway, the way metrics-server serves + `PodMetrics` next to Pods. It would show phase, restarts, endpoints, and + sandboxes that the controller doesn't manage, such as session sandboxes, + with no etcd writes, and would replace `gatewayPhase` in sandbox status. + + It's deferred because an aggregated API puts its server in the cluster's + discovery path. While the server is unavailable, discovery for its group + fails, clients that discover every group report errors, and namespace + deletion stalls with `NamespaceDeletionDiscoveryFailure` because the + namespace controller can't confirm the namespace is empty. CRDs avoid this + because kube-apiserver serves them. The view therefore needs: + + - At least two replicas, a PodDisruptionBudget, and anti-affinity, like + other critical cluster add-ons. + - Independence from the gateway: it keeps serving discovery, and returns a + stale or empty view with a condition instead of an error when the gateway + is unreachable, so a gateway outage doesn't become a cluster outage. + - Read-only access, which avoids admission and write semantics. + - Delegated authentication, authorization with SubjectAccessReview, and an + exclusion for its API group in GitOps tools. + + `Available` and `gatewayPhase` cover the first release's needs without + that commitment. The API starts at `v1alpha1`, so field changes before `v1beta1` don't need conversion webhooks. Graduating to `v1beta1` needs a load test that confirms @@ -526,8 +553,9 @@ nothing in etcd and has one source of truth. But a cluster can register only one server for each API group and version, so it can't serve several gateways. If the gateway is down, discovery and namespace deletion stall, and watch, server-side apply, and admission need custom work. An aggregated server -remains a good fit for a later read-only runtime view that shows live state -with no etcd writes, not for declared intent. +remains a good fit for a read-only runtime view that shows live state with no +etcd writes, not for declared intent; see the follow-ups in +[Implementation plan](#implementation-plan). ### The driver's `agents.x-k8s.io/Sandbox` objects From 01720ce0d81fd28ce2d854c608fdb6e1f5e76639 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 21:26:22 -0800 Subject: [PATCH 6/8] docs(rfc): simplify the language Signed-off-by: Jim Bugwadia --- .../README.md | 676 +++++++++--------- 1 file changed, 322 insertions(+), 354 deletions(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index 1c8e2e291f..c140568212 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -28,82 +28,78 @@ the API group `openshell.ai/v1alpha1`: - `OpenShellSandboxTemplate` - `OpenShellProvider` -You declare long-lived agents in Git, deliver them with -Argo CD or Flux, govern them with Kubernetes RBAC and admission policy, and -wait for them with `kubectl wait`. The controller is an ordinary client of the -gateway's public gRPC API, the same API that the CLI and SDKs use. It never -creates compute resources itself. - -Each Kubernetes namespace that opts in maps to one gateway workspace. A new -gateway setting, `workspace_managers`, makes such a workspace -Kubernetes-managed: only the controller can create or change its sandboxes, -templates, and providers. Everyone else can still read them, connect to -sandboxes, and run commands in them. Workspaces without an entry, and gateways -without the controller, work as they do today. +You declare long-lived agents in Git, deploy them with Argo CD or Flux, +control them with Kubernetes RBAC and admission policy, and wait for them with +`kubectl wait`. The controller calls the gateway's public gRPC API, the same +API that the CLI and SDKs use. It doesn't create pods or other compute +resources. + +Each namespace that opts in maps to one gateway workspace. A new gateway +setting, `workspace_managers`, lets only the controller create or change the +sandboxes, templates, and providers in that workspace. Other users can still +read them, connect to sandboxes, and run commands in them. Workspaces without +the setting, and gateways without the controller, work as they do today. ## Motivation -Teams that run agents on Kubernetes already deliver everything else from Git. -Argo CD and Flux can install the OpenShell gateway with its Helm chart, but not -the agents that run inside OpenShell sandboxes. Today you create sandboxes, -templates, and providers only through the gateway, with the CLI, an SDK, or -gRPC. To deploy an agent from Git, teams write scripts that call the CLI from -CI. +Teams that run agents on Kubernetes deploy everything else from Git. Argo CD +and Flux can install the OpenShell gateway with its Helm chart, but not the +agents that run in OpenShell sandboxes. You can create sandboxes, templates, +and providers only through the gateway, with the CLI, an SDK, or gRPC, so +teams write CI scripts that call the CLI. -Those scripts lose what Kubernetes gives every other workload: +Those scripts miss what Kubernetes provides for other workloads: - **Access control.** Permissions live in the gateway, not in namespace RBAC, so platform teams manage two access models. -- **Drift detection and self-heal.** A CLI call runs once. Nothing notices - when the gateway's state stops matching Git. +- **Drift detection.** A CLI call runs once. Nothing notices when the gateway + no longer matches Git. - **Health.** `kubectl wait` and GitOps health checks can't see a sandbox. - **Policy and audit.** Admission policy engines such as Kyverno, Gatekeeper, and ValidatingAdmissionPolicy don't run, and Kubernetes audit logs don't record changes. The Kubernetes compute driver creates `agents.x-k8s.io/Sandbox` objects, but -they describe pods and the driver owns them. They don't carry policy, -providers, or templates, so they can't serve as the declared intent. +those describe pods and the driver owns them. They don't include policy, +providers, or templates. proposed serving sandboxes from an aggregated API server in the gateway. Reviewers preferred -custom resources and a controller that calls the gateway API, because a -controller supports more than one gateway in a cluster, needs no change to how -the gateway stores data, and works with `kubectl wait`, admission policy, and -GitOps health checks. This RFC describes that design. It needs an RFC because -it adds a public Kubernetes API, a new gateway authorization model for -workspaces, and a component that operators install and run. +custom resources and a controller that calls the gateway API. A controller +supports more than one gateway per cluster, needs no change to gateway +storage, and works with `kubectl wait`, admission policy, and GitOps health +checks. This RFC describes that design. It adds a public Kubernetes API, a +gateway authorization model for workspaces, and a component that operators +install and run. ## Non-goals - **Installing or upgrading the gateway.** - proposes an operator for - that. The controller works with a gateway installed by the Helm chart, the - operator, or any other way. -- **Sandboxes created on demand.** Sandboxes created for each user, session, - or conversation stay on the gateway API. They never become Kubernetes - resources, so etcd grows with the number of declared agents, not with - traffic. + proposes an operator + for that. The controller works with a gateway installed by the Helm chart, + the operator, or any other way. +- **Sandboxes created on demand.** Sandboxes created per user, session, or + conversation stay on the gateway API and never become Kubernetes resources, + so etcd grows with the number of declared agents, not with traffic. - **Mirroring gateway objects into Kubernetes.** Sandboxes created through the gateway API in other workspaces don't get resources. -- **Mixed managers in one workspace.** A workspace is either - Kubernetes-managed or gateway-managed in this RFC. -- **Native declarative apply in the CLI and SDKs.** `openshell apply -f`, with - gateway-owned recovery, is possible follow-up work. This RFC keeps recovery in - the controller. -- **Rollout strategies.** This RFC adds no canaries, session migration, or - zero-downtime replacement. Delivery tooling owns those. -- **A policy resource, shared templates across namespaces, and sandbox sets.** - They can follow without changing the fields defined here. +- **Mixed managers in one workspace.** A workspace is managed either by + Kubernetes or through the gateway API. +- **Declarative apply in the CLI and SDKs.** An `openshell apply -f` command is + possible later work. +- **Rollout strategies.** No canaries, session migration, or zero-downtime + replacement. Delivery tools handle those. +- **A policy resource, templates shared across namespaces, and sandbox sets.** + These can be added later without changing the fields defined here. ## Proposal ### Architecture -The controller watches the three resources in every namespace that opts in, -and applies each one to the namespace's gateway workspace. Kubernetes stores -the declared intent and the controller's recovery journal. The gateway -database remains the record of each object's configuration and state. +The controller watches the three resources in each namespace that opts in and +applies them to that namespace's gateway workspace. Kubernetes stores the +declared spec and the controller's progress. The gateway database stores each +object's configuration and state. ```mermaid graph LR @@ -119,18 +115,15 @@ graph LR - **The controller is optional.** The gateway doesn't depend on it, and a gateway outside Kubernetes works unchanged. -- **It uses only the public API.** The controller calls the same gRPC methods - as the CLI. It has no access to the gateway database or the compute driver. +- **It uses only the public API.** It calls the same gRPC methods as the CLI + and has no access to the gateway database or the compute driver. - **It has its own identity.** It authenticates to the gateway with its own - mTLS client certificate, `CN=openshell-k8s-controller`, separate from every - user's, so the gateway can tell its calls apart. Its Kubernetes - ServiceAccount is used only for the Kubernetes API; the gateway doesn't see - it. + mTLS client certificate, `CN=openshell-k8s-controller`. Its Kubernetes + ServiceAccount is used only for the Kubernetes API. - **It runs separately from the gateway.** It's a Rust Deployment with - Lease-based leader election, packaged as a standalone Helm chart rather than - a sub-chart of the gateway chart. It can run in the gateway's cluster or in - another one, and you upgrade it on its own schedule. Sharing Rust code lets - it validate policy with the gateway's own parser. + Lease-based leader election, in its own Helm chart. It can run in the + gateway's cluster or another one, and you upgrade it separately. It uses the + gateway's policy parser to validate policy. ### Resources @@ -140,7 +133,7 @@ All three resources are namespaced, in API group `openshell.ai`, version | Resource | Short name | Gateway object | |---|---|---| | `OpenShellSandbox` | `ossbx` | A sandbox. | -| `OpenShellSandboxTemplate` | `ossbxt` | A template family. Each spec change publishes a new revision. | +| `OpenShellSandboxTemplate` | `ossbxt` | A template. Each spec change publishes a new revision. | | `OpenShellProvider` | `osprov` | A provider. Credentials come from Kubernetes Secrets in the same namespace. | ```yaml @@ -182,80 +175,73 @@ spec: stopped: false ``` -**`OpenShellSandbox`** takes the existing sandbox inputs: a `templateRef` or -an inline `workload`, but not both; `providers`; `command`; `restartPolicy`; -`serviceExposures`; and an inline `policy`. It adds `stopped`. - -- **Mutable fields** are `providers`, `policy`, and `stopped`. The controller - attaches and detaches providers, applies the policy, and stops or starts the - sandbox. The gateway sandbox keeps its ID. -- **Immutable fields** are `templateRef`, `workload`, `command`, - `restartPolicy`, and `serviceExposures`, because they take effect when the - sandbox starts. A CEL transition rule in the CRD rejects changes to them, so - `kubectl apply` fails instead of the sandbox silently keeping its old - settings. To run a different workload, create a new resource. - -**`OpenShellSandboxTemplate`** carries the image and workload settings, so Git -holds the reviewed workload content, not only its name. Gateway templates -can't change in place, so the controller publishes each spec change as a new -revision, named `-r`. New sandboxes use the current revision, and -existing sandboxes keep the revision they started with. -`status.currentRevision` records the latest. A `templateRef` can also name a -gateway template that has no resource. - -Templates don't expose warm pools in `v1alpha1`. The gateway derives a warm -pool from a template's startup tuning, `ready_within` and `max_burst` -(), and a pool serves only -the template it came from. Without tuning, the gateway keeps no spare -runtimes, so the controller's revisions cost nothing. A later `spec.startup` -field with `readyWithin` and `maxBurst` must keep pools from following old -revisions: - -- **Only the current revision carries startup tuning.** When the controller - publishes a new revision, it removes the tuning from the previous one, and - the gateway drains that pool's unclaimed runtimes. Sandboxes that still run - an old revision are unaffected. -- **The controller deletes superseded revisions that no sandbox uses**, so - revision history doesn't grow without bound. -- **A new revision starts cold.** Its pool fills after it's published, so - frequent template changes reduce the benefit of warm pools. Status reports - the revision, so a rollout can wait for the new pool. - -**`OpenShellProvider`** declares a provider with references to Kubernetes -Secrets, for both credentials and per-provider refresh material. The resource -never holds a value. Its `type` can't change. +**`OpenShellSandbox`** has the same inputs as a gateway sandbox: a +`templateRef` or an inline `workload`, but not both; `providers`; `command`; +`restartPolicy`; `serviceExposures`; and an inline `policy`. It adds +`stopped`. + +- You can change `providers`, `policy`, and `stopped`. The controller attaches + or detaches providers, applies the policy, and stops or starts the sandbox. + The sandbox keeps its ID. +- You can't change `templateRef`, `workload`, `command`, `restartPolicy`, or + `serviceExposures`, because they apply only when the sandbox starts. A CEL + rule in the CRD rejects changes to them, so `kubectl apply` fails instead of + being ignored. To run a different workload, create a new resource. + +**`OpenShellSandboxTemplate`** holds the image and workload settings, so Git +has the reviewed workload, not only its name. Gateway templates can't be +changed, so the controller publishes each spec change as a new revision, +`-r`. New sandboxes use the latest revision, and running sandboxes +keep theirs. `status.currentRevision` shows the latest. A `templateRef` can +also name a gateway template that has no resource. + +Templates don't support warm pools in `v1alpha1`. The gateway creates a warm +pool from a template's startup settings, `ready_within` and `max_burst` +(), and a pool serves +only its own template. Templates without these settings have no pool, so old +revisions cost nothing. If a later `spec.startup` field adds them: + +- Only the latest revision has startup settings. When the controller + publishes a revision, it removes the settings from the previous one, and the + gateway drains that pool. Running sandboxes aren't affected. +- The controller deletes old revisions that no sandbox uses. +- A new revision starts with an empty pool, so frequent template changes + reduce the benefit of warm pools. + +**`OpenShellProvider`** declares a provider whose credentials and refresh +material come from Kubernetes Secrets. The resource never holds a value, and +its `type` can't change. ### Namespaces and workspaces -A namespace opts in with a label whose value names its gateway workspace: +A namespace opts in with a label whose value is its gateway workspace: ```shell kubectl label namespace agents openshell.ai/workspace=agents ``` -- **One controller serves every labeled namespace.** It watches namespaces - that carry the label, so a newly labeled namespace takes effect within - seconds. An optional extra label selector lets several controllers, one per - gateway, share a cluster. -- **Each workspace maps to one namespace.** If two namespaces carry the same - value, the namespace created first keeps the workspace, and resources in the - other report `WorkspaceConflict`. Kubernetes names are unique only within a - namespace, so two namespaces sharing a workspace could overwrite each - other's gateway objects. +- **One controller serves every labeled namespace.** It watches namespaces, so + a new label takes effect within seconds. An optional label selector lets + several controllers, one per gateway, share a cluster. +- **Each workspace has one namespace.** If two namespaces use the same + workspace, the one created first keeps it, and resources in the other + report `WorkspaceConflict`. Resource names are unique only within a + namespace, so two namespaces in one workspace could overwrite each other's + objects. - **The controller creates missing workspaces.** If the gateway lists the - controller's identity in `workspace_provisioners`, the controller becomes - the new workspace's manager. Onboarding a team then needs a label, not a - gateway configuration change or restart. -- **An admission policy enforces opt-in.** The chart ships a + controller in `workspace_provisioners`, the controller becomes the manager + of each workspace it creates. Adding a team then needs only a label, not a + gateway configuration change. +- **An admission policy enforces opt-in.** The chart includes a ValidatingAdmissionPolicy that rejects OpenShell resources in namespaces without a valid label. -- **Labeling a namespace is a privileged action.** The label decides which - workspace a namespace's resources reach. Clusters where tenants can label - their own namespaces should restrict who can set `openshell.ai/workspace`. +- **Labeling a namespace is privileged.** The label decides which workspace a + namespace's resources reach. If tenants can label their own namespaces, + restrict who can set `openshell.ai/workspace`. ### Workspace managers -Two gateway settings decide who can change a workspace's objects: +Two gateway settings control who can change a workspace's objects: ```toml [openshell.gateway] @@ -268,46 +254,42 @@ workspace_provisioners = ["mtls:openshell-k8s-controller"] agents = ["mtls:openshell-k8s-controller"] ``` -Each identity is written as `:`, the form the gateway's -authentication already produces. The subject is the client certificate CN for -`mtls`, and the token's `sub` claim for `oidc`. So -`mtls:openshell-k8s-controller` means "a caller that presented a client -certificate, issued by the gateway's CA, with `CN=openshell-k8s-controller`". -It isn't a Kubernetes ServiceAccount; see [Open questions](#open-questions) -for that option. - -In a managed workspace, only its managers can `create`, `delete`, `stop`, `start`, -`suspend`, `resume`, or `update` sandboxes; `attach` or `detach` providers; expose -services; `approve` or `edit` policy drafts; `create` or `delete` templates; and -`create`, `update`, or `delete` providers. Other authorized callers can still list -and inspect these objects, read logs, and run commands with `sandbox exec`. -Operators, and users with the configured admin role, keep an emergency stop -and delete. The controller then reports the sandbox as missing and doesn't -recreate it. - -- **The gateway enforces it by authenticated identity**, not by client type, - on every interface. -- **The setting is a list of identities, not a mode.** Several controllers, - for example one per cluster, can manage one workspace, and mixed managers - can follow later without a data migration. -- **A provisioned workspace records its manager** in the - `internal.openshell.ai/workspace-managers` annotation when the controller - creates it. A `workspace_managers` entry takes precedence. - `openshell workspace get` shows the effective managers, from a new - `managers` field on `Workspace`. -- **A workspace without an entry is gateway-managed** and works as it does - today. -- **Roles still apply.** The controller needs the workspace admin role to - manage templates and providers. - -The policy advisor's draft approvals change a running sandbox's policy, so the -manager check blocks them in a Kubernetes-managed workspace. To approve a rule -for a declared sandbox, add it to the sandbox's policy in Git. +Each identity has the form `:`, which the gateway's +authentication already uses. The subject is the client certificate CN for +`mtls` and the token's `sub` claim for `oidc`. So +`mtls:openshell-k8s-controller` is a caller with a client certificate, issued +by the gateway's CA, whose CN is `openshell-k8s-controller`. It isn't a +Kubernetes ServiceAccount; see [Open questions](#open-questions). + +In a managed workspace, only its managers can `create`, `delete`, `stop`, +`start`, `suspend`, `resume`, or `update` sandboxes; `attach` or `detach` +providers; expose services; `approve` or `edit` policy drafts; `create` or +`delete` templates; and `create`, `update`, or `delete` providers. Other users +can still list and inspect these objects, read logs, and run commands with +`sandbox exec`. Operators and users with the admin role can still stop or +delete a sandbox in an emergency. The controller then reports the sandbox as +missing and doesn't recreate it. + +- The gateway checks the caller's identity on every API, regardless of client. +- The setting is a list, so several controllers, for example one per cluster, + can manage one workspace, and mixed managers can be added later without a + data migration. +- When the controller creates a workspace, the gateway records the manager in + the `internal.openshell.ai/workspace-managers` annotation. A + `workspace_managers` entry overrides it. `openshell workspace get` shows the + managers, from a new `managers` field on `Workspace`. +- A workspace without managers works as it does today. +- Roles still apply. The controller needs the workspace admin role to manage + templates and providers. + +Approving a policy advisor draft changes a running sandbox's policy, so it's +blocked in a managed workspace. To allow a rule for a declared sandbox, add it +to the sandbox's policy in Git. ### Reconciliation, status, and deletion -The controller records its progress in each resource's status so that a crash, -restart, or leader change never duplicates or loses work. +The controller records its progress in each resource's status, so a crash, +restart, or leader change doesn't duplicate or lose work. ```mermaid sequenceDiagram @@ -326,116 +308,109 @@ sequenceDiagram C->>K: Remove finalizer ``` -- **Finalizers come first.** The controller adds its finalizer before any - gateway call, and removes it only after the gateway reports the object gone, - not when it accepts the delete. This also covers deleting the whole - namespace. -- **Requests are replayed, not repeated.** The controller records each - attempt in `status.journal` before sending it, and sends the same request ID - after a lost response or restart. -- **Deletes are pinned.** A new optional `expected_sandbox_id` on - `DeleteSandboxRequest` makes the gateway delete the sandbox only if its ID - matches. The controller never deletes a sandbox that replaced the one it - created. -- **`Ready` describes the declaration.** Each resource has a `Ready` - condition, `observedGeneration`, `phase`, and `reason`. A sandbox also - reports `sandboxId`, `templateRevision`, and an informational - `gatewayPhase`. A provisioned sandbox stays `Ready` while it's stopped, - suspended, or completed, so sleeping and waking never changes GitOps health. - Error and unknown phases block. Whether the agent works is a separate - condition, `Available`; see [Sandbox availability](#sandbox-availability). -- **Failures are visible.** Resources report reasons such as - `TemplateNotFound`, `PolicyInvalid`, `SecretNotFound`, `SecretsForbidden`, - `WorkspaceConflict`, `WorkspaceUnavailable`, `NamespaceNotEnabled`, and - `CreateRejected`, and the controller's `/readyz` endpoint reports problems - that an administrator must fix. -- **Status stays current without load.** While a sandbox starts or stops, the - controller follows the gateway's `WatchSandbox` stream, so `gatewayPhase` - updates within seconds. It checks settled sandboxes every 2 minutes, writes - status only when it changes, and reconciles at most 16 resources at a time. - A flag turns `gatewayPhase` off for zero status writes from sleep and wake. +- **Finalizers.** The controller adds its finalizer before calling the + gateway, and removes it only after the gateway object is gone. This also + applies when you delete the namespace. +- **Retries.** The controller records each request in `status.journal` before + sending it, and retries with the same request ID after a lost response or a + restart, so the gateway doesn't create a second object. +- **Safe deletes.** A new optional field, `expected_sandbox_id` on + `DeleteSandboxRequest`, makes the gateway delete the sandbox only if its ID + matches, so the controller never deletes a sandbox that replaced its own. +- **The `Ready` condition.** Each resource has a `Ready` condition, + `observedGeneration`, `phase`, and `reason`. A sandbox also reports + `sandboxId`, `templateRevision`, and `gatewayPhase`. `Ready` means the + gateway accepted the spec. It stays `True` while the sandbox is stopped, + suspended, or completed, so stopping a sandbox doesn't change GitOps health. + Error and unknown phases set it to `False`. Whether the agent is running is + a separate condition; see [Sandbox availability](#sandbox-availability). +- **Errors.** Resources report reasons such as `TemplateNotFound`, + `PolicyInvalid`, `SecretNotFound`, `SecretsForbidden`, `WorkspaceConflict`, + `WorkspaceUnavailable`, `NamespaceNotEnabled`, and `CreateRejected`. The + controller's `/readyz` endpoint reports problems an administrator must fix. +- **Load.** While a sandbox starts or stops, the controller follows the + gateway's `WatchSandbox` stream, so `gatewayPhase` updates within seconds. + It checks other sandboxes every 2 minutes, writes status only when it + changes, and reconciles at most 16 resources at a time. A flag turns off + `gatewayPhase`, so stopping and starting sandboxes causes no status writes. ### Sandbox availability -`Ready` means the gateway accepted the declared spec. It doesn't show that the -agent stays up: a process can start, crash, and restart, or run without the -policy or credentials it needs. Each `OpenShellSandbox` therefore has a second -condition, `Available`, the way a Deployment separates `Available` from -rollout progress. GitOps health checks read `Available` instead of `Ready`. +`Ready` doesn't show that the agent is running: a process can crash and +restart, or run without the policy or credentials it needs. Each +`OpenShellSandbox` has a second condition, `Available`, like a Deployment's. +GitOps health checks read `Available` instead of `Ready`. -The controller computes `Available` from the gateway's `WatchSandbox` stream, -which it already follows, so it adds no gateway calls and no polling for each -sandbox. `Available` is `True` when all of these hold: +The controller sets `Available` from the `WatchSandbox` stream it already +follows, so it adds no gateway calls. `Available` is `True` when: -- The sandbox is `READY`. +- The sandbox phase is `READY`. - `current_policy_version` matches the policy the controller applied. -- Every attached provider reports ready. -- Every endpoint in `endpoint_statuses`, which the gateway checks passively - for tool servers such as MCP over HTTP, last succeeded. +- Every attached provider is ready. +- Every endpoint in `endpoint_statuses` last succeeded. The gateway checks + these passively for tool servers, such as MCP over HTTP. - `restart_count` hasn't increased for `spec.minReadySeconds`, 30 seconds by default. -Otherwise it's `False` with a reason such as `CrashLooping`, -`PolicyNotLoaded`, `ProviderNotReady`, or `EndpointUnreachable`. The -controller keeps one timer for each sandbox inside its window and none after. -A stopped or suspended sandbox reports `Available=True` with reason `Stopped` -or `Suspended`, and a completed sandbox reports reason `Completed`, so sleep -and wake don't change application health. +Otherwise it's `False`, with a reason such as `CrashLooping`, +`PolicyNotLoaded`, `ProviderNotReady`, or `EndpointUnreachable`. A stopped, +suspended, or completed sandbox reports `True` with reason `Stopped`, +`Suspended`, or `Completed`, so stopping a sandbox doesn't change application +health. -`OpenShellSandboxTemplate` status reports, for its current revision, how many -sandboxes run it and how many are `Available`, so a GitOps tool can gate a -template change on the sandboxes that use it. +`OpenShellSandboxTemplate` status reports how many sandboxes run the latest +revision and how many of them are `Available`, so a GitOps tool can wait for +a template change to roll out. -Health checks read `Available` only when `observedGeneration` matches the -resource's generation. In Argo CD, that's a Lua health check; in Flux 2.5 and -later, a CEL expression in `healthCheckExprs`. A check that needs a real -request, such as a test prompt, belongs in a hook that runs once per -application, for example an Argo CD PostSync Job or a Flux post-deployment -test that calls `openshell sandbox exec`. +Health checks should read `Available` only when `observedGeneration` matches +the resource's generation: a Lua health check in Argo CD, or a CEL expression +in `healthCheckExprs` in Flux 2.5 and later. To test the agent with a real +request, such as a test prompt, run a hook once per application, for example +an Argo CD PostSync Job or a Flux post-deployment test that calls +`openshell sandbox exec`. ### Secrets -Kubernetes Secrets are the source of truth for credential values, typically -synced from a secret manager by the External Secrets Operator. +Kubernetes Secrets hold credential values, often synced from a secret manager +by the External Secrets Operator. 1. You store or rotate a value in a Secret in the team's namespace. -2. The controller reads it, for each `OpenShellProvider` that references it. -3. The controller sends it over the authenticated gateway connection when it - creates or updates the provider. The gateway stores its copy with its - configured credential driver: the database, Kubernetes Secrets, or Vault. +2. The controller reads it for each `OpenShellProvider` that references it. +3. The controller sends it to the gateway when it creates or updates the + provider. The gateway stores it with its configured credential driver: the + database, Kubernetes Secrets, or Vault. 4. The sandbox gets a placeholder. The sandbox proxy adds the real value only to requests that its policy allows, so the agent never sees it. -- **Access is granted per namespace.** The chart ships a ClusterRole for - reading Secrets with no ClusterRoleBinding. An administrator grants it in - each namespace with a RoleBinding, either through the chart's - `secretsNamespaces` value or with their own tooling. Labeling a namespace - never grants Secret access by itself. A namespace whose providers reference - no Secrets needs no RoleBinding. -- **Rotation reaches the gateway within seconds.** The controller watches - Secret metadata in namespaces whose providers reference Secrets, and - re-applies only the providers that reference a changed Secret. Provider - status records each Secret's resource version, never its value. -- **Values never leave their path.** Status, events, and errors don't include - values, and the controller never calls `RevealSecret`. -- **The controller's access to OpenShell resources is cluster-wide.** - Deleting a namespace deletes its RoleBindings in no particular order, so a - namespaced grant could disappear before the controller removed its +- **Access is granted per namespace.** The chart includes a ClusterRole for + reading Secrets, with no ClusterRoleBinding. An administrator grants it in + each namespace with a RoleBinding, through the chart's `secretsNamespaces` + value or other tooling. A label alone never grants Secret access, and a + namespace whose providers reference no Secrets needs no RoleBinding. +- **Rotation takes seconds.** The controller watches Secret metadata in + namespaces whose providers reference Secrets, and updates only the providers + that use a changed Secret. Provider status records each Secret's resource + version, never its value. +- **Values stay private.** Status, events, and errors never include values, + and the controller never calls `RevealSecret`. +- **Access to OpenShell resources is cluster-wide.** Deleting a namespace + deletes its RoleBindings in no particular order. If the controller's access + to its own resources were namespaced, it could lose it before removing its finalizers, and the namespace would never finish deleting. The cluster-wide - grant covers only `openshell.ai` resources and watching namespaces. Deleting - resources needs no Secrets. + grant covers only `openshell.ai` resources and namespaces. Deleting + resources doesn't need Secrets. -Shared refresh material, such as one OAuth client secret used by many -providers, belongs in workspace secrets from +Refresh material that many providers share, such as one OAuth client secret, +belongs in workspace secrets from [RFC 0024](../0024-workspace-secrets/README.md). A resource for them can follow once that RFC lands. ### Packaging and operations -The controller ships as a container image and a Helm chart that installs the -CRDs (kept on uninstall), the controller's RBAC, optional ClusterRoles for -platform engineers and developers, the admission policy, and a Deployment with -leader election, a readiness probe, and credential reload. The controller +The controller ships as a container image and a Helm chart. The chart installs +the CRDs, which it keeps on uninstall, the controller's RBAC, optional +ClusterRoles for platform engineers and developers, the admission policy, and +a Deployment with leader election and a readiness probe. The controller reloads rotated gateway credentials without a restart. ```shell @@ -446,103 +421,101 @@ helm install openshell-controller deploy/helm/openshell-k8s-controller \ --set "secretsNamespaces={agents}" kubectl label namespace agents openshell.ai/workspace=agents kubectl apply -f support-agent.yaml -kubectl wait ossbx/support-agent -n agents --for=condition=Ready -openshell sandbox exec --workspace agents --name support-agent -- echo hello +kubectl wait ossbx/support-agent -n agents --for=condition=Available ``` ## Implementation plan -The gateway changes and the controller are opt-in, so they can land -incrementally without changing behavior for existing users. A working -implementation, with tests and docs, is on +The gateway changes and the controller are opt-in, so they can land in steps +without changing behavior for existing users. A working implementation, with +tests and docs, is on [`feat/6073-k8s-sandbox-crd/JimBugwadia`](https://github.com/JimBugwadia/OpenShell/tree/feat/6073-k8s-sandbox-crd/JimBugwadia). -1. **Gateway.** Add `workspace_managers` and `workspace_provisioners`, the +1. **Gateway.** Add `workspace_managers`, `workspace_provisioners`, the `managers` field on `Workspace`, and `expected_sandbox_id` on `DeleteSandboxRequest`. Enforce managers for sandboxes, templates, and - providers. Document the settings in the gateway configuration reference and - mark them experimental. Test that only managers can change a managed - workspace and that unmanaged workspaces are unaffected. -2. **Controller crate.** Add `crates/openshell-k8s-controller` with the three - resources, the recovery journal, namespace opt-in, Secret handling, status - streams, the `Available` condition and template rollout status, leader - election, and credential reload. Unit-test reconciliation - against a mock gateway, including lost responses, restarts, rejected - immutable edits, and deletion. -3. **Packaging.** Add the controller image, the - `deploy/helm/openshell-k8s-controller` chart, and Helm tests for install, + providers. Document the settings in the gateway configuration reference as + experimental. Test that only managers can change a managed workspace and + that other workspaces are unaffected. +2. **Controller.** Add `crates/openshell-k8s-controller` with the three + resources, the request journal, namespace opt-in, Secret handling, status + streams, the `Available` condition, template rollout status, leader + election, and credential reload. Test reconciliation against a mock + gateway, including lost responses, restarts, rejected changes, and + deletion. +3. **Packaging.** Add the controller image and the + `deploy/helm/openshell-k8s-controller` chart, with Helm tests for install, leader failover, credential rotation, namespace opt-in, and readiness. 4. **Docs.** Add a Kubernetes sandbox resources page, image requirements, a walkthrough under `examples/`, the chart README, and rows in the `debug-openshell-cluster` skill. -5. **End-to-end validation.** Run the whole stack in a kind cluster with a - NetworkPolicy-enforcing network plugin, such as Cilium. Confirm that the - sandbox's workload pod can't open connections directly, that deleting a - namespace finishes and removes its gateway objects, and that Argo CD - reports sync, health, self-heal, and prune correctly. +5. **End-to-end tests.** Run the full stack in a kind cluster with a network + plugin that enforces NetworkPolicy, such as Cilium. Check that the + sandbox's workload pod can't connect out directly, that deleting a + namespace removes its gateway objects, and that Argo CD reports sync, + health, self-heal, and prune correctly. -Potential follow-ups after the first release: +Possible follow-ups after the first release: -- **Warm pools.** Template startup tuning, with the revision rules in +- **Warm pools.** Template startup settings, with the revision rules in [Resources](#resources). - **A read-only runtime view.** A `SandboxRuntime` resource in its own API group, such as `runtime.openshell.ai`, served by an aggregated API server - that reads live state from the gateway, the way metrics-server serves - `PodMetrics` next to Pods. It would show phase, restarts, endpoints, and - sandboxes that the controller doesn't manage, such as session sandboxes, - with no etcd writes, and would replace `gatewayPhase` in sandbox status. - - It's deferred because an aggregated API puts its server in the cluster's - discovery path. While the server is unavailable, discovery for its group - fails, clients that discover every group report errors, and namespace - deletion stalls with `NamespaceDeletionDiscoveryFailure` because the - namespace controller can't confirm the namespace is empty. CRDs avoid this - because kube-apiserver serves them. The view therefore needs: - - - At least two replicas, a PodDisruptionBudget, and anti-affinity, like - other critical cluster add-ons. - - Independence from the gateway: it keeps serving discovery, and returns a - stale or empty view with a condition instead of an error when the gateway - is unreachable, so a gateway outage doesn't become a cluster outage. - - Read-only access, which avoids admission and write semantics. - - Delegated authentication, authorization with SubjectAccessReview, and an + that reads live state from the gateway, like metrics-server serves + `PodMetrics`. It would show phase, restarts, endpoints, and sandboxes that + the controller doesn't manage, such as session sandboxes, without etcd + writes. It would replace `gatewayPhase`. + + It's deferred because an aggregated API server is in the cluster's + discovery path. While it's down, discovery for its API group fails, clients + that list all API groups report errors, and namespace deletion stops with + `NamespaceDeletionDiscoveryFailure`. CRDs don't have this problem, because + kube-apiserver serves them. The server would need: + + - At least two replicas, a PodDisruptionBudget, and anti-affinity. + - To keep serving when the gateway is down, returning stale or empty data + with a condition instead of an error. + - Read-only access, which avoids admission and writes. + - Delegated authentication, SubjectAccessReview authorization, and an exclusion for its API group in GitOps tools. - `Available` and `gatewayPhase` cover the first release's needs without - that commitment. + The first release doesn't need it: `Available` and `gatewayPhase` cover + status. -The API starts at `v1alpha1`, so field changes before `v1beta1` don't need -conversion webhooks. Graduating to `v1beta1` needs a load test that confirms -the etcd and gateway projections under [Risks](#risks). +The API starts at `v1alpha1`, so fields can change before `v1beta1` without +conversion webhooks. Moving to `v1beta1` needs a load test that confirms the +numbers in [Risks](#risks). ## Risks -- **Two copies of intent.** Kubernetes stores the declaration and the gateway - stores the applied state. In a managed workspace only the controller writes, - so each object has one writer, and status reports the revision that the - gateway accepted. An administrator's emergency stop or delete still makes - the two differ; the controller reports the difference instead of undoing it. +- **Two copies of the spec.** Kubernetes stores the declared spec, and the + gateway stores what it applied. In a managed workspace only the controller + writes, and status reports the revision the gateway accepted. An + administrator's emergency stop or delete still makes them differ; the + controller reports the difference instead of undoing it. - **Deletion depends on the controller.** Finalizers block deletion until the - controller removes the gateway object, so a controller outage stalls - namespace deletion. A rejected or never-submitted create releases its - finalizer without a gateway call, and the runbook documents manual recovery. - Removing a finalizer by hand leaves the gateway object behind. + controller removes the gateway object, so a controller outage blocks + namespace deletion. A create that the gateway rejected or never received + releases its finalizer without a gateway call, and the controller README + documents manual recovery. Removing a finalizer by hand leaves the gateway + object behind. - **The namespace label grants a workspace.** Anyone who can label namespaces - chooses which workspace their resources reach. Mitigations are the - one-namespace-per-workspace rule, the namespace selector, and admission - control on namespace labels. Secret access needs a separate RoleBinding. -- **etcd and gateway load.** The prototype stores about 2.8 KB per sandbox - resource, makes 7 Kubernetes writes from creation to `Ready`, and none while - `Ready`. 10,000 declared sandboxes would use about 28 MB of etcd and cause - about 83 gateway checks a second when settled. Each sandbox on the - Kubernetes driver already stores a Pod and an `agents.x-k8s.io/Sandbox` - object, so declarations are a small share. On-demand sandboxes stay off - Kubernetes. A load test must confirm these numbers. -- **Validation errors appear late.** Errors that only the gateway can detect, + chooses which workspace their resources reach. The one-namespace-per- + workspace rule, the label selector, and admission control on namespace + labels limit this. Secret access needs a separate RoleBinding. +- **etcd and gateway load.** The implementation stores about 2.8 KB per + sandbox resource and makes 7 Kubernetes writes from creation to `Ready`, + then none. 10,000 declared sandboxes would use about 28 MB of etcd and about + 83 gateway checks a second. Each sandbox on the Kubernetes driver already + has a Pod and an `agents.x-k8s.io/Sandbox` object, so this adds little. + On-demand sandboxes stay out of Kubernetes. A load test must confirm these + numbers. +- **Some errors appear after apply.** Errors that only the gateway detects, such as an invalid policy, appear as conditions rather than `kubectl apply` - failures. The CRD schema and CEL rules catch structural errors at admission. -- **A new component to support.** The project takes on a controller, a chart, - and a Kubernetes API with compatibility obligations once it leaves alpha. + failures. The CRD schema and CEL rules catch structural errors at + admission. +- **More to maintain.** The project takes on a controller, a chart, and a + Kubernetes API with compatibility commitments once it leaves alpha. ## Alternatives @@ -550,54 +523,50 @@ the etcd and gateway projections under [Risks](#risks). Proposed in . It stores nothing in etcd and has one source of truth. But a cluster can register only -one server for each API group and version, so it can't serve several gateways. -If the gateway is down, discovery and namespace deletion stall, and watch, -server-side apply, and admission need custom work. An aggregated server -remains a good fit for a read-only runtime view that shows live state with no -etcd writes, not for declared intent; see the follow-ups in +one server per API group and version, so it can't serve several gateways. If +the gateway is down, discovery and namespace deletion stop, and watch, +server-side apply, and admission need custom work. An aggregated server suits +a read-only runtime view, not the declared spec; see the follow-ups in [Implementation plan](#implementation-plan). ### The driver's `agents.x-k8s.io/Sandbox` objects -The Kubernetes driver already creates these objects. They describe pods, +The Kubernetes driver already creates these objects, but they describe pods, the driver owns them, and they exist only on the Kubernetes driver. They can't -carry policy, providers, or templates, and editing them would bypass the +hold policy, providers, or templates, and editing them would bypass the gateway. ### Running the CLI from CI, or doing nothing -Teams can keep calling the CLI from pipelines. This needs no new code, but it +Teams can keep calling the CLI from pipelines. This needs no new code, but gives no drift detection, self-heal, health, or admission policy, and keeps access control in the gateway instead of namespace RBAC. -### Native declarative apply in the gateway first +### Declarative apply in the gateway first -`openshell apply -f`, with the gateway owning recovery, would serve users -outside Kubernetes too. It needs new durable intent and revision tracking in -the gateway database. Current demand is Kubernetes GitOps, so this RFC keeps -recovery in the controller. If native apply arrives, the gateway can take over -recovery from the controller instead of both owning it, without changing the -resources. +`openshell apply -f`, with the gateway handling retries, would also serve +users outside Kubernetes. It needs the gateway database to store declared +specs and revisions. Current demand is Kubernetes GitOps, so this RFC keeps +that work in the controller. If the gateway adds declarative apply later, it +can take over retries from the controller without changing the resources. ## Prior art -- **Kubernetes operators and controllers**, such as cert-manager and Crossplane - providers, declare external resources as custom resources and reconcile them - through the external system's API, with finalizers that guard cleanup. This - RFC follows the same pattern, including status conditions that GitOps tools - already understand. -- **metrics-server** serves `PodMetrics` through API aggregation next to Pods - that etcd stores. It's the model for a later read-only runtime view, and - shows why intent and live state are better split across two APIs. +- **Kubernetes operators**, such as cert-manager and Crossplane providers, + declare external resources as custom resources and reconcile them through + the external system's API, with finalizers that guard cleanup. This RFC + follows the same pattern and uses status conditions that GitOps tools read. +- **metrics-server** serves `PodMetrics` through API aggregation alongside the + Pods that etcd stores. It's the model for the runtime view follow-up, which + keeps live state separate from the declared spec. - **Argo CD and Flux health checks** read conditions and - `observedGeneration`. Designing status around them makes sync, health, - self-heal, and prune work with a short health check. -- **Deployment's `Available` condition and `minReadySeconds`** separate a - rollout that's progressing from one whose Pods stayed ready long enough to - count. `Available` on a sandbox follows the same split. -- **[RFC 0024](../0024-workspace-secrets/README.md)** introduces workspace - secrets for shared refresh material. This RFC leaves shared refresh material - to it. + `observedGeneration`, so sync, health, self-heal, and prune need only a + short health check. +- **Deployments** separate a rollout in progress from `Available` Pods that + stayed ready for `minReadySeconds`. `Available` on a sandbox works the same + way. +- **[RFC 0024](../0024-workspace-secrets/README.md)** adds workspace secrets + for shared refresh material. This RFC leaves shared refresh material to it. ## Open questions @@ -607,17 +576,16 @@ resources. `k8s:system:serviceaccount:openshell-controller:openshell-k8s-controller` in `workspace_managers`. This works only when the gateway runs in the same cluster. -- Should mixed managers within one workspace follow, letting a session service - and the controller share a workspace? Which use cases justify the - per-operation ownership rules that it needs? +- Should a session service and the controller be able to manage the same + workspace? Which use cases justify the per-object ownership rules this + needs? - When should policy get its own resource, and should teams share policies - across namespaces the way they would share templates? -- Should template references across namespaces follow, so platform teams can - publish shared templates from a namespace they control? Only templates from - listed namespaces would be allowed to set placement. + across namespaces? +- Should templates be shareable across namespaces, so platform teams can + publish them from a namespace they control? Only templates from listed + namespaces would be allowed to set placement. - Do agents need a readiness probe that the supervisor runs inside the - sandbox, beyond stability, endpoint status, and delivery hooks? It would - test the agent rather than its process, but needs a template field, + sandbox? It would test the agent itself, but needs a template field, supervisor support, and a gateway condition. -- Should a sandbox set with a replica count follow for interchangeable - workers, and how would a new template revision reach existing members? +- Should a sandbox set with a replica count be added for identical workers, + and how would a new template revision reach existing members? From 14d041d6d90b4b9899004fefcfc0807b56972398 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 21:35:53 -0800 Subject: [PATCH 7/8] docs(rfc): move RFC 0030 to review Signed-off-by: Jim Bugwadia --- rfc/0030-kubernetes-sandbox-resources/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index c140568212..d21b4cbb60 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -1,7 +1,7 @@ --- authors: - "@JimBugwadia" -state: draft +state: review links: - https://github.com/ai-openshell/openshell/issues/6073 - https://github.com/ai-openshell/openshell/issues/5062 From cc30cd91e22723e8a4f2b90b49da0903cf2dc902 Mon Sep 17 00:00:00 2001 From: Jim Bugwadia Date: Tue, 1 Dec 2026 21:39:22 -0800 Subject: [PATCH 8/8] docs(rfc): link the RFC 0030 pull request Signed-off-by: Jim Bugwadia --- rfc/0030-kubernetes-sandbox-resources/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/rfc/0030-kubernetes-sandbox-resources/README.md b/rfc/0030-kubernetes-sandbox-resources/README.md index d21b4cbb60..17a634229d 100644 --- a/rfc/0030-kubernetes-sandbox-resources/README.md +++ b/rfc/0030-kubernetes-sandbox-resources/README.md @@ -9,6 +9,7 @@ links: - https://github.com/ai-openshell/openshell/issues/5847 - https://github.com/ai-openshell/openshell/issues/3362 - https://github.com/ai-openshell/openshell/pull/5518 + - https://github.com/ai-openshell/openshell/pull/6149 --- # RFC 0030 - Kubernetes Resources for Sandboxes, Templates, and Providers