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(sandbox): add Ascii Box workspace provider (#302)

usehoplite[bot]14b56b3d9ab0
diff --git a/.changeset/wacky-seas-talk.md b/.changeset/wacky-seas-talk.md
new file mode 100644
index 000000000..9c3b87b01
--- /dev/null
+++ b/.changeset/wacky-seas-talk.md
@@ -0,0 +1,5 @@
+---
+"akeru-bot": minor
+---
+
+Add Ascii Box sandbox support with persistent VMs, saved workspace reattachment, native snapshot-backed stop and resume, and protected browser access. Configure its API key in Sandbox settings.
diff --git a/apps/server/package.json b/apps/server/package.json
index 7cf98e201..03d164d1d 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -26,6 +26,7 @@
"@ai-sdk/openai": "3.0.101",
"@ai-sdk/openai-compatible": "2.0.72",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
+ "@asciidev/box-sdk": "0.0.37",
"@chat-adapter/discord": "4.39.0",
"@chat-adapter/slack": "4.39.0",
"@chat-adapter/state-memory": "4.39.0",
diff --git a/apps/server/src/provider/AkeruSessionResources.test.ts b/apps/server/src/provider/AkeruSessionResources.test.ts
index e379e50c8..c24f6f80d 100644
--- a/apps/server/src/provider/AkeruSessionResources.test.ts
+++ b/apps/server/src/provider/AkeruSessionResources.test.ts
@@ -503,6 +503,41 @@ describe("AkeruSessionResources", () => {
expect(destroy).not.toHaveBeenCalled();
});
+ it("preserves the Ascii workspace when MCP initialization fails", async () => {
+ const remote: AkeruBotWorkspace = { ...localBotWorkspace(workspace()), provider: "ascii" };
+ const destroy = vi.spyOn(remote, "destroy");
+ const sleep = vi.spyOn(remote, "sleep");
+ const manager = mcpManager({ connected: true, toolCount: 1 });
+ manager.init.mockRejectedValueOnce(new Error("connector failed"));
+ const resources = new AkeruSessionResources({
+ stateDir: stateDir(),
+ makeRemoteWorkspace: async () => remote,
+ makeMcpManager: () => manager as never,
+ toMcpServerConfigs: () => ({}),
+ });
+
+ await expect(
+ resources.acquire({
+ ...remoteInput,
+ botSandbox: "ascii",
+ threadId: "ascii-init-failure",
+ mcpServers: [exaServer],
+ }),
+ ).rejects.toThrow("connector failed");
+ expect(destroy).not.toHaveBeenCalled();
+ expect(sleep).toHaveBeenCalledOnce();
+ expect(manager.disconnect).toHaveBeenCalledOnce();
+ const recovered = await resources.acquire({
+ ...remoteInput,
+ botSandbox: "ascii",
+ threadId: "ascii-init-failure",
+ mcpServers: [exaServer],
+ });
+ expect(recovered.botWorkspace).toBe(remote.workspace);
+ await resources.shutdown();
+ expect(destroy).not.toHaveBeenCalled();
+ });
+
it("coalesces concurrent acquisition for the same thread", async () => {
const remote = workspace();
const stop = vi.spyOn(remote, "stop");
diff --git a/apps/server/src/provider/AkeruSessionResources.ts b/apps/server/src/provider/AkeruSessionResources.ts
index b8292270d..61990f6b0 100644
--- a/apps/server/src/provider/AkeruSessionResources.ts
+++ b/apps/server/src/provider/AkeruSessionResources.ts
@@ -381,7 +381,10 @@ export class AkeruSessionResources {
};
} catch (cause) {
await this.releaseOnce(key, {
- destroy: input.botSandbox !== "railway" && input.botSandbox !== "tenki",
+ destroy:
+ input.botSandbox !== "railway" &&
+ input.botSandbox !== "tenki" &&
+ input.botSandbox !== "ascii",
}).catch(() => undefined);
throw cause;
}
diff --git a/apps/server/src/provider/botWorkspace.test.ts b/apps/server/src/provider/botWorkspace.test.ts
index 0f6091865..02223f544 100644
--- a/apps/server/src/provider/botWorkspace.test.ts
+++ b/apps/server/src/provider/botWorkspace.test.ts
@@ -4,9 +4,11 @@ import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { LocalFilesystem, LocalSandbox, Workspace } from "@mastra/core/workspace";
+import { DateTime } from "effect";
import { assert, describe, expect, it, vi } from "vite-plus/test";
import {
+ ascii,
createBotWorkspace,
createRemoteBotWorkspace,
daytona,
@@ -21,6 +23,467 @@ import {
vercelWorkspaceState,
} from "./botWorkspace.ts";
+describe("Ascii Box", () => {
+ const deleted = {
+ ok: true,
+ type: "box.deleting",
+ operation: {
+ id: "deletion",
+ kind: "box",
+ targetId: "ascii-id",
+ reason: "explicit",
+ status: "completed",
+ attemptCount: 0,
+ requestedAt: DateTime.toDate(DateTime.makeUnsafe(0)),
+ completedAt: null,
+ },
+ } satisfies import("@asciidev/box-sdk").DeletionOperationResponse;
+ async function setup() {
+ const { BoxApi, Configuration } = await import("@asciidev/box-sdk");
+ const client = new BoxApi(new Configuration({ accessToken: "test-key" }));
+ const get = vi.spyOn(client, "get").mockResolvedValue({
+ type: "box.info",
+ box: {
+ id: "ascii-id",
+ name: "test",
+ state: "idle",
+ desktopAvailable: false,
+ snapshotAvailable: true,
+ },
+ ok: true,
+ });
+ return { client, get, session: ascii(client, "ascii-id") };
+ }
+
+ it("waits for pending VM deletion to complete", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "performance"] });
+ try {
+ const { client, session } = await setup();
+ const pending = {
+ ...deleted,
+ operation: { ...deleted.operation, status: "pending" as const },
+ };
+ vi.spyOn(client, "deleteBox").mockResolvedValue(pending);
+ const poll = vi
+ .spyOn(client, "getDeletionOperation")
+ .mockResolvedValueOnce(pending)
+ .mockResolvedValue(deleted);
+ let complete = false;
+ const operation = session.destroy().then(() => {
+ complete = true;
+ });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(complete).toBe(false);
+ await vi.advanceTimersByTimeAsync(2_000);
+ await operation;
+ expect(poll).toHaveBeenCalledWith({ operationId: "deletion" });
+ expect(complete).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("bounds pending deletion waits", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "performance"] });
+ try {
+ const { client, session } = await setup();
+ const pending = {
+ ...deleted,
+ operation: { ...deleted.operation, status: "pending" as const },
+ };
+ vi.spyOn(client, "deleteBox").mockResolvedValue(pending);
+ vi.spyOn(client, "getDeletionOperation").mockResolvedValue(pending);
+ const failure = expect(session.destroy()).rejects.toThrow("deletion timed out");
+ await vi.advanceTimersByTimeAsync(300_000);
+ await failure;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops with a native snapshot, resumes, and deletes with confirmation", async () => {
+ const { client, get, session } = await setup();
+ const stop = vi
+ .spyOn(client, "stop")
+ .mockResolvedValue({ ok: true, type: "box.stopped", id: "ascii-id", status: "archived" });
+ const resume = vi
+ .spyOn(client, "resume")
+ .mockResolvedValue({ ok: true, type: "box.resumed", id: "ascii-id", status: "ready" });
+ const remove = vi.spyOn(client, "deleteBox").mockResolvedValue(deleted);
+ const current = await client.get({ boxId: "ascii-id" });
+ get.mockResolvedValueOnce({ ...current, box: { ...current.box, state: "archived" } });
+ await session.sleep();
+ expect(stop).toHaveBeenCalledWith({ boxId: "ascii-id" });
+ get.mockResolvedValueOnce({ ...current, box: { ...current.box, state: "archived" } });
+ await session.wake();
+ expect(resume).toHaveBeenCalledWith({ boxId: "ascii-id", resumeRequest: { ttlSeconds: null } });
+ expect(await session.inspect()).toBe("running");
+ await session.destroy();
+ expect(remove).toHaveBeenCalledWith({ boxId: "ascii-id", xAsciiConfirmDelete: "ascii-id" });
+ });
+
+ it.each(["sleep", "wake"] as const)(
+ "waits for native snapshot completion during %s",
+ async (action) => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "performance"] });
+ try {
+ const { client, get, session } = await setup();
+ const current = await client.get({ boxId: "ascii-id" });
+ const archiving = { ...current, box: { ...current.box, state: "archiving" as const } };
+ const archived = { ...current, box: { ...current.box, state: "archived" as const } };
+ const stop = vi.spyOn(client, "stop").mockResolvedValue({
+ ok: true,
+ type: "box.stopped",
+ id: "ascii-id",
+ status: "archiving",
+ });
+ const resume = vi
+ .spyOn(client, "resume")
+ .mockResolvedValue({ ok: true, type: "box.resumed", id: "ascii-id", status: "ready" });
+ if (action === "wake") get.mockResolvedValueOnce(archiving);
+ get.mockResolvedValueOnce(archiving).mockResolvedValueOnce(archived);
+ let completed = false;
+ const operation = session[action]().then(() => {
+ completed = true;
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(completed).toBe(false);
+ expect(resume).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2_000);
+ await operation;
+ if (action === "wake")
+ expect(resume).toHaveBeenCalledWith({
+ boxId: "ascii-id",
+ resumeRequest: { ttlSeconds: null },
+ });
+ else expect(stop).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it("surfaces snapshot errors without force-stopping or deleting the VM", async () => {
+ const { client, get, session } = await setup();
+ const current = await client.get({ boxId: "ascii-id" });
+ get.mockResolvedValue({ ...current, box: { ...current.box, state: "error" } });
+ const stop = vi
+ .spyOn(client, "stop")
+ .mockResolvedValue({ ok: true, type: "box.stopped", id: "ascii-id", status: "archiving" });
+ const remove = vi.spyOn(client, "deleteBox");
+ await expect(session.sleep()).rejects.toThrow("snapshot archival failed");
+ expect(stop).toHaveBeenCalledWith({ boxId: "ascii-id" });
+ expect(remove).not.toHaveBeenCalled();
+ });
+
+ it("bounds snapshot waits without deleting the VM", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "performance"] });
+ try {
+ const { client, get, session } = await setup();
+ const current = await client.get({ boxId: "ascii-id" });
+ get.mockResolvedValue({ ...current, box: { ...current.box, state: "archiving" } });
+ const resume = vi.spyOn(client, "resume");
+ const remove = vi.spyOn(client, "deleteBox");
+ const failure = expect(session.wake()).rejects.toThrow("snapshot archival timed out");
+ await vi.advanceTimersByTimeAsync(300_000);
+ await failure;
+ expect(resume).not.toHaveBeenCalled();
+ expect(remove).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each([
+ "init",
+ "provisioning",
+ "provisioned",
+ "cloning",
+ "archiving",
+ "archived",
+ "error",
+ ] as const)("does not report %s VMs as running", async (state) => {
+ const { client, get, session } = await setup();
+ const current = await client.get({ boxId: "ascii-id" });
+ get.mockResolvedValue({ ...current, box: { ...current.box, state } });
+ expect(await session.inspect()).toBe(state === "error" ? "missing" : "sleeping");
+ });
+
+ it("distinguishes missing VMs from credential or transport errors", async () => {
+ const { ResponseError } = await import("@asciidev/box-sdk");
+ const { get, session } = await setup();
+ get.mockRejectedValue(new ResponseError(new Response(null, { status: 404 })));
+ expect(await session.inspect()).toBe("missing");
+ get.mockRejectedValue(new Error("unauthorized"));
+ await expect(session.inspect()).rejects.toThrow("unauthorized");
+ });
+
+ it("quotes commands, absolute working directories and environment values", async () => {
+ const { client, session } = await setup();
+ const command = vi.spyOn(client, "command").mockResolvedValue({
+ ok: true,
+ type: "command.finished",
+ success: false,
+ exitCode: 7,
+ stdout: "out",
+ stderr: "err",
+ timedOut: false,
+ });
+ expect(
+ await session.run("printf", ["a'b"], {
+ cwd: "/workspace/my files",
+ env: { VALUE: "x; echo unsafe" },
+ timeout: 1501,
+ }),
+ ).toEqual({ exitCode: 7, stdout: "out", stderr: "err" });
+ expect(command).toHaveBeenCalledWith({
+ boxId: "ascii-id",
+ commandRequest: {
+ command: "cd '/workspace/my files' && env 'VALUE=x; echo unsafe' 'printf' 'a'\\''b'",
+ timeoutSeconds: 2,
+ },
+ });
+ command.mockResolvedValue({
+ ok: true,
+ type: "command.finished",
+ success: false,
+ exitCode: null,
+ stdout: "",
+ stderr: "",
+ timedOut: true,
+ });
+ expect((await session.run("sleep", ["2"])).exitCode).toBe(124);
+ expect(command).toHaveBeenLastCalledWith({
+ boxId: "ascii-id",
+ commandRequest: { command: "'sleep' '2'", timeoutSeconds: 600 },
+ });
+ await session.run("sleep", ["2"], { timeout: 600_000 });
+ expect(command).toHaveBeenLastCalledWith({
+ boxId: "ascii-id",
+ commandRequest: { command: "'sleep' '2'", timeoutSeconds: 600 },
+ });
+ });
+
+ it.each([900_000, 0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
+ "rejects unsupported command timeout %s before executing",
+ async (timeout) => {
+ const { client, session } = await setup();
+ const command = vi.spyOn(client, "command");
+
+ await expect(session.run("sleep", ["900"], { timeout })).rejects.toThrow(
+ "Ascii Box command timeout must be greater than 0 and at most 600000 ms.",
+ );
+ expect(command).not.toHaveBeenCalled();
+ },
+ );
+
+ it("bounds readiness polling without deleting the VM", async () => {
+ const { client, get, session } = await setup();
+ const current = await client.get({ boxId: "ascii-id" });
+ get.mockResolvedValue({ ...current, box: { ...current.box, state: "provisioning" } });
+ const deleteBox = vi.spyOn(client, "deleteBox");
+ const clock = vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValue(300_001);
+ try {
+ await expect(session.wake()).rejects.toThrow("Timed out waiting for Box state");
+ expect(deleteBox).not.toHaveBeenCalled();
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ it("protects browser control without forwarding the API credential", async () => {
+ const { client, session } = await setup();
+ const hostPort = vi.spyOn(client, "hostPort").mockResolvedValue({
+ ok: true,
+ type: "host_port",
+ url: "https://preview.example/?_token=browser-token",
+ isProtected: true,
+ });
+ expect(await session.browserEndpoint(9223)).toEqual({
+ url: "https://preview.example/?_token=browser-token",
+ requestHeaders: {},
+ });
+ expect(hostPort).toHaveBeenCalledWith({
+ boxId: "ascii-id",
+ hostPortRequest: { port: 9223, _public: false },
+ });
+ hostPort.mockResolvedValue({ ok: true, type: "host_port" });
+ await expect(session.browserEndpoint(9223)).rejects.toThrow("preview URL");
+ hostPort.mockResolvedValue({
+ ok: true,
+ type: "host_port",
+ url: "https://preview.example",
+ isProtected: false,
+ });
+ await expect(session.browserEndpoint(9223)).rejects.toThrow("protected browser endpoint");
+ hostPort.mockResolvedValue({
+ ok: true,
+ type: "host_port",
+ url: "https://preview.example",
+ isProtected: true,
+ });
+ await expect(session.browserEndpoint(9223)).rejects.toThrow("protected browser endpoint");
+ });
+
+ it("creates once with the configured credential and reattaches by saved VM identity", async () => {
+ const { BoxApi } = await import("@asciidev/box-sdk");
+ const root = await NodeFS.promises.mkdtemp(NodePath.join(NodeOS.tmpdir(), "akeru-ascii-"));
+ const box = {
+ id: "ascii-id",
+ name: "test",
+ state: "idle" as const,
+ desktopAvailable: false,
+ snapshotAvailable: true,
+ };
+ const create = vi.spyOn(BoxApi.prototype, "create").mockResolvedValue({
+ ok: true,
+ type: "box.created",
+ status: "provisioning",
+ ttlSeconds: null,
+ box,
+ });
+ const get = vi
+ .spyOn(BoxApi.prototype, "get")
+ .mockResolvedValue({ ok: true, type: "box.info", box });
+ const remove = vi.spyOn(BoxApi.prototype, "deleteBox").mockResolvedValue(deleted);
+ const command = vi.spyOn(BoxApi.prototype, "command").mockResolvedValue({
+ ok: true,
+ type: "command.finished",
+ success: true,
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ timedOut: false,
+ });
+ try {
+ const input = {
+ threadId: "thread",
+ sandbox: "ascii" as const,
+ workspaceId: "workspace",
+ identityFile: NodePath.join(root, "identity.json"),
+ environment: { BOX_API_KEY: "configured-key" },
+ };
+ const first = await createRemoteBotWorkspace(input);
+ expect(create).toHaveBeenCalledWith({ createBoxRequest: { ttlSeconds: null, noEnv: true } });
+ const client = create.mock.contexts[0] as import("@asciidev/box-sdk").BoxApi;
+ expect((await client.createRequestOpts({})).headers.Authorization).toBe(
+ "Bearer configured-key",
+ );
+ expect(first.providerId).toBe("ascii-id");
+ get.mockRejectedValueOnce(new Error("VM unavailable"));
+ await expect(createRemoteBotWorkspace(input)).rejects.toThrow("missing or unavailable");
+ expect(create).toHaveBeenCalledOnce();
+ const second = await createRemoteBotWorkspace(input);
+ expect(create).toHaveBeenCalledOnce();
+ expect(get).toHaveBeenCalledWith({ boxId: "ascii-id" });
+ await second.wake();
+ remove.mockResolvedValueOnce({
+ ...deleted,
+ operation: { ...deleted.operation, status: "blocked" },
+ });
+ await expect(second.destroy()).rejects.toThrow("deletion is blocked");
+ expect(JSON.parse(await NodeFS.promises.readFile(input.identityFile, "utf8"))).toEqual({
+ provider: "ascii",
+ providerId: "ascii-id",
+ });
+ await second.destroy();
+ expect(remove).toHaveBeenCalledTimes(2);
+ await expect(NodeFS.promises.stat(input.identityFile)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ } finally {
+ create.mockRestore();
+ get.mockRestore();
+ remove.mockRestore();
+ command.mockRestore();
+ await NodeFS.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it.each([404, 401, 403, 500])(
+ "reconciles saved VM identity only for a confirmed 404, not %s errors",
+ async (status) => {
+ const { BoxApi, ResponseError } = await import("@asciidev/box-sdk");
+ const root = await NodeFS.promises.mkdtemp(NodePath.join(NodeOS.tmpdir(), "akeru-ascii-"));
+ const identityFile = NodePath.join(root, "identity.json");
+ const previous = { provider: "ascii", providerId: "deleted-id" };
+ const get = vi
+ .spyOn(BoxApi.prototype, "get")
+ .mockRejectedValue(new ResponseError(new Response(null, { status })));
+ const create = vi.spyOn(BoxApi.prototype, "create").mockResolvedValue({
+ ok: true,
+ type: "box.created",
+ status: "provisioning",
+ ttlSeconds: null,
+ box: {
+ id: "replacement-id",
+ name: "test",
+ state: "idle",
+ desktopAvailable: false,
+ snapshotAvailable: false,
+ },
+ });
+ try {
+ await NodeFS.promises.writeFile(identityFile, JSON.stringify(previous));
+ const input = {
+ threadId: "thread",
+ sandbox: "ascii" as const,
+ workspaceId: "workspace",
+ identityFile,
+ environment: { BOX_API_KEY: "configured-key" },
+ };
+ if (status === 404) {
+ create.mockRejectedValueOnce(new Error("creation unavailable"));
+ await expect(createRemoteBotWorkspace(input)).rejects.toThrow("missing or unavailable");
+ expect(JSON.parse(await NodeFS.promises.readFile(identityFile, "utf8"))).toEqual(
+ previous,
+ );
+ const workspace = await createRemoteBotWorkspace(input);
+ expect(workspace.providerId).toBe("replacement-id");
+ expect(JSON.parse(await NodeFS.promises.readFile(identityFile, "utf8"))).toEqual({
+ provider: "ascii",
+ providerId: "replacement-id",
+ });
+ expect(create).toHaveBeenLastCalledWith({
+ createBoxRequest: { ttlSeconds: null, noEnv: true },
+ });
+ } else {
+ await expect(createRemoteBotWorkspace(input)).rejects.toThrow("missing or unavailable");
+ expect(create).not.toHaveBeenCalled();
+ expect(JSON.parse(await NodeFS.promises.readFile(identityFile, "utf8"))).toEqual(
+ previous,
+ );
+ }
+ } finally {
+ get.mockRestore();
+ create.mockRestore();
+ await NodeFS.promises.rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it("rejects a missing credential before creating a VM", async () => {
+ const { BoxApi } = await import("@asciidev/box-sdk");
+ const create = vi.spyOn(BoxApi.prototype, "create");
+ const root = await NodeFS.promises.mkdtemp(NodePath.join(NodeOS.tmpdir(), "akeru-ascii-"));
+ try {
+ await expect(
+ createRemoteBotWorkspace({
+ threadId: "thread",
+ sandbox: "ascii",
+ workspaceId: "workspace",
+ identityFile: NodePath.join(root, "identity.json"),
+ environment: {},
+ }),
+ ).rejects.toThrow("BOX_API_KEY");
+ expect(create).not.toHaveBeenCalled();
+ } finally {
+ create.mockRestore();
+ await NodeFS.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+});
+
function remoteSession(providerId: string): AkeruRemoteSession {
return {
providerId,
@@ -131,7 +594,7 @@ describe("createBotWorkspace", () => {
it("classifies every managed provider", () => {
expect(isRemoteBotSandbox("local")).toBe(false);
- for (const sandbox of ["e2b", "daytona", "vercel", "upstash", "railway"] as const) {
+ for (const sandbox of ["e2b", "daytona", "vercel", "upstash", "ascii", "railway"] as const) {
expect(isRemoteBotSandbox(sandbox)).toBe(true);
}
});
diff --git a/apps/server/src/provider/botWorkspace.ts b/apps/server/src/provider/botWorkspace.ts
index 77c5badb4..d2c535054 100644
--- a/apps/server/src/provider/botWorkspace.ts
+++ b/apps/server/src/provider/botWorkspace.ts
@@ -22,6 +22,7 @@ export const REMOTE_BOT_SANDBOXES = [
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
] as const;
@@ -140,7 +141,7 @@ export async function createRemoteBotWorkspace(
{ cause },
);
}
- if (!persisted) {
+ if (!persisted || persisted.providerId !== session.providerId) {
try {
await writeIdentity(identityFile, {
provider: input.sandbox,
@@ -341,6 +342,14 @@ async function create(
id: string,
environment: Readonly<Record<string, string>> = {},
): Promise<AkeruRemoteSession> {
+ if (provider === "ascii") {
+ const { BoxApi, Configuration } = await import("@asciidev/box-sdk");
+ const client = new BoxApi(
+ new Configuration({ accessToken: credential(environment, "BOX_API_KEY") }),
+ );
+ const { box } = await client.create({ createBoxRequest: { ttlSeconds: null, noEnv: true } });
+ return ascii(client, box.id);
+ }
if (provider === "e2b") {
const { Sandbox } = await import("e2b");
const apiKey = credential(environment, "E2B_API_KEY");
@@ -390,6 +399,21 @@ async function open(
id: string,
environment: Readonly<Record<string, string>> = {},
): Promise<AkeruRemoteSession> {
+ if (provider === "ascii") {
+ const { BoxApi, Configuration, ResponseError } = await import("@asciidev/box-sdk");
+ const client = new BoxApi(
+ new Configuration({ accessToken: credential(environment, "BOX_API_KEY") }),
+ );
+ try {
+ await client.get({ boxId: id });
+ } catch (cause) {
+ if (!(cause instanceof ResponseError) || cause.response.status !== 404) throw cause;
+ // A timed-out deletion can finish later; only confirmed absence permits replacement.
+ const { box } = await client.create({ createBoxRequest: { ttlSeconds: null, noEnv: true } });
+ return ascii(client, box.id);
+ }
+ return ascii(client, id);
+ }
if (provider === "e2b") {
const { Sandbox } = await import("e2b");
const apiKey = credential(environment, "E2B_API_KEY");
@@ -428,6 +452,95 @@ async function open(
return upstash(await Box.get(id, { apiKey: credential(environment, "UPSTASH_BOX_API_KEY") }));
}
+export function ascii(
+ client: import("@asciidev/box-sdk").BoxApi,
+ boxId: string,
+): AkeruRemoteSession {
+ const waitUntilArchived = async () => {
+ const deadline = performance.now() + 300_000;
+ while (true) {
+ const { box } = await client.get({ boxId });
+ if (box.state === "archived") return;
+ if (box.state === "error") throw new Error("Ascii Box snapshot archival failed.");
+ if (performance.now() >= deadline) throw new Error("Ascii Box snapshot archival timed out.");
+ // The SDK lifecycle is promise-based; polling does not own an Effect runtime.
+ // @effect-diagnostics-next-line globalTimers:off
+ await new Promise<void>((resolve) => setTimeout(resolve, 2_000));
+ }
+ };
+ return {
+ providerId: boxId,
+ inspect: async () => {
+ try {
+ const { box } = await client.get({ boxId });
+ if (["ready", "idle", "running"].includes(box.state)) return "running";
+ return box.state === "error" ? "missing" : "sleeping";
+ } catch (cause) {
+ const { ResponseError } = await import("@asciidev/box-sdk");
+ if (cause instanceof ResponseError && cause.response.status === 404) return "missing";
+ throw cause;
+ }
+ },
+ wake: async () => {
+ const { box } = await client.get({ boxId });
+ if (box.state === "archiving") await waitUntilArchived();
+ if (box.state === "archived" || box.state === "archiving")
+ await client.resume({ boxId, resumeRequest: { ttlSeconds: null } });
+ const { waitUntilReady } = await import("@asciidev/box-sdk");
+ await waitUntilReady(client, boxId, { timeoutMs: 300_000 });
+ },
+ // Stop takes a native lifecycle snapshot; never force-stop and discard VM changes.
+ sleep: async () => {
+ await client.stop({ boxId });
+ await waitUntilArchived();
+ },
+ destroy: async () => {
+ let result = await client.deleteBox({ boxId, xAsciiConfirmDelete: boxId });
+ const deadline = performance.now() + 300_000;
+ while (result.operation.status !== "completed") {
+ if (result.operation.status === "blocked")
+ throw new Error("Ascii Box deletion is blocked.");
+ if (performance.now() >= deadline) throw new Error("Ascii Box deletion timed out.");
+ // The SDK lifecycle is promise-based, like the archival wait above.
+ // @effect-diagnostics-next-line globalTimers:off
+ await new Promise<void>((resolve) => setTimeout(resolve, 2_000));
+ result = await client.getDeletionOperation({ operationId: result.operation.id });
+ }
+ },
+ run: async (command, args, options) => {
+ const timeout = options?.timeout ?? 600_000;
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 600_000)
+ throw new Error("Ascii Box command timeout must be greater than 0 and at most 600000 ms.");
+ const env = Object.entries(options?.env ?? {}).map(([key, value]) =>
+ quote(`${key}=${value}`),
+ );
+ const invocation = `${env.length ? `env ${env.join(" ")} ` : ""}${commandLine(command, args)}`;
+ const result = await client.command({
+ boxId,
+ commandRequest: {
+ command: options?.cwd ? `cd ${quote(options.cwd)} && ${invocation}` : invocation,
+ timeoutSeconds: Math.ceil(timeout / 1_000),
+ },
+ });
+ if (result.type !== "command.finished")
+ throw new Error("Ascii Box command did not finish in the foreground.");
+ return {
+ exitCode: result.timedOut ? 124 : (result.exitCode ?? (result.success ? 0 : 1)),
+ stdout: result.stdout,
+ stderr: result.stderr,
+ };
+ },
+ browserEndpoint: async (port) => {
+ const result = await client.hostPort({ boxId, hostPortRequest: { port, _public: false } });
+ if (!result.url || result.success === false)
+ throw new Error("Ascii Box workspace did not return a preview URL.");
+ if (result.isProtected !== true || !new URL(result.url).searchParams.get("_token"))
+ throw new Error("Ascii Box workspace did not return a protected browser endpoint.");
+ return { url: result.url, requestHeaders: {} };
+ },
+ };
+}
+
export function tenki(session: import("@tenkicloud/sandbox").Session): AkeruRemoteSession {
return {
providerId: session.id,
diff --git a/apps/server/src/provider/botWorkspacePool.test.ts b/apps/server/src/provider/botWorkspacePool.test.ts
index c99f0469f..335f099c6 100644
--- a/apps/server/src/provider/botWorkspacePool.test.ts
+++ b/apps/server/src/provider/botWorkspacePool.test.ts
@@ -79,6 +79,258 @@ describe("BotWorkspacePool", () => {
}),
);
+ it("serializes Railway creation across credential-scoped keys with one identity", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ let vmCreated = false;
+ let creates = 0;
+ let activeCreates = 0;
+ let maxActiveCreates = 0;
+ const create = async () => {
+ creates++;
+ activeCreates++;
+ maxActiveCreates = Math.max(maxActiveCreates, activeCreates);
+ if (!vmCreated) {
+ await Promise.resolve();
+ vmCreated = true;
+ }
+ activeCreates--;
+ return remoteWorkspace({ provider: "railway" });
+ };
+
+ const [first, second] = await Promise.all([
+ pool.acquire(key("old"), create),
+ pool.acquire(key("new"), create),
+ ]);
+ expect(creates).toBe(2);
+ expect(maxActiveCreates).toBe(1);
+ expect(vmCreated).toBe(true);
+ await first.release();
+ await second.release();
+ await pool.destroyAll();
+ });
+
+ it("defers Railway destruction until every credential-scoped lease releases", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const destroy = vi.fn(async () => undefined);
+ const create = async () => remoteWorkspace({ provider: "railway", destroy });
+ const oldCredentials = await pool.acquire(key("old"), create);
+ const newCredentials = await pool.acquire(key("new"), create);
+
+ await oldCredentials.release({ destroy: true });
+ expect(destroy).not.toHaveBeenCalled();
+ await newCredentials.release();
+ expect(destroy).toHaveBeenCalledTimes(1);
+ await pool.destroyAll();
+ });
+
+ it("invalidates sleeping credential keys before deleting their shared Railway VM", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const oldDestroy = vi.fn(async () => undefined);
+ const freshDestroy = vi.fn(async () => undefined);
+ const oldLease = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: oldDestroy }),
+ );
+ await oldLease.release();
+
+ const newLease = await pool.acquire(key("new"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: freshDestroy }),
+ );
+ await newLease.release({ destroy: true });
+ expect(oldDestroy).toHaveBeenCalledTimes(1);
+ expect(freshDestroy).not.toHaveBeenCalled();
+
+ const replacementDestroy = vi.fn(async () => undefined);
+ const replacement = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: replacementDestroy }),
+ );
+ expect(replacement.workspace.destroy).not.toBe(oldLease.workspace.destroy);
+ await replacement.release();
+ await pool.destroyAll();
+ });
+
+ it("starts a clean deletion generation after recreating a deleted Railway VM", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const oldDestroy = vi.fn(async () => undefined);
+ const old = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: oldDestroy }),
+ );
+ await old.release();
+ const other = await pool.acquire(key("new"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: oldDestroy }),
+ );
+ await other.release({ destroy: true });
+ expect(oldDestroy).toHaveBeenCalledTimes(1);
+
+ const freshDestroy = vi.fn(async () => undefined);
+ const createFresh = vi.fn(async () =>
+ remoteWorkspace({ provider: "railway", destroy: freshDestroy }),
+ );
+ const recreated = await pool.acquire(key("old"), createFresh);
+ expect(createFresh).toHaveBeenCalledTimes(1);
+ await recreated.release();
+ expect(freshDestroy).not.toHaveBeenCalled();
+
+ const reuse = await pool.acquire(key("old"), createFresh);
+ expect(createFresh).toHaveBeenCalledTimes(1);
+ await reuse.release({ destroy: true });
+ expect(freshDestroy).toHaveBeenCalledTimes(1);
+ await pool.destroyAll();
+ });
+
+ it("accepts successful Railway deletion after an idle credential client fails", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const revokedDestroy = vi.fn(async () => {
+ throw new Error("token revoked");
+ });
+ const currentDestroy = vi.fn(async () => undefined);
+ const first = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: revokedDestroy }),
+ );
+ await first.release();
+ const second = await pool.acquire(key("new"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: currentDestroy }),
+ );
+
+ await expect(second.release({ destroy: true })).resolves.toBeUndefined();
+ expect(revokedDestroy).toHaveBeenCalledOnce();
+ expect(currentDestroy).toHaveBeenCalledOnce();
+ await expect(pool.destroyAll()).resolves.toBeUndefined();
+ });
+
+ it("closes the releasing Railway lease when identity cleanup throws", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const failingDestroy = vi.fn(async () => {
+ throw new Error("delete failed");
+ });
+ const first = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: failingDestroy }),
+ );
+ await first.release();
+ const second = await pool.acquire(key("new"), async () =>
+ remoteWorkspace({ provider: "railway", destroy: failingDestroy }),
+ );
+ await expect(second.release({ destroy: true })).rejects.toThrow("delete failed");
+
+ const createRetry = vi.fn(async () => remoteWorkspace({ provider: "railway" }));
+ const retry = await pool.acquire(key("new"), createRetry);
+ expect(createRetry).toHaveBeenCalledTimes(1);
+ await retry.release();
+ await pool.destroyAll();
+ });
+
+ it("counts a Railway acquisition waiting in creation before honoring deletion", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const destroy = vi.fn(async () => undefined);
+ const old = await pool.acquire(key("old"), async () =>
+ remoteWorkspace({ provider: "railway", destroy }),
+ );
+ let markCreating!: () => void;
+ let finishCreating!: () => void;
+ const creating = new Promise<void>((resolve) => (markCreating = resolve));
+ const finish = new Promise<void>((resolve) => (finishCreating = resolve));
+ const pending = pool.acquire(key("new"), async () => {
+ markCreating();
+ await finish;
+ return remoteWorkspace({ provider: "railway", destroy });
+ });
+ await creating;
+ const releaseOld = old.release({ destroy: true });
+ finishCreating();
+ const next = await pending;
+ await releaseOld;
+ expect(destroy).not.toHaveBeenCalled();
+ await next.release();
+ expect(destroy).toHaveBeenCalledTimes(1);
+ await pool.destroyAll();
+ });
+
+ it("deduplicates Railway VM deletion during destroyAll across credential keys", async () => {
+ const pool = new BotWorkspacePool();
+ const key = (token: string) =>
+ botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: token }),
+ });
+ const destroy = vi.fn(async () => undefined);
+ const create = async () => remoteWorkspace({ provider: "railway", destroy });
+ const first = await pool.acquire(key("old"), create);
+ const second = await pool.acquire(key("new"), create);
+ await first.release();
+ await second.release();
+
+ await pool.destroyAll();
+ expect(destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it("destroys a Railway VM created while destroyAll is waiting for acquisition", async () => {
+ const pool = new BotWorkspacePool();
+ const key = botWorkspaceResourceKey({
+ resourceScope: "bot-one",
+ sandbox: "railway",
+ credentialFingerprint: botWorkspaceCredentialFingerprint({ RAILWAY_API_TOKEN: "token" }),
+ });
+ let markCreating!: () => void;
+ let finishCreating!: () => void;
+ const creating = new Promise<void>((resolve) => (markCreating = resolve));
+ const finish = new Promise<void>((resolve) => (finishCreating = resolve));
+ const destroy = vi.fn(async () => undefined);
+ const acquisition = pool.acquire(key, async () => {
+ markCreating();
+ await finish;
+ return remoteWorkspace({ provider: "railway", destroy });
+ });
+ await creating;
+
+ const shutdown = pool.destroyAll();
+ finishCreating();
+ await expect(acquisition).rejects.toThrow("shutting down");
+ await shutdown;
+ expect(destroy).toHaveBeenCalledTimes(1);
+ });
+
effectIt.effect("derives workspace identities", () =>
Effect.sync(() => {
expect(
@@ -137,6 +389,80 @@ describe("BotWorkspacePool", () => {
expect(create).toHaveBeenCalledTimes(2);
});
+ it("preserves a remote workspace after a failed initial wake and retries it", async () => {
+ const pool = new BotWorkspacePool();
+ const local = localWorkspace();
+ const remote = {
+ id: local.id,
+ provider: "ascii" as const,
+ workspace: local,
+ inspect: async () => "running" as const,
+ wake: () => local.init(),
+ sleep: () => local.stop(),
+ destroy: () => local.destroy(),
+ };
+ vi.spyOn(local, "init").mockRejectedValueOnce(new Error("wake failed"));
+ const destroy = vi.spyOn(local, "destroy");
+ const create = vi.fn(async () => remote);
+
+ await expect(pool.acquire("remote-wake", create)).rejects.toThrow("wake failed");
+ expect(destroy).not.toHaveBeenCalled();
+ const lease = await pool.acquire("remote-wake", create);
+ expect(create).toHaveBeenCalledTimes(2);
+ await lease.release({ destroy: true });
+ expect(destroy).toHaveBeenCalledOnce();
+ });
+
+ it("preserves and reattaches a remote workspace after idle sleep fails", async () => {
+ const pool = new BotWorkspacePool();
+ const local = localWorkspace();
+ const remote = {
+ id: local.id,
+ provider: "ascii" as const,
+ workspace: local,
+ inspect: async () => "running" as const,
+ wake: () => local.init(),
+ sleep: () => local.stop(),
+ destroy: () => local.destroy(),
+ };
+ vi.spyOn(local, "stop").mockRejectedValueOnce(new Error("sleep failed"));
+ const destroy = vi.spyOn(local, "destroy");
+ const create = vi.fn(async () => remote);
+ const lease = await pool.acquire("remote-sleep", create);
+
+ await expect(lease.release()).rejects.toThrow("sleep failed");
+ expect(destroy).not.toHaveBeenCalled();
+ const retry = await pool.acquire("remote-sleep", create);
+ expect(create).toHaveBeenCalledTimes(2);
+ await retry.release({ destroy: true });
+ expect(destroy).toHaveBeenCalledOnce();
+ });
+
+ it("preserves a remote workspace when waking after idle fails", async () => {
+ const pool = new BotWorkspacePool();
+ const local = localWorkspace();
+ const wake = vi.fn(async () => local.init());
+ const destroy = vi.fn(async () => local.destroy());
+ const create = vi.fn(async () => ({
+ id: local.id,
+ provider: "ascii" as const,
+ workspace: local,
+ inspect: async () => "running" as const,
+ wake,
+ sleep: () => local.stop(),
+ destroy,
+ }));
+ const lease = await pool.acquire("remote-idle-wake", create);
+ await lease.release();
+ wake.mockRejectedValueOnce(new Error("resume timed out"));
+ await expect(pool.acquire("remote-idle-wake", create)).rejects.toThrow("resume timed out");
+ expect(destroy).not.toHaveBeenCalled();
+ const retry = await pool.acquire("remote-idle-wake", create);
+ expect(create).toHaveBeenCalledTimes(2);
+ await retry.release({ destroy: true });
+ expect(destroy).toHaveBeenCalledOnce();
+ });
+
it("pauses and reuses a remote workspace after initial wake failure", async () => {
const pool = new BotWorkspacePool();
const failed = remoteWorkspace({
diff --git a/apps/server/src/provider/botWorkspacePool.ts b/apps/server/src/provider/botWorkspacePool.ts
index b773ea131..1086274c1 100644
--- a/apps/server/src/provider/botWorkspacePool.ts
+++ b/apps/server/src/provider/botWorkspacePool.ts
@@ -73,6 +73,15 @@ interface PoolState {
readonly scope: Scope.Closeable;
}
+interface RailwayIdentityState {
+ lock?: Promise<void>;
+ leases: number;
+ destroyRequested: boolean;
+ deleted: boolean;
+ readonly keys: Set<string>;
+ destruction?: Promise<void>;
+}
+
/**
* Keeps one workspace alive while matching thread sessions use it. After the
* final release the workspace stays awake for `idleTimeToLive` (zero by default), then sleeps.
@@ -91,6 +100,8 @@ export class BotWorkspacePool {
private readonly failed = new Set<string>();
private readonly retrying = new Set<string>();
private readonly closing = new Map<string, Promise<void>>();
+ private readonly railwayIdentities = new Map<string, RailwayIdentityState>();
+ private readonly activeAcquisitions = new Set<Promise<void>>();
private destroyingAll = false;
private readonly destroyAllFailures: unknown[] = [];
@@ -129,14 +140,21 @@ export class BotWorkspacePool {
Effect.map((created) =>
created instanceof Workspace ? wrapMastraWorkspace(created) : created,
),
+ Effect.map((workspace) =>
+ key.startsWith("railway:")
+ ? this.withIdentityDestroy(this.identityKey(key), workspace)
+ : workspace,
+ ),
Effect.tap((workspace) =>
Effect.tryPromise({ try: () => workspace.wake(), catch: toPoolError }).pipe(
Effect.tapCause(() =>
workspace.provider === "local"
? Effect.promise(() => workspace.destroy().catch(() => undefined))
- : Effect.sync(() => {
- this.sleepers.set(key, workspace);
- }),
+ : workspace.provider === "ascii"
+ ? Effect.void
+ : Effect.sync(() => {
+ this.sleepers.set(key, workspace);
+ }),
),
),
),
@@ -166,7 +184,13 @@ export class BotWorkspacePool {
}
private closeWorkspace(key: string, workspace: AkeruBotWorkspace): Effect.Effect<void> {
- if (this.destroyingAll || this.destroyRequested.delete(key)) {
+ if (
+ this.destroyingAll ||
+ this.destroyRequested.delete(key) ||
+ (key.startsWith("railway:") &&
+ this.railwayIdentity(this.identityKey(key)).destroyRequested &&
+ this.railwayIdentity(this.identityKey(key)).leases === 0)
+ ) {
this.sleepers.delete(key);
return Effect.tryPromise(() => workspace.destroy()).pipe(
Effect.tapError((cause) =>
@@ -183,10 +207,12 @@ export class BotWorkspacePool {
Effect.tapError(() =>
workspace.provider === "local"
? Effect.promise(() => workspace.destroy().catch(() => undefined))
- : Effect.sync(() => {
- this.sleepers.set(key, workspace);
- this.failed.add(key);
- }),
+ : workspace.provider === "ascii"
+ ? Effect.void
+ : Effect.sync(() => {
+ this.sleepers.set(key, workspace);
+ this.failed.add(key);
+ }),
),
Effect.catch((error) => Effect.die(error.cause)),
);
@@ -196,16 +222,154 @@ export class BotWorkspacePool {
key: string,
create: () => Promise<AkeruBotWorkspace | Workspace>,
): Promise<BotWorkspaceLease> {
+ if (this.destroyingAll) {
+ throw new BotWorkspacePoolError({ message: "Bot workspaces are shutting down." });
+ }
+ let finish!: () => void;
+ const acquisition = new Promise<void>((resolve) => (finish = resolve));
+ this.activeAcquisitions.add(acquisition);
this.acquisitions.set(key, (this.acquisitions.get(key) ?? 0) + 1);
+ const identity = this.identityKey(key);
try {
- return await this.acquireOnce(key, create);
+ const lease = await this.withIdentityCoordination(key, identity, async () => {
+ if (this.destroyingAll) {
+ throw new BotWorkspacePoolError({ message: "Bot workspaces are shutting down." });
+ }
+ if (key.startsWith("railway:")) {
+ const state = this.railwayIdentity(identity);
+ if (state.deleted) {
+ state.deleted = false;
+ delete state.destruction;
+ }
+ state.keys.add(key);
+ }
+ const acquired = await this.acquireOnce(key, create);
+ if (this.destroyingAll) {
+ await acquired.release({ destroy: true });
+ throw new BotWorkspacePoolError({ message: "Bot workspaces are shutting down." });
+ }
+ if (!key.startsWith("railway:")) return acquired;
+ this.railwayIdentity(identity).leases++;
+ return acquired;
+ });
+ if (!key.startsWith("railway:")) return lease;
+ let released = false;
+ return {
+ ...lease,
+ release: async (options) => {
+ if (released) return;
+ released = true;
+ await this.withIdentityCoordination(key, identity, async () => {
+ const state = this.railwayIdentity(identity);
+ if (options?.destroy) state.destroyRequested = true;
+ const remaining = --state.leases;
+ const destroy = state.destroyRequested && remaining === 0;
+ if (destroy) {
+ const { map } = await this.state;
+ const keys = state.keys;
+ let cleanupFailure: unknown;
+ let idleDeletionFailure: unknown;
+ for (const pooledKey of keys) {
+ this.destroyRequested.add(pooledKey);
+ const sleeping = this.sleepers.get(pooledKey);
+ this.sleepers.delete(pooledKey);
+ this.failed.delete(pooledKey);
+ if (sleeping) {
+ try {
+ await this.run(Effect.promise(() => sleeping.destroy()));
+ } catch (cause) {
+ idleDeletionFailure ??= cause;
+ }
+ }
+ try {
+ await this.run(RcMap.invalidate(map, pooledKey));
+ } catch (cause) {
+ cleanupFailure ??= cause;
+ }
+ }
+ for (const pooledKey of keys) this.destroyRequested.delete(pooledKey);
+ state.keys.clear();
+ state.deleted = true;
+ state.destroyRequested = false;
+ try {
+ await lease.release({ destroy });
+ } catch (cause) {
+ cleanupFailure ??= cause;
+ }
+ if (idleDeletionFailure !== undefined) {
+ // A current credential client can complete deletion after an idle client fails.
+ if (!state.destruction) throw idleDeletionFailure;
+ await state.destruction;
+ }
+ if (cleanupFailure !== undefined) throw cleanupFailure;
+ return;
+ }
+ await lease.release({ destroy });
+ });
+ },
+ };
} finally {
+ this.activeAcquisitions.delete(acquisition);
+ finish();
const remaining = (this.acquisitions.get(key) ?? 1) - 1;
if (remaining === 0) this.acquisitions.delete(key);
else this.acquisitions.set(key, remaining);
}
}
+ private identityKey(key: string): string {
+ return key.startsWith("railway:") ? botWorkspaceIdentity(key) : key;
+ }
+
+ private railwayIdentity(identity: string): RailwayIdentityState {
+ let state = this.railwayIdentities.get(identity);
+ if (!state) {
+ state = { leases: 0, destroyRequested: false, deleted: false, keys: new Set() };
+ this.railwayIdentities.set(identity, state);
+ }
+ return state;
+ }
+
+ private withIdentityCoordination<A>(
+ key: string,
+ identity: string,
+ operation: () => Promise<A>,
+ ): Promise<A> {
+ return key.startsWith("railway:") ? this.withIdentityLock(identity, operation) : operation();
+ }
+
+ private async withIdentityLock<A>(identity: string, operation: () => Promise<A>): Promise<A> {
+ const state = this.railwayIdentity(identity);
+ const previous = state.lock;
+ let unlock!: () => void;
+ const lock = new Promise<void>((resolve) => (unlock = resolve));
+ state.lock = lock;
+ await previous;
+ try {
+ return await operation();
+ } finally {
+ unlock();
+ if (state.lock === lock) delete state.lock;
+ }
+ }
+
+ private withIdentityDestroy(identity: string, workspace: AkeruBotWorkspace): AkeruBotWorkspace {
+ return {
+ ...workspace,
+ destroy: () => {
+ const state = this.railwayIdentity(identity);
+ const existing = state.destruction;
+ if (existing) return existing;
+ const destruction = workspace.destroy().catch((error: unknown) => {
+ if (state.destruction === destruction) delete state.destruction;
+ throw error;
+ });
+ state.destruction = destruction;
+ return destruction;
+ },
+ };
+ }
+
private async acquireOnce(
key: string,
create: () => Promise<AkeruBotWorkspace | Workspace>,
@@ -298,6 +462,12 @@ export class BotWorkspacePool {
async destroyAll(): Promise<void> {
const { scope } = await this.state;
this.destroyingAll = true;
+ await Promise.all(this.activeAcquisitions);
+ await Promise.all(
+ [...this.railwayIdentities.values()].flatMap((identity) =>
+ identity.lock ? [identity.lock] : [],
+ ),
+ );
await Promise.all(this.closing.values());
await this.run(Scope.close(scope, Exit.void));
const sleepers = [...this.sleepers.values()];
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 0dee0ef5a..e5f326231 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -190,6 +190,7 @@ export function redactServerSettingsForClient(settings: ServerSettings): ServerS
daytona: redactSandboxProviderConnection(settings.sandbox.providers.daytona),
vercel: redactSandboxProviderConnection(settings.sandbox.providers.vercel),
upstash: redactSandboxProviderConnection(settings.sandbox.providers.upstash),
+ ascii: redactSandboxProviderConnection(settings.sandbox.providers.ascii),
railway: redactSandboxProviderConnection(settings.sandbox.providers.railway),
tenki: redactSandboxProviderConnection(settings.sandbox.providers.tenki),
},
diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts
index a73c3a50d..51844a4cf 100644
--- a/apps/server/src/telemetry/AnalyticsService.test.ts
+++ b/apps/server/src/telemetry/AnalyticsService.test.ts
@@ -252,6 +252,19 @@ it.layer(NodeServices.layer)("anonymous analytics", (it) => {
assert.equal(failedState.cursorBucketStart, currentStart);
assert.isFalse(yield* fs.exists(config.anonymousIdPath));
+ // Simulate a queued state written before Ascii Box support was installed.
+ yield* fs.writeFileString(
+ config.analyticsStatePath,
+ encodeJson({
+ ...failedState,
+ pending: failedState.pending.map((event) => ({
+ ...event,
+ properties: Object.fromEntries(
+ Object.entries(event.properties).filter(([key]) => key !== "sandbox_turns_ascii"),
+ ),
+ })),
+ }),
+ );
yield* analytics.flush;
const deliveredState = readState(yield* fs.readFileString(config.analyticsStatePath));
assert.equal(deliveredState.pending.length, 0);
@@ -274,6 +287,7 @@ it.layer(NodeServices.layer)("anonymous analytics", (it) => {
readonly browser_searches_codex: number;
readonly provider_turns_codex: number;
readonly sandbox_turns_local: number;
+ readonly sandbox_turns_ascii: number;
readonly sandbox_turns_none: number;
readonly plugin_enabled_github: number;
};
@@ -296,6 +310,8 @@ it.layer(NodeServices.layer)("anonymous analytics", (it) => {
assert.equal(requests[0]?.batch[0]?.properties.browser_searches_codex, 1);
assert.equal(requests[0]?.batch[0]?.properties.provider_turns_codex, 1);
assert.equal(requests[0]?.batch[0]?.properties.sandbox_turns_local, 1);
+ assert.equal(requests[1]?.batch[0]?.properties.sandbox_turns_ascii, 0);
+ assert.equal(requests[1]?.batch[1]?.properties.sandbox_turns_ascii, 0);
assert.equal(requests[0]?.batch[0]?.properties.sandbox_turns_none, 1);
assert.equal(requests[0]?.batch[0]?.properties.plugin_enabled_github, 1);
assert.isFalse(requests[0]?.batch[0]?.properties.$process_person_profile);
diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts
index ce462a87d..8f5ce1f75 100644
--- a/apps/server/src/telemetry/AnalyticsService.ts
+++ b/apps/server/src/telemetry/AnalyticsService.ts
@@ -185,6 +185,7 @@ const sandboxValues = new Set([
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
]);
diff --git a/apps/web/src/components/roster/botSandbox.test.ts b/apps/web/src/components/roster/botSandbox.test.ts
index d7729e62e..f989a1407 100644
--- a/apps/web/src/components/roster/botSandbox.test.ts
+++ b/apps/web/src/components/roster/botSandbox.test.ts
@@ -35,6 +35,7 @@ describe("botSandbox", () => {
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
]);
diff --git a/apps/web/src/components/roster/botSandbox.ts b/apps/web/src/components/roster/botSandbox.ts
index b0cf08b2a..2146b9005 100644
--- a/apps/web/src/components/roster/botSandbox.ts
+++ b/apps/web/src/components/roster/botSandbox.ts
@@ -20,6 +20,7 @@ export const BOT_SANDBOX_OPTIONS = [
{ value: "daytona", label: "Daytona" },
{ value: "vercel", label: "Vercel Sandbox" },
{ value: "upstash", label: "Upstash Box" },
+ { value: "ascii", label: "Ascii Box" },
{ value: "railway", label: "Railway" },
{ value: "tenki", label: "Tenki" },
] as const;
diff --git a/apps/web/src/components/roster/types.ts b/apps/web/src/components/roster/types.ts
index 7ff98c4ee..cf655a58f 100644
--- a/apps/web/src/components/roster/types.ts
+++ b/apps/web/src/components/roster/types.ts
@@ -37,7 +37,16 @@ export interface Bot {
disabledMcpServerIds: readonly McpServerId[];
avatar: BotAvatar;
engine: BotEngine | null;
- sandbox: "local" | "e2b" | "daytona" | "vercel" | "upstash" | "railway" | "tenki" | null;
+ sandbox:
+ | "local"
+ | "e2b"
+ | "daytona"
+ | "vercel"
+ | "upstash"
+ | "ascii"
+ | "railway"
+ | "tenki"
+ | null;
runtimeMode: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
usageCap: { unit: "tokens"; limit: number } | null;
/** Personality baseline, 0 (chill) to 100 (professional). Absent on bots saved before the field existed. */
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts b/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts
index b1955a210..5d9f4466b 100644
--- a/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.logic.test.ts
@@ -84,6 +84,28 @@ describe("sandbox settings", () => {
).toBe(false);
});
+ it("connects Ascii Box with a sensitive key and clears the default on disconnect", () => {
+ const settings = DEFAULT_SERVER_SETTINGS.sandbox;
+ expect(canSaveSandboxProviderConnection({ settings, provider: "ascii", draft: {} })).toBe(
+ false,
+ );
+ const connected = saveSandboxProviderConnection({
+ settings,
+ provider: "ascii",
+ draft: { BOX_API_KEY: " ascii-secret " },
+ });
+ expect(connected.providers.ascii.environment).toEqual([
+ { name: "BOX_API_KEY", value: "ascii-secret", sensitive: true },
+ ]);
+ expect(selectableSandboxProviders(connected)).toContain("ascii");
+ const disconnected = disconnectSandboxProvider(
+ { ...connected, defaultProvider: "ascii" },
+ "ascii",
+ );
+ expect(disconnected.defaultProvider).toBe("local");
+ expect(selectableSandboxProviders(disconnected)).not.toContain("ascii");
+ });
+
it("keeps a redacted key and falls back to local on disconnect", () => {
const connected = {
...saveSandboxProviderConnection({
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts b/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts
index 7f08d35c8..a64ce6a91 100644
--- a/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.logic.ts
@@ -51,6 +51,12 @@ const SANDBOX_PROVIDER_DEFINITION_BY_ID: Readonly<
description: "Cloud workspaces managed by Upstash Box. Requires an API key.",
fields: [{ name: "UPSTASH_BOX_API_KEY", label: "API key", secret: true }],
},
+ ascii: {
+ id: "ascii",
+ label: "Ascii Box",
+ description: "Run bots in a persistent Linux VM. Public previews are enabled by default.",
+ fields: [{ name: "BOX_API_KEY", label: "API key", secret: true }],
+ },
railway: {
id: "railway",
label: "Railway",
diff --git a/apps/web/src/components/settings/SandboxSettingsPanel.tsx b/apps/web/src/components/settings/SandboxSettingsPanel.tsx
index 8dbaa4f9d..ec96badf6 100644
--- a/apps/web/src/components/settings/SandboxSettingsPanel.tsx
+++ b/apps/web/src/components/settings/SandboxSettingsPanel.tsx
@@ -42,6 +42,7 @@ const SANDBOX_PROVIDER_LABELS: Readonly<Record<SandboxProvider, string>> = {
daytona: "Daytona",
vercel: "Vercel Sandbox",
upstash: "Upstash Box",
+ ascii: "Ascii Box",
railway: "Railway",
tenki: "Tenki",
};
diff --git a/docs/internals/railway-workspaces.md b/docs/internals/railway-workspaces.md
index 8d897eed9..7a61931c7 100644
--- a/docs/internals/railway-workspaces.md
+++ b/docs/internals/railway-workspaces.md
@@ -6,6 +6,8 @@ The shared identity file persists the Railway sandbox ID. Reattachment uses `San
Railway identity hashes exclude the credential fingerprint while pool keys retain it. Rotating credentials creates a fresh SDK client but reconnects to the same saved VM, including after a server restart. Changing environments or revoking access fails closed rather than abandoning the old identity and creating a second billable VM. Settings requires explicit acknowledgement of the Railway-dashboard retirement path before replacing or removing existing credentials; this is not automatic remote cleanup.
+The workspace pool serializes Railway acquisition and release by durable identity across credential-scoped clients. A destroy request waits for the final identity lease, invalidates idle clients, and deletes the VM once. Shutdown waits for pending identity operations and deduplicates deletion. Creation after deletion starts a fresh lifecycle; stale clients cannot reattach from the idle cache.
+
Railway has no SDK pause/resume operation. Workspace-pool release is therefore nondestructive: sleep is a no-op, wake verifies the VM is running, and destroy deletes the VM before the shared wrapper removes its identity file. Disk checkpoints are a Railway capability, not a substitute for pause/resume: restoring one creates a different VM and cannot transparently preserve the saved identity. No checkpoint API is added to the common workspace contract.
Commands use the existing shell quoting and map cwd, environment, and millisecond timeouts to SDK options. A null exit code is treated as failure, never successful execution.
diff --git a/docs/user/sandboxes.md b/docs/user/sandboxes.md
index f792362b4..419229f06 100644
--- a/docs/user/sandboxes.md
+++ b/docs/user/sandboxes.md
@@ -1,6 +1,6 @@
# Configure sandboxes
-Open **Settings > Sandbox** to connect E2B, Daytona, Vercel Sandbox, Upstash Box, Tenki, or Railway. Local workspaces
+Open **Settings > Sandbox** to connect E2B, Daytona, Vercel Sandbox, Upstash Box, Tenki, Railway, or Ascii Box. Local workspaces
need no credential and are always available.
Tenki runs coding agents in full Linux VMs and supports public previews, disk and memory snapshots,
@@ -26,12 +26,26 @@ so connect that service before you start the bot.
Akeru pauses remote sandboxes other than Railway while bots are idle and reconnects to the saved provider workspace when
bot work resumes.
-If a remote pause fails, Akeru keeps the workspace and retries the pause while it remains idle.
+If a remote pause fails, Akeru keeps the workspace and retries the pause while it remains idle,
+except on Ascii Box, where it reconnects to the saved VM on the next use.
Railway VMs remain running while idle and can continue accruing charges. Connect with a
`RAILWAY_API_TOKEN` and `RAILWAY_ENVIRONMENT_ID`. Previews require a Railway CLI tunnel;
Akeru cannot attach its sandbox browser. See [Railway workspaces](railway-sandboxes.md)
for credential rotation and VM cleanup.
+Ascii Box runs persistent Linux VMs. Stopping a VM saves a native lifecycle snapshot; resuming it
+restores that workspace. Ascii Box supports public previews by default, so do not expose sensitive
+services. Akeru requests protected, token-authenticated access for its browser-control endpoint.
+If session setup fails, Akeru preserves the VM and waits for snapshot cleanup before reporting the
+error. Snapshot archival can take up to five minutes; retries wait for that cleanup to finish.
+New VMs do not inherit credentials from your Ascii account environment.
+Ascii Box commands support timeouts of up to ten minutes. Requests for longer timeouts are rejected
+before the command starts rather than silently shortened.
+If Ascii confirms that a saved VM no longer exists, Akeru creates a replacement on the next use.
+Connection failures and permission errors retain the saved VM identity rather than replacing it.
+Connect it with a Box API key. Ascii Box is now Boat; this integration uses the legacy Box API, which
+the provider supports until its announced sunset. See the [migration notice](https://docs.boat.dev/migrating-from-box).
+
Changing a provider credential replaces active sessions that use the connection. A running session
cannot continue with the old credential.
diff --git a/packages/client-runtime/src/i18n/index.ts b/packages/client-runtime/src/i18n/index.ts
index e123893c1..5a88bfc18 100644
--- a/packages/client-runtime/src/i18n/index.ts
+++ b/packages/client-runtime/src/i18n/index.ts
@@ -11,6 +11,8 @@ export const availableLanguages = [
] as const;
export const englishCatalog = {
+ "Run bots in a persistent Linux VM. Public previews are enabled by default.":
+ "Run bots in a persistent Linux VM. Public previews are enabled by default.",
"Retire Railway VMs before changing access": "Retire Railway VMs before changing access",
"Open Railway dashboard": "Open Railway dashboard",
"I have reviewed my VMs — continue": "I have reviewed my VMs — continue",
diff --git a/packages/client-runtime/src/i18n/zh-CN.ts b/packages/client-runtime/src/i18n/zh-CN.ts
index 50996415b..7738cedca 100644
--- a/packages/client-runtime/src/i18n/zh-CN.ts
+++ b/packages/client-runtime/src/i18n/zh-CN.ts
@@ -2312,6 +2312,8 @@ export const zhCNCatalog: TranslationCatalog = {
"Cloud workspaces managed by Daytona. Requires an API key.":
"由 Daytona 管理的云端工作区。需要 API 密钥。",
"Cloud workspaces in your Vercel team and project.": "位于你的 Vercel 团队和项目中的云端工作区。",
+ "Run bots in a persistent Linux VM. Public previews are enabled by default.":
+ "在持久化 Linux 虚拟机中运行机器人。默认启用公开预览。",
"Cloud workspaces managed by Upstash Box. Requires an API key.":
"由 Upstash Box 管理的云端工作区。需要 API 密钥。",
"Cloud workspaces managed by Tenki. Requires an API key.":
diff --git a/packages/client-runtime/src/state/computerViewer.ts b/packages/client-runtime/src/state/computerViewer.ts
index 847f9eeac..3b6b3c2e9 100644
--- a/packages/client-runtime/src/state/computerViewer.ts
+++ b/packages/client-runtime/src/state/computerViewer.ts
@@ -269,6 +269,7 @@ export const COMPUTER_SANDBOX_CAPABILITY: Readonly<
daytona: { graphical: true },
vercel: { graphical: false },
upstash: { graphical: false },
+ ascii: { graphical: false },
railway: { graphical: false },
tenki: { graphical: false },
};
diff --git a/packages/contracts/src/analytics.test.ts b/packages/contracts/src/analytics.test.ts
index 3cf180656..82413464c 100644
--- a/packages/contracts/src/analytics.test.ts
+++ b/packages/contracts/src/analytics.test.ts
@@ -52,7 +52,7 @@ const rejects = (input: unknown) => expect(() => decodeUsage3hEvent(input)).toTh
describe("Usage3hEvent", () => {
it("accepts the fixed anonymous aggregate payload", () => {
expect(decodeUsage3hEvent(event)).toEqual(event);
- expect(USAGE_3H_COUNTER_KEYS).toHaveLength(96);
+ expect(USAGE_3H_COUNTER_KEYS).toHaveLength(97);
});
it("accepts current remote sandboxes and rejects the retired hosted sandbox", () => {
@@ -61,6 +61,7 @@ describe("Usage3hEvent", () => {
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
] as const) {
@@ -87,7 +88,7 @@ describe("Usage3hEvent", () => {
).toBe(0);
});
- it.each(["sandbox_turns_tenki", "sandbox_turns_railway"])(
+ it.each(["sandbox_turns_tenki", "sandbox_turns_railway", "sandbox_turns_ascii"])(
"defaults queued %s counters without changing event identity",
(counter) => {
const properties = Object.fromEntries(
@@ -110,6 +111,23 @@ describe("Usage3hEvent", () => {
rejects({ ...event, properties: { ...event.properties, thread_id: "thread-1" } });
});
+ it("defaults queued events from before Ascii Box support to zero", () => {
+ const legacyProperties = Object.fromEntries(
+ Object.entries(event.properties).filter(([key]) => key !== "sandbox_turns_ascii"),
+ );
+ expect(decodeUsage3hEvent({ ...event, properties: legacyProperties })).toEqual(event);
+ });
+
+ it("preserves valid Ascii counters and rejects invalid explicit values", () => {
+ expect(
+ decodeUsage3hEvent({ ...event, properties: { ...event.properties, sandbox_turns_ascii: 3 } })
+ .properties.sandbox_turns_ascii,
+ ).toBe(3);
+ for (const sandbox_turns_ascii of [-1, 0.5, USAGE_3H_COUNTER_MAX + 1, null, "0"]) {
+ rejects({ ...event, properties: { ...event.properties, sandbox_turns_ascii } });
+ }
+ });
+
it("rejects free text, invalid enums, and invalid versions", () => {
rejects({ ...event, distinct_id: "installation-name" });
rejects({ ...event, properties: { ...event.properties, provider: "custom-provider" } });
diff --git a/packages/contracts/src/analytics.ts b/packages/contracts/src/analytics.ts
index c0501b3fe..9fc8ba559 100644
--- a/packages/contracts/src/analytics.ts
+++ b/packages/contracts/src/analytics.ts
@@ -33,6 +33,7 @@ export const USAGE_SANDBOX_IDS = [
"vercel",
"akeru_cloud",
"upstash",
+ "ascii",
"railway",
"tenki",
"other",
@@ -170,6 +171,7 @@ export const UsageSandboxProvider = Schema.Literals([
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
"mixed",
@@ -184,6 +186,7 @@ const UsageCounters = Schema.Struct({
new_installations: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 1 })).pipe(
Schema.withDecodingDefault(Effect.succeed(0)),
),
+ sandbox_turns_ascii: UsageCounter.pipe(Schema.withDecodingDefault(Effect.succeed(0))),
});
export const Usage3hProperties = Schema.Struct({
diff --git a/packages/contracts/src/botConfig.test.ts b/packages/contracts/src/botConfig.test.ts
index 4d14d4ee3..04db0b4e1 100644
--- a/packages/contracts/src/botConfig.test.ts
+++ b/packages/contracts/src/botConfig.test.ts
@@ -47,6 +47,7 @@ describe("BotUsageCap", () => {
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
] as const) {
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 6e6f7e885..8b681bd1f 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -381,6 +381,7 @@ export const BotSandbox = Schema.Literals([
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
]);
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 784a1dc39..8a7e03655 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -305,6 +305,7 @@ describe("ServerSettings sandbox providers", () => {
daytona: { environment: [] },
vercel: { environment: [] },
upstash: { environment: [] },
+ ascii: { environment: [] },
railway: { environment: [] },
tenki: { environment: [] },
},
@@ -333,6 +334,20 @@ describe("ServerSettings sandbox providers", () => {
});
});
+ it("accepts the Ascii Box credential", () => {
+ expect(
+ decodeServerSettingsPatch({
+ sandbox: {
+ providers: {
+ ascii: {
+ environment: [{ name: "BOX_API_KEY", value: "secret", sensitive: true }],
+ },
+ },
+ },
+ }).sandbox?.providers?.ascii?.environment,
+ ).toEqual([{ name: "BOX_API_KEY", value: "secret", sensitive: true }]);
+ });
+
it("accepts Tenki's secret API key", () => {
expect(
decodeServerSettingsRpcPatch({
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 0b750f881..03d36e966 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -669,6 +669,7 @@ export const CLOUD_SANDBOX_PROVIDERS = [
"daytona",
"vercel",
"upstash",
+ "ascii",
"railway",
"tenki",
] as const;
@@ -681,6 +682,7 @@ export const SANDBOX_PROVIDER_CREDENTIALS = {
{ name: "VERCEL_PROJECT_ID", sensitive: false },
],
upstash: [{ name: "UPSTASH_BOX_API_KEY", sensitive: true }],
+ ascii: [{ name: "BOX_API_KEY", sensitive: true }],
railway: [
{ name: "RAILWAY_API_TOKEN", sensitive: true },
{ name: "RAILWAY_ENVIRONMENT_ID", sensitive: false },
@@ -710,6 +712,7 @@ export const SandboxSettings = Schema.Struct({
daytona: SandboxProviderConnection,
vercel: SandboxProviderConnection,
upstash: SandboxProviderConnection,
+ ascii: SandboxProviderConnection,
railway: SandboxProviderConnection,
tenki: SandboxProviderConnection,
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
@@ -1024,6 +1027,7 @@ const SandboxSettingsPatch = Schema.Struct({
daytona: Schema.optionalKey(SandboxProviderConnectionPatch),
vercel: Schema.optionalKey(SandboxProviderConnectionPatch),
upstash: Schema.optionalKey(SandboxProviderConnectionPatch),
+ ascii: Schema.optionalKey(SandboxProviderConnectionPatch),
railway: Schema.optionalKey(SandboxProviderConnectionPatch),
tenki: Schema.optionalKey(SandboxProviderConnectionPatch),
}),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 25a4be036..7830ac75f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -463,6 +463,9 @@ importers:
'@anthropic-ai/claude-agent-sdk':
specifier: ^0.3.170
version: 0.3.170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
+ '@asciidev/box-sdk':
+ specifier: 0.0.37
+ version: 0.0.37
'@chat-adapter/discord':
specifier: 4.39.0
@@ -1341,6 +1344,9 @@ packages:
resolution: {integrity: sha512-9C2o9X/lBEDBUnKfAi3mRo9oG7Z03nmISLwsGkWxIWjMAvBdJD0RRSJMekWVKzfXN3byrI1WlCXTITzN4LAoLw==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0, npm: '>=8'}
+ '@asciidev/[email protected]':
+ resolution: {integrity: sha512-fZhs5ygWO3uZ3clx/dPVSRPMadCbNleyeeB2tf+hcqgOKpqWNfjOk/a8M/QffpZfQE8n5LJUtQlqnL7ysBi/Qw==}
+
'@ast-grep/[email protected]':
resolution: {integrity: sha512-pcTBI8UiNQ9xVOYfu3Ww5KXcrrHV/jJqECQ6efpJpzTGwW+mOpzgihfrq5GKjbMONhr0OaRARCMwEsvKgBXCpA==}
engines: {node: '>= 10'}
@@ -14160,6 +14166,8 @@ snapshots:
lru-cache: 10.4.3
set-blocking: 2.0.0
+ '@asciidev/[email protected]': {}
+
'@ast-grep/[email protected]':
optional: true