Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(server): split the 1,484-line sandboxStorage router into sub-domain modules (#21089)

Arvin Xuc67809dcff93
diff --git a/apps/server/src/routers/lambda/sandboxStorage.ts b/apps/server/src/routers/lambda/sandboxStorage.ts
deleted file mode 100644
index f11526d4d8d..00000000000
--- a/apps/server/src/routers/lambda/sandboxStorage.ts
+++ /dev/null
@@ -1,1484 +0,0 @@
-import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';
-import { ConnectorDataError } from '@lobechat/connector-data';
-import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';
-import { type LobeChatDatabase } from '@lobechat/database';
-import { toExecutionConfiguration } from '@lobechat/types';
-import {
- derivedInstanceDirectory,
- isDefaultInstance,
- MAX_DERIVED_DIRECTORY_ATTEMPTS,
-} from '@lobechat/utils/environmentInstance';
-import { TRPCError } from '@trpc/server';
-import pMap from 'p-map';
-import { z } from 'zod';
-
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { EnvironmentModel } from '@/database/models/environment';
-import {
- EnvironmentInstanceModel,
- InstanceDirectoryOverlapError,
-} from '@/database/models/environmentInstance';
-import { TopicModel } from '@/database/models/topic';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { ConnectorDataService } from '@/server/services/connectorData';
-import { MarketService } from '@/server/services/market';
-import { resolveSandboxSessionConfig, resolveSandboxStorageClaim } from '@/server/services/sandbox';
-import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';
-import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';
-
-/**
- * Browsing and managing the persistent sandbox workspace.
- *
- * The workspace lives on a volume mounted into the sandbox runtime, so every
- * call here runs inside a sandbox session on the caller's behalf. Paths are
- * always relative to the workspace root; the absolute mount path never reaches
- * a client, which leaves nothing for one to smuggle back.
- */
-
-/** Relative workspace path, validated with the same rule the runtime applies. */
-const relativePathSchema = z.string().refine(isSafeSandboxCwd, {
- message: 'Path must be a relative path inside the workspace',
-});
-
-/**
- * Topic whose warm sandbox session should serve the call, so listing a
- * directory does not cold-start a second sandbox next to the one the user is
- * already talking to.
- */
-const topicIdSchema = z.string().min(1).max(255).optional();
-
-/**
- * Ceiling on a single write. Generous for anything a person edits by hand and
- * small enough that a runaway body is refused before it is buffered β€” this is
- * an editor's save path, not a bulk upload.
- */
-const MAX_FILE_CONTENT_BYTES = 1024 * 1024;
-
-/**
- * Checked in UTF-8 bytes, which is what the cap is denominated in and what the
- * execution plane actually receives. `z.string().max()` counts UTF-16 code
- * units, so a megabyte of CJK would pass it and send roughly three.
- */
-const fileContentSchema = z
- .string()
- .refine((value) => Buffer.byteLength(value, 'utf8') <= MAX_FILE_CONTENT_BYTES, {
- message: `File content exceeds ${MAX_FILE_CONTENT_BYTES} bytes`,
- });
-
-/**
- * "You have not connected GitHub" travels as an error from the connector layer,
- * but for the picker it is an answer, not a failure β€” the one it is there to
- * help the user fix.
- */
-const isGithubUnavailable = (error: unknown): boolean =>
- error instanceof ConnectorDataError && error.provider === 'github' && !error.retryable;
-
-/**
- * Whether building from this definition does anything: an environment that
- * clones nothing and installs nothing is already everything it will ever be.
- * Shared by the build itself, which settles such an instance without starting
- * a sandbox, and the listing, which is how the row knows a rebuild would be a
- * no-op rather than a folder thrown away.
- */
-const isBuildable = (
- specification: { bootstrapCommand?: string | null; sources?: unknown[] | null } | null,
-): boolean => (specification?.sources?.length ?? 0) > 0 || Boolean(specification?.bootstrapCommand);
-
-/**
- * Statuses the execution plane uses deliberately, each carrying something the
- * user can act on. Anything else is a fault on the far side and says so.
- *
- * `409` is the one worth naming: it means a conversation is still using this
- * environment. Collapsing it into a generic upstream failure would replace the
- * only actionable message with one that suggests the product is broken.
- */
-const WORKSPACE_ERROR_CODES: Record<number, TRPCError['code']> = {
- 400: 'BAD_REQUEST',
- 403: 'FORBIDDEN',
- 404: 'NOT_FOUND',
- 409: 'CONFLICT',
- // The workspace is out of quota β€” the user frees space or upgrades.
- 507: 'PAYLOAD_TOO_LARGE',
-};
-
-const mapStorageError = (error: unknown): never => {
- if (error instanceof SandboxStorageFilesError) {
- throw new TRPCError({
- code: WORKSPACE_ERROR_CODES[error.status] ?? 'BAD_GATEWAY',
- // The machine code when the market sent one, the way this router's own
- // refusals travel (`ENVIRONMENT_HAS_INSTANCES`): the client turns a code
- // into a sentence in the reader's language. The description beside it
- // names the row by its id, so forwarding it verbatim put a UUID in a
- // toast β€” accurate, and useless to the person reading it.
- message: error.code || error.message,
- });
- }
-
- throw error;
-};
-
-/**
- * Resolves the caller's sandbox-storage claim: which directory on the volume
- * they are entitled to and how large it may be.
- *
- * It reads `ctx.workspaceId`, but that is the TEAM workspace, and it is read
- * only to decide whose storage this is β€” a member inside a team gets the
- * team's shared directory, otherwise their personal one. The claim itself has
- * nothing to do with the team workspace, which is why neither this nor
- * anything built on it is named after one.
- *
- * The caller is always acting as themselves here β€” a signed-in user browsing
- * their own storage, not an agent run executing under someone else's identity
- * β€” so there is no share-visitor case to suppress.
- */
-const storageClaimProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const workspaceId = ctx.workspaceId ?? undefined;
-
- const claim = await resolveSandboxStorageClaim({
- isShareVisitorRun: false,
- serverDB: ctx.serverDB,
- userId: ctx.userId,
- workspaceId,
- });
-
- return opts.next({
- ctx: {
- claim,
- marketService: new MarketService({
- userInfo: { sandboxStorage: claim, userId: ctx.userId, workspaceId },
- }),
- },
- });
-});
-
-/**
- * Everything past the entitlement check. Without a claim there is no directory
- * to address β€” the execution plane would reject the call anyway, and failing
- * here keeps a client that renders the panel too eagerly from looking like a
- * server fault.
- */
-const entitledProcedure = storageClaimProcedure.use(async (opts) => {
- const { claim, marketService } = opts.ctx;
- if (!claim) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'This account has no persistent sandbox workspace',
- });
- }
-
- return opts.next({ ctx: { claim, client: marketService.getSandboxStorageClient() } });
-});
-
-/**
- * A user-facing environment name. Distinct from the row's id, which is what the
- * execution plane stores the snapshot under and never changes β€” this is the
- * part a rename is allowed to move.
- */
-const nameSchema = z.string().trim().min(1).max(255);
-
-/**
- * The topic the execution plane keys its file-browser console sessions to.
- * The same literal market uses (`MANAGEMENT_TOPIC_ID`); it is not a topic of
- * ours, so it is never looked up and the run is shown as a console session.
- */
-const MANAGEMENT_TOPIC_ID = 'sandbox-workspace-console';
-
-/**
- * An environment or instance id. Checked for shape rather than left to the
- * lookup, because the lookup cannot answer: a non-UUID compared against a
- * `uuid` column is a Postgres type error, so the caller would get a server
- * fault where "no such environment" was the answer.
- *
- * An instance's id doubles as the name its snapshot is stored under, which is
- * why it never changes.
- */
-const idSchema = z.string().uuid();
-
-/**
- * Who an environment resolves for inside a workspace. Personal environments
- * have no pool to join, so the server stores `private` for them whatever a
- * client sends.
- */
-const visibilitySchema = z.enum(['private', 'public']);
-
-/** The indexes that make a name identify one environment for one member. */
-const ENVIRONMENT_NAME_CONSTRAINTS = new Set([
- 'environments_user_name_unique',
- 'environments_workspace_user_name_unique',
-]);
-
-/** The index that keeps two instances out of the same directory. */
-const INSTANCE_DIRECTORY_CONSTRAINT = 'environment_instances_provider_path_unique';
-
-/**
- * The hosts a checkout may name.
- *
- * An allowlist rather than an SSRF check on the resolved address, because the
- * clone does not happen here: the stored specification is handed to the
- * execution plane, which resolves and fetches it from its own network, so no
- * validation at this layer can speak for what that resolution will return.
- * Naming the hosts is the part this layer can be sure of β€” and every producer
- * already names exactly one, since a source is chosen through the GitHub
- * repository picker and the UI parses the URL back assuming that host.
- */
-const ALLOWED_SOURCE_HOSTS = new Set(['github.com', 'www.github.com']);
-
-/**
- * Where source material comes from. Only `git` for now, and only over HTTPS:
- * the other transports authenticate with a key, and a specification that
- * carries no credentials cannot present one. Private repositories are a
- * separate problem, not a URL scheme.
- *
- * The host is checked because this schema guards an RPC, not the picker: an
- * entitled caller reaching it directly could otherwise store any URL, and the
- * build would then make the execution plane fetch it β€” an internal address
- * included.
- */
-const environmentSourceSchema = z.object({
- kind: z.literal('git'),
- /** Where the checkout lands, relative to the instance's own directory. */
- path: relativePathSchema.optional(),
- ref: z.string().trim().min(1).max(255).optional(),
- url: z
- .string()
- .url()
- .refine(
- (value) => {
- let parsed;
- try {
- parsed = new URL(value);
- } catch {
- return false;
- }
-
- return parsed.protocol === 'https:' && ALLOWED_SOURCE_HOSTS.has(parsed.hostname);
- },
- { message: 'Only https:// github.com git URLs are supported' },
- ),
-});
-
-/**
- * Non-secret values only. Enforced by shape as far as a shape can: the name has
- * to look like an environment variable, and the rest is said plainly in the UI
- * and in the type. A field that stores what the user types cannot tell a region
- * from a token, which is why secrets are resolved at use time instead.
- */
-const environmentEnvSchema = z.record(
- z
- .string()
- .max(128)
- .regex(/^[A-Z_]\w*$/i, 'Must be a valid environment variable name'),
- z.string().max(4096),
-);
-
-const configurationSchema = z.object({
- bootstrapCommand: z.string().max(8000).optional(),
- env: environmentEnvSchema.optional(),
- excludePaths: z.array(relativePathSchema).max(64).optional(),
- internetAccess: z.boolean().optional(),
- // Which form the product shows. Accepted here so it is stored rather than
- // stripped by the parse; it never travels on to the execution plane.
- kind: z.enum(['files', 'code']).optional(),
- maintenanceCommand: z.string().max(8000).optional(),
- // One repository per environment. The wire format stays a list because the
- // execution plane checks out an array of sources, but an environment that
- // builds from two repositories has no single working directory to hand a
- // conversation β€” and the picker that fills this offers exactly one.
- sources: z.array(environmentSourceSchema).max(1).optional(),
-});
-
-/** Postgres surfaces the driver error somewhere down the `cause` chain. */
-const getPostgresErrorField = (error: unknown, field: string): string | undefined => {
- let current: unknown = error;
-
- while (current && typeof current === 'object') {
- const value = (current as Record<string, unknown>)[field];
- if (typeof value === 'string') return value;
-
- current = (current as { cause?: unknown }).cause;
- }
-};
-
-/**
- * The name is the one thing the person chose, and a collision is fixed by
- * typing a different one β€” so it has to arrive as CONFLICT next to the field,
- * not as the generic failure a raw driver error would produce. A code rather
- * than prose because this one is shown inline and has to be translated.
- */
-const rethrowDuplicateEnvironmentName = (error: unknown): never => {
- if (
- getPostgresErrorField(error, 'code') === '23505' &&
- ENVIRONMENT_NAME_CONSTRAINTS.has(getPostgresErrorField(error, 'constraint') ?? '')
- ) {
- throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'DUPLICATE_ENVIRONMENT_NAME' });
- }
-
- throw error;
-};
-
-/**
- * Two instances in one directory would restore two package sets over each
- * other's files, so the database refuses it and the person picks another
- * directory. Same reasoning as a duplicate name, different fix.
- */
-const isDuplicateInstanceDirectory = (error: unknown): boolean =>
- getPostgresErrorField(error, 'code') === '23505' &&
- getPostgresErrorField(error, 'constraint') === INSTANCE_DIRECTORY_CONSTRAINT;
-
-const rethrowDuplicateInstanceDirectory = (error: unknown): never => {
- // The same fix for the person β€” pick another folder β€” but a different
- // sentence, since the folder itself is not taken.
- if (error instanceof InstanceDirectoryOverlapError) {
- throw new TRPCError({
- cause: error,
- code: 'CONFLICT',
- message: 'OVERLAPPING_INSTANCE_DIRECTORY',
- });
- }
-
- if (isDuplicateInstanceDirectory(error)) {
- throw new TRPCError({
- cause: error,
- code: 'CONFLICT',
- message: 'DUPLICATE_INSTANCE_DIRECTORY',
- });
- }
-
- throw error;
-};
-
-/**
- * An environment with instances still on it. The reference is `restrict`
- * on purpose β€” deleting the specification out from under them would leave
- * directories and captured state nothing describes.
- */
-const rethrowEnvironmentInUse = (error: unknown): never => {
- if (getPostgresErrorField(error, 'code') === '23503') {
- throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });
- }
-
- throw error;
-};
-
-/**
- * An environment is a specification plus whatever has been built from it. This
- * layer owns the specification; the snapshot belongs to the execution plane and
- * is addressed by the row's id.
- *
- * An environment that was created but never used has no snapshot yet, which is
- * a normal state and not an error: it becomes real the first time a session
- * using it ends.
- */
-const environmentProcedure = entitledProcedure.use(async (opts) => {
- const { ctx } = opts;
-
- return opts.next({
- ctx: {
- environmentModel: new EnvironmentModel(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ),
- },
- });
-});
-
-/**
- * Where an instance lives, in the vocabulary `environment_instances` uses
- * for every execution target it supports.
- *
- * The scope is the caller's workspace key and the resource is the one
- * persistent workspace inside it β€” there is exactly one, which is why the
- * resource is named rather than identified. What distinguishes two instances is
- * the directory, and `environment_instances_provider_path_unique` covers that
- * tuple, so the database is what stops two copies landing in one folder.
- */
-const sandboxBinding = (workspaceKey: string) => ({
- deviceId: null,
- kind: 'sandbox' as const,
- provider: 'market',
- providerResourceId: 'workspace',
- providerScope: workspaceKey,
-});
-
-const instanceProcedure = environmentProcedure.use(async (opts) => {
- const { ctx } = opts;
-
- return opts.next({
- ctx: {
- instanceModel: new EnvironmentInstanceModel(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ),
- },
- });
-});
-
-type SandboxStorageClient = ReturnType<MarketService['getSandboxStorageClient']>;
-
-/**
- * Run `fn` with the environment and instance models bound to one transaction,
- * for the calls that must change both tables or neither.
- */
-const inEnvironmentTransaction = <T>(
- ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string | null },
- fn: (models: {
- environmentModel: EnvironmentModel;
- instanceModel: EnvironmentInstanceModel;
- }) => Promise<T>,
-): Promise<T> =>
- ctx.serverDB.transaction(async (tx) => {
- const db = tx as unknown as LobeChatDatabase;
- const workspaceId = ctx.workspaceId ?? undefined;
-
- return fn({
- environmentModel: new EnvironmentModel(db, ctx.userId, workspaceId),
- instanceModel: new EnvironmentInstanceModel(db, ctx.userId, workspaceId),
- });
- });
-
-/**
- * A new sandbox instance of an environment the caller owns, with its directory
- * derived from the environment's name rather than asked for.
- *
- * The directory is searched rather than computed in one shot: the unique
- * index spans the whole workspace, not one environment, so a name that is
- * free inside this environment can still be taken outside it. The index stays
- * the authority β€” the pre-check only keeps the common case out of the error
- * path, and a lost race falls through to the next suffix.
- */
-const createDerivedInstance = async (
- instanceModel: EnvironmentInstanceModel,
- workspaceKey: string,
- environment: { id: string; name: string },
-) => {
- for (let attempt = 1; attempt <= MAX_DERIVED_DIRECTORY_ATTEMPTS; attempt += 1) {
- const workingDirectory = derivedInstanceDirectory(environment.name, attempt);
-
- if (await instanceModel.findByWorkingDirectory(workingDirectory)) continue;
-
- const created = await instanceModel
- .create({
- ...sandboxBinding(workspaceKey),
- environmentId: environment.id,
- // The directory is the only thing that distinguishes this instance
- // from its siblings right now, so it is also the only honest label
- // until the person renames it.
- name: workingDirectory,
- workingDirectory,
- })
- .catch((error: unknown) => {
- // Someone else took this directory between the check and the
- // insert, or it nests with another instance's. Not a conflict the
- // caller can act on β€” try the next one.
- if (isDuplicateInstanceDirectory(error)) return undefined;
- if (error instanceof InstanceDirectoryOverlapError) return undefined;
- throw error;
- });
-
- if (!created) continue;
-
- // Nothing to clone and nothing to install means nothing will ever build
- // this instance, so it is ready as it is written. Left to the client's
- // follow-up build call, a tab closed in between would strand it in
- // `pending` β€” and a files environment offers no rebuild to get out of it.
- if (isBuildable(created.configurationSnapshot)) return created;
-
- await instanceModel.update(created.id, { status: 'ready' });
-
- return { ...created, status: 'ready' as const };
- }
-
- throw new TRPCError({ code: 'CONFLICT', message: 'DUPLICATE_INSTANCE_DIRECTORY' });
-};
-
-/**
- * Drop an instance's built state on the execution plane, ahead of its row.
- *
- * No snapshot there is the state this call exists to reach, so a 404 is this
- * step succeeding, not failing. An instance nothing has ever run in has
- * nothing on the execution plane β€” and treating that as an error strands the
- * row permanently, because the environment holding it cannot be deleted
- * either while an instance references it.
- */
-const deleteInstanceSnapshot = (client: SandboxStorageClient, id: string, topicId?: string) =>
- client.deleteInstance({ name: id, topicId }).catch((error: unknown) => {
- if (error instanceof SandboxStorageFilesError && error.status === 404) return;
-
- return mapStorageError(error);
- });
-
-/**
- * The directory a file route may touch, as a path relative to the workspace
- * root; `''` is the whole root.
- *
- * A workspace's root is shared by every member and holds every instance's
- * directory, so a path alone authorizes nothing: it is confined to one
- * instance, reached through the same rules as everywhere else. Reads follow
- * visibility β€” a published instance is readable by the members who run in it.
- * Writes stay with the instance's owner, as every other write to an instance
- * does. A conversation's own files are read through the instance its runs
- * resolve to, so a public agent's conversation is held to published ones.
- *
- * A personal account's root belongs to its owner alone, which is the one case
- * where no instance is needed.
- *
- * An instance's directory is never written through here: it is
- * the saved copy of the sandbox's work tree, written by the sandbox alone. A
- * write from outside would be overwritten by the next save, or leave the
- * directory disagreeing with the record the next restore reads it by.
- */
-const resolveFileRoot = async (
- ctx: {
- instanceModel: EnvironmentInstanceModel;
- serverDB: Parameters<typeof resolveSandboxSessionConfig>[0]['serverDB'];
- userId: string;
- workspaceId?: string | null;
- },
- { instanceId, topicId }: { instanceId?: string; topicId?: string },
- access: 'read' | 'write',
-): Promise<string> => {
- if (instanceId) {
- // Refused before the lookup: the answer is the same whether or not the
- // instance exists, so there is nothing to find out by asking.
- if (access === 'write') {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });
- }
- const instance = await ctx.instanceModel.findById(instanceId);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- return instance.workingDirectory;
- }
-
- if (!ctx.workspaceId) return '';
-
- if (access === 'read' && topicId) {
- const { cwd } = await resolveSandboxSessionConfig({
- isShareVisitorRun: false,
- serverDB: ctx.serverDB,
- topicId,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- if (cwd) return cwd;
- }
-
- throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_REQUIRED' });
-};
-
-/** Whether `path` is `root` itself or somewhere beneath it. */
-const isWithinRoot = (path: string, root: string) =>
- !root || path === root || path.startsWith(`${root}/`);
-
-const assertWithinRoot = (path: string, root: string) => {
- if (!isWithinRoot(path, root)) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });
- }
-};
-
-/** Names the instance a file route works in; see {@link resolveFileRoot}. */
-const instanceIdSchema = idSchema.optional();
-
-export const sandboxStorageRouter = router({
- createDirectory: instanceProcedure
- .input(
- z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),
- )
- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
- assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));
-
- return ctx.client.createDirectory(input).catch(mapStorageError);
- }),
-
- /**
- * Whether this caller has a persistent workspace at all. The client pairs it
- * with the lab flag it already holds: flag off renders nothing, flag on
- * without an entitlement renders the upgrade prompt, and both renders the
- * workspace.
- */
- getEntitlement: storageClaimProcedure.query(async ({ ctx }) => ({
- entitled: Boolean(ctx.claim),
- quotaBytes: ctx.claim?.quotaBytes ?? null,
- })),
-
- /**
- * Where this topic's commands will run, for the prompt that describes it.
- *
- * The browser assembles the system role on the client-executor path, and it
- * cannot resolve this itself: the placement follows an entitlement that is
- * signed server-side. Without it the prompt fell back to the disposable
- * wording β€” "files created here are temporary" β€” while the run had a
- * persistent directory, and the model worked in /tmp on the strength of what
- * it had been told.
- *
- * Returns the placement only. The claim stays on this side; a browser has no
- * use for an entitlement it cannot sign anything with, and every sandbox call
- * it makes is routed through a server that resolves the claim again.
- */
- resolveSessionPlacement: storageClaimProcedure
- .input(z.object({ topicId: z.string().optional() }))
- .query(async ({ ctx, input }) => {
- const { claim, cwd, mode, workingDir } = await resolveSandboxSessionConfig({
- isShareVisitorRun: false,
- serverDB: ctx.serverDB,
- topicId: input.topicId,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId ?? undefined,
- });
-
- return claim ? { cwd, mode, workingDir } : null;
- }),
-
- /**
- * Fork an instance: a second directory that starts with everything the
- * first one had installed. The point of copying rather than creating is to
- * skip the rebuild β€” the specification alone would give an empty directory
- * and a fresh bootstrap.
- */
- copyInstance: instanceProcedure
- .input(
- z.object({
- id: idSchema,
- name: nameSchema,
- workingDirectory: relativePathSchema,
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const source = await ctx.instanceModel.findOwnedById(input.id);
- if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- // A held instance is mid-write, so a copy would capture a tree halfway
- // through a change. The execution plane refuses it too; asking first
- // keeps the refusal ahead of the row insert and gives it the same code
- // the rest of the client already turns into a sentence. A lease store
- // that did not answer is not read as "free" β€” here that means refusing,
- // because unlike a rebuild there is no runtime lease standing behind a
- // copy to catch the second writer.
- const occupancy = await ctx.client
- .readOccupancy({ names: [source.id] })
- .catch(() => ({ held: [], unavailable: true }));
- if (occupancy.unavailable || occupancy.held.some((entry) => entry.id === source.id)) {
- throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });
- }
-
- // Row first: a copy whose snapshot succeeded but whose row is missing
- // would be captured state nobody can name, and therefore nobody can
- // delete. The reverse β€” a row whose snapshot never arrived β€” is the same
- // state as a brand-new instance, which the UI already handles.
- const created = await ctx.instanceModel
- .create({
- ...sandboxBinding(ctx.claim.key),
- // The copy's files are the source's, so its definition is too. Left
- // to default, it would snapshot whatever the environment says now
- // and describe a checkout the copied tree does not contain.
- configurationSnapshot: source.configurationSnapshot,
- environmentId: source.environmentId,
- name: input.name,
- workingDirectory: input.workingDirectory,
- })
- .catch(rethrowDuplicateInstanceDirectory);
-
- if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- await ctx.client
- .copyInstance({
- from: source.id,
- // The copy's own folder. Sharing the source's would let either
- // instance's next save delete files the other still lists.
- instanceDir: created.workingDirectory,
- to: created.id,
- })
- .catch(async (error) => {
- await ctx.instanceModel.delete(created.id);
- return mapStorageError(error);
- });
-
- // A copy starts life with everything the source had built, so it is
- // ready by arrival β€” there is nothing to clone and nothing to install.
- // Left at the insert's default it would sit in `pending` with no build
- // to wait for, which reads as "never built" and offers a rebuild that
- // would throw the copy away.
- await ctx.instanceModel.update(created.id, { status: 'ready' });
-
- return { ...created, status: 'ready' as const };
- }),
-
- /**
- * A new instance of an environment, with its directory derived rather than
- * asked for.
- *
- * The person picked an environment, not a folder. Under the agreed split the
- * checkout and its installed packages live on local disk and travel in the
- * snapshot, so this directory holds the outputs worth keeping β€” which is
- * rarely something anyone has an opinion about before the work exists. Asking
- * would make them invent an answer to start a conversation.
- */
- createInstanceForEnvironment: instanceProcedure
- .input(z.object({ environmentId: idSchema }))
- .mutation(async ({ ctx, input }) => {
- // Owner-scoped: an environment a colleague published is one you can run
- // in, not one you can add copies to.
- const environment = await ctx.environmentModel.findOwnedById(input.environmentId);
- if (!environment)
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- return createDerivedInstance(ctx.instanceModel, ctx.claim.key, environment);
- }),
-
- /**
- * An instance of an environment: its own directory, its own captured
- * state. Created empty β€” nothing is built until a conversation runs in it.
- */
- createInstance: instanceProcedure
- .input(
- z.object({
- environmentId: idSchema,
- name: nameSchema,
- workingDirectory: relativePathSchema,
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const created = await ctx.instanceModel
- .create({
- ...sandboxBinding(ctx.claim.key),
- environmentId: input.environmentId,
- name: input.name,
- workingDirectory: input.workingDirectory,
- })
- .catch(rethrowDuplicateInstanceDirectory);
-
- if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- return created;
- }),
-
- /**
- * Materialize an instance: clone the environment's sources and run its
- * bootstrap, into the instance's own stored generation.
- *
- * Its own mutation rather than part of `createInstance`, because starting a
- * build attaches a sandbox session and that is a cold start β€” seconds, with
- * a dialog open in front of it. The dialog closes on the insert; the list
- * shows the instance as pending and this is what the client fires next.
- *
- * Returns as soon as the build has started: a bootstrap running an install
- * is minutes long, and `instanceBuildStatus` is what follows it.
- */
- startInstanceBuild: instanceProcedure
- .input(z.object({ id: idSchema, topicId: topicIdSchema }))
- .mutation(async ({ ctx, input }) => {
- const instance = await ctx.instanceModel.findOwnedById(input.id);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- // The definition this instance was created from, not the environment's
- // current one: a build has to produce what the instance says it is, and
- // the two differ exactly when the environment moved on.
- const specification = instance.configurationSnapshot;
- const buildable = isBuildable(specification);
-
- // An environment that clones nothing and installs nothing is already
- // everything it is ever going to be. Building it would cold-start a
- // sandbox to do nothing and leave an empty archive behind.
- if (!buildable) {
- await ctx.instanceModel.update(input.id, { status: 'ready' });
-
- return { buildId: null };
- }
-
- // A rebuild replaces the folder a conversation may be writing in right
- // now, so a held instance is refused before the row changes at all. A
- // lease store that did not answer is not read as "free" β€” the runtime's
- // own lease still stands behind this and refuses a second writer.
- const occupancy = await ctx.client
- .readOccupancy({ names: [input.id], topicId: input.topicId })
- .catch(() => ({ held: [], unavailable: true }));
- if (occupancy.held.some((entry) => entry.id === input.id)) {
- throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });
- }
-
- // What to fall back to if the build never starts. An instance that was
- // ready still has everything its last build published β€” a refused start
- // takes none of it away, so it must not come back reading "failed".
- const previousStatus = instance.status;
-
- await ctx.instanceModel.update(input.id, { buildError: null, status: 'pending' });
-
- // Preferred over the execution plane's own GitHub connection, which it
- // falls back to when this answers null: an App installation is granted
- // one repository at a time by whoever administers the account, and the
- // token minted from it is narrower still β€” this repository, read-only,
- // expiring within the hour. It is resolved here because the App's
- // private key lives on this side; the execution plane is handed the
- // result and never the inputs, the same way it is handed the workspace
- // claim.
- const credential = await resolveScmCloneCredential({
- configuration: specification,
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
-
- try {
- const { buildId } = await ctx.client.buildInstance({
- credentials: credential ? [credential] : undefined,
- // Where the checkout lands on the volume: the instance's own folder,
- // which is what its file browser opens.
- instanceDir: instance.workingDirectory,
- name: input.id,
- // Without the product's own fields: the execution plane digests
- // what it is sent, and an instance created before `kind` existed
- // must keep matching the build it already has.
- specification: toExecutionConfiguration(specification),
- topicId: input.topicId,
- });
- await ctx.instanceModel.update(input.id, { buildId });
-
- return { buildId };
- } catch (error) {
- // Recorded on the row rather than only thrown: the client that asked
- // may already be gone, and an instance left saying "pending" forever
- // is the one state nothing recovers from.
- await ctx.instanceModel.update(
- input.id,
- previousStatus === 'ready'
- ? { status: 'ready' }
- : {
- buildError: (error as Error)?.message || 'Could not start the build',
- status: 'error',
- },
- );
- throw error;
- }
- }),
-
- /**
- * Follow a build, and settle the instance once it ends.
- *
- * A query that writes, deliberately: the runtime is the only thing that
- * knows a build finished, nothing calls back, and the row has to end up
- * right whether or not anyone is still watching. Polling it is what moves
- * the instance out of `pending`.
- */
- instanceBuildStatus: instanceProcedure
- .input(
- z.object({
- id: idSchema,
- /** Resume the log from here; the reply says where to go next. */
- logOffset: z.number().int().min(0).optional(),
- topicId: topicIdSchema,
- }),
- )
- .query(async ({ ctx, input }) => {
- const instance = await ctx.instanceModel.findById(input.id);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- if (!instance.buildId) {
- return {
- chunk: '',
- logOffset: input.logOffset ?? 0,
- state: instance.status === 'error' ? ('failed' as const) : ('idle' as const),
- };
- }
-
- const status = await ctx.client
- .buildStatus({
- buildId: instance.buildId,
- logOffset: input.logOffset,
- name: input.id,
- topicId: input.topicId,
- })
- .catch(mapStorageError);
-
- if (status.state !== 'running') {
- // The id is cleared with the verdict: the runtime drops a finished
- // build's log on its own schedule, and an id that outlives it has the
- // UI polling for a log that will never come back. Written through the
- // visibility-scoped recorder, because the poll that happens to receive
- // the terminal status can be a viewer's rather than the owner's.
- await ctx.instanceModel.recordBuildResult(input.id, instance.buildId, {
- buildError:
- status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,
- status: status.state === 'succeeded' ? 'ready' : 'error',
- });
- }
-
- return { chunk: status.chunk, logOffset: status.logOffset, state: status.state };
- }),
-
- /**
- * An environment, together with its default instance.
- *
- * The person creating an environment has not started any work yet, so there
- * is nothing to ask them about where it should happen: the instance is
- * created here, with the same derived directory a new copy gets, and every
- * creation path ends with one. It is returned unbuilt β€” building it
- * cold-starts a sandbox, so the client fires `startInstanceBuild` next, the
- * same split as for any other new instance.
- *
- * Both rows are written in one transaction, so a failure to create the
- * instance leaves no environment behind either: the caller sees the failure
- * and retries, instead of holding an environment that silently skipped the
- * step.
- *
- * Asked for, not assumed. A client from before this follows the call with
- * its own create-instance dialog, and an instance made here as well would
- * leave it with two β€” the unasked one being the default, which cannot be
- * removed on its own. Such a client gets the environment alone, as it always
- * did, and its first instance becomes the default.
- */
- createEnvironment: instanceProcedure
- .input(
- z.object({
- configuration: configurationSchema.optional(),
- description: z.string().max(2000).optional(),
- name: nameSchema,
- visibility: visibilitySchema.optional(),
- withDefaultInstance: z.boolean().optional(),
- }),
- )
- .mutation(async ({ ctx, input: { withDefaultInstance, ...input } }) =>
- inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {
- const environment = await environmentModel
- .create(input)
- .catch(rethrowDuplicateEnvironmentName);
- if (!withDefaultInstance) return { ...environment, defaultInstance: undefined };
-
- const defaultInstance = await createDerivedInstance(
- instanceModel,
- ctx.claim.key,
- environment,
- );
-
- return { ...environment, defaultInstance };
- }),
- ),
-
- /**
- * One instance, from the database alone. Separate from `listInstances`
- * because the composer only needs to know where the conversation is pointed,
- * and `listInstances` pays a sandbox cold start to answer how big everything
- * is β€” seconds, for a label.
- */
- getInstance: instanceProcedure
- .input(z.object({ id: idSchema }))
- .query(async ({ ctx, input }) => (await ctx.instanceModel.findById(input.id)) ?? null),
-
- getStorage: entitledProcedure.query(async ({ ctx }) =>
- ctx.client.getStorage().catch(mapStorageError),
- ),
-
- /**
- * Re-measure the workspace and answer with the fresh figure.
- *
- * A mutation rather than a query because it writes: it walks the volume and
- * stamps the workspace as active. Kept off page load for that reason β€” the
- * settings page reads the stored number and offers this on its refresh
- * button, so a page nobody asked to refresh cannot keep an idle workspace
- * looking busy.
- */
- refreshStorageUsage: entitledProcedure.mutation(async ({ ctx }) =>
- ctx.client.refreshUsage().catch(mapStorageError),
- ),
-
- /** Specifications only. Nothing here needs a sandbox session to answer. */
- listEnvironments: environmentProcedure
- .input(z.object({ visibility: visibilitySchema.optional() }).optional())
- .query(async ({ ctx, input }) => ({
- environments: await ctx.environmentModel.query(input?.visibility),
- })),
-
- /**
- * Instances, each joined with the state the execution plane actually
- * holds for it. An instance that was created but never used has no snapshot
- * yet, which is a normal state and not an error.
- */
- listInstances: instanceProcedure
- .input(
- z.object({
- environmentId: idSchema.optional(),
- topicId: topicIdSchema,
- /**
- * Sizes come from the snapshot store, which is reachable only through a
- * sandbox session and pays a cold start to answer. A settings page is
- * worth that wait; a picker in the composer is not, and asks for names
- * alone.
- */
- withSizes: z.boolean().default(true),
- }),
- )
- .query(async ({ ctx, input }) => {
- const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });
-
- const [snapshots, occupancy] = await Promise.all([
- input.withSizes
- ? ctx.client
- .listInstances({ topicId: input.topicId })
- .then((result) => result.instances)
- // If the store fails, the instances still exist and can still be
- // renamed or selected β€” only their sizes are unknown, so say so
- // rather than failing a settings page.
- .catch(() => null)
- : [],
- // Always, and separately from the sizes: this is a Redis read on the
- // control plane, so it costs the same on every deployment, whereas the
- // listing above opens the volume. An instance held by another
- // conversation cannot be run in β€” the lease answers the second writer
- // with a 409 β€” so a picker that does not know is a picker that offers
- // a choice the first message will refuse.
- instances.length > 0
- ? ctx.client
- .readOccupancy({
- names: instances.map((instance) => instance.id),
- topicId: input.topicId,
- })
- // Same rule the lease store itself follows: a failure is "not
- // known", never "free".
- .catch(() => ({ held: [], unavailable: true }))
- : { held: [], unavailable: false },
- ]);
-
- // A build is polled by whoever has the Instances tab open, and nobody
- // has it open most of the time β€” switch tabs mid-build and the verdict
- // never lands, leaving the row `pending` against a build the runtime
- // has since discarded and an instance the composer will not offer. So
- // every listing settles the builds it finds already finished. Bounded
- // by how many instances can be building at once, and never fatal: an
- // unreachable execution plane just leaves the row as it was.
- const settled = await pMap(
- instances.filter((instance) => instance.buildId),
- async (instance) => {
- const status = await ctx.client
- .buildStatus({ buildId: instance.buildId!, name: instance.id, topicId: input.topicId })
- .catch(() => null);
- if (!status || status.state === 'running') return null;
-
- const next = {
- buildError:
- status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,
- status: status.state === 'succeeded' ? ('ready' as const) : ('error' as const),
- };
- await ctx.instanceModel
- .recordBuildResult(instance.id, instance.buildId!, next)
- .catch(() => undefined);
-
- return [instance.id, next] as const;
- },
- { concurrency: 5 },
- );
- const settledById = new Map(settled.filter((entry) => !!entry));
-
- const byId = new Map((snapshots ?? []).map((snapshot) => [snapshot.id, snapshot]));
- const heldBy = new Map(occupancy.held.map((entry) => [entry.id, entry.own]));
-
- return {
- instances: instances.map((instance) => ({
- /** Set only while a build is worth polling; cleared with its verdict. */
- buildId: settledById.has(instance.id) ? null : instance.buildId,
- // From the definition the instance was made from, which is what a
- // build uses β€” the environment may have moved on since.
- buildable: isBuildable(instance.configurationSnapshot),
- buildError: settledById.get(instance.id)?.buildError ?? instance.buildError,
- createdAt: instance.createdAt,
- environmentId: instance.environmentId,
- id: instance.id,
- // Held by a running sandbox, and by whom. `own` is this topic's own
- // run, which its own picker must keep offering; anything else is
- // another conversation and is what a picker refuses.
- inUse: heldBy.has(instance.id),
- inUseByThisTopic: heldBy.get(instance.id) === true,
- name: instance.name,
- snapshot: byId.get(instance.id) ?? null,
- status: settledById.get(instance.id)?.status ?? instance.status,
- workingDirectory: instance.workingDirectory,
- })),
- occupancyUnavailable: occupancy.unavailable,
- snapshotsUnavailable: snapshots === null,
- };
- }),
-
- /**
- * The run history of every instance of one environment, newest first.
- *
- * The execution plane keys its trail by instance β€” that is the name the
- * snapshot is stored under β€” while the panel shows one environment, so this
- * is the union of the instances' histories with the instance named on each
- * row. Read from the control plane's own records: unlike `listInstances`
- * it starts no sandbox and pays no cold start.
- *
- * Topic titles are looked up for the caller's own topics; a run another
- * member started in a published environment keeps its id only.
- */
- listInstanceSessions: instanceProcedure
- .input(
- z.object({
- environmentId: idSchema,
- /** Per instance, not in total: each instance's page is fetched on its own. */
- limit: z.number().int().min(1).max(100).default(20),
- }),
- )
- .query(async ({ ctx, input }) => {
- const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });
- if (instances.length === 0) return { sessions: [], unavailable: false };
-
- // Bounded: an environment's instance count is whatever the member made,
- // and one request per instance all at once would put that number on the
- // execution plane in a single burst.
- const pages = await pMap(
- instances,
- (instance) =>
- ctx.client
- .listEnvironmentSessions({ limit: input.limit, name: instance.id })
- // One instance's history failing must not blank the others; the
- // caller is told the list is incomplete rather than shown "no runs".
- .catch(() => null),
- { concurrency: 5 },
- );
-
- const merged = instances
- .flatMap((instance, index) =>
- (pages[index]?.sessions ?? []).map((session) => ({
- ...session,
- instanceId: instance.id,
- instanceName: instance.name,
- })),
- )
- .sort((a, b) => b.startedAt.localeCompare(a.startedAt));
-
- const topicIds = [
- ...new Set(
- merged
- .map((session) => session.topicId)
- .filter((id): id is string => !!id && id !== MANAGEMENT_TOPIC_ID),
- ),
- ];
- // Read in the workspace's scope β€” the personal scope matches no
- // workspace topic at all β€” and then narrowed to the caller's own, since
- // a workspace scope also reaches what other members may see.
- const topics =
- topicIds.length > 0
- ? await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)
- .findByIds(topicIds)
- .catch(() => [])
- : [];
- // Where the conversation lives, as well as what it is called: a topic is
- // addressed as `group/<groupId>/<topicId>` when it belongs to a group and
- // `agent/<agentId>/<topicId>` otherwise, so a link built from the topic
- // alone cannot resolve and the panel's one way back into the run is a 404.
- // A group topic carries BOTH ids, which is why the group one is returned
- // rather than inferred from the absence of an agent.
- const topicInfo = new Map(
- topics
- .filter((topic) => topic.userId === ctx.userId)
- .map((topic) => [
- topic.id,
- { agentId: topic.agentId, groupId: topic.groupId, title: topic.title },
- ]),
- );
-
- return {
- sessions: merged.map((session) => {
- const info = session.topicId ? topicInfo.get(session.topicId) : undefined;
-
- return {
- ...session,
- topicAgentId: info?.agentId ?? null,
- topicGroupId: info?.groupId ?? null,
- topicTitle: info?.title || null,
- };
- }),
- unavailable: pages.includes(null),
- };
- }),
-
- listFiles: instanceProcedure
- .input(
- z.object({
- instanceId: instanceIdSchema,
- path: relativePathSchema.optional(),
- recursive: z.boolean().optional(),
- topicId: topicIdSchema,
- }),
- )
- .query(async ({ ctx, input: { instanceId, ...input } }) => {
- const root = await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read');
- // No path means "the top of what may be listed", which inside a
- // workspace is the instance's directory, not the shared root.
- const path = input.path ?? (root || undefined);
- if (path !== undefined) assertWithinRoot(path, root);
-
- return ctx.client.listFiles({ ...input, path }).catch(mapStorageError);
- }),
-
- readFile: instanceProcedure
- .input(
- z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),
- )
- .query(async ({ ctx, input: { instanceId, ...input } }) => {
- assertWithinRoot(
- input.path,
- await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read'),
- );
-
- return ctx.client.readFile(input).catch(mapStorageError);
- }),
-
- /**
- * Write a file's whole contents, creating it and its parents if needed.
- *
- * Text only, because the execution plane's endpoint carries the body as a
- * JSON string with no encoding field. The cap is this layer's own: the
- * endpoint declares none, and an unbounded string arrives in memory on both
- * sides before anything touches a disk.
- */
- writeFile: instanceProcedure
- .input(
- z.object({
- content: fileContentSchema,
- instanceId: instanceIdSchema,
- path: relativePathSchema,
- topicId: topicIdSchema,
- }),
- )
- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
- assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));
-
- return ctx.client.writeFile(input).catch(mapStorageError);
- }),
-
- /**
- * Refused while copies other than the default still reference it β€” those go
- * first.
- *
- * The default instance goes with the environment: it cannot be removed on
- * its own, so for an environment with only that one left, deleting the
- * environment is how it is deleted.
- *
- * Both rows go in one transaction, and the snapshot is dropped last, inside
- * it. Anything that refuses β€” a project still bound to the environment, an
- * instance created meanwhile, a run still holding the snapshot β€” rolls the
- * rows back with the snapshot untouched, so a refused delete costs nothing.
- * The one gap left is a commit that fails after the snapshot is gone, which
- * leaves rows with nothing built behind them. What was lost is what this
- * call was asked to delete, and the call reports its failure, so deleting
- * again finishes the job. The other order is the one with no way back: rows
- * gone and a snapshot nobody can see, name, or reclaim.
- */
- removeEnvironment: instanceProcedure
- .input(z.object({ id: idSchema }))
- .mutation(async ({ ctx, input }) => {
- // Ownership before anything reaches the execution plane: a member who
- // can see a published environment must not get its snapshot deleted on
- // the way to being refused the row.
- const environment = await ctx.environmentModel.findOwnedById(input.id);
- if (!environment)
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- const instances = await ctx.instanceModel.query({ environmentId: environment.id });
- if (instances.length > 1) {
- throw new TRPCError({ code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });
- }
-
- const [onlyInstance] = instances;
- // Only a sandbox instance has a snapshot this router can drop; any other
- // kind keeps referencing the environment and the delete below says so.
- const defaultInstance = onlyInstance?.kind === 'sandbox' ? onlyInstance : undefined;
-
- return inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {
- if (defaultInstance) {
- await instanceModel.delete(defaultInstance.id).catch(rethrowEnvironmentInUse);
- }
-
- const removed = await environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);
- if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- if (defaultInstance) await deleteInstanceSnapshot(ctx.client, defaultInstance.id);
-
- return removed;
- });
- }),
-
- /**
- * Remove one copy of an environment. The default instance is refused: it is
- * what the environment is, so it goes when the environment does, and a
- * broken one is rebuilt rather than deleted.
- */
- removeInstance: instanceProcedure
- .input(z.object({ id: idSchema, topicId: topicIdSchema }))
- .mutation(async ({ ctx, input }) => {
- const instance = await ctx.instanceModel.findOwnedById(input.id);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- const siblings = await ctx.instanceModel.query({ environmentId: instance.environmentId });
- if (isDefaultInstance(instance, siblings)) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'DEFAULT_INSTANCE' });
- }
-
- // Snapshot first, and only drop the row once it is gone: a row removed
- // while the snapshot survives leaves storage nobody can see, name, or
- // reclaim. The execution plane refuses while a session is using it, and
- // that refusal is the one the user needs to see.
- await deleteInstanceSnapshot(ctx.client, instance.id, input.topicId);
-
- return ctx.instanceModel.delete(input.id);
- }),
-
- /**
- * End the run holding an instance, so it can be picked, rebuilt or deleted
- * now instead of after the idle sweep.
- *
- * The owner's, like a rebuild or a delete: in a published environment the
- * run holding the instance is usually a colleague's conversation, and
- * cutting it off is not something reading access should allow. The
- * execution plane does the stop properly β€” snapshot first, lease released
- * only once the stop is confirmed β€” and its refusals (still saving, still
- * starting, being built) travel as codes the client turns into sentences.
- */
- stopInstance: instanceProcedure
- .input(z.object({ id: idSchema }))
- .mutation(async ({ ctx, input }) => {
- const instance = await ctx.instanceModel.findOwnedById(input.id);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- return ctx.client.stopInstance({ name: instance.id }).catch(mapStorageError);
- }),
-
- /**
- * Every repository this account can build an environment from, newest
- * activity first, each carrying the owner it belongs to so the caller can
- * group them without a second request per organization.
- *
- * A missing GitHub connection is NOT an error here: it is the state the
- * picker exists to resolve, so it answers `connected: false` and lets the
- * UI offer the connection instead of a failure.
- */
- /**
- * The branches of one repository, so the environment's checkout target is
- * picked from what exists rather than typed. Same shape as the repository
- * listing: no connection is not an error, it is `connected: false`.
- */
- listGithubBranches: entitledProcedure
- .input(z.object({ owner: z.string().min(1).max(255), repository: z.string().min(1).max(255) }))
- .query(async ({ ctx, input }) => {
- const service = new ConnectorDataService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- try {
- const client = await service.getGitHubClient();
- const branches = await client.listRepositoryBranches(input.owner, input.repository);
-
- return {
- branches,
- connected: true,
- // At the ceiling the list may be missing branches, and a picker
- // that only offers what it was given would make those unselectable.
- truncated: branches.length >= MAX_REPOSITORY_BRANCHES,
- };
- } catch (error) {
- if (isGithubUnavailable(error)) return { branches: [], connected: false, truncated: false };
-
- throw error;
- }
- }),
-
- listGithubRepositories: entitledProcedure.query(async ({ ctx }) => {
- const service = new ConnectorDataService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- try {
- const client = await service.getGitHubClient();
-
- return { connected: true, repositories: await client.listAccessibleRepositories() };
- } catch (error) {
- if (isGithubUnavailable(error)) return { connected: false, repositories: [] };
-
- throw error;
- }
- }),
-
- removeFile: instanceProcedure
- .input(
- z.object({
- instanceId: instanceIdSchema,
- path: relativePathSchema,
- recursive: z.boolean().optional(),
- topicId: topicIdSchema,
- }),
- )
- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
- const root = await resolveFileRoot(ctx, { instanceId }, 'write');
- assertWithinRoot(input.path, root);
- // The instance's own directory is its identity, not a file in it:
- // removing it would orphan the row and the snapshot that name it.
- if (root && input.path === root) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });
- }
-
- return ctx.client.deleteFile(input).catch(mapStorageError);
- }),
-
- /**
- * Edits the specification. Existing instances keep the one they were created
- * with β€” a change here shapes what the NEXT instance is built from and
- * touches nothing a conversation has already installed or produced.
- */
- updateEnvironment: environmentProcedure
- .input(
- z.object({
- configuration: configurationSchema.optional(),
- description: z.string().max(2000).optional(),
- id: idSchema,
- name: nameSchema.optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const { id, ...changes } = input;
- const updated = await ctx.environmentModel
- .update(id, changes)
- .catch(rethrowDuplicateEnvironmentName);
- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- return updated;
- }),
-
- /**
- * Only the label. The directory does not move: the built state sits in it,
- * and the execution plane has no rename that carries one to the other.
- */
- /**
- * Publishing an environment to the workspace, or taking it back.
- *
- * Its own mutation rather than a field on `updateEnvironment`, because the
- * two are not the same kind of edit: renaming is between you and your own
- * row, while this one decides who else can run in what this environment
- * built β€” and the client asks for confirmation before sending it.
- */
- setEnvironmentVisibility: environmentProcedure
- .input(z.object({ id: idSchema, visibility: visibilitySchema }))
- .mutation(async ({ ctx, input }) => {
- const updated = await ctx.environmentModel.setVisibility(input.id, input.visibility);
- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
-
- return updated;
- }),
-
- renameInstance: instanceProcedure
- .input(z.object({ id: idSchema, name: nameSchema }))
- .mutation(async ({ ctx, input }) => {
- const { id, ...changes } = input;
- const updated = await ctx.instanceModel.update(id, changes);
- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- return updated;
- }),
-});
-
-export type SandboxStorageRouter = typeof sandboxStorageRouter;
diff --git a/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts
new file mode 100644
index 00000000000..819cba3f454
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts
@@ -0,0 +1,85 @@
+import { TRPCError } from '@trpc/server';
+
+import { InstanceDirectoryOverlapError } from '@/database/models/environmentInstance';
+
+/** The indexes that make a name identify one environment for one member. */
+const ENVIRONMENT_NAME_CONSTRAINTS = new Set([
+ 'environments_user_name_unique',
+ 'environments_workspace_user_name_unique',
+]);
+
+/** The index that keeps two instances out of the same directory. */
+const INSTANCE_DIRECTORY_CONSTRAINT = 'environment_instances_provider_path_unique';
+
+/** Postgres surfaces the driver error somewhere down the `cause` chain. */
+const getPostgresErrorField = (error: unknown, field: string): string | undefined => {
+ let current: unknown = error;
+
+ while (current && typeof current === 'object') {
+ const value = (current as Record<string, unknown>)[field];
+ if (typeof value === 'string') return value;
+
+ current = (current as { cause?: unknown }).cause;
+ }
+};
+
+/**
+ * The name is the one thing the person chose, and a collision is fixed by
+ * typing a different one β€” so it has to arrive as CONFLICT next to the field,
+ * not as the generic failure a raw driver error would produce. A code rather
+ * than prose because this one is shown inline and has to be translated.
+ */
+export const rethrowDuplicateEnvironmentName = (error: unknown): never => {
+ if (
+ getPostgresErrorField(error, 'code') === '23505' &&
+ ENVIRONMENT_NAME_CONSTRAINTS.has(getPostgresErrorField(error, 'constraint') ?? '')
+ ) {
+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'DUPLICATE_ENVIRONMENT_NAME' });
+ }
+
+ throw error;
+};
+
+/**
+ * Two instances in one directory would restore two package sets over each
+ * other's files, so the database refuses it and the person picks another
+ * directory. Same reasoning as a duplicate name, different fix.
+ */
+export const isDuplicateInstanceDirectory = (error: unknown): boolean =>
+ getPostgresErrorField(error, 'code') === '23505' &&
+ getPostgresErrorField(error, 'constraint') === INSTANCE_DIRECTORY_CONSTRAINT;
+
+export const rethrowDuplicateInstanceDirectory = (error: unknown): never => {
+ // The same fix for the person β€” pick another folder β€” but a different
+ // sentence, since the folder itself is not taken.
+ if (error instanceof InstanceDirectoryOverlapError) {
+ throw new TRPCError({
+ cause: error,
+ code: 'CONFLICT',
+ message: 'OVERLAPPING_INSTANCE_DIRECTORY',
+ });
+ }
+
+ if (isDuplicateInstanceDirectory(error)) {
+ throw new TRPCError({
+ cause: error,
+ code: 'CONFLICT',
+ message: 'DUPLICATE_INSTANCE_DIRECTORY',
+ });
+ }
+
+ throw error;
+};
+
+/**
+ * An environment with instances still on it. The reference is `restrict`
+ * on purpose β€” deleting the specification out from under them would leave
+ * directories and captured state nothing describes.
+ */
+export const rethrowEnvironmentInUse = (error: unknown): never => {
+ if (getPostgresErrorField(error, 'code') === '23503') {
+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });
+ }
+
+ throw error;
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/environments.ts b/apps/server/src/routers/lambda/sandboxStorage/environments.ts
new file mode 100644
index 00000000000..f5768d61aa3
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/environments.ts
@@ -0,0 +1,238 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { rethrowDuplicateEnvironmentName, rethrowEnvironmentInUse } from './constraintErrors';
+import {
+ createDerivedInstance,
+ deleteInstanceSnapshot,
+ inEnvironmentTransaction,
+} from './instanceOperations';
+import { environmentProcedure, instanceProcedure } from './procedures';
+import { idSchema, nameSchema, relativePathSchema, visibilitySchema } from './schemas';
+
+/**
+ * The hosts a checkout may name.
+ *
+ * An allowlist rather than an SSRF check on the resolved address, because the
+ * clone does not happen here: the stored specification is handed to the
+ * execution plane, which resolves and fetches it from its own network, so no
+ * validation at this layer can speak for what that resolution will return.
+ * Naming the hosts is the part this layer can be sure of β€” and every producer
+ * already names exactly one, since a source is chosen through the GitHub
+ * repository picker and the UI parses the URL back assuming that host.
+ */
+const ALLOWED_SOURCE_HOSTS = new Set(['github.com', 'www.github.com']);
+
+/**
+ * Where source material comes from. Only `git` for now, and only over HTTPS:
+ * the other transports authenticate with a key, and a specification that
+ * carries no credentials cannot present one. Private repositories are a
+ * separate problem, not a URL scheme.
+ *
+ * The host is checked because this schema guards an RPC, not the picker: an
+ * entitled caller reaching it directly could otherwise store any URL, and the
+ * build would then make the execution plane fetch it β€” an internal address
+ * included.
+ */
+const environmentSourceSchema = z.object({
+ kind: z.literal('git'),
+ /** Where the checkout lands, relative to the instance's own directory. */
+ path: relativePathSchema.optional(),
+ ref: z.string().trim().min(1).max(255).optional(),
+ url: z
+ .string()
+ .url()
+ .refine(
+ (value) => {
+ let parsed;
+ try {
+ parsed = new URL(value);
+ } catch {
+ return false;
+ }
+
+ return parsed.protocol === 'https:' && ALLOWED_SOURCE_HOSTS.has(parsed.hostname);
+ },
+ { message: 'Only https:// github.com git URLs are supported' },
+ ),
+});
+
+/**
+ * Non-secret values only. Enforced by shape as far as a shape can: the name has
+ * to look like an environment variable, and the rest is said plainly in the UI
+ * and in the type. A field that stores what the user types cannot tell a region
+ * from a token, which is why secrets are resolved at use time instead.
+ */
+const environmentEnvSchema = z.record(
+ z
+ .string()
+ .max(128)
+ .regex(/^[A-Z_]\w*$/i, 'Must be a valid environment variable name'),
+ z.string().max(4096),
+);
+
+const configurationSchema = z.object({
+ bootstrapCommand: z.string().max(8000).optional(),
+ env: environmentEnvSchema.optional(),
+ excludePaths: z.array(relativePathSchema).max(64).optional(),
+ internetAccess: z.boolean().optional(),
+ // Which form the product shows. Accepted here so it is stored rather than
+ // stripped by the parse; it never travels on to the execution plane.
+ kind: z.enum(['files', 'code']).optional(),
+ maintenanceCommand: z.string().max(8000).optional(),
+ // One repository per environment. The wire format stays a list because the
+ // execution plane checks out an array of sources, but an environment that
+ // builds from two repositories has no single working directory to hand a
+ // conversation β€” and the picker that fills this offers exactly one.
+ sources: z.array(environmentSourceSchema).max(1).optional(),
+});
+
+export const environmentsProcedures = {
+ /**
+ * An environment, together with its default instance.
+ *
+ * The person creating an environment has not started any work yet, so there
+ * is nothing to ask them about where it should happen: the instance is
+ * created here, with the same derived directory a new copy gets, and every
+ * creation path ends with one. It is returned unbuilt β€” building it
+ * cold-starts a sandbox, so the client fires `startInstanceBuild` next, the
+ * same split as for any other new instance.
+ *
+ * Both rows are written in one transaction, so a failure to create the
+ * instance leaves no environment behind either: the caller sees the failure
+ * and retries, instead of holding an environment that silently skipped the
+ * step.
+ *
+ * Asked for, not assumed. A client from before this follows the call with
+ * its own create-instance dialog, and an instance made here as well would
+ * leave it with two β€” the unasked one being the default, which cannot be
+ * removed on its own. Such a client gets the environment alone, as it always
+ * did, and its first instance becomes the default.
+ */
+ createEnvironment: instanceProcedure
+ .input(
+ z.object({
+ configuration: configurationSchema.optional(),
+ description: z.string().max(2000).optional(),
+ name: nameSchema,
+ visibility: visibilitySchema.optional(),
+ withDefaultInstance: z.boolean().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { withDefaultInstance, ...input } }) =>
+ inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {
+ const environment = await environmentModel
+ .create(input)
+ .catch(rethrowDuplicateEnvironmentName);
+ if (!withDefaultInstance) return { ...environment, defaultInstance: undefined };
+
+ const defaultInstance = await createDerivedInstance(
+ instanceModel,
+ ctx.claim.key,
+ environment,
+ );
+
+ return { ...environment, defaultInstance };
+ }),
+ ),
+ /** Specifications only. Nothing here needs a sandbox session to answer. */
+ listEnvironments: environmentProcedure
+ .input(z.object({ visibility: visibilitySchema.optional() }).optional())
+ .query(async ({ ctx, input }) => ({
+ environments: await ctx.environmentModel.query(input?.visibility),
+ })),
+ /**
+ * Edits the specification. Existing instances keep the one they were created
+ * with β€” a change here shapes what the NEXT instance is built from and
+ * touches nothing a conversation has already installed or produced.
+ */
+ updateEnvironment: environmentProcedure
+ .input(
+ z.object({
+ configuration: configurationSchema.optional(),
+ description: z.string().max(2000).optional(),
+ id: idSchema,
+ name: nameSchema.optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { id, ...changes } = input;
+ const updated = await ctx.environmentModel
+ .update(id, changes)
+ .catch(rethrowDuplicateEnvironmentName);
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ return updated;
+ }),
+ /**
+ * Only the label. The directory does not move: the built state sits in it,
+ * and the execution plane has no rename that carries one to the other.
+ */
+ /**
+ * Publishing an environment to the workspace, or taking it back.
+ *
+ * Its own mutation rather than a field on `updateEnvironment`, because the
+ * two are not the same kind of edit: renaming is between you and your own
+ * row, while this one decides who else can run in what this environment
+ * built β€” and the client asks for confirmation before sending it.
+ */
+ setEnvironmentVisibility: environmentProcedure
+ .input(z.object({ id: idSchema, visibility: visibilitySchema }))
+ .mutation(async ({ ctx, input }) => {
+ const updated = await ctx.environmentModel.setVisibility(input.id, input.visibility);
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ return updated;
+ }),
+ /**
+ * Refused while copies other than the default still reference it β€” those go
+ * first.
+ *
+ * The default instance goes with the environment: it cannot be removed on
+ * its own, so for an environment with only that one left, deleting the
+ * environment is how it is deleted.
+ *
+ * Both rows go in one transaction, and the snapshot is dropped last, inside
+ * it. Anything that refuses β€” a project still bound to the environment, an
+ * instance created meanwhile, a run still holding the snapshot β€” rolls the
+ * rows back with the snapshot untouched, so a refused delete costs nothing.
+ * The one gap left is a commit that fails after the snapshot is gone, which
+ * leaves rows with nothing built behind them. What was lost is what this
+ * call was asked to delete, and the call reports its failure, so deleting
+ * again finishes the job. The other order is the one with no way back: rows
+ * gone and a snapshot nobody can see, name, or reclaim.
+ */
+ removeEnvironment: instanceProcedure
+ .input(z.object({ id: idSchema }))
+ .mutation(async ({ ctx, input }) => {
+ // Ownership before anything reaches the execution plane: a member who
+ // can see a published environment must not get its snapshot deleted on
+ // the way to being refused the row.
+ const environment = await ctx.environmentModel.findOwnedById(input.id);
+ if (!environment)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ const instances = await ctx.instanceModel.query({ environmentId: environment.id });
+ if (instances.length > 1) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });
+ }
+
+ const [onlyInstance] = instances;
+ // Only a sandbox instance has a snapshot this router can drop; any other
+ // kind keeps referencing the environment and the delete below says so.
+ const defaultInstance = onlyInstance?.kind === 'sandbox' ? onlyInstance : undefined;
+
+ return inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {
+ if (defaultInstance) {
+ await instanceModel.delete(defaultInstance.id).catch(rethrowEnvironmentInUse);
+ }
+
+ const removed = await environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);
+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ if (defaultInstance) await deleteInstanceSnapshot(ctx.client, defaultInstance.id);
+
+ return removed;
+ });
+ }),
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/files.ts b/apps/server/src/routers/lambda/sandboxStorage/files.ts
new file mode 100644
index 00000000000..ce357dfa922
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/files.ts
@@ -0,0 +1,181 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import type { EnvironmentInstanceModel } from '@/database/models/environmentInstance';
+import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
+
+import { instanceProcedure, mapStorageError } from './procedures';
+import { idSchema, relativePathSchema, topicIdSchema } from './schemas';
+
+/**
+ * Ceiling on a single write. Generous for anything a person edits by hand and
+ * small enough that a runaway body is refused before it is buffered β€” this is
+ * an editor's save path, not a bulk upload.
+ */
+const MAX_FILE_CONTENT_BYTES = 1024 * 1024;
+
+/**
+ * Checked in UTF-8 bytes, which is what the cap is denominated in and what the
+ * execution plane actually receives. `z.string().max()` counts UTF-16 code
+ * units, so a megabyte of CJK would pass it and send roughly three.
+ */
+const fileContentSchema = z
+ .string()
+ .refine((value) => Buffer.byteLength(value, 'utf8') <= MAX_FILE_CONTENT_BYTES, {
+ message: `File content exceeds ${MAX_FILE_CONTENT_BYTES} bytes`,
+ });
+
+/**
+ * The directory a file route may touch, as a path relative to the workspace
+ * root; `''` is the whole root.
+ *
+ * A workspace's root is shared by every member and holds every instance's
+ * directory, so a path alone authorizes nothing: it is confined to one
+ * instance, reached through the same rules as everywhere else. Reads follow
+ * visibility β€” a published instance is readable by the members who run in it.
+ * Writes stay with the instance's owner, as every other write to an instance
+ * does. A conversation's own files are read through the instance its runs
+ * resolve to, so a public agent's conversation is held to published ones.
+ *
+ * A personal account's root belongs to its owner alone, which is the one case
+ * where no instance is needed.
+ *
+ * An instance's directory is never written through here: it is
+ * the saved copy of the sandbox's work tree, written by the sandbox alone. A
+ * write from outside would be overwritten by the next save, or leave the
+ * directory disagreeing with the record the next restore reads it by.
+ */
+const resolveFileRoot = async (
+ ctx: {
+ instanceModel: EnvironmentInstanceModel;
+ serverDB: Parameters<typeof resolveSandboxSessionConfig>[0]['serverDB'];
+ userId: string;
+ workspaceId?: string | null;
+ },
+ { instanceId, topicId }: { instanceId?: string; topicId?: string },
+ access: 'read' | 'write',
+): Promise<string> => {
+ if (instanceId) {
+ // Refused before the lookup: the answer is the same whether or not the
+ // instance exists, so there is nothing to find out by asking.
+ if (access === 'write') {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });
+ }
+ const instance = await ctx.instanceModel.findById(instanceId);
+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ return instance.workingDirectory;
+ }
+
+ if (!ctx.workspaceId) return '';
+
+ if (access === 'read' && topicId) {
+ const { cwd } = await resolveSandboxSessionConfig({
+ isShareVisitorRun: false,
+ serverDB: ctx.serverDB,
+ topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (cwd) return cwd;
+ }
+
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_REQUIRED' });
+};
+
+/** Whether `path` is `root` itself or somewhere beneath it. */
+const isWithinRoot = (path: string, root: string) =>
+ !root || path === root || path.startsWith(`${root}/`);
+
+const assertWithinRoot = (path: string, root: string) => {
+ if (!isWithinRoot(path, root)) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });
+ }
+};
+
+/** Names the instance a file route works in; see {@link resolveFileRoot}. */
+const instanceIdSchema = idSchema.optional();
+
+export const filesProcedures = {
+ createDirectory: instanceProcedure
+ .input(
+ z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),
+ )
+ .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
+ assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));
+
+ return ctx.client.createDirectory(input).catch(mapStorageError);
+ }),
+ listFiles: instanceProcedure
+ .input(
+ z.object({
+ instanceId: instanceIdSchema,
+ path: relativePathSchema.optional(),
+ recursive: z.boolean().optional(),
+ topicId: topicIdSchema,
+ }),
+ )
+ .query(async ({ ctx, input: { instanceId, ...input } }) => {
+ const root = await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read');
+ // No path means "the top of what may be listed", which inside a
+ // workspace is the instance's directory, not the shared root.
+ const path = input.path ?? (root || undefined);
+ if (path !== undefined) assertWithinRoot(path, root);
+
+ return ctx.client.listFiles({ ...input, path }).catch(mapStorageError);
+ }),
+ readFile: instanceProcedure
+ .input(
+ z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),
+ )
+ .query(async ({ ctx, input: { instanceId, ...input } }) => {
+ assertWithinRoot(
+ input.path,
+ await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read'),
+ );
+
+ return ctx.client.readFile(input).catch(mapStorageError);
+ }),
+ /**
+ * Write a file's whole contents, creating it and its parents if needed.
+ *
+ * Text only, because the execution plane's endpoint carries the body as a
+ * JSON string with no encoding field. The cap is this layer's own: the
+ * endpoint declares none, and an unbounded string arrives in memory on both
+ * sides before anything touches a disk.
+ */
+ writeFile: instanceProcedure
+ .input(
+ z.object({
+ content: fileContentSchema,
+ instanceId: instanceIdSchema,
+ path: relativePathSchema,
+ topicId: topicIdSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
+ assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));
+
+ return ctx.client.writeFile(input).catch(mapStorageError);
+ }),
+ removeFile: instanceProcedure
+ .input(
+ z.object({
+ instanceId: instanceIdSchema,
+ path: relativePathSchema,
+ recursive: z.boolean().optional(),
+ topicId: topicIdSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input: { instanceId, ...input } }) => {
+ const root = await resolveFileRoot(ctx, { instanceId }, 'write');
+ assertWithinRoot(input.path, root);
+ // The instance's own directory is its identity, not a file in it:
+ // removing it would orphan the row and the snapshot that name it.
+ if (root && input.path === root) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });
+ }
+
+ return ctx.client.deleteFile(input).catch(mapStorageError);
+ }),
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/github.ts b/apps/server/src/routers/lambda/sandboxStorage/github.ts
new file mode 100644
index 00000000000..eadabcaf911
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/github.ts
@@ -0,0 +1,75 @@
+import { ConnectorDataError } from '@lobechat/connector-data';
+import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';
+import { z } from 'zod';
+
+import { ConnectorDataService } from '@/server/services/connectorData';
+
+import { entitledProcedure } from './procedures';
+
+/**
+ * "You have not connected GitHub" travels as an error from the connector layer,
+ * but for the picker it is an answer, not a failure β€” the one it is there to
+ * help the user fix.
+ */
+const isGithubUnavailable = (error: unknown): boolean =>
+ error instanceof ConnectorDataError && error.provider === 'github' && !error.retryable;
+
+export const githubProcedures = {
+ /**
+ * Every repository this account can build an environment from, newest
+ * activity first, each carrying the owner it belongs to so the caller can
+ * group them without a second request per organization.
+ *
+ * A missing GitHub connection is NOT an error here: it is the state the
+ * picker exists to resolve, so it answers `connected: false` and lets the
+ * UI offer the connection instead of a failure.
+ */
+ /**
+ * The branches of one repository, so the environment's checkout target is
+ * picked from what exists rather than typed. Same shape as the repository
+ * listing: no connection is not an error, it is `connected: false`.
+ */
+ listGithubBranches: entitledProcedure
+ .input(z.object({ owner: z.string().min(1).max(255), repository: z.string().min(1).max(255) }))
+ .query(async ({ ctx, input }) => {
+ const service = new ConnectorDataService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ try {
+ const client = await service.getGitHubClient();
+ const branches = await client.listRepositoryBranches(input.owner, input.repository);
+
+ return {
+ branches,
+ connected: true,
+ // At the ceiling the list may be missing branches, and a picker
+ // that only offers what it was given would make those unselectable.
+ truncated: branches.length >= MAX_REPOSITORY_BRANCHES,
+ };
+ } catch (error) {
+ if (isGithubUnavailable(error)) return { branches: [], connected: false, truncated: false };
+
+ throw error;
+ }
+ }),
+ listGithubRepositories: entitledProcedure.query(async ({ ctx }) => {
+ const service = new ConnectorDataService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ try {
+ const client = await service.getGitHubClient();
+
+ return { connected: true, repositories: await client.listAccessibleRepositories() };
+ } catch (error) {
+ if (isGithubUnavailable(error)) return { connected: false, repositories: [] };
+
+ throw error;
+ }
+ }),
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts
new file mode 100644
index 00000000000..99d997ea0a8
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { sandboxStorageRouter } from '.';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('sandboxStorageRouter procedures', () => {
+ const procedures = (sandboxStorageRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['copyInstance', 'mutation', 15],
+ ['createDirectory', 'mutation', 15],
+ ['createEnvironment', 'mutation', 15],
+ ['createInstance', 'mutation', 15],
+ ['createInstanceForEnvironment', 'mutation', 15],
+ ['getEntitlement', 'query', 11],
+ ['getInstance', 'query', 15],
+ ['getStorage', 'query', 12],
+ ['instanceBuildStatus', 'query', 15],
+ ['listEnvironments', 'query', 14],
+ ['listFiles', 'query', 15],
+ ['listGithubBranches', 'query', 13],
+ ['listGithubRepositories', 'query', 12],
+ ['listInstanceSessions', 'query', 15],
+ ['listInstances', 'query', 15],
+ ['readFile', 'query', 15],
+ ['refreshStorageUsage', 'mutation', 12],
+ ['removeEnvironment', 'mutation', 15],
+ ['removeFile', 'mutation', 15],
+ ['removeInstance', 'mutation', 15],
+ ['renameInstance', 'mutation', 15],
+ ['resolveSessionPlacement', 'query', 12],
+ ['setEnvironmentVisibility', 'mutation', 14],
+ ['startInstanceBuild', 'mutation', 15],
+ ['stopInstance', 'mutation', 15],
+ ['updateEnvironment', 'mutation', 14],
+ ['writeFile', 'mutation', 15],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.ts b/apps/server/src/routers/lambda/sandboxStorage/index.ts
new file mode 100644
index 00000000000..aae8b167ed0
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/index.ts
@@ -0,0 +1,28 @@
+import { router } from '@/libs/trpc/lambda';
+
+import { environmentsProcedures } from './environments';
+import { filesProcedures } from './files';
+import { githubProcedures } from './github';
+import { instanceBuildProcedures } from './instanceBuild';
+import { instancesProcedures } from './instances';
+import { storageProcedures } from './storage';
+
+/**
+ * Browsing and managing the persistent sandbox workspace.
+ *
+ * The workspace lives on a volume mounted into the sandbox runtime, so every
+ * call here runs inside a sandbox session on the caller's behalf. Paths are
+ * always relative to the workspace root; the absolute mount path never reaches
+ * a client, which leaves nothing for one to smuggle back.
+ */
+
+export const sandboxStorageRouter = router({
+ ...filesProcedures,
+ ...storageProcedures,
+ ...instancesProcedures,
+ ...instanceBuildProcedures,
+ ...environmentsProcedures,
+ ...githubProcedures,
+});
+
+export type SandboxStorageRouter = typeof sandboxStorageRouter;
diff --git a/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts
new file mode 100644
index 00000000000..93a68f7042f
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts
@@ -0,0 +1,163 @@
+import { toExecutionConfiguration } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';
+
+import { isBuildable } from './instanceOperations';
+import { instanceProcedure, mapStorageError } from './procedures';
+import { idSchema, topicIdSchema } from './schemas';
+
+export const instanceBuildProcedures = {
+ /**
+ * Materialize an instance: clone the environment's sources and run its
+ * bootstrap, into the instance's own stored generation.
+ *
+ * Its own mutation rather than part of `createInstance`, because starting a
+ * build attaches a sandbox session and that is a cold start β€” seconds, with
+ * a dialog open in front of it. The dialog closes on the insert; the list
+ * shows the instance as pending and this is what the client fires next.
+ *
+ * Returns as soon as the build has started: a bootstrap running an install
+ * is minutes long, and `instanceBuildStatus` is what follows it.
+ */
+ startInstanceBuild: instanceProcedure
+ .input(z.object({ id: idSchema, topicId: topicIdSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const instance = await ctx.instanceModel.findOwnedById(input.id);
+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ // The definition this instance was created from, not the environment's
+ // current one: a build has to produce what the instance says it is, and
+ // the two differ exactly when the environment moved on.
+ const specification = instance.configurationSnapshot;
+ const buildable = isBuildable(specification);
+
+ // An environment that clones nothing and installs nothing is already
+ // everything it is ever going to be. Building it would cold-start a
+ // sandbox to do nothing and leave an empty archive behind.
+ if (!buildable) {
+ await ctx.instanceModel.update(input.id, { status: 'ready' });
+
+ return { buildId: null };
+ }
+
+ // A rebuild replaces the folder a conversation may be writing in right
+ // now, so a held instance is refused before the row changes at all. A
+ // lease store that did not answer is not read as "free" β€” the runtime's
+ // own lease still stands behind this and refuses a second writer.
+ const occupancy = await ctx.client
+ .readOccupancy({ names: [input.id], topicId: input.topicId })
+ .catch(() => ({ held: [], unavailable: true }));
+ if (occupancy.held.some((entry) => entry.id === input.id)) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });
+ }
+
+ // What to fall back to if the build never starts. An instance that was
+ // ready still has everything its last build published β€” a refused start
+ // takes none of it away, so it must not come back reading "failed".
+ const previousStatus = instance.status;
+
+ await ctx.instanceModel.update(input.id, { buildError: null, status: 'pending' });
+
+ // Preferred over the execution plane's own GitHub connection, which it
+ // falls back to when this answers null: an App installation is granted
+ // one repository at a time by whoever administers the account, and the
+ // token minted from it is narrower still β€” this repository, read-only,
+ // expiring within the hour. It is resolved here because the App's
+ // private key lives on this side; the execution plane is handed the
+ // result and never the inputs, the same way it is handed the workspace
+ // claim.
+ const credential = await resolveScmCloneCredential({
+ configuration: specification,
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ try {
+ const { buildId } = await ctx.client.buildInstance({
+ credentials: credential ? [credential] : undefined,
+ // Where the checkout lands on the volume: the instance's own folder,
+ // which is what its file browser opens.
+ instanceDir: instance.workingDirectory,
+ name: input.id,
+ // Without the product's own fields: the execution plane digests
+ // what it is sent, and an instance created before `kind` existed
+ // must keep matching the build it already has.
+ specification: toExecutionConfiguration(specification),
+ topicId: input.topicId,
+ });
+ await ctx.instanceModel.update(input.id, { buildId });
+
+ return { buildId };
+ } catch (error) {
+ // Recorded on the row rather than only thrown: the client that asked
+ // may already be gone, and an instance left saying "pending" forever
+ // is the one state nothing recovers from.
+ await ctx.instanceModel.update(
+ input.id,
+ previousStatus === 'ready'
+ ? { status: 'ready' }
+ : {
+ buildError: (error as Error)?.message || 'Could not start the build',
+ status: 'error',
+ },
+ );
+ throw error;
+ }
+ }),
+ /**
+ * Follow a build, and settle the instance once it ends.
+ *
+ * A query that writes, deliberately: the runtime is the only thing that
+ * knows a build finished, nothing calls back, and the row has to end up
+ * right whether or not anyone is still watching. Polling it is what moves
+ * the instance out of `pending`.
+ */
+ instanceBuildStatus: instanceProcedure
+ .input(
+ z.object({
+ id: idSchema,
+ /** Resume the log from here; the reply says where to go next. */
+ logOffset: z.number().int().min(0).optional(),
+ topicId: topicIdSchema,
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const instance = await ctx.instanceModel.findById(input.id);
+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ if (!instance.buildId) {
+ return {
+ chunk: '',
+ logOffset: input.logOffset ?? 0,
+ state: instance.status === 'error' ? ('failed' as const) : ('idle' as const),
+ };
+ }
+
+ const status = await ctx.client
+ .buildStatus({
+ buildId: instance.buildId,
+ logOffset: input.logOffset,
+ name: input.id,
+ topicId: input.topicId,
+ })
+ .catch(mapStorageError);
+
+ if (status.state !== 'running') {
+ // The id is cleared with the verdict: the runtime drops a finished
+ // build's log on its own schedule, and an id that outlives it has the
+ // UI polling for a log that will never come back. Written through the
+ // visibility-scoped recorder, because the poll that happens to receive
+ // the terminal status can be a viewer's rather than the owner's.
+ await ctx.instanceModel.recordBuildResult(input.id, instance.buildId, {
+ buildError:
+ status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,
+ status: status.state === 'succeeded' ? 'ready' : 'error',
+ });
+ }
+
+ return { chunk: status.chunk, logOffset: status.logOffset, state: status.state };
+ }),
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts b/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts
new file mode 100644
index 00000000000..a52726aa035
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts
@@ -0,0 +1,144 @@
+import { type LobeChatDatabase } from '@lobechat/database';
+import {
+ derivedInstanceDirectory,
+ MAX_DERIVED_DIRECTORY_ATTEMPTS,
+} from '@lobechat/utils/environmentInstance';
+import { TRPCError } from '@trpc/server';
+
+import { EnvironmentModel } from '@/database/models/environment';
+import {
+ EnvironmentInstanceModel,
+ InstanceDirectoryOverlapError,
+} from '@/database/models/environmentInstance';
+import type { MarketService } from '@/server/services/market';
+import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';
+
+import { isDuplicateInstanceDirectory } from './constraintErrors';
+import { mapStorageError } from './procedures';
+
+/**
+ * Whether building from this definition does anything: an environment that
+ * clones nothing and installs nothing is already everything it will ever be.
+ * Shared by the build itself, which settles such an instance without starting
+ * a sandbox, and the listing, which is how the row knows a rebuild would be a
+ * no-op rather than a folder thrown away.
+ */
+export const isBuildable = (
+ specification: { bootstrapCommand?: string | null; sources?: unknown[] | null } | null,
+): boolean => (specification?.sources?.length ?? 0) > 0 || Boolean(specification?.bootstrapCommand);
+
+/**
+ * Where an instance lives, in the vocabulary `environment_instances` uses
+ * for every execution target it supports.
+ *
+ * The scope is the caller's workspace key and the resource is the one
+ * persistent workspace inside it β€” there is exactly one, which is why the
+ * resource is named rather than identified. What distinguishes two instances is
+ * the directory, and `environment_instances_provider_path_unique` covers that
+ * tuple, so the database is what stops two copies landing in one folder.
+ */
+export const sandboxBinding = (workspaceKey: string) => ({
+ deviceId: null,
+ kind: 'sandbox' as const,
+ provider: 'market',
+ providerResourceId: 'workspace',
+ providerScope: workspaceKey,
+});
+
+type SandboxStorageClient = ReturnType<MarketService['getSandboxStorageClient']>;
+
+/**
+ * Run `fn` with the environment and instance models bound to one transaction,
+ * for the calls that must change both tables or neither.
+ */
+export const inEnvironmentTransaction = <T>(
+ ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string | null },
+ fn: (models: {
+ environmentModel: EnvironmentModel;
+ instanceModel: EnvironmentInstanceModel;
+ }) => Promise<T>,
+): Promise<T> =>
+ ctx.serverDB.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const workspaceId = ctx.workspaceId ?? undefined;
+
+ return fn({
+ environmentModel: new EnvironmentModel(db, ctx.userId, workspaceId),
+ instanceModel: new EnvironmentInstanceModel(db, ctx.userId, workspaceId),
+ });
+ });
+
+/**
+ * A new sandbox instance of an environment the caller owns, with its directory
+ * derived from the environment's name rather than asked for.
+ *
+ * The directory is searched rather than computed in one shot: the unique
+ * index spans the whole workspace, not one environment, so a name that is
+ * free inside this environment can still be taken outside it. The index stays
+ * the authority β€” the pre-check only keeps the common case out of the error
+ * path, and a lost race falls through to the next suffix.
+ */
+export const createDerivedInstance = async (
+ instanceModel: EnvironmentInstanceModel,
+ workspaceKey: string,
+ environment: { id: string; name: string },
+) => {
+ for (let attempt = 1; attempt <= MAX_DERIVED_DIRECTORY_ATTEMPTS; attempt += 1) {
+ const workingDirectory = derivedInstanceDirectory(environment.name, attempt);
+
+ if (await instanceModel.findByWorkingDirectory(workingDirectory)) continue;
+
+ const created = await instanceModel
+ .create({
+ ...sandboxBinding(workspaceKey),
+ environmentId: environment.id,
+ // The directory is the only thing that distinguishes this instance
+ // from its siblings right now, so it is also the only honest label
+ // until the person renames it.
+ name: workingDirectory,
+ workingDirectory,
+ })
+ .catch((error: unknown) => {
+ // Someone else took this directory between the check and the
+ // insert, or it nests with another instance's. Not a conflict the
+ // caller can act on β€” try the next one.
+ if (isDuplicateInstanceDirectory(error)) return undefined;
+ if (error instanceof InstanceDirectoryOverlapError) return undefined;
+ throw error;
+ });
+
+ if (!created) continue;
+
+ // Nothing to clone and nothing to install means nothing will ever build
+ // this instance, so it is ready as it is written. Left to the client's
+ // follow-up build call, a tab closed in between would strand it in
+ // `pending` β€” and a files environment offers no rebuild to get out of it.
+ if (isBuildable(created.configurationSnapshot)) return created;
+
+ await instanceModel.update(created.id, { status: 'ready' });
+
+ return { ...created, status: 'ready' as const };
+ }
+
+ throw new TRPCError({ code: 'CONFLICT', message: 'DUPLICATE_INSTANCE_DIRECTORY' });
+};
+
+/**
+ * Drop an instance's built state on the execution plane, ahead of its row.
+ *
+ * No snapshot there is the state this call exists to reach, so a 404 is this
+ * step succeeding, not failing. An instance nothing has ever run in has
+ * nothing on the execution plane β€” and treating that as an error strands the
+ * row permanently, because the environment holding it cannot be deleted
+ * either while an instance references it.
+ */
+export const deleteInstanceSnapshot = (
+ client: SandboxStorageClient,
+ id: string,
+ topicId?: string,
+) =>
+ client.deleteInstance({ name: id, topicId }).catch((error: unknown) => {
+ if (error instanceof SandboxStorageFilesError && error.status === 404) return;
+
+ return mapStorageError(error);
+ });
diff --git a/apps/server/src/routers/lambda/sandboxStorage/instances.ts b/apps/server/src/routers/lambda/sandboxStorage/instances.ts
new file mode 100644
index 00000000000..bbc8eedc9a4
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/instances.ts
@@ -0,0 +1,408 @@
+import { isDefaultInstance } from '@lobechat/utils/environmentInstance';
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { TopicModel } from '@/database/models/topic';
+
+import { rethrowDuplicateInstanceDirectory } from './constraintErrors';
+import {
+ createDerivedInstance,
+ deleteInstanceSnapshot,
+ isBuildable,
+ sandboxBinding,
+} from './instanceOperations';
+import { instanceProcedure, mapStorageError } from './procedures';
+import { idSchema, nameSchema, relativePathSchema, topicIdSchema } from './schemas';
+
+/**
+ * The topic the execution plane keys its file-browser console sessions to.
+ * The same literal market uses (`MANAGEMENT_TOPIC_ID`); it is not a topic of
+ * ours, so it is never looked up and the run is shown as a console session.
+ */
+const MANAGEMENT_TOPIC_ID = 'sandbox-workspace-console';
+
+export const instancesProcedures = {
+ /**
+ * Fork an instance: a second directory that starts with everything the
+ * first one had installed. The point of copying rather than creating is to
+ * skip the rebuild β€” the specification alone would give an empty directory
+ * and a fresh bootstrap.
+ */
+ copyInstance: instanceProcedure
+ .input(
+ z.object({
+ id: idSchema,
+ name: nameSchema,
+ workingDirectory: relativePathSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const source = await ctx.instanceModel.findOwnedById(input.id);
+ if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ // A held instance is mid-write, so a copy would capture a tree halfway
+ // through a change. The execution plane refuses it too; asking first
+ // keeps the refusal ahead of the row insert and gives it the same code
+ // the rest of the client already turns into a sentence. A lease store
+ // that did not answer is not read as "free" β€” here that means refusing,
+ // because unlike a rebuild there is no runtime lease standing behind a
+ // copy to catch the second writer.
+ const occupancy = await ctx.client
+ .readOccupancy({ names: [source.id] })
+ .catch(() => ({ held: [], unavailable: true }));
+ if (occupancy.unavailable || occupancy.held.some((entry) => entry.id === source.id)) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });
+ }
+
+ // Row first: a copy whose snapshot succeeded but whose row is missing
+ // would be captured state nobody can name, and therefore nobody can
+ // delete. The reverse β€” a row whose snapshot never arrived β€” is the same
+ // state as a brand-new instance, which the UI already handles.
+ const created = await ctx.instanceModel
+ .create({
+ ...sandboxBinding(ctx.claim.key),
+ // The copy's files are the source's, so its definition is too. Left
+ // to default, it would snapshot whatever the environment says now
+ // and describe a checkout the copied tree does not contain.
+ configurationSnapshot: source.configurationSnapshot,
+ environmentId: source.environmentId,
+ name: input.name,
+ workingDirectory: input.workingDirectory,
+ })
+ .catch(rethrowDuplicateInstanceDirectory);
+
+ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ await ctx.client
+ .copyInstance({
+ from: source.id,
+ // The copy's own folder. Sharing the source's would let either
+ // instance's next save delete files the other still lists.
+ instanceDir: created.workingDirectory,
+ to: created.id,
+ })
+ .catch(async (error) => {
+ await ctx.instanceModel.delete(created.id);
+ return mapStorageError(error);
+ });
+
+ // A copy starts life with everything the source had built, so it is
+ // ready by arrival β€” there is nothing to clone and nothing to install.
+ // Left at the insert's default it would sit in `pending` with no build
+ // to wait for, which reads as "never built" and offers a rebuild that
+ // would throw the copy away.
+ await ctx.instanceModel.update(created.id, { status: 'ready' });
+
+ return { ...created, status: 'ready' as const };
+ }),
+ /**
+ * A new instance of an environment, with its directory derived rather than
+ * asked for.
+ *
+ * The person picked an environment, not a folder. Under the agreed split the
+ * checkout and its installed packages live on local disk and travel in the
+ * snapshot, so this directory holds the outputs worth keeping β€” which is
+ * rarely something anyone has an opinion about before the work exists. Asking
+ * would make them invent an answer to start a conversation.
+ */
+ createInstanceForEnvironment: instanceProcedure
+ .input(z.object({ environmentId: idSchema }))
+ .mutation(async ({ ctx, input }) => {
+ // Owner-scoped: an environment a colleague published is one you can run
+ // in, not one you can add copies to.
+ const environment = await ctx.environmentModel.findOwnedById(input.environmentId);
+ if (!environment)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ return createDerivedInstance(ctx.instanceModel, ctx.claim.key, environment);
+ }),
+ /**
+ * An instance of an environment: its own directory, its own captured
+ * state. Created empty β€” nothing is built until a conversation runs in it.
+ */
+ createInstance: instanceProcedure
+ .input(
+ z.object({
+ environmentId: idSchema,
+ name: nameSchema,
+ workingDirectory: relativePathSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const created = await ctx.instanceModel
+ .create({
+ ...sandboxBinding(ctx.claim.key),
+ environmentId: input.environmentId,
+ name: input.name,
+ workingDirectory: input.workingDirectory,
+ })
+ .catch(rethrowDuplicateInstanceDirectory);
+
+ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+
+ return created;
+ }),
+ /**
+ * One instance, from the database alone. Separate from `listInstances`
+ * because the composer only needs to know where the conversation is pointed,
+ * and `listInstances` pays a sandbox cold start to answer how big everything
+ * is β€” seconds, for a label.
+ */
+ getInstance: instanceProcedure
+ .input(z.object({ id: idSchema }))
+ .query(async ({ ctx, input }) => (await ctx.instanceModel.findById(input.id)) ?? null),
+ /**
+ * Instances, each joined with the state the execution plane actually
+ * holds for it. An instance that was created but never used has no snapshot
+ * yet, which is a normal state and not an error.
+ */
+ listInstances: instanceProcedure
+ .input(
+ z.object({
+ environmentId: idSchema.optional(),
+ topicId: topicIdSchema,
+ /**
+ * Sizes come from the snapshot store, which is reachable only through a
+ * sandbox session and pays a cold start to answer. A settings page is
+ * worth that wait; a picker in the composer is not, and asks for names
+ * alone.
+ */
+ withSizes: z.boolean().default(true),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });
+
+ const [snapshots, occupancy] = await Promise.all([
+ input.withSizes
+ ? ctx.client
+ .listInstances({ topicId: input.topicId })
+ .then((result) => result.instances)
+ // If the store fails, the instances still exist and can still be
+ // renamed or selected β€” only their sizes are unknown, so say so
+ // rather than failing a settings page.
+ .catch(() => null)
+ : [],
+ // Always, and separately from the sizes: this is a Redis read on the
+ // control plane, so it costs the same on every deployment, whereas the
+ // listing above opens the volume. An instance held by another
+ // conversation cannot be run in β€” the lease answers the second writer
+ // with a 409 β€” so a picker that does not know is a picker that offers
+ // a choice the first message will refuse.
+ instances.length > 0
+ ? ctx.client
+ .readOccupancy({
+ names: instances.map((instance) => instance.id),
+ topicId: input.topicId,
+ })
+ // Same rule the lease store itself follows: a failure is "not
+ // known", never "free".
+ .catch(() => ({ held: [], unavailable: true }))
+ : { held: [], unavailable: false },
+ ]);
+
+ // A build is polled by whoever has the Instances tab open, and nobody
+ // has it open most of the time β€” switch tabs mid-build and the verdict
+ // never lands, leaving the row `pending` against a build the runtime
+ // has since discarded and an instance the composer will not offer. So
+ // every listing settles the builds it finds already finished. Bounded
+ // by how many instances can be building at once, and never fatal: an
+ // unreachable execution plane just leaves the row as it was.
+ const settled = await pMap(
+ instances.filter((instance) => instance.buildId),
+ async (instance) => {
+ const status = await ctx.client
+ .buildStatus({ buildId: instance.buildId!, name: instance.id, topicId: input.topicId })
+ .catch(() => null);
+ if (!status || status.state === 'running') return null;
+
+ const next = {
+ buildError:
+ status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,
+ status: status.state === 'succeeded' ? ('ready' as const) : ('error' as const),
+ };
+ await ctx.instanceModel
+ .recordBuildResult(instance.id, instance.buildId!, next)
+ .catch(() => undefined);
+
+ return [instance.id, next] as const;
+ },
+ { concurrency: 5 },
+ );
+ const settledById = new Map(settled.filter((entry) => !!entry));
+
+ const byId = new Map((snapshots ?? []).map((snapshot) => [snapshot.id, snapshot]));
+ const heldBy = new Map(occupancy.held.map((entry) => [entry.id, entry.own]));
+
+ return {
+ instances: instances.map((instance) => ({
+ /** Set only while a build is worth polling; cleared with its verdict. */
+ buildId: settledById.has(instance.id) ? null : instance.buildId,
+ // From the definition the instance was made from, which is what a
+ // build uses β€” the environment may have moved on since.
+ buildable: isBuildable(instance.configurationSnapshot),
+ buildError: settledById.get(instance.id)?.buildError ?? instance.buildError,
+ createdAt: instance.createdAt,
+ environmentId: instance.environmentId,
+ id: instance.id,
+ // Held by a running sandbox, and by whom. `own` is this topic's own
+ // run, which its own picker must keep offering; anything else is
+ // another conversation and is what a picker refuses.
+ inUse: heldBy.has(instance.id),
+ inUseByThisTopic: heldBy.get(instance.id) === true,
+ name: instance.name,
+ snapshot: byId.get(instance.id) ?? null,
+ status: settledById.get(instance.id)?.status ?? instance.status,
+ workingDirectory: instance.workingDirectory,
+ })),
+ occupancyUnavailable: occupancy.unavailable,
+ snapshotsUnavailable: snapshots === null,
+ };
+ }),
+ /**
+ * The run history of every instance of one environment, newest first.
+ *
+ * The execution plane keys its trail by instance β€” that is the name the
+ * snapshot is stored under β€” while the panel shows one environment, so this
+ * is the union of the instances' histories with the instance named on each
+ * row. Read from the control plane's own records: unlike `listInstances`
+ * it starts no sandbox and pays no cold start.
+ *
+ * Topic titles are looked up for the caller's own topics; a run another
+ * member started in a published environment keeps its id only.
+ */
+ listInstanceSessions: instanceProcedure
+ .input(
+ z.object({
+ environmentId: idSchema,
+ /** Per instance, not in total: each instance's page is fetched on its own. */
+ limit: z.number().int().min(1).max(100).default(20),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });
+ if (instances.length === 0) return { sessions: [], unavailable: false };
+
+ // Bounded: an environment's instance count is whatever the member made,
+ // and one request per instance all at once would put that number on the
+ // execution plane in a single burst.
+ const pages = await pMap(
+ instances,
+ (instance) =>
+ ctx.client
+ .listEnvironmentSessions({ limit: input.limit, name: instance.id })
+ // One instance's history failing must not blank the others; the
+ // caller is told the list is incomplete rather than shown "no runs".
+ .catch(() => null),
+ { concurrency: 5 },
+ );
+
+ const merged = instances
+ .flatMap((instance, index) =>
+ (pages[index]?.sessions ?? []).map((session) => ({
+ ...session,
+ instanceId: instance.id,
+ instanceName: instance.name,
+ })),
+ )
+ .sort((a, b) => b.startedAt.localeCompare(a.startedAt));
+
+ const topicIds = [
+ ...new Set(
+ merged
+ .map((session) => session.topicId)
+ .filter((id): id is string => !!id && id !== MANAGEMENT_TOPIC_ID),
+ ),
+ ];
+ // Read in the workspace's scope β€” the personal scope matches no
+ // workspace topic at all β€” and then narrowed to the caller's own, since
+ // a workspace scope also reaches what other members may see.
+ const topics =
+ topicIds.length > 0
+ ? await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)
+ .findByIds(topicIds)
+ .catch(() => [])
+ : [];
+ // Where the conversation lives, as well as what it is called: a topic is
+ // addressed as `group/<groupId>/<topicId>` when it belongs to a group and
+ // `agent/<agentId>/<topicId>` otherwise, so a link built from the topic
+ // alone cannot resolve and the panel's one way back into the run is a 404.
+ // A group topic carries BOTH ids, which is why the group one is returned
+ // rather than inferred from the absence of an agent.
+ const topicInfo = new Map(
+ topics
+ .filter((topic) => topic.userId === ctx.userId)
+ .map((topic) => [
+ topic.id,
+ { agentId: topic.agentId, groupId: topic.groupId, title: topic.title },
+ ]),
+ );
+
+ return {
+ sessions: merged.map((session) => {
+ const info = session.topicId ? topicInfo.get(session.topicId) : undefined;
+
+ return {
+ ...session,
+ topicAgentId: info?.agentId ?? null,
+ topicGroupId: info?.groupId ?? null,
+ topicTitle: info?.title || null,
+ };
+ }),
+ unavailable: pages.includes(null),
+ };
+ }),
+ /**
+ * Remove one copy of an environment. The default instance is refused: it is
+ * what the environment is, so it goes when the environment does, and a
+ * broken one is rebuilt rather than deleted.
+ */
+ removeInstance: instanceProcedure
+ .input(z.object({ id: idSchema, topicId: topicIdSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const instance = await ctx.instanceModel.findOwnedById(input.id);
+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ const siblings = await ctx.instanceModel.query({ environmentId: instance.environmentId });
+ if (isDefaultInstance(instance, siblings)) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'DEFAULT_INSTANCE' });
+ }
+
+ // Snapshot first, and only drop the row once it is gone: a row removed
+ // while the snapshot survives leaves storage nobody can see, name, or
+ // reclaim. The execution plane refuses while a session is using it, and
+ // that refusal is the one the user needs to see.
+ await deleteInstanceSnapshot(ctx.client, instance.id, input.topicId);
+
+ return ctx.instanceModel.delete(input.id);
+ }),
+ /**
+ * End the run holding an instance, so it can be picked, rebuilt or deleted
+ * now instead of after the idle sweep.
+ *
+ * The owner's, like a rebuild or a delete: in a published environment the
+ * run holding the instance is usually a colleague's conversation, and
+ * cutting it off is not something reading access should allow. The
+ * execution plane does the stop properly β€” snapshot first, lease released
+ * only once the stop is confirmed β€” and its refusals (still saving, still
+ * starting, being built) travel as codes the client turns into sentences.
+ */
+ stopInstance: instanceProcedure
+ .input(z.object({ id: idSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const instance = await ctx.instanceModel.findOwnedById(input.id);
+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ return ctx.client.stopInstance({ name: instance.id }).catch(mapStorageError);
+ }),
+ renameInstance: instanceProcedure
+ .input(z.object({ id: idSchema, name: nameSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const { id, ...changes } = input;
+ const updated = await ctx.instanceModel.update(id, changes);
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
+
+ return updated;
+ }),
+};
diff --git a/apps/server/src/routers/lambda/sandboxStorage/procedures.ts b/apps/server/src/routers/lambda/sandboxStorage/procedures.ts
new file mode 100644
index 00000000000..b1ca32ee5c9
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/procedures.ts
@@ -0,0 +1,132 @@
+import { TRPCError } from '@trpc/server';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { EnvironmentModel } from '@/database/models/environment';
+import { EnvironmentInstanceModel } from '@/database/models/environmentInstance';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { MarketService } from '@/server/services/market';
+import { resolveSandboxStorageClaim } from '@/server/services/sandbox';
+import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';
+
+/**
+ * Statuses the execution plane uses deliberately, each carrying something the
+ * user can act on. Anything else is a fault on the far side and says so.
+ *
+ * `409` is the one worth naming: it means a conversation is still using this
+ * environment. Collapsing it into a generic upstream failure would replace the
+ * only actionable message with one that suggests the product is broken.
+ */
+const WORKSPACE_ERROR_CODES: Record<number, TRPCError['code']> = {
+ 400: 'BAD_REQUEST',
+ 403: 'FORBIDDEN',
+ 404: 'NOT_FOUND',
+ 409: 'CONFLICT',
+ // The workspace is out of quota β€” the user frees space or upgrades.
+ 507: 'PAYLOAD_TOO_LARGE',
+};
+
+export const mapStorageError = (error: unknown): never => {
+ if (error instanceof SandboxStorageFilesError) {
+ throw new TRPCError({
+ code: WORKSPACE_ERROR_CODES[error.status] ?? 'BAD_GATEWAY',
+ // The machine code when the market sent one, the way this router's own
+ // refusals travel (`ENVIRONMENT_HAS_INSTANCES`): the client turns a code
+ // into a sentence in the reader's language. The description beside it
+ // names the row by its id, so forwarding it verbatim put a UUID in a
+ // toast β€” accurate, and useless to the person reading it.
+ message: error.code || error.message,
+ });
+ }
+
+ throw error;
+};
+
+/**
+ * Resolves the caller's sandbox-storage claim: which directory on the volume
+ * they are entitled to and how large it may be.
+ *
+ * It reads `ctx.workspaceId`, but that is the TEAM workspace, and it is read
+ * only to decide whose storage this is β€” a member inside a team gets the
+ * team's shared directory, otherwise their personal one. The claim itself has
+ * nothing to do with the team workspace, which is why neither this nor
+ * anything built on it is named after one.
+ *
+ * The caller is always acting as themselves here β€” a signed-in user browsing
+ * their own storage, not an agent run executing under someone else's identity
+ * β€” so there is no share-visitor case to suppress.
+ */
+export const storageClaimProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+
+ const claim = await resolveSandboxStorageClaim({
+ isShareVisitorRun: false,
+ serverDB: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ claim,
+ marketService: new MarketService({
+ userInfo: { sandboxStorage: claim, userId: ctx.userId, workspaceId },
+ }),
+ },
+ });
+});
+
+/**
+ * Everything past the entitlement check. Without a claim there is no directory
+ * to address β€” the execution plane would reject the call anyway, and failing
+ * here keeps a client that renders the panel too eagerly from looking like a
+ * server fault.
+ */
+export const entitledProcedure = storageClaimProcedure.use(async (opts) => {
+ const { claim, marketService } = opts.ctx;
+ if (!claim) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This account has no persistent sandbox workspace',
+ });
+ }
+
+ return opts.next({ ctx: { claim, client: marketService.getSandboxStorageClient() } });
+});
+
+/**
+ * An environment is a specification plus whatever has been built from it. This
+ * layer owns the specification; the snapshot belongs to the execution plane and
+ * is addressed by the row's id.
+ *
+ * An environment that was created but never used has no snapshot yet, which is
+ * a normal state and not an error: it becomes real the first time a session
+ * using it ends.
+ */
+export const environmentProcedure = entitledProcedure.use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ environmentModel: new EnvironmentModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+});
+
+export const instanceProcedure = environmentProcedure.use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ instanceModel: new EnvironmentInstanceModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+});
diff --git a/apps/server/src/routers/lambda/sandboxStorage/schemas.ts b/apps/server/src/routers/lambda/sandboxStorage/schemas.ts
new file mode 100644
index 00000000000..5d149b256e0
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/schemas.ts
@@ -0,0 +1,39 @@
+import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';
+import { z } from 'zod';
+
+/** Relative workspace path, validated with the same rule the runtime applies. */
+export const relativePathSchema = z.string().refine(isSafeSandboxCwd, {
+ message: 'Path must be a relative path inside the workspace',
+});
+
+/**
+ * Topic whose warm sandbox session should serve the call, so listing a
+ * directory does not cold-start a second sandbox next to the one the user is
+ * already talking to.
+ */
+export const topicIdSchema = z.string().min(1).max(255).optional();
+
+/**
+ * A user-facing environment name. Distinct from the row's id, which is what the
+ * execution plane stores the snapshot under and never changes β€” this is the
+ * part a rename is allowed to move.
+ */
+export const nameSchema = z.string().trim().min(1).max(255);
+
+/**
+ * An environment or instance id. Checked for shape rather than left to the
+ * lookup, because the lookup cannot answer: a non-UUID compared against a
+ * `uuid` column is a Postgres type error, so the caller would get a server
+ * fault where "no such environment" was the answer.
+ *
+ * An instance's id doubles as the name its snapshot is stored under, which is
+ * why it never changes.
+ */
+export const idSchema = z.string().uuid();
+
+/**
+ * Who an environment resolves for inside a workspace. Personal environments
+ * have no pool to join, so the server stores `private` for them whatever a
+ * client sends.
+ */
+export const visibilitySchema = z.enum(['private', 'public']);
diff --git a/apps/server/src/routers/lambda/sandboxStorage/storage.ts b/apps/server/src/routers/lambda/sandboxStorage/storage.ts
new file mode 100644
index 00000000000..f2f37e92230
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/storage.ts
@@ -0,0 +1,60 @@
+import { z } from 'zod';
+
+import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
+
+import { entitledProcedure, mapStorageError, storageClaimProcedure } from './procedures';
+
+export const storageProcedures = {
+ /**
+ * Whether this caller has a persistent workspace at all. The client pairs it
+ * with the lab flag it already holds: flag off renders nothing, flag on
+ * without an entitlement renders the upgrade prompt, and both renders the
+ * workspace.
+ */
+ getEntitlement: storageClaimProcedure.query(async ({ ctx }) => ({
+ entitled: Boolean(ctx.claim),
+ quotaBytes: ctx.claim?.quotaBytes ?? null,
+ })),
+ /**
+ * Where this topic's commands will run, for the prompt that describes it.
+ *
+ * The browser assembles the system role on the client-executor path, and it
+ * cannot resolve this itself: the placement follows an entitlement that is
+ * signed server-side. Without it the prompt fell back to the disposable
+ * wording β€” "files created here are temporary" β€” while the run had a
+ * persistent directory, and the model worked in /tmp on the strength of what
+ * it had been told.
+ *
+ * Returns the placement only. The claim stays on this side; a browser has no
+ * use for an entitlement it cannot sign anything with, and every sandbox call
+ * it makes is routed through a server that resolves the claim again.
+ */
+ resolveSessionPlacement: storageClaimProcedure
+ .input(z.object({ topicId: z.string().optional() }))
+ .query(async ({ ctx, input }) => {
+ const { claim, cwd, mode, workingDir } = await resolveSandboxSessionConfig({
+ isShareVisitorRun: false,
+ serverDB: ctx.serverDB,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ return claim ? { cwd, mode, workingDir } : null;
+ }),
+ getStorage: entitledProcedure.query(async ({ ctx }) =>
+ ctx.client.getStorage().catch(mapStorageError),
+ ),
+ /**
+ * Re-measure the workspace and answer with the fresh figure.
+ *
+ * A mutation rather than a query because it writes: it walks the volume and
+ * stamps the workspace as active. Kept off page load for that reason β€” the
+ * settings page reads the stored number and offers this on its refresh
+ * button, so a page nobody asked to refresh cannot keep an idle workspace
+ * looking busy.
+ */
+ refreshStorageUsage: entitledProcedure.mutation(async ({ ctx }) =>
+ ctx.client.refreshUsage().catch(mapStorageError),
+ ),
+};