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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(agent): simplify Agent v2 output contract (#41062)
盐粒 Yanli35a4533889fb
diff --git a/api/core/workflow/nodes/agent_v2/agent_node.py b/api/core/workflow/nodes/agent_v2/agent_node.pyindex 73288b4bcc6..c822e5d3ab1 100644--- a/api/core/workflow/nodes/agent_v2/agent_node.py+++ b/api/core/workflow/nodes/agent_v2/agent_node.py@@ -225,13 +225,9 @@ class DifyAgentNode(Node[DifyAgentNodeData]):agent_config_snapshot_id=bundle.snapshot.id,)- # Stage 4 §4.1 (D-3): use effective outputs so defaults flow through both- # the backend request and the post-run type check.node_job = WorkflowNodeJobConfig.model_validate(bundle.binding.node_job_config_dict)- effective_outputs = list(- WorkflowAgentRuntimeRequestBuilder.effective_declared_outputs(list(node_job.declared_outputs))- )- outputs_by_name = {o.name: o for o in effective_outputs}+ custom_outputs = list(node_job.declared_outputs)+ outputs_by_name = {output.name: output for output in custom_outputs}# ──── ENG-638: resume after a submitted/timed-out ask_human form ────# graphon re-executes this _run when the outer workflow resumes. If a@@ -445,68 +441,60 @@ class DifyAgentNode(Node[DifyAgentNodeData]):metadata=metadata,)- # ──── Stage 4: per-output type check ────- type_check = self._type_checker.check(- declared_outputs=effective_outputs,- raw_output=terminal_event.output,- tenant_id=dify_ctx.tenant_id,- )- self._record_type_check_metadata(metadata, type_check)-- if not type_check.has_failures:- yield StreamCompletedEvent(- node_run_result=self._output_adapter.build_success_result(- event=terminal_event,- inputs=inputs,- process_data=process_data,- metadata=metadata,- declared_outputs=effective_outputs,- )+ success_event = terminal_event+ if custom_outputs:+ # ──── Stage 4: per-output type check ────+ type_check = self._type_checker.check(+ declared_outputs=custom_outputs,+ raw_output=terminal_event.output,+ tenant_id=dify_ctx.tenant_id,)- return+ self._record_type_check_metadata(metadata, type_check)++ if type_check.has_failures:+ # ──── Stage 4: orchestrate retry / default / fail ────+ failures = [+ FailedOutput(+ declared=outputs_by_name[result.name],+ failure_kind=OutputFailureKind.TYPE_CHECK,+ reason=result.reason,+ )+ for result in type_check.failures+ if result.name in outputs_by_name+ ]+ outcome = self._failure_orchestrator.decide(failures=failures, current_attempt=attempt)+ metadata["output_failure_decision"] = outcome.decision.value+ metadata["output_failure_reason"] = outcome.primary_reason++ if outcome.decision == OutputFailureDecision.RETRY:+ attempt = outcome.next_attempt+ continue- # ──── Stage 4: orchestrate retry / default / fail ────- failures = [- FailedOutput(- declared=outputs_by_name[result.name],- failure_kind=OutputFailureKind.TYPE_CHECK,- reason=result.reason,- )- for result in type_check.failures- if result.name in outputs_by_name- ]- outcome = self._failure_orchestrator.decide(failures=failures, current_attempt=attempt)- metadata["output_failure_decision"] = outcome.decision.value- metadata["output_failure_reason"] = outcome.primary_reason-- if outcome.decision == OutputFailureDecision.RETRY:- attempt = outcome.next_attempt- continue-- if outcome.decision == OutputFailureDecision.USE_DEFAULT:- patched_event = self._patch_event_with_defaults(terminal_event, outcome.per_output_actions)- yield StreamCompletedEvent(- node_run_result=self._output_adapter.build_success_result(- event=patched_event,- inputs=inputs,- process_data=process_data,- metadata=metadata,- declared_outputs=effective_outputs,- )+ if outcome.decision == OutputFailureDecision.USE_DEFAULT:+ success_event = self._patch_event_with_defaults(terminal_event, outcome.per_output_actions)+ else:+ error_type = (+ "output_type_check_failed_fail_branch"+ if outcome.decision == OutputFailureDecision.TAKE_FAIL_BRANCH+ else "output_type_check_failed"+ )+ yield self._failure_event(+ inputs=inputs,+ process_data=process_data,+ metadata=metadata,+ error=outcome.primary_reason,+ error_type=error_type,+ )+ return++ yield StreamCompletedEvent(+ node_run_result=self._output_adapter.build_success_result(+ event=success_event,+ inputs=inputs,+ process_data=process_data,+ metadata=metadata,+ declared_outputs=custom_outputs,)- return-- error_type = (- "output_type_check_failed_fail_branch"- if outcome.decision == OutputFailureDecision.TAKE_FAIL_BRANCH- else "output_type_check_failed"- )- yield self._failure_event(- inputs=inputs,- process_data=process_data,- metadata=metadata,- error=outcome.primary_reason,- error_type=error_type,)returndiff --git a/api/core/workflow/nodes/agent_v2/output_adapter.py b/api/core/workflow/nodes/agent_v2/output_adapter.pyindex 96d8dbf50b1..a4c6e3d3fac 100644--- a/api/core/workflow/nodes/agent_v2/output_adapter.py+++ b/api/core/workflow/nodes/agent_v2/output_adapter.py@@ -29,14 +29,14 @@ class ToolFileRebacker(Protocol):class WorkflowAgentOutputAdapter:"""Convert terminal Agent backend events into workflow node run results.- ``DifyAgentNode`` relies on this after the earlier per-output type-check pass:- once the backend payload has been validated against declared ``FILE`` or- ``ARRAY[FILE]`` outputs, this adapter can safely convert canonical file- mappings into ``FileSegment`` values without reintroducing false positives- for normal object outputs. Older Agent backend builds may still return bare- ToolFile ids (``{"id": "..."}``); when a ``ToolFileRebacker`` is provided,- those ids are treated as a backwards-compatible fallback and hydrated from- the server-side ToolFile row instead of trusted from the sandbox payload.+ Structured runs provide custom declarations so their declared ``FILE`` and+ ``ARRAY[FILE]`` fields can be converted into workflow file values without+ treating normal object fields as files. Plain runs provide a free-form+ string, which is mapped directly to the system ``text`` output. Older Agent+ backend builds may still return bare ToolFile ids (``{"id": "..."}``); when+ a ``ToolFileRebacker`` is provided, those ids are treated as a+ backwards-compatible fallback and hydrated from the server-side ToolFile+ row instead of trusted from the sandbox payload."""_tool_file_rebacker: ToolFileRebacker | None@@ -56,9 +56,10 @@ class WorkflowAgentOutputAdapter:) -> NodeRunResult:"""Build the successful node result from one backend terminal event.- ``declared_outputs`` is optional for generic normalization, but callers- should pass it from the earlier type-checking stage so canonical file- mappings are normalized on the correct declared fields only.+ For structured runs, ``declared_outputs`` contains the custom-only+ declarations used to scope field and file normalization. Plain runs+ omit custom declarations, and a free-form string is mapped to the+ system ``text`` output.Canonical persisted-file mappings (``local_file`` / ``tool_file`` /``datasource_file``) also require ``metadata["tenant_id"]`` so thediff --git a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py b/api/core/workflow/nodes/agent_v2/runtime_request_builder.pyindex a9390d005e0..9b9c6b48d5f 100644--- a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py+++ b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py@@ -66,9 +66,6 @@ from models.agent_config_entities import (WorkflowNodeJobConfig,WorkflowPreviousNodeOutputRef,)-from models.agent_config_entities import (- effective_declared_outputs as _effective_declared_outputs,-)from models.provider_ids import ModelProviderIDfrom services.agent.prompt_mentions import (MentionKind,@@ -513,15 +510,15 @@ class WorkflowAgentRuntimeRequestBuilder:def _build_output_config(declared_outputs: Sequence[DeclaredOutputConfig]) -> AgentBackendOutputConfig | None:"""Build the structured-output layer config sent to Agent backend.- Stage 4 §4.1 (D-3): when the user hasn't declared any outputs, inject the- PRD-mandated defaults (text / files / json) at runtime so the backend- always receives a stable schema and the downstream Inspector + nodes- have consistent output names. The defaults are NOT persisted.+ Plain-output jobs omit this layer. Structured jobs prepend the optional,+ system-owned ``text`` field to the persisted custom declarations."""- effective_outputs = WorkflowAgentRuntimeRequestBuilder.effective_declared_outputs(declared_outputs)- properties: dict[str, Any] = {}+ if not declared_outputs:+ return None++ properties: dict[str, Any] = {"text": {"type": "string"}}required: list[str] = []- for output in effective_outputs:+ for output in declared_outputs:properties[output.name] = WorkflowAgentRuntimeRequestBuilder._schema_for_declared_output(output)if output.required:required.append(output.name)@@ -530,20 +527,9 @@ class WorkflowAgentRuntimeRequestBuilder:schema["required"] = requiredreturn AgentBackendOutputConfig(json_schema=schema,- description=WorkflowAgentRuntimeRequestBuilder._build_output_description(effective_outputs),+ description=WorkflowAgentRuntimeRequestBuilder._build_output_description(declared_outputs),)- @staticmethod- def effective_declared_outputs(- declared_outputs: Sequence[DeclaredOutputConfig],- ) -> Sequence[DeclaredOutputConfig]:- """Alias for :func:`models.agent_config_entities.effective_declared_outputs`.-- Kept as a static method on the builder so existing call sites- (``agent_node._run``, tests) don't need to change their import.- """- return _effective_declared_outputs(list(declared_outputs))-@staticmethoddef _schema_for_declared_output(output: DeclaredOutputConfig) -> dict[str, Any]:schema = WorkflowAgentRuntimeRequestBuilder._schema_for_type(diff --git a/api/migrations/versions/2026_08_21_1422-925e75620b69_simplify_agent_v2_output_contract.py b/api/migrations/versions/2026_08_21_1422-925e75620b69_simplify_agent_v2_output_contract.pynew file mode 100644index 00000000000..959b19112b0--- /dev/null+++ b/api/migrations/versions/2026_08_21_1422-925e75620b69_simplify_agent_v2_output_contract.py@@ -0,0 +1,70 @@+"""simplify agent v2 output contract++Revision ID: 925e75620b69+Revises: fbdfcf5f5a6e+Create Date: 2026-08-21 14:22:52.730081++"""++import json++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision = "925e75620b69"+down_revision = "fbdfcf5f5a6e"+branch_labels = None+depends_on = None++_LEGACY_PRESET_OUTPUT_NAMES = frozenset({"text", "files", "json"})+++def _remove_legacy_preset_declared_outputs(value: object) -> bool:+ if not isinstance(value, dict):+ return False+ declared_outputs = value.get("declared_outputs")+ if not isinstance(declared_outputs, list):+ return False++ retained_outputs = [+ output+ for output in declared_outputs+ if not (isinstance(output, dict) and output.get("name") in _LEGACY_PRESET_OUTPUT_NAMES)+ ]+ if len(retained_outputs) == len(declared_outputs):+ return False+ value["declared_outputs"] = retained_outputs+ return True+++def _rewrite_node_job_configs() -> None:+ if op.get_context().as_sql:+ return++ connection = op.get_bind()+ rows = connection.execute(sa.text("SELECT id, node_job_config FROM workflow_agent_node_bindings"))+ for binding_id, raw_value in rows:+ if raw_value is None:+ continue+ value = json.loads(raw_value)+ if not _remove_legacy_preset_declared_outputs(value):+ continue+ connection.execute(+ sa.text("UPDATE workflow_agent_node_bindings SET node_job_config = :value WHERE id = :binding_id"),+ {+ "binding_id": binding_id,+ "value": json.dumps(value, ensure_ascii=False, separators=(",", ":")),+ },+ )+++def upgrade() -> None:+ _rewrite_node_job_configs()+++def downgrade() -> None:+ # ``text`` is now a derived system output, while ``files`` and ``json`` are+ # retired presets. Their removed declarations cannot be reconstructed+ # precisely after cleanup, so this data migration is one-way.+ passdiff --git a/api/models/agent_config_entities.py b/api/models/agent_config_entities.pyindex a81e51d62a5..7accbea4b3c 100644--- a/api/models/agent_config_entities.py+++ b/api/models/agent_config_entities.py@@ -4,9 +4,19 @@ import refrom enum import StrEnumfrom typing import Annotated, Any, Final, Literal, Self-from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, field_validator, model_validator+from pydantic import (+ BaseModel,+ ConfigDict,+ Field,+ WithJsonSchema,+ field_validator,+ model_validator,+)-from core.rag.entities.metadata_entities import ConditionValue, SupportedComparisonOperator+from core.rag.entities.metadata_entities import (+ ConditionValue,+ SupportedComparisonOperator,+)from core.tools.entities.tool_entities import ToolProviderTypefrom core.workflow.file_reference import is_canonical_file_referencefrom graphon.file import FileTransferMethod, FileType@@ -1050,45 +1060,26 @@ class DeclaredOutputConfig(BaseModel):)-# PRD §OUTPUT 配置框 0522 共识: "Output 如果没有配置,则 text, files, json"-# The runtime injects these when ``declared_outputs`` is empty (stage 4 §4.1, D-3).-# Not persisted; mutating this constant changes UI defaults globally.-DEFAULT_DECLARED_OUTPUTS: Final[tuple[DeclaredOutputConfig, ...]] = (+# ``text`` is a system-owned workflow output. It is derived for consumers and+# never persisted in ``WorkflowNodeJobConfig.declared_outputs``.+SYSTEM_DECLARED_OUTPUTS: Final[tuple[DeclaredOutputConfig, ...]] = (DeclaredOutputConfig(name="text",type=DeclaredOutputType.STRING,required=False,description="Free-form text answer.",),- DeclaredOutputConfig(- name="files",- type=DeclaredOutputType.ARRAY,- required=False,- description="Files produced by the agent.",- array_item=DeclaredArrayItem(type=DeclaredOutputType.FILE),- ),- DeclaredOutputConfig(- name="json",- type=DeclaredOutputType.OBJECT,- required=False,- description="Free-form JSON object.",- ),)+# ``switch`` and ``_session`` are reserved for future system output contracts.+RESERVED_DECLARED_OUTPUT_NAMES: Final[frozenset[str]] = frozenset({"text", "switch", "_session"})def effective_declared_outputs(declared_outputs: list[DeclaredOutputConfig] | tuple[DeclaredOutputConfig, ...],) -> tuple[DeclaredOutputConfig, ...]:- """Return the outputs the runtime actually presents.+ """Project the system ``text`` output followed by custom declarations."""- Returns ``declared_outputs`` unchanged when non-empty, otherwise the PRD- defaults from ``DEFAULT_DECLARED_OUTPUTS``. Shared helper so Composer load- responses, runtime request builder, and the Node Output Inspector all use- the same fallback (stage 4 §4.1, decision D-3).- """- if declared_outputs:- return tuple(declared_outputs)- return DEFAULT_DECLARED_OUTPUTS+ return SYSTEM_DECLARED_OUTPUTS + tuple(declared_outputs)class WorkflowNodeJobConfig(BaseModel):@@ -1101,3 +1092,13 @@ class WorkflowNodeJobConfig(BaseModel):declared_outputs: list[DeclaredOutputConfig] = Field(default_factory=list)human_contacts: list[AgentHumanContactConfig] = Field(default_factory=list)metadata: WorkflowNodeJobMetadata = Field(default_factory=WorkflowNodeJobMetadata)++ @field_validator("declared_outputs")+ @classmethod+ def _reject_reserved_declared_output_names(+ cls, declared_outputs: list[DeclaredOutputConfig]+ ) -> list[DeclaredOutputConfig]:+ for output in declared_outputs:+ if output.name in RESERVED_DECLARED_OUTPUT_NAMES:+ raise ValueError(f"declared output name {output.name!r} is reserved")+ return declared_outputsdiff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.pyindex 5ca7d670ad6..813c6495cf2 100644--- a/api/services/agent/composer_service.py+++ b/api/services/agent/composer_service.py@@ -2145,23 +2145,18 @@ class AgentComposerService:@staticmethoddef _declared_outputs_from_binding(binding: WorkflowAgentNodeBinding) -> list[DeclaredOutputConfig]:- """Re-hydrate the binding's node_job_config into typed declared outputs.+ """Re-hydrate the binding's custom-only persisted output declarations.node_job_config is stored as JSON / LongText; the typed view is needed- so the effective_declared_outputs helper can fall back to defaults on- an empty list without callers re-implementing the fallback.+ before the later effective-output projection prepends the system+ ``text`` output."""node_job = WorkflowNodeJobConfig.model_validate(binding.node_job_config_dict)return list(node_job.declared_outputs)@staticmethoddef _serialize_effective_outputs(declared_outputs: list[DeclaredOutputConfig]) -> list[dict[str, Any]]:- """JSON-serialize the effective declared outputs (PRD defaults if empty).-- Stage 4 decision D-3 keeps defaults out of the DB; this helper is the- single place that injects them into the Composer load response so the- wire shape stays consistent whether the user has declared anything yet.- """+ """JSON-serialize system ``text`` followed by custom declarations."""return [output.model_dump(mode="json") for output in _effective_declared_outputs(declared_outputs)]@classmethod@@ -2174,8 +2169,7 @@ class AgentComposerService:"soul_lock": {"locked": False, "can_unlock": False, "reason": "workflow_only_empty"},"agent_soul": AgentSoulConfig().model_dump(mode="json"),"node_job": WorkflowNodeJobConfig().model_dump(mode="json"),- # Stage 4 §4.1 / §10.1 (D-3): empty composer state still surfaces the- # PRD defaults so the front-end has stable output names to render.+ # ``text`` is derived for the editor and is not stored in node_job."effective_declared_outputs": cls._serialize_effective_outputs([]),"save_options": [ComposerSaveStrategy.NODE_JOB_ONLY.value, ComposerSaveStrategy.SAVE_TO_ROSTER.value],"impact_summary": None,@@ -2241,10 +2235,7 @@ class AgentComposerService:if versionelse AgentSoulConfig().model_dump(mode="json"),"node_job": binding.node_job_config_dict,- # Stage 4 §4.1 / §10.1 (D-3): when the saved node_job carries no- # declared_outputs, surface the PRD defaults so the front-end can- # render them as read-only chips. When user-defined outputs exist- # this is the same list (so callers don't need to special-case).+ # Surface system ``text`` followed by the binding's custom outputs."effective_declared_outputs": cls._serialize_effective_outputs(cls._declared_outputs_from_binding(binding)),"save_options": save_options,"impact_summary": cls.calculate_impact(diff --git a/api/services/agent/prompt_mentions.py b/api/services/agent/prompt_mentions.pyindex 3be3a53666e..0cffad70ee1 100644--- a/api/services/agent/prompt_mentions.py+++ b/api/services/agent/prompt_mentions.py@@ -37,6 +37,7 @@ from models.agent_config_entities import (DeclaredOutputType,WorkflowNodeJobConfig,WorkflowPreviousNodeOutputRef,+ effective_declared_outputs,)@@ -300,7 +301,7 @@ def build_node_job_mention_resolver(node_job: WorkflowNodeJobConfig) -> MentionRif selector and f"{selector[0]}.{selector[1]}" == mention.ref_id:return ref.name or mention.label or mention.ref_idcase MentionKind.OUTPUT:- for output in node_job.declared_outputs:+ for output in effective_declared_outputs(node_job.declared_outputs):if output.name == mention.ref_id:return _format_output_mention(output)case MentionKind.HUMAN:diff --git a/api/services/agent/workflow_publish_service.py b/api/services/agent/workflow_publish_service.pyindex 117d8f12ef0..50b2d1dc5bf 100644--- a/api/services/agent/workflow_publish_service.py+++ b/api/services/agent/workflow_publish_service.py@@ -20,7 +20,6 @@ from models.agent import ()from models.agent_config_entities import (AgentSoulConfig,- DeclaredOutputConfig,WorkflowNodeJobConfig,WorkflowPreviousNodeOutputRef,)@@ -554,9 +553,12 @@ class WorkflowAgentPublishService:if not isinstance(declared_outputs_payload, list):raise ValueError("Workflow Agent node agent_declared_outputs must be a list.")try:- node_job.declared_outputs = [- DeclaredOutputConfig.model_validate(output) for output in declared_outputs_payload- ]+ node_job = WorkflowNodeJobConfig.model_validate(+ {+ **node_job.model_dump(mode="python"),+ "declared_outputs": declared_outputs_payload,+ }+ )except ValidationError as exc:raise ValueError("Workflow Agent node has invalid agent_declared_outputs.") from excdiff --git a/api/services/workflow/node_output_inspector_service.py b/api/services/workflow/node_output_inspector_service.pyindex dee806c9464..f96223a6a6c 100644--- a/api/services/workflow/node_output_inspector_service.py+++ b/api/services/workflow/node_output_inspector_service.py@@ -26,8 +26,8 @@ Design constraints baked into this version:Cross-tenant / cross-app rows still 404 via the standard tenant/app scope.3. **Declared outputs by node kind**:* Agent v2 nodes resolve their declared list via- :class:`WorkflowAgentBindingResolver` (the binding owns the canonical- ``DeclaredOutputConfig`` list and falls back to PRD defaults when empty).+ :class:`WorkflowAgentBindingResolver` (the binding owns custom declarations;+ the system ``text`` output is derived for display).* Other node kinds don't have a declared-output schema yet; we surface thekeys present in the execution payload as a best-effort list typed``unknown`` so the panel can still render them.@@ -60,14 +60,11 @@ from core.workflow.nodes.agent_v2.binding_resolver import (WorkflowAgentBindingResolver,)from core.workflow.nodes.agent_v2.discriminator import is_dify_agent_node_data-from core.workflow.nodes.agent_v2.runtime_request_builder import (- WorkflowAgentRuntimeRequestBuilder,-)from factories.file_factory.builders import build_from_mappingfrom graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatusfrom graphon.file import helpers as file_helpersfrom models import App-from models.agent_config_entities import DeclaredOutputConfig, DeclaredOutputType+from models.agent_config_entities import DeclaredOutputConfig, DeclaredOutputType, effective_declared_outputsfrom models.workflow import WorkflowNodeExecutionModel, WorkflowRunlogger = logging.getLogger(__name__)@@ -783,7 +780,7 @@ class NodeOutputInspectorService:"NodeOutputInspector: malformed node_job_config for binding %s", bundle.binding.id, exc_info=True)return None- return list(WorkflowAgentRuntimeRequestBuilder.effective_declared_outputs(list(node_job.declared_outputs)))+ return list(effective_declared_outputs(node_job.declared_outputs))@staticmethoddef _infer_outputs_from_payload(*, execution: WorkflowNodeExecutionModel | None) -> list[_ResolvedDeclaration]:diff --git a/api/tests/integration_tests/services/test_node_output_inspector_service.py b/api/tests/integration_tests/services/test_node_output_inspector_service.pyindex 889ee56dfc4..318d3abae98 100644--- a/api/tests/integration_tests/services/test_node_output_inspector_service.py+++ b/api/tests/integration_tests/services/test_node_output_inspector_service.py@@ -159,13 +159,6 @@ def seeded_run(node_id="agent-node-1",node_type="agent",outputs={"text": "hello world"},- execution_metadata={- "output_type_check": {- "passed": True,- "results": [{"name": "text", "type": "string", "status": "ready"}],- },- "attempt": 0,- },index=1,)tool_execution = _make_execution(@@ -263,7 +256,7 @@ def test_snapshot_returns_agent_v2_declared_outputs_with_status_ready(seeded_run"""Happy path: agent v2 node + tool node both render, statuses come fromreal ``WorkflowRun`` + ``WorkflowNodeExecutionModel`` rows."""app_model, workflow_run, _ = seeded_run- service = NodeOutputInspectorService(binding_resolver=_stub_resolver([{"name": "text", "type": "string"}]))+ service = NodeOutputInspectorService(binding_resolver=_stub_resolver([]))snapshot = _snapshot_workflow_run(service,app_model=app_model,@@ -440,7 +433,7 @@ def test_snapshot_surfaces_output_check_failure_from_metadata(flask_req_ctx, fakdef test_node_detail_serves_one_node(seeded_run):app_model, workflow_run, _ = seeded_run- service = NodeOutputInspectorService(binding_resolver=_stub_resolver([{"name": "text", "type": "string"}]))+ service = NodeOutputInspectorService(binding_resolver=_stub_resolver([]))view = _node_detail(service,app_model=app_model,@@ -464,10 +457,10 @@ def test_output_preview_for_file_renders_signed_url(seeded_run, fake_app_model):select(WorkflowNodeExecutionModel).where(WorkflowNodeExecutionModel.id == agent_execution.id))assert row is not None- row.outputs = json.dumps({"text": {"file_id": "550e8400-e29b-41d4-a716-446655440000", "filename": "x.pdf"}})+ row.outputs = json.dumps({"report": {"file_id": "550e8400-e29b-41d4-a716-446655440000", "filename": "x.pdf"}})session.commit()- service = NodeOutputInspectorService(binding_resolver=_stub_resolver([{"name": "text", "type": "file"}]))+ service = NodeOutputInspectorService(binding_resolver=_stub_resolver([{"name": "report", "type": "file"}]))with patch("services.workflow.node_output_inspector_service.file_helpers.get_signed_file_url",return_value="https://signed.example/x.pdf",@@ -477,9 +470,9 @@ def test_output_preview_for_file_renders_signed_url(seeded_run, fake_app_model):app_model=fake_app_model,workflow_run_id=workflow_run.id,node_id="agent-node-1",- output_name="text",+ output_name="report",)- assert preview.output_name == "text"+ assert preview.output_name == "report"assert isinstance(preview.value, dict)assert preview.value["preview_url"] == "https://signed.example/x.pdf"assert preview.value["filename"] == "x.pdf"@@ -524,7 +517,7 @@ def test_keeps_latest_execution_per_node_by_index(flask_req_ctx, fake_app_model)run_id, ex_ids = workflow_run.id, [older.id, newer.id]try:- service = NodeOutputInspectorService(binding_resolver=_stub_resolver([{"name": "text", "type": "string"}]))+ service = NodeOutputInspectorService(binding_resolver=_stub_resolver([]))snapshot = _snapshot_workflow_run(service, app_model=fake_app_model, workflow_run_id=run_id)assert snapshot.node_outputs[0].outputs[0].value_preview == "second attempt"finally:diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.pyindex a8c254ae604..4847e6af397 100644--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py@@ -9,6 +9,7 @@ import pytestfrom agenton.compositor import CompositorSessionSnapshotfrom dify_agent.layers.ask_human import AskHumanToolResultfrom dify_agent.protocol import (+ DIFY_AGENT_OUTPUT_LAYER_ID,CancelRunRequest,CancelRunResponse,PydanticAIStreamRunEvent,@@ -136,7 +137,7 @@ class FakeBindingResolver(WorkflowAgentBindingResolver):{"workflow_prompt": "Use the previous output.","previous_node_output_refs": [{"node_id": "previous-node", "output": "text"}],- "declared_outputs": [{"name": "text", "type": "string"}],+ "declared_outputs": [],}),)@@ -255,6 +256,24 @@ class FileOutputBackendClient(FakeAgentBackendRunClient):)+class PlainTextOutputBackendClient(FakeAgentBackendRunClient):+ def _events(self, run_id: str):+ from clients.agent_backend.fake_client import _FIXED_TIME++ return (+ RunStartedEvent(id="1-0", run_id=run_id, created_at=_FIXED_TIME),+ RunSucceededEvent(+ id="2-0",+ run_id=run_id,+ created_at=_FIXED_TIME,+ data=RunSucceededEventData(+ output="hello agent",+ session_snapshot=CompositorSessionSnapshot(layers=[]),+ ),+ ),+ )++class AgentMessageDeltaBackendClient(FakeAgentBackendRunClient):def _events(self, run_id: str):created_at = datetime(2026, 1, 1, tzinfo=UTC)@@ -462,7 +481,7 @@ def test_extract_variable_selector_to_variable_mapping_uses_frontend_agent_task_def test_agent_node_run_maps_successful_agent_backend_run_to_node_result():- events = list(_node()._run())+ events = list(_node(agent_backend_client=PlainTextOutputBackendClient())._run())assert len(events) == 1result = cast(StreamCompletedEvent, events[0]).node_run_result@@ -474,6 +493,50 @@ def test_agent_node_run_maps_successful_agent_backend_run_to_node_result():assert result.process_data["agent_id"] == "agent-1"layers = {layer["name"]: layer for layer in result.inputs["agent_backend_request"]["composition"]["layers"]}assert "credentials" not in layers["llm"]["config"]+ assert DIFY_AGENT_OUTPUT_LAYER_ID not in layers+ assert "output_type_check" not in agent_log+++def test_agent_node_structured_success_preserves_text_and_checks_only_custom_outputs():+ events = list(+ _node(+ declared_outputs=[{"name": "summary", "type": DeclaredOutputType.STRING}],+ agent_backend_client=FileOutputBackendClient(+ output_payload={"text": "hello agent", "summary": "Short summary"}+ ),+ )._run()+ )++ result = cast(StreamCompletedEvent, events[0]).node_run_result+ assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED+ assert result.outputs == {"text": "hello agent", "summary": "Short summary"}+ agent_log = result.metadata[WorkflowNodeExecutionMetadataKey.AGENT_LOG]+ assert agent_log["output_type_check"] == {+ "passed": True,+ "results": [+ {+ "name": "summary",+ "type": "string",+ "status": "ready",+ "reason": None,+ }+ ],+ }+++def test_agent_node_structured_output_type_failure_stops_the_node():+ events = list(+ _node(+ declared_outputs=[{"name": "summary", "type": DeclaredOutputType.STRING}],+ agent_backend_client=FileOutputBackendClient(output_payload={"summary": 42}),+ )._run()+ )++ result = cast(StreamCompletedEvent, events[0]).node_run_result+ assert result.status == WorkflowNodeExecutionStatus.FAILED+ assert result.error_type == "output_type_check_failed"+ agent_log = result.metadata[WorkflowNodeExecutionMetadataKey.AGENT_LOG]+ assert agent_log["output_failure_decision"] == "fail_node"def test_agent_node_uses_resolved_backend_binding_before_backend_invocation() -> None:diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_output_adapter.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_output_adapter.pyindex 795996018f4..9c8e5d76f74 100644--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_output_adapter.py+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_output_adapter.py@@ -540,30 +540,6 @@ def test_success_output_adapter_preserves_nested_canonical_file_mapping_inside_g]-def test_success_output_adapter_does_not_normalize_top_level_canonical_file_mapping_without_declared_file_field():- tool_reference = build_file_reference(record_id="tool-file-1")- result = WorkflowAgentOutputAdapter().build_success_result(- event=AgentBackendRunSucceededInternalEvent(- run_id="run-1",- source_event_id="2-0",- output={- "transfer_method": "tool_file",- "reference": tool_reference,- },- session_snapshot=CompositorSessionSnapshot(layers=[]),- ),- inputs={},- process_data={},- metadata={"tenant_id": "tenant-1"},- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING, required=False)],- )-- assert result.outputs == {- "transfer_method": "tool_file",- "reference": tool_reference,- }--def test_success_output_adapter_maps_backend_usage_to_llm_usage_and_metadata():result = WorkflowAgentOutputAdapter().build_success_result(event=AgentBackendRunSucceededInternalEvent(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.pyindex a8ac2f9934c..cafdf139ff6 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@@ -7,7 +7,7 @@ import pytestfrom agenton.compositor import CompositorSessionSnapshotfrom dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolsLayerConfigfrom dify_agent.layers.dify_plugin import DifyPluginToolConfig, DifyPluginToolsLayerConfig-from dify_agent.protocol import DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LAYER_ID+from dify_agent.protocol import DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LAYER_ID, DIFY_AGENT_OUTPUT_LAYER_IDfrom clients.agent_backend import (DIFY_CONFIG_LAYER_ID,@@ -1008,9 +1008,7 @@ def test_invalid_previous_node_output_ref_fails_request_build():assert exc_info.value.error_code == "invalid_previous_node_output_ref"-def test_empty_declared_outputs_injects_prd_defaults_text_files_json():- """Stage 4 §4.1 (D-3): empty declared_outputs → backend receives the PRD defaults- (text / files / json) as a stable structured-output contract."""+def test_empty_declared_outputs_omits_structured_output_layer():context = _context()binding = WorkflowAgentNodeBinding(id="binding-1",@@ -1026,22 +1024,7 @@ def test_empty_declared_outputs_injects_prd_defaults_text_files_json():result = WorkflowAgentRuntimeRequestBuilder().build(context)- dumped = result.request.model_dump(mode="json")- output_layer = dumped["composition"]["layers"][-1]["config"]- properties = output_layer["json_schema"]["properties"]- assert set(properties) == {"text", "files", "json"}- assert properties["text"]["type"] == "string"- assert properties["files"]["type"] == "array"- # `files` defaults to array<file> → items is a file ref object.- 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"]+ assert DIFY_AGENT_OUTPUT_LAYER_ID not in _request_layers(result)def test_array_output_emits_typed_items_per_array_item():@@ -1072,6 +1055,7 @@ def test_array_output_emits_typed_items_per_array_item():result = WorkflowAgentRuntimeRequestBuilder().build(context)output_schema = result.request.model_dump(mode="json")["composition"]["layers"][-1]["config"]["json_schema"]+ assert output_schema["properties"]["text"] == {"type": "string"}tags_schema = output_schema["properties"]["tags"]assert tags_schema["type"] == "array"assert tags_schema["items"]["type"] == "string"@@ -1113,16 +1097,6 @@ def test_nested_declared_output_emits_object_and_array_child_schema():assert schema["required"] == ["email", "addresses"]-def test_effective_declared_outputs_passthrough_when_user_declared():- """effective_declared_outputs() must return user-provided outputs verbatim- when non-empty; only empty input gets PRD defaults injected."""- from models.agent_config_entities import DeclaredOutputConfig-- declared = [DeclaredOutputConfig(name="summary", type=DeclaredOutputType.STRING)]- effective = WorkflowAgentRuntimeRequestBuilder.effective_declared_outputs(declared)- assert list(effective) == declared--def test_mentions_expand_in_soul_and_job_prompts_without_token_leak():"""ENG-616: soul/output mentions expand, while frontend workflow markers stayliteral in the workflow task layer and resolve under workflow context."""diff --git a/api/tests/unit_tests/migrations/test_simplify_agent_v2_output_contract.py b/api/tests/unit_tests/migrations/test_simplify_agent_v2_output_contract.pynew file mode 100644index 00000000000..9526a3de580--- /dev/null+++ b/api/tests/unit_tests/migrations/test_simplify_agent_v2_output_contract.py@@ -0,0 +1,98 @@+from __future__ import annotations++import importlib.util+import json+from pathlib import Path+from types import ModuleType++import sqlalchemy as sa+from alembic.migration import MigrationContext+from alembic.operations import Operations++from models.agent_config_entities import (+ WorkflowNodeJobConfig,+ effective_declared_outputs,+)++_MIGRATION_PATH = (+ Path(__file__).resolve().parents[3]+ / "migrations/versions/2026_08_21_1422-925e75620b69_simplify_agent_v2_output_contract.py"+)+++def _load_migration_module() -> ModuleType:+ spec = importlib.util.spec_from_file_location("simplify_agent_v2_output_contract", _MIGRATION_PATH)+ if spec is None or spec.loader is None:+ raise RuntimeError("failed to load migration module")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_upgrade_removes_legacy_preset_outputs_and_preserves_custom_output_configuration() -> None:+ engine = sa.create_engine("sqlite:///:memory:")+ metadata = sa.MetaData()+ sa.Table(+ "workflow_agent_node_bindings",+ metadata,+ sa.Column("id", sa.String(36), primary_key=True),+ sa.Column("node_job_config", sa.Text(), nullable=False),+ )+ metadata.create_all(engine)+ custom_outputs = [+ {+ "name": "summary",+ "type": "string",+ "required": True,+ "description": "Keep every setting",+ "failure_strategy": {"on_failure": "stop"},+ },+ {+ "name": "attachments",+ "type": "array",+ "required": False,+ "array_item": {"type": "file", "description": "Produced file"},+ },+ ]+ node_job = {+ "workflow_prompt": "Produce a result",+ "declared_outputs": [+ {"name": "text", "type": "string"},+ custom_outputs[0],+ {"name": "files", "type": "array", "array_item": {"type": "file"}},+ custom_outputs[1],+ {"name": "json", "type": "object"},+ ],+ }+ with engine.begin() as connection:+ connection.execute(+ sa.text("INSERT INTO workflow_agent_node_bindings (id, node_job_config) VALUES (:id, :node_job_config)"),+ {"id": "binding-1", "node_job_config": json.dumps(node_job)},+ )++ module = _load_migration_module()+ with engine.begin() as connection:+ operations = Operations(MigrationContext.configure(connection))+ original_op = module.__dict__["op"]+ module.__dict__["op"] = operations+ try:+ module.upgrade()+ finally:+ module.__dict__["op"] = original_op++ with engine.begin() as connection:+ stored = connection.execute(+ sa.text("SELECT node_job_config FROM workflow_agent_node_bindings WHERE id = :id"),+ {"id": "binding-1"},+ ).scalar_one()++ migrated_node_job = json.loads(stored)+ assert migrated_node_job["workflow_prompt"] == "Produce a result"+ assert migrated_node_job["declared_outputs"] == custom_outputs++ node_job = WorkflowNodeJobConfig.model_validate(migrated_node_job)+ assert [output.name for output in effective_declared_outputs(node_job.declared_outputs)] == [+ "text",+ "summary",+ "attachments",+ ]diff --git a/api/tests/unit_tests/models/test_agent_config_entities.py b/api/tests/unit_tests/models/test_agent_config_entities.pyindex 70b98ea2f36..6aff0b297d8 100644--- a/api/tests/unit_tests/models/test_agent_config_entities.py+++ b/api/tests/unit_tests/models/test_agent_config_entities.py@@ -7,6 +7,8 @@ from models.agent_config_entities import (DeclaredOutputChildConfig,DeclaredOutputConfig,DeclaredOutputType,+ WorkflowNodeJobConfig,+ effective_declared_outputs,)@@ -218,3 +220,29 @@ def test_declared_output_validates_shape_and_defaults() -> None:},})+++def test_workflow_node_job_reserves_system_output_names() -> None:+ for name in ("text", "switch", "_session"):+ with pytest.raises(ValueError, match=f"declared output name '{name}' is reserved"):+ WorkflowNodeJobConfig.model_validate({"declared_outputs": [{"name": name, "type": "string"}]})++ node_job = WorkflowNodeJobConfig.model_validate(+ {+ "declared_outputs": [+ {"name": "files", "type": "string"},+ {"name": "json", "type": "string"},+ ]+ }+ )+ assert [output.name for output in node_job.declared_outputs] == ["files", "json"]+++def test_effective_declared_outputs_prepends_optional_system_text() -> None:+ custom = DeclaredOutputConfig(name="summary", type=DeclaredOutputType.STRING)++ effective = effective_declared_outputs([custom])++ assert [output.name for output in effective] == ["text", "summary"]+ assert effective[0].type == DeclaredOutputType.STRING+ assert effective[0].required is Falsediff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.pyindex c3b70798924..5e229d5b6d1 100644--- a/api/tests/unit_tests/services/agent/test_agent_services.py+++ b/api/tests/unit_tests/services/agent/test_agent_services.py@@ -57,7 +57,12 @@ from services.agent.roster_service import AgentRosterServicefrom services.agent.workflow_publish_service import WorkflowAgentPublishServicefrom services.agent.workspace_service import AgentWorkspaceServicefrom services.app_service import AppListParams, AppService-from services.entities.agent_entities import AgentSoulConfig, ComposerSavePayload, ComposerSaveStrategy, ComposerVariant+from services.entities.agent_entities import (+ AgentSoulConfig,+ ComposerSavePayload,+ ComposerSaveStrategy,+ ComposerVariant,+)def _agent_soul_with_model() -> AgentSoulConfig:@@ -254,13 +259,9 @@ def test_load_workflow_composer_returns_empty_state(monkeypatch: pytest.MonkeyPaassert result["binding"] is Noneassert result["save_options"] == ["node_job_only", "save_to_roster"]assert result["workflow_id"] == "workflow-1"- # Stage 4 §4.1 / §10.1 (D-3): empty state still surfaces PRD defaults so- # the front-end has stable output names to render before the user declares- # anything.effective = result["effective_declared_outputs"]- assert [o["name"] for o in effective] == ["text", "files", "json"]- files_output = next(o for o in effective if o["name"] == "files")- assert files_output["array_item"] == {"type": "file", "description": None, "children": []}+ assert [o["name"] for o in effective] == ["text"]+ assert effective[0]["required"] is Falsedef test_load_workflow_composer_serializes_existing_binding(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session):@@ -2260,10 +2261,8 @@ def test_serialize_workflow_state_changes_lock_and_save_options(assert state["agent"]["icon_background"] == "#F5F3FF"assert "save_as_new_version" in state["save_options"]assert state["agent_soul"]["app_features"] == {}- # Stage 4 §10.1 (D-3): binding with no declared_outputs → response surfaces- # PRD defaults via effective_declared_outputs (DB row remains untouched).effective_names = [o["name"] for o in state["effective_declared_outputs"]]- assert effective_names == ["text", "files", "json"]+ assert effective_names == ["text"]def test_serialize_workflow_state_passes_user_declared_outputs_through_effective(@@ -2297,12 +2296,11 @@ def test_serialize_workflow_state_passes_user_declared_outputs_through_effectivesession=session, binding=binding, agent=agent, version=version)- # When the user has declared outputs, effective_declared_outputs is the same- # list (no defaults injected).effective = state["effective_declared_outputs"]- assert [o["name"] for o in effective] == ["summary"]- assert effective[0]["type"] == "string"- assert effective[0]["required"] is True+ assert [o["name"] for o in effective] == ["text", "summary"]+ assert effective[0]["required"] is False+ assert effective[1]["type"] == "string"+ assert effective[1]["required"] is Truedef test_serialize_workflow_state_includes_inline_debug_conversation_message_state(@@ -4410,7 +4408,7 @@ def test_composer_validator_rejects_stage_4_declared_output_violations():{"declared_outputs": [{- "name": "text",+ "name": "summary","type": "string","check": {"enabled": True,@@ -4439,6 +4437,21 @@ def test_composer_validator_rejects_stage_4_declared_output_violations():})+ for reserved_name in ("text", "switch", "_session"):+ with pytest.raises(InvalidComposerConfigError, match="reserved"):+ ComposerConfigValidator.validate_node_job_dict(+ {"declared_outputs": [{"name": reserved_name, "type": "string"}]}+ )++ ComposerConfigValidator.validate_node_job_dict(+ {+ "declared_outputs": [+ {"name": "files", "type": "string"},+ {"name": "json", "type": "string"},+ ]+ }+ )+# Nested array_item is rejected outright.with pytest.raises(InvalidComposerConfigError):ComposerConfigValidator.validate_node_job_dict(@@ -5853,6 +5866,27 @@ class TestWorkflowAgentDraftBindingSync:],).model_dump(mode="json")+ @pytest.mark.parametrize("reserved_name", ["text", "switch", "_session"])+ def test_rejects_reserved_output_names_from_agent_node_graph(self, reserved_name: str):+ with pytest.raises(ValueError, match="invalid agent_declared_outputs"):+ WorkflowAgentPublishService._node_job_config_from_node_data(+ existing_binding=None,+ node_data={+ "agent_declared_outputs": [{"name": reserved_name, "type": "string"}],+ },+ )++ @pytest.mark.parametrize("output_name", ["files", "json"])+ def test_accepts_retired_output_names_as_custom_outputs_from_agent_node_graph(self, output_name: str):+ node_job = WorkflowAgentPublishService._node_job_config_from_node_data(+ existing_binding=None,+ node_data={+ "agent_declared_outputs": [{"name": output_name, "type": "string"}],+ },+ )++ assert [output.name for output in node_job.declared_outputs] == [output_name]+def test_creates_roster_binding_deriving_previous_node_refs_from_agent_task(self, sqlite_session: Session):node_job = self._sync_roster_agent_task_refs(agent_task="Review {{#previous-node.report#}} for {{#sys.query#}}.",diff --git a/api/tests/unit_tests/services/agent/test_prompt_mentions.py b/api/tests/unit_tests/services/agent/test_prompt_mentions.pyindex c6fb262572c..7bba5236f50 100644--- a/api/tests/unit_tests/services/agent/test_prompt_mentions.py+++ b/api/tests/unit_tests/services/agent/test_prompt_mentions.py@@ -252,6 +252,14 @@ def test_node_job_resolver_accepts_legacy_reversed_output_token(node_job: Workflassert "final_output.qna_report" in expanded+def test_node_job_resolver_exposes_system_text_output():+ node_job = WorkflowNodeJobConfig()++ expanded = expand_prompt_mentions("[§output:text§]", build_node_job_mention_resolver(node_job))++ assert expanded == "text (string)"++def test_node_job_resolver_matches_ref_by_node_id_and_output_fields():node_job = WorkflowNodeJobConfig.model_validate({"previous_node_output_refs": [{"node_id": "n-2", "output": "text"}]}diff --git a/api/tests/unit_tests/services/workflow/test_node_output_inspector_service.py b/api/tests/unit_tests/services/workflow/test_node_output_inspector_service.pyindex 6a52ebe5002..285acab49f5 100644--- a/api/tests/unit_tests/services/workflow/test_node_output_inspector_service.py+++ b/api/tests/unit_tests/services/workflow/test_node_output_inspector_service.py@@ -278,9 +278,7 @@ def test_node_detail_404_when_node_id_absent_from_graph(session_for: SessionFor)def test_output_preview_404_when_output_name_unknown(session_for: SessionFor) -> None:- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])ex = _execution(node_id="agent-1", outputs={"text": "hello"})session = session_for(workflow_run=run, executions=[ex])@@ -316,9 +314,7 @@ def test_output_preview_404_when_node_id_absent_from_graph(session_for: SessionFdef test_snapshot_status_pending_when_node_has_no_execution(session_for: SessionFor) -> None:- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])session = session_for(workflow_run=run, executions=[])snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)@@ -330,9 +326,7 @@ def test_snapshot_status_pending_when_node_has_no_execution(session_for: Sessiondef test_snapshot_status_running(session_for: SessionFor) -> None:- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])ex = _execution(node_id="agent-1", status=WorkflowNodeExecutionStatus.RUNNING)session = session_for(workflow_run=run, executions=[ex])@@ -353,13 +347,15 @@ def test_snapshot_status_failed_node_marks_all_outputs_failed(session_for: Sessisession = session_for(workflow_run=run, executions=[ex])snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)statuses = {o.name: o.status for o in snapshot.node_outputs[0].outputs}- assert statuses == {"a": NodeOutputStatus.FAILED, "b": NodeOutputStatus.FAILED}+ assert statuses == {+ "text": NodeOutputStatus.FAILED,+ "a": NodeOutputStatus.FAILED,+ "b": NodeOutputStatus.FAILED,+ }def test_snapshot_status_ready_when_outputs_present_and_no_failure_metadata(session_for: SessionFor) -> None:- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])ex = _execution(node_id="agent-1", outputs={"text": "hello"})session = session_for(workflow_run=run, executions=[ex])@@ -371,22 +367,29 @@ def test_snapshot_status_ready_when_outputs_present_and_no_failure_metadata(sessdef test_snapshot_marks_type_check_failure(session_for: SessionFor) -> None:service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],+ declared_outputs=[DeclaredOutputConfig(name="summary", type=DeclaredOutputType.STRING)],)run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])ex = _execution(node_id="agent-1",- outputs={"text": "ok"},+ outputs={"summary": 42},execution_metadata={"output_type_check": {"passed": False,- "results": [{"name": "text", "type": "string", "status": "type_check_failed", "reason": "wrong shape"}],+ "results": [+ {+ "name": "summary",+ "type": "string",+ "status": "type_check_failed",+ "reason": "wrong shape",+ }+ ],}},)session = session_for(workflow_run=run, executions=[ex])snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)- output = snapshot.node_outputs[0].outputs[0]+ output = next(output for output in snapshot.node_outputs[0].outputs if output.name == "summary")assert output.status == NodeOutputStatus.TYPE_CHECK_FAILEDassert output.type_check is not Noneassert output.type_check.passed is False@@ -420,7 +423,7 @@ def test_snapshot_marks_output_check_failure_when_type_check_passed(session_for:return_value="https://signed.example/x",):snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)- output = snapshot.node_outputs[0].outputs[0]+ output = next(output for output in snapshot.node_outputs[0].outputs if output.name == "report")assert output.status == NodeOutputStatus.OUTPUT_CHECK_FAILEDassert output.output_check is not Noneassert output.output_check.passed is False@@ -430,7 +433,6 @@ def test_snapshot_marks_output_check_failure_when_type_check_passed(session_for:def test_snapshot_marks_not_produced_when_declared_output_missing_from_payload(session_for: SessionFor) -> None:service = _make_service(declared_outputs=[- DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING),DeclaredOutputConfig(name="optional_meta", type=DeclaredOutputType.OBJECT, required=False),],)@@ -487,7 +489,7 @@ def test_file_output_preview_includes_signed_url(session_for: SessionFor) -> Nonreturn_value="https://signed.example/x.pdf",):snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)- preview_value = snapshot.node_outputs[0].outputs[0].value_preview+ preview_value = next(output.value_preview for output in snapshot.node_outputs[0].outputs if output.name == "report")assert isinstance(preview_value, dict)assert preview_value["preview_url"] == "https://signed.example/x.pdf"assert preview_value["reference"] == file_payload["reference"]@@ -551,7 +553,7 @@ def test_array_file_output_preview_includes_signed_urls_for_each_item(session_foservice = _make_service(declared_outputs=[DeclaredOutputConfig(- name="files",+ name="attachments",type=DeclaredOutputType.ARRAY,array_item=DeclaredArrayItem(type=DeclaredOutputType.FILE),),@@ -568,7 +570,7 @@ def test_array_file_output_preview_includes_signed_urls_for_each_item(session_fo"reference": build_file_reference(record_id="550e8400-e29b-41d4-a716-446655440002"),},]- ex = _execution(node_id="agent-1", outputs={"files": file_payloads})+ ex = _execution(node_id="agent-1", outputs={"attachments": file_payloads})session = session_for(workflow_run=run, executions=[ex])with patch("services.workflow.node_output_inspector_service._resolve_preview_url",@@ -586,11 +588,13 @@ def test_array_file_output_preview_includes_signed_urls_for_each_item(session_foapp_model=_app_model(),workflow_run_id="run-1",node_id="agent-1",- output_name="files",+ output_name="attachments",session=session,)- snapshot_value = snapshot.node_outputs[0].outputs[0].value_preview+ snapshot_value = next(+ output.value_preview for output in snapshot.node_outputs[0].outputs if output.name == "attachments"+ )assert isinstance(snapshot_value, list)assert [item["preview_url"] for item in snapshot_value] == ["https://signed.example/1.pdf",@@ -622,7 +626,7 @@ def test_file_output_preview_uses_none_when_signed_url_resolution_fails(session_):snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)- preview_value = snapshot.node_outputs[0].outputs[0].value_preview+ preview_value = next(output.value_preview for output in snapshot.node_outputs[0].outputs if output.name == "report")assert isinstance(preview_value, dict)assert preview_value["preview_url"] is None@@ -653,7 +657,8 @@ def test_object_output_preview_does_not_augment_canonical_file_mapping_shape(sessession=session,)- assert snapshot.node_outputs[0].outputs[0].value_preview == raw_value+ meta_output = next(output for output in snapshot.node_outputs[0].outputs if output.name == "meta")+ assert meta_output.value_preview == raw_valueassert preview.value == raw_value@@ -663,9 +668,7 @@ def test_object_output_preview_does_not_augment_canonical_file_mapping_shape(sesdef test_retried_count_pulled_from_attempt_metadata(session_for: SessionFor) -> None:- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])ex = _execution(node_id="agent-1",@@ -685,9 +688,7 @@ def test_retried_count_pulled_from_attempt_metadata(session_for: SessionFor) ->def test_keeps_latest_execution_per_node_by_index(session_for: SessionFor) -> None:"""When a node has multiple executions (retries / iterations) keep thecanonical one — the row with the highest ``index``."""- service = _make_service(- declared_outputs=[DeclaredOutputConfig(name="text", type=DeclaredOutputType.STRING)],- )+ service = _make_service()run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])older = _execution(node_id="agent-1", outputs={"text": "old"}, index=1)newer = _execution(node_id="agent-1", outputs={"text": "new"}, index=5)@@ -707,17 +708,17 @@ def test_array_typed_output_with_array_item_renders_correctly(session_for: Sessiservice = _make_service(declared_outputs=[DeclaredOutputConfig(- name="files",+ name="attachments",type=DeclaredOutputType.ARRAY,array_item=DeclaredArrayItem(type=DeclaredOutputType.FILE),)],)run = _workflow_run(nodes=[_agent_v2_node(node_id="agent-1")])- ex = _execution(node_id="agent-1", outputs={"files": []})+ ex = _execution(node_id="agent-1", outputs={"attachments": []})session = session_for(workflow_run=run, executions=[ex])snapshot = service.snapshot_workflow_run(app_model=_app_model(), workflow_run_id="run-1", session=session)- output = snapshot.node_outputs[0].outputs[0]+ output = next(output for output in snapshot.node_outputs[0].outputs if output.name == "attachments")assert output.type == DeclaredOutputType.ARRAYdiff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.tsindex 3857fa73a82..f768e74b567 100644--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts@@ -101,11 +101,7 @@ describe('variable utils', () => {expect.arrayContaining([expect.objectContaining({nodeId: 'node-1',- vars: [- { variable: 'text', type: VarType.string },- { variable: 'files', type: VarType.arrayFile },- { variable: 'json', type: VarType.object },- ],+ vars: [{ variable: 'text', type: VarType.string }],}),]),)@@ -150,16 +146,13 @@ describe('variable utils', () => {expect.objectContaining({nodeId: 'node-1',vars: [+ { variable: 'text', type: VarType.string },{ variable: 'summary', type: VarType.string },{ variable: 'attachments', type: VarType.arrayFile },],}),]),)- expect(availableVars.find((item) => item.nodeId === 'node-1')?.vars).not.toContainEqual({- variable: 'text',- type: VarType.string,- })})})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.tsxindex 6a722f72abb..bd86f9a0410 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@@ -447,11 +447,8 @@ describe('agent/panel', () => {expect(screen.getByText('text')).toBeInTheDocument()expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()expect(screen.queryByText('usage')).not.toBeInTheDocument()- expect(screen.getByText('files')).toBeInTheDocument()- expect(screen.getByText('array[file]')).toBeInTheDocument()- expect(screen.getByText('workflow.nodes.agent.outputVars.files.title')).toBeInTheDocument()- expect(screen.getByText('json')).toBeInTheDocument()- expect(screen.getByText('object')).toBeInTheDocument()+ expect(screen.queryByText('files')).not.toBeInTheDocument()+ expect(screen.queryByText('json')).not.toBeInTheDocument()expect(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }),).toBeInTheDocument()@@ -1756,58 +1753,65 @@ describe('agent/panel', () => {)expect(screen.getByText('summary')).toBeInTheDocument()- expect(screen.getByText('string')).toBeInTheDocument()expect(screen.getByText('Short summary')).toBeInTheDocument()expect(screen.getByText('attachments')).toBeInTheDocument()expect(screen.getByText('array[file]')).toBeInTheDocument()expect(screen.getByText('Generated files')).toBeInTheDocument()- expect(screen.queryByText('workflow.nodes.agent.outputVars.text')).not.toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()})- it('adds a declared output to workflow draft node data', () => {- render(<AgentV2Panel id="agent-node" data={createData()} panelProps={panelProps} />)+ it.each(['summary', 'files', 'json'])(+ 'adds custom output %s to workflow draft node data',+ (outputName) => {+ render(<AgentV2Panel id="agent-node" data={createData()} panelProps={panelProps} />)- fireEvent.click(- screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }),- )- fireEvent.change(- screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' }),- {- target: {- value: 'summary',+ fireEvent.click(+ screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }),+ )+ fireEvent.change(+ screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' }),+ {+ target: {+ value: outputName,+ },},- },- )- fireEvent.change(- screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.descriptionLabel' }),- {- target: {- value: 'Short summary',+ )+ fireEvent.change(+ screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.descriptionLabel' }),+ {+ target: {+ value: 'Short summary',+ },},- },- )- fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.confirm' }))+ )+ 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: 'summary',- type: 'string',- required: false,- description: 'Short summary',- }),- ]),+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_declared_outputs: expect.arrayContaining([+ expect.objectContaining({+ name: outputName,+ type: 'string',+ required: false,+ description: 'Short summary',+ }),+ ]),+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,}),- },- expect.objectContaining({- sync: true,- notRefreshWhenSyncError: true,- }),- )- })+ )+ const updatedData = mockHandleNodeDataUpdateWithSyncDraft.mock.calls.at(-1)?.[0]+ .data as AgentV2NodeType+ expect(updatedData.agent_declared_outputs?.map((output) => output.name)).toEqual([outputName])+ },+ )it('submits the output editor with a scoped Mod+Enter shortcut', () => {render(<AgentV2Panel id="agent-node" data={createData()} panelProps={panelProps} />)diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsxindex 25a477089fa..cca5e82e2d3 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx@@ -2,6 +2,7 @@ import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/typeimport { render, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { describe, expect, it, vi } from 'vite-plus/test'+import { agentV2SystemTextOutput } from '../../../output-variables'import { AgentOutputVariables } from '../index'const editorLabel = 'workflow.nodes.agent.outputVars.editorLabel'@@ -22,6 +23,12 @@ function getEditButton(name: string) {})}+function getDeleteButton(name: string) {+ return screen.getByRole('button', {+ name: `workflow.nodes.agent.outputVars.delete:{"name":"${name}"}`,+ })+}+async function confirmEditorName(user: ReturnType<typeof userEvent.setup>, name: string) {const editor = screen.getByRole('form', { name: editorLabel })const nameInput = within(editor).getByLabelText(nameLabel)@@ -32,6 +39,35 @@ async function confirmEditorName(user: ReturnType<typeof userEvent.setup>, name:}describe('AgentOutputVariables', () => {+ it('should keep system text immutable while custom outputs remain editable', async () => {+ const user = userEvent.setup()+ const outputs: DeclaredOutputConfig[] = [+ agentV2SystemTextOutput,+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ ]++ render(<AgentOutputVariables outputs={outputs} onChange={vi.fn()} />)++ await expandOutputVars(user)++ expect(+ screen.queryByRole('button', {+ name: 'workflow.nodes.agent.outputVars.edit:{"name":"text"}',+ }),+ ).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', {+ name: 'workflow.nodes.agent.outputVars.delete:{"name":"text"}',+ }),+ ).not.toBeInTheDocument()+ expect(getEditButton('summary')).toBeInTheDocument()+ expect(getDeleteButton('summary')).toBeInTheDocument()+ })+it('should add an object child without opening the parent editor', async () => {const user = userEvent.setup()const onChange = vi.fn()@@ -236,4 +272,20 @@ describe('AgentOutputVariables', () => {expect(screen.getByText('workflow.nodes.agent.outputVars.nameInvalid')).toBeInTheDocument()expect(onChange).not.toHaveBeenCalled()})++ it.each(['text', 'switch', '_session'])('should reject reserved output name %s', async (name) => {+ const user = userEvent.setup()+ const onChange = vi.fn()++ render(<AgentOutputVariables outputs={[]} onChange={onChange} />)++ await expandOutputVars(user)+ await user.click(+ screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }),+ )+ await confirmEditorName(user, name)++ expect(screen.getByText('workflow.nodes.agent.outputVars.nameInvalid')).toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsxindex 79c90df31f2..488f7ae79fc 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx@@ -43,6 +43,7 @@ export function OutputEditCard({existingOutputs,editingIndex,allowDefaultValue = true,+ reservedNames,state,onCancel,onConfirm,@@ -50,6 +51,7 @@ export function OutputEditCard({existingOutputs: EditableOutputConfig[]editingIndex?: numberallowDefaultValue?: boolean+ reservedNames?: ReadonlySet<string>state: EditingStateonCancel: () => voidonConfirm: (output: DeclaredOutputConfig, state: EditingState) => void@@ -63,9 +65,11 @@ export function OutputEditCard({(output, index) => output.name === trimmedName && index !== editingIndex,)const nameInvalid = !!trimmedName && !OUTPUT_NAME_PATTERN.test(trimmedName)- const hasNameError = duplicateName || nameInvalid+ const reservedName = reservedNames?.has(trimmedName) ?? false+ const hasNameError = duplicateName || nameInvalid || reservedNameconst defaultValueErrorKey = getDefaultValueErrorKey(draft)- const confirmDisabled = !trimmedName || nameInvalid || duplicateName || !!defaultValueErrorKey+ const confirmDisabled =+ !trimmedName || nameInvalid || duplicateName || reservedName || !!defaultValueErrorKeyfunction updateDraft(next: Partial<OutputDraft>) {setDraft((prev) => ({ ...prev, ...next }))}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.tsxindex 186b0242ce4..2354e521ab4 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@@ -11,6 +11,7 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import OutputVars from '../../../_base/components/output-vars'+import { AGENT_V2_RESERVED_OUTPUT_NAMES } from '../../output-variables'import { OutputEditCard } from './edit-card'import {canOutputHaveChildren,@@ -275,6 +276,7 @@ export function AgentOutputVariables({key={`${output.name}-editing`}editingIndex={index}existingOutputs={outputs}+ reservedNames={AGENT_V2_RESERVED_OUTPUT_NAMES}state={editingState}onCancel={() => setEditingState(null)}onConfirm={handleConfirm}@@ -315,6 +317,7 @@ export function AgentOutputVariables({{editingState && editingState.outputIndex == null ? (<OutputEditCardexistingOutputs={outputs}+ reservedNames={AGENT_V2_RESERVED_OUTPUT_NAMES}state={editingState}onCancel={() => setEditingState(null)}onConfirm={handleConfirm}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.tsindex efa51259d6e..5eba1b67577 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts@@ -3,7 +3,7 @@ import type {DeclaredOutputType,} from '@dify/contracts/api/console/apps/types.gen'import type { TFunction } from 'i18next'-import { defaultAgentV2DeclaredOutputs } from '../../output-variables'+import { agentV2SystemTextOutput } from '../../output-variables'export type DeclaredOutputChildConfig = NonNullable<DeclaredOutputConfig['children']>[number]@@ -279,19 +279,15 @@ export function getDefaultValueErrorKey(draft: OutputDraft) {}export function isDefaultOutput(output: DeclaredOutputConfig) {- return defaultAgentV2DeclaredOutputs.some(- (defaultOutput) =>- defaultOutput.name === output.name &&- defaultOutput.type === output.type &&- getOutputTypeOptionValue(defaultOutput) === getOutputTypeOptionValue(output),+ return (+ agentV2SystemTextOutput.name === output.name &&+ agentV2SystemTextOutput.type === output.type &&+ getOutputTypeOptionValue(agentV2SystemTextOutput) === getOutputTypeOptionValue(output))}export function getOutputDescription(output: EditableOutputConfig, t: TFunction) {if (output.name === 'text') return t(($) => $['nodes.agent.outputVars.text'], { ns: 'workflow' })- if (output.name === 'files')- return t(($) => $['nodes.agent.outputVars.files.title'], { ns: 'workflow' })- if (output.name === 'json') return t(($) => $['nodes.agent.outputVars.json'], { ns: 'workflow' })return output.description || ''}diff --git a/web/app/components/workflow/nodes/agent-v2/output-variables.ts b/web/app/components/workflow/nodes/agent-v2/output-variables.tsindex c4201fd18b9..44baae5dda0 100644--- a/web/app/components/workflow/nodes/agent-v2/output-variables.ts+++ b/web/app/components/workflow/nodes/agent-v2/output-variables.ts@@ -3,29 +3,18 @@ import type { AgentV2NodeType } from './types'import type { Var } from '@/app/components/workflow/types'import { VarType } from '@/app/components/workflow/types'-export const defaultAgentV2DeclaredOutputs: DeclaredOutputConfig[] = [- {- name: 'text',- type: 'string',- required: false,- description: 'Free-form text answer.',- },- {- name: 'files',- type: 'array',- required: false,- description: 'Files produced by the agent.',- array_item: {- type: 'file',- },- },- {- name: 'json',- type: 'object',- required: false,- description: 'Free-form JSON object.',- },-]+export const agentV2SystemTextOutput: DeclaredOutputConfig = Object.freeze({+ name: 'text',+ type: 'string',+ required: false,+ description: 'Free-form text answer.',+})++export const AGENT_V2_RESERVED_OUTPUT_NAMES: ReadonlySet<string> = new Set([+ 'text',+ 'switch',+ '_session',+])const outputTypeLabels: Record<DeclaredOutputConfig['type'], string> = {array: 'Array',@@ -55,9 +44,15 @@ const arrayItemVarTypes: Record<DeclaredOutputConfig['type'], VarType> = {}export function getAgentV2DeclaredOutputs(data: AgentV2NodeType) {- return data.agent_declared_outputs?.length- ? data.agent_declared_outputs- : defaultAgentV2DeclaredOutputs+ return normalizeAgentV2DeclaredOutputs(data.agent_declared_outputs ?? [])+}++export function getAgentV2CustomDeclaredOutputs(outputs: readonly DeclaredOutputConfig[]) {+ return outputs.filter((output) => !AGENT_V2_RESERVED_OUTPUT_NAMES.has(output.name))+}++export function normalizeAgentV2DeclaredOutputs(outputs: readonly DeclaredOutputConfig[]) {+ return [agentV2SystemTextOutput, ...getAgentV2CustomDeclaredOutputs(outputs)]}/**diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxindex 2632c30eac9..7c2724046a4 100644--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -38,7 +38,12 @@ import {useCreateInlineAgentBinding,useWorkflowInlineAgentDetail,} from './hooks'-import { getAgentV2DeclaredOutputs } from './output-variables'+import {+ AGENT_V2_RESERVED_OUTPUT_NAMES,+ getAgentV2CustomDeclaredOutputs,+ getAgentV2DeclaredOutputs,+ normalizeAgentV2DeclaredOutputs,+} from './output-variables'import { hasValidInlineAgentBinding } from './types'function FloatingOutputEditor({@@ -82,6 +87,7 @@ function FloatingOutputEditor({key={`${editOutputRequestKey ?? 0}-${output.name}`}editingIndex={isExistingOutput ? outputIndex : undefined}existingOutputs={outputs}+ reservedNames={AGENT_V2_RESERVED_OUTPUT_NAMES}state={{...(isExistingOutput ? { outputIndex } : {}),draft: createDraft(output),@@ -226,8 +232,15 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {const newInputs = produce(inputsRef.current, (draft) => {draft.agent_task = valueif (removedPromptOutputNames.length) {- const currentDeclaredOutputs = getAgentV2DeclaredOutputs(draft)- if (removedPromptOutputNames.length === 1 && addedPromptOutputNames.length === 1) {+ const currentDeclaredOutputs = getAgentV2CustomDeclaredOutputs(+ draft.agent_declared_outputs ?? [],+ )+ if (+ removedPromptOutputNames.length === 1 &&+ addedPromptOutputNames.length === 1 &&+ !AGENT_V2_RESERVED_OUTPUT_NAMES.has(removedPromptOutputNames[0]!) &&+ !AGENT_V2_RESERVED_OUTPUT_NAMES.has(addedPromptOutputNames[0]!)+ ) {const oldName = removedPromptOutputNames[0]!const nextName = addedPromptOutputNames[0]!draft.agent_declared_outputs = currentDeclaredOutputs.map((output) =>@@ -244,7 +257,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {inputsRef.current = newInputspromptOutputNamesRef.current = currentPromptOutputNamesif (removedPromptOutputNames.length)- setLocalDeclaredOutputs(newInputs.agent_declared_outputs ?? [])+ setLocalDeclaredOutputs(getAgentV2DeclaredOutputs(newInputs))setInputs(newInputs)},[setInputs],@@ -525,7 +538,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {setIsOutputVariablesCollapsed(false)const previousOutputs = getAgentV2DeclaredOutputs(inputsRef.current)let nextAgentTask = agentTask- let nextOutputs = outputs+ let nextOutputs = normalizeAgentV2DeclaredOutputs(outputs)if (agentTask !== undefined) {const nextPromptOutputNames = extractAgentOutputNames(agentTask)const removedPromptOutputNames = [...promptOutputNamesRef.current].filter(@@ -535,11 +548,16 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {(name) => !promptOutputNamesRef.current.has(name),)- if (removedPromptOutputNames.length === 1 && addedPromptOutputNames.length === 1) {+ if (+ removedPromptOutputNames.length === 1 &&+ addedPromptOutputNames.length === 1 &&+ !AGENT_V2_RESERVED_OUTPUT_NAMES.has(removedPromptOutputNames[0]!) &&+ !AGENT_V2_RESERVED_OUTPUT_NAMES.has(addedPromptOutputNames[0]!)+ ) {const oldName = removedPromptOutputNames[0]!const nextName = addedPromptOutputNames[0]!const oldOutputIndex = previousOutputs.findIndex((output) => output.name === oldName)- const nextOutput = outputs.find((output) => output.name === nextName)+ const nextOutput = nextOutputs.find((output) => output.name === nextName)if (oldOutputIndex >= 0 && nextOutput) {nextOutputs = previousOutputs.map((output, index) =>index === oldOutputIndex ? nextOutput : output,@@ -547,11 +565,11 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {}}}- if (nextAgentTask === undefined && previousOutputs.length === outputs.length) {+ if (nextAgentTask === undefined && previousOutputs.length === nextOutputs.length) {const renamedOutputs = previousOutputs.map((previousOutput, index) => ({oldName: previousOutput.name,- nextName: outputs[index]?.name,+ nextName: nextOutputs[index]?.name,})).filter(({ oldName, nextName }) => nextName && oldName !== nextName)@@ -563,8 +581,9 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {}}+ const customOutputs = getAgentV2CustomDeclaredOutputs(nextOutputs)const newInputs = produce(inputsRef.current, (draft) => {- draft.agent_declared_outputs = nextOutputs+ draft.agent_declared_outputs = customOutputsif (nextAgentTask !== undefined) draft.agent_task = nextAgentTask})inputsRef.current = newInputs