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.

5.7 KB
Raw Blame
/**
 * Lobe Skills Executor
 *
 * Creates and exports the SkillsExecutor instance for registration.
 * Injects agentSkillService as dependency.
 */
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
import { SkillsExecutor } from '@lobechat/builtin-tool-skills/executor';
import type { BuiltinToolContext } from '@lobechat/types';

import { cloudSandboxService } from '@/services/cloudSandbox';
import { agentSkillService } from '@/services/skill';
import { useChatStore } from '@/store/chat';

import { clientSkillCatalog } from './clientSkillCatalog';

// Create runtime with client-side service
const runtime = (ctx: BuiltinToolContext) => {
  const { builtinSkills, lookup } = clientSkillCatalog(ctx);
  return new SkillsExecutionRuntime({
    builtinSkills,
    service: {
      execScript: async (command, options) => {
        const { activatedSkills, description } = options;

        // Cloud: execute via Cloud Sandbox with execScript tool
        // Server will resolve zipUrls for all activatedSkills
        const chatState = useChatStore.getState();
        const topicId = chatState.activeTopicId || 'default';

        try {
          // Call cloud sandbox execScript tool
          const result = await cloudSandboxService.callTool(
            'execScript',
            {
              activatedSkills,
              command,
              description,
            },
            { topicId },
          );

          if (!result.success) {
            return {
              executionEnv: 'sandbox' as const,
              exitCode: 1,
              output: '',
              ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
              stderr: result.error?.message || 'Command execution failed',
              success: false,
            };
          }

          const sandboxResult = result.result || {};

          return {
            // Web-client commands execute in the cloud sandbox — stamp the
            // execution env so the file-edit scanner excludes these rows
            // (sandbox delivery goes through exportFile, not the card), matching
            // the server runtime's stamping.
            executionEnv: 'sandbox' as const,
            exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
            output: sandboxResult.stdout || sandboxResult.output || '',
            ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
            stderr: sandboxResult.stderr || '',
            success:
              result.success &&
              (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
          };
        } catch (error) {
          return {
            executionEnv: 'sandbox' as const,
            exitCode: 1,
            output: '',
            stderr: (error as Error).message || 'Command execution failed',
            success: false,
          };
        }
      },
      exportFile: async (path, filename) => {
        // Get current session context
        const chatState = useChatStore.getState();
        const topicId = chatState.activeTopicId || 'default';

        try {
          // Call cloud sandbox exportAndUploadFile
          const result = await cloudSandboxService.exportAndUploadFile(path, filename, topicId);

          return {
            fileId: result.fileId,
            filename: result.filename,
            mimeType: result.mimeType,
            size: result.size,
            success: result.success,
            url: result.url,
          };
        } catch {
          return {
            filename,
            success: false,
          };
        }
      },
      ...lookup,
      readResource: (id, path) => agentSkillService.readResource(id, path),
      runCommand: async ({ command, timeout }) => {
        // Cloud: execute via Cloud Sandbox
        // Get current session context for sandbox isolation
        const chatState = useChatStore.getState();
        const topicId = chatState.activeTopicId || 'default';

        try {
          // Call cloud sandbox via TRPC
          // Note: userId is automatically set by server from authenticated context
          const result = await cloudSandboxService.callTool(
            'runCommand',
            {
              command,
              description: `Execute skill command: ${command.slice(0, 100)}${command.length > 100 ? '...' : ''}`,
              timeout,
            },
            { topicId },
          );

          if (!result.success) {
            return {
              executionEnv: 'sandbox' as const,
              exitCode: 1,
              output: '',
              ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
              stderr: result.error?.message || 'Command execution failed',
              success: false,
            };
          }

          // Parse cloud sandbox result
          const sandboxResult = result.result || {};

          return {
            executionEnv: 'sandbox' as const,
            exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
            output: sandboxResult.stdout || sandboxResult.output || '',
            ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),
            stderr: sandboxResult.stderr || '',
            success:
              result.success &&
              (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),
          };
        } catch (error) {
          return {
            executionEnv: 'sandbox' as const,
            exitCode: 1,
            output: '',
            stderr: (error as Error).message || 'Command execution failed',
            success: false,
          };
        }
      },
    },
  });
};

// Create executor instance with the runtime
export const skillsExecutor = new SkillsExecutor(runtime);