Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
7951d78
feat(api): implement BYOA external agent backend
zyssyz123 Nov 9, 2026
92318c9
fix(api): complete BYOA contracts and backend end-to-end validation
zyssyz123 Nov 10, 2026
c3e3e48
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 10, 2026
a3ab8a4
test(api): align BYOA export and worker coverage with CI gates
zyssyz123 Nov 10, 2026
ec0edcc
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 10, 2026
a163160
test: cover BYOA runtime and transport edge cases
zyssyz123 Nov 10, 2026
3aaed77
feat(api): complete BYOA frontend integration contracts
zyssyz123 Nov 12, 2026
dbfac81
fix(api): isolate BYOA control queue and preserve legacy binding writes
zyssyz123 Nov 12, 2026
f812886
docs: record BYOA frontend contracts and incremental dev acceptance
zyssyz123 Nov 12, 2026
52dbfe0
Merge main into BYOA backend implementation
zyssyz123 Nov 12, 2026
6befef8
Merge latest main into BYOA backend implementation
zyssyz123 Nov 12, 2026
f1181a3
fix: skip KnowledgeFS publish sync when integration is disabled
zyssyz123 Nov 15, 2026
4534013
Merge main for BYOA interface assistance (DIFY-3046)
zyssyz123 Nov 15, 2026
e0ea5a9
fix(external-agent): expose effective input file extensions
zyssyz123 Nov 15, 2026
6fd634f
Merge current main for DIFY-3046 API fixes
zyssyz123 Nov 15, 2026
da65116
chore(contracts): regenerate external-agent file capabilities
zyssyz123 Nov 15, 2026
bc57e8c
Merge latest main test coverage into BYOA backend
zyssyz123 Nov 15, 2026
6432715
test: preserve SSE errors across product acceptance projections
zyssyz123 Nov 15, 2026
c73cfa3
Merge latest main strict test coverage into BYOA backend
zyssyz123 Nov 15, 2026
9dd06e1
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 15, 2026
dabf5eb
test(external-agents): track merged file-scanning migration head
zyssyz123 Nov 15, 2026
fd5db27
fix(a2a): resolve task variables in single-node runs (DIFY-3051)
zyssyz123 Nov 17, 2026
4a1e5d2
Merge latest main into BYOA backend
zyssyz123 Nov 17, 2026
a951a7c
test(docker): cover external worker shared URL overrides
zyssyz123 Nov 17, 2026
ffddaea
fix(a2a): record reported final call usage (DIFY-3047)
zyssyz123 Nov 18, 2026
c347ac0
Merge latest main into BYOA usage reporting
zyssyz123 Nov 18, 2026
bfdf7f1
fix(a2a): expose immutable connection save attribution (DIFY-3054)
zyssyz123 Nov 19, 2026
e66e4ef
Merge latest main into BYOA connection audit
zyssyz123 Nov 19, 2026
4df30d1
Merge main evaluation and permission fixes into BYOA
zyssyz123 Nov 19, 2026
f762887
refactor(a2a): preserve closed wire profiles with string enums
zyssyz123 Nov 19, 2026
74897fa
fix: retain external workflow inputs and reported usage
zyssyz123 Nov 19, 2026
5c05f68
Merge commit '6937e798cf32d80d57b44935c6cc840356c9032d' into codex/di…
zyssyz123 Nov 19, 2026
334370c
Merge latest main and align CI workflow test fixtures
zyssyz123 Nov 19, 2026
6f70a74
fix: include authorized external trace content
zyssyz123 Nov 19, 2026
3349644
Merge latest main for external trace content validation
zyssyz123 Nov 19, 2026
d39e5e3
fix: expose App capture consent and frozen export outcomes
zyssyz123 Nov 20, 2026
5915199
Merge latest main for App capture consent validation
zyssyz123 Nov 20, 2026
2d2382a
Merge latest main for App capture consent validation
zyssyz123 Nov 20, 2026
680a788
Merge commit '3f0ae21bb60dbad233c9f01cae28c4e5be705a23' into codex/di…
zyssyz123 Nov 20, 2026
2c3af2d
docs: clarify External Agent Verify conflict recovery
zyssyz123 Nov 20, 2026
9c17c20
fix(external-agents): return live app icons in references
zyssyz123 Nov 23, 2026
59fe70f
Merge latest main into BYOA backend implementation
zyssyz123 Nov 23, 2026
b69e897
Merge commit '56f65f960ec1fd09d5a2cec2263daa87e0319c03' into codex/di…
zyssyz123 Nov 23, 2026
8d23e9c
feat(external-agents): share Agent tags and effective ACLs
zyssyz123 Nov 23, 2026
74d01f4
test(external-agents): distinguish persisted state from ACL projection
zyssyz123 Nov 23, 2026
a7e4224
chore(api): generate External Agent tag contracts
zyssyz123 Nov 23, 2026
61bdedc
Merge commit 'c971b4c17d7c034b9b871359cecce49a7c86d1ae' into codex/di…
zyssyz123 Nov 23, 2026
810d6f3
test(tracing): serve capture cases through the contract fake API
zyssyz123 Nov 23, 2026
ec26576
test(external-agents): include shared tags in archive fixture
zyssyz123 Nov 23, 2026
21be2f9
refactor(migrations): consolidate unreleased BYOA schema
zyssyz123 Nov 24, 2026
d056499
Merge commit '55b4bd7d793e58d69accd82c166f9b197178be00' into codex/di…
zyssyz123 Nov 25, 2026
10c60b7
fix(byoa): refine safe external Agent verification failures
zyssyz123 Nov 25, 2026
cbce7a9
chore(api): regenerate External Agent verification contracts
zyssyz123 Nov 25, 2026
6d723f4
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 25, 2026
9cf0ade
test(api): supply scoped file access in avatar harness
zyssyz123 Nov 25, 2026
0eafee5
test(knowledge): isolate summary retry clock from background workers
zyssyz123 Nov 25, 2026
71df55b
test(knowledge): use isolated stdlib retry clock module
zyssyz123 Nov 25, 2026
6ebca1e
fix: normalize editor default workflow edge handles
zyssyz123 Nov 26, 2026
8a3b8b1
Merge latest main into BYOA backend feature
zyssyz123 Nov 26, 2026
aff2544
fix: preserve inline external capture errors with query meta
zyssyz123 Nov 26, 2026
2628fcb
fix(a2a): diagnose invalid direct message reply fields
zyssyz123 Nov 26, 2026
21cf44f
Merge branch 'main' of https://github.com/langgenius/dify into codex/…
zyssyz123 Nov 26, 2026
94d695f
test(a2a): narrow reply fixture values under strict typing
zyssyz123 Nov 26, 2026
7243d0d
Merge branch 'main' of https://github.com/langgenius/dify into codex/…
zyssyz123 Nov 26, 2026
ff7a9f4
Merge branches 'main' and 'codex/dify-3025-byoa-backend-20261109' of …
zyssyz123 Nov 27, 2026
575e15d
fix(api): consume Graphon from its upstream repository
zyssyz123 Nov 27, 2026
b3a1586
Merge main into BYOA backend and preserve file lifecycle contracts
zyssyz123 Dec 1, 2026
386097f
refactor(api): move External Agent adapters out of providers
zyssyz123 Dec 1, 2026
485d353
fix(api): integrate BYOA file adapters with explicit upload ownership
zyssyz123 Dec 1, 2026
301896f
fix(api): gate External Agent periodic tasks by deployment mode
zyssyz123 Dec 1, 2026
c2aa771
test(api): inject knowledge ports in External Agent factory tests
zyssyz123 Dec 1, 2026
15b4f93
fix(api): connect BYOA resume and tests to main application ports
zyssyz123 Dec 1, 2026
22df2ea
fix(api): keep the shared upload contract stable for reserved files
zyssyz123 Dec 1, 2026
fa09f6b
fix(web): cover External Agent test mutations
zyssyz123 Dec 1, 2026
04adabd
test(api): fix workflow cleanup and parser CI regressions
zyssyz123 Dec 1, 2026
89a6beb
test(api): cover External Agent Beat in the Celery gate
zyssyz123 Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,28 @@ CELERY_BROKER_URL=redis://:difyai123456@localhost:${REDIS_PORT}/1
CELERY_BACKEND=redis

