Skip to content

Open-source design agent: on-brand stills, decks, diagrams, charts and motion graphics from a chat thread, built on Deep Agents.

MDA: deliver files on runs without Slack by attaching them to the trace

Amal Irgashev359bc810ff6b
diff --git a/docs/deploy-mda.md b/docs/deploy-mda.md
index 2b41137..c8bb7db 100644
--- a/docs/deploy-mda.md
+++ b/docs/deploy-mda.md
@@ -69,6 +69,23 @@ In Slack, mention the agent with a quick ask ("a square card announcing …"), t
storyboarded teaser. You should see live progress in the thread, the files attached at the end,
and, for the teaser, a check-in while it renders. `uv run mda logs` tails the deployment.
+Without Slack, call the deployment's Agent Server (the URL `deploy` prints) with your LangSmith key:
+
+```python
+from langgraph_sdk import get_client
+
+client = get_client(url="https://<deployment>.langgraph.app", api_key="<LANGSMITH_API_KEY>")
+thread = await client.threads.create()
+await client.runs.wait(
+ thread["thread_id"],
+ "design-agent",
+ input={"messages": [{"role": "user", "content": "A 1200x630 card announcing …"}]},
+)
+```
+
+Runs without a channel (the API, Studio) have no Slack to attach files to, so `upload_files`
+attaches them to the run's trace in LangSmith; open them from the trace or Studio.
+
## How it behaves on MDA
In Slack the agent streams its steps into one message per turn, ends replies with a short footer
diff --git a/src/design_agent/assembly.py b/src/design_agent/assembly.py
index 5e44604..510b69f 100644
--- a/src/design_agent/assembly.py
+++ b/src/design_agent/assembly.py
@@ -57,7 +57,11 @@ from design_agent.runtime.profiles import RuntimeProfile
from design_agent.runtime.sandbox.docker import current_thread_id
from design_agent.subagents import build_subagents
from design_agent.surfaces.slack.phrasebook import services
-from design_agent.tools.delivery import DeliveryLedgerMiddleware, build_upload_tool
+from design_agent.tools.delivery import (
+ DeliveryLedgerMiddleware,
+ UploadFallbackMiddleware,
+ build_upload_tool,
+)
from design_agent.tools.fetch import build_fetch_tool
from design_agent.tools.mcp import McpServer
from design_agent.tools.media import build_media_tools
@@ -181,6 +185,20 @@ def build_agent_components(
),
WorkspaceStagerMiddleware(manifest, runtime.staging_for),
DeliveryLedgerMiddleware(runtime.backend_for, thread_id_for=runtime.thread_id_for),
+ *(
+ [
+ UploadFallbackMiddleware(
+ build_upload_tool(
+ adapter=runtime.fallback_delivery,
+ backend_for=runtime.backend_for,
+ thread_id_for=runtime.thread_id_for,
+ ),
+ thread_id_for=runtime.thread_id_for,
+ )
+ ]
+ if runtime.delivery is None and runtime.fallback_delivery is not None
+ else []
+ ),
TodoListMiddleware(),
TodayMiddleware(zone_for=zone_for or fixed_zone(settings.timezone)),
RunTagsMiddleware(surface=runtime.surface),
diff --git a/src/design_agent/runtime/profiles.py b/src/design_agent/runtime/profiles.py
index 5ba8b51..c9288db 100644
--- a/src/design_agent/runtime/profiles.py
+++ b/src/design_agent/runtime/profiles.py
@@ -45,6 +45,8 @@ class RuntimeProfile:
thread_id_for: Callable[[Any], str] = thread_id_from_config
delivery: DeliveryAdapter | None = None
"""None means the platform brings `upload_files` (MDA's Slack channel)."""
+ fallback_delivery: DeliveryAdapter | None = None
+ """Where files go on runs the platform's `upload_files` is missing from (MDA without Slack)."""
services: BackgroundServices | None = None
"""The process's wake-up plumbing; None turns background work off (a one-shot run)."""
quiet_status: Callable[[str], str] | None = None
@@ -61,6 +63,7 @@ def mda_profile(project_root: Path, settings: Settings | None = None) -> Runtime
from design_agent.middleware.quiet import running_status
from design_agent.runtime.waker.mda import MdaScheduleWaker
from design_agent.surfaces.slack import MdaSlackResolver, SlackSurface
+ from design_agent.tools.delivery import TraceAttachmentAdapter
settings = settings or Settings()
@@ -87,6 +90,7 @@ def mda_profile(project_root: Path, settings: Settings | None = None) -> Runtime
staging_for=staging_for,
services=services,
quiet_status=running_status,
+ fallback_delivery=TraceAttachmentAdapter(),
slack=SlackSurface(
MdaSlackResolver(), mention_required=not settings.slack_trigger_on_all_messages
),
diff --git a/src/design_agent/tools/delivery.py b/src/design_agent/tools/delivery.py
index d8e71ad..8e79469 100644
--- a/src/design_agent/tools/delivery.py
+++ b/src/design_agent/tools/delivery.py
@@ -1,9 +1,11 @@
"""File delivery: `upload_files` outside MDA, and the exactly-once ledger around any delivery.
-On Managed Deep Agents the Slack channel brings its own `upload_files` tool. Every other runtime
-gets this one, with the same name, arguments and replies, so the prompt and skills read the same
-everywhere. Delivery adapters decide where files go: the CLI copies them to `workspace/out/`, the
-self-hosted Slack adapter uploads them to the thread.
+On Managed Deep Agents the Slack channel brings its own `upload_files` tool and drops it from runs
+without a channel (the API, Studio); those runs get this one through `UploadFallbackMiddleware`,
+which attaches the files to the call's LangSmith run. Every other runtime gets this one too, with
+the same name, arguments and replies, so the prompt and skills read the same everywhere. Delivery
+adapters decide where files go: the CLI copies them to `workspace/out/`, the self-hosted Slack
+adapter uploads them to the thread.
`DeliveryLedgerMiddleware` wraps whichever `upload_files` the run has. It records each delivered
file's sha256 in the project's `DELIVERY.json` and drops files already delivered in this thread,
@@ -14,6 +16,7 @@ from __future__ import annotations
import hashlib
import json
+import mimetypes
import posixpath
import re
import shlex
@@ -21,7 +24,7 @@ import time
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from pathlib import Path
-from typing import Annotated, Any, Protocol
+from typing import Annotated, Any, Protocol, cast
from deepagents.backends.protocol import BackendProtocol
from langchain.agents.middleware import AgentMiddleware
@@ -69,6 +72,35 @@ class LocalOutputAdapter:
(folder / item.name).write_bytes(item.content)
+#: LangSmith refuses larger attachments, and skips a name with a period in it.
+TRACE_ATTACHMENT_BYTES = 100 * 1024 * 1024
+TRACE_NOTE = (
+ "This run has no chat channel: `upload_files` attaches files to this run in LangSmith, where "
+ "the person opens them from the trace or Studio. Say so when you deliver."
+)
+
+
+class TraceAttachmentAdapter:
+ """Delivery for Managed Deep Agents runs without a channel: each file goes on the upload
+ call's own run, which the tracer sends as the call ends, so a long job holds nothing."""
+
+ def deliver(self, thread_id: str, files: Sequence[DeliveredFile]) -> None: # noqa: ARG002
+ from langsmith.run_helpers import get_current_run_tree
+ from langsmith.schemas import Attachment, Attachments
+
+ run = get_current_run_tree()
+ if run is None:
+ raise RuntimeError("this run is not traced")
+ if any(len(item.content) > TRACE_ATTACHMENT_BYTES for item in files):
+ raise ValueError("a file is over the LangSmith attachment limit")
+ # A run being written holds attachments to send (`Attachments`), not read-back info.
+ attachments = cast("Attachments", run.attachments)
+ for item in files:
+ mime = mimetypes.guess_type(item.name)[0] or "application/octet-stream"
+ attachments[re.sub(r"[^A-Za-z0-9_-]", "_", item.name)] = Attachment(mime, item.content)
+ run.add_metadata({"delivered": [item.name for item in files]})
+
+
def workspace_path(path: str) -> str:
"""A normalized absolute path under /workspace, or ValueError."""
candidate = path if path.startswith("/") else f"{WORKSPACE}/{path}"
@@ -300,3 +332,72 @@ class DeliveryLedgerMiddleware(AgentMiddleware[Any, Any, Any]):
posixpath.basename(p) for p in already
)
return result
+
+
+def _tool_name(tool: Any) -> str | None:
+ if isinstance(tool, dict):
+ name = tool.get("name") or (tool.get("function") or {}).get("name")
+ return name if isinstance(name, str) else None
+ return getattr(tool, "name", None)
+
+
+class UploadFallbackMiddleware(AgentMiddleware[Any, Any, Any]):
+ """Managed Deep Agents: when the platform drops its `upload_files` from a run (no Slack
+ channel), offer `tool` under the same name and run calls to it there.
+
+ MDA's channel middleware wraps every authored one, so the tools a model call sees here already
+ say whether the platform's upload is available. The answer is kept per thread for the tool
+ calls that follow, and refreshed on each model call."""
+
+ def __init__(self, tool: BaseTool, *, thread_id_for: Callable[[Any], str]) -> None:
+ super().__init__()
+ self._tool = tool
+ self._thread_id_for = thread_id_for
+ self._fallback: dict[str, bool] = {}
+
+ @property
+ def name(self) -> str:
+ return "DesignAgentUploadFallback"
+
+ def _prepare(self, request: Any) -> Any:
+ from langchain_core.messages import SystemMessage
+
+ missing = UPLOAD_TOOL not in {_tool_name(t) for t in request.tools}
+ thread = self._thread_id_for(request.runtime)
+ self._fallback[thread] = missing
+ if len(self._fallback) > 512:
+ self._fallback.pop(next(iter(self._fallback)))
+ if not missing:
+ return request
+ blocks = list(request.system_message.content_blocks if request.system_message else [])
+ blocks.append({"type": "text", "text": TRACE_NOTE})
+ return request.override(
+ tools=[*request.tools, self._tool], system_message=SystemMessage(content_blocks=blocks)
+ )
+
+ def wrap_model_call(self, request: Any, handler: Callable[[Any], Any]) -> Any:
+ return handler(self._prepare(request))
+
+ async def awrap_model_call(self, request: Any, handler: Callable[[Any], Awaitable[Any]]) -> Any:
+ return await handler(self._prepare(request))
+
+ def _route(self, request: ToolCallRequest) -> ToolCallRequest:
+ if request.tool_call.get("name") == UPLOAD_TOOL and self._fallback.get(
+ self._thread_id_for(request.runtime)
+ ):
+ return request.override(tool=self._tool)
+ return request
+
+ def wrap_tool_call(
+ self,
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
+ ) -> ToolMessage | Command[Any]:
+ return handler(self._route(request))
+
+ async def awrap_tool_call(
+ self,
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
+ ) -> ToolMessage | Command[Any]:
+ return await handler(self._route(request))
diff --git a/tests/contract/test_parity.py b/tests/contract/test_parity.py
index 7216ea8..184f360 100644
--- a/tests/contract/test_parity.py
+++ b/tests/contract/test_parity.py
@@ -61,6 +61,10 @@ def test_mda_local_and_self_hosted_assemble_the_same_agent(tmp_path: Path) -> No
settings=settings, runtime=mda_profile(ROOT), model=model, role_models=roles
)
- assert shape(local) == shape(mda)
+ mda_shape = shape(mda)
+ # MDA's Slack channel brings `upload_files`; the fallback covers runs without a channel.
+ assert "UploadFallbackMiddleware" in mda_shape["middleware"]
+ mda_shape["middleware"].remove("UploadFallbackMiddleware")
+ assert shape(local) == mda_shape
assert "upload_files" in {t.name for t in local.tools}, "local and self-hosted bring delivery"
assert "upload_files" not in {t.name for t in mda.tools}, "MDA's Slack channel brings its own"
diff --git a/tests/unit/test_upload_fallback.py b/tests/unit/test_upload_fallback.py
new file mode 100644
index 0000000..93adc28
--- /dev/null
+++ b/tests/unit/test_upload_fallback.py
@@ -0,0 +1,100 @@
+"""MDA runs without a Slack channel still deliver: files go on the upload call's LangSmith run."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field, replace
+from typing import Any
+
+import pytest
+from langchain_core.messages import SystemMessage
+from langchain_core.tools import tool
+from langsmith.run_trees import RunTree
+from langsmith.schemas import Attachment
+
+from design_agent.tools import delivery
+from design_agent.tools.delivery import (
+ TRACE_NOTE,
+ UPLOAD_TOOL,
+ DeliveredFile,
+ TraceAttachmentAdapter,
+ UploadFallbackMiddleware,
+)
+
+
+@tool("upload_files")
+def ours(paths: list[str]) -> str:
+ """Our upload."""
+ return "ours"
+
+
+@tool("upload_files")
+def platforms(paths: list[str]) -> str:
+ """The platform's upload."""
+ return "platform"
+
+
+@tool
+def ls(path: str) -> str:
+ """List."""
+ return ""
+
+
+@dataclass
+class Request:
+ tools: list[Any]
+ runtime: Any = "thread-1"
+ system_message: SystemMessage | None = field(default_factory=lambda: SystemMessage("base"))
+ tool_call: dict[str, Any] = field(default_factory=dict)
+ tool: Any = None
+
+ def override(self, **changes: Any) -> Request:
+ return replace(self, **changes)
+
+
+def middleware() -> UploadFallbackMiddleware:
+ return UploadFallbackMiddleware(ours, thread_id_for=lambda runtime: str(runtime))
+
+
+def test_a_run_without_the_platforms_upload_gets_ours_and_a_note() -> None:
+ seen: list[Request] = []
+ mw = middleware()
+ mw.wrap_model_call(Request(tools=[ls]), lambda r: seen.append(r))
+ assert [t.name for t in seen[0].tools] == ["ls", UPLOAD_TOOL]
+ assert TRACE_NOTE in seen[0].system_message.text # type: ignore[union-attr]
+ call = Request(tools=[], tool_call={"name": UPLOAD_TOOL, "args": {}}, tool=platforms)
+ assert mw.wrap_tool_call(call, lambda r: r.tool).name == UPLOAD_TOOL # type: ignore[arg-type,return-value]
+ assert mw.wrap_tool_call(call, lambda r: r.tool) is ours # type: ignore[arg-type,comparison-overlap]
+
+
+def test_a_slack_run_keeps_the_platforms_upload() -> None:
+ seen: list[Request] = []
+ mw = middleware()
+ request = Request(tools=[ls, platforms])
+ mw.wrap_model_call(request, lambda r: seen.append(r))
+ assert seen[0] is request
+ call = Request(tools=[], tool_call={"name": UPLOAD_TOOL, "args": {}}, tool=platforms)
+ assert mw.wrap_tool_call(call, lambda r: r.tool) is platforms # type: ignore[arg-type,comparison-overlap]
+
+
+def test_files_go_on_the_current_run_with_names_langsmith_keeps(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ run = RunTree(name="upload_files", run_type="tool")
+ monkeypatch.setattr("langsmith.run_helpers.get_current_run_tree", lambda: run)
+ TraceAttachmentAdapter().deliver("t", [DeliveredFile("card-1200x630.png", b"png")])
+ assert run.attachments == {"card-1200x630_png": Attachment("image/png", b"png")}
+ assert run.metadata["delivered"] == ["card-1200x630.png"]
+
+
+def test_an_untraced_run_or_an_oversized_file_is_not_confirmed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("langsmith.run_helpers.get_current_run_tree", lambda: None)
+ with pytest.raises(RuntimeError):
+ TraceAttachmentAdapter().deliver("t", [DeliveredFile("a.png", b"x")])
+ run = RunTree(name="upload_files", run_type="tool")
+ monkeypatch.setattr("langsmith.run_helpers.get_current_run_tree", lambda: run)
+ monkeypatch.setattr(delivery, "TRACE_ATTACHMENT_BYTES", 2)
+ with pytest.raises(ValueError):
+ TraceAttachmentAdapter().deliver("t", [DeliveredFile("a.png", b"xyz")])
+ assert not run.attachments