Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

chore(agent-v2): sync daily changes (#38162)

yyh0923ebaf88ba
diff --git a/api/clients/agent_backend/__init__.py b/api/clients/agent_backend/__init__.py
index b9032c521eb..172d63858a5 100644
--- a/api/clients/agent_backend/__init__.py
+++ b/api/clients/agent_backend/__init__.py
@@ -32,6 +32,8 @@ from clients.agent_backend.factory import create_agent_backend_run_client
from clients.agent_backend.fake_client import FakeAgentBackendRunClient, FakeAgentBackendScenario
from clients.agent_backend.request_builder import (
AGENT_SOUL_PROMPT_LAYER_ID,
+ DIFY_CONFIG_LAYER_ID,
+ DIFY_CORE_TOOLS_LAYER_ID,
DIFY_EXECUTION_CONTEXT_LAYER_ID,
DIFY_KNOWLEDGE_BASE_LAYER_ID,
DIFY_PLUGIN_TOOLS_LAYER_ID,
@@ -47,6 +49,8 @@ from clients.agent_backend.request_builder import (
__all__ = [
"AGENT_SOUL_PROMPT_LAYER_ID",
+ "DIFY_CONFIG_LAYER_ID",
+ "DIFY_CORE_TOOLS_LAYER_ID",
"DIFY_EXECUTION_CONTEXT_LAYER_ID",
"DIFY_KNOWLEDGE_BASE_LAYER_ID",
"DIFY_PLUGIN_TOOLS_LAYER_ID",
diff --git a/api/clients/agent_backend/request_builder.py b/api/clients/agent_backend/request_builder.py
index fb45a783031..0ed8af042dd 100644
--- a/api/clients/agent_backend/request_builder.py
+++ b/api/clients/agent_backend/request_builder.py
@@ -20,6 +20,8 @@ from agenton.layers import ExitIntent
from agenton_collections.layers.plain import PLAIN_PROMPT_LAYER_TYPE_ID, PromptLayerConfig
from agenton_collections.layers.pydantic_ai import PYDANTIC_AI_HISTORY_LAYER_TYPE_ID
from dify_agent.layers.ask_human import DIFY_ASK_HUMAN_LAYER_TYPE_ID, DifyAskHumanLayerConfig
+from dify_agent.layers.config import DIFY_CONFIG_LAYER_TYPE_ID, DifyConfigLayerConfig
+from dify_agent.layers.dify_core_tools import DIFY_CORE_TOOLS_LAYER_TYPE_ID, DifyCoreToolsLayerConfig
from dify_agent.layers.dify_plugin import (
DIFY_PLUGIN_LLM_LAYER_TYPE_ID,
DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID,
@@ -54,8 +56,10 @@ WORKFLOW_NODE_JOB_PROMPT_LAYER_ID = "workflow_node_job_prompt"
WORKFLOW_USER_PROMPT_LAYER_ID = "workflow_user_prompt"
AGENT_APP_USER_PROMPT_LAYER_ID = "agent_app_user_prompt"
DIFY_EXECUTION_CONTEXT_LAYER_ID = "execution_context"
+DIFY_CONFIG_LAYER_ID = "config"
DIFY_DRIVE_LAYER_ID = "drive"
DIFY_PLUGIN_TOOLS_LAYER_ID = "tools"
+DIFY_CORE_TOOLS_LAYER_ID = "core_tools"
DIFY_KNOWLEDGE_BASE_LAYER_ID = "knowledge"
DIFY_ASK_HUMAN_LAYER_ID = "ask_human"
DIFY_SHELL_LAYER_ID = "shell"
@@ -86,6 +90,10 @@ def _drive_layer_deps() -> dict[str, str]:
return {"shell": DIFY_SHELL_LAYER_ID}
+def _config_layer_deps() -> dict[str, str]:
+ return {"shell": DIFY_SHELL_LAYER_ID}
+
+
def _shell_config_with_drive_ref(
shell_config: DifyShellLayerConfig | None,
drive_config: DifyDriveLayerConfig | None,
@@ -159,7 +167,9 @@ class AgentBackendWorkflowNodeRunInput(BaseModel):
idempotency_key: str | None = None
output: AgentBackendOutputConfig | None = None
tools: DifyPluginToolsLayerConfig | None = None
+ core_tools: DifyCoreToolsLayerConfig | None = None
knowledge: DifyKnowledgeBaseLayerConfig | None = None
+ config_layer_config: DifyConfigLayerConfig | None = None
# Drive Skills & Files declaration (dify.drive) — an index the agent pulls
# through the back proxy, never inline content; see AGENT_DRIVE_MANIFEST_ENABLED.
drive_config: DifyDriveLayerConfig | None = None
@@ -206,7 +216,9 @@ class AgentBackendAgentAppRunInput(BaseModel):
idempotency_key: str | None = None
output: AgentBackendOutputConfig | None = None
tools: DifyPluginToolsLayerConfig | None = None
+ core_tools: DifyCoreToolsLayerConfig | None = None
knowledge: DifyKnowledgeBaseLayerConfig | None = None
+ config_layer_config: DifyConfigLayerConfig | None = None
# Drive Skills & Files declaration (dify.drive) — an index the agent pulls
# through the back proxy, never inline content; see AGENT_DRIVE_MANIFEST_ENABLED.
drive_config: DifyDriveLayerConfig | None = None
@@ -243,8 +255,9 @@ class AgentBackendRunRequestBuilder:
Layer graph: optional Agent Soul system prompt → user prompt →
execution context → optional history (multi-turn) → LLM → optional
- plugin tools / knowledge search → optional structured output. Mirrors the workflow-node
- layer ordering minus the workflow-job / previous-node prompt.
+ plugin-direct tools / core-routed tools / knowledge search →
+ optional structured output. Mirrors the workflow-node layer ordering
+ minus the workflow-job / previous-node prompt.
"""
layers: list[RunLayerSpec] = []
if run_input.agent_soul_prompt:
@@ -274,11 +287,13 @@ class AgentBackendRunRequestBuilder:
]
)
- include_shell = run_input.include_shell or run_input.drive_config is not None
+ include_shell = (
+ run_input.include_shell or run_input.config_layer_config is not None or run_input.drive_config is not None
+ )
if include_shell:
- # Sandboxed bash workspace (dify.shell). It enters before drive so
- # drive can materialize mentioned targets with `dify-agent drive pull`
- # in the same shell-visible filesystem used by model commands.
+ # Sandboxed bash workspace (dify.shell). It enters before config/drive
+ # so eager pulls materialize content in the same filesystem used by
+ # model commands.
layers.append(
RunLayerSpec(
name=DIFY_SHELL_LAYER_ID,
@@ -289,6 +304,17 @@ class AgentBackendRunRequestBuilder:
)
)
+ if run_input.config_layer_config is not None:
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_CONFIG_LAYER_ID,
+ type=DIFY_CONFIG_LAYER_TYPE_ID,
+ deps=_config_layer_deps(),
+ metadata=run_input.metadata,
+ config=run_input.config_layer_config,
+ )
+ )
+
if run_input.drive_config is not None:
# Drive Skills & Files declaration (dify.drive): the catalog plus
# prompt-mentioned entries eagerly pulled through the shell layer.
@@ -338,6 +364,17 @@ class AgentBackendRunRequestBuilder:
)
)
+ if run_input.core_tools is not None and run_input.core_tools.tools:
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_CORE_TOOLS_LAYER_ID,
+ type=DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},
+ metadata=run_input.metadata,
+ config=run_input.core_tools,
+ )
+ )
+
if run_input.knowledge is not None and run_input.knowledge.sets:
layers.append(
RunLayerSpec(
@@ -403,7 +440,8 @@ class AgentBackendRunRequestBuilder:
non-plugin layer graph that produced the snapshot. Plugin layers
(``dify.plugin.llm``, ``dify.plugin.tools``) are excluded from both the
composition and the snapshot before submission because their configs
- require credentials that are not persisted between runs.
+ may carry credentials or runtime-only declarations that are not
+ persisted between runs.
"""
if not runtime_layer_specs:
raise ValueError(
@@ -436,8 +474,9 @@ class AgentBackendRunRequestBuilder:
"""Build a workflow Agent Node run request without defining another wire schema.
Layer graph mirrors the workflow surface: prompts → execution context →
- optional drive/history → LLM → optional plugin tools / knowledge search
- → optional auxiliary layers such as ask_human, shell, and structured output.
+ optional drive/history → LLM → optional plugin-direct tools /
+ core-routed tools / knowledge search → optional auxiliary layers such
+ as ask_human, shell, and structured output.
"""
layers: list[RunLayerSpec] = []
if run_input.agent_soul_prompt:
@@ -473,7 +512,9 @@ class AgentBackendRunRequestBuilder:
]
)
- include_shell = run_input.include_shell or run_input.drive_config is not None
+ include_shell = (
+ run_input.include_shell or run_input.config_layer_config is not None or run_input.drive_config is not None
+ )
if include_shell:
# Sandboxed bash workspace (dify.shell). It enters before drive so
# drive can materialize mentioned targets with `dify-agent drive pull`
@@ -488,6 +529,17 @@ class AgentBackendRunRequestBuilder:
)
)
+ if run_input.config_layer_config is not None:
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_CONFIG_LAYER_ID,
+ type=DIFY_CONFIG_LAYER_TYPE_ID,
+ deps=_config_layer_deps(),
+ metadata=run_input.metadata,
+ config=run_input.config_layer_config,
+ )
+ )
+
if run_input.drive_config is not None:
# Drive Skills & Files declaration (dify.drive): the catalog plus
# prompt-mentioned entries eagerly pulled through the shell layer.
@@ -539,6 +591,17 @@ class AgentBackendRunRequestBuilder:
)
)
+ if run_input.core_tools is not None and run_input.core_tools.tools:
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_CORE_TOOLS_LAYER_ID,
+ type=DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},
+ metadata=run_input.metadata,
+ config=run_input.core_tools,
+ )
+ )
+
if run_input.knowledge is not None and run_input.knowledge.sets:
layers.append(
RunLayerSpec(
diff --git a/api/controllers/console/__init__.py b/api/controllers/console/__init__.py
index cd8d6e0ab46..f5dd5407df3 100644
--- a/api/controllers/console/__init__.py
+++ b/api/controllers/console/__init__.py
@@ -54,6 +54,7 @@ from .app import (
agent_app_access,
agent_app_feature,
agent_app_sandbox,
+ agent_config_inspector,
agent_drive_inspector,
annotation,
app,
@@ -157,6 +158,7 @@ __all__ = [
"agent_app_feature",
"agent_app_sandbox",
"agent_composer",
+ "agent_config_inspector",
"agent_drive_inspector",
"agent_providers",
"agent_roster",
diff --git a/api/controllers/console/agent/composer.py b/api/controllers/console/agent/composer.py
index 7413be95d75..d089772e3ab 100644
--- a/api/controllers/console/agent/composer.py
+++ b/api/controllers/console/agent/composer.py
@@ -57,8 +57,9 @@ class WorkflowAgentComposerApi(Resource):
@login_required
@account_initialization_required
@get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])
+ @with_current_user_id
@with_current_tenant_id
- def get(self, tenant_id: str, app_model: App, node_id: str):
+ def get(self, tenant_id: str, account_id: str, app_model: App, node_id: str):
query = WorkflowAgentComposerQuery.model_validate(request.args.to_dict(flat=True))
return dump_response(
WorkflowAgentComposerResponse,
@@ -66,6 +67,7 @@ class WorkflowAgentComposerApi(Resource):
tenant_id=tenant_id,
app_id=app_model.id,
node_id=node_id,
+ account_id=account_id,
snapshot_id=query.snapshot_id,
),
)
diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.py
index 3b33dc68c72..ec7f32c7609 100644
--- a/api/controllers/console/agent/roster.py
+++ b/api/controllers/console/agent/roster.py
@@ -248,12 +248,16 @@ class AgentAppDetailWithSite(GenericAppDetailWithSite):
backing_app_id: str | None = None
hidden_app_backed: bool = False
debug_conversation_id: str | None = None
+ debug_conversation_has_messages: bool = False
+ debug_conversation_message_count: int = 0
role: str | None = None
active_config_is_published: bool = False
class AgentDebugConversationRefreshResponse(BaseModel):
debug_conversation_id: str
+ debug_conversation_has_messages: bool = False
+ debug_conversation_message_count: int = 0
class AgentPublishPayload(BaseModel):
@@ -372,11 +376,17 @@ def _serialize_agent_app_detail(app_model, *, current_user: Account, agent_id: s
payload["backing_app_id"] = roster_service.runtime_backing_app_id(agent)
payload["hidden_app_backed"] = bool(agent.backing_app_id and agent.backing_app_id != agent.app_id)
payload["id"] = agent.id
- payload["debug_conversation_id"] = roster_service.get_or_create_agent_app_debug_conversation_id(
+ debug_conversation_id = roster_service.get_or_create_agent_app_debug_conversation_id(
tenant_id=app_model.tenant_id,
agent_id=agent.id,
account_id=current_user.id,
)
+ message_count = roster_service.count_agent_app_debug_conversation_messages(
+ conversation_id=debug_conversation_id,
+ )
+ payload["debug_conversation_id"] = debug_conversation_id
+ payload["debug_conversation_has_messages"] = message_count > 0
+ payload["debug_conversation_message_count"] = message_count
payload["role"] = agent.role or ""
payload["active_config_is_published"] = roster_service.active_config_is_published(
tenant_id=app_model.tenant_id,
@@ -635,9 +645,11 @@ class AgentDebugConversationRefreshApi(Resource):
agent_id=str(agent_id),
account_id=current_user.id,
)
- return AgentDebugConversationRefreshResponse(debug_conversation_id=debug_conversation_id).model_dump(
- mode="json"
- )
+ return AgentDebugConversationRefreshResponse(
+ debug_conversation_id=debug_conversation_id,
+ debug_conversation_has_messages=False,
+ debug_conversation_message_count=0,
+ ).model_dump(mode="json")
@console_ns.route("/agent/<uuid:agent_id>/publish")
diff --git a/api/controllers/console/app/agent_config_inspector.py b/api/controllers/console/app/agent_config_inspector.py
new file mode 100644
index 00000000000..83824d6434f
--- /dev/null
+++ b/api/controllers/console/app/agent_config_inspector.py
@@ -0,0 +1,1249 @@
+"""Console API for Agent Soul-backed config assets."""
+
+from __future__ import annotations
+
+import inspect
+import io
+import json
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from typing import Any, Literal
+from uuid import UUID
+
+from flask import Response, request, send_file, url_for
+from flask_restx import Resource
+from pydantic import BaseModel, Field
+
+from controllers.common.schema import (
+ query_params_from_model,
+ query_params_from_request,
+ register_response_schema_models,
+ register_schema_models,
+)
+from controllers.console import console_ns
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
+from controllers.console.app.wraps import get_app_model
+from controllers.console.wraps import (
+ RBACPermission,
+ RBACResourceScope,
+ account_initialization_required,
+ edit_permission_required,
+ rbac_permission_required,
+ setup_required,
+ with_current_tenant_id,
+ with_current_user,
+)
+from extensions.ext_database import db
+from fields.base import ResponseModel
+from libs.login import login_required
+from models.account import Account
+from models.model import App, AppMode
+from services.agent.composer_service import AgentComposerService
+from services.agent.errors import AgentVersionNotFoundError
+from services.agent_config_service import (
+ AgentConfigService,
+ AgentConfigServiceError,
+ AgentConfigVersionKind,
+ ConfigPushFileItem,
+ ConfigPushPayload,
+ ConfigPushSkillItem,
+)
+
+
+class AgentConfigQuery(BaseModel):
+ node_id: str | None = Field(default=None, description="Workflow node ID (workflow composer variant)")
+ version_id: str | None = Field(default=None, description="Published snapshot ID for read-only version view")
+ draft_type: Literal["draft", "debug_build"] | None = Field(
+ default=None,
+ description="Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft",
+ )
+
+
+class AgentConfigByAgentQuery(BaseModel):
+ version_id: str | None = Field(default=None, description="Published snapshot ID for read-only version view")
+ draft_type: Literal["draft", "debug_build"] | None = Field(
+ default=None,
+ description="Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft",
+ )
+
+
+class AgentConfigFileUploadPayload(BaseModel):
+ upload_file_id: str = Field(..., description="UploadFile UUID from POST /console/api/files/upload")
+
+
+_AGENT_CONFIG_SKILL_UPLOAD_PARAMS = {
+ "file": {
+ "in": "formData",
+ "type": "file",
+ "required": True,
+ "description": "Skill package (.zip or .skill).",
+ }
+}
+
+
+class AgentConfigSkillFileQuery(AgentConfigQuery):
+ path: str = Field(..., description="Normalized zip member path inside the skill package")
+
+
+class AgentConfigSkillFileByAgentQuery(AgentConfigByAgentQuery):
+ path: str = Field(..., description="Normalized zip member path inside the skill package")
+
+
+class AgentConfigVersionResponse(ResponseModel):
+ id: str
+ kind: Literal["snapshot", "draft", "build_draft"]
+ writable: bool
+
+
+class AgentConfigSkillItemResponse(ResponseModel):
+ id: str
+ name: str
+ file_id: str | None = None
+ description: str = ""
+ size: int | None = None
+ mime_type: str | None = None
+ hash: str | None = None
+
+
+class AgentConfigFileItemResponse(ResponseModel):
+ id: str
+ name: str
+ file_id: str | None = None
+ size: int | None = None
+ mime_type: str | None = None
+ hash: str | None = None
+
+
+class AgentConfigSkillItemsResponse(ResponseModel):
+ items: list[AgentConfigSkillItemResponse] = Field(default_factory=list)
+
+
+class AgentConfigFileItemsResponse(ResponseModel):
+ items: list[AgentConfigFileItemResponse] = Field(default_factory=list)
+
+
+class AgentConfigSkillUploadResponse(ResponseModel):
+ skill: AgentConfigSkillItemResponse
+ config_version: AgentConfigVersionResponse
+
+
+class AgentConfigFileUploadResponse(ResponseModel):
+ file: AgentConfigFileItemResponse
+ config_version: AgentConfigVersionResponse
+
+
+class AgentConfigManifestResponse(ResponseModel):
+ agent_id: str
+ config_version: AgentConfigVersionResponse
+ skills: AgentConfigSkillItemsResponse = Field(default_factory=AgentConfigSkillItemsResponse)
+ files: AgentConfigFileItemsResponse = Field(default_factory=AgentConfigFileItemsResponse)
+ env_keys: list[str] = Field(default_factory=list)
+ note: str = ""
+
+
+class AgentConfigSkillListResponse(ResponseModel):
+ agent_id: str
+ config_version: AgentConfigVersionResponse
+ items: list[AgentConfigSkillItemResponse] = Field(default_factory=list)
+
+
+class AgentConfigFileListResponse(ResponseModel):
+ agent_id: str
+ config_version: AgentConfigVersionResponse
+ items: list[AgentConfigFileItemResponse] = Field(default_factory=list)
+
+
+class AgentConfigSkillFileResponse(ResponseModel):
+ path: str
+ name: str
+ type: Literal["file", "directory"]
+ previewable: bool
+ downloadable: bool
+
+
+class AgentConfigSkillMarkdownResponse(ResponseModel):
+ path: Literal["SKILL.md"]
+ size: int | None = None
+ truncated: bool
+ binary: Literal[False]
+ text: str
+
+
+class AgentConfigSkillInspectResponse(ResponseModel):
+ id: str
+ name: str
+ description: str = ""
+ size: int | None = None
+ mime_type: str | None = None
+ hash: str | None = None
+ source: Literal["config_skill_zip"]
+ files: list[AgentConfigSkillFileResponse] = Field(default_factory=list)
+ file_tree: list[dict[str, Any]] | None = None
+ skill_md: AgentConfigSkillMarkdownResponse
+ warnings: list[str] = Field(default_factory=list)
+
+
+class AgentConfigFilePreviewResponse(ResponseModel):
+ name: str
+ size: int | None = None
+ truncated: bool
+ binary: bool
+ text: str | None = None
+
+
+class AgentConfigSkillFilePreviewResponse(ResponseModel):
+ path: str
+ size: int | None = None
+ truncated: bool
+ binary: bool
+ text: str | None = None
+
+
+class AgentConfigDownloadResponse(ResponseModel):
+ url: str
+
+
+class AgentConfigDeleteResponse(ResponseModel):
+ result: Literal["success"]
+ removed_names: list[str] = Field(default_factory=list)
+
+
+register_schema_models(console_ns, AgentConfigFileUploadPayload)
+register_response_schema_models(
+ console_ns,
+ AgentConfigDeleteResponse,
+ AgentConfigDownloadResponse,
+ AgentConfigFileItemResponse,
+ AgentConfigFileItemsResponse,
+ AgentConfigFileListResponse,
+ AgentConfigFilePreviewResponse,
+ AgentConfigFileUploadResponse,
+ AgentConfigManifestResponse,
+ AgentConfigSkillFilePreviewResponse,
+ AgentConfigSkillFileResponse,
+ AgentConfigSkillInspectResponse,
+ AgentConfigSkillItemResponse,
+ AgentConfigSkillItemsResponse,
+ AgentConfigSkillListResponse,
+ AgentConfigSkillMarkdownResponse,
+ AgentConfigSkillUploadResponse,
+ AgentConfigVersionResponse,
+)
+
+
+@dataclass(frozen=True, slots=True)
+class _ResolvedConsoleTarget:
+ tenant_id: str
+ agent_id: str
+ account_id: str
+ version_id: str
+ version_kind: AgentConfigVersionKind
+
+
+_WORKFLOW_APP_MODES = [AppMode.WORKFLOW, AppMode.ADVANCED_CHAT]
+
+
+def _service() -> AgentConfigService:
+ return AgentConfigService()
+
+
+def _resolve_agent_id(app_model: App, node_id: str | None) -> str | None:
+ if node_id:
+ return AgentComposerService.resolve_workflow_node_agent_id(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ node_id=node_id,
+ )
+ return app_model.bound_agent_id
+
+
+def _agent_not_bound() -> tuple[dict[str, object], int]:
+ return {"code": "agent_not_bound", "message": "no agent is bound for this app/node"}, 400
+
+
+def _handle(exc: AgentConfigServiceError) -> tuple[dict[str, object], int]:
+ return {"code": exc.code, "message": exc.message}, exc.status_code
+
+
+def _json_response(data: Mapping[str, Any]) -> Response:
+ return Response(
+ response=json.dumps(data, ensure_ascii=False, separators=(",", ":")),
+ content_type="application/json; charset=utf-8",
+ )
+
+
+def _resolve_console_version(
+ *,
+ tenant_id: str,
+ agent_id: str,
+ account_id: str,
+ version_id: str | None,
+ draft_type: str | None,
+) -> tuple[str, AgentConfigVersionKind]:
+ if version_id:
+ return version_id, AgentConfigVersionKind.SNAPSHOT
+ try:
+ if draft_type == "debug_build":
+ state = AgentComposerService.load_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ account_id=account_id,
+ )
+ draft = state.get("draft") or {}
+ draft_id = draft.get("id")
+ if isinstance(draft_id, str) and draft_id:
+ return draft_id, AgentConfigVersionKind.BUILD_DRAFT
+ else:
+ state = AgentComposerService.load_agent_composer(tenant_id=tenant_id, agent_id=agent_id)
+ draft = state.get("draft") or {}
+ draft_id = draft.get("id")
+ if isinstance(draft_id, str) and draft_id:
+ # load_agent_composer creates the normal draft on first access.
+ # Config asset services use their own SQLAlchemy session, so the
+ # draft must be visible before we hand its id across that boundary.
+ db.session.commit()
+ return draft_id, AgentConfigVersionKind.DRAFT
+ except AgentVersionNotFoundError as exc:
+ raise AgentConfigServiceError(
+ "config_version_not_found",
+ "agent config version was not found",
+ status_code=404,
+ ) from exc
+ raise AgentConfigServiceError(
+ "config_version_not_found",
+ "agent config version was not found",
+ status_code=404,
+ )
+
+
+def _resolve_target(
+ *,
+ tenant_id: str,
+ agent_id: str,
+ account_id: str,
+ version_id: str | None,
+ draft_type: str | None,
+) -> _ResolvedConsoleTarget:
+ resolved_version_id, version_kind = _resolve_console_version(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ account_id=account_id,
+ version_id=version_id,
+ draft_type=draft_type,
+ )
+ return _ResolvedConsoleTarget(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ account_id=account_id,
+ version_id=resolved_version_id,
+ version_kind=version_kind,
+ )
+
+
+def _resolve_agent_route_target(
+ *,
+ tenant_id: str,
+ agent_id: UUID,
+ current_user: Account,
+ query: AgentConfigByAgentQuery,
+) -> _ResolvedConsoleTarget:
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ return _resolve_target(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ version_id=query.version_id,
+ draft_type=query.draft_type,
+ )
+
+
+def _resolve_app_route_target(
+ *,
+ app_model: App,
+ current_user: Account,
+ query: AgentConfigQuery,
+) -> _ResolvedConsoleTarget | tuple[dict[str, object], int]:
+ agent_id = _resolve_agent_id(app_model, query.node_id)
+ if not agent_id:
+ return _agent_not_bound()
+ return _resolve_target(
+ tenant_id=app_model.tenant_id,
+ agent_id=agent_id,
+ account_id=current_user.id,
+ version_id=query.version_id,
+ draft_type=query.draft_type,
+ )
+
+
+def _with_agent_route_target(
+ *,
+ tenant_id: str,
+ agent_id: UUID,
+ current_user: Account,
+ action: Callable[[_ResolvedConsoleTarget], Any],
+) -> Any:
+ query = query_params_from_request(AgentConfigByAgentQuery)
+ try:
+ target = _resolve_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ query=query,
+ )
+ return action(target)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+def _with_app_route_target(
+ *,
+ app_model: App,
+ current_user: Account,
+ action: Callable[[_ResolvedConsoleTarget], Any],
+) -> Any:
+ query = query_params_from_request(AgentConfigQuery)
+ try:
+ target = _resolve_app_route_target(app_model=app_model, current_user=current_user, query=query)
+ if isinstance(target, tuple):
+ return target
+ return action(target)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+def _manifest_response(target: _ResolvedConsoleTarget) -> dict[str, object]:
+ return _service().manifest(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ user_id=target.account_id,
+ )
+
+
+def _skill_list_response(target: _ResolvedConsoleTarget) -> dict[str, object]:
+ return _service().list_skills(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ user_id=target.account_id,
+ )
+
+
+def _file_list_response(target: _ResolvedConsoleTarget) -> dict[str, object]:
+ return _service().list_files(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ user_id=target.account_id,
+ )
+
+
+def _read_single_upload() -> tuple[bytes, str]:
+ if "file" not in request.files:
+ raise AgentConfigServiceError("no_file", "no skill file uploaded", status_code=400)
+ if len(request.files) > 1:
+ raise AgentConfigServiceError("too_many_files", "only one skill file is allowed", status_code=400)
+ upload = request.files["file"]
+ return upload.stream.read(), upload.filename or ""
+
+
+def _skill_upload_response(target: _ResolvedConsoleTarget) -> tuple[dict[str, object], int]:
+ return _upload_skill_for_target(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ user_id=target.account_id,
+ version_id=target.version_id,
+ version_kind=target.version_kind,
+ )
+
+
+def _upload_skill_for_target(
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ version_id: str,
+ version_kind: AgentConfigVersionKind,
+ content: bytes | None = None,
+ filename: str = "",
+) -> tuple[dict[str, object], int]:
+ if content is None:
+ content, filename = _read_single_upload()
+ manifest = _service().upload_skill_for_console(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=version_id,
+ config_version_kind=version_kind,
+ content=content,
+ filename=filename,
+ )
+ return manifest, 201
+
+
+def _file_upload_response(
+ target: _ResolvedConsoleTarget, payload: AgentConfigFileUploadPayload
+) -> tuple[dict[str, object], int]:
+ manifest = _service().push_file_for_console(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ user_id=target.account_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ upload_file_id=payload.upload_file_id,
+ )
+ return manifest, 201
+
+
+def _skill_inspect_response(target: _ResolvedConsoleTarget, name: str) -> Response:
+ return _json_response(
+ _service().inspect_skill(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ user_id=target.account_id,
+ )
+ )
+
+
+def _skill_download_response(target: _ResolvedConsoleTarget, name: str) -> Response:
+ return _json_response(
+ {
+ "url": _service().download_skill_url(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ user_id=target.account_id,
+ )
+ }
+ )
+
+
+def _skill_file_preview_response(target: _ResolvedConsoleTarget, name: str, path: str) -> dict[str, object]:
+ return _service().preview_skill_file(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ path=path,
+ user_id=target.account_id,
+ )
+
+
+def _skill_file_download_response(
+ target: _ResolvedConsoleTarget,
+ *,
+ name: str,
+ path: str,
+ raw_endpoint: str,
+ route_params: dict[str, str],
+ extra_query_params: dict[str, str] | None = None,
+) -> Response:
+ member_path = _service().resolve_skill_file_member_path(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ path=path,
+ user_id=target.account_id,
+ )
+ query_args: dict[str, str] = {"path": member_path}
+ if extra_query_params:
+ query_args.update(extra_query_params)
+ if target.version_kind == AgentConfigVersionKind.SNAPSHOT:
+ query_args["version_id"] = target.version_id
+ elif target.version_kind == AgentConfigVersionKind.BUILD_DRAFT:
+ query_args["draft_type"] = "debug_build"
+ url = url_for(raw_endpoint, _external=False, name=name, **route_params, **query_args)
+ return _json_response({"url": url})
+
+
+def _skill_file_raw_download_response(target: _ResolvedConsoleTarget, name: str, path: str) -> Response:
+ download = _service().pull_skill_file(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ path=path,
+ user_id=target.account_id,
+ )
+ return send_file(
+ io.BytesIO(download.payload),
+ mimetype=download.mime_type,
+ as_attachment=True,
+ download_name=download.filename,
+ )
+
+
+def _skill_delete_response(target: _ResolvedConsoleTarget, name: str) -> dict[str, object]:
+ _service().push_for_console(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ user_id=target.account_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ payload=ConfigPushPayload(skills=[ConfigPushSkillItem(name=name)]),
+ )
+ return {"result": "success", "removed_names": [name]}
+
+
+def _file_preview_response(target: _ResolvedConsoleTarget, name: str) -> dict[str, object]:
+ return _service().preview_file(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ user_id=target.account_id,
+ )
+
+
+def _file_download_response(target: _ResolvedConsoleTarget, name: str) -> Response:
+ return _json_response(
+ {
+ "url": _service().download_file_url(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ name=name,
+ user_id=target.account_id,
+ )
+ }
+ )
+
+
+def _file_delete_response(target: _ResolvedConsoleTarget, name: str) -> dict[str, object]:
+ _service().push_for_console(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ user_id=target.account_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ payload=ConfigPushPayload(files=[ConfigPushFileItem(name=name)]),
+ )
+ return {"result": "success", "removed_names": [name]}
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/manifest")
+class AgentConfigManifestByAgentApi(Resource):
+ @console_ns.doc("get_agent_config_manifest_by_agent")
+ @console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentConfigByAgentQuery)})
+ @console_ns.response(200, "Agent config manifest", console_ns.models[AgentConfigManifestResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=_manifest_response,
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/manifest")
+class AgentConfigManifestApi(Resource):
+ @console_ns.doc("get_agent_config_manifest")
+ @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentConfigQuery)})
+ @console_ns.response(200, "Agent config manifest", console_ns.models[AgentConfigManifestResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App):
+ return _with_app_route_target(app_model=app_model, current_user=current_user, action=_manifest_response)
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/upload")
+class AgentConfigSkillUploadByAgentApi(Resource):
+ @console_ns.doc("upload_agent_config_skill_by_agent")
+ @console_ns.doc(
+ consumes=["multipart/form-data"],
+ params={
+ "agent_id": "Agent ID",
+ **query_params_from_model(AgentConfigByAgentQuery),
+ **_AGENT_CONFIG_SKILL_UPLOAD_PARAMS,
+ },
+ )
+ @console_ns.response(201, "Uploaded config skill", console_ns.models[AgentConfigSkillUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=_skill_upload_response,
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/upload")
+class AgentConfigSkillUploadApi(Resource):
+ @console_ns.doc("upload_agent_config_skill")
+ @console_ns.doc(
+ consumes=["multipart/form-data"],
+ params={
+ "app_id": "Application ID",
+ **query_params_from_model(AgentConfigQuery),
+ **_AGENT_CONFIG_SKILL_UPLOAD_PARAMS,
+ },
+ )
+ @console_ns.response(201, "Uploaded config skill", console_ns.models[AgentConfigSkillUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def post(self, current_user: Account, app_model: App):
+ return _with_app_route_target(app_model=app_model, current_user=current_user, action=_skill_upload_response)
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills")
+class AgentConfigSkillsByAgentApi(Resource):
+ @console_ns.doc("get_agent_config_skills_by_agent")
+ @console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentConfigByAgentQuery)})
+ @console_ns.response(200, "Config skills", console_ns.models[AgentConfigSkillListResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=_skill_list_response,
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills")
+class AgentConfigSkillsApi(Resource):
+ @console_ns.doc("get_agent_config_skills")
+ @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentConfigQuery)})
+ @console_ns.response(200, "Config skills", console_ns.models[AgentConfigSkillListResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App):
+ return _with_app_route_target(app_model=app_model, current_user=current_user, action=_skill_list_response)
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/files")
+class AgentConfigFilesByAgentApi(Resource):
+ @console_ns.doc("get_agent_config_files_by_agent")
+ @console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentConfigByAgentQuery)})
+ @console_ns.response(200, "Config files", console_ns.models[AgentConfigFileListResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=_file_list_response,
+ )
+
+ @console_ns.doc("upload_agent_config_file_by_agent")
+ @console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentConfigByAgentQuery)})
+ @console_ns.expect(console_ns.models[AgentConfigFileUploadPayload.__name__])
+ @console_ns.response(201, "Uploaded config file", console_ns.models[AgentConfigFileUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ payload = AgentConfigFileUploadPayload.model_validate(console_ns.payload or {})
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _file_upload_response(target, payload),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/files")
+class AgentConfigFilesApi(Resource):
+ @console_ns.doc("get_agent_config_files")
+ @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentConfigQuery)})
+ @console_ns.response(200, "Config files", console_ns.models[AgentConfigFileListResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App):
+ return _with_app_route_target(app_model=app_model, current_user=current_user, action=_file_list_response)
+
+ @console_ns.doc("upload_agent_config_file")
+ @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentConfigQuery)})
+ @console_ns.expect(console_ns.models[AgentConfigFileUploadPayload.__name__])
+ @console_ns.response(201, "Uploaded config file", console_ns.models[AgentConfigFileUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def post(self, current_user: Account, app_model: App):
+ payload = AgentConfigFileUploadPayload.model_validate(console_ns.payload or {})
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _file_upload_response(target, payload),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>/inspect")
+class AgentConfigSkillInspectByAgentApi(Resource):
+ @console_ns.doc("inspect_agent_config_skill_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config skill name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Config skill inspect view", console_ns.models[AgentConfigSkillInspectResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _skill_inspect_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/<string:name>/inspect")
+class AgentConfigSkillInspectApi(Resource):
+ @console_ns.doc("inspect_agent_config_skill")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config skill name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Config skill inspect view", console_ns.models[AgentConfigSkillInspectResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _skill_inspect_response(target, name),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>/files/preview")
+class AgentConfigSkillFilePreviewByAgentApi(Resource):
+ @console_ns.doc("preview_agent_config_skill_file_by_agent")
+ @console_ns.doc(
+ params={
+ "agent_id": "Agent ID",
+ "name": "Config skill name",
+ **query_params_from_model(AgentConfigSkillFileByAgentQuery),
+ }
+ )
+ @console_ns.response(
+ 200, "Config skill file preview", console_ns.models[AgentConfigSkillFilePreviewResponse.__name__]
+ )
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ query = query_params_from_request(AgentConfigSkillFileByAgentQuery)
+ try:
+ target = _resolve_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ query=query,
+ )
+ return _skill_file_preview_response(target, name, query.path)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/<string:name>/files/preview")
+class AgentConfigSkillFilePreviewApi(Resource):
+ @console_ns.doc("preview_agent_config_skill_file")
+ @console_ns.doc(
+ params={
+ "app_id": "Application ID",
+ "name": "Config skill name",
+ **query_params_from_model(AgentConfigSkillFileQuery),
+ }
+ )
+ @console_ns.response(
+ 200, "Config skill file preview", console_ns.models[AgentConfigSkillFilePreviewResponse.__name__]
+ )
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ query = query_params_from_request(AgentConfigSkillFileQuery)
+ try:
+ target = _resolve_app_route_target(app_model=app_model, current_user=current_user, query=query)
+ if isinstance(target, tuple):
+ return target
+ return _skill_file_preview_response(target, name, query.path)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>/download")
+class AgentConfigSkillDownloadByAgentApi(Resource):
+ @console_ns.doc("download_agent_config_skill_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config skill name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Config skill download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _skill_download_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/<string:name>/download")
+class AgentConfigSkillDownloadApi(Resource):
+ @console_ns.doc("download_agent_config_skill")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config skill name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Config skill download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _skill_download_response(target, name),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>/files/download")
+class AgentConfigSkillFileDownloadByAgentApi(Resource):
+ @console_ns.doc("download_agent_config_skill_file_by_agent")
+ @console_ns.doc(
+ params={
+ "agent_id": "Agent ID",
+ "name": "Config skill name",
+ **query_params_from_model(AgentConfigSkillFileByAgentQuery),
+ }
+ )
+ @console_ns.response(200, "Config skill file download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ query = query_params_from_request(AgentConfigSkillFileByAgentQuery)
+ try:
+ target = _resolve_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ query=query,
+ )
+ return _skill_file_download_response(
+ target,
+ name=name,
+ path=query.path,
+ raw_endpoint="console.agent_config_skill_file_download_content_by_agent_api",
+ route_params={"agent_id": str(agent_id)},
+ )
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/<string:name>/files/download")
+class AgentConfigSkillFileDownloadApi(Resource):
+ @console_ns.doc("download_agent_config_skill_file")
+ @console_ns.doc(
+ params={
+ "app_id": "Application ID",
+ "name": "Config skill name",
+ **query_params_from_model(AgentConfigSkillFileQuery),
+ }
+ )
+ @console_ns.response(200, "Config skill file download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ query = query_params_from_request(AgentConfigSkillFileQuery)
+ try:
+ target = _resolve_app_route_target(app_model=app_model, current_user=current_user, query=query)
+ if isinstance(target, tuple):
+ return target
+ return _skill_file_download_response(
+ target,
+ name=name,
+ path=query.path,
+ raw_endpoint="console.agent_config_skill_file_download_content_api",
+ route_params={"app_id": str(app_model.id)},
+ extra_query_params={"node_id": query.node_id} if query.node_id else None,
+ )
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route(
+ "/agent/<uuid:agent_id>/config/skills/<string:name>/files/content",
+ endpoint="agent_config_skill_file_download_content_by_agent_api",
+)
+class AgentConfigSkillFileDownloadContentByAgentApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ query = query_params_from_request(AgentConfigSkillFileByAgentQuery)
+ try:
+ target = _resolve_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ query=query,
+ )
+ return _skill_file_raw_download_response(target, name, query.path)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route(
+ "/apps/<uuid:app_id>/agent/config/skills/<string:name>/files/content",
+ endpoint="agent_config_skill_file_download_content_api",
+)
+class AgentConfigSkillFileDownloadContentApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ query = query_params_from_request(AgentConfigSkillFileQuery)
+ try:
+ target = _resolve_app_route_target(app_model=app_model, current_user=current_user, query=query)
+ if isinstance(target, tuple):
+ return target
+ return _skill_file_raw_download_response(target, name, query.path)
+ except AgentConfigServiceError as exc:
+ return _handle(exc)
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>")
+class AgentConfigSkillByAgentApi(Resource):
+ @console_ns.doc("delete_agent_config_skill_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config skill name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Config skill deleted", console_ns.models[AgentConfigDeleteResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def delete(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _skill_delete_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/skills/<string:name>")
+class AgentConfigSkillApi(Resource):
+ @console_ns.doc("delete_agent_config_skill")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config skill name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Config skill deleted", console_ns.models[AgentConfigDeleteResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def delete(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _skill_delete_response(target, name),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/files/<string:name>/preview")
+class AgentConfigFilePreviewByAgentApi(Resource):
+ @console_ns.doc("preview_agent_config_file_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config file name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Preview", console_ns.models[AgentConfigFilePreviewResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _file_preview_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/files/<string:name>/preview")
+class AgentConfigFilePreviewApi(Resource):
+ @console_ns.doc("preview_agent_config_file")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config file name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Preview", console_ns.models[AgentConfigFilePreviewResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _file_preview_response(target, name),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/files/<string:name>/download")
+class AgentConfigFileDownloadByAgentApi(Resource):
+ @console_ns.doc("download_agent_config_file_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config file name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Config file download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _file_download_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/files/<string:name>/download")
+class AgentConfigFileDownloadApi(Resource):
+ @console_ns.doc("download_agent_config_file")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config file name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Config file download URL", console_ns.models[AgentConfigDownloadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def get(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _file_download_response(target, name),
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/config/files/<string:name>")
+class AgentConfigFileByAgentApi(Resource):
+ @console_ns.doc("delete_agent_config_file_by_agent")
+ @console_ns.doc(
+ params={"agent_id": "Agent ID", "name": "Config file name", **query_params_from_model(AgentConfigByAgentQuery)}
+ )
+ @console_ns.response(200, "Config file deleted", console_ns.models[AgentConfigDeleteResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @with_current_user
+ @with_current_tenant_id
+ def delete(self, tenant_id: str, current_user: Account, agent_id: UUID, name: str):
+ return _with_agent_route_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _file_delete_response(target, name),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/files/<string:name>")
+class AgentConfigFileApi(Resource):
+ @console_ns.doc("delete_agent_config_file")
+ @console_ns.doc(
+ params={"app_id": "Application ID", "name": "Config file name", **query_params_from_model(AgentConfigQuery)}
+ )
+ @console_ns.response(200, "Config file deleted", console_ns.models[AgentConfigDeleteResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @with_current_user
+ def delete(self, current_user: Account, app_model: App, name: str):
+ return _with_app_route_target(
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _file_delete_response(target, name),
+ )
+
+
+__all__ = [name for name, value in globals().items() if inspect.isclass(value) and issubclass(value, Resource)]
diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.py
index 16c1a2f570b..2862312c1e3 100644
--- a/api/controllers/console/app/completion.py
+++ b/api/controllers/console/app/completion.py
@@ -1,4 +1,6 @@
+import json
import logging
+from collections.abc import Generator
from typing import Any, Literal
from uuid import UUID
@@ -34,6 +36,7 @@ from controllers.console.wraps import (
)
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
from core.app.entities.app_invoke_entities import InvokeFrom
+from core.app.features.rate_limiting.rate_limit import RateLimitGenerator
from core.errors.error import (
ModelCurrentlyNotSupportError,
ProviderTokenNotInitError,
@@ -106,6 +109,32 @@ class ChatMessagePayload(BaseMessagePayload):
return uuid_value(value)
+_BUILD_CHAT_FINALIZATION_QUERY = """Finalize this Build chat configuration for the agent.
+
+This step is only for persisting Agent config changes discovered in the current Build chat. Do not install packages,
+edit workspace files, run validation or debugging commands, make exploratory checks, or perform other work.
+
+Use only the current Build chat message history to identify changes that need to be persisted. Do not inspect, test, or
+validate old config unless the message history already shows that the old config is invalid.
+
+Persist only the build-draft config resources that need to change, using the Agent config CLI usage provided in the
+runtime prompt:
+
+- config files for reusable artifacts that should be available later,
+- config skills for reusable procedures or tools that should be available later,
+- config env when environment keys or values need to be recorded,
+- config note for concise durable context when useful.
+
+When updating the config note, record only durable context needed by later runs, such as:
+
+- what you installed or configured outside the workspace for this agent,
+- where those external updates live, including CLI tools, packages, and persistent $HOME paths,
+- how the agent should use it in later runs,
+- any setup, authentication, or user action still required.
+
+After config persistence completes, respond FINISHED."""
+
+
register_schema_models(console_ns, CompletionMessagePayload, ChatMessagePayload)
register_response_schema_models(console_ns, GeneratedAppResponse, SimpleResultResponse)
@@ -231,6 +260,31 @@ class AgentChatMessageApi(Resource):
)
+@console_ns.route("/agent/<uuid:agent_id>/build-chat/finalize")
+class AgentBuildChatFinalizeApi(Resource):
+ @console_ns.doc("finalize_agent_build_chat")
+ @console_ns.doc(description="Run a build-draft Agent App turn that asks the agent to push config updates")
+ @console_ns.doc(params={"agent_id": "Agent ID"})
+ @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])
+ @console_ns.response(400, "Invalid request parameters")
+ @console_ns.response(404, "Agent, build draft, or conversation not found")
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, current_tenant_id: str, current_user: Account, agent_id: UUID):
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ return _create_build_chat_finalization_message(
+ current_tenant_id=current_tenant_id,
+ current_user=current_user,
+ app_model=app_model,
+ agent_id=str(agent_id),
+ )
+
+
@console_ns.route("/apps/<uuid:app_id>/chat-messages/<string:task_id>/stop")
class ChatMessageStopApi(Resource):
@console_ns.doc("stop_chat_message")
@@ -284,7 +338,11 @@ def _resolve_current_user_agent_debug_conversation_id(
def _create_chat_message(
- *, current_user: Account, app_model: App, current_tenant_id: str | None = None, agent_id: str | None = None
+ *,
+ current_user: Account,
+ app_model: App,
+ current_tenant_id: str | None = None,
+ agent_id: str | None = None,
):
raw_payload = console_ns.payload or {}
args_model = ChatMessagePayload.model_validate(raw_payload)
@@ -314,12 +372,104 @@ def _create_chat_message(
if external_trace_id:
args["external_trace_id"] = external_trace_id
+ return _generate_chat_message_response(
+ current_user=current_user,
+ app_model=app_model,
+ args=args,
+ streaming=streaming,
+ )
+
+
+def _create_build_chat_finalization_message(
+ *, current_user: Account, app_model: App, current_tenant_id: str, agent_id: str
+):
+ debug_conversation_id = _resolve_current_user_agent_debug_conversation_id(
+ current_tenant_id=current_tenant_id,
+ current_user=current_user,
+ app_model=app_model,
+ agent_id=agent_id,
+ )
+ args: dict[str, Any] = {
+ "query": _BUILD_CHAT_FINALIZATION_QUERY,
+ "inputs": {},
+ "response_mode": "streaming",
+ "draft_type": "debug_build",
+ "conversation_id": debug_conversation_id,
+ "auto_generate_name": False,
+ }
+ external_trace_id = get_external_trace_id(request)
+ if external_trace_id:
+ args["external_trace_id"] = external_trace_id
+
+ response = _generate_chat_message(
+ current_user=current_user,
+ app_model=app_model,
+ args=args,
+ streaming=True,
+ )
+ _drain_streaming_generate_response(response)
+ return {"result": "success"}, 200
+
+
+def _drain_streaming_generate_response(response: RateLimitGenerator | Generator[str, None, None]) -> None:
+ """Consume a streamed app-generate response until a terminal message event arrives.
+
+ Finalize keeps the normal Agent App streaming path so the existing queue,
+ persistence, and runtime-session behavior stay intact. The console API only
+ changes the HTTP boundary: it drains the SSE stream server-side and returns
+ success after the generated build-chat message reaches ``message_end``.
+ """
+ close = getattr(response, "close", None)
try:
- response = AppGenerateService.generate(
- app_model=app_model, user=current_user, args=args, invoke_from=InvokeFrom.DEBUGGER, streaming=streaming
+ for chunk in response:
+ for raw_event in chunk.split("\n\n"):
+ if not raw_event.strip():
+ continue
+
+ event_name: str | None = None
+ data_lines: list[str] = []
+ for line in raw_event.splitlines():
+ if line.startswith("event: "):
+ event_name = line.removeprefix("event: ").strip()
+ elif line.startswith("data: "):
+ data_lines.append(line.removeprefix("data: "))
+
+ if not data_lines:
+ if event_name == "ping":
+ continue
+ continue
+
+ payload = json.loads("\n".join(data_lines))
+ if not isinstance(payload, dict):
+ continue
+
+ payload_event = payload.get("event")
+ if payload_event == "message_end":
+ return
+ if payload_event == "error":
+ raise CompletionRequestError(str(payload.get("message") or "Build chat finalization failed."))
+ finally:
+ if callable(close):
+ close()
+
+ raise CompletionRequestError("Build chat finalization did not complete.")
+
+
+def _generate_chat_message(
+ *,
+ current_user: Account,
+ app_model: App,
+ args: dict[str, Any],
+ streaming: bool,
+):
+ try:
+ return AppGenerateService.generate(
+ app_model=app_model,
+ user=current_user,
+ args=args,
+ invoke_from=InvokeFrom.DEBUGGER,
+ streaming=streaming,
)
-
- return helper.compact_generate_response(response)
except services.errors.conversation.ConversationNotExistsError:
raise NotFound("Conversation Not Exists.")
except services.errors.conversation.ConversationCompletedError:
@@ -335,6 +485,8 @@ def _create_chat_message(
raise ProviderModelCurrentlyNotSupportError()
except InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description)
+ except CompletionRequestError:
+ raise
except InvokeError as e:
raise CompletionRequestError(e.description)
except ValueError as e:
@@ -344,6 +496,22 @@ def _create_chat_message(
raise InternalServerError()
+def _generate_chat_message_response(
+ *,
+ current_user: Account,
+ app_model: App,
+ args: dict[str, Any],
+ streaming: bool,
+):
+ response = _generate_chat_message(
+ current_user=current_user,
+ app_model=app_model,
+ args=args,
+ streaming=streaming,
+ )
+ return helper.compact_generate_response(response)
+
+
def _stop_chat_message(*, current_user_id: str, app_model: App, task_id: str):
AppTaskService.stop_task(
task_id=task_id,
diff --git a/api/controllers/inner_api/__init__.py b/api/controllers/inner_api/__init__.py
index 20fd651b759..f47861cf274 100644
--- a/api/controllers/inner_api/__init__.py
+++ b/api/controllers/inner_api/__init__.py
@@ -17,8 +17,10 @@ inner_api_ns = Namespace("inner_api", description="Internal API operations", pat
from . import mail as _mail
from . import runtime_credentials as _runtime_credentials
+from .agent import tools as _agent_tools
from .app import dsl as _app_dsl
from .knowledge import retrieval as _knowledge_retrieval
+from .plugin import agent_config as _agent_config
from .plugin import agent_drive as _agent_drive
from .plugin import plugin as _plugin
from .workspace import workspace as _workspace
@@ -26,7 +28,9 @@ from .workspace import workspace as _workspace
api.add_namespace(inner_api_ns)
__all__ = [
+ "_agent_config",
"_agent_drive",
+ "_agent_tools",
"_app_dsl",
"_knowledge_retrieval",
"_mail",
diff --git a/api/controllers/inner_api/agent/__init__.py b/api/controllers/inner_api/agent/__init__.py
new file mode 100644
index 00000000000..23adade63b7
--- /dev/null
+++ b/api/controllers/inner_api/agent/__init__.py
@@ -0,0 +1 @@
+"""Agent backend inner API controllers."""
diff --git a/api/controllers/inner_api/agent/tools.py b/api/controllers/inner_api/agent/tools.py
new file mode 100644
index 00000000000..8317a64bc28
--- /dev/null
+++ b/api/controllers/inner_api/agent/tools.py
@@ -0,0 +1,68 @@
+"""Inner API endpoint for Agent core tool invocation."""
+
+from flask_restx import Resource
+from pydantic import ValidationError
+
+from controllers.common.schema import register_response_schema_models, register_schema_models
+from controllers.inner_api import inner_api_ns
+from controllers.inner_api.wraps import agent_inner_api_only
+from extensions.ext_database import db
+from libs.exception import BaseHTTPException
+from services.agent_tool_inner_service import AgentToolInnerService
+from services.entities.agent_tool_inner import AgentToolInvokeRequest, AgentToolInvokeResponse
+from services.errors.agent_tool_inner import AgentToolInnerServiceError
+
+
+class AgentToolInvokeHttpError(BaseHTTPException):
+ error_code = "agent_tool_invoke_failed"
+ description = "Agent tool invocation failed."
+ code = 500
+
+ def __init__(
+ self,
+ *,
+ error_code: str | None = None,
+ description: str | None = None,
+ status_code: int | None = None,
+ ) -> None:
+ if error_code is not None:
+ self.error_code = error_code
+ if description is not None:
+ self.description = description
+ if status_code is not None:
+ self.code = status_code
+ super().__init__(self.description)
+
+
+register_schema_models(inner_api_ns, AgentToolInvokeRequest)
+register_response_schema_models(inner_api_ns, AgentToolInvokeResponse)
+
+
+@inner_api_ns.route("/agent/tools/invoke")
+class AgentToolInvokeApi(Resource):
+ """Invoke one Agent tool through the API-owned core tool runtime path."""
+
+ @agent_inner_api_only
+ @inner_api_ns.doc("inner_agent_tool_invoke")
+ @inner_api_ns.expect(inner_api_ns.models[AgentToolInvokeRequest.__name__])
+ @inner_api_ns.response(200, "Tool invoked successfully", inner_api_ns.models[AgentToolInvokeResponse.__name__])
+ def post(self) -> dict[str, object]:
+ try:
+ payload = AgentToolInvokeRequest.model_validate(inner_api_ns.payload or {})
+ except ValidationError as exc:
+ raise AgentToolInvokeHttpError(
+ error_code="invalid_request",
+ description=str(exc),
+ status_code=400,
+ ) from exc
+
+ try:
+ response = AgentToolInnerService().invoke(payload, session=db.session())
+ except AgentToolInnerServiceError as exc:
+ raise AgentToolInvokeHttpError(
+ error_code=exc.error_code,
+ description=exc.description,
+ status_code=exc.status_code,
+ ) from exc
+
+ return response.model_dump(mode="json")
diff --git a/api/controllers/inner_api/plugin/agent_config.py b/api/controllers/inner_api/plugin/agent_config.py
new file mode 100644
index 00000000000..6f12f6e5d02
--- /dev/null
+++ b/api/controllers/inner_api/plugin/agent_config.py
@@ -0,0 +1,243 @@
+"""Inner API for Agent Soul-backed config assets.
+
+These endpoints are called by the dify-agent server with the inner API key.
+They resolve the requested Agent config version directly from Agent Soul JSON
+and never expose signed download URLs or drive-owned metadata.
+"""
+
+from __future__ import annotations
+
+import io
+
+from flask import request, send_file
+from flask_restx import Resource
+from pydantic import BaseModel, ValidationError
+
+from controllers.console.wraps import setup_required
+from controllers.inner_api import inner_api_ns
+from controllers.inner_api.wraps import plugin_inner_api_only
+from services.agent_config_service import (
+ AgentConfigService,
+ AgentConfigServiceError,
+ AgentConfigVersionKind,
+ ConfigPushPayload,
+)
+
+
+class _ConfigTargetQuery(BaseModel):
+ tenant_id: str
+ user_id: str | None = None
+ config_version_id: str
+ config_version_kind: AgentConfigVersionKind
+
+
+class _ConfigMutationRequest(BaseModel):
+ tenant_id: str
+ user_id: str
+ config_version_id: str
+ config_version_kind: AgentConfigVersionKind
+
+
+class _ConfigPushRequest(_ConfigMutationRequest):
+ files: list[dict] = []
+ skills: list[dict] = []
+ env_text: str | None = None
+ note: str | None = None
+
+ def to_payload(self) -> ConfigPushPayload:
+ return ConfigPushPayload.model_validate(
+ {
+ "files": self.files,
+ "skills": self.skills,
+ "env_text": self.env_text,
+ "note": self.note,
+ }
+ )
+
+
+class _ConfigEnvUpdateRequest(_ConfigMutationRequest):
+ env_text: str
+
+
+class _ConfigNoteUpdateRequest(_ConfigMutationRequest):
+ note: str
+
+
+def _target_query_from_request() -> _ConfigTargetQuery:
+ return _ConfigTargetQuery.model_validate(
+ {
+ "tenant_id": request.args.get("tenant_id"),
+ "user_id": request.args.get("user_id"),
+ "config_version_id": request.args.get("config_version_id"),
+ "config_version_kind": request.args.get("config_version_kind"),
+ }
+ )
+
+
+def _error_response(exc: AgentConfigServiceError) -> tuple[dict[str, str], int]:
+ return {"code": exc.code, "message": exc.message}, exc.status_code
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/manifest")
+class AgentConfigManifestApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_manifest")
+ def get(self, agent_id: str):
+ try:
+ query = _target_query_from_request()
+ return AgentConfigService().manifest(
+ tenant_id=query.tenant_id,
+ agent_id=agent_id,
+ user_id=query.user_id,
+ config_version_id=query.config_version_id,
+ config_version_kind=query.config_version_kind,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/skills/<string:name>/pull")
+class AgentConfigSkillPullApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_skill_pull")
+ def get(self, agent_id: str, name: str):
+ try:
+ query = _target_query_from_request()
+ result = AgentConfigService().pull_skill(
+ tenant_id=query.tenant_id,
+ agent_id=agent_id,
+ user_id=query.user_id,
+ config_version_id=query.config_version_id,
+ config_version_kind=query.config_version_kind,
+ name=name,
+ )
+ return send_file(
+ io.BytesIO(result.payload),
+ mimetype=result.mime_type,
+ as_attachment=True,
+ download_name=result.filename,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/skills/<string:name>/inspect")
+class AgentConfigSkillInspectApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_skill_inspect")
+ def get(self, agent_id: str, name: str):
+ try:
+ query = _target_query_from_request()
+ return AgentConfigService().inspect_skill(
+ tenant_id=query.tenant_id,
+ agent_id=agent_id,
+ user_id=query.user_id,
+ config_version_id=query.config_version_id,
+ config_version_kind=query.config_version_kind,
+ name=name,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/files/<string:name>/pull")
+class AgentConfigFilePullApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_file_pull")
+ def get(self, agent_id: str, name: str):
+ try:
+ query = _target_query_from_request()
+ result = AgentConfigService().pull_file(
+ tenant_id=query.tenant_id,
+ agent_id=agent_id,
+ user_id=query.user_id,
+ config_version_id=query.config_version_id,
+ config_version_kind=query.config_version_kind,
+ name=name,
+ )
+ return send_file(
+ io.BytesIO(result.payload),
+ mimetype=result.mime_type,
+ as_attachment=True,
+ download_name=result.filename,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/push")
+class AgentConfigPushApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_push")
+ def post(self, agent_id: str):
+ try:
+ body = _ConfigPushRequest.model_validate(request.get_json(silent=True) or {})
+ return AgentConfigService().push(
+ tenant_id=body.tenant_id,
+ agent_id=agent_id,
+ user_id=body.user_id,
+ config_version_id=body.config_version_id,
+ config_version_kind=body.config_version_kind,
+ payload=body.to_payload(),
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/env")
+class AgentConfigEnvApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_env")
+ def patch(self, agent_id: str):
+ try:
+ body = _ConfigEnvUpdateRequest.model_validate(request.get_json(silent=True) or {})
+ return AgentConfigService().update_env(
+ tenant_id=body.tenant_id,
+ agent_id=agent_id,
+ user_id=body.user_id,
+ config_version_id=body.config_version_id,
+ config_version_kind=body.config_version_kind,
+ env_text=body.env_text,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
+
+
+@inner_api_ns.route("/agent-config/<string:agent_id>/note")
+class AgentConfigNoteApi(Resource):
+ @setup_required
+ @plugin_inner_api_only
+ @inner_api_ns.doc("agent_config_note")
+ def put(self, agent_id: str):
+ try:
+ body = _ConfigNoteUpdateRequest.model_validate(request.get_json(silent=True) or {})
+ return AgentConfigService().update_note(
+ tenant_id=body.tenant_id,
+ agent_id=agent_id,
+ user_id=body.user_id,
+ config_version_id=body.config_version_id,
+ config_version_kind=body.config_version_kind,
+ note=body.note,
+ )
+ except ValidationError as exc:
+ return {"code": "invalid_request", "message": str(exc)}, 400
+ except AgentConfigServiceError as exc:
+ return _error_response(exc)
diff --git a/api/controllers/inner_api/wraps.py b/api/controllers/inner_api/wraps.py
index 999932c98e1..5ddb55aaa3f 100644
--- a/api/controllers/inner_api/wraps.py
+++ b/api/controllers/inner_api/wraps.py
@@ -95,3 +95,15 @@ def plugin_inner_api_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:
return view(*args, **kwargs)
return decorated
+
+
+def agent_inner_api_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:
+ """Temporary alias for agent-backend inner API callers.
+
+ Agent tool and knowledge calls currently share the same trusted
+ `dify-agent -> Dify API` transport credentials as the plugin inner bridge.
+ Keep the wrapper name agent-specific so the controller surface does not grow
+ more plugin-only semantics while auth settings stay shared.
+ """
+
+ return plugin_inner_api_only(view)
diff --git a/api/core/app/apps/agent_app/app_generator.py b/api/core/app/apps/agent_app/app_generator.py
index 4f2c546fb7b..6e9a7a79af5 100644
--- a/api/core/app/apps/agent_app/app_generator.py
+++ b/api/core/app/apps/agent_app/app_generator.py
@@ -1,21 +1,28 @@
-"""Agent App generator: orchestrate one conversation turn for an Agent App.
+"""Agent App generator: orchestrate Agent App chat and finalize executions.
-Mirrors the agent_chat generator (conversation + message + queue + streamed
-response over the EasyUI chat pipeline), but the backing config comes from the
-bound Agent Soul and the answer is produced by ``AgentAppRunner`` calling the
-dify-agent backend rather than an in-process LLM/ReAct loop.
+The primary mode mirrors the agent_chat generator (conversation + message +
+queue + streamed response over the EasyUI chat pipeline), but the backing
+config comes from the bound Agent Soul and the answer is produced by
+``AgentAppRunner`` calling the dify-agent backend rather than an in-process
+LLM/ReAct loop.
+
+It also exposes a stateless build-finalize mode that reuses existing runtime
+context from the bound debug conversation, triggers the Agent backend side
+effect synchronously, and skips Dify-side chat/message persistence.
"""
from __future__ import annotations
import contextvars
+import json
import logging
import threading
import uuid
-from collections.abc import Generator, Mapping
-from typing import Any
+from collections.abc import Generator, Mapping, Sequence
+from typing import Any, Literal
from flask import Flask, current_app
+from pydantic import JsonValue
from sqlalchemy import and_, or_, select
from clients.agent_backend import AgentBackendRunEventAdapter
@@ -61,6 +68,13 @@ class AgentAppGeneratorError(ValueError):
"""Raised when an Agent App turn cannot be set up."""
+def _append_prompt_file_mappings(query: str, prompt_file_mappings: Sequence[JsonValue]) -> str:
+ """Append raw request file references to the backend user prompt."""
+ if not prompt_file_mappings:
+ return query
+ return f"{query}\n{json.dumps(list(prompt_file_mappings), ensure_ascii=False)}"
+
+
class AgentAppGenerator(MessageBasedAppGenerator):
def generate(
self,
@@ -74,14 +88,12 @@ class AgentAppGenerator(MessageBasedAppGenerator):
if not streaming:
raise AgentAppGeneratorError("Agent App only supports streaming mode")
- query = args.get("query")
- if not isinstance(query, str) or not query.strip():
- raise AgentAppGeneratorError("query is required")
- query = query.replace("\x00", "")
+ query = self._require_query(args)
inputs = args["inputs"]
+ prompt_file_mappings = args.get("files") or []
# Resolve the bound roster Agent + its current Agent Soul snapshot.
- agent, agent_config_id, agent_soul = self._resolve_agent(
+ agent, agent_config_id, agent_config_version_kind, agent_soul = self._resolve_agent(
app_model,
invoke_from=invoke_from,
draft_type=args.get("draft_type"),
@@ -122,6 +134,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
),
query=query,
files=[],
+ prompt_file_mappings=prompt_file_mappings,
parent_message_id=(
args.get("parent_message_id")
if invoke_from not in {InvokeFrom.SERVICE_API, InvokeFrom.OPENAPI}
@@ -137,6 +150,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
trace_manager=trace_manager,
agent_id=agent.id,
agent_config_snapshot_id=agent_config_id,
+ agent_config_version_kind=agent_config_version_kind,
agent_runtime_session_snapshot_id=runtime_session_snapshot_id,
)
@@ -176,6 +190,86 @@ class AgentAppGenerator(MessageBasedAppGenerator):
)
return AgentAppGenerateResponseConverter.convert(response=response, invoke_from=invoke_from)
+ def generate_stateless(
+ self,
+ *,
+ app_model: App,
+ user: Account | EndUser,
+ args: Mapping[str, Any],
+ invoke_from: InvokeFrom,
+ ) -> Mapping[str, Any]:
+ """Run one Agent App turn without persisting Dify conversation messages."""
+ query = self._require_query(args)
+ conversation_id = args.get("conversation_id")
+ if not isinstance(conversation_id, str) or not conversation_id:
+ raise AgentAppGeneratorError("conversation_id is required")
+
+ agent, agent_config_id, agent_config_version_kind, agent_soul = self._resolve_agent(
+ app_model,
+ invoke_from=invoke_from,
+ draft_type=args.get("draft_type"),
+ user=user,
+ )
+ runtime_session_snapshot_id = self._runtime_session_snapshot_id(
+ invoke_from=invoke_from,
+ snapshot_id=agent_config_id,
+ )
+
+ return self._run_stateless(
+ app_model=app_model,
+ user=user,
+ invoke_from=invoke_from,
+ query=query,
+ conversation_id=conversation_id,
+ agent=agent,
+ agent_config_id=agent_config_id,
+ agent_config_version_kind=agent_config_version_kind,
+ agent_soul=agent_soul,
+ runtime_session_snapshot_id=runtime_session_snapshot_id,
+ )
+
+ def _run_stateless(
+ self,
+ *,
+ app_model: App,
+ user: Account | EndUser,
+ invoke_from: InvokeFrom,
+ query: str,
+ conversation_id: str,
+ agent: Agent,
+ agent_config_id: str,
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"],
+ agent_soul: AgentSoulConfig,
+ runtime_session_snapshot_id: str | None,
+ ) -> Mapping[str, Any]:
+ """Run the Agent backend without creating or updating Dify chat records.
+
+ Build-chat finalization is an action against the Agent backend (for
+ example, ``dify-agent config push``). It may reuse the active build-chat
+ runtime snapshot for shell/config context, but the API side must not add
+ a synthetic user/assistant turn to the debug conversation.
+ """
+
+ dify_context = DifyRunContext(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ user_id=user.id,
+ user_from=UserFrom.ACCOUNT if isinstance(user, Account) else UserFrom.END_USER,
+ invoke_from=invoke_from,
+ )
+ self._build_runner(dify_context).run_stateless(
+ dify_context=dify_context,
+ agent_id=agent.id,
+ agent_config_snapshot_id=agent_config_id,
+ agent_config_version_kind=agent_config_version_kind,
+ agent_soul=agent_soul,
+ conversation_id=conversation_id,
+ query=query,
+ idempotency_key=str(uuid.uuid4()),
+ session_scope_snapshot_id=runtime_session_snapshot_id,
+ )
+ return {"result": "success"}
+
def resume_after_form_submission(
self,
*,
@@ -192,15 +286,15 @@ class AgentAppGenerator(MessageBasedAppGenerator):
persisted to the conversation. Live streaming to a reconnected client is
out of scope here — the message is persisted and can be re-fetched.
"""
- agent, agent_config_id, agent_soul = self._resolve_agent(
+ conversation = ConversationService.get_conversation(
+ app_model=app_model, conversation_id=conversation_id, user=user
+ )
+ agent, agent_config_id, agent_config_version_kind, agent_soul = self._resolve_agent(
app_model,
invoke_from=invoke_from,
- draft_type="draft",
+ draft_type=self._resume_draft_type(app_model=app_model, conversation=conversation, user=user),
user=user,
)
- conversation = ConversationService.get_conversation(
- app_model=app_model, conversation_id=conversation_id, user=user
- )
app_config = AgentAppConfigManager.get_app_config(
app_model=app_model,
@@ -245,6 +339,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
trace_manager=trace_manager,
agent_id=agent.id,
agent_config_snapshot_id=agent_config_id,
+ agent_config_version_kind=agent_config_version_kind,
)
conversation, message = self._init_generate_records(application_generate_entity, conversation)
@@ -285,6 +380,30 @@ class AgentAppGenerator(MessageBasedAppGenerator):
stream=False,
)
+ @staticmethod
+ def _resume_draft_type(*, app_model: App, conversation: Any, user: Account | EndUser) -> str | None:
+ if conversation.invoke_from != InvokeFrom.DEBUGGER:
+ return None
+ active_session = AgentAppRuntimeSessionStore().load_active_session_for_conversation(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ conversation_id=conversation.id,
+ )
+ snapshot_id = active_session.scope.agent_config_snapshot_id if active_session is not None else None
+ if snapshot_id and isinstance(user, Account):
+ draft = db.session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == app_model.tenant_id,
+ AgentConfigDraft.id == snapshot_id,
+ )
+ )
+ if draft is not None:
+ if draft.draft_type == AgentConfigDraftType.DEBUG_BUILD and draft.account_id == user.id:
+ return AgentConfigDraftType.DEBUG_BUILD.value
+ if draft.draft_type == AgentConfigDraftType.DRAFT and draft.account_id is None:
+ return AgentConfigDraftType.DRAFT.value
+ return AgentConfigDraftType.DRAFT.value
+
def _generate_worker(
self,
*,
@@ -329,6 +448,10 @@ class AgentAppGenerator(MessageBasedAppGenerator):
)
if handled:
return
+ query = _append_prompt_file_mappings(
+ query=query,
+ prompt_file_mappings=application_generate_entity.prompt_file_mappings,
+ )
dify_context = DifyRunContext(
tenant_id=app_config.tenant_id,
@@ -337,27 +460,18 @@ class AgentAppGenerator(MessageBasedAppGenerator):
user_from=user_from,
invoke_from=application_generate_entity.invoke_from,
)
- credentials_provider, _ = build_dify_model_access(dify_context)
_, _, agent_soul = self._resolve_agent_by_id(
tenant_id=app_config.tenant_id,
agent_id=application_generate_entity.agent_id,
snapshot_id=application_generate_entity.agent_config_snapshot_id,
)
- runner = AgentAppRunner(
- request_builder=AgentAppRuntimeRequestBuilder(credentials_provider=credentials_provider),
- agent_backend_client=create_agent_backend_run_client(
- base_url=dify_config.AGENT_BACKEND_BASE_URL,
- use_fake=dify_config.AGENT_BACKEND_USE_FAKE,
- fake_scenario=dify_config.AGENT_BACKEND_FAKE_SCENARIO,
- ),
- event_adapter=AgentBackendRunEventAdapter(),
- session_store=AgentAppRuntimeSessionStore(),
- )
+ runner = self._build_runner(dify_context)
runner.run(
dify_context=dify_context,
agent_id=application_generate_entity.agent_id,
agent_config_snapshot_id=application_generate_entity.agent_config_snapshot_id,
+ agent_config_version_kind=application_generate_entity.agent_config_version_kind,
agent_soul=agent_soul,
conversation_id=conversation.id,
query=query,
@@ -374,6 +488,27 @@ class AgentAppGenerator(MessageBasedAppGenerator):
finally:
db.session.close()
+ @staticmethod
+ def _require_query(args: Mapping[str, Any]) -> str:
+ query = args.get("query")
+ if not isinstance(query, str) or not query.strip():
+ raise AgentAppGeneratorError("query is required")
+ return query.replace("\x00", "")
+
+ @staticmethod
+ def _build_runner(dify_context: DifyRunContext) -> AgentAppRunner:
+ credentials_provider, _ = build_dify_model_access(dify_context)
+ return AgentAppRunner(
+ request_builder=AgentAppRuntimeRequestBuilder(credentials_provider=credentials_provider),
+ agent_backend_client=create_agent_backend_run_client(
+ base_url=dify_config.AGENT_BACKEND_BASE_URL,
+ use_fake=dify_config.AGENT_BACKEND_USE_FAKE,
+ fake_scenario=dify_config.AGENT_BACKEND_FAKE_SCENARIO,
+ ),
+ event_adapter=AgentBackendRunEventAdapter(),
+ session_store=AgentAppRuntimeSessionStore(),
+ )
+
def _run_input_guards(
self,
*,
@@ -446,7 +581,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
invoke_from: InvokeFrom,
draft_type: Any,
user: Account | EndUser,
- ) -> tuple[Agent, str, AgentSoulConfig]:
+ ) -> tuple[Agent, str, Literal["snapshot", "draft", "build_draft"], AgentSoulConfig]:
agent = db.session.scalar(
select(Agent)
.where(
@@ -474,13 +609,16 @@ class AgentAppGenerator(MessageBasedAppGenerator):
account_id=user.id if isinstance(user, Account) else None,
)
agent_soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
- return agent, draft.id, agent_soul
+ config_version_kind: Literal["snapshot", "draft", "build_draft"] = (
+ "build_draft" if draft.draft_type == AgentConfigDraftType.DEBUG_BUILD else "draft"
+ )
+ return agent, draft.id, config_version_kind, agent_soul
_, snapshot, agent_soul = self._resolve_agent_by_id(
tenant_id=app_model.tenant_id,
agent_id=agent.id,
snapshot_id=agent.active_config_snapshot_id,
)
- return agent, snapshot.id, agent_soul
+ return agent, snapshot.id, "snapshot", agent_soul
@staticmethod
def _runtime_session_snapshot_id(*, invoke_from: InvokeFrom, snapshot_id: str) -> str | None:
diff --git a/api/core/app/apps/agent_app/app_runner.py b/api/core/app/apps/agent_app/app_runner.py
index b482afcdf43..d90dad1f891 100644
--- a/api/core/app/apps/agent_app/app_runner.py
+++ b/api/core/app/apps/agent_app/app_runner.py
@@ -1,18 +1,23 @@
-"""Agent App runner: drive one conversation turn through the dify-agent backend.
+"""Agent App runner: drive Agent backend turns for both chat and finalize flows.
Unlike the legacy ``AgentChatAppRunner`` (which runs an in-process ReAct loop),
-this runner delegates to the Agent backend: build the run request from the
-Agent Soul + conversation, create the run, consume its event stream, and
-republish the assistant answer as chat queue events so the existing
-EasyUI chat task pipeline persists the message and streams SSE. The conversation
-``session_snapshot`` is saved on success for multi-turn continuity (S3).
+this runner delegates to the Agent backend and supports two execution modes.
+
+- Normal chat turns build the run request from the Agent Soul + conversation,
+ consume backend stream events, republish the assistant answer through the
+ existing EasyUI chat task pipeline, and save the conversation
+ ``session_snapshot`` on success for multi-turn continuity (S3).
+- Stateless build-finalize turns reuse any prior conversation snapshot only to
+ construct the backend request, wait synchronously for backend completion, and
+ intentionally do not persist Dify-side chat records or runtime-session state.
"""
from __future__ import annotations
import json
import logging
-from typing import Any
+from decimal import Decimal
+from typing import Any, Literal
from dify_agent.layers.ask_human import AskHumanToolArgs
from dify_agent.protocol import DeferredToolResultsPayload
@@ -28,6 +33,7 @@ from clients.agent_backend import (
AgentBackendStreamInternalEvent,
extract_runtime_layer_specs,
)
+from configs import dify_config
from core.app.apps.agent_app.runtime_request_builder import (
AgentAppRuntimeBuildContext,
AgentAppRuntimeRequest,
@@ -41,13 +47,16 @@ from core.app.apps.agent_app.session_store import (
from core.app.apps.base_app_queue_manager import AppQueueManager, PublishFrom
from core.app.apps.exc import GenerateTaskStoppedError
from core.app.entities.app_invoke_entities import DifyRunContext
-from core.app.entities.queue_entities import QueueLLMChunkEvent, QueueMessageEndEvent
+from core.app.entities.queue_entities import QueueAgentThoughtEvent, QueueLLMChunkEvent, QueueMessageEndEvent
from core.repositories.human_input_repository import HumanInputFormRepository, HumanInputFormRepositoryImpl
from core.workflow.nodes.agent_v2.ask_human_hitl import AskHumanFormBuildError, create_ask_human_form
from core.workflow.nodes.agent_v2.ask_human_resume import build_deferred_tool_results, resolve_ask_human_form
+from extensions.ext_database import db
from graphon.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
from graphon.model_runtime.entities.message_entities import AssistantPromptMessage, PromptMessage, UserPromptMessage
from models.agent_config_entities import AgentSoulConfig
+from models.enums import CreatorUserRole
+from models.model import MessageAgentThought
logger = logging.getLogger(__name__)
@@ -134,6 +143,283 @@ def publish_message_end(
)
+class _AgentProcessRecorder:
+ """Persist Agent v2 thinking/tool process events through the legacy thought model."""
+
+ def __init__(
+ self,
+ *,
+ dify_context: DifyRunContext,
+ message_id: str,
+ queue_manager: AppQueueManager,
+ ) -> None:
+ self._dify_context = dify_context
+ self._message_id = message_id
+ self._queue_manager = queue_manager
+ self._next_position = 1
+ self._thinking_by_index: dict[int, str] = {}
+ self._tool_by_index: dict[int, str] = {}
+ self._tool_by_call_id: dict[str, str] = {}
+ self._open_tool_by_name: dict[str, set[str]] = {}
+
+ def handle_stream_event(self, event: AgentBackendStreamInternalEvent) -> None:
+ data = event.data
+ if not isinstance(data, dict):
+ return
+
+ event_kind = data.get("event_kind")
+ if event_kind == "part_delta":
+ self._handle_part_delta(data)
+ elif event_kind == "part_start":
+ self._handle_part(data)
+ elif event_kind in {"function_tool_call", "output_tool_call"}:
+ self._handle_tool_call_event(data)
+ elif event_kind in {"function_tool_result", "output_tool_result"}:
+ self._handle_tool_result_event(data)
+
+ def _handle_part_delta(self, data: dict[str, Any]) -> None:
+ delta = data.get("delta")
+ if not isinstance(delta, dict):
+ return
+
+ index = _event_index(data)
+ delta_kind = delta.get("part_delta_kind")
+ if delta_kind == "thinking":
+ content_delta = delta.get("content_delta")
+ if isinstance(content_delta, str) and content_delta:
+ self._append_thinking(index, content_delta)
+ return
+
+ if delta_kind == "tool_call":
+ self._record_tool_call_delta(index, delta)
+
+ def _handle_part(self, data: dict[str, Any]) -> None:
+ part = data.get("part")
+ if not isinstance(part, dict):
+ return
+
+ index = _event_index(data)
+ part_kind = part.get("part_kind")
+ if part_kind == "thinking":
+ content = part.get("content")
+ if isinstance(content, str) and content:
+ self._append_thinking(index, content)
+ return
+
+ if part_kind in {"tool-call", "builtin-tool-call"}:
+ self._record_tool_call_part(index, part)
+ return
+
+ if part_kind in {"tool-return", "builtin-tool-return"}:
+ self._record_tool_return_part(part)
+
+ def _handle_tool_call_event(self, data: dict[str, Any]) -> None:
+ part = data.get("part")
+ if isinstance(part, dict):
+ self._record_tool_call_part(_event_index(data), part)
+
+ def _handle_tool_result_event(self, data: dict[str, Any]) -> None:
+ part = data.get("part") or data.get("result")
+ if isinstance(part, dict):
+ self._record_tool_return_part(part)
+ return
+
+ content = data.get("content")
+ if content is not None:
+ self._record_tool_observation(
+ tool_call_id=_string_or_none(data.get("tool_call_id")),
+ tool_name=_string_or_none(data.get("tool_name")),
+ observation=content,
+ )
+
+ def _append_thinking(self, index: int, content_delta: str) -> None:
+ thought_id = self._thinking_by_index.get(index)
+ if thought_id is None:
+ thought_id = self._create_thought(thought=content_delta)
+ self._thinking_by_index[index] = thought_id
+ return
+ self._update_thought(thought_id, thought_delta=content_delta)
+
+ def _record_tool_call_delta(self, index: int, delta: dict[str, Any]) -> None:
+ tool_call_id = _string_or_none(delta.get("tool_call_id"))
+ tool_name = _string_or_none(delta.get("tool_name_delta"))
+ args_delta = delta.get("args_delta")
+ thought_id = self._lookup_tool_thought(index=index, tool_call_id=tool_call_id)
+ if thought_id is None:
+ thought_id = self._create_thought(tool=tool_name, tool_input=_json_or_text(args_delta))
+ self._remember_tool_thought(
+ index=index, tool_call_id=tool_call_id, tool_name=tool_name, thought_id=thought_id
+ )
+ return
+
+ self._update_thought(
+ thought_id,
+ tool=tool_name,
+ tool_input_delta=_json_or_text(args_delta),
+ )
+
+ def _record_tool_call_part(self, index: int, part: dict[str, Any]) -> None:
+ tool_call_id = _string_or_none(part.get("tool_call_id"))
+ tool_name = _string_or_none(part.get("tool_name"))
+ thought_id = self._lookup_tool_thought(index=index, tool_call_id=tool_call_id)
+ if thought_id is None:
+ thought_id = self._create_thought(tool=tool_name, tool_input=_json_or_text(part.get("args")))
+ self._remember_tool_thought(
+ index=index, tool_call_id=tool_call_id, tool_name=tool_name, thought_id=thought_id
+ )
+ return
+
+ self._update_thought(
+ thought_id,
+ tool=tool_name,
+ tool_input=_json_or_text(part.get("args")),
+ )
+
+ def _record_tool_return_part(self, part: dict[str, Any]) -> None:
+ tool_call_id = _string_or_none(part.get("tool_call_id"))
+ tool_name = _string_or_none(part.get("tool_name"))
+ content = part.get("content")
+ if content is None:
+ content = part
+ self._record_tool_observation(tool_call_id=tool_call_id, tool_name=tool_name, observation=content)
+
+ def _record_tool_observation(self, *, tool_call_id: str | None, tool_name: str | None, observation: Any) -> None:
+ thought_id = self._lookup_observation_thought(tool_call_id=tool_call_id, tool_name=tool_name)
+ if thought_id is None:
+ thought_id = self._create_thought(tool=tool_name)
+ else:
+ self._mark_tool_observed(thought_id)
+ self._update_thought(thought_id, observation=_json_or_text(observation))
+
+ def _lookup_tool_thought(self, *, index: int, tool_call_id: str | None) -> str | None:
+ if tool_call_id and tool_call_id in self._tool_by_call_id:
+ return self._tool_by_call_id[tool_call_id]
+ return self._tool_by_index.get(index)
+
+ def _remember_tool_thought(
+ self, *, index: int, tool_call_id: str | None, tool_name: str | None, thought_id: str
+ ) -> None:
+ self._tool_by_index[index] = thought_id
+ if tool_call_id:
+ self._tool_by_call_id[tool_call_id] = thought_id
+ if tool_name:
+ self._open_tool_by_name.setdefault(tool_name, set()).add(thought_id)
+
+ def _lookup_observation_thought(self, *, tool_call_id: str | None, tool_name: str | None) -> str | None:
+ if tool_call_id:
+ return self._tool_by_call_id.get(tool_call_id)
+ if tool_name:
+ open_thought_ids = self._open_tool_by_name.get(tool_name, set())
+ if len(open_thought_ids) == 1:
+ return next(iter(open_thought_ids))
+ return None
+
+ def _mark_tool_observed(self, thought_id: str) -> None:
+ for open_thought_ids in self._open_tool_by_name.values():
+ open_thought_ids.discard(thought_id)
+
+ def _create_thought(
+ self, *, thought: str | None = None, tool: str | None = None, tool_input: str | None = None
+ ) -> str:
+ row = MessageAgentThought(
+ message_id=self._message_id,
+ message_chain_id=None,
+ thought=thought,
+ tool=tool,
+ tool_labels_str=_tool_labels(tool),
+ tool_meta_str="{}",
+ tool_input=tool_input,
+ observation=None,
+ tool_process_data=None,
+ message=None,
+ message_token=0,
+ message_unit_price=Decimal(0),
+ message_price_unit=Decimal("0.001"),
+ message_files="",
+ answer="",
+ answer_token=0,
+ answer_unit_price=Decimal(0),
+ answer_price_unit=Decimal("0.001"),
+ tokens=0,
+ total_price=Decimal(0),
+ position=self._next_position,
+ currency="USD",
+ latency=0,
+ created_by_role=self._created_by_role(),
+ created_by=self._dify_context.user_id,
+ )
+ self._next_position += 1
+ db.session.add(row)
+ db.session.commit()
+ thought_id = str(row.id)
+ self._queue_manager.publish(
+ QueueAgentThoughtEvent(agent_thought_id=thought_id), PublishFrom.APPLICATION_MANAGER
+ )
+ return thought_id
+
+ def _update_thought(
+ self,
+ thought_id: str,
+ *,
+ thought_delta: str | None = None,
+ tool: str | None = None,
+ tool_input: str | None = None,
+ tool_input_delta: str | None = None,
+ observation: str | None = None,
+ ) -> None:
+ row = db.session.get(MessageAgentThought, thought_id)
+ if row is None:
+ return
+
+ if thought_delta:
+ row.thought = f"{row.thought or ''}{thought_delta}"
+ if tool:
+ row.tool = tool
+ row.tool_labels_str = _tool_labels(tool)
+ if tool_input is not None:
+ row.tool_input = tool_input
+ if tool_input_delta:
+ row.tool_input = f"{row.tool_input or ''}{tool_input_delta}"
+ if observation is not None:
+ row.observation = observation
+
+ db.session.commit()
+ self._queue_manager.publish(
+ QueueAgentThoughtEvent(agent_thought_id=thought_id), PublishFrom.APPLICATION_MANAGER
+ )
+
+ def _created_by_role(self) -> CreatorUserRole:
+ if self._dify_context.invoke_from.runs_as_account():
+ return CreatorUserRole.ACCOUNT
+ return CreatorUserRole.END_USER
+
+
+def _event_index(data: dict[str, Any]) -> int:
+ index = data.get("index")
+ return index if isinstance(index, int) else -1
+
+
+def _string_or_none(value: Any) -> str | None:
+ return value if isinstance(value, str) and value else None
+
+
+def _json_or_text(value: Any) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ try:
+ return json.dumps(value, ensure_ascii=False)
+ except Exception:
+ return str(value)
+
+
+def _tool_labels(tool: str | None) -> str:
+ if not tool:
+ return "{}"
+ return json.dumps({tool: {"en_US": tool, "zh_Hans": tool}}, ensure_ascii=False)
+
+
class AgentAppRunner:
"""Runs one Agent App conversation turn against the Agent backend."""
@@ -156,6 +442,7 @@ class AgentAppRunner:
dify_context: DifyRunContext,
agent_id: str,
agent_config_snapshot_id: str,
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot",
agent_soul: AgentSoulConfig,
conversation_id: str,
query: str,
@@ -164,42 +451,34 @@ class AgentAppRunner:
queue_manager: AppQueueManager,
session_scope_snapshot_id: str | None | _DefaultSessionScopeSnapshotId = _DEFAULT_SESSION_SCOPE_SNAPSHOT_ID,
) -> None:
- if isinstance(session_scope_snapshot_id, _DefaultSessionScopeSnapshotId):
- effective_session_scope_snapshot_id: str | None = agent_config_snapshot_id
- else:
- effective_session_scope_snapshot_id = session_scope_snapshot_id
- scope = AgentAppSessionScope(
- tenant_id=dify_context.tenant_id,
- app_id=dify_context.app_id,
- conversation_id=conversation_id,
+ scope = self._build_session_scope(
+ dify_context=dify_context,
agent_id=agent_id,
- agent_config_snapshot_id=effective_session_scope_snapshot_id,
+ agent_config_snapshot_id=agent_config_snapshot_id,
+ conversation_id=conversation_id,
+ session_scope_snapshot_id=session_scope_snapshot_id,
)
# ENG-638: if a prior turn paused on ask_human and the form is now answered,
# resume by threading the human's reply into this run as deferred_tool_results.
stored = self._session_store.load_active_session(scope)
- session_snapshot = stored.session_snapshot if stored is not None else None
- deferred_tool_results = self._resolve_pending_ask_human(
- stored=stored, dify_context=dify_context, message_id=message_id
- )
-
- runtime = self._request_builder.build(
- AgentAppRuntimeBuildContext(
- dify_context=dify_context,
- agent_id=agent_id,
- agent_config_snapshot_id=agent_config_snapshot_id,
- agent_soul=agent_soul,
- conversation_id=conversation_id,
- user_query=query,
- idempotency_key=message_id,
- session_snapshot=session_snapshot,
- deferred_tool_results=deferred_tool_results,
- )
+ runtime = self._build_runtime(
+ dify_context=dify_context,
+ agent_id=agent_id,
+ agent_config_snapshot_id=agent_config_snapshot_id,
+ agent_config_version_kind=agent_config_version_kind,
+ agent_soul=agent_soul,
+ conversation_id=conversation_id,
+ query=query,
+ idempotency_key=message_id,
+ stored=stored,
+ message_id=message_id,
)
create_response = self._agent_backend_client.create_run(runtime.request)
terminal, streamed_answer = self._consume_stream(
create_response.run_id,
+ dify_context=dify_context,
+ message_id=message_id,
queue_manager=queue_manager,
model_name=model_name,
query=query,
@@ -241,6 +520,111 @@ class AgentAppRunner:
runtime_layer_specs=extract_runtime_layer_specs(runtime.request.composition),
)
+ def run_stateless(
+ self,
+ *,
+ dify_context: DifyRunContext,
+ agent_id: str,
+ agent_config_snapshot_id: str,
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot",
+ agent_soul: AgentSoulConfig,
+ conversation_id: str,
+ query: str,
+ idempotency_key: str,
+ session_scope_snapshot_id: str | None | _DefaultSessionScopeSnapshotId = _DEFAULT_SESSION_SCOPE_SNAPSHOT_ID,
+ ) -> None:
+ """Run the Agent backend without creating Dify chat message records.
+
+ This path is used by build-chat finalization: the API must trigger the
+ backend side effects in the existing conversation session, but it must
+ not persist a synthetic user/assistant turn, update API-side runtime
+ session rows, or set up HITL state that depends on one.
+ """
+ scope = self._build_session_scope(
+ dify_context=dify_context,
+ agent_id=agent_id,
+ agent_config_snapshot_id=agent_config_snapshot_id,
+ conversation_id=conversation_id,
+ session_scope_snapshot_id=session_scope_snapshot_id,
+ )
+ runtime = self._build_runtime(
+ dify_context=dify_context,
+ agent_id=agent_id,
+ agent_config_snapshot_id=agent_config_snapshot_id,
+ agent_config_version_kind=agent_config_version_kind,
+ agent_soul=agent_soul,
+ conversation_id=conversation_id,
+ query=query,
+ idempotency_key=idempotency_key,
+ stored=self._session_store.load_active_session(scope),
+ message_id=None,
+ )
+
+ create_response = self._agent_backend_client.create_run(runtime.request)
+ status = self._agent_backend_client.wait_run(
+ create_response.run_id,
+ timeout_seconds=dify_config.APP_MAX_EXECUTION_TIME,
+ )
+ if status.status != "succeeded":
+ error = getattr(status, "error", None) or f"Agent backend run ended with status {status.status}."
+ raise AgentBackendError(str(error))
+
+ def _build_session_scope(
+ self,
+ *,
+ dify_context: DifyRunContext,
+ agent_id: str,
+ agent_config_snapshot_id: str,
+ conversation_id: str,
+ session_scope_snapshot_id: str | None | _DefaultSessionScopeSnapshotId,
+ ) -> AgentAppSessionScope:
+ if isinstance(session_scope_snapshot_id, _DefaultSessionScopeSnapshotId):
+ effective_session_scope_snapshot_id: str | None = agent_config_snapshot_id
+ else:
+ effective_session_scope_snapshot_id = session_scope_snapshot_id
+ return AgentAppSessionScope(
+ tenant_id=dify_context.tenant_id,
+ app_id=dify_context.app_id,
+ conversation_id=conversation_id,
+ agent_id=agent_id,
+ agent_config_snapshot_id=effective_session_scope_snapshot_id,
+ )
+
+ def _build_runtime(
+ self,
+ *,
+ dify_context: DifyRunContext,
+ agent_id: str,
+ agent_config_snapshot_id: str,
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"],
+ agent_soul: AgentSoulConfig,
+ conversation_id: str,
+ query: str,
+ idempotency_key: str,
+ stored: StoredAgentAppSession | None,
+ message_id: str | None,
+ ) -> AgentAppRuntimeRequest:
+ session_snapshot = stored.session_snapshot if stored is not None else None
+ deferred_tool_results = (
+ self._resolve_pending_ask_human(stored=stored, dify_context=dify_context, message_id=message_id)
+ if message_id is not None
+ else None
+ )
+ return self._request_builder.build(
+ AgentAppRuntimeBuildContext(
+ dify_context=dify_context,
+ agent_id=agent_id,
+ agent_config_snapshot_id=agent_config_snapshot_id,
+ agent_config_version_kind=agent_config_version_kind,
+ agent_soul=agent_soul,
+ conversation_id=conversation_id,
+ user_query=query,
+ idempotency_key=idempotency_key,
+ session_snapshot=session_snapshot,
+ deferred_tool_results=deferred_tool_results,
+ )
+ )
+
def _pause_for_ask_human(
self,
*,
@@ -334,12 +718,19 @@ class AgentAppRunner:
self,
run_id: str,
*,
+ dify_context: DifyRunContext,
+ message_id: str,
queue_manager: AppQueueManager,
model_name: str,
query: str | None,
):
terminal = None
streamed_answer_parts: list[str] = []
+ process_recorder = _AgentProcessRecorder(
+ dify_context=dify_context,
+ message_id=message_id,
+ queue_manager=queue_manager,
+ )
for public_event in self._agent_backend_client.stream_events(run_id):
if queue_manager.is_stopped():
self._cancel_run(run_id)
@@ -353,6 +744,17 @@ class AgentAppRunner:
AgentBackendInternalEventType.STREAM_EVENT,
):
if isinstance(internal_event, AgentBackendStreamInternalEvent):
+ try:
+ process_recorder.handle_stream_event(internal_event)
+ except Exception:
+ db.session.rollback()
+ logger.warning(
+ "Failed to persist Agent App process event: run_id=%s message_id=%s event_kind=%s",
+ run_id,
+ message_id,
+ internal_event.event_kind,
+ exc_info=True,
+ )
text_delta = self._extract_stream_text_delta(internal_event)
if text_delta:
streamed_answer_parts.append(text_delta)
diff --git a/api/core/app/apps/agent_app/runtime_request_builder.py b/api/core/app/apps/agent_app/runtime_request_builder.py
index 9790f2fbca0..4e850a4887a 100644
--- a/api/core/app/apps/agent_app/runtime_request_builder.py
+++ b/api/core/app/apps/agent_app/runtime_request_builder.py
@@ -12,7 +12,7 @@ from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
-from typing import Any, Protocol, cast
+from typing import Any, Literal, Protocol, cast
from agenton.compositor import CompositorSessionSnapshot
from dify_agent.layers.execution_context import (
@@ -29,20 +29,22 @@ from clients.agent_backend import (
redact_for_agent_backend_log,
)
from configs import dify_config
-from core.app.entities.app_invoke_entities import DifyRunContext
-from core.workflow.nodes.agent_v2.plugin_tools_builder import (
- WorkflowAgentPluginToolsBuilder,
- WorkflowAgentPluginToolsBuildError,
+from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom
+from core.workflow.nodes.agent_v2.dify_tools_builder import (
+ WorkflowAgentDifyToolLayersBuilder,
+ WorkflowAgentDifyToolsBuilder,
+ WorkflowAgentDifyToolsBuildError,
+ WorkflowAgentToolLayers,
)
from core.workflow.nodes.agent_v2.runtime_request_builder import (
append_runtime_warnings,
build_ask_human_layer_config,
- build_drive_aware_soul_mention_resolver,
- build_drive_layer_config,
+ build_config_aware_soul_mention_resolver,
+ build_config_layer_config,
build_knowledge_layer_config,
build_shell_layer_config,
)
-from models.agent_config_entities import AgentSoulConfig
+from models.agent_config_entities import AgentSoulConfig, AgentSoulToolsConfig
from models.provider_ids import ModelProviderID
from services.agent.prompt_mentions import build_soul_mention_resolver, expand_prompt_mentions
@@ -68,6 +70,7 @@ class AgentAppRuntimeBuildContext:
conversation_id: str
user_query: str
idempotency_key: str
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot"
session_snapshot: CompositorSessionSnapshot | None = None
# ENG-638: set when resuming a chat turn after a submitted ask_human form.
deferred_tool_results: DeferredToolResultsPayload | None = None
@@ -88,11 +91,11 @@ class AgentAppRuntimeRequestBuilder:
*,
credentials_provider: CredentialsProvider,
request_builder: AgentBackendRunRequestBuilder | None = None,
- plugin_tools_builder: WorkflowAgentPluginToolsBuilder | None = None,
+ dify_tools_builder: WorkflowAgentDifyToolLayersBuilder | None = None,
) -> None:
self._credentials_provider = credentials_provider
self._request_builder = request_builder or AgentBackendRunRequestBuilder()
- self._plugin_tools_builder = plugin_tools_builder or WorkflowAgentPluginToolsBuilder()
+ self._dify_tools_builder = dify_tools_builder or WorkflowAgentDifyToolsBuilder()
def build(self, context: AgentAppRuntimeBuildContext) -> AgentAppRuntimeRequest:
agent_soul = context.agent_soul
@@ -105,38 +108,33 @@ class AgentAppRuntimeRequestBuilder:
metadata = self._build_metadata(context)
credentials = self._credentials_provider.fetch(agent_soul.model.model_provider, agent_soul.model.model)
try:
- tools_layer = self._plugin_tools_builder.build(
+ tool_layers = self._build_tool_layers(
tenant_id=context.dify_context.tenant_id,
app_id=context.dify_context.app_id,
user_id=context.dify_context.user_id,
tools=agent_soul.tools,
invoke_from=context.dify_context.invoke_from,
)
- except WorkflowAgentPluginToolsBuildError as error:
+ except WorkflowAgentDifyToolsBuildError as error:
raise AgentAppRuntimeRequestBuildError(error.error_code, str(error)) from error
- if tools_layer is not None or agent_soul.tools.cli_tools:
+ if tool_layers.plugin_tools is not None or tool_layers.core_tools is not None or agent_soul.tools.cli_tools:
metadata["agent_tools"] = {
- "dify_tool_count": len(tools_layer.tools) if tools_layer is not None else 0,
- "dify_tool_names": [tool.name or tool.tool_name for tool in tools_layer.tools]
- if tools_layer is not None
- else [],
+ "dify_tool_count": len(tool_layers.exposed_tool_names()),
+ "dify_tool_names": tool_layers.exposed_tool_names(),
"cli_tool_count": len(agent_soul.tools.cli_tools),
}
- drive_config = None
+ config_layer_config = None
soul_prompt_resolver = build_soul_mention_resolver(agent_soul)
if dify_config.AGENT_DRIVE_MANIFEST_ENABLED:
- drive_config, drive_warnings = build_drive_layer_config(
+ config_layer_config, config_warnings = build_config_layer_config(
agent_soul,
- tenant_id=context.dify_context.tenant_id,
- agent_id=context.agent_id,
- )
- append_runtime_warnings(metadata, drive_warnings)
- soul_prompt_resolver = build_drive_aware_soul_mention_resolver(
- agent_soul,
- tenant_id=context.dify_context.tenant_id,
agent_id=context.agent_id,
+ config_version_id=context.agent_config_snapshot_id,
+ config_version_kind=context.agent_config_version_kind,
)
+ append_runtime_warnings(metadata, config_warnings)
+ soul_prompt_resolver = build_config_aware_soul_mention_resolver(agent_soul)
knowledge_config = build_knowledge_layer_config(agent_soul)
request = self._request_builder.build_for_agent_app(
@@ -158,6 +156,7 @@ class AgentAppRuntimeRequestBuilder:
conversation_id=context.conversation_id,
agent_id=context.agent_id,
agent_config_version_id=context.agent_config_snapshot_id,
+ agent_config_version_kind=context.agent_config_version_kind,
# Agent Files §1.3: real Dify access context + agent run mode.
user_from=cast(DifyExecutionContextUserFrom, context.dify_context.user_from.value),
invoke_from=cast(DifyExecutionContextInvokeFrom, context.dify_context.invoke_from.value),
@@ -168,9 +167,10 @@ class AgentAppRuntimeRequestBuilder:
agent_soul_prompt=expand_prompt_mentions(agent_soul.prompt.system_prompt, soul_prompt_resolver).strip()
or None,
user_prompt=context.user_query,
- tools=tools_layer,
+ tools=tool_layers.plugin_tools,
+ core_tools=tool_layers.core_tools,
knowledge=knowledge_config,
- drive_config=drive_config,
+ config_layer_config=config_layer_config,
ask_human_config=build_ask_human_layer_config(agent_soul),
include_shell=dify_config.AGENT_SHELL_ENABLED,
shell_config=build_shell_layer_config(agent_soul),
@@ -183,6 +183,26 @@ class AgentAppRuntimeRequestBuilder:
redacted = cast(dict[str, Any], redact_for_agent_backend_log(request))
return AgentAppRuntimeRequest(request=request, redacted_request=redacted, metadata=metadata)
+ def _build_tool_layers(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ user_id: str | None,
+ tools: AgentSoulToolsConfig,
+ invoke_from: InvokeFrom,
+ ) -> WorkflowAgentToolLayers:
+ # Production Agent App runs intentionally keep existing plugin configs
+ # on the direct `dify.plugin.tools` route. This builder emits plugin
+ # tools directly and non-plugin Dify tools through `dify.core.tools`.
+ return self._dify_tools_builder.build_layers(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ user_id=user_id,
+ tools=tools,
+ invoke_from=invoke_from,
+ )
+
@staticmethod
def _build_metadata(context: AgentAppRuntimeBuildContext) -> dict[str, Any]:
return {
diff --git a/api/core/app/entities/app_invoke_entities.py b/api/core/app/entities/app_invoke_entities.py
index f588c98eefe..690f23c8302 100644
--- a/api/core/app/entities/app_invoke_entities.py
+++ b/api/core/app/entities/app_invoke_entities.py
@@ -1,8 +1,8 @@
from collections.abc import Mapping, Sequence
from enum import StrEnum
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Literal
-from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator
+from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationInfo, field_validator
from constants import UUID_NIL
from core.app.app_config.entities import EasyUIBasedAppConfig, WorkflowUIBasedAppConfig
@@ -220,11 +220,24 @@ class AgentAppGenerateEntity(ChatAppGenerateEntity):
accepted-entity union. The answer is produced by the dify-agent backend
rather than an in-process LLM call; ``model_conf`` is synthesized from the
bound Agent Soul model so the chat task pipeline can persist usage.
+
+ ``agent_config_version_kind`` selects which Agent config surface the
+ backend should read from: immutable snapshot, shared draft, or per-user
+ build draft.
+
+ ``agent_runtime_session_snapshot_id`` carries the runtime session scope
+ used to resume or suspend within the same editable config surface.
+
+ ``prompt_file_mappings`` preserves the raw request ``files`` array for the
+ Agent backend prompt. These references are appended to the backend prompt
+ text while the stored chat message keeps the user's original query.
"""
agent_id: str
agent_config_snapshot_id: str
+ agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot"
agent_runtime_session_snapshot_id: str | None = None
+ prompt_file_mappings: Sequence[JsonValue] = Field(default_factory=list)
class AdvancedChatAppGenerateEntity(ConversationAppGenerateEntity):
diff --git a/api/core/tools/tool_engine.py b/api/core/tools/tool_engine.py
index 6a2eb207641..b3cfd55265e 100644
--- a/api/core/tools/tool_engine.py
+++ b/api/core/tools/tool_engine.py
@@ -111,7 +111,7 @@ class ToolEngine:
tool_messages=binary_files, agent_message=message, invoke_from=invoke_from, user_id=user_id
)
- plain_text = ToolEngine._convert_tool_response_to_str(message_list)
+ plain_text = ToolEngine.tool_response_to_str(message_list)
meta = invocation_meta_dict["meta"]
@@ -234,10 +234,8 @@ class ToolEngine:
yield meta
@staticmethod
- def _convert_tool_response_to_str(tool_response: list[ToolInvokeMessage]) -> str:
- """
- Handle tool response
- """
+ def tool_response_to_str(tool_response: list[ToolInvokeMessage]) -> str:
+ """Convert tool invoke messages into the plain-text observation shown to the model/user."""
parts: list[str] = []
json_parts: list[str] = []
diff --git a/api/core/workflow/nodes/agent_v2/dify_tools_builder.py b/api/core/workflow/nodes/agent_v2/dify_tools_builder.py
new file mode 100644
index 00000000000..acb58a46952
--- /dev/null
+++ b/api/core/workflow/nodes/agent_v2/dify_tools_builder.py
@@ -0,0 +1,500 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any, Literal, Protocol, cast
+
+from dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolProviderType, DifyCoreToolsLayerConfig
+from dify_agent.layers.dify_plugin import (
+ DifyPluginCredentialValue,
+ DifyPluginToolConfig,
+ DifyPluginToolCredentialType,
+ DifyPluginToolParameter,
+ DifyPluginToolParameterForm,
+ DifyPluginToolsLayerConfig,
+)
+from sqlalchemy import select
+from sqlalchemy.orm import Session
+
+from core.agent.entities import AgentToolEntity
+from core.app.entities.app_invoke_entities import InvokeFrom
+from core.tools.__base.tool import Tool
+from core.tools.entities.tool_entities import ToolProviderType
+from core.tools.errors import ToolProviderCredentialValidationError, ToolProviderNotFoundError
+from core.tools.tool_manager import ToolManager
+from core.tools.workflow_as_tool.provider import WorkflowToolProviderController
+from extensions.ext_database import db
+from models.agent_config_entities import AgentSoulDifyToolConfig, AgentSoulToolsConfig
+from models.provider_ids import ToolProviderID
+from models.tools import WorkflowToolProvider
+from services.tools.mcp_tools_manage_service import MCPToolManageService
+
+
+class WorkflowAgentDifyToolsBuildError(ValueError):
+ """Raised when Agent Soul tools cannot be prepared for Agent backend."""
+
+ def __init__(self, error_code: str, message: str) -> None:
+ self.error_code = error_code
+ super().__init__(message)
+
+
+class AgentToolRuntimeProvider(Protocol):
+ def get_agent_tool_runtime(
+ self,
+ tenant_id: str,
+ app_id: str,
+ agent_tool: AgentToolEntity,
+ user_id: str | None = None,
+ invoke_from: InvokeFrom = InvokeFrom.DEBUGGER,
+ variable_pool: Any | None = None,
+ allow_file_parameters: bool = False,
+ use_default_for_missing_form_parameters: bool = False,
+ ) -> Tool: ...
+
+
+class ProviderToolsLister(Protocol):
+ def __call__(
+ self,
+ *,
+ tenant_id: str,
+ provider_type: ToolProviderType,
+ provider_id: str,
+ ) -> list[str]: ...
+
+
+class MCPProviderIDResolver(Protocol):
+ def __call__(self, *, tenant_id: str, provider_id: str) -> str: ...
+
+
+@dataclass(frozen=True, slots=True)
+class WorkflowAgentToolLayers:
+ plugin_tools: DifyPluginToolsLayerConfig | None = None
+ core_tools: DifyCoreToolsLayerConfig | None = None
+
+ def exposed_tool_names(self) -> list[str]:
+ names: list[str] = []
+ if self.plugin_tools is not None:
+ names.extend(tool.name or tool.tool_name for tool in self.plugin_tools.tools)
+ if self.core_tools is not None:
+ names.extend(tool.name or tool.tool_name for tool in self.core_tools.tools)
+ return names
+
+
+class WorkflowAgentDifyToolLayersBuilder(Protocol):
+ def build_layers(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ user_id: str | None,
+ tools: AgentSoulToolsConfig,
+ invoke_from: InvokeFrom,
+ ) -> WorkflowAgentToolLayers: ...
+
+
+def _list_provider_tool_names(
+ *,
+ tenant_id: str,
+ provider_type: ToolProviderType,
+ provider_id: str,
+) -> list[str]:
+ """Tool names a provider currently declares for provider-level Agent entries."""
+ match provider_type:
+ case ToolProviderType.PLUGIN:
+ plugin_provider = ToolManager.get_plugin_provider(provider_id, tenant_id)
+ return [tool.entity.identity.name for tool in plugin_provider.get_tools() or []]
+ case ToolProviderType.BUILT_IN:
+ builtin_provider = ToolManager.get_builtin_provider(provider_id, tenant_id)
+ return [tool.entity.identity.name for tool in builtin_provider.get_tools() or []]
+ case ToolProviderType.API:
+ api_provider, _ = ToolManager.get_api_provider_controller(tenant_id, provider_id)
+ return [tool.entity.identity.name for tool in api_provider.get_tools(tenant_id) or []]
+ case ToolProviderType.WORKFLOW:
+ db_provider = db.session.scalar(
+ select(WorkflowToolProvider)
+ .where(
+ WorkflowToolProvider.id == provider_id,
+ WorkflowToolProvider.tenant_id == tenant_id,
+ )
+ .limit(1)
+ )
+ if db_provider is None:
+ raise ToolProviderNotFoundError(f"workflow provider {provider_id} not found")
+ workflow_provider = WorkflowToolProviderController.from_db(db_provider)
+ return [tool.entity.identity.name for tool in workflow_provider.get_tools(tenant_id) or []]
+ case ToolProviderType.MCP:
+ mcp_provider = ToolManager.get_mcp_provider_controller(tenant_id, provider_id)
+ return [tool.entity.identity.name for tool in mcp_provider.get_tools() or []]
+ case _:
+ raise ToolProviderNotFoundError(f"provider type {provider_type.value} not found")
+
+
+def _resolve_mcp_provider_id(*, tenant_id: str, provider_id: str) -> str:
+ """Normalize MCP provider ids to the runtime-facing server identifier."""
+ service = MCPToolManageService(session=cast(Session, db.session))
+ try:
+ return service.get_provider_entity(provider_id, tenant_id, by_server_id=True).provider_id
+ except ValueError:
+ try:
+ return service.get_provider_entity(provider_id, tenant_id, by_server_id=False).provider_id
+ except ValueError as exc:
+ raise ToolProviderNotFoundError(f"mcp provider {provider_id} not found") from exc
+
+
+class WorkflowAgentDifyToolsBuilder:
+ """Prepare Agent Soul Dify tools for Agent backend run-layer configs.
+
+ Plugin tools keep their existing direct daemon path. Core-routed tools
+ (`builtin`/`api`/`workflow`/`mcp`) are emitted as `dify.core.tools`.
+ """
+
+ def __init__(
+ self,
+ *,
+ tool_runtime_provider: AgentToolRuntimeProvider | None = None,
+ provider_tools_lister: ProviderToolsLister | None = None,
+ mcp_provider_id_resolver: MCPProviderIDResolver | None = None,
+ ) -> None:
+ self._tool_runtime_provider = tool_runtime_provider or ToolManager
+ self._provider_tools_lister = provider_tools_lister or _list_provider_tool_names
+ self._mcp_provider_id_resolver = mcp_provider_id_resolver or _resolve_mcp_provider_id
+
+ def build_layers(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ user_id: str | None,
+ tools: AgentSoulToolsConfig,
+ invoke_from: InvokeFrom,
+ ) -> WorkflowAgentToolLayers:
+ """Resolve user-selected Dify tools into direct/core Agent backend DTOs.
+
+ `invoke_from` is the real runtime caller category (DEBUGGER for a
+ Composer test run, SERVICE_API / WEB_APP for a published run). It must
+ be threaded through to `ToolManager` so credential quotas, rate limits,
+ and audit tags match the actual call site.
+ """
+ enabled_tools = [tool for tool in tools.dify_tools if tool.enabled]
+ if not enabled_tools:
+ return WorkflowAgentToolLayers()
+
+ prepared_plugin: list[DifyPluginToolConfig] = []
+ prepared_core: list[DifyCoreToolConfig] = []
+ seen_names: set[str] = set()
+
+ for tool_config in self._expand_provider_entries(tenant_id=tenant_id, enabled_tools=enabled_tools):
+ normalized_tool_config = self._normalized_tool_config(tenant_id=tenant_id, tool_config=tool_config)
+ destination = self._tool_layer_destination(normalized_tool_config)
+ exposed_name = self._exposed_tool_name(normalized_tool_config)
+ if exposed_name in seen_names:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_name_duplicated",
+ f"Duplicate Dify Tool name {exposed_name!r}.",
+ )
+ seen_names.add(exposed_name)
+
+ agent_tool = self._to_agent_tool_entity(normalized_tool_config)
+ tool_runtime = self._fetch_tool_runtime(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ user_id=user_id,
+ agent_tool=agent_tool,
+ invoke_from=invoke_from,
+ tool_config=normalized_tool_config,
+ )
+
+ if destination == "plugin":
+ prepared_plugin.append(
+ self._to_plugin_backend_tool_config(normalized_tool_config, tool_runtime, exposed_name)
+ )
+ else:
+ prepared_core.append(
+ self._to_core_backend_tool_config(normalized_tool_config, tool_runtime, exposed_name)
+ )
+
+ return WorkflowAgentToolLayers(
+ plugin_tools=DifyPluginToolsLayerConfig(tools=prepared_plugin) if prepared_plugin else None,
+ core_tools=DifyCoreToolsLayerConfig(tools=prepared_core) if prepared_core else None,
+ )
+
+ def _expand_provider_entries(
+ self,
+ *,
+ tenant_id: str,
+ enabled_tools: list[AgentSoulDifyToolConfig],
+ ) -> list[AgentSoulDifyToolConfig]:
+ """Expand provider-level entries (`tool_name` omitted = all tools)."""
+ explicit_by_provider: dict[tuple[ToolProviderType, str], set[str]] = {}
+ for tool_config in enabled_tools:
+ if tool_config.tool_name is not None:
+ explicit_by_provider.setdefault(self._provider_key(tool_config), set()).add(tool_config.tool_name)
+
+ expanded: list[AgentSoulDifyToolConfig] = []
+ for tool_config in enabled_tools:
+ if tool_config.tool_name is not None:
+ expanded.append(tool_config)
+ continue
+ provider_type = ToolProviderType.value_of(tool_config.provider_type)
+ provider_id = self._provider_id(tool_config)
+ try:
+ tool_names = self._provider_declared_tool_names(
+ tenant_id=tenant_id,
+ provider_type=provider_type,
+ provider_id=provider_id,
+ )
+ except ToolProviderNotFoundError as exc:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_declaration_not_found",
+ f"Dify Tool provider {provider_id!r} declaration not found: {exc}",
+ ) from exc
+ if not tool_names:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_declaration_not_found",
+ f"Dify Tool provider {provider_id!r} declares no tools.",
+ )
+ already_explicit = explicit_by_provider.get(self._provider_key(tool_config), set())
+ for tool_name in tool_names:
+ if tool_name in already_explicit:
+ continue
+ expanded.append(tool_config.model_copy(update={"tool_name": tool_name, "runtime_parameters": {}}))
+ return expanded
+
+ def _provider_declared_tool_names(
+ self,
+ *,
+ tenant_id: str,
+ provider_type: ToolProviderType,
+ provider_id: str,
+ ) -> list[str]:
+ return self._provider_tools_lister(
+ tenant_id=tenant_id,
+ provider_type=provider_type,
+ provider_id=provider_id,
+ )
+
+ def _normalized_tool_config(
+ self,
+ *,
+ tenant_id: str,
+ tool_config: AgentSoulDifyToolConfig,
+ ) -> AgentSoulDifyToolConfig:
+ if tool_config.provider_type != ToolProviderType.MCP.value:
+ return tool_config
+ provider_id = self._mcp_provider_id_resolver(tenant_id=tenant_id, provider_id=self._provider_id(tool_config))
+ return tool_config.model_copy(update={"provider_id": provider_id, "plugin_id": None, "provider": None})
+
+ def _fetch_tool_runtime(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ user_id: str | None,
+ agent_tool: AgentToolEntity,
+ invoke_from: InvokeFrom,
+ tool_config: AgentSoulDifyToolConfig,
+ ) -> Tool:
+ """Resolve the API-side `Tool` runtime and map fetch errors to stable codes."""
+ try:
+ return self._tool_runtime_provider.get_agent_tool_runtime(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ agent_tool=agent_tool,
+ user_id=user_id,
+ invoke_from=invoke_from,
+ variable_pool=None,
+ allow_file_parameters=True,
+ use_default_for_missing_form_parameters=True,
+ )
+ except ToolProviderNotFoundError as exc:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_declaration_not_found",
+ f"Dify Tool {tool_config.tool_name!r} declaration not found: {exc}",
+ ) from exc
+ except ToolProviderCredentialValidationError as exc:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_credential_invalid",
+ f"Dify Tool {tool_config.tool_name!r} credential validation failed: {exc}",
+ ) from exc
+ except ValueError as exc:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_config_invalid",
+ f"Dify Tool {tool_config.tool_name!r} runtime construction failed: {exc}",
+ ) from exc
+
+ @staticmethod
+ def _to_agent_tool_entity(tool_config: AgentSoulDifyToolConfig) -> AgentToolEntity:
+ assert tool_config.tool_name is not None
+ return AgentToolEntity(
+ provider_type=ToolProviderType.value_of(tool_config.provider_type),
+ provider_id=WorkflowAgentDifyToolsBuilder._provider_id(tool_config),
+ tool_name=tool_config.tool_name,
+ tool_parameters=dict(tool_config.runtime_parameters),
+ credential_id=tool_config.credential_ref.id if tool_config.credential_ref else None,
+ )
+
+ @staticmethod
+ def _provider_id(tool_config: AgentSoulDifyToolConfig) -> str:
+ if tool_config.provider_id:
+ return tool_config.provider_id
+ assert tool_config.plugin_id is not None
+ assert tool_config.provider is not None
+ return f"{tool_config.plugin_id}/{tool_config.provider}"
+
+ @staticmethod
+ def _provider_key(tool_config: AgentSoulDifyToolConfig) -> tuple[ToolProviderType, str]:
+ return (
+ ToolProviderType.value_of(tool_config.provider_type),
+ WorkflowAgentDifyToolsBuilder._provider_id(tool_config),
+ )
+
+ @staticmethod
+ def _tool_layer_destination(tool_config: AgentSoulDifyToolConfig) -> Literal["plugin", "core"]:
+ provider_type = ToolProviderType.value_of(tool_config.provider_type)
+ if provider_type is ToolProviderType.PLUGIN:
+ return "plugin"
+ if provider_type in {
+ ToolProviderType.BUILT_IN,
+ ToolProviderType.API,
+ ToolProviderType.WORKFLOW,
+ ToolProviderType.MCP,
+ }:
+ return "core"
+ if provider_type is ToolProviderType.DATASET_RETRIEVAL:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_provider_not_supported",
+ "dataset-retrieval remains on the knowledge path and is not supported in Agent tool layers.",
+ )
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_provider_not_supported",
+ f"Dify Tool provider type {provider_type.value!r} is not supported in Agent tool layers.",
+ )
+
+ @staticmethod
+ def _exposed_tool_name(tool_config: AgentSoulDifyToolConfig) -> str:
+ assert tool_config.tool_name is not None
+ return tool_config.tool_name
+
+ def _to_plugin_backend_tool_config(
+ self,
+ tool_config: AgentSoulDifyToolConfig,
+ tool_runtime: Tool,
+ exposed_name: str,
+ ) -> DifyPluginToolConfig:
+ runtime = tool_runtime.runtime
+ if runtime is None:
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_config_invalid",
+ f"Dify Tool {tool_config.tool_name!r} has no runtime.",
+ )
+
+ provider_id = self._provider_id(tool_config)
+ plugin_id, provider = self._plugin_provider(tool_config, provider_id)
+ parameters = self._prepared_parameters(tool_runtime)
+ runtime_parameters = self._runtime_parameters(tool_runtime, parameters)
+ description = self._description(tool_config, tool_runtime)
+
+ return DifyPluginToolConfig(
+ plugin_id=plugin_id,
+ provider=provider,
+ tool_name=exposed_name,
+ credential_type=self._credential_type(tool_config, runtime.credentials),
+ name=exposed_name,
+ description=description,
+ credentials=self._normalize_credentials(runtime.credentials, tool_name=exposed_name),
+ runtime_parameters=runtime_parameters,
+ parameters=parameters,
+ parameters_json_schema=tool_runtime.get_llm_parameters_json_schema(),
+ )
+
+ def _to_core_backend_tool_config(
+ self,
+ tool_config: AgentSoulDifyToolConfig,
+ tool_runtime: Tool,
+ exposed_name: str,
+ ) -> DifyCoreToolConfig:
+ parameters = self._prepared_parameters(tool_runtime)
+ return DifyCoreToolConfig(
+ provider_type=cast(DifyCoreToolProviderType, tool_config.provider_type),
+ provider_id=self._provider_id(tool_config),
+ tool_name=tool_config.tool_name or exposed_name,
+ credential_id=tool_config.credential_ref.id if tool_config.credential_ref else None,
+ name=exposed_name,
+ description=self._description(tool_config, tool_runtime),
+ runtime_parameters=self._runtime_parameters(tool_runtime, parameters),
+ parameters=parameters,
+ parameters_json_schema=tool_runtime.get_llm_parameters_json_schema(),
+ )
+
+ @staticmethod
+ def _plugin_provider(tool_config: AgentSoulDifyToolConfig, provider_id: str) -> tuple[str, str]:
+ if tool_config.plugin_id and tool_config.provider:
+ return tool_config.plugin_id, tool_config.provider
+ provider_id_entity = ToolProviderID(provider_id)
+ return provider_id_entity.plugin_id, provider_id_entity.provider_name
+
+ @staticmethod
+ def _credential_type(
+ tool_config: AgentSoulDifyToolConfig,
+ credentials: Mapping[str, Any],
+ ) -> DifyPluginToolCredentialType:
+ if not credentials and tool_config.credential_type == "unauthorized":
+ return "unauthorized"
+ return tool_config.credential_type
+
+ @staticmethod
+ def _prepared_parameters(tool_runtime: Tool) -> list[DifyPluginToolParameter]:
+ return [
+ DifyPluginToolParameter.model_validate(parameter.model_dump(mode="json"))
+ for parameter in tool_runtime.get_merged_runtime_parameters()
+ ]
+
+ @staticmethod
+ def _description(tool_config: AgentSoulDifyToolConfig, tool_runtime: Tool) -> str | None:
+ description = tool_config.description
+ if description is None and tool_runtime.entity.description is not None:
+ description = tool_runtime.entity.description.llm
+ return description
+
+ @staticmethod
+ def _runtime_parameters(
+ tool_runtime: Tool,
+ parameters: list[DifyPluginToolParameter],
+ ) -> dict[str, Any]:
+ runtime = tool_runtime.runtime
+ runtime_parameters = dict(runtime.runtime_parameters if runtime is not None else {})
+ missing = [
+ parameter.name
+ for parameter in parameters
+ if parameter.form is not DifyPluginToolParameterForm.LLM
+ and parameter.required
+ and parameter.default is None
+ and parameter.name not in runtime_parameters
+ ]
+ if missing:
+ names = ", ".join(sorted(missing))
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_runtime_parameter_missing",
+ f"Dify Tool {tool_runtime.entity.identity.name!r} is missing runtime parameters: {names}.",
+ )
+ return runtime_parameters
+
+ @staticmethod
+ def _normalize_credentials(
+ credentials: Mapping[str, Any],
+ *,
+ tool_name: str,
+ ) -> dict[str, DifyPluginCredentialValue]:
+ normalized: dict[str, DifyPluginCredentialValue] = {}
+ for key, value in credentials.items():
+ if isinstance(value, str | int | float | bool) or value is None:
+ normalized[key] = value
+ continue
+ raise WorkflowAgentDifyToolsBuildError(
+ "agent_tool_credential_shape_invalid",
+ (
+ f"Dify Plugin Tool {tool_name!r} credential {key!r} has a non-scalar value "
+ f"({type(value).__name__}); only str/int/float/bool/None are forwarded to the daemon."
+ ),
+ )
+ return normalized
diff --git a/api/core/workflow/nodes/agent_v2/plugin_tools_builder.py b/api/core/workflow/nodes/agent_v2/plugin_tools_builder.py
deleted file mode 100644
index 80366cc5193..00000000000
--- a/api/core/workflow/nodes/agent_v2/plugin_tools_builder.py
+++ /dev/null
@@ -1,334 +0,0 @@
-from __future__ import annotations
-
-from collections.abc import Mapping
-from typing import Any, Protocol
-
-from dify_agent.layers.dify_plugin import (
- DifyPluginCredentialValue,
- DifyPluginToolConfig,
- DifyPluginToolCredentialType,
- DifyPluginToolParameter,
- DifyPluginToolParameterForm,
- DifyPluginToolsLayerConfig,
-)
-
-from core.agent.entities import AgentToolEntity
-from core.app.entities.app_invoke_entities import InvokeFrom
-from core.tools.__base.tool import Tool
-from core.tools.entities.tool_entities import ToolProviderType
-from core.tools.errors import (
- ToolProviderCredentialValidationError,
- ToolProviderNotFoundError,
-)
-from core.tools.tool_manager import ToolManager
-from models.agent_config_entities import AgentSoulDifyToolConfig, AgentSoulToolsConfig
-from models.provider_ids import ToolProviderID
-
-
-class WorkflowAgentPluginToolsBuildError(ValueError):
- """Raised when Agent Soul tools cannot be prepared for Agent backend."""
-
- def __init__(self, error_code: str, message: str) -> None:
- self.error_code = error_code
- super().__init__(message)
-
-
-class AgentToolRuntimeProvider(Protocol):
- def get_agent_tool_runtime(
- self,
- tenant_id: str,
- app_id: str,
- agent_tool: AgentToolEntity,
- user_id: str | None = None,
- invoke_from: InvokeFrom = InvokeFrom.DEBUGGER,
- variable_pool: Any | None = None,
- allow_file_parameters: bool = False,
- use_default_for_missing_form_parameters: bool = False,
- ) -> Tool: ...
-
-
-class ProviderToolsLister(Protocol):
- def __call__(self, *, tenant_id: str, provider_id: str) -> list[str]: ...
-
-
-def _list_provider_tool_names(*, tenant_id: str, provider_id: str) -> list[str]:
- """Tool names a provider currently declares (provider-level config entries)."""
- provider = ToolManager.get_builtin_provider(provider_id, tenant_id)
- return [tool.entity.identity.name for tool in provider.get_tools() or []]
-
-
-class WorkflowAgentPluginToolsBuilder:
- """Prepare Agent Soul Dify Plugin Tools for the public Agent backend DTO."""
-
- def __init__(
- self,
- *,
- tool_runtime_provider: AgentToolRuntimeProvider | None = None,
- provider_tools_lister: ProviderToolsLister | None = None,
- ) -> None:
- self._tool_runtime_provider = tool_runtime_provider or ToolManager
- self._provider_tools_lister = provider_tools_lister or _list_provider_tool_names
-
- def build(
- self,
- *,
- tenant_id: str,
- app_id: str,
- user_id: str | None,
- tools: AgentSoulToolsConfig,
- invoke_from: InvokeFrom,
- ) -> DifyPluginToolsLayerConfig | None:
- """Resolve user-selected Dify Plugin Tools into the Agent backend DTO.
-
- ``invoke_from`` is the *real* runtime caller category (DEBUGGER for a
- Composer test run, SERVICE_API / WEB_APP for a published run). It must
- be threaded through to :class:`ToolManager` so credential quotas, rate
- limits, and audit tags match the actual call site.
- """
- enabled_tools = [tool for tool in tools.dify_tools if tool.enabled]
- if not enabled_tools:
- return None
-
- prepared: list[DifyPluginToolConfig] = []
- seen_names: set[str] = set()
- for tool_config in self._expand_provider_entries(tenant_id=tenant_id, enabled_tools=enabled_tools):
- agent_tool = self._to_agent_tool_entity(tool_config)
- tool_runtime = self._fetch_tool_runtime(
- tenant_id=tenant_id,
- app_id=app_id,
- user_id=user_id,
- agent_tool=agent_tool,
- invoke_from=invoke_from,
- tool_config=tool_config,
- )
-
- exposed_name = self._exposed_tool_name(tool_config)
- if exposed_name in seen_names:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_name_duplicated",
- f"Duplicate Dify Plugin Tool name {exposed_name!r}.",
- )
- seen_names.add(exposed_name)
-
- prepared.append(self._to_backend_tool_config(tool_config, tool_runtime, exposed_name))
-
- return DifyPluginToolsLayerConfig(tools=prepared)
-
- def _expand_provider_entries(
- self,
- *,
- tenant_id: str,
- enabled_tools: list[AgentSoulDifyToolConfig],
- ) -> list[AgentSoulDifyToolConfig]:
- """Expand provider-level entries (``tool_name`` omitted = all tools).
-
- An explicit per-tool entry of the same provider wins over the expansion
- (it may carry its own ``runtime_parameters``); expanded clones share the
- provider entry's ``credential_ref`` and start with default parameters.
- """
- explicit_by_provider: dict[str, set[str]] = {}
- for tool_config in enabled_tools:
- if tool_config.tool_name is not None:
- explicit_by_provider.setdefault(self._provider_id(tool_config), set()).add(tool_config.tool_name)
-
- expanded: list[AgentSoulDifyToolConfig] = []
- for tool_config in enabled_tools:
- if tool_config.tool_name is not None:
- expanded.append(tool_config)
- continue
- provider_id = self._provider_id(tool_config)
- try:
- tool_names = self._provider_tools_lister(tenant_id=tenant_id, provider_id=provider_id)
- except ToolProviderNotFoundError as exc:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_declaration_not_found",
- f"Dify Plugin Tool provider {provider_id!r} declaration not found: {exc}",
- ) from exc
- if not tool_names:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_declaration_not_found",
- f"Dify Plugin Tool provider {provider_id!r} declares no tools.",
- )
- already_explicit = explicit_by_provider.get(provider_id, set())
- for tool_name in tool_names:
- if tool_name in already_explicit:
- continue
- expanded.append(tool_config.model_copy(update={"tool_name": tool_name, "runtime_parameters": {}}))
- return expanded
-
- def _fetch_tool_runtime(
- self,
- *,
- tenant_id: str,
- app_id: str,
- user_id: str | None,
- agent_tool: AgentToolEntity,
- invoke_from: InvokeFrom,
- tool_config: AgentSoulDifyToolConfig,
- ) -> Tool:
- """Resolve the API-side ``Tool`` runtime, mapping fetch errors to
- Inspector-friendly error codes so callers can render distinct UX for
- "tool definition gone" vs "credential failed".
- """
- try:
- return self._tool_runtime_provider.get_agent_tool_runtime(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_tool=agent_tool,
- user_id=user_id,
- invoke_from=invoke_from,
- variable_pool=None,
- allow_file_parameters=True,
- use_default_for_missing_form_parameters=True,
- )
- except ToolProviderNotFoundError as exc:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_declaration_not_found",
- f"Dify Plugin Tool {tool_config.tool_name!r} declaration not found: {exc}",
- ) from exc
- except ToolProviderCredentialValidationError as exc:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_credential_invalid",
- f"Dify Plugin Tool {tool_config.tool_name!r} credential validation failed: {exc}",
- ) from exc
- except ValueError as exc:
- # ToolManager raises bare ValueError when the agent tool's
- # ``runtime`` / runtime parameters are missing. Surface it under a
- # narrower error code than a generic "declaration not found" so
- # frontend can render an actionable hint.
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_config_invalid",
- f"Dify Plugin Tool {tool_config.tool_name!r} runtime construction failed: {exc}",
- ) from exc
-
- @staticmethod
- def _to_agent_tool_entity(tool_config: AgentSoulDifyToolConfig) -> AgentToolEntity:
- # Provider-level entries are expanded into per-tool clones before this point.
- assert tool_config.tool_name is not None
- return AgentToolEntity(
- provider_type=ToolProviderType.value_of(tool_config.provider_type),
- provider_id=WorkflowAgentPluginToolsBuilder._provider_id(tool_config),
- tool_name=tool_config.tool_name,
- tool_parameters=dict(tool_config.runtime_parameters),
- credential_id=tool_config.credential_ref.id if tool_config.credential_ref else None,
- )
-
- @staticmethod
- def _provider_id(tool_config: AgentSoulDifyToolConfig) -> str:
- if tool_config.provider_id:
- return tool_config.provider_id
- assert tool_config.plugin_id is not None
- assert tool_config.provider is not None
- return f"{tool_config.plugin_id}/{tool_config.provider}"
-
- @staticmethod
- def _exposed_tool_name(tool_config: AgentSoulDifyToolConfig) -> str:
- # Stage 3.1 decision: no user rename yet. Keep the model-visible tool
- # name aligned with the plugin declaration identity. Provider-level
- # entries are expanded into per-tool clones before this point.
- assert tool_config.tool_name is not None
- return tool_config.tool_name
-
- def _to_backend_tool_config(
- self,
- tool_config: AgentSoulDifyToolConfig,
- tool_runtime: Tool,
- exposed_name: str,
- ) -> DifyPluginToolConfig:
- runtime = tool_runtime.runtime
- if runtime is None:
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_config_invalid",
- f"Dify Plugin Tool {tool_config.tool_name!r} has no runtime.",
- )
-
- provider_id = self._provider_id(tool_config)
- plugin_id, provider = self._plugin_provider(tool_config, provider_id)
- parameters = [
- DifyPluginToolParameter.model_validate(parameter.model_dump(mode="json"))
- for parameter in tool_runtime.get_merged_runtime_parameters()
- ]
- runtime_parameters = self._runtime_parameters(tool_runtime, parameters)
- description = tool_config.description
- if description is None and tool_runtime.entity.description is not None:
- description = tool_runtime.entity.description.llm
-
- return DifyPluginToolConfig(
- plugin_id=plugin_id,
- provider=provider,
- tool_name=exposed_name,
- credential_type=self._credential_type(tool_config, runtime.credentials),
- name=exposed_name,
- description=description,
- credentials=self._normalize_credentials(runtime.credentials, tool_name=exposed_name),
- runtime_parameters=runtime_parameters,
- parameters=parameters,
- parameters_json_schema=tool_runtime.get_llm_parameters_json_schema(),
- )
-
- @staticmethod
- def _plugin_provider(tool_config: AgentSoulDifyToolConfig, provider_id: str) -> tuple[str, str]:
- if tool_config.plugin_id and tool_config.provider:
- return tool_config.plugin_id, tool_config.provider
- provider_id_entity = ToolProviderID(provider_id)
- return provider_id_entity.plugin_id, provider_id_entity.provider_name
-
- @staticmethod
- def _credential_type(
- tool_config: AgentSoulDifyToolConfig,
- credentials: Mapping[str, Any],
- ) -> DifyPluginToolCredentialType:
- if not credentials and tool_config.credential_type == "unauthorized":
- return "unauthorized"
- return tool_config.credential_type
-
- @staticmethod
- def _runtime_parameters(
- tool_runtime: Tool,
- parameters: list[DifyPluginToolParameter],
- ) -> dict[str, Any]:
- runtime = tool_runtime.runtime
- runtime_parameters = dict(runtime.runtime_parameters if runtime is not None else {})
- missing = [
- parameter.name
- for parameter in parameters
- if parameter.form is not DifyPluginToolParameterForm.LLM
- and parameter.required
- and parameter.default is None
- and parameter.name not in runtime_parameters
- ]
- if missing:
- names = ", ".join(sorted(missing))
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_runtime_parameter_missing",
- f"Dify Plugin Tool {tool_runtime.entity.identity.name!r} is missing runtime parameters: {names}.",
- )
- return runtime_parameters
-
- @staticmethod
- def _normalize_credentials(
- credentials: Mapping[str, Any],
- *,
- tool_name: str,
- ) -> dict[str, DifyPluginCredentialValue]:
- """Forward only scalar credential values to the Agent backend.
-
- ``DifyPluginCredentialValue`` is ``str | int | float | bool | None``.
- Refusing non-scalar values (lists, dicts, custom objects) is safer than
- ``str(value)`` — stringifying a nested OAuth token blob produces a
- Python ``repr`` that the plugin daemon cannot use, and we'd rather
- surface a clear ``agent_tool_credential_shape_invalid`` than send junk.
- """
- normalized: dict[str, DifyPluginCredentialValue] = {}
- for key, value in credentials.items():
- if isinstance(value, str | int | float | bool) or value is None:
- normalized[key] = value
- continue
- raise WorkflowAgentPluginToolsBuildError(
- "agent_tool_credential_shape_invalid",
- (
- f"Dify Plugin Tool {tool_name!r} credential {key!r} has a non-scalar value "
- f"({type(value).__name__}); only str/int/float/bool/None are forwarded to the daemon."
- ),
- )
- return normalized
diff --git a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
index f4a81bdcc54..5804fd5fdcd 100644
--- a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
+++ b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
@@ -8,9 +8,11 @@ from typing import Any, Literal, Protocol, assert_never, cast
from agenton.compositor import CompositorSessionSnapshot
from dify_agent.agent_stub.protocol import AgentStubFileMapping
from dify_agent.layers.ask_human import DifyAskHumanLayerConfig
-from dify_agent.layers.drive import (
- DifyDriveLayerConfig,
- DifyDriveSkillConfig,
+from dify_agent.layers.config import (
+ DifyConfigFileConfig,
+ DifyConfigLayerConfig,
+ DifyConfigSkillConfig,
+ DifyConfigVersionConfig,
)
from dify_agent.layers.execution_context import (
DifyExecutionContextInvokeFrom,
@@ -55,6 +57,7 @@ from models.agent_config_entities import (
AgentKnowledgeModelConfig,
AgentKnowledgeRetrievalConfig,
AgentSoulConfig,
+ AgentSoulToolsConfig,
DeclaredArrayItem,
DeclaredOutputChildConfig,
DeclaredOutputConfig,
@@ -76,10 +79,14 @@ from services.agent.prompt_mentions import (
parse_prompt_mentions,
workflow_previous_node_output_refs_from_selectors,
)
-from services.agent_drive_service import AgentDriveService, decode_drive_mention_ref
+from .dify_tools_builder import (
+ WorkflowAgentDifyToolLayersBuilder,
+ WorkflowAgentDifyToolsBuilder,
+ WorkflowAgentDifyToolsBuildError,
+ WorkflowAgentToolLayers,
+)
from .output_failure_orchestrator import retry_idempotency_key
-from .plugin_tools_builder import WorkflowAgentPluginToolsBuilder, WorkflowAgentPluginToolsBuildError
from .runtime_feature_manifest import build_runtime_feature_manifest
_DENIED_PERMISSION_STATUSES = frozenset({"unauthorized", "denied", "forbidden", "invalid", "unavailable"})
@@ -97,6 +104,7 @@ _AGENT_STUB_FILE_TRANSFER_METHODS: Mapping[FileTransferMethod, AgentStubFileTran
FileTransferMethod.DATASOURCE_FILE: "datasource_file",
FileTransferMethod.REMOTE_URL: "remote_url",
}
+_CANONICAL_DIFY_FILE_REFERENCE_PATTERN = r"^dify-file-ref:eyJyZWNvcmRfaWQiOi[A-Za-z0-9_-]+={0,2}$"
class WorkflowAgentRuntimeRequestBuildError(ValueError):
@@ -157,11 +165,11 @@ class WorkflowAgentRuntimeRequestBuilder:
*,
credentials_provider: CredentialsProvider,
request_builder: AgentBackendRunRequestBuilder | None = None,
- plugin_tools_builder: WorkflowAgentPluginToolsBuilder | None = None,
+ dify_tools_builder: WorkflowAgentDifyToolLayersBuilder | None = None,
) -> None:
self._credentials_provider = credentials_provider
self._request_builder = request_builder or AgentBackendRunRequestBuilder()
- self._plugin_tools_builder = plugin_tools_builder or WorkflowAgentPluginToolsBuilder()
+ self._dify_tools_builder = dify_tools_builder or WorkflowAgentDifyToolsBuilder()
def build(self, context: WorkflowAgentRuntimeBuildContext) -> WorkflowAgentRuntimeRequest:
agent_soul = AgentSoulConfig.model_validate(context.snapshot.config_snapshot_dict)
@@ -182,42 +190,33 @@ class WorkflowAgentRuntimeRequestBuilder:
user_prompt = workflow_context_prompt or self._WORKFLOW_USER_PROMPT_FALLBACK
credentials = self._credentials_provider.fetch(agent_soul.model.model_provider, agent_soul.model.model)
try:
- tools_layer = self._plugin_tools_builder.build(
+ tool_layers = self._build_tool_layers(
tenant_id=context.dify_context.tenant_id,
app_id=context.dify_context.app_id,
user_id=context.dify_context.user_id,
tools=agent_soul.tools,
- # Thread the *real* runtime invocation source through to
- # ToolManager so credential quotas, rate limits, and audit
- # trails match the actual call site (DEBUGGER for draft test
- # run, SERVICE_API / WEB_APP for published run).
invoke_from=context.dify_context.invoke_from,
)
- except WorkflowAgentPluginToolsBuildError as error:
+ except WorkflowAgentDifyToolsBuildError as error:
raise WorkflowAgentRuntimeRequestBuildError(error.error_code, str(error)) from error
- if tools_layer is not None or agent_soul.tools.cli_tools:
+ if tool_layers.plugin_tools is not None or tool_layers.core_tools is not None or agent_soul.tools.cli_tools:
metadata["agent_tools"] = {
- "dify_tool_count": len(tools_layer.tools) if tools_layer is not None else 0,
- "dify_tool_names": [tool.name or tool.tool_name for tool in tools_layer.tools]
- if tools_layer is not None
- else [],
+ "dify_tool_count": len(tool_layers.exposed_tool_names()),
+ "dify_tool_names": tool_layers.exposed_tool_names(),
"cli_tool_count": len(agent_soul.tools.cli_tools),
}
- drive_config: DifyDriveLayerConfig | None = None
+ config_layer_config: DifyConfigLayerConfig | None = None
soul_prompt_resolver = build_soul_mention_resolver(agent_soul)
if dify_config.AGENT_DRIVE_MANIFEST_ENABLED:
- drive_config, drive_warnings = build_drive_layer_config(
- agent_soul,
- tenant_id=context.dify_context.tenant_id,
- agent_id=context.agent.id,
- )
- append_runtime_warnings(metadata, drive_warnings)
- soul_prompt_resolver = build_drive_aware_soul_mention_resolver(
+ config_layer_config, config_warnings = build_config_layer_config(
agent_soul,
- tenant_id=context.dify_context.tenant_id,
agent_id=context.agent.id,
+ config_version_id=context.snapshot.id,
+ config_version_kind="snapshot",
)
+ append_runtime_warnings(metadata, config_warnings)
+ soul_prompt_resolver = build_config_aware_soul_mention_resolver(agent_soul)
soul_prompt = expand_prompt_mentions(agent_soul.prompt.system_prompt, soul_prompt_resolver).strip()
knowledge_config = build_knowledge_layer_config(agent_soul)
@@ -251,6 +250,7 @@ class WorkflowAgentRuntimeRequestBuilder:
conversation_id=get_system_text(context.variable_pool, SystemVariableKey.CONVERSATION_ID),
agent_id=context.agent.id,
agent_config_version_id=context.snapshot.id,
+ agent_config_version_kind="snapshot",
agent_mode=self._agent_backend_agent_mode(context.dify_context.invoke_from),
invoke_from=cast(DifyExecutionContextInvokeFrom, context.dify_context.invoke_from.value),
),
@@ -258,9 +258,10 @@ class WorkflowAgentRuntimeRequestBuilder:
workflow_node_job_prompt=workflow_job_prompt,
user_prompt=user_prompt,
output=self._build_output_config(node_job.declared_outputs),
- tools=tools_layer,
+ tools=tool_layers.plugin_tools,
+ core_tools=tool_layers.core_tools,
knowledge=knowledge_config,
- drive_config=drive_config,
+ config_layer_config=config_layer_config,
ask_human_config=build_ask_human_layer_config(agent_soul),
include_shell=dify_config.AGENT_SHELL_ENABLED,
shell_config=build_shell_layer_config(agent_soul),
@@ -279,6 +280,26 @@ class WorkflowAgentRuntimeRequestBuilder:
metadata=metadata,
)
+ def _build_tool_layers(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ user_id: str | None,
+ tools: AgentSoulToolsConfig,
+ invoke_from: InvokeFrom,
+ ) -> WorkflowAgentToolLayers:
+ # Production workflow runs intentionally keep existing plugin configs on
+ # the direct `dify.plugin.tools` route. This builder emits plugin tools
+ # directly and non-plugin Dify tools through `dify.core.tools`.
+ return self._dify_tools_builder.build_layers(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ user_id=user_id,
+ tools=tools,
+ invoke_from=invoke_from,
+ )
+
@staticmethod
def _agent_backend_agent_mode(invoke_from: InvokeFrom) -> Literal["workflow_run", "single_step"]:
if invoke_from in {InvokeFrom.DEBUGGER, InvokeFrom.VALIDATION}:
@@ -494,7 +515,10 @@ class WorkflowAgentRuntimeRequestBuilder:
schema: dict[str, Any] = {"type": "object", "properties": properties}
if required:
schema["required"] = required
- return AgentBackendOutputConfig(json_schema=schema)
+ return AgentBackendOutputConfig(
+ json_schema=schema,
+ description=WorkflowAgentRuntimeRequestBuilder._build_output_description(effective_outputs),
+ )
@staticmethod
def effective_declared_outputs(
@@ -551,47 +575,106 @@ class WorkflowAgentRuntimeRequestBuilder:
array_schema["items"]["description"] = array_item.description
return array_schema
case DeclaredOutputType.FILE:
- return {
- "oneOf": [
- {
- "type": "object",
- "additionalProperties": False,
- "properties": {
- "transfer_method": {"const": FileTransferMethod.LOCAL_FILE.value},
- "reference": {"type": "string"},
- },
- "required": ["transfer_method", "reference"],
+ return WorkflowAgentRuntimeRequestBuilder._agent_stub_output_file_mapping_schema()
+ assert_never(output_type)
+
+ @staticmethod
+ def _agent_stub_output_file_mapping_schema() -> dict[str, Any]:
+ """JSON Schema for Agent-produced output file mappings.
+
+ ``AgentStubFileMapping.model_json_schema()`` cannot express the model's
+ ``after`` validator: only ``remote_url`` may carry ``url``; every other
+ method must carry a canonical ``reference``. The structured-output model
+ needs that relationship in the schema, otherwise it may emit
+ ``{"transfer_method": "local_file", "url": "..."}``, which passes the
+ broad generated schema but fails API-side output type checking.
+
+ For files produced inside an Agent run, the supported persisted shape is
+ narrower than every downloadable mapping: the sandbox must upload the
+ local artifact via ``dify-agent file upload <path>``, which returns a
+ ``tool_file`` mapping. ``local_file`` and ``datasource_file`` are valid
+ for existing file references in workflow context, not for newly produced
+ Agent output files.
+ """
+ return {
+ "title": "AgentStubFileMapping",
+ "description": (
+ "Agent output file mapping. Use `tool_file` with `reference` for files uploaded by "
+ "`dify-agent file upload <path>`; use `remote_url` only for files already reachable by URL."
+ ),
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["transfer_method", "reference"],
+ "properties": {
+ "transfer_method": {
+ "type": "string",
+ "enum": ["tool_file"],
},
- {
- "type": "object",
- "additionalProperties": False,
- "properties": {
- "transfer_method": {"const": FileTransferMethod.TOOL_FILE.value},
- "reference": {"type": "string"},
- },
- "required": ["transfer_method", "reference"],
+ "reference": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": _CANONICAL_DIFY_FILE_REFERENCE_PATTERN,
+ "description": (
+ "Canonical Dify file reference returned by `dify-agent file upload <path>`. "
+ "Never use a local path, filename, URL, or synthesized dify-file-ref here."
+ ),
},
- {
- "type": "object",
- "additionalProperties": False,
- "properties": {
- "transfer_method": {"const": FileTransferMethod.DATASOURCE_FILE.value},
- "reference": {"type": "string"},
- },
- "required": ["transfer_method", "reference"],
+ },
+ },
+ {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["transfer_method", "url"],
+ "properties": {
+ "transfer_method": {
+ "type": "string",
+ "enum": ["remote_url"],
},
- {
- "type": "object",
- "additionalProperties": False,
- "properties": {
- "transfer_method": {"const": FileTransferMethod.REMOTE_URL.value},
- "url": {"type": "string"},
- },
- "required": ["transfer_method", "url"],
+ "url": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Remote URL for a file that is already publicly reachable.",
},
- ],
- }
- assert_never(output_type)
+ },
+ },
+ ],
+ }
+
+ @staticmethod
+ def _build_output_description(declared_outputs: Sequence[DeclaredOutputConfig]) -> str | None:
+ file_output_lines: list[str] = []
+ for output in declared_outputs:
+ if output.type == DeclaredOutputType.FILE:
+ file_output_lines.append(
+ f"- `{output.name}`: create the file in the sandbox, run `dify-agent file upload <path>`, "
+ f"and set `final_output.{output.name}` to the returned AgentStubFileMapping JSON object. "
+ "Do not call `final_output` before the upload command succeeds. Do not use the local path, "
+ "filename, URL, or a synthesized/base64-encoded value as the `reference`."
+ )
+ elif (
+ output.type == DeclaredOutputType.ARRAY
+ and output.array_item is not None
+ and output.array_item.type == DeclaredOutputType.FILE
+ ):
+ file_output_lines.append(
+ f"- `{output.name}`: for every produced file, run `dify-agent file upload <path>` and set "
+ f"`final_output.{output.name}` to an array of the returned AgentStubFileMapping JSON objects. "
+ "Do not call `final_output` before all upload commands succeed. Do not use local paths, filenames, "
+ "URLs, or synthesized/base64-encoded values as `reference` values."
+ )
+ if not file_output_lines:
+ return None
+
+ return "\n".join(
+ [
+ "When filling file outputs, do not return a local filesystem path directly.",
+ "Upload each sandbox-local file through the Agent Stub CLI first. Copy the JSON printed by "
+ "`dify-agent file upload <path>` verbatim into the final output; never invent the `reference` value.",
+ *file_output_lines,
+ ]
+ )
@staticmethod
def _apply_child_properties(schema: dict[str, Any], children: Sequence[DeclaredOutputChildConfig]) -> None:
@@ -753,19 +836,12 @@ def append_runtime_warnings(metadata: dict[str, Any], warnings: list[dict[str, s
existing.extend(warnings)
-def build_drive_aware_soul_mention_resolver(
- agent_soul: AgentSoulConfig,
- *,
- tenant_id: str,
- agent_id: str,
-):
- """Resolve skill/file mentions against the agent drive and everything else via Agent Soul."""
+def build_config_aware_soul_mention_resolver(agent_soul: AgentSoulConfig):
+ """Resolve config skill/file mentions and delegate the rest to Agent Soul."""
base_resolver = build_soul_mention_resolver(agent_soul)
- drive_service = AgentDriveService()
- skill_catalog = drive_service.list_skills(tenant_id=tenant_id, agent_id=agent_id)
- skill_names_by_key = {skill["skill_md_key"]: skill["name"] for skill in skill_catalog}
- drive_keys = {item["key"] for item in drive_service.manifest(tenant_id=tenant_id, agent_id=agent_id)}
+ skill_names = {item.name for item in agent_soul.config_skills}
+ file_names = {item.name for item in agent_soul.config_files}
def _resolve(mention: object) -> str | None:
if not hasattr(mention, "kind") or not hasattr(mention, "ref_id"):
@@ -774,88 +850,97 @@ def build_drive_aware_soul_mention_resolver(
ref_id = cast(str, mention.ref_id)
label = cast(str | None, getattr(mention, "label", None))
if kind == MentionKind.SKILL:
- decoded_key = decode_drive_mention_ref(ref_id)
- return skill_names_by_key.get(decoded_key) or label or decoded_key
+ return ref_id if ref_id in skill_names else label or ref_id
if kind == MentionKind.FILE:
- decoded_key = decode_drive_mention_ref(ref_id)
- if decoded_key in drive_keys:
- return decoded_key.rsplit("/", 1)[-1]
- return label or decoded_key
+ return ref_id if ref_id in file_names else label or ref_id
return base_resolver(cast(Any, mention))
return _resolve
-def build_drive_layer_config(
+def build_config_layer_config(
agent_soul: AgentSoulConfig,
*,
- tenant_id: str,
- agent_id: str | None,
-) -> tuple[DifyDriveLayerConfig | None, list[dict[str, str]]]:
- """Derive drive runtime catalog + prompt-mentioned eager-pull keys from the drive."""
-
- mentioned_drive_refs = [
- decode_drive_mention_ref(mention.ref_id)
- for mention in parse_prompt_mentions(agent_soul.prompt.system_prompt)
- if mention.kind in {MentionKind.SKILL, MentionKind.FILE}
- ]
- ordered_mentions = list(dict.fromkeys(ref for ref in mentioned_drive_refs if ref))
- if not agent_id:
- if not ordered_mentions:
- return None, []
- return None, [
- {
- "section": "agent_soul.prompt.system_prompt",
- "code": "drive_ref_dangling",
- "message": "drive mentions are configured but the run has no bound agent to address a drive by.",
- }
- ]
-
- drive_service = AgentDriveService()
- skills_catalog = drive_service.list_skills(tenant_id=tenant_id, agent_id=agent_id)
- manifest_items = drive_service.manifest(tenant_id=tenant_id, agent_id=agent_id)
- manifest_by_key = {item["key"]: item for item in manifest_items}
- skill_keys = {skill["skill_md_key"] for skill in skills_catalog}
+ agent_id: str | None = None,
+ config_version_id: str | None = None,
+ config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot",
+) -> tuple[DifyConfigLayerConfig | None, list[dict[str, str]]]:
+ """Derive prompt-mentioned eager-pull names from Agent Soul."""
+
+ ordered_mentions = list(
+ dict.fromkeys(
+ mention.ref_id
+ for mention in parse_prompt_mentions(agent_soul.prompt.system_prompt)
+ if mention.kind in {MentionKind.SKILL, MentionKind.FILE} and mention.ref_id
+ )
+ )
+ if (
+ not agent_soul.config_skills
+ and not agent_soul.config_files
+ and not agent_soul.config_note
+ and not ordered_mentions
+ ):
+ return None, []
+
+ skill_names = {skill.name for skill in agent_soul.config_skills}
+ file_names = {file_ref.name for file_ref in agent_soul.config_files}
warnings: list[dict[str, str]] = []
- mentioned_skill_keys: list[str] = []
- mentioned_file_keys: list[str] = []
- for drive_key in ordered_mentions:
- if drive_key in skill_keys:
- mentioned_skill_keys.append(drive_key)
+ mentioned_skill_names: list[str] = []
+ mentioned_file_names: list[str] = []
+ for name in ordered_mentions:
+ if name in skill_names:
+ mentioned_skill_names.append(name)
continue
- if drive_key in manifest_by_key:
- mentioned_file_keys.append(drive_key)
+ if name in file_names:
+ mentioned_file_names.append(name)
continue
warnings.append(
{
"section": "agent_soul.prompt.system_prompt",
"code": "mention_target_missing",
- "message": f"drive mention '{drive_key}' has no matching drive entry.",
+ "message": f"config mention '{name}' has no matching config asset.",
}
)
- skills = [
- DifyDriveSkillConfig(
- path=skill["path"],
- name=skill["name"],
- description=skill["description"],
- skill_md_key=skill["skill_md_key"],
- archive_key=skill["archive_key"],
- )
- for skill in skills_catalog
- ]
-
return (
- DifyDriveLayerConfig(
- drive_ref=f"agent-{agent_id}",
- skills=skills,
- mentioned_skill_keys=mentioned_skill_keys,
- mentioned_file_keys=mentioned_file_keys,
+ DifyConfigLayerConfig(
+ agent_id=agent_id,
+ config_version=DifyConfigVersionConfig(
+ id=config_version_id,
+ kind=config_version_kind,
+ writable=config_version_kind == "build_draft",
+ ),
+ skills=[
+ DifyConfigSkillConfig(
+ name=skill.name,
+ description=skill.description,
+ size=skill.size,
+ mime_type=skill.mime_type,
+ )
+ for skill in agent_soul.config_skills
+ ],
+ files=[
+ DifyConfigFileConfig(
+ name=file_ref.name,
+ size=file_ref.size,
+ mime_type=file_ref.mime_type,
+ )
+ for file_ref in agent_soul.config_files
+ ],
+ env_keys=_agent_soul_config_env_keys(agent_soul),
+ note=agent_soul.config_note,
+ mentioned_skill_names=mentioned_skill_names,
+ mentioned_file_names=mentioned_file_names,
),
warnings,
)
+def _agent_soul_config_env_keys(agent_soul: AgentSoulConfig) -> list[str]:
+ keys = [item.key or item.name or item.env_name or item.variable for item in agent_soul.env.variables]
+ return [key for key in keys if key]
+
+
def _cli_tool_enabled(item: object) -> bool:
"""A CLI tool is bootstrapped unless explicitly disabled (default is enabled)."""
data = _plain_mapping(item)
diff --git a/api/fields/agent_fields.py b/api/fields/agent_fields.py
index e045ee39afc..db0dbf8dcc0 100644
--- a/api/fields/agent_fields.py
+++ b/api/fields/agent_fields.py
@@ -371,6 +371,9 @@ class WorkflowAgentComposerResponse(ResponseModel):
backing_app_id: str | None = None
hidden_app_backed: bool = False
chat_endpoint: str | None = None
+ debug_conversation_id: str | None = None
+ debug_conversation_has_messages: bool = False
+ debug_conversation_message_count: int = 0
workflow_id: str | None = None
node_id: str | None = None
diff --git a/api/models/agent_config_entities.py b/api/models/agent_config_entities.py
index c1faa5a6975..64990357acd 100644
--- a/api/models/agent_config_entities.py
+++ b/api/models/agent_config_entities.py
@@ -109,6 +109,7 @@ class OutputErrorStrategy(StrEnum):
# JSON-schema-friendly name pattern. Stage 4 §3.1 / §10.1.
_OUTPUT_NAME_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+_CONFIG_SKILL_NAME_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
JsonPrimitive = str | int | float | bool | None
RuntimeParameterValue = JsonPrimitive | list[str] | list[int] | list[float] | list[bool]
@@ -167,6 +168,63 @@ class AgentSoulFilesConfig(BaseModel):
files: list[AgentFileRefConfig] = Field(default_factory=list)
+def validate_config_name(name: str) -> str:
+ normalized = name.strip()
+ if not normalized:
+ raise ValueError("config asset name must not be blank")
+ if normalized in {".", ".."}:
+ raise ValueError("config asset name must not be '.' or '..'")
+ if "/" in normalized or "\\" in normalized:
+ raise ValueError("config asset name must be a single path segment")
+ if "\x00" in normalized or any(ord(ch) < 0x20 for ch in normalized):
+ raise ValueError("config asset name must not contain control characters")
+ return normalized
+
+
+def validate_config_skill_name(name: str) -> str:
+ normalized = validate_config_name(name)
+ if _CONFIG_SKILL_NAME_PATTERN.fullmatch(normalized) is None:
+ raise ValueError(f"config skill name {normalized!r} must match {_CONFIG_SKILL_NAME_PATTERN.pattern}")
+ return normalized
+
+
+class AgentConfigFileRefConfig(BaseModel):
+ """Stable Agent Soul reference to one config file payload."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(min_length=1, max_length=255)
+ file_kind: Literal["upload_file", "tool_file"]
+ file_id: str = Field(min_length=1, max_length=255)
+ size: int | None = None
+ hash: str | None = None
+ mime_type: str | None = None
+
+ @field_validator("name")
+ @classmethod
+ def _validate_name(cls, value: str) -> str:
+ return validate_config_name(value)
+
+
+class AgentConfigSkillRefConfig(BaseModel):
+ """Stable Agent Soul reference to one normalized skill archive."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(min_length=1, max_length=255)
+ description: str = ""
+ file_kind: Literal["tool_file"] = "tool_file"
+ file_id: str = Field(min_length=1, max_length=255)
+ size: int | None = None
+ hash: str | None = None
+ mime_type: str | None = "application/zip"
+
+ @field_validator("name")
+ @classmethod
+ def _validate_name(cls, value: str) -> str:
+ return validate_config_skill_name(value)
+
+
class AgentPermissionConfig(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -527,12 +585,15 @@ class AgentSoulDifyToolCredentialRef(BaseModel):
class AgentSoulDifyToolConfig(BaseModel):
- """One Dify Plugin Tool configured on Agent Soul.
+ """One Dify tool configured on Agent Soul.
The API backend prepares this persisted product shape into
- ``DifyPluginToolConfig`` before sending a run request to Agent backend.
- ``provider_id`` keeps compatibility with existing Agent tool config payloads;
- new callers should send ``plugin_id`` + ``provider`` when available.
+ either ``DifyPluginToolConfig`` or ``DifyCoreToolConfig`` before sending a
+ run request to Agent backend. ``plugin`` providers keep the direct
+ ``dify.plugin.tools`` transport; ``builtin`` / ``api`` / ``workflow`` /
+ ``mcp`` providers are prepared for ``dify.core.tools``. ``provider_id``
+ keeps compatibility with existing Agent tool config payloads; new callers
+ should send ``plugin_id`` + ``provider`` when available.
"""
# ``extra="ignore"`` (not ``"allow"``) so historical Agent Soul payloads
@@ -542,10 +603,10 @@ class AgentSoulDifyToolConfig(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = True
- # Dify Plugin Tools live behind the ``PLUGIN`` provider type. ``BUILT_IN`` /
- # ``WORKFLOW`` / ``API`` providers are not exposed to the Agent backend in
- # this layer — keep the default narrow so a missing field surfaces as
- # ``agent_tool_declaration_not_found`` against the correct provider table.
+ # ``plugin`` remains the default for legacy Agent Soul payloads. The runtime
+ # now also accepts ``builtin`` / ``api`` / ``workflow`` / ``mcp`` here and
+ # routes them through ``dify.core.tools``; keeping the default narrow still
+ # makes a missing field resolve against the plugin provider table.
provider_type: str = "plugin"
provider_id: str | None = Field(default=None, max_length=255)
plugin_id: str | None = Field(default=None, max_length=255)
@@ -682,6 +743,9 @@ class AgentSoulConfig(BaseModel):
knowledge: AgentSoulKnowledgeConfig = Field(default_factory=AgentSoulKnowledgeConfig)
human: AgentSoulHumanConfig = Field(default_factory=AgentSoulHumanConfig)
env: AgentSoulEnvConfig = Field(default_factory=AgentSoulEnvConfig)
+ config_skills: list[AgentConfigSkillRefConfig] = Field(default_factory=list)
+ config_files: list[AgentConfigFileRefConfig] = Field(default_factory=list)
+ config_note: str = ""
files: AgentSoulFilesConfig = Field(default_factory=AgentSoulFilesConfig)
sandbox: AgentSoulSandboxConfig = Field(default_factory=AgentSoulSandboxConfig)
memory: AgentSoulMemoryConfig = Field(default_factory=AgentSoulMemoryConfig)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 207cfcd78ad..3fe4fde4c15 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -465,6 +465,23 @@ Check if activation token is valid
| ---- | ----------- |
| 204 | Agent service API key deleted |
+### [POST] /agent/{agent_id}/build-chat/finalize
+Run a build-draft Agent App turn that asks the agent to push config updates
+
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Success | **application/json**: [SimpleResultResponse](#simpleresultresponse)<br> |
+| 400 | Invalid request parameters | |
+| 404 | Agent, build draft, or conversation not found | |
+
### [DELETE] /agent/{agent_id}/build-draft
#### Parameters
@@ -658,6 +675,237 @@ Stop a running Agent App chat message generation
| ---- | ----------- | ------ |
| 200 | Agent app composer validation result | **application/json**: [AgentComposerValidateResponse](#agentcomposervalidateresponse)<br> |
+### [GET] /agent/{agent_id}/config/files
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config files | **application/json**: [AgentConfigFileListResponse](#agentconfigfilelistresponse)<br> |
+
+### [POST] /agent/{agent_id}/config/files
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentConfigFileUploadPayload](#agentconfigfileuploadpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Uploaded config file | **application/json**: [AgentConfigFileUploadResponse](#agentconfigfileuploadresponse)<br> |
+
+### [DELETE] /agent/{agent_id}/config/files/{name}
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config file deleted | **application/json**: [AgentConfigDeleteResponse](#agentconfigdeleteresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/files/{name}/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config file download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/files/{name}/preview
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Preview | **application/json**: [AgentConfigFilePreviewResponse](#agentconfigfilepreviewresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/manifest
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent config manifest | **application/json**: [AgentConfigManifestResponse](#agentconfigmanifestresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/skills
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skills | **application/json**: [AgentConfigSkillListResponse](#agentconfigskilllistresponse)<br> |
+
+### [POST] /agent/{agent_id}/config/skills/upload
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **multipart/form-data**: { **"file"**: binary }<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Uploaded config skill | **application/json**: [AgentConfigSkillUploadResponse](#agentconfigskilluploadresponse)<br> |
+
+### [DELETE] /agent/{agent_id}/config/skills/{name}
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill deleted | **application/json**: [AgentConfigDeleteResponse](#agentconfigdeleteresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/skills/{name}/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/skills/{name}/files/content
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+| name | path | | Yes | string |
+
+#### Responses
+
+| Code | Description |
+| ---- | ----------- |
+| 200 | Success |
+
+### [GET] /agent/{agent_id}/config/skills/{name}/files/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| path | query | Normalized zip member path inside the skill package | Yes | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill file download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/skills/{name}/files/preview
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| path | query | Normalized zip member path inside the skill package | Yes | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill file preview | **application/json**: [AgentConfigSkillFilePreviewResponse](#agentconfigskillfilepreviewresponse)<br> |
+
+### [GET] /agent/{agent_id}/config/skills/{name}/inspect
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill inspect view | **application/json**: [AgentConfigSkillInspectResponse](#agentconfigskillinspectresponse)<br> |
+
### [POST] /agent/{agent_id}/copy
#### Parameters
@@ -1633,6 +1881,250 @@ Run draft workflow for advanced chat application
| 400 | Invalid request parameters | |
| 403 | Permission denied | |
+### [GET] /apps/{app_id}/agent/config/files
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config files | **application/json**: [AgentConfigFileListResponse](#agentconfigfilelistresponse)<br> |
+
+### [POST] /apps/{app_id}/agent/config/files
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentConfigFileUploadPayload](#agentconfigfileuploadpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Uploaded config file | **application/json**: [AgentConfigFileUploadResponse](#agentconfigfileuploadresponse)<br> |
+
+### [DELETE] /apps/{app_id}/agent/config/files/{name}
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config file deleted | **application/json**: [AgentConfigDeleteResponse](#agentconfigdeleteresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/files/{name}/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config file download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/files/{name}/preview
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config file name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Preview | **application/json**: [AgentConfigFilePreviewResponse](#agentconfigfilepreviewresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/manifest
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent config manifest | **application/json**: [AgentConfigManifestResponse](#agentconfigmanifestresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/skills
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skills | **application/json**: [AgentConfigSkillListResponse](#agentconfigskilllistresponse)<br> |
+
+### [POST] /apps/{app_id}/agent/config/skills/upload
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **multipart/form-data**: { **"file"**: binary }<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Uploaded config skill | **application/json**: [AgentConfigSkillUploadResponse](#agentconfigskilluploadresponse)<br> |
+
+### [DELETE] /apps/{app_id}/agent/config/skills/{name}
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill deleted | **application/json**: [AgentConfigDeleteResponse](#agentconfigdeleteresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/skills/{name}/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/skills/{name}/files/content
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | | Yes | string (uuid) |
+| name | path | | Yes | string |
+
+#### Responses
+
+| Code | Description |
+| ---- | ----------- |
+| 200 | Success |
+
+### [GET] /apps/{app_id}/agent/config/skills/{name}/files/download
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| path | query | Normalized zip member path inside the skill package | Yes | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill file download URL | **application/json**: [AgentConfigDownloadResponse](#agentconfigdownloadresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/skills/{name}/files/preview
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| path | query | Normalized zip member path inside the skill package | Yes | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill file preview | **application/json**: [AgentConfigSkillFilePreviewResponse](#agentconfigskillfilepreviewresponse)<br> |
+
+### [GET] /apps/{app_id}/agent/config/skills/{name}/inspect
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| name | path | Config skill name | Yes | string |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Config skill inspect view | **application/json**: [AgentConfigSkillInspectResponse](#agentconfigskillinspectresponse)<br> |
+
### [GET] /apps/{app_id}/agent/drive/files
List agent drive entries (read-only inspector; one endpoint for both tabs)
@@ -12375,7 +12867,9 @@ Default namespace
| bound_agent_id | string | | No |
| created_at | integer | | No |
| created_by | string | | No |
+| debug_conversation_has_messages | boolean | | No |
| debug_conversation_id | string | | No |
+| debug_conversation_message_count | integer | | No |
| deleted_tools | [ [DeletedTool](#deletedtool) ] | | No |
| description | string | | No |
| enable_api | boolean | | Yes |
@@ -12703,6 +13197,19 @@ Risk marker for CLI tool bootstrap commands.
| result | string | | Yes |
| warnings | [ [ComposerValidationWarningResponse](#composervalidationwarningresponse) ] | | No |
+#### AgentConfigDeleteResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| removed_names | [ string ] | | No |
+| result | string | | Yes |
+
+#### AgentConfigDownloadResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| url | string | | Yes |
+
#### AgentConfigDraftSummaryResponse
| Name | Type | Description | Required |
@@ -12725,6 +13232,78 @@ Editable Agent Soul draft workspace type.
| ---- | ---- | ----------- | -------- |
| AgentConfigDraftType | string | Editable Agent Soul draft workspace type. | |
+#### AgentConfigFileItemResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| file_id | string | | No |
+| hash | string | | No |
+| id | string | | Yes |
+| mime_type | string | | No |
+| name | string | | Yes |
+| size | integer | | No |
+
+#### AgentConfigFileItemsResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| items | [ [AgentConfigFileItemResponse](#agentconfigfileitemresponse) ] | | No |
+
+#### AgentConfigFileListResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| agent_id | string | | Yes |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| items | [ [AgentConfigFileItemResponse](#agentconfigfileitemresponse) ] | | No |
+
+#### AgentConfigFilePreviewResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| binary | boolean | | Yes |
+| name | string | | Yes |
+| size | integer | | No |
+| text | string | | No |
+| truncated | boolean | | Yes |
+
+#### AgentConfigFileRefConfig
+
+Stable Agent Soul reference to one config file payload.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| file_id | string | | Yes |
+| file_kind | string, <br>**Available values:** "tool_file", "upload_file" | *Enum:* `"tool_file"`, `"upload_file"` | Yes |
+| hash | string | | No |
+| mime_type | string | | No |
+| name | string | | Yes |
+| size | integer | | No |
+
+#### AgentConfigFileUploadPayload
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| upload_file_id | string | UploadFile UUID from POST /console/api/files/upload | Yes |
+
+#### AgentConfigFileUploadResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| file | [AgentConfigFileItemResponse](#agentconfigfileitemresponse) | | Yes |
+
+#### AgentConfigManifestResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| agent_id | string | | Yes |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| env_keys | [ string ] | | No |
+| files | [AgentConfigFileItemsResponse](#agentconfigfileitemsresponse) | | No |
+| note | string | | No |
+| skills | [AgentConfigSkillItemsResponse](#agentconfigskillitemsresponse) | | No |
+
#### AgentConfigRevisionOperation
Audit operation recorded for Agent Soul version/revision changes.
@@ -12747,6 +13326,99 @@ Audit operation recorded for Agent Soul version/revision changes.
| summary | string | | No |
| version_note | string | | No |
+#### AgentConfigSkillFilePreviewResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| binary | boolean | | Yes |
+| path | string | | Yes |
+| size | integer | | No |
+| text | string | | No |
+| truncated | boolean | | Yes |
+
+#### AgentConfigSkillFileResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| downloadable | boolean | | Yes |
+| name | string | | Yes |
+| path | string | | Yes |
+| previewable | boolean | | Yes |
+| type | string, <br>**Available values:** "directory", "file" | *Enum:* `"directory"`, `"file"` | Yes |
+
+#### AgentConfigSkillInspectResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| file_tree | [ object ] | | No |
+| files | [ [AgentConfigSkillFileResponse](#agentconfigskillfileresponse) ] | | No |
+| hash | string | | No |
+| id | string | | Yes |
+| mime_type | string | | No |
+| name | string | | Yes |
+| size | integer | | No |
+| skill_md | [AgentConfigSkillMarkdownResponse](#agentconfigskillmarkdownresponse) | | Yes |
+| source | string | | Yes |
+| warnings | [ string ] | | No |
+
+#### AgentConfigSkillItemResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| file_id | string | | No |
+| hash | string | | No |
+| id | string | | Yes |
+| mime_type | string | | No |
+| name | string | | Yes |
+| size | integer | | No |
+
+#### AgentConfigSkillItemsResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| items | [ [AgentConfigSkillItemResponse](#agentconfigskillitemresponse) ] | | No |
+
+#### AgentConfigSkillListResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| agent_id | string | | Yes |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| items | [ [AgentConfigSkillItemResponse](#agentconfigskillitemresponse) ] | | No |
+
+#### AgentConfigSkillMarkdownResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| binary | boolean | | Yes |
+| path | string | | Yes |
+| size | integer | | No |
+| text | string | | Yes |
+| truncated | boolean | | Yes |
+
+#### AgentConfigSkillRefConfig
+
+Stable Agent Soul reference to one normalized skill archive.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| file_id | string | | Yes |
+| file_kind | string, <br>**Default:** tool_file | | No |
+| hash | string | | No |
+| mime_type | string | | No |
+| name | string | | Yes |
+| size | integer | | No |
+
+#### AgentConfigSkillUploadResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| skill | [AgentConfigSkillItemResponse](#agentconfigskillitemresponse) | | Yes |
+
#### AgentConfigSnapshotDetailResponse
| Name | Type | Description | Required |
@@ -12792,6 +13464,14 @@ Audit operation recorded for Agent Soul version/revision changes.
| version | integer | | Yes |
| version_note | string | | No |
+#### AgentConfigVersionResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| id | string | | Yes |
+| kind | string, <br>**Available values:** "build_draft", "draft", "snapshot" | *Enum:* `"build_draft"`, `"draft"`, `"snapshot"` | Yes |
+| writable | boolean | | Yes |
+
#### AgentDailyConversationStatisticResponse
| Name | Type | Description | Required |
@@ -12817,7 +13497,9 @@ Audit operation recorded for Agent Soul version/revision changes.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
+| debug_conversation_has_messages | boolean | | No |
| debug_conversation_id | string | | Yes |
+| debug_conversation_message_count | integer | | No |
#### AgentDriveDeleteFileByAgentQuery
@@ -13588,6 +14270,9 @@ Visibility and lifecycle scope of an Agent record.
| ---- | ---- | ----------- | -------- |
| app_features | [AgentSoulAppFeaturesConfig](#agentsoulappfeaturesconfig) | | No |
| app_variables | [ [AppVariableConfig](#appvariableconfig) ] | | No |
+| config_files | [ [AgentConfigFileRefConfig](#agentconfigfilerefconfig) ] | | No |
+| config_note | string | | No |
+| config_skills | [ [AgentConfigSkillRefConfig](#agentconfigskillrefconfig) ] | | No |
| env | [AgentSoulEnvConfig](#agentsoulenvconfig) | | No |
| files | [AgentSoulFilesConfig](#agentsoulfilesconfig) | | No |
| human | [AgentSoulHumanConfig](#agentsoulhumanconfig) | | No |
@@ -13602,12 +14287,15 @@ Visibility and lifecycle scope of an Agent record.
#### AgentSoulDifyToolConfig
-One Dify Plugin Tool configured on Agent Soul.
+One Dify tool configured on Agent Soul.
The API backend prepares this persisted product shape into
-``DifyPluginToolConfig`` before sending a run request to Agent backend.
-``provider_id`` keeps compatibility with existing Agent tool config payloads;
-new callers should send ``plugin_id`` + ``provider`` when available.
+either ``DifyPluginToolConfig`` or ``DifyCoreToolConfig`` before sending a
+run request to Agent backend. ``plugin`` providers keep the direct
+``dify.plugin.tools`` transport; ``builtin`` / ``api`` / ``workflow`` /
+``mcp`` providers are prepared for ``dify.core.tools``. ``provider_id``
+keeps compatibility with existing Agent tool config payloads; new callers
+should send ``plugin_id`` + ``provider`` when available.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
@@ -20790,6 +21478,9 @@ How a workflow node is bound to an Agent.
| backing_app_id | string | | No |
| binding | [AgentComposerBindingResponse](#agentcomposerbindingresponse) | | No |
| chat_endpoint | string | | No |
+| debug_conversation_has_messages | boolean | | No |
+| debug_conversation_id | string | | No |
+| debug_conversation_message_count | integer | | No |
| effective_declared_outputs | [ [DeclaredOutputConfig](#declaredoutputconfig) ] | | No |
| hidden_app_backed | boolean | | No |
| impact_summary | [AgentComposerImpactResponse](#agentcomposerimpactresponse) | | No |
diff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.py
index ec81ab3daf2..99817eb6441 100644
--- a/api/services/agent/composer_service.py
+++ b/api/services/agent/composer_service.py
@@ -96,10 +96,14 @@ def _validate_composer_payload_for_strategy(payload: ComposerSavePayload) -> Non
ComposerConfigValidator.validate_draft_save_payload(payload)
+def _agent_soul_config_json(agent_soul: AgentSoulConfig | dict[str, Any]) -> dict[str, Any]:
+ return AgentSoulConfig.model_validate(agent_soul).model_dump(mode="json")
+
+
class AgentComposerService:
@classmethod
def load_workflow_composer(
- cls, *, tenant_id: str, app_id: str, node_id: str, snapshot_id: str | None = None
+ cls, *, tenant_id: str, app_id: str, node_id: str, account_id: str | None = None, snapshot_id: str | None = None
) -> dict[str, Any]:
workflow = cls._get_draft_workflow(tenant_id=tenant_id, app_id=app_id)
binding = cls._get_workflow_binding(tenant_id=tenant_id, workflow_id=workflow.id, node_id=node_id)
@@ -115,7 +119,7 @@ class AgentComposerService:
agent=agent,
snapshot_id=snapshot_id,
)
- return cls._serialize_workflow_state(binding=binding, agent=agent, version=version)
+ return cls._serialize_workflow_state(binding=binding, agent=agent, version=version, account_id=account_id)
@classmethod
def _workflow_composer_version(
@@ -214,7 +218,7 @@ class AgentComposerService:
agent_id=agent.id if agent else None,
version_id=version_id,
)
- state = cls._serialize_workflow_state(binding=binding, agent=agent, version=version)
+ state = cls._serialize_workflow_state(binding=binding, agent=agent, version=version, account_id=account_id)
state["validation"] = cls.collect_validation_findings(
tenant_id=tenant_id,
payload=payload,
@@ -246,7 +250,7 @@ class AgentComposerService:
agent_id=agent.id if agent else None,
version_id=binding.current_snapshot_id,
)
- return cls._serialize_workflow_state(binding=binding, agent=agent, version=version)
+ return cls._serialize_workflow_state(binding=binding, agent=agent, version=version, account_id=account_id)
if binding.binding_type != WorkflowAgentBindingType.ROSTER_AGENT:
raise InvalidComposerConfigError("Workflow agent node must be bound to a roster agent.")
@@ -300,7 +304,9 @@ class AgentComposerService:
agent_id=inline_agent.id,
version_id=inline_agent.active_config_snapshot_id,
)
- return cls._serialize_workflow_state(binding=binding, agent=inline_agent, version=version)
+ return cls._serialize_workflow_state(
+ binding=binding, agent=inline_agent, version=version, account_id=account_id
+ )
@classmethod
def load_agent_app_composer(cls, *, tenant_id: str, app_id: str) -> dict[str, Any]:
@@ -419,7 +425,11 @@ class AgentComposerService:
account_id_for_audit=account_id,
)
agent.updated_by = account_id
- agent.active_config_is_published = False
+ agent.active_config_is_published = cls._agent_soul_matches_active_config(
+ tenant_id=tenant_id,
+ agent=agent,
+ agent_soul=payload.agent_soul,
+ )
db.session.commit()
state = cls.load_agent_composer(tenant_id=tenant_id, agent_id=agent.id)
@@ -430,6 +440,54 @@ class AgentComposerService:
)
return state
+ @classmethod
+ def _agent_soul_matches_active_config(
+ cls,
+ *,
+ tenant_id: str,
+ agent: Agent,
+ agent_soul: AgentSoulConfig,
+ ) -> bool:
+ if not agent.active_config_snapshot_id:
+ return False
+
+ active_version = cls._get_version_if_present(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ version_id=agent.active_config_snapshot_id,
+ )
+ if not active_version:
+ return False
+ if agent.source == AgentSource.AGENT_APP and not cls._has_publish_visible_revision(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ snapshot_id=agent.active_config_snapshot_id,
+ ):
+ return False
+
+ return _agent_soul_config_json(agent_soul) == _agent_soul_config_json(active_version.config_snapshot_dict)
+
+ @classmethod
+ def _has_publish_visible_revision(cls, *, tenant_id: str, agent_id: str, snapshot_id: str) -> bool:
+ revisions = db.session.scalars(
+ select(AgentConfigRevision.operation).where(
+ AgentConfigRevision.tenant_id == tenant_id,
+ AgentConfigRevision.agent_id == agent_id,
+ AgentConfigRevision.current_snapshot_id == snapshot_id,
+ )
+ ).all()
+
+ return any(
+ operation
+ in {
+ AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ AgentConfigRevisionOperation.SAVE_NEW_VERSION,
+ AgentConfigRevisionOperation.SAVE_TO_ROSTER,
+ AgentConfigRevisionOperation.RESTORE_VERSION,
+ }
+ for operation in revisions
+ )
+
@classmethod
def publish_agent_app_draft(
cls, *, tenant_id: str, agent_id: str, account_id: str, version_note: str | None = None
@@ -557,16 +615,21 @@ class AgentComposerService:
)
if build_draft is None:
raise AgentVersionNotFoundError()
+ applied_agent_soul = AgentSoulConfig.model_validate(build_draft.config_snapshot_dict)
normal_draft = cls._save_agent_draft(
tenant_id=tenant_id,
agent=agent,
draft_type=AgentConfigDraftType.DRAFT,
account_id=None,
- agent_soul=AgentSoulConfig.model_validate(build_draft.config_snapshot_dict),
+ agent_soul=applied_agent_soul,
account_id_for_audit=account_id,
base_snapshot_id=build_draft.base_snapshot_id,
)
- agent.active_config_is_published = False
+ agent.active_config_is_published = cls._agent_soul_matches_active_config(
+ tenant_id=tenant_id,
+ agent=agent,
+ agent_soul=applied_agent_soul,
+ )
agent.updated_by = account_id
db.session.delete(build_draft)
db.session.commit()
@@ -1788,6 +1851,7 @@ class AgentComposerService:
binding: WorkflowAgentNodeBinding,
agent: Agent | None,
version: AgentConfigSnapshot | None,
+ account_id: str | None = None,
) -> dict[str, Any]:
locked = bool(agent and agent.scope == AgentScope.ROSTER)
save_options = [ComposerSaveStrategy.NODE_JOB_ONLY.value]
@@ -1801,6 +1865,19 @@ class AgentComposerService:
)
else:
save_options.append(ComposerSaveStrategy.SAVE_TO_ROSTER.value)
+ debug_conversation_id = cls._workflow_inline_debug_conversation_id(
+ tenant_id=binding.tenant_id,
+ binding=binding,
+ agent=agent,
+ account_id=account_id,
+ )
+ debug_conversation_message_count = (
+ AgentRosterService(db.session).count_agent_app_debug_conversation_messages(
+ conversation_id=debug_conversation_id
+ )
+ if debug_conversation_id
+ else 0
+ )
return {
"variant": ComposerVariant.WORKFLOW.value,
"agent": cls._serialize_agent(agent) if agent else None,
@@ -1835,10 +1912,37 @@ class AgentComposerService:
"backing_app_id": agent.backing_app_id if agent else None,
"hidden_app_backed": bool(agent and agent.scope == AgentScope.WORKFLOW_ONLY and agent.backing_app_id),
"chat_endpoint": f"/console/api/agent/{agent.id}/chat-messages" if agent else None,
+ "debug_conversation_id": debug_conversation_id,
+ "debug_conversation_has_messages": debug_conversation_message_count > 0,
+ "debug_conversation_message_count": debug_conversation_message_count,
"workflow_id": binding.workflow_id,
"node_id": binding.node_id,
}
+ @staticmethod
+ def _workflow_inline_debug_conversation_id(
+ *,
+ tenant_id: str,
+ binding: WorkflowAgentNodeBinding,
+ agent: Agent | None,
+ account_id: str | None,
+ ) -> str | None:
+ if (
+ not account_id
+ or not agent
+ or binding.binding_type != WorkflowAgentBindingType.INLINE_AGENT
+ or agent.scope != AgentScope.WORKFLOW_ONLY
+ ):
+ return None
+
+ from services.agent.roster_service import AgentRosterService
+
+ return AgentRosterService(db.session).get_or_create_agent_app_debug_conversation_id(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ account_id=account_id,
+ )
+
@classmethod
def _serialize_agent(cls, agent: Agent) -> dict[str, Any]:
return {
diff --git a/api/services/agent/config_skill_normalize_service.py b/api/services/agent/config_skill_normalize_service.py
new file mode 100644
index 00000000000..8c06dc2bcc8
--- /dev/null
+++ b/api/services/agent/config_skill_normalize_service.py
@@ -0,0 +1,67 @@
+"""Normalize uploaded config skills into one canonical ToolFile reference.
+
+Config skills are Agent Soul-backed assets, not drive rows. This service keeps
+the existing skill package validation rules, enforces the requested stable name,
+stores the normalized archive as one ToolFile, and returns the persisted Soul
+reference metadata used by ``AgentConfigService``.
+"""
+
+from __future__ import annotations
+
+from core.tools.tool_file_manager import ToolFileManager
+from models.agent_config_entities import AgentConfigSkillRefConfig, validate_config_skill_name
+from services.agent.skill_package_service import NormalizedSkillPackage, SkillPackageError, SkillPackageService
+
+
+class ConfigSkillNormalizeService:
+ """Validate, normalize, and persist one config skill archive."""
+
+ def __init__(
+ self,
+ *,
+ package_service: SkillPackageService | None = None,
+ tool_file_manager: ToolFileManager | None = None,
+ ) -> None:
+ self._package = package_service or SkillPackageService()
+ self._tool_files = tool_file_manager or ToolFileManager()
+
+ def normalize(
+ self,
+ *,
+ content: bytes,
+ filename: str,
+ requested_name: str | None,
+ tenant_id: str,
+ user_id: str,
+ ) -> tuple[AgentConfigSkillRefConfig, NormalizedSkillPackage]:
+ package = self._package.validate_and_normalize(content=content, filename=filename)
+ normalized_name = validate_config_skill_name(requested_name or package.manifest.name)
+ if package.manifest.name != normalized_name:
+ raise SkillPackageError(
+ "skill_name_mismatch",
+ "skill package name must match the requested config skill name",
+ status_code=400,
+ )
+
+ tool_file = self._tool_files.create_file_by_raw(
+ user_id=user_id,
+ tenant_id=tenant_id,
+ conversation_id=None,
+ file_binary=package.archive_bytes,
+ mimetype="application/zip",
+ filename=f"{normalized_name}.zip",
+ )
+ return (
+ AgentConfigSkillRefConfig(
+ name=normalized_name,
+ description=package.manifest.description,
+ file_id=tool_file.id,
+ size=tool_file.size,
+ hash=package.manifest.hash,
+ mime_type=tool_file.mimetype,
+ ),
+ package,
+ )
+
+
+__all__ = ["ConfigSkillNormalizeService"]
diff --git a/api/services/agent/prompt_mentions.py b/api/services/agent/prompt_mentions.py
index 520c36043bd..15d257f474a 100644
--- a/api/services/agent/prompt_mentions.py
+++ b/api/services/agent/prompt_mentions.py
@@ -33,6 +33,8 @@ from enum import StrEnum
from models.agent_config_entities import (
AgentHumanContactConfig,
AgentSoulConfig,
+ DeclaredOutputConfig,
+ DeclaredOutputType,
WorkflowNodeJobConfig,
WorkflowPreviousNodeOutputRef,
)
@@ -50,6 +52,8 @@ class MentionKind(StrEnum):
MENTION_PATTERN = re.compile(
+ r"(?:\[§(?P<reversed_output_id>[^:§]+?):(?P<reversed_output_label>[^:§]*?):(?P<reversed_output_kind>output)§\])"
+ r"|"
r"(?:\[§(?P<bracket_kind>skill|file|tool|cli_tool|knowledge|human|node_output|output):"
r"(?P<bracket_id>[^:§]+?)(?::(?P<bracket_label>[^§]*?))?§\])"
r"|(?:§(?P<legacy_kind>output):(?P<legacy_id>[^:§]+?)(?::(?P<legacy_label>[^§]*?))?§)"
@@ -111,6 +115,8 @@ MentionResolver = Callable[[PromptMention], str | None]
def _mention_groups(match: re.Match[str]) -> tuple[str, str, str | None]:
+ if match.group("reversed_output_kind"):
+ return MentionKind.OUTPUT.value, match.group("reversed_output_id"), match.group("reversed_output_label")
kind = match.group("bracket_kind") or match.group("legacy_kind")
ref_id = match.group("bracket_id") or match.group("legacy_id")
label = match.group("bracket_label") or match.group("legacy_label")
@@ -162,7 +168,7 @@ def expand_prompt_mentions(prompt: str, resolver: MentionResolver) -> str:
resolved = resolver(mention)
if resolved is None or not resolved.strip():
return fallback
- return resolved[:MAX_MENTION_LABEL_LENGTH]
+ return resolved
return scrub_mention_markers(MENTION_PATTERN.sub(_replace, prompt))
@@ -298,7 +304,7 @@ def build_node_job_mention_resolver(node_job: WorkflowNodeJobConfig) -> MentionR
case MentionKind.OUTPUT:
for output in node_job.declared_outputs:
if output.name == mention.ref_id:
- return f"{output.name} ({output.type.value})"
+ return _format_output_mention(output)
case MentionKind.HUMAN:
return _resolve_human_contact(node_job.human_contacts, mention.ref_id)
case _:
@@ -308,6 +314,28 @@ def build_node_job_mention_resolver(node_job: WorkflowNodeJobConfig) -> MentionR
return _resolve
+def _format_output_mention(output: DeclaredOutputConfig) -> str:
+ if output.type == DeclaredOutputType.FILE:
+ return (
+ f"{output.name} (file output; create the file locally, run "
+ f"`dify-agent file upload <path>`, then copy the returned AgentStubFileMapping JSON "
+ f"as final_output.{output.name}; do not call final_output before upload succeeds, and do not use "
+ "the local path, filename, URL, or a synthesized dify-file-ref as the reference)"
+ )
+ if (
+ output.type == DeclaredOutputType.ARRAY
+ and output.array_item
+ and output.array_item.type == DeclaredOutputType.FILE
+ ):
+ return (
+ f"{output.name} (array[file] output; upload each produced file with "
+ f"`dify-agent file upload <path>`, then copy the returned AgentStubFileMapping JSON objects "
+ f"as final_output.{output.name}; do not call final_output before all uploads succeed, and do not use "
+ "local paths, filenames, URLs, or synthesized dify-file-ref values as references)"
+ )
+ return f"{output.name} ({output.type.value})"
+
+
def _resolve_human_contact(contacts: list[AgentHumanContactConfig], ref_id: str) -> str | None:
for contact in contacts:
if ref_id in (contact.id, contact.contact_id, contact.human_id):
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index d18a1781892..a34fca67105 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -24,7 +24,7 @@ from models.agent import (
)
from models.agent_config_entities import AgentSoulConfig
from models.enums import AppStatus, ConversationFromSource, ConversationStatus
-from models.model import App, AppMode, AppModelConfig, Conversation, IconType
+from models.model import App, AppMode, AppModelConfig, Conversation, IconType, Message
from models.workflow import Workflow
from services.agent.agent_soul_state import agent_soul_has_model
from services.agent.composer_validator import ComposerConfigValidator
@@ -571,6 +571,35 @@ class AgentRosterService:
self._session.commit()
return conversation_id
+ def load_agent_app_debug_conversation_id(self, *, tenant_id: str, agent_id: str, account_id: str) -> str | None:
+ """Return the current editor's existing debug conversation without creating or repairing rows."""
+
+ return self._session.scalar(
+ select(Conversation.id)
+ .join(AgentDebugConversation, AgentDebugConversation.conversation_id == Conversation.id)
+ .where(
+ AgentDebugConversation.tenant_id == tenant_id,
+ AgentDebugConversation.agent_id == agent_id,
+ AgentDebugConversation.account_id == account_id,
+ AgentDebugConversation.app_id == Conversation.app_id,
+ Conversation.from_source == ConversationFromSource.CONSOLE,
+ Conversation.from_account_id == account_id,
+ Conversation.is_deleted.is_(False),
+ )
+ )
+
+ def count_agent_app_debug_conversation_messages(self, *, conversation_id: str) -> int:
+ """Return the number of visible messages in an Agent App debug conversation."""
+
+ return (
+ self._session.scalar(
+ select(func.count(Message.id)).where(
+ Message.conversation_id == conversation_id,
+ )
+ )
+ or 0
+ )
+
def refresh_agent_app_debug_conversation_id(
self, *, tenant_id: str, agent_id: str, account_id: str, commit: bool = True
) -> str:
@@ -992,9 +1021,10 @@ class AgentRosterService:
def load_active_config_is_published_by_agent_id(self, *, tenant_id: str, agents: list[Agent]) -> dict[str, bool]:
"""Return each Agent's stored normal-draft publish state.
- The flag is maintained by write paths: normal shared draft writes mark it
- dirty, while publish/version creation paths mark it clean. User-scoped
- debug drafts intentionally do not affect this state.
+ The flag is maintained by write paths against the normal shared draft:
+ saves compare the draft content with the active snapshot, while publish
+ and version creation paths mark the new active snapshot clean.
+ User-scoped debug drafts intentionally do not affect this state.
"""
agents = [agent for agent in agents if agent.id]
if not agents:
diff --git a/api/services/agent/workflow_publish_service.py b/api/services/agent/workflow_publish_service.py
index fb20c5c4dac..2c69d9135df 100644
--- a/api/services/agent/workflow_publish_service.py
+++ b/api/services/agent/workflow_publish_service.py
@@ -12,7 +12,6 @@ from core.workflow.nodes.agent_v2.validators import WorkflowAgentNodeValidationE
from models.agent import (
Agent,
AgentConfigSnapshot,
- AgentDriveFile,
AgentScope,
AgentStatus,
WorkflowAgentBindingType,
@@ -187,38 +186,22 @@ class WorkflowAgentPublishService:
agent_soul: AgentSoulConfig,
) -> None:
from services.agent.prompt_mentions import MentionKind, parse_prompt_mentions
- from services.agent_drive_service import decode_drive_mention_ref
- wanted_keys: dict[str, tuple[str, str]] = {}
+ del session
+ configured_skill_names = {item.name for item in agent_soul.config_skills}
+ configured_file_names = {item.name for item in agent_soul.config_files}
+ missing_refs: list[str] = []
for mention in parse_prompt_mentions(agent_soul.prompt.system_prompt):
if mention.kind not in {MentionKind.SKILL, MentionKind.FILE}:
continue
- drive_key = decode_drive_mention_ref(mention.ref_id)
- if not drive_key:
- continue
- code = "skill_ref_dangling" if mention.kind == MentionKind.SKILL else "file_ref_dangling"
- wanted_keys[drive_key] = (code, mention.label or drive_key)
- if not wanted_keys or not binding.agent_id:
- return
-
- existing_keys = set(
- session.scalars(
- select(AgentDriveFile.key).where(
- AgentDriveFile.tenant_id == binding.tenant_id,
- AgentDriveFile.agent_id == binding.agent_id,
- AgentDriveFile.key.in_(sorted(wanted_keys)),
- )
- ).all()
- )
- messages: list[str] = []
- for key, (code, display) in wanted_keys.items():
- if key in existing_keys:
- continue
- kind = "skill" if code == "skill_ref_dangling" else "file"
- messages.append(f"{code}: {kind} '{display}' has no drive entry for key '{key}'.")
- if messages:
+ ref_name = mention.ref_id
+ if mention.kind == MentionKind.SKILL and ref_name not in configured_skill_names:
+ missing_refs.append(f"skill_ref_dangling: skill '{mention.label or ref_name}' is not configured.")
+ if mention.kind == MentionKind.FILE and ref_name not in configured_file_names:
+ missing_refs.append(f"file_ref_dangling: file '{mention.label or ref_name}' is not configured.")
+ if missing_refs:
raise WorkflowAgentNodeValidationError(
- f"Workflow Agent node {binding.node_id} has invalid Agent Soul drive refs: {'; '.join(messages)}"
+ f"Workflow Agent node {binding.node_id} has invalid Agent Soul config refs: {'; '.join(missing_refs)}"
)
@classmethod
diff --git a/api/services/agent_config_service.py b/api/services/agent_config_service.py
new file mode 100644
index 00000000000..af05acb9ef7
--- /dev/null
+++ b/api/services/agent_config_service.py
@@ -0,0 +1,1367 @@
+"""Agent Soul-backed config assets for skills, files, env, and note text.
+
+This service is the single API-side control plane for Agent config assets. It
+resolves the requested config version (published snapshot, shared draft, or
+per-user build draft), reads only from ``AgentSoulConfig.config_skills``,
+``config_files``, ``env.variables``, and ``config_note``, and mutates only the
+target Soul JSON. Source file refs are tenant-scoped rather than user-scoped:
+config writes can be owned by a build-draft Account while the uploaded
+``ToolFile`` came from an end-user execution context. It intentionally does not
+manage object-storage lifecycle: removing or replacing a config asset drops the
+Soul reference only.
+"""
+
+from __future__ import annotations
+
+import io
+import urllib.parse
+import zipfile
+from dataclasses import dataclass
+from enum import StrEnum
+from operator import itemgetter
+from typing import Literal
+
+from dotenv import dotenv_values
+from pydantic import BaseModel, ConfigDict, Field
+from sqlalchemy import select
+from sqlalchemy.exc import DataError, SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from core.app.file_access.controller import DatabaseFileAccessController
+from core.db.session_factory import session_factory
+from core.tools.tool_file_manager import ToolFileManager
+from extensions.ext_storage import storage
+from factories import file_factory
+from models.agent import Agent, AgentConfigDraft, AgentConfigDraftType, AgentConfigSnapshot
+from models.agent_config_entities import (
+ AgentConfigFileRefConfig,
+ AgentConfigSkillRefConfig,
+ AgentEnvVariableConfig,
+ AgentSoulConfig,
+ validate_config_name,
+ validate_config_skill_name,
+)
+from models.model import UploadFile
+from models.tools import ToolFile
+from services.agent.config_skill_normalize_service import ConfigSkillNormalizeService
+from services.agent.skill_package_service import SkillPackageError
+from services.agent_drive_service import DriveFileRef
+
+
+class AgentConfigVersionKind(StrEnum):
+ SNAPSHOT = "snapshot"
+ DRAFT = "draft"
+ BUILD_DRAFT = "build_draft"
+
+
+class AgentConfigMutationSurface(StrEnum):
+ AGENT_STUB = "agent_stub"
+ CONSOLE = "console"
+
+
+class AgentConfigServiceError(Exception):
+ """Config operation failure mapped to HTTP status at controller boundaries."""
+
+ code: str
+ message: str
+ status_code: int
+
+ def __init__(self, code: str, message: str, *, status_code: int = 400) -> None:
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.status_code = status_code
+
+
+class ConfigPushFileItem(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ name: str
+ file_ref: DriveFileRef | None = None
+
+
+class ConfigPushSkillItem(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ name: str
+ file_ref: DriveFileRef | None = None
+
+
+class ConfigPushPayload(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ files: list[ConfigPushFileItem] = Field(default_factory=list)
+ skills: list[ConfigPushSkillItem] = Field(default_factory=list)
+ env_text: str | None = None
+ note: str | None = None
+
+
+@dataclass(slots=True)
+class AgentConfigTarget:
+ agent_id: str
+ version_id: str
+ kind: AgentConfigVersionKind
+ writable: bool
+ version: AgentConfigSnapshot | AgentConfigDraft
+ agent_soul: AgentSoulConfig
+
+
+@dataclass(frozen=True, slots=True)
+class ConfigDownload:
+ filename: str
+ mime_type: str
+ payload: bytes
+
+
+class AgentConfigService:
+ """Read and update Agent Soul-backed config assets for one version target."""
+
+ PREVIEW_MAX_BYTES = 64 * 1024
+
+ def __init__(
+ self,
+ *,
+ tool_file_manager: ToolFileManager | None = None,
+ skill_normalize_service: ConfigSkillNormalizeService | None = None,
+ ) -> None:
+ self._tool_files = tool_file_manager or ToolFileManager()
+ self._skill_normalizer = skill_normalize_service or ConfigSkillNormalizeService()
+
+ def resolve_target(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ user_id: str | None = None,
+ ) -> AgentConfigTarget:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ return AgentConfigTarget(
+ agent_id=target.agent_id,
+ version_id=target.version_id,
+ kind=target.kind,
+ writable=target.writable,
+ version=target.version,
+ agent_soul=target.agent_soul.model_copy(deep=True),
+ )
+
+ def manifest(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ return self._manifest_for_target(target)
+
+ def list_skills(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ return {
+ "agent_id": target.agent_id,
+ "config_version": self._config_version_payload(target),
+ "items": [self._serialize_skill_item(skill) for skill in target.agent_soul.config_skills],
+ }
+
+ def list_files(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ return {
+ "agent_id": target.agent_id,
+ "config_version": self._config_version_payload(target),
+ "items": [self._serialize_file_item(file_ref) for file_ref in target.agent_soul.config_files],
+ }
+
+ def pull_skill(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> ConfigDownload:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ payload, mime_type = self._load_tool_file_bytes(tenant_id=tenant_id, file_id=skill.file_id)
+ return ConfigDownload(filename=f"{skill.name}.zip", mime_type=mime_type or "application/zip", payload=payload)
+
+ def download_skill_url(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> str:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ url = self._resolve_download_url(tenant_id=tenant_id, file_kind=skill.file_kind, file_id=skill.file_id)
+ if url is None:
+ raise AgentConfigServiceError("config_skill_not_found", "config skill payload is missing", status_code=404)
+ return url
+
+ def inspect_skill(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ archive_bytes, _mime_type = self._load_tool_file_bytes(tenant_id=tenant_id, file_id=skill.file_id)
+ try:
+ archive_items, skill_md = self._inspect_skill_archive(archive_bytes)
+ except (OSError, ValueError, zipfile.BadZipFile) as exc:
+ raise AgentConfigServiceError(
+ "skill_archive_invalid",
+ "stored config skill archive is invalid",
+ status_code=500,
+ ) from exc
+ return {
+ **self._serialize_skill_item(skill),
+ "source": "config_skill_zip",
+ "files": archive_items,
+ "skill_md": skill_md,
+ "warnings": [],
+ }
+
+ def preview_skill_file(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ path: str,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ member_path = self._normalize_archive_member_path(path)
+ payload = self._load_skill_archive_member(
+ tenant_id=tenant_id,
+ file_id=skill.file_id,
+ path=member_path,
+ )
+ return self._preview_bytes(path=member_path, size=len(payload), payload=payload)
+
+ def pull_skill_file(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ path: str,
+ user_id: str | None = None,
+ ) -> ConfigDownload:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ member_path = self._normalize_archive_member_path(path)
+ payload = self._load_skill_archive_member(
+ tenant_id=tenant_id,
+ file_id=skill.file_id,
+ path=member_path,
+ )
+ return ConfigDownload(
+ filename=member_path.rsplit("/", 1)[-1],
+ mime_type="application/octet-stream",
+ payload=payload,
+ )
+
+ def resolve_skill_file_member_path(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ path: str,
+ user_id: str | None = None,
+ ) -> str:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ skill = self._require_skill(target.agent_soul, name=name)
+ member_path = self._normalize_archive_member_path(path)
+ self._load_skill_archive_member(
+ tenant_id=tenant_id,
+ file_id=skill.file_id,
+ path=member_path,
+ )
+ return member_path
+
+ def pull_file(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> ConfigDownload:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ file_ref = self._require_file(target.agent_soul, name=name)
+ payload, filename, mime_type = self._load_file_ref_bytes(
+ tenant_id=tenant_id,
+ file_kind=file_ref.file_kind,
+ file_id=file_ref.file_id,
+ )
+ return ConfigDownload(
+ filename=filename or file_ref.name, mime_type=mime_type or "application/octet-stream", payload=payload
+ )
+
+ def download_file_url(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> str:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ file_ref = self._require_file(target.agent_soul, name=name)
+ url = self._resolve_download_url(tenant_id=tenant_id, file_kind=file_ref.file_kind, file_id=file_ref.file_id)
+ if url is None:
+ raise AgentConfigServiceError("config_file_not_found", "config file payload is missing", status_code=404)
+ return url
+
+ def upload_skill(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ content: bytes,
+ filename: str,
+ ) -> dict[str, object]:
+ return self._upload_skill(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ content=content,
+ filename=filename,
+ surface=AgentConfigMutationSurface.AGENT_STUB,
+ )
+
+ def upload_skill_for_console(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ content: bytes,
+ filename: str,
+ ) -> dict[str, object]:
+ return self._upload_skill(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ content=content,
+ filename=filename,
+ surface=AgentConfigMutationSurface.CONSOLE,
+ )
+
+ def _upload_skill(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ content: bytes,
+ filename: str,
+ surface: AgentConfigMutationSurface,
+ ) -> dict[str, object]:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ skill_ref, _package = self._skill_normalizer.normalize(
+ content=content,
+ filename=filename,
+ requested_name=None,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ existing = {item.name: item for item in agent_soul.config_skills}
+ order = [item.name for item in agent_soul.config_skills]
+ if skill_ref.name not in order:
+ order.append(skill_ref.name)
+ existing[skill_ref.name] = skill_ref
+ agent_soul.config_skills = [existing[name] for name in order if name in existing]
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ target.agent_soul = agent_soul
+ return {
+ "skill": self._serialize_skill_item(skill_ref),
+ "config_version": self._config_version_payload(target),
+ }
+
+ def push(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ payload: ConfigPushPayload,
+ ) -> dict[str, object]:
+ return self._push(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ payload=payload,
+ surface=AgentConfigMutationSurface.AGENT_STUB,
+ )
+
+ def push_for_console(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ payload: ConfigPushPayload,
+ ) -> dict[str, object]:
+ return self._push(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ payload=payload,
+ surface=AgentConfigMutationSurface.CONSOLE,
+ )
+
+ def push_file_for_console(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ upload_file_id: str,
+ ) -> dict[str, object]:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=AgentConfigMutationSurface.CONSOLE)
+ upload_file = self._require_console_upload_file_source(session, tenant_id=tenant_id, file_id=upload_file_id)
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ agent_soul.config_files = self._upsert_upload_file(
+ current=agent_soul.config_files,
+ upload_file=upload_file,
+ )
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ target.agent_soul = agent_soul
+ file_ref = self._require_file(agent_soul, name=upload_file.name)
+ return {
+ "file": self._serialize_file_item(file_ref),
+ "config_version": self._config_version_payload(target),
+ }
+
+ def _push(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ payload: ConfigPushPayload,
+ surface: AgentConfigMutationSurface,
+ ) -> dict[str, object]:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ if payload.files:
+ agent_soul.config_files = self._apply_file_updates(
+ session,
+ tenant_id=tenant_id,
+ current=agent_soul.config_files,
+ updates=payload.files,
+ )
+ if payload.skills:
+ agent_soul.config_skills = self._apply_skill_updates(
+ session,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ current=agent_soul.config_skills,
+ updates=payload.skills,
+ )
+ if payload.env_text is not None:
+ agent_soul.env.variables = self._apply_env_text(agent_soul.env.variables, payload.env_text)
+ if payload.note is not None:
+ agent_soul.config_note = payload.note
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ target.agent_soul = agent_soul
+ return self._manifest_for_target(target)
+
+ def preview_file(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ name: str,
+ user_id: str | None = None,
+ ) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ file_ref = self._require_file(target.agent_soul, name=name)
+ payload, filename, _mime_type = self._load_file_ref_bytes(
+ tenant_id=tenant_id,
+ file_kind=file_ref.file_kind,
+ file_id=file_ref.file_id,
+ )
+ return self._preview_bytes(
+ path=filename or file_ref.name, size=file_ref.size, payload=payload, field_name="name"
+ )
+
+ def update_env(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ env_text: str,
+ ) -> dict[str, object]:
+ return self._update_env(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ env_text=env_text,
+ surface=AgentConfigMutationSurface.AGENT_STUB,
+ )
+
+ def _update_env(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ env_text: str,
+ surface: AgentConfigMutationSurface,
+ ) -> dict[str, object]:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ agent_soul.env.variables = self._apply_env_text(agent_soul.env.variables, env_text)
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ return {"env_keys": self._env_keys(agent_soul)}
+
+ def update_note(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ note: str,
+ ) -> dict[str, object]:
+ return self._update_note(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ user_id=user_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ note=note,
+ surface=AgentConfigMutationSurface.AGENT_STUB,
+ )
+
+ def _update_note(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ note: str,
+ surface: AgentConfigMutationSurface,
+ ) -> dict[str, object]:
+ with session_factory.create_session() as session:
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ agent_soul.config_note = note
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ return {"note": agent_soul.config_note}
+
+ def _resolve_target_in_session(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ user_id: str | None,
+ ) -> AgentConfigTarget:
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
+ version: AgentConfigSnapshot | AgentConfigDraft | None
+ try:
+ match config_version_kind:
+ case AgentConfigVersionKind.SNAPSHOT:
+ version = session.scalar(
+ select(AgentConfigSnapshot).where(
+ AgentConfigSnapshot.tenant_id == tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id == config_version_id,
+ )
+ )
+ writable = False
+ case AgentConfigVersionKind.DRAFT:
+ version = session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.id == config_version_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ AgentConfigDraft.account_id.is_(None),
+ )
+ )
+ writable = False
+ case AgentConfigVersionKind.BUILD_DRAFT:
+ if not user_id:
+ raise AgentConfigServiceError(
+ "missing_user_id",
+ "user_id is required for build draft config access",
+ status_code=400,
+ )
+ version = session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.id == config_version_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DEBUG_BUILD,
+ AgentConfigDraft.account_id == user_id,
+ )
+ )
+ writable = True
+ case _:
+ raise AgentConfigServiceError("invalid_config_version_kind", "unsupported config version kind")
+ except (DataError, SQLAlchemyError) as exc:
+ session.rollback()
+ raise AgentConfigServiceError(
+ "config_version_not_found",
+ "agent config version was not found",
+ status_code=404,
+ ) from exc
+ if version is None:
+ raise AgentConfigServiceError(
+ "config_version_not_found",
+ "agent config version was not found",
+ status_code=404,
+ )
+ return AgentConfigTarget(
+ agent_id=agent_id,
+ version_id=version.id,
+ kind=config_version_kind,
+ writable=writable,
+ version=version,
+ agent_soul=AgentSoulConfig.model_validate(version.config_snapshot_dict),
+ )
+
+ @staticmethod
+ def _assert_agent_belongs_to_tenant(session: Session, *, tenant_id: str, agent_id: str) -> None:
+ try:
+ found = session.scalar(select(Agent.id).where(Agent.id == agent_id, Agent.tenant_id == tenant_id))
+ except (DataError, SQLAlchemyError) as exc:
+ session.rollback()
+ raise AgentConfigServiceError(
+ "agent_not_found", "agent does not belong to this tenant", status_code=404
+ ) from exc
+ if found is None:
+ raise AgentConfigServiceError("agent_not_found", "agent does not belong to this tenant", status_code=404)
+
+ @staticmethod
+ def _require_writable(target: AgentConfigTarget, *, surface: AgentConfigMutationSurface) -> None:
+ if target.writable:
+ return
+ if surface == AgentConfigMutationSurface.CONSOLE and target.kind == AgentConfigVersionKind.DRAFT:
+ return
+ if surface == AgentConfigMutationSurface.CONSOLE:
+ raise AgentConfigServiceError(
+ "config_not_writable",
+ "config mutations are only allowed for editable drafts",
+ status_code=403,
+ )
+ raise AgentConfigServiceError(
+ "config_not_writable",
+ "config push is only allowed for build drafts",
+ status_code=403,
+ )
+
+ def _apply_file_updates(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ current: list[AgentConfigFileRefConfig],
+ updates: list[ConfigPushFileItem],
+ ) -> list[AgentConfigFileRefConfig]:
+ by_name = {item.name: item for item in current}
+ order = [item.name for item in current]
+ for update in updates:
+ name = validate_config_name(update.name)
+ if update.file_ref is None:
+ by_name.pop(name, None)
+ continue
+ size, hash_value, mime_type = self._validate_source_ref(
+ session,
+ tenant_id=tenant_id,
+ file_ref=update.file_ref,
+ )
+ if name not in order:
+ order.append(name)
+ by_name[name] = AgentConfigFileRefConfig(
+ name=name,
+ file_kind=update.file_ref.kind,
+ file_id=update.file_ref.id,
+ size=size,
+ hash=hash_value,
+ mime_type=mime_type,
+ )
+ return [by_name[name] for name in order if name in by_name]
+
+ @staticmethod
+ def _upsert_upload_file(
+ *,
+ current: list[AgentConfigFileRefConfig],
+ upload_file: UploadFile,
+ ) -> list[AgentConfigFileRefConfig]:
+ name = validate_config_name(upload_file.name)
+ by_name = {item.name: item for item in current}
+ order = [item.name for item in current]
+ if name not in order:
+ order.append(name)
+ by_name[name] = AgentConfigFileRefConfig(
+ name=name,
+ file_kind="upload_file",
+ file_id=upload_file.id,
+ size=upload_file.size,
+ hash=upload_file.hash,
+ mime_type=upload_file.mime_type,
+ )
+ return [by_name[item_name] for item_name in order if item_name in by_name]
+
+ def _apply_skill_updates(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ user_id: str,
+ current: list[AgentConfigSkillRefConfig],
+ updates: list[ConfigPushSkillItem],
+ ) -> list[AgentConfigSkillRefConfig]:
+ by_name = {item.name: item for item in current}
+ order = [item.name for item in current]
+ for update in updates:
+ name = validate_config_skill_name(update.name)
+ if update.file_ref is None:
+ by_name.pop(name, None)
+ continue
+ if update.file_ref.kind != "tool_file":
+ raise AgentConfigServiceError(
+ "invalid_skill_file_ref",
+ "config skills must be uploaded as tool files",
+ status_code=400,
+ )
+ tool_file = self._require_tool_file_source(
+ session,
+ tenant_id=tenant_id,
+ file_id=update.file_ref.id,
+ )
+ archive_bytes = storage.load_once(tool_file.file_key)
+ try:
+ skill_ref, _package = self._skill_normalizer.normalize(
+ content=archive_bytes,
+ filename=tool_file.name,
+ requested_name=name,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+ except SkillPackageError as exc:
+ raise AgentConfigServiceError(exc.code, exc.message, status_code=exc.status_code) from exc
+ if name not in order:
+ order.append(name)
+ by_name[name] = skill_ref
+ return [by_name[name] for name in order if name in by_name]
+
+ def _validate_source_ref(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ file_ref: DriveFileRef,
+ ) -> tuple[int | None, str | None, str | None]:
+ if file_ref.kind == "tool_file":
+ tool_file = self._require_tool_file_source(
+ session,
+ tenant_id=tenant_id,
+ file_id=file_ref.id,
+ )
+ return tool_file.size, None, tool_file.mimetype
+ upload_file = self._require_upload_file_source(session, tenant_id=tenant_id, file_id=file_ref.id)
+ return upload_file.size, upload_file.hash, upload_file.mime_type
+
+ @staticmethod
+ def _require_tool_file_source(
+ session: Session,
+ *,
+ tenant_id: str,
+ file_id: str,
+ ) -> ToolFile:
+ try:
+ tool_file = session.scalar(
+ select(ToolFile).where(
+ ToolFile.id == file_id,
+ ToolFile.tenant_id == tenant_id,
+ )
+ )
+ except (DataError, SQLAlchemyError) as exc:
+ session.rollback()
+ raise AgentConfigServiceError(
+ "source_not_found", "source tool file ref is invalid", status_code=404
+ ) from exc
+ if tool_file is None:
+ raise AgentConfigServiceError(
+ "source_not_found",
+ "source ToolFile not found for this tenant",
+ status_code=404,
+ )
+ return tool_file
+
+ @staticmethod
+ def _require_console_upload_file_source(session: Session, *, tenant_id: str, file_id: str) -> UploadFile:
+ try:
+ upload_file = session.scalar(
+ select(UploadFile).where(
+ UploadFile.id == file_id,
+ UploadFile.tenant_id == tenant_id,
+ )
+ )
+ except (DataError, SQLAlchemyError) as exc:
+ session.rollback()
+ raise AgentConfigServiceError(
+ "upload_file_not_found",
+ "upload file not found in this workspace",
+ status_code=404,
+ ) from exc
+ if upload_file is None:
+ raise AgentConfigServiceError(
+ "upload_file_not_found",
+ "upload file not found in this workspace",
+ status_code=404,
+ )
+ return upload_file
+
+ @staticmethod
+ def _require_upload_file_source(session: Session, *, tenant_id: str, file_id: str) -> UploadFile:
+ try:
+ upload_file = session.scalar(
+ select(UploadFile).where(
+ UploadFile.id == file_id,
+ UploadFile.tenant_id == tenant_id,
+ )
+ )
+ except (DataError, SQLAlchemyError) as exc:
+ session.rollback()
+ raise AgentConfigServiceError(
+ "source_not_found", "source upload file ref is invalid", status_code=404
+ ) from exc
+ if upload_file is None:
+ raise AgentConfigServiceError(
+ "source_not_found",
+ "source UploadFile not found for this tenant",
+ status_code=404,
+ )
+ return upload_file
+
+ @staticmethod
+ def _env_keys(agent_soul: AgentSoulConfig) -> list[str]:
+ keys = [item.key or item.name or item.env_name or item.variable for item in agent_soul.env.variables]
+ return [key for key in keys if key]
+
+ @staticmethod
+ def _apply_env_text(current: list[AgentEnvVariableConfig], env_text: str) -> list[AgentEnvVariableConfig]:
+ updates = AgentConfigService._parse_env_text(env_text)
+ order: list[str] = []
+ by_key: dict[str, AgentEnvVariableConfig] = {}
+ for item in current:
+ key = AgentConfigService._env_variable_key(item)
+ if key and key not in by_key:
+ by_key[key] = item
+ order.append(key)
+ for key, value in updates:
+ if value is None:
+ by_key.pop(key, None)
+ continue
+ if key not in order:
+ order.append(key)
+ by_key[key] = AgentEnvVariableConfig(key=key, name=key, value=value)
+ return [by_key[key] for key in order if key in by_key]
+
+ @staticmethod
+ def _env_variable_key(item: AgentEnvVariableConfig) -> str | None:
+ for candidate in (item.key, item.name, item.env_name, item.variable):
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return None
+
+ @staticmethod
+ def _parse_env_text(env_text: str) -> list[tuple[str, str | None]]:
+ updates: list[tuple[str, str | None]] = []
+ for raw_line in env_text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if line.startswith("export "):
+ line = line.removeprefix("export ").strip()
+ if "=" not in line:
+ raise AgentConfigServiceError("invalid_env_file", "env line must contain '='", status_code=400)
+ key, raw_value = line.split("=", 1)
+ key = key.strip()
+ AgentConfigService._validate_env_key(key)
+ if raw_value == "":
+ updates.append((key, None))
+ continue
+ parsed = dotenv_values(stream=io.StringIO(f"{key}={raw_value}\n"))
+ value = parsed.get(key)
+ if value is None:
+ raise AgentConfigServiceError("invalid_env_file", f"env value for {key} is invalid", status_code=400)
+ updates.append((key, value))
+ return updates
+
+ @staticmethod
+ def _validate_env_key(key: str) -> None:
+ normalized = key.strip()
+ if not normalized:
+ raise AgentConfigServiceError("invalid_env_file", "env key must not be blank", status_code=400)
+ if not (normalized[0].isalpha() or normalized[0] == "_"):
+ raise AgentConfigServiceError("invalid_env_file", f"invalid env key {normalized!r}", status_code=400)
+ if any(not (ch.isalnum() or ch == "_") for ch in normalized[1:]):
+ raise AgentConfigServiceError("invalid_env_file", f"invalid env key {normalized!r}", status_code=400)
+
+ @staticmethod
+ def _manifest_for_target(target: AgentConfigTarget) -> dict[str, object]:
+ return {
+ "agent_id": target.agent_id,
+ "config_version": AgentConfigService._config_version_payload(target),
+ "skills": {
+ "items": [AgentConfigService._serialize_skill_item(skill) for skill in target.agent_soul.config_skills]
+ },
+ "files": {
+ "items": [
+ AgentConfigService._serialize_file_item(file_ref) for file_ref in target.agent_soul.config_files
+ ]
+ },
+ "env_keys": AgentConfigService._env_keys(target.agent_soul),
+ "note": target.agent_soul.config_note,
+ }
+
+ @staticmethod
+ def _config_version_payload(target: AgentConfigTarget) -> dict[str, object]:
+ return {
+ "id": target.version_id,
+ "kind": target.kind.value,
+ "writable": AgentConfigService._is_console_writable(target),
+ }
+
+ @staticmethod
+ def _is_console_writable(target: AgentConfigTarget) -> bool:
+ return target.writable or target.kind == AgentConfigVersionKind.DRAFT
+
+ @staticmethod
+ def _serialize_skill_item(skill: AgentConfigSkillRefConfig) -> dict[str, object]:
+ return {
+ "id": skill.name,
+ "name": skill.name,
+ "file_id": skill.file_id,
+ "description": skill.description,
+ "size": skill.size,
+ "hash": skill.hash,
+ "mime_type": skill.mime_type,
+ }
+
+ @staticmethod
+ def _serialize_file_item(file_ref: AgentConfigFileRefConfig) -> dict[str, object]:
+ return {
+ "id": file_ref.name,
+ "name": file_ref.name,
+ "file_id": file_ref.file_id,
+ "size": file_ref.size,
+ "hash": file_ref.hash,
+ "mime_type": file_ref.mime_type,
+ }
+
+ @classmethod
+ def _preview_bytes(
+ cls,
+ *,
+ path: str,
+ size: int | None,
+ payload: bytes,
+ field_name: Literal["name", "path"] = "path",
+ ) -> dict[str, object]:
+ truncated = len(payload) > cls.PREVIEW_MAX_BYTES
+ sample = payload[: cls.PREVIEW_MAX_BYTES]
+ if b"\x00" in sample:
+ return {field_name: path, "size": size, "truncated": truncated, "binary": True, "text": None}
+ try:
+ text = sample.decode("utf-8")
+ except UnicodeDecodeError:
+ if truncated:
+ try:
+ text = sample[:-3].decode("utf-8", errors="strict")
+ except UnicodeDecodeError:
+ return {field_name: path, "size": size, "truncated": truncated, "binary": True, "text": None}
+ else:
+ return {field_name: path, "size": size, "truncated": truncated, "binary": True, "text": None}
+ return {field_name: path, "size": size, "truncated": truncated, "binary": False, "text": text}
+
+ @classmethod
+ def _normalize_archive_member_path(cls, path: str) -> str:
+ normalized = path.replace("\\", "/").strip("/")
+ if not normalized:
+ raise AgentConfigServiceError(
+ "config_skill_file_invalid", "config skill file path is invalid", status_code=400
+ )
+ if "\x00" in normalized or any(ord(ch) < 0x20 for ch in normalized):
+ raise AgentConfigServiceError(
+ "config_skill_file_invalid", "config skill file path is invalid", status_code=400
+ )
+ segments = normalized.split("/")
+ if any(not segment or segment in {".", ".."} for segment in segments):
+ raise AgentConfigServiceError(
+ "config_skill_file_invalid", "config skill file path is invalid", status_code=400
+ )
+ return "/".join(segments)
+
+ @classmethod
+ def _inspect_skill_archive(cls, archive_bytes: bytes) -> tuple[list[dict[str, object]], dict[str, object]]:
+ with zipfile.ZipFile(io.BytesIO(archive_bytes)) as archive:
+ members: list[dict[str, object]] = []
+ directories: set[str] = set()
+ skill_md_preview: dict[str, object] | None = None
+ for info in archive.infolist():
+ normalized_path = cls._normalize_archive_member_path(info.filename)
+ segments = normalized_path.split("/")
+ directories.update("/".join(segments[:index]) for index in range(1, len(segments)))
+ if info.is_dir():
+ directories.add(normalized_path)
+ continue
+ members.append(
+ {
+ "path": normalized_path,
+ "name": segments[-1],
+ "type": "file",
+ "previewable": True,
+ "downloadable": True,
+ }
+ )
+ if normalized_path == "SKILL.md":
+ payload = archive.read(info)
+ skill_md_preview = cls._preview_bytes(path="SKILL.md", size=info.file_size, payload=payload)
+ if skill_md_preview is None or skill_md_preview["binary"]:
+ raise ValueError("skill archive is missing a text SKILL.md")
+
+ directory_items: list[dict[str, object]] = [
+ {
+ "path": path,
+ "name": path.rsplit("/", 1)[-1],
+ "type": "directory",
+ "previewable": False,
+ "downloadable": False,
+ }
+ for path in sorted(directories)
+ ]
+ files = sorted([*directory_items, *members], key=itemgetter("path", "type"))
+ return files, skill_md_preview
+
+ def _load_skill_archive_member(self, *, tenant_id: str, file_id: str, path: str) -> bytes:
+ archive_bytes, _mime_type = self._load_tool_file_bytes(tenant_id=tenant_id, file_id=file_id)
+ normalized_path = self._normalize_archive_member_path(path)
+ try:
+ with zipfile.ZipFile(io.BytesIO(archive_bytes)) as archive:
+ for info in archive.infolist():
+ candidate_path = self._normalize_archive_member_path(info.filename)
+ if candidate_path != normalized_path:
+ continue
+ if info.is_dir():
+ raise AgentConfigServiceError(
+ "config_skill_file_not_found",
+ "config skill file not found",
+ status_code=404,
+ )
+ return archive.read(info)
+ except zipfile.BadZipFile as exc:
+ raise AgentConfigServiceError(
+ "skill_archive_invalid",
+ "stored config skill archive is invalid",
+ status_code=500,
+ ) from exc
+ raise AgentConfigServiceError("config_skill_file_not_found", "config skill file not found", status_code=404)
+
+ @staticmethod
+ def _require_skill(agent_soul: AgentSoulConfig, *, name: str) -> AgentConfigSkillRefConfig:
+ normalized = validate_config_skill_name(name)
+ for item in agent_soul.config_skills:
+ if item.name == normalized:
+ return item
+ raise AgentConfigServiceError("config_skill_not_found", "config skill not found", status_code=404)
+
+ @staticmethod
+ def _require_file(agent_soul: AgentSoulConfig, *, name: str) -> AgentConfigFileRefConfig:
+ normalized = validate_config_name(name)
+ for item in agent_soul.config_files:
+ if item.name == normalized:
+ return item
+ raise AgentConfigServiceError("config_file_not_found", "config file not found", status_code=404)
+
+ def _load_tool_file_bytes(self, *, tenant_id: str, file_id: str) -> tuple[bytes, str | None]:
+ with session_factory.create_session() as session:
+ tool_file = session.scalar(select(ToolFile).where(ToolFile.id == file_id, ToolFile.tenant_id == tenant_id))
+ if tool_file is None:
+ raise AgentConfigServiceError("config_skill_not_found", "config skill payload is missing", status_code=404)
+ return storage.load_once(tool_file.file_key), tool_file.mimetype
+
+ def _load_file_ref_bytes(
+ self,
+ *,
+ tenant_id: str,
+ file_kind: Literal["upload_file", "tool_file"],
+ file_id: str,
+ ) -> tuple[bytes, str | None, str | None]:
+ with session_factory.create_session() as session:
+ if file_kind == "tool_file":
+ tool_file = session.scalar(
+ select(ToolFile).where(ToolFile.id == file_id, ToolFile.tenant_id == tenant_id)
+ )
+ if tool_file is None:
+ raise AgentConfigServiceError(
+ "config_file_not_found", "config file payload is missing", status_code=404
+ )
+ return storage.load_once(tool_file.file_key), tool_file.name, tool_file.mimetype
+ upload_file = session.scalar(
+ select(UploadFile).where(UploadFile.id == file_id, UploadFile.tenant_id == tenant_id)
+ )
+ if upload_file is None:
+ raise AgentConfigServiceError("config_file_not_found", "config file payload is missing", status_code=404)
+ return storage.load_once(upload_file.key), upload_file.name, upload_file.mime_type
+
+ @staticmethod
+ def _resolve_download_url(
+ *, tenant_id: str, file_kind: Literal["upload_file", "tool_file"], file_id: str
+ ) -> str | None:
+ controller = DatabaseFileAccessController()
+ from core.app.workflow.file_runtime import DifyWorkflowFileRuntime
+
+ runtime = DifyWorkflowFileRuntime(file_access_controller=controller)
+ try:
+ if file_kind == "upload_file":
+ return runtime.resolve_upload_file_url(
+ upload_file_id=file_id,
+ for_external=True,
+ as_attachment=True,
+ )
+ file = file_factory.build_from_mapping(
+ mapping={"transfer_method": "tool_file", "tool_file_id": file_id},
+ tenant_id=tenant_id,
+ access_controller=controller,
+ )
+ url = runtime.resolve_file_url(file=file, for_external=True)
+ if not url:
+ return None
+ parsed = urllib.parse.urlsplit(url)
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
+ query.append(("as_attachment", "true"))
+ return urllib.parse.urlunsplit(parsed._replace(query=urllib.parse.urlencode(query)))
+ except ValueError:
+ return None
+
+
+__all__ = [
+ "AgentConfigMutationSurface",
+ "AgentConfigService",
+ "AgentConfigServiceError",
+ "AgentConfigTarget",
+ "AgentConfigVersionKind",
+ "ConfigDownload",
+ "ConfigPushFileItem",
+ "ConfigPushPayload",
+ "ConfigPushSkillItem",
+]
diff --git a/api/services/agent_tool_inner_service.py b/api/services/agent_tool_inner_service.py
new file mode 100644
index 00000000000..aa3fbe1c701
--- /dev/null
+++ b/api/services/agent_tool_inner_service.py
@@ -0,0 +1,150 @@
+"""Service layer for Agent-backend core tool invocations.
+
+The `dify.core.tools` layer executes inside the API service boundary so Dify
+Agent can expose API-owned tool providers (`plugin`, `builtin`, `api`,
+`workflow`, and `mcp`) without learning their storage, credential, or runtime
+internals. Production workflow and agent-app request builders still keep
+existing plugin tool configs on the direct `dify.plugin.tools` route by
+default; this service is the lower-level API execution path used when a caller
+explicitly submits a `dify.core.tools` declaration. The service validates
+tenant/app ownership, reuses `ToolManager.get_agent_tool_runtime(...)` to build
+the runtime with `ToolInvokeFrom.AGENT`, invokes through
+`ToolEngine.generic_invoke(...)`, and formats observations through the shared
+public `ToolEngine.tool_response_to_str` helper so Agent and workflow paths
+stay consistent.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.orm import Session
+
+from core.agent.entities import AgentToolEntity
+from core.app.entities.app_invoke_entities import InvokeFrom
+from core.callback_handler.workflow_tool_callback_handler import DifyWorkflowCallbackHandler
+from core.tools.entities.tool_entities import ToolProviderType
+from core.tools.errors import (
+ ToolInvokeError,
+ ToolNotFoundError,
+ ToolNotSupportedError,
+ ToolParameterValidationError,
+ ToolProviderCredentialValidationError,
+ ToolProviderNotFoundError,
+)
+from core.tools.tool_engine import ToolEngine
+from core.tools.tool_manager import ToolManager
+from core.tools.utils.message_transformer import ToolFileMessageTransformer
+from models.model import App
+from services.entities.agent_tool_inner import AgentToolInvokeRequest, AgentToolInvokeResponse
+from services.errors.agent_tool_inner import AgentToolInnerServiceError
+
+
+class AgentToolInnerService:
+ """Invoke one API-owned Agent tool declaration, including explicit plugin-via-core calls."""
+
+ def invoke(self, request: AgentToolInvokeRequest, *, session: Session) -> AgentToolInvokeResponse:
+ app = session.get(App, request.caller.app_id)
+ if app is None:
+ raise AgentToolInnerServiceError(
+ error_code="app_not_found",
+ description="App not found.",
+ status_code=404,
+ )
+ if app.tenant_id != request.caller.tenant_id:
+ raise AgentToolInnerServiceError(
+ error_code="app_tenant_mismatch",
+ description="App does not belong to the caller tenant.",
+ status_code=403,
+ )
+
+ agent_tool = AgentToolEntity(
+ provider_type=ToolProviderType.value_of(request.tool.provider_type),
+ provider_id=request.tool.provider_id,
+ tool_name=request.tool.tool_name,
+ tool_parameters=dict(request.tool.runtime_parameters),
+ credential_id=request.tool.credential_id,
+ )
+ try:
+ tool_runtime = ToolManager.get_agent_tool_runtime(
+ tenant_id=request.caller.tenant_id,
+ app_id=request.caller.app_id,
+ agent_tool=agent_tool,
+ user_id=request.caller.user_id,
+ invoke_from=InvokeFrom.value_of(request.caller.invoke_from),
+ variable_pool=None,
+ allow_file_parameters=True,
+ use_default_for_missing_form_parameters=True,
+ )
+ messages = ToolEngine.generic_invoke(
+ tool=tool_runtime,
+ tool_parameters=dict(request.tool.tool_parameters),
+ user_id=request.caller.user_id,
+ workflow_tool_callback=DifyWorkflowCallbackHandler(),
+ workflow_call_depth=0,
+ conversation_id=request.caller.conversation_id,
+ app_id=request.caller.app_id,
+ )
+ transformed_messages = list(
+ ToolFileMessageTransformer.transform_tool_invoke_messages(
+ messages=messages,
+ user_id=request.caller.user_id,
+ tenant_id=request.caller.tenant_id,
+ conversation_id=request.caller.conversation_id,
+ )
+ )
+ except ToolProviderNotFoundError as exc:
+ raise AgentToolInnerServiceError(
+ error_code="agent_tool_declaration_not_found",
+ description=str(exc),
+ status_code=404,
+ ) from exc
+ except ToolProviderCredentialValidationError as exc:
+ raise AgentToolInnerServiceError(
+ error_code="agent_tool_credential_invalid",
+ description=str(exc),
+ status_code=422,
+ ) from exc
+ except ToolParameterValidationError as exc:
+ raise AgentToolInnerServiceError(
+ error_code="tool_parameters_invalid",
+ description=str(exc),
+ status_code=422,
+ ) from exc
+ except (ToolInvokeError, ToolNotFoundError, ToolNotSupportedError) as exc:
+ raise AgentToolInnerServiceError(
+ error_code="agent_tool_invoke_failed",
+ description=str(exc),
+ status_code=422,
+ ) from exc
+ except ValueError as exc:
+ raise _map_value_error(exc) from exc
+ except Exception as exc:
+ raise AgentToolInnerServiceError(
+ error_code="agent_tool_invoke_unexpected_error",
+ description=str(exc),
+ status_code=500,
+ ) from exc
+
+ return AgentToolInvokeResponse(
+ messages=[message.model_dump(mode="json") for message in transformed_messages],
+ observation=ToolEngine.tool_response_to_str(transformed_messages),
+ metadata={
+ "provider_type": request.tool.provider_type,
+ "provider_id": request.tool.provider_id,
+ "tool_name": request.tool.tool_name,
+ },
+ )
+
+
+def _map_value_error(error: ValueError) -> AgentToolInnerServiceError:
+ description = str(error)
+ if description == "app not found":
+ return AgentToolInnerServiceError(
+ error_code="app_not_found",
+ description="App not found.",
+ status_code=404,
+ )
+ return AgentToolInnerServiceError(
+ error_code="agent_tool_invoke_failed",
+ description=description,
+ status_code=422,
+ )
diff --git a/api/services/app_generate_service.py b/api/services/app_generate_service.py
index 22fc2da322b..79a46ab52c9 100644
--- a/api/services/app_generate_service.py
+++ b/api/services/app_generate_service.py
@@ -38,6 +38,35 @@ if TYPE_CHECKING:
class AppGenerateService:
+ @classmethod
+ @trace_span(AppGenerateHandler)
+ def generate_stateless_agent_app(
+ cls,
+ *,
+ app_model: App,
+ user: Account | EndUser,
+ args: Mapping[str, Any],
+ invoke_from: InvokeFrom,
+ ):
+ """Run build-chat finalization as a blocking, non-SSE Agent App action.
+
+ This is the service entry point for the Agent build-chat finalize flow.
+ It applies the same tracing, quota, and rate-limit guardrails as normal
+ app generation, but invokes the Agent App generator in stateless mode:
+ the call waits synchronously for Agent backend completion, triggers only
+ the backend side effect, and does not create Dify chat/message records.
+ """
+ return cls._run_with_guardrails(
+ app_model=app_model,
+ streaming=False,
+ action=lambda _rate_limit, _request_id: AgentAppGenerator().generate_stateless(
+ app_model=app_model,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ ),
+ )
+
@staticmethod
def _build_streaming_task_on_subscribe(start_task: Callable[[], None]) -> Callable[[], None]:
"""
@@ -105,6 +134,29 @@ class AppGenerateService:
:param streaming: streaming
:return:
"""
+ return cls._run_with_guardrails(
+ app_model=app_model,
+ streaming=streaming,
+ action=lambda rate_limit, request_id: cls._dispatch_generate(
+ app_model=app_model,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ streaming=streaming,
+ root_node_id=root_node_id,
+ rate_limit=rate_limit,
+ request_id=request_id,
+ ),
+ )
+
+ @classmethod
+ def _run_with_guardrails(
+ cls,
+ *,
+ app_model: App,
+ streaming: bool,
+ action: Callable[[RateLimit, str], Any],
+ ):
quota_charge = unlimited()
if dify_config.BILLING_ENABLED:
try:
@@ -119,165 +171,181 @@ class AppGenerateService:
try:
request_id = rate_limit.enter(request_id)
quota_charge.commit()
- effective_mode = (
- AppMode.AGENT_CHAT if app_model.is_agent and app_model.mode != AppMode.AGENT_CHAT else app_model.mode
- )
- match effective_mode:
- case AppMode.COMPLETION:
- return rate_limit.generate(
- CompletionAppGenerator.convert_to_event_stream(
- CompletionAppGenerator().generate(
- app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
- ),
+ return action(rate_limit, request_id)
+ except Exception:
+ quota_charge.refund()
+ if streaming:
+ rate_limit.exit(request_id)
+ raise
+ finally:
+ if not streaming:
+ rate_limit.exit(request_id)
+
+ @classmethod
+ def _dispatch_generate(
+ cls,
+ *,
+ app_model: App,
+ user: Account | EndUser,
+ args: Mapping[str, Any],
+ invoke_from: InvokeFrom,
+ streaming: bool,
+ root_node_id: str | None,
+ rate_limit: RateLimit,
+ request_id: str,
+ ):
+ effective_mode = (
+ AppMode.AGENT_CHAT if app_model.is_agent and app_model.mode != AppMode.AGENT_CHAT else app_model.mode
+ )
+ match effective_mode:
+ case AppMode.COMPLETION:
+ return rate_limit.generate(
+ CompletionAppGenerator.convert_to_event_stream(
+ CompletionAppGenerator().generate(
+ app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
),
- request_id=request_id,
- )
- case AppMode.AGENT_CHAT:
- return rate_limit.generate(
- AgentChatAppGenerator.convert_to_event_stream(
- AgentChatAppGenerator().generate(
- app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
- ),
+ ),
+ request_id=request_id,
+ )
+ case AppMode.AGENT_CHAT:
+ return rate_limit.generate(
+ AgentChatAppGenerator.convert_to_event_stream(
+ AgentChatAppGenerator().generate(
+ app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
),
- request_id,
- )
- case AppMode.AGENT:
- return rate_limit.generate(
- AgentAppGenerator.convert_to_event_stream(
- AgentAppGenerator().generate(
- app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
- ),
+ ),
+ request_id,
+ )
+ case AppMode.AGENT:
+ return rate_limit.generate(
+ AgentAppGenerator.convert_to_event_stream(
+ AgentAppGenerator().generate(
+ app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
),
- request_id,
- )
- case AppMode.CHAT:
+ ),
+ request_id,
+ )
+ case AppMode.CHAT:
+ return rate_limit.generate(
+ ChatAppGenerator.convert_to_event_stream(
+ ChatAppGenerator().generate(
+ app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
+ ),
+ ),
+ request_id=request_id,
+ )
+ case AppMode.ADVANCED_CHAT:
+ workflow_id = args.get("workflow_id")
+ workflow = cls._get_workflow(app_model, invoke_from, workflow_id)
+
+ if streaming:
+ # Streaming mode: subscribe to SSE and enqueue the execution on first subscriber
+ with rate_limit_context(rate_limit, request_id):
+ payload = AppExecutionParams.new(
+ app_model=app_model,
+ workflow=workflow,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ streaming=True,
+ call_depth=0,
+ workflow_run_id=str(uuid.uuid4()),
+ )
+ payload_json = payload.model_dump_json()
+
+ def on_subscribe():
+ workflow_based_app_execution_task.delay(payload_json)
+
+ on_subscribe = cls._build_streaming_task_on_subscribe(on_subscribe)
+ generator = AdvancedChatAppGenerator()
return rate_limit.generate(
- ChatAppGenerator.convert_to_event_stream(
- ChatAppGenerator().generate(
- app_model=app_model, user=user, args=args, invoke_from=invoke_from, streaming=streaming
+ generator.convert_to_event_stream(
+ generator.retrieve_events(
+ AppMode.ADVANCED_CHAT,
+ payload.workflow_run_id,
+ on_subscribe=on_subscribe,
),
),
request_id=request_id,
)
- case AppMode.ADVANCED_CHAT:
- workflow_id = args.get("workflow_id")
- workflow = cls._get_workflow(app_model, invoke_from, workflow_id)
-
- if streaming:
- # Streaming mode: subscribe to SSE and enqueue the execution on first subscriber
- with rate_limit_context(rate_limit, request_id):
- payload = AppExecutionParams.new(
- app_model=app_model,
- workflow=workflow,
- user=user,
- args=args,
- invoke_from=invoke_from,
- streaming=True,
- call_depth=0,
- workflow_run_id=str(uuid.uuid4()),
- )
- payload_json = payload.model_dump_json()
-
- def on_subscribe():
- workflow_based_app_execution_task.delay(payload_json)
-
- on_subscribe = cls._build_streaming_task_on_subscribe(on_subscribe)
- generator = AdvancedChatAppGenerator()
- return rate_limit.generate(
- generator.convert_to_event_stream(
- generator.retrieve_events(
- AppMode.ADVANCED_CHAT,
- payload.workflow_run_id,
- on_subscribe=on_subscribe,
- ),
- ),
- request_id=request_id,
- )
- else:
- # Blocking mode: run synchronously and return JSON instead of SSE
- # Keep behaviour consistent with WORKFLOW blocking branch.
- pause_config = PauseStateLayerConfig(
- session_factory=session_factory.get_session_maker(),
- state_owner_user_id=workflow.created_by,
- )
- advanced_generator = AdvancedChatAppGenerator()
- return rate_limit.generate(
- advanced_generator.convert_to_event_stream(
- advanced_generator.generate(
- app_model=app_model,
- workflow=workflow,
- user=user,
- args=args,
- invoke_from=invoke_from,
- workflow_run_id=str(uuid.uuid4()),
- streaming=False,
- pause_state_config=pause_config,
- )
- ),
- request_id=request_id,
+
+ # Blocking mode: run synchronously and return JSON instead of SSE
+ # Keep behaviour consistent with WORKFLOW blocking branch.
+ pause_config = PauseStateLayerConfig(
+ session_factory=session_factory.get_session_maker(),
+ state_owner_user_id=workflow.created_by,
+ )
+ advanced_generator = AdvancedChatAppGenerator()
+ return rate_limit.generate(
+ advanced_generator.convert_to_event_stream(
+ advanced_generator.generate(
+ app_model=app_model,
+ workflow=workflow,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ workflow_run_id=str(uuid.uuid4()),
+ streaming=False,
+ pause_state_config=pause_config,
)
- case AppMode.WORKFLOW:
- workflow_id = args.get("workflow_id")
- workflow = cls._get_workflow(app_model, invoke_from, workflow_id)
- if streaming:
- with rate_limit_context(rate_limit, request_id):
- payload = AppExecutionParams.new(
- app_model=app_model,
- workflow=workflow,
- user=user,
- args=args,
- invoke_from=invoke_from,
- streaming=True,
- call_depth=0,
- root_node_id=root_node_id,
- workflow_run_id=str(uuid.uuid4()),
- )
- payload_json = payload.model_dump_json()
-
- def on_subscribe():
- workflow_based_app_execution_task.delay(payload_json)
-
- on_subscribe = cls._build_streaming_task_on_subscribe(on_subscribe)
- return rate_limit.generate(
- WorkflowAppGenerator.convert_to_event_stream(
- MessageBasedAppGenerator.retrieve_events(
- AppMode.WORKFLOW,
- payload.workflow_run_id,
- on_subscribe=on_subscribe,
- ),
- ),
- request_id,
+ ),
+ request_id=request_id,
+ )
+ case AppMode.WORKFLOW:
+ workflow_id = args.get("workflow_id")
+ workflow = cls._get_workflow(app_model, invoke_from, workflow_id)
+ if streaming:
+ with rate_limit_context(rate_limit, request_id):
+ payload = AppExecutionParams.new(
+ app_model=app_model,
+ workflow=workflow,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ streaming=True,
+ call_depth=0,
+ root_node_id=root_node_id,
+ workflow_run_id=str(uuid.uuid4()),
)
+ payload_json = payload.model_dump_json()
- pause_config = PauseStateLayerConfig(
- session_factory=session_factory.get_session_maker(),
- state_owner_user_id=workflow.created_by,
- )
+ def on_subscribe():
+ workflow_based_app_execution_task.delay(payload_json)
+
+ on_subscribe = cls._build_streaming_task_on_subscribe(on_subscribe)
return rate_limit.generate(
WorkflowAppGenerator.convert_to_event_stream(
- WorkflowAppGenerator().generate(
- app_model=app_model,
- workflow=workflow,
- user=user,
- args=args,
- invoke_from=invoke_from,
- streaming=False,
- root_node_id=root_node_id,
- call_depth=0,
- pause_state_config=pause_config,
+ MessageBasedAppGenerator.retrieve_events(
+ AppMode.WORKFLOW,
+ payload.workflow_run_id,
+ on_subscribe=on_subscribe,
),
),
request_id,
)
- case _:
- raise ValueError(f"Invalid app mode {app_model.mode}")
- except Exception:
- quota_charge.refund()
- rate_limit.exit(request_id)
- raise
- finally:
- if not streaming:
- rate_limit.exit(request_id)
+
+ pause_config = PauseStateLayerConfig(
+ session_factory=session_factory.get_session_maker(),
+ state_owner_user_id=workflow.created_by,
+ )
+ return rate_limit.generate(
+ WorkflowAppGenerator.convert_to_event_stream(
+ WorkflowAppGenerator().generate(
+ app_model=app_model,
+ workflow=workflow,
+ user=user,
+ args=args,
+ invoke_from=invoke_from,
+ streaming=False,
+ root_node_id=root_node_id,
+ call_depth=0,
+ pause_state_config=pause_config,
+ ),
+ ),
+ request_id,
+ )
+ case _:
+ raise ValueError(f"Invalid app mode {app_model.mode}")
@staticmethod
def _get_max_active_requests(app: App) -> int:
diff --git a/api/services/entities/agent_tool_inner.py b/api/services/entities/agent_tool_inner.py
new file mode 100644
index 00000000000..85c56d68555
--- /dev/null
+++ b/api/services/entities/agent_tool_inner.py
@@ -0,0 +1,59 @@
+"""Request/response DTOs for the Agent tool inner invoke API."""
+
+from __future__ import annotations
+
+from typing import ClassVar, Literal
+
+from pydantic import BaseModel, ConfigDict, Field, JsonValue
+
+type AgentToolProviderType = Literal["plugin", "builtin", "api", "workflow", "mcp"]
+
+
+class AgentToolInvokeCaller(BaseModel):
+ tenant_id: str
+ user_id: str
+ user_from: str
+ app_id: str
+ invoke_from: str
+ conversation_id: str | None = None
+ workflow_id: str | None = None
+ workflow_run_id: str | None = None
+ node_id: str | None = None
+ node_execution_id: str | None = None
+ agent_id: str | None = None
+ agent_config_version_id: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentToolInvokeTarget(BaseModel):
+ """One tool invocation payload.
+
+ `runtime_parameters` are API-prepared hidden/form/runtime values forwarded
+ into `ToolManager` runtime construction. `tool_parameters` are the live
+ LLM/user invocation arguments supplied at call time.
+ """
+
+ provider_type: AgentToolProviderType
+ provider_id: str
+ tool_name: str
+ credential_id: str | None = None
+ tool_parameters: dict[str, JsonValue] = Field(default_factory=dict)
+ runtime_parameters: dict[str, JsonValue] = Field(default_factory=dict)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentToolInvokeRequest(BaseModel):
+ caller: AgentToolInvokeCaller
+ tool: AgentToolInvokeTarget
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentToolInvokeResponse(BaseModel):
+ messages: list[dict[str, JsonValue]] = Field(default_factory=list)
+ observation: str
+ metadata: dict[str, JsonValue] = Field(default_factory=dict)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
diff --git a/api/services/errors/agent_tool_inner.py b/api/services/errors/agent_tool_inner.py
new file mode 100644
index 00000000000..c1c9d1fbef8
--- /dev/null
+++ b/api/services/errors/agent_tool_inner.py
@@ -0,0 +1,13 @@
+"""Domain errors for the Agent tool inner invoke boundary."""
+
+
+class AgentToolInnerServiceError(ValueError):
+ error_code: str
+ description: str
+ status_code: int
+
+ def __init__(self, *, error_code: str, description: str, status_code: int) -> None:
+ self.error_code = error_code
+ self.description = description
+ self.status_code = status_code
+ super().__init__(description)
diff --git a/api/tasks/app_generate/resume_agent_app_task.py b/api/tasks/app_generate/resume_agent_app_task.py
index 118a476bc8d..88dfbaa04b3 100644
--- a/api/tasks/app_generate/resume_agent_app_task.py
+++ b/api/tasks/app_generate/resume_agent_app_task.py
@@ -51,7 +51,7 @@ def resume_agent_app_execution(*, conversation_id: str, form_id: str) -> None:
app_model=app_model,
user=user,
conversation_id=conversation_id,
- invoke_from=InvokeFrom.WEB_APP,
+ invoke_from=_resolve_invoke_from(conversation),
)
except Exception:
logger.exception("Agent App resume failed for conversation %s form %s", conversation_id, form_id)
@@ -68,3 +68,9 @@ def _resolve_conversation_user(*, app_model: App, conversation: Conversation) ->
if conversation.from_end_user_id:
return db.session.get(EndUser, conversation.from_end_user_id)
return None
+
+
+def _resolve_invoke_from(conversation: Conversation) -> InvokeFrom:
+ if conversation.invoke_from is None:
+ return InvokeFrom.WEB_APP
+ return InvokeFrom.value_of(conversation.invoke_from.value)
diff --git a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py
index 274ab737328..f3aac73aac7 100644
--- a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py
+++ b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py
@@ -7,6 +7,11 @@ from agenton.layers import ExitIntent
from agenton.layers.base import LifecycleState
from agenton_collections.layers.plain import PLAIN_PROMPT_LAYER_TYPE_ID, PromptLayerConfig
from agenton_collections.layers.pydantic_ai import PYDANTIC_AI_HISTORY_LAYER_TYPE_ID
+from dify_agent.layers.dify_core_tools import (
+ DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ DifyCoreToolConfig,
+ DifyCoreToolsLayerConfig,
+)
from dify_agent.layers.dify_plugin import (
DIFY_PLUGIN_LLM_LAYER_TYPE_ID,
DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID,
@@ -29,6 +34,7 @@ from pydantic import ValidationError
from clients.agent_backend import (
AGENT_SOUL_PROMPT_LAYER_ID,
+ DIFY_CORE_TOOLS_LAYER_ID,
DIFY_EXECUTION_CONTEXT_LAYER_ID,
DIFY_KNOWLEDGE_BASE_LAYER_ID,
DIFY_PLUGIN_TOOLS_LAYER_ID,
@@ -160,6 +166,30 @@ def test_request_builder_adds_dify_plugin_tools_layer_when_configured():
assert tools_config.tools[0].tool_name == "current_time"
+def test_request_builder_adds_dify_core_tools_layer_when_configured():
+ run_input = _run_input()
+ run_input.core_tools = DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ runtime_parameters={"language": "en"},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ )
+
+ request = AgentBackendRunRequestBuilder().build_for_workflow_node(run_input)
+ layers = {layer.name: layer for layer in request.composition.layers}
+
+ assert layers[DIFY_CORE_TOOLS_LAYER_ID].type == DIFY_CORE_TOOLS_LAYER_TYPE_ID
+ assert layers[DIFY_CORE_TOOLS_LAYER_ID].deps == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
+
+
def test_request_builder_adds_knowledge_layer_when_configured():
run_input = _run_input()
run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index 847f60c2570..e4f347ca61e 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -44,7 +44,12 @@ from controllers.console.agent.roster import (
)
from controllers.console.app import completion as completion_controller
from controllers.console.app import message as message_controller
-from controllers.console.app.completion import AgentChatMessageApi, AgentChatMessageStopApi
+from controllers.console.app.completion import (
+ AgentBuildChatFinalizeApi,
+ AgentChatMessageApi,
+ AgentChatMessageStopApi,
+)
+from controllers.console.app.error import CompletionRequestError
from controllers.console.app.message import (
AgentChatMessageListApi,
AgentMessageApi,
@@ -296,6 +301,11 @@ def test_agent_app_list_and_create_use_agent_route(
"load_or_create_agent_app_debug_conversation_ids_by_agent_id",
lambda _self, **kwargs: {"agent-list": "debug-conversation-list"},
)
+ monkeypatch.setattr(
+ roster_controller.AgentRosterService,
+ "count_agent_app_debug_conversation_messages",
+ lambda _self, **kwargs: 0,
+ )
monkeypatch.setattr(
roster_controller.AgentRosterService,
"get_or_create_agent_app_debug_conversation_id",
@@ -407,6 +417,11 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
"get_or_create_agent_app_debug_conversation_id",
lambda _self, **kwargs: "debug-conversation-detail",
)
+ monkeypatch.setattr(
+ roster_controller.AgentRosterService,
+ "count_agent_app_debug_conversation_messages",
+ lambda _self, **kwargs: 2,
+ )
monkeypatch.setattr(
roster_controller.FeatureService,
"get_system_features",
@@ -431,6 +446,8 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
assert detail["id"] == agent_id
assert detail["app_id"] == "app-1"
assert detail["debug_conversation_id"] == "debug-conversation-detail"
+ assert detail["debug_conversation_has_messages"] is True
+ assert detail["debug_conversation_message_count"] == 2
assert detail["role"] == "Resolved role"
assert detail["active_config_is_published"] is False
assert "bound_agent_id" not in detail
@@ -445,6 +462,8 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
assert updated["id"] == agent_id
assert updated["app_id"] == "app-1"
assert updated["debug_conversation_id"] == "debug-conversation-detail"
+ assert updated["debug_conversation_has_messages"] is True
+ assert updated["debug_conversation_message_count"] == 2
assert updated["role"] == "Resolved role"
assert updated["active_config_is_published"] is False
assert "bound_agent_id" not in updated
@@ -529,7 +548,11 @@ def test_agent_debug_conversation_refresh_uses_current_user(
agent_id,
)
- assert response == {"debug_conversation_id": "new-debug-conversation-id"}
+ assert response == {
+ "debug_conversation_id": "new-debug-conversation-id",
+ "debug_conversation_has_messages": False,
+ "debug_conversation_message_count": 0,
+ }
assert captured == {
"tenant_id": "tenant-1",
"agent_id": agent_id,
@@ -1141,9 +1164,10 @@ def test_workflow_composer_get_put_validate_candidates_impact_and_save(
with app.test_request_context("?snapshot_id=preview-version"):
workflow_state = unwrap(WorkflowAgentComposerApi.get)(
- WorkflowAgentComposerApi(), "tenant-1", app_model, "node-1"
+ WorkflowAgentComposerApi(), "tenant-1", account_id, app_model, "node-1"
)
assert workflow_state["node_id"] == "node-1"
+ assert captured_load["account_id"] == account_id
assert captured_load["snapshot_id"] == "preview-version"
with app.test_request_context(json=payload):
saved_state = unwrap(WorkflowAgentComposerApi.put)(
@@ -1341,6 +1365,132 @@ def test_agent_chat_generate_and_stop_routes_resolve_app_from_agent_id(
assert stop_call == {"current_user_id": account_id, "app_model": app_model, "task_id": "task-1"}
+def test_agent_build_chat_finalize_route_resolves_app_from_agent_id(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, account_id: str
+) -> None:
+ agent_id = "00000000-0000-0000-0000-000000000001"
+ app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode="agent")
+ captured: dict[str, object] = {}
+
+ def resolve_agent_app_model(**kwargs: object) -> object:
+ captured["resolve"] = kwargs
+ return app_model
+
+ def create_finalization_message(**kwargs: object) -> dict[str, object]:
+ captured["finalize"] = kwargs
+ return {"result": "generated"}
+
+ monkeypatch.setattr(completion_controller, "resolve_agent_runtime_app_model", resolve_agent_app_model)
+ monkeypatch.setattr(completion_controller, "_create_build_chat_finalization_message", create_finalization_message)
+
+ with app.test_request_context():
+ assert unwrap(AgentBuildChatFinalizeApi.post)(
+ AgentBuildChatFinalizeApi(), "tenant-1", SimpleNamespace(id=account_id), agent_id
+ ) == {"result": "generated"}
+
+ assert cast(dict[str, object], captured["resolve"]) == {"tenant_id": "tenant-1", "agent_id": agent_id}
+ finalize_call = cast(dict[str, object], captured["finalize"])
+ assert finalize_call["app_model"] is app_model
+ assert finalize_call["current_tenant_id"] == "tenant-1"
+ assert finalize_call["agent_id"] == agent_id
+ assert cast(SimpleNamespace, finalize_call["current_user"]).id == account_id
+
+
+def test_build_chat_finalization_helper_forces_debug_build_and_push_prompt(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, account_id: str
+) -> None:
+ app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode="agent")
+ captured: dict[str, object] = {}
+
+ def resolve_debug_conversation(**kwargs: object) -> str:
+ captured["resolve_debug_conversation"] = kwargs
+ return "debug-conversation-1"
+
+ def generate(**kwargs: object) -> object:
+ captured["generate"] = kwargs
+ return iter(
+ [
+ "event: ping\n\n",
+ 'data: {"event":"message","answer":"working"}\n\n',
+ 'data: {"event":"message_end"}\n\n',
+ ]
+ )
+
+ monkeypatch.setattr(
+ completion_controller,
+ "_resolve_current_user_agent_debug_conversation_id",
+ resolve_debug_conversation,
+ )
+ monkeypatch.setattr(completion_controller.AppGenerateService, "generate", generate)
+
+ with app.test_request_context(headers={"X-Trace-Id": "trace-1"}):
+ result = completion_controller._create_build_chat_finalization_message(
+ current_tenant_id="tenant-1",
+ current_user=SimpleNamespace(id=account_id),
+ app_model=app_model,
+ agent_id="agent-1",
+ )
+
+ assert result == ({"result": "success"}, 200)
+ assert captured["resolve_debug_conversation"] == {
+ "current_tenant_id": "tenant-1",
+ "current_user": SimpleNamespace(id=account_id),
+ "app_model": app_model,
+ "agent_id": "agent-1",
+ }
+ generate_call = cast(dict[str, object], captured["generate"])
+ assert generate_call["app_model"] is app_model
+ assert generate_call["streaming"] is True
+ args = cast(dict[str, object], generate_call["args"])
+ assert args["draft_type"] == "debug_build"
+ assert args["response_mode"] == "streaming"
+ assert args["conversation_id"] == "debug-conversation-1"
+ assert args["inputs"] == {}
+ assert args["auto_generate_name"] is False
+ assert args["external_trace_id"] == "trace-1"
+
+
+def test_drain_streaming_generate_response_returns_on_message_end() -> None:
+ class ClosableResponse:
+ def __init__(self) -> None:
+ self._chunks = iter(
+ [
+ "event: ping\n\n",
+ 'data: {"event":"message","answer":"working"}\n\n',
+ 'data: {"event":"message_end","message_id":"msg-1"}\n\n',
+ ]
+ )
+ self.closed = False
+
+ def __iter__(self):
+ return self
+
+ def __next__(self) -> str:
+ return next(self._chunks)
+
+ def close(self) -> None:
+ self.closed = True
+
+ response = ClosableResponse()
+
+ assert completion_controller._drain_streaming_generate_response(response) is None
+ assert response.closed is True
+
+
+def test_drain_streaming_generate_response_maps_error_event() -> None:
+ response = iter(['data: {"event":"error","message":"backend failed"}\n\n'])
+
+ with pytest.raises(CompletionRequestError, match="backend failed"):
+ completion_controller._drain_streaming_generate_response(response)
+
+
+def test_drain_streaming_generate_response_raises_when_stream_ends_early() -> None:
+ response = iter(['data: {"event":"message","answer":"working"}\n\n'])
+
+ with pytest.raises(CompletionRequestError, match="did not complete"):
+ completion_controller._drain_streaming_generate_response(response)
+
+
def test_agent_chat_helper_forces_agent_streaming_and_external_trace(
app: Flask, monkeypatch: pytest.MonkeyPatch, account_id: str
) -> None:
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
new file mode 100644
index 00000000000..0b9ca517e13
--- /dev/null
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
@@ -0,0 +1,435 @@
+"""Unit tests for the console agent config inspector routes.
+
+These tests unwrap the Flask decorators and focus on version resolution,
+workflow-node agent binding, and service delegation for the new config surface.
+"""
+
+from __future__ import annotations
+
+import inspect
+from types import SimpleNamespace
+from unittest.mock import PropertyMock, patch
+
+from flask import Flask
+
+from controllers.console.app import agent_config_inspector as inspector
+from controllers.console.app.agent_config_inspector import (
+ AgentConfigFileDownloadApi,
+ AgentConfigFilePreviewApi,
+ AgentConfigFilesApi,
+ AgentConfigFilesByAgentApi,
+ AgentConfigManifestApi,
+ AgentConfigManifestByAgentApi,
+ AgentConfigSkillFileDownloadApi,
+ AgentConfigSkillFileDownloadByAgentApi,
+ AgentConfigSkillFilePreviewByAgentApi,
+ AgentConfigSkillInspectByAgentApi,
+ AgentConfigSkillsApi,
+ AgentConfigSkillUploadByAgentApi,
+ console_ns,
+)
+from services.agent_config_service import AgentConfigServiceError
+
+_MOD = "controllers.console.app.agent_config_inspector"
+app = Flask(__name__)
+
+
+def _raw(method):
+ return inspect.unwrap(method)
+
+
+_APP = SimpleNamespace(id="app-1", tenant_id="tenant-1", bound_agent_id="agent-1")
+_USER = SimpleNamespace(id="acct-1")
+
+
+def test_manifest_by_agent_resolves_build_draft_version():
+ raw = _raw(AgentConfigManifestByAgentApi.get)
+ with app.test_request_context("/?draft_type=debug_build"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.manifest.return_value = {
+ "agent_id": "agent-1",
+ "config_version": {"id": "build-draft-1", "kind": "build_draft", "writable": True},
+ "skills": {"items": []},
+ "files": {"items": []},
+ "env_keys": [],
+ "note": "",
+ }
+ body = raw(AgentConfigManifestByAgentApi(), "tenant-1", _USER, "agent-1")
+
+ assert body["config_version"]["kind"] == "build_draft"
+ assert config_service.return_value.manifest.call_args.kwargs["config_version_id"] == "build-draft-1"
+ assert config_service.return_value.manifest.call_args.kwargs["config_version_kind"].value == "build_draft"
+
+
+def test_manifest_resolves_workflow_node_agent_and_normal_draft():
+ raw = _raw(AgentConfigManifestApi.get)
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.manifest.return_value = {
+ "agent_id": "wf-agent-9",
+ "config_version": {"id": "draft-1", "kind": "draft", "writable": True},
+ "skills": {"items": []},
+ "files": {"items": []},
+ "env_keys": [],
+ "note": "",
+ }
+ body = raw(AgentConfigManifestApi(), _USER, _APP)
+
+ assert body["agent_id"] == "wf-agent-9"
+ assert composer.resolve_workflow_node_agent_id.call_args.kwargs["node_id"] == "node-1"
+ assert config_service.return_value.manifest.call_args.kwargs["config_version_kind"].value == "draft"
+
+
+def test_normal_draft_resolution_commits_created_draft_before_service_session() -> None:
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.db") as db,
+ ):
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+
+ version_id, version_kind = inspector._resolve_console_version(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ account_id="acct-1",
+ version_id=None,
+ draft_type="draft",
+ )
+
+ assert version_id == "draft-1"
+ assert version_kind.value == "draft"
+ db.session.commit.assert_called_once()
+
+
+def test_skill_inspect_by_agent_returns_strict_json_response():
+ raw = _raw(AgentConfigSkillInspectByAgentApi.get)
+ with app.test_request_context("/"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.inspect_skill.return_value = {
+ "id": "pdf-toolkit",
+ "name": "pdf-toolkit",
+ "description": "Work with PDFs.",
+ "size": 42,
+ "mime_type": "application/zip",
+ "hash": "sha256:abc",
+ "source": "config_skill_zip",
+ "files": [
+ {
+ "path": "SKILL.md",
+ "name": "SKILL.md",
+ "type": "file",
+ "previewable": True,
+ "downloadable": True,
+ }
+ ],
+ "skill_md": {
+ "path": "SKILL.md",
+ "size": 24,
+ "truncated": False,
+ "binary": False,
+ "text": "# PDF Toolkit\nUse it.\n",
+ },
+ "warnings": [],
+ }
+ response = raw(AgentConfigSkillInspectByAgentApi(), "tenant-1", _USER, "agent-1", "pdf-toolkit")
+
+ assert response.status_code == 200
+ assert response.get_json()["name"] == "pdf-toolkit"
+ assert b"PDF Toolkit" in response.get_data()
+
+
+def test_file_preview_api_passes_through_and_maps_errors():
+ raw = _raw(AgentConfigFilePreviewApi.get)
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.preview_file.return_value = {
+ "name": "sample.txt",
+ "size": 5,
+ "truncated": False,
+ "binary": False,
+ "text": "hello",
+ }
+ body = raw(AgentConfigFilePreviewApi(), _USER, _APP, "sample.txt")
+ assert body["text"] == "hello"
+
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.preview_file.side_effect = AgentConfigServiceError(
+ "config_file_not_found", "missing", status_code=404
+ )
+ body, status = raw(AgentConfigFilePreviewApi(), _USER, _APP, "missing.txt")
+ assert status == 404
+ assert body["code"] == "config_file_not_found"
+
+
+def test_skill_upload_by_agent_delegates_after_version_resolution():
+ raw = _raw(AgentConfigSkillUploadByAgentApi.post)
+ with app.test_request_context("/?draft_type=debug_build"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(
+ f"{_MOD}._upload_skill_for_target",
+ return_value=(
+ {
+ "skill": {"id": "alpha", "name": "alpha", "file_id": "tool-file-1", "description": "Alpha"},
+ "config_version": {"id": "build-draft-1", "kind": "build_draft", "writable": True},
+ },
+ 201,
+ ),
+ ) as upload_skill,
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ body, status = raw(AgentConfigSkillUploadByAgentApi(), "tenant-1", _USER, "agent-1")
+
+ assert status == 201
+ assert body["skill"]["name"] == "alpha"
+ assert upload_skill.call_args.kwargs["version_id"] == "build-draft-1"
+ assert upload_skill.call_args.kwargs["version_kind"].value == "build_draft"
+
+
+def test_file_upload_by_agent_delegates_to_service_owned_upload_lookup():
+ raw = _raw(AgentConfigFilesByAgentApi.post)
+ with app.test_request_context("/?draft_type=debug_build"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch.object(
+ type(console_ns),
+ "payload",
+ new_callable=PropertyMock,
+ return_value={"upload_file_id": "upload-1"},
+ ),
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.push_file_for_console.return_value = {
+ "file": {"id": "guide.txt", "name": "guide.txt", "file_id": "upload-1"},
+ "config_version": {"id": "build-draft-1", "kind": "build_draft", "writable": True},
+ }
+ body, status = raw(AgentConfigFilesByAgentApi(), "tenant-1", _USER, "agent-1")
+
+ assert status == 201
+ assert body["file"]["name"] == "guide.txt"
+ assert config_service.return_value.push_file_for_console.call_args.kwargs["upload_file_id"] == "upload-1"
+ assert config_service.return_value.push_file_for_console.call_args.kwargs["config_version_id"] == "build-draft-1"
+ assert (
+ config_service.return_value.push_file_for_console.call_args.kwargs["config_version_kind"].value == "build_draft"
+ )
+
+
+def test_skill_list_api_uses_config_list_shape() -> None:
+ raw = _raw(AgentConfigSkillsApi.get)
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.list_skills.return_value = {
+ "agent_id": "wf-agent-9",
+ "config_version": {"id": "draft-1", "kind": "draft", "writable": True},
+ "items": [{"id": "alpha", "name": "alpha", "file_id": "tool-file-1", "description": "Alpha"}],
+ }
+ body = raw(AgentConfigSkillsApi(), _USER, _APP)
+
+ assert body["items"][0]["name"] == "alpha"
+ assert body["items"][0]["file_id"] == "tool-file-1"
+ assert config_service.return_value.list_skills.call_args.kwargs["agent_id"] == "wf-agent-9"
+
+
+def test_file_list_api_uses_config_list_shape() -> None:
+ raw = _raw(AgentConfigFilesApi.get)
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.list_files.return_value = {
+ "agent_id": "wf-agent-9",
+ "config_version": {"id": "draft-1", "kind": "draft", "writable": True},
+ "items": [
+ {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-file-1",
+ "hash": "sha256:file-1",
+ "mime_type": "text/plain",
+ "size": 7,
+ }
+ ],
+ }
+ body = raw(AgentConfigFilesApi(), _USER, _APP)
+
+ assert body == {
+ "agent_id": "wf-agent-9",
+ "config_version": {"id": "draft-1", "kind": "draft", "writable": True},
+ "items": [
+ {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-file-1",
+ "hash": "sha256:file-1",
+ "mime_type": "text/plain",
+ "size": 7,
+ }
+ ],
+ }
+ assert config_service.return_value.list_files.call_args.kwargs["agent_id"] == "wf-agent-9"
+
+
+def test_skill_file_preview_by_agent_reads_path_query() -> None:
+ raw = _raw(AgentConfigSkillFilePreviewByAgentApi.get)
+ with app.test_request_context("/?draft_type=debug_build&path=references/guide.md"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.preview_skill_file.return_value = {
+ "path": "references/guide.md",
+ "size": 11,
+ "truncated": False,
+ "binary": False,
+ "text": "hello world",
+ }
+ body = raw(AgentConfigSkillFilePreviewByAgentApi(), "tenant-1", _USER, "agent-1", "alpha")
+
+ assert body["path"] == "references/guide.md"
+ assert config_service.return_value.preview_skill_file.call_args.kwargs["path"] == "references/guide.md"
+
+
+def test_skill_file_download_by_agent_returns_proxy_url() -> None:
+ raw = _raw(AgentConfigSkillFileDownloadByAgentApi.get)
+ with app.test_request_context("/?draft_type=debug_build&path=references/guide.md"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ patch(
+ f"{_MOD}.url_for",
+ return_value="/console/api/agent/agent-1/config/skills/alpha/files/content?path=references%2Fguide.md&draft_type=debug_build",
+ ),
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.resolve_skill_file_member_path.return_value = "references/guide.md"
+ response = raw(AgentConfigSkillFileDownloadByAgentApi(), "tenant-1", _USER, "agent-1", "alpha")
+
+ assert response.status_code == 200
+ assert response.get_json()["url"].endswith(
+ "/agent/agent-1/config/skills/alpha/files/content?path=references%2Fguide.md&draft_type=debug_build"
+ )
+
+
+def test_skill_file_download_by_agent_validates_member_path() -> None:
+ raw = _raw(AgentConfigSkillFileDownloadByAgentApi.get)
+ with app.test_request_context("/?draft_type=debug_build&path=references/missing.md"):
+ with (
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.resolve_skill_file_member_path.side_effect = AgentConfigServiceError(
+ "config_skill_file_not_found", "missing", status_code=404
+ )
+ body, status = raw(AgentConfigSkillFileDownloadByAgentApi(), "tenant-1", _USER, "agent-1", "alpha")
+
+ assert status == 404
+ assert body["code"] == "config_skill_file_not_found"
+
+
+def test_skill_file_download_api_forwards_workflow_node_and_draft_type() -> None:
+ raw = _raw(AgentConfigSkillFileDownloadApi.get)
+ with app.test_request_context("/?node_id=node-1&draft_type=debug_build&path=references/guide.md"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ patch(
+ f"{_MOD}.url_for",
+ return_value=(
+ "/console/api/apps/app-1/agent/config/skills/alpha/files/content"
+ "?node_id=node-1&draft_type=debug_build&path=references%2Fguide.md"
+ ),
+ ) as url_for_mock,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
+ config_service.return_value.resolve_skill_file_member_path.return_value = "references/guide.md"
+ response = raw(AgentConfigSkillFileDownloadApi(), _USER, _APP, "alpha")
+
+ assert response.status_code == 200
+ assert response.get_json()["url"].endswith(
+ "/apps/app-1/agent/config/skills/alpha/files/content"
+ "?node_id=node-1&draft_type=debug_build&path=references%2Fguide.md"
+ )
+ assert url_for_mock.call_args.kwargs == {
+ "_external": False,
+ "app_id": "app-1",
+ "draft_type": "debug_build",
+ "name": "alpha",
+ "node_id": "node-1",
+ "path": "references/guide.md",
+ }
+
+
+def test_skill_file_download_api_propagates_member_lookup_404s() -> None:
+ raw = _raw(AgentConfigSkillFileDownloadApi.get)
+ with app.test_request_context("/?node_id=node-1&path=references/missing.md"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.resolve_skill_file_member_path.side_effect = AgentConfigServiceError(
+ "config_skill_file_not_found", "missing", status_code=404
+ )
+ body, status = raw(AgentConfigSkillFileDownloadApi(), _USER, _APP, "alpha")
+
+ assert status == 404
+ assert body["code"] == "config_skill_file_not_found"
+
+
+def test_file_download_api_returns_signed_url_json() -> None:
+ raw = _raw(AgentConfigFileDownloadApi.get)
+ with app.test_request_context("/?node_id=node-1"):
+ with (
+ patch(f"{_MOD}.AgentComposerService") as composer,
+ patch(f"{_MOD}.AgentConfigService") as config_service,
+ ):
+ composer.resolve_workflow_node_agent_id.return_value = "wf-agent-9"
+ composer.load_agent_composer.return_value = {"draft": {"id": "draft-1"}}
+ config_service.return_value.download_file_url.return_value = "https://example.com/guide.txt"
+ response = raw(AgentConfigFileDownloadApi(), _USER, _APP, "guide.txt")
+
+ assert response.status_code == 200
+ assert response.get_json() == {"url": "https://example.com/guide.txt"}
diff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py
new file mode 100644
index 00000000000..eef6fdf31c0
--- /dev/null
+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py
@@ -0,0 +1,303 @@
+"""Unit tests for the Agent config inner-API controller."""
+
+from __future__ import annotations
+
+import inspect
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from flask import Flask
+
+from controllers.inner_api.plugin.agent_config import (
+ AgentConfigEnvApi,
+ AgentConfigFilePullApi,
+ AgentConfigManifestApi,
+ AgentConfigNoteApi,
+ AgentConfigPushApi,
+ AgentConfigSkillInspectApi,
+ AgentConfigSkillPullApi,
+)
+from services.agent_config_service import AgentConfigServiceError
+
+MODULE = "controllers.inner_api.plugin.agent_config"
+app = Flask(__name__)
+
+
+def _raw(method):
+ return inspect.unwrap(method)
+
+
+def test_manifest_happy_path_calls_service() -> None:
+ raw = _raw(AgentConfigManifestApi.get)
+
+ with app.test_request_context(
+ "/?tenant_id=tenant-1&user_id=user-1&config_version_id=cfg-1&config_version_kind=build_draft"
+ ):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.manifest.return_value = {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {
+ "items": [
+ {
+ "id": "alpha",
+ "name": "alpha",
+ "file_id": "tool-file-1",
+ "description": "Alpha skill",
+ "size": 123,
+ "hash": "sha256:abc",
+ "mime_type": "application/zip",
+ }
+ ]
+ },
+ "files": {
+ "items": [
+ {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-file-1",
+ "size": 7,
+ "hash": "sha256:def",
+ "mime_type": "text/plain",
+ }
+ ]
+ },
+ "env_keys": ["KEY"],
+ "note": "hello",
+ }
+ body = raw(AgentConfigManifestApi(), "agent-1")
+
+ assert body == {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {
+ "items": [
+ {
+ "id": "alpha",
+ "name": "alpha",
+ "file_id": "tool-file-1",
+ "description": "Alpha skill",
+ "size": 123,
+ "hash": "sha256:abc",
+ "mime_type": "application/zip",
+ }
+ ]
+ },
+ "files": {
+ "items": [
+ {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-file-1",
+ "size": 7,
+ "hash": "sha256:def",
+ "mime_type": "text/plain",
+ }
+ ]
+ },
+ "env_keys": ["KEY"],
+ "note": "hello",
+ }
+ assert service.return_value.manifest.call_args.kwargs == {
+ "tenant_id": "tenant-1",
+ "agent_id": "agent-1",
+ "user_id": "user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": service.return_value.manifest.call_args.kwargs["config_version_kind"],
+ }
+ assert service.return_value.manifest.call_args.kwargs["config_version_kind"].value == "build_draft"
+
+
+def test_skill_pull_returns_send_file_response() -> None:
+ raw = _raw(AgentConfigSkillPullApi.get)
+
+ with app.test_request_context(
+ "/?tenant_id=tenant-1&user_id=user-1&config_version_id=cfg-1&config_version_kind=build_draft"
+ ):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.pull_skill.return_value = SimpleNamespace(
+ payload=b"zip-bytes",
+ mime_type="application/zip",
+ filename="alpha.zip",
+ )
+ response = raw(AgentConfigSkillPullApi(), "agent-1", "alpha")
+
+ response.direct_passthrough = False
+ assert response.status_code == 200
+ assert response.mimetype == "application/zip"
+ assert response.get_data() == b"zip-bytes"
+ assert "filename=alpha.zip" in response.headers["Content-Disposition"]
+ assert service.return_value.pull_skill.call_args.kwargs["user_id"] == "user-1"
+
+
+def test_skill_inspect_happy_path_returns_service_payload() -> None:
+ raw = _raw(AgentConfigSkillInspectApi.get)
+
+ with app.test_request_context(
+ "/?tenant_id=tenant-1&user_id=user-1&config_version_id=cfg-1&config_version_kind=build_draft"
+ ):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.inspect_skill.return_value = {"name": "alpha", "files": ["SKILL.md"]}
+ body = raw(AgentConfigSkillInspectApi(), "agent-1", "alpha")
+
+ assert body == {"name": "alpha", "files": ["SKILL.md"]}
+ assert service.return_value.inspect_skill.call_args.kwargs["user_id"] == "user-1"
+
+
+def test_file_pull_returns_send_file_response() -> None:
+ raw = _raw(AgentConfigFilePullApi.get)
+
+ with app.test_request_context(
+ "/?tenant_id=tenant-1&user_id=user-1&config_version_id=cfg-1&config_version_kind=build_draft"
+ ):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.pull_file.return_value = SimpleNamespace(
+ payload=b"file-bytes",
+ mime_type="text/plain",
+ filename="guide.txt",
+ )
+ response = raw(AgentConfigFilePullApi(), "agent-1", "guide.txt")
+
+ response.direct_passthrough = False
+ assert response.status_code == 200
+ assert response.mimetype == "text/plain"
+ assert response.get_data() == b"file-bytes"
+ assert "filename=guide.txt" in response.headers["Content-Disposition"]
+ assert service.return_value.pull_file.call_args.kwargs["user_id"] == "user-1"
+
+
+def test_push_happy_path_validates_body_and_preserves_execution_user() -> None:
+ raw = _raw(AgentConfigPushApi.post)
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "account-user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "files": [{"name": "guide.txt", "file_ref": {"kind": "tool_file", "id": "tool-file-1"}}],
+ "skills": [],
+ "env_text": "KEY=value\n",
+ "note": "hello",
+ }
+
+ with app.test_request_context("/", method="POST", json=payload):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.push.return_value = {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {"items": []},
+ "files": {"items": []},
+ "env_keys": ["KEY"],
+ "note": "hello",
+ }
+ body = raw(AgentConfigPushApi(), "agent-1")
+
+ assert body == {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {"items": []},
+ "files": {"items": []},
+ "env_keys": ["KEY"],
+ "note": "hello",
+ }
+ assert service.return_value.push.call_args.kwargs["user_id"] == "account-user-1"
+ assert service.return_value.push.call_args.kwargs["config_version_kind"].value == "build_draft"
+
+
+def test_env_happy_path_calls_service() -> None:
+ raw = _raw(AgentConfigEnvApi.patch)
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "account-user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "env_text": "KEY=value\n",
+ }
+
+ with app.test_request_context("/", method="PATCH", json=payload):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.update_env.return_value = {"env_keys": ["KEY"]}
+ body = raw(AgentConfigEnvApi(), "agent-1")
+
+ assert body == {"env_keys": ["KEY"]}
+ assert service.return_value.update_env.call_args.kwargs["user_id"] == "account-user-1"
+ assert service.return_value.update_env.call_args.kwargs["env_text"] == "KEY=value\n"
+
+
+def test_note_happy_path_calls_service() -> None:
+ raw = _raw(AgentConfigNoteApi.put)
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "account-user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "note": "hello",
+ }
+
+ with app.test_request_context("/", method="PUT", json=payload):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.update_note.return_value = {"note": "hello"}
+ body = raw(AgentConfigNoteApi(), "agent-1")
+
+ assert body == {"note": "hello"}
+ assert service.return_value.update_note.call_args.kwargs["user_id"] == "account-user-1"
+ assert service.return_value.update_note.call_args.kwargs["note"] == "hello"
+
+
+def test_manifest_invalid_query_returns_400() -> None:
+ raw = _raw(AgentConfigManifestApi.get)
+
+ with app.test_request_context("/?tenant_id=tenant-1"):
+ body, status = raw(AgentConfigManifestApi(), "agent-1")
+
+ assert status == 400
+ assert body["code"] == "invalid_request"
+
+
+def test_push_invalid_body_returns_400() -> None:
+ raw = _raw(AgentConfigPushApi.post)
+
+ with app.test_request_context("/", method="POST", json={"tenant_id": "tenant-1"}):
+ body, status = raw(AgentConfigPushApi(), "agent-1")
+
+ assert status == 400
+ assert body["code"] == "invalid_request"
+
+
+def test_manifest_maps_service_errors() -> None:
+ raw = _raw(AgentConfigManifestApi.get)
+
+ with app.test_request_context("/?tenant_id=tenant-1&config_version_id=cfg-1&config_version_kind=build_draft"):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.manifest.side_effect = AgentConfigServiceError(
+ "config_version_not_found",
+ "missing",
+ status_code=404,
+ )
+ body, status = raw(AgentConfigManifestApi(), "agent-1")
+
+ assert status == 404
+ assert body == {"code": "config_version_not_found", "message": "missing"}
+
+
+def test_push_maps_service_errors() -> None:
+ raw = _raw(AgentConfigPushApi.post)
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "account-user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "files": [],
+ "skills": [],
+ }
+
+ with app.test_request_context("/", method="POST", json=payload):
+ with patch(f"{MODULE}.AgentConfigService") as service:
+ service.return_value.push.side_effect = AgentConfigServiceError(
+ "config_not_writable",
+ "denied",
+ status_code=403,
+ )
+ body, status = raw(AgentConfigPushApi(), "agent-1")
+
+ assert status == 403
+ assert body == {"code": "config_not_writable", "message": "denied"}
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py b/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py
new file mode 100644
index 00000000000..ea53555807e
--- /dev/null
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py
@@ -0,0 +1,124 @@
+"""Unit tests for the Agent tool inner API controller."""
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from unittest.mock import patch
+
+from flask import Flask
+
+from controllers.inner_api import bp as inner_api_bp
+from services.entities.agent_tool_inner import AgentToolInvokeResponse
+from services.errors.agent_tool_inner import AgentToolInnerServiceError
+
+
+def _headers(api_key: str | None = "inner-key") -> dict[str, str]:
+ headers = {"Content-Type": "application/json"}
+ if api_key is not None:
+ headers["X-Inner-Api-Key"] = api_key
+ return headers
+
+
+def _payload() -> dict[str, object]:
+ return {
+ "caller": {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "user_from": "account",
+ "app_id": "app-1",
+ "invoke_from": "service-api",
+ "conversation_id": "conversation-1",
+ "workflow_id": "workflow-1",
+ "workflow_run_id": "workflow-run-1",
+ "node_id": "node-1",
+ "node_execution_id": "node-exec-1",
+ "agent_id": "agent-1",
+ "agent_config_version_id": "snapshot-1",
+ },
+ "tool": {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/search/search",
+ "tool_name": "search",
+ "credential_id": "credential-1",
+ "tool_parameters": {"query": "dify"},
+ "runtime_parameters": {"region": "us"},
+ },
+ }
+
+
+@contextmanager
+def _agent_inner_auth() -> Iterator[None]:
+ with (
+ patch("configs.dify_config.PLUGIN_DAEMON_KEY", "plugin-daemon-key"),
+ patch("configs.dify_config.INNER_API_KEY_FOR_PLUGIN", "inner-key"),
+ ):
+ yield
+
+
+def test_post_returns_service_response() -> None:
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ app.register_blueprint(inner_api_bp)
+
+ with (
+ _agent_inner_auth(),
+ patch("controllers.inner_api.agent.tools.AgentToolInnerService.invoke") as mock_invoke,
+ ):
+ mock_invoke.return_value = AgentToolInvokeResponse(
+ messages=[{"type": "text", "message": {"text": "ok"}}],
+ observation="ok",
+ metadata={"provider_type": "plugin", "tool_name": "search"},
+ )
+
+ response = app.test_client().post(
+ "/inner/api/agent/tools/invoke",
+ json=_payload(),
+ headers=_headers(),
+ )
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["observation"] == "ok"
+ assert body["metadata"]["provider_type"] == "plugin"
+
+
+def test_post_returns_400_for_invalid_body() -> None:
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ app.register_blueprint(inner_api_bp)
+
+ with _agent_inner_auth():
+ response = app.test_client().post(
+ "/inner/api/agent/tools/invoke",
+ json={"caller": {}},
+ headers=_headers(),
+ )
+
+ assert response.status_code == 400
+ body = response.get_json()
+ assert body["code"] == "invalid_request"
+
+
+def test_post_preserves_service_error_status_code_and_description() -> None:
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ app.register_blueprint(inner_api_bp)
+
+ with (
+ _agent_inner_auth(),
+ patch("controllers.inner_api.agent.tools.AgentToolInnerService.invoke") as mock_invoke,
+ ):
+ mock_invoke.side_effect = AgentToolInnerServiceError(
+ error_code="app_tenant_mismatch",
+ description="App does not belong to the caller tenant.",
+ status_code=403,
+ )
+ response = app.test_client().post(
+ "/inner/api/agent/tools/invoke",
+ json=_payload(),
+ headers=_headers(),
+ )
+
+ assert response.status_code == 403
+ body = response.get_json()
+ assert body["code"] == "app_tenant_mismatch"
+ assert body["message"] == "App does not belong to the caller tenant."
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
index 7418ca2660a..6f8c6af2258 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
@@ -10,13 +10,20 @@ manager is replaced with a no-op so the thread body can run inline.
from __future__ import annotations
import contextlib
+import json
+from types import SimpleNamespace
import pytest
from pytest_mock import MockerFixture
-from core.app.apps.agent_app.app_generator import AgentAppGenerator, AgentAppGeneratorError
+from core.app.apps.agent_app.app_generator import (
+ AgentAppGenerator,
+ AgentAppGeneratorError,
+)
from core.app.apps.exc import GenerateTaskStoppedError
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
+from models import Account
+from models.agent import AgentConfigDraftType
MODULE = "core.app.apps.agent_app.app_generator"
@@ -66,7 +73,7 @@ class TestGenerateGuards:
class TestGenerateSuccess:
- def test_runtime_session_snapshot_id_is_stable_for_debugger_only(self):
+ def test_runtime_session_snapshot_id_preserves_snapshot_for_debugger_and_web_app(self):
assert (
AgentAppGenerator._runtime_session_snapshot_id(invoke_from=InvokeFrom.DEBUGGER, snapshot_id="snap-1")
== "snap-1"
@@ -81,7 +88,7 @@ class TestGenerateSuccess:
user = DummyAccount("user")
generator._resolve_agent = mocker.MagicMock(
- return_value=(mocker.MagicMock(id="agent1"), mocker.MagicMock(id="snap1"), mocker.MagicMock())
+ return_value=(mocker.MagicMock(id="agent1"), "snap1", "snapshot", mocker.MagicMock())
)
generator._prepare_user_inputs = mocker.MagicMock(return_value={"x": 1})
generator._init_generate_records = mocker.MagicMock(
@@ -95,16 +102,26 @@ class TestGenerateSuccess:
)
mocker.patch(f"{MODULE}.ModelConfigConverter.convert", return_value=mocker.MagicMock(model="gpt-4o-mini"))
mocker.patch(f"{MODULE}.TraceQueueManager", return_value=mocker.MagicMock())
- mocker.patch(f"{MODULE}.AgentAppGenerateEntity", return_value=mocker.MagicMock(task_id="t", user_id="user"))
+ generate_entity = mocker.patch(
+ f"{MODULE}.AgentAppGenerateEntity", return_value=mocker.MagicMock(task_id="t", user_id="user")
+ )
mocker.patch(f"{MODULE}.MessageBasedAppQueueManager", return_value=mocker.MagicMock())
thread_obj = mocker.MagicMock()
mocker.patch(f"{MODULE}.threading.Thread", return_value=thread_obj)
mocker.patch(f"{MODULE}.AgentAppGenerateResponseConverter.convert", return_value={"result": "ok"})
+ file_mappings = [
+ {
+ "type": "image",
+ "transfer_method": "local_file",
+ "url": "",
+ "upload_file_id": "upload-file-1",
+ }
+ ]
result = generator.generate(
app_model=app_model,
user=user,
- args={"query": "hello", "inputs": {"name": "world"}},
+ args={"query": "hello", "inputs": {"name": "world"}, "files": file_mappings},
invoke_from=InvokeFrom.WEB_APP,
streaming=True,
)
@@ -117,11 +134,12 @@ class TestGenerateSuccess:
draft_type=None,
user=user,
)
+ assert generate_entity.call_args.kwargs["prompt_file_mappings"] == file_mappings
def test_generate_loads_existing_conversation(self, generator: AgentAppGenerator, mocker: MockerFixture):
app_model = mocker.MagicMock(id="app1", tenant_id="tenant", mode="agent")
generator._resolve_agent = mocker.MagicMock(
- return_value=(mocker.MagicMock(id="a"), mocker.MagicMock(id="s"), mocker.MagicMock())
+ return_value=(mocker.MagicMock(id="a"), "snap1", "snapshot", mocker.MagicMock())
)
generator._prepare_user_inputs = mocker.MagicMock(return_value={})
generator._init_generate_records = mocker.MagicMock(
@@ -156,7 +174,7 @@ class TestGenerateSuccess:
user = DummyAccount("user")
generator._resolve_agent = mocker.MagicMock(
- return_value=(mocker.MagicMock(id="agent1"), mocker.MagicMock(id="snap1"), mocker.MagicMock())
+ return_value=(mocker.MagicMock(id="agent1"), "snap1", "snapshot", mocker.MagicMock())
)
generator._prepare_user_inputs = mocker.MagicMock(return_value={})
generator._init_generate_records = mocker.MagicMock(
@@ -187,6 +205,81 @@ class TestGenerateSuccess:
assert generate_entity.call_args.kwargs["extras"] == {"auto_generate_conversation_name": True}
+ def test_generate_stateless_skips_chat_records(self, generator: AgentAppGenerator, mocker: MockerFixture):
+ app_model = mocker.MagicMock(id="app1", tenant_id="tenant", mode="agent")
+ user = DummyAccount("user")
+
+ generator._resolve_agent = mocker.MagicMock(
+ return_value=(mocker.MagicMock(id="agent1"), "build-draft-1", "build_draft", mocker.MagicMock())
+ )
+ generator._init_generate_records = mocker.MagicMock()
+ run_stateless = mocker.patch.object(generator, "_run_stateless", return_value={"result": "success"})
+ converter = mocker.patch(f"{MODULE}.AgentAppGenerateResponseConverter.convert")
+
+ result = generator.generate_stateless(
+ app_model=app_model,
+ user=user,
+ args={
+ "query": "finalize",
+ "inputs": {},
+ "conversation_id": "debug-conversation-1",
+ "draft_type": "debug_build",
+ },
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert result == {"result": "success"}
+ generator._init_generate_records.assert_not_called()
+ converter.assert_not_called()
+ run_call = run_stateless.call_args.kwargs
+ assert run_call["conversation_id"] == "debug-conversation-1"
+ assert run_call["runtime_session_snapshot_id"] == "build-draft-1"
+
+ def test_generate_stateless_requires_conversation_id(self, generator: AgentAppGenerator, mocker: MockerFixture):
+ with pytest.raises(AgentAppGeneratorError, match="conversation_id is required"):
+ generator.generate_stateless(
+ app_model=mocker.MagicMock(),
+ user=DummyAccount("user"),
+ args={"query": "finalize", "inputs": {}, "draft_type": "debug_build"},
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ def test_stateless_run_uses_agent_app_runner(self, generator: AgentAppGenerator, mocker: MockerFixture):
+ app_model = mocker.MagicMock(id="app1", tenant_id="tenant", app_model_config=mocker.MagicMock())
+ user = DummyAccount("user")
+ agent = mocker.MagicMock(id="agent1")
+ dify_context = SimpleNamespace(tenant_id="tenant", app_id="app1")
+ mocker.patch(f"{MODULE}.DifyRunContext", return_value=dify_context)
+ runner = mocker.MagicMock()
+ build_runner = mocker.patch.object(generator, "_build_runner", return_value=runner)
+
+ result = generator._run_stateless(
+ app_model=app_model,
+ user=user,
+ invoke_from=InvokeFrom.DEBUGGER,
+ query="finalize",
+ conversation_id="debug-conversation-1",
+ agent=agent,
+ agent_config_id="build-draft-1",
+ agent_config_version_kind="build_draft",
+ agent_soul=mocker.MagicMock(),
+ runtime_session_snapshot_id="build-draft-1",
+ )
+
+ assert result == {"result": "success"}
+ build_runner.assert_called_once_with(dify_context)
+ runner.run_stateless.assert_called_once_with(
+ dify_context=dify_context,
+ agent_id="agent1",
+ agent_config_snapshot_id="build-draft-1",
+ agent_config_version_kind="build_draft",
+ agent_soul=mocker.ANY,
+ conversation_id="debug-conversation-1",
+ query="finalize",
+ idempotency_key=mocker.ANY,
+ session_scope_snapshot_id="build-draft-1",
+ )
+
class TestGenerateWorker:
@pytest.fixture(autouse=True)
@@ -197,10 +290,18 @@ class TestGenerateWorker:
mocker.patch("libs.flask_utils.preserve_flask_contexts", ctx_manager)
- def _wire(self, generator: AgentAppGenerator, mocker: MockerFixture, *, run_side_effect=None, handled=False):
+ def _wire(
+ self,
+ generator: AgentAppGenerator,
+ mocker: MockerFixture,
+ *,
+ run_side_effect=None,
+ handled=False,
+ guard_query="query",
+ ):
generator._get_conversation = mocker.MagicMock(return_value=mocker.MagicMock(id="conv"))
generator._get_message = mocker.MagicMock(return_value=mocker.MagicMock(id="msg"))
- generator._run_input_guards = mocker.MagicMock(return_value=(handled, "query"))
+ generator._run_input_guards = mocker.MagicMock(return_value=(handled, guard_query))
generator._resolve_agent_by_id = mocker.MagicMock(
return_value=(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock())
)
@@ -227,6 +328,7 @@ class TestGenerateWorker:
is_resume=False,
query="query",
runtime_session_snapshot_id="s",
+ prompt_file_mappings=(),
):
generator._generate_worker(
flask_app=mocker.MagicMock(),
@@ -237,6 +339,7 @@ class TestGenerateWorker:
agent_runtime_session_snapshot_id=runtime_session_snapshot_id,
model_conf=mocker.MagicMock(model="m"),
query=query,
+ prompt_file_mappings=prompt_file_mappings,
),
queue_manager=queue_manager,
conversation_id="conv",
@@ -261,6 +364,30 @@ class TestGenerateWorker:
assert runner.run.call_args.kwargs["agent_config_snapshot_id"] == "s"
assert runner.run.call_args.kwargs["session_scope_snapshot_id"] is None
+ def test_worker_appends_prompt_files_to_backend_query(self, generator, mocker: MockerFixture):
+ runner = self._wire(generator, mocker, guard_query="你看得见这张图片吗")
+ queue_manager = mocker.MagicMock()
+ file_mappings = [
+ {
+ "type": "image",
+ "transfer_method": "local_file",
+ "url": "",
+ "upload_file_id": "upload-file-1",
+ }
+ ]
+
+ self._call(
+ generator,
+ mocker,
+ queue_manager,
+ query="你看得见这张图片吗",
+ prompt_file_mappings=file_mappings,
+ )
+
+ assert runner.run.call_args.kwargs["query"] == (
+ f"你看得见这张图片吗\n{json.dumps(file_mappings, ensure_ascii=False)}"
+ )
+
def test_input_guard_short_circuit_skips_backend(self, generator, mocker: MockerFixture):
runner = self._wire(generator, mocker, handled=True)
queue_manager = mocker.MagicMock()
@@ -300,18 +427,22 @@ class TestResumeAfterFormSubmission:
def _wire(self, generator, mocker: MockerFixture):
generator._resolve_agent = mocker.MagicMock(
- return_value=(mocker.MagicMock(id="agent1"), mocker.MagicMock(id="snap1"), mocker.MagicMock())
+ return_value=(mocker.MagicMock(id="agent1"), "snap1", "draft", mocker.MagicMock())
)
generator._init_generate_records = mocker.MagicMock(
return_value=(mocker.MagicMock(id="conv", mode="agent"), mocker.MagicMock(id="msg"))
)
generator._handle_response = mocker.MagicMock(return_value=None)
- mocker.patch(f"{MODULE}.ConversationService.get_conversation", return_value=mocker.MagicMock(id="conv"))
+ mocker.patch(
+ f"{MODULE}.ConversationService.get_conversation",
+ return_value=mocker.MagicMock(id="conv", invoke_from=InvokeFrom.WEB_APP),
+ )
mocker.patch(f"{MODULE}.AgentAppConfigManager.get_app_config", return_value=mocker.MagicMock(variables=[]))
mocker.patch(f"{MODULE}.ModelConfigConverter.convert", return_value=mocker.MagicMock())
mocker.patch(f"{MODULE}.TraceQueueManager", return_value=mocker.MagicMock())
mocker.patch(f"{MODULE}.MessageBasedAppQueueManager", return_value=mocker.MagicMock())
mocker.patch(f"{MODULE}.threading.Thread", return_value=mocker.MagicMock())
+ mocker.patch(f"{MODULE}.AgentAppRuntimeSessionStore")
return mocker.patch(
f"{MODULE}.AgentAppGenerateEntity", return_value=mocker.MagicMock(task_id="t", user_id="user")
)
@@ -345,3 +476,26 @@ class TestResumeAfterFormSubmission:
# No prior user message -> a non-blank placeholder, still never blank.
assert entity.call_args.kwargs["query"] == "(resumed)"
+
+ def test_resume_uses_build_draft_for_debugger_conversation(self, generator, mocker: MockerFixture):
+ self._wire(generator, mocker)
+ conversation = mocker.MagicMock(id="conv", invoke_from=InvokeFrom.DEBUGGER)
+ mocker.patch(f"{MODULE}.ConversationService.get_conversation", return_value=conversation)
+ session_store = mocker.patch(f"{MODULE}.AgentAppRuntimeSessionStore")
+ session_store.return_value.load_active_session_for_conversation.return_value = mocker.MagicMock(
+ scope=mocker.MagicMock(agent_config_snapshot_id="draft-build-1")
+ )
+ draft_row = mocker.MagicMock(draft_type=AgentConfigDraftType.DEBUG_BUILD, account_id="user")
+ db_mock = mocker.patch(f"{MODULE}.db")
+ db_mock.session.scalar.side_effect = [draft_row, mocker.MagicMock(query="original question")]
+ account_user = mocker.MagicMock(spec=Account)
+ account_user.id = "user"
+
+ generator.resume_after_form_submission(
+ app_model=mocker.MagicMock(id="app1", tenant_id="tenant", mode="agent"),
+ user=account_user,
+ conversation_id="conv",
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert generator._resolve_agent.call_args.kwargs["draft_type"] == "debug_build"
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
index f5f6c12365f..a1f6512625b 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
@@ -23,22 +23,35 @@ from dify_agent.protocol import (
RunSucceededEventData,
RuntimeLayerSpec,
)
-from pydantic_ai.messages import PartDeltaEvent, PartStartEvent, TextPart, TextPartDelta
+from pydantic_ai.messages import (
+ FunctionToolCallEvent,
+ FunctionToolResultEvent,
+ PartDeltaEvent,
+ PartStartEvent,
+ TextPart,
+ TextPartDelta,
+ ThinkingPartDelta,
+ ToolCallPart,
+ ToolReturnPart,
+)
from clients.agent_backend import (
AgentBackendError,
AgentBackendRunEventAdapter,
+ AgentBackendStreamInternalEvent,
FakeAgentBackendRunClient,
FakeAgentBackendScenario,
)
+from core.app.apps.agent_app import app_runner as app_runner_module
from core.app.apps.agent_app.app_runner import AgentAppRunner
from core.app.apps.agent_app.runtime_request_builder import AgentAppRuntimeRequestBuilder
from core.app.apps.agent_app.session_store import AgentAppSessionScope, StoredAgentAppSession
from core.app.apps.exc import GenerateTaskStoppedError
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
-from core.app.entities.queue_entities import QueueLLMChunkEvent, QueueMessageEndEvent
+from core.app.entities.queue_entities import QueueAgentThoughtEvent, QueueLLMChunkEvent, QueueMessageEndEvent
from core.workflow.nodes.agent_v2.ask_human_resume import AskHumanResumeOutcome
from models.agent_config_entities import AgentSoulConfig
+from models.model import MessageAgentThought
class _FakeCredentialsProvider:
@@ -54,8 +67,9 @@ def _disable_drive_manifest_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
class _NoToolsBuilder:
- def build(self, **kwargs):
+ def build_layers(self, **kwargs):
del kwargs
+ return SimpleNamespace(plugin_tools=None, core_tools=None, exposed_tool_names=lambda: [])
class _FakeQueueManager:
@@ -86,6 +100,24 @@ class _RecordingFakeAgentBackendRunClient(FakeAgentBackendRunClient):
return super().cancel_run(run_id, request=request)
+class _BlockingRecordingFakeAgentBackendRunClient(FakeAgentBackendRunClient):
+ def __init__(self, **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self.wait_calls: list[tuple[str, float | None]] = []
+ self.stream_called = False
+
+ @override
+ def stream_events(self, run_id: str, *, after: str | None = None) -> Iterator[RunEvent]:
+ del run_id, after
+ self.stream_called = True
+ return iter(())
+
+ @override
+ def wait_run(self, run_id: str, *, timeout_seconds: float | None = None):
+ self.wait_calls.append((run_id, timeout_seconds))
+ return super().wait_run(run_id, timeout_seconds=timeout_seconds)
+
+
class _StreamingFakeAgentBackendRunClient(FakeAgentBackendRunClient):
@override
def stream_events(self, run_id: str, *, after: str | None = None) -> Iterator[RunEvent]:
@@ -138,6 +170,65 @@ class _StreamingPartStartFakeAgentBackendRunClient(FakeAgentBackendRunClient):
)
+class _ProcessStreamingFakeAgentBackendRunClient(FakeAgentBackendRunClient):
+ @override
+ def stream_events(self, run_id: str, *, after: str | None = None) -> Iterator[RunEvent]:
+ del after
+ created_at = datetime(2026, 1, 1, tzinfo=UTC)
+ yield RunStartedEvent(id="1-0", run_id=run_id, created_at=created_at)
+ yield PydanticAIStreamRunEvent(
+ id="2-0",
+ run_id=run_id,
+ created_at=created_at,
+ data=PartDeltaEvent(index=0, delta=ThinkingPartDelta(content_delta="I need to inspect the file.")),
+ )
+ yield PydanticAIStreamRunEvent(
+ id="3-0",
+ run_id=run_id,
+ created_at=created_at,
+ data=FunctionToolCallEvent(part=ToolCallPart(tool_name="bash", args={"cmd": "ls"}, tool_call_id="tool-1")),
+ )
+ yield PydanticAIStreamRunEvent(
+ id="4-0",
+ run_id=run_id,
+ created_at=created_at,
+ data=FunctionToolResultEvent(part=ToolReturnPart(tool_name="bash", content="ok", tool_call_id="tool-1")),
+ )
+ yield PydanticAIStreamRunEvent(
+ id="5-0",
+ run_id=run_id,
+ created_at=created_at,
+ data=PartDeltaEvent(index=1, delta=TextPartDelta(content_delta="final answer")),
+ )
+ yield RunSucceededEvent(
+ id="6-0",
+ run_id=run_id,
+ created_at=created_at,
+ data=RunSucceededEventData(
+ output={"text": "final answer"},
+ session_snapshot=CompositorSessionSnapshot(layers=[]),
+ ),
+ )
+
+
+class _FakeDbSession:
+ def __init__(self) -> None:
+ self.rows: dict[str, MessageAgentThought] = {}
+ self.rollback_count = 0
+
+ def add(self, row: MessageAgentThought) -> None:
+ self.rows[str(row.id)] = row
+
+ def commit(self) -> None:
+ pass
+
+ def get(self, _model: type[MessageAgentThought], row_id: str) -> MessageAgentThought | None:
+ return self.rows.get(row_id)
+
+ def rollback(self) -> None:
+ self.rollback_count += 1
+
+
class _FakeSessionStore:
def __init__(
self,
@@ -212,7 +303,7 @@ def _runner(client: FakeAgentBackendRunClient, store: _FakeSessionStore) -> Agen
return AgentAppRunner(
request_builder=AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
),
agent_backend_client=client,
event_adapter=AgentBackendRunEventAdapter(),
@@ -234,6 +325,18 @@ def _run(runner: AgentAppRunner, qm: _FakeQueueManager) -> None:
)
+def _run_stateless(runner: AgentAppRunner) -> None:
+ runner.run_stateless(
+ dify_context=_dify_ctx(),
+ agent_id="agent-1",
+ agent_config_snapshot_id="snap-1",
+ agent_soul=_soul(),
+ conversation_id="conv-1",
+ query="finalize",
+ idempotency_key="run-req-1",
+ )
+
+
def _message_end(qm: _FakeQueueManager) -> QueueMessageEndEvent:
return next(e for e in qm.events if isinstance(e, QueueMessageEndEvent))
@@ -311,6 +414,116 @@ def test_successful_turn_forwards_part_start_text_and_publishes_missing_terminal
assert end_events[0].llm_result.message.content == "hello agent"
+def test_successful_turn_persists_thinking_and_tool_process_events(monkeypatch):
+ fake_session = _FakeDbSession()
+ monkeypatch.setattr(app_runner_module.db, "session", fake_session)
+ client = _ProcessStreamingFakeAgentBackendRunClient()
+ store = _FakeSessionStore()
+ qm = _FakeQueueManager()
+
+ _run(_runner(client, store), qm)
+
+ chunk_events = [e for e in qm.events if isinstance(e, QueueLLMChunkEvent)]
+ assert [event.chunk.delta.message.content for event in chunk_events] == ["final answer"]
+ thought_events = [e for e in qm.events if isinstance(e, QueueAgentThoughtEvent)]
+ assert len(thought_events) >= 3
+
+ rows = sorted(fake_session.rows.values(), key=lambda row: row.position)
+ assert rows[0].thought == "I need to inspect the file."
+ assert rows[0].tool is None
+ assert rows[1].tool == "bash"
+ assert rows[1].tool_input == '{"cmd": "ls"}'
+ assert rows[1].observation == "ok"
+
+
+def test_tool_result_without_identity_does_not_attach_to_previous_tool(monkeypatch):
+ fake_session = _FakeDbSession()
+ monkeypatch.setattr(app_runner_module.db, "session", fake_session)
+ qm = _FakeQueueManager()
+ recorder = app_runner_module._AgentProcessRecorder(
+ dify_context=_dify_ctx(),
+ message_id="msg-1",
+ queue_manager=qm, # type: ignore[arg-type]
+ )
+
+ recorder.handle_stream_event(
+ AgentBackendStreamInternalEvent(
+ run_id="run-1",
+ data={
+ "event_kind": "function_tool_call",
+ "part": {
+ "part_kind": "tool-call",
+ "tool_name": "shell_run",
+ "args": {"script": "npx skills find browser"},
+ "tool_call_id": "shell-call-1",
+ },
+ },
+ )
+ )
+ recorder.handle_stream_event(
+ AgentBackendStreamInternalEvent(
+ run_id="run-1",
+ data={
+ "event_kind": "function_tool_result",
+ "content": "Knowledge base search results: browser skill",
+ },
+ )
+ )
+
+ rows = sorted(fake_session.rows.values(), key=lambda row: row.position)
+ assert len(rows) == 2
+ assert rows[0].tool == "shell_run"
+ assert rows[0].tool_input == '{"script": "npx skills find browser"}'
+ assert rows[0].observation is None
+ assert rows[1].tool is None
+ assert rows[1].tool_input is None
+ assert rows[1].observation == "Knowledge base search results: browser skill"
+
+
+def test_tool_result_without_call_id_matches_unique_open_tool_name(monkeypatch):
+ fake_session = _FakeDbSession()
+ monkeypatch.setattr(app_runner_module.db, "session", fake_session)
+ qm = _FakeQueueManager()
+ recorder = app_runner_module._AgentProcessRecorder(
+ dify_context=_dify_ctx(),
+ message_id="msg-1",
+ queue_manager=qm, # type: ignore[arg-type]
+ )
+
+ recorder.handle_stream_event(
+ AgentBackendStreamInternalEvent(
+ run_id="run-1",
+ data={
+ "event_kind": "function_tool_call",
+ "part": {
+ "part_kind": "tool-call",
+ "tool_name": "knowledge_base_search",
+ "args": {"query": "browser"},
+ },
+ },
+ )
+ )
+ recorder.handle_stream_event(
+ AgentBackendStreamInternalEvent(
+ run_id="run-1",
+ data={
+ "event_kind": "function_tool_result",
+ "part": {
+ "part_kind": "tool-return",
+ "tool_name": "knowledge_base_search",
+ "content": "Knowledge base search results: browser skill",
+ },
+ },
+ )
+ )
+
+ rows = sorted(fake_session.rows.values(), key=lambda row: row.position)
+ assert len(rows) == 1
+ assert rows[0].tool == "knowledge_base_search"
+ assert rows[0].tool_input == '{"query": "browser"}'
+ assert rows[0].observation == "Knowledge base search results: browser skill"
+
+
def test_prior_session_snapshot_is_threaded_into_request():
prior = CompositorSessionSnapshot(layers=[])
client = FakeAgentBackendRunClient()
@@ -348,6 +561,31 @@ def test_debug_session_scope_can_reuse_conversation_across_config_snapshots():
assert store.saved[0][0].agent_config_snapshot_id is None
+def test_stateless_run_uses_bounded_wait_and_does_not_save_session_state():
+ prior = CompositorSessionSnapshot(layers=[])
+ client = _BlockingRecordingFakeAgentBackendRunClient()
+ store = _FakeSessionStore(loaded=prior)
+
+ _run_stateless(_runner(client, store))
+
+ assert client.request is not None
+ assert client.request.session_snapshot is prior
+ assert client.wait_calls == [("fake-run-1", app_runner_module.dify_config.APP_MAX_EXECUTION_TIME)]
+ assert client.stream_called is False
+ assert store.saved == []
+
+
+def test_stateless_run_raises_backend_error_on_failed_bounded_wait():
+ client = _BlockingRecordingFakeAgentBackendRunClient(scenario=FakeAgentBackendScenario.FAILED)
+ store = _FakeSessionStore()
+
+ with pytest.raises(AgentBackendError):
+ _run_stateless(_runner(client, store))
+
+ assert client.wait_calls == [("fake-run-1", app_runner_module.dify_config.APP_MAX_EXECUTION_TIME)]
+ assert store.saved == []
+
+
def test_failed_run_raises_agent_backend_error():
client = FakeAgentBackendRunClient(scenario=FakeAgentBackendScenario.FAILED)
store = _FakeSessionStore()
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
index 15f1bacb8f6..806741bb8fe 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
@@ -85,7 +85,7 @@ class TestResolveAgent:
_patch_session(monkeypatch, [bound_agent, inner_agent, snapshot])
app_model = SimpleNamespace(id="app-1", tenant_id="t1")
- agent, snap, soul = AgentAppGenerator()._resolve_agent(
+ agent, config_id, config_version_kind, soul = AgentAppGenerator()._resolve_agent(
app_model,
invoke_from=InvokeFrom.WEB_APP,
draft_type=None,
@@ -93,7 +93,8 @@ class TestResolveAgent:
) # type: ignore[arg-type]
assert agent is bound_agent
- assert snap == snapshot.id
+ assert config_id == snapshot.id
+ assert config_version_kind == "snapshot"
assert soul.model is not None
def test_unbound_app_raises(self, monkeypatch: pytest.MonkeyPatch):
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
index 61bf3443cc8..5267d1833e3 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
@@ -7,9 +7,14 @@ from types import SimpleNamespace
from typing import Any
import pytest
+from dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolsLayerConfig
+from dify_agent.layers.dify_plugin import DifyPluginToolConfig, DifyPluginToolsLayerConfig
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from clients.agent_backend import (
+ DIFY_CONFIG_LAYER_ID,
+ DIFY_CORE_TOOLS_LAYER_ID,
+ DIFY_PLUGIN_TOOLS_LAYER_ID,
AgentBackendAgentAppRunInput,
AgentBackendModelConfig,
AgentBackendRunRequestBuilder,
@@ -81,54 +86,64 @@ class _FakeCredentialsProvider:
class _NoToolsBuilder:
- def build(self, **kwargs):
+ def build_layers(self, **kwargs):
del kwargs
+ return SimpleNamespace(plugin_tools=None, core_tools=None, exposed_tool_names=lambda: [])
+
+
+class _PluginLayerBuilder:
+ def build_layers(self, **kwargs):
+ return SimpleNamespace(
+ plugin_tools=DifyPluginToolsLayerConfig(
+ tools=[
+ DifyPluginToolConfig(
+ plugin_id="langgenius/time",
+ provider="time",
+ tool_name="current_time",
+ credential_type="unauthorized",
+ name="current_time",
+ description="Get current time.",
+ credentials={},
+ runtime_parameters={},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ core_tools=None,
+ exposed_tool_names=lambda: ["current_time"],
+ )
-def _mock_empty_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",
- lambda self, *, tenant_id, agent_id: [],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],
- )
-
-
-def _mock_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",
- lambda self, *, tenant_id, agent_id: [
- {
- "path": "tender-analyzer",
- "skill_md_key": "tender-analyzer/SKILL.md",
- "archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",
- "name": "Tender Analyzer",
- "description": "Parses RFPs.",
- "size": 123,
- "mime_type": "text/markdown",
- "hash": "hash-1",
- "created_at": 1,
- }
- ],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [
- {"key": "tender-analyzer/SKILL.md", "is_skill": True},
- {"key": "tender-analyzer/.DIFY-SKILL-FULL.zip", "is_skill": False},
- {"key": "files/sample.pdf", "is_skill": False},
- ],
- )
-
-
[email protected](autouse=True)
-def _mock_default_agent_app_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
- _mock_empty_drive_catalog(monkeypatch)
+class _CoreLayerBuilder:
+ def build_layers(self, **kwargs):
+ del kwargs
+ return SimpleNamespace(
+ plugin_tools=None,
+ core_tools=DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ runtime_parameters={},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ exposed_tool_names=lambda: ["transcribe"],
+ )
-def _ctx(soul: AgentSoulConfig, *, query: str = "hello") -> AgentAppRuntimeBuildContext:
+def _ctx(
+ soul: AgentSoulConfig,
+ *,
+ query: str = "hello",
+ agent_config_version_kind: str = "snapshot",
+) -> AgentAppRuntimeBuildContext:
dify_context = SimpleNamespace(
tenant_id="tenant-1",
app_id="app-1",
@@ -144,6 +159,7 @@ def _ctx(soul: AgentSoulConfig, *, query: str = "hello") -> AgentAppRuntimeBuild
conversation_id="conv-1",
user_query=query,
idempotency_key="msg-1",
+ agent_config_version_kind=agent_config_version_kind, # type: ignore[arg-type]
)
@@ -164,7 +180,7 @@ class TestAgentAppRuntimeRequestBuilder:
def test_build_maps_soul_to_run_request(self):
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(_soul_with_model()))
@@ -175,8 +191,6 @@ class TestAgentAppRuntimeRequestBuilder:
"agent_soul_prompt",
"agent_app_user_prompt",
"execution_context",
- "shell",
- "drive",
"history",
"llm",
]
@@ -195,6 +209,68 @@ class TestAgentAppRuntimeRequestBuilder:
assert result.redacted_request["composition"]["layers"][-1]["config"]["credentials"] == "[REDACTED]"
assert result.metadata["conversation_id"] == "conv-1"
+ def test_build_includes_plugin_tools_layer_returned_by_injected_builder_for_draft(self):
+ soul = _soul_with_model()
+ soul.tools.dify_tools = [
+ {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/time/time",
+ "tool_name": "current_time",
+ }
+ ]
+ tools_builder = _PluginLayerBuilder()
+ builder = AgentAppRuntimeRequestBuilder(
+ credentials_provider=_FakeCredentialsProvider(),
+ dify_tools_builder=tools_builder, # type: ignore[arg-type]
+ )
+
+ result = builder.build(_ctx(soul, agent_config_version_kind="draft"))
+
+ names = [layer.name for layer in result.request.composition.layers]
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID in names
+ assert DIFY_CORE_TOOLS_LAYER_ID not in names
+
+ def test_build_includes_plugin_tools_layer_returned_by_injected_builder_for_snapshot(self):
+ soul = _soul_with_model()
+ soul.tools.dify_tools = [
+ {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/time/time",
+ "tool_name": "current_time",
+ }
+ ]
+ tools_builder = _PluginLayerBuilder()
+ builder = AgentAppRuntimeRequestBuilder(
+ credentials_provider=_FakeCredentialsProvider(),
+ dify_tools_builder=tools_builder, # type: ignore[arg-type]
+ )
+
+ result = builder.build(_ctx(soul, agent_config_version_kind="snapshot"))
+
+ names = [layer.name for layer in result.request.composition.layers]
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID in names
+ assert DIFY_CORE_TOOLS_LAYER_ID not in names
+
+ def test_build_includes_core_tools_layer_returned_by_injected_builder(self):
+ soul = _soul_with_model()
+ soul.tools.dify_tools = [
+ {
+ "provider_type": "builtin",
+ "provider_id": "audio",
+ "tool_name": "transcribe",
+ }
+ ]
+ builder = AgentAppRuntimeRequestBuilder(
+ credentials_provider=_FakeCredentialsProvider(),
+ dify_tools_builder=_CoreLayerBuilder(), # type: ignore[arg-type]
+ )
+
+ result = builder.build(_ctx(soul))
+
+ names = [layer.name for layer in result.request.composition.layers]
+ assert DIFY_CORE_TOOLS_LAYER_ID in names
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID not in names
+
def test_build_normalizes_marketplace_model_plugin_id(self):
soul = _soul_with_model()
soul.model.plugin_id = (
@@ -202,7 +278,7 @@ class TestAgentAppRuntimeRequestBuilder:
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(soul))
@@ -238,7 +314,7 @@ class TestAgentAppRuntimeRequestBuilder:
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(soul))
@@ -257,7 +333,7 @@ class TestAgentAppRuntimeRequestBuilder:
def test_build_raises_when_model_missing(self):
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
with pytest.raises(AgentAppRuntimeRequestBuildError) as exc:
builder.build(_ctx(AgentSoulConfig()))
@@ -279,7 +355,7 @@ class TestAgentAppRuntimeRequestBuilder:
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(soul))
@@ -298,7 +374,7 @@ class TestAgentAppRuntimeRequestBuilder:
}
-# ── ENG-623: drive declaration on the Agent App surface ──────────────────────
+# ── Agent config layer declaration on the Agent App surface ──────────────────
def _soul_with_model_and_skill() -> AgentSoulConfig:
@@ -309,143 +385,138 @@ def _soul_with_model_and_skill() -> AgentSoulConfig:
"model_provider": "langgenius/openai/openai",
"model": "gpt-4o-mini",
},
- "prompt": {"system_prompt": "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§]"},
- "files": {
- "skills": [
- {
- "path": "tender-analyzer",
- "skill_md_key": "tender-analyzer/SKILL.md",
- "name": "Tender Analyzer",
- "description": "Parses RFPs.",
- }
- ]
- },
+ "prompt": {"system_prompt": "Use [§skill:tender-analyzer:Tender Analyzer§]"},
+ "config_skills": [{"name": "tender-analyzer", "description": "Parses RFPs.", "file_id": "tool-file-1"}],
+ "config_files": [{"name": "sample.pdf", "file_kind": "upload_file", "file_id": "upload-file-1"}],
+ "config_note": "Read the proposal first.",
}
)
-class TestAgentAppDriveLayer:
- def test_drive_layer_injected_when_flag_enabled(self, monkeypatch: pytest.MonkeyPatch):
+class TestAgentAppConfigLayer:
+ def test_config_layer_injected_when_flag_enabled(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
- _mock_drive_catalog(monkeypatch)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(_soul_with_model_and_skill()))
- drive = next(layer for layer in result.request.composition.layers if layer.name == "drive")
- assert drive.type == "dify.drive"
- assert drive.deps == {"shell": DIFY_SHELL_LAYER_ID}
- assert drive.config.drive_ref == "agent-agent-1"
- assert [skill.skill_md_key for skill in drive.config.skills] == ["tender-analyzer/SKILL.md"]
- assert drive.config.mentioned_skill_keys == ["tender-analyzer/SKILL.md"]
- # shell enters first; drive uses that shell to materialize mentioned targets.
+ config = next(layer for layer in result.request.composition.layers if layer.name == DIFY_CONFIG_LAYER_ID)
+ assert config.type == "dify.config"
+ assert config.deps == {"shell": DIFY_SHELL_LAYER_ID}
+ assert config.config.agent_id == "agent-1"
+ assert config.config.config_version is not None
+ assert config.config.config_version.id == "snap-1"
+ assert config.config.config_version.kind == "snapshot"
+ assert config.config.config_version.writable is False
+ assert [skill.name for skill in config.config.skills] == ["tender-analyzer"]
+ assert [file_ref.name for file_ref in config.config.files] == ["sample.pdf"]
+ assert config.config.note == "Read the proposal first."
+ assert config.config.mentioned_skill_names == ["tender-analyzer"]
+ assert config.config.mentioned_file_names == []
+ # shell enters first; config uses that shell to materialize mentioned targets.
names = [layer.name for layer in result.request.composition.layers]
assert names.index(DIFY_SHELL_LAYER_ID) == names.index("execution_context") + 1
- assert names.index("drive") == names.index(DIFY_SHELL_LAYER_ID) + 1
+ assert names.index(DIFY_CONFIG_LAYER_ID) == names.index(DIFY_SHELL_LAYER_ID) + 1
- def test_drive_layer_injected_with_empty_catalog_and_drive_depends_on_shell(self, monkeypatch: pytest.MonkeyPatch):
+ def test_no_config_layer_when_agent_soul_has_no_config_assets(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
monkeypatch.setattr("core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(_soul_with_model()))
layers = {layer.name: layer for layer in result.request.composition.layers}
- assert layers["drive"].config.drive_ref == "agent-agent-1"
- assert layers["drive"].config.skills == []
+ assert DIFY_CONFIG_LAYER_ID not in layers
assert layers[DIFY_SHELL_LAYER_ID].deps == {"execution_context": "execution_context"}
- assert layers[DIFY_SHELL_LAYER_ID].config.agent_stub_drive_ref == "agent-agent-1"
- assert layers["drive"].deps == {"shell": DIFY_SHELL_LAYER_ID}
+ assert layers[DIFY_SHELL_LAYER_ID].config.agent_stub_drive_ref is None
- def test_no_drive_layer_when_flag_disabled(self, monkeypatch: pytest.MonkeyPatch):
+ def test_config_layer_for_build_draft_marks_config_writable(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
- "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
- result = builder.build(_ctx(_soul_with_model_and_skill()))
- assert all(layer.name != "drive" for layer in result.request.composition.layers)
- def test_agent_app_runtime_expands_skill_and_file_mentions_in_agent_soul_prompt(
- self,
- monkeypatch: pytest.MonkeyPatch,
- ):
+ result = builder.build(_ctx(_soul_with_model_and_skill(), agent_config_version_kind="build_draft"))
+
+ config = next(layer for layer in result.request.composition.layers if layer.name == DIFY_CONFIG_LAYER_ID)
+ assert config.config.model_dump(mode="json") == {
+ "agent_id": "agent-1",
+ "config_version": {"id": "snap-1", "kind": "build_draft", "writable": True},
+ "skills": [
+ {
+ "name": "tender-analyzer",
+ "description": "Parses RFPs.",
+ "size": None,
+ "mime_type": "application/zip",
+ }
+ ],
+ "files": [{"name": "sample.pdf", "size": None, "mime_type": None}],
+ "env_keys": [],
+ "note": "Read the proposal first.",
+ "mentioned_skill_names": ["tender-analyzer"],
+ "mentioned_file_names": [],
+ }
+
+ def test_no_config_layer_when_flag_disabled(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
- "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
- )
- _mock_drive_catalog(monkeypatch)
- soul = _soul_with_model()
- soul.prompt.system_prompt = (
- "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]."
+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
-
- result = builder.build(_ctx(soul))
-
- prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert prompt_layer.config.prefix == "Use Tender Analyzer and sample.pdf."
- assert "[§" not in prompt_layer.config.prefix
-
- def test_agent_app_runtime_missing_drive_mentions_fall_back_to_label_then_decoded_key(
+ result = builder.build(_ctx(_soul_with_model_and_skill()))
+ assert all(layer.name != DIFY_CONFIG_LAYER_ID for layer in result.request.composition.layers)
+
+ @pytest.mark.parametrize(
+ ("system_prompt", "expected_prefix"),
+ [
+ (
+ "Use [§skill:tender-analyzer:Tender Analyzer§] and [§file:sample.pdf:sample.pdf§].",
+ "Use tender-analyzer and sample.pdf.",
+ ),
+ (
+ "Use [§skill:tender-analyzer:Tender Analyzer§] and [§file:sample.pdf:sample.pdf§]",
+ "Use tender-analyzer and sample.pdf",
+ ),
+ ],
+ )
+ def test_agent_app_runtime_expands_config_mentions_in_agent_soul_prompt(
self,
monkeypatch: pytest.MonkeyPatch,
+ system_prompt: str,
+ expected_prefix: str,
):
monkeypatch.setattr(
"core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
- _mock_drive_catalog(monkeypatch)
- soul = _soul_with_model()
- soul.prompt.system_prompt = (
- "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "
- "and [§file:files%2Fmissing.txt§]."
- )
- builder = AgentAppRuntimeRequestBuilder(
- credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
- )
-
- result = builder.build(_ctx(soul))
-
- prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert prompt_layer.config.prefix == "Use Ghost Skill, Ghost File, and files/missing.txt."
- assert "[§" not in prompt_layer.config.prefix
-
- def test_agent_app_runtime_expands_drive_mentions_in_agent_soul_prompt(self, monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(
- "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
- )
- _mock_drive_catalog(monkeypatch)
- soul = _soul_with_model()
- soul.prompt.system_prompt = (
- "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]"
- )
+ soul = _soul_with_model_and_skill()
+ soul.prompt.system_prompt = system_prompt
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(soul))
prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert prompt_layer.config.prefix == "Use Tender Analyzer and sample.pdf"
+ assert prompt_layer.config.prefix == expected_prefix
assert "[§" not in prompt_layer.config.prefix
- def test_agent_app_runtime_missing_drive_mentions_fall_back_without_marker_leak(
+ def test_agent_app_runtime_missing_config_mentions_fall_back_without_marker_leak(
self,
monkeypatch: pytest.MonkeyPatch,
):
@@ -454,16 +525,15 @@ class TestAgentAppDriveLayer:
)
soul = _soul_with_model()
soul.prompt.system_prompt = (
- "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "
- "and [§file:files%2Fno-label.txt§]."
+ "Use [§skill:ghost-skill:Ghost Skill§], [§file:ghost.txt:Ghost File§], and [§file:no-label.txt§]."
)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
- plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
+ dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
result = builder.build(_ctx(soul))
prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert prompt_layer.config.prefix == "Use Ghost Skill, Ghost File, and files/no-label.txt."
+ assert prompt_layer.config.prefix == "Use Ghost Skill, Ghost File, and no-label.txt."
assert "[§" not in prompt_layer.config.prefix
diff --git a/api/tests/unit_tests/core/tools/test_tool_engine.py b/api/tests/unit_tests/core/tools/test_tool_engine.py
index 8118f40e8f7..ec1da418228 100644
--- a/api/tests/unit_tests/core/tools/test_tool_engine.py
+++ b/api/tests/unit_tests/core/tools/test_tool_engine.py
@@ -88,7 +88,7 @@ def test_convert_tool_response_to_str_and_extract_binary_messages():
tool.create_json_message({"a": 1}),
tool.create_json_message({"a": 1}, suppress_output=True),
]
- text = ToolEngine._convert_tool_response_to_str(messages)
+ text = ToolEngine.tool_response_to_str(messages)
assert "hello" in text
assert "result link: https://example.com." in text
assert '"a": 1' in text
@@ -271,7 +271,7 @@ def test_convert_tool_response_excludes_variable_messages():
"""Regression test for issue #34723.
WorkflowTool._invoke yields VARIABLE, TEXT, and suppressed-JSON messages.
- _convert_tool_response_to_str must skip VARIABLE messages so that the
+ tool_response_to_str must skip VARIABLE messages so that the
returned string contains only the TEXT representation and not a
duplicated, garbled Pydantic repr of the same data.
"""
@@ -283,7 +283,7 @@ def test_convert_tool_response_excludes_variable_messages():
tool.create_json_message(outputs, suppress_output=True),
]
- result = ToolEngine._convert_tool_response_to_str(messages)
+ result = ToolEngine.tool_response_to_str(messages)
assert result == '{"reports": "hello"}'
assert "variable_name" not in result
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_plugin_tools_builder.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_dify_tools_builder.py
similarity index 71%
rename from api/tests/unit_tests/core/workflow/nodes/agent_v2/test_plugin_tools_builder.py
rename to api/tests/unit_tests/core/workflow/nodes/agent_v2/test_dify_tools_builder.py
index 1ff87614b08..e9af5e7707a 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_plugin_tools_builder.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_dify_tools_builder.py
@@ -16,11 +16,12 @@ from core.tools.entities.tool_entities import (
ToolIdentity,
ToolInvokeMessage,
ToolParameter,
+ ToolProviderType,
)
from core.tools.tool_manager import ToolManager
-from core.workflow.nodes.agent_v2.plugin_tools_builder import (
- WorkflowAgentPluginToolsBuilder,
- WorkflowAgentPluginToolsBuildError,
+from core.workflow.nodes.agent_v2.dify_tools_builder import (
+ WorkflowAgentDifyToolsBuilder,
+ WorkflowAgentDifyToolsBuildError,
)
from models.agent_config_entities import AgentSoulToolsConfig
@@ -29,8 +30,9 @@ class FakeRuntimeProvider:
def __init__(self, tool: Tool | Exception) -> None:
# Either a Tool to hand back, or an exception to raise on lookup. The
# latter lets tests exercise the error-mapping branches in
- # ``WorkflowAgentPluginToolsBuilder._fetch_tool_runtime``.
+ # ``WorkflowAgentDifyToolsBuilder._fetch_tool_runtime``.
self.tool = tool
+ self.call_count = 0
self.last_agent_tool: AgentToolEntity | None = None
self.last_invoke_from: InvokeFrom | None = None
self.last_allow_file_parameters: bool | None = None
@@ -47,6 +49,7 @@ class FakeRuntimeProvider:
allow_file_parameters: bool = False,
use_default_for_missing_form_parameters: bool = False,
) -> Tool:
+ self.call_count += 1
self.last_agent_tool = agent_tool
self.last_invoke_from = invoke_from
self.last_allow_file_parameters = allow_file_parameters
@@ -182,25 +185,26 @@ def _tts_tool() -> FakeTool:
def _build(
- builder: WorkflowAgentPluginToolsBuilder,
+ builder: WorkflowAgentDifyToolsBuilder,
tools: AgentSoulToolsConfig,
*,
invoke_from: InvokeFrom = InvokeFrom.DEBUGGER,
):
- """Shorthand for ``builder.build(...)`` with the standard tenant/app/user
- triple, so each test only highlights what's actually unique to it."""
- return builder.build(
+ """Shorthand for tests that expect ``build_layers(...)`` to return only plugin tools."""
+ layers = builder.build_layers(
tenant_id="tenant-1",
app_id="app-1",
user_id="user-1",
tools=tools,
invoke_from=invoke_from,
)
+ assert layers.core_tools is None
+ return layers.plugin_tools
def test_builds_dify_plugin_tools_layer_from_existing_tool_runtime():
runtime_provider = FakeRuntimeProvider(_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -235,9 +239,9 @@ def test_builds_dify_plugin_tools_layer_from_existing_tool_runtime():
assert runtime_provider.last_agent_tool.provider_type.value == "plugin"
-def test_builds_dify_plugin_tool_with_file_llm_parameter():
+def test_builds_core_tool_with_file_llm_parameter():
runtime_provider = FakeRuntimeProvider(_file_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -251,24 +255,192 @@ def test_builds_dify_plugin_tool_with_file_llm_parameter():
}
)
- result = _build(builder, tools)
+ result = builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
- assert result is not None
- prepared = result.tools[0]
+ assert result.core_tools is not None
+ prepared = result.core_tools.tools[0]
assert prepared.tool_name == "asr"
assert prepared.runtime_parameters == {}
assert prepared.parameters[0].name == "audio_file"
assert prepared.parameters[0].type == "file"
- # The public Agent backend DTO carries non-scalar tool inputs in
- # ``parameters``; legacy JSON schema generation omits file fields.
assert prepared.parameters_json_schema == {"type": "object", "properties": {}, "required": []}
assert runtime_provider.last_allow_file_parameters is True
assert runtime_provider.last_use_default_for_missing_form_parameters is True
-def test_builds_dify_plugin_tool_with_missing_required_select_default():
+def test_build_layers_routes_plugin_direct_and_builtin_via_core() -> None:
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
+ tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_id": "langgenius/search/search",
+ "provider_type": "plugin",
+ "tool_name": "search",
+ "credential_type": "api-key",
+ "credential_id": "credential-1",
+ "runtime_parameters": {"region": "us"},
+ },
+ {
+ "provider_id": "audio",
+ "provider_type": "builtin",
+ "tool_name": "transcribe",
+ "credential_type": "unauthorized",
+ },
+ ]
+ }
+ )
+
+ result = builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert result.plugin_tools is not None
+ assert [tool.tool_name for tool in result.plugin_tools.tools] == ["search"]
+ assert result.core_tools is not None
+ assert [tool.provider_type for tool in result.core_tools.tools] == ["builtin"]
+ assert [tool.tool_name for tool in result.core_tools.tools] == ["transcribe"]
+
+
+ ("provider_type", "provider_id"),
+ [
+ ("api", "search-api"),
+ ("workflow", "workflow-provider-1"),
+ ],
+)
+def test_build_layers_routes_api_and_workflow_via_core(provider_type: str, provider_id: str) -> None:
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
+ tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_id": provider_id,
+ "provider_type": provider_type,
+ "tool_name": "search",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ result = builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert result.plugin_tools is None
+ assert result.core_tools is not None
+ assert [tool.provider_type for tool in result.core_tools.tools] == [provider_type]
+ assert [tool.provider_id for tool in result.core_tools.tools] == [provider_id]
+ assert [tool.tool_name for tool in result.core_tools.tools] == ["search"]
+
+
+def test_build_layers_normalizes_mcp_provider_ids_to_server_identifier() -> None:
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(
+ tool_runtime_provider=runtime_provider,
+ mcp_provider_id_resolver=lambda *, tenant_id, provider_id: "mcp-server-1",
+ )
+ tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_id": "db-row-id",
+ "provider_type": "mcp",
+ "tool_name": "search",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ result = builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert result.core_tools is not None
+ assert result.core_tools.tools[0].provider_id == "mcp-server-1"
+
+
+def test_build_layers_rejects_app_provider_type() -> None:
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
+ tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_id": "app-provider",
+ "provider_type": "app",
+ "tool_name": "search",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ with pytest.raises(WorkflowAgentDifyToolsBuildError, match="not supported"):
+ builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+ assert runtime_provider.last_agent_tool is None
+
+
+def test_build_layers_rejects_dataset_retrieval_provider_type() -> None:
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
+ tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_id": "dataset-provider",
+ "provider_type": "dataset-retrieval",
+ "tool_name": "search",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
+ builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
+
+ assert exc_info.value.error_code == "agent_tool_provider_not_supported"
+ assert runtime_provider.last_agent_tool is None
+
+
+def test_builds_core_tool_with_missing_required_select_default():
runtime_provider = FakeRuntimeProvider(_tts_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -282,17 +454,24 @@ def test_builds_dify_plugin_tool_with_missing_required_select_default():
}
)
- result = _build(builder, tools)
+ result = builder.build_layers(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ user_id="user-1",
+ tools=tools,
+ invoke_from=InvokeFrom.DEBUGGER,
+ )
- assert result is not None
- prepared = result.tools[0]
+ assert result.core_tools is not None
+ prepared = result.core_tools.tools[0]
assert prepared.tool_name == "tts"
assert prepared.runtime_parameters == {"model": "provider-a#model-a"}
assert runtime_provider.last_use_default_for_missing_form_parameters is True
def test_rejects_duplicate_exposed_tool_names():
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(_tool()))
+ runtime_provider = FakeRuntimeProvider(_tool())
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -314,14 +493,15 @@ def test_rejects_duplicate_exposed_tool_names():
}
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, tools)
assert exc_info.value.error_code == "agent_tool_name_duplicated"
+ assert runtime_provider.call_count == 1
def test_rejects_missing_required_runtime_parameter():
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(_tool(runtime_parameters={})))
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(_tool(runtime_parameters={})))
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -335,7 +515,7 @@ def test_rejects_missing_required_runtime_parameter():
}
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, tools)
assert exc_info.value.error_code == "agent_tool_runtime_parameter_missing"
@@ -355,7 +535,7 @@ def test_invoke_from_is_forwarded_to_tool_runtime_provider():
representative invoke_from values."""
for invoke_from in (InvokeFrom.DEBUGGER, InvokeFrom.SERVICE_API, InvokeFrom.WEB_APP):
runtime_provider = FakeRuntimeProvider(_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -382,7 +562,7 @@ def test_invoke_from_is_forwarded_to_tool_runtime_provider():
def test_disabled_tools_are_skipped():
runtime_provider = FakeRuntimeProvider(_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -408,7 +588,7 @@ def test_plugin_id_plus_provider_fallback_when_provider_id_missing():
"""Frontend may send ``plugin_id`` + ``provider`` instead of the
concatenated ``provider_id``; the builder must accept both shapes."""
runtime_provider = FakeRuntimeProvider(_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -444,7 +624,7 @@ def test_unauthorized_tool_without_credentials():
return tool
runtime_provider = FakeRuntimeProvider(_no_credentials_tool())
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider)
tools = AgentSoulToolsConfig.model_validate(
{
"dify_tools": [
@@ -488,10 +668,10 @@ def _standard_tools_payload() -> AgentSoulToolsConfig:
def test_tool_provider_not_found_maps_to_declaration_not_found():
from core.tools.errors import ToolProviderNotFoundError
- builder = WorkflowAgentPluginToolsBuilder(
+ builder = WorkflowAgentDifyToolsBuilder(
tool_runtime_provider=FakeRuntimeProvider(ToolProviderNotFoundError("provider gone"))
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, _standard_tools_payload())
assert exc_info.value.error_code == "agent_tool_declaration_not_found"
@@ -499,10 +679,10 @@ def test_tool_provider_not_found_maps_to_declaration_not_found():
def test_credential_validation_error_maps_to_credential_invalid():
from core.tools.errors import ToolProviderCredentialValidationError
- builder = WorkflowAgentPluginToolsBuilder(
+ builder = WorkflowAgentDifyToolsBuilder(
tool_runtime_provider=FakeRuntimeProvider(ToolProviderCredentialValidationError("creds expired"))
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, _standard_tools_payload())
assert exc_info.value.error_code == "agent_tool_credential_invalid"
@@ -512,8 +692,8 @@ def test_generic_value_error_maps_to_config_invalid():
``agent_tool_config_invalid`` — distinct from
``agent_tool_declaration_not_found`` so callers can render a different
hint."""
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(ValueError("runtime missing")))
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(ValueError("runtime missing")))
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, _standard_tools_payload())
assert exc_info.value.error_code == "agent_tool_config_invalid"
@@ -536,8 +716,8 @@ def test_rejects_non_scalar_credential_value():
tool.runtime.credentials = {"oauth": {"access_token": "secret", "expires_in": 3600}}
return tool
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(_dict_credential_tool()))
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=FakeRuntimeProvider(_dict_credential_tool()))
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, _standard_tools_payload())
assert exc_info.value.error_code == "agent_tool_credential_shape_invalid"
@@ -578,13 +758,13 @@ def test_legacy_provider_name_and_tool_parameters_normalized():
def test_provider_level_entry_expands_to_all_tools():
runtime_provider = FakeRuntimeProvider(_tool())
- listed: list[tuple[str, str]] = []
+ listed: list[tuple[str, str, ToolProviderType]] = []
- def lister(*, tenant_id: str, provider_id: str) -> list[str]:
- listed.append((tenant_id, provider_id))
+ def lister(*, tenant_id: str, provider_type: ToolProviderType, provider_id: str) -> list[str]:
+ listed.append((tenant_id, provider_id, provider_type))
return ["search", "image_search"]
- builder = WorkflowAgentPluginToolsBuilder(tool_runtime_provider=runtime_provider, provider_tools_lister=lister)
+ builder = WorkflowAgentDifyToolsBuilder(tool_runtime_provider=runtime_provider, provider_tools_lister=lister)
tools = AgentSoulToolsConfig.model_validate(
{"dify_tools": [{"provider_id": "langgenius/search/search", "credential_type": "unauthorized"}]}
)
@@ -593,13 +773,13 @@ def test_provider_level_entry_expands_to_all_tools():
assert result is not None
assert [tool.tool_name for tool in result.tools] == ["search", "image_search"]
- assert listed == [("tenant-1", "langgenius/search/search")]
+ assert listed == [("tenant-1", "langgenius/search/search", ToolProviderType.PLUGIN)]
def test_explicit_tool_entry_wins_over_provider_expansion():
- builder = WorkflowAgentPluginToolsBuilder(
+ builder = WorkflowAgentDifyToolsBuilder(
tool_runtime_provider=FakeRuntimeProvider(_tool()),
- provider_tools_lister=lambda *, tenant_id, provider_id: ["search", "image_search"],
+ provider_tools_lister=lambda *, tenant_id, provider_type, provider_id: ["search", "image_search"],
)
tools = AgentSoulToolsConfig.model_validate(
{
@@ -623,15 +803,15 @@ def test_explicit_tool_entry_wins_over_provider_expansion():
def test_provider_level_entry_with_no_tools_maps_to_declaration_not_found():
- builder = WorkflowAgentPluginToolsBuilder(
+ builder = WorkflowAgentDifyToolsBuilder(
tool_runtime_provider=FakeRuntimeProvider(_tool()),
- provider_tools_lister=lambda *, tenant_id, provider_id: [],
+ provider_tools_lister=lambda *, tenant_id, provider_type, provider_id: [],
)
tools = AgentSoulToolsConfig.model_validate(
{"dify_tools": [{"provider_id": "langgenius/search/search", "credential_type": "unauthorized"}]}
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, tools)
assert exc_info.value.error_code == "agent_tool_declaration_not_found"
@@ -639,17 +819,17 @@ def test_provider_level_entry_with_no_tools_maps_to_declaration_not_found():
def test_provider_level_entry_unknown_provider_maps_to_declaration_not_found():
from core.tools.errors import ToolProviderNotFoundError
- def lister(*, tenant_id: str, provider_id: str) -> list[str]:
+ def lister(*, tenant_id: str, provider_type: ToolProviderType, provider_id: str) -> list[str]:
raise ToolProviderNotFoundError("provider gone")
- builder = WorkflowAgentPluginToolsBuilder(
+ builder = WorkflowAgentDifyToolsBuilder(
tool_runtime_provider=FakeRuntimeProvider(_tool()), provider_tools_lister=lister
)
tools = AgentSoulToolsConfig.model_validate(
{"dify_tools": [{"provider_id": "langgenius/search/search", "credential_type": "unauthorized"}]}
)
- with pytest.raises(WorkflowAgentPluginToolsBuildError) as exc_info:
+ with pytest.raises(WorkflowAgentDifyToolsBuildError) as exc_info:
_build(builder, tools)
assert exc_info.value.error_code == "agent_tool_declaration_not_found"
@@ -659,7 +839,7 @@ def test_list_provider_tool_names_reads_builtin_provider(monkeypatch):
to the plain name list the expansion step consumes."""
from types import SimpleNamespace
- from core.workflow.nodes.agent_v2 import plugin_tools_builder as module
+ from core.workflow.nodes.agent_v2 import dify_tools_builder as module
provider = SimpleNamespace(
get_tools=lambda: [
@@ -676,7 +856,11 @@ def test_list_provider_tool_names_reads_builtin_provider(monkeypatch):
monkeypatch.setattr(module.ToolManager, "get_builtin_provider", staticmethod(fake_get_builtin_provider))
- names = module._list_provider_tool_names(tenant_id="tenant-1", provider_id="langgenius/duckduckgo/duckduckgo")
+ names = module._list_provider_tool_names(
+ tenant_id="tenant-1",
+ provider_type=module.ToolProviderType.BUILT_IN,
+ provider_id="langgenius/duckduckgo/duckduckgo",
+ )
assert names == ["ddg_search", "ddg_news"]
assert captured == {"provider_id": "langgenius/duckduckgo/duckduckgo", "tenant_id": "tenant-1"}
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
index 289319d74cb..3ed5a688c8b 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
@@ -1,17 +1,24 @@
import json
from dataclasses import replace
+from types import SimpleNamespace
from typing import cast
import pytest
from agenton.compositor import CompositorSessionSnapshot
+from dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolsLayerConfig
from dify_agent.layers.dify_plugin import DifyPluginToolConfig, DifyPluginToolsLayerConfig
from dify_agent.protocol import DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LAYER_ID
-from clients.agent_backend import DIFY_EXECUTION_CONTEXT_LAYER_ID, DIFY_PLUGIN_TOOLS_LAYER_ID
+from clients.agent_backend import (
+ DIFY_CONFIG_LAYER_ID,
+ DIFY_CORE_TOOLS_LAYER_ID,
+ DIFY_EXECUTION_CONTEXT_LAYER_ID,
+ DIFY_PLUGIN_TOOLS_LAYER_ID,
+)
from clients.agent_backend.request_builder import DIFY_SHELL_LAYER_ID
from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom, UserFrom
from core.workflow.file_reference import build_file_reference
-from core.workflow.nodes.agent_v2.plugin_tools_builder import WorkflowAgentPluginToolsBuilder
+from core.workflow.nodes.agent_v2.dify_tools_builder import WorkflowAgentDifyToolsBuilder
from core.workflow.nodes.agent_v2.runtime_request_builder import (
WorkflowAgentRuntimeBuildContext,
WorkflowAgentRuntimeRequestBuilder,
@@ -24,6 +31,7 @@ from models.agent import Agent, AgentConfigSnapshot, WorkflowAgentNodeBinding
from models.agent_config_entities import (
AgentSoulConfig,
AgentSoulModelConfig,
+ AgentSoulToolsConfig,
DeclaredArrayItem,
DeclaredOutputChildConfig,
DeclaredOutputConfig,
@@ -79,35 +87,65 @@ def test_agent_soul_round_trip_preserves_existing_app_feature_fields():
assert dumped["app_features"]["more_like_this"] == {"enabled": False}
-class FakePluginToolsBuilder:
+class CapturingPluginLayerBuilder:
def __init__(self) -> None:
# Capture the runtime invocation source so tests can assert it was
# threaded through from ``DifyRunContext.invoke_from`` rather than
# hard-coded to a placeholder like ``VALIDATION``.
self.last_invoke_from: InvokeFrom | None = None
- def build(self, *, tenant_id, app_id, user_id, tools, invoke_from):
+ def build_layers(self, *, tenant_id, app_id, user_id, tools, invoke_from):
assert tenant_id == "tenant-1"
assert app_id == "app-1"
assert user_id == "user-1"
self.last_invoke_from = invoke_from
if not tools.dify_tools:
- return None
- return DifyPluginToolsLayerConfig(
- tools=[
- DifyPluginToolConfig(
- plugin_id="langgenius/time",
- provider="time",
- tool_name="current_time",
- credential_type="unauthorized",
- name="current_time",
- description="Get current time.",
- credentials={},
- runtime_parameters={},
- parameters=[],
- parameters_json_schema={"type": "object", "properties": {}, "required": []},
- )
- ]
+ return SimpleNamespace(plugin_tools=None, core_tools=None, exposed_tool_names=lambda: [])
+ return SimpleNamespace(
+ plugin_tools=DifyPluginToolsLayerConfig(
+ tools=[
+ DifyPluginToolConfig(
+ plugin_id="langgenius/time",
+ provider="time",
+ tool_name="current_time",
+ credential_type="unauthorized",
+ name="current_time",
+ description="Get current time.",
+ credentials={},
+ runtime_parameters={},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ core_tools=None,
+ exposed_tool_names=lambda: ["current_time"],
+ )
+
+
+class FakeCoreLayerBuilder:
+ def build_layers(self, *, tenant_id, app_id, user_id, tools, invoke_from):
+ assert tenant_id == "tenant-1"
+ assert app_id == "app-1"
+ assert user_id == "user-1"
+ del tools, invoke_from
+ return SimpleNamespace(
+ plugin_tools=None,
+ core_tools=DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ runtime_parameters={},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ exposed_tool_names=lambda: ["transcribe"],
)
@@ -218,6 +256,89 @@ def test_builds_create_run_request_from_agent_soul_and_node_job():
assert redacted_layers[DIFY_AGENT_MODEL_LAYER_ID]["config"]["credentials"] == "[REDACTED]"
+def test_build_includes_plugin_tools_layer_returned_by_injected_builder_for_debugger():
+ tools_builder = CapturingPluginLayerBuilder()
+ context = _context()
+ context.snapshot.config_snapshot.tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/time/time",
+ "tool_name": "current_time",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(
+ credentials_provider=FakeCredentialsProvider(),
+ dify_tools_builder=tools_builder, # type: ignore[arg-type]
+ ).build(context)
+
+ layers = _request_layers(result)
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID in layers
+ assert DIFY_CORE_TOOLS_LAYER_ID not in layers
+ assert tools_builder.last_invoke_from == InvokeFrom.DEBUGGER
+
+
+def test_build_forwards_service_api_invoke_from_to_injected_plugin_layer_builder():
+ tools_builder = CapturingPluginLayerBuilder()
+ context = _context()
+ context.snapshot.config_snapshot.tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/time/time",
+ "tool_name": "current_time",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+ context = replace(
+ context,
+ dify_context=context.dify_context.model_copy(update={"invoke_from": InvokeFrom.SERVICE_API}),
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(
+ credentials_provider=FakeCredentialsProvider(),
+ dify_tools_builder=tools_builder, # type: ignore[arg-type]
+ ).build(context)
+
+ layers = _request_layers(result)
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID in layers
+ assert DIFY_CORE_TOOLS_LAYER_ID not in layers
+ assert tools_builder.last_invoke_from == InvokeFrom.SERVICE_API
+
+
+def test_build_includes_core_tools_layer_returned_by_injected_builder():
+ context = _context()
+ context.snapshot.config_snapshot.tools = AgentSoulToolsConfig.model_validate(
+ {
+ "dify_tools": [
+ {
+ "provider_type": "builtin",
+ "provider_id": "audio",
+ "tool_name": "transcribe",
+ "credential_type": "unauthorized",
+ }
+ ]
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(
+ credentials_provider=FakeCredentialsProvider(),
+ dify_tools_builder=FakeCoreLayerBuilder(), # type: ignore[arg-type]
+ ).build(context)
+
+ layers = _request_layers(result)
+ assert DIFY_CORE_TOOLS_LAYER_ID in layers
+ assert DIFY_PLUGIN_TOOLS_LAYER_ID not in layers
+
+
def test_normalizes_langgenius_model_provider_for_agent_backend_transport():
context = _context()
context.snapshot.config_snapshot = AgentSoulConfig(
@@ -287,13 +408,25 @@ def test_builds_workflow_run_request_with_file_output_schema_and_reserved_metada
assert layers[DIFY_EXECUTION_CONTEXT_LAYER_ID]["config"]["invoke_from"] == "service-api"
assert dumped["idempotency_key"] == "node-exec-1"
output_schema = dumped["composition"]["layers"][-1]["config"]["json_schema"]
+ output_description = dumped["composition"]["layers"][-1]["config"]["description"]
report_schema = output_schema["properties"]["report"]
- assert len(report_schema["oneOf"]) == 4
- assert all(branch["additionalProperties"] is False for branch in report_schema["oneOf"])
- assert report_schema["oneOf"][0]["required"] == ["transfer_method", "reference"]
- assert report_schema["oneOf"][1]["required"] == ["transfer_method", "reference"]
- assert report_schema["oneOf"][2]["required"] == ["transfer_method", "reference"]
- assert report_schema["oneOf"][3]["required"] == ["transfer_method", "url"]
+ report_schema_branches = {
+ branch["properties"]["transfer_method"]["enum"][0]: branch for branch in report_schema["anyOf"]
+ }
+ assert set(report_schema_branches) == {"tool_file", "remote_url"}
+ tool_file_branch = report_schema_branches["tool_file"]
+ assert tool_file_branch["additionalProperties"] is False
+ assert tool_file_branch["required"] == ["transfer_method", "reference"]
+ assert set(tool_file_branch["properties"]) == {"transfer_method", "reference"}
+ assert tool_file_branch["properties"]["reference"]["pattern"].startswith("^dify-file-ref:")
+ remote_url_branch = report_schema_branches["remote_url"]
+ assert remote_url_branch["additionalProperties"] is False
+ assert remote_url_branch["required"] == ["transfer_method", "url"]
+ assert set(remote_url_branch["properties"]) == {"transfer_method", "url"}
+ assert "dify-agent file upload <path>" in output_description
+ assert "final_output.report" in output_description
+ assert "never invent the `reference` value" in output_description
+ assert "Do not call `final_output` before the upload command succeeds" in output_description
assert output_schema["properties"]["confidence"]["type"] == "number"
assert output_schema["required"] == ["report"]
assert layers[DIFY_AGENT_MODEL_LAYER_ID]["config"]["model_settings"] == {"temperature": 0.2}
@@ -507,10 +640,10 @@ def test_builds_workflow_run_request_with_dify_plugin_tools_layer():
)
context = replace(context, snapshot=snapshot)
- plugin_tools_builder = FakePluginToolsBuilder()
+ dify_tools_builder = CapturingPluginLayerBuilder()
result = WorkflowAgentRuntimeRequestBuilder(
credentials_provider=FakeCredentialsProvider(),
- plugin_tools_builder=cast(WorkflowAgentPluginToolsBuilder, plugin_tools_builder),
+ dify_tools_builder=cast(WorkflowAgentDifyToolsBuilder, dify_tools_builder),
).build(context)
dumped = result.request.model_dump(mode="json")
@@ -527,7 +660,7 @@ def test_builds_workflow_run_request_with_dify_plugin_tools_layer():
# into the plugin tools builder so ToolManager attributes credential
# quotas / rate limits / audit tags to the real call site instead of a
# hard-coded ``VALIDATION`` placeholder.
- assert plugin_tools_builder.last_invoke_from == context.dify_context.invoke_from
+ assert dify_tools_builder.last_invoke_from == context.dify_context.invoke_from
def test_build_maps_agent_soul_knowledge_to_knowledge_layer_config():
@@ -840,8 +973,12 @@ def test_empty_declared_outputs_injects_prd_defaults_text_files_json():
assert properties["text"]["type"] == "string"
assert properties["files"]["type"] == "array"
# `files` defaults to array<file> → items is a file ref object.
- assert len(properties["files"]["items"]["oneOf"]) == 4
- assert all(branch["additionalProperties"] is False for branch in properties["files"]["items"]["oneOf"])
+ file_item_branches = properties["files"]["items"]["anyOf"]
+ assert [branch["properties"]["transfer_method"]["enum"] for branch in file_item_branches] == [
+ ["tool_file"],
+ ["remote_url"],
+ ]
+ assert all(branch["additionalProperties"] is False for branch in file_item_branches)
assert properties["json"]["type"] == "object"
# Defaults are all required=False so no `required:` key on the schema.
assert "required" not in output_layer["json_schema"]
@@ -1123,196 +1260,141 @@ def test_previous_node_remote_url_file_mapping_is_not_truncated_in_workflow_cont
assert "...[truncated]" not in _workflow_user_prompt(result)
-# ── ENG-623: dify.drive declaration layer ─────────────────────────────────────
+# ── Agent config declaration layer ────────────────────────────────────────────
-def _soul_with_drive_skill() -> AgentSoulConfig:
+def _soul_with_config_assets() -> AgentSoulConfig:
return AgentSoulConfig(
prompt={
"system_prompt": (
- "You are careful. Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] "
- "and [§file:files%2Fsample.pdf:sample.pdf§]."
+ "You are careful. Use [§skill:tender-analyzer:Tender Analyzer§] and [§file:sample.pdf:sample.pdf§]."
)
},
model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),
+ config_skills=[{"name": "tender-analyzer", "description": "Parses RFPs.", "file_id": "tool-file-1"}],
+ config_files=[{"name": "sample.pdf", "file_kind": "upload_file", "file_id": "upload-file-1"}],
+ config_note="Read the proposal first.",
)
-def _mock_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",
- lambda self, *, tenant_id, agent_id: [
- {
- "path": "tender-analyzer",
- "skill_md_key": "tender-analyzer/SKILL.md",
- "archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",
- "name": "Tender Analyzer",
- "description": "Parses RFPs.",
- "size": 123,
- "mime_type": "text/markdown",
- "hash": "hash-1",
- "created_at": 1,
- }
- ],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [
- {"key": "tender-analyzer/SKILL.md", "is_skill": True},
- {"key": "tender-analyzer/.DIFY-SKILL-FULL.zip", "is_skill": False},
- {"key": "files/sample.pdf", "is_skill": False},
- ],
- )
-
+def test_build_config_layer_config_includes_soul_context_and_mentions():
+ from core.workflow.nodes.agent_v2.runtime_request_builder import build_config_layer_config
-def _mock_empty_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",
- lambda self, *, tenant_id, agent_id: [],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],
+ config, warnings = build_config_layer_config(
+ _soul_with_config_assets(),
+ agent_id="agent-1",
+ config_version_id="snapshot-1",
)
-
-def test_build_drive_layer_config_catalogs_drive_skills_and_mentions(monkeypatch: pytest.MonkeyPatch):
- from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config
-
- _mock_drive_catalog(monkeypatch)
- config, warnings = build_drive_layer_config(_soul_with_drive_skill(), tenant_id="tenant-1", agent_id="agent-1")
-
assert config is not None
- assert config.drive_ref == "agent-agent-1"
- assert [skill.skill_md_key for skill in config.skills] == ["tender-analyzer/SKILL.md"]
- assert config.skills[0].archive_key == "tender-analyzer/.DIFY-SKILL-FULL.zip"
- assert config.mentioned_skill_keys == ["tender-analyzer/SKILL.md"]
- assert config.mentioned_file_keys == ["files/sample.pdf"]
+ assert config.agent_id == "agent-1"
+ assert config.config_version is not None
+ assert config.config_version.id == "snapshot-1"
+ assert config.config_version.kind == "snapshot"
+ assert config.config_version.writable is False
+ assert [skill.name for skill in config.skills] == ["tender-analyzer"]
+ assert [file_ref.name for file_ref in config.files] == ["sample.pdf"]
+ assert config.note == "Read the proposal first."
+ assert config.mentioned_skill_names == ["tender-analyzer"]
+ assert config.mentioned_file_names == ["sample.pdf"]
assert warnings == []
-def test_build_drive_layer_config_emits_drive_ref_when_catalog_is_empty(monkeypatch: pytest.MonkeyPatch):
- from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config
+def test_build_config_layer_config_returns_none_for_empty_agent_soul():
+ from core.workflow.nodes.agent_v2.runtime_request_builder import build_config_layer_config
- _mock_empty_drive_catalog(monkeypatch)
soul = AgentSoulConfig(
model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test")
)
- config, warnings = build_drive_layer_config(soul, tenant_id="tenant-1", agent_id="agent-1")
+ config, warnings = build_config_layer_config(soul)
- assert config is not None
- assert config.drive_ref == "agent-agent-1"
- assert config.skills == []
- assert config.mentioned_skill_keys == []
- assert config.mentioned_file_keys == []
+ assert config is None
assert warnings == []
-def test_workflow_run_request_contains_drive_layer_with_empty_catalog(monkeypatch: pytest.MonkeyPatch):
+def test_workflow_run_request_has_no_config_layer_with_empty_agent_soul(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
monkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
- _mock_empty_drive_catalog(monkeypatch)
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(_context())
dumped = result.request.model_dump(mode="json")
layers = {layer["name"]: layer for layer in dumped["composition"]["layers"]}
- assert layers["drive"]["config"] == {
- "drive_ref": "agent-agent-1",
- "skills": [],
- "mentioned_skill_keys": [],
- "mentioned_file_keys": [],
- }
+ assert DIFY_CONFIG_LAYER_ID not in layers
assert layers[DIFY_SHELL_LAYER_ID]["deps"] == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
- assert layers[DIFY_SHELL_LAYER_ID]["config"]["agent_stub_drive_ref"] == "agent-agent-1"
- assert layers["drive"]["deps"] == {"shell": DIFY_SHELL_LAYER_ID}
+ assert layers[DIFY_SHELL_LAYER_ID]["config"]["agent_stub_drive_ref"] is None
-def test_build_drive_layer_config_requires_agent_identity():
- from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config
-
- config, warnings = build_drive_layer_config(_soul_with_drive_skill(), tenant_id="tenant-1", agent_id=None)
-
- assert config is None
- assert [w["code"] for w in warnings] == ["drive_ref_dangling"]
-
-
-def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatch: pytest.MonkeyPatch):
- """Contract test: locks the dify.drive composition shape against cross-package drift."""
+def test_workflow_run_request_contains_config_layer_when_flag_enabled(monkeypatch: pytest.MonkeyPatch):
+ """Contract test: locks the dify.config composition shape against cross-package drift."""
monkeypatch.setattr(
"core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
- _mock_drive_catalog(monkeypatch)
context = _context()
- context.snapshot.config_snapshot = _soul_with_drive_skill()
+ context.snapshot.config_snapshot = _soul_with_config_assets()
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
dumped = result.request.model_dump(mode="json")
layer_names = [layer["name"] for layer in dumped["composition"]["layers"]]
- assert "drive" in layer_names
- # shell enters first; drive uses that shell to materialize mentioned targets.
+ assert DIFY_CONFIG_LAYER_ID in layer_names
+ # shell enters first; config uses that shell to materialize mentioned targets.
assert layer_names.index(DIFY_SHELL_LAYER_ID) == layer_names.index("execution_context") + 1
- assert layer_names.index("drive") == layer_names.index(DIFY_SHELL_LAYER_ID) + 1
- drive = next(layer for layer in dumped["composition"]["layers"] if layer["name"] == "drive")
- assert drive["type"] == "dify.drive"
- assert drive["deps"] == {"shell": DIFY_SHELL_LAYER_ID}
- assert drive["config"]["drive_ref"] == "agent-agent-1"
- assert drive["config"]["skills"] == [
- {
- "path": "tender-analyzer",
- "name": "Tender Analyzer",
- "description": "Parses RFPs.",
- "skill_md_key": "tender-analyzer/SKILL.md",
- "archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",
- }
- ]
- assert drive["config"]["mentioned_skill_keys"] == ["tender-analyzer/SKILL.md"]
- assert drive["config"]["mentioned_file_keys"] == ["files/sample.pdf"]
+ assert layer_names.index(DIFY_CONFIG_LAYER_ID) == layer_names.index(DIFY_SHELL_LAYER_ID) + 1
+ config = next(layer for layer in dumped["composition"]["layers"] if layer["name"] == DIFY_CONFIG_LAYER_ID)
+ assert config["type"] == "dify.config"
+ assert config["deps"] == {"shell": DIFY_SHELL_LAYER_ID}
+ assert config["config"] == {
+ "agent_id": "agent-1",
+ "config_version": {"id": "snapshot-1", "kind": "snapshot", "writable": False},
+ "skills": [
+ {
+ "name": "tender-analyzer",
+ "description": "Parses RFPs.",
+ "size": None,
+ "mime_type": "application/zip",
+ }
+ ],
+ "files": [{"name": "sample.pdf", "size": None, "mime_type": None}],
+ "env_keys": [],
+ "note": "Read the proposal first.",
+ "mentioned_skill_names": ["tender-analyzer"],
+ "mentioned_file_names": ["sample.pdf"],
+ }
warnings = result.metadata["runtime_support"]["unsupported_runtime_warnings"]
assert warnings == []
- # the drive layer is non-sensitive and must survive into persistable specs
+ # the config layer is non-sensitive and must survive into persistable specs
from dify_agent.protocol import extract_runtime_layer_specs
specs = extract_runtime_layer_specs(result.request.composition)
- assert any(spec.name == "drive" and spec.type == "dify.drive" for spec in specs)
+ assert any(spec.name == DIFY_CONFIG_LAYER_ID and spec.type == "dify.config" for spec in specs)
-def test_workflow_runtime_expands_drive_mentions_in_agent_soul_prompt(monkeypatch: pytest.MonkeyPatch):
+def test_workflow_runtime_expands_config_mentions_in_agent_soul_prompt(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
- _mock_drive_catalog(monkeypatch)
context = _context()
- context.snapshot.config_snapshot = _soul_with_drive_skill()
+ context.snapshot.config_snapshot = _soul_with_config_assets()
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
soul_prompt = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert soul_prompt.config.prefix == "You are careful. Use Tender Analyzer and sample.pdf."
+ assert soul_prompt.config.prefix == "You are careful. Use tender-analyzer and sample.pdf."
assert "[§" not in soul_prompt.config.prefix
-def test_workflow_runtime_missing_drive_mentions_fall_back_to_label_then_decoded_key(monkeypatch: pytest.MonkeyPatch):
+def test_workflow_runtime_missing_config_mentions_fall_back_to_label_then_name(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True
)
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",
- lambda self, *, tenant_id, agent_id: [],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],
- )
context = _context()
context.snapshot.config_snapshot = AgentSoulConfig(
prompt={
"system_prompt": (
- "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "
- "and [§file:files%2Fno-label.txt§]."
+ "Use [§skill:ghost-skill:Ghost Skill§], [§file:ghost.txt:Ghost File§], and [§file:no-label.txt§]."
)
},
model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),
@@ -1321,34 +1403,36 @@ def test_workflow_runtime_missing_drive_mentions_fall_back_to_label_then_decoded
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
soul_prompt = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")
- assert soul_prompt.config.prefix == "Use Ghost Skill, Ghost File, and files/no-label.txt."
+ assert soul_prompt.config.prefix == "Use Ghost Skill, Ghost File, and no-label.txt."
assert "[§" not in soul_prompt.config.prefix
-def test_workflow_run_request_has_no_drive_layer_when_flag_disabled(monkeypatch: pytest.MonkeyPatch):
+def test_workflow_run_request_has_no_config_layer_when_flag_disabled(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
)
context = _context()
- context.snapshot.config_snapshot = _soul_with_drive_skill()
+ context.snapshot.config_snapshot = _soul_with_config_assets()
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
dumped = result.request.model_dump(mode="json")
- assert all(layer["name"] != "drive" for layer in dumped["composition"]["layers"])
+ assert all(layer["name"] != DIFY_CONFIG_LAYER_ID for layer in dumped["composition"]["layers"])
assert result.metadata["runtime_support"]["unsupported_runtime_warnings"] == []
-def test_build_drive_layer_config_missing_mentions_warn_but_keep_skill_catalog(monkeypatch: pytest.MonkeyPatch):
- from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config
+def test_build_config_layer_config_missing_mentions_warn_without_catalog():
+ from core.workflow.nodes.agent_v2.runtime_request_builder import build_config_layer_config
- _mock_drive_catalog(monkeypatch)
soul = AgentSoulConfig(
model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),
- prompt={"system_prompt": "Use [§skill:ghost%2FSKILL.md:Ghost§]"},
+ config_skills=[{"name": "tender-analyzer", "description": "Parses RFPs.", "file_id": "tool-file-1"}],
+ prompt={"system_prompt": "Use [§skill:ghost-skill:Ghost§]"},
)
- config, warnings = build_drive_layer_config(soul, tenant_id="tenant-1", agent_id="agent-1")
+ config, warnings = build_config_layer_config(soul)
assert config is not None
+ assert config.mentioned_skill_names == []
+ assert config.mentioned_file_names == []
assert [w["code"] for w in warnings] == ["mention_target_missing"]
diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.py
index 60bc36c773f..2ff68108c81 100644
--- a/api/tests/unit_tests/services/agent/test_agent_services.py
+++ b/api/tests/unit_tests/services/agent/test_agent_services.py
@@ -236,6 +236,62 @@ def test_load_workflow_composer_uses_inline_preview_snapshot(monkeypatch: pytest
assert result == {"agent": "inline-agent-1", "version": "inline-preview-version"}
+def test_workflow_inline_debug_conversation_seed(monkeypatch: pytest.MonkeyPatch):
+ captured: dict[str, object] = {}
+
+ class FakeRosterService:
+ def __init__(self, session):
+ captured["session"] = session
+
+ def get_or_create_agent_app_debug_conversation_id(self, **kwargs):
+ captured.update(kwargs)
+ return "debug-conversation-1"
+
+ monkeypatch.setattr(roster_service, "AgentRosterService", FakeRosterService)
+
+ binding = SimpleNamespace(binding_type=WorkflowAgentBindingType.INLINE_AGENT)
+ agent = SimpleNamespace(id="inline-agent-1", scope=AgentScope.WORKFLOW_ONLY)
+
+ debug_conversation_id = AgentComposerService._workflow_inline_debug_conversation_id(
+ tenant_id="tenant-1",
+ binding=binding,
+ agent=agent,
+ account_id="account-1",
+ )
+
+ assert debug_conversation_id == "debug-conversation-1"
+ assert captured["tenant_id"] == "tenant-1"
+ assert captured["agent_id"] == "inline-agent-1"
+ assert captured["account_id"] == "account-1"
+
+
+def test_workflow_inline_debug_conversation_seed_skips_non_inline(monkeypatch: pytest.MonkeyPatch):
+ class UnexpectedRosterService:
+ def __init__(self, session):
+ raise AssertionError("roster service should not be used")
+
+ monkeypatch.setattr(roster_service, "AgentRosterService", UnexpectedRosterService)
+
+ assert (
+ AgentComposerService._workflow_inline_debug_conversation_id(
+ tenant_id="tenant-1",
+ binding=SimpleNamespace(binding_type=WorkflowAgentBindingType.ROSTER_AGENT),
+ agent=SimpleNamespace(id="agent-1", scope=AgentScope.ROSTER),
+ account_id="account-1",
+ )
+ is None
+ )
+ assert (
+ AgentComposerService._workflow_inline_debug_conversation_id(
+ tenant_id="tenant-1",
+ binding=SimpleNamespace(binding_type=WorkflowAgentBindingType.INLINE_AGENT),
+ agent=SimpleNamespace(id="inline-agent-1", scope=AgentScope.WORKFLOW_ONLY),
+ account_id=None,
+ )
+ is None
+ )
+
+
def test_load_workflow_composer_rejects_preview_without_binding(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", lambda **kwargs: SimpleNamespace(id="workflow-1"))
monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", lambda **kwargs: None)
@@ -267,6 +323,7 @@ def test_save_workflow_composer_dispatches_save_strategy(monkeypatch, strategy,
current_snapshot_id="version-1",
)
calls = []
+ serialize_calls = []
monkeypatch.setattr(composer_service.db, "session", fake_session)
monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_draft_save_payload", lambda payload: None)
@@ -282,7 +339,12 @@ def test_save_workflow_composer_dispatches_save_strategy(monkeypatch, strategy,
"_get_version_if_present",
lambda **kwargs: SimpleNamespace(id="version-1"),
)
- monkeypatch.setattr(AgentComposerService, "_serialize_workflow_state", lambda **kwargs: {"state": "ok"})
+
+ def serialize_workflow_state(**kwargs):
+ serialize_calls.append(kwargs)
+ return {"state": "ok"}
+
+ monkeypatch.setattr(AgentComposerService, "_serialize_workflow_state", serialize_workflow_state)
def save_helper(**kwargs):
calls.append(kwargs)
@@ -304,6 +366,7 @@ def test_save_workflow_composer_dispatches_save_strategy(monkeypatch, strategy,
assert result.pop("validation") == {"warnings": [], "knowledge_retrieval_placeholder": []}
assert result == {"state": "ok"}
assert calls
+ assert serialize_calls[0]["account_id"] == "account-1"
assert fake_session.commits == 1
@@ -437,10 +500,12 @@ def test_save_agent_app_composer_rejects_version_save_strategy():
def test_save_agent_app_composer_updates_normal_draft(monkeypatch: pytest.MonkeyPatch):
agent = SimpleNamespace(
id="agent-1",
+ source=AgentSource.AGENT_APP,
active_config_snapshot_id="version-1",
active_config_is_published=True,
updated_by=None,
)
+ active_version = SimpleNamespace(config_snapshot_dict=AgentSoulConfig().model_dump(mode="json"))
fake_session = FakeSession(scalar=[agent])
saved = {}
@@ -451,6 +516,7 @@ def test_save_agent_app_composer_updates_normal_draft(monkeypatch: pytest.Monkey
"_save_agent_draft",
lambda **kwargs: saved.update(kwargs) or SimpleNamespace(id="draft-1"),
)
+ monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **_kwargs: active_version)
monkeypatch.setattr(AgentComposerService, "load_agent_composer", lambda **kwargs: {"loaded": True})
payload = ComposerSavePayload.model_validate(
{
@@ -473,6 +539,43 @@ def test_save_agent_app_composer_updates_normal_draft(monkeypatch: pytest.Monkey
assert fake_session.commits == 1
+def test_save_agent_app_composer_keeps_published_when_draft_matches_active_snapshot(monkeypatch: pytest.MonkeyPatch):
+ agent_soul = _agent_soul_with_model()
+ agent = SimpleNamespace(
+ id="agent-1",
+ source=AgentSource.AGENT_APP,
+ active_config_snapshot_id="version-1",
+ active_config_is_published=False,
+ updated_by=None,
+ )
+ active_version = SimpleNamespace(config_snapshot_dict=agent_soul.model_dump(mode="json"))
+ fake_session = FakeSession(scalar=[agent], scalars=[[AgentConfigRevisionOperation.PUBLISH_DRAFT]])
+
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+ monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_draft_save_payload", lambda payload: None)
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_save_agent_draft",
+ lambda **_kwargs: SimpleNamespace(id="draft-1"),
+ )
+ monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **_kwargs: active_version)
+ monkeypatch.setattr(AgentComposerService, "load_agent_composer", lambda **_kwargs: {"loaded": True})
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": ComposerVariant.AGENT_APP.value,
+ "save_strategy": ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value,
+ "agent_soul": agent_soul.model_dump(mode="json"),
+ }
+ )
+
+ AgentComposerService.save_agent_app_composer(
+ tenant_id="tenant-1", app_id="app-1", account_id="account-1", payload=payload
+ )
+
+ assert agent.active_config_is_published is True
+ assert fake_session.commits == 1
+
+
def test_publish_agent_app_draft_creates_published_snapshot(monkeypatch: pytest.MonkeyPatch):
agent = Agent(
id="agent-1",
@@ -565,7 +668,11 @@ def test_agent_app_build_draft_checkout_and_apply_use_user_isolated_draft(monkey
assert checked_out["agent_soul"] == normal_draft.config_snapshot_dict
assert fake_session.commits == 1
- fake_session = FakeSession(scalar=[agent, build_draft, normal_draft])
+ active_version = SimpleNamespace(config_snapshot_dict=build_draft.config_snapshot_dict)
+ fake_session = FakeSession(
+ scalar=[agent, build_draft, normal_draft, active_version],
+ scalars=[[AgentConfigRevisionOperation.PUBLISH_DRAFT]],
+ )
monkeypatch.setattr(composer_service.db, "session", fake_session)
applied = AgentComposerService.apply_agent_app_build_draft(
@@ -576,6 +683,62 @@ def test_agent_app_build_draft_checkout_and_apply_use_user_isolated_draft(monkey
assert applied["result"] == "success"
assert applied["draft"]["id"] == normal_draft.id
+ assert normal_draft.config_snapshot_dict == build_draft.config_snapshot_dict
+ assert agent.active_config_is_published is True
+ assert fake_session.deleted == [build_draft]
+ assert fake_session.commits == 1
+
+
+def test_agent_app_build_draft_apply_marks_unpublished_when_build_draft_differs(monkeypatch: pytest.MonkeyPatch):
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Iris",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id="version-1",
+ active_config_is_published=True,
+ )
+ active_agent_soul = _agent_soul_with_model()
+ build_agent_soul = AgentSoulConfig.model_validate(
+ {
+ **active_agent_soul.model_dump(mode="json"),
+ "prompt": {
+ "system_prompt": "Build draft prompt",
+ },
+ }
+ )
+ build_draft = AgentConfigDraft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id="account-1",
+ draft_owner_key="account-1",
+ base_snapshot_id="version-1",
+ config_snapshot=build_agent_soul,
+ )
+ normal_draft = AgentConfigDraft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ draft_owner_key="",
+ base_snapshot_id="version-1",
+ config_snapshot=active_agent_soul,
+ )
+ active_version = SimpleNamespace(config_snapshot_dict=active_agent_soul.model_dump(mode="json"))
+ fake_session = FakeSession(scalar=[agent, build_draft, normal_draft, active_version])
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+
+ AgentComposerService.apply_agent_app_build_draft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ account_id="account-1",
+ )
+
assert normal_draft.config_snapshot_dict == build_draft.config_snapshot_dict
assert agent.active_config_is_published is False
assert fake_session.deleted == [build_draft]
@@ -690,6 +853,53 @@ def test_serialize_workflow_state_passes_user_declared_outputs_through_effective
assert effective[0]["required"] is True
+def test_serialize_workflow_state_includes_inline_debug_conversation_message_state(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ binding = WorkflowAgentNodeBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ binding_type=WorkflowAgentBindingType.INLINE_AGENT,
+ agent_id="agent-1",
+ current_snapshot_id="version-1",
+ workflow_id="workflow-1",
+ node_id="node-1",
+ node_job_config='{"workflow_prompt":"work"}',
+ )
+ agent = Agent(
+ id="agent-1",
+ name="Inline Agent",
+ description="",
+ scope=AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.WORKFLOW,
+ status=AgentStatus.ACTIVE,
+ backing_app_id="backing-app-1",
+ )
+ version = AgentConfigSnapshot(id="version-1", version=1, config_snapshot='{"prompt":{"system_prompt":"x"}}')
+ monkeypatch.setattr(AgentComposerService, "calculate_impact", lambda **kwargs: {"workflow_node_count": 1})
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_workflow_inline_debug_conversation_id",
+ lambda **kwargs: "debug-conversation-1",
+ )
+ monkeypatch.setattr(
+ roster_service.AgentRosterService,
+ "count_agent_app_debug_conversation_messages",
+ lambda self, *, conversation_id: 2,
+ )
+
+ state = AgentComposerService._serialize_workflow_state(
+ binding=binding,
+ agent=agent,
+ version=version,
+ account_id="account-1",
+ )
+
+ assert state["debug_conversation_id"] == "debug-conversation-1"
+ assert state["debug_conversation_has_messages"] is True
+ assert state["debug_conversation_message_count"] == 2
+
+
def test_composer_save_helpers_create_and_rebind_agents(monkeypatch: pytest.MonkeyPatch):
fake_session = FakeSession()
monkeypatch.setattr(composer_service.db, "session", fake_session)
@@ -1215,16 +1425,18 @@ def test_copy_workflow_composer_from_roster_is_idempotent_when_already_inline(mo
version=1,
config_snapshot='{"prompt":{"system_prompt":"inline"}}',
)
+ serialize_calls = []
monkeypatch.setattr(composer_service.db, "session", FakeSession())
monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", lambda **kwargs: SimpleNamespace(id="workflow-1"))
monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", lambda **kwargs: inline_binding)
monkeypatch.setattr(AgentComposerService, "_get_agent_if_present", lambda **kwargs: inline_agent)
monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **kwargs: inline_version)
- monkeypatch.setattr(
- AgentComposerService,
- "_serialize_workflow_state",
- lambda **kwargs: {"binding_type": kwargs["binding"].binding_type.value},
- )
+
+ def serialize_workflow_state(**kwargs):
+ serialize_calls.append(kwargs)
+ return {"binding_type": kwargs["binding"].binding_type.value}
+
+ monkeypatch.setattr(AgentComposerService, "_serialize_workflow_state", serialize_workflow_state)
state = AgentComposerService.copy_workflow_composer_from_roster(
tenant_id="tenant-1",
@@ -1236,6 +1448,7 @@ def test_copy_workflow_composer_from_roster_is_idempotent_when_already_inline(mo
)
assert state == {"binding_type": WorkflowAgentBindingType.INLINE_AGENT.value}
+ assert serialize_calls[0]["account_id"] == "account-1"
@pytest.mark.parametrize(
@@ -1611,6 +1824,52 @@ def test_composer_create_roster_agent_raises_when_backing_agent_missing(monkeypa
)
+def test_agent_app_draft_match_does_not_mark_create_version_as_published(monkeypatch: pytest.MonkeyPatch):
+ agent_soul = AgentSoulConfig()
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ source=AgentSource.AGENT_APP,
+ active_config_snapshot_id="snapshot-1",
+ )
+ snapshot = SimpleNamespace(config_snapshot_dict=agent_soul)
+ fake_session = FakeSession(scalars=[[AgentConfigRevisionOperation.CREATE_VERSION]])
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+ monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **kwargs: snapshot)
+
+ assert (
+ AgentComposerService._agent_soul_matches_active_config(
+ tenant_id="tenant-1",
+ agent=agent,
+ agent_soul=agent_soul,
+ )
+ is False
+ )
+
+
+def test_agent_app_draft_match_marks_publish_visible_revision_as_published(monkeypatch: pytest.MonkeyPatch):
+ agent_soul = AgentSoulConfig()
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ source=AgentSource.AGENT_APP,
+ active_config_snapshot_id="snapshot-1",
+ )
+ snapshot = SimpleNamespace(config_snapshot_dict=agent_soul)
+ fake_session = FakeSession(scalars=[[AgentConfigRevisionOperation.PUBLISH_DRAFT]])
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+ monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **kwargs: snapshot)
+
+ assert (
+ AgentComposerService._agent_soul_matches_active_config(
+ tenant_id="tenant-1",
+ agent=agent,
+ agent_soul=agent_soul,
+ )
+ is True
+ )
+
+
def test_composer_version_helpers_and_lookup_errors(monkeypatch: pytest.MonkeyPatch):
fake_session = FakeSession(
scalar=[
@@ -2220,6 +2479,16 @@ def test_agent_app_debug_conversation_create_reuse_and_recreate():
assert recreate_session.commits == 1
+def test_agent_app_debug_conversation_message_count():
+ session = FakeSession(scalar=[3])
+
+ count = AgentRosterService(session).count_agent_app_debug_conversation_messages(
+ conversation_id="debug-conversation-1",
+ )
+
+ assert count == 3
+
+
def test_agent_app_debug_conversation_requires_app_binding():
agent = Agent(
id="agent-1",
diff --git a/api/tests/unit_tests/services/agent/test_prompt_mentions.py b/api/tests/unit_tests/services/agent/test_prompt_mentions.py
index 588093b89ca..b65f8b6f410 100644
--- a/api/tests/unit_tests/services/agent/test_prompt_mentions.py
+++ b/api/tests/unit_tests/services/agent/test_prompt_mentions.py
@@ -241,7 +241,21 @@ def test_node_job_resolver_resolves_each_kind(node_job: WorkflowNodeJobConfig):
expanded = expand_prompt_mentions(prompt, resolver)
- assert expanded == ("Read START/tenders and produce qna_report (file); if unsure contact EMAIL · David Hayes.")
+ assert expanded == (
+ "Read START/tenders and produce qna_report (file output; create the file locally, run "
+ "`dify-agent file upload <path>`, then copy the returned AgentStubFileMapping JSON "
+ "as final_output.qna_report; do not call final_output before upload succeeds, and do not use "
+ "the local path, filename, URL, or a synthesized dify-file-ref as the reference); "
+ "if unsure contact EMAIL · David Hayes."
+ )
+
+
+def test_node_job_resolver_accepts_legacy_reversed_output_token(node_job: WorkflowNodeJobConfig):
+ resolver = build_node_job_mention_resolver(node_job)
+
+ expanded = expand_prompt_mentions("[§qna_report:qna_report:output§]", resolver)
+
+ assert "final_output.qna_report" in expanded
def test_node_job_resolver_matches_ref_by_node_id_and_output_fields():
diff --git a/api/tests/unit_tests/services/test_agent_config_service.py b/api/tests/unit_tests/services/test_agent_config_service.py
new file mode 100644
index 00000000000..e122bcb066b
--- /dev/null
+++ b/api/tests/unit_tests/services/test_agent_config_service.py
@@ -0,0 +1,661 @@
+"""Focused tests for the Agent Soul-backed config service."""
+
+from __future__ import annotations
+
+import io
+import zipfile
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from models.agent_config_entities import (
+ AgentConfigFileRefConfig,
+ AgentConfigSkillRefConfig,
+ AgentEnvVariableConfig,
+ AgentSoulConfig,
+)
+from services.agent.skill_package_service import SkillPackageError
+from services.agent_config_service import (
+ AgentConfigService,
+ AgentConfigServiceError,
+ AgentConfigTarget,
+ AgentConfigVersionKind,
+ ConfigPushPayload,
+ ConfigPushSkillItem,
+)
+
+MODULE = "services.agent_config_service"
+TENANT = "tenant-1"
+AGENT = "agent-1"
+USER = "user-1"
+
+
+def _session_cm(session: MagicMock) -> MagicMock:
+ context_manager = MagicMock()
+ context_manager.__enter__.return_value = session
+ context_manager.__exit__.return_value = None
+ return context_manager
+
+
+def _soul(**updates) -> AgentSoulConfig:
+ payload = AgentSoulConfig().model_dump(mode="json")
+ payload.update(updates)
+ return AgentSoulConfig.model_validate(payload)
+
+
+def _version(*, version_id: str = "version-1", snapshot: AgentSoulConfig | None = None) -> SimpleNamespace:
+ agent_soul = snapshot or _soul()
+ return SimpleNamespace(
+ id=version_id,
+ config_snapshot_dict=agent_soul.model_dump(mode="json"),
+ config_snapshot=agent_soul,
+ )
+
+
+def _target(
+ *,
+ kind: AgentConfigVersionKind,
+ writable: bool,
+ version_id: str = "version-1",
+ soul: AgentSoulConfig | None = None,
+) -> AgentConfigTarget:
+ agent_soul = soul or _soul()
+ return AgentConfigTarget(
+ agent_id=AGENT,
+ version_id=version_id,
+ kind=kind,
+ writable=writable,
+ version=_version(version_id=version_id, snapshot=agent_soul),
+ agent_soul=agent_soul,
+ )
+
+
+def _zip_bytes(members: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, payload in members.items():
+ archive.writestr(name, payload)
+ return buffer.getvalue()
+
+
+ ("kind", "user_id", "version_row", "expected_writable"),
+ [
+ (AgentConfigVersionKind.SNAPSHOT, None, _version(version_id="snapshot-1"), False),
+ (AgentConfigVersionKind.DRAFT, USER, _version(version_id="draft-1"), False),
+ (AgentConfigVersionKind.BUILD_DRAFT, USER, _version(version_id="build-draft-1"), True),
+ ],
+)
+def test_resolve_target_supports_snapshot_draft_and_build_draft(
+ kind: AgentConfigVersionKind,
+ user_id: str | None,
+ version_row: SimpleNamespace,
+ expected_writable: bool,
+) -> None:
+ session = MagicMock()
+ session.scalar.side_effect = [AGENT, version_row]
+ service = AgentConfigService()
+
+ with patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)):
+ target = service.resolve_target(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id=version_row.id,
+ config_version_kind=kind,
+ user_id=user_id,
+ )
+
+ assert target.agent_id == AGENT
+ assert target.version_id == version_row.id
+ assert target.kind == kind
+ assert target.writable is expected_writable
+
+
+def test_resolve_target_requires_user_for_build_draft() -> None:
+ session = MagicMock()
+ session.scalar.side_effect = [AGENT]
+ service = AgentConfigService()
+
+ with patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)):
+ with pytest.raises(AgentConfigServiceError, match="user_id is required") as exc_info:
+ service.resolve_target(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ )
+
+ assert exc_info.value.code == "missing_user_id"
+
+
+ ("first_scalar", "expected_code"),
+ [
+ (None, "agent_not_found"),
+ (AGENT, "config_version_not_found"),
+ ],
+)
+def test_resolve_target_maps_missing_agent_and_version(first_scalar: str | None, expected_code: str) -> None:
+ session = MagicMock()
+ if first_scalar is None:
+ session.scalar.return_value = None
+ else:
+ session.scalar.side_effect = [first_scalar, None]
+ service = AgentConfigService()
+
+ with patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)):
+ with pytest.raises(AgentConfigServiceError) as exc_info:
+ service.resolve_target(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="missing",
+ config_version_kind=AgentConfigVersionKind.SNAPSHOT,
+ user_id=USER,
+ )
+
+ assert exc_info.value.code == expected_code
+
+
+def test_push_rejects_non_build_draft_writes() -> None:
+ session = MagicMock()
+ service = AgentConfigService()
+
+ with (
+ patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)),
+ patch.object(
+ service,
+ "_resolve_target_in_session",
+ return_value=_target(kind=AgentConfigVersionKind.DRAFT, writable=False),
+ ),
+ ):
+ with pytest.raises(AgentConfigServiceError, match="build drafts") as exc_info:
+ service.push(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id="draft-1",
+ config_version_kind=AgentConfigVersionKind.DRAFT,
+ payload=ConfigPushPayload(note="ignored"),
+ )
+
+ assert exc_info.value.code == "config_not_writable"
+ session.commit.assert_not_called()
+
+
+def test_push_for_console_allows_shared_draft_mutations() -> None:
+ session = MagicMock()
+ service = AgentConfigService()
+ target = _target(kind=AgentConfigVersionKind.DRAFT, writable=False, soul=_soul(config_note="before"))
+
+ with (
+ patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)),
+ patch.object(service, "_resolve_target_in_session", return_value=target),
+ ):
+ manifest = service.push_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id="draft-1",
+ config_version_kind=AgentConfigVersionKind.DRAFT,
+ payload=ConfigPushPayload(note="after"),
+ )
+
+ assert manifest["note"] == "after"
+ assert target.version.config_snapshot.config_note == "after"
+ session.commit.assert_called_once()
+
+
+def test_push_accepts_tenant_scoped_tool_file_sources_from_different_upload_owner() -> None:
+ session = MagicMock()
+ service = AgentConfigService()
+ target = _target(kind=AgentConfigVersionKind.BUILD_DRAFT, writable=True)
+ file_source = SimpleNamespace(
+ id="tool-file-file",
+ tenant_id=TENANT,
+ user_id="end-user-1",
+ size=7,
+ mimetype="text/plain",
+ file_key="file-key",
+ name="guide.txt",
+ )
+ skill_source = SimpleNamespace(
+ id="tool-file-skill",
+ tenant_id=TENANT,
+ user_id="end-user-1",
+ size=123,
+ mimetype="application/zip",
+ file_key="skill-key",
+ name="alpha.zip",
+ )
+ skill_ref = AgentConfigSkillRefConfig(
+ name="alpha",
+ description="Alpha skill",
+ file_id="normalized-skill-file",
+ size=321,
+ mime_type="application/zip",
+ )
+
+ with (
+ patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)),
+ patch.object(service, "_resolve_target_in_session", return_value=target),
+ patch.object(service, "_require_tool_file_source", side_effect=[file_source, skill_source]) as require_source,
+ patch(f"{MODULE}.storage.load_once", return_value=b"skill-archive"),
+ patch.object(service._skill_normalizer, "normalize", return_value=(skill_ref, object())),
+ ):
+ manifest = service.push(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ payload=ConfigPushPayload.model_validate(
+ {
+ "files": [{"name": "guide.txt", "file_ref": {"kind": "tool_file", "id": "tool-file-file"}}],
+ "skills": [{"name": "alpha", "file_ref": {"kind": "tool_file", "id": "tool-file-skill"}}],
+ }
+ ),
+ )
+
+ assert [call.args for call in require_source.call_args_list] == [(session,), (session,)]
+ assert [call.kwargs for call in require_source.call_args_list] == [
+ {"tenant_id": TENANT, "file_id": "tool-file-file"},
+ {"tenant_id": TENANT, "file_id": "tool-file-skill"},
+ ]
+ files = manifest["files"]
+ skills = manifest["skills"]
+ assert isinstance(files, dict)
+ assert isinstance(skills, dict)
+ assert files["items"][0]["file_id"] == "tool-file-file"
+ assert skills["items"][0]["file_id"] == "normalized-skill-file"
+ session.commit.assert_called_once()
+
+
+def test_push_file_for_console_rejects_snapshot_writes() -> None:
+ session = MagicMock()
+ service = AgentConfigService()
+
+ with (
+ patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)),
+ patch.object(
+ service,
+ "_resolve_target_in_session",
+ return_value=_target(kind=AgentConfigVersionKind.SNAPSHOT, writable=False),
+ ),
+ ):
+ with pytest.raises(AgentConfigServiceError, match="editable drafts") as exc_info:
+ service.push_file_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id="snapshot-1",
+ config_version_kind=AgentConfigVersionKind.SNAPSHOT,
+ upload_file_id="upload-1",
+ )
+
+ assert exc_info.value.code == "config_not_writable"
+
+
+def test_push_file_for_console_uses_service_owned_upload_lookup_and_naming() -> None:
+ session = MagicMock()
+ service = AgentConfigService()
+ target = _target(kind=AgentConfigVersionKind.DRAFT, writable=False)
+ upload_file = SimpleNamespace(
+ id="upload-1",
+ name="guide.txt",
+ size=7,
+ hash="sha256:abc",
+ mime_type="text/plain",
+ )
+
+ with (
+ patch(f"{MODULE}.session_factory.create_session", return_value=_session_cm(session)),
+ patch.object(service, "_resolve_target_in_session", return_value=target),
+ patch.object(service, "_require_console_upload_file_source", return_value=upload_file),
+ ):
+ response = service.push_file_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id="draft-1",
+ config_version_kind=AgentConfigVersionKind.DRAFT,
+ upload_file_id="upload-1",
+ )
+
+ assert response == {
+ "file": {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-1",
+ "size": 7,
+ "hash": "sha256:abc",
+ "mime_type": "text/plain",
+ },
+ "config_version": {
+ "id": "version-1",
+ "kind": "draft",
+ "writable": True,
+ },
+ }
+ session.commit.assert_called_once()
+
+
+def test_apply_skill_updates_rejects_non_tool_file_refs() -> None:
+ service = AgentConfigService()
+
+ with pytest.raises(AgentConfigServiceError, match="tool files") as exc_info:
+ service._apply_skill_updates(
+ MagicMock(),
+ tenant_id=TENANT,
+ user_id=USER,
+ current=[],
+ updates=[
+ ConfigPushSkillItem.model_validate(
+ {"name": "alpha", "file_ref": {"kind": "upload_file", "id": "upload-1"}}
+ )
+ ],
+ )
+
+ assert exc_info.value.code == "invalid_skill_file_ref"
+
+
+ ("error_code", "message"),
+ [
+ ("skill_name_mismatch", "skill name does not match requested config key"),
+ ("invalid_archive", "stored tool file is not a valid skill archive"),
+ ],
+)
+def test_apply_skill_updates_maps_normalizer_failures(error_code: str, message: str) -> None:
+ service = AgentConfigService()
+ tool_file = SimpleNamespace(name="alpha.zip", file_key="tool-files/alpha.zip")
+
+ with (
+ patch.object(service, "_require_tool_file_source", return_value=tool_file),
+ patch(f"{MODULE}.storage.load_once", return_value=b"bad-archive"),
+ patch.object(
+ service._skill_normalizer,
+ "normalize",
+ side_effect=SkillPackageError(error_code, message, status_code=400),
+ ),
+ ):
+ with pytest.raises(AgentConfigServiceError, match=message) as exc_info:
+ service._apply_skill_updates(
+ MagicMock(),
+ tenant_id=TENANT,
+ user_id=USER,
+ current=[],
+ updates=[
+ ConfigPushSkillItem.model_validate(
+ {"name": "alpha", "file_ref": {"kind": "tool_file", "id": "tool-file-1"}}
+ )
+ ],
+ )
+
+ assert exc_info.value.code == error_code
+
+
+def test_apply_env_text_supports_delete_comments_export_and_keeps_unmentioned_values() -> None:
+ current = [
+ AgentEnvVariableConfig(key="KEEP", name="KEEP", value="old"),
+ AgentEnvVariableConfig(key="REMOVE", name="REMOVE", value="gone"),
+ AgentEnvVariableConfig(key="UNTOUCHED", name="UNTOUCHED", value="still-here"),
+ ]
+
+ updated = AgentConfigService._apply_env_text(
+ current,
+ "# comment\nexport KEEP=new-value\nREMOVE=\nNEW='two words'\n",
+ )
+
+ values = {item.key: item.value for item in updated}
+ assert values == {
+ "KEEP": "new-value",
+ "UNTOUCHED": "still-here",
+ "NEW": "two words",
+ }
+
+
+ "archive_bytes",
+ [
+ b"not-a-zip-archive",
+ _zip_bytes({"README.md": b"missing skill md"}),
+ ],
+)
+def test_inspect_skill_maps_invalid_archives_to_service_errors(archive_bytes: bytes) -> None:
+ service = AgentConfigService()
+ target = _target(
+ kind=AgentConfigVersionKind.BUILD_DRAFT,
+ writable=True,
+ soul=_soul(config_skills=[AgentConfigSkillRefConfig(name="alpha", file_id="tool-file-1")]),
+ )
+
+ with (
+ patch.object(service, "resolve_target", return_value=target),
+ patch.object(service, "_load_tool_file_bytes", return_value=(archive_bytes, "application/zip")),
+ ):
+ with pytest.raises(AgentConfigServiceError, match="stored config skill archive is invalid") as exc_info:
+ service.inspect_skill(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ user_id=USER,
+ )
+
+ assert exc_info.value.code == "skill_archive_invalid"
+ assert exc_info.value.status_code == 500
+
+
+def test_manifest_uses_items_shape_without_download_urls() -> None:
+ target = _target(
+ kind=AgentConfigVersionKind.DRAFT,
+ writable=False,
+ soul=_soul(
+ config_skills=[AgentConfigSkillRefConfig(name="alpha", description="Alpha skill", file_id="tool-file-1")],
+ config_files=[AgentConfigFileRefConfig(name="guide.txt", file_kind="upload_file", file_id="upload-file-1")],
+ config_note="Use the guide.",
+ ),
+ )
+
+ manifest = AgentConfigService._manifest_for_target(target)
+
+ assert manifest == {
+ "agent_id": AGENT,
+ "config_version": {
+ "id": "version-1",
+ "kind": "draft",
+ "writable": True,
+ },
+ "skills": {
+ "items": [
+ {
+ "id": "alpha",
+ "name": "alpha",
+ "file_id": "tool-file-1",
+ "description": "Alpha skill",
+ "size": None,
+ "hash": None,
+ "mime_type": "application/zip",
+ }
+ ]
+ },
+ "files": {
+ "items": [
+ {
+ "id": "guide.txt",
+ "name": "guide.txt",
+ "file_id": "upload-file-1",
+ "size": None,
+ "hash": None,
+ "mime_type": None,
+ }
+ ]
+ },
+ "env_keys": [],
+ "note": "Use the guide.",
+ }
+
+
+def test_preview_skill_file_returns_text_preview() -> None:
+ service = AgentConfigService()
+ target = _target(
+ kind=AgentConfigVersionKind.BUILD_DRAFT,
+ writable=True,
+ soul=_soul(config_skills=[AgentConfigSkillRefConfig(name="alpha", file_id="tool-file-1")]),
+ )
+ archive_bytes = _zip_bytes(
+ {
+ "SKILL.md": b"# Alpha\n",
+ "references/guide.md": b"hello world",
+ }
+ )
+
+ with (
+ patch.object(service, "resolve_target", return_value=target),
+ patch.object(service, "_load_tool_file_bytes", return_value=(archive_bytes, "application/zip")),
+ ):
+ preview = service.preview_skill_file(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ path="references/guide.md",
+ user_id=USER,
+ )
+
+ assert preview == {
+ "path": "references/guide.md",
+ "size": 11,
+ "truncated": False,
+ "binary": False,
+ "text": "hello world",
+ }
+
+
+def test_preview_skill_file_marks_binary_and_truncated_payloads() -> None:
+ service = AgentConfigService()
+ target = _target(
+ kind=AgentConfigVersionKind.BUILD_DRAFT,
+ writable=True,
+ soul=_soul(config_skills=[AgentConfigSkillRefConfig(name="alpha", file_id="tool-file-1")]),
+ )
+ archive_bytes = _zip_bytes(
+ {
+ "SKILL.md": b"# Alpha\n",
+ "bin/data.bin": b"\x00" + (b"x" * (AgentConfigService.PREVIEW_MAX_BYTES + 10)),
+ }
+ )
+
+ with (
+ patch.object(service, "resolve_target", return_value=target),
+ patch.object(service, "_load_tool_file_bytes", return_value=(archive_bytes, "application/zip")),
+ ):
+ preview = service.preview_skill_file(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ path="bin/data.bin",
+ user_id=USER,
+ )
+
+ assert preview == {
+ "path": "bin/data.bin",
+ "size": AgentConfigService.PREVIEW_MAX_BYTES + 11,
+ "truncated": True,
+ "binary": True,
+ "text": None,
+ }
+
+
+def test_resolve_skill_file_member_path_requires_existing_member() -> None:
+ service = AgentConfigService()
+ target = _target(
+ kind=AgentConfigVersionKind.BUILD_DRAFT,
+ writable=True,
+ soul=_soul(config_skills=[AgentConfigSkillRefConfig(name="alpha", file_id="tool-file-1")]),
+ )
+ archive_bytes = _zip_bytes(
+ {
+ "SKILL.md": b"# Alpha\n",
+ "references/guide.md": b"hello world",
+ }
+ )
+
+ with (
+ patch.object(service, "resolve_target", return_value=target),
+ patch.object(service, "_load_tool_file_bytes", return_value=(archive_bytes, "application/zip")),
+ ):
+ assert (
+ service.resolve_skill_file_member_path(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ path="references/guide.md",
+ user_id=USER,
+ )
+ == "references/guide.md"
+ )
+
+ with pytest.raises(AgentConfigServiceError, match="config skill file not found") as exc_info:
+ service.resolve_skill_file_member_path(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ path="references/missing.md",
+ user_id=USER,
+ )
+
+ assert exc_info.value.code == "config_skill_file_not_found"
+ assert exc_info.value.status_code == 404
+
+
+def test_download_url_helpers_use_shared_url_resolution() -> None:
+ service = AgentConfigService()
+ target = _target(
+ kind=AgentConfigVersionKind.BUILD_DRAFT,
+ writable=True,
+ soul=_soul(
+ config_skills=[AgentConfigSkillRefConfig(name="alpha", file_id="tool-file-1")],
+ config_files=[AgentConfigFileRefConfig(name="guide.txt", file_kind="upload_file", file_id="upload-file-1")],
+ ),
+ )
+
+ with (
+ patch.object(service, "resolve_target", return_value=target),
+ patch.object(
+ service,
+ "_resolve_download_url",
+ side_effect=["https://example.com/alpha.zip", "https://example.com/guide.txt"],
+ ),
+ ):
+ assert (
+ service.download_skill_url(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="alpha",
+ user_id=USER,
+ )
+ == "https://example.com/alpha.zip"
+ )
+ assert (
+ service.download_file_url(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ config_version_id="build-draft-1",
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT,
+ name="guide.txt",
+ user_id=USER,
+ )
+ == "https://example.com/guide.txt"
+ )
diff --git a/api/tests/unit_tests/services/test_agent_tool_inner_service.py b/api/tests/unit_tests/services/test_agent_tool_inner_service.py
new file mode 100644
index 00000000000..61049d29e9e
--- /dev/null
+++ b/api/tests/unit_tests/services/test_agent_tool_inner_service.py
@@ -0,0 +1,166 @@
+"""Unit tests for the Agent tool inner invoke service."""
+
+from collections.abc import Generator
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from core.tools.entities.tool_entities import ToolInvokeMessage, ToolProviderType
+from core.tools.errors import (
+ ToolInvokeError,
+ ToolParameterValidationError,
+ ToolProviderCredentialValidationError,
+ ToolProviderNotFoundError,
+)
+from services.agent_tool_inner_service import AgentToolInnerService
+from services.entities.agent_tool_inner import AgentToolInvokeRequest
+from services.errors.agent_tool_inner import AgentToolInnerServiceError
+
+
+def _request() -> AgentToolInvokeRequest:
+ return AgentToolInvokeRequest.model_validate(
+ {
+ "caller": {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "user_from": "account",
+ "app_id": "app-1",
+ "invoke_from": "service-api",
+ "conversation_id": "conversation-1",
+ "workflow_id": "workflow-1",
+ "workflow_run_id": "workflow-run-1",
+ "node_id": "node-1",
+ "node_execution_id": "node-exec-1",
+ "agent_id": "agent-1",
+ "agent_config_version_id": "snapshot-1",
+ },
+ "tool": {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/search/search",
+ "tool_name": "search",
+ "credential_id": "credential-1",
+ "tool_parameters": {"query": "dify"},
+ "runtime_parameters": {"region": "us"},
+ },
+ }
+ )
+
+
+def _messages() -> Generator[ToolInvokeMessage, None, None]:
+ yield ToolInvokeMessage(
+ type=ToolInvokeMessage.MessageType.TEXT,
+ message=ToolInvokeMessage.TextMessage(text="ok"),
+ )
+
+
+def test_invoke_uses_agent_tool_runtime_and_returns_observation() -> None:
+ fake_tool = MagicMock()
+ fake_app = MagicMock(id="app-1", tenant_id="tenant-1")
+ session = MagicMock()
+ session.get.return_value = fake_app
+
+ with (
+ patch(
+ "services.agent_tool_inner_service.ToolManager.get_agent_tool_runtime",
+ return_value=fake_tool,
+ ) as mock_get_runtime,
+ patch("services.agent_tool_inner_service.ToolEngine.generic_invoke", return_value=_messages()) as mock_invoke,
+ patch(
+ "services.agent_tool_inner_service.ToolFileMessageTransformer.transform_tool_invoke_messages",
+ side_effect=lambda messages, **_kwargs: messages,
+ ),
+ ):
+ response = AgentToolInnerService().invoke(_request(), session=session)
+
+ assert response.observation == "ok"
+ assert response.metadata == {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/search/search",
+ "tool_name": "search",
+ }
+ agent_tool = mock_get_runtime.call_args.kwargs["agent_tool"]
+ assert agent_tool.provider_type is ToolProviderType.PLUGIN
+ assert agent_tool.tool_parameters == {"region": "us"}
+ mock_invoke.assert_called_once()
+
+
+def test_invoke_raises_app_not_found_when_session_has_no_app() -> None:
+ session = MagicMock()
+ session.get.return_value = None
+
+ with pytest.raises(AgentToolInnerServiceError) as exc_info:
+ AgentToolInnerService().invoke(_request(), session=session)
+
+ assert exc_info.value.error_code == "app_not_found"
+ assert exc_info.value.status_code == 404
+ assert exc_info.value.description == "App not found."
+
+
+def test_invoke_raises_app_tenant_mismatch_when_app_belongs_to_other_tenant() -> None:
+ fake_app = MagicMock(id="app-1", tenant_id="tenant-2")
+ session = MagicMock()
+ session.get.return_value = fake_app
+
+ with pytest.raises(AgentToolInnerServiceError) as exc_info:
+ AgentToolInnerService().invoke(_request(), session=session)
+
+ assert exc_info.value.error_code == "app_tenant_mismatch"
+ assert exc_info.value.status_code == 403
+ assert exc_info.value.description == "App does not belong to the caller tenant."
+
+
+def test_invoke_maps_tool_runtime_app_not_found_value_error_to_specific_error_code() -> None:
+ fake_tool = MagicMock()
+ fake_app = MagicMock(id="app-1", tenant_id="tenant-1")
+ session = MagicMock()
+ session.get.return_value = fake_app
+
+ with (
+ patch("services.agent_tool_inner_service.ToolManager.get_agent_tool_runtime", return_value=fake_tool),
+ patch("services.agent_tool_inner_service.ToolEngine.generic_invoke", side_effect=ValueError("app not found")),
+ ):
+ with pytest.raises(AgentToolInnerServiceError) as exc_info:
+ AgentToolInnerService().invoke(_request(), session=session)
+
+ assert exc_info.value.error_code == "app_not_found"
+ assert exc_info.value.status_code == 404
+ assert exc_info.value.description == "App not found."
+
+
+def test_invoke_maps_tool_invoke_error_without_private_tool_engine_helper() -> None:
+ fake_tool = MagicMock()
+ fake_app = MagicMock(id="app-1", tenant_id="tenant-1")
+ session = MagicMock()
+ session.get.return_value = fake_app
+
+ with (
+ patch("services.agent_tool_inner_service.ToolManager.get_agent_tool_runtime", return_value=fake_tool),
+ patch(
+ "services.agent_tool_inner_service.ToolEngine.generic_invoke",
+ side_effect=ToolInvokeError("workflow crashed"),
+ ),
+ ):
+ with pytest.raises(AgentToolInnerServiceError) as exc_info:
+ AgentToolInnerService().invoke(_request(), session=session)
+
+ assert exc_info.value.error_code == "agent_tool_invoke_failed"
+
+
+ ("error", "expected_code"),
+ [
+ (ToolProviderNotFoundError("provider gone"), "agent_tool_declaration_not_found"),
+ (ToolProviderCredentialValidationError("credential invalid"), "agent_tool_credential_invalid"),
+ (ToolParameterValidationError("query is required"), "tool_parameters_invalid"),
+ ],
+)
+def test_invoke_maps_runtime_lookup_errors_to_service_error_codes(error: Exception, expected_code: str) -> None:
+ fake_app = MagicMock(id="app-1", tenant_id="tenant-1")
+ session = MagicMock()
+ session.get.return_value = fake_app
+
+ with patch("services.agent_tool_inner_service.ToolManager.get_agent_tool_runtime", side_effect=error):
+ with pytest.raises(AgentToolInnerServiceError) as exc_info:
+ AgentToolInnerService().invoke(_request(), session=session)
+
+ assert exc_info.value.error_code == expected_code
diff --git a/api/tests/unit_tests/services/test_app_generate_service.py b/api/tests/unit_tests/services/test_app_generate_service.py
index 216c5d9db65..f34afb243eb 100644
--- a/api/tests/unit_tests/services/test_app_generate_service.py
+++ b/api/tests/unit_tests/services/test_app_generate_service.py
@@ -306,6 +306,22 @@ class TestGenerate:
assert result == {"result": "chat"}
gen_spy.assert_called_once()
+ def test_stateless_agent_mode(self, mocker: MockerFixture):
+ gen_spy = mocker.patch(
+ "services.app_generate_service.AgentAppGenerator.generate_stateless",
+ return_value={"result": "stateless-agent"},
+ )
+
+ result = AppGenerateService.generate_stateless_agent_app(
+ app_model=_make_app(AppMode.AGENT),
+ user=_make_user(),
+ args={"inputs": {}},
+ invoke_from=InvokeFrom.SERVICE_API,
+ )
+
+ assert result == {"result": "stateless-agent"}
+ gen_spy.assert_called_once()
+
# -- ADVANCED_CHAT blocking ---------------------------------------------
def test_advanced_chat_blocking(self, mocker: MockerFixture):
workflow = _make_workflow()
@@ -550,7 +566,136 @@ class TestGenerateBilling:
streaming=False,
)
# exit is called in finally block for non-streaming
- assert len(exit_calls) >= 1
+ assert exit_calls == ["dummy-request-id"]
+
+ def test_stateless_agent_app_uses_billing_and_rate_limit_guardrails(
+ self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch
+ ):
+ monkeypatch.setattr(ags_module.dify_config, "BILLING_ENABLED", True)
+ quota_charge = MagicMock()
+ reserve_mock = mocker.patch(
+ "services.app_generate_service.QuotaService.reserve",
+ return_value=quota_charge,
+ )
+ exit_calls: list[str] = []
+
+ class _TrackingRateLimit(_DummyRateLimit):
+ def exit(self, request_id: str) -> None:
+ exit_calls.append(request_id)
+
+ mocker.patch("services.app_generate_service.RateLimit", _TrackingRateLimit)
+ gen_spy = mocker.patch(
+ "services.app_generate_service.AgentAppGenerator.generate_stateless",
+ return_value={"ok": True},
+ )
+
+ result = AppGenerateService.generate_stateless_agent_app(
+ app_model=_make_app(AppMode.AGENT),
+ user=_make_user(),
+ args={"inputs": {}},
+ invoke_from=InvokeFrom.SERVICE_API,
+ )
+
+ assert result == {"ok": True}
+ reserve_mock.assert_called_once_with(QuotaType.WORKFLOW, "tenant-id")
+ quota_charge.commit.assert_called_once()
+ assert exit_calls == ["dummy-request-id"]
+ gen_spy.assert_called_once()
+
+ def test_stateless_agent_app_failure_refunds_quota_and_exits_once(
+ self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch
+ ):
+ monkeypatch.setattr(ags_module.dify_config, "BILLING_ENABLED", True)
+ quota_charge = MagicMock()
+ mocker.patch(
+ "services.app_generate_service.QuotaService.reserve",
+ return_value=quota_charge,
+ )
+ exit_calls: list[str] = []
+
+ class _TrackingRateLimit(_DummyRateLimit):
+ def exit(self, request_id: str) -> None:
+ exit_calls.append(request_id)
+
+ mocker.patch("services.app_generate_service.RateLimit", _TrackingRateLimit)
+ mocker.patch(
+ "services.app_generate_service.AgentAppGenerator.generate_stateless",
+ side_effect=RuntimeError("boom"),
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ AppGenerateService.generate_stateless_agent_app(
+ app_model=_make_app(AppMode.AGENT),
+ user=_make_user(),
+ args={"inputs": {}},
+ invoke_from=InvokeFrom.SERVICE_API,
+ )
+
+ quota_charge.commit.assert_called_once()
+ quota_charge.refund.assert_called_once()
+ assert exit_calls == ["dummy-request-id"]
+
+ def test_blocking_failure_exits_rate_limit_once(self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(ags_module.dify_config, "BILLING_ENABLED", True)
+ quota_charge = MagicMock()
+ mocker.patch(
+ "services.app_generate_service.QuotaService.reserve",
+ return_value=quota_charge,
+ )
+ exit_calls: list[str] = []
+
+ class _TrackingRateLimit(_DummyRateLimit):
+ def exit(self, request_id: str) -> None:
+ exit_calls.append(request_id)
+
+ mocker.patch("services.app_generate_service.RateLimit", _TrackingRateLimit)
+ mocker.patch(
+ "services.app_generate_service.CompletionAppGenerator.generate",
+ side_effect=RuntimeError("boom"),
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ AppGenerateService.generate(
+ app_model=_make_app(AppMode.COMPLETION),
+ user=_make_user(),
+ args={"inputs": {}},
+ invoke_from=InvokeFrom.SERVICE_API,
+ streaming=False,
+ )
+
+ quota_charge.refund.assert_called_once()
+ assert exit_calls == ["dummy-request-id"]
+
+ def test_streaming_failure_exits_rate_limit_once(self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(ags_module.dify_config, "BILLING_ENABLED", True)
+ quota_charge = MagicMock()
+ mocker.patch(
+ "services.app_generate_service.QuotaService.reserve",
+ return_value=quota_charge,
+ )
+ exit_calls: list[str] = []
+
+ class _TrackingRateLimit(_DummyRateLimit):
+ def exit(self, request_id: str) -> None:
+ exit_calls.append(request_id)
+
+ mocker.patch("services.app_generate_service.RateLimit", _TrackingRateLimit)
+ mocker.patch(
+ "services.app_generate_service.CompletionAppGenerator.generate",
+ side_effect=RuntimeError("boom"),
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ AppGenerateService.generate(
+ app_model=_make_app(AppMode.COMPLETION),
+ user=_make_user(),
+ args={"inputs": {}},
+ invoke_from=InvokeFrom.SERVICE_API,
+ streaming=True,
+ )
+
+ quota_charge.refund.assert_called_once()
+ assert exit_calls == ["dummy-request-id"]
# ---------------------------------------------------------------------------
diff --git a/api/tests/unit_tests/tasks/test_resume_agent_app_task.py b/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
index 237b43200de..189f6c1512e 100644
--- a/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
+++ b/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock
from pytest_mock import MockerFixture
+from core.app.entities.app_invoke_entities import InvokeFrom
from models.account import Account
from models.human_input import HumanInputForm
from models.model import App, Conversation, EndUser
@@ -45,7 +46,7 @@ def _wire_db(
def test_resume_happy_path_account_user_sets_tenant_and_runs(mocker: MockerFixture):
- conversation = MagicMock(from_account_id="acct-1", from_end_user_id=None)
+ conversation = MagicMock(from_account_id="acct-1", from_end_user_id=None, invoke_from=InvokeFrom.WEB_APP)
account = MagicMock()
app = MagicMock(tenant_id="tenant-1")
_wire_db(mocker, form=_form(), app=app, conversation=conversation, account=account)
@@ -59,10 +60,11 @@ def test_resume_happy_path_account_user_sets_tenant_and_runs(mocker: MockerFixtu
assert kwargs["conversation_id"] == "conv-1"
assert kwargs["user"] is account
assert kwargs["app_model"] is app
+ assert kwargs["invoke_from"] == InvokeFrom.WEB_APP
def test_resume_end_user_path(mocker: MockerFixture):
- conversation = MagicMock(from_account_id=None, from_end_user_id="eu-1")
+ conversation = MagicMock(from_account_id=None, from_end_user_id="eu-1", invoke_from=InvokeFrom.WEB_APP)
end_user = MagicMock()
_wire_db(mocker, form=_form(), app=MagicMock(tenant_id="t"), conversation=conversation, end_user=end_user)
gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
@@ -72,6 +74,18 @@ def test_resume_end_user_path(mocker: MockerFixture):
assert gen.return_value.resume_after_form_submission.call_args.kwargs["user"] is end_user
+def test_resume_preserves_debugger_invoke_from(mocker: MockerFixture):
+ conversation = MagicMock(from_account_id="acct-1", from_end_user_id=None, invoke_from=InvokeFrom.DEBUGGER)
+ account = MagicMock()
+ app = MagicMock(tenant_id="tenant-1")
+ _wire_db(mocker, form=_form(), app=app, conversation=conversation, account=account)
+ gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
+
+ mod.resume_agent_app_execution(conversation_id="conv-1", form_id="form-1")
+
+ assert gen.return_value.resume_after_form_submission.call_args.kwargs["invoke_from"] == InvokeFrom.DEBUGGER
+
+
def test_resume_returns_when_form_missing(mocker: MockerFixture):
_wire_db(mocker, form=None)
gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
@@ -109,7 +123,7 @@ def test_resume_returns_when_conversation_missing(mocker: MockerFixture):
def test_resume_returns_when_no_user_resolvable(mocker: MockerFixture):
- conversation = MagicMock(from_account_id=None, from_end_user_id=None)
+ conversation = MagicMock(from_account_id=None, from_end_user_id=None, invoke_from=InvokeFrom.WEB_APP)
_wire_db(mocker, form=_form(), app=MagicMock(), conversation=conversation)
gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
@@ -119,7 +133,7 @@ def test_resume_returns_when_no_user_resolvable(mocker: MockerFixture):
def test_resume_returns_when_account_id_set_but_account_gone(mocker: MockerFixture):
- conversation = MagicMock(from_account_id="acct-x", from_end_user_id=None)
+ conversation = MagicMock(from_account_id="acct-x", from_end_user_id=None, invoke_from=InvokeFrom.WEB_APP)
_wire_db(mocker, form=_form(), app=MagicMock(), conversation=conversation, account=None)
gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
@@ -129,7 +143,7 @@ def test_resume_returns_when_account_id_set_but_account_gone(mocker: MockerFixtu
def test_resume_swallows_generator_exception(mocker: MockerFixture):
- conversation = MagicMock(from_account_id="acct-1", from_end_user_id=None)
+ conversation = MagicMock(from_account_id="acct-1", from_end_user_id=None, invoke_from=InvokeFrom.WEB_APP)
_wire_db(mocker, form=_form(), app=MagicMock(tenant_id="t"), conversation=conversation, account=MagicMock())
gen = mocker.patch(f"{MODULE}.AgentAppGenerator")
gen.return_value.resume_after_form_submission.side_effect = RuntimeError("boom")
diff --git a/api/uv.lock b/api/uv.lock
index dfdbc7343c9..b53c89bf5a8 100644
--- a/api/uv.lock
+++ b/api/uv.lock
@@ -1302,11 +1302,11 @@ requires-dist = [
{ name = "logfire", extras = ["fastapi", "httpx", "redis"], marker = "extra == 'server'", specifier = ">=4.37.0,<5.0.0" },
{ name = "protobuf", marker = "extra == 'grpc'", specifier = ">=6.33.5,<7.0.0" },
{ name = "pydantic", specifier = ">=2.12.5,<2.13" },
- { name = "pydantic-ai-slim", specifier = ">=1.85.1,<2.0.0" },
+ { name = "pydantic-ai-slim", specifier = ">=1.102.0,<2.0.0" },
{ name = "pydantic-ai-slim", extras = ["anthropic", "google", "openai"], marker = "extra == 'server'", specifier = ">=1.85.1,<2.0.0" },
{ name = "pydantic-settings", marker = "extra == 'server'", specifier = ">=2.12.0,<3.0.0" },
{ name = "redis", marker = "extra == 'server'", specifier = ">=7.4.0,<8.0.0" },
- { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.1" },
+ { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.3.0" },
{ name = "typer", specifier = ">=0.16.1,<0.17" },
{ name = "typing-extensions", specifier = ">=4.12.2,<5.0.0" },
{ name = "uvicorn", extras = ["standard"], marker = "extra == 'server'", specifier = "==0.46.0" },
@@ -2650,15 +2650,15 @@ wheels = [
[[package]]
name = "genai-prices"
-version = "0.0.59"
+version = "0.0.67"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "httpx" },
+ { name = "httpx2" },
{ name = "pydantic" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/cd/c8/b61a028b8d8ee286ffab3f9b9f1c9229087184e7d543cea4e349e11375b0/genai_prices-0.0.59.tar.gz", hash = "sha256:3e1c7dcd9b38163589c8cf4a9bcfd286c52ea57a3becdc062a2cbaa8295b08c4", size = 67406, upload-time = "2026-05-07T12:08:40.475Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/17/9e/f96ad08d62f7bd33a5b24e65d4eb220569714b9a2a8813ada2e1fa47b4dd/genai_prices-0.0.67.tar.gz", hash = "sha256:54e07eb6541fda377187a471c5dba21a81b439c57f8dc44d89db3103c29ca343", size = 80015, upload-time = "2026-06-24T20:16:23.661Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/11/f9/4693c127f9fab0a8d39c47c198e378ecafcb043463e6dd73df205eacbc13/genai_prices-0.0.59-py3-none-any.whl", hash = "sha256:88fd8818e6807374e5a5c03f293b574ade5f18a3060622080cdd94a03cf43115", size = 70509, upload-time = "2026-05-07T12:08:39.075Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/05/d1ca6b960a3305f86d1c5f4274f2ddf8c94611ec7edc436a01cd38a01742/genai_prices-0.0.67-py3-none-any.whl", hash = "sha256:08977f1e83b4132abcfc60dabf21ff13c2d25958afb9199e59c4407bf5c9ed3f", size = 82495, upload-time = "2026-06-24T20:16:22.4Z" },
]
[[package]]
@@ -3278,6 +3278,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
+[[package]]
+name = "httpcore2"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "h11" },
+ { name = "truststore" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e6/34/18f1c596e677962f040284246f393b10a1f8ce440b3a7e69c637d0f1c7ad/httpcore2-2.3.0.tar.gz", hash = "sha256:07327e251560960eea8e969d92d4c6a325feb13cca39e25340731336c3baf924", size = 64300, upload-time = "2026-06-01T13:15:02.998Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c2/dd/3357218c69360d1cecc196c230c9a1d5c9afd5dba362056e23e60a5e64e5/httpcore2-2.3.0-py3-none-any.whl", hash = "sha256:477e9e334f74e5240dcac002e890580f36a57d40ff0fb14cc9655731d23b8415", size = 80024, upload-time = "2026-06-01T13:15:00.001Z" },
+]
+
[[package]]
name = "httplib2"
version = "0.31.0"
@@ -3337,6 +3350,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" },
]
+[[package]]
+name = "httpx2"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "httpcore2" },
+ { name = "idna" },
+ { name = "truststore" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9f/9a/cca0b9145f13d8ae34b885ae28d403a1469a433abc78e0f94f4ce94e650b/httpx2-2.3.0.tar.gz", hash = "sha256:227e7c41d95a76d4077a52640564132777215fc3394e07b66a3116c33d668fa9", size = 81115, upload-time = "2026-06-01T13:15:04.324Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/87/ce/ae2911859847f9ba1d6b23027e53481cbeb50b93234f355a968d300ca2cb/httpx2-2.3.0-py3-none-any.whl", hash = "sha256:6f393663bdf6dbe7fe90118e3eb5b2bd024a675cae0390ac08cec9198812d8b7", size = 74538, upload-time = "2026-06-01T13:15:01.566Z" },
+]
+
[[package]]
name = "huggingface-hub"
version = "1.6.0"
@@ -5153,7 +5181,7 @@ wheels = [
[[package]]
name = "pydantic-ai-slim"
-version = "1.94.0"
+version = "1.107.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "genai-prices" },
@@ -5164,9 +5192,9 @@ dependencies = [
{ name = "pydantic-graph" },
{ name = "typing-inspection" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/23/0b/ce4992e0e29ba81ba48d5bba955c53b72e2cda3636f9b6417386ae7e45f7/pydantic_ai_slim-1.94.0.tar.gz", hash = "sha256:7d7b1d6aec4d0fd31533a4ef5848863e8513ec75e82910296247a08b737aa828", size = 640338, upload-time = "2026-05-12T07:03:55.486Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/4c/26/ced63dfaabbc77f3beb86d59689cdea748e7ccffb6b419dbaf4780f211e8/pydantic_ai_slim-1.107.0.tar.gz", hash = "sha256:4616f689a92fcfecfecf2a7af27aca22f139a873cf6d7a8929eaeee9c0eedbb4", size = 779902, upload-time = "2026-06-10T14:53:10.574Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/e3/dd/b104641c2af7044a788b1071159679aa755e5c9281f110fdc54b4729117b/pydantic_ai_slim-1.94.0-py3-none-any.whl", hash = "sha256:f47cf89c61ef45a48dd575a8b32707edfec2b33ef7af80aa069bde1ce3fb6795", size = 805546, upload-time = "2026-05-12T07:03:46.535Z" },
+ { url = "https://files.pythonhosted.org/packages/15/57/71044e17f931b08cc3930bc0fe5a1e1fd37fa474ae826be004729ef1cb4a/pydantic_ai_slim-1.107.0-py3-none-any.whl", hash = "sha256:1af49bbae06a6c598f72c54d4734ba377100cac493c9a05fa8e089bebeae0da6", size = 964046, upload-time = "2026-06-10T14:53:03.333Z" },
]
[[package]]
@@ -5213,7 +5241,7 @@ wheels = [
[[package]]
name = "pydantic-graph"
-version = "1.94.0"
+version = "1.107.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
@@ -5221,9 +5249,9 @@ dependencies = [
{ name = "pydantic" },
{ name = "typing-inspection" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/79/80/c41aa5ccf7104eba172ff45e617967b0075b3fa34ab76cd3795d7d62334a/pydantic_graph-1.94.0.tar.gz", hash = "sha256:8f991c05d412c9d12d6560c1e131de48bfde12ebd27a0b196440620210f2d52c", size = 59252, upload-time = "2026-05-12T07:03:58.26Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/dd/c3/6e8c2d13b8701041f1b3eac5deb41f25d4dbfa479a190d5c6becc23f2a49/pydantic_graph-1.107.0.tar.gz", hash = "sha256:278dd89b3e33f3a2963ac949f27a53aef705c5d883a8ce5d06d23e6e3cfbd972", size = 62564, upload-time = "2026-06-10T14:53:13.366Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/8a/7e/edcc6177d89174024bca1fb85044bec4855b96f4b724a310638283dfc8c5/pydantic_graph-1.94.0-py3-none-any.whl", hash = "sha256:c6e285abbc8a55d1b65162c238006913edd1ef05e63a29401a580e51f798503e", size = 73063, upload-time = "2026-05-12T07:03:50.651Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/72/621556e3f5068400d43a0375d38e5963de30256eaa5a702aba12e82ed0ff/pydantic_graph-1.107.0-py3-none-any.whl", hash = "sha256:71add94fe7e14c703977a895117c475aae6c0b02a774a036c4d00d9a63c78b00", size = 80106, upload-time = "2026-06-10T14:53:06.543Z" },
]
[[package]]
@@ -6552,6 +6580,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b8/88/ae8320064e32679a5429a2c9ebbc05c2bf32cefb6e076f9b07f6d685a9b4/transformers-5.3.0-py3-none-any.whl", hash = "sha256:50ac8c89c3c7033444fb3f9f53138096b997ebb70d4b5e50a2e810bf12d3d29a", size = 10661827, upload-time = "2026-03-04T17:41:42.722Z" },
]
+[[package]]
+name = "truststore"
+version = "0.10.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" },
+]
+
[[package]]
name = "typer"
version = "0.16.1"
diff --git a/dify-agent/docker/local-sandbox/Dockerfile b/dify-agent/docker/local-sandbox/Dockerfile
index 2dd3dbb677a..955ed68a599 100644
--- a/dify-agent/docker/local-sandbox/Dockerfile
+++ b/dify-agent/docker/local-sandbox/Dockerfile
@@ -9,45 +9,79 @@
FROM python:3.12-slim-bookworm AS base
+ARG NODE_VERSION=22.22.1
+ARG PNPM_VERSION=11.9.0
+ARG UV_VERSION=0.8.9
+ARG DIFY_AGENT_TOOL_SPEC=.[grpc]
+ARG SHELL_SESSION_MANAGER_TOOL_SPEC=shell-session-manager
+
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
- DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive
+ DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive \
+ UV_TOOL_DIR=/opt/dify-agent-tools/envs \
+ UV_TOOL_BIN_DIR=/opt/dify-agent-tools/bin
+ENV PATH="${UV_TOOL_BIN_DIR}:${PATH}"
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
+ file \
+ git \
+ jq \
+ less \
+ openssh-client \
+ procps \
+ ripgrep \
tmux \
+ unzip \
+ xz-utils \
+ zip \
+ && node_arch="$(dpkg --print-architecture)" \
+ && case "${node_arch}" in \
+ amd64) node_arch="x64" ;; \
+ arm64) node_arch="arm64" ;; \
+ *) echo "Unsupported Node.js architecture: ${node_arch}" >&2; exit 1 ;; \
+ esac \
+ && node_dist="node-v${NODE_VERSION}-linux-${node_arch}" \
+ && curl -fsSLO "https://nodejs.org/dist/v${NODE_VERSION}/SHASUMS256.txt" \
+ && curl -fsSLO "https://nodejs.org/dist/v${NODE_VERSION}/${node_dist}.tar.xz" \
+ && grep " ${node_dist}.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
+ && tar -xJf "${node_dist}.tar.xz" -C /usr/local --strip-components=1 \
+ && rm -f SHASUMS256.txt "${node_dist}.tar.xz" \
+ && npm install --global "pnpm@${PNPM_VERSION}" \
+ && npm cache clean --force \
&& rm -rf /var/lib/apt/lists/*
-ENV UV_VERSION=0.8.9
RUN python -m pip install --no-cache-dir "uv==${UV_VERSION}"
WORKDIR /opt/dify-agent
-FROM base AS packages
+FROM base AS tools
-ENV SHELL_SESSION_MANAGER_VERSION=2.2.1
+ARG DIFY_AGENT_TOOL_SPEC
+ARG SHELL_SESSION_MANAGER_TOOL_SPEC
COPY pyproject.toml uv.lock README.md ./
COPY src ./src
-RUN uv sync --frozen --no-dev --no-editable --extra grpc \
- && uv pip install --python .venv/bin/python "shell-session-manager==${SHELL_SESSION_MANAGER_VERSION}"
+RUN uv export --frozen --no-dev --all-extras --no-emit-project --no-hashes \
+ > /tmp/dify-agent-constraints.txt \
+ && uv tool install --force --python /usr/local/bin/python --no-python-downloads \
+ --constraints /tmp/dify-agent-constraints.txt --link-mode=copy "${DIFY_AGENT_TOOL_SPEC}" \
+ && uv tool install --force --python /usr/local/bin/python --no-python-downloads \
+ --constraints /tmp/dify-agent-constraints.txt --link-mode=copy "${SHELL_SESSION_MANAGER_TOOL_SPEC}" \
+ && rm -f /tmp/dify-agent-constraints.txt
FROM base AS production
-ENV VIRTUAL_ENV=/opt/dify-agent/.venv
-ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"
-
-COPY --from=packages ${VIRTUAL_ENV} ${VIRTUAL_ENV}
+COPY --from=tools ${UV_TOOL_DIR} ${UV_TOOL_DIR}
+COPY --from=tools ${UV_TOOL_BIN_DIR} ${UV_TOOL_BIN_DIR}
-RUN ln -s ${VIRTUAL_ENV}/bin/dify-agent /usr/local/bin/dify-agent \
- && ln -s ${VIRTUAL_ENV}/bin/shellctl /usr/local/bin/shellctl \
- && useradd --create-home --shell /bin/sh dify \
+RUN useradd --create-home --shell /bin/sh dify \
&& mkdir -p /mnt/drive \
&& chown -R dify:dify /home/dify /mnt/drive
diff --git a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
index 91842f05dbc..a915031fe1d 100644
--- a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
+++ b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md
@@ -228,8 +228,14 @@ and pre-creates that directory with write access for the same user.
The provided `docker/local-sandbox/Dockerfile` installs:
- `tmux`, required by `shellctl` to manage shell jobs;
-- `shell-session-manager==2.2.1`, which provides the `shellctl` CLI/server;
+- common shell workspace tools: `git`, `openssh-client`, `jq`, `ripgrep`,
+ `unzip`, `zip`, `file`, `procps`, and `less`;
+- `shell-session-manager==2.3.0` as a standalone uv tool, which provides the
+ `shellctl` CLI/server;
- `uv`, so uv shebang scripts with PEP 723 metadata can run inside the shell
- workspace;
-- the `dify-agent` Agent Stub client CLI, including its gRPC transport extra;
+ workspace and Python CLI tools can be installed with isolated tool
+ environments;
+- `node==22.22.1` and `pnpm==11.9.0`, so JavaScript and TypeScript tooling can
+ run inside the shell workspace without per-job installation;
+- the `dify-agent[grpc]` Agent Stub client CLI as a standalone uv tool;
- a non-root default user named `dify`.
diff --git a/dify-agent/pyproject.toml b/dify-agent/pyproject.toml
index 2b0ce1dff56..1c8842dccc5 100644
--- a/dify-agent/pyproject.toml
+++ b/dify-agent/pyproject.toml
@@ -27,7 +27,7 @@ server = [
"pydantic-ai-slim[anthropic,google,openai]>=1.85.1,<2.0.0",
"pydantic-settings>=2.12.0,<3.0.0",
"redis>=7.4.0,<8.0.0",
- "shell-session-manager==2.2.1",
+ "shell-session-manager==2.3.0",
"uvicorn[standard]==0.46.0",
]
diff --git a/dify-agent/src/dify_agent/adapters/shell/__init__.py b/dify-agent/src/dify_agent/adapters/shell/__init__.py
index e87bb39feb7..bb655da3b9a 100644
--- a/dify-agent/src/dify_agent/adapters/shell/__init__.py
+++ b/dify-agent/src/dify_agent/adapters/shell/__init__.py
@@ -1,41 +1,30 @@
-"""Provider-agnostic shell provisioning/execution adapter for the Dify agent.
-
-The boundary protocols live in ``protocols``; the default shellctl backend in
-``shellctl``; and env-var-driven provider selection in ``config``/``factory``.
-``create_shell_provisioner`` is the recommended entry point for callers.
-"""
+"""Provider-agnostic shell adapter exports for the Dify agent."""
from dify_agent.adapters.shell.config import DEFAULT_SHELL_PROVIDER, ShellAdapterSettings
-from dify_agent.adapters.shell.factory import create_shell_provisioner
+from dify_agent.adapters.shell.factory import create_shell_provider
from dify_agent.adapters.shell.protocols import (
- ShellEnvironmentDescriptor,
- ShellExecutionResult,
- ShellExecutorProtocol,
+ CompleteShellCommandResult,
+ ShellCommandProtocol,
+ ShellCommandResult,
+ ShellCommandStatus,
ShellFileTransferProtocol,
- ShellHandle,
- ShellProvisionProtocol,
-)
-from dify_agent.adapters.shell.shellctl import (
- ShellctlEnvironmentDescriptor,
- ShellctlProvisioner,
- ShellFileTransferError,
- ShellProvisionError,
- create_default_shellctl_client_factory,
+ ShellPromptObservation,
+ ShellProviderError,
+ ShellProviderProtocol,
+ ShellResourceProtocol,
)
__all__ = [
+ "CompleteShellCommandResult",
"DEFAULT_SHELL_PROVIDER",
"ShellAdapterSettings",
- "ShellEnvironmentDescriptor",
- "ShellExecutionResult",
- "ShellExecutorProtocol",
- "ShellFileTransferError",
+ "ShellCommandProtocol",
+ "ShellCommandResult",
+ "ShellCommandStatus",
"ShellFileTransferProtocol",
- "ShellHandle",
- "ShellProvisionError",
- "ShellProvisionProtocol",
- "ShellctlEnvironmentDescriptor",
- "ShellctlProvisioner",
- "create_default_shellctl_client_factory",
- "create_shell_provisioner",
+ "ShellPromptObservation",
+ "ShellProviderError",
+ "ShellProviderProtocol",
+ "ShellResourceProtocol",
+ "create_shell_provider",
]
diff --git a/dify-agent/src/dify_agent/adapters/shell/config.py b/dify-agent/src/dify_agent/adapters/shell/config.py
index d2bd96ae348..53325270861 100644
--- a/dify-agent/src/dify_agent/adapters/shell/config.py
+++ b/dify-agent/src/dify_agent/adapters/shell/config.py
@@ -6,7 +6,7 @@ DEFAULT_SHELL_PROVIDER = "shellctl"
class ShellAdapterSettings(BaseSettings):
- """Env-backed settings used to construct a shell provisioner.
+ """Env-backed settings used to construct a shell provider.
``shellctl_auth_token`` defaults to ``None``; the factory forwards an empty
string to the shellctl client so it does not fall back to ambient process
diff --git a/dify-agent/src/dify_agent/adapters/shell/factory.py b/dify-agent/src/dify_agent/adapters/shell/factory.py
index 4de892affc8..104cdf8148b 100644
--- a/dify-agent/src/dify_agent/adapters/shell/factory.py
+++ b/dify-agent/src/dify_agent/adapters/shell/factory.py
@@ -1,21 +1,10 @@
from dify_agent.adapters.shell.config import ShellAdapterSettings
-from dify_agent.adapters.shell.protocols import ShellProvisionProtocol
-from dify_agent.adapters.shell.shellctl import (
- ShellctlEnvironmentDescriptor,
- ShellctlProvisioner,
- create_default_shellctl_client_factory,
-)
+from dify_agent.adapters.shell.protocols import ShellProviderProtocol
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
-def create_shell_provisioner(
- settings: ShellAdapterSettings | None = None,
-) -> ShellProvisionProtocol[ShellctlEnvironmentDescriptor]:
- """Return the shell provisioner selected by ``DIFY_AGENT_SHELL_PROVIDER``.
-
- Raises:
- ValueError: if the provider name is unknown, or if the ``shellctl``
- provider is selected without a non-empty ``DIFY_AGENT_SHELLCTL_ENTRYPOINT``.
- """
+def create_shell_provider(settings: ShellAdapterSettings | None = None) -> ShellProviderProtocol:
+ """Return the shell provider selected by ``DIFY_AGENT_SHELL_PROVIDER``."""
resolved = settings or ShellAdapterSettings()
provider = resolved.shell_provider.strip().lower()
match provider:
@@ -23,14 +12,12 @@ def create_shell_provisioner(
entrypoint = (resolved.shellctl_entrypoint or "").strip()
if not entrypoint:
raise ValueError("DIFY_AGENT_SHELLCTL_ENTRYPOINT is required for the 'shellctl' shell provider.")
- return ShellctlProvisioner(
- client_factory=create_default_shellctl_client_factory(
- entrypoint=entrypoint,
- token=resolved.shellctl_auth_token or "",
- ),
+ return ShellctlProvider(
+ entrypoint=entrypoint,
+ token=resolved.shellctl_auth_token or "",
)
case _:
raise ValueError(f"Unknown shell provider: {resolved.shell_provider!r}.")
-__all__ = ["create_shell_provisioner"]
+__all__ = ["create_shell_provider"]
diff --git a/dify-agent/src/dify_agent/adapters/shell/protocols.py b/dify-agent/src/dify_agent/adapters/shell/protocols.py
index 147441ccb7a..9487a202f45 100644
--- a/dify-agent/src/dify_agent/adapters/shell/protocols.py
+++ b/dify-agent/src/dify_agent/adapters/shell/protocols.py
@@ -1,128 +1,125 @@
-from typing import Protocol, TypeVar
+from __future__ import annotations
-from pydantic import BaseModel, ConfigDict, model_validator
-from typing_extensions import Self
+from dataclasses import dataclass
+from typing import Literal, Protocol
-class ShellEnvironmentDescriptor(BaseModel):
- """Minimal, serializable seed used to re-derive a provisioned environment.
+@dataclass(frozen=True, slots=True)
+class ShellCommandResult:
+ job_id: str
+ status: str
+ done: bool
+ exit_code: int | None
+ output: str
+ offset: int
+ truncated: bool
+ output_path: str | None = None
- Holds only the provider-agnostic identity needed to reattach to an existing
- shell environment across a snapshot/resume cycle — never live resources
- (clients, handles, executors). Callers persist this in their snapshot and
- pass it back to ``ShellProvisionProtocol.reattach`` to reconstruct an
- equivalent ``ShellHandle`` without allocating a new environment.
- Each provider defines its own concrete subclass carrying the fields it needs
- to reattach (e.g. workspace path + session id for shellctl). Validation runs
- at instantiation time via Pydantic so a malicious or corrupt snapshot cannot
- escape the workspace root or inject shell syntax into lifecycle commands,
- even if a future caller uses the provider directly.
- """
+@dataclass(frozen=True, slots=True)
+class ShellCommandStatus:
+ job_id: str
+ status: str
+ done: bool
+ exit_code: int | None
+ offset: int
- model_config = ConfigDict(extra="forbid", frozen=True)
- @model_validator(mode="after")
- def _run_validate(self) -> Self:
- self.validate()
- return self
+@dataclass(frozen=True, slots=True)
+class CompleteShellCommandResult:
+ job_id: str
+ status: str
+ done: bool
+ exit_code: int | None
+ output: str
+ output_complete: bool
+ incomplete_reason: Literal["output_limit", "timeout"] | None
+ offset: int
+ output_path: str | None = None
- def validate(self) -> None:
- """validate the correctness of the object.
- Advanced validations that requires remote procedure calls,
- for example access control, quota checks, should be implemented in
- provision and reattach.
+@dataclass(frozen=True, slots=True)
+class ShellPromptObservation:
+ text: str
+ output_path: str | None
+ offset: int
- """
- raise NotImplementedError
+class ShellProviderError(RuntimeError):
+ code: str | None
-DescriptorT = TypeVar("DescriptorT", bound=ShellEnvironmentDescriptor)
+ def __init__(self, message: str, *, code: str | None = None) -> None:
+ super().__init__(message)
+ self.code = code
-class ShellExecutionResult(Protocol):
- """Completed shell command result.
-
- ``stdout``/``stderr``/``exit_code`` are reserved fields. Backends that
- cannot distinguish a stream return an empty string for it, and return
- ``None`` from ``exit_code()`` when no exit status is available.
- """
-
- def stdout(self) -> str: ...
-
- def stderr(self) -> str: ...
-
- def exit_code(self) -> int | None: ...
-
- def truncated(self) -> bool: ...
-
-
-class ShellExecutorProtocol(Protocol):
- """Runs commands inside an already-provisioned shell environment.
-
- ``execute`` drains the command to completion before returning — there is no
- separate ``wait`` step. This suits the current server-side callers (sandbox
- file helpers, workspace bootstrap) that always run a script to completion.
-
- If a future use case needs to start a command, interact with its stdin, or
- interrupt it before completion, split this protocol into ``execute`` →
- ``ShellExecutionHandle`` plus ``wait`` / ``input`` / ``interrupt`` optional
- capabilities, mirroring the shape that was prototyped here before
- simplification.
- """
-
- async def execute(
+class ShellCommandProtocol(Protocol):
+ async def run(
self,
- command: str,
+ script: str,
*,
cwd: str | None = None,
env: dict[str, str] | None = None,
- ) -> ShellExecutionResult: ...
-
-
-class ShellFileTransferProtocol(Protocol):
- """Moves file bytes between the caller and a provisioned shell environment.
+ timeout: float,
+ ) -> ShellCommandResult: ...
- ``remote_path`` is interpreted by the backend relative to the provisioned
- environment (for the shellctl backend, the session workspace). Higher-level
- Dify/skill transfers are layered on top of this primitive, not implemented
- here. Implementations raise on transfer failure (missing path, decode error,
- or a non-zero transfer command).
- """
+ async def wait(
+ self,
+ job_id: str,
+ *,
+ offset: int,
+ timeout: float,
+ ) -> ShellCommandResult: ...
- async def upload(self, *, content: bytes, remote_path: str) -> None: ...
+ async def read_output(
+ self,
+ job_id: str,
+ *,
+ offset: int,
+ ) -> ShellCommandResult: ...
- async def download(self, *, remote_path: str) -> bytes: ...
+ async def input(
+ self,
+ job_id: str,
+ text: str,
+ *,
+ offset: int,
+ timeout: float,
+ ) -> ShellCommandResult: ...
+ async def interrupt(
+ self,
+ job_id: str,
+ *,
+ grace_seconds: float,
+ ) -> ShellCommandStatus: ...
-# pyrefly: ignore [variance-mismatch]
-# intended to be invariant
-class ShellHandle(Protocol[DescriptorT]):
- """Live reference to one provisioned shell environment.
+ async def tail(self, job_id: str) -> ShellCommandResult: ...
- The handle itself is not serialized. ``descriptor()`` returns the minimal
- seed needed to reconstruct an equivalent handle after a snapshot/resume.
- """
+ async def delete(
+ self,
+ job_id: str,
+ *,
+ force: bool = False,
+ grace_seconds: float | None = None,
+ ) -> None: ...
- def descriptor(self) -> DescriptorT: ...
- async def get_executor(self) -> ShellExecutorProtocol: ...
+class ShellFileTransferProtocol(Protocol):
+ async def upload(self, *, content: bytes, remote_path: str, cwd: str | None = None) -> None: ...
- async def get_file_transfer(self) -> ShellFileTransferProtocol: ...
+ async def download(self, *, remote_path: str, cwd: str | None = None) -> bytes: ...
-class ShellProvisionProtocol(Protocol[DescriptorT]):
- """Creates, reattaches to, and destroys shell environments.
+class ShellResourceProtocol(Protocol):
+ @property
+ def commands(self) -> ShellCommandProtocol: ...
- ``provision`` allocates a fresh environment; ``reattach`` rebuilds a live
- handle for an environment that already exists (from a persisted descriptor)
- without allocating a new one, so resumed runs can keep executing and
- eventually clean up. ``destroy`` tears an environment down.
- """
+ @property
+ def files(self) -> ShellFileTransferProtocol: ...
- async def provision(self) -> ShellHandle[DescriptorT]: ...
+ async def close(self) -> None: ...
- async def reattach(self, descriptor: DescriptorT) -> ShellHandle[DescriptorT]: ...
- async def destroy(self, handle: ShellHandle[DescriptorT]) -> None: ...
+class ShellProviderProtocol(Protocol):
+ async def create(self) -> ShellResourceProtocol: ...
diff --git a/dify-agent/src/dify_agent/adapters/shell/shellctl.py b/dify-agent/src/dify_agent/adapters/shell/shellctl.py
index c1f4e786284..31f2e13675f 100644
--- a/dify-agent/src/dify_agent/adapters/shell/shellctl.py
+++ b/dify-agent/src/dify_agent/adapters/shell/shellctl.py
@@ -4,87 +4,60 @@ import base64
import binascii
import logging
import re
-import secrets
+import time
+from collections.abc import Awaitable
from collections.abc import Callable
from dataclasses import dataclass
-from typing import Protocol
-
-from dify_agent.adapters.shell.protocols import ShellEnvironmentDescriptor, ShellHandle
+from typing import Protocol, TypeVar
+
+from dify_agent.adapters.shell.protocols import (
+ ShellCommandProtocol,
+ ShellCommandResult,
+ ShellCommandStatus,
+ ShellFileTransferProtocol,
+ ShellProviderError,
+ ShellProviderProtocol,
+ ShellResourceProtocol,
+)
logger = logging.getLogger(__name__)
-_WORKSPACE_ROOT = "~/workspace"
+ResultT = TypeVar("ResultT")
+
_DEFAULT_TIMEOUT_SECONDS = 30.0
-_SESSION_ID_PATTERN = re.compile(r"[0-9a-f]{7,16}")
-# Drains at most this many shellctl output windows per wait so a stuck or
-# pathologically chatty job cannot loop forever inside one wait() call.
-_MAX_OUTPUT_WINDOWS = 64
+_READ_OUTPUT_TIMEOUT_SECONDS = 0.0
_DEFAULT_TERMINATE_GRACE_SECONDS = 10.0
_FILE_TRANSFER_TIMEOUT_SECONDS = 60.0
-# Sentinels frame base64 download payloads so prompt/tmux noise around the
-# shellctl merged output stream can be stripped before decoding.
+_SHELLCTL_OUTPUT_LIMIT_BYTES = 16 * 1024
_TRANSFER_BEGIN = "<<<DIFY_SHELL_FILE_BEGIN>>>"
_TRANSFER_END = "<<<DIFY_SHELL_FILE_END>>>"
_DOWNLOAD_MISSING_EXIT_CODE = 66
-class ShellProvisionError(RuntimeError):
- """Raised when a shell environment cannot be provisioned."""
-
-
class ShellFileTransferError(RuntimeError):
- """Raised when a file cannot be uploaded to or downloaded from the workspace."""
-
-
-class ShellctlEnvironmentDescriptor(ShellEnvironmentDescriptor):
- """Shellctl-specific descriptor carrying the workspace path and session id."""
-
- workspace_cwd: str
- session_id: str
-
- def validate(self) -> None:
- if not _SESSION_ID_PATTERN.fullmatch(self.session_id):
- raise ValueError(f"Invalid session_id in reattach descriptor: {self.session_id!r}.")
- expected_workspace = f"{_WORKSPACE_ROOT}/{self.session_id}"
- if self.workspace_cwd != expected_workspace:
- raise ValueError(
- f"workspace_cwd must equal {expected_workspace!r} for session_id {self.session_id!r}, "
- f"got {self.workspace_cwd!r}."
- )
+ """Raised when a file cannot be uploaded or downloaded through shellctl."""
class ShellctlJobResult(Protocol):
- """Structural shape of one shellctl job result the adapter relies on.
-
- Mirrors the fields the adapter reads from ``shell_session_manager`` job
- results without importing the concrete type, so the merged output stream,
- paging offset, completion flag, and exit status stay duck-typed.
- """
-
job_id: str
+ status: object
done: bool
output: str
offset: int
truncated: bool
exit_code: int | None
+ output_path: str | None
class ShellctlJobStatus(Protocol):
- """Structural shape of one shellctl status-only result (no output stream).
-
- Returned by ``terminate``; carries completion and exit status plus the
- latest paging offset so the adapter can drain any remaining output.
- """
-
job_id: str
+ status: object
done: bool
offset: int
exit_code: int | None
class ShellctlClientProtocol(Protocol):
- """Boundary the shellctl adapter needs from a shell-session-manager client."""
-
async def run(
self,
script: str,
@@ -111,13 +84,21 @@ class ShellctlClientProtocol(Protocol):
timeout: float = _DEFAULT_TIMEOUT_SECONDS,
) -> ShellctlJobResult: ...
+ async def tail(self, job_id: str) -> ShellctlJobResult: ...
+
async def terminate(
self,
job_id: str,
grace_seconds: float = _DEFAULT_TERMINATE_GRACE_SECONDS,
) -> ShellctlJobStatus: ...
- async def delete(self, job_id: str, *, force: bool = False) -> object: ...
+ async def delete(
+ self,
+ job_id: str,
+ *,
+ force: bool = False,
+ grace_seconds: float | None = None,
+ ) -> object: ...
async def close(self) -> None: ...
@@ -125,127 +106,86 @@ class ShellctlClientProtocol(Protocol):
type ShellctlClientFactory = Callable[[], ShellctlClientProtocol]
-class ShellctlExecutionResult:
- """Completed shellctl command result.
-
- shellctl merges stderr into a single output stream, so ``stderr()`` is
- always empty and the merged stream is reported as ``stdout()``.
- """
-
- _stdout: str
- _stderr: str
- _exit_code: int | None
- _truncated: bool
+@dataclass(slots=True)
+class ShellctlCommands(ShellCommandProtocol):
+ client: ShellctlClientProtocol
- def __init__(
+ async def run(
self,
+ script: str,
*,
- stdout: str,
- stderr: str = "",
- exit_code: int | None,
- truncated: bool = False,
- ) -> None:
- self._stdout = stdout
- self._stderr = stderr
- self._exit_code = exit_code
- self._truncated = truncated
-
- def stdout(self) -> str:
- return self._stdout
-
- def stderr(self) -> str:
- return self._stderr
-
- def exit_code(self) -> int | None:
- return self._exit_code
-
- def truncated(self) -> bool:
- """Whether the returned ``stdout`` may be incomplete.
+ cwd: str | None = None,
+ env: dict[str, str] | None = None,
+ timeout: float,
+ ) -> ShellCommandResult:
+ return _from_job_result(await _run_client_call(self.client.run(script, cwd=cwd, env=env, timeout=timeout)))
- ``True`` means shellctl still reported more output past what was
- captured when draining stopped (its per-window ``truncated`` flag on the
- final window, e.g. the output-window cap was hit). Callers that need the
- command's *entire* output must treat a truncated result as a failure or
- re-read, rather than trusting ``stdout()`` as complete.
- """
- return self._truncated
+ async def wait(
+ self,
+ job_id: str,
+ *,
+ offset: int,
+ timeout: float,
+ ) -> ShellCommandResult:
+ return _from_job_result(await _run_client_call(self.client.wait(job_id, offset=offset, timeout=timeout)))
+ async def read_output(
+ self,
+ job_id: str,
+ *,
+ offset: int,
+ ) -> ShellCommandResult:
+ return _from_job_result(
+ await _run_client_call(self.client.wait(job_id, offset=offset, timeout=_READ_OUTPUT_TIMEOUT_SECONDS))
+ )
-@dataclass(slots=True)
-class ShellctlExecutor:
- """Runs commands in one provisioned shellctl workspace.
+ async def input(
+ self,
+ job_id: str,
+ text: str,
+ *,
+ offset: int,
+ timeout: float,
+ ) -> ShellCommandResult:
+ return _from_job_result(await _run_client_call(self.client.input(job_id, text, offset=offset, timeout=timeout)))
- Conforms structurally to ``ShellExecutorProtocol``. ``execute`` drains the
- command to completion (accumulating shellctl's paged output windows) and
- best-effort deletes the finished job before returning. The executor is
- single-environment and is not safe to share across workspaces.
- """
+ async def interrupt(
+ self,
+ job_id: str,
+ *,
+ grace_seconds: float,
+ ) -> ShellCommandStatus:
+ return _from_job_status(await _run_client_call(self.client.terminate(job_id, grace_seconds=grace_seconds)))
- client: ShellctlClientProtocol
- workspace_cwd: str
- timeout: float = _DEFAULT_TIMEOUT_SECONDS
+ async def tail(self, job_id: str) -> ShellCommandResult:
+ return _from_job_result(await _run_client_call(self.client.tail(job_id)))
- async def execute(
+ async def delete(
self,
- command: str,
+ job_id: str,
*,
- cwd: str | None = None,
- env: dict[str, str] | None = None,
- ) -> ShellctlExecutionResult:
- result = await self.client.run(
- command,
- cwd=cwd if cwd is not None else self.workspace_cwd,
- env=env,
- timeout=self.timeout,
- )
- output_parts = [result.output]
- done = result.done
- truncated = result.truncated
- offset = result.offset
- exit_code = result.exit_code
- job_id = result.job_id
- windows = 1
- while (not done or truncated) and windows < _MAX_OUTPUT_WINDOWS:
- result = await self.client.wait(job_id, offset=offset, timeout=self.timeout)
- output_parts.append(result.output)
- done = result.done
- truncated = result.truncated
- offset = result.offset
- exit_code = result.exit_code
- windows += 1
- if done:
- await _delete_job_best_effort(self.client, job_id)
- return ShellctlExecutionResult(
- stdout="".join(output_parts),
- exit_code=exit_code,
- truncated=truncated,
- )
+ force: bool = False,
+ grace_seconds: float | None = None,
+ ) -> None:
+ try:
+ _ = await self.client.delete(job_id, force=force, grace_seconds=grace_seconds)
+ except RuntimeError as exc:
+ if getattr(exc, "code", None) == "job_not_found":
+ return
+ raise _map_error(exc) from exc
@dataclass(slots=True)
-class ShellctlFileTransfer:
- """Moves file bytes in and out of one provisioned shellctl workspace.
-
- Conforms structurally to ``ShellFileTransferProtocol``. Transfers run as
- workspace-scoped shellctl jobs over the merged text channel: uploads embed
- base64 in the command and pipe it through ``base64 -d``; downloads emit the
- file's base64 framed by sentinels so prompt/tmux noise can be stripped
- before decoding. Because the encoded payload is embedded in the upload
- command, very large files can exceed the shell argument limit; this
- primitive targets ordinary control-plane file sizes, not bulk binary
- transfer.
- """
-
+class ShellctlFileTransfer(ShellFileTransferProtocol):
client: ShellctlClientProtocol
- workspace_cwd: str
timeout: float = _FILE_TRANSFER_TIMEOUT_SECONDS
- async def upload(self, *, content: bytes, remote_path: str) -> None:
+ async def upload(self, *, content: bytes, remote_path: str, cwd: str | None = None) -> None:
encoded = base64.b64encode(content).decode("ascii")
completed = await _run_to_completion(
self.client,
_upload_script(remote_path=remote_path, encoded=encoded),
- cwd=self.workspace_cwd,
+ cwd=cwd,
timeout=self.timeout,
)
if completed.exit_code != 0:
@@ -254,133 +194,126 @@ class ShellctlFileTransfer:
f"output={_output_tail(completed.output)!r}"
)
- async def download(self, *, remote_path: str) -> bytes:
+ async def download(self, *, remote_path: str, cwd: str | None = None) -> bytes:
completed = await _run_to_completion(
self.client,
_download_script(remote_path=remote_path),
- cwd=self.workspace_cwd,
+ cwd=cwd,
timeout=self.timeout,
)
if completed.exit_code == _DOWNLOAD_MISSING_EXIT_CODE:
- raise ShellFileTransferError(f"File not found in workspace: {remote_path!r}.")
+ raise ShellFileTransferError(f"Remote path not found: {remote_path!r}.")
if completed.exit_code != 0:
raise ShellFileTransferError(
f"Failed to download {remote_path!r}: exit_code={completed.exit_code}, "
f"output={_output_tail(completed.output)!r}"
)
- framed = _extract_framed_payload(completed.output)
+ encoded = _extract_transfer_payload(completed.output)
try:
- return base64.b64decode("".join(framed.split()), validate=True)
- except (binascii.Error, ValueError) as exc:
- raise ShellFileTransferError(f"Failed to decode downloaded file {remote_path!r}: {exc}") from exc
+ return base64.b64decode(encoded.encode("ascii"), validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise ShellFileTransferError(f"Downloaded payload for {remote_path!r} was not valid base64.") from exc
@dataclass(slots=True)
-class ShellctlHandle:
- """Live reference to one provisioned shellctl workspace.
-
- Conforms structurally to ``ShellHandle``. Owns the shellctl ``client`` and
- the allocated ``workspace_cwd`` until the provisioner destroys it.
- ``get_executor`` returns a fresh executor bound to this workspace each call.
- """
-
+class ShellctlResource(ShellResourceProtocol):
client: ShellctlClientProtocol
- workspace_cwd: str
- session_id: str
-
- def descriptor(self) -> ShellctlEnvironmentDescriptor:
- return ShellctlEnvironmentDescriptor(workspace_cwd=self.workspace_cwd, session_id=self.session_id)
+ commands: ShellCommandProtocol
+ files: ShellFileTransferProtocol
- async def get_executor(self) -> ShellctlExecutor:
- return ShellctlExecutor(client=self.client, workspace_cwd=self.workspace_cwd)
-
- async def get_file_transfer(self) -> ShellctlFileTransfer:
- return ShellctlFileTransfer(client=self.client, workspace_cwd=self.workspace_cwd)
+ async def close(self) -> None:
+ try:
+ await self.client.close()
+ except RuntimeError as exc:
+ raise _map_error(exc) from exc
@dataclass(slots=True)
-class ShellctlProvisioner:
- """Provisions isolated shellctl workspaces, one client per environment.
-
- Conforms structurally to ``ShellProvisionProtocol``.
- """
-
- client_factory: ShellctlClientFactory
- timeout: float = _DEFAULT_TIMEOUT_SECONDS
-
- async def provision(self) -> ShellctlHandle:
- client = self.client_factory()
- session_id = _generate_session_id()
- workspace_cwd = f"{_WORKSPACE_ROOT}/{session_id}"
- try:
- completed = await _run_to_completion(client, _mkdir_script(session_id), cwd=None, timeout=self.timeout)
- except BaseException:
- await client.close()
- raise
- if completed.exit_code != 0:
- await client.close()
- raise ShellProvisionError(
- f"Failed to create shell workspace {workspace_cwd}: mkdir exited with code {completed.exit_code}."
- )
- return ShellctlHandle(client=client, workspace_cwd=workspace_cwd, session_id=session_id)
-
- async def reattach(self, descriptor: ShellctlEnvironmentDescriptor) -> ShellctlHandle:
- """Rebuild a live handle for an existing workspace without re-allocating it.
-
- Opens a fresh shellctl client and points it at the workspace recorded in
- ``descriptor``. No ``mkdir`` is issued: the workspace is assumed to still
- exist from the original ``provision``. Used on snapshot resume so a run
- can keep executing in and eventually clean up its prior workspace.
- """
- client = self.client_factory()
- return ShellctlHandle(
+class ShellctlProvider(ShellProviderProtocol):
+ entrypoint: str
+ token: str
+ output_limit: int = _SHELLCTL_OUTPUT_LIMIT_BYTES
+ client_factory: ShellctlClientFactory | None = None
+
+ async def create(self) -> ShellctlResource:
+ client = (
+ self.client_factory()
+ if self.client_factory is not None
+ else create_default_shellctl_client_factory(
+ entrypoint=self.entrypoint,
+ token=self.token,
+ output_limit=self.output_limit,
+ )()
+ )
+ return ShellctlResource(
client=client,
- workspace_cwd=descriptor.workspace_cwd,
- session_id=descriptor.session_id,
+ commands=ShellctlCommands(client=client),
+ files=ShellctlFileTransfer(client=client),
)
- async def destroy(self, handle: ShellHandle[ShellctlEnvironmentDescriptor]) -> None:
- if not isinstance(handle, ShellctlHandle):
- raise TypeError("ShellctlProvisioner can only destroy handles it provisioned.")
- try:
- completed = await _run_to_completion(
- handle.client, _cleanup_script(handle.session_id), cwd=None, timeout=self.timeout
- )
- if completed.exit_code != 0:
- logger.warning(
- "Shell workspace cleanup for session %s exited with code %s.",
- handle.session_id,
- completed.exit_code,
- )
- except (RuntimeError, ValueError) as exc:
- logger.warning("Failed to remove shell workspace for session %s: %s", handle.session_id, exc)
- finally:
- await handle.client.close()
-
-
-def create_default_shellctl_client_factory(*, entrypoint: str, token: str) -> ShellctlClientFactory:
- """Return a factory that builds a real shell-session-manager shellctl client.
-
- The concrete client is imported lazily so importing this module does not
- require the private ``shell-session-manager`` package. An explicit empty
- ``token`` is forwarded as-is to avoid the client falling back to ambient
- process credentials.
- """
+def create_default_shellctl_client_factory(
+ *,
+ entrypoint: str,
+ token: str,
+ output_limit: int = _SHELLCTL_OUTPUT_LIMIT_BYTES,
+) -> ShellctlClientFactory:
def factory() -> ShellctlClientProtocol:
from shell_session_manager.shellctl.client import ShellctlClient
- return ShellctlClient(entrypoint, token=token)
+ return ShellctlClient(entrypoint, token=token, output_limit=output_limit)
return factory
-@dataclass(slots=True)
-class _CompletedJob:
- """Drained result of one internal shellctl job: merged output plus exit code."""
-
- output: str
+@dataclass(frozen=True, slots=True)
+class _CompletedShellctlJob:
+ job_id: str
exit_code: int | None
+ output: str
+
+
+async def _run_client_call(awaitable: Awaitable[ResultT]) -> ResultT:
+ try:
+ return await awaitable
+ except RuntimeError as exc:
+ raise _map_error(exc) from exc
+
+
+def _map_error(exc: RuntimeError) -> ShellProviderError:
+ return ShellProviderError(str(exc), code=getattr(exc, "code", None))
+
+
+def _from_job_result(result: ShellctlJobResult) -> ShellCommandResult:
+ return ShellCommandResult(
+ job_id=result.job_id,
+ status=_status_name(result.status),
+ done=result.done,
+ exit_code=result.exit_code,
+ output=result.output,
+ offset=result.offset,
+ truncated=result.truncated,
+ output_path=result.output_path or None,
+ )
+
+
+def _from_job_status(result: ShellctlJobStatus) -> ShellCommandStatus:
+ return ShellCommandStatus(
+ job_id=result.job_id,
+ status=_status_name(result.status),
+ done=result.done,
+ exit_code=result.exit_code,
+ offset=result.offset,
+ )
+
+
+def _status_name(status: object) -> str:
+ value = getattr(status, "value", None)
+ if isinstance(value, str):
+ return value
+ if isinstance(status, str):
+ return status
+ return str(status)
async def _run_to_completion(
@@ -389,98 +322,78 @@ async def _run_to_completion(
*,
cwd: str | None,
timeout: float,
-) -> _CompletedJob:
- """Run one internal lifecycle script to completion, returning output and exit code."""
- result = await client.run(script, cwd=cwd, env=None, timeout=timeout)
- output_parts = [result.output]
- done = result.done
- truncated = result.truncated
- offset = result.offset
- exit_code = result.exit_code
- job_id = result.job_id
- windows = 1
- while (not done or truncated) and windows < _MAX_OUTPUT_WINDOWS:
- result = await client.wait(job_id, offset=offset, timeout=timeout)
- output_parts.append(result.output)
- done = result.done
- truncated = result.truncated
- offset = result.offset
- exit_code = result.exit_code
- windows += 1
- if done:
- await _delete_job_best_effort(client, job_id)
- return _CompletedJob(output="".join(output_parts), exit_code=exit_code)
-
-
-async def _delete_job_best_effort(client: ShellctlClientProtocol, job_id: str) -> None:
- """Force-delete one shellctl job, never failing the caller on cleanup errors."""
+) -> _CompletedShellctlJob:
+ deadline = time.monotonic() + timeout
+ job_id: str | None = None
try:
- _ = await client.delete(job_id, force=True)
- except Exception as exc: # noqa: BLE001 - best-effort teardown must not surface cleanup errors
- logger.warning("Failed to delete shellctl job %s: %s", job_id, exc)
-
-
-def _generate_session_id() -> str:
- """Return a shell-safe random session id used as the workspace directory name."""
- return secrets.token_hex(8)
+ result = await _run_client_call(client.run(script, cwd=cwd, env=None, timeout=_remaining_timeout(deadline)))
+ parts = [result.output]
+ job_id = result.job_id
+ while not result.done or result.truncated:
+ result = await _run_client_call(
+ client.wait(job_id, offset=result.offset, timeout=_remaining_timeout(deadline))
+ )
+ parts.append(result.output)
+ return _CompletedShellctlJob(job_id=job_id, exit_code=result.exit_code, output="".join(parts))
+ finally:
+ if job_id is not None:
+ try:
+ await client.delete(job_id, force=True)
+ except RuntimeError as exc:
+ logger.warning("Failed to delete shellctl job %s: %s", job_id, exc)
-def _mkdir_script(session_id: str) -> str:
- return f'mkdir -p "$HOME/workspace/{session_id}"'
+def _upload_script(*, remote_path: str, encoded: str) -> str:
+ return (
+ "set -eu\n"
+ f'mkdir -p "$(dirname -- {_shquote(remote_path)})"\n'
+ f"printf %s {_shquote(encoded)} | base64 -d > {_shquote(remote_path)}"
+ )
-def _cleanup_script(session_id: str) -> str:
- return f'rm -rf -- "$HOME/workspace/{session_id}"'
+def _download_script(*, remote_path: str) -> str:
+ return "\n".join(
+ [
+ "set -eu",
+ f"path={_shquote(remote_path)}",
+ 'if [ ! -f "$path" ]; then exit 66; fi',
+ f"printf %s {_shquote(_TRANSFER_BEGIN)}",
+ 'base64 < "$path" | tr -d "\\n"',
+ f"printf %s {_shquote(_TRANSFER_END)}",
+ ]
+ )
-def _upload_script(*, remote_path: str, encoded: str) -> str:
- """Return a script that recreates a file from embedded base64 in the workspace."""
- quoted = _shquote(remote_path)
- return f"mkdir -p \"$(dirname -- {quoted})\" && printf %s '{encoded}' | base64 -d > {quoted}"
+def _extract_transfer_payload(output: str) -> str:
+ pattern = re.escape(_TRANSFER_BEGIN) + r"(.*?)" + re.escape(_TRANSFER_END)
+ match = re.search(pattern, output, re.DOTALL)
+ if match is None:
+ raise ShellFileTransferError("Transfer payload markers were missing from shell output.")
+ return "".join(match.group(1).split())
-def _download_script(*, remote_path: str) -> str:
- """Return a script that emits a file's base64 between transfer sentinels."""
- quoted = _shquote(remote_path)
- return (
- f"if [ ! -f {quoted} ]; then exit {_DOWNLOAD_MISSING_EXIT_CODE}; fi; "
- f"printf %s {_shquote(_TRANSFER_BEGIN)}; "
- f'base64 < {quoted} | tr -d "\\n"; '
- f"printf %s {_shquote(_TRANSFER_END)}"
- )
+def _output_tail(output: str, *, limit: int = 256) -> str:
+ return output[-limit:]
-def _extract_framed_payload(output: str) -> str:
- """Return the base64 text framed by the transfer sentinels in shellctl output."""
- begin = output.find(_TRANSFER_BEGIN)
- end = output.find(_TRANSFER_END, begin + len(_TRANSFER_BEGIN)) if begin != -1 else -1
- if begin == -1 or end == -1:
- raise ShellFileTransferError("download command returned no framed payload")
- return output[begin + len(_TRANSFER_BEGIN) : end]
+def _remaining_timeout(deadline: float) -> float:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0.0:
+ raise ShellProviderError("Shellctl command timed out before completion.", code="timeout")
+ return remaining
def _shquote(value: str) -> str:
- """Single-quote a value for POSIX shells, escaping embedded single quotes."""
return "'" + value.replace("'", "'\\''") + "'"
-def _output_tail(output: str, *, limit: int = 500) -> str:
- """Return the trailing slice of command output for compact error messages."""
- return output[-limit:]
-
-
__all__ = [
"ShellFileTransferError",
- "ShellProvisionError",
"ShellctlClientFactory",
"ShellctlClientProtocol",
- "ShellctlEnvironmentDescriptor",
- "ShellctlExecutionResult",
- "ShellctlExecutor",
+ "ShellctlCommands",
"ShellctlFileTransfer",
- "ShellctlHandle",
- "ShellctlJobResult",
- "ShellctlJobStatus",
- "ShellctlProvisioner",
+ "ShellctlProvider",
+ "ShellctlResource",
"create_default_shellctl_client_factory",
]
diff --git a/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py b/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py
index cf2ec969ae2..b59395496d1 100644
--- a/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py
+++ b/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py
@@ -92,12 +92,12 @@ def resolve_drive_destination(base_path: Path, drive_key: str) -> Path:
return destination
-def extract_skill_archive(archive_path: Path) -> None:
- """Safely extract one downloaded skill archive into its containing directory."""
+def extract_archive_to_directory(archive_path: Path, *, target_dir: Path) -> None:
+ """Safely extract one downloaded archive into one resolved target directory."""
- target_dir = archive_path.parent.resolve()
+ resolved_target_dir = target_dir.resolve()
try:
- with TemporaryDirectory(dir=target_dir, prefix=".dify-skill-extract-") as staging_dir_name:
+ with TemporaryDirectory(dir=resolved_target_dir, prefix=".dify-skill-extract-") as staging_dir_name:
staging_dir = Path(staging_dir_name).resolve()
with ZipFile(archive_path) as archive:
for zip_info in archive.infolist():
@@ -118,7 +118,7 @@ def extract_skill_archive(archive_path: Path) -> None:
if staged_path.is_dir():
continue
relative_path = staged_path.relative_to(staging_dir)
- destination = (target_dir / relative_path).resolve()
+ destination = (resolved_target_dir / relative_path).resolve()
destination.parent.mkdir(parents=True, exist_ok=True)
_ = staged_path.replace(destination)
except DriveMaterializationValidationError:
@@ -127,6 +127,12 @@ def extract_skill_archive(archive_path: Path) -> None:
raise DriveMaterializationTransferError(f"downloaded skill archive is invalid: {archive_path.name}") from exc
+def extract_skill_archive(archive_path: Path) -> None:
+ """Safely extract one downloaded skill archive into its containing directory."""
+
+ extract_archive_to_directory(archive_path, target_dir=archive_path.parent.resolve())
+
+
def _resolve_zip_entry_destination(target_dir: Path, entry_name: str) -> Path:
normalized_name = entry_name.replace("\\", "/")
pure_path = PurePosixPath(normalized_name)
@@ -163,6 +169,7 @@ __all__ = [
"DriveMaterializationTransferError",
"DriveMaterializationValidationError",
"SKILL_ARCHIVE_FILENAME",
+ "extract_archive_to_directory",
"extract_skill_archive",
"materialize_drive_downloads",
"resolve_drive_destination",
diff --git a/dify-agent/src/dify_agent/agent_stub/cli/_config.py b/dify-agent/src/dify_agent/agent_stub/cli/_config.py
new file mode 100644
index 00000000000..0aabc9b1e25
--- /dev/null
+++ b/dify-agent/src/dify_agent/agent_stub/cli/_config.py
@@ -0,0 +1,320 @@
+"""CLI helpers for sandbox-visible Agent Stub config commands."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from pydantic import BaseModel, ConfigDict
+
+from dify_agent.agent_stub._drive_materialization import (
+ DriveMaterializationTransferError,
+ DriveMaterializationValidationError,
+ extract_archive_to_directory,
+)
+from dify_agent.agent_stub.cli._drive import _build_skill_archive
+from dify_agent.agent_stub.cli._env import read_agent_stub_environment
+from dify_agent.agent_stub.cli._files import upload_tool_file_resource_from_environment
+from dify_agent.agent_stub.client._agent_stub import (
+ request_agent_stub_config_manifest_sync,
+ request_agent_stub_config_push_sync,
+ request_agent_stub_config_file_pull_sync,
+ request_agent_stub_config_skill_pull_sync,
+)
+from dify_agent.agent_stub.client._errors import AgentStubTransferError, AgentStubValidationError
+from dify_agent.agent_stub.protocol.agent_stub import (
+ AgentStubConfigFileRef,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigPushFileItem,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushSkillItem,
+)
+
+_DEFAULT_CONFIG_BASE = Path("./.dify_conf")
+_SKILL_MD_FILENAME = "SKILL.md"
+_SAFE_ENV_VALUE = re.compile(r"^[A-Za-z0-9_./:@+-]+$")
+
+
+class ConfigSkillPullResult(BaseModel):
+ class Item(BaseModel):
+ name: str
+ archive_path: str
+ directory_path: str
+ skill_md: str
+
+ model_config = ConfigDict(extra="forbid")
+
+ items: list[Item]
+
+ model_config = ConfigDict(extra="forbid")
+
+
+class ConfigFilePullResult(BaseModel):
+ class Item(BaseModel):
+ name: str
+ path: str
+
+ model_config = ConfigDict(extra="forbid")
+
+ items: list[Item]
+
+ model_config = ConfigDict(extra="forbid")
+
+
+@dataclass(frozen=True, slots=True)
+class _PreparedPushItem:
+ name: str
+ path: Path
+
+
+def manifest_from_environment() -> AgentStubConfigManifestResponse:
+ environment = read_agent_stub_environment()
+ return request_agent_stub_config_manifest_sync(url=environment.url, auth_jwe=environment.auth_jwe)
+
+
+def pull_config_skills_from_environment(
+ names: list[str] | None = None,
+ local_dir: str | None = None,
+) -> ConfigSkillPullResult:
+ environment = read_agent_stub_environment()
+ manifest = request_agent_stub_config_manifest_sync(url=environment.url, auth_jwe=environment.auth_jwe)
+ selected_names = names or [item.name for item in manifest.skills.items]
+ target_dir = Path(local_dir or (_DEFAULT_CONFIG_BASE / "skills")).expanduser().resolve()
+ target_dir.mkdir(parents=True, exist_ok=True)
+
+ items: list[ConfigSkillPullResult.Item] = []
+ for name in selected_names:
+ archive_bytes = request_agent_stub_config_skill_pull_sync(
+ url=environment.url,
+ auth_jwe=environment.auth_jwe,
+ name=name,
+ )
+ archive_path = target_dir / f"{name}.zip"
+ skill_dir = target_dir / name
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ archive_path.write_bytes(archive_bytes)
+ try:
+ extract_archive_to_directory(archive_path, target_dir=skill_dir)
+ except DriveMaterializationValidationError as exc:
+ raise AgentStubValidationError(str(exc)) from exc
+ except DriveMaterializationTransferError as exc:
+ raise AgentStubTransferError(str(exc)) from exc
+ skill_md_path = skill_dir / _SKILL_MD_FILENAME
+ if not skill_md_path.is_file():
+ raise AgentStubValidationError(f"pulled config skill is missing {_SKILL_MD_FILENAME}: {name}")
+ items.append(
+ ConfigSkillPullResult.Item(
+ name=name,
+ archive_path=str(archive_path),
+ directory_path=str(skill_dir),
+ skill_md=skill_md_path.read_text(encoding="utf-8"),
+ )
+ )
+ return ConfigSkillPullResult(items=items)
+
+
+def pull_config_files_from_environment(
+ names: list[str] | None = None,
+ local_dir: str | None = None,
+) -> ConfigFilePullResult:
+ environment = read_agent_stub_environment()
+ manifest = request_agent_stub_config_manifest_sync(url=environment.url, auth_jwe=environment.auth_jwe)
+ selected_names = names or [item.name for item in manifest.files.items]
+ target_dir = Path(local_dir or (_DEFAULT_CONFIG_BASE / "files")).expanduser().resolve()
+ target_dir.mkdir(parents=True, exist_ok=True)
+
+ items: list[ConfigFilePullResult.Item] = []
+ for name in selected_names:
+ payload = request_agent_stub_config_file_pull_sync(
+ url=environment.url,
+ auth_jwe=environment.auth_jwe,
+ name=name,
+ )
+ target_path = target_dir / name
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ target_path.write_bytes(payload)
+ items.append(ConfigFilePullResult.Item(name=name, path=str(target_path)))
+ return ConfigFilePullResult(items=items)
+
+
+def pull_config_env_from_environment(local_path: str | None = None) -> Path:
+ manifest = manifest_from_environment()
+ target_path = Path(local_path or (_DEFAULT_CONFIG_BASE / ".env")).expanduser().resolve()
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ lines: list[str] = []
+ for key in manifest.env_keys:
+ if key not in os.environ:
+ raise AgentStubValidationError(f"config env key is not present in the current environment: {key}")
+ lines.append(f"{key}={_format_env_value(os.environ[key])}")
+ target_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
+ return target_path
+
+
+def pull_config_note_from_environment(local_path: str | None = None) -> Path:
+ manifest = manifest_from_environment()
+ target_path = Path(local_path or (_DEFAULT_CONFIG_BASE / "note.md")).expanduser().resolve()
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ target_path.write_text(manifest.note, encoding="utf-8")
+ return target_path
+
+
+def push_config_note_from_environment(local_path: str | None) -> AgentStubConfigManifestResponse:
+ note = _read_text_input(local_path, _DEFAULT_CONFIG_BASE / "note.md")
+ return _push_config_from_environment(note=note)
+
+
+def push_config_env_from_environment(local_path: str | None) -> AgentStubConfigManifestResponse:
+ env_text = _read_text_input(local_path, _DEFAULT_CONFIG_BASE / ".env")
+ return _push_config_from_environment(env_text=env_text)
+
+
+def push_config_files_from_environment(paths: list[str], name: str | None) -> AgentStubConfigManifestResponse:
+ _require_non_empty_inputs(paths, kind="file path")
+ override_name = None if name is None else _require_config_entry_name(name, kind="file")
+ if override_name is not None and len(paths) != 1:
+ raise AgentStubValidationError("--name requires exactly one PATH")
+ items = [
+ _PreparedPushItem(
+ name=override_name if index == 0 and override_name is not None else _infer_name_from_path(source_path),
+ path=source_path,
+ )
+ for index, source_path in enumerate(_resolve_input_paths(paths))
+ ]
+ return _push_config_from_environment(files=[_build_file_push_item(item=item) for item in items])
+
+
+def delete_config_files_from_environment(names: list[str]) -> AgentStubConfigManifestResponse:
+ _require_non_empty_inputs(names, kind="file name")
+ return _push_config_from_environment(
+ files=[
+ AgentStubConfigPushFileItem(name=_require_config_entry_name(name, kind="file"), file_ref=None)
+ for name in names
+ ]
+ )
+
+
+def push_config_skills_from_environment(paths: list[str]) -> AgentStubConfigManifestResponse:
+ _require_non_empty_inputs(paths, kind="skill directory")
+ items = [
+ _PreparedPushItem(name=_infer_name_from_path(source_path), path=source_path)
+ for source_path in _resolve_input_paths(paths)
+ ]
+ return _push_config_from_environment(skills=[_build_skill_push_item(item=item) for item in items])
+
+
+def delete_config_skills_from_environment(names: list[str]) -> AgentStubConfigManifestResponse:
+ _require_non_empty_inputs(names, kind="skill name")
+ return _push_config_from_environment(
+ skills=[
+ AgentStubConfigPushSkillItem(name=_require_config_entry_name(name, kind="skill"), file_ref=None)
+ for name in names
+ ]
+ )
+
+
+def _push_config_from_environment(
+ *,
+ files: list[AgentStubConfigPushFileItem] | None = None,
+ skills: list[AgentStubConfigPushSkillItem] | None = None,
+ env_text: str | None = None,
+ note: str | None = None,
+) -> AgentStubConfigManifestResponse:
+ environment = read_agent_stub_environment()
+ return request_agent_stub_config_push_sync(
+ url=environment.url,
+ auth_jwe=environment.auth_jwe,
+ request=AgentStubConfigPushRequest(
+ files=files or [],
+ skills=skills or [],
+ env_text=env_text,
+ note=note,
+ ),
+ )
+
+
+def _read_text_input(path_value: str | None, default_path: Path) -> str:
+ if path_value == "-":
+ return os.fdopen(os.dup(0), encoding="utf-8").read()
+ source_path = Path(path_value or default_path).expanduser().resolve()
+ if not source_path.is_file():
+ raise AgentStubValidationError(f"local file not found: {source_path}")
+ return source_path.read_text(encoding="utf-8")
+
+
+def _resolve_input_paths(paths: list[str]) -> list[Path]:
+ return [Path(path).expanduser().resolve() for path in paths]
+
+
+def _infer_name_from_path(path: Path) -> str:
+ return path.name
+
+
+def _build_file_push_item(
+ *,
+ item: _PreparedPushItem,
+) -> AgentStubConfigPushFileItem:
+ if not item.path.is_file():
+ raise AgentStubValidationError(f"config file path must be a regular file: {item.path}")
+ uploaded = upload_tool_file_resource_from_environment(path=str(item.path))
+ return AgentStubConfigPushFileItem(
+ name=item.name,
+ file_ref=AgentStubConfigFileRef(kind="tool_file", id=uploaded.tool_file_id),
+ )
+
+
+def _build_skill_push_item(
+ *,
+ item: _PreparedPushItem,
+) -> AgentStubConfigPushSkillItem:
+ if not item.path.is_dir():
+ raise AgentStubValidationError(f"config skill path must be a directory: {item.path}")
+ skill_md_path = item.path / _SKILL_MD_FILENAME
+ if not skill_md_path.is_file():
+ raise AgentStubValidationError(f"config skill directory must contain {_SKILL_MD_FILENAME}: {item.path}")
+ with TemporaryDirectory() as temp_dir:
+ archive_path = Path(temp_dir) / f"{item.name}.zip"
+ _build_skill_archive(item.path, archive_path)
+ uploaded = upload_tool_file_resource_from_environment(path=str(archive_path))
+ return AgentStubConfigPushSkillItem(
+ name=item.name,
+ file_ref=AgentStubConfigFileRef(kind="tool_file", id=uploaded.tool_file_id),
+ )
+
+
+def _require_config_entry_name(name: str, *, kind: str) -> str:
+ normalized = name.strip()
+ if not normalized:
+ raise AgentStubValidationError(f"config {kind} name must not be empty")
+ return normalized
+
+
+def _require_non_empty_inputs(values: list[str], *, kind: str) -> None:
+ if not values:
+ raise AgentStubValidationError(f"at least one {kind} is required")
+
+
+def _format_env_value(value: str) -> str:
+ if _SAFE_ENV_VALUE.fullmatch(value):
+ return value
+ return json.dumps(value)
+
+
+__all__ = [
+ "ConfigFilePullResult",
+ "ConfigSkillPullResult",
+ "manifest_from_environment",
+ "pull_config_env_from_environment",
+ "pull_config_files_from_environment",
+ "pull_config_note_from_environment",
+ "pull_config_skills_from_environment",
+ "push_config_env_from_environment",
+ "push_config_files_from_environment",
+ "push_config_note_from_environment",
+ "push_config_skills_from_environment",
+ "delete_config_files_from_environment",
+ "delete_config_skills_from_environment",
+]
diff --git a/dify-agent/src/dify_agent/agent_stub/cli/main.py b/dify-agent/src/dify_agent/agent_stub/cli/main.py
index 3d34b96d62e..1c1e328e436 100644
--- a/dify-agent/src/dify_agent/agent_stub/cli/main.py
+++ b/dify-agent/src/dify_agent/agent_stub/cli/main.py
@@ -13,10 +13,24 @@ from __future__ import annotations
import sys
from typing import cast
+import click
import typer
from typer.main import get_command
from dify_agent.agent_stub.cli._agent_stub import connect_from_environment
+from dify_agent.agent_stub.cli._config import (
+ delete_config_files_from_environment,
+ delete_config_skills_from_environment,
+ manifest_from_environment,
+ pull_config_env_from_environment,
+ pull_config_files_from_environment,
+ pull_config_note_from_environment,
+ pull_config_skills_from_environment,
+ push_config_env_from_environment,
+ push_config_files_from_environment,
+ push_config_note_from_environment,
+ push_config_skills_from_environment,
+)
from dify_agent.agent_stub.cli._drive import (
DrivePushKind,
format_drive_manifest,
@@ -33,17 +47,45 @@ from dify_agent.agent_stub.cli._files import download_file_from_environment, upl
from dify_agent.agent_stub.client._errors import AgentStubClientError
from dify_agent.agent_stub.protocol.agent_stub import AGENT_STUB_DRIVE_BASE_ENV_VAR, DEFAULT_AGENT_STUB_DRIVE_BASE
+_CONFIG_MANIFEST_STDOUT_EXCLUDE = {
+ "skills": {"items": {"__all__": {"hash"}}},
+ "files": {"items": {"__all__": {"hash"}}},
+}
+
app = typer.Typer(
add_completion=False,
help="Forward shell-visible dify-agent commands to the Dify Agent Stub server.",
no_args_is_help=True,
+ rich_markup_mode=None,
+)
+file_app = typer.Typer(help="Upload or download workflow files through the Agent Stub.", rich_markup_mode=None)
+config_app = typer.Typer(
+ help="Inspect or update Agent Soul-backed config assets through the Agent Stub.",
+ rich_markup_mode=None,
)
-file_app = typer.Typer(help="Upload or download workflow files through the Agent Stub.")
-drive_app = typer.Typer(help="List, pull, or push agent drive files through the Agent Stub.")
+config_skills_app = typer.Typer(help="Pull or update config skills through the Agent Stub.", rich_markup_mode=None)
+config_files_app = typer.Typer(help="Pull or update config files through the Agent Stub.", rich_markup_mode=None)
+config_skill_pull_alias_app = typer.Typer(help="Pull config skills through the Agent Stub.", rich_markup_mode=None)
+config_file_pull_alias_app = typer.Typer(help="Pull config files through the Agent Stub.", rich_markup_mode=None)
+config_env_app = typer.Typer(
+ help="Pull or update config env variables visible to the current run.", rich_markup_mode=None
+)
+config_note_app = typer.Typer(help="Pull or update the current config note.", rich_markup_mode=None)
+drive_app = typer.Typer(help="List, pull, or push agent drive files through the Agent Stub.", rich_markup_mode=None)
app.add_typer(file_app, name="file")
+app.add_typer(config_app, name="config")
+config_app.add_typer(config_skills_app, name="skills")
+# Keep hidden singular aliases on separate pull-only apps. Reusing the plural
+# apps here would also expose push/delete through `config skill|file ...`,
+# which is intentionally not part of the compatibility surface.
+config_app.add_typer(config_skill_pull_alias_app, name="skill", hidden=True)
+config_app.add_typer(config_files_app, name="files")
+config_app.add_typer(config_file_pull_alias_app, name="file", hidden=True)
+config_app.add_typer(config_env_app, name="env")
+config_app.add_typer(config_note_app, name="note")
app.add_typer(drive_app, name="drive")
-_KNOWN_ROOT_COMMANDS = frozenset({"connect", "drive", "file"})
+_KNOWN_ROOT_COMMANDS = frozenset({"config", "connect", "drive", "file"})
@app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
@@ -77,6 +119,121 @@ def download(
)
+@config_app.command("manifest")
+def config_manifest() -> None:
+ """Show the current visible Agent config manifest as JSON."""
+ _run_config_manifest()
+
+
+@config_skills_app.command("pull")
+def config_skills_pull(
+ names: list[str] = typer.Argument(None, metavar="NAME"),
+ local_dir: str | None = typer.Option(None, "--to", help="Local directory for pulled config skills."),
+ json_output: bool = typer.Option(False, "--json", help="Emit the pull result as JSON."),
+) -> None:
+ """Pull one or all visible config skills into ./.dify_conf/skills by default."""
+ _run_config_skill_pull(names=names or None, local_dir=local_dir, json_output=json_output)
+
+
+@config_skill_pull_alias_app.command("pull")
+def config_skill_pull_alias(
+ names: list[str] = typer.Argument(None, metavar="NAME"),
+ local_dir: str | None = typer.Option(None, "--to", help="Local directory for pulled config skills."),
+ json_output: bool = typer.Option(False, "--json", help="Emit the pull result as JSON."),
+) -> None:
+ """Pull one or all visible config skills into ./.dify_conf/skills by default."""
+ _run_config_skill_pull(names=names or None, local_dir=local_dir, json_output=json_output)
+
+
+@config_skills_app.command("push")
+def config_skills_push(
+ paths: list[str] = typer.Argument(..., metavar="PATH"),
+) -> None:
+ """Upload one or more local skill directories into the current config manifest."""
+ _run_config_skills_push(paths=paths)
+
+
+@config_skills_app.command("delete")
+def config_skills_delete(
+ names: list[str] = typer.Argument(..., metavar="NAME"),
+) -> None:
+ """Delete one or more config skills by name without touching local directories."""
+ _run_config_skills_delete(names=names)
+
+
+@config_files_app.command("pull")
+def config_files_pull(
+ names: list[str] = typer.Argument(None, metavar="NAME"),
+ local_dir: str | None = typer.Option(None, "--to", help="Local directory for pulled config files."),
+ json_output: bool = typer.Option(False, "--json", help="Emit the pull result as JSON."),
+) -> None:
+ """Pull one or all visible config files into ./.dify_conf/files by default."""
+ _run_config_file_pull(names=names or None, local_dir=local_dir, json_output=json_output)
+
+
+@config_file_pull_alias_app.command("pull")
+def config_file_pull_alias(
+ names: list[str] = typer.Argument(None, metavar="NAME"),
+ local_dir: str | None = typer.Option(None, "--to", help="Local directory for pulled config files."),
+ json_output: bool = typer.Option(False, "--json", help="Emit the pull result as JSON."),
+) -> None:
+ """Pull one or all visible config files into ./.dify_conf/files by default."""
+ _run_config_file_pull(names=names or None, local_dir=local_dir, json_output=json_output)
+
+
+@config_files_app.command("push")
+def config_files_push(
+ paths: list[str] = typer.Argument(..., metavar="PATH"),
+ name: str | None = typer.Option(
+ None,
+ "--name",
+ help="Override the target config file name when uploading exactly one local file.",
+ ),
+) -> None:
+ """Upload one or more local files into the current config manifest."""
+ _run_config_files_push(paths=paths, name=name)
+
+
+@config_files_app.command("delete")
+def config_files_delete(
+ names: list[str] = typer.Argument(..., metavar="NAME"),
+) -> None:
+ """Delete one or more config files by name without touching local files."""
+ _run_config_files_delete(names=names)
+
+
+@config_env_app.command("pull")
+def config_env_pull(
+ local_path: str | None = typer.Option(None, "--to", help="Local dotenv file path."),
+) -> None:
+ """Export visible config env values into ./.dify_conf/.env by default."""
+ _run_config_env_pull(local_path=local_path)
+
+
+@config_env_app.command("push")
+def config_env_push(
+ local_path: str | None = typer.Argument(None, metavar="PATH|-"),
+) -> None:
+ """Replace visible config env values from one local dotenv file or stdin."""
+ _run_config_env_push(local_path=local_path)
+
+
+@config_note_app.command("pull")
+def config_note_pull(
+ local_path: str | None = typer.Option(None, "--to", help="Local markdown file path."),
+) -> None:
+ """Export the current config note into ./.dify_conf/note.md by default."""
+ _run_config_note_pull(local_path=local_path)
+
+
+@config_note_app.command("push")
+def config_note_push(
+ local_path: str | None = typer.Argument(None, metavar="PATH|-"),
+) -> None:
+ """Replace the current config note from one local text file or stdin."""
+ _run_config_note_push(local_path=local_path)
+
+
@drive_app.command("list")
def drive_list(
path_prefix: str = typer.Argument("", metavar="REMOTE_PREFIX"),
@@ -174,6 +331,25 @@ def _show_root_help() -> None:
typer.echo(command.get_help(context))
+def render_agent_stub_cli_help(args: tuple[str, ...]) -> str:
+ """Render Click help for one known ``dify-agent`` subcommand without executing a shell."""
+ command: click.Command = get_command(app)
+ parent_context: click.Context | None = None
+ command_path = ["dify-agent"]
+ for name in args:
+ if not isinstance(command, click.Group):
+ raise ValueError(f"dify-agent {' '.join(args)} is not a command group")
+ next_command = command.commands.get(name)
+ if next_command is None:
+ raise ValueError(f"unknown dify-agent command path: {' '.join(args)}")
+ current_context = click.Context(command, info_name=command_path[-1], parent=parent_context)
+ parent_context = current_context
+ command = next_command
+ command_path.append(name)
+ context = click.Context(command, info_name=command_path[-1], parent=parent_context)
+ return command.get_help(context).strip()
+
+
def _run_connect(*, argv: list[str], json_output: bool) -> None:
try:
response = connect_from_environment(argv=argv)
@@ -225,6 +401,149 @@ def _run_file_download(
typer.echo(str(response.path))
+def _run_config_manifest() -> None:
+ try:
+ response = manifest_from_environment()
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json(exclude=_CONFIG_MANIFEST_STDOUT_EXCLUDE))
+
+
+def _run_config_skill_pull(*, names: list[str] | None, local_dir: str | None, json_output: bool) -> None:
+ try:
+ response = pull_config_skills_from_environment(names=names, local_dir=local_dir)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ if json_output:
+ typer.echo(response.model_dump_json())
+ return
+ for index, item in enumerate(response.items):
+ if index:
+ typer.echo("")
+ typer.echo(item.directory_path)
+ typer.echo(item.skill_md, nl=False)
+
+
+def _run_config_file_pull(*, names: list[str] | None, local_dir: str | None, json_output: bool) -> None:
+ try:
+ response = pull_config_files_from_environment(names=names, local_dir=local_dir)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ if json_output:
+ typer.echo(response.model_dump_json())
+ return
+ for item in response.items:
+ typer.echo(item.path)
+
+
+def _run_config_env_pull(*, local_path: str | None) -> None:
+ try:
+ path = pull_config_env_from_environment(local_path=local_path)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(str(path))
+
+
+def _run_config_note_pull(*, local_path: str | None) -> None:
+ try:
+ path = pull_config_note_from_environment(local_path=local_path)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(str(path))
+
+
+def _run_config_note_push(*, local_path: str | None) -> None:
+ try:
+ response = push_config_note_from_environment(local_path=local_path)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
+def _run_config_env_push(*, local_path: str | None) -> None:
+ try:
+ response = push_config_env_from_environment(local_path=local_path)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
+def _run_config_files_push(*, paths: list[str], name: str | None) -> None:
+ try:
+ response = push_config_files_from_environment(paths=paths, name=name)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
+def _run_config_files_delete(*, names: list[str]) -> None:
+ try:
+ response = delete_config_files_from_environment(names=names)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
+def _run_config_skills_push(*, paths: list[str]) -> None:
+ try:
+ response = push_config_skills_from_environment(paths=paths)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
+def _run_config_skills_delete(*, names: list[str]) -> None:
+ try:
+ response = delete_config_skills_from_environment(names=names)
+ except MissingAgentStubEnvironmentError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(2) from exc
+ except AgentStubClientError as exc:
+ typer.echo(str(exc), err=True)
+ raise SystemExit(1) from exc
+ typer.echo(response.model_dump_json())
+
+
def _run_drive_list(*, path_prefix: str, json_output: bool) -> None:
try:
response = list_drive_manifest_from_environment(prefix=path_prefix)
diff --git a/dify-agent/src/dify_agent/agent_stub/client/_agent_stub.py b/dify-agent/src/dify_agent/agent_stub/client/_agent_stub.py
index 34b54cabaca..b76e74cd354 100644
--- a/dify-agent/src/dify_agent/agent_stub/client/_agent_stub.py
+++ b/dify-agent/src/dify_agent/agent_stub/client/_agent_stub.py
@@ -8,6 +8,13 @@ from pydantic import JsonValue
from dify_agent.agent_stub.client._agent_stub_http import (
connect_agent_stub_http_sync,
download_file_bytes_from_signed_url_sync,
+ request_agent_stub_config_env_update_http_sync,
+ request_agent_stub_config_file_pull_http_sync,
+ request_agent_stub_config_manifest_http_sync,
+ request_agent_stub_config_note_update_http_sync,
+ request_agent_stub_config_push_http_sync,
+ request_agent_stub_config_skill_inspect_http_sync,
+ request_agent_stub_config_skill_pull_http_sync,
request_agent_stub_drive_commit_http_sync,
request_agent_stub_drive_manifest_http_sync,
request_agent_stub_file_download_http_sync,
@@ -16,9 +23,10 @@ from dify_agent.agent_stub.client._agent_stub_http import (
)
from dify_agent.agent_stub.client._errors import AgentStubValidationError
from dify_agent.agent_stub.protocol.agent_stub import (
+ AgentStubConfigPushRequest,
AgentStubDriveCommitRequest,
- AgentStubFileMapping,
parse_agent_stub_endpoint,
+ AgentStubFileMapping,
)
@@ -166,7 +174,157 @@ def request_agent_stub_drive_commit_sync(
)
+def request_agent_stub_config_manifest_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Fetch the current config manifest through the HTTP Agent Stub transport.
+
+ Config operations are HTTP-only in this stage. ``grpc://`` endpoints raise
+ ``AgentStubValidationError`` instead of attempting transport fallback.
+ """
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_manifest_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_skill_pull_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Download one config skill archive through the HTTP Agent Stub transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_skill_pull_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ name=name,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_skill_inspect_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Fetch one config skill inspect view through the HTTP Agent Stub transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_skill_inspect_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ name=name,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_file_pull_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Download one config file payload through the HTTP Agent Stub transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_file_pull_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ name=name,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_push_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ request: AgentStubConfigPushRequest,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Push config file/skill/env/note mutations through the HTTP transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_push_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ request=request,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_env_update_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ env_text: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Replace or delete config env entries through the HTTP transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_env_update_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ env_text=env_text,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def request_agent_stub_config_note_update_sync(
+ *,
+ url: str,
+ auth_jwe: str,
+ note: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+):
+ """Update the config note text through the HTTP Agent Stub transport."""
+ endpoint = _parse_endpoint(url)
+ if endpoint.is_grpc:
+ raise AgentStubValidationError("Agent Stub config operations require an HTTP Agent Stub URL")
+ return request_agent_stub_config_note_update_http_sync(
+ base_url=endpoint.url,
+ auth_jwe=auth_jwe,
+ note=note,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
def _parse_endpoint(url: str):
+ """Normalize one Agent Stub base URL and map parse failures to client errors."""
try:
return parse_agent_stub_endpoint(url)
except ValueError as exc:
@@ -176,6 +334,13 @@ def _parse_endpoint(url: str):
__all__ = [
"connect_agent_stub_sync",
"download_file_bytes_from_signed_url_sync",
+ "request_agent_stub_config_env_update_sync",
+ "request_agent_stub_config_file_pull_sync",
+ "request_agent_stub_config_manifest_sync",
+ "request_agent_stub_config_note_update_sync",
+ "request_agent_stub_config_push_sync",
+ "request_agent_stub_config_skill_inspect_sync",
+ "request_agent_stub_config_skill_pull_sync",
"request_agent_stub_drive_commit_sync",
"request_agent_stub_drive_manifest_sync",
"request_agent_stub_file_download_sync",
diff --git a/dify-agent/src/dify_agent/agent_stub/client/_agent_stub_http.py b/dify-agent/src/dify_agent/agent_stub/client/_agent_stub_http.py
index 9c80e2d060d..49c7c83ae94 100644
--- a/dify-agent/src/dify_agent/agent_stub/client/_agent_stub_http.py
+++ b/dify-agent/src/dify_agent/agent_stub/client/_agent_stub_http.py
@@ -8,6 +8,7 @@ must stay safe to import in default installations, so these helpers live under
from __future__ import annotations
+import json
from collections.abc import Callable
from typing import BinaryIO
from typing import cast
@@ -24,6 +25,11 @@ from dify_agent.agent_stub.client._errors import (
from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubConnectRequest,
AgentStubConnectResponse,
+ AgentStubConfigEnvUpdateRequest,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigNoteUpdateRequest,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
AgentStubDriveCommitRequest,
AgentStubDriveCommitResponse,
AgentStubDriveManifestResponse,
@@ -32,6 +38,13 @@ from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubFileMapping,
AgentStubFileUploadRequest,
AgentStubFileUploadResponse,
+ agent_stub_config_env_url,
+ agent_stub_config_file_pull_url,
+ agent_stub_config_manifest_url,
+ agent_stub_config_note_url,
+ agent_stub_config_push_url,
+ agent_stub_config_skill_inspect_url,
+ agent_stub_config_skill_pull_url,
agent_stub_connections_url,
agent_stub_drive_commit_url,
agent_stub_drive_manifest_url,
@@ -172,13 +185,213 @@ def request_agent_stub_drive_commit_http_sync(
auth_jwe=auth_jwe,
endpoint_name="drive commit request",
endpoint_url_factory=agent_stub_drive_commit_url,
- request_body=request.model_dump_json(exclude_none=True),
+ request_body=_dump_drive_commit_request(request),
timeout=timeout,
sync_http_client=sync_http_client,
)
return _parse_success_response(response=response, response_model=AgentStubDriveCommitResponse, label="drive commit")
+def request_agent_stub_config_manifest_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> AgentStubConfigManifestResponse:
+ """Fetch the current config manifest from the HTTP Agent Stub endpoint."""
+ response = _get_agent_stub_json(
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config manifest request",
+ endpoint_url_factory=agent_stub_config_manifest_url,
+ params={},
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ return _parse_success_response(
+ response=response,
+ response_model=AgentStubConfigManifestResponse,
+ label="config manifest",
+ )
+
+
+def request_agent_stub_config_skill_pull_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> bytes:
+ """Download one config skill archive from the HTTP Agent Stub endpoint."""
+ response = _get_agent_stub_json(
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config skill pull request",
+ endpoint_url_factory=lambda resolved_base_url: agent_stub_config_skill_pull_url(resolved_base_url, name),
+ params={},
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ if response.is_error:
+ payload = _parse_json_payload(
+ response, invalid_json_message="Agent Stub returned invalid JSON for config skill pull"
+ )
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubHTTPError(response.status_code, detail)
+ return response.content
+
+
+def request_agent_stub_config_skill_inspect_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> dict[str, object]:
+ """Fetch the JSON inspect view for one config skill."""
+ response = _get_agent_stub_json(
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config skill inspect request",
+ endpoint_url_factory=lambda resolved_base_url: agent_stub_config_skill_inspect_url(resolved_base_url, name),
+ params={},
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ payload = _parse_json_payload(
+ response, invalid_json_message="Agent Stub returned invalid JSON for config skill inspect"
+ )
+ if response.is_error:
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubHTTPError(response.status_code, detail)
+ if not isinstance(payload, dict):
+ raise AgentStubValidationError("invalid Agent Stub config skill inspect response")
+ return cast(dict[str, object], payload)
+
+
+def request_agent_stub_config_file_pull_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ name: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> bytes:
+ """Download one config file payload from the HTTP Agent Stub endpoint."""
+ response = _get_agent_stub_json(
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config file pull request",
+ endpoint_url_factory=lambda resolved_base_url: agent_stub_config_file_pull_url(resolved_base_url, name),
+ params={},
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ if response.is_error:
+ payload = _parse_json_payload(
+ response, invalid_json_message="Agent Stub returned invalid JSON for config file pull"
+ )
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubHTTPError(response.status_code, detail)
+ return response.content
+
+
+def request_agent_stub_config_push_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ request: AgentStubConfigPushRequest,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> AgentStubConfigPushResponse:
+ """Push config file/skill/env/note mutations to the HTTP Agent Stub endpoint."""
+ response = _post_agent_stub_json(
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config push request",
+ endpoint_url_factory=agent_stub_config_push_url,
+ request_body=request.model_dump_json(exclude_none=True, exclude_defaults=True),
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ return _parse_success_response(response=response, response_model=AgentStubConfigPushResponse, label="config push")
+
+
+def _dump_drive_commit_request(request: AgentStubDriveCommitRequest) -> str:
+ payload = cast(dict[str, object], request.model_dump(mode="json", exclude_none=True))
+ items = payload.get("items")
+ if isinstance(items, list):
+ for item in items:
+ if isinstance(item, dict) and item.get("is_skill") is False:
+ item.pop("is_skill")
+ return json.dumps(payload, separators=(",", ":"))
+
+
+def request_agent_stub_config_env_update_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ env_text: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> dict[str, object]:
+ """Replace or delete config env entries through the HTTP Agent Stub endpoint."""
+ request_model = AgentStubConfigEnvUpdateRequest(env_text=env_text)
+ response = _send_agent_stub_json(
+ method="PATCH",
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config env update request",
+ endpoint_url_factory=agent_stub_config_env_url,
+ request_body=request_model.model_dump_json(),
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ payload = _parse_json_payload(
+ response, invalid_json_message="Agent Stub returned invalid JSON for config env update"
+ )
+ if response.is_error:
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubHTTPError(response.status_code, detail)
+ if not isinstance(payload, dict):
+ raise AgentStubValidationError("invalid Agent Stub config env update response")
+ return cast(dict[str, object], payload)
+
+
+def request_agent_stub_config_note_update_http_sync(
+ *,
+ base_url: str,
+ auth_jwe: str,
+ note: str,
+ timeout: float | httpx.Timeout = 30.0,
+ sync_http_client: httpx.Client | None = None,
+) -> dict[str, object]:
+ """Update the config note text through the HTTP Agent Stub endpoint."""
+ request_model = AgentStubConfigNoteUpdateRequest(note=note)
+ response = _send_agent_stub_json(
+ method="PUT",
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name="config note update request",
+ endpoint_url_factory=agent_stub_config_note_url,
+ request_body=request_model.model_dump_json(),
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+ payload = _parse_json_payload(
+ response, invalid_json_message="Agent Stub returned invalid JSON for config note update"
+ )
+ if response.is_error:
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubHTTPError(response.status_code, detail)
+ if not isinstance(payload, dict):
+ raise AgentStubValidationError("invalid Agent Stub config note update response")
+ return cast(dict[str, object], payload)
+
+
def upload_file_to_signed_url_sync(
*,
upload_url: str,
@@ -258,6 +471,29 @@ def _post_agent_stub_json(
request_body: str,
timeout: float | httpx.Timeout,
sync_http_client: httpx.Client | None,
+) -> httpx.Response:
+ return _send_agent_stub_json(
+ method="POST",
+ base_url=base_url,
+ auth_jwe=auth_jwe,
+ endpoint_name=endpoint_name,
+ endpoint_url_factory=endpoint_url_factory,
+ request_body=request_body,
+ timeout=timeout,
+ sync_http_client=sync_http_client,
+ )
+
+
+def _send_agent_stub_json(
+ *,
+ method: str,
+ base_url: str,
+ auth_jwe: str,
+ endpoint_name: str,
+ endpoint_url_factory: Callable[[str], str],
+ request_body: str,
+ timeout: float | httpx.Timeout,
+ sync_http_client: httpx.Client | None,
) -> httpx.Response:
try:
endpoint_url = endpoint_url_factory(base_url)
@@ -266,7 +502,8 @@ def _post_agent_stub_json(
owns_client = sync_http_client is None
client = sync_http_client or httpx.Client(timeout=timeout, follow_redirects=True)
try:
- return client.post(
+ return client.request(
+ method,
endpoint_url,
content=request_body,
headers={
@@ -344,6 +581,13 @@ def _parse_json_payload(response: httpx.Response, *, invalid_json_message: str)
__all__ = [
"connect_agent_stub_http_sync",
"download_file_bytes_from_signed_url_sync",
+ "request_agent_stub_config_env_update_http_sync",
+ "request_agent_stub_config_file_pull_http_sync",
+ "request_agent_stub_config_manifest_http_sync",
+ "request_agent_stub_config_note_update_http_sync",
+ "request_agent_stub_config_push_http_sync",
+ "request_agent_stub_config_skill_inspect_http_sync",
+ "request_agent_stub_config_skill_pull_http_sync",
"request_agent_stub_drive_commit_http_sync",
"request_agent_stub_drive_manifest_http_sync",
"request_agent_stub_file_download_http_sync",
diff --git a/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py b/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py
index b607b3daa09..d10643de944 100644
--- a/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py
+++ b/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py
@@ -8,6 +8,17 @@ from .agent_stub import (
DEFAULT_AGENT_STUB_DRIVE_BASE,
AgentStubConnectRequest,
AgentStubConnectResponse,
+ AgentStubConfigEnvUpdateRequest,
+ AgentStubConfigFileItem,
+ AgentStubConfigFileRef,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigNoteUpdateRequest,
+ AgentStubConfigPushFileItem,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
+ AgentStubConfigPushSkillItem,
+ AgentStubConfigSkillItem,
+ AgentStubConfigVersionInfo,
AgentStubDriveCommitItem,
AgentStubDriveCommitRequest,
AgentStubDriveCommitResponse,
@@ -21,6 +32,13 @@ from .agent_stub import (
AgentStubFileUploadRequest,
AgentStubFileUploadResponse,
AgentStubURLScheme,
+ agent_stub_config_env_url,
+ agent_stub_config_file_pull_url,
+ agent_stub_config_manifest_url,
+ agent_stub_config_note_url,
+ agent_stub_config_push_url,
+ agent_stub_config_skill_inspect_url,
+ agent_stub_config_skill_pull_url,
agent_stub_connections_url,
agent_stub_drive_base_for_ref,
agent_stub_drive_commit_url,
@@ -40,6 +58,17 @@ __all__ = [
"DEFAULT_AGENT_STUB_DRIVE_BASE",
"AgentStubConnectRequest",
"AgentStubConnectResponse",
+ "AgentStubConfigEnvUpdateRequest",
+ "AgentStubConfigFileItem",
+ "AgentStubConfigFileRef",
+ "AgentStubConfigManifestResponse",
+ "AgentStubConfigNoteUpdateRequest",
+ "AgentStubConfigPushFileItem",
+ "AgentStubConfigPushRequest",
+ "AgentStubConfigPushResponse",
+ "AgentStubConfigPushSkillItem",
+ "AgentStubConfigSkillItem",
+ "AgentStubConfigVersionInfo",
"AgentStubDriveCommitItem",
"AgentStubDriveCommitRequest",
"AgentStubDriveCommitResponse",
@@ -53,6 +82,13 @@ __all__ = [
"AgentStubFileUploadRequest",
"AgentStubFileUploadResponse",
"AgentStubURLScheme",
+ "agent_stub_config_env_url",
+ "agent_stub_config_file_pull_url",
+ "agent_stub_config_manifest_url",
+ "agent_stub_config_note_url",
+ "agent_stub_config_push_url",
+ "agent_stub_config_skill_inspect_url",
+ "agent_stub_config_skill_pull_url",
"agent_stub_connections_url",
"agent_stub_drive_base_for_ref",
"agent_stub_drive_commit_url",
diff --git a/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py b/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py
index c6d0333cd5c..f13e5d9fb9f 100644
--- a/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py
+++ b/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py
@@ -142,6 +142,35 @@ def agent_stub_drive_commit_url(base_url: str) -> str:
return f"{_require_http_base_url(base_url)}/drive/commit"
+def agent_stub_config_manifest_url(base_url: str) -> str:
+ """Return the stable HTTP config-manifest endpoint URL for one base URL."""
+ return f"{_require_http_base_url(base_url)}/config/manifest"
+
+
+def agent_stub_config_skill_pull_url(base_url: str, name: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/skills/{name}/pull"
+
+
+def agent_stub_config_skill_inspect_url(base_url: str, name: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/skills/{name}/inspect"
+
+
+def agent_stub_config_file_pull_url(base_url: str, name: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/files/{name}/pull"
+
+
+def agent_stub_config_push_url(base_url: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/push"
+
+
+def agent_stub_config_env_url(base_url: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/env"
+
+
+def agent_stub_config_note_url(base_url: str) -> str:
+ return f"{_require_http_base_url(base_url)}/config/note"
+
+
def is_canonical_dify_file_reference(reference: str) -> bool:
"""Return whether one string matches Dify's opaque file reference format."""
prefix = "dify-file-ref:"
@@ -189,8 +218,6 @@ class AgentStubFileUploadResponse(BaseModel):
upload_url: str
- model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
-
class AgentStubFileMapping(BaseModel):
"""Public file mapping used by download-request control-plane calls."""
@@ -234,8 +261,6 @@ class AgentStubFileDownloadResponse(BaseModel):
size: int
download_url: str
- model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
-
class AgentStubDriveFileRef(BaseModel):
"""Trusted file reference used by Agent Stub drive commit requests."""
@@ -294,14 +319,94 @@ class AgentStubDriveManifestResponse(BaseModel):
items: list[AgentStubDriveItem]
- model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
-
class AgentStubDriveCommitResponse(BaseModel):
"""Response body for one Agent Stub drive commit request."""
items: list[AgentStubDriveItem]
+
+class AgentStubConfigVersionInfo(BaseModel):
+ id: str
+ kind: Literal["snapshot", "draft", "build_draft"]
+ writable: bool
+
+
+class AgentStubConfigSkillItem(BaseModel):
+ name: str
+ description: str
+ size: int | None = None
+ hash: str | None = None
+ mime_type: str | None = None
+
+
+class AgentStubConfigSkillItemsResponse(BaseModel):
+ items: list[AgentStubConfigSkillItem] = Field(default_factory=list)
+
+
+class AgentStubConfigFileItem(BaseModel):
+ name: str
+ size: int | None = None
+ hash: str | None = None
+ mime_type: str | None = None
+
+
+class AgentStubConfigFileItemsResponse(BaseModel):
+ items: list[AgentStubConfigFileItem] = Field(default_factory=list)
+
+
+class AgentStubConfigManifestResponse(BaseModel):
+ agent_id: str
+ config_version: AgentStubConfigVersionInfo
+ skills: AgentStubConfigSkillItemsResponse = Field(default_factory=AgentStubConfigSkillItemsResponse)
+ files: AgentStubConfigFileItemsResponse = Field(default_factory=AgentStubConfigFileItemsResponse)
+ env_keys: list[str] = Field(default_factory=list)
+ note: str = ""
+
+
+class AgentStubConfigFileRef(BaseModel):
+ kind: Literal["upload_file", "tool_file"]
+ id: str
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentStubConfigPushFileItem(BaseModel):
+ name: str
+ file_ref: AgentStubConfigFileRef | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentStubConfigPushSkillItem(BaseModel):
+ name: str
+ file_ref: AgentStubConfigFileRef | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentStubConfigPushRequest(BaseModel):
+ files: list[AgentStubConfigPushFileItem] = Field(default_factory=list)
+ skills: list[AgentStubConfigPushSkillItem] = Field(default_factory=list)
+ env_text: str | None = None
+ note: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentStubConfigPushResponse(AgentStubConfigManifestResponse):
+ """Updated config manifest returned after one config push."""
+
+
+class AgentStubConfigEnvUpdateRequest(BaseModel):
+ env_text: str
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class AgentStubConfigNoteUpdateRequest(BaseModel):
+ note: str
+
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
@@ -325,6 +430,19 @@ __all__ = [
"AgentStubConnectRequest",
"AgentStubConnectResponse",
"AgentStubEndpoint",
+ "AgentStubConfigEnvUpdateRequest",
+ "AgentStubConfigFileItem",
+ "AgentStubConfigFileItemsResponse",
+ "AgentStubConfigFileRef",
+ "AgentStubConfigManifestResponse",
+ "AgentStubConfigNoteUpdateRequest",
+ "AgentStubConfigPushFileItem",
+ "AgentStubConfigPushRequest",
+ "AgentStubConfigPushResponse",
+ "AgentStubConfigPushSkillItem",
+ "AgentStubConfigSkillItem",
+ "AgentStubConfigSkillItemsResponse",
+ "AgentStubConfigVersionInfo",
"AgentStubDriveCommitItem",
"AgentStubDriveCommitRequest",
"AgentStubDriveCommitResponse",
@@ -337,6 +455,13 @@ __all__ = [
"AgentStubFileUploadRequest",
"AgentStubFileUploadResponse",
"AgentStubURLScheme",
+ "agent_stub_config_env_url",
+ "agent_stub_config_file_pull_url",
+ "agent_stub_config_manifest_url",
+ "agent_stub_config_note_url",
+ "agent_stub_config_push_url",
+ "agent_stub_config_skill_inspect_url",
+ "agent_stub_config_skill_pull_url",
"agent_stub_connections_url",
"agent_stub_drive_base_for_ref",
"agent_stub_drive_commit_url",
diff --git a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_config.py b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_config.py
new file mode 100644
index 00000000000..46f4a13bb77
--- /dev/null
+++ b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_config.py
@@ -0,0 +1,262 @@
+"""Server-side Dify API client for Agent Stub config endpoints.
+
+Config requests are scoped entirely by the signed execution context carried in
+the Agent Stub token. Tenant, agent, user, and config-version identifiers come
+only from that trusted context; sandbox request bodies contribute only mutable
+content such as asset names, env text, and note text.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any, Protocol
+
+import httpx
+from pydantic import ValidationError
+
+from dify_agent.agent_stub.protocol.agent_stub import (
+ AgentStubConfigManifestResponse,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
+)
+from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubPrincipal
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+
+
+class AgentStubConfigRequestHandler(Protocol):
+ async def manifest(self, *, principal: AgentStubPrincipal) -> AgentStubConfigManifestResponse: ...
+
+ async def pull_skill(self, *, principal: AgentStubPrincipal, name: str) -> bytes: ...
+
+ async def inspect_skill(self, *, principal: AgentStubPrincipal, name: str) -> dict[str, object]: ...
+
+ async def pull_file(self, *, principal: AgentStubPrincipal, name: str) -> bytes: ...
+
+ async def push(
+ self,
+ *,
+ principal: AgentStubPrincipal,
+ request: AgentStubConfigPushRequest,
+ ) -> AgentStubConfigPushResponse: ...
+
+ async def update_env(self, *, principal: AgentStubPrincipal, env_text: str) -> dict[str, object]: ...
+
+ async def update_note(self, *, principal: AgentStubPrincipal, note: str) -> dict[str, object]: ...
+
+
+class AgentStubConfigRequestError(RuntimeError):
+ status_code: int
+ detail: object
+
+ def __init__(self, status_code: int, detail: object) -> None:
+ self.status_code = status_code
+ self.detail = detail
+ super().__init__(str(detail))
+
+
+@dataclass(slots=True)
+class DifyApiAgentStubConfigRequestHandler:
+ """Call Dify API inner config endpoints on behalf of authenticated sandboxes.
+
+ The sandbox never chooses tenant, agent, user, or config-version scope
+ directly. Those routing fields are derived from the signed execution
+ context, while request payloads only carry mutable config content.
+ """
+
+ inner_api_url: str
+ inner_api_key: str
+ timeout: httpx.Timeout | float = 30.0
+
+ async def manifest(self, *, principal: AgentStubPrincipal) -> AgentStubConfigManifestResponse:
+ execution_context = self._require_config_context(principal.execution_context)
+ payload = await self._get_inner_api_json(
+ f"/inner/api/agent-config/{execution_context.agent_id}/manifest",
+ self._config_query_params(execution_context),
+ )
+ try:
+ return AgentStubConfigManifestResponse.model_validate(payload)
+ except ValidationError as exc:
+ raise AgentStubConfigRequestError(502, "Dify API config manifest response is invalid") from exc
+
+ async def pull_skill(self, *, principal: AgentStubPrincipal, name: str) -> bytes:
+ execution_context = self._require_config_context(principal.execution_context)
+ return await self._get_inner_api_bytes(
+ f"/inner/api/agent-config/{execution_context.agent_id}/skills/{name}/pull",
+ self._config_query_params(execution_context),
+ )
+
+ async def inspect_skill(self, *, principal: AgentStubPrincipal, name: str) -> dict[str, object]:
+ execution_context = self._require_config_context(principal.execution_context)
+ payload = await self._get_inner_api_json(
+ f"/inner/api/agent-config/{execution_context.agent_id}/skills/{name}/inspect",
+ self._config_query_params(execution_context),
+ )
+ if not isinstance(payload, dict):
+ raise AgentStubConfigRequestError(502, "Dify API config skill inspect response is invalid")
+ return payload
+
+ async def pull_file(self, *, principal: AgentStubPrincipal, name: str) -> bytes:
+ execution_context = self._require_config_context(principal.execution_context)
+ return await self._get_inner_api_bytes(
+ f"/inner/api/agent-config/{execution_context.agent_id}/files/{name}/pull",
+ self._config_query_params(execution_context),
+ )
+
+ async def push(
+ self,
+ *,
+ principal: AgentStubPrincipal,
+ request: AgentStubConfigPushRequest,
+ ) -> AgentStubConfigPushResponse:
+ execution_context = self._require_user_context(self._require_config_context(principal.execution_context))
+ payload = await self._post_inner_api_json(
+ f"/inner/api/agent-config/{execution_context.agent_id}/push",
+ {
+ "tenant_id": execution_context.tenant_id,
+ "user_id": execution_context.user_id,
+ "config_version_id": execution_context.agent_config_version_id,
+ "config_version_kind": execution_context.agent_config_version_kind,
+ **request.model_dump(mode="json", exclude_none=True),
+ },
+ )
+ try:
+ return AgentStubConfigPushResponse.model_validate(payload)
+ except ValidationError as exc:
+ raise AgentStubConfigRequestError(502, "Dify API config push response is invalid") from exc
+
+ async def update_env(self, *, principal: AgentStubPrincipal, env_text: str) -> dict[str, object]:
+ execution_context = self._require_user_context(self._require_config_context(principal.execution_context))
+ payload = await self._patch_inner_api_json(
+ f"/inner/api/agent-config/{execution_context.agent_id}/env",
+ {
+ "tenant_id": execution_context.tenant_id,
+ "user_id": execution_context.user_id,
+ "config_version_id": execution_context.agent_config_version_id,
+ "config_version_kind": execution_context.agent_config_version_kind,
+ "env_text": env_text,
+ },
+ )
+ if not isinstance(payload, dict):
+ raise AgentStubConfigRequestError(502, "Dify API config env response is invalid")
+ return payload
+
+ async def update_note(self, *, principal: AgentStubPrincipal, note: str) -> dict[str, object]:
+ execution_context = self._require_user_context(self._require_config_context(principal.execution_context))
+ payload = await self._put_inner_api_json(
+ f"/inner/api/agent-config/{execution_context.agent_id}/note",
+ {
+ "tenant_id": execution_context.tenant_id,
+ "user_id": execution_context.user_id,
+ "config_version_id": execution_context.agent_config_version_id,
+ "config_version_kind": execution_context.agent_config_version_kind,
+ "note": note,
+ },
+ )
+ if not isinstance(payload, dict):
+ raise AgentStubConfigRequestError(502, "Dify API config note response is invalid")
+ return payload
+
+ @staticmethod
+ def _require_config_context(execution_context: DifyExecutionContextLayerConfig) -> DifyExecutionContextLayerConfig:
+ if execution_context.agent_id is None:
+ raise AgentStubConfigRequestError(400, "execution context agent_id is required for config operations")
+ if execution_context.agent_config_version_id is None:
+ raise AgentStubConfigRequestError(400, "execution context agent_config_version_id is required")
+ if execution_context.agent_config_version_kind is None:
+ raise AgentStubConfigRequestError(400, "execution context agent_config_version_kind is required")
+ return execution_context
+
+ @staticmethod
+ def _require_user_context(execution_context: DifyExecutionContextLayerConfig) -> DifyExecutionContextLayerConfig:
+ if execution_context.user_id is None:
+ raise AgentStubConfigRequestError(400, "execution context user_id is required for config write operations")
+ return execution_context
+
+ @staticmethod
+ def _config_query_params(execution_context: DifyExecutionContextLayerConfig) -> dict[str, str]:
+ params = {
+ "tenant_id": execution_context.tenant_id,
+ "config_version_id": execution_context.agent_config_version_id or "",
+ "config_version_kind": execution_context.agent_config_version_kind or "",
+ }
+ if execution_context.user_id is not None:
+ params["user_id"] = execution_context.user_id
+ return params
+
+ async def _get_inner_api_json(self, path: str, params: Mapping[str, str]) -> object:
+ response = await self._request("GET", path, params=dict(params))
+ return self._normalize_json_payload(
+ response, invalid_json_detail="Dify API config request returned invalid JSON"
+ )
+
+ async def _get_inner_api_bytes(self, path: str, params: Mapping[str, str]) -> bytes:
+ response = await self._request("GET", path, params=dict(params))
+ if response.is_error:
+ detail = self._normalize_json_payload(
+ response,
+ invalid_json_detail="Dify API config request returned invalid JSON",
+ )
+ raise AgentStubConfigRequestError(
+ response.status_code, detail.get("detail", detail) if isinstance(detail, dict) else detail
+ )
+ return response.content
+
+ async def _post_inner_api_json(self, path: str, payload: Mapping[str, Any]) -> object:
+ response = await self._request("POST", path, json=dict(payload))
+ return self._normalize_json_payload(
+ response, invalid_json_detail="Dify API config request returned invalid JSON"
+ )
+
+ async def _patch_inner_api_json(self, path: str, payload: Mapping[str, Any]) -> object:
+ response = await self._request("PATCH", path, json=dict(payload))
+ return self._normalize_json_payload(
+ response, invalid_json_detail="Dify API config request returned invalid JSON"
+ )
+
+ async def _put_inner_api_json(self, path: str, payload: Mapping[str, Any]) -> object:
+ response = await self._request("PUT", path, json=dict(payload))
+ return self._normalize_json_payload(
+ response, invalid_json_detail="Dify API config request returned invalid JSON"
+ )
+
+ async def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Mapping[str, str] | None = None,
+ json: Mapping[str, Any] | None = None,
+ ) -> httpx.Response:
+ url = f"{self.inner_api_url.rstrip('/')}{path}"
+ async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True, trust_env=False) as client:
+ try:
+ return await client.request(
+ method,
+ url,
+ params=dict(params or {}),
+ json=dict(json or {}) if json is not None else None,
+ headers={"X-Inner-Api-Key": self.inner_api_key},
+ )
+ except httpx.TimeoutException as exc:
+ raise AgentStubConfigRequestError(504, "Dify API config request timed out") from exc
+ except httpx.RequestError as exc:
+ raise AgentStubConfigRequestError(502, f"Dify API config request failed: {exc}") from exc
+
+ @staticmethod
+ def _normalize_json_payload(response: httpx.Response, *, invalid_json_detail: str) -> object:
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise AgentStubConfigRequestError(502, invalid_json_detail) from exc
+ if response.is_error:
+ detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
+ raise AgentStubConfigRequestError(response.status_code, detail)
+ return payload
+
+
+__all__ = [
+ "AgentStubConfigRequestError",
+ "AgentStubConfigRequestHandler",
+ "DifyApiAgentStubConfigRequestHandler",
+]
diff --git a/dify-agent/src/dify_agent/agent_stub/server/app.py b/dify-agent/src/dify_agent/agent_stub/server/app.py
index 8467dea79f4..ba16abf18c7 100644
--- a/dify-agent/src/dify_agent/agent_stub/server/app.py
+++ b/dify-agent/src/dify_agent/agent_stub/server/app.py
@@ -23,6 +23,7 @@ def create_agent_stub_app(settings: ServerSettings | None = None) -> FastAPI:
create_agent_stub_router(
token_codec=resolved_settings.create_agent_stub_token_codec(),
file_request_handler=resolved_settings.create_agent_stub_file_request_handler(),
+ config_request_handler=resolved_settings.create_agent_stub_config_request_handler(),
drive_request_handler=resolved_settings.create_agent_stub_drive_request_handler(),
)
)
diff --git a/dify-agent/src/dify_agent/agent_stub/server/control_plane.py b/dify-agent/src/dify_agent/agent_stub/server/control_plane.py
index ef747bd6d0e..5b887af8288 100644
--- a/dify-agent/src/dify_agent/agent_stub/server/control_plane.py
+++ b/dify-agent/src/dify_agent/agent_stub/server/control_plane.py
@@ -1,4 +1,10 @@
-"""Shared Agent Stub control-plane service used by HTTP and gRPC transports."""
+"""Shared Agent Stub control-plane service used by HTTP and gRPC transports.
+
+This layer owns the authenticated control-plane delegation for file, config,
+and drive operations. Transport adapters validate transport DTOs first, then
+call into this service so auth, handler lookup, and error mapping stay shared
+across HTTP and gRPC.
+"""
from __future__ import annotations
@@ -8,6 +14,9 @@ from uuid import uuid4
from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubConnectResponse,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
AgentStubDriveCommitRequest,
AgentStubDriveCommitResponse,
AgentStubDriveManifestResponse,
@@ -16,6 +25,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubFileUploadRequest,
AgentStubFileUploadResponse,
)
+from dify_agent.agent_stub.server.agent_stub_config import AgentStubConfigRequestError, AgentStubConfigRequestHandler
from dify_agent.agent_stub.server.agent_stub_drive import AgentStubDriveRequestError, AgentStubDriveRequestHandler
from dify_agent.agent_stub.server.agent_stub_files import AgentStubFileRequestError, AgentStubFileRequestHandler
from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubPrincipal, AgentStubTokenCodec, AgentStubTokenError
@@ -47,11 +57,12 @@ class AgentStubControlPlaneService:
HTTP and gRPC adapters validate or decode transport payloads before calling
this service, so this layer focuses only on shared auth, connection-id
- generation, plus file and drive request delegation.
+ generation, plus file, config, and drive request delegation.
"""
token_codec: AgentStubTokenCodec | None
file_request_handler: AgentStubFileRequestHandler | None = None
+ config_request_handler: AgentStubConfigRequestHandler | None = None
drive_request_handler: AgentStubDriveRequestHandler | None = None
connection_id_factory: Callable[[], str] = field(default=lambda: str(uuid4()))
@@ -107,6 +118,96 @@ class AgentStubControlPlaneService:
except AgentStubDriveRequestError as exc:
raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+ async def get_config_manifest(
+ self,
+ *,
+ authorization: str | None,
+ ) -> AgentStubConfigManifestResponse:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.manifest(principal=principal)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def pull_config_skill(
+ self,
+ *,
+ name: str,
+ authorization: str | None,
+ ) -> bytes:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.pull_skill(principal=principal, name=name)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def inspect_config_skill(
+ self,
+ *,
+ name: str,
+ authorization: str | None,
+ ) -> dict[str, object]:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.inspect_skill(principal=principal, name=name)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def pull_config_file(
+ self,
+ *,
+ name: str,
+ authorization: str | None,
+ ) -> bytes:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.pull_file(principal=principal, name=name)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def push_config(
+ self,
+ *,
+ request: AgentStubConfigPushRequest,
+ authorization: str | None,
+ ) -> AgentStubConfigPushResponse:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.push(principal=principal, request=request)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def update_config_env(
+ self,
+ *,
+ env_text: str,
+ authorization: str | None,
+ ) -> dict[str, object]:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.update_env(principal=principal, env_text=env_text)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
+ async def update_config_note(
+ self,
+ *,
+ note: str,
+ authorization: str | None,
+ ) -> dict[str, object]:
+ principal = self._authenticate(authorization)
+ handler = self._require_config_request_handler()
+ try:
+ return await handler.update_note(principal=principal, note=note)
+ except AgentStubConfigRequestError as exc:
+ raise AgentStubControlPlaneError(exc.status_code, exc.detail) from exc
+
async def commit_drive(
self,
*,
@@ -135,6 +236,11 @@ class AgentStubControlPlaneService:
raise AgentStubConfigurationError(503, "Agent Stub file API is not configured")
return self.file_request_handler
+ def _require_config_request_handler(self) -> AgentStubConfigRequestHandler:
+ if self.config_request_handler is None:
+ raise AgentStubConfigurationError(503, "Agent Stub config API is not configured")
+ return self.config_request_handler
+
def _require_drive_request_handler(self) -> AgentStubDriveRequestHandler:
if self.drive_request_handler is None:
raise AgentStubConfigurationError(503, "Agent Stub drive API is not configured")
diff --git a/dify-agent/src/dify_agent/agent_stub/server/router.py b/dify-agent/src/dify_agent/agent_stub/server/router.py
index fa506ab0188..5c77202093d 100644
--- a/dify-agent/src/dify_agent/agent_stub/server/router.py
+++ b/dify-agent/src/dify_agent/agent_stub/server/router.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from fastapi import APIRouter
+from dify_agent.agent_stub.server.agent_stub_config import AgentStubConfigRequestHandler
from dify_agent.agent_stub.server.agent_stub_drive import AgentStubDriveRequestHandler
from dify_agent.agent_stub.server.agent_stub_files import AgentStubFileRequestHandler
from dify_agent.agent_stub.server.routes.agent_stub import create_agent_stub_http_router
@@ -23,9 +24,15 @@ def create_agent_stub_router(
token_codec: AgentStubTokenCodec | None,
file_request_handler: AgentStubFileRequestHandler | None = None,
drive_request_handler: AgentStubDriveRequestHandler | None = None,
+ config_request_handler: AgentStubConfigRequestHandler | None = None,
) -> APIRouter:
"""Build the embeddable stub router from pre-built server dependencies."""
- return create_agent_stub_http_router(token_codec, file_request_handler, drive_request_handler)
+ return create_agent_stub_http_router(
+ token_codec,
+ file_request_handler,
+ drive_request_handler,
+ config_request_handler,
+ )
__all__ = ["create_agent_stub_router"]
diff --git a/dify-agent/src/dify_agent/agent_stub/server/routes/agent_stub.py b/dify-agent/src/dify_agent/agent_stub/server/routes/agent_stub.py
index 72077c88545..411fcc4c6af 100644
--- a/dify-agent/src/dify_agent/agent_stub/server/routes/agent_stub.py
+++ b/dify-agent/src/dify_agent/agent_stub/server/routes/agent_stub.py
@@ -2,17 +2,22 @@
The router is a thin HTTP adapter around ``AgentStubControlPlaneService``. It
keeps FastAPI-specific request parsing and HTTPException translation here while
-sharing auth, DTO validation, connection-id generation, and file/drive
+sharing auth, DTO validation, connection-id generation, and file/config/drive
delegation with the gRPC transport.
"""
from __future__ import annotations
-from fastapi import APIRouter, Header, HTTPException
+from fastapi import APIRouter, Header, HTTPException, Response
from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubConnectRequest,
AgentStubConnectResponse,
+ AgentStubConfigEnvUpdateRequest,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigNoteUpdateRequest,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
AgentStubDriveCommitRequest,
AgentStubDriveCommitResponse,
AgentStubDriveManifestResponse,
@@ -21,6 +26,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubFileUploadRequest,
AgentStubFileUploadResponse,
)
+from dify_agent.agent_stub.server.agent_stub_config import AgentStubConfigRequestHandler
from dify_agent.agent_stub.server.agent_stub_drive import AgentStubDriveRequestHandler
from dify_agent.agent_stub.server.agent_stub_files import AgentStubFileRequestHandler
from dify_agent.agent_stub.server.control_plane import AgentStubControlPlaneError, AgentStubControlPlaneService
@@ -31,10 +37,13 @@ def create_agent_stub_http_router(
token_codec: AgentStubTokenCodec | None,
file_request_handler: AgentStubFileRequestHandler | None = None,
drive_request_handler: AgentStubDriveRequestHandler | None = None,
+ config_request_handler: AgentStubConfigRequestHandler | None = None,
) -> APIRouter:
"""Create HTTP routes bound to the application's Agent Stub dependencies."""
router = APIRouter(prefix="/agent-stub", tags=["agent-stub"])
- service = AgentStubControlPlaneService(token_codec, file_request_handler, drive_request_handler)
+ service = AgentStubControlPlaneService(
+ token_codec, file_request_handler, config_request_handler, drive_request_handler
+ )
@router.post("/connections", response_model=AgentStubConnectResponse)
async def create_connection(
@@ -67,6 +76,77 @@ def create_agent_stub_http_router(
except AgentStubControlPlaneError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+ @router.get("/config/manifest", response_model=AgentStubConfigManifestResponse)
+ async def get_config_manifest(
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> AgentStubConfigManifestResponse:
+ try:
+ return await service.get_config_manifest(authorization=authorization)
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.get("/config/skills/{name}/pull")
+ async def pull_config_skill(
+ name: str,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> Response:
+ try:
+ payload = await service.pull_config_skill(name=name, authorization=authorization)
+ return Response(content=payload, media_type="application/zip")
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.get("/config/skills/{name}/inspect")
+ async def inspect_config_skill(
+ name: str,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> dict[str, object]:
+ try:
+ return await service.inspect_config_skill(name=name, authorization=authorization)
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.get("/config/files/{name}/pull")
+ async def pull_config_file(
+ name: str,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> Response:
+ try:
+ payload = await service.pull_config_file(name=name, authorization=authorization)
+ return Response(content=payload, media_type="application/octet-stream")
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.post("/config/push", response_model=AgentStubConfigPushResponse)
+ async def push_config(
+ request: AgentStubConfigPushRequest,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> AgentStubConfigPushResponse:
+ try:
+ return await service.push_config(request=request, authorization=authorization)
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.patch("/config/env")
+ async def update_config_env(
+ request: AgentStubConfigEnvUpdateRequest,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> dict[str, object]:
+ try:
+ return await service.update_config_env(env_text=request.env_text, authorization=authorization)
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
+ @router.put("/config/note")
+ async def update_config_note(
+ request: AgentStubConfigNoteUpdateRequest,
+ authorization: str | None = Header(default=None, alias="Authorization"),
+ ) -> dict[str, object]:
+ try:
+ return await service.update_config_note(note=request.note, authorization=authorization)
+ except AgentStubControlPlaneError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+
@router.get("/drive/manifest", response_model=AgentStubDriveManifestResponse)
async def get_drive_manifest(
prefix: str = "",
diff --git a/dify-agent/src/dify_agent/layers/config/__init__.py b/dify-agent/src/dify_agent/layers/config/__init__.py
new file mode 100644
index 00000000000..f5c3d0c4b3a
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/config/__init__.py
@@ -0,0 +1,19 @@
+"""Client-safe exports for the Dify config runtime catalog DTOs."""
+
+from dify_agent.layers.config.configs import (
+ DIFY_CONFIG_LAYER_TYPE_ID,
+ DifyConfigFileConfig,
+ DifyConfigLayerConfig,
+ DifyConfigRuntimeState,
+ DifyConfigSkillConfig,
+ DifyConfigVersionConfig,
+)
+
+__all__ = [
+ "DIFY_CONFIG_LAYER_TYPE_ID",
+ "DifyConfigFileConfig",
+ "DifyConfigLayerConfig",
+ "DifyConfigRuntimeState",
+ "DifyConfigSkillConfig",
+ "DifyConfigVersionConfig",
+]
diff --git a/dify-agent/src/dify_agent/layers/config/configs.py b/dify-agent/src/dify_agent/layers/config/configs.py
new file mode 100644
index 00000000000..c3d20c878f1
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/config/configs.py
@@ -0,0 +1,86 @@
+"""Client-safe DTOs for the Dify config declaration layer."""
+
+from typing import ClassVar, Final, Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from agenton.layers import LayerConfig
+
+
+DIFY_CONFIG_LAYER_TYPE_ID: Final[str] = "dify.config"
+
+
+class DifyConfigVersionConfig(BaseModel):
+ """Agent config version metadata visible to the runtime prompt."""
+
+ id: str | None = None
+ kind: Literal["snapshot", "draft", "build_draft"] = "snapshot"
+ writable: bool = False
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyConfigSkillConfig(BaseModel):
+ """Prompt-safe summary of one Agent Soul config skill."""
+
+ name: str
+ description: str = ""
+ size: int | None = None
+ mime_type: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyConfigFileConfig(BaseModel):
+ """Prompt-safe summary of one Agent Soul config file."""
+
+ name: str
+ size: int | None = None
+ mime_type: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyConfigLayerConfig(LayerConfig):
+ """Agent Soul config context plus eager-pull instructions for prompt mentions."""
+
+ agent_id: str | None = None
+ config_version: DifyConfigVersionConfig | None = None
+ skills: list[DifyConfigSkillConfig] = Field(default_factory=list)
+ files: list[DifyConfigFileConfig] = Field(default_factory=list)
+ env_keys: list[str] = Field(default_factory=list)
+ note: str = ""
+ mentioned_skill_names: list[str] = Field(default_factory=list)
+ mentioned_file_names: list[str] = Field(default_factory=list)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyConfigRuntimeState(BaseModel):
+ """Serializable config-layer values computed once during context entry.
+
+ The ``push_spec_*`` fields are compatibility leftovers from the removed root
+ JSON-spec config mutation workflow. This change keeps them in the runtime-state
+ schema to avoid snapshot churn, but new code should treat them as inert
+ compatibility fields rather than active prompt data.
+ """
+
+ pulled_skill_outputs: dict[str, str] = Field(default_factory=dict)
+ pulled_file_outputs: dict[str, str] = Field(default_factory=dict)
+ config_context_json: str = ""
+ config_cli_help: dict[str, str] = Field(default_factory=dict)
+ push_spec_semantics: str = ""
+ push_spec_json_schema: str = ""
+ push_spec_example: str = ""
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", validate_assignment=True)
+
+
+__all__ = [
+ "DIFY_CONFIG_LAYER_TYPE_ID",
+ "DifyConfigFileConfig",
+ "DifyConfigLayerConfig",
+ "DifyConfigRuntimeState",
+ "DifyConfigSkillConfig",
+ "DifyConfigVersionConfig",
+]
diff --git a/dify-agent/src/dify_agent/layers/config/layer.py b/dify-agent/src/dify_agent/layers/config/layer.py
new file mode 100644
index 00000000000..5bec83d6173
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/config/layer.py
@@ -0,0 +1,227 @@
+"""Runtime Dify config layer with shell-backed eager pulls."""
+
+from __future__ import annotations
+
+import asyncio
+import shlex
+from dataclasses import dataclass
+from typing import ClassVar
+
+from typing_extensions import Self, override
+
+from agenton.layers import LayerDeps, PlainLayer
+from dify_agent.agent_stub.cli.main import render_agent_stub_cli_help
+from dify_agent.layers.config.configs import (
+ DIFY_CONFIG_LAYER_TYPE_ID,
+ DifyConfigLayerConfig,
+ DifyConfigRuntimeState,
+)
+from dify_agent.layers.shell.layer import DifyShellLayer
+
+_CONFIG_CONTEXT_HEADING = "Agent config context from the current Agent Soul:"
+_CONFIG_CLI_USAGE_PROMPT = """Agent config CLI usage is available inside shell jobs. The command help below is generated
+from the same `dify-agent` CLI definitions available in shell jobs.
+
+Local edits to config files, skills, env, or notes are not saved by themselves. Config changes are saved only by a
+matching resource mutation command. Those commands are available only when the Agent config context reports
+`config_version.kind` as `build_draft` and `config_version.writable` as true."""
+_CONFIG_CLI_HELP_COMMANDS: dict[str, tuple[str, ...]] = {
+ "dify-agent config --help": ("config",),
+ "dify-agent config manifest --help": ("config", "manifest"),
+ "dify-agent config skills pull --help": ("config", "skills", "pull"),
+ "dify-agent config files pull --help": ("config", "files", "pull"),
+ "dify-agent config env pull --help": ("config", "env", "pull"),
+ "dify-agent config note pull --help": ("config", "note", "pull"),
+}
+_CONFIG_CLI_MUTATION_HELP_COMMANDS: dict[str, tuple[str, ...]] = {
+ "dify-agent config note push --help": ("config", "note", "push"),
+ "dify-agent config env push --help": ("config", "env", "push"),
+ "dify-agent config files push --help": ("config", "files", "push"),
+ "dify-agent config files delete --help": ("config", "files", "delete"),
+ "dify-agent config skills push --help": ("config", "skills", "push"),
+ "dify-agent config skills delete --help": ("config", "skills", "delete"),
+}
+_CONFIG_CONTEXT_EXCLUDE = {"mentioned_skill_names": True, "mentioned_file_names": True}
+
+
+class DifyConfigLayerError(RuntimeError):
+ """Raised when one eager-pull config operation fails."""
+
+
+class DifyConfigDeps(LayerDeps):
+ shell: DifyShellLayer # pyright: ignore[reportUninitializedInstanceVariable]
+
+
+@dataclass(slots=True)
+class DifyConfigLayer(PlainLayer[DifyConfigDeps, DifyConfigLayerConfig, DifyConfigRuntimeState]):
+ """Config runtime layer that materializes prompt-mentioned targets via shell."""
+
+ type_id: ClassVar[str | None] = DIFY_CONFIG_LAYER_TYPE_ID
+
+ config: DifyConfigLayerConfig
+
+ @classmethod
+ @override
+ def from_config(cls, config: DifyConfigLayerConfig) -> Self:
+ return cls(config=DifyConfigLayerConfig.model_validate(config))
+
+ @property
+ @override
+ def prefix_prompts(self) -> list[str]:
+ return [self.build_prompt_context()]
+
+ @property
+ @override
+ def suffix_prompts(self) -> list[str]:
+ return [self.build_suffix_prompt()]
+
+ @override
+ async def on_context_create(self) -> None:
+ await self._initialize_context()
+
+ @override
+ async def on_context_resume(self) -> None:
+ return None
+
+ async def _initialize_context(self) -> None:
+ self._initialize_runtime_prompt_state()
+ await self._pull_mentioned_targets()
+
+ def _initialize_runtime_prompt_state(self) -> None:
+ command_paths = dict(_CONFIG_CLI_HELP_COMMANDS)
+ if self._config_writable:
+ command_paths.update(_CONFIG_CLI_MUTATION_HELP_COMMANDS)
+ self.runtime_state.config_context_json = self._format_config_context_json()
+ self.runtime_state.config_cli_help = {
+ command: render_agent_stub_cli_help(args) for command, args in command_paths.items()
+ }
+ self.runtime_state.push_spec_semantics = ""
+ self.runtime_state.push_spec_json_schema = ""
+ self.runtime_state.push_spec_example = ""
+
+ def build_prompt_context(self) -> str:
+ sections: list[str] = []
+
+ loaded_skill_sections = []
+ for name in self.config.mentioned_skill_names:
+ output = self.runtime_state.pulled_skill_outputs.get(name)
+ if output is None:
+ continue
+ loaded_skill_sections.append(f"Name: {name}\nPull output:\n{output}")
+ if loaded_skill_sections:
+ sections.append("Loaded mentioned skills:\n\n" + "\n\n".join(loaded_skill_sections))
+
+ mentioned_file_sections = [
+ f"Name: {name}\nPull output:\n{self.runtime_state.pulled_file_outputs[name]}"
+ for name in self.config.mentioned_file_names
+ if name in self.runtime_state.pulled_file_outputs
+ ]
+ if mentioned_file_sections:
+ sections.append("Mentioned files pulled locally:\n\n" + "\n\n".join(mentioned_file_sections))
+
+ return "\n\n".join(section for section in sections if section)
+
+ def build_suffix_prompt(self) -> str:
+ sections: list[str] = []
+ if self.runtime_state.config_context_json:
+ sections.append(f"{_CONFIG_CONTEXT_HEADING}\n{self.runtime_state.config_context_json}")
+ usage_lines = [_CONFIG_CLI_USAGE_PROMPT]
+ if cli_help := self._format_config_cli_help():
+ usage_lines.append(cli_help)
+ sections.append("\n".join(usage_lines))
+ return "\n\n".join(section for section in sections if section)
+
+ @property
+ def _config_writable(self) -> bool:
+ return self.config.config_version is not None and self.config.config_version.writable
+
+ def _format_config_cli_help(self) -> str:
+ commands = list(_CONFIG_CLI_HELP_COMMANDS)
+ if self._config_writable:
+ commands.extend(_CONFIG_CLI_MUTATION_HELP_COMMANDS)
+ command_sections = [
+ f"$ {command}\n{self.runtime_state.config_cli_help[command]}"
+ for command in commands
+ if command in self.runtime_state.config_cli_help
+ ]
+ if not command_sections:
+ return ""
+ return "Agent config CLI help:\n" + "\n\n".join(command_sections)
+
+ def _format_config_context_json(self) -> str:
+ return self.config.model_dump_json(exclude=_CONFIG_CONTEXT_EXCLUDE, exclude_none=True)
+
+ async def _pull_mentioned_targets(self) -> None:
+ self.runtime_state.pulled_skill_outputs = {}
+ self.runtime_state.pulled_file_outputs = {}
+ if not self.config.mentioned_skill_names and not self.config.mentioned_file_names:
+ return
+
+ tasks = [
+ *(self._pull_mentioned_skill(name) for name in self.config.mentioned_skill_names),
+ *(self._pull_mentioned_file(name) for name in self.config.mentioned_file_names),
+ ]
+ await asyncio.gather(*tasks)
+
+ async def _pull_mentioned_skill(self, name: str) -> None:
+ result = await self.deps.shell.run_remote_script(
+ self._build_shell_skill_pull_script(name),
+ inject_agent_stub_env=True,
+ )
+ if result.exit_code != 0:
+ raise DifyConfigLayerError(
+ "config mentioned skill pull failed in shell: "
+ f"{result.status} exit_code={result.exit_code}\n{result.output}"
+ )
+ if not result.output_complete:
+ reason = result.incomplete_reason or "unknown"
+ raise DifyConfigLayerError(
+ f"config mentioned skill pull output was incomplete before the payload finished: {reason}"
+ )
+ output = result.output.strip()
+ if not output:
+ raise DifyConfigLayerError(f"missing pull output for mentioned config skill {name}")
+ self.runtime_state.pulled_skill_outputs = {
+ **self.runtime_state.pulled_skill_outputs,
+ name: output,
+ }
+
+ async def _pull_mentioned_file(self, name: str) -> None:
+ result = await self.deps.shell.run_remote_script(
+ self._build_shell_file_pull_script(name),
+ inject_agent_stub_env=True,
+ )
+ if result.exit_code != 0:
+ raise DifyConfigLayerError(
+ "config mentioned file pull failed in shell: "
+ f"{result.status} exit_code={result.exit_code}\n{result.output}"
+ )
+ if not result.output_complete:
+ reason = result.incomplete_reason or "unknown"
+ raise DifyConfigLayerError(
+ f"config mentioned file pull output was incomplete before the payload finished: {reason}"
+ )
+ output = result.output.strip()
+ if not output:
+ raise DifyConfigLayerError(f"missing pull output for mentioned config file {name}")
+ self.runtime_state.pulled_file_outputs = {
+ **self.runtime_state.pulled_file_outputs,
+ name: output,
+ }
+
+ def _build_shell_skill_pull_script(self, name: str) -> str:
+ lines = [
+ "set -eu",
+ f"dify-agent config skills pull {shlex.quote(name)}",
+ ]
+ return "\n".join(lines)
+
+ def _build_shell_file_pull_script(self, name: str) -> str:
+ lines = [
+ "set -eu",
+ f"dify-agent config files pull {shlex.quote(name)}",
+ ]
+ return "\n".join(lines)
+
+
+__all__ = ["DifyConfigLayer", "DifyConfigLayerError"]
diff --git a/dify-agent/src/dify_agent/layers/dify_core_tools/__init__.py b/dify-agent/src/dify_agent/layers/dify_core_tools/__init__.py
new file mode 100644
index 00000000000..dd8b09574cf
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/dify_core_tools/__init__.py
@@ -0,0 +1,15 @@
+"""Client-safe exports for the Dify core-tools layer DTOs and type ids."""
+
+from dify_agent.layers.dify_core_tools.configs import (
+ DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ DifyCoreToolConfig,
+ DifyCoreToolProviderType,
+ DifyCoreToolsLayerConfig,
+)
+
+__all__ = [
+ "DIFY_CORE_TOOLS_LAYER_TYPE_ID",
+ "DifyCoreToolConfig",
+ "DifyCoreToolProviderType",
+ "DifyCoreToolsLayerConfig",
+]
diff --git a/dify-agent/src/dify_agent/layers/dify_core_tools/client.py b/dify-agent/src/dify_agent/layers/dify_core_tools/client.py
new file mode 100644
index 00000000000..387185724ef
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/dify_core_tools/client.py
@@ -0,0 +1,208 @@
+"""Async client for the Dify API inner core-tools invoke endpoint."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import ClassVar
+
+import httpx
+from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationError
+
+from dify_agent.layers.dify_core_tools.configs import DifyCoreToolConfig
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+
+
+class DifyCoreToolsClientError(RuntimeError):
+ """Raised when the inner core-tools HTTP boundary fails."""
+
+ status_code: int | None
+ error_code: str | None
+ retryable: bool
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ status_code: int | None = None,
+ error_code: str | None = None,
+ retryable: bool,
+ ) -> None:
+ self.status_code = status_code
+ self.error_code = error_code
+ self.retryable = retryable
+ super().__init__(message)
+
+
+class DifyCoreToolsClientConfigurationError(DifyCoreToolsClientError):
+ """Raised for local layer/configuration precondition failures before HTTP I/O."""
+
+
+class _DifyCoreToolsCaller(BaseModel):
+ tenant_id: str
+ user_id: str
+ user_from: str
+ app_id: str
+ invoke_from: str
+ conversation_id: str | None = None
+ workflow_id: str | None = None
+ workflow_run_id: str | None = None
+ node_id: str | None = None
+ node_execution_id: str | None = None
+ agent_id: str | None = None
+ agent_config_version_id: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class _DifyCoreToolsRequestTool(BaseModel):
+ """Inner-API tool envelope.
+
+ `runtime_parameters` are API-prepared hidden/form/runtime values attached
+ to the tool declaration. `tool_parameters` are the live LLM/user arguments
+ passed by the runtime when invoking the tool.
+ """
+
+ provider_type: str
+ provider_id: str
+ tool_name: str
+ credential_id: str | None = None
+ tool_parameters: dict[str, JsonValue] = Field(default_factory=dict)
+ runtime_parameters: dict[str, JsonValue] = Field(default_factory=dict)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class _DifyCoreToolsInvokeRequest(BaseModel):
+ caller: _DifyCoreToolsCaller
+ tool: _DifyCoreToolsRequestTool
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyCoreToolsInvokeResponse(BaseModel):
+ messages: list[dict[str, JsonValue]] = Field(default_factory=list)
+ observation: str
+ metadata: dict[str, JsonValue] = Field(default_factory=dict)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+@dataclass(slots=True)
+class DifyCoreToolsClient:
+ """Boundary client for `POST /inner/api/agent/tools/invoke`."""
+
+ base_url: str
+ api_key: str = field(repr=False)
+ http_client: httpx.AsyncClient = field(repr=False)
+
+ def __post_init__(self) -> None:
+ self.base_url = self.base_url.rstrip("/")
+
+ async def invoke(
+ self,
+ *,
+ execution_context: DifyExecutionContextLayerConfig,
+ tool_config: DifyCoreToolConfig,
+ tool_parameters: dict[str, JsonValue],
+ ) -> DifyCoreToolsInvokeResponse:
+ _validate_execution_context(execution_context)
+
+ request_payload = _DifyCoreToolsInvokeRequest(
+ caller=_DifyCoreToolsCaller(
+ tenant_id=execution_context.tenant_id,
+ user_id=execution_context.user_id,
+ user_from=execution_context.user_from,
+ app_id=execution_context.app_id,
+ invoke_from=execution_context.invoke_from,
+ conversation_id=execution_context.conversation_id,
+ workflow_id=execution_context.workflow_id,
+ workflow_run_id=execution_context.workflow_run_id,
+ node_id=execution_context.node_id,
+ node_execution_id=execution_context.node_execution_id,
+ agent_id=execution_context.agent_id,
+ agent_config_version_id=execution_context.agent_config_version_id,
+ ),
+ tool=_DifyCoreToolsRequestTool(
+ provider_type=tool_config.provider_type,
+ provider_id=tool_config.provider_id,
+ tool_name=tool_config.tool_name,
+ credential_id=tool_config.credential_id,
+ tool_parameters=tool_parameters,
+ runtime_parameters=tool_config.runtime_parameters,
+ ),
+ )
+
+ try:
+ response = await self.http_client.post(
+ f"{self.base_url}/inner/api/agent/tools/invoke",
+ headers={
+ "X-Inner-Api-Key": self.api_key,
+ "Content-Type": "application/json",
+ },
+ json=request_payload.model_dump(mode="json"),
+ )
+ except (httpx.InvalidURL, httpx.UnsupportedProtocol) as exc:
+ raise DifyCoreToolsClientError(f"Core tools are misconfigured: {exc}", retryable=False) from exc
+ except httpx.TimeoutException as exc:
+ raise DifyCoreToolsClientError("Core tool invocation timed out.", retryable=True) from exc
+ except httpx.RequestError as exc:
+ raise DifyCoreToolsClientError(f"Core tool invocation request failed: {exc}", retryable=True) from exc
+
+ if response.status_code >= 400:
+ raise _build_http_error(response)
+
+ try:
+ return DifyCoreToolsInvokeResponse.model_validate_json(response.text)
+ except ValidationError as exc:
+ raise DifyCoreToolsClientError(
+ "Invalid core tool response from Dify API.",
+ status_code=response.status_code,
+ error_code="invalid_response",
+ retryable=False,
+ ) from exc
+
+
+def _validate_execution_context(execution_context: DifyExecutionContextLayerConfig) -> None:
+ missing_fields = [
+ field_name
+ for field_name in ("user_id", "user_from", "app_id")
+ if getattr(execution_context, field_name) is None
+ ]
+ if missing_fields:
+ missing = ", ".join(missing_fields)
+ raise DifyCoreToolsClientConfigurationError(
+ f"Missing required execution context fields: {missing}.",
+ error_code="missing_execution_context",
+ retryable=False,
+ )
+
+
+def _build_http_error(response: httpx.Response) -> DifyCoreToolsClientError:
+ detail = _decode_error_detail(response)
+ retryable = response.status_code >= 500 or response.status_code == 429
+ message = detail["message"] or f"HTTP {response.status_code}"
+ return DifyCoreToolsClientError(
+ message,
+ status_code=response.status_code,
+ error_code=detail["error_code"],
+ retryable=retryable,
+ )
+
+
+def _decode_error_detail(response: httpx.Response) -> dict[str, str | None]:
+ raw_body = response.text
+ try:
+ payload = response.json()
+ except json.JSONDecodeError:
+ payload = None
+
+ if isinstance(payload, dict):
+ error_code = payload.get("code")
+ message = payload.get("message")
+ return {
+ "error_code": error_code if isinstance(error_code, str) else None,
+ "message": message if isinstance(message, str) and message else raw_body or f"HTTP {response.status_code}",
+ }
+
+ return {"error_code": None, "message": raw_body or f"HTTP {response.status_code}"}
diff --git a/dify-agent/src/dify_agent/layers/dify_core_tools/configs.py b/dify-agent/src/dify_agent/layers/dify_core_tools/configs.py
new file mode 100644
index 00000000000..47184d04b56
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/dify_core_tools/configs.py
@@ -0,0 +1,47 @@
+"""Client-safe DTOs for the Dify core-tools Agenton layer.
+
+This layer exposes API-routed tool invocations for the Dify-owned provider
+families that should execute inside the API service boundary: `plugin`,
+`builtin`, `api`, `workflow`, and `mcp`. Prepared parameter declarations and
+LLM-facing JSON schema are still sent by the API side so the agent runtime does
+not need to inspect provider internals or storage state.
+"""
+
+from __future__ import annotations
+
+from typing import ClassVar, Final, Literal
+
+from pydantic import ConfigDict, Field, JsonValue
+
+from agenton.layers import LayerConfig
+from dify_agent.layers.dify_plugin.configs import DifyPluginToolParameter
+
+type DifyCoreToolProviderType = Literal["plugin", "builtin", "api", "workflow", "mcp"]
+
+DIFY_CORE_TOOLS_LAYER_TYPE_ID: Final[str] = "dify.core.tools"
+
+
+class DifyCoreToolConfig(LayerConfig):
+ """Prepared API-routed tool declaration exposed to the model."""
+
+ provider_type: DifyCoreToolProviderType
+ provider_id: str
+ tool_name: str
+ credential_id: str | None = None
+ name: str | None = None
+ description: str | None = None
+ runtime_parameters: dict[str, JsonValue] = Field(default_factory=dict)
+ parameters: list[DifyPluginToolParameter] = Field(default_factory=list)
+ parameters_json_schema: dict[str, JsonValue] = Field(
+ default_factory=lambda: {"type": "object", "properties": {}, "required": []}
+ )
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
+
+
+class DifyCoreToolsLayerConfig(LayerConfig):
+ """Public config for the Dify core-tools layer."""
+
+ tools: list[DifyCoreToolConfig] = Field(default_factory=list)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
diff --git a/dify-agent/src/dify_agent/layers/dify_core_tools/layer.py b/dify-agent/src/dify_agent/layers/dify_core_tools/layer.py
new file mode 100644
index 00000000000..86e60ba86d6
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/dify_core_tools/layer.py
@@ -0,0 +1,163 @@
+"""Dify core-tools layer for API-routed agent-accessible tools.
+
+This layer consumes API-prepared tool declarations for provider families that
+must execute inside the Dify API service boundary. The runtime keeps the same
+prepared-parameter contract as the direct plugin layer, but invocation itself
+is delegated to `POST /inner/api/agent/tools/invoke` so credentials and
+provider-local state stay in the API process.
+"""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from dataclasses import dataclass
+from typing import ClassVar
+
+import httpx
+from pydantic_ai import RunContext, Tool
+from pydantic_ai.tools import ToolDefinition
+from typing_extensions import Self, override
+
+from agenton.layers import LayerDeps, PlainLayer
+from dify_agent.layers.dify_core_tools.client import (
+ DifyCoreToolsClient,
+ DifyCoreToolsClientConfigurationError,
+ DifyCoreToolsClientError,
+)
+from dify_agent.layers.dify_core_tools.configs import (
+ DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ DifyCoreToolConfig,
+ DifyCoreToolsLayerConfig,
+)
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
+
+CORE_TOOL_STRICT = False
+TEMPORARY_UNAVAILABLE_OBSERVATION = "Tool is temporarily unavailable. Please continue without it if possible."
+
+
+class DifyCoreToolsDeps(LayerDeps):
+ """Dependencies required by `DifyCoreToolsLayer`."""
+
+ execution_context: DifyExecutionContextLayer # pyright: ignore[reportUninitializedInstanceVariable]
+
+
+@dataclass(slots=True)
+class DifyCoreToolsLayer(PlainLayer[DifyCoreToolsDeps, DifyCoreToolsLayerConfig]):
+ """Layer that resolves API-routed Dify tools into Pydantic AI tools."""
+
+ type_id: ClassVar[str | None] = DIFY_CORE_TOOLS_LAYER_TYPE_ID
+
+ config: DifyCoreToolsLayerConfig
+ inner_api_url: str
+ inner_api_key: str
+
+ @classmethod
+ @override
+ def from_config(cls, config: DifyCoreToolsLayerConfig) -> Self:
+ del config
+ raise TypeError("DifyCoreToolsLayer requires server-side Dify API settings and must use a provider factory.")
+
+ @classmethod
+ def from_config_with_settings(
+ cls,
+ config: DifyCoreToolsLayerConfig,
+ *,
+ inner_api_url: str,
+ inner_api_key: str,
+ ) -> Self:
+ return cls(
+ config=DifyCoreToolsLayerConfig.model_validate(config),
+ inner_api_url=inner_api_url,
+ inner_api_key=inner_api_key,
+ )
+
+ async def get_tools(self, *, http_client: httpx.AsyncClient) -> list[Tool[object]]:
+ if http_client.is_closed:
+ raise RuntimeError("DifyCoreToolsLayer.get_tools() requires an open shared HTTP client.")
+
+ execution_context = self.deps.execution_context.config
+ client = DifyCoreToolsClient(
+ base_url=self.inner_api_url,
+ api_key=self.inner_api_key,
+ http_client=http_client,
+ )
+ tools: list[Tool[object]] = []
+ for tool_config in self.config.tools:
+ tools.append(
+ self._build_tool(
+ client=client,
+ execution_context=execution_context,
+ tool_config=tool_config,
+ )
+ )
+ return tools
+
+ @staticmethod
+ def _build_tool(
+ *,
+ client: DifyCoreToolsClient,
+ execution_context: DifyExecutionContextLayerConfig,
+ tool_config: DifyCoreToolConfig,
+ ) -> Tool[object]:
+ tool_name = tool_config.name or tool_config.tool_name
+ tool_description = tool_config.description or tool_name
+ tool_schema = deepcopy(tool_config.parameters_json_schema)
+
+ async def invoke_tool(_ctx: RunContext[object], **tool_arguments: object) -> str:
+ try:
+ response = await client.invoke(
+ execution_context=execution_context,
+ tool_config=tool_config,
+ tool_parameters=tool_arguments,
+ )
+ return response.observation
+ except DifyCoreToolsClientConfigurationError:
+ return "Tool is unavailable because required execution context is missing."
+ except DifyCoreToolsClientError as exc:
+ return _tool_error_text(tool_name=tool_name, error=exc)
+
+ async def prepare_tool_definition(_ctx: RunContext[object], tool_def: ToolDefinition) -> ToolDefinition:
+ return ToolDefinition(
+ name=tool_def.name,
+ description=tool_def.description,
+ parameters_json_schema=tool_schema,
+ strict=CORE_TOOL_STRICT,
+ sequential=tool_def.sequential,
+ metadata=tool_def.metadata,
+ timeout=tool_def.timeout,
+ defer_loading=tool_def.defer_loading,
+ kind=tool_def.kind,
+ return_schema=tool_def.return_schema,
+ include_return_schema=tool_def.include_return_schema,
+ )
+
+ return Tool(
+ invoke_tool,
+ takes_ctx=True,
+ name=tool_name,
+ description=tool_description,
+ prepare=prepare_tool_definition,
+ )
+
+
+def _tool_error_text(*, tool_name: str, error: DifyCoreToolsClientError) -> str:
+ if error.retryable:
+ return TEMPORARY_UNAVAILABLE_OBSERVATION
+ error_code = error.error_code or ""
+ if error_code == "app_not_found":
+ return "Tool is unavailable because its app context no longer exists."
+ if error_code == "app_tenant_mismatch":
+ return "Tool is unavailable because its app context is invalid."
+ if error_code == "agent_tool_credential_invalid":
+ return "Please check your tool provider credentials"
+ if error_code == "agent_tool_declaration_not_found":
+ return f"there is not a tool named {tool_name}"
+ if error_code == "tool_parameters_invalid":
+ return f"tool parameters validation error: {error}, please check your tool parameters"
+ if error_code == "agent_tool_invoke_failed":
+ return f"tool invoke error: {error}"
+ return f"tool invoke error: {error}"
+
+
+__all__ = ["DifyCoreToolsDeps", "DifyCoreToolsLayer"]
diff --git a/dify-agent/src/dify_agent/layers/drive/layer.py b/dify-agent/src/dify_agent/layers/drive/layer.py
index e6941b50cbe..fec1109e74d 100644
--- a/dify-agent/src/dify_agent/layers/drive/layer.py
+++ b/dify-agent/src/dify_agent/layers/drive/layer.py
@@ -5,9 +5,9 @@ mentioned in the prompt. When the layer enters a run context it eagerly pulls
those mentioned skills/files through the already-active shell layer by running
the sandbox-visible ``dify-agent drive pull`` command, then contributes a
concise prompt block describing what was loaded. It also contributes a suffix
-prompt with the remaining skill catalog plus ``dify-agent drive`` and
-``dify-agent file`` usage so the model has concrete Agent Stub commands for
-materializing drive content and workflow files.
+prompt with the remaining skill catalog plus agent-visible ``dify-agent file``
+usage captured from the real CLI. Drive commands remain internal for now and
+are not exposed to the model.
"""
from __future__ import annotations
@@ -24,26 +24,11 @@ from dify_agent.agent_stub.protocol import agent_stub_drive_base_for_ref
from dify_agent.layers.drive.configs import DIFY_DRIVE_LAYER_TYPE_ID, DifyDriveLayerConfig
from dify_agent.layers.shell.layer import DifyShellLayer
-_AGENT_STUB_CLI_USAGE_PROMPT = """Agent Stub CLI usage is available inside shell jobs:
-
-Drive assets are Agent Soul versioned assets:
-
-- List drive assets: `dify-agent drive list [REMOTE_PREFIX]`
-- Pull drive assets: `dify-agent drive pull [REMOTE ...] [--to LOCAL_DIR]`
- With no remote, pulls the whole visible drive. Pull overwrites local files.
- Defaults to `$DIFY_AGENT_STUB_DRIVE_BASE`; use `--to .` for cwd.
- `--to` is a local root; remote keys keep their path under it.
- Skill archives are automatically extracted after pull.
-- Push one file: `dify-agent drive push LOCAL_FILE REMOTE_PATH`
-- Push a skill package: `dify-agent drive push LOCAL_DIR REMOTE_PATH --kind skill`
-- Push a raw directory: `dify-agent drive push LOCAL_DIR REMOTE_PATH --kind dir`
-
-Workflow file mappings:
-
-- Download a mapping: `dify-agent file download TRANSFER_METHOD REFERENCE_OR_URL [--to LOCAL_DIR]`
-- Or pass a mapping object: `dify-agent file download --mapping '{"transfer_method":"tool_file","reference":"..."}'`
-- Upload an output file: `dify-agent file upload PATH`
- Prints JSON like `{"transfer_method":"tool_file","reference":"..."}`."""
+_AGENT_STUB_FILE_HELP_COMMANDS = (
+ "dify-agent file --help",
+ "dify-agent file upload --help",
+ "dify-agent file download --help",
+)
class DifyDriveLayerError(RuntimeError):
@@ -63,6 +48,7 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
config: DifyDriveLayerConfig
_loaded_skill_bodies: dict[str, str] = field(default_factory=dict)
_pulled_file_paths: dict[str, str] = field(default_factory=dict)
+ _agent_stub_cli_help: dict[str, str] = field(default_factory=dict)
@classmethod
@override
@@ -81,10 +67,12 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
@override
async def on_context_create(self) -> None:
+ await self._load_agent_stub_cli_help()
await self._pull_mentioned_targets()
@override
async def on_context_resume(self) -> None:
+ await self._load_agent_stub_cli_help()
await self._pull_mentioned_targets()
def build_prompt_context(self) -> str:
@@ -127,20 +115,31 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
if skill.skill_md_key not in mentioned_skill_keys
]
if other_skills:
- pull_and_read_command = (
- '`skill_dir="$(dify-agent drive pull <SKILL_PATH> --to /tmp/drive)"; '
- + 'printf "%s\\n" "$skill_dir"; cat "$skill_dir/SKILL.md"`'
- )
- sections.append(
- "Other available skills:\n"
- + "\n".join(other_skills)
- + "\n\nTo use one, pull it and read its SKILL.md in one command: "
- + pull_and_read_command
- + "."
- )
- sections.append(_AGENT_STUB_CLI_USAGE_PROMPT)
+ sections.append("Other available skills:\n" + "\n".join(other_skills))
+ if cli_help := self._format_agent_stub_cli_help():
+ sections.append(cli_help)
return "\n\n".join(sections)
+ def _format_agent_stub_cli_help(self) -> str:
+ command_sections = [
+ f"$ {command}\n{self._agent_stub_cli_help[command]}"
+ for command in _AGENT_STUB_FILE_HELP_COMMANDS
+ if command in self._agent_stub_cli_help
+ ]
+ if not command_sections:
+ return ""
+ return "Agent Stub file CLI help:\n" + "\n\n".join(command_sections)
+
+ async def _load_agent_stub_cli_help(self) -> None:
+ self._agent_stub_cli_help = {}
+ for command in _AGENT_STUB_FILE_HELP_COMMANDS:
+ result = await self.deps.shell.run_remote_script(command, timeout=10.0)
+ if result.exit_code != 0 or not result.output_complete:
+ continue
+ output = result.output.strip()
+ if output:
+ self._agent_stub_cli_help[command] = output
+
async def _pull_mentioned_targets(self) -> None:
self._loaded_skill_bodies = {}
self._pulled_file_paths = {}
@@ -149,21 +148,30 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
return
script = self._build_shell_pull_script(targets=targets)
- result = await self.deps.shell.run_remote_script(script, inject_agent_stub_env=True)
+ result = await self.deps.shell.run_remote_script_complete(script, inject_agent_stub_env=True)
if result.exit_code != 0:
raise DifyDriveLayerError(
- f"drive mentioned pull failed in shell: {result.status} exit_code={result.exit_code}\n{result.output}"
+ "drive mentioned pull failed in shell: "
+ + f"{result.status} exit_code={result.exit_code} "
+ + f"output_complete={result.output_complete} "
+ + f"incomplete_reason={result.incomplete_reason} "
+ + f"output_path={result.output_path}\n{result.output}"
)
- if result.truncated:
- raise DifyDriveLayerError("drive mentioned pull output was truncated before SKILL.md content was loaded")
-
- written_paths, skill_bodies = self._parse_shell_pull_output(result.output)
- self._record_pulled_paths(written_paths)
- for skill_key in self.config.mentioned_skill_keys:
- body = skill_bodies.get(skill_key)
- if body is None:
- raise DifyDriveLayerError(f"missing pulled SKILL.md content for mentioned skill {skill_key}")
- self._loaded_skill_bodies[skill_key] = body
+ try:
+ written_paths, skill_bodies = self._parse_shell_pull_output(result.output)
+ self._record_pulled_paths(written_paths)
+ for skill_key in self.config.mentioned_skill_keys:
+ body = skill_bodies.get(skill_key)
+ if body is None:
+ raise DifyDriveLayerError(f"missing pulled SKILL.md content for mentioned skill {skill_key}")
+ self._loaded_skill_bodies[skill_key] = body
+ except DifyDriveLayerError:
+ if result.output_complete:
+ raise
+ raise DifyDriveLayerError(
+ "drive mentioned pull output incomplete before required SKILL.md content was captured: "
+ + f"reason={result.incomplete_reason} output_path={result.output_path}\n{result.output}"
+ ) from None
def _build_shell_pull_script(self, *, targets: list[tuple[str, bool]]) -> str:
pull_targets = list(dict.fromkeys(prefix for prefix, _exact in targets))
diff --git a/dify-agent/src/dify_agent/layers/execution_context/__init__.py b/dify-agent/src/dify_agent/layers/execution_context/__init__.py
index aaf031501b3..45575faf3e2 100644
--- a/dify-agent/src/dify_agent/layers/execution_context/__init__.py
+++ b/dify-agent/src/dify_agent/layers/execution_context/__init__.py
@@ -8,6 +8,7 @@ DTO, but that runtime implementation still lives in sibling modules.
from dify_agent.layers.execution_context.configs import (
DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID,
+ DifyExecutionContextAgentConfigVersionKind,
DifyExecutionContextAgentMode,
DifyExecutionContextInvokeFrom,
DifyExecutionContextLayerConfig,
@@ -16,6 +17,7 @@ from dify_agent.layers.execution_context.configs import (
__all__ = [
"DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID",
+ "DifyExecutionContextAgentConfigVersionKind",
"DifyExecutionContextAgentMode",
"DifyExecutionContextInvokeFrom",
"DifyExecutionContextLayerConfig",
diff --git a/dify-agent/src/dify_agent/layers/execution_context/configs.py b/dify-agent/src/dify_agent/layers/execution_context/configs.py
index 21abe9b9481..afddd7b9344 100644
--- a/dify-agent/src/dify_agent/layers/execution_context/configs.py
+++ b/dify-agent/src/dify_agent/layers/execution_context/configs.py
@@ -26,6 +26,7 @@ DifyExecutionContextAgentMode: TypeAlias = Literal[
"babysit",
"fasten",
]
+DifyExecutionContextAgentConfigVersionKind: TypeAlias = Literal["snapshot", "draft", "build_draft"]
DifyExecutionContextUserFrom: TypeAlias = Literal["account", "end-user"]
DifyExecutionContextInvokeFrom: TypeAlias = Literal[
"service-api",
@@ -53,6 +54,7 @@ class DifyExecutionContextLayerConfig(LayerConfig):
conversation_id: str | None = None
agent_id: str | None = None
agent_config_version_id: str | None = None
+ agent_config_version_kind: DifyExecutionContextAgentConfigVersionKind | None = None
agent_mode: DifyExecutionContextAgentMode
invoke_from: DifyExecutionContextInvokeFrom
trace_id: str | None = None
@@ -62,6 +64,7 @@ class DifyExecutionContextLayerConfig(LayerConfig):
__all__ = [
"DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID",
+ "DifyExecutionContextAgentConfigVersionKind",
"DifyExecutionContextAgentMode",
"DifyExecutionContextInvokeFrom",
"DifyExecutionContextUserFrom",
diff --git a/dify-agent/src/dify_agent/layers/shell/layer.py b/dify-agent/src/dify_agent/layers/shell/layer.py
index b54e0bb4d26..d514025aa45 100644
--- a/dify-agent/src/dify_agent/layers/shell/layer.py
+++ b/dify-agent/src/dify_agent/layers/shell/layer.py
@@ -1,54 +1,49 @@
-"""Shell layer backed by the shell adapter provisioner/executor mechanism.
-
-``DifyShellLayer`` is a stateful pydantic-ai tool layer that exposes exactly
-``shell_run``, ``shell_wait``, ``shell_input``, and ``shell_interrupt``. The
-layer persists only JSON-safe shell session state in ``runtime_state`` and keeps
-its live ``ShellctlHandle`` on the layer instance only while
-``resource_context()`` is active. Agenton enters that resource scope before
-``on_context_create`` or ``on_context_resume`` and exits it after
-``on_context_suspend`` or ``on_context_delete``, so business hooks and shell
-tools can rely on live resources without ever serializing them into snapshots.
-
-The layer delegates workspace lifecycle to ``ShellProvisionProtocol``:
-``provision`` allocates a fresh workspace, ``reattach`` rebuilds a live handle
-for an existing workspace from a serialized descriptor, and ``destroy`` tears
-the workspace down. User-facing shell tools call the shellctl client obtained
-from the handle directly; trusted server-owned scripts go through
-``ShellctlExecutor`` which auto-cleans completed jobs.
-"""
+"""Shell runtime layer backed by a live shell provider resource."""
from __future__ import annotations
-from collections.abc import AsyncGenerator, Callable, Sequence
+from collections.abc import AsyncGenerator, Sequence
from contextlib import asynccontextmanager
import json
import logging
import re
+import secrets
+import time
from dataclasses import dataclass
-from typing import ClassVar, NotRequired, Protocol, TypedDict, cast
+from typing import ClassVar, Literal, NotRequired, TypedDict
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, field_validator, model_validator
from pydantic_ai import Tool
-from shell_session_manager.shellctl.client import ShellctlClientError
-from shell_session_manager.shellctl.shared import (
- DEFAULT_TERMINATE_GRACE_SECONDS,
- DEFAULT_TIMEOUT_SECONDS,
- JobResult,
- JobStatusView,
-)
from typing_extensions import Self, override
from agenton.layers import LayerDeps, PydanticAILayer, PydanticAIPrompt, PydanticAITool
-from dify_agent.adapters.shell.protocols import ShellProvisionProtocol
-from dify_agent.adapters.shell.shellctl import ShellctlEnvironmentDescriptor, ShellctlExecutor, ShellctlHandle
+from dify_agent.adapters.shell.protocols import (
+ CompleteShellCommandResult,
+ ShellCommandProtocol,
+ ShellCommandResult,
+ ShellPromptObservation,
+ ShellProviderProtocol,
+ ShellResourceProtocol,
+)
from dify_agent.agent_stub.server.shell_agent_stub_env import ShellAgentStubTokenFactory, build_shell_agent_stub_env
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
from dify_agent.layers.shell.configs import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
-
+from dify_agent.layers.shell.output_text import normalized_output_text, utf8_prefix, utf8_suffix
logger = logging.getLogger(__name__)
+DEFAULT_TIMEOUT_SECONDS = 30.0
+DEFAULT_TERMINATE_GRACE_SECONDS = 10.0
_WORKSPACE_ROOT = "~/workspace"
+_WORKSPACE_COLLISION_EXIT_CODE = 17
+_SESSION_TIME_HEX_MASK = 0xFFFFF
+_SESSION_RANDOM_HEX_LENGTH = 2
+_SESSION_ID_ATTEMPT_LIMIT = 256
+_SESSION_ID_PATTERN = re.compile(r"^[0-9a-f]{7}$")
+_SHELL_OUTPUT_PROMPT_EDGE_BYTES = 8 * 1024
+_SHELLCTL_OUTPUT_LIMIT_BYTES = 2 * _SHELL_OUTPUT_PROMPT_EDGE_BYTES
+_REMOTE_COMPLETE_OUTPUT_MAX_BYTES = 1024 * 1024
+_REMOTE_COMMAND_TIMEOUT_SECONDS = 60.0
_SHELL_LAYER_PREFIX_PROMPT = """You have access to a shell layer. It provides four tools:
1. shell_run
@@ -95,6 +90,16 @@ Usage rules:
- Use shell_input only when the job is running and waiting for stdin.
- Use shell_interrupt when a job is stuck or should be stopped.
+Workspace persistence rules:
+
+- The current workspace cwd is stable during this agent run, but it is temporary and may be deleted later.
+- Do not use the current workspace cwd as persistent storage.
+- $HOME outside the current workspace cwd is persistent storage. In build draft mode, when Agent config context reports
+ `config_version.kind` as `build_draft` and `config_version.writable` as true, changes there can be persisted for
+ later runs. In non-build-draft modes, those changes are rolled back.
+- Saving config files, skills, env, or notes still requires the corresponding Agent config CLI mutation command; follow
+ the Agent config CLI help in the config layer. Shell file edits alone do not save config.
+
The script argument of shell_run can be a normal shell script, or a shebang script.
If the first line is a shebang, the shell layer executes the script directly.
@@ -120,113 +125,20 @@ response = httpx.get("https://example.com", timeout=10)
print(f"[green]status:[/green] {response.status_code}")"""
-class ShellJobObservation(TypedDict):
- """JSON-safe output-oriented shell tool observation."""
-
- job_id: str
- status: str
- done: bool
- exit_code: int | None
- output: str
- offset: int
- truncated: bool
- output_path: str
-
-
-class ShellJobStatusObservation(TypedDict):
- """JSON-safe status-only shell tool observation."""
-
- job_id: str
- status: str
- done: bool
- exit_code: int | None
- offset: int
-
-
class ShellToolErrorObservation(TypedDict):
- """Tool-visible failure payload for expected shell-layer errors."""
-
error: str
job_id: NotRequired[str]
-type ShellRunToolResult = ShellJobObservation | ShellToolErrorObservation
-type ShellInterruptToolResult = ShellJobStatusObservation | ShellToolErrorObservation
+type ShellRunToolResult = str | ShellToolErrorObservation
+type ShellInterruptToolResult = str | ShellToolErrorObservation
class DifyShellLayerDeps(LayerDeps):
- """Optional direct-layer dependencies used by the shell runtime layer.
-
- The execution context supplies the token principal. The drive ref used for
- Agent Stub CLI commands is passed through config so the drive layer can
- depend on shell for eager materialization without a dependency cycle.
- """
-
execution_context: DifyExecutionContextLayer | None # pyright: ignore[reportUninitializedInstanceVariable]
-class ShellctlClientProtocol(Protocol):
- """Boundary that the shell layer needs from a shellctl client."""
-
- async def run(
- self,
- script: str,
- *,
- cwd: str | None = None,
- env: dict[str, str] | None = None,
- timeout: float = DEFAULT_TIMEOUT_SECONDS,
- ) -> JobResult: ...
-
- async def wait(
- self,
- job_id: str,
- *,
- offset: int,
- timeout: float = DEFAULT_TIMEOUT_SECONDS,
- ) -> JobResult: ...
-
- async def input(
- self,
- job_id: str,
- text: str,
- *,
- offset: int,
- timeout: float = DEFAULT_TIMEOUT_SECONDS,
- ) -> JobResult: ...
-
- async def terminate(
- self,
- job_id: str,
- grace_seconds: float = DEFAULT_TERMINATE_GRACE_SECONDS,
- ) -> JobStatusView: ...
-
- async def delete(
- self,
- job_id: str,
- *,
- force: bool = False,
- grace_seconds: float | None = None,
- ) -> object: ...
-
- async def close(self) -> None: ...
-
-
-type ShellctlClientFactory = Callable[[str], ShellctlClientProtocol]
-
-
class DifyShellRuntimeState(BaseModel):
- """Serializable shell session state stored in Agenton snapshots.
-
- ``job_ids`` and ``job_offsets`` contain both user-facing jobs and internal
- lifecycle jobs so resumed sessions can still clean up shellctl state that was
- created before suspension. Callers should replace the stored list/dict values
- rather than mutating them in place so Pydantic assignment validation keeps
- guarding the serialized state. Hydrated public snapshots must keep
- ``session_id`` and ``workspace_cwd`` consistent with the descriptor returned
- by the shell provisioner, so resume and delete paths cannot escape the
- isolated workspace root or inject shell syntax into lifecycle commands.
- """
-
session_id: str | None = None
workspace_cwd: str | None = None
job_ids: list[str] = Field(default_factory=list)
@@ -237,24 +149,19 @@ class DifyShellRuntimeState(BaseModel):
@field_validator("session_id")
@classmethod
def validate_session_id(cls, value: str | None) -> str | None:
- """Reject session ids that could escape the workspace root or inject shell syntax."""
if value is None:
return value
- if not re.fullmatch(r"[0-9a-f]{7,16}", value):
- raise ValueError("session_id must be 7 to 16 lowercase hex characters (got an invalid value).")
- return value
+ return _validated_session_id(value)
@field_validator("job_ids")
@classmethod
def validate_job_ids(cls, value: list[str]) -> list[str]:
- """Keep tracked shellctl job ids unique within one serialized session."""
if len(value) != len(set(value)):
raise ValueError("job_ids must not contain duplicates.")
return value
@model_validator(mode="after")
def validate_workspace_and_offsets(self) -> Self:
- """Keep resumed workspace identity and tracked offset keys self-consistent."""
if self.workspace_cwd is not None:
if self.session_id is None:
raise ValueError("workspace_cwd requires a matching session_id.")
@@ -268,67 +175,39 @@ class DifyShellRuntimeState(BaseModel):
return self
-@dataclass(frozen=True, slots=True)
-class RemoteCommandResult:
- """Completed remote sandbox command returned to server-owned callers.
-
- Only fields with live consumers are kept: ``output``/``exit_code`` (read by
- every caller), ``truncated`` (drive pull treats a truncated result as a
- failure because it needs the command's full output), and ``status`` (used in
- drive's human-readable error message). shellctl paging details such as the
- job id, completion flag, byte offset, and output path are intentionally not
- surfaced here, since no caller reads them.
- """
-
- status: str
- exit_code: int | None
- output: str
- truncated: bool
+CompleteRemoteCommandResult = CompleteShellCommandResult
@dataclass(slots=True)
class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerConfig, DifyShellRuntimeState]):
- """Shell tool layer backed by the shell provisioner/executor mechanism.
-
- The mutable serializable state lives in ``runtime_state``; the live
- ``ShellctlHandle`` is intentionally kept off-snapshot. Tool methods update
- tracked job ids and output offsets after every successful shellctl response so
- later ``shell_wait``/``shell_input`` calls can resume from the last known
- offset without exposing offsets as model-controlled inputs.
- """
-
type_id: ClassVar[str | None] = DIFY_SHELL_LAYER_TYPE_ID
config: DifyShellLayerConfig
- shell_provisioner: ShellProvisionProtocol[ShellctlEnvironmentDescriptor]
+ shell_provider: ShellProviderProtocol
agent_stub_api_base_url: str | None = None
agent_stub_token_factory: ShellAgentStubTokenFactory | None = None
- _shell_handle: ShellctlHandle | None = None
+ _shell_resource: ShellResourceProtocol | None = None
@classmethod
@override
def from_config(cls, config: DifyShellLayerConfig) -> Self:
- """Reject construction that omits the shell provisioner."""
del config
- raise TypeError("DifyShellLayer requires a shell provisioner and must use a provider factory.")
+ raise TypeError("DifyShellLayer requires a shell provider and must use a provider factory.")
@classmethod
def from_config_with_settings(
cls,
config: DifyShellLayerConfig,
*,
- shell_provisioner: ShellProvisionProtocol[ShellctlEnvironmentDescriptor] | None,
+ shell_provider: ShellProviderProtocol | None,
agent_stub_api_base_url: str | None = None,
agent_stub_token_factory: ShellAgentStubTokenFactory | None = None,
) -> Self:
- """Create the layer from public config plus shell provisioner settings."""
- if shell_provisioner is None:
- raise ValueError(
- "DifyShellLayer requires a non-null shell provisioner when the 'dify.shell' layer is used."
- )
+ if shell_provider is None:
+ raise ValueError("DifyShellLayer requires a non-null shell provider when the 'dify.shell' layer is used.")
layer = cls(
config=config,
- shell_provisioner=shell_provisioner,
+ shell_provider=shell_provider,
agent_stub_api_base_url=agent_stub_api_base_url,
agent_stub_token_factory=agent_stub_token_factory,
)
@@ -353,126 +232,138 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
@override
@asynccontextmanager
async def resource_context(self) -> AsyncGenerator[None]:
- """Hold the live shell handle scope.
-
- The actual handle is set in ``on_context_create`` /
- ``on_context_resume``. This scope ensures cleanup if a lifecycle hook
- fails before the handle is set.
- """
+ if self._shell_resource is not None:
+ raise RuntimeError("DifyShellLayer resource_context() is already active for this layer instance.")
+ resource = await self.shell_provider.create()
+ self._shell_resource = resource
try:
yield
finally:
- self._shell_handle = None
+ self._shell_resource = None
+ await resource.close()
@override
async def on_context_create(self) -> None:
- """Provision a new workspace session using the shell provisioner.
-
- The provisioner allocates the workspace directory and returns a
- ``ShellctlHandle``. The layer then bootstraps the workspace with Agent
- Soul env exports and CLI tool install commands. If workspace setup
- partially succeeds and this hook later raises, the layer never becomes
- ``ACTIVE``. In that path Agenton still exits ``resource_context()``, but
- ``on_context_delete()`` will not run, so this hook must clean up any
- tracked artifacts before re-raising.
- """
+ _ = self._require_resource()
+ session_id: str | None = None
try:
- handle = cast(ShellctlHandle, await self.shell_provisioner.provision())
- self._shell_handle = handle
- descriptor = handle.descriptor()
- await self._bootstrap_workspace(descriptor.workspace_cwd)
+ session_id, workspace_cwd = await self._allocate_workspace()
+ await self._bootstrap_workspace(workspace_cwd)
except BaseException:
- await self._cleanup_create_failure()
+ if session_id is not None:
+ await self._cleanup_workspace_best_effort(session_id)
raise
self.runtime_state = DifyShellRuntimeState.model_validate(
{
**self.runtime_state.model_dump(mode="python"),
- "session_id": descriptor.session_id,
- "workspace_cwd": descriptor.workspace_cwd,
+ "session_id": session_id,
+ "workspace_cwd": workspace_cwd,
}
)
@override
async def on_context_resume(self) -> None:
- """Reattach to an existing serialized shell session.
-
- Builds a ``ShellEnvironmentDescriptor`` from the persisted runtime state
- and asks the provisioner to reattach without allocating a new workspace.
- If a future resume path adds self-heal side effects before raising, this
- hook must compensate for them itself because failed resume attempts never
- transition the slot back to ``ACTIVE``.
- """
- session_id, workspace_cwd = self._require_session_identity()
- descriptor = ShellctlEnvironmentDescriptor(
- workspace_cwd=workspace_cwd,
- session_id=session_id,
- )
- handle = cast(ShellctlHandle, await self.shell_provisioner.reattach(descriptor))
- self._shell_handle = handle
+ _ = self._require_resource()
+ _ = self._require_session_identity()
@override
async def on_context_suspend(self) -> None:
- """Close the live client so it does not leak across snapshot boundaries.
-
- ``reattach`` on the next resume creates a fresh client pointing at the
- same workspace. ``resource_context()`` clears the handle reference after
- this hook returns.
- """
- handle = self._shell_handle
- if handle is not None:
- await handle.client.close()
+ _ = self._require_resource()
@override
async def on_context_delete(self) -> None:
- """Best-effort cleanup for tracked shellctl jobs and workspace deletion.
-
- Tracked shellctl jobs are force-deleted on a best-effort basis before the
- handle is destroyed, since job records may outlive the workspace. The
- provisioner's ``destroy`` handles workspace removal and client close.
- """
- handle = self._shell_handle
- if handle is None:
- return
+ _ = self._require_resource()
+ identity = self._try_session_identity()
+ if identity is not None:
+ session_id, _workspace_cwd = identity
+ result = await self._run_internal_script_complete(
+ _workspace_cleanup_script(session_id=session_id), cwd=None
+ )
+ if result.exit_code != 0 or not result.output_complete:
+ logger.warning(
+ "Shell workspace cleanup for session %s ended with status=%s exit_code=%s output_complete=%s.",
+ session_id,
+ result.status,
+ result.exit_code,
+ result.output_complete,
+ )
await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)
self._clear_tracked_jobs()
- await self.shell_provisioner.destroy(handle)
- self._shell_handle = None
async def _tool_run(self, script: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> ShellRunToolResult:
- """Start a new shell job inside the session workspace."""
try:
- client = self._require_client()
- result = await client.run(
+ result = await self._require_resource().commands.run(
_wrap_user_script(script, self.config),
cwd=self._require_workspace_cwd(),
env=self._build_user_shell_run_env(),
timeout=timeout,
)
- self._track_job_result(result)
- return _job_result_observation(result)
- except (RuntimeError, ValueError, ShellctlClientError) as exc:
+ observation = await render_prompt_observation_from_result(
+ self._require_resource().commands,
+ result,
+ edge_bytes=_SHELL_OUTPUT_PROMPT_EDGE_BYTES,
+ )
+ self._remember_job_id(result.job_id)
+ self._remember_job_offset(result.job_id, observation.offset)
+ return _tagged_shell_observation(
+ _metadata_dict(
+ job_id=result.job_id,
+ status=result.status,
+ done=result.done,
+ exit_code=result.exit_code,
+ output_path=observation.output_path,
+ ),
+ observation.text,
+ )
+ except (RuntimeError, ValueError) as exc:
return _tool_error(str(exc))
async def _tool_wait(self, job_id: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> ShellRunToolResult:
- """Wait for more output or completion from a tracked shell job."""
try:
- client = self._require_client()
offset = self._tracked_offset(job_id)
- result = await client.wait(job_id, offset=offset, timeout=timeout)
- self._track_job_result(result)
- return _job_result_observation(result)
- except (RuntimeError, ValueError, ShellctlClientError) as exc:
+ result = await self._require_resource().commands.wait(job_id, offset=offset, timeout=timeout)
+ observation = await render_prompt_observation_from_result(
+ self._require_resource().commands,
+ result,
+ edge_bytes=_SHELL_OUTPUT_PROMPT_EDGE_BYTES,
+ )
+ self._remember_job_id(result.job_id)
+ self._remember_job_offset(result.job_id, observation.offset)
+ return _tagged_shell_observation(
+ _metadata_dict(
+ job_id=result.job_id,
+ status=result.status,
+ done=result.done,
+ exit_code=result.exit_code,
+ output_path=observation.output_path,
+ ),
+ observation.text,
+ )
+ except (RuntimeError, ValueError) as exc:
return _tool_error(str(exc), job_id=job_id)
async def _tool_input(self, job_id: str, text: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> ShellRunToolResult:
- """Send text input to a tracked shell job and wait for output."""
try:
- client = self._require_client()
offset = self._tracked_offset(job_id)
- result = await client.input(job_id, text, offset=offset, timeout=timeout)
- self._track_job_result(result)
- return _job_result_observation(result)
- except (RuntimeError, ValueError, ShellctlClientError) as exc:
+ result = await self._require_resource().commands.input(job_id, text, offset=offset, timeout=timeout)
+ observation = await render_prompt_observation_from_result(
+ self._require_resource().commands,
+ result,
+ edge_bytes=_SHELL_OUTPUT_PROMPT_EDGE_BYTES,
+ )
+ self._remember_job_id(result.job_id)
+ self._remember_job_offset(result.job_id, observation.offset)
+ return _tagged_shell_observation(
+ _metadata_dict(
+ job_id=result.job_id,
+ status=result.status,
+ done=result.done,
+ exit_code=result.exit_code,
+ output_path=observation.output_path,
+ ),
+ observation.text,
+ )
+ except (RuntimeError, ValueError) as exc:
return _tool_error(str(exc), job_id=job_id)
async def _tool_interrupt(
@@ -480,138 +371,127 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
job_id: str,
grace_seconds: float = DEFAULT_TERMINATE_GRACE_SECONDS,
) -> ShellInterruptToolResult:
- """Interrupt a tracked shell job without removing its persisted shellctl state."""
try:
- client = self._require_client()
self._ensure_tracked_job(job_id)
- result = await client.terminate(job_id, grace_seconds=grace_seconds)
- self._track_job_status(result)
- return _job_status_observation(result)
- except (RuntimeError, ValueError, ShellctlClientError) as exc:
+ result = await self._require_resource().commands.interrupt(job_id, grace_seconds=grace_seconds)
+ self._remember_job_id(result.job_id)
+ self._remember_job_offset(result.job_id, result.offset)
+ output_path: str | None = None
+ try:
+ output_path = (await self._require_resource().commands.tail(job_id)).output_path
+ except (RuntimeError, ValueError) as exc:
+ logger.warning(
+ "Failed to fetch output path for interrupted shell job %s in session %s: %s",
+ job_id,
+ self.runtime_state.session_id,
+ exc,
+ )
+ return _tagged_shell_observation(
+ _metadata_dict(
+ job_id=result.job_id,
+ status=result.status,
+ done=result.done,
+ exit_code=result.exit_code,
+ output_path=output_path,
+ ),
+ "Job was interrupted.",
+ )
+ except (RuntimeError, ValueError) as exc:
return _tool_error(str(exc), job_id=job_id)
- async def run_remote_script(
+ async def run_remote_script_complete(
self,
script: str,
*,
- timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ timeout: float = _REMOTE_COMMAND_TIMEOUT_SECONDS,
+ max_output_bytes: int = _REMOTE_COMPLETE_OUTPUT_MAX_BYTES,
inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
- """Run one trusted server-side script inside the sandbox workspace.
-
- The sandbox file service uses this boundary for fixed list/read/upload
- helpers. Execution, output draining, and transient shellctl job cleanup
- are delegated to ``ShellctlExecutor`` from the shell adapter; the layer
- owns only the optional Agent Stub env injection and the
- ``RemoteCommandResult`` mapping.
-
- Unlike model-visible ``shell.run``, this server-owned boundary does not
- inject Agent Soul shell env. Keeping the user-controlled shell env out
- of this path prevents sandbox code from clobbering trusted Agent Stub
- env values before ``dify-agent file upload`` executes.
- """
+ ) -> CompleteRemoteCommandResult:
env = None
if inject_agent_stub_env:
env = self._build_user_shell_run_env()
if env is None:
raise RuntimeError("Agent Stub environment injection is not available for this shell session.")
- handle = self._require_handle()
- executor = ShellctlExecutor(
- client=handle.client, # pyright: ignore[reportArgumentType]
- workspace_cwd=self._require_workspace_cwd(),
+ return await execute_complete_with_commands(
+ self._require_resource().commands,
+ script,
+ cwd=self._require_workspace_cwd(),
+ env=env,
timeout=timeout,
- )
- result = await executor.execute(script, env=env)
- return RemoteCommandResult(
- status="exited" if not result.truncated() else "running",
- exit_code=result.exit_code(),
- output=result.stdout(),
- truncated=result.truncated(),
+ max_output_bytes=max_output_bytes,
)
- def environment_descriptor(self) -> ShellctlEnvironmentDescriptor:
- """Return the serializable workspace seed for the shell adapter.
+ async def run_remote_script(
+ self,
+ script: str,
+ *,
+ timeout: float = _REMOTE_COMMAND_TIMEOUT_SECONDS,
+ inject_agent_stub_env: bool = False,
+ ) -> CompleteRemoteCommandResult:
+ return await self.run_remote_script_complete(
+ script,
+ timeout=timeout,
+ inject_agent_stub_env=inject_agent_stub_env,
+ )
- Bridges this layer's ``runtime_state`` to
- ``dify_agent.adapters.shell``: the returned descriptor identifies the
- session workspace so an adapter ``ShellProvisionProtocol.reattach`` can
- rebuild a live handle pointing at it without re-allocating, and without
- re-entering this layer. Raises ``ValueError`` if the session identity is
- missing or inconsistent.
- """
- session_id, workspace_cwd = self._require_session_identity()
- return ShellctlEnvironmentDescriptor(workspace_cwd=workspace_cwd, session_id=session_id)
+ async def _allocate_workspace(self) -> tuple[str, str]:
+ for _attempt in range(_SESSION_ID_ATTEMPT_LIMIT):
+ session_id = _generate_session_id()
+ result = await self._run_internal_script_complete(_workspace_mkdir_script(session_id=session_id), cwd=None)
+ if result.exit_code == _WORKSPACE_COLLISION_EXIT_CODE:
+ continue
+ if result.exit_code != 0 or not result.output_complete:
+ raise RuntimeError(
+ f"Failed to create shell workspace {_workspace_cwd(session_id)}: "
+ + f"{result.status} exit_code={result.exit_code}"
+ )
+ return session_id, _workspace_cwd(session_id)
+ raise RuntimeError("Failed to allocate a unique shell workspace session id after 256 attempts.")
async def _bootstrap_workspace(self, workspace_cwd: str) -> None:
- """Apply Agent Soul shell config to the freshly-created workspace."""
bootstrap_script = _workspace_bootstrap_script(self.config)
if not bootstrap_script:
return
- result = await self._run_internal_job_to_completion(bootstrap_script, cwd=workspace_cwd)
- if result["exit_code"] != 0:
+ result = await self._run_internal_script_complete(bootstrap_script, cwd=workspace_cwd)
+ if result.exit_code != 0 or not result.output_complete:
raise RuntimeError(
- f"Failed to bootstrap shell workspace {workspace_cwd}: {result['status']} exit_code={result['exit_code']}"
+ f"Failed to bootstrap shell workspace {workspace_cwd}: {result.status} exit_code={result.exit_code}"
)
- async def _cleanup_create_failure(self) -> None:
- """Best-effort cleanup for create failures before ACTIVE state.
-
- Agenton only calls ``on_context_delete`` for layers that successfully
- entered ``ACTIVE``. If ``on_context_create`` fails after issuing
- internal jobs, those tracked job artifacts would otherwise leak because
- no later lifecycle hook owns them. The provisioner's ``destroy`` handles
- workspace removal and client close.
- """
- handle = self._shell_handle
- if handle is None:
- return
- if self.runtime_state.job_ids:
- try:
- await self._delete_tracked_jobs_best_effort(self.runtime_state.job_ids)
- finally:
- self._clear_tracked_jobs()
- await self.shell_provisioner.destroy(handle)
- self._shell_handle = None
+ async def _cleanup_workspace_best_effort(self, session_id: str) -> None:
+ try:
+ _ = await self._run_internal_script_complete(_workspace_cleanup_script(session_id=session_id), cwd=None)
+ except (RuntimeError, ValueError) as exc:
+ logger.warning("Failed to remove shell workspace for session %s after create failure: %s", session_id, exc)
- async def _run_internal_job_to_completion(
+ async def _run_internal_script_complete(
self,
script: str,
*,
cwd: str | None,
- ) -> ShellJobObservation:
- """Run an internal lifecycle command, track it, and wait for completion."""
- client = self._require_client()
- result = await client.run(script, cwd=cwd, env=None, timeout=DEFAULT_TIMEOUT_SECONDS)
- self._track_job_result(result)
- while not result.done:
- result = await client.wait(
- result.job_id,
- offset=self._tracked_offset(result.job_id),
- timeout=DEFAULT_TIMEOUT_SECONDS,
- )
- self._track_job_result(result)
- return _job_result_observation(result)
+ ) -> CompleteRemoteCommandResult:
+ return await execute_complete_with_commands(
+ self._require_resource().commands,
+ script,
+ cwd=cwd,
+ env=None,
+ timeout=DEFAULT_TIMEOUT_SECONDS,
+ max_output_bytes=_REMOTE_COMPLETE_OUTPUT_MAX_BYTES,
+ )
- def _require_handle(self) -> ShellctlHandle:
- """Return the live handle or reject tool/lifecycle use without one."""
- if self._shell_handle is None:
+ def _require_resource(self) -> ShellResourceProtocol:
+ if self._shell_resource is None:
raise RuntimeError(
- "DifyShellLayer requires an active shell handle inside resource_context(); "
+ "DifyShellLayer requires an active shell resource inside resource_context(); "
+ "enter the layer through Agenton or wrap direct hook/tool usage in resource_context()."
)
- return self._shell_handle
-
- def _require_client(self) -> ShellctlClientProtocol:
- """Return the live shellctl client from the handle."""
- return cast(ShellctlClientProtocol, self._require_handle().client)
+ return self._shell_resource
def _require_workspace_cwd(self) -> str:
- """Return the configured workspace directory for user-facing shell jobs."""
_session_id, workspace_cwd = self._require_session_identity()
return workspace_cwd
def _require_session_identity(self) -> tuple[str, str]:
- """Return the stored session id and workspace path or raise for corrupt state."""
identity = self._try_session_identity()
if identity is None:
raise ValueError("DifyShellLayer runtime state is missing session_id or workspace_cwd.")
@@ -631,30 +511,13 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
return session_id, workspace_cwd
def _ensure_tracked_job(self, job_id: str) -> None:
- """Reject tool access to job ids not tracked in the current runtime state.
-
- This first version treats shellctl job ids as opaque strings and uses
- membership in ``runtime_state.job_ids`` as the tool-access boundary for
- wait/input/interrupt operations.
- """
if job_id not in self.runtime_state.job_ids:
raise ValueError(f"Unknown shell job id for this session: {job_id}.")
def _tracked_offset(self, job_id: str) -> int:
- """Return the stored offset for a tracked job, defaulting legacy state to zero."""
self._ensure_tracked_job(job_id)
return int(self.runtime_state.job_offsets.get(job_id, 0))
- def _track_job_result(self, result: JobResult) -> None:
- """Track one output-oriented shellctl result in serializable runtime state."""
- self._remember_job_id(result.job_id)
- self._remember_job_offset(result.job_id, result.offset)
-
- def _track_job_status(self, result: JobStatusView) -> None:
- """Track status-only shellctl results that still carry the latest offset."""
- self._remember_job_id(result.job_id)
- self._remember_job_offset(result.job_id, result.offset)
-
def _remember_job_id(self, job_id: str) -> None:
if job_id in self.runtime_state.job_ids:
return
@@ -666,47 +529,23 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
self.runtime_state.job_offsets = job_offsets
async def _delete_tracked_jobs_best_effort(self, job_ids: Sequence[str]) -> None:
- """Force-delete tracked shellctl jobs, ignoring already-missing ones."""
+ commands = self._require_resource().commands
for job_id in _deduplicate_preserving_order(job_ids):
- await self._delete_job_best_effort(job_id)
+ try:
+ await commands.delete(job_id, force=True)
+ except RuntimeError as exc:
+ logger.warning(
+ "Failed to delete shell job %s for session %s: %s",
+ job_id,
+ self.runtime_state.session_id,
+ exc,
+ )
def _clear_tracked_jobs(self) -> None:
self.runtime_state.job_offsets = {}
self.runtime_state.job_ids = []
- async def _delete_job_best_effort(self, job_id: str) -> None:
- client = self._require_client()
- try:
- _ = await client.delete(job_id, force=True)
- except ShellctlClientError as exc:
- if exc.code == "job_not_found":
- return
- logger.warning(
- "Failed to delete shellctl job %s for session %s: %s",
- job_id,
- self.runtime_state.session_id,
- exc,
- )
- except RuntimeError as exc:
- logger.warning(
- "Failed to delete shellctl job %s for session %s: %s",
- job_id,
- self.runtime_state.session_id,
- exc,
- )
-
- def _forget_tracked_job(self, job_id: str) -> None:
- if job_id not in self.runtime_state.job_ids and job_id not in self.runtime_state.job_offsets:
- return
- job_offsets = dict(self.runtime_state.job_offsets)
- _ = job_offsets.pop(job_id, None)
- self.runtime_state.job_offsets = job_offsets
- self.runtime_state.job_ids = [
- tracked_job_id for tracked_job_id in self.runtime_state.job_ids if tracked_job_id != job_id
- ]
-
def _build_user_shell_run_env(self) -> dict[str, str] | None:
- """Build per-command Agent Stub env only for user-visible ``shell.run``."""
execution_context_layer = self.deps.execution_context
execution_context = execution_context_layer.config if execution_context_layer is not None else None
return build_shell_agent_stub_env(
@@ -718,32 +557,129 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
)
-def _shell_layer_prefix_prompt() -> str:
- """Return the static model-facing shell tool usage guidance."""
- return _SHELL_LAYER_PREFIX_PROMPT
+async def execute_complete_with_commands(
+ commands: ShellCommandProtocol,
+ script: str,
+ *,
+ cwd: str | None,
+ env: dict[str, str] | None,
+ timeout: float,
+ max_output_bytes: int,
+) -> CompleteShellCommandResult:
+ deadline = time.monotonic() + timeout
+ job_id: str | None = None
+ result: ShellCommandResult | None = None
+ output_parts: list[str] = []
+ captured_bytes = 0
+ incomplete_reason: Literal["output_limit", "timeout"] | None = None
+ try:
+ result = await commands.run(script, cwd=cwd, env=env, timeout=_remaining_time(deadline))
+ job_id = result.job_id
+ while True:
+ remaining_bytes = max(max_output_bytes - captured_bytes, 0)
+ limited_output = utf8_prefix(result.output, remaining_bytes)
+ output_parts.append(limited_output)
+ captured_bytes += len(limited_output.encode("utf-8"))
+ if limited_output != result.output:
+ incomplete_reason = "output_limit"
+ break
+ if captured_bytes >= max_output_bytes and (result.truncated or not result.done):
+ incomplete_reason = "output_limit"
+ break
+ if result.truncated:
+ result = await commands.read_output(result.job_id, offset=result.offset)
+ continue
+ if result.done:
+ break
+ remaining_time = _remaining_time(deadline)
+ if remaining_time <= 0.0:
+ incomplete_reason = "timeout"
+ break
+ result = await commands.wait(result.job_id, offset=result.offset, timeout=remaining_time)
+
+ assert result is not None
+ final_status = result.status
+ final_done = result.done
+ final_exit_code = result.exit_code
+ final_offset = result.offset
+ final_output_path = result.output_path
+ if incomplete_reason is not None and not result.done:
+ terminal_status = await commands.interrupt(result.job_id, grace_seconds=DEFAULT_TERMINATE_GRACE_SECONDS)
+ final_status = terminal_status.status
+ final_done = terminal_status.done
+ final_exit_code = terminal_status.exit_code
+ final_offset = terminal_status.offset
+ return CompleteShellCommandResult(
+ job_id=result.job_id,
+ status=final_status,
+ done=final_done,
+ exit_code=final_exit_code,
+ output="".join(output_parts),
+ output_complete=incomplete_reason is None,
+ incomplete_reason=incomplete_reason,
+ offset=final_offset,
+ output_path=final_output_path,
+ )
+ finally:
+ if job_id is not None:
+ try:
+ await commands.delete(job_id, force=True)
+ except RuntimeError as exc:
+ logger.warning("Failed to delete transient shell job %s: %s", job_id, exc)
+
+
+async def render_prompt_observation_from_result(
+ commands: ShellCommandProtocol,
+ result: ShellCommandResult,
+ *,
+ edge_bytes: int,
+) -> ShellPromptObservation:
+ output_exceeds_edge_budget = len(result.output.encode("utf-8")) > edge_bytes
+ tail: str | None = None
+ output_path = result.output_path
+ offset = result.offset
+ if result.truncated:
+ try:
+ tail_result = await commands.tail(result.job_id)
+ except RuntimeError as exc:
+ logger.warning("Failed to fetch tail for shell job %s: %s", result.job_id, exc)
+ else:
+ tail = utf8_suffix(tail_result.output, edge_bytes)
+ output_path = tail_result.output_path or output_path
+ offset = tail_result.offset
+ elif output_exceeds_edge_budget:
+ tail = utf8_suffix(result.output, edge_bytes)
+ text = normalized_output_text(
+ utf8_prefix(result.output, edge_bytes),
+ tail=tail,
+ output_path=output_path if (result.truncated or output_exceeds_edge_budget) else None,
+ max_output_size_bytes=_SHELLCTL_OUTPUT_LIMIT_BYTES,
+ truncated_in_middle=result.truncated or output_exceeds_edge_budget,
+ )
+ return ShellPromptObservation(text=text, output_path=output_path, offset=offset)
-def _job_result_observation(result: JobResult) -> ShellJobObservation:
- return {
- "job_id": result.job_id,
- "status": result.status.value,
- "done": result.done,
- "exit_code": result.exit_code,
- "output": result.output,
- "offset": result.offset,
- "truncated": result.truncated,
- "output_path": result.output_path,
- }
+def _shell_layer_prefix_prompt() -> str:
+ return _SHELL_LAYER_PREFIX_PROMPT
-def _job_status_observation(result: JobStatusView) -> ShellJobStatusObservation:
- return {
- "job_id": result.job_id,
- "status": result.status.value,
- "done": result.done,
- "exit_code": result.exit_code,
- "offset": result.offset,
+def _metadata_dict(
+ *,
+ job_id: str,
+ status: str,
+ done: bool,
+ exit_code: int | None,
+ output_path: str | None,
+) -> dict[str, object]:
+ metadata: dict[str, object] = {
+ "job_id": job_id,
+ "status": status,
+ "done": done,
+ "exit_code": exit_code,
}
+ if output_path is not None:
+ metadata["output_path"] = output_path
+ return metadata
def _tool_error(message: str, *, job_id: str | None = None) -> ShellToolErrorObservation:
@@ -753,28 +689,31 @@ def _tool_error(message: str, *, job_id: str | None = None) -> ShellToolErrorObs
return result
+def _generate_session_id() -> str:
+ time_component = int(time.time()) & _SESSION_TIME_HEX_MASK
+ random_component = secrets.token_hex(1)
+ if len(random_component) != _SESSION_RANDOM_HEX_LENGTH:
+ raise RuntimeError("Expected a one-byte random hex suffix for Dify shell session ids.")
+ return f"{time_component:05x}{random_component}"
+
+
def _workspace_cwd(session_id: str) -> str:
- return f"{_WORKSPACE_ROOT}/{session_id}"
+ return f"{_WORKSPACE_ROOT}/{_validated_session_id(session_id)}"
def _workspace_bootstrap_script(config: DifyShellLayerConfig) -> str:
- """Return the workspace bootstrap script for CLI tool declarations."""
install_commands = [command for tool in config.cli_tools for command in tool.install_commands]
if not install_commands:
return ""
-
lines: list[str] = ["set -eu", *_shell_config_export_lines(config), *install_commands]
return "\n".join(lines)
def _shell_config_export_lines(config: DifyShellLayerConfig) -> list[str]:
- """Return ephemeral Agent Soul shell exports for one shellctl command."""
lines: list[str] = []
for env_var in config.env:
lines.append(f"export {env_var.name}={_shquote(env_var.value)}")
for secret_ref in config.secret_refs:
- # Secret refs are resolved outside this public DTO. Preserve the env var
- # name without inventing a value so host-provided env can flow through.
lines.append(f'export {secret_ref.name}="${{{secret_ref.name}:-}}"')
for tool in config.cli_tools:
for env_var in tool.env:
@@ -791,18 +730,37 @@ def _shell_config_export_lines(config: DifyShellLayerConfig) -> list[str]:
def _wrap_user_script(script: str, config: DifyShellLayerConfig) -> str:
- """Inject Agent Soul env before executing a model-requested shell command."""
lines = _shell_config_export_lines(config)
if not lines:
return script
return "\n".join([*lines, script])
+def _workspace_mkdir_script(*, session_id: str) -> str:
+ safe_session_id = _validated_session_id(session_id)
+ workspace_dir = f"$HOME/workspace/{safe_session_id}"
+ return (
+ 'mkdir -p "$HOME/workspace"; '
+ f'if mkdir "{workspace_dir}"; then exit 0; fi; '
+ f'if [ -e "{workspace_dir}" ]; then exit {_WORKSPACE_COLLISION_EXIT_CODE}; fi; '
+ "exit 1"
+ )
+
+
+def _workspace_cleanup_script(*, session_id: str) -> str:
+ return f'rm -rf -- "$HOME/workspace/{_validated_session_id(session_id)}"'
+
+
def _shquote(value: str) -> str:
- """Single-quote a value for POSIX shells, escaping embedded single quotes."""
return "'" + value.replace("'", "'\\''") + "'"
+def _validated_session_id(session_id: str) -> str:
+ if not _SESSION_ID_PATTERN.fullmatch(session_id):
+ raise ValueError("session_id must match the 5+2 lowercase hex format '<5 hex><2 hex>'.")
+ return session_id
+
+
def _deduplicate_preserving_order(values: Sequence[str]) -> list[str]:
seen: set[str] = set()
result: list[str] = []
@@ -814,10 +772,22 @@ def _deduplicate_preserving_order(values: Sequence[str]) -> list[str]:
return result
+def _tagged_shell_observation(metadata: dict[str, object], output: str) -> str:
+ compact_metadata = json.dumps(metadata, separators=(",", ":"))
+ return f"<metadata>\n{compact_metadata}\n</metadata>\n\n<output>\n{output}\n</output>"
+
+
+def _remaining_time(deadline: float) -> float:
+ return max(0.0, deadline - time.monotonic())
+
+
__all__ = [
- "DifyShellLayerDeps",
+ "CompleteRemoteCommandResult",
"DifyShellLayer",
+ "DifyShellLayerDeps",
"DifyShellRuntimeState",
- "RemoteCommandResult",
- "ShellctlClientProtocol",
+ "DEFAULT_TERMINATE_GRACE_SECONDS",
+ "DEFAULT_TIMEOUT_SECONDS",
+ "execute_complete_with_commands",
+ "render_prompt_observation_from_result",
]
diff --git a/dify-agent/src/dify_agent/layers/shell/output_text.py b/dify-agent/src/dify_agent/layers/shell/output_text.py
new file mode 100644
index 00000000000..04ec3329844
--- /dev/null
+++ b/dify-agent/src/dify_agent/layers/shell/output_text.py
@@ -0,0 +1,55 @@
+"""Helpers for formatting shell output into bounded prompt-safe text.
+
+The shell layer uses byte budgets, not Python character counts, because
+shellctl output windows are byte-limited. These helpers keep UTF-8 boundaries
+valid while producing a compact head/tail rendering for model-visible output.
+"""
+
+from __future__ import annotations
+
+
+def utf8_prefix(text: str, max_bytes: int) -> str:
+ """Return the longest UTF-8-safe prefix that fits within ``max_bytes``."""
+ if max_bytes <= 0:
+ return ""
+ return text.encode("utf-8")[:max_bytes].decode("utf-8", errors="ignore")
+
+
+def utf8_suffix(text: str, max_bytes: int) -> str:
+ """Return the longest UTF-8-safe suffix that fits within ``max_bytes``."""
+ if max_bytes <= 0:
+ return ""
+ return text.encode("utf-8")[-max_bytes:].decode("utf-8", errors="ignore")
+
+
+def normalized_output_text(
+ head: str,
+ *,
+ tail: str | None,
+ output_path: str | None,
+ max_output_size_bytes: int,
+ truncated_in_middle: bool | None = None,
+ truncation_message: str | None = None,
+) -> str:
+ """Format bounded shell output with an optional truncation marker and log path."""
+ if truncated_in_middle is None:
+ truncated_in_middle = tail is not None and tail != head
+ if not truncated_in_middle:
+ return head
+ if truncation_message is None:
+ truncation_message = (
+ f"truncated in middle because the max output size is limited to {max_output_size_bytes} bytes"
+ )
+
+ parts = [
+ head,
+ f"... ({truncation_message}) ...",
+ ]
+ if tail is not None:
+ parts.append(tail)
+ if output_path:
+ parts.append(f"(check the {output_path} for full output)")
+ return "\n".join(parts)
+
+
+__all__ = ["normalized_output_text", "utf8_prefix", "utf8_suffix"]
diff --git a/dify-agent/src/dify_agent/protocol/sandbox.py b/dify-agent/src/dify_agent/protocol/sandbox.py
index 3d7b9aad129..83f3d4b0adc 100644
--- a/dify-agent/src/dify_agent/protocol/sandbox.py
+++ b/dify-agent/src/dify_agent/protocol/sandbox.py
@@ -4,8 +4,8 @@ The sandbox file APIs must rebuild only the minimum runtime needed to re-enter a
prior shell session: ``dify.execution_context`` for Dify-owned identity and
``dify.shell`` for the sandbox workspace itself. ``SandboxLocator`` therefore
contains a safe composition subset plus the matching filtered session snapshot.
-Credential-bearing plugin layers are intentionally excluded from persisted
-runtime specs and from sandbox locators.
+Credential-bearing or runtime-only tool layers are intentionally excluded from
+persisted runtime specs and from sandbox locators.
"""
from __future__ import annotations
@@ -14,12 +14,19 @@ from typing import ClassVar, Literal, cast
from agenton.compositor import CompositorSessionSnapshot
from agenton.compositor.schemas import LayerSessionSnapshot
+from dify_agent.layers.dify_core_tools import DIFY_CORE_TOOLS_LAYER_TYPE_ID
from dify_agent.layers.dify_plugin import DIFY_PLUGIN_LLM_LAYER_TYPE_ID, DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID
from pydantic import BaseModel, ConfigDict, Field, JsonValue
from .schemas import CreateRunRequest, RunComposition, RunLayerSpec
-_SENSITIVE_LAYER_TYPES = frozenset({DIFY_PLUGIN_LLM_LAYER_TYPE_ID, DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID})
+_SENSITIVE_LAYER_TYPES = frozenset(
+ {
+ DIFY_PLUGIN_LLM_LAYER_TYPE_ID,
+ DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID,
+ DIFY_CORE_TOOLS_LAYER_TYPE_ID,
+ }
+)
class RuntimeLayerSpec(BaseModel):
diff --git a/dify-agent/src/dify_agent/runtime/compositor_factory.py b/dify-agent/src/dify_agent/runtime/compositor_factory.py
index 1a70d306809..9772663c020 100644
--- a/dify-agent/src/dify_agent/runtime/compositor_factory.py
+++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py
@@ -6,25 +6,28 @@ state-free Dify structured output layer, the optional Dify ask-human layer, the
Dify execution-context layer, the stateful Dify shell layer, and the Dify
plugin/knowledge business-layer family:
-- ``dify.drive`` for drive-backed skill catalog + eager pull,
+- ``dify.config`` for Agent Soul-backed config assets + eager pull,
- ``dify.execution_context`` for shared tenant/user/run daemon context,
- ``dify.shell`` for shellctl-backed shell job control,
- ``dify.plugin.llm`` for plugin-backed model selection,
- ``dify.plugin.tools`` for prepared plugin tool exposure, and
+- ``dify.core.tools`` for API-routed Dify tool exposure, and
- ``dify.knowledge_base`` for inner-API-backed knowledge search tools.
Public DTOs provide Dify context plus plugin/model/tool data, while server-only
plugin daemon settings and Dify API inner settings are injected through provider
-factories. Optional shellctl entrypoint/auth token, client factory, and Agent
-Stub URL/token issuer are injected for ``DifyShellLayer``. The resulting
-``Compositor`` remains Agenton state-only at the snapshot boundary: live
-resources such as HTTP clients are injected by runtime-owned providers, may be
-held on active layer instances inside ``resource_context()``, and never enter
-session snapshots.
+factories. Optional shellctl entrypoint/auth token and Agent Stub URL/token
+issuer are injected for ``DifyShellLayer``. The resulting ``Compositor``
+remains Agenton state-only at the snapshot boundary: live resources such as
+HTTP clients are injected by runtime-owned providers, may be held on active
+layer instances inside ``resource_context()``, and never enter session
+snapshots.
"""
+from __future__ import annotations
+
from collections.abc import Mapping, Sequence
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, cast
from pydantic_ai.messages import UserContent
@@ -34,8 +37,10 @@ from agenton_collections.layers.pydantic_ai import PydanticAIHistoryLayer
from agenton_collections.layers.plain.basic import PromptLayer
from agenton_collections.transformers.pydantic_ai import PYDANTIC_AI_TRANSFORMERS
from dify_agent.agent_stub.server.shell_agent_stub_env import ShellAgentStubTokenFactory
-from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodec
from dify_agent.layers.ask_human.layer import DifyAskHumanLayer
+from dify_agent.layers.config.layer import DifyConfigLayer
+from dify_agent.layers.dify_core_tools.configs import DifyCoreToolsLayerConfig
+from dify_agent.layers.dify_core_tools.layer import DifyCoreToolsLayer
from dify_agent.layers.dify_plugin.llm_layer import DifyPluginLLMLayer
from dify_agent.layers.dify_plugin.tools_layer import DifyPluginToolsLayer
from dify_agent.layers.drive.layer import DifyDriveLayer
@@ -45,10 +50,13 @@ from dify_agent.layers.knowledge.configs import DifyKnowledgeBaseLayerConfig
from dify_agent.layers.knowledge.layer import DifyKnowledgeBaseLayer
from dify_agent.layers.output.output_layer import DifyOutputLayer
from dify_agent.adapters.shell.config import ShellAdapterSettings
-from dify_agent.adapters.shell.factory import create_shell_provisioner
+from dify_agent.adapters.shell.factory import create_shell_provider
from dify_agent.layers.shell.configs import DifyShellLayerConfig
from dify_agent.layers.shell.layer import DifyShellLayer
+if TYPE_CHECKING:
+ from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodec
+
type DifyAgentLayerProvider = LayerProvider[Any]
@@ -84,11 +92,23 @@ def create_default_layer_providers(
)
agent_stub_token_factory = build_agent_stub_token
+ shell_provider = (
+ create_shell_provider(
+ ShellAdapterSettings(
+ shell_provider="shellctl",
+ shellctl_entrypoint=shellctl_entrypoint,
+ shellctl_auth_token=shellctl_auth_token,
+ )
+ )
+ if shellctl_entrypoint
+ else None
+ )
return (
LayerProvider.from_layer_type(PromptLayer),
LayerProvider.from_layer_type(PydanticAIHistoryLayer),
LayerProvider.from_layer_type(DifyOutputLayer),
LayerProvider.from_layer_type(DifyAskHumanLayer),
+ LayerProvider.from_layer_type(DifyConfigLayer),
LayerProvider.from_layer_type(DifyDriveLayer),
LayerProvider.from_factory(
layer_type=DifyExecutionContextLayer,
@@ -102,21 +122,21 @@ def create_default_layer_providers(
layer_type=DifyShellLayer,
create=lambda config: DifyShellLayer.from_config_with_settings(
DifyShellLayerConfig.model_validate(config),
- shell_provisioner=create_shell_provisioner(
- ShellAdapterSettings(
- shell_provider="shellctl",
- shellctl_entrypoint=shellctl_entrypoint,
- shellctl_auth_token=shellctl_auth_token,
- )
- )
- if shellctl_entrypoint
- else None,
+ shell_provider=shell_provider,
agent_stub_api_base_url=agent_stub_api_base_url,
agent_stub_token_factory=agent_stub_token_factory,
),
),
LayerProvider.from_layer_type(DifyPluginLLMLayer),
LayerProvider.from_layer_type(DifyPluginToolsLayer),
+ LayerProvider.from_factory(
+ layer_type=DifyCoreToolsLayer,
+ create=lambda config: DifyCoreToolsLayer.from_config_with_settings(
+ DifyCoreToolsLayerConfig.model_validate(config),
+ inner_api_url=inner_api_url,
+ inner_api_key=inner_api_key,
+ ),
+ ),
LayerProvider.from_factory(
layer_type=DifyKnowledgeBaseLayer,
create=lambda config: DifyKnowledgeBaseLayer.from_config_with_settings(
diff --git a/dify-agent/src/dify_agent/server/app.py b/dify-agent/src/dify_agent/server/app.py
index 50f27660e77..ab619b7509a 100644
--- a/dify-agent/src/dify_agent/server/app.py
+++ b/dify-agent/src/dify_agent/server/app.py
@@ -40,6 +40,7 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:
resolved_settings = settings or ServerSettings()
agent_stub_token_codec = resolved_settings.create_agent_stub_token_codec()
agent_stub_file_request_handler = resolved_settings.create_agent_stub_file_request_handler()
+ agent_stub_config_request_handler = resolved_settings.create_agent_stub_config_request_handler()
agent_stub_drive_request_handler = resolved_settings.create_agent_stub_drive_request_handler()
layer_providers = create_default_layer_providers(
plugin_daemon_url=resolved_settings.plugin_daemon_url,
@@ -111,6 +112,7 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:
create_agent_stub_router(
token_codec=agent_stub_token_codec,
file_request_handler=agent_stub_file_request_handler,
+ config_request_handler=agent_stub_config_request_handler,
drive_request_handler=agent_stub_drive_request_handler,
)
)
diff --git a/dify-agent/src/dify_agent/server/sandbox_files.py b/dify-agent/src/dify_agent/server/sandbox_files.py
index 034fcf1d06b..78f5210b6aa 100644
--- a/dify-agent/src/dify_agent/server/sandbox_files.py
+++ b/dify-agent/src/dify_agent/server/sandbox_files.py
@@ -4,7 +4,7 @@ Unlike the removed workspace inspector, this service never talks to shellctl
directly and never reads sandbox files outside the shell layer. It rebuilds a
minimal compositor from ``SandboxLocator``, enters the saved
``execution_context`` + ``shell`` layers, and executes fixed scripts through
-``DifyShellLayer.run_remote_script()``.
+``DifyShellLayer.run_remote_script_complete()``.
The scripts still frame their structured payloads with a PTY-safe
base64-between-sentinels envelope. shellctl jobs are tmux-backed, so raw JSON can
@@ -22,7 +22,8 @@ import textwrap
from dataclasses import dataclass
from typing import TypeVar, cast
-from dify_agent.layers.shell.layer import DifyShellLayer, RemoteCommandResult
+from dify_agent.layers.shell.layer import CompleteRemoteCommandResult, DifyShellLayer
+from dify_agent.layers.shell.output_text import utf8_suffix
from dify_agent.protocol import (
SandboxListRequest,
SandboxListResponse,
@@ -42,6 +43,7 @@ _READ_TIMEOUT_SECONDS = 15.0
_UPLOAD_TIMEOUT_SECONDS = 30.0
_OUTPUT_BEGIN = "<<<DIFY_SANDBOX_BEGIN>>>"
_OUTPUT_END = "<<<DIFY_SANDBOX_END>>>"
+_SHELL_RESULT_OUTPUT_TAIL_BYTES = 8 * 1024
ResponseModelT = TypeVar("ResponseModelT", bound=BaseModel)
_LIST_SCRIPT = """
@@ -294,7 +296,7 @@ class SandboxFileService:
async with compositor.enter(configs=layer_configs, session_snapshot=locator.session_snapshot) as run:
run.suspend_on_exit()
shell_layer = run.get_layer("shell", DifyShellLayer)
- result = await shell_layer.run_remote_script(
+ result = await shell_layer.run_remote_script_complete(
_build_python_script_command(script_source=script_source, args=args),
timeout=timeout,
inject_agent_stub_env=inject_agent_stub_env,
@@ -328,16 +330,23 @@ def _build_python_script_command(*, script_source: str, args: list[str]) -> str:
return f"python3 - {quoted_args} <<'PY'\n{script}\nPY"
-def _decode_sandbox_payload(result: RemoteCommandResult) -> dict[str, object]:
+def _decode_sandbox_payload(result: CompleteRemoteCommandResult) -> dict[str, object]:
if result.exit_code not in (0, None):
raise SandboxFileError(
"sandbox_command_failed",
- f"sandbox command exited with code {result.exit_code}: {_output_tail(result.output)!r}",
+ "sandbox command exited with code " + f"{result.exit_code}: {_shell_result_details(result)}",
status_code=502,
)
begin = result.output.find(_OUTPUT_BEGIN)
end = result.output.find(_OUTPUT_END, begin + len(_OUTPUT_BEGIN)) if begin != -1 else -1
if begin == -1 or end == -1:
+ if not result.output_complete:
+ raise SandboxFileError(
+ "sandbox_command_failed",
+ "sandbox command output incomplete before framed payload was captured: "
+ + _shell_result_details(result),
+ status_code=502,
+ )
raise SandboxFileError(
"sandbox_command_failed",
"sandbox command returned no framed payload",
@@ -349,12 +358,25 @@ def _decode_sandbox_payload(result: RemoteCommandResult) -> dict[str, object]:
decoded = base64.b64decode(compact, validate=True)
loaded = cast(object, json.loads(decoded.decode("utf-8")))
except (binascii.Error, ValueError) as exc:
+ if not result.output_complete:
+ raise SandboxFileError(
+ "sandbox_command_failed",
+ "sandbox command output incomplete while decoding framed payload: " + _shell_result_details(result),
+ status_code=502,
+ ) from exc
raise SandboxFileError(
"sandbox_command_failed",
f"sandbox command returned invalid framed payload: {exc}",
status_code=502,
) from exc
if not isinstance(loaded, dict):
+ if not result.output_complete:
+ raise SandboxFileError(
+ "sandbox_command_failed",
+ "sandbox command output incomplete while validating framed payload object: "
+ + _shell_result_details(result),
+ status_code=502,
+ )
raise SandboxFileError(
"sandbox_command_failed", "sandbox command returned a non-object payload", status_code=502
)
@@ -379,9 +401,22 @@ def _decode_sandbox_payload(result: RemoteCommandResult) -> dict[str, object]:
return payload
-def _output_tail(output: str) -> str:
- stripped = output.strip()
- return stripped[-200:]
+def _shell_result_details(result: CompleteRemoteCommandResult) -> str:
+ details = (
+ f"output_complete={result.output_complete} "
+ + f"incomplete_reason={result.incomplete_reason} "
+ + f"output_path={result.output_path}"
+ )
+ if not result.output:
+ return details
+ return details + "\n" + _bounded_output_tail(result.output)
+
+
+def _bounded_output_tail(output: str) -> str:
+ tail = utf8_suffix(output, _SHELL_RESULT_OUTPUT_TAIL_BYTES)
+ if tail == output:
+ return output
+ return f"... (showing last {_SHELL_RESULT_OUTPUT_TAIL_BYTES} bytes of raw output) ...\n{tail}"
def _validate_response_model(
diff --git a/dify-agent/src/dify_agent/server/settings.py b/dify-agent/src/dify_agent/server/settings.py
index 7c16a8e50b1..e614ed336b4 100644
--- a/dify-agent/src/dify_agent/server/settings.py
+++ b/dify-agent/src/dify_agent/server/settings.py
@@ -18,6 +18,7 @@ from pydantic import AnyHttpUrl, Field, TypeAdapter, field_validator, model_vali
from pydantic_settings import BaseSettings, SettingsConfigDict
from dify_agent.agent_stub.protocol.agent_stub import normalize_agent_stub_api_base_url, parse_agent_stub_endpoint
+from dify_agent.agent_stub.server.agent_stub_config import DifyApiAgentStubConfigRequestHandler
from dify_agent.agent_stub.server.agent_stub_drive import DifyApiAgentStubDriveRequestHandler
from dify_agent.agent_stub.server.agent_stub_files import DifyApiAgentStubFileRequestHandler
from dify_agent.agent_stub.server.grpc_bind import normalize_agent_stub_grpc_bind_address
@@ -145,6 +146,16 @@ class ServerSettings(BaseSettings):
inner_api_key=self.inner_api_key,
)
+ def create_agent_stub_config_request_handler(self) -> DifyApiAgentStubConfigRequestHandler | None:
+ """Return the Dify API config bridge when both Dify API settings are configured."""
+ if self.inner_api_key is None:
+ return None
+ return DifyApiAgentStubConfigRequestHandler(
+ inner_api_url=self.inner_api_url,
+ inner_api_key=self.inner_api_key,
+ timeout=self.create_outbound_http_timeout(),
+ )
+
def create_agent_stub_drive_request_handler(self) -> DifyApiAgentStubDriveRequestHandler | None:
"""Return the Dify API drive bridge when both Dify API settings are configured.
diff --git a/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py b/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py
index 74b11175c0d..dca0a9e7376 100644
--- a/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py
+++ b/dify-agent/tests/local/dify_agent/adapters/shell/test_shellctl.py
@@ -1,14 +1,9 @@
-"""Local tests for the shellctl shell adapter and env-driven provider factory.
+"""Local tests for the shellctl shell adapter and env-driven provider factory."""
-These exercise the provider-agnostic boundary contract (provision/execute/wait,
-file transfer, optional input/interrupt) against a fake shellctl client, plus the
-``DIFY_AGENT_SHELL_PROVIDER`` selection in the factory. They avoid the private
-``shell-session-manager`` package by injecting a structural fake client.
-"""
+from __future__ import annotations
import asyncio
import base64
-import secrets
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -16,37 +11,30 @@ import pytest
from dify_agent.adapters.shell import shellctl
from dify_agent.adapters.shell.config import ShellAdapterSettings
-from dify_agent.adapters.shell.factory import create_shell_provisioner
-from dify_agent.adapters.shell.protocols import (
- ShellEnvironmentDescriptor,
-)
-from dify_agent.adapters.shell.shellctl import (
- ShellctlEnvironmentDescriptor,
- ShellctlProvisioner,
- ShellFileTransferError,
- ShellProvisionError,
-)
-
-_SESSION_HEX = "deadbeefdeadbeef"
-_WORKSPACE_CWD = f"~/workspace/{_SESSION_HEX}"
+from dify_agent.adapters.shell.factory import create_shell_provider
+from dify_agent.adapters.shell.protocols import ShellCommandResult
+from dify_agent.adapters.shell.shellctl import ShellFileTransferError, ShellProviderError, ShellctlProvider
@dataclass(slots=True)
class _Job:
job_id: str
+ status: str = "running"
done: bool = True
output: str = ""
offset: int = 0
truncated: bool = False
exit_code: int | None = 0
+ output_path: str | None = "/tmp/output.log"
@dataclass(slots=True)
class _Status:
job_id: str
+ status: str = "terminated"
done: bool = True
offset: int = 0
- exit_code: int | None = 0
+ exit_code: int | None = 130
@dataclass(slots=True)
@@ -54,278 +42,290 @@ class _RunCall:
script: str
cwd: str | None
env: dict[str, str] | None
+ timeout: float
-type _RunHandler = Callable[[str, str | None, dict[str, str] | None], _Job]
-type _WaitHandler = Callable[[str, int], _Job]
-type _InputHandler = Callable[[str, str, int], _Job]
-type _TerminateHandler = Callable[[str], _Status]
+type _RunHandler = Callable[[str, str | None, dict[str, str] | None, float], _Job]
+type _WaitHandler = Callable[[str, int, float], _Job]
+type _InputHandler = Callable[[str, str, int, float], _Job]
+type _TerminateHandler = Callable[[str, float], _Status]
@dataclass(slots=True)
class FakeShellctlClient:
- """Structural shellctl client double recording calls and replaying handlers."""
-
run_handler: _RunHandler | None = None
wait_handler: _WaitHandler | None = None
input_handler: _InputHandler | None = None
+ tail_handler: Callable[[str], _Job] | None = None
terminate_handler: _TerminateHandler | None = None
run_calls: list[_RunCall] = field(default_factory=list)
- wait_calls: list[tuple[str, int]] = field(default_factory=list)
- input_calls: list[tuple[str, str, int]] = field(default_factory=list)
+ wait_calls: list[tuple[str, int, float]] = field(default_factory=list)
+ input_calls: list[tuple[str, str, int, float]] = field(default_factory=list)
terminate_calls: list[tuple[str, float]] = field(default_factory=list)
- delete_calls: list[str] = field(default_factory=list)
+ delete_calls: list[tuple[str, bool, float | None]] = field(default_factory=list)
closed: bool = False
async def run(self, script, *, cwd=None, env=None, timeout=30.0):
- del timeout
- self.run_calls.append(_RunCall(script=script, cwd=cwd, env=env))
+ self.run_calls.append(_RunCall(script=script, cwd=cwd, env=env, timeout=timeout))
if self.run_handler is not None:
- return self.run_handler(script, cwd, env)
- return _Job(job_id="job", done=True, exit_code=0)
+ return self.run_handler(script, cwd, env, timeout)
+ return _Job(job_id="job", status="exited", done=True, exit_code=0)
async def wait(self, job_id, *, offset, timeout=30.0):
- del timeout
- self.wait_calls.append((job_id, offset))
+ self.wait_calls.append((job_id, offset, timeout))
if self.wait_handler is not None:
- return self.wait_handler(job_id, offset)
- return _Job(job_id=job_id, done=True, offset=offset, exit_code=0)
+ return self.wait_handler(job_id, offset, timeout)
+ return _Job(job_id=job_id, status="exited", done=True, offset=offset, exit_code=0)
async def input(self, job_id, text, *, offset, timeout=30.0):
- del timeout
- self.input_calls.append((job_id, text, offset))
+ self.input_calls.append((job_id, text, offset, timeout))
if self.input_handler is not None:
- return self.input_handler(job_id, text, offset)
- return _Job(job_id=job_id, done=True, offset=offset, exit_code=0)
+ return self.input_handler(job_id, text, offset, timeout)
+ return _Job(job_id=job_id, status="exited", done=True, offset=offset, exit_code=0)
+
+ async def tail(self, job_id):
+ if self.tail_handler is not None:
+ return self.tail_handler(job_id)
+ return _Job(job_id=job_id, status="exited", done=True, output="", exit_code=0)
async def terminate(self, job_id, grace_seconds=10.0):
self.terminate_calls.append((job_id, grace_seconds))
if self.terminate_handler is not None:
- return self.terminate_handler(job_id)
- return _Status(job_id=job_id, done=True, exit_code=130)
+ return self.terminate_handler(job_id, grace_seconds)
+ return _Status(job_id=job_id)
- async def delete(self, job_id, *, force=False):
- del force
- self.delete_calls.append(job_id)
+ async def delete(self, job_id, *, force=False, grace_seconds=None):
+ self.delete_calls.append((job_id, force, grace_seconds))
return None
async def close(self):
self.closed = True
[email protected](autouse=True)
-def _fixed_session_id(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: _SESSION_HEX)
-
-
-def _provisioner(client: FakeShellctlClient) -> ShellctlProvisioner:
- return ShellctlProvisioner(client_factory=lambda: client)
-
-
-def test_provision_allocates_workspace_and_execute_drains_merged_output() -> None:
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del env
- if script.startswith("mkdir"):
- assert cwd is None
- return _Job(job_id="mkdir-job", done=True, exit_code=0)
- assert cwd == _WORKSPACE_CWD
- return _Job(job_id="user-job", done=False, output="par", offset=3, truncated=False, exit_code=None)
-
- def wait_handler(job_id: str, offset: int) -> _Job:
- assert job_id == "user-job"
- assert offset == 3
- return _Job(job_id="user-job", done=True, output="tial", offset=7, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)
-
- async def scenario() -> None:
- handle = await _provisioner(client).provision()
- assert handle.workspace_cwd == _WORKSPACE_CWD
- executor = await handle.get_executor()
- result = await executor.execute("pwd", env={"FOO": "bar"})
- assert result.stdout() == "partial"
- assert result.stderr() == ""
- assert result.exit_code() == 0
- assert result.truncated() is False
-
- asyncio.run(scenario())
-
- assert client.run_calls[0].cwd is None
- user_run = next(call for call in client.run_calls if call.script == "pwd")
- assert user_run.env == {"FOO": "bar"}
- # completed jobs (internal mkdir + user command) are self-cleaned.
- assert "mkdir-job" in client.delete_calls
- assert "user-job" in client.delete_calls
+def _provider(client: FakeShellctlClient) -> ShellctlProvider:
+ return ShellctlProvider(entrypoint="http://shellctl", token="", client_factory=lambda: client)
-def test_execute_reports_truncated_when_output_window_cap_is_hit() -> None:
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del cwd, env
- if script.startswith("mkdir"):
- return _Job(job_id="mkdir-job", done=True, exit_code=0)
- return _Job(job_id="user-job", done=False, output="x", offset=1, truncated=True, exit_code=None)
+def test_factory_unknown_provider_raises() -> None:
+ settings = ShellAdapterSettings(shell_provider="nope")
+ with pytest.raises(ValueError, match="Unknown shell provider"):
+ create_shell_provider(settings)
- def wait_handler(job_id: str, offset: int) -> _Job:
- return _Job(job_id=job_id, done=False, output="x", offset=offset + 1, truncated=True, exit_code=None)
- client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)
+def test_factory_shellctl_requires_entrypoint() -> None:
+ settings = ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=None)
+ with pytest.raises(ValueError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):
+ create_shell_provider(settings)
- async def scenario() -> bool:
- handle = await _provisioner(client).provision()
- executor = await handle.get_executor()
- result = await executor.execute("tail -f log")
- return result.truncated()
- assert asyncio.run(scenario()) is True
- # a job that never completed is left intact (not deleted/forgotten).
- assert "user-job" not in client.delete_calls
+def test_factory_builds_shellctl_provider_from_settings() -> None:
+ settings = ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint="http://shellctl.example")
+ provider = create_shell_provider(settings)
+ assert isinstance(provider, ShellctlProvider)
+ assert provider.entrypoint == "http://shellctl.example"
+ assert provider.token == ""
-def test_provision_failure_closes_client_and_raises() -> None:
- client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env: _Job(job_id="mkdir-job", done=True, exit_code=1)
- )
+def test_provider_create_opens_only_live_resource_and_close_closes_client() -> None:
+ client = FakeShellctlClient()
async def scenario() -> None:
- with pytest.raises(ShellProvisionError):
- await _provisioner(client).provision()
+ resource = await _provider(client).create()
+ assert client.run_calls == []
+ await resource.close()
asyncio.run(scenario())
assert client.closed is True
-def test_destroy_runs_cleanup_in_default_cwd_then_closes_client() -> None:
- client = FakeShellctlClient(run_handler=lambda _script, _cwd, _env: _Job(job_id="job", done=True, exit_code=0))
+def test_commands_forward_parameters_and_map_metadata() -> None:
+ client = FakeShellctlClient(
+ run_handler=lambda script, cwd, env, timeout: _Job(
+ job_id="run-job",
+ status="running",
+ done=False,
+ output="abc",
+ offset=3,
+ truncated=True,
+ exit_code=None,
+ output_path="/tmp/run.log",
+ ),
+ wait_handler=lambda job_id, offset, timeout: _Job(
+ job_id=job_id,
+ status="running",
+ done=False,
+ output="def",
+ offset=6,
+ truncated=False,
+ exit_code=None,
+ output_path="/tmp/run.log",
+ ),
+ input_handler=lambda job_id, text, offset, timeout: _Job(
+ job_id=job_id,
+ status="exited",
+ done=True,
+ output="ghi",
+ offset=9,
+ truncated=False,
+ exit_code=0,
+ output_path="/tmp/run.log",
+ ),
+ tail_handler=lambda job_id: _Job(
+ job_id=job_id,
+ status="exited",
+ done=True,
+ output="tail",
+ offset=11,
+ truncated=False,
+ exit_code=0,
+ output_path="/tmp/tail.log",
+ ),
+ terminate_handler=lambda job_id, grace_seconds: _Status(
+ job_id=job_id,
+ status="terminated",
+ done=True,
+ offset=12,
+ exit_code=130,
+ ),
+ )
async def scenario() -> None:
- provisioner = _provisioner(client)
- handle = await provisioner.provision()
- await provisioner.destroy(handle)
+ resource = await _provider(client).create()
+ run_result = await resource.commands.run("pwd", cwd="~/workspace/abc12ff", env={"FOO": "bar"}, timeout=2.5)
+ wait_result = await resource.commands.wait("run-job", offset=3, timeout=4.0)
+ read_result = await resource.commands.read_output("run-job", offset=6)
+ input_result = await resource.commands.input("run-job", "ls\n", offset=6, timeout=5.0)
+ interrupt_result = await resource.commands.interrupt("run-job", grace_seconds=1.5)
+ tail_result = await resource.commands.tail("run-job")
+ await resource.commands.delete("run-job", force=True, grace_seconds=2.0)
+ await resource.close()
+
+ assert run_result == ShellCommandResult(
+ job_id="run-job",
+ status="running",
+ done=False,
+ exit_code=None,
+ output="abc",
+ offset=3,
+ truncated=True,
+ output_path="/tmp/run.log",
+ )
+ assert wait_result.offset == 6
+ assert read_result.offset == 6
+ assert input_result.exit_code == 0
+ assert interrupt_result.status == "terminated"
+ assert tail_result.output_path == "/tmp/tail.log"
asyncio.run(scenario())
- cleanup_call = client.run_calls[-1]
- assert cleanup_call.cwd is None
- assert _SESSION_HEX in cleanup_call.script and cleanup_call.script.startswith("rm -rf")
- assert client.closed is True
+ assert client.run_calls == [_RunCall(script="pwd", cwd="~/workspace/abc12ff", env={"FOO": "bar"}, timeout=2.5)]
+ assert client.wait_calls == [
+ ("run-job", 3, 4.0),
+ ("run-job", 6, 0.0),
+ ]
+ assert client.input_calls == [("run-job", "ls\n", 6, 5.0)]
+ assert client.terminate_calls == [("run-job", 1.5)]
+ assert client.delete_calls == [("run-job", True, 2.0)]
-def test_file_transfer_download_decodes_sentinel_framed_base64() -> None:
+def test_files_upload_and_download_still_work() -> None:
content = b"hello \x00 world"
encoded = base64.b64encode(content).decode("ascii")
- framed = f"noise{shellctl._TRANSFER_BEGIN}{encoded}{shellctl._TRANSFER_END}trailing"
-
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del env
- if script.startswith("mkdir"):
- return _Job(job_id="mkdir-job", done=True, exit_code=0)
- assert cwd == _WORKSPACE_CWD
- return _Job(job_id="dl-job", done=True, output=framed, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler)
+ client = FakeShellctlClient(
+ run_handler=lambda script, cwd, env, timeout: (
+ _Job(job_id="ul-job", status="exited", done=True, exit_code=0)
+ if "base64 -d" in script
+ else _Job(
+ job_id="dl-job",
+ status="exited",
+ done=True,
+ exit_code=0,
+ output=f"noise{shellctl._TRANSFER_BEGIN}{encoded}{shellctl._TRANSFER_END}tail",
+ )
+ )
+ )
async def scenario() -> None:
- handle = await _provisioner(client).provision()
- transfer = await handle.get_file_transfer()
- downloaded = await transfer.download(remote_path="report.txt")
+ resource = await _provider(client).create()
+ await resource.files.upload(content=content, remote_path="out.bin", cwd="~/workspace/abc12ff")
+ downloaded = await resource.files.download(remote_path="report.txt", cwd="~/workspace/abc12ff")
assert downloaded == content
asyncio.run(scenario())
-def test_file_transfer_download_missing_file_raises() -> None:
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del cwd, env
- if script.startswith("mkdir"):
- return _Job(job_id="mkdir-job", done=True, exit_code=0)
- return _Job(job_id="dl-job", done=True, output="", exit_code=shellctl._DOWNLOAD_MISSING_EXIT_CODE)
-
- client = FakeShellctlClient(run_handler=run_handler)
-
- async def scenario() -> None:
- handle = await _provisioner(client).provision()
- transfer = await handle.get_file_transfer()
- with pytest.raises(ShellFileTransferError, match="not found"):
- await transfer.download(remote_path="missing.txt")
+def test_file_transfer_timeout_is_an_end_to_end_budget(monkeypatch: pytest.MonkeyPatch) -> None:
+ clock = {"value": 100.0}
- asyncio.run(scenario())
+ def fake_monotonic() -> float:
+ return clock["value"]
+ monkeypatch.setattr(shellctl.time, "monotonic", fake_monotonic)
-def test_file_transfer_upload_embeds_base64_and_succeeds() -> None:
- content = b"payload-bytes"
- encoded = base64.b64encode(content).decode("ascii")
+ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None, timeout: float) -> _Job:
+ del script, cwd, env
+ assert timeout == pytest.approx(5.0, rel=0, abs=0.01)
+ clock["value"] = 103.5
+ return _Job(job_id="upload-job", status="running", done=False, output="part-1", offset=6, exit_code=None)
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del env
- if script.startswith('mkdir -p "$HOME'):
- return _Job(job_id="mkdir-job", done=True, exit_code=0)
- assert cwd == _WORKSPACE_CWD
- assert encoded in script
- return _Job(job_id="ul-job", done=True, exit_code=0)
+ def wait_handler(job_id: str, offset: int, timeout: float) -> _Job:
+ assert job_id == "upload-job"
+ assert offset == 6
+ assert timeout == pytest.approx(1.5, rel=0, abs=0.01)
+ return _Job(job_id=job_id, status="exited", done=True, output="part-2", offset=12, exit_code=0)
- client = FakeShellctlClient(run_handler=run_handler)
+ client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)
async def scenario() -> None:
- handle = await _provisioner(client).provision()
- transfer = await handle.get_file_transfer()
- await transfer.upload(content=content, remote_path="out.bin")
+ transfer = shellctl.ShellctlFileTransfer(client=client, timeout=5.0)
+ await transfer.upload(content=b"payload", remote_path="out.bin")
asyncio.run(scenario())
+ assert client.delete_calls == [("upload-job", True, None)]
-def test_provision_exposes_descriptor_seed() -> None:
- client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env: _Job(job_id="mkdir-job", done=True, exit_code=0)
- )
-
- async def scenario() -> ShellEnvironmentDescriptor:
- handle = await _provisioner(client).provision()
- return handle.descriptor()
+def test_file_transfer_timeout_exhaustion_raises_timeout_and_still_deletes_job(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ clock = {"value": 100.0}
- descriptor = asyncio.run(scenario())
- assert isinstance(descriptor, ShellctlEnvironmentDescriptor)
- assert descriptor.workspace_cwd == _WORKSPACE_CWD
- assert descriptor.session_id == _SESSION_HEX
+ def fake_monotonic() -> float:
+ return clock["value"]
+ monkeypatch.setattr(shellctl.time, "monotonic", fake_monotonic)
-def test_reattach_rebuilds_handle_without_mkdir_and_executes_in_same_workspace() -> None:
- descriptor = ShellctlEnvironmentDescriptor(workspace_cwd=_WORKSPACE_CWD, session_id=_SESSION_HEX)
-
- def run_handler(script: str, cwd: str | None, env: dict[str, str] | None) -> _Job:
- del env
- assert not script.startswith("mkdir")
- assert cwd == _WORKSPACE_CWD
- return _Job(job_id="user-job", done=True, output="ok", offset=2, exit_code=0)
+ def run_handler(script: str, cwd: str | None, env: dict[str, str] | None, timeout: float) -> _Job:
+ del script, cwd, env
+ assert timeout == pytest.approx(5.0, rel=0, abs=0.01)
+ clock["value"] = 106.0
+ return _Job(job_id="upload-job", status="running", done=False, output="part-1", offset=6, exit_code=None)
client = FakeShellctlClient(run_handler=run_handler)
- async def scenario() -> str:
- handle = await _provisioner(client).reattach(descriptor)
- executor = await handle.get_executor()
- result = await executor.execute("pwd")
- return result.stdout()
-
- assert asyncio.run(scenario()) == "ok"
- # reattach must not allocate a new workspace.
- assert all(not call.script.startswith("mkdir") for call in client.run_calls)
-
+ async def scenario() -> None:
+ transfer = shellctl.ShellctlFileTransfer(client=client, timeout=5.0)
+ with pytest.raises(ShellProviderError, match="timed out") as exc_info:
+ await transfer.upload(content=b"payload", remote_path="out.bin")
+ assert exc_info.value.code == "timeout"
-def test_factory_unknown_provider_raises() -> None:
- settings = ShellAdapterSettings(shell_provider="nope")
- with pytest.raises(ValueError, match="Unknown shell provider"):
- create_shell_provisioner(settings)
+ asyncio.run(scenario())
+ assert client.delete_calls == [("upload-job", True, None)]
-def test_factory_shellctl_requires_entrypoint() -> None:
- settings = ShellAdapterSettings(shell_provider="shellctl", shellctl_entrypoint=None)
- with pytest.raises(ValueError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):
- create_shell_provisioner(settings)
+def test_download_missing_file_raises() -> None:
+ client = FakeShellctlClient(
+ run_handler=lambda script, cwd, env, timeout: _Job(
+ job_id="dl-job",
+ status="exited",
+ done=True,
+ output="",
+ exit_code=shellctl._DOWNLOAD_MISSING_EXIT_CODE,
+ )
+ )
+ async def scenario() -> None:
+ resource = await _provider(client).create()
+ with pytest.raises(ShellFileTransferError, match="not found"):
+ await resource.files.download(remote_path="missing.txt")
-def test_factory_builds_shellctl_provisioner_from_settings() -> None:
- settings = ShellAdapterSettings(
- shell_provider="shellctl",
- shellctl_entrypoint="http://shellctl.example",
- )
- provisioner = create_shell_provisioner(settings)
- assert isinstance(provisioner, ShellctlProvisioner)
+ asyncio.run(scenario())
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_config.py b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_config.py
new file mode 100644
index 00000000000..b9fbe015969
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_config.py
@@ -0,0 +1,390 @@
+from __future__ import annotations
+
+import io
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+from typing import cast
+
+import pytest
+
+from dify_agent.agent_stub.cli import _config as config_cli
+from dify_agent.agent_stub.cli._env import AgentStubEnvironment
+from dify_agent.agent_stub.client._errors import AgentStubValidationError
+from dify_agent.agent_stub.protocol.agent_stub import AgentStubConfigManifestResponse, AgentStubConfigPushRequest
+
+
+def _manifest_payload() -> AgentStubConfigManifestResponse:
+ return AgentStubConfigManifestResponse.model_validate(
+ {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {"items": [{"name": "alpha", "description": "Alpha skill"}]},
+ "files": {"items": [{"name": "guide.txt"}]},
+ "env_keys": ["API_KEY", "JSON_VALUE"],
+ "note": "Use carefully.",
+ }
+ )
+
+
+def _zip_bytes(members: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, payload in members.items():
+ archive.writestr(name, payload)
+ return buffer.getvalue()
+
+
+def _environment() -> AgentStubEnvironment:
+ return AgentStubEnvironment(url="https://agent.example.com/agent-stub", auth_jwe="test-jwe")
+
+
+def test_pull_config_skills_from_environment_downloads_and_extracts_archives(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_manifest_sync", lambda **_kwargs: _manifest_payload())
+ monkeypatch.setattr(
+ config_cli,
+ "request_agent_stub_config_skill_pull_sync",
+ lambda **_kwargs: _zip_bytes({"SKILL.md": b"# Alpha\n", "refs/spec.md": b"spec"}),
+ )
+
+ result = config_cli.pull_config_skills_from_environment(local_dir=str(tmp_path))
+
+ assert [item.name for item in result.items] == ["alpha"]
+ assert Path(result.items[0].archive_path).read_bytes()
+ assert Path(result.items[0].directory_path, "SKILL.md").read_text(encoding="utf-8") == "# Alpha\n"
+ assert result.items[0].skill_md == "# Alpha\n"
+
+
+def test_pull_config_files_from_environment_downloads_visible_files(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_manifest_sync", lambda **_kwargs: _manifest_payload())
+ monkeypatch.setattr(
+ config_cli,
+ "request_agent_stub_config_file_pull_sync",
+ lambda **_kwargs: b"guide-bytes",
+ )
+
+ result = config_cli.pull_config_files_from_environment(local_dir=str(tmp_path))
+
+ assert result.items == [config_cli.ConfigFilePullResult.Item(name="guide.txt", path=str(tmp_path / "guide.txt"))]
+ assert (tmp_path / "guide.txt").read_bytes() == b"guide-bytes"
+
+
+def test_pull_config_env_from_environment_writes_only_declared_keys(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(config_cli, "manifest_from_environment", _manifest_payload)
+ monkeypatch.setenv("API_KEY", "plain")
+ monkeypatch.setenv("JSON_VALUE", "two words")
+
+ result = config_cli.pull_config_env_from_environment(local_path=str(tmp_path / ".env"))
+
+ assert result.read_text(encoding="utf-8") == 'API_KEY=plain\nJSON_VALUE="two words"\n'
+
+
+def test_pull_config_env_and_note_use_hidden_default_dir(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(config_cli, "manifest_from_environment", _manifest_payload)
+ monkeypatch.setenv("API_KEY", "plain")
+ monkeypatch.setenv("JSON_VALUE", "two words")
+
+ env_path = config_cli.pull_config_env_from_environment()
+ note_path = config_cli.pull_config_note_from_environment()
+
+ assert env_path == (tmp_path / ".dify_conf" / ".env").resolve()
+ assert note_path == (tmp_path / ".dify_conf" / "note.md").resolve()
+ assert env_path.read_text(encoding="utf-8") == 'API_KEY=plain\nJSON_VALUE="two words"\n'
+ assert note_path.read_text(encoding="utf-8") == "Use carefully."
+
+
+def test_push_config_note_from_environment_reads_default_file(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ note_path = tmp_path / ".dify_conf" / "note.md"
+ note_path.parent.mkdir()
+ note_path.write_text("hello", encoding="utf-8")
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ response = config_cli.push_config_note_from_environment(None)
+
+ assert response.agent_id == "agent-1"
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.note == "hello"
+ assert request.env_text is None
+ assert request.files == []
+ assert request.skills == []
+
+
+def test_push_config_note_from_environment_reads_explicit_file(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ note_path = tmp_path / "note.md"
+ note_path.write_text("explicit", encoding="utf-8")
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_note_from_environment(str(note_path))
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.note == "explicit"
+
+
+def test_push_config_note_from_environment_reads_stdin(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+ monkeypatch.setattr(config_cli.os, "dup", lambda _fd: 99)
+ monkeypatch.setattr(config_cli.os, "fdopen", lambda _fd, encoding: io.StringIO("from-stdin"))
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_note_from_environment("-")
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.note == "from-stdin"
+
+
+def test_push_config_env_from_environment_reads_default_file(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ env_path = tmp_path / ".dify_conf" / ".env"
+ env_path.parent.mkdir()
+ env_path.write_text("API_KEY=value\n", encoding="utf-8")
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_env_from_environment(None)
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.env_text == "API_KEY=value\n"
+ assert request.note is None
+
+
+def test_push_config_env_from_environment_reads_explicit_file(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ env_path = tmp_path / "custom.env"
+ env_path.write_text("API_KEY=custom\n", encoding="utf-8")
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_env_from_environment(str(env_path))
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.env_text == "API_KEY=custom\n"
+
+
+def test_push_config_env_from_environment_reads_stdin(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+ monkeypatch.setattr(config_cli.os, "dup", lambda _fd: 99)
+ monkeypatch.setattr(config_cli.os, "fdopen", lambda _fd, encoding: io.StringIO("API_KEY=stdin\n"))
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_env_from_environment("-")
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.env_text == "API_KEY=stdin\n"
+
+
+def test_push_config_files_from_environment_builds_upload_items(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ file_path = tmp_path / "guide.txt"
+ file_path.write_text("guide", encoding="utf-8")
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+ monkeypatch.setattr(
+ config_cli,
+ "upload_tool_file_resource_from_environment",
+ lambda *, path: SimpleNamespace(tool_file_id=f"tool-file:{Path(path).name}"),
+ )
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_files_from_environment([str(file_path)], None)
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.files[0].name == "guide.txt"
+ assert request.files[0].file_ref is not None
+ assert request.files[0].file_ref.id == "tool-file:guide.txt"
+ assert request.skills == []
+
+
+def test_push_config_files_from_environment_validates_name_usage(tmp_path: Path) -> None:
+ first = tmp_path / "a.txt"
+ second = tmp_path / "b.txt"
+ first.write_text("a", encoding="utf-8")
+ second.write_text("b", encoding="utf-8")
+
+ with pytest.raises(AgentStubValidationError, match="--name requires exactly one PATH"):
+ config_cli.push_config_files_from_environment([str(first), str(second)], "renamed.txt")
+
+
+def test_push_config_files_from_environment_rejects_empty_paths() -> None:
+ with pytest.raises(AgentStubValidationError, match="at least one file path is required"):
+ config_cli.push_config_files_from_environment([], None)
+
+
+def test_delete_config_files_from_environment_builds_delete_items(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.delete_config_files_from_environment(["old.txt", "legacy.txt"])
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert [item.name for item in request.files] == ["old.txt", "legacy.txt"]
+ assert all(item.file_ref is None for item in request.files)
+
+
+def test_delete_config_files_from_environment_rejects_empty_names() -> None:
+ with pytest.raises(AgentStubValidationError, match="at least one file name is required"):
+ config_cli.delete_config_files_from_environment([])
+
+
+def test_push_config_skills_from_environment_builds_archive_upload_items(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ skill_dir = tmp_path / "alpha"
+ skill_dir.mkdir()
+ (skill_dir / "SKILL.md").write_text("# Alpha\n", encoding="utf-8")
+ uploaded_paths: list[str] = []
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ def fake_upload_tool_file_resource_from_environment(*, path: str):
+ uploaded_paths.append(path)
+ return SimpleNamespace(tool_file_id=f"tool-file-{len(uploaded_paths)}")
+
+ monkeypatch.setattr(
+ config_cli,
+ "upload_tool_file_resource_from_environment",
+ fake_upload_tool_file_resource_from_environment,
+ )
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.push_config_skills_from_environment([str(skill_dir)])
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert request.skills[0].name == "alpha"
+ assert request.skills[0].file_ref is not None
+ assert request.skills[0].file_ref.id == "tool-file-1"
+ assert len(uploaded_paths) == 1
+ assert uploaded_paths[0].endswith("/alpha.zip")
+
+
+def test_push_config_skills_from_environment_rejects_empty_paths() -> None:
+ with pytest.raises(AgentStubValidationError, match="at least one skill directory is required"):
+ config_cli.push_config_skills_from_environment([])
+
+
+def test_delete_config_skills_from_environment_builds_delete_items(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(config_cli, "read_agent_stub_environment", lambda: _environment())
+
+ captured: dict[str, object] = {}
+
+ def fake_push_sync(**kwargs):
+ captured.update(kwargs)
+ return _manifest_payload()
+
+ monkeypatch.setattr(config_cli, "request_agent_stub_config_push_sync", fake_push_sync)
+
+ config_cli.delete_config_skills_from_environment(["alpha", "beta"])
+
+ request = cast(AgentStubConfigPushRequest, captured["request"])
+ assert [item.name for item in request.skills] == ["alpha", "beta"]
+ assert all(item.file_ref is None for item in request.skills)
+
+
+def test_delete_config_skills_from_environment_rejects_empty_names() -> None:
+ with pytest.raises(AgentStubValidationError, match="at least one skill name is required"):
+ config_cli.delete_config_skills_from_environment([])
+
+
+def test_build_file_push_item_rejects_non_regular_files(tmp_path: Path) -> None:
+ with pytest.raises(AgentStubValidationError, match="regular file"):
+ config_cli._build_file_push_item(item=config_cli._PreparedPushItem(name="bad", path=tmp_path))
+
+
+def test_build_skill_push_item_rejects_missing_skill_md(tmp_path: Path) -> None:
+ skill_dir = tmp_path / "alpha"
+ skill_dir.mkdir()
+
+ with pytest.raises(AgentStubValidationError, match="must contain SKILL.md"):
+ config_cli._build_skill_push_item(item=config_cli._PreparedPushItem(name="alpha", path=skill_dir))
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py
index 8bdb8b2106d..0aedc6f435f 100644
--- a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py
+++ b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py
@@ -9,6 +9,12 @@ import pytest
from dify_agent.agent_stub.cli._drive import DrivePullResult
from dify_agent.agent_stub.cli.main import main
from dify_agent.agent_stub.protocol.agent_stub import (
+ AgentStubConfigFileItemsResponse,
+ AgentStubConfigFileItem,
+ AgentStubConfigManifestResponse,
+ AgentStubConfigSkillItemsResponse,
+ AgentStubConfigSkillItem,
+ AgentStubConfigVersionInfo,
AgentStubDriveCommitResponse,
AgentStubDriveItem,
AgentStubDriveManifestResponse,
@@ -21,6 +27,17 @@ def _reference(record_id: str) -> str:
return f"dify-file-ref:{payload}"
+def _config_manifest_response() -> AgentStubConfigManifestResponse:
+ return AgentStubConfigManifestResponse(
+ agent_id="agent-1",
+ config_version=AgentStubConfigVersionInfo(id="cfg-1", kind="build_draft", writable=True),
+ skills=AgentStubConfigSkillItemsResponse(items=[]),
+ files=AgentStubConfigFileItemsResponse(items=[]),
+ env_keys=[],
+ note="Runtime note.",
+ )
+
+
def test_cli_connect_reports_missing_environment_variables(capsys: pytest.CaptureFixture[str]) -> None:
with pytest.raises(SystemExit) as exc_info:
main(["connect"])
@@ -91,6 +108,63 @@ def test_cli_connect_help_routes_to_typer_help(capsys: pytest.CaptureFixture[str
assert exc_info.value.code == 0
assert "Establish one Agent Stub connection" in captured.out
assert "--json" in captured.out
+ assert "╭" not in captured.out
+ assert "─" not in captured.out
+
+
+def test_cli_config_push_is_not_a_valid_command(capsys: pytest.CaptureFixture[str]) -> None:
+ with pytest.raises(SystemExit) as exc_info:
+ main(["config", "push"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 2
+ assert "No such command 'push'" in captured.err
+ assert "╭" not in captured.err
+ assert "─" not in captured.err
+
+
+def test_cli_config_help_lists_plural_groups_and_no_root_push(capsys: pytest.CaptureFixture[str]) -> None:
+ with pytest.raises(SystemExit) as exc_info:
+ main(["config", "--help"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert "Usage: dify-agent config" in captured.out
+ assert "manifest" in captured.out
+ assert "files" in captured.out
+ assert "skills" in captured.out
+ assert "env" in captured.out
+ assert "note" in captured.out
+
+
[email protected]("argv", [["config", "files", "--help"], ["config", "skills", "--help"]])
+def test_cli_plural_config_groups_expose_pull_push_and_delete(
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+) -> None:
+ with pytest.raises(SystemExit) as exc_info:
+ main(argv)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert "pull" in captured.out
+ assert "push" in captured.out
+ assert "delete" in captured.out
+
+
[email protected]("argv", [["config", "file", "--help"], ["config", "skill", "--help"]])
+def test_cli_hidden_singular_alias_help_exposes_pull_only(
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+) -> None:
+ with pytest.raises(SystemExit) as exc_info:
+ main(argv)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert "pull" in captured.out
+ assert "push" not in captured.out
+ assert "delete" not in captured.out
def test_cli_reports_invalid_agent_stub_api_base_url_environment_value(
@@ -154,6 +228,205 @@ def test_cli_connect_accepts_grpc_agent_stub_api_base_url(
assert captured.out.strip() == "connected conn-1"
+def test_cli_config_manifest_omits_hash_fields(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.manifest_from_environment",
+ lambda: AgentStubConfigManifestResponse(
+ agent_id="agent-1",
+ config_version=AgentStubConfigVersionInfo(id="cfg-1", kind="build_draft", writable=True),
+ skills=AgentStubConfigSkillItemsResponse(
+ items=[
+ AgentStubConfigSkillItem(
+ name="alpha",
+ description="Alpha skill.",
+ size=12,
+ hash="sha256:skill",
+ mime_type="application/zip",
+ )
+ ]
+ ),
+ files=AgentStubConfigFileItemsResponse(
+ items=[
+ AgentStubConfigFileItem(
+ name="guide.txt",
+ size=34,
+ hash="sha256:file",
+ mime_type="text/plain",
+ )
+ ]
+ ),
+ env_keys=["RUNTIME_KEY"],
+ note="Runtime note.",
+ ),
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["config", "manifest"])
+
+ captured = capsys.readouterr()
+ payload = json.loads(captured.out)
+ assert exc_info.value.code == 0
+ assert payload["skills"] == {
+ "items": [
+ {
+ "name": "alpha",
+ "description": "Alpha skill.",
+ "size": 12,
+ "mime_type": "application/zip",
+ }
+ ]
+ }
+ assert payload["files"] == {
+ "items": [
+ {
+ "name": "guide.txt",
+ "size": 34,
+ "mime_type": "text/plain",
+ }
+ ]
+ }
+
+
+ ("argv", "helper_name", "expected_kwargs"),
+ [
+ (["config", "note", "push"], "push_config_note_from_environment", {"local_path": None}),
+ (
+ ["config", "note", "push", "/tmp/note.md"],
+ "push_config_note_from_environment",
+ {"local_path": "/tmp/note.md"},
+ ),
+ (["config", "env", "push"], "push_config_env_from_environment", {"local_path": None}),
+ (["config", "env", "push", "/tmp/.env"], "push_config_env_from_environment", {"local_path": "/tmp/.env"}),
+ (
+ ["config", "files", "push", "/tmp/guide.txt", "--name", "runtime.txt"],
+ "push_config_files_from_environment",
+ {"paths": ["/tmp/guide.txt"], "name": "runtime.txt"},
+ ),
+ (
+ ["config", "files", "delete", "old.txt", "legacy.txt"],
+ "delete_config_files_from_environment",
+ {"names": ["old.txt", "legacy.txt"]},
+ ),
+ (
+ ["config", "skills", "push", "/tmp/alpha", "/tmp/beta"],
+ "push_config_skills_from_environment",
+ {"paths": ["/tmp/alpha", "/tmp/beta"]},
+ ),
+ (
+ ["config", "skills", "delete", "alpha", "beta"],
+ "delete_config_skills_from_environment",
+ {"names": ["alpha", "beta"]},
+ ),
+ ],
+)
+def test_cli_config_mutation_commands_forward_and_print_manifest_json(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+ helper_name: str,
+ expected_kwargs: dict[str, object],
+) -> None:
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_helper(**kwargs):
+ captured_kwargs.update(kwargs)
+ return _config_manifest_response()
+
+ monkeypatch.setattr(f"dify_agent.agent_stub.cli.main.{helper_name}", fake_helper)
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(argv)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert json.loads(captured.out) == json.loads(_config_manifest_response().model_dump_json())
+ assert captured_kwargs == expected_kwargs
+
+
+ ("argv", "helper_name"),
+ [
+ (["config", "skills", "pull", "alpha", "--json"], "pull_config_skills_from_environment"),
+ (["config", "skill", "pull", "alpha", "--json"], "pull_config_skills_from_environment"),
+ (["config", "files", "pull", "guide.txt", "--json"], "pull_config_files_from_environment"),
+ (["config", "file", "pull", "guide.txt", "--json"], "pull_config_files_from_environment"),
+ ],
+)
+def test_cli_config_pull_commands_support_plural_and_hidden_singular_aliases(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+ helper_name: str,
+) -> None:
+ if "skills" in helper_name:
+ expected_json = {
+ "items": [
+ {
+ "name": "alpha",
+ "archive_path": "/tmp/alpha.zip",
+ "directory_path": "/tmp/alpha",
+ "skill_md": "# Alpha\n",
+ }
+ ]
+ }
+ response = type(
+ "Response",
+ (),
+ {"model_dump_json": lambda self: json.dumps(expected_json)},
+ )()
+ expected_kwargs = {"names": ["alpha"], "local_dir": None}
+ else:
+ expected_json = {"items": [{"name": "guide.txt", "path": "/tmp/guide.txt"}]}
+ response = type(
+ "Response",
+ (),
+ {"model_dump_json": lambda self: json.dumps(expected_json)},
+ )()
+ expected_kwargs = {"names": ["guide.txt"], "local_dir": None}
+
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_helper(*, names, local_dir):
+ captured_kwargs["names"] = names
+ captured_kwargs["local_dir"] = local_dir
+ return response
+
+ monkeypatch.setattr(f"dify_agent.agent_stub.cli.main.{helper_name}", fake_helper)
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(argv)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert json.loads(captured.out) == expected_json
+ assert captured_kwargs == expected_kwargs
+
+
+ "argv",
+ [
+ ["config", "skill", "push", "/tmp/alpha"],
+ ["config", "skill", "delete", "alpha"],
+ ["config", "file", "push", "/tmp/guide.txt"],
+ ["config", "file", "delete", "guide.txt"],
+ ],
+)
+def test_cli_hidden_singular_aliases_do_not_expose_mutation_commands(
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+) -> None:
+ with pytest.raises(SystemExit) as exc_info:
+ main(argv)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 2
+ assert "No such command" in captured.err
+
+
def test_cli_file_upload_prints_uploaded_tool_file_json(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_config_client.py b/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_config_client.py
new file mode 100644
index 00000000000..ed2fbf5a678
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_config_client.py
@@ -0,0 +1,310 @@
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+
+from dify_agent.agent_stub.client._agent_stub import (
+ request_agent_stub_config_env_update_sync,
+ request_agent_stub_config_file_pull_sync,
+ request_agent_stub_config_manifest_sync,
+ request_agent_stub_config_note_update_sync,
+ request_agent_stub_config_push_sync,
+ request_agent_stub_config_skill_inspect_sync,
+ request_agent_stub_config_skill_pull_sync,
+)
+from dify_agent.agent_stub.client._agent_stub_http import (
+ request_agent_stub_config_env_update_http_sync,
+ request_agent_stub_config_file_pull_http_sync,
+ request_agent_stub_config_manifest_http_sync,
+ request_agent_stub_config_note_update_http_sync,
+ request_agent_stub_config_push_http_sync,
+ request_agent_stub_config_skill_inspect_http_sync,
+ request_agent_stub_config_skill_pull_http_sync,
+)
+from dify_agent.agent_stub.client._errors import AgentStubClientError, AgentStubHTTPError, AgentStubValidationError
+from dify_agent.agent_stub.protocol.agent_stub import AgentStubConfigPushRequest
+
+
+def _manifest_payload() -> dict[str, object]:
+ return {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
+ "skills": {"items": [{"name": "alpha", "description": "Alpha skill"}]},
+ "files": {"items": [{"name": "guide.txt"}]},
+ "env_keys": ["API_KEY"],
+ "note": "Use carefully.",
+ }
+
+
+def test_config_manifest_sync_normalizes_url_and_uses_http_transport() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "GET"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/manifest"
+ assert request.headers["Authorization"] == "Bearer test-jwe"
+ return httpx.Response(200, json=_manifest_payload())
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ response = request_agent_stub_config_manifest_sync(
+ url="https://agent.example.com/agent-stub/",
+ auth_jwe="test-jwe",
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert response.agent_id == "agent-1"
+
+
+ ("func", "kwargs"),
+ [
+ (request_agent_stub_config_manifest_sync, {}),
+ (request_agent_stub_config_skill_pull_sync, {"name": "alpha"}),
+ (request_agent_stub_config_skill_inspect_sync, {"name": "alpha"}),
+ (request_agent_stub_config_file_pull_sync, {"name": "guide.txt"}),
+ (request_agent_stub_config_push_sync, {"request": AgentStubConfigPushRequest(note="hello")}),
+ (request_agent_stub_config_env_update_sync, {"env_text": "API_KEY=value\n"}),
+ (request_agent_stub_config_note_update_sync, {"note": "hello"}),
+ ],
+)
+def test_config_sync_entrypoints_reject_grpc_urls(func, kwargs: dict[str, object]) -> None:
+ with pytest.raises(AgentStubValidationError, match="require an HTTP Agent Stub URL"):
+ func(
+ url="grpc://agent.example.com:9091",
+ auth_jwe="test-jwe",
+ **kwargs,
+ )
+
+
+def test_request_agent_stub_config_manifest_http_sync_gets_manifest() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "GET"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/manifest"
+ assert request.headers["Authorization"] == "Bearer test-jwe"
+ return httpx.Response(200, json=_manifest_payload())
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ response = request_agent_stub_config_manifest_http_sync(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert response.agent_id == "agent-1"
+ assert response.config_version.kind == "build_draft"
+
+
+def test_request_agent_stub_config_skill_pull_http_sync_returns_binary_payload() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "GET"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/skills/alpha/pull"
+ return httpx.Response(200, content=b"zip-bytes")
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ payload = request_agent_stub_config_skill_pull_http_sync(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ name="alpha",
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert payload == b"zip-bytes"
+
+
+def test_request_agent_stub_config_skill_inspect_http_sync_returns_json_dict() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "GET"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/skills/alpha/inspect"
+ return httpx.Response(200, json={"name": "alpha", "files": ["SKILL.md"]})
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ payload = request_agent_stub_config_skill_inspect_http_sync(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ name="alpha",
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert payload == {"name": "alpha", "files": ["SKILL.md"]}
+
+
+def test_request_agent_stub_config_file_pull_http_sync_returns_binary_payload() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "GET"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/files/guide.txt/pull"
+ return httpx.Response(200, content=b"file-bytes")
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ payload = request_agent_stub_config_file_pull_http_sync(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ name="guide.txt",
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert payload == b"file-bytes"
+
+
+def test_request_agent_stub_config_push_http_sync_posts_json_and_validates_response() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "POST"
+ assert str(request.url) == "https://agent.example.com/agent-stub/config/push"
+ assert json.loads(request.content) == {"note": "hello"}
+ return httpx.Response(200, json=_manifest_payload())
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ response = request_agent_stub_config_push_http_sync(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ request=AgentStubConfigPushRequest(note="hello"),
+ sync_http_client=http_client,
+ )
+ finally:
+ http_client.close()
+
+ assert response.note == "Use carefully."
+
+
+ ("func", "kwargs", "expected_path", "expected_body", "expected_response"),
+ [
+ (
+ request_agent_stub_config_env_update_http_sync,
+ {"env_text": "API_KEY=value\n"},
+ "https://agent.example.com/agent-stub/config/env",
+ {"env_text": "API_KEY=value\n"},
+ {"env_keys": ["API_KEY"]},
+ ),
+ (
+ request_agent_stub_config_note_update_http_sync,
+ {"note": "hello"},
+ "https://agent.example.com/agent-stub/config/note",
+ {"note": "hello"},
+ {"note": "hello"},
+ ),
+ ],
+)
+def test_config_update_http_entrypoints_round_trip_json(
+ func,
+ kwargs: dict[str, object],
+ expected_path: str,
+ expected_body: dict[str, object],
+ expected_response: dict[str, object],
+) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert str(request.url) == expected_path
+ assert json.loads(request.content) == expected_body
+ return httpx.Response(200, json=expected_response)
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ payload = func(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ sync_http_client=http_client,
+ **kwargs,
+ )
+ finally:
+ http_client.close()
+
+ assert payload == expected_response
+
+
+ ("func", "kwargs", "response", "expected_error", "expected_match"),
+ [
+ (
+ request_agent_stub_config_manifest_http_sync,
+ {},
+ httpx.Response(401, json={"detail": "denied"}),
+ AgentStubHTTPError,
+ "401",
+ ),
+ (
+ request_agent_stub_config_manifest_http_sync,
+ {},
+ httpx.Response(200, text="not-json", headers={"Content-Type": "application/json"}),
+ AgentStubClientError,
+ "invalid JSON",
+ ),
+ (
+ request_agent_stub_config_push_http_sync,
+ {"request": AgentStubConfigPushRequest(note="hello")},
+ httpx.Response(200, json={"bad": "shape"}),
+ AgentStubValidationError,
+ "config push response",
+ ),
+ (
+ request_agent_stub_config_skill_pull_http_sync,
+ {"name": "alpha"},
+ httpx.Response(404, json={"detail": "missing"}),
+ AgentStubHTTPError,
+ "404",
+ ),
+ (
+ request_agent_stub_config_skill_inspect_http_sync,
+ {"name": "alpha"},
+ httpx.Response(200, json=["bad"]),
+ AgentStubValidationError,
+ "config skill inspect response",
+ ),
+ (
+ request_agent_stub_config_file_pull_http_sync,
+ {"name": "guide.txt"},
+ httpx.Response(404, json={"detail": "missing"}),
+ AgentStubHTTPError,
+ "404",
+ ),
+ (
+ request_agent_stub_config_env_update_http_sync,
+ {"env_text": "API_KEY=value\n"},
+ httpx.Response(200, json=["bad"]),
+ AgentStubValidationError,
+ "config env update response",
+ ),
+ (
+ request_agent_stub_config_note_update_http_sync,
+ {"note": "hello"},
+ httpx.Response(200, text="not-json", headers={"Content-Type": "application/json"}),
+ AgentStubClientError,
+ "invalid JSON",
+ ),
+ ],
+)
+def test_config_http_entrypoints_map_http_json_and_validation_errors(
+ func,
+ kwargs: dict[str, object],
+ response: httpx.Response,
+ expected_error: type[Exception],
+ expected_match: str,
+) -> None:
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return response
+
+ http_client = httpx.Client(transport=httpx.MockTransport(handler))
+ try:
+ with pytest.raises(expected_error, match=expected_match):
+ func(
+ base_url="https://agent.example.com/agent-stub",
+ auth_jwe="test-jwe",
+ sync_http_client=http_client,
+ **kwargs,
+ )
+ finally:
+ http_client.close()
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_config.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_config.py
new file mode 100644
index 00000000000..7846fcded42
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_config.py
@@ -0,0 +1,516 @@
+from __future__ import annotations
+
+import base64
+import json
+import secrets
+import time
+from typing import cast
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from dify_agent.agent_stub.protocol.agent_stub import (
+ AgentStubConfigManifestResponse,
+ AgentStubConfigPushRequest,
+ AgentStubConfigPushResponse,
+)
+from dify_agent.agent_stub.server.agent_stub_config import (
+ AgentStubConfigRequestError,
+ AgentStubConfigRequestHandler,
+ DifyApiAgentStubConfigRequestHandler,
+)
+from dify_agent.agent_stub.server.control_plane import AgentStubControlPlaneError, AgentStubControlPlaneService
+from dify_agent.agent_stub.server.routes.agent_stub import create_agent_stub_http_router
+from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubPrincipal, AgentStubTokenCodec
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+
+
+def _base64url_secret(value: bytes) -> str:
+ return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
+
+
+def _token_codec() -> AgentStubTokenCodec:
+ return AgentStubTokenCodec.from_server_secret(_base64url_secret(secrets.token_bytes(32)))
+
+
+def _execution_context(**updates: object) -> DifyExecutionContextLayerConfig:
+ payload = {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "user_from": "account",
+ "agent_mode": "workflow_run",
+ "invoke_from": "service-api",
+ "agent_id": "agent-1",
+ "agent_config_version_id": "cfg-1",
+ "agent_config_version_kind": "build_draft",
+ }
+ payload.update(updates)
+ return DifyExecutionContextLayerConfig.model_validate(payload)
+
+
+def _principal(**context_updates: object) -> AgentStubPrincipal:
+ return AgentStubPrincipal(
+ execution_context=_execution_context(**context_updates),
+ session_id=None,
+ scope=["agent_stub:connect"],
+ token_id="token-1",
+ )
+
+
+def _manifest_payload() -> dict[str, object]:
+ return {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True, "source": "inner-api"},
+ "skills": {"items": [{"id": "alpha", "name": "alpha", "description": "Alpha skill", "file_id": "tool-file-1"}]},
+ "files": {"items": [{"id": "guide.txt", "name": "guide.txt", "file_id": "upload-file-1"}]},
+ "env_keys": ["API_KEY"],
+ "note": "Use carefully.",
+ "ignored": True,
+ }
+
+
+async def test_dify_api_handler_manifest_success(monkeypatch: pytest.MonkeyPatch) -> None:
+ original_async_client = httpx.AsyncClient
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert str(request.url) == (
+ "https://api.example.com/inner/api/agent-config/agent-1/manifest"
+ "?tenant_id=tenant-1&config_version_id=cfg-1&config_version_kind=build_draft&user_id=user-1"
+ )
+ assert request.headers["X-Inner-Api-Key"] == "inner-secret"
+ return httpx.Response(200, json=_manifest_payload())
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.server.agent_stub_config.httpx.AsyncClient",
+ lambda **kwargs: original_async_client(transport=httpx.MockTransport(handler), **kwargs),
+ )
+
+ response = await DifyApiAgentStubConfigRequestHandler(
+ inner_api_url="https://api.example.com",
+ inner_api_key="inner-secret",
+ ).manifest(principal=_principal())
+
+ assert isinstance(response, AgentStubConfigManifestResponse)
+ assert response.agent_id == "agent-1"
+ assert response.config_version.kind == "build_draft"
+ assert response.skills.items[0].model_dump() == {
+ "name": "alpha",
+ "description": "Alpha skill",
+ "size": None,
+ "hash": None,
+ "mime_type": None,
+ }
+ assert response.files.items[0].model_dump() == {
+ "name": "guide.txt",
+ "size": None,
+ "hash": None,
+ "mime_type": None,
+ }
+
+
+async def test_dify_api_handler_pull_endpoints_return_bytes(monkeypatch: pytest.MonkeyPatch) -> None:
+ original_async_client = httpx.AsyncClient
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.params["user_id"] == "user-1"
+ if request.url.path.endswith("/skills/alpha/pull"):
+ return httpx.Response(200, content=b"zip-bytes")
+ if request.url.path.endswith("/files/guide.txt/pull"):
+ return httpx.Response(200, content=b"file-bytes")
+ raise AssertionError(f"unexpected path: {request.url.path}")
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.server.agent_stub_config.httpx.AsyncClient",
+ lambda **kwargs: original_async_client(transport=httpx.MockTransport(handler), **kwargs),
+ )
+
+ request_handler = DifyApiAgentStubConfigRequestHandler(
+ inner_api_url="https://api.example.com",
+ inner_api_key="inner-secret",
+ )
+
+ assert await request_handler.pull_skill(principal=_principal(), name="alpha") == b"zip-bytes"
+ assert await request_handler.pull_file(principal=_principal(), name="guide.txt") == b"file-bytes"
+
+
+async def test_dify_api_handler_push_env_and_note_success(monkeypatch: pytest.MonkeyPatch) -> None:
+ original_async_client = httpx.AsyncClient
+ captured: list[tuple[str, dict[str, object]]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ payload = json.loads(request.content)
+ captured.append((request.url.path, payload))
+ if request.url.path.endswith("/push"):
+ return httpx.Response(200, json=_manifest_payload())
+ if request.url.path.endswith("/env"):
+ return httpx.Response(200, json={"env_keys": ["API_KEY"]})
+ if request.url.path.endswith("/note"):
+ return httpx.Response(200, json={"note": "updated"})
+ raise AssertionError(f"unexpected path: {request.url.path}")
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.server.agent_stub_config.httpx.AsyncClient",
+ lambda **kwargs: original_async_client(transport=httpx.MockTransport(handler), **kwargs),
+ )
+
+ request_handler = DifyApiAgentStubConfigRequestHandler(
+ inner_api_url="https://api.example.com",
+ inner_api_key="inner-secret",
+ )
+
+ push_response = await request_handler.push(
+ principal=_principal(),
+ request=AgentStubConfigPushRequest(note="hello"),
+ )
+ env_response = await request_handler.update_env(principal=_principal(), env_text="API_KEY=value\n")
+ note_response = await request_handler.update_note(principal=_principal(), note="updated")
+
+ assert isinstance(push_response, AgentStubConfigPushResponse)
+ assert env_response == {"env_keys": ["API_KEY"]}
+ assert note_response == {"note": "updated"}
+ assert captured == [
+ (
+ "/inner/api/agent-config/agent-1/push",
+ {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "files": [],
+ "skills": [],
+ "note": "hello",
+ },
+ ),
+ (
+ "/inner/api/agent-config/agent-1/env",
+ {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "env_text": "API_KEY=value\n",
+ },
+ ),
+ (
+ "/inner/api/agent-config/agent-1/note",
+ {
+ "tenant_id": "tenant-1",
+ "user_id": "user-1",
+ "config_version_id": "cfg-1",
+ "config_version_kind": "build_draft",
+ "note": "updated",
+ },
+ ),
+ ]
+
+
+ ("method_name", "path", "response", "expected_status", "expected_message"),
+ [
+ (
+ "manifest",
+ "/inner/api/agent-config/agent-1/manifest",
+ httpx.Response(200, json={"bad": "shape"}),
+ 502,
+ "manifest",
+ ),
+ (
+ "pull_skill",
+ "/inner/api/agent-config/agent-1/skills/alpha/pull",
+ httpx.Response(404, json={"detail": "missing"}),
+ 404,
+ "missing",
+ ),
+ ("push", "/inner/api/agent-config/agent-1/push", httpx.Response(200, json={"bad": "shape"}), 502, "push"),
+ ("update_env", "/inner/api/agent-config/agent-1/env", httpx.Response(200, json=["bad"]), 502, "env"),
+ (
+ "update_note",
+ "/inner/api/agent-config/agent-1/note",
+ httpx.Response(200, text="not-json"),
+ 502,
+ "invalid JSON",
+ ),
+ ],
+)
+async def test_dify_api_handler_maps_error_cases(
+ monkeypatch: pytest.MonkeyPatch,
+ method_name: str,
+ path: str,
+ response: httpx.Response,
+ expected_status: int,
+ expected_message: str,
+) -> None:
+ original_async_client = httpx.AsyncClient
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == path
+ return response
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.server.agent_stub_config.httpx.AsyncClient",
+ lambda **kwargs: original_async_client(transport=httpx.MockTransport(handler), **kwargs),
+ )
+
+ request_handler = DifyApiAgentStubConfigRequestHandler(
+ inner_api_url="https://api.example.com",
+ inner_api_key="inner-secret",
+ )
+
+ with pytest.raises(AgentStubConfigRequestError, match=expected_message) as exc_info:
+ match method_name:
+ case "manifest":
+ await request_handler.manifest(principal=_principal())
+ case "pull_skill":
+ await request_handler.pull_skill(principal=_principal(), name="alpha")
+ case "push":
+ await request_handler.push(principal=_principal(), request=AgentStubConfigPushRequest())
+ case "update_env":
+ await request_handler.update_env(principal=_principal(), env_text="API_KEY=value\n")
+ case "update_note":
+ await request_handler.update_note(principal=_principal(), note="hello")
+ case _:
+ raise AssertionError(f"unexpected method: {method_name}")
+
+ assert exc_info.value.status_code == expected_status
+
+
+ ("context_updates", "expected_message"),
+ [
+ ({"agent_id": None}, "agent_id is required"),
+ ({"agent_config_version_id": None}, "agent_config_version_id is required"),
+ ({"agent_config_version_kind": None}, "agent_config_version_kind is required"),
+ ({"user_id": None}, "user_id is required"),
+ ],
+)
+async def test_dify_api_handler_validates_required_execution_context_fields(
+ context_updates: dict[str, object],
+ expected_message: str,
+) -> None:
+ request_handler = DifyApiAgentStubConfigRequestHandler(
+ inner_api_url="https://api.example.com",
+ inner_api_key="inner-secret",
+ )
+
+ with pytest.raises(AgentStubConfigRequestError, match=expected_message) as exc_info:
+ if context_updates.get("user_id", "user-1") is None:
+ await request_handler.push(principal=_principal(**context_updates), request=AgentStubConfigPushRequest())
+ else:
+ await request_handler.manifest(principal=_principal(**context_updates))
+
+ assert exc_info.value.status_code == 400
+
+
+ "method_name",
+ [
+ "get_config_manifest",
+ "pull_config_skill",
+ "inspect_config_skill",
+ "pull_config_file",
+ "push_config",
+ "update_config_env",
+ "update_config_note",
+ ],
+)
+async def test_control_plane_maps_config_request_errors(method_name: str) -> None:
+ codec = _token_codec()
+ authorization = f"Bearer {codec.encode_connection_token(_execution_context(), now=int(time.time()) - 1)}"
+
+ class FakeHandler:
+ async def manifest(self, *, principal):
+ del principal
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def pull_skill(self, *, principal, name):
+ del principal, name
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def inspect_skill(self, *, principal, name):
+ del principal, name
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def pull_file(self, *, principal, name):
+ del principal, name
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def push(self, *, principal, request):
+ del principal, request
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def update_env(self, *, principal, env_text):
+ del principal, env_text
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ async def update_note(self, *, principal, note):
+ del principal, note
+ raise AgentStubConfigRequestError(409, {"code": "conflict"})
+
+ service = AgentStubControlPlaneService(
+ codec, config_request_handler=cast(AgentStubConfigRequestHandler, FakeHandler())
+ )
+
+ with pytest.raises(AgentStubControlPlaneError) as exc_info:
+ match method_name:
+ case "get_config_manifest":
+ await service.get_config_manifest(authorization=authorization)
+ case "pull_config_skill":
+ await service.pull_config_skill(name="alpha", authorization=authorization)
+ case "inspect_config_skill":
+ await service.inspect_config_skill(name="alpha", authorization=authorization)
+ case "pull_config_file":
+ await service.pull_config_file(name="guide.txt", authorization=authorization)
+ case "push_config":
+ await service.push_config(request=AgentStubConfigPushRequest(), authorization=authorization)
+ case "update_config_env":
+ await service.update_config_env(env_text="API_KEY=value\n", authorization=authorization)
+ case "update_config_note":
+ await service.update_config_note(note="hello", authorization=authorization)
+ case _:
+ raise AssertionError(f"unexpected method: {method_name}")
+
+ assert exc_info.value.status_code == 409
+ assert exc_info.value.detail == {"code": "conflict"}
+
+
+ ("path", "method", "body", "expected_status", "expected_detail"),
+ [
+ ("/agent-stub/config/manifest", "get", None, 200, {"agent_id": "agent-1"}),
+ ("/agent-stub/config/skills/alpha/pull", "get", None, 200, b"zip-bytes"),
+ ("/agent-stub/config/skills/alpha/inspect", "get", None, 200, {"name": "alpha", "files": ["SKILL.md"]}),
+ ("/agent-stub/config/files/guide.txt/pull", "get", None, 200, b"file-bytes"),
+ ("/agent-stub/config/push", "post", {"note": "hello"}, 200, {"agent_id": "agent-1"}),
+ ("/agent-stub/config/env", "patch", {"env_text": "API_KEY=value\n"}, 200, {"env_keys": ["API_KEY"]}),
+ ("/agent-stub/config/note", "put", {"note": "hello"}, 200, {"note": "hello"}),
+ ],
+)
+def test_http_config_routes_forward_requests(
+ path: str,
+ method: str,
+ body: dict[str, object] | None,
+ expected_status: int,
+ expected_detail: dict[str, object] | bytes,
+) -> None:
+ codec = _token_codec()
+ token = codec.encode_connection_token(_execution_context(), now=int(time.time()) - 1)
+ captured: dict[str, object] = {}
+
+ class FakeHandler:
+ async def manifest(self, *, principal):
+ captured["manifest_agent_id"] = principal.execution_context.agent_id
+ return AgentStubConfigManifestResponse.model_validate(_manifest_payload())
+
+ async def pull_skill(self, *, principal, name):
+ del principal
+ captured["skill_name"] = name
+ return b"zip-bytes"
+
+ async def inspect_skill(self, *, principal, name):
+ del principal
+ captured["inspect_name"] = name
+ return {"name": name, "files": ["SKILL.md"]}
+
+ async def pull_file(self, *, principal, name):
+ del principal
+ captured["file_name"] = name
+ return b"file-bytes"
+
+ async def push(self, *, principal, request):
+ del principal
+ captured["push_note"] = request.note
+ return AgentStubConfigPushResponse.model_validate(_manifest_payload())
+
+ async def update_env(self, *, principal, env_text):
+ del principal
+ captured["env_text"] = env_text
+ return {"env_keys": ["API_KEY"]}
+
+ async def update_note(self, *, principal, note):
+ del principal
+ captured["note"] = note
+ return {"note": note}
+
+ app = FastAPI()
+ app.include_router(
+ create_agent_stub_http_router(codec, config_request_handler=cast(AgentStubConfigRequestHandler, FakeHandler()))
+ )
+ client = TestClient(app)
+ headers = {"Authorization": f"Bearer {token}"}
+ response = client.request(method.upper(), path, headers=headers, json=body)
+
+ assert response.status_code == expected_status
+ if isinstance(expected_detail, bytes):
+ assert response.content == expected_detail
+ else:
+ for key, value in expected_detail.items():
+ assert response.json()[key] == value
+
+ if path.endswith("/manifest"):
+ assert captured["manifest_agent_id"] == "agent-1"
+ elif path.endswith("/skills/alpha/pull"):
+ assert captured["skill_name"] == "alpha"
+ assert response.headers["content-type"] == "application/zip"
+ elif path.endswith("/skills/alpha/inspect"):
+ assert captured["inspect_name"] == "alpha"
+ elif path.endswith("/files/guide.txt/pull"):
+ assert captured["file_name"] == "guide.txt"
+ assert response.headers["content-type"] == "application/octet-stream"
+ elif path.endswith("/config/push"):
+ assert captured["push_note"] == "hello"
+ elif path.endswith("/config/env"):
+ assert captured["env_text"] == "API_KEY=value\n"
+ elif path.endswith("/config/note"):
+ assert captured["note"] == "hello"
+
+
+def test_http_config_routes_map_handler_errors() -> None:
+ codec = _token_codec()
+ token = codec.encode_connection_token(_execution_context(), now=int(time.time()) - 1)
+
+ class ErrorHandler:
+ async def manifest(self, *, principal):
+ del principal
+ raise AgentStubConfigRequestError(422, {"code": "invalid_request"})
+
+ async def pull_skill(self, *, principal, name):
+ del principal, name
+ raise AssertionError("unexpected route")
+
+ async def inspect_skill(self, *, principal, name):
+ del principal, name
+ raise AssertionError("unexpected route")
+
+ async def pull_file(self, *, principal, name):
+ del principal, name
+ raise AssertionError("unexpected route")
+
+ async def push(self, *, principal, request):
+ del principal, request
+ raise AssertionError("unexpected route")
+
+ async def update_env(self, *, principal, env_text):
+ del principal, env_text
+ raise AssertionError("unexpected route")
+
+ async def update_note(self, *, principal, note):
+ del principal, note
+ raise AssertionError("unexpected route")
+
+ app = FastAPI()
+ app.include_router(
+ create_agent_stub_http_router(codec, config_request_handler=cast(AgentStubConfigRequestHandler, ErrorHandler()))
+ )
+ client = TestClient(app)
+ response = client.get("/agent-stub/config/manifest", headers={"Authorization": f"Bearer {token}"})
+
+ assert response.status_code == 422
+ assert response.json()["detail"] == {"code": "invalid_request"}
diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py
index 11e56f62d67..c636fc0a0fd 100644
--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py
+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py
@@ -100,6 +100,7 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_commit(
"key": "skills/example/SKILL.md",
"file_ref": {"kind": "tool_file", "id": "tool-file-1"},
"value_owned_by_drive": True,
+ "is_skill": False,
}
],
}
diff --git a/dify-agent/tests/local/dify_agent/layers/config/test_layer.py b/dify-agent/tests/local/dify_agent/layers/config/test_layer.py
new file mode 100644
index 00000000000..0ea4bf1195f
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/config/test_layer.py
@@ -0,0 +1,202 @@
+"""Behavior tests for the runtime Dify config layer."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Literal
+
+import pytest
+
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
+from dify_agent.layers.config import DifyConfigLayerConfig
+from dify_agent.layers.config.layer import DifyConfigLayer, DifyConfigLayerError
+from dify_agent.layers.shell import DifyShellLayerConfig
+from dify_agent.layers.shell.layer import CompleteRemoteCommandResult, DifyShellLayer
+
+
+def _unused_client_factory():
+ raise AssertionError("shellctl client should not be used by these config-layer tests")
+
+
+def _shell_layer() -> DifyShellLayer:
+ return DifyShellLayer.from_config_with_settings(
+ DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
+ shell_provider=ShellctlProvider(entrypoint="http://shellctl", token="", client_factory=_unused_client_factory),
+ )
+
+
+def _build_layer(*, writable: bool = True) -> DifyConfigLayer:
+ layer = DifyConfigLayer.from_config(
+ DifyConfigLayerConfig.model_validate(
+ {
+ "agent_id": "agent-1",
+ "config_version": {"id": "cfg-1", "kind": "build_draft", "writable": writable},
+ "skills": [{"name": "runtime-skill", "description": "Runtime skill."}],
+ "files": [{"name": "runtime-file.txt"}],
+ "env_keys": ["RUNTIME_KEY"],
+ "note": "Runtime note.",
+ "mentioned_skill_names": ["alpha"],
+ "mentioned_file_names": ["guide.txt"],
+ }
+ )
+ )
+ layer.bind_deps({"shell": _shell_layer()})
+ return layer
+
+
+def _remote_result(
+ output: str,
+ *,
+ exit_code: int | None = 0,
+ output_complete: bool = True,
+ incomplete_reason: Literal["output_limit", "timeout"] | None = None,
+) -> CompleteRemoteCommandResult:
+ return CompleteRemoteCommandResult(
+ job_id="remote-config-pull",
+ status="exited",
+ done=True,
+ exit_code=exit_code,
+ output=output,
+ output_complete=output_complete,
+ incomplete_reason=incomplete_reason,
+ offset=len(output),
+ output_path="/tmp/config-pull-output.log",
+ )
+
+
+def _skill_pull_output(*, include_skill: bool = True) -> str:
+ if not include_skill:
+ return ""
+ return "/workspace/.dify_conf/skills/alpha\n# Alpha\nUse it.\n"
+
+
+def _file_pull_output(*, include_file: bool = True) -> str:
+ if not include_file:
+ return ""
+ return "/workspace/.dify_conf/files/guide.txt\n"
+
+
+def test_build_shell_pull_scripts_include_targets() -> None:
+ layer = _build_layer()
+
+ skill_script = layer._build_shell_skill_pull_script("alpha")
+ file_script = layer._build_shell_file_pull_script("guide.txt")
+
+ assert skill_script == "set -eu\ndify-agent config skills pull alpha"
+ assert "__DIFY_CONFIG_SKILLS_BEGIN__" not in skill_script
+ assert file_script == "set -eu\ndify-agent config files pull guide.txt"
+ assert "__DIFY_CONFIG_FILES_BEGIN__" not in file_script
+
+
+async def test_on_context_create_computes_runtime_fields_and_pulls_mentioned_assets_in_parallel(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ layer = _build_layer()
+ captured_scripts: list[str] = []
+ active_commands = 0
+ max_active_commands = 0
+
+ async def fake_run_remote_script(self, script: str, *, inject_agent_stub_env: bool = False, timeout: float = 10.0):
+ nonlocal active_commands, max_active_commands
+ del self, timeout
+ assert inject_agent_stub_env is True
+ assert "--help" not in script
+ assert "dify-agent config manifest" not in script
+ captured_scripts.append(script)
+ active_commands += 1
+ max_active_commands = max(max_active_commands, active_commands)
+ await asyncio.sleep(0)
+ active_commands -= 1
+ if "skills pull" in script:
+ return _remote_result(_skill_pull_output())
+ if "files pull" in script:
+ return _remote_result(_file_pull_output())
+ raise AssertionError(f"unexpected script: {script}")
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+
+ await layer.on_context_create()
+
+ assert max_active_commands > 1
+ assert len(captured_scripts) == 2
+ assert sorted(captured_scripts) == [
+ "set -eu\ndify-agent config files pull guide.txt",
+ "set -eu\ndify-agent config skills pull alpha",
+ ]
+ assert layer.runtime_state.pulled_skill_outputs == {"alpha": "/workspace/.dify_conf/skills/alpha\n# Alpha\nUse it."}
+ assert layer.runtime_state.pulled_file_outputs == {"guide.txt": "/workspace/.dify_conf/files/guide.txt"}
+ assert "dify-agent config note push --help" in layer.runtime_state.config_cli_help
+ assert layer.runtime_state.push_spec_json_schema == ""
+
+
+async def test_on_context_resume_does_not_recompute_or_pull(monkeypatch: pytest.MonkeyPatch) -> None:
+ layer = _build_layer()
+ layer.runtime_state.config_context_json = "cached"
+ layer.runtime_state.config_cli_help = {"cached": "help"}
+
+ async def fail_run_remote_script(self, script: str, *, inject_agent_stub_env: bool = False, timeout: float = 10.0):
+ del self, script, inject_agent_stub_env, timeout
+ raise AssertionError("resume must not run config shell commands")
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fail_run_remote_script)
+
+ await layer.on_context_resume()
+
+ assert layer.runtime_state.config_context_json == "cached"
+ assert layer.runtime_state.config_cli_help == {"cached": "help"}
+
+
+async def test_on_context_create_raises_when_shell_output_is_truncated(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ layer = _build_layer()
+
+ async def fake_run_remote_script(self, script: str, *, inject_agent_stub_env: bool = False, timeout: float = 10.0):
+ del self, inject_agent_stub_env, timeout
+ if "skills pull" in script:
+ return _remote_result(_skill_pull_output(), output_complete=False, incomplete_reason="output_limit")
+ return _remote_result(_file_pull_output())
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+
+ with pytest.raises(DifyConfigLayerError, match="output was incomplete"):
+ await layer.on_context_create()
+
+
+async def test_on_context_create_raises_when_mentioned_skill_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ layer = _build_layer()
+
+ async def fake_run_remote_script(self, script: str, *, inject_agent_stub_env: bool = False, timeout: float = 10.0):
+ del self, inject_agent_stub_env, timeout
+ if "skills pull" in script:
+ return _remote_result(_skill_pull_output(include_skill=False))
+ return _remote_result(_file_pull_output())
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+
+ with pytest.raises(DifyConfigLayerError, match="missing pull output"):
+ await layer.on_context_create()
+
+
+async def test_on_context_create_raises_when_mentioned_file_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ layer = _build_layer()
+
+ async def fake_run_remote_script(self, script: str, *, inject_agent_stub_env: bool = False, timeout: float = 10.0):
+ del self, inject_agent_stub_env, timeout
+ if "skills pull" in script:
+ return _remote_result(_skill_pull_output())
+ return _remote_result(_file_pull_output(include_file=False))
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+
+ with pytest.raises(DifyConfigLayerError, match="missing pull output"):
+ await layer.on_context_create()
diff --git a/dify-agent/tests/local/dify_agent/layers/conftest.py b/dify-agent/tests/local/dify_agent/layers/conftest.py
new file mode 100644
index 00000000000..9d393301962
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/conftest.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+import sys
+import types
+
+from agenton.layers import EmptyLayerConfig, EmptyRuntimeState, NoLayerDeps, PlainLayer
+from pydantic import BaseModel
+
+
+class _BaseSettings(BaseModel):
+ """Minimal test stub for environments without pydantic-settings installed."""
+
+
+class _SettingsConfigDict(dict[str, object]):
+ """Minimal callable mapping used by ShellAdapterSettings.model_config."""
+
+
+if "pydantic_settings" not in sys.modules:
+ stub = types.ModuleType("pydantic_settings")
+ setattr(stub, "BaseSettings", _BaseSettings)
+ setattr(stub, "SettingsConfigDict", _SettingsConfigDict)
+ sys.modules["pydantic_settings"] = stub
+
+
+if "dify_agent.layers.execution_context.layer" not in sys.modules:
+ execution_context_stub = types.ModuleType("dify_agent.layers.execution_context.layer")
+
+ class DifyExecutionContextLayer(PlainLayer[NoLayerDeps, EmptyLayerConfig, EmptyRuntimeState]):
+ """Minimal test stub for shell-layer type-only imports."""
+
+ setattr(execution_context_stub, "DifyExecutionContextLayer", DifyExecutionContextLayer)
+ sys.modules["dify_agent.layers.execution_context.layer"] = execution_context_stub
diff --git a/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_client.py b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_client.py
new file mode 100644
index 00000000000..1453ded7fd6
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_client.py
@@ -0,0 +1,165 @@
+import json
+
+import httpx
+import pytest
+
+from dify_agent.layers.dify_core_tools.client import DifyCoreToolsClient, DifyCoreToolsClientError
+from dify_agent.layers.dify_core_tools.configs import DifyCoreToolConfig
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+
+
+def _execution_context() -> DifyExecutionContextLayerConfig:
+ return DifyExecutionContextLayerConfig(
+ tenant_id="tenant-1",
+ user_id="user-1",
+ user_from="account",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_run_id="workflow-run-1",
+ node_id="node-1",
+ node_execution_id="node-exec-1",
+ conversation_id="conversation-1",
+ agent_id="agent-1",
+ agent_config_version_id="snapshot-1",
+ agent_mode="workflow_run",
+ invoke_from="service-api",
+ )
+
+
+def _tool_config() -> DifyCoreToolConfig:
+ return DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ credential_id="credential-1",
+ runtime_parameters={"language": "en"},
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+
+
+def test_core_tools_client_posts_inner_api_request() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert str(request.url) == "http://dify-api/inner/api/agent/tools/invoke"
+ assert request.headers["X-Inner-Api-Key"] == "inner-secret"
+ payload = json.loads(request.content.decode("utf-8"))
+ assert payload["caller"]["tenant_id"] == "tenant-1"
+ assert payload["tool"]["provider_type"] == "builtin"
+ assert payload["tool"]["runtime_parameters"] == {"language": "en"}
+ assert payload["tool"]["tool_parameters"] == {"audio_url": "https://example.com/a.mp3"}
+ return httpx.Response(
+ 200,
+ json={
+ "messages": [{"type": "text", "message": {"text": "ok"}}],
+ "observation": "ok",
+ "metadata": {"provider_type": "builtin"},
+ },
+ )
+
+ async def scenario() -> None:
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
+ client = DifyCoreToolsClient(base_url="http://dify-api", api_key="inner-secret", http_client=http_client)
+ response = await client.invoke(
+ execution_context=_execution_context(),
+ tool_config=_tool_config(),
+ tool_parameters={"audio_url": "https://example.com/a.mp3"},
+ )
+ assert response.observation == "ok"
+
+ import asyncio
+
+ asyncio.run(scenario())
+
+
+def test_core_tools_client_marks_retryable_http_failures() -> None:
+ async def scenario() -> None:
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _request: httpx.Response(502, json={"code": "tool_failed"}))
+ ) as http_client:
+ client = DifyCoreToolsClient(base_url="http://dify-api", api_key="inner-secret", http_client=http_client)
+ with pytest.raises(DifyCoreToolsClientError) as exc_info:
+ _ = await client.invoke(
+ execution_context=_execution_context(),
+ tool_config=_tool_config(),
+ tool_parameters={"audio_url": "https://example.com/a.mp3"},
+ )
+ assert exc_info.value.retryable is True
+
+ import asyncio
+
+ asyncio.run(scenario())
+
+
+ ("error_factory", "expected_substring"),
+ [
+ (
+ lambda request: httpx.ReadTimeout("timed out", request=request),
+ "timed out",
+ ),
+ (
+ lambda request: httpx.ConnectError("connect failed", request=request),
+ "request failed",
+ ),
+ ],
+)
+def test_core_tools_client_marks_transport_failures_retryable(error_factory, expected_substring: str) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise error_factory(request)
+
+ async def scenario() -> None:
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
+ client = DifyCoreToolsClient(base_url="http://dify-api", api_key="inner-secret", http_client=http_client)
+ with pytest.raises(DifyCoreToolsClientError) as exc_info:
+ _ = await client.invoke(
+ execution_context=_execution_context(),
+ tool_config=_tool_config(),
+ tool_parameters={"audio_url": "https://example.com/a.mp3"},
+ )
+ assert exc_info.value.retryable is True
+ assert expected_substring in str(exc_info.value)
+
+ import asyncio
+
+ asyncio.run(scenario())
+
+
+def test_core_tools_client_validates_execution_context_prerequisites_separately() -> None:
+ async def scenario() -> None:
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _request: httpx.Response(200, json={}))
+ ) as http_client:
+ client = DifyCoreToolsClient(base_url="http://dify-api", api_key="inner-secret", http_client=http_client)
+ with pytest.raises(DifyCoreToolsClientError) as exc_info:
+ _ = await client.invoke(
+ execution_context=_execution_context().model_copy(update={"app_id": None}),
+ tool_config=_tool_config(),
+ tool_parameters={"audio_url": "https://example.com/a.mp3"},
+ )
+ assert exc_info.value.error_code == "missing_execution_context"
+ assert exc_info.value.retryable is False
+ assert "app_id" in str(exc_info.value)
+
+ import asyncio
+
+ asyncio.run(scenario())
+
+
+def test_core_tools_client_raises_invalid_response_for_malformed_success_body() -> None:
+ async def scenario() -> None:
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _request: httpx.Response(200, json={"messages": []}))
+ ) as http_client:
+ client = DifyCoreToolsClient(base_url="http://dify-api", api_key="inner-secret", http_client=http_client)
+ with pytest.raises(DifyCoreToolsClientError) as exc_info:
+ _ = await client.invoke(
+ execution_context=_execution_context(),
+ tool_config=_tool_config(),
+ tool_parameters={"audio_url": "https://example.com/a.mp3"},
+ )
+ assert exc_info.value.error_code == "invalid_response"
+ assert exc_info.value.retryable is False
+
+ import asyncio
+
+ asyncio.run(scenario())
diff --git a/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_configs.py b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_configs.py
new file mode 100644
index 00000000000..8e795112853
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_configs.py
@@ -0,0 +1,62 @@
+import pytest
+from pydantic import ValidationError
+
+import dify_agent.layers.dify_core_tools as dify_core_tools_exports
+from dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolsLayerConfig
+
+
+def test_dify_core_tools_package_exports_client_safe_config_symbols_only() -> None:
+ assert dify_core_tools_exports.__all__ == [
+ "DIFY_CORE_TOOLS_LAYER_TYPE_ID",
+ "DifyCoreToolConfig",
+ "DifyCoreToolProviderType",
+ "DifyCoreToolsLayerConfig",
+ ]
+ assert dify_core_tools_exports.DIFY_CORE_TOOLS_LAYER_TYPE_ID == "dify.core.tools"
+
+
+def test_dify_core_tools_layer_config_accepts_supported_provider_types() -> None:
+ config = DifyCoreToolsLayerConfig.model_validate(
+ {
+ "tools": [
+ {
+ "provider_type": "plugin",
+ "provider_id": "langgenius/search/search",
+ "tool_name": "search",
+ },
+ {
+ "provider_type": "builtin",
+ "provider_id": "audio",
+ "tool_name": "transcribe",
+ },
+ {
+ "provider_type": "api",
+ "provider_id": "weather",
+ "tool_name": "forecast",
+ },
+ {
+ "provider_type": "workflow",
+ "provider_id": "workflow-tool",
+ "tool_name": "run_workflow",
+ },
+ {
+ "provider_type": "mcp",
+ "provider_id": "server-1",
+ "tool_name": "search_docs",
+ },
+ ]
+ }
+ )
+
+ assert [tool.provider_type for tool in config.tools] == ["plugin", "builtin", "api", "workflow", "mcp"]
+
+
+def test_dify_core_tool_config_rejects_unsupported_provider_types() -> None:
+ with pytest.raises(ValidationError, match="provider_type"):
+ _ = DifyCoreToolConfig.model_validate(
+ {
+ "provider_type": "app",
+ "provider_id": "app-tool",
+ "tool_name": "run",
+ }
+ )
diff --git a/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_layer.py b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_layer.py
new file mode 100644
index 00000000000..4f46cd0a394
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/dify_core_tools/test_layer.py
@@ -0,0 +1,290 @@
+import asyncio
+import sys
+import types
+
+import httpx
+import pytest
+
+from agenton.compositor import Compositor, LayerNode, LayerProvider
+
+
+def _install_graphon_stubs() -> None:
+ if "graphon.model_runtime.entities.llm_entities" in sys.modules:
+ return
+
+ graphon_module = types.ModuleType("graphon")
+ model_runtime_module = types.ModuleType("graphon.model_runtime")
+ entities_module = types.ModuleType("graphon.model_runtime.entities")
+ llm_entities_module = types.ModuleType("graphon.model_runtime.entities.llm_entities")
+ message_entities_module = types.ModuleType("graphon.model_runtime.entities.message_entities")
+
+ llm_entities_module.LLMResultChunk = type("LLMResultChunk", (), {})
+ llm_entities_module.LLMUsage = type("LLMUsage", (), {})
+
+ for name in (
+ "AssistantPromptMessage",
+ "AudioPromptMessageContent",
+ "DocumentPromptMessageContent",
+ "ImagePromptMessageContent",
+ "PromptMessage",
+ "PromptMessageContentUnionTypes",
+ "PromptMessageTool",
+ "SystemPromptMessage",
+ "TextPromptMessageContent",
+ "ToolPromptMessage",
+ "UserPromptMessage",
+ "VideoPromptMessageContent",
+ ):
+ setattr(message_entities_module, name, type(name, (), {}))
+
+ sys.modules["graphon"] = graphon_module
+ sys.modules["graphon.model_runtime"] = model_runtime_module
+ sys.modules["graphon.model_runtime.entities"] = entities_module
+ sys.modules["graphon.model_runtime.entities.llm_entities"] = llm_entities_module
+ sys.modules["graphon.model_runtime.entities.message_entities"] = message_entities_module
+
+ graphon_module.model_runtime = model_runtime_module
+ model_runtime_module.entities = entities_module
+ entities_module.llm_entities = llm_entities_module
+ entities_module.message_entities = message_entities_module
+
+
+_install_graphon_stubs()
+
+from dify_agent.layers.dify_core_tools.configs import DifyCoreToolConfig, DifyCoreToolsLayerConfig # noqa: E402
+from dify_agent.layers.dify_core_tools.layer import DifyCoreToolsLayer # noqa: E402
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig # noqa: E402
+from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer # noqa: E402
+
+
+def _execution_context_provider() -> LayerProvider[DifyExecutionContextLayer]:
+ return LayerProvider.from_factory(
+ layer_type=DifyExecutionContextLayer,
+ create=lambda config: DifyExecutionContextLayer.from_config_with_settings(
+ DifyExecutionContextLayerConfig.model_validate(config),
+ daemon_url="http://plugin-daemon",
+ daemon_api_key="daemon-secret",
+ ),
+ )
+
+
+def _core_tools_provider() -> LayerProvider[DifyCoreToolsLayer]:
+ return LayerProvider.from_factory(
+ layer_type=DifyCoreToolsLayer,
+ create=lambda config: DifyCoreToolsLayer.from_config_with_settings(
+ DifyCoreToolsLayerConfig.model_validate(config),
+ inner_api_url="http://dify-api",
+ inner_api_key="inner-secret",
+ ),
+ )
+
+
+def _execution_context_config() -> DifyExecutionContextLayerConfig:
+ return DifyExecutionContextLayerConfig(
+ tenant_id="tenant-1",
+ user_id="user-1",
+ user_from="account",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_run_id="workflow-run-1",
+ node_id="node-1",
+ node_execution_id="node-exec-1",
+ conversation_id="conversation-1",
+ agent_id="agent-1",
+ agent_config_version_id="snapshot-1",
+ agent_mode="workflow_run",
+ invoke_from="service-api",
+ )
+
+
+def test_core_tools_layer_exposes_pydantic_ai_tool_and_returns_inner_api_observation() -> None:
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("core_tools", _core_tools_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(
+ lambda _request: httpx.Response(
+ 200,
+ json={
+ "messages": [{"type": "text", "message": {"text": "done"}}],
+ "observation": "done",
+ "metadata": {"provider_type": "builtin"},
+ },
+ )
+ )
+ ) as http_client:
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config(),
+ "core_tools": DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ }
+ ) as run:
+ layer = run.get_layer("core_tools", DifyCoreToolsLayer)
+ tool = (await layer.get_tools(http_client=http_client))[0]
+ result = await tool.function_schema.call({}, None) # pyright: ignore[reportArgumentType]
+ assert result == "done"
+
+ asyncio.run(scenario())
+
+
+ ("response", "expected"),
+ [
+ (
+ httpx.Response(404, json={"code": "app_not_found", "message": "App not found."}),
+ "Tool is unavailable because its app context no longer exists.",
+ ),
+ (
+ httpx.Response(403, json={"code": "app_tenant_mismatch", "message": "App does not belong to tenant."}),
+ "Tool is unavailable because its app context is invalid.",
+ ),
+ (
+ httpx.Response(404, json={"code": "agent_tool_declaration_not_found", "message": "tool missing"}),
+ "there is not a tool named transcribe",
+ ),
+ (
+ httpx.Response(
+ 422,
+ json={"code": "agent_tool_credential_invalid", "message": "credential region is required"},
+ ),
+ "Please check your tool provider credentials",
+ ),
+ (
+ httpx.Response(422, json={"code": "tool_parameters_invalid", "message": "query is required"}),
+ "tool parameters validation error: query is required, please check your tool parameters",
+ ),
+ (
+ httpx.Response(422, json={"code": "agent_tool_invoke_failed", "message": "workflow crashed"}),
+ "tool invoke error: workflow crashed",
+ ),
+ ],
+)
+def test_core_tools_layer_maps_specific_inner_api_error_codes_to_observations(
+ response: httpx.Response,
+ expected: str,
+) -> None:
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("core_tools", _core_tools_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _request: response)) as http_client:
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config(),
+ "core_tools": DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ }
+ ) as run:
+ layer = run.get_layer("core_tools", DifyCoreToolsLayer)
+ tool = (await layer.get_tools(http_client=http_client))[0]
+ result = await tool.function_schema.call({}, None) # pyright: ignore[reportArgumentType]
+ assert result == expected
+
+ asyncio.run(scenario())
+
+
+def test_core_tools_layer_reports_missing_execution_context_without_parameter_validation_text() -> None:
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("core_tools", _core_tools_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _request: httpx.Response(200, json={"observation": "unused"}))
+ ) as http_client:
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config().model_copy(update={"app_id": None}),
+ "core_tools": DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ }
+ ) as run:
+ layer = run.get_layer("core_tools", DifyCoreToolsLayer)
+ tool = (await layer.get_tools(http_client=http_client))[0]
+ result = await tool.function_schema.call({}, None) # pyright: ignore[reportArgumentType]
+ assert result == "Tool is unavailable because required execution context is missing."
+
+ asyncio.run(scenario())
+
+
+ "response", [httpx.Response(429, json={"code": "knowledge_rate_limited"}), httpx.Response(502)]
+)
+def test_core_tools_layer_converts_retryable_failures_to_temporary_unavailable_observation(
+ response: httpx.Response,
+) -> None:
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("core_tools", _core_tools_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _request: response)) as http_client:
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config(),
+ "core_tools": DifyCoreToolsLayerConfig(
+ tools=[
+ DifyCoreToolConfig(
+ provider_type="builtin",
+ provider_id="audio",
+ tool_name="transcribe",
+ name="transcribe",
+ description="Transcribe audio.",
+ parameters=[],
+ parameters_json_schema={"type": "object", "properties": {}, "required": []},
+ )
+ ]
+ ),
+ }
+ ) as run:
+ layer = run.get_layer("core_tools", DifyCoreToolsLayer)
+ tool = (await layer.get_tools(http_client=http_client))[0]
+ result = await tool.function_schema.call({}, None) # pyright: ignore[reportArgumentType]
+ assert result == "Tool is temporarily unavailable. Please continue without it if possible."
+
+ asyncio.run(scenario())
diff --git a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py
index f41ce2de61f..86b04f95297 100644
--- a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py
+++ b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py
@@ -2,13 +2,15 @@
from __future__ import annotations
+from typing import Literal
+
import pytest
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
from dify_agent.layers.drive import DifyDriveLayerConfig, DifyDriveSkillConfig
from dify_agent.layers.drive.layer import DifyDriveLayer, DifyDriveLayerError
-from dify_agent.adapters.shell.shellctl import ShellctlProvisioner
from dify_agent.layers.shell import DifyShellLayerConfig
-from dify_agent.layers.shell.layer import DifyShellLayer, RemoteCommandResult
+from dify_agent.layers.shell.layer import CompleteRemoteCommandResult, DifyShellLayer
def _unused_client_factory():
@@ -18,7 +20,7 @@ def _unused_client_factory():
def _shell_layer() -> DifyShellLayer:
return DifyShellLayer.from_config_with_settings(
DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
- shell_provisioner=ShellctlProvisioner(client_factory=_unused_client_factory),
+ shell_provider=ShellctlProvider(entrypoint="http://shellctl", token="", client_factory=_unused_client_factory),
)
@@ -54,13 +56,19 @@ def _remote_result(
output: str,
*,
exit_code: int | None = 0,
- truncated: bool = False,
-) -> RemoteCommandResult:
- return RemoteCommandResult(
+ output_complete: bool = True,
+ incomplete_reason: Literal["output_limit", "timeout"] | None = None,
+) -> CompleteRemoteCommandResult:
+ return CompleteRemoteCommandResult(
+ job_id="remote-drive-pull",
status="exited",
+ done=True,
exit_code=exit_code,
output=output,
- truncated=truncated,
+ output_complete=output_complete,
+ incomplete_reason=incomplete_reason,
+ offset=len(output),
+ output_path="/tmp/output.log",
)
@@ -77,173 +85,155 @@ def _pulled_output() -> str:
)
+def _file_help_output(command: str) -> str:
+ return f"Usage: {command.removesuffix(' --help')} [OPTIONS]\n\nAgent Stub file command help.\n"
+
+
+def _patch_file_help(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ captured_scripts: list[str] = []
+
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> CompleteRemoteCommandResult:
+ del self, timeout, inject_agent_stub_env
+ captured_scripts.append(script)
+ return _remote_result(_file_help_output(script))
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+ return captured_scripts
+
+
def test_drive_layer_exposes_agent_stub_cli_usage_suffix_prompt() -> None:
layer = _build_layer()
+ layer._agent_stub_cli_help = {
+ "dify-agent file --help": _file_help_output("dify-agent file --help"),
+ "dify-agent file upload --help": _file_help_output("dify-agent file upload --help"),
+ }
assert len(layer.suffix_prompts) == 1
prompt = layer.suffix_prompts[0]
assert "Other available skills" in prompt
- assert "other-skill: Other Skill — Fallback catalog entry." in prompt
- assert "`dify-agent drive pull other-skill/`" not in prompt
- assert (
- '`skill_dir="$(dify-agent drive pull <SKILL_PATH> --to /tmp/drive)"; '
- 'printf "%s\\n" "$skill_dir"; cat "$skill_dir/SKILL.md"`'
- ) in prompt
- assert "dify-agent drive list [REMOTE_PREFIX]" in prompt
- assert "dify-agent drive pull [REMOTE ...] [--to LOCAL_DIR]" in prompt
- assert "--to ." in prompt
- assert "dify-agent drive push LOCAL_FILE REMOTE_PATH" in prompt
- assert "dify-agent drive push LOCAL_DIR REMOTE_PATH --kind skill" in prompt
- assert "dify-agent drive push LOCAL_DIR REMOTE_PATH --kind dir" in prompt
- assert "dify-agent file download TRANSFER_METHOD REFERENCE_OR_URL [--to LOCAL_DIR]" in prompt
- assert "dify-agent file download --mapping" in prompt
- assert "dify-agent file upload PATH" in prompt
- assert '{"transfer_method":"tool_file","reference":"..."}' in prompt
- assert "--recursive" not in prompt
- assert "--drive-base" not in prompt
+ assert "other-skill: Other Skill" in prompt
+ assert "Agent Stub file CLI help" in prompt
+ assert "$ dify-agent file upload --help" in prompt
+ assert "dify-agent drive" not in prompt
@pytest.mark.anyio
-async def test_on_context_create_pulls_mentioned_targets_through_shell(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
+async def test_on_context_create_pulls_mentioned_targets_through_shell(monkeypatch: pytest.MonkeyPatch) -> None:
layer = _build_layer()
captured: dict[str, object] = {}
+ help_scripts = _patch_file_help(monkeypatch)
- async def fake_run_remote_script(
+ async def fake_run_remote_script_complete(
self: DifyShellLayer,
script: str,
*,
timeout: float = 10.0,
inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
+ ) -> CompleteRemoteCommandResult:
del self, timeout
captured["script"] = script
captured["inject_agent_stub_env"] = inject_agent_stub_env
return _remote_result(_pulled_output())
- monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script_complete", fake_run_remote_script_complete)
await layer.on_context_create()
+ assert help_scripts == [
+ "dify-agent file --help",
+ "dify-agent file upload --help",
+ "dify-agent file download --help",
+ ]
+ assert "dify-agent file download --help" in layer._agent_stub_cli_help
script = captured["script"]
assert isinstance(script, str)
assert captured["inject_agent_stub_env"] is True
- assert "base=/mnt/drive/agent-1" in script
assert 'dify-agent drive pull tender-analyzer/ files/report.pdf --to "$base"' in script
- assert "cat /mnt/drive/agent-1/tender-analyzer/SKILL.md" in script
prompt = layer.build_prompt_context()
assert "Loaded mentioned skills" in prompt
- assert "Path: tender-analyzer" in prompt
- assert "Local path: /mnt/drive/agent-1/tender-analyzer" in prompt
- assert "Name: Tender Analyzer" not in prompt
assert "# Tender Analyzer\nUse carefully." in prompt
- assert "files/report.pdf -> /mnt/drive/agent-1/files/report.pdf" in prompt
- assert "Other available skills" not in prompt
-
-
-async def test_on_context_resume_repulls_mentioned_targets_through_shell(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- layer = _build_layer()
- calls = 0
-
- async def fake_run_remote_script(
- self: DifyShellLayer,
- script: str,
- *,
- timeout: float = 10.0,
- inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
- del self, script, timeout
- nonlocal calls
- calls += 1
- assert inject_agent_stub_env is True
- return _remote_result(_pulled_output())
-
- monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
-
- await layer.on_context_resume()
-
- assert calls == 1
- assert "Loaded mentioned skills" in layer.build_prompt_context()
@pytest.mark.anyio
-async def test_on_context_create_raises_when_mentioned_file_is_missing(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
+async def test_on_context_create_raises_when_shell_pull_fails(monkeypatch: pytest.MonkeyPatch) -> None:
layer = _build_layer()
+ _patch_file_help(monkeypatch)
- async def fake_run_remote_script(
+ async def fake_run_remote_script_complete(
self: DifyShellLayer,
script: str,
*,
timeout: float = 10.0,
inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
+ ) -> CompleteRemoteCommandResult:
del self, script, timeout, inject_agent_stub_env
- output = (
- "__DIFY_DRIVE_MENTIONED_PATH__\ttender-analyzer/SKILL.md\t/mnt/drive/agent-1/tender-analyzer/SKILL.md\n"
- "__DIFY_DRIVE_SKILL_BEGIN__\ttender-analyzer/SKILL.md\n"
- "# Tender Analyzer\n"
- "__DIFY_DRIVE_SKILL_END__\ttender-analyzer/SKILL.md\n"
- )
- return _remote_result(output)
+ return _remote_result("permission denied\n", exit_code=1)
- monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script_complete", fake_run_remote_script_complete)
- with pytest.raises(DifyDriveLayerError, match="missing pulled file"):
+ with pytest.raises(DifyDriveLayerError) as exc_info:
await layer.on_context_create()
+ message = str(exc_info.value)
+ assert "drive mentioned pull failed in shell: exited exit_code=1" in message
+ assert "output_complete=True" in message
+ assert "output_path=/tmp/output.log" in message
+
@pytest.mark.anyio
-async def test_on_context_create_raises_when_shell_pull_fails(
+async def test_on_context_create_raises_when_required_skill_marker_is_missing_from_complete_output(
monkeypatch: pytest.MonkeyPatch,
) -> None:
layer = _build_layer()
+ _patch_file_help(monkeypatch)
- async def fake_run_remote_script(
+ async def fake_run_remote_script_complete(
self: DifyShellLayer,
script: str,
*,
timeout: float = 10.0,
inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
+ ) -> CompleteRemoteCommandResult:
del self, script, timeout, inject_agent_stub_env
- return _remote_result("permission denied\n", exit_code=1)
+ return _remote_result("__DIFY_DRIVE_MENTIONED_PATH__\tfiles/report.pdf\t/mnt/drive/agent-1/files/report.pdf\n")
- monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script_complete", fake_run_remote_script_complete)
- with pytest.raises(DifyDriveLayerError, match="drive mentioned pull failed in shell"):
+ with pytest.raises(DifyDriveLayerError, match="missing pulled SKILL.md"):
await layer.on_context_create()
@pytest.mark.anyio
-async def test_on_context_create_raises_when_shell_output_is_truncated(
+async def test_on_context_create_reports_incomplete_capture_when_required_marker_is_missing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
layer = _build_layer()
+ _patch_file_help(monkeypatch)
- async def fake_run_remote_script(
+ async def fake_run_remote_script_complete(
self: DifyShellLayer,
script: str,
*,
timeout: float = 10.0,
inject_agent_stub_env: bool = False,
- ) -> RemoteCommandResult:
+ ) -> CompleteRemoteCommandResult:
del self, script, timeout, inject_agent_stub_env
- return _remote_result(_pulled_output(), truncated=True)
+ output = (
+ "__DIFY_DRIVE_MENTIONED_PATH__\ttender-analyzer/SKILL.md\t/mnt/drive/agent-1/tender-analyzer/SKILL.md\n"
+ )
+ return _remote_result(output, output_complete=False, incomplete_reason="output_limit")
- monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script_complete", fake_run_remote_script_complete)
- with pytest.raises(DifyDriveLayerError, match="output was truncated"):
+ with pytest.raises(DifyDriveLayerError) as exc_info:
await layer.on_context_create()
-
-def test_parse_shell_pull_output_rejects_unclosed_skill_marker() -> None:
- layer = _build_layer()
-
- with pytest.raises(DifyDriveLayerError, match="omitted SKILL.md end marker"):
- layer._parse_shell_pull_output("__DIFY_DRIVE_SKILL_BEGIN__\ttender-analyzer/SKILL.md\n# Tender\n")
+ message = str(exc_info.value)
+ assert "output incomplete before required SKILL.md content was captured" in message
+ assert "reason=output_limit" in message
diff --git a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py
index 58aae61bd75..f4bf3fa8b99 100644
--- a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py
+++ b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py
@@ -1,50 +1,42 @@
+from __future__ import annotations
+
import asyncio
+import json
from collections.abc import Callable, Mapping
-import secrets
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import cast
import pytest
-from agenton.compositor import Compositor, LayerNode, LayerProvider
-from agenton.layers import LifecycleState
-from dify_agent.agent_stub.server.shell_agent_stub_env import (
- AGENT_STUB_AUTH_JWE_ENV_VAR,
- AGENT_STUB_DRIVE_BASE_ENV_VAR,
- AGENT_STUB_API_BASE_URL_ENV_VAR,
-)
-from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
-from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
-from dify_agent.layers.shell import (
- DIFY_SHELL_LAYER_TYPE_ID,
- DifyShellCliToolConfig,
- DifyShellEnvVarConfig,
- DifyShellLayerConfig,
- DifyShellSandboxConfig,
- DifyShellSecretRefConfig,
+import dify_agent.layers.shell.layer as shell_layer_module
+from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
+from dify_agent.layers.shell.layer import (
+ CompleteRemoteCommandResult,
+ DEFAULT_TERMINATE_GRACE_SECONDS,
+ DifyShellLayer,
+ DifyShellRuntimeState,
)
-from dify_agent.adapters.shell.shellctl import (
- ShellctlEnvironmentDescriptor,
- ShellctlHandle,
- ShellctlProvisioner,
- ShellProvisionError,
+from dify_agent.adapters.shell.protocols import (
+ ShellCommandResult,
+ ShellCommandStatus,
+ ShellFileTransferProtocol,
+ ShellProviderProtocol,
+ ShellResourceProtocol,
)
-from dify_agent.layers.shell.layer import DifyShellLayer, DifyShellRuntimeState
-from shell_session_manager.shellctl.shared import JobResult, JobStatusName, JobStatusView
-def _job_result(
+def _command_result(
job_id: str,
*,
- status: JobStatusName = JobStatusName.RUNNING,
+ status: str = "running",
done: bool = False,
exit_code: int | None = None,
output: str = "",
offset: int = 0,
truncated: bool = False,
- output_path: str = "/tmp/output.log",
-) -> JobResult:
- return JobResult(
+ output_path: str | None = "/tmp/output.log",
+) -> ShellCommandResult:
+ return ShellCommandResult(
job_id=job_id,
status=status,
done=done,
@@ -56,34 +48,36 @@ def _job_result(
)
-def _job_status(
+def _command_status(
job_id: str,
*,
- status: JobStatusName = JobStatusName.RUNNING,
- done: bool = False,
- exit_code: int | None = None,
+ status: str = "terminated",
+ done: bool = True,
+ exit_code: int | None = 130,
offset: int = 0,
-) -> JobStatusView:
- return JobStatusView(
- job_id=job_id,
- status=status,
- done=done,
- exit_code=exit_code,
- created_at="2026-05-28T12:00:00Z",
- started_at="2026-05-28T12:00:01Z",
- ended_at="2026-05-28T12:00:02Z" if done else None,
- offset=offset,
- )
+) -> ShellCommandStatus:
+ return ShellCommandStatus(job_id=job_id, status=status, done=done, exit_code=exit_code, offset=offset)
+
+
+def _parse_tagged_observation(result: object) -> tuple[dict[str, object], str]:
+ assert isinstance(result, str)
+ metadata_tag = "\n</metadata>\n\n<output>\n"
+ assert result.startswith("<metadata>\n")
+ assert result.endswith("\n</output>")
+ metadata_block, output_block = result.split(metadata_tag, 1)
+ metadata = json.loads(metadata_block.removeprefix("<metadata>\n"))
+ assert isinstance(metadata, dict)
+ output = output_block.removesuffix("\n</output>")
+ return cast(dict[str, object], metadata), output
def _assert_error_observation(result: object, *, job_id: str | None = None, includes: str | None = None) -> None:
assert isinstance(result, dict)
assert isinstance(result.get("error"), str)
- assert result["error"]
if job_id is None:
assert "job_id" not in result
else:
- assert result.get("job_id") == job_id
+ assert result["job_id"] == job_id
if includes is not None:
assert includes in result["error"]
@@ -92,8 +86,8 @@ def _assert_error_observation(result: object, *, job_id: str | None = None, incl
class RunCall:
script: str
cwd: str | None
- timeout: float
env: Mapping[str, str] | None
+ timeout: float
@dataclass(slots=True)
@@ -112,7 +106,12 @@ class InputCall:
@dataclass(slots=True)
-class TerminateCall:
+class TailCall:
+ job_id: str
+
+
+@dataclass(slots=True)
+class InterruptCall:
job_id: str
grace_seconds: float
@@ -121,479 +120,246 @@ class TerminateCall:
class DeleteCall:
job_id: str
force: bool
+ grace_seconds: float | None
+
+
+class FakeFiles(ShellFileTransferProtocol):
+ async def upload(self, *, content: bytes, remote_path: str, cwd: str | None = None) -> None:
+ raise AssertionError("resource.files should not be used by production shell layer logic")
+ async def download(self, *, remote_path: str, cwd: str | None = None) -> bytes:
+ raise AssertionError("resource.files should not be used by production shell layer logic")
-class FakeShellctlClient:
- run_calls: list[RunCall]
- wait_calls: list[WaitCall]
- input_calls: list[InputCall]
- terminate_calls: list[TerminateCall]
- delete_calls: list[DeleteCall]
- events: list[tuple[str, str]]
- closed: bool
-
- def __init__(
- self,
- *,
- run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], JobResult] | None = None,
- wait_handler: Callable[[str, int, float], JobResult] | None = None,
- input_handler: Callable[[str, str, int, float], JobResult] | None = None,
- terminate_handler: Callable[[str, float], JobStatusView] | None = None,
- delete_handler: Callable[[str, bool, float | None], object] | None = None,
- ) -> None:
- self._run_handler = run_handler
- self._wait_handler = wait_handler
- self._input_handler = input_handler
- self._terminate_handler = terminate_handler
- self._delete_handler = delete_handler
- self.run_calls = []
- self.wait_calls = []
- self.input_calls = []
- self.terminate_calls = []
- self.delete_calls = []
- self.events = []
- self.closed = False
-
- async def run(
- self,
- script: str,
- *,
- cwd: str | None = None,
- env: Mapping[str, str] | None = None,
- timeout: float = 10.0,
- ) -> JobResult:
- self.run_calls.append(RunCall(script=script, cwd=cwd, timeout=timeout, env=env))
- self.events.append(("run", script))
- if self._run_handler is None:
+
+@dataclass(slots=True)
+class FakeCommands:
+ run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], ShellCommandResult] | None = None
+ wait_handler: Callable[[str, int, float], ShellCommandResult] | None = None
+ input_handler: Callable[[str, str, int, float], ShellCommandResult] | None = None
+ tail_handler: Callable[[str], ShellCommandResult] | None = None
+ interrupt_handler: Callable[[str, float], ShellCommandStatus] | None = None
+ delete_handler: Callable[[str, bool, float | None], None] | None = None
+ run_calls: list[RunCall] = field(default_factory=list)
+ wait_calls: list[WaitCall] = field(default_factory=list)
+ input_calls: list[InputCall] = field(default_factory=list)
+ tail_calls: list[TailCall] = field(default_factory=list)
+ interrupt_calls: list[InterruptCall] = field(default_factory=list)
+ delete_calls: list[DeleteCall] = field(default_factory=list)
+
+ async def run(self, script: str, *, cwd: str | None = None, env: dict[str, str] | None = None, timeout: float):
+ self.run_calls.append(RunCall(script=script, cwd=cwd, env=env, timeout=timeout))
+ if self.run_handler is None:
raise AssertionError("Unexpected run() call")
- return self._run_handler(script, cwd, env, timeout)
+ return self.run_handler(script, cwd, env, timeout)
- async def wait(self, job_id: str, *, offset: int, timeout: float = 10.0) -> JobResult:
+ async def wait(self, job_id: str, *, offset: int, timeout: float):
self.wait_calls.append(WaitCall(job_id=job_id, offset=offset, timeout=timeout))
- self.events.append(("wait", job_id))
- if self._wait_handler is None:
+ if self.wait_handler is None:
raise AssertionError("Unexpected wait() call")
- return self._wait_handler(job_id, offset, timeout)
+ return self.wait_handler(job_id, offset, timeout)
- async def input(self, job_id: str, text: str, *, offset: int, timeout: float = 10.0) -> JobResult:
+ async def read_output(self, job_id: str, *, offset: int):
+ self.wait_calls.append(WaitCall(job_id=job_id, offset=offset, timeout=0.0))
+ if self.wait_handler is None:
+ raise AssertionError("Unexpected read_output() call")
+ return self.wait_handler(job_id, offset, 0.0)
+
+ async def input(self, job_id: str, text: str, *, offset: int, timeout: float):
self.input_calls.append(InputCall(job_id=job_id, text=text, offset=offset, timeout=timeout))
- self.events.append(("input", job_id))
- if self._input_handler is None:
+ if self.input_handler is None:
raise AssertionError("Unexpected input() call")
- return self._input_handler(job_id, text, offset, timeout)
-
- async def terminate(self, job_id: str, grace_seconds: float = 2.0) -> JobStatusView:
- self.terminate_calls.append(TerminateCall(job_id=job_id, grace_seconds=grace_seconds))
- self.events.append(("terminate", job_id))
- if self._terminate_handler is None:
- raise AssertionError("Unexpected terminate() call")
- return self._terminate_handler(job_id, grace_seconds)
-
- async def delete(
- self,
- job_id: str,
- *,
- force: bool = False,
- ) -> object:
- self.delete_calls.append(DeleteCall(job_id=job_id, force=force))
- self.events.append(("delete", job_id))
- if self._delete_handler is None:
- return None
- return self._delete_handler(job_id, force, None)
+ return self.input_handler(job_id, text, offset, timeout)
- async def close(self) -> None:
- self.closed = True
- self.events.append(("close", "client"))
+ async def interrupt(self, job_id: str, *, grace_seconds: float):
+ self.interrupt_calls.append(InterruptCall(job_id=job_id, grace_seconds=grace_seconds))
+ if self.interrupt_handler is None:
+ raise AssertionError("Unexpected interrupt() call")
+ return self.interrupt_handler(job_id, grace_seconds)
+ async def tail(self, job_id: str):
+ self.tail_calls.append(TailCall(job_id=job_id))
+ if self.tail_handler is None:
+ raise AssertionError("Unexpected tail() call")
+ return self.tail_handler(job_id)
-def _shell_layer(*, client: FakeShellctlClient, config: DifyShellLayerConfig | None = None) -> DifyShellLayer:
- return DifyShellLayer.from_config_with_settings(
- config or DifyShellLayerConfig(),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- )
+ async def delete(self, job_id: str, *, force: bool = False, grace_seconds: float | None = None) -> None:
+ self.delete_calls.append(DeleteCall(job_id=job_id, force=force, grace_seconds=grace_seconds))
+ if self.delete_handler is not None:
+ self.delete_handler(job_id, force, grace_seconds)
-def _execution_context_layer() -> DifyExecutionContextLayer:
- return DifyExecutionContextLayer.from_config_with_settings(
- DifyExecutionContextLayerConfig(
- tenant_id="tenant-1",
- user_id="user-1",
- user_from="account",
- app_id="app-1",
- workflow_id="workflow-1",
- workflow_run_id="workflow-run-1",
- node_id="node-1",
- node_execution_id="node-execution-1",
- conversation_id="conversation-1",
- agent_id="agent-1",
- agent_config_version_id="agent-config-version-1",
- agent_mode="workflow_run",
- invoke_from="service-api",
- trace_id="trace-1",
- ),
- daemon_url="http://plugin-daemon",
- daemon_api_key="daemon-secret",
- )
+@dataclass(slots=True)
+class FakeResource(ShellResourceProtocol):
+ commands: FakeCommands
+ files: FakeFiles = field(default_factory=FakeFiles)
+ closed: bool = False
+ async def close(self) -> None:
+ self.closed = True
-def _shell_provider(*, client: FakeShellctlClient) -> LayerProvider[DifyShellLayer]:
- return LayerProvider.from_factory(
- layer_type=DifyShellLayer,
- create=lambda config: DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig.model_validate(config),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- ),
- )
+@dataclass(slots=True)
+class FakeProvider(ShellProviderProtocol):
+ resource: FakeResource
+ create_calls: int = 0
-def test_shell_type_id_constant_matches_implementation_class() -> None:
- assert DIFY_SHELL_LAYER_TYPE_ID == DifyShellLayer.type_id
+ async def create(self) -> ShellResourceProtocol:
+ self.create_calls += 1
+ return self.resource
-def test_environment_descriptor_returns_workspace_seed_from_runtime_state() -> None:
- layer = _shell_layer(client=FakeShellctlClient())
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
+def _layer(
+ *, commands: FakeCommands, config: DifyShellLayerConfig | None = None
+) -> tuple[DifyShellLayer, FakeProvider]:
+ provider = FakeProvider(resource=FakeResource(commands=commands))
+ layer = DifyShellLayer.from_config_with_settings(config or DifyShellLayerConfig(), shell_provider=provider)
+ return layer, provider
- descriptor = layer.environment_descriptor()
- assert descriptor == ShellctlEnvironmentDescriptor(workspace_cwd="~/workspace/abc12ff", session_id="abc12ff")
+def test_shell_type_id_constant_matches_implementation_class() -> None:
+ assert DIFY_SHELL_LAYER_TYPE_ID == DifyShellLayer.type_id
-def test_environment_descriptor_raises_without_session_identity() -> None:
- layer = _shell_layer(client=FakeShellctlClient())
+def test_resource_context_calls_provider_create_and_resource_close() -> None:
+ layer, provider = _layer(commands=FakeCommands())
- with pytest.raises(ValueError, match="session_id or workspace_cwd"):
- _ = layer.environment_descriptor()
+ async def scenario() -> None:
+ async with layer.resource_context():
+ assert provider.create_calls == 1
+ assert provider.resource.closed is False
+ assert provider.resource.closed is True
+
+ asyncio.run(scenario())
-def test_shell_layer_create_provisions_workspace_and_bootstraps(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "deadbeefdeadbeef")
+def test_shell_layer_create_allocates_workspace_and_bootstraps(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(shell_layer_module.time, "time", lambda: int("abc12", 16))
+ monkeypatch.setattr(shell_layer_module.secrets, "token_hex", lambda _nbytes: "ff")
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
assert env is None
if cwd is None:
- assert 'mkdir -p "$HOME/workspace/deadbeefdeadbeef"' in script
- return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)
- raise AssertionError(f"Unexpected script with cwd={cwd}: {script}")
+ assert 'mkdir -p "$HOME/workspace"' in script
+ return _command_result("mkdir-job", status="exited", done=True, exit_code=0)
+ assert cwd == "~/workspace/abc12ff"
+ assert "apt-get install -y ripgrep" in script
+ return _command_result("bootstrap-job", status="exited", done=True, exit_code=0)
- client = FakeShellctlClient(run_handler=run_handler)
- layer = _shell_layer(client=client)
+ layer, provider = _layer(
+ commands=FakeCommands(run_handler=run_handler),
+ config=DifyShellLayerConfig(
+ cli_tools=[{"name": "ripgrep", "install_commands": ["apt-get install -y ripgrep"]}],
+ ),
+ )
async def scenario() -> None:
async with layer.resource_context():
await layer.on_context_create()
- assert client.closed is False
+ assert provider.resource.closed is False
asyncio.run(scenario())
- assert layer.runtime_state.session_id == "deadbeefdeadbeef"
- assert layer.runtime_state.workspace_cwd == "~/workspace/deadbeefdeadbeef"
+ assert layer.runtime_state == DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
+ assert [call.job_id for call in provider.resource.commands.delete_calls] == ["mkdir-job", "bootstrap-job"]
-def test_shell_layer_suspend_closes_client_before_resource_context_exits() -> None:
- client = FakeShellctlClient()
- layer = _shell_layer(client=client)
+def test_shell_layer_suspend_does_not_close_before_resource_context_exits() -> None:
+ layer, provider = _layer(commands=FakeCommands())
layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
await layer.on_context_suspend()
- assert client.closed is True
+ assert provider.resource.closed is False
+ assert provider.resource.closed is True
asyncio.run(scenario())
-def test_shell_layer_suspend_and_resume_reuse_state_with_fresh_clients() -> None:
- first_client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env, _timeout: _job_result(
- "mkdir-job",
- status=JobStatusName.EXITED,
- done=True,
- exit_code=0,
- )
+def test_shell_layer_delete_cleans_workspace_and_tracked_jobs() -> None:
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
+ del env, timeout
+ assert cwd is None
+ assert script == 'rm -rf -- "$HOME/workspace/abc12ff"'
+ return _command_result("cleanup-job", status="exited", done=True, exit_code=0)
+
+ commands = FakeCommands(run_handler=run_handler)
+ layer, provider = _layer(commands=commands)
+ layer.runtime_state = DifyShellRuntimeState(
+ session_id="abc12ff",
+ workspace_cwd="~/workspace/abc12ff",
+ job_ids=["user-job"],
+ job_offsets={"user-job": 9},
)
- second_client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env, _timeout: _job_result(
- "cleanup-job",
- status=JobStatusName.EXITED,
- done=True,
- exit_code=0,
- )
- )
- clients = iter([first_client, second_client])
-
- def factory() -> FakeShellctlClient:
- return next(clients)
-
- provisioner = ShellctlProvisioner(client_factory=factory)
-
- def make_provider(c: FakeShellctlClient) -> LayerProvider[DifyShellLayer]:
- return LayerProvider.from_factory(
- layer_type=DifyShellLayer,
- create=lambda config: DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig.model_validate(config),
- shell_provisioner=provisioner,
- ),
- )
-
- compositor = Compositor([LayerNode("shell", make_provider(first_client))])
-
- async def scenario() -> None:
- async with compositor.enter(configs={"shell": DifyShellLayerConfig()}) as run:
- shell_layer = run.get_layer("shell", DifyShellLayer)
- initial_session_id = shell_layer.runtime_state.session_id
- assert initial_session_id is not None
- assert shell_layer.runtime_state.workspace_cwd == f"~/workspace/{initial_session_id}"
- shell_layer.runtime_state.job_ids = [*shell_layer.runtime_state.job_ids, "user-job"]
- shell_layer.runtime_state.job_offsets = {
- **shell_layer.runtime_state.job_offsets,
- "user-job": 42,
- }
- assert first_client.closed is False
- run.suspend_layer_on_exit("shell")
-
- assert run.session_snapshot is not None
- assert first_client.closed is True
- assert run.session_snapshot.layers[0].lifecycle_state is LifecycleState.SUSPENDED
-
- async with compositor.enter(
- configs={"shell": DifyShellLayerConfig()},
- session_snapshot=run.session_snapshot,
- ) as resumed_run:
- resumed_shell = resumed_run.get_layer("shell", DifyShellLayer)
- assert second_client.closed is False
- assert resumed_shell.runtime_state.session_id == initial_session_id
- assert resumed_shell.runtime_state.workspace_cwd == f"~/workspace/{initial_session_id}"
- assert set(resumed_shell.runtime_state.job_ids) == {"user-job"}
- assert resumed_shell.runtime_state.job_offsets == {"user-job": 42}
- resumed_run.suspend_layer_on_exit("shell")
-
- assert second_client.closed is True
-
- asyncio.run(scenario())
-
-
-def test_shell_layer_delete_force_deletes_tracked_jobs_then_destroys_workspace() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- del cwd, env, timeout
- return _job_result("cleanup-job", status=JobStatusName.EXITED, done=True, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = _shell_layer(client=client)
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer.runtime_state.job_ids = ["user-job", "mkdir-job"]
- layer.runtime_state.job_offsets = {"user-job": 9, "mkdir-job": 1}
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
await layer.on_context_delete()
asyncio.run(scenario())
- deleted_job_ids = {call.job_id for call in client.delete_calls}
- assert {"user-job", "mkdir-job"}.issubset(deleted_job_ids)
- assert all(call.force is True for call in client.delete_calls)
+ assert [call.job_id for call in commands.delete_calls] == ["cleanup-job", "user-job"]
assert layer.runtime_state.job_ids == []
assert layer.runtime_state.job_offsets == {}
- assert client.closed is True
-
-
-def test_shell_layer_create_failure_destroys_provisioned_workspace() -> None:
- client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env, _timeout: _job_result(
- "mkdir-failed",
- status=JobStatusName.EXITED,
- done=True,
- exit_code=1,
- )
- )
- layer = _shell_layer(client=client)
-
- async def scenario() -> None:
- with pytest.raises(ShellProvisionError, match="Failed to create shell workspace"):
- async with layer.resource_context():
- await layer.on_context_create()
-
- asyncio.run(scenario())
-
- assert client.closed is True
-
-
-def test_shell_layer_create_bootstraps_agent_soul_shell_config(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "abc12ffabc12ff")
-
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- assert env is None
- if cwd is None:
- return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)
- assert cwd == "~/workspace/abc12ffabc12ff"
- assert "export PROJECT_NAME='demo project'" in script
- assert "export QUOTED='it'\\''s ok'" in script
- assert 'export OPENAI_API_KEY="${OPENAI_API_KEY:-}"' in script
- assert "export RG_CONFIG_PATH='.ripgreprc'" in script
- assert 'export GITHUB_TOKEN="${GITHUB_TOKEN:-}"' in script
- assert "export DIFY_SANDBOX_PROVIDER='independent'" in script
- assert "export DIFY_SANDBOX_CONFIG_JSON='{\"cpu\": 2}'" in script
- assert "apt-get install -y ripgrep" in script
- return _job_result("bootstrap-job", status=JobStatusName.EXITED, done=True, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = _shell_layer(
- client=client,
- config=DifyShellLayerConfig(
- cli_tools=[
- DifyShellCliToolConfig(
- name="ripgrep",
- install_commands=["apt-get install -y ripgrep"],
- env=[DifyShellEnvVarConfig(name="RG_CONFIG_PATH", value=".ripgreprc")],
- secret_refs=[DifyShellSecretRefConfig(name="GITHUB_TOKEN", ref="secret-2")],
- )
- ],
- env=[
- DifyShellEnvVarConfig(name="PROJECT_NAME", value="demo project"),
- DifyShellEnvVarConfig(name="QUOTED", value="it's ok"),
- ],
- secret_refs=[DifyShellSecretRefConfig(name="OPENAI_API_KEY", ref="secret-1")],
- sandbox=DifyShellSandboxConfig(provider="independent", config={"cpu": 2}),
- ),
- )
-
- async def scenario() -> None:
- async with layer.resource_context():
- await layer.on_context_create()
-
- asyncio.run(scenario())
-
- assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ffabc12ff"]
-
-
-def test_shell_layer_injects_agent_soul_env_without_workspace_env_file(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(secrets, "token_hex", lambda _nbytes: "abc12ffabc12ff")
-
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- del timeout
- assert env is None
- if cwd is None:
- return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)
-
- assert cwd == "~/workspace/abc12ffabc12ff"
- assert "export PROJECT_NAME='demo project'" in script
- assert 'export OPENAI_API_KEY="${OPENAI_API_KEY:-}"' in script
- assert "export DIFY_SANDBOX_PROVIDER='independent'" in script
- assert "export DIFY_SANDBOX_CONFIG_JSON='{\"cpu\": 2}'" in script
- assert script.endswith("\npwd")
- return _job_result("user-job", status=JobStatusName.EXITED, done=True, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = _shell_layer(
- client=client,
- config=DifyShellLayerConfig(
- env=[DifyShellEnvVarConfig(name="PROJECT_NAME", value="demo project")],
- secret_refs=[DifyShellSecretRefConfig(name="OPENAI_API_KEY", ref="secret-1")],
- sandbox=DifyShellSandboxConfig(provider="independent", config={"cpu": 2}),
- ),
- )
- tools = {tool.name: tool for tool in layer.tools}
-
- async def scenario() -> None:
- async with layer.resource_context():
- await layer.on_context_create()
- run_result = cast(
- Mapping[str, object],
- await tools["shell_run"].function_schema.call(
- {"script": "pwd"},
- None, # pyright: ignore[reportArgumentType]
- ),
- )
- assert run_result["job_id"] == "user-job"
-
- asyncio.run(scenario())
-
- assert [call.cwd for call in client.run_calls] == [None, "~/workspace/abc12ffabc12ff"]
+ assert provider.resource.closed is True
-def test_shell_layer_tools_map_inputs_to_shellctl_calls_and_maintain_offsets() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
+def test_shell_layer_tools_map_inputs_and_maintain_offsets_with_tail_end() -> None:
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
assert script == "pwd"
assert cwd == "~/workspace/abc12ff"
assert env is None
- assert timeout == 2.5
- return _job_result(
+ return _command_result(
"user-job",
- status=JobStatusName.RUNNING,
+ status="running",
done=False,
+ output="head-output\n",
offset=10,
- output="/home/test\n",
+ truncated=True,
+ output_path="/tmp/initial.log",
)
- def wait_handler(job_id: str, offset: int, timeout: float) -> JobResult:
+ def wait_handler(job_id: str, offset: int, timeout: float) -> ShellCommandResult:
assert job_id == "user-job"
- assert offset == 10
- assert timeout == 4.0
- return _job_result(
- "user-job",
- status=JobStatusName.RUNNING,
- done=False,
- offset=18,
- output="more\n",
- )
+ if timeout == 4.0:
+ assert offset == 22
+ return _command_result("user-job", status="running", done=False, output="more\n", offset=30)
+ raise AssertionError(f"Unexpected wait/read_output: offset={offset} timeout={timeout}")
- def input_handler(job_id: str, text: str, offset: int, timeout: float) -> JobResult:
+ def input_handler(job_id: str, text: str, offset: int, timeout: float) -> ShellCommandResult:
+ assert (job_id, text, offset, timeout) == ("user-job", "ls\n", 30, 5.0)
+ return _command_result("user-job", status="exited", done=True, exit_code=0, output="file.txt\n", offset=34)
+
+ def tail_handler(job_id: str) -> ShellCommandResult:
assert job_id == "user-job"
- assert text == "ls\n"
- assert offset == 18
- assert timeout == 5.0
- return _job_result(
- "user-job",
- status=JobStatusName.EXITED,
+ return _command_result(
+ job_id,
+ status="exited",
done=True,
exit_code=0,
+ output="tail-output\n",
offset=22,
- output="file.txt\n",
+ output_path="/tmp/resolved.log",
)
- def terminate_handler(job_id: str, grace_seconds: float) -> JobStatusView:
- assert job_id == "user-job"
- assert grace_seconds == 1.5
- return _job_status(
- "user-job",
- status=JobStatusName.TERMINATED,
- done=True,
- exit_code=130,
- offset=22,
- )
+ def interrupt_handler(job_id: str, grace_seconds: float) -> ShellCommandStatus:
+ assert (job_id, grace_seconds) == ("user-job", 1.5)
+ return _command_status("user-job", status="terminated", done=True, exit_code=130, offset=34)
- client = FakeShellctlClient(
+ commands = FakeCommands(
run_handler=run_handler,
wait_handler=wait_handler,
input_handler=input_handler,
- terminate_handler=terminate_handler,
+ tail_handler=tail_handler,
+ interrupt_handler=interrupt_handler,
)
- layer = _shell_layer(client=client)
+ layer, provider = _layer(commands=commands)
tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
-
- run_tool_def = await tools["shell_run"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]
- wait_tool_def = await tools["shell_wait"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]
- input_tool_def = await tools["shell_input"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]
- interrupt_tool_def = await tools["shell_interrupt"].prepare_tool_def(None) # pyright: ignore[reportArgumentType]
-
- run_result = await tools["shell_run"].function_schema.call(
- {"script": "pwd", "timeout": 2.5},
- None, # pyright: ignore[reportArgumentType]
- )
+ run_result = await tools["shell_run"].function_schema.call({"script": "pwd"}, None) # pyright: ignore[reportArgumentType]
wait_result = await tools["shell_wait"].function_schema.call(
{"job_id": "user-job", "timeout": 4.0},
None, # pyright: ignore[reportArgumentType]
@@ -607,324 +373,296 @@ def test_shell_layer_tools_map_inputs_to_shellctl_calls_and_maintain_offsets() -
None, # pyright: ignore[reportArgumentType]
)
- assert run_tool_def is not None
- assert wait_tool_def is not None
- assert input_tool_def is not None
- assert interrupt_tool_def is not None
- assert "offset" not in run_tool_def.parameters_json_schema.get("properties", {})
- assert "offset" not in wait_tool_def.parameters_json_schema.get("properties", {})
- assert "offset" not in input_tool_def.parameters_json_schema.get("properties", {})
- assert "offset" not in interrupt_tool_def.parameters_json_schema.get("properties", {})
- assert set(tools) == {"shell_run", "shell_wait", "shell_input", "shell_interrupt"}
- assert run_result["job_id"] == "user-job"
- assert run_result["offset"] == 10
- assert wait_result["offset"] == 18
- assert input_result["offset"] == 22
- assert interrupt_result == {
+ run_metadata, run_output = _parse_tagged_observation(run_result)
+ wait_metadata, wait_output = _parse_tagged_observation(wait_result)
+ input_metadata, input_output = _parse_tagged_observation(input_result)
+ interrupt_metadata, interrupt_output = _parse_tagged_observation(interrupt_result)
+
+ assert run_metadata == {
+ "job_id": "user-job",
+ "status": "running",
+ "done": False,
+ "exit_code": None,
+ "output_path": "/tmp/resolved.log",
+ }
+ assert "head-output" in run_output
+ assert "tail-output" in run_output
+ assert wait_metadata["job_id"] == "user-job"
+ assert wait_output == "more\n"
+ assert input_metadata["exit_code"] == 0
+ assert input_output == "file.txt\n"
+ assert interrupt_metadata == {
"job_id": "user-job",
"status": "terminated",
"done": True,
"exit_code": 130,
- "offset": 22,
+ "output_path": "/tmp/resolved.log",
}
- assert client.closed is False
+ assert interrupt_output == "Job was interrupted."
asyncio.run(scenario())
- assert layer.runtime_state.job_ids == ["user-job"]
- assert layer.runtime_state.job_offsets == {"user-job": 22}
- assert client.closed is False
+ assert layer.runtime_state.job_offsets == {"user-job": 34}
+ assert commands.tail_calls == [TailCall(job_id="user-job"), TailCall(job_id="user-job")]
+ assert provider.resource.closed is True
-def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- del cwd, timeout
- if script == "pwd":
- assert env is not None
- return _job_result("user-job", status=JobStatusName.EXITED, done=True, exit_code=0)
+def test_shell_run_keeps_original_offset_when_tail_lookup_fails_for_truncated_output() -> None:
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
+ assert script == "pwd"
+ assert cwd == "~/workspace/abc12ff"
assert env is None
- return _job_result("mkdir-job", status=JobStatusName.EXITED, done=True, exit_code=0)
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- agent_stub_api_base_url="https://agent.example.com/agent-stub",
- agent_stub_token_factory=lambda execution_context, *, session_id: (
- f"token-for:{execution_context.tenant_id}:{session_id}"
- ),
- )
- layer.deps = layer.deps_type(execution_context=_execution_context_layer())
+ return _command_result(
+ "user-job",
+ status="running",
+ done=False,
+ output="head-output\n",
+ offset=10,
+ truncated=True,
+ output_path="/tmp/current.log",
+ )
+
+ def tail_handler(job_id: str) -> ShellCommandResult:
+ raise RuntimeError(f"tail unavailable for {job_id}")
+
+ commands = FakeCommands(run_handler=run_handler, tail_handler=tail_handler)
+ layer, provider = _layer(commands=commands)
tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- await layer.on_context_create()
- run_result = await tools["shell_run"].function_schema.call(
- {"script": "pwd"},
- None, # pyright: ignore[reportArgumentType]
- )
- assert run_result["job_id"] == "user-job"
+ run_result = await tools["shell_run"].function_schema.call({"script": "pwd"}, None) # pyright: ignore[reportArgumentType]
+ metadata, output = _parse_tagged_observation(run_result)
+ assert metadata == {
+ "job_id": "user-job",
+ "status": "running",
+ "done": False,
+ "exit_code": None,
+ "output_path": "/tmp/current.log",
+ }
+ assert "head-output" in output
+ assert set(metadata) == {"job_id", "status", "done", "exit_code", "output_path"}
asyncio.run(scenario())
- user_run_call = next(call for call in client.run_calls if call.script == "pwd")
- internal_run_calls = [call for call in client.run_calls if call.script != "pwd"]
+ assert layer.runtime_state.job_offsets == {"user-job": 10}
+ assert commands.tail_calls == [TailCall(job_id="user-job")]
+ assert provider.resource.closed is True
- assert user_run_call.env == {
- AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",
- AGENT_STUB_AUTH_JWE_ENV_VAR: f"token-for:tenant-1:{layer.runtime_state.session_id}",
- AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive/agent-1",
- }
- assert internal_run_calls
- assert all(call.env is None for call in internal_run_calls)
-
-def test_run_remote_script_uses_workspace_cwd_accumulates_output_and_deletes_job() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- assert '. ".dify/env.sh"' not in script
- assert script == "printf 'hello world'"
- assert cwd == "~/workspace/abc12ff"
- assert env is None
- assert timeout == 7.5
- return _job_result(
- "remote-job",
- status=JobStatusName.RUNNING,
- done=False,
- output="hello ",
- offset=6,
- truncated=True,
- )
-
- def wait_handler(job_id: str, offset: int, timeout: float) -> JobResult:
- assert job_id == "remote-job"
- assert offset == 6
- assert timeout == 7.5
- return _job_result(
- "remote-job",
- status=JobStatusName.EXITED,
+def test_shell_run_formats_large_non_truncated_output_without_tail_lookup() -> None:
+ large_output = ("head-" + ("x" * 9000) + "-tail").replace("head-x", "head-y", 1)
+ commands = FakeCommands(
+ run_handler=lambda script, cwd, env, timeout: _command_result(
+ "user-job",
+ status="exited",
done=True,
exit_code=0,
- output="world",
- offset=11,
+ output=large_output,
+ offset=len(large_output),
+ output_path="/tmp/large.log",
)
-
- client = FakeShellctlClient(run_handler=run_handler, wait_handler=wait_handler)
- layer = _shell_layer(client=client)
+ )
+ layer, _provider = _layer(commands=commands)
+ tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
- result = await layer.run_remote_script("printf 'hello world'", timeout=7.5)
- assert result.output == "hello world"
- assert result.exit_code == 0
- assert result.truncated is False
+ result = await tools["shell_run"].function_schema.call({"script": "cat large.log"}, None) # pyright: ignore[reportArgumentType]
+ metadata, output = _parse_tagged_observation(result)
+ assert metadata["output_path"] == "/tmp/large.log"
+ assert output.startswith("head-y")
+ assert output.endswith("(check the /tmp/large.log for full output)")
+ assert "-tail" in output
asyncio.run(scenario())
-
- assert [call.job_id for call in client.delete_calls] == ["remote-job"]
- assert layer.runtime_state.job_ids == []
- assert layer.runtime_state.job_offsets == {}
+ assert commands.tail_calls == []
-def test_run_remote_script_deletes_job_even_when_command_exits_non_zero() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- assert script == "exit 17"
- assert cwd == "~/workspace/abc12ff"
- assert env is None
- assert timeout == 3.0
- return _job_result(
- "remote-failed-job",
- status=JobStatusName.EXITED,
- done=True,
- exit_code=17,
- output="failed\n",
- offset=7,
- )
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = _shell_layer(client=client)
+def test_shell_interrupt_succeeds_when_tail_lookup_fails() -> None:
+ commands = FakeCommands(
+ interrupt_handler=lambda job_id, grace_seconds: _command_status(job_id, offset=22),
+ tail_handler=lambda job_id: (_ for _ in ()).throw(RuntimeError("tail unavailable")),
+ )
+ layer, _provider = _layer(commands=commands)
+ tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(
+ session_id="abc12ff",
+ workspace_cwd="~/workspace/abc12ff",
+ job_ids=["user-job"],
+ job_offsets={"user-job": 22},
+ )
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
- result = await layer.run_remote_script("exit 17", timeout=3.0)
- assert result.exit_code == 17
- assert result.output == "failed\n"
+ result = await tools["shell_interrupt"].function_schema.call({"job_id": "user-job"}, None) # pyright: ignore[reportArgumentType]
+ metadata, output = _parse_tagged_observation(result)
+ assert metadata == {
+ "job_id": "user-job",
+ "status": "terminated",
+ "done": True,
+ "exit_code": 130,
+ }
+ assert output == "Job was interrupted."
asyncio.run(scenario())
- assert [call.job_id for call in client.delete_calls] == ["remote-failed-job"]
- assert layer.runtime_state.job_ids == []
- assert layer.runtime_state.job_offsets == {}
+def test_run_remote_script_complete_uses_read_output_before_wait_and_deletes_job() -> None:
+ events: list[str] = []
-def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- assert script == "dify-agent file upload report.txt"
- assert '. ".dify/env.sh"' not in script
- del timeout
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
+ events.append("run")
+ assert script == "printf 'abcdefghi'"
assert cwd == "~/workspace/abc12ff"
- assert env == {
- AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",
- AGENT_STUB_AUTH_JWE_ENV_VAR: "token-for:tenant-1:abc12ff",
- AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive/agent-1",
- }
- return _job_result("remote-upload", status=JobStatusName.EXITED, done=True, exit_code=0, output="{}")
-
- client = FakeShellctlClient(run_handler=run_handler)
- layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- agent_stub_api_base_url="https://agent.example.com/agent-stub",
- agent_stub_token_factory=lambda execution_context, *, session_id: (
- f"token-for:{execution_context.tenant_id}:{session_id}"
- ),
- )
- layer.deps = layer.deps_type(execution_context=_execution_context_layer())
+ assert env is None
+ return _command_result("remote-job", status="running", done=False, output="abc", offset=3, truncated=True)
+
+ def wait_handler(job_id: str, offset: int, timeout: float) -> ShellCommandResult:
+ if timeout == 0.0:
+ events.append("read_output")
+ assert offset == 3
+ return _command_result(job_id, status="running", done=False, output="def", offset=6)
+ events.append("wait")
+ assert offset == 6
+ return _command_result(job_id, status="exited", done=True, exit_code=0, output="ghi", offset=9)
+
+ commands = FakeCommands(run_handler=run_handler, wait_handler=wait_handler)
+ layer, _provider = _layer(commands=commands)
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
- _ = await layer.run_remote_script("dify-agent file upload report.txt", inject_agent_stub_env=True)
+ result = await layer.run_remote_script_complete("printf 'abcdefghi'")
+ assert isinstance(result, CompleteRemoteCommandResult)
+ assert result.output == "abcdefghi"
+ assert result.output_complete is True
+ assert result.incomplete_reason is None
asyncio.run(scenario())
-
- assert [call.job_id for call in client.delete_calls] == ["remote-upload"]
+ assert events == ["run", "read_output", "wait"]
+ assert [call.job_id for call in commands.delete_calls] == ["remote-job"]
-def test_run_remote_script_raises_when_agent_stub_env_is_unavailable() -> None:
- client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env, _timeout: _job_result(
- "unexpected-run",
- status=JobStatusName.EXITED,
- done=True,
- exit_code=0,
- )
- )
- layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- agent_stub_api_base_url="https://agent.example.com/agent-stub",
- agent_stub_token_factory=lambda execution_context, *, session_id: (
- f"token-for:{execution_context.tenant_id}:{session_id}"
+def test_run_remote_script_complete_returns_incomplete_reason_for_output_limit() -> None:
+ commands = FakeCommands(
+ run_handler=lambda script, cwd, env, timeout: _command_result(
+ "remote-job",
+ status="running",
+ done=False,
+ output="hello world",
+ offset=11,
+ truncated=True,
),
+ interrupt_handler=lambda job_id, grace_seconds: _command_status(job_id, status="terminated", offset=11),
)
+ layer, _provider = _layer(commands=commands)
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
- with pytest.raises(RuntimeError, match="Agent Stub environment injection is not available"):
- await layer.run_remote_script("dify-agent file upload report.txt", inject_agent_stub_env=True)
+ result = await layer.run_remote_script_complete("printf 'hello world'", max_output_bytes=5)
+ assert result.output == "hello"
+ assert result.output_complete is False
+ assert result.incomplete_reason == "output_limit"
+ assert result.status == "terminated"
asyncio.run(scenario())
+ assert commands.wait_calls == []
+ assert commands.interrupt_calls == [
+ InterruptCall(job_id="remote-job", grace_seconds=DEFAULT_TERMINATE_GRACE_SECONDS)
+ ]
- assert client.run_calls == []
+def test_run_remote_script_complete_returns_incomplete_reason_for_timeout(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ now = 100.0
-def test_shell_layer_skips_agent_stub_env_without_execution_context_dependency() -> None:
- client = FakeShellctlClient(
- run_handler=lambda _script, _cwd, _env, _timeout: _job_result(
- "user-job",
- status=JobStatusName.EXITED,
+ def fake_monotonic() -> float:
+ return now
+
+ monkeypatch.setattr(shell_layer_module.time, "monotonic", fake_monotonic)
+
+ def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> ShellCommandResult:
+ nonlocal now
+ assert script == "sleep 10"
+ assert cwd == "~/workspace/abc12ff"
+ assert env is None
+ assert timeout == pytest.approx(60.0, rel=0, abs=0.01)
+ now = 161.0
+ return _command_result("remote-job", status="running", done=False, output="hello", offset=5)
+
+ commands = FakeCommands(
+ run_handler=run_handler,
+ interrupt_handler=lambda job_id, grace_seconds: _command_status(
+ job_id,
+ status="terminated",
done=True,
- exit_code=0,
- )
- )
- layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
- agent_stub_api_base_url="https://agent.example.com/agent-stub",
- agent_stub_token_factory=lambda execution_context, *, session_id: (
- f"token-for:{execution_context.tenant_id}:{session_id}"
+ exit_code=130,
+ offset=5,
),
)
- tools = {tool.name: tool for tool in layer.tools}
+ layer, _provider = _layer(commands=commands)
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
- _ = await tools["shell_run"].function_schema.call(
- {"script": "pwd"},
- None, # pyright: ignore[reportArgumentType]
- )
+ result = await layer.run_remote_script_complete("sleep 10", timeout=60.0)
+ assert result.output == "hello"
+ assert result.output_complete is False
+ assert result.incomplete_reason == "timeout"
+ assert result.status == "terminated"
+ assert result.exit_code == 130
asyncio.run(scenario())
-
- assert client.run_calls[0].env is None
+ assert commands.wait_calls == []
+ assert commands.interrupt_calls == [
+ InterruptCall(job_id="remote-job", grace_seconds=DEFAULT_TERMINATE_GRACE_SECONDS)
+ ]
+ assert [call.job_id for call in commands.delete_calls] == ["remote-job"]
-def test_shell_layer_tools_reject_untracked_job_ids_without_shellctl_calls() -> None:
- client = FakeShellctlClient()
- layer = _shell_layer(client=client)
+def test_shell_layer_rejects_untracked_job_ids_without_provider_calls() -> None:
+ commands = FakeCommands()
+ layer, _provider = _layer(commands=commands)
tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
async with layer.resource_context():
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
- layer._shell_handle = ShellctlHandle(
- client=client, workspace_cwd="~/workspace/abc12ff", session_id="abc12ff"
- )
-
- wait_result = await tools["shell_wait"].function_schema.call(
- {"job_id": "missing-job"},
- None, # pyright: ignore[reportArgumentType]
- )
+ wait_result = await tools["shell_wait"].function_schema.call({"job_id": "missing"}, None) # pyright: ignore[reportArgumentType]
input_result = await tools["shell_input"].function_schema.call(
- {"job_id": "missing-job", "text": "hello"},
- None, # pyright: ignore[reportArgumentType]
- )
- interrupt_result = await tools["shell_interrupt"].function_schema.call(
- {"job_id": "missing-job"},
+ {"job_id": "missing", "text": "hello"},
None, # pyright: ignore[reportArgumentType]
)
-
- _assert_error_observation(wait_result, job_id="missing-job")
- _assert_error_observation(input_result, job_id="missing-job")
- _assert_error_observation(interrupt_result, job_id="missing-job")
+ interrupt_result = await tools["shell_interrupt"].function_schema.call({"job_id": "missing"}, None) # pyright: ignore[reportArgumentType]
+ _assert_error_observation(wait_result, job_id="missing")
+ _assert_error_observation(input_result, job_id="missing")
+ _assert_error_observation(interrupt_result, job_id="missing")
asyncio.run(scenario())
-
- assert client.wait_calls == []
- assert client.input_calls == []
- assert client.terminate_calls == []
+ assert commands.wait_calls == []
+ assert commands.input_calls == []
+ assert commands.interrupt_calls == []
def test_shell_layer_hooks_and_tools_fail_clearly_outside_active_resource_context() -> None:
- client = FakeShellctlClient()
- layer = _shell_layer(client=client)
- layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
+ layer, _provider = _layer(commands=FakeCommands())
tools = {tool.name: tool for tool in layer.tools}
+ layer.runtime_state = DifyShellRuntimeState(session_id="abc12ff", workspace_cwd="~/workspace/abc12ff")
async def scenario() -> None:
- run_result = await tools["shell_run"].function_schema.call(
- {"script": "pwd"},
- None, # pyright: ignore[reportArgumentType]
- )
- _assert_error_observation(run_result, includes="shell handle")
+ result = await tools["shell_run"].function_schema.call({"script": "pwd"}, None) # pyright: ignore[reportArgumentType]
+ _assert_error_observation(result, includes="shell resource")
asyncio.run(scenario())
- assert client.run_calls == []
-
-def test_shell_runtime_state_rejects_unsafe_resumed_workspace_identity() -> None:
- with pytest.raises(ValueError, match="session_id must be 7 or 16 lowercase hex characters"):
+def test_shell_runtime_state_validates_workspace_identity_and_offset_keys() -> None:
+ with pytest.raises(ValueError, match="5\\+2 lowercase hex format"):
_ = DifyShellRuntimeState.model_validate(
{
"session_id": "../../tmp",
@@ -944,8 +682,6 @@ def test_shell_runtime_state_rejects_unsafe_resumed_workspace_identity() -> None
}
)
-
-def test_shell_runtime_state_treats_job_ids_as_opaque_strings_and_rejects_unknown_offset_keys() -> None:
state = DifyShellRuntimeState.model_validate(
{
"session_id": "abc12ff",
@@ -954,10 +690,7 @@ def test_shell_runtime_state_treats_job_ids_as_opaque_strings_and_rejects_unknow
"job_offsets": {'job"bad with spaces': 0},
}
)
-
assert state.job_ids == ['job"bad with spaces']
- assert state.job_offsets == {'job"bad with spaces': 0}
-
with pytest.raises(ValueError, match="unknown job ids"):
_ = DifyShellRuntimeState.model_validate(
{
diff --git a/dify-agent/tests/local/dify_agent/layers/shell/test_output_text.py b/dify-agent/tests/local/dify_agent/layers/shell/test_output_text.py
new file mode 100644
index 00000000000..15e195d6fcd
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/layers/shell/test_output_text.py
@@ -0,0 +1,77 @@
+from dify_agent.layers.shell.output_text import normalized_output_text, utf8_prefix, utf8_suffix
+
+
+def test_normalized_output_text_includes_marker_and_log_guidance() -> None:
+ assert normalized_output_text(
+ "head",
+ tail="tail",
+ output_path="/tmp/output.log",
+ max_output_size_bytes=16,
+ ) == (
+ "head\n"
+ "... (truncated in middle because the max output size is limited to 16 bytes) ...\n"
+ "tail\n"
+ "(check the /tmp/output.log for full output)"
+ )
+
+
+def test_normalized_output_text_avoids_duplicate_tail_for_short_output() -> None:
+ assert (
+ normalized_output_text(
+ "short output",
+ tail="short output",
+ output_path="/tmp/output.log",
+ max_output_size_bytes=16,
+ )
+ == "short output"
+ )
+
+
+def test_normalized_output_text_can_force_middle_truncation_when_head_matches_tail() -> None:
+ assert normalized_output_text(
+ "repeat",
+ tail="repeat",
+ output_path="/tmp/output.log",
+ max_output_size_bytes=16,
+ truncated_in_middle=True,
+ ) == (
+ "repeat\n"
+ "... (truncated in middle because the max output size is limited to 16 bytes) ...\n"
+ "repeat\n"
+ "(check the /tmp/output.log for full output)"
+ )
+
+
+def test_utf8_helpers_do_not_split_multibyte_characters() -> None:
+ text = "A🙂B"
+
+ assert utf8_prefix(text, 1) == "A"
+ assert utf8_prefix(text, 2) == "A"
+ assert utf8_prefix(text, 5) == "A🙂"
+ assert utf8_suffix(text, 1) == "B"
+ assert utf8_suffix(text, 2) == "B"
+ assert utf8_suffix(text, 5) == "🙂B"
+
+
+def test_normalized_output_text_omits_log_guidance_without_output_path() -> None:
+ assert normalized_output_text(
+ "head",
+ tail="tail",
+ output_path=None,
+ max_output_size_bytes=16,
+ ) == ("head\n... (truncated in middle because the max output size is limited to 16 bytes) ...\ntail")
+
+
+def test_normalized_output_text_can_use_custom_truncation_message() -> None:
+ assert normalized_output_text(
+ "head",
+ tail="tail",
+ output_path="/tmp/output.log",
+ max_output_size_bytes=16,
+ truncation_message="command timed out before full output was captured",
+ ) == (
+ "head\n"
+ "... (command timed out before full output was captured) ...\n"
+ "tail\n"
+ "(check the /tmp/output.log for full output)"
+ )
diff --git a/dify-agent/tests/local/dify_agent/protocol/test_sandbox_locator.py b/dify-agent/tests/local/dify_agent/protocol/test_sandbox_locator.py
index a717c6b899b..6de05187708 100644
--- a/dify-agent/tests/local/dify_agent/protocol/test_sandbox_locator.py
+++ b/dify-agent/tests/local/dify_agent/protocol/test_sandbox_locator.py
@@ -5,6 +5,7 @@ from agenton.compositor import CompositorSessionSnapshot
from agenton.compositor.schemas import LayerSessionSnapshot
from agenton.layers.base import LifecycleState
from agenton_collections.layers.plain import PromptLayerConfig
+from dify_agent.layers.dify_core_tools import DIFY_CORE_TOOLS_LAYER_TYPE_ID
from dify_agent.layers.dify_plugin import DIFY_PLUGIN_LLM_LAYER_TYPE_ID
from dify_agent.layers.execution_context import DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID, DifyExecutionContextLayerConfig
from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
@@ -167,3 +168,11 @@ def test_build_sandbox_locator_from_layer_specs_rejects_sensitive_runtime_specs(
layer_specs=[RuntimeLayerSpec(name="llm", type=DIFY_PLUGIN_LLM_LAYER_TYPE_ID)],
session_snapshot=CompositorSessionSnapshot(layers=[]),
)
+
+
+def test_build_sandbox_locator_from_layer_specs_rejects_sensitive_core_tool_runtime_specs() -> None:
+ with pytest.raises(ValueError, match="sensitive"):
+ build_sandbox_locator_from_layer_specs(
+ layer_specs=[RuntimeLayerSpec(name="core_tools", type=DIFY_CORE_TOOLS_LAYER_TYPE_ID)],
+ session_snapshot=CompositorSessionSnapshot(layers=[]),
+ )
diff --git a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py
index 2482c635d74..30ad414e45a 100644
--- a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py
+++ b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py
@@ -1,41 +1,119 @@
+import sys
+import types
from typing import cast
import pytest
+from pydantic import BaseModel
+
+
+if "pydantic_settings" not in sys.modules:
+ pydantic_settings = types.ModuleType("pydantic_settings")
+ pydantic_settings.BaseSettings = BaseModel
+ pydantic_settings.SettingsConfigDict = dict
+ sys.modules["pydantic_settings"] = pydantic_settings
+
+if "graphon.model_runtime.entities.llm_entities" not in sys.modules:
+ graphon_module = types.ModuleType("graphon")
+ model_runtime_module = types.ModuleType("graphon.model_runtime")
+ entities_module = types.ModuleType("graphon.model_runtime.entities")
+ llm_entities_module = types.ModuleType("graphon.model_runtime.entities.llm_entities")
+ message_entities_module = types.ModuleType("graphon.model_runtime.entities.message_entities")
+
+ llm_entities_module.LLMResultChunk = type("LLMResultChunk", (), {})
+ llm_entities_module.LLMUsage = type("LLMUsage", (), {})
+
+ for name in (
+ "AssistantPromptMessage",
+ "AudioPromptMessageContent",
+ "DocumentPromptMessageContent",
+ "ImagePromptMessageContent",
+ "PromptMessage",
+ "PromptMessageContentUnionTypes",
+ "PromptMessageTool",
+ "SystemPromptMessage",
+ "TextPromptMessageContent",
+ "ToolPromptMessage",
+ "UserPromptMessage",
+ "VideoPromptMessageContent",
+ ):
+ setattr(message_entities_module, name, type(name, (), {}))
+
+ sys.modules["graphon"] = graphon_module
+ sys.modules["graphon.model_runtime"] = model_runtime_module
+ sys.modules["graphon.model_runtime.entities"] = entities_module
+ sys.modules["graphon.model_runtime.entities.llm_entities"] = llm_entities_module
+ sys.modules["graphon.model_runtime.entities.message_entities"] = message_entities_module
+
+ graphon_module.model_runtime = model_runtime_module
+ model_runtime_module.entities = entities_module
+ entities_module.llm_entities = llm_entities_module
+ entities_module.message_entities = message_entities_module
+
+if "jsonschema" not in sys.modules:
+ jsonschema_module = types.ModuleType("jsonschema")
+ jsonschema_exceptions_module = types.ModuleType("jsonschema.exceptions")
+ jsonschema_protocols_module = types.ModuleType("jsonschema.protocols")
+ jsonschema_validators_module = types.ModuleType("jsonschema.validators")
+
+ class _SchemaError(Exception):
+ pass
+
+ class _ValidationError(Exception):
+ path: tuple[object, ...] = ()
+
+ class _Validator:
+ @staticmethod
+ def check_schema(schema):
+ return None
+
+ def __init__(self, schema):
+ self.schema = schema
+
+ def iter_errors(self, value):
+ return iter(())
+
+ def _validator_for(schema):
+ return _Validator
+
+ jsonschema_module.SchemaError = _SchemaError
+ jsonschema_exceptions_module.ValidationError = _ValidationError
+ jsonschema_protocols_module.Validator = _Validator
+ jsonschema_validators_module.validator_for = _validator_for
+
+ sys.modules["jsonschema"] = jsonschema_module
+ sys.modules["jsonschema.exceptions"] = jsonschema_exceptions_module
+ sys.modules["jsonschema.protocols"] = jsonschema_protocols_module
+ sys.modules["jsonschema.validators"] = jsonschema_validators_module
import dify_agent.runtime.compositor_factory as compositor_factory_module
from dify_agent.adapters.shell.config import ShellAdapterSettings
-from dify_agent.adapters.shell.protocols import ShellProvisionProtocol
-from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodec
+from dify_agent.adapters.shell.protocols import ShellProviderProtocol
+from dify_agent.layers.dify_core_tools import DIFY_CORE_TOOLS_LAYER_TYPE_ID, DifyCoreToolsLayerConfig
+from dify_agent.layers.dify_core_tools.layer import DifyCoreToolsLayer
from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.shell.layer import DifyShellLayer
from dify_agent.runtime.compositor_factory import create_default_layer_providers
-class FakeProvisioner:
- """No-op provisioner for tests that never actually provision a workspace."""
+class FakeProvider:
+ """No-op provider for tests that never actually open a shell resource."""
- async def provision(self) -> object:
- raise AssertionError("provision should not be called by these tests")
-
- async def reattach(self, descriptor: object) -> object:
- raise AssertionError("reattach should not be called by these tests")
-
- async def destroy(self, handle: object) -> None:
- raise AssertionError("destroy should not be called by these tests")
+ async def create(self) -> object:
+ raise AssertionError("create should not be called by these tests")
def test_default_layer_providers_register_shell_layer_with_configured_token_factory(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured_settings: list[ShellAdapterSettings] = []
- fake_provisioner = FakeProvisioner()
+ fake_provider = FakeProvider()
- def fake_create_shell_provisioner(settings: ShellAdapterSettings) -> ShellProvisionProtocol:
+ def fake_create_shell_provider(settings: ShellAdapterSettings) -> ShellProviderProtocol:
captured_settings.append(settings)
- return cast(ShellProvisionProtocol, fake_provisioner)
+ return cast(ShellProviderProtocol, fake_provider)
- monkeypatch.setattr(compositor_factory_module, "create_shell_provisioner", fake_create_shell_provisioner)
+ monkeypatch.setattr(compositor_factory_module, "create_shell_provider", fake_create_shell_provider)
providers = create_default_layer_providers(
shellctl_entrypoint="http://shellctl.example",
@@ -45,7 +123,7 @@ def test_default_layer_providers_register_shell_layer_with_configured_token_fact
shell_layer = shell_provider.create_layer(DifyShellLayerConfig())
assert isinstance(shell_layer, DifyShellLayer)
- assert shell_layer.shell_provisioner is fake_provisioner
+ assert shell_layer.shell_provider is fake_provider
assert len(captured_settings) == 1
assert captured_settings[0].shellctl_entrypoint == "http://shellctl.example"
assert captured_settings[0].shellctl_auth_token == "shell-secret"
@@ -56,11 +134,11 @@ def test_default_layer_providers_keep_empty_shellctl_token_by_default(
) -> None:
captured_settings: list[ShellAdapterSettings] = []
- def fake_create_shell_provisioner(settings: ShellAdapterSettings) -> ShellProvisionProtocol:
+ def fake_create_shell_provider(settings: ShellAdapterSettings) -> ShellProviderProtocol:
captured_settings.append(settings)
- return cast(ShellProvisionProtocol, FakeProvisioner())
+ return cast(ShellProviderProtocol, FakeProvider())
- monkeypatch.setattr(compositor_factory_module, "create_shell_provisioner", fake_create_shell_provisioner)
+ monkeypatch.setattr(compositor_factory_module, "create_shell_provider", fake_create_shell_provider)
providers = create_default_layer_providers(shellctl_entrypoint="http://shellctl.example")
shell_provider = next(provider for provider in providers if provider.type_id == DIFY_SHELL_LAYER_TYPE_ID)
@@ -70,15 +148,17 @@ def test_default_layer_providers_keep_empty_shellctl_token_by_default(
assert captured_settings[0].shellctl_auth_token is None
-def test_shell_provider_rejects_blank_settings_entrypoint_only_when_shell_layer_is_created() -> None:
- providers = create_default_layer_providers(shellctl_entrypoint=" ")
- shell_provider = next(provider for provider in providers if provider.type_id == DIFY_SHELL_LAYER_TYPE_ID)
-
+def test_shell_provider_rejects_blank_settings_entrypoint_when_default_providers_are_built() -> None:
with pytest.raises(ValueError, match="DIFY_AGENT_SHELLCTL_ENTRYPOINT"):
- _ = shell_provider.create_layer(DifyShellLayerConfig())
+ _ = create_default_layer_providers(shellctl_entrypoint=" ")
def test_default_layer_providers_build_agent_stub_token_factory_from_agent_stub_codec() -> None:
+ AgentStubTokenCodec = pytest.importorskip(
+ "dify_agent.agent_stub.server.tokens.agent_stub",
+ reason="jwcrypto is not available in this local test environment",
+ ).AgentStubTokenCodec
+
codec = AgentStubTokenCodec.from_server_secret("MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE")
providers = create_default_layer_providers(
@@ -102,3 +182,16 @@ def test_default_layer_providers_build_agent_stub_token_factory_from_agent_stub_
assert isinstance(token, str)
assert token
+
+
+def test_default_layer_providers_register_core_tools_layer() -> None:
+ providers = create_default_layer_providers(inner_api_url="http://dify-api", inner_api_key="inner-secret")
+
+ core_provider = next(provider for provider in providers if provider.type_id == DIFY_CORE_TOOLS_LAYER_TYPE_ID)
+ layer = core_provider.create_layer(DifyCoreToolsLayerConfig())
+
+ assert isinstance(layer, DifyCoreToolsLayer)
+ assert layer.type_id == DIFY_CORE_TOOLS_LAYER_TYPE_ID
+ assert layer.inner_api_url == "http://dify-api"
+ assert layer.inner_api_key == "inner-secret"
+ assert layer.config == DifyCoreToolsLayerConfig()
diff --git a/dify-agent/tests/local/dify_agent/runtime/test_runner.py b/dify-agent/tests/local/dify_agent/runtime/test_runner.py
index 6730624fdca..af95aaf535c 100644
--- a/dify-agent/tests/local/dify_agent/runtime/test_runner.py
+++ b/dify-agent/tests/local/dify_agent/runtime/test_runner.py
@@ -29,7 +29,7 @@ from agenton_collections.layers.plain import PromptLayerConfig, ToolsLayer
from dify_agent.layers.ask_human import DIFY_ASK_HUMAN_LAYER_TYPE_ID, DifyAskHumanLayerConfig
from dify_agent.layers.execution_context import DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID, DifyExecutionContextLayerConfig
from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
-from dify_agent.adapters.shell.shellctl import ShellctlProvisioner
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
from dify_agent.layers.shell.layer import DifyShellLayer
from dify_agent.layers.dify_plugin.configs import (
DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID,
@@ -66,10 +66,12 @@ class StaticToolsTestLayer(ToolsLayer):
class FakeRunnerShellctlClient:
run_calls: list[tuple[str, str | None, Mapping[str, str] | None, float]]
+ delete_calls: list[tuple[str, bool, float | None]]
closed: bool
def __init__(self) -> None:
self.run_calls = []
+ self.delete_calls = []
self.closed = False
async def run(
@@ -114,8 +116,8 @@ class FakeRunnerShellctlClient:
force: bool = False,
grace_seconds: float | None = None,
) -> DeleteJobResponse:
- del job_id, force, grace_seconds
- raise AssertionError("delete() should not be called in this test")
+ self.delete_calls.append((job_id, force, grace_seconds))
+ return DeleteJobResponse(job_id=job_id)
def _request(
@@ -1347,7 +1349,11 @@ def test_runner_rejects_duplicate_tool_names_between_shell_and_other_layers(
layer_type=DifyShellLayer,
create=lambda config: DifyShellLayer.from_config_with_settings(
DifyShellLayerConfig.model_validate(config),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: shell_client),
+ shell_provider=ShellctlProvider(
+ entrypoint="http://shellctl",
+ token="",
+ client_factory=lambda: shell_client,
+ ),
),
)
layer_providers = tuple(
@@ -1426,6 +1432,7 @@ def test_runner_rejects_duplicate_tool_names_between_shell_and_other_layers(
asyncio.run(scenario())
assert create_agent_called is False
+ assert shell_client.delete_calls == [("mkdir-job", True, None)]
assert shell_client.closed is True
assert [event.type for event in sink.events["run-shell-duplicate-tools"]] == ["run_started", "run_failed"]
assert sink.statuses["run-shell-duplicate-tools"] == "failed"
@@ -2342,7 +2349,7 @@ def test_runner_treats_missing_shell_entrypoint_as_validation_error() -> None:
async def scenario() -> None:
async with httpx.AsyncClient() as client:
- with pytest.raises(AgentRunValidationError, match="non-null shell provisioner"):
+ with pytest.raises(AgentRunValidationError, match="non-null shell provider"):
await AgentRunRunner(
sink=sink,
request=request,
diff --git a/dify-agent/tests/local/dify_agent/server/test_app.py b/dify-agent/tests/local/dify_agent/server/test_app.py
index ea83ec30080..c02cdf1cafd 100644
--- a/dify-agent/tests/local/dify_agent/server/test_app.py
+++ b/dify-agent/tests/local/dify_agent/server/test_app.py
@@ -8,7 +8,7 @@ import httpx
import pytest
from fastapi.testclient import TestClient
-from dify_agent.adapters.shell.shellctl import ShellctlProvisioner
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
import dify_agent.server.app as app_module
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
@@ -246,7 +246,7 @@ def test_create_app_creates_scheduler_and_closes_after_shutdown(monkeypatch: pyt
assert isinstance(knowledge_layer, DifyKnowledgeBaseLayer)
assert knowledge_layer.inner_api_url == "http://dify-api"
assert knowledge_layer.inner_api_key == "inner-secret"
- assert isinstance(shell_layer.shell_provisioner, ShellctlProvisioner)
+ assert isinstance(shell_layer.shell_provider, ShellctlProvider)
assert shell_layer.agent_stub_api_base_url == "https://agent.example.com/agent-stub"
http_client = scheduler.plugin_daemon_http_client
assert http_client is fake_http_client
diff --git a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py
index 72d70940a83..eae7f945bfb 100644
--- a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py
+++ b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py
@@ -5,41 +5,52 @@ import base64
import json
from collections.abc import Callable, Mapping
from dataclasses import dataclass
+from typing import Literal
import pytest
from agenton.compositor import CompositorSessionSnapshot, LayerProvider
from agenton.compositor.schemas import LayerSessionSnapshot
from agenton.layers.base import LifecycleState
+from dify_agent.adapters.shell.shellctl import ShellctlProvider
from dify_agent.agent_stub.server.shell_agent_stub_env import (
+ AGENT_STUB_API_BASE_URL_ENV_VAR,
AGENT_STUB_AUTH_JWE_ENV_VAR,
AGENT_STUB_DRIVE_BASE_ENV_VAR,
- AGENT_STUB_API_BASE_URL_ENV_VAR,
)
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
from dify_agent.layers.shell import DifyShellLayerConfig
-from dify_agent.layers.shell.layer import DifyShellLayer
-from dify_agent.adapters.shell.shellctl import ShellctlProvisioner
+from dify_agent.layers.shell.layer import CompleteRemoteCommandResult, DifyShellLayer
from dify_agent.protocol import (
CreateRunRequest,
RunComposition,
RunLayerSpec,
- SandboxLocator,
SandboxListRequest,
+ SandboxLocator,
SandboxReadRequest,
SandboxUploadRequest,
build_sandbox_locator_from_run_request,
)
-from dify_agent.server.routes.sandbox_files import create_sandbox_files_router
from dify_agent.server.sandbox_files import (
SandboxFileError,
SandboxFileService,
_OUTPUT_BEGIN,
_OUTPUT_END,
+ _decode_sandbox_payload,
+ _shell_result_details,
)
-from fastapi import FastAPI
-from fastapi.testclient import TestClient
-from shell_session_manager.shellctl.shared import JobResult, JobStatusName
+
+
+@dataclass(slots=True)
+class _Job:
+ job_id: str
+ status: str = "exited"
+ done: bool = True
+ exit_code: int | None = 0
+ output: str = ""
+ offset: int = 0
+ truncated: bool = False
+ output_path: str | None = "/tmp/sandbox-job.out"
@dataclass(slots=True)
@@ -51,42 +62,31 @@ class RunCall:
class FakeShellctlClient:
- def __init__(
- self,
- *,
- run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], JobResult],
- ) -> None:
+ def __init__(self, *, run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], _Job]) -> None:
self.run_handler = run_handler
self.run_calls: list[RunCall] = []
self.delete_calls: list[str] = []
async def run(
- self,
- script: str,
- *,
- cwd: str | None = None,
- env: Mapping[str, str] | None = None,
- timeout: float = 10.0,
- ) -> JobResult:
+ self, script: str, *, cwd: str | None = None, env: Mapping[str, str] | None = None, timeout: float = 10.0
+ ):
self.run_calls.append(RunCall(script=script, cwd=cwd, env=env, timeout=timeout))
return self.run_handler(script, cwd, env, timeout)
- async def wait(self, job_id: str, *, offset: int, timeout: float = 10.0) -> JobResult:
- return self.run_handler("", None, None, timeout)
+ async def wait(self, job_id: str, *, offset: int, timeout: float = 10.0):
+ raise AssertionError(f"Unexpected wait() call for {job_id} offset={offset} timeout={timeout}")
- async def input(self, job_id: str, text: str, *, offset: int, timeout: float = 10.0) -> JobResult:
+ async def input(self, job_id: str, text: str, *, offset: int, timeout: float = 10.0):
raise AssertionError(f"Unexpected input() call for {job_id} text={text!r}")
- async def terminate(self, job_id: str, grace_seconds: float = 2.0):
+ async def tail(self, job_id: str):
+ raise AssertionError(f"Unexpected tail() call for {job_id}")
+
+ async def terminate(self, job_id: str, grace_seconds: float = 10.0):
raise AssertionError(f"Unexpected terminate() call for {job_id} grace={grace_seconds}")
- async def delete(
- self,
- job_id: str,
- *,
- force: bool = False,
- ) -> object:
- del force
+ async def delete(self, job_id: str, *, force: bool = False, grace_seconds: float | None = None):
+ del force, grace_seconds
self.delete_calls.append(job_id)
return None
@@ -100,32 +100,27 @@ def _wrap(payload: dict[str, object], *, pty_wrap: int = 0, noise: bool = False)
blob = "\n".join(blob[index : index + pty_wrap] for index in range(0, len(blob), pty_wrap))
framed = f"{_OUTPUT_BEGIN}{blob}{_OUTPUT_END}\n"
if noise:
- framed = f"user@host:~/workspace/abc12ff$ python3 - ...\r\n{framed}user@host:~/workspace/abc12ff$ \r\n"
+ framed = f"user@host$ python3 - ...\r\n{framed}user@host$ \r\n"
return framed
-def _job_result(*, output: dict[str, object] | str, job_id: str = "sandbox-job") -> JobResult:
- return JobResult(
+def _complete_result(
+ *,
+ output: str,
+ exit_code: int | None = 0,
+ output_complete: bool = True,
+ incomplete_reason: Literal["output_limit", "timeout"] | None = None,
+ job_id: str = "sandbox-job",
+) -> CompleteRemoteCommandResult:
+ return CompleteRemoteCommandResult(
job_id=job_id,
- status=JobStatusName.EXITED,
- done=True,
- exit_code=0,
- output=_wrap(output) if isinstance(output, dict) else output,
- offset=0,
- truncated=False,
- output_path="/tmp/sandbox-job.out",
- )
-
-
-def _failed_job_result(*, output: str, exit_code: int, job_id: str = "sandbox-job") -> JobResult:
- return JobResult(
- job_id=job_id,
- status=JobStatusName.EXITED,
+ status="exited",
done=True,
exit_code=exit_code,
output=output,
- offset=0,
- truncated=False,
+ output_complete=output_complete,
+ incomplete_reason=incomplete_reason,
+ offset=len(output),
output_path="/tmp/sandbox-job.out",
)
@@ -153,16 +148,14 @@ def _locator() -> SandboxLocator:
name="shell",
type="dify.shell",
deps={"execution_context": "execution_context"},
- config=DifyShellLayerConfig(),
+ config=DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
),
]
),
session_snapshot=CompositorSessionSnapshot(
layers=[
LayerSessionSnapshot(
- name="execution_context",
- lifecycle_state=LifecycleState.SUSPENDED,
- runtime_state={},
+ name="execution_context", lifecycle_state=LifecycleState.SUSPENDED, runtime_state={}
),
LayerSessionSnapshot(
name="shell",
@@ -176,7 +169,7 @@ def _locator() -> SandboxLocator:
def _service(
- run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], JobResult],
+ run_handler: Callable[[str, str | None, Mapping[str, str] | None, float], _Job],
) -> tuple[SandboxFileService, FakeShellctlClient]:
client = FakeShellctlClient(run_handler=run_handler)
execution_context_provider = LayerProvider.from_factory(
@@ -191,7 +184,11 @@ def _service(
layer_type=DifyShellLayer,
create=lambda config: DifyShellLayer.from_config_with_settings(
DifyShellLayerConfig.model_validate(config),
- shell_provisioner=ShellctlProvisioner(client_factory=lambda: client),
+ shell_provider=ShellctlProvider(
+ entrypoint="http://shellctl",
+ token="",
+ client_factory=lambda: client,
+ ),
agent_stub_api_base_url="https://agent.example.com/agent-stub",
agent_stub_token_factory=lambda execution_context, *, session_id: (
f"token-for:{execution_context.tenant_id}:{session_id}"
@@ -203,12 +200,15 @@ def _service(
def test_list_files_runs_fixed_script_and_parses_response() -> None:
service, client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "path": ".",
- "entries": [{"name": "notes.txt", "type": "file", "size": 5, "mtime": 1}],
- "truncated": False,
- }
+ lambda script, cwd, env, timeout: _Job(
+ job_id="sandbox-job",
+ output=_wrap(
+ {
+ "path": ".",
+ "entries": [{"name": "notes.txt", "type": "file", "size": 5, "mtime": 1}],
+ "truncated": False,
+ }
+ ),
)
)
@@ -223,228 +223,72 @@ def test_list_files_runs_fixed_script_and_parses_response() -> None:
@pytest.mark.parametrize("bad_path", ["/etc/passwd", "~/secret-dir", "bad\x00path"])
def test_list_files_rejects_invalid_paths_before_shell_execution(bad_path: str) -> None:
- service, client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={"path": ".", "entries": [], "truncated": False},
- )
- )
+ service, client = _service(lambda script, cwd, env, timeout: _Job(job_id="sandbox-job", output="unused"))
- with pytest.raises(SandboxFileError) as exc_info:
+ with pytest.raises(SandboxFileError, match="path"):
asyncio.run(service.list_files(SandboxListRequest(locator=_locator(), path=bad_path)))
- assert exc_info.value.code == "invalid_sandbox_path"
assert client.run_calls == []
-def test_decode_tolerates_pty_wrapped_base64_and_shell_noise() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output=_wrap(
- {
- "path": "note.txt",
- "size": 40,
- "truncated": False,
- "binary": False,
- "text": "hello from sandbox\n" * 4,
- },
- pty_wrap=12,
- noise=True,
- )
+def test_decode_payload_reports_incomplete_capture_when_frame_is_missing() -> None:
+ with pytest.raises(SandboxFileError, match="incomplete before framed payload was captured"):
+ _decode_sandbox_payload(
+ _complete_result(output="partial", output_complete=False, incomplete_reason="output_limit")
)
- )
-
- result = asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="note.txt")))
- assert result.text == "hello from sandbox\n" * 4
+def test_decode_payload_reports_incomplete_capture_when_frame_is_corrupt() -> None:
+ broken = f"{_OUTPUT_BEGIN}%%%%{_OUTPUT_END}"
+ with pytest.raises(SandboxFileError, match="incomplete while decoding framed payload"):
+ _decode_sandbox_payload(_complete_result(output=broken, output_complete=False, incomplete_reason="timeout"))
-def test_read_file_maps_script_error_codes() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={"error": "sandbox_path_not_found", "message": "path not found in sandbox"}
- )
- )
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="missing.txt")))
-
- assert exc_info.value.code == "sandbox_path_not_found"
- assert exc_info.value.status_code == 404
-
-
[email protected]("bad_path", ["", "/etc/passwd", "~/secret.txt", "bad\x00path"])
-def test_read_file_rejects_invalid_paths_before_shell_execution(bad_path: str) -> None:
+def test_upload_injects_agent_stub_env_and_returns_mapping() -> None:
service, client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "path": "should-not-run",
- "size": 1,
- "truncated": False,
- "binary": False,
- "text": "x",
- }
- )
- )
-
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path=bad_path)))
-
- assert exc_info.value.code == "invalid_sandbox_path"
- assert client.run_calls == []
-
-
-def test_read_file_returns_binary_payload_without_text() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "path": "blob.bin",
- "size": 64,
- "truncated": False,
- "binary": True,
- "text": None,
- }
- )
- )
-
- result = asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="blob.bin")))
-
- assert result.binary is True
- assert result.text is None
- assert result.truncated is False
-
-
-def test_read_file_preserves_truncated_flag_for_large_text() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "path": "large.txt",
- "size": 1024,
- "truncated": True,
- "binary": False,
- "text": "partial preview",
- }
+ lambda script, cwd, env, timeout: _Job(
+ job_id="sandbox-job",
+ output=_wrap(
+ {
+ "path": "report.txt",
+ "file": {"transfer_method": "tool_file", "reference": "file-ref"},
+ },
+ noise=True,
+ ),
)
)
- result = asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="large.txt")))
-
- assert result.binary is False
- assert result.text == "partial preview"
- assert result.truncated is True
-
-
-def test_upload_file_injects_agent_stub_env_and_returns_mapping() -> None:
- def run_handler(script: str, cwd: str | None, env: Mapping[str, str] | None, timeout: float) -> JobResult:
- assert cwd == "~/workspace/abc12ff"
- assert timeout == 30.0
- assert env == {
- AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",
- AGENT_STUB_AUTH_JWE_ENV_VAR: "token-for:tenant-1:abc12ff",
- AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive",
- }
- assert 'dify-agent", "file", "upload"' in script
- return _job_result(
- output={
- "path": "report.txt",
- "file": {"transfer_method": "tool_file", "reference": "dify-file-ref:file-1"},
- },
- job_id="upload-job",
- )
-
- service, client = _service(run_handler)
-
result = asyncio.run(service.upload_file(SandboxUploadRequest(locator=_locator(), path="report.txt")))
- assert result.file.reference == "dify-file-ref:file-1"
- assert client.delete_calls == ["upload-job"]
-
-
-def test_upload_file_maps_agent_stub_upload_failed_payload() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "error": "agent_stub_upload_failed",
- "message": "upload returned invalid JSON",
- },
- job_id="upload-failed-job",
- )
- )
-
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.upload_file(SandboxUploadRequest(locator=_locator(), path="report.txt")))
-
- assert exc_info.value.code == "agent_stub_upload_failed"
- assert exc_info.value.status_code == 502
-
-
-def test_read_file_maps_non_zero_command_exit_to_sandbox_command_failed() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _failed_job_result(
- output="python traceback or stderr tail",
- exit_code=17,
- )
- )
-
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="note.txt")))
-
- assert exc_info.value.code == "sandbox_command_failed"
- assert exc_info.value.status_code == 502
+ assert result.file.transfer_method == "tool_file"
+ assert result.file.reference == "file-ref"
+ assert client.run_calls[0].cwd == "~/workspace/abc12ff"
+ assert client.run_calls[0].env == {
+ AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",
+ AGENT_STUB_AUTH_JWE_ENV_VAR: "token-for:tenant-1:abc12ff",
+ AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive/agent-1",
+ }
-def test_upload_file_maps_missing_framed_payload_to_sandbox_command_failed() -> None:
- service, _client = _service(
- lambda script, cwd, env, timeout: _job_result(output="plain output without sentinel framing")
+def test_shell_result_details_include_output_metadata_and_tail() -> None:
+ details = _shell_result_details(
+ _complete_result(output="hello", output_complete=False, incomplete_reason="output_limit")
)
+ assert "output_complete=False" in details
+ assert "incomplete_reason=output_limit" in details
+ assert "output_path=/tmp/sandbox-job.out" in details
+ assert details.endswith("hello")
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.upload_file(SandboxUploadRequest(locator=_locator(), path="report.txt")))
- assert exc_info.value.code == "sandbox_command_failed"
- assert exc_info.value.status_code == 502
-
-
[email protected]("bad_path", ["", "/etc/passwd", "~/secret.txt", "bad\x00path"])
-def test_upload_file_rejects_invalid_paths_before_shell_execution(bad_path: str) -> None:
+def test_read_file_uses_complete_mode_and_parses_response() -> None:
service, client = _service(
- lambda script, cwd, env, timeout: _job_result(
- output={
- "path": "should-not-run",
- "file": {"transfer_method": "tool_file", "reference": "dify-file-ref:file-1"},
- }
+ lambda script, cwd, env, timeout: _Job(
+ job_id="sandbox-job",
+ output=_wrap({"path": "notes.txt", "size": 5, "truncated": False, "binary": False, "text": "hello"}),
)
)
- with pytest.raises(SandboxFileError) as exc_info:
- asyncio.run(service.upload_file(SandboxUploadRequest(locator=_locator(), path=bad_path)))
-
- assert exc_info.value.code == "invalid_sandbox_path"
- assert client.run_calls == []
-
-
-def _client(service: SandboxFileService | None) -> TestClient:
- app = FastAPI()
- app.include_router(create_sandbox_files_router(lambda: service))
- return TestClient(app)
-
-
-def test_router_list_ok() -> None:
- service, _client_instance = _service(
- lambda script, cwd, env, timeout: _job_result(output={"path": ".", "entries": [], "truncated": False})
- )
-
- response = _client(service).post(
- "/sandbox/files/list", json={"locator": _locator().model_dump(mode="json"), "path": "."}
- )
-
- assert response.status_code == 200
- assert response.json()["path"] == "."
-
-
-def test_router_returns_503_when_service_unconfigured() -> None:
- response = _client(None).post(
- "/sandbox/files/list", json={"locator": _locator().model_dump(mode="json"), "path": "."}
- )
+ result = asyncio.run(service.read_file(SandboxReadRequest(locator=_locator(), path="notes.txt", max_bytes=8)))
- assert response.status_code == 503
- assert response.json()["detail"]["code"] == "sandbox_backend_unavailable"
+ assert result.text == "hello"
+ assert "python3 - notes.txt 8 <<'PY'" in client.run_calls[0].script
diff --git a/dify-agent/tests/local/test_packaging.py b/dify-agent/tests/local/test_packaging.py
index 84ee53ba2dd..c91ce3a7af4 100644
--- a/dify-agent/tests/local/test_packaging.py
+++ b/dify-agent/tests/local/test_packaging.py
@@ -23,7 +23,7 @@ SERVER_RUNTIME_DEPENDENCIES = {
"pydantic-ai-slim[anthropic,google,openai]>=1.85.1,<2.0.0",
"pydantic-settings>=2.12.0,<3.0.0",
"redis>=7.4.0,<8.0.0",
- "shell-session-manager==2.2.1",
+ "shell-session-manager==2.3.0",
"uvicorn[standard]==0.46.0",
}
@@ -66,24 +66,43 @@ def test_default_package_discovery_excludes_example_packages() -> None:
assert "dify_agent_examples*" not in find_config["include"]
-def test_project_declares_console_script_and_local_sandbox_docker_version() -> None:
+def test_project_declares_console_scripts() -> None:
pyproject = _read_pyproject()
scripts = pyproject["project"]["scripts"]
- dockerfile = (PROJECT_ROOT / "docker" / "local-sandbox" / "Dockerfile").read_text(encoding="utf-8")
assert scripts["dify-agent"] == "dify_agent.agent_stub.cli.main:main"
assert scripts["dify-agent-stub-server"] == "dify_agent.agent_stub.server.cli:main"
- assert "SHELL_SESSION_MANAGER_VERSION=2.2.1" in dockerfile
def test_local_sandbox_dockerfile_installs_stub_client_and_shellctl() -> None:
dockerfile = (PROJECT_ROOT / "docker" / "local-sandbox" / "Dockerfile").read_text(encoding="utf-8")
- assert "uv sync --frozen --no-dev --no-editable --extra grpc" in dockerfile
- assert "SHELL_SESSION_MANAGER_VERSION=2.2.1" in dockerfile
- assert "shell-session-manager==${SHELL_SESSION_MANAGER_VERSION}" in dockerfile
+ assert "ARG NODE_VERSION=22.22.1" in dockerfile
+ assert "ARG PNPM_VERSION=11.9.0" in dockerfile
+ assert "ARG UV_VERSION=0.8.9" in dockerfile
+ assert "ARG DIFY_AGENT_TOOL_SPEC=.[grpc]" in dockerfile
+ assert "ARG SHELL_SESSION_MANAGER_TOOL_SPEC=shell-session-manager" in dockerfile
+ assert "UV_TOOL_DIR=/opt/dify-agent-tools/envs" in dockerfile
+ assert "UV_TOOL_BIN_DIR=/opt/dify-agent-tools/bin" in dockerfile
+ assert "git" in dockerfile
+ assert "jq" in dockerfile
+ assert "openssh-client" in dockerfile
+ assert "ripgrep" in dockerfile
+ assert 'node_dist="node-v${NODE_VERSION}-linux-${node_arch}"' in dockerfile
+ assert 'curl -fsSLO "https://nodejs.org/dist/v${NODE_VERSION}/SHASUMS256.txt"' in dockerfile
+ assert 'tar -xJf "${node_dist}.tar.xz" -C /usr/local --strip-components=1' in dockerfile
+ assert 'npm install --global "pnpm@${PNPM_VERSION}"' in dockerfile
+ assert "uv export --frozen --no-dev --all-extras --no-emit-project --no-hashes" in dockerfile
+ assert "> /tmp/dify-agent-constraints.txt" in dockerfile
+ assert '--constraints /tmp/dify-agent-constraints.txt --link-mode=copy "${DIFY_AGENT_TOOL_SPEC}"' in dockerfile
+ assert (
+ '--constraints /tmp/dify-agent-constraints.txt --link-mode=copy "${SHELL_SESSION_MANAGER_TOOL_SPEC}"'
+ in dockerfile
+ )
assert "DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive" in dockerfile
- assert "ln -s ${VIRTUAL_ENV}/bin/dify-agent /usr/local/bin/dify-agent" in dockerfile
- assert "ln -s ${VIRTUAL_ENV}/bin/shellctl /usr/local/bin/shellctl" in dockerfile
+ assert "COPY --from=tools ${UV_TOOL_DIR} ${UV_TOOL_DIR}" in dockerfile
+ assert "COPY --from=tools ${UV_TOOL_BIN_DIR} ${UV_TOOL_BIN_DIR}" in dockerfile
+ assert "VIRTUAL_ENV" not in dockerfile
+ assert "uv sync" not in dockerfile
assert "mkdir -p /mnt/drive" in dockerfile
assert '["shellctl", "serve", "--listen", "0.0.0.0:5004"]' in dockerfile
diff --git a/dify-agent/uv.lock b/dify-agent/uv.lock
index 22348434e5b..df40ea9fe1a 100644
--- a/dify-agent/uv.lock
+++ b/dify-agent/uv.lock
@@ -650,7 +650,7 @@ requires-dist = [
{ name = "pydantic-ai-slim", extras = ["anthropic", "google", "openai"], marker = "extra == 'server'", specifier = ">=1.85.1,<2.0.0" },
{ name = "pydantic-settings", marker = "extra == 'server'", specifier = ">=2.12.0,<3.0.0" },
{ name = "redis", marker = "extra == 'server'", specifier = ">=7.4.0,<8.0.0" },
- { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.1" },
+ { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.3.0" },
{ name = "typer", specifier = ">=0.16.1,<0.17" },
{ name = "typing-extensions", specifier = ">=4.12.2,<5.0.0" },
{ name = "uvicorn", extras = ["standard"], marker = "extra == 'server'", specifier = "==0.46.0" },
@@ -3503,7 +3503,7 @@ wheels = [
[[package]]
name = "shell-session-manager"
-version = "2.2.1"
+version = "2.3.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiosqlite" },
@@ -3515,9 +3515,9 @@ dependencies = [
{ name = "typer" },
{ name = "uvicorn" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/54/c3/83701914c5194e0390b93a05685ddfceda425348523254f43fdcb5024a37/shell_session_manager-2.2.1.tar.gz", hash = "sha256:421531c8bca5a586e9245282e13fdbe2566fca34e72a7320749c745cc2a935ee", size = 51380, upload-time = "2026-06-19T12:21:58.67Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/ed/27/64b6086f54a700836c3fe6fc403e1a180a5c0285b528588663d0de951a6b/shell_session_manager-2.3.0.tar.gz", hash = "sha256:59598f4824623053405a6d0ba85c931e263597752aa6b91e67b0e523474dccf5", size = 51361, upload-time = "2026-06-28T18:32:57.249Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/5f/b6/b8d84ff7e59661cef85a1f021f500c798451121775f5aafd7b670ba63117/shell_session_manager-2.2.1-py3-none-any.whl", hash = "sha256:b7452dd5d50b5f55d2a108a2c422ed9883a817e2145f884844d072ec95dcaff8", size = 48895, upload-time = "2026-06-19T12:21:57.183Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/26/07e4815e630316f1840e36b686f91bd389940437e38b897a0231c487298f/shell_session_manager-2.3.0-py3-none-any.whl", hash = "sha256:7727cc328661d93dd40d6f42d2c6b46c95d49717698558e81d78b41a42501b4f", size = 48900, upload-time = "2026-06-28T18:32:55.937Z" },
]
[[package]]
diff --git a/packages/contracts/generated/api/console/agent/orpc.gen.ts b/packages/contracts/generated/api/console/agent/orpc.gen.ts
index f8f9ccaa785..c813a2f5bc6 100644
--- a/packages/contracts/generated/api/console/agent/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/agent/orpc.gen.ts
@@ -8,6 +8,12 @@ import {
zDeleteAgentByAgentIdApiKeysByApiKeyIdResponse,
zDeleteAgentByAgentIdBuildDraftPath,
zDeleteAgentByAgentIdBuildDraftResponse,
+ zDeleteAgentByAgentIdConfigFilesByNamePath,
+ zDeleteAgentByAgentIdConfigFilesByNameQuery,
+ zDeleteAgentByAgentIdConfigFilesByNameResponse,
+ zDeleteAgentByAgentIdConfigSkillsByNamePath,
+ zDeleteAgentByAgentIdConfigSkillsByNameQuery,
+ zDeleteAgentByAgentIdConfigSkillsByNameResponse,
zDeleteAgentByAgentIdFilesPath,
zDeleteAgentByAgentIdFilesQuery,
zDeleteAgentByAgentIdFilesResponse,
@@ -30,6 +36,35 @@ import {
zGetAgentByAgentIdComposerCandidatesResponse,
zGetAgentByAgentIdComposerPath,
zGetAgentByAgentIdComposerResponse,
+ zGetAgentByAgentIdConfigFilesByNameDownloadPath,
+ zGetAgentByAgentIdConfigFilesByNameDownloadQuery,
+ zGetAgentByAgentIdConfigFilesByNameDownloadResponse,
+ zGetAgentByAgentIdConfigFilesByNamePreviewPath,
+ zGetAgentByAgentIdConfigFilesByNamePreviewQuery,
+ zGetAgentByAgentIdConfigFilesByNamePreviewResponse,
+ zGetAgentByAgentIdConfigFilesPath,
+ zGetAgentByAgentIdConfigFilesQuery,
+ zGetAgentByAgentIdConfigFilesResponse,
+ zGetAgentByAgentIdConfigManifestPath,
+ zGetAgentByAgentIdConfigManifestQuery,
+ zGetAgentByAgentIdConfigManifestResponse,
+ zGetAgentByAgentIdConfigSkillsByNameDownloadPath,
+ zGetAgentByAgentIdConfigSkillsByNameDownloadQuery,
+ zGetAgentByAgentIdConfigSkillsByNameDownloadResponse,
+ zGetAgentByAgentIdConfigSkillsByNameFilesContentPath,
+ zGetAgentByAgentIdConfigSkillsByNameFilesContentResponse,
+ zGetAgentByAgentIdConfigSkillsByNameFilesDownloadPath,
+ zGetAgentByAgentIdConfigSkillsByNameFilesDownloadQuery,
+ zGetAgentByAgentIdConfigSkillsByNameFilesDownloadResponse,
+ zGetAgentByAgentIdConfigSkillsByNameFilesPreviewPath,
+ zGetAgentByAgentIdConfigSkillsByNameFilesPreviewQuery,
+ zGetAgentByAgentIdConfigSkillsByNameFilesPreviewResponse,
+ zGetAgentByAgentIdConfigSkillsByNameInspectPath,
+ zGetAgentByAgentIdConfigSkillsByNameInspectQuery,
+ zGetAgentByAgentIdConfigSkillsByNameInspectResponse,
+ zGetAgentByAgentIdConfigSkillsPath,
+ zGetAgentByAgentIdConfigSkillsQuery,
+ zGetAgentByAgentIdConfigSkillsResponse,
zGetAgentByAgentIdDriveFilesDownloadPath,
zGetAgentByAgentIdDriveFilesDownloadQuery,
zGetAgentByAgentIdDriveFilesDownloadResponse,
@@ -80,6 +115,8 @@ import {
zPostAgentByAgentIdApiEnableResponse,
zPostAgentByAgentIdApiKeysPath,
zPostAgentByAgentIdApiKeysResponse,
+ zPostAgentByAgentIdBuildChatFinalizePath,
+ zPostAgentByAgentIdBuildChatFinalizeResponse,
zPostAgentByAgentIdBuildDraftApplyPath,
zPostAgentByAgentIdBuildDraftApplyResponse,
zPostAgentByAgentIdBuildDraftCheckoutBody,
@@ -90,6 +127,14 @@ import {
zPostAgentByAgentIdComposerValidateBody,
zPostAgentByAgentIdComposerValidatePath,
zPostAgentByAgentIdComposerValidateResponse,
+ zPostAgentByAgentIdConfigFilesBody,
+ zPostAgentByAgentIdConfigFilesPath,
+ zPostAgentByAgentIdConfigFilesQuery,
+ zPostAgentByAgentIdConfigFilesResponse,
+ zPostAgentByAgentIdConfigSkillsUploadBody,
+ zPostAgentByAgentIdConfigSkillsUploadPath,
+ zPostAgentByAgentIdConfigSkillsUploadQuery,
+ zPostAgentByAgentIdConfigSkillsUploadResponse,
zPostAgentByAgentIdCopyBody,
zPostAgentByAgentIdCopyPath,
zPostAgentByAgentIdCopyResponse,
@@ -221,7 +266,30 @@ export const apiKeys = {
byApiKeyId,
}
+/**
+ * Run a build-draft Agent App turn that asks the agent to push config updates
+ */
export const post3 = oc
+ .route({
+ description: 'Run a build-draft Agent App turn that asks the agent to push config updates',
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdBuildChatFinalize',
+ path: '/agent/{agent_id}/build-chat/finalize',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zPostAgentByAgentIdBuildChatFinalizePath }))
+ .output(zPostAgentByAgentIdBuildChatFinalizeResponse)
+
+export const finalize = {
+ post: post3,
+}
+
+export const buildChat = {
+ finalize,
+}
+
+export const post4 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -233,10 +301,10 @@ export const post3 = oc
.output(zPostAgentByAgentIdBuildDraftApplyResponse)
export const apply = {
- post: post3,
+ post: post4,
}
-export const post4 = oc
+export const post5 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -253,7 +321,7 @@ export const post4 = oc
.output(zPostAgentByAgentIdBuildDraftCheckoutResponse)
export const checkout = {
- post: post4,
+ post: post5,
}
export const delete2 = oc
@@ -325,7 +393,7 @@ export const byMessageId = {
/**
* Stop a running Agent App chat message generation
*/
-export const post5 = oc
+export const post6 = oc
.route({
description: 'Stop a running Agent App chat message generation',
inputStructure: 'detailed',
@@ -338,7 +406,7 @@ export const post5 = oc
.output(zPostAgentByAgentIdChatMessagesByTaskIdStopResponse)
export const stop = {
- post: post5,
+ post: post6,
}
export const byTaskId = {
@@ -386,7 +454,7 @@ export const candidates = {
get: get7,
}
-export const post6 = oc
+export const post7 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -403,7 +471,7 @@ export const post6 = oc
.output(zPostAgentByAgentIdComposerValidateResponse)
export const validate = {
- post: post6,
+ post: post7,
}
export const get8 = oc
@@ -435,7 +503,303 @@ export const composer = {
validate,
}
-export const post7 = oc
+export const get9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigFilesByNameDownload',
+ path: '/agent/{agent_id}/config/files/{name}/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigFilesByNameDownloadPath,
+ query: zGetAgentByAgentIdConfigFilesByNameDownloadQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigFilesByNameDownloadResponse)
+
+export const download = {
+ get: get9,
+}
+
+export const get10 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigFilesByNamePreview',
+ path: '/agent/{agent_id}/config/files/{name}/preview',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigFilesByNamePreviewPath,
+ query: zGetAgentByAgentIdConfigFilesByNamePreviewQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigFilesByNamePreviewResponse)
+
+export const preview = {
+ get: get10,
+}
+
+export const delete3 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'DELETE',
+ operationId: 'deleteAgentByAgentIdConfigFilesByName',
+ path: '/agent/{agent_id}/config/files/{name}',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zDeleteAgentByAgentIdConfigFilesByNamePath,
+ query: zDeleteAgentByAgentIdConfigFilesByNameQuery.optional(),
+ }),
+ )
+ .output(zDeleteAgentByAgentIdConfigFilesByNameResponse)
+
+export const byName = {
+ delete: delete3,
+ download,
+ preview,
+}
+
+export const get11 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigFiles',
+ path: '/agent/{agent_id}/config/files',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigFilesPath,
+ query: zGetAgentByAgentIdConfigFilesQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigFilesResponse)
+
+export const post8 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdConfigFiles',
+ path: '/agent/{agent_id}/config/files',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAgentByAgentIdConfigFilesBody,
+ params: zPostAgentByAgentIdConfigFilesPath,
+ query: zPostAgentByAgentIdConfigFilesQuery.optional(),
+ }),
+ )
+ .output(zPostAgentByAgentIdConfigFilesResponse)
+
+export const files = {
+ get: get11,
+ post: post8,
+ byName,
+}
+
+export const get12 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigManifest',
+ path: '/agent/{agent_id}/config/manifest',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigManifestPath,
+ query: zGetAgentByAgentIdConfigManifestQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigManifestResponse)
+
+export const manifest = {
+ get: get12,
+}
+
+export const post9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdConfigSkillsUpload',
+ path: '/agent/{agent_id}/config/skills/upload',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAgentByAgentIdConfigSkillsUploadBody,
+ params: zPostAgentByAgentIdConfigSkillsUploadPath,
+ query: zPostAgentByAgentIdConfigSkillsUploadQuery.optional(),
+ }),
+ )
+ .output(zPostAgentByAgentIdConfigSkillsUploadResponse)
+
+export const upload = {
+ post: post9,
+}
+
+export const get13 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkillsByNameDownload',
+ path: '/agent/{agent_id}/config/skills/{name}/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigSkillsByNameDownloadPath,
+ query: zGetAgentByAgentIdConfigSkillsByNameDownloadQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigSkillsByNameDownloadResponse)
+
+export const download2 = {
+ get: get13,
+}
+
+export const get14 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkillsByNameFilesContent',
+ path: '/agent/{agent_id}/config/skills/{name}/files/content',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zGetAgentByAgentIdConfigSkillsByNameFilesContentPath }))
+ .output(zGetAgentByAgentIdConfigSkillsByNameFilesContentResponse)
+
+export const content = {
+ get: get14,
+}
+
+export const get15 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkillsByNameFilesDownload',
+ path: '/agent/{agent_id}/config/skills/{name}/files/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigSkillsByNameFilesDownloadPath,
+ query: zGetAgentByAgentIdConfigSkillsByNameFilesDownloadQuery,
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigSkillsByNameFilesDownloadResponse)
+
+export const download3 = {
+ get: get15,
+}
+
+export const get16 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkillsByNameFilesPreview',
+ path: '/agent/{agent_id}/config/skills/{name}/files/preview',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigSkillsByNameFilesPreviewPath,
+ query: zGetAgentByAgentIdConfigSkillsByNameFilesPreviewQuery,
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigSkillsByNameFilesPreviewResponse)
+
+export const preview2 = {
+ get: get16,
+}
+
+export const files2 = {
+ content,
+ download: download3,
+ preview: preview2,
+}
+
+export const get17 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkillsByNameInspect',
+ path: '/agent/{agent_id}/config/skills/{name}/inspect',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigSkillsByNameInspectPath,
+ query: zGetAgentByAgentIdConfigSkillsByNameInspectQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigSkillsByNameInspectResponse)
+
+export const inspect = {
+ get: get17,
+}
+
+export const delete4 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'DELETE',
+ operationId: 'deleteAgentByAgentIdConfigSkillsByName',
+ path: '/agent/{agent_id}/config/skills/{name}',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zDeleteAgentByAgentIdConfigSkillsByNamePath,
+ query: zDeleteAgentByAgentIdConfigSkillsByNameQuery.optional(),
+ }),
+ )
+ .output(zDeleteAgentByAgentIdConfigSkillsByNameResponse)
+
+export const byName2 = {
+ delete: delete4,
+ download: download2,
+ files: files2,
+ inspect,
+}
+
+export const get18 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdConfigSkills',
+ path: '/agent/{agent_id}/config/skills',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAgentByAgentIdConfigSkillsPath,
+ query: zGetAgentByAgentIdConfigSkillsQuery.optional(),
+ }),
+ )
+ .output(zGetAgentByAgentIdConfigSkillsResponse)
+
+export const skills = {
+ get: get18,
+ upload,
+ byName: byName2,
+}
+
+export const config = {
+ files,
+ manifest,
+ skills,
+}
+
+export const post10 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -448,10 +812,10 @@ export const post7 = oc
.output(zPostAgentByAgentIdCopyResponse)
export const copy = {
- post: post7,
+ post: post10,
}
-export const post8 = oc
+export const post11 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -463,7 +827,7 @@ export const post8 = oc
.output(zPostAgentByAgentIdDebugConversationRefreshResponse)
export const refresh = {
- post: post8,
+ post: post11,
}
export const debugConversation = {
@@ -473,7 +837,7 @@ export const debugConversation = {
/**
* Time-limited external signed URL for one Agent App drive value
*/
-export const get9 = oc
+export const get19 = oc
.route({
description: 'Time-limited external signed URL for one Agent App drive value',
inputStructure: 'detailed',
@@ -490,14 +854,14 @@ export const get9 = oc
)
.output(zGetAgentByAgentIdDriveFilesDownloadResponse)
-export const download = {
- get: get9,
+export const download4 = {
+ get: get19,
}
/**
* Truncated text preview of one Agent App drive value
*/
-export const get10 = oc
+export const get20 = oc
.route({
description: 'Truncated text preview of one Agent App drive value',
inputStructure: 'detailed',
@@ -514,14 +878,14 @@ export const get10 = oc
)
.output(zGetAgentByAgentIdDriveFilesPreviewResponse)
-export const preview = {
- get: get10,
+export const preview3 = {
+ get: get20,
}
/**
* List agent drive entries for an Agent App
*/
-export const get11 = oc
+export const get21 = oc
.route({
description: 'List agent drive entries for an Agent App',
inputStructure: 'detailed',
@@ -538,16 +902,16 @@ export const get11 = oc
)
.output(zGetAgentByAgentIdDriveFilesResponse)
-export const files = {
- get: get11,
- download,
- preview,
+export const files3 = {
+ get: get21,
+ download: download4,
+ preview: preview3,
}
/**
* Inspect one drive-backed skill for slash-menu hover/detail UI
*/
-export const get12 = oc
+export const get22 = oc
.route({
description: 'Inspect one drive-backed skill for slash-menu hover/detail UI',
inputStructure: 'detailed',
@@ -559,18 +923,18 @@ export const get12 = oc
.input(z.object({ params: zGetAgentByAgentIdDriveSkillsBySkillPathInspectPath }))
.output(zGetAgentByAgentIdDriveSkillsBySkillPathInspectResponse)
-export const inspect = {
- get: get12,
+export const inspect2 = {
+ get: get22,
}
export const bySkillPath = {
- inspect,
+ inspect: inspect2,
}
/**
* List drive-backed skills for an Agent App
*/
-export const get13 = oc
+export const get23 = oc
.route({
description: 'List drive-backed skills for an Agent App',
inputStructure: 'detailed',
@@ -582,20 +946,20 @@ export const get13 = oc
.input(z.object({ params: zGetAgentByAgentIdDriveSkillsPath }))
.output(zGetAgentByAgentIdDriveSkillsResponse)
-export const skills = {
- get: get13,
+export const skills2 = {
+ get: get23,
bySkillPath,
}
export const drive = {
- files,
- skills,
+ files: files3,
+ skills: skills2,
}
/**
* Update an Agent App's presentation features (opener, follow-up, citations, ...)
*/
-export const post9 = oc
+export const post12 = oc
.route({
description: 'Update an Agent App\'s presentation features (opener, follow-up, citations, ...)',
inputStructure: 'detailed',
@@ -610,13 +974,13 @@ export const post9 = oc
.output(zPostAgentByAgentIdFeaturesResponse)
export const features = {
- post: post9,
+ post: post12,
}
/**
* Create or update Agent App message feedback
*/
-export const post10 = oc
+export const post13 = oc
.route({
description: 'Create or update Agent App message feedback',
inputStructure: 'detailed',
@@ -631,13 +995,13 @@ export const post10 = oc
.output(zPostAgentByAgentIdFeedbacksResponse)
export const feedbacks = {
- post: post10,
+ post: post13,
}
/**
* Delete one Agent App drive file by key
*/
-export const delete3 = oc
+export const delete5 = oc
.route({
description: 'Delete one Agent App drive file by key',
inputStructure: 'detailed',
@@ -654,7 +1018,7 @@ export const delete3 = oc
/**
* Commit an uploaded file into the Agent App drive under files/<name>
*/
-export const post11 = oc
+export const post14 = oc
.route({
description: 'Commit an uploaded file into the Agent App drive under files/<name>',
inputStructure: 'detailed',
@@ -667,12 +1031,12 @@ export const post11 = oc
.input(z.object({ body: zPostAgentByAgentIdFilesBody, params: zPostAgentByAgentIdFilesPath }))
.output(zPostAgentByAgentIdFilesResponse)
-export const files2 = {
- delete: delete3,
- post: post11,
+export const files4 = {
+ delete: delete5,
+ post: post14,
}
-export const get14 = oc
+export const get24 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -684,10 +1048,10 @@ export const get14 = oc
.output(zGetAgentByAgentIdLogSourcesResponse)
export const logSources = {
- get: get14,
+ get: get24,
}
-export const get15 = oc
+export const get25 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -704,14 +1068,14 @@ export const get15 = oc
.output(zGetAgentByAgentIdLogsByConversationIdMessagesResponse)
export const messages = {
- get: get15,
+ get: get25,
}
export const byConversationId = {
messages,
}
-export const get16 = oc
+export const get26 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -725,14 +1089,14 @@ export const get16 = oc
.output(zGetAgentByAgentIdLogsResponse)
export const logs = {
- get: get16,
+ get: get26,
byConversationId,
}
/**
* Get Agent App message details by ID
*/
-export const get17 = oc
+export const get27 = oc
.route({
description: 'Get Agent App message details by ID',
inputStructure: 'detailed',
@@ -745,14 +1109,14 @@ export const get17 = oc
.output(zGetAgentByAgentIdMessagesByMessageIdResponse)
export const byMessageId2 = {
- get: get17,
+ get: get27,
}
export const messages2 = {
byMessageId: byMessageId2,
}
-export const post12 = oc
+export const post15 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -764,13 +1128,13 @@ export const post12 = oc
.output(zPostAgentByAgentIdPublishResponse)
export const publish = {
- post: post12,
+ post: post15,
}
/**
* List workflow apps that reference this Agent App's bound Agent (read-only)
*/
-export const get18 = oc
+export const get28 = oc
.route({
description: 'List workflow apps that reference this Agent App\'s bound Agent (read-only)',
inputStructure: 'detailed',
@@ -783,13 +1147,13 @@ export const get18 = oc
.output(zGetAgentByAgentIdReferencingWorkflowsResponse)
export const referencingWorkflows = {
- get: get18,
+ get: get28,
}
/**
* Read a text/binary preview file in an Agent App conversation sandbox
*/
-export const get19 = oc
+export const get29 = oc
.route({
description: 'Read a text/binary preview file in an Agent App conversation sandbox',
inputStructure: 'detailed',
@@ -807,13 +1171,13 @@ export const get19 = oc
.output(zGetAgentByAgentIdSandboxFilesReadResponse)
export const read = {
- get: get19,
+ get: get29,
}
/**
* Upload one Agent App sandbox file as a Dify ToolFile mapping
*/
-export const post13 = oc
+export const post16 = oc
.route({
description: 'Upload one Agent App sandbox file as a Dify ToolFile mapping',
inputStructure: 'detailed',
@@ -830,14 +1194,14 @@ export const post13 = oc
)
.output(zPostAgentByAgentIdSandboxFilesUploadResponse)
-export const upload = {
- post: post13,
+export const upload2 = {
+ post: post16,
}
/**
* List a directory in an Agent App conversation sandbox
*/
-export const get20 = oc
+export const get30 = oc
.route({
description: 'List a directory in an Agent App conversation sandbox',
inputStructure: 'detailed',
@@ -854,20 +1218,20 @@ export const get20 = oc
)
.output(zGetAgentByAgentIdSandboxFilesResponse)
-export const files3 = {
- get: get20,
+export const files5 = {
+ get: get30,
read,
- upload,
+ upload: upload2,
}
export const sandbox = {
- files: files3,
+ files: files5,
}
/**
* Upload + standardize a Skill into an Agent App drive
*/
-export const post14 = oc
+export const post17 = oc
.route({
description: 'Upload + standardize a Skill into an Agent App drive',
inputStructure: 'detailed',
@@ -885,14 +1249,14 @@ export const post14 = oc
)
.output(zPostAgentByAgentIdSkillsUploadResponse)
-export const upload2 = {
- post: post14,
+export const upload3 = {
+ post: post17,
}
/**
* Infer CLI tool + ENV suggestions from a standardized Agent App skill
*/
-export const post15 = oc
+export const post18 = oc
.route({
description: 'Infer CLI tool + ENV suggestions from a standardized Agent App skill',
inputStructure: 'detailed',
@@ -905,13 +1269,13 @@ export const post15 = oc
.output(zPostAgentByAgentIdSkillsBySlugInferToolsResponse)
export const inferTools = {
- post: post15,
+ post: post18,
}
/**
* Delete a standardized skill from an Agent App drive
*/
-export const delete4 = oc
+export const delete6 = oc
.route({
description: 'Delete a standardized skill from an Agent App drive',
inputStructure: 'detailed',
@@ -924,16 +1288,16 @@ export const delete4 = oc
.output(zDeleteAgentByAgentIdSkillsBySlugResponse)
export const bySlug = {
- delete: delete4,
+ delete: delete6,
inferTools,
}
-export const skills2 = {
- upload: upload2,
+export const skills3 = {
+ upload: upload3,
bySlug,
}
-export const get21 = oc
+export const get31 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -950,14 +1314,14 @@ export const get21 = oc
.output(zGetAgentByAgentIdStatisticsSummaryResponse)
export const summary = {
- get: get21,
+ get: get31,
}
export const statistics = {
summary,
}
-export const post16 = oc
+export const post19 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -969,10 +1333,10 @@ export const post16 = oc
.output(zPostAgentByAgentIdVersionsByVersionIdRestoreResponse)
export const restore = {
- post: post16,
+ post: post19,
}
-export const get22 = oc
+export const get32 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -984,11 +1348,11 @@ export const get22 = oc
.output(zGetAgentByAgentIdVersionsByVersionIdResponse)
export const byVersionId = {
- get: get22,
+ get: get32,
restore,
}
-export const get23 = oc
+export const get33 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -1000,11 +1364,11 @@ export const get23 = oc
.output(zGetAgentByAgentIdVersionsResponse)
export const versions = {
- get: get23,
+ get: get33,
byVersionId,
}
-export const delete5 = oc
+export const delete7 = oc
.route({
inputStructure: 'detailed',
method: 'DELETE',
@@ -1016,7 +1380,7 @@ export const delete5 = oc
.input(z.object({ params: zDeleteAgentByAgentIdPath }))
.output(zDeleteAgentByAgentIdResponse)
-export const get24 = oc
+export const get34 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -1039,33 +1403,35 @@ export const put3 = oc
.output(zPutAgentByAgentIdResponse)
export const byAgentId = {
- delete: delete5,
- get: get24,
+ delete: delete7,
+ get: get34,
put: put3,
apiAccess,
apiEnable,
apiKeys,
+ buildChat,
buildDraft,
chatMessages,
composer,
+ config,
copy,
debugConversation,
drive,
features,
feedbacks,
- files: files2,
+ files: files4,
logSources,
logs,
messages: messages2,
publish,
referencingWorkflows,
sandbox,
- skills: skills2,
+ skills: skills3,
statistics,
versions,
}
-export const get25 = oc
+export const get35 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -1076,7 +1442,7 @@ export const get25 = oc
.input(z.object({ query: zGetAgentQuery.optional() }))
.output(zGetAgentResponse)
-export const post17 = oc
+export const post20 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1089,8 +1455,8 @@ export const post17 = oc
.output(zPostAgentResponse)
export const agent = {
- get: get25,
- post: post17,
+ get: get35,
+ post: post20,
inviteOptions,
byAgentId,
}
diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.ts
index bd4918a22ce..08b9fe90e1d 100644
--- a/packages/contracts/generated/api/console/agent/types.gen.ts
+++ b/packages/contracts/generated/api/console/agent/types.gen.ts
@@ -30,7 +30,9 @@ export type AgentAppDetailWithSite = {
bound_agent_id?: string | null
created_at?: number | null
created_by?: string | null
+ debug_conversation_has_messages?: boolean
debug_conversation_id?: string | null
+ debug_conversation_message_count?: number
deleted_tools?: Array<DeletedTool>
description?: string | null
enable_api: boolean
@@ -109,6 +111,10 @@ export type ApiKeyItem = {
type: string
}
+export type SimpleResultResponse = {
+ result: string
+}
+
export type AgentSimpleResultResponse = {
result: string
}
@@ -162,10 +168,6 @@ export type SuggestedQuestionsResponse = {
data: Array<string>
}
-export type SimpleResultResponse = {
- result: string
-}
-
export type AgentAppComposerResponse = {
active_config_snapshot?: AgentConfigSnapshotSummaryResponse | null
agent: AgentComposerAgentResponse
@@ -195,6 +197,82 @@ export type AgentComposerValidateResponse = {
warnings?: Array<ComposerValidationWarningResponse>
}
+export type AgentConfigFileListResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ items?: Array<AgentConfigFileItemResponse>
+}
+
+export type AgentConfigFileUploadPayload = {
+ upload_file_id: string
+}
+
+export type AgentConfigFileUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ file: AgentConfigFileItemResponse
+}
+
+export type AgentConfigDeleteResponse = {
+ removed_names?: Array<string>
+ result: 'success'
+}
+
+export type AgentConfigDownloadResponse = {
+ url: string
+}
+
+export type AgentConfigFilePreviewResponse = {
+ binary: boolean
+ name: string
+ size?: number | null
+ text?: string | null
+ truncated: boolean
+}
+
+export type AgentConfigManifestResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ env_keys?: Array<string>
+ files?: AgentConfigFileItemsResponse
+ note?: string
+ skills?: AgentConfigSkillItemsResponse
+}
+
+export type AgentConfigSkillListResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ items?: Array<AgentConfigSkillItemResponse>
+}
+
+export type AgentConfigSkillUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ skill: AgentConfigSkillItemResponse
+}
+
+export type AgentConfigSkillFilePreviewResponse = {
+ binary: boolean
+ path: string
+ size?: number | null
+ text?: string | null
+ truncated: boolean
+}
+
+export type AgentConfigSkillInspectResponse = {
+ description?: string
+ file_tree?: Array<{
+ [key: string]: unknown
+ }> | null
+ files?: Array<AgentConfigSkillFileResponse>
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+ skill_md: AgentConfigSkillMarkdownResponse
+ source: 'config_skill_zip'
+ warnings?: Array<string>
+}
+
export type AgentAppCopyPayload = {
description?: string | null
icon?: string | null
@@ -205,7 +283,9 @@ export type AgentAppCopyPayload = {
}
export type AgentDebugConversationRefreshResponse = {
+ debug_conversation_has_messages?: boolean
debug_conversation_id: string
+ debug_conversation_message_count?: number
}
export type AgentDriveListResponse = {
@@ -554,6 +634,9 @@ export type AgentInviteOptionResponse = {
export type AgentSoulConfig = {
app_features?: AgentSoulAppFeaturesConfig
app_variables?: Array<AppVariableConfig>
+ config_files?: Array<AgentConfigFileRefConfig>
+ config_note?: string
+ config_skills?: Array<AgentConfigSkillRefConfig>
env?: AgentSoulEnvConfig
files?: AgentSoulFilesConfig
human?: AgentSoulHumanConfig
@@ -675,6 +758,55 @@ export type ComposerValidationWarningResponse = {
surface?: string | null
}
+export type AgentConfigVersionResponse = {
+ id: string
+ kind: 'build_draft' | 'draft' | 'snapshot'
+ writable: boolean
+}
+
+export type AgentConfigFileItemResponse = {
+ file_id?: string | null
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigFileItemsResponse = {
+ items?: Array<AgentConfigFileItemResponse>
+}
+
+export type AgentConfigSkillItemsResponse = {
+ items?: Array<AgentConfigSkillItemResponse>
+}
+
+export type AgentConfigSkillItemResponse = {
+ description?: string
+ file_id?: string | null
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigSkillFileResponse = {
+ downloadable: boolean
+ name: string
+ path: string
+ previewable: boolean
+ type: 'directory' | 'file'
+}
+
+export type AgentConfigSkillMarkdownResponse = {
+ binary: false
+ path: 'SKILL.md'
+ size?: number | null
+ text: string
+ truncated: boolean
+}
+
export type AgentDriveItemResponse = {
created_at?: number | null
file_kind: string
@@ -1004,6 +1136,25 @@ export type AppVariableConfig = {
type: string
}
+export type AgentConfigFileRefConfig = {
+ file_id: string
+ file_kind: 'tool_file' | 'upload_file'
+ hash?: string | null
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigSkillRefConfig = {
+ description?: string
+ file_id: string
+ file_kind?: 'tool_file'
+ hash?: string | null
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
export type AgentSoulEnvConfig = {
secret_refs?: Array<AgentSecretRefConfig>
variables?: Array<AgentEnvVariableConfig>
@@ -1690,7 +1841,9 @@ export type AgentAppDetailWithSiteWritable = {
bound_agent_id?: string | null
created_at?: number | null
created_by?: string | null
+ debug_conversation_has_messages?: boolean
debug_conversation_id?: string | null
+ debug_conversation_message_count?: number
deleted_tools?: Array<DeletedTool>
description?: string | null
enable_api: boolean
@@ -1989,6 +2142,27 @@ export type DeleteAgentByAgentIdApiKeysByApiKeyIdResponses = {
export type DeleteAgentByAgentIdApiKeysByApiKeyIdResponse
= DeleteAgentByAgentIdApiKeysByApiKeyIdResponses[keyof DeleteAgentByAgentIdApiKeysByApiKeyIdResponses]
+export type PostAgentByAgentIdBuildChatFinalizeData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-chat/finalize'
+}
+
+export type PostAgentByAgentIdBuildChatFinalizeErrors = {
+ 400: unknown
+ 404: unknown
+}
+
+export type PostAgentByAgentIdBuildChatFinalizeResponses = {
+ 200: SimpleResultResponse
+}
+
+export type PostAgentByAgentIdBuildChatFinalizeResponse
+ = PostAgentByAgentIdBuildChatFinalizeResponses[keyof PostAgentByAgentIdBuildChatFinalizeResponses]
+
export type DeleteAgentByAgentIdBuildDraftData = {
body?: never
path: {
@@ -2195,6 +2369,284 @@ export type PostAgentByAgentIdComposerValidateResponses = {
export type PostAgentByAgentIdComposerValidateResponse
= PostAgentByAgentIdComposerValidateResponses[keyof PostAgentByAgentIdComposerValidateResponses]
+export type GetAgentByAgentIdConfigFilesData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files'
+}
+
+export type GetAgentByAgentIdConfigFilesResponses = {
+ 200: AgentConfigFileListResponse
+}
+
+export type GetAgentByAgentIdConfigFilesResponse
+ = GetAgentByAgentIdConfigFilesResponses[keyof GetAgentByAgentIdConfigFilesResponses]
+
+export type PostAgentByAgentIdConfigFilesData = {
+ body: AgentConfigFileUploadPayload
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files'
+}
+
+export type PostAgentByAgentIdConfigFilesResponses = {
+ 201: AgentConfigFileUploadResponse
+}
+
+export type PostAgentByAgentIdConfigFilesResponse
+ = PostAgentByAgentIdConfigFilesResponses[keyof PostAgentByAgentIdConfigFilesResponses]
+
+export type DeleteAgentByAgentIdConfigFilesByNameData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files/{name}'
+}
+
+export type DeleteAgentByAgentIdConfigFilesByNameResponses = {
+ 200: AgentConfigDeleteResponse
+}
+
+export type DeleteAgentByAgentIdConfigFilesByNameResponse
+ = DeleteAgentByAgentIdConfigFilesByNameResponses[keyof DeleteAgentByAgentIdConfigFilesByNameResponses]
+
+export type GetAgentByAgentIdConfigFilesByNameDownloadData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files/{name}/download'
+}
+
+export type GetAgentByAgentIdConfigFilesByNameDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAgentByAgentIdConfigFilesByNameDownloadResponse
+ = GetAgentByAgentIdConfigFilesByNameDownloadResponses[keyof GetAgentByAgentIdConfigFilesByNameDownloadResponses]
+
+export type GetAgentByAgentIdConfigFilesByNamePreviewData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files/{name}/preview'
+}
+
+export type GetAgentByAgentIdConfigFilesByNamePreviewResponses = {
+ 200: AgentConfigFilePreviewResponse
+}
+
+export type GetAgentByAgentIdConfigFilesByNamePreviewResponse
+ = GetAgentByAgentIdConfigFilesByNamePreviewResponses[keyof GetAgentByAgentIdConfigFilesByNamePreviewResponses]
+
+export type GetAgentByAgentIdConfigManifestData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/manifest'
+}
+
+export type GetAgentByAgentIdConfigManifestResponses = {
+ 200: AgentConfigManifestResponse
+}
+
+export type GetAgentByAgentIdConfigManifestResponse
+ = GetAgentByAgentIdConfigManifestResponses[keyof GetAgentByAgentIdConfigManifestResponses]
+
+export type GetAgentByAgentIdConfigSkillsData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills'
+}
+
+export type GetAgentByAgentIdConfigSkillsResponses = {
+ 200: AgentConfigSkillListResponse
+}
+
+export type GetAgentByAgentIdConfigSkillsResponse
+ = GetAgentByAgentIdConfigSkillsResponses[keyof GetAgentByAgentIdConfigSkillsResponses]
+
+export type PostAgentByAgentIdConfigSkillsUploadData = {
+ body: {
+ file: Blob | File
+ }
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/upload'
+}
+
+export type PostAgentByAgentIdConfigSkillsUploadResponses = {
+ 201: AgentConfigSkillUploadResponse
+}
+
+export type PostAgentByAgentIdConfigSkillsUploadResponse
+ = PostAgentByAgentIdConfigSkillsUploadResponses[keyof PostAgentByAgentIdConfigSkillsUploadResponses]
+
+export type DeleteAgentByAgentIdConfigSkillsByNameData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/{name}'
+}
+
+export type DeleteAgentByAgentIdConfigSkillsByNameResponses = {
+ 200: AgentConfigDeleteResponse
+}
+
+export type DeleteAgentByAgentIdConfigSkillsByNameResponse
+ = DeleteAgentByAgentIdConfigSkillsByNameResponses[keyof DeleteAgentByAgentIdConfigSkillsByNameResponses]
+
+export type GetAgentByAgentIdConfigSkillsByNameDownloadData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/{name}/download'
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameDownloadResponse
+ = GetAgentByAgentIdConfigSkillsByNameDownloadResponses[keyof GetAgentByAgentIdConfigSkillsByNameDownloadResponses]
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesContentData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/config/skills/{name}/files/content'
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesContentResponses = {
+ 200: {
+ [key: string]: unknown
+ }
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesContentResponse
+ = GetAgentByAgentIdConfigSkillsByNameFilesContentResponses[keyof GetAgentByAgentIdConfigSkillsByNameFilesContentResponses]
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesDownloadData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query: {
+ draft_type?: 'debug_build' | 'draft'
+ path: string
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/{name}/files/download'
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesDownloadResponse
+ = GetAgentByAgentIdConfigSkillsByNameFilesDownloadResponses[keyof GetAgentByAgentIdConfigSkillsByNameFilesDownloadResponses]
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesPreviewData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query: {
+ draft_type?: 'debug_build' | 'draft'
+ path: string
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/{name}/files/preview'
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesPreviewResponses = {
+ 200: AgentConfigSkillFilePreviewResponse
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameFilesPreviewResponse
+ = GetAgentByAgentIdConfigSkillsByNameFilesPreviewResponses[keyof GetAgentByAgentIdConfigSkillsByNameFilesPreviewResponses]
+
+export type GetAgentByAgentIdConfigSkillsByNameInspectData = {
+ body?: never
+ path: {
+ agent_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/skills/{name}/inspect'
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameInspectResponses = {
+ 200: AgentConfigSkillInspectResponse
+}
+
+export type GetAgentByAgentIdConfigSkillsByNameInspectResponse
+ = GetAgentByAgentIdConfigSkillsByNameInspectResponses[keyof GetAgentByAgentIdConfigSkillsByNameInspectResponses]
+
export type PostAgentByAgentIdCopyData = {
body: AgentAppCopyPayload
path: {
diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.ts
index 712f9c54a08..d14cd5c7e89 100644
--- a/packages/contracts/generated/api/console/agent/zod.gen.ts
+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts
@@ -47,6 +47,13 @@ export const zApiKeyList = z.object({
data: z.array(zApiKeyItem),
})
+/**
+ * SimpleResultResponse
+ */
+export const zSimpleResultResponse = z.object({
+ result: z.string(),
+})
+
/**
* AgentSimpleResultResponse
*/
@@ -86,17 +93,56 @@ export const zSuggestedQuestionsResponse = z.object({
})
/**
- * SimpleResultResponse
+ * AgentConfigFileUploadPayload
*/
-export const zSimpleResultResponse = z.object({
- result: z.string(),
+export const zAgentConfigFileUploadPayload = z.object({
+ upload_file_id: z.string(),
+})
+
+/**
+ * AgentConfigDeleteResponse
+ */
+export const zAgentConfigDeleteResponse = z.object({
+ removed_names: z.array(z.string()).optional(),
+ result: z.literal('success'),
+})
+
+/**
+ * AgentConfigDownloadResponse
+ */
+export const zAgentConfigDownloadResponse = z.object({
+ url: z.string(),
+})
+
+/**
+ * AgentConfigFilePreviewResponse
+ */
+export const zAgentConfigFilePreviewResponse = z.object({
+ binary: z.boolean(),
+ name: z.string(),
+ size: z.int().nullish(),
+ text: z.string().nullish(),
+ truncated: z.boolean(),
+})
+
+/**
+ * AgentConfigSkillFilePreviewResponse
+ */
+export const zAgentConfigSkillFilePreviewResponse = z.object({
+ binary: z.boolean(),
+ path: z.string(),
+ size: z.int().nullish(),
+ text: z.string().nullish(),
+ truncated: z.boolean(),
})
/**
* AgentDebugConversationRefreshResponse
*/
export const zAgentDebugConversationRefreshResponse = z.object({
+ debug_conversation_has_messages: z.boolean().optional().default(false),
debug_conversation_id: z.string(),
+ debug_conversation_message_count: z.int().optional().default(0),
})
/**
@@ -407,6 +453,139 @@ export const zComposerValidationFindingsResponse = z.object({
warnings: z.array(zComposerValidationWarningResponse).optional(),
})
+/**
+ * AgentConfigVersionResponse
+ */
+export const zAgentConfigVersionResponse = z.object({
+ id: z.string(),
+ kind: z.enum(['build_draft', 'draft', 'snapshot']),
+ writable: z.boolean(),
+})
+
+/**
+ * AgentConfigFileItemResponse
+ */
+export const zAgentConfigFileItemResponse = z.object({
+ file_id: z.string().nullish(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigFileListResponse
+ */
+export const zAgentConfigFileListResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ items: z.array(zAgentConfigFileItemResponse).optional(),
+})
+
+/**
+ * AgentConfigFileUploadResponse
+ */
+export const zAgentConfigFileUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ file: zAgentConfigFileItemResponse,
+})
+
+/**
+ * AgentConfigFileItemsResponse
+ */
+export const zAgentConfigFileItemsResponse = z.object({
+ items: z.array(zAgentConfigFileItemResponse).optional(),
+})
+
+/**
+ * AgentConfigSkillItemResponse
+ */
+export const zAgentConfigSkillItemResponse = z.object({
+ description: z.string().optional().default(''),
+ file_id: z.string().nullish(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigSkillListResponse
+ */
+export const zAgentConfigSkillListResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ items: z.array(zAgentConfigSkillItemResponse).optional(),
+})
+
+/**
+ * AgentConfigSkillUploadResponse
+ */
+export const zAgentConfigSkillUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ skill: zAgentConfigSkillItemResponse,
+})
+
+/**
+ * AgentConfigSkillItemsResponse
+ */
+export const zAgentConfigSkillItemsResponse = z.object({
+ items: z.array(zAgentConfigSkillItemResponse).optional(),
+})
+
+/**
+ * AgentConfigManifestResponse
+ */
+export const zAgentConfigManifestResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ env_keys: z.array(z.string()).optional(),
+ files: zAgentConfigFileItemsResponse.optional(),
+ note: z.string().optional().default(''),
+ skills: zAgentConfigSkillItemsResponse.optional(),
+})
+
+/**
+ * AgentConfigSkillFileResponse
+ */
+export const zAgentConfigSkillFileResponse = z.object({
+ downloadable: z.boolean(),
+ name: z.string(),
+ path: z.string(),
+ previewable: z.boolean(),
+ type: z.enum(['directory', 'file']),
+})
+
+/**
+ * AgentConfigSkillMarkdownResponse
+ */
+export const zAgentConfigSkillMarkdownResponse = z.object({
+ binary: z.literal(false),
+ path: z.literal('SKILL.md'),
+ size: z.int().nullish(),
+ text: z.string(),
+ truncated: z.boolean(),
+})
+
+/**
+ * AgentConfigSkillInspectResponse
+ */
+export const zAgentConfigSkillInspectResponse = z.object({
+ description: z.string().optional().default(''),
+ file_tree: z.array(z.record(z.string(), z.unknown())).nullish(),
+ files: z.array(zAgentConfigSkillFileResponse).optional(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+ skill_md: zAgentConfigSkillMarkdownResponse,
+ source: z.literal('config_skill_zip'),
+ warnings: z.array(z.string()).optional(),
+})
+
/**
* AgentDriveItemResponse
*/
@@ -864,7 +1043,9 @@ export const zAgentAppDetailWithSite = z.object({
bound_agent_id: z.string().nullish(),
created_at: z.int().nullish(),
created_by: z.string().nullish(),
+ debug_conversation_has_messages: z.boolean().optional().default(false),
debug_conversation_id: z.string().nullish(),
+ debug_conversation_message_count: z.int().optional().default(0),
deleted_tools: z.array(zDeletedTool).optional(),
description: z.string().nullish(),
enable_api: z.boolean(),
@@ -1016,6 +1197,35 @@ export const zAppVariableConfig = z.object({
type: z.string().min(1).max(64),
})
+/**
+ * AgentConfigFileRefConfig
+ *
+ * Stable Agent Soul reference to one config file payload.
+ */
+export const zAgentConfigFileRefConfig = z.object({
+ file_id: z.string().min(1).max(255),
+ file_kind: z.enum(['tool_file', 'upload_file']),
+ hash: z.string().nullish(),
+ mime_type: z.string().nullish(),
+ name: z.string().min(1).max(255),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigSkillRefConfig
+ *
+ * Stable Agent Soul reference to one normalized skill archive.
+ */
+export const zAgentConfigSkillRefConfig = z.object({
+ description: z.string().optional().default(''),
+ file_id: z.string().min(1).max(255),
+ file_kind: z.literal('tool_file').optional().default('tool_file'),
+ hash: z.string().nullish(),
+ mime_type: z.string().nullish().default('application/zip'),
+ name: z.string().min(1).max(255),
+ size: z.int().nullish(),
+})
+
/**
* AgentSoulPromptConfig
*/
@@ -1806,12 +2016,15 @@ export const zAgentSoulDifyToolCredentialRef = z.object({
/**
* AgentSoulDifyToolConfig
*
- * One Dify Plugin Tool configured on Agent Soul.
+ * One Dify tool configured on Agent Soul.
*
* The API backend prepares this persisted product shape into
- * ``DifyPluginToolConfig`` before sending a run request to Agent backend.
- * ``provider_id`` keeps compatibility with existing Agent tool config payloads;
- * new callers should send ``plugin_id`` + ``provider`` when available.
+ * either ``DifyPluginToolConfig`` or ``DifyCoreToolConfig`` before sending a
+ * run request to Agent backend. ``plugin`` providers keep the direct
+ * ``dify.plugin.tools`` transport; ``builtin`` / ``api`` / ``workflow`` /
+ * ``mcp`` providers are prepared for ``dify.core.tools``. ``provider_id``
+ * keeps compatibility with existing Agent tool config payloads; new callers
+ * should send ``plugin_id`` + ``provider`` when available.
*/
export const zAgentSoulDifyToolConfig = z.object({
credential_ref: zAgentSoulDifyToolCredentialRef.nullish(),
@@ -2155,6 +2368,9 @@ export const zAgentSoulKnowledgeConfig = z.object({
export const zAgentSoulConfig = z.object({
app_features: zAgentSoulAppFeaturesConfig.optional(),
app_variables: z.array(zAppVariableConfig).optional(),
+ config_files: z.array(zAgentConfigFileRefConfig).optional(),
+ config_note: z.string().optional().default(''),
+ config_skills: z.array(zAgentConfigSkillRefConfig).optional(),
env: zAgentSoulEnvConfig.optional(),
files: zAgentSoulFilesConfig.optional(),
human: zAgentSoulHumanConfig.optional(),
@@ -2435,7 +2651,9 @@ export const zAgentAppDetailWithSiteWritable = z.object({
bound_agent_id: z.string().nullish(),
created_at: z.int().nullish(),
created_by: z.string().nullish(),
+ debug_conversation_has_messages: z.boolean().optional().default(false),
debug_conversation_id: z.string().nullish(),
+ debug_conversation_message_count: z.int().optional().default(0),
deleted_tools: z.array(zDeletedTool).optional(),
description: z.string().nullish(),
enable_api: z.boolean(),
@@ -2588,6 +2806,15 @@ export const zDeleteAgentByAgentIdApiKeysByApiKeyIdPath = z.object({
*/
export const zDeleteAgentByAgentIdApiKeysByApiKeyIdResponse = z.void()
+export const zPostAgentByAgentIdBuildChatFinalizePath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Success
+ */
+export const zPostAgentByAgentIdBuildChatFinalizeResponse = zSimpleResultResponse
+
export const zDeleteAgentByAgentIdBuildDraftPath = z.object({
agent_id: z.uuid(),
})
@@ -2713,6 +2940,219 @@ export const zPostAgentByAgentIdComposerValidatePath = z.object({
*/
export const zPostAgentByAgentIdComposerValidateResponse = zAgentComposerValidateResponse
+export const zGetAgentByAgentIdConfigFilesPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zGetAgentByAgentIdConfigFilesQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config files
+ */
+export const zGetAgentByAgentIdConfigFilesResponse = zAgentConfigFileListResponse
+
+export const zPostAgentByAgentIdConfigFilesBody = zAgentConfigFileUploadPayload
+
+export const zPostAgentByAgentIdConfigFilesPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zPostAgentByAgentIdConfigFilesQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Uploaded config file
+ */
+export const zPostAgentByAgentIdConfigFilesResponse = zAgentConfigFileUploadResponse
+
+export const zDeleteAgentByAgentIdConfigFilesByNamePath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zDeleteAgentByAgentIdConfigFilesByNameQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config file deleted
+ */
+export const zDeleteAgentByAgentIdConfigFilesByNameResponse = zAgentConfigDeleteResponse
+
+export const zGetAgentByAgentIdConfigFilesByNameDownloadPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigFilesByNameDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config file download URL
+ */
+export const zGetAgentByAgentIdConfigFilesByNameDownloadResponse = zAgentConfigDownloadResponse
+
+export const zGetAgentByAgentIdConfigFilesByNamePreviewPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigFilesByNamePreviewQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Preview
+ */
+export const zGetAgentByAgentIdConfigFilesByNamePreviewResponse = zAgentConfigFilePreviewResponse
+
+export const zGetAgentByAgentIdConfigManifestPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zGetAgentByAgentIdConfigManifestQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Agent config manifest
+ */
+export const zGetAgentByAgentIdConfigManifestResponse = zAgentConfigManifestResponse
+
+export const zGetAgentByAgentIdConfigSkillsPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zGetAgentByAgentIdConfigSkillsQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skills
+ */
+export const zGetAgentByAgentIdConfigSkillsResponse = zAgentConfigSkillListResponse
+
+export const zPostAgentByAgentIdConfigSkillsUploadBody = z.object({
+ file: z.custom<Blob | File>(),
+})
+
+export const zPostAgentByAgentIdConfigSkillsUploadPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zPostAgentByAgentIdConfigSkillsUploadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Uploaded config skill
+ */
+export const zPostAgentByAgentIdConfigSkillsUploadResponse = zAgentConfigSkillUploadResponse
+
+export const zDeleteAgentByAgentIdConfigSkillsByNamePath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zDeleteAgentByAgentIdConfigSkillsByNameQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill deleted
+ */
+export const zDeleteAgentByAgentIdConfigSkillsByNameResponse = zAgentConfigDeleteResponse
+
+export const zGetAgentByAgentIdConfigSkillsByNameDownloadPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigSkillsByNameDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill download URL
+ */
+export const zGetAgentByAgentIdConfigSkillsByNameDownloadResponse = zAgentConfigDownloadResponse
+
+export const zGetAgentByAgentIdConfigSkillsByNameFilesContentPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+/**
+ * Success
+ */
+export const zGetAgentByAgentIdConfigSkillsByNameFilesContentResponse = z.record(
+ z.string(),
+ z.unknown(),
+)
+
+export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ path: z.string(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill file download URL
+ */
+export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadResponse
+ = zAgentConfigDownloadResponse
+
+export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ path: z.string(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill file preview
+ */
+export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewResponse
+ = zAgentConfigSkillFilePreviewResponse
+
+export const zGetAgentByAgentIdConfigSkillsByNameInspectPath = z.object({
+ agent_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAgentByAgentIdConfigSkillsByNameInspectQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill inspect view
+ */
+export const zGetAgentByAgentIdConfigSkillsByNameInspectResponse = zAgentConfigSkillInspectResponse
+
export const zPostAgentByAgentIdCopyBody = zAgentAppCopyPayload
export const zPostAgentByAgentIdCopyPath = z.object({
diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.ts
index 59783646462..83637302055 100644
--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts
@@ -4,6 +4,12 @@ import { oc } from '@orpc/contract'
import * as z from 'zod'
import {
+ zDeleteAppsByAppIdAgentConfigFilesByNamePath,
+ zDeleteAppsByAppIdAgentConfigFilesByNameQuery,
+ zDeleteAppsByAppIdAgentConfigFilesByNameResponse,
+ zDeleteAppsByAppIdAgentConfigSkillsByNamePath,
+ zDeleteAppsByAppIdAgentConfigSkillsByNameQuery,
+ zDeleteAppsByAppIdAgentConfigSkillsByNameResponse,
zDeleteAppsByAppIdAgentFilesPath,
zDeleteAppsByAppIdAgentFilesQuery,
zDeleteAppsByAppIdAgentFilesResponse,
@@ -45,6 +51,35 @@ import {
zGetAppsByAppIdAdvancedChatWorkflowRunsPath,
zGetAppsByAppIdAdvancedChatWorkflowRunsQuery,
zGetAppsByAppIdAdvancedChatWorkflowRunsResponse,
+ zGetAppsByAppIdAgentConfigFilesByNameDownloadPath,
+ zGetAppsByAppIdAgentConfigFilesByNameDownloadQuery,
+ zGetAppsByAppIdAgentConfigFilesByNameDownloadResponse,
+ zGetAppsByAppIdAgentConfigFilesByNamePreviewPath,
+ zGetAppsByAppIdAgentConfigFilesByNamePreviewQuery,
+ zGetAppsByAppIdAgentConfigFilesByNamePreviewResponse,
+ zGetAppsByAppIdAgentConfigFilesPath,
+ zGetAppsByAppIdAgentConfigFilesQuery,
+ zGetAppsByAppIdAgentConfigFilesResponse,
+ zGetAppsByAppIdAgentConfigManifestPath,
+ zGetAppsByAppIdAgentConfigManifestQuery,
+ zGetAppsByAppIdAgentConfigManifestResponse,
+ zGetAppsByAppIdAgentConfigSkillsByNameDownloadPath,
+ zGetAppsByAppIdAgentConfigSkillsByNameDownloadQuery,
+ zGetAppsByAppIdAgentConfigSkillsByNameDownloadResponse,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesContentPath,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesContentResponse,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadPath,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadQuery,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponse,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewPath,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewQuery,
+ zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponse,
+ zGetAppsByAppIdAgentConfigSkillsByNameInspectPath,
+ zGetAppsByAppIdAgentConfigSkillsByNameInspectQuery,
+ zGetAppsByAppIdAgentConfigSkillsByNameInspectResponse,
+ zGetAppsByAppIdAgentConfigSkillsPath,
+ zGetAppsByAppIdAgentConfigSkillsQuery,
+ zGetAppsByAppIdAgentConfigSkillsResponse,
zGetAppsByAppIdAgentDriveFilesDownloadPath,
zGetAppsByAppIdAgentDriveFilesDownloadQuery,
zGetAppsByAppIdAgentDriveFilesDownloadResponse,
@@ -271,6 +306,14 @@ import {
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunBody,
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunPath,
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunResponse,
+ zPostAppsByAppIdAgentConfigFilesBody,
+ zPostAppsByAppIdAgentConfigFilesPath,
+ zPostAppsByAppIdAgentConfigFilesQuery,
+ zPostAppsByAppIdAgentConfigFilesResponse,
+ zPostAppsByAppIdAgentConfigSkillsUploadBody,
+ zPostAppsByAppIdAgentConfigSkillsUploadPath,
+ zPostAppsByAppIdAgentConfigSkillsUploadQuery,
+ zPostAppsByAppIdAgentConfigSkillsUploadResponse,
zPostAppsByAppIdAgentFilesBody,
zPostAppsByAppIdAgentFilesPath,
zPostAppsByAppIdAgentFilesQuery,
@@ -796,10 +839,306 @@ export const advancedChat = {
workflows: workflows2,
}
+export const get5 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigFilesByNameDownload',
+ path: '/apps/{app_id}/agent/config/files/{name}/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigFilesByNameDownloadPath,
+ query: zGetAppsByAppIdAgentConfigFilesByNameDownloadQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigFilesByNameDownloadResponse)
+
+export const download = {
+ get: get5,
+}
+
+export const get6 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigFilesByNamePreview',
+ path: '/apps/{app_id}/agent/config/files/{name}/preview',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigFilesByNamePreviewPath,
+ query: zGetAppsByAppIdAgentConfigFilesByNamePreviewQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigFilesByNamePreviewResponse)
+
+export const preview2 = {
+ get: get6,
+}
+
+export const delete_ = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'DELETE',
+ operationId: 'deleteAppsByAppIdAgentConfigFilesByName',
+ path: '/apps/{app_id}/agent/config/files/{name}',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zDeleteAppsByAppIdAgentConfigFilesByNamePath,
+ query: zDeleteAppsByAppIdAgentConfigFilesByNameQuery.optional(),
+ }),
+ )
+ .output(zDeleteAppsByAppIdAgentConfigFilesByNameResponse)
+
+export const byName = {
+ delete: delete_,
+ download,
+ preview: preview2,
+}
+
+export const get7 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigFiles',
+ path: '/apps/{app_id}/agent/config/files',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigFilesPath,
+ query: zGetAppsByAppIdAgentConfigFilesQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigFilesResponse)
+
+export const post9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAppsByAppIdAgentConfigFiles',
+ path: '/apps/{app_id}/agent/config/files',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAppsByAppIdAgentConfigFilesBody,
+ params: zPostAppsByAppIdAgentConfigFilesPath,
+ query: zPostAppsByAppIdAgentConfigFilesQuery.optional(),
+ }),
+ )
+ .output(zPostAppsByAppIdAgentConfigFilesResponse)
+
+export const files = {
+ get: get7,
+ post: post9,
+ byName,
+}
+
+export const get8 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigManifest',
+ path: '/apps/{app_id}/agent/config/manifest',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigManifestPath,
+ query: zGetAppsByAppIdAgentConfigManifestQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigManifestResponse)
+
+export const manifest = {
+ get: get8,
+}
+
+export const post10 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAppsByAppIdAgentConfigSkillsUpload',
+ path: '/apps/{app_id}/agent/config/skills/upload',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAppsByAppIdAgentConfigSkillsUploadBody,
+ params: zPostAppsByAppIdAgentConfigSkillsUploadPath,
+ query: zPostAppsByAppIdAgentConfigSkillsUploadQuery.optional(),
+ }),
+ )
+ .output(zPostAppsByAppIdAgentConfigSkillsUploadResponse)
+
+export const upload = {
+ post: post10,
+}
+
+export const get9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkillsByNameDownload',
+ path: '/apps/{app_id}/agent/config/skills/{name}/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigSkillsByNameDownloadPath,
+ query: zGetAppsByAppIdAgentConfigSkillsByNameDownloadQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigSkillsByNameDownloadResponse)
+
+export const download2 = {
+ get: get9,
+}
+
+export const get10 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkillsByNameFilesContent',
+ path: '/apps/{app_id}/agent/config/skills/{name}/files/content',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zGetAppsByAppIdAgentConfigSkillsByNameFilesContentPath }))
+ .output(zGetAppsByAppIdAgentConfigSkillsByNameFilesContentResponse)
+
+export const content = {
+ get: get10,
+}
+
+export const get11 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkillsByNameFilesDownload',
+ path: '/apps/{app_id}/agent/config/skills/{name}/files/download',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadPath,
+ query: zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadQuery,
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponse)
+
+export const download3 = {
+ get: get11,
+}
+
+export const get12 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkillsByNameFilesPreview',
+ path: '/apps/{app_id}/agent/config/skills/{name}/files/preview',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewPath,
+ query: zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewQuery,
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponse)
+
+export const preview3 = {
+ get: get12,
+}
+
+export const files2 = {
+ content,
+ download: download3,
+ preview: preview3,
+}
+
+export const get13 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkillsByNameInspect',
+ path: '/apps/{app_id}/agent/config/skills/{name}/inspect',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigSkillsByNameInspectPath,
+ query: zGetAppsByAppIdAgentConfigSkillsByNameInspectQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigSkillsByNameInspectResponse)
+
+export const inspect = {
+ get: get13,
+}
+
+export const delete2 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'DELETE',
+ operationId: 'deleteAppsByAppIdAgentConfigSkillsByName',
+ path: '/apps/{app_id}/agent/config/skills/{name}',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zDeleteAppsByAppIdAgentConfigSkillsByNamePath,
+ query: zDeleteAppsByAppIdAgentConfigSkillsByNameQuery.optional(),
+ }),
+ )
+ .output(zDeleteAppsByAppIdAgentConfigSkillsByNameResponse)
+
+export const byName2 = {
+ delete: delete2,
+ download: download2,
+ files: files2,
+ inspect,
+}
+
+export const get14 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAppsByAppIdAgentConfigSkills',
+ path: '/apps/{app_id}/agent/config/skills',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ params: zGetAppsByAppIdAgentConfigSkillsPath,
+ query: zGetAppsByAppIdAgentConfigSkillsQuery.optional(),
+ }),
+ )
+ .output(zGetAppsByAppIdAgentConfigSkillsResponse)
+
+export const skills = {
+ get: get14,
+ upload,
+ byName: byName2,
+}
+
+export const config = {
+ files,
+ manifest,
+ skills,
+}
+
/**
* Time-limited external signed URL for one drive value (no streaming proxy)
*/
-export const get5 = oc
+export const get15 = oc
.route({
description: 'Time-limited external signed URL for one drive value (no streaming proxy)',
inputStructure: 'detailed',
@@ -816,14 +1155,14 @@ export const get5 = oc
)
.output(zGetAppsByAppIdAgentDriveFilesDownloadResponse)
-export const download = {
- get: get5,
+export const download4 = {
+ get: get15,
}
/**
* Truncated text preview of one drive value (binary-safe; SKILL.md is the main case)
*/
-export const get6 = oc
+export const get16 = oc
.route({
description:
'Truncated text preview of one drive value (binary-safe; SKILL.md is the main case)',
@@ -841,14 +1180,14 @@ export const get6 = oc
)
.output(zGetAppsByAppIdAgentDriveFilesPreviewResponse)
-export const preview2 = {
- get: get6,
+export const preview4 = {
+ get: get16,
}
/**
* List agent drive entries (read-only inspector; one endpoint for both tabs)
*/
-export const get7 = oc
+export const get17 = oc
.route({
description: 'List agent drive entries (read-only inspector; one endpoint for both tabs)',
inputStructure: 'detailed',
@@ -865,16 +1204,16 @@ export const get7 = oc
)
.output(zGetAppsByAppIdAgentDriveFilesResponse)
-export const files = {
- get: get7,
- download,
- preview: preview2,
+export const files3 = {
+ get: get17,
+ download: download4,
+ preview: preview4,
}
/**
* Inspect one drive-backed skill for slash-menu hover/detail UI
*/
-export const get8 = oc
+export const get18 = oc
.route({
description: 'Inspect one drive-backed skill for slash-menu hover/detail UI',
inputStructure: 'detailed',
@@ -891,18 +1230,18 @@ export const get8 = oc
)
.output(zGetAppsByAppIdAgentDriveSkillsBySkillPathInspectResponse)
-export const inspect = {
- get: get8,
+export const inspect2 = {
+ get: get18,
}
export const bySkillPath = {
- inspect,
+ inspect: inspect2,
}
/**
* List drive-backed skills for the bound agent
*/
-export const get9 = oc
+export const get19 = oc
.route({
description: 'List drive-backed skills for the bound agent',
inputStructure: 'detailed',
@@ -919,20 +1258,20 @@ export const get9 = oc
)
.output(zGetAppsByAppIdAgentDriveSkillsResponse)
-export const skills = {
- get: get9,
+export const skills2 = {
+ get: get19,
bySkillPath,
}
export const drive = {
- files,
- skills,
+ files: files3,
+ skills: skills2,
}
/**
* Delete one drive file by key via drive commit-null semantics
*/
-export const delete_ = oc
+export const delete3 = oc
.route({
description: 'Delete one drive file by key via drive commit-null semantics',
inputStructure: 'detailed',
@@ -954,7 +1293,7 @@ export const delete_ = oc
*
* Commit an uploaded file into the agent drive under files/<name> (ENG-625 D3)
*/
-export const post9 = oc
+export const post11 = oc
.route({
description: 'Commit an uploaded file into the agent drive under files/<name> (ENG-625 D3)',
inputStructure: 'detailed',
@@ -974,9 +1313,9 @@ export const post9 = oc
)
.output(zPostAppsByAppIdAgentFilesResponse)
-export const files2 = {
- delete: delete_,
- post: post9,
+export const files4 = {
+ delete: delete3,
+ post: post11,
}
/**
@@ -984,7 +1323,7 @@ export const files2 = {
*
* Get agent execution logs for an application
*/
-export const get10 = oc
+export const get20 = oc
.route({
description: 'Get agent execution logs for an application',
inputStructure: 'detailed',
@@ -998,7 +1337,7 @@ export const get10 = oc
.output(zGetAppsByAppIdAgentLogsResponse)
export const logs = {
- get: get10,
+ get: get20,
}
/**
@@ -1006,7 +1345,7 @@ export const logs = {
*
* Upload + standardize a Skill into the agent drive
*/
-export const post10 = oc
+export const post12 = oc
.route({
description: 'Upload + standardize a Skill into the agent drive',
inputStructure: 'detailed',
@@ -1026,8 +1365,8 @@ export const post10 = oc
)
.output(zPostAppsByAppIdAgentSkillsUploadResponse)
-export const upload = {
- post: post10,
+export const upload2 = {
+ post: post12,
}
/**
@@ -1036,7 +1375,7 @@ export const upload = {
* Infer CLI tool + ENV suggestions from a standardized skill's SKILL.md (draft only, ENG-371)
* Saving still goes through composer validation.
*/
-export const post11 = oc
+export const post13 = oc
.route({
description:
'Infer CLI tool + ENV suggestions from a standardized skill\'s SKILL.md (draft only, ENG-371)\nSaving still goes through composer validation.',
@@ -1056,13 +1395,13 @@ export const post11 = oc
.output(zPostAppsByAppIdAgentSkillsBySlugInferToolsResponse)
export const inferTools = {
- post: post11,
+ post: post13,
}
/**
* Delete a standardized skill by removing its known drive keys via commit-null
*/
-export const delete2 = oc
+export const delete4 = oc
.route({
description: 'Delete a standardized skill by removing its known drive keys via commit-null',
inputStructure: 'detailed',
@@ -1080,26 +1419,27 @@ export const delete2 = oc
.output(zDeleteAppsByAppIdAgentSkillsBySlugResponse)
export const bySlug = {
- delete: delete2,
+ delete: delete4,
inferTools,
}
-export const skills2 = {
- upload,
+export const skills3 = {
+ upload: upload2,
bySlug,
}
export const agent = {
+ config,
drive,
- files: files2,
+ files: files4,
logs,
- skills: skills2,
+ skills: skills3,
}
/**
* Get status of annotation reply action job
*/
-export const get11 = oc
+export const get21 = oc
.route({
description: 'Get status of annotation reply action job',
inputStructure: 'detailed',
@@ -1112,7 +1452,7 @@ export const get11 = oc
.output(zGetAppsByAppIdAnnotationReplyByActionStatusByJobIdResponse)
export const byJobId = {
- get: get11,
+ get: get21,
}
export const status = {
@@ -1122,7 +1462,7 @@ export const status = {
/**
* Enable or disable annotation reply for an app
*/
-export const post12 = oc
+export const post14 = oc
.route({
description: 'Enable or disable annotation reply for an app',
inputStructure: 'detailed',
@@ -1140,7 +1480,7 @@ export const post12 = oc
.output(zPostAppsByAppIdAnnotationReplyByActionResponse)
export const byAction = {
- post: post12,
+ post: post14,
status,
}
@@ -1151,7 +1491,7 @@ export const annotationReply = {
/**
* Get annotation settings for an app
*/
-export const get12 = oc
+export const get22 = oc
.route({
description: 'Get annotation settings for an app',
inputStructure: 'detailed',
@@ -1164,13 +1504,13 @@ export const get12 = oc
.output(zGetAppsByAppIdAnnotationSettingResponse)
export const annotationSetting = {
- get: get12,
+ get: get22,
}
/**
* Update annotation settings for an app
*/
-export const post13 = oc
+export const post15 = oc
.route({
description: 'Update annotation settings for an app',
inputStructure: 'detailed',
@@ -1188,7 +1528,7 @@ export const post13 = oc
.output(zPostAppsByAppIdAnnotationSettingsByAnnotationSettingIdResponse)
export const byAnnotationSettingId = {
- post: post13,
+ post: post15,
}
export const annotationSettings = {
@@ -1198,7 +1538,7 @@ export const annotationSettings = {
/**
* Batch import annotations from CSV file with rate limiting and security checks
*/
-export const post14 = oc
+export const post16 = oc
.route({
description: 'Batch import annotations from CSV file with rate limiting and security checks',
inputStructure: 'detailed',
@@ -1211,13 +1551,13 @@ export const post14 = oc
.output(zPostAppsByAppIdAnnotationsBatchImportResponse)
export const batchImport = {
- post: post14,
+ post: post16,
}
/**
* Get status of batch import job
*/
-export const get13 = oc
+export const get23 = oc
.route({
description: 'Get status of batch import job',
inputStructure: 'detailed',
@@ -1230,7 +1570,7 @@ export const get13 = oc
.output(zGetAppsByAppIdAnnotationsBatchImportStatusByJobIdResponse)
export const byJobId2 = {
- get: get13,
+ get: get23,
}
export const batchImportStatus = {
@@ -1240,7 +1580,7 @@ export const batchImportStatus = {
/**
* Get count of message annotations for the app
*/
-export const get14 = oc
+export const get24 = oc
.route({
description: 'Get count of message annotations for the app',
inputStructure: 'detailed',
@@ -1253,13 +1593,13 @@ export const get14 = oc
.output(zGetAppsByAppIdAnnotationsCountResponse)
export const count2 = {
- get: get14,
+ get: get24,
}
/**
* Export all annotations for an app with CSV injection protection
*/
-export const get15 = oc
+export const get25 = oc
.route({
description: 'Export all annotations for an app with CSV injection protection',
inputStructure: 'detailed',
@@ -1272,13 +1612,13 @@ export const get15 = oc
.output(zGetAppsByAppIdAnnotationsExportResponse)
export const export_ = {
- get: get15,
+ get: get25,
}
/**
* Get hit histories for an annotation
*/
-export const get16 = oc
+export const get26 = oc
.route({
description: 'Get hit histories for an annotation',
inputStructure: 'detailed',
@@ -1296,10 +1636,10 @@ export const get16 = oc
.output(zGetAppsByAppIdAnnotationsByAnnotationIdHitHistoriesResponse)
export const hitHistories = {
- get: get16,
+ get: get26,
}
-export const delete3 = oc
+export const delete5 = oc
.route({
inputStructure: 'detailed',
method: 'DELETE',
@@ -1314,7 +1654,7 @@ export const delete3 = oc
/**
* Update or delete an annotation
*/
-export const post15 = oc
+export const post17 = oc
.route({
description: 'Update or delete an annotation',
inputStructure: 'detailed',
@@ -1332,12 +1672,12 @@ export const post15 = oc
.output(zPostAppsByAppIdAnnotationsByAnnotationIdResponse)
export const byAnnotationId = {
- delete: delete3,
- post: post15,
+ delete: delete5,
+ post: post17,
hitHistories,
}
-export const delete4 = oc
+export const delete6 = oc
.route({
inputStructure: 'detailed',
method: 'DELETE',
@@ -1352,7 +1692,7 @@ export const delete4 = oc
/**
* Get annotations for an app with pagination
*/
-export const get17 = oc
+export const get27 = oc
.route({
description: 'Get annotations for an app with pagination',
inputStructure: 'detailed',
@@ -1372,7 +1712,7 @@ export const get17 = oc
/**
* Create a new annotation for an app
*/
-export const post16 = oc
+export const post18 = oc
.route({
description: 'Create a new annotation for an app',
inputStructure: 'detailed',
@@ -1388,9 +1728,9 @@ export const post16 = oc
.output(zPostAppsByAppIdAnnotationsResponse)
export const annotations = {
- delete: delete4,
- get: get17,
- post: post16,
+ delete: delete6,
+ get: get27,
+ post: post18,
batchImport,
batchImportStatus,
count: count2,
@@ -1401,7 +1741,7 @@ export const annotations = {
/**
* Enable or disable app API
*/
-export const post17 = oc
+export const post19 = oc
.route({
description: 'Enable or disable app API',
inputStructure: 'detailed',
@@ -1414,13 +1754,13 @@ export const post17 = oc
.output(zPostAppsByAppIdApiEnableResponse)
export const apiEnable = {
- post: post17,
+ post: post19,
}
/**
* Transcript audio to text for chat messages
*/
-export const post18 = oc
+export const post20 = oc
.route({
description: 'Transcript audio to text for chat messages',
inputStructure: 'detailed',
@@ -1433,13 +1773,13 @@ export const post18 = oc
.output(zPostAppsByAppIdAudioToTextResponse)
export const audioToText = {
- post: post18,
+ post: post20,
}
/**
* Delete a chat conversation
*/
-export const delete5 = oc
+export const delete7 = oc
.route({
description: 'Delete a chat conversation',
inputStructure: 'detailed',
@@ -1455,7 +1795,7 @@ export const delete5 = oc
/**
* Get chat conversation details
*/
-export const get18 = oc
+export const get28 = oc
.route({
description: 'Get chat conversation details',
inputStructure: 'detailed',
@@ -1468,14 +1808,14 @@ export const get18 = oc
.output(zGetAppsByAppIdChatConversationsByConversationIdResponse)
export const byConversationId = {
- delete: delete5,
- get: get18,
+ delete: delete7,
+ get: get28,
}
/**
* Get chat conversations with pagination, filtering and summary
*/
-export const get19 = oc
+export const get29 = oc
.route({
description: 'Get chat conversations with pagination, filtering and summary',
inputStructure: 'detailed',
@@ -1493,14 +1833,14 @@ export const get19 = oc
.output(zGetAppsByAppIdChatConversationsResponse)
export const chatConversations = {
- get: get19,
+ get: get29,
byConversationId,
}
/**
* Get suggested questions for a message
*/
-export const get20 = oc
+export const get30 = oc
.route({
description: 'Get suggested questions for a message',
inputStructure: 'detailed',
@@ -1513,7 +1853,7 @@ export const get20 = oc
.output(zGetAppsByAppIdChatMessagesByMessageIdSuggestedQuestionsResponse)
export const suggestedQuestions = {
- get: get20,
+ get: get30,
}
export const byMessageId = {
@@ -1523,7 +1863,7 @@ export const byMessageId = {
/**
* Stop a running chat message generation
*/
-export const post19 = oc
+export const post21 = oc
.route({
description: 'Stop a running chat message generation',
inputStructure: 'detailed',
@@ -1536,7 +1876,7 @@ export const post19 = oc
.output(zPostAppsByAppIdChatMessagesByTaskIdStopResponse)
export const stop = {
- post: post19,
+ post: post21,
}
export const byTaskId = {
@@ -1546,7 +1886,7 @@ export const byTaskId = {
/**
* Get chat messages for a conversation with pagination
*/
-export const get21 = oc
+export const get31 = oc
.route({
description: 'Get chat messages for a conversation with pagination',
inputStructure: 'detailed',
@@ -1561,7 +1901,7 @@ export const get21 = oc
.output(zGetAppsByAppIdChatMessagesResponse)
export const chatMessages = {
- get: get21,
+ get: get31,
byMessageId,
byTaskId,
}
@@ -1569,7 +1909,7 @@ export const chatMessages = {
/**
* Delete a completion conversation
*/
-export const delete6 = oc
+export const delete8 = oc
.route({
description: 'Delete a completion conversation',
inputStructure: 'detailed',
@@ -1585,7 +1925,7 @@ export const delete6 = oc
/**
* Get completion conversation details with messages
*/
-export const get22 = oc
+export const get32 = oc
.route({
description: 'Get completion conversation details with messages',
inputStructure: 'detailed',
@@ -1598,14 +1938,14 @@ export const get22 = oc
.output(zGetAppsByAppIdCompletionConversationsByConversationIdResponse)
export const byConversationId2 = {
- delete: delete6,
- get: get22,
+ delete: delete8,
+ get: get32,
}
/**
* Get completion conversations with pagination and filtering
*/
-export const get23 = oc
+export const get33 = oc
.route({
description: 'Get completion conversations with pagination and filtering',
inputStructure: 'detailed',
@@ -1623,14 +1963,14 @@ export const get23 = oc
.output(zGetAppsByAppIdCompletionConversationsResponse)
export const completionConversations = {
- get: get23,
+ get: get33,
byConversationId: byConversationId2,
}
/**
* Stop a running completion message generation
*/
-export const post20 = oc
+export const post22 = oc
.route({
description: 'Stop a running completion message generation',
inputStructure: 'detailed',
@@ -1643,7 +1983,7 @@ export const post20 = oc
.output(zPostAppsByAppIdCompletionMessagesByTaskIdStopResponse)
export const stop2 = {
- post: post20,
+ post: post22,
}
export const byTaskId2 = {
@@ -1653,7 +1993,7 @@ export const byTaskId2 = {
/**
* Generate completion message for debugging
*/
-export const post21 = oc
+export const post23 = oc
.route({
description: 'Generate completion message for debugging',
inputStructure: 'detailed',
@@ -1671,14 +2011,14 @@ export const post21 = oc
.output(zPostAppsByAppIdCompletionMessagesResponse)
export const completionMessages = {
- post: post21,
+ post: post23,
byTaskId: byTaskId2,
}
/**
* Get conversation variables for an application
*/
-export const get24 = oc
+export const get34 = oc
.route({
description: 'Get conversation variables for an application',
inputStructure: 'detailed',
@@ -1696,7 +2036,7 @@ export const get24 = oc
.output(zGetAppsByAppIdConversationVariablesResponse)
export const conversationVariables = {
- get: get24,
+ get: get34,
}
/**
@@ -1706,7 +2046,7 @@ export const conversationVariables = {
* Convert expert mode of chatbot app to workflow mode
* Convert Completion App to Workflow App
*/
-export const post22 = oc
+export const post24 = oc
.route({
description:
'Convert application to workflow mode\nConvert expert mode of chatbot app to workflow mode\nConvert Completion App to Workflow App',
@@ -1726,7 +2066,7 @@ export const post22 = oc
.output(zPostAppsByAppIdConvertToWorkflowResponse)
export const convertToWorkflow = {
- post: post22,
+ post: post24,
}
/**
@@ -1734,7 +2074,7 @@ export const convertToWorkflow = {
*
* Create a copy of an existing application
*/
-export const post23 = oc
+export const post25 = oc
.route({
description: 'Create a copy of an existing application',
inputStructure: 'detailed',
@@ -1749,7 +2089,7 @@ export const post23 = oc
.output(zPostAppsByAppIdCopyResponse)
export const copy = {
- post: post23,
+ post: post25,
}
/**
@@ -1757,7 +2097,7 @@ export const copy = {
*
* Export application configuration as DSL
*/
-export const get25 = oc
+export const get35 = oc
.route({
description: 'Export application configuration as DSL',
inputStructure: 'detailed',
@@ -1773,13 +2113,13 @@ export const get25 = oc
.output(zGetAppsByAppIdExportResponse)
export const export2 = {
- get: get25,
+ get: get35,
}
/**
* Export user feedback data for Google Sheets
*/
-export const get26 = oc
+export const get36 = oc
.route({
description: 'Export user feedback data for Google Sheets',
inputStructure: 'detailed',
@@ -1797,13 +2137,13 @@ export const get26 = oc
.output(zGetAppsByAppIdFeedbacksExportResponse)
export const export3 = {
- get: get26,
+ get: get36,
}
/**
* Create or update message feedback (like/dislike)
*/
-export const post24 = oc
+export const post26 = oc
.route({
description: 'Create or update message feedback (like/dislike)',
inputStructure: 'detailed',
@@ -1816,14 +2156,14 @@ export const post24 = oc
.output(zPostAppsByAppIdFeedbacksResponse)
export const feedbacks = {
- post: post24,
+ post: post26,
export: export3,
}
/**
* Update application icon
*/
-export const post25 = oc
+export const post27 = oc
.route({
description: 'Update application icon',
inputStructure: 'detailed',
@@ -1836,13 +2176,13 @@ export const post25 = oc
.output(zPostAppsByAppIdIconResponse)
export const icon = {
- post: post25,
+ post: post27,
}
/**
* Get message details by ID
*/
-export const get27 = oc
+export const get37 = oc
.route({
description: 'Get message details by ID',
inputStructure: 'detailed',
@@ -1855,7 +2195,7 @@ export const get27 = oc
.output(zGetAppsByAppIdMessagesByMessageIdResponse)
export const byMessageId2 = {
- get: get27,
+ get: get37,
}
export const messages = {
@@ -1867,7 +2207,7 @@ export const messages = {
*
* Update application model configuration
*/
-export const post26 = oc
+export const post28 = oc
.route({
description: 'Update application model configuration',
inputStructure: 'detailed',
@@ -1883,13 +2223,13 @@ export const post26 = oc
.output(zPostAppsByAppIdModelConfigResponse)
export const modelConfig = {
- post: post26,
+ post: post28,
}
/**
* Check if app name is available
*/
-export const post27 = oc
+export const post29 = oc
.route({
description: 'Check if app name is available',
inputStructure: 'detailed',
@@ -1902,13 +2242,13 @@ export const post27 = oc
.output(zPostAppsByAppIdNameResponse)
export const name = {
- post: post27,
+ post: post29,
}
/**
* Publish app to Creators Platform
*/
-export const post28 = oc
+export const post30 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1921,13 +2261,13 @@ export const post28 = oc
.output(zPostAppsByAppIdPublishToCreatorsPlatformResponse)
export const publishToCreatorsPlatform = {
- post: post28,
+ post: post30,
}
/**
* Get MCP server configuration for an application
*/
-export const get28 = oc
+export const get38 = oc
.route({
description: 'Get MCP server configuration for an application',
inputStructure: 'detailed',
@@ -1942,7 +2282,7 @@ export const get28 = oc
/**
* Create MCP server configuration for an application
*/
-export const post29 = oc
+export const post31 = oc
.route({
description: 'Create MCP server configuration for an application',
inputStructure: 'detailed',
@@ -1971,15 +2311,15 @@ export const put = oc
.output(zPutAppsByAppIdServerResponse)
export const server = {
- get: get28,
- post: post29,
+ get: get38,
+ post: post31,
put,
}
/**
* Reset access token for application site
*/
-export const post30 = oc
+export const post32 = oc
.route({
description: 'Reset access token for application site',
inputStructure: 'detailed',
@@ -1992,13 +2332,13 @@ export const post30 = oc
.output(zPostAppsByAppIdSiteAccessTokenResetResponse)
export const accessTokenReset = {
- post: post30,
+ post: post32,
}
/**
* Update application site configuration
*/
-export const post31 = oc
+export const post33 = oc
.route({
description: 'Update application site configuration',
inputStructure: 'detailed',
@@ -2011,14 +2351,14 @@ export const post31 = oc
.output(zPostAppsByAppIdSiteResponse)
export const site = {
- post: post31,
+ post: post33,
accessTokenReset,
}
/**
* Enable or disable app site
*/
-export const post32 = oc
+export const post34 = oc
.route({
description: 'Enable or disable app site',
inputStructure: 'detailed',
@@ -2031,13 +2371,13 @@ export const post32 = oc
.output(zPostAppsByAppIdSiteEnableResponse)
export const siteEnable = {
- post: post32,
+ post: post34,
}
/**
* Remove the current account's star from an application
*/
-export const delete7 = oc
+export const delete9 = oc
.route({
description: 'Remove the current account\'s star from an application',
inputStructure: 'detailed',
@@ -2052,7 +2392,7 @@ export const delete7 = oc
/**
* Star an application for the current account
*/
-export const post33 = oc
+export const post35 = oc
.route({
description: 'Star an application for the current account',
inputStructure: 'detailed',
@@ -2065,14 +2405,14 @@ export const post33 = oc
.output(zPostAppsByAppIdStarResponse)
export const star = {
- delete: delete7,
- post: post33,
+ delete: delete9,
+ post: post35,
}
/**
* Get average response time statistics for an application
*/
-export const get29 = oc
+export const get39 = oc
.route({
description: 'Get average response time statistics for an application',
inputStructure: 'detailed',
@@ -2090,13 +2430,13 @@ export const get29 = oc
.output(zGetAppsByAppIdStatisticsAverageResponseTimeResponse)
export const averageResponseTime = {
- get: get29,
+ get: get39,
}
/**
* Get average session interaction statistics for an application
*/
-export const get30 = oc
+export const get40 = oc
.route({
description: 'Get average session interaction statistics for an application',
inputStructure: 'detailed',
@@ -2114,13 +2454,13 @@ export const get30 = oc
.output(zGetAppsByAppIdStatisticsAverageSessionInteractionsResponse)
export const averageSessionInteractions = {
- get: get30,
+ get: get40,
}
/**
* Get daily conversation statistics for an application
*/
-export const get31 = oc
+export const get41 = oc
.route({
description: 'Get daily conversation statistics for an application',
inputStructure: 'detailed',
@@ -2138,13 +2478,13 @@ export const get31 = oc
.output(zGetAppsByAppIdStatisticsDailyConversationsResponse)
export const dailyConversations = {
- get: get31,
+ get: get41,
}
/**
* Get daily terminal/end-user statistics for an application
*/
-export const get32 = oc
+export const get42 = oc
.route({
description: 'Get daily terminal/end-user statistics for an application',
inputStructure: 'detailed',
@@ -2162,13 +2502,13 @@ export const get32 = oc
.output(zGetAppsByAppIdStatisticsDailyEndUsersResponse)
export const dailyEndUsers = {
- get: get32,
+ get: get42,
}
/**
* Get daily message statistics for an application
*/
-export const get33 = oc
+export const get43 = oc
.route({
description: 'Get daily message statistics for an application',
inputStructure: 'detailed',
@@ -2186,13 +2526,13 @@ export const get33 = oc
.output(zGetAppsByAppIdStatisticsDailyMessagesResponse)
export const dailyMessages = {
- get: get33,
+ get: get43,
}
/**
* Get daily token cost statistics for an application
*/
-export const get34 = oc
+export const get44 = oc
.route({
description: 'Get daily token cost statistics for an application',
inputStructure: 'detailed',
@@ -2210,13 +2550,13 @@ export const get34 = oc
.output(zGetAppsByAppIdStatisticsTokenCostsResponse)
export const tokenCosts = {
- get: get34,
+ get: get44,
}
/**
* Get tokens per second statistics for an application
*/
-export const get35 = oc
+export const get45 = oc
.route({
description: 'Get tokens per second statistics for an application',
inputStructure: 'detailed',
@@ -2234,13 +2574,13 @@ export const get35 = oc
.output(zGetAppsByAppIdStatisticsTokensPerSecondResponse)
export const tokensPerSecond = {
- get: get35,
+ get: get45,
}
/**
* Get user satisfaction rate statistics for an application
*/
-export const get36 = oc
+export const get46 = oc
.route({
description: 'Get user satisfaction rate statistics for an application',
inputStructure: 'detailed',
@@ -2258,7 +2598,7 @@ export const get36 = oc
.output(zGetAppsByAppIdStatisticsUserSatisfactionRateResponse)
export const userSatisfactionRate = {
- get: get36,
+ get: get46,
}
export const statistics = {
@@ -2275,7 +2615,7 @@ export const statistics = {
/**
* Get available TTS voices for a specific language
*/
-export const get37 = oc
+export const get47 = oc
.route({
description: 'Get available TTS voices for a specific language',
inputStructure: 'detailed',
@@ -2293,13 +2633,13 @@ export const get37 = oc
.output(zGetAppsByAppIdTextToAudioVoicesResponse)
export const voices = {
- get: get37,
+ get: get47,
}
/**
* Convert text to speech for chat messages
*/
-export const post34 = oc
+export const post36 = oc
.route({
description: 'Convert text to speech for chat messages',
inputStructure: 'detailed',
@@ -2314,7 +2654,7 @@ export const post34 = oc
.output(zPostAppsByAppIdTextToAudioResponse)
export const textToAudio = {
- post: post34,
+ post: post36,
voices,
}
@@ -2323,7 +2663,7 @@ export const textToAudio = {
*
* Get app tracing configuration
*/
-export const get38 = oc
+export const get48 = oc
.route({
description: 'Get app tracing configuration',
inputStructure: 'detailed',
@@ -2339,7 +2679,7 @@ export const get38 = oc
/**
* Update app tracing configuration
*/
-export const post35 = oc
+export const post37 = oc
.route({
description: 'Update app tracing configuration',
inputStructure: 'detailed',
@@ -2352,8 +2692,8 @@ export const post35 = oc
.output(zPostAppsByAppIdTraceResponse)
export const trace = {
- get: get38,
- post: post35,
+ get: get48,
+ post: post37,
}
/**
@@ -2361,7 +2701,7 @@ export const trace = {
*
* Delete an existing tracing configuration for an application
*/
-export const delete8 = oc
+export const delete10 = oc
.route({
description: 'Delete an existing tracing configuration for an application',
inputStructure: 'detailed',
@@ -2383,7 +2723,7 @@ export const delete8 = oc
/**
* Get tracing configuration for an application
*/
-export const get39 = oc
+export const get49 = oc
.route({
description: 'Get tracing configuration for an application',
inputStructure: 'detailed',
@@ -2422,7 +2762,7 @@ export const patch = oc
*
* Create a new tracing configuration for an application
*/
-export const post36 = oc
+export const post38 = oc
.route({
description: 'Create a new tracing configuration for an application',
inputStructure: 'detailed',
@@ -2439,16 +2779,16 @@ export const post36 = oc
.output(zPostAppsByAppIdTraceConfigResponse)
export const traceConfig = {
- delete: delete8,
- get: get39,
+ delete: delete10,
+ get: get49,
patch,
- post: post36,
+ post: post38,
}
/**
* Update app trigger (enable/disable)
*/
-export const post37 = oc
+export const post39 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -2466,13 +2806,13 @@ export const post37 = oc
.output(zPostAppsByAppIdTriggerEnableResponse)
export const triggerEnable = {
- post: post37,
+ post: post39,
}
/**
* Get app triggers list
*/
-export const get40 = oc
+export const get50 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -2485,7 +2825,7 @@ export const get40 = oc
.output(zGetAppsByAppIdTriggersResponse)
export const triggers = {
- get: get40,
+ get: get50,
}
/**
@@ -2493,7 +2833,7 @@ export const triggers = {
*
* Get workflow application execution logs
*/
-export const get41 = oc
+export const get51 = oc
.route({
description: 'Get workflow application execution logs',
inputStructure: 'detailed',
@@ -2512,7 +2852,7 @@ export const get41 = oc
.output(zGetAppsByAppIdWorkflowAppLogsResponse)
export const workflowAppLogs = {
- get: get41,
+ get: get51,
}
/**
@@ -2520,7 +2860,7 @@ export const workflowAppLogs = {
*
* Get workflow archived execution logs
*/
-export const get42 = oc
+export const get52 = oc
.route({
description: 'Get workflow archived execution logs',
inputStructure: 'detailed',
@@ -2539,7 +2879,7 @@ export const get42 = oc
.output(zGetAppsByAppIdWorkflowArchivedLogsResponse)
export const workflowArchivedLogs = {
- get: get42,
+ get: get52,
}
/**
@@ -2547,7 +2887,7 @@ export const workflowArchivedLogs = {
*
* Get workflow runs count statistics
*/
-export const get43 = oc
+export const get53 = oc
.route({
description: 'Get workflow runs count statistics',
inputStructure: 'detailed',
@@ -2566,7 +2906,7 @@ export const get43 = oc
.output(zGetAppsByAppIdWorkflowRunsCountResponse)
export const count3 = {
- get: get43,
+ get: get53,
}
/**
@@ -2574,7 +2914,7 @@ export const count3 = {
*
* Stop running workflow task
*/
-export const post38 = oc
+export const post40 = oc
.route({
description: 'Stop running workflow task',
inputStructure: 'detailed',
@@ -2588,7 +2928,7 @@ export const post38 = oc
.output(zPostAppsByAppIdWorkflowRunsTasksByTaskIdStopResponse)
export const stop3 = {
- post: post38,
+ post: post40,
}
export const byTaskId3 = {
@@ -2602,7 +2942,7 @@ export const tasks = {
/**
* Generate a download URL for an archived workflow run.
*/
-export const get44 = oc
+export const get54 = oc
.route({
description: 'Generate a download URL for an archived workflow run.',
inputStructure: 'detailed',
@@ -2615,7 +2955,7 @@ export const get44 = oc
.output(zGetAppsByAppIdWorkflowRunsByRunIdExportResponse)
export const export4 = {
- get: get44,
+ get: get54,
}
/**
@@ -2623,7 +2963,7 @@ export const export4 = {
*
* Get workflow run node execution list
*/
-export const get45 = oc
+export const get55 = oc
.route({
description: 'Get workflow run node execution list',
inputStructure: 'detailed',
@@ -2637,7 +2977,7 @@ export const get45 = oc
.output(zGetAppsByAppIdWorkflowRunsByRunIdNodeExecutionsResponse)
export const nodeExecutions = {
- get: get45,
+ get: get55,
}
/**
@@ -2645,7 +2985,7 @@ export const nodeExecutions = {
*
* Get workflow run detail
*/
-export const get46 = oc
+export const get56 = oc
.route({
description: 'Get workflow run detail',
inputStructure: 'detailed',
@@ -2659,7 +2999,7 @@ export const get46 = oc
.output(zGetAppsByAppIdWorkflowRunsByRunIdResponse)
export const byRunId = {
- get: get46,
+ get: get56,
export: export4,
nodeExecutions,
}
@@ -2667,7 +3007,7 @@ export const byRunId = {
/**
* Read a text/binary preview file in a workflow Agent node sandbox
*/
-export const get47 = oc
+export const get57 = oc
.route({
description: 'Read a text/binary preview file in a workflow Agent node sandbox',
inputStructure: 'detailed',
@@ -2685,13 +3025,13 @@ export const get47 = oc
.output(zGetAppsByAppIdWorkflowRunsByWorkflowRunIdAgentNodesByNodeIdSandboxFilesReadResponse)
export const read = {
- get: get47,
+ get: get57,
}
/**
* Upload one workflow Agent sandbox file as a Dify ToolFile mapping
*/
-export const post39 = oc
+export const post41 = oc
.route({
description: 'Upload one workflow Agent sandbox file as a Dify ToolFile mapping',
inputStructure: 'detailed',
@@ -2708,14 +3048,14 @@ export const post39 = oc
)
.output(zPostAppsByAppIdWorkflowRunsByWorkflowRunIdAgentNodesByNodeIdSandboxFilesUploadResponse)
-export const upload2 = {
- post: post39,
+export const upload3 = {
+ post: post41,
}
/**
* List a directory in a workflow Agent node sandbox
*/
-export const get48 = oc
+export const get58 = oc
.route({
description: 'List a directory in a workflow Agent node sandbox',
inputStructure: 'detailed',
@@ -2732,15 +3072,15 @@ export const get48 = oc
}),
)
.output(zGetAppsByAppIdWorkflowRunsByWorkflowRunIdAgentNodesByNodeIdSandboxFilesResponse)
-
-export const files3 = {
- get: get48,
+
+export const files5 = {
+ get: get58,
read,
- upload: upload2,
+ upload: upload3,
}
export const sandbox = {
- files: files3,
+ files: files5,
}
export const byNodeId4 = {
@@ -2760,7 +3100,7 @@ export const byWorkflowRunId = {
*
* Get workflow run list
*/
-export const get49 = oc
+export const get59 = oc
.route({
description: 'Get workflow run list',
inputStructure: 'detailed',
@@ -2779,7 +3119,7 @@ export const get49 = oc
.output(zGetAppsByAppIdWorkflowRunsResponse)
export const workflowRuns2 = {
- get: get49,
+ get: get59,
count: count3,
tasks,
byRunId,
@@ -2791,7 +3131,7 @@ export const workflowRuns2 = {
*
* Get all users in current tenant for mentions
*/
-export const get50 = oc
+export const get60 = oc
.route({
description: 'Get all users in current tenant for mentions',
inputStructure: 'detailed',
@@ -2805,7 +3145,7 @@ export const get50 = oc
.output(zGetAppsByAppIdWorkflowCommentsMentionUsersResponse)
export const mentionUsers = {
- get: get50,
+ get: get60,
}
/**
@@ -2813,7 +3153,7 @@ export const mentionUsers = {
*
* Delete a comment reply
*/
-export const delete9 = oc
+export const delete11 = oc
.route({
description: 'Delete a comment reply',
inputStructure: 'detailed',
@@ -2851,7 +3191,7 @@ export const put2 = oc
.output(zPutAppsByAppIdWorkflowCommentsByCommentIdRepliesByReplyIdResponse)
export const byReplyId = {
- delete: delete9,
+ delete: delete11,
put: put2,
}
@@ -2860,7 +3200,7 @@ export const byReplyId = {
*
* Add a reply to a workflow comment
*/
-export const post40 = oc
+export const post42 = oc
.route({
description: 'Add a reply to a workflow comment',
inputStructure: 'detailed',
@@ -2880,7 +3220,7 @@ export const post40 = oc
.output(zPostAppsByAppIdWorkflowCommentsByCommentIdRepliesResponse)
export const replies = {
- post: post40,
+ post: post42,
byReplyId,
}
@@ -2889,7 +3229,7 @@ export const replies = {
*
* Resolve a workflow comment
*/
-export const post41 = oc
+export const post43 = oc
.route({
description: 'Resolve a workflow comment',
inputStructure: 'detailed',
@@ -2903,7 +3243,7 @@ export const post41 = oc
.output(zPostAppsByAppIdWorkflowCommentsByCommentIdResolveResponse)
export const resolve = {
- post: post41,
+ post: post43,
}
/**
@@ -2911,7 +3251,7 @@ export const resolve = {
*
* Delete a workflow comment
*/
-export const delete10 = oc
+export const delete12 = oc
.route({
description: 'Delete a workflow comment',
inputStructure: 'detailed',
@@ -2930,7 +3270,7 @@ export const delete10 = oc
*
* Get a specific workflow comment
*/
-export const get51 = oc
+export const get61 = oc
.route({
description: 'Get a specific workflow comment',
inputStructure: 'detailed',
@@ -2967,8 +3307,8 @@ export const put3 = oc
.output(zPutAppsByAppIdWorkflowCommentsByCommentIdResponse)
export const byCommentId = {
- delete: delete10,
- get: get51,
+ delete: delete12,
+ get: get61,
put: put3,
replies,
resolve,
@@ -2979,7 +3319,7 @@ export const byCommentId = {
*
* Get all comments for a workflow
*/
-export const get52 = oc
+export const get62 = oc
.route({
description: 'Get all comments for a workflow',
inputStructure: 'detailed',
@@ -2997,7 +3337,7 @@ export const get52 = oc
*
* Create a new workflow comment
*/
-export const post42 = oc
+export const post44 = oc
.route({
description: 'Create a new workflow comment',
inputStructure: 'detailed',
@@ -3017,8 +3357,8 @@ export const post42 = oc
.output(zPostAppsByAppIdWorkflowCommentsResponse)
export const comments = {
- get: get52,
- post: post42,
+ get: get62,
+ post: post44,
mentionUsers,
byCommentId,
}
@@ -3026,7 +3366,7 @@ export const comments = {
/**
* Get workflow average app interaction statistics
*/
-export const get53 = oc
+export const get63 = oc
.route({
description: 'Get workflow average app interaction statistics',
inputStructure: 'detailed',
@@ -3044,13 +3384,13 @@ export const get53 = oc
.output(zGetAppsByAppIdWorkflowStatisticsAverageAppInteractionsResponse)
export const averageAppInteractions = {
- get: get53,
+ get: get63,
}
/**
* Get workflow daily runs statistics
*/
-export const get54 = oc
+export const get64 = oc
.route({
description: 'Get workflow daily runs statistics',
inputStructure: 'detailed',
@@ -3068,13 +3408,13 @@ export const get54 = oc
.output(zGetAppsByAppIdWorkflowStatisticsDailyConversationsResponse)
export const dailyConversations2 = {
- get: get54,
+ get: get64,
}
/**
* Get workflow daily terminals statistics
*/
-export const get55 = oc
+export const get65 = oc
.route({
description: 'Get workflow daily terminals statistics',
inputStructure: 'detailed',
@@ -3092,13 +3432,13 @@ export const get55 = oc
.output(zGetAppsByAppIdWorkflowStatisticsDailyTerminalsResponse)
export const dailyTerminals = {
- get: get55,
+ get: get65,
}
/**
* Get workflow daily token cost statistics
*/
-export const get56 = oc
+export const get66 = oc
.route({
description: 'Get workflow daily token cost statistics',
inputStructure: 'detailed',
@@ -3116,7 +3456,7 @@ export const get56 = oc
.output(zGetAppsByAppIdWorkflowStatisticsTokenCostsResponse)
export const tokenCosts2 = {
- get: get56,
+ get: get66,
}
export const statistics2 = {
@@ -3136,7 +3476,7 @@ export const workflow = {
*
* Get default block configuration by type
*/
-export const get57 = oc
+export const get67 = oc
.route({
description: 'Get default block configuration by type',
inputStructure: 'detailed',
@@ -3155,7 +3495,7 @@ export const get57 = oc
.output(zGetAppsByAppIdWorkflowsDefaultWorkflowBlockConfigsByBlockTypeResponse)
export const byBlockType = {
- get: get57,
+ get: get67,
}
/**
@@ -3163,7 +3503,7 @@ export const byBlockType = {
*
* Get default block configurations for workflow
*/
-export const get58 = oc
+export const get68 = oc
.route({
description: 'Get default block configurations for workflow',
inputStructure: 'detailed',
@@ -3177,14 +3517,14 @@ export const get58 = oc
.output(zGetAppsByAppIdWorkflowsDefaultWorkflowBlockConfigsResponse)
export const defaultWorkflowBlockConfigs = {
- get: get58,
+ get: get68,
byBlockType,
}
/**
* Get conversation variables for workflow
*/
-export const get59 = oc
+export const get69 = oc
.route({
description: 'Get conversation variables for workflow',
inputStructure: 'detailed',
@@ -3199,7 +3539,7 @@ export const get59 = oc
/**
* Update conversation variables for workflow draft
*/
-export const post43 = oc
+export const post45 = oc
.route({
description: 'Update conversation variables for workflow draft',
inputStructure: 'detailed',
@@ -3217,8 +3557,8 @@ export const post43 = oc
.output(zPostAppsByAppIdWorkflowsDraftConversationVariablesResponse)
export const conversationVariables2 = {
- get: get59,
- post: post43,
+ get: get69,
+ post: post45,
}
/**
@@ -3226,7 +3566,7 @@ export const conversationVariables2 = {
*
* Get environment variables for workflow
*/
-export const get60 = oc
+export const get70 = oc
.route({
description: 'Get environment variables for workflow',
inputStructure: 'detailed',
@@ -3242,7 +3582,7 @@ export const get60 = oc
/**
* Update environment variables for workflow draft
*/
-export const post44 = oc
+export const post46 = oc
.route({
description: 'Update environment variables for workflow draft',
inputStructure: 'detailed',
@@ -3260,14 +3600,14 @@ export const post44 = oc
.output(zPostAppsByAppIdWorkflowsDraftEnvironmentVariablesResponse)
export const environmentVariables = {
- get: get60,
- post: post44,
+ get: get70,
+ post: post46,
}
/**
* Update draft workflow features
*/
-export const post45 = oc
+export const post47 = oc
.route({
description: 'Update draft workflow features',
inputStructure: 'detailed',
@@ -3285,7 +3625,7 @@ export const post45 = oc
.output(zPostAppsByAppIdWorkflowsDraftFeaturesResponse)
export const features = {
- post: post45,
+ post: post47,
}
/**
@@ -3293,7 +3633,7 @@ export const features = {
*
* Test human input delivery for workflow
*/
-export const post46 = oc
+export const post48 = oc
.route({
description: 'Test human input delivery for workflow',
inputStructure: 'detailed',
@@ -3312,7 +3652,7 @@ export const post46 = oc
.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdDeliveryTestResponse)
export const deliveryTest = {
- post: post46,
+ post: post48,
}
/**
@@ -3320,7 +3660,7 @@ export const deliveryTest = {
*
* Get human input form preview for workflow
*/
-export const post47 = oc
+export const post49 = oc
.route({
description: 'Get human input form preview for workflow',
inputStructure: 'detailed',
@@ -3338,8 +3678,8 @@ export const post47 = oc
)
.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdFormPreviewResponse)
-export const preview3 = {
- post: post47,
+export const preview5 = {
+ post: post49,
}
/**
@@ -3347,7 +3687,7 @@ export const preview3 = {
*
* Submit human input form preview for workflow
*/
-export const post48 = oc
+export const post50 = oc
.route({
description: 'Submit human input form preview for workflow',
inputStructure: 'detailed',
@@ -3366,11 +3706,11 @@ export const post48 = oc
.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdFormRunResponse)
export const run5 = {
- post: post48,
+ post: post50,
}
export const form2 = {
- preview: preview3,
+ preview: preview5,
run: run5,
}
@@ -3392,7 +3732,7 @@ export const humanInput2 = {
*
* Run draft workflow iteration node
*/
-export const post49 = oc
+export const post51 = oc
.route({
description: 'Run draft workflow iteration node',
inputStructure: 'detailed',
@@ -3411,7 +3751,7 @@ export const post49 = oc
.output(zPostAppsByAppIdWorkflowsDraftIterationNodesByNodeIdRunResponse)
export const run6 = {
- post: post49,
+ post: post51,
}
export const byNodeId6 = {
@@ -3431,7 +3771,7 @@ export const iteration2 = {
*
* Run draft workflow loop node
*/
-export const post50 = oc
+export const post52 = oc
.route({
description: 'Run draft workflow loop node',
inputStructure: 'detailed',
@@ -3450,7 +3790,7 @@ export const post50 = oc
.output(zPostAppsByAppIdWorkflowsDraftLoopNodesByNodeIdRunResponse)
export const run7 = {
- post: post50,
+ post: post52,
}
export const byNodeId7 = {
@@ -3465,7 +3805,7 @@ export const loop2 = {
nodes: nodes6,
}
-export const get61 = oc
+export const get71 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -3479,10 +3819,10 @@ export const get61 = oc
.output(zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerCandidatesResponse)
export const candidates = {
- get: get61,
+ get: get71,
}
-export const post51 = oc
+export const post53 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -3499,10 +3839,10 @@ export const post51 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerCopyFromRosterResponse)
export const copyFromRoster = {
- post: post51,
+ post: post53,
}
-export const post52 = oc
+export const post54 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -3519,10 +3859,10 @@ export const post52 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerImpactResponse)
export const impact = {
- post: post52,
+ post: post54,
}
-export const post53 = oc
+export const post55 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -3539,10 +3879,10 @@ export const post53 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerSaveToRosterResponse)
export const saveToRoster = {
- post: post53,
+ post: post55,
}
-export const post54 = oc
+export const post56 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -3559,10 +3899,10 @@ export const post54 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerValidateResponse)
export const validate = {
- post: post54,
+ post: post56,
}
-export const get62 = oc
+export const get72 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -3595,7 +3935,7 @@ export const put4 = oc
.output(zPutAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerResponse)
export const agentComposer = {
- get: get62,
+ get: get72,
put: put4,
candidates,
copyFromRoster,
@@ -3607,7 +3947,7 @@ export const agentComposer = {
/**
* Get last run result for draft workflow node
*/
-export const get63 = oc
+export const get73 = oc
.route({
description: 'Get last run result for draft workflow node',
inputStructure: 'detailed',
@@ -3620,7 +3960,7 @@ export const get63 = oc
.output(zGetAppsByAppIdWorkflowsDraftNodesByNodeIdLastRunResponse)
export const lastRun = {
- get: get63,
+ get: get73,
}
/**
@@ -3628,7 +3968,7 @@ export const lastRun = {
*
* Run draft workflow node
*/
-export const post55 = oc
+export const post57 = oc
.route({
description: 'Run draft workflow node',
inputStructure: 'detailed',
@@ -3647,7 +3987,7 @@ export const post55 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdRunResponse)
export const run8 = {
- post: post55,
+ post: post57,
}
/**
@@ -3655,7 +3995,7 @@ export const run8 = {
*
* Poll for trigger events and execute single node when event arrives
*/
-export const post56 = oc
+export const post58 = oc
.route({
description: 'Poll for trigger events and execute single node when event arrives',
inputStructure: 'detailed',
@@ -3669,7 +4009,7 @@ export const post56 = oc
.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdTriggerRunResponse)
export const run9 = {
- post: post56,
+ post: post58,
}
export const trigger = {
@@ -3679,7 +4019,7 @@ export const trigger = {
/**
* Delete all variables for a specific node
*/
-export const delete11 = oc
+export const delete13 = oc
.route({
description: 'Delete all variables for a specific node',
inputStructure: 'detailed',
@@ -3695,7 +4035,7 @@ export const delete11 = oc
/**
* Get variables for a specific node
*/
-export const get64 = oc
+export const get74 = oc
.route({
description: 'Get variables for a specific node',
inputStructure: 'detailed',
@@ -3708,8 +4048,8 @@ export const get64 = oc
.output(zGetAppsByAppIdWorkflowsDraftNodesByNodeIdVariablesResponse)
export const variables = {
- delete: delete11,
- get: get64,
+ delete: delete13,
+ get: get74,
}
export const byNodeId8 = {
@@ -3729,7 +4069,7 @@ export const nodes7 = {
*
* Run draft workflow
*/
-export const post57 = oc
+export const post59 = oc
.route({
description: 'Run draft workflow',
inputStructure: 'detailed',
@@ -3748,13 +4088,13 @@ export const post57 = oc
.output(zPostAppsByAppIdWorkflowsDraftRunResponse)
export const run10 = {
- post: post57,
+ post: post59,
}
/**
* Server-Sent Events stream of inspector deltas for a draft workflow run.
*/
-export const get65 = oc
+export const get75 = oc
.route({
description: 'Server-Sent Events stream of inspector deltas for a draft workflow run.',
inputStructure: 'detailed',
@@ -3767,13 +4107,13 @@ export const get65 = oc
.output(zGetAppsByAppIdWorkflowsDraftRunsByRunIdNodeOutputsEventsResponse)
export const events = {
- get: get65,
+ get: get75,
}
/**
* Full value for one declared output, including signed download URL for files.
*/
-export const get66 = oc
+export const get76 = oc
.route({
description: 'Full value for one declared output, including signed download URL for files.',
inputStructure: 'detailed',
@@ -3789,18 +4129,18 @@ export const get66 = oc
)
.output(zGetAppsByAppIdWorkflowsDraftRunsByRunIdNodeOutputsByNodeIdByOutputNamePreviewResponse)
-export const preview4 = {
- get: get66,
+export const preview6 = {
+ get: get76,
}
export const byOutputName = {
- preview: preview4,
+ preview: preview6,
}
/**
* One node's declared outputs for a draft workflow run.
*/
-export const get67 = oc
+export const get77 = oc
.route({
description: 'One node\'s declared outputs for a draft workflow run.',
inputStructure: 'detailed',
@@ -3813,14 +4153,14 @@ export const get67 = oc
.output(zGetAppsByAppIdWorkflowsDraftRunsByRunIdNodeOutputsByNodeIdResponse)
export const byNodeId9 = {
- get: get67,
+ get: get77,
byOutputName,
}
/**
* Snapshot of every node's declared outputs for a draft workflow run.
*/
-export const get68 = oc
+export const get78 = oc
.route({
description: 'Snapshot of every node\'s declared outputs for a draft workflow run.',
inputStructure: 'detailed',
@@ -3833,7 +4173,7 @@ export const get68 = oc
.output(zGetAppsByAppIdWorkflowsDraftRunsByRunIdNodeOutputsResponse)
export const nodeOutputs = {
- get: get68,
+ get: get78,
events,
byNodeId: byNodeId9,
}
@@ -3849,7 +4189,7 @@ export const runs = {
/**
* Get system variables for workflow
*/
-export const get69 = oc
+export const get79 = oc
.route({
description: 'Get system variables for workflow',
inputStructure: 'detailed',
@@ -3862,7 +4202,7 @@ export const get69 = oc
.output(zGetAppsByAppIdWorkflowsDraftSystemVariablesResponse)
export const systemVariables = {
- get: get69,
+ get: get79,
}
/**
@@ -3870,7 +4210,7 @@ export const systemVariables = {
*
* Poll for trigger events and execute full workflow when event arrives
*/
-export const post58 = oc
+export const post60 = oc
.route({
description: 'Poll for trigger events and execute full workflow when event arrives',
inputStructure: 'detailed',
@@ -3889,7 +4229,7 @@ export const post58 = oc
.output(zPostAppsByAppIdWorkflowsDraftTriggerRunResponse)
export const run11 = {
- post: post58,
+ post: post60,
}
/**
@@ -3897,7 +4237,7 @@ export const run11 = {
*
* Full workflow debug when the start node is a trigger
*/
-export const post59 = oc
+export const post61 = oc
.route({
description: 'Full workflow debug when the start node is a trigger',
inputStructure: 'detailed',
@@ -3916,7 +4256,7 @@ export const post59 = oc
.output(zPostAppsByAppIdWorkflowsDraftTriggerRunAllResponse)
export const runAll = {
- post: post59,
+ post: post61,
}
export const trigger2 = {
@@ -3946,7 +4286,7 @@ export const reset = {
/**
* Delete a workflow variable
*/
-export const delete12 = oc
+export const delete14 = oc
.route({
description: 'Delete a workflow variable',
inputStructure: 'detailed',
@@ -3962,7 +4302,7 @@ export const delete12 = oc
/**
* Get a specific workflow variable
*/
-export const get70 = oc
+export const get80 = oc
.route({
description: 'Get a specific workflow variable',
inputStructure: 'detailed',
@@ -3995,8 +4335,8 @@ export const patch2 = oc
.output(zPatchAppsByAppIdWorkflowsDraftVariablesByVariableIdResponse)
export const byVariableId = {
- delete: delete12,
- get: get70,
+ delete: delete14,
+ get: get80,
patch: patch2,
reset,
}
@@ -4004,7 +4344,7 @@ export const byVariableId = {
/**
* Delete all draft workflow variables
*/
-export const delete13 = oc
+export const delete15 = oc
.route({
description: 'Delete all draft workflow variables',
inputStructure: 'detailed',
@@ -4022,7 +4362,7 @@ export const delete13 = oc
*
* Get draft workflow variables
*/
-export const get71 = oc
+export const get81 = oc
.route({
description: 'Get draft workflow variables',
inputStructure: 'detailed',
@@ -4041,8 +4381,8 @@ export const get71 = oc
.output(zGetAppsByAppIdWorkflowsDraftVariablesResponse)
export const variables2 = {
- delete: delete13,
- get: get71,
+ delete: delete15,
+ get: get81,
byVariableId,
}
@@ -4051,7 +4391,7 @@ export const variables2 = {
*
* Get draft workflow for an application
*/
-export const get72 = oc
+export const get82 = oc
.route({
description: 'Get draft workflow for an application',
inputStructure: 'detailed',
@@ -4069,7 +4409,7 @@ export const get72 = oc
*
* Sync draft workflow configuration
*/
-export const post60 = oc
+export const post62 = oc
.route({
description: 'Sync draft workflow configuration',
inputStructure: 'detailed',
@@ -4088,8 +4428,8 @@ export const post60 = oc
.output(zPostAppsByAppIdWorkflowsDraftResponse)
export const draft2 = {
- get: get72,
- post: post60,
+ get: get82,
+ post: post62,
conversationVariables: conversationVariables2,
environmentVariables,
features,
@@ -4109,7 +4449,7 @@ export const draft2 = {
*
* Get published workflow for an application
*/
-export const get73 = oc
+export const get83 = oc
.route({
description: 'Get published workflow for an application',
inputStructure: 'detailed',
@@ -4125,7 +4465,7 @@ export const get73 = oc
/**
* Publish workflow
*/
-export const post61 = oc
+export const post63 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4143,14 +4483,14 @@ export const post61 = oc
.output(zPostAppsByAppIdWorkflowsPublishResponse)
export const publish = {
- get: get73,
- post: post61,
+ get: get83,
+ post: post63,
}
/**
* Server-Sent Events stream of inspector deltas for a published workflow run.
*/
-export const get74 = oc
+export const get84 = oc
.route({
description: 'Server-Sent Events stream of inspector deltas for a published workflow run.',
inputStructure: 'detailed',
@@ -4163,13 +4503,13 @@ export const get74 = oc
.output(zGetAppsByAppIdWorkflowsPublishedRunsByRunIdNodeOutputsEventsResponse)
export const events2 = {
- get: get74,
+ get: get84,
}
/**
* Full value for one declared output of a published run.
*/
-export const get75 = oc
+export const get85 = oc
.route({
description: 'Full value for one declared output of a published run.',
inputStructure: 'detailed',
@@ -4189,18 +4529,18 @@ export const get75 = oc
zGetAppsByAppIdWorkflowsPublishedRunsByRunIdNodeOutputsByNodeIdByOutputNamePreviewResponse,
)
-export const preview5 = {
- get: get75,
+export const preview7 = {
+ get: get85,
}
export const byOutputName2 = {
- preview: preview5,
+ preview: preview7,
}
/**
* One node's declared outputs for a published workflow run.
*/
-export const get76 = oc
+export const get86 = oc
.route({
description: 'One node\'s declared outputs for a published workflow run.',
inputStructure: 'detailed',
@@ -4213,14 +4553,14 @@ export const get76 = oc
.output(zGetAppsByAppIdWorkflowsPublishedRunsByRunIdNodeOutputsByNodeIdResponse)
export const byNodeId10 = {
- get: get76,
+ get: get86,
byOutputName: byOutputName2,
}
/**
* Snapshot of every node's declared outputs for a published workflow run.
*/
-export const get77 = oc
+export const get87 = oc
.route({
description: 'Snapshot of every node\'s declared outputs for a published workflow run.',
inputStructure: 'detailed',
@@ -4233,7 +4573,7 @@ export const get77 = oc
.output(zGetAppsByAppIdWorkflowsPublishedRunsByRunIdNodeOutputsResponse)
export const nodeOutputs2 = {
- get: get77,
+ get: get87,
events: events2,
byNodeId: byNodeId10,
}
@@ -4253,7 +4593,7 @@ export const published = {
/**
* Get webhook trigger for a node
*/
-export const get78 = oc
+export const get88 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -4271,7 +4611,7 @@ export const get78 = oc
.output(zGetAppsByAppIdWorkflowsTriggersWebhookResponse)
export const webhook = {
- get: get78,
+ get: get88,
}
export const triggers2 = {
@@ -4281,7 +4621,7 @@ export const triggers2 = {
/**
* Restore a published workflow version into the draft workflow
*/
-export const post62 = oc
+export const post64 = oc
.route({
description: 'Restore a published workflow version into the draft workflow',
inputStructure: 'detailed',
@@ -4294,13 +4634,13 @@ export const post62 = oc
.output(zPostAppsByAppIdWorkflowsByWorkflowIdRestoreResponse)
export const restore = {
- post: post62,
+ post: post64,
}
/**
* Delete workflow
*/
-export const delete14 = oc
+export const delete16 = oc
.route({
inputStructure: 'detailed',
method: 'DELETE',
@@ -4337,7 +4677,7 @@ export const patch3 = oc
.output(zPatchAppsByAppIdWorkflowsByWorkflowIdResponse)
export const byWorkflowId = {
- delete: delete14,
+ delete: delete16,
patch: patch3,
restore,
}
@@ -4347,7 +4687,7 @@ export const byWorkflowId = {
*
* Get all published workflows for an application
*/
-export const get79 = oc
+export const get89 = oc
.route({
description: 'Get all published workflows for an application',
inputStructure: 'detailed',
@@ -4366,7 +4706,7 @@ export const get79 = oc
.output(zGetAppsByAppIdWorkflowsResponse)
export const workflows3 = {
- get: get79,
+ get: get89,
defaultWorkflowBlockConfigs,
draft: draft2,
publish,
@@ -4380,7 +4720,7 @@ export const workflows3 = {
*
* Delete application
*/
-export const delete15 = oc
+export const delete17 = oc
.route({
description: 'Delete application',
inputStructure: 'detailed',
@@ -4399,7 +4739,7 @@ export const delete15 = oc
*
* Get application details
*/
-export const get80 = oc
+export const get90 = oc
.route({
description: 'Get application details',
inputStructure: 'detailed',
@@ -4431,8 +4771,8 @@ export const put6 = oc
.output(zPutAppsByAppIdResponse)
export const byAppId2 = {
- delete: delete15,
- get: get80,
+ delete: delete17,
+ get: get90,
put: put6,
advancedChat,
agent,
@@ -4478,7 +4818,7 @@ export const byAppId2 = {
*
* Delete an API key for an app
*/
-export const delete16 = oc
+export const delete18 = oc
.route({
description: 'Delete an API key for an app',
inputStructure: 'detailed',
@@ -4493,7 +4833,7 @@ export const delete16 = oc
.output(zDeleteAppsByResourceIdApiKeysByApiKeyIdResponse)
export const byApiKeyId = {
- delete: delete16,
+ delete: delete18,
}
/**
@@ -4501,7 +4841,7 @@ export const byApiKeyId = {
*
* Get all API keys for an app
*/
-export const get81 = oc
+export const get91 = oc
.route({
description: 'Get all API keys for an app',
inputStructure: 'detailed',
@@ -4519,7 +4859,7 @@ export const get81 = oc
*
* Create a new API key for an app
*/
-export const post63 = oc
+export const post65 = oc
.route({
description: 'Create a new API key for an app',
inputStructure: 'detailed',
@@ -4534,8 +4874,8 @@ export const post63 = oc
.output(zPostAppsByResourceIdApiKeysResponse)
export const apiKeys = {
- get: get81,
- post: post63,
+ get: get91,
+ post: post65,
byApiKeyId,
}
@@ -4546,7 +4886,7 @@ export const byResourceId = {
/**
* Refresh MCP server configuration and regenerate server code
*/
-export const get82 = oc
+export const get92 = oc
.route({
description: 'Refresh MCP server configuration and regenerate server code',
inputStructure: 'detailed',
@@ -4559,7 +4899,7 @@ export const get82 = oc
.output(zGetAppsByServerIdServerRefreshResponse)
export const refresh = {
- get: get82,
+ get: get92,
}
export const server2 = {
@@ -4575,7 +4915,7 @@ export const byServerId = {
*
* Get list of applications with pagination and filtering
*/
-export const get83 = oc
+export const get93 = oc
.route({
description: 'Get list of applications with pagination and filtering',
inputStructure: 'detailed',
@@ -4593,7 +4933,7 @@ export const get83 = oc
*
* Create a new application
*/
-export const post64 = oc
+export const post66 = oc
.route({
description: 'Create a new application',
inputStructure: 'detailed',
@@ -4608,8 +4948,8 @@ export const post64 = oc
.output(zPostAppsResponse)
export const apps = {
- get: get83,
- post: post64,
+ get: get93,
+ post: post66,
imports,
starred,
workflows,
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index b8f44b27f12..0354f6cde86 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -177,6 +177,82 @@ export type AdvancedChatWorkflowRunPayload = {
query?: string
}
+export type AgentConfigFileListResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ items?: Array<AgentConfigFileItemResponse>
+}
+
+export type AgentConfigFileUploadPayload = {
+ upload_file_id: string
+}
+
+export type AgentConfigFileUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ file: AgentConfigFileItemResponse
+}
+
+export type AgentConfigDeleteResponse = {
+ removed_names?: Array<string>
+ result: 'success'
+}
+
+export type AgentConfigDownloadResponse = {
+ url: string
+}
+
+export type AgentConfigFilePreviewResponse = {
+ binary: boolean
+ name: string
+ size?: number | null
+ text?: string | null
+ truncated: boolean
+}
+
+export type AgentConfigManifestResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ env_keys?: Array<string>
+ files?: AgentConfigFileItemsResponse
+ note?: string
+ skills?: AgentConfigSkillItemsResponse
+}
+
+export type AgentConfigSkillListResponse = {
+ agent_id: string
+ config_version: AgentConfigVersionResponse
+ items?: Array<AgentConfigSkillItemResponse>
+}
+
+export type AgentConfigSkillUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ skill: AgentConfigSkillItemResponse
+}
+
+export type AgentConfigSkillFilePreviewResponse = {
+ binary: boolean
+ path: string
+ size?: number | null
+ text?: string | null
+ truncated: boolean
+}
+
+export type AgentConfigSkillInspectResponse = {
+ description?: string
+ file_tree?: Array<{
+ [key: string]: unknown
+ }> | null
+ files?: Array<AgentConfigSkillFileResponse>
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+ skill_md: AgentConfigSkillMarkdownResponse
+ source: 'config_skill_zip'
+ warnings?: Array<string>
+}
+
export type AgentDriveListResponse = {
items?: Array<AgentDriveItemResponse>
}
@@ -975,6 +1051,9 @@ export type WorkflowAgentComposerResponse = {
backing_app_id?: string | null
binding?: AgentComposerBindingResponse | null
chat_endpoint?: string | null
+ debug_conversation_has_messages?: boolean
+ debug_conversation_id?: string | null
+ debug_conversation_message_count?: number
effective_declared_outputs?: Array<DeclaredOutputConfig>
hidden_app_backed?: boolean
impact_summary?: AgentComposerImpactResponse | null
@@ -1318,6 +1397,55 @@ export type AdvancedChatWorkflowRunForListResponse = {
version?: string | null
}
+export type AgentConfigVersionResponse = {
+ id: string
+ kind: 'build_draft' | 'draft' | 'snapshot'
+ writable: boolean
+}
+
+export type AgentConfigFileItemResponse = {
+ file_id?: string | null
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigFileItemsResponse = {
+ items?: Array<AgentConfigFileItemResponse>
+}
+
+export type AgentConfigSkillItemsResponse = {
+ items?: Array<AgentConfigSkillItemResponse>
+}
+
+export type AgentConfigSkillItemResponse = {
+ description?: string
+ file_id?: string | null
+ hash?: string | null
+ id: string
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigSkillFileResponse = {
+ downloadable: boolean
+ name: string
+ path: string
+ previewable: boolean
+ type: 'directory' | 'file'
+}
+
+export type AgentConfigSkillMarkdownResponse = {
+ binary: false
+ path: 'SKILL.md'
+ size?: number | null
+ text: string
+ truncated: boolean
+}
+
export type AgentDriveItemResponse = {
created_at?: number | null
file_kind: string
@@ -1820,6 +1948,9 @@ export type AgentComposerAgentResponse = {
export type AgentSoulConfig = {
app_features?: AgentSoulAppFeaturesConfig
app_variables?: Array<AppVariableConfig>
+ config_files?: Array<AgentConfigFileRefConfig>
+ config_note?: string
+ config_skills?: Array<AgentConfigSkillRefConfig>
env?: AgentSoulEnvConfig
files?: AgentSoulFilesConfig
human?: AgentSoulHumanConfig
@@ -2152,6 +2283,25 @@ export type AppVariableConfig = {
type: string
}
+export type AgentConfigFileRefConfig = {
+ file_id: string
+ file_kind: 'tool_file' | 'upload_file'
+ hash?: string | null
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
+export type AgentConfigSkillRefConfig = {
+ description?: string
+ file_id: string
+ file_kind?: 'tool_file'
+ hash?: string | null
+ mime_type?: string | null
+ name: string
+ size?: number | null
+}
+
export type AgentSoulEnvConfig = {
secret_refs?: Array<AgentSecretRefConfig>
variables?: Array<AgentEnvVariableConfig>
@@ -3227,6 +3377,297 @@ export type PostAppsByAppIdAdvancedChatWorkflowsDraftRunResponses = {
export type PostAppsByAppIdAdvancedChatWorkflowsDraftRunResponse
= PostAppsByAppIdAdvancedChatWorkflowsDraftRunResponses[keyof PostAppsByAppIdAdvancedChatWorkflowsDraftRunResponses]
+export type GetAppsByAppIdAgentConfigFilesData = {
+ body?: never
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files'
+}
+
+export type GetAppsByAppIdAgentConfigFilesResponses = {
+ 200: AgentConfigFileListResponse
+}
+
+export type GetAppsByAppIdAgentConfigFilesResponse
+ = GetAppsByAppIdAgentConfigFilesResponses[keyof GetAppsByAppIdAgentConfigFilesResponses]
+
+export type PostAppsByAppIdAgentConfigFilesData = {
+ body: AgentConfigFileUploadPayload
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files'
+}
+
+export type PostAppsByAppIdAgentConfigFilesResponses = {
+ 201: AgentConfigFileUploadResponse
+}
+
+export type PostAppsByAppIdAgentConfigFilesResponse
+ = PostAppsByAppIdAgentConfigFilesResponses[keyof PostAppsByAppIdAgentConfigFilesResponses]
+
+export type DeleteAppsByAppIdAgentConfigFilesByNameData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files/{name}'
+}
+
+export type DeleteAppsByAppIdAgentConfigFilesByNameResponses = {
+ 200: AgentConfigDeleteResponse
+}
+
+export type DeleteAppsByAppIdAgentConfigFilesByNameResponse
+ = DeleteAppsByAppIdAgentConfigFilesByNameResponses[keyof DeleteAppsByAppIdAgentConfigFilesByNameResponses]
+
+export type GetAppsByAppIdAgentConfigFilesByNameDownloadData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files/{name}/download'
+}
+
+export type GetAppsByAppIdAgentConfigFilesByNameDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAppsByAppIdAgentConfigFilesByNameDownloadResponse
+ = GetAppsByAppIdAgentConfigFilesByNameDownloadResponses[keyof GetAppsByAppIdAgentConfigFilesByNameDownloadResponses]
+
+export type GetAppsByAppIdAgentConfigFilesByNamePreviewData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files/{name}/preview'
+}
+
+export type GetAppsByAppIdAgentConfigFilesByNamePreviewResponses = {
+ 200: AgentConfigFilePreviewResponse
+}
+
+export type GetAppsByAppIdAgentConfigFilesByNamePreviewResponse
+ = GetAppsByAppIdAgentConfigFilesByNamePreviewResponses[keyof GetAppsByAppIdAgentConfigFilesByNamePreviewResponses]
+
+export type GetAppsByAppIdAgentConfigManifestData = {
+ body?: never
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/manifest'
+}
+
+export type GetAppsByAppIdAgentConfigManifestResponses = {
+ 200: AgentConfigManifestResponse
+}
+
+export type GetAppsByAppIdAgentConfigManifestResponse
+ = GetAppsByAppIdAgentConfigManifestResponses[keyof GetAppsByAppIdAgentConfigManifestResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsData = {
+ body?: never
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsResponses = {
+ 200: AgentConfigSkillListResponse
+}
+
+export type GetAppsByAppIdAgentConfigSkillsResponse
+ = GetAppsByAppIdAgentConfigSkillsResponses[keyof GetAppsByAppIdAgentConfigSkillsResponses]
+
+export type PostAppsByAppIdAgentConfigSkillsUploadData = {
+ body: {
+ file: Blob | File
+ }
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/upload'
+}
+
+export type PostAppsByAppIdAgentConfigSkillsUploadResponses = {
+ 201: AgentConfigSkillUploadResponse
+}
+
+export type PostAppsByAppIdAgentConfigSkillsUploadResponse
+ = PostAppsByAppIdAgentConfigSkillsUploadResponses[keyof PostAppsByAppIdAgentConfigSkillsUploadResponses]
+
+export type DeleteAppsByAppIdAgentConfigSkillsByNameData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/{name}'
+}
+
+export type DeleteAppsByAppIdAgentConfigSkillsByNameResponses = {
+ 200: AgentConfigDeleteResponse
+}
+
+export type DeleteAppsByAppIdAgentConfigSkillsByNameResponse
+ = DeleteAppsByAppIdAgentConfigSkillsByNameResponses[keyof DeleteAppsByAppIdAgentConfigSkillsByNameResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsByNameDownloadData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/{name}/download'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameDownloadResponse
+ = GetAppsByAppIdAgentConfigSkillsByNameDownloadResponses[keyof GetAppsByAppIdAgentConfigSkillsByNameDownloadResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesContentData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: never
+ url: '/apps/{app_id}/agent/config/skills/{name}/files/content'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesContentResponses = {
+ 200: {
+ [key: string]: unknown
+ }
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesContentResponse
+ = GetAppsByAppIdAgentConfigSkillsByNameFilesContentResponses[keyof GetAppsByAppIdAgentConfigSkillsByNameFilesContentResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesDownloadData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ path: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/{name}/files/download'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponses = {
+ 200: AgentConfigDownloadResponse
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponse
+ = GetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponses[keyof GetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesPreviewData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ path: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/{name}/files/preview'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponses = {
+ 200: AgentConfigSkillFilePreviewResponse
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponse
+ = GetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponses[keyof GetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponses]
+
+export type GetAppsByAppIdAgentConfigSkillsByNameInspectData = {
+ body?: never
+ path: {
+ app_id: string
+ name: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/skills/{name}/inspect'
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameInspectResponses = {
+ 200: AgentConfigSkillInspectResponse
+}
+
+export type GetAppsByAppIdAgentConfigSkillsByNameInspectResponse
+ = GetAppsByAppIdAgentConfigSkillsByNameInspectResponses[keyof GetAppsByAppIdAgentConfigSkillsByNameInspectResponses]
+
export type GetAppsByAppIdAgentDriveFilesData = {
body?: never
path: {
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 89afe8f3ddf..bff73e75da9 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -98,6 +98,50 @@ export const zAdvancedChatWorkflowRunPayload = z.object({
query: z.string().optional().default(''),
})
+/**
+ * AgentConfigFileUploadPayload
+ */
+export const zAgentConfigFileUploadPayload = z.object({
+ upload_file_id: z.string(),
+})
+
+/**
+ * AgentConfigDeleteResponse
+ */
+export const zAgentConfigDeleteResponse = z.object({
+ removed_names: z.array(z.string()).optional(),
+ result: z.literal('success'),
+})
+
+/**
+ * AgentConfigDownloadResponse
+ */
+export const zAgentConfigDownloadResponse = z.object({
+ url: z.string(),
+})
+
+/**
+ * AgentConfigFilePreviewResponse
+ */
+export const zAgentConfigFilePreviewResponse = z.object({
+ binary: z.boolean(),
+ name: z.string(),
+ size: z.int().nullish(),
+ text: z.string().nullish(),
+ truncated: z.boolean(),
+})
+
+/**
+ * AgentConfigSkillFilePreviewResponse
+ */
+export const zAgentConfigSkillFilePreviewResponse = z.object({
+ binary: z.boolean(),
+ path: z.string(),
+ size: z.int().nullish(),
+ text: z.string().nullish(),
+ truncated: z.boolean(),
+})
+
/**
* AgentDriveDownloadResponse
*/
@@ -932,6 +976,139 @@ export const zImport = z.object({
status: zImportStatus,
})
+/**
+ * AgentConfigVersionResponse
+ */
+export const zAgentConfigVersionResponse = z.object({
+ id: z.string(),
+ kind: z.enum(['build_draft', 'draft', 'snapshot']),
+ writable: z.boolean(),
+})
+
+/**
+ * AgentConfigFileItemResponse
+ */
+export const zAgentConfigFileItemResponse = z.object({
+ file_id: z.string().nullish(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigFileListResponse
+ */
+export const zAgentConfigFileListResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ items: z.array(zAgentConfigFileItemResponse).optional(),
+})
+
+/**
+ * AgentConfigFileUploadResponse
+ */
+export const zAgentConfigFileUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ file: zAgentConfigFileItemResponse,
+})
+
+/**
+ * AgentConfigFileItemsResponse
+ */
+export const zAgentConfigFileItemsResponse = z.object({
+ items: z.array(zAgentConfigFileItemResponse).optional(),
+})
+
+/**
+ * AgentConfigSkillItemResponse
+ */
+export const zAgentConfigSkillItemResponse = z.object({
+ description: z.string().optional().default(''),
+ file_id: z.string().nullish(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigSkillListResponse
+ */
+export const zAgentConfigSkillListResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ items: z.array(zAgentConfigSkillItemResponse).optional(),
+})
+
+/**
+ * AgentConfigSkillUploadResponse
+ */
+export const zAgentConfigSkillUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ skill: zAgentConfigSkillItemResponse,
+})
+
+/**
+ * AgentConfigSkillItemsResponse
+ */
+export const zAgentConfigSkillItemsResponse = z.object({
+ items: z.array(zAgentConfigSkillItemResponse).optional(),
+})
+
+/**
+ * AgentConfigManifestResponse
+ */
+export const zAgentConfigManifestResponse = z.object({
+ agent_id: z.string(),
+ config_version: zAgentConfigVersionResponse,
+ env_keys: z.array(z.string()).optional(),
+ files: zAgentConfigFileItemsResponse.optional(),
+ note: z.string().optional().default(''),
+ skills: zAgentConfigSkillItemsResponse.optional(),
+})
+
+/**
+ * AgentConfigSkillFileResponse
+ */
+export const zAgentConfigSkillFileResponse = z.object({
+ downloadable: z.boolean(),
+ name: z.string(),
+ path: z.string(),
+ previewable: z.boolean(),
+ type: z.enum(['directory', 'file']),
+})
+
+/**
+ * AgentConfigSkillMarkdownResponse
+ */
+export const zAgentConfigSkillMarkdownResponse = z.object({
+ binary: z.literal(false),
+ path: z.literal('SKILL.md'),
+ size: z.int().nullish(),
+ text: z.string(),
+ truncated: z.boolean(),
+})
+
+/**
+ * AgentConfigSkillInspectResponse
+ */
+export const zAgentConfigSkillInspectResponse = z.object({
+ description: z.string().optional().default(''),
+ file_tree: z.array(z.record(z.string(), z.unknown())).nullish(),
+ files: z.array(zAgentConfigSkillFileResponse).optional(),
+ hash: z.string().nullish(),
+ id: z.string(),
+ mime_type: z.string().nullish(),
+ name: z.string(),
+ size: z.int().nullish(),
+ skill_md: zAgentConfigSkillMarkdownResponse,
+ source: z.literal('config_skill_zip'),
+ warnings: z.array(z.string()).optional(),
+})
+
/**
* AgentDriveItemResponse
*/
@@ -2542,6 +2719,35 @@ export const zAppVariableConfig = z.object({
type: z.string().min(1).max(64),
})
+/**
+ * AgentConfigFileRefConfig
+ *
+ * Stable Agent Soul reference to one config file payload.
+ */
+export const zAgentConfigFileRefConfig = z.object({
+ file_id: z.string().min(1).max(255),
+ file_kind: z.enum(['tool_file', 'upload_file']),
+ hash: z.string().nullish(),
+ mime_type: z.string().nullish(),
+ name: z.string().min(1).max(255),
+ size: z.int().nullish(),
+})
+
+/**
+ * AgentConfigSkillRefConfig
+ *
+ * Stable Agent Soul reference to one normalized skill archive.
+ */
+export const zAgentConfigSkillRefConfig = z.object({
+ description: z.string().optional().default(''),
+ file_id: z.string().min(1).max(255),
+ file_kind: z.literal('tool_file').optional().default('tool_file'),
+ hash: z.string().nullish(),
+ mime_type: z.string().nullish().default('application/zip'),
+ name: z.string().min(1).max(255),
+ size: z.int().nullish(),
+})
+
/**
* AgentSoulPromptConfig
*/
@@ -3232,12 +3438,15 @@ export const zAgentSoulDifyToolCredentialRef = z.object({
/**
* AgentSoulDifyToolConfig
*
- * One Dify Plugin Tool configured on Agent Soul.
+ * One Dify tool configured on Agent Soul.
*
* The API backend prepares this persisted product shape into
- * ``DifyPluginToolConfig`` before sending a run request to Agent backend.
- * ``provider_id`` keeps compatibility with existing Agent tool config payloads;
- * new callers should send ``plugin_id`` + ``provider`` when available.
+ * either ``DifyPluginToolConfig`` or ``DifyCoreToolConfig`` before sending a
+ * run request to Agent backend. ``plugin`` providers keep the direct
+ * ``dify.plugin.tools`` transport; ``builtin`` / ``api`` / ``workflow`` /
+ * ``mcp`` providers are prepared for ``dify.core.tools``. ``provider_id``
+ * keeps compatibility with existing Agent tool config payloads; new callers
+ * should send ``plugin_id`` + ``provider`` when available.
*/
export const zAgentSoulDifyToolConfig = z.object({
credential_ref: zAgentSoulDifyToolCredentialRef.nullish(),
@@ -3635,6 +3844,9 @@ export const zAgentSoulKnowledgeConfig = z.object({
export const zAgentSoulConfig = z.object({
app_features: zAgentSoulAppFeaturesConfig.optional(),
app_variables: z.array(zAppVariableConfig).optional(),
+ config_files: z.array(zAgentConfigFileRefConfig).optional(),
+ config_note: z.string().optional().default(''),
+ config_skills: z.array(zAgentConfigSkillRefConfig).optional(),
env: zAgentSoulEnvConfig.optional(),
files: zAgentSoulFilesConfig.optional(),
human: zAgentSoulHumanConfig.optional(),
@@ -3659,6 +3871,9 @@ export const zWorkflowAgentComposerResponse = z.object({
backing_app_id: z.string().nullish(),
binding: zAgentComposerBindingResponse.nullish(),
chat_endpoint: z.string().nullish(),
+ debug_conversation_has_messages: z.boolean().optional().default(false),
+ debug_conversation_id: z.string().nullish(),
+ debug_conversation_message_count: z.int().optional().default(0),
effective_declared_outputs: z.array(zDeclaredOutputConfig).optional(),
hidden_app_backed: z.boolean().optional().default(false),
impact_summary: zAgentComposerImpactResponse.nullish(),
@@ -4110,6 +4325,233 @@ export const zPostAppsByAppIdAdvancedChatWorkflowsDraftRunPath = z.object({
*/
export const zPostAppsByAppIdAdvancedChatWorkflowsDraftRunResponse = zGeneratedAppResponse
+export const zGetAppsByAppIdAgentConfigFilesPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zGetAppsByAppIdAgentConfigFilesQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config files
+ */
+export const zGetAppsByAppIdAgentConfigFilesResponse = zAgentConfigFileListResponse
+
+export const zPostAppsByAppIdAgentConfigFilesBody = zAgentConfigFileUploadPayload
+
+export const zPostAppsByAppIdAgentConfigFilesPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zPostAppsByAppIdAgentConfigFilesQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Uploaded config file
+ */
+export const zPostAppsByAppIdAgentConfigFilesResponse = zAgentConfigFileUploadResponse
+
+export const zDeleteAppsByAppIdAgentConfigFilesByNamePath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zDeleteAppsByAppIdAgentConfigFilesByNameQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config file deleted
+ */
+export const zDeleteAppsByAppIdAgentConfigFilesByNameResponse = zAgentConfigDeleteResponse
+
+export const zGetAppsByAppIdAgentConfigFilesByNameDownloadPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigFilesByNameDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config file download URL
+ */
+export const zGetAppsByAppIdAgentConfigFilesByNameDownloadResponse = zAgentConfigDownloadResponse
+
+export const zGetAppsByAppIdAgentConfigFilesByNamePreviewPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigFilesByNamePreviewQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Preview
+ */
+export const zGetAppsByAppIdAgentConfigFilesByNamePreviewResponse = zAgentConfigFilePreviewResponse
+
+export const zGetAppsByAppIdAgentConfigManifestPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zGetAppsByAppIdAgentConfigManifestQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Agent config manifest
+ */
+export const zGetAppsByAppIdAgentConfigManifestResponse = zAgentConfigManifestResponse
+
+export const zGetAppsByAppIdAgentConfigSkillsPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zGetAppsByAppIdAgentConfigSkillsQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skills
+ */
+export const zGetAppsByAppIdAgentConfigSkillsResponse = zAgentConfigSkillListResponse
+
+export const zPostAppsByAppIdAgentConfigSkillsUploadBody = z.object({
+ file: z.custom<Blob | File>(),
+})
+
+export const zPostAppsByAppIdAgentConfigSkillsUploadPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zPostAppsByAppIdAgentConfigSkillsUploadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Uploaded config skill
+ */
+export const zPostAppsByAppIdAgentConfigSkillsUploadResponse = zAgentConfigSkillUploadResponse
+
+export const zDeleteAppsByAppIdAgentConfigSkillsByNamePath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zDeleteAppsByAppIdAgentConfigSkillsByNameQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill deleted
+ */
+export const zDeleteAppsByAppIdAgentConfigSkillsByNameResponse = zAgentConfigDeleteResponse
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameDownloadPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill download URL
+ */
+export const zGetAppsByAppIdAgentConfigSkillsByNameDownloadResponse = zAgentConfigDownloadResponse
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesContentPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+/**
+ * Success
+ */
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesContentResponse = z.record(
+ z.string(),
+ z.unknown(),
+)
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ path: z.string(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill file download URL
+ */
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesDownloadResponse
+ = zAgentConfigDownloadResponse
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ path: z.string(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill file preview
+ */
+export const zGetAppsByAppIdAgentConfigSkillsByNameFilesPreviewResponse
+ = zAgentConfigSkillFilePreviewResponse
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameInspectPath = z.object({
+ app_id: z.uuid(),
+ name: z.string(),
+})
+
+export const zGetAppsByAppIdAgentConfigSkillsByNameInspectQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Config skill inspect view
+ */
+export const zGetAppsByAppIdAgentConfigSkillsByNameInspectResponse
+ = zAgentConfigSkillInspectResponse
+
export const zGetAppsByAppIdAgentDriveFilesPath = z.object({
app_id: z.uuid(),
})
diff --git a/packages/contracts/generated/api/console/orpc.gen.ts b/packages/contracts/generated/api/console/orpc.gen.ts
index 89b2865fd77..035163b9fb7 100644
--- a/packages/contracts/generated/api/console/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/orpc.gen.ts
@@ -4,44 +4,67 @@ export const contractLoaders = {
account: () => import('./account/orpc.gen').then(({ account }) => ({ account })),
activate: () => import('./activate/orpc.gen').then(({ activate }) => ({ activate })),
agent: () => import('./agent/orpc.gen').then(({ agent }) => ({ agent })),
- allWorkspaces: () => import('./all-workspaces/orpc.gen').then(({ allWorkspaces }) => ({ allWorkspaces })),
- apiBasedExtension: () => import('./api-based-extension/orpc.gen').then(({ apiBasedExtension }) => ({ apiBasedExtension })),
+ allWorkspaces: () =>
+ import('./all-workspaces/orpc.gen').then(({ allWorkspaces }) => ({ allWorkspaces })),
+ apiBasedExtension: () =>
+ import('./api-based-extension/orpc.gen').then(({ apiBasedExtension }) => ({
+ apiBasedExtension,
+ })),
apiKeyAuth: () => import('./api-key-auth/orpc.gen').then(({ apiKeyAuth }) => ({ apiKeyAuth })),
app: () => import('./app/orpc.gen').then(({ app }) => ({ app })),
- appDslVersion: () => import('./app-dsl-version/orpc.gen').then(({ appDslVersion }) => ({ appDslVersion })),
+ appDslVersion: () =>
+ import('./app-dsl-version/orpc.gen').then(({ appDslVersion }) => ({ appDslVersion })),
apps: () => import('./apps/orpc.gen').then(({ apps }) => ({ apps })),
auth: () => import('./auth/orpc.gen').then(({ auth }) => ({ auth })),
billing: () => import('./billing/orpc.gen').then(({ billing }) => ({ billing })),
- codeBasedExtension: () => import('./code-based-extension/orpc.gen').then(({ codeBasedExtension }) => ({ codeBasedExtension })),
+ codeBasedExtension: () =>
+ import('./code-based-extension/orpc.gen').then(({ codeBasedExtension }) => ({
+ codeBasedExtension,
+ })),
compliance: () => import('./compliance/orpc.gen').then(({ compliance }) => ({ compliance })),
dataSource: () => import('./data-source/orpc.gen').then(({ dataSource }) => ({ dataSource })),
datasets: () => import('./datasets/orpc.gen').then(({ datasets }) => ({ datasets })),
- emailCodeLogin: () => import('./email-code-login/orpc.gen').then(({ emailCodeLogin }) => ({ emailCodeLogin })),
- emailRegister: () => import('./email-register/orpc.gen').then(({ emailRegister }) => ({ emailRegister })),
+ emailCodeLogin: () =>
+ import('./email-code-login/orpc.gen').then(({ emailCodeLogin }) => ({ emailCodeLogin })),
+ emailRegister: () =>
+ import('./email-register/orpc.gen').then(({ emailRegister }) => ({ emailRegister })),
explore: () => import('./explore/orpc.gen').then(({ explore }) => ({ explore })),
features: () => import('./features/orpc.gen').then(({ features }) => ({ features })),
files: () => import('./files/orpc.gen').then(({ files }) => ({ files })),
- forgotPassword: () => import('./forgot-password/orpc.gen').then(({ forgotPassword }) => ({ forgotPassword })),
+ forgotPassword: () =>
+ import('./forgot-password/orpc.gen').then(({ forgotPassword }) => ({ forgotPassword })),
form: () => import('./form/orpc.gen').then(({ form }) => ({ form })),
info: () => import('./info/orpc.gen').then(({ info }) => ({ info })),
- installedApps: () => import('./installed-apps/orpc.gen').then(({ installedApps }) => ({ installedApps })),
- instructionGenerate: () => import('./instruction-generate/orpc.gen').then(({ instructionGenerate }) => ({ instructionGenerate })),
+ installedApps: () =>
+ import('./installed-apps/orpc.gen').then(({ installedApps }) => ({ installedApps })),
+ instructionGenerate: () =>
+ import('./instruction-generate/orpc.gen').then(({ instructionGenerate }) => ({
+ instructionGenerate,
+ })),
login: () => import('./login/orpc.gen').then(({ login }) => ({ login })),
logout: () => import('./logout/orpc.gen').then(({ logout }) => ({ logout })),
- notification: () => import('./notification/orpc.gen').then(({ notification }) => ({ notification })),
+ notification: () =>
+ import('./notification/orpc.gen').then(({ notification }) => ({ notification })),
notion: () => import('./notion/orpc.gen').then(({ notion }) => ({ notion })),
oauth: () => import('./oauth/orpc.gen').then(({ oauth }) => ({ oauth })),
rag: () => import('./rag/orpc.gen').then(({ rag }) => ({ rag })),
- refreshToken: () => import('./refresh-token/orpc.gen').then(({ refreshToken }) => ({ refreshToken })),
+ refreshToken: () =>
+ import('./refresh-token/orpc.gen').then(({ refreshToken }) => ({ refreshToken })),
remoteFiles: () => import('./remote-files/orpc.gen').then(({ remoteFiles }) => ({ remoteFiles })),
- resetPassword: () => import('./reset-password/orpc.gen').then(({ resetPassword }) => ({ resetPassword })),
- ruleCodeGenerate: () => import('./rule-code-generate/orpc.gen').then(({ ruleCodeGenerate }) => ({ ruleCodeGenerate })),
- ruleGenerate: () => import('./rule-generate/orpc.gen').then(({ ruleGenerate }) => ({ ruleGenerate })),
+ resetPassword: () =>
+ import('./reset-password/orpc.gen').then(({ resetPassword }) => ({ resetPassword })),
+ ruleCodeGenerate: () =>
+ import('./rule-code-generate/orpc.gen').then(({ ruleCodeGenerate }) => ({ ruleCodeGenerate })),
+ ruleGenerate: () =>
+ import('./rule-generate/orpc.gen').then(({ ruleGenerate }) => ({ ruleGenerate })),
ruleStructuredOutputGenerate: () =>
- import('./rule-structured-output-generate/orpc.gen').then(({ ruleStructuredOutputGenerate }) => ({ ruleStructuredOutputGenerate })),
+ import('./rule-structured-output-generate/orpc.gen').then(
+ ({ ruleStructuredOutputGenerate }) => ({ ruleStructuredOutputGenerate }),
+ ),
snippets: () => import('./snippets/orpc.gen').then(({ snippets }) => ({ snippets })),
spec: () => import('./spec/orpc.gen').then(({ spec }) => ({ spec })),
- systemFeatures: () => import('./system-features/orpc.gen').then(({ systemFeatures }) => ({ systemFeatures })),
+ systemFeatures: () =>
+ import('./system-features/orpc.gen').then(({ systemFeatures }) => ({ systemFeatures })),
tagBindings: () => import('./tag-bindings/orpc.gen').then(({ tagBindings }) => ({ tagBindings })),
tags: () => import('./tags/orpc.gen').then(({ tags }) => ({ tags })),
test: () => import('./test/orpc.gen').then(({ test }) => ({ test })),
@@ -49,6 +72,7 @@ export const contractLoaders = {
trialModels: () => import('./trial-models/orpc.gen').then(({ trialModels }) => ({ trialModels })),
website: () => import('./website/orpc.gen').then(({ website }) => ({ website })),
workflow: () => import('./workflow/orpc.gen').then(({ workflow }) => ({ workflow })),
- workflowGenerate: () => import('./workflow-generate/orpc.gen').then(({ workflowGenerate }) => ({ workflowGenerate })),
+ workflowGenerate: () =>
+ import('./workflow-generate/orpc.gen').then(({ workflowGenerate }) => ({ workflowGenerate })),
workspaces: () => import('./workspaces/orpc.gen').then(({ workspaces }) => ({ workspaces })),
}
diff --git a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
index 9b8eddbce25..ebcb6a1d1eb 100644
--- a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
@@ -1,7 +1,7 @@
import type { ChatConfig, ChatItemInTree } from '../../types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { act, renderHook } from '@testing-library/react'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { useParams, usePathname } from '@/next/navigation'
import { sseGet, ssePost } from '@/service/base'
import { useChat } from '../hooks'
@@ -353,6 +353,74 @@ describe('useChat', () => {
expect(result.current.chatList[1]!.id).toBe('m-1')
})
+ it('should process inputs with the per-send input form override', () => {
+ vi.mocked(ssePost).mockImplementation(async () => undefined)
+ const { result } = renderHook(() => useChat(undefined, {
+ inputs: {},
+ inputsForm: [{
+ type: InputVarType.textInput,
+ label: 'City',
+ variable: 'city',
+ required: true,
+ hide: false,
+ }],
+ }))
+
+ act(() => {
+ result.current.handleSend('test-url', {
+ query: 'hello',
+ inputs: {
+ enabled: undefined,
+ },
+ overrideInputsForm: [{
+ type: InputVarType.checkbox,
+ label: 'Enabled',
+ variable: 'enabled',
+ required: true,
+ hide: false,
+ }],
+ }, {})
+ })
+
+ expect(ssePost).toHaveBeenCalledWith(
+ 'test-url',
+ expect.objectContaining({
+ body: expect.objectContaining({
+ inputs: {
+ enabled: false,
+ },
+ }),
+ }),
+ expect.any(Object),
+ )
+ })
+
+ it('should settle a send once when the SSE stream errors', () => {
+ let callbacks: HookCallbacks
+ const onSendSettled = vi.fn()
+
+ vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => {
+ callbacks = options as HookCallbacks
+ })
+
+ const { result } = renderHook(() => useChat())
+
+ act(() => {
+ result.current.handleSend('test-url', { query: 'hello' }, {
+ onSendSettled,
+ })
+ })
+
+ act(() => {
+ callbacks.onError()
+ callbacks.onCompleted(true)
+ })
+
+ expect(result.current.isResponding).toBe(false)
+ expect(onSendSettled).toHaveBeenCalledTimes(1)
+ expect(onSendSettled).toHaveBeenCalledWith(true)
+ })
+
it('should handle onThought and different workflow events', async () => {
let callbacks: HookCallbacks
@@ -511,6 +579,7 @@ describe('useChat', () => {
answer_tokens: 10,
message_tokens: 5,
provider_response_latency: 0.5,
+ workflow_run_id: 'workflow-run-from-history',
inputs: {},
query: 'hi',
}],
@@ -545,7 +614,7 @@ describe('useChat', () => {
expect(onGetConversationMessages).toHaveBeenCalled()
expect(onGetSuggestedQuestions).toHaveBeenCalled()
- expect(onConversationComplete).toHaveBeenCalledWith('c-1')
+ expect(onConversationComplete).toHaveBeenCalledWith('c-1', 'workflow-run-from-history')
const updatedResponse = result.current.chatList[1]
expect(updatedResponse!.content).toBe('Updated answer from history') // Fetched from mock
@@ -1106,6 +1175,44 @@ describe('useChat', () => {
expect(result.current.isResponding).toBe(false)
})
+ it('should settle a resume once when the event stream errors', () => {
+ let callbacks: HookCallbacks
+ const onSendSettled = vi.fn()
+ vi.mocked(sseGet).mockImplementation(async (_url, _params, options) => {
+ callbacks = options as HookCallbacks
+ })
+
+ const prevChatTree = [{
+ id: 'q-1',
+ content: 'query',
+ isAnswer: false,
+ children: [{
+ id: 'm-resume-error',
+ content: 'initial',
+ isAnswer: true,
+ siblingIndex: 0,
+ }],
+ }]
+
+ const { result } = renderHook(() => useChat(undefined, undefined, prevChatTree as ChatItemInTree[]))
+
+ act(() => {
+ result.current.handleResume('m-resume-error', 'wr-error', {
+ isPublicAPI: true,
+ onSendSettled,
+ })
+ })
+
+ act(() => {
+ callbacks.onError()
+ callbacks.onCompleted(true)
+ })
+
+ expect(onSendSettled).toHaveBeenCalledTimes(1)
+ expect(onSendSettled).toHaveBeenCalledWith(true)
+ expect(result.current.isResponding).toBe(false)
+ })
+
it('should abort previous workflow event stream when resuming again', () => {
const callbacksList: HookCallbacks[] = []
vi.mocked(sseGet).mockImplementation(async (_url, _params, options) => {
@@ -1215,7 +1322,7 @@ describe('useChat', () => {
await callbacks.onCompleted()
})
- expect(onConversationComplete).toHaveBeenCalledWith('c-resume')
+ expect(onConversationComplete).toHaveBeenCalledWith('c-resume', 'wr-1')
expect(onGetSuggestedQuestions).toHaveBeenCalled()
expect(result.current.suggestedQuestions).toEqual([])
})
@@ -1489,6 +1596,45 @@ describe('useChat', () => {
expect(clearChatListCallback).toHaveBeenCalledWith(false)
})
+
+ it('should keep the first send after a reset acknowledgement', () => {
+ let clearChatList = true
+ const clearChatListCallback = vi.fn((nextClearChatList: boolean) => {
+ clearChatList = nextClearChatList
+ })
+ const { rerender, result } = renderHook(() => useChat(
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ clearChatList,
+ clearChatListCallback,
+ ))
+
+ expect(clearChatListCallback).toHaveBeenCalledWith(false)
+
+ rerender()
+
+ act(() => {
+ result.current.handleSend('test-url', { query: 'first after reset' }, {})
+ })
+
+ expect(ssePost).toHaveBeenCalledWith(
+ 'test-url',
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: 'first after reset',
+ }),
+ }),
+ expect.any(Object),
+ )
+ expect(result.current.chatList).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ content: 'first after reset',
+ isAnswer: false,
+ }),
+ ]))
+ })
})
describe('annotations and siblings', () => {
diff --git a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
index dbb11d9454c..a10b7652fdf 100644
--- a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
@@ -361,6 +361,32 @@ describe('ChatInputArea', () => {
expect(textarea).toHaveValue('')
})
+ it('should keep the textarea when async send is rejected by the owner', async () => {
+ const user = userEvent.setup({ delay: null })
+ const onSend = vi.fn().mockResolvedValue(false)
+ render(<ChatInputArea onSend={onSend} visionConfig={mockVisionConfig} />)
+ const textarea = getTextarea()!
+
+ await user.type(textarea, 'Keep this message')
+ await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
+
+ await waitFor(() => expect(onSend).toHaveBeenCalled())
+ expect(textarea).toHaveValue('Keep this message')
+ })
+
+ it('should keep the textarea when async send fails', async () => {
+ const user = userEvent.setup({ delay: null })
+ const onSend = vi.fn().mockRejectedValue(new Error('send failed'))
+ render(<ChatInputArea onSend={onSend} visionConfig={mockVisionConfig} />)
+ const textarea = getTextarea()!
+
+ await user.type(textarea, 'Retry this message')
+ await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
+
+ await waitFor(() => expect(onSend).toHaveBeenCalled())
+ expect(textarea).toHaveValue('Retry this message')
+ })
+
it('should call onSend and reset the input when pressing Enter', async () => {
const user = userEvent.setup({ delay: null })
const onSend = vi.fn()
diff --git a/web/app/components/base/chat/chat/chat-input-area/index.tsx b/web/app/components/base/chat/chat/chat-input-area/index.tsx
index e05aa8648e3..1fbb779c5ee 100644
--- a/web/app/components/base/chat/chat/chat-input-area/index.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/index.tsx
@@ -24,6 +24,8 @@ type AudioRecorderWithPermission = typeof Recorder & {
getPermission: () => Promise<void>
}
+type SendAcceptance = void | boolean | Promise<void | boolean>
+
type ChatInputAreaProps = {
readonly?: boolean
botName?: string
@@ -62,10 +64,19 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
const historyRef = useRef([''])
const [currentIndex, setCurrentIndex] = useState(-1)
const isComposingRef = useRef(false)
+ const queryRef = useRef('')
const handleQueryChange = useCallback((value: string) => {
+ queryRef.current = value
setQuery(value)
setTimeout(handleTextareaResize, 0)
}, [handleTextareaResize])
+ const resetAcceptedMessage = useCallback((acceptedQuery: string, acceptedFiles: ReturnType<typeof filesStore.getState>['files']) => {
+ const { files, setFiles } = filesStore.getState()
+ if (queryRef.current === acceptedQuery)
+ handleQueryChange('')
+ if (files === acceptedFiles)
+ setFiles([])
+ }, [filesStore, handleQueryChange])
const handleSend = () => {
if (!canSend)
return
@@ -75,15 +86,23 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
return
}
if (onSend) {
- const { files, setFiles } = filesStore.getState()
+ const { files } = filesStore.getState()
if (files.some(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) {
toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))
return
}
if (checkInputsForm(inputs, inputsForm)) {
- onSend(query, files)
- handleQueryChange('')
- setFiles([])
+ const sendResult = onSend(query, files) as SendAcceptance
+ if (sendResult instanceof Promise) {
+ sendResult.then((accepted) => {
+ if (accepted !== false)
+ resetAcceptedMessage(query, files)
+ }).catch(noop)
+ return
+ }
+
+ if (sendResult !== false)
+ resetAcceptedMessage(query, files)
}
}
}
diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.ts
index 72233118d12..dbb770af849 100644
--- a/web/app/components/base/chat/chat/hooks.ts
+++ b/web/app/components/base/chat/chat/hooks.ts
@@ -51,7 +51,8 @@ type GetAbortController = (abortController: AbortController) => void
type SendCallback = {
onGetConversationMessages?: (conversationId: string, getAbortController: GetAbortController) => Promise<any>
onGetSuggestedQuestions?: (responseItemId: string, getAbortController: GetAbortController) => Promise<any>
- onConversationComplete?: (conversationId: string) => void
+ onConversationComplete?: (conversationId: string, workflowRunId?: string) => void
+ onSendSettled?: (hasError?: boolean) => void
isPublicAPI?: boolean
}
@@ -256,10 +257,19 @@ export const useChat = (
{
onGetSuggestedQuestions,
onConversationComplete,
+ onSendSettled,
isPublicAPI,
}: SendCallback,
) => {
const getOrCreatePlayer = createAudioPlayerManager()
+ let hasSettled = false
+ const settleSend = (hasError?: boolean) => {
+ if (hasSettled)
+ return
+
+ hasSettled = true
+ onSendSettled?.(hasError)
+ }
// Re-subscribe to workflow events for the specific message
const url = `/workflow/${workflowRunId}/events?include_state_snapshot=true`
@@ -303,25 +313,29 @@ export const useChat = (
async onCompleted(hasError?: boolean) {
handleResponding(false)
- if (hasError)
- return
+ try {
+ if (hasError)
+ return
- if (onConversationComplete)
- onConversationComplete(conversationIdRef.current)
+ if (onConversationComplete)
+ onConversationComplete(conversationIdRef.current, workflowRunId)
- if (config?.suggested_questions_after_answer?.enabled && !hasStopRespondedRef.current && onGetSuggestedQuestions) {
- try {
- const { data }: any = await onGetSuggestedQuestions(
- messageId,
- newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
- )
- setSuggestedQuestions(data)
- }
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (e) {
- setSuggestedQuestions([])
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopRespondedRef.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ messageId,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestedQuestions(data)
+ }
+ catch {
+ setSuggestedQuestions([])
+ }
}
}
+ finally {
+ settleSend(hasError)
+ }
},
onFile(file) {
// Convert simple file type to MIME type for non-agent mode
@@ -404,6 +418,7 @@ export const useChat = (
},
onError() {
handleResponding(false)
+ settleSend(true)
},
onWorkflowStarted: ({ workflow_run_id, task_id }) => {
handleResponding(true)
@@ -669,6 +684,7 @@ export const useChat = (
onGetConversationMessages,
onGetSuggestedQuestions,
onConversationComplete,
+ onSendSettled,
isPublicAPI,
}: SendCallback,
) => {
@@ -721,13 +737,14 @@ export const useChat = (
handleResponding(true)
hasStopRespondedRef.current = false
- const { query, files, inputs, ...restData } = data
+ const { query, files, inputs, overrideInputsForm, ...restData } = data
+ const requestInputsForm = overrideInputsForm ?? formSettings?.inputsForm ?? []
const bodyParams = {
response_mode: 'streaming',
conversation_id: conversationIdRef.current,
files: getProcessedFiles(files || []),
query,
- inputs: getProcessedInputs(inputs || {}, formSettings?.inputsForm || []),
+ inputs: getProcessedInputs(inputs || {}, requestInputsForm),
...restData,
}
if (bodyParams?.files?.length) {
@@ -744,6 +761,14 @@ export const useChat = (
let isAgentMode = false
let hasSetResponseId = false
+ let hasSettled = false
+ const settleSend = (hasError?: boolean) => {
+ if (hasSettled)
+ return
+
+ hasSettled = true
+ onSendSettled?.(hasError)
+ }
const getOrCreatePlayer = createAudioPlayerManager()
@@ -802,63 +827,70 @@ export const useChat = (
async onCompleted(hasError?: boolean) {
handleResponding(false)
- if (hasError)
- return
-
- if (onConversationComplete)
- onConversationComplete(conversationIdRef.current)
-
- if (conversationIdRef.current && !hasStopRespondedRef.current && onGetConversationMessages) {
- const { data }: any = await onGetConversationMessages(
- conversationIdRef.current,
- newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
- )
- const newResponseItem = data.find((item: any) => item.id === responseItem.id)
- if (!newResponseItem)
+ try {
+ if (hasError)
return
- const isUseAgentThought = newResponseItem.agent_thoughts?.length > 0 && newResponseItem.agent_thoughts[newResponseItem.agent_thoughts?.length - 1].thought === newResponseItem.answer
- updateChatTreeNode(responseItem.id, {
- content: isUseAgentThought ? '' : newResponseItem.answer,
- log: [
- ...newResponseItem.message,
- ...(newResponseItem.message.at(-1).role !== 'assistant'
- ? [
- {
- role: 'assistant',
- text: newResponseItem.answer,
- files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
- },
- ]
- : []),
- ],
- more: {
- time: formatTime(newResponseItem.created_at, 'hh:mm A'),
- tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
- latency: newResponseItem.provider_response_latency.toFixed(2),
- tokens_per_second: newResponseItem.provider_response_latency > 0 ? (newResponseItem.answer_tokens / newResponseItem.provider_response_latency).toFixed(2) : undefined,
- },
- // for agent log
- conversationId: conversationIdRef.current,
- input: {
- inputs: newResponseItem.inputs,
- query: newResponseItem.query,
- },
- })
- }
- if (config?.suggested_questions_after_answer?.enabled && !hasStopRespondedRef.current && onGetSuggestedQuestions) {
- try {
- const { data }: any = await onGetSuggestedQuestions(
- responseItem.id,
- newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ let completedWorkflowRunId = responseItem.workflow_run_id
+
+ if (conversationIdRef.current && !hasStopRespondedRef.current && onGetConversationMessages) {
+ const { data }: any = await onGetConversationMessages(
+ conversationIdRef.current,
+ newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
)
- setSuggestedQuestions(data)
+ const newResponseItem = data.find((item: any) => item.id === responseItem.id)
+ completedWorkflowRunId = newResponseItem?.workflow_run_id ?? completedWorkflowRunId
+ if (!newResponseItem)
+ return onConversationComplete?.(conversationIdRef.current, completedWorkflowRunId)
+
+ const isUseAgentThought = newResponseItem.agent_thoughts?.length > 0 && newResponseItem.agent_thoughts[newResponseItem.agent_thoughts?.length - 1].thought === newResponseItem.answer
+ updateChatTreeNode(responseItem.id, {
+ content: isUseAgentThought ? '' : newResponseItem.answer,
+ log: [
+ ...newResponseItem.message,
+ ...(newResponseItem.message.at(-1).role !== 'assistant'
+ ? [
+ {
+ role: 'assistant',
+ text: newResponseItem.answer,
+ files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
+ },
+ ]
+ : []),
+ ],
+ more: {
+ time: formatTime(newResponseItem.created_at, 'hh:mm A'),
+ tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
+ latency: newResponseItem.provider_response_latency.toFixed(2),
+ tokens_per_second: newResponseItem.provider_response_latency > 0 ? (newResponseItem.answer_tokens / newResponseItem.provider_response_latency).toFixed(2) : undefined,
+ },
+ // for agent log
+ conversationId: conversationIdRef.current,
+ input: {
+ inputs: newResponseItem.inputs,
+ query: newResponseItem.query,
+ },
+ })
}
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (e) {
- setSuggestedQuestions([])
+
+ onConversationComplete?.(conversationIdRef.current, completedWorkflowRunId)
+
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopRespondedRef.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ responseItem.id,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestedQuestions(data)
+ }
+ catch {
+ setSuggestedQuestions([])
+ }
}
}
+ finally {
+ settleSend(hasError)
+ }
},
onFile(file) {
// Convert simple file type to MIME type for non-agent mode
@@ -965,6 +997,7 @@ export const useChat = (
},
onError() {
handleResponding(false)
+ settleSend(true)
updateCurrentQAOnTree({
placeholderQuestionId,
questionItem,
diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
index a40a5f3d4ca..9fce0509aa3 100644
--- a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
@@ -134,6 +134,7 @@ describe('AgentOutputBlockComponent', () => {
}),
]),
onChange,
+ undefined,
)
expect(mockNodeReplace).toHaveBeenCalledTimes(1)
expect(mockSelectNext).not.toHaveBeenCalled()
@@ -202,6 +203,7 @@ describe('AgentOutputBlockComponent', () => {
}),
]),
onChange,
+ undefined,
)
})
@@ -240,6 +242,7 @@ describe('AgentOutputBlockComponent', () => {
}),
]),
onChange,
+ undefined,
)
expect(onChange).toHaveBeenCalledWith(expect.arrayContaining([
expect.objectContaining({
@@ -280,6 +283,7 @@ describe('AgentOutputBlockComponent', () => {
}),
]),
onChange,
+ undefined,
)
})
@@ -320,6 +324,7 @@ describe('AgentOutputBlockComponent', () => {
}),
]),
onChange,
+ undefined,
)
})
@@ -366,4 +371,23 @@ describe('AgentOutputBlockComponent', () => {
expect(screen.getByText('qna_report_pdf')).toBeInTheDocument()
expect(screen.getByText('file')).toBeInTheDocument()
})
+
+ it('requests the output editor when hovering a committed output block', () => {
+ const onEdit = vi.fn()
+
+ render(
+ <AgentOutputBlockComponent
+ nodeKey="output-node"
+ name="qna_report_pdf"
+ outputType="file"
+ isEditing={false}
+ outputs={outputs}
+ onEdit={onEdit}
+ />,
+ )
+
+ fireEvent.mouseEnter(screen.getByText('qna_report_pdf').parentElement!)
+
+ expect(onEdit).toHaveBeenCalledWith('qna_report_pdf', 'file')
+ })
})
diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx
index 68d128f956c..2305cf817c9 100644
--- a/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx
+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx
@@ -29,6 +29,7 @@ type AgentOutputBlockComponentProps = {
isEditing: boolean
outputs: DeclaredOutputConfig[]
onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void
+ onEdit?: (name: string, outputType: AgentOutputTypeOptionValue) => void
}
function upsertOutput(
@@ -61,6 +62,7 @@ const AgentOutputBlockComponent = ({
isEditing,
outputs,
onChange,
+ onEdit,
}: AgentOutputBlockComponentProps) => {
const { t } = useTranslation()
const [editor] = useLexicalComposerContext()
@@ -92,7 +94,7 @@ const AgentOutputBlockComponent = ({
return
const nextOutputType = inferAgentOutputType(trimmedName, nextType)
- const nextNode = node.replace($createAgentOutputBlockNode(trimmedName, nextOutputType, false, nextOutputs, onChange))
+ const nextNode = node.replace($createAgentOutputBlockNode(trimmedName, nextOutputType, false, nextOutputs, onChange, onEdit))
if (selectAfterCommit)
nextNode.selectNext()
nextPrompt = $getRoot().getChildren().map(node => node.getTextContent()).join('\n')
@@ -111,9 +113,11 @@ const AgentOutputBlockComponent = ({
return (
<span
contentEditable={false}
- className="inline-flex min-w-[18px] items-center gap-1 rounded-[5px] border border-util-colors-violet-violet-100 bg-util-colors-violet-violet-50 px-1 py-0.5 align-middle shadow-xs"
+ className="group/agent-output inline-flex min-w-[18px] items-center gap-1 rounded-[5px] border border-util-colors-violet-violet-100 bg-util-colors-violet-violet-50 px-1 py-0.5 align-middle shadow-xs"
+ onMouseEnter={() => onEdit?.(name, outputType)}
>
- <span aria-hidden="true" className="i-custom-vender-workflow-variable-x size-3.5 shrink-0 text-util-colors-violet-violet-700" />
+ <span aria-hidden="true" className="i-custom-vender-workflow-variable-x size-3.5 shrink-0 text-util-colors-violet-violet-700 group-hover/agent-output:hidden" />
+ <span aria-hidden="true" className="i-ri-edit-2-line hidden size-3.5 shrink-0 text-util-colors-violet-violet-700 group-hover/agent-output:inline-block" />
<span className="system-xs-medium whitespace-nowrap text-util-colors-violet-violet-700">
{name}
</span>
diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx
index aeafc69c5f4..51d3f6ad34d 100644
--- a/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx
@@ -31,6 +31,7 @@ function getAgentOutputBlockNodeType(name: string, outputs: NonNullable<AgentOut
const AgentOutputBlock = memo(({
outputs = [],
onChange,
+ onEdit,
}: AgentOutputBlockType) => {
const [editor] = useLexicalComposerContext()
@@ -45,7 +46,7 @@ const AgentOutputBlock = memo(({
const name = getUniqueAgentOutputName(outputs)
const outputType = 'string'
const nextOutputs = [...outputs, createAgentOutputConfig(name, outputType)]
- const agentOutputBlockNode = $createAgentOutputBlockNode(name, outputType, true, nextOutputs, onChange)
+ const agentOutputBlockNode = $createAgentOutputBlockNode(name, outputType, true, nextOutputs, onChange, onEdit)
$insertNodes([agentOutputBlockNode])
const nextPrompt = $getRoot().getChildren().map(node => node.getTextContent()).join('\n')
@@ -56,7 +57,7 @@ const AgentOutputBlock = memo(({
COMMAND_PRIORITY_EDITOR,
),
)
- }, [editor, onChange, outputs])
+ }, [editor, onChange, onEdit, outputs])
return null
})
@@ -65,6 +66,7 @@ AgentOutputBlock.displayName = 'AgentOutputBlock'
const AgentOutputBlockReplacementBlock = memo(({
outputs = [],
onChange,
+ onEdit,
}: AgentOutputBlockType) => {
const [editor] = useLexicalComposerContext()
@@ -78,8 +80,8 @@ const AgentOutputBlockReplacementBlock = memo(({
const name = match?.name || ''
const outputType = getAgentOutputBlockNodeType(name, outputs)
- return $applyNodeReplacement($createAgentOutputBlockNode(name, outputType, false, outputs, onChange))
- }, [onChange, outputs])
+ return $applyNodeReplacement($createAgentOutputBlockNode(name, outputType, false, outputs, onChange, onEdit))
+ }, [onChange, onEdit, outputs])
const getMatch = useCallback((text: string) => {
const match = parseAgentOutputToken(text)
@@ -116,8 +118,9 @@ const AgentOutputBlockReplacementBlock = memo(({
child.getOutputType() !== outputType
|| child.getOutputs() !== outputs
|| child.getOnChange() !== onChange
+ || child.getOnEdit() !== onEdit
) {
- child.replace($createAgentOutputBlockNode(name, outputType, child.isEditing(), outputs, onChange))
+ child.replace($createAgentOutputBlockNode(name, outputType, child.isEditing(), outputs, onChange, onEdit))
}
return
}
@@ -129,7 +132,7 @@ const AgentOutputBlockReplacementBlock = memo(({
visitNode($getRoot())
})
- }, [editor, onChange, outputs])
+ }, [editor, onChange, onEdit, outputs])
return null
})
diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx
index 11e14f7c245..ecf8d53e1c6 100644
--- a/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx
+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx
@@ -16,6 +16,7 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
__isEditing: boolean
__outputs: DeclaredOutputConfig[]
__onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void
+ __onEdit?: (name: string, outputType: AgentOutputTypeOptionValue) => void
static override getType(): string {
return 'agent-output-block'
@@ -28,6 +29,7 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
node.__isEditing,
node.__outputs,
node.__onChange,
+ node.__onEdit,
node.__key,
)
}
@@ -42,6 +44,7 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
isEditing = false,
outputs: DeclaredOutputConfig[] = [],
onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void,
+ onEdit?: (name: string, outputType: AgentOutputTypeOptionValue) => void,
key?: NodeKey,
) {
super(key)
@@ -51,6 +54,7 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
this.__isEditing = isEditing
this.__outputs = outputs
this.__onChange = onChange
+ this.__onEdit = onEdit
}
override createDOM(): HTMLElement {
@@ -72,6 +76,7 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
isEditing={this.isEditing()}
outputs={this.getOutputs()}
onChange={this.getOnChange()}
+ onEdit={this.getOnEdit()}
/>
)
}
@@ -109,6 +114,10 @@ export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {
return this.getLatest().__onChange
}
+ getOnEdit(): ((name: string, outputType: AgentOutputTypeOptionValue) => void) | undefined {
+ return this.getLatest().__onEdit
+ }
+
override getTextContent(): string {
return getAgentOutputToken(this.getName())
}
@@ -120,8 +129,9 @@ export function $createAgentOutputBlockNode(
isEditing = false,
outputs: DeclaredOutputConfig[] = [],
onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void,
+ onEdit?: (name: string, outputType: AgentOutputTypeOptionValue) => void,
): AgentOutputBlockNode {
- return new AgentOutputBlockNode(name, outputType, isEditing, outputs, onChange)
+ return new AgentOutputBlockNode(name, outputType, isEditing, outputs, onChange, onEdit)
}
export function $isAgentOutputBlockNode(
diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
index 91062d40060..710df306a70 100644
--- a/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
@@ -4,8 +4,10 @@ import type {
LexicalNode,
} from 'lexical'
import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { createEditor } from 'lexical'
import RosterReferenceBlockComponent from '../component'
+import { RosterReferenceBlockContext } from '../context'
import {
$createRosterReferenceBlockNode,
RosterReferenceBlockNode,
@@ -70,6 +72,28 @@ describe('RosterReferenceBlockNode', () => {
expect(iconShell?.querySelector('.i-ri-book-open-line')).toBeInTheDocument()
})
+ it('should render warning state for missing references', async () => {
+ const user = userEvent.setup()
+ render(
+ <RosterReferenceBlockContext value={{
+ getWarning: token => `${token.label} does not exist`,
+ }}
+ >
+ <RosterReferenceBlockComponent text="[§skill:playwright:Playwright§]" />
+ </RosterReferenceBlockContext>,
+ )
+
+ const token = screen.getByTitle('Playwright does not exist')
+ expect(token).toHaveAttribute('data-roster-reference-warning', 'true')
+ expect(token).toHaveClass('border-components-badge-status-light-warning-halo')
+ expect(token).toHaveClass('bg-state-warning-hover')
+ expect(token).toHaveTextContent('Playwright')
+ expect(token.querySelector('.i-ri-alert-fill')).toBeInTheDocument()
+
+ await user.hover(token)
+ expect(await screen.findByText('Playwright does not exist')).toBeInTheDocument()
+ })
+
it('should expose DecoratorNode behavior and preserve raw text content', () => {
runInEditor(() => {
const node = new RosterReferenceBlockNode('[§tool-all:tavily/tavily:tavily§]', 'node-key')
diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
index bfe83cd322b..2b26e4db943 100644
--- a/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
@@ -1,5 +1,6 @@
import { cn } from '@langgenius/dify-ui/cn'
import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { use } from 'react'
import { RosterReferenceBlockContext } from './context'
import {
@@ -23,17 +24,24 @@ const RosterReferenceBlockComponent = ({
const isKnowledge = token.kind === 'knowledge'
const customIcon = rosterReferenceBlock?.renderIcon?.(token)
+ const warning = rosterReferenceBlock?.getWarning?.(token)
const defaultIcon = token.kind === 'file'
? <FileTreeIcon type={getRosterReferenceFileIconType(token.label)} className="size-4" />
: <span className={cn(isKnowledge ? 'size-3.5' : 'size-3.5 shrink-0', getRosterReferenceIconClassName(token))} />
- return (
+ const tokenBlock = (
<span
contentEditable={false}
data-roster-reference-kind={token.kind}
data-roster-reference-id={token.id}
- title={token.label}
- className="inline-flex min-w-[18px] items-center gap-0.5 overflow-hidden rounded-[5px] border border-state-accent-hover-alt bg-state-accent-hover py-px pr-1 pl-px align-middle shadow-xs shadow-shadow-shadow-3"
+ data-roster-reference-warning={warning ? true : undefined}
+ title={warning ?? token.label}
+ className={cn(
+ 'inline-flex min-w-[18px] items-center gap-0.5 overflow-hidden rounded-[5px] border py-px pr-1 pl-px align-middle shadow-xs shadow-shadow-shadow-3',
+ warning
+ ? 'border-components-badge-status-light-warning-halo bg-state-warning-hover'
+ : 'border-state-accent-hover-alt bg-state-accent-hover',
+ )}
>
<span
aria-hidden
@@ -45,11 +53,30 @@ const RosterReferenceBlockComponent = ({
>
{customIcon || defaultIcon}
</span>
- <span className="max-w-48 truncate system-xs-medium text-text-accent">
+ <span className={cn(
+ 'max-w-48 truncate system-xs-medium',
+ warning ? 'text-text-warning' : 'text-text-accent',
+ )}
+ >
{token.label}
</span>
+ {warning && (
+ <span aria-hidden className="i-ri-alert-fill size-3 shrink-0 text-text-warning" />
+ )}
</span>
)
+
+ if (!warning)
+ return tokenBlock
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={tokenBlock} />
+ <TooltipContent>
+ {warning}
+ </TooltipContent>
+ </Tooltip>
+ )
}
export default RosterReferenceBlockComponent
diff --git a/web/app/components/base/prompt-editor/types.ts b/web/app/components/base/prompt-editor/types.ts
index 5846ca51229..d87e19dbf74 100644
--- a/web/app/components/base/prompt-editor/types.ts
+++ b/web/app/components/base/prompt-editor/types.ts
@@ -2,6 +2,7 @@ import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/type
import type { GeneratorType } from '../../app/configuration/config/automatic/types'
import type { FormInputItem } from '../../workflow/nodes/human-input/types'
import type { Type } from '../../workflow/nodes/llm/types'
+import type { AgentOutputTypeOptionValue } from './plugins/agent-output-block/utils'
import type { Dataset } from './plugins/context-block'
import type { RoleName } from './plugins/history-block'
import type { RosterReferenceToken } from './plugins/roster-reference-block/utils'
@@ -64,6 +65,7 @@ export type VariableBlockType = {
export type RosterReferenceBlockType = {
show?: boolean
renderIcon?: (token: RosterReferenceToken) => React.ReactNode
+ getWarning?: (token: RosterReferenceToken) => string | undefined
}
export type ExternalToolBlockType = {
@@ -92,6 +94,7 @@ export type AgentOutputBlockType = {
show?: boolean
outputs?: DeclaredOutputConfig[]
onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void
+ onEdit?: (name: string, outputType: AgentOutputTypeOptionValue) => void
}
export type WorkflowNodesMap = Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'> & { modelProvider?: string }>
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-selector-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-selector-trigger.spec.tsx
index a0d7503c94c..85b0292c962 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-selector-trigger.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-selector-trigger.spec.tsx
@@ -242,6 +242,20 @@ describe('ModelSelectorTrigger', () => {
expect(await screen.findByText('common.modelProvider.selector.incompatibleTip')).toBeInTheDocument()
})
+
+ it('should show incompatible badge when selected model fails the compatibility predicate', () => {
+ const { container } = render(
+ <ModelSelectorTrigger
+ currentProvider={createModel()}
+ currentModel={createModelItem()}
+ isModelCompatible={false}
+ />,
+ )
+
+ expect(screen.getByText('common.modelProvider.selector.incompatible')).toBeInTheDocument()
+ expect(screen.queryByText('CHAT')).not.toBeInTheDocument()
+ expect(container.querySelector('.i-ri-arrow-down-s-line')).toBeInTheDocument()
+ })
})
describe('Edge Cases', () => {
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
index 66d66807b2e..4c3c90558b6 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
@@ -584,6 +584,43 @@ describe('Popup', () => {
expect(screen.queryByText('gpt-4-tool')).not.toBeInTheDocument()
})
+ it('should toggle incompatible models from the reveal action', async () => {
+ const user = userEvent.setup()
+
+ renderPopup(
+ <PopupHarness
+ modelList={[
+ makeModel({
+ provider: 'openai',
+ models: [
+ makeModelItem({ model: 'gpt-4o', label: { en_US: 'GPT-4o', zh_Hans: 'GPT-4o' } }),
+ makeModelItem({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' } }),
+ ],
+ }),
+ ]}
+ modelPredicate={(_provider, modelItem) => modelItem.model !== 'gpt-4'}
+ onHide={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('gpt-4o')).toBeInTheDocument()
+ expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.modelProvider.selector.showIncompatibleModels' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'common.modelProvider.selector.showIncompatibleModels' }))
+
+ expect(screen.getByText('gpt-4o')).toBeInTheDocument()
+ expect(screen.getByText('gpt-4')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.modelProvider.selector.showIncompatibleModels' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.modelProvider.selector.hideIncompatibleModels' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'common.modelProvider.selector.hideIncompatibleModels' }))
+
+ expect(screen.getByText('gpt-4o')).toBeInTheDocument()
+ expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.modelProvider.selector.showIncompatibleModels' })).toBeInTheDocument()
+ })
+
it('should show matching models when searching by model name', () => {
renderPopup(
<PopupHarness
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx
index 8f771444976..fc86e82927c 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx
@@ -1,6 +1,6 @@
import type { ComboboxRootChangeEventDetails } from '@langgenius/dify-ui/combobox'
import type { DefaultModel, Model, ModelFeatureEnum, ModelItem } from '../declarations'
-import type { ModelSelectorValue } from './types'
+import type { ModelSelectorModelPredicate, ModelSelectorValue } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { Combobox, ComboboxContent, ComboboxTrigger } from '@langgenius/dify-ui/combobox'
import { useCallback, useMemo, useState } from 'react'
@@ -36,6 +36,7 @@ type ModelSelectorProps = {
onOpenMarketplace?: () => void
providerSettingsSource?: 'agent'
showModelMeta?: boolean
+ modelPredicate?: ModelSelectorModelPredicate
}
function ModelSelector({
defaultModel,
@@ -53,6 +54,7 @@ function ModelSelector({
onOpenMarketplace,
providerSettingsSource,
showModelMeta,
+ modelPredicate,
}: ModelSelectorProps) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
@@ -155,6 +157,7 @@ function ModelSelector({
deprecatedClassName={deprecatedClassName}
showDeprecatedWarnIcon={showDeprecatedWarnIcon}
showModelMeta={showModelMeta}
+ isModelCompatible={currentProvider && currentModel ? modelPredicate?.(currentProvider, currentModel) : undefined}
/>
</ComboboxTrigger>
<ComboboxContent
@@ -169,6 +172,7 @@ function ModelSelector({
scopeFeatures={scopeFeatures}
hideProviderSettingsFooter={hideProviderSettingsFooter}
providerSettingsSource={providerSettingsSource}
+ modelPredicate={modelPredicate}
onConfigureEmptyState={onConfigureEmptyState ? handleConfigureEmptyState : undefined}
onOpenMarketplace={onOpenMarketplace}
onInputValueChange={setInputValue}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/model-search.ts b/web/app/components/header/account-setting/model-provider-page/model-selector/model-search.ts
index 9870b70ea97..4c3a1138d3b 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/model-search.ts
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/model-search.ts
@@ -1,4 +1,5 @@
import type { DefaultModel, Model, ModelItem, TypeWithI18N } from '../declarations'
+import type { ModelSelectorModelPredicate } from './types'
import Fuse from 'fuse.js'
import { supportFunctionCall } from '@/utils/tool-call'
import { ModelFeatureEnum } from '../declarations'
@@ -29,6 +30,7 @@ type FilterModelSelectorModelsParams = {
defaultModel?: DefaultModel
inputValue: string
installedModelList: Model[]
+ modelPredicate?: ModelSelectorModelPredicate
scopeFeatures: ModelFeatureEnum[]
searchIndex: ModelSelectorSearchIndex
}
@@ -152,6 +154,7 @@ export const filterModelSelectorModels = ({
defaultModel,
inputValue,
installedModelList,
+ modelPredicate,
scopeFeatures,
searchIndex,
}: FilterModelSelectorModelsParams) => {
@@ -170,6 +173,7 @@ export const filterModelSelectorModels = ({
return matches.models.has(createModelSearchKey(model.provider, modelItem.model))
})
.filter(modelItem => modelSupportsScopeFeatures(modelItem, scopeFeatures))
+ .filter(modelItem => modelPredicate?.(model, modelItem) ?? true)
if (
(trimmedInputValue && filteredModels.length === 0)
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx
index 98af4b0f63d..a81d79951ff 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx
@@ -18,6 +18,7 @@ type ModelSelectorTriggerProps = {
deprecatedClassName?: string
showDeprecatedWarnIcon?: boolean
showModelMeta?: boolean
+ isModelCompatible?: boolean
}
function ModelSelectorTrigger({
@@ -30,6 +31,7 @@ function ModelSelectorTrigger({
deprecatedClassName,
showDeprecatedWarnIcon = true,
showModelMeta = true,
+ isModelCompatible = true,
}: ModelSelectorTriggerProps) {
const { t } = useTranslation()
const { modelProviders } = useProviderContext()
@@ -58,10 +60,14 @@ function ModelSelectorTrigger({
const isDisabled = status !== 'active' && status !== 'empty'
const statusI18nKey = DERIVED_MODEL_STATUS_BADGE_I18N[status as keyof typeof DERIVED_MODEL_STATUS_BADGE_I18N]
const tooltipI18nKey = DERIVED_MODEL_STATUS_TOOLTIP_I18N[status as keyof typeof DERIVED_MODEL_STATUS_TOOLTIP_I18N]
- const statusLabel = statusI18nKey ? t(statusI18nKey, { ns: 'common' }) : null
- const tooltipLabel = tooltipI18nKey ? t(tooltipI18nKey, { ns: 'common' }) : null
+ const statusLabel = isModelCompatible && statusI18nKey
+ ? t(statusI18nKey, { ns: 'common' })
+ : t('modelProvider.selector.incompatible', { ns: 'common' })
+ const tooltipLabel = isModelCompatible && tooltipI18nKey
+ ? t(tooltipI18nKey, { ns: 'common' })
+ : t('modelProvider.selector.incompatibleTip', { ns: 'common' })
const isCreditsExhausted = status === 'credits-exhausted'
- const shouldShowModelMeta = showModelMeta && status === 'active'
+ const shouldShowModelMeta = showModelMeta && status === 'active' && isModelCompatible
const deprecatedStatusLabel = statusLabel || t('modelProvider.selector.incompatible', { ns: 'common' })
const deprecatedTooltipLabel = tooltipLabel || t('modelProvider.selector.incompatibleTip', { ns: 'common' })
@@ -114,7 +120,7 @@ function ModelSelectorTrigger({
</div>
)}
- {isSelected && !readonly && !isActive && statusI18nKey && (
+ {isSelected && !readonly && ((!isActive && statusI18nKey) || !isModelCompatible) && (
<Tooltip>
<TooltipTrigger
disabled={!tooltipLabel}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-layout.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-layout.tsx
index a5412e11b74..4861c101388 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-layout.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-layout.tsx
@@ -113,6 +113,32 @@ export function CompatibleModelsNotice() {
)
}
+type ShowIncompatibleModelsButtonProps = {
+ showIncompatibleModels: boolean
+ onClick: () => void
+}
+
+export function ShowIncompatibleModelsButton({
+ showIncompatibleModels,
+ onClick,
+}: ShowIncompatibleModelsButtonProps) {
+ const { t } = useTranslation()
+
+ return (
+ <button
+ type="button"
+ className="flex h-10 w-full cursor-pointer items-center px-4 text-left system-xs-regular text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary"
+ onClick={onClick}
+ >
+ <span className="min-w-0 truncate">
+ {showIncompatibleModels
+ ? t('modelProvider.selector.hideIncompatibleModels', { ns: 'common' })
+ : t('modelProvider.selector.showIncompatibleModels', { ns: 'common' })}
+ </span>
+ </button>
+ )
+}
+
type ModelProviderSettingsFooterProps = {
onOpenSettings: () => void
}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
index 1855680bf33..7b8c0bf4857 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
@@ -1,5 +1,6 @@
import type { DefaultModel, Model } from '../declarations'
import type { ModelSelectorPreviewPayload } from './popup-item'
+import type { ModelSelectorModelPredicate } from './types'
import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'
import { ComboboxList } from '@langgenius/dify-ui/combobox'
import { createPreviewCardHandle, PreviewCard, PreviewCardContent } from '@langgenius/dify-ui/preview-card'
@@ -31,7 +32,7 @@ import MarketplaceSection from './marketplace-section'
import { createModelSelectorSearchIndex, filterModelSelectorModels } from './model-search'
import ModelSelectorEmptyState from './popup-empty-state'
import PopupItem from './popup-item'
-import { CompatibleModelsNotice, ModelProviderSettingsFooter, ModelSelectorPopupFrame, ModelSelectorScrollBody, ModelSelectorSearchHeader } from './popup-layout'
+import { CompatibleModelsNotice, ModelProviderSettingsFooter, ModelSelectorPopupFrame, ModelSelectorScrollBody, ModelSelectorSearchHeader, ShowIncompatibleModelsButton } from './popup-layout'
export type PopupProps = {
defaultModel?: DefaultModel
@@ -40,6 +41,7 @@ export type PopupProps = {
scopeFeatures?: ModelFeatureEnum[]
hideProviderSettingsFooter?: boolean
providerSettingsSource?: 'agent'
+ modelPredicate?: ModelSelectorModelPredicate
onConfigureEmptyState?: () => void
onInputValueChange: (value: string) => void
onOpenMarketplace?: () => void
@@ -52,6 +54,7 @@ function Popup({
scopeFeatures = [],
hideProviderSettingsFooter,
providerSettingsSource,
+ modelPredicate,
onConfigureEmptyState,
onInputValueChange,
onOpenMarketplace,
@@ -63,6 +66,7 @@ function Popup({
const language = useLanguage()
const previewCardHandle = useMemo(() => createPreviewCardHandle<ModelSelectorPreviewPayload>(), [])
const [marketplaceCollapsed, setMarketplaceCollapsed] = useState(false)
+ const [showIncompatibleModels, setShowIncompatibleModels] = useState(false)
const openIntegrationsSetting = useIntegrationsSetting()
const { modelProviders } = useProviderContext()
const { data: enableMarketplace } = useSuspenseQuery({
@@ -165,9 +169,11 @@ function Popup({
defaultModel,
inputValue,
installedModelList,
+ modelPredicate: showIncompatibleModels ? undefined : modelPredicate,
scopeFeatures,
searchIndex,
- }), [aiCreditVisibleProviders, defaultModel, inputValue, installedModelList, scopeFeatures, searchIndex])
+ }), [aiCreditVisibleProviders, defaultModel, inputValue, installedModelList, modelPredicate, scopeFeatures, searchIndex, showIncompatibleModels])
+ const shouldShowModelPredicateReveal = !!modelPredicate
const marketplaceProviders = useMemo(() => {
if (!enableMarketplace)
@@ -228,6 +234,12 @@ function Popup({
{scopeFeatures.length > 0 && (
<CompatibleModelsNotice />
)}
+ {shouldShowModelPredicateReveal && (
+ <ShowIncompatibleModelsButton
+ showIncompatibleModels={showIncompatibleModels}
+ onClick={() => setShowIncompatibleModels(value => !value)}
+ />
+ )}
{enableMarketplace && (
<MarketplaceSection
marketplaceProviders={marketplaceProviders}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/types.ts b/web/app/components/header/account-setting/model-provider-page/model-selector/types.ts
index 93314a6208a..ce2d6135a91 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/types.ts
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/types.ts
@@ -1,8 +1,12 @@
+import type { Model, ModelItem } from '../declarations'
+
export type ModelSelectorValue = {
provider: string
model: string
}
+export type ModelSelectorModelPredicate = (provider: Model, modelItem: ModelItem) => boolean
+
export const isSameModelSelectorValue = (
itemValue: ModelSelectorValue,
value: ModelSelectorValue,
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 06428dcc2d3..1a2ad212d6c 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -181,6 +181,28 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
})
+ it('should ignore non-JSON sync errors without throwing an unhandled rejection', async () => {
+ const error = {
+ json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected token U')),
+ bodyUsed: false,
+ }
+ const callbacks = {
+ onError: vi.fn(),
+ onSettled: vi.fn(),
+ }
+ mockSyncWorkflowDraft.mockRejectedValue(error)
+
+ const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeUndefined()
+ })
+
+ expect(error.json).toHaveBeenCalled()
+ expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onError).toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalled()
+ })
+
it('should not include source_workflow_id in draft sync payloads', async () => {
const { result } = renderUseNodesSyncDraft()
diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
index 47328410f10..16358cb9eaf 100644
--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
@@ -179,10 +179,14 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
catch (error: unknown) {
const responseError = error as { bodyUsed?: boolean, json?: () => Promise<{ code?: string }> }
if (responseError.json && !responseError.bodyUsed) {
- responseError.json().then((err) => {
+ try {
+ const err = await responseError.json()
if (err.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)
handleRefreshWorkflowDraft(true)
- })
+ }
+ catch {
+ // Non-JSON upstream errors should not surface as unhandled promise rejections.
+ }
}
callback?.onError?.()
}
diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
index d9dfc4fa04e..47d385e41b1 100644
--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
@@ -356,6 +356,10 @@ describe('Blocks', () => {
)
await user.click(screen.getByRole('button', { name: 'Agent' }))
+ const consoleLink = await screen.findByRole('option', { name: 'agentV2.roster.nodeSelector.manageInAgentConsole' })
+ expect(consoleLink).toHaveAttribute('href', '/roster')
+ expect(consoleLink).toHaveAttribute('target', '_blank')
+ expect(consoleLink).toHaveAttribute('rel', 'noopener noreferrer')
await user.click(await screen.findByRole('option', { name: 'agentV2.roster.nodeSelector.startFromScratch' }))
expect(onSelect).toHaveBeenCalledWith(BlockEnum.AgentV2, {
diff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsx
index 1239b559b87..b6725f47ccc 100644
--- a/web/app/components/workflow/block-selector/agent-selector.tsx
+++ b/web/app/components/workflow/block-selector/agent-selector.tsx
@@ -278,7 +278,7 @@ function AgentSelectorActionItem({
return (
<ComboboxItem
value={option}
- render={isStartFromScratch ? undefined : <Link href="/roster" />}
+ render={isStartFromScratch ? undefined : <Link href="/roster" target="_blank" rel="noopener noreferrer" />}
className="flex min-h-7 w-full grid-cols-none items-center gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-highlighted:bg-state-base-hover data-highlighted:text-text-secondary"
>
<ComboboxItemText className="flex items-center gap-2 px-0 system-sm-regular text-text-secondary">
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
index 089182565ba..9cc7f17b133 100644
--- a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
@@ -1,5 +1,12 @@
import { QueryClient } from '@tanstack/react-query'
import { act, waitFor } from '@testing-library/react'
+import { getDefaultStore } from 'jotai'
+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
+import {
+ agentComposerDraftAtom,
+ agentComposerOriginalConfigAtom,
+ agentComposerOriginalDraftAtom,
+} from '@/features/agent-v2/agent-composer/store'
import { FlowType } from '@/types/common'
import { renderWorkflowHook } from '../../../__tests__/workflow-test-env'
import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'
@@ -282,6 +289,10 @@ describe('useCreateInlineAgentBinding', () => {
describe('useWorkflowInlineAgentConfigureSync', () => {
beforeEach(() => {
vi.clearAllMocks()
+ const store = getDefaultStore()
+ store.set(agentComposerOriginalConfigAtom, undefined)
+ store.set(agentComposerOriginalDraftAtom, defaultAgentSoulConfigFormState)
+ store.set(agentComposerDraftAtom, defaultAgentSoulConfigFormState)
})
it('saves inline agent composer changes through the workflow node composer API', async () => {
@@ -317,6 +328,13 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
},
})
+ act(() => {
+ getDefaultStore().set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Workflow inline prompt',
+ })
+ })
+
await act(async () => {
await result.current.saveDraft()
})
@@ -332,7 +350,7 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
agent_soul: expect.objectContaining({
schema_version: 1,
prompt: expect.objectContaining({
- system_prompt: '',
+ system_prompt: 'Workflow inline prompt',
}),
model: expect.objectContaining({
model_provider: 'langgenius/openai/openai',
@@ -378,6 +396,13 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
},
})
+ act(() => {
+ getDefaultStore().set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Manual inline prompt',
+ })
+ })
+
await act(async () => {
await result.current.saveDraft()
})
@@ -392,8 +417,97 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
save_strategy: 'node_job_only',
agent_soul: expect.objectContaining({
schema_version: 1,
+ prompt: expect.objectContaining({
+ system_prompt: 'Manual inline prompt',
+ }),
}),
}),
}, expect.any(Object))
})
+
+ it('does not save manually when the inline agent composer draft is unchanged', async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ mutations: {
+ retry: false,
+ },
+ },
+ })
+ const { result } = renderWorkflowHook(() => useWorkflowInlineAgentConfigureSync({
+ nodeId: 'node-1',
+ baseConfig: {
+ schema_version: 1,
+ },
+ enabled: true,
+ }), {
+ queryClient,
+ hooksStoreProps: {
+ configsMap: {
+ flowId: 'app-1',
+ flowType: FlowType.appFlow,
+ fileSettings: {} as never,
+ },
+ },
+ })
+
+ await act(async () => {
+ await result.current.saveDraft()
+ })
+
+ expect(mockComposerMutationFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData(['workflow-agent-composer', 'app-1', 'node-1'])).toBeUndefined()
+ expect(result.current.draftSavedAt).toBeUndefined()
+ })
+
+ it('saves the effective inline model when the form draft is unchanged', async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ mutations: {
+ retry: false,
+ },
+ },
+ })
+ const { result } = renderWorkflowHook(() => useWorkflowInlineAgentConfigureSync({
+ nodeId: 'node-1',
+ baseConfig: {
+ schema_version: 1,
+ },
+ currentModel: {
+ provider: 'langgenius/openai/openai',
+ model: 'gpt-4o-mini',
+ },
+ enabled: true,
+ }), {
+ queryClient,
+ hooksStoreProps: {
+ configsMap: {
+ flowId: 'app-1',
+ flowType: FlowType.appFlow,
+ fileSettings: {} as never,
+ },
+ },
+ })
+
+ await act(async () => {
+ await result.current.saveDraft()
+ })
+
+ expect(mockComposerMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ model: expect.objectContaining({
+ model_provider: 'langgenius/openai/openai',
+ model: 'gpt-4o-mini',
+ plugin_id: 'langgenius/openai',
+ }),
+ }),
+ }),
+ }), expect.any(Object))
+ })
})
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
index c8a362ccda2..6710f730f66 100644
--- a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
@@ -2,7 +2,7 @@ import type { ReactNode } from 'react'
import type { AgentV2NodeType } from '../types'
import type { PromptEditorProps } from '@/app/components/base/prompt-editor'
import type { NodePanelProps } from '@/app/components/workflow/types'
-import { fireEvent, render, screen, within } from '@testing-library/react'
+import { act, fireEvent, render, screen, within } from '@testing-library/react'
import { BlockEnum } from '@/app/components/workflow/types'
import { AgentV2Panel } from '../panel'
@@ -408,7 +408,10 @@ describe('agent/panel', () => {
const panel = screen.getByRole('dialog', { name: 'Nadia' })
expect(panel).toBeInTheDocument()
expect(within(panel).getByText('Researcher')).toBeInTheDocument()
- expect(within(panel).getByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })).toHaveAttribute('href', '/roster/agent/agent-1/configure')
+ const consoleLink = within(panel).getByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })
+ expect(consoleLink).toHaveAttribute('href', '/roster/agent/agent-1/configure')
+ expect(consoleLink).toHaveAttribute('target', '_blank')
+ expect(consoleLink).toHaveAttribute('rel', 'noopener noreferrer')
expect(within(panel).getByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' })).toBeInTheDocument()
expect(within(panel).getByRole('region', { name: 'readonly-roster-orchestrate-panel' })).toBeInTheDocument()
expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
@@ -1016,6 +1019,7 @@ describe('agent/panel', () => {
outputs: expect.arrayContaining([
expect.objectContaining({ name: 'text' }),
]),
+ onEdit: expect.any(Function),
})
expect(mockPromptEditorProps[0]?.contextBlock).toBeUndefined()
@@ -1030,6 +1034,190 @@ describe('agent/panel', () => {
expect(screen.queryByRole('button', { name: 'workflow.nodes.agent.task.mention' })).not.toBeInTheDocument()
})
+ it('opens the output variable editor from an agent task output token hover', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_declared_outputs: [{
+ name: 'summary',
+ type: 'string',
+ required: false,
+ description: 'Short summary',
+ }],
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ act(() => {
+ mockPromptEditorProps[0]?.agentOutputBlock?.onEdit?.('summary', 'string')
+ })
+
+ expect(screen.getByRole('form', { name: 'workflow.nodes.agent.outputVars.editorLabel' })).toBeInTheDocument()
+ expect(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })).toHaveValue('summary')
+ })
+
+ it('opens the output variable editor for a prompt token missing from declared outputs', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData()}
+ panelProps={panelProps}
+ />,
+ )
+
+ act(() => {
+ mockPromptEditorProps[0]?.agentOutputBlock?.onEdit?.('qna_report', 'string')
+ })
+
+ expect(screen.getByRole('form', { name: 'workflow.nodes.agent.outputVars.editorLabel' })).toBeInTheDocument()
+ expect(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })).toHaveValue('qna_report')
+
+ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.confirm' }))
+
+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
+ {
+ id: 'agent-node',
+ data: expect.objectContaining({
+ agent_declared_outputs: expect.arrayContaining([
+ expect.objectContaining({
+ name: 'qna_report',
+ type: 'string',
+ }),
+ ]),
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
+ })
+
+ it('renames the current prompt output token instead of creating a separate output', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_task: 'Generate [§output:qna_report:qna_report§]',
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ act(() => {
+ mockPromptEditorProps[0]?.agentOutputBlock?.onEdit?.('qna_report', 'string')
+ })
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' }), {
+ target: {
+ value: 'final_report',
+ },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.confirm' }))
+
+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
+ {
+ id: 'agent-node',
+ data: expect.objectContaining({
+ agent_task: 'Generate [§output:final_report:final_report§]',
+ agent_declared_outputs: expect.arrayContaining([
+ expect.objectContaining({
+ name: 'final_report',
+ type: 'string',
+ }),
+ ]),
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
+ const updatedData = mockHandleNodeDataUpdateWithSyncDraft.mock.calls.at(-1)?.[0].data as AgentV2NodeType
+ expect(updatedData.agent_declared_outputs?.some(output => output.name === 'qna_report')).toBe(false)
+ expect(screen.getByText('final_report')).toBeInTheDocument()
+ })
+
+ it('reconciles inline prompt output renames with the existing declared output row', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_task: 'Generate [§output:qna_report:qna_report§]',
+ agent_declared_outputs: [{
+ name: 'qna_report',
+ type: 'string',
+ required: false,
+ description: 'Old report',
+ }],
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ act(() => {
+ mockPromptEditorProps[0]?.agentOutputBlock?.onChange?.([
+ {
+ name: 'qna_report',
+ type: 'string',
+ required: false,
+ description: 'Old report',
+ },
+ {
+ name: 'final_report',
+ type: 'string',
+ required: false,
+ },
+ ], 'Generate [§output:final_report:final_report§]')
+ })
+
+ const updatedData = mockHandleNodeDataUpdateWithSyncDraft.mock.calls.at(-1)?.[0].data as AgentV2NodeType
+ expect(updatedData.agent_task).toBe('Generate [§output:final_report:final_report§]')
+ expect(updatedData.agent_declared_outputs).toEqual([
+ expect.objectContaining({
+ name: 'final_report',
+ type: 'string',
+ }),
+ ])
+ expect(screen.getByText('final_report')).toBeInTheDocument()
+ })
+
+ it('keeps output variables synced when prompt text rename arrives before output block data', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_task: 'Generate [§output:qna_report:qna_report§]',
+ agent_declared_outputs: [{
+ name: 'qna_report',
+ type: 'string',
+ required: false,
+ description: 'Old report',
+ }],
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ act(() => {
+ mockPromptEditorProps[0]?.onChange?.('Generate [§output:final_report:final_report§]')
+ })
+
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({
+ agent_task: 'Generate [§output:final_report:final_report§]',
+ agent_declared_outputs: [
+ expect.objectContaining({
+ name: 'final_report',
+ type: 'string',
+ description: 'Old report',
+ }),
+ ],
+ }))
+ expect(screen.getByText('final_report')).toBeInTheDocument()
+ })
+
it('syncs declared outputs created from the agent task editor', () => {
render(
<AgentV2Panel
diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
index 3db9cf28e15..8c2f602aa5e 100644
--- a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
@@ -2,6 +2,7 @@ import type { AgentSoulConfig, WorkflowAgentComposerResponse } from '@dify/contr
import type { DefaultModelResponse } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { debounce } from 'es-toolkit/compat'
+import isEqual from 'fast-deep-equal'
import { useStore as useJotaiStore, useSetAtom } from 'jotai'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
@@ -144,9 +145,18 @@ export function useWorkflowInlineAgentConfigureSync({
if (!enabledRef.current)
return
+ const configSnapshot = getAgentSoulDraft()
+ const hasEffectiveModelChange = !isEqual(configSnapshot.model, baseConfigRef.current?.model)
debouncedSaveDraft.cancel?.()
- return saveComposer(getAgentSoulDraft())
- }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer])
+ if (!store.get(isAgentComposerDirtyAtom) && !hasEffectiveModelChange)
+ return
+
+ return saveComposer(configSnapshot)
+ }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer, store])
+ const saveAgentSoulConfig = useCallback(async (agentSoulConfig: AgentSoulConfig) => {
+ debouncedSaveDraft.cancel?.()
+ return saveComposer(agentSoulConfig)
+ }, [debouncedSaveDraft, saveComposer])
useEffect(() => {
return store.sub(agentComposerDraftAtom, () => {
@@ -175,6 +185,7 @@ export function useWorkflowInlineAgentConfigureSync({
return {
draftSavedAt,
+ saveAgentSoulConfig,
saveDraft,
}
}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
index 4905f88c1b6..ba6dd76ee08 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -1,11 +1,18 @@
import type { AgentSoulConfig, WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { WorkflowInlineAgentConfigureWorkspace } from '../agent-orchestrate-panel-content'
const mocks = vi.hoisted(() => ({
checkoutBuildDraft: vi.fn(),
+ deleteBuildDraft: vi.fn(),
+ loadBuildDraft: vi.fn(),
+ applyBuildDraft: vi.fn(),
+ finalizeBuildChat: vi.fn(),
+ refreshDebugConversation: vi.fn(),
+ saveBuildDraft: vi.fn(),
+ saveAgentSoulConfig: vi.fn(),
saveDraft: vi.fn(),
}))
@@ -18,14 +25,50 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()
}),
}))
-vi.mock('@/features/agent-v2/agent-detail/configure/components/orchestrate', () => ({
- AgentOrchestratePanel: (props: {
- bottomBar?: ReactNode
- headerAction?: ReactNode
+vi.mock('@/features/agent-v2/agent-detail/configure/components/orchestrate', async () => {
+ const { useAtom } = await import('jotai')
+ const { agentComposerDraftAtom } = await import('@/features/agent-v2/agent-composer/store')
+
+ return {
+ AgentOrchestratePanel: (props: {
+ bottomAction?: ReactNode
+ headerAction?: ReactNode
+ isBuildDraftActive?: boolean
+ readOnly?: boolean
+ }) => {
+ const [draft, setDraft] = useAtom(agentComposerDraftAtom)
+
+ return (
+ <div role="region" aria-label="orchestrate-panel">
+ <span>{`readonly:${props.readOnly ? 'yes' : 'no'}`}</span>
+ <span>{`buildDraft:${props.isBuildDraftActive ? 'yes' : 'no'}`}</span>
+ {props.headerAction}
+ <input
+ aria-label="local composer draft"
+ value={draft.prompt}
+ onChange={event => setDraft({
+ ...draft,
+ prompt: event.currentTarget.value,
+ })}
+ />
+ {props.bottomAction}
+ </div>
+ )
+ },
+ }
+})
+
+vi.mock('@/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar', () => ({
+ AgentBuildDraftBar: (props: {
+ changesCount: number
+ disabled?: boolean
+ onApply: () => void
+ onDiscard: () => void
}) => (
- <div role="region" aria-label="orchestrate-panel">
- {props.headerAction}
- {props.bottomBar}
+ <div role="region" aria-label="build-draft-bar">
+ <span>{`changes:${props.changesCount}`}</span>
+ <button type="button" disabled={props.disabled} onClick={props.onApply}>apply build draft</button>
+ <button type="button" disabled={props.disabled} onClick={props.onDiscard}>discard build draft</button>
</div>
),
}))
@@ -34,26 +77,59 @@ vi.mock('@/features/agent-v2/agent-detail/configure/components/preview/build-bac
AgentBuildPanelBackground: () => null,
}))
-vi.mock('@/features/agent-v2/agent-detail/configure/components/preview/build-chat', () => ({
- AgentBuildChat: (props: {
- onSaveDraftBeforeRun?: () => Promise<void>
- }) => (
- <div role="region" aria-label="build-chat">
- <button
- type="button"
- onClick={() => {
- void props.onSaveDraftBeforeRun?.()
- }}
- >
- start build
- </button>
- </div>
- ),
-}))
+vi.mock('@/features/agent-v2/agent-detail/configure/components/preview/build-chat', async () => {
+ const { useState } = await import('react')
+
+ return {
+ AgentBuildChat: (props: {
+ conversationId?: string | null
+ onConversationComplete?: (conversationId: string, workflowRunId?: string) => void
+ onConversationIdChange?: (conversationId: string) => void
+ onSendInterrupted?: () => void
+ onSaveDraftBeforeRun?: () => Promise<AgentSoulConfig | void>
+ }) => {
+ const [messageSent, setMessageSent] = useState(false)
+ const [sentPrompt, setSentPrompt] = useState<string | undefined>()
+
+ return (
+ <div role="region" aria-label="build-chat">
+ <span>{`build:${props.conversationId ?? 'none'}`}</span>
+ <span>{`sent:${messageSent ? 'yes' : 'no'}`}</span>
+ <span>{`prompt:${sentPrompt ?? 'none'}`}</span>
+ <button
+ type="button"
+ onClick={() => {
+ void props.onSaveDraftBeforeRun?.().then((agentSoulConfig) => {
+ setSentPrompt(agentSoulConfig?.prompt?.system_prompt)
+ setMessageSent(true)
+ props.onConversationIdChange?.('build-conversation-new')
+ })
+ }}
+ >
+ send build message
+ </button>
+ <button type="button" onClick={() => props.onConversationComplete?.('build-conversation-new', 'workflow-run-1')}>
+ complete build conversation
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setMessageSent(true)
+ props.onSendInterrupted?.()
+ }}
+ >
+ fail build conversation
+ </button>
+ </div>
+ )
+ },
+ }
+})
vi.mock('@/app/components/workflow/nodes/agent-v2/agent-soul-config', () => ({
useWorkflowInlineAgentConfigureSync: () => ({
draftSavedAt: undefined,
+ saveAgentSoulConfig: mocks.saveAgentSoulConfig,
saveDraft: mocks.saveDraft,
}),
}))
@@ -62,6 +138,25 @@ vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
byAgentId: {
+ get: {
+ queryKey: () => ['agent-detail'],
+ },
+ debugConversation: {
+ refresh: {
+ post: {
+ mutationOptions: (options?: {
+ onSuccess?: (data: {
+ debug_conversation_has_messages: boolean
+ debug_conversation_id: string
+ debug_conversation_message_count: number
+ }) => void
+ }) => ({
+ mutationFn: mocks.refreshDebugConversation,
+ ...options,
+ }),
+ },
+ },
+ },
composer: {
get: {
queryOptions: vi.fn(),
@@ -69,7 +164,21 @@ vi.mock('@/service/client', () => ({
},
buildDraft: {
get: {
- queryOptions: () => ({ queryKey: ['build-draft'] }),
+ queryOptions: () => ({
+ queryKey: ['build-draft'],
+ queryFn: mocks.loadBuildDraft,
+ }),
+ },
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.deleteBuildDraft }),
+ },
+ put: {
+ mutationOptions: () => ({ mutationFn: mocks.saveBuildDraft }),
+ },
+ apply: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.applyBuildDraft }),
+ },
},
checkout: {
post: {
@@ -77,13 +186,120 @@ vi.mock('@/service/client', () => ({
},
},
},
+ buildChat: {
+ finalize: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.finalizeBuildChat }),
+ },
+ },
+ },
+ sandbox: {
+ files: {
+ get: {
+ queryOptions: () => ({
+ queryKey: ['sandbox-files'],
+ queryFn: () => Promise.resolve({
+ entries: [{
+ name: 'result.txt',
+ type: 'file',
+ }],
+ path: '.',
+ }),
+ }),
+ },
+ read: {
+ get: {
+ queryOptions: () => ({
+ queryKey: ['sandbox-file'],
+ queryFn: () => Promise.resolve({
+ text: 'result',
+ }),
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ apps: {
+ byAppId: {
+ workflowRuns: {
+ byWorkflowRunId: {
+ agentNodes: {
+ byNodeId: {
+ sandbox: {
+ files: {
+ get: {
+ key: () => ['workflow-agent-node-sandbox-files'],
+ queryOptions: () => ({
+ queryKey: ['workflow-agent-node-sandbox-files'],
+ queryFn: () => Promise.resolve({
+ entries: [{
+ name: 'result.txt',
+ type: 'file',
+ }],
+ path: '.',
+ }),
+ }),
+ },
+ read: {
+ get: {
+ queryOptions: () => ({
+ queryKey: ['workflow-agent-node-sandbox-file'],
+ queryFn: () => Promise.resolve({
+ text: 'result',
+ }),
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ workflows: {
+ draft: {
+ nodes: {
+ byNodeId: {
+ agentComposer: {
+ get: {
+ queryKey: ({ input }: {
+ input: {
+ params: {
+ app_id: string
+ node_id: string
+ }
+ }
+ }) => ['workflow-agent-composer', input.params.app_id, input.params.node_id],
+ },
+ },
+ },
+ },
+ },
+ },
},
},
},
}))
-function createInlineComposerState(): WorkflowAgentComposerResponse {
+function createInlineComposerState({
+ debugConversationHasMessages = false,
+ debugConversationId = null,
+ debugConversationMessageCount = 0,
+ snapshotId = 'snapshot-1',
+ systemPrompt = 'Help with workflow tasks.',
+}: {
+ debugConversationHasMessages?: boolean
+ debugConversationId?: string | null
+ debugConversationMessageCount?: number
+ snapshotId?: string
+ systemPrompt?: string
+} = {}): WorkflowAgentComposerResponse {
return {
+ active_config_snapshot: {
+ id: snapshotId,
+ },
agent: {
id: 'agent-1',
icon: 'A',
@@ -94,42 +310,74 @@ function createInlineComposerState(): WorkflowAgentComposerResponse {
agent_soul: {
schema_version: 1,
prompt: {
- system_prompt: 'Help with workflow tasks.',
+ system_prompt: systemPrompt,
},
} satisfies AgentSoulConfig,
binding: {
id: 'binding-1',
binding_type: 'inline_agent',
agent_id: 'agent-1',
- current_snapshot_id: 'snapshot-1',
+ current_snapshot_id: snapshotId,
workflow_id: 'workflow-1',
node_id: 'node-1',
},
+ debug_conversation_has_messages: debugConversationHasMessages,
+ debug_conversation_id: debugConversationId,
+ debug_conversation_message_count: debugConversationMessageCount,
} as WorkflowAgentComposerResponse
}
describe('WorkflowInlineAgentConfigureWorkspace', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.loadBuildDraft.mockRejectedValue(new Response(null, { status: 404 }))
mocks.checkoutBuildDraft.mockResolvedValue({
agent_soul: {},
draft: {},
variant: 'agent_app',
})
+ mocks.deleteBuildDraft.mockResolvedValue({ result: 'success' })
+ mocks.applyBuildDraft.mockResolvedValue({
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.finalizeBuildChat.mockResolvedValue({ result: 'success' })
+ mocks.refreshDebugConversation.mockResolvedValue({
+ debug_conversation_has_messages: false,
+ debug_conversation_id: 'build-conversation-refreshed',
+ debug_conversation_message_count: 0,
+ })
+ mocks.saveBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Help with workflow tasks.',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
mocks.saveDraft.mockResolvedValue(createInlineComposerState())
+ mocks.saveAgentSoulConfig.mockResolvedValue(createInlineComposerState())
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
})
function renderWorkspace(props: {
+ inlineComposerState?: WorkflowAgentComposerResponse
onSaveInlineToRoster?: () => void
} = {}) {
const queryClient = new QueryClient()
- render(
+ return render(
<QueryClientProvider client={queryClient}>
<WorkflowInlineAgentConfigureWorkspace
agentId="agent-1"
appId="app-1"
- inlineComposerState={createInlineComposerState()}
+ inlineComposerState={props.inlineComposerState ?? createInlineComposerState()}
nodeId="node-1"
onSaveInlineToRoster={props.onSaveInlineToRoster}
open
@@ -139,55 +387,468 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
}
describe('Working Directory', () => {
- it('should show save-to-roster in the configure header menu without rendering the old action bar', () => {
+ it('should show save-to-roster in the configure header menu without rendering the old action bar', async () => {
renderWorkspace({
onSaveInlineToRoster: vi.fn(),
})
- expect(screen.getByRole('button', { name: 'common.operation.more' })).toBeInTheDocument()
+ expect(await screen.findByRole('button', { name: 'common.operation.more' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.save' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
})
it('should show the working directory panel when the header action is clicked', async () => {
- renderWorkspace()
+ renderWorkspace({
+ inlineComposerState: createInlineComposerState({
+ debugConversationHasMessages: true,
+ debugConversationId: 'inline-debug-conversation-1',
+ debugConversationMessageCount: 1,
+ }),
+ })
- fireEvent.click(screen.getByRole('button', {
+ fireEvent.click(await screen.findByRole('button', {
+ name: 'complete build conversation',
+ }))
+ fireEvent.click(await screen.findByRole('button', {
name: 'agentV2.agentDetail.configure.workingDirectory.open',
}))
expect(await screen.findByRole('dialog', {
name: 'agentV2.agentDetail.configure.workingDirectory.title',
})).toBeInTheDocument()
- expect(screen.getByRole('region', {
- name: 'agentV2.agentDetail.configure.workingDirectory.treeLabel',
- })).toBeInTheDocument()
+ expect(await screen.findAllByText('result.txt')).not.toHaveLength(0)
})
})
describe('Build Chat', () => {
- it('should save the workflow agent draft and checkout a build draft before starting build chat', async () => {
+ it('should save the workflow agent draft and write that snapshot into the build draft before starting build chat', async () => {
+ mocks.saveDraft.mockResolvedValue(createInlineComposerState({
+ snapshotId: 'snapshot-saved',
+ systemPrompt: 'Saved workflow snapshot prompt.',
+ }))
renderWorkspace()
- fireEvent.click(screen.getByRole('button', { name: 'start build' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
await waitFor(() => expect(mocks.saveDraft).toHaveBeenCalled())
- expect(mocks.checkoutBuildDraft).toHaveBeenCalledWith({
+ expect(mocks.saveBuildDraft).toHaveBeenCalledWith({
params: {
agent_id: 'agent-1',
},
body: {
- force: false,
+ variant: 'agent_app',
+ save_strategy: 'save_to_current_version',
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Saved workflow snapshot prompt.',
+ }),
+ }),
},
}, expect.any(Object))
const saveDraftCallOrder = mocks.saveDraft.mock.invocationCallOrder[0]
- const checkoutBuildDraftCallOrder = mocks.checkoutBuildDraft.mock.invocationCallOrder[0]
+ const saveBuildDraftCallOrder = mocks.saveBuildDraft.mock.invocationCallOrder[0]
expect(saveDraftCallOrder).toBeDefined()
- expect(checkoutBuildDraftCallOrder).toBeDefined()
- if (saveDraftCallOrder === undefined || checkoutBuildDraftCallOrder === undefined)
- throw new Error('Expected save draft and checkout mutations to be called')
+ expect(saveBuildDraftCallOrder).toBeDefined()
+ if (saveDraftCallOrder === undefined || saveBuildDraftCallOrder === undefined)
+ throw new Error('Expected workflow draft and build draft saves to be called')
+
+ expect(saveDraftCallOrder).toBeLessThan(saveBuildDraftCallOrder)
+ expect(mocks.checkoutBuildDraft).not.toHaveBeenCalled()
+ })
+
+ it('should use the saved build draft response as the build chat source', async () => {
+ mocks.saveDraft.mockResolvedValue(createInlineComposerState({
+ snapshotId: 'snapshot-saved',
+ systemPrompt: 'Saved workflow snapshot prompt.',
+ }))
+ mocks.saveBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Normalized build draft prompt.',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
+
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes')
+ })
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('prompt:Normalized build draft prompt.')
+ })
+
+ it('should enter build draft mode without resetting the current inline build chat', async () => {
+ mocks.loadBuildDraft
+ .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.saveBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ expect(await screen.findByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeDisabled()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
+
+ await waitFor(() => expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes'))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:build-conversation-new')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:yes')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:yes')
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeDisabled()
+
+ vi.useFakeTimers()
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(mocks.loadBuildDraft).toHaveBeenCalled()
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes')
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:build-conversation-new')
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeEnabled()
+ })
+
+ it('should seed inline build chat from the workflow composer debug conversation when reopening build draft', async () => {
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+
+ renderWorkspace({
+ inlineComposerState: createInlineComposerState({
+ debugConversationId: 'inline-debug-conversation-1',
+ }),
+ })
+
+ expect(await screen.findByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:inline-debug-conversation-1')
+ expect(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeEnabled()
+ })
+
+ it('should keep restart disabled when workflow composer debug conversation has no messages', async () => {
+ renderWorkspace({
+ inlineComposerState: createInlineComposerState({
+ debugConversationHasMessages: false,
+ debugConversationId: 'inline-debug-conversation-1',
+ debugConversationMessageCount: 0,
+ }),
+ })
+
+ expect(await screen.findByRole('region', { name: 'build-chat' })).toHaveTextContent('build:inline-debug-conversation-1')
+ expect(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeDisabled()
+ })
+
+ it('should refresh inline debug conversation when restarting an existing debug chat', async () => {
+ renderWorkspace({
+ inlineComposerState: createInlineComposerState({
+ debugConversationHasMessages: true,
+ debugConversationId: 'inline-debug-conversation-1',
+ debugConversationMessageCount: 1,
+ }),
+ })
+
+ expect(await screen.findByRole('region', { name: 'build-chat' })).toHaveTextContent('build:inline-debug-conversation-1')
+ fireEvent.click(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ }))
+
+ await waitFor(() => expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object)))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should re-enable inline build draft actions when build chat fails', async () => {
+ mocks.loadBuildDraft
+ .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.saveBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
+
+ await waitFor(() => expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled())
+
+ fireEvent.click(screen.getByRole('button', { name: 'fail build conversation' }))
+
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ })).toBeEnabled()
+ })
+
+ it('should not let a previous inline build completion refresh unlock a new build run', async () => {
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ await screen.findByRole('region', { name: 'build-draft-bar' })
+ const initialBuildDraftLoadCount = mocks.loadBuildDraft.mock.calls.length
+
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled())
+
+ vi.useFakeTimers()
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(mocks.loadBuildDraft).toHaveBeenCalledTimes(initialBuildDraftLoadCount)
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
+ })
+
+ it('should refresh the inline build debug conversation when restarting after a build send', async () => {
+ mocks.loadBuildDraft
+ .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.saveBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'send build message' }))
+ await waitFor(() => expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:build-conversation-new'))
+
+ fireEvent.click(screen.getByRole('button', { name: 'fail build conversation' }))
+ fireEvent.click(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.preview.restart',
+ }))
+
+ await waitFor(() => expect(mocks.deleteBuildDraft).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object)))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should apply inline build draft through the workflow node composer owner', async () => {
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Applied inline build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'apply build draft' }))
+
+ await waitFor(() => expect(mocks.saveAgentSoulConfig).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Applied inline build prompt',
+ }),
+ })))
+ expect(mocks.deleteBuildDraft).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object))
+ expect(mocks.applyBuildDraft).not.toHaveBeenCalled()
+ })
+
+ it('should keep exiting inline build draft when debug conversation refresh fails after applying', async () => {
+ mocks.refreshDebugConversation.mockRejectedValueOnce(new Error('refresh failed'))
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Applied inline build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'apply build draft' }))
+
+ await waitFor(() => expect(mocks.saveAgentSoulConfig).toHaveBeenCalled())
+ expect(mocks.deleteBuildDraft).toHaveBeenCalled()
+ await waitFor(() => expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument())
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
+ })
+
+ it('should refresh the inline build debug conversation when discarding the build draft', async () => {
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Discarded inline build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'discard build draft' }))
+
+ await waitFor(() => expect(mocks.deleteBuildDraft).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object)))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should keep exiting inline build draft when debug conversation refresh fails after discarding', async () => {
+ mocks.refreshDebugConversation.mockRejectedValueOnce(new Error('refresh failed'))
+ mocks.loadBuildDraft.mockResolvedValue({
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Discarded inline build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ renderWorkspace()
+
+ fireEvent.click(await screen.findByRole('button', { name: 'discard build draft' }))
+
+ await waitFor(() => expect(mocks.deleteBuildDraft).toHaveBeenCalled())
+ await waitFor(() => expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument())
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
+ })
+
+ it('should keep the composer session mounted when the inline snapshot changes', async () => {
+ const { rerender } = renderWorkspace({
+ inlineComposerState: createInlineComposerState({ snapshotId: 'snapshot-1' }),
+ })
+ const localDraftInput = await screen.findByRole('textbox', { name: 'local composer draft' })
+
+ fireEvent.change(localDraftInput, { target: { value: 'draft still mounted' } })
+
+ rerender(
+ <QueryClientProvider client={new QueryClient()}>
+ <WorkflowInlineAgentConfigureWorkspace
+ agentId="agent-1"
+ appId="app-1"
+ inlineComposerState={createInlineComposerState({ snapshotId: 'snapshot-2' })}
+ nodeId="node-1"
+ open
+ />
+ </QueryClientProvider>,
+ )
- expect(saveDraftCallOrder).toBeLessThan(checkoutBuildDraftCallOrder)
+ expect(screen.getByRole('textbox', { name: 'local composer draft' })).toHaveValue('draft still mounted')
})
})
})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
index 43d1821b502..7b7e6fe0bb5 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
@@ -1,6 +1,6 @@
'use client'
-import type { AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentAppDetailWithSite, AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { AgentComposerBindingResponse, WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
import {
DropdownMenu,
@@ -8,24 +8,35 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { skipToken, useQuery } from '@tanstack/react-query'
-import { useAtom } from 'jotai'
-import { useState } from 'react'
+import { toast } from '@langgenius/dify-ui/toast'
+import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useAtom, useAtomValue, useStore as useJotaiStore, useSetAtom } from 'jotai'
+import { ScopeProvider } from 'jotai-scope'
+import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
-import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
+import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import { agentComposerDraftAtom, rebaseAgentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
import { AgentOrchestratePanel } from '@/features/agent-v2/agent-detail/configure/components/orchestrate'
+import { AgentBuildDraftBar } from '@/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar'
import { AgentBuildPanelBackground } from '@/features/agent-v2/agent-detail/configure/components/preview/build-background'
-import { AgentBuildChat } from '@/features/agent-v2/agent-detail/configure/components/preview/build-chat'
import { AgentPreviewHeader } from '@/features/agent-v2/agent-detail/configure/components/preview/header'
-import { useAgentWorkingDirectoryPanel } from '@/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel'
+import { invalidateAgentWorkingDirectoryFiles, useAgentWorkingDirectoryPanel } from '@/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel'
+import { AgentConfigureRightPanelChat } from '@/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat'
import { AgentConfigurePreviewSurface, AgentConfigureWorkspace } from '@/features/agent-v2/agent-detail/configure/components/workspace'
-import { useAgentPreviewSoulConfig } from '@/features/agent-v2/agent-detail/configure/hooks'
-import { usePrepareAgentBuildDraftBeforeRun } from '@/features/agent-v2/agent-detail/configure/use-agent-build-draft-run'
+import {
+ agentConfigureConversationIdsAtom,
+ agentConfigureRightPanelChatModeAtom,
+ agentConfigureScopedAtoms,
+ agentConfigureSoulSourceOverrideAtom,
+ resetAgentConfigureConversationAtom,
+ setAgentConfigureConversationIdAtom,
+} from '@/features/agent-v2/agent-detail/configure/state'
+import { useAgentConfigureBuildDraftActions, useAgentConfigureBuildDraftData } from '@/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft'
import { consoleQuery } from '@/service/client'
import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'
@@ -150,21 +161,75 @@ export function WorkflowInlineAgentConfigureWorkspace(props: WorkflowInlineAgent
)
}
- const composerSessionKey = `${nodeId}:${agentId}:${activeConfigSnapshot?.id ?? 'draft'}`
+ const composerSessionKey = `${nodeId}:${agentId}`
return (
- <AgentComposerProvider
- key={composerSessionKey}
- initialDraft={agentSoulConfigToFormState(agentSoulConfig)}
- initialOriginalConfig={agentSoulConfig}
- >
- <WorkflowInlineAgentConfigureWorkspaceContent
+ <ScopeProvider key={composerSessionKey} atoms={agentConfigureScopedAtoms} name="WorkflowInlineAgentConfigure">
+ <WorkflowInlineAgentConfigureWorkspaceComposerScope
{...props}
activeConfigSnapshot={activeConfigSnapshot}
agentId={agentId}
agentSoulConfig={agentSoulConfig}
/>
- </AgentComposerProvider>
+ </ScopeProvider>
+ )
+}
+
+function WorkflowInlineAgentConfigureWorkspaceComposerScope({
+ agentId,
+ agentSoulConfig,
+ activeConfigSnapshot,
+ ...props
+}: Omit<WorkflowInlineAgentConfigureWorkspaceProps, 'agentId'> & {
+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
+ agentId: string
+ agentSoulConfig: AgentSoulConfig
+}) {
+ const soulSourceOverride = useAtomValue(agentConfigureSoulSourceOverrideAtom)
+ const setSoulSourceOverride = useSetAtom(agentConfigureSoulSourceOverrideAtom)
+ const buildDraft = useAgentConfigureBuildDraftData({
+ agentId,
+ activeVersionId: activeConfigSnapshot?.id,
+ composerAgentSoulConfig: agentSoulConfig,
+ isViewingVersion: false,
+ normalAgentSoulConfig: agentSoulConfig,
+ setSoulSourceOverride,
+ soulSourceOverride,
+ })
+ const composerSessionKey = `${props.nodeId}:${agentId}`
+
+ if (buildDraft.isPending) {
+ return (
+ <div className="flex h-full min-h-80 items-center justify-center bg-components-panel-bg">
+ <Loading type="app" />
+ </div>
+ )
+ }
+
+ return (
+ <ScopeProvider
+ atoms={[
+ [agentConfigureConversationIdsAtom, {
+ build: props.inlineComposerState?.debug_conversation_id ?? null,
+ preview: null,
+ }],
+ ]}
+ name="WorkflowInlineAgentConfigureConversation"
+ >
+ <AgentComposerProvider
+ key={composerSessionKey}
+ initialDraft={agentSoulConfigToFormState(buildDraft.agentSoulConfig)}
+ initialOriginalConfig={buildDraft.agentSoulConfig}
+ >
+ <WorkflowInlineAgentConfigureWorkspaceContent
+ {...props}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentId={agentId}
+ agentSoulConfig={agentSoulConfig}
+ buildDraft={buildDraft}
+ />
+ </AgentComposerProvider>
+ </ScopeProvider>
)
}
@@ -173,6 +238,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
agentId,
agentSoulConfig,
appId,
+ buildDraft,
inlineComposerState,
nodeId,
onClose,
@@ -183,14 +249,30 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
agentId: string
agentSoulConfig: AgentSoulConfig
+ buildDraft: ReturnType<typeof useAgentConfigureBuildDraftData>
}) {
- const { t } = useTranslation()
- const [clearChatList, setClearChatList] = useState(false)
- const [conversationId, setConversationId] = useState<string | null>(null)
- const workingDirectoryPanel = useAgentWorkingDirectoryPanel()
+ const { t } = useTranslation('common')
+ const queryClient = useQueryClient()
+ const jotaiStore = useJotaiStore()
const composerState = inlineComposerState
+ const [buildDraftActionsDisabled, setBuildDraftActionsDisabled] = useState(false)
+ const [clearPreviewChat, setClearPreviewChat] = useState(false)
+ const [workflowRunId, setWorkflowRunId] = useState<string | null>(null)
+ const conversationIds = useAtomValue(agentConfigureConversationIdsAtom)
+ const rightPanelChatMode = useAtomValue(agentConfigureRightPanelChatModeAtom)
+ const workingDirectoryPanel = useAgentWorkingDirectoryPanel({
+ agentId,
+ appId,
+ conversationId: conversationIds[rightPanelChatMode],
+ nodeId,
+ workflowRunId,
+ })
+ const resetConversation = useSetAtom(resetAgentConfigureConversationAtom)
+ const setConversationId = useSetAtom(setAgentConfigureConversationIdAtom)
+ const rebaseComposerDraft = useSetAtom(rebaseAgentComposerDraftAtom)
const { currentModel, setConfigureModel, textGenerationModelList } = useAgentOrchestrateModelOptions()
- const { draftSavedAt, saveDraft } = useWorkflowInlineAgentConfigureSync({
+ const [isApplyingInlineBuildDraft, setIsApplyingInlineBuildDraft] = useState(false)
+ const { draftSavedAt, saveAgentSoulConfig, saveDraft } = useWorkflowInlineAgentConfigureSync({
nodeId,
baseConfig: agentSoulConfig,
currentModel,
@@ -206,14 +288,198 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
onSaved?.(binding)
},
- enabled: open && !!agentSoulConfig,
+ enabled: open && !!agentSoulConfig && !buildDraft.isActive,
})
- const buildDraftRun = usePrepareAgentBuildDraftBeforeRun({
+ const refreshDebugConversationMutation = useMutation(consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions({
+ onSuccess: ({
+ debug_conversation_has_messages,
+ debug_conversation_id,
+ debug_conversation_message_count,
+ }) => {
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ (agentDetail) => {
+ if (!agentDetail)
+ return agentDetail
+
+ return {
+ ...agentDetail,
+ debug_conversation_has_messages,
+ debug_conversation_id,
+ debug_conversation_message_count,
+ }
+ },
+ )
+ if (!appId)
+ return
+
+ queryClient.setQueryData<WorkflowAgentComposerResponse | undefined>(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: {
+ app_id: appId,
+ node_id: nodeId,
+ },
+ },
+ }),
+ composerState => composerState
+ ? {
+ ...composerState,
+ debug_conversation_has_messages,
+ debug_conversation_id,
+ debug_conversation_message_count,
+ }
+ : composerState,
+ )
+ },
+ }))
+ const {
+ mutateAsync: refreshDebugConversationRequestAsync,
+ isPending: isRefreshingDebugConversation,
+ } = refreshDebugConversationMutation
+ const refreshDebugConversationInput = useCallback(() => ({
+ params: {
+ agent_id: agentId,
+ },
+ }), [agentId])
+ const refreshDebugConversationAsync = useCallback(() => {
+ return refreshDebugConversationRequestAsync(refreshDebugConversationInput())
+ }, [refreshDebugConversationInput, refreshDebugConversationRequestAsync])
+ const resetBuildChatSession = useCallback(async () => {
+ await refreshDebugConversationAsync().catch(() => undefined)
+ setConversationId({ mode: 'build', conversationId: null })
+ setWorkflowRunId(null)
+ setClearPreviewChat(true)
+ }, [refreshDebugConversationAsync, setClearPreviewChat, setConversationId, setWorkflowRunId])
+ const rebaseComposerDraftFromSoulConfig = useCallback((agentSoulConfig?: AgentSoulConfig) => {
+ rebaseComposerDraft({
+ draft: agentSoulConfigToFormState(agentSoulConfig),
+ originalConfig: agentSoulConfig,
+ })
+ }, [rebaseComposerDraft])
+ const buildDraftActions = useAgentConfigureBuildDraftActions({
agentId,
- isBuildDraftActive: false,
- saveDraft,
+ buildDraftAgentSoulConfig: buildDraft.agentSoulConfig,
+ isActive: buildDraft.isActive,
+ normalAgentSoulConfig: agentSoulConfig,
+ rebaseComposerDraft: rebaseComposerDraftFromSoulConfig,
+ refetchBuildDraft: buildDraft.refetch,
+ refetchComposer: async () => ({
+ data: {
+ agent_soul: agentSoulConfig,
+ },
+ }),
+ resetBuildChatSession,
+ saveDraft: async () => {
+ await saveDraft()
+ },
+ setSoulSourceOverride: buildDraft.setSoulSourceOverride,
})
- const previewAgentSoulConfig = useAgentPreviewSoulConfig(agentSoulConfig as AgentSoulConfig | undefined)
+ const { cancelBuildDraftRefresh } = buildDraftActions
+ const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ })
+ const { mutateAsync: saveBuildDraft } = useMutation(consoleQuery.agent.byAgentId.buildDraft.put.mutationOptions())
+ const discardBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions())
+ const getInlineAgentSoulDraft = useCallback(() => formStateToAgentSoulConfig({
+ baseConfig: agentSoulConfig,
+ formState: jotaiStore.get(agentComposerDraftAtom),
+ currentModel,
+ }), [agentSoulConfig, currentModel, jotaiStore])
+ const prepareInlineBuildDraftBeforeRun = useCallback(async () => {
+ cancelBuildDraftRefresh()
+ const configSnapshot = getInlineAgentSoulDraft()
+ const savedComposerState = await saveDraft()
+ const preparedAgentSoulConfig = savedComposerState?.agent_soul ?? configSnapshot
+ const buildDraftState = await saveBuildDraft({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ variant: 'agent_app',
+ save_strategy: 'save_to_current_version',
+ agent_soul: preparedAgentSoulConfig,
+ },
+ })
+
+ const savedBuildAgentSoulConfig = buildDraftState.agent_soul ?? preparedAgentSoulConfig
+ queryClient.setQueryData(buildDraftQueryOptions.queryKey, buildDraftState)
+ rebaseComposerDraftFromSoulConfig(savedBuildAgentSoulConfig)
+ buildDraft.setSoulSourceOverride('build-draft')
+ return savedBuildAgentSoulConfig
+ }, [agentId, buildDraft, buildDraftQueryOptions.queryKey, cancelBuildDraftRefresh, getInlineAgentSoulDraft, queryClient, rebaseComposerDraftFromSoulConfig, saveBuildDraft, saveDraft])
+ const applyInlineBuildDraft = async () => {
+ cancelBuildDraftRefresh()
+ setIsApplyingInlineBuildDraft(true)
+ try {
+ if (!buildDraft.agentSoulConfig)
+ return
+
+ const savedComposerState = await saveAgentSoulConfig(buildDraft.agentSoulConfig)
+ await discardBuildDraftMutation.mutateAsync({
+ params: {
+ agent_id: agentId,
+ },
+ }).catch(() => undefined)
+ await resetBuildChatSession().catch(() => undefined)
+ buildDraft.setSoulSourceOverride('draft')
+ queryClient.removeQueries({
+ queryKey: buildDraftQueryOptions.queryKey,
+ })
+ rebaseComposerDraftFromSoulConfig(savedComposerState?.agent_soul ?? buildDraft.agentSoulConfig)
+ toast.success(t('api.actionSuccess'))
+ }
+ catch {
+ toast.error(t('api.actionFailed'))
+ }
+ finally {
+ setIsApplyingInlineBuildDraft(false)
+ }
+ }
+ const discardInlineBuildDraft = async () => {
+ cancelBuildDraftRefresh()
+ try {
+ await discardBuildDraftMutation.mutateAsync({
+ params: {
+ agent_id: agentId,
+ },
+ })
+ await resetBuildChatSession().catch(() => undefined)
+ buildDraft.setSoulSourceOverride('draft')
+ queryClient.removeQueries({
+ queryKey: buildDraftQueryOptions.queryKey,
+ })
+ rebaseComposerDraftFromSoulConfig(agentSoulConfig)
+ toast.success(t('api.actionSuccess'))
+ }
+ catch {
+ toast.error(t('api.actionFailed'))
+ }
+ }
+ const hasRestartCurrentChatTarget = (inlineComposerState?.debug_conversation_has_messages ?? false)
+ || buildDraft.isActive
+ const isRestartCurrentChatDisabled = !hasRestartCurrentChatTarget
+ || buildDraftActionsDisabled
+ || isApplyingInlineBuildDraft
+ || discardBuildDraftMutation.isPending
+ || isRefreshingDebugConversation
+ const restartCurrentChat = () => {
+ if (isRestartCurrentChatDisabled)
+ return
+
+ if (buildDraft.isActive) {
+ void discardInlineBuildDraft()
+ return
+ }
+
+ void refreshDebugConversationAsync().catch(() => undefined)
+ resetConversation(rightPanelChatMode)
+ setClearPreviewChat(true)
+ }
return (
<AgentConfigureWorkspace
@@ -224,12 +490,31 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
appId={appId}
nodeId={nodeId}
activeConfigSnapshot={activeConfigSnapshot}
- agentSoulConfig={agentSoulConfig}
+ agentSoulConfig={buildDraft.agentSoulConfig}
agentName={composerState?.agent?.name}
currentModel={currentModel}
textGenerationModelList={textGenerationModelList}
draftSavedAt={draftSavedAt}
+ readOnly={buildDraft.isActive}
+ isBuildDraftActive={buildDraft.isActive}
+ buildDraftChangedKeys={buildDraft.changedKeys}
showPublishBar={false}
+ bottomAction={buildDraft.isActive
+ ? (
+ <AgentBuildDraftBar
+ changesCount={buildDraft.changesCount}
+ disabled={buildDraftActionsDisabled}
+ isApplying={isApplyingInlineBuildDraft}
+ isDiscarding={discardBuildDraftMutation.isPending}
+ onApply={() => {
+ void applyInlineBuildDraft()
+ }}
+ onDiscard={() => {
+ void discardInlineBuildDraft()
+ }}
+ />
+ )
+ : undefined}
headerAction={onSaveInlineToRoster
? <WorkflowInlineAgentConfigureMoreAction onSaveInlineToRoster={onSaveInlineToRoster} />
: undefined}
@@ -252,17 +537,15 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
onModeChange={() => undefined}
onToggleChatFeatures={() => undefined}
onOpenWorkingDirectory={workingDirectoryPanel.openWorkingDirectory}
- onRefresh={() => {
- setConversationId(null)
- setClearChatList(true)
- }}
+ onRefresh={restartCurrentChat}
+ refreshDisabled={isRestartCurrentChatDisabled}
showChatFeaturesAction={false}
trailingAction={(
<button
type="button"
onClick={onClose}
className="flex size-8 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- aria-label={t('operation.close', { ns: 'common' })}
+ aria-label={t('operation.close')}
>
<span aria-hidden className="i-ri-close-line size-4" />
</button>
@@ -270,19 +553,53 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
/>
)}
chat={(
- <AgentBuildChat
+ <AgentConfigureRightPanelChat
agentId={agentId}
agentIcon={composerState?.agent?.icon}
agentIconBackground={composerState?.agent?.icon_background}
- agentIconType={composerState?.agent?.icon_type as Parameters<typeof AgentBuildChat>[0]['agentIconType']}
+ agentIconType={composerState?.agent?.icon_type as Parameters<typeof AgentConfigureRightPanelChat>[0]['agentIconType']}
agentName={composerState?.agent?.name}
- agentSoulConfig={previewAgentSoulConfig}
- clearChatList={clearChatList}
- conversationId={conversationId}
+ agentSoulConfig={buildDraft.agentSoulConfig}
+ clearChatList={clearPreviewChat}
+ conversationIds={conversationIds}
draftType="debug_build"
- onClearChatListChange={setClearChatList}
- onConversationIdChange={setConversationId}
- onSaveDraftBeforeRun={buildDraftRun.prepareBuildDraftBeforeRun}
+ mode={rightPanelChatMode}
+ onClearChatListChange={setClearPreviewChat}
+ onConversationComplete={(mode, completedConversationId, completedWorkflowRunId) => {
+ if (mode === 'build') {
+ setWorkflowRunId(completedWorkflowRunId ?? completedConversationId)
+ invalidateAgentWorkingDirectoryFiles({
+ agentId,
+ appId,
+ conversationId: completedConversationId,
+ nodeId,
+ queryClient,
+ workflowRunId: completedWorkflowRunId ?? completedConversationId,
+ })
+ buildDraftActions.refreshBuildDraftAfterBuildChat(() => setBuildDraftActionsDisabled(false))
+ }
+ }}
+ onConversationIdChange={(mode, conversationId) => {
+ setConversationId({ mode, conversationId })
+ }}
+ onWorkflowRunIdChange={(nextWorkflowRunId) => {
+ if (nextWorkflowRunId)
+ setWorkflowRunId(nextWorkflowRunId)
+ }}
+ onSaveDraftBeforeRun={async () => {
+ setBuildDraftActionsDisabled(true)
+ setWorkflowRunId(null)
+ try {
+ return await prepareInlineBuildDraftBeforeRun()
+ }
+ catch (error) {
+ setBuildDraftActionsDisabled(false)
+ throw error
+ }
+ }}
+ onSendInterrupted={() => {
+ setBuildDraftActionsDisabled(false)
+ }}
/>
)}
/>
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
index e339fd3699b..35676cfbc76 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
@@ -112,6 +112,7 @@ export function AgentOutputVariables({
}: AgentOutputVariablesProps) {
const { t } = useTranslation()
const [editingState, setEditingState] = useState<EditingState | null>(null)
+ const [collapsed, setCollapsed] = useState(true)
function handleNewOutput() {
setEditingState({ draft: createDraft() })
}
@@ -213,7 +214,7 @@ export function AgentOutputVariables({
)
}
return (
- <OutputVars>
+ <OutputVars collapsed={collapsed} onCollapse={setCollapsed}>
<div className="pb-2">
<div className="flex flex-col">
{outputs.map((output, index) => {
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
index fb669684bcc..62b7336056e 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
@@ -206,6 +206,8 @@ function AgentRosterDrawer({
{showConsoleLink && (
<Link
href={getAgentDetailPath(agent.id, 'configure')}
+ target="_blank"
+ rel="noopener noreferrer"
className="inline-flex h-8 min-w-0 flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 text-[13px] leading-4 font-medium whitespace-nowrap text-components-button-secondary-text shadow-xs outline-hidden backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"
>
<span aria-hidden className="i-ri-external-link-line size-4 shrink-0" />
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
index ef20a3c7c9e..ae4a94a3df5 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
@@ -1,5 +1,6 @@
import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
import type { AgentV2NodeType } from '../types'
+import type { AgentOutputTypeOptionValue } from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'
import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types'
import { cn } from '@langgenius/dify-ui/cn'
import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'
@@ -61,6 +62,7 @@ export function AgentTaskField({
onChange,
outputs,
onOutputsChange,
+ onEditOutput,
}: {
id: string
data: AgentV2NodeType
@@ -68,6 +70,7 @@ export function AgentTaskField({
onChange: (value: string) => void
outputs: DeclaredOutputConfig[]
onOutputsChange: (outputs: DeclaredOutputConfig[], prompt?: string) => void
+ onEditOutput?: (name: string, outputType: AgentOutputTypeOptionValue) => void
}) {
const { t } = useTranslation()
const getVarType = useWorkflowVariableType()
@@ -140,6 +143,7 @@ export function AgentTaskField({
show: true,
outputs,
onChange: onOutputsChange,
+ onEdit: onEditOutput,
}}
>
{isFocus && (
diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsx
index a3c922de7ce..e30121e7cab 100644
--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx
@@ -1,12 +1,16 @@
-import type { AgentComposerBindingResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { AgentComposerBindingResponse, DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
import type { AgentRosterNodeData } from '../../block-selector/types'
import type { NodePanelProps } from '../../types'
import type { AgentV2NodeType } from './types'
+import type { AgentOutputTypeOptionValue } from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'
import { useMutation } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback, useEffect, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import {
+
+ createAgentOutputConfig,
extractAgentOutputNames,
replaceAgentOutputName,
} from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'
@@ -17,6 +21,8 @@ import useNodeCrud from '../_base/hooks/use-node-crud'
import { AgentAdvancedSettings } from './components/agent-advanced-settings'
import { WorkflowInlineAgentConfigureWorkspace, WorkflowRosterAgentOrchestratePanelContent } from './components/agent-orchestrate-panel-content'
import { AgentOutputVariables } from './components/agent-output-variables'
+import { OutputEditCard } from './components/agent-output-variables/edit-card'
+import { createDraft, isDefaultOutput } from './components/agent-output-variables/utils'
import { AgentRosterField } from './components/agent-roster-field'
import { AgentTaskField } from './components/agent-task-field'
import { SaveInlineAgentToRosterDialog } from './components/save-inline-agent-to-roster-dialog'
@@ -24,6 +30,70 @@ import { useAgentRosterDetail, useCreateInlineAgentBinding, useWorkflowInlineAge
import { getAgentV2DeclaredOutputs } from './output-variables'
import { hasValidInlineAgentBinding } from './types'
+function FloatingOutputEditor({
+ agentTask,
+ editOutputName,
+ editOutputRequestKey,
+ editOutputType,
+ outputs,
+ position,
+ onCancel,
+ onChange,
+}: {
+ agentTask?: string
+ editOutputName?: string
+ editOutputRequestKey?: number
+ editOutputType?: AgentOutputTypeOptionValue
+ outputs: DeclaredOutputConfig[]
+ position?: { left: number, top: number }
+ onCancel: () => void
+ onChange: (outputs: DeclaredOutputConfig[], agentTask?: string) => void
+}) {
+ if (!editOutputName || !position || typeof document === 'undefined')
+ return null
+
+ const outputIndex = outputs.findIndex(output => output.name === editOutputName)
+ const existingOutput = outputs[outputIndex]
+ if (existingOutput && isDefaultOutput(existingOutput))
+ return null
+
+ const output = existingOutput ?? createAgentOutputConfig(editOutputName, editOutputType ?? 'string')
+ const isExistingOutput = !!existingOutput
+
+ return createPortal(
+ <div
+ className="fixed z-60 w-[400px]"
+ style={{
+ left: position.left,
+ top: position.top,
+ }}
+ >
+ <OutputEditCard
+ key={`${editOutputRequestKey ?? 0}-${output.name}`}
+ editingIndex={isExistingOutput ? outputIndex : undefined}
+ existingOutputs={outputs}
+ state={{
+ ...(isExistingOutput ? { outputIndex } : {}),
+ draft: createDraft(output),
+ }}
+ onCancel={onCancel}
+ onConfirm={(nextOutput) => {
+ const currentAgentTask = agentTask || ''
+ const nextAgentTask = nextOutput.name !== editOutputName && extractAgentOutputNames(currentAgentTask).has(editOutputName)
+ ? replaceAgentOutputName(currentAgentTask, editOutputName, nextOutput.name)
+ : undefined
+
+ onChange(isExistingOutput
+ ? outputs.map((item, index) => index === outputIndex ? nextOutput : item)
+ : [...outputs.filter(output => output.name !== editOutputName), nextOutput], nextAgentTask)
+ onCancel()
+ }}
+ />
+ </div>,
+ document.body,
+ )
+}
+
export function AgentV2Panel({
id,
data,
@@ -35,13 +105,15 @@ export function AgentV2Panel({
const [isRosterAgentPanelOpen, setIsRosterAgentPanelOpen] = useState(false)
const [isInlineAgentPanelOpenedFromTrigger, setIsInlineAgentPanelOpenedFromTrigger] = useState(false)
const [isSaveToRosterDialogOpen, setIsSaveToRosterDialogOpen] = useState(false)
+ const [editingOutputFromTask, setEditingOutputFromTask] = useState<{ name: string, outputType: AgentOutputTypeOptionValue, position: { left: number, top: number }, requestKey: number } | null>(null)
const [saveToRosterSessionKey, setSaveToRosterSessionKey] = useState(0)
const { handleNodeDataUpdate, handleNodeDataUpdateWithSyncDraft } = useNodeDataUpdate()
const openInlineAgentPanelNodeId = useStore(state => state.openInlineAgentPanelNodeId)
const setOpenInlineAgentPanelNodeId = useStore(state => state.setOpenInlineAgentPanelNodeId)
const appId = useStore(state => state.appId)
const drawerPortalContainerRef = useRef<HTMLDivElement>(null)
- const declaredOutputs = getAgentV2DeclaredOutputs(inputs)
+ const [localDeclaredOutputs, setLocalDeclaredOutputs] = useState<DeclaredOutputConfig[] | null>(null)
+ const declaredOutputs = localDeclaredOutputs ?? getAgentV2DeclaredOutputs(inputs)
const rosterAgentId = inputs.agent_binding?.binding_type === 'roster_agent' ? inputs.agent_binding.agent_id : undefined
const inlineAgentId = inputs.agent_binding?.binding_type === 'inline_agent' ? inputs.agent_binding.agent_id : undefined
const isInlineAgentReady = hasValidInlineAgentBinding(inputs)
@@ -93,16 +165,29 @@ export function AgentV2Panel({
const handleTaskChange = useCallback((value: string) => {
const currentPromptOutputNames = extractAgentOutputNames(value)
const removedPromptOutputNames = [...promptOutputNamesRef.current].filter(name => !currentPromptOutputNames.has(name))
+ const addedPromptOutputNames = [...currentPromptOutputNames].filter(name => !promptOutputNamesRef.current.has(name))
const newInputs = produce(inputsRef.current, (draft) => {
draft.agent_task = value
if (removedPromptOutputNames.length) {
- const removedNameSet = new Set(removedPromptOutputNames)
- draft.agent_declared_outputs = getAgentV2DeclaredOutputs(draft)
- .filter(output => !removedNameSet.has(output.name))
+ const currentDeclaredOutputs = getAgentV2DeclaredOutputs(draft)
+ if (removedPromptOutputNames.length === 1 && addedPromptOutputNames.length === 1) {
+ const oldName = removedPromptOutputNames[0]!
+ const nextName = addedPromptOutputNames[0]!
+ draft.agent_declared_outputs = currentDeclaredOutputs.map(output =>
+ output.name === oldName ? { ...output, name: nextName } : output,
+ )
+ }
+ else {
+ const removedNameSet = new Set(removedPromptOutputNames)
+ draft.agent_declared_outputs = currentDeclaredOutputs
+ .filter(output => !removedNameSet.has(output.name))
+ }
}
})
inputsRef.current = newInputs
promptOutputNamesRef.current = currentPromptOutputNames
+ if (removedPromptOutputNames.length)
+ setLocalDeclaredOutputs(newInputs.agent_declared_outputs ?? [])
setInputs(newInputs)
}, [setInputs])
@@ -318,6 +403,22 @@ export function AgentV2Panel({
const handleDeclaredOutputsChange = useCallback((outputs: ReturnType<typeof getAgentV2DeclaredOutputs>, agentTask?: string) => {
const previousOutputs = getAgentV2DeclaredOutputs(inputsRef.current)
let nextAgentTask = agentTask
+ let nextOutputs = outputs
+ if (agentTask !== undefined) {
+ const nextPromptOutputNames = extractAgentOutputNames(agentTask)
+ const removedPromptOutputNames = [...promptOutputNamesRef.current].filter(name => !nextPromptOutputNames.has(name))
+ const addedPromptOutputNames = [...nextPromptOutputNames].filter(name => !promptOutputNamesRef.current.has(name))
+
+ if (removedPromptOutputNames.length === 1 && addedPromptOutputNames.length === 1) {
+ const oldName = removedPromptOutputNames[0]!
+ const nextName = addedPromptOutputNames[0]!
+ const oldOutputIndex = previousOutputs.findIndex(output => output.name === oldName)
+ const nextOutput = outputs.find(output => output.name === nextName)
+ if (oldOutputIndex >= 0 && nextOutput) {
+ nextOutputs = previousOutputs.map((output, index) => index === oldOutputIndex ? nextOutput : output)
+ }
+ }
+ }
if (nextAgentTask === undefined && previousOutputs.length === outputs.length) {
const renamedOutputs = previousOutputs
.map((previousOutput, index) => ({
@@ -335,11 +436,12 @@ export function AgentV2Panel({
}
const newInputs = produce(inputsRef.current, (draft) => {
- draft.agent_declared_outputs = outputs
+ draft.agent_declared_outputs = nextOutputs
if (nextAgentTask !== undefined)
draft.agent_task = nextAgentTask
})
inputsRef.current = newInputs
+ setLocalDeclaredOutputs(nextOutputs)
if (nextAgentTask !== undefined)
promptOutputNamesRef.current = extractAgentOutputNames(nextAgentTask)
handleNodeDataUpdateWithSyncDraft(
@@ -354,8 +456,35 @@ export function AgentV2Panel({
)
}, [handleNodeDataUpdateWithSyncDraft, id])
+ const handleEditTaskOutput = useCallback((name: string, outputType: AgentOutputTypeOptionValue) => {
+ const panelRect = drawerPortalContainerRef.current?.getBoundingClientRect()
+ const editorWidth = 400
+ const gap = 24
+ const position = {
+ left: Math.max(16, (panelRect?.left ?? 0) - editorWidth - gap),
+ top: Math.max(16, (panelRect?.top ?? 0) + 144),
+ }
+
+ setEditingOutputFromTask(current => ({
+ name,
+ outputType,
+ position,
+ requestKey: (current?.requestKey ?? 0) + 1,
+ }))
+ }, [])
+
return (
- <div ref={drawerPortalContainerRef} className="pt-2">
+ <div ref={drawerPortalContainerRef} className="relative pt-2">
+ <FloatingOutputEditor
+ agentTask={inputs.agent_task}
+ editOutputName={editingOutputFromTask?.name}
+ editOutputRequestKey={editingOutputFromTask?.requestKey}
+ editOutputType={editingOutputFromTask?.outputType}
+ outputs={declaredOutputs}
+ position={editingOutputFromTask?.position}
+ onCancel={() => setEditingOutputFromTask(null)}
+ onChange={handleDeclaredOutputsChange}
+ />
<div className="border-b border-divider-subtle">
<AgentRosterField
agent={displayedAgent}
@@ -421,6 +550,7 @@ export function AgentV2Panel({
data={inputs}
outputs={declaredOutputs}
onChange={handleTaskChange}
+ onEditOutput={handleEditTaskOutput}
onOutputsChange={handleDeclaredOutputsChange}
/>
</div>
diff --git a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
index 17acef94a85..17483a2560d 100644
--- a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
+++ b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
@@ -1,12 +1,42 @@
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
-import type { AgentSoulConfigWithFiles } from '../conversions'
+import { createStore } from 'jotai'
import { describe, expect, it } from 'vitest'
import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '../conversions'
import { defaultAgentSoulConfigFormState } from '../form-state'
+import {
+ agentComposerDraftAtom,
+ agentComposerOriginalConfigAtom,
+ agentComposerOriginalDraftAtom,
+ agentComposerPublishedDraftAtom,
+ rebaseAgentComposerDraftAtom,
+} from '../store'
describe('agent composer store conversions', () => {
+ it('rebases draft baselines through the composer state action', () => {
+ const store = createStore()
+ const nextDraft = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Build draft prompt',
+ }
+ const originalConfig = {
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ } satisfies AgentSoulConfig
+
+ store.set(rebaseAgentComposerDraftAtom, {
+ draft: nextDraft,
+ originalConfig,
+ })
+
+ expect(store.get(agentComposerDraftAtom).prompt).toBe('Build draft prompt')
+ expect(store.get(agentComposerOriginalDraftAtom)?.prompt).toBe('Build draft prompt')
+ expect(store.get(agentComposerPublishedDraftAtom)?.prompt).toBe('Build draft prompt')
+ expect(store.get(agentComposerOriginalConfigAtom)?.prompt?.system_prompt).toBe('Build draft prompt')
+ })
+
it('should hydrate editable form state from an AgentSoulConfig and preserve it in the config snapshot', () => {
- const baseConfig: AgentSoulConfigWithFiles = {
+ const baseConfig: AgentSoulConfig = {
app_features: {
opening_statement: 'Hello',
suggested_questions: ['What changed?'],
@@ -53,29 +83,30 @@ describe('agent composer store conversions', () => {
},
],
},
- files: {
- skills: [
- {
- id: 'tender-analyzer',
- name: 'Tender Analyzer',
- description: 'Parses RFPs.',
- path: 'tender-analyzer',
- skill_md_key: 'tender-analyzer/SKILL.md',
- full_archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- },
- ],
- files: [
- {
- id: 'files/sample.pdf',
- file_id: 'drive-file-1',
- name: 'sample.pdf',
- drive_key: 'files/sample.pdf',
- },
- ],
- },
+ config_skills: [
+ {
+ name: 'Tender Analyzer',
+ description: 'Parses RFPs.',
+ file_id: 'tool-file-1',
+ file_kind: 'tool_file',
+ },
+ ],
+ config_files: [
+ {
+ file_id: 'drive-file-1',
+ file_kind: 'upload_file',
+ name: 'sample.pdf',
+ mime_type: 'application/pdf',
+ },
+ ],
+ config_note: 'Read the proposal first.',
model: {
model: 'gpt-4.1',
model_provider: 'openai',
+ model_settings: {
+ temperature: 0.2,
+ max_tokens: 1024,
+ },
plugin_id: 'openai',
},
prompt: {
@@ -126,6 +157,10 @@ describe('agent composer store conversions', () => {
prompt: 'Be precise.',
model: {
model: 'gpt-4.1',
+ model_settings: {
+ temperature: 0.2,
+ max_tokens: 1024,
+ },
provider: 'openai',
plugin_id: 'openai',
},
@@ -152,16 +187,19 @@ describe('agent composer store conversions', () => {
],
skills: [
expect.objectContaining({
+ id: 'Tender Analyzer',
+ description: 'Parses RFPs.',
+ fileId: 'tool-file-1',
name: 'Tender Analyzer',
- skillMdKey: 'tender-analyzer/SKILL.md',
- archiveKey: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
}),
],
files: [
expect.objectContaining({
+ configName: 'sample.pdf',
+ icon: 'pdf',
+ id: 'sample.pdf',
name: 'sample.pdf',
fileId: 'drive-file-1',
- driveKey: 'files/sample.pdf',
}),
],
})
@@ -187,25 +225,32 @@ describe('agent composer store conversions', () => {
})
expect(publishConfig).not.toHaveProperty('skills_files')
- expect(publishConfig.files).toEqual({
- skills: [
- {
- id: 'tender-analyzer',
- name: 'Tender Analyzer',
- description: 'Parses RFPs.',
- path: 'tender-analyzer',
- skill_md_key: 'tender-analyzer/SKILL.md',
- full_archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- },
- ],
- files: [
- {
- id: 'files/sample.pdf',
- file_id: 'drive-file-1',
- name: 'sample.pdf',
- drive_key: 'files/sample.pdf',
- },
- ],
+ expect(publishConfig).not.toHaveProperty('files')
+ expect(publishConfig.config_skills).toEqual([
+ {
+ name: 'Tender Analyzer',
+ description: 'Parses RFPs.',
+ file_id: 'tool-file-1',
+ file_kind: 'tool_file',
+ size: undefined,
+ hash: undefined,
+ mime_type: undefined,
+ },
+ ])
+ expect(publishConfig.config_files).toEqual([
+ {
+ name: 'sample.pdf',
+ file_id: 'drive-file-1',
+ file_kind: 'upload_file',
+ size: undefined,
+ hash: undefined,
+ mime_type: 'application/pdf',
+ },
+ ])
+ expect(publishConfig.config_note).toBe('Read the proposal first.')
+ expect(publishConfig.model?.model_settings).toEqual({
+ temperature: 0.2,
+ max_tokens: 1024,
})
expect(publishConfig.tools?.dify_tools).toEqual([
expect.objectContaining({
diff --git a/web/features/agent-v2/agent-composer/conversions.ts b/web/features/agent-v2/agent-composer/conversions.ts
index 6aa2339730b..9ca67a2a1a4 100644
--- a/web/features/agent-v2/agent-composer/conversions.ts
+++ b/web/features/agent-v2/agent-composer/conversions.ts
@@ -1,4 +1,6 @@
import type {
+ AgentConfigFileRefConfig,
+ AgentConfigSkillRefConfig,
AgentKnowledgeMetadataConditions,
AgentKnowledgeModelConfig,
AgentKnowledgeRetrievalConfig,
@@ -7,6 +9,7 @@ import type {
} from '@dify/contracts/api/console/agent/types.gen'
import type {
AgentCliTool,
+ AgentComposerModel,
AgentFileNode,
AgentKnowledgeRetrievalItem,
AgentProviderTool,
@@ -15,7 +18,6 @@ import type {
AgentTool,
EnvVariable,
} from './form-state'
-import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type {
MetadataFilteringConditions,
MultipleRetrievalConfig,
@@ -24,37 +26,12 @@ import type {
import type { ModelConfig } from '@/app/components/workflow/types'
import { MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import { DATASET_DEFAULT } from '@/config'
+import { getFileIconType } from '@/features/agent-v2/agent-detail/configure/components/orchestrate/files/file-icon'
import { RETRIEVE_TYPE } from '@/types/app'
import { checkKey } from '@/utils/var'
import { defaultAgentSoulConfigFormState } from './form-state'
import { getKnowledgeRetrievalSetName } from './knowledge-validation'
-type AgentSoulFileRefConfig = {
- id?: string | null
- file_id?: string | null
- name?: string | null
- type?: string | null
- drive_key?: string | null
-}
-
-type AgentSoulSkillRefConfig = {
- id?: string | null
- name?: string | null
- description?: string | null
- path?: string | null
- skill_md_key?: string | null
- full_archive_key?: string | null
-}
-
-type AgentSoulFilesConfig = {
- skills?: AgentSoulSkillRefConfig[]
- files?: AgentSoulFileRefConfig[]
-}
-
-export type AgentSoulConfigWithFiles = AgentSoulConfig & {
- files?: AgentSoulFilesConfig
-}
-
type AgentSoulDifyToolConfig = NonNullable<NonNullable<AgentSoulConfig['tools']>['dify_tools']>[number]
type AgentSoulCliToolConfig = NonNullable<NonNullable<AgentSoulConfig['tools']>['cli_tools']>[number]
type AgentSoulToolRuntimeParameterValue = NonNullable<AgentSoulDifyToolConfig['runtime_parameters']>[string]
@@ -424,80 +401,77 @@ const toEnvConfig = (variables: EnvVariable[]): AgentSoulConfig['env'] => ({
})),
})
-const toSkillConfigs = (skills: AgentSkill[]): AgentSoulSkillRefConfig[] => skills.map(skill => ({
- id: skill.path ?? skill.id,
- name: skill.name,
- description: skill.description,
- path: skill.path,
- skill_md_key: skill.skillMdKey,
- full_archive_key: skill.archiveKey,
-}))
-
-const toFileConfigs = (files: AgentFileNode[]): AgentSoulFileRefConfig[] => files.flatMap((file) => {
- if (file.children?.length)
- return toFileConfigs(file.children)
-
- return [{
- id: file.id,
- file_id: file.fileId,
- name: file.name,
- drive_key: file.driveKey,
- }]
-})
-
-const toFilesConfig = (formState: AgentSoulConfigFormState): AgentSoulFilesConfig => ({
- skills: toSkillConfigs(formState.skills),
- files: toFileConfigs(formState.files),
-})
+const toConfigSkillConfigs = (skills: AgentSkill[], baseConfig?: AgentSoulConfig): AgentConfigSkillRefConfig[] => {
+ const existingByName = new Map((baseConfig?.config_skills ?? []).map(skill => [skill.name, skill]))
-const getAgentFileName = (file: AgentSoulFileRefConfig) => {
- if (file.name)
- return file.name
-
- const driveKey = file.drive_key ?? file.id ?? file.file_id ?? ''
- return driveKey.split('/').pop() || driveKey
-}
-
-const toSkillFormState = (config?: AgentSoulConfig): AgentSkill[] => {
- const filesConfig = (config as AgentSoulConfigWithFiles | undefined)?.files
-
- return (filesConfig?.skills ?? []).flatMap((skill) => {
- const id = skill.skill_md_key ?? skill.path ?? skill.id
- const name = skill.name ?? skill.path ?? id
- if (!id || !name)
+ return skills.flatMap((skill) => {
+ const existing = existingByName.get(skill.name)
+ const fileId = skill.fileId ?? existing?.file_id
+ if (!fileId)
return []
return [{
- id,
- name,
- description: skill.description ?? undefined,
- path: skill.path ?? undefined,
- skillMdKey: skill.skill_md_key ?? undefined,
- archiveKey: skill.full_archive_key ?? undefined,
+ name: skill.name,
+ description: skill.description ?? existing?.description ?? '',
+ file_id: fileId,
+ file_kind: existing?.file_kind ?? 'tool_file',
+ size: skill.size ?? existing?.size,
+ hash: skill.hash ?? existing?.hash,
+ mime_type: skill.mimeType ?? existing?.mime_type,
}]
})
}
-const toFileFormState = (config?: AgentSoulConfig): AgentFileNode[] => {
- const filesConfig = (config as AgentSoulConfigWithFiles | undefined)?.files
+const toConfigFileConfigs = (files: AgentFileNode[], baseConfig?: AgentSoulConfig): AgentConfigFileRefConfig[] => {
+ const existingByName = new Map((baseConfig?.config_files ?? []).map(file => [file.name, file]))
- return (filesConfig?.files ?? []).flatMap((file) => {
- const id = file.drive_key ?? file.file_id ?? file.id
- const name = getAgentFileName(file)
- if (!id || !name)
+ return files.flatMap((file) => {
+ if (file.children?.length)
+ return toConfigFileConfigs(file.children, baseConfig)
+
+ const configName = file.configName ?? file.name
+ const existing = existingByName.get(configName)
+ const fileId = file.fileId ?? existing?.file_id
+ if (!fileId)
return []
return [{
- id,
- name,
- icon: 'file' as const,
- fileId: file.file_id ?? undefined,
- driveKey: file.drive_key ?? undefined,
+ name: configName,
+ file_id: fileId,
+ file_kind: existing?.file_kind ?? 'upload_file',
+ size: file.size ?? existing?.size,
+ hash: file.hash ?? existing?.hash,
+ mime_type: file.mimeType ?? existing?.mime_type,
}]
})
}
-const toDraftModel = (config?: AgentSoulConfig): DefaultModel | undefined => {
+const toSkillFormState = (config?: AgentSoulConfig): AgentSkill[] => {
+ return (config?.config_skills ?? []).map(skill => ({
+ id: skill.name,
+ name: skill.name,
+ description: skill.description ?? undefined,
+ fileId: skill.file_id,
+ size: skill.size ?? undefined,
+ hash: skill.hash ?? undefined,
+ mimeType: skill.mime_type ?? undefined,
+ }))
+}
+
+const toFileFormState = (config?: AgentSoulConfig): AgentFileNode[] => {
+ return (config?.config_files ?? []).map(file => ({
+ id: file.name,
+ name: file.name,
+ icon: getFileIconType(file.name, file.mime_type ?? undefined),
+ fileId: file.file_id,
+ configName: file.name,
+ size: file.size ?? undefined,
+ hash: file.hash ?? undefined,
+ mimeType: file.mime_type ?? undefined,
+ }))
+}
+
+const toDraftModel = (config?: AgentSoulConfig): AgentComposerModel | undefined => {
const modelProvider = config?.model?.model_provider
const model = config?.model?.model
@@ -508,10 +482,11 @@ const toDraftModel = (config?: AgentSoulConfig): DefaultModel | undefined => {
provider: modelProvider,
model,
plugin_id: config?.model?.plugin_id,
+ model_settings: config?.model?.model_settings,
}
}
-const getModelProviderPluginId = (model: DefaultModel, baseModel?: AgentSoulConfig['model']) => {
+const getModelProviderPluginId = (model: AgentComposerModel, baseModel?: AgentSoulConfig['model']) => {
if (model.plugin_id)
return model.plugin_id
@@ -533,8 +508,8 @@ export const formStateToAgentSoulConfig = ({
}: {
baseConfig?: AgentSoulConfig
formState: AgentSoulConfigFormState
- currentModel?: DefaultModel
-}): AgentSoulConfigWithFiles => {
+ currentModel?: AgentComposerModel
+}): AgentSoulConfig => {
return {
...baseConfig,
prompt: {
@@ -547,6 +522,7 @@ export const formStateToAgentSoulConfig = ({
model_provider: currentModel.provider,
model: currentModel.model,
plugin_id: getModelProviderPluginId(currentModel, baseConfig?.model),
+ model_settings: currentModel.model_settings,
}
: baseConfig?.model,
tools: {
@@ -557,7 +533,9 @@ export const formStateToAgentSoulConfig = ({
app_features: formState.appFeatures ?? baseConfig?.app_features,
knowledge: toKnowledgeConfig(formState.knowledgeRetrievals),
env: toEnvConfig(formState.envVariables),
- files: toFilesConfig(formState),
+ config_skills: toConfigSkillConfigs(formState.skills, baseConfig),
+ config_files: toConfigFileConfigs(formState.files, baseConfig),
+ config_note: baseConfig?.config_note ?? '',
}
}
diff --git a/web/features/agent-v2/agent-composer/form-state.ts b/web/features/agent-v2/agent-composer/form-state.ts
index 42598a0d214..fc61e968672 100644
--- a/web/features/agent-v2/agent-composer/form-state.ts
+++ b/web/features/agent-v2/agent-composer/form-state.ts
@@ -1,4 +1,4 @@
-import type { AgentKnowledgeDatasetConfig, AgentSoulAppFeaturesConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentKnowledgeDatasetConfig, AgentSoulAppFeaturesConfig, AgentSoulModelConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'
@@ -15,6 +15,10 @@ import type { I18nKeysWithPrefix } from '@/types/i18n'
export type EnvScope = 'secret' | 'plain'
+export type AgentComposerModel = DefaultModel & {
+ model_settings?: AgentSoulModelConfig['model_settings']
+}
+
export type EnvVariable = {
id: string
key: string
@@ -25,20 +29,27 @@ export type EnvVariable = {
export type AgentSkill = {
description?: string
- archiveKey?: string
+ fileId?: string
+ hash?: string
id: string
+ mimeType?: string
name: string
- path?: string
+ size?: number
skillMdKey?: string
}
export type AgentFileNode = {
+ driveKey?: string
+ hash?: string
id: string
- name: string
icon: FileTreeIconType
fileId?: string
- driveKey?: string
+ configName?: string
children?: AgentFileNode[]
+ virtualContent?: string
+ mimeType?: string
+ name: string
+ size?: number
}
export type AgentKnowledgeRetrievalItem = {
@@ -98,7 +109,7 @@ export type AgentTool = AgentProviderTool | AgentCliTool
export type AgentSoulConfigFormState = {
prompt: string
- model?: DefaultModel
+ model?: AgentComposerModel
appFeatures?: AgentSoulAppFeaturesConfig
skills: AgentSkill[]
files: AgentFileNode[]
diff --git a/web/features/agent-v2/agent-composer/provider.tsx b/web/features/agent-v2/agent-composer/provider.tsx
index e5c5fdec5f7..66b6d9aa305 100644
--- a/web/features/agent-v2/agent-composer/provider.tsx
+++ b/web/features/agent-v2/agent-composer/provider.tsx
@@ -3,8 +3,8 @@
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { ReactNode } from 'react'
import type { AgentSoulConfigFormState } from './form-state'
-import { createStore, Provider as JotaiProvider } from 'jotai'
-import { useRef } from 'react'
+import { ScopeProvider } from 'jotai-scope'
+import { defaultAgentSoulConfigFormState } from './form-state'
import {
agentComposerDraftAtom,
agentComposerOriginalConfigAtom,
@@ -12,27 +12,6 @@ import {
agentComposerPublishedDraftAtom,
} from './store'
-function createAgentComposerStore({
- initialDraft,
- initialOriginalConfig,
-}: {
- initialDraft?: AgentSoulConfigFormState
- initialOriginalConfig?: AgentSoulConfig
-}) {
- const store = createStore()
-
- if (initialOriginalConfig)
- store.set(agentComposerOriginalConfigAtom, initialOriginalConfig)
- if (initialDraft)
- store.set(agentComposerDraftAtom, initialDraft)
- if (initialDraft)
- store.set(agentComposerOriginalDraftAtom, initialDraft)
- if (initialDraft)
- store.set(agentComposerPublishedDraftAtom, initialDraft)
-
- return store
-}
-
export function AgentComposerProvider({
children,
initialDraft,
@@ -42,18 +21,19 @@ export function AgentComposerProvider({
initialDraft?: AgentSoulConfigFormState
initialOriginalConfig?: AgentSoulConfig
}) {
- const storeRef = useRef<ReturnType<typeof createAgentComposerStore> | null>(null)
- if (!storeRef.current) {
- storeRef.current = createAgentComposerStore({
- initialDraft,
- initialOriginalConfig,
- })
- }
- const store = storeRef.current
+ const draft = initialDraft ?? defaultAgentSoulConfigFormState
return (
- <JotaiProvider store={store}>
+ <ScopeProvider
+ atoms={[
+ [agentComposerOriginalConfigAtom, initialOriginalConfig],
+ [agentComposerDraftAtom, draft],
+ [agentComposerOriginalDraftAtom, draft],
+ [agentComposerPublishedDraftAtom, draft],
+ ]}
+ name="AgentComposer"
+ >
{children}
- </JotaiProvider>
+ </ScopeProvider>
)
}
diff --git a/web/features/agent-v2/agent-composer/store-modules/model.ts b/web/features/agent-v2/agent-composer/store-modules/model.ts
index c44359633a6..28d8d8c59c4 100644
--- a/web/features/agent-v2/agent-composer/store-modules/model.ts
+++ b/web/features/agent-v2/agent-composer/store-modules/model.ts
@@ -1,12 +1,12 @@
+import type { AgentComposerModel } from '../form-state'
import type { DraftFieldUpdate } from './utils'
-import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { atom } from 'jotai'
import { agentComposerDraftAtom } from '../store'
import { resolveDraftFieldUpdate } from './utils'
export const agentComposerModelAtom = atom(
get => get(agentComposerDraftAtom).model,
- (get, set, modelUpdate: DraftFieldUpdate<DefaultModel | undefined>) => {
+ (get, set, modelUpdate: DraftFieldUpdate<AgentComposerModel | undefined>) => {
const draft = get(agentComposerDraftAtom)
set(agentComposerDraftAtom, {
diff --git a/web/features/agent-v2/agent-composer/store.ts b/web/features/agent-v2/agent-composer/store.ts
index 66389542e3a..c83283b0429 100644
--- a/web/features/agent-v2/agent-composer/store.ts
+++ b/web/features/agent-v2/agent-composer/store.ts
@@ -9,6 +9,19 @@ export const agentComposerOriginalDraftAtom = atom<AgentSoulConfigFormState | un
export const agentComposerPublishedDraftAtom = atom<AgentSoulConfigFormState | undefined>(defaultAgentSoulConfigFormState)
export const agentComposerDraftAtom = atom<AgentSoulConfigFormState>(defaultAgentSoulConfigFormState)
+export const rebaseAgentComposerDraftAtom = atom(null, (_get, set, {
+ draft,
+ originalConfig,
+}: {
+ draft: AgentSoulConfigFormState
+ originalConfig?: AgentSoulConfig
+}) => {
+ set(agentComposerOriginalConfigAtom, originalConfig)
+ set(agentComposerDraftAtom, draft)
+ set(agentComposerOriginalDraftAtom, draft)
+ set(agentComposerPublishedDraftAtom, draft)
+})
+
export const isAgentComposerDirtyAtom = atom((get) => {
const originalDraft = get(agentComposerOriginalDraftAtom)
const draft = get(agentComposerDraftAtom)
diff --git a/web/features/agent-v2/agent-detail/configure/README.md b/web/features/agent-v2/agent-detail/configure/README.md
new file mode 100644
index 00000000000..1027c44ab76
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/README.md
@@ -0,0 +1,56 @@
+# Agent Configure
+
+Owns the Agent V2 configure runtime used by the Agent App configure page and workflow inline Agent configure surface, including editable composer draft wiring, build chat sessions, version viewing, build draft mode, and preview side panels.
+
+## Internal Modules
+
+- agent-composer
+- agent-detail/configure/state
+- agent-detail/configure/use-agent-build-draft-run
+- agent-detail/configure/use-agent-configure-build-draft
+- agent-detail/configure/use-agent-configure-sync
+- agent-detail/configure/components/orchestrate
+- agent-detail/configure/components/preview
+- agent-detail/configure/components/workspace
+- agent-detail/configure/model-compatibility
+
+## External Modules
+
+- app/components/base/chat
+- app/components/base/action-button
+- app/components/base/app-icon
+- app/components/base/features
+- app/components/base/file-uploader
+- app/components/base/infotip
+- app/components/base/loading
+- app/components/base/prompt-editor
+- app/components/base/skeleton
+- app/components/app/configuration/config/agent/agent-tools
+- app/components/datasets
+- app/components/header/account-setting/model-provider-page
+- app/components/plugins
+- app/components/tools
+- app/components/workflow/block-icon
+- app/components/workflow/block-selector
+- app/components/workflow/hooks/use-serial-async-callback
+- app/components/workflow/nodes
+- app/components/workflow/types
+- config
+- context/app-context
+- context/i18n
+- context/modal-context
+- contract/router
+- hooks/use-format-time-from-now
+- hooks/use-theme
+- hooks/use-timestamp
+- models/datasets
+- models/debug
+- models/log
+- service/base
+- service/use-common
+- types/app
+- types/common
+- types/i18n
+- types/workflow
+- utils/format
+- utils/var
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/model-compatibility.spec.ts b/web/features/agent-v2/agent-detail/configure/__tests__/model-compatibility.spec.ts
new file mode 100644
index 00000000000..4a8bbd0f5b5
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/model-compatibility.spec.ts
@@ -0,0 +1,71 @@
+import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import {
+ ConfigurationMethodEnum,
+ ModelStatusEnum,
+ ModelTypeEnum,
+} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { isAgentCompatibleModel } from '../model-compatibility'
+
+const createModel = (provider: string): Model => ({
+ provider,
+ icon_small: { en_US: '', zh_Hans: '' },
+ label: { en_US: provider, zh_Hans: provider },
+ models: [],
+ status: ModelStatusEnum.active,
+})
+
+const createModelItem = (model: string, overrides: Partial<ModelItem> = {}): ModelItem => ({
+ model,
+ label: { en_US: model, zh_Hans: model },
+ model_type: ModelTypeEnum.textGeneration,
+ fetch_from: ConfigurationMethodEnum.predefinedModel,
+ status: ModelStatusEnum.active,
+ model_properties: {},
+ load_balancing_enabled: false,
+ ...overrides,
+})
+
+describe('isAgentCompatibleModel', () => {
+ it('should reject configured OpenAI models below the Agent-compatible baseline', () => {
+ const provider = createModel('langgenius/openai/openai')
+
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4o-mini'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4.1-mini'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4.1-nano'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4-turbo'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-4-vision-preview'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('gpt-3.5-turbo-16k'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('o3-mini'))).toBe(false)
+ expect(isAgentCompatibleModel(provider, createModelItem('o4-mini'))).toBe(false)
+ })
+
+ it('should allow newer OpenAI models and other providers', () => {
+ expect(isAgentCompatibleModel(createModel('openai'), createModelItem('gpt-4o'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('openai'), createModelItem('gpt-4.1'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('anthropic'), createModelItem('other-model'))).toBe(true)
+ })
+
+ it('should reject specifically configured models that do not meet the Agent baseline', () => {
+ expect(isAgentCompatibleModel(createModel('anthropic'), createModelItem('claude-3-haiku-20240307'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('anthropic'), createModelItem('claude-3.5-sonnet-20241022'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('langgenius/gemini/google'), createModelItem('gemini-2.5-flash-lite'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('langgenius/gemini/google'), createModelItem('gemini-1.5-flash-8b'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('deepseek'), createModelItem('deepseek-r1-distill-qwen-32b'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('minimax'), createModelItem('minimax-text-01'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('minimax'), createModelItem('minimax-m1'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('tongyi'), createModelItem('qwen2.5-72b-instruct'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('tongyi'), createModelItem('qwen2.5-coder-32b-instruct'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('tongyi'), createModelItem('qwen3-30b'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('langgenius/zhipuai/zhipuai'), createModelItem('glm-4-airx'))).toBe(false)
+ expect(isAgentCompatibleModel(createModel('langgenius/zhipuai/zhipuai'), createModelItem('glm-z1-flash'))).toBe(false)
+ })
+
+ it('should allow unconfigured models from the same providers', () => {
+ expect(isAgentCompatibleModel(createModel('anthropic'), createModelItem('claude-sonnet-4'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('langgenius/gemini/google'), createModelItem('gemini-2.5-pro'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('deepseek'), createModelItem('deepseek-coder'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('tongyi'), createModelItem('qwen3-coder-plus'))).toBe(true)
+ expect(isAgentCompatibleModel(createModel('langgenius/zhipuai/zhipuai'), createModelItem('glm-4.7'))).toBe(true)
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
index 09b9be74b9a..099a4ae4ee9 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AgentConfigurePage } from '../page'
@@ -8,11 +8,14 @@ const mocks = vi.hoisted(() => ({
applyBuildDraft: vi.fn(),
checkoutBuildDraft: vi.fn(),
discardBuildDraft: vi.fn(),
+ finalizeBuildChat: vi.fn(),
refreshDebugConversation: vi.fn(),
queryState: {
agent: {
data: {
+ debug_conversation_has_messages: true,
debug_conversation_id: 'debug-conversation-old',
+ debug_conversation_message_count: 1,
icon: 'agent',
icon_background: '#E0F2FE',
icon_type: 'emoji',
@@ -51,6 +54,25 @@ const mocks = vi.hoisted(() => ({
},
}))
+function createDeferredPromise<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((promiseResolve) => {
+ resolve = promiseResolve
+ })
+
+ return { promise, resolve }
+}
+
+function expectFirstMockCallBefore(first: ReturnType<typeof vi.fn>, second: ReturnType<typeof vi.fn>) {
+ const firstCallOrder = first.mock.invocationCallOrder[0]
+ const secondCallOrder = second.mock.invocationCallOrder[0]
+
+ if (firstCallOrder === undefined || secondCallOrder === undefined)
+ throw new Error('Expected both mocks to be called before comparing invocation order.')
+
+ expect(firstCallOrder).toBeLessThan(secondCallOrder)
+}
+
vi.mock('@tanstack/react-query', async (importOriginal) => {
const actual = await importOriginal<typeof import('@tanstack/react-query')>()
@@ -82,6 +104,9 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {
vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
+ get: {
+ key: () => ['agents'],
+ },
byAgentId: {
get: {
queryOptions: () => ({ queryKey: ['agent'] }),
@@ -90,13 +115,26 @@ vi.mock('@/service/client', () => ({
debugConversation: {
refresh: {
post: {
- mutationOptions: (options?: { onSuccess?: (data: { debug_conversation_id: string }) => void }) => ({
+ mutationOptions: (options?: {
+ onSuccess?: (data: {
+ debug_conversation_has_messages?: boolean
+ debug_conversation_id: string
+ debug_conversation_message_count?: number
+ }) => void
+ }) => ({
mutationFn: mocks.refreshDebugConversation,
...options,
}),
},
},
},
+ buildChat: {
+ finalize: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.finalizeBuildChat }),
+ },
+ },
+ },
publish: {
post: {
mutationOptions: () => ({ mutationFn: vi.fn() }),
@@ -113,7 +151,11 @@ vi.mock('@/service/client', () => ({
},
buildDraft: {
get: {
- queryOptions: () => ({ queryKey: ['build-draft'] }),
+ queryOptions: (options?: object) => ({
+ ...options,
+ queryFn: vi.fn(),
+ queryKey: ['build-draft'],
+ }),
},
checkout: {
post: {
@@ -129,6 +171,13 @@ vi.mock('@/service/client', () => ({
mutationOptions: () => ({ mutationFn: mocks.discardBuildDraft }),
},
},
+ sandbox: {
+ files: {
+ get: {
+ key: () => ['sandbox-files'],
+ },
+ },
+ },
versions: {
byVersionId: {
get: {
@@ -144,23 +193,6 @@ vi.mock('@/service/client', () => ({
},
}))
-vi.mock('../build-draft-query', () => ({
- agentConfigureConsoleQuery: {
- agent: {
- byAgentId: {
- buildDraft: {
- get: {
- queryOptions: () => ({
- queryFn: vi.fn(),
- queryKey: ['build-draft'],
- }),
- },
- },
- },
- },
- },
-}))
-
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useDefaultModel: () => ({ data: undefined }),
useTextGenerationCurrentProviderAndModelAndModelList: () => ({
@@ -199,43 +231,58 @@ vi.mock('../components/orchestrate', async () => {
vi.mock('../components/orchestrate/build-draft-bar', () => ({
AgentBuildDraftBar: (props: {
changesCount: number
+ disabled?: boolean
onApply: () => void
onDiscard: () => void
}) => (
<div role="region" aria-label="build-draft-bar">
<span>{`changes:${props.changesCount}`}</span>
- <button type="button" onClick={props.onApply}>apply build draft</button>
- <button type="button" onClick={props.onDiscard}>discard build draft</button>
+ <button type="button" disabled={props.disabled} onClick={props.onApply}>apply build draft</button>
+ <button type="button" disabled={props.disabled} onClick={props.onDiscard}>discard build draft</button>
</div>
),
}))
-vi.mock('../components/preview/build-chat', () => ({
- AgentBuildChat: (props: {
- conversationId?: string | null
- onConversationComplete?: () => void
- onConversationIdChange?: (conversationId: string) => void
- onSaveDraftBeforeRun?: () => Promise<void>
- }) => (
- <div role="region" aria-label="build-chat">
- <span>{`build:${props.conversationId ?? 'none'}`}</span>
- <button type="button" onClick={() => props.onConversationIdChange?.('build-conversation-new')}>
- save build conversation
- </button>
- <button
- type="button"
- onClick={() => {
- void props.onSaveDraftBeforeRun?.()
- }}
- >
- send build message
- </button>
- <button type="button" onClick={() => props.onConversationComplete?.()}>
- complete build conversation
- </button>
- </div>
- ),
-}))
+vi.mock('../components/preview/build-chat', async () => {
+ const { useState } = await import('react')
+
+ return {
+ AgentBuildChat: (props: {
+ clearChatList?: boolean
+ conversationId?: string | null
+ onConversationComplete?: (conversationId: string) => void
+ onConversationIdChange?: (conversationId: string) => void
+ onSaveDraftBeforeRun?: () => Promise<void>
+ }) => {
+ const [messageSent, setMessageSent] = useState(false)
+
+ return (
+ <div role="region" aria-label="build-chat">
+ <span>{`build:${props.conversationId ?? 'none'}`}</span>
+ <span>{`clear:${props.clearChatList ? 'yes' : 'no'}`}</span>
+ <span>{`sent:${messageSent ? 'yes' : 'no'}`}</span>
+ <button type="button" onClick={() => props.onConversationIdChange?.('build-conversation-new')}>
+ save build conversation
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void props.onSaveDraftBeforeRun?.().then(() => {
+ setMessageSent(true)
+ props.onConversationIdChange?.('build-conversation-new')
+ })
+ }}
+ >
+ send build message
+ </button>
+ <button type="button" onClick={() => props.onConversationComplete?.('build-conversation-new')}>
+ complete build conversation
+ </button>
+ </div>
+ )
+ },
+ }
+})
vi.mock('../components/preview/preview-chat', () => ({
AgentPreviewChat: (props: {
@@ -252,7 +299,20 @@ vi.mock('../components/preview/preview-chat', () => ({
}))
vi.mock('../components/preview/chat-features-panel', () => ({
- AgentChatFeaturesPanel: () => null,
+ AgentChatFeaturesPanel: (props: {
+ appFeatures?: {
+ opening_statement?: string
+ }
+ disabled?: boolean
+ show: boolean
+ }) => props.show
+ ? (
+ <div role="region" aria-label="chat-features-panel">
+ <span>{`chatFeaturesDisabled:${props.disabled ? 'yes' : 'no'}`}</span>
+ <span>{`opening:${props.appFeatures?.opening_statement ?? ''}`}</span>
+ </div>
+ )
+ : null,
}))
vi.mock('../components/preview/header', () => ({
@@ -260,8 +320,10 @@ vi.mock('../components/preview/header', () => ({
mode: 'build' | 'preview'
previewEnabled: boolean
onModeChange: (mode: 'build' | 'preview') => void
+ onToggleChatFeatures: () => void
onOpenWorkingDirectory: () => void
onRefresh: () => void
+ refreshDisabled?: boolean
}) => (
<div>
<div>{props.mode}</div>
@@ -271,10 +333,13 @@ vi.mock('../components/preview/header', () => ({
<button type="button" onClick={() => props.onModeChange('build')}>
build mode
</button>
+ <button type="button" onClick={props.onToggleChatFeatures}>
+ chat features
+ </button>
<button type="button" onClick={props.onOpenWorkingDirectory}>
open working directory
</button>
- <button type="button" onClick={props.onRefresh}>
+ <button type="button" disabled={props.refreshDisabled} onClick={props.onRefresh}>
restart preview
</button>
</div>
@@ -291,8 +356,11 @@ describe('AgentConfigurePage', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.refreshDebugConversation.mockResolvedValue({
+ debug_conversation_has_messages: false,
debug_conversation_id: 'debug-conversation-new',
+ debug_conversation_message_count: 0,
})
+ mocks.finalizeBuildChat.mockResolvedValue({ result: 'success' })
mocks.applyBuildDraft.mockResolvedValue({ result: 'success', draft: {} })
mocks.checkoutBuildDraft.mockResolvedValue({
variant: 'agent_app',
@@ -302,11 +370,13 @@ describe('AgentConfigurePage', () => {
mocks.discardBuildDraft.mockResolvedValue({ result: 'success' })
mocks.queryState.agent = {
data: {
+ debug_conversation_has_messages: true,
+ debug_conversation_id: 'debug-conversation-old',
+ debug_conversation_message_count: 1,
icon: 'agent',
icon_background: '#E0F2FE',
icon_type: 'emoji',
name: 'Research Agent',
- debug_conversation_id: 'debug-conversation-old',
},
isFetching: false,
isError: false,
@@ -395,9 +465,6 @@ describe('AgentConfigurePage', () => {
params: {
agent_id: 'agent-1',
},
- body: {
- debug_conversation_id: 'build-conversation-new',
- },
}, expect.any(Object))
expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
@@ -411,6 +478,74 @@ describe('AgentConfigurePage', () => {
expect(screen.queryByRole('region', { name: 'preview-chat' })).not.toBeInTheDocument()
})
+ it('should not keep a stale clear command after the composer content remounts', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ const view = render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:debug-conversation-old')
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('clear:no')
+
+ await user.click(screen.getByRole('button', { name: 'restart preview' }))
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('clear:yes')
+
+ mocks.queryState.agent = {
+ ...mocks.queryState.agent,
+ data: {
+ ...mocks.queryState.agent.data,
+ debug_conversation_has_messages: true,
+ debug_conversation_id: 'debug-conversation-new',
+ debug_conversation_message_count: 1,
+ },
+ }
+ mocks.queryState.composer = {
+ data: undefined,
+ isFetching: true,
+ isError: false,
+ isPending: true,
+ isSuccess: false,
+ refetch: vi.fn(),
+ }
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+ expect(screen.queryByRole('region', { name: 'build-chat' })).not.toBeInTheDocument()
+
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:debug-conversation-new')
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('clear:no')
+ })
+
it('should keep preview disabled', async () => {
const user = userEvent.setup()
const queryClient = new QueryClient()
@@ -438,6 +573,42 @@ describe('AgentConfigurePage', () => {
expect(screen.queryByRole('region', { name: 'preview-chat', hidden: true })).not.toBeInTheDocument()
})
+ it('should disable restart when the debug conversation has no messages', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.agent = {
+ ...mocks.queryState.agent,
+ data: {
+ ...mocks.queryState.agent.data,
+ debug_conversation_has_messages: false,
+ debug_conversation_id: 'debug-conversation-empty',
+ debug_conversation_message_count: 0,
+ },
+ }
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ const restartButton = screen.getByRole('button', { name: 'restart preview' })
+
+ expect(restartButton).toBeDisabled()
+
+ await user.click(restartButton)
+
+ expect(mocks.refreshDebugConversation).not.toHaveBeenCalled()
+ })
+
it('should stay in normal draft mode when build draft returns 404 even if a debug conversation exists', () => {
const queryClient = new QueryClient()
mocks.queryState.composer = {
@@ -477,6 +648,43 @@ describe('AgentConfigurePage', () => {
expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
})
+ it('should keep build draft query refresh owned by explicit workflow actions', () => {
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ let buildDraftQueryOptions: unknown
+ for (const [options] of vi.mocked(useQuery).mock.calls) {
+ if (Array.isArray(options.queryKey) && options.queryKey[0] === 'build-draft') {
+ buildDraftQueryOptions = options
+ break
+ }
+ }
+
+ expect(buildDraftQueryOptions).toMatchObject({
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
+ })
+ })
+
it('should enter build draft mode when build draft data exists', () => {
const queryClient = new QueryClient()
mocks.queryState.composer = {
@@ -524,10 +732,8 @@ describe('AgentConfigurePage', () => {
expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
})
- it('should show the build draft bar after a new build conversation refresh completes', async () => {
- vi.useFakeTimers()
+ it('should not checkout again when sending build chat from active build draft mode', async () => {
const queryClient = new QueryClient()
- const refetchBuildDraft = vi.fn().mockResolvedValue({})
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -558,7 +764,7 @@ describe('AgentConfigurePage', () => {
isError: false,
isPending: false,
isSuccess: true,
- refetch: refetchBuildDraft,
+ refetch: vi.fn(),
}
render(
@@ -567,29 +773,30 @@ describe('AgentConfigurePage', () => {
</QueryClientProvider>,
)
- expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:yes')
fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
- expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
-
- fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
-
- expect(refetchBuildDraft).not.toHaveBeenCalled()
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(1000)
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes')
})
-
- expect(refetchBuildDraft).toHaveBeenCalled()
- expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(mocks.checkoutBuildDraft).not.toHaveBeenCalled()
})
- it('should discard the build draft when restarting build mode with a build draft', async () => {
+ it('should show chat features from the active build draft source as read-only', async () => {
const user = userEvent.setup()
const queryClient = new QueryClient()
mocks.queryState.composer = {
- data: {},
+ data: {
+ agent_soul: {
+ app_features: {
+ opening_statement: 'draft opening',
+ },
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
isFetching: false,
isError: false,
isPending: false,
@@ -598,7 +805,14 @@ describe('AgentConfigurePage', () => {
}
mocks.queryState.buildDraft = {
data: {
- agent_soul: {},
+ agent_soul: {
+ app_features: {
+ opening_statement: 'build opening',
+ },
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
draft: {},
variant: 'agent_app',
},
@@ -617,29 +831,13 @@ describe('AgentConfigurePage', () => {
</QueryClientProvider>,
)
- await user.click(screen.getByRole('button', { name: 'restart preview' }))
+ await user.click(screen.getByRole('button', { name: 'chat features' }))
- await waitFor(() => expect(mocks.discardBuildDraft).toHaveBeenCalledWith(
- {
- params: {
- agent_id: 'agent-1',
- },
- },
- expect.any(Object),
- ))
- expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
- params: {
- agent_id: 'agent-1',
- },
- body: {
- debug_conversation_id: 'debug-conversation-old',
- },
- }, expect.any(Object))
- expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ expect(screen.getByRole('region', { name: 'chat-features-panel' })).toHaveTextContent('chatFeaturesDisabled:yes')
+ expect(screen.getByRole('region', { name: 'chat-features-panel' })).toHaveTextContent('opening:build opening')
})
- it('should switch soul source to view version when selecting a version from build draft mode', async () => {
- const user = userEvent.setup()
+ it('should switch to build draft mode without resetting the sending chat when sending from normal draft mode', async () => {
const queryClient = new QueryClient()
mocks.queryState.composer = {
data: {
@@ -656,21 +854,13 @@ describe('AgentConfigurePage', () => {
refetch: vi.fn(),
}
mocks.queryState.buildDraft = {
- data: {
- agent_soul: {
- prompt: {
- system_prompt: 'build prompt',
- },
- },
- draft: {},
- variant: 'agent_app',
- },
- dataUpdatedAt: 1,
- error: null,
+ data: undefined as unknown,
+ dataUpdatedAt: 0,
+ error: new Response(null, { status: 404 }),
isFetching: false,
- isError: false,
+ isError: true,
isPending: false,
- isSuccess: true,
+ isSuccess: false,
refetch: vi.fn(),
}
@@ -680,19 +870,502 @@ describe('AgentConfigurePage', () => {
</QueryClientProvider>,
)
- expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
- await user.click(screen.getByRole('button', { name: 'open versions' }))
- await user.click(screen.getByRole('button', { name: 'select version' }))
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await waitFor(() => {
+ expect(mocks.checkoutBuildDraft).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ force: false,
+ },
+ }, expect.any(Object))
+ })
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes')
+ })
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:build-conversation-new')
expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:yes')
- expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('publish:yes')
- expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:yes')
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
})
- it('should apply the build draft and rebase the composer store from the refetched normal draft', async () => {
- const user = userEvent.setup()
+ it('should keep the build draft bar disabled while a build conversation is responding', async () => {
+ vi.useFakeTimers()
const queryClient = new QueryClient()
+ const refetchBuildDraft = vi.fn().mockResolvedValue({})
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchBuildDraft,
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('sent:yes')
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+
+ expect(refetchBuildDraft).not.toHaveBeenCalled()
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(refetchBuildDraft).toHaveBeenCalled()
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeEnabled()
+ })
+
+ it('should not keep a stale build draft action lock after the composer content remounts', async () => {
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ const view = render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+
+ mocks.queryState.composer = {
+ data: undefined,
+ isFetching: true,
+ isError: false,
+ isPending: true,
+ isSuccess: false,
+ refetch: vi.fn(),
+ }
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+ expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeEnabled()
+ })
+
+ it('should settle build draft actions when the build completion refresh fails', async () => {
+ vi.useFakeTimers()
+ const queryClient = new QueryClient()
+ const refetchBuildDraft = vi.fn().mockRejectedValue(new Error('refresh failed'))
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchBuildDraft,
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(refetchBuildDraft).toHaveBeenCalledTimes(1)
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeEnabled()
+ })
+
+ it('should not let a previous build completion refresh unlock a new build run', async () => {
+ vi.useFakeTimers()
+ const queryClient = new QueryClient()
+ const refetchBuildDraft = vi.fn().mockResolvedValue({})
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchBuildDraft,
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(refetchBuildDraft).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
+ })
+
+ it('should ignore a previous build completion refresh that is already in flight', async () => {
+ vi.useFakeTimers()
+ const queryClient = new QueryClient()
+ const refetchBuildDraft = vi.fn()
+ const staleRefresh = createDeferredPromise<unknown>()
+ refetchBuildDraft.mockReturnValueOnce(staleRefresh.promise)
+ mocks.checkoutBuildDraft.mockResolvedValue({
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchBuildDraft,
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+ expect(refetchBuildDraft).toHaveBeenCalledTimes(1)
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+ await act(async () => {
+ await Promise.resolve()
+ })
+ await act(async () => {
+ staleRefresh.resolve({
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'stale refreshed prompt',
+ },
+ },
+ },
+ })
+ await staleRefresh.promise
+ })
+
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('prompt:build prompt')
+ expect(screen.getByRole('button', { name: 'apply build draft' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'discard build draft' })).toBeDisabled()
+ })
+
+ it('should discard the build draft when restarting build mode with a build draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'restart preview' }))
+
+ await waitFor(() => expect(mocks.discardBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should switch soul source to view version when selecting a version from build draft mode', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'open versions' }))
+ await user.click(screen.getByRole('button', { name: 'select version' }))
+
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:yes')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('publish:yes')
+ expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+ })
+
+ it('should apply the build draft and rebase the composer store from the refetched normal draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
const refetchComposer = vi.fn(async () => {
mocks.queryState.composer = {
...mocks.queryState.composer,
@@ -748,6 +1421,14 @@ describe('AgentConfigurePage', () => {
await user.click(screen.getByRole('button', { name: 'apply build draft' }))
+ await waitFor(() => expect(mocks.finalizeBuildChat).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
await waitFor(() => expect(mocks.applyBuildDraft).toHaveBeenCalledWith(
{
params: {
@@ -756,13 +1437,17 @@ describe('AgentConfigurePage', () => {
},
expect.any(Object),
))
+ expectFirstMockCallBefore(mocks.finalizeBuildChat, mocks.applyBuildDraft)
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ['agent'],
+ })
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ['agents'],
+ })
expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
params: {
agent_id: 'agent-1',
},
- body: {
- debug_conversation_id: 'debug-conversation-old',
- },
}, expect.any(Object))
expect(refetchComposer).toHaveBeenCalled()
expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
@@ -830,6 +1515,14 @@ describe('AgentConfigurePage', () => {
await user.click(screen.getByRole('button', { name: 'apply build draft' }))
+ await waitFor(() => expect(mocks.finalizeBuildChat).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
await waitFor(() => expect(mocks.applyBuildDraft).toHaveBeenCalledWith(
{
params: {
@@ -838,13 +1531,11 @@ describe('AgentConfigurePage', () => {
},
expect.any(Object),
))
+ expectFirstMockCallBefore(mocks.finalizeBuildChat, mocks.applyBuildDraft)
expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
params: {
agent_id: 'agent-1',
},
- body: {
- debug_conversation_id: 'debug-conversation-old',
- },
}, expect.any(Object))
expect(refetchComposer).toHaveBeenCalled()
expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
@@ -900,9 +1591,6 @@ describe('AgentConfigurePage', () => {
params: {
agent_id: 'agent-1',
},
- body: {
- debug_conversation_id: 'debug-conversation-old',
- },
}, expect.any(Object))
expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
})
@@ -954,9 +1642,6 @@ describe('AgentConfigurePage', () => {
params: {
agent_id: 'agent-1',
},
- body: {
- debug_conversation_id: 'debug-conversation-old',
- },
}, expect.any(Object))
expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
await waitFor(() => {
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/state.spec.ts b/web/features/agent-v2/agent-detail/configure/__tests__/state.spec.ts
new file mode 100644
index 00000000000..ac1d31e0b8f
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/state.spec.ts
@@ -0,0 +1,83 @@
+import { createStore } from 'jotai'
+import { describe, expect, it } from 'vitest'
+import {
+ agentConfigureComposerRebaseRevisionAtom,
+ agentConfigureConversationIdsAtom,
+ agentConfigureRightPanelChatModeAtom,
+ agentConfigureRightPanelModeAtom,
+ agentConfigureSelectedVersionIdAtom,
+ agentConfigureSelectVersionAtom,
+ agentConfigureShowPreviewVersionsAtom,
+ agentConfigureSoulSourceOverrideAtom,
+ rebaseAgentConfigureComposerAtom,
+ resetAgentConfigureConversationAtom,
+ setAgentConfigureConversationIdAtom,
+} from '../state'
+
+describe('agent configure state graph', () => {
+ it('selects versions through the shared source override entrypoint', () => {
+ const store = createStore()
+
+ store.set(agentConfigureSelectVersionAtom, 'snapshot-1')
+
+ expect(store.get(agentConfigureSelectedVersionIdAtom)).toBe('snapshot-1')
+ expect(store.get(agentConfigureSoulSourceOverrideAtom)).toBe('view-version')
+
+ store.set(agentConfigureSelectVersionAtom, null)
+
+ expect(store.get(agentConfigureSelectedVersionIdAtom)).toBeNull()
+ expect(store.get(agentConfigureSoulSourceOverrideAtom)).toBeNull()
+ })
+
+ it('derives the actual chat mode from the visible right panel mode', () => {
+ const store = createStore()
+
+ expect(store.get(agentConfigureRightPanelChatModeAtom)).toBe('build')
+
+ store.set(agentConfigureRightPanelModeAtom, 'preview')
+
+ expect(store.get(agentConfigureRightPanelChatModeAtom)).toBe('build')
+ })
+
+ it('updates and resets conversation state through named actions', () => {
+ const store = createStore()
+
+ store.set(setAgentConfigureConversationIdAtom, {
+ mode: 'build',
+ conversationId: 'build-conversation-1',
+ })
+ store.set(setAgentConfigureConversationIdAtom, {
+ mode: 'preview',
+ conversationId: 'preview-conversation-1',
+ })
+
+ expect(store.get(agentConfigureConversationIdsAtom)).toEqual({
+ build: 'build-conversation-1',
+ preview: 'preview-conversation-1',
+ })
+
+ store.set(resetAgentConfigureConversationAtom, 'build')
+
+ expect(store.get(agentConfigureConversationIdsAtom)).toEqual({
+ build: null,
+ preview: 'preview-conversation-1',
+ })
+ })
+
+ it('tracks composer rebase as a workflow command', () => {
+ const store = createStore()
+
+ store.set(rebaseAgentConfigureComposerAtom)
+ store.set(rebaseAgentConfigureComposerAtom)
+
+ expect(store.get(agentConfigureComposerRebaseRevisionAtom)).toBe(2)
+ })
+
+ it('keeps independent panel state as separate primitives', () => {
+ const store = createStore()
+
+ store.set(agentConfigureShowPreviewVersionsAtom, true)
+
+ expect(store.get(agentConfigureShowPreviewVersionsAtom)).toBe(true)
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
index 70d0b4fc352..0bc0be92734 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
@@ -6,9 +6,11 @@ import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-compo
import { agentComposerDraftAtom, agentComposerPublishedDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
+import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
import { useAgentConfigureSync } from '../use-agent-configure-sync'
const toastMock = vi.hoisted(() => ({
+ error: vi.fn(),
success: vi.fn(),
}))
@@ -81,6 +83,13 @@ function createDeferredPromise<T>() {
return { promise, resolve }
}
+function setDocumentVisibilityState(visibilityState: DocumentVisibilityState) {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: visibilityState,
+ })
+}
+
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: toastMock,
}))
@@ -88,6 +97,9 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
+ get: {
+ key: () => ['agents'],
+ },
byAgentId: {
get: {
queryKey: ({ input }: { input: { params: { agent_id: string } } }) => [
@@ -162,12 +174,14 @@ describe('useAgentConfigureSync', () => {
})
afterEach(() => {
+ setDocumentVisibilityState('visible')
vi.useRealTimers()
})
it('should automatically save configure page changes to draft', async () => {
vi.setSystemTime(1710000100000)
const { queryClient, result, store } = renderUseAgentConfigureSync()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['agent-detail', 'agent-1'], {
active_config_is_published: true,
name: 'Agent',
@@ -183,7 +197,7 @@ describe('useAgentConfigureSync', () => {
})
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
- active_config_is_published: false,
+ active_config_is_published: true,
name: 'Agent',
})
expect(composerPutMutationFn).not.toHaveBeenCalled()
@@ -206,14 +220,95 @@ describe('useAgentConfigureSync', () => {
}),
}),
}))
- expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toBeUndefined()
+ expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toEqual({
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Draft only prompt',
+ }),
+ }),
+ })
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
- active_config_is_published: false,
+ active_config_is_published: true,
name: 'Agent',
})
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ['agent-detail', 'agent-1'],
+ })
expect(result.current.draftSavedAt).toBe(1710000105000)
})
+ it('should cancel pending autosave when the draft returns to the saved baseline', async () => {
+ const { queryClient, result, store } = renderUseAgentConfigureSync()
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ active_config_is_published: true,
+ name: 'Agent',
+ })
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Temporary prompt',
+ })
+ })
+ act(() => {
+ store.set(agentComposerDraftAtom, defaultAgentSoulConfigFormState)
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
+ active_config_is_published: true,
+ name: 'Agent',
+ })
+ expect(result.current.draftSavedAt).toBeUndefined()
+ })
+
+ it('should save dirty draft once when the page is closing', async () => {
+ const saveDeferred = createDeferredPromise<{ agent_soul: Record<string, unknown> }>()
+ composerPutMutationFn.mockReturnValueOnce(saveDeferred.promise)
+ const { store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Closing prompt',
+ })
+ })
+
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+
+ await act(async () => {
+ setDocumentVisibilityState('hidden')
+ document.dispatchEvent(new Event('visibilitychange'))
+ window.dispatchEvent(new Event('beforeunload'))
+ await Promise.resolve()
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledTimes(1)
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: expect.objectContaining({
+ variant: 'agent_app',
+ save_strategy: 'save_to_current_version',
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Closing prompt',
+ }),
+ }),
+ }),
+ }))
+
+ await act(async () => {
+ saveDeferred.resolve({ agent_soul: {} })
+ await Promise.resolve()
+ })
+ })
+
it('should include Agent Soul files when autosaving file changes', async () => {
const { store } = renderUseAgentConfigureSync()
@@ -222,11 +317,11 @@ describe('useAgentConfigureSync', () => {
...defaultAgentSoulConfigFormState,
files: [
{
- id: 'files/uploaded.md',
+ id: 'uploaded.md',
name: 'uploaded.md',
icon: 'markdown',
fileId: 'drive-file-1',
- driveKey: 'files/uploaded.md',
+ configName: 'uploaded.md',
},
],
})
@@ -239,17 +334,59 @@ describe('useAgentConfigureSync', () => {
expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
body: expect.objectContaining({
agent_soul: expect.objectContaining({
- files: {
- skills: [],
- files: [
- {
- id: 'files/uploaded.md',
- file_id: 'drive-file-1',
- name: 'uploaded.md',
- drive_key: 'files/uploaded.md',
- },
- ],
- },
+ config_files: [
+ {
+ file_id: 'drive-file-1',
+ file_kind: 'upload_file',
+ name: 'uploaded.md',
+ },
+ ],
+ config_skills: [],
+ }),
+ }),
+ }))
+ })
+
+ it('should preserve uploaded skills when prompt is updated immediately after upload', async () => {
+ const { store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerSkillsAtom, [
+ {
+ id: 'Tender Analyzer',
+ name: 'Tender Analyzer',
+ description: 'Extracts tender requirements.',
+ fileId: 'tool-file-1',
+ hash: 'sha256:skill-1',
+ mimeType: 'application/zip',
+ size: 42,
+ },
+ ])
+ store.set(agentComposerPromptAtom, 'Use [§skill:Tender Analyzer:Tender Analyzer§]')
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Use [§skill:Tender Analyzer:Tender Analyzer§]',
+ }),
+ config_skills: [
+ {
+ description: 'Extracts tender requirements.',
+ file_id: 'tool-file-1',
+ file_kind: 'tool_file',
+ hash: 'sha256:skill-1',
+ mime_type: 'application/zip',
+ name: 'Tender Analyzer',
+ size: 42,
+ },
+ ],
+ config_files: [],
}),
}),
}))
@@ -261,14 +398,17 @@ describe('useAgentConfigureSync', () => {
act(() => {
store.set(agentComposerFilesAtom, [
{
- id: 'files/uploaded.md',
+ id: 'uploaded.md',
name: 'uploaded.md',
icon: 'markdown',
fileId: 'drive-file-1',
- driveKey: 'files/uploaded.md',
+ configName: 'uploaded.md',
+ hash: 'sha256:file-1',
+ mimeType: 'text/markdown',
+ size: 5,
},
])
- store.set(agentComposerPromptAtom, 'Use [§file:files%2Fuploaded.md:uploaded.md§]')
+ store.set(agentComposerPromptAtom, 'Use [§file:uploaded.md:uploaded.md§]')
})
await act(async () => {
@@ -279,19 +419,19 @@ describe('useAgentConfigureSync', () => {
body: expect.objectContaining({
agent_soul: expect.objectContaining({
prompt: expect.objectContaining({
- system_prompt: 'Use [§file:files%2Fuploaded.md:uploaded.md§]',
+ system_prompt: 'Use [§file:uploaded.md:uploaded.md§]',
}),
- files: {
- skills: [],
- files: [
- {
- id: 'files/uploaded.md',
- file_id: 'drive-file-1',
- name: 'uploaded.md',
- drive_key: 'files/uploaded.md',
- },
- ],
- },
+ config_files: [
+ {
+ file_id: 'drive-file-1',
+ file_kind: 'upload_file',
+ hash: 'sha256:file-1',
+ mime_type: 'text/markdown',
+ name: 'uploaded.md',
+ size: 5,
+ },
+ ],
+ config_skills: [],
}),
}),
}))
@@ -321,6 +461,27 @@ describe('useAgentConfigureSync', () => {
expect(result.current.draftSavedAt).toBeUndefined()
})
+ it('should keep autosave failures silent and leave the local draft dirty', async () => {
+ composerPutMutationFn.mockRejectedValueOnce(new Error('save failed'))
+ const { result, store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Unsaved autosave prompt',
+ })
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledTimes(1)
+ expect(result.current.draftSavedAt).toBeUndefined()
+ expect(store.get(agentComposerDraftAtom).prompt).toBe('Unsaved autosave prompt')
+ expect(toastMock.error).not.toHaveBeenCalled()
+ })
+
it('should save the latest draft immediately when requested', async () => {
vi.setSystemTime(1710000200000)
const { result, store } = renderUseAgentConfigureSync()
@@ -354,6 +515,73 @@ describe('useAgentConfigureSync', () => {
expect(result.current.draftSavedAt).toBe(1710000200000)
})
+ it('should reject explicit save requests when the draft cannot be saved', async () => {
+ composerPutMutationFn.mockRejectedValueOnce(new Error('save failed'))
+ const { result, store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Run prompt',
+ })
+ })
+
+ await expect(result.current.saveDraft()).rejects.toThrow('Failed to save agent composer draft.')
+ expect(result.current.draftSavedAt).toBeUndefined()
+ expect(store.get(agentComposerDraftAtom).prompt).toBe('Run prompt')
+ expect(toastMock.error).toHaveBeenCalledWith('common.api.actionFailed')
+ })
+
+ it('should not save the draft immediately when the composer draft is unchanged', async () => {
+ const { queryClient, result } = renderUseAgentConfigureSync()
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ active_config_is_published: true,
+ name: 'Agent',
+ })
+
+ await act(async () => {
+ await result.current.saveDraft()
+ })
+
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
+ active_config_is_published: true,
+ name: 'Agent',
+ })
+ expect(result.current.draftSavedAt).toBeUndefined()
+ })
+
+ it('should save the effective model before run when the form draft is unchanged', async () => {
+ const { result } = renderUseAgentConfigureSync({
+ baseConfig: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: '',
+ },
+ },
+ currentModel: {
+ provider: 'langgenius/openai/openai',
+ model: 'gpt-4o-mini',
+ },
+ })
+
+ await act(async () => {
+ await result.current.saveDraft()
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ model: expect.objectContaining({
+ model_provider: 'langgenius/openai/openai',
+ model: 'gpt-4o-mini',
+ plugin_id: 'langgenius/openai',
+ }),
+ }),
+ }),
+ }))
+ })
+
it('should reject manual save when knowledge retrieval validation fails', async () => {
const { result, store } = renderUseAgentConfigureSync()
@@ -502,6 +730,31 @@ describe('useAgentConfigureSync', () => {
expect(publishAgentMutationFn).toHaveBeenCalledTimes(1)
})
+ it('should reject publish and keep the publish mutation untouched when saving the draft fails', async () => {
+ composerPutMutationFn.mockRejectedValueOnce(new Error('save failed'))
+ const { queryClient, result, store } = renderUseAgentConfigureSync()
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ active_config_is_published: false,
+ name: 'Agent',
+ })
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Unpublished prompt',
+ })
+ })
+
+ await expect(result.current.publishDraft()).rejects.toThrow('Failed to save agent composer draft.')
+
+ expect(publishAgentMutationFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
+ active_config_is_published: false,
+ name: 'Agent',
+ })
+ expect(toastMock.error).toHaveBeenCalledWith('common.api.actionFailed')
+ })
+
it('should reject publish when knowledge retrieval validation fails', async () => {
const { result, store } = renderUseAgentConfigureSync()
diff --git a/web/features/agent-v2/agent-detail/configure/build-draft-query.ts b/web/features/agent-v2/agent-detail/configure/build-draft-query.ts
deleted file mode 100644
index 77ed5f8509e..00000000000
--- a/web/features/agent-v2/agent-detail/configure/build-draft-query.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-'use client'
-
-import type { ContractRouterClient } from '@orpc/contract'
-import type { JsonifiedClient } from '@orpc/openapi-client'
-import type { ConsoleRouterContract } from '@/service/console-link'
-import { createORPCClient } from '@orpc/client'
-import { OpenAPILink } from '@orpc/openapi-client/fetch'
-import { createTanstackQueryUtils } from '@orpc/tanstack-query'
-import { API_PREFIX } from '@/config'
-// eslint-disable-next-line no-restricted-imports
-import { request } from '@/service/base'
-import { getBaseURL } from '@/service/client'
-import { createConsoleDynamicLink } from '@/service/console-link'
-
-type AgentConfigureConsoleClientContext = {
- silent?: boolean
-}
-
-const agentConfigureConsoleLink = createConsoleDynamicLink<AgentConfigureConsoleClientContext>(contract => new OpenAPILink<AgentConfigureConsoleClientContext>(contract, {
- url: getBaseURL(API_PREFIX),
- fetch: (input, init, options) => {
- return request(
- input.url,
- init,
- {
- fetchCompat: true,
- request: input,
- silent: options.context.silent,
- },
- )
- },
-}))
-
-const agentConfigureConsoleClient: JsonifiedClient<ContractRouterClient<ConsoleRouterContract, AgentConfigureConsoleClientContext>>
- = createORPCClient(agentConfigureConsoleLink)
-
-export const agentConfigureConsoleQuery = createTanstackQueryUtils(agentConfigureConsoleClient, {
- path: ['console'],
-})
diff --git a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
index 9a5a9d73a75..3ee53dc8675 100644
--- a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
@@ -15,6 +15,7 @@ import { AgentPromptSlashMenu } from '../orchestrate/prompt-editor/slash'
const mockPromptEditor = vi.hoisted(() => vi.fn())
const mockCopy = vi.hoisted(() => vi.fn())
const mockReset = vi.hoisted(() => vi.fn())
+const mockUseClipboard = vi.hoisted(() => vi.fn())
const mockBuiltInTools = vi.hoisted(() => [
{
id: 'duckduckgo',
@@ -71,11 +72,7 @@ vi.mock('@/app/components/base/infotip', () => ({
}))
vi.mock('foxact/use-clipboard', () => ({
- useClipboard: () => ({
- copied: false,
- copy: mockCopy,
- reset: mockReset,
- }),
+ useClipboard: mockUseClipboard,
}))
vi.mock('@/context/i18n', () => ({
@@ -100,17 +97,16 @@ vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: 'light' }),
}))
-vi.mock('../orchestrate/drive-context', () => ({
- useAgentDriveSkills: () => ({
+vi.mock('../orchestrate/config-context', () => ({
+ useAgentConfigSkills: () => ({
skills: [
{
- id: 'playwright/SKILL.md',
+ id: 'playwright',
name: 'Playwright',
- skillMdKey: 'playwright/SKILL.md',
},
],
}),
- useAgentDriveFiles: () => ({ files: [] }),
+ useAgentConfigFiles: () => ({ files: [] }),
}))
const duckDuckGoSearchAction = {
@@ -171,6 +167,11 @@ const renderAgentPromptEditor = (
describe('AgentPromptEditor', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockUseClipboard.mockReturnValue({
+ copied: false,
+ copy: mockCopy,
+ reset: mockReset,
+ })
})
// Prompt actions should expose the designed copy control and copy the current draft prompt.
@@ -183,6 +184,18 @@ describe('AgentPromptEditor', () => {
expect(mockCopy).toHaveBeenCalledWith('Review these tenders')
})
+ it('should let clipboard timeout restore the copied state instead of resetting on mouse leave', () => {
+ renderAgentPromptEditor('Review these tenders')
+
+ expect(mockUseClipboard).toHaveBeenCalledWith(expect.objectContaining({
+ timeout: 2000,
+ }))
+
+ fireEvent.mouseLeave(screen.getByRole('button', { name: /agentDetail\.configure\.prompt\.copy/i }))
+
+ expect(mockReset).not.toHaveBeenCalled()
+ })
+
it('should update knowledge reference labels when the retrieval title changes', () => {
const store = createStore()
store.set(agentComposerDraftAtom, {
@@ -293,7 +306,7 @@ describe('AgentPromptEditor', () => {
fireEvent.click(screen.getByRole('button', { name: /Playwright/i }))
- expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders [§skill:playwright%2FSKILL.md:Playwright§]')
+ expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders [§skill:playwright:Playwright§]')
await waitFor(() => {
expect(screen.queryByRole('button', { name: /Playwright/i })).not.toBeInTheDocument()
})
@@ -330,7 +343,7 @@ describe('AgentPromptEditor', () => {
files={[]}
tools={[]}
onToolsChange={vi.fn()}
- onAddSkill={options => options?.onAdded?.({ id: 'skill-1', name: 'Skill One', skillMdKey: 'skills/skill-1/SKILL.md' })}
+ onAddSkill={options => options?.onAdded?.({ id: 'skill-1', name: 'Skill One' })}
retrievals={[]}
onBack={vi.fn()}
onOpenCategory={vi.fn()}
@@ -338,7 +351,7 @@ describe('AgentPromptEditor', () => {
/>,
)
fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.add/i }))
- expect(onSelect).toHaveBeenCalledWith('[§skill:skills%2Fskill-1%2FSKILL.md:Skill One§]')
+ expect(onSelect).toHaveBeenCalledWith('[§skill:skill-1:Skill One§]')
rerender(
<AgentPromptSlashMenu
@@ -348,7 +361,7 @@ describe('AgentPromptEditor', () => {
files={[]}
tools={[]}
onToolsChange={vi.fn()}
- onAddFile={options => options?.onAdded?.({ id: 'file-1', name: 'Guide.md', icon: 'markdown', driveKey: 'files/Guide.md' })}
+ onAddFile={options => options?.onAdded?.({ id: 'file-1', name: 'Guide.md', icon: 'markdown', configName: 'Guide.md' })}
retrievals={[]}
onBack={vi.fn()}
onOpenCategory={vi.fn()}
@@ -356,7 +369,7 @@ describe('AgentPromptEditor', () => {
/>,
)
fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.files\.add/i }))
- expect(onSelect).toHaveBeenCalledWith('[§file:files%2FGuide.md:Guide.md§]')
+ expect(onSelect).toHaveBeenCalledWith('[§file:Guide.md:Guide.md§]')
rerender(
<AgentPromptSlashMenu
diff --git a/web/features/agent-v2/agent-detail/configure/components/build-grid-texture.tsx b/web/features/agent-v2/agent-detail/configure/components/build-grid-texture.tsx
new file mode 100644
index 00000000000..e6122129216
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/build-grid-texture.tsx
@@ -0,0 +1,60 @@
+import type { ComponentPropsWithoutRef } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
+
+const buildGridColumnCount = 384
+const buildGridRowCount = 32
+
+function getBuildGridCellOpacity(row: number, column: number) {
+ const seed = Math.sin((row + 1) * 12.9898 + (column + 1) * 78.233) * 43758.5453
+ const noise = seed - Math.floor(seed)
+ const verticalProgress = row / (buildGridRowCount - 1)
+ const densityThreshold = 0.26 + verticalProgress * 0.72
+ const horizontalWeight = Math.min(1, column / 160)
+ const verticalWeight = (1 - verticalProgress) ** 1.7
+
+ if (noise < densityThreshold)
+ return 0
+
+ return Number(Math.min(0.272, (0.032 + noise * 0.058 + horizontalWeight * 0.09) * verticalWeight).toFixed(3))
+}
+
+const buildGridCells = Array.from(
+ { length: buildGridColumnCount * buildGridRowCount },
+ (_, index) => {
+ const row = Math.floor(index / buildGridColumnCount)
+ const column = index % buildGridColumnCount
+ const opacity = getBuildGridCellOpacity(row, column)
+
+ return {
+ id: `build-grid-cell-${row}-${column}`,
+ column: column + 1,
+ opacity,
+ row: row + 1,
+ }
+ },
+).filter(cell => cell.opacity > 0)
+
+export function AgentBuildGridTexture({
+ cellOpacityMultiplier = 1,
+ className,
+ dotClassName,
+ ...props
+}: ComponentPropsWithoutRef<'div'> & {
+ cellOpacityMultiplier?: number
+ dotClassName?: string
+}) {
+ return (
+ <div
+ className={cn('grid grid-cols-[repeat(384,4px)] grid-rows-[repeat(32,4px)] gap-0.5 opacity-70', className)}
+ {...props}
+ >
+ {buildGridCells.map(cell => (
+ <span
+ key={cell.id}
+ className={cn('rounded-[1px] bg-[#98A2B2]', dotClassName)}
+ style={{ gridColumn: `${cell.column}`, gridRow: `${cell.row}`, opacity: Math.min(1, cell.opacity * cellOpacityMultiplier) }}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
index e6ec0d94c1c..c9a53698b30 100644
--- a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
@@ -1,16 +1,27 @@
'use client'
-import type { AgentAppDetailWithSite, AgentIconType } from '@dify/contracts/api/console/agent/types.gen'
-import type { Dispatch, SetStateAction } from 'react'
+import type { AgentAppDetailWithSite, AgentIconType, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { useAgentConfigureData } from '../hooks'
-import type { AgentConfigureConversationIds, AgentConfigureRightPanelMode } from './preview/right-panel-chat'
import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useAtomValue, useSetAtom } from 'jotai'
+import { ScopeProvider } from 'jotai-scope'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import { rebaseAgentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { consoleQuery } from '@/service/client'
import { useAgentConfigureModelOptions } from '../hooks'
+import {
+ agentConfigureConversationIdsAtom,
+ agentConfigureRightPanelChatModeAtom,
+ agentConfigureRightPanelModeAtom,
+ agentConfigureShowChatFeaturesAtom,
+ agentConfigureShowPreviewVersionsAtom,
+ agentConfigureSoulSourceOverrideAtom,
+ resetAgentConfigureConversationAtom,
+ setAgentConfigureConversationIdAtom,
+} from '../state'
import { useAgentConfigureBuildDraftActions, useAgentConfigureBuildDraftData } from '../use-agent-configure-build-draft'
import { useAgentConfigureSync } from '../use-agent-configure-sync'
import { AgentOrchestratePanel } from './orchestrate'
@@ -19,20 +30,11 @@ import { AgentConfigurePageLoading } from './page-loading'
import { AgentBuildPanelBackground } from './preview/build-background'
import { AgentChatFeaturesPanel } from './preview/chat-features-panel'
import { AgentPreviewHeader } from './preview/header'
+import { invalidateAgentWorkingDirectoryFiles, useAgentWorkingDirectoryPanel } from './preview/hook/use-working-directory-panel'
import { AgentConfigureRightPanelChat } from './preview/right-panel-chat'
-import { useAgentWorkingDirectoryPanel } from './preview/use-working-directory-panel'
import { AgentPreviewVersionsPanel } from './preview/versions-panel'
import { AgentConfigurePreviewSurface, AgentConfigureWorkspace } from './workspace'
-type DebugConversationRefreshInput = {
- params: {
- agent_id: string
- }
- body: {
- debug_conversation_id: string
- }
-}
-
export function AgentConfigureComposerScope({
agentId,
composerRebaseRevision,
@@ -53,6 +55,8 @@ export function AgentConfigureComposerScope({
activeVersionId,
agentSoulConfig,
} = configureData
+ const soulSourceOverride = useAtomValue(agentConfigureSoulSourceOverrideAtom)
+ const setSoulSourceOverride = useSetAtom(agentConfigureSoulSourceOverrideAtom)
const isViewingVersion = !!selectedVersionId
const buildDraft = useAgentConfigureBuildDraftData({
agentId,
@@ -60,6 +64,8 @@ export function AgentConfigureComposerScope({
composerAgentSoulConfig: composerQuery.data?.agent_soul,
isViewingVersion,
normalAgentSoulConfig: agentSoulConfig,
+ setSoulSourceOverride,
+ soulSourceOverride,
})
if (buildDraft.isPending) {
@@ -68,9 +74,7 @@ export function AgentConfigureComposerScope({
)
}
- const composerSessionKey = buildDraft.isActive
- ? `${agentId}:${buildDraft.activeVersionId ?? 'build-draft'}`
- : `${agentId}:${buildDraft.activeVersionId ?? 'draft'}:${composerRebaseRevision}`
+ const composerSessionKey = `${agentId}:${activeVersionId ?? selectedVersionId ?? 'draft'}:${composerRebaseRevision}`
return (
<AgentConfigurePageComposerSession
@@ -106,19 +110,13 @@ function AgentConfigurePageComposerSession({
agentQuery,
} = configureData
const queryClient = useQueryClient()
- const [showChatFeatures, setShowChatFeatures] = useState(false)
- const [showPreviewVersions, setShowPreviewVersions] = useState(false)
- const workingDirectoryPanel = useAgentWorkingDirectoryPanel()
- const [clearPreviewChat, setClearPreviewChat] = useState(false)
- const [rightPanelMode, setRightPanelMode] = useState<AgentConfigureRightPanelMode>('build')
- const [hideBuildDraftBarUntilRefresh, setHideBuildDraftBarUntilRefresh] = useState(false)
- const [conversationIds, setConversationIds] = useState<AgentConfigureConversationIds>({
- build: agentQuery.data?.debug_conversation_id ?? null,
- preview: null,
- })
const agentIconType = agentQuery.data?.icon_type as AgentIconType | null | undefined
const refreshDebugConversationMutation = useMutation(consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions({
- onSuccess: ({ debug_conversation_id }) => {
+ onSuccess: ({
+ debug_conversation_id,
+ debug_conversation_has_messages,
+ debug_conversation_message_count,
+ }) => {
queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
(agentDetail) => {
@@ -128,6 +126,8 @@ function AgentConfigurePageComposerSession({
return {
...agentDetail,
debug_conversation_id,
+ debug_conversation_has_messages: debug_conversation_has_messages ?? false,
+ debug_conversation_message_count: debug_conversation_message_count ?? 0,
}
},
)
@@ -138,73 +138,47 @@ function AgentConfigurePageComposerSession({
mutateAsync: refreshDebugConversationRequestAsync,
isPending: isRefreshingDebugConversation,
} = refreshDebugConversationMutation
- const refreshDebugConversationInput = useCallback((conversationId: string): DebugConversationRefreshInput => ({
+ const refreshDebugConversationInput = useCallback(() => ({
params: {
agent_id: agentId,
},
- body: {
- debug_conversation_id: conversationId,
- },
}), [agentId])
- const refreshDebugConversation = useCallback((conversationId: string) => {
- const input = refreshDebugConversationInput(conversationId)
-
- refreshDebugConversationRequest(
- input as unknown as Parameters<typeof refreshDebugConversationRequest>[0],
- )
+ const refreshDebugConversation = useCallback(() => {
+ refreshDebugConversationRequest(refreshDebugConversationInput())
}, [refreshDebugConversationInput, refreshDebugConversationRequest])
- const refreshDebugConversationAsync = useCallback((conversationId: string) => {
- const input = refreshDebugConversationInput(conversationId)
-
- return refreshDebugConversationRequestAsync(
- input as unknown as Parameters<typeof refreshDebugConversationRequestAsync>[0],
- )
+ const refreshDebugConversationAsync = useCallback(() => {
+ return refreshDebugConversationRequestAsync(refreshDebugConversationInput())
}, [refreshDebugConversationInput, refreshDebugConversationRequestAsync])
- const resetBuildChatSession = useCallback(async () => {
- try {
- await refreshDebugConversationAsync(conversationIds.build ?? '')
- }
- finally {
- setConversationIds(current => ({
- ...current,
- build: null,
- }))
- setClearPreviewChat(true)
- }
- }, [conversationIds.build, refreshDebugConversationAsync])
return (
- <AgentComposerProvider
- key={composerSessionKey}
- initialDraft={agentSoulConfigToFormState(buildDraft.agentSoulConfig)}
- initialOriginalConfig={buildDraft.agentSoulConfig}
+ <ScopeProvider
+ atoms={[
+ [agentConfigureConversationIdsAtom, {
+ build: agentQuery.data?.debug_conversation_id ?? null,
+ preview: null,
+ }],
+ ]}
+ name="AgentConfigureConversation"
>
- <AgentConfigurePageComposerContent
- agentId={agentId}
- agentIconType={agentIconType}
- buildDraft={buildDraft}
- clearPreviewChat={clearPreviewChat}
- configureData={configureData}
- conversationIds={conversationIds}
- hideBuildDraftBarUntilRefresh={hideBuildDraftBarUntilRefresh}
- isRefreshingDebugConversation={isRefreshingDebugConversation}
- isViewingVersion={isViewingVersion}
- resetBuildChatSession={resetBuildChatSession}
- rightPanelMode={rightPanelMode}
- setClearPreviewChat={setClearPreviewChat}
- setConversationIds={setConversationIds}
- setHideBuildDraftBarUntilRefresh={setHideBuildDraftBarUntilRefresh}
- setRightPanelMode={setRightPanelMode}
- setShowChatFeatures={setShowChatFeatures}
- setShowPreviewVersions={setShowPreviewVersions}
- showChatFeatures={showChatFeatures}
- showPreviewVersions={showPreviewVersions}
- workingDirectoryPanel={workingDirectoryPanel}
- onComposerRebase={onComposerRebase}
- onRefreshDebugConversation={refreshDebugConversation}
- onSelectVersion={onSelectVersion}
- />
- </AgentComposerProvider>
+ <AgentComposerProvider
+ key={composerSessionKey}
+ initialDraft={agentSoulConfigToFormState(buildDraft.agentSoulConfig)}
+ initialOriginalConfig={buildDraft.agentSoulConfig}
+ >
+ <AgentConfigurePageComposerContent
+ agentId={agentId}
+ agentIconType={agentIconType}
+ buildDraft={buildDraft}
+ configureData={configureData}
+ isRefreshingDebugConversation={isRefreshingDebugConversation}
+ isViewingVersion={isViewingVersion}
+ onComposerRebase={onComposerRebase}
+ onRefreshDebugConversation={refreshDebugConversation}
+ onRefreshDebugConversationAsync={refreshDebugConversationAsync}
+ onSelectVersion={onSelectVersion}
+ />
+ </AgentComposerProvider>
+ </ScopeProvider>
)
}
@@ -212,49 +186,23 @@ function AgentConfigurePageComposerContent({
agentId,
agentIconType,
buildDraft,
- clearPreviewChat,
configureData,
- conversationIds,
- hideBuildDraftBarUntilRefresh,
isRefreshingDebugConversation,
isViewingVersion,
- resetBuildChatSession,
- rightPanelMode,
- setClearPreviewChat,
- setConversationIds,
- setHideBuildDraftBarUntilRefresh,
- setRightPanelMode,
- setShowChatFeatures,
- setShowPreviewVersions,
- showChatFeatures,
- showPreviewVersions,
- workingDirectoryPanel,
onComposerRebase,
onRefreshDebugConversation,
+ onRefreshDebugConversationAsync,
onSelectVersion,
}: {
agentId: string
agentIconType: AgentIconType | null | undefined
buildDraft: ReturnType<typeof useAgentConfigureBuildDraftData>
- clearPreviewChat: boolean
configureData: ReturnType<typeof useAgentConfigureData>
- conversationIds: AgentConfigureConversationIds
- hideBuildDraftBarUntilRefresh: boolean
isRefreshingDebugConversation: boolean
isViewingVersion: boolean
- resetBuildChatSession: () => Promise<void>
- rightPanelMode: AgentConfigureRightPanelMode
- setClearPreviewChat: Dispatch<SetStateAction<boolean>>
- setConversationIds: Dispatch<SetStateAction<AgentConfigureConversationIds>>
- setHideBuildDraftBarUntilRefresh: Dispatch<SetStateAction<boolean>>
- setRightPanelMode: Dispatch<SetStateAction<AgentConfigureRightPanelMode>>
- setShowChatFeatures: Dispatch<SetStateAction<boolean>>
- setShowPreviewVersions: Dispatch<SetStateAction<boolean>>
- showChatFeatures: boolean
- showPreviewVersions: boolean
- workingDirectoryPanel: ReturnType<typeof useAgentWorkingDirectoryPanel>
onComposerRebase: () => void
- onRefreshDebugConversation: (conversationId: string) => void
+ onRefreshDebugConversation: () => void
+ onRefreshDebugConversationAsync: () => Promise<unknown>
onSelectVersion: (versionId: string | null) => void
}) {
const {
@@ -266,8 +214,39 @@ function AgentConfigurePageComposerContent({
activeConfigSnapshot,
agentSoulConfig,
} = configureData
- const rightPanelChatMode: AgentConfigureRightPanelMode = rightPanelMode === 'preview' ? 'build' : rightPanelMode
- const showBuildDraftBar = buildDraft.isActive && !hideBuildDraftBarUntilRefresh
+ const [buildDraftActionsDisabled, setBuildDraftActionsDisabled] = useState(false)
+ const [clearPreviewChat, setClearPreviewChat] = useState(false)
+ const conversationIds = useAtomValue(agentConfigureConversationIdsAtom)
+ const rightPanelChatMode = useAtomValue(agentConfigureRightPanelChatModeAtom)
+ const workingDirectoryPanel = useAgentWorkingDirectoryPanel({
+ agentId,
+ conversationId: conversationIds[rightPanelChatMode],
+ })
+ const showChatFeatures = useAtomValue(agentConfigureShowChatFeaturesAtom)
+ const showPreviewVersions = useAtomValue(agentConfigureShowPreviewVersionsAtom)
+ const resetConversation = useSetAtom(resetAgentConfigureConversationAtom)
+ const setConversationId = useSetAtom(setAgentConfigureConversationIdAtom)
+ const setRightPanelMode = useSetAtom(agentConfigureRightPanelModeAtom)
+ const setShowChatFeatures = useSetAtom(agentConfigureShowChatFeaturesAtom)
+ const setShowPreviewVersions = useSetAtom(agentConfigureShowPreviewVersionsAtom)
+ const rebaseComposerDraft = useSetAtom(rebaseAgentComposerDraftAtom)
+ const queryClient = useQueryClient()
+ const showBuildDraftBar = buildDraft.isActive
+ const resetBuildChatSession = useCallback(async () => {
+ try {
+ await onRefreshDebugConversationAsync()
+ }
+ finally {
+ setConversationId({ mode: 'build', conversationId: null })
+ setClearPreviewChat(true)
+ }
+ }, [onRefreshDebugConversationAsync, setClearPreviewChat, setConversationId])
+ const rebaseComposerDraftFromSoulConfig = useCallback((agentSoulConfig?: AgentSoulConfig) => {
+ rebaseComposerDraft({
+ draft: agentSoulConfigToFormState(agentSoulConfig),
+ originalConfig: agentSoulConfig,
+ })
+ }, [rebaseComposerDraft])
const {
currentModel,
setConfigureModel,
@@ -286,7 +265,10 @@ function AgentConfigurePageComposerContent({
})
const buildDraftActions = useAgentConfigureBuildDraftActions({
agentId,
+ buildDraftAgentSoulConfig: buildDraft.agentSoulConfig,
isActive: buildDraft.isActive,
+ normalAgentSoulConfig: agentSoulConfig,
+ rebaseComposerDraft: rebaseComposerDraftFromSoulConfig,
refetchBuildDraft: buildDraft.refetch,
refetchComposer: composerQuery.refetch,
resetBuildChatSession,
@@ -295,22 +277,30 @@ function AgentConfigurePageComposerContent({
setSoulSourceOverride: buildDraft.setSoulSourceOverride,
})
const selectVersion = useCallback((versionId: string | null) => {
- buildDraft.setSoulSourceOverride(versionId ? 'view-version' : null)
onSelectVersion(versionId)
- }, [buildDraft, onSelectVersion])
+ }, [onSelectVersion])
+ const hasRestartCurrentChatTarget = rightPanelChatMode === 'build'
+ ? (agentQuery.data?.debug_conversation_has_messages ?? false) || buildDraft.isActive
+ : !!conversationIds[rightPanelChatMode]
+ const isRestartCurrentChatDisabled = !hasRestartCurrentChatTarget
+ || buildDraftActionsDisabled
+ || isRefreshingDebugConversation
+ || buildDraftActions.isApplyingBuildDraft
+ || buildDraftActions.isDiscardingBuildDraft
+ const isChatFeaturesReadOnly = (isViewingVersion && versionQuery.isPending) || buildDraft.isActive
const restartCurrentChat = () => {
+ if (isRestartCurrentChatDisabled)
+ return
+
if (rightPanelChatMode === 'build' && buildDraft.isActive) {
void buildDraftActions.discardBuildDraft()
return
}
if (rightPanelChatMode === 'build')
- onRefreshDebugConversation(conversationIds.build ?? '')
+ onRefreshDebugConversation()
- setConversationIds(current => ({
- ...current,
- [rightPanelChatMode]: null,
- }))
+ resetConversation(rightPanelChatMode)
setClearPreviewChat(true)
}
@@ -331,11 +321,13 @@ function AgentConfigurePageComposerContent({
readOnly={isViewingVersion || buildDraft.isActive}
selectedVersionSnapshot={isViewingVersion ? activeConfigSnapshot : undefined}
isBuildDraftActive={buildDraft.isActive}
+ buildDraftChangedKeys={buildDraft.changedKeys}
showPublishBar={!buildDraft.isActive}
bottomAction={showBuildDraftBar
? (
<AgentBuildDraftBar
changesCount={buildDraft.changesCount}
+ disabled={buildDraftActionsDisabled}
isApplying={buildDraftActions.isApplyingBuildDraft}
isDiscarding={buildDraftActions.isDiscardingBuildDraft}
onApply={() => {
@@ -371,7 +363,7 @@ function AgentConfigurePageComposerContent({
workingDirectoryPanel.openWorkingDirectory()
}}
onRefresh={restartCurrentChat}
- refreshDisabled={isRefreshingDebugConversation || buildDraftActions.isDiscardingBuildDraft}
+ refreshDisabled={isRestartCurrentChatDisabled}
/>
)}
chat={(
@@ -387,22 +379,35 @@ function AgentConfigurePageComposerContent({
draftType={rightPanelChatMode === 'build' ? 'debug_build' : undefined}
mode={rightPanelChatMode}
onClearChatListChange={setClearPreviewChat}
- onConversationComplete={(mode) => {
- if (mode === 'build')
- buildDraftActions.refreshBuildDraftAfterBuildChat(() => setHideBuildDraftBarUntilRefresh(false))
+ onConversationComplete={(mode, completedConversationId) => {
+ if (mode === 'build') {
+ invalidateAgentWorkingDirectoryFiles({
+ agentId,
+ conversationId: completedConversationId,
+ queryClient,
+ })
+ buildDraftActions.refreshBuildDraftAfterBuildChat(() => setBuildDraftActionsDisabled(false))
+ }
}}
onConversationIdChange={(mode, conversationId) => {
- setConversationIds(current => ({
- ...current,
- [mode]: conversationId,
- }))
+ setConversationId({ mode, conversationId })
}}
onSaveDraftBeforeRun={rightPanelChatMode === 'build'
? async () => {
- setHideBuildDraftBarUntilRefresh(true)
- await buildDraftActions.prepareBuildDraftBeforeRun()
+ setBuildDraftActionsDisabled(true)
+ try {
+ return await buildDraftActions.prepareBuildDraftBeforeRun()
+ }
+ catch (error) {
+ setBuildDraftActionsDisabled(false)
+ throw error
+ }
}
: saveDraft}
+ onSendInterrupted={() => {
+ if (rightPanelChatMode === 'build')
+ setBuildDraftActionsDisabled(false)
+ }}
/>
)}
/>
@@ -420,8 +425,8 @@ function AgentConfigurePageComposerContent({
{workingDirectoryPanel.panel}
<AgentChatFeaturesPanel
show={showChatFeatures}
- appFeatures={agentSoulConfig?.app_features}
- disabled={versionQuery.isPending}
+ appFeatures={buildDraft.agentSoulConfig?.app_features}
+ disabled={isChatFeaturesReadOnly}
onClose={() => setShowChatFeatures(false)}
/>
</>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/build-draft-bar.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/build-draft-bar.spec.tsx
new file mode 100644
index 00000000000..91d34550e2f
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/build-draft-bar.spec.tsx
@@ -0,0 +1,127 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { AgentBuildDraftBar } from '../build-draft-bar'
+
+describe('AgentBuildDraftBar', () => {
+ it('should disable both build draft actions when the bar is disabled', async () => {
+ const user = userEvent.setup()
+ const onApply = vi.fn()
+ const onDiscard = vi.fn()
+
+ render(
+ <AgentBuildDraftBar
+ changesCount={1}
+ disabled
+ onApply={onApply}
+ onDiscard={onDiscard}
+ />,
+ )
+
+ const applyButton = screen.getByRole('button', { name: 'custom.apply' })
+ const discardButton = screen.getByRole('button', { name: 'agentV2.agentDetail.configure.buildDraft.discard' })
+
+ expect(applyButton).toBeDisabled()
+ expect(discardButton).toBeDisabled()
+
+ await user.click(applyButton)
+ await user.click(discardButton)
+
+ expect(onApply).not.toHaveBeenCalled()
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('should disable both actions while apply is pending', async () => {
+ const user = userEvent.setup()
+ const onApply = vi.fn()
+ const onDiscard = vi.fn()
+
+ render(
+ <AgentBuildDraftBar
+ changesCount={1}
+ isApplying
+ onApply={onApply}
+ onDiscard={onDiscard}
+ />,
+ )
+
+ const applyButton = screen.getByRole('button', { name: 'custom.apply' })
+ const discardButton = screen.getByRole('button', { name: 'agentV2.agentDetail.configure.buildDraft.discard' })
+
+ expect(applyButton).toHaveAttribute('aria-disabled', 'true')
+ expect(applyButton.querySelector('[aria-hidden="true"]')).toBeInTheDocument()
+ expect(discardButton).toBeDisabled()
+
+ await user.click(applyButton)
+ await user.click(discardButton)
+
+ expect(onApply).not.toHaveBeenCalled()
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('should disable both actions while discard is pending', () => {
+ render(
+ <AgentBuildDraftBar
+ changesCount={1}
+ isDiscarding
+ onApply={vi.fn()}
+ onDiscard={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'custom.apply' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.buildDraft.discard' })).toBeDisabled()
+ })
+
+ it('should not show build draft change metadata', () => {
+ const { rerender } = render(
+ <AgentBuildDraftBar
+ changesCount={0}
+ onApply={vi.fn()}
+ onDiscard={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('agentV2.agentDetail.configure.buildDraft.title')).toBeInTheDocument()
+ expect(screen.getAllByText(/^agentV2\.agentDetail\.configure\.buildDraft\./)).toHaveLength(2)
+
+ rerender(
+ <AgentBuildDraftBar
+ changesCount={2}
+ onApply={vi.fn()}
+ onDiscard={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('agentV2.agentDetail.configure.buildDraft.title')).toBeInTheDocument()
+ expect(screen.getAllByText(/^agentV2\.agentDetail\.configure\.buildDraft\./)).toHaveLength(2)
+ })
+
+ it('should keep both actions enabled when there are no build draft changes', async () => {
+ const user = userEvent.setup()
+ const onApply = vi.fn()
+ const onDiscard = vi.fn()
+
+ render(
+ <AgentBuildDraftBar
+ changesCount={0}
+ onApply={onApply}
+ onDiscard={onDiscard}
+ />,
+ )
+
+ const discardButton = screen.getByRole('button', { name: 'agentV2.agentDetail.configure.buildDraft.discard' })
+ const applyButton = screen.getByRole('button', { name: 'custom.apply' })
+ const buttons = screen.getAllByRole('button')
+
+ expect(buttons[0]).toBe(discardButton)
+ expect(buttons[1]).toBe(applyButton)
+ expect(discardButton).toBeEnabled()
+ expect(applyButton).toBeEnabled()
+
+ await user.click(discardButton)
+ await user.click(applyButton)
+
+ expect(onDiscard).toHaveBeenCalledTimes(1)
+ expect(onApply).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx
index 705b83e6039..c09998b1eb5 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx
@@ -8,12 +8,10 @@ import { AgentKnowledgeRetrieval } from '../knowledge'
import { AgentSkills } from '../skills'
import { AgentTools } from '../tools'
-vi.mock('../drive-context', () => ({
- FILES_DRIVE_PREFIX: 'files/',
- getAgentDriveFileName: (key: string) => key.split('/').pop() ?? key,
- useAgentDriveApiContext: () => ({ agentId: 'agent-1' }),
- useAgentDriveFiles: () => ({ files: [], query: { refetch: vi.fn() } }),
- useAgentDriveSkills: () => ({ skills: [], query: { refetch: vi.fn() } }),
+vi.mock('../config-context', () => ({
+ useAgentConfigApiContext: () => ({ agentId: 'agent-1', draftType: 'draft' }),
+ useAgentConfigFiles: () => ({ files: [] }),
+ useAgentConfigSkills: () => ({ skills: [] }),
}))
function renderEmptySections() {
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
index 833b5f072bc..7ba52ad0841 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
@@ -186,14 +186,16 @@ function renderPublishBar({
setupStore?.(store)
const renderPublishBarTree = (nextProps?: {
+ activeConfigIsPublished?: boolean
+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
isPublishing?: boolean
}) => (
<QueryClientProvider client={queryClient}>
<JotaiProvider store={store}>
<AgentConfigurePublishBar
agentId="agent-1"
- activeConfigIsPublished={activeConfigIsPublished}
- activeConfigSnapshot={activeConfigSnapshot}
+ activeConfigIsPublished={nextProps && 'activeConfigIsPublished' in nextProps ? nextProps.activeConfigIsPublished : activeConfigIsPublished}
+ activeConfigSnapshot={nextProps && 'activeConfigSnapshot' in nextProps ? nextProps.activeConfigSnapshot : activeConfigSnapshot}
draftSavedAt={draftSavedAt}
agentName="Iris"
isPublishing={nextProps?.isPublishing ?? isPublishing}
@@ -334,11 +336,16 @@ describe('AgentConfigurePublishBar', () => {
})
it('should keep published state when the published detail updates before the active snapshot is refreshed', () => {
- renderPublishBar({
+ const { rerender, rerenderPublishBar } = renderPublishBar({
activeConfigIsPublished: true,
activeConfigSnapshot: null,
})
+ rerender(rerenderPublishBar({
+ activeConfigIsPublished: undefined,
+ activeConfigSnapshot: undefined,
+ }))
+
expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()
expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
@@ -346,17 +353,17 @@ describe('AgentConfigurePublishBar', () => {
)
})
- it('should keep published state from active config status even when local draft differs', () => {
+ it('should show unpublished state from local draft changes even when active config is published', () => {
renderPublishBar({
activeConfigIsPublished: true,
activeConfigSnapshot: null,
prompt: 'Updated system prompt',
})
- expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()
+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toBeInTheDocument()
expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: false, ignoreInputs: false }),
+ expect.objectContaining({ enabled: true, ignoreInputs: false }),
)
})
@@ -437,6 +444,31 @@ describe('AgentConfigurePublishBar', () => {
expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toBeInTheDocument()
})
+ it('should trust backend published state after autosave confirms the draft matches the active snapshot', () => {
+ const stalePublishedDraftBaseline = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Old unpublished normal draft',
+ }
+ const savedDraftMatchingActiveSnapshot = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Published prompt',
+ }
+
+ renderPublishBar({
+ activeConfigIsPublished: true,
+ activeConfigSnapshot,
+ setupStore: (store) => {
+ store.set(agentComposerPublishedDraftAtom, stalePublishedDraftBaseline)
+ store.set(agentComposerOriginalDraftAtom, savedDraftMatchingActiveSnapshot)
+ store.set(agentComposerDraftAtom, savedDraftMatchingActiveSnapshot)
+ },
+ })
+
+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()
+ expect(screen.queryByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).not.toBeInTheDocument()
+ })
+
it('should render publishing as a single disabled action state', () => {
renderPublishBar({ isPublishing: true, prompt: 'Updated system prompt' })
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx
index c7b423ecf59..eb726953acd 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx
@@ -23,6 +23,6 @@ describe('AgentAdvancedSettings', () => {
fireEvent.click(triggers[0]!)
expect(screen.getByText('advanced-env-editor')).toBeInTheDocument()
- expect(screen.getByText('advanced-content-moderation')).toBeInTheDocument()
+ expect(screen.queryByText('advanced-content-moderation')).not.toBeInTheDocument()
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx
index 7c1aa1ce52d..7f71c52fd6c 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx
@@ -1,6 +1,7 @@
'use client'
import { useTranslation } from 'react-i18next'
+import { ENABLE_AGENT_CONTENT_MODERATION } from '../../../feature-flags'
import { ConfigureSection } from '../common/section'
import { AgentContentModerationSettings } from './content-moderation'
import { AgentEnvEditor } from './env'
@@ -22,7 +23,7 @@ export function AgentAdvancedSettings() {
panelContentClassName="flex flex-col rounded-lg bg-background-section"
>
<AgentEnvEditor />
- <AgentContentModerationSettings />
+ {ENABLE_AGENT_CONTENT_MODERATION && <AgentContentModerationSettings />}
</ConfigureSection>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx
index ca91a3959e5..924f3e44f15 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx
@@ -2,9 +2,11 @@
import { Button } from '@langgenius/dify-ui/button'
import { useTranslation } from 'react-i18next'
+import { AgentBuildGridTexture } from '../build-grid-texture'
type AgentBuildDraftBarProps = {
changesCount: number
+ disabled?: boolean
isApplying?: boolean
isDiscarding?: boolean
onApply: () => void
@@ -12,7 +14,7 @@ type AgentBuildDraftBarProps = {
}
export function AgentBuildDraftBar({
- changesCount,
+ disabled = false,
isApplying = false,
isDiscarding = false,
onApply,
@@ -20,40 +22,41 @@ export function AgentBuildDraftBar({
}: AgentBuildDraftBarProps) {
const { t } = useTranslation('agentV2')
const { t: tCustom } = useTranslation('custom')
- const isPending = isApplying || isDiscarding
- const metaLabel = changesCount > 0
- ? t('agentDetail.configure.buildDraft.changes', { count: changesCount })
- : t('agentDetail.configure.buildDraft.noChanges')
+ const isActionPending = isApplying || isDiscarding
+ const applyDisabled = disabled || isActionPending
+ const discardDisabled = disabled || isActionPending
return (
- <div className="pointer-events-auto flex max-w-full min-w-0 items-center gap-2 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur py-2 pr-2 pl-4 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">
- <div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 pr-2">
+ <div className="pointer-events-auto relative flex h-[50px] w-fit max-w-full min-w-0 items-center gap-2 overflow-hidden rounded-xl border-[1.5px] border-[#A0BDFF] bg-components-panel-bg-blur p-2 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[10px]">
+ <AgentBuildGridTexture
+ aria-hidden
+ cellOpacityMultiplier={3}
+ className="pointer-events-none absolute top-[-104px] left-[-1171px] z-0 opacity-70"
+ dotClassName="bg-[#5C90FF]"
+ />
+ <div className="relative z-1 flex min-w-0 flex-1 flex-col justify-center gap-0.5 pr-8 pl-2">
<p className="min-w-0 truncate system-sm-semibold text-text-primary">
{t('agentDetail.configure.buildDraft.title')}
</p>
- <p className="min-w-0 truncate system-xs-regular text-text-tertiary">
- {metaLabel}
- </p>
</div>
<Button
type="button"
- variant="primary"
- loading={isApplying}
- disabled={isPending}
- className="h-8 rounded-lg px-3"
- onClick={onApply}
+ variant="secondary"
+ disabled={discardDisabled}
+ className="relative z-1 h-8 shrink-0 rounded-lg px-3"
+ onClick={onDiscard}
>
- {tCustom('apply')}
+ {t('agentDetail.configure.buildDraft.discard')}
</Button>
<Button
type="button"
- variant="secondary"
- loading={isDiscarding}
- disabled={isPending}
- className="h-8 rounded-lg px-3"
- onClick={onDiscard}
+ variant="primary"
+ loading={isApplying}
+ disabled={applyDisabled}
+ className="relative z-1 h-8 min-w-20 shrink-0 rounded-lg px-3"
+ onClick={onApply}
>
- {t('agentDetail.configure.buildDraft.discard')}
+ {tCustom('apply')}
</Button>
</div>
)
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-change-dot.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-change-dot.tsx
new file mode 100644
index 00000000000..634dc6a460d
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-change-dot.tsx
@@ -0,0 +1,10 @@
+'use client'
+
+export function AgentBuildDraftChangeDot() {
+ return (
+ <span
+ aria-hidden="true"
+ className="absolute top-[9px] left-[-9px] size-[5px] rounded-full bg-text-warning-secondary"
+ />
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-changes-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-changes-context.ts
new file mode 100644
index 00000000000..3ba01f16da1
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-changes-context.ts
@@ -0,0 +1,43 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
+import { createContext, createElement, useContext, useMemo } from 'react'
+
+export type AgentBuildDraftChangedKey = keyof AgentSoulConfigFormState
+
+export type AgentBuildDraftChangeSection
+ = | 'skills'
+ | 'files'
+
+const changedKeysBySection: Record<AgentBuildDraftChangeSection, readonly AgentBuildDraftChangedKey[]> = {
+ skills: ['skills'],
+ files: ['files'],
+}
+
+const AgentBuildDraftChangedKeysContext = createContext<ReadonlySet<AgentBuildDraftChangedKey>>(new Set())
+
+export function AgentBuildDraftChangedKeysProvider({
+ changedKeys,
+ children,
+}: {
+ changedKeys: readonly AgentBuildDraftChangedKey[]
+ children: ReactNode
+}) {
+ const changedKeySet = useMemo(() => new Set(changedKeys), [changedKeys])
+
+ return createElement(
+ AgentBuildDraftChangedKeysContext.Provider,
+ { value: changedKeySet },
+ children,
+ )
+}
+
+export function useIsAgentBuildDraftSectionChanged(section?: AgentBuildDraftChangeSection) {
+ const changedKeys = useContext(AgentBuildDraftChangedKeysContext)
+
+ if (!section)
+ return false
+
+ return changedKeysBySection[section].some(key => changedKeys.has(key))
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/__tests__/section.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/__tests__/section.spec.tsx
new file mode 100644
index 00000000000..fabcecab16f
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/__tests__/section.spec.tsx
@@ -0,0 +1,44 @@
+import type { AgentBuildDraftChangedKey } from '../../build-draft-changes-context'
+import { render, screen } from '@testing-library/react'
+import { AgentBuildDraftChangedKeysProvider } from '../../build-draft-changes-context'
+import { ConfigureSection } from '../section'
+
+function renderSection({
+ section = 'skills',
+ changedKeys,
+}: {
+ section?: 'skills' | 'files'
+ changedKeys: AgentBuildDraftChangedKey[]
+}) {
+ return render(
+ <AgentBuildDraftChangedKeysProvider changedKeys={changedKeys}>
+ <ConfigureSection
+ label={section === 'skills' ? 'Skills' : 'Files'}
+ labelId={`${section}-label`}
+ buildDraftChangeSection={section}
+ >
+ <div>{`${section} content`}</div>
+ </ConfigureSection>
+ </AgentBuildDraftChangedKeysProvider>,
+ )
+}
+
+describe('ConfigureSection', () => {
+ it('should show a build draft change dot when Skills changed', () => {
+ renderSection({ section: 'skills', changedKeys: ['skills'] })
+
+ expect(screen.getByRole('heading', { name: 'Skills' }).querySelector('.bg-text-warning-secondary')).toBeInTheDocument()
+ })
+
+ it('should show a build draft change dot when Files changed', () => {
+ renderSection({ section: 'files', changedKeys: ['files'] })
+
+ expect(screen.getByRole('heading', { name: 'Files' }).querySelector('.bg-text-warning-secondary')).toBeInTheDocument()
+ })
+
+ it('should not show a build draft change dot when only another key changed', () => {
+ renderSection({ section: 'skills', changedKeys: ['prompt'] })
+
+ expect(screen.getByRole('heading', { name: 'Skills' }).querySelector('.bg-text-warning-secondary')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx
index 22ab3e0946c..a81822f5f6a 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx
@@ -1,6 +1,7 @@
'use client'
import type { ReactNode } from 'react'
+import type { AgentBuildDraftChangeSection } from '../build-draft-changes-context'
import { cn } from '@langgenius/dify-ui/cn'
import {
CollapsiblePanel,
@@ -8,12 +9,15 @@ import {
CollapsibleTrigger,
} from '@langgenius/dify-ui/collapsible'
import { Infotip } from '@/app/components/base/infotip'
+import { AgentBuildDraftChangeDot } from '../build-draft-change-dot'
+import { useIsAgentBuildDraftSectionChanged } from '../build-draft-changes-context'
type ConfigureSectionBaseProps = {
label: ReactNode
labelId: string
children: ReactNode
actions?: ReactNode
+ buildDraftChangeSection?: AgentBuildDraftChangeSection
description?: ReactNode
defaultOpen?: boolean
headingLevel?: 'h3' | 'h4'
@@ -40,6 +44,7 @@ export function ConfigureSection({
labelId,
children,
actions,
+ buildDraftChangeSection,
description,
defaultOpen = true,
headingLevel = 'h3',
@@ -54,6 +59,7 @@ export function ConfigureSection({
const Heading = headingLevel
const hasDescription = description !== undefined && description !== null
const hasTip = tip !== undefined && tip !== null
+ const isBuildDraftChanged = useIsAgentBuildDraftSectionChanged(buildDraftChangeSection)
return (
<CollapsibleRoot
@@ -65,7 +71,8 @@ export function ConfigureSection({
<div className={cn('mb-2 flex min-h-6 items-center gap-2', headerClassName)}>
<div className="min-w-0 flex-1">
<div className={cn('flex min-w-0 items-center', titleRowClassName)}>
- <Heading id={labelId} className="min-w-0 shrink-0">
+ <Heading id={labelId} className="relative min-w-0 shrink-0">
+ {isBuildDraftChanged && <AgentBuildDraftChangeDot />}
<CollapsibleTrigger
className="h-6 min-h-0 w-auto max-w-full justify-start gap-0 rounded-sm px-0 text-text-secondary hover:not-data-disabled:bg-transparent hover:not-data-disabled:text-text-secondary data-panel-open:text-text-secondary"
>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/config-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/config-context.ts
new file mode 100644
index 00000000000..faa1892cf7e
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/config-context.ts
@@ -0,0 +1,48 @@
+'use client'
+
+import { useAtomValue } from 'jotai'
+import { createContext, use } from 'react'
+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
+import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
+
+export type AgentConfigApiContext = {
+ agentId: string
+ draftType?: 'draft' | 'debug_build'
+ versionId?: string
+ workflow?: {
+ appId: string
+ nodeId: string
+ }
+}
+
+const AgentConfigApiContext = createContext<AgentConfigApiContext | null>(null)
+
+export const AgentConfigApiContextProvider = AgentConfigApiContext.Provider
+
+export const useAgentConfigApiContext = () => {
+ const context = use(AgentConfigApiContext)
+ if (!context)
+ throw new Error('AgentConfigApiContextProvider is required for config-backed UI.')
+
+ return context
+}
+
+export const useAgentConfigSkills = () => {
+ const apiContext = useAgentConfigApiContext()
+ const skills = useAtomValue(agentComposerSkillsAtom)
+
+ return {
+ apiContext,
+ skills,
+ }
+}
+
+export const useAgentConfigFiles = () => {
+ const apiContext = useAgentConfigApiContext()
+ const files = useAtomValue(agentComposerFilesAtom)
+
+ return {
+ apiContext,
+ files,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.ts
deleted file mode 100644
index b9443c6b59d..00000000000
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-'use client'
-
-import { useAtomValue } from 'jotai'
-import { createContext, use, useMemo } from 'react'
-import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
-import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
-
-export type AgentDriveApiContext = {
- agentId: string
- workflow?: {
- appId: string
- nodeId: string
- }
-}
-
-export const FILES_DRIVE_PREFIX = 'files/'
-
-const AgentDriveApiContext = createContext<AgentDriveApiContext | null>(null)
-
-export const AgentDriveApiContextProvider = AgentDriveApiContext.Provider
-
-export const useAgentDriveApiContext = () => {
- const context = use(AgentDriveApiContext)
- if (!context)
- throw new Error('AgentDriveApiContextProvider is required for drive-backed UI.')
-
- return context
-}
-
-export const useAgentDriveSkills = () => {
- const apiContext = useAgentDriveApiContext()
- const skills = useAtomValue(agentComposerSkillsAtom)
-
- return {
- apiContext,
- skills,
- }
-}
-
-export const useAgentDriveFiles = ({
- prefix = FILES_DRIVE_PREFIX,
-}: {
- prefix?: string
-} = {}) => {
- const apiContext = useAgentDriveApiContext()
- const draftFiles = useAtomValue(agentComposerFilesAtom)
- const files = useMemo(
- () => draftFiles.filter(file => !prefix || file.driveKey?.startsWith(prefix)),
- [draftFiles, prefix],
- )
-
- return {
- apiContext,
- files,
- }
-}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
index 02c263be6da..d6921776e3e 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
@@ -1,858 +1,406 @@
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentConfigApiContext } from '../../config-context'
import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
+import { toast } from '@langgenius/dify-ui/toast'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
-import { AgentDriveApiContextProvider } from '../../drive-context'
+import { AgentConfigApiContextProvider } from '../../config-context'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentFiles } from '../index'
+type ConfigFileQueryOptionsInput = {
+ input: {
+ params: {
+ name: string
+ }
+ }
+}
+
const mocks = vi.hoisted(() => ({
- agentDriveFilesQueryOptions: vi.fn(),
- agentFileCommitMutationFn: vi.fn(),
- agentFileDeleteMutationFn: vi.fn(),
- agentFileDeleteMutationOptions: vi.fn(),
- agentFileDownloadQueryOptions: vi.fn(),
- agentFilePreviewQueryOptions: vi.fn(),
- agentFileCommitMutationOptions: vi.fn(),
- workflowAgentDriveFilesQueryOptions: vi.fn(),
- workflowAgentFileCommitMutationFn: vi.fn(),
- workflowAgentFileDeleteMutationFn: vi.fn(),
- workflowAgentFileDeleteMutationOptions: vi.fn(),
- workflowAgentFileDownloadQueryOptions: vi.fn(),
- workflowAgentFilePreviewQueryOptions: vi.fn(),
- workflowAgentFileCommitMutationOptions: vi.fn(),
- uploadFileMutationFn: vi.fn(),
- uploadFileMutationOptions: vi.fn(),
+ uploadFileMutationFn: vi.fn(async (_input: unknown) => ({ id: 'upload-1' })),
+ commitFileMutationFn: vi.fn(async (_input: unknown) => ({
+ config_version: { id: 'draft-1', kind: 'draft', writable: true },
+ file: {
+ id: 'uploaded.md',
+ name: 'uploaded.md',
+ file_id: 'drive-file-1',
+ hash: 'sha256:file-1',
+ mime_type: 'text/markdown',
+ size: 5,
+ },
+ })),
+ deleteFileMutationFn: vi.fn(async (_input: unknown) => ({ removed_names: ['brief.md'], result: 'success' })),
+ previewQueryOptions: vi.fn((_options: ConfigFileQueryOptionsInput) => ({})),
+ downloadQueryOptions: vi.fn((_options: ConfigFileQueryOptionsInput) => ({})),
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
}))
vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
byAgentId: {
- drive: {
+ config: {
files: {
- get: {
- queryOptions: mocks.agentDriveFilesQueryOptions,
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.commitFileMutationFn }),
},
- download: {
- get: {
- queryOptions: mocks.agentFileDownloadQueryOptions,
+ byName: {
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.deleteFileMutationFn }),
},
- },
- preview: {
- get: {
- queryOptions: mocks.agentFilePreviewQueryOptions,
+ preview: {
+ get: {
+ queryOptions: mocks.previewQueryOptions,
+ },
+ },
+ download: {
+ get: {
+ queryOptions: mocks.downloadQueryOptions,
+ },
},
},
},
},
- files: {
- delete: {
- mutationOptions: mocks.agentFileDeleteMutationOptions,
- },
- post: {
- mutationOptions: mocks.agentFileCommitMutationOptions,
- },
- },
},
},
apps: {
byAppId: {
agent: {
- drive: {
+ config: {
files: {
- get: {
- queryOptions: mocks.workflowAgentDriveFilesQueryOptions,
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.commitFileMutationFn }),
},
- download: {
- get: {
- queryOptions: mocks.workflowAgentFileDownloadQueryOptions,
+ byName: {
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.deleteFileMutationFn }),
},
- },
- preview: {
- get: {
- queryOptions: mocks.workflowAgentFilePreviewQueryOptions,
+ preview: {
+ get: {
+ queryOptions: mocks.previewQueryOptions,
+ },
+ },
+ download: {
+ get: {
+ queryOptions: mocks.downloadQueryOptions,
+ },
},
},
},
},
- files: {
- delete: {
- mutationOptions: mocks.workflowAgentFileDeleteMutationOptions,
- },
- post: {
- mutationOptions: mocks.workflowAgentFileCommitMutationOptions,
- },
- },
},
},
},
files: {
upload: {
post: {
- mutationOptions: mocks.uploadFileMutationOptions,
+ mutationOptions: () => ({ mutationFn: mocks.uploadFileMutationFn }),
},
},
},
},
}))
-const agentFilesDraft = {
- ...defaultAgentSoulConfigFormState,
- files: [
- {
- id: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- name: 'agent-roster-skill-detail-dialog-preview-image.png',
- icon: 'image',
- driveKey: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- },
- {
- id: 'files/brief.md',
- name: 'brief.md',
- icon: 'markdown',
- driveKey: 'files/brief.md',
- },
- ],
-} satisfies AgentSoulConfigFormState
-
-const agentSkillFilesDraft = {
- ...defaultAgentSoulConfigFormState,
- files: [
- {
- id: 'files/run.py',
- name: 'run.py',
- icon: 'code',
- driveKey: 'files/run.py',
- },
- {
- id: 'files/SKILL.md',
- name: 'SKILL.md',
- icon: 'markdown',
- driveKey: 'files/SKILL.md',
- },
- ],
-} satisfies AgentSoulConfigFormState
-
-function renderAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDraft) {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
+function ConfigSnapshotProbe() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
- return render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={initialDraft}>
- <AgentFiles />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
+ return (
+ <pre data-testid="config-snapshot-probe">
+ {JSON.stringify(configSnapshot)}
+ </pre>
)
}
-function renderReadonlyAgentFiles() {
+function renderAgentFiles({
+ initialDraft = {
+ ...defaultAgentSoulConfigFormState,
+ files: [
+ {
+ id: 'diagram.png',
+ name: 'diagram.png',
+ icon: 'image',
+ fileId: 'upload-file-1',
+ configName: 'diagram.png',
+ },
+ {
+ id: 'brief.md',
+ name: 'brief.md',
+ icon: 'markdown',
+ fileId: 'upload-file-2',
+ configName: 'brief.md',
+ },
+ ],
+ } satisfies AgentSoulConfigFormState,
+ initialOriginalConfig,
+ apiContext = { agentId: 'agent-1', draftType: 'draft' } satisfies AgentConfigApiContext,
+ readOnly = false,
+}: {
+ initialDraft?: AgentSoulConfigFormState
+ initialOriginalConfig?: AgentSoulConfig
+ apiContext?: AgentConfigApiContext
+ readOnly?: boolean
+} = {}) {
const queryClient = new QueryClient({
defaultOptions: {
- queries: {
- retry: false,
- },
+ queries: { retry: false },
+ mutations: { retry: false },
},
})
return render(
<QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={agentFilesDraft}>
- <AgentOrchestrateReadOnlyContext value>
+ <AgentConfigApiContextProvider value={apiContext}>
+ <AgentComposerProvider initialDraft={initialDraft} initialOriginalConfig={initialOriginalConfig}>
+ <AgentOrchestrateReadOnlyContext value={readOnly}>
<AgentFiles />
+ <ConfigSnapshotProbe />
</AgentOrchestrateReadOnlyContext>
</AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
- )
-}
-
-function renderWorkflowAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDraft) {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
-
- return render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1', workflow: { appId: 'app-1', nodeId: 'node-1' } }}>
- <AgentComposerProvider initialDraft={initialDraft}>
- <AgentFiles />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
+ </AgentConfigApiContextProvider>
</QueryClientProvider>,
)
}
-function ConfigSnapshotProbe() {
- const draft = useAtomValue(agentComposerDraftAtom)
- const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
-
- return (
- <pre data-testid="config-snapshot-probe">
- {JSON.stringify(configSnapshot)}
- </pre>
- )
-}
-
describe('AgentFiles', () => {
beforeEach(() => {
vi.clearAllMocks()
- const baseItems = [
- {
- file_kind: 'file',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- mime_type: 'image/png',
- },
- {
- file_kind: 'file',
- key: 'files/brief.md',
- mime_type: 'text/markdown',
- },
- ]
- mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
- initialData: { items: baseItems },
- queryFn: async () => ({
- items: baseItems,
- }),
- }))
- mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-drive-files', input],
- initialData: { items: baseItems },
- queryFn: async () => ({
- items: baseItems,
- }),
- }))
- mocks.agentFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-file-preview', input],
- queryFn: async () => ({
- binary: false,
- text: `Preview content for ${input.query.key}`,
- }),
- }))
- mocks.workflowAgentFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-file-preview', input],
+ mocks.previewQueryOptions.mockImplementation(({ input }) => ({
+ queryKey: ['preview-config-file', input],
queryFn: async () => ({
+ name: input.params.name,
binary: false,
- text: `Preview content for ${input.query.key}`,
- }),
- }))
- mocks.agentFileDownloadQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-file-download', input],
- queryFn: async () => ({
- url: `https://signed.example/${input.query.key}`,
+ truncated: false,
+ text: `Preview for ${input.params.name}`,
}),
}))
- mocks.workflowAgentFileDownloadQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-file-download', input],
+ mocks.downloadQueryOptions.mockImplementation(({ input }) => ({
+ queryKey: ['download-config-file', input],
queryFn: async () => ({
- url: `https://signed.example/${input.query.key}`,
+ url: `https://example.com/${input.params.name}`,
}),
}))
- mocks.uploadFileMutationOptions.mockReturnValue({
- mutationFn: mocks.uploadFileMutationFn.mockResolvedValue({
- id: 'upload-file-1',
- name: 'uploaded.md',
- mime_type: 'text/markdown',
- }),
- mutationKey: ['upload-file'],
- })
- mocks.agentFileCommitMutationOptions.mockReturnValue({
- mutationFn: mocks.agentFileCommitMutationFn.mockResolvedValue({
- file: {
- drive_key: 'files/uploaded.md',
- file_id: 'drive-file-1',
- mime_type: 'text/markdown',
- name: 'uploaded.md',
- },
- }),
- mutationKey: ['commit-agent-file'],
- })
- mocks.workflowAgentFileCommitMutationOptions.mockReturnValue({
- mutationFn: mocks.workflowAgentFileCommitMutationFn.mockResolvedValue({
- file: {
- drive_key: 'files/uploaded.md',
- file_id: 'drive-file-1',
- mime_type: 'text/markdown',
- name: 'uploaded.md',
- },
- }),
- mutationKey: ['commit-workflow-agent-file'],
- })
- mocks.agentFileDeleteMutationOptions.mockReturnValue({
- mutationFn: mocks.agentFileDeleteMutationFn.mockResolvedValue({ result: 'success' }),
- mutationKey: ['delete-agent-file'],
- })
- mocks.workflowAgentFileDeleteMutationOptions.mockReturnValue({
- mutationFn: mocks.workflowAgentFileDeleteMutationFn.mockResolvedValue({ result: 'success' }),
- mutationKey: ['delete-workflow-agent-file'],
- })
})
- it('should list Agent Soul files under the files prefix', () => {
- renderAgentFiles()
+ it('should delete configured files by config name', async () => {
+ const { container } = renderAgentFiles()
- expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
- expect(mocks.agentDriveFilesQueryOptions).not.toHaveBeenCalled()
- })
+ const removeButton = container.querySelector('[data-agent-file-remove-button]')
+ expect(removeButton).not.toBeNull()
- it('should list workflow-node Agent Soul files under the files prefix', () => {
- renderWorkflowAgentFiles()
+ fireEvent.click(removeButton!)
- expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
- expect(mocks.workflowAgentDriveFilesQueryOptions).not.toHaveBeenCalled()
- })
-
- it('should keep the file preview trigger focus ring inside the row bounds', () => {
- renderAgentFiles()
-
- expect(screen.getByRole('button', { name: 'brief.md' })).toHaveClass(
- 'focus-visible:ring-2',
- 'focus-visible:ring-state-accent-solid',
- 'focus-visible:ring-inset',
- )
- })
-
- it('should open the shared detail dialog with the full file tree when the file row is clicked', async () => {
- renderAgentFiles()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'brief.md',
- }))
-
- const dialog = screen.getByRole('dialog')
-
- expect(dialog).toBeInTheDocument()
- expect(within(dialog).getByText('agent-roster-skill-detail-dialog-preview-image.png')).toBeInTheDocument()
- expect(within(dialog).getAllByText('brief.md')).toHaveLength(2)
- expect(mocks.agentFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
+ await waitFor(() => {
+ expect(mocks.deleteFileMutationFn).toHaveBeenCalled()
+ expect(mocks.deleteFileMutationFn.mock.calls[0]?.[0]).toEqual({
params: {
agent_id: 'agent-1',
+ name: 'diagram.png',
},
query: {
- key: 'files/brief.md',
+ draft_type: 'draft',
+ version_id: undefined,
},
- },
+ })
})
- expect(await within(dialog).findByText('Preview content for files/brief.md')).toBeInTheDocument()
- })
- it('should preview the clicked file when SKILL.md also exists', async () => {
- mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
- initialData: {
- items: [
- { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },
- { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },
- ],
- },
- queryFn: async () => ({
- items: [
- { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },
- { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },
- ],
- }),
- }))
- renderAgentFiles(agentSkillFilesDraft)
-
- fireEvent.click(screen.getByRole('button', {
- name: 'run.py',
- }))
-
- const dialog = screen.getByRole('dialog')
-
- expect(await within(dialog).findByText('Preview content for files/run.py')).toBeInTheDocument()
- expect(mocks.agentFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- agent_id: 'agent-1',
- },
- query: {
- key: 'files/run.py',
- },
- },
- })
+ expect(screen.queryByText('diagram.png')).not.toBeInTheDocument()
})
- it('should preview the selected file from the detail file tree', async () => {
- mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
- initialData: {
- items: [
- { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },
- { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },
- ],
- },
- queryFn: async () => ({
- items: [
- { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },
- { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },
- ],
- }),
- }))
- renderAgentFiles(agentSkillFilesDraft)
+ it('should upload through the two-step config file flow and persist config_files in draft state', async () => {
+ const user = userEvent.setup()
+ renderAgentFiles({ initialDraft: defaultAgentSoulConfigFormState })
- fireEvent.click(screen.getByRole('button', {
- name: 'run.py',
- }))
+ await user.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.files\.add/i }))
- const dialog = screen.getByRole('dialog')
- const skillFile = within(dialog).getByRole('button', { name: 'SKILL.md' })
- fireEvent.click(skillFile)
-
- expect(await within(dialog).findByText('Preview content for files/SKILL.md')).toBeInTheDocument()
-
- const scriptFile = within(dialog).getAllByRole('button', { name: 'run.py' }).at(-1)
- expect(scriptFile).toBeDefined()
- fireEvent.click(scriptFile!)
+ const input = await waitFor(() => {
+ const element = document.querySelector('input[type="file"]')
+ expect(element).not.toBeNull()
+ return element as HTMLInputElement
+ })
+ const file = new File(['hello'], 'uploaded.md', { type: 'text/markdown' })
+ await user.upload(input, file)
+ await user.click(screen.getByRole('button', { name: /agentDetail\.configure\.files\.upload\.action/i }))
- expect(await within(dialog).findByText('Preview content for files/run.py')).toBeInTheDocument()
- expect(mocks.agentFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- agent_id: 'agent-1',
- },
- query: {
- key: 'files/run.py',
+ await waitFor(() => {
+ expect(mocks.uploadFileMutationFn).toHaveBeenCalled()
+ expect(mocks.uploadFileMutationFn.mock.calls[0]?.[0]).toEqual({
+ body: {
+ file,
},
- },
+ })
})
- })
- it('should render image files directly from the drive download URL without a download link', async () => {
- mocks.agentFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-file-preview', input],
- queryFn: async () => ({
- binary: false,
- key: input.query.key,
- size: 12345,
- text: 'image preview should not render as text',
- truncated: false,
- }),
- }))
- renderAgentFiles()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'agent-roster-skill-detail-dialog-preview-image.png',
- }))
-
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- expect(mocks.agentFileDownloadQueryOptions).toHaveBeenCalledWith({
- input: {
+ await waitFor(() => {
+ expect(mocks.commitFileMutationFn).toHaveBeenCalled()
+ expect(mocks.commitFileMutationFn.mock.calls[0]?.[0]).toEqual({
params: {
agent_id: 'agent-1',
},
query: {
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
+ draft_type: 'draft',
+ version_id: undefined,
},
- },
+ body: {
+ upload_file_id: 'upload-1',
+ },
+ })
})
- })
- it('should render a download link for binary non-image files', async () => {
- mocks.agentFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-file-preview', input],
- queryFn: async () => ({
- binary: true,
- key: input.query.key,
- size: 12345,
- text: null,
- truncated: false,
+ const snapshot = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')
+ expect(snapshot.config_files).toEqual([
+ expect.objectContaining({
+ name: 'uploaded.md',
+ file_id: 'drive-file-1',
+ file_kind: 'upload_file',
+ hash: 'sha256:file-1',
+ mime_type: 'text/markdown',
+ size: 5,
}),
- }))
- renderAgentFiles()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'brief.md',
- }))
-
- const link = await screen.findByRole('link', { name: 'common.operation.download' })
-
- expect(screen.getByText('agentV2.agentDetail.configure.files.preview.unsupported')).toBeInTheDocument()
- expect(link).toHaveAttribute('href', 'https://signed.example/files/brief.md')
- expect(screen.queryByText('Preview content for files/brief.md')).not.toBeInTheDocument()
+ ])
+ expect(toast.success).toHaveBeenCalled()
})
- it('should use workflow preview and download routes when workflow context is active', async () => {
- mocks.workflowAgentFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-file-preview', input],
- queryFn: async () => ({
- binary: true,
- key: input.query.key,
- size: 12345,
- text: null,
- truncated: false,
- }),
- }))
- renderWorkflowAgentFiles()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'brief.md',
- }))
-
- expect(mocks.workflowAgentFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- key: 'files/brief.md',
- },
- },
- })
- expect(mocks.workflowAgentFileDownloadQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- key: 'files/brief.md',
+ it('should use workflow config file endpoints with node_id for preview and upload', async () => {
+ const user = userEvent.setup()
+ renderAgentFiles({
+ apiContext: {
+ agentId: 'agent-1',
+ draftType: 'draft',
+ versionId: 'draft-1',
+ workflow: {
+ appId: 'app-1',
+ nodeId: 'node-1',
},
},
})
- expect(await screen.findByRole('link', { name: 'common.operation.download' })).toHaveAttribute(
- 'href',
- 'https://signed.example/files/brief.md',
- )
- })
- it('should commit an uploaded file to the Agent App drive before adding it to the composer draft', async () => {
- const driveFiles = [
- {
- file_kind: 'file',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- mime_type: 'image/png',
- },
- {
- file_kind: 'file',
- key: 'files/brief.md',
- mime_type: 'text/markdown',
- },
- ]
- mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
- initialData: { items: [...driveFiles] },
- queryFn: async () => ({ items: [...driveFiles] }),
- }))
- mocks.agentFileCommitMutationOptions.mockReturnValue({
- mutationFn: mocks.agentFileCommitMutationFn.mockImplementation(async () => {
- driveFiles.push({
- file_kind: 'file',
- key: 'files/uploaded.md',
- mime_type: 'text/markdown',
- })
- return {
- file: {
- drive_key: 'files/uploaded.md',
- file_id: 'drive-file-1',
- mime_type: 'text/markdown',
- name: 'uploaded.md',
- },
- }
- }),
- mutationKey: ['commit-agent-file'],
- })
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
+ await user.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.files\.add/i }))
- render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={defaultAgentSoulConfigFormState}>
- <AgentFiles />
- <ConfigSnapshotProbe />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))
- const input = document.querySelector('input[type="file"]')
- expect(input).toBeInstanceOf(HTMLInputElement)
-
- fireEvent.change(input!, {
- target: {
- files: [new File(['# Uploaded'], 'uploaded.md', { type: 'text/markdown' })],
- },
+ const input = await waitFor(() => {
+ const element = document.querySelector('input[type="file"]')
+ expect(element).not.toBeNull()
+ return element as HTMLInputElement
})
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.upload.action' }))
+ const file = new File(['hello'], 'uploaded.md', { type: 'text/markdown' })
+ await user.upload(input, file)
+ await user.click(screen.getByRole('button', { name: /agentDetail\.configure\.files\.upload\.action/i }))
await waitFor(() => {
- expect(mocks.agentFileCommitMutationFn).toHaveBeenCalledWith(
- {
- params: {
- agent_id: 'agent-1',
- },
- body: {
- upload_file_id: 'upload-file-1',
- },
+ expect(mocks.commitFileMutationFn.mock.calls[0]?.[0]).toEqual({
+ params: {
+ app_id: 'app-1',
},
- expect.anything(),
- )
- })
- expect(await screen.findByRole('button', { name: 'uploaded.md' })).toBeInTheDocument()
- await waitFor(() => {
- const serializedConfig = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')
- expect(serializedConfig.files.files).toEqual([
- {
- id: 'drive-file-1',
- file_id: 'drive-file-1',
- name: 'uploaded.md',
- drive_key: 'files/uploaded.md',
+ query: {
+ draft_type: 'draft',
+ node_id: 'node-1',
+ version_id: 'draft-1',
},
- ])
- })
- })
-
- it('should upload a dropped file before committing it to the Agent App drive', async () => {
- renderAgentFiles({
- ...defaultAgentSoulConfigFormState,
- })
-
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))
-
- const uploadArea = screen.getByRole('group', { name: 'agentV2.agentDetail.configure.files.upload.title' })
- const file = new File(['# Uploaded'], 'uploaded.md', { type: 'text/markdown' })
- fireEvent.dragEnter(uploadArea, {
- dataTransfer: {
- files: [file],
- types: ['Files'],
- },
- })
- fireEvent.drop(uploadArea, {
- dataTransfer: {
- files: [file],
- types: ['Files'],
- },
- })
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.upload.action' }))
-
- await waitFor(() => {
- expect(mocks.uploadFileMutationFn).toHaveBeenCalledWith(
- {
- body: {
- file,
- },
+ body: {
+ upload_file_id: 'upload-1',
},
- expect.anything(),
- )
- })
- })
-
- it('should commit an uploaded file through workflow-node drive endpoints and refresh the list', async () => {
- const driveFiles = [
- {
- file_kind: 'file',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- mime_type: 'image/png',
- },
- {
- file_kind: 'file',
- key: 'files/brief.md',
- mime_type: 'text/markdown',
- },
- ]
- mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-drive-files', input],
- initialData: { items: [...driveFiles] },
- queryFn: async () => ({ items: [...driveFiles] }),
- }))
- mocks.workflowAgentFileCommitMutationOptions.mockReturnValue({
- mutationFn: mocks.workflowAgentFileCommitMutationFn.mockImplementation(async () => {
- driveFiles.push({
- file_kind: 'file',
- key: 'files/uploaded.md',
- mime_type: 'text/markdown',
- })
- return {
- file: {
- drive_key: 'files/uploaded.md',
- file_id: 'drive-file-1',
- mime_type: 'text/markdown',
- name: 'uploaded.md',
- },
- }
- }),
- mutationKey: ['commit-workflow-agent-file'],
- })
- renderWorkflowAgentFiles({
- ...defaultAgentSoulConfigFormState,
+ })
})
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))
- const input = document.querySelector('input[type="file"]')
- expect(input).toBeInstanceOf(HTMLInputElement)
-
- fireEvent.change(input!, {
- target: {
- files: [new File(['# Uploaded'], 'uploaded.md', { type: 'text/markdown' })],
- },
- })
- fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.upload.action' }))
+ await user.click(screen.getByText('diagram.png').closest('button')!)
await waitFor(() => {
- expect(mocks.workflowAgentFileCommitMutationFn).toHaveBeenCalledWith(
- {
+ expect(mocks.previewQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
params: {
app_id: 'app-1',
+ name: 'diagram.png',
},
query: {
+ draft_type: 'draft',
node_id: 'node-1',
+ version_id: 'draft-1',
},
- body: {
- upload_file_id: 'upload-file-1',
- },
- },
- expect.anything(),
- )
+ }),
+ }))
})
- expect(await screen.findByRole('button', { name: 'uploaded.md' })).toBeInTheDocument()
})
- // File rows expose a hover/focus remove action that updates the composer draft.
- it('should delete the file when the remove action is clicked', async () => {
- const driveFiles = [
- {
- file_kind: 'file',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- mime_type: 'image/png',
- },
- {
- file_kind: 'file',
- key: 'files/brief.md',
- mime_type: 'text/markdown',
- },
- ]
- mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
- initialData: { items: [...driveFiles] },
- queryFn: async () => ({ items: [...driveFiles] }),
- }))
- mocks.agentFileDeleteMutationOptions.mockReturnValue({
- mutationFn: mocks.agentFileDeleteMutationFn.mockImplementation(async () => {
- driveFiles.splice(0, 1)
- return { result: 'success' }
- }),
- mutationKey: ['delete-agent-file'],
- })
+ it('should preview and download files through config file endpoints by name', async () => {
+ const user = userEvent.setup()
renderAgentFiles()
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,
- }))
+ await user.click(screen.getByText('diagram.png').closest('button')!)
await waitFor(() => {
- expect(mocks.agentFileDeleteMutationFn).toHaveBeenCalledWith(
- {
+ expect(mocks.previewQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
params: {
agent_id: 'agent-1',
+ name: 'diagram.png',
},
- query: {
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- },
- },
- expect.anything(),
- )
- })
- await waitFor(() => {
- expect(screen.queryByRole('button', { name: 'agent-roster-skill-detail-dialog-preview-image.png' })).not.toBeInTheDocument()
+ }),
+ }))
})
- expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
- })
-
- it('should delete a workflow-node file through workflow endpoints and refresh the list', async () => {
- const driveFiles = [
- {
- file_kind: 'file',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
- mime_type: 'image/png',
- },
- {
- file_kind: 'file',
- key: 'files/brief.md',
- mime_type: 'text/markdown',
- },
- ]
- mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['workflow-agent-drive-files', input],
- initialData: { items: [...driveFiles] },
- queryFn: async () => ({ items: [...driveFiles] }),
- }))
- mocks.workflowAgentFileDeleteMutationOptions.mockReturnValue({
- mutationFn: mocks.workflowAgentFileDeleteMutationFn.mockImplementation(async () => {
- driveFiles.splice(0, 1)
- return { result: 'success' }
- }),
- mutationKey: ['delete-workflow-agent-file'],
- })
- renderWorkflowAgentFiles()
-
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,
- }))
await waitFor(() => {
- expect(mocks.workflowAgentFileDeleteMutationFn).toHaveBeenCalledWith(
- {
+ expect(mocks.downloadQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- key: 'files/agent-roster-skill-detail-dialog-preview-image.png',
+ agent_id: 'agent-1',
+ name: 'diagram.png',
},
- },
- expect.anything(),
- )
- })
- await waitFor(() => {
- expect(screen.queryByRole('button', { name: 'agent-roster-skill-detail-dialog-preview-image.png' })).not.toBeInTheDocument()
+ }),
+ }))
})
- expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
})
- it('should render the empty state when Agent Soul has no files', () => {
+ it('should show config note as a virtual build note file and preview its content locally', async () => {
+ const user = userEvent.setup()
renderAgentFiles({
- ...defaultAgentSoulConfigFormState,
+ initialOriginalConfig: {
+ config_note: 'Build context from the latest build chat.',
+ },
})
- expect(screen.getByText('agentV2.agentDetail.configure.files.empty.title')).toBeInTheDocument()
+ expect(screen.getByText('build_note.md')).toBeInTheDocument()
+ const fileNames = screen.getAllByText(/^(build_note\.md|diagram\.png|brief\.md)$/).map(element => element.textContent)
+ expect(fileNames).toEqual(['build_note.md', 'diagram.png', 'brief.md'])
+
+ vi.clearAllMocks()
+
+ await user.click(screen.getByText('build_note.md').closest('button')!)
+
+ expect(await screen.findByText('Build context from the latest build chat.')).toBeInTheDocument()
+ expect(mocks.previewQueryOptions).not.toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
+ params: expect.objectContaining({
+ name: 'build_note.md',
+ }),
+ }),
+ }))
+ expect(mocks.downloadQueryOptions).not.toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
+ params: expect.objectContaining({
+ name: 'build_note.md',
+ }),
+ }),
+ }))
})
- it('should hide add and remove actions when readonly', () => {
- renderReadonlyAgentFiles()
+ it('should keep flat config files visible without drive-prefix filtering and disable add in read-only mode', () => {
+ renderAgentFiles({ readOnly: true })
- expect(screen.getByRole('button', {
- name: 'agent-roster-skill-detail-dialog-preview-image.png',
- })).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.files.add' })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', {
- name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,
- })).not.toBeInTheDocument()
+ expect(screen.getByText('diagram.png')).toBeInTheDocument()
+ expect(screen.getByText('brief.md')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /agentV2\.agentDetail\.configure\.files\.add/i })).not.toBeInTheDocument()
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
index d8b5663c3bb..f60a1c8f0fd 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
@@ -2,7 +2,7 @@
import type { ReactNode } from 'react'
import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'
-import type { AgentDriveApiContext } from '../drive-context'
+import type { AgentConfigApiContext } from '../config-context'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
import {
Dialog,
@@ -15,6 +15,7 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useAtomValue, useSetAtom } from 'jotai'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { agentComposerOriginalConfigAtom } from '@/features/agent-v2/agent-composer/store'
import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
import { consoleQuery } from '@/service/client'
import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'
@@ -22,13 +23,28 @@ import { ConfigureSectionAddButton } from '../common/add-button'
import { ConfigureSectionEmpty } from '../common/empty'
import { ConfigureSection } from '../common/section'
import { AgentConfigureTipContent } from '../common/tip-content'
-import { FILES_DRIVE_PREFIX, useAgentDriveApiContext } from '../drive-context'
+import { useAgentConfigApiContext } from '../config-context'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
import { AgentSkillDetailDialog } from '../skills/detail-dialog'
import { AgentFileTree } from './tree'
import { AgentFileUploadDialog } from './upload-dialog'
-const getAgentFilePreviewKey = (file: AgentFileNode) => file.driveKey ?? file.id
+const BUILD_NOTE_FILE_ID = '__agent_config_build_note__'
+const BUILD_NOTE_FILE_NAME = 'build_note.md'
+
+const getAgentFilePreviewKey = (file: AgentFileNode) => file.configName ?? file.name
+
+const getBuildNoteFile = (configNote: string | undefined): AgentFileNode | undefined => {
+ if (!configNote?.trim())
+ return undefined
+
+ return {
+ id: BUILD_NOTE_FILE_ID,
+ icon: 'markdown',
+ name: BUILD_NOTE_FILE_NAME,
+ virtualContent: configNote,
+ }
+}
const findAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileNode | undefined => {
for (const file of files) {
@@ -64,7 +80,7 @@ function AgentFileItem({
depth: number
file: AgentFileNode
files: AgentFileNode[]
- apiContext: AgentDriveApiContext
+ apiContext: AgentConfigApiContext
onRemove: (fileId: string) => void
selected: boolean
}) {
@@ -73,60 +89,69 @@ function AgentFileItem({
const [isPreviewOpen, setIsPreviewOpen] = useState(false)
const [selectedFileId, setSelectedFileId] = useState<string>()
const selectedFile = selectedFileId ? findAgentFileNode(files, selectedFileId) : undefined
- const previewFileId = getAgentFilePreviewKey(selectedFile ?? file)
+ const selectedPreviewFile = selectedFile ?? file
+ const isVirtualPreviewFile = selectedPreviewFile.virtualContent !== undefined
+ const previewFileId = isVirtualPreviewFile ? undefined : getAgentFilePreviewKey(selectedPreviewFile)
const agentPreviewQuery = useQuery({
- ...consoleQuery.agent.byAgentId.drive.files.preview.get.queryOptions({
+ ...consoleQuery.agent.byAgentId.config.files.byName.preview.get.queryOptions({
input: {
params: {
agent_id: apiContext.agentId,
+ name: previewFileId ?? '',
},
query: {
- key: previewFileId ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled: isPreviewOpen && !!previewFileId && !apiContext.workflow,
+ enabled: isPreviewOpen && !!previewFileId && !isVirtualPreviewFile && !apiContext.workflow,
})
const workflowPreviewQuery = useQuery({
- ...consoleQuery.apps.byAppId.agent.drive.files.preview.get.queryOptions({
+ ...consoleQuery.apps.byAppId.agent.config.files.byName.preview.get.queryOptions({
input: {
params: {
app_id: apiContext.workflow?.appId ?? '',
+ name: previewFileId ?? '',
},
query: {
- key: previewFileId ?? '',
node_id: apiContext.workflow?.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled: isPreviewOpen && !!previewFileId && !!apiContext.workflow,
+ enabled: isPreviewOpen && !!previewFileId && !isVirtualPreviewFile && !!apiContext.workflow,
})
const previewQuery = apiContext.workflow ? workflowPreviewQuery : agentPreviewQuery
- const selectedPreviewFile = selectedFile ?? file
const isImagePreviewFile = selectedPreviewFile.icon === 'image'
- const shouldDownloadPreviewFile = isPreviewOpen && !!previewFileId && (isImagePreviewFile || !!previewQuery.data?.binary)
+ const shouldDownloadPreviewFile = isPreviewOpen && !!previewFileId && !isVirtualPreviewFile && (isImagePreviewFile || !!previewQuery.data?.binary)
const agentDownloadQuery = useQuery({
- ...consoleQuery.agent.byAgentId.drive.files.download.get.queryOptions({
+ ...consoleQuery.agent.byAgentId.config.files.byName.download.get.queryOptions({
input: {
params: {
agent_id: apiContext.agentId,
+ name: previewFileId ?? '',
},
query: {
- key: previewFileId ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
enabled: shouldDownloadPreviewFile && !apiContext.workflow,
})
const workflowDownloadQuery = useQuery({
- ...consoleQuery.apps.byAppId.agent.drive.files.download.get.queryOptions({
+ ...consoleQuery.apps.byAppId.agent.config.files.byName.download.get.queryOptions({
input: {
params: {
app_id: apiContext.workflow?.appId ?? '',
+ name: previewFileId ?? '',
},
query: {
- key: previewFileId ?? '',
node_id: apiContext.workflow?.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
@@ -169,14 +194,14 @@ function AgentFileItem({
files,
filePreview: {
binary: previewQuery.data?.binary,
- content: previewQuery.data?.text ?? undefined,
+ content: selectedPreviewFile.virtualContent ?? previewQuery.data?.text ?? undefined,
downloadUrl: downloadQuery.data?.url,
fileName: selectedPreviewFile.name,
isDownloadError: downloadQuery.isError,
isDownloadLoading: shouldDownloadPreviewFile && downloadQuery.isPending,
- isError: previewQuery.isError,
+ isError: !isVirtualPreviewFile && previewQuery.isError,
isImage: isImagePreviewFile,
- isLoading: previewQuery.isPending,
+ isLoading: !isVirtualPreviewFile && previewQuery.isPending,
},
onSelectFile: selectedFile => setSelectedFileId(selectedFile.id),
selectedFileId: selectedFileId ?? file.id,
@@ -184,7 +209,7 @@ function AgentFileItem({
}}
/>
</Dialog>
- {!readOnly && (
+ {!readOnly && !file.virtualContent && (
<button
type="button"
data-agent-file-remove-button
@@ -205,17 +230,19 @@ export function AgentFiles() {
const filesTreeId = 'agent-configure-files-tree'
const [isUploadOpen, setIsUploadOpen] = useState(false)
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
- const apiContext = useAgentDriveApiContext()
- const draftFiles = useAtomValue(agentComposerFilesAtom)
+ const apiContext = useAgentConfigApiContext()
+ const originalConfig = useAtomValue(agentComposerOriginalConfigAtom)
+ const files = useAtomValue(agentComposerFilesAtom)
const setFiles = useSetAtom(agentComposerFilesAtom)
- const files = draftFiles.filter(file => file.driveKey?.startsWith(FILES_DRIVE_PREFIX))
- const { mutate: deleteAgentFile } = useMutation(consoleQuery.agent.byAgentId.files.delete.mutationOptions())
- const { mutate: deleteWorkflowAgentFile } = useMutation(consoleQuery.apps.byAppId.agent.files.delete.mutationOptions())
+ const buildNoteFile = getBuildNoteFile(originalConfig?.config_note)
+ const visibleFiles = buildNoteFile ? [buildNoteFile, ...files] : files
+ const { mutate: deleteAgentFile } = useMutation(consoleQuery.agent.byAgentId.config.files.byName.delete.mutationOptions())
+ const { mutate: deleteWorkflowAgentFile } = useMutation(consoleQuery.apps.byAppId.agent.config.files.byName.delete.mutationOptions())
const removeFile = useCallback((fileId: string) => {
const file = findAgentFileNode(files, fileId)
- const driveKey = file?.driveKey
+ const configName = file?.configName ?? file?.name
- if (!driveKey)
+ if (!configName)
return
const onSuccess = () => {
@@ -225,10 +252,12 @@ export function AgentFiles() {
deleteWorkflowAgentFile({
params: {
app_id: apiContext.workflow.appId,
+ name: configName,
},
query: {
- key: driveKey,
node_id: apiContext.workflow.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
}, { onSuccess })
return
@@ -237,9 +266,11 @@ export function AgentFiles() {
deleteAgentFile({
params: {
agent_id: apiContext.agentId,
+ name: configName,
},
query: {
- key: driveKey,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
}, { onSuccess })
}, [apiContext, deleteAgentFile, deleteWorkflowAgentFile, files, setFiles])
@@ -267,6 +298,7 @@ export function AgentFiles() {
<ConfigureSection
label={t('agentDetail.configure.files.label')}
labelId="agent-configure-files-label"
+ buildDraftChangeSection="files"
tip={<AgentConfigureTipContent type="files" />}
tipAriaLabel={filesTip}
rootClassName="border-b border-divider-subtle pt-4"
@@ -278,7 +310,7 @@ export function AgentFiles() {
/>
)}
>
- {files.length === 0
+ {visibleFiles.length === 0
? (
<ConfigureSectionEmpty
title={t('agentDetail.configure.files.empty.title')}
@@ -288,7 +320,7 @@ export function AgentFiles() {
: (
<AgentFileTree
id={filesTreeId}
- files={files}
+ files={visibleFiles}
treeLabel={t('agentDetail.configure.files.treeLabel')}
className="rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-1 shadow-xs shadow-shadow-shadow-3"
scrollAreaClassName="max-h-[250px] flex-none"
@@ -296,7 +328,7 @@ export function AgentFiles() {
<AgentFileItem
depth={depth}
file={file}
- files={files}
+ files={visibleFiles}
apiContext={apiContext}
selected={selected}
onRemove={removeFile}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx
index 6732d5a180b..6950191e457 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx
@@ -28,6 +28,21 @@ type AgentFileTreeRenderFile = (context: {
children: ReactNode
}) => ReactNode
+type AgentFileTreeRenderFolderPanel = (context: {
+ depth: number
+ file: AgentFileNode
+}) => ReactNode
+
+type AgentFileTreeRenderFolderSuffix = (context: {
+ depth: number
+ file: AgentFileNode
+}) => ReactNode
+
+type AgentFileTreeFolderOpenState = (context: {
+ file: AgentFileNode
+ depth: number
+}) => boolean
+
const firstLevelFolderOpenStrategy: AgentFileTreeFolderOpenStrategy = ({ depth }) => depth === 1
function AgentFileTreeRows({
@@ -35,13 +50,23 @@ function AgentFileTreeRows({
selectedFileId,
depth,
folderOpenStrategy,
+ folderOpenState,
+ onFolderOpenChange,
+ onFolderOpen,
renderFile,
+ renderFolderSuffix,
+ renderFolderPanel,
}: {
files: AgentFileNode[]
selectedFileId?: string
depth: number
folderOpenStrategy: AgentFileTreeFolderOpenStrategy
+ folderOpenState?: AgentFileTreeFolderOpenState
+ onFolderOpenChange?: (context: { file: AgentFileNode, depth: number, open: boolean }) => void
+ onFolderOpen?: (file: AgentFileNode) => void
renderFile: AgentFileTreeRenderFile
+ renderFolderSuffix?: AgentFileTreeRenderFolderSuffix
+ renderFolderPanel?: AgentFileTreeRenderFolderPanel
}) {
return files.map((file) => {
const children = (
@@ -51,23 +76,32 @@ function AgentFileTreeRows({
</>
)
- if (file.children?.length) {
+ if (file.icon === 'folder') {
return (
<FileTreeFolder
key={file.id}
defaultOpen={folderOpenStrategy({ file, depth })}
+ open={folderOpenState?.({ file, depth })}
+ onOpenChange={open => onFolderOpenChange?.({ file, depth, open })}
>
- <FileTreeFolderTrigger>
+ <FileTreeFolderTrigger onClick={() => onFolderOpen?.(file)}>
<FileTreeIcon type="folder" />
<FileTreeLabel className="max-w-full" title={file.name}>{file.name}</FileTreeLabel>
+ {renderFolderSuffix?.({ depth, file })}
</FileTreeFolderTrigger>
<FileTreeFolderPanel>
+ {renderFolderPanel?.({ depth, file })}
<AgentFileTreeRows
- files={file.children}
+ files={file.children ?? []}
selectedFileId={selectedFileId}
depth={depth + 1}
folderOpenStrategy={folderOpenStrategy}
+ folderOpenState={folderOpenState}
+ onFolderOpenChange={onFolderOpenChange}
+ onFolderOpen={onFolderOpen}
renderFile={renderFile}
+ renderFolderSuffix={renderFolderSuffix}
+ renderFolderPanel={renderFolderPanel}
/>
</FileTreeFolderPanel>
</FileTreeFolder>
@@ -106,7 +140,12 @@ export function AgentFileTree({
rootClassName,
listClassName,
folderOpenStrategy = firstLevelFolderOpenStrategy,
+ folderOpenState,
+ onFolderOpenChange,
+ onFolderOpen,
renderFile = defaultRenderFile,
+ renderFolderSuffix,
+ renderFolderPanel,
}: {
files: AgentFileNode[]
selectedFileId?: string
@@ -120,7 +159,12 @@ export function AgentFileTree({
rootClassName?: string
listClassName?: string
folderOpenStrategy?: AgentFileTreeFolderOpenStrategy
+ folderOpenState?: AgentFileTreeFolderOpenState
+ onFolderOpenChange?: (context: { file: AgentFileNode, depth: number, open: boolean }) => void
+ onFolderOpen?: (file: AgentFileNode) => void
renderFile?: AgentFileTreeRenderFile
+ renderFolderSuffix?: AgentFileTreeRenderFolderSuffix
+ renderFolderPanel?: AgentFileTreeRenderFolderPanel
}) {
return (
<div className={cn('flex min-h-0 w-full max-w-full min-w-0 flex-col overflow-clip', className)}>
@@ -146,7 +190,12 @@ export function AgentFileTree({
selectedFileId={selectedFileId}
depth={1}
folderOpenStrategy={folderOpenStrategy}
+ folderOpenState={folderOpenState}
+ onFolderOpenChange={onFolderOpenChange}
+ onFolderOpen={onFolderOpen}
renderFile={renderFile}
+ renderFolderSuffix={renderFolderSuffix}
+ renderFolderPanel={renderFolderPanel}
/>
</FileTreeList>
</FileTreeRoot>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
index cb91d28a633..f499ead02de 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
@@ -1,8 +1,9 @@
'use client'
+import type { AgentConfigFileItemResponse, AgentConfigFileUploadResponse } from '@dify/contracts/api/console/agent/types.gen'
import type { FileResponse } from '@dify/contracts/api/console/files/types.gen'
import type { ChangeEvent, DragEvent } from 'react'
-import type { AgentDriveApiContext } from '../drive-context'
+import type { AgentConfigApiContext } from '../config-context'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -17,22 +18,16 @@ import { consoleQuery } from '@/service/client'
import { formatFileSize } from '@/utils/format'
import { getFileIconType } from './file-icon'
-type AgentDriveFileCommit = {
- file: {
- drive_key: string
- file_id: string
- mime_type?: string | null
- name: string
- }
-}
-
-function toAgentFileNode(committedFile: AgentDriveFileCommit['file']): AgentFileNode {
+function toAgentFileNode(committedFile: AgentConfigFileItemResponse): AgentFileNode {
return {
- id: committedFile.file_id,
+ id: committedFile.name,
name: committedFile.name,
icon: getFileIconType(committedFile.name, committedFile.mime_type),
- fileId: committedFile.file_id,
- driveKey: committedFile.drive_key,
+ fileId: committedFile.file_id ?? undefined,
+ configName: committedFile.name,
+ size: committedFile.size ?? undefined,
+ hash: committedFile.hash ?? undefined,
+ mimeType: committedFile.mime_type ?? undefined,
}
}
@@ -178,7 +173,7 @@ export function AgentFileUploadDialog({
onOpenChange,
onUploaded,
}: {
- apiContext: AgentDriveApiContext
+ apiContext: AgentConfigApiContext
open: boolean
onOpenChange: (open: boolean) => void
onUploaded: (file: AgentFileNode) => void
@@ -187,14 +182,14 @@ export function AgentFileUploadDialog({
const { t: tCommon } = useTranslation('common')
const [file, setFile] = useState<File>()
const uploadFileMutation = useMutation(consoleQuery.files.upload.post.mutationOptions())
- const commitAgentFileMutation = useMutation(consoleQuery.agent.byAgentId.files.post.mutationOptions())
- const commitWorkflowAgentFileMutation = useMutation(consoleQuery.apps.byAppId.agent.files.post.mutationOptions())
+ const commitAgentFileMutation = useMutation(consoleQuery.agent.byAgentId.config.files.post.mutationOptions())
+ const commitWorkflowAgentFileMutation = useMutation(consoleQuery.apps.byAppId.agent.config.files.post.mutationOptions())
const isUploading = uploadFileMutation.isPending
|| commitAgentFileMutation.isPending
|| commitWorkflowAgentFileMutation.isPending
const commitUploadedFile = (uploadedFile: FileResponse, options: {
- onSuccess: (committedFile: AgentDriveFileCommit) => void
+ onSuccess: (committedFile: AgentConfigFileUploadResponse) => void
onError: () => void
}) => {
const body = {
@@ -208,6 +203,8 @@ export function AgentFileUploadDialog({
},
query: {
node_id: apiContext.workflow.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
body,
}, options)
@@ -218,6 +215,10 @@ export function AgentFileUploadDialog({
params: {
agent_id: apiContext.agentId,
},
+ query: {
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
+ },
body,
}, options)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx
index f79f475dba8..faf9e57bc55 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx
@@ -2,7 +2,9 @@
import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
import type { ReactNode } from 'react'
-import type { DefaultModel, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { AgentBuildDraftChangedKey } from './build-draft-changes-context'
+import type { Model } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { AgentComposerModel } from '@/features/agent-v2/agent-composer/form-state'
import { cn } from '@langgenius/dify-ui/cn'
import { ScrollArea } from '@langgenius/dify-ui/scroll-area'
import { useMemo } from 'react'
@@ -10,7 +12,8 @@ import { useTranslation } from 'react-i18next'
import { AgentOrchestrateAddActionsProvider } from './add-actions'
import { AgentAdvancedSettings } from './advanced'
import { AgentOrchestrateBottomActions } from './bottom-actions'
-import { AgentDriveApiContextProvider } from './drive-context'
+import { AgentBuildDraftChangedKeysProvider } from './build-draft-changes-context'
+import { AgentConfigApiContextProvider } from './config-context'
import { AgentFiles } from './files'
import { AgentOrchestrateHeader } from './header'
import { AgentKnowledgeRetrieval } from './knowledge'
@@ -21,6 +24,8 @@ import { AgentOrchestrateReadOnlyContext } from './read-only-context'
import { AgentSkills } from './skills'
import { AgentTools } from './tools'
+const EMPTY_BUILD_DRAFT_CHANGED_KEYS: readonly AgentBuildDraftChangedKey[] = []
+
type AgentOrchestratePanelProps = {
agentId: string
appId?: string
@@ -29,7 +34,7 @@ type AgentOrchestratePanelProps = {
activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
agentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']
agentName?: string | null
- currentModel?: DefaultModel
+ currentModel?: AgentComposerModel
textGenerationModelList: Model[]
draftSavedAt?: number
isPublishing?: boolean
@@ -37,14 +42,15 @@ type AgentOrchestratePanelProps = {
readOnly?: boolean
selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | null
isBuildDraftActive?: boolean
+ buildDraftChangedKeys?: readonly AgentBuildDraftChangedKey[]
showHeader?: boolean
showPublishBar?: boolean
headerAction?: ReactNode
bottomAction?: ReactNode
- onSelectModel: (model: DefaultModel) => void
- onPublish: () => void | Promise<void>
+ onSelectModel: (model: AgentComposerModel) => void
+ onPublish?: () => void | Promise<void>
onExitVersions?: () => void
- onOpenVersions: () => void
+ onOpenVersions?: () => void
}
export function AgentOrchestratePanel({
@@ -63,6 +69,7 @@ export function AgentOrchestratePanel({
readOnly = false,
selectedVersionSnapshot,
isBuildDraftActive = false,
+ buildDraftChangedKeys = [],
showHeader = true,
showPublishBar = true,
headerAction,
@@ -92,15 +99,22 @@ export function AgentOrchestratePanel({
)
: null)
const hasBottomAction = !!orchestrateBottomAction
- const driveApiContext = useMemo(() => appId && nodeId
+ const draftType = isBuildDraftActive ? ('debug_build' as const) : ('draft' as const)
+ const configApiContext = useMemo(() => appId && nodeId
? {
agentId,
+ draftType,
+ versionId: selectedVersionSnapshot?.id ?? undefined,
workflow: {
appId,
nodeId,
},
}
- : { agentId }, [agentId, appId, nodeId])
+ : {
+ agentId,
+ draftType,
+ versionId: selectedVersionSnapshot?.id ?? undefined,
+ }, [agentId, appId, draftType, nodeId, selectedVersionSnapshot?.id])
return (
<div className={cn('relative flex max-w-140 min-w-90 flex-[0_0_min(41.08280255%,560px)] flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg', className)}>
@@ -121,21 +135,23 @@ export function AgentOrchestratePanel({
scrollbar: hasBottomAction ? 'z-20' : undefined,
}}
>
- <AgentDriveApiContextProvider value={driveApiContext}>
+ <AgentConfigApiContextProvider value={configApiContext}>
<AgentOrchestrateAddActionsProvider>
- <AgentModelField
- currentModel={currentModel}
- textGenerationModelList={textGenerationModelList}
- onSelect={onSelectModel}
- />
- <AgentPromptEditor />
- <AgentSkills />
- <AgentFiles />
- <AgentTools />
- <AgentKnowledgeRetrieval />
- <AgentAdvancedSettings />
+ <AgentBuildDraftChangedKeysProvider changedKeys={isBuildDraftActive ? buildDraftChangedKeys : EMPTY_BUILD_DRAFT_CHANGED_KEYS}>
+ <AgentModelField
+ currentModel={currentModel}
+ textGenerationModelList={textGenerationModelList}
+ onSelect={onSelectModel}
+ />
+ <AgentPromptEditor />
+ <AgentSkills />
+ <AgentFiles />
+ <AgentTools />
+ <AgentKnowledgeRetrieval />
+ <AgentAdvancedSettings />
+ </AgentBuildDraftChangedKeysProvider>
</AgentOrchestrateAddActionsProvider>
- </AgentDriveApiContextProvider>
+ </AgentConfigApiContextProvider>
</ScrollArea>
</div>
</AgentOrchestrateReadOnlyContext>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx
index f2434667119..58892224a8a 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx
@@ -11,6 +11,24 @@ import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentKnowledgeRetrieval } from '../index'
+vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset', () => ({
+ default: function MockAddKnowledge({
+ onChange,
+ }: {
+ onChange: (datasets: Array<{ id: string, name: string }>) => void
+ }) {
+ return (
+ <button
+ type="button"
+ aria-label="common.operation.add workflow.nodes.knowledgeRetrieval.knowledge"
+ onClick={() => onChange([{ id: 'dataset-2', name: 'Release Docs' }])}
+ >
+ Add mock knowledge
+ </button>
+ )
+ },
+}))
+
const agentKnowledgeDraft = {
...defaultAgentSoulConfigFormState,
knowledgeRetrievals: [
@@ -136,6 +154,9 @@ describe('AgentKnowledgeRetrieval', () => {
expect(within(dialog).getByRole('button', {
name: 'workflow.nodes.knowledgeRetrieval.metadata.options.disabled.title',
})).toBeInTheDocument()
+ expect(screen.queryByRole('button', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo"}',
+ })).not.toBeInTheDocument()
})
it('should show the custom query input when query mode changes', async () => {
@@ -162,7 +183,24 @@ describe('AgentKnowledgeRetrieval', () => {
expect(within(dialog).queryByText('agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription')).not.toBeInTheDocument()
})
- it('should show inline validation for missing datasets and blank custom queries', async () => {
+ it('should not create a new retrieval until knowledge is selected', async () => {
+ const user = userEvent.setup()
+ renderKnowledgeRetrieval()
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))
+
+ expect(screen.queryByRole('button', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo"}',
+ })).not.toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+
+ expect(screen.queryByRole('button', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo"}',
+ })).not.toBeInTheDocument()
+ })
+
+ it('should show inline validation for blank custom queries after knowledge is selected', async () => {
const user = userEvent.setup()
renderKnowledgeRetrieval()
@@ -171,7 +209,9 @@ describe('AgentKnowledgeRetrieval', () => {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',
})
- expect(within(dialog).getByText('common.errorMsg.fieldRequired:{"field":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label"}')).toBeInTheDocument()
+ await user.click(within(dialog).getByRole('button', {
+ name: 'common.operation.add workflow.nodes.knowledgeRetrieval.knowledge',
+ }))
await user.click(within(dialog).getByRole('radio', {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.custom',
@@ -240,6 +280,9 @@ describe('AgentKnowledgeRetrieval', () => {
await user.type(within(dialog).getByRole('textbox', {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',
}), 'new release notes')
+ await user.click(within(dialog).getByRole('button', {
+ name: 'common.operation.add workflow.nodes.knowledgeRetrieval.knowledge',
+ }))
const knowledgeConfig = JSON.parse(screen.getByLabelText('config snapshot').textContent ?? '{}')
expect(knowledgeConfig.sets).toEqual(expect.arrayContaining([
@@ -253,7 +296,12 @@ describe('AgentKnowledgeRetrieval', () => {
}),
expect.objectContaining({
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo',
- datasets: [],
+ datasets: [
+ expect.objectContaining({
+ id: 'dataset-2',
+ name: 'Release Docs',
+ }),
+ ],
query: {
mode: 'user_query',
value: 'new release notes',
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
index 0b8529617fe..d809521336b 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
@@ -218,12 +218,14 @@ const createMetadataCondition = ({ id, name, type }: MetadataInDoc): MetadataFil
export function AgentKnowledgeRetrievalDialog({
item,
initialName,
+ onItemCreate,
onItemChange,
open,
onOpenChange,
}: {
item?: AgentKnowledgeRetrievalItem
initialName?: string
+ onItemCreate?: (item: AgentKnowledgeRetrievalItem) => void
onItemChange?: (item: AgentKnowledgeRetrievalItem) => void
open: boolean
onOpenChange: (open: boolean) => void
@@ -294,6 +296,20 @@ export function AgentKnowledgeRetrievalDialog({
}
})
}
+ const createItemFromDialogState = (patch: Partial<AgentKnowledgeRetrievalItem>): AgentKnowledgeRetrievalItem => ({
+ id: globalThis.crypto?.randomUUID?.() ?? `retrieval-${Date.now()}`,
+ name,
+ queryMode,
+ customQuery,
+ selectedDatasets,
+ retrievalMode,
+ multipleRetrievalConfig,
+ singleRetrievalConfig,
+ metadataFilterMode,
+ metadataFilteringConditions,
+ metadataModelConfig,
+ ...patch,
+ })
const updateItem = (patch: Partial<AgentKnowledgeRetrievalItem>) => {
if (!item)
return
@@ -313,6 +329,17 @@ export function AgentKnowledgeRetrievalDialog({
...patch,
})
}
+ const handleSelectedDatasetsChange = (nextDatasets: DataSet[]) => {
+ patchDialogState({ selectedDatasets: nextDatasets })
+
+ if (item) {
+ updateItem({ selectedDatasets: nextDatasets })
+ return
+ }
+
+ if (nextDatasets.length > 0)
+ onItemCreate?.(createItemFromDialogState({ selectedDatasets: nextDatasets }))
+ }
const metadataList = useMemo(() => {
const datasetsWithMetadata = selectedDatasets.filter(dataset => !!dataset.doc_metadata)
@@ -523,10 +550,7 @@ export function AgentKnowledgeRetrievalDialog({
<AddKnowledge
selectedIds={selectedDatasets.map(dataset => dataset.id)}
modal
- onChange={(nextDatasets) => {
- patchDialogState({ selectedDatasets: nextDatasets })
- updateItem({ selectedDatasets: nextDatasets })
- }}
+ onChange={handleSelectedDatasetsChange}
/>
</div>
)}
@@ -534,10 +558,7 @@ export function AgentKnowledgeRetrievalDialog({
<>
<DatasetList
list={selectedDatasets}
- onChange={(nextDatasets) => {
- patchDialogState({ selectedDatasets: nextDatasets })
- updateItem({ selectedDatasets: nextDatasets })
- }}
+ onChange={handleSelectedDatasetsChange}
settingsDrawerBackdropClassName="bg-background-overlay"
settingsDrawerBackdropForceRender
settingsDrawerPopupClassName="data-[swipe-direction=right]:top-6 data-[swipe-direction=right]:bottom-6"
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
index a51945bdbf5..1fd3b4d5508 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
@@ -3,7 +3,7 @@
import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'
import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-composer/form-state'
import { useAtom } from 'jotai'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'
@@ -49,7 +49,9 @@ export function AgentKnowledgeRetrieval() {
const { t } = useTranslation('agentV2')
const [retrievals, setRetrievals] = useAtom(agentComposerKnowledgeRetrievalsAtom)
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
+ const [addDialogName, setAddDialogName] = useState<string>()
const [editingRetrieval, setEditingRetrieval] = useState<AgentKnowledgeRetrievalItem | null>(null)
+ const addOptionsRef = useRef<AgentOrchestrateAddActionOptions | undefined>(undefined)
const knowledgeRetrievalTip = t('agentDetail.configure.knowledgeRetrieval.tip')
const retrievalListId = 'agent-configure-knowledge-retrieval-list'
const isDialogOpen = isAddDialogOpen || !!editingRetrieval
@@ -66,16 +68,16 @@ export function AgentKnowledgeRetrieval() {
return t('agentDetail.configure.knowledgeRetrieval.defaultName', { index })
}
const addRetrieval = (options?: AgentOrchestrateAddActionOptions) => {
- const nextRetrieval: AgentKnowledgeRetrievalItem = {
- id: globalThis.crypto?.randomUUID?.() ?? `retrieval-${Date.now()}`,
- name: getDefaultRetrievalName(retrievals.length + 1),
- queryMode: 'agent',
- }
-
- setRetrievals([...retrievals, nextRetrieval])
- setEditingRetrieval(nextRetrieval)
+ addOptionsRef.current = options
+ setAddDialogName(getDefaultRetrievalName(retrievals.length + 1))
setIsAddDialogOpen(true)
- options?.onAdded?.(nextRetrieval)
+ }
+ const createRetrieval = (nextRetrieval: AgentKnowledgeRetrievalItem) => {
+ setRetrievals(current => [...current, nextRetrieval])
+ setEditingRetrieval(nextRetrieval)
+ setIsAddDialogOpen(false)
+ addOptionsRef.current?.onAdded?.(nextRetrieval)
+ addOptionsRef.current = undefined
}
useRegisterAgentOrchestrateAddAction('knowledge', addRetrieval)
@@ -114,13 +116,16 @@ export function AgentKnowledgeRetrieval() {
</ConfigureSection>
<AgentKnowledgeRetrievalDialog
item={editingRetrieval ?? undefined}
- initialName={editingRetrieval ? (editingRetrieval.name ?? (editingRetrieval.nameKey ? t(editingRetrieval.nameKey) : editingRetrieval.id)) : undefined}
+ initialName={editingRetrieval ? (editingRetrieval.name ?? (editingRetrieval.nameKey ? t(editingRetrieval.nameKey) : editingRetrieval.id)) : addDialogName}
+ onItemCreate={createRetrieval}
onItemChange={updateRetrieval}
open={isDialogOpen}
onOpenChange={(open) => {
setIsAddDialogOpen(open)
- if (!open)
+ if (!open) {
setEditingRetrieval(null)
+ addOptionsRef.current = undefined
+ }
}}
/>
</>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
index a8c7697930e..3a937a9bc66 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
@@ -1,15 +1,19 @@
'use client'
-import type { DefaultModel, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { FormValue, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { AgentComposerModel } from '@/features/agent-v2/agent-composer/form-state'
import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useTranslation } from 'react-i18next'
+import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'
+import { isAgentCompatibleModel } from '../../../model-compatibility'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
type AgentModelFieldProps = {
- currentModel?: DefaultModel
+ currentModel?: AgentComposerModel
textGenerationModelList: Model[]
- onSelect: (model: DefaultModel) => void
+ onSelect: (model: AgentComposerModel) => void
}
export function AgentModelField({
@@ -18,7 +22,9 @@ export function AgentModelField({
onSelect,
}: AgentModelFieldProps) {
const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
const readOnly = useAgentOrchestrateReadOnly()
+ const canConfigureModelSettings = !readOnly && !!currentModel?.provider && !!currentModel.model
return (
<FieldRoot name="model" className="gap-1 pb-4">
@@ -33,20 +39,61 @@ export function AgentModelField({
</div>
)
: (
- <>
+ <div className="flex h-8 min-w-0 items-center gap-px overflow-hidden rounded-lg">
<ModelSelector
defaultModel={currentModel}
modelList={textGenerationModelList}
- triggerClassName="h-8! w-full rounded-lg! pr-10! [&_.i-ri-arrow-down-s-line]:hidden"
+ triggerClassName="h-8! w-full rounded-r-none! [&_.i-ri-arrow-down-s-line]:hidden"
popupClassName="w-(--anchor-width) max-w-[min(var(--anchor-width),var(--available-width),calc(100vw-32px))]"
providerSettingsSource="agent"
showModelMeta={false}
+ modelPredicate={isAgentCompatibleModel}
onSelect={onSelect}
/>
- <div className="pointer-events-none absolute inset-y-0 right-0 flex w-8 items-center justify-center rounded-r-lg bg-components-button-tertiary-bg">
- <span aria-hidden="true" className="i-ri-equalizer-2-line size-4 text-text-tertiary" />
+ <div className="w-8 shrink-0">
+ <ModelParameterModal
+ isAdvancedMode
+ modelId={currentModel?.model ?? ''}
+ provider={currentModel?.provider ?? ''}
+ completionParams={(currentModel?.model_settings ?? {}) as FormValue}
+ readonly={!canConfigureModelSettings}
+ hideDebugWithMultipleModel
+ popupClassName="w-[400px]"
+ setModel={({ modelId, provider }) => {
+ onSelect({
+ ...currentModel,
+ provider,
+ model: modelId,
+ })
+ }}
+ onCompletionParamsChange={(modelSettings) => {
+ if (!currentModel)
+ return
+
+ onSelect({
+ ...currentModel,
+ model_settings: modelSettings,
+ })
+ }}
+ renderTrigger={() => (
+ <Tooltip>
+ <TooltipTrigger
+ disabled={!canConfigureModelSettings}
+ render={(
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-l-none rounded-r-lg bg-components-button-tertiary-bg text-text-tertiary hover:bg-components-button-tertiary-bg-hover hover:text-text-secondary aria-disabled:cursor-not-allowed aria-disabled:text-text-disabled">
+ <span className="sr-only">{tCommon('modelProvider.modelSettings')}</span>
+ <span className="i-ri-equalizer-2-line size-4" />
+ </span>
+ )}
+ />
+ <TooltipContent placement="top">
+ {tCommon('modelProvider.modelSettings')}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ />
</div>
- </>
+ </div>
)}
</div>
</FieldRoot>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
index 332f2c9300f..2f6f818b95a 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
@@ -3,14 +3,14 @@
import type { KeyboardEvent, MouseEvent, PointerEvent as ReactPointerEvent } from 'react'
import type { SlashMenuCategory, SlashMenuView } from './slash'
import type { RosterReferenceToken } from '@/app/components/base/prompt-editor/plugins/roster-reference-block/utils'
-import type { AgentProviderTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'
+import type { AgentFileNode, AgentProviderTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'
import { cn } from '@langgenius/dify-ui/cn'
import { Kbd } from '@langgenius/dify-ui/kbd'
import { toast } from '@langgenius/dify-ui/toast'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useClipboard } from 'foxact/use-clipboard'
import { useAtom, useAtomValue } from 'jotai'
-import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import { useTranslation } from 'react-i18next'
import { Infotip } from '@/app/components/base/infotip'
import PromptEditor from '@/app/components/base/prompt-editor'
@@ -22,7 +22,7 @@ import { agentComposerToolsAtom } from '@/features/agent-v2/agent-composer/store
import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import { useAgentOrchestrateAddActions } from '../add-actions-context'
import { AgentConfigureTipContent } from '../common/tip-content'
-import { useAgentDriveFiles, useAgentDriveSkills } from '../drive-context'
+import { useAgentConfigFiles, useAgentConfigSkills } from '../config-context'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
import { useAgentPromptToolIconResolver } from './hooks'
import { replaceTrailingSlashWithToken } from './options'
@@ -63,12 +63,17 @@ function getProviderToolFromToken(token: RosterReferenceToken, tools: AgentTool[
return tools.find(tool =>
tool.kind === 'provider'
&& (
- token.id === `${tool.id}/*`
+ token.id === tool.id
+ || token.id === `${tool.id}/*`
|| tool.actions.some(action => token.id === `${tool.id}/${action.toolName}`)
),
)
}
+const flattenFileNodes = (files: AgentFileNode[]): AgentFileNode[] => files.flatMap(file => (
+ file.children?.length ? flattenFileNodes(file.children) : [file]
+))
+
function AgentPromptRosterReferenceIcon({
token,
tools,
@@ -151,8 +156,8 @@ export function AgentPromptEditor() {
const { t } = useTranslation('agentV2')
const readOnly = useAgentOrchestrateReadOnly()
const [value, setValue] = useAtom(agentComposerPromptAtom)
- const { skills } = useAgentDriveSkills()
- const { files } = useAgentDriveFiles()
+ const { skills } = useAgentConfigSkills()
+ const { files } = useAgentConfigFiles()
const [tools, setTools] = useAtom(agentComposerToolsAtom)
const { getConfiguredToolIcon } = useAgentPromptToolIconResolver()
const retrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)
@@ -165,7 +170,8 @@ export function AgentPromptEditor() {
insertLabel={t('agentDetail.configure.prompt.insert.label').toLocaleLowerCase()}
/>
)
- const { copied, copy, reset } = useClipboard({
+ const { copied, copy } = useClipboard({
+ timeout: 2000,
onCopyError: () => {
toast.error(t('agentDetail.configure.prompt.copyFailed'))
},
@@ -174,6 +180,34 @@ export function AgentPromptEditor() {
const [isSlashMenuOpen, setIsSlashMenuOpen] = useState(false)
const rootRef = useRef<HTMLDivElement>(null)
const editorRef = useRef<HTMLDivElement>(null)
+ const configuredReferenceIds = useMemo(() => {
+ const skillIds = new Set<string>()
+ skills.forEach((skill) => {
+ skillIds.add(skill.id)
+ skillIds.add(encodeURIComponent(skill.id))
+ if (skill.skillMdKey) {
+ skillIds.add(skill.skillMdKey)
+ skillIds.add(encodeURIComponent(skill.skillMdKey))
+ }
+ })
+
+ const fileIds = new Set<string>()
+ flattenFileNodes(files).forEach((file) => {
+ fileIds.add(file.id)
+ fileIds.add(encodeURIComponent(file.id))
+ if (file.driveKey) {
+ fileIds.add(file.driveKey)
+ fileIds.add(encodeURIComponent(file.driveKey))
+ }
+ })
+
+ return {
+ skills: skillIds,
+ files: fileIds,
+ knowledge: new Set(retrievals.map(retrieval => retrieval.id)),
+ cliTools: new Set(tools.flatMap(tool => tool.kind === 'cli' ? [tool.id] : [])),
+ }
+ }, [files, retrievals, skills, tools])
const handleCopyPrompt = useCallback(() => {
void copy(value)
@@ -269,6 +303,9 @@ export function AgentPromptEditor() {
if (token.kind !== 'tool' && token.kind !== 'tool-all' && token.kind !== 'cli_tool')
return null
+ if ((token.kind === 'tool' || token.kind === 'tool-all') && !getProviderToolFromToken(token, tools))
+ return null
+
return (
<AgentPromptRosterReferenceIcon
token={token}
@@ -278,6 +315,25 @@ export function AgentPromptEditor() {
)
}, [getConfiguredToolIcon, tools])
+ const getRosterReferenceWarning = useCallback((token: RosterReferenceToken) => {
+ const warning = t('agentDetail.configure.prompt.referenceMissing', { name: token.label })
+
+ if (token.kind === 'skill')
+ return configuredReferenceIds.skills.has(token.id) ? undefined : warning
+
+ if (token.kind === 'file')
+ return configuredReferenceIds.files.has(token.id) ? undefined : warning
+
+ if (token.kind === 'knowledge')
+ return configuredReferenceIds.knowledge.has(token.id) ? undefined : warning
+
+ if (token.kind === 'cli_tool')
+ return ENABLE_AGENT_CLI_TOOLS && configuredReferenceIds.cliTools.has(token.id) ? undefined : warning
+
+ if (token.kind === 'tool' || token.kind === 'tool-all')
+ return getProviderToolFromToken(token, tools) ? undefined : warning
+ }, [configuredReferenceIds, t, tools])
+
useEffect(() => {
if (!isSlashMenuOpen)
return
@@ -342,7 +398,6 @@ export function AgentPromptEditor() {
aria-label={copied ? t('agentDetail.configure.prompt.copied') : t('agentDetail.configure.prompt.copy')}
className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
onClick={handleCopyPrompt}
- onMouseLeave={reset}
>
<span aria-hidden className={copied ? 'i-ri-check-line size-4' : 'i-ri-clipboard-line size-4'} />
</button>
@@ -382,6 +437,7 @@ export function AgentPromptEditor() {
rosterReferenceBlock={{
show: true,
renderIcon: renderRosterReferenceIcon,
+ getWarning: getRosterReferenceWarning,
}}
disableSlashPicker
disableBracePicker
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
index fe06ac81533..41bd5254582 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
@@ -57,14 +57,18 @@ const createReferenceToken = (kind: string, id: string, label?: string) => (
`[§${kind}:${id}${label ? `:${label}` : ''}§]`
)
-const createDriveReferenceToken = (kind: 'skill' | 'file', driveKey: string, label: string) => (
- createReferenceToken(kind, encodeURIComponent(driveKey), label)
+const createConfigReferenceToken = (kind: 'skill' | 'file', name: string, label: string) => (
+ createReferenceToken(kind, name, label)
)
const isPromptReferenceItem = (item: AgentOrchestrateAddedItem): item is AgentFileNode | AgentSkill => (
'id' in item && 'name' in item
)
+const isAgentFileNode = (item: AgentOrchestrateAddedItem): item is AgentFileNode => (
+ 'icon' in item
+)
+
const isCliToolItem = (item: AgentOrchestrateAddedItem): item is Extract<AgentTool, { kind: 'cli' }> => (
'kind' in item && item.kind === 'cli'
)
@@ -95,8 +99,8 @@ export function AgentPromptSlashMenu({
if (view === 'skills') {
onAddSkill?.({
onAdded: (item) => {
- if (isPromptReferenceItem(item) && 'skillMdKey' in item && typeof item.skillMdKey === 'string')
- onSelect(createDriveReferenceToken('skill', item.skillMdKey, item.name))
+ if (isPromptReferenceItem(item))
+ onSelect(createConfigReferenceToken('skill', item.id, item.name))
},
})
return
@@ -105,8 +109,8 @@ export function AgentPromptSlashMenu({
if (view === 'files') {
onAddFile?.({
onAdded: (item) => {
- if (isPromptReferenceItem(item) && 'driveKey' in item && typeof item.driveKey === 'string')
- onSelect(createDriveReferenceToken('file', item.driveKey, item.name))
+ if (isAgentFileNode(item))
+ onSelect(createConfigReferenceToken('file', item.configName ?? item.id, item.name))
},
})
return
@@ -234,7 +238,7 @@ function AgentPromptSkillRows({
key={skill.id}
icon="i-ri-box-3-line"
label={skill.name}
- onClick={() => skill.skillMdKey && onSelect(createDriveReferenceToken('skill', skill.skillMdKey, skill.name))}
+ onClick={() => onSelect(createConfigReferenceToken('skill', skill.id, skill.name))}
/>
))}
</>
@@ -259,7 +263,10 @@ function AgentPromptFileRows({
label={file.name}
depth={depth}
hasChildren={!!file.children?.length}
- onClick={() => file.driveKey && onSelect(createDriveReferenceToken('file', file.driveKey, file.name))}
+ onClick={() => {
+ if (!file.children?.length)
+ onSelect(createConfigReferenceToken('file', file.configName ?? file.id, file.name))
+ }}
/>
{!!file.children?.length && (
<AgentPromptFileRows files={file.children} depth={depth + 1} onSelect={onSelect} />
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
index 34c8cc1f6c4..fb0e5e87eac 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
@@ -10,10 +10,10 @@ import { toast } from '@langgenius/dify-ui/toast'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useKnowledgeValidationMessage, validateKnowledgeRetrievals } from '@/features/agent-v2/agent-composer/knowledge-validation'
-import { hasAgentComposerUnpublishedChangesAtom } from '@/features/agent-v2/agent-composer/store'
+import { hasAgentComposerUnpublishedChangesAtom, isAgentComposerDirtyAtom } from '@/features/agent-v2/agent-composer/store'
import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import useTimestamp from '@/hooks/use-timestamp'
@@ -37,27 +37,32 @@ type AgentConfigurePublishBarProps = {
selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | null
onPublish?: () => void | Promise<void>
onExitVersions?: () => void
- onOpenVersions: () => void
+ onOpenVersions?: () => void
}
function getPublishState({
activeConfigIsPublished,
activeConfigSnapshot,
- isDirty,
+ hasLocalChanges,
+ hasUnpublishedChanges,
isPublishing,
}: {
activeConfigIsPublished?: boolean
activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
- isDirty: boolean
+ hasLocalChanges: boolean
+ hasUnpublishedChanges: boolean
isPublishing: boolean
}): AgentConfigurePublishState {
if (isPublishing)
return 'publishing'
+ if (hasLocalChanges)
+ return 'unpublished'
+
if (activeConfigIsPublished)
return 'published'
- if (isDirty)
+ if (hasUnpublishedChanges)
return 'unpublished'
if (!activeConfigSnapshot)
@@ -96,20 +101,29 @@ export function AgentConfigurePublishBar({
const { formatTimeFromNow } = useFormatTimeFromNow()
const queryClient = useQueryClient()
const [publishBarMode, setPublishBarMode] = useState<PublishBarMode>({ status: 'compact' })
+ const lastKnownPublishedRef = useRef(false)
+ if (activeConfigIsPublished === true)
+ lastKnownPublishedRef.current = true
+ if (activeConfigIsPublished === false)
+ lastKnownPublishedRef.current = false
+ const stableActiveConfigIsPublished = activeConfigIsPublished ?? (lastKnownPublishedRef.current ? true : undefined)
const hasUnpublishedChanges = useAtomValue(hasAgentComposerUnpublishedChangesAtom)
+ const hasLocalChanges = useAtomValue(isAgentComposerDirtyAtom)
const knowledgeRetrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)
const knowledgeValidation = validateKnowledgeRetrievals(knowledgeRetrievals)
const getValidationMessage = useKnowledgeValidationMessage()
const publishableState = getPublishState({
- activeConfigIsPublished,
+ activeConfigIsPublished: stableActiveConfigIsPublished,
activeConfigSnapshot,
- isDirty: hasUnpublishedChanges,
+ hasLocalChanges,
+ hasUnpublishedChanges,
isPublishing: false,
})
const publishState = getPublishState({
- activeConfigIsPublished,
+ activeConfigIsPublished: stableActiveConfigIsPublished,
activeConfigSnapshot,
- isDirty: hasUnpublishedChanges,
+ hasLocalChanges,
+ hasUnpublishedChanges,
isPublishing,
})
const publishIsAvailable = !isPublishing && (publishableState === 'draft' || publishableState === 'unpublished')
@@ -296,7 +310,7 @@ export function AgentConfigurePublishBar({
statusLabel={currentStateMeta.statusLabel}
canPublish={canPublish}
onCancelImpact={() => setPublishBarMode({ status: 'compact' })}
- onOpenVersions={onOpenVersions}
+ onOpenVersions={() => onOpenVersions?.()}
onPublishRequest={handlePublishRequest}
/>
</CollapsibleRoot>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
index 9cb27c1736e..fe8e7252430 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
@@ -1,6 +1,8 @@
+import type { AgentConfigApiContext } from '../../config-context'
+import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { toast } from '@langgenius/dify-ui/toast'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -8,18 +10,43 @@ import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/c
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
-import { AgentDriveApiContextProvider } from '../../drive-context'
+import { AgentConfigApiContextProvider } from '../../config-context'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentSkills } from '../index'
+type ConfigSkillInspectQueryOptionsInput = {
+ input: {
+ params: {
+ name: string
+ }
+ }
+}
+
+type ConfigSkillFileQueryOptionsInput = {
+ input: {
+ query: {
+ path: string
+ }
+ }
+}
+
const mocks = vi.hoisted(() => ({
- driveSkillsQueryOptions: vi.fn(),
- driveSkillInspectQueryOptions: vi.fn(),
- driveFilesQueryOptions: vi.fn(),
- driveFileDownloadQueryOptions: vi.fn(),
- driveFilePreviewQueryOptions: vi.fn(),
- deleteSkillMutationOptions: vi.fn(),
- uploadSkillMutationOptions: vi.fn(),
+ deleteSkillMutationFn: vi.fn(async (_input: unknown) => ({ removed_names: ['Tender Analyzer'], result: 'success' })),
+ uploadSkillMutationFn: vi.fn(async (_input: unknown) => ({
+ config_version: { id: 'draft-1', kind: 'draft', writable: true },
+ skill: {
+ id: 'Invoice Helper',
+ name: 'Invoice Helper',
+ file_id: 'tool-file-2',
+ description: 'Summarizes invoices.',
+ hash: 'sha256:skill-2',
+ mime_type: 'application/zip',
+ size: 128,
+ },
+ })),
+ inspectQueryOptions: vi.fn((_options: ConfigSkillInspectQueryOptionsInput) => ({})),
+ previewQueryOptions: vi.fn((_options: ConfigSkillFileQueryOptionsInput) => ({})),
+ downloadQueryOptions: vi.fn((_options: ConfigSkillFileQueryOptionsInput) => ({})),
}))
vi.mock('@langgenius/dify-ui/toast', () => ({
@@ -33,842 +60,352 @@ vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
byAgentId: {
- drive: {
+ config: {
skills: {
- get: {
- queryOptions: mocks.driveSkillsQueryOptions,
+ upload: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.uploadSkillMutationFn }),
+ },
},
- bySkillPath: {
+ byName: {
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.deleteSkillMutationFn }),
+ },
inspect: {
get: {
- queryOptions: mocks.driveSkillInspectQueryOptions,
+ queryOptions: mocks.inspectQueryOptions,
},
},
- },
- },
- files: {
- get: {
- queryOptions: mocks.driveFilesQueryOptions,
- },
- download: {
- get: {
- queryOptions: mocks.driveFileDownloadQueryOptions,
- },
- },
- preview: {
- get: {
- queryOptions: mocks.driveFilePreviewQueryOptions,
+ files: {
+ preview: {
+ get: {
+ queryOptions: mocks.previewQueryOptions,
+ },
+ },
+ download: {
+ get: {
+ queryOptions: mocks.downloadQueryOptions,
+ },
+ },
},
},
},
},
- skills: {
- bySlug: {
- delete: {
- mutationOptions: mocks.deleteSkillMutationOptions,
- },
- },
- upload: {
- post: {
- mutationOptions: mocks.uploadSkillMutationOptions,
- },
- },
- },
},
},
apps: {
byAppId: {
agent: {
- drive: {
+ config: {
skills: {
- get: {
- queryOptions: mocks.driveSkillsQueryOptions,
+ upload: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.uploadSkillMutationFn }),
+ },
},
- bySkillPath: {
+ byName: {
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.deleteSkillMutationFn }),
+ },
inspect: {
get: {
- queryOptions: mocks.driveSkillInspectQueryOptions,
+ queryOptions: mocks.inspectQueryOptions,
},
},
- },
- },
- files: {
- get: {
- queryOptions: mocks.driveFilesQueryOptions,
- },
- download: {
- get: {
- queryOptions: mocks.driveFileDownloadQueryOptions,
- },
- },
- preview: {
- get: {
- queryOptions: mocks.driveFilePreviewQueryOptions,
+ files: {
+ preview: {
+ get: {
+ queryOptions: mocks.previewQueryOptions,
+ },
+ },
+ download: {
+ get: {
+ queryOptions: mocks.downloadQueryOptions,
+ },
+ },
},
},
},
},
- skills: {
- bySlug: {
- delete: {
- mutationOptions: mocks.deleteSkillMutationOptions,
- },
- },
- upload: {
- post: {
- mutationOptions: mocks.uploadSkillMutationOptions,
- },
- },
- },
},
},
},
},
}))
-const agentSkillsDraft = {
- ...defaultAgentSoulConfigFormState,
- skills: [
- {
- archiveKey: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- id: 'tender-analyzer/SKILL.md',
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skillMdKey: 'tender-analyzer/SKILL.md',
- },
- {
- id: 'meeting-brief/SKILL.md',
- name: 'Meeting Brief',
- path: 'meeting-brief',
- skillMdKey: 'meeting-brief/SKILL.md',
- },
- ],
-} satisfies typeof defaultAgentSoulConfigFormState
-
-function renderAgentSkills() {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
+function ConfigSnapshotProbe() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
- return render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={agentSkillsDraft}>
- <AgentSkills />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
+ return (
+ <pre data-testid="config-snapshot-probe">
+ {JSON.stringify(configSnapshot)}
+ </pre>
)
}
-function renderWorkflowAgentSkills() {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
+function renderAgentSkills({
+ initialDraft = {
+ ...defaultAgentSoulConfigFormState,
+ skills: [
+ {
+ id: 'Tender Analyzer',
+ name: 'Tender Analyzer',
+ description: 'Extracts tender requirements.',
+ fileId: 'tool-file-1',
},
- },
- })
-
- return render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1', workflow: { appId: 'app-1', nodeId: 'node-1' } }}>
- <AgentComposerProvider initialDraft={agentSkillsDraft}>
- <AgentSkills />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
- )
-}
-
-function renderReadonlyAgentSkills() {
+ ],
+ },
+ apiContext = { agentId: 'agent-1', draftType: 'draft' } satisfies AgentConfigApiContext,
+ readOnly = false,
+}: {
+ initialDraft?: AgentSoulConfigFormState
+ apiContext?: AgentConfigApiContext
+ readOnly?: boolean
+} = {}) {
const queryClient = new QueryClient({
defaultOptions: {
- queries: {
- retry: false,
- },
+ queries: { retry: false },
+ mutations: { retry: false },
},
})
return render(
<QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={agentSkillsDraft}>
- <AgentOrchestrateReadOnlyContext value>
+ <AgentConfigApiContextProvider value={apiContext}>
+ <AgentComposerProvider initialDraft={initialDraft}>
+ <AgentOrchestrateReadOnlyContext value={readOnly}>
<AgentSkills />
+ <ConfigSnapshotProbe />
</AgentOrchestrateReadOnlyContext>
</AgentComposerProvider>
- </AgentDriveApiContextProvider>
+ </AgentConfigApiContextProvider>
</QueryClientProvider>,
)
}
-function ConfigSnapshotProbe() {
- const draft = useAtomValue(agentComposerDraftAtom)
- const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
-
- return (
- <pre data-testid="config-snapshot-probe">
- {JSON.stringify(configSnapshot)}
- </pre>
- )
-}
-
describe('AgentSkills', () => {
beforeEach(() => {
vi.clearAllMocks()
- const skillItems = [
- {
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skill_md_key: 'tender-analyzer/SKILL.md',
- },
- {
- description: '',
- name: 'Meeting Brief',
- path: 'meeting-brief',
- skill_md_key: 'meeting-brief/SKILL.md',
- },
- ]
- mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skills', input],
- initialData: { items: skillItems },
- queryFn: async () => ({
- items: skillItems,
- }),
- }))
- mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skill-inspect', input],
+ mocks.inspectQueryOptions.mockImplementation(({ input }) => ({
+ queryKey: ['inspect-skill', input],
queryFn: async () => ({
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
+ id: input.params.name,
+ name: input.params.name,
+ description: 'Inspect skill',
+ source: 'config_skill_zip',
files: [
{
- available_in_drive: true,
- drive_key: 'tender-analyzer/SKILL.md',
- name: 'SKILL.md',
path: 'SKILL.md',
+ name: 'SKILL.md',
type: 'file',
+ previewable: true,
+ downloadable: true,
},
{
- available_in_drive: true,
- drive_key: 'tender-analyzer/references/guide.md',
- name: 'guide.md',
path: 'references/guide.md',
+ name: 'guide.md',
type: 'file',
- },
- {
- available_in_drive: true,
- drive_key: 'tender-analyzer/scripts/extract.py',
- name: 'extract.py',
- path: 'scripts/extract.py',
- type: 'file',
- },
- {
- available_in_drive: true,
- drive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- name: '.DIFY-SKILL-FULL.zip',
- path: '.DIFY-SKILL-FULL.zip',
- type: 'file',
+ previewable: true,
+ downloadable: true,
},
],
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
skill_md: {
- binary: false,
- key: 'tender-analyzer/SKILL.md',
- text: 'Skill markdown content',
+ path: 'SKILL.md',
+ size: 16,
truncated: false,
+ binary: false,
+ text: '# Skill\n',
},
- skill_md_key: 'tender-analyzer/SKILL.md',
- source: 'drive',
warnings: [],
}),
}))
- mocks.driveFilesQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-files', input],
+ mocks.previewQueryOptions.mockImplementation(({ input }) => ({
+ queryKey: ['preview-skill-file', input],
queryFn: async () => ({
- items: [
- {
- file_kind: 'file',
- key: 'tender-analyzer/SKILL.md',
- },
- {
- file_kind: 'file',
- key: 'tender-analyzer/scripts/extract.py',
- },
- ],
- }),
- }))
- mocks.driveFilePreviewQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-file-preview', input],
- queryFn: async () => ({
- text: `Preview content for ${input.query.key}`,
+ path: input.query.path,
+ binary: false,
+ truncated: false,
+ text: `Preview for ${input.query.path}`,
}),
}))
- mocks.driveFileDownloadQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-file-download', input],
+ mocks.downloadQueryOptions.mockImplementation(({ input }) => ({
+ queryKey: ['download-skill-file', input],
queryFn: async () => ({
- url: `https://example.com/${input.query.key}`,
+ url: `https://example.com/${input.query.path}`,
}),
}))
- mocks.uploadSkillMutationOptions.mockReturnValue({
- mutationFn: vi.fn(),
- mutationKey: ['upload-skill'],
- })
- mocks.deleteSkillMutationOptions.mockReturnValue({
- mutationFn: vi.fn(),
- mutationKey: ['delete-skill'],
- })
})
- it('should fetch drive files and open the skill detail dialog when the skill row is clicked', async () => {
- renderAgentSkills()
+ it('should delete a configured skill by config name', async () => {
+ const { container } = renderAgentSkills()
- fireEvent.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
+ const removeButton = container.querySelector('[data-agent-skill-remove-button]')
+ expect(removeButton).not.toBeNull()
- const dialog = screen.getByRole('dialog')
+ fireEvent.click(removeButton!)
- expect(dialog).toBeInTheDocument()
await waitFor(() => {
- expect(mocks.driveSkillInspectQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- agent_id: 'agent-1',
- skill_path: 'tender-analyzer',
- },
- },
- })
- })
- expect(mocks.driveFilesQueryOptions).not.toHaveBeenCalled()
- expect(within(dialog).getByText('Tender Analyzer')).toBeInTheDocument()
- expect(within(dialog).getByText('Extracts tender requirements and scoring criteria.')).toBeInTheDocument()
- expect(await within(dialog).findByText('references')).toBeInTheDocument()
- expect(within(dialog).getByText('guide.md')).toBeInTheDocument()
- expect(within(dialog).getByText('scripts')).toBeInTheDocument()
- expect(within(dialog).getByText('extract.py')).toBeInTheDocument()
- expect(within(dialog).queryByText('.DIFY-SKILL-FULL.zip')).not.toBeInTheDocument()
- })
-
- it('should keep the detail dialog open after selecting a skill', async () => {
- renderAgentSkills()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
-
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- })
-
- it('should preview selected package file content in the skill detail dialog', async () => {
- const user = userEvent.setup()
- renderAgentSkills()
-
- await user.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
-
- const dialog = screen.getByRole('dialog')
- await user.click(await within(dialog).findByText('guide.md'))
-
- expect(await within(dialog).findByText('Preview content for tender-analyzer/references/guide.md')).toBeInTheDocument()
- expect(mocks.driveFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
+ expect(mocks.deleteSkillMutationFn).toHaveBeenCalled()
+ expect(mocks.deleteSkillMutationFn.mock.calls[0]?.[0]).toEqual({
params: {
agent_id: 'agent-1',
+ name: 'Tender Analyzer',
},
query: {
- key: 'tender-analyzer/references/guide.md',
+ draft_type: 'draft',
+ version_id: undefined,
},
- },
+ })
})
+
+ expect(screen.queryByText('Tender Analyzer')).not.toBeInTheDocument()
})
- it('should not request preview for package files without a drive entry', async () => {
+ it('should upload a skill through the config endpoint and add it to the draft UI', async () => {
const user = userEvent.setup()
- mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skill-inspect', input],
- queryFn: async () => ({
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- files: [
- {
- available_in_drive: true,
- drive_key: 'tender-analyzer/SKILL.md',
- name: 'SKILL.md',
- path: 'SKILL.md',
- type: 'file',
- },
- {
- available_in_drive: false,
- drive_key: null,
- name: 'animation-rows.md',
- path: 'references/animation-rows.md',
- type: 'file',
- },
- ],
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skill_md: {
- binary: false,
- key: 'tender-analyzer/SKILL.md',
- text: 'Skill markdown content',
- truncated: false,
- },
- skill_md_key: 'tender-analyzer/SKILL.md',
- source: 'drive',
- warnings: [],
- }),
- }))
+ renderAgentSkills({ initialDraft: defaultAgentSoulConfigFormState })
- renderAgentSkills()
-
- await user.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
+ await user.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.skills\.add/i }))
- const dialog = screen.getByRole('dialog')
- await user.click(await within(dialog).findByText('animation-rows.md'))
+ const input = await waitFor(() => {
+ const element = document.querySelector('input[type="file"]')
+ expect(element).not.toBeNull()
+ return element as HTMLInputElement
+ })
+ const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
+ await user.upload(input, file)
+ await user.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.upload\.action/i }))
- expect(mocks.driveFilePreviewQueryOptions).not.toHaveBeenCalledWith({
- input: {
+ await waitFor(() => {
+ expect(mocks.uploadSkillMutationFn).toHaveBeenCalled()
+ expect(mocks.uploadSkillMutationFn.mock.calls[0]?.[0]).toEqual({
params: {
agent_id: 'agent-1',
},
query: {
- key: 'tender-analyzer/references/animation-rows.md',
+ draft_type: 'draft',
+ version_id: undefined,
},
- },
- })
- expect(within(dialog).getByText('agentV2.agentDetail.configure.files.preview.empty')).toBeInTheDocument()
- })
-
- it('should deduplicate package files by path in the skill detail dialog', async () => {
- const user = userEvent.setup()
- mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skill-inspect', input],
- queryFn: async () => ({
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- files: [
- {
- available_in_drive: true,
- drive_key: 'tender-analyzer/SKILL.md',
- name: 'SKILL.md',
- path: 'SKILL.md',
- type: 'file',
- },
- {
- available_in_drive: false,
- drive_key: null,
- name: 'SKILL.md',
- path: 'tender-analyzer/SKILL.md',
- type: 'file',
- },
- {
- available_in_drive: true,
- drive_key: 'tender-analyzer/scripts/extract.py',
- name: 'extract.py',
- path: 'scripts/extract.py',
- type: 'file',
- },
- ],
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skill_md: {
- binary: false,
- key: 'tender-analyzer/SKILL.md',
- text: 'Skill markdown content',
- truncated: false,
- },
- skill_md_key: 'tender-analyzer/SKILL.md',
- source: 'drive',
- warnings: [],
- }),
- }))
-
- renderAgentSkills()
-
- await user.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
-
- const dialog = screen.getByRole('dialog')
-
- expect(await within(dialog).findByText('SKILL.md')).toBeInTheDocument()
- expect(within(dialog).getAllByText('SKILL.md')).toHaveLength(1)
- expect(within(dialog).getByText('agentV2.agentDetail.configure.skills.detail.fileCount:{"count":2}')).toBeInTheDocument()
- })
-
- it('should use workflow node drive routes for skill preview in inline workflow mode', async () => {
- renderWorkflowAgentSkills()
-
- expect(mocks.driveSkillsQueryOptions).not.toHaveBeenCalled()
-
- fireEvent.click(screen.getByRole('button', {
- name: 'Tender Analyzer',
- }))
-
- await waitFor(() => {
- expect(mocks.driveSkillInspectQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- skill_path: 'tender-analyzer',
- },
- query: {
- node_id: 'node-1',
- },
- },
- })
- })
- fireEvent.click(await screen.findByText('guide.md'))
-
- await waitFor(() => {
- expect(mocks.driveFilePreviewQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- key: 'tender-analyzer/references/guide.md',
- },
+ body: {
+ file,
},
})
})
- })
- it('should delete the skill without opening the detail dialog when the remove action is clicked', () => {
- renderAgentSkills()
-
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,
- }))
-
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(screen.getByText('Invoice Helper')).toBeInTheDocument()
+ const snapshot = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')
+ expect(snapshot.config_skills).toEqual([
+ expect.objectContaining({
+ name: 'Invoice Helper',
+ file_id: 'tool-file-2',
+ file_kind: 'tool_file',
+ hash: 'sha256:skill-2',
+ mime_type: 'application/zip',
+ size: 128,
+ }),
+ ])
+ expect(toast.success).toHaveBeenCalled()
})
- it('should route Agent App skill delete through agent and slug identifiers', async () => {
- const deleteSkill = vi.fn().mockResolvedValue({ result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] })
- mocks.deleteSkillMutationOptions.mockReturnValue({
- mutationFn: deleteSkill,
- mutationKey: ['delete-skill'],
- })
- renderAgentSkills()
-
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,
- }))
-
- await waitFor(() => {
- expect(deleteSkill.mock.calls[0]?.[0]).toEqual({
- params: {
- agent_id: 'agent-1',
- slug: 'tender-analyzer',
+ it('should use workflow config skill endpoints with node_id for uploads and skill member queries', async () => {
+ const user = userEvent.setup()
+ renderAgentSkills({
+ apiContext: {
+ agentId: 'agent-1',
+ draftType: 'draft',
+ versionId: 'draft-1',
+ workflow: {
+ appId: 'app-1',
+ nodeId: 'node-1',
},
- })
+ },
})
- })
- it('should route workflow skill delete through app and node identifiers', async () => {
- const deleteSkill = vi.fn().mockResolvedValue({ result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] })
- mocks.deleteSkillMutationOptions.mockReturnValue({
- mutationFn: deleteSkill,
- mutationKey: ['delete-skill'],
+ await user.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.skills\.add/i }))
+ const input = await waitFor(() => {
+ const element = document.querySelector('input[type="file"]')
+ expect(element).not.toBeNull()
+ return element as HTMLInputElement
})
- renderWorkflowAgentSkills()
-
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,
- }))
+ const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
+ await user.upload(input, file)
+ await user.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.upload\.action/i }))
await waitFor(() => {
- expect(deleteSkill.mock.calls[0]?.[0]).toEqual({
+ expect(mocks.uploadSkillMutationFn.mock.calls[0]?.[0]).toEqual({
params: {
app_id: 'app-1',
- slug: 'tender-analyzer',
},
query: {
+ draft_type: 'draft',
node_id: 'node-1',
+ version_id: 'draft-1',
},
- })
- })
- })
-
- it('should hide add and remove actions when readonly', () => {
- renderReadonlyAgentSkills()
-
- expect(screen.getByRole('button', { name: 'Tender Analyzer' })).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', {
- name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,
- })).not.toBeInTheDocument()
- })
-
- it('should upload a skill through the drive-backed endpoint', async () => {
- const user = userEvent.setup()
- const driveSkills = [
- {
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skill_md_key: 'tender-analyzer/SKILL.md',
- },
- {
- description: '',
- name: 'Meeting Brief',
- path: 'meeting-brief',
- skill_md_key: 'meeting-brief/SKILL.md',
- },
- ]
- mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skills', input],
- initialData: { items: [...driveSkills] },
- queryFn: async () => ({ items: [...driveSkills] }),
- }))
- const uploadSkill = vi.fn().mockImplementation(async () => {
- driveSkills.push({
- archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',
- description: '',
- name: 'Invoice Helper',
- path: 'invoice-helper',
- skill_md_key: 'invoice-helper/SKILL.md',
- })
- return {
- manifest: {
- files: ['SKILL.md', 'scripts/run.py'],
- name: 'Invoice Helper',
- },
- skill: {
- manifest_files: ['SKILL.md', 'scripts/run.py'],
- name: 'Invoice Helper',
- path: 'invoice-helper',
- skill_md_key: 'invoice-helper/SKILL.md',
- archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',
- },
- }
- })
- mocks.uploadSkillMutationOptions.mockReturnValue({
- mutationFn: uploadSkill,
- mutationKey: ['upload-skill'],
- })
-
- renderAgentSkills()
-
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))
-
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
- const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
- await user.upload(fileInput, file)
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))
-
- await waitFor(() => {
- expect(uploadSkill.mock.calls[0]?.[0]).toEqual({
body: {
file,
},
- params: {
- agent_id: 'agent-1',
- },
})
})
- expect(await screen.findByRole('button', { name: 'Invoice Helper' })).toBeInTheDocument()
- expect(vi.mocked(toast.success)).toHaveBeenCalledWith('agentV2.agentDetail.configure.skills.upload.success')
- })
-
- it('should upload a dropped skill package through the drive-backed endpoint', async () => {
- const user = userEvent.setup()
- const uploadSkill = vi.fn().mockResolvedValue({
- manifest: {
- files: ['SKILL.md'],
- name: 'Invoice Helper',
- },
- skill: {
- name: 'Invoice Helper',
- path: 'invoice-helper',
- skill_md_key: 'invoice-helper/SKILL.md',
- },
- })
- mocks.uploadSkillMutationOptions.mockReturnValue({
- mutationFn: uploadSkill,
- mutationKey: ['upload-skill'],
- })
-
- renderAgentSkills()
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))
-
- const uploadArea = screen.getByRole('group', { name: 'agentV2.agentDetail.configure.skills.upload.title' })
- const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
- fireEvent.dragEnter(uploadArea, {
- dataTransfer: {
- files: [file],
- types: ['Files'],
- },
- })
- fireEvent.drop(uploadArea, {
- dataTransfer: {
- files: [file],
- types: ['Files'],
- },
- })
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))
+ await user.click(screen.getByText('Tender Analyzer').closest('button')!)
await waitFor(() => {
- expect(uploadSkill.mock.calls[0]?.[0]).toEqual({
- body: {
- file,
- },
- params: {
- agent_id: 'agent-1',
- },
- })
+ expect(mocks.inspectQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
+ params: {
+ app_id: 'app-1',
+ name: 'Tender Analyzer',
+ },
+ query: {
+ draft_type: 'draft',
+ node_id: 'node-1',
+ version_id: 'draft-1',
+ },
+ }),
+ }))
})
})
- it('should refresh the rendered skill list after delete succeeds', async () => {
- const driveSkills = [
- {
- archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
- description: 'Extracts tender requirements and scoring criteria.',
- name: 'Tender Analyzer',
- path: 'tender-analyzer',
- skill_md_key: 'tender-analyzer/SKILL.md',
- },
- {
- description: '',
- name: 'Meeting Brief',
- path: 'meeting-brief',
- skill_md_key: 'meeting-brief/SKILL.md',
- },
- ]
- mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({
- queryKey: ['agent-drive-skills', input],
- initialData: { items: [...driveSkills] },
- queryFn: async () => ({ items: [...driveSkills] }),
- }))
- const deleteSkill = vi.fn().mockImplementation(async () => {
- driveSkills.splice(0, 1)
- return { result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] }
- })
- mocks.deleteSkillMutationOptions.mockReturnValue({
- mutationFn: deleteSkill,
- mutationKey: ['delete-skill'],
- })
-
+ it('should inspect skills by config name and preview package members by member path', async () => {
+ const user = userEvent.setup()
renderAgentSkills()
- fireEvent.click(screen.getByRole('button', {
- name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,
- }))
+ await user.click(screen.getByText('Tender Analyzer').closest('button')!)
await waitFor(() => {
- expect(screen.queryByRole('button', { name: 'Tender Analyzer' })).not.toBeInTheDocument()
- })
- expect(screen.getByRole('button', { name: 'Meeting Brief' })).toBeInTheDocument()
- })
-
- it('should route workflow skill uploads through app and node identifiers', async () => {
- const user = userEvent.setup()
- const uploadSkill = vi.fn().mockResolvedValue({
- manifest: {
- files: ['SKILL.md'],
- name: 'Invoice Helper',
- },
- skill: {
- name: 'Invoice Helper',
- path: 'invoice-helper',
- skill_md_key: 'invoice-helper/SKILL.md',
- },
- })
- mocks.uploadSkillMutationOptions.mockReturnValue({
- mutationFn: uploadSkill,
- mutationKey: ['upload-skill'],
+ expect(mocks.inspectQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
+ params: {
+ agent_id: 'agent-1',
+ name: 'Tender Analyzer',
+ },
+ }),
+ }))
})
- renderWorkflowAgentSkills()
-
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))
-
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
- const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
- await user.upload(fileInput, file)
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))
+ await user.click(screen.getByText('references').closest('button')!)
+ await user.click(screen.getByText('guide.md').closest('button')!)
await waitFor(() => {
- expect(uploadSkill.mock.calls[0]?.[0]).toEqual({
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- },
- body: {
- file,
- },
- })
+ expect(mocks.previewQueryOptions).toHaveBeenCalledWith(expect.objectContaining({
+ input: expect.objectContaining({
+ params: {
+ agent_id: 'agent-1',
+ name: 'Tender Analyzer',
+ },
+ query: expect.objectContaining({
+ path: 'references/guide.md',
+ }),
+ }),
+ }))
})
})
- it('should not persist skills_files when the draft is serialized', async () => {
- const user = userEvent.setup()
- const uploadSkill = vi.fn().mockResolvedValue({
- manifest: {
- files: ['SKILL.md', 'scripts/run.py'],
- name: 'Invoice Helper',
- },
- skill: {
- archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',
- name: 'Invoice Helper',
- path: 'invoice-helper',
- skill_md_key: 'invoice-helper/SKILL.md',
- },
- })
- mocks.uploadSkillMutationOptions.mockReturnValue({
- mutationFn: uploadSkill,
- mutationKey: ['upload-skill'],
- })
+ it('should disable add and remove actions when the section is read only', () => {
+ const { container } = renderAgentSkills({ readOnly: true })
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
-
- render(
- <QueryClientProvider client={queryClient}>
- <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
- <AgentComposerProvider initialDraft={agentSkillsDraft}>
- <AgentSkills />
- <ConfigSnapshotProbe />
- </AgentComposerProvider>
- </AgentDriveApiContextProvider>
- </QueryClientProvider>,
- )
-
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))
-
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
- const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
- await user.upload(fileInput, file)
- await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))
-
- await waitFor(() => {
- const serializedConfig = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')
- expect(serializedConfig).not.toHaveProperty('skills_files')
- })
+ expect(screen.queryByRole('button', { name: /agentV2\.agentDetail\.configure\.skills\.add/i })).not.toBeInTheDocument()
+ expect(container.querySelector('[data-agent-skill-remove-button]')).toBeNull()
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx
index 9a9407b9e61..bd64cca23b8 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx
@@ -1,5 +1,6 @@
'use client'
+import type { ReactNode } from 'react'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
import {
DialogCloseButton,
@@ -12,7 +13,6 @@ import { ScrollArea } from '@langgenius/dify-ui/scroll-area'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { AgentFileTree } from '../files/tree'
-import { countAgentFileNodes } from '../utils'
type AgentSkillFileNode = AgentFileNode
@@ -26,7 +26,9 @@ type AgentSkillDetailSection = {
export type AgentSkillDetail = {
description: string
fileCount?: number
+ fileListTitle?: string
files: AgentSkillFileNode[]
+ folderOpenState?: (context: { file: AgentSkillFileNode, depth: number }) => boolean
filePreview?: {
binary?: boolean
content?: string
@@ -38,20 +40,30 @@ export type AgentSkillDetail = {
isImage?: boolean
isLoading?: boolean
}
+ onFolderOpenChange?: (context: { file: AgentSkillFileNode, depth: number, open: boolean }) => void
onSelectFile?: (file: AgentSkillFileNode) => void
+ renderFolderSuffix?: (context: { file: AgentSkillFileNode, depth: number }) => ReactNode
selectedFileId?: string
sections: AgentSkillDetailSection[]
}
+const keepSkillFoldersClosed = () => false
+
function AgentSkillFileList({
+ fileListTitle,
files,
- fileCount,
+ folderOpenState,
+ onFolderOpenChange,
onSelectFile,
+ renderFolderSuffix,
selectedFileId,
}: {
+ fileListTitle?: string
files: AgentSkillFileNode[]
- fileCount: number
+ folderOpenState?: AgentSkillDetail['folderOpenState']
+ onFolderOpenChange?: AgentSkillDetail['onFolderOpenChange']
onSelectFile?: (file: AgentSkillFileNode) => void
+ renderFolderSuffix?: AgentSkillDetail['renderFolderSuffix']
selectedFileId?: string
}) {
const { t } = useTranslation('agentV2')
@@ -61,7 +73,11 @@ function AgentSkillFileList({
files={files}
selectedFileId={selectedFileId}
labelledBy="agent-skill-detail-files-heading"
- className="h-[258px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-1 shadow-xs shadow-shadow-shadow-3"
+ className="h-full bg-background-section p-1"
+ scrollAreaClassName="flex-1"
+ folderOpenStrategy={keepSkillFoldersClosed}
+ folderOpenState={folderOpenState}
+ onFolderOpenChange={onFolderOpenChange}
renderFile={onSelectFile
? ({ file, selected, children }) => (
<FileTreeFile selected={selected} onClick={() => onSelectFile(file)}>
@@ -69,17 +85,12 @@ function AgentSkillFileList({
</FileTreeFile>
)
: undefined}
+ renderFolderSuffix={renderFolderSuffix}
header={(
<>
- <h3 id="agent-skill-detail-files-heading" className="sr-only">
- {t('agentDetail.configure.skills.detail.files')}
+ <h3 id="agent-skill-detail-files-heading" className="px-4 pt-3.5 pb-3 system-xl-semibold text-text-primary">
+ {fileListTitle ?? t('agentDetail.configure.skills.detail.files')}
</h3>
- <div
- aria-hidden="true"
- className="px-2 py-1 system-2xs-semibold-uppercase text-text-tertiary"
- >
- {t('agentDetail.configure.skills.detail.fileCount', { count: fileCount })}
- </div>
</>
)}
/>
@@ -138,7 +149,7 @@ function AgentFilePreviewContent({
if (isLoading || isDownloadLoading) {
return (
- <div className="flex min-h-40 items-center justify-center">
+ <div className="flex min-h-40 flex-1 items-center justify-center">
<Loading type="area" />
</div>
)
@@ -146,7 +157,7 @@ function AgentFilePreviewContent({
if (isError || isDownloadError) {
return (
- <p className="system-sm-regular text-text-tertiary">
+ <p className="px-4 system-sm-regular text-text-tertiary">
{t('agentDetail.configure.files.preview.failed')}
</p>
)
@@ -154,11 +165,11 @@ function AgentFilePreviewContent({
if (isImage && downloadUrl) {
return (
- <div className="flex min-h-40 items-start justify-center">
+ <div className="flex min-h-40 flex-1 items-start justify-center overflow-auto px-2 pb-4">
<img
src={downloadUrl}
alt={fileName ?? ''}
- className="max-h-[560px] max-w-full rounded-lg object-contain"
+ className="max-h-140 max-w-full rounded-lg object-contain"
/>
</div>
)
@@ -167,7 +178,7 @@ function AgentFilePreviewContent({
if (binary) {
if (downloadUrl) {
return (
- <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <div className="flex min-w-0 flex-wrap items-center gap-2 px-4">
<span className="system-sm-regular text-text-tertiary">
{t('agentDetail.configure.files.preview.unsupported')}
</span>
@@ -185,7 +196,7 @@ function AgentFilePreviewContent({
}
return (
- <p className="system-sm-regular text-text-tertiary">
+ <p className="px-4 system-sm-regular text-text-tertiary">
{t('agentDetail.configure.files.preview.empty')}
</p>
)
@@ -193,16 +204,26 @@ function AgentFilePreviewContent({
if (!content) {
return (
- <p className="system-sm-regular text-text-tertiary">
+ <p className="px-4 system-sm-regular text-text-tertiary">
{t('agentDetail.configure.files.preview.empty')}
</p>
)
}
+ const lines = content.split('\n')
+
return (
- <pre className="m-0 pb-4 font-mono text-xs leading-5 break-words whitespace-pre-wrap text-text-secondary">
- {content}
- </pre>
+ <div className="flex min-h-0 flex-1 overflow-auto px-2 pb-4">
+ <pre
+ aria-hidden="true"
+ className="m-0 w-7 shrink-0 pr-2 text-right font-mono text-[13px] leading-[22px] text-text-quaternary select-none"
+ >
+ {lines.map((_, index) => String(index + 1).padStart(2, '0')).join('\n')}
+ </pre>
+ <pre className="m-0 min-w-max flex-1 font-mono text-[13px] leading-[22px] whitespace-pre text-text-primary">
+ {content}
+ </pre>
+ </div>
)
}
@@ -214,27 +235,46 @@ export function AgentSkillDetailDialog({
detail: AgentSkillDetail
}) {
const { t } = useTranslation('agentV2')
- const fileCount = detail.fileCount ?? countAgentFileNodes(detail.files)
+ const previewTitle = detail.filePreview?.fileName
return (
- <DialogContent backdropProps={{ forceRender: true }} backdropClassName="fixed" className="flex h-[min(720px,calc(100dvh-2rem))] max-h-none w-[min(960px,calc(100vw-2rem))] flex-col overflow-hidden rounded-2xl p-0">
- <DialogCloseButton className="top-5 right-5" />
- <div className="shrink-0 border-b-[0.5px] border-components-panel-border-subtle pt-6 pr-14 pb-3 pl-6">
- <DialogTitle className="title-xl-semi-bold text-text-primary">
- {skillName}
- </DialogTitle>
- <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">
+ <DialogContent backdropProps={{ forceRender: true }} backdropClassName="fixed" className="flex h-[min(720px,calc(100dvh-2rem))] max-h-none w-[min(960px,calc(100vw-2rem))] flex-row overflow-hidden rounded-2xl p-0">
+ <div className="flex w-56 min-w-0 shrink-0 border-r-[0.5px] border-divider-subtle bg-background-section">
+ <DialogDescription className="sr-only">
{detail.description}
</DialogDescription>
+ <DialogTitle className="sr-only">
+ {previewTitle || skillName}
+ </DialogTitle>
+ <div className="min-h-0 w-full">
+ <AgentSkillFileList
+ fileListTitle={detail.fileListTitle}
+ files={detail.files}
+ folderOpenState={detail.folderOpenState}
+ onFolderOpenChange={detail.onFolderOpenChange}
+ selectedFileId={detail.selectedFileId}
+ onSelectFile={detail.onSelectFile}
+ renderFolderSuffix={detail.renderFolderSuffix}
+ />
+ </div>
</div>
-
- <div className="flex min-h-0 flex-1 items-start">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex shrink-0 items-start gap-2 px-4 pt-3.5 pb-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {!!previewTitle && (
+ <h2 className="min-w-0 truncate system-xl-semibold text-text-primary" title={previewTitle}>
+ {previewTitle}
+ </h2>
+ )}
+ </div>
+ <DialogCloseButton className="static size-7 shrink-0 rounded-md" />
+ </div>
<ScrollArea
- className="relative min-h-0 flex-1 self-stretch overflow-hidden has-[>_:first-child:focus-visible]:outline-2 has-[>_:first-child:focus-visible]:outline-offset-0 has-[>_:first-child:focus-visible]:outline-state-accent-solid"
+ className="relative min-h-0 flex-1 overflow-hidden has-[>_:first-child:focus-visible]:outline-2 has-[>_:first-child:focus-visible]:outline-offset-0 has-[>_:first-child:focus-visible]:outline-state-accent-solid"
label={t('agentDetail.configure.skills.detail.contentRegion')}
slotClassNames={{
- viewport: 'overscroll-contain outline-none focus-visible:outline-none mask-linear-[to_bottom,transparent_0,black_min(40px,var(--scroll-area-overflow-y-start)),black_calc(100%_-_min(40px,var(--scroll-area-overflow-y-end,40px))),transparent_100%] mask-no-repeat',
- content: 'flex min-h-full w-full max-w-full min-w-0 flex-col gap-2 px-6 pt-4 pb-0',
+ viewport: 'overscroll-contain outline-none focus-visible:outline-none',
+ content: 'flex min-h-full w-full max-w-full min-w-0 flex-col gap-2',
}}
>
{detail.filePreview && (
@@ -251,17 +291,11 @@ export function AgentSkillDetailDialog({
/>
)}
{detail.sections.map(section => (
- <AgentSkillDetailSectionBlock key={section.id} section={section} />
+ <div key={section.id} className="px-4">
+ <AgentSkillDetailSectionBlock section={section} />
+ </div>
))}
</ScrollArea>
- <div className="flex w-56 max-w-56 min-w-0 shrink-0 items-start justify-center p-4 pl-2">
- <AgentSkillFileList
- files={detail.files}
- fileCount={fileCount}
- selectedFileId={detail.selectedFileId}
- onSelectFile={detail.onSelectFile}
- />
- </div>
</div>
</DialogContent>
)
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
index 8461138cd30..6efbfe0346d 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
@@ -13,7 +13,7 @@ import { ConfigureSectionAddButton } from '../common/add-button'
import { ConfigureSectionEmpty } from '../common/empty'
import { ConfigureSection } from '../common/section'
import { AgentConfigureTipContent } from '../common/tip-content'
-import { useAgentDriveApiContext } from '../drive-context'
+import { useAgentConfigApiContext } from '../config-context'
import { AgentSkillItem } from './item'
import { AgentSkillUploadDialog } from './upload-dialog'
@@ -23,11 +23,11 @@ export function AgentSkills() {
const skillsListId = 'agent-configure-skills-list'
const [isUploadOpen, setIsUploadOpen] = useState(false)
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
- const apiContext = useAgentDriveApiContext()
+ const apiContext = useAgentConfigApiContext()
const skills = useAtomValue(agentComposerSkillsAtom)
const setSkills = useSetAtom(agentComposerSkillsAtom)
- const { mutate: deleteAgentSkill } = useMutation(consoleQuery.agent.byAgentId.skills.bySlug.delete.mutationOptions())
- const { mutate: deleteAppSkill } = useMutation(consoleQuery.apps.byAppId.agent.skills.bySlug.delete.mutationOptions())
+ const { mutate: deleteAgentSkill } = useMutation(consoleQuery.agent.byAgentId.config.skills.byName.delete.mutationOptions())
+ const { mutate: deleteAppSkill } = useMutation(consoleQuery.apps.byAppId.agent.config.skills.byName.delete.mutationOptions())
const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {
promptAddCallbackRef.current = options?.onAdded
@@ -52,8 +52,7 @@ export function AgentSkills() {
const handleRemoveSkill = useCallback((skillId: string) => {
const skill = skills.find(item => item.id === skillId)
- const skillSlug = skill?.path ?? skill?.skillMdKey?.split('/', 1)[0]
- if (!skillSlug)
+ if (!skill)
return
const onSuccess = () => {
@@ -63,10 +62,12 @@ export function AgentSkills() {
deleteAppSkill({
params: {
app_id: apiContext.workflow.appId,
- slug: skillSlug,
+ name: skill.name,
},
query: {
node_id: apiContext.workflow.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
}, { onSuccess })
return
@@ -75,7 +76,11 @@ export function AgentSkills() {
deleteAgentSkill({
params: {
agent_id: apiContext.agentId,
- slug: skillSlug,
+ name: skill.name,
+ },
+ query: {
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
}, { onSuccess })
}, [apiContext, deleteAgentSkill, deleteAppSkill, setSkills, skills])
@@ -85,6 +90,7 @@ export function AgentSkills() {
<ConfigureSection
label={t('agentDetail.configure.skills.label')}
labelId="agent-configure-skills-label"
+ buildDraftChangeSection="skills"
panelId={skillsListId}
tip={<AgentConfigureTipContent type="skills" />}
tipAriaLabel={skillsTip}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx
index c4126124793..689aeab7880 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx
@@ -1,7 +1,8 @@
'use client'
-import type { AgentDriveApiContext } from '../drive-context'
+import type { AgentConfigApiContext } from '../config-context'
import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'
+import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
} from '@langgenius/dify-ui/dialog'
@@ -16,7 +17,7 @@ export function AgentSkillItem({
skill,
onRemove,
}: {
- apiContext: AgentDriveApiContext
+ apiContext: AgentConfigApiContext
skill: AgentSkill
onRemove: (skillId: string) => void
}) {
@@ -38,35 +39,37 @@ export function AgentSkillItem({
return (
<Dialog open={isPreviewOpen} onOpenChange={setIsPreviewOpen}>
- <div className="group flex h-8 items-center gap-1 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-1 pr-2.5 pl-2 shadow-xs shadow-shadow-shadow-3 focus-within:bg-components-panel-on-panel-item-bg-hover focus-within:shadow-sm hover:bg-components-panel-on-panel-item-bg-hover hover:pr-1 hover:shadow-sm has-[[data-agent-skill-remove-button]:focus-visible]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:focus-visible]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:focus-visible]:shadow-xs! has-[[data-agent-skill-remove-button]:hover]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:hover]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:hover]:shadow-xs!">
+ <div className="group relative h-8 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs shadow-shadow-shadow-3 focus-within:bg-components-panel-on-panel-item-bg-hover focus-within:shadow-sm hover:bg-components-panel-on-panel-item-bg-hover hover:shadow-sm has-[[data-agent-skill-remove-button]:focus-visible]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:focus-visible]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:focus-visible]:shadow-xs! has-[[data-agent-skill-remove-button]:hover]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:hover]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:hover]:shadow-xs!">
<button
type="button"
- className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-md text-left outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
+ aria-label={skill.name}
+ className="flex h-full w-full min-w-0 cursor-pointer items-center gap-1 rounded-lg py-1 pr-2.5 pl-2 text-left outline-hidden select-none focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"
onClick={handleOpenPreview}
>
<span aria-hidden className="i-custom-public-agent-building-blocks size-4 shrink-0" />
<span className="min-w-0 flex-1 truncate system-sm-medium text-text-secondary">
{skill.name}
</span>
+ <span
+ className={cn(
+ 'shrink-0 system-xs-regular text-text-tertiary',
+ !readOnly && 'group-focus-within:opacity-0 group-hover:opacity-0',
+ )}
+ >
+ {t('agentDetail.configure.skills.itemType')}
+ </span>
</button>
{!readOnly && (
- <div className="hidden shrink-0 items-center justify-center rounded-md p-0.5 group-focus-within:flex group-hover:flex">
- <button
- type="button"
- data-agent-skill-remove-button
- aria-label={t('agentDetail.configure.skills.remove', { name: skill.name })}
- onClick={handleRemove}
- className="flex size-5 items-center justify-center rounded-md text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:bg-state-destructive-hover focus-visible:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- >
- <span aria-hidden className="i-ri-delete-bin-line size-4" />
- </button>
- </div>
+ <button
+ type="button"
+ data-agent-skill-remove-button
+ aria-label={t('agentDetail.configure.skills.remove', { name: skill.name })}
+ onClick={handleRemove}
+ className="pointer-events-none absolute top-1/2 right-1 flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-text-tertiary opacity-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:bg-state-destructive-hover focus-visible:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ >
+ <span aria-hidden className="i-ri-delete-bin-line size-4" />
+ </button>
)}
- <div className="flex shrink-0 items-center justify-center group-focus-within:hidden group-hover:hidden">
- <span className="system-xs-regular text-text-tertiary">
- {t('agentDetail.configure.skills.itemType')}
- </span>
- </div>
</div>
{isPreviewOpen && (
<AgentSkillDetailDialog
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx
index 82d328cd78d..86a53e15fdd 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx
@@ -1,9 +1,9 @@
'use client'
-import type { PostAgentByAgentIdSkillsUploadResponse } from '@dify/contracts/api/console/agent/types.gen'
-import type { PostAppsByAppIdAgentSkillsUploadResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { PostAgentByAgentIdConfigSkillsUploadResponse } from '@dify/contracts/api/console/agent/types.gen'
+import type { PostAppsByAppIdAgentConfigSkillsUploadResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { ChangeEvent, DragEvent } from 'react'
-import type { AgentDriveApiContext } from '../drive-context'
+import type { AgentConfigApiContext } from '../config-context'
import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -22,23 +22,19 @@ const skillPackageExtensions = ['.zip', '.skill']
const getSkillNameFromFile = (file: File) => file.name.replace(/\.(?:skill|zip)$/iu, '') || file.name
const toUploadedSkill = (
- response: PostAgentByAgentIdSkillsUploadResponse | PostAppsByAppIdAgentSkillsUploadResponse,
+ response: PostAgentByAgentIdConfigSkillsUploadResponse | PostAppsByAppIdAgentConfigSkillsUploadResponse,
file: File,
): AgentSkill => {
- const name = response.skill?.name
- ?? response.manifest?.name
- ?? getSkillNameFromFile(file)
- const id = response.skill?.skill_md_key
- ?? response.skill?.path
- ?? name
+ const name = response.skill?.name ?? getSkillNameFromFile(file)
return {
- description: response.skill?.description ?? response.manifest?.description ?? undefined,
- archiveKey: response.skill?.archive_key ?? undefined,
- id,
+ description: response.skill?.description ?? undefined,
+ fileId: response.skill?.file_id ?? undefined,
+ hash: response.skill?.hash ?? undefined,
+ id: name,
+ mimeType: response.skill?.mime_type ?? undefined,
name,
- path: response.skill?.path ?? undefined,
- skillMdKey: response.skill?.skill_md_key ?? undefined,
+ size: response.skill?.size ?? undefined,
}
}
@@ -191,7 +187,7 @@ export function AgentSkillUploadDialog({
open,
onOpenChange,
}: {
- apiContext: AgentDriveApiContext
+ apiContext: AgentConfigApiContext
onUploaded?: (skill: AgentSkill) => void
open: boolean
onOpenChange: (open: boolean) => void
@@ -199,8 +195,8 @@ export function AgentSkillUploadDialog({
const { t } = useTranslation('agentV2')
const { t: tCommon } = useTranslation('common')
const [file, setFile] = useState<File>()
- const uploadAgentSkillMutation = useMutation(consoleQuery.agent.byAgentId.skills.upload.post.mutationOptions())
- const uploadWorkflowSkillMutation = useMutation(consoleQuery.apps.byAppId.agent.skills.upload.post.mutationOptions())
+ const uploadAgentSkillMutation = useMutation(consoleQuery.agent.byAgentId.config.skills.upload.post.mutationOptions())
+ const uploadWorkflowSkillMutation = useMutation(consoleQuery.apps.byAppId.agent.config.skills.upload.post.mutationOptions())
const uploadSkillMutation = apiContext.workflow ? uploadWorkflowSkillMutation : uploadAgentSkillMutation
const handleUpload = () => {
@@ -208,7 +204,9 @@ export function AgentSkillUploadDialog({
return
const options = {
- onSuccess: (response: PostAgentByAgentIdSkillsUploadResponse | PostAppsByAppIdAgentSkillsUploadResponse) => {
+ onSuccess: (
+ response: PostAgentByAgentIdConfigSkillsUploadResponse | PostAppsByAppIdAgentConfigSkillsUploadResponse,
+ ) => {
toast.success(t('agentDetail.configure.skills.upload.success'))
onUploaded?.(toUploadedSkill(response, file))
setFile(undefined)
@@ -226,6 +224,8 @@ export function AgentSkillUploadDialog({
},
query: {
node_id: apiContext.workflow.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
body: {
file,
@@ -238,6 +238,10 @@ export function AgentSkillUploadDialog({
params: {
agent_id: apiContext.agentId,
},
+ query: {
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
+ },
body: {
file,
},
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
index e254923b9b4..1bfe4101af2 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
@@ -1,7 +1,7 @@
'use client'
-import type { AgentDriveSkillFileResponse } from '@dify/contracts/api/console/agent/types.gen'
-import type { AgentDriveApiContext } from '../drive-context'
+import type { AgentConfigSkillFileResponse } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentConfigApiContext } from '../config-context'
import type { AgentSkillDetail } from './detail-dialog'
import type { AgentFileNode, AgentSkill } from '@/features/agent-v2/agent-composer/form-state'
import { useQuery } from '@tanstack/react-query'
@@ -9,34 +9,16 @@ import { useMemo, useState } from 'react'
import { consoleQuery } from '@/service/client'
import { getDriveFileIconType } from '../files/file-icon'
-const DIFY_SKILL_FULL_ARCHIVE_NAME = '.DIFY-SKILL-FULL.zip'
+const isSkillFolder = (file: AgentConfigSkillFileResponse) =>
+ file.type === 'directory'
-const getSkillDrivePath = (skill: AgentSkill) => {
- const skillMdKeySlug = skill.skillMdKey?.split('/', 1)[0]
- return skill.path ?? skillMdKeySlug ?? skill.id
-}
-
-const getSkillFileName = (key: string, skillDrivePath: string) => key.startsWith(`${skillDrivePath}/`)
- ? key.slice(skillDrivePath.length + 1)
- : key
-
-const getSkillRelativePath = (path: string, skillDrivePath: string) =>
- getSkillFileName(path, skillDrivePath).split('/').filter(Boolean).join('/')
-
-const isSkillArchiveFile = (path: string) =>
- path === DIFY_SKILL_FULL_ARCHIVE_NAME || path.endsWith(`/${DIFY_SKILL_FULL_ARCHIVE_NAME}`)
-
-const isSkillFolder = (file: AgentDriveSkillFileResponse) =>
- file.type === 'directory' || file.type === 'folder'
-
-const toSkillFileNode = (item: AgentDriveSkillFileResponse, skillDrivePath: string): AgentFileNode => {
- const filePath = getSkillFileName(item.path, skillDrivePath)
- const fileName = item.name || filePath.split('/').pop() || filePath
- const id = item.drive_key
- ?? (item.path.startsWith(`${skillDrivePath}/`) ? item.path : `${skillDrivePath}/${item.path}`)
+const toSkillFileNode = (item: AgentConfigSkillFileResponse): AgentFileNode => {
+ const fileName = item.name || item.path.split('/').pop() || item.path
return {
- driveKey: item.available_in_drive ? item.drive_key ?? undefined : undefined,
+ id: item.path,
+ name: fileName,
+ configName: item.path,
icon: isSkillFolder(item)
? 'folder'
: getDriveFileIconType({
@@ -44,8 +26,6 @@ const toSkillFileNode = (item: AgentDriveSkillFileResponse, skillDrivePath: stri
fileName,
mimeType: undefined,
}),
- id,
- name: fileName,
}
}
@@ -59,21 +39,14 @@ const sortSkillFileNodes = (files: AgentFileNode[]): AgentFileNode[] => [...file
return first.name.localeCompare(second.name)
}).map(file => file.children ? { ...file, children: sortSkillFileNodes(file.children) } : file)
-const toSkillFileTree = (files: AgentDriveSkillFileResponse[], skillDrivePath: string): AgentFileNode[] => {
+const toSkillFileTree = (files: AgentConfigSkillFileResponse[]): AgentFileNode[] => {
const root: AgentFileNode[] = []
const folders = new Map<string, AgentFileNode>()
- const seenFilePaths = new Set<string>()
for (const file of files) {
- const relativePath = getSkillRelativePath(file.path, skillDrivePath)
- if (!relativePath || isSkillArchiveFile(relativePath))
+ const relativePath = file.path.split('/').filter(Boolean).join('/')
+ if (!relativePath)
continue
- if (!isSkillFolder(file)) {
- if (seenFilePaths.has(relativePath))
- continue
-
- seenFilePaths.add(relativePath)
- }
const segments = relativePath.split('/').filter(Boolean)
let siblings = root
@@ -104,7 +77,7 @@ const toSkillFileTree = (files: AgentDriveSkillFileResponse[], skillDrivePath: s
}
siblings.push({
- ...toSkillFileNode(file, skillDrivePath),
+ ...toSkillFileNode(file),
name: segment,
})
})
@@ -113,15 +86,15 @@ const toSkillFileTree = (files: AgentDriveSkillFileResponse[], skillDrivePath: s
return sortSkillFileNodes(root)
}
-const countSkillPackageFiles = (files: AgentDriveSkillFileResponse[] | undefined, skillDrivePath: string) => {
+const countSkillPackageFiles = (files: AgentConfigSkillFileResponse[] | undefined) => {
const filePaths = new Set<string>()
for (const file of files ?? []) {
if (isSkillFolder(file))
continue
- const relativePath = getSkillRelativePath(file.path, skillDrivePath)
- if (!relativePath || isSkillArchiveFile(relativePath))
+ const relativePath = file.path.split('/').filter(Boolean).join('/')
+ if (!relativePath)
continue
filePaths.add(relativePath)
@@ -172,33 +145,38 @@ export function useAgentSkillDetail({
isOpen,
skill,
}: {
- apiContext: AgentDriveApiContext
+ apiContext: AgentConfigApiContext
description: string
isOpen: boolean
skill: AgentSkill
}): AgentSkillDetail {
const [selectedFileId, setSelectedFileId] = useState<string>()
- const skillDrivePath = getSkillDrivePath(skill)
const agentSkillInspectQuery = useQuery({
- ...consoleQuery.agent.byAgentId.drive.skills.bySkillPath.inspect.get.queryOptions({
+ ...consoleQuery.agent.byAgentId.config.skills.byName.inspect.get.queryOptions({
input: {
params: {
agent_id: apiContext.agentId,
- skill_path: skillDrivePath,
+ name: skill.name,
+ },
+ query: {
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
enabled: isOpen && !apiContext.workflow,
})
const workflowSkillInspectQuery = useQuery({
- ...consoleQuery.apps.byAppId.agent.drive.skills.bySkillPath.inspect.get.queryOptions({
+ ...consoleQuery.apps.byAppId.agent.config.skills.byName.inspect.get.queryOptions({
input: {
params: {
app_id: apiContext.workflow?.appId ?? '',
- skill_path: skillDrivePath,
+ name: skill.name,
},
query: {
node_id: apiContext.workflow?.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
@@ -206,89 +184,89 @@ export function useAgentSkillDetail({
})
const inspectQuery = apiContext.workflow ? workflowSkillInspectQuery : agentSkillInspectQuery
const detailFiles = useMemo(
- () => toSkillFileTree(inspectQuery.data?.files ?? [], skillDrivePath),
- [inspectQuery.data?.files, skillDrivePath],
+ () => toSkillFileTree(inspectQuery.data?.files ?? []),
+ [inspectQuery.data?.files],
)
const previewFileId = selectedFileId
- ?? skill.skillMdKey
- ?? inspectQuery.data?.skill_md.key
+ ?? inspectQuery.data?.skill_md.path
?? (inspectQuery.isSuccess ? getSkillMdFileId(detailFiles) ?? getFirstSkillFileId(detailFiles) : undefined)
const selectedFile = findSkillFileById(detailFiles, previewFileId)
- const isSkillMdSelected = previewFileId === inspectQuery.data?.skill_md.key
- || previewFileId === skill.skillMdKey
- || selectedFile?.name === 'SKILL.md'
- const selectedPreviewKey = isSkillMdSelected
- ? undefined
- : selectedFile?.driveKey
+ const isSkillMdSelected = previewFileId === inspectQuery.data?.skill_md.path || selectedFile?.name === 'SKILL.md'
+ const selectedPreviewPath = isSkillMdSelected ? undefined : selectedFile?.configName ?? selectedFile?.id
const agentPreviewQuery = useQuery({
- ...consoleQuery.agent.byAgentId.drive.files.preview.get.queryOptions({
+ ...consoleQuery.agent.byAgentId.config.skills.byName.files.preview.get.queryOptions({
input: {
params: {
agent_id: apiContext.agentId,
+ name: skill.name,
},
query: {
- key: selectedPreviewKey ?? '',
+ path: selectedPreviewPath ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled: isOpen && !!selectedPreviewKey && !apiContext.workflow,
+ enabled: isOpen && !!selectedPreviewPath && !apiContext.workflow,
})
const workflowPreviewQuery = useQuery({
- ...consoleQuery.apps.byAppId.agent.drive.files.preview.get.queryOptions({
+ ...consoleQuery.apps.byAppId.agent.config.skills.byName.files.preview.get.queryOptions({
input: {
params: {
app_id: apiContext.workflow?.appId ?? '',
+ name: skill.name,
},
query: {
node_id: apiContext.workflow?.nodeId,
- key: selectedPreviewKey ?? '',
+ path: selectedPreviewPath ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled: isOpen && !!selectedPreviewKey && !!apiContext.workflow,
+ enabled: isOpen && !!selectedPreviewPath && !!apiContext.workflow,
})
const previewQuery = apiContext.workflow ? workflowPreviewQuery : agentPreviewQuery
const isImagePreviewFile = selectedFile?.icon === 'image'
+ const shouldDownloadPreviewFile = isOpen && !!selectedPreviewPath && (isImagePreviewFile || !!previewQuery.data?.binary)
const agentDownloadQuery = useQuery({
- ...consoleQuery.agent.byAgentId.drive.files.download.get.queryOptions({
+ ...consoleQuery.agent.byAgentId.config.skills.byName.files.download.get.queryOptions({
input: {
params: {
agent_id: apiContext.agentId,
+ name: skill.name,
},
query: {
- key: selectedPreviewKey ?? '',
+ path: selectedPreviewPath ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled:
- isOpen
- && !!selectedPreviewKey
- && (isImagePreviewFile || !!previewQuery.data?.binary)
- && !apiContext.workflow,
+ enabled: shouldDownloadPreviewFile && !apiContext.workflow,
})
const workflowDownloadQuery = useQuery({
- ...consoleQuery.apps.byAppId.agent.drive.files.download.get.queryOptions({
+ ...consoleQuery.apps.byAppId.agent.config.skills.byName.files.download.get.queryOptions({
input: {
params: {
app_id: apiContext.workflow?.appId ?? '',
+ name: skill.name,
},
query: {
node_id: apiContext.workflow?.nodeId,
- key: selectedPreviewKey ?? '',
+ path: selectedPreviewPath ?? '',
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
},
},
}),
- enabled:
- isOpen
- && !!selectedPreviewKey
- && (isImagePreviewFile || !!previewQuery.data?.binary)
- && !!apiContext.workflow,
+ enabled: shouldDownloadPreviewFile && !!apiContext.workflow,
})
const downloadQuery = apiContext.workflow ? workflowDownloadQuery : agentDownloadQuery
return {
description,
- fileCount: countSkillPackageFiles(inspectQuery.data?.files, skillDrivePath),
+ fileCount: countSkillPackageFiles(inspectQuery.data?.files),
files: detailFiles,
filePreview: {
binary: isSkillMdSelected ? inspectQuery.data?.skill_md.binary : previewQuery.data?.binary,
@@ -296,10 +274,10 @@ export function useAgentSkillDetail({
downloadUrl: downloadQuery.data?.url,
fileName: selectedFile?.name,
isDownloadError: downloadQuery.isError,
- isDownloadLoading: !!selectedPreviewKey && (isImagePreviewFile || !!previewQuery.data?.binary) && downloadQuery.isPending,
- isError: isSkillMdSelected ? inspectQuery.isError : !!selectedPreviewKey && previewQuery.isError,
+ isDownloadLoading: shouldDownloadPreviewFile && downloadQuery.isPending,
+ isError: isSkillMdSelected ? inspectQuery.isError : !!selectedPreviewPath && previewQuery.isError,
isImage: isImagePreviewFile,
- isLoading: isSkillMdSelected ? inspectQuery.isPending : !!selectedPreviewKey && previewQuery.isPending,
+ isLoading: isSkillMdSelected ? inspectQuery.isPending : !!selectedPreviewPath && previewQuery.isPending,
},
onSelectFile: file => setSelectedFileId(file.id),
selectedFileId: previewFileId,
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
index 4b59db51a42..74ff5f7aab4 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
@@ -3,10 +3,17 @@ import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-compose
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createStore, Provider as JotaiProvider } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CollectionType } from '@/app/components/tools/types'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import {
+ agentComposerDraftAtom,
+ agentComposerOriginalDraftAtom,
+ agentComposerPublishedDraftAtom,
+ isAgentComposerDirtyAtom,
+} from '@/features/agent-v2/agent-composer/store'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentTools } from '../index'
@@ -233,6 +240,33 @@ function renderAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDra
)
}
+function renderAgentToolsWithStore(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ })
+ const store = createStore()
+ store.set(agentComposerDraftAtom, initialDraft)
+ store.set(agentComposerOriginalDraftAtom, initialDraft)
+ store.set(agentComposerPublishedDraftAtom, initialDraft)
+
+ const view = render(
+ <QueryClientProvider client={queryClient}>
+ <JotaiProvider store={store}>
+ <AgentTools />
+ </JotaiProvider>
+ </QueryClientProvider>,
+ )
+
+ return {
+ ...view,
+ store,
+ }
+}
+
function renderReadonlyAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {
const queryClient = new QueryClient({
defaultOptions: {
@@ -384,6 +418,21 @@ describe('AgentTools', () => {
expect(screen.queryByText('tools.notAuthorized')).not.toBeInTheDocument()
})
+ it('should keep provider credential metadata display-only without dirtying the composer draft', () => {
+ toolProviderState.builtInTools = [duckDuckGoProvider]
+ const { store } = renderAgentToolsWithStore(reflectedUnauthorizedNoCredentialDraft)
+
+ expect(screen.getByRole('button', {
+ name: 'DuckDuckGo',
+ })).toBeInTheDocument()
+ expect(screen.queryByText('tools.notAuthorized')).not.toBeInTheDocument()
+ expect(store.get(agentComposerDraftAtom).tools[0]).toMatchObject({
+ credentialType: 'unauthorized',
+ credentialVariant: 'unauthorized',
+ })
+ expect(store.get(isAgentComposerDirtyAtom)).toBe(false)
+ })
+
it('should open provider tool settings with catalog icon and parameters', async () => {
const user = userEvent.setup()
toolProviderState.builtInTools = [duckDuckGoProvider]
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
index 61dfcc1b9f9..20cbb247888 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
@@ -7,7 +7,7 @@ import type { ToolWithProvider } from '@/app/components/workflow/types'
import type { AgentCliTool, AgentProviderTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ToolPickerContent } from '@/app/components/workflow/block-selector/tool-picker'
import { useGetLanguage } from '@/context/i18n'
@@ -340,7 +340,6 @@ export function AgentTools() {
settingTarget,
isCliToolDialogOpen,
editingCliTool,
- setTools,
setToolOpen,
setSettingTarget,
addTools,
@@ -358,43 +357,52 @@ export function AgentTools() {
[tools],
)
const displayTools = useDisplayTools(visibleTools, providerById)
- const displayToolById = useMemo(
- () => new Map(displayTools.map(tool => [tool.id, tool])),
- [displayTools],
- )
- useEffect(() => {
- if (readOnly)
- return
-
- let shouldSyncCredentials = false
- const nextTools = tools.map((tool) => {
- const displayTool = displayToolById.get(tool.id)
-
- if (tool.kind !== 'provider' || displayTool?.kind !== 'provider')
- return tool
-
- if (
- tool.allowDelete === displayTool.allowDelete
- && tool.credentialKey === displayTool.credentialKey
- && tool.credentialType === displayTool.credentialType
- && tool.credentialVariant === displayTool.credentialVariant
- ) {
- return tool
- }
-
- shouldSyncCredentials = true
- return {
- ...tool,
- allowDelete: displayTool.allowDelete,
- credentialKey: displayTool.credentialKey,
- credentialType: displayTool.credentialType,
- credentialVariant: displayTool.credentialVariant,
- }
- })
-
- if (shouldSyncCredentials)
- setTools(nextTools)
- }, [displayToolById, readOnly, setTools, tools])
+ /*
+ * knip-ignore-start
+ * Keep this disabled sync logic while backend credential snapshots are being investigated.
+ * Re-enabling it writes catalog-derived credential metadata into the composer draft on page entry.
+ * That can mark a published agent as locally dirty before the user changes anything.
+ *
+ * const displayToolById = useMemo(
+ * () => new Map(displayTools.map(tool => [tool.id, tool])),
+ * [displayTools],
+ * )
+ *
+ * useEffect(() => {
+ * if (readOnly)
+ * return
+ *
+ * let shouldSyncCredentials = false
+ * const nextTools = tools.map((tool) => {
+ * const displayTool = displayToolById.get(tool.id)
+ *
+ * if (tool.kind !== 'provider' || displayTool?.kind !== 'provider')
+ * return tool
+ *
+ * if (
+ * tool.allowDelete === displayTool.allowDelete
+ * && tool.credentialKey === displayTool.credentialKey
+ * && tool.credentialType === displayTool.credentialType
+ * && tool.credentialVariant === displayTool.credentialVariant
+ * ) {
+ * return tool
+ * }
+ *
+ * shouldSyncCredentials = true
+ * return {
+ * ...tool,
+ * allowDelete: displayTool.allowDelete,
+ * credentialKey: displayTool.credentialKey,
+ * credentialType: displayTool.credentialType,
+ * credentialVariant: displayTool.credentialVariant,
+ * }
+ * })
+ *
+ * if (shouldSyncCredentials)
+ * setTools(nextTools)
+ * }, [displayToolById, readOnly, setTools, tools])
+ * knip-ignore-end
+ */
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
const openCliToolDialogFromPrompt = useCallback((options?: AgentOrchestrateAddActionOptions) => {
promptAddCallbackRef.current = options?.onAdded
@@ -414,7 +422,7 @@ export function AgentTools() {
}, [handleCliDialogOpenChange])
useRegisterAgentOrchestrateAddAction(
'cli',
- ENABLE_AGENT_CLI_TOOLS ? openCliToolDialogFromPrompt : () => {},
+ ENABLE_AGENT_CLI_TOOLS ? openCliToolDialogFromPrompt : () => { },
)
const toolsTip = t('agentDetail.configure.tools.tip')
const toolsListId = 'agent-configure-tools-list'
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.ts
deleted file mode 100644
index 4c6a473103b..00000000000
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
-
-export function countAgentFileNodes(files: AgentFileNode[]): number {
- return files.reduce((count, file) => count + 1 + (file.children ? countAgentFileNodes(file.children) : 0), 0)
-}
-
-/**
- * @public
- */
-// TODO: Remove this marker after the first file selector is wired.
-export function getFirstAgentFileId(files: AgentFileNode[]): string | undefined {
- for (const file of files) {
- if (!file.children?.length)
- return file.id
-
- const childFileId = getFirstAgentFileId(file.children)
- if (childFileId)
- return childFileId
- }
-}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
index 599654c5245..c626e2fc813 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
@@ -1,10 +1,12 @@
import type { ComponentProps } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { createStore, Provider as JotaiProvider } from 'jotai'
+import { useState } from 'react'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
+import { consoleQuery } from '@/service/client'
import { TransferMethod } from '@/types/app'
import { AgentChatRuntime } from '../chat-runtime'
@@ -13,27 +15,43 @@ const handleSendMock = vi.hoisted(() => vi.fn())
const stopCallbackRef = vi.hoisted(() => ({
current: undefined as undefined | ((taskId: string) => void),
}))
+const sendResultRef = vi.hoisted(() => ({
+ current: undefined as unknown,
+}))
const chatMessagesGetMock = vi.hoisted(() => vi.fn())
const suggestedQuestionsGetMock = vi.hoisted(() => vi.fn())
const stopPostMock = vi.hoisted(() => vi.fn())
-vi.mock('@/next/dynamic', () => ({
- default: () => function MockChat(props: {
- onSend: (message: string) => void
- onStopResponding: () => void
- }) {
- return (
- <div>
- <button type="button" onClick={() => props.onSend('hello')}>
- send
- </button>
- <button type="button" onClick={props.onStopResponding}>
- stop
- </button>
- </div>
- )
- },
-}))
+vi.mock('@/next/dynamic', async () => {
+ const { useState } = await import('react')
+
+ return {
+ default: () => function MockChat(props: {
+ onSend: (message: string) => unknown
+ onStopResponding: () => void
+ }) {
+ const [sent, setSent] = useState(false)
+
+ return (
+ <div>
+ <span>{`sessionSent:${sent ? 'yes' : 'no'}`}</span>
+ <button
+ type="button"
+ onClick={() => {
+ setSent(true)
+ sendResultRef.current = props.onSend('hello')
+ }}
+ >
+ send
+ </button>
+ <button type="button" onClick={props.onStopResponding}>
+ stop
+ </button>
+ </div>
+ )
+ },
+ }
+})
vi.mock('@/app/components/base/chat/chat/hooks', () => ({
useChat: useChatMock.mockImplementation((
@@ -83,27 +101,47 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()
}),
}))
-vi.mock('@/service/client', () => ({
- consoleClient: {
- agent: {
- byAgentId: {
- chatMessages: {
- get: chatMessagesGetMock,
- byMessageId: {
- suggestedQuestions: {
- get: suggestedQuestionsGetMock,
+vi.mock('@/service/client', async () => {
+ const { skipToken } = await import('@tanstack/react-query')
+ const getChatMessagesQueryKey = (input: unknown) => ['agent-chat-conversation-messages', input]
+
+ return {
+ consoleClient: {
+ agent: {
+ byAgentId: {
+ chatMessages: {
+ get: chatMessagesGetMock,
+ byMessageId: {
+ suggestedQuestions: {
+ get: suggestedQuestionsGetMock,
+ },
+ },
+ byTaskId: {
+ stop: {
+ post: stopPostMock,
+ },
},
},
- byTaskId: {
- stop: {
- post: stopPostMock,
+ },
+ },
+ },
+ consoleQuery: {
+ agent: {
+ byAgentId: {
+ chatMessages: {
+ get: {
+ queryKey: ({ input }: { input: unknown }) => getChatMessagesQueryKey(input),
+ queryOptions: ({ input }: { input: unknown }) => ({
+ queryKey: getChatMessagesQueryKey(input),
+ queryFn: input === skipToken ? skipToken : () => chatMessagesGetMock(input),
+ }),
},
},
},
},
},
- },
-}))
+ }
+})
function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentChatRuntime>>) {
const store = createStore()
@@ -120,22 +158,112 @@ function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentChatRuntim
})
store.set(agentComposerPromptAtom, 'You are helpful.')
+ return {
+ queryClient,
+ ...render(
+ <QueryClientProvider client={queryClient}>
+ <JotaiProvider store={store}>
+ <AgentChatRuntime
+ agentId="agent-1"
+ clearChatList={false}
+ inputPlaceholder="Message agent"
+ renderEmptyState={() => null}
+ onClearChatListChange={vi.fn()}
+ {...props}
+ />
+ </JotaiProvider>
+ </QueryClientProvider>,
+ ),
+ }
+}
+
+function RuntimeConversationHarness() {
+ const [conversationId, setConversationId] = useState<string | null>(null)
+
+ return (
+ <AgentChatRuntime
+ agentId="agent-1"
+ clearChatList={false}
+ conversationId={conversationId}
+ inputPlaceholder="Message agent"
+ renderEmptyState={() => null}
+ onClearChatListChange={vi.fn()}
+ onConversationIdChange={setConversationId}
+ />
+ )
+}
+
+function RuntimeClearCommandHarness({
+ inputPlaceholder,
+}: {
+ inputPlaceholder: string
+}) {
+ const [clearChatList, setClearChatList] = useState(true)
+
+ return (
+ <AgentChatRuntime
+ agentId="agent-1"
+ clearChatList={clearChatList}
+ inputPlaceholder={inputPlaceholder}
+ renderEmptyState={() => null}
+ onClearChatListChange={setClearChatList}
+ />
+ )
+}
+
+function renderPreviewChatWithConversationHarness() {
+ const store = createStore()
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ })
+ store.set(agentComposerModelAtom, {
+ provider: 'openai',
+ model: 'gpt-4',
+ })
+ store.set(agentComposerPromptAtom, 'You are helpful.')
+
return render(
<QueryClientProvider client={queryClient}>
<JotaiProvider store={store}>
- <AgentChatRuntime
- agentId="agent-1"
- clearChatList={false}
- inputPlaceholder="Message agent"
- renderEmptyState={() => null}
- onClearChatListChange={vi.fn()}
- {...props}
- />
+ <RuntimeConversationHarness />
</JotaiProvider>
</QueryClientProvider>,
)
}
+function renderPreviewChatWithClearCommandHarness() {
+ const store = createStore()
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ })
+ store.set(agentComposerModelAtom, {
+ provider: 'openai',
+ model: 'gpt-4',
+ })
+ store.set(agentComposerPromptAtom, 'You are helpful.')
+
+ const renderHarness = (inputPlaceholder: string) => (
+ <QueryClientProvider client={queryClient}>
+ <JotaiProvider store={store}>
+ <RuntimeClearCommandHarness inputPlaceholder={inputPlaceholder} />
+ </JotaiProvider>
+ </QueryClientProvider>
+ )
+
+ return {
+ ...render(renderHarness('Message agent')),
+ renderHarness,
+ }
+}
+
describe('AgentPreviewChat', () => {
beforeEach(() => {
useChatMock.mockClear()
@@ -144,6 +272,7 @@ describe('AgentPreviewChat', () => {
suggestedQuestionsGetMock.mockResolvedValue({ data: [] })
stopPostMock.mockResolvedValue({ result: 'success' })
stopCallbackRef.current = undefined
+ sendResultRef.current = undefined
})
it('should initialize preview chat with the stable debug conversation history', async () => {
@@ -258,6 +387,103 @@ describe('AgentPreviewChat', () => {
})
})
+ it('should sync the completed conversation history into the query cache', async () => {
+ const conversationMessagesResponse = {
+ data: [
+ {
+ id: 'message-after-send',
+ conversation_id: 'conversation-1',
+ query: 'hello',
+ answer: 'hi',
+ inputs: {},
+ message: [],
+ message_files: [],
+ agent_thoughts: [],
+ feedbacks: [],
+ answer_tokens: 1,
+ message_tokens: 1,
+ provider_response_latency: 1,
+ status: 'success',
+ from_source: 'console',
+ },
+ ],
+ }
+ chatMessagesGetMock.mockResolvedValue(conversationMessagesResponse)
+ const { queryClient } = renderPreviewChat()
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ const callbacks = handleSendMock.mock.calls.at(0)?.[2]
+
+ await callbacks.onGetConversationMessages('conversation-1')
+
+ expect(queryClient.getQueryData(consoleQuery.agent.byAgentId.chatMessages.get.queryKey({
+ input: {
+ params: {
+ agent_id: 'agent-1',
+ },
+ query: {
+ conversation_id: 'conversation-1',
+ },
+ },
+ }))).toBe(conversationMessagesResponse)
+ })
+
+ it('should notify the owner when a send settles with an error', async () => {
+ const onSendInterrupted = vi.fn()
+ renderPreviewChat({
+ onSendInterrupted,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ const callbacks = handleSendMock.mock.calls.at(0)?.[2]
+
+ act(() => {
+ callbacks.onSendSettled(true)
+ })
+
+ expect(onSendInterrupted).toHaveBeenCalledTimes(1)
+ })
+
+ it('should notify the owner when stopping a responding send', async () => {
+ const onSendInterrupted = vi.fn()
+ renderPreviewChat({
+ onSendInterrupted,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'stop' }))
+
+ expect(onSendInterrupted).toHaveBeenCalledTimes(1)
+ expect(stopPostMock).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ task_id: 'task-1',
+ },
+ })
+ })
+
+ it('should notify the owner once when a stopped send later settles with an error', async () => {
+ const onSendInterrupted = vi.fn()
+ renderPreviewChat({
+ onSendInterrupted,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ const callbacks = handleSendMock.mock.calls.at(0)?.[2]
+
+ fireEvent.click(screen.getByRole('button', { name: 'stop' }))
+ act(() => {
+ callbacks.onSendSettled(true)
+ })
+
+ expect(onSendInterrupted).toHaveBeenCalledTimes(1)
+ })
+
it('should not send preview chat when draft save fails', async () => {
const saveDraftBeforeRun = vi.fn().mockRejectedValue(new Error('save failed'))
renderPreviewChat({
@@ -267,6 +493,7 @@ describe('AgentPreviewChat', () => {
fireEvent.click(screen.getByRole('button', { name: 'send' }))
await waitFor(() => expect(saveDraftBeforeRun).toHaveBeenCalledTimes(1))
+ await expect(sendResultRef.current).resolves.toBe(false)
expect(handleSendMock).not.toHaveBeenCalled()
})
@@ -287,6 +514,92 @@ describe('AgentPreviewChat', () => {
)
})
+ it('should send build chat inputs from the prepared build draft snapshot', async () => {
+ const saveDraftBeforeRun = vi.fn().mockResolvedValue({
+ app_variables: [
+ {
+ name: 'city',
+ type: 'text-input',
+ default: 'Paris',
+ required: true,
+ },
+ ],
+ model: {
+ model_provider: 'openai',
+ model: 'gpt-4',
+ },
+ prompt: {
+ system_prompt: 'Build draft prompt',
+ },
+ })
+ renderPreviewChat({
+ agentSoulConfig: {
+ app_variables: [
+ {
+ name: 'city',
+ type: 'text-input',
+ default: 'London',
+ required: true,
+ },
+ ],
+ },
+ draftType: 'debug_build',
+ onSaveDraftBeforeRun: saveDraftBeforeRun,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ expect(handleSendMock).toHaveBeenCalledWith(
+ 'agent/agent-1/chat-messages',
+ expect.objectContaining({
+ draft_type: 'debug_build',
+ inputs: {
+ city: 'Paris',
+ },
+ overrideInputsForm: [
+ expect.objectContaining({
+ variable: 'city',
+ default: 'Paris',
+ }),
+ ],
+ }),
+ expect.any(Object),
+ )
+ })
+
+ it('should keep the current chat session visible when a sent message creates a conversation', async () => {
+ chatMessagesGetMock.mockReturnValue(new Promise(() => undefined))
+ renderPreviewChatWithConversationHarness()
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ const callbacks = handleSendMock.mock.calls.at(0)?.[2]
+
+ await act(async () => {
+ callbacks.onConversationComplete('conversation-created-by-send')
+ })
+
+ expect(screen.getByRole('button', { name: 'send' })).toBeInTheDocument()
+ expect(screen.getByText('sessionSent:yes')).toBeInTheDocument()
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ })
+
+ it('should keep the reset command acknowledgement stable while clear chat is pending', async () => {
+ const { renderHarness, rerender } = renderPreviewChatWithClearCommandHarness()
+
+ await waitFor(() => expect(useChatMock).toHaveBeenCalled())
+ const firstResetAcknowledgement = useChatMock.mock.calls.at(-1)?.[5]
+
+ rerender(renderHarness('Message agent again'))
+
+ await waitFor(() => expect(useChatMock.mock.calls.length).toBeGreaterThan(1))
+ const secondResetAcknowledgement = useChatMock.mock.calls.at(-1)?.[5]
+
+ expect(secondResetAcknowledgement).toBe(firstResetAcknowledgement)
+ })
+
it('should keep preview file upload disabled by default', async () => {
renderPreviewChat()
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx
index 7f0465f9b01..4bb7ca8a226 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx
@@ -9,6 +9,7 @@ function renderHeader({
onToggleChatFeatures = vi.fn(),
onOpenWorkingDirectory = vi.fn(),
onRefresh = vi.fn(),
+ refreshDisabled = false,
}: {
mode?: 'build' | 'preview'
previewEnabled?: boolean
@@ -16,6 +17,7 @@ function renderHeader({
onToggleChatFeatures?: () => void
onOpenWorkingDirectory?: () => void
onRefresh?: () => void
+ refreshDisabled?: boolean
} = {}) {
render(
<AgentPreviewHeader
@@ -26,6 +28,7 @@ function renderHeader({
onToggleChatFeatures={onToggleChatFeatures}
onOpenWorkingDirectory={onOpenWorkingDirectory}
onRefresh={onRefresh}
+ refreshDisabled={refreshDisabled}
/>,
)
}
@@ -45,6 +48,16 @@ describe('AgentPreviewHeader', () => {
expect(onRefresh).toHaveBeenCalledTimes(1)
})
+ it('should not emit refresh when the restart button is disabled', async () => {
+ const user = userEvent.setup()
+ const onRefresh = vi.fn()
+ renderHeader({ mode: 'build', onRefresh, refreshDisabled: true })
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.preview.restart' }))
+
+ expect(onRefresh).not.toHaveBeenCalled()
+ })
+
it('should show chat features in build mode', async () => {
const user = userEvent.setup()
const onToggleChatFeatures = vi.fn()
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
index 206c46732f7..f0b5a14691a 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
@@ -13,10 +13,17 @@ const versions: AgentConfigSnapshotSummaryResponse[] = [
{
id: 'version-1',
version: 1,
- version_note: 'Initial release',
+ version_note: null,
created_at: 1710000000,
created_by: 'Bob',
},
+ {
+ id: 'version-0',
+ version: 0,
+ version_note: 'Initial release',
+ created_at: 1709999900,
+ created_by: 'user-1',
+ },
]
vi.mock('@tanstack/react-query', async (importOriginal) => {
@@ -51,6 +58,17 @@ vi.mock('@/service/client', () => ({
},
}))
+vi.mock('@/context/app-context', () => ({
+ useSelector: <T,>(selector: (state: { userProfile: { id: string, name: string, email: string } }) => T) =>
+ selector({
+ userProfile: {
+ id: 'user-1',
+ name: 'Alice',
+ email: '[email protected]',
+ },
+ }),
+}))
+
describe('AgentPreviewVersionsPanel', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -71,7 +89,7 @@ describe('AgentPreviewVersionsPanel', () => {
fireEvent.click(screen.getByRole('button', { name: /Initial release/i }))
- expect(handleSelectVersion).toHaveBeenCalledWith('version-1')
+ expect(handleSelectVersion).toHaveBeenCalledWith('version-0')
})
it('should notify null when the current draft row is clicked', () => {
@@ -91,4 +109,41 @@ describe('AgentPreviewVersionsPanel', () => {
expect(handleSelectVersion).toHaveBeenCalledWith(null)
})
})
+
+ describe('Version filter', () => {
+ it('should show filter options when the filter trigger is clicked', () => {
+ render(
+ <AgentPreviewVersionsPanel
+ agentId="agent-1"
+ activeVersionId="version-2"
+ onSelectVersion={vi.fn()}
+ onClose={vi.fn()}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /filter/i }))
+
+ expect(screen.getByRole('button', { name: /all/i })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /onlyYours/i })).toBeInTheDocument()
+ expect(screen.queryByText(/onlyShowNamedVersions/i)).not.toBeInTheDocument()
+ })
+
+ it('should only show current user versions when only yours is selected', () => {
+ render(
+ <AgentPreviewVersionsPanel
+ agentId="agent-1"
+ activeVersionId="version-2"
+ onSelectVersion={vi.fn()}
+ onClose={vi.fn()}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /filter/i }))
+ fireEvent.click(screen.getByRole('button', { name: /onlyYours/i }))
+
+ expect(screen.getByRole('button', { name: /Published update/i })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Initial release/i })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /versionName.*1/i })).not.toBeInTheDocument()
+ })
+ })
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx
index bb57bff650e..2f5ff6c74f3 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx
@@ -1,55 +1,5 @@
import { cn } from '@langgenius/dify-ui/cn'
-
-const buildPanelGridColumnCount = 384
-const buildPanelGridRowCount = 32
-
-function getBuildPanelGridCellOpacity(row: number, column: number) {
- const seed = Math.sin((row + 1) * 12.9898 + (column + 1) * 78.233) * 43758.5453
- const noise = seed - Math.floor(seed)
- const verticalProgress = row / (buildPanelGridRowCount - 1)
- const densityThreshold = 0.26 + verticalProgress * 0.72
- const horizontalWeight = Math.min(1, column / 160)
- const verticalWeight = (1 - verticalProgress) ** 1.7
-
- if (noise < densityThreshold)
- return 0
-
- return Number(Math.min(0.272, (0.032 + noise * 0.058 + horizontalWeight * 0.09) * verticalWeight).toFixed(3))
-}
-
-const buildPanelGridCells = Array.from(
- { length: buildPanelGridColumnCount * buildPanelGridRowCount },
- (_, index) => {
- const row = Math.floor(index / buildPanelGridColumnCount)
- const column = index % buildPanelGridColumnCount
- const opacity = getBuildPanelGridCellOpacity(row, column)
-
- return {
- id: `build-panel-grid-cell-${row}-${column}`,
- column: column + 1,
- opacity,
- row: row + 1,
- }
- },
-).filter(cell => cell.opacity > 0)
-
-function AgentBuildPanelGrid({
- className,
-}: {
- className?: string
-}) {
- return (
- <div className={cn('grid grid-cols-[repeat(384,4px)] grid-rows-[repeat(32,4px)] gap-0.5 opacity-70', className)}>
- {buildPanelGridCells.map(cell => (
- <span
- key={cell.id}
- className="rounded-[1px] bg-[#98A2B2]"
- style={{ gridColumn: `${cell.column}`, gridRow: `${cell.row}`, opacity: cell.opacity }}
- />
- ))}
- </div>
- )
-}
+import { AgentBuildGridTexture } from '../build-grid-texture'
export function AgentBuildPanelBackground({
visible,
@@ -64,8 +14,8 @@ export function AgentBuildPanelBackground({
visible && 'opacity-100',
)}
>
- <AgentBuildPanelGrid className="absolute top-0 left-0" />
- <AgentBuildPanelGrid className="absolute bottom-0 left-0 origin-center scale-y-[-1]" />
+ <AgentBuildGridTexture className="absolute top-0 left-0" />
+ <AgentBuildGridTexture className="absolute bottom-0 left-0 origin-center scale-y-[-1]" />
</div>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx
index 490f58bdb28..61d7259d665 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx
@@ -80,12 +80,15 @@ function AgentChatFeaturesPanelContent({
const featuresStore = useFeaturesStore()
const setAppFeatures = useSetAppFeatures()
const handleChange = useCallback(() => {
+ if (disabled)
+ return
+
const features = featuresStore?.getState().features
if (!features)
return
setAppFeatures(currentAppFeatures => toAppFeatures(features, currentAppFeatures ?? appFeatures))
- }, [appFeatures, featuresStore, setAppFeatures])
+ }, [appFeatures, disabled, featuresStore, setAppFeatures])
return (
<NewFeaturePanel
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx
index e48f23c92d4..7fe67be6972 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx
@@ -11,19 +11,19 @@ import type {
import type {
ReactNode,
} from 'react'
-import type { FeedbackType, IChatItem, ThoughtItem } from '@/app/components/base/chat/chat/type'
+import type { FeedbackType, IChatItem, InputForm, ThoughtItem } from '@/app/components/base/chat/chat/type'
import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '@/app/components/base/chat/types'
import type { FileUpload } from '@/app/components/base/features/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
-import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { AgentComposerModel } from '@/features/agent-v2/agent-composer/form-state'
import type { Inputs } from '@/models/debug'
import type { MessageRating } from '@/models/log'
import type { FileResponse } from '@/types/workflow'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
-import { useQuery } from '@tanstack/react-query'
+import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useCallback, useMemo } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import ChatInputArea from '@/app/components/base/chat/chat/chat-input-area'
import { useChat } from '@/app/components/base/chat/chat/hooks'
import { buildChatItemTree, getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'
@@ -40,7 +40,7 @@ import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/stor
import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import { PromptMode } from '@/models/debug'
import dynamic from '@/next/dynamic'
-import { consoleClient } from '@/service/client'
+import { consoleClient, consoleQuery } from '@/service/client'
import { AgentStrategy, ModelModeType, RETRIEVE_TYPE, TransferMethod } from '@/types/app'
const Chat = dynamic(() => import('@/app/components/base/chat/chat'), { ssr: false })
@@ -155,6 +155,15 @@ const toInputForm = (variable: NonNullable<AgentSoulConfig['app_variables']>[num
}
}
+const getAgentSoulInputsForm = (agentSoulConfig?: AgentSoulConfig) => (agentSoulConfig?.app_variables ?? []).map(toInputForm)
+
+const getAgentSoulInputs = (inputsForm: InputForm[]) => {
+ return inputsForm.reduce<Inputs>((acc, input) => {
+ acc[input.variable] = (input.default ?? '') as Inputs[string]
+ return acc
+ }, {})
+}
+
const toAgentTool = (tool: AgentSoulDifyToolConfig) => ({
provider_id: tool.provider_id ?? tool.provider ?? tool.plugin_id ?? '',
provider_type: tool.provider_type ?? 'builtin',
@@ -215,17 +224,6 @@ const stopAgentChatMessageResponding = (agentId: string, taskId: string) => {
})
}
-const fetchAgentConversationMessages = (agentId: string, conversationId: string) => {
- return consoleClient.agent.byAgentId.chatMessages.get({
- params: {
- agent_id: agentId,
- },
- query: {
- conversation_id: conversationId,
- },
- })
-}
-
const toFileResponse = (file: NonNullable<MessageDetailResponse['message_files']>[number]): FileResponse => ({
related_id: file.id ?? file.upload_file_id,
extension: '',
@@ -287,6 +285,16 @@ const getAgentDebugMessageAnswer = (message: MessageDetailResponse) => {
return message.answer ?? ''
}
+function getLastWorkflowRunId(messages: MessageDetailResponse[]) {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const workflowRunId = messages[index]?.workflow_run_id
+ if (workflowRunId)
+ return workflowRunId
+ }
+
+ return null
+}
+
function getFormattedAgentDebugChatTree(messages: MessageDetailResponse[]): ChatItemInTree[] {
const chatList: IChatItem[] = []
@@ -350,10 +358,10 @@ const buildChatConfig = ({
prompt,
}: {
agentSoulConfig?: AgentSoulConfig
- currentModel?: DefaultModel
+ currentModel?: AgentComposerModel
prompt: string
}): AgentPreviewChatConfig => {
- const modelSettings = getModelSettings(agentSoulConfig)
+ const modelSettings = currentModel?.model_settings ?? getModelSettings(agentSoulConfig)
const appFeatures = agentSoulConfig?.app_features ?? {}
const difyTools = agentSoulConfig?.tools?.dify_tools ?? []
const cliTools = ENABLE_AGENT_CLI_TOOLS ? (agentSoulConfig?.tools?.cli_tools ?? []) : []
@@ -443,9 +451,11 @@ export type AgentChatRuntimeProps = {
sendButtonLabel?: string
renderEmptyState: (props: AgentChatRuntimeEmptyStateProps) => ReactNode
onClearChatListChange: (clearChatList: boolean) => void
- onConversationComplete?: (conversationId: string) => void
+ onConversationComplete?: (conversationId: string, workflowRunId?: string) => void
onConversationIdChange?: (conversationId: string) => void
- onSaveDraftBeforeRun?: () => Promise<void>
+ onWorkflowRunIdChange?: (workflowRunId: string | null) => void
+ onSaveDraftBeforeRun?: () => Promise<AgentSoulConfig | void>
+ onSendInterrupted?: () => void
}
export function AgentChatRuntime({
@@ -464,29 +474,54 @@ export function AgentChatRuntime({
onClearChatListChange,
onConversationComplete,
onConversationIdChange,
+ onWorkflowRunIdChange,
+ onSendInterrupted,
onSaveDraftBeforeRun,
}: AgentChatRuntimeProps) {
- const historyQuery = useQuery({
- queryKey: ['agent-chat-conversation-messages', agentId, conversationId],
- queryFn: () => fetchAgentConversationMessages(agentId, conversationId!),
- enabled: !!conversationId,
- })
+ const [currentSessionConversationId, setCurrentSessionConversationId] = useState<string | null>(null)
+ const handleClearChatListChange = useCallback((nextClearChatList: boolean) => {
+ if (!nextClearChatList)
+ setCurrentSessionConversationId(null)
+ onClearChatListChange(nextClearChatList)
+ }, [onClearChatListChange])
+ const historyQuery = useQuery(consoleQuery.agent.byAgentId.chatMessages.get.queryOptions({
+ input: conversationId
+ ? {
+ params: {
+ agent_id: agentId,
+ },
+ query: {
+ conversation_id: conversationId,
+ },
+ }
+ : skipToken,
+ }))
+ const conversationBelongsToCurrentSession = !!conversationId && conversationId === currentSessionConversationId
const initialChatTree = useMemo(
() => getFormattedAgentDebugChatTree(historyQuery.data?.data ?? []),
[historyQuery.data?.data],
)
+ useEffect(() => {
+ if (!conversationId || !historyQuery.data)
+ return
- if (conversationId && historyQuery.isPending) {
+ onWorkflowRunIdChange?.(getLastWorkflowRunId(historyQuery.data.data ?? []))
+ }, [conversationId, historyQuery.data, onWorkflowRunIdChange])
+
+ if (conversationId && historyQuery.isPending && !conversationBelongsToCurrentSession) {
return (
<div className="flex h-full items-center justify-center">
<Loading type="app" />
</div>
)
}
+ const chatSessionKey = !conversationId || conversationBelongsToCurrentSession
+ ? 'current-session'
+ : `${conversationId}-${historyQuery.dataUpdatedAt}`
return (
<AgentPreviewChatSession
- key={`${conversationId ?? 'new'}-${historyQuery.dataUpdatedAt}`}
+ key={chatSessionKey}
agentId={agentId}
agentIcon={agentIcon}
agentIconBackground={agentIconBackground}
@@ -500,9 +535,11 @@ export function AgentChatRuntime({
inputPlaceholder={inputPlaceholder}
sendButtonLabel={sendButtonLabel}
renderEmptyState={renderEmptyState}
- onClearChatListChange={onClearChatListChange}
+ onClearChatListChange={handleClearChatListChange}
onConversationComplete={onConversationComplete}
onConversationIdChange={onConversationIdChange}
+ onCurrentSessionConversationIdChange={setCurrentSessionConversationId}
+ onSendInterrupted={onSendInterrupted}
onSaveDraftBeforeRun={onSaveDraftBeforeRun}
/>
)
@@ -525,6 +562,8 @@ function AgentPreviewChatSession({
onClearChatListChange,
onConversationComplete,
onConversationIdChange,
+ onCurrentSessionConversationIdChange,
+ onSendInterrupted,
onSaveDraftBeforeRun,
}: {
agentId: string
@@ -541,10 +580,13 @@ function AgentPreviewChatSession({
sendButtonLabel?: string
renderEmptyState: (props: AgentChatRuntimeEmptyStateProps) => ReactNode
onClearChatListChange: (clearChatList: boolean) => void
- onConversationComplete?: (conversationId: string) => void
+ onConversationComplete?: (conversationId: string, workflowRunId?: string) => void
onConversationIdChange?: (conversationId: string) => void
- onSaveDraftBeforeRun?: () => Promise<void>
+ onCurrentSessionConversationIdChange: (conversationId: string) => void
+ onSaveDraftBeforeRun?: () => Promise<AgentSoulConfig | void>
+ onSendInterrupted?: () => void
}) {
+ const queryClient = useQueryClient()
const { userProfile } = useAppContext()
const prompt = useAtomValue(agentComposerPromptAtom)
const currentModel = useAtomValue(agentComposerModelAtom)
@@ -553,13 +595,16 @@ function AgentPreviewChatSession({
currentModel,
prompt,
}), [agentSoulConfig, currentModel, prompt])
- const inputsForm = useMemo(() => (agentSoulConfig?.app_variables ?? []).map(toInputForm), [agentSoulConfig?.app_variables])
- const inputs = useMemo(() => {
- return inputsForm.reduce<Inputs>((acc, input) => {
- acc[input.variable] = (input.default ?? '') as Inputs[string]
- return acc
- }, {})
- }, [inputsForm])
+ const inputsForm = useMemo(() => getAgentSoulInputsForm(agentSoulConfig), [agentSoulConfig])
+ const inputs = useMemo(() => getAgentSoulInputs(inputsForm), [inputsForm])
+ const sendInterruptedRef = useRef(false)
+ const notifySendInterrupted = useCallback(() => {
+ if (sendInterruptedRef.current)
+ return
+
+ sendInterruptedRef.current = true
+ onSendInterrupted?.()
+ }, [onSendInterrupted])
const {
textGenerationModelList,
} = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)
@@ -589,40 +634,78 @@ function AgentPreviewChatSession({
)
const doSend: OnSend = useCallback(async (message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {
+ sendInterruptedRef.current = false
+
try {
- await onSaveDraftBeforeRun?.()
+ const preparedAgentSoulConfig = await onSaveDraftBeforeRun?.()
+ const runtimeAgentSoulConfig = preparedAgentSoulConfig || agentSoulConfig
+ const runtimeInputsForm = preparedAgentSoulConfig ? getAgentSoulInputsForm(runtimeAgentSoulConfig) : inputsForm
+ const runtimeInputs = preparedAgentSoulConfig ? getAgentSoulInputs(runtimeInputsForm) : inputs
+ const runtimeConfig = preparedAgentSoulConfig
+ ? buildChatConfig({
+ agentSoulConfig: runtimeAgentSoulConfig,
+ currentModel: undefined,
+ prompt: runtimeAgentSoulConfig?.prompt?.system_prompt ?? '',
+ })
+ : config
+
+ const currentProvider = textGenerationModelList.find(item => item.provider === runtimeConfig.model.provider)
+ const selectedModel = currentProvider?.models.find(model => model.model === runtimeConfig.model.name)
+ const supportVision = selectedModel?.features?.includes(ModelFeatureEnum.vision)
+ const data: Record<string, unknown> = {
+ query: message,
+ inputs: runtimeInputs,
+ overrideInputsForm: runtimeInputsForm,
+ parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,
+ }
+ if (draftType)
+ data.draft_type = draftType
+
+ if (files?.length && supportVision)
+ data.files = files
+
+ handleSend(
+ `agent/${agentId}/chat-messages`,
+ data as Parameters<typeof handleSend>[1],
+ {
+ onGetConversationMessages: async (conversationId) => {
+ return queryClient.fetchQuery({
+ ...consoleQuery.agent.byAgentId.chatMessages.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ query: {
+ conversation_id: conversationId,
+ },
+ },
+ }),
+ staleTime: 0,
+ })
+ },
+ onGetSuggestedQuestions: responseItemId => fetchAgentSuggestedQuestions(agentId, responseItemId),
+ onConversationComplete: (completedConversationId, workflowRunId) => {
+ if (completedConversationId && completedConversationId !== conversationId)
+ onCurrentSessionConversationIdChange(completedConversationId)
+ onConversationIdChange?.(completedConversationId)
+ onConversationComplete?.(completedConversationId, workflowRunId)
+ },
+ onSendSettled: (hasError) => {
+ if (hasError)
+ notifySendInterrupted()
+ },
+ },
+ )
}
catch {
- return
+ return false
}
+ }, [agentId, agentSoulConfig, chatList, config, conversationId, draftType, handleSend, inputs, inputsForm, notifySendInterrupted, onConversationComplete, onConversationIdChange, onCurrentSessionConversationIdChange, onSaveDraftBeforeRun, queryClient, textGenerationModelList])
- const currentProvider = textGenerationModelList.find(item => item.provider === config.model.provider)
- const selectedModel = currentProvider?.models.find(model => model.model === config.model.name)
- const supportVision = selectedModel?.features?.includes(ModelFeatureEnum.vision)
- const data: Record<string, unknown> = {
- query: message,
- inputs,
- parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,
- }
- if (draftType)
- data.draft_type = draftType
-
- if (files?.length && supportVision)
- data.files = files
-
- handleSend(
- `agent/${agentId}/chat-messages`,
- data as Parameters<typeof handleSend>[1],
- {
- onGetConversationMessages: conversationId => fetchAgentConversationMessages(agentId, conversationId),
- onGetSuggestedQuestions: responseItemId => fetchAgentSuggestedQuestions(agentId, responseItemId),
- onConversationComplete: (conversationId) => {
- onConversationIdChange?.(conversationId)
- onConversationComplete?.(conversationId)
- },
- },
- )
- }, [agentId, chatList, config.model.name, config.model.provider, draftType, handleSend, inputs, onConversationComplete, onConversationIdChange, onSaveDraftBeforeRun, textGenerationModelList])
+ const doStopResponding = useCallback(() => {
+ handleStop()
+ notifySendInterrupted()
+ }, [handleStop, notifySendInterrupted])
const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {
const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)
@@ -685,7 +768,7 @@ function AgentPreviewChatSession({
inputsForm={inputsForm}
onRegenerate={doRegenerate}
switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}
- onStopResponding={handleStop}
+ onStopResponding={doStopResponding}
noChatInput={isEmptyChat}
showPromptLog
questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsx
new file mode 100644
index 00000000000..3e982083bdb
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsx
@@ -0,0 +1,83 @@
+'use client'
+
+import type { QueryClient } from '@tanstack/react-query'
+import type { ReactNode } from 'react'
+import type { AgentWorkingDirectorySource } from '../working-directory-panel'
+import { useState } from 'react'
+import { consoleQuery } from '@/service/client'
+import { AgentWorkingDirectoryPanel } from '../working-directory-panel'
+
+export function invalidateAgentWorkingDirectoryFiles({
+ appId,
+ conversationId,
+ nodeId,
+ queryClient,
+}: {
+ agentId: string
+ appId?: string
+ conversationId?: string | null
+ nodeId?: string
+ queryClient: QueryClient
+ workflowRunId?: string | null
+}) {
+ if (appId && nodeId) {
+ void queryClient.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflowRuns.byWorkflowRunId.agentNodes.byNodeId.sandbox.files.get.key({ type: 'query' }),
+ })
+ return
+ }
+
+ if (!conversationId)
+ return
+
+ void queryClient.invalidateQueries({
+ queryKey: consoleQuery.agent.byAgentId.sandbox.files.get.key({ type: 'query' }),
+ })
+}
+
+export function useAgentWorkingDirectoryPanel({
+ agentId,
+ appId,
+ conversationId,
+ nodeId,
+ workflowRunId,
+}: {
+ agentId: string
+ appId?: string
+ conversationId?: string | null
+ nodeId?: string
+ workflowRunId?: string | null
+}): {
+ closeWorkingDirectory: () => void
+ openWorkingDirectory: () => void
+ panel: ReactNode
+} {
+ const [open, setOpen] = useState(false)
+ const source: AgentWorkingDirectorySource = appId && nodeId
+ ? {
+ type: 'workflow-node',
+ appId,
+ conversationId,
+ nodeId,
+ workflowRunId,
+ }
+ : {
+ type: 'agent',
+ agentId,
+ conversationId,
+ }
+
+ return {
+ closeWorkingDirectory: () => setOpen(false),
+ openWorkingDirectory: () => setOpen(true),
+ panel: open
+ ? (
+ <AgentWorkingDirectoryPanel
+ source={source}
+ open={open}
+ onOpenChange={setOpen}
+ />
+ )
+ : null,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx
index 1455ec5e06b..ad461c5ff2d 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx
@@ -1,13 +1,11 @@
'use client'
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentConfigureConversationIds, AgentConfigureRightPanelMode } from '../../state'
import { useAgentPreviewSoulConfig } from '../../hooks'
import { AgentBuildChat } from './build-chat'
import { AgentPreviewChat } from './preview-chat'
-export type AgentConfigureRightPanelMode = 'build' | 'preview'
-export type AgentConfigureConversationIds = Record<AgentConfigureRightPanelMode, string | null>
-
export function AgentConfigureRightPanelChat({
agentSoulConfig,
conversationIds,
@@ -19,7 +17,7 @@ export function AgentConfigureRightPanelChat({
agentSoulConfig?: AgentSoulConfig
conversationIds: AgentConfigureConversationIds
mode: AgentConfigureRightPanelMode
- onConversationComplete?: (mode: AgentConfigureRightPanelMode) => void
+ onConversationComplete?: (mode: AgentConfigureRightPanelMode, conversationId: string, workflowRunId?: string) => void
onConversationIdChange: (mode: AgentConfigureRightPanelMode, conversationId: string) => void
}) {
const previewAgentSoulConfig = useAgentPreviewSoulConfig(agentSoulConfig)
@@ -27,8 +25,8 @@ export function AgentConfigureRightPanelChat({
const handleConversationIdChange = (newConversationId: string) => {
onConversationIdChange(mode, newConversationId)
}
- const handleConversationComplete = () => {
- onConversationComplete?.(mode)
+ const handleConversationComplete = (completedConversationId: string, workflowRunId?: string) => {
+ onConversationComplete?.(mode, completedConversationId, workflowRunId)
}
return mode === 'build'
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx
deleted file mode 100644
index 3369c94b576..00000000000
--- a/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-'use client'
-
-import type { ReactNode } from 'react'
-import { useState } from 'react'
-import { AgentWorkingDirectoryPanel } from './working-directory-panel'
-
-export function useAgentWorkingDirectoryPanel(): {
- closeWorkingDirectory: () => void
- openWorkingDirectory: () => void
- panel: ReactNode
-} {
- const [open, setOpen] = useState(false)
-
- return {
- closeWorkingDirectory: () => setOpen(false),
- openWorkingDirectory: () => setOpen(true),
- panel: (
- <AgentWorkingDirectoryPanel
- open={open}
- onOpenChange={setOpen}
- />
- ),
- }
-}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsx
deleted file mode 100644
index 329b6e6d2de..00000000000
--- a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-'use client'
-
-import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
-import { cn } from '@langgenius/dify-ui/cn'
-import { useQuery } from '@tanstack/react-query'
-import { useTranslation } from 'react-i18next'
-import useTimestamp from '@/hooks/use-timestamp'
-import { consoleQuery } from '@/service/client'
-
-type AgentPreviewVersionsPanelProps = {
- agentId: string
- activeVersionId?: string | null
- onSelectVersion: (versionId: string | null) => void
- onClose: () => void
-}
-
-function VersionTimelineDot({
- isActive,
- isFirst,
- isLast,
-}: {
- isActive: boolean
- isFirst: boolean
- isLast: boolean
-}) {
- return (
- <div className="relative flex w-[18px] shrink-0 justify-center pt-1.5">
- {!isFirst && <div className="absolute top-0 h-2 w-0.5 bg-divider-subtle" />}
- <span
- aria-hidden
- className={cn(
- 'relative z-1 size-2 rounded-full border-2 bg-components-panel-bg',
- isActive ? 'border-text-accent' : 'border-text-quaternary',
- )}
- />
- {!isLast && <div className="absolute top-3 bottom-[-18px] w-0.5 bg-divider-subtle" />}
- </div>
- )
-}
-
-function VersionMetadata({
- version,
-}: {
- version: AgentConfigSnapshotSummaryResponse
-}) {
- const { t } = useTranslation('agentV2')
- const { formatTime } = useTimestamp()
-
- if (version.created_at == null && !version.created_by)
- return null
-
- return (
- <p className="truncate system-xs-regular text-text-tertiary">
- {version.created_at != null && formatTime(version.created_at, t('roster.dateTimeFormat'))}
- {version.created_at != null && version.created_by && ' · '}
- {version.created_by}
- </p>
- )
-}
-
-function VersionItem({
- version,
- activeVersionId,
- isLatest,
- isFirst,
- isLast,
- onSelect,
-}: {
- version: AgentConfigSnapshotSummaryResponse
- activeVersionId?: string | null
- isLatest: boolean
- isFirst: boolean
- isLast: boolean
- onSelect: (versionId: string) => void
-}) {
- const { t } = useTranslation('agentV2')
- const { t: tWorkflow } = useTranslation('workflow')
- const isActive = version.id === activeVersionId
- const label = version.version_note || t('agentDetail.versionHistory.versionName', { version: version.version })
-
- return (
- <button
- type="button"
- aria-current={isActive ? 'true' : undefined}
- onClick={() => onSelect(version.id)}
- className={cn(
- 'group relative flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
- isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
- )}
- >
- <VersionTimelineDot isActive={isActive} isFirst={isFirst} isLast={isLast} />
- <div className="min-w-0 flex-1 py-0.5">
- <div className="flex min-w-0 items-center gap-1">
- <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>
- {label}
- </p>
- {isLatest && (
- <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-[5px] py-[3px] system-2xs-medium-uppercase text-text-accent-secondary">
- {tWorkflow('versionHistory.latest')}
- </span>
- )}
- </div>
- {isActive && version.summary && (
- <p className="mt-0.5 line-clamp-4 system-xs-regular text-text-secondary">
- {version.summary}
- </p>
- )}
- <VersionMetadata version={version} />
- </div>
- </button>
- )
-}
-
-function CurrentDraftItem({
- isActive,
- isLast,
- onSelect,
-}: {
- isActive: boolean
- isLast: boolean
- onSelect: () => void
-}) {
- const { t: tWorkflow } = useTranslation('workflow')
-
- return (
- <button
- type="button"
- aria-current={isActive ? 'true' : undefined}
- onClick={onSelect}
- className={cn(
- 'flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
- isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
- )}
- >
- <VersionTimelineDot isActive={isActive} isFirst isLast={isLast} />
- <div className="min-w-0 flex-1 py-1">
- <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>
- {tWorkflow('versionHistory.currentDraft')}
- </p>
- </div>
- </button>
- )
-}
-
-export function AgentPreviewVersionsPanel({
- agentId,
- activeVersionId,
- onSelectVersion,
- onClose,
-}: AgentPreviewVersionsPanelProps) {
- const { t } = useTranslation('agentV2')
- const { t: tCommon } = useTranslation('common')
- const { t: tWorkflow } = useTranslation('workflow')
- const versionsQuery = useQuery(consoleQuery.agent.byAgentId.versions.get.queryOptions({
- input: {
- params: {
- agent_id: agentId,
- },
- },
- }))
- const versions = versionsQuery.data?.data ?? []
- const latestVersionId = versions[0]?.id
-
- return (
- <aside className="flex h-full w-[268px] shrink-0 flex-col rounded-l-lg bg-components-panel-bg shadow-xl shadow-shadow-shadow-5">
- <div className="flex shrink-0 items-center gap-2 pt-3 pr-3 pl-4">
- <h2 className="min-w-0 flex-1 truncate system-xl-semibold text-text-primary">
- {tWorkflow('versionHistory.title')}
- </h2>
- <button
- type="button"
- aria-label={t('agentDetail.versionHistory.filter')}
- className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- >
- <span aria-hidden className="i-ri-filter-3-line size-4" />
- </button>
- <div className="h-3.5 w-px shrink-0 bg-divider-regular" />
- <button
- type="button"
- aria-label={tCommon('operation.close')}
- onClick={onClose}
- className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- >
- <span aria-hidden className="i-ri-close-line size-4" />
- </button>
- </div>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-3 py-2">
- {versionsQuery.isPending && (
- <div className="space-y-1">
- <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />
- <div className="h-18 animate-pulse rounded-lg bg-state-base-hover" />
- <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />
- </div>
- )}
- {!versionsQuery.isPending && versions.length === 0 && (
- <div className="rounded-lg border border-components-panel-border bg-components-panel-on-panel-item-bg px-3 py-6 text-center system-sm-regular text-text-tertiary">
- {t('agentDetail.versionHistory.empty')}
- </div>
- )}
- {!versionsQuery.isPending && versions.length > 0 && (
- <div className="flex flex-col gap-px">
- <CurrentDraftItem
- isActive={!activeVersionId}
- isLast={versions.length === 0}
- onSelect={() => onSelectVersion(null)}
- />
- {versions.map((version, index) => (
- <VersionItem
- key={version.id}
- version={version}
- activeVersionId={activeVersionId}
- isLatest={version.id === latestVersionId}
- isFirst={false}
- isLast={index === versions.length - 1}
- onSelect={onSelectVersion}
- />
- ))}
- </div>
- )}
- </div>
- </aside>
- )
-}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/current-draft-item.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/current-draft-item.tsx
new file mode 100644
index 00000000000..f3c7506ba5d
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/current-draft-item.tsx
@@ -0,0 +1,34 @@
+import { cn } from '@langgenius/dify-ui/cn'
+import { useTranslation } from 'react-i18next'
+import { VersionTimelineDot } from './version-timeline-dot'
+
+export function CurrentDraftItem({
+ isActive,
+ isLast,
+ onSelect,
+}: {
+ isActive: boolean
+ isLast: boolean
+ onSelect: () => void
+}) {
+ const { t: tWorkflow } = useTranslation('workflow')
+
+ return (
+ <button
+ type="button"
+ aria-current={isActive ? 'true' : undefined}
+ onClick={onSelect}
+ className={cn(
+ 'flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
+ isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
+ )}
+ >
+ <VersionTimelineDot isActive={isActive} isFirst isLast={isLast} />
+ <div className="min-w-0 flex-1 py-1">
+ <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>
+ {tWorkflow('versionHistory.currentDraft')}
+ </p>
+ </div>
+ </button>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/filter.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/filter.tsx
new file mode 100644
index 00000000000..9684398364b
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/filter.tsx
@@ -0,0 +1,89 @@
+'use client'
+
+import { cn } from '@langgenius/dify-ui/cn'
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@langgenius/dify-ui/popover'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export type AgentVersionFilter = 'all' | 'onlyYours'
+
+function FilterItem({
+ label,
+ selected,
+ onClick,
+}: {
+ label: string
+ selected: boolean
+ onClick: () => void
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="flex w-full cursor-pointer items-center justify-between gap-x-1 rounded-lg px-2 py-1.5 text-left hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ >
+ <span className="min-w-0 flex-1 truncate system-md-regular text-text-primary">{label}</span>
+ {selected && <span aria-hidden className="i-ri-check-line size-4 shrink-0 text-text-accent" />}
+ </button>
+ )
+}
+
+export function VersionFilter({
+ filterValue,
+ onFilterChange,
+}: {
+ filterValue: AgentVersionFilter
+ onFilterChange: (filterValue: AgentVersionFilter) => void
+}) {
+ const { t } = useTranslation('agentV2')
+ const { t: tWorkflow } = useTranslation('workflow')
+ const [open, setOpen] = useState(false)
+ const isFiltering = filterValue !== 'all'
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ nativeButton={false}
+ render={(
+ <button
+ type="button"
+ aria-label={t('agentDetail.versionHistory.filter')}
+ className={cn(
+ 'flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
+ isFiltering
+ ? 'bg-state-accent-active-alt text-text-accent'
+ : 'text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary',
+ )}
+ >
+ <span aria-hidden className="i-ri-filter-3-line size-4" />
+ </button>
+ )}
+ />
+ <PopoverContent
+ placement="bottom-end"
+ sideOffset={4}
+ alignOffset={55}
+ popupClassName="border-none bg-transparent shadow-none"
+ >
+ <div className="flex w-[248px] flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">
+ <div className="flex flex-col p-1">
+ <FilterItem
+ label={tWorkflow('versionHistory.filter.all')}
+ selected={filterValue === 'all'}
+ onClick={() => onFilterChange('all')}
+ />
+ <FilterItem
+ label={tWorkflow('versionHistory.filter.onlyYours')}
+ selected={filterValue === 'onlyYours'}
+ onClick={() => onFilterChange('onlyYours')}
+ />
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx
new file mode 100644
index 00000000000..50473b55f4d
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx
@@ -0,0 +1,118 @@
+'use client'
+
+import type { AgentVersionFilter } from './filter'
+import { useQuery } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSelector as useAppContextSelector } from '@/context/app-context'
+import { consoleQuery } from '@/service/client'
+import { CurrentDraftItem } from './current-draft-item'
+import { VersionFilter } from './filter'
+import { VersionFilterEmpty } from './version-filter-empty'
+import { VersionItem } from './version-item'
+
+type AgentPreviewVersionsPanelProps = {
+ agentId: string
+ activeVersionId?: string | null
+ onSelectVersion: (versionId: string | null) => void
+ onClose: () => void
+}
+
+export function AgentPreviewVersionsPanel({
+ agentId,
+ activeVersionId,
+ onSelectVersion,
+ onClose,
+}: AgentPreviewVersionsPanelProps) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const { t: tWorkflow } = useTranslation('workflow')
+ const userProfile = useAppContextSelector(state => state.userProfile)
+ const [filterValue, setFilterValue] = useState<AgentVersionFilter>('all')
+ const versionsQuery = useQuery(consoleQuery.agent.byAgentId.versions.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }))
+ const versions = versionsQuery.data?.data ?? []
+ const latestVersionId = versions[0]?.id
+ const currentUserCreatedByValues = new Set([
+ userProfile.id,
+ userProfile.name,
+ userProfile.email,
+ ].filter(Boolean))
+ const filteredVersions = versions.filter((version) => {
+ if (filterValue === 'onlyYours')
+ return !!version.created_by && currentUserCreatedByValues.has(version.created_by)
+
+ return true
+ })
+ const isFiltering = filterValue !== 'all'
+
+ const handleResetFilter = () => {
+ setFilterValue('all')
+ }
+
+ return (
+ <aside className="flex h-full w-[268px] shrink-0 flex-col rounded-l-lg bg-components-panel-bg shadow-xl shadow-shadow-shadow-5">
+ <div className="flex shrink-0 items-center gap-2 pt-3 pr-3 pl-4">
+ <h2 className="min-w-0 flex-1 truncate system-xl-semibold text-text-primary">
+ {tWorkflow('versionHistory.title')}
+ </h2>
+ <VersionFilter
+ filterValue={filterValue}
+ onFilterChange={setFilterValue}
+ />
+ <div className="h-3.5 w-px shrink-0 bg-divider-regular" />
+ <button
+ type="button"
+ aria-label={tCommon('operation.close')}
+ onClick={onClose}
+ className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ >
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-2">
+ {versionsQuery.isPending && (
+ <div className="space-y-1">
+ <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />
+ <div className="h-18 animate-pulse rounded-lg bg-state-base-hover" />
+ <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />
+ </div>
+ )}
+ {!versionsQuery.isPending && versions.length === 0 && (
+ <div className="rounded-lg border border-components-panel-border bg-components-panel-on-panel-item-bg px-3 py-6 text-center system-sm-regular text-text-tertiary">
+ {t('agentDetail.versionHistory.empty')}
+ </div>
+ )}
+ {!versionsQuery.isPending && versions.length > 0 && (
+ <div className="flex flex-col gap-px">
+ <CurrentDraftItem
+ isActive={!activeVersionId}
+ isLast={filteredVersions.length === 0}
+ onSelect={() => onSelectVersion(null)}
+ />
+ {filteredVersions.length === 0 && isFiltering && (
+ <VersionFilterEmpty onReset={handleResetFilter} />
+ )}
+ {filteredVersions.map((version, index) => (
+ <VersionItem
+ key={version.id}
+ version={version}
+ activeVersionId={activeVersionId}
+ isLatest={version.id === latestVersionId}
+ isFirst={false}
+ isLast={index === filteredVersions.length - 1}
+ onSelect={onSelectVersion}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </aside>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-filter-empty.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-filter-empty.tsx
new file mode 100644
index 00000000000..f54d362ce29
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-filter-empty.tsx
@@ -0,0 +1,24 @@
+import { useTranslation } from 'react-i18next'
+
+export function VersionFilterEmpty({
+ onReset,
+}: {
+ onReset: () => void
+}) {
+ const { t: tWorkflow } = useTranslation('workflow')
+
+ return (
+ <div className="rounded-lg border border-components-panel-border bg-components-panel-on-panel-item-bg px-3 py-6 text-center">
+ <p className="system-sm-regular text-text-tertiary">
+ {tWorkflow('versionHistory.filter.empty')}
+ </p>
+ <button
+ type="button"
+ onClick={onReset}
+ className="mt-2 rounded-md px-2 py-1 system-xs-medium text-text-accent hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ >
+ {tWorkflow('versionHistory.filter.reset')}
+ </button>
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx
new file mode 100644
index 00000000000..985d87da86a
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx
@@ -0,0 +1,78 @@
+import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
+import { cn } from '@langgenius/dify-ui/cn'
+import { useTranslation } from 'react-i18next'
+import useTimestamp from '@/hooks/use-timestamp'
+import { VersionTimelineDot } from './version-timeline-dot'
+
+function VersionMetadata({
+ version,
+}: {
+ version: AgentConfigSnapshotSummaryResponse
+}) {
+ const { t } = useTranslation('agentV2')
+ const { formatTime } = useTimestamp()
+
+ if (version.created_at == null && !version.created_by)
+ return null
+
+ return (
+ <p className="truncate system-xs-regular text-text-tertiary">
+ {version.created_at != null && formatTime(version.created_at, t('roster.dateTimeFormat'))}
+ {version.created_at != null && version.created_by && ' · '}
+ {version.created_by}
+ </p>
+ )
+}
+
+export function VersionItem({
+ version,
+ activeVersionId,
+ isLatest,
+ isFirst,
+ isLast,
+ onSelect,
+}: {
+ version: AgentConfigSnapshotSummaryResponse
+ activeVersionId?: string | null
+ isLatest: boolean
+ isFirst: boolean
+ isLast: boolean
+ onSelect: (versionId: string) => void
+}) {
+ const { t } = useTranslation('agentV2')
+ const { t: tWorkflow } = useTranslation('workflow')
+ const isActive = version.id === activeVersionId
+ const label = version.version_note || t('agentDetail.versionHistory.versionName', { version: version.version })
+
+ return (
+ <button
+ type="button"
+ aria-current={isActive ? 'true' : undefined}
+ onClick={() => onSelect(version.id)}
+ className={cn(
+ 'group relative flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
+ isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
+ )}
+ >
+ <VersionTimelineDot isActive={isActive} isFirst={isFirst} isLast={isLast} />
+ <div className="min-w-0 flex-1 py-0.5">
+ <div className="flex min-w-0 items-center gap-1">
+ <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>
+ {label}
+ </p>
+ {isLatest && (
+ <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-[5px] py-[3px] system-2xs-medium-uppercase text-text-accent-secondary">
+ {tWorkflow('versionHistory.latest')}
+ </span>
+ )}
+ </div>
+ {isActive && version.summary && (
+ <p className="mt-0.5 line-clamp-4 system-xs-regular text-text-secondary">
+ {version.summary}
+ </p>
+ )}
+ <VersionMetadata version={version} />
+ </div>
+ </button>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-timeline-dot.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-timeline-dot.tsx
new file mode 100644
index 00000000000..a9dbcdb86d9
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-timeline-dot.tsx
@@ -0,0 +1,25 @@
+import { cn } from '@langgenius/dify-ui/cn'
+
+export function VersionTimelineDot({
+ isActive,
+ isFirst,
+ isLast,
+}: {
+ isActive: boolean
+ isFirst: boolean
+ isLast: boolean
+}) {
+ return (
+ <div className="relative flex w-[18px] shrink-0 justify-center pt-1.5">
+ {!isFirst && <div className="absolute top-0 h-2 w-0.5 bg-divider-subtle" />}
+ <span
+ aria-hidden
+ className={cn(
+ 'relative z-1 size-2 rounded-full border-2 bg-components-panel-bg',
+ isActive ? 'border-text-accent' : 'border-text-quaternary',
+ )}
+ />
+ {!isLast && <div className="absolute top-3 bottom-[-18px] w-0.5 bg-divider-subtle" />}
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
index 4773d6d2f9f..7814769e735 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
@@ -1,124 +1,386 @@
'use client'
+import type { SandboxFileEntryResponse, SandboxListResponse, SandboxReadResponse } from '@dify/contracts/api/console/agent/types.gen'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
-import {
- Drawer,
- DrawerBackdrop,
- DrawerCloseButton,
- DrawerContent,
- DrawerDescription,
- DrawerPopup,
- DrawerPortal,
- DrawerTitle,
- DrawerViewport,
-} from '@langgenius/dify-ui/drawer'
-import { FileTreeFile } from '@langgenius/dify-ui/file-tree'
+import { Dialog } from '@langgenius/dify-ui/dialog'
+import { skipToken, useQueries, useQuery } from '@tanstack/react-query'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { AgentFileTree } from '../orchestrate/files/tree'
+import { consoleQuery } from '@/service/client'
+import { getFileIconType } from '../orchestrate/files/file-icon'
+import { AgentSkillDetailDialog } from '../orchestrate/skills/detail-dialog'
type AgentWorkingDirectoryPanelProps = {
+ source: AgentWorkingDirectorySource
onOpenChange: (open: boolean) => void
open: boolean
}
-const workingDirectoryFiles: AgentFileNode[] = [
- {
- id: 'working-directory/_index.json',
- name: '_index.json',
- icon: 'json',
- driveKey: 'working-directory/_index.json',
- },
- {
- id: 'working-directory/web-game',
- name: 'web-game',
- icon: 'folder',
- driveKey: 'working-directory/web-game',
- children: [
- {
- id: 'working-directory/web-game/public',
- name: 'public',
- icon: 'folder',
- driveKey: 'working-directory/web-game/public',
- },
- {
- id: 'working-directory/web-game/assets',
- name: 'assets',
- icon: 'folder',
- driveKey: 'working-directory/web-game/assets',
- },
- {
- id: 'working-directory/web-game/src',
- name: 'src',
- icon: 'folder',
- driveKey: 'working-directory/web-game/src',
- },
- {
- id: 'working-directory/web-game/styles',
- name: 'styles',
- icon: 'folder',
- driveKey: 'working-directory/web-game/styles',
- },
- {
- id: 'working-directory/web-game/README.md',
- name: 'README.md',
- icon: 'markdown',
- driveKey: 'working-directory/web-game/README.md',
- },
- ],
- },
-]
-
-const selectedWorkingDirectoryFileId = 'working-directory/web-game/README.md'
+export type AgentWorkingDirectorySource = {
+ type: 'agent'
+ agentId: string
+ conversationId?: string | null
+} | {
+ type: 'workflow-node'
+ appId?: string
+ conversationId?: string | null
+ nodeId: string
+ workflowRunId?: string | null
+}
+
+type SandboxErrorPayload = {
+ code?: string
+}
+
+const normalizeSandboxPath = (path: string) => {
+ const normalizedPath = path.replace(/^\.\//, '').replace(/^\/+|\/+$/g, '')
+ return normalizedPath === '.' ? '' : normalizedPath
+}
+
+const joinSandboxPath = (basePath: string, name: string) => {
+ const normalizedBasePath = normalizeSandboxPath(basePath)
+ return normalizedBasePath ? `${normalizedBasePath}/${name}` : name
+}
+
+function getSandboxEntryPathSegments(entryName: string, basePath: string) {
+ const normalizedBasePath = normalizeSandboxPath(basePath)
+ const normalizedEntryName = normalizeSandboxPath(entryName)
+
+ if (!normalizedEntryName)
+ return []
+
+ if (!normalizedBasePath)
+ return normalizedEntryName.split('/').filter(Boolean)
+
+ if (normalizedEntryName === normalizedBasePath || normalizedEntryName.startsWith(`${normalizedBasePath}/`))
+ return normalizedEntryName.split('/').filter(Boolean)
+
+ return [...normalizedBasePath.split('/').filter(Boolean), ...normalizedEntryName.split('/').filter(Boolean)]
+}
+
+function buildSandboxFileTree(entries: SandboxFileEntryResponse[] = [], basePath = '.'): AgentFileNode[] {
+ const rootFiles: AgentFileNode[] = []
+
+ for (const entry of entries) {
+ const pathSegments = getSandboxEntryPathSegments(entry.name, basePath)
+ if (!pathSegments.length)
+ continue
+
+ let currentFiles = rootFiles
+ let currentPath = ''
+
+ pathSegments.forEach((segment, index) => {
+ const isLeaf = index === pathSegments.length - 1
+ const isFolder = !isLeaf || entry.type === 'dir'
+ const nodePath = joinSandboxPath(currentPath, segment)
+ let node = currentFiles.find(file => file.id === nodePath)
+
+ if (!node) {
+ node = {
+ id: nodePath,
+ name: segment,
+ icon: isFolder ? 'folder' : getFileIconType(segment),
+ children: isFolder ? [] : undefined,
+ }
+ currentFiles.push(node)
+ }
+
+ if (isFolder) {
+ node.children ??= []
+ currentFiles = node.children
+ }
+
+ currentPath = nodePath
+ })
+ }
+
+ return rootFiles
+}
+
+function mergeSandboxFileTree(targetFiles: AgentFileNode[], sourceFiles: AgentFileNode[]): AgentFileNode[] {
+ const mergedFiles = [...targetFiles]
+
+ for (const sourceFile of sourceFiles) {
+ const targetFileIndex = mergedFiles.findIndex(file => file.id === sourceFile.id)
+ if (targetFileIndex === -1) {
+ mergedFiles.push(sourceFile)
+ continue
+ }
+
+ const targetFile = mergedFiles[targetFileIndex]!
+ mergedFiles[targetFileIndex] = {
+ ...targetFile,
+ ...sourceFile,
+ children: mergeSandboxFileTree(targetFile.children ?? [], sourceFile.children ?? []),
+ }
+ }
+
+ return mergedFiles
+}
+
+function findFirstReadableFile(files: AgentFileNode[]): AgentFileNode | undefined {
+ for (const file of files) {
+ if (file.children?.length) {
+ const childFile = findFirstReadableFile(file.children)
+ if (childFile)
+ return childFile
+ }
+ else if (file.icon !== 'folder') {
+ return file
+ }
+ }
+}
+
+function findReadableFile(files: AgentFileNode[], fileId?: string): AgentFileNode | undefined {
+ if (!fileId)
+ return undefined
+
+ for (const file of files) {
+ if (file.id === fileId && file.icon !== 'folder')
+ return file
+
+ const childFile = findReadableFile(file.children ?? [], fileId)
+ if (childFile)
+ return childFile
+ }
+}
+
+function countReadableFiles(files: AgentFileNode[]): number {
+ return files.reduce((count, file) => {
+ if (file.icon === 'folder')
+ return count + countReadableFiles(file.children ?? [])
+
+ return count + 1
+ }, 0)
+}
+
+async function isNoActiveSessionError(error: unknown) {
+ if (!(error instanceof Response) || error.status !== 404)
+ return false
+
+ try {
+ const payload = await error.clone().json() as SandboxErrorPayload
+ return payload.code === 'no_active_session'
+ }
+ catch {
+ return false
+ }
+}
+
+const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
export function AgentWorkingDirectoryPanel({
+ source,
onOpenChange,
open,
}: AgentWorkingDirectoryPanelProps) {
const { t } = useTranslation('agentV2')
const { t: tCommon } = useTranslation('common')
+ const [selectedFileId, setSelectedFileId] = useState<string>()
+ const [loadedFolderPaths, setLoadedFolderPaths] = useState<string[]>([])
+ const [openFolderPaths, setOpenFolderPaths] = useState<string[]>([])
+ const [pendingOpenFolderPaths, setPendingOpenFolderPaths] = useState<string[]>([])
+ const workflowNodeRunId = source.type === 'workflow-node'
+ ? (source.workflowRunId ?? source.conversationId)
+ : undefined
+ const hasWorkingDirectorySource = source.type === 'agent'
+ ? !!source.conversationId
+ : !!source.appId && !!workflowNodeRunId
+ const getFileListQueryOptions = (path: string) => source.type === 'agent'
+ ? consoleQuery.agent.byAgentId.sandbox.files.get.queryOptions({
+ input: source.conversationId
+ ? {
+ params: {
+ agent_id: source.agentId,
+ },
+ query: {
+ conversation_id: source.conversationId,
+ path,
+ },
+ }
+ : skipToken,
+ context: {
+ silent: true,
+ },
+ })
+ : consoleQuery.apps.byAppId.workflowRuns.byWorkflowRunId.agentNodes.byNodeId.sandbox.files.get.queryOptions({
+ input: source.appId && workflowNodeRunId
+ ? {
+ params: {
+ app_id: source.appId,
+ workflow_run_id: workflowNodeRunId,
+ node_id: source.nodeId,
+ },
+ query: {
+ path,
+ },
+ }
+ : skipToken,
+ context: {
+ silent: true,
+ },
+ })
+ const fileListQueryOptions = getFileListQueryOptions('.')
+ const fileListQuery = useQuery({
+ ...fileListQueryOptions,
+ queryFn: async (context): Promise<SandboxListResponse> => {
+ try {
+ return await fileListQueryOptions.queryFn(context)
+ }
+ catch (error) {
+ if (await isNoActiveSessionError(error)) {
+ return {
+ entries: [],
+ path: '.',
+ }
+ }
+
+ throw error
+ }
+ },
+ retry: false,
+ })
+ const expandedFolderQueries = useQueries({
+ queries: hasWorkingDirectorySource
+ ? loadedFolderPaths.map((path) => {
+ const queryOptions = getFileListQueryOptions(path)
+
+ return {
+ ...queryOptions,
+ queryFn: async (context): Promise<SandboxListResponse> => {
+ try {
+ return await queryOptions.queryFn(context)
+ }
+ catch (error) {
+ if (await isNoActiveSessionError(error)) {
+ return {
+ entries: [],
+ path,
+ }
+ }
+
+ throw error
+ }
+ },
+ retry: false,
+ }
+ })
+ : [],
+ })
+ const workingDirectoryFiles = expandedFolderQueries.reduce((files, query) => {
+ return mergeSandboxFileTree(files, buildSandboxFileTree(query.data?.entries, query.data?.path))
+ }, buildSandboxFileTree(fileListQuery.data?.entries, fileListQuery.data?.path))
+ const selectedWorkingDirectoryFile = findReadableFile(workingDirectoryFiles, selectedFileId)
+ ?? findFirstReadableFile(workingDirectoryFiles)
+ const isFileListLoading = hasWorkingDirectorySource && fileListQuery.isPending
+ const loadingFolderPaths = new Set(loadedFolderPaths.filter((path, index) => expandedFolderQueries[index]?.isPending))
+ const loadedFolderPathIndexes = new Map(loadedFolderPaths.map((path, index) => [path, index]))
+ const fileReadQueryOptions = source.type === 'agent'
+ ? consoleQuery.agent.byAgentId.sandbox.files.read.get.queryOptions({
+ input: source.conversationId && selectedWorkingDirectoryFile?.id
+ ? {
+ params: {
+ agent_id: source.agentId,
+ },
+ query: {
+ conversation_id: source.conversationId,
+ path: selectedWorkingDirectoryFile.id,
+ },
+ }
+ : skipToken,
+ context: {
+ silent: true,
+ },
+ })
+ : consoleQuery.apps.byAppId.workflowRuns.byWorkflowRunId.agentNodes.byNodeId.sandbox.files.read.get.queryOptions({
+ input: source.appId && workflowNodeRunId && selectedWorkingDirectoryFile?.id
+ ? {
+ params: {
+ app_id: source.appId,
+ workflow_run_id: workflowNodeRunId,
+ node_id: source.nodeId,
+ },
+ query: {
+ path: selectedWorkingDirectoryFile.id,
+ },
+ }
+ : skipToken,
+ context: {
+ silent: true,
+ },
+ })
+ const fileReadQuery = useQuery({
+ ...fileReadQueryOptions,
+ enabled: open && !!selectedWorkingDirectoryFile,
+ queryFn: async (context): Promise<SandboxReadResponse> => {
+ try {
+ return await fileReadQueryOptions.queryFn(context)
+ }
+ catch (error) {
+ if (isNotFoundResponse(error)) {
+ return {
+ binary: false,
+ path: selectedWorkingDirectoryFile?.id ?? '',
+ text: null,
+ truncated: false,
+ }
+ }
+
+ throw error
+ }
+ },
+ retry: false,
+ })
+ const isFileReadLoading = !!selectedWorkingDirectoryFile && fileReadQuery.isPending
return (
- <Drawer open={open} onOpenChange={onOpenChange} swipeDirection="right">
- <DrawerPortal>
- <DrawerBackdrop forceRender className="fixed bg-transparent" />
- <DrawerViewport>
- <DrawerPopup className="data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[360px]">
- <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">
- <div className="flex shrink-0 items-start gap-2 px-4 pt-3 pb-2">
- <div className="min-w-0 flex-1">
- <DrawerTitle className="truncate system-xl-semibold text-text-primary">
- {t('agentDetail.configure.workingDirectory.title')}
- </DrawerTitle>
- <DrawerDescription className="body-xs-regular text-text-tertiary">
- {t('agentDetail.configure.workingDirectory.description')}
- </DrawerDescription>
- </div>
- <DrawerCloseButton
- aria-label={tCommon('operation.close')}
- className="size-6 rounded-md p-0.5"
- />
- </div>
- <AgentFileTree
- files={workingDirectoryFiles}
- selectedFileId={selectedWorkingDirectoryFileId}
- treeLabel={t('agentDetail.configure.workingDirectory.treeLabel')}
- className="min-h-0 flex-1 px-3 py-1"
- scrollAreaClassName="flex-1"
- rootClassName="p-0"
- listClassName="gap-px"
- renderFile={({ selected, children }) => (
- <FileTreeFile selected={selected}>
- {children}
- {selected && (
- <span aria-hidden className="ms-auto i-ri-more-fill flex size-5 shrink-0 items-center justify-center text-text-tertiary" />
- )}
- </FileTreeFile>
- )}
- />
- </DrawerContent>
- </DrawerPopup>
- </DrawerViewport>
- </DrawerPortal>
- </Drawer>
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <AgentSkillDetailDialog
+ skillName={t('agentDetail.configure.workingDirectory.title')}
+ detail={{
+ description: t('agentDetail.configure.workingDirectory.description'),
+ fileCount: countReadableFiles(workingDirectoryFiles),
+ fileListTitle: t('agentDetail.configure.workingDirectory.title'),
+ files: workingDirectoryFiles,
+ filePreview: {
+ binary: fileReadQuery.data?.binary,
+ content: fileReadQuery.data?.text ?? undefined,
+ fileName: isFileListLoading ? '' : selectedWorkingDirectoryFile?.name,
+ isError: fileListQuery.isError || fileReadQuery.isError,
+ isLoading: isFileListLoading || isFileReadLoading,
+ },
+ folderOpenState: ({ file }) => {
+ const queryIndex = loadedFolderPathIndexes.get(file.id)
+ const folderLoaded = queryIndex !== undefined && expandedFolderQueries[queryIndex]?.isSuccess
+
+ return openFolderPaths.includes(file.id)
+ || (pendingOpenFolderPaths.includes(file.id) && !!folderLoaded)
+ },
+ onFolderOpenChange: ({ file, open }) => {
+ if (loadingFolderPaths.has(file.id))
+ return
+
+ if (open && !loadedFolderPaths.includes(file.id)) {
+ setLoadedFolderPaths(paths => [...paths, file.id])
+ setPendingOpenFolderPaths(paths => paths.includes(file.id) ? paths : [...paths, file.id])
+ return
+ }
+
+ setPendingOpenFolderPaths(paths => paths.filter(path => path !== file.id))
+ setOpenFolderPaths(paths => open
+ ? (paths.includes(file.id) ? paths : [...paths, file.id])
+ : paths.filter(path => path !== file.id))
+ },
+ onSelectFile: selectedFile => setSelectedFileId(selectedFile.id),
+ renderFolderSuffix: ({ file }) => loadingFolderPaths.has(file.id)
+ ? (
+ <span aria-label={tCommon('loading')} className="ms-auto i-ri-loader-4-line size-4 shrink-0 animate-spin text-text-tertiary" />
+ )
+ : null,
+ selectedFileId: selectedWorkingDirectoryFile?.id,
+ sections: [],
+ }}
+ />
+ </Dialog>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/feature-flags.ts b/web/features/agent-v2/agent-detail/configure/feature-flags.ts
index 0769fc6f597..4e9fc1d6508 100644
--- a/web/features/agent-v2/agent-detail/configure/feature-flags.ts
+++ b/web/features/agent-v2/agent-detail/configure/feature-flags.ts
@@ -1 +1,2 @@
export const ENABLE_AGENT_CLI_TOOLS = false
+export const ENABLE_AGENT_CONTENT_MODERATION = false
diff --git a/web/features/agent-v2/agent-detail/configure/hooks.ts b/web/features/agent-v2/agent-detail/configure/hooks.ts
index dfdf4c7d8da..785a803728d 100644
--- a/web/features/agent-v2/agent-detail/configure/hooks.ts
+++ b/web/features/agent-v2/agent-detail/configure/hooks.ts
@@ -42,6 +42,9 @@ export function useAgentConfigureData(agentId: string, selectedVersionId: string
const activeVersionId = selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : null)
const activeConfigSnapshot = selectedVersionId ? versionDetail : (composerQuery.data?.active_config_snapshot ?? versionDetail)
const agentSoulConfig = selectedVersionId ? versionDetail?.config_snapshot : (composerQuery.data?.agent_soul ?? versionDetail?.config_snapshot)
+ const isPending = agentQuery.isPending
+ || composerQuery.isPending
+ || (shouldLoadVersion && versionQuery.isPending)
return {
agentQuery,
@@ -52,6 +55,7 @@ export function useAgentConfigureData(agentId: string, selectedVersionId: string
activeVersionId,
activeConfigSnapshot,
agentSoulConfig,
+ isPending,
}
}
diff --git a/web/features/agent-v2/agent-detail/configure/model-compatibility.ts b/web/features/agent-v2/agent-detail/configure/model-compatibility.ts
new file mode 100644
index 00000000000..fece602ba37
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/model-compatibility.ts
@@ -0,0 +1,75 @@
+import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'
+
+type ProviderModelCompatibility = {
+ providers: string[]
+ incompatibleModels: RegExp[]
+}
+
+const agentIncompatibleModelConfig: ProviderModelCompatibility[] = [
+ {
+ providers: ['openai'],
+ incompatibleModels: [
+ /^gpt-4o-mini(?:-|$)/i,
+ /^gpt-4\.1-(?:mini|nano)(?:-|$)/i,
+ /^gpt-4(?:-|$)/i,
+ /^gpt-3\.5/i,
+ /^o[34]-mini(?:-|$)/i,
+ ],
+ },
+ {
+ providers: ['anthropic'],
+ incompatibleModels: [
+ /^claude-3-(?:haiku|sonnet|opus)(?:-|$)/i,
+ /^claude-3(?:\.5|-5)-(?:haiku|sonnet)(?:-|$)/i,
+ ],
+ },
+ {
+ providers: ['gemini', 'google'],
+ incompatibleModels: [
+ /^gemini-2[.-][05]-flash(?:-lite)?(?:-|$)/i,
+ /^gemini-1[.-]5-flash(?:-8b)?(?:-|$)/i,
+ ],
+ },
+ {
+ providers: ['deepseek'],
+ incompatibleModels: [
+ /^deepseek-r1$/i,
+ /^deepseek-r1-lite$/i,
+ /^deepseek-r1-distill(?:-[a-z0-9]+)*-(?:1\.5b|7b|8b|14b|32b|70b)$/i,
+ ],
+ },
+ {
+ providers: ['minimax'],
+ incompatibleModels: [
+ /^minimax-text-01$/i,
+ /^minimax-m1$/i,
+ ],
+ },
+ {
+ providers: ['tongyi', 'qwen'],
+ incompatibleModels: [
+ /^qwen2[.-]5(?:-[a-z0-9.]+)?-instruct(?:-|$)/i,
+ /^qwen2[.-]5-coder(?:-|$)/i,
+ /^qwen3-(?:0\.6b|1\.7b|4b|8b|14b|30b)(?:-|$)/i,
+ ],
+ },
+ {
+ providers: ['chatglm', 'zhipuai'],
+ incompatibleModels: [
+ /^glm-4-(?:air|airx|flash)$/i,
+ /^glm-z1-(?:air|flash)$/i,
+ ],
+ },
+]
+
+const normalizeProviderName = (provider: string) => provider.split('/').at(-1)?.toLowerCase() ?? provider.toLowerCase()
+
+export function isAgentCompatibleModel(provider: Model, modelItem: ModelItem) {
+ const providerName = normalizeProviderName(provider.provider)
+ const providerConfig = agentIncompatibleModelConfig.find(config => config.providers.includes(providerName))
+
+ if (!providerConfig)
+ return true
+
+ return !providerConfig.incompatibleModels.some(pattern => pattern.test(modelItem.model))
+}
diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsx
index 75339f7d2e9..2b9a5880466 100644
--- a/web/features/agent-v2/agent-detail/configure/page.tsx
+++ b/web/features/agent-v2/agent-detail/configure/page.tsx
@@ -1,10 +1,18 @@
'use client'
-import { useState } from 'react'
+import { useAtomValue, useSetAtom } from 'jotai'
+import { ScopeProvider } from 'jotai-scope'
import { useTranslation } from 'react-i18next'
import { AgentConfigureComposerScope } from './components/composer-session'
import { AgentConfigurePageLoading } from './components/page-loading'
import { useAgentConfigureData } from './hooks'
+import {
+ agentConfigureComposerRebaseRevisionAtom,
+ agentConfigureScopedAtoms,
+ agentConfigureSelectedVersionIdAtom,
+ agentConfigureSelectVersionAtom,
+ rebaseAgentConfigureComposerAtom,
+} from './state'
type AgentConfigurePageProps = {
agentId: string
@@ -14,7 +22,13 @@ export function AgentConfigurePage({
agentId,
}: AgentConfigurePageProps) {
return (
- <AgentConfigurePageContent agentId={agentId} />
+ <ScopeProvider
+ key={agentId}
+ atoms={agentConfigureScopedAtoms}
+ name="AgentConfigure"
+ >
+ <AgentConfigurePageContent agentId={agentId} />
+ </ScopeProvider>
)
}
@@ -22,14 +36,13 @@ function AgentConfigurePageContent({
agentId,
}: AgentConfigurePageProps) {
const { t } = useTranslation('agentV2')
- const [selectedVersionId, setSelectedVersionId] = useState<string | null>(null)
- const [composerRebaseRevision, setComposerRebaseRevision] = useState(0)
+ const selectedVersionId = useAtomValue(agentConfigureSelectedVersionIdAtom)
+ const composerRebaseRevision = useAtomValue(agentConfigureComposerRebaseRevisionAtom)
+ const rebaseComposer = useSetAtom(rebaseAgentConfigureComposerAtom)
+ const selectVersion = useSetAtom(agentConfigureSelectVersionAtom)
const configureData = useAgentConfigureData(agentId, selectedVersionId)
- const isConfigureDataPending = configureData.agentQuery.isPending
- || configureData.composerQuery.isPending
- || (configureData.shouldLoadVersion && configureData.versionQuery.isPending)
- if (isConfigureDataPending) {
+ if (configureData.isPending) {
return (
<AgentConfigurePageLoading label={t('agentDetail.sections.configure')} />
)
@@ -40,8 +53,8 @@ function AgentConfigurePageContent({
agentId={agentId}
composerRebaseRevision={composerRebaseRevision}
configureData={configureData}
- onComposerRebase={() => setComposerRebaseRevision(revision => revision + 1)}
- onSelectVersion={setSelectedVersionId}
+ onComposerRebase={rebaseComposer}
+ onSelectVersion={selectVersion}
/>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/state.ts b/web/features/agent-v2/agent-detail/configure/state.ts
new file mode 100644
index 00000000000..610a86b74d7
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/state.ts
@@ -0,0 +1,61 @@
+import { atom } from 'jotai'
+
+export type AgentConfigureRightPanelMode = 'build' | 'preview'
+export type AgentConfigureConversationIds = Record<AgentConfigureRightPanelMode, string | null>
+export type AgentConfigureSoulSource = 'draft' | 'build-draft' | 'view-version'
+
+export const agentConfigureSelectedVersionIdAtom = atom<string | null>(null)
+export const agentConfigureComposerRebaseRevisionAtom = atom(0)
+export const agentConfigureSoulSourceOverrideAtom = atom<AgentConfigureSoulSource | null>(null)
+
+export const agentConfigureShowChatFeaturesAtom = atom(false)
+export const agentConfigureShowPreviewVersionsAtom = atom(false)
+export const agentConfigureRightPanelModeAtom = atom<AgentConfigureRightPanelMode>('build')
+export const agentConfigureConversationIdsAtom = atom<AgentConfigureConversationIds>({
+ build: null,
+ preview: null,
+})
+
+export const agentConfigureRightPanelChatModeAtom = atom((get): AgentConfigureRightPanelMode => {
+ const mode = get(agentConfigureRightPanelModeAtom)
+
+ return mode === 'preview' ? 'build' : mode
+})
+
+export const agentConfigureSelectVersionAtom = atom(null, (_get, set, versionId: string | null) => {
+ set(agentConfigureSoulSourceOverrideAtom, versionId ? 'view-version' : null)
+ set(agentConfigureSelectedVersionIdAtom, versionId)
+})
+
+export const rebaseAgentConfigureComposerAtom = atom(null, (get, set) => {
+ set(agentConfigureComposerRebaseRevisionAtom, get(agentConfigureComposerRebaseRevisionAtom) + 1)
+})
+
+export const setAgentConfigureConversationIdAtom = atom(null, (get, set, {
+ mode,
+ conversationId,
+}: {
+ mode: AgentConfigureRightPanelMode
+ conversationId: string | null
+}) => {
+ set(agentConfigureConversationIdsAtom, {
+ ...get(agentConfigureConversationIdsAtom),
+ [mode]: conversationId,
+ })
+})
+
+export const resetAgentConfigureConversationAtom = atom(null, (get, set, mode: AgentConfigureRightPanelMode) => {
+ set(agentConfigureConversationIdsAtom, {
+ ...get(agentConfigureConversationIdsAtom),
+ [mode]: null,
+ })
+})
+
+export const agentConfigureScopedAtoms = [
+ agentConfigureSelectedVersionIdAtom,
+ agentConfigureComposerRebaseRevisionAtom,
+ agentConfigureSoulSourceOverrideAtom,
+ agentConfigureShowChatFeaturesAtom,
+ agentConfigureShowPreviewVersionsAtom,
+ agentConfigureRightPanelModeAtom,
+] as const
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
index 7db81165711..f624ac30c58 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
@@ -1,19 +1,23 @@
'use client'
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentConfigureSoulSource } from './state'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import { consoleQuery } from '@/service/client'
-export type AgentConfigureSoulSource = 'draft' | 'build-draft' | 'view-version'
-
export function usePrepareAgentBuildDraftBeforeRun({
agentId,
+ buildDraftAgentSoulConfig,
isBuildDraftActive,
+ rebaseComposerDraft,
saveDraft,
setSoulSourceOverride,
}: {
agentId?: string
+ buildDraftAgentSoulConfig?: AgentSoulConfig
isBuildDraftActive: boolean
+ rebaseComposerDraft?: (agentSoulConfig?: AgentSoulConfig) => void
saveDraft: () => Promise<unknown>
setSoulSourceOverride?: (source: AgentConfigureSoulSource) => void
}) {
@@ -32,8 +36,10 @@ export function usePrepareAgentBuildDraftBeforeRun({
if (!agentId)
return
- if (!isBuildDraftActive)
- await saveDraft()
+ if (isBuildDraftActive)
+ return buildDraftAgentSoulConfig
+
+ await saveDraft()
const buildDraft = await checkoutBuildDraft({
params: {
@@ -44,8 +50,10 @@ export function usePrepareAgentBuildDraftBeforeRun({
},
})
queryClient.setQueryData(buildDraftQueryOptions.queryKey, buildDraft)
+ rebaseComposerDraft?.(buildDraft.agent_soul as AgentSoulConfig | undefined)
setSoulSourceOverride?.('build-draft')
- }, [agentId, buildDraftQueryOptions.queryKey, checkoutBuildDraft, isBuildDraftActive, queryClient, saveDraft, setSoulSourceOverride])
+ return buildDraft.agent_soul as AgentSoulConfig | undefined
+ }, [agentId, buildDraftAgentSoulConfig, buildDraftQueryOptions.queryKey, checkoutBuildDraft, isBuildDraftActive, queryClient, rebaseComposerDraft, saveDraft, setSoulSourceOverride])
return {
isCheckingOutBuildDraft,
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
index 033d4796ef7..900a960540e 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
@@ -1,18 +1,21 @@
'use client'
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentBuildDraftChangedKey } from './components/orchestrate/build-draft-changes-context'
+import type { AgentConfigureSoulSource } from './state'
import { toast } from '@langgenius/dify-ui/toast'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import isEqual from 'fast-deep-equal'
+import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
import { consoleQuery } from '@/service/client'
-import { agentConfigureConsoleQuery } from './build-draft-query'
import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'
-export type AgentConfigureSoulSource = 'draft' | 'build-draft' | 'view-version'
-
const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
+const getAgentSoulConfigFromRefetchResult = (result: unknown) => {
+ return (result as { data?: { agent_soul?: AgentSoulConfig } } | undefined)?.data?.agent_soul
+}
export function useAgentConfigureBuildDraftData({
agentId,
@@ -20,27 +23,30 @@ export function useAgentConfigureBuildDraftData({
composerAgentSoulConfig,
isViewingVersion,
normalAgentSoulConfig,
+ setSoulSourceOverride,
+ soulSourceOverride,
}: {
agentId: string
activeVersionId: string | null | undefined
composerAgentSoulConfig?: AgentSoulConfig
isViewingVersion: boolean
normalAgentSoulConfig?: AgentSoulConfig
+ setSoulSourceOverride: (source: AgentConfigureSoulSource | null) => void
+ soulSourceOverride: AgentConfigureSoulSource | null
}) {
const shouldSilenceBuildDraftCheckRef = useRef(true)
- const [soulSourceOverride, setSoulSourceOverride] = useState<AgentConfigureSoulSource | null>(null)
const buildDraftQueryInput = {
params: {
agent_id: agentId,
},
}
- const buildDraftQueryOptions = agentConfigureConsoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
input: {
params: buildDraftQueryInput.params,
},
context: {},
})
- const silentBuildDraftQueryOptions = agentConfigureConsoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ const silentBuildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
input: {
params: buildDraftQueryInput.params,
},
@@ -68,6 +74,8 @@ export function useAgentConfigureBuildDraftData({
}
},
retry: false,
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
})
const {
data: buildDraftData,
@@ -84,22 +92,22 @@ export function useAgentConfigureBuildDraftData({
const isBuildDraftActive = soulSource === 'build-draft'
const buildDraftAgentSoulConfig = buildDraftData?.agent_soul as AgentSoulConfig | undefined
const visibleAgentSoulConfig = isBuildDraftActive ? buildDraftAgentSoulConfig : normalAgentSoulConfig
- const buildDraftChangesCount = useMemo(() => {
+ const buildDraftChangedKeys = useMemo<AgentBuildDraftChangedKey[]>(() => {
if (!buildDraftAgentSoulConfig || !composerAgentSoulConfig)
- return 0
+ return []
const normalDraft = agentSoulConfigToFormState(composerAgentSoulConfig)
const buildDraft = agentSoulConfigToFormState(buildDraftAgentSoulConfig)
return (Object.keys(buildDraft) as Array<keyof typeof buildDraft>)
- .filter(key => JSON.stringify(buildDraft[key]) !== JSON.stringify(normalDraft[key]))
- .length
+ .filter(key => !isEqual(buildDraft[key], normalDraft[key]))
}, [buildDraftAgentSoulConfig, composerAgentSoulConfig])
return {
activeVersionId: isBuildDraftActive ? `build-draft:${buildDraftDataUpdatedAt}` : activeVersionId,
agentSoulConfig: visibleAgentSoulConfig,
- changesCount: buildDraftChangesCount,
+ changedKeys: buildDraftChangedKeys,
+ changesCount: buildDraftChangedKeys.length,
isActive: isBuildDraftActive,
isPending: !isViewingVersion && soulSourceOverride !== 'draft' && soulSourceOverride !== 'view-version' && isBuildDraftPending,
refetch: refetchBuildDraft,
@@ -110,7 +118,10 @@ export function useAgentConfigureBuildDraftData({
export function useAgentConfigureBuildDraftActions({
agentId,
+ buildDraftAgentSoulConfig,
isActive,
+ normalAgentSoulConfig,
+ rebaseComposerDraft,
refetchBuildDraft,
refetchComposer,
resetBuildChatSession,
@@ -119,7 +130,10 @@ export function useAgentConfigureBuildDraftActions({
setSoulSourceOverride,
}: {
agentId: string
+ buildDraftAgentSoulConfig?: AgentSoulConfig
isActive: boolean
+ normalAgentSoulConfig?: AgentSoulConfig
+ rebaseComposerDraft: (agentSoulConfig?: AgentSoulConfig) => void
refetchBuildDraft: () => Promise<unknown>
refetchComposer: () => Promise<unknown>
resetBuildChatSession: () => Promise<void>
@@ -130,6 +144,7 @@ export function useAgentConfigureBuildDraftActions({
const { t: tCommon } = useTranslation('common')
const queryClient = useQueryClient()
const buildDraftRefreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const buildDraftRefreshGenerationRef = useRef(0)
const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
input: {
params: {
@@ -137,47 +152,94 @@ export function useAgentConfigureBuildDraftActions({
},
},
})
+ const agentDetailQueryKey = consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } })
+ const finalizeBuildChatMutation = useMutation(consoleQuery.agent.byAgentId.buildChat.finalize.post.mutationOptions())
const applyBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.apply.post.mutationOptions())
const discardBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions())
+ const { mutateAsync: finalizeBuildChatRequest, isPending: isFinalizingBuildChat } = finalizeBuildChatMutation
const { mutateAsync: applyBuildDraftRequest, isPending: isApplyingBuildDraft } = applyBuildDraftMutation
const { mutateAsync: discardBuildDraftRequest, isPending: isDiscardingBuildDraft } = discardBuildDraftMutation
const { prepareBuildDraftBeforeRun } = usePrepareAgentBuildDraftBeforeRun({
agentId,
+ buildDraftAgentSoulConfig,
isBuildDraftActive: isActive,
+ rebaseComposerDraft,
saveDraft,
setSoulSourceOverride,
})
+ const cancelBuildDraftRefresh = useCallback(() => {
+ buildDraftRefreshGenerationRef.current += 1
+ if (!buildDraftRefreshTimerRef.current)
+ return
+
+ clearTimeout(buildDraftRefreshTimerRef.current)
+ buildDraftRefreshTimerRef.current = null
+ }, [])
+
+ const prepareBuildDraftRun = useCallback(async () => {
+ cancelBuildDraftRefresh()
+ return prepareBuildDraftBeforeRun()
+ }, [cancelBuildDraftRefresh, prepareBuildDraftBeforeRun])
+
const refreshBuildDraftAfterBuildChat = useCallback((onRefreshed?: () => void) => {
- if (buildDraftRefreshTimerRef.current)
- clearTimeout(buildDraftRefreshTimerRef.current)
+ cancelBuildDraftRefresh()
+ const refreshGeneration = buildDraftRefreshGenerationRef.current
buildDraftRefreshTimerRef.current = setTimeout(async () => {
buildDraftRefreshTimerRef.current = null
- await refetchBuildDraft()
- onRefreshed?.()
+ try {
+ const result = await refetchBuildDraft()
+ if (refreshGeneration !== buildDraftRefreshGenerationRef.current)
+ return
+
+ const agentSoulConfig = getAgentSoulConfigFromRefetchResult(result)
+ if (agentSoulConfig)
+ rebaseComposerDraft(agentSoulConfig)
+ }
+ catch {}
+ finally {
+ if (refreshGeneration === buildDraftRefreshGenerationRef.current)
+ onRefreshed?.()
+ }
}, 1000)
- }, [refetchBuildDraft])
+ }, [cancelBuildDraftRefresh, rebaseComposerDraft, refetchBuildDraft])
const exitBuildDraftMode = useCallback(async (shouldRefetchComposer: boolean) => {
+ cancelBuildDraftRefresh()
await resetBuildChatSession().catch(() => undefined)
setSoulSourceOverride('draft')
queryClient.removeQueries({
queryKey: buildDraftQueryOptions.queryKey,
})
if (shouldRefetchComposer) {
- await refetchComposer()
+ const result = await refetchComposer()
+ rebaseComposerDraft(getAgentSoulConfigFromRefetchResult(result) ?? normalAgentSoulConfig)
onComposerRebased?.()
}
- }, [buildDraftQueryOptions.queryKey, onComposerRebased, queryClient, refetchComposer, resetBuildChatSession, setSoulSourceOverride])
+ else {
+ rebaseComposerDraft(normalAgentSoulConfig)
+ }
+ }, [buildDraftQueryOptions.queryKey, cancelBuildDraftRefresh, normalAgentSoulConfig, onComposerRebased, queryClient, rebaseComposerDraft, refetchComposer, resetBuildChatSession, setSoulSourceOverride])
const applyBuildDraft = async () => {
try {
+ await finalizeBuildChatRequest({
+ params: {
+ agent_id: agentId,
+ },
+ })
await applyBuildDraftRequest({
params: {
agent_id: agentId,
},
})
+ await queryClient.invalidateQueries({
+ queryKey: agentDetailQueryKey,
+ })
+ await queryClient.invalidateQueries({
+ queryKey: consoleQuery.agent.get.key(),
+ })
await exitBuildDraftMode(true)
toast.success(tCommon('api.actionSuccess'))
}
@@ -203,17 +265,17 @@ export function useAgentConfigureBuildDraftActions({
useEffect(() => {
return () => {
- if (buildDraftRefreshTimerRef.current)
- clearTimeout(buildDraftRefreshTimerRef.current)
+ cancelBuildDraftRefresh()
}
- }, [])
+ }, [cancelBuildDraftRefresh])
return {
applyBuildDraft,
+ cancelBuildDraftRefresh,
discardBuildDraft,
- isApplyingBuildDraft,
+ isApplyingBuildDraft: isFinalizingBuildChat || isApplyingBuildDraft,
isDiscardingBuildDraft,
- prepareBuildDraftBeforeRun,
+ prepareBuildDraftBeforeRun: prepareBuildDraftRun,
refreshBuildDraftAfterBuildChat,
}
}
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
index 8b34801f177..7fa6a53537b 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
@@ -1,11 +1,12 @@
'use client'
-import type { AgentAppDetailWithSite, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { toast } from '@langgenius/dify-ui/toast'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { debounce } from 'es-toolkit/compat'
+import isEqual from 'fast-deep-equal'
import { useSetAtom, useStore } from 'jotai'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -52,6 +53,7 @@ export function useAgentConfigureSync({
const currentModelRef = useRef(currentModel)
const enabledRef = useRef(enabled)
const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)
+ const pageCloseSavingDraftKeyRef = useRef<string | undefined>(undefined)
const publishInFlightRef = useRef(false)
baseConfigRef.current = baseConfig
@@ -64,21 +66,6 @@ export function useAgentConfigureSync({
currentModel: currentModelRef.current,
}), [store])
- const markActiveConfigUnpublished = useCallback(() => {
- queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
- consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
- (agentDetail) => {
- if (!agentDetail)
- return agentDetail
-
- return {
- ...agentDetail,
- active_config_is_published: false,
- }
- },
- )
- }, [agentId, queryClient])
-
const {
mutateAsync: saveComposerDraft,
} = useMutation(
@@ -94,13 +81,16 @@ export function useAgentConfigureSync({
const saveComposer = useSerialAsyncCallback(async ({
configSnapshot,
draftBaseline,
+ silent = true,
}: {
configSnapshot: AgentSoulConfig
draftBaseline: AgentSoulConfigFormState
+ silent?: boolean
}) => {
const savedDraftKey = JSON.stringify(configSnapshot)
+ const agentDetailQueryKey = consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } })
try {
- await saveComposerDraft({
+ const composerState = await saveComposerDraft({
params: {
agent_id: agentId,
},
@@ -110,13 +100,24 @@ export function useAgentConfigureSync({
agent_soul: configSnapshot,
},
})
+ queryClient.setQueryData(
+ consoleQuery.agent.byAgentId.composer.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ composerState,
+ )
+ await queryClient.invalidateQueries({
+ queryKey: agentDetailQueryKey,
+ })
}
catch {
- // Draft sync follows workflow autosave behavior: save failures are silent and keep the local draft intact.
+ // Autosave is silent and keeps the local draft intact; explicit commands must stop at this boundary.
+ if (!silent) {
+ toast.error(tCommon('api.actionFailed'))
+ throw new Error('Failed to save agent composer draft.')
+ }
+
return false
}
- markActiveConfigUnpublished()
setOriginalDraft(draftBaseline)
setDraftSavedAt(Date.now())
lastAutosavedDraftKeyRef.current = savedDraftKey
@@ -146,11 +147,49 @@ export function useAgentConfigureSync({
const draft = store.get(agentComposerDraftAtom)
if (!validateKnowledgeRetrievals(draft.knowledgeRetrievals).isValid)
throw new InvalidKnowledgeConfigurationError()
-
+ const configSnapshot = getAgentSoulDraft()
+ const hasEffectiveModelChange = !isEqual(configSnapshot.model, baseConfigRef.current?.model)
debouncedSaveDraft.cancel?.()
+ if (!store.get(isAgentComposerDirtyAtom) && !hasEffectiveModelChange)
+ return
+
await saveComposer({
- configSnapshot: getAgentSoulDraft(),
+ configSnapshot,
draftBaseline: draft,
+ silent: false,
+ })
+ }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer, store])
+
+ const saveDirtyDraftOnPageClose = useCallback(() => {
+ if (!enabledRef.current || publishInFlightRef.current) {
+ return
+ }
+
+ const draft = store.get(agentComposerDraftAtom)
+ if (
+ !store.get(isAgentComposerDirtyAtom)
+ || !validateKnowledgeRetrievals(draft.knowledgeRetrievals).isValid
+ ) {
+ return
+ }
+
+ const configSnapshot = getAgentSoulDraft()
+ const draftKey = JSON.stringify(configSnapshot)
+ if (
+ lastAutosavedDraftKeyRef.current === draftKey
+ || pageCloseSavingDraftKeyRef.current === draftKey
+ ) {
+ return
+ }
+
+ debouncedSaveDraft.cancel?.()
+ pageCloseSavingDraftKeyRef.current = draftKey
+ void saveComposer({
+ configSnapshot,
+ draftBaseline: draft,
+ }).finally(() => {
+ if (pageCloseSavingDraftKeyRef.current === draftKey)
+ pageCloseSavingDraftKeyRef.current = undefined
})
}, [debouncedSaveDraft, getAgentSoulDraft, saveComposer, store])
@@ -164,11 +203,11 @@ export function useAgentConfigureSync({
!enabledRef.current
|| !isDirty
) {
+ if (!isDirty)
+ debouncedSaveDraft.cancel?.()
return
}
- markActiveConfigUnpublished()
-
if (
!validateKnowledgeRetrievals(store.get(agentComposerDraftAtom).knowledgeRetrievals).isValid
|| lastAutosavedDraftKeyRef.current === agentSoulDraftKey
@@ -178,7 +217,7 @@ export function useAgentConfigureSync({
debouncedSaveDraft()
})
- }, [debouncedSaveDraft, getAgentSoulDraft, markActiveConfigUnpublished, store])
+ }, [debouncedSaveDraft, getAgentSoulDraft, store])
useEffect(() => {
return () => {
@@ -186,6 +225,24 @@ export function useAgentConfigureSync({
}
}, [debouncedSaveDraft])
+ useEffect(() => {
+ const saveDraftWhenPageHidden = () => {
+ if (document.visibilityState === 'hidden')
+ saveDirtyDraftOnPageClose()
+ }
+ const saveDraftBeforeUnload = () => {
+ saveDirtyDraftOnPageClose()
+ }
+
+ document.addEventListener('visibilitychange', saveDraftWhenPageHidden)
+ window.addEventListener('beforeunload', saveDraftBeforeUnload)
+
+ return () => {
+ document.removeEventListener('visibilitychange', saveDraftWhenPageHidden)
+ window.removeEventListener('beforeunload', saveDraftBeforeUnload)
+ }
+ }, [saveDirtyDraftOnPageClose])
+
const publishDraft = useCallback(async () => {
if (publishInFlightRef.current)
return
@@ -206,6 +263,7 @@ export function useAgentConfigureSync({
const saved = await saveComposer({
configSnapshot,
draftBaseline: draft,
+ silent: false,
})
if (!saved)
return
diff --git a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
index 637e4f3623c..f11e76d2960 100644
--- a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
@@ -209,6 +209,8 @@ describe('AgentRosterList', () => {
const workflowLink = screen.getByRole('menuitem', { name: /RFP Review Flow/ })
expect(workflowLink).toHaveAttribute('href', '/app/workflow-app-id/workflow')
+ expect(workflowLink).toHaveAttribute('target', '_blank')
+ expect(workflowLink).toHaveAttribute('rel', 'noopener noreferrer')
expect(screen.getByText(/agentV2\.roster\.references\.label/)).toBeInTheDocument()
})
diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsx
index 9dd4cd43d10..a7f98b81506 100644
--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx
+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx
@@ -182,7 +182,7 @@ function AgentRosterItem({
/>
)
: (
- <div className="flex shrink-0 items-center gap-1">
+ <div className="flex h-4 shrink-0 items-center gap-1">
<span aria-hidden className="i-custom-vender-agent-v2-plan size-3 shrink-0 text-text-tertiary" />
<span className="system-xs-regular text-text-tertiary">{referenceCount}</span>
</div>
diff --git a/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx b/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx
index 9974a30468c..762017365d7 100644
--- a/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx
+++ b/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx
@@ -45,7 +45,7 @@ export function AgentWorkflowReferencesDropdown({
<DropdownMenu modal={false}>
<DropdownMenuTrigger
aria-label={t('roster.references.trigger', { name: agentName, count: referenceCount })}
- className="-ml-1 flex shrink-0 cursor-pointer items-center gap-1 rounded-md px-1 py-0.5 outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover"
+ className="relative flex h-4 shrink-0 cursor-pointer items-center gap-1 rounded-md outline-hidden before:pointer-events-none before:absolute before:-inset-x-1 before:-inset-y-0.5 before:rounded-md before:content-[''] hover:before:bg-state-base-hover focus-visible:before:ring-2 focus-visible:before:ring-state-accent-solid data-popup-open:before:bg-state-base-hover"
>
<span aria-hidden className="i-custom-vender-agent-v2-plan size-3 shrink-0 text-text-tertiary" />
<span className="system-xs-regular text-text-tertiary">{referenceCount}</span>
@@ -57,7 +57,7 @@ export function AgentWorkflowReferencesDropdown({
{publishedReferences.map(reference => (
<DropdownMenuLinkItem
key={reference.app_id}
- render={<Link href={getWorkflowReferenceHref(reference)} />}
+ render={<Link href={getWorkflowReferenceHref(reference)} target="_blank" rel="noopener noreferrer" />}
className="mx-0 h-8 gap-2 px-2 py-1 pr-2.5 system-md-regular text-text-secondary"
>
<span aria-hidden className="shrink-0">
diff --git a/web/i18n/ar-TN/agent-v-2.json b/web/i18n/ar-TN/agent-v-2.json
index 9d5d121c24d..f520d9a9608 100644
--- a/web/i18n/ar-TN/agent-v-2.json
+++ b/web/i18n/ar-TN/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "ابنِ وكيلك عبر الدردشة",
"agentDetail.configure.build.inputPlaceholder": "صِف ما يجب أن يفعله وكيلك",
"agentDetail.configure.build.startBuild": "ابدأ البناء",
- "agentDetail.configure.buildDraft.changes": "{{count}} تغييرات للتطبيق",
"agentDetail.configure.buildDraft.discard": "تجاهل",
"agentDetail.configure.buildDraft.modeBadge": "وضع البناء",
"agentDetail.configure.buildDraft.modeDescription": "أنت في وضع البناء. شكّل هذا الإعداد عبر الدردشة على اليمين، ثم طبّق.",
- "agentDetail.configure.buildDraft.noChanges": "لا توجد تغييرات للتطبيق",
"agentDetail.configure.buildDraft.title": "مسودة البناء",
"agentDetail.configure.chatFeatures.description": "شكّل تجربة الدردشة للمستخدم النهائي على Web app وأسطح الدردشة.",
"agentDetail.configure.chatFeatures.title": "ميزات الدردشة",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "اكتب التعليمات هنا،",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} غير موجود",
"agentDetail.configure.prompt.tip": "عرّف دور الوكيل وصف مهمته المعتادة. استخدم / للإشارة صراحةً إلى المهارات والملفات والأدوات واسترجاع المعرفة.",
"agentDetail.configure.publishBar.draft": "مسودة",
"agentDetail.configure.publishBar.publishUpdate": "نشر التحديث",
diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.json
index 6c1a766379b..205e6290ab6 100644
--- a/web/i18n/ar-TN/common.json
+++ b/web/i18n/ar-TN/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "معطل",
"modelProvider.selector.discoverMoreInMarketplace": "اكتشف المزيد في السوق",
"modelProvider.selector.fromMarketplace": "من السوق",
+ "modelProvider.selector.hideIncompatibleModels": "إخفاء النماذج غير المتوافقة",
"modelProvider.selector.incompatible": "غير متوافق",
"modelProvider.selector.incompatibleTip": "هذا النموذج غير متاح في الإصدار الحالي. يرجى تحديد نموذج متاح آخر.",
"modelProvider.selector.install": "تثبيت",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "لم يتم تكوين أي مزود نموذج",
"modelProvider.selector.noProviderConfiguredDesc": "تصفح السوق لتثبيت مزود، أو قم بتكوين المزودين في الإعدادات.",
"modelProvider.selector.onlyCompatibleModelsShown": "يتم عرض النماذج المتوافقة فقط",
+ "modelProvider.selector.showIncompatibleModels": "عرض النماذج غير المتوافقة",
"modelProvider.showModels": "عرض النماذج",
"modelProvider.speechToTextModel.key": "نموذج تحويل الكلام إلى نص",
"modelProvider.speechToTextModel.tip": "تعيين النموذج الافتراضي لإدخال تحويل الكلام إلى نص في المحادثة.",
diff --git a/web/i18n/de-DE/agent-v-2.json b/web/i18n/de-DE/agent-v-2.json
index 69f16b6989c..f2de2278448 100644
--- a/web/i18n/de-DE/agent-v-2.json
+++ b/web/i18n/de-DE/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Agent per Chat erstellen",
"agentDetail.configure.build.inputPlaceholder": "Beschreiben Sie, was Ihr Agent tun soll",
"agentDetail.configure.build.startBuild": "Build starten",
- "agentDetail.configure.buildDraft.changes": "{{count}} Änderungen anzuwenden",
"agentDetail.configure.buildDraft.discard": "Verwerfen",
"agentDetail.configure.buildDraft.modeBadge": "Build-Modus",
"agentDetail.configure.buildDraft.modeDescription": "Sie sind im Build-Modus. Formen Sie diese Einrichtung über den Chat rechts und wenden Sie sie dann an.",
- "agentDetail.configure.buildDraft.noChanges": "Keine Änderungen anzuwenden",
"agentDetail.configure.buildDraft.title": "Build-Entwurf",
"agentDetail.configure.chatFeatures.description": "Gestalten Sie das Chat-Erlebnis für Endnutzer in Ihrer Webapp und in Chat-Oberflächen.",
"agentDetail.configure.chatFeatures.title": "Chat-Funktionen",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Anweisungen hier eintragen,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} existiert nicht",
"agentDetail.configure.prompt.tip": "Definieren Sie die Rolle des Agenten und beschreiben Sie seine typische Aufgabe. Verwenden Sie /, um explizit auf Skills, Dateien, Tools und Wissensabrufe zu verweisen.",
"agentDetail.configure.publishBar.draft": "Entwurf",
"agentDetail.configure.publishBar.publishUpdate": "Update veröffentlichen",
diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.json
index 836d9094974..09d9b3ce2e0 100644
--- a/web/i18n/de-DE/common.json
+++ b/web/i18n/de-DE/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Deaktiviert",
"modelProvider.selector.discoverMoreInMarketplace": "Mehr im Marketplace entdecken",
"modelProvider.selector.fromMarketplace": "Vom Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Inkompatible Modelle ausblenden",
"modelProvider.selector.incompatible": "Inkompatibel",
"modelProvider.selector.incompatibleTip": "Dieses Modell ist in der aktuellen Version nicht verfügbar. Bitte wählen Sie ein anderes verfügbares Modell.",
"modelProvider.selector.install": "Installieren",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Kein Modellanbieter konfiguriert",
"modelProvider.selector.noProviderConfiguredDesc": "Durchsuchen Sie den Marketplace, um einen zu installieren, oder konfigurieren Sie Anbieter in den Einstellungen.",
"modelProvider.selector.onlyCompatibleModelsShown": "Es werden nur kompatible Modelle angezeigt",
+ "modelProvider.selector.showIncompatibleModels": "Inkompatible Modelle anzeigen",
"modelProvider.showModels": "Modelle anzeigen",
"modelProvider.speechToTextModel.key": "Sprach-zu-Text-Modell",
"modelProvider.speechToTextModel.tip": "Legen Sie das Standardmodell für die Spracheingabe in Konversationen fest.",
diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.json
index bdcc044a1fb..f884399fc2f 100644
--- a/web/i18n/en-US/agent-v-2.json
+++ b/web/i18n/en-US/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Build your agent by chatting",
"agentDetail.configure.build.inputPlaceholder": "Describe what your agent should do",
"agentDetail.configure.build.startBuild": "Start build",
- "agentDetail.configure.buildDraft.changes": "{{count}} changes to apply",
"agentDetail.configure.buildDraft.discard": "Discard",
"agentDetail.configure.buildDraft.modeBadge": "Build mode",
"agentDetail.configure.buildDraft.modeDescription": "You're in build mode. Shape this setup through the chat on the right, then Apply.",
- "agentDetail.configure.buildDraft.noChanges": "No changes to apply",
"agentDetail.configure.buildDraft.title": "Build draft",
"agentDetail.configure.chatFeatures.description": "Shape the end-user chat experience on your web app and chat surfaces.",
"agentDetail.configure.chatFeatures.title": "Chat Features",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Write instructions here,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} does not exist",
"agentDetail.configure.prompt.tip": "Define the agent's role and describe its typical task. Use / to make explicit reference to Skills, Files, Tools and Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Draft",
"agentDetail.configure.publishBar.publishUpdate": "Publish update",
diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.json
index bf15b3ff4df..aed5bbaec4f 100644
--- a/web/i18n/en-US/common.json
+++ b/web/i18n/en-US/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Disabled",
"modelProvider.selector.discoverMoreInMarketplace": "Discover more in Marketplace",
"modelProvider.selector.fromMarketplace": "From Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Hide incompatible models",
"modelProvider.selector.incompatible": "Incompatible",
"modelProvider.selector.incompatibleTip": "This model is not available in the current version. Please select another available model.",
"modelProvider.selector.install": "Install",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "No Model Provider configured",
"modelProvider.selector.noProviderConfiguredDesc": "Browse Marketplace to install one, or configure providers in settings.",
"modelProvider.selector.onlyCompatibleModelsShown": "Only compatible models are shown",
+ "modelProvider.selector.showIncompatibleModels": "Show incompatible models",
"modelProvider.showModels": "Show Models",
"modelProvider.speechToTextModel.key": "Speech-to-Text Model",
"modelProvider.speechToTextModel.tip": "Set the default model for speech-to-text input in conversation.",
diff --git a/web/i18n/es-ES/agent-v-2.json b/web/i18n/es-ES/agent-v-2.json
index 8b481001edd..d2eb951ee78 100644
--- a/web/i18n/es-ES/agent-v-2.json
+++ b/web/i18n/es-ES/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Crea tu agente chateando",
"agentDetail.configure.build.inputPlaceholder": "Describe qué debe hacer tu agente",
"agentDetail.configure.build.startBuild": "Iniciar compilación",
- "agentDetail.configure.buildDraft.changes": "{{count}} cambios por aplicar",
"agentDetail.configure.buildDraft.discard": "Descartar",
"agentDetail.configure.buildDraft.modeBadge": "Modo build",
"agentDetail.configure.buildDraft.modeDescription": "Estás en modo build. Ajusta esta configuración con el chat de la derecha y luego aplica los cambios.",
- "agentDetail.configure.buildDraft.noChanges": "No hay cambios por aplicar",
"agentDetail.configure.buildDraft.title": "Borrador de compilación",
"agentDetail.configure.chatFeatures.description": "Da forma a la experiencia de chat del usuario final en tu webapp y superficies de chat.",
"agentDetail.configure.chatFeatures.title": "Funciones de chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Escribe las instrucciones aquí,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} no existe",
"agentDetail.configure.prompt.tip": "Define el rol del agente y describe su tarea habitual. Usa / para hacer referencia explícita a habilidades, archivos, herramientas y recuperaciones de conocimiento.",
"agentDetail.configure.publishBar.draft": "Borrador",
"agentDetail.configure.publishBar.publishUpdate": "Publicar actualización",
diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.json
index f2c5ad385a4..3da4be4475c 100644
--- a/web/i18n/es-ES/common.json
+++ b/web/i18n/es-ES/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Desactivado",
"modelProvider.selector.discoverMoreInMarketplace": "Descubre más en el Marketplace",
"modelProvider.selector.fromMarketplace": "Desde el Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Ocultar modelos incompatibles",
"modelProvider.selector.incompatible": "Incompatible",
"modelProvider.selector.incompatibleTip": "Este modelo no está disponible en la versión actual. Por favor, selecciona otro modelo disponible.",
"modelProvider.selector.install": "Instalar",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Ningún proveedor de modelos configurado",
"modelProvider.selector.noProviderConfiguredDesc": "Explora el Marketplace para instalar uno, o configura proveedores en los ajustes.",
"modelProvider.selector.onlyCompatibleModelsShown": "Solo se muestran los modelos compatibles",
+ "modelProvider.selector.showIncompatibleModels": "Mostrar modelos incompatibles",
"modelProvider.showModels": "Mostrar Modelos",
"modelProvider.speechToTextModel.key": "Modelo de Voz a Texto",
"modelProvider.speechToTextModel.tip": "Establece el modelo predeterminado para la entrada de voz a texto en la conversación.",
diff --git a/web/i18n/fa-IR/agent-v-2.json b/web/i18n/fa-IR/agent-v-2.json
index 8ed6a7fc3ce..c16a7939c64 100644
--- a/web/i18n/fa-IR/agent-v-2.json
+++ b/web/i18n/fa-IR/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "عامل خود را با چت بسازید",
"agentDetail.configure.build.inputPlaceholder": "توضیح دهید عامل شما باید چه کاری انجام دهد",
"agentDetail.configure.build.startBuild": "شروع ساخت",
- "agentDetail.configure.buildDraft.changes": "{{count}} تغییر برای اعمال",
"agentDetail.configure.buildDraft.discard": "رد کردن",
"agentDetail.configure.buildDraft.modeBadge": "حالت ساخت",
"agentDetail.configure.buildDraft.modeDescription": "شما در حالت ساخت هستید. این تنظیمات را از طریق چت سمت راست شکل دهید، سپس اعمال کنید.",
- "agentDetail.configure.buildDraft.noChanges": "تغییری برای اعمال وجود ندارد",
"agentDetail.configure.buildDraft.title": "پیش نویس ساخت",
"agentDetail.configure.chatFeatures.description": "تجربه چت کاربر نهایی را در Web app و سطوح چت خود شکل دهید.",
"agentDetail.configure.chatFeatures.title": "ویژگی‌های چت",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "دستورالعمل‌ها را اینجا بنویسید،",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} وجود ندارد",
"agentDetail.configure.prompt.tip": "نقش عامل را تعریف کنید و وظیفه معمول آن را شرح دهید. برای ارجاع صریح به مهارت‌ها، فایل‌ها، ابزارها و بازیابی‌های دانش از / استفاده کنید.",
"agentDetail.configure.publishBar.draft": "پیش‌نویس",
"agentDetail.configure.publishBar.publishUpdate": "انتشار به‌روزرسانی",
diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.json
index 94cd6ceb8cb..043b31d6945 100644
--- a/web/i18n/fa-IR/common.json
+++ b/web/i18n/fa-IR/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "غیرفعال",
"modelProvider.selector.discoverMoreInMarketplace": "اطلاعات بیشتر در Marketplace",
"modelProvider.selector.fromMarketplace": "از Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "پنهان کردن مدل‌های ناسازگار",
"modelProvider.selector.incompatible": "ناسازگار",
"modelProvider.selector.incompatibleTip": "این مدل در نسخه فعلی موجود نیست. لطفاً مدل دیگری انتخاب کنید.",
"modelProvider.selector.install": "نصب",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "هیچ ارائه‌دهنده مدلی پیکربندی نشده است",
"modelProvider.selector.noProviderConfiguredDesc": "در Marketplace جستجو کنید تا یکی نصب کنید، یا ارائه‌دهندگان را در تنظیمات پیکربندی کنید.",
"modelProvider.selector.onlyCompatibleModelsShown": "فقط مدل‌های سازگار نمایش داده می‌شوند",
+ "modelProvider.selector.showIncompatibleModels": "نمایش مدل‌های ناسازگار",
"modelProvider.showModels": "نمایش مدل‌ها",
"modelProvider.speechToTextModel.key": "مدل تبدیل گفتار به متن",
"modelProvider.speechToTextModel.tip": "مدل پیش‌فرض را برای ورودی گفتار به متن در مکالمه تنظیم کنید.",
diff --git a/web/i18n/fr-FR/agent-v-2.json b/web/i18n/fr-FR/agent-v-2.json
index 215df8016c0..ba60f976443 100644
--- a/web/i18n/fr-FR/agent-v-2.json
+++ b/web/i18n/fr-FR/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Créez votre agent par chat",
"agentDetail.configure.build.inputPlaceholder": "Décrivez ce que votre agent doit faire",
"agentDetail.configure.build.startBuild": "Démarrer la création",
- "agentDetail.configure.buildDraft.changes": "{{count}} modifications à appliquer",
"agentDetail.configure.buildDraft.discard": "Ignorer",
"agentDetail.configure.buildDraft.modeBadge": "Mode build",
"agentDetail.configure.buildDraft.modeDescription": "Vous êtes en mode build. Ajustez cette configuration avec le chat à droite, puis appliquez.",
- "agentDetail.configure.buildDraft.noChanges": "Aucune modification à appliquer",
"agentDetail.configure.buildDraft.title": "Brouillon de build",
"agentDetail.configure.chatFeatures.description": "Façonnez l’expérience de chat de l’utilisateur final sur votre webapp et vos surfaces de chat.",
"agentDetail.configure.chatFeatures.title": "Fonctionnalités de chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Écrivez les instructions ici,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} n’existe pas",
"agentDetail.configure.prompt.tip": "Définissez le rôle de l’agent et décrivez sa tâche habituelle. Utilisez / pour faire explicitement référence aux compétences, fichiers, outils et récupérations de connaissances.",
"agentDetail.configure.publishBar.draft": "Brouillon",
"agentDetail.configure.publishBar.publishUpdate": "Publier la mise à jour",
diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.json
index 5a89527c4cd..85773502285 100644
--- a/web/i18n/fr-FR/common.json
+++ b/web/i18n/fr-FR/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Désactivé",
"modelProvider.selector.discoverMoreInMarketplace": "Découvrir plus sur le Marketplace",
"modelProvider.selector.fromMarketplace": "Depuis le Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Masquer les modèles incompatibles",
"modelProvider.selector.incompatible": "Incompatible",
"modelProvider.selector.incompatibleTip": "Ce modèle n'est pas disponible dans la version actuelle. Veuillez sélectionner un autre modèle disponible.",
"modelProvider.selector.install": "Installer",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Aucun fournisseur de modèle configuré",
"modelProvider.selector.noProviderConfiguredDesc": "Parcourez le Marketplace pour en installer un, ou configurez les fournisseurs dans les paramètres.",
"modelProvider.selector.onlyCompatibleModelsShown": "Seuls les modèles compatibles sont affichés",
+ "modelProvider.selector.showIncompatibleModels": "Afficher les modèles incompatibles",
"modelProvider.showModels": "Montrer les modèles",
"modelProvider.speechToTextModel.key": "Modèle de Texte-à-Parole",
"modelProvider.speechToTextModel.tip": "Définissez le modèle par défaut pour l'entrée de texte par la parole dans la conversation.",
diff --git a/web/i18n/hi-IN/agent-v-2.json b/web/i18n/hi-IN/agent-v-2.json
index a6bb3017b96..18b4b583c56 100644
--- a/web/i18n/hi-IN/agent-v-2.json
+++ b/web/i18n/hi-IN/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "चैट करके अपना एजेंट बनाएं",
"agentDetail.configure.build.inputPlaceholder": "बताएं कि आपका एजेंट क्या करे",
"agentDetail.configure.build.startBuild": "बिल्ड शुरू करें",
- "agentDetail.configure.buildDraft.changes": "{{count}} बदलाव लागू करने हैं",
"agentDetail.configure.buildDraft.discard": "छोड़ें",
"agentDetail.configure.buildDraft.modeBadge": "बिल्ड मोड",
"agentDetail.configure.buildDraft.modeDescription": "आप बिल्ड मोड में हैं। दाईं ओर की चैट से इस सेटअप को आकार दें, फिर लागू करें।",
- "agentDetail.configure.buildDraft.noChanges": "लागू करने के लिए कोई बदलाव नहीं",
"agentDetail.configure.buildDraft.title": "बिल्ड ड्राफ्ट",
"agentDetail.configure.chatFeatures.description": "अपने Web app और चैट सतहों पर अंतिम-उपयोगकर्ता चैट अनुभव को आकार दें।",
"agentDetail.configure.chatFeatures.title": "चैट सुविधाएँ",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "यहाँ निर्देश लिखें,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} मौजूद नहीं है",
"agentDetail.configure.prompt.tip": "एजेंट की भूमिका परिभाषित करें और उसके सामान्य कार्य का वर्णन करें। Skills, Files, Tools और Knowledge Retrievals का स्पष्ट संदर्भ देने के लिए / का उपयोग करें।",
"agentDetail.configure.publishBar.draft": "ड्राफ्ट",
"agentDetail.configure.publishBar.publishUpdate": "अपडेट प्रकाशित करें",
diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.json
index 0fb4e519896..61211e65331 100644
--- a/web/i18n/hi-IN/common.json
+++ b/web/i18n/hi-IN/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "अक्षम",
"modelProvider.selector.discoverMoreInMarketplace": "Marketplace में और खोजें",
"modelProvider.selector.fromMarketplace": "Marketplace से",
+ "modelProvider.selector.hideIncompatibleModels": "असंगत मॉडल छिपाएं",
"modelProvider.selector.incompatible": "असंगत",
"modelProvider.selector.incompatibleTip": "यह मॉडल वर्तमान संस्करण में उपलब्ध नहीं है। कृपया कोई अन्य उपलब्ध मॉडल चुनें।",
"modelProvider.selector.install": "इंस्टॉल करें",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "कोई मॉडल प्रदाता कॉन्फ़िगर नहीं है",
"modelProvider.selector.noProviderConfiguredDesc": "इंस्टॉल करने के लिए Marketplace ब्राउज़ करें, या सेटिंग्स में प्रदाता कॉन्फ़िगर करें।",
"modelProvider.selector.onlyCompatibleModelsShown": "केवल संगत मॉडल दिखाए गए हैं",
+ "modelProvider.selector.showIncompatibleModels": "असंगत मॉडल दिखाएं",
"modelProvider.showModels": "मॉडल्स दिखाएं",
"modelProvider.speechToTextModel.key": "भाषण-से-पाठ मॉडल",
"modelProvider.speechToTextModel.tip": "संवाद में भाषण-से-पाठ इनपुट के लिए डिफ़ॉल्ट मॉडल सेट करें।",
diff --git a/web/i18n/id-ID/agent-v-2.json b/web/i18n/id-ID/agent-v-2.json
index 1be97df9c64..4869392bc5a 100644
--- a/web/i18n/id-ID/agent-v-2.json
+++ b/web/i18n/id-ID/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Bangun agen Anda lewat chat",
"agentDetail.configure.build.inputPlaceholder": "Jelaskan apa yang harus dilakukan agen Anda",
"agentDetail.configure.build.startBuild": "Mulai build",
- "agentDetail.configure.buildDraft.changes": "{{count}} perubahan untuk diterapkan",
"agentDetail.configure.buildDraft.discard": "Buang",
"agentDetail.configure.buildDraft.modeBadge": "Mode build",
"agentDetail.configure.buildDraft.modeDescription": "Anda berada dalam mode build. Bentuk pengaturan ini lewat chat di kanan, lalu terapkan.",
- "agentDetail.configure.buildDraft.noChanges": "Tidak ada perubahan untuk diterapkan",
"agentDetail.configure.buildDraft.title": "Draf build",
"agentDetail.configure.chatFeatures.description": "Bentuk pengalaman chat pengguna akhir di Web app dan permukaan chat Anda.",
"agentDetail.configure.chatFeatures.title": "Fitur Chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Tulis instruksi di sini,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} tidak ada",
"agentDetail.configure.prompt.tip": "Tentukan peran agen dan jelaskan tugas umumnya. Gunakan / untuk membuat referensi eksplisit ke Skills, Files, Tools, dan Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Draf",
"agentDetail.configure.publishBar.publishUpdate": "Terbitkan pembaruan",
diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.json
index 022b998c80f..807ed4e4ad6 100644
--- a/web/i18n/id-ID/common.json
+++ b/web/i18n/id-ID/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Dinonaktifkan",
"modelProvider.selector.discoverMoreInMarketplace": "Temukan lebih banyak di Marketplace",
"modelProvider.selector.fromMarketplace": "Dari Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Sembunyikan model yang tidak kompatibel",
"modelProvider.selector.incompatible": "Tidak kompatibel",
"modelProvider.selector.incompatibleTip": "Model ini tidak tersedia dalam versi saat ini. Silakan pilih model lain yang tersedia.",
"modelProvider.selector.install": "Instal",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Belum ada penyedia model yang dikonfigurasi",
"modelProvider.selector.noProviderConfiguredDesc": "Jelajahi Marketplace untuk menginstal, atau konfigurasikan penyedia di pengaturan.",
"modelProvider.selector.onlyCompatibleModelsShown": "Hanya model yang kompatibel yang ditampilkan",
+ "modelProvider.selector.showIncompatibleModels": "Tampilkan model yang tidak kompatibel",
"modelProvider.showModels": "Tampilkan Model",
"modelProvider.speechToTextModel.key": "Model Ucapan-ke-Teks",
"modelProvider.speechToTextModel.tip": "Atur model default untuk input ucapan-ke-teks dalam percakapan.",
diff --git a/web/i18n/it-IT/agent-v-2.json b/web/i18n/it-IT/agent-v-2.json
index 1f2ce754164..339eeedbc8f 100644
--- a/web/i18n/it-IT/agent-v-2.json
+++ b/web/i18n/it-IT/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Crea il tuo agente con la chat",
"agentDetail.configure.build.inputPlaceholder": "Descrivi cosa dovrebbe fare il tuo agente",
"agentDetail.configure.build.startBuild": "Avvia build",
- "agentDetail.configure.buildDraft.changes": "{{count}} modifiche da applicare",
"agentDetail.configure.buildDraft.discard": "Scarta",
"agentDetail.configure.buildDraft.modeBadge": "Modalità build",
"agentDetail.configure.buildDraft.modeDescription": "Sei in modalità build. Modella questa configurazione tramite la chat a destra, poi applica.",
- "agentDetail.configure.buildDraft.noChanges": "Nessuna modifica da applicare",
"agentDetail.configure.buildDraft.title": "Bozza di build",
"agentDetail.configure.chatFeatures.description": "Definisci l’esperienza di chat per l’utente finale sulla tua webapp e sulle superfici di chat.",
"agentDetail.configure.chatFeatures.title": "Funzionalità chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Scrivi le istruzioni qui,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} non esiste",
"agentDetail.configure.prompt.tip": "Definisci il ruolo dell’agente e descrivi la sua attività tipica. Usa / per fare riferimento esplicito a abilità, file, strumenti e recuperi di conoscenza.",
"agentDetail.configure.publishBar.draft": "Bozza",
"agentDetail.configure.publishBar.publishUpdate": "Pubblica aggiornamento",
diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.json
index 1f0bece9b05..8b61eb2a839 100644
--- a/web/i18n/it-IT/common.json
+++ b/web/i18n/it-IT/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Disabilitato",
"modelProvider.selector.discoverMoreInMarketplace": "Scopri di più nel Marketplace",
"modelProvider.selector.fromMarketplace": "Dal Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Nascondi modelli incompatibili",
"modelProvider.selector.incompatible": "Incompatibile",
"modelProvider.selector.incompatibleTip": "Questo modello non è disponibile nella versione corrente. Seleziona un altro modello disponibile.",
"modelProvider.selector.install": "Installa",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Nessun fornitore di modelli configurato",
"modelProvider.selector.noProviderConfiguredDesc": "Cerca nel Marketplace per installarne uno o configura i fornitori nelle impostazioni.",
"modelProvider.selector.onlyCompatibleModelsShown": "Vengono mostrati solo i modelli compatibili",
+ "modelProvider.selector.showIncompatibleModels": "Mostra modelli incompatibili",
"modelProvider.showModels": "Mostra Modelli",
"modelProvider.speechToTextModel.key": "Modello da Voce a Testo",
"modelProvider.speechToTextModel.tip": "Imposta il modello predefinito per l'input da voce a testo nella conversazione.",
diff --git a/web/i18n/ja-JP/agent-v-2.json b/web/i18n/ja-JP/agent-v-2.json
index f80ff2a772c..603c9aeb39b 100644
--- a/web/i18n/ja-JP/agent-v-2.json
+++ b/web/i18n/ja-JP/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "チャットでエージェントを作成",
"agentDetail.configure.build.inputPlaceholder": "エージェントに実行させたいことを説明",
"agentDetail.configure.build.startBuild": "ビルドを開始",
- "agentDetail.configure.buildDraft.changes": "適用する変更 {{count}} 件",
"agentDetail.configure.buildDraft.discard": "破棄",
"agentDetail.configure.buildDraft.modeBadge": "ビルドモード",
"agentDetail.configure.buildDraft.modeDescription": "ビルドモードです。右側のチャットでこの設定を調整してから適用してください。",
- "agentDetail.configure.buildDraft.noChanges": "適用する変更はありません",
"agentDetail.configure.buildDraft.title": "ビルドドラフト",
"agentDetail.configure.chatFeatures.description": "Web app やチャット画面でのエンドユーザー向けチャット体験を設定します。",
"agentDetail.configure.chatFeatures.title": "チャット機能",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "ここに指示を記述してください、",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} は存在しません",
"agentDetail.configure.prompt.tip": "エージェントの役割を定義し、通常のタスクを説明します。/ を使ってスキル、ファイル、ツール、ナレッジ検索を明示的に参照してください。",
"agentDetail.configure.publishBar.draft": "ドラフト",
"agentDetail.configure.publishBar.publishUpdate": "更新を公開",
diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.json
index 8ba25af57c9..e1c151c29c9 100644
--- a/web/i18n/ja-JP/common.json
+++ b/web/i18n/ja-JP/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "無効",
"modelProvider.selector.discoverMoreInMarketplace": "マーケットプレイスでもっと探す",
"modelProvider.selector.fromMarketplace": "マーケットプレイスから",
+ "modelProvider.selector.hideIncompatibleModels": "互換性のないモデルを非表示",
"modelProvider.selector.incompatible": "非互換",
"modelProvider.selector.incompatibleTip": "このモデルは現在のバージョンでは利用できません。別の利用可能なモデルを選択してください。",
"modelProvider.selector.install": "インストール",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "モデルプロバイダーが設定されていません",
"modelProvider.selector.noProviderConfiguredDesc": "マーケットプレイスでインストールするか、設定でプロバイダーを設定してください。",
"modelProvider.selector.onlyCompatibleModelsShown": "互換性のあるモデルのみが表示されます",
+ "modelProvider.selector.showIncompatibleModels": "互換性のないモデルを表示",
"modelProvider.showModels": "モデルの表示",
"modelProvider.speechToTextModel.key": "音声-to-テキストモデル",
"modelProvider.speechToTextModel.tip": "会話での音声-to-テキスト入力に使用するデフォルトモデルを設定します。",
diff --git a/web/i18n/ko-KR/agent-v-2.json b/web/i18n/ko-KR/agent-v-2.json
index e863ce30565..c79a9540842 100644
--- a/web/i18n/ko-KR/agent-v-2.json
+++ b/web/i18n/ko-KR/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "채팅으로 에이전트 만들기",
"agentDetail.configure.build.inputPlaceholder": "에이전트가 해야 할 일을 설명하세요",
"agentDetail.configure.build.startBuild": "빌드 시작",
- "agentDetail.configure.buildDraft.changes": "적용할 변경 사항 {{count}}개",
"agentDetail.configure.buildDraft.discard": "폐기",
"agentDetail.configure.buildDraft.modeBadge": "빌드 모드",
"agentDetail.configure.buildDraft.modeDescription": "빌드 모드입니다. 오른쪽 채팅으로 이 설정을 다듬은 뒤 적용하세요.",
- "agentDetail.configure.buildDraft.noChanges": "적용할 변경 사항 없음",
"agentDetail.configure.buildDraft.title": "빌드 초안",
"agentDetail.configure.chatFeatures.description": "Web app 및 채팅 화면에서의 최종 사용자 채팅 경험을 구성합니다.",
"agentDetail.configure.chatFeatures.title": "채팅 기능",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "여기에 지시 사항을 작성하세요,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}}이(가) 존재하지 않습니다",
"agentDetail.configure.prompt.tip": "에이전트의 역할을 정의하고 일반적인 작업을 설명합니다. /를 사용해 스킬, 파일, 도구, 지식 검색을 명시적으로 참조하세요.",
"agentDetail.configure.publishBar.draft": "초안",
"agentDetail.configure.publishBar.publishUpdate": "업데이트 게시",
diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.json
index b7a701c49b8..6a0664818f8 100644
--- a/web/i18n/ko-KR/common.json
+++ b/web/i18n/ko-KR/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "비활성화됨",
"modelProvider.selector.discoverMoreInMarketplace": "마켓플레이스에서 더 찾아보기",
"modelProvider.selector.fromMarketplace": "마켓플레이스에서",
+ "modelProvider.selector.hideIncompatibleModels": "호환되지 않는 모델 숨기기",
"modelProvider.selector.incompatible": "호환되지 않음",
"modelProvider.selector.incompatibleTip": "이 모델은 현재 버전에서 사용할 수 없습니다. 다른 사용 가능한 모델을 선택하세요.",
"modelProvider.selector.install": "설치",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "모델 공급자가 구성되지 않았습니다",
"modelProvider.selector.noProviderConfiguredDesc": "마켓플레이스에서 설치하거나 설정에서 공급자를 구성하세요.",
"modelProvider.selector.onlyCompatibleModelsShown": "호환되는 모델만 표시됩니다",
+ "modelProvider.selector.showIncompatibleModels": "호환되지 않는 모델 표시",
"modelProvider.showModels": "모델 표시",
"modelProvider.speechToTextModel.key": "음성-to-텍스트 모델",
"modelProvider.speechToTextModel.tip": "대화에서의 음성-to-텍스트 입력에 사용되는 기본 모델을 설정합니다.",
diff --git a/web/i18n/nl-NL/agent-v-2.json b/web/i18n/nl-NL/agent-v-2.json
index 0321ffdb143..9e7e87d3018 100644
--- a/web/i18n/nl-NL/agent-v-2.json
+++ b/web/i18n/nl-NL/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Bouw je agent via chat",
"agentDetail.configure.build.inputPlaceholder": "Beschrijf wat je agent moet doen",
"agentDetail.configure.build.startBuild": "Build starten",
- "agentDetail.configure.buildDraft.changes": "{{count}} wijzigingen om toe te passen",
"agentDetail.configure.buildDraft.discard": "Negeren",
"agentDetail.configure.buildDraft.modeBadge": "Buildmodus",
"agentDetail.configure.buildDraft.modeDescription": "Je bent in buildmodus. Werk deze configuratie bij via de chat rechts en pas daarna toe.",
- "agentDetail.configure.buildDraft.noChanges": "Geen wijzigingen om toe te passen",
"agentDetail.configure.buildDraft.title": "Buildconcept",
"agentDetail.configure.chatFeatures.description": "Geef vorm aan de chatervaring voor eindgebruikers in je webapp en chatoppervlakken.",
"agentDetail.configure.chatFeatures.title": "Chatfuncties",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Schrijf hier instructies,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} bestaat niet",
"agentDetail.configure.prompt.tip": "Definieer de rol van de agent en beschrijf zijn typische taak. Gebruik / om expliciet te verwijzen naar skills, bestanden, tools en kennisophalingen.",
"agentDetail.configure.publishBar.draft": "Concept",
"agentDetail.configure.publishBar.publishUpdate": "Update publiceren",
diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.json
index f9145e7b0e1..5834f227105 100644
--- a/web/i18n/nl-NL/common.json
+++ b/web/i18n/nl-NL/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Uitgeschakeld",
"modelProvider.selector.discoverMoreInMarketplace": "Ontdek meer in de Marketplace",
"modelProvider.selector.fromMarketplace": "Vanuit de Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Incompatibele modellen verbergen",
"modelProvider.selector.incompatible": "Incompatibel",
"modelProvider.selector.incompatibleTip": "Dit model is niet beschikbaar in de huidige versie. Selecteer een ander beschikbaar model.",
"modelProvider.selector.install": "Installeren",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Geen modelprovider geconfigureerd",
"modelProvider.selector.noProviderConfiguredDesc": "Blader in de Marketplace om er een te installeren, of configureer providers in de instellingen.",
"modelProvider.selector.onlyCompatibleModelsShown": "Alleen compatibele modellen worden weergegeven",
+ "modelProvider.selector.showIncompatibleModels": "Incompatibele modellen weergeven",
"modelProvider.showModels": "Show Models",
"modelProvider.speechToTextModel.key": "Speech-to-Text Model",
"modelProvider.speechToTextModel.tip": "Set the default model for speech-to-text input in conversation.",
diff --git a/web/i18n/pl-PL/agent-v-2.json b/web/i18n/pl-PL/agent-v-2.json
index f3ea570a96b..fc6fa1d7e24 100644
--- a/web/i18n/pl-PL/agent-v-2.json
+++ b/web/i18n/pl-PL/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Buduj agenta przez czat",
"agentDetail.configure.build.inputPlaceholder": "Opisz, co agent ma robić",
"agentDetail.configure.build.startBuild": "Rozpocznij budowanie",
- "agentDetail.configure.buildDraft.changes": "{{count}} zmian do zastosowania",
"agentDetail.configure.buildDraft.discard": "Odrzuć",
"agentDetail.configure.buildDraft.modeBadge": "Tryb budowania",
"agentDetail.configure.buildDraft.modeDescription": "Jesteś w trybie budowania. Dostosuj tę konfigurację przez czat po prawej, a następnie zastosuj.",
- "agentDetail.configure.buildDraft.noChanges": "Brak zmian do zastosowania",
"agentDetail.configure.buildDraft.title": "Szkic budowania",
"agentDetail.configure.chatFeatures.description": "Ukształtuj doświadczenie czatu użytkownika końcowego w aplikacji webowej i powierzchniach czatu.",
"agentDetail.configure.chatFeatures.title": "Funkcje czatu",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Napisz tutaj instrukcje,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} nie istnieje",
"agentDetail.configure.prompt.tip": "Zdefiniuj rolę agenta i opisz jego typowe zadanie. Użyj /, aby jawnie odwołać się do umiejętności, plików, narzędzi i pobierania wiedzy.",
"agentDetail.configure.publishBar.draft": "Wersja robocza",
"agentDetail.configure.publishBar.publishUpdate": "Opublikuj aktualizację",
diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.json
index 25af5d5f368..d8b17617e0b 100644
--- a/web/i18n/pl-PL/common.json
+++ b/web/i18n/pl-PL/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Wyłączony",
"modelProvider.selector.discoverMoreInMarketplace": "Odkryj więcej w Marketplace",
"modelProvider.selector.fromMarketplace": "Z Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Ukryj niezgodne modele",
"modelProvider.selector.incompatible": "Niekompatybilny",
"modelProvider.selector.incompatibleTip": "Ten model nie jest dostępny w bieżącej wersji. Proszę wybrać inny dostępny model.",
"modelProvider.selector.install": "Zainstaluj",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Nie skonfigurowano dostawcy modeli",
"modelProvider.selector.noProviderConfiguredDesc": "Przeglądaj Marketplace, aby zainstalować dostawcę, lub skonfiguruj dostawców w ustawieniach.",
"modelProvider.selector.onlyCompatibleModelsShown": "Wyświetlane są tylko kompatybilne modele",
+ "modelProvider.selector.showIncompatibleModels": "Pokaż niezgodne modele",
"modelProvider.showModels": "Pokaż modele",
"modelProvider.speechToTextModel.key": "Model mowy na tekst",
"modelProvider.speechToTextModel.tip": "Ustaw domyślny model do przetwarzania mowy na tekst w rozmowach.",
diff --git a/web/i18n/pt-BR/agent-v-2.json b/web/i18n/pt-BR/agent-v-2.json
index c06c1d40374..a49613b9680 100644
--- a/web/i18n/pt-BR/agent-v-2.json
+++ b/web/i18n/pt-BR/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Crie seu agente conversando",
"agentDetail.configure.build.inputPlaceholder": "Descreva o que seu agente deve fazer",
"agentDetail.configure.build.startBuild": "Iniciar build",
- "agentDetail.configure.buildDraft.changes": "{{count}} alterações para aplicar",
"agentDetail.configure.buildDraft.discard": "Descartar",
"agentDetail.configure.buildDraft.modeBadge": "Modo build",
"agentDetail.configure.buildDraft.modeDescription": "Você está no modo build. Ajuste esta configuração pelo chat à direita e depois aplique.",
- "agentDetail.configure.buildDraft.noChanges": "Nenhuma alteração para aplicar",
"agentDetail.configure.buildDraft.title": "Rascunho de build",
"agentDetail.configure.chatFeatures.description": "Modele a experiência de chat do usuário final no seu webapp e superfícies de chat.",
"agentDetail.configure.chatFeatures.title": "Recursos de chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Escreva as instruções aqui,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} não existe",
"agentDetail.configure.prompt.tip": "Defina o papel do agente e descreva sua tarefa típica. Use / para fazer referência explícita a habilidades, arquivos, ferramentas e recuperações de conhecimento.",
"agentDetail.configure.publishBar.draft": "Rascunho",
"agentDetail.configure.publishBar.publishUpdate": "Publicar atualização",
diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.json
index 05cd08af5be..4eb27aec7aa 100644
--- a/web/i18n/pt-BR/common.json
+++ b/web/i18n/pt-BR/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Desativado",
"modelProvider.selector.discoverMoreInMarketplace": "Descubra mais no Marketplace",
"modelProvider.selector.fromMarketplace": "Do Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Ocultar modelos incompatíveis",
"modelProvider.selector.incompatible": "Incompatível",
"modelProvider.selector.incompatibleTip": "Este modelo não está disponível na versão atual. Por favor, selecione outro modelo disponível.",
"modelProvider.selector.install": "Instalar",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Nenhum provedor de modelo configurado",
"modelProvider.selector.noProviderConfiguredDesc": "Navegue pelo Marketplace para instalar um, ou configure provedores nas configurações.",
"modelProvider.selector.onlyCompatibleModelsShown": "Apenas modelos compatíveis são exibidos",
+ "modelProvider.selector.showIncompatibleModels": "Mostrar modelos incompatíveis",
"modelProvider.showModels": "Mostrar Modelos",
"modelProvider.speechToTextModel.key": "Modelo de Fala para Texto",
"modelProvider.speechToTextModel.tip": "Defina o modelo padrão para entrada de fala para texto na conversa.",
diff --git a/web/i18n/ro-RO/agent-v-2.json b/web/i18n/ro-RO/agent-v-2.json
index 5c2355341fb..f431c2ebba0 100644
--- a/web/i18n/ro-RO/agent-v-2.json
+++ b/web/i18n/ro-RO/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Construiește agentul prin chat",
"agentDetail.configure.build.inputPlaceholder": "Descrie ce ar trebui să facă agentul tău",
"agentDetail.configure.build.startBuild": "Pornește build-ul",
- "agentDetail.configure.buildDraft.changes": "{{count}} modificări de aplicat",
"agentDetail.configure.buildDraft.discard": "Renunță",
"agentDetail.configure.buildDraft.modeBadge": "Mod build",
"agentDetail.configure.buildDraft.modeDescription": "Ești în modul build. Ajustează această configurare prin chatul din dreapta, apoi aplică.",
- "agentDetail.configure.buildDraft.noChanges": "Nu există modificări de aplicat",
"agentDetail.configure.buildDraft.title": "Schiță de build",
"agentDetail.configure.chatFeatures.description": "Modelează experiența de chat a utilizatorului final pe webapp-ul tău și pe suprafețele de chat.",
"agentDetail.configure.chatFeatures.title": "Funcții de chat",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Scrieți instrucțiunile aici,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} nu există",
"agentDetail.configure.prompt.tip": "Definiți rolul agentului și descrieți sarcina sa tipică. Folosiți / pentru a face referire explicită la abilități, fișiere, instrumente și recuperări de cunoștințe.",
"agentDetail.configure.publishBar.draft": "Ciornă",
"agentDetail.configure.publishBar.publishUpdate": "Publică actualizarea",
diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.json
index b36af8851f0..041bf1239fc 100644
--- a/web/i18n/ro-RO/common.json
+++ b/web/i18n/ro-RO/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Dezactivat",
"modelProvider.selector.discoverMoreInMarketplace": "Descoperiți mai multe în Marketplace",
"modelProvider.selector.fromMarketplace": "Din Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Ascunde modelele incompatibile",
"modelProvider.selector.incompatible": "Incompatibil",
"modelProvider.selector.incompatibleTip": "Acest model nu este disponibil în versiunea curentă. Vă rugăm să selectați alt model disponibil.",
"modelProvider.selector.install": "Instalare",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Niciun furnizor de modele configurat",
"modelProvider.selector.noProviderConfiguredDesc": "Răsfoiți Marketplace pentru a instala unul sau configurați furnizorii în setări.",
"modelProvider.selector.onlyCompatibleModelsShown": "Sunt afișate doar modelele compatibile",
+ "modelProvider.selector.showIncompatibleModels": "Afișează modelele incompatibile",
"modelProvider.showModels": "Arată modele",
"modelProvider.speechToTextModel.key": "Model de conversie text-la-vorbire",
"modelProvider.speechToTextModel.tip": "Setați modelul implicit pentru intrarea de conversie text-la-vorbire în conversație.",
diff --git a/web/i18n/ru-RU/agent-v-2.json b/web/i18n/ru-RU/agent-v-2.json
index 141acee3bf8..890559ca68a 100644
--- a/web/i18n/ru-RU/agent-v-2.json
+++ b/web/i18n/ru-RU/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Создайте агента в чате",
"agentDetail.configure.build.inputPlaceholder": "Опишите, что должен делать агент",
"agentDetail.configure.build.startBuild": "Начать сборку",
- "agentDetail.configure.buildDraft.changes": "{{count}} изменений для применения",
"agentDetail.configure.buildDraft.discard": "Отменить",
"agentDetail.configure.buildDraft.modeBadge": "Режим сборки",
"agentDetail.configure.buildDraft.modeDescription": "Вы в режиме сборки. Настройте эту конфигурацию через чат справа, затем примените изменения.",
- "agentDetail.configure.buildDraft.noChanges": "Нет изменений для применения",
"agentDetail.configure.buildDraft.title": "Черновик сборки",
"agentDetail.configure.chatFeatures.description": "Настройте чат-опыт конечного пользователя в вашем веб-приложении и чат-поверхностях.",
"agentDetail.configure.chatFeatures.title": "Функции чата",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Напишите инструкции здесь,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} не существует",
"agentDetail.configure.prompt.tip": "Определите роль агента и опишите его типичную задачу. Используйте /, чтобы явно ссылаться на навыки, файлы, инструменты и извлечение знаний.",
"agentDetail.configure.publishBar.draft": "Черновик",
"agentDetail.configure.publishBar.publishUpdate": "Опубликовать обновление",
diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.json
index 8ee073dbf2e..313011ca004 100644
--- a/web/i18n/ru-RU/common.json
+++ b/web/i18n/ru-RU/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Отключено",
"modelProvider.selector.discoverMoreInMarketplace": "Найти больше в Marketplace",
"modelProvider.selector.fromMarketplace": "Из Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Скрыть несовместимые модели",
"modelProvider.selector.incompatible": "Несовместимо",
"modelProvider.selector.incompatibleTip": "Эта модель недоступна в текущей версии. Пожалуйста, выберите другую доступную модель.",
"modelProvider.selector.install": "Установить",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Поставщик моделей не настроен",
"modelProvider.selector.noProviderConfiguredDesc": "Установите из Marketplace или настройте поставщиков в настройках.",
"modelProvider.selector.onlyCompatibleModelsShown": "Показаны только совместимые модели",
+ "modelProvider.selector.showIncompatibleModels": "Показать несовместимые модели",
"modelProvider.showModels": "Показать модели",
"modelProvider.speechToTextModel.key": "Модель преобразования речи в текст",
"modelProvider.speechToTextModel.tip": "Установите модель по умолчанию для ввода речи в текст в разговоре.",
diff --git a/web/i18n/sl-SI/agent-v-2.json b/web/i18n/sl-SI/agent-v-2.json
index c503342a267..f594eb2fdab 100644
--- a/web/i18n/sl-SI/agent-v-2.json
+++ b/web/i18n/sl-SI/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Izdelajte agenta s klepetom",
"agentDetail.configure.build.inputPlaceholder": "Opišite, kaj naj vaš agent počne",
"agentDetail.configure.build.startBuild": "Začni gradnjo",
- "agentDetail.configure.buildDraft.changes": "{{count}} sprememb za uporabo",
"agentDetail.configure.buildDraft.discard": "Zavrzi",
"agentDetail.configure.buildDraft.modeBadge": "Način gradnje",
"agentDetail.configure.buildDraft.modeDescription": "Ste v načinu gradnje. Nastavitev oblikujte s klepetom na desni, nato jo uporabite.",
- "agentDetail.configure.buildDraft.noChanges": "Ni sprememb za uporabo",
"agentDetail.configure.buildDraft.title": "Osnutek gradnje",
"agentDetail.configure.chatFeatures.description": "Oblikujte uporabniško izkušnjo klepeta v vaši spletni aplikaciji in klepetalnih površinah.",
"agentDetail.configure.chatFeatures.title": "Funkcije klepeta",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Tukaj napišite navodila,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} ne obstaja",
"agentDetail.configure.prompt.tip": "Določite vlogo agenta in opišite njegovo tipično opravilo. Uporabite / za izrecno sklicevanje na veščine, datoteke, orodja in pridobivanje znanja.",
"agentDetail.configure.publishBar.draft": "Osnutek",
"agentDetail.configure.publishBar.publishUpdate": "Objavi posodobitev",
diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.json
index ab5c23a62e2..88b2c3a9dc3 100644
--- a/web/i18n/sl-SI/common.json
+++ b/web/i18n/sl-SI/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Onemogočeno",
"modelProvider.selector.discoverMoreInMarketplace": "Odkrijte več v Tržnici",
"modelProvider.selector.fromMarketplace": "Iz Tržnice",
+ "modelProvider.selector.hideIncompatibleModels": "Skrij nezdružljive modele",
"modelProvider.selector.incompatible": "Nezdružljivo",
"modelProvider.selector.incompatibleTip": "Ta model ni na voljo v trenutni različici. Izberite drug razpoložljiv model.",
"modelProvider.selector.install": "Namesti",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Noben ponudnik modelov ni konfiguriran",
"modelProvider.selector.noProviderConfiguredDesc": "Poiščite v Tržnici za namestitev ali konfigurirajte ponudnike v nastavitvah.",
"modelProvider.selector.onlyCompatibleModelsShown": "Prikazani so samo združljivi modeli",
+ "modelProvider.selector.showIncompatibleModels": "Prikaži nezdružljive modele",
"modelProvider.showModels": "Prikaži modele",
"modelProvider.speechToTextModel.key": "Model za pretvorbo govora v besedilo",
"modelProvider.speechToTextModel.tip": "Nastavite privzeti model za vnos govora v besedilo v pogovoru.",
diff --git a/web/i18n/th-TH/agent-v-2.json b/web/i18n/th-TH/agent-v-2.json
index d5668c0fa10..ea2d5e4bf67 100644
--- a/web/i18n/th-TH/agent-v-2.json
+++ b/web/i18n/th-TH/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "สร้างเอเจนต์ของคุณด้วยการแชท",
"agentDetail.configure.build.inputPlaceholder": "อธิบายว่าเอเจนต์ของคุณควรทำอะไร",
"agentDetail.configure.build.startBuild": "เริ่มสร้าง",
- "agentDetail.configure.buildDraft.changes": "{{count}} รายการเปลี่ยนแปลงที่ต้องใช้",
"agentDetail.configure.buildDraft.discard": "ทิ้ง",
"agentDetail.configure.buildDraft.modeBadge": "โหมด Build",
"agentDetail.configure.buildDraft.modeDescription": "คุณอยู่ในโหมด Build ปรับแต่งการตั้งค่านี้ผ่านแชททางขวา แล้วกดนำไปใช้",
- "agentDetail.configure.buildDraft.noChanges": "ไม่มีการเปลี่ยนแปลงที่ต้องใช้",
"agentDetail.configure.buildDraft.title": "ฉบับร่าง Build",
"agentDetail.configure.chatFeatures.description": "กำหนดประสบการณ์การแชทของผู้ใช้ปลายทางบน Web app และหน้าจอแชท",
"agentDetail.configure.chatFeatures.title": "ฟีเจอร์แชท",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "เขียนคำสั่งที่นี่,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} ไม่มีอยู่",
"agentDetail.configure.prompt.tip": "กำหนดบทบาทของตัวแทนและอธิบายงานทั่วไป ใช้ / เพื่ออ้างอิง Skills, Files, Tools และ Knowledge Retrievals อย่างชัดเจน",
"agentDetail.configure.publishBar.draft": "ฉบับร่าง",
"agentDetail.configure.publishBar.publishUpdate": "เผยแพร่อัปเดต",
diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.json
index 74c67abb94f..5c2e35f5243 100644
--- a/web/i18n/th-TH/common.json
+++ b/web/i18n/th-TH/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "ปิดใช้งาน",
"modelProvider.selector.discoverMoreInMarketplace": "ค้นพบเพิ่มเติมใน Marketplace",
"modelProvider.selector.fromMarketplace": "จาก Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "ซ่อนโมเดลที่ไม่รองรับ",
"modelProvider.selector.incompatible": "ไม่รองรับ",
"modelProvider.selector.incompatibleTip": "โมเดลนี้ไม่พร้อมใช้งานในเวอร์ชันปัจจุบัน กรุณาเลือกโมเดลอื่นที่พร้อมใช้งาน",
"modelProvider.selector.install": "ติดตั้ง",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "ยังไม่ได้กำหนดค่าผู้ให้บริการโมเดล",
"modelProvider.selector.noProviderConfiguredDesc": "เรียกดู Marketplace เพื่อติดตั้ง หรือกำหนดค่าผู้ให้บริการในการตั้งค่า",
"modelProvider.selector.onlyCompatibleModelsShown": "แสดงเฉพาะโมเดลที่รองรับเท่านั้น",
+ "modelProvider.selector.showIncompatibleModels": "แสดงโมเดลที่ไม่รองรับ",
"modelProvider.showModels": "แสดงโมเดล",
"modelProvider.speechToTextModel.key": "โมเดลคําพูดเป็นข้อความ",
"modelProvider.speechToTextModel.tip": "ตั้งค่าโมเดลเริ่มต้นสําหรับการป้อนข้อมูลคําพูดเป็นข้อความในการสนทนา",
diff --git a/web/i18n/tr-TR/agent-v-2.json b/web/i18n/tr-TR/agent-v-2.json
index 1496617207c..1f44c31217b 100644
--- a/web/i18n/tr-TR/agent-v-2.json
+++ b/web/i18n/tr-TR/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Aracınızı sohbet ederek oluşturun",
"agentDetail.configure.build.inputPlaceholder": "Aracınızın ne yapması gerektiğini açıklayın",
"agentDetail.configure.build.startBuild": "Build’i başlat",
- "agentDetail.configure.buildDraft.changes": "Uygulanacak {{count}} değişiklik",
"agentDetail.configure.buildDraft.discard": "Vazgeç",
"agentDetail.configure.buildDraft.modeBadge": "Build modu",
"agentDetail.configure.buildDraft.modeDescription": "Build modundasınız. Bu kurulumu sağdaki sohbetle şekillendirin, ardından uygulayın.",
- "agentDetail.configure.buildDraft.noChanges": "Uygulanacak değişiklik yok",
"agentDetail.configure.buildDraft.title": "Build taslağı",
"agentDetail.configure.chatFeatures.description": "Web app ve sohbet yüzeylerinizde son kullanıcı sohbet deneyimini şekillendirin.",
"agentDetail.configure.chatFeatures.title": "Sohbet Özellikleri",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Talimatları buraya yazın,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} mevcut değil",
"agentDetail.configure.prompt.tip": "Aracının rolünü tanımlayın ve tipik görevini açıklayın. Skills, Files, Tools ve Knowledge Retrievals için açık referans vermek üzere / kullanın.",
"agentDetail.configure.publishBar.draft": "Taslak",
"agentDetail.configure.publishBar.publishUpdate": "Güncellemeyi yayınla",
diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.json
index 32b6c8a1a2c..5df1bb70ae9 100644
--- a/web/i18n/tr-TR/common.json
+++ b/web/i18n/tr-TR/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Devre Dışı",
"modelProvider.selector.discoverMoreInMarketplace": "Pazar Yeri'nde daha fazlasını keşfedin",
"modelProvider.selector.fromMarketplace": "Pazar Yeri'nden",
+ "modelProvider.selector.hideIncompatibleModels": "Uyumsuz modelleri gizle",
"modelProvider.selector.incompatible": "Uyumsuz",
"modelProvider.selector.incompatibleTip": "Bu model mevcut sürümde kullanılamıyor. Lütfen başka bir kullanılabilir model seçin.",
"modelProvider.selector.install": "Yükle",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Yapılandırılmış model sağlayıcı yok",
"modelProvider.selector.noProviderConfiguredDesc": "Yüklemek için Pazar Yeri'ne göz atın veya ayarlardan sağlayıcıları yapılandırın.",
"modelProvider.selector.onlyCompatibleModelsShown": "Yalnızca uyumlu modeller gösterilir",
+ "modelProvider.selector.showIncompatibleModels": "Uyumsuz modelleri göster",
"modelProvider.showModels": "Modelleri Göster",
"modelProvider.speechToTextModel.key": "Konuşmadan Metne Modeli",
"modelProvider.speechToTextModel.tip": "Konuşmada konuşmadan metne giriş için varsayılan modeli ayarlayın.",
diff --git a/web/i18n/uk-UA/agent-v-2.json b/web/i18n/uk-UA/agent-v-2.json
index 0d368a75ae3..e57e6c27c69 100644
--- a/web/i18n/uk-UA/agent-v-2.json
+++ b/web/i18n/uk-UA/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Створіть агента через чат",
"agentDetail.configure.build.inputPlaceholder": "Опишіть, що має робити ваш агент",
"agentDetail.configure.build.startBuild": "Почати збірку",
- "agentDetail.configure.buildDraft.changes": "{{count}} змін для застосування",
"agentDetail.configure.buildDraft.discard": "Відхилити",
"agentDetail.configure.buildDraft.modeBadge": "Режим збірки",
"agentDetail.configure.buildDraft.modeDescription": "Ви в режимі збірки. Налаштуйте цю конфігурацію через чат праворуч, а потім застосуйте.",
- "agentDetail.configure.buildDraft.noChanges": "Немає змін для застосування",
"agentDetail.configure.buildDraft.title": "Чернетка збірки",
"agentDetail.configure.chatFeatures.description": "Налаштуйте чат-досвід кінцевого користувача у вашому веб-застосунку та чат-поверхнях.",
"agentDetail.configure.chatFeatures.title": "Функції чату",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Напишіть інструкції тут,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} не існує",
"agentDetail.configure.prompt.tip": "Визначте роль агента й опишіть його типове завдання. Використовуйте /, щоб явно посилатися на навички, файли, інструменти та пошук знань.",
"agentDetail.configure.publishBar.draft": "Чернетка",
"agentDetail.configure.publishBar.publishUpdate": "Опублікувати оновлення",
diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.json
index c3ce66f7d06..b2fb8ce15c2 100644
--- a/web/i18n/uk-UA/common.json
+++ b/web/i18n/uk-UA/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Вимкнено",
"modelProvider.selector.discoverMoreInMarketplace": "Знайти більше в Marketplace",
"modelProvider.selector.fromMarketplace": "З Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Приховати несумісні моделі",
"modelProvider.selector.incompatible": "Несумісно",
"modelProvider.selector.incompatibleTip": "Ця модель недоступна в поточній версії. Будь ласка, виберіть іншу доступну модель.",
"modelProvider.selector.install": "Встановити",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Постачальник моделей не налаштований",
"modelProvider.selector.noProviderConfiguredDesc": "Перегляньте Marketplace для встановлення або налаштуйте постачальників у параметрах.",
"modelProvider.selector.onlyCompatibleModelsShown": "Показано лише сумісні моделі",
+ "modelProvider.selector.showIncompatibleModels": "Показати несумісні моделі",
"modelProvider.showModels": "Показати моделі",
"modelProvider.speechToTextModel.key": "Модель перетворення мовлення в текст",
"modelProvider.speechToTextModel.tip": "Встановіть модель за замовчуванням для введення мовлення в текст під час розмови.",
diff --git a/web/i18n/vi-VN/agent-v-2.json b/web/i18n/vi-VN/agent-v-2.json
index baa90f40d70..6b639155d03 100644
--- a/web/i18n/vi-VN/agent-v-2.json
+++ b/web/i18n/vi-VN/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "Xây dựng tác nhân bằng trò chuyện",
"agentDetail.configure.build.inputPlaceholder": "Mô tả tác nhân của bạn nên làm gì",
"agentDetail.configure.build.startBuild": "Bắt đầu build",
- "agentDetail.configure.buildDraft.changes": "{{count}} thay đổi cần áp dụng",
"agentDetail.configure.buildDraft.discard": "Hủy bỏ",
"agentDetail.configure.buildDraft.modeBadge": "Chế độ build",
"agentDetail.configure.buildDraft.modeDescription": "Bạn đang ở chế độ build. Điều chỉnh thiết lập này qua khung chat bên phải, rồi Áp dụng.",
- "agentDetail.configure.buildDraft.noChanges": "Không có thay đổi cần áp dụng",
"agentDetail.configure.buildDraft.title": "Bản nháp build",
"agentDetail.configure.chatFeatures.description": "Định hình trải nghiệm trò chuyện cho người dùng cuối trên Web app và các bề mặt trò chuyện.",
"agentDetail.configure.chatFeatures.title": "Tính năng trò chuyện",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Viết hướng dẫn tại đây,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} không tồn tại",
"agentDetail.configure.prompt.tip": "Xác định vai trò của tác nhân và mô tả nhiệm vụ điển hình của nó. Dùng / để tham chiếu rõ ràng đến Skills, Files, Tools và Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Bản nháp",
"agentDetail.configure.publishBar.publishUpdate": "Xuất bản cập nhật",
diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.json
index 81838ca6844..c3e51a77ecc 100644
--- a/web/i18n/vi-VN/common.json
+++ b/web/i18n/vi-VN/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "Đã tắt",
"modelProvider.selector.discoverMoreInMarketplace": "Khám phá thêm trên Marketplace",
"modelProvider.selector.fromMarketplace": "Từ Marketplace",
+ "modelProvider.selector.hideIncompatibleModels": "Ẩn mô hình không tương thích",
"modelProvider.selector.incompatible": "Không tương thích",
"modelProvider.selector.incompatibleTip": "Mô hình này không khả dụng trong phiên bản hiện tại. Vui lòng chọn mô hình khả dụng khác.",
"modelProvider.selector.install": "Cài đặt",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "Chưa cấu hình nhà cung cấp mô hình",
"modelProvider.selector.noProviderConfiguredDesc": "Duyệt Marketplace để cài đặt hoặc cấu hình nhà cung cấp trong phần cài đặt.",
"modelProvider.selector.onlyCompatibleModelsShown": "Chỉ hiển thị các mô hình tương thích",
+ "modelProvider.selector.showIncompatibleModels": "Hiển thị mô hình không tương thích",
"modelProvider.showModels": "Hiện Mô hình",
"modelProvider.speechToTextModel.key": "Mô hình Chuyển đổi Văn bản thành Tiếng nói",
"modelProvider.speechToTextModel.tip": "Thiết lập mô hình mặc định cho đầu vào chuyển đổi tiếng nói thành văn bản trong cuộc trò chuyện.",
diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.json
index a2416bdcaac..9a3862943d9 100644
--- a/web/i18n/zh-Hans/agent-v-2.json
+++ b/web/i18n/zh-Hans/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "通过对话构建 Agent",
"agentDetail.configure.build.inputPlaceholder": "描述你的 Agent 应该做什么",
"agentDetail.configure.build.startBuild": "开始构建",
- "agentDetail.configure.buildDraft.changes": "{{count}} 项待应用更改",
"agentDetail.configure.buildDraft.discard": "放弃",
"agentDetail.configure.buildDraft.modeBadge": "构建模式",
"agentDetail.configure.buildDraft.modeDescription": "你正在使用构建模式。通过右侧聊天调整此配置,然后应用。",
- "agentDetail.configure.buildDraft.noChanges": "没有待应用的更改",
"agentDetail.configure.buildDraft.title": "Build 草稿",
"agentDetail.configure.chatFeatures.description": "配置 Web app 和聊天界面的终端用户聊天体验。",
"agentDetail.configure.chatFeatures.title": "Chat 功能",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "在此编写指令,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} 不存在",
"agentDetail.configure.prompt.tip": "定义 Agent 的角色,并描述它的典型任务。使用 / 显式引用 Skill、文件、工具和知识检索。",
"agentDetail.configure.publishBar.draft": "草稿",
"agentDetail.configure.publishBar.publishUpdate": "发布更新",
diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.json
index 47f93a80e1d..01225047ae9 100644
--- a/web/i18n/zh-Hans/common.json
+++ b/web/i18n/zh-Hans/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "已禁用",
"modelProvider.selector.discoverMoreInMarketplace": "在 Marketplace 发现更多",
"modelProvider.selector.fromMarketplace": "从 Marketplace 安装",
+ "modelProvider.selector.hideIncompatibleModels": "隐藏不兼容模型",
"modelProvider.selector.incompatible": "不兼容",
"modelProvider.selector.incompatibleTip": "该模型在当前版本中不可用,请选择其他可用模型。",
"modelProvider.selector.install": "安装",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "未配置模型提供商",
"modelProvider.selector.noProviderConfiguredDesc": "前往 Marketplace 安装,或在设置中配置提供商。",
"modelProvider.selector.onlyCompatibleModelsShown": "仅显示兼容的模型",
+ "modelProvider.selector.showIncompatibleModels": "显示不兼容模型",
"modelProvider.showModels": "显示模型",
"modelProvider.speechToTextModel.key": "语音转文本模型",
"modelProvider.speechToTextModel.tip": "设置对话中语音转文字输入的默认使用模型。",
diff --git a/web/i18n/zh-Hant/agent-v-2.json b/web/i18n/zh-Hant/agent-v-2.json
index 8eb424b4041..c32f23f6090 100644
--- a/web/i18n/zh-Hant/agent-v-2.json
+++ b/web/i18n/zh-Hant/agent-v-2.json
@@ -64,11 +64,9 @@
"agentDetail.configure.build.empty.title": "透過對話建置 Agent",
"agentDetail.configure.build.inputPlaceholder": "描述你的 Agent 應該做什麼",
"agentDetail.configure.build.startBuild": "開始構建",
- "agentDetail.configure.buildDraft.changes": "{{count}} 項待套用變更",
"agentDetail.configure.buildDraft.discard": "放棄",
"agentDetail.configure.buildDraft.modeBadge": "建置模式",
"agentDetail.configure.buildDraft.modeDescription": "你正在使用建置模式。透過右側聊天調整此設定,然後套用。",
- "agentDetail.configure.buildDraft.noChanges": "沒有待套用的變更",
"agentDetail.configure.buildDraft.title": "Build 草稿",
"agentDetail.configure.chatFeatures.description": "配置 Web app 和聊天介面的終端使用者聊天體驗。",
"agentDetail.configure.chatFeatures.title": "Chat 功能",
@@ -145,6 +143,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "在此編寫指令,",
+ "agentDetail.configure.prompt.referenceMissing": "{{name}} 不存在",
"agentDetail.configure.prompt.tip": "定義 Agent 的角色,並描述它的典型任務。使用 / 明確引用 Skill、檔案、工具和知識檢索。",
"agentDetail.configure.publishBar.draft": "草稿",
"agentDetail.configure.publishBar.publishUpdate": "發佈更新",
diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.json
index a708dafa564..5502458d43f 100644
--- a/web/i18n/zh-Hant/common.json
+++ b/web/i18n/zh-Hant/common.json
@@ -396,6 +396,7 @@
"modelProvider.selector.disabled": "已停用",
"modelProvider.selector.discoverMoreInMarketplace": "在 Marketplace 探索更多",
"modelProvider.selector.fromMarketplace": "從 Marketplace 安裝",
+ "modelProvider.selector.hideIncompatibleModels": "隱藏不相容模型",
"modelProvider.selector.incompatible": "不相容",
"modelProvider.selector.incompatibleTip": "此模型在目前版本中不可用,請選擇其他可用模型。",
"modelProvider.selector.install": "安裝",
@@ -404,6 +405,7 @@
"modelProvider.selector.noProviderConfigured": "未配置模型供應商",
"modelProvider.selector.noProviderConfiguredDesc": "前往 Marketplace 安裝,或在設定中配置供應商。",
"modelProvider.selector.onlyCompatibleModelsShown": "僅顯示相容的模型",
+ "modelProvider.selector.showIncompatibleModels": "顯示不相容模型",
"modelProvider.showModels": "顯示模型",
"modelProvider.speechToTextModel.key": "語音轉文字模型",
"modelProvider.speechToTextModel.tip": "設定對話中語音轉文字輸入的預設使用模型。",
diff --git a/web/service/base.spec.ts b/web/service/base.spec.ts
index 07180a44606..0b117adbe0e 100644
--- a/web/service/base.spec.ts
+++ b/web/service/base.spec.ts
@@ -1,6 +1,20 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { toast } from '@langgenius/dify-ui/toast'
+import { waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// eslint-disable-next-line no-restricted-imports
-import { del, get, handleStream, patch, post, put } from './base'
+import { del, get, handleStream, patch, post, put, sseGet, ssePost } from './base'
+
+const refreshAccessTokenOrReLoginMock = vi.hoisted(() => vi.fn())
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}))
+
+vi.mock('./refresh-token', () => ({
+ refreshAccessTokenOrReLogin: refreshAccessTokenOrReLoginMock,
+}))
describe('handleStream', () => {
beforeEach(() => {
@@ -9,11 +23,9 @@ describe('handleStream', () => {
describe('Invalid response data handling', () => {
it('should handle null bufferObj from JSON.parse gracefully', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
- // Create a mock response that returns 'data: null'
const mockReader = {
read: vi.fn()
.mockResolvedValueOnce({
@@ -33,13 +45,10 @@ describe('handleStream', () => {
},
} as unknown as Response
- // Act
handleStream(mockResponse, onData, onCompleted)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert
expect(onData).toHaveBeenCalledWith('', true, {
conversationId: undefined,
messageId: '',
@@ -50,11 +59,9 @@ describe('handleStream', () => {
})
it('should handle non-object bufferObj from JSON.parse gracefully', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
- // Create a mock response that returns a primitive value
const mockReader = {
read: vi.fn()
.mockResolvedValueOnce({
@@ -74,13 +81,10 @@ describe('handleStream', () => {
},
} as unknown as Response
- // Act
handleStream(mockResponse, onData, onCompleted)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert
expect(onData).toHaveBeenCalledWith('', true, {
conversationId: undefined,
messageId: '',
@@ -91,7 +95,6 @@ describe('handleStream', () => {
})
it('should handle valid message event correctly', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
@@ -122,13 +125,10 @@ describe('handleStream', () => {
},
} as unknown as Response
- // Act
handleStream(mockResponse, onData, onCompleted)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert
expect(onData).toHaveBeenCalledWith('Hello world', true, {
conversationId: 'conv-123',
taskId: 'task-456',
@@ -138,7 +138,6 @@ describe('handleStream', () => {
})
it('should handle error status 400 correctly', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
@@ -167,13 +166,10 @@ describe('handleStream', () => {
},
} as unknown as Response
- // Act
handleStream(mockResponse, onData, onCompleted)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert
expect(onData).toHaveBeenCalledWith('', false, {
conversationId: undefined,
messageId: '',
@@ -184,7 +180,6 @@ describe('handleStream', () => {
})
it('should handle malformed JSON gracefully', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
@@ -207,19 +202,15 @@ describe('handleStream', () => {
},
} as unknown as Response
- // Act
handleStream(mockResponse, onData, onCompleted)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert - malformed JSON triggers the catch block which calls onData and returns
expect(onData).toHaveBeenCalled()
expect(onCompleted).toHaveBeenCalled()
})
it('should dispatch reasoning_chunk events to onReasoning', async () => {
- // Arrange
const onData = vi.fn()
const onCompleted = vi.fn()
const onReasoning = vi.fn()
@@ -249,10 +240,8 @@ describe('handleStream', () => {
},
} as unknown as Response
- // onReasoning is the last positional handler; fill the unused intervening slots.
const interveningNoops = Array.from({ length: 29 }, () => undefined)
- // Act
;(handleStream as (...args: unknown[]) => void)(
mockResponse,
onData,
@@ -261,27 +250,140 @@ describe('handleStream', () => {
onReasoning,
)
- // Wait for the stream to be processed
await new Promise(resolve => setTimeout(resolve, 50))
- // Assert - the full event object is forwarded to onReasoning, answer stays untouched
expect(onReasoning).toHaveBeenCalledWith(reasoningEvent)
expect(onData).not.toHaveBeenCalled()
})
+ it('should complete with error when the stream reader rejects', async () => {
+ const onData = vi.fn()
+ const onCompleted = vi.fn()
+
+ const mockReader = {
+ read: vi.fn().mockRejectedValueOnce(new Error('stream lost')),
+ }
+
+ const mockResponse = {
+ ok: true,
+ body: {
+ getReader: () => mockReader,
+ },
+ } as unknown as Response
+
+ handleStream(mockResponse, onData, onCompleted)
+
+ await waitFor(() => {
+ expect(onData).toHaveBeenCalledWith('', false, {
+ conversationId: undefined,
+ messageId: '',
+ errorMessage: 'Error: stream lost',
+ errorCode: 'stream_read_error',
+ })
+ })
+ expect(onCompleted).toHaveBeenCalledWith(true, 'Error: stream lost')
+ })
+
it('should throw error when response is not ok', () => {
- // Arrange
const onData = vi.fn()
const mockResponse = {
ok: false,
} as unknown as Response
- // Act & Assert
expect(() => handleStream(mockResponse, onData)).toThrow('Network response was not ok')
})
})
})
+describe('ssePost and sseGet', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ })
+
+ it('should report fetch failures through onError without throwing from the catch handler', async () => {
+ const onError = vi.fn()
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new TypeError('Network failed'))
+
+ await ssePost('/chat-messages', {
+ body: {
+ query: 'hello',
+ },
+ }, {
+ onError,
+ })
+
+ await waitFor(() => {
+ expect(onError).toHaveBeenCalledWith('TypeError: Network failed')
+ })
+ expect(toast.error).toHaveBeenCalledWith('TypeError: Network failed')
+ })
+
+ it('should report token refresh failures through onError', async () => {
+ const onError = vi.fn()
+ refreshAccessTokenOrReLoginMock.mockRejectedValueOnce(new Error('refresh failed'))
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(null, { status: 401 }))
+
+ await ssePost('/chat-messages', {
+ body: {
+ query: 'hello',
+ },
+ }, {
+ onError,
+ })
+
+ await waitFor(() => {
+ expect(onError).toHaveBeenCalledWith('Error: refresh failed')
+ })
+ })
+
+ it('should report event stream token refresh failures through onError', async () => {
+ const onError = vi.fn()
+ refreshAccessTokenOrReLoginMock.mockRejectedValueOnce(new Error('resume refresh failed'))
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(null, { status: 401 }))
+
+ await sseGet('/workflow/workflow-run-1/events', {}, {
+ onError,
+ })
+
+ await waitFor(() => {
+ expect(onError).toHaveBeenCalledWith('Error: resume refresh failed')
+ })
+ })
+
+ it('should report stream reader failures through onError and onCompleted', async () => {
+ const onError = vi.fn()
+ const onCompleted = vi.fn()
+ const mockReader = {
+ read: vi.fn().mockRejectedValueOnce(new Error('stream lost')),
+ }
+ const response = {
+ status: 200,
+ ok: true,
+ body: {
+ getReader: () => mockReader,
+ },
+ } as unknown as Response
+
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response)
+
+ await ssePost('/chat-messages', {
+ body: {
+ query: 'hello',
+ },
+ }, {
+ onError,
+ onCompleted,
+ })
+
+ await waitFor(() => {
+ expect(onError).toHaveBeenCalledWith('Error: stream lost', 'stream_read_error')
+ })
+ expect(onCompleted).toHaveBeenCalledWith(true, 'Error: stream lost')
+ expect(toast.error).toHaveBeenCalledWith('Error: stream lost')
+ })
+})
+
describe('HTTP methods', () => {
it('should export methods correctly', () => {
expect(typeof get).toBe('function')
diff --git a/web/service/base.ts b/web/service/base.ts
index ce3d9a5b458..68f839cab6f 100644
--- a/web/service/base.ts
+++ b/web/service/base.ts
@@ -236,6 +236,16 @@ export const handleStream = (
let buffer = ''
let bufferObj: Record<string, any>
let isFirstMessage = true
+ const completeWithError = (errorMessage: string, errorCode?: string) => {
+ onData('', false, {
+ conversationId: bufferObj?.conversation_id,
+ messageId: bufferObj?.message_id ?? '',
+ errorMessage,
+ errorCode,
+ })
+ onCompleted?.(true, errorMessage)
+ }
+
function read() {
let hasError = false
reader?.read().then((result: ReadableStreamReadResult<Uint8Array>) => {
@@ -399,6 +409,8 @@ export const handleStream = (
}
if (!hasError)
read()
+ }, (e: unknown) => {
+ completeWithError(String(e), 'stream_read_error')
})
}
read()
@@ -553,7 +565,9 @@ export const ssePost = async (
refreshAccessTokenOrReLogin(TIME_OUT).then(() => {
ssePost(url, fetchOptions, otherOptions)
}).catch((err) => {
+ const errorMessage = String(err)
console.error(err)
+ onError?.(errorMessage)
})
}
}
@@ -611,9 +625,10 @@ export const ssePost = async (
)
})
.catch((e) => {
- if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().errorMessage.includes('TypeError: Cannot assign to read only property'))
- toast.error(String(e))
- onError?.(e)
+ const errorMessage = String(e)
+ if (errorMessage !== 'AbortError: The user aborted a request.' && !errorMessage.includes('TypeError: Cannot assign to read only property'))
+ toast.error(errorMessage)
+ onError?.(errorMessage)
})
}
@@ -703,7 +718,9 @@ export const sseGet = async (
refreshAccessTokenOrReLogin(TIME_OUT).then(() => {
sseGet(url, fetchOptions, otherOptions)
}).catch((err) => {
+ const errorMessage = String(err)
console.error(err)
+ onError?.(errorMessage)
})
}
}
@@ -761,9 +778,10 @@ export const sseGet = async (
)
})
.catch((e) => {
- if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().includes('TypeError: Cannot assign to read only property'))
- toast.error(String(e))
- onError?.(e)
+ const errorMessage = String(e)
+ if (errorMessage !== 'AbortError: The user aborted a request.' && !errorMessage.includes('TypeError: Cannot assign to read only property'))
+ toast.error(errorMessage)
+ onError?.(errorMessage)
})
}
diff --git a/web/service/client.spec.ts b/web/service/client.spec.ts
index 2e1464787ec..57aedf9f97c 100644
--- a/web/service/client.spec.ts
+++ b/web/service/client.spec.ts
@@ -1,6 +1,6 @@
import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'
import type { TagResponse as Tag } from '@dify/contracts/api/console/tags/types.gen'
-import type { MutationFunctionContext } from '@tanstack/react-query'
+import type { MutationFunctionContext, QueryFunctionContext } from '@tanstack/react-query'
import type { consoleQuery as ConsoleQuery } from './client'
import { QueryClient } from '@tanstack/react-query'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -23,6 +23,16 @@ const loadConsoleQuery = async () => {
return module.consoleQuery
}
+const loadConsoleQueryWithRequest = async (request: ReturnType<typeof vi.fn>) => {
+ vi.resetModules()
+ vi.doMock('@/utils/client', () => ({ isClient: true, isServer: false }))
+ vi.doMock('./base', () => ({ request }))
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const module = await import('./client')
+ warnSpy.mockRestore()
+ return module.consoleQuery
+}
+
const createMutationContext = (queryClient: QueryClient): MutationFunctionContext => ({
client: queryClient,
meta: undefined,
@@ -52,6 +62,8 @@ type WorkflowAgentComposerMutationResponse = Parameters<NonNullable<ReturnType<t
const createAgent = (overrides: Partial<AgentMutationResponse> = {}): AgentMutationResponse => ({
...overrides,
active_config_is_published: overrides.active_config_is_published ?? false,
+ debug_conversation_has_messages: overrides.debug_conversation_has_messages ?? false,
+ debug_conversation_message_count: overrides.debug_conversation_message_count ?? 0,
enable_api: overrides.enable_api ?? true,
enable_site: overrides.enable_site ?? true,
description: overrides.description ?? 'Agent description',
@@ -78,6 +90,7 @@ const createComposerState = (overrides: Partial<AgentComposerMutationResponse> =
status: 'active',
},
agent_soul: {
+ config_note: '',
schema_version: 1,
},
hidden_app_backed: false,
@@ -107,8 +120,11 @@ const createWorkflowComposerState = (overrides: Partial<WorkflowAgentComposerMut
status: 'active',
},
agent_soul: {
+ config_note: '',
schema_version: 1,
},
+ debug_conversation_has_messages: overrides.debug_conversation_has_messages ?? false,
+ debug_conversation_message_count: overrides.debug_conversation_message_count ?? 0,
hidden_app_backed: false,
binding: {
agent_id: 'agent-1',
@@ -201,6 +217,46 @@ describe('getBaseURL', () => {
})
})
+// Scenario: oRPC operation context controls transport behavior without handwritten REST helpers.
+describe('consoleQuery transport context', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('should forward silent context to the base request transport', async () => {
+ const request = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), {
+ status: 200,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }))
+ const consoleQuery = await loadConsoleQueryWithRequest(request)
+ const queryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ context: {
+ silent: true,
+ },
+ })
+
+ await Promise
+ .resolve(queryOptions.queryFn({ signal: new AbortController().signal } as QueryFunctionContext))
+ .catch(() => undefined)
+
+ expect(request).toHaveBeenCalledWith(
+ expect.stringContaining('/agent/agent-1/build-draft'),
+ expect.any(Object),
+ expect.objectContaining({
+ fetchCompat: true,
+ silent: true,
+ }),
+ )
+ })
+})
+
// Scenario: oRPC mutation defaults own shared Agent roster cache behavior.
describe('consoleQuery agent mutation defaults', () => {
beforeEach(() => {
@@ -519,7 +575,7 @@ describe('consoleQuery agent mutation defaults', () => {
expect(queryClient.getQueryData(inviteOptionsQueryKey)).toBeUndefined()
})
- it('should keep roster and invite option lists stable after saving an agent draft', async () => {
+ it('should invalidate roster list but keep invite options stable after saving an agent draft', async () => {
const consoleQuery = await loadConsoleQuery()
const queryClient = new QueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
@@ -543,7 +599,7 @@ describe('consoleQuery agent mutation defaults', () => {
createMutationContext(queryClient),
)
- expect(invalidateQueries).not.toHaveBeenCalledWith({
+ expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: consoleQuery.agent.get.key(),
})
expect(invalidateQueries).not.toHaveBeenCalledWith({
diff --git a/web/service/client.ts b/web/service/client.ts
index 7e31b817364..eb9d9bbffc8 100644
--- a/web/service/client.ts
+++ b/web/service/client.ts
@@ -9,7 +9,7 @@ import type {
import type { ClientLink } from '@orpc/client'
import type { AnyContractRouter, ContractRouterClient } from '@orpc/contract'
import type { JsonifiedClient } from '@orpc/openapi-client'
-import type { RouterUtils } from '@orpc/tanstack-query'
+import type { RouterUtils, TanstackQueryOperationContext } from '@orpc/tanstack-query'
import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import type { consoleRouterContract } from '@/contract/router'
import { createORPCClient, onError } from '@orpc/client'
@@ -58,19 +58,23 @@ export function getBaseURL(path: string) {
return url
}
-type ConsoleClientContext = Record<never, never>
+export type ConsoleClientContext = TanstackQueryOperationContext & {
+ silent?: boolean
+}
+
type ConsoleClientLink = ClientLink<ConsoleClientContext>
function createConsoleOpenAPILink(contract: AnyContractRouter): ConsoleClientLink {
return new OpenAPILink<ConsoleClientContext>(contract, {
url: getBaseURL(API_PREFIX),
- fetch: (input, init) => {
+ fetch: (input, init, options) => {
return request(
input.url,
init,
{
fetchCompat: true,
request: input,
+ silent: options.context.silent,
},
)
},
@@ -118,7 +122,7 @@ type AppDeployInvalidationOptions = {
developerApiSettings?: boolean
}
-type ConsoleQueryUtils = RouterUtils<JsonifiedClient<ContractRouterClient<typeof consoleRouterContract>>>
+type ConsoleQueryUtils = RouterUtils<JsonifiedClient<ContractRouterClient<typeof consoleRouterContract, ConsoleClientContext>>>
function isTagType(type: string | null | undefined): type is TagType {
return type === 'app' || type === 'knowledge' || type === 'snippet'
@@ -353,7 +357,7 @@ async function invalidateReleaseMutationQueries(
const consoleLink = createConsoleDynamicLink<ConsoleClientContext>(createConsoleOpenAPILink)
-export const consoleClient: JsonifiedClient<ContractRouterClient<typeof consoleRouterContract>> = createORPCClient(consoleLink)
+export const consoleClient: JsonifiedClient<ContractRouterClient<typeof consoleRouterContract, ConsoleClientContext>> = createORPCClient(consoleLink)
export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQueryUtils(consoleClient, {
path: ['console'],
@@ -531,12 +535,12 @@ export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQue
put: {
mutationOptions: {
onSuccess: (_composerState, variables, _onMutateResult, context) => {
- if (variables.body.save_strategy !== 'save_as_new_version')
- return
-
context.client.invalidateQueries({
queryKey: consoleQuery.agent.get.key(),
})
+ if (variables.body.save_strategy !== 'save_as_new_version')
+ return
+
context.client.invalidateQueries({
queryKey: consoleQuery.agent.inviteOptions.get.key(),
})
diff --git a/web/service/console-link.ts b/web/service/console-link.ts
index e6423fa149a..34f9419b379 100644
--- a/web/service/console-link.ts
+++ b/web/service/console-link.ts
@@ -1,11 +1,8 @@
import type { ClientContext, ClientLink } from '@orpc/client'
import type { AnyContractRouter } from '@orpc/contract'
-import type { consoleRouterContract } from '@/contract/router'
import { DynamicLink } from '@orpc/client'
import { loadConsoleContractForSegment } from './console-router-loader'
-export type ConsoleRouterContract = typeof consoleRouterContract
-
export function createConsoleDynamicLink<TContext extends ClientContext>(
createLink: (contract: AnyContractRouter) => ClientLink<TContext>,
) {