# Ops trace configuration
# External Agent A2A 1.0 HTTP+JSON profile. Run a dedicated external_agents
# worker and beat before enabling. Production uses the frozen defaults.
EXTERNAL_AGENTS_ENABLED=false
EXTERNAL_AGENTS_QUEUE=external_agents
EXTERNAL_AGENTS_HTTP_CONNECT_SECONDS=5
EXTERNAL_AGENTS_HTTP_TIMEOUT_SECONDS=30
EXTERNAL_AGENTS_LOGICAL_BUDGET_SECONDS=3600
EXTERNAL_AGENTS_SSE_WINDOW_SECONDS=30
EXTERNAL_AGENTS_POLL_SECONDS=5
EXTERNAL_AGENTS_CANCEL_WINDOW_SECONDS=30
EXTERNAL_AGENTS_TRACKING_SECONDS=86400
EXTERNAL_AGENTS_BACKGROUND_INITIAL_SECONDS=60
EXTERNAL_AGENTS_BACKGROUND_MAX_SECONDS=300
EXTERNAL_AGENTS_BACKGROUND_MAX_QUERIES=300
EXTERNAL_AGENTS_WORKSPACE_QUERY_CONCURRENCY=20
EXTERNAL_AGENTS_ENDPOINT_QUERY_CONCURRENCY=5
EXTERNAL_AGENTS_IO_CONCURRENCY=32
EXTERNAL_AGENTS_MAX_FILES=5
EXTERNAL_AGENTS_DOCUMENT_BYTES=15728640
EXTERNAL_AGENTS_IMAGE_BYTES=10485760
EXTERNAL_AGENTS_TOTAL_FILE_BYTES=31457280

