Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(settings): connect remote sandbox providers (#81)

Leo8a2bc20c004d
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index 5c149228e..54bb80758 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -662,7 +662,7 @@ describe("ProviderCommandReactor", () => {
respondingBotId: null,
groupMemberBotIds: [],
},
- botSandbox: null,
+ botSandbox: "local",
runtimeMode: "approval-required",
});
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 82c0a73ab..1edfdb07c 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -15,6 +15,7 @@ import {
ThreadId,
type ProviderSession,
resolveBotMcpServers,
+ SANDBOX_PROVIDER_CREDENTIALS,
type RuntimeMode,
type TurnId,
} from "@t3tools/contracts";
@@ -42,6 +43,7 @@ import type { AgentControllerError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import {
botRuntimeResourceScope,
+ botWorkspaceCredentialFingerprint,
botWorkspaceResourceKey,
} from "../../provider/botWorkspacePool.ts";
import {
@@ -718,8 +720,8 @@ const make = Effect.gen(function* () {
? yield* projectionSnapshotQuery.getOriginalProjectIdByWorkspaceRoot(project.workspaceRoot)
: Option.none<ProjectId>();
const mcpServers = yield* resolveControllerMcpServers(thread);
- const botSandboxBrowserSharing = (yield* serverSettingsService.getSettings)
- .botSandboxBrowserSharing;
+ const serverSettings = yield* serverSettingsService.getSettings;
+ const botSandboxBrowserSharing = serverSettings.botSandboxBrowserSharing;
const respondingBotId = resolveControllerBotId(thread);
const respondingBot =
respondingBotId === null
@@ -733,6 +735,28 @@ const make = Effect.gen(function* () {
: (yield* projectionSnapshotQuery.getCommandReadModel()).groups.find(
(group) => group.id === thread.groupId,
);
+ const effectiveSandbox = respondingBot?.sandbox ?? serverSettings.sandbox.defaultProvider;
+ const sandboxEnvironment =
+ effectiveSandbox === "local"
+ ? undefined
+ : Object.fromEntries(
+ serverSettings.sandbox.providers[effectiveSandbox].environment.map((variable) => [
+ variable.name,
+ variable.value,
+ ]),
+ );
+ if (effectiveSandbox !== "local") {
+ const missingCredential = SANDBOX_PROVIDER_CREDENTIALS[effectiveSandbox].find(
+ (credential) => !(sandboxEnvironment?.[credential.name] ?? "").trim(),
+ );
+ if (missingCredential) {
+ return yield* new ProviderAdapterRequestError({
+ provider: providerErrorLabel(preferredProvider),
+ method: "thread.turn.start",
+ detail: `Connect ${effectiveSandbox} in Settings before using it as a bot sandbox.`,
+ });
+ }
+ }
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: project ? [project] : [],
@@ -743,7 +767,12 @@ const make = Effect.gen(function* () {
...(respondingBotId ? { botId: respondingBotId } : {}),
threadId,
}),
- sandbox: respondingBot?.sandbox ?? null,
+ sandbox: effectiveSandbox,
+ ...(sandboxEnvironment
+ ? {
+ credentialFingerprint: botWorkspaceCredentialFingerprint(sandboxEnvironment),
+ }
+ : {}),
});
const startProviderSession = (input?: {
@@ -778,7 +807,8 @@ const make = Effect.gen(function* () {
},
}
: {}),
- botSandbox: respondingBot?.sandbox ?? null,
+ botSandbox: effectiveSandbox,
+ ...(sandboxEnvironment ? { botSandboxEnvironment: sandboxEnvironment } : {}),
botSandboxBrowserSharing,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
diff --git a/apps/server/src/provider/AkeruSessionResources.ts b/apps/server/src/provider/AkeruSessionResources.ts
index e3805e664..378dee6dd 100644
--- a/apps/server/src/provider/AkeruSessionResources.ts
+++ b/apps/server/src/provider/AkeruSessionResources.ts
@@ -38,6 +38,7 @@ export interface AkeruSessionResourceInput {
readonly workspaceResourceKey: string;
readonly workspaceId: string;
readonly botSandbox?: BotSandbox | null;
+ readonly sandboxEnvironment?: Readonly<Record<string, string>>;
readonly userComputerCwd?: string;
readonly mcpServers: readonly McpServer[];
}
@@ -132,7 +133,10 @@ export class AkeruSessionResources {
"provider.json",
),
...(isRemoteBotSandbox(input.botSandbox)
- ? { sandbox: input.botSandbox }
+ ? {
+ sandbox: input.botSandbox,
+ ...(input.sandboxEnvironment ? { environment: input.sandboxEnvironment } : {}),
+ }
: {
sandbox: "local" as const,
localRoot: NodePath.join(
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index 26dbb534e..292a283a3 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -2165,9 +2165,19 @@ describe("AgentControllerLive", () => {
}).pipe(Effect.provide(layer), Effect.orDie);
});
- it.effect("creates a remote Mastra workspace for the bot sandbox provider", () => {
+ it.effect("creates a credentialed remote workspace for a delegated sandbox grant", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
+ const access: AkeruDelegationAccessGrant = {
+ allowedToolIds: ["Shell", "Read"],
+ memoryScopes: [],
+ sandbox: "upstash",
+ runtimeMode: "full-access",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "secrets",
+ };
const remote = new Workspace({
filesystem: new LocalFilesystem({ basePath: process.cwd() }),
sandbox: new LocalSandbox({ workingDirectory: process.cwd() }),
@@ -2183,6 +2193,14 @@ describe("AgentControllerLive", () => {
makeMastraHarness: mastra.factory,
makeRemoteWorkspace,
makeBotBrowser: makeBotBrowser as never,
+ delegationRuntime: {
+ send: vi.fn(async () => null),
+ sendToUser: vi.fn(async () => {
+ throw new Error("not used");
+ }),
+ parentFinished: vi.fn(async () => undefined),
+ accessForThread: () => access,
+ },
}).pipe(
Layer.provide(
Layer.mergeAll(
@@ -2205,6 +2223,10 @@ describe("AgentControllerLive", () => {
modelSelection: codexSelection,
runtimeMode: "full-access",
botSandbox: "upstash",
+ botSandboxEnvironment: {
+ UPSTASH_REDIS_REST_URL: "https://sandbox.example",
+ UPSTASH_REDIS_REST_TOKEN: "sandbox-token",
+ },
});
expect(makeRemoteWorkspace).toHaveBeenCalledOnce();
@@ -2212,6 +2234,10 @@ describe("AgentControllerLive", () => {
expect.objectContaining({
threadId: `thread-${codexThreadId}`,
sandbox: "upstash",
+ environment: {
+ UPSTASH_REDIS_REST_URL: "https://sandbox.example",
+ UPSTASH_REDIS_REST_TOKEN: "sandbox-token",
+ },
workspaceId: expect.stringMatching(/^akeru-[a-f0-9]{24}$/),
identityFile: expect.stringMatching(/provider\.json$/),
}),
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index e7bba1c00..92d9a8d00 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -109,6 +109,7 @@ import {
import type { AkeruBotWorkspace, CreateRemoteBotWorkspaceInput } from "../botWorkspace.ts";
import {
botRuntimeResourceScope,
+ botWorkspaceCredentialFingerprint,
botWorkspaceIdentity,
botWorkspaceResourceKey,
} from "../botWorkspacePool.ts";
@@ -1285,6 +1286,11 @@ const make = (options?: AgentControllerLiveOptions) =>
const workspaceResourceKey = botWorkspaceResourceKey({
resourceScope,
sandbox: access.sandbox,
+ ...(access.sandbox !== null && access.sandbox !== "local" && input.botSandboxEnvironment
+ ? {
+ credentialFingerprint: botWorkspaceCredentialFingerprint(input.botSandboxEnvironment),
+ }
+ : {}),
});
const workspaceId = botWorkspaceIdentity(workspaceResourceKey);
const existing = sessions.get(key);
@@ -1393,6 +1399,11 @@ const make = (options?: AgentControllerLiveOptions) =>
workspaceResourceKey,
workspaceId,
...(access.sandbox !== null ? { botSandbox: access.sandbox } : {}),
+ ...(access.sandbox !== null &&
+ access.sandbox !== "local" &&
+ input.botSandboxEnvironment
+ ? { sandboxEnvironment: input.botSandboxEnvironment }
+ : {}),
...((!delegatedAccess || access.hasUserComputer) && input.cwd
? { userComputerCwd: input.cwd }
: {}),
diff --git a/apps/server/src/provider/botWorkspace.test.ts b/apps/server/src/provider/botWorkspace.test.ts
index d7a4840bc..84e01e216 100644
--- a/apps/server/src/provider/botWorkspace.test.ts
+++ b/apps/server/src/provider/botWorkspace.test.ts
@@ -71,12 +71,22 @@ describe("createBotWorkspace", () => {
threadId: "thread-vercel",
sandbox: "vercel",
workspaceId: "akeru-vercel",
+ environment: {
+ VERCEL_TOKEN: "token",
+ VERCEL_TEAM_ID: "team",
+ VERCEL_PROJECT_ID: "project",
+ },
makeRemoteWorkspace,
});
expect(makeRemoteWorkspace).toHaveBeenCalledWith({
threadId: "thread-vercel",
sandbox: "vercel",
workspaceId: "akeru-vercel",
+ environment: {
+ VERCEL_TOKEN: "token",
+ VERCEL_TEAM_ID: "team",
+ VERCEL_PROJECT_ID: "project",
+ },
});
await remote.destroy();
});
diff --git a/apps/server/src/provider/botWorkspace.ts b/apps/server/src/provider/botWorkspace.ts
index a7600544b..ea8e10b4e 100644
--- a/apps/server/src/provider/botWorkspace.ts
+++ b/apps/server/src/provider/botWorkspace.ts
@@ -55,6 +55,7 @@ export interface CreateRemoteBotWorkspaceInput {
readonly sandbox: RemoteBotSandbox;
readonly identityFile?: string;
readonly workspaceId?: string;
+ readonly environment?: Readonly<Record<string, string>>;
readonly openSession?: (providerId?: string) => Promise<AkeruRemoteSession>;
}
@@ -65,6 +66,7 @@ export interface CreateBotWorkspaceInput {
readonly localRoot?: string;
readonly sandbox?: BotSandbox | null;
readonly workspaceId?: string;
+ readonly environment?: Readonly<Record<string, string>>;
readonly makeRemoteWorkspace?: (
input: CreateRemoteBotWorkspaceInput,
) => Promise<AkeruBotWorkspace | Workspace>;
@@ -85,6 +87,7 @@ export async function createBotWorkspace(
sandbox: input.sandbox,
...(input.identityFile ? { identityFile: input.identityFile } : {}),
...(input.workspaceId ? { workspaceId: input.workspaceId } : {}),
+ ...(input.environment ? { environment: input.environment } : {}),
});
return remote instanceof Workspace ? wrap(remote, input.sandbox) : remote;
}
@@ -117,8 +120,8 @@ export async function createRemoteBotWorkspace(
session = input.openSession
? await input.openSession(persisted?.providerId)
: persisted
- ? await open(input.sandbox, persisted.providerId)
- : await create(input.sandbox, input.workspaceId);
+ ? await open(input.sandbox, persisted.providerId, input.environment)
+ : await create(input.sandbox, input.workspaceId, input.environment);
} catch (cause) {
if (!persisted) throw cause;
throw new Error(
@@ -259,55 +262,92 @@ const quote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
const commandLine = (command: string, args: readonly string[]) =>
[command, ...args].map(quote).join(" ");
-async function create(provider: RemoteBotSandbox, id: string): Promise<AkeruRemoteSession> {
+function credential(environment: Readonly<Record<string, string>>, name: string): string {
+ const value = environment[name]?.trim();
+ if (!value) throw new Error(`Remote sandbox credential '${name}' is missing.`);
+ return value;
+}
+
+async function create(
+ provider: RemoteBotSandbox,
+ id: string,
+ environment: Readonly<Record<string, string>> = {},
+): Promise<AkeruRemoteSession> {
if (provider === "e2b") {
const { Sandbox } = await import("e2b");
+ const apiKey = credential(environment, "E2B_API_KEY");
return e2b(
await Sandbox.create({
+ apiKey,
lifecycle: { onTimeout: "pause" },
network: { allowPublicTraffic: false },
}),
+ apiKey,
);
}
if (provider === "daytona") {
const { Daytona } = await import("@daytona/sdk");
- const client = new Daytona();
+ const client = new Daytona({ apiKey: credential(environment, "DAYTONA_API_KEY") });
return daytona(client, await client.create({ name: id }));
}
if (provider === "vercel") {
const { Sandbox } = await import("@vercel/sandbox");
- return vercel(await Sandbox.create({ name: id, persistent: true }));
+ return vercel(
+ await Sandbox.create({
+ name: id,
+ persistent: true,
+ token: credential(environment, "VERCEL_TOKEN"),
+ teamId: credential(environment, "VERCEL_TEAM_ID"),
+ projectId: credential(environment, "VERCEL_PROJECT_ID"),
+ }),
+ environment,
+ );
}
const { Box } = await import("@upstash/box");
- return upstash(await Box.create());
+ return upstash(await Box.create({ apiKey: credential(environment, "UPSTASH_BOX_API_KEY") }));
}
-async function open(provider: RemoteBotSandbox, id: string): Promise<AkeruRemoteSession> {
+async function open(
+ provider: RemoteBotSandbox,
+ id: string,
+ environment: Readonly<Record<string, string>> = {},
+): Promise<AkeruRemoteSession> {
if (provider === "e2b") {
const { Sandbox } = await import("e2b");
- return e2b(await Sandbox.connect(id));
+ const apiKey = credential(environment, "E2B_API_KEY");
+ return e2b(await Sandbox.connect(id, { apiKey }), apiKey);
}
if (provider === "daytona") {
const { Daytona } = await import("@daytona/sdk");
- const client = new Daytona();
+ const client = new Daytona({ apiKey: credential(environment, "DAYTONA_API_KEY") });
return daytona(client, await client.get(id));
}
if (provider === "vercel") {
const { Sandbox } = await import("@vercel/sandbox");
- return vercel(await Sandbox.get({ name: id, resume: true }));
+ return vercel(
+ await Sandbox.get({
+ name: id,
+ resume: true,
+ token: credential(environment, "VERCEL_TOKEN"),
+ teamId: credential(environment, "VERCEL_TEAM_ID"),
+ projectId: credential(environment, "VERCEL_PROJECT_ID"),
+ }),
+ environment,
+ );
}
const { Box } = await import("@upstash/box");
- return upstash(await Box.get(id));
+ return upstash(await Box.get(id, { apiKey: credential(environment, "UPSTASH_BOX_API_KEY") }));
}
-export function e2b(initial: import("e2b").Sandbox): AkeruRemoteSession {
+export function e2b(initial: import("e2b").Sandbox, apiKey?: string): AkeruRemoteSession {
let sandbox = initial;
const providerId = sandbox.sandboxId;
+ const options = apiKey ? { apiKey } : {};
return {
providerId,
inspect: async () => {
const { Sandbox } = await import("e2b");
- const info = await Sandbox.getInfo(providerId);
+ const info = await Sandbox.getInfo(providerId, options);
return info.state === "paused" ? "sleeping" : "running";
},
run: async (command, args, options) => {
@@ -328,7 +368,7 @@ export function e2b(initial: import("e2b").Sandbox): AkeruRemoteSession {
},
wake: async () => {
const { Sandbox } = await import("e2b");
- sandbox = await Sandbox.connect(providerId);
+ sandbox = await Sandbox.connect(providerId, options);
},
sleep: async () => {
await sandbox.pause();
@@ -390,13 +430,22 @@ export function vercelWorkspaceState(
return "sleeping";
}
-export function vercel(initial: import("@vercel/sandbox").Sandbox): AkeruRemoteSession {
+export function vercel(
+ initial: import("@vercel/sandbox").Sandbox,
+ environment: Readonly<Record<string, string>> = {},
+): AkeruRemoteSession {
let sandbox = initial;
return {
providerId: sandbox.name,
inspect: async () => {
const { Sandbox } = await import("@vercel/sandbox");
- sandbox = await Sandbox.get({ name: sandbox.name, resume: false });
+ sandbox = await Sandbox.get({
+ name: sandbox.name,
+ resume: false,
+ token: credential(environment, "VERCEL_TOKEN"),
+ teamId: credential(environment, "VERCEL_TEAM_ID"),
+ projectId: credential(environment, "VERCEL_PROJECT_ID"),
+ });
return vercelWorkspaceState(sandbox.status);
},
run: async (command, args, options) => {
@@ -421,7 +470,13 @@ export function vercel(initial: import("@vercel/sandbox").Sandbox): AkeruRemoteS
},
wake: async () => {
const { Sandbox } = await import("@vercel/sandbox");
- sandbox = await Sandbox.get({ name: sandbox.name, resume: true });
+ sandbox = await Sandbox.get({
+ name: sandbox.name,
+ resume: true,
+ token: credential(environment, "VERCEL_TOKEN"),
+ teamId: credential(environment, "VERCEL_TEAM_ID"),
+ projectId: credential(environment, "VERCEL_PROJECT_ID"),
+ });
},
sleep: async () => {
await sandbox.stop();
diff --git a/apps/server/src/provider/botWorkspacePool.test.ts b/apps/server/src/provider/botWorkspacePool.test.ts
index 084ac22a7..ef83834d1 100644
--- a/apps/server/src/provider/botWorkspacePool.test.ts
+++ b/apps/server/src/provider/botWorkspacePool.test.ts
@@ -5,7 +5,9 @@ import { describe, expect, it, vi } from "vite-plus/test";
import {
botRuntimeResourceScope,
BotWorkspacePool,
+ botWorkspaceCredentialFingerprint,
botWorkspaceIdentity,
+ botWorkspaceResourceKey,
} from "./botWorkspacePool.ts";
function localWorkspace() {
@@ -32,6 +34,21 @@ describe("BotWorkspacePool", () => {
}),
).toBe("bot-bot-one");
expect(botWorkspaceIdentity("local:/private:bot-one")).not.toContain("private");
+ const firstCredential = botWorkspaceCredentialFingerprint({ E2B_API_KEY: "first" });
+ const secondCredential = botWorkspaceCredentialFingerprint({ E2B_API_KEY: "second" });
+ expect(
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "e2b",
+ credentialFingerprint: firstCredential,
+ }),
+ ).not.toBe(
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "e2b",
+ credentialFingerprint: secondCredential,
+ }),
+ );
});
it("sleeps after final release and wakes once on reuse", async () => {
diff --git a/apps/server/src/provider/botWorkspacePool.ts b/apps/server/src/provider/botWorkspacePool.ts
index 33d9a79d8..0d959ca30 100644
--- a/apps/server/src/provider/botWorkspacePool.ts
+++ b/apps/server/src/provider/botWorkspacePool.ts
@@ -18,11 +18,24 @@ export function botWorkspaceResourceKey(input: {
readonly resourceScope: string;
readonly cwd?: string;
readonly sandbox?: BotSandbox | null;
+ readonly credentialFingerprint?: string;
}): string {
const sandbox = input.sandbox ?? "local";
return sandbox === "local"
? `${sandbox}:${input.cwd ?? "no-workspace"}:${input.resourceScope}`
- : `${sandbox}:${input.resourceScope}`;
+ : `${sandbox}:${input.credentialFingerprint ?? "no-credentials"}:${input.resourceScope}`;
+}
+
+export function botWorkspaceCredentialFingerprint(
+ environment: Readonly<Record<string, string>>,
+): string {
+ return NodeCrypto.createHash("sha256")
+ .update(
+ JSON.stringify(
+ Object.entries(environment).toSorted(([left], [right]) => left.localeCompare(right)),
+ ),
+ )
+ .digest("hex");
}
export function botWorkspaceIdentity(resourceKey: string): string {
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index 8949b8b40..eccef4fd3 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1120,4 +1120,125 @@ it.layer(NodeServices.layer)("server settings", (it) => {
);
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
+
+ it.effect("rejects plaintext sandbox secrets loaded from settings.json", () =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ yield* fileSystem.writeFileString(
+ serverConfig.settingsPath,
+ '{"sandbox":{"providers":{"e2b":{"environment":[{"name":"E2B_API_KEY","value":"plaintext-key","sensitive":true}]}}}}',
+ );
+
+ const error = yield* Effect.flip(serverSettings.getSettings);
+ assert.deepInclude(error, {
+ operation: "validate-sandbox",
+ providerInstanceId: "sandbox:e2b",
+ environmentVariable: "E2B_API_KEY",
+ });
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
+
+ it.effect("rejects plaintext sandbox secrets after a valid redacted marker", () =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ yield* fileSystem.writeFileString(
+ serverConfig.settingsPath,
+ '{"sandbox":{"providers":{"e2b":{"environment":[{"name":"E2B_API_KEY","value":"","sensitive":true,"valueRedacted":true},{"name":"E2B_API_KEY","value":"plaintext-key","sensitive":true}]}}}}',
+ );
+
+ const error = yield* Effect.flip(serverSettings.getSettings);
+ assert.deepInclude(error, {
+ operation: "validate-sandbox",
+ providerInstanceId: "sandbox:e2b",
+ environmentVariable: "E2B_API_KEY",
+ });
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
+
+ it.effect("rejects incomplete sandbox connections", () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const error = yield* Effect.flip(
+ serverSettings.updateSettings({
+ sandbox: {
+ providers: {
+ vercel: {
+ environment: [
+ { name: "VERCEL_TOKEN", value: "secret", sensitive: true },
+ { name: "VERCEL_TEAM_ID", value: "team", sensitive: false },
+ ],
+ },
+ },
+ },
+ }),
+ );
+ assert.deepInclude(error, {
+ operation: "validate-sandbox",
+ providerInstanceId: "sandbox:vercel",
+ environmentVariable: "VERCEL_PROJECT_ID",
+ });
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
+
+ it.effect("rejects a sandbox secret marker without a stored secret", () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const error = yield* Effect.flip(
+ serverSettings.updateSettings({
+ sandbox: {
+ providers: {
+ e2b: {
+ environment: [
+ { name: "E2B_API_KEY", value: "", sensitive: true, valueRedacted: true },
+ ],
+ },
+ },
+ },
+ }),
+ );
+ assert.deepInclude(error, {
+ operation: "validate-sandbox",
+ providerInstanceId: "sandbox:e2b",
+ environmentVariable: "E2B_API_KEY",
+ });
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
+
+ it.effect("stores sandbox secrets outside settings.json and redacts client settings", () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+
+ const next = yield* serverSettings.updateSettings({
+ sandbox: {
+ defaultProvider: "e2b",
+ providers: {
+ e2b: {
+ environment: [{ name: "E2B_API_KEY", value: "e2b-secret", sensitive: true }],
+ },
+ },
+ },
+ });
+
+ assert.equal(next.sandbox.providers.e2b.environment[0]?.value, "e2b-secret");
+ const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
+ assert.notInclude(raw, "e2b-secret");
+
+ const clientSettings = ServerSettingsModule.redactServerSettingsForClient(next);
+ assert.deepInclude(clientSettings.sandbox.providers.e2b.environment[0], {
+ value: "",
+ valueRedacted: true,
+ });
+
+ const roundTripped = yield* serverSettings.updateSettings({
+ sandbox: clientSettings.sandbox,
+ });
+ assert.equal(roundTripped.sandbox.providers.e2b.environment[0]?.value, "e2b-secret");
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
});
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index dbe97c9ea..ba03a2a5c 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -11,6 +11,8 @@
* @module ServerSettings
*/
import {
+ type CloudSandboxProvider,
+ CLOUD_SANDBOX_PROVIDERS,
DEFAULT_TEXT_GENERATION_MODEL,
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
DEFAULT_MODEL_BY_PROVIDER,
@@ -20,6 +22,8 @@ import {
type ProviderInstanceEnvironmentVariable,
ProviderDriverKind,
ProviderInstanceId,
+ type SandboxProviderConnection,
+ SANDBOX_PROVIDER_CREDENTIALS,
ServerSettings,
ServerSettingsError,
type ServerSettingsPatch,
@@ -133,6 +137,13 @@ function providerEnvironmentSecretName(input: {
return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`;
}
+function sandboxEnvironmentSecretName(input: {
+ readonly provider: CloudSandboxProvider;
+ readonly name: string;
+}): string {
+ return `sandbox-env-${input.provider}-${Buffer.from(input.name, "utf8").toString("base64url")}`;
+}
+
function redactProviderEnvironmentVariable(
variable: ProviderInstanceEnvironmentVariable,
): ProviderInstanceEnvironmentVariable {
@@ -147,6 +158,14 @@ function redactProviderEnvironmentVariable(
};
}
+function redactSandboxProviderConnection(
+ connection: SandboxProviderConnection,
+): SandboxProviderConnection {
+ return {
+ environment: connection.environment.map(redactProviderEnvironmentVariable),
+ };
+}
+
export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
const providerInstances = Object.fromEntries(
Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
@@ -159,7 +178,19 @@ export function redactServerSettingsForClient(settings: ServerSettings): ServerS
: instance,
]),
);
- return { ...settings, providerInstances };
+ return {
+ ...settings,
+ providerInstances,
+ sandbox: {
+ ...settings.sandbox,
+ providers: {
+ e2b: redactSandboxProviderConnection(settings.sandbox.providers.e2b),
+ daytona: redactSandboxProviderConnection(settings.sandbox.providers.daytona),
+ vercel: redactSandboxProviderConnection(settings.sandbox.providers.vercel),
+ upstash: redactSandboxProviderConnection(settings.sandbox.providers.upstash),
+ },
+ },
+ };
}
export class ServerSettingsService extends Context.Service<
@@ -466,9 +497,13 @@ const make = Effect.gen(function* () {
),
);
- return foldProviderInstanceEnabledFlags(
+ const normalized = foldProviderInstanceEnabledFlags(
restoreUsedProviders(settings, persisted, providerHistory),
);
+ yield* validatePersistedSandboxSecrets(normalized);
+ const sandboxMaterialized = yield* materializeSandboxEnvironmentSecrets(normalized);
+ yield* validateSandboxSettings(sandboxMaterialized);
+ return normalized;
});
const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
@@ -523,12 +558,204 @@ const make = Effect.gen(function* () {
};
});
+ const materializeSandboxEnvironmentSecrets = (
+ settings: ServerSettings,
+ ): Effect.Effect<ServerSettings, ServerSettingsError> =>
+ Effect.gen(function* () {
+ const providers = { ...settings.sandbox.providers };
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ const environment: ProviderInstanceEnvironmentVariable[] = [];
+ for (const variable of settings.sandbox.providers[provider].environment) {
+ if (!variable.sensitive || !variable.valueRedacted) {
+ environment.push(variable);
+ continue;
+ }
+ const secret = yield* secretStore
+ .get(sandboxEnvironmentSecretName({ provider, name: variable.name }))
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "read-secret",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ cause,
+ }),
+ ),
+ );
+ environment.push({
+ ...variable,
+ value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
+ });
+ }
+ providers[provider] = { environment } satisfies SandboxProviderConnection;
+ }
+ return {
+ ...settings,
+ sandbox: { ...settings.sandbox, providers },
+ };
+ });
+
+ const sandboxValidationError = (
+ provider: CloudSandboxProvider,
+ environmentVariable: string,
+ cause: string,
+ ) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "validate-sandbox",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable,
+ cause: new Error(cause),
+ });
+
+ const validatePersistedSandboxSecrets = (settings: ServerSettings) =>
+ Effect.gen(function* () {
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ const variables = settings.sandbox.providers[provider].environment;
+ for (const credential of SANDBOX_PROVIDER_CREDENTIALS[provider]) {
+ if (!credential.sensitive) continue;
+ const hasInvalidMarker = variables.some(
+ (variable) =>
+ variable.name === credential.name &&
+ (variable.sensitive !== true ||
+ variable.valueRedacted !== true ||
+ variable.value.length > 0),
+ );
+ if (!hasInvalidMarker) continue;
+ return yield* sandboxValidationError(
+ provider,
+ credential.name,
+ "Persisted sandbox secrets must use a redacted secret-store marker.",
+ );
+ }
+ }
+ });
+
+ const validateSandboxSettings = (settings: ServerSettings) =>
+ Effect.gen(function* () {
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ const environment = settings.sandbox.providers[provider].environment;
+ const credentials = SANDBOX_PROVIDER_CREDENTIALS[provider];
+ for (const credential of credentials) {
+ if (
+ credential.sensitive &&
+ environment.some(
+ (variable) => variable.name === credential.name && variable.sensitive !== true,
+ )
+ ) {
+ return yield* sandboxValidationError(
+ provider,
+ credential.name,
+ "Sandbox secret credentials must be marked sensitive.",
+ );
+ }
+ }
+
+ if (environment.length === 0 && settings.sandbox.defaultProvider !== provider) continue;
+ const values = new Map(environment.map((variable) => [variable.name, variable.value]));
+ for (const credential of credentials) {
+ if ((values.get(credential.name) ?? "").trim().length > 0) continue;
+ return yield* sandboxValidationError(
+ provider,
+ credential.name,
+ "The sandbox provider is missing a required credential.",
+ );
+ }
+ }
+ });
+
+ const materializeAllSecrets = (settings: ServerSettings) =>
+ materializeProviderEnvironmentSecrets(settings).pipe(
+ Effect.flatMap(materializeSandboxEnvironmentSecrets),
+ );
+
+ type SecretSnapshot = {
+ readonly name: string;
+ readonly previous: Option.Option<Uint8Array>;
+ readonly providerInstanceId: string;
+ readonly environmentVariable: string;
+ };
+
+ const snapshotSettingsSecrets = (current: ServerSettings, next: ServerSettings) =>
+ Effect.gen(function* () {
+ const references = new Map<
+ string,
+ Pick<SecretSnapshot, "providerInstanceId" | "environmentVariable">
+ >();
+ for (const settings of [current, next]) {
+ for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
+ for (const variable of instance.environment ?? []) {
+ references.set(providerEnvironmentSecretName({ instanceId, name: variable.name }), {
+ providerInstanceId: instanceId,
+ environmentVariable: variable.name,
+ });
+ }
+ }
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ for (const variable of settings.sandbox.providers[provider].environment) {
+ references.set(sandboxEnvironmentSecretName({ provider, name: variable.name }), {
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ });
+ }
+ }
+ }
+
+ const snapshots: SecretSnapshot[] = [];
+ for (const [name, reference] of references) {
+ const previous = yield* secretStore.get(name).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "read-secret",
+ ...reference,
+ cause,
+ }),
+ ),
+ );
+ snapshots.push({ name, previous, ...reference });
+ }
+ return snapshots;
+ });
+
+ const rollbackSettingsSecrets = (snapshots: ReadonlyArray<SecretSnapshot>) =>
+ Effect.gen(function* () {
+ let firstFailure: ServerSettingsError | undefined;
+ for (const snapshot of snapshots.toReversed()) {
+ const restore = Option.match(snapshot.previous, {
+ onNone: () => secretStore.remove(snapshot.name),
+ onSome: (value) => secretStore.set(snapshot.name, value),
+ }).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "rollback-secret",
+ providerInstanceId: snapshot.providerInstanceId,
+ environmentVariable: snapshot.environmentVariable,
+ cause,
+ }),
+ ),
+ );
+ yield* restore.pipe(
+ Effect.catch((error) => {
+ firstFailure ??= error;
+ return Effect.void;
+ }),
+ );
+ }
+ if (firstFailure) return yield* firstFailure;
+ });
+
const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
changes.pipe(
Stream.mapEffect((settings) =>
- materializeProviderEnvironmentSecrets(settings).pipe(
+ materializeAllSecrets(settings).pipe(
Effect.catch((error: ServerSettingsError) =>
- Effect.logWarning("failed to materialize provider environment secrets", {
+ Effect.logWarning("failed to materialize settings secrets", {
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
@@ -641,6 +868,101 @@ const make = Effect.gen(function* () {
};
});
+ const persistSandboxEnvironmentSecrets = (
+ current: ServerSettings,
+ next: ServerSettings,
+ ): Effect.Effect<ServerSettings, ServerSettingsError> =>
+ Effect.gen(function* () {
+ const providers = { ...next.sandbox.providers };
+ const nextSecretKeys = new Set<string>();
+
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ const environment: ProviderInstanceEnvironmentVariable[] = [];
+ for (const variable of next.sandbox.providers[provider].environment) {
+ const secretName = sandboxEnvironmentSecretName({ provider, name: variable.name });
+ if (!variable.sensitive) {
+ yield* secretStore.remove(secretName).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "remove-secret",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ cause,
+ }),
+ ),
+ );
+ environment.push(redactProviderEnvironmentVariable(variable));
+ continue;
+ }
+
+ nextSecretKeys.add(secretName);
+ if (!variable.valueRedacted) {
+ if (variable.value.length > 0) {
+ yield* secretStore.set(secretName, textEncoder.encode(variable.value)).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "write-secret",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ cause,
+ }),
+ ),
+ );
+ environment.push({ ...variable, value: "", valueRedacted: true });
+ } else {
+ yield* secretStore.remove(secretName).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "remove-secret",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ cause,
+ }),
+ ),
+ );
+ const { valueRedacted: _omit, ...rest } = variable;
+ environment.push(rest);
+ }
+ continue;
+ }
+
+ environment.push(redactProviderEnvironmentVariable(variable));
+ }
+ providers[provider] = { environment } satisfies SandboxProviderConnection;
+ }
+
+ for (const provider of CLOUD_SANDBOX_PROVIDERS) {
+ for (const variable of current.sandbox.providers[provider].environment) {
+ if (!variable.sensitive) continue;
+ const secretName = sandboxEnvironmentSecretName({ provider, name: variable.name });
+ if (nextSecretKeys.has(secretName)) continue;
+ yield* secretStore.remove(secretName).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "remove-stale-secret",
+ providerInstanceId: `sandbox:${provider}`,
+ environmentVariable: variable.name,
+ cause,
+ }),
+ ),
+ );
+ }
+ }
+
+ return {
+ ...next,
+ sandbox: { ...next.sandbox, providers },
+ };
+ });
+
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
const sparseSettingsJson = yield* encodeServerSettingsJson(
@@ -737,19 +1059,47 @@ const make = Effect.gen(function* () {
start,
ready: Deferred.await(startedDeferred),
getSettings: getSettingsFromCache.pipe(
- Effect.flatMap(materializeProviderEnvironmentSecrets),
+ Effect.flatMap(materializeAllSecrets),
Effect.map(resolveTextGenerationProvider),
),
updateSettings: (patch) =>
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
- const nextPersisted = yield* persistProviderEnvironmentSecrets(
- current,
- applyServerSettingsPatch(current, patch),
+ const patched = applyServerSettingsPatch(current, patch);
+ const sandboxMaterialized = yield* materializeSandboxEnvironmentSecrets(patched);
+ yield* validateSandboxSettings(sandboxMaterialized);
+ const secretSnapshots = yield* snapshotSettingsSecrets(current, patched);
+ const next = yield* Effect.gen(function* () {
+ const providerSecretsPersisted = yield* persistProviderEnvironmentSecrets(
+ current,
+ patched,
+ );
+ const nextPersisted = yield* persistSandboxEnvironmentSecrets(current, {
+ ...providerSecretsPersisted,
+ sandbox: sandboxMaterialized.sandbox,
+ });
+ const normalized = yield* normalizeServerSettings(nextPersisted);
+ yield* writeSettingsAtomically(normalized);
+ return normalized;
+ }).pipe(
+ Effect.onExit((exit) => {
+ if (Exit.isSuccess(exit)) return Effect.void;
+ return rollbackSettingsSecrets(secretSnapshots).pipe(
+ Effect.mapError(
+ (rollbackError) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "rollback-secret",
+ cause: new AggregateError(
+ [Cause.squash(exit.cause), rollbackError],
+ "Failed to restore server settings secrets after an update failure.",
+ ),
+ }),
+ ),
+ );
+ }),
);
- const next = yield* normalizeServerSettings(nextPersisted);
- yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
if (patch.analyticsEnabled === false) {
@@ -769,7 +1119,7 @@ const make = Effect.gen(function* () {
{ concurrency: "unbounded", discard: true },
);
}
- const materialized = yield* materializeProviderEnvironmentSecrets(next);
+ const materialized = yield* materializeAllSecrets(next);
return resolveTextGenerationProvider(materialized);
}),
),
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts b/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts
new file mode 100644
index 000000000..1f862b210
--- /dev/null
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts
@@ -0,0 +1,59 @@
+import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ canSaveSandboxProviderConnection,
+ disconnectSandboxProvider,
+ isSandboxProviderConnected,
+ saveSandboxProviderConnection,
+ selectableSandboxProviders,
+} from "./SandboxSettingsPanel.logic";
+
+describe("sandbox settings", () => {
+ it("offers only local until a cloud provider is connected", () => {
+ expect(selectableSandboxProviders(DEFAULT_SERVER_SETTINGS.sandbox)).toEqual(["local"]);
+ });
+
+ it("connects E2B and makes it available as a default", () => {
+ const sandbox = saveSandboxProviderConnection({
+ settings: DEFAULT_SERVER_SETTINGS.sandbox,
+ provider: "e2b",
+ draft: { E2B_API_KEY: " e2b-secret " },
+ });
+ expect(isSandboxProviderConnected(sandbox, "e2b")).toBe(true);
+ expect(selectableSandboxProviders(sandbox)).toEqual(["local", "e2b"]);
+ });
+
+ it("requires all Vercel credentials", () => {
+ expect(
+ canSaveSandboxProviderConnection({
+ settings: DEFAULT_SERVER_SETTINGS.sandbox,
+ provider: "vercel",
+ draft: { VERCEL_TOKEN: "token", VERCEL_TEAM_ID: "team", VERCEL_PROJECT_ID: "" },
+ }),
+ ).toBe(false);
+ });
+
+ it("keeps a redacted key and falls back to local on disconnect", () => {
+ const connected = {
+ ...saveSandboxProviderConnection({
+ settings: DEFAULT_SERVER_SETTINGS.sandbox,
+ provider: "e2b",
+ draft: { E2B_API_KEY: "secret" },
+ }),
+ defaultProvider: "e2b" as const,
+ };
+ const redacted = {
+ ...connected,
+ providers: {
+ ...connected.providers,
+ e2b: {
+ environment: [{ name: "E2B_API_KEY", value: "", sensitive: true, valueRedacted: true }],
+ },
+ },
+ };
+ const saved = saveSandboxProviderConnection({ settings: redacted, provider: "e2b", draft: {} });
+ expect(saved.providers.e2b.environment[0]?.valueRedacted).toBe(true);
+ expect(disconnectSandboxProvider(saved, "e2b").defaultProvider).toBe("local");
+ });
+});
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts b/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts
new file mode 100644
index 000000000..a9c459de5
--- /dev/null
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts
@@ -0,0 +1,142 @@
+import type {
+ ProviderInstanceEnvironmentVariable,
+ SandboxProvider,
+ SandboxSettings,
+} from "@t3tools/contracts";
+
+export type CloudSandboxProvider = Exclude<SandboxProvider, "local">;
+
+export interface SandboxCredentialField {
+ readonly name: string;
+ readonly label: string;
+ readonly secret: boolean;
+}
+
+export interface SandboxProviderDefinition {
+ readonly id: CloudSandboxProvider;
+ readonly label: string;
+ readonly description: string;
+ readonly fields: ReadonlyArray<SandboxCredentialField>;
+}
+
+const SANDBOX_PROVIDER_DEFINITION_BY_ID: Readonly<
+ Record<CloudSandboxProvider, SandboxProviderDefinition>
+> = {
+ e2b: {
+ id: "e2b",
+ label: "E2B",
+ description: "Run bots in an E2B sandbox with your API key.",
+ fields: [{ name: "E2B_API_KEY", label: "API key", secret: true }],
+ },
+ daytona: {
+ id: "daytona",
+ label: "Daytona",
+ description: "Run bots in a Daytona sandbox with your API key.",
+ fields: [{ name: "DAYTONA_API_KEY", label: "API key", secret: true }],
+ },
+ vercel: {
+ id: "vercel",
+ label: "Vercel Sandbox",
+ description: "Run bots in your Vercel team and project.",
+ fields: [
+ { name: "VERCEL_TOKEN", label: "Token", secret: true },
+ { name: "VERCEL_TEAM_ID", label: "Team ID", secret: false },
+ { name: "VERCEL_PROJECT_ID", label: "Project ID", secret: false },
+ ],
+ },
+ upstash: {
+ id: "upstash",
+ label: "Upstash Box",
+ description: "Run bots in an Upstash Box with your API key.",
+ fields: [{ name: "UPSTASH_BOX_API_KEY", label: "API key", secret: true }],
+ },
+};
+
+export const SANDBOX_PROVIDER_DEFINITIONS = Object.values(SANDBOX_PROVIDER_DEFINITION_BY_ID);
+
+export function sandboxProviderDefinition(provider: CloudSandboxProvider) {
+ return SANDBOX_PROVIDER_DEFINITION_BY_ID[provider];
+}
+
+export function isSandboxProviderConnected(
+ settings: SandboxSettings,
+ provider: CloudSandboxProvider,
+): boolean {
+ const environment = settings.providers[provider].environment;
+ return sandboxProviderDefinition(provider).fields.every((field) => {
+ const variable = environment.find((candidate) => candidate.name === field.name);
+ return Boolean(variable && (variable.value.trim().length > 0 || variable.valueRedacted));
+ });
+}
+
+export function selectableSandboxProviders(settings: SandboxSettings) {
+ return [
+ "local" as const,
+ ...SANDBOX_PROVIDER_DEFINITIONS.filter((definition) =>
+ isSandboxProviderConnected(settings, definition.id),
+ ).map((definition) => definition.id),
+ ];
+}
+
+export function sandboxConnectionDraft(
+ settings: SandboxSettings,
+ provider: CloudSandboxProvider,
+): Readonly<Record<string, string>> {
+ return Object.fromEntries(
+ sandboxProviderDefinition(provider).fields.map((field) => [
+ field.name,
+ settings.providers[provider].environment.find((variable) => variable.name === field.name)
+ ?.value ?? "",
+ ]),
+ );
+}
+
+export function canSaveSandboxProviderConnection(input: {
+ readonly settings: SandboxSettings;
+ readonly provider: CloudSandboxProvider;
+ readonly draft: Readonly<Record<string, string>>;
+}): boolean {
+ const existing = input.settings.providers[input.provider].environment;
+ return sandboxProviderDefinition(input.provider).fields.every((field) => {
+ if ((input.draft[field.name] ?? "").trim().length > 0) return true;
+ const variable = existing.find((candidate) => candidate.name === field.name);
+ return field.secret && variable?.valueRedacted === true;
+ });
+}
+
+export function saveSandboxProviderConnection(input: {
+ readonly settings: SandboxSettings;
+ readonly provider: CloudSandboxProvider;
+ readonly draft: Readonly<Record<string, string>>;
+}): SandboxSettings {
+ const currentEnvironment = input.settings.providers[input.provider].environment;
+ const environment = sandboxProviderDefinition(input.provider).fields.map((field) => {
+ const value = (input.draft[field.name] ?? "").trim();
+ const current = currentEnvironment.find((variable) => variable.name === field.name);
+ if (field.secret && value.length === 0 && current?.valueRedacted) return current;
+ return {
+ name: field.name,
+ value,
+ sensitive: field.secret,
+ } satisfies ProviderInstanceEnvironmentVariable;
+ });
+
+ return {
+ ...input.settings,
+ providers: {
+ ...input.settings.providers,
+ [input.provider]: { environment },
+ },
+ };
+}
+
+export function disconnectSandboxProvider(
+ settings: SandboxSettings,
+ provider: CloudSandboxProvider,
+): SandboxSettings {
+ return {
+ ...settings,
+ defaultProvider: settings.defaultProvider === provider ? "local" : settings.defaultProvider,
+ providers: { ...settings.providers, [provider]: { environment: [] } },
+ };
+}
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.test.tsx b/apps/web/src/components/settings/SandboxSettingsPanel.test.tsx
new file mode 100644
index 000000000..9fa6fc21b
--- /dev/null
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.test.tsx
@@ -0,0 +1,20 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+const settingsDialog = vi.hoisted(() => ({ environmentId: "environment-a" }));
+
+vi.mock("../../settingsDialogStore", () => ({
+ useSettingsEnvironmentId: () => settingsDialog.environmentId,
+}));
+
+import { SandboxSettingsPanel } from "./SandboxSettingsPanel";
+
+describe("SandboxSettingsPanel", () => {
+ it("keys provider editor state to the selected environment", () => {
+ const first = SandboxSettingsPanel();
+ settingsDialog.environmentId = "environment-b";
+ const second = SandboxSettingsPanel();
+
+ expect(first.key).toBe("environment-a");
+ expect(second.key).toBe("environment-b");
+ });
+});
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.tsx b/apps/web/src/components/settings/SandboxSettingsPanel.tsx
new file mode 100644
index 000000000..a20b96518
--- /dev/null
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.tsx
@@ -0,0 +1,238 @@
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentId, SandboxProvider, SandboxSettings } from "@t3tools/contracts";
+import { useState } from "react";
+
+import { useEnvironmentSettings } from "../../hooks/useSettings";
+import { useSettingsEnvironmentId } from "../../settingsDialogStore";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import {
+ Dialog,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogPopup,
+ DialogTitle,
+} from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { Switch } from "../ui/switch";
+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
+import { searchableSetting } from "./settingsSearch";
+import {
+ canSaveSandboxProviderConnection,
+ type CloudSandboxProvider,
+ disconnectSandboxProvider,
+ isSandboxProviderConnected,
+ SANDBOX_PROVIDER_DEFINITIONS,
+ sandboxConnectionDraft,
+ sandboxProviderDefinition,
+ saveSandboxProviderConnection,
+ selectableSandboxProviders,
+} from "./SandboxSettingsPanel.logic";
+
+const SANDBOX_PROVIDER_LABELS: Readonly<Record<SandboxProvider, string>> = {
+ local: "Local",
+ e2b: "E2B",
+ daytona: "Daytona",
+ vercel: "Vercel Sandbox",
+ upstash: "Upstash Box",
+};
+
+function errorMessage(result: Parameters<typeof squashAtomCommandFailure>[0]) {
+ const error = squashAtomCommandFailure(result);
+ return error instanceof Error && error.message.trim()
+ ? error.message
+ : "The server rejected these sandbox settings.";
+}
+
+export function SandboxSettingsPanel() {
+ const environmentId = useSettingsEnvironmentId();
+ if (environmentId === null) {
+ return (
+ <div className="p-6 text-sm text-muted-foreground">Connect to an environment first.</div>
+ );
+ }
+ return <EnvironmentSandboxSettingsPanel key={environmentId} environmentId={environmentId} />;
+}
+
+function EnvironmentSandboxSettingsPanel({
+ environmentId,
+}: {
+ readonly environmentId: EnvironmentId;
+}) {
+ const sandbox = useEnvironmentSettings(environmentId, (settings) => settings.sandbox);
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
+ const [editingProvider, setEditingProvider] = useState<CloudSandboxProvider | null>(null);
+ const [draft, setDraft] = useState<Readonly<Record<string, string>>>({});
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const persist = async (next: SandboxSettings) => {
+ setSaving(true);
+ setError(null);
+ const result = await updateSettings({ environmentId, input: { patch: { sandbox: next } } });
+ setSaving(false);
+ if (result._tag === "Failure") {
+ setError(errorMessage(result));
+ return false;
+ }
+ return true;
+ };
+
+ const openConnection = (provider: CloudSandboxProvider) => {
+ setEditingProvider(provider);
+ setDraft(sandboxConnectionDraft(sandbox, provider));
+ setError(null);
+ };
+
+ const closeConnection = () => {
+ if (saving) return;
+ setEditingProvider(null);
+ setDraft({});
+ setError(null);
+ };
+
+ const saveConnection = async () => {
+ if (editingProvider === null) return;
+ const next = saveSandboxProviderConnection({
+ settings: sandbox,
+ provider: editingProvider,
+ draft,
+ });
+ if (await persist(next)) closeConnection();
+ };
+
+ const editingDefinition = editingProvider ? sandboxProviderDefinition(editingProvider) : null;
+ const canSave =
+ editingProvider !== null &&
+ canSaveSandboxProviderConnection({ settings: sandbox, provider: editingProvider, draft });
+
+ return (
+ <>
+ <SettingsPageContainer>
+ <SettingsSection {...searchableSetting("sandbox")}>
+ <SettingsRow
+ {...searchableSetting("default-sandbox")}
+ description="Bots without an override use this sandbox."
+ control={
+ <Select
+ value={sandbox.defaultProvider}
+ onValueChange={(value) => {
+ if (value === null) return;
+ const provider = value as SandboxProvider;
+ if (!selectableSandboxProviders(sandbox).includes(provider)) return;
+ void persist({ ...sandbox, defaultProvider: provider });
+ }}
+ >
+ <SelectTrigger className="w-44" aria-label="Default sandbox">
+ <SelectValue>{SANDBOX_PROVIDER_LABELS[sandbox.defaultProvider]}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ {selectableSandboxProviders(sandbox).map((provider) => (
+ <SelectItem key={provider} value={provider}>
+ {SANDBOX_PROVIDER_LABELS[provider]}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ }
+ />
+ <SettingsRow
+ {...searchableSetting("sandbox-auto-idle")}
+ description="Akeru pauses remote sandboxes when bots are idle."
+ control={<Switch checked disabled aria-label="Auto-idle" />}
+ />
+ </SettingsSection>
+
+ <SettingsSection title="Providers">
+ <SettingsRow
+ title="Local"
+ description="This computer. No credential required."
+ control={<Badge variant="success">Connected</Badge>}
+ />
+ {SANDBOX_PROVIDER_DEFINITIONS.map((definition) => {
+ const connected = isSandboxProviderConnected(sandbox, definition.id);
+ return (
+ <SettingsRow
+ key={definition.id}
+ title={definition.label}
+ description={definition.description}
+ control={
+ <div className="flex items-center gap-2">
+ <Badge variant={connected ? "success" : "secondary"}>
+ {connected ? "Connected" : "Not connected"}
+ </Badge>
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => openConnection(definition.id)}
+ >
+ {connected ? "Reconnect" : "Connect"}
+ </Button>
+ {connected ? (
+ <Button
+ size="xs"
+ variant="ghost-muted"
+ disabled={saving}
+ onClick={() =>
+ void persist(disconnectSandboxProvider(sandbox, definition.id))
+ }
+ >
+ Disconnect
+ </Button>
+ ) : null}
+ </div>
+ }
+ />
+ );
+ })}
+ </SettingsSection>
+ </SettingsPageContainer>
+
+ <Dialog open={editingProvider !== null} onOpenChange={(open) => !open && closeConnection()}>
+ <DialogPopup>
+ <DialogHeader>
+ <DialogTitle>
+ {editingDefinition ? `Connect ${editingDefinition.label}` : "Connect sandbox"}
+ </DialogTitle>
+ <DialogDescription>
+ The server stores these credentials in its secret store.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-2">
+ {editingDefinition?.fields.map((field) => (
+ <label key={field.name} className="grid gap-1.5 text-sm font-medium">
+ {field.label}
+ <Input
+ type={field.secret ? "password" : undefined}
+ autoComplete="off"
+ value={draft[field.name] ?? ""}
+ placeholder={field.secret ? "Leave blank to keep the saved value" : undefined}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, [field.name]: event.currentTarget.value }))
+ }
+ />
+ </label>
+ ))}
+ {error ? (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" disabled={saving} onClick={closeConnection}>
+ Cancel
+ </Button>
+ <Button disabled={!canSave || saving} onClick={() => void saveConnection()}>
+ {saving ? "Connecting" : "Connect"}
+ </Button>
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
+ </>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsx
index 3cc9be711..b447ccf08 100644
--- a/apps/web/src/components/settings/SettingsDialog.tsx
+++ b/apps/web/src/components/settings/SettingsDialog.tsx
@@ -2,6 +2,7 @@ import {
AlertCircleIcon,
BotIcon,
CallIcon,
+ HardDriveIcon,
KeyboardIcon,
Link02Icon,
PaintBrush01Icon,
@@ -32,6 +33,9 @@ const ProvidersPanel = lazy(async () => ({
const VoiceSettingsPanel = lazy(async () => ({
default: (await import("./VoiceSettings")).VoiceSettingsPanel,
}));
+const SandboxSettingsPanel = lazy(async () => ({
+ default: (await import("./SandboxSettingsPanel")).SandboxSettingsPanel,
+}));
const PrivacySettingsPanel = lazy(async () => ({
default: (await import("./PrivacySettings")).PrivacySettingsPanel,
}));
@@ -53,6 +57,7 @@ const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {
inbox: InboxPanel,
appearance: AppearanceSettingsPanel,
providers: ProvidersPanel,
+ sandbox: SandboxSettingsPanel,
voice: VoiceSettingsPanel,
privacy: PrivacySettingsPanel,
connections: ConnectionsSettings,
@@ -70,6 +75,7 @@ const NAV_ITEMS: ReadonlyArray<{
{ section: "general", label: "General", icon: Settings02Icon },
{ section: "appearance", label: "Appearance", icon: PaintBrush01Icon },
{ section: "providers", label: "Providers", icon: BotIcon },
+ { section: "sandbox", label: "Sandbox", icon: HardDriveIcon },
{ section: "voice", label: "Voice", icon: CallIcon },
{ section: "privacy", label: "Privacy", icon: SecurityCheckIcon },
{ section: "inbox", label: "Errors", icon: AlertCircleIcon },
diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts
index 5b0f083ea..6fb7c1c5b 100644
--- a/apps/web/src/components/settings/settingsSearch.test.ts
+++ b/apps/web/src/components/settings/settingsSearch.test.ts
@@ -86,6 +86,13 @@ describe("searchSettings", () => {
});
});
+ it("routes sandbox provider settings to Sandbox settings", () => {
+ expect(searchSettings("default sandbox")[0]).toMatchObject({
+ id: "default-sandbox",
+ to: "/settings/sandbox",
+ });
+ });
+
it("routes analytics to Privacy settings", () => {
expect(searchSettings("analytics")[0]).toMatchObject({
id: "anonymous-analytics",
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 751db10e1..c3d61fa11 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -5,6 +5,7 @@ export type SettingsPath =
| "/settings/appearance"
| "/settings/keybindings"
| "/settings/providers"
+ | "/settings/sandbox"
| "/settings/voice"
| "/settings/privacy"
| "/settings/integrations"
@@ -31,6 +32,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/appearance": "Appearance",
"/settings/keybindings": "Keybindings",
"/settings/providers": "Providers",
+ "/settings/sandbox": "Sandbox",
"/settings/voice": "Voice",
"/settings/privacy": "Privacy",
"/settings/integrations": "Integrations",
@@ -272,6 +274,21 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Providers",
to: "/settings/providers",
},
+ {
+ id: "sandbox",
+ title: "Sandbox",
+ to: "/settings/sandbox",
+ },
+ {
+ id: "default-sandbox",
+ title: "Default sandbox",
+ to: "/settings/sandbox",
+ },
+ {
+ id: "sandbox-auto-idle",
+ title: "Sandbox auto-idle",
+ to: "/settings/sandbox",
+ },
{
id: "agent-browser-access",
title: "Agent browser access",
diff --git a/apps/web/src/settingsDialogStore.test.ts b/apps/web/src/settingsDialogStore.test.ts
index 60848e980..949ef21f6 100644
--- a/apps/web/src/settingsDialogStore.test.ts
+++ b/apps/web/src/settingsDialogStore.test.ts
@@ -71,6 +71,7 @@ describe("legacy settings deep links", () => {
expect(settingsSectionFromPathname("/settings/connections")).toBe("connections");
expect(settingsSectionFromPathname("/settings/inbox")).toBe("inbox");
expect(settingsSectionFromPathname("/settings/voice")).toBe("voice");
+ expect(settingsSectionFromPathname("/settings/sandbox")).toBe("sandbox");
expect(settingsSectionFromPathname("/settings/source-control")).toBe("source-control");
});
diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.ts
index 1c75672b7..1f72877e7 100644
--- a/apps/web/src/settingsDialogStore.ts
+++ b/apps/web/src/settingsDialogStore.ts
@@ -17,6 +17,7 @@ export const SETTINGS_SECTIONS = [
"inbox",
"appearance",
"providers",
+ "sandbox",
"voice",
"privacy",
"connections",
diff --git a/docs/README.md b/docs/README.md
index 92742d5f3..55150eef7 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,6 +4,7 @@
- [Install and first run](./user/install.md)
- [Permission modes](./user/permission-modes.md)
+- [Configure sandboxes](./user/sandboxes.md)
- [Keyboard shortcuts](./user/keybindings.md)
- [Organizing threads](./user/thread-sidebar.md)
- [Sending product feedback](./user/product-feedback.md)
diff --git a/docs/user/bots.md b/docs/user/bots.md
index 493d84d81..f60b7ddfd 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -15,7 +15,7 @@ Akeru Bot stores the profile in the connected environment. Other clients connect
Each settled bot reply shows its engine, step tokens, and estimated USD cost when the provider reports enough usage data.
-Settings controls whether bots share their workspace and browser. **Separate** is the default and gives each bot its own workspace identity and browser profile. **Shared** lets bots share files and cookies. Bots can use Local, E2B, Daytona, Vercel Sandbox, or Upstash Box workspaces. Remote workspaces use the provider credentials available to the environment and fail if those credentials are missing.
+Settings controls whether bots share their workspace and browser. **Separate** is the default and gives each bot its own workspace identity and browser profile. **Shared** lets bots share files and cookies. Bots can use Local, E2B, Daytona, Vercel Sandbox, or Upstash Box workspaces. Connect remote providers in **Settings > Sandbox**. Remote workspaces use the provider credentials available to the environment and fail if those credentials are missing. A bot's explicit sandbox overrides the default.
Local bots ask before file changes and shell commands by default. Select **Settings > General > Local execution > Full access** to skip those local prompts. Actions that send, pay, delete, change production, or use secrets still ask. Bots that run in a cloud sandbox do not show the local computer prompt.
diff --git a/docs/user/sandboxes.md b/docs/user/sandboxes.md
new file mode 100644
index 000000000..3232bc228
--- /dev/null
+++ b/docs/user/sandboxes.md
@@ -0,0 +1,11 @@
+# Configure sandboxes
+
+Open **Settings > Sandbox** to connect a remote sandbox provider. Akeru Bot supports E2B, Daytona, Vercel Sandbox, and Upstash Box. Local needs no credential and is always available.
+
+Select **Connect** and enter the provider credentials. The server stores secret values outside `settings.json`. A client receives only a redacted marker for each saved secret.
+
+Only connected providers appear in the default sandbox selector. Disconnecting the default provider changes the default to Local. Akeru pauses remote sandboxes when bots are idle and reconnects to the saved provider workspace when work resumes.
+
+The default applies when a bot has no sandbox override. A bot with an explicit sandbox keeps that choice. Connect that provider before you start the bot.
+
+Changing a provider credential replaces active sessions that use that connection. This prevents an existing session from continuing with an old account credential.
diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts
index 6b20b81aa..5a244965f 100644
--- a/packages/contracts/src/provider.ts
+++ b/packages/contracts/src/provider.ts
@@ -69,6 +69,7 @@ export const ProviderSessionStartInput = Schema.Struct({
botId: Schema.optional(BotId),
botName: Schema.optional(TrimmedNonEmptyString),
botSandbox: Schema.optional(Schema.NullOr(BotSandbox)),
+ botSandboxEnvironment: Schema.optional(Schema.Record(Schema.String, Schema.String)),
botSandboxBrowserSharing: Schema.optional(BotSandboxBrowserSharing),
mcpServers: Schema.optional(Schema.Array(McpServer)),
runtimeMode: RuntimeMode,
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index ed1593a84..fa5f62c74 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -267,6 +267,47 @@ describe("ServerSettings bot sandbox and browser sharing", () => {
});
});
+describe("ServerSettings sandbox providers", () => {
+ it("defaults to local with cloud providers disconnected", () => {
+ expect(decodeServerSettings({}).sandbox).toEqual({
+ defaultProvider: "local",
+ autoIdle: true,
+ providers: {
+ e2b: { environment: [] },
+ daytona: { environment: [] },
+ vercel: { environment: [] },
+ upstash: { environment: [] },
+ },
+ });
+ });
+
+ it("accepts a provider credential patch", () => {
+ expect(
+ decodeServerSettingsPatch({
+ sandbox: {
+ defaultProvider: "e2b",
+ providers: {
+ e2b: {
+ environment: [{ name: "E2B_API_KEY", value: "secret", sensitive: true }],
+ },
+ },
+ },
+ }).sandbox,
+ ).toEqual({
+ defaultProvider: "e2b",
+ providers: {
+ e2b: {
+ environment: [{ name: "E2B_API_KEY", value: "secret", sensitive: true }],
+ },
+ },
+ });
+ });
+
+ it("keeps automatic idle cleanup enabled", () => {
+ expect(() => decodeServerSettingsPatch({ sandbox: { autoIdle: false } })).toThrow();
+ });
+});
+
describe("ServerSettings local execution", () => {
it("asks first by default and accepts full access only as an opt-in", () => {
expect(decodeServerSettings({}).localExecutionMode).toBe("approval-required");
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index d3bb4c44c..8897f0cda 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -10,6 +10,7 @@ import {
ProviderOptionSelections,
} from "./model.ts";
import {
+ BotSandbox,
BotSandboxBrowserSharing,
DEFAULT_BOT_SANDBOX_BROWSER_SHARING,
DEFAULT_LOCAL_EXECUTION_MODE,
@@ -27,6 +28,7 @@ import {
import { VoiceProvider, ChatGptRealtimeVoice, VoiceSettings } from "./voiceCall.ts";
import {
ProviderInstanceConfig,
+ ProviderInstanceEnvironmentVariable,
ProviderInstanceId,
type ProviderDriverKind,
} from "./providerInstance.ts";
@@ -663,6 +665,48 @@ export const BackgroundActivitySettings = Schema.Struct({
}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
+export const SandboxProvider = BotSandbox;
+export type SandboxProvider = BotSandbox;
+export type CloudSandboxProvider = Exclude<SandboxProvider, "local">;
+
+export const CLOUD_SANDBOX_PROVIDERS = ["e2b", "daytona", "vercel", "upstash"] as const;
+export const SANDBOX_PROVIDER_CREDENTIALS = {
+ e2b: [{ name: "E2B_API_KEY", sensitive: true }],
+ daytona: [{ name: "DAYTONA_API_KEY", sensitive: true }],
+ vercel: [
+ { name: "VERCEL_TOKEN", sensitive: true },
+ { name: "VERCEL_TEAM_ID", sensitive: false },
+ { name: "VERCEL_PROJECT_ID", sensitive: false },
+ ],
+ upstash: [{ name: "UPSTASH_BOX_API_KEY", sensitive: true }],
+} as const satisfies Readonly<
+ Record<
+ CloudSandboxProvider,
+ ReadonlyArray<{ readonly name: string; readonly sensitive: boolean }>
+ >
+>;
+
+export const SandboxProviderConnection = Schema.Struct({
+ environment: Schema.Array(ProviderInstanceEnvironmentVariable).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
+}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
+export type SandboxProviderConnection = typeof SandboxProviderConnection.Type;
+
+export const SandboxSettings = Schema.Struct({
+ defaultProvider: SandboxProvider.pipe(
+ Schema.withDecodingDefault(Effect.succeed("local" as const)),
+ ),
+ autoIdle: Schema.Literal(true).pipe(Schema.withDecodingDefault(Effect.succeed(true as const))),
+ providers: Schema.Struct({
+ e2b: SandboxProviderConnection,
+ daytona: SandboxProviderConnection,
+ vercel: SandboxProviderConnection,
+ upstash: SandboxProviderConnection,
+ }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
+}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
+export type SandboxSettings = typeof SandboxSettings.Type;
+
export const ServerSettings = Schema.Struct({
// Legacy token-by-token assistant output. Deliberately a fresh key (was
// `enableAssistantStreaming`): decoding drops the old key, so everyone,
@@ -761,6 +805,7 @@ export const ServerSettings = Schema.Struct({
providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
+ sandbox: SandboxSettings,
observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
@@ -820,7 +865,9 @@ export const ServerSettingsOperation = Schema.Literals([
"remove-secret",
"remove-stale-secret",
"remove-analytics-state",
+ "rollback-secret",
"write-secret",
+ "validate-sandbox",
"write-file",
"prepare-directory",
]);
@@ -911,6 +958,23 @@ const OpenCodeSettingsPatch = Schema.Struct({
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
+const SandboxProviderConnectionPatch = Schema.Struct({
+ environment: Schema.optionalKey(Schema.Array(ProviderInstanceEnvironmentVariable)),
+});
+
+const SandboxSettingsPatch = Schema.Struct({
+ defaultProvider: Schema.optionalKey(SandboxProvider),
+ autoIdle: Schema.optionalKey(Schema.Literal(true)),
+ providers: Schema.optionalKey(
+ Schema.Struct({
+ e2b: Schema.optionalKey(SandboxProviderConnectionPatch),
+ daytona: Schema.optionalKey(SandboxProviderConnectionPatch),
+ vercel: Schema.optionalKey(SandboxProviderConnectionPatch),
+ upstash: Schema.optionalKey(SandboxProviderConnectionPatch),
+ }),
+ ),
+});
+
export const ServerSettingsPatch = Schema.Struct({
// Server settings
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
@@ -951,6 +1015,7 @@ export const ServerSettingsPatch = Schema.Struct({
}),
),
sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
+ sandbox: Schema.optionalKey(SandboxSettingsPatch),
observability: Schema.optionalKey(
Schema.Struct({
otlpTracesUrl: Schema.optionalKey(TrimmedString),