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.

23.7 KB
Raw Blame
import type { EnvironmentConfiguration } from '@lobechat/types';
import debug from 'debug';

const log = debug('lobe-server:sandbox:workspace-files');

/**
 * Client for the execution plane's persistent-workspace file API.
 *
 * Hand-written rather than taken from the market SDK, which does not carry
 * these endpoints yet. It is deliberately small and replaceable: same paths,
 * same shapes, so swapping it for the generated client later is a deletion.
 *
 * Every `path` is RELATIVE to the workspace root (`reports/q3.md`). The
 * absolute mount path never crosses this boundary — which keeps the mount
 * layout an implementation detail and makes the server-side fence unambiguous,
 * since there is no absolute path for a caller to smuggle in.
 */
export interface SandboxStorageFileEntry {
  isDirectory: boolean;
  /** A directory that is the top of a git checkout; absent where it is not. */
  isGitRepository?: boolean;
  modifiedAt?: string;
  name: string;
  /** Relative to the workspace root. */
  path: string;
  size?: number;
}

/**
 * What a drive's space goes to, in the categories the storage analysis sorts
 * it into. `dependencies` and `cache` (caches and build output) can be
 * regenerated; the rest cannot, and `environments` is the runtime's own
 * snapshot store, deleted through the environment, never as files.
 */
export const SANDBOX_STORAGE_CATEGORIES = [
  'dependencies',
  'cache',
  'archives',
  'media',
  'git',
  'environments',
  'other',
] as const;

export type SandboxStorageCategory = (typeof SANDBOX_STORAGE_CATEGORIES)[number];

export interface SandboxStorageAnalysisItem {
  bytes: number;
  category: SandboxStorageCategory;
  /** `environments` only: the stored environment (instance id) this is. */
  environment?: string;
  isDirectory: boolean;
  /** Relative to the drive's root. */
  path: string;
  /** Deletable without asking: a dependency directory, a cache or build output. */
  regenerable: boolean;
}

export interface SandboxStorageAnalysisResult {
  categories: { bytes: number; category: SandboxStorageCategory; items: number }[];
  items: SandboxStorageAnalysisItem[];
  largestDirectories: { bytes: number; path: string }[];
  largestFiles: { bytes: number; category: SandboxStorageCategory; path: string }[];
  /** A delete since the scan could not be subtracted exactly; scan again for exact figures. */
  stale?: boolean;
  totalBytes: number;
}

export interface SandboxStorageAnalysis {
  finishedAt?: string;
  /** Snapshot so far while scanning; the final figures once `done`. */
  result?: SandboxStorageAnalysisResult;
  scannedBytes: number;
  startedAt?: string;
  /** `scanning`: this call advanced the scan; `running`: another call is advancing it. */
  status: 'done' | 'running' | 'scanning';
}

export interface SandboxStorageDeleteResult {
  deleted: string[];
  /** Everything requested is gone or failed; otherwise call again with `pending`. */
  done: boolean;
  /** Paths the volume refused to remove (permissions, busy); the rest of the batch still ran. */
  failed?: { message: string; path: string }[];
  freedBytes: number;
  missing: string[];
  pending: string[];
}

export interface SandboxStorageExportResult {
  contentType: string;
  kind: 'directory' | 'file';
  size: number;
}

export interface SandboxStorageFileList {
  entries: SandboxStorageFileEntry[];
  path: string;
  /** True when the listing hit the server-side entry cap. */
  truncated: boolean;
}

export interface SandboxStorageInfo {
  dir: string;
  key: string;
  /**
   * `public` or `member` for a workspace's drives, `personal` for an
   * account's own. Absent from an execution plane that predates member drives.
   */
  kind?: 'member' | 'personal' | 'public';
  lastActiveAt: string | null;
  /**
   * Outcome of the most recent environment snapshot. Snapshots happen when a
   * session is torn down, with no request left to fail, so this is the only
   * place a user can learn their environments stopped being saved.
   */
  lastSnapshotAt: string | null;
  lastSnapshotError: string | null;
  quotaBytes: number;
  status: 'active' | 'archived';
  usageBytes: number | null;
  usageCheckedAt: string | null;
  /**
   * Every drive in that pool with its stored figure, when the read asked for
   * them (`withDrives`). Absent from an execution plane that predates it.
   */
  workspaceDrives?: { storageKey: string; usageBytes: number | null }[];
  /**
   * A workspace drive's pool: its public drive plus every member's personal
   * one, which is the figure the quota is judged on. Absent for a personal
   * account's drive.
   */
  workspaceUsageBytes?: number | null;
}