# Keep new workers separate from legacy ops_trace workers during upgrades.
OPS_TRACE_QUEUE=ops_trace_v2
OPS_TRACE_EXPORT_MAX_ATTEMPTS=6
Expand Down
31 changes: 31 additions & 0 deletions api/.importlinter
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[importlinter]
root_packages =
adapters
core
constants
context
Expand All @@ -17,12 +18,34 @@ root_packages =
services
include_external_packages = True

[importlinter:contract:external-agents-application]
name = External Agent application services use consumer ports and plain records
type = forbidden
source_modules =
services.external_agents
forbidden_modules =
adapters
celery
configs
controllers
core
enterprise
extensions
flask
models
repositories
sqlalchemy
tasks
werkzeug
allow_indirect_imports = True

[importlinter:contract:domain-boundary]
name = Domain code depends on no application, persistence, framework, configuration, queue, transport, or legacy kernel code
type = forbidden
source_modules =
domain
forbidden_modules =
adapters
celery
configs
controllers
Expand Down Expand Up @@ -81,6 +104,14 @@ layers =
# error makes this list shrink whenever a legacy dependency is removed.
unmatched_ignore_imports_alerting = error
ignore_imports =
# Legacy workflow composition selects the External adapter; application
# policy/state stays in the framework-neutral external_agents slice.
core.workflow.node_factory -> extensions.ext_application_services
core.workflow.node_factory -> adapters.external_agents.workflow_node
core.workflow.workflow_entry -> extensions.ext_application_services
core.workflow.workflow_entry -> adapters.external_agents.workflow_budget
core.workflow.nodes.agent_v2.validators -> services.external_agents.workflow_runtime
core.workflow.nodes.agent_v2.validators -> adapters.external_agents.workflow_node
# The Dify node factory composes the Human Input runtime for workflow execution.
core.workflow.node_factory -> services.human_input_v2.composition
# Legacy generators delegate configured file defaults to the application owner during core migration.
Expand Down
1 change: 1 addition & 0 deletions api/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Adapters for Dify application ports."""
1 change: 1 addition & 0 deletions api/adapters/external_agents/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""A2A and Dify runtime adapters for External Agents."""
91 changes: 91 additions & 0 deletions api/adapters/external_agents/call_usage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""Dify's finite remote-reported call-total profile, not an A2A standard or billing authority.

Comment thread
wylswz marked this conversation as resolved.
Resolved
Only explicit gateway carrier provenance is admitted. A terminal Task (including
its correlated terminal status event) or a direct Agent Message can report one
final cumulative total. Working snapshots, arbitrary nested metadata and Trace
steps never establish call usage. Observations cannot submit business work.
"""

from enum import StrEnum
from typing import Annotated

from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, ValidationError

from services.external_agents.protocol import GatewayReceipt
from services.external_agents.traceability import ReportedCallUsage

METADATA_USAGE_PROFILE = "dify.metadata-usage-total-tokens.v1"
_TERMINAL_TASK_STATES = frozenset(
{"TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"}
)


class MetadataUsageScope(StrEnum):
CALL = "call"
INVOCATION = "invocation"
TASK = "task"
MESSAGE = "message"


def _metadata_usage_scope_from_wire(value: object) -> MetadataUsageScope:
"""Accept a supported scope string; return its member or reject coercion.

Preconditions: value is untrusted metadata or an existing scope member.
Postconditions: only the four frozen scope strings succeed; bytes and
non-string values cannot establish call usage or relax token validation.
"""
if not isinstance(value, str):
raise ValueError("A usage scope must be a string.")
return MetadataUsageScope(value)


class _MetadataUsage(BaseModel):
"""Validate the exact total and optional explicit call-scope declaration.

Other JSON components are deliberately uninterpreted: they cannot establish
a total or modify this profile's scope. No component totals are summed.
"""

model_config = ConfigDict(strict=True, extra="ignore", populate_by_name=False)

total_tokens: int = Field(alias="totalTokens", ge=0, le=2**63 - 1)
scope: Annotated[MetadataUsageScope, BeforeValidator(_metadata_usage_scope_from_wire)] = MetadataUsageScope.CALL


class MetadataCallUsageProof:
def prove(self, receipt: GatewayReceipt) -> tuple[ReportedCallUsage, int] | None:
"""Prove this profile's final remote-reported total, or leave usage unknown.

