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.

12.9 KB
Raw Blame
import {
  type MarketSkillItem,
  type SearchSkillParams,
  SkillStoreIdentifier,
} from '@lobechat/builtin-tool-skill-store';
import {
  type SkillImportServiceResult,
  SkillStoreExecutionRuntime,
  type SkillStoreRuntimeService,
} from '@lobechat/builtin-tool-skill-store/executionRuntime';
import { RBAC_PERMISSIONS } from '@lobechat/const/rbac';
import { LIBRARY_SKILL_IMPLICIT_MODE, parsePluginEntry, upsertPluginMode } from '@lobechat/types';
import debug from 'debug';

import { AgentModel } from '@/database/models/agent';
import { RbacModel } from '@/database/models/rbac';
import { UserModel } from '@/database/models/user';
import {
  emitToolOutcomeSafely,
  resolveToolOutcomeScope,
} from '@/server/services/agentSignal/procedure';
import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';
import { MarketService } from '@/server/services/market';
import { SkillImporter } from '@/server/services/skill/importer';

import { type ServerRuntimeRegistration } from './types';

const log = debug('lobe-server:skill-store-runtime');

class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
  private agentId?: string;
  private emitOutcome?: typeof emitToolOutcomeSafely;
  private messageId?: string;
  private importer: SkillImporter;
  private marketService: MarketService;
  private enableImportedSkill?: (identifier: string) => Promise<void>;
  private operationId?: string;
  private taskId?: string;
  private toolCallId?: string;
  private topicId?: string;
  private userId: string;

  constructor(options: {
    agentId?: string;
    emitOutcome?: typeof emitToolOutcomeSafely;
    importer: SkillImporter;
    marketService: MarketService;
    messageId?: string;
    /**
     * Runs after every successful import with the skill's identifier. A library
     * skill is opt-in per agent, so the run's own agent is opted in here —
     * otherwise the model could not use the skill it just installed.
     */
    enableImportedSkill?: (identifier: string) => Promise<void>;
    operationId?: string;
    taskId?: string;
    toolCallId?: string;
    topicId?: string;
    userId: string;
  }) {
    this.agentId = options.agentId;
    this.emitOutcome = options.emitOutcome;
    this.messageId = options.messageId;
    this.importer = options.importer;
    this.marketService = options.marketService;
    this.enableImportedSkill = options.enableImportedSkill;
    this.operationId = options.operationId;
    this.taskId = options.taskId;
    this.toolCallId = options.toolCallId;
    this.topicId = options.topicId;
    this.userId = options.userId;
  }

  private emitSkillOutcome = async (input: {
    apiName: string;
    errorReason?: string;
    intentClass?: string;
    objectId?: string;
    relation?: string;
    status: 'failed' | 'succeeded';
    summary: string;
    toolAction: string;
  }) => {
    const { scope, scopeKey } = resolveToolOutcomeScope({
      agentId: this.agentId,
      taskId: this.taskId,
      topicId: this.topicId,
      userId: this.userId,
    });

    await this.emitOutcome?.({
      apiName: input.apiName,
      context: { agentId: this.agentId, userId: this.userId },
      domainKey: 'skill:market-skill',
      errorReason: input.errorReason,
      identifier: SkillStoreIdentifier,
      intentClass: input.intentClass,
      messageId: this.messageId,
      operationId: this.operationId,
      policyStateStore: redisPolicyStateStore,
      relatedObjects: input.objectId
        ? [{ objectId: input.objectId, objectType: 'skill', relation: input.relation }]
        : undefined,
      scope,
      scopeKey,
      status: input.status,
      summary: input.summary,
      ttlSeconds: 7 * 24 * 60 * 60,
      toolAction: input.toolAction,
      toolCallId: this.toolCallId,
    });
  };

  importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {
    try {
      const result = await this.importer.importFromGitHub({ gitUrl });
      await this.enableImportedSkill?.(result.skill.identifier);
      await this.emitSkillOutcome({
        apiName: 'importFromGitHub',
        intentClass: 'tool_command',
        objectId: result.skill.id,
        relation: 'created',
        status: 'succeeded',
        summary: 'Skill store imported a GitHub skill.',
        toolAction: 'import',
      });
      return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
    } catch (error) {
      await this.emitSkillOutcome({
        apiName: 'importFromGitHub',
        errorReason: (error as Error).message,
        intentClass: 'tool_command',
        status: 'failed',
        summary: 'Skill store failed to import a GitHub skill.',
        toolAction: 'import',
      });
      throw error;
    }
  };

  importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {
    try {
      const result = await this.importer.importFromUrl({ url });
      await this.enableImportedSkill?.(result.skill.identifier);
      await this.emitSkillOutcome({
        apiName: 'importFromUrl',
        intentClass: 'tool_command',
        objectId: result.skill.id,
        relation: 'created',
        status: 'succeeded',
        summary: 'Skill store imported a skill from URL.',
        toolAction: 'import',
      });
      return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
    } catch (error) {
      await this.emitSkillOutcome({
        apiName: 'importFromUrl',
        errorReason: (error as Error).message,
        intentClass: 'tool_command',
        status: 'failed',
        summary: 'Skill store failed to import a skill from URL.',
        toolAction: 'import',
      });
      throw error;
    }
  };

  importFromZipUrl = async (
    url: string,
    options?: { identifier?: string; source?: 'market' | 'user' },
  ): Promise<SkillImportServiceResult> => {
    try {
      const result = await this.importer.importFromUrl({ url }, options);
      await this.enableImportedSkill?.(result.skill.identifier);
      await this.emitSkillOutcome({
        apiName: 'importFromZipUrl',
        intentClass: 'tool_command',
        objectId: result.skill.id,
        relation: 'created',
        status: 'succeeded',
        summary: 'Skill store imported a zipped skill.',
        toolAction: 'import',
      });
      return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
    } catch (error) {
      await this.emitSkillOutcome({
        apiName: 'importFromZipUrl',
        errorReason: (error as Error).message,
        intentClass: 'tool_command',
        status: 'failed',
        summary: 'Skill store failed to import a zipped skill.',
        toolAction: 'import',
      });
      throw error;
    }
  };

  searchSkill = async (
    params: SearchSkillParams,
  ): Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }> => {
    log('Searching skills with params: %O', params);

    try {
      const result = await this.marketService.searchSkill(params);
      log('Search skills result: %O', result);
      await this.emitSkillOutcome({
        apiName: 'searchSkill',
        status: 'succeeded',
        summary: 'Skill store searched marketplace skills.',
        toolAction: 'search',
      });
      // Transform SDK response to match expected interface
      return {
        items: result.items,
        page: result.currentPage,
        pageSize: result.pageSize,
        total: result.totalCount,
      };
    } catch (error) {
      log('Error searching skills: %O', error);
      await this.emitSkillOutcome({
        apiName: 'searchSkill',
        errorReason: (error as Error).message,
        status: 'failed',
        summary: 'Skill store failed to search marketplace skills.',
        toolAction: 'search',
      });
      throw error;
    }
  };

  importFromMarket = async (identifier: string): Promise<SkillImportServiceResult> => {
    log('Importing skill from market: %s', identifier);

    try {
      const downloadUrl = this.marketService.getSkillDownloadUrl(identifier);
      log('Download URL: %s', downloadUrl);

      // Same identifier as the Skill Store UI / `lh skill install` path, so a
      // skill installed there is recognized instead of colliding on its name.
      const result = await this.importFromZipUrl(downloadUrl, { identifier, source: 'market' });
      log('Import from market result: %O', result);
      return result;
    } catch (error) {
      log('Error importing skill from market: %O', error);
      throw error;
    }
  };
}

