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.

8.4 KB
Raw Blame
import type { SandboxCallToolResult, SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';
import type { CodeInterpreterToolName } from '@lobehub/market-sdk';
import debug from 'debug';

import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';

import { SandboxMiddlewareService } from '../service';
import type {
  SandboxProvider,
  SandboxProviderCapabilities,
  SandboxProviderFileExportRequest,
  SandboxProviderFileExportResult,
  SandboxService,
  SandboxServiceOptions,
} from '../types';

const log = debug('lobe-server:sandbox:market');
const REDACTED_SANDBOX_PARAM = '[redacted]';
// `GIT_CONFIG_VALUE_<n>` carries the clone credential an environment's
// initializer exports for git; see `buildSandboxEnvironmentInitCommand`.
// `LOBE_DRIVE_DOWNLOAD` carries a drive download's presigned upload URL; see
// `buildDriveDownloadCommand`.
const SANDBOX_AUTH_ENV_PATTERN =
  /\b(LOBEHUB_JWT|GITHUB_TOKEN|GIT_CONFIG_VALUE_\d+|LOBE_DRIVE_DOWNLOAD)=("[^"]*"|'[^']*'|\S+)/g;
/**
 * Any command that writes into `~/.creds/env` (the path documented to the
 * model as where `injectCredsToSandbox` places credentials) carries
 * arbitrary, caller-named plaintext secrets whose variable names
 * `SANDBOX_AUTH_ENV_PATTERN` can't predict. Rather than extend that
 * name-specific pattern (which would need updating every time a new
 * credential key shape shows up), blank the whole command when it targets
 * that path β€” the credential name/value details aren't worth preserving in
 * a debug log anyway.
 */
const CREDS_ENV_WRITE_PATTERN = />>\s*~\/\.creds\/env\b/;

export class MarketSandboxProvider implements SandboxProvider {
  readonly capabilities = {
    backgroundCommands: true,
    exportFile: true,
    files: true,
    languages: ['python', 'javascript', 'typescript'],
    persistentSession: true,
    shell: true,
    skillScripts: true,
  } as const satisfies SandboxProviderCapabilities;

  readonly kind = 'market';

  private readonly options: SandboxServiceOptions;

  constructor(options: SandboxServiceOptions) {
    this.options = options;
  }

  async callTool(
    toolName: string,
    params: Record<string, unknown>,
  ): Promise<SandboxCallToolResult> {
    const {
      marketService,
      sandboxCwd,
      sandboxInstanceId,
      sandboxMode,
      sandboxSpecification,
      sandboxWorkingDir,
      topicId,
      userId,
    } = this.options;

    log(
      'Calling sandbox tool: %s with params: %O, topicId: %s, mode: %s',
      toolName,
      redactSandboxParams(params),
      topicId,
      sandboxMode ?? 'ephemeral',
    );

    try {
      const response = await marketService
        .getSDK()
        .plugins.runBuildInTool(toolName as CodeInterpreterToolName, params as never, {
          // Named one by one, and deliberately NOT cast. Market validates this
          // body with a non-strict schema, so an SDK that predates these fields
          // drops them silently and the call runs in a throwaway sandbox while
          // reporting success β€” which is exactly what shipped: the package was
          // bumped in the cloud superproject only, this workspace resolved the
          // older SDK, and every persistent run landed in /tmp without one
          // error. Excess-property checking is what turns that into a build
          // failure, and it does NOT see properties contributed by a
          // conditional spread β€” `...(sandboxMode && { sandboxMode })` compiles
          // happily against a context type that has no such field. Each one is
          // written out so that it does. The SDK omits an undefined field from
          // the request body itself, so naming them costs nothing on the wire.
          sandboxCwd,
          sandboxInstanceId,
          // Widened for `drive` alone, which the market accepts from the
          // release that added it while the published SDK still types the
          // pair it shipped with. Remove the cast with the SDK bump; the field
          // itself stays named, so it is still checked.
          sandboxMode: sandboxMode as Exclude<SandboxMode, 'drive'> | undefined,
          // The SDK types this one loosely (`Record<string, unknown>`) while
          // ours is a named shape, so only this field is widened β€” the rest
          // stay checked, which is the point of dropping the blanket cast.
          sandboxSpecification: sandboxSpecification as Record<string, unknown> | undefined,
          sandboxWorkingDir,
          topicId,
          userId,
        });

      log('Sandbox tool %s response: %O', toolName, response);

      if (!response.success) {
        return {
          error: getToolAccessDeniedError(response.error, response.error?.message || '') || {
            message: response.error?.message || 'Unknown error',
            name: response.error?.code,
          },
          result: null,
          sessionExpiredAndRecreated: false,
          success: false,
        };
      }

      return {
        result: response.data?.result,
        sessionExpiredAndRecreated: response.data?.sessionExpiredAndRecreated || false,
        success: true,
      };
    } catch (error) {
      log('Error calling sandbox tool %s: %O', toolName, error);

      return {
        error: getToolAccessDeniedError(error, (error as Error).message) || {
          message: (error as Error).message,
          name: (error as Error).name,
        },
        result: null,
        sessionExpiredAndRecreated: false,
        success: false,
      };
    }
  }

  async exportFileToUploadUrl({
    path,
    uploadUrl,
  }: SandboxProviderFileExportRequest): Promise<SandboxProviderFileExportResult> {
    const {
      marketService,
      sandboxCwd,
      sandboxInstanceId,
      sandboxMode,
      sandboxSpecification,
      sandboxWorkingDir,
      topicId,
      userId,
    } = this.options;

    try {
      const response = await marketService.exportFile(
        { path, uploadUrl },
        {
          // Named one by one for the same reason callTool's context is β€” see
          // the comment there: a dropped field silently runs the export in a
          // throwaway sandbox that cannot see the persistent volume's file.
          sandboxCwd,
          sandboxInstanceId,
          // Widened for `drive` like callTool's; remove with the SDK bump.
          sandboxMode: sandboxMode as Exclude<SandboxMode, 'drive'> | undefined,
          sandboxSpecification: sandboxSpecification as Record<string, unknown> | undefined,
          sandboxWorkingDir,
          topicId,
          userId,
        },
      );

      log('Sandbox exportFile response: %O', response);

      if (!response.success) {
        return {
          error: getToolAccessDeniedError(response.error, response.error?.message || '') || {
            message: response.error?.message || 'Failed to export file from sandbox',
            name: response.error?.code,
          },
          success: false,
        };
      }

      const result = response.data?.result;
      const uploadSuccess = result?.success !== false;

      if (!uploadSuccess) {
        return {
          error: { message: result?.error || 'Failed to upload file from sandbox' },
          success: false,
        };
      }

      return {
        mimeType: result?.mimeType,
        result,
        success: true,
      };
    } catch (error) {
      log('Error exporting file: %O', error);

      return {
        error: getToolAccessDeniedError(error, (error as Error).message) || {
          message: (error as Error).message,
        },
        success: false,
      };
    }
  }
}

export const redactSandboxParams = (params: Record<string, unknown>) => {
  const hasCommand = typeof params.command === 'string';
  if (!params.skillZipUrls && !params.zipUrl && !hasCommand) return params;

  const redacted = {
    ...params,
  };

  if (params.zipUrl) redacted.zipUrl = REDACTED_SANDBOX_PARAM;
  if (params.skillZipUrls) redacted.skillZipUrls = REDACTED_SANDBOX_PARAM;
  if (typeof params.command === 'string') {
    redacted.command = CREDS_ENV_WRITE_PATTERN.test(params.command)
      ? REDACTED_SANDBOX_PARAM
      : params.command.replaceAll(
          SANDBOX_AUTH_ENV_PATTERN,
          (_, name: string) => `${name}=${REDACTED_SANDBOX_PARAM}`,
        );
  }

  return redacted;
};

/** @deprecated Use createSandboxService. */
export class ServerSandboxService extends SandboxMiddlewareService implements SandboxService {
  constructor(options: SandboxServiceOptions) {
    super(new MarketSandboxProvider(options), options);
  }
}