Repository navigation
feat(api): implement BYOA external agent backend (DIFY-3025) #45918
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 92318c9
fix(api): complete BYOA contracts and backend end-to-end validation
zyssyz123 c3e3e48
[autofix.ci] apply automated fixes
autofix-ci[bot] a3ab8a4
test(api): align BYOA export and worker coverage with CI gates
zyssyz123 ec0edcc
[autofix.ci] apply automated fixes
autofix-ci[bot] a163160
test: cover BYOA runtime and transport edge cases
zyssyz123 3aaed77
feat(api): complete BYOA frontend integration contracts
zyssyz123 dbfac81
fix(api): isolate BYOA control queue and preserve legacy binding writes
zyssyz123 f812886
docs: record BYOA frontend contracts and incremental dev acceptance
zyssyz123 52dbfe0
Merge main into BYOA backend implementation
zyssyz123 6befef8
Merge latest main into BYOA backend implementation
zyssyz123 f1181a3
fix: skip KnowledgeFS publish sync when integration is disabled
zyssyz123 4534013
Merge main for BYOA interface assistance (DIFY-3046)
zyssyz123 e0ea5a9
fix(external-agent): expose effective input file extensions
zyssyz123 6fd634f
Merge current main for DIFY-3046 API fixes
zyssyz123 da65116
chore(contracts): regenerate external-agent file capabilities
zyssyz123 bc57e8c
Merge latest main test coverage into BYOA backend
zyssyz123 6432715
test: preserve SSE errors across product acceptance projections
zyssyz123 c73cfa3
Merge latest main strict test coverage into BYOA backend
zyssyz123 9dd06e1
[autofix.ci] apply automated fixes
autofix-ci[bot] dabf5eb
test(external-agents): track merged file-scanning migration head
zyssyz123 fd5db27
fix(a2a): resolve task variables in single-node runs (DIFY-3051)
zyssyz123 4a1e5d2
Merge latest main into BYOA backend
zyssyz123 a951a7c
test(docker): cover external worker shared URL overrides
zyssyz123 ffddaea
fix(a2a): record reported final call usage (DIFY-3047)
zyssyz123 c347ac0
Merge latest main into BYOA usage reporting
zyssyz123 bfdf7f1
fix(a2a): expose immutable connection save attribution (DIFY-3054)
zyssyz123 e66e4ef
Merge latest main into BYOA connection audit
zyssyz123 4df30d1
Merge main evaluation and permission fixes into BYOA
zyssyz123 f762887
refactor(a2a): preserve closed wire profiles with string enums
zyssyz123 74897fa
fix: retain external workflow inputs and reported usage
zyssyz123 5c05f68
Merge commit '6937e798cf32d80d57b44935c6cc840356c9032d' into codex/di…
zyssyz123 334370c
Merge latest main and align CI workflow test fixtures
zyssyz123 6f70a74
fix: include authorized external trace content
zyssyz123 3349644
Merge latest main for external trace content validation
zyssyz123 d39e5e3
fix: expose App capture consent and frozen export outcomes
zyssyz123 5915199
Merge latest main for App capture consent validation
zyssyz123 2d2382a
Merge latest main for App capture consent validation
zyssyz123 680a788
Merge commit '3f0ae21bb60dbad233c9f01cae28c4e5be705a23' into codex/di…
zyssyz123 2c3af2d
docs: clarify External Agent Verify conflict recovery
zyssyz123 9c17c20
fix(external-agents): return live app icons in references
zyssyz123 59fe70f
Merge latest main into BYOA backend implementation
zyssyz123 b69e897
Merge commit '56f65f960ec1fd09d5a2cec2263daa87e0319c03' into codex/di…
zyssyz123 8d23e9c
feat(external-agents): share Agent tags and effective ACLs
zyssyz123 74d01f4
test(external-agents): distinguish persisted state from ACL projection
zyssyz123 a7e4224
chore(api): generate External Agent tag contracts
zyssyz123 61bdedc
Merge commit 'c971b4c17d7c034b9b871359cecce49a7c86d1ae' into codex/di…
zyssyz123 810d6f3
test(tracing): serve capture cases through the contract fake API
zyssyz123 ec26576
test(external-agents): include shared tags in archive fixture
zyssyz123 21be2f9
refactor(migrations): consolidate unreleased BYOA schema
zyssyz123 d056499
Merge commit '55b4bd7d793e58d69accd82c166f9b197178be00' into codex/di…
zyssyz123 10c60b7
fix(byoa): refine safe external Agent verification failures
zyssyz123 cbce7a9
chore(api): regenerate External Agent verification contracts
zyssyz123 6d723f4
[autofix.ci] apply automated fixes
autofix-ci[bot] 9cf0ade
test(api): supply scoped file access in avatar harness
zyssyz123 0eafee5
test(knowledge): isolate summary retry clock from background workers
zyssyz123 71df55b
test(knowledge): use isolated stdlib retry clock module
zyssyz123 6ebca1e
fix: normalize editor default workflow edge handles
zyssyz123 8a3b8b1
Merge latest main into BYOA backend feature
zyssyz123 aff2544
fix: preserve inline external capture errors with query meta
zyssyz123 2628fcb
fix(a2a): diagnose invalid direct message reply fields
zyssyz123 21cf44f
Merge branch 'main' of https://github.com/langgenius/dify into codex/…
zyssyz123 94d695f
test(a2a): narrow reply fixture values under strict typing
zyssyz123 7243d0d
Merge branch 'main' of https://github.com/langgenius/dify into codex/…
zyssyz123 ff7a9f4
Merge branches 'main' and 'codex/dify-3025-byoa-backend-20261109' of …
zyssyz123 575e15d
fix(api): consume Graphon from its upstream repository
zyssyz123 b3a1586
Merge main into BYOA backend and preserve file lifecycle contracts
zyssyz123 386097f
refactor(api): move External Agent adapters out of providers
zyssyz123 485d353
fix(api): integrate BYOA file adapters with explicit upload ownership
zyssyz123 301896f
fix(api): gate External Agent periodic tasks by deployment mode
zyssyz123 c2aa771
test(api): inject knowledge ports in External Agent factory tests
zyssyz123 15b4f93
fix(api): connect BYOA resume and tests to main application ports
zyssyz123 22df2ea
fix(api): keep the shared upload contract stable for reserved files
zyssyz123 fa09f6b
fix(web): cover External Agent test mutations
zyssyz123 04adabd
test(api): fix workflow cleanup and parser CI regressions
zyssyz123 89a6beb
test(api): cover External Agent Beat in the Celery gate
zyssyz123 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Adapters for Dify application ports.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """A2A and Dify runtime adapters for External Agents.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
| 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, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.