/**
 * Skill Store Server Runtime
 * Per-request runtime (needs serverDB, userId)
 */
export const skillStoreRuntime: ServerRuntimeRegistration = {
  factory: async (context) => {
    if (!context.serverDB) {
      throw new Error('serverDB is required for Skill Store execution');
    }
    if (!context.userId) {
      throw new Error('userId is required for Skill Store execution');
    }

    // Fetch market access token from user settings
    let marketAccessToken: string | undefined;
    try {
      const userModel = new UserModel(context.serverDB, context.userId);
      const userSettings = await userModel.getUserSettings();
      marketAccessToken = (userSettings?.market as any)?.accessToken;
      log(
        'Fetched market accessToken for user %s: %s',
        context.userId,
        marketAccessToken ? 'exists' : 'not found',
      );
    } catch (error) {
      log('Failed to fetch market accessToken for user %s: %O', context.userId, error);
    }

    // Importing inside a workspace writes the SHARED workspace skill catalog.
    // This server-runtime path is reached via aiAgentWriteProcedure
    // (message:create) and does NOT pass through agentSkillsRouter's
    // withScopedPermission('agent:update') write gate, so an approve-only member
    // (chat/tool-approval rights but no skill-management grant) could otherwise
    // mutate the shared catalog by approving an import. Gate the workspace scope
    // on the same permission; fall back to personal scope when the caller lacks
    // it (safe direction — mirrors the pre-workspace behavior for that member and
    // never touches the shared catalog without authorization).
    let importWorkspaceId = context.workspaceId;
    if (importWorkspaceId) {
      try {
        const rbac = new RbacModel(context.serverDB, context.userId);
        const canManageWorkspaceSkills = await rbac.hasAnyPermission(
          [RBAC_PERMISSIONS.AGENT_UPDATE_ALL, RBAC_PERMISSIONS.AGENT_UPDATE_OWNER],
          { workspaceId: importWorkspaceId },
        );
        if (!canManageWorkspaceSkills) {
          log(
            'User %s lacks agent:update in workspace %s; importing skill into personal scope',
            context.userId,
            importWorkspaceId,
          );
          importWorkspaceId = undefined;
        }
      } catch (error) {
        // Fail safe: never write the shared workspace catalog on an unverified
        // permission check.
        log(
          'Failed to verify workspace skill-write permission; falling back to personal scope: %O',
          error,
        );
        importWorkspaceId = undefined;
      }
    }

    const importer = new SkillImporter(context.serverDB, context.userId, importWorkspaceId);
    const marketService = new MarketService({
      accessToken: marketAccessToken,
      userInfo: { userId: context.userId },
    });

    const { agentId, serverDB, userId } = context;
    const enableForRunAgent = agentId
      ? async (identifier: string) => {
          try {
            const agentModel = new AgentModel(serverDB, userId, context.workspaceId);
            const agent = await agentModel.getAgentConfigById(agentId);
            if (!agent) return;

            // Only a skill the agent has no entry for: a pin or an explicit
            // disable is the user's own choice and a re-import must not undo it.
            const plugins = agent.plugins ?? undefined;
            if (plugins?.some((entry) => parsePluginEntry(entry).identifier === identifier)) return;

            await agentModel.updateConfig(agentId, {
              plugins: upsertPluginMode(
                plugins,
                identifier,
                'auto',
                LIBRARY_SKILL_IMPLICIT_MODE,
              ) as unknown as string[],
            });
          } catch (error) {
            // The import itself succeeded; the skill can still be turned on by hand.
            log('Failed to turn imported skill %s on for agent %s: %O', identifier, agentId, error);
          }
        }
      : undefined;

    const service = new SkillStoreServerRuntimeService({
      agentId: context.agentId,
      emitOutcome: emitToolOutcomeSafely,
      importer,
      marketService,
      messageId: context.messageId,
      enableImportedSkill: enableForRunAgent,
      operationId: context.operationId,
      taskId: context.taskId,
      toolCallId: context.toolCallId,
      topicId: context.topicId,
      userId: context.userId,
    });

    return new SkillStoreExecutionRuntime({ service });
  },
  identifier: SkillStoreIdentifier,
};