Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ SKILL_PACKAGE_MAX_SKILL_MD_BYTES=1048576
AGENT_PACKAGE_MAX_BYTES=536870912
AGENT_PACKAGE_MAX_MANIFEST_BYTES=5242880
AGENT_PACKAGE_MAX_ENTRIES=5000
APP_PACKAGE_MAX_WORKFLOW_TOOLS=20

# Comma-separated list of file extensions blocked from upload for security reasons.
# Extensions should be lowercase without dots (e.g., exe,bat,sh,dll).
Expand Down
5 changes: 5 additions & 0 deletions api/configs/feature/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,11 @@ class FileUploadConfig(BaseSettings):
default=5000,
)

APP_PACKAGE_MAX_WORKFLOW_TOOLS: PositiveInt = Field(
description="Maximum number of Workflow Tool workflows bundled into one App package",
default=20,
)

BATCH_UPLOAD_LIMIT: NonNegativeInt = Field(
description="Maximum number of files allowed in a batch upload operation",
default=20,
Expand Down
96 changes: 92 additions & 4 deletions api/services/app/console_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,29 @@
from __future__ import annotations

import copy
from collections.abc import Callable
from collections.abc import Callable, Sequence
from contextlib import AbstractContextManager
from dataclasses import dataclass, replace
from typing import Any, BinaryIO, Final, Literal, override
from uuid import UUID
from uuid import UUID, uuid4

from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, sessionmaker

from configs import dify_config
from core.rbac import RBACPermission
from core.rbac import RBACPermission, RBACResourceScope
from enums import DeploymentEdition
from events.app_event import app_was_updated
from graphon.enums import BuiltinNodeTypes
from graphon.model_runtime.entities.llm_entities import LLMMode
from graphon.model_runtime.entities.message_entities import PromptMessageRole
from libs.datetime_utils import naive_utc_now
from machinery.context import RequestContext
from models.account import Account
from models.agent import AgentIconType
from models.model import AppMode
from models.model import App, AppMode
from models.tools import WorkflowToolProvider
from repositories.app.console_repository import ConsoleAppRepository, console_app_actor, require_console_app
from repositories.app.response import app_record
from services.agent.errors import AgentNameConflictError
Expand Down Expand Up @@ -65,14 +68,17 @@
DraftGuardedImportParams,
Import,
ImportStatus,
PackagedWorkflowTool,
)
from services.errors.base import NoPermissionError
from services.feature_service import FeatureService
from services.rbac import contracts as rbac_contracts
from services.rbac.members import MemberService
from services.recommended_app_package_service import RecommendedAppPackageService
from services.system_feature_service import SystemFeatureService
from services.tools.workflow_tools_manage_service import WorkflowToolManageService
from services.workflow_service import WorkflowService
from services.workflow_tool_references import WorkflowToolTarget
from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task

