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.

7.7 KB
Raw Blame
import { CloudSandboxIdentifier, type ISandboxService } from '@lobechat/builtin-tool-cloud-sandbox';
import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';
import debug from 'debug';

import { UserModel } from '@/database/models/user';
import { FileService } from '@/server/services/file';
import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';
import {
  isDirectLhInvocation,
  isLhCommand,
  preprocessLhCommand,
  SHARE_VISITOR_LH_BLOCKED_MESSAGE,
} from '@/server/services/toolExecution/preprocessLhCommand';

import { pageSandboxWrapper } from './pageSandboxSync';
import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
import { createSandboxMarketService } from './sandboxMarket';
import { type ServerRuntimeRegistration } from './types';

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

/** Sandbox tools whose `command` param can carry an `lh` invocation. */
const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);

/**
 * Wrap a sandbox service so shell tools get the same `lh` prelude as the skills
 * runtime and the client-side executor (`routers/tools/market.ts`).
 *
 * Without this the sandbox has no `lh` binary and no credentials at all, so a
 * model that reaches for the cloud-sandbox shell instead of the skills one β€”
 * both expose a `runCommand` and nothing tells the model they differ β€” gets a
 * bare `lh: not found` for a command the platform advertises.
 *
 * `isShareVisitor` (set from `context.agentShareVisitor`, see the factory
 * below) disables the shim entirely: a share visitor's run executes under the
 * creator's identity, so the shim's `LOBEHUB_JWT=…` `lh` wrapper would
 * otherwise hand a JWT scoped to the CREATOR's own account into a shell the
 * VISITOR fully controls. `lobe-cloud-sandbox` is allowlisted for share
 * visitors specifically because this shim is skipped for them β€” see
 * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` in `@lobechat/builtin-tools`.
 */
const withLhPreprocessing = (
  service: ISandboxService,
  resolve: {
    /** This run's operation, so an `lh agent run` from here is attributed to its agent. */
    operationId: string | undefined;
    userId: string;
    /** Raw context workspace id, log-only β€” cheap to read, unlike {@link resolveContentWorkspaceId}. */
    workspaceIdHint: string | undefined;
    workspaceId: () => Promise<string | undefined>;
    isShareVisitor: boolean;
  },
): ISandboxService => ({
  // Delegated explicitly rather than spread: `createSandboxService` returns a
  // class instance, whose methods live on the prototype and would be dropped.
  callTool: async (toolName, params) => {
    const command = params?.command;
    if (!SHELL_TOOL_NAMES.has(toolName) || typeof command !== 'string') {
      return service.callTool(toolName, params);
    }

    // Fail closed BEFORE any workspace/JWT resolution: a share visitor never
    // gets the `lh` shim, so an `lh` invocation in their sandbox command
    // returns a plain error result the model can react to, instead of
    // silently falling through to `preprocessLhCommand` (which independently
    // refuses too β€” see its `shareVisitorBlocked` param β€” but this is the
    // primary, intended-to-be-load-bearing check).
    if (resolve.isShareVisitor && isDirectLhInvocation(command)) {
      // Deliberately no command content: it is visitor/model-controlled and
      // may carry an inline token β€” same as the `preprocessLhCommand` refusal.
      log(
        'Refused lh command for share visitor (user %s, workspace %s)',
        resolve.userId,
        resolve.workspaceIdHint,
      );
      return {
        error: {
          message: SHARE_VISITOR_LH_BLOCKED_MESSAGE,
          name: 'ShareVisitorBlocked',
        },
        result: null,
        success: false,
      };
    }

    const workspaceId = isLhCommand(command) ? await resolve.workspaceId() : undefined;
    const result = await preprocessLhCommand(
      command,
      resolve.userId,
      workspaceId,
      resolve.isShareVisitor,
      resolve.operationId,
    );

    if (result.error) {
      return {
        error: { message: result.error, name: 'AuthError' },
        result: null,
        success: false,
      };
    }

    return service.callTool(toolName, { ...params, command: result.command });
  },
  exportAndUploadFile: (path, filename, options) =>
    service.exportAndUploadFile(path, filename, options),
});

/**
 * CloudSandbox Server Runtime
 * Per-request runtime (needs topicId, userId)
 */
export const cloudSandboxRuntime: ServerRuntimeRegistration = {
  factory: async (context) => {
    if (!context.userId || !context.topicId) {
      throw new Error('userId and topicId are required for Cloud Sandbox execution');
    }

    if (!context.serverDB) {
      throw new Error('serverDB is required for Cloud Sandbox execution');
    }

    // Read market accessToken from DB so server-side sandbox runtime can authenticate.
    let accessToken: string | undefined;
    try {
      const userModel = new UserModel(context.serverDB, context.userId);
      const settings = await userModel.getUserSettings();
      accessToken = (settings?.market as any)?.accessToken;
    } catch {
      // non-fatal β€” MarketService will fall back to trustedClientToken
    }

    // The workspace this run belongs to. `context.workspaceId` is empty on the
    // dispatch and resume paths, which is most of them: a workspace agent's
    // tool call then resolved its topic in the personal scope, found nothing,
    // and ran ephemeral β€” the conversation said "Lobehub Dev" while `pwd`
    // answered `/workspace` and the clone went somewhere nothing reads.
    //
    // Recovered once and used for everything this runtime builds, because the
    // danger is not the recovery but a disagreement: the claim signs a
    // directory that the token's identity must also name, or an organization's
    // files mount inside a personal session. `creds.ts` recovers the same way.
    const workspaceId = await resolveContentWorkspaceId(context);

    // Persistence for this run: the entitlement that goes on the trust token,
    // and the topic's own preferences that go on each request.
    const sandbox = await resolveSandboxSessionConfig({
      isShareVisitorRun: Boolean(context.agentShareVisitor),
      serverDB: context.serverDB,
      topicId: context.topicId,
      userId: context.userId,
      workspaceId,
    });

    const marketService = createSandboxMarketService(
      context,
      accessToken,
      workspaceId,
      sandbox.claim,
    );
    const fileService = new FileService(context.serverDB, context.userId, workspaceId);
    const sandboxService = createSandboxService({
      agentShareVisitor: context.agentShareVisitor
        ? {
            shareId: context.agentShareVisitor.shareId,
            visitorUserId: context.agentShareVisitor.visitorUserId,
          }
        : undefined,
      fileService,
      marketService,
      sandboxCwd: sandbox.cwd,
      sandboxInitialization: sandbox.initialization,
      sandboxInstanceId: sandbox.environment,
      sandboxSpecification: sandbox.specification,
      sandboxWorkingDir: sandbox.workingDir,
      sandboxMode: sandbox.mode,
      serverDB: context.serverDB,
      topicId: context.topicId,
      userId: context.userId,
    });

    const wrapPage = pageSandboxWrapper(context, workspaceId);
    const preprocessed = withLhPreprocessing(sandboxService, {
      isShareVisitor: Boolean(context.agentShareVisitor),
      operationId: context.operationId,
      userId: context.userId,
      workspaceId: async () => workspaceId,
      workspaceIdHint: workspaceId,
    });

    return new CloudSandboxExecutionRuntime(wrapPage ? wrapPage(preprocessed) : preprocessed);
  },
  identifier: CloudSandboxIdentifier,
};