diff --git a/.env.example b/.env.example index 37c9185d4e..53063f75a0 100644 --- a/.env.example +++ b/.env.example @@ -313,28 +313,52 @@ ALLOW_UNVERIFIED_EMAILS=1 # SLACK_WORKBENCH_TENANT_SLUG= # SLACK_DEFAULT_AGENT_DEFINITION_ID= -# Exclusive per-workbench sidecar placement (CL-6096, CL-6283). Leave unset -# (the default) to keep every workbench on the hub's current single shared -# sidecar, with no exclusive-placement backend registered — a workbench's -# "run this workbench on its own sidecar" setting still saves, but exclusive -# deployments fail closed until a provisioner is configured here. +# Exclusive per-workbench sidecar placement (CL-6096, CL-6283, CL-6534). +# Leave unset (the default) and the hub registers the "process" backend +# alone: each exclusive sidecar runs as one apps/sidecar child process on +# the hub's own host, so a single server hosts many chats and workflows +# with no configuration, no container runtime, and no sandbox account. # -# SIDECAR_PROVISIONERS is a comma-separated list of backend ids to register, -# e.g. "docker" (each id has its own required settings below it — "docker" -# needs DOCKER_PROVISIONER_IMAGE). SIDECAR_DEFAULT_PROVISIONER picks which -# listed id exclusive placements provision on; optional when exactly one id -# is listed, required when listing more than one. -# SIDECAR_PROVISIONERS=docker -# SIDECAR_DEFAULT_PROVISIONER=docker +# SIDECAR_PROVISIONERS is a comma-separated list of backend ids to +# register. Setting it replaces the default entirely — list "process" too +# if you want it alongside another backend. Supported ids: +# +# process same host, one child process per allocation (the default). +# No required settings. Process isolation only: sidecars share +# the hub's kernel, filesystem, and user account. +# docker one container per allocation via the local docker CLI. +# Requires DOCKER_PROVISIONER_IMAGE. +# e2b one remote E2B sandbox per allocation. Requires E2B_API_KEY +# and E2B_TEMPLATE (see packages/e2b-sandbox-sidecar/README.md). +# +# SIDECAR_DEFAULT_PROVISIONER picks which listed id exclusive placements +# provision on; optional when exactly one id is listed, required when +# listing more than one. +# +# Adding another backend is three steps, no hub surgery: implement +# SidecarProvisioner in its own package (copy packages/process-provisioner +# — the allocation lifecycle itself comes from @corbits/sandbox-sidecar), +# add its id to SIDECAR_PROVISIONER_IDS in apps/hub/src/config.ts, and add +# a case to buildSidecarProvisioner in apps/hub/src/index.ts. +# SIDECAR_PROVISIONERS=process +# SIDECAR_DEFAULT_PROVISIONER=process # DOCKER_PROVISIONER_IMAGE= +# Overrides for the "process" backend, both optional. Unset, it spawns +# this repository's own apps/sidecar/src/index.ts with the bun binary +# running the hub — which is why the default install needs no settings. +# Set these to run a sidecar build from somewhere else on the host. +# PROCESS_PROVISIONER_SIDECAR_ENTRY=/opt/workbench/apps/sidecar/src/index.ts +# PROCESS_PROVISIONER_RUNTIME=/usr/local/bin/bun + # HUB_SIDECAR_WEBSOCKET_URL overrides the ws(s):// address a provisioned # sidecar dials back to reach this hub. Leave unset to derive it from # BASE_URL — fine when the hub and its sidecars can reach each other at -# that address. Set this explicitly whenever SIDECAR_PROVISIONERS includes -# "docker": a docker sidecar container's own "localhost" is itself, not the -# hub host, so BASE_URL's derived ws:// URL cannot reach the hub from -# inside it. +# that address, which is always true for the "process" backend (a child +# process on the hub's own host). Set this explicitly whenever +# SIDECAR_PROVISIONERS includes "docker" or "e2b": a container's own +# "localhost" is itself, not the hub host, and an E2B sandbox is a remote +# machine that needs a publicly reachable wss:// URL or tunnel. # HUB_SIDECAR_WEBSOCKET_URL= # SIDECAR_ADAPTER_MANIFEST configures custom Interchange inference adapters diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md index 20729e9895..32d359e887 100644 --- a/IMPLEMENTATION.md +++ b/IMPLEMENTATION.md @@ -110,6 +110,14 @@ Deployment is explicit via **Pulumi**, targeting **Railway**. CI runs tests only — nothing auto-deploys on `main`; a deploy is a deliberate, separate action. +**Where sidecars run** is one variable, `SIDECAR_PROVISIONERS`. Unset — +the default — the hub registers the `process` backend alone and runs each +exclusive sidecar as a child process on its own host, so a single-server +install works with no configuration. `docker` and `e2b` are the other +shipped backends. See +[docs/sidecar-provisioners.md](docs/sidecar-provisioners.md) for the +comparison, the required settings per backend, and how to add another. + ## Workbench Definition (shipped) `WorkbenchDefinition` (`WorkbenchDefinitionSchema` in diff --git a/apps/hub/package.json b/apps/hub/package.json index a8a4ea709e..2aa504213c 100644 --- a/apps/hub/package.json +++ b/apps/hub/package.json @@ -38,6 +38,7 @@ "@corbits/notify": "workspace:*", "@corbits/preferences": "workspace:*", "@corbits/presence": "workspace:*", + "@corbits/process-provisioner": "workspace:*", "@corbits/run-key-history": "workspace:*", "@corbits/run-scope": "workspace:*", "@corbits/sidecar-placement": "workspace:*", diff --git a/apps/hub/src/config.ts b/apps/hub/src/config.ts index 01e3118857..d9fdad334a 100644 --- a/apps/hub/src/config.ts +++ b/apps/hub/src/config.ts @@ -194,11 +194,17 @@ const HubEnv = type({ "opt-in to initialize hub git-on-disk state inside a directory that is already a git work tree; refused by default because a nested init that misses its own .git walks up and commits onto the enclosing working branch", ), "SIDECAR_PROVISIONERS?": type("string").describe( - "comma-separated sidecar-allocation backend ids to register for workbenches placed on their own exclusive sidecar, e.g. 'docker'; unset or empty (default) keeps the hub on its current single shared sidecar with no exclusive-placement backend available", + "comma-separated sidecar-allocation backend ids to register for workbenches placed on their own exclusive sidecar: 'process' (a child process on this host), 'docker', or 'e2b'; unset or empty (default) registers 'process' alone, so a single-server install provisions exclusive sidecars with no operator configuration", ), "SIDECAR_DEFAULT_PROVISIONER?": type("string > 0").describe( "which id listed in SIDECAR_PROVISIONERS is the default backend exclusive placements provision on; required when SIDECAR_PROVISIONERS lists more than one id, optional (defaults to that one id) when it lists exactly one", ), + "PROCESS_PROVISIONER_SIDECAR_ENTRY?": type("string > 0").describe( + "the sidecar entry point the process backend spawns for each exclusive allocation; unset (default) resolves this repository's own apps/sidecar/src/index.ts", + ), + "PROCESS_PROVISIONER_RUNTIME?": type("string > 0").describe( + "the executable the process backend runs that entry point with; unset (default) reuses the bun binary running the hub", + ), "E2B_API_KEY?": type("string > 0").describe( "the E2B API key the e2b sidecar provisioner authenticates with; required when SIDECAR_PROVISIONERS includes 'e2b'", ), @@ -304,10 +310,22 @@ export type E2BSidecarProvisionerConfig = { readonly sandboxTimeoutMs?: string; }; +/** The default backend: one `apps/sidecar` child process per allocation + * on this host. It needs no operator settings at all — an unconfigured + * install gets it — and both env keys below are overrides for an operator + * running a sidecar build from somewhere other than this repository. */ +export type ProcessSidecarProvisionerConfig = { + readonly id: "process"; + readonly sidecarEntryPath?: string; + readonly runtimePath?: string; +}; + export type SidecarProvisionerConfig = - DockerSidecarProvisionerConfig | E2BSidecarProvisionerConfig; + | ProcessSidecarProvisionerConfig + | DockerSidecarProvisionerConfig + | E2BSidecarProvisionerConfig; -const SIDECAR_PROVISIONER_IDS = ["docker", "e2b"] as const; +const SIDECAR_PROVISIONER_IDS = ["process", "docker", "e2b"] as const; type SidecarProvisionerId = (typeof SIDECAR_PROVISIONER_IDS)[number]; function isSidecarProvisionerId(value: string): value is SidecarProvisionerId { @@ -368,12 +386,11 @@ export type HubConfig = { * production cadence (`routine-scheduler.ts`'s own default). */ readonly routineSchedulerPollIntervalMs?: number; /** Every sidecar-allocation backend registered for exclusive placement, - * zero or more, each addressable by its provisioner id. Empty when - * unconfigured — the registry then holds no provisioners and every - * exclusive placement fails closed at deployment time. */ + * one or more, each addressable by its provisioner id. Never empty: an + * install that configures nothing registers the `process` backend, so + * exclusive placement works on a single server out of the box. */ readonly sidecarProvisioners: readonly SidecarProvisionerConfig[]; - /** Which registered id exclusive placements provision on. Undefined - * exactly when `sidecarProvisioners` is empty. */ + /** Which registered id exclusive placements provision on. */ readonly defaultSidecarProvisionerId?: string; /** Overrides the ws(s):// URL a provisioned sidecar dials back to reach * this hub. Unset derives it from baseUrl instead. */ @@ -470,11 +487,13 @@ type SidecarProvisionersConfig = { * backend's own required settings (e.g. `DOCKER_PROVISIONER_IMAGE` for * `docker`) must be present, and an unknown id, a duplicate id, or a * `SIDECAR_DEFAULT_PROVISIONER` naming a backend that isn't listed all - * fail boot loudly — never silently falling back to the no-provisioner - * default. With `SIDECAR_PROVISIONERS` unset or empty, this returns no - * provisioners and no default, so every exclusive placement fails - * closed at deployment time rather than falling back to the shared - * sidecar. + * fail boot loudly. With `SIDECAR_PROVISIONERS` unset or empty, the + * `process` backend is registered as the sole default: an operator who + * configures nothing gets exclusive sidecar placement on the hub's own + * host, which is what makes a single-server install work with many + * chats and workflows on one VPS. Choosing where sidecars run is then + * one variable — `SIDECAR_PROVISIONERS` — and listing it explicitly + * (including `process`) behaves exactly as any other explicit list. */ function sidecarProvisionersFrom( parsed: ParsedHubEnv, @@ -493,7 +512,10 @@ function sidecarProvisionersFrom( ].join("\n"), ); } - return { provisioners: [] }; + return { + provisioners: [sidecarProvisionerConfigFor("process", parsed)], + defaultProvisionerId: "process", + }; } const seen = new Set(); @@ -547,6 +569,16 @@ function sidecarProvisionerConfigFor( parsed: ParsedHubEnv, ): SidecarProvisionerConfig { switch (id) { + case "process": + return { + id: "process", + ...(parsed.PROCESS_PROVISIONER_SIDECAR_ENTRY === undefined + ? {} + : { sidecarEntryPath: parsed.PROCESS_PROVISIONER_SIDECAR_ENTRY }), + ...(parsed.PROCESS_PROVISIONER_RUNTIME === undefined + ? {} + : { runtimePath: parsed.PROCESS_PROVISIONER_RUNTIME }), + }; case "docker": { if (parsed.DOCKER_PROVISIONER_IMAGE === undefined) { throw new Error( diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 66495f6e45..f64981ec3a 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -221,8 +221,8 @@ import { createSessionService, createSidecarAllocationReconciler, createSidecarPluginRegistry, + createSidecarCredentialResolver, createSidecarRouter, - createSidecarTokenAuthenticator, createWorkflowAllocationService, createWorkflowDispatchService, DEFAULT_ASSET_REF, @@ -251,6 +251,10 @@ import { createTenantGrantLister, } from "./grant-allowance"; import { createDockerSidecarProvisioner } from "@corbits/docker-provisioner"; +import { + createProcessSidecarProvisioner, + readProcessProvisionerConfig, +} from "@corbits/process-provisioner"; import { getArtifact, writeArtifactVersion } from "@corbits/artifacts"; import { createArtifactDbStore, @@ -527,8 +531,30 @@ export function hubCredentialCipher( function buildSidecarProvisioner( config: SidecarProvisionerConfig, hubDataDir: string, + hubWebSocketUrl: string, ): SidecarProvisioner { switch (config.id) { + case "process": + // Same derivation as the other two backends: the hub-side + // allocation state lives under the hub's own data dir, and so do + // the per-allocation directories each spawned sidecar uses as its + // own SIDECAR_DATA_DIR. + return createProcessSidecarProvisioner({ + config: readProcessProvisionerConfig({ + env: { + ...(config.sidecarEntryPath === undefined + ? {} + : { + PROCESS_PROVISIONER_SIDECAR_ENTRY: config.sidecarEntryPath, + }), + ...(config.runtimePath === undefined + ? {} + : { PROCESS_PROVISIONER_RUNTIME: config.runtimePath }), + }, + dataDir: path.resolve(hubDataDir, "process-provisioner"), + hubWebSocketUrl, + }), + }); case "docker": return createDockerSidecarProvisioner({ config: { @@ -780,9 +806,20 @@ export async function createHub(config: HubConfig) { )) !== null; const pinnedPackageCredentialBindingsFor = createPinnedPackageCredentialBindingsFor(isConnectorConnected); + // One resolver serves both seams, exactly as @intx/hub-sessions's own + // reference host wires them: `resolve` turns a presented bearer token + // into a verified identity at the handshake, and `isCurrent` + // revalidates that identity at the registration, readiness, and + // routing boundaries. Without the second one the router falls back to + // its always-true default, and a provisioner-issued token stays + // accepted after its allocation was superseded or destroyed — which a + // process-provisioned sidecar reaches easily, since a child that + // outlives its allocation keeps reconnecting to the same hub. + const sidecarCredentials = createSidecarCredentialResolver({ db }); const sidecarRouter = createSidecarRouter({ hubPublicKey, - authenticateSidecar: createSidecarTokenAuthenticator({ db }), + authenticateSidecar: async ({ token }) => sidecarCredentials.resolve(token), + validateSidecarIdentity: sidecarCredentials.isCurrent, lookups, }); // A finalized turn's persisted-artifact tool-call results become @@ -946,20 +983,26 @@ export async function createHub(config: HubConfig) { }), workflowDeploySourceStore, ); + const hubWebSocketUrl = + config.sidecarWebSocketUrl ?? + `${config.baseUrl.replace(/^http/, "ws")}/api/sidecars/ws`; // Provisioner plugins are injected at the application composition - // boundary, mirroring @intx/hub-sessions's own reference wiring: the - // registry always exists, but ships with no provisioners (and no - // default) until SIDECAR_PROVISIONERS names one or more builds. A - // workbench's "run this workbench on its own sidecar" setting can then - // always write a tenant's exclusive `sidecarPlacement`; without any - // configured provisioner that placement simply fails closed at - // deployment time rather than silently falling back to the shared - // sidecar. Adding a new backend here is: implement `SidecarProvisioner` - // in its own package, add a case to `buildSidecarProvisioner`, and add - // its id to `apps/hub/src/config.ts`'s `SIDECAR_PROVISIONER_IDS`. + // boundary, mirroring @intx/hub-sessions's own reference wiring. An + // install that configures nothing registers the `process` backend + // (`@corbits/process-provisioner`) as the sole default, so a + // workbench's "run this workbench on its own sidecar" setting works on + // one server with no operator setup; `SIDECAR_PROVISIONERS` is the one + // variable that changes where sidecars run. Adding a new backend here + // is: implement `SidecarProvisioner` in its own package, add a case to + // `buildSidecarProvisioner`, and add its id to + // `apps/hub/src/config.ts`'s `SIDECAR_PROVISIONER_IDS`. const sidecarPlugins = createSidecarPluginRegistry({ provisioners: config.sidecarProvisioners.map((provisionerConfig) => - buildSidecarProvisioner(provisionerConfig, config.hubDataDir), + buildSidecarProvisioner( + provisionerConfig, + config.hubDataDir, + hubWebSocketUrl, + ), ), ...(config.defaultSidecarProvisionerId !== undefined ? { defaultProvisionerId: config.defaultSidecarProvisionerId } @@ -985,9 +1028,6 @@ export async function createHub(config: HubConfig) { return row?.address ?? null; }, }); - const hubWebSocketUrl = - config.sidecarWebSocketUrl ?? - `${config.baseUrl.replace(/^http/, "ws")}/api/sidecars/ws`; const sidecarAllocationReconciler = createSidecarAllocationReconciler({ allocationStore: sidecarAllocationStore, plugins: sidecarPlugins, diff --git a/apps/hub/test/config.test.ts b/apps/hub/test/config.test.ts index da1ee3640b..9d34351174 100644 --- a/apps/hub/test/config.test.ts +++ b/apps/hub/test/config.test.ts @@ -36,7 +36,8 @@ describe("readHubConfig", () => { signInRateLimit: { windowSeconds: 60, max: 10 }, allowPlaintextSecrets: false, allowUnverifiedEmails: false, - sidecarProvisioners: [], + sidecarProvisioners: [{ id: "process" }], + defaultSidecarProvisionerId: "process", envProviderKeys: {}, envProviderBaseUrls: {}, envCredentialPlantAdmin: { @@ -442,10 +443,45 @@ describe("readHubConfig", () => { }); describe("sidecarProvisioners", () => { - test("defaults to empty with no default id, matching the current static-sidecar behavior", () => { + test("an unconfigured install registers the process backend as its sole default", () => { const config = readHubConfig(validEnv); - expect(config.sidecarProvisioners).toEqual([]); - expect(config.defaultSidecarProvisionerId).toBeUndefined(); + expect(config.sidecarProvisioners).toEqual([{ id: "process" }]); + expect(config.defaultSidecarProvisionerId).toBe("process"); + }); + + test("the process backend's optional overrides reach its config", () => { + const config = readHubConfig({ + ...validEnv, + PROCESS_PROVISIONER_SIDECAR_ENTRY: "/opt/sidecar/index.js", + PROCESS_PROVISIONER_RUNTIME: "/usr/bin/node", + }); + expect(config.sidecarProvisioners).toEqual([ + { + id: "process", + sidecarEntryPath: "/opt/sidecar/index.js", + runtimePath: "/usr/bin/node", + }, + ]); + }); + + test("process is a listable id like any other backend", () => { + const config = readHubConfig({ + ...validEnv, + SIDECAR_PROVISIONERS: "process", + }); + expect(config.sidecarProvisioners).toEqual([{ id: "process" }]); + expect(config.defaultSidecarProvisionerId).toBe("process"); + }); + + test("an explicit list without process does not get the default backend", () => { + const config = readHubConfig({ + ...validEnv, + SIDECAR_PROVISIONERS: "docker", + DOCKER_PROVISIONER_IMAGE: "ghcr.io/corbits/sidecar:latest", + }); + expect(config.sidecarProvisioners.map((one) => one.id)).toEqual([ + "docker", + ]); }); test("SIDECAR_PROVISIONERS=docker with an image is wired and becomes the default", () => { diff --git a/bun.lock b/bun.lock index e752f7c0b1..027ee412cb 100644 --- a/bun.lock +++ b/bun.lock @@ -62,6 +62,7 @@ "@corbits/notify": "workspace:*", "@corbits/preferences": "workspace:*", "@corbits/presence": "workspace:*", + "@corbits/process-provisioner": "workspace:*", "@corbits/run-key-history": "workspace:*", "@corbits/run-scope": "workspace:*", "@corbits/seeding": "workspace:*", @@ -1126,6 +1127,20 @@ "typescript": "catalog:", }, }, + "packages/process-provisioner": { + "name": "@corbits/process-provisioner", + "version": "0.0.1", + "dependencies": { + "@corbits/error-sink": "workspace:*", + "@corbits/sandbox-sidecar": "workspace:*", + "@intx/hub-sessions": "workspace:*", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "packages/provider-pricing": { "name": "@corbits/provider-pricing", "version": "0.0.1", @@ -1383,7 +1398,7 @@ }, "packages/tools-skills": { "name": "@corbits/tools-skills", - "version": "0.0.1", + "version": "0.0.2", "dependencies": { "@intx/agent": "workspace:*", "@intx/types": "workspace:*", @@ -2221,6 +2236,8 @@ "@corbits/process-granola-call-workflow": ["@corbits/process-granola-call-workflow@workspace:workflows/process-granola-call"], + "@corbits/process-provisioner": ["@corbits/process-provisioner@workspace:packages/process-provisioner"], + "@corbits/provider-pricing": ["@corbits/provider-pricing@workspace:packages/provider-pricing"], "@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], @@ -3533,6 +3550,14 @@ "@corbits/artifacts-hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#81049ed", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-81049ed", "sha512-oTE0iFDyQdz0ifG1epo39pwaCaYaw19YcKXwfaZqAEQ56a1g9YIozXwH9CG4NaUTwcJKUeYGuNls6oJsMPisCw=="], + "@corbits/chat-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + + "@corbits/context-menu/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + + "@corbits/plugins-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + + "@corbits/settings-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3557,6 +3582,8 @@ "@workbench/hub/@corbits/artifacts": ["@corbits/artifacts@github:corbitsdev/corbits-artifacts#81049ed", { "dependencies": { "@hono/standard-validator": "^0.2.3" }, "peerDependencies": { "@intx/types": "^0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.2", "hono": "^4.12.32", "hono-openapi": "^1.2.0", "postgres": "^3.4.9" } }, "corbitsdev-corbits-artifacts-81049ed", "sha512-oTE0iFDyQdz0ifG1epo39pwaCaYaw19YcKXwfaZqAEQ56a1g9YIozXwH9CG4NaUTwcJKUeYGuNls6oJsMPisCw=="], + "@workbench/web/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], + "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "better-call/@better-auth/utils": ["@better-auth/utils@0.5.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="], diff --git a/docs/sidecar-provisioners.md b/docs/sidecar-provisioners.md new file mode 100644 index 0000000000..fcb1e6c7da --- /dev/null +++ b/docs/sidecar-provisioners.md @@ -0,0 +1,92 @@ +# Sidecar provisioners + +A **sidecar** is the execution host a workbench's agents and workflow runs +actually run on. A **provisioner** is the backend that creates and destroys +one: Interchange's `SidecarProvisioner` contract, `ensure`/`destroy`, keyed +by allocation and generation. + +This is the one page for deciding where an install's sidecars run. + +## The shipped backends + +| id | Where a sidecar runs | Isolation | Requires | Package | +| --------- | --------------------------------------- | ------------------------------------------------ | ------------------------------------------------------- | ------------------------------ | +| `process` | A child process of the hub, same host | Process only — shared kernel, filesystem, user | nothing | `packages/process-provisioner` | +| `docker` | A container on the hub's host | Container — own filesystem and network namespace | `DOCKER_PROVISIONER_IMAGE`, a local `docker` CLI | `packages/docker-provisioner` | +| `e2b` | A remote [E2B](https://e2b.dev) sandbox | VM — separate machine | `E2B_API_KEY`, `E2B_TEMPLATE`, a publicly reachable hub | `packages/e2b-sandbox-sidecar` | + +`process` is the **default**: a hub with `SIDECAR_PROVISIONERS` unset +registers it as the sole backend, so one server runs many chats and +workflows with no operator configuration at all. Pick `docker` or `e2b` +when a sidecar runs untrusted code or needs its own filesystem and network. + +## Configuring it + +Two variables decide everything: + +```sh +# Register a set of backends. Unset means exactly `process`. +SIDECAR_PROVISIONERS=process,docker +# Which of them exclusive placements provision on. Optional when the list +# has one id; required when it has more. +SIDECAR_DEFAULT_PROVISIONER=docker +``` + +Setting `SIDECAR_PROVISIONERS` **replaces** the default rather than adding +to it — list `process` explicitly to keep it alongside another backend. An +unknown id, a duplicate id, a missing backend setting, or a +`SIDECAR_DEFAULT_PROVISIONER` naming an unlisted id all fail the boot with +a message naming the variable; nothing silently degrades to a different +backend than the one asked for. + +Per-backend settings, and the `HUB_SIDECAR_WEBSOCKET_URL` override a +container or remote sandbox needs to dial back, are documented against each +variable in [`.env.example`](../.env.example) and in +`apps/hub/src/config.ts`'s env schema. + +### Where a sidecar's state lives + +Every backend keeps its hub-side allocation state — generation fences, +destroy tombstones, external refs — under the hub's own `HUB_DATA_DIR`, +derived and never separately configurable, so no two backends can drift or +collide: + +``` +$HUB_DATA_DIR/process-provisioner/ +$HUB_DATA_DIR/docker-provisioner/ +$HUB_DATA_DIR/e2b-provisioner/ +``` + +The `process` backend additionally keeps each allocation's own +`SIDECAR_DATA_DIR` there, one directory per generation, removed when the +allocation is destroyed — see +[`packages/process-provisioner/README.md`](../packages/process-provisioner/README.md). + +## Adding a backend + +Three steps, no hub surgery: + +1. **Implement the backend.** Copy `packages/process-provisioner`: a + `SidecarBackend` (`startUnit` / `stopUnit` / `findUnitsByAllocation`) + plus identity (`id`, `apiVersion`, `bindingFingerprint`). Idempotence, + generation fencing, destroy tombstones, and obsolete-unit sweeping come + from `@corbits/sandbox-sidecar`'s shared core — never reimplement them + per backend. +2. **Name it.** Add its id to `SIDECAR_PROVISIONER_IDS` and a member to + `SidecarProvisionerConfig` in `apps/hub/src/config.ts`, with its own + required settings parsed there (the hub's one env boundary). +3. **Wire it.** Add a case to `buildSidecarProvisioner` in + `apps/hub/src/index.ts`. + +The registry itself is composed at the hub's composition root and takes +whatever the config named, so a new backend is a package plus two switch +cases — an operator then reaches it by id, exactly like the shipped three. + +## Related + +- [`packages/process-provisioner/README.md`](../packages/process-provisioner/README.md) + — the default backend's layout, environment, and trade-offs. +- [`packages/e2b-sandbox-sidecar/README.md`](../packages/e2b-sandbox-sidecar/README.md) + — building the E2B template. +- [`docs/sidecar-placement-adoption.md`](sidecar-placement-adoption.md) — + the design analysis behind hub-authoritative placement. diff --git a/packages/process-provisioner/LICENSE b/packages/process-provisioner/LICENSE new file mode 100644 index 0000000000..c6487f4fdf --- /dev/null +++ b/packages/process-provisioner/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/packages/process-provisioner/README.md b/packages/process-provisioner/README.md new file mode 100644 index 0000000000..d38b186ac7 --- /dev/null +++ b/packages/process-provisioner/README.md @@ -0,0 +1,67 @@ +# @corbits/process-provisioner + +The **default** `SidecarProvisioner` backend: each exclusive sidecar +allocation runs as one `apps/sidecar` child process on the hub's own host. + +A hub with no `SIDECAR_PROVISIONERS` set registers this backend as its sole +provisioner, so a single-server install provisions exclusive sidecars — +many chats and workflows on one VPS — with no operator configuration, no +container runtime, and no remote sandbox account. + +## What one allocation looks like + +Under the hub's data directory: + +``` +$HUB_DATA_DIR/process-provisioner/state.json # generation fences, destroy tombstones +$HUB_DATA_DIR/process-provisioner/allocations//gen-/sidecar.pid +$HUB_DATA_DIR/process-provisioner/allocations//gen-/data/ # that sidecar's SIDECAR_DATA_DIR +``` + +`ensure` creates the generation's directory, spawns +` `, and records the pid; `destroy` sends SIGTERM +(escalating to SIGKILL after a grace period) and removes the directory. + +Each spawned process gets only what `apps/sidecar/src/config.ts` requires: +`HUB_WS_URL` (the allocation's hub WebSocket URL), `SIDECAR_TOKEN` (the +provisioner-issued bearer token for that allocation), `SIDECAR_ID`, +`SIDECAR_DATA_DIR`, and the host's `PATH`/`HOME`/`TMPDIR`. Nothing else of +the hub's environment is inherited — a sidecar learns everything else over +the wire. + +Idempotence, generation fencing, destroy tombstones, and obsolete-unit +sweeping are not implemented here: they come from +`@corbits/sandbox-sidecar`'s shared core, the same core the `docker` and +`e2b` backends use. This package supplies only the OS-level unit. Scoping a +unit by generation is what keeps the sweep honest — a new generation's pid +never overwrites the record of the unit it replaces, so a superseded +process is still found and stopped. + +The binding fingerprint is `process:v1::`: the +two facts that decide what a provisioned sidecar actually is. + +## Operator environment variables + +Both are optional overrides; an unconfigured install needs neither. + +- `PROCESS_PROVISIONER_SIDECAR_ENTRY` — the sidecar entry point to spawn. + Unset resolves this repository's own `apps/sidecar/src/index.ts`. +- `PROCESS_PROVISIONER_RUNTIME` — the executable that runs it. Unset + reuses the `bun` binary running the hub. + +The hub's own state directory for this backend is derived from +`HUB_DATA_DIR`, never configured separately, so it cannot drift from the +other backends' state. + +## Trade-offs + +Sidecars share the hub's kernel, filesystem, and user account: this +backend gives process isolation, not the sandbox isolation `docker` or +`e2b` give. Choose it for a single-server deployment or local development; +choose `docker`/`e2b` when a sidecar runs untrusted code or needs its own +filesystem and network namespace. + +Process recovery is by pid, so pid reuse after a host reboot is +theoretically ambiguous. In practice the pid file lives inside the +allocation's own directory and is removed with it, and the hub's +reconciler re-ensures live allocations on boot. diff --git a/packages/process-provisioner/package.json b/packages/process-provisioner/package.json new file mode 100644 index 0000000000..84967e1380 --- /dev/null +++ b/packages/process-provisioner/package.json @@ -0,0 +1,25 @@ +{ + "name": "@corbits/process-provisioner", + "private": true, + "description": "SidecarProvisioner plugin that runs each sidecar allocation as a child process on the hub host", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@corbits/error-sink": "workspace:*", + "@corbits/sandbox-sidecar": "workspace:*", + "@intx/hub-sessions": "workspace:*", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/process-provisioner/src/config.test.ts b/packages/process-provisioner/src/config.test.ts new file mode 100644 index 0000000000..2697b45ab6 --- /dev/null +++ b/packages/process-provisioner/src/config.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; + +import { readProcessProvisionerConfig } from "./config"; + +const HUB_WS_URL = "ws://127.0.0.1:3000/api/sidecars/ws"; + +describe("readProcessProvisionerConfig", () => { + test("an unconfigured environment resolves this repository's sidecar entry and the running bun", () => { + const config = readProcessProvisionerConfig({ + env: {}, + dataDir: "/srv/hub-data/process-provisioner", + hubWebSocketUrl: HUB_WS_URL, + }); + + expect(config.sidecarEntryPath).toEndWith("/apps/sidecar/src/index.ts"); + expect(config.runtimePath).toBe(process.execPath); + expect(config.allocationsDir).toBe( + "/srv/hub-data/process-provisioner/allocations", + ); + expect(config.stateFilePath).toBe( + "/srv/hub-data/process-provisioner/state.json", + ); + expect(config.hubWebSocketUrl).toBe(HUB_WS_URL); + }); + + test("an operator can point the backend at another entry point and runtime", () => { + const config = readProcessProvisionerConfig({ + env: { + PROCESS_PROVISIONER_SIDECAR_ENTRY: "/opt/sidecar/index.js", + PROCESS_PROVISIONER_RUNTIME: "/usr/bin/node", + }, + dataDir: "/srv/hub-data/process-provisioner", + hubWebSocketUrl: HUB_WS_URL, + }); + + expect(config.sidecarEntryPath).toBe("/opt/sidecar/index.js"); + expect(config.runtimePath).toBe("/usr/bin/node"); + }); + + test("a relative data dir fails loudly instead of resolving against the cwd", () => { + expect(() => + readProcessProvisionerConfig({ + env: {}, + dataDir: ".data/hub/process-provisioner", + hubWebSocketUrl: HUB_WS_URL, + }), + ).toThrow("must be an absolute path"); + }); + + test("an empty override is a misconfiguration, not an unset key", () => { + expect(() => + readProcessProvisionerConfig({ + env: { PROCESS_PROVISIONER_RUNTIME: "" }, + dataDir: "/srv/hub-data/process-provisioner", + hubWebSocketUrl: HUB_WS_URL, + }), + ).toThrow("invalid process provisioner environment"); + }); +}); diff --git a/packages/process-provisioner/src/config.ts b/packages/process-provisioner/src/config.ts new file mode 100644 index 0000000000..495eec0537 --- /dev/null +++ b/packages/process-provisioner/src/config.ts @@ -0,0 +1,89 @@ +import { isAbsolute, resolve } from "node:path"; + +import { type } from "arktype"; + +// The sidecar entry this provisioner spawns, relative to this package's +// own directory: the same `apps/sidecar/src/index.ts` that `bun run dev` +// starts. Resolved from `import.meta.dir` rather than the process cwd so +// the hub can be launched from anywhere on the host. +const DEFAULT_SIDECAR_ENTRY = resolve( + import.meta.dir, + "..", + "..", + "..", + "apps", + "sidecar", + "src", + "index.ts", +); + +const Environment = type({ + "PROCESS_PROVISIONER_SIDECAR_ENTRY?": "string > 0", + "PROCESS_PROVISIONER_RUNTIME?": "string > 0", +}); + +export type ProcessProvisionerConfig = { + /** The executable that runs the sidecar entry — `bun` by default. */ + readonly runtimePath: string; + /** Absolute path to the sidecar entry point this backend spawns. */ + readonly sidecarEntryPath: string; + /** + * Hub-side root for per-allocation directories. Each allocation gets + * `//`, holding the pid file this backend + * recovers units from after a hub restart plus the sidecar's own + * `SIDECAR_DATA_DIR`. Destroying an allocation removes that directory. + */ + readonly allocationsDir: string; + /** Where the shared allocation state store keeps generation fences. */ + readonly stateFilePath: string; + /** The ws(s):// URL provisioned sidecars dial back on; part of the + * binding fingerprint, since a hub moved to a new address is a + * different backend binding even with the same entry point. */ + readonly hubWebSocketUrl: string; +}; + +export type ReadProcessProvisionerConfigArgs = { + readonly env: Record; + /** + * The HUB's own state directory for this backend, derived from + * `HUB_DATA_DIR` by the caller — never an environment variable an + * operator could point somewhere unrelated. Matches how the docker and + * e2b backends receive theirs. + */ + readonly dataDir: string; + readonly hubWebSocketUrl: string; +}; + +/** + * Parse the process provisioner's configuration. Both environment keys + * are optional: an unconfigured install spawns this repository's own + * `apps/sidecar` entry with the running `bun`, which is what makes + * "no provisioner configured" work on a single server with no operator + * setup at all. + */ +export function readProcessProvisionerConfig( + args: ReadProcessProvisionerConfigArgs, +): ProcessProvisionerConfig { + const parsed = Environment(args.env); + if (parsed instanceof type.errors) { + throw new Error( + `invalid process provisioner environment: ${parsed.summary}`, + ); + } + if (!isAbsolute(args.dataDir)) { + throw new Error( + "process provisioner data dir must be an absolute path; got " + + JSON.stringify(args.dataDir), + ); + } + const sidecarEntryPath = resolve( + parsed.PROCESS_PROVISIONER_SIDECAR_ENTRY ?? DEFAULT_SIDECAR_ENTRY, + ); + return { + runtimePath: parsed.PROCESS_PROVISIONER_RUNTIME ?? process.execPath, + sidecarEntryPath, + allocationsDir: resolve(args.dataDir, "allocations"), + stateFilePath: resolve(args.dataDir, "state.json"), + hubWebSocketUrl: args.hubWebSocketUrl, + }; +} diff --git a/packages/process-provisioner/src/fake-process-runner.ts b/packages/process-provisioner/src/fake-process-runner.ts new file mode 100644 index 0000000000..d3fa1ec3c8 --- /dev/null +++ b/packages/process-provisioner/src/fake-process-runner.ts @@ -0,0 +1,56 @@ +import type { + SidecarProcessRunner, + SpawnSidecarProcessArgs, +} from "./process-runner"; + +export type FakeSidecarProcessRunner = SidecarProcessRunner & { + readonly spawns: SpawnSidecarProcessArgs[]; + readonly signals: { readonly pid: number; readonly signal: string }[]; + /** Marks a pid dead without a signal, standing in for a crashed child. */ + kill(pid: number): void; +}; + +export type CreateFakeSidecarProcessRunnerOpts = { + readonly firstPid?: number; + /** Throws from `spawn` instead of starting a process. */ + readonly spawnError?: Error; + /** Throws from `signal` instead of delivering it. */ + readonly signalError?: Error; +}; + +export function createFakeSidecarProcessRunner( + opts: CreateFakeSidecarProcessRunnerOpts = {}, +): FakeSidecarProcessRunner { + const spawns: SpawnSidecarProcessArgs[] = []; + const signals: { pid: number; signal: string }[] = []; + const alive = new Set(); + let nextPid = opts.firstPid ?? 4001; + + return { + spawns, + signals, + + spawn(args) { + if (opts.spawnError !== undefined) throw opts.spawnError; + spawns.push(args); + const pid = nextPid; + nextPid += 1; + alive.add(pid); + return pid; + }, + + isAlive(pid) { + return alive.has(pid); + }, + + signal(pid, signal) { + if (opts.signalError !== undefined) throw opts.signalError; + signals.push({ pid, signal }); + if (signal === "SIGTERM" || signal === "SIGKILL") alive.delete(pid); + }, + + kill(pid) { + alive.delete(pid); + }, + }; +} diff --git a/packages/process-provisioner/src/index.ts b/packages/process-provisioner/src/index.ts new file mode 100644 index 0000000000..04671c1b8e --- /dev/null +++ b/packages/process-provisioner/src/index.ts @@ -0,0 +1,28 @@ +export { + createProcessSidecarProvisioner, + PROCESS_PROVISIONER_ID, + type CreateProcessSidecarProvisionerOpts, +} from "./interchange-plugin"; +export { + readProcessProvisionerConfig, + type ProcessProvisionerConfig, + type ReadProcessProvisionerConfigArgs, +} from "./config"; +export { createProcessBackend } from "./process-backend"; +export { + createBunSidecarProcessRunner, + type SidecarProcessRunner, + type SpawnSidecarProcessArgs, +} from "./process-runner"; +export { + createAllocationStateStore, + type AllocationStateStore, + type AllocationRecord, +} from "@corbits/sandbox-sidecar"; +export type { + DestroySidecarRequest, + DestroySidecarResult, + EnsureSidecarRequest, + EnsureSidecarResult, + SidecarProvisioner, +} from "@intx/hub-sessions"; diff --git a/packages/process-provisioner/src/interchange-plugin.test.ts b/packages/process-provisioner/src/interchange-plugin.test.ts new file mode 100644 index 0000000000..0853f2323c --- /dev/null +++ b/packages/process-provisioner/src/interchange-plugin.test.ts @@ -0,0 +1,212 @@ +import { mkdtemp, readFile, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +import { describe, expect, test } from "bun:test"; + +import type { EnsureSidecarRequest } from "@intx/hub-sessions"; + +import type { ProcessProvisionerConfig } from "./config"; +import { + createFakeSidecarProcessRunner, + type FakeSidecarProcessRunner, +} from "./fake-process-runner"; +import { createProcessSidecarProvisioner } from "./interchange-plugin"; + +const HUB_WS_URL = "ws://127.0.0.1:3000/api/sidecars/ws"; +const SIDECAR_ENTRY = "/srv/workbench/apps/sidecar/src/index.ts"; + +async function configIn(dataDir: string): Promise { + return { + runtimePath: "/usr/local/bin/bun", + sidecarEntryPath: SIDECAR_ENTRY, + allocationsDir: resolve(dataDir, "allocations"), + stateFilePath: resolve(dataDir, "state.json"), + hubWebSocketUrl: HUB_WS_URL, + }; +} + +async function harness( + opts: Parameters[0] = {}, +): Promise<{ + provisioner: ReturnType; + runner: FakeSidecarProcessRunner; + config: ProcessProvisionerConfig; +}> { + const dataDir = await mkdtemp(join(tmpdir(), "process-provisioner-")); + const config = await configIn(dataDir); + const runner = createFakeSidecarProcessRunner(opts); + return { + provisioner: createProcessSidecarProvisioner({ config, runner }), + runner, + config, + }; +} + +function ensureRequest( + overrides: Partial = {}, +): EnsureSidecarRequest { + return { + allocationId: "alloc-1", + generation: 1, + tenantId: "tenant-1", + anchorRunId: "run-1", + sidecarId: "sidecar-1", + token: "token-abc", + hubWebSocketUrl: HUB_WS_URL, + ...overrides, + }; +} + +describe("createProcessSidecarProvisioner", () => { + test("declares the process backend identity and a fingerprint over entry point and hub URL", async () => { + const { provisioner } = await harness(); + expect(provisioner.id).toBe("process"); + expect(provisioner.apiVersion).toBe(1); + expect(provisioner.bindingFingerprint).toBe( + `process:v1:${SIDECAR_ENTRY}:${HUB_WS_URL}`, + ); + }); + + test("ensure spawns the sidecar entry with the allocation's own token, data dir, and hub URL", async () => { + const { provisioner, runner, config } = await harness(); + + const result = await provisioner.ensure(ensureRequest()); + + expect(result.kind).toBe("accepted"); + expect(runner.spawns).toHaveLength(1); + const spawn = runner.spawns[0]; + expect(spawn?.command).toEqual([ + "/usr/local/bin/bun", + "/srv/workbench/apps/sidecar/src/index.ts", + ]); + expect(spawn?.env["HUB_WS_URL"]).toBe(HUB_WS_URL); + expect(spawn?.env["SIDECAR_TOKEN"]).toBe("token-abc"); + expect(spawn?.env["SIDECAR_ID"]).toBe("sidecar-1"); + expect(spawn?.env["SIDECAR_DATA_DIR"]).toBe( + resolve(config.allocationsDir, "alloc-1", "gen-1", "data"), + ); + expect(spawn?.env["PATH"]).toBe(process.env["PATH"]); + }); + + test("ensure records the pid so a restarted hub can still find the unit", async () => { + const { provisioner, config } = await harness({ firstPid: 5150 }); + + const result = await provisioner.ensure(ensureRequest()); + + expect(result).toMatchObject({ + kind: "accepted", + externalRef: "alloc-1:1:5150", + }); + const pidFile = await readFile( + resolve(config.allocationsDir, "alloc-1", "gen-1", "sidecar.pid"), + "utf8", + ); + expect(pidFile.trim()).toBe("5150"); + }); + + test("ensure is idempotent for the same allocation and generation", async () => { + const { provisioner, runner } = await harness(); + + const first = await provisioner.ensure(ensureRequest()); + const second = await provisioner.ensure(ensureRequest()); + + expect(first).toEqual(second); + expect(runner.spawns).toHaveLength(1); + }); + + test("ensure rejects a generation older than one already observed", async () => { + const { provisioner, runner } = await harness(); + + await provisioner.ensure(ensureRequest({ generation: 3 })); + const stale = await provisioner.ensure(ensureRequest({ generation: 2 })); + + expect(stale).toMatchObject({ kind: "rejected", code: "stale_generation" }); + expect(runner.spawns).toHaveLength(1); + }); + + test("a newer generation replaces the previous process for the allocation", async () => { + const { provisioner, runner } = await harness({ firstPid: 700 }); + + await provisioner.ensure(ensureRequest({ generation: 1 })); + const next = await provisioner.ensure(ensureRequest({ generation: 2 })); + + expect(next).toMatchObject({ + kind: "accepted", + externalRef: "alloc-1:2:701", + }); + expect(runner.spawns).toHaveLength(2); + expect(runner.signals).toEqual([{ pid: 700, signal: "SIGTERM" }]); + }); + + test("ensure rejects, without spawning, when the process cannot start", async () => { + const { provisioner, runner } = await harness({ + spawnError: new Error("EAGAIN: out of process slots"), + }); + + const result = await provisioner.ensure(ensureRequest()); + + expect(result).toMatchObject({ + kind: "rejected", + code: "sidecar_spawn_failed", + retryable: true, + }); + expect(runner.spawns).toHaveLength(0); + }); + + test("destroy terminates the process and removes the allocation directory", async () => { + const { provisioner, runner, config } = await harness({ firstPid: 900 }); + await provisioner.ensure(ensureRequest()); + const allocationDir = resolve(config.allocationsDir, "alloc-1"); + expect((await stat(allocationDir)).isDirectory()).toBe(true); + + const result = await provisioner.destroy({ + allocationId: "alloc-1", + generation: 1, + sidecarId: "sidecar-1", + }); + + expect(result).toEqual({ kind: "destroyed" }); + expect(runner.signals).toEqual([{ pid: 900, signal: "SIGTERM" }]); + expect(runner.isAlive(900)).toBe(false); + await expect(stat(allocationDir)).rejects.toThrow(); + }); + + test("destroy is idempotent and fences a later ensure of the destroyed generation", async () => { + const { provisioner, runner } = await harness(); + await provisioner.ensure(ensureRequest()); + const destroyRequest = { + allocationId: "alloc-1", + generation: 1, + sidecarId: "sidecar-1", + }; + + expect(await provisioner.destroy(destroyRequest)).toEqual({ + kind: "destroyed", + }); + expect(await provisioner.destroy(destroyRequest)).toEqual({ + kind: "destroyed", + }); + const revived = await provisioner.ensure(ensureRequest()); + expect(revived).toMatchObject({ + kind: "rejected", + code: "generation_destroyed", + }); + expect(runner.spawns).toHaveLength(1); + }); + + test("an allocation id that is not a safe directory name is rejected outright", async () => { + const { provisioner, runner } = await harness(); + + const result = await provisioner.ensure( + ensureRequest({ allocationId: "../escape" }), + ); + + expect(result).toMatchObject({ + kind: "rejected", + code: "invalid_allocation_id", + retryable: false, + }); + expect(runner.spawns).toHaveLength(0); + }); +}); diff --git a/packages/process-provisioner/src/interchange-plugin.ts b/packages/process-provisioner/src/interchange-plugin.ts new file mode 100644 index 0000000000..12e875140b --- /dev/null +++ b/packages/process-provisioner/src/interchange-plugin.ts @@ -0,0 +1,51 @@ +import { + createAllocationStateStore, + createSidecarProvisioner, + type AllocationStateStore, +} from "@corbits/sandbox-sidecar"; +import type { SidecarProvisioner } from "@intx/hub-sessions"; + +import type { ProcessProvisionerConfig } from "./config"; +import { createProcessBackend } from "./process-backend"; +import { + createBunSidecarProcessRunner, + type SidecarProcessRunner, +} from "./process-runner"; + +const PROVISIONER_API_VERSION = 1 as const; + +export const PROCESS_PROVISIONER_ID = "process"; + +export type CreateProcessSidecarProvisionerOpts = { + readonly config: ProcessProvisionerConfig; + readonly runner?: SidecarProcessRunner; + readonly store?: AllocationStateStore; +}; + +/** + * The default sidecar backend: every allocation is a child process of the + * hub on the same host. Idempotence, generation fencing, and destroy + * tombstones come from `@corbits/sandbox-sidecar`'s shared core, exactly + * as they do for the docker and e2b backends — this package supplies only + * the OS-level unit. + * + * The binding fingerprint pins the two facts that decide what a + * provisioned sidecar actually is: which entry point runs, and which hub + * it dials. A change to either is a different backend binding, so + * allocations bound to the old one are not silently treated as current. + */ +export function createProcessSidecarProvisioner( + opts: CreateProcessSidecarProvisionerOpts, +): SidecarProvisioner { + const { config } = opts; + const runner = opts.runner ?? createBunSidecarProcessRunner(); + const store = opts.store ?? createAllocationStateStore(config.stateFilePath); + + return createSidecarProvisioner({ + id: PROCESS_PROVISIONER_ID, + apiVersion: PROVISIONER_API_VERSION, + bindingFingerprint: `process:v1:${config.sidecarEntryPath}:${config.hubWebSocketUrl}`, + backend: createProcessBackend(runner, config), + store, + }); +} diff --git a/packages/process-provisioner/src/process-backend.ts b/packages/process-provisioner/src/process-backend.ts new file mode 100644 index 0000000000..c8f1457fe9 --- /dev/null +++ b/packages/process-provisioner/src/process-backend.ts @@ -0,0 +1,336 @@ +import { + mkdir, + readFile, + readdir, + rm, + rmdir, + writeFile, +} from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +import { reportError } from "@corbits/error-sink"; +import { + BackendOperationError, + type SidecarBackend, + type StartUnitArgs, +} from "@corbits/sandbox-sidecar"; + +import type { ProcessProvisionerConfig } from "./config"; +import type { SidecarProcessRunner } from "./process-runner"; + +const PID_FILE_NAME = "sidecar.pid"; +const SIDECAR_DATA_DIR_NAME = "data"; +const UNIT_DIR_PREFIX = "gen-"; +// An allocation id names a directory on the hub host, so it may only be +// the id-shaped text Interchange actually issues — never a traversal. +const ALLOCATION_ID_PATTERN = /^[A-Za-z0-9._-]+$/; +const TERMINATION_GRACE_MS = 5_000; +const TERMINATION_POLL_MS = 100; + +/** + * Implements `@corbits/sandbox-sidecar`'s `SidecarBackend` port by running + * one `apps/sidecar` process per allocation on the hub host itself. This + * is the backend an install with no `SIDECAR_PROVISIONERS` configured + * gets, so one server hosts many chats and workflows with no container + * runtime and no remote sandbox account. + * + * Layout under the hub's data dir, one directory per started unit: + * + * //gen-/sidecar.pid + * //gen-/data/ + * + * `data/` is that sidecar's own `SIDECAR_DATA_DIR`. The pid file is what + * makes this backend survive a hub restart: the child handle is gone, but + * `findUnitsByAllocation` still finds every live unit from disk, so the + * core can sweep a superseded generation and destroy can still clean up + * after a unit this process never started. Scoping a unit by generation + * (rather than one pid file per allocation) is what keeps that sweep + * honest — a new generation's pid never overwrites the record of the one + * it is replacing. + */ +export function createProcessBackend( + runner: SidecarProcessRunner, + config: ProcessProvisionerConfig, +): SidecarBackend { + function allocationDirOf(allocationId: string): string { + if (!ALLOCATION_ID_PATTERN.test(allocationId)) { + throw new BackendOperationError( + "invalid_allocation_id", + `allocationId ${JSON.stringify(allocationId)} is not a valid directory name`, + false, + ); + } + return resolve(config.allocationsDir, allocationId); + } + + function unitDirOf(allocationId: string, generation: number): string { + return resolve( + allocationDirOf(allocationId), + `${UNIT_DIR_PREFIX}${String(generation)}`, + ); + } + + return { + async startUnit(args: StartUnitArgs): Promise { + const unitDir = unitDirOf(args.allocationId, args.generation); + const sidecarDataDir = resolve(unitDir, SIDECAR_DATA_DIR_NAME); + const env = sidecarEnvFor(args, sidecarDataDir); + try { + await mkdir(sidecarDataDir, { recursive: true, mode: 0o700 }); + } catch (error) { + throw operationalFailure( + error, + "allocation_dir_failed", + `unable to create unit directory ${unitDir}`, + args.allocationId, + ); + } + + let pid: number; + try { + pid = runner.spawn({ + command: [config.runtimePath, config.sidecarEntryPath], + cwd: dirname(config.sidecarEntryPath), + env, + }); + } catch (error) { + throw operationalFailure( + error, + "sidecar_spawn_failed", + `unable to spawn ${config.sidecarEntryPath}`, + args.allocationId, + ); + } + + try { + await writeFile(resolve(unitDir, PID_FILE_NAME), `${String(pid)}\n`, { + mode: 0o600, + }); + } catch (error) { + await terminate(runner, pid); + throw operationalFailure( + error, + "pid_file_write_failed", + `unable to record pid ${String(pid)} for allocation ${args.allocationId}`, + args.allocationId, + ); + } + return externalRefOf(args.allocationId, args.generation, pid); + }, + + async stopUnit(externalRef: string): Promise { + const unit = parseExternalRef(externalRef); + if (unit === null) { + throw new BackendOperationError( + "invalid_external_ref", + `external ref ${JSON.stringify(externalRef)} is not ::`, + false, + ); + } + try { + await terminate(runner, unit.pid); + } catch (error) { + throw operationalFailure( + error, + "sidecar_terminate_failed", + `unable to terminate pid ${String(unit.pid)}`, + unit.allocationId, + ); + } + const unitDir = unitDirOf(unit.allocationId, unit.generation); + try { + await rm(unitDir, { recursive: true, force: true }); + // The allocation's own directory goes once its last unit does; + // a still-running newer generation keeps it, which is why this + // is an rmdir and not a recursive remove. + await rmdir(allocationDirOf(unit.allocationId)).catch( + ignoreNonEmptyOrMissing, + ); + } catch (error) { + throw operationalFailure( + error, + "allocation_dir_cleanup_failed", + `unable to remove unit directory ${unitDir}`, + unit.allocationId, + ); + } + }, + + async findUnitsByAllocation( + allocationId: string, + ): Promise { + const allocationDir = allocationDirOf(allocationId); + let entries: string[]; + try { + entries = await readdir(allocationDir); + } catch (error) { + if (isErrnoCode(error, "ENOENT")) return []; + throw operationalFailure( + error, + "allocation_dir_read_failed", + `unable to list units under ${allocationDir}`, + allocationId, + ); + } + + const refs: string[] = []; + for (const entry of entries) { + const generation = generationOf(entry); + if (generation === null) continue; + const pid = await readPidFile( + resolve(allocationDir, entry), + allocationId, + ); + if (pid === null || !runner.isAlive(pid)) continue; + refs.push(externalRefOf(allocationId, generation, pid)); + } + return refs; + }, + }; +} + +/** + * The sidecar's own boot config (`apps/sidecar/src/config.ts`) requires + * `SIDECAR_DATA_DIR`, `HUB_WS_URL`, `SIDECAR_ID`, `SIDECAR_TOKEN` and + * `PATH`, and forwards `HOME`/`TMPDIR` into each workflow-process child. + * Nothing else of the hub's environment is inherited: a sidecar learns + * everything else over the wire. + */ +function sidecarEnvFor( + args: StartUnitArgs, + sidecarDataDir: string, +): Record { + const path = process.env["PATH"]; + if (path === undefined || path === "") { + const error = new Error( + "the hub process has no PATH to forward; a spawned sidecar cannot resolve its runtime", + ); + reportError(error, { + operation: "process-provisioner.missing_path", + extra: { allocationId: args.allocationId }, + }); + throw new BackendOperationError("missing_path", error.message, false); + } + const home = process.env["HOME"]; + const tmpdir = process.env["TMPDIR"]; + return { + SIDECAR_DATA_DIR: sidecarDataDir, + HUB_WS_URL: args.hubWebSocketUrl, + SIDECAR_ID: args.sidecarId, + SIDECAR_TOKEN: args.token, + PATH: path, + ...(home === undefined ? {} : { HOME: home }), + ...(tmpdir === undefined ? {} : { TMPDIR: tmpdir }), + }; +} + +/** + * Sends SIGTERM and waits out the grace period so the sidecar can flush + * its own state, escalating to SIGKILL only if it is still alive. A pid + * that is already gone is success — destroy has to stay idempotent. + */ +async function terminate( + runner: SidecarProcessRunner, + pid: number, +): Promise { + if (!runner.isAlive(pid)) return; + runner.signal(pid, "SIGTERM"); + const deadline = Date.now() + TERMINATION_GRACE_MS; + while (runner.isAlive(pid) && Date.now() < deadline) { + await sleep(TERMINATION_POLL_MS); + } + if (runner.isAlive(pid)) runner.signal(pid, "SIGKILL"); +} + +function sleep(ms: number): Promise { + return new Promise((done) => setTimeout(done, ms)); +} + +async function readPidFile( + unitDir: string, + allocationId: string, +): Promise { + let raw: string; + try { + raw = await readFile(resolve(unitDir, PID_FILE_NAME), "utf8"); + } catch (error) { + if (isErrnoCode(error, "ENOENT")) return null; + throw operationalFailure( + error, + "pid_file_read_failed", + `unable to read the pid file under ${unitDir}`, + allocationId, + ); + } + const pid = Number(raw.trim()); + return Number.isInteger(pid) && pid > 0 ? pid : null; +} + +function externalRefOf( + allocationId: string, + generation: number, + pid: number, +): string { + return `${allocationId}:${String(generation)}:${String(pid)}`; +} + +function parseExternalRef(externalRef: string): { + allocationId: string; + generation: number; + pid: number; +} | null { + const parts = externalRef.split(":"); + if (parts.length !== 3) return null; + const [allocationId, generationText, pidText] = parts; + if (allocationId === undefined || allocationId === "") return null; + const generation = Number(generationText); + const pid = Number(pidText); + if (!Number.isInteger(generation) || generation <= 0) return null; + if (!Number.isInteger(pid) || pid <= 0) return null; + return { allocationId, generation, pid }; +} + +function generationOf(entryName: string): number | null { + if (!entryName.startsWith(UNIT_DIR_PREFIX)) return null; + const generation = Number(entryName.slice(UNIT_DIR_PREFIX.length)); + return Number.isInteger(generation) && generation > 0 ? generation : null; +} + +function ignoreNonEmptyOrMissing(error: unknown): void { + if ( + isErrnoCode(error, "ENOTEMPTY") || + isErrnoCode(error, "EEXIST") || + isErrnoCode(error, "ENOENT") + ) { + return; + } + throw error; +} + +/** + * Reports a caught OS failure with its allocation context and returns the + * classified error to throw, so the shared provisioner core turns it into + * a retryable rejection carrying a `refId` support can quote. + */ +function operationalFailure( + error: unknown, + code: string, + message: string, + allocationId: string, +): BackendOperationError { + if (error instanceof BackendOperationError) return error; + const refId = reportError(error, { + operation: `process-provisioner.${code}`, + extra: { allocationId }, + }); + const detail = error instanceof Error ? error.message : String(error); + return new BackendOperationError( + code, + `${message}: ${detail} (${refId})`, + true, + ); +} + +function isErrnoCode(error: unknown, code: string): boolean { + return error instanceof Error && "code" in error && error.code === code; +} diff --git a/packages/process-provisioner/src/process-runner.ts b/packages/process-provisioner/src/process-runner.ts new file mode 100644 index 0000000000..69ad25d9c1 --- /dev/null +++ b/packages/process-provisioner/src/process-runner.ts @@ -0,0 +1,64 @@ +export type SpawnSidecarProcessArgs = { + readonly command: readonly string[]; + readonly cwd: string; + readonly env: Record; +}; + +/** + * The narrow OS port this backend needs: start a detached child, ask + * whether a pid is still alive, and signal it. Injected so the unit + * suite exercises the full ensure/destroy lifecycle — including + * generation fencing and directory cleanup — without starting a real + * sidecar. + */ +export interface SidecarProcessRunner { + spawn(args: SpawnSidecarProcessArgs): number; + isAlive(pid: number): boolean; + signal(pid: number, signal: "SIGTERM" | "SIGKILL"): void; +} + +/** + * Bun implementation. The child is spawned with its own stdio inherited + * from the hub so a local operator sees sidecar logs in the same + * terminal, and `unref`ed so a hub shutdown is not blocked waiting on + * it — a still-running sidecar is reconciled (or destroyed) on the next + * boot from its pid file. + */ +export function createBunSidecarProcessRunner(): SidecarProcessRunner { + return { + spawn(args) { + const child = Bun.spawn([...args.command], { + cwd: args.cwd, + env: args.env, + stdin: "ignore", + stdout: "inherit", + stderr: "inherit", + }); + child.unref(); + return child.pid; + }, + + isAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // A signal-0 probe answers the liveness question through its + // errno: ESRCH means no such process, EPERM means the process + // exists but belongs to another user. Anything else is a real + // failure and must not be read as "dead". + if (isErrnoCode(error, "ESRCH")) return false; + if (isErrnoCode(error, "EPERM")) return true; + throw error; + } + }, + + signal(pid, signal) { + process.kill(pid, signal); + }, + }; +} + +function isErrnoCode(error: unknown, code: string): boolean { + return error instanceof Error && "code" in error && error.code === code; +} diff --git a/packages/process-provisioner/tsconfig.json b/packages/process-provisioner/tsconfig.json new file mode 100644 index 0000000000..0680b4ecbc --- /dev/null +++ b/packages/process-provisioner/tsconfig.json @@ -0,0 +1,26 @@ +{ + "extends": "./tsconfig.src.json", + "compilerOptions": { + "composite": false, + "noEmit": true, + "disableSourceOfProjectReferenceRedirect": true, + "declaration": false, + "declarationMap": false, + "emitDeclarationOnly": false, + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "rootDir": "../.." + }, + "include": ["src"], + "exclude": [], + "references": [ + { + "path": "../../vendor/intx/hub-sessions/tsconfig.src.json" + }, + { + "path": "../error-sink/tsconfig.src.json" + }, + { + "path": "../sandbox-sidecar/tsconfig.src.json" + } + ] +} diff --git a/packages/process-provisioner/tsconfig.src.json b/packages/process-provisioner/tsconfig.src.json new file mode 100644 index 0000000000..1bb244f76b --- /dev/null +++ b/packages/process-provisioner/tsconfig.src.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "package.json", "src/**/*.json"], + "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], + "compilerOptions": { + "types": ["bun"], + "composite": true, + "emitDeclarationOnly": true, + "outDir": "dist", + "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" + }, + "references": [ + { + "path": "../../vendor/intx/hub-sessions/tsconfig.src.json" + }, + { + "path": "../error-sink/tsconfig.src.json" + }, + { + "path": "../sandbox-sidecar/tsconfig.src.json" + } + ] +} diff --git a/packages/sidecar-placement/src/routes.ts b/packages/sidecar-placement/src/routes.ts index e8468c2813..fc0b204e53 100644 --- a/packages/sidecar-placement/src/routes.ts +++ b/packages/sidecar-placement/src/routes.ts @@ -16,8 +16,10 @@ export type CreateSidecarPlacementRoutesDeps = { store: SidecarPlacementStore; requireGrant: RequireGrant; /** - * Whether the hub has a sidecar provisioner registered - * (SIDECAR_PROVISIONERS names a real backend). When false, exclusive + * Whether the host has a sidecar provisioner registered. The workbench + * hub always does — an unconfigured install registers the `process` + * backend — but this package is a library, so a host that registers + * none must still get an honest answer. When false, exclusive * placement can never actually take effect — enabling it would silently * leave a workbench on the shared sidecar despite the setting reading * "on" — so PUT enabling it fails closed with 409, and GET exposes the diff --git a/tsconfig.build.json b/tsconfig.build.json index 7a4de489ae..74fd79f218 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -121,6 +121,9 @@ { "path": "./packages/presence/tsconfig.src.json" }, + { + "path": "./packages/process-provisioner/tsconfig.src.json" + }, { "path": "./packages/reddit-tools/tsconfig.src.json" },