# Positions as the console editor lays out its templates (START_INITIAL_POSITION and
Expand Down Expand Up @@ -415,6 +421,73 @@ def import_agent_package_url(self, context: RequestContext, params: AppImportPar
def check_dependencies(self, context: RequestContext, app_id: str) -> CheckDependenciesResult:
return AppDslService.check_app_dependencies(tenant_id=context.active_workspace_id, app_id=app_id)

@override
def plan_workflow_tools(
self, context: RequestContext, tools: Sequence[PackagedWorkflowTool], *, creates_root_app: bool
) -> dict[str, WorkflowToolTarget]:
"""Reuse tools that already exist here, and admit, name and reserve ids for the ones to create."""
workspace_id = context.active_workspace_id
with self._session_factory() as session:
account = console_app_actor(session, context)
existing = {
provider.id: provider.name
for provider in session.scalars(
select(WorkflowToolProvider).where(
WorkflowToolProvider.tenant_id == workspace_id,
WorkflowToolProvider.id.in_([tool.provider_id for tool in tools]),
)
)
}
taken_names = set(
session.scalars(select(WorkflowToolProvider.name).where(WorkflowToolProvider.tenant_id == workspace_id))
)
can_manage_tools = account.is_admin_or_owner
missing = [tool for tool in tools if tool.provider_id not in existing]
if missing and dify_config.RBAC_ENABLED:
can_manage_tools = rbac_service.RBACService.CheckAccess.check(
workspace_id, context.account_id, scene=RBACPermission.TOOL_MANAGE, resource_type=None, resource_id=None
)
if missing and not can_manage_tools:
raise NoPermissionError("You do not have permission to create the workflow tools this App calls")
AppDslService.check_app_quota(tenant_id=workspace_id, new_apps=len(missing) + int(creates_root_app))
targets = {
provider_id: WorkflowToolTarget(provider_id=provider_id, name=name, create=False)
for provider_id, name in existing.items()
}
for tool in missing:
name, suffix = tool.name, 2
while name in taken_names:
name, suffix = f"{tool.name}_{suffix}", suffix + 1
taken_names.add(name)
targets[tool.provider_id] = WorkflowToolTarget(provider_id=str(uuid4()), name=name, create=True)
return targets

@override
def create_workflow_tool(
self, context: RequestContext, *, app_id: str, tool: PackagedWorkflowTool, target: WorkflowToolTarget
) -> None:
"""Publish an imported workflow and expose it as the Workflow Tool its callers already reference."""
with self._session_factory.begin() as session:
account = console_app_actor(session, context)
app = require_console_app(session, context, app_id)
workflow = WorkflowService().publish_workflow(session=session, app_model=app, account=account)
app.workflow_id = workflow.id
app.updated_by = account.id
app.updated_at = naive_utc_now()
WorkflowToolManageService.create_workflow_tool(
user_id=context.account_id,
tenant_id=context.active_workspace_id,
workflow_app_id=app_id,
name=target.name,
label=tool.label,
icon=dict(tool.icon),
description=tool.description,
parameters=tool.parameters,
privacy_policy=tool.privacy_policy,
labels=tool.labels,
import_id=target.provider_id,
)

@override
def export_dsl(self, context: RequestContext, app_id: str, options: AppExportOptions) -> str:
with self._session_factory() as session:
Expand All @@ -441,6 +514,21 @@ def export_app_package(
include_secret=options.include_secret,
workflow_id=options.workflow_id,
preserve_agent_bindings=options.preserve_agent_bindings,
may_bundle=lambda called_app: self._may_export_app(context, called_app),
)

@staticmethod
def _may_export_app(context: RequestContext, app: App) -> bool:
"""Apply the export endpoint's App check to a workflow the exported App calls."""
# Without RBAC, the workspace role the endpoint admitted covers every App in the workspace.
if not dify_config.RBAC_ENABLED or app.maintainer == context.account_id:
return True
return rbac_service.RBACService.CheckAccess.check(
context.active_workspace_id,
context.account_id,
scene=RBACPermission.APP_IMPORT_EXPORT_DSL,
resource_type=RBACResourceScope.APP,
resource_id=app.id,
)

@override
Expand Down
95 changes: 95 additions & 0 deletions api/services/app/console_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import logging
from collections.abc import Sequence
from contextlib import AbstractContextManager, closing
from dataclasses import replace
from typing import BinaryIO, Literal, Protocol
Expand Down Expand Up @@ -33,9 +35,14 @@
AppImportPackage,
AppImportParams,
CheckDependenciesResult,
DslImportWarning,
Import,
ImportStatus,
PackagedWorkflowTool,
)
from services.workflow_tool_references import WorkflowToolTarget, retarget_workflow_tool_dsl

logger = logging.getLogger(__name__)


