Files
paperclip/packages/plugins/sandbox-providers/kubernetes/src/tenant-orchestrator.ts
T
Jannes Stubbemann 05ab45225a feat(plugin-kubernetes): self-hostable Kubernetes sandbox provider (stage 1/3: plugin package) (#5790)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Sandbox providers are the seam that lets agent runs execute in
isolated environments; today the only first-party remote provider is
Daytona, a hosted third-party service
> - Self-hosters running Paperclip on their own infrastructure (often
Kubernetes already) have no first-party way to run agent sandboxes on a
cluster they control
> - That gap matters for teams with data-residency, sovereignty, or cost
constraints who cannot or will not send workloads to a hosted sandbox
service
> - This pull request adds a Kubernetes sandbox-provider plugin as a
standalone, workspace-excluded package: it implements every
SandboxProvider hook the Daytona provider does, on infrastructure the
operator owns
> - The benefit is that any Paperclip deployment with a Kubernetes
cluster gets multi-tenant, network-isolated, quota-bounded agent
sandboxes with zero new external dependencies

## Linked Issues or Issue Description

No existing issue. Following the feature template:

- **Problem:** Paperclip's remote sandbox execution requires a hosted
third-party provider. Self-hosters cannot run agent sandboxes on their
own Kubernetes clusters with a first-party provider.
- **Proposed solution:** A `@paperclipai/plugin-kubernetes`
sandbox-provider plugin with two backends: long-lived sandboxes via the
[kubernetes-sigs/agent-sandbox](https://github.com/kubernetes-sigs/agent-sandbox)
CRD (multi-command exec, adapter-install pattern) and one-shot
`batch/v1` Jobs (stable APIs only, no extra controllers).
- **Alternatives considered:** Driving kubectl from a generic shell
provider (no lifecycle/lease semantics), or requiring a hosted provider
(exactly the constraint this removes).

## What Changed

This is **stage 1 of 3** of a staged contribution (direction agreed with
maintainers): the plugin package alone. Stage 2 (server integration:
lease params, provider registration) and stage 3 (agent runtime images +
CI) are companion PRs that will be cross-linked from a comment here.

- New package `packages/plugins/sandbox-providers/kubernetes`
(workspace-excluded, like the path already carved out in
`pnpm-workspace.yaml`): src, unit + kind integration tests, operator
prerequisite manifests, README, smoke-test guide
- Implements the full SandboxProvider hook surface the Daytona provider
implements: `validateConfig`, `probe`, `acquireLease`, `resumeLease`,
`releaseLease`, `destroyLease`, `realizeWorkspace`, `execute`
- Two backends: `sandbox-cr` (default; long-lived pod via the
agent-sandbox `Sandbox` CR, supports multi-command exec) and `job`
(one-shot `batch/v1` Job; nothing beyond k8s 1.27+ required)
- Per-run adapter resolution: one environment serves mixed harnesses;
the per-run `adapterType` hint is read through a local optional type
extension, so the plugin typechecks and builds against the current
plugin SDK and simply falls back to the environment's configured default
adapter until stage 2 lands
- Exec-env wrapping: the Kubernetes exec API carries no environment, so
commands are wrapped to receive the run's env
- Fast-upload interception for workspace realization, scoped per lease
- Per-tenant isolation: derived namespace per company, RBAC,
ResourceQuota, restricted-PSS pod security (runAsNonRoot, drop ALL,
seccomp RuntimeDefault, no SA token automount)
- Network egress policy in two flavors: native `NetworkPolicy` and
`CiliumNetworkPolicy` (FQDN allowlists)
- Image allowlist with glob matching, registry override, and per-run
image override validation
- Per-run Kubernetes Secrets carrying agent credentials, ownerRef'd to
the Job or Sandbox CR for cascade GC

## Verification

- Standalone build, exactly as the README documents:
  ```bash
  cd packages/plugins/sandbox-providers/kubernetes
  pnpm install --ignore-workspace
  pnpm test        # 147 unit tests, 17 files, all green
  pnpm typecheck   # clean against the in-repo plugin SDK on master
pnpm build # dist/ emitted, manifest + worker entrypoints present
  ```
- A kind-cluster end-to-end integration test is included
(`RUN_K8S_INTEGRATION_TESTS=1 pnpm test
test/integration/end-to-end-run.test.ts`)
- Beyond CI: this provider has been verified in a production
multi-tenant deployment against five harnesses (opencode, pi, codex,
gemini, claude code) with real billed runs

## Risks

- **Zero behavior change for any existing deployment.** The package is
workspace-excluded; nothing in the server imports or loads it until
stage 2's integration lands. No existing code paths are touched.
- The default `sandbox-cr` backend depends on an alpha CRD
(`agents.x-k8s.io/v1alpha1`); the README flags this and the `job`
backend uses only stable APIs as a fallback.
- Risk surface is confined to deployments that explicitly install and
configure the plugin.
- The default runtime images (`ghcr.io/paperclipai/agent-runtime-*`) are
published by the stage 3 companion PR (#7934); until that lands,
deployments must point `runtimeImage` at their own images.

## Model Used

Claude Opus 4.8 (1M context), extended thinking, with tool use (Claude
Code).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots (no UI changes)
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green (pending this push)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 21:07:00 -07:00

300 lines
10 KiB
TypeScript

import type { KubeClients } from "./kube-client.js";
import { buildNetworkPolicyManifests } from "./network-policy.js";
import { buildCiliumNetworkPolicyManifest } from "./cilium-network-policy.js";
export interface EnsureTenantInput {
namespace: string;
companyId: string;
paperclipServerNamespace: string;
serviceAccountAnnotations: Record<string, string>;
egressMode: "standard" | "cilium";
egressAllowFqdns: string[];
egressAllowCidrs: string[];
resourceQuota: {
pods: string;
requestsCpu: string;
requestsMemory: string;
limitsCpu: string;
limitsMemory: string;
};
}
const SERVICE_ACCOUNT_NAME = "paperclip-tenant-sa";
const ROLE_NAME = "paperclip-tenant-role";
const ROLE_BINDING_NAME = "paperclip-tenant-rb";
const RESOURCE_QUOTA_NAME = "paperclip-quota";
const LIMIT_RANGE_NAME = "paperclip-limits";
/**
* Lazy, first-write-wins tenant provisioning. Each helper checks if the named
* resource exists and creates it only on 404; if it already exists, it is
* left as-is — config-driven values (quota limits, RBAC permissions, network
* policies, egress allow-list) are FROZEN at first provisioning time.
*
* V1 limitation: changing KubernetesProviderConfig after a tenant namespace
* is provisioned does NOT update the in-cluster resources. To apply config
* changes, an operator must delete the per-tenant resources manually (or
* the namespace itself). A future iteration should add strategic-merge
* reconciliation here.
*
* Particular gotcha: switching egressMode "standard" → "cilium" leaves the
* old paperclip-egress-allow NetworkPolicy in place alongside the new
* CiliumNetworkPolicy. Both apply; the effective egress is the intersection.
*/
export async function ensureTenant(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
await ensureNamespace(clients, input);
await ensureServiceAccount(clients, input);
await ensureRole(clients, input);
await ensureRoleBinding(clients, input);
await ensureResourceQuota(clients, input);
await ensureLimitRange(clients, input);
await ensureNetworkPolicies(clients, input);
}
async function ensureNamespace(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.core.readNamespace({ name: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.core.createNamespace({
body: {
apiVersion: "v1",
kind: "Namespace",
metadata: {
name: input.namespace,
labels: {
"paperclip.io/company-id": input.companyId,
"paperclip.io/managed-by": "paperclip-k8s-plugin",
"pod-security.kubernetes.io/enforce": "restricted",
"pod-security.kubernetes.io/audit": "restricted",
"pod-security.kubernetes.io/warn": "restricted",
},
},
},
}),
);
}
async function ensureServiceAccount(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.core.readNamespacedServiceAccount({ name: SERVICE_ACCOUNT_NAME, namespace: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.core.createNamespacedServiceAccount({
namespace: input.namespace,
body: {
apiVersion: "v1",
kind: "ServiceAccount",
metadata: {
name: SERVICE_ACCOUNT_NAME,
namespace: input.namespace,
annotations: input.serviceAccountAnnotations,
labels: { "paperclip.io/managed-by": "paperclip-k8s-plugin" },
},
},
}),
);
}
async function ensureRole(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.rbac.readNamespacedRole({ name: ROLE_NAME, namespace: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.rbac.createNamespacedRole({
namespace: input.namespace,
body: {
apiVersion: "rbac.authorization.k8s.io/v1",
kind: "Role",
metadata: { name: ROLE_NAME, namespace: input.namespace },
rules: [
{ apiGroups: [""], resources: ["pods/log"], verbs: ["get"] },
],
},
}),
);
}
async function ensureRoleBinding(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.rbac.readNamespacedRoleBinding({ name: ROLE_BINDING_NAME, namespace: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.rbac.createNamespacedRoleBinding({
namespace: input.namespace,
body: {
apiVersion: "rbac.authorization.k8s.io/v1",
kind: "RoleBinding",
metadata: { name: ROLE_BINDING_NAME, namespace: input.namespace },
roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "Role", name: ROLE_NAME },
subjects: [{ kind: "ServiceAccount", name: SERVICE_ACCOUNT_NAME, namespace: input.namespace }],
},
}),
);
}
async function ensureResourceQuota(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.core.readNamespacedResourceQuota({ name: RESOURCE_QUOTA_NAME, namespace: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.core.createNamespacedResourceQuota({
namespace: input.namespace,
body: {
apiVersion: "v1",
kind: "ResourceQuota",
metadata: { name: RESOURCE_QUOTA_NAME, namespace: input.namespace },
spec: {
hard: {
pods: input.resourceQuota.pods,
"requests.cpu": input.resourceQuota.requestsCpu,
"requests.memory": input.resourceQuota.requestsMemory,
"limits.cpu": input.resourceQuota.limitsCpu,
"limits.memory": input.resourceQuota.limitsMemory,
},
},
},
}),
);
}
async function ensureLimitRange(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
try {
await clients.core.readNamespacedLimitRange({ name: LIMIT_RANGE_NAME, namespace: input.namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.core.createNamespacedLimitRange({
namespace: input.namespace,
body: {
apiVersion: "v1",
kind: "LimitRange",
metadata: { name: LIMIT_RANGE_NAME, namespace: input.namespace },
spec: {
limits: [
{
type: "Container",
max: { cpu: "4", memory: "8Gi" },
min: { cpu: "100m", memory: "128Mi" },
// The k8s client-node type names this `_default` but the actual
// Kubernetes API field is `default`. We produce a JSON-shape
// manifest so the cast is safe.
default: { cpu: "1", memory: "2Gi" },
defaultRequest: { cpu: "250m", memory: "512Mi" },
},
],
},
} as never,
}),
);
}
async function ensureNetworkPolicies(clients: KubeClients, input: EnsureTenantInput): Promise<void> {
const [denyAll, egressStd] = buildNetworkPolicyManifests({
namespace: input.namespace,
paperclipServerNamespace: input.paperclipServerNamespace,
egressAllowCidrs: input.egressAllowCidrs,
egressAllowFqdns: input.egressAllowFqdns,
});
await ensureNetworkPolicy(clients, input.namespace, denyAll);
if (input.egressMode === "cilium") {
const cnp = buildCiliumNetworkPolicyManifest({
namespace: input.namespace,
paperclipServerNamespace: input.paperclipServerNamespace,
egressAllowFqdns: input.egressAllowFqdns,
egressAllowCidrs: input.egressAllowCidrs,
});
await ensureCiliumNetworkPolicy(clients, input.namespace, cnp);
} else {
await ensureNetworkPolicy(clients, input.namespace, egressStd);
}
}
async function ensureNetworkPolicy(
clients: KubeClients,
namespace: string,
manifest: Record<string, unknown>,
): Promise<void> {
const name = (manifest.metadata as { name: string }).name;
try {
await clients.networking.readNamespacedNetworkPolicy({ name, namespace });
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.networking.createNamespacedNetworkPolicy({ namespace, body: manifest as never }),
);
}
async function ensureCiliumNetworkPolicy(
clients: KubeClients,
namespace: string,
manifest: Record<string, unknown>,
): Promise<void> {
const name = (manifest.metadata as { name: string }).name;
try {
await clients.custom.getNamespacedCustomObject({
group: "cilium.io",
version: "v2",
namespace,
plural: "ciliumnetworkpolicies",
name,
});
return;
} catch (err) {
if (!isNotFound(err)) throw err;
}
await createIgnoringAlreadyExists(
clients.custom.createNamespacedCustomObject({
group: "cilium.io",
version: "v2",
namespace,
plural: "ciliumnetworkpolicies",
body: manifest,
}),
);
}
function isNotFound(err: unknown): boolean {
if (typeof err !== "object" || err === null) return false;
const e = err as { code?: number; statusCode?: number };
return e.code === 404 || e.statusCode === 404;
}
function isAlreadyExists(err: unknown): boolean {
if (typeof err !== "object" || err === null) return false;
const e = err as { code?: number; statusCode?: number };
return e.code === 409 || e.statusCode === 409;
}
// Two concurrent lease acquisitions for a brand-new tenant can both observe
// the 404 read and race the create; a 409 AlreadyExists from the loser means
// the desired state already exists, which is exactly what ensure* wants.
async function createIgnoringAlreadyExists(create: Promise<unknown>): Promise<void> {
try {
await create;
} catch (err) {
if (!isAlreadyExists(err)) throw err;
}
}