/**
 * A snapshot the execution plane holds. Only instances that have actually been
 * captured appear — one created but never used has metadata here and no
 * snapshot there, which is why the two are joined rather than assumed to match.
 */
export interface SandboxInstanceSnapshot {
  /** Size of the snapshot archive itself; exact, not a directory walk. */
  bytes: number;
  /** Files in the archive, or `null` when the sidecar metadata disagrees with it. */
  files: number | null;
  /** This platform's `environment_instances` row id. */
  id: string;
  updatedAt: string;
}

/** One run of an instance, as the execution plane's trail records it. */
export interface SandboxSessionRecord {
  /** Set on builds: what the build status endpoint is polled with. */
  buildId: string | null;
  endedAt: string | null;
  /** Null while the run is still going. */
  endReason:
    | 'build_failed'
    | 'build_gone'
    | 'build_succeeded'
    | 'build_timeout'
    | 'expired'
    | 'explicit'
    | 'idle'
    | 'lost'
    | 'switched'
    | null;
  id: number;
  /** The instance id, which is what the snapshot is stored under. */
  instanceId: string | null;
  kind: 'build' | 'session';
  /**
   * Not a conversation's session. The file browser opens one, and so does a
   * build — its sandbox is a management session too, which is why a build
   * appears in the trail twice, once under each `kind`, with one `sessionId`.
   */
  management: boolean;
  sessionId: string;
  sessionUserId: string;
  /** Archive size after the teardown snapshot; null when it failed or has not run. */
  snapshotBytes: number | null;
  snapshotError: string | null;
  startedAt: string;
  topicId: string | null;
}

/**
 * Who holds which instance right now. Its own call rather than a field on the
 * environment listing: occupancy is a Redis read, while a listing reads the
 * volume, and a composer menu that only wants to mark a row "running" must not
 * be the reason a sandbox starts on a deployment without a files function.
 */
/** A build in flight, or the verdict on one that finished. */
export interface SandboxBuildStatus {
  buildId: string;
  /** Log since the requested offset; empty when nothing new has been written. */
  chunk: string;
  /** The process's exit status once it has one; null while running. */
  exitCode: number | null;
  instanceId: string;
  /** Where to resume the log from on the next poll. */
  logOffset: number;
  seconds: number;
  /**
   * Which revision of the specification the finished instance was built
   * from, read back from the manifest the runtime published. Null while
   * running and on a failure: nothing is published on that path, so there is
   * no revision to record.
   */
  specDigest: string | null;
  state: 'running' | 'succeeded' | 'failed';
}

export interface SandboxOccupancy {
  /** Held right now. An instance nobody holds is absent. */
  held: { id: string; own: boolean }[];
  /** The lease store did not answer, so `held` is empty for want of one. */
  unavailable: boolean;
}

export interface SandboxSessionList {
  /** Pass as `before` to fetch the next page; null on the last one. */
  nextBefore: string | null;
  sessions: SandboxSessionRecord[];
}

export interface SandboxStorageClientOptions {
  baseURL: string;
  headers: Record<string, string>;
}

interface RequestContext {
  /**
   * Topic whose warm sandbox session should serve the call. The volume is
   * mounted into the sandbox, not into the market service, so every file
   * operation runs inside a session; reusing the one the user is already
   * working in avoids cold-starting a second sandbox just to list a directory.
   */
  topicId?: string;
}

/**
 * `current` resolves to whatever workspace the caller's signed entitlement
 * names. Sending a literal key would be the only way for a caller to ask for
 * someone else's directory, so we never do.
 */
const CURRENT_STORAGE = 'current';