Preconditions: the runtime admitted the gateway receipt's Task/context
identity. Postconditions: only the current carrier's strict integer total
becomes usage, including zero. A constant revision makes repeated final
snapshots idempotent; changed final totals retain the repository's
conflict protection. Missing, partial, non-call or ambiguous data returns
no proof and cannot change the business outcome.
"""
carrier = receipt.usage_carrier
if carrier is None:
return None
if receipt.kind == "task":
if receipt.state not in _TERMINAL_TASK_STATES or carrier.source not in {"task", "statusUpdate"}:
return None
elif carrier.source != "message" or receipt.payload.get("role") != "ROLE_AGENT":
return None
if not isinstance(carrier.value, dict) or "total_tokens" in carrier.value:
return None
try:
usage = _MetadataUsage.model_validate(carrier.value)
except ValidationError:
return None
if usage.scope not in {"call", "invocation", receipt.kind}:
return None
return (
ReportedCallUsage(
total_tokens=usage.total_tokens,
# This path is relative to the validated wire carrier. Keep it
# stable when a final SSE report is replayed by a full GetTask.
source_path="metadata.usage.totalTokens",
adapter=METADATA_USAGE_PROFILE,
),
1,
)
84 changes: 84 additions & 0 deletions api/adapters/external_agents/control_adapters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Workspace permissions and encryption for the External Agent control plane."""

import hmac
from collections.abc import Mapping, Sequence

from core.helper.encrypter import batch_decrypt_token, encrypt_token
from enums.account import TenantAccountRole
from libs.helper import build_icon_url
from machinery.context import RequestContext
from repositories.workspace.workspace_repository import WorkspaceRepository
from services.enterprise import rbac_service as enterprise
from services.external_agents.contracts import ExternalAsset
from services.rbac.builtin import builtin_permissions
from services.rbac.members import MemberService


class DifyExternalIconURLs:
"""Use Dify's existing signed-image route for already admitted upload IDs."""

def image_urls(self, file_ids: Sequence[str]) -> Mapping[str, str]:
"""Generate refreshable capabilities without querying or reading file bytes."""
urls = {identifier: build_icon_url("image", identifier) for identifier in file_ids}
return {identifier: url for identifier, url in urls.items() if url is not None}


class WorkspaceExternalSecretCodec:
def encrypt(self, tenant_id: str, plaintext: str) -> str:
return encrypt_token(tenant_id, plaintext)

def decrypt(self, tenant_id: str, ciphertext: str) -> str:
return batch_decrypt_token(tenant_id, [ciphertext])[0]

def matches(self, tenant_id: str, ciphertext: str, plaintext: str) -> bool:
return hmac.compare_digest(self.decrypt(tenant_id, ciphertext), plaintext)


class WorkspaceExternalAssetAccess:
def __init__(self, *, workspaces: WorkspaceRepository, permissions: MemberService, rbac_enabled: bool) -> None:
self._workspaces = workspaces
self._permissions = permissions
self._rbac_enabled = rbac_enabled

def role(self, context: RequestContext) -> str | None:
return self._workspaces.get_account_role(account_id=context.account_id, tenant_id=context.active_workspace_id)

def permission_keys(
self, context: RequestContext, assets: Sequence[ExternalAsset]
) -> Mapping[str, tuple[str, ...]]:
"""Project Native Agent ACL semantics once for an admitted External page.

Preconditions: assets were tenant-scoped and visibility-filtered before
this read. Postconditions: custom resource overrides replace defaults;
the same resource-creator bypass as AGENT_EDIT applies only under RBAC.
Legacy roles retain their existing permissions. These keys do not grant
External connection/enable/delete control-plane access.
"""
if not assets:
return {}
snapshot = self._permissions.permissions(context.active_workspace_id, context.account_id).agent
keys = snapshot.permission_keys_by_resource_ids([asset.id for asset in assets])
creator_keys = tuple(builtin_permissions(TenantAccountRole.OWNER).agent.default_permission_keys)
return {
asset.id: creator_keys
if self._rbac_enabled and asset.created_by == context.account_id
else tuple(keys.get(asset.id, ()))
for asset in assets
}

def visible_agent_ids(self, context: RequestContext) -> frozenset[str] | None:
if not self._rbac_enabled:
return None
permissions = self._permissions.permissions(context.active_workspace_id, context.account_id)
scope = enterprise.RBACService.AgentAccess.whitelist_resources(context.active_workspace_id, context.account_id)
preview = "agent.acl.preview"
has_default = (
preview in permissions.agent.default_permission_keys or preview in permissions.workspace.permission_keys
)
permitted = (
None
if has_default
else frozenset(item.resource_id for item in permissions.agent.overrides if preview in item.permission_keys)
)
# Preserve the same effective whitelist semantics as the Agent roster.
return permitted if scope.unrestricted else frozenset(scope.resource_ids)
Loading
Loading