chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from mkdocs.config.defaults import MkDocsConfig
|
||||
from mkdocs.structure.files import Files
|
||||
from mkdocs.structure.pages import Page
|
||||
from snippets import inject_snippets
|
||||
|
||||
DOCS_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def on_page_markdown(markdown: str, page: Page, config: MkDocsConfig, files: Files) -> str:
|
||||
"""Inject repository snippets before MkDocs renders Markdown."""
|
||||
relative_path = DOCS_ROOT / page.file.src_uri
|
||||
return inject_snippets(markdown, relative_path.parent)
|
||||
@@ -0,0 +1,228 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
SNIPPET_DIRECTIVE_PATTERN = re.compile(r"^```snippet\s+\{[^}]+\}\s*(?:```|\n```)$", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SnippetDirective:
|
||||
path: str
|
||||
title: str | None = None
|
||||
fragment: str | None = None
|
||||
highlight: str | None = None
|
||||
extra_attrs: dict[str, str] | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LineRange:
|
||||
start_line: int
|
||||
end_line: int
|
||||
|
||||
def intersection(self, ranges: list[LineRange]) -> list[LineRange]:
|
||||
intersections: list[LineRange] = []
|
||||
for line_range in ranges:
|
||||
start_line = max(self.start_line, line_range.start_line)
|
||||
end_line = min(self.end_line, line_range.end_line)
|
||||
if start_line < end_line:
|
||||
intersections.append(LineRange(start_line, end_line))
|
||||
return intersections
|
||||
|
||||
@staticmethod
|
||||
def merge(ranges: list[LineRange]) -> list[LineRange]:
|
||||
if not ranges:
|
||||
return []
|
||||
|
||||
merged: list[LineRange] = []
|
||||
for line_range in sorted(ranges, key=lambda item: item.start_line):
|
||||
if not merged or merged[-1].end_line < line_range.start_line:
|
||||
merged.append(line_range)
|
||||
else:
|
||||
previous = merged[-1]
|
||||
merged[-1] = LineRange(previous.start_line, max(previous.end_line, line_range.end_line))
|
||||
return merged
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RenderedSnippet:
|
||||
content: str
|
||||
highlights: list[LineRange]
|
||||
original_range: LineRange
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ParsedFile:
|
||||
lines: list[str]
|
||||
sections: dict[str, list[LineRange]]
|
||||
lines_mapping: dict[int, int]
|
||||
|
||||
def render(self, fragment_sections: list[str], highlight_sections: list[str]) -> RenderedSnippet:
|
||||
fragment_ranges: list[LineRange] = []
|
||||
if fragment_sections:
|
||||
for section_name in fragment_sections:
|
||||
fragment_ranges.extend(_section_ranges(self.sections, section_name))
|
||||
fragment_ranges = LineRange.merge(fragment_ranges)
|
||||
else:
|
||||
fragment_ranges = [LineRange(0, len(self.lines))]
|
||||
|
||||
highlight_ranges: list[LineRange] = []
|
||||
for section_name in highlight_sections:
|
||||
highlight_ranges.extend(_section_ranges(self.sections, section_name))
|
||||
highlight_ranges = LineRange.merge(highlight_ranges)
|
||||
|
||||
rendered_highlights: list[LineRange] = []
|
||||
rendered_lines: list[str] = []
|
||||
last_end_line = 0
|
||||
current_line = 0
|
||||
for fragment_range in fragment_ranges:
|
||||
if fragment_range.start_line > last_end_line:
|
||||
rendered_lines.append("..." if current_line == 0 else "\n...")
|
||||
current_line += 1
|
||||
|
||||
for highlight_range in fragment_range.intersection(highlight_ranges):
|
||||
rendered_highlights.append(
|
||||
LineRange(
|
||||
highlight_range.start_line - fragment_range.start_line + current_line,
|
||||
highlight_range.end_line - fragment_range.start_line + current_line,
|
||||
)
|
||||
)
|
||||
|
||||
for line_number in range(fragment_range.start_line, fragment_range.end_line):
|
||||
rendered_lines.append(self.lines[line_number])
|
||||
current_line += 1
|
||||
last_end_line = fragment_range.end_line
|
||||
|
||||
if last_end_line < len(self.lines):
|
||||
rendered_lines.append("\n...")
|
||||
|
||||
return RenderedSnippet(
|
||||
content="\n".join(rendered_lines),
|
||||
highlights=LineRange.merge(rendered_highlights),
|
||||
original_range=LineRange(
|
||||
self.lines_mapping[fragment_ranges[0].start_line],
|
||||
self.lines_mapping[fragment_ranges[-1].end_line - 1] + 1,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def parse_snippet_directive(line: str) -> SnippetDirective | None:
|
||||
match = re.fullmatch(r"```snippet\s+\{([^}]+)\}\s*(?:```|\n```)", line.strip())
|
||||
if not match:
|
||||
return None
|
||||
|
||||
attrs = {key: value for key, value in re.findall(r'(\w+)="([^"]*)"', match.group(1))}
|
||||
if "path" not in attrs:
|
||||
raise ValueError('Missing required key "path" in snippet directive')
|
||||
|
||||
extra_attrs = {key: value for key, value in attrs.items() if key not in {"path", "title", "fragment", "highlight"}}
|
||||
return SnippetDirective(
|
||||
path=attrs["path"],
|
||||
title=attrs.get("title"),
|
||||
fragment=attrs.get("fragment"),
|
||||
highlight=attrs.get("highlight"),
|
||||
extra_attrs=extra_attrs or None,
|
||||
)
|
||||
|
||||
|
||||
def parse_file_sections(file_path: Path) -> ParsedFile:
|
||||
input_lines = file_path.read_text(encoding="utf-8").splitlines()
|
||||
output_lines: list[str] = []
|
||||
lines_mapping: dict[int, int] = {}
|
||||
sections: dict[str, list[LineRange]] = {}
|
||||
section_starts: dict[str, int] = {}
|
||||
|
||||
output_line_number = 0
|
||||
for source_line_number, line in enumerate(input_lines):
|
||||
section_match = re.search(r"\s*(?:###|///)\s*\[([^]]+)]\s*$", line)
|
||||
if section_match is None:
|
||||
output_lines.append(line)
|
||||
lines_mapping[output_line_number] = source_line_number
|
||||
output_line_number += 1
|
||||
continue
|
||||
|
||||
line_before_marker = line[: section_match.start()]
|
||||
for section_name in section_match.group(1).split(","):
|
||||
section_name = section_name.strip()
|
||||
if section_name.startswith("/"):
|
||||
start_line = section_starts.pop(section_name[1:], None)
|
||||
if start_line is None:
|
||||
raise ValueError(f"Cannot end unstarted section {section_name!r} at {file_path}")
|
||||
end_line = output_line_number + 1 if line_before_marker else output_line_number
|
||||
sections.setdefault(section_name[1:], []).append(LineRange(start_line, end_line))
|
||||
else:
|
||||
if section_name in section_starts:
|
||||
raise ValueError(f"Cannot nest section {section_name!r} at {file_path}")
|
||||
section_starts[section_name] = output_line_number
|
||||
|
||||
if line_before_marker:
|
||||
output_lines.append(line_before_marker)
|
||||
lines_mapping[output_line_number] = source_line_number
|
||||
output_line_number += 1
|
||||
|
||||
if section_starts:
|
||||
raise ValueError(f"Some sections were not finished in {file_path}: {list(section_starts)}")
|
||||
|
||||
return ParsedFile(lines=output_lines, sections=sections, lines_mapping=lines_mapping)
|
||||
|
||||
|
||||
def format_highlight_lines(highlight_ranges: list[LineRange]) -> str:
|
||||
parts: list[str] = []
|
||||
for highlight_range in highlight_ranges:
|
||||
start_line = highlight_range.start_line + 1
|
||||
end_line = highlight_range.end_line
|
||||
parts.append(str(start_line) if start_line == end_line else f"{start_line}-{end_line}")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def inject_snippets(markdown: str, relative_path_root: Path) -> str:
|
||||
def replace_snippet(match: re.Match[str]) -> str:
|
||||
directive = parse_snippet_directive(match.group(0))
|
||||
if directive is None:
|
||||
return match.group(0)
|
||||
|
||||
file_path = _resolve_snippet_path(directive.path, relative_path_root)
|
||||
parsed_file = parse_file_sections(file_path)
|
||||
rendered = parsed_file.render(
|
||||
directive.fragment.split() if directive.fragment else [],
|
||||
directive.highlight.split() if directive.highlight else [],
|
||||
)
|
||||
|
||||
attrs: list[str] = []
|
||||
title = directive.title or _default_title(file_path, rendered.original_range, bool(directive.fragment))
|
||||
if title:
|
||||
attrs.append(f'title="{title}"')
|
||||
if rendered.highlights:
|
||||
attrs.append(f'hl_lines="{format_highlight_lines(rendered.highlights)}"')
|
||||
if directive.extra_attrs:
|
||||
attrs.extend(f'{key}="{value}"' for key, value in directive.extra_attrs.items())
|
||||
|
||||
attrs_text = f" {{{' '.join(attrs)}}}" if attrs else ""
|
||||
file_extension = file_path.suffix.lstrip(".") or "text"
|
||||
return f"```{file_extension}{attrs_text}\n{rendered.content}\n```"
|
||||
|
||||
return SNIPPET_DIRECTIVE_PATTERN.sub(replace_snippet, markdown)
|
||||
|
||||
|
||||
def _section_ranges(sections: dict[str, list[LineRange]], section_name: str) -> list[LineRange]:
|
||||
if section_name not in sections:
|
||||
raise ValueError(f"Unrecognized snippet section {section_name!r}; expected one of {list(sections)}")
|
||||
return sections[section_name]
|
||||
|
||||
|
||||
def _resolve_snippet_path(path: str, relative_path_root: Path) -> Path:
|
||||
file_path = (REPO_ROOT / path[1:]).resolve() if path.startswith("/") else (relative_path_root / path).resolve()
|
||||
if not file_path.exists():
|
||||
raise FileNotFoundError(f"Snippet file {file_path} not found")
|
||||
if not file_path.is_relative_to(REPO_ROOT):
|
||||
raise ValueError(f"Snippet file {file_path} must be inside {REPO_ROOT}")
|
||||
return file_path
|
||||
|
||||
|
||||
def _default_title(file_path: Path, original_range: LineRange, has_fragment: bool) -> str:
|
||||
relative_path = file_path.relative_to(REPO_ROOT)
|
||||
if not has_fragment:
|
||||
return str(relative_path)
|
||||
return f"{relative_path} (L{original_range.start_line + 1}-L{original_range.end_line})"
|
||||
@@ -0,0 +1,38 @@
|
||||
# Agent run lifecycle
|
||||
|
||||
The server validates current Config, restored State and module references before
|
||||
external operations. It creates fresh native Capability/Toolset instances and
|
||||
runs Pydantic AI with a per-run Deps object. Current prompts and instructions are
|
||||
built from that run's config.
|
||||
|
||||
Native `wrap_run` scopes acquire operation resources and clean them in `finally`.
|
||||
Runtime acquires a lease; Shell bootstraps once and removes tracked jobs on exit;
|
||||
Config pulls mentioned assets on successful first initialization. Initialization
|
||||
flags are written only after successful setup, so failures can retry. The API's
|
||||
workflow terminal events own Workspace retirement and physical resource collection.
|
||||
|
||||
The runner saves captured conversation history in its outer `finally`, strips
|
||||
transient instructions and marks unexecuted trailing tool calls interrupted.
|
||||
If no messages were captured, restored history remains intact. Compaction rewrites
|
||||
are included. A terminal state snapshot is built after capability cleanup for
|
||||
success, failure and cancellation.
|
||||
|
||||
Snapshot v2 stores only JSON state:
|
||||
|
||||
```json
|
||||
{"schema_version": 2, "layers": {"history": {"messages": []}}}
|
||||
```
|
||||
|
||||
Configurations, clients, lease handles, tokens, models and lifecycle enums are
|
||||
excluded. State is keyed by name, so instruction order does not constrain resume;
|
||||
known optional modules can be added or removed. The API resubmits current Config
|
||||
and retains session ownership through `AgentWorkspaceBinding.session_snapshot`.
|
||||
All snapshot readers use `SessionSnapshot` validation. Its `migrate_snapshot`
|
||||
validator dispatches v1 (including unversioned legacy lists) to the data-only
|
||||
`migrate_snapshot_v1_to_v2` helper. V2 is validated directly; unknown explicit
|
||||
versions are rejected. Reading converts data in memory without updating stored
|
||||
JSON; the API saves the terminal v2 snapshot through its existing session owner.
|
||||
Known legacy names map to their meaningful State and removed AskHuman slots are
|
||||
discarded. Their unanswered tool calls are marked interrupted so native history
|
||||
repair closes them before the first new user turn. All runs use the native runner.
|
||||
Unknown legacy names and malformed state are rejected.
|
||||
@@ -0,0 +1,232 @@
|
||||
# Runtime resources
|
||||
|
||||
Dify separates persistent product resources from request-time execution:
|
||||
|
||||
- a **Home Snapshot** is immutable Agent-owned Home content;
|
||||
- a **Workspace** is mutable working data owned by a product scope such as a
|
||||
conversation, Build Draft, or Workflow run;
|
||||
- an **Execution Binding** is one materialized Agent participant, including its
|
||||
private Home and resumable session, attached to a Workspace;
|
||||
- a **RuntimeLease** is operation-scoped access to the physical Binding.
|
||||
|
||||
`AgentWorkspaceBinding.id` is the participant, materialized Home, and persisted
|
||||
module session identity. `agent_id` identifies the source Agent. The same
|
||||
Agent can therefore have multiple active Bindings in one Workspace:
|
||||
each has an independent Home and session, while all may share Workspace files.
|
||||
|
||||
Home and Workspace are logically independent. A backend may still couple their
|
||||
physical representation. For example, current E2B maps one Binding and its
|
||||
Workspace to one E2B resource, while Local can attach multiple materialized
|
||||
Homes to one shared Workspace.
|
||||
|
||||
## Runtime modules
|
||||
|
||||
Agent requests do not expose separate Home, Workspace, or Sandbox layers. Dify
|
||||
API resolves the Binding selected by the product flow and sends its opaque
|
||||
backend ref to the `runtime` module:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
EC["dify.execution_context<br/>request identity"]
|
||||
RT["dify.runtime<br/>opaque backend_binding_ref"]
|
||||
SH["dify.shell<br/>commands and jobs"]
|
||||
|
||||
EC --> SH
|
||||
RT --> SH
|
||||
```
|
||||
|
||||
`runtime.Capability` calls the selected `ExecutionBindingBackend.acquire()` when
|
||||
its native `wrap_run` scope opens and `release()` when the operation ends. It exposes
|
||||
the resulting `RuntimeLease` only while that context is active. The module does
|
||||
not create, retire, or destroy persistent resources, and it stores no backend
|
||||
SDK object in an module session snapshot.
|
||||
|
||||
The Shell module consumes `RuntimeLease.commands` and `RuntimeLease.layout`. It
|
||||
tracks only request-local shell job ids and offsets.
|
||||
Closing a run clears that job state; it does not retire the Binding.
|
||||
|
||||
## State ownership
|
||||
|
||||
Dify API is the lifecycle ledger. It stores three resource records:
|
||||
|
||||
| Record | Meaning | Backend field |
|
||||
| --- | --- | --- |
|
||||
| `agent_home_snapshots` | One immutable Home version owned by an Agent. | `snapshot_ref` |
|
||||
| `agent_workspaces` | One mutable Workspace owned by a product scope. | `backend_workspace_ref` |
|
||||
| `agent_workspace_bindings` | One materialized participant, private Home, and resumable session attached to a Workspace. | `backend_binding_ref` |
|
||||
|
||||
Backend refs are opaque strings interpreted only by the selected backend
|
||||
adapter. Dify API stores the latest module session snapshot on the Binding, but
|
||||
it does not serialize `RuntimeLease`, SDK clients, credentials, or temporary
|
||||
access tokens.
|
||||
|
||||
Dify Agent does not connect to the Dify product database and has no persistent
|
||||
resource registry. Its private control-plane endpoints create or destroy
|
||||
backend resources from requests made by Dify API. Redis run records and event
|
||||
streams are observability state, not the Home/Workspace/Binding ledger.
|
||||
|
||||
When `DIFY_AGENT_API_TOKEN` is configured, every private control-plane request must carry the matching Dify API `AGENT_BACKEND_API_TOKEN` as a Bearer token.
|
||||
|
||||
## Creation and execution flow
|
||||
|
||||
Agent creation does not create a Home Snapshot. A config with no logical Home
|
||||
Snapshot asks the selected backend to materialize its deployment-default Home
|
||||
when the Binding is created. This default Home is mutable and private to the
|
||||
Binding; it does not produce an `agent_home_snapshots` row or an implicit
|
||||
snapshot ref.
|
||||
|
||||
Build Draft Apply uses `POST /home-snapshots/from-binding`: Dify Agent acquires
|
||||
the exact source Binding, snapshots its materialized Home through the
|
||||
backend-native operation, releases the lease, and returns a new opaque snapshot
|
||||
ref. Dify API then stores a new immutable `agent_home_snapshots` row and records
|
||||
its logical id on the resulting config version. There is no replay or fallback
|
||||
when the source Binding is unavailable.
|
||||
|
||||
Before an Agent request, Dify API loads the specific product context. If it has
|
||||
no associated Binding, Dify API materializes one and saves the Binding id in the
|
||||
same database transaction. Otherwise it resolves only that Binding and validates
|
||||
its owner and config/Home generation. Missing, retired, or mismatched Bindings
|
||||
fail fast; Dify API does not search by Agent, Workspace, candidate count, or
|
||||
recency, and it does not create a replacement implicitly.
|
||||
|
||||
`POST /execution-bindings` accepts either an exact `home_snapshot_ref` or
|
||||
`null`. An exact ref must be materialized without fallback; `null` selects the
|
||||
backend's deployment-default Home. It returns opaque Binding and Workspace
|
||||
refs. Every create request represents a new participant, even when the Agent,
|
||||
Snapshot, config generation, and Workspace match another Binding. The request
|
||||
composition contains:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "runtime",
|
||||
"config": {"backend_binding_ref": "opaque-backend-binding-ref"}
|
||||
}
|
||||
```
|
||||
|
||||
Each Agent request acquires that ref for the duration of the run and releases it
|
||||
afterward. Local release closes the operation's shellctl connection. E2B release
|
||||
also pauses the underlying E2B resource with memory preserved. A later request
|
||||
or Binding file operation acquires a new lease for the same Binding ref. If a
|
||||
backend confirms the resource is gone, acquisition fails; it does not create an
|
||||
empty replacement Workspace.
|
||||
|
||||
## Retirement and collection
|
||||
|
||||
Retirement is a database transition from `ACTIVE` to `RETIRED`. It prevents new
|
||||
product use without performing network I/O inside the caller's transaction.
|
||||
Product lifecycle paths commit this transition synchronously. After the
|
||||
transaction commits, one Celery task asks Dify Agent to destroy the physical
|
||||
resources. A successful collector deletes the corresponding ledger row. If a
|
||||
collector raises, the task logs the tenant, resource type, and resource ID and
|
||||
continues with the other independent resources in the batch. After all resources
|
||||
have been attempted, any failure makes the Celery task fail and prevents Agent
|
||||
aggregate deletion. Failed RETIRED rows remain available for a later retry. A
|
||||
failure to publish the Celery task is also propagated to the product caller. No
|
||||
automatic retry or reconciliation is performed.
|
||||
|
||||
The unified `collect_agent_resources` task is registered on normal Celery
|
||||
workers and explicitly uses the existing `retention` queue. Standard workers
|
||||
already consume that queue, so no dedicated Agent resource worker or new queue
|
||||
is required. At a Workflow terminal event, the graph layer synchronously retires
|
||||
and commits the run's Workspaces before enqueueing collection. When a Workflow
|
||||
change may orphan Workflow-only Agents, the main product transaction commits
|
||||
first; a fresh session then rechecks effective ownership and retires only Agents
|
||||
that remain unowned. An effective reference is a binding in a normal App's
|
||||
current draft or current published Workflow. This ownership check applies only
|
||||
to implicit retirement of Workflow-only Agents. Explicit deletion of a roster
|
||||
Agent or Agent App proceeds even while Workflows reference it.
|
||||
|
||||
Retiring a final Binding also retires its Workspace. Workspace collection
|
||||
destroys the physical Workspace through one Binding and then collects remaining
|
||||
materialized Homes. Home Snapshots are retired when their owning Agent is
|
||||
retired. `RETIRED` is the sole physical-deletion condition for a Home Snapshot;
|
||||
Draft and Config Snapshot references are historical pointers and do not keep it
|
||||
alive. After every external resource in a deletion batch succeeds, Dify API
|
||||
hard-deletes the archived Agent together with its Drafts, Config Snapshots,
|
||||
Config Revisions, debug-conversation mappings, and resource ledgers in one
|
||||
database transaction. Workflow Agent bindings belong to
|
||||
their Workflows and remain unchanged, so they may hold a dangling Agent ID after
|
||||
explicit deletion. Dify Agent itself remains stateless.
|
||||
|
||||
A `RETIRED` Workspace without a `RETIRED` Binding cannot identify a backend
|
||||
participant through which to destroy the Workspace. That state is a lifecycle
|
||||
invariant violation and fails collection instead of being logged as success.
|
||||
|
||||
There is currently no age-based TTL, periodic GC, or global orphan reconciler.
|
||||
Backend destroy operations are idempotent where supported. Dify API does not
|
||||
perform cross-system compensation after a backend create returns success. Any
|
||||
later API failure, including Python, flush, or commit failure, may leave a
|
||||
physical orphan for a future global reconciler.
|
||||
|
||||
Backends still clean up partial resources when a create operation fails before
|
||||
returning success. For example, E2B kills a Sandbox when its initialization
|
||||
fails, and Local removes paths created by an incomplete operation. This
|
||||
backend-local cleanup does not cross the database commit boundary.
|
||||
|
||||
## Binding file boundary
|
||||
|
||||
Dify API's public file APIs accept a product locator, not a Binding id or
|
||||
backend ref: a Conversation, a debug Build Draft, or a Workflow Node Execution.
|
||||
Dify API authorizes that object and resolves its associated active Binding. It
|
||||
does not select the latest Binding or fall back to another product context.
|
||||
|
||||
The resolved request reaches Dify Agent through its private
|
||||
`POST /execution-bindings/files/list`, `POST /execution-bindings/files/read`,
|
||||
and `POST /execution-bindings/files/download` endpoints. Each operation receives a
|
||||
`backend_binding_ref`, acquires a fresh RuntimeLease, performs the file action,
|
||||
and releases the lease.
|
||||
|
||||
`BindingFileService` resolves relative paths from `workspace_dir`, `~` and
|
||||
`~/...` from `home_dir`, and leaves absolute paths in the Binding filesystem
|
||||
namespace. It does not enforce Workspace containment or reject `..`; the
|
||||
selected backend's isolation policy remains authoritative. List and preview
|
||||
run bounded inspection scripts through `RuntimeLease.commands`. Download runs
|
||||
`dify-agent file upload --no-download-link` inside the Binding so bytes stream
|
||||
directly from the runtime to Dify's existing ToolFile endpoint. Dify Agent
|
||||
returns only the canonical ToolFile reference and releases the lease before
|
||||
Dify API signs a browser URL.
|
||||
|
||||
The default Binding-download deadline chain leaves each caller time to receive
|
||||
and normalize the lower layer's result: the sandbox CLI upload is 180 seconds,
|
||||
`DIFY_AGENT_BINDING_FILE_DOWNLOAD_COMMAND_TIMEOUT_SECONDS` is 210 seconds,
|
||||
Dify API's `AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS` is 240 seconds,
|
||||
and `DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS` is 3600 seconds.
|
||||
|
||||
`RuntimeLayout.home_dir` and `RuntimeLayout.workspace_dir` are canonical paths
|
||||
inside the backend execution namespace. They are not host paths, product ids,
|
||||
or request configuration. Shell commands start in `workspace_dir`, and `HOME`
|
||||
is forced to `home_dir`. The standard temp variables `TMPDIR`, `TMP`, and `TEMP`
|
||||
also point directly to `workspace_dir`, so the Workspace is both the command
|
||||
`cwd` and temp space. On Local, sibling materialized Homes may exist in the same
|
||||
shellctl namespace, while path isolation restricts the active lease to its own
|
||||
Home plus the shared Workspace.
|
||||
|
||||
## Backend support
|
||||
|
||||
| Backend | Home Snapshot operations | Binding operations | Physical relationship |
|
||||
| --- | --- | --- | --- |
|
||||
| Local | Supported | Supported, including default empty Homes and attaching multiple Bindings to one Workspace | Snapshot directory, per-Binding materialized Home, and Workspace directory are separate. |
|
||||
| E2B | Supported | Supported with template-backed default Homes, without shared-Workspace attachment | Binding and Workspace refs map to the same E2B resource; checkpoints use E2B snapshots. |
|
||||
| Enterprise | Not implemented | Default-Home Binding creation, acquire, and coupled destroy are supported | Binding and Workspace refs map to one Gateway sandbox. Explicit Home Snapshot materialization fails fast. |
|
||||
| OpenShell | Supported via directory copies on an operator-provided shared volume | Supported with image-backed default Homes, without shared-Workspace attachment | Binding and Workspace refs map to the same OpenShell sandbox, addressed by its stable name; snapshots live under `home-snapshots/<tenant-digest>/` on the shared volume. Production deployments must use one workspace and one dedicated volume per tenant. |
|
||||
|
||||
Local creates a new Home for every Binding id. Destroying one Binding without
|
||||
the Workspace leaves sibling Homes and the shared Workspace intact. Current E2B
|
||||
rejects `existing_workspace_ref` with `shared_workspace_unsupported`, because
|
||||
its Binding and Workspace are one Sandbox. It also rejects binding-only destroy.
|
||||
OpenShell shares the E2B shape: one sandbox per Binding, no
|
||||
`existing_workspace_ref`, no binding-only destroy. Neither path creates a
|
||||
fallback Workspace or switches backends.
|
||||
|
||||
`DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS` limits continuous active time for an E2B
|
||||
resource to one hour. The limit covers the complete Agent run held by one
|
||||
RuntimeLease rather than an individual tool call. Its 3600-second default is
|
||||
intentionally the same as `DIFY_AGENT_RUN_TIMEOUT_SECONDS`, but the two settings
|
||||
remain independently configurable. Runtime resources pause on timeout, but this
|
||||
resource setting does not own the Agent run terminal state. It is not a retention
|
||||
TTL and does not delete paused resources or immutable snapshots.
|
||||
|
||||
See the [Shell module](../../user-manual/shell-layer/index.md) for request
|
||||
composition, the [Operations Guide](../../guide/index.md) for Local and E2B
|
||||
validation, and the [OpenShell guide](../../guide/openshell.md) for OpenShell
|
||||
configuration and validation.
|
||||
@@ -0,0 +1,25 @@
|
||||
# Dify Agent examples
|
||||
|
||||
These examples live under `examples/dify_agent/dify_agent_examples`. They use
|
||||
registered modules and depend on the Agent server, Redis, Dify API, and plugin
|
||||
daemon settings described in the operations guide.
|
||||
|
||||
## Run a Dify plugin-daemon backed model
|
||||
|
||||
```snippet {path="/examples/dify_agent/dify_agent_examples/run_pydantic_ai_agent.py"}
|
||||
```
|
||||
|
||||
## Poll run events
|
||||
|
||||
```snippet {path="/examples/dify_agent/dify_agent_examples/run_server_consumer.py"}
|
||||
```
|
||||
|
||||
## Use the synchronous client
|
||||
|
||||
```snippet {path="/examples/dify_agent/dify_agent_examples/run_server_sync_client.py"}
|
||||
```
|
||||
|
||||
## Stream run events with SSE
|
||||
|
||||
```snippet {path="/examples/dify_agent/dify_agent_examples/run_server_sse_consumer.py"}
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
# Get started
|
||||
|
||||
Create a run with `POST /runs`; poll `/runs/{run_id}` or consume its event stream.
|
||||
The composition schema version is 2. Each entry contains a registered `name` and
|
||||
current JSON `config`. Module identity comes from the server registry; there are
|
||||
no graph type/dependency fields or generic per-module exit policy.
|
||||
|
||||
```json
|
||||
{
|
||||
"composition": {
|
||||
"schema_version": 2,
|
||||
"layers": [
|
||||
{"name": "execution_context", "config": {"tenant_id": "tenant", "agent_mode": "agent_app", "invoke_from": "service-api"}},
|
||||
{"name": "prompt", "config": {"prefix": "Be helpful", "user": "Hello"}},
|
||||
{"name": "history", "config": {}},
|
||||
{"name": "llm", "config": {"execution_context": "execution_context", "plugin_id": "langgenius/openai", "model_provider": "openai", "model": "gpt-4o-mini"}}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Resume by including the previous terminal `session_snapshot` and submitting the
|
||||
current composition. `llm` is required, `history` and `output` are optional.
|
||||
Resource cleanup always happens at exit. Cancellation is a separate operation;
|
||||
its terminal event is published only after the owner run has cleaned up.
|
||||
@@ -0,0 +1,671 @@
|
||||
# Operating the Dify Agent Run Server
|
||||
|
||||
This guide describes how to run the MVP Dify Agent API server. The server is
|
||||
implemented in `dify-agent/src/dify_agent/server/app.py` and uses Redis for run
|
||||
records and per-run event streams. Optional E2B usage collection is triggered by
|
||||
the API's existing Celery Beat schedule through a separate one-shot endpoint.
|
||||
It adds no operation logging, polling loop, leader election or accounting context
|
||||
to business runtime execution.
|
||||
|
||||
## Default local startup
|
||||
|
||||
Start Redis, then run one FastAPI/uvicorn process:
|
||||
|
||||
```bash
|
||||
uv run --project dify-agent uvicorn dify_agent.server.app:app --reload
|
||||
```
|
||||
|
||||
By default, the FastAPI lifespan creates:
|
||||
|
||||
- one Redis-backed run store used by HTTP routes
|
||||
- shared plugin-daemon and Dify API inner `httpx.AsyncClient` instances
|
||||
- one deployment-selected, stateless runtime backend profile when configured
|
||||
- one process-local scheduler that starts background `asyncio` run tasks
|
||||
|
||||
This means local development needs one uvicorn process plus Redis, and
|
||||
plugin-backed runs also need a reachable Dify plugin daemon. Run execution still
|
||||
happens outside request handlers, so client disconnects do not cancel the agent
|
||||
run.
|
||||
|
||||
## Configuration
|
||||
|
||||
`ServerSettings` loads environment variables with the `DIFY_AGENT_` prefix. It
|
||||
also reads `.env` and `dify-agent/.env` when present.
|
||||
|
||||
OpenShell-specific settings are listed in the
|
||||
[OpenShell configuration reference](openshell.md#configuration).
|
||||
|
||||
Independent E2B execution accounting, activation and rollout checks are described
|
||||
in [E2B runtime metering](runtime-metering.md).
|
||||
|
||||
| Environment variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `DIFY_AGENT_REDIS_URL` | `redis://localhost:6379/0` | Redis connection URL. |
|
||||
| `DIFY_AGENT_REDIS_PREFIX` | `dify-agent` | Prefix for Redis record and event keys. |
|
||||
| `DIFY_AGENT_SHUTDOWN_GRACE_SECONDS` | `30` | Seconds to wait for active local runs during graceful shutdown before cancellation. |
|
||||
| `DIFY_AGENT_RUN_RETENTION_SECONDS` | `7200` | Seconds to retain Redis run records and per-run event streams after their last write; defaults to 2 hours. |
|
||||
| `DIFY_AGENT_RUN_EVENT_STREAM_MAX_LENGTH` | `5000` | Approximate target maximum for replayable events retained in each per-run Redis Stream. |
|
||||
| `DIFY_AGENT_STREAM_TEXT_DELTA_COALESCING_ENABLED` | `true` | Set `false` to publish each text delta without coalescing. |
|
||||
| `DIFY_AGENT_STREAM_TEXT_DELTA_FLUSH_INTERVAL_MS` | `100` | Soft debounce interval for compatible text deltas. Already-ready source events may continue to merge after this interval; a waiting source triggers the timed flush. Must be greater than zero; use `DIFY_AGENT_STREAM_TEXT_DELTA_COALESCING_ENABLED=false` to disable coalescing. |
|
||||
| `DIFY_AGENT_STREAM_TEXT_DELTA_MAX_CHARS` | `4096` | Character threshold that flushes a buffered text-delta event immediately. |
|
||||
| `DIFY_AGENT_RUN_TIMEOUT_SECONDS` | `3600` | Wall-clock deadline in seconds for the Pydantic AI `agent.run(...)` model/tool loop. Deadline failures use `agent_run_limit_exceeded`. Its default intentionally matches `DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS`, but the settings are independently configurable. |
|
||||
| `DIFY_AGENT_BINDING_FILE_DOWNLOAD_COMMAND_TIMEOUT_SECONDS` | `210` | Shell command deadline for running the sandbox `dify-agent file upload --no-download-link` conversion. Keep it above the CLI's 180-second upload deadline. |
|
||||
| `DIFY_AGENT_API_TOKEN` | empty | Optional Bearer token required by private run, Execution Binding, Home Snapshot, and Binding file control-plane routes. Must match Dify API `AGENT_BACKEND_API_TOKEN`. |
|
||||
| `DIFY_AGENT_PLUGIN_DAEMON_URL` | `http://localhost:5002` | Base URL for the Dify plugin daemon. |
|
||||
| `DIFY_AGENT_PLUGIN_DAEMON_API_KEY` | empty | API key sent to the Dify plugin daemon. |
|
||||
| `DIFY_AGENT_INNER_API_URL` | `http://localhost:5001` | Dify API service root used when dify-agent calls `/inner/api/...` endpoints. |
|
||||
| `DIFY_AGENT_INNER_API_KEY` | empty | API key sent to Dify API inner plugin endpoints. Set this to Dify API `INNER_API_KEY_FOR_PLUGIN` (Docker: `PLUGIN_DIFY_INNER_API_KEY`). |
|
||||
| `DIFY_AGENT_RUNTIME_BACKEND` | `local` | Selects one coherent `local`, `enterprise`, `e2b`, or `openshell` Home Snapshot + Execution Binding backend profile. |
|
||||
| `DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT` | empty | Local shellctl data-plane URL. With the default Local selection, leaving it empty disables `dify.runtime` and resource endpoints. |
|
||||
| `DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN` | empty | Required nonblank bearer token when the Local endpoint is configured; must match shellctl's `SHELLCTL_AUTH_TOKEN`. |
|
||||
| `DIFY_AGENT_LOCAL_SANDBOX_MATERIALIZED_HOME_ROOT` | `/home/dify` | Root directory, on the Local shellctl filesystem, for per-Binding materialized Homes. |
|
||||
| `DIFY_AGENT_LOCAL_SANDBOX_WORKSPACE_ROOT` | `/workspace` | Root directory, on the Local shellctl filesystem, for mutable Workspaces. |
|
||||
| `DIFY_AGENT_LOCAL_SANDBOX_HOME_SNAPSHOT_ROOT` | `/home/dify/.snapshots` | Root directory, on the Local shellctl filesystem, for immutable Home Snapshots. |
|
||||
| `DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_ENDPOINT` | empty | Enterprise Gateway endpoint required by configuration. Default-Home Bindings are supported; immutable Home Snapshot operations remain unsupported. |
|
||||
| `DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_AUTH_TOKEN` | empty | Optional `X-Inner-Api-Key` sent to the Enterprise Gateway. |
|
||||
| `DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_TIMEOUT` | `30` | Enterprise control-plane timeout in seconds. |
|
||||
| `DIFY_AGENT_ENTERPRISE_SANDBOX_PROXY_TIMEOUT` | `60` | Enterprise shellctl-proxy timeout in seconds. |
|
||||
| `DIFY_AGENT_E2B_API_KEY` | empty | E2B API key; required for E2B. |
|
||||
| `DIFY_AGENT_E2B_TEMPLATE` | `difys-default-team/dify-agent-local-sandbox` | Prepared E2B template containing shellctl and the deployment-default Home environment. |
|
||||
| `DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS` | `3600` | Maximum continuous active time for the RuntimeLease spanning one complete Agent run. Its default intentionally matches `DIFY_AGENT_RUN_TIMEOUT_SECONDS`, but the settings are independently configurable. Binding resources pause on timeout; this setting does not own the run terminal state and is not a retention TTL. |
|
||||
| `DIFY_AGENT_E2B_SHELLCTL_PORT` | `5004` | shellctl port exposed by the E2B template. |
|
||||
| `DIFY_AGENT_SHELL_REDACT_PATTERNS` | empty | JSON array of additional regex patterns redacted from Shell output. |
|
||||
| `DIFY_AGENT_STUB_API_BASE_URL` | empty | HTTP(S) Agent Stub API base URL reachable from the Sandbox. It may be the service root or `/agent-stub`. Enables `DIFY_AGENT_STUB_*` env injection for user `shell.run` jobs. |
|
||||
| `DIFY_AGENT_SANDBOX_FILES_BASE_URL` | empty | Dify API base URL reachable from the Sandbox for signed `/files/*` upload/download bytes, including Config file and skill pulls. Required when Agent Stub file operations are enabled. May include an ingress path prefix, but not a query or fragment. |
|
||||
| `DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT` | `50` | Agent service-owned maximum Agent Stub upload size in MiB. The file-request handler factory converts it to bytes and sends it to Dify API as the required `max_size` used to sign a size-limited upload URL. |
|
||||
| `DIFY_AGENT_SERVER_SECRET_KEY` | empty | Security-sensitive server-wide root secret used to derive the JWE encryption key for Agent Stub bearer tokens; required when `DIFY_AGENT_STUB_API_BASE_URL` is set. The supplied default config uses a development value; set a unique unpadded base64url 32-byte secret in production. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_CONNECT_TIMEOUT` | `10` | Shared outbound HTTP connect timeout in seconds. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_READ_TIMEOUT` | `600` | Shared outbound HTTP read timeout in seconds. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_WRITE_TIMEOUT` | `30` | Shared outbound HTTP write timeout in seconds. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_POOL_TIMEOUT` | `10` | Shared outbound connection-pool wait timeout in seconds. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_MAX_CONNECTIONS` | `100` | Maximum total shared outbound HTTP connections. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_MAX_KEEPALIVE_CONNECTIONS` | `20` | Maximum idle shared outbound HTTP connections. |
|
||||
| `DIFY_AGENT_OUTBOUND_HTTP_KEEPALIVE_EXPIRY` | `30` | Idle keep-alive expiry in seconds. |
|
||||
| `DIFY_AGENT_TRAJECTORY_ENABLED` | `false` | Opt-in switch for the separate Agent trajectory export pipeline. |
|
||||
| `DIFY_AGENT_APPLICATION_TRACING_ENABLED` | `false` | Collect API-authorized application spans into the Dify inner API tracing inbox. Requires the server inner API URL and key. |
|
||||
| `DIFY_AGENT_TRAJECTORY_OTLP_TRACES_ENDPOINT` | empty | Full HTTP(S) OTLP traces endpoint required when trajectory export is enabled. |
|
||||
| `DIFY_AGENT_TRAJECTORY_OTLP_HEADERS` | `{}` | JSON object of request headers sent with Agent OTLP trace exports. |
|
||||
| `DIFY_AGENT_TRAJECTORY_SERVICE_NAME` | `dify-agent-trajectory` | Resource service name attached to Agent trajectory spans. |
|
||||
| `DIFY_AGENT_TRAJECTORY_INCLUDE_CONTENT` | `false` | Include message and tool content in Agent trajectory spans. |
|
||||
| `DIFY_AGENT_TRAJECTORY_TRACE_CONTEXT_MODE` | `isolated` | `isolated` starts independent platform/Agent traces; `shared` preserves cross-instance parent context. Requires process restart to change. |
|
||||
| `DIFY_AGENT_TRAJECTORY_MAX_QUEUE_SIZE` | `2048` | Maximum number of spans queued for Agent trace export; must be positive. |
|
||||
| `DIFY_AGENT_TRAJECTORY_MAX_EXPORT_BATCH_SIZE` | `512` | Maximum spans per export batch; must be positive and no greater than the queue size. |
|
||||
| `DIFY_AGENT_TRAJECTORY_SCHEDULE_DELAY_MS` | `5000` | Delay between scheduled Agent span exports, in milliseconds; must be positive. |
|
||||
| `DIFY_AGENT_TRAJECTORY_EXPORT_TIMEOUT_MS` | `5000` | Batch processor export timeout setting, in milliseconds; must be positive. Does not change the OTLP HTTP exporter request timeout. |
|
||||
|
||||
Platform observability uses the process-level Logfire instance and standard
|
||||
`OTEL_*` / `LOGFIRE_*` configuration. Agent observability uses a separate local
|
||||
Logfire instance and is disabled by default. Set `DIFY_AGENT_TRAJECTORY_ENABLED=true`
|
||||
and a full `DIFY_AGENT_TRAJECTORY_OTLP_TRACES_ENDPOINT` to opt in;
|
||||
`DIFY_AGENT_TRAJECTORY_OTLP_HEADERS` is a JSON object of request headers. Agent
|
||||
traces do not inherit platform endpoints, credentials, sampling, or console
|
||||
export. Message/tool content requires the separate
|
||||
`DIFY_AGENT_TRAJECTORY_INCLUDE_CONTENT` opt-in. Platform FastAPI parameter/error
|
||||
payloads, HTTPX bodies/headers and Redis statements are not captured by these
|
||||
instrumentations. The Agent instance is created at service startup and shut down
|
||||
after active runs finish. These are deployment-level settings, not yet
|
||||
per-tenant authorization or routing; a shared backend does not provide storage
|
||||
isolation.
|
||||
|
||||
With `DIFY_AGENT_TRAJECTORY_TRACE_CONTEXT_MODE=isolated` (the default), Agent
|
||||
run spans start independent traces instead of inheriting platform request
|
||||
parents. Platform HTTPX/Redis instrumentation also detaches local Agent
|
||||
parents while preserving platform-only and incoming distributed trace
|
||||
relationships. In `shared` mode both pipelines retain cross-instance parent
|
||||
context and the Agent sampler respects the parent sampling decision. Use
|
||||
`shared` only when both pipelines export to the same queryable backend space;
|
||||
otherwise missing-root spans can recur. Service names do not select the mode.
|
||||
The two SDK instances, exporters, enable switch, and content opt-in remain
|
||||
separate. The mode is fixed at process initialization and requires a restart
|
||||
to change. No extra shared root span is added; incomplete traces may still
|
||||
appear temporarily while a run or export is in progress.
|
||||
|
||||
Application tracing is a third, independent pipeline. When enabled, a run's
|
||||
API-issued `execution_context.tracing` supplies its durable run/invocation IDs,
|
||||
OpenTelemetry parent, session and content/sampling policy. Its spans are sent as
|
||||
JSON to `POST /inner/api/agent/tracing/batches`, authenticated with the server's
|
||||
`DIFY_AGENT_INNER_API_KEY` in `X-Inner-Api-Key`. Provider credentials and routing
|
||||
remain in the Dify API. Application spans do not inherit platform or deployment
|
||||
trajectory destinations, and one Agent is never instrumented by both application
|
||||
and deployment pipelines. Binary content is excluded.
|
||||
|
||||
The actual model-call span also carries the Dify gateway's billed amount as
|
||||
`dify.llm.total_price` (a decimal string) and `dify.llm.currency` when a usage
|
||||
payload is returned. `gen_ai.response.time_to_first_token` is measured in seconds
|
||||
(`dify.llm.time_to_first_token_unit=s`): gateway-provided TTFT takes precedence;
|
||||
otherwise it measures request issue to the first content/tool-call chunk.
|
||||
`dify.llm.time_to_first_token_source` distinguishes those two sources. Missing
|
||||
accounting is left absent. The current Graphon LLM gateway does not expose cache
|
||||
token counters, so the Agent adapter does not manufacture them.
|
||||
|
||||
Each batch has a stable `batch_id`. Retries reuse the same payload, and a 2xx
|
||||
response is accepted only with `{result: "success", batch_id, accepted_spans}`
|
||||
matching that batch. An invocation emits an empty `final: true` batch after its
|
||||
ended spans are flushed and acknowledged, before its normal terminal event when
|
||||
delivery completes within five seconds. Failure or cancellation still flushes.
|
||||
Collection failures do not fail the Agent run; outstanding delivery can finish
|
||||
in the background after the terminal-event deadline. A full in-memory queue or
|
||||
unacknowledged data suppresses completion instead of claiming a complete trace.
|
||||
The queue is bounded (2048 spans, batches of at most 128), with up to 128 unacknowledged
|
||||
batches retained until invocation finalization. Batches are split below 1 MiB
|
||||
of UTF-8 JSON. A single oversized span is dropped and marks its invocation
|
||||
incomplete rather than silently truncating content or sending a success marker.
|
||||
This is not a durable local
|
||||
spool: process loss can leave an incomplete trace in the API. Shutdown drains the
|
||||
collector after active runs finish.
|
||||
|
||||
If setup fails or cancellation arrives before Pydantic AI starts its Agent span,
|
||||
the collector emits one failed `invoke_agent` span with the measured setup
|
||||
interval, then finalizes normally. It records `dify.agent.execution_state` as
|
||||
`initialization_failed` or `cancelled`. Runs that already started their native
|
||||
Agent span keep that span without an extra wrapper. Sampling-off invocations
|
||||
remain span-free; successful but unexplained empty collections are not converted
|
||||
to synthetic success.
|
||||
|
||||
Example `.env`:
|
||||
|
||||
```env
|
||||
DIFY_AGENT_REDIS_URL=redis://localhost:6379/0
|
||||
DIFY_AGENT_REDIS_PREFIX=dify-agent-dev
|
||||
DIFY_AGENT_SHUTDOWN_GRACE_SECONDS=30
|
||||
DIFY_AGENT_RUN_RETENTION_SECONDS=7200
|
||||
DIFY_AGENT_RUN_EVENT_STREAM_MAX_LENGTH=5000
|
||||
DIFY_AGENT_STREAM_TEXT_DELTA_FLUSH_INTERVAL_MS=100
|
||||
DIFY_AGENT_STREAM_TEXT_DELTA_MAX_CHARS=4096
|
||||
DIFY_AGENT_RUN_TIMEOUT_SECONDS=3600
|
||||
DIFY_AGENT_API_TOKEN=replace-with-agent-backend-token
|
||||
DIFY_AGENT_PLUGIN_DAEMON_URL=http://localhost:5002
|
||||
DIFY_AGENT_PLUGIN_DAEMON_API_KEY=replace-with-daemon-key
|
||||
DIFY_AGENT_INNER_API_URL=http://localhost:5001
|
||||
DIFY_AGENT_INNER_API_KEY=replace-with-dify-inner-api-key-for-plugin
|
||||
DIFY_AGENT_RUNTIME_BACKEND=local
|
||||
DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT=http://127.0.0.1:5004
|
||||
DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN=replace-with-shellctl-token
|
||||
# Set these when shellctl runs directly on a host that does not have /home/dify.
|
||||
DIFY_AGENT_LOCAL_SANDBOX_MATERIALIZED_HOME_ROOT=/tmp/dify-agent/materialized-homes
|
||||
DIFY_AGENT_LOCAL_SANDBOX_WORKSPACE_ROOT=/tmp/dify-agent/workspaces
|
||||
DIFY_AGENT_LOCAL_SANDBOX_HOME_SNAPSHOT_ROOT=/tmp/dify-agent/home-snapshots
|
||||
DIFY_AGENT_STUB_API_BASE_URL=https://agent.example.com/agent-stub
|
||||
DIFY_AGENT_SANDBOX_FILES_BASE_URL=https://dify.example.com
|
||||
DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT=50
|
||||
# This is security-sensitive: it derives the JWE encryption key for Agent Stub bearer tokens.
|
||||
# Replace this development default in production.
|
||||
# Generate one with: python -c 'import secrets; print(secrets.token_urlsafe(32))'
|
||||
DIFY_AGENT_SERVER_SECRET_KEY=MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY
|
||||
```
|
||||
|
||||
The two Sandbox-facing base URLs have different owners. Agent Stub control
|
||||
requests use `DIFY_AGENT_STUB_API_BASE_URL`; signed file bytes use
|
||||
`DIFY_AGENT_SANDBOX_FILES_BASE_URL`. `DIFY_AGENT_INNER_API_URL` remains a
|
||||
trusted service-to-service URL and is never returned to the Sandbox.
|
||||
|
||||
Config file and skill pulls use the same split: Agent Stub authorizes the
|
||||
Config target and returns a short-lived URL, then the Sandbox fetches the bytes
|
||||
directly from the Dify API `/files/*` data plane.
|
||||
|
||||
Removing Agent Stub gRPC is a breaking transport migration: replace every
|
||||
`grpc://` Agent Stub URL with HTTP(S), remove
|
||||
`DIFY_AGENT_STUB_GRPC_BIND_ADDRESS`, and deploy without a gRPC fallback.
|
||||
|
||||
For a remote Sandbox, expose only `/agent-stub/*` from Agent Backend and the
|
||||
existing `/files/*` Dify API data plane. The `/files/*` ingress must preserve
|
||||
the complete signed query string and set its request-body limit above the
|
||||
configured file-size limit to leave room for multipart framing and headers; the
|
||||
two limits need not be numerically equal. Use response streaming and timeouts
|
||||
suitable for large downloads. Do not expose Agent Backend `/runs`, Workspace,
|
||||
or Binding management routes through the Sandbox ingress.
|
||||
|
||||
Browser presentation URLs are independent. Configure Dify API `FILES_URL` to a
|
||||
browser-reachable public origin, or leave it empty so responses use same-origin
|
||||
relative `/files/...` URIs. Never set `FILES_URL` to a Docker-only service name
|
||||
such as `http://api:5001`.
|
||||
|
||||
`DIFY_AGENT_SHELLCTL_ENTRYPOINT` and `DIFY_AGENT_SHELLCTL_AUTH_TOKEN` remain
|
||||
accepted only as legacy aliases for the two Local settings. New deployments
|
||||
must use `DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT` and
|
||||
`DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN`. There is no compatibility setting for
|
||||
the removed shell-provider selector.
|
||||
|
||||
Local shellctl deployments must start with `shellctl serve --require-auth-token`
|
||||
and set `SHELLCTL_AUTH_TOKEN` to the same secret as the Agent Backend. Compose's
|
||||
`local_sandbox` command enables this check; missing, empty, or whitespace-only
|
||||
tokens fail before service initialization. E2B and Enterprise retain their
|
||||
existing token requirements, and an unset Local endpoint still disables runtime.
|
||||
|
||||
For Compose, set `DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN` in a shared interpolation
|
||||
source: the invoking shell, `docker/.env`, or a Compose `--env-file`. This supplies
|
||||
the same secret to Agent Backend and shellctl. Setting it only in a service env
|
||||
file is insufficient: Compose's explicit `environment` values override that
|
||||
file, including with an empty interpolated value. The legacy token alias remains
|
||||
accepted. Deploy this change with a rebuilt runtime image containing
|
||||
`--require-auth-token`; the previously published `1.17.1` image does not support
|
||||
the new flag.
|
||||
|
||||
When shellctl path isolation is enabled, any Landlock setup error aborts the job
|
||||
with exit code `125` before its user script executes. Deployments may explicitly
|
||||
set `SHELLCTL_ENABLE_PATH_ISOLATION=false` to disable shellctl path isolation.
|
||||
|
||||
The backend selection is deployment-private. Shell-enabled run requests use an
|
||||
Execution Context, `dify.runtime`, and `dify.shell` graph. Runtime config carries
|
||||
only the opaque `backend_binding_ref` resolved by Dify API. See
|
||||
[Runtime resources](../concepts/runtime-resources/index.md) for the ownership
|
||||
and lifecycle contract.
|
||||
|
||||
Run records and event streams use the same retention. Status writes refresh the
|
||||
record TTL, and event writes refresh both the stream TTL and the corresponding
|
||||
record TTL so active runs that keep producing events remain observable. Text
|
||||
deltas for the same response part and provider metadata are coalesced within a
|
||||
soft debounce/size window before being published. The debounce timer flushes
|
||||
when reading the next source event would block; already-ready events may keep
|
||||
merging until the character threshold or a non-compatible event is reached.
|
||||
Every Redis Stream write also applies the configured approximate maximum length. A reconnect cursor older than the
|
||||
retained window resumes from the oldest remaining event, so callers must treat
|
||||
the terminal snapshot and application-owned history as authoritative rather
|
||||
than relying on the Agent event stream as long-term history.
|
||||
|
||||
## Validate the E2B Compose deployment
|
||||
|
||||
The E2B overlay requires a prepared template that starts shellctl on port 5004.
|
||||
The default is `difys-default-team/dify-agent-local-sandbox`. It also requires
|
||||
an E2B API key in `DIFY_AGENT_E2B_API_KEY`; the Compose interpolation accepts
|
||||
`E2B_API_KEY` and `E2B_API_TOKEN` only as deployment-level fallbacks.
|
||||
|
||||
From the repository root, keep the normal `docker/.env` unchanged and export the
|
||||
secret for this shell:
|
||||
|
||||
```bash
|
||||
export DIFY_AGENT_E2B_API_KEY="${DIFY_AGENT_E2B_API_KEY:-${E2B_API_KEY:-${E2B_API_TOKEN:-}}}"
|
||||
test -n "$DIFY_AGENT_E2B_API_KEY"
|
||||
export DIFY_AGENT_E2B_TEMPLATE=difys-default-team/dify-agent-local-sandbox
|
||||
|
||||
docker compose \
|
||||
--env-file docker/.env \
|
||||
-f docker/docker-compose.yaml \
|
||||
-f docker/docker-compose.e2b.yaml \
|
||||
up -d --build
|
||||
```
|
||||
|
||||
The overlay builds `dify-api:e2b-local` and
|
||||
`dify-agent-backend:e2b-local` from the current checkout. It disables the
|
||||
normal Local sandbox service, switches Dify Agent to E2B, and mounts PostgreSQL
|
||||
on the separate `dify_e2b_postgres_data` Compose volume. That database is empty
|
||||
when the volume is first created and is isolated from the normal stack; later
|
||||
starts reuse it until an operator explicitly removes the volume.
|
||||
|
||||
Verify the merged deployment and the branch-built Dify Agent API:
|
||||
|
||||
```bash
|
||||
docker compose \
|
||||
--env-file docker/.env \
|
||||
-f docker/docker-compose.yaml \
|
||||
-f docker/docker-compose.e2b.yaml \
|
||||
ps
|
||||
|
||||
agent_backend_port="$(
|
||||
docker compose \
|
||||
--env-file docker/.env \
|
||||
-f docker/docker-compose.yaml \
|
||||
-f docker/docker-compose.e2b.yaml \
|
||||
port agent_backend 5050 | awk -F: 'NR == 1 { print $NF }'
|
||||
)"
|
||||
test -n "$agent_backend_port"
|
||||
curl --fail --silent --show-error \
|
||||
--connect-timeout 2 --max-time 5 \
|
||||
--retry 12 --retry-delay 1 --retry-connrefused --retry-max-time 60 \
|
||||
"http://127.0.0.1:${agent_backend_port}/openapi.json" \
|
||||
>/dev/null
|
||||
|
||||
docker compose \
|
||||
--env-file docker/.env \
|
||||
-f docker/docker-compose.yaml \
|
||||
-f docker/docker-compose.e2b.yaml \
|
||||
logs --tail=100 agent_backend api worker
|
||||
```
|
||||
|
||||
Stop the validation stack without deleting its isolated database volume:
|
||||
|
||||
```bash
|
||||
docker compose \
|
||||
--env-file docker/.env \
|
||||
-f docker/docker-compose.yaml \
|
||||
-f docker/docker-compose.e2b.yaml \
|
||||
down
|
||||
```
|
||||
|
||||
`DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS` controls continuous active E2B time.
|
||||
The physical resource behind a Binding pauses when that timeout fires, preserving
|
||||
the current Workspace. The setting is not a resource-age TTL, does not delete
|
||||
paused resources or immutable snapshots, and does not authoritatively finalize
|
||||
the Agent run. If the paused Sandbox is first observed by a Shell tool, that
|
||||
provider failure is returned to Pydantic AI as a tool error observation.
|
||||
|
||||
The run and E2B defaults both equal 3600 seconds, but independent clocks and
|
||||
asynchronous E2B pause propagation make their ordering nondeterministic. A Shell
|
||||
provider `RuntimeError` observed first becomes a tool observation. In contrast,
|
||||
run-deadline cancellation propagates through the Shell boundary; only the Dify
|
||||
Agent run deadline owns the terminal `agent_run_limit_exceeded` failure.
|
||||
|
||||
The E2B backend uses SDK 2.55.1 or later with three control-plane retries.
|
||||
The SDK retries `502` only for replayable operations, including when the response
|
||||
has `Retry-After`; a gateway can return `502` after a resource was already created.
|
||||
Sandbox and snapshot creation therefore surface `502` without replaying the
|
||||
request. The SDK still retries `503`, `429` with `Retry-After`, and safely
|
||||
replayable network failures. Backend adapters invoke each SDK operation once;
|
||||
exhausted retries and timeouts do not start a second SDK request budget.
|
||||
Resource creation and snapshot creation are also not replayed after an ambiguous
|
||||
post-write network failure. See the [SDK replay policy](https://github.com/e2b-dev/E2B/pull/1924).
|
||||
|
||||
This policy covers E2B lifecycle API calls. Shell commands and normal file
|
||||
operations use the separate shellctl client, and usage collection uses its own
|
||||
HTTP client. Neither inherits the E2B SDK retry or connection-pool settings.
|
||||
|
||||
The backend explicitly requests `mode="full"` for timeout pauses, explicit
|
||||
pauses, and Home Snapshots, preserving both filesystem and memory state. Binding
|
||||
acquisition uses `on_resume="restore"`; `connect` does not accept a snapshot
|
||||
mode. These settings preserve the existing full-memory restore intent while
|
||||
replacing the deprecated `keep_memory` option. They do not override platform
|
||||
fallbacks: E2B may save only the filesystem if a timeout pause is continuously
|
||||
refused because a previous snapshot is still being finalized. See the
|
||||
[E2B persistence contract](https://docs.e2b.dev/sandbox/persistence).
|
||||
|
||||
## OpenShell backend
|
||||
|
||||
See the [OpenShell Runtime Backend guide](openshell.md) for its configuration
|
||||
reference, runtime image build instructions, gateway and shared-volume setup,
|
||||
and deployment validation.
|
||||
|
||||
## Run runtime-backend integration contracts
|
||||
|
||||
Run the disposable Local contract from the `dify-agent` directory. The script
|
||||
starts one local-sandbox container on an unused port and removes that exact
|
||||
container on exit. It intentionally has no image fallback: provide a Local
|
||||
Sandbox image built from the same commit as the code under test so an older
|
||||
shellctl implementation cannot make the lifecycle contract pass incorrectly:
|
||||
|
||||
```bash
|
||||
cd dify-agent
|
||||
DIFY_AGENT_TEST_LOCAL_SANDBOX_IMAGE=<same-commit-local-sandbox-image> \
|
||||
tests/integration/dify_agent/runtime_backend/run_local_integration.sh
|
||||
```
|
||||
|
||||
To use an already managed Local shellctl endpoint instead:
|
||||
|
||||
```bash
|
||||
cd dify-agent
|
||||
DIFY_AGENT_TEST_LOCAL_SHELLCTL_ENDPOINT=http://127.0.0.1:5004 \
|
||||
DIFY_AGENT_TEST_LOCAL_SHELLCTL_AUTH_TOKEN=replace-with-shellctl-token \
|
||||
pdm run pytest --import-mode=importlib \
|
||||
tests/integration/dify_agent/runtime_backend/test_working_environment.py \
|
||||
-k local -q -rs
|
||||
```
|
||||
|
||||
Run the real E2B contract with an explicit test credential and template:
|
||||
|
||||
```bash
|
||||
cd dify-agent
|
||||
DIFY_AGENT_TEST_E2B_API_KEY="$E2B_API_TOKEN" \
|
||||
DIFY_AGENT_TEST_E2B_TEMPLATE=difys-default-team/dify-agent-local-sandbox \
|
||||
pdm run pytest --import-mode=importlib \
|
||||
tests/integration/dify_agent/runtime_backend/test_working_environment.py \
|
||||
-k e2b -q -rs
|
||||
```
|
||||
|
||||
For OpenShell, see [Run the OpenShell integration contract](openshell.md#run-the-openshell-integration-contract).
|
||||
|
||||
The Local auth token is optional when shellctl has authentication disabled.
|
||||
The E2B contract uses the one-hour `E2B_MAX_ACTIVE_TIMEOUT_SECONDS` RuntimeLease
|
||||
limit. This is continuous active test time, not a post-test retention TTL. All
|
||||
contracts create unique resources and perform explicit cleanup in `finally`
|
||||
blocks.
|
||||
|
||||
## Scheduling and shutdown semantics
|
||||
|
||||
`POST /runs` persists a `running` run record and starts an `asyncio` task in the
|
||||
same process. There is no Redis job stream, consumer group, pending reclaim, or
|
||||
automatic retry layer. Request-shaped runtime failures such as bad composition,
|
||||
prompt, output, or snapshot inputs are reported later as failed runs rather than
|
||||
rejected synchronously once the request DTO itself is accepted.
|
||||
|
||||
Each run explicitly limits Pydantic AI to 500 model-request steps. Tool calls do
|
||||
not have a separate count limit, but every model request used to continue the
|
||||
tool loop consumes one of those steps.
|
||||
|
||||
`DIFY_AGENT_RUN_TIMEOUT_SECONDS` additionally applies a wall-clock deadline around
|
||||
native Pydantic AI's `agent.run(...)`. This includes capability entry, RuntimeLease
|
||||
acquisition, dynamic tool preparation, the model/tool loop, and the event handler.
|
||||
Request validation and agent assembly happen before this deadline. Expiry cancels
|
||||
the native run; capability scopes unwind and release resources before the runner
|
||||
generates the session snapshot and finalizes the run as failed with
|
||||
`error_type: "agent_run_limit_exceeded"`. History persistence, snapshot generation,
|
||||
and terminal finalization occur after native execution.
|
||||
|
||||
During FastAPI shutdown the scheduler rejects new runs, waits up to
|
||||
`DIFY_AGENT_SHUTDOWN_GRACE_SECONDS` for active tasks, then cancels remaining tasks
|
||||
and attempts to finalize them as failed. Success and failure use an atomic Redis
|
||||
transition. Cancellation first atomically records a private intent; after the
|
||||
owner exits the runner, a second atomic transition appends `run_cancelled`,
|
||||
updates the run record, and deletes the intent. The first accepted success,
|
||||
failure, or cancellation intent wins. A hard process crash can still leave
|
||||
active runs, including runs with accepted cancellation intent, stuck as
|
||||
`running`; there is no in-service recovery or worker handoff.
|
||||
|
||||
Horizontal scaling is possible by running multiple API processes against the same
|
||||
Redis prefix, but each process executes only the runs it accepted. Redis provides
|
||||
shared status/event visibility, not load balancing or queued-job recovery. The
|
||||
cancel endpoint can atomically accept a running run on any process. The process
|
||||
that owns the runner observes the private cancellation-intent stream, cancels
|
||||
and cleans up its local task, and only then emits `run_cancelled`. The HTTP
|
||||
response confirms that cancellation intent is durable; `GET /runs/{run_id}` may
|
||||
still report `running` until cleanup finishes. Retrying an accepted or completed
|
||||
cancellation is idempotent.
|
||||
|
||||
Atomic terminal finalization currently assumes the configured Redis URL targets
|
||||
one Redis deployment that can execute all run-coordination keys in a Lua script.
|
||||
The record and event key names are unchanged, and cancellation adds a private
|
||||
cancel-intent key. These keys do not contain a shared Redis Cluster hash tag, so
|
||||
Redis Cluster is not supported for this transition. During
|
||||
a rolling upgrade, older processes can still use the former split event/status
|
||||
writes; treat the single-terminal invariant as active only after those processes
|
||||
have exited. Deploy atomic terminal finalization everywhere first, then ensure
|
||||
every process that can own a runner has the cancellation observer before relying
|
||||
on route-independent cancellation. Operators should then alert on more than one
|
||||
terminal event per run and on disagreement between the run record status and
|
||||
terminal event type.
|
||||
|
||||
## Run inputs and session snapshots
|
||||
|
||||
Submit a `RunComposition` with registered module names and JSON Config. The
|
||||
`llm` model module is required and references an `execution_context` module.
|
||||
Prompt modules contribute instructions and `config.user` input:
|
||||
|
||||
```json
|
||||
{
|
||||
"composition": {
|
||||
"schema_version": 2,
|
||||
"layers": [
|
||||
{"name": "prompt", "config": {"prefix": "You are concise.", "user": "Summarize the current state."}},
|
||||
{"name": "execution_context", "config": {"tenant_id": "tenant-id", "agent_mode": "agent_app", "invoke_from": "web-app"}},
|
||||
{"name": "llm", "config": {"plugin_id": "langgenius/openai", "model_provider": "openai", "model": "gpt-4o-mini"}}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`config.user` can be a string or a list of strings. Empty or whitespace-only
|
||||
effective prompts and module configuration are validated by the runner before
|
||||
resource acquisition or model I/O. HTTP create-run parses the wire shape, persists
|
||||
the run and schedules execution; configuration errors produce `run_failed`.
|
||||
|
||||
Agent App callers can use the `agent_app_user_prompt` module to send text and images
|
||||
in the same model turn. Each image must provide exactly one transport: an
|
||||
HTTP(S) `url` or unprefixed Base64 data in `base64_data`. The image is passed as
|
||||
structured multimodal content; it is not interpolated into `config.text`.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "agent_app_user_prompt",
|
||||
"config": {
|
||||
"text": "Describe this image.",
|
||||
"files": [
|
||||
{
|
||||
"delivery": "multimodal",
|
||||
"type": "image",
|
||||
"filename": "earth.png",
|
||||
"mime_type": "image/png",
|
||||
"format": "png",
|
||||
"url": "https://files.example.com/earth.png",
|
||||
"base64_data": null,
|
||||
"detail": "high"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
All attachments use `config.files`. The `delivery` field selects how an attachment
|
||||
is presented, independently of its file `type` (`image`, `document`, `audio`,
|
||||
`video`, or `custom`):
|
||||
|
||||
- `delivery: "multimodal"` currently supports `type: "image"` only. Dify API
|
||||
chooses URL or Base64 transport according to `MULTIMODAL_SEND_FORMAT`.
|
||||
- `delivery: "download"` preserves the original file `type`, including `image`
|
||||
when the selected model has no Vision feature. It contains either
|
||||
`transfer_method: "remote_url"` with `url`, or a `local_file`, `tool_file`, or
|
||||
`datasource_file` transfer method with a canonical `reference`. An optional
|
||||
`filename` identifies the attachment in the rendered file locators.
|
||||
|
||||
When an Agent App has KnowledgeFS spaces, each uploaded `local_file` image sent
|
||||
as multimodal content also has a named download entry. The model receives the
|
||||
image directly and can use its canonical `reference` with
|
||||
`dify-agent knowledge search --image-file-id`. Remote URLs and tool/datasource
|
||||
file references are not valid upload references for KnowledgeFS image search.
|
||||
|
||||
The module appends sandbox file-download instructions for download attachments
|
||||
and adds multimodal attachments as structured model content. Callers keep
|
||||
`config.text` as the original user text. Omitting `config.files` is equivalent
|
||||
to an empty list.
|
||||
|
||||
The optional history module uses the reserved name `history`. It persists captured
|
||||
messages, including failure and cancellation history, with current instructions
|
||||
removed. Snapshots have `schema_version: 2` and a `layers` JSON dict containing only
|
||||
State. Submit current Config on each turn along with the previous snapshot. Modules
|
||||
can be added or removed between turns; retained state is matched by name.
|
||||
|
||||
Known v1 snapshots are converted once at read time without restoring legacy
|
||||
instances or lifecycle. Native resource scopes always release leases and clear
|
||||
tracked shell jobs at run exit. Success always contains the resulting snapshot;
|
||||
failure and cancellation contain one when validated run data was available and
|
||||
cleanup produced a snapshot. Callers retain the previous snapshot when none is
|
||||
returned. Product Workspace retirement remains owned by the API.
|
||||
|
||||
## Observing runs
|
||||
|
||||
Use the HTTP status endpoint for coarse state and the event endpoints for detailed
|
||||
progress:
|
||||
|
||||
- `POST /runs` creates a running run and schedules it locally.
|
||||
- `GET /runs/{run_id}` returns `running`, `succeeded`, `failed`, or `cancelled`.
|
||||
Failed records can also expose a stable machine-readable `error_type` alongside
|
||||
the diagnostic `error` text.
|
||||
- `POST /runs/{run_id}/cancel` atomically accepts cancellation on any API process
|
||||
and returns immediately. `CancelRunResponse.status == "cancelled"` acknowledges
|
||||
a durably accepted cancellation intent, not completed runner cleanup. Callers
|
||||
that require cleanup-complete state or its session snapshot must await the
|
||||
public `run_cancelled` event or use `cancel_run_and_wait`. The endpoint returns
|
||||
`409` only when a success/failure terminal already won.
|
||||
- `GET /runs/{run_id}/events` polls the Redis Stream event log with `after` and
|
||||
`next_cursor` cursors.
|
||||
- `GET /runs/{run_id}/events/sse` replays and streams events over SSE. The SSE
|
||||
`id` is the event Redis Stream ID. `after` query cursors take precedence over
|
||||
`Last-Event-ID` headers. The server closes the SSE response normally after
|
||||
delivering a terminal event. Clients must stop reconnecting after consuming
|
||||
that event. Both cursor forms remain exclusive resume cursors, so the server
|
||||
does not resend a terminal event that the supplied cursor already excludes.
|
||||
|
||||
Both event endpoints replay with nonblocking `XREAD`, which supports exclusive
|
||||
resume cursors on Redis 6.0, including 6.0.14. `0-0` starts at the earliest
|
||||
retained event. Polling returns at most `limit` events; an empty page preserves
|
||||
the supplied `after` as `next_cursor`. SSE switches to blocking reads after
|
||||
replay is exhausted. Both endpoints return `404` when the run record is missing.
|
||||
This read-command compatibility does not define the platform's full Redis
|
||||
support matrix; the Redis deployment constraints above still apply.
|
||||
|
||||
Successful runs emit `run_started`, zero or more `pydantic_ai_event`, and
|
||||
`run_succeeded`. Failed runs end with `run_failed`, and accepted cancellations
|
||||
end with `run_cancelled`. Each run can append at most one of these terminal
|
||||
events. Event envelopes retain `id`, `run_id`, `type`, `data`, and `created_at`;
|
||||
`data` is typed per event type,
|
||||
including Pydantic AI's `AgentStreamEvent` payload for `pydantic_ai_event` and a
|
||||
terminal event may contain a `SessionSnapshot` for resumption.
|
||||
`run_succeeded` always contains it; `run_failed` and `run_cancelled` contain it
|
||||
when the runner produced State after native capability cleanup. A successful run
|
||||
contains JSON-safe `output`, which may be null.
|
||||
Failed event payloads contain the diagnostic `error`, optional source-specific
|
||||
`reason`, optional stable `error_type`, and optional `session_snapshot`.
|
||||
Cancelled payloads likewise may contain `session_snapshot`. Pydantic AI request/step budget
|
||||
exhaustion enforced by Dify Agent is reported as
|
||||
`error_type: "agent_run_limit_exceeded"`; consumers should branch on that value
|
||||
rather than parsing the error text. The Dify Agent-owned wall-clock run deadline
|
||||
uses the same error type; provider and connection timeouts do not. The matching
|
||||
failed run record and terminal event are committed atomically with the same error
|
||||
type. For independently deployed Agent backend and API services, deploy consumers
|
||||
that accept the optional field before producers begin emitting it because the
|
||||
public protocol models reject unknown fields.
|
||||
|
||||
## Examples
|
||||
|
||||
The repository includes simple consumers that print observed output/events:
|
||||
|
||||
- `dify-agent/examples/dify_agent/dify_agent_examples/run_server_consumer.py`
|
||||
creates a run and polls events.
|
||||
- `dify-agent/examples/dify_agent/dify_agent_examples/run_server_sse_consumer.py`
|
||||
consumes raw SSE frames for an existing run id.
|
||||
|
||||
The create-run examples submit Dify plugin model modules, so they require Redis,
|
||||
the Agent server, Dify API gateway settings, and a configured model provider in Dify.
|
||||
|
||||
### Automatic KnowledgeFS quality reporting
|
||||
|
||||
Knowledge CLI calls now contribute bounded, server-owned investigation observations.
|
||||
The Stub records command IDs, queries/paths, outcomes, error codes, timing, small text
|
||||
snippets and receipt IDs. The runtime separately marks which observations were delivered
|
||||
to the model. This ledger survives the consumable tool-result queue and session cleanup.
|
||||
It shares the knowledge budget's two-hour retention and identity boundary. A human-input
|
||||
pause retains the investigation; a resumed run continues it. A new user turn gets a fresh
|
||||
investigation. Images and bearer capabilities are never included in these observations.
|
||||
|
||||
After the authoritative final-answer event, the runtime submits the original question,
|
||||
final answer and observations to the private Dify API. Failed runs submit an interrupted
|
||||
report; cancellation leaves a bounded diagnostic ledger and does not create quality cases.
|
||||
A human-input pause does not submit a final report. Queue admission is retried with the same
|
||||
investigation ID, and submission failures do not change the completed Agent result.
|
||||
|
||||
The existing `dataset` Celery workers process one job per investigated knowledge space.
|
||||
Each attempt reconstructs the Agent/app/configuration ownership and reissues a capability.
|
||||
An authorization fingerprint binds observations to the original caller, ACL/content policy
|
||||
revisions and content scopes; a changed scope rejects publication of old observations.
|
||||
Agent applications, Workflow Agent nodes and interactive previews use their actual caller
|
||||
identities and a dedicated `queries.agent_investigation.capture` action.
|
||||
|
||||
KnowledgeFS makes one batched assessment of the space's complete investigation using its
|
||||
configured reasoning model with a 60-second model budget. The worker uses the existing
|
||||
`KNOWLEDGE_FS_RETRIEVAL_TEST_TIMEOUT_SECONDS` transport timeout for this operation.
|
||||
Query rewrites and recovered empty searches are grouped. An
|
||||
unresolved subquestion produces a failed-query record; only `retrieval-miss` produces a
|
||||
quality bad case tagged `agent`, `auto-captured`, `retrieval-miss`. Coverage gaps, unrelated
|
||||
questions and uncertain issues do not become retrieval bad cases. Tool errors, directory
|
||||
probing, unobserved results, image-only investigations and interruptions cannot by themselves
|
||||
produce a bad case. If the model is unavailable or returns an invalid assessment, the trace
|
||||
is retained as uncertain without automatic cases.
|
||||
|
||||
The committed assessment and stable child IDs fence retries, so projection retries do not
|
||||
create duplicate failed queries/cases or repeat the committed judgment. Separate unanswered
|
||||
subquestions remain separate, with at most eight issues per space. The original question and
|
||||
bounded command history remain linked to each issue trace. The final answer is used for
|
||||
assessment but is not copied into a knowledge space's shared trace, since it may contain
|
||||
content from other spaces. Document snippets likewise remain transient classifier input;
|
||||
shared traces retain command metadata and receipt IDs without copying document text outside
|
||||
the existing evidence permission projection. Reports are best-effort: after bounded dispatch retries, an
|
||||
undelivered report remains only in the expiring runtime ledger. Deploy matching Agent,
|
||||
Dify API/worker and KnowledgeFS versions to enable the complete path; no new environment
|
||||
variable or Agent tool is required.
|
||||
@@ -0,0 +1,269 @@
|
||||
# OpenShell Runtime Backend
|
||||
|
||||
This guide covers OpenShell-specific configuration, deployment, and validation.
|
||||
See the [Operations Guide](index.md) for shared server configuration and
|
||||
scheduling behavior.
|
||||
|
||||
## Configuration
|
||||
|
||||
`ServerSettings` loads environment variables with the `DIFY_AGENT_` prefix. It
|
||||
also reads `.env` and `dify-agent/.env` when present. Select
|
||||
`DIFY_AGENT_RUNTIME_BACKEND=openshell` to use this backend. Shared settings,
|
||||
including Agent Stub and file-service URLs, are documented in the
|
||||
[server configuration reference](index.md#configuration).
|
||||
|
||||
| Environment variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT` | empty | OpenShell gateway gRPC endpoint as `host:port` (no scheme); required for OpenShell. Prefer `localhost` over an IPv6 literal when the gateway listens on loopback. |
|
||||
| `DIFY_AGENT_OPENSHELL_WORKSPACE` | `default` | OpenShell workspace that owns the sandboxes. Production multi-tenant deployments must use one workspace and one dedicated shared volume per tenant. |
|
||||
| `DIFY_AGENT_OPENSHELL_BEARER_TOKEN` | empty | Static OIDC bearer token sent to the gateway. Combines with the mTLS bundle. The token is not refreshed in-process; restart `agent_backend` or switch to a long-lived token when it expires. |
|
||||
| `DIFY_AGENT_OPENSHELL_TLS_CA_PATH` | empty | Custom gateway CA certificate path. Empty uses the system trust store. |
|
||||
| `DIFY_AGENT_OPENSHELL_TLS_CLIENT_CERT_PATH` | empty | mTLS client certificate path; set together with the key path. |
|
||||
| `DIFY_AGENT_OPENSHELL_TLS_CLIENT_KEY_PATH` | empty | mTLS client key path; set together with the certificate path. |
|
||||
| `DIFY_AGENT_OPENSHELL_INSECURE` | `false` | Use a plaintext gRPC channel. Local development only. |
|
||||
| `DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE` | `langgenius/dify-agent-local-sandbox:latest` | Build the runtime image yourself from this checkout and explicitly set this to the resulting image reference. Do not rely on the code fallback or a published `latest` tag: older images may lack `iproute2`, which the OpenShell supervisor requires alongside shellctl. The env templates use the self-built `docker.io/library/dify-agent-runtime:latest`; see the build command below. |
|
||||
| `DIFY_AGENT_OPENSHELL_DRIVER_CONFIG` | empty | JSON `SandboxTemplate.driver_config`; required for OpenShell and must be a non-empty object. Must mount the shared Home Snapshot volume at the shared mount path in every sandbox. |
|
||||
| `DIFY_AGENT_OPENSHELL_SHARED_MOUNT_PATH` | `/mnt/dify-agent-shared` | In-sandbox mount path of the shared volume; Home Snapshots live under `home-snapshots/<tenant-digest>/`. |
|
||||
| `DIFY_AGENT_OPENSHELL_EGRESS_ALLOW` | empty | Optional comma-separated `host:port` egress allowlist (no scheme or path). Empty sends no network policy (gateway/driver default egress). When set, sandbox egress is enforced to exactly these endpoints — include the Agent Stub and files endpoints. |
|
||||
| `DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN` | empty | Required bearer token the exec-bootstrapped shellctl expects on its data plane. Empty is rejected at startup. |
|
||||
| `DIFY_AGENT_OPENSHELL_SHELLCTL_PORT` | `5004` | Sandbox-loopback port shellctl listens on; reached through the gateway `ForwardTcp` tunnel. |
|
||||
| `DIFY_AGENT_OPENSHELL_READY_TIMEOUT_SECONDS` | `300` | Maximum wait for a sandbox to reach the READY phase. |
|
||||
| `DIFY_AGENT_OPENSHELL_EXEC_TIMEOUT_SECONDS` | `120` | Timeout for gateway exec calls (bootstrap and maintenance scripts). |
|
||||
|
||||
## Deploy with the OpenShell backend
|
||||
|
||||
The OpenShell backend runs each Binding in its own sandbox on a self-hosted
|
||||
[NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) gateway. Dify Agent
|
||||
only talks to the gateway gRPC API: it creates sandboxes from the configured
|
||||
image, bootstraps shellctl through gateway exec, and reaches the shellctl data
|
||||
plane through an authenticated `ForwardTcp` tunnel.
|
||||
|
||||
New Bindings are initialized and then stopped. Acquire starts a stopped sandbox
|
||||
when needed, verifies its Home and Workspace, ensures shellctl is running, and
|
||||
opens a fresh lease-local tunnel. Release closes only that lease's HTTP client
|
||||
and tunnel; it does not stop the sandbox or shellctl. Subsequent operations can
|
||||
reuse the running sandbox, and releasing one lease does not interrupt another
|
||||
lease on the same Binding.
|
||||
|
||||
There is no automatic idle-stop or sandbox TTL in this adapter. After a
|
||||
successful acquire/release cycle, the sandbox remains running until explicitly
|
||||
stopped or destroyed, or a runtime failure stops it. Operators must account for
|
||||
these running resources. Binding creation and failed-acquire cleanup retain
|
||||
their existing stop behavior; this change only makes lease release lightweight.
|
||||
Explicitly stopped sandboxes are restarted on the next acquire.
|
||||
|
||||
Backend selection lives in `docker/.env`; create it from the template first if
|
||||
this deployment does not have one yet (`cp docker/.env.example docker/.env`).
|
||||
|
||||
Deployment prerequisites:
|
||||
|
||||
1. An OpenShell gateway, version 0.0.106 or newer (validated against
|
||||
0.0.106–0.0.110; the bundled SDK is pinned `>=0.0.106,<0.1.0`), reachable
|
||||
from `agent_backend` at `DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT`, with
|
||||
credentials via `DIFY_AGENT_OPENSHELL_BEARER_TOKEN` or the mTLS bundle
|
||||
paths. Prefer `localhost:17670` when the gateway listens on loopback.
|
||||
Sandboxes reconnect to the gateway through `host.openshell.internal`; on
|
||||
macOS local development bind the gateway to `127.0.0.1:17670` so that
|
||||
alias can reach it.
|
||||
2. Sandboxes must reach `DIFY_AGENT_STUB_API_BASE_URL` and
|
||||
`DIFY_AGENT_SANDBOX_FILES_BASE_URL`. When the gateway runs outside this
|
||||
Compose stack, set both to externally reachable URLs; compose-internal
|
||||
hostnames are not resolvable from OpenShell sandboxes. When the
|
||||
deployment restricts sandbox egress, set
|
||||
`DIFY_AGENT_OPENSHELL_EGRESS_ALLOW` so the sandbox policy carries an
|
||||
enforced allowlist covering at least those two endpoints:
|
||||
|
||||
```text
|
||||
DIFY_AGENT_OPENSHELL_EGRESS_ALLOW=agent.example.com:443,dify.example.com:443
|
||||
```
|
||||
|
||||
Left empty (the default), the policy carries no network rules and egress
|
||||
follows the gateway/driver default — a stock Docker driver leaves sandbox
|
||||
outbound unrestricted, which agent-run tools (package installs, web
|
||||
access) may rely on. When set, egress is restricted to exactly the listed
|
||||
endpoints, from any in-sandbox binary.
|
||||
|
||||
3. **Build the runtime image yourself from the current checkout.** It must
|
||||
bundle shellctl and `iproute2`. A published or cached
|
||||
`langgenius/dify-agent-local-sandbox:latest` is not a substitute: older images
|
||||
lack `iproute2`, causing the OpenShell supervisor to exit during startup.
|
||||
4. A required `DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN`. shellctl is
|
||||
bootstrapped with `SHELLCTL_ENABLE_PATH_ISOLATION=false` because the
|
||||
sandbox Landlock policy is authoritative; stacking both would require
|
||||
re-granting every device path twice. The token still authenticates the
|
||||
in-sandbox command plane.
|
||||
5. A shared Home Snapshot volume mounted into every sandbox via
|
||||
`DIFY_AGENT_OPENSHELL_DRIVER_CONFIG`. Production multi-tenant deployments
|
||||
must use one OpenShell workspace and one dedicated volume per tenant:
|
||||
Landlock is best-effort and every sandbox runs as the same image UID, so a
|
||||
shared volume is a shared trust boundary. Snapshots are stored under
|
||||
`home-snapshots/<tenant-digest>/`; the sandbox policy grants only that
|
||||
tenant directory.
|
||||
|
||||
Build from the repository root (the directory containing `dify-agent-runtime/`):
|
||||
|
||||
```bash
|
||||
docker build -f dify-agent-runtime/docker/Dockerfile \
|
||||
-t dify-agent-runtime:latest dify-agent-runtime
|
||||
```
|
||||
|
||||
Set the **exact built image reference** in `dify-agent/.env` for a local Agent
|
||||
Backend process, or in `docker/.env` for Docker Compose:
|
||||
|
||||
```ini
|
||||
DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest
|
||||
```
|
||||
|
||||
The gateway's Docker driver must use the same Docker daemon containing this
|
||||
image. For a remote gateway or a multi-node deployment, tag and push the image
|
||||
to a registry accessible to the compute nodes and configure that registry
|
||||
reference instead. A local build on your laptop is not available to a remote
|
||||
gateway automatically. If the configured tag is absent, the driver attempts to
|
||||
pull it; a mismatched name can fail with `ImagePullFailed` / `pull access denied`.
|
||||
|
||||
Initialize the volume once. It is operator-owned and shared with the OpenShell
|
||||
gateway, so create it with these commands rather than declaring it in a compose
|
||||
file — `docker compose down -v` on a managing stack would delete every Home
|
||||
Snapshot. Docker named volume (single-tenant local development; `1777` is not
|
||||
a multi-tenant control):
|
||||
|
||||
```bash
|
||||
docker volume create dify-agent-shared
|
||||
docker run --rm -v dify-agent-shared:/mnt busybox \
|
||||
sh -c "mkdir -p /mnt/home-snapshots && chmod 1777 /mnt /mnt/home-snapshots"
|
||||
```
|
||||
|
||||
Kubernetes: provision one ReadWriteMany PVC per tenant trust zone and mount
|
||||
it read-write at `DIFY_AGENT_OPENSHELL_SHARED_MOUNT_PATH` through that
|
||||
driver's `driver_config` (shape is driver-specific; the Docker example
|
||||
above is the local-dev analogue). Initialize the volume with an
|
||||
initContainer or `fsGroup` so the sandbox UID can write
|
||||
`home-snapshots/` — do not rely on `chmod 1777` as isolation.
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: dify-agent-shared-tenant-a
|
||||
spec:
|
||||
accessModes: ["ReadWriteMany"]
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
```
|
||||
|
||||
Configure the backend in `docker/.env`. The full `DIFY_AGENT_OPENSHELL_*`
|
||||
variable reference lives in `docker/envs/core-services/dify-agent.defaults`;
|
||||
values may also be set in the `envs/core-services/dify-agent.env` env_file,
|
||||
but `docker/.env` is loaded last into `agent_backend` and overrides it. These
|
||||
lines are `.env` file content, not shell commands — values are taken verbatim,
|
||||
so the `driver_config` JSON needs no quoting:
|
||||
|
||||
```ini
|
||||
# docker/.env
|
||||
DIFY_AGENT_RUNTIME_BACKEND=openshell
|
||||
DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT=gateway.example.com:17670
|
||||
DIFY_AGENT_OPENSHELL_BEARER_TOKEN=replace-with-gateway-token
|
||||
DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest
|
||||
DIFY_AGENT_OPENSHELL_DRIVER_CONFIG={"docker":{"mounts":[{"type":"volume","source":"dify-agent-shared","target":"/mnt/dify-agent-shared","read_only":false}]}}
|
||||
DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN=replace-with-shellctl-token
|
||||
```
|
||||
|
||||
Then start the stack normally:
|
||||
|
||||
```bash
|
||||
docker compose -f docker/docker-compose.yaml up -d
|
||||
```
|
||||
|
||||
The Local backend's `local_sandbox` container and its dedicated SSRF proxy
|
||||
stay in the stack unused, exactly as they do in an E2B deployment. The standard
|
||||
Compose file does not build the OpenShell runtime image or provision its
|
||||
gateway; complete the prerequisites above and the deployment-specific
|
||||
networking and certificate setup below before starting the stack.
|
||||
|
||||
Home Snapshots are directory copies under
|
||||
`<shared mount>/home-snapshots/<tenant-digest>/`; snapshot deletion runs a
|
||||
short-lived maintenance sandbox granted only that tenant's snapshot root
|
||||
(unlinking the snapshot directory itself requires write on its parent).
|
||||
|
||||
## Validate the OpenShell deployment
|
||||
|
||||
For local development, run the API and Agent Backend from the current checkout.
|
||||
Copy `dify-agent/.example.env` to `dify-agent/.env`, select
|
||||
`DIFY_AGENT_RUNTIME_BACKEND=openshell`, and build the runtime image as described
|
||||
above. The local template targets `localhost:17670` and the Homebrew gateway's
|
||||
mTLS bundle; adjust those paths if your gateway registration has a different
|
||||
name. Install Agent Backend dependencies with `uv sync --extra server` from
|
||||
`dify-agent/` before starting the server.
|
||||
|
||||
For Docker Compose, use `docker/docker-compose.yaml` and explicitly configure
|
||||
your deployment:
|
||||
|
||||
- Use API and Agent Backend images containing the OpenShell integration. If your
|
||||
images predate it, build them from the checkout using `api/Dockerfile` and
|
||||
`dify-agent/Dockerfile`, and update the corresponding Compose service image
|
||||
references. Building the runtime image alone does not update these services.
|
||||
Keep the Agent Backend's glibc ≥ 2.39 base (`python:3.13-slim-trixie` in its
|
||||
Dockerfile): the bundled OpenShell wheel requires it.
|
||||
- The gateway endpoint must be reachable from the `agent_backend` container.
|
||||
For a gateway on the Docker host, use `host.docker.internal:17670`, not
|
||||
`localhost:17670`. On Linux Docker, add
|
||||
`extra_hosts: ["host.docker.internal:host-gateway"]` to that service and ensure
|
||||
the gateway listens on a container-reachable address. Verify that the gateway
|
||||
certificate covers the hostname you use.
|
||||
- When using mTLS, add a read-only bind mount for the gateway client bundle to
|
||||
`agent_backend` and set `DIFY_AGENT_OPENSHELL_TLS_*_PATH` to the paths **inside
|
||||
the container**. There is no automatic certificate mount. Ensure the service
|
||||
user can traverse the mounted directory and read the files; copy the bundle
|
||||
to a dedicated directory with appropriate permissions rather than mounting
|
||||
the CLI's private gateway directory directly.
|
||||
- Set sandbox-reachable Agent Stub and file-service URLs. Any required service
|
||||
port publishing must be configured explicitly; the Agent Backend control
|
||||
plane should remain private.
|
||||
|
||||
The runtime image must be available to the gateway's compute driver, not merely
|
||||
in the Docker daemon used to build the API or Agent Backend images.
|
||||
|
||||
Smoke-test through the Agent Backend control plane. Set `AGENT_BACKEND_BASE_URL`
|
||||
to its reachable service root (`http://localhost:5050` for a local process on
|
||||
port 5050), and export the matching `DIFY_AGENT_API_TOKEN` from your deployment.
|
||||
Use a disposable test tenant and binding; the destroy request deletes the test
|
||||
sandbox and its workspace.
|
||||
|
||||
```bash
|
||||
curl -s -w '\n%{http_code}\n' -X POST "$AGENT_BACKEND_BASE_URL/execution-bindings" \
|
||||
-H "Authorization: Bearer $DIFY_AGENT_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"tenant_id":"smoke-tenant","agent_id":"smoke-agent","binding_id":"smoke-binding-1","workspace_id":"smoke-ws-1"}'
|
||||
# → {"binding_ref":"dify-<digest>","workspace_ref":"dify-<digest>"} then 201
|
||||
curl -s -w '\n%{http_code}\n' -X POST "$AGENT_BACKEND_BASE_URL/execution-bindings/destroy" \
|
||||
-H "Authorization: Bearer $DIFY_AGENT_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"binding_ref":"<binding_ref>","destroy_workspace":true,"workspace_ref":"<binding_ref>"}'
|
||||
# → 204
|
||||
```
|
||||
|
||||
A created ref verifies gateway authentication, sandbox startup from the
|
||||
configured runtime image, and Binding initialization. Home Snapshot operations
|
||||
also require the initialized shared volume described above.
|
||||
|
||||
## Run the OpenShell integration contract
|
||||
|
||||
Run the real OpenShell contract against a reachable gateway. The driver config
|
||||
must mount an initialized shared Home Snapshot volume (see the OpenShell
|
||||
deployment section above); pass the gateway credential through the bearer-token
|
||||
or mTLS-path variables that match your gateway:
|
||||
|
||||
```bash
|
||||
cd dify-agent
|
||||
DIFY_AGENT_TEST_OPENSHELL_GATEWAY_ENDPOINT=gateway.example.com:17670 \
|
||||
DIFY_AGENT_TEST_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest \
|
||||
DIFY_AGENT_TEST_OPENSHELL_DRIVER_CONFIG='{"docker":{"mounts":[{"type":"volume","source":"dify-agent-shared","target":"/mnt/dify-agent-shared","read_only":false}]}}' \
|
||||
DIFY_AGENT_TEST_OPENSHELL_BEARER_TOKEN=replace-with-gateway-token \
|
||||
uv run --extra server pytest --import-mode=importlib \
|
||||
tests/integration/dify_agent/runtime_backend/test_working_environment.py \
|
||||
-k openshell -q -rs
|
||||
```
|
||||
|
||||
The contract creates unique resources and performs explicit cleanup in `finally`
|
||||
blocks.
|
||||
@@ -0,0 +1,156 @@
|
||||
# E2B runtime metering
|
||||
|
||||
One ledger row represents one E2B `sandboxExecutionId`, from start/resume to
|
||||
pause/kill. Provider execution time and resource sizes determine compute usage;
|
||||
LLM token usage, message latency and local SDK-call duration do not.
|
||||
|
||||
## Scheduled collection and boundaries
|
||||
|
||||
The Dify API's existing Celery Beat schedule dispatches
|
||||
`schedule.collect_agent_sandbox_usage.collect_agent_sandbox_usage` every 60 seconds
|
||||
by default, through the existing `ops_trace` worker queue. The job calls
|
||||
`POST /internal/e2b/usage/collect` on the Agent backend using its existing Bearer
|
||||
service token and a `project_id` body. The E2B key stays in the Agent backend.
|
||||
|
||||
The provider-specific endpoint performs one bounded scan, using request-scoped
|
||||
HTTP clients. It reads E2B lifecycle events and posts them to the Dify API's
|
||||
idempotent usage ingestion endpoint. It returns `{"completed": true}` only after
|
||||
all scanned pages and the checkpoint have been acknowledged. Partial scans return
|
||||
`completed=false`; provider/API errors fail this accounting request only.
|
||||
|
||||
There is no Agent-process polling loop, Redis leader election, log outbox,
|
||||
observation worker, or requested/observed operation reporting. Generic leases,
|
||||
Agent runs, files, snapshots and binding lookups do not participate in metering.
|
||||
Their timing, cancellation handling and SDK retries retain their normal behavior.
|
||||
Metering misconfiguration is checked when collection is invoked, rather than
|
||||
becoming a prerequisite for business runtime startup or binding operations.
|
||||
|
||||
The endpoint has a 240-second deadline. The scheduled HTTP caller has a
|
||||
260-second timeout, and the Celery task configures 270/300-second soft/hard limits.
|
||||
Pool support differs: gevent workers do not implement soft time limits, and
|
||||
blocking work cannot rely on their hard limit. The collection and HTTP deadlines
|
||||
are the primary bounds; verify the deployed worker pool before relying on Celery
|
||||
limits. See the [Celery time-limit documentation](https://docs.celeryq.dev/en/stable/userguide/workers.html#time-limits).
|
||||
Scheduled messages expire after one collection interval to avoid stale backlog.
|
||||
There is no automatic HTTP retry; future scheduled scans can redeliver provider
|
||||
IDs safely. Overlapping tasks may duplicate reads, but cannot multiply usage.
|
||||
|
||||
## Data and attribution
|
||||
|
||||
The API owns `agent_sandbox_usage_events` and `agent_sandbox_executions`.
|
||||
Ingestion persists provider facts and projects execution rows atomically; the
|
||||
execution key is `(provider, provider_project_id, provider_execution_id)`.
|
||||
A short project transaction lock protects ingestion. Binding creation/lookups do
|
||||
not register allocations, write accounting rows or acquire that lock.
|
||||
Steady-state usage-state reads do not take a project `FOR UPDATE` lock; activation
|
||||
can be initialized once when first needed.
|
||||
|
||||
E2B's existing sandbox metadata contains binding, tenant, Agent and workspace
|
||||
identifiers. During background ingestion, optional attribution checks those IDs
|
||||
against the existing Binding → Workspace → App/Agent tenant-owned chain and the
|
||||
physical sandbox reference. It never trusts labels alone. Missing, malformed or
|
||||
already-deleted business records leave attribution unresolved while preserving
|
||||
complete project-level provider usage. A previously verified ownership snapshot
|
||||
survives later business deletion. Conflicting ownership is not silently reassigned.
|
||||
|
||||
No accounting callback or transaction is added to the business path. There is no
|
||||
pre-create allocation journal. Older diagnostic/allocation columns and records
|
||||
are not destructively migrated in this revision; new accounting accepts only
|
||||
provider events and collector checkpoint/coverage-gap control records. Table
|
||||
retention is unchanged, with no new automatic cleanup policy.
|
||||
|
||||
## Configuration
|
||||
|
||||
Apply the existing usage-table migration before first enabling metering.
|
||||
Configure Dify API, Beat and the workers consuming `ops_trace` consistently:
|
||||
|
||||
```dotenv
|
||||
AGENT_SANDBOX_METERING_ENABLED=true
|
||||
AGENT_SANDBOX_METERING_PROJECT_ID=<E2B project/team ID>
|
||||
AGENT_SANDBOX_METERING_START_AT=<whole-second UTC instant>
|
||||
AGENT_SANDBOX_METERING_INTERVAL_SECONDS=60
|
||||
```
|
||||
|
||||
The task reuses `AGENT_BACKEND_BASE_URL` and `AGENT_BACKEND_API_TOKEN`; the
|
||||
existing SSRF-safe HTTP policy must permit that internal service. No E2B key is
|
||||
copied into API or worker configuration.
|
||||
|
||||
Configure the Agent backend's one-shot endpoint:
|
||||
|
||||
```dotenv
|
||||
DIFY_AGENT_SANDBOX_METERING_ENABLED=true
|
||||
DIFY_AGENT_E2B_PROJECT_ID=<same E2B project/team ID>
|
||||
DIFY_AGENT_SANDBOX_METERING_OVERLAP_SECONDS=900
|
||||
DIFY_AGENT_SANDBOX_METERING_FULL_SCAN_INTERVAL_SECONDS=3600
|
||||
DIFY_AGENT_SANDBOX_METERING_MAX_PAGES=1000
|
||||
```
|
||||
|
||||
It reuses the existing E2B key, `DIFY_AGENT_API_TOKEN`, inner API URL and inner API
|
||||
key. The new endpoint requires a nonempty Bearer-token configuration even when
|
||||
legacy control-plane routes permit unauthenticated local development.
|
||||
`DIFY_AGENT_SANDBOX_METERING_POLL_INTERVAL_SECONDS` is no longer used: the interval
|
||||
belongs to Celery Beat on the API side. Both metering feature flags default off.
|
||||
|
||||
Activation T0 is persisted and immutable. Only provider executions started at or
|
||||
after T0 are metered; starting before T0 and ending after it does not include an
|
||||
old execution. Resuming an older sandbox after T0 creates a new execution and is
|
||||
included. There is no historical backfill and no environment column; databases
|
||||
separate environments. A project ID also scopes and allowlists ingestion.
|
||||
|
||||
## Failure semantics
|
||||
|
||||
- Only complete provider terminal execution data populates metered duration. A
|
||||
local `finally`, SDK expiry deadline or business success is not a billing clock.
|
||||
- Missing terminal fields remain pending; conflicts remain visible. Late starts
|
||||
cannot reopen closed executions, and duplicate facts do not add duration twice.
|
||||
- Every scan starts provider offset pagination from zero, overlaps prior coverage
|
||||
and periodically rescans the retained window. Failed, cancelled or page-bounded
|
||||
scans never claim a completed checkpoint. SQL idempotency protects redelivery.
|
||||
- The assumed default provider event retention is seven days. Older uncovered
|
||||
intervals are recorded as gaps rather than reconstructed or counted as zero.
|
||||
- A failed scheduled task affects accounting only. No accounting network request
|
||||
is added to create/connect/pause/kill, lease helpers, runner or file operations.
|
||||
|
||||
The API's private ingestion endpoints remain:
|
||||
`GET /inner/api/agent/sandbox-usage/state?project_id=...` and
|
||||
`POST /inner/api/agent/sandbox-usage/events`, authenticated with `X-Inner-Api-Key`.
|
||||
Event batches are limited to 100 records and 1 MiB, acknowledged after commit.
|
||||
They are for the isolated collector, not business-operation logging.
|
||||
|
||||
## Querying usage
|
||||
|
||||
For complete `quality='metered'` executions:
|
||||
|
||||
```text
|
||||
sandbox_hours = sum(metered_duration_ms) / 3600000
|
||||
vcpu_hours = sum(metered_duration_ms * vcpu_count) / 3600000
|
||||
ram_gib_hours = sum(metered_duration_ms * memory_mib) / (3600000 * 1024)
|
||||
```
|
||||
|
||||
Project totals include complete executions with unresolved attribution; report
|
||||
that count separately. Tenant/app reports require verified resolved attribution.
|
||||
For UTC windows `[A, B)`, clip execution intervals using start plus provider
|
||||
duration. Start time can have second precision, so cross-boundary allocation is
|
||||
not claimed to be millisecond-accurate; complete-window totals conserve duration.
|
||||
|
||||
## Rollout checks
|
||||
|
||||
1. Verify Beat's schedule, task registration and an existing worker consuming
|
||||
`ops_trace`, along with image revisions, flags, project and immutable T0.
|
||||
2. Verify the authenticated one-shot endpoint, real scheduled execution and
|
||||
advancing checkpoints. The Agent must not start a metering poller or leader.
|
||||
3. Keep a real business binding until collection resolves its owner, then retire
|
||||
it and confirm previously copied accounting remains. Also verify complete
|
||||
project usage for test sandboxes without business records.
|
||||
4. Exercise model success/failure/cancellation, files/list/read/download/errors,
|
||||
snapshots/restoration and resource cleanup. Isolated bad accounting settings
|
||||
or failing accounting-service stubs must not make business lookups fail.
|
||||
5. Compare physical execution IDs, duration and resources against actual E2B
|
||||
events; replay scans/events and confirm totals do not increase.
|
||||
6. Verify old outbox and collector-leader keys are absent after deployment. Do
|
||||
not alter run-store keys or stop shared services to inject accounting faults.
|
||||
|
||||
Disable the metering flags and restart the relevant processes to stop collection;
|
||||
business runtime behavior remains the same. Keep the ledger and original T0.
|
||||
The independent stdout-only sandbox file-error fix is tracked separately from
|
||||
this accounting integration.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Dify Agent runtime
|
||||
|
||||
Dify Agent hosts native Pydantic AI runs behind FastAPI. Implementations remain
|
||||
under `src/dify_agent`; there is no separate agent composition framework.
|
||||
|
||||
Each module declares Pydantic `Config`, `State`, and exactly one native
|
||||
`Capability` or `Toolset`. The server registry maps a name to a module. Names
|
||||
identify configuration, state and instances; aliases can use the same module
|
||||
with independent state. New instances are created for every run.
|
||||
|
||||
`ctx.deps.layers[name]` contains JSON `config` and `state`. Config is read-only
|
||||
within a run and comes from the current request. State belongs to its module;
|
||||
validated models are copies, so mutations require explicit
|
||||
`entry["state"] = state.model_dump(mode="json")` writeback. Stateful tools that
|
||||
read and modify across awaits execute sequentially.
|
||||
|
||||
`deps.services` borrows lifespan clients and server settings. `deps.resources`
|
||||
holds only operation leases, shell sessions and temporary credentials. The
|
||||
capability that acquires a resource releases it in `wrap_run` using `finally`,
|
||||
including failures and cancellation. The API owns durable Binding/Workspace
|
||||
retirement and saves snapshots in the owning session.
|
||||
|
||||
Registered production names are `agent_soul_prompt`, `workflow_node_job_prompt`,
|
||||
`workflow_user_prompt`, `agent_app_user_prompt`, `execution_context`, `runtime`,
|
||||
`shell`, `config`, `history`, `llm`, `tools`, `core_tools`, `knowledge`, `output`,
|
||||
plus `prompt` and `user_prompt` convenience names. HTTP input cannot supply an
|
||||
import path. Cross-module references live in Config, for example
|
||||
`execution_context`, `runtime`, and `shell`; the loader validates their targets
|
||||
before I/O. Instruction ordering is unspecified. Native capability ordering
|
||||
preserves Runtime → Shell → Config resource scopes.
|
||||
|
||||
An enabled Local runtime requires a nonblank deployment auth token matching
|
||||
shellctl. When shellctl path isolation is enabled, Landlock setup errors abort
|
||||
the job before its user script executes. Deployment settings may explicitly
|
||||
disable path isolation. See the [operations guide](guide/index.md) for setup.
|
||||
|
||||
Model, output type, current user content and initial history use explicit runner
|
||||
assembly and native Agent arguments. Knowledge eager results stay in the user
|
||||
role through a native model-request hook. Tool dispatch, instructions and
|
||||
capability hooks use native Pydantic AI interfaces.
|
||||
|
||||
The sandbox's installed `dify-agent` CLI can read the saved Agent Soul system
|
||||
prompt with `dify-agent config prompt pull [--to PATH]`. It writes UTF-8 text to
|
||||
`./.dify_conf/prompt.md` by default and prints the file's absolute path. The text
|
||||
includes raw, unexpanded mention markers; whitespace and line endings are preserved.
|
||||
The prompt is fetched separately and is not included in the config manifest.
|
||||
|
||||
To persist an edit, use `dify-agent config prompt push [PATH|-]`. Omitting PATH
|
||||
reads the default file; `-` reads stdin. Push fully replaces the prompt and prints
|
||||
`{"prompt": "saved text"}` as JSON. Empty text clears it. A missing file, invalid
|
||||
UTF-8, missing prompt field, or JSON null is an error. Local edits alone do not
|
||||
change Agent configuration.
|
||||
|
||||
Authenticated `GET/PUT /agent-stub/config/prompt` exchange `{"prompt": "raw text"}`
|
||||
with `GET/PUT /inner/api/agent-config/<agent_id>/prompt`. The Stub derives tenant,
|
||||
agent, user, and version scope solely from the signed execution context. Reads
|
||||
follow snapshot, shared-draft, and personal build-draft access rules. Writes are
|
||||
allowed only to the current account's build draft and only replace
|
||||
`AgentSoulConfig.prompt.system_prompt`. Later requests built from that draft use
|
||||
the saved prompt and resolve its mentions; already-built requests keep their
|
||||
prompt. Draft merge and publication retain their existing lifecycle.
|
||||
|
||||
See [run lifecycle](concepts/run-lifecycle/index.md),
|
||||
[resources](concepts/runtime-resources/index.md), and the
|
||||
[operations guide](guide/index.md).
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Execution context module
|
||||
|
||||
`dify_agent.layers.execution_context.layer` declares Config, empty State and
|
||||
Capability. Config carries tenant/user/app/invoke identity and correlation IDs.
|
||||
Other modules refer to its registered name in their Config. Server-only daemon
|
||||
settings and clients are borrowed from Deps.services. Knowledge retrieval
|
||||
requires its complete caller identity before any external request.
|
||||
|
||||
The optional `tracing` field is an API-issued `ApplicationTracingContext`:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"run_id": "429cab49-8663-42b4-a701-ac1038ee4fa7",
|
||||
"invocation_id": "95bdeed9-4652-4708-8322-b866f159ad62",
|
||||
"trace_id": "81b617d638eb419ba2b209c14984d908",
|
||||
"parent_span_id": "716db0b6c736b395",
|
||||
"session_id": "conversation-id",
|
||||
"capture_content": false,
|
||||
"sampled": true
|
||||
}
|
||||
```
|
||||
|
||||
`run_id` identifies the API's persisted application trace. `invocation_id`
|
||||
identifies this particular Agent execution; multiple nodes or attempts can
|
||||
belong to one application trace. Both are UUIDs. The trace and parent span IDs
|
||||
are nonzero, lowercase OpenTelemetry hex IDs (32 and 16 characters). The parent
|
||||
is the API-owned message or Agent-node invocation, and is restored as the actual
|
||||
OpenTelemetry parent rather than attached only as metadata. Tenant/app identity
|
||||
continues to come from the containing execution context.
|
||||
|
||||
Application collection requires `DIFY_AGENT_APPLICATION_TRACING_ENABLED=true`
|
||||
on the Agent server. The API owns sampling and content policy per invocation;
|
||||
no third-party destination or credential is accepted in a run request. When an
|
||||
application context is selected it replaces deployment trajectory instrumentation
|
||||
for that invocation, including when `sampled` is false. Without an application
|
||||
context, the existing deployment trajectory behavior is unchanged.
|
||||
@@ -0,0 +1,8 @@
|
||||
# History module
|
||||
|
||||
`dify_agent.layers.history` declares Config, State and Capability. Config is
|
||||
empty. State contains `messages`, encoded as JSON using Pydantic AI message
|
||||
schemas. The runner explicitly loads initial message_history and writes the
|
||||
captured history on every terminal outcome, preserving compaction and partial
|
||||
responses. Current instructions are removed and unmatched trailing calls are
|
||||
marked interrupted on failure or cancellation. The reserved name is `history`.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Model module
|
||||
|
||||
`dify_agent.layers.dify_plugin.llm_layer` declares Config, State and Capability.
|
||||
The reserved `llm` name selects model assembly. Public Config contains plugin,
|
||||
provider, model, model settings, context window and an `execution_context` name.
|
||||
The runtime builds a model through the Dify API metered gateway with borrowed
|
||||
lifespan HTTP services. Credentials stay API-owned; no model/client is persisted.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Plugin tool module
|
||||
|
||||
`dify_agent.layers.dify_plugin.tools_layer` declares Config, State and native
|
||||
Toolset. The `tools` registry name accepts API-prepared declarations, parameters,
|
||||
runtime values and model-facing schema, plus `execution_context` and optional
|
||||
`shell` Config references. Hidden/default parameter merging, loose schemas and
|
||||
observation mapping preserve the API-prepared contract. Sandbox paths use the
|
||||
referenced live shell session to upload files; file mappings resolve signed URLs
|
||||
through the borrowed Dify API client. Config and credentials are never snapshotted.
|
||||
|
||||
Each prepared tool includes `plugin_unique_identifier` (version and checksum)
|
||||
alongside `plugin_id`. The daemon receives it as `X-Plugin-Unique-Identifier`
|
||||
and executes that exact plugin package, even if the installed version changes
|
||||
during the run. Tool clients are shared only within the same complete identifier.
|
||||
Older configurations can omit the identifier and retain plugin-ID dispatch.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Prompt module
|
||||
|
||||
`dify_agent.layers.prompt` declares Config, State and native Toolset. Config
|
||||
accepts `prefix`, `suffix` and `user` string fragments or lists. Prefix/suffix
|
||||
become dynamic instructions; `user` contributes current user content. State is
|
||||
empty. Instruction order is unspecified. Product names `agent_soul_prompt`,
|
||||
`workflow_node_job_prompt`, and `workflow_user_prompt` map to this module.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Shell module
|
||||
|
||||
`dify_agent.layers.shell.layer` declares Config, State and Capability. Config
|
||||
contains CLI tools, environment values, secret names, redaction patterns and
|
||||
`runtime` / optional `execution_context` references. Native ordering ensures an
|
||||
active lease exists before shell bootstrap and config eager pulls.
|
||||
|
||||
The Capability exposes shell_run, shell_wait, shell_input and shell_interrupt
|
||||
through a native sequential Toolset. JSON State holds initialized, job_ids and
|
||||
job_offsets; live tokens remain in the run-scoped ShellSession. Bootstrap marks
|
||||
initialized only on success. Exit cleanup removes tracked jobs and clears IDs,
|
||||
offsets and credentials before Runtime releases the lease, including cancellation.
|
||||
The API owns Workspace/Binding retirement. HOME is reusable system space; cwd
|
||||
and TMPDIR/TMP/TEMP refer to the active Workspace.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Structured output module
|
||||
|
||||
`dify_agent.layers.output.output_layer` declares Config, empty State and
|
||||
Capability. The reserved `output` name accepts a top-level object JSON Schema,
|
||||
optional description and strictness. The runner resolves native output_type
|
||||
before running the agent. A fresh dynamic type exposes the schema and performs
|
||||
JSON Schema validation in Pydantic AI's retry pipeline. The model-facing tool
|
||||
name is final_output. Local `#/$defs/` references are supported; remote or
|
||||
recursive references are rejected before I/O. Resume resubmits current Config.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Dify Agent
|
||||
|
||||
[Runtime modules](dify-agent/index.md) compose native Pydantic AI capabilities
|
||||
and toolsets. [Getting started](dify-agent/get-started/index.md) covers the HTTP
|
||||
protocol; [operations](dify-agent/guide/index.md) covers deployment.
|
||||
Reference in new issue
Block a user