export class SandboxStorageFilesError extends Error {
  /**
   * The market's machine code for the refusal (`error` in its OAuth-shaped
   * body), when it sent one. The description beside it names the row by its
   * id — fine in a log, not a sentence to put in front of a person — so the
   * code is what the UI translates and the description is only the fallback.
   */
  readonly code?: string;
  readonly status: number;

  constructor(message: string, status: number, code?: string) {
    super(message);
    this.name = 'SandboxStorageFilesError';
    this.code = code;
    this.status = status;
  }
}

export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageClientOptions) => {
  const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
    const response = await fetch(`${baseURL}/api/v1/sandbox/storages/${path}`, {
      ...init,
      headers: { ...headers, ...init?.headers },
    });

    if (!response.ok) {
      const body = await response
        .json()
        .catch(() => ({}) as { error?: string; error_description?: string; message?: string });
      log('workspace file request failed: %s %d %O', path, response.status, body);
      // The market answers in the OAuth shape — `error` for the code and
      // `error_description` for the reason — so reading `message` alone
      // reduced every refusal ("could not delete", "outside the workspace")
      // to the status number, which is the one thing the user cannot act on.
      throw new SandboxStorageFilesError(
        body.error_description ||
          body.message ||
          `Workspace request failed with status ${response.status}`,
        response.status,
        body.error,
      );
    }

    const payload = (await response.json()) as { data: T };
    return payload.data;
  };

  const withTopic = (query: URLSearchParams, { topicId }: RequestContext) => {
    if (topicId) query.set('topicId', topicId);
    return query;
  };

  return {
    /**
     * Copy one file as it is, or one folder as a zip, to a presigned upload
     * URL — read off the volume by the storage service itself, without a
     * sandbox session. A refusal carries an `EXPORT_*` code; a deployment
     * that cannot export answers 501 `EXPORT_UNAVAILABLE`, and one that
     * predates the route answers 404 with no code.
     */
    exportFile: async (
      params: {
        fileOnly?: boolean;
        hidden?: string[];
        maxBytes?: number;
        maxFiles?: number;
        path: string;
        uploadHeaders?: Record<string, string>;
        uploadUrl: string;
      },
      options: { signal?: AbortSignal } = {},
    ): Promise<SandboxStorageExportResult> =>
      request(`${CURRENT_STORAGE}/export`, {
        body: JSON.stringify(params),
        signal: options.signal,
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    /**
     * Create a directory, parents included. Idempotent — an existing directory
     * is a success, so a picker can offer "new folder" without first proving
     * the name is free.
     */
    createDirectory: async (params: RequestContext & { path: string }): Promise<{ path: string }> =>
      request(`${CURRENT_STORAGE}/directory`, {
        body: JSON.stringify({ path: params.path, topicId: params.topicId }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    copyInstance: async (
      params: RequestContext & {
        from: string;
        /** The copy's own directory; the runtime writes its work tree there. */
        instanceDir?: string;
        to: string;
      },
    ): Promise<{ name: string }> =>
      request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.from)}/copy`, {
        body: JSON.stringify({
          instanceDir: params.instanceDir,
          to: params.to,
          topicId: params.topicId,
        }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    deleteInstance: async (
      params: RequestContext & { name: string },
    ): Promise<{ name: string }> => {
      const query = withTopic(new URLSearchParams(), params);
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}${suffix}`, {
        method: 'DELETE',
      });
    },

    /**
     * One step of the drive's space analysis: what takes the space, by
     * category, with the largest files and folders. A large drive takes
     * several steps — call again while `status` is not `done`. A finished
     * analysis is reused for a while unless `restart`. Not quota gated, and
     * no sandbox session: it is how an over-quota drive is emptied.
     */
    analyzeStorage: async (
      params: RequestContext & { restart?: boolean; top?: number } = {},
    ): Promise<SandboxStorageAnalysis> =>
      request(`${CURRENT_STORAGE}/analysis`, {
        body: JSON.stringify({ restart: params.restart, top: params.top, topicId: params.topicId }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    /**
     * Delete several files or folders at once, for good. Not quota gated.
     * With `regenerableOnly` the storage service refuses the whole call
     * (`storage_paths_not_regenerable`) unless every path is a dependency
     * directory, a cache or build output, or inside one.
     */
    deletePaths: async (
      params: RequestContext & { paths: string[]; regenerableOnly?: boolean },
    ): Promise<SandboxStorageDeleteResult> =>
      request(`${CURRENT_STORAGE}/files/delete`, {
        body: JSON.stringify({
          paths: params.paths,
          regenerableOnly: params.regenerableOnly,
          topicId: params.topicId,
        }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    deleteFile: async (
      params: RequestContext & { path: string; recursive?: boolean },
    ): Promise<{ path: string }> => {
      const query = withTopic(new URLSearchParams({ path: params.path }), params);
      if (params.recursive) query.set('recursive', 'true');

      return request(`${CURRENT_STORAGE}/file?${query.toString()}`, { method: 'DELETE' });
    },

    /**
     * Rename or move a file or folder. Never overwrites: an existing
     * destination is refused with 409, and the drive's root cannot be renamed.
     */
    renameFile: async (
      params: RequestContext & { newPath: string; path: string },
    ): Promise<{ path: string }> =>
      request(`${CURRENT_STORAGE}/rename`, {
        body: JSON.stringify({
          newPath: params.newPath,
          path: params.path,
          topicId: params.topicId,
        }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    getStorage: async (
      params: RequestContext & {
        /** Also list every drive in a workspace pool with its figure, in this one read. */
        withDrives?: boolean;
      } = {},
    ): Promise<SandboxStorageInfo> => {
      const query = withTopic(new URLSearchParams(), params);
      if (params.withDrives) query.set('drives', 'true');
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(`${CURRENT_STORAGE}${suffix}`);
    },

    /**
     * Re-measure the directory and return the workspace with the fresh figure.
     *
     * Separate from {@link getStorage}, which reads the stored number: this
     * one walks the volume, and it also stamps the workspace as active. So it
     * belongs on something the user asked for — a refresh button — and never
     * on a page load, where it would keep every workspace it displays
     * permanently young and hide the idle ones from any later sweep.
     */
    refreshUsage: async (params: RequestContext = {}): Promise<SandboxStorageInfo> =>
      request(`${CURRENT_STORAGE}/usage`, {
        body: JSON.stringify({ topicId: params.topicId }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    /**
     * Needs a live sandbox session, so it can take seconds on a cold start —
     * a caller rendering this must show it is loading rather than treat it as
     * data it already has.
     */
    listInstances: async (
      params: RequestContext = {},
    ): Promise<{ instances: SandboxInstanceSnapshot[] }> => {
      const query = withTopic(new URLSearchParams(), params);
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(`${CURRENT_STORAGE}/instances${suffix}`);
    },

    /**
     * One environment's run history, newest first. Answered from the control
     * plane's own trail, so unlike the listings above it needs no sandbox
     * session and costs no cold start.
     */
    listEnvironmentSessions: async (params: {
      before?: string;
      limit?: number;
      name: string;
    }): Promise<SandboxSessionList> => {
      const query = new URLSearchParams();
      if (params.limit !== undefined) query.set('limit', String(params.limit));
      if (params.before) query.set('before', params.before);
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(
        `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/sessions${suffix}`,
      );
    },

    /**
     * Which of `names` a running sandbox holds, and whether the holder is this
     * topic's own session. Control plane only — no sandbox, no volume.
     */
    readOccupancy: async (params: {
      names: string[];
      topicId?: string;
    }): Promise<SandboxOccupancy> => {
      const query = new URLSearchParams({ names: params.names.join(',') });
      if (params.topicId) query.set('topicId', params.topicId);

      return request(`${CURRENT_STORAGE}/instances/occupancy?${query.toString()}`);
    },

    /**
     * Stop whatever sandbox holds `name` and release it, rather than waiting
     * for the idle sweep. The execution plane snapshots that sandbox first and
     * refuses retryably (`SNAPSHOT_IN_PROGRESS`) while the snapshot is still
     * packing. `stopped: false` means nothing held it. Control plane only —
     * stopping a sandbox never starts one.
     */
    readStopTarget: async (params: {
      name: string;
    }): Promise<{ sessionId: string; topicId: string | null } | null> =>
      request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop-target`),

    prepareStop: async (params: {
      expectedSessionId: string;
      name: string;
      operationIds: string[];
    }): Promise<{ prepared: boolean }> => {
      const query = new URLSearchParams({
        expectedSessionId: params.expectedSessionId,
        prepare: 'true',
      });
      for (const id of params.operationIds) query.append('operationId', id);
      return request(
        `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop?${query}`,
        { method: 'POST' },
      );
    },

    stopInstance: async (params: {
      expectedSessionId?: string;
      name: string;
      operationIds?: string[];
    }): Promise<{ stopped: boolean }> => {
      const query = new URLSearchParams();
      if (params.expectedSessionId) query.set('expectedSessionId', params.expectedSessionId);
      for (const id of params.operationIds ?? []) query.append('operationId', id);
      const suffix = query.size ? `?${query.toString()}` : '';
      return request(
        `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop${suffix}`,
        {
          method: 'POST',
        },
      );
    },

    /**
     * Start building an environment from its specification.
     *
     * Returns as soon as the build has started: a bootstrap running an install
     * is minutes long, so it is polled through {@link buildStatus} rather than
     * awaited.
     *
     * `credentials` is the ONE thing in this call that may be a secret, and it
     * is separate from the specification on purpose: the stored configuration
     * has no such field and must never gain one. A token here is scoped to the
     * repository being cloned and expires on its own; the execution plane
     * forwards it and the runtime strips it before anything is remembered.
     * Omitted, the execution plane falls back to its own GitHub connection, so
     * a caller that cannot mint one takes nothing away.
     *
     * Never log this argument.
     */
    buildInstance: async (params: {
      credentials?: { header: string; urlPrefix: string }[];
      /**
       * The instance's directory, relative to the workspace. The runtime writes
       * the checkout there, so it is what the file browser shows, and keeps
       * using it for every later save of this environment.
       */
      instanceDir?: string;
      name: string;
      specification: EnvironmentConfiguration;
      topicId?: string;
    }): Promise<{ buildId: string }> =>
      request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/build`, {
        body: JSON.stringify({
          credentials: params.credentials,
          instanceDir: params.instanceDir,
          specification: params.specification,
          topicId: params.topicId,
        }),
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
      }),

    /** Poll a build, pulling its log from `logOffset` on. */
    buildStatus: async (params: {
      buildId: string;
      logOffset?: number;
      name: string;
      topicId?: string;
    }): Promise<SandboxBuildStatus> => {
      const query = new URLSearchParams();
      if (params.logOffset !== undefined) query.set('logOffset', String(params.logOffset));
      if (params.topicId) query.set('topicId', params.topicId);
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(
        `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}` +
          `/build/${encodeURIComponent(params.buildId)}${suffix}`,
      );
    },

    listFiles: async (
      params: RequestContext & { path?: string; recursive?: boolean } = {},
    ): Promise<SandboxStorageFileList> => {
      const query = withTopic(new URLSearchParams(), params);
      if (params.path) query.set('path', params.path);
      if (params.recursive) query.set('recursive', 'true');
      const suffix = query.size > 0 ? `?${query.toString()}` : '';

      return request(`${CURRENT_STORAGE}/files${suffix}`);
    },

    readFile: async (
      params: RequestContext & { path: string },
    ): Promise<{ content: string; mimeType?: string; path: string }> => {
      const query = withTopic(new URLSearchParams({ path: params.path }), params);

      return request(`${CURRENT_STORAGE}/file?${query.toString()}`);
    },

    /**
     * Write a file, creating it and its parents when they do not exist.
     *
     * Text only: the endpoint carries `content` as a JSON string with no
     * encoding field, so there is no way to round-trip bytes through it. A
     * caller holding binary has to wait for an upload path rather than
     * smuggling it through as text.
     */
    writeFile: async (
      params: RequestContext & { content: string; path: string },
    ): Promise<{ path: string }> =>
      request(`${CURRENT_STORAGE}/file`, {
        body: JSON.stringify({
          content: params.content,
          path: params.path,
          topicId: params.topicId,
        }),
        headers: { 'Content-Type': 'application/json' },
        method: 'PUT',
      }),
  };
};

export type SandboxStorageClient = ReturnType<typeof createSandboxStorageClient>;