class ConsoleAppNotFoundError(Exception):
Expand Down Expand Up @@ -150,6 +157,14 @@ def import_agent_package_url(self, context: RequestContext, params: AppImportPar

def check_dependencies(self, context: RequestContext, app_id: str) -> CheckDependenciesResult: ...

def plan_workflow_tools(
self, context: RequestContext, tools: Sequence[PackagedWorkflowTool], *, creates_root_app: bool
) -> dict[str, WorkflowToolTarget]: ...

def create_workflow_tool(
self, context: RequestContext, *, app_id: str, tool: PackagedWorkflowTool, target: WorkflowToolTarget
) -> None: ...

def export_dsl(self, context: RequestContext, app_id: str, options: AppExportOptions) -> str: ...

def export_app_package(
Expand Down Expand Up @@ -259,6 +274,8 @@ def _import_package(self, context: RequestContext, params: AppImportParams, sour
package = self._transfers.read_app_package(source)
if package is not None:
with closing(package):
if package.workflow_tools:
return self._import_with_workflow_tools(context, params, package)
return self._import_dsl(
context,
params.model_copy(update={"mode": "yaml-content", "yaml_content": package.dsl, "yaml_url": None}),
Expand All @@ -270,6 +287,84 @@ def _import_package(self, context: RequestContext, params: AppImportParams, sour
result = self._transfers.import_agent_package(context, source)
return self._import_agent_result(result)

def _import_with_workflow_tools(
self, context: RequestContext, params: AppImportParams, package: AppImportPackage
) -> Import:
"""Create the workflows a package calls as Workflow Tools, then import the App that calls them.

Workflow Tools already in the workspace are reused. New tools get their ids up front, so a DSL can
reference a tool that is created after it and workflows that call each other need no order. Apps
created before a failure are deleted.
"""
self._access.require_import(context, "dsl")
targets = self._transfers.plan_workflow_tools(
context, package.workflow_tools, creates_root_app=not params.app_id
)
created_app_ids: list[str] = []
warnings: list[DslImportWarning] = []
try:
for tool in package.workflow_tools:
target = targets[tool.provider_id]
if not target.create:
continue
with closing(package.open_workflow_tool(tool)) as workflow_package:
imported = self._import_dsl(
context,
AppImportParams(
mode="yaml-content",
yaml_content=retarget_workflow_tool_dsl(workflow_package.dsl, targets),
),
package=workflow_package,
)
if imported.app_id and imported.app_created:
created_app_ids.append(imported.app_id)
if (
imported.status not in {ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS}
or not imported.app_id
):
raise InvalidRosterAgentPackageError(
f"Workflow tool {tool.name!r} could not be imported: {imported.error}"
)
try:
self._transfers.create_workflow_tool(context, app_id=imported.app_id, tool=tool, target=target)
except ValueError as exc:
# Publishing validates the workflow against this workspace, e.g. its Knowledge Bases.
raise InvalidRosterAgentPackageError(
f"Workflow tool {tool.name!r} could not be created: {exc}"
) from exc
warnings.extend(
warning.model_copy(update={"path": f"workflow_tools.{tool.id}.{warning.path}"})
for warning in imported.warnings
)
result = self._import_dsl(
context,
params.model_copy(
update={
"mode": "yaml-content",
"yaml_content": retarget_workflow_tool_dsl(package.dsl, targets),
"yaml_url": None,
}
),
package=package,
)
except Exception:
self._discard_imported_apps(context, created_app_ids)
raise
if result.status == ImportStatus.FAILED:
self._discard_imported_apps(context, created_app_ids)
return result
result.warnings = [*warnings, *result.warnings]
if result.warnings and result.status == ImportStatus.COMPLETED:
result.status = ImportStatus.COMPLETED_WITH_WARNINGS
return result

def _discard_imported_apps(self, context: RequestContext, app_ids: list[str]) -> None:
for app_id in reversed(app_ids):
try:
self.delete(context, app_id)
except Exception:
logger.exception("Failed to delete App %s left by a failed package import", app_id)

def _import_agent_result(self, result: ImportedAppPackage) -> Import:
return Import(
id=str(uuid4()),
Expand Down
17 changes: 15 additions & 2 deletions api/services/app_dsl_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
from graphon.nodes.llm.entities import LLMNodeData, ModelConfig
from graphon.nodes.parameter_extractor.entities import ParameterExtractorNodeData
from graphon.nodes.question_classifier.entities import QuestionClassifierNodeData
from graphon.nodes.tool.entities import ToolNodeData
from graphon.nodes.tool.entities import ToolNodeData, ToolProviderType
from libs.datetime_utils import naive_utc_now
from models import Account, App, AppMode
from models.agent import AgentScope, WorkflowAgentBindingType, WorkflowAgentNodeBinding
Expand Down Expand Up @@ -96,6 +96,8 @@
CHECK_DEPENDENCIES_REDIS_KEY_PREFIX = "app_check_dependencies:"
IMPORT_INFO_REDIS_EXPIRY = 10 * 60 # 10 minutes
CURRENT_DSL_VERSION = CURRENT_APP_DSL_VERSION
# Other provider types reference workspace records by id, so they never map to a plugin.
PLUGIN_TOOL_PROVIDER_TYPES = frozenset({ToolProviderType.BUILT_IN, ToolProviderType.PLUGIN})


def initialize_imported_app_creator_access(result: Import, *, tenant_id: str, account_id: str) -> None:
Expand Down Expand Up @@ -167,12 +169,19 @@ def _check_app_quota(account: Account) -> None:
tenant_id = account.current_tenant_id
if tenant_id is None:
raise ValueError("Current tenant is not set")
AppDslService.check_app_quota(tenant_id=tenant_id, new_apps=1)

@staticmethod
def check_app_quota(*, tenant_id: str, new_apps: int) -> None:
"""Reject an import on Cloud when creating ``new_apps`` more Apps would exceed the plan's limit."""
if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
return
try:
apps = FeatureService.get_features(tenant_id, exclude_vector_space=True).apps
except Exception as error:
# A failed lookup is a server failure, not an invalid DSL or exhausted quota.
raise AppQuotaCheckError("Unable to check the app quota.") from error
if 0 < apps.limit <= apps.size:
if 0 < apps.limit < apps.size + new_apps:
raise NoPermissionError("The number of apps has reached the limit of your subscription.")

def import_app(
Expand Down Expand Up @@ -1220,6 +1229,8 @@ def _extract_dependencies_from_workflow_graph(cls, graph: Mapping) -> list[str]:
match typ:
case BuiltinNodeTypes.TOOL:
tool_entity = ToolNodeData.model_validate(node["data"])
if tool_entity.provider_type not in PLUGIN_TOOL_PROVIDER_TYPES:
continue
dependencies.append(
node_data.get("plugin_id")
or DependenciesAnalysisService.analyze_tool_provider_reference(tool_entity.provider_id),
Expand Down Expand Up @@ -1320,6 +1331,8 @@ def _extract_dependencies_from_model_config(cls, model_config: Mapping) -> list[
agent_configs = model_config.get("agent_mode", {})
if agent_configs:
for agent_config in agent_configs.get("tools", []):
if agent_config.get("provider_type") not in PLUGIN_TOOL_PROVIDER_TYPES:
continue
dependencies.append(
DependenciesAnalysisService.analyze_tool_dependency(agent_config.get("provider_id"))
)
Expand Down
Loading
Loading